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