yxma commited on
Commit
706821a
·
verified ·
1 Parent(s): 3bee798

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

Browse files
toolbox/__init__.py CHANGED
@@ -22,5 +22,14 @@ __all__ = [
22
  "next_state_action", "delta_pose_action", "integrate_delta",
23
  "diff_heatmap", "contact_overlay", "reference_compare", "depth_view", "height_to_pointcloud",
24
  "load_calibration", "project_gel_to_pixel",
 
 
25
  ]
26
  __version__ = "0.1.0"
 
 
 
 
 
 
 
 
22
  "next_state_action", "delta_pose_action", "integrate_delta",
23
  "diff_heatmap", "contact_overlay", "reference_compare", "depth_view", "height_to_pointcloud",
24
  "load_calibration", "project_gel_to_pixel",
25
+ "draw_projection", "force_radius_px",
26
+ "read_world_frame", "verify_world_frame", "projection_fingerprint",
27
  ]
28
  __version__ = "0.1.0"
29
+
30
+ # Projection debugging. `draw_projection` renders what `project_gel_to_pixel`
31
+ # computed, so a user can see whether it lands on the sensor; the world-frame
32
+ # helpers let them check the same thing without looking.
33
+ from .viz import draw_projection, force_radius_px # noqa: F401
34
+ from .world_frame import (projection_fingerprint, # noqa: F401
35
+ read_world_frame, verify_world_frame)
toolbox/calibration.py CHANGED
@@ -38,12 +38,46 @@ def load_calibration(task_root):
38
  for side in ("left", "right"):
39
  p = cdir / f"T_gel_to_rigid_{side}.json"
40
  if p.exists():
41
- d = json.loads(p.read_text())
42
- T = np.array(d.get("T_gel_to_rigid", d.get("T")), np.float64)
43
- out[f"gel_{side}"] = T[:3, 3] if T.shape == (4, 4) else np.array(d.get("gel_center_mm", [0, 0, 0]))
44
  return out
45
 
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  def pose7_to_matrix(pose7):
48
  """[x,y,z, qx,qy,qz,qw] (m, scalar-last) -> 4x4 (mm translation)."""
49
  p = np.asarray(pose7, np.float64)
 
38
  for side in ("left", "right"):
39
  p = cdir / f"T_gel_to_rigid_{side}.json"
40
  if p.exists():
41
+ out[f"gel_{side}"] = _gel_center(p)
 
 
42
  return out
43
 
44
 
45
+ def _gel_center(path) -> np.ndarray:
46
+ """The measured gel centre in rigid-body millimetres. RAISES if absent.
47
+
48
+ This read three keys that do not exist in any published file —
49
+ `T_gel_to_rigid`, `T`, `gel_center_mm` — and fell through to a default of
50
+ `[0, 0, 0]`. The real key is `gel_center_in_rigid_mm`, and it is present in
51
+ all four published files of both tasks.
52
+
53
+ Zero is the worst possible default here because it is a VALID-LOOKING
54
+ offset: it says "the gel centre is the rigid-body origin", so nothing
55
+ downstream can tell it from a real answer. Every projection the toolbox
56
+ produced was of the rigid body, off by the real offset — measured on
57
+ motherboard/2026-05-11/episode_003, median over the episode: 35.8 px
58
+ (left camera), 20.8 (middle), 28.0 (right), against a calibration rmse of
59
+ 4.75 mm ~ 3 px. Seven to twelve times the rig's own error, and still
60
+ shaped like a slightly miscalibrated rig rather than like a bug.
61
+
62
+ So: no fallback. A calibration file that cannot say where the gel is stops
63
+ the caller, because a projection of the wrong point is worse than none.
64
+ """
65
+ d = json.loads(Path(path).read_text())
66
+ for key in ("gel_center_in_rigid_mm", "gel_center_mm"):
67
+ if key in d:
68
+ return np.asarray(d[key], np.float64)
69
+ T = d.get("T_gel_to_rigid", d.get("T"))
70
+ if T is not None:
71
+ T = np.asarray(T, np.float64)
72
+ if T.shape == (4, 4):
73
+ return T[:3, 3]
74
+ raise KeyError(
75
+ f"{path}: no gel centre. Looked for gel_center_in_rigid_mm, "
76
+ f"gel_center_mm, T_gel_to_rigid, T. Refusing to assume [0,0,0] — "
77
+ f"that is a valid-looking offset and would silently project the "
78
+ f"rigid-body origin instead of the gel.")
79
+
80
+
81
  def pose7_to_matrix(pose7):
