Datasets:
Download code/layers/worldcover.py from enzeeoai/starman: direct link, hf CLI and curl.
- Browser
- Download file 13.5 kB
-
https://huggingface.co/datasets/enzeeoai/starman/resolve/main/code/layers/worldcover.py
- Command line
-
hf download hf://datasets/enzeeoai/starman/code/layers/worldcover.py
-
curl -L -o worldcover.py https://huggingface.co/datasets/enzeeoai/starman/resolve/main/code/layers/worldcover.py
13.5 kB
| """ESA WorldCover 2021 v200 class fractions per cell, Earth only, from the x4 overview. | |
| ``plan()`` returns the 3-degree v200 tiles that intersect the band group, one item per tile whose | |
| ``fetch`` reads only the rows of the group from the x4 overview (never the 10 m level) and hands them to | |
| the driver cache (charged to ``--cache-max-gb``; the driver retries transient errors and stops the | |
| band group on a permanent one). ``reduce()`` assigns each overview pixel to a cell by its centre and | |
| counts classes, streaming one tile at a time. Every row carries the flag ``overview_resampled``. | |
| Open sea is coded 0 in some places and 80 in others (S-A), so neither code 0 nor class 80 is used to find | |
| ocean. A cell none of whose pixels was read (no tile) gets valid_frac = 0, NaN fractions and the flag | |
| ``no_tile``. A valid pixel is a pixel with one of the 11 class codes. | |
| Mars rows are not written; no Mars bare-ground fraction is inferred from this Earth product. | |
| """ | |
| from __future__ import annotations | |
| import io | |
| import json | |
| import re | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| import pyarrow as pa | |
| import rasterio | |
| from rasterio.errors import RasterioIOError | |
| from rasterio.windows import Window | |
| _PIPELINE = str(Path(__file__).resolve().parent.parent) | |
| if _PIPELINE not in sys.path: | |
| sys.path.insert(0, _PIPELINE) | |
| import terrain_features as tf # noqa: E402 | |
| from layers import driver # noqa: E402 | |
| VERSION = 'v0.1' | |
| SOURCE = { | |
| 'product': 'ESA WorldCover 10 m 2021 v200 (x4 overview)', | |
| 'version': 'v200 (2021)', | |
| 'url': 's3://esa-worldcover/v200/2021/map/', | |
| 'licence': 'CC BY 4.0; "(c) ESA WorldCover project 2021 / Contains modified Copernicus Sentinel data ' | |
| '(2021) processed by ESA WorldCover consortium"', | |
| 'planet': 'earth', | |
| } | |
| CLASS_CODES = (10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100) | |
| CLASS_NAMES = ('tree', 'shrub', 'grass', 'crop', 'built', 'bare', 'snow', 'water', 'wetland', 'mangrove', 'moss') | |
| FRAC_COLUMNS = tuple(f'{name}_frac' for name in CLASS_NAMES) | |
| INVALID = len(CLASS_CODES) # counts column for code 0 and any code that is not a class | |
| SURFACE_NOT_GROUND_CLASSES = ('tree', 'mangrove', 'built') | |
| SURFACE_NOT_GROUND_THRESHOLD = 0.20 # provisional historical flag; never an implicit eligibility rule | |
| LOW_COVERAGE = tf.LOW_COVERAGE_FRACTION | |
| TILE_DEG = 3 | |
| NATIVE_PPD = 12000 # 10 m: 36000 pixels per 3 degree tile | |
| OVERVIEW_FACTOR = 4 # the x4 level (overview index 1); never 1 | |
| WORLDCOVER_ROOT = 's3://esa-worldcover/v200/2021/map' | |
| TILE_PATTERN = 'ESA_WorldCover_10m_2021_v200_{name}_Map.tif' | |
| GDAL_ENV = {'AWS_NO_SIGN_REQUEST': 'YES', 'AWS_DEFAULT_REGION': 'eu-central-1', | |
| 'GDAL_DISABLE_READDIR_ON_OPEN': 'EMPTY_DIR'} | |
| _FRAC = {'dtype': 'float32', 'unit': 'fraction', 'comparison': 'planet_specific'} | |
| COLUMNS = { | |
| **{f'{name}_frac': {**_FRAC, 'description': f'Fraction of valid pixels in class {code} ({name})'} | |
| for name, code in zip(CLASS_NAMES, CLASS_CODES)}, | |
| 'lc_major': {'dtype': 'int16', 'unit': 'code', 'comparison': 'categorical', 'fill': 0, | |
| 'description': 'Majority WorldCover class code (ties go to the lowest code; 0 = no valid pixel)'}, | |
| 'surface_not_ground': {'dtype': 'bool', 'unit': 'flag', 'comparison': 'planet_specific', 'fill': False, | |
| 'description': '(tree + mangrove + built) fraction >= SURFACE_NOT_GROUND_THRESHOLD ' | |
| '(0.20), provisional canopy/roof indicator; use only if explicitly requested. ' | |
| 'False with no valid pixels is unknown, not bare ground'}, | |
| 'n_px': {'dtype': 'int32', 'unit': 'count', 'comparison': 'planet_specific', 'fill': 0, | |
| 'description': 'x4-overview pixels read whose centre is in the cell'}, | |
| 'valid_frac': {'dtype': 'float32', 'unit': 'fraction', 'comparison': 'planet_specific', 'fill': 0.0, | |
| 'description': 'Valid pixels over the pixels the cell would hold with full tile coverage'}, | |
| } | |
| COLUMNS['bare_frac']['description'] += '. Earth-only; no Mars value is inferred.' | |
| LIMITATIONS = [ | |
| 'Read from the x4 overview (about 40 m): every overview pixel is one pixel of its 4 x 4 parent block ' | |
| '(nearest-style), so fractions differ from full resolution (S-A: up to 0.03 for built-up in a city).', | |
| 'Open sea is coded 0 (nodata) in some places and 80 in others; class 80 is not ocean and code 0 is not ' | |
| '"outside the tile". valid_frac is low where sea is coded 0.', | |
| 'No Antarctica; the north limit is 82.75 N (flag no_tile).', | |
| 'Class 70 (snow and ice) and 100 (moss and lichen) are reported as the product codes them.', | |
| 'Every row has flag overview_resampled.', | |
| 'surface_not_ground uses a 0.20 threshold that has not been tuned against Copernicus bias yet.', | |
| ] | |
| # -------------------------------------------------------------------------- | |
| # geometry | |
| # -------------------------------------------------------------------------- | |
| def overview_ppd() -> float: | |
| return NATIVE_PPD / OVERVIEW_FACTOR | |
| def tile_name(lat_sw: int, lon_sw: int) -> str: | |
| return f"{'N' if lat_sw >= 0 else 'S'}{abs(lat_sw):02d}{'E' if lon_sw >= 0 else 'W'}{abs(lon_sw):03d}" | |
| def group_tile_corners(grid, bands: list[int]) -> list[tuple[int, int]]: | |
| """South-west corners (lat, lon) of the 3 degree tiles intersecting the band group, west to east.""" | |
| lat_lo = max(float(grid.edges_deg[bands[0]]), -90.0) | |
| lat_hi = min(float(grid.edges_deg[bands[-1] + 1]), 90.0) | |
| first = int(np.floor(lat_lo / TILE_DEG)) * TILE_DEG | |
| last = int(np.ceil(lat_hi / TILE_DEG)) * TILE_DEG | |
| return [(lat, lon) for lat in range(first, last, TILE_DEG) for lon in range(-180, 180, TILE_DEG)] | |
| def tile_rows(lat_sw: int, lat_lo: float, lat_hi: float) -> tuple[int, int]: | |
| """Overview rows [first, stop) of a tile whose centre latitude lies in [lat_lo, lat_hi).""" | |
| ppd = overview_ppd() | |
| n_rows = int(round(TILE_DEG * ppd)) | |
| top = lat_sw + TILE_DEG | |
| # row i centre latitude = top - (i + 0.5) / ppd | |
| first = int(np.ceil((top - lat_hi) * ppd - 0.5 + 1e-9)) | |
| stop = int(np.ceil((top - lat_lo) * ppd - 0.5 - 1e-9)) | |
| return max(first, 0), min(max(stop, first), n_rows) | |
| def expected_pixels(grid, bands: list[int]) -> np.ndarray: | |
| """Overview pixel centres each cell of the group would hold with full coverage, in grid order.""" | |
| ppd = overview_ppd() | |
| n_rows, n_cols = int(round(180 * ppd)), int(round(360 * ppd)) | |
| lat = 90.0 - (np.arange(n_rows) + 0.5) / ppd | |
| band = np.searchsorted(grid.edges_deg, lat, side='right') - 1 | |
| rows_in_band = np.bincount(band, minlength=len(grid.column_counts)) | |
| lon = -180.0 + (np.arange(n_cols) + 0.5) / ppd | |
| out = [] | |
| for b in bands: | |
| n = int(grid.column_counts[b]) | |
| col = np.minimum(((lon + 180.0) / 360.0 * n).astype(np.int64), n - 1) | |
| out.append(np.bincount(col, minlength=n) * int(rows_in_band[b])) | |
| return np.concatenate(out).astype(np.int64) | |
| def count_classes(window: np.ndarray, lat_sw: int, lon_sw: int, first_row: int, grid, bands: list[int], | |
| counts: np.ndarray) -> None: | |
| """Add the class counts of one tile window to ``counts`` (n_cells x 12), assigning pixels by centre.""" | |
| ppd = overview_ppd() | |
| n_rows, n_cols = window.shape | |
| lut = np.full(256, INVALID, dtype=np.int64) | |
| for i, code in enumerate(CLASS_CODES): | |
| lut[code] = i | |
| klass = lut[window] | |
| lat = lat_sw + TILE_DEG - (first_row + np.arange(n_rows) + 0.5) / ppd | |
| lon = lon_sw + (np.arange(n_cols) + 0.5) / ppd | |
| band_of_row = np.searchsorted(grid.edges_deg, lat, side='right') - 1 | |
| group_counts = grid.column_counts[bands].astype(np.int64) | |
| offset = np.concatenate([[0], np.cumsum(group_counts)[:-1]]) | |
| for local, b in enumerate(bands): | |
| rows = np.nonzero(band_of_row == b)[0] | |
| if rows.size == 0: | |
| continue | |
| n = int(group_counts[local]) | |
| col = np.minimum(((lon + 180.0) / 360.0 * n).astype(np.int64), n - 1) | |
| key = (offset[local] + col)[None, :] * (INVALID + 1) + klass[rows[0]:rows[-1] + 1] | |
| counts += np.bincount(key.ravel(), minlength=counts.size).reshape(counts.shape) | |
| def fractions(counts: np.ndarray, expected: np.ndarray) -> dict: | |
| """Class fractions over valid pixels, majority class, threshold flag, n_px and valid_frac.""" | |
| classes = counts[:, :INVALID].astype(np.float64) | |
| valid = classes.sum(axis=1) | |
| n_px = counts.sum(axis=1) | |
| with np.errstate(invalid='ignore', divide='ignore'): | |
| frac = np.where(valid[:, None] > 0, classes / np.maximum(valid, 1)[:, None], np.nan) | |
| valid_frac = np.where(expected > 0, valid / np.maximum(expected, 1), 0.0) | |
| major = np.where(valid > 0, np.array(CLASS_CODES)[classes.argmax(axis=1)], 0) # ties: lowest code | |
| index = [CLASS_NAMES.index(n) for n in SURFACE_NOT_GROUND_CLASSES] | |
| sng = np.where(valid > 0, frac[:, index].sum(axis=1) >= SURFACE_NOT_GROUND_THRESHOLD, False) | |
| return {'frac': frac, 'lc_major': major, 'surface_not_ground': sng.astype(bool), 'n_px': n_px, | |
| 'valid_frac': np.minimum(valid_frac, 1.0), 'valid': valid} | |
| # -------------------------------------------------------------------------- | |
| # driver interface | |
| # -------------------------------------------------------------------------- | |
| def fetch_tile_window(item, out) -> None: | |
| """Read the group's rows of one tile from the x4 overview and write them as .npy to the cache.""" | |
| meta = item.meta | |
| level = int(np.log2(OVERVIEW_FACTOR)) - 1 | |
| first, stop = meta['rows'] | |
| try: | |
| with rasterio.Env(**GDAL_ENV): | |
| with rasterio.open(driver.gdal_path(item.url), overview_level=level) as src: | |
| array = src.read(1, window=Window(0, first, src.width, stop - first)) | |
| except RasterioIOError as exc: | |
| text = str(exc) | |
| if any(s in text for s in ('No such file', 'does not exist', 'not recognized', '404')): | |
| raise driver.ItemAbsent(f'{item.url}: {text}') from exc | |
| raise driver.TransientError(f'{item.url}: {text}') from exc | |
| buffer = io.BytesIO() | |
| np.save(buffer, array, allow_pickle=False) | |
| out.name = 'window.npy' | |
| out.write(buffer.getvalue()) | |
| GRID_URL = 'https://esa-worldcover.s3.eu-central-1.amazonaws.com/v200/2021/esa_worldcover_grid.geojson' | |
| _TILE_NAME = re.compile(r'^[NS]\d{2}[EW]\d{3}$') | |
| def tiles_from_grid_geojson(path: Path) -> set[str]: | |
| """Tile names (``N00E009``) found anywhere in the properties of the official tile grid.""" | |
| names = set() | |
| for feature in json.loads(Path(path).read_text(encoding='utf8')).get('features', []): | |
| for value in (feature.get('properties') or {}).values(): | |
| if isinstance(value, str) and _TILE_NAME.match(value): | |
| names.add(value) | |
| return names | |
| def prepare(ctx): | |
| """Fetch the official tile grid (small) so plan() can skip the ocean tiles that do not exist.""" | |
| path = ctx.download(GRID_URL) | |
| names = tiles_from_grid_geojson(path) | |
| if names: | |
| ctx.state['worldcover_tiles'] = names | |
| ctx.record_source_file(path) | |
| def plan(band_group, ctx): | |
| grid, bands = ctx.grid, ctx.bands | |
| lat_lo, lat_hi = float(grid.edges_deg[bands[0]]), float(grid.edges_deg[bands[-1] + 1]) | |
| known = ctx.state.get('worldcover_tiles') | |
| items = [] | |
| for lat_sw, lon_sw in group_tile_corners(grid, bands): | |
| name = tile_name(lat_sw, lon_sw) | |
| if known is not None and name not in known: | |
| continue | |
| first, stop = tile_rows(lat_sw, lat_lo, lat_hi) | |
| if stop <= first: | |
| continue | |
| n_cols = int(round(TILE_DEG * overview_ppd())) | |
| root = str(WORLDCOVER_ROOT).rstrip('/') | |
| items.append({'key': f'wc:{name}', 'url': f'{root}/{TILE_PATTERN.format(name=name)}', | |
| 'method': 'api', 'fetch': fetch_tile_window, 'required': False, | |
| 'size': (stop - first) * n_cols + 256, | |
| 'meta': {'tile': name, 'lat_sw': lat_sw, 'lon_sw': lon_sw, 'rows': (first, stop), | |
| 'overview_factor': OVERVIEW_FACTOR}}) | |
| return items | |
| def reduce(band_group, items, ctx): | |
| grid, bands = ctx.grid, ctx.bands | |
| cells = ctx.cells(band_group) | |
| n_cells = len(cells) | |
| counts = np.zeros((n_cells, INVALID + 1), dtype=np.int64) | |
| for fetched in items: | |
| if fetched.absent: | |
| continue | |
| meta = fetched.meta | |
| count_classes(fetched.array(), meta['lat_sw'], meta['lon_sw'], meta['rows'][0], grid, bands, counts) | |
| result = fractions(counts, expected_pixels(grid, bands)) | |
| flags = [] | |
| for n, v, valid in zip(result['n_px'], result['valid_frac'], result['valid']): | |
| own = ['overview_resampled'] | |
| if n == 0: | |
| own.append('no_tile') | |
| elif valid == 0: | |
| own.append('no_valid') | |
| elif v < LOW_COVERAGE: | |
| own.append('low_coverage') | |
| flags.append(';'.join(own)) | |
| table = {'region_id': cells['region_id']} | |
| for i, name in enumerate(FRAC_COLUMNS): | |
| table[name] = pa.array(result['frac'][:, i].astype(np.float32)) | |
| table['lc_major'] = pa.array(result['lc_major'].astype(np.int16)) | |
| table['surface_not_ground'] = pa.array(result['surface_not_ground']) | |
| table['n_px'] = pa.array(result['n_px'].astype(np.int32)) | |
| table['valid_frac'] = pa.array(result['valid_frac'].astype(np.float32)) | |
| table['quality_flags'] = pa.array(flags, type=pa.string()) | |
| return pa.table(table) | |