1 package org.opentrafficsim.demo.carFollowing;
2
3 import static org.opentrafficsim.core.gtu.GTUType.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.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.TimeUnit;
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.base.parameters.Parameters;
37 import org.opentrafficsim.core.dsol.OTSModelInterface;
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.network.LongitudinalDirectionality;
45 import org.opentrafficsim.core.network.NetworkException;
46 import org.opentrafficsim.core.network.OTSNetwork;
47 import org.opentrafficsim.core.network.OTSNode;
48 import org.opentrafficsim.demo.carFollowing.Straight.StraightModel;
49 import org.opentrafficsim.graphs.AccelerationContourPlot;
50 import org.opentrafficsim.graphs.ContourPlot;
51 import org.opentrafficsim.graphs.DensityContourPlot;
52 import org.opentrafficsim.graphs.FlowContourPlot;
53 import org.opentrafficsim.graphs.LaneBasedGTUSampler;
54 import org.opentrafficsim.graphs.SpeedContourPlot;
55 import org.opentrafficsim.graphs.TrajectoryPlot;
56 import org.opentrafficsim.road.animation.AnimationToggles;
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.simtime.SimTimeDoubleUnit;
80 import nl.tudelft.simulation.dsol.simulators.DEVSSimulatorInterface;
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(Time.ZERO, Duration.ZERO, new Duration(3600.0, SECOND), localProperties, null,
170 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()
191 {
192 this.model = new SequentialModel(this.savedUserModifiedProperties);
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 class SequentialModel implements OTSModelInterface, UNITS
336 {
337
338 private static final long serialVersionUID = 20150130L;
339
340
341 private DEVSSimulatorInterface.TimeDoubleUnit 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 = 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
393
394 SequentialModel(final List<Property<?>> properties)
395 {
396 this.properties = properties;
397 }
398
399
400
401
402 public List<Lane> getPath()
403 {
404 return new ArrayList<>(this.path);
405 }
406
407
408 @Override
409 public final void constructModel(final SimulatorInterface<Time, Duration, SimTimeDoubleUnit> theSimulator)
410 throws SimRuntimeException
411 {
412 this.simulator = (DEVSSimulatorInterface.TimeDoubleUnit) theSimulator;
413 this.speedLimit = new Speed(100, KM_PER_HOUR);
414
415
416 boolean minus = false;
417
418 this.nodes = new ArrayList<>();
419 try
420 {
421 OTSNode n0 = new OTSNode(this.network, "Node(0,0)", new OTSPoint3D(0, 0));
422 OTSNode n1 = new OTSNode(this.network, "Node(1000,0)", new OTSPoint3D(1000, 0));
423 OTSNode n2 = new OTSNode(this.network, "Node(1020,3)", new OTSPoint3D(1020, 3));
424 OTSNode n3 = new OTSNode(this.network, "Node(2000,197)", new OTSPoint3D(2000, 197));
425 OTSNode n4 = new OTSNode(this.network, "Node(2020,200)", new OTSPoint3D(2020, 200));
426 OTSNode n5 = new OTSNode(this.network, "Node(2200,200)", new OTSPoint3D(2200, 200));
427 this.nodes.addAll(Arrays.asList(new OTSNode[] { n0, n1, n2, n3, n4, n5 }));
428
429 LaneType laneType = LaneType.TWO_WAY_LANE;
430
431
432 ArrayList<CrossSectionLink> links = new ArrayList<>();
433 OTSLine3D l01 = new OTSLine3D(n0.getPoint(), n1.getPoint());
434 OTSLine3D l12 = LaneFactory.makeBezier(n0, n1, n2, n3);
435 OTSLine3D l23 =
436 minus ? new OTSLine3D(n3.getPoint(), n2.getPoint()) : new OTSLine3D(n2.getPoint(), n3.getPoint());
437 OTSLine3D l34 = LaneFactory.makeBezier(n2, n3, n4, n5);
438 OTSLine3D l45 = new OTSLine3D(n4.getPoint(), n5.getPoint());
439 OTSLine3D[] lines = new OTSLine3D[] { l01, l12, l23, l34, l45 };
440
441 for (int i = 1; i < this.nodes.size(); i++)
442 {
443 OTSNode fromNode = this.nodes.get(i - 1);
444 OTSNode toNode = this.nodes.get(i);
445 OTSLine3D line = lines[i - 1];
446 String linkName = fromNode.getId() + "-" + toNode.getId();
447 LongitudinalDirectionality direction = line.equals(l23) && minus ? LongitudinalDirectionality.DIR_MINUS
448 : LongitudinalDirectionality.DIR_PLUS;
449 Lane[] lanes = LaneFactory.makeMultiLane(this.network, linkName, fromNode, toNode, line.getPoints(), 1,
450 laneType, this.speedLimit, this.simulator);
451 if (i == this.nodes.size() - 1)
452 {
453 new SinkSensor(lanes[0], new Length(100.0, METER), this.simulator);
454 }
455 this.path.add(lanes[0]);
456 links.add(lanes[0].getParentLink());
457 if (1 == i)
458 {
459 this.initialLane = lanes[0];
460 }
461 }
462 }
463 catch (NamingException | NetworkException | OTSGeometryException exception)
464 {
465 exception.printStackTrace();
466 }
467
468
469 this.headway = new Duration(3600.0 / 1500.0, SECOND);
470
471 this.simulator.scheduleEventAbs(Time.ZERO, this, this, "generateCar", null);
472
473 for (int t = 1; t <= 1800; t++)
474 {
475 this.simulator.scheduleEventAbs(new Time(t - 0.001, TimeUnit.BASE_SECOND), this, this, "drawGraphs", null);
476 }
477 try
478 {
479 String carFollowingModelName = null;
480 CompoundProperty propertyContainer = new CompoundProperty("", "", "", this.properties, false, 0);
481 Property<?> cfmp = propertyContainer.findByKey("CarFollowingModel");
482 if (null == cfmp)
483 {
484 throw new Error("Cannot find \"Car following model\" property");
485 }
486 if (cfmp instanceof SelectionProperty)
487 {
488 carFollowingModelName = ((SelectionProperty) cfmp).getValue();
489 }
490 else
491 {
492 throw new Error("\"Car following model\" property has wrong type");
493 }
494 for (Property<?> ap : new CompoundProperty("", "", "", this.properties, false, 0))
495 {
496 if (ap instanceof SelectionProperty)
497 {
498 SelectionProperty sp = (SelectionProperty) ap;
499 if ("CarFollowingModel".equals(sp.getKey()))
500 {
501 carFollowingModelName = sp.getValue();
502 }
503 }
504 else if (ap instanceof ProbabilityDistributionProperty)
505 {
506 ProbabilityDistributionProperty pdp = (ProbabilityDistributionProperty) ap;
507 if (ap.getKey().equals("TrafficComposition"))
508 {
509 this.carProbability = pdp.getValue()[0];
510 }
511 }
512 else if (ap instanceof CompoundProperty)
513 {
514 CompoundProperty cp = (CompoundProperty) ap;
515 if (ap.getKey().equals("OutputGraphs"))
516 {
517 continue;
518 }
519 if (ap.getKey().contains("IDM"))
520 {
521
522 Acceleration a = IDMPropertySet.getA(cp);
523 Acceleration b = IDMPropertySet.getB(cp);
524 Length s0 = IDMPropertySet.getS0(cp);
525 Duration tSafe = IDMPropertySet.getTSafe(cp);
526 GTUFollowingModelOld gtuFollowingModel = null;
527 if (carFollowingModelName.equals("IDM"))
528 {
529 gtuFollowingModel = new IDMOld(a, b, s0, tSafe, 1.0);
530 }
531 else if (carFollowingModelName.equals("IDM+"))
532 {
533 gtuFollowingModel = new IDMPlusOld(a, b, s0, tSafe, 1.0);
534 }
535 else
536 {
537 throw new Error("Unknown gtu following model: " + carFollowingModelName);
538 }
539 if (ap.getKey().contains("Car"))
540 {
541 this.carFollowingModelCars = gtuFollowingModel;
542 }
543 else if (ap.getKey().contains("Truck"))
544 {
545 this.carFollowingModelTrucks = gtuFollowingModel;
546 }
547 else
548 {
549 throw new Error("Cannot determine gtu type for " + ap.getKey());
550 }
551 }
552 }
553 }
554 }
555 catch (Exception e)
556 {
557 System.out.println("Caught exception " + e);
558 }
559 }
560
561
562 @Override
563 public SimulatorInterface<Time, Duration, SimTimeDoubleUnit> getSimulator()
564 {
565 return this.simulator;
566 }
567
568
569 @Override
570 public OTSNetwork getNetwork()
571 {
572 return this.network;
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 =
624 generateTruck ? this.carFollowingModelTrucks : this.carFollowingModelCars;
625 if (null == gtuFollowingModel)
626 {
627 throw new Error("gtuFollowingModel is null");
628 }
629 Parameters parameters = DefaultsFactory.getDefaultParameters();
630 LaneBasedIndividualGTU gtu = new LaneBasedIndividualGTU("" + (++this.carsCreated), this.gtuType, vehicleLength,
631 new Length(1.8, METER), new Speed(200, KM_PER_HOUR), vehicleLength.multiplyBy(0.5), this.simulator,
632 this.network);
633 LaneBasedStrategicalPlanner strategicalPlanner = new LaneBasedStrategicalRoutePlanner(
634 new LaneBasedGTUFollowingTacticalPlanner(gtuFollowingModel, gtu), gtu);
635 gtu.setParameters(parameters);
636 gtu.initWithAnimation(strategicalPlanner, initialPositions, initialSpeed, DefaultCarAnimation.class,
637 SequentialLanes.this.getColorer());
638 this.simulator.scheduleEventRel(this.headway, this, this, "generateCar", null);
639 }
640 catch (SimRuntimeException | NamingException | NetworkException | GTUException | OTSGeometryException exception)
641 {
642 exception.printStackTrace();
643 }
644 }
645
646 }
647 }