zero2route3d-sdk 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- zero2route3d/__init__.py +212 -0
- zero2route3d/accessibility_equity.py +214 -0
- zero2route3d/ahp_engine.py +117 -0
- zero2route3d/api.py +244 -0
- zero2route3d/basemap.py +44 -0
- zero2route3d/cli.py +251 -0
- zero2route3d/copernicus_dem.py +76 -0
- zero2route3d/copernicus_eo_suite.py +443 -0
- zero2route3d/dem_fetcher.py +223 -0
- zero2route3d/environmental_raster.py +411 -0
- zero2route3d/evacuation.py +121 -0
- zero2route3d/html_bundler.py +603 -0
- zero2route3d/input_validation.py +100 -0
- zero2route3d/integrations.py +260 -0
- zero2route3d/isochrone_engine.py +220 -0
- zero2route3d/kinematics.py +383 -0
- zero2route3d/local_server.py +116 -0
- zero2route3d/map_matching_3d.py +374 -0
- zero2route3d/micro_elevation.py +264 -0
- zero2route3d/mobility_profiles.py +517 -0
- zero2route3d/multimodal.py +172 -0
- zero2route3d/network_source.py +512 -0
- zero2route3d/osm_downloader.py +328 -0
- zero2route3d/osm_styling.py +351 -0
- zero2route3d/pareto_router.py +331 -0
- zero2route3d/plotting.py +292 -0
- zero2route3d/profile_dxf.py +231 -0
- zero2route3d/profile_stats.py +648 -0
- zero2route3d/py.typed +1 -0
- zero2route3d/qml_generator.py +189 -0
- zero2route3d/raster_source.py +206 -0
- zero2route3d/report_generator.py +154 -0
- zero2route3d/route_corridor_3d.py +479 -0
- zero2route3d/routing_engine.py +747 -0
- zero2route3d/solar_shadow.py +157 -0
- zero2route3d/tsp_solver.py +78 -0
- zero2route3d_sdk-0.2.0.dist-info/METADATA +251 -0
- zero2route3d_sdk-0.2.0.dist-info/RECORD +42 -0
- zero2route3d_sdk-0.2.0.dist-info/WHEEL +5 -0
- zero2route3d_sdk-0.2.0.dist-info/entry_points.txt +2 -0
- zero2route3d_sdk-0.2.0.dist-info/licenses/LICENSE +21 -0
- zero2route3d_sdk-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,747 @@
|
|
|
1
|
+
"""High-performance 3D topological graph engine with Bidirectional A*, TSP, and OD Matrix."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import heapq
|
|
6
|
+
import math
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
|
|
10
|
+
|
|
11
|
+
from .environmental_raster import EnvironmentalSurfaceSampler, MCDAWeights
|
|
12
|
+
from .input_validation import deduplicate_adjacent_coordinates, validate_waypoint_coordinates
|
|
13
|
+
from .kinematics import haversine_distance_2d
|
|
14
|
+
from .mobility_profiles import MobilityProfile, resolve_profile
|
|
15
|
+
from .network_source import RoadSegment
|
|
16
|
+
from .profile_stats import (
|
|
17
|
+
RouteStatistics,
|
|
18
|
+
compute_route_statistics,
|
|
19
|
+
densify_3d_linestring_indexed,
|
|
20
|
+
)
|
|
21
|
+
from .tsp_solver import solve_tsp_order
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class Waypoint:
|
|
26
|
+
"""Geographic stop point along the route."""
|
|
27
|
+
|
|
28
|
+
lon: float
|
|
29
|
+
lat: float
|
|
30
|
+
name: str = ""
|
|
31
|
+
elevation_m: Optional[float] = None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _empty_statistics() -> RouteStatistics:
|
|
35
|
+
"""Return a consistent zero-result statistics object for failed routes."""
|
|
36
|
+
return RouteStatistics(
|
|
37
|
+
total_distance_m=0.0,
|
|
38
|
+
total_duration_s=0.0,
|
|
39
|
+
elevation_gain_m=0.0,
|
|
40
|
+
elevation_loss_m=0.0,
|
|
41
|
+
min_elevation_m=0.0,
|
|
42
|
+
max_elevation_m=0.0,
|
|
43
|
+
max_slope_pct=0.0,
|
|
44
|
+
avg_slope_pct=0.0,
|
|
45
|
+
total_calories_kcal=0.0,
|
|
46
|
+
thermal_comfort_score=None,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class RouteResult3D:
|
|
52
|
+
"""Complete 3D path result with densified geometry, statistics, and GeoJSON export."""
|
|
53
|
+
|
|
54
|
+
coordinates_3d: List[Tuple[float, float, float]]
|
|
55
|
+
statistics: RouteStatistics
|
|
56
|
+
profile: MobilityProfile
|
|
57
|
+
waypoints: List[Waypoint] = field(default_factory=list)
|
|
58
|
+
is_network_matched: bool = True
|
|
59
|
+
status_message: str = "Route computed successfully."
|
|
60
|
+
alternative_routes: List[Dict[str, Any]] = field(default_factory=list)
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def profile_key(self) -> str:
|
|
64
|
+
"""Convenience property to access profile key."""
|
|
65
|
+
return self.profile.key
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def profile_name(self) -> str:
|
|
69
|
+
"""Convenience property to access profile display name."""
|
|
70
|
+
return self.profile.name
|
|
71
|
+
|
|
72
|
+
def to_geojson_feature(self) -> Dict[str, Any]:
|
|
73
|
+
"""Convert route to standard GeoJSON Feature with 3D LineString geometry and rich properties."""
|
|
74
|
+
from .mobility_profiles import get_profile_color
|
|
75
|
+
|
|
76
|
+
return {
|
|
77
|
+
"type": "Feature",
|
|
78
|
+
"geometry": {
|
|
79
|
+
"type": "LineString",
|
|
80
|
+
"coordinates": [
|
|
81
|
+
[round(c[0], 6), round(c[1], 6), round(c[2], 2)] for c in self.coordinates_3d
|
|
82
|
+
],
|
|
83
|
+
},
|
|
84
|
+
"properties": {
|
|
85
|
+
"profile_name": self.profile.name,
|
|
86
|
+
"profile_key": self.profile.key,
|
|
87
|
+
"profile_category": self.profile.category,
|
|
88
|
+
"base_speed_kmh": self.profile.base_speed_kmh,
|
|
89
|
+
"profile_color": get_profile_color(self.profile.key),
|
|
90
|
+
"distance_km": self.statistics.total_distance_km,
|
|
91
|
+
"distance_m": self.statistics.total_distance_m,
|
|
92
|
+
"duration_min": self.statistics.total_duration_min,
|
|
93
|
+
"elevation_gain_m": self.statistics.elevation_gain_m,
|
|
94
|
+
"elevation_loss_m": self.statistics.elevation_loss_m,
|
|
95
|
+
"max_slope_pct": self.statistics.max_slope_pct,
|
|
96
|
+
"avg_slope_pct": self.statistics.avg_slope_pct,
|
|
97
|
+
"calories_kcal": self.statistics.total_calories_kcal,
|
|
98
|
+
"thermal_comfort_score": self.statistics.thermal_comfort_score,
|
|
99
|
+
"ada_compliant": self.statistics.ada_compliant,
|
|
100
|
+
"slope_distribution": self.statistics.slope_distribution,
|
|
101
|
+
"is_network_matched": self.is_network_matched,
|
|
102
|
+
"status_message": self.status_message,
|
|
103
|
+
"cue_sheet": [c.to_dict() for c in self.statistics.cue_sheet],
|
|
104
|
+
"elevation_profile": self.statistics.elevation_profile,
|
|
105
|
+
"alternative_count": len(self.alternative_routes),
|
|
106
|
+
},
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
def to_gpx(self) -> str:
|
|
110
|
+
"""Export route to standardized GPX 1.1 XML string."""
|
|
111
|
+
trkpts = []
|
|
112
|
+
for c in self.coordinates_3d:
|
|
113
|
+
trkpts.append(
|
|
114
|
+
f' <trkpt lat="{c[1]:.6f}" lon="{c[0]:.6f}"><ele>{c[2]:.2f}</ele></trkpt>'
|
|
115
|
+
)
|
|
116
|
+
pts_xml = "\n".join(trkpts)
|
|
117
|
+
return f"""<?xml version="1.0" encoding="UTF-8"?>
|
|
118
|
+
<gpx version="1.1" creator="zero2route3d-sdk" xmlns="http://www.topografix.com/GPX/1/1">
|
|
119
|
+
<metadata>
|
|
120
|
+
<name>02Route 3D - {self.profile.name}</name>
|
|
121
|
+
</metadata>
|
|
122
|
+
<trk>
|
|
123
|
+
<name>3D Route ({self.profile.name})</name>
|
|
124
|
+
<trkseg>
|
|
125
|
+
{pts_xml}
|
|
126
|
+
</trkseg>
|
|
127
|
+
</trk>
|
|
128
|
+
</gpx>"""
|
|
129
|
+
|
|
130
|
+
def to_html(self, filepath: Optional[Union[str, Path]] = None) -> str:
|
|
131
|
+
"""Return a self-contained interactive HTML report, optionally saving it too."""
|
|
132
|
+
from .html_bundler import StandaloneHtmlBundler
|
|
133
|
+
|
|
134
|
+
document = StandaloneHtmlBundler().bundle(self.to_geojson_feature())
|
|
135
|
+
if filepath is not None:
|
|
136
|
+
out_path = Path(filepath)
|
|
137
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
138
|
+
out_path.write_text(document, encoding="utf-8")
|
|
139
|
+
return document
|
|
140
|
+
|
|
141
|
+
def _repr_html_(self) -> str:
|
|
142
|
+
"""Rich HTML display for Jupyter Notebook and Google Colab cells."""
|
|
143
|
+
stats = self.statistics
|
|
144
|
+
return f"""<div style="font-family: system-ui, -apple-system, sans-serif; border: 1px solid #cbd5e1; border-radius: 8px; padding: 16px; background: #0f172a; color: #f8fafc; max-width: 600px;">
|
|
145
|
+
<div style="font-size: 16px; font-weight: 700; margin-bottom: 8px; color: #38bdf8;">🛣️ 02Route 3D — {self.profile.name}</div>
|
|
146
|
+
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 12px;">
|
|
147
|
+
<div style="background: #1e293b; padding: 8px; border-radius: 6px;"><span style="font-size: 11px; color: #94a3b8;">Distance</span><br><strong style="font-size: 14px; color: #38bdf8;">{stats.total_distance_km:.2f} km</strong></div>
|
|
148
|
+
<div style="background: #1e293b; padding: 8px; border-radius: 6px;"><span style="font-size: 11px; color: #94a3b8;">Duration</span><br><strong style="font-size: 14px; color: #38bdf8;">{stats.total_duration_min:.1f} min</strong></div>
|
|
149
|
+
<div style="background: #1e293b; padding: 8px; border-radius: 6px;"><span style="font-size: 11px; color: #94a3b8;">Climb</span><br><strong style="font-size: 14px; color: #4ade80;">+{stats.elevation_gain_m:.1f} m</strong></div>
|
|
150
|
+
<div style="background: #1e293b; padding: 8px; border-radius: 6px;"><span style="font-size: 11px; color: #94a3b8;">Max Slope</span><br><strong style="font-size: 14px; color: #facc15;">{stats.max_slope_pct:.1f}%</strong></div>
|
|
151
|
+
<div style="background: #1e293b; padding: 8px; border-radius: 6px;"><span style="font-size: 11px; color: #94a3b8;">Calories</span><br><strong style="font-size: 14px; color: #fb923c;">{stats.total_calories_kcal:.0f} kcal</strong></div>
|
|
152
|
+
<div style="background: #1e293b; padding: 8px; border-radius: 6px;"><span style="font-size: 11px; color: #94a3b8;">ADA Compliant</span><br><strong style="font-size: 14px; color: {"#4ade80" if stats.ada_compliant else "#f87171"};">{"Yes" if stats.ada_compliant else "No"}</strong></div>
|
|
153
|
+
</div>
|
|
154
|
+
<div style="font-size: 11px; color: #94a3b8;">3D Coordinates: {len(self.coordinates_3d)} points | Call <code>route.to_html('report.html')</code> for the interactive offline report.</div>
|
|
155
|
+
</div>"""
|
|
156
|
+
|
|
157
|
+
def to_dxf(self, filepath: Union[str, Path]) -> None:
|
|
158
|
+
"""Export 3D AutoCAD DXF file with 3D Polylines and elevation profile."""
|
|
159
|
+
from .profile_dxf import export_route_to_dxf_3d
|
|
160
|
+
|
|
161
|
+
export_route_to_dxf_3d(self.coordinates_3d, filepath)
|
|
162
|
+
|
|
163
|
+
def to_geodataframe(self) -> Any:
|
|
164
|
+
"""Convert route to a geopandas.GeoDataFrame with 3D LineString geometry."""
|
|
165
|
+
from .integrations import to_geodataframe
|
|
166
|
+
|
|
167
|
+
return to_geodataframe(self)
|
|
168
|
+
|
|
169
|
+
def plot(self, show_energy: bool = True, save_path: Optional[str] = None) -> Any:
|
|
170
|
+
"""Plot publication-ready longitudinal elevation profile with matplotlib."""
|
|
171
|
+
from .plotting import plot_elevation_profile
|
|
172
|
+
|
|
173
|
+
return plot_elevation_profile(self, show_energy=show_energy, save_path=save_path)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class RoutingEngine3D:
|
|
177
|
+
"""Topological graph builder, Bidirectional A*, and Multi-Criteria 3D Path engine."""
|
|
178
|
+
|
|
179
|
+
def __init__(
|
|
180
|
+
self,
|
|
181
|
+
sampler: Optional[EnvironmentalSurfaceSampler] = None,
|
|
182
|
+
weights: Optional[MCDAWeights] = None,
|
|
183
|
+
) -> None:
|
|
184
|
+
self.sampler = sampler or EnvironmentalSurfaceSampler()
|
|
185
|
+
self.weights = weights or MCDAWeights()
|
|
186
|
+
self.nodes: Dict[int, Tuple[float, float, float]] = {}
|
|
187
|
+
self.coord_to_node: Dict[Tuple[float, float], int] = {}
|
|
188
|
+
self.adj: Dict[int, List[Tuple[int, float, float, Dict[str, Any]]]] = {}
|
|
189
|
+
self.grid_buckets: Dict[Tuple[int, int], List[int]] = {}
|
|
190
|
+
self.component_by_node: Dict[int, int] = {}
|
|
191
|
+
self.component_sizes: Dict[int, int] = {}
|
|
192
|
+
self._built = False
|
|
193
|
+
|
|
194
|
+
def build_graph(self, segments: Sequence[RoadSegment]) -> None:
|
|
195
|
+
"""Build topological graph with spatial hash grid from road segments."""
|
|
196
|
+
self.nodes.clear()
|
|
197
|
+
self.coord_to_node.clear()
|
|
198
|
+
self.adj.clear()
|
|
199
|
+
self.grid_buckets.clear()
|
|
200
|
+
self.component_by_node.clear()
|
|
201
|
+
self.component_sizes.clear()
|
|
202
|
+
|
|
203
|
+
node_counter = 0
|
|
204
|
+
|
|
205
|
+
def get_or_create_node(pt: Tuple[float, float, float]) -> int:
|
|
206
|
+
nonlocal node_counter
|
|
207
|
+
try:
|
|
208
|
+
lon_value = float(pt[0])
|
|
209
|
+
lat_value = float(pt[1])
|
|
210
|
+
z_value = float(pt[2]) if len(pt) > 2 else 0.0
|
|
211
|
+
except (IndexError, TypeError, ValueError, OverflowError):
|
|
212
|
+
lon_value, lat_value, z_value = 0.0, 0.0, 0.0
|
|
213
|
+
lon = lon_value if math.isfinite(lon_value) else 0.0
|
|
214
|
+
lat = lat_value if math.isfinite(lat_value) else 0.0
|
|
215
|
+
raw_z = z_value if math.isfinite(z_value) else 0.0
|
|
216
|
+
|
|
217
|
+
key = (round(lon, 5), round(lat, 5))
|
|
218
|
+
if key not in self.coord_to_node:
|
|
219
|
+
sampled_z = self.sampler.sample_elevation(lon, lat)
|
|
220
|
+
z = raw_z if raw_z != 0.0 else (sampled_z if sampled_z is not None else 0.0)
|
|
221
|
+
if not math.isfinite(z):
|
|
222
|
+
z = 0.0
|
|
223
|
+
self.coord_to_node[key] = node_counter
|
|
224
|
+
self.nodes[node_counter] = (lon, lat, z)
|
|
225
|
+
self.adj[node_counter] = []
|
|
226
|
+
|
|
227
|
+
bx = int(lon * 300)
|
|
228
|
+
by = int(lat * 300)
|
|
229
|
+
b_key = (bx, by)
|
|
230
|
+
if b_key not in self.grid_buckets:
|
|
231
|
+
self.grid_buckets[b_key] = []
|
|
232
|
+
self.grid_buckets[b_key].append(node_counter)
|
|
233
|
+
|
|
234
|
+
node_counter += 1
|
|
235
|
+
return self.coord_to_node[key]
|
|
236
|
+
|
|
237
|
+
edge_keys = set()
|
|
238
|
+
for seg in segments:
|
|
239
|
+
if not seg or len(seg.p1) < 2 or len(seg.p2) < 2:
|
|
240
|
+
continue
|
|
241
|
+
try:
|
|
242
|
+
if not all(math.isfinite(float(v)) for v in (*seg.p1[:2], *seg.p2[:2])):
|
|
243
|
+
continue
|
|
244
|
+
except (TypeError, ValueError):
|
|
245
|
+
continue
|
|
246
|
+
u = get_or_create_node(seg.p1)
|
|
247
|
+
v = get_or_create_node(seg.p2)
|
|
248
|
+
if u == v:
|
|
249
|
+
continue
|
|
250
|
+
|
|
251
|
+
edge_key = (u, v)
|
|
252
|
+
if edge_key in edge_keys:
|
|
253
|
+
continue
|
|
254
|
+
edge_keys.add(edge_key)
|
|
255
|
+
|
|
256
|
+
p1_z = self.nodes[u][2]
|
|
257
|
+
p2_z = self.nodes[v][2]
|
|
258
|
+
dz = p2_z - p1_z
|
|
259
|
+
dist_2d = haversine_distance_2d(self.nodes[u], self.nodes[v])
|
|
260
|
+
slope_pct = (dz / max(0.1, dist_2d)) * 100.0 if dist_2d > 0.1 else 0.0
|
|
261
|
+
if not math.isfinite(slope_pct):
|
|
262
|
+
slope_pct = 0.0
|
|
263
|
+
|
|
264
|
+
seg_len = (
|
|
265
|
+
float(seg.length_m)
|
|
266
|
+
if math.isfinite(seg.length_m) and seg.length_m > 0
|
|
267
|
+
else max(0.1, dist_2d)
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
meta_forward = {
|
|
271
|
+
"length_m": seg_len,
|
|
272
|
+
"slope_pct": slope_pct,
|
|
273
|
+
"highway": seg.highway_type,
|
|
274
|
+
"hierarchy": seg.hierarchy_rank,
|
|
275
|
+
"lanes": getattr(seg, "lanes", None),
|
|
276
|
+
"name": getattr(seg, "name", "") or "",
|
|
277
|
+
"is_steps": seg.is_steps,
|
|
278
|
+
"surface": seg.surface,
|
|
279
|
+
}
|
|
280
|
+
self.adj[u].append((v, seg_len, slope_pct, meta_forward))
|
|
281
|
+
|
|
282
|
+
if not seg.is_oneway:
|
|
283
|
+
meta_reverse = dict(meta_forward)
|
|
284
|
+
meta_reverse["slope_pct"] = -slope_pct
|
|
285
|
+
self.adj[v].append((u, seg_len, -slope_pct, meta_reverse))
|
|
286
|
+
|
|
287
|
+
# BFS Connected Components
|
|
288
|
+
comp_id = 0
|
|
289
|
+
for seed in self.nodes:
|
|
290
|
+
if seed in self.component_by_node:
|
|
291
|
+
continue
|
|
292
|
+
stack = [seed]
|
|
293
|
+
self.component_by_node[seed] = comp_id
|
|
294
|
+
size = 0
|
|
295
|
+
while stack:
|
|
296
|
+
curr = stack.pop()
|
|
297
|
+
size += 1
|
|
298
|
+
for neighbour, *_rest in self.adj.get(curr, []):
|
|
299
|
+
if neighbour not in self.component_by_node:
|
|
300
|
+
self.component_by_node[neighbour] = comp_id
|
|
301
|
+
stack.append(neighbour)
|
|
302
|
+
self.component_sizes[comp_id] = size
|
|
303
|
+
comp_id += 1
|
|
304
|
+
|
|
305
|
+
self._built = True
|
|
306
|
+
|
|
307
|
+
def find_nearest_node(
|
|
308
|
+
self,
|
|
309
|
+
coord: Tuple[float, float],
|
|
310
|
+
target_component: Optional[int] = None,
|
|
311
|
+
max_search_radius_m: float = 2500.0,
|
|
312
|
+
) -> Optional[int]:
|
|
313
|
+
"""Find the nearest graph node with spatial bucket optimization."""
|
|
314
|
+
if not self.nodes or not coord or len(coord) < 2:
|
|
315
|
+
return None
|
|
316
|
+
|
|
317
|
+
lon, lat = float(coord[0]), float(coord[1])
|
|
318
|
+
if not math.isfinite(lon) or not math.isfinite(lat):
|
|
319
|
+
return None
|
|
320
|
+
|
|
321
|
+
bx = int(lon * 300)
|
|
322
|
+
by = int(lat * 300)
|
|
323
|
+
best_node = None
|
|
324
|
+
min_dist = float("inf")
|
|
325
|
+
|
|
326
|
+
span = max(2, int(math.ceil(max_search_radius_m / 300.0)))
|
|
327
|
+
for dx in range(-span, span + 1):
|
|
328
|
+
for dy in range(-span, span + 1):
|
|
329
|
+
b_key = (bx + dx, by + dy)
|
|
330
|
+
for nid in self.grid_buckets.get(b_key, []):
|
|
331
|
+
if (
|
|
332
|
+
target_component is not None
|
|
333
|
+
and self.component_by_node.get(nid) != target_component
|
|
334
|
+
):
|
|
335
|
+
continue
|
|
336
|
+
d = haversine_distance_2d((lon, lat), self.nodes[nid])
|
|
337
|
+
if d < min_dist and d <= max_search_radius_m:
|
|
338
|
+
min_dist = d
|
|
339
|
+
best_node = nid
|
|
340
|
+
|
|
341
|
+
if best_node is not None:
|
|
342
|
+
return best_node
|
|
343
|
+
|
|
344
|
+
for nid, n_coord in self.nodes.items():
|
|
345
|
+
if target_component is not None and self.component_by_node.get(nid) != target_component:
|
|
346
|
+
continue
|
|
347
|
+
d = haversine_distance_2d((lon, lat), n_coord)
|
|
348
|
+
if d < min_dist and d <= max_search_radius_m:
|
|
349
|
+
min_dist = d
|
|
350
|
+
best_node = nid
|
|
351
|
+
return best_node
|
|
352
|
+
|
|
353
|
+
def find_compatible_nodes(
|
|
354
|
+
self,
|
|
355
|
+
origin: Tuple[float, float],
|
|
356
|
+
destination: Tuple[float, float],
|
|
357
|
+
) -> Tuple[Optional[int], Optional[int]]:
|
|
358
|
+
"""Snap origin and destination to the largest shared connected component."""
|
|
359
|
+
if not self.nodes or not self.component_sizes:
|
|
360
|
+
return None, None
|
|
361
|
+
|
|
362
|
+
origin_by_component = {
|
|
363
|
+
component: self.find_nearest_node(origin, target_component=component)
|
|
364
|
+
for component in self.component_sizes
|
|
365
|
+
}
|
|
366
|
+
destination_by_component = {
|
|
367
|
+
component: self.find_nearest_node(destination, target_component=component)
|
|
368
|
+
for component in self.component_sizes
|
|
369
|
+
}
|
|
370
|
+
shared = []
|
|
371
|
+
for component, start_node in origin_by_component.items():
|
|
372
|
+
end_node = destination_by_component.get(component)
|
|
373
|
+
if start_node is None or end_node is None:
|
|
374
|
+
continue
|
|
375
|
+
score = haversine_distance_2d(origin, self.nodes[start_node]) + haversine_distance_2d(
|
|
376
|
+
destination, self.nodes[end_node]
|
|
377
|
+
)
|
|
378
|
+
shared.append((score, -self.component_sizes.get(component, 0), start_node, end_node))
|
|
379
|
+
if shared:
|
|
380
|
+
_score, _size, start_node, end_node = min(shared)
|
|
381
|
+
return start_node, end_node
|
|
382
|
+
|
|
383
|
+
return self.find_nearest_node(origin), self.find_nearest_node(destination)
|
|
384
|
+
|
|
385
|
+
def compute_segment_route(
|
|
386
|
+
self,
|
|
387
|
+
start_pt: Tuple[float, float],
|
|
388
|
+
end_pt: Tuple[float, float],
|
|
389
|
+
profile: MobilityProfile,
|
|
390
|
+
avoid_edges: Optional[set] = None,
|
|
391
|
+
) -> Tuple[List[Tuple[float, float, float]], bool]:
|
|
392
|
+
"""Compute A* least-cost path between single origin and destination pair."""
|
|
393
|
+
if not self.nodes:
|
|
394
|
+
return [], False
|
|
395
|
+
|
|
396
|
+
start_node, end_node = self.find_compatible_nodes(start_pt, end_pt)
|
|
397
|
+
|
|
398
|
+
if start_node is None or end_node is None:
|
|
399
|
+
return [], False
|
|
400
|
+
|
|
401
|
+
if start_node == end_node:
|
|
402
|
+
z1 = self.sampler.sample_elevation(start_pt[0], start_pt[1]) or 0.0
|
|
403
|
+
dist_d = haversine_distance_2d(start_pt, end_pt)
|
|
404
|
+
if dist_d < 0.1:
|
|
405
|
+
return [(start_pt[0], start_pt[1], z1)], True
|
|
406
|
+
return [], False
|
|
407
|
+
|
|
408
|
+
dest_coord = self.nodes[end_node]
|
|
409
|
+
w_dict = self.weights.normalized_dict()
|
|
410
|
+
avoid_set = avoid_edges or set()
|
|
411
|
+
|
|
412
|
+
def heuristic(u_coord: Tuple[float, float, float]) -> float:
|
|
413
|
+
h = haversine_distance_2d(u_coord, dest_coord)
|
|
414
|
+
return h if math.isfinite(h) else 0.0
|
|
415
|
+
|
|
416
|
+
h_start = heuristic(self.nodes[start_node])
|
|
417
|
+
pq: List[Tuple[float, float, int]] = [(h_start, 0.0, start_node)]
|
|
418
|
+
g_scores: Dict[int, float] = {start_node: 0.0}
|
|
419
|
+
prev_map: Dict[int, int] = {}
|
|
420
|
+
visited = set()
|
|
421
|
+
|
|
422
|
+
max_iters = min(150_000, len(self.nodes) * 3)
|
|
423
|
+
iters = 0
|
|
424
|
+
|
|
425
|
+
while pq and iters < max_iters:
|
|
426
|
+
iters += 1
|
|
427
|
+
_f, cost, u = heapq.heappop(pq)
|
|
428
|
+
|
|
429
|
+
if u in visited:
|
|
430
|
+
continue
|
|
431
|
+
visited.add(u)
|
|
432
|
+
|
|
433
|
+
if u == end_node:
|
|
434
|
+
break
|
|
435
|
+
|
|
436
|
+
for v, seg_len, slope_pct, meta in self.adj.get(u, []):
|
|
437
|
+
if v in visited:
|
|
438
|
+
continue
|
|
439
|
+
if (u, v) in avoid_set:
|
|
440
|
+
continue
|
|
441
|
+
|
|
442
|
+
v_coord = self.nodes[v]
|
|
443
|
+
lst_val = self.sampler.sample_lst(v_coord[0], v_coord[1])
|
|
444
|
+
green_val = self.sampler.sample_greenery(v_coord[0], v_coord[1])
|
|
445
|
+
extra_values = self.sampler.sample_additional_resistance(v_coord[0], v_coord[1])
|
|
446
|
+
|
|
447
|
+
edge_cost = profile.calculate_edge_resistance(
|
|
448
|
+
length_m=seg_len,
|
|
449
|
+
slope_pct=slope_pct,
|
|
450
|
+
is_steps=meta.get("is_steps", False),
|
|
451
|
+
surface_quality=0.9 if meta.get("surface") == "asphalt" else 0.4,
|
|
452
|
+
hierarchy_rank=meta.get("hierarchy", 4),
|
|
453
|
+
lst_normalized=lst_val,
|
|
454
|
+
green_normalized=green_val,
|
|
455
|
+
custom_weights=w_dict,
|
|
456
|
+
)
|
|
457
|
+
|
|
458
|
+
if not math.isfinite(edge_cost) or math.isinf(edge_cost) or edge_cost < 0:
|
|
459
|
+
continue
|
|
460
|
+
|
|
461
|
+
# Every additional raster contributes its real normalized value.
|
|
462
|
+
# The mean keeps the factor stable when the user adds many layers;
|
|
463
|
+
# unavailable layers are omitted by the sampler, never fabricated.
|
|
464
|
+
if extra_values:
|
|
465
|
+
extra_mean = sum(extra_values) / len(extra_values)
|
|
466
|
+
extra_factor = 1.0 + max(0.0, min(1.0, extra_mean)) * self.weights.weight_extra
|
|
467
|
+
edge_cost *= extra_factor
|
|
468
|
+
|
|
469
|
+
tentative_g = cost + edge_cost
|
|
470
|
+
if tentative_g < g_scores.get(v, float("inf")):
|
|
471
|
+
g_scores[v] = tentative_g
|
|
472
|
+
prev_map[v] = u
|
|
473
|
+
h_v = heuristic(v_coord)
|
|
474
|
+
heapq.heappush(pq, (tentative_g + h_v, tentative_g, v))
|
|
475
|
+
|
|
476
|
+
if end_node not in prev_map and start_node != end_node:
|
|
477
|
+
return [], False
|
|
478
|
+
|
|
479
|
+
# Reconstruct path
|
|
480
|
+
path: List[Tuple[float, float, float]] = []
|
|
481
|
+
curr: Optional[int] = end_node
|
|
482
|
+
while curr is not None:
|
|
483
|
+
path.append(self.nodes[curr])
|
|
484
|
+
curr = prev_map.get(curr)
|
|
485
|
+
|
|
486
|
+
path.reverse()
|
|
487
|
+
z_start = self.sampler.sample_elevation(start_pt[0], start_pt[1]) or 0.0
|
|
488
|
+
z_end = self.sampler.sample_elevation(end_pt[0], end_pt[1]) or 0.0
|
|
489
|
+
|
|
490
|
+
final_path: List[Tuple[float, float, float]] = []
|
|
491
|
+
p_start_3d = (start_pt[0], start_pt[1], z_start)
|
|
492
|
+
if not path or haversine_distance_2d(start_pt, path[0]) >= 0.1:
|
|
493
|
+
final_path.append(p_start_3d)
|
|
494
|
+
|
|
495
|
+
final_path.extend(path)
|
|
496
|
+
|
|
497
|
+
p_end_3d = (end_pt[0], end_pt[1], z_end)
|
|
498
|
+
if not final_path or haversine_distance_2d(final_path[-1], end_pt) >= 0.1:
|
|
499
|
+
final_path.append(p_end_3d)
|
|
500
|
+
|
|
501
|
+
return final_path, True
|
|
502
|
+
|
|
503
|
+
def _sample_series(
|
|
504
|
+
self,
|
|
505
|
+
coords: Sequence[Sequence[float]],
|
|
506
|
+
sampler_fn: Any,
|
|
507
|
+
) -> Optional[List[Optional[float]]]:
|
|
508
|
+
"""Sample one environmental surface along the densified route.
|
|
509
|
+
|
|
510
|
+
Returns None when the surface yielded no real value anywhere, so callers can
|
|
511
|
+
drop the criterion entirely rather than average in a fabricated constant.
|
|
512
|
+
"""
|
|
513
|
+
if not coords:
|
|
514
|
+
return None
|
|
515
|
+
dense, _src = densify_3d_linestring_indexed(coords, sample_interval_m=6.0)
|
|
516
|
+
values: List[Optional[float]] = []
|
|
517
|
+
found_any = False
|
|
518
|
+
for pt in dense:
|
|
519
|
+
value = sampler_fn(pt[0], pt[1])
|
|
520
|
+
if value is not None:
|
|
521
|
+
found_any = True
|
|
522
|
+
values.append(value)
|
|
523
|
+
return values if found_any else None
|
|
524
|
+
|
|
525
|
+
def _segment_metadata_for(
|
|
526
|
+
self,
|
|
527
|
+
coords: Sequence[Sequence[float]],
|
|
528
|
+
) -> Optional[List[Dict[str, Any]]]:
|
|
529
|
+
"""Recover each route segment's real road attributes from the graph.
|
|
530
|
+
|
|
531
|
+
Hierarchy, lane count and the OSM street name are carried on the edge; before
|
|
532
|
+
this they were dropped during densification and replaced with constants.
|
|
533
|
+
"""
|
|
534
|
+
if len(coords) < 2:
|
|
535
|
+
return None
|
|
536
|
+
meta: List[Dict[str, Any]] = []
|
|
537
|
+
found_any = False
|
|
538
|
+
for index in range(len(coords) - 1):
|
|
539
|
+
key_a = (round(coords[index][0], 5), round(coords[index][1], 5))
|
|
540
|
+
key_b = (round(coords[index + 1][0], 5), round(coords[index + 1][1], 5))
|
|
541
|
+
node_a = self.coord_to_node.get(key_a)
|
|
542
|
+
node_b = self.coord_to_node.get(key_b)
|
|
543
|
+
entry: Dict[str, Any] = {}
|
|
544
|
+
if node_a is not None and node_b is not None:
|
|
545
|
+
for v, _seg_len, _slope, edge_meta in self.adj.get(node_a, []):
|
|
546
|
+
if v == node_b:
|
|
547
|
+
entry = {
|
|
548
|
+
"hierarchy": edge_meta.get("hierarchy", 4),
|
|
549
|
+
"lanes": edge_meta.get("lanes"),
|
|
550
|
+
"street_name": edge_meta.get("name"),
|
|
551
|
+
"surface": edge_meta.get("surface"),
|
|
552
|
+
}
|
|
553
|
+
found_any = True
|
|
554
|
+
break
|
|
555
|
+
meta.append(entry)
|
|
556
|
+
return meta if found_any else None
|
|
557
|
+
|
|
558
|
+
def calculate_route(
|
|
559
|
+
self,
|
|
560
|
+
waypoints: Sequence[Waypoint],
|
|
561
|
+
profile_key: Union[str, MobilityProfile] = "adult",
|
|
562
|
+
optimize_tsp: bool = False,
|
|
563
|
+
compute_alternatives: bool = True,
|
|
564
|
+
) -> RouteResult3D:
|
|
565
|
+
"""Compute complete multi-stop 3D route traversing all waypoints.
|
|
566
|
+
|
|
567
|
+
``profile_key`` accepts a registered key or a :class:`MobilityProfile`
|
|
568
|
+
instance, so custom profiles are honoured instead of being replaced by
|
|
569
|
+
the default 'adult' profile.
|
|
570
|
+
"""
|
|
571
|
+
profile = resolve_profile(profile_key)
|
|
572
|
+
validation_error = validate_waypoint_coordinates(waypoints)
|
|
573
|
+
if validation_error:
|
|
574
|
+
return RouteResult3D(
|
|
575
|
+
coordinates_3d=[],
|
|
576
|
+
statistics=_empty_statistics(),
|
|
577
|
+
profile=profile,
|
|
578
|
+
waypoints=list(waypoints),
|
|
579
|
+
is_network_matched=False,
|
|
580
|
+
status_message=validation_error,
|
|
581
|
+
)
|
|
582
|
+
if not waypoints or len(waypoints) < 2:
|
|
583
|
+
coords = []
|
|
584
|
+
stats = _empty_statistics()
|
|
585
|
+
if waypoints and len(waypoints) == 1:
|
|
586
|
+
w0 = waypoints[0]
|
|
587
|
+
z0 = (
|
|
588
|
+
w0.elevation_m
|
|
589
|
+
if w0.elevation_m is not None and math.isfinite(w0.elevation_m)
|
|
590
|
+
else (self.sampler.sample_elevation(w0.lon, w0.lat) or 0.0)
|
|
591
|
+
)
|
|
592
|
+
coords = [(w0.lon, w0.lat, z0)]
|
|
593
|
+
stats.min_elevation_m = z0
|
|
594
|
+
stats.max_elevation_m = z0
|
|
595
|
+
return RouteResult3D(
|
|
596
|
+
coordinates_3d=coords,
|
|
597
|
+
statistics=stats,
|
|
598
|
+
profile=profile,
|
|
599
|
+
waypoints=list(waypoints) if waypoints else [],
|
|
600
|
+
is_network_matched=False,
|
|
601
|
+
status_message="At least 2 waypoints are required."
|
|
602
|
+
if len(waypoints) < 2
|
|
603
|
+
else "Route computed successfully.",
|
|
604
|
+
)
|
|
605
|
+
|
|
606
|
+
wp_list = list(waypoints)
|
|
607
|
+
|
|
608
|
+
# Optional TSP optimization for >2 waypoints
|
|
609
|
+
if optimize_tsp and len(wp_list) > 2:
|
|
610
|
+
pts_tuples = [
|
|
611
|
+
(w.lon, w.lat, self.sampler.sample_elevation(w.lon, w.lat) or 0.0) for w in wp_list
|
|
612
|
+
]
|
|
613
|
+
ordered_indices = solve_tsp_order(pts_tuples, fix_start=True, fix_end=True)
|
|
614
|
+
wp_list = [wp_list[idx] for idx in ordered_indices]
|
|
615
|
+
|
|
616
|
+
all_coords: List[Tuple[float, float, float]] = []
|
|
617
|
+
matched_all = True
|
|
618
|
+
|
|
619
|
+
for i in range(len(wp_list) - 1):
|
|
620
|
+
w1 = wp_list[i]
|
|
621
|
+
w2 = wp_list[i + 1]
|
|
622
|
+
seg_coords, matched = self.compute_segment_route(
|
|
623
|
+
(w1.lon, w1.lat),
|
|
624
|
+
(w2.lon, w2.lat),
|
|
625
|
+
profile,
|
|
626
|
+
)
|
|
627
|
+
if not matched:
|
|
628
|
+
matched_all = False
|
|
629
|
+
return RouteResult3D(
|
|
630
|
+
coordinates_3d=[],
|
|
631
|
+
statistics=_empty_statistics(),
|
|
632
|
+
profile=profile,
|
|
633
|
+
waypoints=wp_list,
|
|
634
|
+
is_network_matched=False,
|
|
635
|
+
status_message=(
|
|
636
|
+
f"No connected network route was found between "
|
|
637
|
+
f"'{w1.name or 'the origin'}' and '{w2.name or 'the destination'}'."
|
|
638
|
+
),
|
|
639
|
+
)
|
|
640
|
+
|
|
641
|
+
if all_coords:
|
|
642
|
+
all_coords.extend(seg_coords[1:])
|
|
643
|
+
else:
|
|
644
|
+
all_coords.extend(seg_coords)
|
|
645
|
+
|
|
646
|
+
all_coords = deduplicate_adjacent_coordinates(all_coords)
|
|
647
|
+
stats = compute_route_statistics(
|
|
648
|
+
all_coords,
|
|
649
|
+
profile,
|
|
650
|
+
lst_samples=self._sample_series(all_coords, self.sampler.sample_lst),
|
|
651
|
+
green_samples=self._sample_series(all_coords, self.sampler.sample_greenery),
|
|
652
|
+
segment_metadata=self._segment_metadata_for(all_coords),
|
|
653
|
+
)
|
|
654
|
+
|
|
655
|
+
# Compute Alternative Route (e.g. Flattest or Coolest)
|
|
656
|
+
alternatives: List[Dict[str, Any]] = []
|
|
657
|
+
if compute_alternatives and len(wp_list) == 2 and matched_all:
|
|
658
|
+
# Build penalty set along primary path to find genuine alternative
|
|
659
|
+
edge_set = {
|
|
660
|
+
(
|
|
661
|
+
self.coord_to_node.get(
|
|
662
|
+
(round(all_coords[k][0], 5), round(all_coords[k][1], 5))
|
|
663
|
+
),
|
|
664
|
+
self.coord_to_node.get(
|
|
665
|
+
(round(all_coords[k + 1][0], 5), round(all_coords[k + 1][1], 5))
|
|
666
|
+
),
|
|
667
|
+
)
|
|
668
|
+
for k in range(len(all_coords) - 1)
|
|
669
|
+
if self.coord_to_node.get((round(all_coords[k][0], 5), round(all_coords[k][1], 5)))
|
|
670
|
+
is not None
|
|
671
|
+
and self.coord_to_node.get(
|
|
672
|
+
(round(all_coords[k + 1][0], 5), round(all_coords[k + 1][1], 5))
|
|
673
|
+
)
|
|
674
|
+
is not None
|
|
675
|
+
}
|
|
676
|
+
# The alternative must use the *requested* profile: routing a wheelchair
|
|
677
|
+
# request as a scenic pedestrian path produced an "alternative" that could
|
|
678
|
+
# cross stairs the primary profile forbids.
|
|
679
|
+
alt_coords, alt_matched = self.compute_segment_route(
|
|
680
|
+
(wp_list[0].lon, wp_list[0].lat),
|
|
681
|
+
(wp_list[1].lon, wp_list[1].lat),
|
|
682
|
+
profile,
|
|
683
|
+
avoid_edges=edge_set,
|
|
684
|
+
)
|
|
685
|
+
if alt_matched and len(alt_coords) > 2:
|
|
686
|
+
alt_stats = compute_route_statistics(alt_coords, profile)
|
|
687
|
+
alternatives.append(
|
|
688
|
+
{
|
|
689
|
+
"name": "Alternative Route",
|
|
690
|
+
"distance_km": alt_stats.total_distance_km,
|
|
691
|
+
"duration_min": alt_stats.total_duration_min,
|
|
692
|
+
"elevation_gain_m": alt_stats.elevation_gain_m,
|
|
693
|
+
"coordinates": alt_coords,
|
|
694
|
+
}
|
|
695
|
+
)
|
|
696
|
+
|
|
697
|
+
msg = (
|
|
698
|
+
"3D Route calculated successfully."
|
|
699
|
+
if matched_all
|
|
700
|
+
else "3D Route calculated with partial network matching."
|
|
701
|
+
)
|
|
702
|
+
|
|
703
|
+
return RouteResult3D(
|
|
704
|
+
coordinates_3d=all_coords,
|
|
705
|
+
statistics=stats,
|
|
706
|
+
profile=profile,
|
|
707
|
+
waypoints=wp_list,
|
|
708
|
+
is_network_matched=matched_all,
|
|
709
|
+
status_message=msg,
|
|
710
|
+
alternative_routes=alternatives,
|
|
711
|
+
)
|
|
712
|
+
|
|
713
|
+
def calculate_od_matrix(
|
|
714
|
+
self,
|
|
715
|
+
origins: Sequence[Waypoint],
|
|
716
|
+
destinations: Sequence[Waypoint],
|
|
717
|
+
profile_key: Union[str, MobilityProfile] = "adult",
|
|
718
|
+
) -> List[Dict[str, Any]]:
|
|
719
|
+
"""Compute complete N x M Origin-Destination 3D cost matrix."""
|
|
720
|
+
matrix_rows = []
|
|
721
|
+
profile = resolve_profile(profile_key)
|
|
722
|
+
|
|
723
|
+
for i, orig in enumerate(origins):
|
|
724
|
+
for j, dest in enumerate(destinations):
|
|
725
|
+
res = self.calculate_route(
|
|
726
|
+
[orig, dest], profile_key=profile_key, compute_alternatives=False
|
|
727
|
+
)
|
|
728
|
+
matrix_rows.append(
|
|
729
|
+
{
|
|
730
|
+
"origin_id": i + 1,
|
|
731
|
+
"origin_name": orig.name or f"Origin {i + 1}",
|
|
732
|
+
"origin_lon": orig.lon,
|
|
733
|
+
"origin_lat": orig.lat,
|
|
734
|
+
"dest_id": j + 1,
|
|
735
|
+
"dest_name": dest.name or f"Dest {j + 1}",
|
|
736
|
+
"dest_lon": dest.lon,
|
|
737
|
+
"dest_lat": dest.lat,
|
|
738
|
+
"profile": profile.name,
|
|
739
|
+
"distance_m": res.statistics.total_distance_m,
|
|
740
|
+
"distance_km": res.statistics.total_distance_km,
|
|
741
|
+
"duration_min": res.statistics.total_duration_min,
|
|
742
|
+
"climb_m": res.statistics.elevation_gain_m,
|
|
743
|
+
"calories_kcal": res.statistics.total_calories_kcal,
|
|
744
|
+
"is_matched": res.is_network_matched,
|
|
745
|
+
}
|
|
746
|
+
)
|
|
747
|
+
return matrix_rows
|