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