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