File size: 16,015 Bytes
9e6da2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2de4806
 
9e6da2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7de16d
9e6da2c
c7de16d
 
9e6da2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7de16d
9e6da2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7de16d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2de4806
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e6da2c
 
 
 
 
 
 
 
 
 
 
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
"""The exported probe test set is self-contained, self-consistent, and scorable.

`probes.json` used to be the "test set": amplitudes, speeds and an episode
name. Reproducing a probe from it required the raw HDF5, which is not
published, so nothing could actually be evaluated. These checks are the ones
that would have caught that.

  SELF-CONTAINED  everything needed to score a rollout ships in the package —
                  context images, the action, the held hand, the calibration.
  SELF-CONSISTENT the ground-truth pixels recompute from the calibration IN
                  the package. A stored projection that only agrees with the
                  calibration on my disk is a trap.
  SCORABLE        the scorer returns zero on the ground truth and recovers a
                  known injected error. A metric that cannot be shown to move
                  cannot be shown to mean anything.

    python scripts/test_probe_testset.py
"""
from __future__ import annotations

import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from react_paths import release_root, testset_root   # noqa: E402

import numpy as np                                             # noqa: E402

import react_toolbox.calibration as T_                          # noqa: E402

RESULTS: list[tuple[bool, str, str]] = []
ROOT = testset_root()


def check(ok: bool, name: str, evidence: str) -> None:
    RESULTS.append((bool(ok), name, evidence))


