yxma commited on
Commit
b6fe757
·
verified ·
1 Parent(s): 7bd7bf0

scripts: publish what the READMEs tell you to run

Browse files
scripts/test_probe_frame_and_collision.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One sensor moves, the other stays, they never touch, and depth is visible.
2
+
3
+ Four properties the first version of the probe set did not have:
4
+
5
+ 1 THE WHOLE SENSOR FRAME IS DRAWN, not a dot. A dot shows position and
6
+ hides orientation, which makes the six ROTATION probes unreadable — they
7
+ move the marker barely at all. The React previews draw a triad for this
8
+ reason and so does this.
9
+
10
+ 2 PERSPECTIVE IS REAL. The axis tips are placed in 3D at a fixed
11
+ millimetre length and then projected, so a sensor nearer the camera draws
12
+ a larger triad. Drawing a fixed PIXEL length would assert that two
13
+ sensors at different depths are the same size, which is the one thing a
14
+ projection is supposed to tell you.
15
+
16
+ 3 ONE SENSOR MOVES PER PROBE, and which one is random. Every probe in the
17
+ first version moved the left sensor, so half the rig was never exercised
18
+ and any left-specific defect would have been invisible.
19
+
20
+ 4 THEY DO NOT COLLIDE. Each gel carries a 0.12 m-diameter exclusion circle,
21
+ so the two centres must stay at least 0.12 m apart for every step. In the
22
+ real data the centres sit 0.225 m apart at the median and closer than
23
+ 0.12 m on 1.67% of frames, so this rejects a little and forbids the
24
+ physically impossible.
25
+
26
+ python scripts/test_probe_frame_and_collision.py
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import shutil
31
+ import sys
32
+ import tempfile
33
+ from pathlib import Path
34
+
35
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
36
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
37
+
38
+ import numpy as np # noqa: E402
39
+
40
+ RESULTS: list[tuple[bool, str, str]] = []
41
+ COLLISION_M = 0.12
42
+
43
+
44
+ def check(ok: bool, name: str, evidence: str) -> None:
45
+ RESULTS.append((bool(ok), name, evidence))
46
+
47
+
48
+ def main() -> int:
49
+ import pyarrow.parquet as pq
50
+
51
+ import react_toolbox as T
52
+ from react_toolbox.synth_actions import COLLISION_DIAMETER_M, sample_probe
53
+ from twm.calib_epoch import calib_dir
54
+
55
+ stage = Path(tempfile.mkdtemp())
56
+ shutil.copytree(calib_dir("motherboard"), stage / "calibration")
57
+ cal = T.load_calibration(stage)
58
+ cam = cal["cams"]["middle"]
59
+
60
+ check(abs(COLLISION_DIAMETER_M - COLLISION_M) < 1e-9,
61
+ "the collision diameter is 0.12 m",
62
+ f"COLLISION_DIAMETER_M = {COLLISION_DIAMETER_M}")
63
+
64
+ # 1 / 2 — the frame projects with real perspective
65
+ if not hasattr(T, "project_gel_frame"):
66
+ check(False, "the whole sensor frame is projected", "no project_gel_frame")
67
+ check(False, "a nearer sensor draws a bigger triad", "not attempted")
68
+ else:
69
+ # DEPTH IS MEASURED, NOT ASSUMED. My first version displaced along
70
+ # world +z and called the result "further from the camera"; world +z
71
+ # is not the camera's view direction here, so the "far" pose came out
72
+ # NEARER and the check failed on its own premise. `project_gel_frame`
73
+ # returns the camera-frame depth, so the two poses are ordered by what
74
+ # it reports rather than by which way I guessed the axis points.
75
+ base = np.array([0.40, 0.02, 0.20, 0.0, 0.0, 0.0, 1.0])
76
+ cands = []
77
+ for k in range(3):
78
+ for sgn in (+1, -1):
79
+ q = base.copy()
80
+ q[k] += sgn * 0.35
81
+ r = T.project_gel_frame(q, cal["gel_left"], cam, axis_len_mm=60.0)
82
+ if r is not None:
83
+ cands.append((r["depth_mm"], q))
84
+ cands.sort()
85
+ near, far = cands[0][1], cands[-1][1]
86
+ depths = (cands[0][0], cands[-1][0])
87
+ spans = []
88
+ for p in (near, far):
89
+ r = T.project_gel_frame(p, cal["gel_left"], cam, axis_len_mm=60.0)
90
+ if r is None:
91
+ spans.append(None)
92
+ continue
93
+ c, tips = r["centre"], [t for t in r["tips"] if t is not None]
94
+ spans.append(max(float(np.hypot(t[0] - c[0], t[1] - c[1]))
95
+ for t in tips) if tips else 0.0)
96
+ ok = all(s is not None for s in spans)
97
+ check(ok and len(spans[0:1]) == 1,
98
+ "the whole sensor frame is projected",
99
+ f"centre + {len(tips)} axis tips")
100
+ check(ok and spans[0] > spans[1] * 1.2,
101
+ "a nearer sensor draws a bigger triad",
102
+ f"depth {depths[0]:.0f} mm -> span {spans[0]:.1f} px, "
103
+ f"depth {depths[1]:.0f} mm -> span {spans[1]:.1f} px"
104
+ if ok else "projection failed")
105
+
106
+ # 3 / 4 — one sensor moves, chosen at random, and no collision
107
+ P = ("/media/yxma/Disk1/twm/release_force/motherboard/meta/"
108
+ "2026-05-11/episode_003.parquet")
109
+ t = pq.read_table(P, columns=["sensor_left_pose", "sensor_right_pose"]).to_pydict()
110
+ poses = {s: np.asarray([x for x in t[f"sensor_{s}_pose"]], float)
111
+ for s in ("left", "right")}
112
+
113
+ moving = set()
114
+ viol = []
115
+ for seed in range(12):
116
+ try:
117
+ r = sample_probe(poses, cal, seed=seed, view="middle")
118
+ except (TypeError, ValueError) as exc:
119
+ check(False, "one sensor moves per probe, chosen at random",
120
+ f"sample_probe: {type(exc).__name__}: {str(exc)[:70]}")
121
+ check(False, "the two sensors never come within 0.12 m",
122
+ "not attempted")
123
+ _report()
124
+ return 1
125
+ moving.add(r["moving_side"])
126
+ for p in r["probes"]:
127
+ d = p.get("min_separation_m")
128
+ if d is not None and d < COLLISION_M - 1e-9:
129
+ viol.append(f"{r['moving_side']}/{p['name']}: {d:.3f} m")
130
+ check(moving == {"left", "right"},
131
+ "one sensor moves per probe, chosen at random",
132
+ f"over 12 seeds the moving side was {sorted(moving)}")
133
+ check(not viol, "the two sensors never come within 0.12 m",
134
+ f"{len(viol)} violating probe(s)" + (f"; {viol[:2]}" if viol else ""))
135
+
136
+ _report()
137
+ return 1 if sum(not ok for ok, _, _ in RESULTS) else 0
138
+
139
+
140
+ def _report() -> None:
141
+ w = max(len(x) for _, x, _ in RESULTS)
142
+ print()
143
+ for ok, name, ev in RESULTS:
144
+ print(f" [{'ok' if ok else 'FAIL'}] {name:<{w}} {ev}")
145
+ print(f"\nprobe frame + collision: {len(RESULTS)} checks, "
146
+ f"{sum(not ok for ok, _, _ in RESULTS)} failing")
147
+
148
+
149
+ if __name__ == "__main__":
150
+ raise SystemExit(main())