Spaces:
Sleeping
Sleeping
Download vicoffee_predict_core.py from minhcreus/vicoffee-coffee-mapper: direct link, hf CLI and curl.
- Browser
- Download file 23.2 kB
-
https://huggingface.co/spaces/minhcreus/vicoffee-coffee-mapper/resolve/main/vicoffee_predict_core.py
- Command line
-
hf download hf://spaces/minhcreus/vicoffee-coffee-mapper/vicoffee_predict_core.py
-
curl -L -o vicoffee_predict_core.py https://huggingface.co/spaces/minhcreus/vicoffee-coffee-mapper/resolve/main/vicoffee_predict_core.py
23.2 kB
| """ViCoffee coffee-map prediction: MAESTRO Tiny (setup H) on a Sentinel-2 L2A time series.""" | |
| import io, json, math, re, zipfile, tempfile | |
| from pathlib import Path | |
| import numpy as np | |
| import torch, torch.nn as nn | |
| DEVICE = "cuda" if torch.cuda.is_available() else "cpu" | |
| AMP_ON, AMP_DTYPE = DEVICE == "cuda", torch.bfloat16 | |
| BANDS = ["B02", "B03", "B04", "B05", "B06", "B07", "B08", "B8A", "B11", "B12"] # training order | |
| CLEAR_SCL = (4, 5, 6, 7) | |
| N_BANDS, N_CLASSES, CROP, PATCH, BINS, STRIDE, TTA_DRAWS = 10, 2, 16, 2, 16, 8, 4 | |
| PRESETS = {"tiny": dict(dim=192, depth=12, heads=3), "small": dict(dim=384, depth=12, heads=6)} | |
| # test sites of each fold (report Table IV.9); a site is checked with the fold that never trained on it | |
| FOLD_TEST = {0: ["p01", "p06"], 1: ["p02", "p10"], 2: ["p03", "p08"], 3: ["p04", "p09"], 4: ["p05", "p07"]} | |
| # fallback normalisation (unlabelled windows, same as training); the pretrain checkpoint's own copy wins | |
| NORM = {"q05": [210, 397, 192, 229, 143, 150, 128, 121, 101, 73], | |
| "median": [495, 755, 614, 1233, 2595, 3088, 3138, 3414, 2419, 1261], | |
| "q95": [1494, 1668, 1744, 2190, 3830, 4612, 4617, 4997, 3843, 2725]} | |
| TRAIN_B2_MEDIAN = 495.0 | |
| # ---------------- model (same code as the v1.2 notebook) ---------------- | |
| def temporal_features(doy, days_since_ref): | |
| d = doy / 365.25 | |
| r = (days_since_ref / 365.25).unsqueeze(-1).expand(*doy.shape, 4) | |
| return torch.cat([torch.stack([torch.sin(2 * math.pi * d), torch.cos(2 * math.pi * d), | |
| torch.sin(4 * math.pi * d), torch.cos(4 * math.pi * d)], -1), r], -1) | |
| def sincos_2d(dim, g): | |
| y, x = torch.meshgrid(torch.arange(g, dtype=torch.float32), torch.arange(g, dtype=torch.float32), indexing="ij") | |
| om = 1.0 / 10000 ** (torch.arange(dim // 4, dtype=torch.float32) / (dim // 4)) | |
| return torch.cat([f(c.flatten()[:, None] * om[None]) for c in (y, x) for f in (torch.sin, torch.cos)], 1) | |
| def patchify(x, P): | |
| B, T, C, H, W = x.shape | |
| g = H // P | |
| x = x.reshape(B, T, C, g, P, g, P).permute(0, 1, 3, 5, 4, 6, 2) | |
| return x.reshape(B, T, g * g, P * P * C) | |
| def safe_mask(kpm): | |
| return None if kpm is None else kpm & ~kpm.all(1, keepdim=True) | |
| class Block(nn.Module): | |
| def __init__(self, dim, heads, mlp=4.0): | |
| super().__init__() | |
| self.n1, self.n2 = nn.LayerNorm(dim), nn.LayerNorm(dim) | |
| self.attn = nn.MultiheadAttention(dim, heads, batch_first=True) | |
| self.mlp = nn.Sequential(nn.Linear(dim, int(dim * mlp)), nn.GELU(), nn.Linear(int(dim * mlp), dim)) | |
| def forward(self, x, kpm=None): | |
| h = self.n1(x) | |
| x = x + self.attn(h, h, h, key_padding_mask=kpm, need_weights=False)[0] | |
| return x + self.mlp(self.n2(x)) | |
| class Encoder(nn.Module): | |
| def __init__(self, in_ch=10, patch=2, crop=16, dim=192, depth=12, heads=3, **_): | |
| super().__init__() | |
| self.P, self.C, self.g, self.dim = patch, in_ch, crop // patch, dim | |
| self.embed = nn.Linear(patch * patch * in_ch, dim) | |
| self.register_buffer("pos", sincos_2d(dim - 8, self.g), persistent=False) | |
| self.te = nn.Linear(8, 8, bias=False) | |
| self.blocks = nn.ModuleList(Block(dim, heads) for _ in range(depth)) | |
| self.norm = nn.LayerNorm(dim) | |
| def forward(self, x, tfeat, kpm=None): | |
| B, T = x.shape[:2] | |
| S = self.g * self.g | |
| pe = torch.cat([self.pos[None, None].expand(B, T, S, -1), self.te(tfeat)[:, :, None].expand(B, T, S, 8)], -1) | |
| z = (self.embed(patchify(x, self.P)) + pe).reshape(B, T * S, self.dim) | |
| kpm = safe_mask(kpm) | |
| for b in self.blocks: | |
| z = b(z, kpm) | |
| return self.norm(z) | |
| class Segmenter(nn.Module): | |
| def __init__(self, encoder, n_classes, spatial=False, **_): | |
| super().__init__() | |
| self.encoder, self.K, self.spatial = encoder, n_classes, spatial | |
| d = encoder.dim | |
| self.query = nn.Parameter(torch.zeros(1, 1, d)) | |
| self.pn = nn.LayerNorm(d) | |
| self.pool = nn.MultiheadAttention(d, max(1, d // 64), batch_first=True) | |
| self.out = nn.Linear(d, n_classes * encoder.P ** 2) | |
| if spatial: | |
| self.refine = nn.Sequential(nn.Conv2d(d, d, 3, padding=1, groups=d), nn.Conv2d(d, d, 1), nn.GELU(), | |
| nn.Conv2d(d, d, 3, padding=1, groups=d), nn.Conv2d(d, d, 1)) | |
| def forward(self, x, tfeat, kpm=None): | |
| B, T = x.shape[:2] | |
| g, P, d = self.encoder.g, self.encoder.P, self.encoder.dim | |
| z = self.encoder(x, tfeat, kpm=kpm) | |
| z = self.pn(z.reshape(B, T, g * g, d).transpose(1, 2).reshape(B * g * g, T, d)) | |
| pm = None if kpm is None else safe_mask(kpm.reshape(B, T, g * g).transpose(1, 2).reshape(B * g * g, T)) | |
| pooled = self.pool(self.query.expand(B * g * g, 1, d), z, z, key_padding_mask=pm, need_weights=False)[0].squeeze(1) | |
| if self.spatial: | |
| h = pooled.reshape(B, g, g, d).permute(0, 3, 1, 2) | |
| pooled = pooled + self.refine(h).permute(0, 2, 3, 1).reshape(B * g * g, d) | |
| lg = self.out(pooled).reshape(B, g, g, P, P, self.K) | |
| return lg.permute(0, 5, 1, 3, 2, 4).reshape(B, self.K, g * P, g * P) | |
| # ---------------- loading weights ---------------- | |
| def _members(paths): | |
| """Yield (name, loader) for every .pt inside the given files, folders and zips.""" | |
| for p in map(Path, paths): | |
| if p.is_dir(): | |
| for q in sorted(p.rglob("*")): | |
| if q.suffix == ".zip": | |
| yield from _members([q]) | |
| elif q.suffix == ".pt": | |
| yield q.as_posix(), (lambda q=q: torch.load(q, map_location="cpu", weights_only=False)) | |
| elif p.suffix == ".zip": | |
| z = zipfile.ZipFile(p) | |
| for n in z.namelist(): | |
| if n.endswith(".pt"): | |
| yield n, (lambda z=z, n=n: torch.load(io.BytesIO(z.read(n)), map_location="cpu", weights_only=False)) | |
| elif p.suffix == ".pt": | |
| yield p.as_posix(), (lambda p=p: torch.load(p, map_location="cpu", weights_only=False)) | |
| def load_models(paths, ratio="1.0"): | |
| """FT weights (weights zip) are used when present; otherwise LP = pretrained encoder + LP head (session bundle).""" | |
| ft, lp, enc = {}, {}, None | |
| for name, get in _members(paths): | |
| base = name.rsplit("/", 1)[-1] | |
| m = re.fullmatch(rf"FT_f(\d)_r{re.escape(ratio)}_best\.pt", base) | |
| if m: | |
| f = int(m.group(1)) | |
| # a weights zip can hold several setups: prefer setup H (folder H_pre400) | |
| if f not in ft or "H_pre400/" in name or "/" not in name: | |
| ft[f] = get | |
| m = re.fullmatch(rf"f(\d)_r{re.escape(ratio)}_s(\d)\.pt", base) | |
| if m and "lp_heads" in name and int(m.group(1)) not in lp: | |
| lp[int(m.group(1))] = get | |
| if base.startswith("mae_") and base.endswith(".pt") and "/pretrain/" in "/" + name and not base.endswith(".part.pt"): | |
| enc = get | |
| norm = {k: np.asarray(v, "f4") for k, v in NORM.items()} | |
| enc_ck = enc() if enc else None | |
| if enc_ck is not None and "norm_stats" in enc_ck: | |
| norm = {k: np.asarray(enc_ck["norm_stats"][k], "f4").ravel() for k in ("q05", "median", "q95")} | |
| models, kind = {}, None | |
| if ft: | |
| kind = "FT" | |
| for f, get in sorted(ft.items()): | |
| w = get() | |
| m = Segmenter(Encoder(N_BANDS, w["patch"], w["crop"], **PRESETS[w["encoder_size"]]), w["n_classes"], spatial=w.get("spatial", False)) | |
| m.load_state_dict(w["model"], strict=False) | |
| models[f] = m.to(DEVICE).eval() | |
| elif lp and enc_ck is not None: | |
| kind = "LP" | |
| size = enc_ck.get("model", "tiny") if isinstance(enc_ck.get("model"), str) else "tiny" | |
| for f, get in sorted(lp.items()): | |
| head = get() | |
| spatial = any(k.startswith("refine.") for k in head) | |
| m = Segmenter(Encoder(N_BANDS, enc_ck.get("patch", PATCH), enc_ck.get("crop", CROP), **PRESETS[size]), N_CLASSES, spatial=spatial) | |
| m.encoder.load_state_dict(enc_ck["encoder"], strict=False) | |
| m.load_state_dict(head, strict=False) | |
| models[f] = m.to(DEVICE).eval() | |
| if not models: | |
| raise FileNotFoundError("No weights found. Give the weights zip (FT_f*_r1.0_best.pt) or the session bundle " | |
| "(pretrain/mae_*.pt plus lp_heads/).") | |
| st = {k: norm[k][None, :, None, None] for k in norm} | |
| st["range"] = np.maximum(st["q95"] - st["q05"], 1e-6) | |
| return dict(models=models, kind=kind, norm=st) | |
| # ---------------- inference ---------------- | |
| def make_bins(T, nb=BINS): | |
| if T < nb: # fewer dates than bins: reuse dates | |
| return np.round(np.linspace(0, T - 1, nb)).astype(int)[:, None] | |
| parts = np.array_split(np.arange(T), nb) | |
| idx = np.full((nb, max(len(p) for p in parts)), -1) | |
| for i, p in enumerate(parts): | |
| idx[i, :len(p)] = p | |
| return idx | |
| def pick_dates_eval(xn, cnt, bins): | |
| idx, ok = np.maximum(bins, 0), bins >= 0 | |
| xb = np.where(ok[..., None], xn.reshape(len(xn), -1)[idx], np.nan) | |
| mad = np.abs(xb - np.nanmedian(xb, 1, keepdims=True)).mean(-1) | |
| c = np.where(ok, cnt[idx], -1) | |
| mad[(c < 0.95 * c.max(1, keepdims=True)) | ~ok] = np.inf | |
| return idx[np.arange(len(bins)), mad.argmin(1)] | |
| def pick_dates(cnt, bins, rng): | |
| idx, ok = np.maximum(bins, 0), bins >= 0 | |
| cand = ok & (cnt[idx] > 0) | |
| none = ~cand.any(1) | |
| cand[none] = ok[none] | |
| return idx[np.arange(len(bins)), (rng.random(bins.shape) * cand).argmax(1)] | |
| def tile_pos(H, W, stride=STRIDE): | |
| return [(r, c) for r in sorted(set(range(0, H - CROP + 1, stride)) | {H - CROP}) | |
| for c in sorted(set(range(0, W - CROP + 1, stride)) | {W - CROP})] | |
| def make_crops(X, clear, doy, norm, pos, rng=None): | |
| bins = make_bins(len(X)) | |
| xs, cls, ds = [], [], [] | |
| for r, c in pos: | |
| cl = clear[:, r:r + CROP, c:c + CROP] | |
| if rng is None: | |
| xn = ((np.clip(X[:, :, r:r + CROP, c:c + CROP].astype("f4"), norm["q05"], norm["q95"]) - norm["median"]) / norm["range"]) * cl[:, None] | |
| k = pick_dates_eval(xn, cl.sum((1, 2)), bins) | |
| xs.append(xn[k].astype(np.float16)) | |
| else: | |
| k = pick_dates(cl.sum((1, 2)), bins, rng) | |
| xn = ((np.clip(X[k, :, r:r + CROP, c:c + CROP].astype("f4"), norm["q05"], norm["q95"]) - norm["median"]) / norm["range"]) * cl[k][:, None] | |
| xs.append(xn.astype(np.float16)) | |
| cls.append(cl[k]) | |
| ds.append(doy[k]) | |
| return np.stack(xs), np.stack(cls), np.stack(ds) | |
| VIEWS = [(k, f) for k in range(4) for f in (False, True)] | |
| def _view(a, k, f): | |
| a = np.rot90(a, k, axes=(-2, -1)) | |
| return a[..., ::-1] if f else a | |
| def _unview(a, k, f): | |
| return np.rot90(a[..., ::-1] if f else a, -k, axes=(-2, -1)) | |
| def _predict_crops(model, x, cl, doy, tta): | |
| chunk = 512 if DEVICE == "cuda" else 64 | |
| out = 0.0 | |
| views = VIEWS if tta else [(0, False)] | |
| for k, f in views: | |
| xv, cv, prob = np.ascontiguousarray(_view(x, k, f)), np.ascontiguousarray(_view(cl, k, f)), [] | |
| for a in range(0, len(x), chunk): | |
| xa = torch.from_numpy(xv[a:a + chunk]).to(DEVICE).float() | |
| ca = torch.from_numpy(cv[a:a + chunk]).to(DEVICE) | |
| B, T, g = ca.shape[0], ca.shape[1], CROP // PATCH | |
| kpm = ~ca.reshape(B, T, g, PATCH, g, PATCH).any(5).any(3).reshape(B, T * g * g) | |
| d = torch.from_numpy(np.asarray(doy[a:a + chunk], "f4")).to(DEVICE) | |
| with torch.autocast(DEVICE, dtype=AMP_DTYPE, enabled=AMP_ON): | |
| prob.append(model(xa, temporal_features(d, d - 1), kpm).float().softmax(1).cpu().numpy()) | |
| out = out + _unview(np.concatenate(prob), k, f) | |
| return out / len(views) | |
| def predict(W, X, clear, doy, tta=False, folds=None, progress=None): | |
| """X: (T, 10, H, W) reflance x10000, clear: (T, H, W) bool, doy: (T,) day of year, one calendar year. | |
| Returns the coffee probability (H, W), averaged over the fold models.""" | |
| T, C, H, Wd = X.shape | |
| assert C == N_BANDS, f"need 10 bands, got {C}" | |
| if H < CROP or Wd < CROP: | |
| raise ValueError(f"image is {H}x{Wd} px; it must be at least {CROP}x{CROP} px") | |
| order = np.argsort(doy) | |
| X, clear, doy = X[order], clear[order], np.asarray(doy)[order] | |
| pos = tile_pos(H, Wd) | |
| folds = [f for f in (folds or W["models"]) if f in W["models"]] | |
| acc, cnt = np.zeros((H, Wd), "f4"), np.zeros((H, Wd), "f4") | |
| draws = TTA_DRAWS if tta else 1 | |
| crops = [make_crops(X, clear, doy, W["norm"], pos, None if dr == 0 else np.random.default_rng([0, dr])) for dr in range(draws)] | |
| n, done = len(folds) * draws, 0 | |
| for f in folds: | |
| for x, cl, d in crops: | |
| prob = _predict_crops(W["models"][f], x, cl, d, tta)[:, 1] | |
| for k, (r, c) in enumerate(pos): | |
| acc[r:r + CROP, c:c + CROP] += prob[k] | |
| cnt[r:r + CROP, c:c + CROP] += 1 | |
| done += 1 | |
| if progress: | |
| progress(done / n) | |
| return acc / cnt | |
| # ---------------- reading inputs ---------------- | |
| DATE_RE = re.compile(r"(20\d\d)[-_]?([01]\d)[-_]?([0-3]\d)") | |
| def doy_of(date): | |
| d = np.datetime64(date[:10], "D") | |
| return int((d - np.datetime64(date[:4] + "-01-01", "D")).astype(int)) + 1 | |
| def _date_from_name(name): | |
| m = DATE_RE.search(Path(name).name) | |
| if not m: | |
| raise ValueError(f"no date (YYYY-MM-DD or YYYYMMDD) in file name: {Path(name).name}") | |
| return f"{m.group(1)}-{m.group(2)}-{m.group(3)}" | |
| def read_tifs(files): | |
| """One GeoTIFF per date: 10 bands in BANDS order, optional 11th band = SCL.""" | |
| import rasterio | |
| rows, profile = [], None | |
| for fp in sorted(files, key=lambda p: _date_from_name(p)): | |
| with rasterio.open(fp) as src: | |
| a = src.read() | |
| if profile is None: | |
| profile = dict(crs=src.crs, transform=src.transform, height=src.height, width=src.width) | |
| elif (src.height, src.width) != (profile["height"], profile["width"]): | |
| raise ValueError(f"{Path(fp).name} is {src.height}x{src.width}, the first file is {profile['height']}x{profile['width']}; all dates must share one grid") | |
| if a.shape[0] not in (10, 11): | |
| raise ValueError(f"{Path(fp).name} has {a.shape[0]} bands; need 10 (B2,B3,B4,B5,B6,B7,B8,B8A,B11,B12) or 11 (+ SCL)") | |
| rows.append((_date_from_name(fp), a)) | |
| X = np.stack([a[:10] for _, a in rows]).astype("f4") | |
| scl = np.stack([a[10] for _, a in rows]) if rows[0][1].shape[0] == 11 else None | |
| return dict(X=X, scl=scl, dates=[d for d, _ in rows], profile=profile) | |
| def read_array_file(fp): | |
| """.npz or .h5 with X (T,10,H,W), dates (T,), and SCL (T,H,W) or clear (T,H,W) if available.""" | |
| fp = Path(fp) | |
| if fp.suffix == ".npz": | |
| z = np.load(fp, allow_pickle=False) | |
| get = lambda k: z[k] if k in z.files else None | |
| else: | |
| import h5py | |
| z = h5py.File(fp, "r") | |
| get = lambda k: z[k][:] if k in z else None | |
| X = get("X") | |
| if X is None: | |
| raise ValueError("the file needs an array named X with shape (T, 10, H, W)") | |
| dates = [d.decode() if isinstance(d, bytes) else str(d) for d in get("dates")] | |
| scl, clear = get("SCL"), get("clear") | |
| out = dict(X=X.astype("f4"), scl=scl, dates=dates, profile=None) | |
| if clear is not None: | |
| out["clear"], out["given"] = clear.astype(bool), ("clear",) | |
| return out | |
| def read_upload(paths): | |
| paths = [Path(p) for p in (paths if isinstance(paths, (list, tuple)) else [paths])] | |
| tifs, other = [], [] | |
| tmp = Path(tempfile.mkdtemp()) | |
| for p in paths: | |
| if p.suffix.lower() == ".zip": | |
| with zipfile.ZipFile(p) as z: | |
| for n in z.namelist(): | |
| if n.lower().endswith((".tif", ".tiff")) and not n.startswith("__MACOSX"): | |
| q = tmp / Path(n).name | |
| q.write_bytes(z.read(n)) | |
| tifs.append(q) | |
| elif n.lower().endswith((".npz", ".h5")): | |
| q = tmp / Path(n).name | |
| q.write_bytes(z.read(n)) | |
| other.append(q) | |
| elif p.suffix.lower() in (".tif", ".tiff"): | |
| tifs.append(p) | |
| elif p.suffix.lower() in (".npz", ".h5", ".hdf5"): | |
| other.append(p) | |
| if other: | |
| d = read_array_file(other[0]) | |
| elif tifs: | |
| d = read_tifs(tifs) | |
| else: | |
| raise ValueError("no .tif, .zip of .tif, .npz or .h5 found in the upload") | |
| if "clear" not in d: | |
| d["clear"] = np.isin(d["scl"], CLEAR_SCL) if d["scl"] is not None else np.ones((len(d["X"]),) + d["X"].shape[2:], bool) | |
| d["X"] = np.nan_to_num(d["X"]) | |
| return d | |
| def check_scale(X, clear): | |
| """Median clear B2 should be near the training value (about 500). Returns a note or ''.""" | |
| b2 = X[:, 0][clear] | |
| if b2.size == 0: | |
| return "No clear pixels in the image." | |
| m = float(np.median(b2)) | |
| if m < 2: | |
| return f"Band values look like 0-1 reflectance (median B2 {m:.3f}); multiply by 10000 first." | |
| if m > 1100: | |
| return (f"Median clear B2 is {m:.0f}, training data is about {TRAIN_B2_MEDIAN:.0f}. The 1000 offset of processing " | |
| "baseline 04.00+ may still be in the data: tick 'Remove the 1000 offset' or export from S2_SR_HARMONIZED.") | |
| return "" | |
| def split_years(dates): | |
| years = sorted({d[:4] for d in dates}) | |
| return {y: np.array([i for i, d in enumerate(dates) if d[:4] == y]) for y in years} | |
| # ---------------- fetch from Earth Search (AWS) ---------------- | |
| def fetch_s2(lat, lon, size_km, year, max_cloud=90, progress=None): | |
| """Download an L2A series around (lat, lon) for one year from the Earth Search STAC (public, no account).""" | |
| import pystac_client | |
| cat = pystac_client.Client.open("https://earth-search.aws.element84.com/v1") | |
| half = size_km / 2 / 111.32 | |
| bbox = [lon - half / math.cos(math.radians(lat)), lat - half, lon + half / math.cos(math.radians(lat)), lat + half] | |
| items = list(cat.search(collections=["sentinel-2-l2a"], bbox=bbox, datetime=f"{year}-01-01/{year}-12-31", | |
| query={"eo:cloud_cover": {"lt": max_cloud}}).items()) | |
| if not items: | |
| raise ValueError("no Sentinel-2 L2A scenes found for that place and year") | |
| return read_items(items, bbox, progress) | |
| def read_items(items, bbox, progress=None, grid=None): | |
| """Read 10 bands + SCL of STAC items over a lon/lat bbox (or a UTM grid (x0, y1, width, height)) onto one 10 m grid.""" | |
| import rasterio | |
| from rasterio.warp import transform as warp_xy | |
| from rasterio.windows import from_bounds | |
| from rasterio.enums import Resampling | |
| # keep the MGRS tile seen most often, one scene per day | |
| tiles = [i.properties.get("grid:code") or i.properties.get("s2:mgrs_tile") for i in items] | |
| best = max(set(tiles), key=tiles.count) | |
| by_day = {} | |
| for i, t in zip(items, tiles): | |
| if t == best: | |
| by_day.setdefault(i.datetime.date().isoformat(), i) | |
| days = sorted(by_day) | |
| keymap = {"B02": "blue", "B03": "green", "B04": "red", "B05": "rededge1", "B06": "rededge2", "B07": "rededge3", | |
| "B08": "nir", "B8A": "nir08", "B11": "swir16", "B12": "swir22", "SCL": "scl"} | |
| first = by_day[days[0]] | |
| with rasterio.open(first.assets[keymap["B02"]].href) as src: | |
| crs = src.crs | |
| if grid: | |
| x0, y1, gw, gh = grid | |
| x1, y0 = x0 + 10 * gw, y1 - 10 * gh | |
| else: | |
| xs, ys = warp_xy("EPSG:4326", crs, [bbox[0], bbox[2]], [bbox[1], bbox[3]]) | |
| x0, x1 = math.floor(min(xs) / 10) * 10, math.ceil(max(xs) / 10) * 10 | |
| y0, y1 = math.floor(min(ys) / 10) * 10, math.ceil(max(ys) / 10) * 10 | |
| H, Wd = int((y1 - y0) / 10), int((x1 - x0) / 10) | |
| X = np.zeros((len(days), 10, H, Wd), "f4") | |
| scl = np.zeros((len(days), H, Wd), "u1") | |
| from concurrent.futures import ThreadPoolExecutor | |
| def read_one(job): | |
| t, b, name = job | |
| it = by_day[days[t]] | |
| pb = float(it.properties.get("s2:processing_baseline", "0") or 0) | |
| off = 1000.0 if pb >= 4.0 and not it.properties.get("earthsearch:boa_offset_applied", False) else 0.0 | |
| with rasterio.Env(GDAL_DISABLE_READDIR_ON_OPEN="EMPTY_DIR", CPL_VSIL_CURL_ALLOWED_EXTENSIONS=".tif", GDAL_HTTP_MAX_RETRY="4"): | |
| with rasterio.open(it.assets[keymap[name]].href) as src: | |
| win = from_bounds(x0, y0, x1, y1, src.transform) | |
| a = src.read(1, window=win, out_shape=(H, Wd), resampling=Resampling.nearest, boundless=True, fill_value=0) | |
| if name == "SCL": | |
| scl[t] = a | |
| else: | |
| X[t, b] = np.maximum(a.astype("f4") - off, 0) | |
| jobs = [(t, b, n) for t in range(len(days)) for b, n in enumerate(BANDS + ["SCL"])] | |
| with ThreadPoolExecutor(16) as ex: | |
| for k, _ in enumerate(ex.map(read_one, jobs)): | |
| if progress and (k + 1) % 11 == 0: | |
| progress((k + 1) / len(jobs), f"date {(k + 1) // 11}/{len(days)}") | |
| from rasterio.transform import from_origin | |
| profile = dict(crs=crs, transform=from_origin(x0, y1, 10, 10), height=H, width=Wd) | |
| return dict(X=X, scl=scl, clear=np.isin(scl, CLEAR_SCL), dates=days, profile=profile) | |
| # ---------------- pictures and files ---------------- | |
| def rgb_composite(X, clear, doy): | |
| dry = (doy <= 120) | (doy >= 335) | |
| use = dry if dry.sum() >= 3 else np.ones_like(dry) | |
| rgb = np.stack([np.nanmedian(np.where(clear[use], X[use, b], np.nan), 0) for b in (2, 1, 0)], -1) | |
| rgb = np.where(np.isnan(rgb), np.nanmedian(np.stack([np.where(clear, X[:, b], np.nan) for b in (2, 1, 0)], -1), 0), rgb) | |
| rgb = np.nan_to_num(rgb) | |
| lo, hi = np.percentile(rgb, 0.5, (0, 1)), np.percentile(rgb, 97, (0, 1)) | |
| x = np.clip((rgb - lo) / np.maximum(hi - lo, 1e-6), 0, 1) ** 0.6 | |
| return (x * 255).astype(np.uint8) | |
| def overlay(rgb, mask, color=(232, 160, 40), alpha=0.55): | |
| out = rgb.astype("f4").copy() | |
| out[mask] = out[mask] * (1 - alpha) + np.array(color, "f4") * alpha | |
| return out.astype(np.uint8) | |
| def upscale(img, target=640): | |
| k = max(1, int(target / max(img.shape[:2]))) | |
| return np.repeat(np.repeat(img, k, 0), k, 1) | |
| def prob_image(prob): | |
| p = np.clip(prob, 0, 1)[..., None] | |
| lo, hi = np.array([58, 127, 200], "f4"), np.array([232, 160, 40], "f4") | |
| return (lo * (1 - p) + hi * p).astype(np.uint8) | |
| def write_geotiff(path, prob, profile): | |
| import rasterio | |
| pred = (prob >= 0.5).astype("u1") | |
| meta = dict(driver="GTiff", count=2, dtype="uint8", compress="deflate", height=prob.shape[0], width=prob.shape[1]) | |
| if profile: | |
| meta.update(crs=profile["crs"], transform=profile["transform"]) | |
| with rasterio.open(path, "w", **meta) as dst: | |
| dst.write(pred, 1) | |
| dst.write((np.clip(prob, 0, 1) * 100).round().astype("u1"), 2) | |
| dst.set_band_description(1, "coffee (1) / not coffee (0)") | |
| dst.set_band_description(2, "coffee probability, percent") | |
| def miou(pred, label): | |
| ok = label != 255 | |
| p, l = pred[ok].astype(int), label[ok].astype(int) | |
| ious = [] | |
| for c in (0, 1): | |
| inter, union = ((p == c) & (l == c)).sum(), ((p == c) | (l == c)).sum() | |
| ious.append(inter / max(union, 1)) | |
| return float(np.mean(ious)), ious | |