#!/usr/bin/env python3 """Build the China POV Earth boundary PMTiles artifact. Layers (all lines, Web Mercator MVT tiles): - ``coastline`` OSM coastline (osmdata.openstreetmap.de, ODbL) - ``boundary_admin0`` shared land edges of the policy-applied admin-0 polygons - ``boundary_disputed_internal`` Natural Earth disputed lines outside China - ``boundary_admin1`` Natural Earth admin-1 lines (China POV filtered), z4+ - ``claim_line`` Natural Earth China POV nine-dash maritime line Coastal ends of admin-0 / admin-1 lines are trimmed or extended onto the OSM coastline so borders meet the shore that the satellite imagery shows. """ from __future__ import annotations import argparse import ctypes import datetime as dt import gc import hashlib import json import os import resource import shutil import subprocess import sys import tempfile import time from collections import Counter from pathlib import Path from typing import Any from shapely import STRtree from shapely.geometry import Point, shape from earth_boundary_geometry import ( CoastlineCountryAssigner, admin1_lines, build_geo_labels, china_clip_geometry, collect_coast_near, country_geometries, derive_land_borders, disputed_lines, free_endpoints, geojson_feature, hover_borders, hover_index, iter_shapefile_lines, resolve_coastline_shapefile, rounded_mapping, snap_coastal_ends, ) from earth_boundary_policy import apply_admin0_policy, load_policy, policy_digest ARTIFACT_PREFIX = "earth-boundaries" CLAIM_RULE_ID = "china-maritime-claim-line" MIN_CLAIM_DASHES = 9 HOVER_INDEX_TOLERANCE = 0.02 TIPPECANOE_DEFAULT_THREADS = "2" HOVER_BORDER_TOLERANCE = 0.002 ADMIN1_BORDER_CLEARANCE = 0.02 BORDER_LAYER_MAX_ZOOM = 6 ATTRIBUTION = ["© OpenStreetMap contributors (ODbL)", "Natural Earth (public domain)"] def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--admin0-source", type=Path, required=True) parser.add_argument("--coastline-source", type=Path, required=True) parser.add_argument("--disputed-source", type=Path, required=True) parser.add_argument("--claims-source", type=Path, required=True) parser.add_argument("--admin1-source", type=Path, required=True) parser.add_argument("--places-source", type=Path, default=None) parser.add_argument("--output-dir", type=Path, required=True) parser.add_argument("--build-input-hash", required=True) parser.add_argument("--pov-policy", type=Path, required=True) parser.add_argument("--pov-geometry", type=Path, required=True) parser.add_argument("--min-zoom", type=int, default=0) parser.add_argument("--max-zoom", type=int, default=10) parser.add_argument("--coastline-max-zoom", type=int, default=None) parser.add_argument("--simplification", type=float, default=4.0) parser.add_argument("--temp-dir", type=Path, default=None) return parser.parse_args() def log(message: str, **fields: Any) -> None: # Progress goes to stderr; stdout carries the final JSON result only. payload = {"event": message, **fields} print(json.dumps(payload, ensure_ascii=False, sort_keys=True), file=sys.stderr, flush=True) def current_rss_mb() -> float: try: pages = int(Path("/proc/self/statm").read_text().split()[1]) except (OSError, ValueError, IndexError): return 0.0 return round(pages * os.sysconf("SC_PAGE_SIZE") / 1024 / 1024, 1) def release_heap() -> None: """Return freed geometry memory to the OS before the tippecanoe child starts.""" try: ctypes.CDLL("libc.so.6").malloc_trim(0) except (OSError, AttributeError): pass def require_tool(name: str) -> str: path = shutil.which(name) if not path: raise RuntimeError(f"required external tool not found in PATH: {name}") return path def load_geojson(path: Path) -> dict[str, Any]: with path.open("r", encoding="utf-8") as f: payload = json.load(f) if payload.get("type") != "FeatureCollection": raise ValueError(f"{path} must be a GeoJSON FeatureCollection") return payload def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as f: for chunk in iter(lambda: f.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def write_json(path: Path, payload: Any, *, indent: int | None = None) -> None: tmp = path.with_suffix(path.suffix + ".tmp") with tmp.open("w", encoding="utf-8") as f: if indent: json.dump(payload, f, ensure_ascii=False, indent=indent) else: json.dump(payload, f, ensure_ascii=False, separators=(",", ":")) f.write("\n") tmp.replace(path) def claim_features(collection: dict[str, Any]) -> list[dict[str, Any]]: """Accept only the Natural Earth China POV dashed maritime line.""" features = [] for feature in collection.get("features") or []: props = feature.get("properties") or {} if not feature.get("geometry"): continue if "9 dash" not in str(props.get("COMMENT") or ""): continue if not str(props.get("FCLASS_CN") or "").startswith("International boundary"): continue features.append( { "type": "Feature", "geometry": shape(feature["geometry"]), "properties": {"name": "九段线", "name_en": "Nine-dash line"}, } ) return features def admin1_coastal_endpoints( features: list[dict[str, Any]], borders: list[dict[str, Any]] ) -> set[tuple[float, float]]: """Admin-1 free ends that do not sit on a national border are coastal.""" free = free_endpoints(features) if not borders: return free border_tree = STRtree([feature["geometry"] for feature in borders]) coastal = set() for lon, lat in free: point = Point(lon, lat) nearby = border_tree.query(point.buffer(ADMIN1_BORDER_CLEARANCE)) if not any( borders[int(i)]["geometry"].distance(point) <= ADMIN1_BORDER_CLEARANCE for i in nearby ): coastal.add((lon, lat)) return coastal def apply_claim_coverage(coverage: dict[str, Any], claims: list[dict[str, Any]]) -> None: applied = set(coverage.get("appliedRuleIds") or []) unresolved = set(coverage.get("unresolvedRuleIds") or []) reasons = dict(coverage.get("unresolvedReasons") or {}) if len(claims) >= MIN_CLAIM_DASHES: applied.add(CLAIM_RULE_ID) unresolved.discard(CLAIM_RULE_ID) reasons.pop(CLAIM_RULE_ID, None) coverage["appliedRuleIds"] = sorted(applied) coverage["unresolvedRuleIds"] = sorted(unresolved) coverage["unresolvedReasons"] = reasons coverage["coverage"] = "partial" if unresolved else "complete" coverage["claimLine"] = { "source": "Natural Earth ne_10m_admin_0_boundary_lines_maritime_indicator_chn", "featureCount": len(claims), } def remove_stale_artifacts(output_dir: Path, keep: set[str]) -> list[str]: removed = [] for path in output_dir.iterdir(): if not path.is_file() or path.name in keep or path.name == "manifest.json": continue if path.name.startswith((ARTIFACT_PREFIX, "hover-index", "hover-borders", "geo-labels")): path.unlink() removed.append(path.name) return removed def main() -> None: args = parse_args() started = time.monotonic() tippecanoe = require_tool("tippecanoe") coast_max_zoom = args.coastline_max_zoom if args.coastline_max_zoom is not None else args.max_zoom policy = load_policy(args.pov_policy) geometry_package = json.loads(args.pov_geometry.read_text(encoding="utf-8")) admin0, coverage = apply_admin0_policy( load_geojson(args.admin0_source), policy, geometry_package=geometry_package ) countries = country_geometries(admin0) coast_assigner = CoastlineCountryAssigner(countries) china_clip = china_clip_geometry(countries) border_max_zoom = min(BORDER_LAYER_MAX_ZOOM, args.max_zoom) log("policy_applied", countries=len(countries)) borders = derive_land_borders(countries) admin1 = admin1_lines(load_geojson(args.admin1_source), china_clip) disputed = disputed_lines(load_geojson(args.disputed_source), china_clip) claims = claim_features(load_geojson(args.claims_source)) if len(claims) < MIN_CLAIM_DASHES: raise RuntimeError( f"China POV claim line source must contain {MIN_CLAIM_DASHES} audited dashes, found {len(claims)}" ) apply_claim_coverage(coverage, claims) border_free = free_endpoints(borders) admin1_free = admin1_coastal_endpoints(admin1, borders) log( "lines_derived", borders=len(borders), admin1=len(admin1), disputed=len(disputed), claims=len(claims), border_coastal_ends=len(border_free), admin1_coastal_ends=len(admin1_free), ) args.output_dir.mkdir(parents=True, exist_ok=True) temp_parent = args.temp_dir or args.output_dir.parent temp_parent.mkdir(parents=True, exist_ok=True) asset_version = f"{args.build_input_hash[:12]}-{coverage['geometrySha256'][:12]}" pmtiles_name = f"{ARTIFACT_PREFIX}.{asset_version}.pmtiles" hover_name = f"hover-index.{asset_version}.json" hover_borders_name = f"hover-borders.{asset_version}.json" geo_labels_name = f"geo-labels.{asset_version}.json" geo_labels_payload: dict[str, Any] | None = None if args.places_source and args.places_source.is_file(): geo_labels_payload = build_geo_labels( load_geojson(args.places_source), policy=policy, china_clip=china_clip, ) log("geo_labels_built", **(geo_labels_payload.get("counts") or {})) with tempfile.TemporaryDirectory(prefix="planet-earth-boundaries-", dir=temp_parent) as tmp: tmp_dir = Path(tmp) coast_shp = resolve_coastline_shapefile(args.coastline_source, tmp_dir) if coast_shp is None: raise RuntimeError(f"coastline source has no lines.shp: {args.coastline_source}") ndjson_path = tmp_dir / "earth-boundaries.ndjson" endpoints = border_free | admin1_free coast_count = 0 coast_tagged = 0 with ndjson_path.open("w", encoding="utf-8") as out: near: list[Any] = [] def stream_coast(): nonlocal coast_count, coast_tagged for line in iter_shapefile_lines(coast_shp): for tagged_line, adm0_a3 in coast_assigner.assign(line): coast_count += 1 if adm0_a3: coast_tagged += 1 out.write(json.dumps( { "type": "Feature", "tippecanoe": {"layer": "coastline", "minzoom": args.min_zoom, "maxzoom": coast_max_zoom}, "properties": {"ADM0_A3": adm0_a3} if adm0_a3 else {}, "geometry": rounded_mapping(tagged_line, 7), }, separators=(",", ":"), )) out.write("\n") yield line near = collect_coast_near(stream_coast(), endpoints) log("coastline_streamed", features=coast_count, tagged=coast_tagged, near_endpoints=len(near)) snap_stats = { "boundary_admin0": dict(snap_coastal_ends(borders, near, border_free)), "boundary_admin1": dict(snap_coastal_ends(admin1, near, admin1_free)), } log("coastal_ends_snapped", **snap_stats) layer_counts: Counter[str] = Counter({"coastline": coast_count}) for layer, features, min_zoom in ( ("boundary_admin0", borders, args.min_zoom), ("boundary_disputed_internal", disputed, args.min_zoom), ("claim_line", claims, args.min_zoom), ): for feature in features: out.write( json.dumps( geojson_feature(feature, layer, min_zoom, border_max_zoom), ensure_ascii=False, separators=(",", ":"), ) ) out.write("\n") layer_counts[layer] += 1 for feature in admin1: out.write(json.dumps( geojson_feature(feature, "boundary_admin1", feature["properties"]["minzoom"], border_max_zoom), ensure_ascii=False, separators=(",", ":"), )) out.write("\n") layer_counts["boundary_admin1"] += 1 hover = hover_index(admin0, countries, HOVER_INDEX_TOLERANCE) hover_border_fc = hover_borders(borders, HOVER_BORDER_TOLERANCE) write_json(tmp_dir / hover_name, hover) write_json(tmp_dir / hover_borders_name, hover_border_fc) move_names = [pmtiles_name, hover_name, hover_borders_name] if geo_labels_payload is not None: write_json(tmp_dir / geo_labels_name, geo_labels_payload) move_names.append(geo_labels_name) # Release geometry before tippecanoe so the backend container keeps headroom. del near, borders, admin1, disputed, hover, hover_border_fc, countries, china_clip, coast_assigner gc.collect() release_heap() log("python_rss_before_tiles", rss_mb=current_rss_mb()) tmp_pmtiles = tmp_dir / pmtiles_name tippecanoe_started = time.monotonic() tippecanoe_env = { **os.environ, "TIPPECANOE_MAX_THREADS": os.environ.get("TIPPECANOE_MAX_THREADS", TIPPECANOE_DEFAULT_THREADS), } subprocess.run( [ tippecanoe, "--force", "--quiet", "--read-parallel", "--minimum-zoom", str(args.min_zoom), "--maximum-zoom", str(args.max_zoom), "--no-feature-limit", "--no-tile-size-limit", "--simplification", str(args.simplification), "--temporary-directory", str(tmp_dir), "--name", "Planet Earth boundaries (china-pov-v1)", "--attribution", " | ".join(ATTRIBUTION), "--output", str(tmp_pmtiles), str(ndjson_path), ], check=True, env=tippecanoe_env, ) tippecanoe_seconds = round(time.monotonic() - tippecanoe_started, 1) log("tiles_built", seconds=tippecanoe_seconds, bytes=tmp_pmtiles.stat().st_size) for name in move_names: shutil.move(str(tmp_dir / name), args.output_dir / name) pmtiles_path = args.output_dir / pmtiles_name keep_names = {pmtiles_name, hover_name, hover_borders_name} geo_labels_manifest: dict[str, Any] = {} if geo_labels_payload is not None and (args.output_dir / geo_labels_name).is_file(): keep_names.add(geo_labels_name) geo_labels_manifest = { "geoLabels": geo_labels_name, "geoLabelsSha256": sha256_file(args.output_dir / geo_labels_name), "geoLabelsCounts": geo_labels_payload.get("counts"), } manifest = { "schema": "planet-earth-boundaries/v2", "version": coverage["profile"], "assetVersion": asset_version, "builtAt": dt.datetime.now(dt.UTC).replace(microsecond=0).isoformat(), "tileProvider": "pmtiles-mvt", "format": "pmtiles+mvt", "buildInputHash": args.build_input_hash, "pmtiles": { "path": pmtiles_name, "sha256": sha256_file(pmtiles_path), "sizeBytes": pmtiles_path.stat().st_size, }, "tiles": { "minZoom": args.min_zoom, "maxZoom": args.max_zoom, "layerZoom": { "coastline": [args.min_zoom, coast_max_zoom], "boundary_admin0": [args.min_zoom, border_max_zoom], "boundary_disputed_internal": [args.min_zoom, border_max_zoom], "boundary_admin1": [4, border_max_zoom], "claim_line": [args.min_zoom, border_max_zoom], }, }, "layers": ["coastline", "boundary_admin0", "boundary_disputed_internal", "boundary_admin1", "claim_line"], "layerFeatureCounts": dict(layer_counts), "snap": snap_stats, "povPolicy": coverage, "chinaClaims": {"available": True, "featureCount": len(claims)}, "base": None, "hoverIndex": hover_name, "hoverIndexSha256": sha256_file(args.output_dir / hover_name), "hoverBorders": hover_borders_name, "hoverBordersSha256": sha256_file(args.output_dir / hover_borders_name), **geo_labels_manifest, "policySha256": policy_digest(policy), "attribution": ATTRIBUTION, } write_json(args.output_dir / "manifest.json", manifest, indent=2) removed = remove_stale_artifacts(args.output_dir, keep_names) peak_rss_mb = round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024, 1) child_peak_rss_mb = round(resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss / 1024, 1) print( json.dumps( { "status": "success", "format": "pmtiles+mvt", "output": str(pmtiles_path), "sizeBytes": manifest["pmtiles"]["sizeBytes"], "layerFeatureCounts": manifest["layerFeatureCounts"], "snap": snap_stats, "seconds": round(time.monotonic() - started, 1), "tippecanoeSeconds": tippecanoe_seconds, "peakRssMb": peak_rss_mb, "tippecanoePeakRssMb": child_peak_rss_mb, "removedStaleArtifacts": removed, }, ensure_ascii=False, sort_keys=True, ) ) if __name__ == "__main__": main()