View Javadoc
1   package 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.opentrafficsim.base.parameters.ParameterException;
26  import org.opentrafficsim.base.parameters.ParameterTypes;
27  import org.opentrafficsim.base.parameters.Parameters;
28  import org.opentrafficsim.core.geometry.OTSGeometryException;
29  import org.opentrafficsim.core.gtu.AbstractGTU;
30  import org.opentrafficsim.core.gtu.GTUException;
31  import org.opentrafficsim.core.gtu.GTUType;
32  import org.opentrafficsim.core.gtu.animation.AccelerationGTUColorer;
33  import org.opentrafficsim.core.gtu.animation.SpeedGTUColorer;
34  import org.opentrafficsim.core.gtu.animation.SwitchableGTUColorer;
35  import org.opentrafficsim.core.gtu.behavioralcharacteristics.ParameterFactoryByType;
36  import org.opentrafficsim.core.gtu.perception.DirectEgoPerception;
37  import org.opentrafficsim.core.network.NetworkException;
38  import org.opentrafficsim.core.network.Node;
39  import org.opentrafficsim.core.network.OTSNetwork;
40  import org.opentrafficsim.core.perception.HistoryManager;
41  import org.opentrafficsim.core.perception.HistoryManagerDEVS;
42  import org.opentrafficsim.kpi.interfaces.LaneDataInterface;
43  import org.opentrafficsim.kpi.sampling.KpiGtuDirectionality;
44  import org.opentrafficsim.kpi.sampling.KpiLaneDirection;
45  import org.opentrafficsim.kpi.sampling.SpaceTimeRegion;
46  import org.opentrafficsim.road.animation.AbstractSimulationScript;
47  import org.opentrafficsim.road.gtu.animation.DesiredHeadwayColorer;
48  import org.opentrafficsim.road.gtu.animation.DesiredSpeedColorer;
49  import org.opentrafficsim.road.gtu.animation.FixedColor;
50  import org.opentrafficsim.road.gtu.animation.GTUTypeColorer;
51  import org.opentrafficsim.road.gtu.animation.IncentiveColorer;
52  import org.opentrafficsim.road.gtu.animation.SynchronizationColorer;
53  import org.opentrafficsim.road.gtu.animation.TaskSaturationColorer;
54  import org.opentrafficsim.road.gtu.animation.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.Anticipation;
64  import org.opentrafficsim.road.gtu.lane.perception.categories.AnticipationTrafficPerception;
65  import org.opentrafficsim.road.gtu.lane.perception.categories.DirectInfrastructurePerception;
66  import org.opentrafficsim.road.gtu.lane.perception.categories.DirectNeighborsPerception;
67  import org.opentrafficsim.road.gtu.lane.perception.categories.Estimation;
68  import org.opentrafficsim.road.gtu.lane.perception.categories.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.xml.sax.SAXException;
111 
112 import nl.tudelft.simulation.dsol.SimRuntimeException;
113 import nl.tudelft.simulation.dsol.simulators.DEVSSimulatorInterface;
114 import nl.tudelft.simulation.jstats.streams.StreamInterface;
115 import nl.tudelft.simulation.language.io.URLResource;
116 
117 /**
118  * Distraction simulation.
119  * <p>
120  * Copyright (c) 2013-2018 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
121  * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
122  * <p>
123  * @version $Revision$, $LastChangedDate$, by $Author$, initial version 9 apr. 2018 <br>
124  * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
125  * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
126  * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
127  */
128 public final class DistractionScript extends AbstractSimulationScript
129 {
130 
131     /** Distance to not consider at start of the network. */
132     private static Length ignoreStart = Length.createSI(2900); // Not 100m on pre-link, so 3000 total
133 
134     /** Distance to not consider at end of the network. */
135     private static Length ignoreEnd = Length.createSI(1000);
136 
137     /** Sampler. */
138     private RoadSampler sampler;
139 
140     /**
141      * Main method.
142      * @param args String[]; command line arguments
143      */
144     public static void main(final String[] args)
145     {
146         // Long start = System.currentTimeMillis();
147         DistractionScript script = new DistractionScript(args);
148         // script.setProperty("autorun", true);
149         script.start();
150         // Long end = System.currentTimeMillis();
151         // System.out.println("That took " + (end - start) / 1000 + "s.");
152     }
153 
154     /**
155      * Constructor.
156      * @param properties String[]; properties as name-value pairs
157      */
158     private DistractionScript(final String[] properties)
159     {
160         super("Distraction", "Distraction simulation", properties);
161         setGtuColorer(SwitchableGTUColorer.builder().addActiveColorer(new FixedColor(Color.BLUE, "Blue"))
162                 .addColorer(GTUTypeColorer.DEFAULT).addColorer(new SpeedGTUColorer(new Speed(150, SpeedUnit.KM_PER_HOUR)))
163                 .addColorer(
164                         new DesiredSpeedColorer(new Speed(50, SpeedUnit.KM_PER_HOUR), new Speed(150, SpeedUnit.KM_PER_HOUR)))
165                 .addColorer(new AccelerationGTUColorer(Acceleration.createSI(-6.0), Acceleration.createSI(2)))
166                 .addColorer(new SynchronizationColorer())
167                 .addColorer(new DesiredHeadwayColorer(Duration.createSI(0.56), Duration.createSI(2.4)))
168                 .addColorer(new TotalDesireColorer()).addColorer(new IncentiveColorer(IncentiveRoute.class))
169                 .addColorer(new IncentiveColorer(IncentiveSpeedWithCourtesy.class))
170                 .addColorer(new IncentiveColorer(IncentiveSpeed.class)).addColorer(new IncentiveColorer(IncentiveKeep.class))
171                 .addColorer(new IncentiveColorer(IncentiveGetInLane.class))
172                 .addColorer(new IncentiveColorer(IncentiveCourtesy.class))
173                 .addColorer(new IncentiveColorer(IncentiveSocioSpeed.class)).addColorer(new TaskSaturationColorer()).build());
174     }
175 
176     /** {@inheritDoc} */
177     @Override
178     protected void setDefaultProperties()
179     {
180         setProperty("fTruck", "0.05");
181         setProperty("leftDemand", "3500");
182         setProperty("rightDemand", "3200");
183         setProperty("sampler", "true");
184         setProperty("warmupTime", "360");
185         setProperty("simulationTime", "3960");
186         setProperty("scenario", "test");
187     }
188 
189     /** {@inheritDoc} */
190     @Override
191     protected void onSimulationEnd()
192     {
193         if (this.sampler != null)
194         {
195             this.sampler.writeToFile(getProperty("outputDir") + getProperty("scenario") + ".csv");
196         }
197     }
198 
199     /** {@inheritDoc} */
200     @Override
201     protected OTSNetwork setupSimulation(final DEVSSimulatorInterface.TimeDoubleUnit sim) throws Exception
202     {
203         AbstractGTU.ALIGNED = false;
204         LaneOperationalPlanBuilder.INSTANT_LANE_CHANGES = true;
205 
206         // Network
207         InputStream stream = URLResource.getResourceAsStream("/AHFE/Network.xml");
208         XmlNetworkLaneParser nlp = new XmlNetworkLaneParser(sim);
209         OTSNetwork network = new OTSNetwork("Distraction");
210         try
211         {
212             nlp.build(stream, network, false);
213         }
214         catch (NetworkException | ParserConfigurationException | SAXException | IOException | NamingException | GTUException
215                 | OTSGeometryException | ValueException | ParameterException | SimRuntimeException exception)
216         {
217             exception.printStackTrace();
218         }
219         new Distraction("distraction", ((CrossSectionLink) network.getLink("END")).getLanes().get(0), Length.createSI(1000),
220                 sim, new TrapezoidProfile(0.2, Length.createSI(-400), Length.createSI(200), Length.createSI(400)));
221 
222         // OD
223         List<Node> origins = new ArrayList<>();
224         origins.add(network.getNode("LEFTINPRE"));
225         origins.add(network.getNode("RIGHTINPRE"));
226         List<Node> destinations = new ArrayList<>();
227         destinations.add(network.getNode("EXIT"));
228         Categorization categorization = new Categorization("Distraction", GTUType.class);
229         TimeVector globalTime =
230                 new TimeVector(new double[] { 0, 360, 1560, 2160, 3960 }, TimeUnit.BASE_SECOND, StorageType.DENSE);
231         ODMatrix od = new ODMatrix("Distraction", origins, destinations, categorization, globalTime, Interpolation.LINEAR);
232         Category carCategory = new Category(categorization, GTUType.CAR);
233         Category truckCategory = new Category(categorization, GTUType.TRUCK);
234         double fTruck = getDoubleProperty("fTruck");
235         double demandLeft = getDoubleProperty("leftDemand");
236         double demandRight = getDoubleProperty("rightDemand");
237         FrequencyVector leftDemandPatternCar = getDemand(demandLeft * (1.0 - fTruck));
238         FrequencyVector leftDemandPatternTruck = getDemand(demandLeft * fTruck);
239         FrequencyVector rightDemandPatternCar = getDemand(demandRight * (1.0 - fTruck));
240         FrequencyVector rightDemandPatternTruck = getDemand(demandRight * fTruck);
241         od.putDemandVector(network.getNode("LEFTINPRE"), network.getNode("EXIT"), carCategory, leftDemandPatternCar);
242         od.putDemandVector(network.getNode("LEFTINPRE"), network.getNode("EXIT"), truckCategory, leftDemandPatternTruck);
243         od.putDemandVector(network.getNode("RIGHTINPRE"), network.getNode("EXIT"), carCategory, rightDemandPatternCar);
244         od.putDemandVector(network.getNode("RIGHTINPRE"), network.getNode("EXIT"), truckCategory, rightDemandPatternTruck);
245         ODOptions odOptions = new ODOptions().set(ODOptions.ANIMATION, true).set(ODOptions.GTU_COLORER, getGtuColorer())
246                 .set(ODOptions.GTU_TYPE, new DefaultGTUCharacteristicsGeneratorOD(new DistractionFactorySupplier()));
247         ODApplier.applyOD(network, od, sim, odOptions);
248 
249         // History
250         HistoryManager.set(new HistoryManagerDEVS(sim, Duration.createSI(2.0), Duration.createSI(1.0)), sim);
251 
252         // Sampler
253         this.sampler = new RoadSampler(sim);
254         this.sampler.registerExtendedDataType(new TimeToCollision());
255         LinkData linkData = new LinkData((CrossSectionLink) network.getLink("LEFTIN"));
256         registerLinkToSampler(linkData, ignoreStart, linkData.getLength());
257         linkData = new LinkData((CrossSectionLink) network.getLink("RIGHTIN"));
258         registerLinkToSampler(linkData, ignoreStart, linkData.getLength());
259         linkData = new LinkData((CrossSectionLink) network.getLink("CONVERGE"));
260         registerLinkToSampler(linkData, Length.ZERO, linkData.getLength());
261         linkData = new LinkData((CrossSectionLink) network.getLink("WEAVING"));
262         registerLinkToSampler(linkData, Length.ZERO, linkData.getLength());
263         linkData = new LinkData((CrossSectionLink) network.getLink("END"));
264         registerLinkToSampler(linkData, Length.ZERO, linkData.getLength().minus(ignoreEnd));
265 
266         // return
267         return network;
268     }
269 
270     /**
271      * Register a link to the sampler, so data is sampled there.
272      * @param linkData link data
273      * @param startDistance start distance on link
274      * @param endDistance 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-2018 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 }