geo-carto-engine 1.1.0__tar.gz

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 (31) hide show
  1. geo_carto_engine-1.1.0/PKG-INFO +12 -0
  2. geo_carto_engine-1.1.0/geo_carto/__init__.py +3 -0
  3. geo_carto_engine-1.1.0/geo_carto/assets/fonts/NotoSansCJKsc-Regular.otf +0 -0
  4. geo_carto_engine-1.1.0/geo_carto/basemap_overlay.py +577 -0
  5. geo_carto_engine-1.1.0/geo_carto/cli.py +216 -0
  6. geo_carto_engine-1.1.0/geo_carto/data/curriculum_kb/hs_geography_syllabus_graph.json +255 -0
  7. geo_carto_engine-1.1.0/geo_carto/data/distilled_knowledge/colab_deep_v1/deep_distill_synthesis.json +7473 -0
  8. geo_carto_engine-1.1.0/geo_carto/data/distilled_knowledge/colab_deep_v1/geoedu_bge_m3_text_index.npz +0 -0
  9. geo_carto_engine-1.1.0/geo_carto/data/distilled_knowledge/colab_deep_v1/geoedu_bge_m3_text_meta.json +1 -0
  10. geo_carto_engine-1.1.0/geo_carto/data/distilled_knowledge/colab_deep_v1/geoedu_siglip_visual_index.npz +0 -0
  11. geo_carto_engine-1.1.0/geo_carto/data/distilled_knowledge/colab_deep_v1/geoedu_siglip_visual_meta.json +1 -0
  12. geo_carto_engine-1.1.0/geo_carto/data/distilled_knowledge/colab_deep_v1/progressive_layer_pairs_detected.json +9005 -0
  13. geo_carto_engine-1.1.0/geo_carto/data/distilled_knowledge/colab_deep_v1/siglip_category_prototypes.npz +0 -0
  14. geo_carto_engine-1.1.0/geo_carto/data/distilled_knowledge/full_corpus_v2/consensus_by_canonical_topic.json +6305 -0
  15. geo_carto_engine-1.1.0/geo_carto/data/distilled_knowledge/round1/lesson_pedagogical_blueprints.json +5522 -0
  16. geo_carto_engine-1.1.0/geo_carto/data/golden_layouts.json +146 -0
  17. geo_carto_engine-1.1.0/geo_carto/dem_terrain.py +836 -0
  18. geo_carto_engine-1.1.0/geo_carto/distill_bridge.py +1192 -0
  19. geo_carto_engine-1.1.0/geo_carto/earth_svg_and_charts.py +198 -0
  20. geo_carto_engine-1.1.0/geo_carto/rs_analyzer.py +966 -0
  21. geo_carto_engine-1.1.0/geo_carto/spatial_interp.py +111 -0
  22. geo_carto_engine-1.1.0/geo_carto/stac_fetcher.py +599 -0
  23. geo_carto_engine-1.1.0/geo_carto/theme.py +172 -0
  24. geo_carto_engine-1.1.0/geo_carto_engine.egg-info/PKG-INFO +12 -0
  25. geo_carto_engine-1.1.0/geo_carto_engine.egg-info/SOURCES.txt +29 -0
  26. geo_carto_engine-1.1.0/geo_carto_engine.egg-info/dependency_links.txt +1 -0
  27. geo_carto_engine-1.1.0/geo_carto_engine.egg-info/entry_points.txt +2 -0
  28. geo_carto_engine-1.1.0/geo_carto_engine.egg-info/requires.txt +7 -0
  29. geo_carto_engine-1.1.0/geo_carto_engine.egg-info/top_level.txt +1 -0
  30. geo_carto_engine-1.1.0/pyproject.toml +34 -0
  31. geo_carto_engine-1.1.0/setup.cfg +4 -0
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.4
2
+ Name: geo-carto-engine
3
+ Version: 1.1.0
4
+ Summary: Remote Sensing and GIS Spatial Analysis Cartography Engine for Senior High School Geography
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: numpy>=1.26
7
+ Requires-Dist: scipy>=1.11
8
+ Requires-Dist: matplotlib>=3.8
9
+ Requires-Dist: pillow>=10.0
10
+ Requires-Dist: rasterio>=1.3
11
+ Requires-Dist: shapely>=2.0
12
+ Requires-Dist: python-pptx>=0.6.23
@@ -0,0 +1,3 @@
1
+ """GeoCarto Engine: Remote Sensing & GIS Automated Cartography for Geography Education."""
2
+
3
+ __version__ = "1.1.0"
@@ -0,0 +1,577 @@
1
+ """MNR GS-Compliant Administrative Boundary Basemap Loader, Reprojector, and Cartographic Overlay."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import unicodedata
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import matplotlib.pyplot as plt
12
+ from matplotlib.patches import PathPatch, Rectangle
13
+ from matplotlib.path import Path as MplPath
14
+ from rasterio.warp import transform_geom
15
+ from shapely.geometry import box as shapely_box
16
+ from shapely.geometry import shape
17
+ from shapely.validation import make_valid
18
+
19
+ from .theme import configure_cjk_font
20
+
21
+ FORBIDDEN_BASEMAP_TOKENS = (
22
+ "natural" + "earth",
23
+ "natural_" + "earth",
24
+ "natural " + "earth",
25
+ "natural" + "-earth",
26
+ "natural." + "earth",
27
+ "ne_" + "10m",
28
+ "ne_" + "50m",
29
+ "ne_" + "110m",
30
+ "ne" + "10m",
31
+ "ne" + "50m",
32
+ "ne" + "110m",
33
+ "ga" + "dm",
34
+ "diva-" + "gis",
35
+ "diva_" + "gis",
36
+ "diva" + "gis",
37
+ )
38
+
39
+ FORBIDDEN_SCHEMA_KEYS = (
40
+ "gid_" + "0",
41
+ "gid_" + "1",
42
+ "gid_" + "2",
43
+ "gid_" + "3",
44
+ "gid_" + "4",
45
+ "gid_" + "5",
46
+ "adm0_" + "a3",
47
+ "sov_" + "a3",
48
+ "ne_" + "id",
49
+ "feature" + "cla",
50
+ "sover" + "eignt",
51
+ )
52
+
53
+
54
+ def _norm_compliance_str(text: str) -> str:
55
+ return unicodedata.normalize("NFKC", text).strip().lower()
56
+
57
+
58
+ def _collapse_sep(text: str) -> str:
59
+ return re.sub(r"[\s._\-/:]+", "", _norm_compliance_str(text))
60
+
61
+
62
+ def _scan_forbidden_tokens(obj: Any, path_prefix: str = "") -> str | None:
63
+ """Recursively scan JSON metadata/properties for forbidden overseas boundary provenance markers."""
64
+ if isinstance(obj, dict):
65
+ for k, v in obj.items():
66
+ k_norm = _norm_compliance_str(str(k))
67
+ k_coll = _collapse_sep(str(k))
68
+ if k_norm in FORBIDDEN_SCHEMA_KEYS or k_coll in {_collapse_sep(sk) for sk in FORBIDDEN_SCHEMA_KEYS}:
69
+ return f"forbidden schema key '{k}' at {path_prefix}"
70
+ for tok in FORBIDDEN_BASEMAP_TOKENS:
71
+ if tok in k_norm or tok in k_coll:
72
+ return f"forbidden token '{tok}' in key '{k}' at {path_prefix}"
73
+ hit = _scan_forbidden_tokens(v, f"{path_prefix}.{k}" if path_prefix else str(k))
74
+ if hit:
75
+ return hit
76
+ elif isinstance(obj, list):
77
+ for idx, item in enumerate(obj):
78
+ hit = _scan_forbidden_tokens(item, f"{path_prefix}[{idx}]")
79
+ if hit:
80
+ return hit
81
+ elif isinstance(obj, str):
82
+ val_norm = _norm_compliance_str(obj)
83
+ val_coll = _collapse_sep(obj)
84
+ for tok in FORBIDDEN_BASEMAP_TOKENS:
85
+ if tok in val_norm or tok in val_coll:
86
+ return f"forbidden token '{tok}' in value at {path_prefix}"
87
+ return None
88
+
89
+
90
+ def _validate_compliant_geojson(basemap_path: str | Path, payload: dict[str, Any]) -> None:
91
+ """Strictly reject unapproved overseas boundary datasets and enforce MNR GS compliance."""
92
+ p = Path(basemap_path)
93
+ filename_norm = _norm_compliance_str(p.name)
94
+ filename_coll = _collapse_sep(p.name)
95
+ for tok in FORBIDDEN_BASEMAP_TOKENS:
96
+ if tok in filename_norm or tok in filename_coll:
97
+ raise ValueError(
98
+ f"Rejected non-compliant basemap '{p.name}': contains forbidden boundary source token '{tok}'. "
99
+ "中国行政区划与国界底图严禁使用境外开源或未审图号边界数据。"
100
+ )
101
+ # Check non-test parent directory names as well
102
+ for part in p.parts[:-1]:
103
+ part_norm = _norm_compliance_str(part)
104
+ if part_norm.startswith("test_") or part_norm.startswith("pytest"):
105
+ continue
106
+ part_coll = _collapse_sep(part)
107
+ for tok in FORBIDDEN_BASEMAP_TOKENS:
108
+ if tok in part_norm or tok in part_coll:
109
+ raise ValueError(
110
+ f"Rejected non-compliant basemap path '{basemap_path}': contains '{tok}'."
111
+ )
112
+
113
+ top_meta = {
114
+ k: v
115
+ for k, v in payload.items()
116
+ if k not in ("type", "features")
117
+ }
118
+ hit = _scan_forbidden_tokens(top_meta, "metadata")
119
+ if hit:
120
+ raise ValueError(f"Rejected non-compliant basemap GeoJSON ({hit}). 严禁使用境外未审图号边界数据。")
121
+
122
+ for idx, feat in enumerate(payload.get("features", [])):
123
+ if not isinstance(feat, dict):
124
+ continue
125
+ feat_meta = {
126
+ k: v
127
+ for k, v in feat.items()
128
+ if k not in ("type", "geometry")
129
+ }
130
+ if feat_meta:
131
+ hit = _scan_forbidden_tokens(feat_meta, f"features[{idx}]")
132
+ if hit:
133
+ raise ValueError(f"Rejected non-compliant basemap feature ({hit}). 严禁使用境外未审图号边界数据。")
134
+
135
+
136
+ def _normalize_crs_str(crs_raw: str | None) -> str:
137
+ """Normalize GeoJSON CRS URN/string to EPSG:xxxx where possible."""
138
+ if not crs_raw:
139
+ return "EPSG:4326"
140
+ s = str(crs_raw).strip()
141
+ if "CRS84" in s.upper():
142
+ return "EPSG:4326"
143
+ m = re.search(r"EPSG[:/]+(\d+)", s, flags=re.IGNORECASE)
144
+ if m:
145
+ return f"EPSG:{m.group(1)}"
146
+ return s
147
+
148
+
149
+ def _lookup_registry_entry(filename: str) -> dict[str, Any] | None:
150
+ """Look up optional local vector metadata from data/standard_basemaps/registry.json."""
151
+ reg_path = Path(__file__).resolve().parents[2] / "data" / "standard_basemaps" / "registry.json"
152
+ if not reg_path.exists():
153
+ return None
154
+ try:
155
+ reg = json.loads(reg_path.read_text(encoding="utf-8"))
156
+ for item in reg.get("local_vectors", []):
157
+ if item.get("file") == filename:
158
+ return item
159
+ except Exception:
160
+ return None
161
+ return None
162
+
163
+
164
+ def _flatten_geometries(geom: dict[str, Any] | None) -> list[dict[str, Any]]:
165
+ """Recursively flatten GeoJSON GeometryCollection into atomic geometry dicts."""
166
+ if not isinstance(geom, dict):
167
+ return []
168
+ if geom.get("type") == "GeometryCollection":
169
+ out: list[dict[str, Any]] = []
170
+ for sub in geom.get("geometries") or []:
171
+ out.extend(_flatten_geometries(sub))
172
+ return out
173
+ return [geom]
174
+
175
+
176
+ def _safe_make_valid(shp):
177
+ """Ensure Shapely geometry is topologically valid before intersection/area ops."""
178
+ if shp.is_empty:
179
+ return shp
180
+ if not shp.is_valid:
181
+ try:
182
+ fixed = make_valid(shp)
183
+ except Exception:
184
+ fixed = shp.buffer(0)
185
+ return fixed
186
+ return shp
187
+
188
+
189
+ def _ring_signed_area(pts: list[list[float]]) -> float:
190
+ area = 0.0
191
+ n = len(pts)
192
+ for i in range(n):
193
+ x1, y1 = pts[i]
194
+ x2, y2 = pts[(i + 1) % n]
195
+ area += x1 * y2 - x2 * y1
196
+ return 0.5 * area
197
+
198
+
199
+ def _polygon_coords_to_path(coords: list[Any]) -> MplPath | None:
200
+ """Build a Matplotlib compound Path supporting exterior and interior hole rings."""
201
+ if not coords or not coords[0] or len(coords[0]) < 3:
202
+ return None
203
+ verts: list[tuple[float, float]] = []
204
+ codes: list[int] = []
205
+ for r_idx, ring in enumerate(coords):
206
+ if len(ring) < 3:
207
+ continue
208
+ pts = [[float(pt[0]), float(pt[1])] for pt in ring]
209
+ if pts[0] != pts[-1]:
210
+ pts.append(list(pts[0]))
211
+ if len(pts) < 4:
212
+ continue
213
+ s_area = _ring_signed_area(pts[:-1])
214
+ if r_idx == 0 and s_area < 0:
215
+ pts = pts[::-1]
216
+ elif r_idx > 0 and s_area > 0:
217
+ pts = pts[::-1]
218
+ verts.extend((p[0], p[1]) for p in pts)
219
+ codes.extend([MplPath.MOVETO] + [MplPath.LINETO] * (len(pts) - 2) + [MplPath.CLOSEPOLY])
220
+ if not verts:
221
+ return None
222
+ return MplPath(verts, codes)
223
+
224
+
225
+ def load_standard_basemap(basemap_path: str | Path, target_crs: str | None = None) -> dict[str, Any]:
226
+ """Load and validate an MNR GS-compliant GeoJSON basemap, optionally reprojecting via rasterio.warp."""
227
+ path = Path(basemap_path)
228
+ if not path.exists():
229
+ raise FileNotFoundError(f"Standard basemap GeoJSON not found: {path}")
230
+
231
+ payload = json.loads(path.read_text(encoding="utf-8"))
232
+ if not isinstance(payload, dict):
233
+ raise ValueError(f"Invalid GeoJSON root type (expected JSON object): {path}")
234
+ if payload.get("type") != "FeatureCollection" or not isinstance(payload.get("features"), list):
235
+ raise ValueError(f"Invalid GeoJSON FeatureCollection: {path}")
236
+ if len(payload["features"]) == 0:
237
+ raise ValueError(f"Basemap GeoJSON contains zero features: {path}")
238
+
239
+ _validate_compliant_geojson(path, payload)
240
+
241
+ crs_raw = payload.get("crs", {}).get("properties", {}).get("name") if isinstance(payload.get("crs"), dict) else None
242
+ src_crs = _normalize_crs_str(crs_raw)
243
+ out_crs = _normalize_crs_str(target_crs) if target_crs else src_crs
244
+ need_reproject = target_crs is not None and out_crs.upper() != src_crs.upper()
245
+
246
+ out_features: list[dict[str, Any]] = []
247
+ minx = miny = float("inf")
248
+ maxx = maxy = float("-inf")
249
+
250
+ for feat in payload["features"]:
251
+ geom = feat.get("geometry")
252
+ if not geom:
253
+ continue
254
+ out_geom = transform_geom(src_crs, out_crs, geom) if need_reproject else geom
255
+ shp = shape(out_geom)
256
+ if not shp.is_empty:
257
+ bx0, by0, bx1, by1 = shp.bounds
258
+ minx = min(minx, bx0)
259
+ miny = min(miny, by0)
260
+ maxx = max(maxx, bx1)
261
+ maxy = max(maxy, by1)
262
+ new_feat = dict(feat)
263
+ new_feat["geometry"] = out_geom
264
+ out_features.append(new_feat)
265
+
266
+ if not out_features or minx == float("inf"):
267
+ raise ValueError(f"No valid geometries found in basemap: {path}")
268
+
269
+ reg_entry = _lookup_registry_entry(path.name)
270
+ meta = payload.get("metadata", {}) if isinstance(payload.get("metadata"), dict) else {}
271
+ gs_code = (
272
+ payload.get("gs_code")
273
+ or meta.get("gs_code")
274
+ or meta.get("gs_number")
275
+ or (reg_entry.get("gs_number") if reg_entry else None)
276
+ )
277
+ basemap_source = (
278
+ payload.get("basemap_source")
279
+ or payload.get("source")
280
+ or meta.get("source")
281
+ or (reg_entry.get("source") if reg_entry else None)
282
+ or "国家地理信息公共服务平台(天地图)/ 自然资源部标准地图服务"
283
+ )
284
+
285
+ return {
286
+ "crs": out_crs,
287
+ "src_crs": src_crs,
288
+ "gs_code": gs_code,
289
+ "basemap_source": basemap_source,
290
+ "metadata": meta,
291
+ "features": out_features,
292
+ "bounds": (float(minx), float(miny), float(maxx), float(maxy)),
293
+ }
294
+
295
+
296
+ def _looks_geographic_lonlat(features: list[dict[str, Any]]) -> bool:
297
+ """Heuristic check whether ALL feature geometries appear to be in EPSG:4326 lon/lat degrees."""
298
+ has_geom = False
299
+ for feat in features:
300
+ geom = feat.get("geometry")
301
+ if not geom:
302
+ continue
303
+ shp = shape(geom)
304
+ if not shp.is_empty:
305
+ has_geom = True
306
+ x0, y0, x1, y1 = shp.bounds
307
+ if not (-180.1 <= x0 <= 180.1 and -180.1 <= x1 <= 180.1 and -90.1 <= y0 <= 90.1 and -90.1 <= y1 <= 90.1):
308
+ return False
309
+ return has_geom
310
+
311
+
312
+ def overlay_admin_boundaries(
313
+ ax,
314
+ features: list[dict[str, Any]],
315
+ target_crs: str,
316
+ label_field: str = "name",
317
+ extent_km: bool = False,
318
+ origin_xy: tuple[float, float] | None = None,
319
+ line_color: str = "#1E293B",
320
+ src_crs: str | None = None,
321
+ ) -> None:
322
+ """Draw administrative polygon outlines and CJK labels onto an existing Matplotlib Axes."""
323
+ configure_cjk_font()
324
+ norm_target = _normalize_crs_str(target_crs)
325
+ is_target_projected = norm_target.upper() not in ("EPSG:4326", "EPSG:4490")
326
+
327
+ if extent_km and origin_xy is None:
328
+ origin_xy = (0.0, 0.0)
329
+
330
+ def _to_plot_xy(coords) -> tuple[list[float], list[float]]:
331
+ xs: list[float] = []
332
+ ys: list[float] = []
333
+ for pt in coords:
334
+ x, y = float(pt[0]), float(pt[1])
335
+ if extent_km and origin_xy is not None:
336
+ x = (x - origin_xy[0]) / 1000.0
337
+ y = (y - origin_xy[1]) / 1000.0
338
+ xs.append(x)
339
+ ys.append(y)
340
+ return xs, ys
341
+
342
+ xlim0, xlim1 = ax.get_xlim()
343
+ ylim0, ylim1 = ax.get_ylim()
344
+ x_lo, x_hi = min(xlim0, xlim1), max(xlim0, xlim1)
345
+ y_lo, y_hi = min(ylim0, ylim1), max(ylim0, ylim1)
346
+
347
+ if extent_km and origin_xy is not None:
348
+ vx0 = x_lo * 1000.0 + origin_xy[0]
349
+ vx1 = x_hi * 1000.0 + origin_xy[0]
350
+ vy0 = y_lo * 1000.0 + origin_xy[1]
351
+ vy1 = y_hi * 1000.0 + origin_xy[1]
352
+ else:
353
+ vx0, vx1, vy0, vy1 = x_lo, x_hi, y_lo, y_hi
354
+ viewport_poly = shapely_box(vx0, vy0, vx1, vy1)
355
+
356
+ if src_crs is not None:
357
+ auto_reproject = _normalize_crs_str(src_crs).upper() != norm_target.upper()
358
+ else:
359
+ auto_reproject = is_target_projected and _looks_geographic_lonlat(features)
360
+ # Disambiguate small local metric coordinates inside [-180..180] when axes viewport already frames them
361
+ if auto_reproject and not (x_lo == 0.0 and x_hi == 1.0 and y_lo == 0.0 and y_hi == 1.0):
362
+ raw_intersects = False
363
+ proj_intersects = False
364
+ for feat in features:
365
+ g = feat.get("geometry")
366
+ if not g:
367
+ continue
368
+ try:
369
+ raw_shp = _safe_make_valid(shape(g))
370
+ if not raw_shp.is_empty and raw_shp.intersects(viewport_poly):
371
+ raw_intersects = True
372
+ proj_shp = _safe_make_valid(shape(transform_geom("EPSG:4326", norm_target, g)))
373
+ if not proj_shp.is_empty and proj_shp.intersects(viewport_poly):
374
+ proj_intersects = True
375
+ except Exception:
376
+ continue
377
+ if raw_intersects and not proj_intersects:
378
+ auto_reproject = False
379
+
380
+ # Preserve current axis limits so overlay does not zoom out beyond the raster extent
381
+ saved_xlim = ax.get_xlim()
382
+ saved_ylim = ax.get_ylim()
383
+
384
+ for feat in features:
385
+ geom = feat.get("geometry")
386
+ if not geom:
387
+ continue
388
+ if auto_reproject:
389
+ reproj_src = _normalize_crs_str(src_crs) if src_crs else "EPSG:4326"
390
+ geom = transform_geom(reproj_src, norm_target, geom)
391
+
392
+ props = feat.get("properties") or {}
393
+ feat_meta = {k: v for k, v in feat.items() if k not in ("type", "geometry")}
394
+ hit = _scan_forbidden_tokens(feat_meta, "overlay.feature")
395
+ if hit:
396
+ raise ValueError(f"Rejected non-compliant boundary feature in overlay ({hit}).")
397
+
398
+ atomic_geoms = _flatten_geometries(geom)
399
+ poly_shapes = []
400
+
401
+ for sub in atomic_geoms:
402
+ gtype = sub.get("type", "")
403
+ coords = sub.get("coordinates", [])
404
+
405
+ if gtype == "Polygon":
406
+ for ring in coords:
407
+ xs, ys = _to_plot_xy(ring)
408
+ ax.plot(xs, ys, color=line_color, linestyle="--", linewidth=1.15, alpha=0.9, zorder=14)
409
+ poly_shapes.append(_safe_make_valid(shape(sub)))
410
+ elif gtype == "MultiPolygon":
411
+ for poly in coords:
412
+ for ring in poly:
413
+ xs, ys = _to_plot_xy(ring)
414
+ ax.plot(xs, ys, color=line_color, linestyle="--", linewidth=1.15, alpha=0.9, zorder=14)
415
+ poly_shapes.append(_safe_make_valid(shape(sub)))
416
+ elif gtype == "LineString":
417
+ xs, ys = _to_plot_xy(coords)
418
+ ax.plot(xs, ys, color=line_color, linestyle="-.", linewidth=1.0, alpha=0.85, zorder=14)
419
+ elif gtype == "MultiLineString":
420
+ for line in coords:
421
+ xs, ys = _to_plot_xy(line)
422
+ ax.plot(xs, ys, color=line_color, linestyle="-.", linewidth=1.0, alpha=0.85, zorder=14)
423
+
424
+ # Label placement inside current viewport
425
+ if poly_shapes:
426
+ label_val = props.get(label_field) or props.get("name") or props.get("NAME") or ""
427
+ label_text = str(label_val).strip()
428
+ if not label_text or "境界线" in label_text:
429
+ continue
430
+ best_clipped = None
431
+ best_area = 0.0
432
+ for shp in poly_shapes:
433
+ if shp.is_empty:
434
+ continue
435
+ try:
436
+ clipped = shp.intersection(viewport_poly)
437
+ except Exception:
438
+ try:
439
+ clipped = shp.buffer(0).intersection(viewport_poly)
440
+ except Exception:
441
+ continue
442
+ if not clipped.is_empty and clipped.area > best_area:
443
+ best_area = float(clipped.area)
444
+ best_clipped = clipped
445
+ if best_clipped is None or best_area <= 0.0:
446
+ continue
447
+ rep_pt = best_clipped.representative_point()
448
+ px, py = float(rep_pt.x), float(rep_pt.y)
449
+ if extent_km and origin_xy is not None:
450
+ px = (px - origin_xy[0]) / 1000.0
451
+ py = (py - origin_xy[1]) / 1000.0
452
+ if x_lo <= px <= x_hi and y_lo <= py <= y_hi:
453
+ ax.text(
454
+ px,
455
+ py,
456
+ label_text,
457
+ ha="center",
458
+ va="center",
459
+ fontsize=8.5,
460
+ fontweight="bold",
461
+ color="#111111",
462
+ bbox=dict(boxstyle="round,pad=0.18", fc="#FFFFFF", ec="#737373", lw=0.5, alpha=0.84),
463
+ zorder=16,
464
+ )
465
+
466
+ ax.set_xlim(saved_xlim)
467
+ ax.set_ylim(saved_ylim)
468
+
469
+
470
+ def draw_china_locator_inset(
471
+ fig,
472
+ study_bbox_lonlat: tuple[float, float, float, float],
473
+ china_geojson: str | Path | None = None,
474
+ gs_code: str = "GS(2024)0650号",
475
+ mode: str = "color_slide",
476
+ rect: tuple[float, float, float, float] | list[float] | None = None,
477
+ ):
478
+ """Render an MNR GS-compliant China locator inset highlighting the study bounding box."""
479
+ configure_cjk_font()
480
+
481
+ resolved_path: Path | None = None
482
+ if china_geojson is not None:
483
+ resolved_path = Path(china_geojson)
484
+ else:
485
+ basemap_dir = Path(__file__).resolve().parents[2] / "data" / "standard_basemaps"
486
+ for candidate in (
487
+ "china_provinces_tianditu.geojson",
488
+ "cn_provinces_datav.geojson",
489
+ "china_standard.geojson",
490
+ ):
491
+ cand_path = basemap_dir / candidate
492
+ if cand_path.exists():
493
+ resolved_path = cand_path
494
+ break
495
+
496
+ basemap_data = None
497
+ if resolved_path is not None:
498
+ # Enforces strict forbidden-source rejection via load_standard_basemap
499
+ basemap_data = load_standard_basemap(resolved_path, target_crs="EPSG:4326")
500
+
501
+ is_mono = mode == "exam_mono"
502
+ bg_col = "#FFFFFF" if is_mono else "#F8FAFC"
503
+ spine_col = "#222222" if is_mono else "#475569"
504
+ fill_col = "#E5E5E5" if is_mono else "#E2E8F0"
505
+ edge_col = "#555555" if is_mono else "#64748B"
506
+ line_col = "#333333" if is_mono else "#475569"
507
+ hi_col = "#111111" if is_mono else "#DC2626"
508
+ txt_col = "#111111" if is_mono else "#B91C1C"
509
+ title_col = "#111111" if is_mono else "#1E293B"
510
+
511
+ inset_rect = list(rect) if rect is not None else [0.825, 0.77, 0.155, 0.175]
512
+ ax_in = fig.add_axes(inset_rect, zorder=30)
513
+ ax_in.set_facecolor(bg_col)
514
+ for spine in ax_in.spines.values():
515
+ spine.set_edgecolor(spine_col)
516
+ spine.set_linewidth(0.8)
517
+
518
+ if basemap_data is not None:
519
+ for feat in basemap_data["features"]:
520
+ for sub in _flatten_geometries(feat.get("geometry")):
521
+ gtype = sub.get("type", "")
522
+ coords = sub.get("coordinates", [])
523
+ if gtype == "Polygon":
524
+ pth = _polygon_coords_to_path(coords)
525
+ if pth is not None:
526
+ ax_in.add_patch(PathPatch(pth, facecolor=fill_col, edgecolor=edge_col, linewidth=0.35, zorder=2))
527
+ elif gtype == "MultiPolygon":
528
+ for poly in coords:
529
+ pth = _polygon_coords_to_path(poly)
530
+ if pth is not None:
531
+ ax_in.add_patch(PathPatch(pth, facecolor=fill_col, edgecolor=edge_col, linewidth=0.35, zorder=2))
532
+ elif gtype == "LineString":
533
+ xs = [pt[0] for pt in coords]
534
+ ys = [pt[1] for pt in coords]
535
+ ax_in.plot(xs, ys, color=line_col, linestyle="--", linewidth=0.55, zorder=3)
536
+ elif gtype == "MultiLineString":
537
+ for line in coords:
538
+ xs = [pt[0] for pt in line]
539
+ ys = [pt[1] for pt in line]
540
+ ax_in.plot(xs, ys, color=line_col, linestyle="--", linewidth=0.55, zorder=3)
541
+ else:
542
+ # Clean coordinate frame when no national vector file is supplied; never falls back to unapproved sources
543
+ ax_in.grid(True, linestyle=":", linewidth=0.4, color="#CCCCCC" if is_mono else "#CBD5E1")
544
+
545
+ minx, miny, maxx, maxy = [float(v) for v in study_bbox_lonlat]
546
+ cx = 0.5 * (minx + maxx)
547
+ cy = 0.5 * (miny + maxy)
548
+ w = max(maxx - minx, 1.2)
549
+ h = max(maxy - miny, 1.0)
550
+ ax_in.add_patch(
551
+ Rectangle(
552
+ (cx - w / 2.0, cy - h / 2.0),
553
+ w,
554
+ h,
555
+ facecolor="none",
556
+ edgecolor=hi_col,
557
+ linewidth=1.1,
558
+ zorder=8,
559
+ )
560
+ )
561
+ ax_in.scatter([cx], [cy], s=18, color=hi_col, zorder=9)
562
+ ax_in.text(
563
+ min(cx + 2.2, 127.0),
564
+ min(cy + 1.5, 49.0),
565
+ "研究区",
566
+ fontsize=6.5,
567
+ fontweight="bold",
568
+ color=txt_col,
569
+ zorder=10,
570
+ )
571
+
572
+ ax_in.set_xlim(72.0, 136.5)
573
+ ax_in.set_ylim(2.5, 54.5)
574
+ ax_in.set_xticks([])
575
+ ax_in.set_yticks([])
576
+ ax_in.set_title(f"中国区位 ({gs_code})", fontsize=6.8, color=title_col, pad=3.0)
577
+ return ax_in