CARLA-MWRS / scripts /validate_release.py
PeterNano's picture
Add CARLA-MWRS v1.0.0 metadata and verification tools
1788f61 verified
Raw
History Blame Contribute Delete
12 kB
#!/usr/bin/env python3
"""Validate an unpacked CARLA-MWRS release or the canonical source tree.
The validator is intentionally independent of the IAF-Net training code. It
checks pairing, the frozen Town/weather protocol, image encodings, NumPy
headers and values, calibration records, and the depth conversion invariant.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import re
import sys
from collections import Counter
from pathlib import Path
import numpy as np
from PIL import Image
MODALITIES = {
"image_2": ".png",
"gt_image_2": ".png",
"depth_u16": ".png",
"depth_meters": ".npy",
"normal": ".npy",
"calib": ".txt",
}
WEATHERS = ("ClearDay", "ClearNight", "HeavyFoggyNight", "HeavyRainFoggyNight")
EXPECTED = {
"training": {"towns": ("Town05", "Town06"), "total": 2400, "per_weather": 600},
"validation": {"towns": ("Town04",), "total": 1200, "per_weather": 300},
}
STEM_RE = re.compile(
r"^(Town04|Town05|Town06)_(ClearDay|ClearNight|HeavyFoggyNight|HeavyRainFoggyNight)_(\d{6})$"
)
def fail(errors: list[str], message: str) -> None:
errors.append(message)
def sha256_file(path: Path, chunk: int = 1024 * 1024) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
while True:
block = f.read(chunk)
if not block:
break
h.update(block)
return h.hexdigest()
def parse_calibration(path: Path, errors: list[str]) -> dict[str, list[float]]:
values: dict[str, list[float]] = {}
try:
lines = path.read_text(encoding="utf-8").splitlines()
except Exception as exc: # pragma: no cover - diagnostic path
fail(errors, f"{path}: cannot read calibration ({exc})")
return values
for line in lines:
if ":" not in line:
continue
key, raw = line.split(":", 1)
try:
vals = [float(x) for x in raw.split()]
except ValueError:
fail(errors, f"{path}: non-numeric calibration line")
continue
values[key.strip()] = vals
if len(values.get("P2", [])) != 12:
fail(errors, f"{path}: P2 must contain 12 values")
if len(values.get("Vehicle_pos", [])) != 3:
fail(errors, f"{path}: Vehicle_pos must contain 3 values")
if any(not math.isfinite(x) for xs in values.values() for x in xs):
fail(errors, f"{path}: non-finite calibration value")
return values
def validate(root: Path, full_values: bool = True) -> dict:
errors: list[str] = []
report: dict = {
"root": str(root),
"status": "PASS",
"splits": {},
"errors": errors,
}
for split, spec in EXPECTED.items():
split_report: dict = {"modalities": {}, "weather_counts": {}, "town_counts": {}}
report["splits"][split] = split_report
stem_sets: dict[str, set[str]] = {}
for modality, suffix in MODALITIES.items():
directory = root / split / modality
if not directory.is_dir():
fail(errors, f"missing directory: {directory}")
stem_sets[modality] = set()
continue
paths = sorted(p for p in directory.iterdir() if p.is_file())
wrong = [p.name for p in paths if p.suffix.lower() != suffix]
if wrong:
fail(errors, f"{directory}: unexpected extensions ({wrong[:3]})")
stems = {p.stem for p in paths if p.suffix.lower() == suffix}
if len(stems) != len([p for p in paths if p.suffix.lower() == suffix]):
fail(errors, f"{directory}: duplicate stems")
stem_sets[modality] = stems
split_report["modalities"][modality] = {"count": len(paths), "suffix": suffix}
if stem_sets:
union = set().union(*stem_sets.values())
if len(union) != spec["total"]:
fail(errors, f"{split}: expected {spec['total']} unique stems, got {len(union)}")
first = stem_sets.get("image_2", set())
for modality, stems in stem_sets.items():
if stems != first:
fail(errors, f"{split}: stem mismatch image_2 vs {modality}")
counts = Counter()
towns = Counter()
for stem in sorted(first):
match = STEM_RE.match(stem)
if not match:
fail(errors, f"{split}: invalid stem {stem}")
continue
town, weather, _ = match.groups()
counts[weather] += 1
towns[town] += 1
if town not in spec["towns"]:
fail(errors, f"{split}: unexpected town {town} in {stem}")
split_report["weather_counts"] = dict(sorted(counts.items()))
split_report["town_counts"] = dict(sorted(towns.items()))
for weather in WEATHERS:
if counts[weather] != spec["per_weather"]:
fail(errors, f"{split}: {weather} expected {spec['per_weather']}, got {counts[weather]}")
# Decode every file. This is deliberately strict for a release
# validator; --headers-only below can be added if a future release
# becomes too large for a quick CI job.
value_stats = {
"rgb_min": 255,
"rgb_max": 0,
"gt_values": set(),
"depth_u16_min": 65535,
"depth_u16_max": 0,
"depth_meters_min": float("inf"),
"depth_meters_max": float("-inf"),
"normal_min": float("inf"),
"normal_max": float("-inf"),
"normal_norm_min": float("inf"),
"normal_norm_max": float("-inf"),
"depth_saturated_pixels": 0,
"depth_mismatch_pixels": 0,
}
for stem in sorted(first):
rgb_path = root / split / "image_2" / f"{stem}.png"
gt_path = root / split / "gt_image_2" / f"{stem}.png"
du_path = root / split / "depth_u16" / f"{stem}.png"
dm_path = root / split / "depth_meters" / f"{stem}.npy"
no_path = root / split / "normal" / f"{stem}.npy"
ca_path = root / split / "calib" / f"{stem}.txt"
try:
rgb = np.asarray(Image.open(rgb_path))
if rgb.shape != (384, 1248, 3) or rgb.dtype != np.uint8:
fail(errors, f"{rgb_path}: expected RGB uint8 (384,1248,3), got {rgb.shape} {rgb.dtype}")
value_stats["rgb_min"] = min(value_stats["rgb_min"], int(rgb.min()))
value_stats["rgb_max"] = max(value_stats["rgb_max"], int(rgb.max()))
except Exception as exc:
fail(errors, f"{rgb_path}: decode failed ({exc})")
try:
gt = np.asarray(Image.open(gt_path))
if gt.shape != (384, 1248) or gt.dtype != np.uint8:
fail(errors, f"{gt_path}: expected grayscale uint8 (384,1248), got {gt.shape} {gt.dtype}")
value_stats["gt_values"].update(int(x) for x in np.unique(gt))
if not set(np.unique(gt).tolist()).issubset({0, 255}):
fail(errors, f"{gt_path}: label contains values outside {{0,255}}")
except Exception as exc:
fail(errors, f"{gt_path}: decode failed ({exc})")
try:
du = np.asarray(Image.open(du_path))
if du.shape != (384, 1248) or du.dtype != np.uint16:
fail(errors, f"{du_path}: expected uint16 (384,1248), got {du.shape} {du.dtype}")
value_stats["depth_u16_min"] = min(value_stats["depth_u16_min"], int(du.min()))
value_stats["depth_u16_max"] = max(value_stats["depth_u16_max"], int(du.max()))
value_stats["depth_saturated_pixels"] += int(np.count_nonzero(du == 65535))
except Exception as exc:
fail(errors, f"{du_path}: decode failed ({exc})")
du = None
try:
dm = np.load(dm_path, allow_pickle=False)
if dm.shape != (384, 1248) or dm.dtype != np.dtype("<f4"):
fail(errors, f"{dm_path}: expected little-endian float32 (384,1248), got {dm.shape} {dm.dtype}")
if not np.isfinite(dm).all() or (dm < 0).any():
fail(errors, f"{dm_path}: non-finite or negative depth")
value_stats["depth_meters_min"] = min(value_stats["depth_meters_min"], float(dm.min()))
value_stats["depth_meters_max"] = max(value_stats["depth_meters_max"], float(dm.max()))
if du is not None:
# Preserve the float32 arithmetic used when the
# materialization was written. Promoting to float64
# before floor can move values that are mathematically
# integral by one ULP to the neighbouring bin.
expected_du = np.clip(np.floor(dm * np.float32(1000.0)), 0, 65535).astype(np.uint16)
value_stats["depth_mismatch_pixels"] += int(np.count_nonzero(expected_du != du))
except Exception as exc:
fail(errors, f"{dm_path}: load/validation failed ({exc})")
try:
normal = np.load(no_path, allow_pickle=False)
if normal.shape != (3, 384, 1248) or normal.dtype != np.dtype("<f4"):
fail(errors, f"{no_path}: expected little-endian float32 (3,384,1248), got {normal.shape} {normal.dtype}")
if not np.isfinite(normal).all():
fail(errors, f"{no_path}: non-finite normal")
value_stats["normal_min"] = min(value_stats["normal_min"], float(normal.min()))
value_stats["normal_max"] = max(value_stats["normal_max"], float(normal.max()))
norms = np.linalg.norm(normal, axis=0)
value_stats["normal_norm_min"] = min(value_stats["normal_norm_min"], float(norms.min()))
value_stats["normal_norm_max"] = max(value_stats["normal_norm_max"], float(norms.max()))
if float(np.max(np.abs(norms - 1.0))) > 1e-3:
fail(errors, f"{no_path}: normal norm exceeds 1e-3 tolerance")
except Exception as exc:
fail(errors, f"{no_path}: load/validation failed ({exc})")
parsed = parse_calibration(ca_path, errors)
if parsed.get("P2") != [624.0, 0.0, 624.0, 0.0, 0.0, 624.0, 192.0, 0.0, 0.0, 0.0, 1.0, 0.0]:
# Do not require one exact matrix for future compatible
# releases, but record a warning-like error for malformed
# dimensions only. The current protocol is uniform.
if len(parsed.get("P2", [])) != 12:
fail(errors, f"{ca_path}: malformed P2")
value_stats["gt_values"] = sorted(value_stats["gt_values"])
split_report["value_ranges"] = value_stats
report["status"] = "PASS" if not errors else "FAIL"
return report
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--data-root", type=Path, required=True)
parser.add_argument("--report", type=Path)
args = parser.parse_args()
report = validate(args.data_root.resolve())
encoded = json.dumps(report, indent=2, sort_keys=True, default=list) + "\n"
if args.report:
args.report.write_text(encoded, encoding="utf-8")
print(encoded, end="")
return 0 if report["status"] == "PASS" else 1
if __name__ == "__main__":
sys.exit(main())