File size: 4,560 Bytes
7e6579d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build the area of interest: Naryn oblast, its districts, and a 20 km buffer for AppEEARS.

Source: geoBoundaries (gbOpen, KGZ ADM1/ADM2). Writes GeoJSON to --out and prints a summary,
including whether the PRD's known places fall inside the oblast and inside the buffer.
"""
from __future__ import annotations

import argparse
import json
from pathlib import Path

import geopandas as gpd
import requests
from shapely.geometry import Point, box

API = "https://www.geoboundaries.org/api/current/gbOpen/KGZ/{level}/"
SINU = "+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +R=6371007.181 +units=m +no_defs"  # MODIS grid, equal-area
BUFFER_M = 20_000
SIMPLIFY_DEG = 0.005  # ~0.5 km, keeps the AppEEARS polygon small

# Official districts of Naryn oblast. geoBoundaries' ADM1 "Naryn Region" also contains Toguz-Toro,
# which (to our knowledge) belongs to Jalal-Abad oblast, so the oblast is built from these five instead.
OFFICIAL_DISTRICTS = ["Ak-Talaa", "At-Bashy", "Jumgal", "Kochkor", "Naryn"]

# PRD known places outside the oblast get their own box in the AppEEARS request (approximate extents).
EXTRA_BOXES = {
    "Suusamyr valley (Chuy oblast)": (73.60, 41.95, 74.50, 42.30),   # lon_min, lat_min, lon_max, lat_max
    "Ak-Shyirak massif (Issyk-Kul oblast)": (77.90, 41.70, 78.50, 42.00),
}

# Approximate coordinates (lat, lon) of the PRD's "known places"; used only for the inside/outside check.
KNOWN_PLACES = {
    "Son-Kul lake": (41.83, 75.13),
    "Naryn city": (41.43, 75.99),
    "Ak-Shyirak (Kumtor area, approx.)": (41.86, 78.19),
    "Suusamyr village": (42.17, 73.97),
}


def fetch(level: str, cache: Path) -> gpd.GeoDataFrame:
    path = cache / f"geoBoundaries-KGZ-{level}.geojson"
    if not path.exists():
        meta = requests.get(API.format(level=level), timeout=60).json()
        r = requests.get(meta["gjDownloadURL"], timeout=300)
        r.raise_for_status()
        path.write_bytes(r.content)
    return gpd.read_file(path).to_crs(4326)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", type=Path, default=Path("/root/trendex-ml/data/aoi"))
    args = ap.parse_args()
    args.out.mkdir(parents=True, exist_ok=True)

    adm1 = fetch("ADM1", args.out)
    adm2 = fetch("ADM2", args.out)
    print("ADM1 names:", sorted(adm1["shapeName"]))
    gb_naryn = adm1[adm1["shapeName"].str.contains("Naryn", case=False)]
    reps = adm2.geometry.representative_point()
    in_gb_naryn = sorted(adm2[reps.within(gb_naryn.geometry.iloc[0])]["shapeName"])

    districts = adm2[adm2["shapeName"].isin(OFFICIAL_DISTRICTS)][["shapeName", "shapeID", "geometry"]]
    districts = districts.reset_index(drop=True)
    missing = sorted(set(OFFICIAL_DISTRICTS) - set(districts["shapeName"]))
    if missing:
        raise SystemExit(f"Districts not found in geoBoundaries ADM2: {missing}")
    naryn = gpd.GeoDataFrame({"shapeName": ["Naryn oblast (5 districts)"]},
                             geometry=[districts.union_all()], crs=4326)
    naryn_geom = naryn.geometry.iloc[0]

    naryn_sinu = naryn.to_crs(SINU)
    area_km2 = naryn_sinu.area.iloc[0] / 1e6
    buffered = naryn_sinu.buffer(BUFFER_M).to_crs(4326).simplify(SIMPLIFY_DEG)
    names = ["Naryn oblast + 20 km"] + list(EXTRA_BOXES)
    geoms = [buffered.iloc[0]] + [box(*b) for b in EXTRA_BOXES.values()]
    aoi = gpd.GeoDataFrame({"name": names}, geometry=geoms, crs=4326)
    aoi_union = aoi.union_all()

    naryn.to_file(args.out / "naryn_oblast.geojson", driver="GeoJSON")
    districts.to_file(args.out / "naryn_districts.geojson", driver="GeoJSON")
    aoi.to_file(args.out / "aoi_request.geojson", driver="GeoJSON")  # what AppEEARS gets

    summary = {
        "oblast_name": naryn["shapeName"].iloc[0],
        "oblast_area_km2": round(area_km2),
        "expected_1km_cells_approx": round(area_km2 / 0.8586),
        "districts": sorted(districts["shapeName"]),
        "geoboundaries_adm1_naryn_contains": in_gb_naryn,
        "oblast_area_km2_note": "official figure is about 45,200 km2; compare",
        "aoi_bbox_lon_lat": [round(v, 3) for v in aoi.total_bounds],
        "aoi_features": names,
        "known_places": {
            name: {"in_oblast": naryn_geom.contains(Point(lon, lat)),
                   "in_request": aoi_union.contains(Point(lon, lat))}
            for name, (lat, lon) in KNOWN_PLACES.items()
        },
    }
    (args.out / "aoi_summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False))
    print(json.dumps(summary, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()