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