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