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