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