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.
Files changed (42) hide show
  1. zero2route3d/__init__.py +212 -0
  2. zero2route3d/accessibility_equity.py +214 -0
  3. zero2route3d/ahp_engine.py +117 -0
  4. zero2route3d/api.py +244 -0
  5. zero2route3d/basemap.py +44 -0
  6. zero2route3d/cli.py +251 -0
  7. zero2route3d/copernicus_dem.py +76 -0
  8. zero2route3d/copernicus_eo_suite.py +443 -0
  9. zero2route3d/dem_fetcher.py +223 -0
  10. zero2route3d/environmental_raster.py +411 -0
  11. zero2route3d/evacuation.py +121 -0
  12. zero2route3d/html_bundler.py +603 -0
  13. zero2route3d/input_validation.py +100 -0
  14. zero2route3d/integrations.py +260 -0
  15. zero2route3d/isochrone_engine.py +220 -0
  16. zero2route3d/kinematics.py +383 -0
  17. zero2route3d/local_server.py +116 -0
  18. zero2route3d/map_matching_3d.py +374 -0
  19. zero2route3d/micro_elevation.py +264 -0
  20. zero2route3d/mobility_profiles.py +517 -0
  21. zero2route3d/multimodal.py +172 -0
  22. zero2route3d/network_source.py +512 -0
  23. zero2route3d/osm_downloader.py +328 -0
  24. zero2route3d/osm_styling.py +351 -0
  25. zero2route3d/pareto_router.py +331 -0
  26. zero2route3d/plotting.py +292 -0
  27. zero2route3d/profile_dxf.py +231 -0
  28. zero2route3d/profile_stats.py +648 -0
  29. zero2route3d/py.typed +1 -0
  30. zero2route3d/qml_generator.py +189 -0
  31. zero2route3d/raster_source.py +206 -0
  32. zero2route3d/report_generator.py +154 -0
  33. zero2route3d/route_corridor_3d.py +479 -0
  34. zero2route3d/routing_engine.py +747 -0
  35. zero2route3d/solar_shadow.py +157 -0
  36. zero2route3d/tsp_solver.py +78 -0
  37. zero2route3d_sdk-0.2.0.dist-info/METADATA +251 -0
  38. zero2route3d_sdk-0.2.0.dist-info/RECORD +42 -0
  39. zero2route3d_sdk-0.2.0.dist-info/WHEEL +5 -0
  40. zero2route3d_sdk-0.2.0.dist-info/entry_points.txt +2 -0
  41. zero2route3d_sdk-0.2.0.dist-info/licenses/LICENSE +21 -0
  42. zero2route3d_sdk-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,648 @@
