View Javadoc
1   package org.opentrafficsim.demo.carFollowing;
2   
3   import static org.opentrafficsim.road.gtu.lane.RoadGTUTypes.CAR;
4   
5   import java.awt.Frame;
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.SwingUtilities;
16  
17  import org.djunits.unit.UNITS;
18  import org.djunits.value.vdouble.scalar.Acceleration;
19  import org.djunits.value.vdouble.scalar.Duration;
20  import org.djunits.value.vdouble.scalar.Length;
21  import org.djunits.value.vdouble.scalar.Speed;
22  import org.djunits.value.vdouble.scalar.Time;
23  import org.opentrafficsim.base.modelproperties.ProbabilityDistributionProperty;
24  import org.opentrafficsim.base.modelproperties.Property;
25  import org.opentrafficsim.base.modelproperties.PropertyException;
26  import org.opentrafficsim.base.modelproperties.SelectionProperty;
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.GTUDirectionality;
33  import org.opentrafficsim.core.gtu.GTUException;
34  import org.opentrafficsim.core.gtu.GTUType;
35  import org.opentrafficsim.core.gtu.animation.GTUColorer;
36  import org.opentrafficsim.core.gtu.behavioralcharacteristics.BehavioralCharacteristics;
37  import org.opentrafficsim.core.network.LongitudinalDirectionality;
38  import org.opentrafficsim.core.network.NetworkException;
39  import org.opentrafficsim.core.network.OTSNetwork;
40  import org.opentrafficsim.core.network.OTSNode;
41  import org.opentrafficsim.graphs.FundamentalDiagram;
42  import org.opentrafficsim.road.animation.AnimationToggles;
43  import org.opentrafficsim.road.gtu.animation.DefaultCarAnimation;
44  import org.opentrafficsim.road.gtu.lane.LaneBasedIndividualGTU;
45  import org.opentrafficsim.road.gtu.lane.tactical.LaneBasedGTUFollowingTacticalPlanner;
46  import org.opentrafficsim.road.gtu.lane.tactical.following.GTUFollowingModelOld;
47  import org.opentrafficsim.road.gtu.lane.tactical.following.IDMOld;
48  import org.opentrafficsim.road.gtu.lane.tactical.following.IDMPlusOld;
49  import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalPlanner;
50  import org.opentrafficsim.road.gtu.strategical.route.LaneBasedStrategicalRoutePlanner;
51  import org.opentrafficsim.road.network.factory.LaneFactory;
52  import org.opentrafficsim.road.network.lane.CrossSectionLink;
53  import org.opentrafficsim.road.network.lane.DirectedLanePosition;
54  import org.opentrafficsim.road.network.lane.Lane;
55  import org.opentrafficsim.road.network.lane.LaneType;
56  import org.opentrafficsim.road.network.lane.changing.OvertakingConditions;
57  import org.opentrafficsim.road.network.lane.object.sensor.SinkSensor;
58  import org.opentrafficsim.simulationengine.AbstractWrappableAnimation;
59  import org.opentrafficsim.simulationengine.OTSSimulationException;
60  import org.opentrafficsim.simulationengine.SimpleSimulatorInterface;
61  
62  import nl.tudelft.simulation.dsol.SimRuntimeException;
63  import nl.tudelft.simulation.dsol.gui.swing.TablePanel;
64  import nl.tudelft.simulation.dsol.simulators.SimulatorInterface;
65  
66  /**
67   * Demonstrate the FundamentalDiagram plot.
68   * <p>
69   * Copyright (c) 2013-2016 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
70   * BSD-style license. See <a href="http://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
71   * <p>
72   * $LastChangedDate: 2017-01-16 02:02:12 +0100 (Mon, 16 Jan 2017) $, @version $Revision: 3285 $, by $Author: averbraeck $,
73   * initial version 17 dec. 2014 <br>
74   * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
75   */
76  public class FundamentalDiagrams extends AbstractWrappableAnimation implements UNITS
77  {
78      /** */
79      private static final long serialVersionUID = 1L;
80  
81      /** The model. */
82      private FundamentalDiagramPlotsModel model;
83  
84      /** Create a FundamentalDiagrams simulation. */
85      public FundamentalDiagrams()
86      {
87          try
88          {
89              this.properties.add(new SelectionProperty("CarFollowingModel", "Car following model",
90                      "<html>The car following model determines "
91                              + "the acceleration that a vehicle will make taking into account nearby vehicles, "
92                              + "infrastructural restrictions (e.g. speed limit, curvature of the road) "
93                              + "capabilities of the vehicle and personality of the driver.</html>",
94                      new String[] { "IDM", "IDM+" }, 1, false, 500));
95              this.properties.add(new ProbabilityDistributionProperty("TrafficComposition", "Traffic composition",
96                      "<html>Mix of passenger cars and trucks</html>", new String[] { "passenger car", "truck" },
97                      new Double[] { 0.8, 0.2 }, false, 10));
98          }
99          catch (PropertyException exception)
100         {
101             exception.printStackTrace();
102         }
103     }
104 
105     /** {@inheritDoc} */
106     @Override
107     public final void stopTimersThreads()
108     {
109         super.stopTimersThreads();
110         this.model = null;
111     }
112 
113     /**
114      * Main program.
115      * @param args String[]; the command line arguments (not used)
116      * @throws SimRuntimeException on ???
117      */
118     public static void main(final String[] args) throws SimRuntimeException
119     {
120         // Create the simulation and wrap its panel in a JFrame. It does not get much easier/shorter than this...
121         SwingUtilities.invokeLater(new Runnable()
122         {
123             @Override
124             public void run()
125             {
126                 try
127                 {
128                     FundamentalDiagrams fundamentalDiagrams = new FundamentalDiagrams();
129                     fundamentalDiagrams.buildAnimator(new Time(0.0, SECOND), new Duration(0.0, SECOND),
130                             new Duration(3600.0, SECOND), fundamentalDiagrams.getProperties(), null, true);
131                 }
132                 catch (SimRuntimeException | NamingException | OTSSimulationException | PropertyException exception)
133                 {
134                     exception.printStackTrace();
135                 }
136             }
137         });
138     }
139 
140     /** {@inheritDoc} */
141     @Override
142     protected final OTSModelInterface makeModel(final GTUColorer colorer)
143     {
144         this.model = new FundamentalDiagramPlotsModel(this.savedUserModifiedProperties, colorer);
145         return this.model;
146     }
147 
148     /** {@inheritDoc} */
149     @Override
150     protected final void addAnimationToggles()
151     {
152         AnimationToggles.setTextAnimationTogglesStandard(this);
153     }
154 
155     /** {@inheritDoc} */
156     @Override
157     protected final void addTabs(final SimpleSimulatorInterface simulator) throws OTSSimulationException
158     {
159         final int panelsPerRow = 3;
160         TablePanel charts = new TablePanel(4, panelsPerRow);
161         for (int plotNumber = 0; plotNumber < 10; plotNumber++)
162         {
163             Length detectorLocation = new Length(400 + 500 * plotNumber, METER);
164             FundamentalDiagram fd;
165             try
166             {
167                 fd = new FundamentalDiagram("Fundamental Diagram at " + detectorLocation.getSI() + "m", new Duration(1, MINUTE),
168                         this.model.getLane(), detectorLocation, simulator);
169                 fd.setTitle("Density Contour Graph");
170                 fd.setExtendedState(Frame.MAXIMIZED_BOTH);
171                 this.model.getFundamentalDiagrams().add(fd);
172                 charts.setCell(fd.getContentPane(), plotNumber / panelsPerRow, plotNumber % panelsPerRow);
173             }
174             catch (NetworkException exception)
175             {
176                 exception.printStackTrace();
177             }
178         }
179         addTab(getTabCount(), "statistics", charts);
180     }
181 
182     /** {@inheritDoc} */
183     @Override
184     public final String shortName()
185     {
186         return "Fundamental Diagrams";
187     }
188 
189     /** {@inheritDoc} */
190     @Override
191     public final String description()
192     {
193         return "<html><h1>Fundamental Diagram Plots</H1>"
194                 + "Simulation of a single lane road of 5 km length. Vechicles are generated at a constant rate of "
195                 + "1500 veh/hour. At time 300s a blockade is inserted at position 4km; this blockade is removed at time "
196                 + "500s. This blockade simulates a bridge opening.<br>"
197                 + "The blockade causes a traffic jam that slowly dissolves after the blockade is removed.<br>"
198                 + "Output is a set of Diagrams that plot observed density, flow and speed plots against each other.</html>";
199     }
200 
201     /**
202      * Simulate a single lane road of 5 km length. Vehicles are generated at a constant rate of 1500 veh/hour. At time 300s a
203      * blockade is inserted at position 4 km; this blockade is removed at time 500s. The used car following algorithm is IDM+
204      * <a href="http://opentrafficsim.org/downloads/MOTUS%20reference.pdf"><i>Integrated Lane Change Model with Relaxation and
205      * Synchronization</i>, by Wouter J. Schakel, Victor L. Knoop and Bart van Arem, 2012</a>. <br>
206      * Output is a set of FundamentalDiagram plots for various point along the lane.
207      * <p>
208      * Copyright (c) 2013-2016 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
209      * <br>
210      * BSD-style license. See <a href="http://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
211      * <p>
212      * $LastChangedDate: 2017-01-16 02:02:12 +0100 (Mon, 16 Jan 2017) $, @version $Revision: 3285 $, by $Author: averbraeck $,
213      * initial version ug 1, 2014 <br>
214      * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
215      */
216     class FundamentalDiagramPlotsModel implements OTSModelInterface, UNITS
217     {
218         /** */
219         private static final long serialVersionUID = 20140820L;
220 
221         /** The simulator. */
222         private OTSDEVSSimulatorInterface simulator;
223 
224         /** The network. */
225         private OTSNetwork network = new OTSNetwork("network");
226 
227         /** The headway (inter-vehicle time). */
228         private Duration headway;
229 
230         /** Number of cars created. */
231         private int carsCreated = 0;
232 
233         /** Type of all GTUs. */
234         private GTUType gtuType = CAR;
235 
236         /** The car following model, e.g. IDM Plus for cars. */
237         private GTUFollowingModelOld carFollowingModelCars;
238 
239         /** The car following model, e.g. IDM Plus for trucks. */
240         private GTUFollowingModelOld carFollowingModelTrucks;
241 
242         /** The probability that the next generated GTU is a passenger car. */
243         private double carProbability;
244 
245         /** The blocking car. */
246         private LaneBasedIndividualGTU block = null;
247 
248         /** Minimum distance. */
249         private Length minimumDistance = new Length(0, METER);
250 
251         /** Maximum distance. */
252         private Length maximumDistance = new Length(5000, METER);
253 
254         /** The Lane containing the simulated Cars. */
255         private Lane lane;
256 
257         /** The speed limit. */
258         private Speed speedLimit = new Speed(100, KM_PER_HOUR);
259 
260         /** The fundamental diagram plots. */
261         private List<FundamentalDiagram> fundamentalDiagrams = new ArrayList<>();
262 
263         /** User settable properties. */
264         private List<Property<?>> fundamentalDiagramProperties = null;
265 
266         /** The random number generator used to decide what kind of GTU to generate. */
267         private Random randomGenerator = new Random(12345);
268 
269         /** The GTUColorer for the generated vehicles. */
270         private final GTUColorer gtuColorer;
271 
272         /**
273          * @param properties ArrayList&lt;AbstractProperty&lt;?&gt;&gt;; the properties
274          * @param gtuColorer the default and initial GTUColorer, e.g. a DefaultSwitchableTUColorer.
275          */
276         FundamentalDiagramPlotsModel(final List<Property<?>> properties, final GTUColorer gtuColorer)
277         {
278             this.fundamentalDiagramProperties = properties;
279             this.gtuColorer = gtuColorer;
280         }
281 
282         /** {@inheritDoc} */
283         @Override
284         public final void constructModel(final SimulatorInterface<Time, Duration, OTSSimTimeDouble> theSimulator)
285                 throws SimRuntimeException, RemoteException
286         {
287             try
288             {
289                 this.simulator = (OTSDEVSSimulatorInterface) theSimulator;
290                 OTSNode from = new OTSNode(this.network, "From", new OTSPoint3D(getMinimumDistance().getSI(), 0, 0));
291                 OTSNode to = new OTSNode(this.network, "To", new OTSPoint3D(getMaximumDistance().getSI(), 0, 0));
292                 OTSNode end = new OTSNode(this.network, "End", new OTSPoint3D(getMaximumDistance().getSI() + 50.0, 0, 0));
293                 Set<GTUType> compatibility = new HashSet<>();
294                 compatibility.add(this.gtuType);
295                 LaneType laneType = new LaneType("CarLane", compatibility);
296                 this.lane = LaneFactory.makeLane(this.network, "Lane", from, to, null, laneType, this.speedLimit,
297                         this.simulator, LongitudinalDirectionality.DIR_PLUS);
298                 CrossSectionLink endLink = LaneFactory.makeLink(this.network, "endLink", to, end, null,
299                         LongitudinalDirectionality.DIR_PLUS, simulator);
300                 // No overtaking, single lane
301                 Lane sinkLane = new Lane(endLink, "sinkLane", this.lane.getLateralCenterPosition(1.0),
302                         this.lane.getLateralCenterPosition(1.0), this.lane.getWidth(1.0), this.lane.getWidth(1.0), laneType,
303                         LongitudinalDirectionality.DIR_PLUS, this.speedLimit, new OvertakingConditions.None());
304                 new SinkSensor(sinkLane, new Length(10.0, METER), this.simulator);
305             }
306             catch (NamingException | NetworkException | OTSGeometryException exception)
307             {
308                 exception.printStackTrace();
309             }
310 
311             // create SinkLane
312 
313             for (Property<?> p : this.fundamentalDiagramProperties)
314             {
315                 if (p instanceof SelectionProperty)
316                 {
317                     SelectionProperty sp = (SelectionProperty) p;
318                     if ("CarFollowingModel".equals(sp.getKey()))
319                     {
320                         String modelName = sp.getValue();
321                         if (modelName.equals("IDM"))
322                         {
323                             this.carFollowingModelCars = new IDMOld(new Acceleration(1, METER_PER_SECOND_2),
324                                     new Acceleration(1.5, METER_PER_SECOND_2), new Length(2, METER), new Duration(1, SECOND),
325                                     1d);
326                             this.carFollowingModelTrucks = new IDMOld(new Acceleration(0.5, METER_PER_SECOND_2),
327                                     new Acceleration(1.5, METER_PER_SECOND_2), new Length(2, METER), new Duration(1, SECOND),
328                                     1d);
329                         }
330                         else if (modelName.equals("IDM+"))
331                         {
332                             this.carFollowingModelCars = new IDMPlusOld(new Acceleration(1, METER_PER_SECOND_2),
333                                     new Acceleration(1.5, METER_PER_SECOND_2), new Length(2, METER), new Duration(1, SECOND),
334                                     1d);
335                             this.carFollowingModelTrucks = new IDMPlusOld(new Acceleration(0.5, METER_PER_SECOND_2),
336                                     new Acceleration(1.5, METER_PER_SECOND_2), new Length(2, METER), new Duration(1, SECOND),
337                                     1d);
338                         }
339                         else
340                         {
341                             throw new Error("Car following model " + modelName + " not implemented");
342                         }
343                     }
344                     else
345                     {
346                         throw new Error("Unhandled SelectionProperty " + p.getKey());
347                     }
348                 }
349                 else if (p instanceof ProbabilityDistributionProperty)
350                 {
351                     ProbabilityDistributionProperty pdp = (ProbabilityDistributionProperty) p;
352                     String modelName = p.getKey();
353                     if (modelName.equals("TrafficComposition"))
354                     {
355                         this.carProbability = pdp.getValue()[0];
356                     }
357                     else
358                     {
359                         throw new Error("Unhandled ProbabilityDistributionProperty " + p.getKey());
360                     }
361                 }
362                 else
363                 {
364                     throw new Error("Unhandled property: " + p);
365                 }
366             }
367 
368             // 1500 [veh / hour] == 2.4s headway
369             this.headway = new Duration(3600.0 / 1500.0, SECOND);
370 
371             try
372             {
373                 // Schedule creation of the first car (this will re-schedule itself one headway later, etc.).
374                 this.simulator.scheduleEventAbs(new Time(0.0, SECOND), this, this, "generateCar", null);
375                 // Create a block at t = 5 minutes
376                 this.simulator.scheduleEventAbs(new Time(300, SECOND), this, this, "createBlock", null);
377                 // Remove the block at t = 7 minutes
378                 this.simulator.scheduleEventAbs(new Time(420, SECOND), this, this, "removeBlock", null);
379                 // Schedule regular updates of the graph
380                 for (int t = 1; t <= 1800; t++)
381                 {
382                     this.simulator.scheduleEventAbs(new Time(t - 0.001, SECOND), this, this, "drawGraphs", null);
383                 }
384             }
385             catch (SimRuntimeException exception)
386             {
387                 exception.printStackTrace();
388             }
389         }
390 
391         /**
392          * Set up the block.
393          * @throws RemoteException on communications failure
394          */
395         protected final void createBlock() throws RemoteException
396         {
397             Length initialPosition = new Length(4000, METER);
398             Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1);
399             try
400             {
401                 initialPositions.add(new DirectedLanePosition(this.getLane(), initialPosition, GTUDirectionality.DIR_PLUS));
402                 BehavioralCharacteristics behavioralCharacteristics = DefaultsFactory.getDefaultBehavioralCharacteristics();
403                 // LaneBasedBehavioralCharacteristics drivingCharacteristics =
404                 // new LaneBasedBehavioralCharacteristics(this.carFollowingModelCars, this.laneChangeModel);
405 
406                 this.block = new LaneBasedIndividualGTU("999999", this.gtuType, new Length(4, METER), new Length(1.8, METER),
407                         new Speed(0.0, KM_PER_HOUR), this.simulator, this.network);
408                 LaneBasedStrategicalPlanner strategicalPlanner = new LaneBasedStrategicalRoutePlanner(behavioralCharacteristics,
409                         new LaneBasedGTUFollowingTacticalPlanner(this.carFollowingModelCars, this.block), this.block);
410                 this.block.initWithAnimation(strategicalPlanner, initialPositions, new Speed(0.0, KM_PER_HOUR),
411                         DefaultCarAnimation.class, this.gtuColorer);
412             }
413             catch (SimRuntimeException | NamingException | NetworkException | GTUException | OTSGeometryException exception)
414             {
415                 exception.printStackTrace();
416             }
417         }
418 
419         /**
420          * Remove the block.
421          */
422         protected final void removeBlock()
423         {
424             this.block.destroy();
425             this.block = null;
426         }
427 
428         /**
429          * Generate cars at a fixed rate (implemented by re-scheduling this method).
430          */
431         protected final void generateCar()
432         {
433             boolean generateTruck = this.randomGenerator.nextDouble() > this.carProbability;
434             Length initialPosition = new Length(0, METER);
435             Speed initialSpeed = new Speed(100, KM_PER_HOUR);
436             Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1);
437             try
438             {
439                 initialPositions.add(new DirectedLanePosition(this.getLane(), initialPosition, GTUDirectionality.DIR_PLUS));
440                 Length vehicleLength = new Length(generateTruck ? 15 : 4, METER);
441                 GTUFollowingModelOld gtuFollowingModel =
442                         generateTruck ? this.carFollowingModelTrucks : this.carFollowingModelCars;
443                 if (null == gtuFollowingModel)
444                 {
445                     throw new Error("gtuFollowingModel is null");
446                 }
447                 BehavioralCharacteristics behavioralCharacteristics = DefaultsFactory.getDefaultBehavioralCharacteristics();
448                 // LaneBasedBehavioralCharacteristics drivingCharacteristics =
449                 // new LaneBasedBehavioralCharacteristics(gtuFollowingModel, this.laneChangeModel);
450 
451                 LaneBasedIndividualGTU gtu = new LaneBasedIndividualGTU("" + (++this.carsCreated), this.gtuType, vehicleLength,
452                         new Length(1.8, METER), new Speed(200, KM_PER_HOUR), this.simulator, this.network);
453                 LaneBasedStrategicalPlanner strategicalPlanner = new LaneBasedStrategicalRoutePlanner(behavioralCharacteristics,
454                         new LaneBasedGTUFollowingTacticalPlanner(gtuFollowingModel, gtu), gtu);
455                 gtu.initWithAnimation(strategicalPlanner, initialPositions, initialSpeed, DefaultCarAnimation.class,
456                         this.gtuColorer);
457 
458                 this.simulator.scheduleEventRel(this.headway, this, this, "generateCar", null);
459             }
460             catch (SimRuntimeException | NamingException | NetworkException | GTUException | OTSGeometryException exception)
461             {
462                 exception.printStackTrace();
463             }
464         }
465 
466         /**
467         * 
468         */
469         protected final void drawGraphs()
470         {
471             // Notify the Fundamental Diagram plots that the underlying data has changed
472             for (FundamentalDiagram fd : this.fundamentalDiagrams)
473             {
474                 fd.reGraph();
475             }
476         }
477 
478         /** {@inheritDoc} */
479         @Override
480         public final SimulatorInterface<Time, Duration, OTSSimTimeDouble> getSimulator() throws RemoteException
481         {
482             return this.simulator;
483         }
484 
485         /** {@inheritDoc} */
486         @Override
487         public OTSNetwork getNetwork()
488         {
489             return this.network;
490         }
491 
492         /**
493          * @return fundamentalDiagramPlots
494          */
495         public final List<FundamentalDiagram> getFundamentalDiagrams()
496         {
497             return this.fundamentalDiagrams;
498         }
499 
500         /**
501          * @return minimumDistance
502          */
503         public final Length getMinimumDistance()
504         {
505             return this.minimumDistance;
506         }
507 
508         /**
509          * @return maximumDistance
510          */
511         public final Length getMaximumDistance()
512         {
513             return this.maximumDistance;
514         }
515 
516         /**
517          * @return lane.
518          */
519         public Lane getLane()
520         {
521             return this.lane;
522         }
523     }
524 
525     /** {@inheritDoc} */
526     @Override
527     public final String toString()
528     {
529         return "FundamentalDiagrams [model=" + this.model + "]";
530     }
531 }