diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..7da5923516c13ec3d8fc7ef8c4ebcef2585e1e3e --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.cache/ +__pycache__/ +.ipynb_checkpoints/ +*.partial.* diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..33ae011640754011328c0247715d4003bcebadf5 --- /dev/null +++ b/README.md @@ -0,0 +1,163 @@ +--- +license: cc-by-4.0 +configs: + - config_name: annotations + default: true + data_files: + - split: records + path: processed/label.parquet + - config_name: acquisitions + data_files: + - split: records + path: processed/ingest_log.parquet +task_categories: + - image-segmentation +tags: + - remote-sensing + - earth-observation + - sentinel-2 + - land-cover + - geotiff + - geosave +size_categories: + - 1K dict: + """Copy an existing verified spectral layout and keep its calibration and source.""" + src = subset / record["image_path"] + with rasterio.open(src) as reflectance: + names = [reflectance.tags(i)["variable_name"] for i in reflectance.indexes] + if names != BANDS: + raise ValueError("The subset must contain the nine Dynamic World bands") + info = { + "band_scales": list(reflectance.scales), + "band_offsets": list(reflectance.offsets), + } + (processed / image).parent.mkdir(parents=True, exist_ok=True) + (processed / scl).parent.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory(dir=processed) as tmp: + for original, output in [(src, image), (subset / record["scl_path"], scl)]: + pending = Path(tmp) / "asset.tif" + shutil.copyfile(original, pending) + pending.replace(processed / output) + return { + **info, + "provenance": source, + "source_item_ids": record.get("source_item_ids"), + "processing_baselines": record.get("processing_baselines"), + } + + +def safe_error(exc: Exception) -> str: + """Keep diagnostic text without signed asset URL query parameters.""" + return re.sub( + r"(https?://[^\s?'\"]+)\?[^\s'\"]+", r"\1", f"{type(exc).__name__}: {exc}" + )[:1500] + + +def write_paired_benchmark(processed: Path) -> None: + """Mark matched benchmark scenes, with equally sized validation and test sets.""" + labels = pd.read_parquet( + processed / "label.parquet", columns=["scene_id", "split", "benchmark"] + ) + split = labels.loc[labels.benchmark].set_index("scene_id")["split"] + path = processed / "ingest_log.parquet" + log = pd.read_parquet(path) + matched = log.image_path.notna() & log.scl_path.notna() & log.error.isna() + assignment = log.scene_id.map(split).where(matched) + selected = assignment.eq("train") + size = min(assignment.eq("val").sum(), assignment.eq("test").sum()) + for group in ("val", "test"): + scenes = log.loc[assignment.eq(group), "scene_id"].sort_values() + if len(scenes) > size: + scenes = scenes.sample(n=size, random_state=0) + selected |= log.scene_id.isin(scenes) + log["paired_benchmark"] = selected + pending = path.with_suffix(".partial.parquet") + log.to_parquet(pending, index=False) + pending.replace(path) + + +def main( + processed: Path, + subset: Path | None = None, + threads: int = 8, + band_threads: int = 4, + subset_revision: str | None = None, +) -> None: + """Ingest each scene once, reusing existing imagery and retrying errors.""" + labels = pd.read_parquet( + processed / "label.parquet", columns=["scene_id", "label_path", "date", "split"] + ) + scenes = labels.drop_duplicates("scene_id").sort_values(["date", "scene_id"]) + references = {} + subset_source = "fatmur/dynamicworld-300" + if subset_revision is not None: + if subset is None: + raise ValueError("--subset-revision requires --subset") + subset_source += f"@{subset_revision}" + if subset is not None: + subset_labels = pd.read_parquet( + subset / "label.parquet", columns=["scene_id", "label_path"] + ) + subset_log = pd.read_parquet(subset / "ingest_log.parquet") + pairs = subset_labels.merge( + subset_log, on="label_path", validate="one_to_one" + ).dropna(subset=["image_path", "scl_path"]) + references = pairs.set_index("scene_id").to_dict(orient="index") + + log_path = processed / "ingest_log.parquet" + entries = {} + if log_path.exists(): + entries = ( + pd.read_parquet(log_path) + .drop(columns=["paired_benchmark"], errors="ignore") + .set_index("scene_id", drop=False) + .to_dict(orient="index") + ) + + def checkpoint() -> None: + log = pd.DataFrame(entries.values()).sort_values("scene_id") + tmp = log_path.with_suffix(".partial.parquet") + log.to_parquet(tmp, index=False) + tmp.replace(log_path) + + ready = { + key + for key, r in entries.items() + if pd.isna(r["error"]) + and (processed / r["image_path"]).is_file() + and (processed / r["scl_path"]).is_file() + } + pending = scenes.loc[~scenes.scene_id.isin(ready)] + if pending.empty: + write_paired_benchmark(processed) + print(f"All {len(scenes)} scenes are complete.") + return + client = stac.StacClient.planetary_computer() + with ThreadPoolExecutor(threads) as jobs: + + def ingest(scene) -> dict: + image = f"image/{scene.split}/{scene.scene_id}.tif" + scl = f"scl/{scene.split}/{scene.scene_id}.tif" + try: + if subset is not None and scene.scene_id in references: + info = reuse_subset( + subset, + references[scene.scene_id], + processed, + image, + scl, + subset_source, + ) + else: + info = ingest_scene( + client, + processed / scene.label_path, + scene.date, + processed / image, + processed / scl, + pool=band_threads, + ) + info["provenance"] = "planetary-computer/sentinel-2-l2a" + return dict( + scene_id=scene.scene_id, + image_path=image, + scl_path=scl, + error=None, + **info, + ) + except Exception as exc: + return dict( + scene_id=scene.scene_id, + image_path=None, + scl_path=None, + error=safe_error(exc), + provenance=None, + source_item_ids=None, + processing_baselines=None, + band_scales=None, + band_offsets=None, + ) + + futures = { + jobs.submit(ingest, scene): scene.scene_id for scene in pending.itertuples() + } + print( + f"{len(ready)} already complete; attempting {len(futures)} scenes", + flush=True, + ) + completed = 0 + try: + for task in as_completed(futures): + result = task.result() + entries[result["scene_id"]] = result + completed += 1 + if completed % 20 == 0: + checkpoint() + ok = sum(pd.isna(r["error"]) for r in entries.values()) + print( + f"{completed}/{len(futures)} attempted, {ok} matched, {len(entries) - ok} unavailable", + flush=True, + ) + finally: + if entries: + checkpoint() + write_paired_benchmark(processed) + + +if __name__ == "__main__": + typer.run(main) diff --git a/scripts/prepare_labels.py b/scripts/prepare_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..23c7a2efcef2acac971213541b306235f2872660 --- /dev/null +++ b/scripts/prepare_labels.py @@ -0,0 +1,110 @@ +"""Prepare the expert label archive and the nested 3,609/409/409 benchmark. + + python scripts/prepare_labels.py PARENT SUBSET DESTINATION + +PARENT contains the full Dynamic World `processed/label.parquet` and `raw/` +source files. SUBSET contains dynamicworld-300's `processed/label.parquet` +with its 200/50/50 assignment (revision 1037fcb). Image ingestion is separate. +""" + +import argparse +import shutil +from pathlib import Path +from tempfile import TemporaryDirectory + +import geopandas as gpd +import pandas as pd + + +def prepare_labels(parent: Path, subset: Path, destination: Path) -> None: + """Copy original expert annotations once and assign splits by footprint.""" + parent_labels = gpd.read_parquet(parent / "processed/label.parquet") + subset_labels = pd.read_parquet( + subset / "processed/label.parquet", + columns=["annotation_id", "split", "location_id"], + ) + labels = parent_labels.loc[parent_labels["annotation_source"].eq("expert")].copy() + labels["parent_split"] = labels["split"] + + # All alternate expert votes and voting composites for a test location stay together. + consensus = labels["source_group"].eq("expert_composites") & labels[ + "voting_rule" + ].eq("consensus").fillna(False) + test_locations = set(labels.loc[consensus, "location_id"]) + parent_val = ( + labels.loc[ + labels["source_group"].eq("experts") & labels["parent_split"].eq("val"), + "location_id", + ] + .drop_duplicates() + .sort_values() + ) + fixed_val = set(subset_labels.loc[subset_labels["split"].eq("val"), "location_id"]) + if not fixed_val.issubset(parent_val): + raise ValueError( + "The teaching subset's validation locations must belong to parent validation" + ) + candidates = parent_val.loc[~parent_val.isin(fixed_val)] + draw = candidates.sample(n=len(test_locations) - len(fixed_val), random_state=0) + val_locations = fixed_val.union(draw) + + # Use exactly the parent EDA's one footprint per location and intersects predicate. + footprints = parent_labels[["location_id", "geometry"]].drop_duplicates( + "location_id" + ) + held_out = footprints.loc[ + footprints["location_id"].isin(test_locations | val_locations) + ] + intersections = gpd.sjoin( + footprints, held_out[["geometry"]], predicate="intersects" + ) + labels["split"] = "train" + labels.loc[labels["location_id"].isin(intersections["location_id"]), "split"] = ( + "excluded" + ) + labels.loc[labels["location_id"].isin(val_locations), "split"] = "val" + labels.loc[labels["location_id"].isin(test_locations), "split"] = "test" + labels["benchmark"] = ( + labels["source_group"].eq("experts") & labels["split"].isin(["train", "val"]) + ) | (consensus & labels["split"].eq("test")) + labels["label_path"] = "../" + labels["source_path"] + + benchmark = labels.loc[labels["benchmark"]] + counts = benchmark.groupby("split").size().to_dict() + if ( + counts != {"train": 3609, "val": 409, "test": 409} + or not benchmark["scene_id"].is_unique + ): + raise ValueError(f"Unexpected benchmark assignment: {counts}") + inherited = benchmark.set_index("annotation_id")["split"].reindex( + subset_labels["annotation_id"] + ) + if ( + inherited.isna().any() + or not (inherited.to_numpy() == subset_labels["split"].to_numpy()).all() + ): + raise ValueError("The teaching subset must retain its published assignments") + + processed = destination / "processed" + processed.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory(dir=destination) as temp: + pending = Path(temp) / "label" + for relative_path in [*labels["source_path"], "raw/README.txt", "labels.yaml"]: + target = destination / relative_path + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(parent / relative_path, pending) + pending.replace(target) + labels.to_parquet(pending, index=False) + pending.replace(processed / "label.parquet") + + print(f"{len(labels):,} annotations across {labels['scene_id'].nunique():,} scenes") + print(benchmark.groupby("split")["scene_id"].nunique().to_string()) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("parent", type=Path) + parser.add_argument("subset", type=Path) + parser.add_argument("destination", type=Path) + args = parser.parse_args() + prepare_labels(args.parent, args.subset, args.destination) diff --git a/scripts/sentinel2.py b/scripts/sentinel2.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce665a07d806213acbf899308ecc58c20d8ec11 --- /dev/null +++ b/scripts/sentinel2.py @@ -0,0 +1,230 @@ +"""Acquire the nine Dynamic World reflectance bands and SCL from Planetary Computer.""" + +from dataclasses import dataclass +from datetime import date +from functools import lru_cache +from pathlib import Path +from tempfile import TemporaryDirectory +from xml.etree import ElementTree as ET + +import numpy as np +import odc.stac +import planetary_computer +import pystac +import requests +from odc.geo.geobox import GeoBox + +import geosave as gs +from geosave.geodata import io, stac +from geosave.geodata.attrs import CFPacking + +BANDS = ["B02", "B03", "B04", "B05", "B06", "B07", "B08", "B11", "B12"] +# ESA's BOA_ADD_OFFSET band_id is zero based and includes B8A and B10. +ESA_BANDS = ["B01", *BANDS[:7], "B8A", "B09", "B10", "B11", "B12"] + + +@dataclass +class Scene: + geobox: GeoBox + items: list[pystac.Item] + packing: dict[str, tuple[float, float]] + + def provenance(self) -> dict: + """Calibration lists follow BANDS; baseline and Item ID lists correspond.""" + return { + "source_item_ids": [item.id for item in self.items], + "processing_baselines": [ + item.properties["s2:processing_baseline"] for item in self.items + ], + "band_scales": [self.packing[band][0] for band in BANDS], + "band_offsets": [self.packing[band][1] for band in BANDS], + } + + +@lru_cache(maxsize=4096) +def _xml_packing(href: str, baseline: str) -> dict[str, tuple[float, float]]: + # Cache unsigned product addresses: adjacent labels can use the same product. + try: + response = requests.get(planetary_computer.sign(href), timeout=(15, 60)) + response.raise_for_status() + except requests.RequestException as error: + # Signed query strings are temporary credentials and do not belong in logs. + raise RuntimeError( + f"Cannot read {href.split('?')[0]}: {type(error).__name__}" + ) from None + + root = ET.fromstring(response.content) + q = root.findtext(".//{*}BOA_QUANTIFICATION_VALUE") + if q is None: + q = root.findtext(".//{*}L2A_BOA_QUANTIFICATION_VALUE") + if q is None or float(q) <= 0: + raise ValueError( + "L2A product metadata lacks a positive BOA quantification value" + ) + quantification = float(q) + offsets = { + ESA_BANDS[int(node.attrib["band_id"])]: float(node.text) + for node in root.findall(".//{*}BOA_ADD_OFFSET") + } + if float(baseline) >= 4 or offsets: + if not set(BANDS).issubset(offsets): + raise ValueError( + f"Incomplete BOA offset list for processing baseline {baseline}" + ) + return { + band: (1 / quantification, offsets.get(band, 0.0) / quantification) + for band in BANDS + } + + +def _item_packing(item: pystac.Item) -> dict[str, tuple[float, float]]: + result = {} + for band in BANDS: + asset = item.assets[band].extra_fields + # Each Sentinel-2 asset is single-band. STAC 1.1 "bands" or the + # Raster extension's "raster:bands" can override asset-level fields. + records = [asset] + for listing in ("raster:bands", "bands"): + if entries := asset.get(listing): + records.append(entries[0]) + fields = {} + for record in records: + for key in ("scale", "offset"): + value = record.get(f"raster:{key}", record.get(key)) + if value is not None: + fields[key] = float(value) + if len(fields) == 2: + scale, offset = fields["scale"], fields["offset"] + else: + scale, offset = _xml_packing( + item.assets["product-metadata"].href, + item.properties["s2:processing_baseline"], + )[band] + if fields and not np.allclose( + [fields.get("scale", scale), fields.get("offset", offset)], + [scale, offset], + rtol=1e-7, + atol=1e-12, + ): + raise ValueError( + f"Conflicting STAC and product metadata for {item.id} {band}" + ) + if not np.isfinite([scale, offset]).all() or scale <= 0: + raise ValueError(f"Invalid reflectance calibration for {item.id} {band}") + result[band] = (scale, offset) + return result + + +def _select_versions( + items: list[pystac.Item], +) -> tuple[list[pystac.Item], dict[str, tuple[float, float]]]: + """Resolve duplicate processings only when the original mosaic mixes calibrations.""" + packing = {item.id: _item_packing(item) for item in items} + first = packing[items[0].id] + if all(calibration == first for calibration in packing.values()): + return items, first + + # PC IDs end in the processing timestamp. The prefix identifies platform, + # sensing event, relative orbit and MGRS tile across product reprocessings. + groups = {} + versions = {} + for item in items: + group, generation = item.id.rsplit("_", 1) + groups[item.id] = group + baseline = tuple(map(int, item.properties["s2:processing_baseline"].split("."))) + versions[item.id] = baseline, generation + + coverage = {} + for item in sorted(items, key=lambda it: versions[it.id], reverse=True): + signature = tuple(packing[item.id][band] for band in BANDS) + coverage.setdefault(signature, {}).setdefault(groups[item.id], item) + all_groups = set(groups.values()) + complete = [ + by_group for by_group in coverage.values() if by_group.keys() == all_groups + ] + if not complete: + raise ValueError( + f"No common reflectance calibration across all tile acquisitions: " + f"{sorted(packing)}" + ) + + # Prefer the newest baseline/generation available even at the least recent + # tile. Subsequent tiles break ties when several calibrations cover all tiles. + def rank(by_group): + return sorted(versions[it.id] for it in by_group.values()), sorted( + it.id for it in by_group.values() + ) + + best = max(complete, key=rank) + selected = [best[group] for group in sorted(best)] + return selected, packing[selected[0].id] + + +def discover_scene(client: stac.StacClient, label_path: Path, day: date) -> Scene: + """Search the original label grid/day and verify raw DN calibration across Items.""" + with gs.open_raster(label_path, chunks=None) as label: + grid = label.gs.geobox + if grid is None: + raise ValueError(f"Label lacks a raster grid: {label_path}") + items = client.search_items( + stac.StacQuery( + collections=["sentinel-2-l2a"], + intersects=grid.extent.to_crs("EPSG:4326").json, + datetime=f"{day:%Y-%m-%d}", + ) + ) + if not items: + raise ValueError(f"no Sentinel-2 scene on {day:%Y-%m-%d}") + + items, packing = _select_versions(items) + return Scene(grid, items, packing) + + +def ingest_scene( + client: stac.StacClient, + label_path: Path, + day: date, + image_path: Path, + scl_path: Path, + *, + pool: int | None = None, +) -> dict: + """Write same-day reflectance DNs and categorical SCL aligned to the label.""" + source = discover_scene(client, label_path, day) + raster = odc.stac.load( + source.items, + bands=[*BANDS, "SCL"], + geobox=source.geobox, + groupby="solar_day", + resampling={"*": "bilinear", "SCL": "nearest"}, + dtype="uint16", + nodata=0, + patch_url=client.patch_url, + pool=pool, + ) + if raster.sizes["time"] != 1: + raise ValueError( + f"Expected one solar day for {label_path}, found {raster.sizes['time']}" + ) + raster = raster.isel(time=0).gs.write_nodata(0) + image = raster[BANDS].copy(deep=False) + for band, (scale, offset) in source.packing.items(): + image[band] = image[band].gs.write_packing( + CFPacking(scale_factor=scale, add_offset=offset, fill_value=0) + ) + image = image.gs.write_rgb("B04", "B03", "B02") + if not np.any(image["B04"].values): + raise ValueError( + f"Source acquisition contains no valid reflectance on {label_path}" + ) + + image_path.parent.mkdir(parents=True, exist_ok=True) + scl_path.parent.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory(dir=image_path.parent) as staging: + image_tmp = Path(staging) / "image.tif" + scl_tmp = Path(staging) / "scl.tif" + io.write_cog(image, image_tmp, compress="ZSTD", predictor=2, interleave="BAND") + io.write_cog(raster[["SCL"]], scl_tmp, compress="ZSTD") + image_tmp.replace(image_path) + scl_tmp.replace(scl_path) + return source.provenance()