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