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.Iterator;
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 nl.tudelft.simulation.dsol.SimRuntimeException;
25 import nl.tudelft.simulation.dsol.gui.swing.HTMLPanel;
26 import nl.tudelft.simulation.dsol.gui.swing.TablePanel;
27 import nl.tudelft.simulation.dsol.simulators.SimulatorInterface;
28
29 import org.djunits.unit.TimeUnit;
30 import org.djunits.unit.UNITS;
31 import org.djunits.value.vdouble.scalar.Acceleration;
32 import org.djunits.value.vdouble.scalar.DoubleScalar;
33 import org.djunits.value.vdouble.scalar.DoubleScalar.Abs;
34 import org.djunits.value.vdouble.scalar.DoubleScalar.Rel;
35 import org.djunits.value.vdouble.scalar.Duration;
36 import org.djunits.value.vdouble.scalar.Length;
37 import org.djunits.value.vdouble.scalar.Speed;
38 import org.djunits.value.vdouble.scalar.Time;
39 import org.opentrafficsim.core.dsol.OTSDEVSSimulatorInterface;
40 import org.opentrafficsim.core.dsol.OTSModelInterface;
41 import org.opentrafficsim.core.dsol.OTSSimTimeDouble;
42 import org.opentrafficsim.core.geometry.OTSGeometryException;
43 import org.opentrafficsim.core.geometry.OTSLine3D;
44 import org.opentrafficsim.core.geometry.OTSPoint3D;
45 import org.opentrafficsim.core.gtu.GTUDirectionality;
46 import org.opentrafficsim.core.gtu.GTUException;
47 import org.opentrafficsim.core.gtu.GTUType;
48 import org.opentrafficsim.core.gtu.animation.GTUColorer;
49 import org.opentrafficsim.core.gtu.behavioralcharacteristics.BehavioralCharacteristics;
50 import org.opentrafficsim.core.network.LongitudinalDirectionality;
51 import org.opentrafficsim.core.network.NetworkException;
52 import org.opentrafficsim.core.network.OTSNetwork;
53 import org.opentrafficsim.core.network.OTSNode;
54 import org.opentrafficsim.graphs.AccelerationContourPlot;
55 import org.opentrafficsim.graphs.ContourPlot;
56 import org.opentrafficsim.graphs.DensityContourPlot;
57 import org.opentrafficsim.graphs.FlowContourPlot;
58 import org.opentrafficsim.graphs.LaneBasedGTUSampler;
59 import org.opentrafficsim.graphs.SpeedContourPlot;
60 import org.opentrafficsim.graphs.TrajectoryPlot;
61 import org.opentrafficsim.road.gtu.animation.DefaultCarAnimation;
62 import org.opentrafficsim.road.gtu.lane.LaneBasedIndividualGTU;
63 import org.opentrafficsim.road.gtu.lane.tactical.LaneBasedGTUFollowingTacticalPlanner;
64 import org.opentrafficsim.road.gtu.lane.tactical.following.GTUFollowingModelOld;
65 import org.opentrafficsim.road.gtu.lane.tactical.following.IDMOld;
66 import org.opentrafficsim.road.gtu.lane.tactical.following.IDMPlusOld;
67 import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalPlanner;
68 import org.opentrafficsim.road.gtu.strategical.route.LaneBasedStrategicalRoutePlanner;
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.Sensor;
75 import org.opentrafficsim.road.network.lane.SinkSensor;
76 import org.opentrafficsim.simulationengine.AbstractWrappableAnimation;
77 import org.opentrafficsim.simulationengine.OTSSimulationException;
78 import org.opentrafficsim.simulationengine.properties.AbstractProperty;
79 import org.opentrafficsim.simulationengine.properties.BooleanProperty;
80 import org.opentrafficsim.simulationengine.properties.CompoundProperty;
81 import org.opentrafficsim.simulationengine.properties.IDMPropertySet;
82 import org.opentrafficsim.simulationengine.properties.ProbabilityDistributionProperty;
83 import org.opentrafficsim.simulationengine.properties.PropertyException;
84 import org.opentrafficsim.simulationengine.properties.SelectionProperty;
85
86
87
88
89
90
91
92
93
94
95
96
97
98 public class SequentialLanes extends AbstractWrappableAnimation implements UNITS
99 {
100
101 private static final long serialVersionUID = 1L;
102
103
104 private SequentialModel model;
105
106
107
108
109
110 public SequentialLanes() throws PropertyException
111 {
112 ArrayList<AbstractProperty<?>> outputProperties = new ArrayList<>();
113 outputProperties.add(new BooleanProperty("DensityPlot", "Density", "Density contour plot", true, false, 0));
114 outputProperties.add(new BooleanProperty("FlowPlot", "Flow", "Flow contour plot", true, false, 1));
115 outputProperties.add(new BooleanProperty("SpeedPlot", "Speed", "Speed contour plot", true, false, 2));
116 outputProperties.add(new BooleanProperty("AccelerationPlot", "Acceleration", "Acceleration contour plot", true,
117 false, 3));
118 outputProperties.add(new BooleanProperty("TrajectoryPlot", "Trajectories", "Trajectory (time/distance) diagram",
119 true, false, 4));
120 this.properties.add(new CompoundProperty("OutputGraphs", "Output graphs", "Select the graphical output",
121 outputProperties, true, 1000));
122 }
123
124
125 @Override
126 public final void stopTimersThreads()
127 {
128 super.stopTimersThreads();
129 this.model = null;
130 }
131
132
133
134
135
136
137 public static void main(final String[] args) throws SimRuntimeException
138 {
139 SwingUtilities.invokeLater(new Runnable()
140 {
141 @Override
142 public void run()
143 {
144 try
145 {
146 SequentialLanes sequential = new SequentialLanes();
147 ArrayList<AbstractProperty<?>> localProperties = sequential.getProperties();
148 try
149 {
150 localProperties.add(new ProbabilityDistributionProperty("TrafficComposition", "Traffic composition",
151 "<html>Mix of passenger cars and trucks</html>", new String[] {"passenger car", "truck"},
152 new Double[] {0.8, 0.2}, false, 10));
153 }
154 catch (PropertyException exception)
155 {
156 exception.printStackTrace();
157 }
158 localProperties.add(new SelectionProperty("CarFollowingModel", "Car following model",
159 "<html>The car following model determines "
160 + "the acceleration that a vehicle will make taking into account "
161 + "nearby vehicles, infrastructural restrictions (e.g. speed limit, "
162 + "curvature of the road) capabilities of the vehicle and personality "
163 + "of the driver.</html>", new String[] {"IDM", "IDM+"}, 1, false, 1));
164 localProperties.add(IDMPropertySet.makeIDMPropertySet("IDMCar", "Car", new Acceleration(1.0,
165 METER_PER_SECOND_2), new Acceleration(1.5, METER_PER_SECOND_2), new Length(2.0, METER),
166 new Duration(1.0, SECOND), 2));
167 localProperties.add(IDMPropertySet.makeIDMPropertySet("IDMTruck", "Truck", new Acceleration(0.5,
168 METER_PER_SECOND_2), new Acceleration(1.25, METER_PER_SECOND_2), new Length(2.0, METER),
169 new Duration(1.0, SECOND), 3));
170 sequential.buildAnimator(new Time(0.0, SECOND), new Duration(0.0, SECOND), 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 Rectangle2D.Double makeAnimationRectangle()
185 {
186 return new Rectangle2D.Double(0, -100, 2010, 200);
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 JPanel makeCharts() throws OTSSimulationException, PropertyException
223 {
224
225 AbstractProperty<?> 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 (AbstractProperty<?> 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 = new TrajectoryPlot("TrajectoryPlot", new Duration(0.5, SECOND), this.model.getPath());
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 return 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 OTSNetwork network = new OTSNetwork("network");
346
347
348 private ArrayList<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 = new 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 ArrayList<LaneBasedGTUSampler> plots = new ArrayList<>();
379
380
381 private Random randomGenerator = new Random(12345);
382
383
384 private ArrayList<AbstractProperty<?>> 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 public SequentialModel(final ArrayList<AbstractProperty<?>> 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<Abs<TimeUnit>, Rel<TimeUnit>, 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 OTSNode n0 = new OTSNode("Node(0,0)", new OTSPoint3D(0, 0));
426 OTSNode n1 = new OTSNode("Node(1000,0)", new OTSPoint3D(1000, 0));
427 OTSNode n2 = new OTSNode("Node(1020,3)", new OTSPoint3D(1020, 3));
428 OTSNode n3 = new OTSNode("Node(2000,197)", new OTSPoint3D(2000, 197));
429 OTSNode n4 = new OTSNode("Node(2020,200)", new OTSPoint3D(2020, 200));
430 OTSNode n5 = new OTSNode("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 try
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 =
444 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 =
458 LaneFactory.makeMultiLane(linkName, fromNode, toNode, line.getPoints(), 1, laneType, this.speedLimit,
459 this.simulator, direction);
460 if (i == this.nodes.size() - 1)
461 {
462 Sensor sensor = new SinkSensor(lanes[0], new Length(100.0, METER), this.simulator);
463 lanes[0].addSensor(sensor, GTUType.ALL);
464 }
465 this.path.add(lanes[0]);
466 links.add(lanes[0].getParentLink());
467 if (1 == i)
468 {
469 this.initialLane = lanes[0];
470 }
471 }
472 }
473 catch (NamingException | NetworkException | OTSGeometryException exception)
474 {
475 exception.printStackTrace();
476 }
477
478
479 this.headway = new Duration(3600.0 / 1500.0, SECOND);
480
481 this.simulator.scheduleEventAbs(new DoubleScalar.Abs<>(0.0, SECOND), this, this, "generateCar", null);
482
483 for (int t = 1; t <= 1800; t++)
484 {
485 this.simulator.scheduleEventAbs(new DoubleScalar.Abs<>(t - 0.001, SECOND), this, this, "drawGraphs",
486 null);
487 }
488 try
489 {
490 String carFollowingModelName = null;
491 CompoundProperty propertyContainer = new CompoundProperty("", "", "", this.properties, false, 0);
492 AbstractProperty<?> cfmp = propertyContainer.findByKey("CarFollowingModel");
493 if (null == cfmp)
494 {
495 throw new Error("Cannot find \"Car following model\" property");
496 }
497 if (cfmp instanceof SelectionProperty)
498 {
499 carFollowingModelName = ((SelectionProperty) cfmp).getValue();
500 }
501 else
502 {
503 throw new Error("\"Car following model\" property has wrong type");
504 }
505 Iterator<AbstractProperty<List<AbstractProperty<?>>>> iterator =
506 new CompoundProperty("", "", "", this.properties, false, 0).iterator();
507 while (iterator.hasNext())
508 {
509 AbstractProperty<?> ap = iterator.next();
510 if (ap instanceof SelectionProperty)
511 {
512 SelectionProperty sp = (SelectionProperty) ap;
513 if ("CarFollowingModel".equals(sp.getKey()))
514 {
515 carFollowingModelName = sp.getValue();
516 }
517 }
518 else if (ap instanceof ProbabilityDistributionProperty)
519 {
520 ProbabilityDistributionProperty pdp = (ProbabilityDistributionProperty) ap;
521 if (ap.getKey().equals("TrafficComposition"))
522 {
523 this.carProbability = pdp.getValue()[0];
524 }
525 }
526 else if (ap instanceof CompoundProperty)
527 {
528 CompoundProperty cp = (CompoundProperty) ap;
529 if (ap.getKey().equals("OutputGraphs"))
530 {
531 continue;
532 }
533 if (ap.getKey().contains("IDM"))
534 {
535
536 Acceleration a = IDMPropertySet.getA(cp);
537 Acceleration b = IDMPropertySet.getB(cp);
538 Length s0 = IDMPropertySet.getS0(cp);
539 Duration tSafe = IDMPropertySet.getTSafe(cp);
540 GTUFollowingModelOld gtuFollowingModel = null;
541 if (carFollowingModelName.equals("IDM"))
542 {
543 gtuFollowingModel = new IDMOld(a, b, s0, tSafe, 1.0);
544 }
545 else if (carFollowingModelName.equals("IDM+"))
546 {
547 gtuFollowingModel = new IDMPlusOld(a, b, s0, tSafe, 1.0);
548 }
549 else
550 {
551 throw new Error("Unknown gtu following model: " + carFollowingModelName);
552 }
553 if (ap.getKey().contains("Car"))
554 {
555 this.carFollowingModelCars = gtuFollowingModel;
556 }
557 else if (ap.getKey().contains("Truck"))
558 {
559 this.carFollowingModelTrucks = gtuFollowingModel;
560 }
561 else
562 {
563 throw new Error("Cannot determine gtu type for " + ap.getKey());
564 }
565 }
566 }
567 }
568 }
569 catch (Exception e)
570 {
571 System.out.println("Caught exception " + e);
572 }
573 }
574
575
576 @Override
577 public SimulatorInterface<Abs<TimeUnit>, Rel<TimeUnit>, OTSSimTimeDouble> getSimulator() throws RemoteException
578 {
579 return this.simulator;
580 }
581
582
583
584
585 public final ArrayList<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 =
631 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 =
638 new LaneBasedIndividualGTU("" + (++this.carsCreated), this.gtuType, vehicleLength, new Length(1.8, METER),
639 new Speed(200, KM_PER_HOUR), this.simulator, DefaultCarAnimation.class, this.gtuColorer, this.network);
640 LaneBasedStrategicalPlanner strategicalPlanner =
641 new LaneBasedStrategicalRoutePlanner(behavioralCharacteristics, new LaneBasedGTUFollowingTacticalPlanner(
642 gtuFollowingModel, gtu), gtu);
643 gtu.init(strategicalPlanner, initialPositions, initialSpeed);
644 this.simulator.scheduleEventRel(this.headway, this, this, "generateCar", null);
645 }
646 catch (SimRuntimeException | NamingException | NetworkException | GTUException | OTSGeometryException exception)
647 {
648 exception.printStackTrace();
649 }
650 }
651
652 }