Y-SAGE_Full_window_dataset / code /02_verify_outputs.py
Tuteldove's picture
Add N64 full-window protocol and reproduction code
c800256 verified
Raw
History Blame Contribute Delete
6.46 kB
# -*- coding: utf-8 -*-
"""Verify outputs from 01_full_to_n64_windows.py."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import numpy as np
import pandas as pd
DEFAULT_CHUNK_SIZE = 25_000
TOL = 2.0e-6
BASE_REQUIRED = {
"source_row_id",
"original_x",
"image_width",
"image_height",
"aspect_ratio",
"k1",
"full_estimated_midline_x",
"full_feature_x_min",
"full_feature_x_max",
"full_feature_x_span",
}
WINDOW_REQUIRED = {
"source_row_id",
"window_id",
"window_y0_norm",
"window_y1_norm",
"estimated_midline_x",
"feature_x_min",
"feature_x_max",
"feature_x_span",
"feature_y_min_norm",
"feature_y_max_norm",
"feature_y_span_norm",
"feature_y_valid",
"n_observed_samples",
"hgm_sample_count",
"reobserve_protocol",
}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--manifest", type=Path, required=True)
parser.add_argument("--full-scan", action="store_true")
parser.add_argument("--chunk-size", type=int, default=DEFAULT_CHUNK_SIZE)
parser.add_argument("--report", type=Path, default=None)
return parser.parse_args()
def finite_max(values: np.ndarray) -> float:
arr = np.asarray(values, dtype=np.float64)
arr = arr[np.isfinite(arr)]
return float(np.max(arr)) if arr.size else 0.0
def scan_window(path: Path, chunk_size: int) -> dict[str, float | int]:
rows = 0
hgm_err = 0.0
x_span_err = 0.0
y_span_err = 0.0
support_leaks = 0
for chunk in pd.read_csv(path, chunksize=chunk_size, low_memory=False):
rows += len(chunk)
valid = pd.to_numeric(chunk["feature_y_valid"], errors="coerce").fillna(0).to_numpy(dtype=np.int64) == 1
x_min = pd.to_numeric(chunk["feature_x_min"], errors="coerce").to_numpy(dtype=np.float64)
x_max = pd.to_numeric(chunk["feature_x_max"], errors="coerce").to_numpy(dtype=np.float64)
span = pd.to_numeric(chunk["feature_x_span"], errors="coerce").to_numpy(dtype=np.float64)
hgm = pd.to_numeric(chunk["estimated_midline_x"], errors="coerce").to_numpy(dtype=np.float64)
y_min = pd.to_numeric(chunk["feature_y_min_norm"], errors="coerce").to_numpy(dtype=np.float64)
y_max = pd.to_numeric(chunk["feature_y_max_norm"], errors="coerce").to_numpy(dtype=np.float64)
y_span = pd.to_numeric(chunk["feature_y_span_norm"], errors="coerce").to_numpy(dtype=np.float64)
low = pd.to_numeric(chunk["window_y0_norm"], errors="coerce").to_numpy(dtype=np.float64)
high = pd.to_numeric(chunk["window_y1_norm"], errors="coerce").to_numpy(dtype=np.float64)
hgm_err = max(hgm_err, finite_max(np.abs(hgm[valid] - 0.5 * (x_min[valid] + x_max[valid]))))
x_span_err = max(x_span_err, finite_max(np.abs(span[valid] - (x_max[valid] - x_min[valid]))))
y_span_err = max(y_span_err, finite_max(np.abs(y_span[valid] - (y_max[valid] - y_min[valid]))))
support_leaks += int(((y_min[valid] < low[valid] - TOL) | (y_max[valid] > high[valid] + TOL)).sum())
return {
"rows": rows,
"max_hgm_formula_abs_err": hgm_err,
"max_x_span_formula_abs_err": x_span_err,
"max_y_span_formula_abs_err": y_span_err,
"support_leak_count": support_leaks,
}
def main() -> None:
args = parse_args()
manifest = json.loads(args.manifest.read_text(encoding="utf-8-sig"))
failures: list[str] = []
if manifest.get("status") != "complete":
failures.append("manifest status is not complete")
if manifest.get("random_x_resampling") is not False:
failures.append("random_x_resampling must be false")
if manifest.get("camera_jitter") is not False:
failures.append("camera_jitter must be false")
if not manifest.get("validation", {}).get("overall_valid", False):
failures.append("producer internal validation failed")
base_path = Path(manifest["outputs"]["base_feature_reference"])
if not base_path.exists():
failures.append(f"missing base reference: {base_path}")
base_columns: set[str] = set()
else:
base_columns = set(pd.read_csv(base_path, nrows=0).columns)
missing = BASE_REQUIRED - base_columns
if missing:
failures.append(f"base reference missing columns: {sorted(missing)}")
window_reports: dict[str, object] = {}
expected_rows = int(manifest["rows_written"])
for window_id, value in manifest["outputs"]["window_observations"].items():
path = Path(value)
if not path.exists():
failures.append(f"missing window output: {path}")
continue
columns = set(pd.read_csv(path, nrows=0).columns)
missing = WINDOW_REQUIRED - columns
if missing:
failures.append(f"{window_id} missing columns: {sorted(missing)}")
if args.full_scan:
report = scan_window(path, args.chunk_size)
window_reports[window_id] = report
if int(report["rows"]) != expected_rows:
failures.append(f"{window_id} row count {report['rows']} != {expected_rows}")
if float(report["max_hgm_formula_abs_err"]) > TOL:
failures.append(f"{window_id} HGM formula error exceeds tolerance")
if float(report["max_x_span_formula_abs_err"]) > TOL:
failures.append(f"{window_id} x-span formula error exceeds tolerance")
if float(report["max_y_span_formula_abs_err"]) > TOL:
failures.append(f"{window_id} y-span formula error exceeds tolerance")
if int(report["support_leak_count"]) != 0:
failures.append(f"{window_id} support leakage detected")
result = {
"manifest": str(args.manifest),
"full_scan": bool(args.full_scan),
"expected_rows_per_output": expected_rows,
"window_count": len(manifest["outputs"]["window_observations"]),
"window_reports": window_reports,
"failures": failures,
"overall_valid": len(failures) == 0,
}
report_path = args.report or args.manifest.with_name("shortest_path_verification.json")
report_path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps(result, ensure_ascii=False, indent=2))
if failures:
raise SystemExit(1)
if __name__ == "__main__":
main()