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 org.djunits.unit.UNITS;
23 import org.djunits.value.vdouble.scalar.Acceleration;
24 import org.djunits.value.vdouble.scalar.Duration;
25 import org.djunits.value.vdouble.scalar.Length;
26 import org.djunits.value.vdouble.scalar.Speed;
27 import org.djunits.value.vdouble.scalar.Time;
28 import org.opentrafficsim.base.modelproperties.BooleanProperty;
29 import org.opentrafficsim.base.modelproperties.CompoundProperty;
30 import org.opentrafficsim.base.modelproperties.ProbabilityDistributionProperty;
31 import org.opentrafficsim.base.modelproperties.Property;
32 import org.opentrafficsim.base.modelproperties.PropertyException;
33 import org.opentrafficsim.base.modelproperties.SelectionProperty;
34 import org.opentrafficsim.core.dsol.OTSDEVSSimulatorInterface;
35 import org.opentrafficsim.core.dsol.OTSModelInterface;
36 import org.opentrafficsim.core.dsol.OTSSimTimeDouble;
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.gtu.animation.GTUColorer;
43 import org.opentrafficsim.core.gtu.behavioralcharacteristics.BehavioralCharacteristics;
44 import org.opentrafficsim.core.network.LongitudinalDirectionality;
45 import org.opentrafficsim.core.network.NetworkException;
46 import org.opentrafficsim.core.network.OTSNetwork;
47 import org.opentrafficsim.core.network.OTSNode;
48 import org.opentrafficsim.graphs.AccelerationContourPlot;
49 import org.opentrafficsim.graphs.ContourPlot;
50 import org.opentrafficsim.graphs.DensityContourPlot;
51 import org.opentrafficsim.graphs.FlowContourPlot;
52 import org.opentrafficsim.graphs.LaneBasedGTUSampler;
53 import org.opentrafficsim.graphs.SpeedContourPlot;
54 import org.opentrafficsim.graphs.TrajectoryPlot;
55 import org.opentrafficsim.road.gtu.animation.DefaultCarAnimation;
56 import org.opentrafficsim.road.gtu.lane.LaneBasedIndividualGTU;
57 import org.opentrafficsim.road.gtu.lane.tactical.LaneBasedGTUFollowingTacticalPlanner;
58 import org.opentrafficsim.road.gtu.lane.tactical.following.GTUFollowingModelOld;
59 import org.opentrafficsim.road.gtu.lane.tactical.following.IDMOld;
60 import org.opentrafficsim.road.gtu.lane.tactical.following.IDMPlusOld;
61 import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalPlanner;
62 import org.opentrafficsim.road.gtu.strategical.route.LaneBasedStrategicalRoutePlanner;
63 import org.opentrafficsim.road.modelproperties.IDMPropertySet;
64 import org.opentrafficsim.road.network.factory.LaneFactory;
65 import org.opentrafficsim.road.network.lane.CrossSectionLink;
66 import org.opentrafficsim.road.network.lane.DirectedLanePosition;
67 import org.opentrafficsim.road.network.lane.Lane;
68 import org.opentrafficsim.road.network.lane.LaneType;
69 import org.opentrafficsim.road.network.lane.changing.OvertakingConditions;
70 import org.opentrafficsim.road.network.lane.object.sensor.SinkSensor;
71 import org.opentrafficsim.simulationengine.AbstractWrappableAnimation;
72 import org.opentrafficsim.simulationengine.OTSSimulationException;
73 import org.opentrafficsim.simulationengine.SimpleSimulatorInterface;
74
75 import nl.tudelft.simulation.dsol.SimRuntimeException;
76 import nl.tudelft.simulation.dsol.gui.swing.HTMLPanel;
77 import nl.tudelft.simulation.dsol.gui.swing.TablePanel;
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.add(new BooleanProperty("AccelerationPlot", "Acceleration", "Acceleration contour plot", true, false,
109 3));
110 outputProperties.add(new BooleanProperty("TrajectoryPlot", "Trajectories", "Trajectory (time/distance) diagram", true,
111 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>", new String[] { "IDM", "IDM+" }, 1, false, 1));
157 localProperties.add(IDMPropertySet.makeIDMPropertySet("IDMCar", "Car", new Acceleration(1.0,
158 METER_PER_SECOND_2), new Acceleration(1.5, METER_PER_SECOND_2), new Length(2.0, METER),
159 new Duration(1.0, SECOND), 2));
160 localProperties.add(IDMPropertySet.makeIDMPropertySet("IDMTruck", "Truck", new Acceleration(0.5,
161 METER_PER_SECOND_2), new Acceleration(1.25, METER_PER_SECOND_2), new Length(2.0, METER),
162 new Duration(1.0, SECOND), 3));
163 straight.buildAnimator(new Time(0.0, SECOND), new Duration(0.0, SECOND), new Duration(3600.0, SECOND),
164 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 Rectangle2D.Double makeAnimationRectangle()
178 {
179 return new Rectangle2D.Double(1500, -100, 2000, 200);
180 }
181
182
183 @Override
184 protected final OTSModelInterface makeModel(final GTUColorer colorer)
185 {
186 this.model = new StraightModel(this.savedUserModifiedProperties, colorer);
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 JPanel makeCharts(final SimpleSimulatorInterface simulator) throws OTSSimulationException,
216 PropertyException
217 {
218
219
220 Property<?> output = new CompoundProperty("", "", "", this.properties, false, 0).findByKey("OutputGraphs");
221 if (null == output)
222 {
223 throw new Error("Cannot find output properties");
224 }
225 ArrayList<BooleanProperty> graphs = new ArrayList<>();
226 if (output instanceof CompoundProperty)
227 {
228 CompoundProperty outputProperties = (CompoundProperty) output;
229 for (Property<?> ap : outputProperties.getValue())
230 {
231 if (ap instanceof BooleanProperty)
232 {
233 BooleanProperty bp = (BooleanProperty) ap;
234 if (bp.getValue())
235 {
236 graphs.add(bp);
237 }
238 }
239 }
240 }
241 else
242 {
243 throw new Error("output properties should be compound");
244 }
245 int graphCount = graphs.size();
246 int columns = (int) Math.ceil(Math.sqrt(graphCount));
247 int rows = 0 == columns ? 0 : (int) Math.ceil(graphCount * 1.0 / columns);
248 TablePanel charts = new TablePanel(columns, rows);
249
250 for (int i = 0; i < graphCount; i++)
251 {
252 String graphName = graphs.get(i).getKey();
253 Container container = null;
254 LaneBasedGTUSampler graph;
255 if (graphName.contains("TrajectoryPlot"))
256 {
257 List<Lane> path = new ArrayList<>();
258 path.add(this.model.getLane());
259 TrajectoryPlot tp = new TrajectoryPlot("Trajectory Graph", new Duration(0.5, SECOND), path, simulator);
260 tp.setTitle("Trajectory Graph");
261 tp.setExtendedState(Frame.MAXIMIZED_BOTH);
262 graph = tp;
263 container = tp.getContentPane();
264 }
265 else
266 {
267 ContourPlot cp;
268 if (graphName.contains("DensityPlot"))
269 {
270 cp = new DensityContourPlot("Density Graph", this.model.getPath());
271 cp.setTitle("Density Contour Graph");
272 }
273 else if (graphName.contains("SpeedPlot"))
274 {
275 cp = new SpeedContourPlot("Speed Graph", this.model.getPath());
276 cp.setTitle("Speed Contour Graph");
277 }
278 else if (graphName.contains("Flow"))
279 {
280 cp = new FlowContourPlot("Flow Graph", this.model.getPath());
281 cp.setTitle("Flow Contour Graph");
282 }
283 else if (graphName.contains("AccelerationPlot"))
284 {
285 cp = new AccelerationContourPlot("Acceleration Graph", this.model.getPath());
286 cp.setTitle("Acceleration Contour Graph");
287 }
288 else
289 {
290 throw new Error("Unhandled type of contourplot: " + graphName);
291 }
292 graph = cp;
293 container = cp.getContentPane();
294 }
295
296 charts.setCell(container, i % columns, i / columns);
297 this.model.getPlots().add(graph);
298 }
299 return charts;
300 }
301
302
303 @Override
304 public final String shortName()
305 {
306 return "Straight lane";
307 }
308
309
310 @Override
311 public final String description()
312 {
313 return "<html><h1>Simulation of a straight one-lane road with opening bridge</H1>"
314 + "Simulation of a single lane road of 5 km length. Vehicles are generated at a constant rate of "
315 + "1500 veh/hour. At time 300s a blockade is inserted at position 4km; this blockade is removed at "
316 + "time 420s. This blockade simulates a bridge opening.<br>"
317 + "The blockade causes a traffic jam that slowly dissolves after the blockade is removed.<br>"
318 + "Selected trajectory and contour plots are generated during the simulation.</html>";
319 }
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 class StraightModel implements OTSModelInterface, UNITS
345 {
346
347 private static final long serialVersionUID = 20140815L;
348
349
350 private OTSDEVSSimulatorInterface simulator;
351
352
353 private final OTSNetwork network = new OTSNetwork("network");
354
355
356 private Duration headway;
357
358
359 private int carsCreated = 0;
360
361
362 private GTUType gtuType = new GTUType("Car");
363
364
365 private GTUFollowingModelOld carFollowingModelCars;
366
367
368 private GTUFollowingModelOld carFollowingModelTrucks;
369
370
371 private double carProbability;
372
373
374 private LaneBasedIndividualGTU block = null;
375
376
377 private Length minimumDistance = new Length(0, METER);
378
379
380 private Length maximumDistance = new Length(5000, METER);
381
382
383 private Lane lane;
384
385
386 private List<LaneBasedGTUSampler> plots = new ArrayList<>();
387
388
389 private List<Property<?>> properties = null;
390
391
392 private Random randomGenerator = new Random(12345);
393
394
395 private final GTUColorer gtuColorer;
396
397
398
399
400
401 StraightModel(final List<Property<?>> properties, final GTUColorer gtuColorer)
402 {
403 this.properties = properties;
404 this.gtuColorer = gtuColorer;
405 }
406
407
408 private List<Lane> path = new ArrayList<>();
409
410
411 private Speed speedLimit = new Speed(100, KM_PER_HOUR);
412
413
414
415
416 public List<Lane> getPath()
417 {
418 return new ArrayList<>(this.path);
419 }
420
421
422 @Override
423 public final void constructModel(final SimulatorInterface<Time, Duration, OTSSimTimeDouble> theSimulator)
424 throws SimRuntimeException, RemoteException
425 {
426 this.simulator = (OTSDEVSSimulatorInterface) theSimulator;
427 try
428 {
429 OTSNode from = new OTSNode(this.network, "From", new OTSPoint3D(getMinimumDistance().getSI(), 0, 0));
430 OTSNode to = new OTSNode(this.network, "To", new OTSPoint3D(getMaximumDistance().getSI(), 0, 0));
431 OTSNode end = new OTSNode(this.network, "End", new OTSPoint3D(getMaximumDistance().getSI() + 50.0, 0, 0));
432 Set<GTUType> compatibility = new HashSet<>();
433 compatibility.add(this.gtuType);
434 LaneType laneType = new LaneType("CarLane", compatibility);
435 this.lane =
436 LaneFactory.makeLane(this.network, "Lane", from, to, null, laneType, this.speedLimit, this.simulator,
437 LongitudinalDirectionality.DIR_PLUS);
438 this.path.add(this.lane);
439 CrossSectionLink endLink =
440 LaneFactory.makeLink(this.network, "endLink", to, end, null, LongitudinalDirectionality.DIR_PLUS);
441
442 Lane sinkLane =
443 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),
445 laneType, 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 =
571 new LaneBasedIndividualGTU("999999", this.gtuType, new Length(4, METER), new Length(1.8, METER),
572 Speed.ZERO, this.simulator, this.network);
573 LaneBasedStrategicalPlanner strategicalPlanner =
574 new LaneBasedStrategicalRoutePlanner(behavioralCharacteristics, new LaneBasedGTUFollowingTacticalPlanner(
575 new IDMOld(), this.block), this.block);
576 this.block.initWithAnimation(strategicalPlanner, initialPositions, Speed.ZERO, DefaultCarAnimation.class,
577 this.gtuColorer);
578 }
579 catch (SimRuntimeException | NamingException | NetworkException | GTUException | OTSGeometryException exception)
580 {
581 exception.printStackTrace();
582 }
583 }
584
585
586
587
588 protected final void removeBlock()
589 {
590 this.block.destroy();
591 this.block = null;
592 }
593
594
595
596
597 protected final void generateCar()
598 {
599 boolean generateTruck = this.randomGenerator.nextDouble() > this.carProbability;
600 Length initialPosition = new Length(0, METER);
601 Speed initialSpeed = new Speed(100, KM_PER_HOUR);
602 Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1);
603 try
604 {
605 initialPositions.add(new DirectedLanePosition(this.lane, initialPosition, GTUDirectionality.DIR_PLUS));
606 Length vehicleLength = new Length(generateTruck ? 15 : 4, METER);
607 GTUFollowingModelOld gtuFollowingModel = generateTruck ? this.carFollowingModelTrucks : this.carFollowingModelCars;
608 if (null == gtuFollowingModel)
609 {
610 throw new Error("gtuFollowingModel is null");
611 }
612 BehavioralCharacteristics behavioralCharacteristics = DefaultsFactory.getDefaultBehavioralCharacteristics();
613 LaneBasedIndividualGTU gtu =
614 new LaneBasedIndividualGTU("" + (++this.carsCreated), this.gtuType, vehicleLength, new Length(1.8, METER),
615 new Speed(200, KM_PER_HOUR), this.simulator, this.network);
616 LaneBasedStrategicalPlanner strategicalPlanner =
617 new LaneBasedStrategicalRoutePlanner(behavioralCharacteristics, new LaneBasedGTUFollowingTacticalPlanner(
618 gtuFollowingModel, gtu), gtu);
619 gtu.initWithAnimation(strategicalPlanner, initialPositions, initialSpeed, DefaultCarAnimation.class,
620 this.gtuColorer);
621 this.simulator.scheduleEventRel(this.headway, this, this, "generateCar", null);
622 }
623 catch (SimRuntimeException | NamingException | NetworkException | GTUException | OTSGeometryException exception)
624 {
625 exception.printStackTrace();
626 }
627 }
628
629
630 @Override
631 public final SimulatorInterface<Time, Duration, OTSSimTimeDouble> getSimulator() throws RemoteException
632 {
633 return this.simulator;
634 }
635
636
637
638
639 public final List<LaneBasedGTUSampler> getPlots()
640 {
641 return this.plots;
642 }
643
644
645
646
647 public final Length getMinimumDistance()
648 {
649 return this.minimumDistance;
650 }
651
652
653
654
655 public final Length getMaximumDistance()
656 {
657 return this.maximumDistance;
658 }
659
660
661
662
663 public Lane getLane()
664 {
665 return this.lane;
666 }
667
668 }