GeoDisaster / data /release_tools /evaluate_c12_sen1_accuracy.py
vimageiitb's picture
Upload GeoDisasterBenchmark (attempt 1)
7aae553 verified
Raw History Blame Contribute Delete
17.1 kB
#!/usr/bin/env python3
"""Evaluate the declared Sentinel-1 Otsu baseline against evaluator-only labels.
The canonical tasks intentionally ask for properties of a predicted mask. This
script is a separate construct-validity check: it recreates that mask from each
declared S1 input and compares it with the Sen1Floods11 ``LabelHand`` reference.
Reference labels are never added to the agent's initial artifacts or answers.
"""
from __future__ import annotations
import argparse
import hashlib
import json
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any, Iterable
import numpy as np
import rasterio
METHOD = "s1_min_backscatter_otsu_v1"
REFERENCE_NAME = "Sen1Floods11 v1.1 LabelHand"
ACCURACY_KEYS = {"accuracy", "iou", "f1", "precision", "recall"}
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 round6(value: float | None) -> float | None:
return None if value is None else round(float(value), 6)
def safe_div(numerator: int, denominator: int) -> float | None:
return None if denominator == 0 else numerator / denominator
def otsu_threshold(values: np.ndarray) -> float:
"""Match the worker's 256-bin Otsu implementation exactly."""
values = values[np.isfinite(values)]
if values.size == 0:
return 0.0
hist, edges = np.histogram(values, bins=256)
centers = (edges[:-1] + edges[1:]) / 2
total = int(hist.sum())
if total == 0:
return float(np.nanmean(values))
weight1 = np.cumsum(hist)
weight2 = total - weight1
mean1 = np.cumsum(hist * centers) / np.maximum(weight1, 1)
mean2 = (
np.cumsum((hist * centers)[::-1])
/ np.maximum(np.cumsum(hist[::-1]), 1)
)[::-1]
between = weight1[:-1] * weight2[:-1] * (mean1[:-1] - mean2[1:]) ** 2
if between.size == 0:
return float(np.nanmean(values))
return float(centers[:-1][int(np.argmax(between))])
def predicted_mask(path: Path) -> tuple[np.ndarray, np.ndarray, float, dict[str, Any]]:
with rasterio.open(path) as dataset:
band1 = dataset.read(1).astype("float32")
band2 = dataset.read(2).astype("float32") if dataset.count >= 2 else band1
valid = np.isfinite(band1) & np.isfinite(band2)
if dataset.nodata is not None and np.isfinite(float(dataset.nodata)):
valid &= (band1 != float(dataset.nodata)) & (band2 != float(dataset.nodata))
score = np.minimum(band1, band2)
threshold = otsu_threshold(score[valid])
mask = valid & (score <= threshold)
profile = {
"shape": [dataset.height, dataset.width],
"crs": str(dataset.crs) if dataset.crs else None,
"transform": list(dataset.transform)[:6],
}
return mask, valid, threshold, profile
def contains_accuracy_field(value: Any) -> bool:
if isinstance(value, dict):
if any(str(key).lower() in ACCURACY_KEYS for key in value):
return True
return any(contains_accuracy_field(item) for item in value.values())
if isinstance(value, list):
return any(contains_accuracy_field(item) for item in value)
return False
def declared_paths(value: Any) -> Iterable[str]:
if isinstance(value, dict):
path = value.get("path")
if isinstance(path, str):
yield path
for item in value.values():
yield from declared_paths(item)
elif isinstance(value, list):
for item in value:
yield from declared_paths(item)
def load_contract(dataset_path: Path) -> tuple[dict[str, dict[str, Any]], dict[str, Any]]:
samples: dict[str, dict[str, Any]] = {}
records = []
forbidden_declarations = []
accuracy_answer_ids = []
wrong_method_ids = []
with dataset_path.open(encoding="utf-8") as stream:
for line_number, line in enumerate(stream, 1):
record = json.loads(line)
record_id = str(record.get("id", ""))
if not record_id.startswith("sen1_flood/"):
continue
records.append(record)
sample_id = str(record["sample_id"])
question_type = str(record["question_type"])
expected = record.get("expected_final_answer") or {}
if expected.get("prediction_method") != METHOD:
wrong_method_ids.append(record_id)
if contains_accuracy_field(expected):
accuracy_answer_ids.append(record_id)
for path in declared_paths(record.get("initial_artifacts") or {}):
lowered = path.lower()
if "/labelhand.tif" in lowered or "s1otsulabelhand.tif" in lowered:
forbidden_declarations.append({"id": record_id, "path": path})
s1_path = (
record["initial_artifacts"]["sar_chip_1"]["paths"]["s1_image"]["path"]
)
entry = samples.setdefault(
sample_id,
{
"sample_id": sample_id,
"split": record["split"],
"s1_path": s1_path,
"question_types": [],
"expected_flood_percentages": [],
},
)
if entry["split"] != record["split"] or entry["s1_path"] != s1_path:
raise ValueError(f"inconsistent split or S1 path for {sample_id}")
entry["question_types"].append(question_type)
if "flood_percentage" in expected:
entry["expected_flood_percentages"].append(
{"question_type": question_type, "value": float(expected["flood_percentage"])}
)
if len(records) != 500 or len(samples) != 100:
raise ValueError(f"expected 500 records/100 samples, found {len(records)}/{len(samples)}")
for sample_id, entry in samples.items():
if Counter(entry["question_types"]) != Counter("ABCDE"):
raise ValueError(f"{sample_id}: expected one record for each of A-E")
audit = {
"records": len(records),
"unique_samples": len(samples),
"question_types": sorted({str(row["question_type"]) for row in records}),
"records_with_declared_reference_label": len(forbidden_declarations),
"declared_reference_label_violations": forbidden_declarations,
"records_with_accuracy_fields_in_expected_answer": len(accuracy_answer_ids),
"accuracy_field_answer_ids": accuracy_answer_ids,
"records_with_wrong_or_missing_prediction_method": len(wrong_method_ids),
"wrong_method_ids": wrong_method_ids,
"expected_answer_contract": (
"agent-facing answers describe deterministic Otsu predictions; "
"reference-label accuracy is evaluator-only"
),
}
return samples, audit
def evaluate_sample(root: Path, entry: dict[str, Any]) -> dict[str, Any]:
sample_id = entry["sample_id"]
s1_path = root / entry["s1_path"]
label_path = root / "source_assets" / "sen1_flood" / sample_id / "labels" / "LabelHand.tif"
if not s1_path.is_file():
raise FileNotFoundError(f"missing declared S1 input: {s1_path}")
if not label_path.is_file():
raise FileNotFoundError(f"missing evaluator-only reference label: {label_path}")
prediction, source_valid, threshold, source_profile = predicted_mask(s1_path)
with rasterio.open(label_path) as dataset:
label = dataset.read(1)
label_profile = {
"shape": [dataset.height, dataset.width],
"crs": str(dataset.crs) if dataset.crs else None,
"transform": list(dataset.transform)[:6],
}
same_grid = (
source_profile["shape"] == label_profile["shape"]
and source_profile["crs"] == label_profile["crs"]
and np.allclose(
source_profile["transform"],
label_profile["transform"],
rtol=0.0,
atol=1e-12,
)
)
if not same_grid:
raise ValueError(f"{sample_id}: S1/reference grids differ")
values = {int(value) for value in np.unique(label)}
if not values.issubset({-1, 0, 1}):
raise ValueError(f"{sample_id}: unsupported reference values {sorted(values)}")
full_prediction_count = int(prediction.sum())
full_valid_count = int(source_valid.sum())
full_percentage = full_prediction_count / full_valid_count * 100 if full_valid_count else 0.0
expected_percentages = entry["expected_flood_percentages"]
canonical_percentage_match = bool(expected_percentages) and all(
abs(round(full_percentage, 6) - round(item["value"], 6)) <= 1e-6
for item in expected_percentages
)
valid = label != -1
ground_truth = label == 1
prediction = prediction & valid
tp = int((prediction & ground_truth).sum())
fp = int((prediction & (label == 0)).sum())
fn = int(((~prediction) & ground_truth & valid).sum())
tn = int(((~prediction) & (label == 0) & valid).sum())
precision = safe_div(tp, tp + fp)
recall = safe_div(tp, tp + fn)
iou = safe_div(tp, tp + fp + fn)
f1 = safe_div(2 * tp, 2 * tp + fp + fn)
return {
"sample_id": sample_id,
"split": entry["split"],
"question_record_count": 5,
"prediction_method": METHOD,
"reference": REFERENCE_NAME,
"s1_path": entry["s1_path"],
"reference_label_path": str(label_path.relative_to(root)),
"s1_sha256": sha256(s1_path),
"reference_label_sha256": sha256(label_path),
"prediction_threshold": round(float(threshold), 8),
"computed_full_s1_flood_percentage": round6(full_percentage),
"canonical_expected_flood_percentages": expected_percentages,
"canonical_prediction_percentage_match": canonical_percentage_match,
"valid_reference_pixels": int(valid.sum()),
"reference_flood_pixels": int(ground_truth.sum()),
"predicted_flood_pixels_in_reference_footprint": int(prediction.sum()),
"TP": tp,
"FP": fp,
"FN": fn,
"TN": tn,
"IoU": round6(iou),
"precision": round6(precision),
"recall": round6(recall),
"F1": round6(f1),
}
def summarize(rows: list[dict[str, Any]]) -> dict[str, Any]:
def metric_mean(name: str) -> float | None:
values = [float(row[name]) for row in rows if row.get(name) is not None]
return round6(float(np.mean(values))) if values else None
aggregate = {name: sum(int(row[name]) for row in rows) for name in ("TP", "FP", "FN", "TN")}
tp, fp, fn = aggregate["TP"], aggregate["FP"], aggregate["FN"]
return {
"samples": len(rows),
"question_records_represented": len(rows) * 5,
"samples_without_reference_flood_pixels": sum(
int(row["reference_flood_pixels"]) == 0 for row in rows
),
"macro": {
"IoU": metric_mean("IoU"),
"precision": metric_mean("precision"),
"recall": metric_mean("recall"),
"F1": metric_mean("F1"),
"recall_defined_samples": sum(row.get("recall") is not None for row in rows),
},
"aggregate_confusion": aggregate,
"micro": {
"IoU": round6(safe_div(tp, tp + fp + fn)),
"precision": round6(safe_div(tp, tp + fp)),
"recall": round6(safe_div(tp, tp + fn)),
"F1": round6(safe_div(2 * tp, 2 * tp + fp + fn)),
},
}
def write_report(output_dir: Path, result: dict[str, Any]) -> None:
output_dir.mkdir(parents=True, exist_ok=True)
(output_dir / "summary.json").write_text(
json.dumps(result, indent=2, sort_keys=False) + "\n", encoding="utf-8"
)
with (output_dir / "per_sample_metrics.jsonl").open("w", encoding="utf-8") as stream:
for row in result["per_sample_metrics"]:
stream.write(json.dumps(row, sort_keys=True) + "\n")
held_out = result["summaries"]["test"]
overall = result["summaries"]["all"]
audit = result["contract_audit"]
text = f"""# C12 Sentinel-1 reference-label evaluation
This is an evaluator-side construct-validity report. The 500 agent-facing
questions and expected answers describe outputs of `{METHOD}`. They do not
claim that those outputs equal the Sen1Floods11 hand labels, and the labels are
not declared agent inputs.
## Contract audit
- Sentinel records: {audit['records']} (100 scenes x A-E)
- Declared reference-label paths: {audit['records_with_declared_reference_label']}
- Expected answers containing accuracy/IoU/F1/precision/recall: {audit['records_with_accuracy_fields_in_expected_answer']}
- Wrong or missing `prediction_method`: {audit['records_with_wrong_or_missing_prediction_method']}
- Scenes whose recomputed flood percentage matches the canonical answer: {audit['samples_matching_canonical_prediction_percentage']}/100
## Held-out test result
- Scenes: {held_out['samples']} ({held_out['question_records_represented']} question records)
- Macro IoU / F1: {held_out['macro']['IoU']} / {held_out['macro']['F1']}
- Macro precision / recall: {held_out['macro']['precision']} / {held_out['macro']['recall']}
- Micro IoU / F1: {held_out['micro']['IoU']} / {held_out['micro']['F1']}
- Micro precision / recall: {held_out['micro']['precision']} / {held_out['micro']['recall']}
## All-scene diagnostic
- Scenes: {overall['samples']} ({overall['question_records_represented']} question records)
- Macro IoU / F1: {overall['macro']['IoU']} / {overall['macro']['F1']}
- Micro IoU / F1: {overall['micro']['IoU']} / {overall['micro']['F1']}
- Scenes with no positive reference pixels (recall undefined): {overall['samples_without_reference_flood_pixels']}
## Interpretation
The baseline has relatively high recall and low precision; it is a simple,
reproducible flood-candidate baseline, not a validated operational flood map.
The held-out metrics quantify its agreement with `LabelHand`, but do not turn
the agent-facing targets into ground-truth flood masks. No acceptance threshold
was selected after observing these results.
"""
(output_dir / "README.md").write_text(text, encoding="utf-8")
def parser() -> argparse.ArgumentParser:
result = argparse.ArgumentParser(description=__doc__)
root = Path(__file__).resolve().parents[1]
result.add_argument("--root", type=Path, default=root)
result.add_argument(
"--dataset",
type=Path,
default=Path("data/core/geodisaster_2921_source_with_splits.jsonl"),
)
result.add_argument(
"--output-dir",
type=Path,
default=Path("sen1_accuracy_results"),
)
return result
def main() -> None:
args = parser().parse_args()
root = args.root.resolve()
dataset = args.dataset if args.dataset.is_absolute() else root / args.dataset
output_dir = args.output_dir if args.output_dir.is_absolute() else root / args.output_dir
samples, audit = load_contract(dataset)
if audit["records_with_declared_reference_label"]:
raise RuntimeError("reference-label leakage detected in declared initial artifacts")
if audit["records_with_accuracy_fields_in_expected_answer"]:
raise RuntimeError("agent-facing expected answers improperly contain accuracy fields")
if audit["records_with_wrong_or_missing_prediction_method"]:
raise RuntimeError("Sentinel expected-answer method contract is inconsistent")
rows = [evaluate_sample(root, samples[key]) for key in sorted(samples)]
canonical_mismatches = [
row["sample_id"] for row in rows if not row["canonical_prediction_percentage_match"]
]
audit["samples_matching_canonical_prediction_percentage"] = len(rows) - len(canonical_mismatches)
audit["canonical_prediction_percentage_mismatches"] = canonical_mismatches
if canonical_mismatches:
raise RuntimeError(
"evaluator prediction does not reproduce canonical expected values for: "
+ ", ".join(canonical_mismatches)
)
grouped: dict[str, list[dict[str, Any]]] = defaultdict(list)
for row in rows:
grouped[str(row["split"])].append(row)
if set(grouped) != {"train", "test"}:
raise ValueError(f"unexpected sample splits: {sorted(grouped)}")
result = {
"schema_version": "c12_sen1_reference_label_evaluation_v1",
"dataset": str(dataset.relative_to(root)),
"dataset_sha256": sha256(dataset),
"prediction_method": METHOD,
"reference": REFERENCE_NAME,
"reference_valid_values": [0, 1],
"reference_nodata_value": -1,
"contract_audit": audit,
"summaries": {
"all": summarize(rows),
"train": summarize(grouped["train"]),
"test": summarize(grouped["test"]),
},
"per_sample_metrics": rows,
}
write_report(output_dir, result)
print(json.dumps({"output_dir": str(output_dir), "summaries": result["summaries"]}, indent=2))
if __name__ == "__main__":
main()