Download stage2_windows.py from TMayer77/DenseForestViT: direct link, hf CLI and curl.
- Browser
- Download file 4.15 kB
-
https://huggingface.co/TMayer77/DenseForestViT/resolve/main/stage2_windows.py
- Command line
-
hf download hf://TMayer77/DenseForestViT/stage2_windows.py
-
curl -L -o stage2_windows.py https://huggingface.co/TMayer77/DenseForestViT/resolve/main/stage2_windows.py
4.15 kB
| # stage2_windows.py -- the ONE rule for building Stage 2 model inputs (Colab + HPC) | |
| import numpy as np, rasterio | |
| from scipy.ndimage import map_coordinates | |
| ORDER = ['dem', 'hls', 'landsat', 'landsatidx', 's1', 'tcap', 's2', 's2idx'] # == stage1 meta.json eo_list | |
| PRODUCT = {'s1': 's1Ascending', 'dem': 'DEMindices', 'hls': 'HLS', 'landsat': 'LandsatComposite', | |
| 'landsatidx': 'LandsatIndices', 'tcap': 'landsatTasseledCapIndices', 's2': 'S2Composite', 's2idx': 'S2Indices'} | |
| BANDS = {'s1': ['VV', 'VH', 'ratio', 'ndratio'], 'dem': ['dem', 'slope'], | |
| 'hls': ['NDVI', 'NDWI', 'MNDWI', 'SAVI', 'NDMI', 'NDBI'], 'landsat': ['red', 'green', 'blue', 'nir', 'swir1'], | |
| 'landsatidx': ['NDVI', 'NDWI', 'MNDWI', 'SAVI', 'NDMI', 'NDBI'], | |
| 'tcap': ['brightness', 'greenness', 'wetness', 'fourth', 'fifth', 'sixth'], | |
| 's2': ['red', 'green', 'blue', 'nir', 'swir1'], | |
| 's2idx': ['S2_NDVI', 'S2_NDWI', 'S2_EVI', 'S2_MNDWI', 'S2_SAVI', 'S2_NDMI', 'S2_NDBI']} | |
| CHIP, S0 = 32, 15 # 32x32 window; supervised 3x3 = rows/cols 15:18 | |
| def load_site(site_dir): | |
| # Read the 8 full-AOI tifs; select bands BY NAME; NaN for nodata. | |
| out = {} | |
| for m in ORDER: | |
| with rasterio.open(f'{site_dir}/{PRODUCT[m]}_2024.tif') as s: | |
| desc = list(s.descriptions) | |
| idx = [desc.index(b) + 1 for b in BANDS[m]] if all(desc) else list(range(1, len(BANDS[m]) + 1)) | |
| a = s.read(idx).astype(np.float32) | |
| if s.nodata is not None: a[a == s.nodata] = np.nan | |
| out[m] = dict(a=a, T=s.transform, crs=s.crs) | |
| return out | |
| def centers(site, aoi_bounds=None, stride=3): | |
| # Chip centres on the s1 10 m grid: one chip per output 3x3 block (rows r..r+2, cols c..c+2). | |
| # Centre = top-left corner of s1 pixel (r+1, c+1), so window rows/cols 15:18 land exactly on r..r+2 / c..c+2. | |
| T = site['s1']['T']; H, W = site['s1']['a'].shape[1:] | |
| r0 = c0 = 0; r1, c1 = H - 3, W - 3 | |
| if aoi_bounds is not None: # (lon0, lat0, lon1, lat1) | |
| c0 = max(0, int((aoi_bounds[0] - T.c) / T.a)); c1 = min(W - 3, int((aoi_bounds[2] - T.c) / T.a)) | |
| r0 = max(0, int((aoi_bounds[3] - T.f) / T.e)); r1 = min(H - 3, int((aoi_bounds[1] - T.f) / T.e)) | |
| rr, cc = np.meshgrid(np.arange(r0, r1 + 1, stride), np.arange(c0, c1 + 1, stride), indexing='ij') | |
| rr, cc = rr.ravel(), cc.ravel() | |
| return rr, cc, T.c + (cc + 1) * T.a, T.f + (rr + 1) * T.e | |
| def window(prod, lon, lat): | |
| # 32x32 window at the product's NATIVE resolution centred on (lon, lat); nearest sampling (GEE default); | |
| # NaN -> window median; per-band 0-1 stretch (== training chips). | |
| a, T = prod['a'], prod['T']; j = np.arange(CHIP) - (CHIP / 2 - 0.5) | |
| xs = lon + j * T.a; ys = lat + j * T.e | |
| col = (xs - T.c) / T.a - 0.5; row = (ys - T.f) / T.e - 0.5 | |
| R, C = np.meshgrid(row, col, indexing='ij') | |
| out = np.empty((a.shape[0], CHIP, CHIP), np.float32) | |
| for b in range(a.shape[0]): | |
| v = map_coordinates(a[b], [R, C], order=0, mode='constant', cval=np.nan) | |
| v = np.zeros_like(v) if np.isnan(v).all() else np.where(np.isnan(v), np.nanmedian(v), v) | |
| mn, mx = v.min(), v.max() | |
| out[b] = 0 if mx == mn else (v - mn) / (mx - mn) | |
| return out | |
| def chip(site, lon, lat): | |
| return {m: window(site[m], lon, lat) for m in ORDER} | |
| # ---- validity (added 2026-11-10) ---- | |
| def raw_window(prod, lon, lat): | |
| # same sampling as window(), no fill/stretch: NaN where there is no data | |
| a, T = prod['a'], prod['T']; j = np.arange(CHIP) - (CHIP / 2 - 0.5) | |
| R, C = np.meshgrid((lat + j * T.e - T.f) / T.e - 0.5, (lon + j * T.a - T.c) / T.a - 0.5, indexing='ij') | |
| return np.stack([map_coordinates(a[b], [R, C], order=0, mode='constant', cval=np.nan) for b in range(a.shape[0])]) | |
| def chip_valid(site, lon, lat): | |
| # centre_ok: supervised 3x3 (10 m) has data in s1 and S2; context: min fraction of valid pixels over the 8 windows | |
| cen = all(np.isfinite(raw_window(site[m], lon, lat)[:, S0:S0 + 3, S0:S0 + 3]).all() for m in ['s1', 's2', 's2idx']) | |
| ctx = min(float(np.isfinite(raw_window(site[m], lon, lat)).all(0).mean()) for m in ORDER) | |
| return cen, ctx | |