82
  """[x,y,z, qx,qy,qz,qw] (m, scalar-last) -> 4x4 (mm translation)."""
83
  p = np.asarray(pose7, np.float64)
toolbox/quickstart.md CHANGED
@@ -40,6 +40,22 @@ ov = T.contact_overlay(frames[100], ref)
40
  cal = T.load_calibration("data/motherboard") # after snapshot_download of calibration/
41
  uv = T.project_gel_to_pixel(meta["sensor_left_pose"][100], cal["gel_left"], cal["cams"]["middle"])
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  # 6) derive actions from handheld poses
44
  act = T.next_state_action(meta["sensor_left_pose"]) # next-frame absolute state
45
  delta = T.delta_pose_action(meta["sensor_left_pose"]) # frame-to-frame delta
 
40
  cal = T.load_calibration("data/motherboard") # after snapshot_download of calibration/
41
  uv = T.project_gel_to_pixel(meta["sensor_left_pose"][100], cal["gel_left"], cal["cams"]["middle"])
42
 
43
+ # 5b) SEE it land — a coordinate cannot tell you whether it is on the sensor,
44
+ # and every projection defect this dataset has shipped was obvious in a
45
+ # picture and invisible in a number (21-36 px, 35-73 px, 155-223 px, all
46
+ # of them shaped like a slightly miscalibrated rig).
47
+ img = T.draw_projection(cam_frame, meta["sensor_left_pose"][100],
48
+ cal["gel_left"], cal["cams"]["middle"],
49
+ force_n=meta["force_left_normal_n"][100],
50
+ target_pose7=meta["force_left_target_pose"][100])
51
+
52
+ # 5c) or check it without looking: every episode's parquet declares the world
53
+ # frame its poses are in, and carries a projection fingerprint you can
54
+ # recompute. A pose array in the wrong frame misses it by 150+ px.
55
+ dec = T.read_world_frame(episode_parquet) # {"world_frame", "raw_h5_offset_m", "fingerprint"}
56
+ err = T.verify_world_frame(meta["sensor_left_pose"], "left", "motherboard", dec)
57
+ assert err < 6.0, f"poses are not in the declared frame: {err:.1f} px off"
58
+
59
  # 6) derive actions from handheld poses
60
  act = T.next_state_action(meta["sensor_left_pose"]) # next-frame absolute state
61
  delta = T.delta_pose_action(meta["sensor_left_pose"]) # frame-to-frame delta
toolbox/viz.py CHANGED
@@ -60,3 +60,96 @@ def height_to_pointcloud(height_map, stride=4, z_scale=1.0):
60
  h = height_map[::stride, ::stride]
61
  ys, xs = np.mgrid[0:h.shape[0], 0:h.shape[1]]
62
  return np.stack([xs.ravel(), ys.ravel(), (h * z_scale).ravel()], axis=1).astype(np.float32)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  h = height_map[::stride, ::stride]
61
  ys, xs = np.mgrid[0:h.shape[0], 0:h.shape[1]]
62
  return np.stack([xs.ravel(), ys.ravel(), (h * z_scale).ravel()], axis=1).astype(np.float32)
