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