import sys from pathlib import Path from shapely.geometry import LineString, Polygon, box, mapping SCRIPTS = Path(__file__).resolve().parents[2] / "scripts" if str(SCRIPTS) not in sys.path: sys.path.insert(0, str(SCRIPTS)) import build_earth_boundary_pmtiles as builder # noqa: E402 import earth_boundary_geometry as geo # noqa: E402 def feature(code, geometry, **props): return {"type": "Feature", "properties": {"ADM0_A3": code, **props}, "geometry": mapping(geometry)} def test_land_borders_keep_only_shared_edges(): countries = {"AAA": box(0, 0, 1, 1), "BBB": box(1, 0, 2, 1), "CCC": box(5, 5, 6, 6)} borders = geo.derive_land_borders(countries) assert len(borders) == 1 line = borders[0]["geometry"] assert borders[0]["properties"] == {"ADM0_L": "AAA", "ADM0_R": "BBB"} assert sorted(line.coords) == [(1.0, 0.0), (1.0, 1.0)] def test_country_geometries_dissolve_internal_policy_edges(): admin0 = { "type": "FeatureCollection", "features": [feature("CHN", box(0, 0, 1, 1)), feature("CHN", box(1, 0, 2, 1))], } countries = geo.country_geometries(admin0) assert list(countries) == ["CHN"] assert countries["CHN"].equals(box(0, 0, 2, 1)) def test_free_endpoints_are_line_ends_touched_once(): lines = [ {"geometry": LineString([(0, 0), (1, 0)])}, {"geometry": LineString([(1, 0), (2, 0)])}, {"geometry": LineString([(1, 0), (1, 1)])}, ] assert geo.free_endpoints(lines) == {(0.0, 0.0), (2.0, 0.0), (1.0, 1.0)} def test_coastal_end_is_trimmed_at_osm_coast_crossing(): border = [{"geometry": LineString([(0, 0), (0, 1.03)])}] coast = [LineString([(-1, 1.0), (1, 1.0)])] stats = geo.snap_coastal_ends(border, coast, {(0.0, 1.03)}, max_distance=0.05) assert stats["trimmed"] == 1 assert border[0]["geometry"].coords[-1] == (0.0, 1.0) def test_coastal_end_is_extended_to_nearby_osm_coast(): border = [{"geometry": LineString([(0, 0), (0, 0.98)])}] coast = [LineString([(-1, 1.0), (1, 1.0)])] stats = geo.snap_coastal_ends(border, coast, {(0.0, 0.98)}, max_distance=0.05) assert stats["extended"] == 1 assert border[0]["geometry"].coords[-1] == (0.0, 1.0) def test_coastal_end_beyond_snap_distance_is_left_alone(): border = [{"geometry": LineString([(0, 0), (0, 0.9)])}] coast = [LineString([(-1, 0.96), (1, 0.96)])] stats = geo.snap_coastal_ends(border, coast, {(0.0, 0.9)}, max_distance=0.05) assert stats["extended"] == 0 and stats["trimmed"] == 0 assert border[0]["geometry"].coords[-1] == (0.0, 0.9) def test_admin1_lines_follow_china_pov(): china = box(0, 0, 10, 10) clip = china.buffer(-geo.CHINA_CLIP_BUFFER_DEGREES) collection = { "type": "FeatureCollection", "features": [ feature("CHN", LineString([(2, 2), (3, 3)]), MIN_ZOOM=4.6), feature("TWN", LineString([(20, 20), (21, 21)]), MIN_ZOOM=8.7), feature("HKG", LineString([(30, 30), (31, 31)]), MIN_ZOOM=10), feature("IND", LineString([(5, 5), (15, 5)]), MIN_ZOOM=4.6), feature("USA", LineString([(40, 40), (41, 41)]), MIN_ZOOM=2), feature("RUS", LineString([(50, 50), (51, 51)]), FCLASS_CN="Unrecognized Admin-1 boundary"), ], } lines = geo.admin1_lines(collection, clip) by_code = {} for line in lines: by_code.setdefault(line["properties"]["ADM0_A3"], []).append(line) assert set(by_code) == {"CHN", "IND", "USA"} india = by_code["IND"][0]["geometry"] assert min(x for x, _y in india.coords) >= 10 - geo.CHINA_CLIP_BUFFER_DEGREES - 1e-9 assert by_code["USA"][0]["properties"]["minzoom"] == 4 assert by_code["CHN"][0]["properties"]["minzoom"] == 4 def test_disputed_lines_inside_china_are_removed(): clip = box(0, 0, 10, 10) collection = { "type": "FeatureCollection", "features": [ feature("X", LineString([(2, 2), (3, 3)]), FEATURECLA="Disputed"), feature("X", LineString([(20, 2), (21, 3)]), FEATURECLA="Line of control"), ], } lines = geo.disputed_lines(collection, clip) assert len(lines) == 1 assert lines[0]["properties"]["FEATURECLA"] == "Line of control" def test_claim_features_accept_only_china_pov_nine_dash_line(): dash = mapping(LineString([(110, 10), (110.1, 10.1)])) collection = { "type": "FeatureCollection", "features": [ {"type": "Feature", "properties": {"COMMENT": "Chinese 9 dash line", "FCLASS_CN": "International boundary (verify)"}, "geometry": dash}, {"type": "Feature", "properties": {"COMMENT": "Chinese 9 dash line", "FCLASS_CN": None}, "geometry": dash}, {"type": "Feature", "properties": {"COMMENT": "Median", "FCLASS_CN": "International boundary (verify)"}, "geometry": dash}, ], } claims = builder.claim_features(collection) assert len(claims) == 1 assert claims[0]["properties"] == {"name": "九段线", "name_en": "Nine-dash line"} def test_claim_coverage_marks_rule_applied_only_with_all_dashes(): coverage = { "appliedRuleIds": ["kosovo"], "unresolvedRuleIds": [builder.CLAIM_RULE_ID, "china-south-china-sea-islands"], "unresolvedReasons": {builder.CLAIM_RULE_ID: "missing", "china-south-china-sea-islands": "partial"}, } builder.apply_claim_coverage(coverage, [{}] * builder.MIN_CLAIM_DASHES) assert builder.CLAIM_RULE_ID in coverage["appliedRuleIds"] assert coverage["unresolvedRuleIds"] == ["china-south-china-sea-islands"] assert coverage["coverage"] == "partial" assert coverage["claimLine"]["featureCount"] == builder.MIN_CLAIM_DASHES def test_hover_index_is_one_simplified_polygon_per_country(): admin0 = { "type": "FeatureCollection", "features": [ feature("CHN", box(1, 0, 2, 1), ISO_A3="CHN", NAME_ZH="中国", PLANET_POLICY_RULE="china-hong-kong"), feature("CHN", box(0, 0, 1, 1), ISO_A3="CHN", NAME_ZH="中国", EXTRA="dropped"), ], } countries = geo.country_geometries(admin0) hover = geo.hover_index(admin0, countries, tolerance=0.01) assert len(hover["features"]) == 1 props = hover["features"][0]["properties"] assert props == { "ISO_A3": "CHN", "ADM0_A3": "CHN", "NAME_ZH": "中国", "PLANET_POLICY_RULES": ["china-hong-kong"], } assert Polygon(hover["features"][0]["geometry"]["coordinates"][0]).equals(box(0, 0, 2, 1)) def test_geojson_feature_sets_tippecanoe_layer_and_zoom(): out = geo.geojson_feature( {"geometry": LineString([(0, 0), (1, 1)]), "properties": {"ADM0_A3": "USA", "minzoom": 4, "NAME": None}}, "boundary_admin1", 4, 6, ) assert out["tippecanoe"] == {"layer": "boundary_admin1", "minzoom": 4, "maxzoom": 6} assert out["properties"] == {"ADM0_A3": "USA"} assert out["geometry"]["type"] == "LineString" def test_coastline_country_assigner_tags_single_and_cross_border_lines(): countries = { "CHN": box(0, 0, 10, 10), "VNM": box(10, 0, 20, 10), "JPN": box(30, 0, 35, 5), } assigner = geo.CoastlineCountryAssigner(countries) # Pure inland/coastal Taiwan/Japan single-country segment. jpn_tags = assigner.assign(LineString([(30.0, 0.0), (35.0, 0.0)])) assert jpn_tags == [(LineString([(30.0, 0.0), (35.0, 0.0)]), "JPN")] # Multi-country coastline crossing CHN|VNM at x=10 splits cleanly. cross_tags = assigner.assign(LineString([(8.0, 0.0), (12.0, 0.0)])) codes = [code for _seg, code in cross_tags] assert "CHN" in codes and "VNM" in codes assert all(seg.length > 0 for seg, _code in cross_tags) def test_build_geo_labels_applies_china_pov_and_tiers(): def place(name, zh, lon, lat, adm0, fclass, sr, pop, wc=0): return { "type": "Feature", "geometry": {"type": "Point", "coordinates": [lon, lat]}, "properties": { "NAME": name, "NAME_EN": name, "NAME_ZH": zh, "ADM0_A3": adm0, "FEATURECLA": fclass, "SCALERANK": sr, "POP_MAX": pop, "WORLDCITY": wc, }, } places = { "type": "FeatureCollection", "features": [ place("Beijing", "北京", 116.4, 39.9, "CHN", "Admin-0 capital", 0, 11106000, 1), place("Shanghai", "上海", 121.4, 31.2, "CHN", "Admin-1 capital", 0, 14987000, 1), place("Taipei", "台北", 121.56, 25.03, "TWN", "Admin-0 capital", 1, 6900000, 1), place("Pristina", "普里什蒂纳", 21.16, 42.66, "KOS", "Admin-0 capital", 4, 465000, 0), place("Itanagar", "伊塔那噶", 93.61, 27.10, "IND", "Admin-1 capital", 7, 45000, 0), place("Hangzhou", "杭州", 120.15, 30.27, "CHN", "Admin-1 capital", 3, 5000000, 0), place("SmallTown", "小镇", 110.0, 30.0, "CHN", "Populated place", 8, 5000, 0), place("ResearchBase", "科考站", 0.0, -70.0, "ATA", "Scientific station", 3, 50, 0), ], } china_clip = box(91.5, 26.8, 97.5, 29.5) payload = geo.build_geo_labels(places, policy={"profile": "china-pov-v1"}, china_clip=china_clip) assert payload["schema"] == "planet-earth-geo-labels/v1" by_en = {item["en"]: item for item in payload["places"]} assert by_en["Beijing"]["t"] == 1 and by_en["Beijing"]["k"] == "capital" and by_en["Beijing"]["iso"] == "CHN" assert by_en["Shanghai"]["t"] == 1 and by_en["Shanghai"]["k"] == "megacity" assert by_en["Taipei"]["t"] == 1 and by_en["Taipei"]["k"] == "admin1" and by_en["Taipei"]["iso"] == "CHN" assert by_en["Pristina"]["t"] == 2 and by_en["Pristina"]["k"] == "admin1" and by_en["Pristina"]["iso"] == "SRB" assert by_en["Hangzhou"]["t"] == 2 assert "Itanagar" not in by_en assert "SmallTown" not in by_en assert "ResearchBase" not in by_en # Capitals appear before megacities/admin1 inside Tier 1 tier1_kinds = [item["k"] for item in payload["places"] if item["t"] == 1] assert tier1_kinds[0] == "capital"