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.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 nl.tudelft.simulation.dsol.SimRuntimeException;
23 import nl.tudelft.simulation.dsol.gui.swing.HTMLPanel;
24 import nl.tudelft.simulation.dsol.gui.swing.TablePanel;
25 import nl.tudelft.simulation.dsol.simulators.SimulatorInterface;
26
27 import org.djunits.unit.UNITS;
28 import org.djunits.value.vdouble.scalar.Acceleration;
29 import org.djunits.value.vdouble.scalar.Duration;
30 import org.djunits.value.vdouble.scalar.Length;
31 import org.djunits.value.vdouble.scalar.Speed;
32 import org.djunits.value.vdouble.scalar.Time;
33 import org.opentrafficsim.base.modelproperties.BooleanProperty;
34 import org.opentrafficsim.base.modelproperties.CompoundProperty;
35 import org.opentrafficsim.base.modelproperties.ProbabilityDistributionProperty;
36 import org.opentrafficsim.base.modelproperties.Property;
37 import org.opentrafficsim.base.modelproperties.PropertyException;
38 import org.opentrafficsim.base.modelproperties.SelectionProperty;
39 import org.opentrafficsim.core.dsol.OTSDEVSSimulatorInterface;
40 import org.opentrafficsim.core.dsol.OTSModelInterface;
41 import org.opentrafficsim.core.dsol.OTSSimTimeDouble;
42 import org.opentrafficsim.core.geometry.OTSGeometryException;
43 import org.opentrafficsim.core.geometry.OTSPoint3D;
44 import org.opentrafficsim.core.gtu.GTUDirectionality;
45 import org.opentrafficsim.core.gtu.GTUException;
46 import org.opentrafficsim.core.gtu.GTUType;
47 import org.opentrafficsim.core.gtu.animation.GTUColorer;
48 import org.opentrafficsim.core.gtu.behavioralcharacteristics.BehavioralCharacteristics;
49 import org.opentrafficsim.core.network.LongitudinalDirectionality;
50 import org.opentrafficsim.core.network.NetworkException;
51 import org.opentrafficsim.core.network.OTSNetwork;
52 import org.opentrafficsim.core.network.OTSNode;
53 import org.opentrafficsim.graphs.AccelerationContourPlot;
54 import org.opentrafficsim.graphs.ContourPlot;
55 import org.opentrafficsim.graphs.DensityContourPlot;
56 import org.opentrafficsim.graphs.FlowContourPlot;
57 import org.opentrafficsim.graphs.LaneBasedGTUSampler;
58 import org.opentrafficsim.graphs.SpeedContourPlot;
59 import org.opentrafficsim.graphs.TrajectoryPlot;
60 import org.opentrafficsim.road.gtu.animation.DefaultCarAnimation;
61 import org.opentrafficsim.road.gtu.lane.LaneBasedIndividualGTU;
62 import org.opentrafficsim.road.gtu.lane.tactical.LaneBasedGTUFollowingTacticalPlanner;
63 import org.opentrafficsim.road.gtu.lane.tactical.following.GTUFollowingModelOld;
64 import org.opentrafficsim.road.gtu.lane.tactical.following.IDMOld;
65 import org.opentrafficsim.road.gtu.lane.tactical.following.IDMPlusOld;
66 import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalPlanner;
67 import org.opentrafficsim.road.gtu.strategical.route.LaneBasedStrategicalRoutePlanner;
68 import org.opentrafficsim.road.modelproperties.IDMPropertySet;
69 import org.opentrafficsim.road.network.factory.LaneFactory;
70 import org.opentrafficsim.road.network.lane.CrossSectionLink;
71 import org.opentrafficsim.road.network.lane.DirectedLanePosition;
72 import org.opentrafficsim.road.network.lane.Lane;
73 import org.opentrafficsim.road.network.lane.LaneType;
74 import org.opentrafficsim.road.network.lane.changing.OvertakingConditions;
75 import org.opentrafficsim.road.network.lane.object.sensor.Sensor;
76 import org.opentrafficsim.road.network.lane.object.sensor.SinkSensor;
77 import org.opentrafficsim.simulationengine.AbstractWrappableAnimation;
78 import org.opentrafficsim.simulationengine.OTSSimulationException;
79 import org.opentrafficsim.simulationengine.SimpleSimulatorInterface;
80
81
82
83
84
85
86
87
88
89
90
91 public class Straight extends AbstractWrappableAnimation implements UNITS
92 {
93
94 private static final long serialVersionUID = 1L;
95
96
97 private StraightModel model;
98
99
100
101
102
103 public Straight() throws PropertyException
104 {
105 List<Property<?>> outputProperties = new ArrayList<>();
106 outputProperties.add(new BooleanProperty("DensityPlot", "Density", "Density contour plot", true, false, 0));
107 outputProperties.add(new BooleanProperty("FlowPlot", "Flow", "Flow contour plot", true, false, 1));
108 outputProperties.add(new BooleanProperty("SpeedPlot", "Speed", "Speed contour plot", true, false, 2));
109 outputProperties.add(new BooleanProperty("AccelerationPlot", "Acceleration", "Acceleration contour plot", true, false,
110 3));
111 outputProperties.add(new BooleanProperty("TrajectoryPlot", "Trajectories", "Trajectory (time/distance) diagram", true,
112 false, 4));
113 this.properties.add(new CompoundProperty("OutputGraphs", "Output graphs", "Select the graphical output",
114 outputProperties, true, 1000));
115 }
116
117
118 @Override
119 public final void stopTimersThreads()
120 {
121 super.stopTimersThreads();
122 this.model = null;
123 }
124
125
126
127
128
129
130 public static void main(final String[] args) throws SimRuntimeException
131 {
132 SwingUtilities.invokeLater(new Runnable()
133 {
134 @SuppressWarnings("synthetic-access")
135 @Override
136 public void run()
137 {
138 try
139 {
140 Straight straight = new Straight();
141 List<Property<?>> localProperties = straight.getProperties();
142 try
143 {
144 localProperties.add(new ProbabilityDistributionProperty("TrafficComposition", "Traffic composition",
145 "<html>Mix of passenger cars and trucks</html>", new String[] { "passenger car", "truck" },
146 new Double[] { 0.8, 0.2 }, false, 10));
147 }
148 catch (PropertyException exception)
149 {
150 exception.printStackTrace();
151 }
152 localProperties.add(new SelectionProperty("CarFollowingModel", "Car following model",
153 "<html>The car following model determines "
154 + "the acceleration that a vehicle will make taking into account "
155 + "nearby vehicles, infrastructural restrictions (e.g. speed limit, "
156 + "curvature of the road) capabilities of the vehicle and personality "
157 + "of the driver.</html>", new String[] { "IDM", "IDM+" }, 1, false, 1));
158 localProperties.add(IDMPropertySet.makeIDMPropertySet("IDMCar", "Car", new Acceleration(1.0,
159 METER_PER_SECOND_2), new Acceleration(1.5, METER_PER_SECOND_2), new Length(2.0, METER),
160 new Duration(1.0, SECOND), 2));
161 localProperties.add(IDMPropertySet.makeIDMPropertySet("IDMTruck", "Truck", new Acceleration(0.5,
162 METER_PER_SECOND_2), new Acceleration(1.25, METER_PER_SECOND_2), new Length(2.0, METER),
163 new Duration(1.0, SECOND), 3));
164 straight.buildAnimator(new Time(0.0, SECOND), new Duration(0.0, SECOND), new Duration(3600.0, SECOND),
165 localProperties, null, true);
166 straight.panel.getTabbedPane().addTab("info", straight.makeInfoPane());
167 }
168 catch (SimRuntimeException | NamingException | OTSSimulationException | PropertyException exception)
169 {
170 exception.printStackTrace();
171 }
172 }
173 });
174 }
175
176
177 @Override
178 protected final Rectangle2D.Double makeAnimationRectangle()
179 {
180 return new Rectangle2D.Double(1500, -100, 2000, 200);
181 }
182
183
184 @Override
185 protected final OTSModelInterface makeModel(final GTUColorer colorer)
186 {
187 this.model = new StraightModel(this.savedUserModifiedProperties, colorer);
188 return this.model;
189 }
190
191
192
193
194 protected final JComponent makeInfoPane()
195 {
196
197 String helpSource = "/" + StraightModel.class.getPackage().getName().replace('.', '/') + "/IDMPlus.html";
198 URL page = StraightModel.class.getResource(helpSource);
199 if (page != null)
200 {
201 try
202 {
203 HTMLPanel htmlPanel = new HTMLPanel(page);
204 return new JScrollPane(htmlPanel);
205 }
206 catch (IOException exception)
207 {
208 exception.printStackTrace();
209 }
210 }
211 return new JPanel();
212 }
213
214
215 @Override
216 protected final JPanel makeCharts(final SimpleSimulatorInterface simulator) throws OTSSimulationException,
217 PropertyException
218 {
219
220
221 Property<?> 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 (Property<?> 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, simulator);
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 final 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 List<LaneBasedGTUSampler> plots = new ArrayList<>();
388
389
390 private List<Property<?>> properties = null;
391
392
393 private Random randomGenerator = new Random(12345);
394
395
396 private final GTUColorer gtuColorer;
397
398
399
400
401
402 StraightModel(final List<Property<?>> 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(final SimulatorInterface<Time, Duration, OTSSimTimeDouble> theSimulator)
425 throws SimRuntimeException, RemoteException
426 {
427 this.simulator = (OTSDEVSSimulatorInterface) theSimulator;
428 try
429 {
430 OTSNode from = new OTSNode(this.network, "From", new OTSPoint3D(getMinimumDistance().getSI(), 0, 0));
431 OTSNode to = new OTSNode(this.network, "To", new OTSPoint3D(getMaximumDistance().getSI(), 0, 0));
432 OTSNode end = new OTSNode(this.network, "End", new OTSPoint3D(getMaximumDistance().getSI() + 50.0, 0, 0));
433 Set<GTUType> compatibility = new HashSet<>();
434 compatibility.add(this.gtuType);
435 LaneType laneType = new LaneType("CarLane", compatibility);
436 this.lane =
437 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);
442
443 Lane sinkLane =
444 new Lane(endLink, "sinkLane", this.lane.getLateralCenterPosition(1.0),
445 this.lane.getLateralCenterPosition(1.0), this.lane.getWidth(1.0), this.lane.getWidth(1.0),
446 laneType, 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 Property<?> 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 for (Property<?> ap : new CompoundProperty("", "", "", this.properties, false, 0))
465 {
466 if (ap instanceof SelectionProperty)
467 {
468 SelectionProperty sp = (SelectionProperty) ap;
469 if ("CarFollowingModel".equals(sp.getKey()))
470 {
471 carFollowingModelName = sp.getValue();
472 }
473 }
474 else if (ap instanceof ProbabilityDistributionProperty)
475 {
476 ProbabilityDistributionProperty pdp = (ProbabilityDistributionProperty) ap;
477 String modelName = ap.getKey();
478 if (modelName.equals("TrafficComposition"))
479 {
480 this.carProbability = pdp.getValue()[0];
481 }
482 }
483 else if (ap instanceof CompoundProperty)
484 {
485 CompoundProperty cp = (CompoundProperty) ap;
486 if (ap.getKey().equals("OutputGraphs"))
487 {
488 continue;
489 }
490 if (ap.getKey().contains("IDM"))
491 {
492 Acceleration a = IDMPropertySet.getA(cp);
493 Acceleration b = IDMPropertySet.getB(cp);
494 Length s0 = IDMPropertySet.getS0(cp);
495 Duration tSafe = IDMPropertySet.getTSafe(cp);
496 GTUFollowingModelOld gtuFollowingModel = null;
497 if (carFollowingModelName.equals("IDM"))
498 {
499 gtuFollowingModel = new IDMOld(a, b, s0, tSafe, 1.0);
500 }
501 else if (carFollowingModelName.equals("IDM+"))
502 {
503 gtuFollowingModel = new IDMPlusOld(a, b, s0, tSafe, 1.0);
504 }
505 else
506 {
507 throw new Error("Unknown gtu following model: " + carFollowingModelName);
508 }
509 if (ap.getKey().contains("Car"))
510 {
511 this.carFollowingModelCars = gtuFollowingModel;
512 }
513 else if (ap.getKey().contains("Truck"))
514 {
515 this.carFollowingModelTrucks = gtuFollowingModel;
516 }
517 else
518 {
519 throw new Error("Cannot determine gtu type for " + ap.getKey());
520 }
521
522
523
524
525
526 }
527 }
528 }
529
530
531 this.headway = new Duration(3600.0 / 1500.0, SECOND);
532
533 this.simulator.scheduleEventAbs(new Time(0.0, SECOND), this, this, "generateCar", null);
534
535 this.simulator.scheduleEventAbs(new Time(300, SECOND), this, this, "createBlock", null);
536
537 this.simulator.scheduleEventAbs(new Time(420, SECOND), this, this, "removeBlock", null);
538
539 for (int t = 1; t <= 1800; t++)
540 {
541 this.simulator.scheduleEventAbs(new Time(t - 0.001, SECOND), this, this, "drawGraphs", null);
542 }
543 }
544 catch (SimRuntimeException | NamingException | NetworkException | OTSGeometryException | PropertyException exception)
545 {
546 exception.printStackTrace();
547 }
548 }
549
550
551
552
553 protected final void drawGraphs()
554 {
555 for (LaneBasedGTUSampler plot : this.plots)
556 {
557 plot.reGraph();
558 }
559 }
560
561
562
563
564 protected final void createBlock()
565 {
566 Length initialPosition = new Length(4000, METER);
567 Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1);
568 try
569 {
570 initialPositions.add(new DirectedLanePosition(this.lane, initialPosition, GTUDirectionality.DIR_PLUS));
571 BehavioralCharacteristics behavioralCharacteristics = DefaultsFactory.getDefaultBehavioralCharacteristics();
572 this.block =
573 new LaneBasedIndividualGTU("999999", this.gtuType, new Length(4, METER), new Length(1.8, METER),
574 Speed.ZERO, this.simulator, this.network);
575 LaneBasedStrategicalPlanner strategicalPlanner =
576 new LaneBasedStrategicalRoutePlanner(behavioralCharacteristics, new LaneBasedGTUFollowingTacticalPlanner(
577 new IDMOld(), this.block), this.block);
578 this.block.initWithAnimation(strategicalPlanner, initialPositions, Speed.ZERO, DefaultCarAnimation.class,
579 this.gtuColorer);
580 }
581 catch (SimRuntimeException | NamingException | NetworkException | GTUException | OTSGeometryException exception)
582 {
583 exception.printStackTrace();
584 }
585 }
586
587
588
589
590 protected final void removeBlock()
591 {
592 this.block.destroy();
593 this.block = null;
594 }
595
596
597
598
599 protected final void generateCar()
600 {
601 boolean generateTruck = this.randomGenerator.nextDouble() > this.carProbability;
602 Length initialPosition = new Length(0, METER);
603 Speed initialSpeed = new Speed(100, KM_PER_HOUR);
604 Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1);
605 try
606 {
607 initialPositions.add(new DirectedLanePosition(this.lane, initialPosition, GTUDirectionality.DIR_PLUS));
608 Length vehicleLength = new Length(generateTruck ? 15 : 4, METER);
609 GTUFollowingModelOld gtuFollowingModel = generateTruck ? this.carFollowingModelTrucks : this.carFollowingModelCars;
610 if (null == gtuFollowingModel)
611 {
612 throw new Error("gtuFollowingModel is null");
613 }
614 BehavioralCharacteristics behavioralCharacteristics = DefaultsFactory.getDefaultBehavioralCharacteristics();
615 LaneBasedIndividualGTU gtu =
616 new LaneBasedIndividualGTU("" + (++this.carsCreated), this.gtuType, vehicleLength, new Length(1.8, METER),
617 new Speed(200, KM_PER_HOUR), this.simulator, this.network);
618 LaneBasedStrategicalPlanner strategicalPlanner =
619 new LaneBasedStrategicalRoutePlanner(behavioralCharacteristics, new LaneBasedGTUFollowingTacticalPlanner(
620 gtuFollowingModel, gtu), gtu);
621 gtu.initWithAnimation(strategicalPlanner, initialPositions, initialSpeed, DefaultCarAnimation.class,
622 this.gtuColorer);
623 this.simulator.scheduleEventRel(this.headway, this, this, "generateCar", null);
624 }
625 catch (SimRuntimeException | NamingException | NetworkException | GTUException | OTSGeometryException exception)
626 {
627 exception.printStackTrace();
628 }
629 }
630
631
632 @Override
633 public final SimulatorInterface<Time, Duration, OTSSimTimeDouble> getSimulator() throws RemoteException
634 {
635 return this.simulator;
636 }
637
638
639
640
641 public final List<LaneBasedGTUSampler> getPlots()
642 {
643 return this.plots;
644 }
645
646
647
648
649 public final Length getMinimumDistance()
650 {
651 return this.minimumDistance;
652 }
653
654
655
656
657 public final Length getMaximumDistance()
658 {
659 return this.maximumDistance;
660 }
661
662
663
664
665 public Lane getLane()
666 {
667 return this.lane;
668 }
669
670 }