63
+
64
+
65
+ # ── camera-view projection, for checking your own geometry ──────────────────
66
+ # Force -> disc radius. Area is linear in force: human size judgement of a
67
+ # filled disc tracks its area, so radius ∝ F would exaggerate large forces
68
+ # roughly quadratically. Same law the published preview videos use.
69
+ F_FULL_N, R_MIN_PX, R_MAX_PX = 8.0, 3.0, 22.0
70
+ TARGET_GAIN = 40.0 # drawn gap exaggeration; see draw_projection
71
+
72
+
73
+ def force_radius_px(force_n):
74
+ """THE force -> pixel-radius law, so a legend cannot drift from a disc."""
75
+ f = max(float(force_n), 0.0)
76
+ return R_MIN_PX + (R_MAX_PX - R_MIN_PX) * (min(f, F_FULL_N) / F_FULL_N) ** 0.5
77
+
78
+
79
+ def draw_projection(frame_rgb, sensor_pose7, gel_center_mm, cam_calib,
80
+ force_n=None, target_pose7=None, gain=TARGET_GAIN,
81
+ label=None):
82
+ """Draw where the sensor projects into this camera view. Returns a copy.
83
+
84
+ WHY THE TOOLBOX DRAWS AT ALL
85
+
86
+ A coordinate is a weak debugging aid for a geometry problem. Knowing that
87
+ `project_gel_to_pixel` returned (366, 188) says nothing about whether that
88
+ is ON the sensor, and every projection defect this dataset has shipped was
89
+ obvious in a picture and invisible in a number:
90
+
91
+ wrong calibration epoch 35-73 px
92
+ gel centre defaulted to the origin 21-36 px
93
+ world offset not applied 155-223 px
94
+
95
+ All three look like a slightly miscalibrated rig, which is exactly why
96
+ they survived. Render one frame and they stop looking like that.
97
+
98
+ Draws, when given: the gel centre (dot), the pressing normal (line), the
99
+ press force (translucent disc, area linear in newtons) and the DexForce
100
+ virtual target (ring joined to the dot).
101
+
102
+ ONE PROJECTION. Every element goes through `calibration.project_gel_to_pixel`
103
+ — the same call you use — so the picture cannot disagree with the number
104
+ you got from the library.
105
+
106
+ `gain` exaggerates the drawn target OFFSET only, and is printed on the
107
+ image. At true scale it is invisible: force/k is millimetres while the
108
+ view spans a metre, measured p50 0.00 px and max 1.41 px on a real
109
+ episode, against a force disc of radius up to 22 px. An unlabelled
110
+ exaggeration is a false statement about a distance.
111
+ """
112
+ import cv2
113
+
114
+ from .calibration import project_gel_to_pixel
115
+
116
+ out = np.ascontiguousarray(frame_rgb).copy()
117
+ uv = project_gel_to_pixel(sensor_pose7, gel_center_mm, cam_calib)
118
+ if uv is None: # behind the camera: draw nothing.
119
+ return out # A wrapped coordinate is not a position.
120
+ u, v = int(round(uv[0])), int(round(uv[1]))
121
+ h, w = out.shape[:2]
122
+ if not (0 <= u < w and 0 <= v < h):
123
+ return out
124
+
125
+ if force_n is not None and float(force_n) > 0.02:
126
+ r = int(round(force_radius_px(force_n)))
127
+ layer = out.copy()
128
+ cv2.circle(layer, (u, v), r, (255, 120, 60), -1, cv2.LINE_AA)
129
+ cv2.addWeighted(layer, 0.42, out, 0.58, 0, out)
130
+ cv2.circle(out, (u, v), r, (255, 120, 60), 1, cv2.LINE_AA)
131
+ cv2.putText(out, f"{float(force_n):.1f}N", (u + r + 4, v - r - 4),
132
+ cv2.FONT_HERSHEY_SIMPLEX, 0.42, (255, 120, 60), 1,
133
+ cv2.LINE_AA)
134
+
135
+ if target_pose7 is not None:
136
+ t = np.asarray(target_pose7, np.float64).copy()
137
+ o = np.asarray(sensor_pose7, np.float64)
138
+ if not np.allclose(t[:3], o[:3]): # force 0 -> target IS pose
139
+ t[:3] = o[:3] + gain * (t[:3] - o[:3]) # exaggerate in WORLD mm,
140
+ tuv = project_gel_to_pixel(t, gel_center_mm, cam_calib) # then project
141
+ if tuv is not None:
142
+ tu, tv = int(round(tuv[0])), int(round(tuv[1]))
143
+ cv2.line(out, (u, v), (tu, tv), (220, 0, 255), 1, cv2.LINE_AA)
144
+ cv2.circle(out, (tu, tv), 5, (220, 0, 255), 1, cv2.LINE_AA)
145
+ cv2.putText(out, f"target x{gain:g}", (tu + 7, tv + 4),
146
+ cv2.FONT_HERSHEY_SIMPLEX, 0.36, (220, 0, 255), 1,
147
+ cv2.LINE_AA)
148
+
149
+ cv2.circle(out, (u, v), 3, (255, 255, 255), -1, cv2.LINE_AA)
150
+ cv2.circle(out, (u, v), 5, (0, 200, 255), 1, cv2.LINE_AA)
151
+ if label:
152
+ cv2.putText(out, str(label), (u + 8, v + 4),
153
+ cv2.FONT_HERSHEY_SIMPLEX, 0.42, (0, 200, 255), 1,
154
+ cv2.LINE_AA)
155
+ return out
toolbox/world_frame.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Which world frame a pose array is in — read it, and check it.
2
+
3
+ The 2026-05-19 motherboard session redefined the OptiTrack origin: its raw
4
+ poses sit (0.23, 0, 0.175) m from every other date. The published poses have
5
+ the correction baked in, so all 32 episodes share one frame — but that fact
6
+ used to live in one free-text sentence inside `calibration.json`, which a
7
+ machine cannot read, which states a difference without a direction, and which
8
+ nothing can check.
9
+
10
+ Each episode's parquet now carries the declaration, and a FINGERPRINT: the
11
+ median pixel the gel centre projects to in each camera, computed from the
12
+ poses that ship. Recompute it from whatever poses you hold and compare.
13
+
14
+ dec = read_world_frame("episode_002.parquet")
15
+ err = verify_world_frame(my_poses, "left", "motherboard", dec)
16
+ assert err < 6.0
17
+
18
+ Measured discriminating power on 2026-05-19/episode_002:
19
+
20
+ missing world offset 222.9 px
21
+ y/z axes swapped 227.2 px
22
+ metres read as mm 1741-2782 px
23
+ 1 degree of yaw 1.7-3.2 px
24
+
25
+ against a calibration rmse of 4.75 mm — about 3 px at this depth. So it
26
+ catches every frame error this rig can plausibly suffer, including ones nobody
27
+ has thought of, which a check for one known offset cannot.
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import json
32
+
33
+ import numpy as np
34
+
35
+ VIEWS = ("left", "middle", "right")
36
+
37
+
38
+ def read_world_frame(parquet_path):
39
+ """The declaration embedded in an episode's parquet, or None."""
40
+ import pyarrow.parquet as pq
41
+ md = pq.read_schema(str(parquet_path)).metadata or {}
42
+ raw = md.get(b"twm.world_frame")
43
+ return json.loads(raw.decode()) if raw is not None else None
44
+
45
+
46
+ def projection_fingerprint(pose7, gel_center_mm, cams) -> dict:
47
+ """Median projected gel-centre pixel per camera.
48
+
49
+ Median, not mean: a handful of tracking dropouts move a mean by tens of
50
+ pixels and leave a median untouched, and a signature that drifts with the
51
+ noise cannot be compared against a stored one.
52
+ """
53
+ from .calibration import project_gel_to_pixel
54
+
55
+ p = np.asarray(pose7, float)
56
+ ok = np.isfinite(p).all(1) & (np.linalg.norm(p[:, 3:], axis=1) > 0.5)
57
+ p = p[ok]
58
+ if len(p) < 10:
59
+ raise ValueError(f"only {len(p)} valid poses — cannot fingerprint")
60
+ out = {}
61
+ for v in VIEWS:
62
+ if v not in cams:
63
+ continue
64
+ uv = [project_gel_to_pixel(q, gel_center_mm, cams[v]) for q in p]
65
+ uv = np.asarray([x for x in uv if x is not None], float)
66
+ if len(uv) < 10:
67
+ continue
68
+ out[v] = [float(np.median(uv[:, 0])), float(np.median(uv[:, 1]))]
69
+ return out
70
+
71
+
72
+ def verify_world_frame(pose7, side: str, task_root, declaration) -> float:
73
+ """Worst per-camera pixel distance from the declared fingerprint.
74
+
75
+ WORST, not mean: a frame error along one camera's optical axis is
76
+ invisible to that camera and obvious to the others, so averaging would
77
+ dilute exactly the evidence that matters.
78
+
79
+ `task_root` is the directory holding `calibration/` — the same argument
80
+ `load_calibration` takes.
81
+ """
82
+ from .calibration import load_calibration
83
+
84
+ if not declaration or "fingerprint" not in declaration:
85
+ raise ValueError("declaration has no fingerprint; this episode "
86
+ "predates the world-frame metadata")
87
+ stored = declaration["fingerprint"].get(side)
88
+ if not isinstance(stored, dict):
89
+ raise ValueError(
90
+ f"no fingerprint for side {side!r}. Pass the whole declaration; "
91
+ f"this function selects the side. (The sides and the cameras "
92
+ f"share the names left/right, so selecting by hand is easy to "
93
+ f"get wrong — an earlier version of this check did, and returned "
94
+ f"0.0 for every input as a result.)")
95
+ cal = load_calibration(task_root)
96
+ got = projection_fingerprint(pose7, cal[f"gel_{side}"], cal["cams"])
97
+ common = [v for v in VIEWS if v in got and v in stored]
98
+ if not common:
99
+ raise ValueError("no camera in common between the fingerprint and "
100
+ "this calibration")
101
+ return max(float(np.hypot(got[v][0] - stored[v][0],
102
+ got[v][1] - stored[v][1])) for v in common)