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