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.TimeUnit;
22  import org.djunits.unit.UNITS;
23  import org.djunits.value.vdouble.scalar.Acceleration;
24  import org.djunits.value.vdouble.scalar.DoubleScalar;
25  import org.djunits.value.vdouble.scalar.Duration;
26  import org.djunits.value.vdouble.scalar.Length;
27  import org.djunits.value.vdouble.scalar.Speed;
28  import org.djunits.value.vdouble.scalar.Time;
29  import org.opentrafficsim.core.dsol.OTSDEVSSimulatorInterface;
30  import org.opentrafficsim.core.dsol.OTSModelInterface;
31  import org.opentrafficsim.core.dsol.OTSSimTimeDouble;
32  import org.opentrafficsim.core.geometry.OTSGeometryException;
33  import org.opentrafficsim.core.geometry.OTSPoint3D;
34  import org.opentrafficsim.core.gtu.GTUDirectionality;
35  import org.opentrafficsim.core.gtu.GTUException;
36  import org.opentrafficsim.core.gtu.GTUType;
37  import org.opentrafficsim.core.gtu.animation.GTUColorer;
38  import org.opentrafficsim.core.gtu.behavioralcharacteristics.BehavioralCharacteristics;
39  import org.opentrafficsim.core.network.LongitudinalDirectionality;
40  import org.opentrafficsim.core.network.NetworkException;
41  import org.opentrafficsim.core.network.OTSNetwork;
42  import org.opentrafficsim.core.network.OTSNode;
43  import org.opentrafficsim.graphs.TrajectoryPlot;
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.Sensor;
58  import org.opentrafficsim.road.network.lane.SinkSensor;
59  import org.opentrafficsim.road.network.lane.changing.OvertakingConditions;
60  import org.opentrafficsim.simulationengine.AbstractWrappableAnimation;
61  import org.opentrafficsim.simulationengine.OTSSimulationException;
62  import org.opentrafficsim.simulationengine.properties.AbstractProperty;
63  import org.opentrafficsim.simulationengine.properties.ProbabilityDistributionProperty;
64  import org.opentrafficsim.simulationengine.properties.PropertyException;
65  import org.opentrafficsim.simulationengine.properties.SelectionProperty;
66  
67  /**
68   * Demonstrate the Trajectories plot.
69   * <p>
70   * Copyright (c) 2013-2016 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: 2016-08-04 17:07:01 +0200 (Thu, 04 Aug 2016) $, @version $Revision: 2124 $, by $Author: wjschakel $,
74   * initial version 17 dec. 2014 <br>
75   * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
76   */
77  public class Trajectories extends AbstractWrappableAnimation implements UNITS
78  {
79      /** */
80      private static final long serialVersionUID = 1L;
81  
82      /** The model. */
83      private TrajectoriesModel model;
84  
85      /** Create a Trajectories simulation. */
86      public Trajectories()
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>", new String[] {"IDM", "IDM+"}, 1,
95                  false, 10));
96              this.properties.add(new ProbabilityDistributionProperty("TrafficComposition", "Traffic composition",
97                  "<html>Mix of passenger cars and trucks</html>", new String[] {"passenger car", "truck"}, new Double[] {0.8,
98                      0.2}, false, 9));
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                     Trajectories trajectories = new Trajectories();
130                     trajectories.buildAnimator(new Time(0.0, SECOND), new Duration(0.0, SECOND),
131                         new Duration(3600.0, SECOND), trajectories.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 Rectangle2D.Double makeAnimationRectangle()
144     {
145         return new Rectangle2D.Double(0, -100, 5000, 200);
146     }
147 
148     /** {@inheritDoc} */
149     @Override
150     protected final OTSModelInterface makeModel(final GTUColorer colorer)
151     {
152         this.model = new TrajectoriesModel(this.savedUserModifiedProperties, colorer);
153         return this.model;
154     }
155 
156     /** {@inheritDoc} */
157     @Override
158     protected final JPanel makeCharts() throws OTSSimulationException
159     {
160         TablePanel charts = new TablePanel(1, 1);
161         Duration sampleInterval = new Duration(0.5, SECOND);
162         List<Lane> path = new ArrayList<>();
163         path.add(this.model.getLane());
164         TrajectoryPlot tp = new TrajectoryPlot("Trajectory Plot", sampleInterval, path);
165         tp.setTitle("Density Contour Graph");
166         tp.setExtendedState(Frame.MAXIMIZED_BOTH);
167         this.model.setTrajectoryPlot(tp);
168         charts.setCell(tp.getContentPane(), 0, 0);
169         return charts;
170     }
171 
172     /** {@inheritDoc} */
173     @Override
174     public final String shortName()
175     {
176         return "Trajectory plot";
177     }
178 
179     /** {@inheritDoc} */
180     @Override
181     public final String description()
182     {
183         return "<html><H1>Trajectories</H1>"
184             + "Simulation of a single lane road of 5 km length. Vechicles are generated at a constant rate of "
185             + "1500 veh/hour. At time 300s a blockade is inserted at position 4km; this blockade is removed at time "
186             + "420s. This blockade simulates a bridge opening.<br>"
187             + "The blockade causes a traffic jam that slowly dissolves after the blockade is removed.<br>"
188             + "Output is a Trajectory plots.</html>";
189     }
190 
191 }
192 
193 /**
194  * Simulate a single lane road of 5 km length. Vehicles are generated at a constant rate of 1500 veh/hour. At time 300s a
195  * blockade is inserted at position 4 km; this blockade is removed at time 500s. The used car following algorithm is IDM+ <a
196  * href="http://opentrafficsim.org/downloads/MOTUS%20reference.pdf"><i>Integrated Lane Change Model with Relaxation and
197  * Synchronization</i>, by Wouter J. Schakel, Victor L. Knoop and Bart van Arem, 2012</a>. <br>
198  * Output is a trajectory plot with simulation time along the horizontal axis and distance along the road along the vertical
199  * axis.
200  * <p>
201  * Copyright (c) 2013-2016 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
202  * BSD-style license. See <a href="http://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
203  * <p>
204  * $LastChangedDate: 2016-08-04 17:07:01 +0200 (Thu, 04 Aug 2016) $, @version $Revision: 2124 $, by $Author: wjschakel $,
205  * initial version ug 1, 2014 <br>
206  * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
207  */
208 class TrajectoriesModel implements OTSModelInterface, UNITS
209 {
210     /** */
211     private static final long serialVersionUID = 20140815L;
212 
213     /** The simulator. */
214     private OTSDEVSSimulatorInterface simulator;
215 
216     /** The network. */
217     private OTSNetwork network = new OTSNetwork("network");
218 
219     /** The headway (inter-vehicle time). */
220     private Duration headway;
221 
222     /** Number of cars created. */
223     private int carsCreated = 0;
224 
225     /** Type of all GTUs. */
226     private GTUType gtuType = new GTUType("Car");
227 
228     /** The car following model, e.g. IDM Plus for cars. */
229     private GTUFollowingModelOld carFollowingModelCars;
230 
231     /** The car following model, e.g. IDM Plus for trucks. */
232     private GTUFollowingModelOld carFollowingModelTrucks;
233 
234     /** The probability that the next generated GTU is a passenger car. */
235     private double carProbability;
236 
237     /** The blocking car. */
238     private LaneBasedIndividualGTU block = null;
239 
240     /** Minimum distance. */
241     private Length minimumDistance = new Length(0, METER);
242 
243     /** Maximum distance. */
244     private Length maximumDistance = new Length(5000, METER);
245 
246     /** The Lane containing the simulated Cars. */
247     private Lane lane;
248 
249     /** The speed limit. */
250     private Speed speedLimit = new Speed(100, KM_PER_HOUR);
251 
252     /** The trajectory plot. */
253     private TrajectoryPlot trajectoryPlot;
254 
255     /** User settable properties. */
256     private ArrayList<AbstractProperty<?>> properties = null;
257 
258     /** The random number generator used to decide what kind of GTU to generate. */
259     private Random randomGenerator = new Random(12345);
260 
261     /** The GTUColorer for the generated vehicles. */
262     private final GTUColorer gtuColorer;
263 
264     /**
265      * @param properties ArrayList&lt;AbstractProperty&lt;?&gt;&gt;; the properties
266      * @param gtuColorer the default and initial GTUColorer, e.g. a DefaultSwitchableTUColorer.
267      */
268     public TrajectoriesModel(final ArrayList<AbstractProperty<?>> properties, final GTUColorer gtuColorer)
269     {
270         this.properties = properties;
271         this.gtuColorer = gtuColorer;
272     }
273 
274     /** {@inheritDoc} */
275     @Override
276     public final void constructModel(
277         final SimulatorInterface<DoubleScalar.Abs<TimeUnit>, DoubleScalar.Rel<TimeUnit>, OTSSimTimeDouble> theSimulator)
278         throws SimRuntimeException, RemoteException
279     {
280         this.simulator = (OTSDEVSSimulatorInterface) theSimulator;
281         OTSNode from = new OTSNode("From", new OTSPoint3D(getMinimumDistance().getSI(), 0, 0));
282         OTSNode to = new OTSNode("To", new OTSPoint3D(getMaximumDistance().getSI(), 0, 0));
283         OTSNode end = new OTSNode("End", new OTSPoint3D(getMaximumDistance().getSI() + 50.0, 0, 0));
284         Set<GTUType> compatibility = new HashSet<>();
285         compatibility.add(this.gtuType);
286         LaneType laneType = new LaneType("CarLane", compatibility);
287         try
288         {
289             this.lane =
290                 LaneFactory.makeLane("Lane", from, to, null, laneType, this.speedLimit, this.simulator,
291                     LongitudinalDirectionality.DIR_PLUS);
292             CrossSectionLink endLink = LaneFactory.makeLink("endLink", to, end, null, LongitudinalDirectionality.DIR_PLUS);
293             // No overtaking, single (sink) lane
294             Lane sinkLane =
295                 new Lane(endLink, "sinkLane", this.lane.getLateralCenterPosition(1.0), this.lane
296                     .getLateralCenterPosition(1.0), this.lane.getWidth(1.0), this.lane.getWidth(1.0), laneType,
297                     LongitudinalDirectionality.DIR_PLUS, this.speedLimit, new OvertakingConditions.None());
298             Sensor sensor = new SinkSensor(sinkLane, new Length(10.0, METER), this.simulator);
299             sinkLane.addSensor(sensor, GTUType.ALL);
300         }
301         catch (NamingException | NetworkException | OTSGeometryException exception1)
302         {
303             exception1.printStackTrace();
304         }
305 
306         for (AbstractProperty<?> p : this.properties)
307         {
308             if (p instanceof SelectionProperty)
309             {
310                 SelectionProperty sp = (SelectionProperty) p;
311                 if ("CarFollowingModel".equals(sp.getKey()))
312                 {
313                     String modelName = sp.getValue();
314                     if (modelName.equals("IDM"))
315                     {
316                         this.carFollowingModelCars =
317                             new IDMOld(new Acceleration(1, METER_PER_SECOND_2), new Acceleration(1.5, METER_PER_SECOND_2),
318                                 new Length(2, METER), new Duration(1, SECOND), 1d);
319                         this.carFollowingModelTrucks =
320                             new IDMOld(new Acceleration(0.5, METER_PER_SECOND_2), new Acceleration(1.5, METER_PER_SECOND_2),
321                                 new Length(2, METER), new Duration(1, SECOND), 1d);
322                     }
323                     else if (modelName.equals("IDM+"))
324                     {
325                         this.carFollowingModelCars =
326                             new IDMPlusOld(new Acceleration(1, METER_PER_SECOND_2),
327                                 new Acceleration(1.5, METER_PER_SECOND_2), new Length(2, METER), new Duration(1, SECOND), 1d);
328                         this.carFollowingModelTrucks =
329                             new IDMPlusOld(new Acceleration(0.5, METER_PER_SECOND_2), new Acceleration(1.5,
330                                 METER_PER_SECOND_2), new Length(2, METER), new Duration(1, SECOND), 1d);
331                     }
332                     else
333                     {
334                         throw new Error("Car following model " + modelName + " not implemented");
335                     }
336                 }
337                 else
338                 {
339                     throw new Error("Unhandled SelectionProperty " + p.getKey());
340                 }
341             }
342             else if (p instanceof ProbabilityDistributionProperty)
343             {
344                 ProbabilityDistributionProperty pdp = (ProbabilityDistributionProperty) p;
345                 String modelName = p.getKey();
346                 if (modelName.equals("TrafficComposition"))
347                 {
348                     this.carProbability = pdp.getValue()[0];
349                 }
350                 else
351                 {
352                     throw new Error("Unhandled ProbabilityDistributionProperty " + p.getKey());
353                 }
354             }
355             else
356             {
357                 throw new Error("Unhandled property: " + p);
358             }
359         }
360 
361         // 1500 [vehicles / hour] == 2.4s headway
362         this.headway = new Duration(3600.0 / 1500.0, SECOND);
363 
364         try
365         {
366             // Schedule creation of the first car (this will re-schedule itself one headway later, etc.).
367             this.simulator.scheduleEventAbs(new DoubleScalar.Abs<>(0.0, SECOND), this, this, "generateCar", null);
368             // Create a block at t = 5 minutes
369             this.simulator.scheduleEventAbs(new DoubleScalar.Abs<>(300, SECOND), this, this, "createBlock", null);
370             // Remove the block at t = 7 minutes
371             this.simulator.scheduleEventAbs(new DoubleScalar.Abs<>(420, SECOND), this, this, "removeBlock", null);
372             // Schedule regular updates of the graph
373             for (int t = 1; t <= 1800; t++)
374             {
375                 this.simulator.scheduleEventAbs(new DoubleScalar.Abs<>(t - 0.001, SECOND), this, this, "drawGraph",
376                     null);
377             }
378         }
379         catch (SimRuntimeException exception)
380         {
381             exception.printStackTrace();
382         }
383     }
384 
385     /**
386      * Set up the block.
387      * @throws NamingException on error during adding of animation handler
388      * @throws SimRuntimeException on ???
389      * @throws NetworkException on network inconsistency
390      * @throws GTUException if creation of the GTU fails
391      * @throws OTSGeometryException when the initial position is not on the cecnter line of the lane
392      */
393     protected final void createBlock() throws NamingException, SimRuntimeException, NetworkException, GTUException,
394         OTSGeometryException
395     {
396         Length initialPosition = new Length(4000, METER);
397         Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1);
398         initialPositions.add(new DirectedLanePosition(this.getLane(), initialPosition, GTUDirectionality.DIR_PLUS));
399         BehavioralCharacteristics behavioralCharacteristics = DefaultsFactory.getDefaultBehavioralCharacteristics();
400         this.block =
401             new LaneBasedIndividualGTU("999999", this.gtuType, new Length(4, METER), new Length(1.8, METER), new Speed(0.0,
402                 KM_PER_HOUR), this.simulator, DefaultCarAnimation.class, this.gtuColorer, this.network);
403         LaneBasedStrategicalPlanner strategicalPlanner =
404             new LaneBasedStrategicalRoutePlanner(behavioralCharacteristics, new LaneBasedGTUFollowingTacticalPlanner(
405                 this.carFollowingModelCars, this.block), this.block);
406         this.block.init(strategicalPlanner, initialPositions, new Speed(0.0, KM_PER_HOUR));
407     }
408 
409     /**
410      * Remove the block.
411      */
412     protected final void removeBlock()
413     {
414         this.block.destroy();
415         this.block = null;
416     }
417 
418     /**
419      * Generate cars at a fixed rate (implemented by re-scheduling this method).
420      */
421     protected final void generateCar()
422     {
423         boolean generateTruck = this.randomGenerator.nextDouble() > this.carProbability;
424         Length initialPosition = new Length(0, METER);
425         Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1);
426         try
427         {
428             initialPositions.add(new DirectedLanePosition(this.getLane(), initialPosition, GTUDirectionality.DIR_PLUS));
429             Speed initialSpeed = new Speed(100, KM_PER_HOUR);
430             Length vehicleLength = new Length(generateTruck ? 15 : 4, METER);
431             GTUFollowingModelOld gtuFollowingModel =
432                 generateTruck ? this.carFollowingModelTrucks : this.carFollowingModelCars;
433             if (null == gtuFollowingModel)
434             {
435                 throw new Error("gtuFollowingModel is null");
436             }
437             BehavioralCharacteristics behavioralCharacteristics = DefaultsFactory.getDefaultBehavioralCharacteristics();
438             LaneBasedIndividualGTU gtu =
439                 new LaneBasedIndividualGTU("" + (++this.carsCreated), this.gtuType, vehicleLength, new Length(1.8, METER),
440                     new Speed(200, KM_PER_HOUR), this.simulator, DefaultCarAnimation.class, this.gtuColorer, this.network);
441             LaneBasedStrategicalPlanner strategicalPlanner =
442                 new LaneBasedStrategicalRoutePlanner(behavioralCharacteristics, new LaneBasedGTUFollowingTacticalPlanner(
443                     gtuFollowingModel, gtu), gtu);
444             gtu.init(strategicalPlanner, initialPositions, initialSpeed);
445             // Re-schedule this method after headway seconds
446             this.simulator.scheduleEventRel(this.headway, this, this, "generateCar", null);
447         }
448         catch (SimRuntimeException | NamingException | NetworkException | GTUException | OTSGeometryException exception)
449         {
450             exception.printStackTrace();
451         }
452     }
453 
454     /** {@inheritDoc} */
455     @Override
456     public final SimulatorInterface<DoubleScalar.Abs<TimeUnit>, DoubleScalar.Rel<TimeUnit>, OTSSimTimeDouble> getSimulator()
457         throws RemoteException
458     {
459         return this.simulator;
460     }
461 
462     /**
463      * Notify the contour plots that the underlying data has changed.
464      */
465     protected final void drawGraph()
466     {
467         this.trajectoryPlot.reGraph();
468     }
469 
470     /**
471      * @return minimum distance of the simulation
472      */
473     public final Length getMinimumDistance()
474     {
475         return this.minimumDistance;
476     }
477 
478     /**
479      * @return maximum distance of the simulation
480      */
481     public final Length getMaximumDistance()
482     {
483         return this.maximumDistance;
484     }
485 
486     /**
487      * @param trajectoryPlot TrajectoryPlot
488      */
489     public final void setTrajectoryPlot(final TrajectoryPlot trajectoryPlot)
490     {
491         this.trajectoryPlot = trajectoryPlot;
492     }
493 
494     /**
495      * @return lane.
496      */
497     public Lane getLane()
498     {
499         return this.lane;
500     }
501 
502 }