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