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