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