File size: 2,372 Bytes
a5899e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Central Asia area of interest: KAZ, KGZ, TJK, TKM, UZB (geoBoundaries gbOpen ADM0 + ADM1).

Writes to --out: ca_adm0.geojson (country polygons, iso3), ca_adm1.geojson (region polygons, iso3, shapeName),
aoi_request.geojson (simplified union, used for downloads), aoi_summary.json.
"""
from __future__ import annotations

import argparse
import json
from pathlib import Path

import geopandas as gpd
import pandas as pd
import requests

API = "https://www.geoboundaries.org/api/current/gbOpen/{iso}/{level}/"
ISO3 = ["KAZ", "KGZ", "TJK", "TKM", "UZB"]
SINU = "+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +R=6371007.181 +units=m +no_defs"


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


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", type=Path, default=Path("/root/trendex-ca/data/aoi"))
    a = ap.parse_args()
    a.out.mkdir(parents=True, exist_ok=True)
    adm0 = gpd.GeoDataFrame(pd.concat([fetch(i, "ADM0", a.out) for i in ISO3], ignore_index=True), crs=4326)
    adm1 = gpd.GeoDataFrame(pd.concat([fetch(i, "ADM1", a.out) for i in ISO3], ignore_index=True), crs=4326)
    adm0[["iso3", "shapeName", "geometry"]].to_file(a.out / "ca_adm0.geojson", driver="GeoJSON")
    adm1[["iso3", "shapeName", "geometry"]].to_file(a.out / "ca_adm1.geojson", driver="GeoJSON")
    union = adm0.union_all().simplify(0.01)
    gpd.GeoDataFrame({"name": ["Central Asia (KAZ, KGZ, TJK, TKM, UZB)"]}, geometry=[union], crs=4326) \
        .to_file(a.out / "aoi_request.geojson", driver="GeoJSON")
    area = adm0.to_crs(SINU).area / 1e6
    summary = {"countries": dict(zip(adm0["iso3"], area.round().astype(int))),
               "total_km2": int(area.sum()), "expected_1km_cells": int(area.sum() / 0.8586),
               "adm1_regions": int(len(adm1)), "bbox_lon_lat": [round(v, 3) for v in adm0.total_bounds]}
    (a.out / "aoi_summary.json").write_text(json.dumps(summary, indent=2))
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    main()