Datasets:
Download code/layers/soilgrids.py from enzeeoai/starman: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/datasets/enzeeoai/starman/resolve/main/code/layers/soilgrids.py
- Command line
-
hf download hf://datasets/enzeeoai/starman/code/layers/soilgrids.py
-
curl -L -o soilgrids.py https://huggingface.co/datasets/enzeeoai/starman/resolve/main/code/layers/soilgrids.py
12.9 kB
| """ISRIC SoilGrids 2.0 (1000 m, 0-5 cm): rock fraction, effective grain size and texture, Earth only. | |
| No download step: ``plan()`` returns the four local files in ``data/raw/earth/soilgrids/<var>/``. Per | |
| pixel the stored integers are divided by 10 (ISRIC conversion table: g/kg -> %, cm3/dm3 -> vol %), | |
| sand + silt + clay are renormalized to 100 % (the raw sums are 998-1003 g/kg), and the effective grain | |
| size is the geometric mean diameter of the fine earth (Shirazi & Boersma 1984), | |
| d_g = exp(f_clay ln 0.001 + f_silt ln 0.026 + f_sand ln 1.025) [mm] -> x 1000 = um. | |
| Pixel centres of the Interrupted Goode Homolosine grid are transformed to longitude / latitude and | |
| assigned to cells by centre. Earth only: no Mars rows. ``rock_frac_pct``, ``sand_pct``, ``silt_pct`` and | |
| ``clay_pct`` are Earth-only filters. ``grain_eff_um`` is a texture-derived diameter, not a | |
| validated counterpart of the thermally inferred Mars grain size. | |
| """ | |
| from __future__ import annotations | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| import pyarrow as pa | |
| import rasterio | |
| from pyproj import Transformer | |
| 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 | |
| VERSION = 'v0.2' | |
| SOURCE = { | |
| 'product': 'ISRIC SoilGrids 2.0 aggregated 1000 m, 0-5 cm mean (cfvo, sand, silt, clay)', | |
| 'version': 'v2.0 (files modified 2022-06-02)', | |
| 'url': 'https://files.isric.org/soilgrids/latest/data_aggregated/1000m/', | |
| 'licence': 'CC BY 4.0 (ISRIC data policy; attribution text not quoted, cite Poggio et al. 2021)', | |
| 'planet': 'earth', | |
| } | |
| VARIABLES = ('cfvo', 'sand', 'silt', 'clay') | |
| FILE_PATTERN = '{var}_0-5cm_mean_1000.tif' | |
| NODATA = -32768 | |
| CONVERSION_FACTOR = {'cfvo': 10.0, 'sand': 10.0, 'silt': 10.0, 'clay': 10.0} # ISRIC table: stored / 10 | |
| D_CLAY_MM, D_SILT_MM, D_SAND_MM = 0.001, 0.026, 1.025 | |
| MM_TO_UM = 1000.0 | |
| LOW_COVERAGE = tf.LOW_COVERAGE_FRACTION | |
| ROW_MARGIN = 3 # rows read beyond the group's latitude range | |
| _PCT = {'dtype': 'float32', 'unit': '%', 'comparison': 'planet_specific'} | |
| COLUMNS = { | |
| 'rock_frac_pct': {**_PCT, 'description': 'Mean coarse-fragment volume fraction (cfvo / 10), vol %. ' | |
| 'Earth only: no Mars twin in v0.1'}, | |
| 'rock_frac_pct_std': {**_PCT, 'description': 'Standard deviation of rock_frac_pct over the cell\'s pixels'}, | |
| 'rock_frac_pct_p10': {**_PCT, 'description': '10th percentile of rock_frac_pct'}, | |
| 'rock_frac_pct_p50': {**_PCT, 'description': 'Median rock_frac_pct'}, | |
| 'rock_frac_pct_p90': {**_PCT, 'description': '90th percentile of rock_frac_pct'}, | |
| 'grain_eff_um': {'dtype': 'float32', 'unit': 'um', 'comparison': 'planet_specific', | |
| 'description': 'Effective grain size exp(mean ln d) of the fine earth, d the geometric mean ' | |
| 'diameter (Shirazi & Boersma 1984); no validated thermal-grain counterpart'}, | |
| 'grain_eff_um_p10': {'dtype': 'float32', 'unit': 'um', 'comparison': 'planet_specific', | |
| 'description': '10th percentile of per-pixel grain size'}, | |
| 'grain_eff_um_p90': {'dtype': 'float32', 'unit': 'um', 'comparison': 'planet_specific', | |
| 'description': '90th percentile of per-pixel grain size'}, | |
| 'sand_pct': {**_PCT, 'description': 'Mean sand mass fraction after renormalizing sand+silt+clay to 100 %'}, | |
| 'silt_pct': {**_PCT, 'description': 'Mean silt mass fraction (renormalized)'}, | |
| 'clay_pct': {**_PCT, 'description': 'Mean clay mass fraction (renormalized)'}, | |
| 'n_px': {'dtype': 'int32', 'unit': 'count', 'comparison': 'planet_specific', 'fill': 0, | |
| 'description': '1 km pixels with valid sand, silt and clay whose centre is in the cell'}, | |
| 'valid_frac': {'dtype': 'float32', 'unit': 'fraction', 'comparison': 'planet_specific', 'fill': 0.0, | |
| 'description': 'n_px over the cell area in km2 (SoilGrids pixels are 1 km2), capped at 1'}, | |
| } | |
| LIMITATIONS = [ | |
| 'SoilGrids is weak in deserts; it is masked over ice sheets, glaciers, open water and urban cores, ' | |
| 'and has no Antarctica (flag no_coverage).', | |
| 'The 1000 m aggregation kernel (mean of the 250 m means) is not documented in anything we read.', | |
| 'rock_frac_pct, sand_pct, silt_pct and clay_pct have no Mars twin in v0.1 (Earth-only filters); the ' | |
| 'Mars grain_eff_um is an effective thermal grain size; this is not an absolute pair.', | |
| 'grain_eff_um covers the fine earth only (sand, silt, clay); coarse fragments are in rock_frac_pct.', | |
| 'Cells are assigned by pixel centre; with 1 km pixels a 5 km cell holds ~25 of them.', | |
| 'Pixels outside the valid Homolosine lobes are excluded by inverse/forward projection round-trip; ' | |
| 'a finite inverse alone can alias a different lobe at polar latitudes.', | |
| ] | |
| # -------------------------------------------------------------------------- | |
| # pixel stage (pure numpy) | |
| # -------------------------------------------------------------------------- | |
| def convert(raw: np.ndarray, var: str) -> np.ndarray: | |
| """Stored Int16 -> mapped unit divided by ISRIC's factor (percent); nodata becomes NaN.""" | |
| raw = np.asarray(raw) | |
| return np.where(raw == NODATA, np.nan, raw.astype(np.float64) / CONVERSION_FACTOR[var]) | |
| def renormalize(sand, silt, clay) -> tuple[np.ndarray, np.ndarray, np.ndarray]: | |
| """Scale sand, silt and clay (percent) so they sum to exactly 100; NaN if any is missing.""" | |
| total = sand + silt + clay | |
| with np.errstate(invalid='ignore', divide='ignore'): | |
| scale = np.where(total > 0, 100.0 / total, np.nan) | |
| return sand * scale, silt * scale, clay * scale | |
| def grain_size_um(sand_pct, silt_pct, clay_pct) -> np.ndarray: | |
| """Geometric mean grain diameter in um of renormalized texture percentages.""" | |
| ln_d = (clay_pct * np.log(D_CLAY_MM) + silt_pct * np.log(D_SILT_MM) + sand_pct * np.log(D_SAND_MM)) / 100.0 | |
| return MM_TO_UM * np.exp(ln_d) | |
| def assign_cells(lon, lat, grid, bands: list[int]) -> np.ndarray: | |
| """Index of each (lon, lat) within the band group's cells in grid order, -1 outside the group.""" | |
| lon, lat = np.asarray(lon, dtype=np.float64), np.asarray(lat, dtype=np.float64) | |
| bands = np.asarray(bands) | |
| counts = grid.column_counts[bands].astype(np.int64) | |
| offset = np.concatenate([[0], np.cumsum(counts)[:-1]]) | |
| band = np.searchsorted(grid.edges_deg, lat, side='right') - 1 | |
| band = np.where(lat == 90.0, len(grid.column_counts) - 1, band) | |
| in_group = (band >= bands[0]) & (band <= bands[-1]) & np.isfinite(lat) & np.isfinite(lon) | |
| local = np.clip(band - bands[0], 0, len(bands) - 1) | |
| n = counts[local] | |
| wrapped = (lon + 180.0) % 360.0 - 180.0 | |
| col = np.minimum(((wrapped + 180.0) / 360.0 * n).astype(np.int64), n - 1) | |
| return np.where(in_group, offset[local] + col, -1) | |
| def cell_statistics(cell, rock, sand, silt, clay, n_cells: int) -> dict: | |
| """Per-cell statistics of the pixels of one band group (``cell`` = index in the group, -1 skip).""" | |
| texture_ok = (cell >= 0) & np.isfinite(sand) & np.isfinite(silt) & np.isfinite(clay) | |
| rock_ok = (cell >= 0) & np.isfinite(rock) | |
| out = {name: np.full(n_cells, np.nan) for name in COLUMNS} | |
| n_px = np.bincount(cell[texture_ok], minlength=n_cells)[:n_cells] | |
| out['n_px'] = n_px | |
| if rock_ok.any(): | |
| c, v = cell[rock_ok], rock[rock_ok] | |
| p, counts, _ = tf.grouped_percentiles(v, c, n_cells, (10, 50, 90)) | |
| total = np.bincount(c, weights=v, minlength=n_cells)[:n_cells] | |
| squares = np.bincount(c, weights=v * v, minlength=n_cells)[:n_cells] | |
| has = counts > 0 | |
| mean = np.where(has, total / np.maximum(counts, 1), np.nan) | |
| out['rock_frac_pct'] = mean | |
| out['rock_frac_pct_std'] = np.where(has, np.sqrt(np.maximum(squares / np.maximum(counts, 1) - mean ** 2, 0)), np.nan) | |
| out['rock_frac_pct_p10'], out['rock_frac_pct_p50'], out['rock_frac_pct_p90'] = p | |
| if texture_ok.any(): | |
| c = cell[texture_ok] | |
| s, si, cl = sand[texture_ok], silt[texture_ok], clay[texture_ok] | |
| grain = grain_size_um(s, si, cl) | |
| has = n_px > 0 | |
| for name, values in (('sand_pct', s), ('silt_pct', si), ('clay_pct', cl)): | |
| out[name] = np.where(has, np.bincount(c, weights=values, minlength=n_cells)[:n_cells] / np.maximum(n_px, 1), np.nan) | |
| mean_ln = np.bincount(c, weights=np.log(grain), minlength=n_cells)[:n_cells] / np.maximum(n_px, 1) | |
| out['grain_eff_um'] = np.where(has, np.exp(mean_ln), np.nan) | |
| p, _, _ = tf.grouped_percentiles(grain, c, n_cells, (10, 90)) | |
| out['grain_eff_um_p10'], out['grain_eff_um_p90'] = p | |
| return out | |
| # -------------------------------------------------------------------------- | |
| # driver interface | |
| # -------------------------------------------------------------------------- | |
| def plan(band_group, ctx): | |
| return [{'key': f'soilgrids:{var}', 'url': str(Path(ctx.raw_dir) / var / FILE_PATTERN.format(var=var)), | |
| 'method': 'local'} for var in VARIABLES] | |
| def _row_window(src, grid, bands) -> tuple[int, int]: | |
| """Rows of the raster that can hold pixels of the group (y depends only on latitude in IGH).""" | |
| lat_lo, lat_hi = float(grid.edges_deg[bands[0]]), float(grid.edges_deg[bands[-1] + 1]) | |
| to_igh = Transformer.from_crs('EPSG:4326', src.crs, always_xy=True) | |
| ys = [] | |
| for lon in (-100.0, -60.0, 20.0, 30.0): | |
| for lat in (lat_lo, lat_hi): | |
| _, y = to_igh.transform(lon, max(min(lat, 90.0), -90.0)) | |
| if np.isfinite(y): | |
| ys.append(y) | |
| if not ys: | |
| return 0, 0 | |
| top = src.transform.f | |
| height_px = abs(src.transform.e) | |
| first = int(np.floor((top - max(ys)) / height_px)) - ROW_MARGIN | |
| last = int(np.ceil((top - min(ys)) / height_px)) + ROW_MARGIN | |
| return max(first, 0), min(last, src.height) | |
| def read_group_pixels(paths: dict, grid, bands: list[int]) -> dict: | |
| """lon/lat of every valid pixel of the group's rows, and the converted variables.""" | |
| with rasterio.open(paths['sand']) as ref: | |
| r0, r1 = _row_window(ref, grid, bands) | |
| crs, transform, width = ref.crs, ref.transform, ref.width | |
| empty = {'lon': np.zeros(0), 'lat': np.zeros(0), **{v: np.zeros(0) for v in VARIABLES}} | |
| if r1 <= r0: | |
| return empty | |
| stacks = {} | |
| for var in VARIABLES: | |
| with rasterio.open(paths[var]) as src: | |
| if (src.crs != crs) or src.transform != transform: | |
| raise ValueError(f'{paths[var]}: grid differs from the sand layer') | |
| stacks[var] = src.read(1, window=Window(0, r0, width, r1 - r0)) | |
| any_valid = np.zeros(stacks['sand'].shape, dtype=bool) | |
| for var in VARIABLES: | |
| any_valid |= stacks[var] != NODATA | |
| rows, cols = np.nonzero(any_valid) | |
| if rows.size == 0: | |
| return empty | |
| x = transform.c + (cols + 0.5) * transform.a | |
| y = transform.f + (rows + r0 + 0.5) * transform.e | |
| lon, lat = Transformer.from_crs(crs, 'EPSG:4326', always_xy=True).transform(x, y) | |
| out = {'lon': np.asarray(lon), 'lat': np.asarray(lat)} | |
| for var in VARIABLES: | |
| out[var] = convert(stacks[var][rows, cols], var) | |
| round_x, round_y = Transformer.from_crs('EPSG:4326', crs, always_xy=True).transform(lon, lat) | |
| valid = (np.isfinite(out['lon']) & np.isfinite(out['lat']) & | |
| (np.abs(np.asarray(round_x) - x) < 0.001) & | |
| (np.abs(np.asarray(round_y) - y) < 0.001)) | |
| return {k: v[valid] for k, v in out.items()} | |
| def reduce(band_group, items, ctx): | |
| paths = {f.key.split(':', 1)[1]: Path(f.path) for f in items.all()} | |
| grid, bands = ctx.grid, ctx.bands | |
| cells = ctx.cells(band_group) | |
| n_cells = len(cells) | |
| pixels = read_group_pixels(paths, grid, bands) | |
| cell = assign_cells(pixels['lon'], pixels['lat'], grid, bands) | |
| sand, silt, clay = renormalize(pixels['sand'], pixels['silt'], pixels['clay']) | |
| stats = cell_statistics(cell, pixels['cfvo'], sand, silt, clay, n_cells) | |
| area = cells['area_km2'].to_numpy() | |
| n_px = stats['n_px'] | |
| with np.errstate(invalid='ignore', divide='ignore'): | |
| valid_frac = np.where(area > 0, np.minimum(n_px / area, 1.0), 0.0) | |
| flags = [] | |
| for n, v in zip(n_px, valid_frac): | |
| if n == 0: | |
| flags.append('no_coverage') | |
| elif v < LOW_COVERAGE: | |
| flags.append('low_coverage') | |
| else: | |
| flags.append('') | |
| table = {'region_id': cells['region_id']} | |
| for name, spec in COLUMNS.items(): | |
| values = n_px if name == 'n_px' else valid_frac if name == 'valid_frac' else stats[name] | |
| table[name] = pa.array(np.asarray(values), type=pa.type_for_alias(spec['dtype'])) | |
| table['quality_flags'] = pa.array(flags, type=pa.string()) | |
| return pa.table(table) | |