#!/usr/bin/env python3 """Audit C01 path completeness and file-family provenance coverage. This audit is intentionally independent of the tool replay. It checks every path declaration in the canonical 2,921-record source file, every physical file under source_assets/, and every multi-hazard raster-sidecar source label. """ from __future__ import annotations import argparse import hashlib import json from collections import Counter, defaultdict from pathlib import Path from typing import Any DEFAULT_ROOT = Path(__file__).resolve().parents[1] CATEGORY_PROVENANCE = { "D01": "Sentinel-1 GRD source raster or GDAL sidecar", "D02": "Sentinel-2 L2A source raster or GDAL sidecar", "D03": "Sentinel-2-derived RGB preview", "D04": "Hansen GFC source/derived mask or GDAL sidecar", "D05": "project-authored deforestation question", "D06": "project-generated deforestation quality report", "MH00": "multi-hazard sample-directory container handle", "MH01": "project-authored AOI/metadata/handle manifest", "MH02": "project-authored question, answer, or trajectory record", "MH03": "project-generated quality report", "MH04": "source-derived tabular baseline", "MH05": "OpenStreetMap POI extract", "MH06": "source-derived visualization panel", "MH07": "WorldPop population raster and provider sidecar", "MH08": "wildfire source/derived raster, sidecar, or GDAL sidecar", "MH09": "deforestation source/derived raster or sidecar", "MH10": "urban-expansion source/derived raster or sidecar", "MH11": "drought source/derived raster or sidecar", "MH12": "air-pollution source/derived raster or sidecar", "MH13": "OpenAQ empty-query provenance (no measurements)", "MH14": "project-authored train-only air-pollution normalization contract", "MH15": "project-authored train-only drought normalization contract", "R01": "legacy project-authored routing split export", "R02": "CEMS flood-extent source vector", "R03": "Sentinel-2 L2A raster/preview or GDAL sidecar", "R04": "project-authored routing metadata with source identifiers", "R05": "OSM+CEMS-derived road/route/score product", "R06": "project-selected route answer", "R07": "Sentinel-2+OSM+CEMS-derived route overlay", "S01": "Sen1Floods11 Sentinel-1 chip or GDAL sidecar", "S02": "Sen1Floods11 JRC-water layer or GDAL sidecar", "S03": "Sen1Floods11 hand label or GDAL sidecar", "S04": "legacy Sen1Floods11 Otsu derivative or GDAL sidecar", "S05": "source-derived public preview or packaged overlay", "S06": "project-generated hidden derivative of Sen1Floods11 hand labels", "X01": "xBD pre/post imagery", "X02": "xBD-label-derived target mask", "X03": "xBD damage polygons or coordinate conversion", "X04": "project-generated grid/quadrant geometry", } SOURCE_MARKERS = { "COPERNICUS/S2_SR_HARMONIZED NBR": "COPERNICUS/S2_SR_HARMONIZED", "COPERNICUS/S2_SR_HARMONIZED NDBI": "COPERNICUS/S2_SR_HARMONIZED", "COPERNICUS/S2_SR_HARMONIZED NDVI": "COPERNICUS/S2_SR_HARMONIZED", "COPERNICUS/S2_SR_HARMONIZED RGB": "COPERNICUS/S2_SR_HARMONIZED", "COPERNICUS/S5P/OFFL/L3_CO CO": "COPERNICUS/S5P/OFFL/L3_CO", "COPERNICUS/S5P/OFFL/L3_NO2 tropospheric NO2 * 1e6": "COPERNICUS/S5P/OFFL/L3_NO2", "COPERNICUS/S5P/OFFL/L3_SO2 SO2 * 1e6": "COPERNICUS/S5P/OFFL/L3_SO2", "ECMWF Copernicus Atmosphere Monitoring Service — CAMS Global Near-Real-Time": "ECMWF/CAMS/NRT", "ECMWF/ERA5_LAND/DAILY_AGGR volumetric_soil_water_layer_1": "ECMWF/ERA5_LAND/DAILY_AGGR", "ESA/WorldCover/v200 Map class 50 built-up": "ESA/WorldCover/v200", "ESA WorldCover 2020 class 50 built-up": "ESA/WorldCover/v100", "GOOGLE/DYNAMICWORLD/V1 built probability": "GOOGLE/DYNAMICWORLD/V1", "JRC/GHSL/P2023A/GHS_BUILT_S 2020 built_surface>0": "JRC/GHSL/P2023A/GHS_BUILT_S", "JRC/GHSL/P2023A/GHS_BUILT_S 2025 built_surface>0": "JRC/GHSL/P2023A/GHS_BUILT_S", "LANDSAT/LC08+LC09/C02/T1_L2 NBR": "LANDSAT/LC08/C02/T1_L2", "MODIS/061/MCD19A2_GRANULES Optical_Depth_047 * 0.001": "MODIS/061/MCD19A2_GRANULES", "MODIS/061/MCD64A1 BurnDate": "MODIS/061/MCD64A1", "MODIS/061/MOD13Q1 NDVI": "MODIS/061/MOD13Q1", "NASA LP DAAC — VNP14A1.002 Thermal Anomalies/Fire Daily L3 Global 1 km": "NASA/VIIRS/002/VNP14A1", "NASA LP DAAC — VNP21A1D.002 Day LST and Emissivity Daily 1 km": "NASA/VIIRS/002/VNP21A1D", "National Interagency Fire Center — WFIGS Interagency Fire Perimeters": "WFIGS_Interagency_Perimeters/FeatureServer/0", "Wageningen University & Research / Global Forest Watch — RADD Forest Disturbance Alerts v1": "projects/radar-wur/raddalert/v1", "UCSB-CHG/CHIRPS/DAILY same-window z-score": "UCSB-CHG/CHIRPS/DAILY", "UMD/hansen/global_forest_change_2025_v1_13 lossyear=2022": "UMD/hansen/global_forest_change_2025_v1_13", "UMD/hansen/global_forest_change_2025_v1_13 treecover2000>30": "UMD/hansen/global_forest_change_2025_v1_13", "EC JRC TMF v1_2023 AnnualChanges": "projects/JRC/TMF/v1_2023/AnnualChanges", } def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def classify(relative: str) -> str | None: parts = Path(relative).parts if len(parts) < 2 or parts[0] != "source_assets": return None family = parts[1] tail = "/".join(parts[2:]) if family == "deforestation": if "/cache/s1_grd/" in f"/{tail}/": return "D01" if "/cache/s2/" in f"/{tail}/": return "D02" if "/visible/s2_rgb/" in f"/{tail}/": return "D03" if "/masks/" in f"/{tail}/": return "D04" if "/questions/" in f"/{tail}/": return "D05" if tail.endswith("/quality_report.json"): return "D06" if family == "multi_hazard": if tail == "air_pollution/source_normalization.json": return "MH14" if len(parts) == 4: return "MH00" if tail.endswith(("/aoi.geojson", "/available_handles.json", "/metadata.json")): return "MH01" if any(f"/{name}/" in f"/{tail}/" for name in ("questions", "gt", "trajectories")): return "MH02" if tail.endswith("/quality_report.json"): return "MH03" if "/baselines/" in f"/{tail}/": return "MH04" if tail.endswith("/osm/pois.geojson"): return "MH05" if "/panels/" in f"/{tail}/": return "MH06" if tail.endswith(("/tabular/worldpop.tif", "/tabular/worldpop.json")): return "MH07" if tail.endswith("/drought_normalization.json"): return "MH15" if tail.endswith("/normalization.json"): return "MH14" if tail.endswith(("/tabular/openaq_stations.csv", "/tabular/openaq_status.json")): return "MH13" hazard = parts[2] if len(parts) > 2 else "" if "/rasters/" in f"/{tail}/": return { "wildfire": "MH08", "deforestation": "MH09", "urban_expansion": "MH10", "drought": "MH11", "air_pollution": "MH12", }.get(hazard) if family == "routing": if len(parts) == 3 and parts[2] in {"train.json", "val.json", "test.json"}: return "R01" if "/copernicus/" in f"/{tail}/": return "R02" if "/input/rgb" in f"/{tail}/": return "R03" if tail.endswith("/input/metadata.json"): return "R04" if "/derived/" in f"/{tail}/": return "R05" if tail.endswith("/ground_truth/selected_routes.json"): return "R06" if tail.endswith("/overlays/routes_overlay.png"): return "R07" if family == "sen1_flood": if "/labels/S1Hand.tif" in f"/{tail}" or "/derived/S1Portable.tif" in f"/{tail}": return "S01" if "/labels/JRCWaterHand.tif" in f"/{tail}": return "S02" if "/labels/LabelHand.tif" in f"/{tail}": return "S03" if "/labels/S1OtsuLabelHand.tif" in f"/{tail}": return "S04" if "/public/" in f"/{tail}/": return "S05" if "/hidden/" in f"/{tail}/": return "S06" if family == "xbd_damage": if tail.endswith(("/pre.png", "/post.png")): return "X01" if tail.endswith("/post_target.png"): return "X02" if tail.endswith(("/building_damage_xy.geojson", "/building_damage_lnglat.geojson")): return "X03" if tail.endswith(("/grid_4x4.geojson", "/quadrants.geojson")): return "X04" return None def collect_path_cards(value: Any, record_id: str, trail: str = "") -> list[dict[str, Any]]: cards: list[dict[str, Any]] = [] if isinstance(value, dict): if isinstance(value.get("path"), str): cards.append( { "record_id": record_id, "trail": trail, "path": value["path"], "optional": bool(value.get("optional", False)), "declared_exists": value.get("exists"), } ) for key, child in value.items(): child_trail = f"{trail}.{key}" if trail else key cards.extend(collect_path_cards(child, record_id, child_trail)) elif isinstance(value, list): for index, child in enumerate(value): cards.extend(collect_path_cards(child, record_id, f"{trail}[{index}]")) return cards def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, default=DEFAULT_ROOT) parser.add_argument( "--mode", choices=("thin", "hydrated", "development"), default="thin", help=( "thin permits only the documented Sen1Floods11 hydration gap; " "hydrated and development require every declared path." ), ) parser.add_argument( "--output", type=Path, default=None, help="Optional report path. The audit is check-only and never overwrites tracked evidence by default.", ) args = parser.parse_args() root = args.root.expanduser().resolve() canonical = root / "data/core/geodisaster_2921_source_with_splits.jsonl" attributions = root / "ATTRIBUTIONS.md" records = [json.loads(line) for line in canonical.open() if line.strip()] declarations: list[dict[str, Any]] = [] for record in records: declarations.extend(collect_path_cards(record, record["id"])) by_path: dict[str, list[dict[str, Any]]] = defaultdict(list) for card in declarations: by_path[card["path"]].append(card) required = {path for path, cards in by_path.items() if any(not card["optional"] for card in cards)} optional_only = set(by_path) - required missing_required = sorted(path for path in required if not (root / path).exists()) missing_optional = sorted(path for path in optional_only if not (root / path).exists()) permitted_thin_missing = sorted( path for path in missing_required if path.startswith("source_assets/sen1_flood/") and path.endswith(("/derived/S1Portable.tif", "/labels/JRCWaterHand.tif")) ) unexpected_missing_required = ( sorted(set(missing_required) - set(permitted_thin_missing)) if args.mode == "thin" else missing_required ) outside = sorted(path for path in by_path if not path.startswith("source_assets/")) flag_mismatches = [] for path, cards in by_path.items(): actual_exists = (root / path).exists() for card in cards: if card["declared_exists"] is not None and bool(card["declared_exists"]) != actual_exists: if not (args.mode == "thin" and path in permitted_thin_missing): flag_mismatches.append(card | {"actual_exists": actual_exists}) physical_files = [path for path in (root / "source_assets").rglob("*") if path.is_file()] relative_files = [str(path.relative_to(root)) for path in physical_files] unclassified_files = sorted(path for path in relative_files if classify(path) is None) unclassified_references = sorted(path for path in by_path if classify(path) is None) category_counts: dict[str, Counter[str]] = defaultdict(Counter) for path in relative_files: category = classify(path) if category: category_counts[category]["physical_files"] += 1 for path in by_path: category = classify(path) if category: status = "required_paths" if path in required else "optional_paths" category_counts[category][status] += 1 if not (root / path).exists(): category_counts[category]["missing_paths"] += 1 source_labels = set() for sidecar in (root / "source_assets/multi_hazard").glob("*/*/rasters/*.json"): payload = json.loads(sidecar.read_text()) if isinstance(payload.get("source"), str): source_labels.add(payload["source"]) direct_labels = sorted(label for label in source_labels if not label.startswith("derived ")) derived_labels = sorted(label for label in source_labels if label.startswith("derived ")) attribution_text = attributions.read_text() unmapped_labels = sorted(label for label in direct_labels if label not in SOURCE_MARKERS) uncited_markers = sorted( {SOURCE_MARKERS[label] for label in direct_labels if label in SOURCE_MARKERS and SOURCE_MARKERS[label] not in attribution_text} ) referenced_existing_files = sum(1 for path in by_path if (root / path).is_file()) referenced_existing_directories = sum(1 for path in by_path if (root / path).is_dir()) physical_unreferenced = len(set(relative_files) - set(by_path)) suffix_counts = Counter(path.suffix.lower() or "" for path in physical_files) unregistered_category_keys = sorted( category for category in category_counts if f"| {category} |" not in attribution_text ) report = { "audit": "c01_source_asset_registry_v1", "inventory_mode": args.mode, "root": str(root), "canonical": str(canonical.relative_to(root)), "canonical_sha256": sha256(canonical), "record_count": len(records), "path_declarations": { "occurrences": len(declarations), "unique": len(by_path), "required_unique": len(required), "optional_only_unique": len(optional_only), "required_missing": len(missing_required), "permitted_thin_missing": len(permitted_thin_missing) if args.mode == "thin" else 0, "unexpected_required_missing": len(unexpected_missing_required), "optional_missing": len(missing_optional), "outside_source_assets": len(outside), "declared_exists_mismatches": len(flag_mismatches), "existing_file_paths": referenced_existing_files, "existing_directory_paths": referenced_existing_directories, }, "physical_inventory": { "files": len(physical_files), "referenced_files": referenced_existing_files, "packaged_support_or_internal_files_not_directly_referenced": physical_unreferenced, "suffix_counts": dict(sorted(suffix_counts.items())), "unclassified_files": len(unclassified_files), "unregistered_category_keys": unregistered_category_keys, }, "source_sidecars": { "unique_source_labels": len(source_labels), "direct_source_labels": len(direct_labels), "derived_source_labels": len(derived_labels), "unmapped_direct_labels": unmapped_labels, "citation_markers_absent_from_attributions": uncited_markers, }, "category_counts": { category: {"description": CATEGORY_PROVENANCE[category], **dict(sorted(counts.items()))} for category, counts in sorted(category_counts.items()) }, "missing_required": missing_required, "permitted_thin_missing": permitted_thin_missing if args.mode == "thin" else [], "unexpected_missing_required": unexpected_missing_required, "missing_optional": missing_optional, "outside_source_assets": outside, "declared_exists_mismatches": flag_mismatches, "unclassified_physical_files": unclassified_files, "unclassified_referenced_paths": unclassified_references, "direct_source_labels": direct_labels, "derived_source_labels": derived_labels, } output = args.output.expanduser().resolve() if args.output else None if output is not None: output.parent.mkdir(parents=True, exist_ok=True) output.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n") print(json.dumps({ "mode": args.mode, "output": str(output) if output else None, "required_missing": len(missing_required), "permitted_thin_missing": len(permitted_thin_missing) if args.mode == "thin" else 0, "unexpected_required_missing": len(unexpected_missing_required), "optional_missing": len(missing_optional), "unclassified_files": len(unclassified_files), "unclassified_references": len(unclassified_references), "unmapped_source_labels": len(unmapped_labels), "uncited_source_markers": len(uncited_markers), "unregistered_category_keys": len(unregistered_category_keys), }, indent=2)) if unexpected_missing_required or missing_optional or outside or flag_mismatches or unclassified_files or unclassified_references or unmapped_labels or uncited_markers or unregistered_category_keys: raise SystemExit(1) if __name__ == "__main__": main()