GeoDisaster / data /release_tools /raster_portability.py
vimageiitb's picture
Upload GeoDisasterBenchmark (attempt 1)
7aae553 verified
Raw History Blame Contribute Delete
6.66 kB
#!/usr/bin/env python3
"""Deterministic finite-nodata GeoTIFF conversions used by C10."""
from __future__ import annotations
import os
from pathlib import Path
from typing import Any
import numpy as np
import rasterio
S1_PORTABLE_NODATA = -9999.0
BINARY_PORTABLE_NODATA = 255
def valid_pixels(data: np.ndarray, nodata: float | int | None) -> np.ndarray:
"""Return pixels valid in every band, including a finite nodata value."""
bands = data if data.ndim == 3 else data[np.newaxis, ...]
valid = np.logical_and.reduce([np.isfinite(band) for band in bands])
if nodata is not None and np.isfinite(float(nodata)):
valid &= np.logical_and.reduce([band != float(nodata) for band in bands])
return valid
def _copy_tags(source: rasterio.io.DatasetReader, target: rasterio.io.DatasetWriter) -> None:
target.update_tags(**source.tags())
for index in range(1, source.count + 1):
target.update_tags(index, **source.tags(index))
if source.descriptions[index - 1]:
target.set_band_description(index, source.descriptions[index - 1])
def _atomic_raster_write(destination: Path, writer: Any) -> None:
destination.parent.mkdir(parents=True, exist_ok=True)
temporary = destination.with_name(f".{destination.stem}.tmp.{os.getpid()}{destination.suffix}")
try:
writer(temporary)
os.replace(temporary, destination)
finally:
if temporary.exists():
temporary.unlink()
def write_portable_s1(source: Path, destination: Path) -> dict[str, Any]:
"""Preserve finite S1 values and encode invalid pixels as finite -9999."""
source = source.resolve()
destination = destination.resolve()
with rasterio.open(source) as dataset:
data = dataset.read().astype("float32")
valid = valid_pixels(data, dataset.nodata)
if np.any(data[:, valid] == S1_PORTABLE_NODATA):
raise ValueError(f"valid source pixels collide with {S1_PORTABLE_NODATA}: {source}")
converted = data.copy()
converted[:, ~valid] = S1_PORTABLE_NODATA
profile = dataset.profile.copy()
profile.update(dtype="float32", nodata=S1_PORTABLE_NODATA, compress="deflate", predictor=3)
def writer(path: Path) -> None:
with rasterio.open(path, "w", **profile) as output:
output.write(converted)
_copy_tags(dataset, output)
_atomic_raster_write(destination, writer)
return {
"bands": int(dataset.count),
"height": int(dataset.height),
"width": int(dataset.width),
"valid_spatial_pixels": int(valid.sum()),
"invalid_spatial_pixels": int(valid.size - valid.sum()),
"source_nodata": str(dataset.nodata),
"portable_nodata": S1_PORTABLE_NODATA,
}
def verify_portable_s1(source: Path, destination: Path) -> dict[str, Any]:
"""Prove a portable S1 raster is a value-preserving source derivative."""
if not destination.is_file():
raise FileNotFoundError(destination)
with rasterio.open(source) as upstream, rasterio.open(destination) as portable:
original = upstream.read().astype("float32")
derived = portable.read().astype("float32")
valid = valid_pixels(original, upstream.nodata)
if original.shape != derived.shape:
raise ValueError(f"shape mismatch: {source} vs {destination}")
if portable.nodata != S1_PORTABLE_NODATA:
raise ValueError(f"unexpected portable nodata {portable.nodata}: {destination}")
if upstream.crs != portable.crs or upstream.transform != portable.transform:
raise ValueError(f"georeferencing mismatch: {source} vs {destination}")
if not np.array_equal(original[:, valid], derived[:, valid]):
raise ValueError(f"valid values changed: {source} vs {destination}")
if not np.all(derived[:, ~valid] == S1_PORTABLE_NODATA):
raise ValueError(f"invalid values were not normalized: {destination}")
return {
"valid_spatial_pixels": int(valid.sum()),
"invalid_spatial_pixels": int(valid.size - valid.sum()),
"valid_values_identical": True,
"georeferencing_identical": True,
"nodata": S1_PORTABLE_NODATA,
}
def normalize_binary_mask_in_place(path: Path) -> dict[str, Any]:
"""Convert one binary mask to uint8 0/1 with nodata 255, preserving validity."""
path = path.resolve()
with rasterio.open(path) as dataset:
if dataset.count != 1:
raise ValueError(f"binary mask must have one band: {path}")
source = dataset.read(1)
valid = valid_pixels(source, dataset.nodata)
positive = valid & (source > 0)
converted = np.full(source.shape, BINARY_PORTABLE_NODATA, dtype="uint8")
converted[valid] = positive[valid].astype("uint8")
profile = dataset.profile.copy()
profile.update(
dtype="uint8",
count=1,
nodata=BINARY_PORTABLE_NODATA,
compress="deflate",
predictor=2,
)
source_nodata = dataset.nodata
def writer(destination: Path) -> None:
with rasterio.open(destination, "w", **profile) as output:
output.write(converted, 1)
_copy_tags(dataset, output)
_atomic_raster_write(path, writer)
return {
"valid_pixels": int(valid.sum()),
"invalid_pixels": int(valid.size - valid.sum()),
"positive_pixels": int(positive.sum()),
"source_nodata": str(source_nodata),
"portable_nodata": BINARY_PORTABLE_NODATA,
}
def verify_portable_binary_mask(path: Path) -> dict[str, Any]:
with rasterio.open(path) as dataset:
values = dataset.read(1)
if dataset.count != 1 or dataset.dtypes[0] != "uint8":
raise ValueError(f"portable binary raster must be one uint8 band: {path}")
if dataset.nodata != BINARY_PORTABLE_NODATA:
raise ValueError(f"unexpected binary nodata {dataset.nodata}: {path}")
unique = set(int(value) for value in np.unique(values))
if not unique <= {0, 1, BINARY_PORTABLE_NODATA}:
raise ValueError(f"non-binary values {sorted(unique)}: {path}")
valid = values != BINARY_PORTABLE_NODATA
return {
"valid_pixels": int(valid.sum()),
"invalid_pixels": int(valid.size - valid.sum()),
"positive_pixels": int((values == 1).sum()),
"values": sorted(unique),
"nodata": BINARY_PORTABLE_NODATA,
}