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,328 @@
1
+ """OpenStreetMap road network, building footprint, tree, and park fetcher for 02Route 3D."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import http.client
7
+ import json
8
+ import math
9
+ from dataclasses import dataclass
10
+ from typing import List, Optional, Tuple
11
+
12
+ USER_AGENT = "zero2route3d-sdk (https://github.com/YusufEminoglu/zero2route3d_sdk)"
13
+ DEFAULT_TIMEOUT_S = 30
14
+
15
+
16
+ @dataclass
17
+ class OsmBuilding:
18
+ """Real OSM building footprint with height and levels."""
19
+
20
+ building_id: str
21
+ polygon: List[Tuple[float, float]] # [(lon, lat), ...]
22
+ height_m: float = 12.0
23
+ levels: int = 4
24
+ building_type: str = "yes"
25
+
26
+
27
+ @dataclass
28
+ class OsmRoad:
29
+ """Real OSM road centerline with highway type and name."""
30
+
31
+ road_id: str
32
+ geometry: List[Tuple[float, float]] # [(lon, lat), ...]
33
+ highway_type: str = "residential"
34
+ name: str = ""
35
+ oneway: bool = False
36
+ maxspeed: Optional[float] = None
37
+
38
+
39
+ @dataclass
40
+ class OsmTree:
41
+ """Real OSM standalone tree or tree-row point."""
42
+
43
+ tree_id: str
44
+ lon: float
45
+ lat: float
46
+ species: str = "tree"
47
+ height_m: float = 8.0
48
+ canopy_radius_m: float = 3.0
49
+ tree_type: str = "deciduous" # 'deciduous', 'broadleaf', 'conifer', 'pine'
50
+
51
+
52
+ @dataclass
53
+ class OsmPark:
54
+ """Real OSM park, garden, wood, or greenery polygon."""
55
+
56
+ park_id: str
57
+ polygon: List[Tuple[float, float]] # [(lon, lat), ...]
58
+ park_type: str = "park"
59
+ name: str = ""
60
+
61
+
62
+ class OsmDataFetcher:
63
+ """Fetches real roads, building footprints, trees, and park greenery from OpenStreetMap Overpass API."""
64
+
65
+ @staticmethod
66
+ def fetch_roads_and_buildings(
67
+ bbox: Tuple[float, float, float, float],
68
+ timeout_s: int = DEFAULT_TIMEOUT_S,
69
+ ) -> Tuple[List[OsmRoad], List[OsmBuilding]]:
70
+ """Fetch roads and buildings in bbox: (min_lon, min_lat, max_lon, max_lat)."""
71
+ roads, buildings, _, _ = OsmDataFetcher.fetch_full_urban_environment(
72
+ bbox, timeout_s=timeout_s
73
+ )
74
+ return roads, buildings
75
+
76
+ @staticmethod
77
+ def fetch_full_urban_environment(
78
+ bbox: Tuple[float, float, float, float],
79
+ timeout_s: int = DEFAULT_TIMEOUT_S,
80
+ ) -> Tuple[List[OsmRoad], List[OsmBuilding], List[OsmTree], List[OsmPark]]:
81
+ """Fetch roads, buildings, trees, and parks in bbox: (min_lon, min_lat, max_lon, max_lat)."""
82
+ if not bbox or len(bbox) < 4:
83
+ return [], [], [], []
84
+
85
+ min_lon, min_lat, max_lon, max_lat = (
86
+ float(bbox[0]),
87
+ float(bbox[1]),
88
+ float(bbox[2]),
89
+ float(bbox[3]),
90
+ )
91
+ if not (
92
+ math.isfinite(min_lon)
93
+ and math.isfinite(min_lat)
94
+ and math.isfinite(max_lon)
95
+ and math.isfinite(max_lat)
96
+ ):
97
+ return [], [], [], []
98
+
99
+ if min_lon >= max_lon or min_lat >= max_lat:
100
+ return [], [], [], []
101
+
102
+ to_sec = (
103
+ max(1, int(timeout_s))
104
+ if math.isfinite(timeout_s) and timeout_s > 0
105
+ else DEFAULT_TIMEOUT_S
106
+ )
107
+
108
+ query = f"""
109
+ [out:json][timeout:{to_sec}];
110
+ (
111
+ way["highway"~"primary|secondary|tertiary|residential|service|footway|cycleway|living_street|pedestrian|path|track|unclassified"]({min_lat},{min_lon},{max_lat},{max_lon});
112
+ way["building"]({min_lat},{min_lon},{max_lat},{max_lon});
113
+ relation["building"]({min_lat},{min_lon},{max_lat},{max_lon});
114
+ node["natural"="tree"]({min_lat},{min_lon},{max_lat},{max_lon});
115
+ way["natural"~"tree_row|wood|scrub|heath"]({min_lat},{min_lon},{max_lat},{max_lon});
116
+ way["leisure"~"park|garden|pitch"]({min_lat},{min_lon},{max_lat},{max_lon});
117
+ way["landuse"~"grass|forest|recreation_ground|village_green|meadow"]({min_lat},{min_lon},{max_lat},{max_lon});
118
+ );
119
+ out body geom;
120
+ """.strip()
121
+
122
+ roads: List[OsmRoad] = []
123
+ buildings: List[OsmBuilding] = []
124
+ trees: List[OsmTree] = []
125
+ parks: List[OsmPark] = []
126
+
127
+ with contextlib.suppress(Exception):
128
+ import urllib.parse
129
+
130
+ body = urllib.parse.urlencode({"data": query}).encode("utf-8")
131
+ headers = {
132
+ "Content-Type": "application/x-www-form-urlencoded",
133
+ "User-Agent": USER_AGENT,
134
+ }
135
+ conn = http.client.HTTPSConnection("overpass-api.de", timeout=to_sec)
136
+ try:
137
+ conn.request("POST", "/api/interpreter", body=body, headers=headers)
138
+ resp = conn.getresponse()
139
+ if resp.status == 200:
140
+ raw_bytes = resp.read()
141
+ data = json.loads(raw_bytes.decode("utf-8"))
142
+
143
+ for elem in data.get("elements", []):
144
+ tags = elem.get("tags", {})
145
+ elem_id = str(elem.get("id", ""))
146
+ elem_type = elem.get("type", "")
147
+
148
+ # 1. Real Road Network
149
+ if "highway" in tags and elem_type == "way":
150
+ geom = elem.get("geometry", [])
151
+ coords = []
152
+ for pt in geom:
153
+ try:
154
+ lon_val = float(pt["lon"])
155
+ lat_val = float(pt["lat"])
156
+ if math.isfinite(lon_val) and math.isfinite(lat_val):
157
+ coords.append((lon_val, lat_val))
158
+ except (KeyError, ValueError, TypeError):
159
+ continue
160
+
161
+ if len(coords) >= 2:
162
+ roads.append(
163
+ OsmRoad(
164
+ road_id=elem_id,
165
+ geometry=coords,
166
+ highway_type=str(tags.get("highway", "residential")),
167
+ name=str(tags.get("name", "")),
168
+ oneway=tags.get("oneway") in ("yes", "1", "true"),
169
+ )
170
+ )
171
+
172
+ # 2. Real Buildings
173
+ elif "building" in tags:
174
+ geom = elem.get("geometry", [])
175
+ coords = []
176
+ for pt in geom:
177
+ try:
178
+ lon_val = float(pt["lon"])
179
+ lat_val = float(pt["lat"])
180
+ if math.isfinite(lon_val) and math.isfinite(lat_val):
181
+ coords.append((lon_val, lat_val))
182
+ except (KeyError, ValueError, TypeError):
183
+ continue
184
+
185
+ if len(coords) >= 3:
186
+ levels = 4
187
+ height_m = 12.0
188
+ if "building:levels" in tags:
189
+ with contextlib.suppress(ValueError, TypeError):
190
+ levels = max(1, int(float(tags["building:levels"])))
191
+ height_m = levels * 3.2
192
+ elif "height" in tags:
193
+ with contextlib.suppress(ValueError, TypeError):
194
+ h_str = str(tags["height"]).replace("m", "").strip()
195
+ height_m = max(3.0, float(h_str))
196
+ levels = max(1, int(height_m / 3.2))
197
+
198
+ buildings.append(
199
+ OsmBuilding(
200
+ building_id=elem_id,
201
+ polygon=coords,
202
+ height_m=height_m,
203
+ levels=levels,
204
+ building_type=str(tags.get("building", "yes")),
205
+ )
206
+ )
207
+
208
+ # 3. Real Standalone Tree Nodes
209
+ elif tags.get("natural") == "tree" and elem_type == "node":
210
+ try:
211
+ t_lon = float(elem.get("lon", tags.get("lon", 0.0)))
212
+ t_lat = float(elem.get("lat", tags.get("lat", 0.0)))
213
+ except (ValueError, TypeError):
214
+ continue
215
+
216
+ if (
217
+ math.isfinite(t_lon)
218
+ and math.isfinite(t_lat)
219
+ and t_lon != 0.0
220
+ and t_lat != 0.0
221
+ ):
222
+ t_species = tags.get(
223
+ "species", tags.get("genus", tags.get("taxon", "tree"))
224
+ )
225
+ t_leaf = tags.get("leaf_type", "").lower()
226
+ t_type = (
227
+ "conifer"
228
+ if (
229
+ "needle" in t_leaf
230
+ or "conifer" in t_leaf
231
+ or "pine" in t_species.lower()
232
+ )
233
+ else "deciduous"
234
+ )
235
+ t_height = 8.0
236
+ if "height" in tags:
237
+ with contextlib.suppress(ValueError, TypeError):
238
+ t_height = max(
239
+ 3.0,
240
+ min(
241
+ 35.0,
242
+ float(str(tags["height"]).replace("m", "").strip()),
243
+ ),
244
+ )
245
+ t_radius = max(1.5, min(8.0, t_height * 0.38))
246
+ if "diameter_crown" in tags:
247
+ with contextlib.suppress(ValueError, TypeError):
248
+ t_radius = max(
249
+ 1.5,
250
+ min(
251
+ 10.0,
252
+ float(
253
+ str(tags["diameter_crown"])
254
+ .replace("m", "")
255
+ .strip()
256
+ )
257
+ * 0.5,
258
+ ),
259
+ )
260
+
261
+ trees.append(
262
+ OsmTree(
263
+ tree_id=elem_id,
264
+ lon=t_lon,
265
+ lat=t_lat,
266
+ species=str(t_species),
267
+ height_m=t_height,
268
+ canopy_radius_m=t_radius,
269
+ tree_type=t_type,
270
+ )
271
+ )
272
+
273
+ # 4. Real Tree Rows
274
+ elif tags.get("natural") == "tree_row" and elem_type == "way":
275
+ geom = elem.get("geometry", [])
276
+ for idx, pt in enumerate(geom):
277
+ with contextlib.suppress(Exception):
278
+ t_lon = float(pt["lon"])
279
+ t_lat = float(pt["lat"])
280
+ if math.isfinite(t_lon) and math.isfinite(t_lat):
281
+ trees.append(
282
+ OsmTree(
283
+ tree_id=f"{elem_id}_{idx}",
284
+ lon=t_lon,
285
+ lat=t_lat,
286
+ species="tree_row",
287
+ height_m=7.5,
288
+ canopy_radius_m=2.6,
289
+ tree_type="deciduous",
290
+ )
291
+ )
292
+
293
+ # 5. Real Parks, Gardens, Grass and Greenery Polygons
294
+ elif (
295
+ "leisure" in tags
296
+ or "landuse" in tags
297
+ or tags.get("natural") in ("wood", "scrub", "heath")
298
+ ) and elem_type == "way":
299
+ geom = elem.get("geometry", [])
300
+ coords = []
301
+ for pt in geom:
302
+ try:
303
+ lon_val = float(pt["lon"])
304
+ lat_val = float(pt["lat"])
305
+ if math.isfinite(lon_val) and math.isfinite(lat_val):
306
+ coords.append((lon_val, lat_val))
307
+ except (KeyError, ValueError, TypeError):
308
+ continue
309
+
310
+ if len(coords) >= 3:
311
+ p_type = str(
312
+ tags.get(
313
+ "leisure", tags.get("landuse", tags.get("natural", "park"))
314
+ )
315
+ )
316
+ p_name = str(tags.get("name", ""))
317
+ parks.append(
318
+ OsmPark(
319
+ park_id=elem_id,
320
+ polygon=coords,
321
+ park_type=p_type,
322
+ name=p_name,
323
+ )
324
+ )
325
+ finally:
326
+ conn.close()
327
+
328
+ return roads, buildings, trees, parks
@@ -0,0 +1,351 @@
1
+ """Native QGIS cartographic styling inspired by the 02Agent OSM Downloader palette suite."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any, Dict, List, Tuple
7
+
8
+ _HEX_COLOR = re.compile(r"^#[0-9a-fA-F]{6}$")
9
+
10
+ OSM_THEMES: Dict[str, dict] = {
11
+ "atlas": {
12
+ "label": "Civic Atlas",
13
+ "description": "Clean, legible civic cartography for general urban mobility planning.",
14
+ "bg": "#f7f8f2",
15
+ "base": "#566b6f",
16
+ "roads_major": "#2f4858",
17
+ "roads_minor": "#d8d7ce",
18
+ "greens": "#7fb069",
19
+ "water": "#3a86b5",
20
+ "trees": "#3f7d4e",
21
+ "buildings": {
22
+ "residential": "#d9c8b4",
23
+ "commercial": "#a9bdd0",
24
+ "industrial": "#c4b79a",
25
+ "civic": "#b8d5ce",
26
+ "worship": "#d9c7df",
27
+ "other": "#cfd0c8",
28
+ },
29
+ },
30
+ "cyber": {
31
+ "label": "Tokyo Cyber",
32
+ "description": "High-contrast dark neon tones for striking network and mobility maps.",
33
+ "bg": "#0a0b10",
34
+ "base": "#121420",
35
+ "roads_major": "#ff0055",
36
+ "roads_minor": "#1a1d36",
37
+ "greens": "#082c2b",
38
+ "water": "#00ffcc",
39
+ "trees": "#00ff66",
40
+ "buildings": {
41
+ "residential": "#bc39fa",
42
+ "commercial": "#ff8800",
43
+ "industrial": "#ffdd00",
44
+ "civic": "#00aaff",
45
+ "worship": "#00ff66",
46
+ "other": "#ff007f",
47
+ },
48
+ },
49
+ "paper": {
50
+ "label": "Editorial Paper",
51
+ "description": "Warm ink-and-parchment tones for high-end master plan publications.",
52
+ "bg": "#fdfbf7",
53
+ "base": "#e6dfd3",
54
+ "roads_major": "#7c5c43",
55
+ "roads_minor": "#eadecc",
56
+ "greens": "#c2c5aa",
57
+ "water": "#9ab8c2",
58
+ "trees": "#6b705c",
59
+ "buildings": {
60
+ "residential": "#ebd4c0",
61
+ "commercial": "#c4d1db",
62
+ "industrial": "#dbcfb8",
63
+ "civic": "#cfdcd5",
64
+ "worship": "#e8dfeb",
65
+ "other": "#dcd8d3",
66
+ },
67
+ },
68
+ "frost": {
69
+ "label": "Nordic Frost",
70
+ "description": "Cool minimal scandinavian tones with crisp glacier blue accents.",
71
+ "bg": "#f5f7fa",
72
+ "base": "#d8dee9",
73
+ "roads_major": "#4c566a",
74
+ "roads_minor": "#e5e9f0",
75
+ "greens": "#a3be8c",
76
+ "water": "#88c0d0",
77
+ "trees": "#4c566a",
78
+ "buildings": {
79
+ "residential": "#d8dee9",
80
+ "commercial": "#81a1c1",
81
+ "industrial": "#4c566a",
82
+ "civic": "#88c0d0",
83
+ "worship": "#b48ead",
84
+ "other": "#e5e9f0",
85
+ },
86
+ },
87
+ "noir": {
88
+ "label": "Monochrome Noir",
89
+ "description": "Architectural high-contrast grayscale scheme for structural massing.",
90
+ "bg": "#1e1e1e",
91
+ "base": "#121212",
92
+ "roads_major": "#ffffff",
93
+ "roads_minor": "#2e2e2e",
94
+ "greens": "#262626",
95
+ "water": "#3a3a3a",
96
+ "trees": "#5c5c5c",
97
+ "buildings": {
98
+ "residential": "#404040",
99
+ "commercial": "#808080",
100
+ "industrial": "#2a2a2a",
101
+ "civic": "#a0a0a0",
102
+ "worship": "#c0c0c0",
103
+ "other": "#606060",
104
+ },
105
+ },
106
+ "mediterranean": {
107
+ "label": "Mediterranean Survey",
108
+ "description": "Sun, terracotta and deep azure tones for coastal urban morphology.",
109
+ "bg": "#fbf4e6",
110
+ "base": "#8a7a5a",
111
+ "roads_major": "#c65f46",
112
+ "roads_minor": "#eadfc9",
113
+ "greens": "#86a873",
114
+ "water": "#4fa6c6",
115
+ "trees": "#4e7f55",
116
+ "buildings": {
117
+ "residential": "#e7c7aa",
118
+ "commercial": "#b8cad8",
119
+ "industrial": "#d4b98d",
120
+ "civic": "#c8d9c9",
121
+ "worship": "#ddc2d9",
122
+ "other": "#d8cfc1",
123
+ },
124
+ },
125
+ "nightprint": {
126
+ "label": "Night Print",
127
+ "description": "Deep obsidian backdrop with warm amber arterial transit highlights.",
128
+ "bg": "#11161a",
129
+ "base": "#1b2628",
130
+ "roads_major": "#ffd166",
131
+ "roads_minor": "#2d3a3f",
132
+ "greens": "#2a6f58",
133
+ "water": "#118ab2",
134
+ "trees": "#5fbf7a",
135
+ "buildings": {
136
+ "residential": "#7d8da1",
137
+ "commercial": "#f4a261",
138
+ "industrial": "#a7a16d",
139
+ "civic": "#74c0c2",
140
+ "worship": "#b28fd8",
141
+ "other": "#98a0a6",
142
+ },
143
+ },
144
+ "default": {
145
+ "label": "Muted Planning",
146
+ "description": "Quiet everyday planning tones for comprehensive urban analytics.",
147
+ "bg": "#ffffff",
148
+ "base": "#5e7274",
149
+ "roads_major": "#e1846f",
150
+ "roads_minor": "#eae5da",
151
+ "greens": "#a9c08a",
152
+ "water": "#a5c9eb",
153
+ "trees": "#6f9e5c",
154
+ "buildings": {
155
+ "residential": "#d8c3b1",
156
+ "commercial": "#b7c2d0",
157
+ "industrial": "#c6b9a4",
158
+ "civic": "#cdd6d2",
159
+ "worship": "#d8cfe2",
160
+ "other": "#cac5bf",
161
+ },
162
+ },
163
+ }
164
+
165
+ DEFAULT_THEME = "atlas"
166
+
167
+
168
+ def list_osm_themes() -> List[Tuple[str, str]]:
169
+ """Return list of (theme_key, display_label) tuples for all 8 cartographic styles."""
170
+ return [(k, v["label"]) for k, v in OSM_THEMES.items()]
171
+
172
+
173
+ def get_theme_palette(theme_key: str = "atlas") -> dict:
174
+ """Retrieve theme dictionary by key with fallback to atlas."""
175
+ return OSM_THEMES.get(theme_key, OSM_THEMES["atlas"])
176
+
177
+
178
+ def _shade(color: str, factor: float) -> str:
179
+ if not (color.startswith("#") and len(color) == 7):
180
+ return color
181
+ rgb = [int(color[index : index + 2], 16) for index in (1, 3, 5)]
182
+ if factor <= 1.0:
183
+ values = [round(value * factor) for value in rgb]
184
+ else:
185
+ amount = min(1.0, factor - 1.0)
186
+ values = [round(value + (255 - value) * amount) for value in rgb]
187
+ return "#%02x%02x%02x" % tuple(values)
188
+
189
+
190
+ def _fill(color: str, opacity: float = 0.82) -> Any:
191
+ from qgis.core import QgsFillSymbol
192
+
193
+ symbol = QgsFillSymbol.createSimple(
194
+ {
195
+ "color": color,
196
+ "outline_color": _shade(color, 0.72),
197
+ "outline_width": "0.18",
198
+ "style": "solid",
199
+ }
200
+ )
201
+ symbol.setOpacity(opacity)
202
+ return symbol
203
+
204
+
205
+ def _line(color: str, width: float, dashed: bool = False) -> Any:
206
+ from qgis.core import QgsLineSymbol
207
+
208
+ properties = {
209
+ "color": color,
210
+ "width": str(width),
211
+ "capstyle": "round",
212
+ "joinstyle": "round",
213
+ }
214
+ if dashed:
215
+ properties["line_style"] = "dash"
216
+ return QgsLineSymbol.createSimple(properties)
217
+
218
+
219
+ def _renderer(expression: str, entries: Any) -> Any:
220
+ from qgis.core import QgsCategorizedSymbolRenderer, QgsRendererCategory
221
+
222
+ return QgsCategorizedSymbolRenderer(
223
+ expression,
224
+ [QgsRendererCategory(value, symbol, label) for value, label, symbol in entries],
225
+ )
226
+
227
+
228
+ def _building_renderer(theme: dict) -> Any:
229
+ colors = theme["buildings"]
230
+ expression = (
231
+ "CASE"
232
+ " WHEN lower(coalesce(\"building\",'')) IN ('apartments','residential','house','detached','terrace','dormitory','bungalow','semidetached_house','hut') THEN 'building_residential'"
233
+ " WHEN lower(coalesce(\"building\",'')) IN ('commercial','retail','office','supermarket','kiosk','hotel') THEN 'building_commercial'"
234
+ " WHEN lower(coalesce(\"building\",'')) IN ('industrial','warehouse','manufacture','hangar','factory') THEN 'building_industrial'"
235
+ " WHEN lower(coalesce(\"building\",'')) IN ('church','mosque','temple','synagogue','cathedral','chapel') THEN 'building_worship'"
236
+ " WHEN coalesce(\"building\",'') <> '' THEN 'building_civic'"
237
+ " WHEN lower(coalesce(\"type\",'')) IN ('commercial','retail','office') THEN 'building_commercial'"
238
+ " WHEN lower(coalesce(\"type\",'')) IN ('industrial','warehouse') THEN 'building_industrial'"
239
+ " ELSE 'building_other' END"
240
+ )
241
+ labels = {
242
+ "residential": "Residential buildings",
243
+ "commercial": "Commercial buildings",
244
+ "industrial": "Industrial buildings",
245
+ "civic": "Civic buildings",
246
+ "worship": "Worship buildings",
247
+ }
248
+ entries = [
249
+ (f"building_{key}", labels[key], _fill(color))
250
+ for key, color in colors.items()
251
+ if key != "other"
252
+ ]
253
+ entries.append(("building_other", "Other buildings", _fill(colors["other"], 0.66)))
254
+ return _renderer(expression, entries)
255
+
256
+
257
+ def _road_renderer(theme: dict) -> Any:
258
+ major = theme["roads_major"]
259
+ minor = theme["roads_minor"]
260
+ greens = theme["greens"]
261
+ base = theme["base"]
262
+ expression = (
263
+ "CASE"
264
+ " WHEN lower(coalesce(\"highway\",'')) IN ('motorway','trunk','motorway_link','trunk_link') THEN 'major'"
265
+ " WHEN lower(coalesce(\"highway\",'')) IN ('primary','primary_link') THEN 'primary'"
266
+ " WHEN lower(coalesce(\"highway\",'')) IN ('secondary','secondary_link') THEN 'secondary'"
267
+ " WHEN lower(coalesce(\"highway\",'')) IN ('tertiary','tertiary_link') THEN 'tertiary'"
268
+ " WHEN lower(coalesce(\"highway\",'')) IN ('residential','unclassified','living_street','road') THEN 'residential'"
269
+ " WHEN lower(coalesce(\"highway\",'')) IN ('service','track') THEN 'service'"
270
+ " WHEN lower(coalesce(\"highway\",'')) IN ('footway','path','pedestrian','steps','corridor','bridleway','cycleway') THEN 'active'"
271
+ " WHEN lower(coalesce(\"type\",'')) IN ('primary','secondary','tertiary') THEN lower(\"type\")"
272
+ " ELSE 'other' END"
273
+ )
274
+ widths = {
275
+ "major": 1.55,
276
+ "primary": 1.28,
277
+ "secondary": 1.05,
278
+ "tertiary": 0.82,
279
+ "residential": 0.66,
280
+ "service": 0.48,
281
+ "active": 0.55,
282
+ "other": 0.58,
283
+ }
284
+ entries = [
285
+ ("major", "Motorway and trunk", _line(major, widths["major"])),
286
+ ("primary", "Primary roads", _line(major, widths["primary"])),
287
+ ("secondary", "Secondary roads", _line(major, widths["secondary"])),
288
+ ("tertiary", "Tertiary roads", _line(major, widths["tertiary"])),
289
+ ("residential", "Residential roads", _line(minor, widths["residential"])),
290
+ ("service", "Service roads", _line(minor, widths["service"])),
291
+ ("active", "Walking and cycling", _line(greens, widths["active"], True)),
292
+ ("other", "Other lines", _line(base, widths["other"])),
293
+ ]
294
+ return _renderer(expression, entries)
295
+
296
+
297
+ def _point_renderer(theme: dict) -> Any:
298
+ from qgis.core import QgsMarkerSymbol, QgsSingleSymbolRenderer
299
+
300
+ tree_color = theme.get("trees", "#16a34a")
301
+ sym = QgsMarkerSymbol.createSimple(
302
+ {
303
+ "name": "circle",
304
+ "color": tree_color,
305
+ "outline_color": "#ffffff",
306
+ "outline_width": "0.4",
307
+ "size": "3.5",
308
+ }
309
+ )
310
+ return QgsSingleSymbolRenderer(sym)
311
+
312
+
313
+ def apply_osm_theme_style(layer: Any, theme_key: str = "atlas") -> bool:
314
+ """Apply any of the 8 02Agent OSM Downloader visual themes to a vector layer."""
315
+ try:
316
+ geometry_type = int(layer.geometryType())
317
+ from qgis.core import QgsWkbTypes
318
+
319
+ theme = get_theme_palette(theme_key)
320
+
321
+ if geometry_type == int(QgsWkbTypes.PolygonGeometry):
322
+ renderer = _building_renderer(theme)
323
+ elif geometry_type == int(QgsWkbTypes.LineGeometry):
324
+ renderer = _road_renderer(theme)
325
+ elif geometry_type == int(QgsWkbTypes.PointGeometry):
326
+ renderer = _point_renderer(theme)
327
+ else:
328
+ return False
329
+
330
+ layer.setRenderer(renderer)
331
+ layer.setCustomProperty("zero2route3d/style", f"02Agent OSM Downloader — {theme['label']}")
332
+ layer.setCustomProperty("zero2route3d/theme_key", theme_key)
333
+ layer.triggerRepaint()
334
+ return True
335
+ except Exception:
336
+ return False
337
+
338
+
339
+ def apply_osm_atlas_style(layer: Any) -> bool:
340
+ """Backwards-compatible convenience helper applying Civic Atlas style."""
341
+ return apply_osm_theme_style(layer, "atlas")
342
+
343
+
344
+ __all__ = [
345
+ "OSM_THEMES",
346
+ "DEFAULT_THEME",
347
+ "list_osm_themes",
348
+ "get_theme_palette",
349
+ "apply_osm_theme_style",
350
+ "apply_osm_atlas_style",
351
+ ]