yxma commited on
Commit
05aa77d
·
verified ·
1 Parent(s): cab11aa

toolbox: projection rendering + world-frame check; gel centre fix

Browse files
Files changed (1) hide show
  1. toolbox/conformance.py +236 -0
toolbox/conformance.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Check that YOUR poses are in the frame this release publishes.
2
+
3
+ Every other test in this project validates the dataset. This one validates
4
+ your use of it, which is the half that actually goes wrong: the data can be
5
+ perfect and still be read in millimetres, or with `w` first, or paired with
6
+ extrinsics from the wrong convention. None of those raise. They shift every
7
+ projection by tens to hundreds of pixels and leave every self-consistency
8
+ check green, because the same wrong assumption draws and re-verifies.
9
+
10
+ from react_toolbox.conformance import check_poses
11
+ r = check_poses(my_poses, task="motherboard", date="2026-05-10",
12
+ episode="episode_000", side="left", release=ROOT)
13
+ print(r)
14
+ assert r.ok
15
+
16
+ or, without writing any code:
17
+
18
+ python -m react_toolbox.conformance --release /path/to/data \\
19
+ --task motherboard --episode 2026-05-10/episode_000
20
+
21
+ A passing report also prints what each mistake WOULD have read. A validator
22
+ that only ever says "ok" teaches you nothing about whether it can say
23
+ anything else.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ from dataclasses import dataclass, field
29
+ from pathlib import Path
30
+
31
+ import numpy as np
32
+
33
+ # Distances are in pixels of a 640x480 view unless stated. The floor is set by
34
+ # the rig: camera reprojection rmse is 3.6-5.7 px and the gel centre adds
35
+ # ~3.8 px, so agreement inside ~6 px is as good as this hardware can tell.
36
+ FINGERPRINT_TOL_PX = 6.0
37
+ _M_PER_MM = 1e-3
38
+
39
+
40
+ @dataclass
41
+ class Report:
42
+ ok: bool = True
43
+ n_checks: int = 0
44
+ failures: list = field(default_factory=list)
45
+ notes: list = field(default_factory=list)
46
+ detail: dict = field(default_factory=dict)
47
+
48
+ def _add(self, ok: bool, key: str, note: str):
49
+ self.n_checks += 1
50
+ self.notes.append(("ok " if ok else "FAIL") + " " + note)
51
+ if not ok:
52
+ self.ok = False
53
+ self.failures.append(key)
54
+
55
+ def __str__(self):
56
+ head = "conformance: PASS" if self.ok else \
57
+ f"conformance: FAIL ({', '.join(self.failures)})"
58
+ return head + "\n" + "\n".join(" " + n for n in self.notes)
59
+
60
+
61
+ def _decl(release: Path, task: str, date: str, episode: str) -> dict:
62
+ """The episode's world-frame declaration, from its parquet metadata."""
63
+ import pyarrow.parquet as pq
64
+ for base in (Path(release) / "meta", Path(release) / task / "meta"):
65
+ f = base / date / f"{episode}.parquet"
66
+ if f.exists():
67
+ md = pq.read_schema(str(f)).metadata or {}
68
+ raw = md.get(b"twm.world_frame")
69
+ if raw:
70
+ return json.loads(raw.decode())
71
+ raise FileNotFoundError(
72
+ f"no world-frame declaration for {task}/{date}/{episode} under "
73
+ f"{release}. It lives in the parquet's `twm.world_frame` metadata; "
74
+ f"the force export carries it.")
75
+
76
+
77
+ def _episode_poses(release: Path, task: str, date: str, episode: str,
78
+ side: str):
79
+ import pyarrow.parquet as pq
80
+ for base in (Path(release) / "meta", Path(release) / task / "meta"):
81
+ f = base / date / f"{episode}.parquet"
82
+ if f.exists():
83
+ t = pq.read_table(str(f),
84
+ columns=[f"sensor_{side}_pose"]).to_pydict()
85
+ return np.asarray([x for x in t[f"sensor_{side}_pose"]], float)
86
+ return None
87
+
88
+
89
+ def check_poses(poses7, *, task: str, date: str, episode: str,
90
+ side: str = "left", release, tol_px: float = FINGERPRINT_TOL_PX,
91
+ rows=None) -> Report:
92
+ """Battery of checks on a user-supplied (N, 7) pose array.
93
+
94
+ Pass the episode's WHOLE pose array. The stored fingerprint is a median
95
+ over its rows, so a subset moves the median by real motion and reads as a
96
+ frame error: measured on one episode, the first 400 rows give 10.4 px and
97
+ a random 400 give 3.9, against 0.000 for all 6,890. That is a false alarm
98
+ big enough to send someone hunting a bug that is not there.
99
+
100
+ If you only have some rows, pass their indices as `rows=`; the check then
101
+ compares your poses to the release's own for those same rows, which is
102
+ stronger than the fingerprint and works on any subset.
103
+ """
104
+ from .world_frame import verify_world_frame
105
+ from .frames import convert_poses
106
+
107
+ r = Report()
108
+ P = np.asarray(poses7, float)
109
+ if P.ndim != 2 or P.shape[1] != 7:
110
+ r._add(False, "shape", f"expected (N, 7), got {P.shape}")
111
+ return r
112
+ root = Path(release)
113
+ task_root = root if (root / "calibration").is_dir() else root / task
114
+
115
+ # --- quaternion norm ------------------------------------------------
116
+ n = np.linalg.norm(P[:, 3:7], axis=1)
117
+ good = np.isfinite(n) & (n > 0.5)
118
+ worst = float(np.abs(n[good] - 1).max()) if good.any() else np.inf
119
+ r._add(worst < 1e-3, "quaternion-norm",
120
+ f"quaternion norm deviates by at most {worst:.2e} from 1 "
121
+ f"(a scaled or unnormalised quaternion silently scales the "
122
+ f"rotation)")
123
+
124
+ # --- units ----------------------------------------------------------
125
+ # The rig's working volume is a table: metres give |p| of order 1, and
126
+ # millimetres of order 1000. Nothing here is 1000 m from the origin.
127
+ med = float(np.median(np.linalg.norm(P[good, :3], axis=1)))
128
+ r._add(med < 20.0, "units",
129
+ f"median |position| = {med:.3f}; expected metres (order 1), not "
130
+ f"millimetres (order 1000)")
131
+ r.detail["median_abs_position"] = med
132
+
133
+ # --- row coverage ---------------------------------------------------
134
+ ref_all = _episode_poses(root, task, date, episode, side)
135
+ if ref_all is not None and rows is None:
136
+ valid = np.isfinite(ref_all).all(1) & (
137
+ np.linalg.norm(ref_all[:, 3:7], axis=1) > 0.5)
138
+ want = int(valid.sum())
139
+ r._add(len(P) == want, "row-coverage",
140
+ f"{len(P)} poses given, episode has {want} valid rows. The "
141
+ f"fingerprint is a MEDIAN over the episode; a subset shifts it "
142
+ f"by real motion (measured: 10.4 px from the first 400 rows, "
143
+ f"0.000 from all of them). Pass rows= to check a subset.")
144
+
145
+ # --- row-wise comparison when the caller named their rows -----------
146
+ if rows is not None and ref_all is not None:
147
+ idx = np.asarray(rows, int)
148
+ if len(idx) != len(P):
149
+ r._add(False, "rows", f"{len(idx)} indices for {len(P)} poses")
150
+ else:
151
+ d = np.abs(P[:, :3] - ref_all[idx][:, :3]).max()
152
+ r.detail["max_position_diff_m"] = float(d)
153
+ r._add(d < 1e-9, "rows-match",
154
+ f"worst position difference from the release's own rows "
155
+ f"{d:.2e} m")
156
+
157
+ # --- the frame itself, against the release's own fingerprint --------
158
+ # Skipped when the caller named their rows: the row-wise comparison above
159
+ # already settles it, and the episode-level fingerprint would fail on any
160
+ # subset for reasons that have nothing to do with the frame.
161
+ decl = _decl(root, task, date, episode)
162
+ if rows is not None and "rows-match" not in r.failures and \
163
+ "rows" not in r.failures:
164
+ r.notes.append(" fingerprint skipped: rows were named, so the "
165
+ "row-wise comparison above is the stronger check")
166
+ r.detail["negative_controls"] = {}
167
+ return r
168
+ try:
169
+ px = float(verify_world_frame(P[good], side, task_root, decl))
170
+ except Exception as ex:
171
+ r._add(False, "frame", f"could not verify the frame: "
172
+ f"{type(ex).__name__}: {ex}")
173
+ return r
174
+ r.detail["fingerprint_px"] = px
175
+ r._add(px <= tol_px, "frame",
176
+ f"worst-camera fingerprint error {px:.2f} px "
177
+ f"(tolerance {tol_px:g}; the rig's own floor is ~6)")
178
+
179
+ # --- negative controls ----------------------------------------------
180
+ # Printed on a PASS too. A reader should be able to see the check can
181
+ # fail without having to make it fail themselves.
182
+ ctrl = {}
183
+ try:
184
+ ctrl["other up-axis"] = float(
185
+ verify_world_frame(convert_poses(P[good], to_zup=False), side,
186
+ task_root, decl))
187
+ except Exception:
188
+ pass
189
+ try:
190
+ Q = P[good].copy()
191
+ Q[:, 3:7] = P[good][:, [6, 3, 4, 5]]
192
+ ctrl["quaternion as wxyz"] = float(
193
+ verify_world_frame(Q, side, task_root, decl))
194
+ except Exception:
195
+ pass
196
+ r.detail["negative_controls"] = ctrl
197
+ if ctrl:
198
+ r.notes.append(" would read: " + ", ".join(
199
+ f"{k} {v:.0f} px" for k, v in ctrl.items()))
200
+ return r
201
+
202
+
203
+ def _main(argv=None) -> int:
204
+ import argparse
205
+ import pyarrow.parquet as pq
206
+
207
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
208
+ ap.add_argument("--release", required=True,
209
+ help="the release tree (holds episodes.jsonl / meta / calibration)")
210
+ ap.add_argument("--task", default="motherboard")
211
+ ap.add_argument("--episode", required=True, help="<date>/<episode>")
212
+ ap.add_argument("--side", default="left", choices=("left", "right"))
213
+ ap.add_argument("--poses", default=None,
214
+ help=".npy of your own (N, 7) poses; omit to check the "
215
+ "release's own, which is the self-test")
216
+ a = ap.parse_args(argv)
217
+ date, ep = a.episode.split("/")
218
+ root = Path(a.release)
219
+
220
+ if a.poses:
221
+ P = np.load(a.poses)
222
+ else:
223
+ base = root / "meta" if (root / "meta").is_dir() else root / a.task / "meta"
224
+ t = pq.read_table(str(base / date / f"{ep}.parquet"),
225
+ columns=[f"sensor_{a.side}_pose"]).to_pydict()
226
+ P = np.asarray([x for x in t[f"sensor_{a.side}_pose"]], float)
227
+ P = P[np.isfinite(P).all(1) & (np.linalg.norm(P[:, 3:], axis=1) > .5)]
228
+
229
+ r = check_poses(P, task=a.task, date=date, episode=ep, side=a.side,
230
+ release=root)
231
+ print(r)
232
+ return 0 if r.ok else 1
233
+
234
+
235
+ if __name__ == "__main__":
236
+ raise SystemExit(_main())