View Javadoc
1   package org.opentrafficsim.road.gtu.lane.tactical;
2   
3   import java.util.ArrayList;
4   import java.util.Collection;
5   import java.util.HashMap;
6   import java.util.List;
7   import java.util.Map;
8   
9   import org.djunits.unit.AccelerationUnit;
10  import org.djunits.unit.DurationUnit;
11  import org.djunits.unit.LengthUnit;
12  import org.djunits.value.StorageType;
13  import org.djunits.value.ValueException;
14  import org.djunits.value.vdouble.scalar.Acceleration;
15  import org.djunits.value.vdouble.scalar.Duration;
16  import org.djunits.value.vdouble.scalar.Length;
17  import org.djunits.value.vdouble.scalar.Speed;
18  import org.djunits.value.vdouble.scalar.Time;
19  import org.djunits.value.vdouble.vector.AccelerationVector;
20  import org.opentrafficsim.base.parameters.ParameterException;
21  import org.opentrafficsim.base.parameters.ParameterTypeLength;
22  import org.opentrafficsim.base.parameters.ParameterTypes;
23  import org.opentrafficsim.core.geometry.OTSGeometryException;
24  import org.opentrafficsim.core.geometry.OTSLine3D;
25  import org.opentrafficsim.core.gtu.GTUDirectionality;
26  import org.opentrafficsim.core.gtu.GTUException;
27  import org.opentrafficsim.core.gtu.GTUType;
28  import org.opentrafficsim.core.gtu.plan.operational.OperationalPlan;
29  import org.opentrafficsim.core.gtu.plan.operational.OperationalPlan.Segment;
30  import org.opentrafficsim.core.gtu.plan.operational.OperationalPlanException;
31  import org.opentrafficsim.core.network.LateralDirectionality;
32  import org.opentrafficsim.core.network.Link;
33  import org.opentrafficsim.core.network.NetworkException;
34  import org.opentrafficsim.core.network.Node;
35  import org.opentrafficsim.road.gtu.lane.LaneBasedGTU;
36  import org.opentrafficsim.road.gtu.lane.perception.CategoricalLanePerception;
37  import org.opentrafficsim.road.gtu.lane.perception.LanePerception;
38  import org.opentrafficsim.road.gtu.lane.perception.categories.DefaultSimplePerception;
39  import org.opentrafficsim.road.gtu.lane.perception.categories.DirectDefaultSimplePerception;
40  import org.opentrafficsim.road.gtu.lane.perception.headway.Headway;
41  import org.opentrafficsim.road.gtu.lane.perception.headway.HeadwayTrafficLight;
42  import org.opentrafficsim.road.gtu.lane.tactical.following.GTUFollowingModelOld;
43  import org.opentrafficsim.road.gtu.lane.tactical.lanechangemobil.LaneChangeModel;
44  import org.opentrafficsim.road.gtu.lane.tactical.lanechangemobil.LaneMovementStep;
45  import org.opentrafficsim.road.network.lane.CrossSectionElement;
46  import org.opentrafficsim.road.network.lane.CrossSectionLink;
47  import org.opentrafficsim.road.network.lane.DirectedLanePosition;
48  import org.opentrafficsim.road.network.lane.Lane;
49  import org.opentrafficsim.road.network.lane.object.sensor.SingleSensor;
50  import org.opentrafficsim.road.network.lane.object.sensor.SinkSensor;
51  
52  import nl.tudelft.simulation.language.d3.DirectedPoint;
53  
54  /**
55   * Lane-based tactical planner that implements car following and lane change behavior. This lane-based tactical planner makes
56   * decisions based on headway (GTU following model) and lane change (Lane Change model), and will generate an operational plan
57   * for the GTU. It can ask the strategic planner for assistance on the route to take when the network splits.
58   * <p>
59   * Copyright (c) 2013-2019 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
60   * BSD-style license. See <a href="http://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
61   * </p>
62   * $LastChangedDate: 2015-07-24 02:58:59 +0200 (Fri, 24 Jul 2015) $, @version $Revision: 1147 $, by $Author: averbraeck $,
63   * initial version Nov 25, 2015 <br>
64   * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
65   * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
66   */
67  public class LaneBasedCFLCTacticalPlanner extends AbstractLaneBasedTacticalPlanner
68  {
69      /** */
70      private static final long serialVersionUID = 20151125L;
71  
72      /** Look back parameter type. */
73      protected static final ParameterTypeLength LOOKBACKOLD = ParameterTypes.LOOKBACKOLD;
74  
75      /** Standard incentive to stay in the current lane. */
76      private static final Acceleration STAYINCURRENTLANEINCENTIVE = new Acceleration(0.1, AccelerationUnit.METER_PER_SECOND_2);
77  
78      /** Standard incentive to stay in the current lane. */
79      private static final Acceleration PREFERREDLANEINCENTIVE = new Acceleration(0.3, AccelerationUnit.METER_PER_SECOND_2);
80  
81      /** Standard incentive to stay in the current lane. */
82      private static final Acceleration NONPREFERREDLANEINCENTIVE = new Acceleration(-0.3, AccelerationUnit.METER_PER_SECOND_2);
83  
84      /** Return value of suitability when no lane change is required within the time horizon. */
85      public static final Length NOLANECHANGENEEDED = new Length(Double.MAX_VALUE, LengthUnit.SI);
86  
87      /** Return value of suitability when a lane change is required <i>right now</i>. */
88      public static final Length GETOFFTHISLANENOW = Length.ZERO;
89  
90      /** Standard time horizon for route choices. */
91      private static final Duration TIMEHORIZON = new Duration(90, DurationUnit.SECOND);
92  
93      /** Lane change model for this tactical planner. */
94      private LaneChangeModel laneChangeModel;
95  
96      /**
97       * Instantiated a tactical planner with GTU following and lane change behavior.
98       * @param carFollowingModel GTUFollowingModelOld; Car-following model.
99       * @param laneChangeModel LaneChangeModel; Lane change model.
100      * @param gtu LaneBasedGTU; GTU
101      */
102     public LaneBasedCFLCTacticalPlanner(final GTUFollowingModelOld carFollowingModel, final LaneChangeModel laneChangeModel,
103             final LaneBasedGTU gtu)
104     {
105         super(carFollowingModel, gtu, new CategoricalLanePerception(gtu));
106         this.laneChangeModel = laneChangeModel;
107         getPerception().addPerceptionCategory(new DirectDefaultSimplePerception(getPerception()));
108     }
109 
110     /** {@inheritDoc} */
111     @Override
112     public final OperationalPlan generateOperationalPlan(final Time startTime, final DirectedPoint locationAtStartTime)
113             throws OperationalPlanException, NetworkException, GTUException, ParameterException
114     {
115         try
116         {
117             // define some basic variables
118             LaneBasedGTU laneBasedGTU = getGtu();
119             LanePerception perception = getPerception();
120 
121             // if the GTU's maximum speed is zero (block), generate a stand still plan for one second
122             if (laneBasedGTU.getMaximumSpeed().si < OperationalPlan.DRIFTING_SPEED_SI)
123             {
124                 return new OperationalPlan(getGtu(), locationAtStartTime, startTime, new Duration(1.0, DurationUnit.SECOND));
125             }
126 
127             Length maximumForwardHeadway = laneBasedGTU.getParameters().getParameter(LOOKAHEAD);
128             DefaultSimplePerception simplePerception = perception.getPerceptionCategory(DefaultSimplePerception.class);
129             Speed speedLimit = simplePerception.getSpeedLimit();
130 
131             // look at the conditions for headway on the current lane
132             Headway sameLaneLeader = simplePerception.getForwardHeadwayGTU();
133             // TODO how to handle objects on this lane or another lane???
134             Headway sameLaneFollower = simplePerception.getBackwardHeadway();
135             Collection<Headway> sameLaneTraffic = new ArrayList<>();
136             if (sameLaneLeader.getObjectType().isGtu())
137             {
138                 sameLaneTraffic.add(sameLaneLeader);
139             }
140             if (sameLaneFollower.getObjectType().isGtu())
141             {
142                 sameLaneTraffic.add(sameLaneFollower);
143             }
144 
145             // Are we in the right lane for the route?
146             LanePathInfo lanePathInfo = buildLanePathInfo(laneBasedGTU, maximumForwardHeadway);
147 
148             // TODO these two info's are not used
149             NextSplitInfo nextSplitInfo = determineNextSplit(laneBasedGTU, maximumForwardHeadway);
150             boolean currentLaneFine = nextSplitInfo.getCorrectCurrentLanes().contains(lanePathInfo.getReferenceLane());
151 
152             // calculate the lane change step
153             // TODO skip if:
154             // - we are in the right lane and drive at max speed or we accelerate maximally
155             // - there are no other lanes
156             Collection<Headway> leftLaneTraffic = simplePerception.getNeighboringHeadwaysLeft();
157             Collection<Headway> rightLaneTraffic = simplePerception.getNeighboringHeadwaysRight();
158 
159             // FIXME: whether we drive on the right should be stored in some central place.
160             final LateralDirectionality preferred = LateralDirectionality.RIGHT;
161             final Acceleration defaultLeftLaneIncentive =
162                     preferred.isLeft() ? PREFERREDLANEINCENTIVE : NONPREFERREDLANEINCENTIVE;
163             final Acceleration defaultRightLaneIncentive =
164                     preferred.isRight() ? PREFERREDLANEINCENTIVE : NONPREFERREDLANEINCENTIVE;
165 
166             AccelerationVector defaultLaneIncentives =
167                     new AccelerationVector(new double[] {defaultLeftLaneIncentive.getSI(), STAYINCURRENTLANEINCENTIVE.getSI(),
168                             defaultRightLaneIncentive.getSI()}, AccelerationUnit.SI, StorageType.DENSE);
169             AccelerationVector laneIncentives = laneIncentives(laneBasedGTU, defaultLaneIncentives);
170             LaneMovementStep lcmr = this.laneChangeModel.computeLaneChangeAndAcceleration(laneBasedGTU, sameLaneTraffic,
171                     rightLaneTraffic, leftLaneTraffic, speedLimit,
172                     new Acceleration(laneIncentives.get(preferred.isRight() ? 2 : 0)), new Acceleration(laneIncentives.get(1)),
173                     new Acceleration(laneIncentives.get(preferred.isRight() ? 0 : 2)));
174             Duration duration = lcmr.getGfmr().getValidUntil().minus(getGtu().getSimulator().getSimulatorTime());
175             if (lcmr.getLaneChangeDirection() != null)
176             {
177                 laneBasedGTU.changeLaneInstantaneously(lcmr.getLaneChangeDirection());
178 
179                 // create the path to drive in this timestep.
180                 lanePathInfo = buildLanePathInfo(laneBasedGTU, maximumForwardHeadway);
181             }
182 
183             // incorporate traffic light
184             Headway object = simplePerception.getForwardHeadwayObject();
185             Acceleration a = lcmr.getGfmr().getAcceleration();
186             if (object instanceof HeadwayTrafficLight)
187             {
188                 // if it was perceived, it was red, or yellow and judged as requiring to stop
189                 a = Acceleration.min(a, ((GTUFollowingModelOld) getCarFollowingModel()).computeAcceleration(getGtu().getSpeed(),
190                         getGtu().getMaximumSpeed(), Speed.ZERO, object.getDistance(), speedLimit));
191             }
192 
193             // incorporate dead-end/split
194             Length dist = lanePathInfo.getPath().getLength().minus(getGtu().getFront().getDx());
195             a = Acceleration.min(a, ((GTUFollowingModelOld) getCarFollowingModel()).computeAcceleration(getGtu().getSpeed(),
196                     getGtu().getMaximumSpeed(), Speed.ZERO, dist, speedLimit));
197 
198             // build a list of lanes forward, with a maximum headway.
199             OTSLine3D path = lanePathInfo.getPath();
200             if (a.si < 1E-6 && laneBasedGTU.getSpeed().si < OperationalPlan.DRIFTING_SPEED_SI)
201             {
202                 try
203                 {
204                     return new OperationalPlan(getGtu(), path.getLocationFraction(0.0), startTime, duration);
205                 }
206                 catch (OTSGeometryException exception)
207                 {
208                     // should not happen as 0.0 should be accepted
209                     throw new RuntimeException(exception);
210                 }
211             }
212             List<Segment> operationalPlanSegmentList = new ArrayList<>();
213 
214             if (a.si == 0.0)
215             {
216                 Segment segment = new OperationalPlan.SpeedSegment(duration);
217                 operationalPlanSegmentList.add(segment);
218             }
219             else
220             {
221                 Segment segment = new OperationalPlan.AccelerationSegment(duration, a);
222                 operationalPlanSegmentList.add(segment);
223             }
224             OperationalPlan op =
225                     new OperationalPlan(getGtu(), path, startTime, getGtu().getSpeed(), operationalPlanSegmentList);
226             return op;
227         }
228         catch (ValueException exception)
229         {
230             throw new GTUException(exception);
231         }
232     }
233 
234     /**
235      * TODO: move laneIncentives to LanePerception? Figure out if the default lane incentives are OK, or override them with
236      * values that should keep this GTU on the intended route.
237      * @param gtu LaneBasedGTU; the GTU for which to calculate the incentives
238      * @param defaultLaneIncentives AccelerationVector; the three lane incentives for the next left adjacent lane, the current
239      *            lane and the next right adjacent lane
240      * @return AccelerationVector; the (possibly adjusted) lane incentives
241      * @throws NetworkException on network inconsistency
242      * @throws ValueException cannot happen
243      * @throws GTUException when the position of the GTU cannot be correctly determined
244      * @throws OperationalPlanException if DefaultAlexander perception category is not present
245      */
246     private AccelerationVector laneIncentives(final LaneBasedGTU gtu, final AccelerationVector defaultLaneIncentives)
247             throws NetworkException, ValueException, GTUException, OperationalPlanException
248     {
249         Length leftSuitability = suitability(gtu, LateralDirectionality.LEFT);
250         Length currentSuitability = suitability(gtu, null);
251         Length rightSuitability = suitability(gtu, LateralDirectionality.RIGHT);
252         if (leftSuitability == NOLANECHANGENEEDED && currentSuitability == NOLANECHANGENEEDED
253                 && rightSuitability == NOLANECHANGENEEDED)
254         {
255             return checkLaneDrops(gtu, defaultLaneIncentives);
256         }
257         if ((leftSuitability == NOLANECHANGENEEDED || leftSuitability == GETOFFTHISLANENOW)
258                 && currentSuitability == NOLANECHANGENEEDED
259                 && (rightSuitability == NOLANECHANGENEEDED || rightSuitability == GETOFFTHISLANENOW))
260         {
261             return checkLaneDrops(gtu,
262                     new AccelerationVector(new double[] {acceleration(gtu, leftSuitability),
263                             defaultLaneIncentives.get(1).getSI(), acceleration(gtu, rightSuitability)}, AccelerationUnit.SI,
264                             StorageType.DENSE));
265         }
266         if (currentSuitability == NOLANECHANGENEEDED)
267         {
268             return new AccelerationVector(new double[] {acceleration(gtu, leftSuitability),
269                     defaultLaneIncentives.get(1).getSI(), acceleration(gtu, rightSuitability)}, AccelerationUnit.SI,
270                     StorageType.DENSE);
271         }
272         return new AccelerationVector(new double[] {acceleration(gtu, leftSuitability), acceleration(gtu, currentSuitability),
273                 acceleration(gtu, rightSuitability)}, AccelerationUnit.SI, StorageType.DENSE);
274     }
275 
276     /**
277      * Figure out if the default lane incentives are OK, or override them with values that should keep this GTU from running out
278      * of road at an upcoming lane drop.
279      * @param gtu LaneBasedGTU; the GTU for which to check the lane drops
280      * @param defaultLaneIncentives AccelerationVector; DoubleVector.Rel.Dense&lt;AccelerationUnit&gt; the three lane incentives
281      *            for the next left adjacent lane, the current lane and the next right adjacent lane
282      * @return DoubleVector.Rel.Dense&lt;AccelerationUnit&gt;; the (possibly adjusted) lane incentives
283      * @throws NetworkException on network inconsistency
284      * @throws ValueException cannot happen
285      * @throws GTUException when the positions of the GTU cannot be determined
286      * @throws OperationalPlanException if DefaultAlexander perception category is not present
287      */
288     private AccelerationVector checkLaneDrops(final LaneBasedGTU gtu, final AccelerationVector defaultLaneIncentives)
289             throws NetworkException, ValueException, GTUException, OperationalPlanException
290     {
291         // FIXME: these comparisons to -10 is ridiculous.
292         Length leftSuitability = Double.isNaN(defaultLaneIncentives.get(0).si) || defaultLaneIncentives.get(0).si < -10
293                 ? GETOFFTHISLANENOW : laneDrop(gtu, LateralDirectionality.LEFT);
294         Length currentSuitability = laneDrop(gtu, null);
295         Length rightSuitability = Double.isNaN(defaultLaneIncentives.get(2).si) || defaultLaneIncentives.get(2).si < -10
296                 ? GETOFFTHISLANENOW : laneDrop(gtu, LateralDirectionality.RIGHT);
297         // @formatter:off
298         if ((leftSuitability == NOLANECHANGENEEDED || leftSuitability == GETOFFTHISLANENOW)
299                 && currentSuitability == NOLANECHANGENEEDED
300                 && (rightSuitability == NOLANECHANGENEEDED || rightSuitability == GETOFFTHISLANENOW))
301         {
302             return defaultLaneIncentives;
303         }
304         // @formatter:on
305         if (currentSuitability == NOLANECHANGENEEDED)
306         {
307             return new AccelerationVector(new double[] {acceleration(gtu, leftSuitability),
308                     defaultLaneIncentives.get(1).getSI(), acceleration(gtu, rightSuitability)}, AccelerationUnit.SI,
309                     StorageType.DENSE);
310         }
311         if (currentSuitability.le(leftSuitability))
312         {
313             return new AccelerationVector(
314                     new double[] {PREFERREDLANEINCENTIVE.getSI(), NONPREFERREDLANEINCENTIVE.getSI(), GETOFFTHISLANENOW.getSI()},
315                     AccelerationUnit.SI, StorageType.DENSE);
316         }
317         if (currentSuitability.le(rightSuitability))
318         {
319             return new AccelerationVector(
320                     new double[] {GETOFFTHISLANENOW.getSI(), NONPREFERREDLANEINCENTIVE.getSI(), PREFERREDLANEINCENTIVE.getSI()},
321                     AccelerationUnit.SI, StorageType.DENSE);
322         }
323         return new AccelerationVector(new double[] {acceleration(gtu, leftSuitability), acceleration(gtu, currentSuitability),
324                 acceleration(gtu, rightSuitability)}, AccelerationUnit.SI, StorageType.DENSE);
325     }
326 
327     /**
328      * Return the distance until the next lane drop in the specified (nearby) lane.
329      * @param gtu LaneBasedGTU; the GTU to determine the next lane drop for
330      * @param direction LateralDirectionality; one of the values <cite>LateralDirectionality.LEFT</cite> (use the left-adjacent
331      *            lane), or <cite>LateralDirectionality.RIGHT</cite> (use the right-adjacent lane), or <cite>null</cite> (use
332      *            the current lane)
333      * @return DoubleScalar.Rel&lt;LengthUnit&gt;; distance until the next lane drop if it occurs within the TIMEHORIZON, or
334      *         LaneBasedRouteNavigator.NOLANECHANGENEEDED if this lane can be followed until the next split junction or until
335      *         beyond the TIMEHORIZON
336      * @throws NetworkException on network inconsistency
337      * @throws GTUException when the positions of the GTU cannot be determined
338      * @throws OperationalPlanException if DefaultAlexander perception category is not present
339      */
340     private Length laneDrop(final LaneBasedGTU gtu, final LateralDirectionality direction)
341             throws NetworkException, GTUException, OperationalPlanException
342     {
343         DirectedLanePosition dlp = gtu.getReferencePosition();
344         Lane lane = dlp.getLane();
345         Length longitudinalPosition = dlp.getPosition();
346         if (null != direction)
347         {
348             lane = getPerception().getPerceptionCategory(DefaultSimplePerception.class).bestAccessibleAdjacentLane(lane,
349                     direction, longitudinalPosition);
350         }
351         if (null == lane)
352         {
353             return GETOFFTHISLANENOW;
354         }
355         double remainingLength = lane.getLength().getSI() - longitudinalPosition.getSI();
356         double remainingTimeSI = TIMEHORIZON.getSI() - remainingLength / lane.getSpeedLimit(gtu.getGTUType()).getSI();
357         while (remainingTimeSI >= 0)
358         {
359             for (SingleSensor s : lane.getSensors())
360             {
361                 if (s instanceof SinkSensor)
362                 {
363                     return NOLANECHANGENEEDED;
364                 }
365             }
366             int branching = lane.nextLanes(gtu.getGTUType()).size();
367             if (branching == 0)
368             {
369                 return new Length(remainingLength, LengthUnit.SI);
370             }
371             if (branching > 1)
372             {
373                 return NOLANECHANGENEEDED;
374             }
375             lane = lane.nextLanes(gtu.getGTUType()).keySet().iterator().next();
376             remainingTimeSI -= lane.getLength().getSI() / lane.getSpeedLimit(gtu.getGTUType()).getSI();
377             remainingLength += lane.getLength().getSI();
378         }
379         return NOLANECHANGENEEDED;
380     }
381 
382     /**
383      * TODO: move suitability to LanePerception? Return the suitability for the current lane, left adjacent lane or right
384      * adjacent lane.
385      * @param gtu LaneBasedGTU; the GTU for which to calculate the incentives
386      * @param direction LateralDirectionality; one of the values <cite>null</cite>, <cite>LateralDirectionality.LEFT</cite>, or
387      *            <cite>LateralDirectionality.RIGHT</cite>
388      * @return DoubleScalar.Rel&lt;LengthUnit&gt;; the suitability of the lane for reaching the (next) destination
389      * @throws NetworkException on network inconsistency
390      * @throws GTUException when position cannot be determined
391      * @throws OperationalPlanException if DefaultAlexander perception category is not present
392      */
393     private Length suitability(final LaneBasedGTU gtu, final LateralDirectionality direction)
394             throws NetworkException, GTUException, OperationalPlanException
395     {
396         DirectedLanePosition dlp = gtu.getReferencePosition();
397         Lane lane = dlp.getLane();
398         Length longitudinalPosition = dlp.getPosition().plus(gtu.getFront().getDx());
399         if (null != direction)
400         {
401             lane = getPerception().getPerceptionCategory(DefaultSimplePerception.class).bestAccessibleAdjacentLane(lane,
402                     direction, longitudinalPosition);
403         }
404         if (null == lane)
405         {
406             return GETOFFTHISLANENOW;
407         }
408         try
409         {
410             return suitability(lane, longitudinalPosition, gtu, TIMEHORIZON);
411             // return suitability(lane, lane.getLength().minus(longitudinalPosition), gtu, TIMEHORIZON);
412         }
413         catch (NetworkException ne)
414         {
415             System.err.println(gtu + " has a route problem in suitability: " + ne.getMessage());
416             return NOLANECHANGENEEDED;
417         }
418     }
419 
420     /**
421      * Compute deceleration needed to stop at a specified distance.
422      * @param gtu LaneBasedGTU; the GTU for which to calculate the acceleration to come to a full stop at the distance
423      * @param stopDistance Length; the distance
424      * @return double; the acceleration (deceleration) needed to stop at the specified distance in m/s/s
425      */
426     private double acceleration(final LaneBasedGTU gtu, final Length stopDistance)
427     {
428         // What is the deceleration that will bring this GTU to a stop at exactly the suitability distance?
429         // Answer: a = -v^2 / 2 / suitabilityDistance
430         double v = gtu.getSpeed().getSI();
431         double a = -v * v / 2 / stopDistance.getSI();
432         return a;
433     }
434 
435     /**
436      * Determine the suitability of being at a particular longitudinal position in a particular Lane for following this Route.
437      * <br>
438      * TODO this code assumes GTUDirectionality.DIR_PLUS on all lanes of interest
439      * @param lane Lane; the lane to consider
440      * @param longitudinalPosition Length; the longitudinal position in the lane
441      * @param gtu LaneBasedGTU; the GTU (used to check lane compatibility of lanes, and current lane the GTU is on)
442      * @param timeHorizon Duration; the maximum time that a driver may want to look ahead
443      * @return DoubleScalar.Rel&lt;LengthUnit&gt;; a value that indicates within what distance the GTU should try to vacate this
444      *         lane.
445      * @throws NetworkException on network inconsistency, or when the continuation Link at a branch cannot be determined
446      */
447     private Length suitability(final Lane lane, final Length longitudinalPosition, final LaneBasedGTU gtu,
448             final Duration timeHorizon) throws NetworkException
449     {
450         double remainingDistance = lane.getLength().getSI() - longitudinalPosition.getSI();
451         double spareTime = timeHorizon.getSI() - remainingDistance / lane.getSpeedLimit(gtu.getGTUType()).getSI();
452         // Find the first upcoming Node where there is a branch
453         Node nextNode = lane.getParentLink().getEndNode();
454         Link lastLink = lane.getParentLink();
455         Node nextSplitNode = null;
456         Lane currentLane = lane;
457         CrossSectionLink linkBeforeBranch = lane.getParentLink();
458         while (null != nextNode)
459         {
460             if (spareTime <= 0)
461             {
462                 return NOLANECHANGENEEDED; // It is not yet time to worry; this lane will do as well as any other
463             }
464             int laneCount = countCompatibleLanes(linkBeforeBranch, gtu.getGTUType(), GTUDirectionality.DIR_PLUS);
465             if (0 == laneCount)
466             {
467                 throw new NetworkException("No compatible Lanes on Link " + linkBeforeBranch);
468             }
469             if (1 == laneCount)
470             {
471                 return NOLANECHANGENEEDED; // Only one compatible lane available; we'll get there "automatically";
472                 // i.e. without influence from the Route
473             }
474             int branching = nextNode.getLinks().size();
475             if (branching > 2)
476             { // Found a split
477                 nextSplitNode = nextNode;
478                 break;
479             }
480             else if (1 == branching)
481             {
482                 return NOLANECHANGENEEDED; // dead end; no more choices to make
483             }
484             else
485             { // Look beyond this nextNode
486                 Link nextLink = gtu.getStrategicalPlanner().nextLinkDirection(nextNode, lastLink, gtu.getGTUType()).getLink();
487                 if (nextLink instanceof CrossSectionLink)
488                 {
489                     GTUDirectionality drivingDirection =
490                             nextNode.equals(nextLink.getStartNode()) ? GTUDirectionality.DIR_PLUS : GTUDirectionality.DIR_MINUS;
491                     nextNode = nextLink.getEndNode();
492                     // Oops: wrong code added the length of linkBeforeBranch in stead of length of nextLink
493                     remainingDistance += nextLink.getLength().getSI();
494                     linkBeforeBranch = (CrossSectionLink) nextLink;
495                     // Figure out the new currentLane
496                     if (currentLane.nextLanes(gtu.getGTUType()).size() == 0)
497                     {
498                         // Lane drop; our lane disappears. This is a compulsory lane change; which is not controlled
499                         // by the Route. Perform the forced lane change.
500                         if (currentLane
501                                 .accessibleAdjacentLanesLegal(LateralDirectionality.RIGHT, gtu.getGTUType(), drivingDirection)
502                                 .size() > 0)
503                         {
504                             for (Lane adjacentLane : currentLane.accessibleAdjacentLanesLegal(LateralDirectionality.RIGHT,
505                                     gtu.getGTUType(), drivingDirection))
506                             {
507                                 if (adjacentLane.nextLanes(gtu.getGTUType()).size() > 0)
508                                 {
509                                     currentLane = adjacentLane;
510                                     break;
511                                 }
512                                 // If there are several adjacent lanes that have non empty nextLanes, we simple take the
513                                 // first in the set
514                             }
515                         }
516                         for (Lane adjacentLane : currentLane.accessibleAdjacentLanesLegal(LateralDirectionality.LEFT,
517                                 gtu.getGTUType(), drivingDirection))
518                         {
519                             if (adjacentLane.nextLanes(gtu.getGTUType()).size() > 0)
520                             {
521                                 currentLane = adjacentLane;
522                                 break;
523                             }
524                             // If there are several adjacent lanes that have non empty nextLanes, we simple take the
525                             // first in the set
526                         }
527                         if (currentLane.nextLanes(gtu.getGTUType()).size() == 0)
528                         {
529                             throw new NetworkException(
530                                     "Lane ends and there is not a compatible adjacent lane that does " + "not end");
531                         }
532                     }
533                     // Any compulsory lane change(s) have been performed and there is guaranteed a compatible next lane.
534                     for (Lane nextLane : currentLane.nextLanes(gtu.getGTUType()).keySet())
535                     {
536                         if (nextLane.getLaneType().getDirectionality(gtu.getGTUType()).getDirectionalities()
537                                 .contains(drivingDirection))
538                         {
539                             currentLane = currentLane.nextLanes(gtu.getGTUType()).keySet().iterator().next();
540                             break;
541                         }
542                     }
543                     spareTime -= currentLane.getLength().getSI() / currentLane.getSpeedLimit(gtu.getGTUType()).getSI();
544                 }
545                 else
546                 {
547                     // There is a non-CrossSectionLink on the path to the next branch. A non-CrossSectionLink does not
548                     // have identifiable Lanes, therefore we can't aim for a particular Lane
549                     return NOLANECHANGENEEDED; // Any Lane will do equally well
550                 }
551                 lastLink = nextLink;
552             }
553         }
554         if (null == nextNode)
555         {
556             throw new NetworkException("Cannot find the next branch or sink node");
557         }
558         // We have now found the first upcoming branching Node
559         // Which continuing link is the one we need?
560         Map<Lane, Length> suitabilityOfLanesBeforeBranch = new HashMap<>();
561         Link linkAfterBranch =
562                 gtu.getStrategicalPlanner().nextLinkDirection(nextSplitNode, lastLink, gtu.getGTUType()).getLink();
563         GTUDirectionality drivingDirectionOnNextLane =
564                 linkAfterBranch.getStartNode().equals(nextSplitNode) ? GTUDirectionality.DIR_PLUS : GTUDirectionality.DIR_MINUS;
565         for (CrossSectionElement cse : linkBeforeBranch.getCrossSectionElementList())
566         {
567             if (cse instanceof Lane)
568             {
569                 Lane l = (Lane) cse;
570                 if (l.getLaneType().getDirectionality(gtu.getGTUType()).getDirectionalities()
571                         .contains(GTUDirectionality.DIR_PLUS))
572                 {
573                     for (Lane connectingLane : l.nextLanes(gtu.getGTUType()).keySet())
574                     {
575                         if (connectingLane.getParentLink() == linkAfterBranch
576                                 && connectingLane.getLaneType().isCompatible(gtu.getGTUType(), drivingDirectionOnNextLane))
577                         {
578                             Length currentValue = suitabilityOfLanesBeforeBranch.get(l);
579                             // Use recursion to find out HOW suitable this continuation lane is, but don't revert back
580                             // to the maximum time horizon (or we could end up in infinite recursion when there are
581                             // loops in the network).
582                             Length value = suitability(connectingLane, new Length(0, LengthUnit.SI), gtu,
583                                     new Duration(spareTime, DurationUnit.SI));
584                             // This line was missing...
585                             value = value.plus(new Length(remainingDistance, LengthUnit.SI));
586                             // Use the minimum of the value computed for the first split junction (if there is one)
587                             // and the value computed for the second split junction.
588                             suitabilityOfLanesBeforeBranch.put(l,
589                                     null == currentValue || value.le(currentValue) ? value : currentValue);
590                         }
591                     }
592                 }
593             }
594         }
595         if (suitabilityOfLanesBeforeBranch.size() == 0)
596         {
597             throw new NetworkException("No lanes available on Link " + linkBeforeBranch);
598         }
599         Length currentLaneSuitability = suitabilityOfLanesBeforeBranch.get(currentLane);
600         if (null != currentLaneSuitability)
601         {
602             return currentLaneSuitability; // Following the current lane will keep us on the Route
603         }
604         // Performing one or more lane changes (left or right) is required.
605         int totalLanes = countCompatibleLanes(currentLane.getParentLink(), gtu.getGTUType(), GTUDirectionality.DIR_PLUS);
606         Length leftSuitability =
607                 computeSuitabilityWithLaneChanges(currentLane, remainingDistance, suitabilityOfLanesBeforeBranch, totalLanes,
608                         LateralDirectionality.LEFT, gtu.getGTUType(), GTUDirectionality.DIR_PLUS);
609         Length rightSuitability =
610                 computeSuitabilityWithLaneChanges(currentLane, remainingDistance, suitabilityOfLanesBeforeBranch, totalLanes,
611                         LateralDirectionality.RIGHT, gtu.getGTUType(), GTUDirectionality.DIR_PLUS);
612         if (leftSuitability.ge(rightSuitability))
613         {
614             return leftSuitability;
615         }
616         else if (rightSuitability.ge(leftSuitability))
617         {
618             // TODO
619             return rightSuitability;
620         }
621         if (leftSuitability.le(GETOFFTHISLANENOW))
622         {
623             throw new NetworkException("Changing lanes in any direction does not get the GTU on a suitable lane");
624         }
625         return leftSuitability; // left equals right; this is odd but topologically possible
626     }
627 
628     /**
629      * Compute the suitability of a lane from which lane changes are required to get to the next point on the Route.<br>
630      * This method weighs the suitability of the nearest suitable lane by (m - n) / m where n is the number of lane changes
631      * required and m is the total number of lanes in the CrossSectionLink.
632      * @param startLane Lane; the current lane of the GTU
633      * @param remainingDistance double; distance in m of GTU to first branch
634      * @param suitabilities Map&lt;Lane, Length&gt;; the set of suitable lanes and their suitability
635      * @param totalLanes int; total number of lanes compatible with the GTU type
636      * @param direction LateralDirectionality; the direction of the lane changes to attempt
637      * @param gtuType GTUType; the type of the GTU
638      * @param drivingDirection GTUDirectionality; the driving direction of the GTU
639      * @return double; the suitability of the <cite>startLane</cite> for following the Route
640      */
641     protected final Length computeSuitabilityWithLaneChanges(final Lane startLane, final double remainingDistance,
642             final Map<Lane, Length> suitabilities, final int totalLanes, final LateralDirectionality direction,
643             final GTUType gtuType, final GTUDirectionality drivingDirection)
644     {
645         /*-
646          * The time per required lane change seems more relevant than distance per required lane change.
647          * Total time required does not grow linearly with the number of required lane changes. Logarithmic, arc tangent 
648          * is more like it.
649          * Rijkswaterstaat appears to use a fixed time for ANY number of lane changes (about 60s). 
650          * TomTom navigation systems give more time (about 90s).
651          * In this method the returned suitability decreases linearly with the number of required lane changes. This
652          * ensures that there is a gradient that coaches the GTU towards the most suitable lane.
653          */
654         int laneChangesUsed = 0;
655         Lane currentLane = startLane;
656         Length currentSuitability = null;
657         while (null == currentSuitability)
658         {
659             laneChangesUsed++;
660             if (currentLane.accessibleAdjacentLanesLegal(direction, gtuType, drivingDirection).size() == 0)
661             {
662                 return GETOFFTHISLANENOW;
663             }
664             currentLane = currentLane.accessibleAdjacentLanesLegal(direction, gtuType, drivingDirection).iterator().next();
665             currentSuitability = suitabilities.get(currentLane);
666         }
667         double fraction = currentSuitability == NOLANECHANGENEEDED ? 0 : 0.5;
668         int notSuitableLaneCount = totalLanes - suitabilities.size();
669         return new Length(
670                 remainingDistance * (notSuitableLaneCount - laneChangesUsed + 1 + fraction) / (notSuitableLaneCount + fraction),
671                 LengthUnit.SI);
672     }
673 
674     /**
675      * Determine how many lanes on a CrossSectionLink are compatible with a particular GTU type.<br>
676      * TODO: this method should probably be moved into the CrossSectionLink class
677      * @param link CrossSectionLink; the link
678      * @param gtuType GTUType; the GTU type
679      * @param drivingDirection GTUDirectionality; the driving direction on the link
680      * @return integer; the number of lanes on the link that are compatible with the GTU type
681      */
682     protected final int countCompatibleLanes(final CrossSectionLink link, final GTUType gtuType,
683             final GTUDirectionality drivingDirection)
684     {
685         int result = 0;
686         for (CrossSectionElement cse : link.getCrossSectionElementList())
687         {
688             if (cse instanceof Lane)
689             {
690                 Lane l = (Lane) cse;
691                 if (l.getLaneType().isCompatible(gtuType, drivingDirection))
692                 {
693                     result++;
694                 }
695             }
696         }
697         return result;
698     }
699 
700     /** {@inheritDoc} */
701     @Override
702     public final String toString()
703     {
704         return "LaneBasedCFLCTacticalPlanner [laneChangeModel=" + this.laneChangeModel + "]";
705     }
706 
707 }