File size: 19,793 Bytes
7eea874 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 | """Read a completed DISFOR Sentinel-1 companion release from local files.
The reader uses Parquet indexes and byte ranges in uncompressed TAR shards. It
does not extract archive members, contact Earth Engine/Hugging Face, interpolate
dates, assign disturbance labels, or combine different radar tracks implicitly.
"""
from __future__ import annotations
import hashlib
import io
import json
import re
import tarfile
from datetime import datetime, timezone
from pathlib import Path, PurePosixPath
from typing import Iterable, Iterator, Mapping, Sequence
import numpy as np
import pyarrow as pa
import pyarrow.dataset as ds
FLOAT_ARRAYS = (
"VV_sigma0_db", "VH_sigma0_db", "incidence_deg", "local_incidence_deg",
)
BOOL_ARRAYS = (
"source_valid", "angle_ok", "terrain_known", "layover_risk", "shadow_risk",
"terrain_ok", "recommended_valid",
)
CUBE_ARRAYS = FLOAT_ARRAYS + ("source_scene_index",) + BOOL_ARRAYS
DEFAULT_ARRAYS = ("VV_sigma0_db", "VH_sigma0_db", "recommended_valid")
_TRACK = re.compile(r"R\d{3}_(ASCENDING|DESCENDING)\Z")
_SHA256 = re.compile(r"[0-9a-f]{64}\Z")
def _safe_relative(value: str) -> PurePosixPath:
"""Only accept canonical portable paths, never Windows or parent paths."""
if not isinstance(value, str) or not value or "\\" in value or ":" in value:
raise ValueError(f"Invalid release-relative path: {value!r}")
path = PurePosixPath(value)
if path.is_absolute() or any(part in ("", ".", "..") for part in value.split("/")):
raise ValueError(f"Invalid release-relative path: {value!r}")
if path.as_posix() != value:
raise ValueError(f"Noncanonical release-relative path: {value!r}")
return path
def _resolve_relative(root: Path, value: str) -> Path:
relative = _safe_relative(value)
path = root.joinpath(*relative.parts).resolve()
try:
path.relative_to(root)
except ValueError as exc:
raise ValueError(f"Release path leaves the release directory: {value!r}") from exc
return path
def _utc(value: str | datetime, *, name: str = "timestamp") -> datetime:
"""Parse an aware ISO time; an ISO date alone means midnight UTC."""
if isinstance(value, datetime):
parsed = value
elif isinstance(value, str):
text = value.strip()
if re.fullmatch(r"\d{4}-\d{2}-\d{2}", text):
text += "T00:00:00+00:00"
if text.endswith("Z"):
text = text[:-1] + "+00:00"
try:
parsed = datetime.fromisoformat(text)
except ValueError as exc:
raise ValueError(f"Invalid {name}: {value!r}") from exc
else:
raise TypeError(f"{name} must be an ISO string or aware datetime.")
if parsed.tzinfo is None or parsed.utcoffset() is None:
raise ValueError(f"{name} needs a time zone, for example +00:00 or Z.")
return parsed.astimezone(timezone.utc)
def _integer(value, name: str, *, minimum: int = 0) -> int:
if isinstance(value, bool) or not isinstance(value, (int, np.integer)):
raise ValueError(f"{name} must be an integer.")
result = int(value)
if result < minimum:
raise ValueError(f"{name} must be at least {minimum}.")
return result
def _json_object(path: Path) -> dict:
try:
value = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
raise ValueError(f"Cannot read release JSON: {path.name}: {exc}") from exc
if not isinstance(value, dict):
raise ValueError(f"Expected a JSON object in {path.name}.")
return value
class CompanionDataset:
"""A local, completed release with native irregular radar acquisition times.
Completion metadata is required, but construction does not reread every
dataset byte. ``load_block`` checks each requested payload's SHA-256 by
default. Run the package's separate full verification command when all
exported files need to be verified.
"""
def __init__(self, root: str | Path, *, max_block_bytes: int = 1 << 30,
_build_validation: bool = False):
self.root = Path(root).expanduser().resolve()
if not self.root.is_dir():
raise ValueError(f"Release directory does not exist: {self.root}")
marker = self.root / "RELEASE_COMPLETE.json"
if not isinstance(_build_validation, bool):
raise TypeError("_build_validation is a private boolean build option.")
if not marker.is_file() and not _build_validation:
raise ValueError("The release is incomplete: RELEASE_COMPLETE.json is missing.")
self.release = _json_object(self.root / "release.json")
self.completion = _json_object(marker) if marker.is_file() else None
identity = self.release.get("release_id")
if not isinstance(identity, str) or not identity:
raise ValueError("release.json must declare a nonempty release_id.")
if self.completion is not None and self.completion.get("release_id") != identity:
raise ValueError("The completion marker belongs to a different release_id.")
self.release_id = identity
self.max_block_bytes = _integer(max_block_bytes, "max_block_bytes", minimum=1)
self._blocks = None
self._centres = None
def _dataset(self, relative: str):
path = _resolve_relative(self.root, relative)
if not path.is_dir():
raise ValueError(f"Required Parquet catalogue is missing: {relative}")
try:
return ds.dataset(path, format="parquet", exclude_invalid_files=False)
except (pa.ArrowException, OSError) as exc:
raise ValueError(f"Cannot open Parquet catalogue {relative}: {exc}") from exc
@staticmethod
def _filter(sample_id: int | None, track: str | None):
condition = None
if sample_id is not None:
sample_id = _integer(sample_id, "sample_id")
condition = ds.field("sample_id") == sample_id
if track is not None:
if not isinstance(track, str) or not _TRACK.fullmatch(track):
raise ValueError("track must be R###_ASCENDING or R###_DESCENDING.")
track_condition = ds.field("track") == track
condition = track_condition if condition is None else condition & track_condition
return condition
def iter_blocks(
self, sample_id: int | None = None, track: str | None = None,
*, batch_size: int = 4096,
) -> Iterator[dict]:
"""Yield index rows without loading the entire catalogue into memory."""
batch_size = _integer(batch_size, "batch_size", minimum=1)
condition = self._filter(sample_id, track)
if self._blocks is None:
self._blocks = self._dataset("radar/blocks")
for batch in self._blocks.to_batches(filter=condition, batch_size=batch_size):
yield from batch.to_pylist()
def tracks(self, sample_id: int) -> list[str]:
"""Return available relative-orbit/direction tracks for one location."""
return sorted({row["track"] for row in self.iter_blocks(sample_id=sample_id)})
def read_centre_rows(
self, sample_id: int | None = None, track: str | None = None,
*, columns: Sequence[str] | None = None, batch_size: int = 65536,
) -> Iterator[pa.RecordBatch]:
"""Yield Arrow batches of centre observations, with the original masks.
No temporal or label filter is applied implicitly. For example, callers
can select ``recommended_valid`` themselves while keeping the rejected
records available for quality analysis.
"""
batch_size = _integer(batch_size, "batch_size", minimum=1)
condition = self._filter(sample_id, track)
if self._centres is None:
self._centres = self._dataset("radar/pixel_data")
if columns is not None:
columns = list(columns)
yield from self._centres.to_batches(
filter=condition, columns=columns, batch_size=batch_size,
)
def load_block(self, block: Mapping, *, verify_hash: bool = True) -> dict:
"""Decode one annual NPZ by its indexed TAR byte range.
The result contains every NPZ array and a parsed ``metadata`` object.
``metadata_json`` is retained as its original scalar string array.
Archive extraction is never used. Disabling the hash check is an
explicit performance choice; path, TAR header and structure checks
remain active.
"""
if not isinstance(block, Mapping):
raise TypeError("block must be a row from iter_blocks().")
required = {
"sample_id", "track", "year", "archive_path", "member_path",
"byte_offset", "byte_size", "payload_sha256", "n_frames", "grid_hash",
}
missing = required.difference(block)
if missing:
raise ValueError(f"Block index fields missing: {sorted(missing)}")
sample_id = _integer(block["sample_id"], "sample_id")
year = _integer(block["year"], "year", minimum=1)
self._filter(sample_id, block["track"])
archive = _resolve_relative(self.root, block["archive_path"])
member = _safe_relative(block["member_path"]).as_posix()
offset = _integer(block["byte_offset"], "byte_offset", minimum=512)
size = _integer(block["byte_size"], "byte_size", minimum=1)
frames = _integer(block["n_frames"], "n_frames", minimum=1)
if offset % tarfile.BLOCKSIZE:
raise ValueError("TAR data byte_offset must be aligned to 512 bytes.")
if size > self.max_block_bytes:
raise ValueError("Indexed NPZ exceeds max_block_bytes.")
expected_hash = block["payload_sha256"]
if not isinstance(expected_hash, str) or not _SHA256.fullmatch(expected_hash):
raise ValueError("payload_sha256 must be a lowercase SHA-256 digest.")
try:
with archive.open("rb") as stream:
stream.seek(0, 2)
if offset + size > stream.tell():
raise ValueError("Indexed payload extends beyond the TAR archive.")
stream.seek(offset - tarfile.BLOCKSIZE)
header = stream.read(tarfile.BLOCKSIZE)
try:
entry = tarfile.TarInfo.frombuf(header, "utf-8", "strict")
except (tarfile.TarError, UnicodeError, ValueError) as exc:
raise ValueError("The indexed payload has an invalid TAR header.") from exc
if not entry.isreg() or entry.name != member or entry.size != size:
raise ValueError("TAR header does not match the indexed member/size.")
payload = stream.read(size)
if len(payload) != size:
raise ValueError("Incomplete read of the indexed payload.")
except OSError as exc:
raise ValueError(f"Cannot read payload archive {block['archive_path']}: {exc}") from exc
if verify_hash and hashlib.sha256(payload).hexdigest() != expected_hash:
raise ValueError(f"Payload SHA-256 mismatch: {member}")
try:
with np.load(io.BytesIO(payload), allow_pickle=False) as stored:
arrays = {name: stored[name] for name in stored.files}
except (OSError, ValueError, EOFError) as exc:
raise ValueError(f"Cannot decode NPZ payload {member}: {exc}") from exc
expected_arrays = set(CUBE_ARRAYS) | {"utc", "pass_id", "metadata_json"}
if set(arrays) != expected_arrays:
raise ValueError("The NPZ array names do not match the native release schema.")
for name in CUBE_ARRAYS:
expected_dtype = np.dtype("float32" if name in FLOAT_ARRAYS else
"bool" if name in BOOL_ARRAYS else "uint16")
if arrays[name].shape != (frames, 32, 32) or arrays[name].dtype != expected_dtype:
raise ValueError(f"Invalid shape or dtype for array {name}.")
for name in ("utc", "pass_id"):
if arrays[name].shape != (frames,) or arrays[name].dtype.kind not in "US":
raise ValueError(f"Invalid frame strings in {name}.")
scalar = arrays["metadata_json"]
if scalar.shape != () or scalar.dtype.kind not in "US":
raise ValueError("metadata_json must be a scalar string array.")
try:
metadata = json.loads(scalar.item())
except (TypeError, ValueError) as exc:
raise ValueError("Invalid embedded metadata JSON.") from exc
if not isinstance(metadata, dict):
raise ValueError("Embedded metadata must be an object.")
if (metadata.get("sample_id") != sample_id or metadata.get("track") != block["track"]
or str(metadata.get("year")) != str(year)):
raise ValueError("Embedded identity disagrees with the block index.")
grid = metadata.get("grid")
if not isinstance(grid, dict) or grid.get("grid_hash") != block["grid_hash"]:
raise ValueError("Embedded grid identity disagrees with the block index.")
if (grid.get("height"), grid.get("width"), grid.get("reference_row"),
grid.get("reference_col")) != (32, 32, 16, 16):
raise ValueError("Embedded grid is not the documented DISFOR reference grid.")
passes = arrays["pass_id"].astype(str).tolist()
acquisition_records = metadata.get("passes")
if not isinstance(acquisition_records, list) or any(
not isinstance(item, dict) for item in acquisition_records
) or [item.get("pass_id") for item in acquisition_records] != passes:
raise ValueError("Metadata pass order disagrees with NPZ frame order.")
if len(set(passes)) != frames:
raise ValueError("Duplicate physical passes within one annual block.")
times = [_utc(value, name="frame utc") for value in arrays["utc"].astype(str)]
if any(a > b for a, b in zip(times, times[1:])):
raise ValueError("Frame UTC order is not chronological.")
if "first_utc" in block and _utc(block["first_utc"]) != min(times):
raise ValueError("Block first_utc disagrees with NPZ frame UTCs.")
if "last_utc" in block and _utc(block["last_utc"]) != max(times):
raise ValueError("Block last_utc disagrees with NPZ frame UTCs.")
if "n_valid_centres" in block and int(block["n_valid_centres"]) != int(
arrays["recommended_valid"][:, 16, 16].sum()
):
raise ValueError("Block n_valid_centres disagrees with the NPZ mask.")
arrays["metadata"] = metadata
return arrays
def read_sequence(
self, sample_id: int, track: str, *, valid_centres_only: bool = False,
start: str | datetime | None = None, end: str | datetime | None = None,
arrays: Sequence[str] = DEFAULT_ARRAYS,
) -> dict:
"""Read one location and one track, retaining native acquisition times.
``start`` is inclusive and ``end`` exclusive. Date-only boundaries are
midnight UTC. ``valid_centres_only`` filters by the centre mask; it does
not establish ecological health or valid weather conditions. The default
retains every frame, including frames with rejected centre pixels.
Selected cube arrays are returned under their own names, with ``utc``,
``pass_id``, ``block_ids`` and ``frame_indices`` aligned along axis zero.
This method materializes one location/track sequence; use iter_blocks()
and load_block() when an annual-block memory bound is required.
"""
sample_id = _integer(sample_id, "sample_id")
self._filter(sample_id, track)
names = tuple(arrays)
if not names or len(set(names)) != len(names) or any(name not in CUBE_ARRAYS for name in names):
raise ValueError("arrays must contain distinct native cube-array names.")
lower = _utc(start, name="start") if start is not None else None
upper = _utc(end, name="end") if end is not None else None
if lower is not None and upper is not None and lower >= upper:
raise ValueError("start must be earlier than end.")
collected: dict[str, list[np.ndarray]] = {name: [] for name in names}
utc_chunks, pass_chunks, block_chunks, frame_chunks = [], [], [], []
seen_passes: set[str] = set()
grid_hash = None
source_blocks = []
found = False
for block in self.iter_blocks(sample_id=sample_id, track=track):
found = True
native = self.load_block(block)
if grid_hash is None:
grid_hash = block["grid_hash"]
elif grid_hash != block["grid_hash"]:
raise ValueError("A location/track sequence contains incompatible grids.")
current_passes = native["pass_id"].astype(str)
if seen_passes.intersection(current_passes.tolist()):
raise ValueError("Duplicate physical pass across annual blocks.")
seen_passes.update(current_passes.tolist())
times = [_utc(value) for value in native["utc"].astype(str)]
keep = np.array([
(lower is None or moment >= lower) and (upper is None or moment < upper)
for moment in times
], dtype=bool)
if valid_centres_only:
keep &= native["recommended_valid"][:, 16, 16]
count = int(keep.sum())
block_id = str(block.get("block_id", block["member_path"]))
source_blocks.append({"block_id": block_id, "frames_selected": count,
"n_frames": len(times)})
if not count:
continue
for name in names:
collected[name].append(native[name][keep])
utc_chunks.append(native["utc"][keep].astype(str))
pass_chunks.append(current_passes[keep])
block_chunks.append(np.full(count, block_id, dtype=f"U{len(block_id)}"))
frame_chunks.append(np.flatnonzero(keep).astype(np.int64))
if not found:
raise KeyError(f"No blocks for sample_id={sample_id}, track={track}.")
result = {
"sample_id": sample_id, "track": track, "grid_hash": grid_hash,
"valid_centres_only": bool(valid_centres_only),
"start": lower.isoformat() if lower is not None else None,
"end": upper.isoformat() if upper is not None else None,
"source_blocks": source_blocks,
}
if utc_chunks:
utc_values = np.concatenate(utc_chunks)
pass_values = np.concatenate(pass_chunks)
order = np.asarray(sorted(range(len(utc_values)),
key=lambda i: (_utc(str(utc_values[i])), str(pass_values[i]))),
dtype=np.int64)
result["utc"] = utc_values[order]
result["pass_id"] = pass_values[order]
result["block_ids"] = np.concatenate(block_chunks)[order]
result["frame_indices"] = np.concatenate(frame_chunks)[order]
for name in names:
result[name] = np.concatenate(collected[name], axis=0)[order]
else:
result.update(utc=np.empty(0, dtype="U1"), pass_id=np.empty(0, dtype="U1"),
block_ids=np.empty(0, dtype="U1"),
frame_indices=np.empty(0, dtype=np.int64))
for name in names:
dtype = "float32" if name in FLOAT_ARRAYS else "bool" if name in BOOL_ARRAYS else "uint16"
result[name] = np.empty((0, 32, 32), dtype=dtype)
return result
|