1
+ """Route diagnostics, elevation profiles, kinematic statistics, and turn-by-turn cue sheets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass, field
7
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
8
+
9
+ from .kinematics import (
10
+ cycling_energy_cost,
11
+ cyclist_speed,
12
+ haversine_distance_2d,
13
+ minetti_energy_cost,
14
+ scooter_speed,
15
+ senior_fatigue_decay,
16
+ tobler_walking_speed,
17
+ vehicle_free_flow_speed,
18
+ )
19
+ from .mobility_profiles import MobilityProfile, get_profile
20
+
21
+
22
+ @dataclass
23
+ class CueInstruction:
24
+ """Single step in a turn-by-turn navigation sheet."""
25
+
26
+ step_number: int
27
+ instruction: str
28
+ direction: str # 'depart', 'left', 'right', 'slight_left', 'slight_right', 'straight', 'arrive'
29
+ distance_m: float
30
+ elevation_delta_m: float
31
+ slope_pct: float
32
+ street_name: str
33
+ warning: str = ""
34
+
35
+ def to_dict(self) -> Dict[str, Any]:
36
+ return {
37
+ "step_number": self.step_number,
38
+ "instruction": self.instruction,
39
+ "direction": self.direction,
40
+ "distance_m": round(self.distance_m, 1),
41
+ "elevation_delta_m": round(self.elevation_delta_m, 1),
42
+ "slope_pct": round(self.slope_pct, 1),
43
+ "street_name": self.street_name,
44
+ "warning": self.warning,
45
+ }
46
+
47
+
48
+ @dataclass
49
+ class RouteStatistics:
50
+ """Comprehensive KPIs and diagnostics for a computed 3D route."""
51
+
52
+ total_distance_m: float
53
+ total_duration_s: float
54
+ elevation_gain_m: float
55
+ elevation_loss_m: float
56
+ min_elevation_m: float
57
+ max_elevation_m: float
58
+ max_slope_pct: float
59
+ avg_slope_pct: float
60
+ total_calories_kcal: float
61
+ # 0.0 (extreme heat) to 1.0 (ideal cool shade); None when no LST raster covered
62
+ # the route -- a score must never be invented from a missing surface.
63
+ thermal_comfort_score: Optional[float]
64
+ ada_compliant: bool = True
65
+ ada_violations_count: int = 0
66
+ slope_distribution: Dict[str, float] = field(default_factory=dict)
67
+ elevation_profile: List[Dict[str, Any]] = field(default_factory=list)
68
+ cue_sheet: List[CueInstruction] = field(default_factory=list)
69
+
70
+ @property
71
+ def total_distance_km(self) -> float:
72
+ return round(self.total_distance_m / 1000.0, 2)
73
+
74
+ @property
75
+ def total_duration_min(self) -> float:
76
+ return round(self.total_duration_s / 60.0, 1)
77
+
78
+ def to_dict(self) -> Dict[str, Any]:
79
+ return {
80
+ "total_distance_m": round(self.total_distance_m, 1),
81
+ "total_distance_km": self.total_distance_km,
82
+ "total_duration_s": round(self.total_duration_s, 1),
83
+ "total_duration_min": self.total_duration_min,
84
+ "elevation_gain_m": round(self.elevation_gain_m, 1),
85
+ "elevation_loss_m": round(self.elevation_loss_m, 1),
86
+ "min_elevation_m": round(self.min_elevation_m, 1),
87
+ "max_elevation_m": round(self.max_elevation_m, 1),
88
+ "max_slope_pct": round(self.max_slope_pct, 1),
89
+ "avg_slope_pct": round(self.avg_slope_pct, 1),
90
+ "total_calories_kcal": round(self.total_calories_kcal, 1),
91
+ "thermal_comfort_score": (
92
+ round(self.thermal_comfort_score, 2)
93
+ if self.thermal_comfort_score is not None
94
+ else None
95
+ ),
96
+ "ada_compliant": self.ada_compliant,
97
+ "ada_violations_count": self.ada_violations_count,
98
+ "slope_distribution": self.slope_distribution,
99
+ "elevation_profile": self.elevation_profile,
100
+ "cue_sheet": [c.to_dict() for c in self.cue_sheet],
101
+ }
102
+
103
+
104
+ def densify_3d_linestring(
105
+ coords: Sequence[Sequence[float]],
106
+ sample_interval_m: float = 8.0,
107
+ max_points: int = 100_000,
108
+ ) -> List[Tuple[float, float, float]]:
109
+ """Densify a 3D coordinate sequence with a hard memory-safe point cap."""
110
+ valid_coords = [
111
+ (
112
+ float(c[0]),
113
+ float(c[1]),
114
+ float(c[2]) if len(c) > 2 and math.isfinite(float(c[2])) else 0.0,
115
+ )
116
+ for c in coords
117
+ if c and len(c) >= 2 and math.isfinite(float(c[0])) and math.isfinite(float(c[1]))
118
+ ]
119
+ if len(valid_coords) < 2:
120
+ return valid_coords
121
+
122
+ interval = (
123
+ max(0.5, float(sample_interval_m))
124
+ if math.isfinite(sample_interval_m) and sample_interval_m > 0
125
+ else 8.0
126
+ )
127
+ point_limit = max(1_000, min(1_000_000, int(max_points))) if max_points > 0 else 100_000
128
+ total_distance = sum(
129
+ haversine_distance_2d(valid_coords[index], valid_coords[index + 1])
130
+ for index in range(len(valid_coords) - 1)
131
+ )
132
+ estimated_points = total_distance / interval if interval > 0 else float("inf")
133
+ if estimated_points > point_limit:
134
+ interval = max(interval, total_distance / point_limit)
135
+ densified: List[Tuple[float, float, float]] = []
136
+
137
+ for i in range(len(valid_coords) - 1):
138
+ p1 = valid_coords[i]
139
+ p2 = valid_coords[i + 1]
140
+ z1 = p1[2]
141
+ z2 = p2[2]
142
+
143
+ seg_dist = haversine_distance_2d(p1, p2)
144
+ steps = max(1, int(math.ceil(seg_dist / interval)))
145
+
146
+ for step in range(steps):
147
+ frac = step / steps
148
+ lon = p1[0] + (p2[0] - p1[0]) * frac
149
+ lat = p1[1] + (p2[1] - p1[1]) * frac
150
+ z = z1 + (z2 - z1) * frac
151
+ densified.append((lon, lat, z))
152
+
153
+ last = valid_coords[-1]
154
+ densified.append((last[0], last[1], last[2]))
155
+ return densified
156
+
157
+
158
+ def densify_3d_linestring_indexed(
159
+ coords: Sequence[Sequence[float]],
160
+ sample_interval_m: float = 8.0,
161
+ max_points: int = 100_000,
162
+ ) -> Tuple[List[Tuple[float, float, float]], List[int]]:
163
+ """Densify like densify_3d_linestring, also returning each point's source segment.
164
+
165
+ The plain densifier throws away which original segment every interpolated point
166
+ came from, which is why per-edge road attributes (hierarchy, lane count, real
167
+ street name) used to be unavailable downstream and were replaced by constants.
168
+ """
169
+ densified = densify_3d_linestring(coords, sample_interval_m, max_points)
170
+ valid_coords = [
171
+ (float(c[0]), float(c[1]))
172
+ for c in coords
173
+ if c and len(c) >= 2 and math.isfinite(float(c[0])) and math.isfinite(float(c[1]))
174
+ ]
175
+ if len(valid_coords) < 2 or not densified:
176
+ return densified, [0] * len(densified)
177
+
178
+ # Walk both sequences once: the densified points are emitted in segment order.
179
+ source_idx: List[int] = []
180
+ seg = 0
181
+ for pt in densified:
182
+ while seg < len(valid_coords) - 2:
183
+ here = haversine_distance_2d(pt, valid_coords[seg])
184
+ nxt = haversine_distance_2d(pt, valid_coords[seg + 1])
185
+ if nxt < here:
186
+ seg += 1
187
+ else:
188
+ break
189
+ source_idx.append(min(seg, len(valid_coords) - 2))
190
+ return densified, source_idx
191
+
192
+
193
+ def smooth_elevation_series(elevations: Sequence[float], window_size: int = 5) -> List[float]:
194
+ """Apply moving Gaussian-weighted smoothing to filter DEM quantization noise."""
195
+ if not elevations:
196
+ return []
197
+ n = len(elevations)
198
+ w = max(1, int(window_size)) if math.isfinite(window_size) and window_size > 0 else 5
199
+ if n < w or w <= 1:
200
+ return [float(e) if math.isfinite(float(e)) else 0.0 for e in elevations]
201
+
202
+ clean_elev = [float(e) if math.isfinite(float(e)) else 0.0 for e in elevations]
203
+ smoothed = []
204
+ half = w // 2
205
+ for i in range(n):
206
+ sub = clean_elev[max(0, i - half) : min(n, i + half + 1)]
207
+ smoothed.append(sum(sub) / len(sub))
208
+ return smoothed
209
+
210
+
211
+ def compute_turn_angle_and_direction(
212
+ p_prev: Sequence[float],
213
+ p_curr: Sequence[float],
214
+ p_next: Sequence[float],
215
+ ) -> Tuple[float, str]:
216
+ """Compute turn angle in degrees and turn direction string."""
217
+ if (
218
+ not p_prev
219
+ or not p_curr
220
+ or not p_next
221
+ or len(p_prev) < 2
222
+ or len(p_curr) < 2
223
+ or len(p_next) < 2
224
+ ):
225
+ return 0.0, "straight"
226
+
227
+ dx1 = float(p_curr[0]) - float(p_prev[0])
228
+ dy1 = float(p_curr[1]) - float(p_prev[1])
229
+ dx2 = float(p_next[0]) - float(p_curr[0])
230
+ dy2 = float(p_next[1]) - float(p_curr[1])
231
+
232
+ if not (
233
+ math.isfinite(dx1) and math.isfinite(dy1) and math.isfinite(dx2) and math.isfinite(dy2)
234
+ ):
235
+ return 0.0, "straight"
236
+
237
+ b1 = (math.degrees(math.atan2(dx1, dy1)) + 360.0) % 360.0
238
+ b2 = (math.degrees(math.atan2(dx2, dy2)) + 360.0) % 360.0
239
+ diff = (b2 - b1 + 180.0) % 360.0 - 180.0
240
+
241
+ if abs(diff) < 15.0:
242
+ return diff, "straight"
243
+ if diff > 45.0:
244
+ return diff, "right"
245
+ if diff > 15.0:
246
+ return diff, "slight_right"
247
+ if diff < -45.0:
248
+ return diff, "left"
249
+ return diff, "slight_left"
250
+
251
+
252
+ def _street_name_at(
253
+ segment_metadata: Optional[Sequence[Dict[str, Any]]],
254
+ index: int,
255
+ ) -> str:
256
+ """Real OSM street name for a segment, or "" when the way is unnamed.
257
+
258
+ Returning an empty string is deliberate: a placeholder such as "Urban Path"
259
+ reads like a surveyed name and is indistinguishable from a real one.
260
+ """
261
+ if not segment_metadata or index < 0 or index >= len(segment_metadata):
262
+ return ""
263
+ return str((segment_metadata[index] or {}).get("street_name") or "")
264
+
265
+
266
+ def generate_cue_sheet(
267
+ raw_coords_3d: Sequence[Sequence[float]],
268
+ profile: Optional[MobilityProfile] = None,
269
+ segment_metadata: Optional[Sequence[Dict[str, Any]]] = None,
270
+ ) -> List[CueInstruction]:
271
+ """Generate human-readable turn-by-turn navigation instructions."""
272
+ if not raw_coords_3d or len(raw_coords_3d) < 2:
273
+ return []
274
+
275
+ prof = profile if profile is not None else get_profile("adult")
276
+ cues: List[CueInstruction] = []
277
+ step_num = 1
278
+
279
+ # Start Departure
280
+ cues.append(
281
+ CueInstruction(
282
+ step_number=step_num,
283
+ instruction="Depart from origin point heading forward.",
284
+ direction="depart",
285
+ distance_m=0.0,
286
+ elevation_delta_m=0.0,
287
+ slope_pct=0.0,
288
+ street_name=_street_name_at(segment_metadata, 0),
289
+ )
290
+ )
291
+ step_num += 1
292
+
293
+ accum_dist = 0.0
294
+ accum_dz = 0.0
295
+
296
+ for i in range(1, len(raw_coords_3d) - 1):
297
+ p_prev = raw_coords_3d[i - 1]
298
+ p_curr = raw_coords_3d[i]
299
+ p_next = raw_coords_3d[i + 1]
300
+
301
+ z_prev = float(p_prev[2]) if len(p_prev) > 2 and math.isfinite(float(p_prev[2])) else 0.0
302
+ z_curr = float(p_curr[2]) if len(p_curr) > 2 and math.isfinite(float(p_curr[2])) else 0.0
303
+
304
+ d = haversine_distance_2d(p_prev, p_curr)
305
+ dz = z_curr - z_prev
306
+ accum_dist += d
307
+ accum_dz += dz
308
+
309
+ angle, direction = compute_turn_angle_and_direction(p_prev, p_curr, p_next)
310
+
311
+ if direction != "straight" or accum_dist > 400.0:
312
+ slope = (accum_dz / max(0.1, accum_dist)) * 100.0
313
+ if not math.isfinite(slope):
314
+ slope = 0.0
315
+ warning = ""
316
+ max_s = prof.max_slope_pct if math.isfinite(prof.max_slope_pct) else 25.0
317
+ if abs(slope) > max_s:
318
+ warning = f"Warning: Steep gradient ({slope:.1f}%) exceeds profile recommendation!"
319
+
320
+ dir_text = {
321
+ "left": "Turn left",
322
+ "right": "Turn right",
323
+ "slight_left": "Bear slightly left",
324
+ "slight_right": "Bear slightly right",
325
+ "straight": "Continue straight",
326
+ }.get(direction, "Continue")
327
+
328
+ instr = f"{dir_text} along path for {accum_dist:.0f}m ({accum_dz:+.1f}m elevation)."
329
+ cues.append(
330
+ CueInstruction(
331
+ step_number=step_num,
332
+ instruction=instr,
333
+ direction=direction,
334
+ distance_m=accum_dist,
335
+ elevation_delta_m=accum_dz,
336
+ slope_pct=slope,
337
+ street_name=_street_name_at(segment_metadata, i),
338
+ warning=warning,
339
+ )
340
+ )
341
+ step_num += 1
342
+ accum_dist = 0.0
343
+ accum_dz = 0.0
344
+
345
+ # Arrival at Destination
346
+ last_p1 = raw_coords_3d[-2]
347
+ last_p2 = raw_coords_3d[-1]
348
+ last_z1 = float(last_p1[2]) if len(last_p1) > 2 and math.isfinite(float(last_p1[2])) else 0.0
349
+ last_z2 = float(last_p2[2]) if len(last_p2) > 2 and math.isfinite(float(last_p2[2])) else 0.0
350
+
351
+ last_d = haversine_distance_2d(last_p1, last_p2)
352
+ last_dz = last_z2 - last_z1
353
+ cues.append(
354
+ CueInstruction(
355
+ step_number=step_num,
356
+ instruction="Arrive at destination.",
357
+ direction="arrive",
358
+ distance_m=accum_dist + last_d,
359
+ elevation_delta_m=accum_dz + last_dz,
360
+ slope_pct=0.0,
361
+ street_name=_street_name_at(
362
+ segment_metadata, len(segment_metadata) - 1 if segment_metadata else 0
363
+ ),
364
+ )
365
+ )
366
+
367
+ return cues
368
+
369
+
370
+ def compute_route_statistics(
371
+ coords_3d: Sequence[Sequence[float]],
372
+ profile: Optional[MobilityProfile] = None,
373
+ lst_samples: Optional[Sequence[Optional[float]]] = None,
374
+ green_samples: Optional[Sequence[Optional[float]]] = None,
375
+ segment_metadata: Optional[Sequence[Dict[str, Any]]] = None,
376
+ ) -> RouteStatistics:
377
+ """Compute comprehensive kinematic, topographic, and thermal statistics along 3D route."""
378
+ if not coords_3d:
379
+ return RouteStatistics(
380
+ total_distance_m=0.0,
381
+ total_duration_s=0.0,
382
+ elevation_gain_m=0.0,
383
+ elevation_loss_m=0.0,
384
+ min_elevation_m=0.0,
385
+ max_elevation_m=0.0,
386
+ max_slope_pct=0.0,
387
+ avg_slope_pct=0.0,
388
+ total_calories_kcal=0.0,
389
+ thermal_comfort_score=None,
390
+ )
391
+
392
+ if len(coords_3d) == 1:
393
+ ele = (
394
+ float(coords_3d[0][2])
395
+ if len(coords_3d[0]) > 2 and math.isfinite(float(coords_3d[0][2]))
396
+ else 0.0
397
+ )
398
+ return RouteStatistics(
399
+ total_distance_m=0.0,
400
+ total_duration_s=0.0,
401
+ elevation_gain_m=0.0,
402
+ elevation_loss_m=0.0,
403
+ min_elevation_m=ele,
404
+ max_elevation_m=ele,
405
+ max_slope_pct=0.0,
406
+ avg_slope_pct=0.0,
407
+ total_calories_kcal=0.0,
408
+ thermal_comfort_score=None,
409
+ )
410
+
411
+ prof = profile if profile is not None else get_profile("adult")
412
+
413
+ # Densify coordinates
414
+ dense_pts, dense_src = densify_3d_linestring_indexed(coords_3d, sample_interval_m=6.0)
415
+
416
+ def _segment_attr(vertex_index: int, key: str, fallback: Any) -> Any:
417
+ """Real per-edge road attribute for a densified vertex, or the fallback."""
418
+ if not segment_metadata:
419
+ return fallback
420
+ if vertex_index >= len(dense_src):
421
+ return fallback
422
+ src = dense_src[vertex_index]
423
+ if src >= len(segment_metadata):
424
+ return fallback
425
+ value = (segment_metadata[src] or {}).get(key)
426
+ return fallback if value is None else value
427
+
428
+ if len(dense_pts) < 2:
429
+ ele = (
430
+ float(coords_3d[0][2])
431
+ if len(coords_3d[0]) > 2 and math.isfinite(float(coords_3d[0][2]))
432
+ else 0.0
433
+ )
434
+ return RouteStatistics(
435
+ total_distance_m=0.0,
436
+ total_duration_s=0.0,
437
+ elevation_gain_m=0.0,
438
+ elevation_loss_m=0.0,
439
+ min_elevation_m=ele,
440
+ max_elevation_m=ele,
441
+ max_slope_pct=0.0,
442
+ avg_slope_pct=0.0,
443
+ total_calories_kcal=0.0,
444
+ thermal_comfort_score=None,
445
+ )
446
+
447
+ cumulative_dist = 0.0
448
+ total_time_s = 0.0
449
+ elevation_gain = 0.0
450
+ elevation_loss = 0.0
451
+ total_calories = 0.0
452
+ slope_sum = 0.0
453
+ ada_violations = 0
454
+
455
+ elevations = [p[2] for p in dense_pts]
456
+ min_elev = min(elevations) if elevations else 0.0
457
+ max_elev = max(elevations) if elevations else 0.0
458
+ max_slope = 0.0
459
+
460
+ slope_bins = {
461
+ "flat_0_3": 0.0,
462
+ "gentle_3_6": 0.0,
463
+ "moderate_6_10": 0.0,
464
+ "steep_10_15": 0.0,
465
+ "extreme_over_15": 0.0,
466
+ }
467
+
468
+ profile_list: List[Dict[str, Any]] = []
469
+ thermal_sum = 0.0
470
+ thermal_dist = 0.0
471
+ category = prof.category
472
+ base_spd = (
473
+ prof.base_speed_kmh
474
+ if math.isfinite(prof.base_speed_kmh) and prof.base_speed_kmh > 0
475
+ else 5.0
476
+ )
477
+
478
+ for i in range(len(dense_pts) - 1):
479
+ p1 = dense_pts[i]
480
+ p2 = dense_pts[i + 1]
481
+
482
+ d_2d = haversine_distance_2d(p1, p2)
483
+ dz = p2[2] - p1[2]
484
+ d_3d = math.hypot(d_2d, dz)
485
+
486
+ if not math.isfinite(d_3d) or d_3d < 0.01:
487
+ continue
488
+
489
+ slope_pct = (dz / max(0.1, d_2d)) * 100.0 if d_2d >= 0.01 else 0.0
490
+ if not math.isfinite(slope_pct):
491
+ slope_pct = 0.0
492
+ abs_slope = abs(slope_pct)
493
+ max_slope = max(max_slope, abs_slope)
494
+ slope_sum += abs_slope * d_3d
495
+
496
+ if abs_slope > 8.33:
497
+ ada_violations += 1
498
+
499
+ if dz > 0:
500
+ elevation_gain += dz
501
+ else:
502
+ elevation_loss += abs(dz)
503
+
504
+ # Slope bins
505
+ if abs_slope < 3.0:
506
+ slope_bins["flat_0_3"] += d_3d
507
+ elif abs_slope < 6.0:
508
+ slope_bins["gentle_3_6"] += d_3d
509
+ elif abs_slope < 10.0:
510
+ slope_bins["moderate_6_10"] += d_3d
511
+ elif abs_slope < 15.0:
512
+ slope_bins["steep_10_15"] += d_3d
513
+ else:
514
+ slope_bins["extreme_over_15"] += d_3d
515
+
516
+ # Kinematic calculation
517
+ slope_frac = dz / max(0.1, d_2d) if d_2d >= 0.01 else 0.0
518
+ if not math.isfinite(slope_frac):
519
+ slope_frac = 0.0
520
+
521
+ if category == "pedestrian":
522
+ fatigue_mult = (
523
+ senior_fatigue_decay(cumulative_dist, elevation_gain)
524
+ if prof.key == "senior"
525
+ else 1.0
526
+ )
527
+ speed_kmh = tobler_walking_speed(slope_frac, base_speed_kmh=base_spd) * fatigue_mult
528
+ _j, kcal = minetti_energy_cost(slope_frac, mass_kg=70.0, distance_m=d_3d)
529
+ total_calories += kcal
530
+ elif prof.key in {"bicycle", "mtb"}:
531
+ speed_kmh = cyclist_speed(slope_frac, base_speed_kmh=base_spd)
532
+ total_calories += cycling_energy_cost(slope_frac, mass_kg=70.0, distance_m=d_3d)[1]
533
+ elif prof.key == "scooter":
534
+ speed_kmh = scooter_speed(slope_frac, base_speed_kmh=base_spd)
535
+ else:
536
+ # Use the segment's real road hierarchy and lane count when the graph
537
+ # supplied them, and honour the profile's own free-flow speed, so a
538
+ # paramedic is not timed identically to a heavy truck.
539
+ speed_kmh = vehicle_free_flow_speed(
540
+ hierarchy_rank=int(_segment_attr(i, "hierarchy", 4)),
541
+ lanes=int(_segment_attr(i, "lanes", 2) or 2),
542
+ slope_pct=slope_pct,
543
+ base_vehicle_speed_kmh=base_spd,
544
+ )
545
+
546
+ if not math.isfinite(speed_kmh) or speed_kmh <= 0:
547
+ speed_kmh = base_spd
548
+
549
+ spd_ms = max(0.1, speed_kmh * 1000.0 / 3600.0)
550
+ seg_time_s = d_3d / spd_ms
551
+ if math.isfinite(seg_time_s):
552
+ total_time_s += seg_time_s
553
+
554
+ # A missing LST raster contributes nothing: it must not be averaged in as
555
+ # a mid-range constant, which would make thermal_comfort_score a fixed 0.5
556
+ # for every route on Earth.
557
+ lst_val: Optional[float] = None
558
+ if lst_samples and i < len(lst_samples):
559
+ raw_lst = lst_samples[i]
560
+ if raw_lst is not None and math.isfinite(float(raw_lst)):
561
+ lst_val = float(raw_lst)
562
+ if lst_val is not None:
563
+ thermal_sum += lst_val * d_3d
564
+ thermal_dist += d_3d
565
+
566
+ green_val: Optional[float] = None
567
+ if green_samples and i < len(green_samples):
568
+ raw_green = green_samples[i]
569
+ if raw_green is not None and math.isfinite(float(raw_green)):
570
+ green_val = float(raw_green)
571
+
572
+ vertex: Dict[str, Any] = {
573
+ "distance_m": round(cumulative_dist, 1),
574
+ "elevation_m": round(p1[2], 1),
575
+ "slope_pct": round(slope_pct, 1),
576
+ "speed_kmh": round(speed_kmh, 1),
577
+ "lon": round(p1[0], 6),
578
+ "lat": round(p1[1], 6),
579
+ }
580
+ # Only emit the environmental keys when they are backed by a real raster,
581
+ # so the viewer can render an explicit "no data" state instead of a
582
+ # constant that looks like a measurement.
583
+ if lst_val is not None:
584
+ vertex["lst_normalized"] = round(lst_val, 3)
585
+ if green_val is not None:
586
+ vertex["ndvi_normalized"] = round(green_val, 3)
587
+ profile_list.append(vertex)
588
+ cumulative_dist += d_3d
589
+
590
+ if dense_pts:
591
+ last_pt = dense_pts[-1]
592
+ last_vertex: Dict[str, Any] = {
593
+ "distance_m": round(cumulative_dist, 1),
594
+ "elevation_m": round(last_pt[2], 1),
595
+ "slope_pct": 0.0,
596
+ "speed_kmh": round(base_spd, 1),
597
+ "lon": round(last_pt[0], 6),
598
+ "lat": round(last_pt[1], 6),
599
+ }
600
+ # Without this the final vertex loses its environmental readings, so a
601
+ # profile chart drops to zero heat/greenery at the destination.
602
+ if lst_samples and len(lst_samples) >= len(dense_pts):
603
+ raw_last_lst = lst_samples[-1]
604
+ if raw_last_lst is not None and math.isfinite(float(raw_last_lst)):
605
+ last_vertex["lst_normalized"] = round(float(raw_last_lst), 3)
606
+ elif lst_samples and profile_list and "lst_normalized" in profile_list[-1]:
607
+ last_vertex["lst_normalized"] = profile_list[-1]["lst_normalized"]
608
+
609
+ if green_samples and len(green_samples) >= len(dense_pts):
610
+ raw_last_green = green_samples[-1]
611
+ if raw_last_green is not None and math.isfinite(float(raw_last_green)):
612
+ last_vertex["ndvi_normalized"] = round(float(raw_last_green), 3)
613
+ elif green_samples and profile_list and "ndvi_normalized" in profile_list[-1]:
614
+ last_vertex["ndvi_normalized"] = profile_list[-1]["ndvi_normalized"]
615
+
616
+ profile_list.append(last_vertex)
617
+
618
+ avg_slope = (slope_sum / cumulative_dist) if cumulative_dist > 0 else 0.0
619
+ # thermal_comfort_score stays None unless a real LST raster covered the route.
620
+ thermal_comfort: Optional[float] = None
621
+ if thermal_dist > 0:
622
+ mean_lst = thermal_sum / thermal_dist
623
+ thermal_comfort = max(0.0, min(1.0, 1.0 - mean_lst))
624
+
625
+ slope_dist_pct = {
626
+ k: round((v / cumulative_dist) * 100.0, 1) if cumulative_dist > 0 else 0.0
627
+ for k, v in slope_bins.items()
628
+ }
629
+
630
+ cues = generate_cue_sheet(coords_3d, prof, segment_metadata)
631
+
632
+ return RouteStatistics(
633
+ total_distance_m=cumulative_dist,
634
+ total_duration_s=total_time_s,
635
+ elevation_gain_m=elevation_gain,
636
+ elevation_loss_m=elevation_loss,
637
+ min_elevation_m=min_elev,
638
+ max_elevation_m=max_elev,
639
+ max_slope_pct=max_slope,
640
+ avg_slope_pct=avg_slope,
641
+ total_calories_kcal=total_calories,
642
+ thermal_comfort_score=thermal_comfort,
643
+ ada_compliant=(ada_violations == 0),
644
+ ada_violations_count=ada_violations,
645
+ slope_distribution=slope_dist_pct,
646
+ elevation_profile=profile_list,
647
+ cue_sheet=cues,
648
+ )
zero2route3d/py.typed ADDED
@@ -0,0 +1 @@
1
+ # Marker file for PEP 561 type checking