View Javadoc
1   package org.opentrafficsim.demo.carFollowing;
2   
3   import static org.opentrafficsim.core.gtu.GTUType.CAR;
4   
5   import java.awt.Container;
6   import java.awt.Frame;
7   import java.util.ArrayList;
8   import java.util.LinkedHashSet;
9   import java.util.List;
10  import java.util.Set;
11  
12  import javax.naming.NamingException;
13  
14  import org.djunits.unit.DurationUnit;
15  import org.djunits.unit.LengthUnit;
16  import org.djunits.unit.SpeedUnit;
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.DoubleScalar;
21  import org.djunits.value.vdouble.scalar.Duration;
22  import org.djunits.value.vdouble.scalar.Length;
23  import org.djunits.value.vdouble.scalar.Speed;
24  import org.djunits.value.vdouble.scalar.Time;
25  import org.opentrafficsim.base.modelproperties.CompoundProperty;
26  import org.opentrafficsim.base.modelproperties.ContinuousProperty;
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.base.parameters.ParameterException;
32  import org.opentrafficsim.core.distributions.Distribution;
33  import org.opentrafficsim.core.distributions.Distribution.FrequencyAndObject;
34  import org.opentrafficsim.core.distributions.Generator;
35  import org.opentrafficsim.core.distributions.ProbabilityException;
36  import org.opentrafficsim.core.dsol.OTSModelInterface;
37  import org.opentrafficsim.core.geometry.OTSGeometryException;
38  import org.opentrafficsim.core.geometry.OTSPoint3D;
39  import org.opentrafficsim.core.gtu.GTUDirectionality;
40  import org.opentrafficsim.core.gtu.GTUException;
41  import org.opentrafficsim.core.gtu.GTUType;
42  import org.opentrafficsim.core.idgenerator.IdGenerator;
43  import org.opentrafficsim.core.network.NetworkException;
44  import org.opentrafficsim.core.network.Node;
45  import org.opentrafficsim.core.network.OTSNetwork;
46  import org.opentrafficsim.core.network.OTSNode;
47  import org.opentrafficsim.core.network.route.FixedRouteGenerator;
48  import org.opentrafficsim.core.network.route.ProbabilisticRouteGenerator;
49  import org.opentrafficsim.core.network.route.Route;
50  import org.opentrafficsim.core.network.route.RouteGenerator;
51  import org.opentrafficsim.core.units.distributions.ContinuousDistDoubleScalar;
52  import org.opentrafficsim.graphs.LaneBasedGTUSampler;
53  import org.opentrafficsim.graphs.TrajectoryPlot;
54  import org.opentrafficsim.road.animation.AnimationToggles;
55  import org.opentrafficsim.road.gtu.generator.CFRoomChecker;
56  import org.opentrafficsim.road.gtu.generator.GeneratorPositions;
57  import org.opentrafficsim.road.gtu.generator.LaneBasedGTUGenerator;
58  import org.opentrafficsim.road.gtu.generator.characteristics.LaneBasedTemplateGTUType;
59  import org.opentrafficsim.road.gtu.generator.characteristics.LaneBasedTemplateGTUTypeDistribution;
60  import org.opentrafficsim.road.gtu.lane.tactical.LaneBasedCFLCTacticalPlannerFactory;
61  import org.opentrafficsim.road.gtu.lane.tactical.LaneBasedGTUFollowingDirectedChangeTacticalPlannerFactory;
62  import org.opentrafficsim.road.gtu.lane.tactical.LaneBasedGTUFollowingTacticalPlannerFactory;
63  import org.opentrafficsim.road.gtu.lane.tactical.following.GTUFollowingModelOld;
64  import org.opentrafficsim.road.gtu.lane.tactical.following.IDMOld;
65  import org.opentrafficsim.road.gtu.lane.tactical.following.IDMPlusFactory;
66  import org.opentrafficsim.road.gtu.lane.tactical.following.IDMPlusOld;
67  import org.opentrafficsim.road.gtu.lane.tactical.lanechangemobil.AbstractLaneChangeModel;
68  import org.opentrafficsim.road.gtu.lane.tactical.lanechangemobil.Altruistic;
69  import org.opentrafficsim.road.gtu.lane.tactical.lanechangemobil.Egoistic;
70  import org.opentrafficsim.road.gtu.lane.tactical.lmrs.DefaultLMRSPerceptionFactory;
71  import org.opentrafficsim.road.gtu.lane.tactical.lmrs.LMRSFactory;
72  import org.opentrafficsim.road.gtu.lane.tactical.toledo.ToledoFactory;
73  import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalPlanner;
74  import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalPlannerFactory;
75  import org.opentrafficsim.road.gtu.strategical.route.LaneBasedStrategicalRoutePlannerFactory;
76  import org.opentrafficsim.road.modelproperties.IDMPropertySet;
77  import org.opentrafficsim.road.network.factory.LaneFactory;
78  import org.opentrafficsim.road.network.lane.CrossSectionLink;
79  import org.opentrafficsim.road.network.lane.DirectedLanePosition;
80  import org.opentrafficsim.road.network.lane.Lane;
81  import org.opentrafficsim.road.network.lane.LaneType;
82  import org.opentrafficsim.road.network.lane.changing.OvertakingConditions;
83  import org.opentrafficsim.road.network.lane.object.sensor.SinkSensor;
84  import org.opentrafficsim.simulationengine.AbstractWrappableAnimation;
85  import org.opentrafficsim.simulationengine.SimpleSimulatorInterface;
86  
87  import nl.tudelft.simulation.dsol.SimRuntimeException;
88  import nl.tudelft.simulation.dsol.gui.swing.TablePanel;
89  import nl.tudelft.simulation.dsol.simtime.SimTimeDoubleUnit;
90  import nl.tudelft.simulation.dsol.simulators.DEVSSimulatorInterface;
91  import nl.tudelft.simulation.dsol.simulators.SimulatorInterface;
92  import nl.tudelft.simulation.jstats.distributions.DistContinuous;
93  import nl.tudelft.simulation.jstats.distributions.DistErlang;
94  import nl.tudelft.simulation.jstats.distributions.DistUniform;
95  import nl.tudelft.simulation.jstats.streams.MersenneTwister;
96  import nl.tudelft.simulation.jstats.streams.StreamInterface;
97  
98  /**
99   * <p>
100  * Copyright (c) 2013-2018 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
101  * BSD-style license. See <a href="http://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
102  * <p>
103  * $LastChangedDate: 2018-09-20 17:32:03 +0200 (Thu, 20 Sep 2018) $, @version $Revision: 4174 $, by $Author: wjschakel $,
104  * initial version 4 mrt. 2015 <br>
105  * @author <a href="http://Hansvanlint.weblog.tudelft.nl">Hans van Lint</a>
106  * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
107  */
108 public class XMLNetworks extends AbstractWrappableAnimation implements UNITS
109 {
110     /** */
111     private static final long serialVersionUID = 20160422L;
112 
113     /** The model. */
114     private XMLNetworkModel model;
115 
116     /**
117      * Define the XMLNetworks.
118      */
119     public XMLNetworks()
120     {
121         this.properties.add(new SelectionProperty(
122                 "Network", "Network", "Network", new String[] { "Merge 1 plus 1 into 1", "Merge 2 plus 1 into 2",
123                         "Merge 2 plus 2 into 4", "Split 1 into 1 plus 1", "Split 2 into 1 plus 2", "Split 4 into 2 plus 2" },
124                 0, false, 0));
125         this.properties.add(new SelectionProperty("TacticalPlanner", "Tactical planner",
126                 "<html>The tactical planner determines if a lane change is desired and possible.</html>",
127                 new String[] { "MOBIL/IDM", "DIRECTED/IDM", "LMRS", "Toledo" }, 0, false, 600));
128         this.properties.add(new SelectionProperty("LaneChanging", "Lane changing",
129                 "<html>The lane change friendliness (if used -- eg just for MOBIL.</html>",
130                 new String[] { "Egoistic", "Altruistic" }, 0, false, 600));
131         this.properties.add(new ContinuousProperty("FlowPerInputLane", "Flow per input lane", "Traffic flow per input lane",
132                 500d, 0d, 3000d, "%.0f veh/h", false, 1));
133     }
134 
135     /** {@inheritDoc} */
136     @Override
137     public final void stopTimersThreads()
138     {
139         super.stopTimersThreads();
140         this.model = null;
141     }
142 
143     /** {@inheritDoc} */
144     @Override
145     protected final void addAnimationToggles()
146     {
147         AnimationToggles.setTextAnimationTogglesStandard(this);
148     }
149 
150     /** {@inheritDoc} */
151     @Override
152     protected final OTSModelInterface makeModel()
153     {
154         this.model = new XMLNetworkModel(this.savedUserModifiedProperties);
155         return this.model;
156     }
157 
158     /** {@inheritDoc} */
159     @Override
160     protected final void addTabs(final SimpleSimulatorInterface simulator)
161     {
162         int graphCount = this.model.pathCount();
163         int columns = 1;
164         int rows = 0 == columns ? 0 : (int) Math.ceil(graphCount * 1.0 / columns);
165         TablePanel charts = new TablePanel(columns, rows);
166         for (int graphIndex = 0; graphIndex < graphCount; graphIndex++)
167         {
168             TrajectoryPlot tp = new TrajectoryPlot("Trajectories on lane " + (graphIndex + 1), new Duration(0.5, SECOND),
169                     this.model.getPath(graphIndex), simulator);
170             tp.setTitle("Trajectory Graph");
171             tp.setExtendedState(Frame.MAXIMIZED_BOTH);
172             LaneBasedGTUSampler graph = tp;
173             Container container = tp.getContentPane();
174             charts.setCell(container, graphIndex % columns, graphIndex / columns);
175             this.model.getPlots().add(graph);
176         }
177         addTab(getTabCount(), "statistics", charts);
178     }
179 
180     /** {@inheritDoc} */
181     @Override
182     public final String shortName()
183     {
184         return "Test networks";
185     }
186 
187     /** {@inheritDoc} */
188     @Override
189     public final String description()
190     {
191         return "<html><h1>Test Networks</h1>Prove that the test networks can be constructed and rendered on screen "
192                 + "and that a mix of cars and trucks can run on them.<br>On the statistics tab, a trajectory plot "
193                 + "is generated for each lane.</html>";
194     }
195 
196     /**
197      * <p>
198      * Copyright (c) 2013-2018 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
199      * <br>
200      * BSD-style license. See <a href="http://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
201      * <p>
202      * $LastChangedDate: 2018-09-20 17:32:03 +0200 (Thu, 20 Sep 2018) $, @version $Revision: 4174 $, by $Author: wjschakel $,
203      * initial version mrt. 2015 <br>
204      * @author <a href="http://Hansvanlint.weblog.tudelft.nl">Hans van Lint</a>
205      * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
206      */
207     class XMLNetworkModel implements OTSModelInterface, UNITS
208     {
209         /** */
210         private static final long serialVersionUID = 20150304L;
211 
212         /** The simulator. */
213         private DEVSSimulatorInterface.TimeDoubleUnit simulator;
214 
215         /** The network. */
216         private final OTSNetwork network = new OTSNetwork("network");
217 
218         /** The plots. */
219         private List<LaneBasedGTUSampler> plots = new ArrayList<>();
220 
221         /** User settable properties. */
222         private List<Property<?>> props = null;
223 
224         /** The sequence of Lanes that all vehicles will follow. */
225         private List<List<Lane>> paths = new ArrayList<>();
226 
227         /** The average headway (inter-vehicle time). */
228         private Duration averageHeadway;
229 
230         /** The minimum headway. */
231         private Duration minimumHeadway;
232 
233         /** The probability distribution for the variable part of the headway. */
234         private DistContinuous headwayGenerator;
235 
236         /** The speed limit. */
237         private Speed speedLimit = new Speed(60, KM_PER_HOUR);
238 
239         /** Number of cars created. */
240         // private int carsCreated = 0;
241 
242         /** Type of all GTUs (required to permit lane changing). */
243         private GTUType gtuType = CAR;
244 
245         /** The car following model, e.g. IDM Plus for cars. */
246         private GTUFollowingModelOld carFollowingModelCars;
247 
248         /** The car following model, e.g. IDM Plus for trucks. */
249         private GTUFollowingModelOld carFollowingModelTrucks;
250 
251         /** The lane change model. */
252         private AbstractLaneChangeModel laneChangeModel = new Egoistic();
253 
254         /** The probability that the next generated GTU is a passenger car. */
255         private double carProbability;
256 
257         /** The random number generator used to decide what kind of GTU to generate. */
258         // private Random randomGenerator = new Random(12346);
259 
260         /** Probability distribution disttria(70,80,100). */
261         // private DistContinuous disttria = new DistTriangular(new MersenneTwister(), 70, 80, 100);
262 
263         /** The route generator. */
264         private RouteGenerator routeGenerator;
265 
266         /** Strategical planner generator for cars. */
267         private LaneBasedStrategicalPlannerFactory<LaneBasedStrategicalPlanner> strategicalPlannerGeneratorCars = null;
268 
269         /** Strategical planner generator for cars. */
270         private LaneBasedStrategicalPlannerFactory<LaneBasedStrategicalPlanner> strategicalPlannerGeneratorTrucks = null;
271 
272         /** Id generator (used by all generators). */
273         private IdGenerator idGenerator = new IdGenerator("");
274 
275         /** Random stream. */
276         private StreamInterface stream = new MersenneTwister(1234); // Use a fixed seed for the demos
277 
278         /**
279          * @param userModifiedProperties ArrayList&lt;AbstractProperty&lt;?&gt;&gt;; the (possibly user modified) properties
280          */
281         XMLNetworkModel(final List<Property<?>> userModifiedProperties)
282         {
283             this.props = userModifiedProperties;
284         }
285 
286         /**
287          * @param index int; the rank number of the path
288          * @return List&lt;Lane&gt;; the set of lanes for the specified index
289          */
290         public final List<Lane> getPath(final int index)
291         {
292             return this.paths.get(index);
293         }
294 
295         /**
296          * Return the number of paths that can be used to show graphs.
297          * @return int; the number of paths that can be used to show graphs
298          */
299         public final int pathCount()
300         {
301             return this.paths.size();
302         }
303 
304         /**
305          * @return plots
306          */
307         public final List<LaneBasedGTUSampler> getPlots()
308         {
309             return this.plots;
310         }
311 
312         /** {@inheritDoc} */
313         @Override
314         public final void constructModel(final SimulatorInterface<Time, Duration, SimTimeDoubleUnit> theSimulator)
315                 throws SimRuntimeException
316         {
317             this.simulator = (DEVSSimulatorInterface.TimeDoubleUnit) theSimulator;
318             try
319             {
320                 OTSNode from = new OTSNode(this.network, "From", new OTSPoint3D(0, 0, 0));
321                 OTSNode end = new OTSNode(this.network, "End", new OTSPoint3D(2000, 0, 0));
322                 OTSNode from2a = new OTSNode(this.network, "From2a", new OTSPoint3D(0, -50, 0));
323                 OTSNode from2b = new OTSNode(this.network, "From2b", new OTSPoint3D(490, -2, 0));
324                 OTSNode firstVia = new OTSNode(this.network, "Via1", new OTSPoint3D(500, 0, 0));
325                 OTSNode end2a = new OTSNode(this.network, "End2a", new OTSPoint3D(1020, -2, 0));
326                 OTSNode end2b = new OTSNode(this.network, "End2b", new OTSPoint3D(2000, -50, 0));
327                 OTSNode secondVia = new OTSNode(this.network, "Via2", new OTSPoint3D(1000, 0, 0));
328                 CompoundProperty cp = null;
329                 try
330                 {
331                     cp = new CompoundProperty("", "", "", this.props, false, 0);
332                 }
333                 catch (PropertyException exception2)
334                 {
335                     exception2.printStackTrace();
336                 }
337                 String networkType = (String) cp.findByKey("Network").getValue();
338                 boolean merge = networkType.startsWith("M");
339                 int lanesOnMain = Integer.parseInt(networkType.split(" ")[merge ? 1 : 5]);
340                 int lanesOnBranch = Integer.parseInt(networkType.split(" ")[3]);
341                 int lanesOnCommon = lanesOnMain + lanesOnBranch;
342                 int lanesOnCommonCompressed = Integer.parseInt(networkType.split(" ")[merge ? 5 : 1]);
343 
344                 LaneType laneType = LaneType.TWO_WAY_LANE;
345                 // Get car-following model name
346                 String carFollowingModelName = null;
347                 CompoundProperty propertyContainer = new CompoundProperty("", "", "", this.props, false, 0);
348                 Property<?> cfmp = propertyContainer.findByKey("CarFollowingModel");
349                 if (null == cfmp)
350                 {
351                     throw new Error("Cannot find \"Car following model\" property");
352                 }
353                 if (cfmp instanceof SelectionProperty)
354                 {
355                     carFollowingModelName = ((SelectionProperty) cfmp).getValue();
356                 }
357                 else
358                 {
359                     throw new Error("\"Car following model\" property has wrong type");
360                 }
361 
362                 // Get car-following model parameter
363                 for (Property<?> ap : new CompoundProperty("", "", "", this.props, false, 0))
364                 {
365                     if (ap instanceof CompoundProperty)
366                     {
367                         cp = (CompoundProperty) ap;
368                         if (ap.getKey().contains("IDM"))
369                         {
370                             // System.out.println("Car following model name appears to be " + ap.getKey());
371                             Acceleration a = IDMPropertySet.getA(cp);
372                             Acceleration b = IDMPropertySet.getB(cp);
373                             Length s0 = IDMPropertySet.getS0(cp);
374                             Duration tSafe = IDMPropertySet.getTSafe(cp);
375                             GTUFollowingModelOld gtuFollowingModel = null;
376                             if (carFollowingModelName.equals("IDM"))
377                             {
378                                 gtuFollowingModel = new IDMOld(a, b, s0, tSafe, 1.0);
379                             }
380                             else if (carFollowingModelName.equals("IDM+"))
381                             {
382                                 gtuFollowingModel = new IDMPlusOld(a, b, s0, tSafe, 1.0);
383                             }
384                             else
385                             {
386                                 throw new Error("Unknown gtu following model: " + carFollowingModelName);
387                             }
388                             if (ap.getKey().contains("Car"))
389                             {
390                                 this.carFollowingModelCars = gtuFollowingModel;
391                             }
392                             else if (ap.getKey().contains("Truck"))
393                             {
394                                 this.carFollowingModelTrucks = gtuFollowingModel;
395                             }
396                             else
397                             {
398                                 throw new Error("Cannot determine gtu type for " + ap.getKey());
399                             }
400                         }
401                     }
402                 }
403 
404                 // Get lane change model
405                 cfmp = propertyContainer.findByKey("LaneChanging");
406                 if (null == cfmp)
407                 {
408                     throw new Error("Cannot find \"Lane changing\" property");
409                 }
410                 if (cfmp instanceof SelectionProperty)
411                 {
412                     String laneChangeModelName = ((SelectionProperty) cfmp).getValue();
413                     if ("Egoistic".equals(laneChangeModelName))
414                     {
415                         this.laneChangeModel = new Egoistic();
416                     }
417                     else if ("Altruistic".equals(laneChangeModelName))
418                     {
419                         this.laneChangeModel = new Altruistic();
420                     }
421                     else
422                     {
423                         throw new Error("Lane changing " + laneChangeModelName + " not implemented");
424                     }
425                 }
426                 else
427                 {
428                     throw new Error("\"Lane changing\" property has wrong type");
429                 }
430 
431                 if (merge)
432                 {
433                     // provide a route -- at the merge point, the GTU can otherwise decide to "go back"
434                     ArrayList<Node> mainRouteNodes = new ArrayList<>();
435                     mainRouteNodes.add(firstVia);
436                     mainRouteNodes.add(secondVia);
437                     mainRouteNodes.add(end);
438                     Route mainRoute = new Route("main", mainRouteNodes);
439                     this.routeGenerator = new FixedRouteGenerator(mainRoute);
440                 }
441                 else
442                 {
443                     // determine the routes
444                     List<FrequencyAndObject<Route>> routeProbabilities = new ArrayList<>();
445 
446                     ArrayList<Node> mainRouteNodes = new ArrayList<>();
447                     mainRouteNodes.add(firstVia);
448                     mainRouteNodes.add(secondVia);
449                     mainRouteNodes.add(end);
450                     Route mainRoute = new Route("main", mainRouteNodes);
451                     routeProbabilities.add(new FrequencyAndObject<>(lanesOnMain, mainRoute));
452 
453                     ArrayList<Node> sideRouteNodes = new ArrayList<>();
454                     sideRouteNodes.add(firstVia);
455                     sideRouteNodes.add(secondVia);
456                     sideRouteNodes.add(end2a);
457                     sideRouteNodes.add(end2b);
458                     Route sideRoute = new Route("side", sideRouteNodes);
459                     routeProbabilities.add(new FrequencyAndObject<>(lanesOnBranch, sideRoute));
460                     try
461                     {
462                         this.routeGenerator = new ProbabilisticRouteGenerator(routeProbabilities, new MersenneTwister(1234));
463                     }
464                     catch (ProbabilityException exception)
465                     {
466                         exception.printStackTrace();
467                     }
468                 }
469 
470                 // Get remaining properties
471                 for (Property<?> ap : new CompoundProperty("", "", "", this.props, false, 0))
472                 {
473                     if (ap instanceof SelectionProperty)
474                     {
475                         SelectionProperty sp = (SelectionProperty) ap;
476                         if ("TacticalPlanner".equals(sp.getKey()))
477                         {
478                             String tacticalPlannerName = sp.getValue();
479                             if ("IDM".equals(tacticalPlannerName))
480                             {
481                                 this.strategicalPlannerGeneratorCars = new LaneBasedStrategicalRoutePlannerFactory(
482                                         new LaneBasedGTUFollowingTacticalPlannerFactory(this.carFollowingModelCars));
483                                 this.strategicalPlannerGeneratorTrucks = new LaneBasedStrategicalRoutePlannerFactory(
484                                         new LaneBasedGTUFollowingTacticalPlannerFactory(this.carFollowingModelTrucks));
485                             }
486                             else if ("MOBIL/IDM".equals(tacticalPlannerName))
487                             {
488                                 this.strategicalPlannerGeneratorCars =
489                                         new LaneBasedStrategicalRoutePlannerFactory(new LaneBasedCFLCTacticalPlannerFactory(
490                                                 this.carFollowingModelCars, this.laneChangeModel));
491                                 this.strategicalPlannerGeneratorTrucks =
492                                         new LaneBasedStrategicalRoutePlannerFactory(new LaneBasedCFLCTacticalPlannerFactory(
493                                                 this.carFollowingModelTrucks, this.laneChangeModel));
494                             }
495                             else if ("DIRECTED/IDM".equals(tacticalPlannerName))
496                             {
497                                 this.strategicalPlannerGeneratorCars = new LaneBasedStrategicalRoutePlannerFactory(
498                                         new LaneBasedGTUFollowingDirectedChangeTacticalPlannerFactory(
499                                                 this.carFollowingModelCars));
500                                 this.strategicalPlannerGeneratorTrucks = new LaneBasedStrategicalRoutePlannerFactory(
501                                         new LaneBasedGTUFollowingDirectedChangeTacticalPlannerFactory(
502                                                 this.carFollowingModelTrucks));
503                             }
504                             else if ("LMRS".equals(tacticalPlannerName))
505                             {
506                                 // provide default parameters with the car-following model
507                                 this.strategicalPlannerGeneratorCars = new LaneBasedStrategicalRoutePlannerFactory(
508                                         new LMRSFactory(new IDMPlusFactory(this.stream), new DefaultLMRSPerceptionFactory()));
509                                 this.strategicalPlannerGeneratorTrucks = new LaneBasedStrategicalRoutePlannerFactory(
510                                         new LMRSFactory(new IDMPlusFactory(this.stream), new DefaultLMRSPerceptionFactory()));
511                             }
512                             else if ("Toledo".equals(tacticalPlannerName))
513                             {
514                                 this.strategicalPlannerGeneratorCars =
515                                         new LaneBasedStrategicalRoutePlannerFactory(new ToledoFactory());
516                                 this.strategicalPlannerGeneratorTrucks =
517                                         new LaneBasedStrategicalRoutePlannerFactory(new ToledoFactory());
518                             }
519                             else
520                             {
521                                 throw new Error("Don't know how to create a " + tacticalPlannerName + " tactical planner");
522                             }
523                         }
524 
525                     }
526                     else if (ap instanceof ProbabilityDistributionProperty)
527                     {
528                         ProbabilityDistributionProperty pdp = (ProbabilityDistributionProperty) ap;
529                         String modelName = ap.getKey();
530                         if (modelName.equals("TrafficComposition"))
531                         {
532                             this.carProbability = pdp.getValue()[0];
533                         }
534                     }
535                     else if (ap instanceof ContinuousProperty)
536                     {
537                         ContinuousProperty contP = (ContinuousProperty) ap;
538                         if (contP.getKey().startsWith("Flow"))
539                         {
540                             this.averageHeadway = new Duration(3600.0 / contP.getValue(), SECOND);
541                             this.minimumHeadway = new Duration(3, SECOND);
542                             this.headwayGenerator = new DistErlang(new MersenneTwister(1234), 4,
543                                     DoubleScalar.minus(this.averageHeadway, this.minimumHeadway).getSI());
544                         }
545                     }
546                     else if (ap instanceof CompoundProperty)
547                     {
548                         CompoundProperty compoundProperty = (CompoundProperty) ap;
549                         if (ap.getKey().equals("Output"))
550                         {
551                             continue; // Output settings are handled elsewhere
552                         }
553                         if (ap.getKey().contains("IDM"))
554                         {
555                             Acceleration a = IDMPropertySet.getA(compoundProperty);
556                             Acceleration b = IDMPropertySet.getB(compoundProperty);
557                             Length s0 = IDMPropertySet.getS0(compoundProperty);
558                             Duration tSafe = IDMPropertySet.getTSafe(compoundProperty);
559                             GTUFollowingModelOld gtuFollowingModel = null;
560                             if (carFollowingModelName.equals("IDM"))
561                             {
562                                 gtuFollowingModel = new IDMOld(a, b, s0, tSafe, 1.0);
563                             }
564                             else if (carFollowingModelName.equals("IDM+"))
565                             {
566                                 gtuFollowingModel = new IDMPlusOld(a, b, s0, tSafe, 1.0);
567                             }
568                             else
569                             {
570                                 throw new Error("Unknown gtu following model: " + carFollowingModelName);
571                             }
572                             if (ap.getKey().contains("Car"))
573                             {
574                                 this.carFollowingModelCars = gtuFollowingModel;
575                             }
576                             else if (ap.getKey().contains("Truck"))
577                             {
578                                 this.carFollowingModelTrucks = gtuFollowingModel;
579                             }
580                             else
581                             {
582                                 throw new Error("Cannot determine gtu type for " + ap.getKey());
583                             }
584                         }
585                     }
586                 }
587 
588                 if (merge)
589                 {
590                     setupGenerator(LaneFactory.makeMultiLane(this.network, "From2a to From2b", from2a, from2b, null,
591                             lanesOnBranch, 0, lanesOnCommon - lanesOnBranch, laneType, this.speedLimit, this.simulator));
592                     LaneFactory.makeMultiLaneBezier(this.network, "From2b to FirstVia", from2a, from2b, firstVia, secondVia,
593                             lanesOnBranch, lanesOnCommon - lanesOnBranch, lanesOnCommon - lanesOnBranch, laneType,
594                             this.speedLimit, this.simulator);
595                 }
596                 else
597                 {
598                     LaneFactory.makeMultiLaneBezier(this.network, "SecondVia to end2a", firstVia, secondVia, end2a, end2b,
599                             lanesOnBranch, lanesOnCommon - lanesOnBranch, lanesOnCommon - lanesOnBranch, laneType,
600                             this.speedLimit, this.simulator);
601                     setupSink(LaneFactory.makeMultiLane(this.network, "end2a to end2b", end2a, end2b, null, lanesOnBranch,
602                             lanesOnCommon - lanesOnBranch, 0, laneType, this.speedLimit, this.simulator), laneType);
603                 }
604 
605                 Lane[] startLanes = LaneFactory.makeMultiLane(this.network, "From to FirstVia", from, firstVia, null,
606                         merge ? lanesOnMain : lanesOnCommonCompressed, laneType, this.speedLimit, this.simulator);
607                 setupGenerator(startLanes);
608                 Lane[] common = LaneFactory.makeMultiLane(this.network, "FirstVia to SecondVia", firstVia, secondVia, null,
609                         lanesOnCommon, laneType, this.speedLimit, this.simulator);
610                 if (merge)
611                 {
612                     for (int i = lanesOnCommonCompressed; i < lanesOnCommon; i++)
613                     {
614                         setupBlock(common[i]);
615                     }
616                 }
617                 setupSink(
618                         LaneFactory.makeMultiLane(this.network, "SecondVia to end", secondVia, end, null,
619                                 merge ? lanesOnCommonCompressed : lanesOnMain, laneType, this.speedLimit, this.simulator),
620                         laneType);
621 
622                 for (int index = 0; index < lanesOnCommon; index++)
623                 {
624                     this.paths.add(new ArrayList<Lane>());
625                     Lane lane = common[index];
626                     // Follow back
627                     while (lane.prevLanes(this.gtuType).size() > 0)
628                     {
629                         if (lane.prevLanes(this.gtuType).size() > 1)
630                         {
631                             throw new NetworkException("This network should not have lane merge points");
632                         }
633                         lane = lane.prevLanes(this.gtuType).keySet().iterator().next();
634                     }
635                     // Follow forward
636                     while (true)
637                     {
638                         this.paths.get(index).add(lane);
639                         int branching = lane.nextLanes(this.gtuType).size();
640                         if (branching == 0)
641                         {
642                             break;
643                         }
644                         if (branching > 1)
645                         {
646                             throw new NetworkException("This network should not have lane split points");
647                         }
648                         lane = lane.nextLanes(this.gtuType).keySet().iterator().next();
649                     }
650                 }
651                 this.simulator.scheduleEventAbs(new Time(0.999, TimeUnit.BASE_SECOND), this, this, "drawGraphs", null);
652             }
653             catch (NamingException | NetworkException | GTUException | OTSGeometryException | ProbabilityException
654                     | PropertyException | ParameterException exception1)
655             {
656                 exception1.printStackTrace();
657             }
658         }
659 
660         /**
661          * Add a generator to an array of Lane.
662          * @param lanes Lane[]; the lanes that must get a generator at the start
663          * @return Lane[]; the lanes
664          * @throws GTUException when lane position out of bounds
665          * @throws SimRuntimeException when generation scheduling fails
666          * @throws ProbabilityException when probability distribution is wrong
667          * @throws ParameterException when a parameter is missing for the perception of the GTU
668          */
669         private Lane[] setupGenerator(final Lane[] lanes)
670                 throws SimRuntimeException, GTUException, ProbabilityException, ParameterException
671         {
672             for (Lane lane : lanes)
673             {
674                 makeGenerator(lane);
675 
676                 // Object[] arguments = new Object[1];
677                 // arguments[0] = lane;
678                 // this.simulator.scheduleEventAbs(Time.ZERO, this, this, "generateCar", arguments);
679             }
680             return lanes;
681         }
682 
683         /**
684          * Build a generator.
685          * @param lane Lane; the lane on which the generated GTUs are placed
686          * @return LaneBasedGTUGenerator
687          * @throws GTUException when lane position out of bounds
688          * @throws SimRuntimeException when generation scheduling fails
689          * @throws ProbabilityException when probability distribution is wrong
690          * @throws ParameterException when a parameter is missing for the perception of the GTU
691          */
692         private LaneBasedGTUGenerator makeGenerator(final Lane lane)
693                 throws GTUException, SimRuntimeException, ProbabilityException, ParameterException
694         {
695             Distribution<LaneBasedTemplateGTUType> distribution = new Distribution<>(this.stream);
696             Length initialPosition = new Length(16, METER);
697             Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1);
698             initialPositions.add(new DirectedLanePosition(lane, initialPosition, GTUDirectionality.DIR_PLUS));
699 
700             LaneBasedTemplateGTUType template = makeTemplate(this.stream, lane,
701                     new ContinuousDistDoubleScalar.Rel<Length, LengthUnit>(new DistUniform(this.stream, 3, 6), METER),
702                     new ContinuousDistDoubleScalar.Rel<Length, LengthUnit>(new DistUniform(this.stream, 1.6, 2.0), METER),
703                     new ContinuousDistDoubleScalar.Rel<Speed, SpeedUnit>(new DistUniform(this.stream, 140, 180), KM_PER_HOUR),
704                     initialPositions, this.strategicalPlannerGeneratorCars);
705             // System.out.println("Constructed template " + template);
706             distribution.add(new FrequencyAndObject<>(this.carProbability, template));
707             template = makeTemplate(this.stream, lane,
708                     new ContinuousDistDoubleScalar.Rel<Length, LengthUnit>(new DistUniform(this.stream, 8, 14), METER),
709                     new ContinuousDistDoubleScalar.Rel<Length, LengthUnit>(new DistUniform(this.stream, 2.0, 2.5), METER),
710                     new ContinuousDistDoubleScalar.Rel<Speed, SpeedUnit>(new DistUniform(this.stream, 100, 140), KM_PER_HOUR),
711                     initialPositions, this.strategicalPlannerGeneratorTrucks);
712             // System.out.println("Constructed template " + template);
713             distribution.add(new FrequencyAndObject<>(1.0 - this.carProbability, template));
714             LaneBasedTemplateGTUTypeDistribution templateDistribution = new LaneBasedTemplateGTUTypeDistribution(distribution);
715             LaneBasedGTUGenerator.RoomChecker roomChecker = new CFRoomChecker();
716             return new LaneBasedGTUGenerator(lane.getId(), new Generator<Duration>()
717             {
718                 @SuppressWarnings("synthetic-access")
719                 @Override
720                 public Duration draw()
721                 {
722                     return new Duration(XMLNetworkModel.this.headwayGenerator.draw(), DurationUnit.SECOND);
723                 }
724             }, XMLNetworks.this.getColorer(), templateDistribution, GeneratorPositions.create(initialPositions, this.stream),
725                     this.network, this.simulator,
726                     /*-
727                     new LaneBasedGTUGenerator.RoomChecker()
728                     {
729                     @Override
730                     public Speed canPlace(Speed leaderSpeed, org.djunits.value.vdouble.scalar.Length headway,
731                     LaneBasedGTUCharacteristics laneBasedGTUCharacteristics) throws NetworkException
732                     {
733                     // This implementation simply returns null if the headway is less than the headway wanted for driving at
734                     // the current speed of the leader
735                     if (headway.lt(laneBasedGTUCharacteristics
736                     .getStrategicalPlanner()
737                     .getDrivingCharacteristics()
738                     .getGTUFollowingModel()
739                     .minimumHeadway(leaderSpeed, leaderSpeed, new Length(0.1, LengthUnit.METER),
740                           new Length(Double.MAX_VALUE, LengthUnit.SI),
741                           lane.getSpeedLimit(XMLNetworkModel.this.gtuType),
742                           laneBasedGTUCharacteristics.getMaximumSpeed())))
743                     {
744                     return null;
745                     }
746                     return leaderSpeed;
747                     }
748                     }
749                     */
750                     roomChecker, this.idGenerator);
751         }
752 
753         /**
754          * @param randStream the random stream to use
755          * @param lane reference lane to generate GTUs on
756          * @param lengthDistribution distribution of the GTU length
757          * @param widthDistribution distribution of the GTU width
758          * @param maximumSpeedDistribution distribution of the GTU's maximum speed
759          * @param initialPositions initial position(s) of the GTU on the Lane(s)
760          * @param strategicalPlannerFactory factory to generate the strategical planner for the GTU
761          * @return template for a GTU
762          * @throws GTUException when characteristics cannot be initialized
763          */
764         LaneBasedTemplateGTUType makeTemplate(final StreamInterface randStream, final Lane lane,
765                 final ContinuousDistDoubleScalar.Rel<Length, LengthUnit> lengthDistribution,
766                 final ContinuousDistDoubleScalar.Rel<Length, LengthUnit> widthDistribution,
767                 final ContinuousDistDoubleScalar.Rel<Speed, SpeedUnit> maximumSpeedDistribution,
768                 final Set<DirectedLanePosition> initialPositions,
769                 final LaneBasedStrategicalPlannerFactory<LaneBasedStrategicalPlanner> strategicalPlannerFactory)
770                 throws GTUException
771         {
772             return new LaneBasedTemplateGTUType(this.gtuType, new Generator<Length>()
773             {
774                 @Override
775                 public Length draw()
776                 {
777                     return lengthDistribution.draw();
778                 }
779             }, new Generator<Length>()
780             {
781                 @Override
782                 public Length draw()
783                 {
784                     return widthDistribution.draw();
785                 }
786             }, new Generator<Speed>()
787             {
788                 @Override
789                 public Speed draw()
790                 {
791                     return maximumSpeedDistribution.draw();
792                 }
793             },
794                     /*-new Generator<LaneBasedStrategicalPlanner>()
795                     {
796                         public LaneBasedStrategicalPlanner draw() throws ProbabilityException, ParameterException
797                         {
798                             BehavioralCharacteristics parameters = DefaultsFactory.getDefaultBehavioralCharacteristics();
799                             parameters.setParameter(ParameterTypes.LOOKAHEAD, new Length(450.0, LengthUnit.METER));
800                             try
801                             {
802                                 return new LaneBasedStrategicalRoutePlanner(parameters, tacticalPlanner,
803                                     XMLNetworkModel.this.routeGenerator.draw());
804                             }
805                             catch (GTUException exception)
806                             {
807                                 throw new ParameterException(exception);
808                             }
809                         }
810                     }*/
811                     strategicalPlannerFactory, this.routeGenerator);
812 
813         }
814 
815         /**
816          * Append a sink to each lane of an array of Lanes.
817          * @param lanes Lane[]; the array of lanes
818          * @param laneType the LaneType for cars
819          * @return Lane[]; the lanes
820          * @throws NetworkException on network inconsistency
821          * @throws OTSGeometryException on problem making the path for a link
822          */
823         private Lane[] setupSink(final Lane[] lanes, final LaneType laneType) throws NetworkException, OTSGeometryException
824         {
825             CrossSectionLink link = lanes[0].getParentLink();
826             Node to = link.getEndNode();
827             Node from = link.getStartNode();
828             double endLinkLength = 50; // [m]
829             double endX = to.getPoint().x + (endLinkLength / link.getLength().getSI()) * (to.getPoint().x - from.getPoint().x);
830             double endY = to.getPoint().y + (endLinkLength / link.getLength().getSI()) * (to.getPoint().y - from.getPoint().y);
831             Node end = new OTSNode(this.network, link.getId() + "END", new OTSPoint3D(endX, endY, to.getPoint().z));
832             CrossSectionLink endLink =
833                     LaneFactory.makeLink(this.network, link.getId() + "endLink", to, end, null, this.simulator);
834             for (Lane lane : lanes)
835             {
836                 // Overtaking left and right allowed on the sinkLane
837                 Lane sinkLane = new Lane(endLink, lane.getId() + "." + "sinkLane", lane.getLateralCenterPosition(1.0),
838                         lane.getLateralCenterPosition(1.0), lane.getWidth(1.0), lane.getWidth(1.0), laneType, this.speedLimit,
839                         new OvertakingConditions.LeftAndRight());
840                 new SinkSensor(sinkLane, new Length(10.0, METER), this.simulator);
841             }
842             return lanes;
843         }
844 
845         /**
846          * Put a block at the end of a Lane.
847          * @param lane Lane; the lane on which the block is placed
848          * @return Lane; the lane
849          * @throws NamingException on ???
850          * @throws NetworkException on network inconsistency
851          * @throws SimRuntimeException on ???
852          * @throws GTUException when construction of the GTU (the block is a GTU) fails
853          * @throws OTSGeometryException when the initial path is wrong
854          */
855         private Lane setupBlock(final Lane lane)
856                 throws NamingException, NetworkException, SimRuntimeException, GTUException, OTSGeometryException
857         {
858             // Length initialPosition = lane.getLength();
859             // Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1);
860             // initialPositions.add(new DirectedLanePosition(lane, initialPosition, GTUDirectionality.DIR_PLUS));
861             // // GTUFollowingModelOld gfm =
862             // // new FixedAccelerationModel(new Acceleration(0, AccelerationUnit.SI), new Duration(java.lang.Double.MAX_VALUE,
863             // // TimeUnit.SI));
864             // // LaneChangeModel lcm = new FixedLaneChangeModel(null);
865             // Parameters parameters = DefaultsFactory.getDefaultParameters();
866             // LaneBasedIndividualGTU block = new LaneBasedIndividualGTU("999999", this.gtuType, Length.ZERO,
867             // lane.getWidth(1), Speed.ZERO, Length.ZERO, this.simulator, this.network);
868             // LaneBasedStrategicalPlanner strategicalPlanner = new LaneBasedStrategicalRoutePlanner(
869             // new LaneBasedGTUFollowingTacticalPlanner(this.carFollowingModelCars, block), block);
870             // block.setParameters(parameters);
871             // block.initWithAnimation(strategicalPlanner, initialPositions, Speed.ZERO, DefaultCarAnimation.class,
872             // XMLNetworks.this.getColorer());
873             return lane;
874         }
875 
876         /**
877          * Notify the contour plots that the underlying data has changed.
878          */
879         protected final void drawGraphs()
880         {
881             for (LaneBasedGTUSampler plot : this.plots)
882             {
883                 plot.reGraph();
884             }
885             // Re schedule this method
886             try
887             {
888                 this.simulator.scheduleEventAbs(new Time(this.simulator.getSimulatorTime().getSI() + 1, TimeUnit.BASE_SECOND),
889                         this, this, "drawGraphs", null);
890             }
891             catch (SimRuntimeException exception)
892             {
893                 exception.printStackTrace();
894             }
895 
896         }
897 
898         /**
899          * Generate cars at a fixed rate (implemented by re-scheduling this method).
900          * @param lane Lane; the lane on which the generated cars are placed
901          */
902         // protected final void generateCar(final Lane lane)
903         // {
904         // Length initialPosition = new Length(16, METER);
905         // Speed initialSpeed = new Speed(50, KM_PER_HOUR);
906         // boolean generate = true;
907         // // Check if there is sufficient room
908         // // Find the first vehicle on the lane
909         // LaneBasedGTU leader = null;
910         // Time when = new Time(this.simulator.getSimulatorTime().si, TimeUnit.SI);
911         // try
912         // {
913         // leader = lane.getGtuAhead(initialPosition, GTUDirectionality.DIR_PLUS, RelativePosition.REAR, when);
914         // if (null != leader)
915         // {
916         // double headway =
917         // leader.fractionalPosition(lane, leader.getRear()) * lane.getLength().si - initialPosition.si - 15.0 / 2;
918         // if (headway < 0.1)
919         // {
920         // System.out.println("Not generating GTU due to insufficient room");
921         // generate = false;
922         // }
923         // double leaderSpeed = leader.getSpeed().si;
924         // if (leaderSpeed < initialSpeed.si)
925         // {
926         // // What distance will it take to reduce speed to 0 with a decent deceleration?
927         // double decentDeceleration = 5; // [m/s/s]
928         // double deltaT = initialSpeed.si / decentDeceleration;
929         // double distance = 0.5 * decentDeceleration * deltaT * deltaT;
930         // if (distance > headway)
931         // {
932         // System.out.println("Not generating GTU due to slow driving GTU within emergency stop range");
933         // generate = false;
934         // }
935         // }
936         // }
937         // }
938         // catch (GTUException exception1)
939         // {
940         // exception1.printStackTrace();
941         // }
942         // try
943         // {
944         // if (generate)
945         // {
946         // boolean generateTruck = this.randomGenerator.nextDouble() > this.carProbability;
947         // Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1);
948         // initialPositions.add(new DirectedLanePosition(lane, initialPosition, GTUDirectionality.DIR_PLUS));
949         // Length vehicleLength = new Length(generateTruck ? 15 : 4, METER);
950         // GTUFollowingModel gtuFollowingModel = generateTruck ? this.carFollowingModelTrucks : this.carFollowingModelCars;
951         // double speed = this.disttria.draw();
952         //
953         // LaneBasedDrivingCharacteristics drivingCharacteristics =
954         // new LaneBasedDrivingCharacteristics(gtuFollowingModel, this.laneChangeModel);
955         // drivingCharacteristics.setForwardHeadwayDistance(new Length(450.0, LengthUnit.METER));
956         // LaneBasedStrategicalPlanner strategicalPlanner =
957         // new LaneBasedStrategicalRoutePlanner(drivingCharacteristics, this.tacticalPlanner,
958         // this.routeGenerator.draw());
959         // new LaneBasedIndividualGTU("" + (++this.carsCreated), this.gtuType, initialPositions, initialSpeed,
960         // vehicleLength, new Length(1.8, METER), new Speed(speed, KM_PER_HOUR), this.simulator,
961         // strategicalPlanner, new LanePerceptionFull(), DefaultCarAnimation.class, this.gtuColorer, this.network);
962         // }
963         // Object[] arguments = new Object[1];
964         // arguments[0] = lane;
965         // this.simulator.scheduleEventRel(new Duration(this.headwayGenerator.draw(), SECOND), this, this, "generateCar",
966         // arguments);
967         // }
968         // catch (SimRuntimeException | NamingException | NetworkException | GTUException | OTSGeometryException
969         // | ProbabilityException exception)
970         // {
971         // exception.printStackTrace();
972         // }
973         // }
974 
975         /** {@inheritDoc} */
976         @Override
977         public SimulatorInterface<Time, Duration, SimTimeDoubleUnit> getSimulator()
978         {
979             return this.simulator;
980         }
981 
982         /** {@inheritDoc} */
983         @Override
984         public OTSNetwork getNetwork()
985         {
986             return this.network;
987         }
988     }
989 }