Datasets:
Download scripts/build.py from asterisk-labs/rumi-api-fixtures: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/datasets/asterisk-labs/rumi-api-fixtures/resolve/main/scripts/build.py
- Command line
-
hf download hf://datasets/asterisk-labs/rumi-api-fixtures/scripts/build.py
-
curl -L -o build.py https://huggingface.co/datasets/asterisk-labs/rumi-api-fixtures/resolve/main/scripts/build.py
13.1 kB
| #!/usr/bin/env python3 | |
| """Build deterministic Rumi API fixtures from a local EarthCompress checkout.""" | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import hashlib | |
| import json | |
| import subprocess | |
| import sys | |
| from dataclasses import dataclass | |
| from datetime import datetime, timedelta | |
| from pathlib import Path | |
| import geozl | |
| import numpy as np | |
| import rumi | |
| ROOT = Path(__file__).resolve().parents[1] | |
| DEFAULT_EARTHCOMPRESS = ROOT.parent / "ec-benchmark" | |
| GRAPH = "planar>zigzag>zstd" | |
| PATTERNS = { | |
| "tile": "b (row h) (col w) -> row col b (h w)", | |
| "planar": "b (row h) (col w) -> row col (b h w)", | |
| "chunky": "b (row h) (col w) -> row col (h w b)", | |
| "time": "t b (row h) (col w) -> row col t b (h w)", | |
| } | |
| class Fixture: | |
| name: str | |
| corpus: str | |
| sample_index: int | |
| layout: str | |
| tile_size: int | |
| purpose: str | |
| temporal: bool = False | |
| georeferenced: bool = False | |
| FIXTURES = ( | |
| Fixture( | |
| "s2-00-tile", | |
| "s2-l1c-10m-4", | |
| 0, | |
| "tile", | |
| 256, | |
| "window and band-selective reads", | |
| georeferenced=True, | |
| ), | |
| Fixture( | |
| "s2-01-tile", "s2-l1c-10m-4", 1, "tile", 256, "batch reads", georeferenced=True | |
| ), | |
| Fixture( | |
| "s2-02-tile", "s2-l1c-10m-4", 2, "tile", 256, "batch reads", georeferenced=True | |
| ), | |
| Fixture( | |
| "s2-00-planar", | |
| "s2-l1c-10m-4", | |
| 0, | |
| "planar", | |
| 256, | |
| "planar frame layout", | |
| georeferenced=True, | |
| ), | |
| Fixture( | |
| "s2-00-chunky", | |
| "s2-l1c-10m-4", | |
| 0, | |
| "chunky", | |
| 256, | |
| "pixel-interleaved frame layout", | |
| georeferenced=True, | |
| ), | |
| Fixture( | |
| "era5-t2m-00-time", | |
| "era5-t2m-1h", | |
| 0, | |
| "time", | |
| 256, | |
| "temporal selections and ragged edges", | |
| temporal=True, | |
| ), | |
| Fixture( | |
| "alphaearth-00", "alphaearth-v1-64", 0, "tile", 256, "signed int8 with 64 bands" | |
| ), | |
| Fixture("emit-00", "emit-l2a-285", 0, "tile", 64, "signed int16 with 285 bands"), | |
| Fixture("s1-00", "s1-grd-iw-2", 0, "tile", 256, "signed radar values"), | |
| Fixture( | |
| "worldcover-00", "esa-wc-v200", 0, "tile", 256, "single-band categorical data" | |
| ), | |
| ) | |
| def digest(data: bytes) -> str: | |
| return hashlib.sha256(data).hexdigest() | |
| def array_digest(array: np.ndarray) -> str: | |
| return digest(np.ascontiguousarray(array).tobytes(order="C")) | |
| def serialize_time(values) -> list: | |
| if not values: | |
| return [] | |
| serialized = [] | |
| for value in values: | |
| if isinstance(value, tuple): | |
| serialized.append([part.isoformat() for part in value]) | |
| else: | |
| serialized.append(value.isoformat()) | |
| return serialized | |
| def manifest_rows(corpus: Path) -> list[dict[str, str]]: | |
| with (corpus / "manifest.csv").open(newline="") as stream: | |
| return list(csv.DictReader(stream)) | |
| def git_revision(repository: Path) -> str: | |
| result = subprocess.run( | |
| ["git", "-C", str(repository), "rev-parse", "HEAD"], | |
| check=True, | |
| capture_output=True, | |
| text=True, | |
| ) | |
| return result.stdout.strip() | |
| def source_metadata(row: dict[str, str]) -> dict[str, str]: | |
| names = ( | |
| "site", | |
| "regime", | |
| "lon", | |
| "lat", | |
| "variable", | |
| "units", | |
| "scale", | |
| "offset", | |
| "band_order", | |
| "start_utc", | |
| "hours", | |
| "year", | |
| "dataset_version", | |
| "model_version", | |
| ) | |
| return {name: row[name] for name in names if row.get(name)} | |
| def time_axis(row: dict[str, str]) -> list[str]: | |
| start = datetime.fromisoformat(row["start_utc"]) | |
| count = int(row["hours"]) | |
| return [(start + timedelta(hours=index)).isoformat() for index in range(count)] | |
| def georeferencing(row: dict[str, str]) -> dict[str, object]: | |
| scale = float(row["native_scale_m"]) | |
| return { | |
| "crs": row["crs"], | |
| "transform": ( | |
| scale, | |
| 0.0, | |
| float(row["translate_x"]), | |
| 0.0, | |
| -scale, | |
| float(row["translate_y"]), | |
| ), | |
| } | |
| S2_BANDS = [ | |
| "B2, Blue, 496.6nm (S2A) / 492.1nm (S2B)", | |
| "B3, Green, 560nm (S2A) / 559nm (S2B)", | |
| "B4, Red, 664.5nm (S2A) / 665nm (S2B)", | |
| "B8, NIR, 835.1nm (S2A) / 833nm (S2B)", | |
| ] | |
| def year(value: int) -> list[tuple[str, str]]: | |
| """A sample whose acquisition day is unknown covers its whole year.""" | |
| return [(f"{value}-01-01", f"{value + 1}-01-01")] | |
| def labels(fixture: Fixture, row: dict[str, str], bands: int) -> dict[str, list]: | |
| """Band texts and time steps; every Rumi file carries both.""" | |
| if fixture.corpus.startswith("s2-"): | |
| return {"bands": S2_BANDS, "time": year(2023)} | |
| if fixture.corpus.startswith("era5-"): | |
| return {"bands": ["t2m, 2 metre air temperature, K"], "time": time_axis(row)} | |
| if fixture.corpus.startswith("alphaearth-"): | |
| axes = row["band_order"].split("|") | |
| return { | |
| "bands": [f"{a}, AlphaEarth satellite embedding axis {int(a[1:])}" for a in axes], | |
| "time": year(int(row["year"])), | |
| } | |
| if fixture.corpus.startswith("emit-"): | |
| return { | |
| "bands": [f"Band {b + 1}, EMIT L2A surface reflectance" for b in range(bands)], | |
| "time": year(2023), | |
| } | |
| if fixture.corpus.startswith("s1-"): | |
| return { | |
| "bands": [ | |
| "VV, vertical transmit and receive backscatter, dB", | |
| "VH, vertical transmit, horizontal receive backscatter, dB", | |
| ], | |
| "time": year(2023), | |
| } | |
| if fixture.corpus.startswith("esa-wc-"): | |
| return {"bands": ["Map, ESA WorldCover 2021 v200 land cover class"], "time": year(2021)} | |
| raise KeyError(fixture.corpus) | |
| def logical_array(array: np.ndarray, temporal: bool) -> np.ndarray: | |
| if temporal: | |
| if array.ndim != 3: | |
| raise ValueError(f"temporal fixture needs (T,Y,X), got {array.shape}") | |
| return np.ascontiguousarray(array[:, np.newaxis, :, :]) | |
| if array.ndim == 2: | |
| array = array[np.newaxis, :, :] | |
| if array.ndim != 3: | |
| raise ValueError(f"image fixture needs (B,Y,X), got {array.shape}") | |
| return np.ascontiguousarray(array) | |
| def probe_for(array: np.ndarray, tile_size: int) -> tuple[dict, np.ndarray]: | |
| height, width = array.shape[-2:] | |
| row = min(max(tile_size - 19, 0), max(height - 1, 0)) | |
| column = min(max(tile_size - 23, 0), max(width - 1, 0)) | |
| window = ( | |
| row, | |
| column, | |
| min(91, height - row), | |
| min(107, width - column), | |
| ) | |
| bands = array.shape[-3] | |
| selected_bands = [bands - 1, 0] if bands > 1 else [0] | |
| kwargs: dict[str, object] = { | |
| "bands": selected_bands, | |
| "window": list(window), | |
| } | |
| r, c, h, w = window | |
| if array.ndim == 4: | |
| selected_time = [array.shape[0] - 1, 0] | |
| kwargs["time"] = selected_time | |
| expected = array[selected_time][:, selected_bands, r : r + h, c : c + w] | |
| else: | |
| expected = array[selected_bands, r : r + h, c : c + w] | |
| return kwargs, np.ascontiguousarray(expected) | |
| def build(earthcompress: Path) -> None: | |
| earthcompress = earthcompress.resolve() | |
| sys.path.insert(0, str(earthcompress)) | |
| from earthcompress.corpus import load_samples | |
| data_dir = ROOT / "data" | |
| header_dir = ROOT / "headers" | |
| data_dir.mkdir(exist_ok=True) | |
| header_dir.mkdir(exist_ok=True) | |
| source_cache: dict[tuple[str, int], tuple[np.ndarray, dict[str, str]]] = {} | |
| source_revision = git_revision(earthcompress) | |
| records = [] | |
| checksum_lines = [] | |
| for fixture in FIXTURES: | |
| key = (fixture.corpus, fixture.sample_index) | |
| if key not in source_cache: | |
| corpus = earthcompress / "corpora" / fixture.corpus | |
| sample = load_samples(corpus, limit=fixture.sample_index + 1)[-1] | |
| row = manifest_rows(corpus)[fixture.sample_index] | |
| if row["id"] != sample.id: | |
| raise ValueError(f"manifest/sample mismatch for {fixture.name}") | |
| source_cache[key] = (sample.array, row) | |
| source, row = source_cache[key] | |
| array = logical_array(source, fixture.temporal) | |
| frames = rumi.frames(array, PATTERNS[fixture.layout], fixture.tile_size) | |
| graphs = {} | |
| for frame in frames: | |
| graph_key = (frame.data.dtype.str, frame.data.shape) | |
| graph = graphs.get(graph_key) | |
| if graph is None: | |
| graph = graphs[graph_key] = geozl.graph(frame.data, GRAPH) | |
| frame.compressed = geozl.compress(frame.data, graph=graph) | |
| write_options: dict[str, object] = labels(fixture, row, array.shape[-3]) | |
| if fixture.georeferenced: | |
| write_options.update(georeferencing(row)) | |
| data_path = data_dir / f"{fixture.name}.rumi" | |
| header_path = header_dir / f"{fixture.name}.header" | |
| _, header = rumi.write(data_path, frames, **write_options) | |
| header_path.write_bytes(header) | |
| info = rumi.info(source=data_path, header=header) | |
| decoded = np.asarray(rumi.read(data_path, header)) | |
| if not np.array_equal(decoded, array): | |
| raise ValueError(f"round-trip mismatch for {fixture.name}") | |
| probe_kwargs, expected = probe_for(array, fixture.tile_size) | |
| read_kwargs = dict(probe_kwargs) | |
| read_kwargs["window"] = tuple(read_kwargs["window"]) | |
| actual = np.asarray(rumi.read(data_path, header, **read_kwargs)) | |
| if not np.array_equal(actual, expected): | |
| raise ValueError(f"probe mismatch for {fixture.name}") | |
| data_hash = digest(data_path.read_bytes()) | |
| header_hash = digest(header) | |
| checksum_lines.extend( | |
| ( | |
| f"{data_hash} data/{data_path.name}", | |
| f"{header_hash} headers/{header_path.name}", | |
| ) | |
| ) | |
| records.append( | |
| { | |
| "name": fixture.name, | |
| "purpose": fixture.purpose, | |
| "data": f"data/{data_path.name}", | |
| "header": f"headers/{header_path.name}", | |
| "source": { | |
| "repository": "https://github.com/csaybar/ec-benchmark", | |
| "revision": source_revision, | |
| "corpus": fixture.corpus, | |
| "sample_id": row["id"], | |
| "input_sha256": row["input_sha256"], | |
| "metadata": source_metadata(row), | |
| }, | |
| "shape": list(info.shape), | |
| "dtype": np.dtype(info.dtype).name, | |
| "tile": list(info.tile), | |
| "frame_layout": info.frame_layout, | |
| "index_order": list(info.index_order), | |
| "frames": info.frames, | |
| "time_count": info.time_count, | |
| "bands": info.bands, | |
| "time": serialize_time(info.time), | |
| "time_kind": info.time_kind, | |
| "crs": info.crs, | |
| "transform": list(info.transform) if info.transform else None, | |
| "pixel_is_point": info.pixel_is_point, | |
| "size_bytes": data_path.stat().st_size, | |
| "data_sha256": data_hash, | |
| "header_sha256": header_hash, | |
| "array_sha256": array_digest(array), | |
| "probe": { | |
| **probe_kwargs, | |
| "shape": list(expected.shape), | |
| "array_sha256": array_digest(expected), | |
| }, | |
| } | |
| ) | |
| print(f"built {fixture.name}: {data_path.stat().st_size:,} bytes") | |
| batch_names = ["s2-00-tile", "s2-01-tile", "s2-02-tile"] | |
| batch_arrays = [ | |
| logical_array(source_cache[("s2-l1c-10m-4", i)][0], False) for i in range(3) | |
| ] | |
| batch_window = [221, 217, 91, 107] | |
| batch_bands = [3, 0] | |
| r, c, h, w = batch_window | |
| batch_expected = np.stack( | |
| [array[batch_bands, r : r + h, c : c + w] for array in batch_arrays] | |
| ) | |
| manifest = { | |
| "schema_version": 1, | |
| "description": "Deterministic fixtures for the Rumi read API", | |
| "generator": { | |
| "rumi": rumi.__version__, | |
| "geozl": geozl.__version__, | |
| "compression_graph": GRAPH, | |
| }, | |
| "fixtures": records, | |
| "batches": [ | |
| { | |
| "name": "s2-three-scenes", | |
| "fixtures": batch_names, | |
| "bands": batch_bands, | |
| "windows": [batch_window] * len(batch_names), | |
| "shape": list(batch_expected.shape), | |
| "array_sha256": array_digest(batch_expected), | |
| } | |
| ], | |
| } | |
| (ROOT / "manifest.json").write_text( | |
| json.dumps(manifest, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| (ROOT / "checksums.sha256").write_text( | |
| "\n".join(checksum_lines) + "\n", encoding="utf-8" | |
| ) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--earthcompress", type=Path, default=DEFAULT_EARTHCOMPRESS) | |
| args = parser.parse_args() | |
| build(args.earthcompress) | |
| if __name__ == "__main__": | |
| main() | |