View Javadoc
1   package org.opentrafficsim.ahfe;
2   
3   import java.awt.Color;
4   import java.io.IOException;
5   import java.io.InputStream;
6   import java.util.ArrayList;
7   import java.util.LinkedHashSet;
8   import java.util.List;
9   import java.util.Set;
10  
11  import javax.naming.NamingException;
12  import javax.xml.parsers.ParserConfigurationException;
13  
14  import org.djunits.unit.FrequencyUnit;
15  import org.djunits.unit.SpeedUnit;
16  import org.djunits.unit.TimeUnit;
17  import org.djunits.value.StorageType;
18  import org.djunits.value.ValueException;
19  import org.djunits.value.vdouble.scalar.Acceleration;
20  import org.djunits.value.vdouble.scalar.Duration;
21  import org.djunits.value.vdouble.scalar.Length;
22  import org.djunits.value.vdouble.scalar.Speed;
23  import org.djunits.value.vdouble.vector.FrequencyVector;
24  import org.djunits.value.vdouble.vector.TimeVector;
25  import org.djutils.io.URLResource;
26  import org.opentrafficsim.base.parameters.ParameterException;
27  import org.opentrafficsim.base.parameters.ParameterTypes;
28  import org.opentrafficsim.base.parameters.Parameters;
29  import org.opentrafficsim.core.animation.gtu.colorer.AccelerationGTUColorer;
30  import org.opentrafficsim.core.animation.gtu.colorer.SpeedGTUColorer;
31  import org.opentrafficsim.core.animation.gtu.colorer.SwitchableGTUColorer;
32  import org.opentrafficsim.core.dsol.OTSSimulatorInterface;
33  import org.opentrafficsim.core.geometry.OTSGeometryException;
34  import org.opentrafficsim.core.gtu.AbstractGTU;
35  import org.opentrafficsim.core.gtu.GTUException;
36  import org.opentrafficsim.core.gtu.GTUType;
37  import org.opentrafficsim.core.gtu.behavioralcharacteristics.ParameterFactoryByType;
38  import org.opentrafficsim.core.gtu.perception.DirectEgoPerception;
39  import org.opentrafficsim.core.network.NetworkException;
40  import org.opentrafficsim.core.network.Node;
41  import org.opentrafficsim.core.network.OTSNetwork;
42  import org.opentrafficsim.core.perception.HistoryManagerDEVS;
43  import org.opentrafficsim.kpi.interfaces.LaneDataInterface;
44  import org.opentrafficsim.kpi.sampling.KpiGtuDirectionality;
45  import org.opentrafficsim.kpi.sampling.KpiLaneDirection;
46  import org.opentrafficsim.kpi.sampling.SpaceTimeRegion;
47  import org.opentrafficsim.road.gtu.colorer.DesiredHeadwayColorer;
48  import org.opentrafficsim.road.gtu.colorer.DesiredSpeedColorer;
49  import org.opentrafficsim.road.gtu.colorer.FixedColor;
50  import org.opentrafficsim.road.gtu.colorer.GTUTypeColorer;
51  import org.opentrafficsim.road.gtu.colorer.IncentiveColorer;
52  import org.opentrafficsim.road.gtu.colorer.SynchronizationColorer;
53  import org.opentrafficsim.road.gtu.colorer.TaskSaturationColorer;
54  import org.opentrafficsim.road.gtu.colorer.TotalDesireColorer;
55  import org.opentrafficsim.road.gtu.generator.od.DefaultGTUCharacteristicsGeneratorOD;
56  import org.opentrafficsim.road.gtu.generator.od.ODApplier;
57  import org.opentrafficsim.road.gtu.generator.od.ODOptions;
58  import org.opentrafficsim.road.gtu.generator.od.StrategicalPlannerFactorySupplierOD;
59  import org.opentrafficsim.road.gtu.lane.LaneBasedGTU;
60  import org.opentrafficsim.road.gtu.lane.perception.CategoricalLanePerception;
61  import org.opentrafficsim.road.gtu.lane.perception.LanePerception;
62  import org.opentrafficsim.road.gtu.lane.perception.PerceptionFactory;
63  import org.opentrafficsim.road.gtu.lane.perception.categories.AnticipationTrafficPerception;
64  import org.opentrafficsim.road.gtu.lane.perception.categories.DirectInfrastructurePerception;
65  import org.opentrafficsim.road.gtu.lane.perception.categories.neighbors.Anticipation;
66  import org.opentrafficsim.road.gtu.lane.perception.categories.neighbors.DirectNeighborsPerception;
67  import org.opentrafficsim.road.gtu.lane.perception.categories.neighbors.Estimation;
68  import org.opentrafficsim.road.gtu.lane.perception.categories.neighbors.HeadwayGtuType.PerceivedHeadwayGtuType;
69  import org.opentrafficsim.road.gtu.lane.perception.mental.AdaptationHeadway;
70  import org.opentrafficsim.road.gtu.lane.perception.mental.AdaptationSituationalAwareness;
71  import org.opentrafficsim.road.gtu.lane.perception.mental.Fuller;
72  import org.opentrafficsim.road.gtu.lane.perception.mental.Fuller.BehavioralAdaptation;
73  import org.opentrafficsim.road.gtu.lane.perception.mental.Fuller.Task;
74  import org.opentrafficsim.road.gtu.lane.perception.mental.TaskCarFollowing;
75  import org.opentrafficsim.road.gtu.lane.perception.mental.TaskLaneChanging;
76  import org.opentrafficsim.road.gtu.lane.perception.mental.TaskLaneChanging.LateralConsideration;
77  import org.opentrafficsim.road.gtu.lane.perception.mental.TaskRoadSideDistraction;
78  import org.opentrafficsim.road.gtu.lane.plan.operational.LaneOperationalPlanBuilder;
79  import org.opentrafficsim.road.gtu.lane.tactical.following.IDMPlusFactory;
80  import org.opentrafficsim.road.gtu.lane.tactical.lmrs.AccelerationIncentive;
81  import org.opentrafficsim.road.gtu.lane.tactical.lmrs.DefaultLMRSPerceptionFactory;
82  import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveCourtesy;
83  import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveGetInLane;
84  import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveKeep;
85  import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveRoute;
86  import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveSocioSpeed;
87  import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveSpeed;
88  import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveSpeedWithCourtesy;
89  import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveStayRight;
90  import org.opentrafficsim.road.gtu.lane.tactical.lmrs.LMRSFactory;
91  import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.Cooperation;
92  import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.GapAcceptance;
93  import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.MandatoryIncentive;
94  import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.Synchronization;
95  import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.Tailgating;
96  import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.VoluntaryIncentive;
97  import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalPlannerFactory;
98  import org.opentrafficsim.road.gtu.strategical.od.Categorization;
99  import org.opentrafficsim.road.gtu.strategical.od.Category;
100 import org.opentrafficsim.road.gtu.strategical.od.Interpolation;
101 import org.opentrafficsim.road.gtu.strategical.od.ODMatrix;
102 import org.opentrafficsim.road.gtu.strategical.route.LaneBasedStrategicalRoutePlannerFactory;
103 import org.opentrafficsim.road.network.factory.xml.XmlNetworkLaneParser;
104 import org.opentrafficsim.road.network.lane.CrossSectionLink;
105 import org.opentrafficsim.road.network.lane.object.Distraction;
106 import org.opentrafficsim.road.network.lane.object.Distraction.TrapezoidProfile;
107 import org.opentrafficsim.road.network.sampling.LinkData;
108 import org.opentrafficsim.road.network.sampling.RoadSampler;
109 import org.opentrafficsim.road.network.sampling.data.TimeToCollision;
110 import org.opentrafficsim.swing.script.AbstractSimulationScript;
111 import org.xml.sax.SAXException;
112 
113 import nl.tudelft.simulation.dsol.SimRuntimeException;
114 import nl.tudelft.simulation.jstats.streams.StreamInterface;
115 
116 /**
117  * Distraction simulation.
118  * <p>
119  * Copyright (c) 2013-2019 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
120  * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
121  * <p>
122  * @version $Revision$, $LastChangedDate$, by $Author$, initial version 9 apr. 2018 <br>
123  * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
124  * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
125  * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
126  */
127 public final class DistractionScript extends AbstractSimulationScript
128 {
129 
130     /** Distance to not consider at start of the network. */
131     private static Length ignoreStart = Length.createSI(2900); // Not 100m on pre-link, so 3000 total
132 
133     /** Distance to not consider at end of the network. */
134     private static Length ignoreEnd = Length.createSI(1000);
135 
136     /** Sampler. */
137     private RoadSampler sampler;
138 
139     /**
140      * Main method.
141      * @param args String[]; command line arguments
142      */
143     public static void main(final String[] args)
144     {
145         // Long start = System.currentTimeMillis();
146         DistractionScript script = new DistractionScript(args);
147         // script.setProperty("autorun", true);
148         script.start();
149         // Long end = System.currentTimeMillis();
150         // System.out.println("That took " + (end - start) / 1000 + "s.");
151     }
152 
153     /**
154      * Constructor.
155      * @param properties String[]; properties as name-value pairs
156      */
157     private DistractionScript(final String[] properties)
158     {
159         super("Distraction", "Distraction simulation", properties);
160         setGtuColorer(SwitchableGTUColorer.builder().addActiveColorer(new FixedColor(Color.BLUE, "Blue"))
161                 .addColorer(GTUTypeColorer.DEFAULT).addColorer(new SpeedGTUColorer(new Speed(150, SpeedUnit.KM_PER_HOUR)))
162                 .addColorer(
163                         new DesiredSpeedColorer(new Speed(50, SpeedUnit.KM_PER_HOUR), new Speed(150, SpeedUnit.KM_PER_HOUR)))
164                 .addColorer(new AccelerationGTUColorer(Acceleration.createSI(-6.0), Acceleration.createSI(2)))
165                 .addColorer(new SynchronizationColorer())
166                 .addColorer(new DesiredHeadwayColorer(Duration.createSI(0.56), Duration.createSI(2.4)))
167                 .addColorer(new TotalDesireColorer()).addColorer(new IncentiveColorer(IncentiveRoute.class))
168                 .addColorer(new IncentiveColorer(IncentiveSpeedWithCourtesy.class))
169                 .addColorer(new IncentiveColorer(IncentiveSpeed.class)).addColorer(new IncentiveColorer(IncentiveKeep.class))
170                 .addColorer(new IncentiveColorer(IncentiveGetInLane.class))
171                 .addColorer(new IncentiveColorer(IncentiveCourtesy.class))
172                 .addColorer(new IncentiveColorer(IncentiveSocioSpeed.class)).addColorer(new TaskSaturationColorer()).build());
173     }
174 
175     /** {@inheritDoc} */
176     @Override
177     protected void setDefaultProperties()
178     {
179         setProperty("fTruck", "0.05");
180         setProperty("leftDemand", "3500");
181         setProperty("rightDemand", "3200");
182         setProperty("sampler", "true");
183         setProperty("warmupTime", "360");
184         setProperty("simulationTime", "3960");
185         setProperty("scenario", "test");
186     }
187 
188     /** {@inheritDoc} */
189     @Override
190     protected void onSimulationEnd()
191     {
192         if (this.sampler != null)
193         {
194             this.sampler.writeToFile(getProperty("outputDir") + getProperty("scenario") + ".csv");
195         }
196     }
197 
198     /** {@inheritDoc} */
199     @Override
200     protected OTSNetwork setupSimulation(final OTSSimulatorInterface sim) throws Exception
201     {
202         AbstractGTU.ALIGNED = false;
203         LaneOperationalPlanBuilder.INSTANT_LANE_CHANGES = true;
204 
205         // Network
206         InputStream stream = URLResource.getResourceAsStream("/AHFE/Network.xml");
207         XmlNetworkLaneParser nlp = new XmlNetworkLaneParser(sim);
208         OTSNetwork network = new OTSNetwork("Distraction");
209         try
210         {
211             nlp.build(stream, network, false);
212         }
213         catch (NetworkException | ParserConfigurationException | SAXException | IOException | NamingException | GTUException
214                 | OTSGeometryException | ValueException | ParameterException | SimRuntimeException exception)
215         {
216             exception.printStackTrace();
217         }
218         new Distraction("distraction", ((CrossSectionLink) network.getLink("END")).getLanes().get(0), Length.createSI(1000),
219                 sim, new TrapezoidProfile(0.2, Length.createSI(-400), Length.createSI(200), Length.createSI(400)));
220 
221         // OD
222         List<Node> origins = new ArrayList<>();
223         origins.add(network.getNode("LEFTINPRE"));
224         origins.add(network.getNode("RIGHTINPRE"));
225         List<Node> destinations = new ArrayList<>();
226         destinations.add(network.getNode("EXIT"));
227         Categorization categorization = new Categorization("Distraction", GTUType.class);
228         TimeVector globalTime =
229                 new TimeVector(new double[] { 0, 360, 1560, 2160, 3960 }, TimeUnit.BASE_SECOND, StorageType.DENSE);
230         ODMatrix od = new ODMatrix("Distraction", origins, destinations, categorization, globalTime, Interpolation.LINEAR);
231         Category carCategory = new Category(categorization, GTUType.CAR);
232         Category truckCategory = new Category(categorization, GTUType.TRUCK);
233         double fTruck = getDoubleProperty("fTruck");
234         double demandLeft = getDoubleProperty("leftDemand");
235         double demandRight = getDoubleProperty("rightDemand");
236         FrequencyVector leftDemandPatternCar = getDemand(demandLeft * (1.0 - fTruck));
237         FrequencyVector leftDemandPatternTruck = getDemand(demandLeft * fTruck);
238         FrequencyVector rightDemandPatternCar = getDemand(demandRight * (1.0 - fTruck));
239         FrequencyVector rightDemandPatternTruck = getDemand(demandRight * fTruck);
240         od.putDemandVector(network.getNode("LEFTINPRE"), network.getNode("EXIT"), carCategory, leftDemandPatternCar);
241         od.putDemandVector(network.getNode("LEFTINPRE"), network.getNode("EXIT"), truckCategory, leftDemandPatternTruck);
242         od.putDemandVector(network.getNode("RIGHTINPRE"), network.getNode("EXIT"), carCategory, rightDemandPatternCar);
243         od.putDemandVector(network.getNode("RIGHTINPRE"), network.getNode("EXIT"), truckCategory, rightDemandPatternTruck);
244         ODOptions odOptions = new ODOptions().set(ODOptions.GTU_TYPE,
245                 new DefaultGTUCharacteristicsGeneratorOD(new DistractionFactorySupplier()));
246         ODApplier.applyOD(network, od, sim, odOptions);
247 
248         // History
249         sim.getReplication().setHistoryManager(new HistoryManagerDEVS(sim, Duration.createSI(2.0), Duration.createSI(1.0)));
250 
251         // Sampler
252         this.sampler = new RoadSampler(sim);
253         this.sampler.registerExtendedDataType(new TimeToCollision());
254         LinkData linkData = new LinkData((CrossSectionLink) network.getLink("LEFTIN"));
255         registerLinkToSampler(linkData, ignoreStart, linkData.getLength());
256         linkData = new LinkData((CrossSectionLink) network.getLink("RIGHTIN"));
257         registerLinkToSampler(linkData, ignoreStart, linkData.getLength());
258         linkData = new LinkData((CrossSectionLink) network.getLink("CONVERGE"));
259         registerLinkToSampler(linkData, Length.ZERO, linkData.getLength());
260         linkData = new LinkData((CrossSectionLink) network.getLink("WEAVING"));
261         registerLinkToSampler(linkData, Length.ZERO, linkData.getLength());
262         linkData = new LinkData((CrossSectionLink) network.getLink("END"));
263         registerLinkToSampler(linkData, Length.ZERO, linkData.getLength().minus(ignoreEnd));
264 
265         // return
266         animateNetwork(network, true);
267         return network;
268     }
269 
270     /**
271      * Register a link to the sampler, so data is sampled there.
272      * @param linkData LinkData; link data
273      * @param startDistance Length; start distance on link
274      * @param endDistance Length; end distance on link
275      */
276     private void registerLinkToSampler(final LinkData linkData, final Length startDistance, final Length endDistance)
277     {
278         for (LaneDataInterface laneData : linkData.getLaneDatas())
279         {
280             Length start = laneData.getLength().multiplyBy(startDistance.si / linkData.getLength().si);
281             Length end = laneData.getLength().multiplyBy(endDistance.si / linkData.getLength().si);
282             this.sampler
283                     .registerSpaceTimeRegion(new SpaceTimeRegion(new KpiLaneDirection(laneData, KpiGtuDirectionality.DIR_PLUS),
284                             start, end, getTimeProperty("warmupTime"), getTimeProperty("simulationTime")));
285         }
286     }
287 
288     /**
289      * Compose demand vector.
290      * @param demand double; maximum demand value
291      * @return FrequencyVector demand vector
292      * @throws ValueException on value exception
293      */
294     private static FrequencyVector getDemand(final double demand) throws ValueException
295     {
296         return new FrequencyVector(new double[] { demand * 0.5, demand * 0.5, demand, demand, 0.0 }, FrequencyUnit.PER_HOUR,
297                 StorageType.DENSE);
298     }
299 
300     /**
301      * Supplier of strategical factory.
302      * <p>
303      * Copyright (c) 2013-2019 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
304      * <br>
305      * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
306      * <p>
307      * @version $Revision$, $LastChangedDate$, by $Author$, initial version 9 apr. 2018 <br>
308      * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
309      * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
310      * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
311      */
312     private class DistractionFactorySupplier implements StrategicalPlannerFactorySupplierOD
313     {
314         /** */
315         DistractionFactorySupplier()
316         {
317         }
318 
319         /** {@inheritDoc} */
320         @Override
321         public LaneBasedStrategicalPlannerFactory<?> getFactory(final Node origin, final Node destination,
322                 final Category category, final StreamInterface randomStream) throws GTUException
323         {
324             IDMPlusFactory idm = new IDMPlusFactory(randomStream);
325             PerceptionFactory perc = new DefaultLMRSPerceptionFactory()
326             {
327                 @Override
328                 public LanePerception generatePerception(final LaneBasedGTU gtu)
329                 {
330                     Set<Task> tasks = new LinkedHashSet<>();
331                     tasks.add(new TaskCarFollowing());
332                     tasks.add(new TaskLaneChanging(LateralConsideration.DESIRE));
333                     tasks.add(new TaskRoadSideDistraction());
334                     Set<BehavioralAdaptation> adaptations = new LinkedHashSet<>();
335                     adaptations.add(new AdaptationSituationalAwareness());
336                     adaptations.add(new AdaptationHeadway());
337                     LanePerception perception = new CategoricalLanePerception(gtu, new Fuller(tasks, adaptations));
338                     perception.addPerceptionCategory(new DirectEgoPerception(perception));
339                     perception.addPerceptionCategory(new DirectInfrastructurePerception(perception));
340                     perception.addPerceptionCategory(new DirectNeighborsPerception(perception,
341                             new PerceivedHeadwayGtuType(Estimation.UNDERESTIMATION, Anticipation.CONSTANT_SPEED)));
342                     perception.addPerceptionCategory(new AnticipationTrafficPerception(perception));
343                     return perception;
344                 }
345 
346                 @Override
347                 public Parameters getParameters() throws ParameterException
348                 {
349                     Parameters params = super.getParameters();
350                     params.setParameter(Fuller.TC, 1.0);
351                     params.setParameter(Fuller.TS_CRIT, 0.8);
352                     params.setParameter(Fuller.TS_MAX, 2.0);
353                     params.setParameter(AdaptationSituationalAwareness.SA_MAX, 1.0);
354                     params.setParameter(AdaptationSituationalAwareness.SA_MIN, 0.5);
355                     params.setParameter(AdaptationSituationalAwareness.TR_MAX, Duration.createSI(2.0));
356                     params.setParameter(ParameterTypes.TR, Duration.ZERO);
357                     params.setParameter(AdaptationHeadway.BETA_T, 1.0);
358                     return params;
359                 }
360             };
361             ParameterFactoryByType params = new ParameterFactoryByType();
362             Set<MandatoryIncentive> mandatoryIncentives = new LinkedHashSet<>();
363             mandatoryIncentives.add(new IncentiveRoute());
364             Set<VoluntaryIncentive> voluntaryIncentives = new LinkedHashSet<>();
365             voluntaryIncentives.add(new IncentiveSpeedWithCourtesy());
366             voluntaryIncentives.add(new IncentiveKeep());
367             if (category.getCategorization().entails(GTUType.class) && category.get(GTUType.class).isOfType(GTUType.TRUCK))
368             {
369                 voluntaryIncentives.add(new IncentiveStayRight());
370                 params.addParameter(GTUType.TRUCK, ParameterTypes.A, Acceleration.createSI(0.8));
371             }
372             Set<AccelerationIncentive> accelerationIncentives = new LinkedHashSet<>();
373             return new LaneBasedStrategicalRoutePlannerFactory(
374                     new LMRSFactory(idm, perc, Synchronization.PASSIVE, Cooperation.PASSIVE, GapAcceptance.INFORMED,
375                             Tailgating.NONE, mandatoryIncentives, voluntaryIncentives, accelerationIncentives),
376                     params);
377         }
378     }
379 
380 }