Repository navigation
Expand file tree
/
Copy pathpath.py
More file actions
174 lines (145 loc) · 5.28 KB
/
Copy pathpath.py
File metadata and controls
174 lines (145 loc) · 5.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
"""Path computation functions mirroring the R cppRouting API."""
import numpy as np
import pandas as pd
from pycpprouting._algorithms import (
astar,
bidirectional_dijkstra,
build_adjacency,
dijkstra,
dijkstra_early_stop,
reconstruct_bidir_path,
reconstruct_path,
)
from pycpprouting.distance import _resolve_ids
def get_path_pair(graph, from_nodes, to_nodes, algorithm="bi", constant=1,
keep=None, long=False):
"""Compute shortest path node sequences between paired origin-destination nodes.
Parameters
----------
graph : dict
Graph from makegraph(), cpp_simplify(), or cpp_contract().
from_nodes : list
Origin node IDs. Must be same length as to_nodes.
to_nodes : list
Destination node IDs.
algorithm : str
"Dijkstra", "bi", "A*", or "NBA".
constant : float
Heuristic constant for A*/NBA.
keep : list, optional
Only return these nodes in paths.
long : bool
If True, return DataFrame instead of dict.
Returns
-------
dict or pandas.DataFrame
Shortest path node sequences.
"""
from_nodes = list(from_nodes)
to_nodes = list(to_nodes)
if len(from_nodes) != len(to_nodes):
raise ValueError("from and to have not the same length")
from_ids = _resolve_ids(graph, from_nodes)
to_ids = _resolve_ids(graph, to_nodes)
nbnode = graph["nbnode"]
node_refs = graph["dict"]["ref"].values
has_coords = graph.get("coords") is not None and algorithm in ("A*", "NBA")
if has_coords:
coords_x = graph["coords"]["X"].values
coords_y = graph["coords"]["Y"].values
gfrom = graph["data"]["from"].values
gto = graph["data"]["to"].values
gw = graph["data"]["dist"].values
fwd, rev = build_adjacency(gfrom, gto, gw, nbnode)
keep_set = None
if keep is not None:
keep_set = {str(k) for k in keep}
results = {}
from_labels = [str(n) for n in from_nodes]
to_labels = [str(n) for n in to_nodes]
for i, (s, t) in enumerate(zip(from_ids, to_ids)):
if algorithm == "bi":
mu, meeting, df, dr, pf, pr = bidirectional_dijkstra(fwd, rev, s, t, nbnode)
if mu == np.inf:
path = []
else:
path = reconstruct_bidir_path(pf, pr, s, t, meeting, node_refs)
elif algorithm == "A*" and has_coords:
dist, parent = astar(fwd, s, t, nbnode, coords_x, coords_y, constant)
if dist[t] == np.inf:
path = []
else:
path = reconstruct_path(parent, s, t, node_refs)
else:
dist, parent = dijkstra_early_stop(fwd, s, t, nbnode)
if dist[t] == np.inf:
path = []
else:
path = reconstruct_path(parent, s, t, node_refs)
if keep_set and path:
path = [n for n in path if n in keep_set]
key = f"{from_labels[i]}_{to_labels[i]}"
results[key] = path
if long:
rows = []
for i in range(len(from_labels)):
key = f"{from_labels[i]}_{to_labels[i]}"
for node in results[key]:
rows.append({"from": from_labels[i], "to": to_labels[i], "node": node})
return pd.DataFrame(rows, columns=["from", "to", "node"])
return results
def get_multi_paths(graph, from_nodes, to_nodes, keep=None, long=False):
"""Compute all shortest paths between origin and destination nodes (one-to-many).
Parameters
----------
graph : dict
Graph from makegraph() or cpp_simplify().
from_nodes : list
Origin node IDs.
to_nodes : list
Destination node IDs.
keep : list, optional
Only return these nodes in paths.
long : bool
If True, return DataFrame instead of nested dict.
Returns
-------
dict or pandas.DataFrame
Nested dict: {from: {to: [path nodes]}} or DataFrame.
"""
if len(graph) != 5:
raise ValueError("Input should be generated by makegraph() or cpp_simplify()")
from_ids = _resolve_ids(graph, from_nodes)
to_ids = _resolve_ids(graph, to_nodes)
nbnode = graph["nbnode"]
node_refs = graph["dict"]["ref"].values
gfrom = graph["data"]["from"].values
gto = graph["data"]["to"].values
gw = graph["data"]["dist"].values
fwd, _ = build_adjacency(gfrom, gto, gw, nbnode)
keep_set = None
if keep is not None:
keep_set = {str(k) for k in keep}
from_labels = [str(n) for n in from_nodes]
to_labels = [str(n) for n in to_nodes]
results = {}
for i, src in enumerate(from_ids):
dist, parent = dijkstra(fwd, src, nbnode)
inner = {}
for j, tgt in enumerate(to_ids):
if dist[tgt] == np.inf:
path = []
else:
path = reconstruct_path(parent, src, tgt, node_refs)
if keep_set and path:
path = [n for n in path if n in keep_set]
inner[to_labels[j]] = path
results[from_labels[i]] = inner
if long:
rows = []
for fr in from_labels:
for to in to_labels:
for node in results[fr][to]:
rows.append({"from": fr, "to": to, "node": node})
return pd.DataFrame(rows, columns=["from", "to", "node"])
return results