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