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