File size: 5,044 Bytes
2a7bf26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#!/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()