1 package org.opentrafficsim.road.network;
2
3 import java.util.Iterator;
4 import java.util.LinkedHashMap;
5 import java.util.List;
6 import java.util.Map;
7 import java.util.Set;
8 import java.util.SortedSet;
9 import java.util.TreeSet;
10
11 import org.djunits.value.vdouble.scalar.Length;
12 import org.djutils.base.Identifiable;
13 import org.djutils.exceptions.Throw;
14 import org.djutils.immutablecollections.ImmutableSortedSet;
15 import org.djutils.immutablecollections.ImmutableTreeSet;
16 import org.djutils.multikeymap.MultiKeyMap;
17 import org.jgrapht.GraphPath;
18 import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
19 import org.jgrapht.graph.SimpleDirectedWeightedGraph;
20 import org.opentrafficsim.core.dsol.OtsSimulatorInterface;
21 import org.opentrafficsim.core.gtu.GtuType;
22 import org.opentrafficsim.core.network.LateralDirectionality;
23 import org.opentrafficsim.core.network.Link;
24 import org.opentrafficsim.core.network.Network;
25 import org.opentrafficsim.core.network.NetworkException;
26 import org.opentrafficsim.core.network.Node;
27 import org.opentrafficsim.core.network.route.Route;
28 import org.opentrafficsim.road.network.lane.CrossSectionLink;
29 import org.opentrafficsim.road.network.lane.Lane;
30
31 /**
32 * RoadNetwork adds the ability to retrieve lane change information.
33 * <p>
34 * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
35 * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
36 * </p>
37 * @author <a href="https://github.com/averbraeck" target="_blank">Alexander Verbraeck</a>
38 * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
39 */
40 public class RoadNetwork extends Network
41 {
42 /** */
43 private static final long serialVersionUID = 1L;
44
45 /** Cached lane graph for legal connections, per GTU type. */
46 private Map<GtuType, RouteWeightedGraph> legalLaneGraph = new LinkedHashMap<>();
47
48 /** Cached lane graph for physical connections. */
49 private RouteWeightedGraph physicalLaneGraph = null;
50
51 /** Cached legal lane change info, over complete length of route. */
52 private MultiKeyMap<SortedSet<LaneChangeInfo>> legalLaneChangeInfoCache =
53 new MultiKeyMap<>(GtuType.class, Route.class, Lane.class);
54
55 /** Cached physical lane change info, over complete length of route. */
56 private MultiKeyMap<SortedSet<LaneChangeInfo>> physicalLaneChangeInfoCache = new MultiKeyMap<>(Route.class, Lane.class);
57
58 /**
59 * Construction of an empty network.
60 * @param id the network id.
61 * @param simulator the DSOL simulator engine
62 */
63 public RoadNetwork(final String id, final OtsSimulatorInterface simulator)
64 {
65 super(id, simulator);
66 }
67
68 /**
69 * Returns lane change info from the given lane. Distances are given from the start of the lane and will never exceed the
70 * given range. This method returns {@code null} if no valid path exists. If there are no reasons to change lane within
71 * range, an empty set is returned.
72 * @param lane from lane.
73 * @param route route.
74 * @param gtuType GTU Type.
75 * @param range maximum range of info to consider, from the start of the given lane.
76 * @param laneAccessLaw lane access law.
77 * @return lane change info from the given lane, or {@code null} if no path exists.
78 */
79 public ImmutableSortedSet<LaneChangeInfo> getLaneChangeInfo(final Lane lane, final Route route, final GtuType gtuType,
80 final Length range, final LaneAccessLaw laneAccessLaw)
81 {
82 Throw.whenNull(lane, "Lane may not be null.");
83 Throw.whenNull(route, "Route may not be null.");
84 Throw.whenNull(gtuType, "GTU type may not be null.");
85 Throw.whenNull(range, "Range may not be null.");
86 Throw.whenNull(laneAccessLaw, "Lane access law may not be null.");
87 Throw.when(range.le0(), IllegalArgumentException.class, "Range should be a positive value.");
88
89 // get the complete info
90 SortedSet<LaneChangeInfo> info = getCompleteLaneChangeInfo(lane, route, gtuType, laneAccessLaw);
91 if (info == null)
92 {
93 return null;
94 }
95
96 // find first LaneChangeInfo beyond range, if any
97 LaneChangeInfo lcInfoBeyondHorizon = null;
98 Iterator<LaneChangeInfo> iterator = info.iterator();
99 while (lcInfoBeyondHorizon == null && iterator.hasNext())
100 {
101 LaneChangeInfo lcInfo = iterator.next();
102 if (lcInfo.remainingDistance().gt(range))
103 {
104 lcInfoBeyondHorizon = lcInfo;
105 }
106 }
107
108 // return subset in range
109 if (lcInfoBeyondHorizon != null)
110 {
111 return new ImmutableTreeSet<>(info.headSet(lcInfoBeyondHorizon));
112 }
113 return new ImmutableTreeSet<>(info); // empty, or all in range
114 }
115
116 /**
117 * Returns the complete (i.e. without range) lane change info from the given lane. It is either taken from cache, or
118 * created.
119 * @param lane from lane.
120 * @param route route.
121 * @param gtuType GTU Type.
122 * @param laneAccessLaw lane access law.
123 * @return complete (i.e. without range) lane change info from the given lane, or {@code null} if no path exists.
124 */
125 private SortedSet<LaneChangeInfo> getCompleteLaneChangeInfo(final Lane lane, final Route route, final GtuType gtuType,
126 final LaneAccessLaw laneAccessLaw)
127 {
128 // try to get info from the right cache
129 SortedSet<LaneChangeInfo> outputLaneChangeInfo;
130 if (laneAccessLaw.equals(LaneAccessLaw.LEGAL))
131 {
132 outputLaneChangeInfo = this.legalLaneChangeInfoCache.get(gtuType, route, lane);
133 // build info if required
134 if (outputLaneChangeInfo == null)
135 {
136 // get the right lane graph for the GTU type, or build it
137 RouteWeightedGraph graph = this.legalLaneGraph.get(gtuType);
138 if (graph == null)
139 {
140 graph = new RouteWeightedGraph();
141 this.legalLaneGraph.put(gtuType, graph);
142 buildGraph(graph, gtuType, laneAccessLaw);
143 }
144 List<LaneChangeInfoEdge> path = findPath(lane, graph, gtuType, route);
145
146 if (path != null)
147 {
148 // derive lane change info from every lane along the path and cache it
149 boolean originalPath = true;
150 while (!path.isEmpty())
151 {
152 SortedSet<LaneChangeInfo> laneChangeInfo = extractLaneChangeInfo(path);
153 if (originalPath)
154 {
155 outputLaneChangeInfo = laneChangeInfo;
156 originalPath = false;
157 }
158 this.legalLaneChangeInfoCache.put(laneChangeInfo, gtuType, route, path.get(0).fromLane());
159 path.remove(0); // next lane
160 }
161 }
162 }
163 }
164 else if (laneAccessLaw.equals(LaneAccessLaw.PHYSICAL))
165 {
166 outputLaneChangeInfo = this.physicalLaneChangeInfoCache.get(route, lane);
167 // build info if required
168 if (outputLaneChangeInfo == null)
169 {
170 // build the lane graph if required
171 if (this.physicalLaneGraph == null)
172 {
173 this.physicalLaneGraph = new RouteWeightedGraph();
174 // TODO: Is the GTU type actually relevant for physical? It is used still to find adjacent lanes.
175 buildGraph(this.physicalLaneGraph, gtuType, laneAccessLaw);
176 }
177 List<LaneChangeInfoEdge> path = findPath(lane, this.physicalLaneGraph, gtuType, route);
178
179 if (path != null)
180 {
181 // derive lane change info from every lane along the path and cache it
182 boolean originalPath = true;
183 while (!path.isEmpty())
184 {
185 SortedSet<LaneChangeInfo> laneChangeInfo = extractLaneChangeInfo(path);
186 if (originalPath)
187 {
188 outputLaneChangeInfo = laneChangeInfo;
189 originalPath = false;
190 }
191 this.physicalLaneChangeInfoCache.put(laneChangeInfo, route, path.get(0).fromLane());
192 path.remove(0); // next lane
193 }
194 }
195 }
196 }
197 else
198 {
199 // in case it is inadvertently extended in the future
200 throw new RuntimeException(String.format("Unknown LaneChangeLaw %s", laneAccessLaw));
201 }
202 return outputLaneChangeInfo;
203 }
204
205 /**
206 * Builds the graph.
207 * @param graph empty graph to build.
208 * @param gtuType GTU type.
209 * @param laneChangeLaw lane change law, legal or physical.
210 */
211 private void buildGraph(final RouteWeightedGraph graph, final GtuType gtuType, final LaneAccessLaw laneChangeLaw)
212 {
213 // add vertices
214 boolean legal = laneChangeLaw.equals(LaneAccessLaw.LEGAL);
215 for (Link link : this.getLinkMap().values())
216 {
217 for (Lane lane : legal ? ((CrossSectionLink) link).getLanes() : ((CrossSectionLink) link).getLanesAndShoulders())
218 {
219 graph.addVertex(lane);
220 }
221 // each end node may be a destination for the shortest path search
222 graph.addVertex(link.getEndNode());
223 }
224
225 // add edges
226 for (Link link : this.getLinkMap().values())
227 {
228 if (link instanceof CrossSectionLink cLink)
229 {
230 for (Lane lane : legal ? cLink.getLanes() : cLink.getLanesAndShoulders())
231 {
232 // adjacent lanes
233 for (LateralDirectionality lat : List.of(LateralDirectionality.LEFT, LateralDirectionality.RIGHT))
234 {
235 Set<Lane> adjacentLanes;
236 if (legal)
237 {
238 adjacentLanes = lane.accessibleAdjacentLanesLegal(lat, gtuType);
239 }
240 else
241 {
242 adjacentLanes = lane.accessibleAdjacentLanesPhysical(lat, gtuType);
243 }
244 for (Lane adjacentLane : adjacentLanes)
245 {
246 LaneChangeInfoEdgeType type = lat.equals(LateralDirectionality.LEFT) ? LaneChangeInfoEdgeType.LEFT
247 : LaneChangeInfoEdgeType.RIGHT;
248 // downstream link may be null for lateral edges
249 LaneChangeInfoEdge edge = new LaneChangeInfoEdge(lane, type, null);
250 graph.addEdge(lane, adjacentLane, edge);
251 }
252 }
253 // next lanes
254 Set<Lane> nextLanes = lane.nextLanes(legal ? gtuType : null);
255 for (Lane nextLane : nextLanes)
256 {
257 LaneChangeInfoEdge edge =
258 new LaneChangeInfoEdge(lane, LaneChangeInfoEdgeType.DOWNSTREAM, nextLane.getLink());
259 graph.addEdge(lane, nextLane, edge);
260 }
261 // add edge towards end node so that it can be used as a destination in the shortest path search
262 LaneChangeInfoEdge edge = new LaneChangeInfoEdge(lane, LaneChangeInfoEdgeType.DOWNSTREAM, null);
263 graph.addEdge(lane, lane.getLink().getEndNode(), edge);
264 }
265 }
266 }
267 }
268
269 /**
270 * Returns a set of lane change info, extracted from the graph.
271 * @param lane from lane.
272 * @param graph graph.
273 * @param gtuType GTU Type.
274 * @param route route.
275 * @return path derived from the graph, or {@code null} if there is no path.
276 */
277 private List<LaneChangeInfoEdge> findPath(final Lane lane, final RouteWeightedGraph graph, final GtuType gtuType,
278 final Route route)
279 {
280 // if there is no route, find the destination node by moving down the links (no splits allowed)
281 Node destination = null;
282 Route routeForWeights = route;
283 if (route == null)
284 {
285 destination = graph.getNoRouteDestinationNode(gtuType);
286 try
287 {
288 routeForWeights = getShortestRouteBetween(gtuType, lane.getLink().getStartNode(), destination);
289 }
290 catch (NetworkException exception)
291 {
292 // this should not happen, as we obtained the destination by moving downstream towards the end of the network
293 throw new RuntimeException("Could not find route to destination.", exception);
294 }
295 }
296 else
297 {
298 // otherwise, get destination node from route, which is the last node on a link with lanes (i.e. no connector)
299 List<Node> nodes = route.getNodes();
300 for (int i = nodes.size() - 1; i > 0; i--)
301 {
302 Link link = getLink(nodes.get(i - 1), nodes.get(i));
303 if (link instanceof CrossSectionLink && !((CrossSectionLink) link).getLanes().isEmpty())
304 {
305 destination = nodes.get(i);
306 break; // found most downstream link with lanes, who's end node is the destination for lane changes
307 }
308 }
309 Throw.whenNull(destination, "Route has no links with lanes, "
310 + "unable to find a suitable destination node regarding lane change information.");
311 }
312
313 // set the route on the path for route-dependent edge weights
314 graph.setRoute(routeForWeights);
315
316 // find the shortest path
317 GraphPath<Identifiable, LaneChangeInfoEdge> path = DijkstraShortestPath.findPathBetween(graph, lane, destination);
318 return path == null ? null : path.getEdgeList();
319 }
320
321 /**
322 * Extracts lane change info from a path.
323 * @param path path.
324 * @return lane change info.
325 */
326 private SortedSet<LaneChangeInfo> extractLaneChangeInfo(final List<LaneChangeInfoEdge> path)
327 {
328 SortedSet<LaneChangeInfo> info = new TreeSet<>();
329 Length x = Length.ZERO; // cumulative longitudinal distance
330 int n = 0; // number of applied lane changes
331 boolean inLateralState = false; // consecutive lateral moves in the path create 1 LaneChangeInfo
332 for (LaneChangeInfoEdge edge : path)
333 {
334 LaneChangeInfoEdgeType lcType = edge.laneChangeInfoEdgeType();
335 int lat = lcType.equals(LaneChangeInfoEdgeType.LEFT) ? -1 : (lcType.equals(LaneChangeInfoEdgeType.RIGHT) ? 1 : 0);
336
337 // check opposite lateral direction
338 if (n * lat < 0)
339 {
340 /*
341 * The required direction is opposite a former required direction, in which case all further lane change
342 * information is not yet of concern. For example, we first need to make 1 right lane change for a lane drop,
343 * and then later 2 lane changes to the left for a split. The latter information is pointless before the lane
344 * drop; we are not going to stay on the lane longer as it won't affect the ease of the left lane changes later.
345 */
346 break;
347 }
348
349 // increase n, x, and trigger (consecutive) lateral move start or stop
350 if (lat == 0)
351 {
352 // lateral move stop
353 if (inLateralState)
354 {
355 // TODO: isDeadEnd should be removed from LaneChangeInfo, behavior should consider legal vs. physical
356 boolean isDeadEnd = false;
357 info.add(new LaneChangeInfo(Math.abs(n), x, isDeadEnd,
358 n < 0 ? LateralDirectionality.LEFT : LateralDirectionality.RIGHT));
359 inLateralState = false;
360 // don't add the length of the previous lane, that was already done for the first lane of all lateral moves
361 }
362 else
363 {
364 // longitudinal move, we need to add distance to x
365 x = x.plus(edge.fromLane().getLength());
366 }
367 }
368 else
369 {
370 // lateral move start
371 if (!inLateralState)
372 {
373 x = x.plus(edge.fromLane().getLength()); // need to add length of first lane of all lateral moves
374 inLateralState = true;
375 }
376 // increase lane change count (negative for left)
377 n += lat;
378 }
379 }
380 return info;
381 }
382
383 /**
384 * Clears all lane change info graphs and cached sets. This method should be invoked on every network change that affects
385 * lane changes and the distances within which they need to be performed.
386 */
387 public void clearLaneChangeInfoCache()
388 {
389 this.legalLaneGraph.clear();
390 this.physicalLaneGraph = null;
391 this.legalLaneChangeInfoCache = new MultiKeyMap<>(GtuType.class, Route.class, Lane.class);
392 this.physicalLaneChangeInfoCache = new MultiKeyMap<>(Route.class, Lane.class);
393 }
394
395 /**
396 * A {@code SimpleDirectedWeightedGraph} to search over the lanes, where the weight of an edge (movement between lanes) is
397 * tailored to providing lane change information. The vertex type is {@code Identifiable} such that both {@code Lane}'s and
398 * {@code Node}'s can be used. The latter is required to find paths towards a destination node.
399 * <p>
400 * Copyright (c) 2022-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
401 * <br>
402 * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
403 * </p>
404 * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
405 */
406 private class RouteWeightedGraph extends SimpleDirectedWeightedGraph<Identifiable, LaneChangeInfoEdge>
407 {
408
409 /** */
410 private static final long serialVersionUID = 20220923L;
411
412 /** Route. */
413 private Route route;
414
415 /** Node in the network that is the destination if no route is used. */
416 private Node noRouteDestination = null;
417
418 /**
419 * Constructor.
420 */
421 RouteWeightedGraph()
422 {
423 super(LaneChangeInfoEdge.class);
424 }
425
426 /**
427 * Set the route.
428 * @param route route.
429 */
430 public void setRoute(final Route route)
431 {
432 Throw.whenNull(route, "Route may not be null for lane change information.");
433 this.route = route;
434 }
435
436 /**
437 * Returns the weight of moving from one lane to the next. In order to find the latest possible location at which lane
438 * changes may still be performed, the longitudinal weights are 1.0 while the lateral weights are 1.0 + 1/X, where X is
439 * the number (index) of the link within the route. This favors later lane changes for the shortest path algorithm, as
440 * we are interested in the distances within which the lane change have to be performed. In the case an edge is towards
441 * a link that is not in a given route, a positive infinite weight is returned. Finally, when the edge is towards a
442 * node, which may be the destination in a route, 0.0 is returned.
443 */
444 @Override
445 public double getEdgeWeight(final LaneChangeInfoEdge e)
446 {
447 if (e.laneChangeInfoEdgeType().equals(LaneChangeInfoEdgeType.LEFT)
448 || e.laneChangeInfoEdgeType().equals(LaneChangeInfoEdgeType.RIGHT))
449 {
450 int indexEndNode = this.route.indexOf(e.fromLane().getLink().getEndNode());
451 return 1.0 + 1.0 / indexEndNode; // lateral, reduce weight for further lane changes
452 }
453 Link toLink = e.toLink();
454 if (toLink == null)
455 {
456 return 0.0; // edge towards Node, which may be the destination in a Route
457 }
458 if (this.route.contains(toLink.getEndNode())
459 && this.route.indexOf(toLink.getEndNode()) == this.route.indexOf(toLink.getStartNode()) + 1)
460 {
461 return 1.0; // downstream, always 1.0 if the next lane is on the route
462 }
463 return Double.POSITIVE_INFINITY; // next lane not on the route, this is a dead-end branch for the route
464 }
465
466 /**
467 * Returns the destination node to use when no route is available. This will be the last node found moving downstream.
468 * @param gtuType GTU type.
469 * @return destination node to use when no route is available.
470 */
471 public Node getNoRouteDestinationNode(final GtuType gtuType)
472 {
473 if (this.noRouteDestination == null)
474 {
475 // get any lane from the network
476 Lane lane = null;
477 Iterator<Identifiable> iterator = this.vertexSet().iterator();
478 while (lane == null && iterator.hasNext())
479 {
480 Identifiable next = iterator.next();
481 if (next instanceof Lane)
482 {
483 lane = (Lane) next;
484 }
485 }
486 Throw.when(lane == null, RuntimeException.class, "Requesting destination node on network without lanes.");
487 // move to downstream link for as long as there is 1 downstream link
488 try
489 {
490 Link link = lane.getLink();
491 Set<Link> downstreamLinks = link.getEndNode().nextLinks(gtuType, link);
492 while (downstreamLinks.size() == 1)
493 {
494 link = downstreamLinks.iterator().next();
495 downstreamLinks = link.getEndNode().nextLinks(gtuType, link);
496 }
497 Throw.when(downstreamLinks.size() > 1, RuntimeException.class, "Using null route on network with split. "
498 + "Unable to find a destination to find lane change info towards.");
499 this.noRouteDestination = link.getEndNode();
500 }
501 catch (NetworkException ne)
502 {
503 throw new RuntimeException("Requesting lane change info from link that does not allow the GTU type.", ne);
504 }
505 }
506 return this.noRouteDestination;
507 }
508 }
509
510 /**
511 * Edge between two lanes, or between a lane and a node (to provide the shortest path algorithm with a suitable
512 * destination). From a list of these from a path, the lane change information along the path (distances and number of lane
513 * changes) can be derived.
514 * <p>
515 * Copyright (c) 2022-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
516 * <br>
517 * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
518 * </p>
519 * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
520 * @param fromLane from lane, to allow construction of distances from a path.
521 * @param laneChangeInfoEdgeType the type of lane to lane movement performed along this edge.
522 * @param toLink to link (of the lane this edge moves to).
523 */
524 private static record LaneChangeInfoEdge(Lane fromLane, LaneChangeInfoEdgeType laneChangeInfoEdgeType, Link toLink)
525 {
526 }
527
528 /**
529 * Enum to provide information on the lane to lane movement in a path.
530 * <p>
531 * Copyright (c) 2022-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
532 * <br>
533 * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
534 * </p>
535 * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
536 */
537 private enum LaneChangeInfoEdgeType
538 {
539 /** Left lane change. */
540 LEFT,
541
542 /** Right lane change. */
543 RIGHT,
544
545 /** Downstream movement, either towards a lane, or towards a node (which may be the destination in a route). */
546 DOWNSTREAM;
547 }
548
549 }