File size: 3,567 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
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
"""Central Asia downloads (earthaccess, straight from NASA archives; re-runnable, skips existing files).

    python ca/10_download_ca.py lpdaac --products MOD13A3 MCD12Q1 NASADEM
    python ca/10_download_ca.py gesdisc

MOD13A3: Apr-Oct only (what the formula and the model use). NASADEM: only 1-degree tiles touching the AOI.
"""
from __future__ import annotations

import argparse
import json
import re
from pathlib import Path

import geopandas as gpd
from shapely.geometry import box

ROOT = Path("/root/trendex-ca/data")
RAW = ROOT / "raw"
AOI = ROOT / "aoi" / "aoi_request.geojson"
LAST_YEAR = 2025
NDVI_MONTHS = set(range(4, 11))

LPDAAC = {"MOD13A3": ("MOD13A3", "061", "2000-02-01", f"{LAST_YEAR}-12-31"),
          "MCD12Q1": ("MCD12Q1", "061", "2020-01-01", "2020-12-31"),
          "NASADEM": ("NASADEM_HGT", "001", "2000-02-11", "2000-02-21")}
GESDISC = {"GPM_3IMERGM": ("07", "2000-06-01"), "GLDAS_NOAH025_M": ("2.1", "2000-01-01")}


def aoi():
    g = gpd.read_file(AOI).to_crs(4326)
    return g.union_all(), tuple(g.total_bounds)


def granule_name(gr) -> str:
    return gr["umm"].get("GranuleUR", "")


def keep(name: str, product: str, shape) -> bool:
    if product == "MOD13A3":
        m = re.search(r"\.A(\d{4})(\d{3})\.", name)
        if not m:
            return True
        import datetime as dt
        month = (dt.date(int(m[1]), 1, 1) + dt.timedelta(days=int(m[2]) - 1)).month
        return month in NDVI_MONTHS
    if product == "NASADEM":
        m = re.search(r"([ns])(\d{2})([ew])(\d{3})", name.lower())
        if not m:
            return True
        lat = int(m[2]) * (1 if m[1] == "n" else -1)
        lon = int(m[4]) * (1 if m[3] == "e" else -1)
        return shape.intersects(box(lon, lat, lon + 1, lat + 1))
    return True


def lpdaac(products: list[str]) -> None:
    import earthaccess
    earthaccess.login(strategy="netrc")
    shape, bbox = aoi()
    for name in products:
        short, ver, first, last = LPDAAC[name]
        found = earthaccess.search_data(short_name=short, version=ver, temporal=(first, last), bounding_box=bbox)
        sel = [g for g in found if keep(granule_name(g), name, shape)]
        dest = RAW / "earthaccess" / name
        dest.mkdir(parents=True, exist_ok=True)
        print(f"[lpdaac] {name}: {len(found)} granules in bbox, {len(sel)} kept", flush=True)
        earthaccess.download(sel, local_path=str(dest), threads=24)
        print(f"[lpdaac] {name}: {len(list(dest.iterdir()))} files on disk", flush=True)
    print("LPDAAC_COMPLETE", products, flush=True)


def gesdisc() -> None:
    import earthaccess
    earthaccess.login(strategy="netrc")
    _, bbox = aoi()
    for short, (ver, first) in GESDISC.items():
        found = earthaccess.search_data(short_name=short, version=ver, temporal=(first, f"{LAST_YEAR}-12-31"),
                                        bounding_box=bbox)
        dest = RAW / "gesdisc" / short
        dest.mkdir(parents=True, exist_ok=True)
        print(f"[gesdisc] {short}: {len(found)} granules", flush=True)
        earthaccess.download(found, local_path=str(dest), threads=16)
        print(f"[gesdisc] {short}: {len(list(dest.iterdir()))} files on disk", flush=True)
    print("GESDISC_COMPLETE", flush=True)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("step", choices=["lpdaac", "gesdisc"])
    ap.add_argument("--products", nargs="*", default=["MOD13A3", "MCD12Q1", "NASADEM"])
    a = ap.parse_args()
    lpdaac(a.products) if a.step == "lpdaac" else gesdisc()


if __name__ == "__main__":
    main()