1 package org.opentrafficsim.demo.carFollowing;
2
3 import static org.opentrafficsim.core.gtu.GTUType.CAR;
4
5 import java.awt.Container;
6 import java.awt.Frame;
7 import java.rmi.RemoteException;
8 import java.util.ArrayList;
9 import java.util.LinkedHashSet;
10 import java.util.List;
11 import java.util.Random;
12 import java.util.Set;
13
14 import javax.naming.NamingException;
15 import javax.swing.SwingUtilities;
16
17 import org.djunits.unit.TimeUnit;
18 import org.djunits.unit.UNITS;
19 import org.djunits.value.vdouble.scalar.Acceleration;
20 import org.djunits.value.vdouble.scalar.Duration;
21 import org.djunits.value.vdouble.scalar.Length;
22 import org.djunits.value.vdouble.scalar.Speed;
23 import org.djunits.value.vdouble.scalar.Time;
24 import org.opentrafficsim.base.modelproperties.BooleanProperty;
25 import org.opentrafficsim.base.modelproperties.CompoundProperty;
26 import org.opentrafficsim.base.modelproperties.ContinuousProperty;
27 import org.opentrafficsim.base.modelproperties.IntegerProperty;
28 import org.opentrafficsim.base.modelproperties.ProbabilityDistributionProperty;
29 import org.opentrafficsim.base.modelproperties.Property;
30 import org.opentrafficsim.base.modelproperties.PropertyException;
31 import org.opentrafficsim.base.modelproperties.SelectionProperty;
32 import org.opentrafficsim.base.parameters.Parameters;
33 import org.opentrafficsim.core.dsol.OTSModelInterface;
34 import org.opentrafficsim.core.geometry.OTSGeometryException;
35 import org.opentrafficsim.core.geometry.OTSPoint3D;
36 import org.opentrafficsim.core.gtu.GTUDirectionality;
37 import org.opentrafficsim.core.gtu.GTUException;
38 import org.opentrafficsim.core.gtu.GTUType;
39 import org.opentrafficsim.core.network.NetworkException;
40 import org.opentrafficsim.core.network.OTSNetwork;
41 import org.opentrafficsim.core.network.OTSNode;
42 import org.opentrafficsim.graphs.AccelerationContourPlot;
43 import org.opentrafficsim.graphs.ContourPlot;
44 import org.opentrafficsim.graphs.DensityContourPlot;
45 import org.opentrafficsim.graphs.FlowContourPlot;
46 import org.opentrafficsim.graphs.LaneBasedGTUSampler;
47 import org.opentrafficsim.graphs.SpeedContourPlot;
48 import org.opentrafficsim.graphs.TrajectoryPlot;
49 import org.opentrafficsim.road.animation.AnimationToggles;
50 import org.opentrafficsim.road.gtu.animation.DefaultCarAnimation;
51 import org.opentrafficsim.road.gtu.lane.LaneBasedIndividualGTU;
52 import org.opentrafficsim.road.gtu.lane.tactical.LaneBasedGTUFollowingTacticalPlanner;
53 import org.opentrafficsim.road.gtu.lane.tactical.following.GTUFollowingModelOld;
54 import org.opentrafficsim.road.gtu.lane.tactical.following.IDMOld;
55 import org.opentrafficsim.road.gtu.lane.tactical.following.IDMPlusOld;
56 import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalPlanner;
57 import org.opentrafficsim.road.gtu.strategical.route.LaneBasedStrategicalRoutePlanner;
58 import org.opentrafficsim.road.modelproperties.IDMPropertySet;
59 import org.opentrafficsim.road.network.factory.LaneFactory;
60 import org.opentrafficsim.road.network.lane.DirectedLanePosition;
61 import org.opentrafficsim.road.network.lane.Lane;
62 import org.opentrafficsim.road.network.lane.LaneType;
63 import org.opentrafficsim.simulationengine.AbstractWrappableAnimation;
64 import org.opentrafficsim.simulationengine.OTSSimulationException;
65 import org.opentrafficsim.simulationengine.SimpleSimulatorInterface;
66
67 import nl.tudelft.simulation.dsol.SimRuntimeException;
68 import nl.tudelft.simulation.dsol.gui.swing.TablePanel;
69 import nl.tudelft.simulation.dsol.simtime.SimTimeDoubleUnit;
70 import nl.tudelft.simulation.dsol.simulators.DEVSSimulatorInterface;
71 import nl.tudelft.simulation.dsol.simulators.SimulatorInterface;
72
73
74
75
76
77
78
79
80
81
82
83 public class CircularLane extends AbstractWrappableAnimation implements UNITS
84 {
85
86 private static final long serialVersionUID = 1L;
87
88
89 private LaneSimulationModel model;
90
91
92
93
94
95 public CircularLane() throws PropertyException
96 {
97 this.properties.add(new IntegerProperty("TrackLength", "Track length", "Circumference of the track", 2000, 500, 6000,
98 "Track length %dm", false, 10));
99 this.properties.add(new ContinuousProperty("MeanDensity", "Mean density", "Number of vehicles per km", 40.0, 5.0, 45.0,
100 "Density %.1f veh/km", false, 11));
101 this.properties.add(new ContinuousProperty("DensityVariability", "Density variability",
102 "Variability of the number of vehicles per km", 0.0, 0.0, 1.0, "%.1f", false, 12));
103 List<Property<?>> outputProperties = new ArrayList<>();
104 outputProperties.add(new BooleanProperty("DensityPlot", "Density", "Density contour plot", true, false, 0));
105 outputProperties.add(new BooleanProperty("FlowPlot", "Flow", "Flow contour plot", true, false, 1));
106 outputProperties.add(new BooleanProperty("SpeedPlot", "Speed", "Speed contour plot", true, false, 2));
107 outputProperties
108 .add(new BooleanProperty("AccelerationPlot", "Acceleration", "Acceleration contour plot", true, false, 3));
109 outputProperties.add(
110 new BooleanProperty("TrajectoryPlot", "Trajectories", "Trajectory (time/distance) diagram", true, false, 4));
111 this.properties.add(new CompoundProperty("OutputGraphs", "Output graphs", "Select the graphical output",
112 outputProperties, true, 1000));
113 }
114
115
116 @Override
117 public final void stopTimersThreads()
118 {
119 super.stopTimersThreads();
120 this.model = null;
121 }
122
123
124
125
126
127
128 public static void main(final String[] args) throws SimRuntimeException
129 {
130 SwingUtilities.invokeLater(new Runnable()
131 {
132 @Override
133 public void run()
134 {
135 try
136 {
137 CircularLane circularLane = new CircularLane();
138 List<Property<?>> propertyList = circularLane.getProperties();
139 try
140 {
141 propertyList.add(new ProbabilityDistributionProperty("TrafficComposition", "Traffic composition",
142 "<html>Mix of passenger cars and trucks</html>", new String[] { "passenger car", "truck" },
143 new Double[] { 0.8, 0.2 }, false, 10));
144 }
145 catch (PropertyException exception)
146 {
147 exception.printStackTrace();
148 }
149 propertyList.add(new SelectionProperty("CarFollowingModel", "Car following model",
150 "<html>The car following model determines "
151 + "the acceleration that a vehicle will make taking into account "
152 + "nearby vehicles, infrastructural restrictions (e.g. speed limit, "
153 + "curvature of the road) capabilities of the vehicle and personality "
154 + "of the driver.</html>",
155 new String[] { "IDM", "IDM+" }, 1, false, 1));
156 propertyList.add(IDMPropertySet.makeIDMPropertySet("IDMCar", "Car",
157 new Acceleration(1.0, METER_PER_SECOND_2), new Acceleration(1.5, METER_PER_SECOND_2),
158 new Length(2.0, METER), new Duration(1.0, SECOND), 2));
159 propertyList.add(IDMPropertySet.makeIDMPropertySet("IDMTruck", "Truck",
160 new Acceleration(0.5, METER_PER_SECOND_2), new Acceleration(1.25, METER_PER_SECOND_2),
161 new Length(2.0, METER), new Duration(1.0, SECOND), 3));
162 circularLane.buildAnimator(Time.ZERO, Duration.ZERO, new Duration(3600.0, SECOND), propertyList, null,
163 true);
164 }
165 catch (SimRuntimeException | NamingException | OTSSimulationException | PropertyException exception)
166 {
167 exception.printStackTrace();
168 }
169 }
170 });
171 }
172
173
174 @Override
175 protected final OTSModelInterface makeModel()
176 {
177 this.model = new LaneSimulationModel(this.savedUserModifiedProperties);
178 return this.model;
179 }
180
181
182 @Override
183 protected final void addAnimationToggles()
184 {
185 AnimationToggles.setTextAnimationTogglesStandard(this);
186 }
187
188
189 @Override
190 protected final void addTabs(final SimpleSimulatorInterface simulator) throws OTSSimulationException, PropertyException
191 {
192
193 Property<?> output = new CompoundProperty("", "", "", this.properties, false, 0).findSubPropertyByKey("OutputGraphs");
194 if (null == output)
195 {
196 throw new OTSSimulationException("Cannot find output properties");
197 }
198 ArrayList<BooleanProperty> graphs = new ArrayList<>();
199 if (output instanceof CompoundProperty)
200 {
201 CompoundProperty outputProperties = (CompoundProperty) output;
202 for (Property<?> ap : outputProperties.getValue())
203 {
204 if (ap instanceof BooleanProperty)
205 {
206 BooleanProperty bp = (BooleanProperty) ap;
207 if (bp.getValue())
208 {
209 graphs.add(bp);
210 }
211 }
212 }
213 }
214 else
215 {
216 throw new OTSSimulationException("output properties should be compound");
217 }
218 int graphCount = graphs.size();
219 int columns = (int) Math.ceil(Math.sqrt(graphCount));
220 int rows = 0 == columns ? 0 : (int) Math.ceil(graphCount * 1.0 / columns);
221 TablePanel charts = new TablePanel(columns, rows);
222
223 for (int i = 0; i < graphCount; i++)
224 {
225 String graphName = graphs.get(i).getKey();
226 Container container = null;
227 LaneBasedGTUSampler graph;
228 if (graphName.equals("TrajectoryPlot"))
229 {
230 TrajectoryPlot tp =
231 new TrajectoryPlot("TrajectoryPlot", new Duration(0.5, SECOND), this.model.getPath(), simulator);
232 tp.setTitle("Trajectory Graph");
233 tp.setExtendedState(Frame.MAXIMIZED_BOTH);
234 graph = tp;
235 container = tp.getContentPane();
236 }
237 else
238 {
239 ContourPlot cp;
240 if (graphName.equals("DensityPlot"))
241 {
242 cp = new DensityContourPlot("DensityPlot", this.model.getPath());
243 cp.setTitle("Density Contour Graph");
244 }
245 else if (graphName.equals("SpeedPlot"))
246 {
247 cp = new SpeedContourPlot("SpeedPlot", this.model.getPath());
248 cp.setTitle("Speed Contour Graph");
249 }
250 else if (graphName.equals("FlowPlot"))
251 {
252 cp = new FlowContourPlot("FlowPlot", this.model.getPath());
253 cp.setTitle("Flow Contour Graph");
254 }
255 else if (graphName.equals("AccelerationPlot"))
256 {
257 cp = new AccelerationContourPlot("AccelerationPlot", this.model.getPath());
258 cp.setTitle("Acceleration Contour Graph");
259 }
260 else
261 {
262 throw new OTSSimulationException("Unhandled type of contourplot: " + graphName);
263 }
264 graph = cp;
265 container = cp.getContentPane();
266 }
267
268 charts.setCell(container, i % columns, i / columns);
269 this.model.getPlots().add(graph);
270 }
271 addTab(getTabCount(), "statistics", charts);
272 }
273
274
275 @Override
276 public final String shortName()
277 {
278 return "Circular Lane simulation";
279 }
280
281
282 @Override
283 public final String description()
284 {
285 return "<html><h1>Circular Lane simulation</h1>" + "Vehicles are unequally distributed over a one lane ring road.<br>"
286 + "When simulation starts, all vehicles begin driving and some shockwaves may develop (depending on "
287 + "the selected track length and car following parameters).<br>"
288 + "Selected trajectory and contour plots are generated during the simulation.</html>";
289 }
290
291
292
293
294
295
296
297
298
299
300
301
302 class LaneSimulationModel implements OTSModelInterface, UNITS
303 {
304
305 private static final long serialVersionUID = 20141121L;
306
307
308 private final OTSNetwork network = new OTSNetwork("network");
309
310
311 private DEVSSimulatorInterface.TimeDoubleUnit simulator;
312
313
314 private int carsCreated = 0;
315
316
317 private GTUType gtuType = CAR;
318
319
320 private GTUFollowingModelOld carFollowingModelCars;
321
322
323 private GTUFollowingModelOld carFollowingModelTrucks;
324
325
326 private double carProbability;
327
328
329 private Length minimumDistance = new Length(0, METER);
330
331
332 private Lane lane1;
333
334
335 private Lane lane2;
336
337
338 private Speed speedLimit = new Speed(100, KM_PER_HOUR);
339
340
341 private List<LaneBasedGTUSampler> contourPlots = new ArrayList<>();
342
343
344 private List<TrajectoryPlot> trajectoryPlots = new ArrayList<>();
345
346
347 private List<Property<?>> properties = null;
348
349
350 private Random randomGenerator = new Random(12345);
351
352
353 private List<Lane> path = new ArrayList<>();
354
355
356
357
358 LaneSimulationModel(final List<Property<?>> properties)
359 {
360 this.properties = properties;
361 }
362
363
364 @Override
365 public void constructModel(final SimulatorInterface<Time, Duration, SimTimeDoubleUnit> theSimulator)
366 throws SimRuntimeException
367 {
368 this.simulator = (DEVSSimulatorInterface.TimeDoubleUnit) theSimulator;
369 double radius = 2000 / 2 / Math.PI;
370 double headway = 40;
371 double headwayVariability = 0;
372 try
373 {
374 String carFollowingModelName = null;
375 CompoundProperty propertyContainer = new CompoundProperty("", "", "", this.properties, false, 0);
376 Property<?> cfmp = propertyContainer.findByKey("CarFollowingModel");
377 if (null == cfmp)
378 {
379 throw new SimRuntimeException("Cannot find \"Car following model\" property");
380 }
381 if (cfmp instanceof SelectionProperty)
382 {
383 carFollowingModelName = ((SelectionProperty) cfmp).getValue();
384 }
385 else
386 {
387 throw new SimRuntimeException("\"Car following model\" property has wrong type");
388 }
389 for (Property<?> ap : new CompoundProperty("", "", "", this.properties, false, 0))
390 {
391
392 if (ap instanceof SelectionProperty)
393 {
394 SelectionProperty sp = (SelectionProperty) ap;
395 if ("CarFollowingModel".equals(sp.getKey()))
396 {
397 carFollowingModelName = sp.getValue();
398 }
399 }
400 else if (ap instanceof ProbabilityDistributionProperty)
401 {
402 ProbabilityDistributionProperty pdp = (ProbabilityDistributionProperty) ap;
403 String modelName = ap.getKey();
404 if (modelName.equals("TrafficComposition"))
405 {
406 this.carProbability = pdp.getValue()[0];
407 }
408 }
409 else if (ap instanceof IntegerProperty)
410 {
411 IntegerProperty ip = (IntegerProperty) ap;
412 if ("Track length".equals(ip.getKey()))
413 {
414 radius = ip.getValue() / 2 / Math.PI;
415 }
416 }
417 else if (ap instanceof ContinuousProperty)
418 {
419 ContinuousProperty cp = (ContinuousProperty) ap;
420 if (cp.getKey().equals("MeanDensity"))
421 {
422 headway = 1000 / cp.getValue();
423 }
424 if (cp.getKey().equals("DensityVariability"))
425 {
426 headwayVariability = cp.getValue();
427 }
428 }
429 else if (ap instanceof CompoundProperty)
430 {
431 CompoundProperty cp = (CompoundProperty) ap;
432 if (ap.getKey().equals("OutputGraphs"))
433 {
434 continue;
435 }
436 if (ap.getKey().contains("IDM"))
437 {
438 Acceleration a = IDMPropertySet.getA(cp);
439 Acceleration b = IDMPropertySet.getB(cp);
440 Length s0 = IDMPropertySet.getS0(cp);
441 Duration tSafe = IDMPropertySet.getTSafe(cp);
442 GTUFollowingModelOld gtuFollowingModel = null;
443 if (carFollowingModelName.equals("IDM"))
444 {
445 gtuFollowingModel = new IDMOld(a, b, s0, tSafe, 1.0);
446 }
447 else if (carFollowingModelName.equals("IDM+"))
448 {
449 gtuFollowingModel = new IDMPlusOld(a, b, s0, tSafe, 1.0);
450 }
451 else
452 {
453 throw new SimRuntimeException("Unknown gtu following model: " + carFollowingModelName);
454 }
455 if (ap.getKey().contains("Car"))
456 {
457 this.carFollowingModelCars = gtuFollowingModel;
458 }
459 else if (ap.getKey().contains("Truck"))
460 {
461 this.carFollowingModelTrucks = gtuFollowingModel;
462 }
463 else
464 {
465 throw new SimRuntimeException("Cannot determine gtu type for " + ap.getKey());
466 }
467 }
468 }
469 }
470
471 OTSNode start = new OTSNode(this.network, "Start", new OTSPoint3D(radius, 0, 0));
472 OTSNode halfway = new OTSNode(this.network, "Halfway", new OTSPoint3D(-radius, 0, 0));
473 LaneType laneType = LaneType.TWO_WAY_LANE;
474
475 OTSPoint3D[] coordsHalf1 = new OTSPoint3D[127];
476 for (int i = 0; i < coordsHalf1.length; i++)
477 {
478 double angle = Math.PI * (1 + i) / (1 + coordsHalf1.length);
479 coordsHalf1[i] = new OTSPoint3D(radius * Math.cos(angle), radius * Math.sin(angle), 0);
480 }
481 this.lane1 = LaneFactory.makeMultiLane(this.network, "Lane1", start, halfway, coordsHalf1, 1, laneType,
482 this.speedLimit, this.simulator)[0];
483 this.path.add(this.lane1);
484
485 OTSPoint3D[] coordsHalf2 = new OTSPoint3D[127];
486 for (int i = 0; i < coordsHalf2.length; i++)
487 {
488 double angle = Math.PI + Math.PI * (1 + i) / (1 + coordsHalf2.length);
489 coordsHalf2[i] = new OTSPoint3D(radius * Math.cos(angle), radius * Math.sin(angle), 0);
490 }
491 this.lane2 = LaneFactory.makeMultiLane(this.network, "Lane2", halfway, start, coordsHalf2, 1, laneType,
492 this.speedLimit, this.simulator)[0];
493 this.path.add(this.lane2);
494
495
496 double trackLength = this.lane1.getLength().getSI();
497 double variability = (headway - 20) * headwayVariability;
498 System.out.println("headway is " + headway + " variability limit is " + variability);
499 Random random = new Random(12345);
500 for (double pos = 0; pos <= trackLength - headway - variability;)
501 {
502
503 double actualHeadway = headway + (random.nextDouble() * 2 - 1) * variability;
504 generateCar(this.lane1, new Length(pos, METER));
505 pos += actualHeadway;
506 }
507
508 trackLength = this.lane2.getLength().getSI();
509 variability = (headway - 20) * headwayVariability;
510 System.out.println("headway is " + headway + " variability limit is " + variability);
511 random = new Random(54321);
512 for (double pos = 0; pos <= trackLength - headway - variability;)
513 {
514
515 double actualHeadway = headway + (random.nextDouble() * 2 - 1) * variability;
516 generateCar(this.lane2, new Length(pos, METER));
517 pos += actualHeadway;
518 }
519
520 this.simulator.scheduleEventAbs(new Time(0.999, TimeUnit.BASE_SECOND), this, this, "drawGraphs", null);
521 }
522 catch (SimRuntimeException | NamingException | NetworkException | GTUException | OTSGeometryException
523 | PropertyException exception)
524 {
525 exception.printStackTrace();
526 }
527 }
528
529
530
531
532 public List<Lane> getPath()
533 {
534 return new ArrayList<>(this.path);
535 }
536
537
538
539
540 protected final void drawGraphs()
541 {
542 for (LaneBasedGTUSampler contourPlot : this.contourPlots)
543 {
544 contourPlot.reGraph();
545 }
546 for (TrajectoryPlot trajectoryPlot : this.trajectoryPlots)
547 {
548 trajectoryPlot.reGraph();
549 }
550
551 try
552 {
553 this.simulator.scheduleEventAbs(
554 new Time(this.simulator.getSimulatorTime().getSI() + 1, TimeUnit.BASE_SECOND), this, this,
555 "drawGraphs", null);
556 }
557 catch (SimRuntimeException exception)
558 {
559 exception.printStackTrace();
560 }
561
562 }
563
564
565
566
567
568
569
570 protected final void generateCar(final Lane lane, final Length initialPosition) throws GTUException
571 {
572 boolean generateTruck = this.randomGenerator.nextDouble() > this.carProbability;
573 Speed initialSpeed = new Speed(0, KM_PER_HOUR);
574 Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1);
575 initialPositions.add(new DirectedLanePosition(lane, initialPosition, GTUDirectionality.DIR_PLUS));
576 try
577 {
578 Length vehicleLength = new Length(generateTruck ? 15 : 4, METER);
579 GTUFollowingModelOld gtuFollowingModel =
580 generateTruck ? this.carFollowingModelTrucks : this.carFollowingModelCars;
581 if (null == gtuFollowingModel)
582 {
583 throw new GTUException("gtuFollowingModel is null");
584 }
585 Parameters parameters = DefaultsFactory.getDefaultParameters();
586 LaneBasedIndividualGTU gtu = new LaneBasedIndividualGTU("" + (++this.carsCreated), this.gtuType, vehicleLength,
587 new Length(1.8, METER), new Speed(200, KM_PER_HOUR), vehicleLength.multiplyBy(0.5), this.simulator,
588 this.network);
589 LaneBasedStrategicalPlanner strategicalPlanner = new LaneBasedStrategicalRoutePlanner(
590 new LaneBasedGTUFollowingTacticalPlanner(gtuFollowingModel, gtu), gtu);
591 gtu.setParameters(parameters);
592 gtu.initWithAnimation(strategicalPlanner, initialPositions, initialSpeed, DefaultCarAnimation.class,
593 CircularLane.this.getColorer());
594 }
595 catch (NamingException | SimRuntimeException | NetworkException | OTSGeometryException exception)
596 {
597 throw new GTUException(exception);
598 }
599 }
600
601
602 @Override
603 public SimulatorInterface<Time, Duration, SimTimeDoubleUnit> getSimulator()
604 {
605 return this.simulator;
606 }
607
608
609 @Override
610 public OTSNetwork getNetwork()
611 {
612 return this.network;
613 }
614
615
616
617
618 public final List<LaneBasedGTUSampler> getPlots()
619 {
620 return this.contourPlots;
621 }
622
623
624
625
626 public final List<TrajectoryPlot> getTrajectoryPlots()
627 {
628 return this.trajectoryPlots;
629 }
630
631
632
633
634 public final Length getMinimumDistance()
635 {
636 return this.minimumDistance;
637 }
638
639 }
640 }