File size: 6,731 Bytes
49f3de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
"""Fetch <=2018 Sentinel-2 L2A windows around each station (Planetary Computer).



Hard rule: every STAC query is capped at 2018-12-31; scene IDs are logged to a

manifest so the exact inputs are reproducible. For each city-year we keep the

least-cloudy scene per quarter (4 timesteps) at 64x64 px, 10 m (640 m window)

centred on the station -- the OlmoEarth sample geometry at small scale.



Output: data/eo/s2_<city_id>_<year>.npz with array (T=4, C=12, 64, 64) float32

in reflectance units (DN/10000), plus manifest.csv.

Bands (OlmoEarth order): B02 B03 B04 B08 B05 B06 B07 B8A B11 B12 B01 B09

20m/60m bands are read resampled to the 64x64 window (documented choice for

from-scratch training).

"""
from __future__ import annotations

import argparse
import json
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path

import numpy as np
import pandas as pd

sys.path.insert(0, str(Path(__file__).parent))
from dataset import download, load_annual
from leakage import assert_dates_le_cutoff

END = "2018-12-31T23:59:59Z"
BANDS = ["B02", "B03", "B04", "B08", "B05", "B06", "B07", "B8A", "B11", "B12", "B01", "B09"]
SIZE = 64  # px at 10 m


def city_table(root: Path) -> pd.DataFrame:
    annual = load_annual(root)
    cities = (annual.drop_duplicates("ID")[["ID", "Name", "Lat", "Lon"]]
              .rename(columns={"ID": "city_id"}))
    return cities.sort_values("city_id").reset_index(drop=True)


def fetch_city_year(client, city_id: str, lat: float, lon: float, year: int,

                    out_dir: Path) -> tuple[bool, list[dict]]:
    """Returns (ok, manifest_rows). Thread-safe: no shared state."""
    import planetary_computer
    import rasterio
    from rasterio.transform import from_bounds as tf_bounds
    from rasterio.warp import transform as warp_transform
    from rasterio.windows import from_bounds

    out_path = out_dir / f"s2_{city_id}_{year}.npz"
    if out_path.exists():
        return True, []
    dlat = 0.0032
    dlon = 0.0032 / max(np.cos(np.radians(lat)), 0.2)
    bbox = [lon - dlon, lat - dlat, lon + dlon, lat + dlat]
    quarters = [(f"{year}-01-01", f"{year}-03-31"), (f"{year}-04-01", f"{year}-06-30"),
                (f"{year}-07-01", f"{year}-09-30"), (f"{year}-10-01", f"{year}-12-31")]
    timesteps, rows = [], []
    for qi, (q0, q1) in enumerate(quarters):
        assert_dates_le_cutoff([q1], f"STAC quarter end {city_id} {year} Q{qi+1}")
        search = client.search(
            collections=["sentinel-2-l2a"], bbox=bbox,
            datetime=f"{q0}T00:00:00Z/{q1}T23:59:59Z",
            query={"eo:cloud_cover": {"lt": 60}},
            sortby=[{"field": "properties.eo:cloud_cover", "direction": "asc"}],
            max_items=3,
        )
        items = list(search.items())
        if not items:
            return False, []
        item = items[0]
        signed = planetary_computer.sign(item)
        bands_arr = []
        target_bounds = None
        for band in BANDS:
            with rasterio.open(signed.assets[band].href) as src:
                if target_bounds is None:
                    xs, ys = warp_transform("EPSG:4326", src.crs, [lon], [lat])
                    half = SIZE * 10 / 2
                    target_bounds = (xs[0] - half, ys[0] - half,
                                     xs[0] + half, ys[0] + half)
                win = from_bounds(*target_bounds, transform=src.transform)
                arr = src.read(1, window=win, out_shape=(SIZE, SIZE),
                               boundless=True, fill_value=0)
                bands_arr.append(arr.astype(np.float32) / 10000.0)
        timesteps.append(np.stack(bands_arr))
        rows.append({"city_id": city_id, "year": year, "quarter": qi + 1,
                     "scene_id": item.id, "datetime": str(item.datetime),
                     "cloud_cover": item.properties.get("eo:cloud_cover")})
    np.savez_compressed(out_path, data=np.stack(timesteps).astype(np.float32))
    return True, rows


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--years", default="2018,2017", help="priority order")
    ap.add_argument("--limit", type=int, default=0, help="0 = all cities")
    ap.add_argument("--workers", type=int, default=8)
    ap.add_argument("--out", default="data/eo")
    args = ap.parse_args()

    from pystac_client import Client
    root = Path(__file__).resolve().parent.parent
    data_root = download(root / "data" / "_source")
    cities = city_table(data_root)
    if args.limit:
        cities = cities.head(args.limit)
    out_dir = root / args.out
    out_dir.mkdir(parents=True, exist_ok=True)
    client = Client.open("https://planetarycomputer.microsoft.com/api/stac/v1")
    manifest_path = out_dir / "manifest.csv"
    manifest = pd.read_csv(manifest_path).to_dict("records") if manifest_path.exists() else []
    seen = {(str(r["city_id"]), int(r["year"]), int(r["quarter"])) for r in manifest}
    years = [int(y) for y in args.years.split(",")]
    assert_dates_le_cutoff([f"{max(years)}-12-31"], "EO years")

    tasks = [(row["city_id"], float(row["Lat"]), float(row["Lon"]), year)
             for year in years for _, row in cities.iterrows()]
    print(f"{len(tasks)} city-year tasks, {args.workers} workers", flush=True)
    ok = fail = 0
    with ThreadPoolExecutor(max_workers=args.workers) as ex:
        futs = {ex.submit(fetch_city_year, client, c, la, lo, y, out_dir): (c, y)
                for c, la, lo, y in tasks}
        for i, fut in enumerate(as_completed(futs), 1):
            city_id, year = futs[fut]
            try:
                done, rows = fut.result()
            except Exception as exc:
                print(f"FAIL {city_id} {year}: {type(exc).__name__}: {exc}", flush=True)
                done, rows = False, []
            for r in rows:
                key = (str(r["city_id"]), int(r["year"]), int(r["quarter"]))
                if key not in seen:
                    manifest.append(r); seen.add(key)
            ok, fail = ok + bool(done), fail + (not done)
            if i % 20 == 0:
                print(f"... {i}/{len(tasks)}: {ok} ok, {fail} failed", flush=True)
                pd.DataFrame(manifest).to_csv(manifest_path, index=False)
    pd.DataFrame(manifest).to_csv(manifest_path, index=False)
    print(f"done: {ok} city-years ok, {fail} failed; manifest rows={len(manifest)}")
    (out_dir / "fetch_summary.json").write_text(json.dumps(
        {"ok": ok, "failed": fail, "years": years, "bands": BANDS,
         "end_cap": END}, indent=2))


if __name__ == "__main__":
    main()