View Javadoc
1   package strategies;
2   
3   import java.awt.Color;
4   import java.awt.Dimension;
5   import java.awt.Toolkit;
6   import java.io.BufferedWriter;
7   import java.io.IOException;
8   import java.rmi.RemoteException;
9   import java.util.ArrayList;
10  import java.util.LinkedHashMap;
11  import java.util.LinkedHashSet;
12  import java.util.List;
13  import java.util.Map;
14  import java.util.Set;
15  
16  import javax.naming.NamingException;
17  
18  import org.djunits.unit.FrequencyUnit;
19  import org.djunits.unit.SpeedUnit;
20  import org.djunits.unit.TimeUnit;
21  import org.djunits.value.ValueRuntimeException;
22  import org.djunits.value.storage.StorageType;
23  import org.djunits.value.vdouble.scalar.Acceleration;
24  import org.djunits.value.vdouble.scalar.Direction;
25  import org.djunits.value.vdouble.scalar.Duration;
26  import org.djunits.value.vdouble.scalar.Frequency;
27  import org.djunits.value.vdouble.scalar.Length;
28  import org.djunits.value.vdouble.scalar.Speed;
29  import org.djunits.value.vdouble.scalar.Time;
30  import org.djunits.value.vdouble.vector.FrequencyVector;
31  import org.djunits.value.vdouble.vector.TimeVector;
32  import org.djunits.value.vdouble.vector.base.DoubleVector;
33  import org.djunits.value.vfloat.scalar.FloatDuration;
34  import org.djunits.value.vfloat.scalar.FloatLength;
35  import org.djunits.value.vfloat.scalar.FloatSpeed;
36  import org.djutils.exceptions.Throw;
37  import org.djutils.exceptions.Try;
38  import org.opentrafficsim.base.CompressedFileWriter;
39  import org.opentrafficsim.base.parameters.ParameterException;
40  import org.opentrafficsim.base.parameters.ParameterSet;
41  import org.opentrafficsim.base.parameters.ParameterTypes;
42  import org.opentrafficsim.base.parameters.Parameters;
43  import org.opentrafficsim.core.animation.gtu.colorer.AccelerationGTUColorer;
44  import org.opentrafficsim.core.animation.gtu.colorer.GTUColorer;
45  import org.opentrafficsim.core.animation.gtu.colorer.IDGTUColorer;
46  import org.opentrafficsim.core.animation.gtu.colorer.SpeedGTUColorer;
47  import org.opentrafficsim.core.animation.gtu.colorer.SwitchableGTUColorer;
48  import org.opentrafficsim.core.compatibility.Compatible;
49  import org.opentrafficsim.core.dsol.AbstractOTSModel;
50  import org.opentrafficsim.core.dsol.AbstractOTSSimulationApplication;
51  import org.opentrafficsim.core.dsol.OTSAnimator;
52  import org.opentrafficsim.core.dsol.OTSModelInterface;
53  import org.opentrafficsim.core.dsol.OTSSimulator;
54  import org.opentrafficsim.core.dsol.OTSSimulatorInterface;
55  import org.opentrafficsim.core.geometry.OTSGeometryException;
56  import org.opentrafficsim.core.geometry.OTSLine3D;
57  import org.opentrafficsim.core.geometry.OTSPoint3D;
58  import org.opentrafficsim.core.gtu.GTU;
59  import org.opentrafficsim.core.gtu.GTUCharacteristics;
60  import org.opentrafficsim.core.gtu.GTUException;
61  import org.opentrafficsim.core.gtu.GTUType;
62  import org.opentrafficsim.core.gtu.perception.DirectEgoPerception;
63  import org.opentrafficsim.core.network.LateralDirectionality;
64  import org.opentrafficsim.core.network.LinkType;
65  import org.opentrafficsim.core.network.Network;
66  import org.opentrafficsim.core.network.NetworkException;
67  import org.opentrafficsim.core.network.Node;
68  import org.opentrafficsim.core.network.OTSLink;
69  import org.opentrafficsim.core.network.OTSNode;
70  import org.opentrafficsim.core.parameters.ParameterFactoryByType;
71  import org.opentrafficsim.core.units.distributions.ContinuousDistDoubleScalar;
72  import org.opentrafficsim.core.units.distributions.ContinuousDistSpeed;
73  import org.opentrafficsim.draw.core.OTSDrawingException;
74  import org.opentrafficsim.draw.gtu.GtuGeneratorQueueAnimation;
75  import org.opentrafficsim.draw.network.LinkAnimation;
76  import org.opentrafficsim.draw.network.NodeAnimation;
77  import org.opentrafficsim.draw.road.LaneAnimation;
78  import org.opentrafficsim.draw.road.StripeAnimation;
79  import org.opentrafficsim.draw.road.StripeAnimation.TYPE;
80  import org.opentrafficsim.kpi.sampling.KpiGtuDirectionality;
81  import org.opentrafficsim.kpi.sampling.KpiLaneDirection;
82  import org.opentrafficsim.kpi.sampling.Sampler;
83  import org.opentrafficsim.kpi.sampling.SpaceTimeRegion;
84  import org.opentrafficsim.kpi.sampling.data.ExtendedDataTypeDuration;
85  import org.opentrafficsim.kpi.sampling.data.ExtendedDataTypeLength;
86  import org.opentrafficsim.kpi.sampling.data.ExtendedDataTypeNumber;
87  import org.opentrafficsim.kpi.sampling.data.ExtendedDataTypeSpeed;
88  import org.opentrafficsim.road.gtu.colorer.DesiredHeadwayColorer;
89  import org.opentrafficsim.road.gtu.colorer.DesiredSpeedColorer;
90  import org.opentrafficsim.road.gtu.colorer.FixedColor;
91  import org.opentrafficsim.road.gtu.colorer.GTUTypeColorer;
92  import org.opentrafficsim.road.gtu.colorer.IncentiveColorer;
93  import org.opentrafficsim.road.gtu.colorer.SocialPressureColorer;
94  import org.opentrafficsim.road.gtu.colorer.SynchronizationColorer;
95  import org.opentrafficsim.road.gtu.colorer.TotalDesireColorer;
96  import org.opentrafficsim.road.gtu.generator.GeneratorPositions.LaneBias;
97  import org.opentrafficsim.road.gtu.generator.GeneratorPositions.LaneBiases;
98  import org.opentrafficsim.road.gtu.generator.GtuGeneratorQueue;
99  import org.opentrafficsim.road.gtu.generator.MarkovCorrelation;
100 import org.opentrafficsim.road.gtu.generator.characteristics.LaneBasedGTUCharacteristics;
101 import org.opentrafficsim.road.gtu.generator.headway.ArrivalsHeadwayGenerator.HeadwayDistribution;
102 import org.opentrafficsim.road.gtu.generator.od.GTUCharacteristicsGeneratorOD;
103 import org.opentrafficsim.road.gtu.generator.od.ODApplier;
104 import org.opentrafficsim.road.gtu.generator.od.ODApplier.GeneratorObjects;
105 import org.opentrafficsim.road.gtu.generator.od.ODOptions;
106 import org.opentrafficsim.road.gtu.lane.LaneBasedGTU;
107 import org.opentrafficsim.road.gtu.lane.VehicleModel;
108 import org.opentrafficsim.road.gtu.lane.perception.CategoricalLanePerception;
109 import org.opentrafficsim.road.gtu.lane.perception.LanePerception;
110 import org.opentrafficsim.road.gtu.lane.perception.PerceptionFactory;
111 import org.opentrafficsim.road.gtu.lane.perception.categories.AnticipationTrafficPerception;
112 import org.opentrafficsim.road.gtu.lane.perception.categories.DirectInfrastructurePerception;
113 import org.opentrafficsim.road.gtu.lane.perception.categories.neighbors.DirectNeighborsPerception;
114 import org.opentrafficsim.road.gtu.lane.perception.categories.neighbors.HeadwayGtuType;
115 import org.opentrafficsim.road.gtu.lane.plan.operational.LaneChange;
116 import org.opentrafficsim.road.gtu.lane.tactical.DesireBased;
117 import org.opentrafficsim.road.gtu.lane.tactical.following.AbstractIDM;
118 import org.opentrafficsim.road.gtu.lane.tactical.following.CarFollowingModelFactory;
119 import org.opentrafficsim.road.gtu.lane.tactical.following.IDMPlus;
120 import org.opentrafficsim.road.gtu.lane.tactical.following.IDMPlusFactory;
121 import org.opentrafficsim.road.gtu.lane.tactical.lmrs.AccelerationIncentive;
122 import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveKeep;
123 import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveRoute;
124 import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveSocioSpeed;
125 import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveSpeedWithCourtesy;
126 import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveStayRight;
127 import org.opentrafficsim.road.gtu.lane.tactical.lmrs.LMRSFactory;
128 import org.opentrafficsim.road.gtu.lane.tactical.lmrs.SocioDesiredSpeed;
129 import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.Cooperation;
130 import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.GapAcceptance;
131 import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.Incentive;
132 import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.LmrsParameters;
133 import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.MandatoryIncentive;
134 import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.Synchronization;
135 import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.Tailgating;
136 import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.VoluntaryIncentive;
137 import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalPlannerFactory;
138 import org.opentrafficsim.road.gtu.strategical.od.Categorization;
139 import org.opentrafficsim.road.gtu.strategical.od.Category;
140 import org.opentrafficsim.road.gtu.strategical.od.Interpolation;
141 import org.opentrafficsim.road.gtu.strategical.od.ODMatrix;
142 import org.opentrafficsim.road.gtu.strategical.route.LaneBasedStrategicalRoutePlannerFactory;
143 import org.opentrafficsim.road.network.OTSRoadNetwork;
144 import org.opentrafficsim.road.network.lane.CrossSectionLink;
145 import org.opentrafficsim.road.network.lane.DirectedLanePosition;
146 import org.opentrafficsim.road.network.lane.Lane;
147 import org.opentrafficsim.road.network.lane.LaneType;
148 import org.opentrafficsim.road.network.lane.OTSRoadNode;
149 import org.opentrafficsim.road.network.lane.Stripe;
150 import org.opentrafficsim.road.network.lane.Stripe.Permeable;
151 import org.opentrafficsim.road.network.lane.changing.LaneKeepingPolicy;
152 import org.opentrafficsim.road.network.lane.object.SpeedSign;
153 import org.opentrafficsim.road.network.lane.object.sensor.Detector;
154 import org.opentrafficsim.road.network.lane.object.sensor.Detector.CompressionMethod;
155 import org.opentrafficsim.road.network.lane.object.sensor.Detector.DetectorMeasurement;
156 import org.opentrafficsim.road.network.lane.object.sensor.SinkSensor;
157 import org.opentrafficsim.road.network.sampling.GtuData;
158 import org.opentrafficsim.road.network.sampling.LaneData;
159 import org.opentrafficsim.road.network.sampling.RoadSampler;
160 import org.opentrafficsim.swing.gui.AnimationToggles;
161 import org.opentrafficsim.swing.gui.OTSAnimationPanel;
162 import org.opentrafficsim.swing.gui.OTSSimulationApplication;
163 
164 import nl.tudelft.simulation.dsol.SimRuntimeException;
165 import nl.tudelft.simulation.dsol.simulators.DEVSSimulatorInterface;
166 import nl.tudelft.simulation.dsol.simulators.SimulatorInterface;
167 import nl.tudelft.simulation.event.EventInterface;
168 import nl.tudelft.simulation.event.EventListenerInterface;
169 import nl.tudelft.simulation.jstats.distributions.DistLogNormal;
170 import nl.tudelft.simulation.jstats.distributions.DistNormal;
171 import nl.tudelft.simulation.jstats.distributions.DistTriangular;
172 import nl.tudelft.simulation.jstats.streams.MersenneTwister;
173 import nl.tudelft.simulation.jstats.streams.StreamInterface;
174 
175 /**
176  * Simulations regarding LMRS lane change strategies. This entails the base LMRS with:
177  * <ul>
178  * <li>Distributed Tmax</li>
179  * <li>Distributed vGain</li>
180  * <li>Distributed socio-speed sensitivity parameter (LmrsParameters.SOCIO)</li>
181  * <li>Altered gap-acceptance: use own Tmax (GapAcceptance.EGO_HEADWAY) [not required if Tmin/max not distributed]</li>
182  * <li>Altered desired speed: increase during overtaking (SocioDesiredSpeed)</li>
183  * <li>Lane change incentive to get out of the way (IncentiveSocioSpeed)</li>
184  * </ul>
185  * <p>
186  * Copyright (c) 2013-2019 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
187  * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
188  * <p>
189  * @version $Revision$, $LastChangedDate$, by $Author$, initial version 2 mrt. 2018 <br>
190  * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
191  * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
192  * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
193  */
194 public class LmrsStrategies implements EventListenerInterface
195 {
196 
197     /** Simulation time. */
198     static final Time SIMTIME = Time.instantiateSI(3900);
199 
200     /** Truck fraction. */
201     private double fTruck;
202 
203     /** Synchronization. */
204     static final Synchronization SYNCHRONIZATION = Synchronization.PASSIVE;
205 
206     /** Cooperation. */
207     static final Cooperation COOPERATION = Cooperation.PASSIVE;
208 
209     /** Gap-acceptance. */
210     static final GapAcceptance GAPACCEPTANCE = GapAcceptance.INFORMED;
211 
212     /** Use base LMRS. */
213     private boolean baseLMRS;
214 
215     /** Form of tailgating. */
216     private Tailgating tailgating;
217 
218     /** Seed. */
219     private long seed;
220 
221     /** Sigma. */
222     private double sigma;
223 
224     /** vGain [km/h] (after log-normal shift). */
225     private double vGain;
226 
227     /** Maximum headway [s]. */
228     private double tMax;
229 
230     /** Maximum flow [veh/h]. */
231     private double qMax;
232 
233     /** Suffix for file name. */
234     private String suffix;
235 
236     /** Folder to save files. */
237     private String folder;
238 
239     /** Strategical planner factories per GTU type. */
240     private final Map<GTUType, LaneBasedStrategicalPlannerFactory<?>> factories = new LinkedHashMap<>();
241 
242     /** The simulator. */
243     private DEVSSimulatorInterface.TimeDoubleUnit simulator;
244 
245     /** The network. */
246     private OTSRoadNetwork network;
247 
248     /** Autorun. */
249     private boolean autorun;
250 
251     /** List of lane changes. */
252     private List<String> laneChanges = new ArrayList<>();
253 
254     /** Sample data or not. */
255     private boolean sampling;
256 
257     /** Sampler when sampling. */
258     private Sampler<GtuData> sampler;
259 
260     /** GTU colorer. */
261     private static final GTUColorer colorer = SwitchableGTUColorer.builder()
262             .addActiveColorer(new FixedColor(Color.BLUE, "Blue")).addColorer(GTUTypeColorer.DEFAULT)
263             .addColorer(new IDGTUColorer()).addColorer(new SpeedGTUColorer(new Speed(150, SpeedUnit.KM_PER_HOUR)))
264             .addColorer(new DesiredSpeedColorer(new Speed(80, SpeedUnit.KM_PER_HOUR), new Speed(150, SpeedUnit.KM_PER_HOUR)))
265             .addColorer(new AccelerationGTUColorer(Acceleration.instantiateSI(-6.0), Acceleration.instantiateSI(2)))
266             .addColorer(new SynchronizationColorer())
267             .addColorer(new DesiredHeadwayColorer(Duration.instantiateSI(0.5), Duration.instantiateSI(2.0)))
268             .addColorer(new TotalDesireColorer()).addColorer(new IncentiveColorer(IncentiveRoute.class))
269             .addColorer(new IncentiveColorer(IncentiveStayRight.class))
270             .addColorer(new IncentiveColorer(IncentiveSpeedWithCourtesy.class))
271             .addColorer(new IncentiveColorer(IncentiveKeep.class)).addColorer(new IncentiveColorer(IncentiveSocioSpeed.class))
272             .addColorer(new SocialPressureColorer()).build();
273 
274     /**
275      * Main method with command line arguments.
276      * @param args String[]; String[] command line arguments
277      */
278     @SuppressWarnings("unchecked")
279     public static void main(final String[] args)
280     {
281         LaneChange.MIN_LC_LENGTH_FACTOR = 1.0;
282 
283         // default properties
284         boolean autorun = false;
285         String suffix = "";
286         long seed = 1L;
287         double sigma = 0.1; // 0.25;
288         double vGain = 3.3789;
289         // 25km/h -> 3.3789
290         // 35km/h -> 3.7153
291         // 50km/h -> 4.072
292         // 70km/h -> 4.4085
293         // base: 69.6km/h
294         boolean baseLMRS = false;
295         double tMax = 1.6;
296         double fTruck = 0.1;
297         double qMax = 5500;
298         String folder = "D:/";
299         boolean sampling = false;
300         Tailgating tailgating = Tailgating.PRESSURE;
301 
302         boolean vGainSet = false;
303 
304         // parse args
305         for (String arg : args)
306         {
307             int equalsPos = arg.indexOf("=");
308             if (equalsPos >= 0)
309             {
310                 // set something
311                 String key = arg.substring(0, equalsPos);
312                 String value = arg.substring(equalsPos + 1);
313                 if ("autorun".equalsIgnoreCase(key))
314                 {
315                     autorun = Boolean.parseBoolean(value);
316                 }
317                 else if ("suffix".equalsIgnoreCase(key))
318                 {
319                     suffix = value;
320                 }
321                 else if ("seed".equalsIgnoreCase(key))
322                 {
323                     seed = Long.parseLong(value);
324                 }
325                 else if ("sigma".equalsIgnoreCase(key))
326                 {
327                     sigma = Double.parseDouble(value);
328                 }
329                 else if ("vgain".equalsIgnoreCase(key))
330                 {
331                     vGain = Double.parseDouble(value);
332                     vGainSet = true;
333                 }
334                 else if ("baselmrs".equalsIgnoreCase(key))
335                 {
336                     baseLMRS = Boolean.parseBoolean(value);
337                     if (baseLMRS && !vGainSet)
338                     {
339                         vGain = Try.assign(() -> LmrsParameters.VGAIN.getDefaultValue().getInUnit(SpeedUnit.KM_PER_HOUR), "");
340                     }
341                 }
342                 else if ("tmax".equalsIgnoreCase(key))
343                 {
344                     tMax = Double.parseDouble(value);
345                 }
346                 else if ("ftruck".equalsIgnoreCase(key))
347                 {
348                     fTruck = Double.parseDouble(value);
349                 }
350                 else if ("qmax".equalsIgnoreCase(key))
351                 {
352                     qMax = Double.parseDouble(value);
353                 }
354                 else if ("folder".equalsIgnoreCase(key))
355                 {
356                     folder = value;
357                 }
358                 else if ("sampling".equalsIgnoreCase(key))
359                 {
360                     sampling = Boolean.parseBoolean(value);
361                 }
362                 else if ("tailgating".equalsIgnoreCase(key))
363                 {
364                     // overrule for sensitivity analysis
365                     tailgating = value.equalsIgnoreCase("none") ? Tailgating.NONE
366                             : (value.equalsIgnoreCase("pressure") ? Tailgating.PRESSURE : Tailgating.RHO_ONLY);
367                 }
368                 else
369                 {
370                     throw new RuntimeException("Key " + key + " not supported.");
371                 }
372             }
373         }
374         Throw.whenNull(folder, "Provide a folder to save files using a command line argument named 'folder'.");
375 
376         // setup arguments
377         LmrsStrategiesrategies lmrsStrategies = new LmrsStrategies();
378         lmrsStrategies.autorun = autorun;
379         lmrsStrategies.suffix = suffix;
380         lmrsStrategies.seed = seed;
381         lmrsStrategies.sigma = sigma;
382         lmrsStrategies.vGain = vGain;
383         lmrsStrategies.baseLMRS = baseLMRS;
384         lmrsStrategies.tailgating = tailgating;
385         lmrsStrategies.tMax = tMax;
386         lmrsStrategies.fTruck = fTruck;
387         lmrsStrategies.qMax = qMax;
388         lmrsStrategies.folder = folder;
389         lmrsStrategies.sampling = sampling;
390         if (baseLMRS)
391         {
392             lmrsStrategies.incentives =
393                     new Class[] {IncentiveRoute.class, IncentiveSpeedWithCourtesy.class, IncentiveKeep.class};
394         }
395         else
396         {
397             lmrsStrategies.incentives = new Class[] {IncentiveRoute.class, IncentiveSpeedWithCourtesy.class,
398                     IncentiveKeep.class, IncentiveSocioSpeed.class};
399         }
400 
401         // run
402         if (autorun)
403         {
404             try
405             {
406                 OTSSimulator simulator = new OTSSimulator();
407                 final LmrsStrategiesModel lmrsModel = lmrsStrategies.new LmrsStrategiesModel(simulator);
408                 // + 1e-9 is a hack to allow step() to perform detector aggregation of more than 1 detectors -at- the sim end
409                 simulator.initialize(Time.ZERO, Duration.ZERO, Duration.instantiateSI(SIMTIME.si + 1e-9), lmrsModel);
410                 lmrsStrategies.new LmrsStrategiesSimulation(lmrsModel);
411                 double tReport = 60.0;
412                 Time t = simulator.getSimulatorTime();
413                 while (t.le(SIMTIME))
414                 {
415                     simulator.step();
416                     t = simulator.getSimulatorTime();
417                     if (t.si >= tReport)
418                     {
419                         System.out.println("Simulation time is " + t);
420                         tReport += 60.0;
421                     }
422                 }
423                 simulator.stop(); // end of simulation event
424             }
425             catch (Exception exception)
426             {
427                 exception.printStackTrace();
428                 System.exit(-1);
429             }
430         }
431         else
432         {
433             try
434             {
435                 OTSAnimator simulator = new OTSAnimator();
436                 final LmrsStrategiesModel lmrsModel = lmrsStrategies.new LmrsStrategiesModel(simulator);
437                 // + 1e-9 is a hack to allow step() to perform detector aggregation of more than 1 detectors -at- the sim end
438                 simulator.initialize(Time.ZERO, Duration.ZERO, Duration.instantiateSI(SIMTIME.si + 1e-9), lmrsModel);
439                 OTSAnimationPanel animationPanel = new OTSAnimationPanel(lmrsModel.getNetwork().getExtent(),
440                         new Dimension(800, 600), simulator, lmrsModel, LmrsStrategies.colorer, lmrsModel.getNetwork());
441                 lmrsStrategies.new LmrsStrategiesAnimation(lmrsModel, animationPanel);
442             }
443             catch (Exception exception)
444             {
445                 exception.printStackTrace();
446             }
447         }
448     }
449 
450     /**
451      * Simulation without visualization.
452      * <p>
453      * Copyright (c) 2013-2019 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
454      * <br>
455      * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
456      * <p>
457      * @version $Revision$, $LastChangedDate$, by $Author$, initial version 21 mrt. 2018 <br>
458      * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
459      * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
460      * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
461      */
462     class LmrsStrategiesSimulation extends AbstractOTSSimulationApplication
463     {
464         /** */
465         private static final long serialVersionUID = 1L;
466 
467         /**
468          * @param model OTSModelInterface; model
469          */
470         LmrsStrategiesSimulation(final OTSModelInterface model)
471         {
472             super(model);
473         }
474     }
475 
476     /**
477      * Animator.
478      * <p>
479      * Copyright (c) 2013-2019 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
480      * <br>
481      * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
482      * <p>
483      * @version $Revision$, $LastChangedDate$, by $Author$, initial version 3 mrt. 2018 <br>
484      * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
485      * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
486      * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
487      */
488     class LmrsStrategiesAnimation extends OTSSimulationApplication<OTSModelInterface>
489     {
490         /** */
491         private static final long serialVersionUID = 20180303L;
492 
493         /**
494          * @param model OTSModelInterface; the model
495          * @param panel OTSAnimationPanel; the animation panel
496          * @throws OTSDrawingException on animation error
497          */
498         LmrsStrategiesAnimation(final OTSModelInterface model, final OTSAnimationPanel panel) throws OTSDrawingException
499         {
500             super(model, panel);
501         }
502 
503         /** {@inheritDoc} */
504         @Override
505         protected void setAnimationToggles()
506         {
507             AnimationToggles.setIconAnimationTogglesFull(getAnimationPanel());
508             getAnimationPanel().getAnimationPanel().toggleClass(OTSLink.class);
509             getAnimationPanel().getAnimationPanel().toggleClass(OTSNode.class);
510             getAnimationPanel().getAnimationPanel().toggleClass(GtuGeneratorQueue.class);
511             getAnimationPanel().getAnimationPanel().showClass(SpeedSign.class);
512         }
513 
514     }
515 
516     /**
517      * LMRS model.
518      * <p>
519      * Copyright (c) 2013-2019 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
520      * <br>
521      * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
522      * <p>
523      * @version $Revision$, $LastChangedDate$, by $Author$, initial version 3 mrt. 2018 <br>
524      * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
525      * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
526      * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
527      */
528     class LmrsStrategiesModel extends AbstractOTSModel
529     {
530         /**
531          * @param simulator OTSSimulatorInterface; the simulator
532          */
533         LmrsStrategiesModel(final OTSSimulatorInterface simulator)
534         {
535             super(simulator);
536         }
537 
538         /** */
539         private static final long serialVersionUID = 20180303L;
540 
541         /** {@inheritDoc} */
542         @Override
543         @SuppressWarnings({"synthetic-access", "checkstyle:methodlength"})
544         public void constructModel()
545         {
546             LmrsStrategies.this.simulator = getSimulator();
547             OTSRoadNetwork net = new OTSRoadNetwork("LMRS strategies", true);
548             try
549             {
550                 LmrsStrategies.this.simulator.addListener(LmrsStrategies.this, SimulatorInterface.END_REPLICATION_EVENT);
551             }
552             catch (RemoteException exception1)
553             {
554                 exception1.printStackTrace();
555             }
556             LmrsStrategies.this.network = net;
557             net.addListener(LmrsStrategies.this, Network.GTU_ADD_EVENT);
558             net.addListener(LmrsStrategies.this, Network.GTU_REMOVE_EVENT);
559             Map<String, StreamInterface> streams = new LinkedHashMap<>();
560             StreamInterface stream = new MersenneTwister(LmrsStrategies.this.seed);
561             streams.put("generation", stream);
562             getSimulator().getReplication().setStreams(streams);
563 
564             // Vehicle-driver classes
565             // characteristics generator using the input available in this context
566             /** Characteristics generator. */
567             class LmrsStrategyCharacteristicsGenerator implements GTUCharacteristicsGeneratorOD
568             {
569 
570                 /** Distributed maximum speed for trucks. */
571                 private ContinuousDistDoubleScalar.Rel<Speed, SpeedUnit> vTruck;
572 
573                 /**
574                  * Constructor.
575                  * @param strm StreamInterface;
576                  */
577                 LmrsStrategyCharacteristicsGenerator(final StreamInterface strm)
578                 {
579                     this.vTruck = new ContinuousDistDoubleScalar.Rel<>(new DistNormal(strm, 85.0, 2.5), SpeedUnit.KM_PER_HOUR);
580                 }
581 
582                 /** {@inheritDoc} */
583                 @Override
584                 public LaneBasedGTUCharacteristics draw(final Node origin, final Node destination, final Category category,
585                         final StreamInterface randomStream) throws GTUException
586                 {
587                     GTUType gtuType = category.get(GTUType.class);
588                     GTUCharacteristics gtuCharacteristics =
589                             Try.assign(() -> GTUType.defaultCharacteristics(gtuType, LmrsStrategies.this.network, randomStream),
590                                     "Exception while applying default GTU characteristics.");
591                     if (gtuType.equals(LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.TRUCK)))
592                     {
593                         gtuCharacteristics = new GTUCharacteristics(
594                                 LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.TRUCK), gtuCharacteristics.getLength(),
595                                 gtuCharacteristics.getWidth(), this.vTruck.draw(), gtuCharacteristics.getMaximumAcceleration(),
596                                 gtuCharacteristics.getMaximumDeceleration(), gtuCharacteristics.getFront());
597                     }
598                     return new LaneBasedGTUCharacteristics(gtuCharacteristics, LmrsStrategies.this.factories.get(gtuType), null,
599                             origin, destination, VehicleModel.NONE);
600                 }
601             }
602             /** Perception factory. */
603             class LmrsStrategiesPerceptionFactory implements PerceptionFactory
604             {
605                 /** {@inheritDoc} */
606                 @Override
607                 public LanePerception generatePerception(final LaneBasedGTU gtu)
608                 {
609                     LanePerception perception = new CategoricalLanePerception(gtu);
610                     perception.addPerceptionCategory(new DirectEgoPerception<>(perception));
611                     perception.addPerceptionCategory(new DirectInfrastructurePerception(perception));
612                     perception.addPerceptionCategory(new DirectNeighborsPerception(perception, HeadwayGtuType.WRAP));
613                     perception.addPerceptionCategory(new AnticipationTrafficPerception(perception));
614                     return perception;
615                 }
616 
617                 /** {@inheritDoc} */
618                 @Override
619                 public Parameters getParameters() throws ParameterException
620                 {
621                     return new ParameterSet().setDefaultParameter(ParameterTypes.LOOKAHEAD)
622                             .setDefaultParameter(ParameterTypes.LOOKBACKOLD).setDefaultParameter(ParameterTypes.PERCEPTION)
623                             .setDefaultParameter(ParameterTypes.LOOKBACK);
624                 }
625             }
626             PerceptionFactory perceptionFactory = new LmrsStrategiesPerceptionFactory();
627             /** IDM factory with socio speed. */
628             class SocioIDMFactory implements CarFollowingModelFactory<IDMPlus>
629             {
630                 /** {@inheritDoc} */
631                 @Override
632                 public Parameters getParameters() throws ParameterException
633                 {
634                     ParameterSet parameters = new ParameterSet();
635                     parameters.setDefaultParameters(AbstractIDM.class);
636                     return parameters;
637                 }
638 
639                 /** {@inheritDoc} */
640                 @Override
641                 public IDMPlus generateCarFollowingModel()
642                 {
643                     return new IDMPlus(AbstractIDM.HEADWAY, new SocioDesiredSpeed(AbstractIDM.DESIRED_SPEED));
644                 }
645             }
646             // random parameters
647             ParameterFactoryByType parameterFactory = new ParameterFactoryByType();
648             parameterFactory.addParameter(Tailgating.RHO, 0.0);
649             if (!LmrsStrategies.this.baseLMRS)
650             {
651                 parameterFactory.addParameter(LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.CAR),
652                         LmrsParameters.SOCIO, new DistTriangular(stream, 0.0, LmrsStrategies.this.sigma, 1.0));
653                 parameterFactory.addCorrelation(LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.CAR), null,
654                         LmrsParameters.SOCIO, (first, then) -> then <= 1.0 ? then : 1.0);
655                 parameterFactory.addParameter(LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.TRUCK),
656                         LmrsParameters.SOCIO, 1.0);
657                 parameterFactory.addParameter(LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.CAR),
658                         LmrsParameters.VGAIN, new ContinuousDistSpeed(new DistLogNormal(stream, LmrsStrategies.this.vGain, 0.4),
659                                 SpeedUnit.KM_PER_HOUR));
660                 parameterFactory.addParameter(LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.TRUCK),
661                         LmrsParameters.VGAIN, new Speed(50.0, SpeedUnit.KM_PER_HOUR));
662                 parameterFactory.addParameter(ParameterTypes.TMAX, Duration.instantiateSI(LmrsStrategies.this.tMax));
663             }
664             else
665             {
666                 // overrule for sensitivity analysis
667                 parameterFactory.addParameter(LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.CAR),
668                         LmrsParameters.VGAIN, new Speed(LmrsStrategies.this.vGain, SpeedUnit.KM_PER_HOUR));
669             }
670             parameterFactory.addParameter(LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.CAR), ParameterTypes.FSPEED,
671                     new DistNormal(stream, 123.7 / 120.0, 12.0 / 120.0));
672             parameterFactory.addParameter(LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.TRUCK), ParameterTypes.A,
673                     Acceleration.instantiateSI(0.4));
674             parameterFactory.addParameter(LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.TRUCK), ParameterTypes.FSPEED,
675                     1.0);
676 
677             try
678             {
679                 // Strategical factories
680                 for (GTUType gtuType : new GTUType[] {LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.CAR),
681                         LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.TRUCK)})
682                 {
683                     // incentives
684                     Set<MandatoryIncentive> mandatoryIncentives = new LinkedHashSet<>();
685                     Set<VoluntaryIncentive> voluntaryIncentives = new LinkedHashSet<>();
686                     Set<AccelerationIncentive> accelerationIncentives = new LinkedHashSet<>();
687                     mandatoryIncentives.add(new IncentiveRoute());
688                     voluntaryIncentives.add(new IncentiveSpeedWithCourtesy());
689                     voluntaryIncentives.add(new IncentiveKeep()); // before socio-speed and stay-right
690                     if (!LmrsStrategies.this.baseLMRS)
691                     {
692                         voluntaryIncentives.add(new IncentiveSocioSpeed());
693                     }
694                     // accelerationIncentives.add(new AccelerationNoRightOvertake());
695                     if (gtuType.equals(LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.TRUCK)))
696                     {
697                         voluntaryIncentives.add(new IncentiveStayRight());
698                     }
699                     // car-following factory
700                     CarFollowingModelFactory<?> cfFactory = // trucks don't change their desired speed
701                             gtuType.equals(LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.CAR))
702                                     && !LmrsStrategies.this.baseLMRS ? new SocioIDMFactory() : new IDMPlusFactory(stream);
703                     // tailgating
704                     Tailgating tlgt = LmrsStrategies.this.baseLMRS ? Tailgating.NONE : LmrsStrategies.this.tailgating;
705                     // strategical and tactical factory
706                     LaneBasedStrategicalPlannerFactory<?> laneBasedStrategicalPlannerFactory =
707                             new LaneBasedStrategicalRoutePlannerFactory(
708                                     new LMRSFactory(cfFactory, perceptionFactory, SYNCHRONIZATION, COOPERATION, GAPACCEPTANCE,
709                                             tlgt, mandatoryIncentives, voluntaryIncentives, accelerationIncentives),
710                                     parameterFactory);
711                     LmrsStrategies.this.factories.put(gtuType, laneBasedStrategicalPlannerFactory);
712                 }
713 
714                 // Network
715                 OTSPoint3D pointA = new OTSPoint3D(0, 0, 0);
716                 OTSPoint3D pointB = new OTSPoint3D(4000, 0, 0);
717                 OTSPoint3D pointC = new OTSPoint3D(7400, 0, 0);
718                 OTSRoadNode nodeA = new OTSRoadNode(net, "A", pointA, Direction.ZERO);
719                 OTSRoadNode nodeB = new OTSRoadNode(net, "B", pointB, Direction.ZERO);
720                 OTSRoadNode nodeC = new OTSRoadNode(net, "C", pointC, Direction.ZERO);
721                 CrossSectionLink linkAB = new CrossSectionLink(net, "AB", nodeA, nodeB,
722                         LmrsStrategies.this.network.getLinkType(LinkType.DEFAULTS.FREEWAY), new OTSLine3D(pointA, pointB),
723                         getSimulator(), LaneKeepingPolicy.KEEPRIGHT);
724                 CrossSectionLink linkBC = new CrossSectionLink(net, "BC", nodeB, nodeC,
725                         LmrsStrategies.this.network.getLinkType(LinkType.DEFAULTS.FREEWAY), new OTSLine3D(pointB, pointC),
726                         getSimulator(), LaneKeepingPolicy.KEEPRIGHT);
727                 Lane laneAB1 = new Lane(linkAB, "laneAB1", Length.instantiateSI(0.0), Length.instantiateSI(3.5),
728                         LmrsStrategies.this.network.getLaneType(LaneType.DEFAULTS.HIGHWAY),
729                         new Speed(120, SpeedUnit.KM_PER_HOUR));
730                 Lane laneAB2 = new Lane(linkAB, "laneAB2", Length.instantiateSI(3.5), Length.instantiateSI(3.5),
731                         LmrsStrategies.this.network.getLaneType(LaneType.DEFAULTS.HIGHWAY),
732                         new Speed(120, SpeedUnit.KM_PER_HOUR));
733                 Lane laneAB3 = new Lane(linkAB, "laneAB3", Length.instantiateSI(7.0), Length.instantiateSI(3.5),
734                         LmrsStrategies.this.network.getLaneType(LaneType.DEFAULTS.HIGHWAY),
735                         new Speed(120, SpeedUnit.KM_PER_HOUR));
736                 Lane laneBC1 = new Lane(linkBC, "laneBC1", Length.instantiateSI(0.0), Length.instantiateSI(3.5),
737                         LmrsStrategies.this.network.getLaneType(LaneType.DEFAULTS.HIGHWAY),
738                         new Speed(120, SpeedUnit.KM_PER_HOUR));
739                 Lane laneBC2 = new Lane(linkBC, "laneBC2", Length.instantiateSI(3.5), Length.instantiateSI(3.5),
740                         LmrsStrategies.this.network.getLaneType(LaneType.DEFAULTS.HIGHWAY),
741                         new Speed(120, SpeedUnit.KM_PER_HOUR));
742                 Set<GTUType> gtuTypes = new LinkedHashSet<>();
743                 gtuTypes.add(LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.VEHICLE));
744                 Stripe stripeAB1 = new Stripe(linkAB, Length.instantiateSI(-1.75), Length.instantiateSI(-1.75), Length.instantiateSI(0.2));
745                 Stripe stripeAB2 = new Stripe(linkAB, Length.instantiateSI(1.75), Length.instantiateSI(1.75), Length.instantiateSI(0.2),
746                         gtuTypes, Permeable.BOTH);
747                 Stripe stripeAB3 = new Stripe(linkAB, Length.instantiateSI(5.25), Length.instantiateSI(5.25), Length.instantiateSI(0.2),
748                         gtuTypes, Permeable.BOTH);
749                 Stripe stripeAB4 = new Stripe(linkAB, Length.instantiateSI(8.75), Length.instantiateSI(8.75), Length.instantiateSI(0.2),
750                         gtuTypes, Permeable.BOTH);
751                 Stripe stripeBC1 = new Stripe(linkBC, Length.instantiateSI(-1.75), Length.instantiateSI(-1.75), Length.instantiateSI(0.2),
752                         gtuTypes, Permeable.BOTH);
753                 Stripe stripeBC2 = new Stripe(linkBC, Length.instantiateSI(1.75), Length.instantiateSI(1.75), Length.instantiateSI(0.2),
754                         gtuTypes, Permeable.BOTH);
755                 Stripe stripeBC3 = new Stripe(linkBC, Length.instantiateSI(5.25), Length.instantiateSI(5.25), Length.instantiateSI(0.2),
756                         gtuTypes, Permeable.BOTH);
757                 new NodeAnimation(nodeA, getSimulator());
758                 new NodeAnimation(nodeB, getSimulator());
759                 new NodeAnimation(nodeC, getSimulator());
760                 new LinkAnimation(linkAB, getSimulator(), 0.5f);
761                 new LinkAnimation(linkBC, getSimulator(), 0.5f);
762                 new LaneAnimation(laneAB1, getSimulator(), Color.GRAY.brighter());
763                 new LaneAnimation(laneAB2, getSimulator(), Color.GRAY.brighter());
764                 new LaneAnimation(laneAB3, getSimulator(), Color.GRAY.brighter());
765                 new LaneAnimation(laneBC1, getSimulator(), Color.GRAY.brighter());
766                 new LaneAnimation(laneBC2, getSimulator(), Color.GRAY.brighter());
767                 new StripeAnimation(stripeAB1, getSimulator(), TYPE.SOLID);
768                 new StripeAnimation(stripeAB2, getSimulator(), TYPE.DASHED);
769                 new StripeAnimation(stripeAB3, getSimulator(), TYPE.DASHED);
770                 new StripeAnimation(stripeAB4, getSimulator(), TYPE.SOLID);
771                 new StripeAnimation(stripeBC1, getSimulator(), TYPE.SOLID);
772                 new StripeAnimation(stripeBC2, getSimulator(), TYPE.DASHED);
773                 new StripeAnimation(stripeBC3, getSimulator(), TYPE.SOLID);
774                 // sensors
775                 new SinkSensor(laneBC1, laneBC1.getLength().minus(Length.instantiateSI(100.0)), Compatible.EVERYTHING, getSimulator());
776                 new SinkSensor(laneBC2, laneBC2.getLength().minus(Length.instantiateSI(100.0)), Compatible.EVERYTHING, getSimulator());
777 
778                 // detectors
779                 Lane[][] grid =
780                         new Lane[][] {new Lane[] {laneAB3}, new Lane[] {laneAB2, laneBC2}, new Lane[] {laneAB1, laneBC1}};
781                 Duration aggregationPeriod = Duration.instantiateSI(60.0);
782                 DetectorMeasurement<?, ?>[] measurements = new DetectorMeasurement[] {Detector.MEAN_SPEED, Detector.PASSAGES,
783                         new VGainMeasurement(), new SigmaMeasurement(), new VDesMeasurement(), new VDes0Measurement()};
784                 String[] prefix = {"A", "B", "C"};
785                 for (int i = 0; i < grid.length; i++)
786                 {
787                     int num = 1;
788                     Length pos = Length.instantiateSI(100.0);
789                     for (int j = 0; j < grid[i].length; j++)
790                     {
791                         while (pos.lt(grid[i][j].getLength()))
792                         {
793                             new Detector(String.format("%s%02d", prefix[i], num), grid[i][j], pos, Length.ZERO,
794                                     LmrsStrategies.this.simulator, aggregationPeriod, measurements);
795                             num++;
796                             pos = pos.plus(Length.instantiateSI(100.0));
797                         }
798                         pos = pos.minus(grid[i][j].getLength());
799                     }
800                 }
801 
802                 // OD
803                 Categorization categorization = new Categorization("ODExample", GTUType.class);
804                 List<Node> origins = new ArrayList<>();
805                 origins.add(nodeA);
806                 List<Node> destinations = new ArrayList<>();
807                 destinations.add(nodeC);
808                 TimeVector timeVector =
809                         DoubleVector.instantiate(new double[] {0.0, 300.0, 2700.0, SIMTIME.si}, TimeUnit.DEFAULT, StorageType.DENSE);
810                 ODMatrix od = new ODMatrix("LMRS strategies", origins, destinations, categorization, timeVector,
811                         Interpolation.LINEAR);
812                 double q = LmrsStrategies.this.qMax;
813                 FrequencyVector demand =
814                         DoubleVector.instantiate(new double[] {q * .6, q * .6, q, 0.0}, FrequencyUnit.PER_HOUR, StorageType.DENSE);
815                 Category category = new Category(categorization, LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.CAR));
816                 od.putDemandVector(nodeA, nodeC, category, demand, timeVector, Interpolation.LINEAR,
817                         1.0 - LmrsStrategies.this.fTruck);
818                 category = new Category(categorization, LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.TRUCK));
819                 od.putDemandVector(nodeA, nodeC, category, demand, timeVector, Interpolation.LINEAR,
820                         LmrsStrategies.this.fTruck);
821                 // options
822                 MarkovCorrelation<GTUType, Frequency> markov = new MarkovCorrelation<>();
823                 markov.addState(LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.TRUCK), 0.4);
824                 LaneBiases biases = new LaneBiases()
825                         .addBias(LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.VEHICLE), LaneBias.bySpeed(140, 100))
826                         .addBias(LmrsStrategies.this.network.getGtuType(GTUType.DEFAULTS.TRUCK), LaneBias.TRUCK_RIGHT);
827                 ODOptions odOptions = new ODOptions().set(ODOptions.MARKOV, markov)
828                         .set(ODOptions.getLaneBiasOption(LmrsStrategies.this.network), biases)
829                         .set(ODOptions.NO_LC_DIST, Length.instantiateSI(100.0))
830                         .set(ODOptions.INSTANT_LC, true)
831                         .set(ODOptions.GTU_TYPE, new LmrsStrategyCharacteristicsGenerator(stream))
832                         .set(ODOptions.HEADWAY_DIST, HeadwayDistribution.CONSTANT);
833                 Map<String, GeneratorObjects> generatedObjects = ODApplier.applyOD(net, od, getSimulator(), odOptions);
834                 for (String str : generatedObjects.keySet())
835                 {
836                     new GtuGeneratorQueueAnimation(generatedObjects.get(str).getGenerator(), getSimulator());
837                 }
838 
839                 // Sampler
840                 if (LmrsStrategies.this.sampling)
841                 {
842                     LmrsStrategies.this.sampler = new RoadSampler(LmrsStrategies.this.simulator);
843                     addLaneToSampler(laneAB1);
844                     addLaneToSampler(laneAB2);
845                     addLaneToSampler(laneAB3);
846                     addLaneToSampler(laneBC1);
847                     addLaneToSampler(laneBC2);
848                     LmrsStrategies.this.sampler.registerExtendedDataType(new ExtendedDataTypeLength<GtuData>("Length")
849                     {
850                         @Override
851                         public FloatLength getValue(final GtuData gtu)
852                         {
853                             return FloatLength.instantiateSI((float) gtu.getGtu().getLength().si);
854                         }
855                     });
856                     LmrsStrategies.this.sampler.registerExtendedDataType(new ExtendedDataTypeNumber<GtuData>("Rho")
857                     {
858                         @Override
859                         public Float getValue(final GtuData gtu)
860                         {
861                             try
862                             {
863                                 return gtu.getGtu().getParameters().getParameter(Tailgating.RHO).floatValue();
864                             }
865                             catch (ParameterException exception)
866                             {
867                                 throw new RuntimeException("Could not obtain rho for trajectory.", exception);
868                             }
869                         }
870                     });
871                     LmrsStrategies.this.sampler.registerExtendedDataType(new ExtendedDataTypeSpeed<GtuData>("V0")
872                     {
873                         @Override
874                         public FloatSpeed getValue(final GtuData gtu)
875                         {
876                             try
877                             {
878                                 return FloatSpeed.instantiateSI(gtu.getGtu().getDesiredSpeed().floatValue());
879                             }
880                             catch (NullPointerException ex)
881                             {
882                                 return FloatSpeed.NaN;
883                             }
884                         }
885                     });
886                     LmrsStrategies.this.sampler.registerExtendedDataType(new ExtendedDataTypeDuration<GtuData>("T")
887                     {
888                         @Override
889                         public FloatDuration getValue(final GtuData gtu)
890                         {
891                             try
892                             {
893                                 return FloatDuration
894                                         .instantiateSI(gtu.getGtu().getParameters().getParameter(ParameterTypes.T).floatValue());
895                             }
896                             catch (ParameterException exception)
897                             {
898                                 throw new RuntimeException("Could not obtain T for trajectory.", exception);
899                             }
900                         }
901                     });
902                 }
903             }
904             catch (NetworkException | OTSGeometryException | NamingException | ValueRuntimeException | ParameterException
905                     | RemoteException | SimRuntimeException exception)
906             {
907                 exception.printStackTrace();
908             }
909         }
910 
911         /**
912          * Adds a lane to the sampler.
913          * @param lane Lane; lane
914          */
915         @SuppressWarnings("synthetic-access")
916         private void addLaneToSampler(final Lane lane)
917         {
918             LmrsStrategies.this.sampler.registerSpaceTimeRegion(
919                     new SpaceTimeRegion(new KpiLaneDirection(new LaneData(lane), KpiGtuDirectionality.DIR_PLUS), Length.ZERO,
920                             lane.getLength(), Time.instantiateSI(300), SIMTIME));
921         }
922 
923         /** {@inheritDoc} */
924         @SuppressWarnings("synthetic-access")
925         @Override
926         public OTSRoadNetwork getNetwork()
927         {
928             return LmrsStrategies.this.network;
929         }
930 
931     }
932 
933     /** Incentives. */
934     private Class<? extends Incentive>[] incentives;
935 
936     /** {@inheritDoc} */
937     @Override
938     public void notify(final EventInterface event) throws RemoteException
939     {
940         if (event.getType().equals(LaneBasedGTU.LANE_CHANGE_EVENT))
941         {
942             Object[] payload = (Object[]) event.getContent();
943             GTU gtu = this.network.getGTU((String) payload[0]);
944             LateralDirectionality dir = (LateralDirectionality) payload[1];
945             DirectedLanePosition from = (DirectedLanePosition) payload[2];
946             DesireBased desire = (DesireBased) gtu.getTacticalPlanner();
947             Double dMax = Double.NEGATIVE_INFINITY;
948             String cause = "Unknown";
949             for (Class<? extends Incentive> incentive : this.incentives)
950             {
951                 double d = desire.getLatestDesire(incentive).get(dir);
952                 if (d > dMax)
953                 {
954                     cause = incentive.getSimpleName();
955                     dMax = d;
956                 }
957             }
958             this.laneChanges.add(String.format("%.3f,%s,%.3f,%s,%s", this.simulator.getSimulatorTime().si,
959                     from.getLane().getFullId(), from.getPosition().si, dir, cause));
960         }
961         else if (event.getType().equals(Network.GTU_ADD_EVENT))
962         {
963             this.network.getGTU((String) event.getContent()).addListener(this, LaneBasedGTU.LANE_CHANGE_EVENT);
964         }
965         else if (event.getType().equals(Network.GTU_REMOVE_EVENT))
966         {
967             this.network.getGTU((String) event.getContent()).removeListener(this, LaneBasedGTU.LANE_CHANGE_EVENT);
968         }
969         else if (event.getType().equals(SimulatorInterface.END_REPLICATION_EVENT))
970         {
971             CompressionMethod compression = this.autorun ? CompressionMethod.ZIP : CompressionMethod.NONE;
972             // write detector data
973             Detector.writeToFile(this.network, this.folder + "detsAggrData" + LmrsStrategies.this.suffix + ".txt", true, "%.3f",
974                     compression);
975             Detector.writeToFile(this.network, this.folder + "detsMesoData" + LmrsStrategies.this.suffix + ".txt", false,
976                     "%.3f", compression);
977             // write lane change data
978             this.laneChanges.add(0, "t[s],lane,x[m],dir,cause");
979             BufferedWriter bw = CompressedFileWriter.create(this.folder + "laneChanges" + LmrsStrategies.this.suffix + ".txt",
980                     this.autorun);
981             try
982             {
983                 for (String str : this.laneChanges)
984                 {
985                     bw.write(str);
986                     bw.newLine();
987                 }
988             }
989             catch (IOException exception)
990             {
991                 throw new RuntimeException("Could not write to file.", exception);
992             }
993             finally
994             {
995                 try
996                 {
997                     if (bw != null)
998                     {
999                         bw.close();
1000                     }
1001                 }
1002                 catch (IOException ex)
1003                 {
1004                     ex.printStackTrace();
1005                 }
1006             }
1007             // write sampler data
1008             if (LmrsStrategies.this.sampling)
1009             {
1010                 LmrsStrategies.this.sampler.writeToFile(this.folder + "sampled" + LmrsStrategies.this.suffix + ".txt");
1011             }
1012             // solve bug that event is fired twice
1013             LmrsStrategies.this.simulator.removeListener(LmrsStrategies.this, SimulatorInterface.END_REPLICATION_EVENT);
1014             // beep
1015             if (!this.autorun)
1016             {
1017                 Toolkit.getDefaultToolkit().beep();
1018             }
1019             else
1020             {
1021                 System.exit(0);
1022             }
1023         }
1024     }
1025 
1026     /**
1027      * Class to store sigma value.
1028      * <p>
1029      * Copyright (c) 2013-2019 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
1030      * <br>
1031      * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
1032      * <p>
1033      * @version $Revision$, $LastChangedDate$, by $Author$, initial version 3 mei 2018 <br>
1034      * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
1035      * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
1036      * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
1037      */
1038     class SigmaMeasurement implements DetectorMeasurement<List<Double>, List<Double>>
1039     {
1040         /** {@inheritDoc} */
1041         @Override
1042         public List<Double> identity()
1043         {
1044             return new ArrayList<>();
1045         }
1046 
1047         /** {@inheritDoc} */
1048         @Override
1049         public List<Double> accumulateEntry(final List<Double> cumulative, final LaneBasedGTU gtu, final Detector loopDetector)
1050         {
1051             Double sig = gtu.getParameters().getParameterOrNull(LmrsParameters.SOCIO);
1052             if (sig == null)
1053             {
1054                 cumulative.add(Double.NaN);
1055             }
1056             else
1057             {
1058                 cumulative.add(sig);
1059             }
1060             return cumulative;
1061         }
1062 
1063         /** {@inheritDoc} */
1064         @Override
1065         public List<Double> accumulateExit(final List<Double> cumulative, final LaneBasedGTU gtu, final Detector loopDetector)
1066         {
1067             return cumulative;
1068         }
1069 
1070         /** {@inheritDoc} */
1071         @Override
1072         public boolean isPeriodic()
1073         {
1074             return false;
1075         }
1076 
1077         /** {@inheritDoc} */
1078         @Override
1079         public List<Double> aggregate(final List<Double> cumulative, final int count, final Duration aggregation)
1080         {
1081             return cumulative;
1082         }
1083 
1084         /** {@inheritDoc} */
1085         @Override
1086         public String getName()
1087         {
1088             return "sigma";
1089         }
1090 
1091         /** {@inheritDoc} */
1092         @Override
1093         public String stringValue(final List<Double> aggregate, final String format)
1094         {
1095             return Detector.printListDouble(aggregate, format);
1096         }
1097     }
1098 
1099     /**
1100      * Class to store vGain value.
1101      * <p>
1102      * Copyright (c) 2013-2019 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
1103      * <br>
1104      * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
1105      * <p>
1106      * @version $Revision$, $LastChangedDate$, by $Author$, initial version 3 mei 2018 <br>
1107      * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
1108      * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
1109      * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
1110      */
1111     class VGainMeasurement implements DetectorMeasurement<List<Double>, List<Double>>
1112     {
1113         /** {@inheritDoc} */
1114         @Override
1115         public List<Double> identity()
1116         {
1117             return new ArrayList<>();
1118         }
1119 
1120         /** {@inheritDoc} */
1121         @Override
1122         public List<Double> accumulateEntry(final List<Double> cumulative, final LaneBasedGTU gtu, final Detector loopDetector)
1123         {
1124             Speed vGn = gtu.getParameters().getParameterOrNull(LmrsParameters.VGAIN);
1125             if (vGn == null)
1126             {
1127                 cumulative.add(Double.NaN);
1128             }
1129             else
1130             {
1131                 cumulative.add(vGn.si);
1132             }
1133             return cumulative;
1134         }
1135 
1136         /** {@inheritDoc} */
1137         @Override
1138         public List<Double> accumulateExit(final List<Double> cumulative, final LaneBasedGTU gtu, final Detector loopDetector)
1139         {
1140             return cumulative;
1141         }
1142 
1143         /** {@inheritDoc} */
1144         @Override
1145         public boolean isPeriodic()
1146         {
1147             return false;
1148         }
1149 
1150         /** {@inheritDoc} */
1151         @Override
1152         public List<Double> aggregate(final List<Double> cumulative, final int count, final Duration aggregation)
1153         {
1154             return cumulative;
1155         }
1156 
1157         /** {@inheritDoc} */
1158         @Override
1159         public String getName()
1160         {
1161             return "vGain";
1162         }
1163 
1164         /** {@inheritDoc} */
1165         @Override
1166         public String stringValue(final List<Double> aggregate, final String format)
1167         {
1168             return Detector.printListDouble(aggregate, format);
1169         }
1170     }
1171 
1172     /**
1173      * Class to store vDes value.
1174      * <p>
1175      * Copyright (c) 2013-2019 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
1176      * <br>
1177      * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
1178      * <p>
1179      * @version $Revision$, $LastChangedDate$, by $Author$, initial version 3 mei 2018 <br>
1180      * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
1181      * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
1182      * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
1183      */
1184     class VDesMeasurement implements DetectorMeasurement<List<Double>, List<Double>>
1185     {
1186         /** {@inheritDoc} */
1187         @Override
1188         public List<Double> identity()
1189         {
1190             return new ArrayList<>();
1191         }
1192 
1193         /** {@inheritDoc} */
1194         @Override
1195         public List<Double> accumulateEntry(final List<Double> cumulative, final LaneBasedGTU gtu, final Detector loopDetector)
1196         {
1197             Speed vDes = gtu.getDesiredSpeed();
1198             if (vDes == null)
1199             {
1200                 cumulative.add(Double.NaN);
1201             }
1202             else
1203             {
1204                 cumulative.add(vDes.si);
1205             }
1206             return cumulative;
1207         }
1208 
1209         /** {@inheritDoc} */
1210         @Override
1211         public List<Double> accumulateExit(final List<Double> cumulative, final LaneBasedGTU gtu, final Detector loopDetector)
1212         {
1213             return cumulative;
1214         }
1215 
1216         /** {@inheritDoc} */
1217         @Override
1218         public boolean isPeriodic()
1219         {
1220             return false;
1221         }
1222 
1223         /** {@inheritDoc} */
1224         @Override
1225         public List<Double> aggregate(final List<Double> cumulative, final int count, final Duration aggregation)
1226         {
1227             return cumulative;
1228         }
1229 
1230         /** {@inheritDoc} */
1231         @Override
1232         public String getName()
1233         {
1234             return "vDes";
1235         }
1236 
1237         /** {@inheritDoc} */
1238         @Override
1239         public String stringValue(final List<Double> aggregate, final String format)
1240         {
1241             return Detector.printListDouble(aggregate, format);
1242         }
1243     }
1244 
1245     /**
1246      * Class to store vDes value.
1247      * <p>
1248      * Copyright (c) 2013-2019 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
1249      * <br>
1250      * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
1251      * <p>
1252      * @version $Revision$, $LastChangedDate$, by $Author$, initial version 3 mei 2018 <br>
1253      * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
1254      * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
1255      * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
1256      */
1257     class VDes0Measurement implements DetectorMeasurement<List<Double>, List<Double>>
1258     {
1259         /** {@inheritDoc} */
1260         @Override
1261         public List<Double> identity()
1262         {
1263             return new ArrayList<>();
1264         }
1265 
1266         /** {@inheritDoc} */
1267         @Override
1268         public List<Double> accumulateEntry(final List<Double> cumulative, final LaneBasedGTU gtu, final Detector loopDetector)
1269         {
1270             double vDes0;
1271             try
1272             {
1273                 vDes0 = Math.min(gtu.getMaximumSpeed().si, gtu.getParameters().getParameter(ParameterTypes.FSPEED)
1274                         * loopDetector.getLane().getSpeedLimit(gtu.getGTUType()).si);
1275             }
1276             catch (ParameterException | NetworkException exception)
1277             {
1278                 throw new RuntimeException(exception);
1279             }
1280             cumulative.add(vDes0);
1281             return cumulative;
1282         }
1283 
1284         /** {@inheritDoc} */
1285         @Override
1286         public List<Double> accumulateExit(final List<Double> cumulative, final LaneBasedGTU gtu, final Detector loopDetector)
1287         {
1288             return cumulative;
1289         }
1290 
1291         /** {@inheritDoc} */
1292         @Override
1293         public boolean isPeriodic()
1294         {
1295             return false;
1296         }
1297 
1298         /** {@inheritDoc} */
1299         @Override
1300         public List<Double> aggregate(final List<Double> cumulative, final int count, final Duration aggregation)
1301         {
1302             return cumulative;
1303         }
1304 
1305         /** {@inheritDoc} */
1306         @Override
1307         public String getName()
1308         {
1309             return "vDes0";
1310         }
1311 
1312         /** {@inheritDoc} */
1313         @Override
1314         public String stringValue(final List<Double> aggregate, final String format)
1315         {
1316             return Detector.printListDouble(aggregate, format);
1317         }
1318     }
1319 
1320 }