-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit_map_data.py
More file actions
3409 lines (3081 loc) · 126 KB
/
Copy pathinit_map_data.py
File metadata and controls
3409 lines (3081 loc) · 126 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Initialize and prepare NUTS-3 map data for Scenario Forge."""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import os
import re
import sys
import subprocess
import shutil
import tempfile
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Iterable
try:
from importlib import util as importlib_util
except Exception: # pragma: no cover - fallback if importlib is shadowed
import pkgutil
def find_spec(name: str):
return pkgutil.find_loader(name)
else:
def find_spec(name: str):
return importlib_util.find_spec(name)
def require_packages(packages: Iterable[str]) -> None:
missing = []
for name in packages:
if find_spec(name) is None:
missing.append(name)
if not missing:
return
missing_list = ", ".join(sorted(missing))
raise SystemExit(
"Missing required Python packages. Install them before running init_map_data.py: "
f"{missing_list}"
)
def _peek_requested_mode(argv: list[str]) -> str:
for index, arg in enumerate(argv):
if arg == "--mode" and index + 1 < len(argv):
return str(argv[index + 1]).strip().lower()
if arg.startswith("--mode="):
return str(arg.split("=", 1)[1]).strip().lower()
return "all"
def _read_json_strict_light(path: Path) -> object:
return json.loads(path.read_text(encoding="utf-8"))
def _read_json_optional_light(path: Path | None, *, default: object = None) -> object:
if path is None or not path.exists():
return default
try:
return _read_json_strict_light(path)
except (OSError, ValueError, json.JSONDecodeError):
return default
def _write_json_atomic_light(
path: Path,
payload: object,
*,
ensure_ascii: bool = False,
indent: int | None = 2,
separators: tuple[str, str] | None = None,
allow_nan: bool = True,
trailing_newline: bool = False,
) -> None:
text = json.dumps(
payload,
ensure_ascii=ensure_ascii,
indent=indent,
separators=separators,
allow_nan=allow_nan,
)
if trailing_newline:
text += "\n"
path.parent.mkdir(parents=True, exist_ok=True)
fd, temp_name = tempfile.mkstemp(
dir=path.parent,
prefix=f".{path.name}.",
suffix=".tmp",
text=True,
)
temp_path = Path(temp_name)
try:
with os.fdopen(fd, "w", encoding="utf-8", newline="") as handle:
handle.write(text)
temp_path.replace(path)
except Exception:
temp_path.unlink(missing_ok=True)
raise
REQUESTED_MODE = _peek_requested_mode(sys.argv[1:])
if REQUESTED_MODE != "palettes":
require_packages([
"contourpy",
"geopandas",
"matplotlib",
"mapclassify",
"rasterio",
"requests",
"shapely",
"topojson",
])
import geopandas as gpd
import pandas as pd
import requests
from shapely.geometry import Polygon, box
from shapely.ops import unary_union
else: # pragma: no cover - palettes mode does not touch GIS stack
gpd = None
pd = None
requests = None
Polygon = None
box = None
unary_union = None
from map_builder import (
base_stage,
build_orchestrator,
config as cfg,
detail_topology_stage,
hierarchy_locale_stage,
primary_topology_stage,
runtime_political_topology_stage,
validation_schema,
)
from map_builder.contracts import DATA_ARTIFACT_SPECS_BY_PATH
from map_builder.runtime_asset_registry import load_runtime_asset_registry
if REQUESTED_MODE != "palettes":
from map_builder.cities import (
assign_urban_country_owners,
assign_stable_urban_area_ids,
build_city_aliases_payload,
build_world_cities,
emit_default_scenario_city_assets,
)
from map_builder.geo.local_canonicalization import (
LOCAL_CANONICAL_COUNTRY_CODES,
collect_topology_country_metrics,
evaluate_country_gate_metrics,
)
from map_builder.geo.topology import build_topology, _repair_geometry, _extract_country_code_from_id
from map_builder.geo.utils import (
clip_to_map_bounds,
pick_column,
smart_island_cull,
)
from map_builder.io.fetch import fetch_ne_zip, fetch_or_load_geojson
from map_builder.io.readers import (
load_physical,
load_rivers,
load_urban,
read_json_optional,
read_json_strict,
)
from map_builder.io.writers import write_json_atomic
from map_builder.processors.admin1 import build_extension_admin1, extract_country_code
from map_builder.processors.china import apply_china_replacement
from map_builder.processors.config_subdivisions import (
apply_config_subdivisions as _processor_apply_config_subdivisions,
load_subdivision_admin1_context as _processor_load_subdivision_admin1_context,
)
from map_builder.processors.detail_shell_coverage import (
DEFAULT_SHELL_COVERAGE_SPECS,
SHELL_COVERAGE_MIN_AREA_KM2,
collect_shell_coverage_gaps,
)
from map_builder.processors.denmark_border_detail import apply_denmark_border_detail
from map_builder.processors.france import apply_holistic_replacements
from map_builder.processors.north_america import apply_north_america_replacement
from map_builder.processors.physical_context import build_and_save_physical_context_layers
from map_builder.processors.poland import apply_poland_replacement
from map_builder.processors.russia_ukraine import apply_russia_ukraine_replacement
from map_builder.processors.south_asia import apply_south_asia_replacement
from map_builder.processors.special_zones import build_special_zones
from map_builder.outputs.save import save_outputs
else: # pragma: no cover - palettes mode avoids GIS/runtime build imports
assign_urban_country_owners = None
assign_stable_urban_area_ids = None
build_city_aliases_payload = None
build_world_cities = None
emit_default_scenario_city_assets = None
build_topology = None
clip_to_map_bounds = None
pick_column = None
smart_island_cull = None
fetch_ne_zip = None
fetch_or_load_geojson = None
load_physical = None
load_rivers = None
load_urban = None
build_extension_admin1 = None
extract_country_code = None
apply_china_replacement = None
_processor_apply_config_subdivisions = None
_processor_load_subdivision_admin1_context = None
DEFAULT_SHELL_COVERAGE_SPECS = {}
SHELL_COVERAGE_MIN_AREA_KM2 = 1.0
collect_shell_coverage_gaps = None
apply_denmark_border_detail = None
apply_holistic_replacements = None
apply_north_america_replacement = None
build_and_save_physical_context_layers = None
apply_poland_replacement = None
apply_russia_ukraine_replacement = None
apply_south_asia_replacement = None
build_special_zones = None
save_outputs = None
read_json_optional = _read_json_optional_light
read_json_strict = _read_json_strict_light
write_json_atomic = _write_json_atomic_light
LOCAL_CANONICAL_COUNTRY_CODES = ()
collect_topology_country_metrics = None
evaluate_country_gate_metrics = None
PROJECT_ROOT = Path(__file__).resolve().parent
D3_VENDOR_PATH = PROJECT_ROOT / 'vendor' / 'd3.v7.min.js'
TOPOJSON_VENDOR_PATH = PROJECT_ROOT / 'vendor' / 'topojson-client.min.js'
BUILD_STAGE_CACHE_FILENAME = base_stage.BUILD_STAGE_CACHE_FILENAME
MODERN_CITY_LIGHTS_ASSET_PATH = PROJECT_ROOT / "js" / "core" / "city_lights_modern_asset.js"
HISTORICAL_1930_CITY_LIGHTS_ASSET_PATH = PROJECT_ROOT / "js" / "core" / "city_lights_historical_1930_asset.js"
GLOBAL_OCEAN_MIN_BBOX_WIDTH = 220.0
GLOBAL_OCEAN_MIN_BBOX_HEIGHT = 90.0
ALLOWED_SENTINEL_FEATURE_IDS = {
"GAZ+00?",
"WEB+00?",
"RUS+99?",
"CO_ADM1_COL+99?",
"VE_ADM1_VEN+99?",
}
DETAIL_OVERLAY_WARN_THRESHOLD = 0.90
ALLOWED_DETAIL_OVERLAY_SUPPORT_TIERS = {
"GB": {"nuts1_basic"},
"GR": {"adm1_basic"},
}
MAJOR_MARINE_WATER_NAMES = {
"Arctic Ocean",
"SOUTHERN OCEAN",
"North Atlantic Ocean",
"South Atlantic Ocean",
"North Pacific Ocean",
"South Pacific Ocean",
"INDIAN OCEAN",
"Black Sea",
"Philippine Sea",
"Tasman Sea",
"Bay of Bengal",
"South China Sea",
"Arabian Sea",
"Beaufort Sea",
"Caribbean Sea",
"Gulf of Mexico",
"Labrador Sea",
"Hudson Bay",
"Caspian Sea",
"Baffin Bay",
"Gulf of Alaska",
"Red Sea",
"Ross Sea",
"Weddell Sea",
"Persian Gulf",
"Celebes Sea",
"Sulu Sea",
"Norwegian Sea",
"Greenland Sea",
"Banda Sea",
"Bay of Biscay",
"Mozambique Channel",
"Gulf of Guinea",
"Scotia Sea",
"Baltic Sea",
"Barents Sea",
"North Sea",
"Irish Sea",
"Java Sea",
"Andaman Sea",
"Yellow Sea",
"East China Sea",
"Sea of Okhotsk",
"Gulf of Aden",
"Gulf of Oman",
"Great Australian Bight",
"Gulf of Carpentaria",
"Sea of Azov",
"Sea of Marmara",
"Salish Sea",
}
MEDITERRANEAN_COMPONENT_NAMES = {
"Mediterranean Sea",
"Alboran Sea",
"Tyrrhenian Sea",
"Ligurian Sea",
"Adriatic Sea",
"Ionian Sea",
"Aegean Sea",
"Gulf of Sidra",
"Strait of Gibraltar",
"Dardanelles",
"Sea of Marmara",
"Gulf of Suez",
}
SEEDED_LAKE_REGION_SPECS = [
{
"id": "lake_superior",
"name": "Lake Superior",
"label": "Superior",
"match_names": ["Lake Superior"],
"water_type": "lake",
"region_group": "great_lakes",
},
{
"id": "lake_michigan",
"name": "Lake Michigan",
"label": "Michigan",
"match_names": ["Lake Michigan"],
"water_type": "lake",
"region_group": "great_lakes",
},
{
"id": "lake_huron",
"name": "Lake Huron",
"label": "Huron",
"match_names": ["Lake Huron"],
"water_type": "lake",
"region_group": "great_lakes",
},
{
"id": "lake_erie",
"name": "Lake Erie",
"label": "Erie",
"match_names": ["Lake Erie"],
"water_type": "lake",
"region_group": "great_lakes",
},
{
"id": "lake_ontario",
"name": "Lake Ontario",
"label": "Ontario",
"match_names": ["Lake Ontario"],
"water_type": "lake",
"region_group": "great_lakes",
},
{
"id": "lake_baikal",
"name": "Lake Baikal",
"label": "Baikal",
"match_names": ["Lake Baikal"],
"water_type": "lake",
"region_group": "eurasia_lakes",
},
{
"id": "caspian_sea",
"name": "Caspian Sea",
"label": "Caspian",
"match_names": ["Caspian Sea"],
"water_type": "inland_sea",
"region_group": "eurasia_lakes",
"source_layer": "marine",
},
{
"id": "aral_sea",
"name": "Aral Sea",
"label": "Aral Sea",
"match_names": ["North Aral Sea", "South Aral Sea"],
"water_type": "inland_sea",
"region_group": "eurasia_lakes",
},
{
"id": "lake_victoria",
"name": "Lake Victoria",
"label": "Victoria",
"match_names": ["Lake Victoria"],
"water_type": "lake",
"region_group": "african_great_lakes",
},
{
"id": "lake_tanganyika",
"name": "Lake Tanganyika",
"label": "Tanganyika",
"match_names": ["Lake Tanganyika"],
"water_type": "lake",
"region_group": "african_great_lakes",
},
{
"id": "lake_malawi_nyasa",
"name": "Lake Malawi / Nyasa",
"label": "Malawi / Nyasa",
"match_names": ["Lake Malawi"],
"water_type": "lake",
"region_group": "african_great_lakes",
},
{
"id": "lake_ladoga",
"name": "Lake Ladoga",
"label": "Ladoga",
"match_names": ["Lake Ladoga"],
"water_type": "lake",
"region_group": "eurasia_lakes",
},
{
"id": "lake_onega",
"name": "Lake Onega",
"label": "Onega",
"match_names": ["Lake Onega"],
"water_type": "lake",
"region_group": "eurasia_lakes",
},
{
"id": "lake_balkhash",
"name": "Lake Balkhash",
"label": "Balkhash",
"match_names": ["Lake Balkhash"],
"water_type": "lake",
"region_group": "eurasia_lakes",
},
{
"id": "lake_titicaca",
"name": "Lake Titicaca",
"label": "Titicaca",
"match_names": ["Lago Titicaca", "Lake Titicaca"],
"water_type": "lake",
"region_group": "andes_lakes",
},
]
MEDITERRANEAN_REGION_SPECS = [
{
"id": "med_gibraltar",
"name": "Gibraltar Chokepoint",
"label": "Gibraltar",
"water_type": "strait",
"bbox": (-6.25, 35.0, -4.75, 36.4),
"is_chokepoint": True,
},
{
"id": "med_bosporus_dardanelles",
"name": "Bosporus-Dardanelles Chokepoint",
"label": "Bosporus-Dardanelles",
"water_type": "chokepoint",
"bbox": (25.4, 39.7, 30.4, 41.5),
"is_chokepoint": True,
},
{
"id": "med_suez_approach",
"name": "Suez Approach",
"label": "Suez",
"water_type": "chokepoint",
"bbox": (29.6, 30.2, 34.9, 32.8),
"is_chokepoint": True,
},
{
"id": "med_adriatic",
"name": "Adriatic Basin",
"label": "Adriatic",
"water_type": "sea",
"bbox": (12.0, 39.0, 20.7, 45.9),
"is_chokepoint": False,
},
{
"id": "med_aegean",
"name": "Aegean Sea",
"label": "Aegean",
"water_type": "sea",
"bbox": (22.0, 34.5, 28.8, 41.4),
"is_chokepoint": False,
},
{
"id": "med_ionian",
"name": "Ionian Sea",
"label": "Ionian",
"water_type": "sea",
"bbox": (13.5, 34.0, 22.4, 40.4),
"is_chokepoint": False,
},
{
"id": "med_tyrr_lig",
"name": "Tyrrhenian-Ligurian Sea",
"label": "Tyrrhenian-Ligurian",
"water_type": "sea",
"bbox": (6.0, 37.4, 16.6, 45.6),
"is_chokepoint": False,
},
{
"id": "med_levantine",
"name": "Levantine Basin",
"label": "Levantine",
"water_type": "sea",
"bbox": (25.0, 30.4, 37.6, 36.9),
"is_chokepoint": False,
},
{
"id": "med_central_corridor",
"name": "Central Mediterranean Corridor",
"label": "Central Mediterranean",
"water_type": "sea",
"bbox": (8.0, 32.4, 18.1, 39.6),
"is_chokepoint": False,
},
]
ANTARCTIC_POLAR_CRS = "EPSG:3031"
ANTARCTIC_PARTITION_SCHEME = "claim_meridians_v1"
ANTARCTIC_VALIDATION_TOLERANCE_KM2 = 5.0
ANTARCTIC_POLE_CAP_RADIUS_M = 1_000.0
ANTARCTIC_SECTOR_SPECS = [
{
"id": "AQ_QML",
"name": "20W-45E Sector",
"sector_start_lon": -20.0,
"sector_end_lon": 45.0,
"claimants": ["NO"],
},
{
"id": "AQ_AAT_WEST",
"name": "45E-136E Sector",
"sector_start_lon": 45.0,
"sector_end_lon": 136.0,
"claimants": ["AU"],
},
{
"id": "AQ_ADELIE",
"name": "136E-142E Sector",
"sector_start_lon": 136.0,
"sector_end_lon": 142.0,
"claimants": ["FR"],
},
{
"id": "AQ_AAT_EAST",
"name": "142E-160E Sector",
"sector_start_lon": 142.0,
"sector_end_lon": 160.0,
"claimants": ["AU"],
},
{
"id": "AQ_ROSS",
"name": "160E-150W Sector",
"sector_start_lon": 160.0,
"sector_end_lon": -150.0,
"claimants": ["NZ"],
},
{
"id": "AQ_MARIE_BYRD",
"name": "150W-90W Sector",
"sector_start_lon": -150.0,
"sector_end_lon": -90.0,
"claimants": [],
"claim_status": "unclaimed",
},
{
"id": "AQ_PEN_WEST",
"name": "Peninsula 90W-80W Sector",
"sector_start_lon": -90.0,
"sector_end_lon": -80.0,
"claimants": ["CL"],
},
{
"id": "AQ_PEN_OVERLAP_WEST",
"name": "Peninsula 80W-74W Overlap Sector",
"sector_start_lon": -80.0,
"sector_end_lon": -74.0,
"claimants": ["GB", "CL"],
},
{
"id": "AQ_PEN_OVERLAP_CORE",
"name": "Peninsula 74W-53W Overlap Sector",
"sector_start_lon": -74.0,
"sector_end_lon": -53.0,
"claimants": ["GB", "AR", "CL"],
},
{
"id": "AQ_PEN_OVERLAP_EAST",
"name": "Peninsula 53W-25W Overlap Sector",
"sector_start_lon": -53.0,
"sector_end_lon": -25.0,
"claimants": ["GB", "AR"],
},
{
"id": "AQ_PEN_EAST",
"name": "Peninsula 25W-20W Sector",
"sector_start_lon": -25.0,
"sector_end_lon": -20.0,
"claimants": ["GB"],
},
]
def _normalize_antarctic_claim_status(claimants: list[str]) -> str:
if not claimants:
return "unclaimed"
if len(claimants) > 1:
return "overlapping_claims"
return "claimed"
def _to_unwrapped_east_longitude(lon: float) -> float:
east_lon = float(lon)
if east_lon < 0:
east_lon += 360.0
return east_lon
def _compute_antarctic_sector_radius(projected_geom) -> float:
minx, miny, maxx, maxy = projected_geom.bounds
return max(4_500_000.0, max(abs(minx), abs(miny), abs(maxx), abs(maxy)) * 1.2)
def _build_antarctic_sector_wedge(
sector_start_lon: float,
sector_end_lon: float,
radius_m: float,
) -> Polygon:
start_east = _to_unwrapped_east_longitude(sector_start_lon)
end_east = _to_unwrapped_east_longitude(sector_end_lon)
if end_east <= start_east:
end_east += 360.0
start_angle = math.radians(90.0 - start_east)
end_angle = math.radians(90.0 - end_east)
step_count = max(16, int(abs(end_angle - start_angle) / math.radians(1.0)))
inner_radius_m = max(1.0, float(ANTARCTIC_POLE_CAP_RADIUS_M))
points: list[tuple[float, float]] = []
for step_index in range(step_count + 1):
angle = start_angle + ((end_angle - start_angle) * step_index / step_count)
points.append((radius_m * math.cos(angle), radius_m * math.sin(angle)))
# Avoid an exact South Pole apex in WGS84 output. A tiny inner polar arc keeps
# the sector partition valid while preventing every sector from collapsing to
# the same 0° / -90° vertex after reprojection.
for step_index in range(step_count, -1, -1):
angle = start_angle + ((end_angle - start_angle) * step_index / step_count)
points.append((inner_radius_m * math.cos(angle), inner_radius_m * math.sin(angle)))
return Polygon(points)
def _validate_antarctic_sector_partition(
antarctica_proj,
sector_geoms_proj: list,
) -> None:
if not sector_geoms_proj:
raise SystemExit("[Antarctica] Sectorization failed: no sector geometries were produced.")
union_geom = _repair_geometry(unary_union(sector_geoms_proj))
if union_geom is None or union_geom.is_empty:
raise SystemExit("[Antarctica] Sectorization failed: union geometry is empty.")
missing_geom = _repair_geometry(antarctica_proj.difference(union_geom))
extra_geom = _repair_geometry(union_geom.difference(antarctica_proj))
missing_area_km2 = 0.0 if missing_geom is None or missing_geom.is_empty else missing_geom.area / 1_000_000.0
extra_area_km2 = 0.0 if extra_geom is None or extra_geom.is_empty else extra_geom.area / 1_000_000.0
if (
missing_area_km2 > ANTARCTIC_VALIDATION_TOLERANCE_KM2
or extra_area_km2 > ANTARCTIC_VALIDATION_TOLERANCE_KM2
):
raise SystemExit(
"[Antarctica] Sectorization coverage check failed: "
f"missing={missing_area_km2:.3f} km^2, extra={extra_area_km2:.3f} km^2"
)
print(
"[Antarctica] Sector coverage validated: "
f"missing={missing_area_km2:.3f} km^2, extra={extra_area_km2:.3f} km^2."
)
def build_antarctic_sectors(gdf: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
if gdf is None or gdf.empty or "cntr_code" not in gdf.columns or "geometry" not in gdf.columns:
return gdf
normalized_codes = gdf["cntr_code"].fillna("").astype(str).str.strip().str.upper()
aq_rows = gdf.loc[normalized_codes == "AQ"].copy()
if aq_rows.empty:
return gdf
antarctica_ll = aq_rows.to_crs("EPSG:4326").copy()
antarctica_geom_ll = _repair_geometry(unary_union(antarctica_ll.geometry.tolist()))
if antarctica_geom_ll is None or antarctica_geom_ll.is_empty:
print("[Antarctica] AQ geometry is empty after union; keeping original feature.")
return gdf
antarctica_proj = gpd.GeoSeries([antarctica_geom_ll], crs="EPSG:4326").to_crs(ANTARCTIC_POLAR_CRS).iloc[0]
radius_m = _compute_antarctic_sector_radius(antarctica_proj)
sector_records: list[dict] = []
sector_geoms_proj: list = []
base_row = aq_rows.iloc[0].to_dict()
for spec in ANTARCTIC_SECTOR_SPECS:
wedge = _build_antarctic_sector_wedge(
sector_start_lon=float(spec["sector_start_lon"]),
sector_end_lon=float(spec["sector_end_lon"]),
radius_m=radius_m,
)
sector_geom_proj = _repair_geometry(antarctica_proj.intersection(wedge))
if sector_geom_proj is None or sector_geom_proj.is_empty:
raise SystemExit(f"[Antarctica] Sector {spec['id']} produced empty geometry.")
sector_geoms_proj.append(sector_geom_proj)
sector_geom_ll = gpd.GeoSeries([sector_geom_proj], crs=ANTARCTIC_POLAR_CRS).to_crs("EPSG:4326").iloc[0]
claimants = list(spec.get("claimants", []))
record = dict(base_row)
record.update(
{
"id": str(spec["id"]).strip(),
"name": f"Antarctica / {str(spec['name']).strip()}",
"cntr_code": "AQ",
"detail_tier": "antarctic_sector",
"claim_status": str(spec.get("claim_status") or _normalize_antarctic_claim_status(claimants)),
"claimants": claimants,
"partition_scheme": ANTARCTIC_PARTITION_SCHEME,
"sector_start_lon": float(spec["sector_start_lon"]),
"sector_end_lon": float(spec["sector_end_lon"]),
"geometry": sector_geom_ll,
}
)
sector_records.append(record)
_validate_antarctic_sector_partition(antarctica_proj, sector_geoms_proj)
sector_gdf = gpd.GeoDataFrame(sector_records, geometry="geometry", crs="EPSG:4326")
sector_gdf["geometry"] = sector_gdf.geometry.apply(_repair_geometry)
sector_gdf = sector_gdf[sector_gdf.geometry.notna() & ~sector_gdf.geometry.is_empty].copy()
if len(sector_gdf) != len(ANTARCTIC_SECTOR_SPECS):
raise SystemExit(
"[Antarctica] Sectorization output count mismatch: "
f"expected {len(ANTARCTIC_SECTOR_SPECS)}, got {len(sector_gdf)}"
)
base = gdf.loc[normalized_codes != "AQ"].copy()
combined = pd.concat([base, sector_gdf], ignore_index=True)
combined = gpd.GeoDataFrame(combined, geometry="geometry", crs="EPSG:4326")
print(
"[Antarctica] Replaced AQ shell with "
f"{len(sector_gdf)} claim-informed sectors ({ANTARCTIC_PARTITION_SCHEME})."
)
return combined
def _get_peak_memory_mb() -> float | None:
return base_stage.get_peak_memory_mb()
def _record_stage_timing(timings: dict[str, dict], stage_name: str, start_time: float, **extra: object) -> None:
base_stage.record_stage_timing(timings, stage_name, start_time, **extra)
def _write_timings_json(path: Path | None, timings: dict[str, dict]) -> None:
base_stage.write_timings_json(
path,
timings,
write_json_atomic_func=lambda target, payload: write_json_atomic(
target,
payload,
ensure_ascii=False,
indent=2,
),
)
def _candidate_topology_path(path: Path) -> Path:
return path.with_name(f"{path.stem}.candidate{path.suffix}")
def _previous_topology_path(path: Path) -> Path:
return path.with_name(f"{path.stem}.previous{path.suffix}")
def _candidate_topology_audit_path(path: Path) -> Path:
return path.with_suffix(path.suffix + ".candidate_audit.json")
def _candidate_topology_parameter_profile(stage_label: str) -> tuple[str, dict[str, object]]:
normalized = str(stage_label or "").strip().lower()
if "runtime" in normalized:
profile_id = "runtime_political"
quantization = getattr(cfg, "RUNTIME_POLITICAL_TOPOLOGY_QUANTIZATION", cfg.TOPOLOGY_QUANTIZATION)
elif "detail" in normalized:
profile_id = "detail_output"
quantization = getattr(cfg, "DETAIL_OUTPUT_TOPOLOGY_QUANTIZATION", cfg.TOPOLOGY_QUANTIZATION)
else:
profile_id = "default"
quantization = cfg.TOPOLOGY_QUANTIZATION
return profile_id, {
"quantization": quantization,
"presimplify": False,
"toposimplify": False,
"shared_coords": True,
}
def _sha256_file_or_empty(path: Path | None) -> str:
if path is None or not path.exists() or not path.is_file():
return ""
h = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def _safe_topology_summary(path: Path | None) -> dict[str, object]:
if path is None or not path.exists():
return {"exists": False}
try:
summary = dict(_topology_summary(path))
except Exception as exc: # keep audit writing best-effort and non-promoting
return {"exists": True, "summary_error": str(exc)}
summary["exists"] = True
summary["bytes"] = path.stat().st_size
summary["sha256"] = _sha256_file_or_empty(path)
return summary
def _safe_topology_transform(path: Path | None) -> dict[str, object]:
if path is None or not path.exists():
return {"scale": None, "translate": None}
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except Exception as exc:
return {"scale": None, "translate": None, "transform_error": str(exc)}
transform = payload.get("transform", {}) if isinstance(payload, dict) else {}
if not isinstance(transform, dict):
transform = {}
return {
"scale": transform.get("scale"),
"translate": transform.get("translate"),
}
def _candidate_topology_fallback_used(path: Path | None) -> bool:
transform = _safe_topology_transform(path)
return not bool(transform.get("scale") and transform.get("translate"))
def _write_candidate_topology_audit(
*,
stage_label: str,
candidate_path: Path,
output_path: Path,
result: str,
contract_problems: list[str] | None = None,
gate_problems: list[str] | None = None,
candidate_metrics: dict[str, dict[str, float | int]] | None = None,
baseline_metrics: dict[str, dict[str, float | int]] | None = None,
topology_parameters: dict[str, object] | None = None,
fallback_used: bool | None = None,
parameter_profile_id: str | None = None,
) -> None:
default_profile_id, default_parameters = _candidate_topology_parameter_profile(stage_label)
parameters = dict(default_parameters)
if topology_parameters:
parameters.update(topology_parameters)
payload = {
"version": 2,
"stage": stage_label,
"stage_label": stage_label,
"generated_at": datetime.now(timezone.utc).isoformat(),
"result": result,
"candidate_path": str(candidate_path),
"output_path": str(output_path),
"previous_path": str(_previous_topology_path(output_path)),
"candidate_summary": _safe_topology_summary(candidate_path),
"baseline_summary": _safe_topology_summary(output_path),
"topology_parameters": parameters,
"topology_transform": _safe_topology_transform(candidate_path),
"fallback_used": _candidate_topology_fallback_used(candidate_path) if fallback_used is None else bool(fallback_used),
"parameter_profile_id": parameter_profile_id or default_profile_id,
"contract_problems": list(contract_problems or []),
"gate_problems": list(gate_problems or []),
"country_gate": {
"target_country_codes": list(LOCAL_CANONICAL_COUNTRY_CODES),
"candidate_metrics": candidate_metrics or {},
"baseline_metrics": baseline_metrics or {},
},
}
write_json_atomic(
_candidate_topology_audit_path(output_path),
payload,
ensure_ascii=False,
indent=2,
)
def _summarize_country_gate_metrics(
stage_label: str,
metrics: dict[str, dict[str, float | int]] | None,
) -> None:
if not metrics:
print(f"[{stage_label}] No country gate metrics available.")
return
for country_code in LOCAL_CANONICAL_COUNTRY_CODES:
row = metrics.get(country_code, {})
print(
f"[{stage_label}] {country_code}: "
f"features={int(row.get('feature_count', 0) or 0)}, "
f"gaps={int(row.get('fragment_count', 0) or 0)}, "
f"total_area_km2={float(row.get('total_area_km2', 0.0) or 0.0):.3f}, "
f"max_fragment_area_km2={float(row.get('max_fragment_area_km2', 0.0) or 0.0):.3f}, "
f"arc_shared_ratio={float(row.get('shared_arc_ratio', 0.0) or 0.0):.4f}"
)
def _validate_candidate_topology_contract(candidate_path: Path, *, label: str) -> list[str]:
problems: list[str] = []
if not candidate_path.exists():
return [f"{label}: candidate output missing ({candidate_path})"]
ids, duplicates, missing_names, illegal_ids = _extract_political_topology_ids(candidate_path)
if duplicates:
problems.append(f"{label}: duplicate ids={len(duplicates)}")
if illegal_ids:
problems.append(f"{label}: illegal sentinel ids={len(illegal_ids)}")
if missing_names:
problems.append(f"{label}: missing names={len(missing_names)}")
summary = _topology_summary(candidate_path)
if summary.get("political_geometries", 0) and not summary.get("has_computed_neighbors", False):
problems.append(f"{label}: missing computed_neighbors")
if int(summary.get("world_bounds_geometries", 0) or 0) > 0:
problems.append(f"{label}: world-bounds geometries={summary['world_bounds_geometries']}")
if not ids:
problems.append(f"{label}: zero political ids")
return problems
def _collect_country_gate_metrics(
topology_path: Path,
*,
primary_topology_path: Path,
) -> dict[str, dict[str, float | int]] | None:
if collect_topology_country_metrics is None or not topology_path.exists() or not primary_topology_path.exists():
return None
primary_shell = _load_political_gdf_from_topology(primary_topology_path)
allowed_area = _load_topology_object_gdf_from_topology(primary_topology_path, "land")
return collect_topology_country_metrics(
topology_path,
shell_gdf=primary_shell,
allowed_area_gdf=allowed_area,
target_country_codes=LOCAL_CANONICAL_COUNTRY_CODES,
)
def _promote_candidate_topology_if_safe(
*,
stage_label: str,
primary_topology_path: Path,
candidate_path: Path,
output_path: Path,
detail_topology_path: Path | None = None,
override_path: Path | None = None,
) -> None:
if collect_topology_country_metrics is None:
gate_problems = ["country gate metrics collector unavailable"]
_write_candidate_topology_audit(
stage_label=stage_label,
candidate_path=candidate_path,
output_path=output_path,
result="failed_country_gate",
gate_problems=gate_problems,
)
raise SystemExit(f"{stage_label}: candidate gate failed: {'; '.join(gate_problems)}")
contract_problems = _validate_candidate_topology_contract(candidate_path, label=stage_label)
if contract_problems:
_write_candidate_topology_audit(
stage_label=stage_label,
candidate_path=candidate_path,
output_path=output_path,
result="failed_contract",
contract_problems=contract_problems,
)
raise SystemExit(f"{stage_label}: candidate contract failed: {'; '.join(contract_problems)}")
if detail_topology_path is not None:
try:
from tools.build_runtime_political_topology import _compose_political_features, _load_topology
override_collection = _read_json(override_path) if override_path is not None and override_path.exists() else None
expected_runtime = _compose_political_features(
primary_topology=_load_topology(primary_topology_path),
detail_topology=_load_topology(detail_topology_path) if detail_topology_path.exists() else None,
override_collection=override_collection,
canonicalize_countries=LOCAL_CANONICAL_COUNTRY_CODES,
)
expected_ids = {
str(feature_id).strip()