Repository navigation
Expand file tree
/
Copy pathgraph.py
More file actions
250 lines (208 loc) · 8.32 KB
/
Copy pathgraph.py
File metadata and controls
250 lines (208 loc) · 8.32 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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
"""Graph construction and manipulation functions mirroring the R cppRouting API."""
import numpy as np
import pandas as pd
from pycpprouting._algorithms import contract_graph, simplify_graph
def makegraph(df, directed=True, coords=None, aux=None, capacity=None, alpha=None, beta=None):
"""Construct a graph object for routing operations.
Parameters
----------
df : pandas.DataFrame or array-like
3-column data with (from, to, cost). Cost must be non-negative.
directed : bool
If False, edges are duplicated in both directions.
coords : pandas.DataFrame or array-like, optional
3-column data with (node_ID, X, Y). Must be projected coordinates.
aux : float or array-like, optional
Additional edge weight(s) to aggregate along shortest paths.
capacity : float or array-like, optional
Edge capacity for traffic assignment.
alpha : float or array-like, optional
BPR function alpha parameter. Must be != 0.
beta : float or array-like, optional
BPR function beta parameter. Must be >= 1.
Returns
-------
dict
Graph object with keys: data, coords, nbnode, dict, attrib.
"""
df = pd.DataFrame(df)
if df.shape[1] != 3:
raise ValueError("Data should have 3 columns")
df.columns = ["from", "to", "dist"]
df["from"] = df["from"].astype(str)
df["to"] = df["to"].astype(str)
df["dist"] = df["dist"].astype(float)
if df.isna().any().any():
raise ValueError("NAs are not allowed in the graph")
if (df["dist"] < 0).any():
raise ValueError("Negative cost is not allowed")
nodes = pd.unique(pd.concat([df["from"], df["to"]], ignore_index=True))
nrow = len(df)
# Validate and expand auxiliary attributes
def _validate_vec(val, name, nrow):
if val is None:
return None
val = np.atleast_1d(np.asarray(val, dtype=float))
if len(val) == 1:
val = np.repeat(val, nrow)
if len(val) != nrow:
raise ValueError(f"length({name}) must equal 1 or nrow(df)")
return val
aux = _validate_vec(aux, "aux", nrow)
capacity = _validate_vec(capacity, "capacity", nrow)
alpha_v = _validate_vec(alpha, "alpha", nrow)
beta_v = _validate_vec(beta, "beta", nrow)
if aux is not None and (aux < 0).any():
import warnings
warnings.warn("aux contains negative values, this weight is aggregate-only and cannot be minimized")
if capacity is not None and (capacity <= 0).any():
raise ValueError("capacity must be strictly positive")
if alpha_v is not None and (alpha_v == 0).any():
raise ValueError("alpha must be different from 0")
if beta_v is not None and (beta_v < 1).any():
raise ValueError("beta must be equal or greater than 1")
attrib = {"aux": aux, "cap": capacity, "alpha": alpha_v, "beta": beta_v}
if not directed:
df2 = df[["to", "from", "dist"]].copy()
df2.columns = ["from", "to", "dist"]
df = pd.concat([df, df2], ignore_index=True)
attrib = {k: (np.tile(v, 2) if v is not None else None) for k, v in attrib.items()}
coords_out = None
if coords is not None:
coords = pd.DataFrame(coords)
if coords.shape[1] != 3:
raise ValueError("Coords should have 3 columns")
coords.columns = ["node", "X", "Y"]
coords["node"] = coords["node"].astype(str)
coords["X"] = coords["X"].astype(float)
coords["Y"] = coords["Y"].astype(float)
if coords.isna().any().any():
raise ValueError("NAs are not allowed in coordinates")
if coords["node"].duplicated().any():
raise ValueError("Nodes should be unique in the coordinates data frame")
missing = set(nodes) - set(coords["node"])
if missing:
raise ValueError("Some nodes are missing in coordinates data")
coords = coords[coords["node"].isin(nodes)]
# Reorder to match nodes order
coords = coords.set_index("node").loc[nodes].reset_index()
coords_out = coords
# Build dictionary mapping node refs to integer IDs
dict_df = pd.DataFrame({"ref": nodes, "id": np.arange(len(nodes))})
# Map from/to to integer IDs
ref_to_id = dict(zip(dict_df["ref"], dict_df["id"]))
df = df.copy()
df["from"] = df["from"].map(ref_to_id).astype(int)
df["to"] = df["to"].map(ref_to_id).astype(int)
return {
"data": df,
"coords": coords_out,
"nbnode": len(nodes),
"dict": dict_df,
"attrib": attrib,
}
def to_df(graph):
"""Convert a cppRouting graph back to a DataFrame with original node IDs.
Parameters
----------
graph : dict
Graph object from makegraph() or cpp_simplify().
Returns
-------
pandas.DataFrame
DataFrame with columns: from, to, dist.
"""
if len(graph) != 5 or "data" not in graph:
raise ValueError("Invalid graph input, must be an object generated by makegraph() or cpp_simplify()")
dat = graph["data"].copy()
id_to_ref = dict(zip(graph["dict"]["id"], graph["dict"]["ref"]))
dat["from"] = dat["from"].map(id_to_ref)
dat["to"] = dat["to"].map(id_to_ref)
return dat
def cpp_simplify(graph, keep=None, rm_loop=True, iterate=False, silent=True):
"""Simplify a graph by removing non-intersection nodes.
Parameters
----------
graph : dict
Graph from makegraph().
keep : list, optional
Node IDs to preserve.
rm_loop : bool
If True, remove isolated loops.
iterate : bool
If True, repeat until only intersection nodes remain.
silent : bool
If False and iterate=True, show progress.
Returns
-------
dict
Simplified graph object.
"""
to_keep = [0] * graph["nbnode"]
if keep is not None:
keep_set = {str(k) for k in keep}
refs = graph["dict"]["ref"].values
for i, ref in enumerate(refs):
if ref in keep_set:
to_keep[i] = 1
gfrom = graph["data"]["from"].values
gto = graph["data"]["to"].values
gw = graph["data"]["dist"].values
new_from, new_to, new_w = simplify_graph(
gfrom, gto, gw, graph["nbnode"], to_keep, rm_loop, iterate, not silent
)
if len(new_from) == 0:
raise ValueError("All nodes have been removed")
simp = pd.DataFrame({"from": new_from, "to": new_to, "dist": new_w})
# Rebuild node dictionary
used_nodes = set(new_from) | set(new_to)
old_dict = graph["dict"]
new_dict = old_dict[old_dict["id"].isin(used_nodes)].copy()
new_dict = new_dict.reset_index(drop=True)
# Remap IDs
old_to_new = dict(zip(new_dict["id"], range(len(new_dict))))
simp["from"] = simp["from"].map(old_to_new).astype(int)
simp["to"] = simp["to"].map(old_to_new).astype(int)
new_dict["id"] = range(len(new_dict))
coords_out = None
if graph["coords"] is not None:
old_refs = new_dict["ref"].values
coords_out = graph["coords"][graph["coords"]["node"].isin(old_refs)].copy()
# Reorder to match new dict
coords_out = coords_out.set_index("node").loc[old_refs].reset_index()
return {
"data": simp,
"coords": coords_out,
"nbnode": len(new_dict),
"dict": new_dict,
"attrib": {"aux": None, "cap": None, "alpha": None, "beta": None},
}
def cpp_contract(graph, silent=False):
"""Contract a graph using contraction hierarchies.
Parameters
----------
graph : dict
Graph from makegraph() or cpp_simplify().
silent : bool
If True, suppress progress output.
Returns
-------
dict
Contracted graph with 6 keys: data, rank, shortcuts, nbnode, dict, original.
"""
if len(graph) != 5:
raise ValueError("Input should be generated by makegraph() or cpp_simplify()")
gfrom = graph["data"]["from"].values
gto = graph["data"]["to"].values
gw = graph["data"]["dist"].values
c_from, c_to, c_w, rank, sf, st, sv = contract_graph(
gfrom, gto, gw, graph["nbnode"], verbose=not silent
)
return {
"data": pd.DataFrame({"from": c_from, "to": c_to, "dist": c_w}),
"rank": rank,
"shortcuts": pd.DataFrame({"shortf": sf, "shortt": st, "shortc": sv}),
"nbnode": graph["nbnode"],
"dict": graph["dict"],
"original": {"data": graph["data"], "attrib": graph["attrib"]},
}