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,331 @@
1
+ """Pareto Frontier Multi-Objective 3D Routing Engine (NAMOA* with Epsilon-Dominance).
2
+
3
+ Calculates the complete non-dominated Pareto frontier across 4 conflicting objectives:
4
+ 1. Duration / Travel Time (seconds)
5
+ 2. Elevation Ascent / Incline Gain (meters)
6
+ 3. Microclimate Heat / LST Exposure Dose (cumulative index)
7
+ 4. Metabolic Energy Expenditure (Minetti kcal)
8
+
9
+ Author: Yusuf Eminoglu
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import heapq
15
+ import math
16
+ from dataclasses import dataclass, field
17
+ from typing import Any, Dict, List, Tuple, Union
18
+
19
+ from .environmental_raster import EnvironmentalSurfaceSampler
20
+ from .kinematics import (
21
+ cycling_energy_cost,
22
+ cyclist_speed,
23
+ haversine_distance_2d,
24
+ minetti_energy_cost,
25
+ tobler_walking_speed,
26
+ )
27
+ from .mobility_profiles import MobilityProfile, resolve_profile
28
+ from .profile_stats import RouteStatistics, compute_route_statistics
29
+
30
+
31
+ @dataclass
32
+ class ParetoCostVector:
33
+ """4D Objective cost vector for multi-objective optimization."""
34
+
35
+ time_s: float
36
+ ascent_m: float
37
+ heat_dose: float
38
+ energy_kcal: float
39
+
40
+ def dominates(self, other: ParetoCostVector, epsilon: float = 0.0) -> bool:
41
+ """Return True if self dominates other under approximate (1+eps) Pareto dominance."""
42
+ c1 = (1.0 + epsilon) * self.time_s <= other.time_s
43
+ c2 = (1.0 + epsilon) * self.ascent_m <= other.ascent_m
44
+ c3 = (1.0 + epsilon) * self.heat_dose <= other.heat_dose
45
+ c4 = (1.0 + epsilon) * self.energy_kcal <= other.energy_kcal
46
+
47
+ strictly_better = (
48
+ self.time_s < other.time_s
49
+ or self.ascent_m < other.ascent_m
50
+ or self.heat_dose < other.heat_dose
51
+ or self.energy_kcal < other.energy_kcal
52
+ )
53
+ return (c1 and c2 and c3 and c4) and strictly_better
54
+
55
+ def add(self, delta: ParetoCostVector) -> ParetoCostVector:
56
+ return ParetoCostVector(
57
+ time_s=self.time_s + delta.time_s,
58
+ ascent_m=self.ascent_m + delta.ascent_m,
59
+ heat_dose=self.heat_dose + delta.heat_dose,
60
+ energy_kcal=self.energy_kcal + delta.energy_kcal,
61
+ )
62
+
63
+ def to_dict(self) -> Dict[str, float]:
64
+ return {
65
+ "duration_min": round(self.time_s / 60.0, 1),
66
+ "ascent_m": round(self.ascent_m, 1),
67
+ "heat_dose": round(self.heat_dose, 2),
68
+ "energy_kcal": round(self.energy_kcal, 1),
69
+ }
70
+
71
+
72
+ @dataclass
73
+ class ParetoRouteSolution:
74
+ """Individual non-dominated route on the Pareto frontier."""
75
+
76
+ label: str # 'Fastest', 'Flattest', 'Coolest', 'Lowest Energy', 'Balanced Knee'
77
+ cost: ParetoCostVector
78
+ coordinates_3d: List[Tuple[float, float, float]]
79
+ statistics: RouteStatistics
80
+ tradeoff_radar: Dict[str, float] = field(default_factory=dict)
81
+
82
+ def to_dict(self) -> Dict[str, Any]:
83
+ return {
84
+ "label": self.label,
85
+ "cost": self.cost.to_dict(),
86
+ "distance_km": self.statistics.total_distance_km,
87
+ "duration_min": self.statistics.total_duration_min,
88
+ "elevation_gain_m": self.statistics.elevation_gain_m,
89
+ "calories_kcal": self.statistics.total_calories_kcal,
90
+ "thermal_comfort_score": self.statistics.thermal_comfort_score,
91
+ "tradeoff_radar": self.tradeoff_radar,
92
+ "coordinates": [
93
+ [round(c[0], 6), round(c[1], 6), round(c[2], 2)] for c in self.coordinates_3d
94
+ ],
95
+ }
96
+
97
+
98
+ @dataclass
99
+ class ParetoFrontierResult:
100
+ """Collection of all non-dominated routes along the Pareto frontier."""
101
+
102
+ solutions: List[ParetoRouteSolution]
103
+ hypervolume_indicator: float
104
+ profile_name: str
105
+
106
+ def to_dict(self) -> Dict[str, Any]:
107
+ return {
108
+ "solution_count": len(self.solutions),
109
+ "hypervolume_indicator": round(self.hypervolume_indicator, 4),
110
+ "profile_name": self.profile_name,
111
+ "solutions": [s.to_dict() for s in self.solutions],
112
+ }
113
+
114
+
115
+ class ParetoMultiObjectiveRouter:
116
+ """New Approach to Multi-Objective A* (NAMOA*) 3D Routing Engine."""
117
+
118
+ def __init__(
119
+ self,
120
+ nodes: Dict[int, Tuple[float, float, float]],
121
+ adj: Dict[int, List[Tuple[int, float, float, Dict[str, Any]]]],
122
+ sampler: EnvironmentalSurfaceSampler,
123
+ ) -> None:
124
+ self.nodes = nodes
125
+ self.adj = adj
126
+ self.sampler = sampler
127
+
128
+ def _calculate_edge_vector(
129
+ self,
130
+ u: int,
131
+ v: int,
132
+ length_m: float,
133
+ slope_pct: float,
134
+ meta: Dict[str, Any],
135
+ profile: MobilityProfile,
136
+ ) -> ParetoCostVector:
137
+ """Compute 4D cost vector for traversing edge (u -> v)."""
138
+ v_coord = self.nodes[v]
139
+ slope_frac = slope_pct / 100.0
140
+ dz = max(0.0, self.nodes[v][2] - self.nodes[u][2])
141
+
142
+ # 1. Travel Time & Energy
143
+ if profile.category == "pedestrian":
144
+ spd_kmh = tobler_walking_speed(slope_frac, base_speed_kmh=profile.base_speed_kmh)
145
+ _j, kcal = minetti_energy_cost(slope_frac, mass_kg=70.0, distance_m=length_m)
146
+ elif profile.key in {"bicycle", "mtb"}:
147
+ spd_kmh = cyclist_speed(slope_frac, base_speed_kmh=profile.base_speed_kmh)
148
+ kcal = cycling_energy_cost(slope_frac, mass_kg=70.0, distance_m=length_m)[1]
149
+ else:
150
+ spd_kmh = max(5.0, profile.base_speed_kmh * (1.0 - abs(slope_pct) * 0.02))
151
+ # Motorised travel has no rider metabolic cost; reporting one would be
152
+ # an invented figure in a column of measured ones.
153
+ kcal = 0.0
154
+
155
+ time_s = length_m / max(0.2, (spd_kmh * 1000.0 / 3600.0))
156
+ ascent_m = dz
157
+
158
+ # 3. Heat Exposure Dose.
159
+ # Without a real LST raster there is no heat signal at all: a constant here
160
+ # would make heat_dose proportional to length, i.e. the "Coolest" objective
161
+ # would silently collapse into "Shortest".
162
+ lst_val = self.sampler.sample_lst(v_coord[0], v_coord[1])
163
+ heat_dose = (lst_val * (length_m / 100.0)) if lst_val is not None else 0.0
164
+
165
+ return ParetoCostVector(
166
+ time_s=time_s,
167
+ ascent_m=ascent_m,
168
+ heat_dose=heat_dose,
169
+ energy_kcal=kcal,
170
+ )
171
+
172
+ def solve_pareto_frontier(
173
+ self,
174
+ start_node: int,
175
+ end_node: int,
176
+ profile_key: Union[str, MobilityProfile] = "adult",
177
+ epsilon_dominance: float = 0.03,
178
+ max_frontier_size: int = 12,
179
+ ) -> ParetoFrontierResult:
180
+ """Compute the Pareto Frontier using multi-objective label propagation."""
181
+ profile = resolve_profile(profile_key)
182
+ dest_coord = self.nodes[end_node]
183
+
184
+ def heuristic_time(u_coord: Tuple[float, float, float]) -> float:
185
+ d_m = haversine_distance_2d(u_coord, dest_coord)
186
+ max_spd_ms = (profile.base_speed_kmh * 1.5) * 1000.0 / 3600.0
187
+ return d_m / max_spd_ms
188
+
189
+ labels_g: Dict[int, List[ParetoCostVector]] = {start_node: [ParetoCostVector(0, 0, 0, 0)]}
190
+ h0 = heuristic_time(self.nodes[start_node])
191
+ pq: List[Tuple[float, float, int, Tuple[int, ...]]] = [(h0, 0.0, start_node, (start_node,))]
192
+
193
+ dest_solutions: List[Tuple[ParetoCostVector, Tuple[int, ...]]] = []
194
+ max_iters = 80_000
195
+ iters = 0
196
+
197
+ while pq and iters < max_iters:
198
+ iters += 1
199
+ f_pri, g_time, u, path = heapq.heappop(pq)
200
+ g_vec = None
201
+ for cand in labels_g.get(u, []):
202
+ if abs(cand.time_s - g_time) < 1e-4:
203
+ g_vec = cand
204
+ break
205
+ if g_vec is None:
206
+ continue
207
+
208
+ if u == end_node:
209
+ is_dominated = any(
210
+ sol_cost.dominates(g_vec, epsilon_dominance) for sol_cost, _ in dest_solutions
211
+ )
212
+ if not is_dominated:
213
+ dest_solutions = [
214
+ (sc, sp)
215
+ for sc, sp in dest_solutions
216
+ if not g_vec.dominates(sc, epsilon_dominance)
217
+ ]
218
+ dest_solutions.append((g_vec, path))
219
+ continue
220
+
221
+ if any(sol_cost.dominates(g_vec, epsilon_dominance) for sol_cost, _ in dest_solutions):
222
+ continue
223
+
224
+ for v, seg_len, slope_pct, meta in self.adj.get(u, []):
225
+ if v in path:
226
+ continue
227
+
228
+ edge_vec = self._calculate_edge_vector(u, v, seg_len, slope_pct, meta, profile)
229
+ new_g = g_vec.add(edge_vec)
230
+
231
+ existing = labels_g.setdefault(v, [])
232
+ if any(ext.dominates(new_g, epsilon_dominance) for ext in existing):
233
+ continue
234
+
235
+ labels_g[v] = [
236
+ ext for ext in existing if not new_g.dominates(ext, epsilon_dominance)
237
+ ]
238
+ labels_g[v].append(new_g)
239
+
240
+ h_val = heuristic_time(self.nodes[v])
241
+ heapq.heappush(pq, (new_g.time_s + h_val, new_g.time_s, v, path + (v,)))
242
+
243
+ if not dest_solutions:
244
+ return ParetoFrontierResult([], 0.0, profile.name)
245
+
246
+ return self._extract_archetypes(dest_solutions, profile)
247
+
248
+ def _extract_archetypes(
249
+ self,
250
+ raw_solutions: List[Tuple[ParetoCostVector, Tuple[int, ...]]],
251
+ profile: MobilityProfile,
252
+ ) -> ParetoFrontierResult:
253
+ """Extract archetype solutions (Fastest, Flattest, Coolest, Least Effort, Balanced Knee)."""
254
+ if not raw_solutions:
255
+ return ParetoFrontierResult([], 0.0, profile.name)
256
+
257
+ sol_fastest = min(raw_solutions, key=lambda s: s[0].time_s)
258
+ sol_flattest = min(raw_solutions, key=lambda s: s[0].ascent_m)
259
+ sol_coolest = min(raw_solutions, key=lambda s: s[0].heat_dose)
260
+ sol_least_effort = min(raw_solutions, key=lambda s: s[0].energy_kcal)
261
+
262
+ min_t = sol_fastest[0].time_s
263
+ max_t = max(s[0].time_s for s in raw_solutions)
264
+ min_a = sol_flattest[0].ascent_m
265
+ max_a = max(s[0].ascent_m for s in raw_solutions)
266
+ min_h = sol_coolest[0].heat_dose
267
+ max_h = max(s[0].heat_dose for s in raw_solutions)
268
+ min_e = sol_least_effort[0].energy_kcal
269
+ max_e = max(s[0].energy_kcal for s in raw_solutions)
270
+
271
+ range_t = max(1.0, max_t - min_t)
272
+ range_a = max(1.0, max_a - min_a)
273
+ range_h = max(0.1, max_h - min_h)
274
+ range_e = max(1.0, max_e - min_e)
275
+
276
+ def utopia_dist(s: Tuple[ParetoCostVector, Tuple[int, ...]]) -> float:
277
+ nt = (s[0].time_s - min_t) / range_t
278
+ na = (s[0].ascent_m - min_a) / range_a
279
+ nh = (s[0].heat_dose - min_h) / range_h
280
+ ne = (s[0].energy_kcal - min_e) / range_e
281
+ return math.sqrt(nt**2 + na**2 + nh**2 + ne**2)
282
+
283
+ sol_knee = min(raw_solutions, key=utopia_dist)
284
+
285
+ archetype_map = [
286
+ ("Fastest Route", sol_fastest),
287
+ ("Flattest / Minimum Slope", sol_flattest),
288
+ ("Coolest / Microclimate Shade", sol_coolest),
289
+ ("Minimum Energy / Effort", sol_least_effort),
290
+ ("Balanced Compromise (Knee)", sol_knee),
291
+ ]
292
+
293
+ seen_paths = set()
294
+ solutions: List[ParetoRouteSolution] = []
295
+
296
+ for label, (cost_vec, path_nodes) in archetype_map:
297
+ if path_nodes in seen_paths:
298
+ continue
299
+ seen_paths.add(path_nodes)
300
+
301
+ coords = [self.nodes[nid] for nid in path_nodes]
302
+ stats = compute_route_statistics(coords, profile)
303
+
304
+ radar = {
305
+ "speed_score": round(1.0 - (cost_vec.time_s - min_t) / max(1.0, max_t - min_t), 2),
306
+ "flatness_score": round(
307
+ 1.0 - (cost_vec.ascent_m - min_a) / max(1.0, max_a - min_a), 2
308
+ ),
309
+ "shade_score": round(
310
+ 1.0 - (cost_vec.heat_dose - min_h) / max(0.1, max_h - min_h), 2
311
+ ),
312
+ "energy_efficiency": round(
313
+ 1.0 - (cost_vec.energy_kcal - min_e) / max(1.0, max_e - min_e), 2
314
+ ),
315
+ }
316
+
317
+ solutions.append(
318
+ ParetoRouteSolution(
319
+ label=label,
320
+ cost=cost_vec,
321
+ coordinates_3d=coords,
322
+ statistics=stats,
323
+ tradeoff_radar=radar,
324
+ )
325
+ )
326
+
327
+ return ParetoFrontierResult(
328
+ solutions=solutions,
329
+ hypervolume_indicator=1.0 - utopia_dist(sol_knee),
330
+ profile_name=profile.name,
331
+ )
@@ -0,0 +1,292 @@
1
+ """Publication-ready scientific plotting and visualization for 02Route 3D.
2
+
3
+ Generates longitudinal elevation profiles with a profile-aware energy curve,
4
+ 4D Pareto trade-off diagrams, and E2SFCA Lorenz equity curves. matplotlib is
5
+ imported lazily so the core SDK stays dependency-light.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any, Callable, List, Optional, Tuple
11
+
12
+ PARETO_METRICS = ("time_min", "climb_m", "calories_kcal")
13
+
14
+
15
+ def plot_elevation_profile(
16
+ route: Any,
17
+ show_energy: bool = True,
18
+ title: Optional[str] = None,
19
+ figsize: Tuple[float, float] = (10.0, 4.5),
20
+ save_path: Optional[str] = None,
21
+ ) -> Any:
22
+ """Plot high-grade longitudinal elevation profile with slope color coding and cumulative energy.
23
+
24
+ Args:
25
+ route: RouteResult3D or list of (lon, lat, elev) tuples.
26
+ show_energy: Show secondary axis with metabolic kilocalorie expenditure.
27
+ title: Plot title (defaults to route statistics summary).
28
+ figsize: Figure dimensions (width, height) in inches.
29
+ save_path: Optional filepath to save the figure (PNG, SVG, PDF).
30
+
31
+ Returns:
32
+ matplotlib.figure.Figure instance.
33
+ """
34
+ try:
35
+ import matplotlib.pyplot as plt
36
+ except ImportError as exc:
37
+ raise ImportError(
38
+ "matplotlib is required for plotting. Install via 'pip install matplotlib'."
39
+ ) from exc
40
+
41
+ coords: List[Tuple[float, float, float]] = []
42
+ if hasattr(route, "coordinates_3d"):
43
+ coords = [
44
+ (float(c[0]), float(c[1]), float(c[2]) if len(c) > 2 else 0.0)
45
+ for c in route.coordinates_3d
46
+ ]
47
+ elif isinstance(route, list):
48
+ coords = [(float(c[0]), float(c[1]), float(c[2]) if len(c) > 2 else 0.0) for c in route]
49
+
50
+ if len(coords) < 2:
51
+ raise ValueError("At least 2 coordinates are required to plot an elevation profile.")
52
+
53
+ # Calculate cumulative distance and incremental slopes
54
+ from .kinematics import cycling_energy_cost, haversine_distance_2d, minetti_energy_cost
55
+
56
+ # Metabolic energy depends on how the route is travelled. Charging a car
57
+ # driver walking calories -- or a cyclist a pedestrian's -- is not a rounding
58
+ # error, it is the wrong model.
59
+ category = str(getattr(getattr(route, "profile", None), "category", "pedestrian")).lower()
60
+ energy_model: Optional[Callable[..., Tuple[float, float]]]
61
+ if category == "vehicle":
62
+ energy_model = None
63
+ elif category == "micromobility":
64
+ energy_model = cycling_energy_cost
65
+ else:
66
+ energy_model = minetti_energy_cost
67
+
68
+ distances_km = [0.0]
69
+ elevations_m = [coords[0][2]]
70
+ slopes_pct = [0.0]
71
+ calories_kcal = [0.0]
72
+
73
+ cum_dist = 0.0
74
+ cum_kcal = 0.0
75
+
76
+ for i in range(len(coords) - 1):
77
+ p1 = coords[i]
78
+ p2 = coords[i + 1]
79
+ step_m = haversine_distance_2d(p1, p2)
80
+ cum_dist += step_m / 1000.0
81
+ elev_diff_m = p2[2] - p1[2]
82
+ slope_pct = (elev_diff_m / step_m * 100.0) if step_m > 0 else 0.0
83
+
84
+ if energy_model is not None:
85
+ _j, step_kcal = energy_model(slope_pct / 100.0, mass_kg=70.0, distance_m=step_m)
86
+ cum_kcal += step_kcal
87
+
88
+ distances_km.append(cum_dist)
89
+ elevations_m.append(p2[2])
90
+ slopes_pct.append(slope_pct)
91
+ calories_kcal.append(cum_kcal)
92
+
93
+ # A motorised profile expends no metabolic energy, so there is no curve to draw.
94
+ if energy_model is None:
95
+ show_energy = False
96
+
97
+ fig, ax1 = plt.subplots(figsize=figsize, dpi=150)
98
+
99
+ # Plot elevation line
100
+ ax1.plot(
101
+ distances_km, elevations_m, color="#0284c7", linewidth=2.5, label="Elevation (m)", zorder=3
102
+ )
103
+ ax1.fill_between(
104
+ distances_km, elevations_m, min(elevations_m) - 2.0, color="#0284c7", alpha=0.15, zorder=2
105
+ )
106
+
107
+ ax1.set_xlabel("Cumulative Distance (km)", fontsize=11, fontweight="600")
108
+ ax1.set_ylabel("Elevation (m)", fontsize=11, fontweight="600", color="#0284c7")
109
+ ax1.tick_params(axis="y", labelcolor="#0284c7")
110
+ ax1.grid(True, linestyle="--", alpha=0.5, zorder=1)
111
+
112
+ # Optional secondary axis for metabolic calories
113
+ if show_energy:
114
+ ax2 = ax1.twinx()
115
+ ax2.plot(
116
+ distances_km,
117
+ calories_kcal,
118
+ color="#f97316",
119
+ linestyle="--",
120
+ linewidth=2.0,
121
+ label="Metabolic Calories (kcal)",
122
+ zorder=4,
123
+ )
124
+ ax2.set_ylabel("Cumulative Energy (kcal)", fontsize=11, fontweight="600", color="#f97316")
125
+ ax2.tick_params(axis="y", labelcolor="#f97316")
126
+
127
+ # Title & formatting. Scoped to this figure, not to pyplot's global "current"
128
+ # axes, which is ax2 once twinx() has run.
129
+ ascent_m = sum(max(0.0, coords[i + 1][2] - coords[i][2]) for i in range(len(coords) - 1))
130
+ stat_title = title or (
131
+ f"3D Route Elevation Profile - Distance: {cum_dist:.2f} km | Ascent: +{ascent_m:.1f} m"
132
+ )
133
+ ax1.set_title(stat_title, fontsize=12, fontweight="bold", pad=12)
134
+ fig.tight_layout()
135
+
136
+ if save_path:
137
+ fig.savefig(save_path, bbox_inches="tight")
138
+
139
+ return fig
140
+
141
+
142
+ def plot_pareto_frontier_2d(
143
+ pareto_result: Any,
144
+ x_metric: str = "time_min",
145
+ y_metric: str = "climb_m",
146
+ figsize: Tuple[float, float] = (8.0, 5.0),
147
+ save_path: Optional[str] = None,
148
+ ) -> Any:
149
+ """Plot 2D non-dominated Pareto trade-off scatter curve."""
150
+ try:
151
+ import matplotlib.pyplot as plt
152
+ except ImportError as exc:
153
+ raise ImportError("matplotlib is required for plotting.") from exc
154
+
155
+ if not hasattr(pareto_result, "solutions") or not pareto_result.solutions:
156
+ raise ValueError("ParetoFrontierResult must contain at least 1 solution.")
157
+
158
+ for name, metric in (("x_metric", x_metric), ("y_metric", y_metric)):
159
+ if metric not in PARETO_METRICS:
160
+ raise ValueError(
161
+ f"{name}={metric!r} is not a Pareto metric. Choose one of "
162
+ f"{', '.join(PARETO_METRICS)}."
163
+ )
164
+
165
+ x_vals: List[float] = []
166
+ y_vals: List[float] = []
167
+ labels: List[str] = []
168
+
169
+ for idx, sol in enumerate(pareto_result.solutions, start=1):
170
+ time_min = (
171
+ sol.statistics.total_duration_min
172
+ if hasattr(sol, "statistics")
173
+ else (sol.costs.time_sec / 60.0)
174
+ )
175
+ climb_m = (
176
+ sol.statistics.elevation_gain_m if hasattr(sol, "statistics") else sol.costs.climb_m
177
+ )
178
+ cal_kcal = (
179
+ sol.statistics.total_calories_kcal
180
+ if hasattr(sol, "statistics")
181
+ else sol.costs.calories_kcal
182
+ )
183
+
184
+ by_metric = {"time_min": time_min, "climb_m": climb_m, "calories_kcal": cal_kcal}
185
+ xv = by_metric[x_metric]
186
+ yv = by_metric[y_metric]
187
+
188
+ x_vals.append(xv)
189
+ y_vals.append(yv)
190
+ labels.append(f"Sol #{idx}")
191
+
192
+ fig, ax = plt.subplots(figsize=figsize, dpi=150)
193
+ ax.scatter(x_vals, y_vals, color="#8b5cf6", s=90, edgecolors="#4c1d95", linewidth=1.5, zorder=3)
194
+
195
+ for i, txt in enumerate(labels):
196
+ ax.annotate(
197
+ txt,
198
+ (x_vals[i], y_vals[i]),
199
+ textcoords="offset points",
200
+ xytext=(8, 5),
201
+ fontsize=9,
202
+ fontweight="600",
203
+ )
204
+
205
+ ax.set_xlabel(x_metric.replace("_", " ").title(), fontsize=11, fontweight="600")
206
+ ax.set_ylabel(y_metric.replace("_", " ").title(), fontsize=11, fontweight="600")
207
+ ax.set_title(
208
+ "NAMOA* 4D Multi-Objective Pareto Trade-Off Frontier",
209
+ fontsize=12,
210
+ fontweight="bold",
211
+ pad=12,
212
+ )
213
+ ax.grid(True, linestyle="--", alpha=0.5, zorder=1)
214
+ fig.tight_layout()
215
+
216
+ if save_path:
217
+ fig.savefig(save_path, bbox_inches="tight")
218
+
219
+ return fig
220
+
221
+
222
+ def plot_lorenz_equity_curve(
223
+ scorecard: Any,
224
+ figsize: Tuple[float, float] = (6.0, 6.0),
225
+ save_path: Optional[str] = None,
226
+ ) -> Any:
227
+ """Plot Lorenz curve of spatial healthcare/amenity accessibility vs perfect equality line."""
228
+ try:
229
+ import matplotlib.pyplot as plt
230
+ except ImportError as exc:
231
+ raise ImportError("matplotlib is required for plotting.") from exc
232
+
233
+ if not hasattr(scorecard, "lorenz_curve"):
234
+ raise ValueError("Expected EquityScorecardResult instance with lorenz_curve.")
235
+
236
+ def _share(mapping: Any, *keys: str) -> float:
237
+ for key in keys:
238
+ value = mapping.get(key)
239
+ if value is not None:
240
+ try:
241
+ return float(value)
242
+ except (TypeError, ValueError):
243
+ continue
244
+ return 0.0
245
+
246
+ lorenz_pts = scorecard.lorenz_curve
247
+ x_pop: List[float] = []
248
+ y_acc: List[float] = []
249
+ for point in lorenz_pts:
250
+ if isinstance(point, dict):
251
+ x_pop.append(_share(point, "pop_share", "pop_fraction"))
252
+ y_acc.append(_share(point, "acc_share", "acc_fraction"))
253
+ elif isinstance(point, (list, tuple)) and len(point) >= 2:
254
+ x_pop.append(float(point[0]))
255
+ y_acc.append(float(point[1]))
256
+
257
+ fig, ax = plt.subplots(figsize=figsize, dpi=150)
258
+ ax.plot(
259
+ [0, 1],
260
+ [0, 1],
261
+ color="#94a3b8",
262
+ linestyle="--",
263
+ linewidth=1.5,
264
+ label="Line of Perfect Equality",
265
+ )
266
+ ax.plot(
267
+ x_pop,
268
+ y_acc,
269
+ color="#10b981",
270
+ linewidth=2.5,
271
+ label=f"Lorenz Curve (Gini = {scorecard.gini_coefficient:.3f})",
272
+ )
273
+ ax.fill_between(x_pop, y_acc, x_pop, color="#10b981", alpha=0.15)
274
+
275
+ ax.set_xlabel("Cumulative Share of Population", fontsize=11, fontweight="600")
276
+ ax.set_ylabel("Cumulative Share of Accessibility", fontsize=11, fontweight="600")
277
+ ax.set_title(
278
+ f"Spatial Equity Lorenz Curve (Gini = {scorecard.gini_coefficient:.3f})",
279
+ fontsize=12,
280
+ fontweight="bold",
281
+ pad=12,
282
+ )
283
+ ax.legend(loc="upper left", frameon=True)
284
+ ax.grid(True, linestyle="--", alpha=0.5)
285
+ ax.set_xlim(0.0, 1.0)
286
+ ax.set_ylim(0.0, 1.0)
287
+ fig.tight_layout()
288
+
289
+ if save_path:
290
+ fig.savefig(save_path, bbox_inches="tight")
291
+
292
+ return fig