yxma commited on
Commit
1650142
·
verified ·
1 Parent(s): 5a41e8e

toolbox: republish the four stale scripts, and ship test_conformance.py that USAGE.md tells people to run

Browse files
scripts/build_probe_clips.py CHANGED
@@ -138,9 +138,20 @@ def main() -> int:
138
  ap.add_argument("--out", default=str(out_root("probe_clips")))
139
  args = ap.parse_args()
140
  out = Path(args.out)
 
 
 
 
 
 
 
 
 
141
  if out.exists():
142
  shutil.rmtree(out)
143
  (out / "clips").mkdir(parents=True)
 
 
144
 
145
  cal = load_calibration(SRC)
146
  require_up_axis(cal, where=f"{SRC}/calibration")
@@ -217,8 +228,36 @@ def _page(out: Path, recs, man) -> None:
217
  f"speed vs the dataset (median p{st.median(pct):.0f})"),
218
  (f"{min(seps):.3f} m", "closest the hands come (rule 0.12)"),
219
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  secs = "".join(
221
- f"<h2>{name}</h2><div class='grid'>" + "".join(
222
  f"<figure><video src='{r['clip']}' controls loop muted playsinline "
223
  f"poster='{r['clip'].replace('.mp4', '.jpg')}' preload='none'>"
224
  f"</video><figcaption>run{r['run']} &middot; "
@@ -245,6 +284,8 @@ p{color:var(--dim);max-width:78ch}a{color:var(--accent)}
245
  figure{margin:0;background:var(--card);border:1px solid var(--line);border-radius:10px;padding:8px}
246
  video{width:100%;border-radius:6px;background:#000}
247
  figcaption{color:var(--dim);font-size:12px;margin-top:6px}
 
 
248
  </style></head><body><div class="wrap">
249
  <h1>React probe clips</h1>
250
  <p>Every clip here is an animation <b>of the published test set</b> &mdash; the same
 
138
  ap.add_argument("--out", default=str(out_root("probe_clips")))
139
  args = ap.parse_args()
140
  out = Path(args.out)
141
+ # real/ is built by a different script and must survive this rebuild.
142
+ # Without this the page would show the real clips exactly once, until the
143
+ # next time anyone regenerated the synthetic ones -- and it would look
144
+ # like they had simply never been built.
145
+ import tempfile
146
+ stash = None
147
+ if (out / "real").is_dir():
148
+ stash = Path(tempfile.mkdtemp()) / "real"
149
+ shutil.move(str(out / "real"), str(stash))
150
  if out.exists():
151
  shutil.rmtree(out)
152
  (out / "clips").mkdir(parents=True)
153
+ if stash is not None:
154
+ shutil.move(str(stash), str(out / "real"))
155
 
156
  cal = load_calibration(SRC)
157
  require_up_axis(cal, where=f"{SRC}/calibration")
 
228
  f"speed vs the dataset (median p{st.median(pct):.0f})"),
229
  (f"{min(seps):.3f} m", "closest the hands come (rule 0.12)"),
230
  ]
231
+ # REAL counterparts, if they have been built. The synthetic probes show a
232
+ # commanded motion over a frozen frame; nobody performed them. Beside each
233
+ # one, the same signed axis as it actually occurs in the recordings, found
234
+ # by the criteria the probes are BUILT with (translation holds
235
+ # orientation, rotation holds the gel centre) rather than a looser
236
+ # "mostly along x".
237
+ real = {}
238
+ rj = out / "real" / "real_motion.json"
239
+ if rj.exists():
240
+ for r in json.loads(rj.read_text()):
241
+ real[r["name"]] = r
242
+
243
+ def _real_fig(name):
244
+ r = real.get(name)
245
+ if not r:
246
+ return ""
247
+ return (f"<figure class='real'><video src='{r['clip']}' controls loop "
248
+ f"muted playsinline preload='none' "
249
+ f"poster='{r['clip'].replace('.mp4', '.jpg')}'></video>"
250
+ f"<figcaption><b>real</b> &middot; {r['date']}/{r['episode']}"
251
+ f"<br>{r['amount']:.0f}"
252
+ f"{'mm' if r['unit'] == 'mm' else '&deg;'} &middot; "
253
+ f"{r['purity_kind']} {r['purity']:.2f} &middot; "
254
+ f"per-step {r['step_dominance']:.2f}<br>"
255
+ f"holds {r['counter']:.1f}"
256
+ f"{'&deg;' if r['counter_unit'] == 'deg' else 'mm'} &middot; "
257
+ f"{r['window']}f &middot; {r['side']}</figcaption></figure>")
258
+
259
  secs = "".join(
260
+ f"<h2>{name}</h2><div class='grid'>" + _real_fig(name) + "".join(
261
  f"<figure><video src='{r['clip']}' controls loop muted playsinline "
262
  f"poster='{r['clip'].replace('.mp4', '.jpg')}' preload='none'>"
263
  f"</video><figcaption>run{r['run']} &middot; "
 
284
  figure{margin:0;background:var(--card);border:1px solid var(--line);border-radius:10px;padding:8px}
285
  video{width:100%;border-radius:6px;background:#000}
286
  figcaption{color:var(--dim);font-size:12px;margin-top:6px}
287
+ figure.real{border-color:var(--accent)}
288
+ figure.real figcaption b{color:var(--accent)}
289
  </style></head><body><div class="wrap">
290
  <h1>React probe clips</h1>
291
  <p>Every clip here is an animation <b>of the published test set</b> &mdash; the same
scripts/build_splits.py CHANGED
@@ -23,12 +23,17 @@ def main() -> int:
23
  ap.add_argument("--seed", type=int, default=0)
24
  ap.add_argument("--test-len", type=int, default=TEST_INTERVAL_FRAMES)
25
  ap.add_argument("--max-train-window", type=int, default=MAX_TRAIN_WINDOW)
 
 
 
 
26
  ap.add_argument("--target", type=float, default=TARGET_TEST_FRACTION)
27
  a = ap.parse_args()
28
  root = Path(a.root)
29
  eps = [json.loads(l) for l in (root / "episodes.jsonl").read_text().splitlines() if l.strip()]
30
  bad = json.loads((root / "bad_frames.json").read_text())["episodes"]
31
  s = build_splits(eps, bad, seed=a.seed, test_len=a.test_len,
 
32
  max_train_window=a.max_train_window, target=a.target)
33
  (root / "splits.json").write_text(json.dumps(s, indent=1))
34
  st = s["stats"]
 
23
  ap.add_argument("--seed", type=int, default=0)
24
  ap.add_argument("--test-len", type=int, default=TEST_INTERVAL_FRAMES)
25
  ap.add_argument("--max-train-window", type=int, default=MAX_TRAIN_WINDOW)
26
+ ap.add_argument("--hold-out", nargs="*", default=(), metavar="DATE/EPISODE",
27
+ help="episodes held out WHOLE, e.g. a validation session. "
28
+ "Leaving them out of the file instead makes a loader "
29
+ "treat them as training data, silently.")
30
  ap.add_argument("--target", type=float, default=TARGET_TEST_FRACTION)
31
  a = ap.parse_args()
32
  root = Path(a.root)
33
  eps = [json.loads(l) for l in (root / "episodes.jsonl").read_text().splitlines() if l.strip()]
34
  bad = json.loads((root / "bad_frames.json").read_text())["episodes"]
35
  s = build_splits(eps, bad, seed=a.seed, test_len=a.test_len,
36
+ hold_out=a.hold_out,
37
  max_train_window=a.max_train_window, target=a.target)
38
  (root / "splits.json").write_text(json.dumps(s, indent=1))
39
  st = s["stats"]
scripts/check_session_ready.py CHANGED
@@ -48,10 +48,10 @@ def main() -> int:
48
  # 1 — a calibration epoch is declared for the task, and it is the right one
49
  try:
50
  from twm.calib_epoch import calib_dir, check_epoch, epoch_of
51
- d = calib_dir(a.task)
52
  try:
53
- check_epoch(a.task)
54
- note(True, "calibration epoch declared", f"{epoch_of(a.task)} at {d.name}")
55
  except ValueError as e:
56
  note(False, "calibration epoch declared", str(e)[:90])
57
  except Exception as e:
 
48
  # 1 — a calibration epoch is declared for the task, and it is the right one
49
  try:
50
  from twm.calib_epoch import calib_dir, check_epoch, epoch_of
51
+ d = calib_dir(a.task, date=a.date)
52
  try:
53
+ check_epoch(a.task, a.date)
54
+ note(True, "calibration epoch declared", f"{epoch_of(a.task, a.date)} at {d.name}")
55
  except ValueError as e:
56
  note(False, "calibration epoch declared", str(e)[:90])
57
  except Exception as e:
scripts/play_react_pt.py CHANGED
@@ -3,7 +3,7 @@ directory of segments / episodes, concatenates same-episode segments
3
  into one continuous timeline, and lets you switch between source
4
  episodes with N / P.
5
 
6
- The viewer reuses `twm.viz.build_preview_panel`'s 1280x480 grid:
7
 
8
  Row 1 (y=0..240): [left cam | middle cam | right cam | OptiTrack]
9
  Row 2 (y=240..480): [gs_L_raw | gs_L_diff | gs_R_raw | gs_R_diff | Controls]
@@ -96,7 +96,7 @@ except Exception:
96
 
97
 
98
  # ──────────────────────────────────────────────────────────────────────────────
99
- # Layout constants (matches twm.viz.build_preview_panel)
100
  # ──────────────────────────────────────────────────────────────────────────────
101
  PANEL_W, PANEL_H = 1280, 480
102
  RS_THUMB_W, RS_THUMB_H = 320, 240 # RealSense cam cell
@@ -466,7 +466,7 @@ class LoadedEpisode:
466
 
467
 
468
  # ──────────────────────────────────────────────────────────────────────────────
469
- # Panel renderer (visualize.py-style 1280x480 grid)
470
  # ──────────────────────────────────────────────────────────────────────────────
471
 
472
  def _make_ot_panel(ot_poses, t_idx, t_sec, w, h):
 
3
  into one continuous timeline, and lets you switch between source
4
  episodes with N / P.
5
 
6
+ The viewer builds its own 1280x480 grid (no status strip):
7
 
8
  Row 1 (y=0..240): [left cam | middle cam | right cam | OptiTrack]
9
  Row 2 (y=240..480): [gs_L_raw | gs_L_diff | gs_R_raw | gs_R_diff | Controls]
 
96
 
97
 
98
  # ──────────────────────────────────────────────────────────────────────────────
99
+ # Layout constants for this viewer's own panel
100
  # ──────────────────────────────────────────────────────────────────────────────
101
  PANEL_W, PANEL_H = 1280, 480
102
  RS_THUMB_W, RS_THUMB_H = 320, 240 # RealSense cam cell
 
466
 
467
 
468
  # ──────────────────────────────────────────────────────────────────────────────
469
+ # Panel renderer (this viewer's own 1280x480 grid)
470
  # ──────────────────────────────────────────────────────────────────────────────
471
 
472
  def _make_ot_panel(ot_poses, t_idx, t_sec, w, h):
scripts/test_conformance.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The conformance checker must fail on every way a user gets this wrong.
2
+
3
+ A validator that only passes is worthless. This asserts the opposite half:
4
+ feed it each classic mistake and it has to say so, by name, with a number.
5
+
6
+ The mistakes are not hypothetical. Every one of them happened in this repo:
7
+ poses in one up-axis convention with extrinsics in the other (153 px, all
8
+ self-checks green); a doc that said "quat wxyz" over scalar-last code;
9
+ millimetres handed to a function documented in metres.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
17
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
18
+
19
+ import numpy as np # noqa: E402
20
+
21
+ from react_paths import release_root # noqa: E402
22
+
23
+ RESULTS: list[tuple[bool, str, str]] = []
24
+
25
+
26
+ def check(ok: bool, name: str, evidence: str) -> None:
27
+ RESULTS.append((bool(ok), name, evidence))
28
+
29
+
30
+ def main() -> int:
31
+ try:
32
+ from react_toolbox import conformance
33
+ except Exception as ex:
34
+ check(False, "react_toolbox.conformance exists",
35
+ f"{type(ex).__name__}: {ex}")
36
+ return _report()
37
+
38
+ import json
39
+ import pyarrow.parquet as pq
40
+ from react_toolbox.frames import convert_poses
41
+
42
+ # Stage the layout a USER downloads: calibration and the declaring meta/
43
+ # in one tree. Locally they live apart (calibration in the release,
44
+ # twm.world_frame in the force export), and checking against either half
45
+ # alone would be testing a shape nobody receives.
46
+ import shutil
47
+ from react_toolbox.staging import staging_dir
48
+ from react_paths import force_meta
49
+ src = release_root("motherboard")
50
+ root = staging_dir() / "motherboard"
51
+ (root).mkdir(parents=True)
52
+ shutil.copytree(src / "calibration", root / "calibration")
53
+ shutil.copytree(force_meta("motherboard"), root / "meta")
54
+ shutil.copy(src / "episodes.jsonl", root / "episodes.jsonl")
55
+ key = json.loads(
56
+ [l for l in (root / "episodes.jsonl").read_text().splitlines()
57
+ if l.strip()][0])["episode"]
58
+ date, ep = key.split("/")
59
+ t = pq.read_table(str(root / "meta" / date / f"{ep}.parquet"),
60
+ columns=["sensor_left_pose"]).to_pydict()
61
+ P = np.asarray([x for x in t["sensor_left_pose"]], float)
62
+ P = P[np.isfinite(P).all(1) & (np.linalg.norm(P[:, 3:], axis=1) > 0.5)]
63
+
64
+ def run(poses, **kw):
65
+ return conformance.check_poses(poses, task="motherboard", date=date,
66
+ episode=ep, side="left",
67
+ release=root, **kw)
68
+
69
+ # 1 — the published poses, used correctly, must pass
70
+ r = run(P)
71
+ check(r.ok and r.n_checks >= 4,
72
+ "the published poses pass their own conformance check",
73
+ f"{r.n_checks} checks, {len(r.failures)} failing; "
74
+ f"worst fingerprint error {r.detail.get('fingerprint_px', float('nan')):.3f} px")
75
+
76
+ # 2 — millimetres instead of metres
77
+ r = run(P * np.array([1000, 1000, 1000, 1, 1, 1, 1.0]))
78
+ check(not r.ok and any("unit" in f for f in r.failures),
79
+ "positions in millimetres are rejected",
80
+ f"failures: {r.failures}")
81
+
82
+ # 3 — quaternion read as wxyz
83
+ Q = P.copy()
84
+ Q[:, 3:7] = P[:, [6, 3, 4, 5]]
85
+ r = run(Q)
86
+ check(not r.ok, "a wxyz quaternion is rejected",
87
+ f"failures: {r.failures}; fingerprint "
88
+ f"{r.detail.get('fingerprint_px', float('nan')):.1f} px")
89
+
90
+ # 4 — the OTHER up-axis convention
91
+ r = run(convert_poses(P, to_zup=False))
92
+ check(not r.ok and any("frame" in f or "up" in f for f in r.failures),
93
+ "poses in the recorded Y-up convention are rejected",
94
+ f"failures: {r.failures}; fingerprint "
95
+ f"{r.detail.get('fingerprint_px', float('nan')):.1f} px")
96
+
97
+ # 5 — unnormalised quaternions
98
+ U = P.copy(); U[:, 3:7] *= 1.4
99
+ r = run(U)
100
+ check(not r.ok and any("quaternion" in f for f in r.failures),
101
+ "unnormalised quaternions are rejected",
102
+ f"failures: {r.failures}")
103
+
104
+ # 6 — the report names what each mistake would have read, so a reader can
105
+ # see the check has teeth without running it themselves
106
+ r = run(P)
107
+ ctrl = r.detail.get("negative_controls") or {}
108
+ check(isinstance(ctrl, dict) and len(ctrl) >= 2
109
+ and all(v > 20 for v in ctrl.values()),
110
+ "a passing report still shows what each mistake would read",
111
+ f"negative controls (px): "
112
+ f"{ {k: round(v, 1) for k, v in ctrl.items()} }")
113
+
114
+ # 7 — a subset must be REFUSED, not silently reported as a frame error.
115
+ # Measured: the first 400 rows of this episode read 10.4 px against
116
+ # the episode fingerprint, which is above tolerance and looks exactly
117
+ # like a broken world frame.
118
+ r = run(P[:400])
119
+ check(not r.ok and "row-coverage" in r.failures,
120
+ "a subset of rows is refused rather than misread as a frame error",
121
+ f"failures: {r.failures}; fingerprint would have read "
122
+ f"{r.detail.get('fingerprint_px', float('nan')):.1f} px")
123
+
124
+ # 8 — but a subset the caller identifies is checked row-wise, and passes
125
+ idx = np.arange(400)
126
+ r = run(P[idx], rows=idx)
127
+ check(r.ok, "an identified subset is checked row-wise and passes",
128
+ f"worst position difference "
129
+ f"{r.detail.get('max_position_diff_m', float('nan')):.2e} m")
130
+
131
+ return _report()
132
+
133
+
134
+ def _report() -> int:
135
+ w = max(len(x) for _, x, _ in RESULTS)
136
+ print()
137
+ for ok, name, ev in RESULTS:
138
+ print(f" [{'ok' if ok else 'FAIL'}] {name:<{w}} {ev}")
139
+ n = sum(not x for x, _, _ in RESULTS)
140
+ print(f"\nconformance: {len(RESULTS)} checks, {n} failing")
141
+ return 1 if n else 0
142
+
143
+
144
+ if __name__ == "__main__":
145
+ raise SystemExit(main())