jimchen2-pendulum-shift / scripts /crosscheck_answers.py
jimchen2's picture
Upload folder using huggingface_hub (part 2)
2a7bf26 verified
Raw History Blame Contribute Delete
5.04 kB
#!/usr/bin/env python3
"""Cross-check emitted descriptive answers against INDEPENDENT ground truth.
python3 crosscheck_answers.py
Deliberately does NOT import questions_v2. It recomputes every answer straight
from the shipped frame-aligned CSVs using a different peak-detection method
(local maxima of |theta| via neighbour comparison, instead of omega sign
changes), so agreement is real evidence rather than the same code agreeing
with itself.
"""
from __future__ import annotations
import csv
import json
import sys
from pathlib import Path
import numpy as np
OMEGA_STILL = 0.196
def load(path, hi, lo=0):
rows = list(csv.DictReader(open(path)))
return {k: np.asarray([float(r[k]) for r in rows], dtype=float) for k in rows[0]}
def turning_points(theta_deg, omega0):
"""Frames where the bob reverses direction.
Independent of the integrated `omega_rad_s` series used by questions_v2:
interior velocities come from finite differences of the angle series. Only
the initial velocity is taken from the data (it cannot be differenced -
there is no frame before it), which matters because a bob released at max
displacement with a small outward velocity turns around *inside the first
frame interval* and a pure-difference detector would miss it.
"""
n = len(theta_deg)
v = np.empty(n)
v[0] = omega0
v[1:] = np.diff(theta_deg)
return np.array([i for i in range(n - 1)
if v[i] == 0.0 or v[i] * v[i + 1] < 0.0], dtype=int)
def truth(A, hi, lo=0):
th = A["theta_deg"][lo:hi]
om = A["omega_rad_s"][lo:hi]
lt = A["light_angle_deg"][lo:hi]
pk = turning_points(th, float(om[0]))
amps = np.maximum(np.abs(th[pk]), np.abs(th[pk + 1])) if len(pk) else np.array([])
def side(d):
return "left" if d < 0 else "right"
def band(v, t1, t2):
return "small" if v < t1 else ("medium" if v < t2 else "large")
t = {}
t["count_swing_wide"] = str(int((amps > 15.0).sum()))
t["count_swing_very_wide"] = str(int((amps > 20.0).sum()))
t["count_turning_points"] = str(len(pk))
t["query_release_side"] = side(A["theta_deg"][lo])
t["query_initial_direction"] = ("left" if om[0] < -0.01
else "right" if om[0] > 0.01 else "still")
t["query_release_amplitude"] = band(abs(A["theta_deg"][lo]), 23.0, 32.0)
if len(pk) >= 3:
t["query_mid_amplitude"] = band(float(amps[len(pk) // 2]), 8.0, 18.0)
win = om[-12:]
omax = float(np.max(np.abs(win)))
j = int(np.argmax(np.abs(win)))
t["query_end_direction"] = ("still" if omax < OMEGA_STILL
else "left" if win[j] < 0 else "right")
t["query_end_side"] = side(A["theta_deg"][hi - 1])
t["query_light_travel"] = band(float(lt.max() - lt.min()), 10.0, 20.0)
t["query_light_direction"] = ("left" if lt[1] < lt[0] else "right")
t["exist_still_swinging"] = "yes" if omax >= OMEGA_STILL else "no"
return t
def main():
pairs = [("out/questions/questions_train.json", "root_ts/{}.csv", 0, 160),
("out/questions/questions_val.json", "root_ts/{}.csv", 0, 160),
("out/intervened/questions/questions_train.json",
"itv_ts/{}.csv", 0, 96)]
itv_kind = {r["video_id"]: r["intervention_type"] for r in
csv.DictReader(open("intervened/index_intervention.csv"))}
ITV_TRUTH = {
"light_shift": {"query_intervention_target": "light",
"query_intervention_invariant": "bob",
"query_energy_at_cut": "smooth"},
"torque_push": {"query_intervention_target": "bob",
"query_intervention_invariant": "light",
"query_energy_at_cut": "jumps"},
}
n = bad = skipped = 0
for src, tpl, lo, hi in pairs:
data = json.load(open(src))
sampled = [v for v in data["scene_annotation"]
if Path(tpl.format(v["video_id"])).exists()]
for v in sampled:
A = load(tpl.format(v["video_id"]), hi, lo)
t = dict(truth(A, hi, lo))
if v["video_id"] in itv_kind:
t.update(ITV_TRUTH[itv_kind[v["video_id"]]])
for q in v["questions"]:
if q["question_type"] != "descriptive":
continue
fam = q["question_family"]
if fam not in t: # gated out for this window
skipped += 1
continue
n += 1
if str(q["answer"]) != str(t[fam]):
bad += 1
if bad <= 10:
print(f" MISMATCH {v['video_id']} {fam}: "
f"emitted={q['answer']!r} truth={t[fam]!r}")
print(f"\nchecked {n} answers ({skipped} skipped as gated), "
f"{bad} mismatches")
print("ALL ANSWERS CORRECT" if not bad else f"{bad} WRONG")
sys.exit(0 if not bad else 1)
if __name__ == "__main__":
main()