def main() -> int:
    import cv2

    from react_toolbox.calibration import load_calibration
    from react_toolbox.probe_eval import project_gt, rollout_error
    from scipy.spatial.transform import Rotation

    man = json.loads((ROOT / "manifest.json").read_text())
    # loaded from the PACKAGE, not from the repo — that is the point
    cal = load_calibration(ROOT)

    runs = [json.loads((ROOT / p["meta"]).read_text()) for p in man["probes"]]
    files = [(r, q) for r in runs for q in r["probes"]]

    # 1 — everything a scorer needs is present
    missing = []
    for r, q in files:
        f = ROOT / q["file"]
        if not f.exists():
            missing.append(q["file"]); continue
        d = np.load(f)
        need = {"poses", "held_pose", "gel_pos_m", "delta_gel_pos_m",
                "delta_gel_rotvec_rad", "delta_rigid_pos_m",
                "delta_rigid_rotvec_rad", "action_scalar", "action_axis",
                "action_sign", "context_poses_moving", "context_poses_held"} | \
               {f"gt_px_{v}" for v in man["views"]}
        if not need <= set(d.files):
            missing.append(f"{q['file']}: {sorted(need - set(d.files))}")
    n_ctx = sum(len(list((ROOT / f"probes/run{r['run']}/context").glob("*.jpg")))
                for r in runs)
    check(not missing and n_ctx == len(runs) * man["context_frames"] * len(man["context_streams"]),
          "every probe ships its action, ground truth and context",
          f"{len(files)} probes, {n_ctx} context images ({len(runs)} runs x "
          f"{man['context_frames']} frames x {len(man['context_streams'])} streams)"
          + (f"; missing {missing[:2]}" if missing else ""))

    # 2 — the stored ground-truth pixels recompute from the PACKAGED calibration
    worst, n = 0.0, 0
    for r, q in files[:24]:
        d = np.load(ROOT / q["file"])
        gel = cal[f"gel_{r['moving_side']}"]
        for v in man["views"]:
            got = project_gt(d["poses"], gel, cal["cams"][v])
            a, b = got, d[f"gt_px_{v}"]
            m = np.isfinite(a).all(1) & np.isfinite(b).all(1)
            if m.any():
                worst = max(worst, float(np.max(np.linalg.norm(a[m] - b[m], axis=1))))
                n += int(m.sum())
    check(worst < 1e-6, "stored ground-truth pixels recompute from the package",
          f"worst disagreement {worst:.2e} px over {n} projected points")

    # 3 — the deltas reconstruct the absolute poses
    bad = []
    for r, q in files:
        d = np.load(ROOT / q["file"])
        P = d["poses"]
        # BOTH deltas must integrate: the rigid one back to `poses`, the gel
        # one back to `gel_pos_m`. They are different trajectories — that is
        # the point — so checking only one would let the other rot.
        pos = P[0, :3] + np.cumsum(d["delta_rigid_pos_m"], axis=0)
        e = float(np.max(np.linalg.norm(pos - P[1:, :3], axis=1)))
        g = d["gel_pos_m"][0] + np.cumsum(d["delta_gel_pos_m"], axis=0)
        eg = float(np.max(np.linalg.norm(g - d["gel_pos_m"][1:], axis=1)))
        qq = Rotation.from_quat(P[0, 3:7])
        for rv in d["delta_gel_rotvec_rad"]:
            qq = Rotation.from_rotvec(rv) * qq        # world-frame: pre-multiply
        ang = float(np.degrees((qq.inv() * Rotation.from_quat(P[-1, 3:7])).magnitude()))
        if e > 1e-9 or eg > 1e-9 or ang > 1e-6:
            bad.append(f"{q['file']}: rigid {e:.2e} m, gel {eg:.2e} m, {ang:.2e} deg")
    check(not bad, "the published deltas integrate back to the poses",
          f"{len(files)}/{len(files)} exact to 1e-9 m and 1e-6 deg"
          + (f"; {bad[:2]}" if bad else ""))

    # 4 — THE SCORER IS ZERO ON TRUTH AND MOVES BY A KNOWN AMOUNT.
    r, q = files[0]
    d = np.load(ROOT / q["file"])
    gel = cal[f"gel_{r['moving_side']}"]
    z = rollout_error(d["poses"], d["poses"], gel, cal["cams"]["middle"])
    inj = d["poses"].copy(); inj[:, 0] += 0.010            # 10 mm along world x
    e = rollout_error(inj, d["poses"], gel, cal["cams"]["middle"])
    check(z["pos_mm_final"] < 1e-9 and abs(e["pos_mm_final"] - 10.0) < 1e-6,
          "the scorer is zero on truth and recovers an injected 10 mm",
          f"truth {z['pos_mm_final']:.2e} mm; injected 10 mm reads "
          f"{e['pos_mm_final']:.4f} mm and {e['px_final']:.1f} px")

    # 5 — START FRAMES ARE HELD-OUT FRAMES. Without this the context images
    #     were training frames: the action is novel but the model had already
    #     seen the picture it starts from, and nothing said so.
    sp = json.loads((release_root("motherboard") /
                     "splits.json").read_text())
    leaked = []
    for r in runs:
        info = sp["episodes"].get(r["episode"])
        if info is None:
            leaked.append(f"{r['episode']}: not in splits.json"); continue
        for row in r["context_rows"]:
            if not any(a <= row <= b for a, b in info["test"]):
                leaked.append(f"{r['episode']} row {row}")
    check(not leaked, "every start frame lies in a held-out interval",
          f"{sum(len(r['context_rows']) for r in runs)} context rows across "
          f"{len(runs)} runs, all inside splits.json test intervals"
          + (f"; leaked {leaked[:3]}" if leaked else ""))

    # ...and the world-frame residual is published for every session used
    miss = [d for d in {r["episode"].split("/")[0] for r in runs}
            if d not in man["world_residual"]]
    check(not miss, "each session used publishes its world-frame residual",
          f"{sorted({r['episode'].split('/')[0] for r in runs})}; "
          f"2026-05-19 carries a stated unmeasured yaw rather than being dropped"
          + (f"; missing {miss}" if miss else ""))

    # 6 — the overlay runs and puts the marker where the stored truth says
    from react_toolbox.probe_eval import overlay_gt
    r, q = files[0]
    d = np.load(ROOT / q["file"])
    img = cv2.imread(str(ROOT / f"probes/run{r['run']}/context/ctx3_view_middle.jpg"))[:, :, ::-1]
    vis = overlay_gt(img, d["poses"], cal[f"gel_{r['moving_side']}"],
                     cal["cams"]["middle"], held_pose7=d["held_pose"],
                     held_gel_mm=cal[f"gel_{r['held_side']}"])
    diff = int((np.abs(vis.astype(int) - img.astype(int)).sum(2) > 25).sum())
    start = d["gt_px_middle"][0]
    near = vis[max(0, int(start[1])-4):int(start[1])+5,
               max(0, int(start[0])-4):int(start[0])+5]
    check(vis.shape == img.shape and diff > 200 and near.max() > 240,
          "overlay_gt draws the commanded path on a context frame",
          f"{diff} pixels changed; the start marker is bright at the stored "
          f"ground-truth pixel {np.round(start, 1).tolist()}")

    # 7 — GROUND TRUTH STAYS CLEAR OF THE EDGE. In frame is not enough: a path
    #     ending 15 px from the border cannot be scored, because a rollout that
    #     overshoots even slightly leaves the image entirely. The preview used
    #     an 8 px margin, which is right for looking and wrong for measuring.
    close = []
    for r, q in files:
        d = np.load(ROOT / q["file"])
        p_ = d["gt_px_middle"]
        m = np.isfinite(p_).all(1)
        if not m.any():
            close.append(f"{q['file']}: nothing in view"); continue
        e = float(min(p_[m][:, 0].min(), p_[m][:, 1].min(),
                      (640 - p_[m][:, 0]).min(), (480 - p_[m][:, 1]).min()))
        if e < man["view_margin_px"] - 1:
            close.append(f"{q['file']}: {e:.0f} px")
    check(not close, "ground truth keeps a scoring margin from the edge",
          f"{len(files)}/{len(files)} stay >= {man['view_margin_px']:.0f} px "
          f"inside the middle view"
          + (f"; {close[:2]}" if close else ""))

    # 8 — EACH ACTION MOVES ALONG EXACTLY ONE AXIS. This is the defining
    #     property of the set and nothing checked it. Measured at the GEL:
    #     the pose 7-vec is the marker cluster's and rotations pivot on the
    #     gel 65.7 mm away, so in RIGID-BODY coordinates a "pure rotation"
    #     carries up to 75.7 mm of translation and a model fed that action
    #     reads "translate 76 mm AND rotate 79 deg".
    off = []
    for r, q in files:
        d = np.load(ROOT / q["file"])
        ax = int(d["action_axis"])
        dp, dr = d["delta_gel_pos_m"], d["delta_gel_rotvec_rad"]
        if q["kind"] == "translation":
            cross = float(np.abs(np.delete(dp, ax, axis=1)).max())
            other = float(np.abs(dr).max())
            unit = "m"
        else:
            cross = float(np.abs(np.delete(dr, ax, axis=1)).max())
            other = float(np.abs(dp).max())
            unit = "rad"
        if cross > 1e-12 or other > 1e-9:
            off.append(f"{q['file']}: off-axis {cross:.1e} {unit}, "
                       f"other-kind {other:.1e}")
        # and the 1-D form must reconstruct the full delta
        recon = np.zeros_like(dp)
        recon[:, ax] = d["action_scalar"]
        tgt = dp if q["kind"] == "translation" else dr
        if float(np.abs(recon - tgt).max()) > 1e-15:
            off.append(f"{q['file']}: action_scalar does not reconstruct")
    check(not off, "every action moves along exactly one axis, at the gel",
          f"{len(files)}/{len(files)} have zero off-axis and zero other-kind "
          f"motion, and action_scalar reconstructs the delta exactly"
          + (f"; {off[:2]}" if off else ""))

    # ...and the rigid-body delta is NOT zero for rotations, which is the whole
    # reason the gel frame is the primary one. Asserted so the distinction
    # cannot quietly collapse back.
    rots = [(r, q) for r, q in files if q["kind"] == "rotation"]
    mx = max(float(np.abs(np.load(ROOT / q["file"])["delta_rigid_pos_m"]).sum(0).max())
             for _, q in rots)
    check(mx > 0.005, "the rigid-body action is documented as different",
          f"rotation probes carry up to {mx*1000:.0f} mm of marker-cluster "
          f"translation, which is why delta_gel_* is primary")

    # 11 — THE CONTEXT INCLUDES TACTILE. The first export shipped three camera
    #      views and nothing else, which made the package unusable for the one
    #      thing it exists to test: a TACTILE world model.
    tac = [s_ for s_ in man["context_streams"] if s_.startswith("tactile")]
    have = []
    for r in runs:
        for i in range(man["context_frames"]):
            for s_ in tac:
                have.append((ROOT / f"probes/run{r['run']}/context/ctx{i}_{s_}.jpg").is_file())
    check(len(tac) == 2 and all(have) and have,
          "the context includes both tactile streams, not only cameras",
          f"streams {man['context_streams']}; {sum(have)}/{len(have)} tactile "
          f"context images present")

    # 12 — and every context image IS the release video's frame at that row.
    #      Saved from the published videos rather than the unpublished raw tree,
    #      so this also proves the package can be rebuilt from what ships.
    rel = release_root("motherboard")
    diffs = []
    for r in runs[:2]:
        d_, e_ = r["episode"].split("/")
        for s_ in man["context_streams"]:
            cap = cv2.VideoCapture(str(rel / "videos" / d_ / e_ / f"{s_}.mp4"))
            for i, row in enumerate(r["context_rows"]):
                cap.set(cv2.CAP_PROP_POS_FRAMES, int(row))
                ok, fr = cap.read()
                got = cv2.imread(str(ROOT / f"probes/run{r['run']}/context/ctx{i}_{s_}.jpg"))
                if ok and got is not None:
                    diffs.append(float(np.abs(got.astype(int) - fr.astype(int)).mean()))
            cap.release()
    check(diffs and max(diffs) < 3.0,
          "each context image is the published video's frame at that row",
          f"{len(diffs)} images, worst mean pixel difference {max(diffs):.2f} "
          f"(JPEG q95 noise; the tactile video is row-aligned, cross-correlation "
          f"r=0.98 at lag 0)")

    # 13 — the numeric channels at those rows ship too
    d0 = np.load(ROOT / files[0][1]["file"])
    cols = [k for k in d0.files if k.startswith("context_")]
    check(len(cols) >= 8,
          "the context carries its numeric channels as well as images",
          f"{len(cols)} per-row arrays: "
          f"{', '.join(sorted(c[8:] for c in cols)[:4])}...")

    # 14 — the shipped calibration is the SAME one the poses came from.
    # The poses are copied out of the release parquet. The calibration used to
    # be copied from calib_dir(), a separate tree. When the release was rotated
    # to Z-up and that tree was not, the two silently disagreed and every
    # overlay was 153 px off with nothing raising.
    import hashlib
    rel_c = release_root("motherboard") / "calibration"
    ours = sorted((ROOT / "calibration").glob("T_*.json"))
    def _h(f):
        return hashlib.sha256(f.read_bytes()).hexdigest()[:12]
    mism = [f.name for f in ours if not (rel_c / f.name).exists()
            or _h(f) != _h(rel_c / f.name)]
    check(bool(ours) and not mism,
          "calibration is byte-identical to the release the poses come from",
          f"{len(ours)} files match {rel_c}" if not mism
          else f"DIFFER from the release: {', '.join(mism)}")

    up = {json.loads(f.read_text()).get("up_axis") for f in ours
          if f.name.startswith("T_mocap_to_cam_")}
    check(up == {"z"},
          "every camera calibration declares the Z-up convention",
          f"declared up_axis={sorted(str(u) for u in up)} "
          f"(None means a pre-conversion Y-up file)")

    # 15 — physical cross-check, independent of any file's own label: the
    # middle camera looks down at the table, so the world vertical axis must
    # point nearly AT it. A Y-up calibration paired with Z-up poses puts the
    # in-plane component at 1.00 instead of ~0.03.
    Tm = T_.load_calibration(ROOT)["cams"]["middle"]["T_mocap_to_cam"][:3, :3]
    d = Tm @ np.array([0.0, 0.0, 1.0])
    inpl = float(np.hypot(d[0], d[1]))
    check(inpl < 0.20 and d[2] < 0.0,
          "world +z points at the top-down middle camera",
          f"in-plane {inpl:.3f} (a Y-up calibration gives 1.00), "
          f"depth {d[2]:+.3f} (negative = toward the camera)")

    w = max(len(x) for _, x, _ in RESULTS)
    print()
    for ok, name, ev in RESULTS:
        print(f"  [{'ok' if ok else 'FAIL'}] {name:<{w}}  {ev}")
    nf = sum(not ok for ok, _, _ in RESULTS)
    print(f"\nprobe test set: {len(RESULTS)} checks, {nf} failing")
    return 1 if nf else 0


if __name__ == "__main__":
    raise SystemExit(main())