View Javadoc
1   package org.opentrafficsim.demo.carFollowing;
2   
3   import java.awt.Frame;
4   import java.awt.geom.Rectangle2D;
5   import java.rmi.RemoteException;
6   import java.util.ArrayList;
7   import java.util.HashSet;
8   import java.util.LinkedHashSet;
9   import java.util.List;
10  import java.util.Random;
11  import java.util.Set;
12  
13  import javax.naming.NamingException;
14  import javax.swing.JPanel;
15  import javax.swing.SwingUtilities;
16  
17  import nl.tudelft.simulation.dsol.SimRuntimeException;
18  import nl.tudelft.simulation.dsol.gui.swing.TablePanel;
19  import nl.tudelft.simulation.dsol.simulators.SimulatorInterface;
20  
21  import org.djunits.unit.UNITS;
22  import org.djunits.value.vdouble.scalar.Acceleration;
23  import org.djunits.value.vdouble.scalar.Duration;
24  import org.djunits.value.vdouble.scalar.Length;
25  import org.djunits.value.vdouble.scalar.Speed;
26  import org.djunits.value.vdouble.scalar.Time;
27  import org.opentrafficsim.base.modelproperties.ProbabilityDistributionProperty;
28  import org.opentrafficsim.base.modelproperties.Property;
29  import org.opentrafficsim.base.modelproperties.PropertyException;
30  import org.opentrafficsim.base.modelproperties.SelectionProperty;
31  import org.opentrafficsim.core.dsol.OTSDEVSSimulatorInterface;
32  import org.opentrafficsim.core.dsol.OTSModelInterface;
33  import org.opentrafficsim.core.dsol.OTSSimTimeDouble;
34  import org.opentrafficsim.core.geometry.OTSGeometryException;
35  import org.opentrafficsim.core.geometry.OTSPoint3D;
36  import org.opentrafficsim.core.gtu.GTUDirectionality;
37  import org.opentrafficsim.core.gtu.GTUException;
38  import org.opentrafficsim.core.gtu.GTUType;
39  import org.opentrafficsim.core.gtu.animation.GTUColorer;
40  import org.opentrafficsim.core.gtu.behavioralcharacteristics.BehavioralCharacteristics;
41  import org.opentrafficsim.core.network.LongitudinalDirectionality;
42  import org.opentrafficsim.core.network.NetworkException;
43  import org.opentrafficsim.core.network.OTSNetwork;
44  import org.opentrafficsim.core.network.OTSNode;
45  import org.opentrafficsim.graphs.FundamentalDiagram;
46  import org.opentrafficsim.road.gtu.animation.DefaultCarAnimation;
47  import org.opentrafficsim.road.gtu.lane.LaneBasedIndividualGTU;
48  import org.opentrafficsim.road.gtu.lane.tactical.LaneBasedGTUFollowingTacticalPlanner;
49  import org.opentrafficsim.road.gtu.lane.tactical.following.GTUFollowingModelOld;
50  import org.opentrafficsim.road.gtu.lane.tactical.following.IDMOld;
51  import org.opentrafficsim.road.gtu.lane.tactical.following.IDMPlusOld;
52  import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalPlanner;
53  import org.opentrafficsim.road.gtu.strategical.route.LaneBasedStrategicalRoutePlanner;
54  import org.opentrafficsim.road.network.factory.LaneFactory;
55  import org.opentrafficsim.road.network.lane.CrossSectionLink;
56  import org.opentrafficsim.road.network.lane.DirectedLanePosition;
57  import org.opentrafficsim.road.network.lane.Lane;
58  import org.opentrafficsim.road.network.lane.LaneType;
59  import org.opentrafficsim.road.network.lane.changing.OvertakingConditions;
60  import org.opentrafficsim.road.network.lane.object.sensor.Sensor;
61  import org.opentrafficsim.road.network.lane.object.sensor.SinkSensor;
62  import org.opentrafficsim.simulationengine.AbstractWrappableAnimation;
63  import org.opentrafficsim.simulationengine.OTSSimulationException;
64  import org.opentrafficsim.simulationengine.SimpleSimulatorInterface;
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: 2016-11-02 11:22:48 +0100 (Wed, 02 Nov 2016) $, @version $Revision: 2441 $, 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" }, new Double[] {
97                              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), new Duration(3600.0,
130                             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 Rectangle2D.Double makeAnimationRectangle()
151     {
152         return new Rectangle2D.Double(0, -100, 5000, 200);
153     }
154 
155     /** {@inheritDoc} */
156     @Override
157     protected final JPanel makeCharts(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 =
168                         new FundamentalDiagram("Fundamental Diagram at " + detectorLocation.getSI() + "m", new Duration(1,
169                                 MINUTE), this.model.getLane(), detectorLocation, simulator);
170                 fd.setTitle("Density Contour Graph");
171                 fd.setExtendedState(Frame.MAXIMIZED_BOTH);
172                 this.model.getFundamentalDiagrams().add(fd);
173                 charts.setCell(fd.getContentPane(), plotNumber / panelsPerRow, plotNumber % panelsPerRow);
174             }
175             catch (NetworkException exception)
176             {
177                 exception.printStackTrace();
178             }
179         }
180         return charts;
181     }
182 
183     /** {@inheritDoc} */
184     @Override
185     public final String shortName()
186     {
187         return "Fundamental Diagrams";
188     }
189 
190     /** {@inheritDoc} */
191     @Override
192     public final String description()
193     {
194         return "<html><h1>Fundamental Diagram Plots</H1>"
195                 + "Simulation of a single lane road of 5 km length. Vechicles are generated at a constant rate of "
196                 + "1500 veh/hour. At time 300s a blockade is inserted at position 4km; this blockade is removed at time "
197                 + "500s. This blockade simulates a bridge opening.<br>"
198                 + "The blockade causes a traffic jam that slowly dissolves after the blockade is removed.<br>"
199                 + "Output is a set of Diagrams that plot observed density, flow and speed plots against each other.</html>";
200     }
201 
202     /**
203      * Simulate a single lane road of 5 km length. Vehicles are generated at a constant rate of 1500 veh/hour. At time 300s a
204      * blockade is inserted at position 4 km; this blockade is removed at time 500s. The used car following algorithm is IDM+ <a
205      * href="http://opentrafficsim.org/downloads/MOTUS%20reference.pdf"><i>Integrated Lane Change Model with Relaxation and
206      * Synchronization</i>, by Wouter J. Schakel, Victor L. Knoop and Bart van Arem, 2012</a>. <br>
207      * Output is a set of FundamentalDiagram plots for various point along the lane.
208      * <p>
209      * Copyright (c) 2013-2016 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
210      * BSD-style license. See <a href="http://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
211      * <p>
212      * $LastChangedDate: 2016-11-02 11:22:48 +0100 (Wed, 02 Nov 2016) $, @version $Revision: 2441 $, 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 = new 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 =
297                         LaneFactory.makeLane(this.network, "Lane", from, to, null, laneType, this.speedLimit, this.simulator,
298                                 LongitudinalDirectionality.DIR_PLUS);
299                 CrossSectionLink endLink =
300                         LaneFactory.makeLink(this.network, "endLink", to, end, null, LongitudinalDirectionality.DIR_PLUS);
301                 // No overtaking, single lane
302                 Lane sinkLane =
303                         new Lane(endLink, "sinkLane", this.lane.getLateralCenterPosition(1.0),
304                                 this.lane.getLateralCenterPosition(1.0), this.lane.getWidth(1.0), this.lane.getWidth(1.0),
305                                 laneType, LongitudinalDirectionality.DIR_PLUS, this.speedLimit, new OvertakingConditions.None());
306                 Sensor sensor = new SinkSensor(sinkLane, new Length(10.0, METER), this.simulator);
307                 sinkLane.addSensor(sensor, GTUType.ALL);
308             }
309             catch (NamingException | NetworkException | OTSGeometryException exception)
310             {
311                 exception.printStackTrace();
312             }
313 
314             // create SinkLane
315 
316             for (Property<?> p : this.fundamentalDiagramProperties)
317             {
318                 if (p instanceof SelectionProperty)
319                 {
320                     SelectionProperty sp = (SelectionProperty) p;
321                     if ("CarFollowingModel".equals(sp.getKey()))
322                     {
323                         String modelName = sp.getValue();
324                         if (modelName.equals("IDM"))
325                         {
326                             this.carFollowingModelCars =
327                                     new IDMOld(new Acceleration(1, METER_PER_SECOND_2), new Acceleration(1.5,
328                                             METER_PER_SECOND_2), new Length(2, METER), new Duration(1, SECOND), 1d);
329                             this.carFollowingModelTrucks =
330                                     new IDMOld(new Acceleration(0.5, METER_PER_SECOND_2), new Acceleration(1.5,
331                                             METER_PER_SECOND_2), new Length(2, METER), new Duration(1, SECOND), 1d);
332                         }
333                         else if (modelName.equals("IDM+"))
334                         {
335                             this.carFollowingModelCars =
336                                     new IDMPlusOld(new Acceleration(1, METER_PER_SECOND_2), new Acceleration(1.5,
337                                             METER_PER_SECOND_2), new Length(2, METER), new Duration(1, SECOND), 1d);
338                             this.carFollowingModelTrucks =
339                                     new IDMPlusOld(new Acceleration(0.5, METER_PER_SECOND_2), new Acceleration(1.5,
340                                             METER_PER_SECOND_2), new Length(2, METER), new Duration(1, SECOND), 1d);
341                         }
342                         else
343                         {
344                             throw new Error("Car following model " + modelName + " not implemented");
345                         }
346                     }
347                     else
348                     {
349                         throw new Error("Unhandled SelectionProperty " + p.getKey());
350                     }
351                 }
352                 else if (p instanceof ProbabilityDistributionProperty)
353                 {
354                     ProbabilityDistributionProperty pdp = (ProbabilityDistributionProperty) p;
355                     String modelName = p.getKey();
356                     if (modelName.equals("TrafficComposition"))
357                     {
358                         this.carProbability = pdp.getValue()[0];
359                     }
360                     else
361                     {
362                         throw new Error("Unhandled ProbabilityDistributionProperty " + p.getKey());
363                     }
364                 }
365                 else
366                 {
367                     throw new Error("Unhandled property: " + p);
368                 }
369             }
370 
371             // 1500 [veh / hour] == 2.4s headway
372             this.headway = new Duration(3600.0 / 1500.0, SECOND);
373 
374             try
375             {
376                 // Schedule creation of the first car (this will re-schedule itself one headway later, etc.).
377                 this.simulator.scheduleEventAbs(new Time(0.0, SECOND), this, this, "generateCar", null);
378                 // Create a block at t = 5 minutes
379                 this.simulator.scheduleEventAbs(new Time(300, SECOND), this, this, "createBlock", null);
380                 // Remove the block at t = 7 minutes
381                 this.simulator.scheduleEventAbs(new Time(420, SECOND), this, this, "removeBlock", null);
382                 // Schedule regular updates of the graph
383                 for (int t = 1; t <= 1800; t++)
384                 {
385                     this.simulator.scheduleEventAbs(new Time(t - 0.001, SECOND), this, this, "drawGraphs", null);
386                 }
387             }
388             catch (SimRuntimeException exception)
389             {
390                 exception.printStackTrace();
391             }
392         }
393 
394         /**
395          * Set up the block.
396          * @throws RemoteException on communications failure
397          */
398         protected final void createBlock() throws RemoteException
399         {
400             Length initialPosition = new Length(4000, METER);
401             Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1);
402             try
403             {
404                 initialPositions.add(new DirectedLanePosition(this.getLane(), initialPosition, GTUDirectionality.DIR_PLUS));
405                 BehavioralCharacteristics behavioralCharacteristics = DefaultsFactory.getDefaultBehavioralCharacteristics();
406                 // LaneBasedBehavioralCharacteristics drivingCharacteristics =
407                 // new LaneBasedBehavioralCharacteristics(this.carFollowingModelCars, this.laneChangeModel);
408 
409                 this.block =
410                         new LaneBasedIndividualGTU("999999", this.gtuType, new Length(4, METER), new Length(1.8, METER),
411                                 new Speed(0.0, KM_PER_HOUR), this.simulator, this.network);
412                 LaneBasedStrategicalPlanner strategicalPlanner =
413                         new LaneBasedStrategicalRoutePlanner(behavioralCharacteristics,
414                                 new LaneBasedGTUFollowingTacticalPlanner(this.carFollowingModelCars, this.block), this.block);
415                 this.block.initWithAnimation(strategicalPlanner, initialPositions, new Speed(0.0, KM_PER_HOUR),
416                         DefaultCarAnimation.class, this.gtuColorer);
417             }
418             catch (SimRuntimeException | NamingException | NetworkException | GTUException | OTSGeometryException exception)
419             {
420                 exception.printStackTrace();
421             }
422         }
423 
424         /**
425          * Remove the block.
426          */
427         protected final void removeBlock()
428         {
429             this.block.destroy();
430             this.block = null;
431         }
432 
433         /**
434          * Generate cars at a fixed rate (implemented by re-scheduling this method).
435          */
436         protected final void generateCar()
437         {
438             boolean generateTruck = this.randomGenerator.nextDouble() > this.carProbability;
439             Length initialPosition = new Length(0, METER);
440             Speed initialSpeed = new Speed(100, KM_PER_HOUR);
441             Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1);
442             try
443             {
444                 initialPositions.add(new DirectedLanePosition(this.getLane(), initialPosition, GTUDirectionality.DIR_PLUS));
445                 Length vehicleLength = new Length(generateTruck ? 15 : 4, METER);
446                 GTUFollowingModelOld gtuFollowingModel =
447                         generateTruck ? this.carFollowingModelTrucks : this.carFollowingModelCars;
448                 if (null == gtuFollowingModel)
449                 {
450                     throw new Error("gtuFollowingModel is null");
451                 }
452                 BehavioralCharacteristics behavioralCharacteristics = DefaultsFactory.getDefaultBehavioralCharacteristics();
453                 // LaneBasedBehavioralCharacteristics drivingCharacteristics =
454                 // new LaneBasedBehavioralCharacteristics(gtuFollowingModel, this.laneChangeModel);
455 
456                 LaneBasedIndividualGTU gtu =
457                         new LaneBasedIndividualGTU("" + (++this.carsCreated), this.gtuType, vehicleLength, new Length(1.8,
458                                 METER), new Speed(200, KM_PER_HOUR), this.simulator, this.network);
459                 LaneBasedStrategicalPlanner strategicalPlanner =
460                         new LaneBasedStrategicalRoutePlanner(behavioralCharacteristics,
461                                 new LaneBasedGTUFollowingTacticalPlanner(gtuFollowingModel, gtu), gtu);
462                 gtu.initWithAnimation(strategicalPlanner, initialPositions, initialSpeed, DefaultCarAnimation.class,
463                         this.gtuColorer);
464 
465                 this.simulator.scheduleEventRel(this.headway, this, this, "generateCar", null);
466             }
467             catch (SimRuntimeException | NamingException | NetworkException | GTUException | OTSGeometryException exception)
468             {
469                 exception.printStackTrace();
470             }
471         }
472 
473         /**
474         * 
475         */
476         protected final void drawGraphs()
477         {
478             // Notify the Fundamental Diagram plots that the underlying data has changed
479             for (FundamentalDiagram fd : this.fundamentalDiagrams)
480             {
481                 fd.reGraph();
482             }
483         }
484 
485         /** {@inheritDoc} */
486         @Override
487         public final SimulatorInterface<Time, Duration, OTSSimTimeDouble> getSimulator() throws RemoteException
488         {
489             return null;
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 }