"""Geometry helpers for the China POV Earth boundary PMTiles build. The display policy decides country ownership on admin-0 polygons (``earth_boundary_policy``). This module turns those polygons into the line layers the globe renders, aligns their coastal ends with the high precision OSM coastline and prepares the light-weight hover / label assets. """ from __future__ import annotations import math import zipfile from collections import Counter from collections.abc import Iterable, Iterator from pathlib import Path from typing import Any import shapefile from shapely import STRtree, get_coordinates, prepare from shapely.geometry import LineString, MultiLineString, Point, Polygon, box, mapping, shape from shapely.geometry.base import BaseGeometry from shapely.ops import linemerge, nearest_points, substring, unary_union SNAP_MAX_DEGREES = 0.05 # ~5 km; larger gaps stay visible and are logged. ENDPOINT_KEY_DIGITS = 7 CHINA_CLIP_BUFFER_DEGREES = 0.01 CHINA_ADMIN0_CODE = "CHN" ABSORBED_ADMIN1_CODES = {"TWN", "HKG", "MAC"} def country_code(properties: dict[str, Any]) -> str: code = properties.get("ADM0_A3") or properties.get("ISO_A3") or "" return str(code).upper() def _line_parts(geometry: BaseGeometry | None) -> list[LineString]: if geometry is None or geometry.is_empty: return [] if isinstance(geometry, LineString): return [geometry] if geometry.length > 0 else [] if isinstance(geometry, MultiLineString): return [part for part in geometry.geoms if part.length > 0] parts: list[LineString] = [] for part in getattr(geometry, "geoms", []): parts.extend(_line_parts(part)) return parts def _merged_lines(geometry: BaseGeometry | None) -> list[LineString]: parts = _line_parts(geometry) if not parts: return [] merged = linemerge(MultiLineString(parts)) if len(parts) > 1 else parts[0] return _line_parts(merged) def country_geometries(admin0: dict[str, Any]) -> dict[str, BaseGeometry]: """Dissolve policy-applied admin-0 features into one geometry per country.""" grouped: dict[str, list[BaseGeometry]] = {} for feature in admin0.get("features") or []: geometry = feature.get("geometry") if not geometry: continue code = country_code(feature.get("properties") or {}) if not code: continue geom = shape(geometry) if not geom.is_valid: geom = geom.buffer(0) grouped.setdefault(code, []).append(geom) return { code: parts[0] if len(parts) == 1 else unary_union(parts) for code, parts in grouped.items() } def derive_land_borders(countries: dict[str, BaseGeometry]) -> list[dict[str, Any]]: """Return shared admin-0 edges only, so coasts never double the coastline layer.""" codes = sorted(countries) geoms = [countries[code] for code in codes] boundaries = [geom.boundary for geom in geoms] tree = STRtree(geoms) features: list[dict[str, Any]] = [] for left_index, left_code in enumerate(codes): for right_index in tree.query(geoms[left_index]): right_index = int(right_index) if right_index <= left_index: continue shared = boundaries[left_index].intersection(boundaries[right_index]) for line in _merged_lines(shared): features.append( { "type": "Feature", "geometry": line, "properties": {"ADM0_L": left_code, "ADM0_R": codes[right_index]}, } ) return features def _endpoint_key(coord: Iterable[float]) -> tuple[float, float]: lon, lat = list(coord)[:2] return (round(lon, ENDPOINT_KEY_DIGITS), round(lat, ENDPOINT_KEY_DIGITS)) def free_endpoints(features: list[dict[str, Any]]) -> set[tuple[float, float]]: """Endpoints touched by a single line: coastal ends of a border network.""" counts: Counter[tuple[float, float]] = Counter() for feature in features: line: LineString = feature["geometry"] coords = line.coords counts[_endpoint_key(coords[0])] += 1 counts[_endpoint_key(coords[-1])] += 1 return {key for key, count in counts.items() if count == 1} def iter_shapefile_lines(path: Path) -> Iterator[LineString]: with shapefile.Reader(str(path)) as reader: for shp in reader.iterShapes(): if not shp.points or len(shp.points) < 2: continue parts = list(shp.parts) + [len(shp.points)] for start, end in zip(parts[:-1], parts[1:], strict=False): points = shp.points[start:end] if len(points) >= 2: yield LineString(points) def resolve_coastline_shapefile(source: Path, work_dir: Path) -> Path | None: """Accept an OSM coastline zip, an extracted directory or a .shp file.""" if source.suffix.lower() == ".shp": return source if source.is_dir(): matches = sorted(source.rglob("lines.shp")) return matches[0] if matches else None if source.suffix.lower() == ".zip": target = work_dir / "coastline" target.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(source) as archive: for member in archive.namelist(): name = Path(member).name if name.startswith("lines."): with archive.open(member) as src, (target / name).open("wb") as dst: while chunk := src.read(1024 * 1024): dst.write(chunk) shp = target / "lines.shp" return shp if shp.exists() else None return None def collect_coast_near( coast_lines: Iterable[LineString], endpoints: Iterable[tuple[float, float]], radius: float = SNAP_MAX_DEGREES, ) -> list[LineString]: points = [Point(lon, lat).buffer(radius, quad_segs=2) for lon, lat in endpoints] if not points: return [] endpoint_tree = STRtree(points) near: list[LineString] = [] for line in coast_lines: if len(endpoint_tree.query(line)): near.append(line) return near def _cut_or_extend( line: LineString, at_start: bool, coast_tree: STRtree, coast: list[LineString], max_distance: float, ) -> tuple[LineString, str]: coords = list(line.coords) end = Point(coords[0] if at_start else coords[-1]) candidates = [coast[int(i)] for i in coast_tree.query(end.buffer(max_distance))] if not candidates: return line, "no_coast" nearby = unary_union(candidates) window = min(line.length, max_distance) tail = ( substring(line, 0, window) if at_start else substring(line, line.length - window, line.length) ) crossing = tail.intersection(nearby) crossing_points = [Point(c) for c in get_coordinates(crossing)] if not crossing.is_empty else [] if crossing_points: # Keep the land part: cut at the crossing closest to the line end. distances = [line.project(point) for point in crossing_points] cut = min(distances) if at_start else max(distances) if at_start: trimmed = substring(line, cut, line.length) else: trimmed = substring(line, 0, cut) if isinstance(trimmed, LineString) and trimmed.length > 0: return trimmed, "trimmed" return line, "unchanged" target = nearest_points(end, nearby)[1] gap = end.distance(target) if gap == 0: return line, "unchanged" if gap > max_distance: return line, "gap_too_large" if at_start: return LineString([target.coords[0], *coords]), "extended" return LineString([*coords, target.coords[0]]), "extended" def snap_coastal_ends( features: list[dict[str, Any]], coast: list[LineString], free: set[tuple[float, float]], max_distance: float = SNAP_MAX_DEGREES, ) -> Counter[str]: """Trim or extend coastal border ends onto the OSM coastline in place.""" stats: Counter[str] = Counter() if not coast: stats["no_coast_data"] = len(free) return stats coast_tree = STRtree(coast) for feature in features: line: LineString = feature["geometry"] for at_start in (True, False): coord = line.coords[0] if at_start else line.coords[-1] if _endpoint_key(coord) not in free: continue line, outcome = _cut_or_extend(line, at_start, coast_tree, coast, max_distance) stats[outcome] += 1 feature["geometry"] = line return stats def china_clip_geometry(countries: dict[str, BaseGeometry]) -> BaseGeometry | None: china = countries.get(CHINA_ADMIN0_CODE) if china is None: return None # Shrink slightly so lines on the shared border survive the clip. return china.buffer(-CHINA_CLIP_BUFFER_DEGREES) def _clip_outside(geometry: BaseGeometry, clip: BaseGeometry | None) -> list[LineString]: if clip is None or not geometry.intersects(clip): return _line_parts(geometry) return _line_parts(geometry.difference(clip)) def admin1_lines(collection: dict[str, Any], china_clip: BaseGeometry | None) -> list[dict[str, Any]]: """China POV admin-1 lines: no unrecognized lines and no foreign lines inside China.""" features: list[dict[str, Any]] = [] for feature in collection.get("features") or []: geometry = feature.get("geometry") if not geometry: continue props = feature.get("properties") or {} code = country_code(props) if code in ABSORBED_ADMIN1_CODES: continue if str(props.get("FCLASS_CN") or "").startswith("Unrecognized"): continue geom = shape(geometry) parts = _line_parts(geom) if code == CHINA_ADMIN0_CODE else _clip_outside(geom, china_clip) for part in parts: features.append( { "type": "Feature", "geometry": part, "properties": {"ADM0_A3": code, "minzoom": 4}, } ) return features def disputed_lines(collection: dict[str, Any], china_clip: BaseGeometry | None) -> list[dict[str, Any]]: """Keep disputed lines outside China; China POV has no internal disputed lines.""" features: list[dict[str, Any]] = [] for feature in collection.get("features") or []: geometry = feature.get("geometry") if not geometry: continue props = feature.get("properties") or {} if props.get("PLANET_LAYER") == "claim_line": continue for part in _clip_outside(shape(geometry), china_clip): features.append( { "type": "Feature", "geometry": part, "properties": {"FEATURECLA": props.get("FEATURECLA"), "NAME": props.get("NAME")}, } ) return features def hover_index( admin0: dict[str, Any], countries: dict[str, BaseGeometry], tolerance: float, ) -> dict[str, Any]: """One dissolved, simplified polygon per country for picking and hover fill.""" properties_by_code: dict[str, dict[str, Any]] = {} rules_by_code: dict[str, set[str]] = {} for feature in admin0.get("features") or []: props = feature.get("properties") or {} code = country_code(props) if not code: continue if props.get("PLANET_POLICY_RULE"): rules_by_code.setdefault(code, set()).add(str(props["PLANET_POLICY_RULE"])) # Prefer the source feature that is not a policy-absorbed region. current = properties_by_code.get(code) if current is None or (current.get("PLANET_POLICY_RULE") and not props.get("PLANET_POLICY_RULE")): properties_by_code[code] = props keep = ( "ISO_A3", "ADM0_A3", "ISO_A2", "NAME", "NAME_EN", "NAME_ZH", "ADMIN", "CONTINENT", ) features = [] for code in sorted(countries): simplified = countries[code].simplify(tolerance, preserve_topology=True) if simplified.is_empty: continue source = properties_by_code.get(code, {}) props = {key: source[key] for key in keep if source.get(key) not in (None, "")} if code in rules_by_code: # Dissolved polygons keep the list of display-policy rules they absorbed. props["PLANET_POLICY_RULES"] = sorted(rules_by_code[code]) features.append({"type": "Feature", "properties": props, "geometry": rounded_mapping(simplified, 4)}) return {"type": "FeatureCollection", "features": features} def hover_borders(borders: list[dict[str, Any]], tolerance: float) -> dict[str, Any]: features = [] for feature in borders: simplified = feature["geometry"].simplify(tolerance, preserve_topology=False) if simplified.is_empty or simplified.length == 0: continue features.append( { "type": "Feature", "properties": dict(feature["properties"]), "geometry": rounded_mapping(simplified, 4), } ) return {"type": "FeatureCollection", "features": features} def _round_coords(value: Any, digits: int) -> Any: if isinstance(value, (list, tuple)): if value and isinstance(value[0], (int, float)): return [round(float(v), digits) for v in value[:2]] return [_round_coords(item, digits) for item in value] return value def rounded_mapping(geometry: BaseGeometry, digits: int = 5) -> dict[str, Any]: geojson = mapping(geometry) return {"type": geojson["type"], "coordinates": _round_coords(geojson["coordinates"], digits)} def _polygon_parts(geometry: BaseGeometry | None) -> list[Polygon]: if geometry is None or geometry.is_empty: return [] if isinstance(geometry, Polygon): return [geometry] if geometry.area > 0 else [] parts: list[Polygon] = [] for geom in getattr(geometry, "geoms", []): parts.extend(_polygon_parts(geom)) return parts class CoastlineCountryAssigner: """Assign policy-normalized `ADM0_A3` codes to OSM coastline segments.""" SEARCH_RADIUS_DEGREES = 0.08 FALLBACK_RADIUS_DEGREES = 0.25 MIN_SPLIT_LENGTH = 0.05 MAX_SPLIT_DEPTH = 5 def __init__(self, countries: dict[str, BaseGeometry], tolerance: float = 0.005) -> None: self.polys: list[Polygon] = [] self.codes: list[str] = [] for code in sorted(countries): for poly in _polygon_parts(countries[code]): simplified = poly.simplify(tolerance, preserve_topology=False) if tolerance > 0 else poly candidate = simplified if isinstance(simplified, Polygon) and not simplified.is_empty else poly if not candidate.is_valid: candidate = candidate.buffer(0) for clean in _polygon_parts(candidate): prepare(clean) self.polys.append(clean) self.codes.append(code) self.tree = STRtree(self.polys) if self.polys else None def _nearest_code(self, point: Point, candidate_indices: Iterable[int]) -> str | None: for raw_idx in candidate_indices: idx = int(raw_idx) if self.polys[idx].contains(point): return self.codes[idx] best_code: str | None = None best_dist = math.inf for raw_idx in candidate_indices: idx = int(raw_idx) dist = self.polys[idx].distance(point) if dist < best_dist: best_dist = dist best_code = self.codes[idx] return best_code def _assign_segment( self, line: LineString, candidate_indices: list[int], depth: int, ) -> list[tuple[LineString, str | None]]: coords = line.coords if len(coords) < 2 or line.length <= 0: return [] start_code = self._nearest_code(Point(coords[0]), candidate_indices) mid_code = self._nearest_code(line.interpolate(0.5, normalized=True), candidate_indices) end_code = self._nearest_code(Point(coords[-1]), candidate_indices) if start_code == mid_code == end_code: return [(line, mid_code)] if depth < self.MAX_SPLIT_DEPTH and line.length > self.MIN_SPLIT_LENGTH: half = line.length * 0.5 left = substring(line, 0.0, half) right = substring(line, half, line.length) out: list[tuple[LineString, str | None]] = [] for part in (*_line_parts(left), *_line_parts(right)): out.extend(self._assign_segment(part, candidate_indices, depth + 1)) return out return [(line, mid_code or start_code or end_code)] def assign(self, line: LineString) -> list[tuple[LineString, str | None]]: if self.tree is None or line.is_empty or line.length <= 0: return [(line, None)] if not line.is_empty else [] minx, miny, maxx, maxy = line.bounds pad = self.SEARCH_RADIUS_DEGREES candidates = self.tree.query(box(minx - pad, miny - pad, maxx + pad, maxy + pad)) if len(candidates) == 0: pad = self.FALLBACK_RADIUS_DEGREES candidates = self.tree.query(box(minx - pad, miny - pad, maxx + pad, maxy + pad)) if len(candidates) == 0: return [(line, None)] cand_list = [int(i) for i in candidates] distinct_codes = {self.codes[idx] for idx in cand_list} if len(distinct_codes) == 1: return [(line, next(iter(distinct_codes)))] raw_segments = self._assign_segment(line, cand_list, 0) if len(raw_segments) <= 1: return raw_segments merged: list[tuple[LineString, str | None]] = [] for seg, code in raw_segments: if ( merged and merged[-1][1] == code and merged[-1][0].coords[-1] == seg.coords[0] ): merged[-1] = (LineString([*merged[-1][0].coords, *seg.coords[1:]]), code) else: merged.append((seg, code)) return merged def geojson_feature( feature: dict[str, Any], layer: str, min_zoom: int | None = None, max_zoom: int | None = None, ) -> dict[str, Any]: geometry = feature["geometry"] if isinstance(geometry, BaseGeometry): geometry = rounded_mapping(geometry, 7) props = {k: v for k, v in (feature.get("properties") or {}).items() if k != "minzoom" and v is not None} tippecanoe: dict[str, Any] = {"layer": layer} if min_zoom is not None: tippecanoe["minzoom"] = min_zoom if max_zoom is not None: tippecanoe["maxzoom"] = max_zoom return {"type": "Feature", "tippecanoe": tippecanoe, "properties": props, "geometry": geometry} _SKIP_SETTLEMENT_CLASSES = { "Scientific station", "Historic place", "Meteorological Station", } _ADMIN1_SETTLEMENT_CLASSES = { "Admin-1 capital", "Admin-1 region capital", "Admin-0 region capital", } def _clean_label_text(value: Any) -> str: if value is None: return "" return " ".join(str(value).split()) def build_geo_labels( places_geojson: dict[str, Any], *, policy: dict[str, Any] | None = None, china_clip: BaseGeometry | None = None, ) -> dict[str, Any]: """Build China-POV filtered, 3-tier global city labels payload.""" prepared_clip = china_clip if prepared_clip is not None and not prepared_clip.is_empty: prepare(prepared_clip) dedup: dict[tuple[str, str, float, float], dict[str, Any]] = {} for feature in places_geojson.get("features") or []: geometry = feature.get("geometry") or {} if geometry.get("type") != "Point": continue coords = geometry.get("coordinates") or [] if len(coords) < 2: continue lon = float(coords[0]) lat = float(coords[1]) if not (-180.0 <= lon <= 180.0 and -90.0 <= lat <= 90.0): continue props = feature.get("properties") or {} fclass = _clean_label_text(props.get("FCLASS_CN") or props.get("FEATURECLA") or "") if fclass in _SKIP_SETTLEMENT_CLASSES: continue raw_adm0 = str(props.get("ADM0_A3") or "").strip().upper() raw_sov = str(props.get("SOV_A3") or "").strip().upper() raw_iso = str(props.get("ISO_A3") or "").strip().upper() iso = raw_adm0 or raw_sov or raw_iso or "" demoted_from_admin0 = False if iso in ABSORBED_ADMIN1_CODES: iso = CHINA_ADMIN0_CODE demoted_from_admin0 = True elif iso in {"KOS", "XKS"}: iso = "SRB" demoted_from_admin0 = True elif iso == "SOL": iso = "SOM" demoted_from_admin0 = True was_admin0 = fclass in {"Admin-0 capital", "Admin-0 capital alt"} if demoted_from_admin0 and was_admin0: fclass = "Admin-1 capital" if ( prepared_clip is not None and not prepared_clip.is_empty and iso != CHINA_ADMIN0_CODE and prepared_clip.contains(Point(lon, lat)) ): continue sr = int(props.get("SCALERANK") if props.get("SCALERANK") is not None else 10) pop = int(props.get("POP_MAX") or 0) wc = int(props.get("WORLDCITY") or 0) if fclass == "Admin-0 capital": tier = 1 kind = "capital" elif sr <= 1 or (wc == 1 and pop >= 3_500_000): tier = 1 kind = "admin1" if demoted_from_admin0 else "megacity" elif sr <= 4 or pop >= 1_000_000 or fclass in {"Admin-0 region capital", "Admin-0 capital alt"} or (demoted_from_admin0 and was_admin0): tier = 2 kind = "admin1" if (demoted_from_admin0 or fclass in _ADMIN1_SETTLEMENT_CLASSES) else "major" elif fclass in {"Admin-1 capital", "Admin-1 region capital"} and (sr <= 7 or pop >= 100_000): tier = 3 kind = "admin1" else: continue en = _clean_label_text(props.get("NAME_EN") or props.get("NAME") or props.get("NAMEASCII")) zh = _clean_label_text(props.get("NAME_ZH") or props.get("NAME_ZHT") or en) if not en and not zh: continue item = { "zh": zh or en, "en": en or zh, "lat": round(lat, 4), "lon": round(lon, 4), "t": tier, "k": kind, "iso": iso, "sr": sr, "pop": pop, } dedup_key = (iso, (en or zh).lower(), round(lat, 2), round(lon, 2)) prev = dedup.get(dedup_key) if prev is None or (item["t"], item["sr"], -item["pop"]) < (prev["t"], prev["sr"], -prev["pop"]): dedup[dedup_key] = item kind_rank = {"capital": 0, "megacity": 1, "major": 2, "admin1": 3} places = sorted( dedup.values(), key=lambda item: (item["t"], kind_rank.get(item["k"], 4), item["sr"], -item["pop"], item["en"]), ) tier_counts = Counter(item["t"] for item in places) profile = (policy or {}).get("profile") or "china-pov-v1" return { "schema": "planet-earth-geo-labels/v1", "version": profile, "counts": { "total": len(places), "tier1": tier_counts[1], "tier2": tier_counts[2], "tier3": tier_counts[3], }, "places": places, }