Physibench / eval /validate_dataset.py
sattsansar's picture
Upload folder using huggingface_hub (part 2)
c263a1a verified
Raw History Blame Contribute Delete
7.83 kB
"""
validate_dataset.py — full PhysiBench audit
----------------------------------------------
Checks EVERY item in dataset.jsonl, not just valid ones:
VALID items:
1. Stored x/y matches an independently recomputed physics simulation
2. Starts at (0,0), never underground, lands by the final point
3. max_height_m / range_m metadata matches a fresh calculation
4. No NaN/Infinity
INVALID items:
5. Stored x/y does NOT match clean physics — i.e. actually broken,
not accidentally a valid trajectory mislabeled as invalid
ALL items:
6. Image file exists and opens without corruption
7. No duplicate (v0, angle_deg, g, drag) parameter combos
8. No duplicate ids
9. Every item assigned to exactly one split (train/val/test)
10. Total counts match expectations (300 total, 210/45/45 splits)
Run with: python3 validate_dataset.py
"""
import json
import os
import numpy as np
from PIL import Image
from collections import Counter
DATASET_PATH = "../data/dataset.jsonl"
IMAGES_BASE = "../data"
TOLERANCE = 0.15 # meters
def independent_recompute(v0, angle_deg, g, drag):
"""Separately reimplemented from physics.py — not just checking the
generator against itself."""
angle_rad = np.radians(angle_deg)
vx0 = v0 * np.cos(angle_rad)
vy0 = v0 * np.sin(angle_rad)
if not drag:
t_flight = 2 * vy0 / g
t = np.linspace(0, t_flight, 6)
x = vx0 * t
y = vy0 * t - 0.5 * g * t**2
return x, y
else:
Cd, rho, r, mass = 0.47, 1.225, 0.11, 0.6
A = np.pi * r**2
vx, vy, x, y, t, dt = vx0, vy0, 0.0, 0.0, 0.0, 0.001
xs, ys = [x], [y]
while y >= 0 and t < 10:
speed = np.sqrt(vx**2 + vy**2)
f = 0.5 * Cd * rho * A * speed**2
ax = -f * (vx / speed) / mass if speed > 0 else 0
ay = -g + (-f * (vy / speed) / mass if speed > 0 else 0)
vx += ax * dt
vy += ay * dt
x += vx * dt
y += vy * dt
t += dt
xs.append(x)
ys.append(y)
idx = np.linspace(0, len(xs) - 1, 6).astype(int)
return np.array([xs[i] for i in idx]), np.array([ys[i] for i in idx])
def check_valid_item(rec):
issues = []
x = np.array(rec["x"])
y = np.array(rec["y"])
p = rec["params"]
if not np.all(np.isfinite(x)) or not np.all(np.isfinite(y)):
issues.append("contains NaN or Infinity")
return issues
if abs(x[0]) > 0.01 or abs(y[0]) > 0.01:
issues.append(f"doesn't start at (0,0): starts at ({x[0]:.2f}, {y[0]:.2f})")
if y.min() < -0.05:
issues.append(f"goes underground: min y = {y.min():.3f}")
if abs(y[-1]) > 0.3:
issues.append(f"doesn't land by final point: y[-1] = {y[-1]:.2f}")
recomputed_x, recomputed_y = independent_recompute(p["v0"], p["angle_deg"], p["g"], p["drag"])
max_diff_x = np.max(np.abs(recomputed_x - x))
max_diff_y = np.max(np.abs(recomputed_y - y))
if max_diff_x > TOLERANCE or max_diff_y > TOLERANCE:
issues.append(f"stored coordinates don't match recomputed physics: max diff x={max_diff_x:.3f}, y={max_diff_y:.3f}")
angle_rad = np.radians(p["angle_deg"])
expected_height = (p["v0"] ** 2 * np.sin(angle_rad) ** 2) / (2 * p["g"])
expected_range = (p["v0"] ** 2 * np.sin(2 * angle_rad)) / p["g"]
if abs(expected_height - p["max_height_m"]) > TOLERANCE:
issues.append(f"max_height_m mismatch: stored {p['max_height_m']}, expected {expected_height:.2f}")
if abs(expected_range - p["range_m"]) > TOLERANCE:
issues.append(f"range_m mismatch: stored {p['range_m']}, expected {expected_range:.2f}")
return issues
def check_invalid_item(rec):
"""Confirm this item is GENUINELY non-physical — i.e. its stored path
deviates meaningfully from what clean physics would produce. Catches
the case where a violation function accidentally produced something
that's still physically plausible."""
issues = []
x = np.array(rec["x"])
y = np.array(rec["y"])
p = rec["params"]
if not np.all(np.isfinite(x)) or not np.all(np.isfinite(y)):
issues.append("contains NaN or Infinity")
return issues
clean_x, clean_y = independent_recompute(p["v0"], p["angle_deg"], p["g"], False)
diff_x = np.max(np.abs(clean_x - x))
diff_y = np.max(np.abs(clean_y - y))
# If a supposedly "broken" trajectory is nearly identical to clean physics,
# the violation didn't actually do anything — mislabeled data.
if diff_x < TOLERANCE and diff_y < TOLERANCE:
issues.append(f"labeled invalid but matches clean physics (diff x={diff_x:.3f}, y={diff_y:.3f}) — violation had no effect")
return issues
def main():
with open(DATASET_PATH) as f:
records = [json.loads(line) for line in f]
print(f"Auditing {len(records)} total items...\n")
problems = []
# ---- Per-item checks ----
param_signatures = []
seen_ids = set()
for rec in records:
# 8. duplicate ids
if rec["id"] in seen_ids:
problems.append(f"{rec['id']}: DUPLICATE ID")
seen_ids.add(rec["id"])
# 6. image file integrity
img_path = os.path.join(IMAGES_BASE, rec["image_path"])
if not os.path.exists(img_path):
problems.append(f"{rec['id']}: image file missing at {img_path}")
else:
try:
with Image.open(img_path) as im:
im.verify()
except Exception as e:
problems.append(f"{rec['id']}: image file corrupted ({e})")
# 9. split assignment
if rec.get("split") not in ("train", "val", "test"):
problems.append(f"{rec['id']}: invalid/missing split '{rec.get('split')}'")
# physics checks
if rec["valid"]:
issues = check_valid_item(rec)
else:
issues = check_invalid_item(rec)
for issue in issues:
problems.append(f"{rec['id']}: {issue}")
# 7. collect param signatures for duplicate check
p = rec["params"]
sig = (round(p["v0"], 2), round(p["angle_deg"], 2), p["g"], p["drag"], rec["valid"], rec["violation_type"])
param_signatures.append(sig)
# 7. duplicate param combos
sig_counts = Counter(param_signatures)
dupes = {sig: count for sig, count in sig_counts.items() if count > 1}
if dupes:
problems.append(f"{len(dupes)} duplicate parameter combinations found (same v0/angle/g/drag/label)")
# 10. count checks
valid_count = sum(1 for r in records if r["valid"])
invalid_count = len(records) - valid_count
split_counts = Counter(r.get("split") for r in records)
violation_counts = Counter(r["violation_type"] for r in records if not r["valid"])
print("=" * 55)
print(f"Total items: {len(records)} (expected 300)")
print(f"Valid: {valid_count} (expected 180)")
print(f"Invalid: {invalid_count} (expected 120)")
print(f"Splits: {dict(split_counts)} (expected train=210, val=45, test=45)")
print(f"Violation types: {dict(violation_counts)} (expected 24 each)")
print("=" * 55)
if problems:
print(f"\nFAILED — {len(problems)} issue(s) found:\n")
for p in problems[:50]: # cap output if there are many
print(f" - {p}")
if len(problems) > 50:
print(f" ... and {len(problems) - 50} more")
else:
print(f"\nPASSED — all {len(records)} items verified clean.")
print("All valid items: physically correct, matched to independent recomputation.")
print("All invalid items: genuinely deviate from clean physics (violations had real effect).")
print("No duplicates, no missing/corrupt images, no split errors.")
if __name__ == "__main__":
main()