""" RockGlacierNet — repair Slope/Aspect in already-downloaded region tiles. The first collect_region.py runs computed terrain AFTER DEM.mosaic(), so the image was in EPSG:4326 (degrees) and GEE produced garbage Slope (~1 deg) and a collapsed Aspect. The Elev band (band 10) is correct. This script recomputes Slope (band 11) and Aspect (band 12) directly from Elev at the tile's metric pixel spacing and overwrites those two bands in place. No re-download needed. (collect_region.py is now fixed, so freshly downloaded tiles don't need this.) python patch_dataset/repair_terrain.py """ import os import sys import glob import numpy as np import rasterio sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import config as C ELEV, SLOPE, ASPECT = 9, 10, 11 # 0-based band indices (B..,NDxx,Elev,Slope,Aspect) def slope_aspect_from_elev(elev, xres, yres): """Horn-style slope/aspect (degrees) from an elevation grid in metres.""" # np.gradient returns dz/drow, dz/dcol; row spacing = yres, col spacing = xres dzdy, dzdx = np.gradient(elev.astype(np.float64), yres, xres) slope = np.degrees(np.arctan(np.hypot(dzdx, dzdy))) # aspect: degrees clockwise from north (0=N, 90=E), 0 where flat aspect = (90.0 - np.degrees(np.arctan2(dzdy, -dzdx))) % 360.0 aspect[(dzdx == 0) & (dzdy == 0)] = 0.0 return slope.astype(np.float32), aspect.astype(np.float32) def main(): tifs = sorted(glob.glob(str(C.RAW_REGION_FEATURES_DIR / "*.tif"))) print(f"Repairing Slope/Aspect in {len(tifs)} tiles…") fixed = 0 for fp in tifs: with rasterio.open(fp) as s: arr = s.read() xres, yres = abs(s.res[0]), abs(s.res[1]) profile = s.profile before = float(arr[SLOPE].mean()) slope, aspect = slope_aspect_from_elev(arr[ELEV], xres, yres) arr[SLOPE] = slope arr[ASPECT] = aspect with rasterio.open(fp, "w", **profile) as dst: dst.write(arr) fixed += 1 if fixed % 25 == 0 or fixed == len(tifs): print(f" {fixed}/{len(tifs)} (last tile slope mean {before:.2f} -> {slope.mean():.2f})") print(f"Done. Repaired {fixed} tiles.") if __name__ == "__main__": main()