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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""THE definition of which calibration and which world frame a recording uses.
|
| 2 |
+
|
| 3 |
+
Why this module exists
|
| 4 |
+
----------------------
|
| 5 |
+
Two facts about the rig change between recordings, and both were hard-coded to
|
| 6 |
+
a single value by every consumer:
|
| 7 |
+
|
| 8 |
+
1. **Camera extrinsics were recalibrated between tasks.** The dataset says so
|
| 9 |
+
itself (yxma/React README, "Calibration epochs"):
|
| 10 |
+
motherboard -> May-12 extrinsics
|
| 11 |
+
pushT -> June-26 extrinsics
|
| 12 |
+
The preview builder pointed at one directory, `calibration/result`, which
|
| 13 |
+
holds the **June-26** files. pushT was right by luck; every motherboard
|
| 14 |
+
preview was published with the wrong camera pose. Measured between the two
|
| 15 |
+
epochs: |dT| = 53-64 mm, dR = 2.6-6.0 deg per camera, which lands the
|
| 16 |
+
projected sensor marker 35-73 px from the sensor in a 640x480 view —
|
| 17 |
+
visibly wrong, but shaped exactly like a slightly miscalibrated rig, not
|
| 18 |
+
like a bug. The May-12 files were on disk the whole time — in a directory
|
| 19 |
+
named `result backup`, a name that reads like a discardable copy rather
|
| 20 |
+
than "the epoch the motherboard task requires".
|
| 21 |
+
|
| 22 |
+
2. **The 2026-05-19 session redefined the world origin.** Its poses are
|
| 23 |
+
offset (0.23, 0, 0.175) m from every other date. The published release has
|
| 24 |
+
that baked in; the **raw H5 does not**. Measured on episode_002:
|
| 25 |
+
median(release - rawH5) = (+0.230, +0.000, +0.175) m [2026-05-19]
|
| 26 |
+
median(release - rawH5) = (+0.000, +0.000, +0.000) m [2026-05-11]
|
| 27 |
+
Anything reading poses out of the H5 must add it, and the preview builder
|
| 28 |
+
applied 0 — so 05-19 carried BOTH errors at once, which is why it looked
|
| 29 |
+
worst and got reported first.
|
| 30 |
+
|
| 31 |
+
The failure mode is the one `tactile_align` was written for, repeated: a fact
|
| 32 |
+
about the DATA lived in the CALLERS, so every new consumer had to rediscover
|
| 33 |
+
it and one silently did not. Same remedy — one module, imported everywhere,
|
| 34 |
+
reading the dataset's own declaration rather than restating it.
|
| 35 |
+
|
| 36 |
+
The offsets are NOT restated here: `episodes.jsonl` records
|
| 37 |
+
`world_frame_offset` per episode, and that file ships with the release. This
|
| 38 |
+
module reads it. A constant typed here would be a fourth copy of a number the
|
| 39 |
+
dataset already publishes.
|
| 40 |
+
"""
|
| 41 |
+
from __future__ import annotations
|
| 42 |
+
|
| 43 |
+
import json
|
| 44 |
+
from functools import lru_cache
|
| 45 |
+
from pathlib import Path
|
| 46 |
+
|
| 47 |
+
REPO = Path(__file__).resolve().parent
|
| 48 |
+
RELEASE = Path("/media/yxma/Disk1/twm/release")
|
| 49 |
+
|
| 50 |
+
# Which on-disk directory holds each task's epoch. The mapping is the thing
|
| 51 |
+
# worth naming; the directory names themselves are historical accidents.
|
| 52 |
+
# Verified equal to the published `data/<task>/calibration/` for both tasks.
|
| 53 |
+
CALIB_DIRS = {
|
| 54 |
+
"motherboard": REPO / "calibration" / "result backup", # May-12 epoch
|
| 55 |
+
"pushT": REPO / "calibration" / "result", # June-26 epoch
|
| 56 |
+
}
|
| 57 |
+
EXPECTED_EPOCH = {"motherboard": "2026-05-12", "pushT": "2026-06-26"}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def calib_dir(task: str) -> Path:
|
| 61 |
+
"""Directory of camera extrinsics valid for `task`.
|
| 62 |
+
|
| 63 |
+
Raises on an unknown task rather than falling back to a default: a wrong
|
| 64 |
+
calibration does not look wrong, it looks like a slightly miscalibrated
|
| 65 |
+
rig, which is exactly how this shipped unnoticed.
|
| 66 |
+
"""
|
| 67 |
+
try:
|
| 68 |
+
d = CALIB_DIRS[task]
|
| 69 |
+
except KeyError:
|
| 70 |
+
raise KeyError(
|
| 71 |
+
f"no calibration epoch declared for task {task!r}; add it to "
|
| 72 |
+
f"calib_epoch.CALIB_DIRS — do not fall back to another task's "
|
| 73 |
+
f"extrinsics") from None
|
| 74 |
+
if not d.is_dir():
|
| 75 |
+
raise FileNotFoundError(f"calibration dir for {task!r} missing: {d}")
|
| 76 |
+
return d
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def calib_dir_for_path(p: str | Path) -> Path:
|
| 80 |
+
"""Epoch dir inferred from any path containing a task-name component.
|
| 81 |
+
|
| 82 |
+
For the interactive viewers, whose old default was `calibration/result`
|
| 83 |
+
for every input — June-26 extrinsics under May recordings. No guess on
|
| 84 |
+
failure: raises, listing the known tasks, so the caller passes explicit
|
| 85 |
+
calibration paths instead of silently viewing through the wrong epoch.
|
| 86 |
+
"""
|
| 87 |
+
parts = set(Path(p).parts) | set(Path(p).resolve().parts)
|
| 88 |
+
hits = [t for t in CALIB_DIRS if t in parts]
|
| 89 |
+
if len(hits) == 1:
|
| 90 |
+
return calib_dir(hits[0])
|
| 91 |
+
raise KeyError(
|
| 92 |
+
f"cannot infer task from {str(p)!r} (matches: {hits or 'none'}); pass "
|
| 93 |
+
f"explicit --cam_calib/--gel_* paths. Known tasks: {sorted(CALIB_DIRS)}")
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def epoch_of(task: str) -> str:
|
| 97 |
+
"""The calibration date actually on disk for `task` (from the files)."""
|
| 98 |
+
p = calib_dir(task) / "T_mocap_to_cam_middle.json"
|
| 99 |
+
created = json.loads(p.read_text()).get("created_at") or ""
|
| 100 |
+
return created[:10]
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def check_epoch(task: str) -> None:
|
| 104 |
+
"""Fail loudly if the directory does not hold the epoch it should."""
|
| 105 |
+
got, want = epoch_of(task), EXPECTED_EPOCH.get(task)
|
| 106 |
+
if want and got != want:
|
| 107 |
+
raise ValueError(
|
| 108 |
+
f"{task}: calibration dir holds the {got} epoch, expected {want} "
|
| 109 |
+
f"({calib_dir(task)}). Using another epoch's extrinsics puts the "
|
| 110 |
+
f"projected sensor off the sensor.")
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@lru_cache(maxsize=None)
|
| 114 |
+
def _episodes(task: str) -> dict:
|
| 115 |
+
"""`episodes.jsonl` keyed by its own `episode` field, `<date>/<episode>`."""
|
| 116 |
+
p = RELEASE / task / "episodes.jsonl"
|
| 117 |
+
if not p.exists():
|
| 118 |
+
return {}
|
| 119 |
+
return {r["episode"]: r for r in
|
| 120 |
+
(json.loads(l) for l in p.read_text().splitlines() if l.strip())}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def release_episodes(task: str) -> set[str]:
|
| 124 |
+
"""`<date>/<episode>` keys the release actually publishes.
|
| 125 |
+
|
| 126 |
+
The previews mirror the release; a preview of an episode the release does
|
| 127 |
+
not contain is not "extra material", it is a claim that the episode
|
| 128 |
+
exists. Four such clips (2026-03-23, 2026-05-15) sat on the dataset for
|
| 129 |
+
months and were reported as "not updated" — they could never be updated,
|
| 130 |
+
because there was nothing in the release to update them from.
|
| 131 |
+
"""
|
| 132 |
+
return set(_episodes(task))
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def world_offset_m(task: str, date: str, episode: str) -> tuple[float, float, float]:
|
| 136 |
+
"""Offset to ADD to raw-H5 OptiTrack poses to reach the release frame.
|
| 137 |
+
|
| 138 |
+
Read from the release's own `episodes.jsonl` (`world_frame_offset`), never
|
| 139 |
+
restated. `episode` may be `episode_002` or `2026-05-19/episode_002`.
|
| 140 |
+
|
| 141 |
+
An episode the release does not list RAISES. The first version returned
|
| 142 |
+
(0, 0, 0) on a miss and its key was wrong — `episodes.jsonl` prefixes the
|
| 143 |
+
date — so it silently reported "no shift" for the one date that has one.
|
| 144 |
+
A default that is indistinguishable from the correct answer for every
|
| 145 |
+
other recording is not a safe default; it is a silent failure.
|
| 146 |
+
"""
|
| 147 |
+
key = episode if "/" in episode else f"{date}/{episode}"
|
| 148 |
+
eps = _episodes(task)
|
| 149 |
+
if not eps:
|
| 150 |
+
return (0.0, 0.0, 0.0) # no release tree; nothing to align to
|
| 151 |
+
if key not in eps:
|
| 152 |
+
raise KeyError(
|
| 153 |
+
f"{task}: {key!r} is not in {RELEASE / task / 'episodes.jsonl'}, so "
|
| 154 |
+
f"its world-frame offset is unknown. Refusing to assume zero — "
|
| 155 |
+
f"2026-05-19 is offset (0.23, 0, 0.175) m and would render wrong.")
|
| 156 |
+
off = eps[key].get("world_frame_offset") or (0.0, 0.0, 0.0)
|
| 157 |
+
return (float(off[0]), float(off[1]), float(off[2]))
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def describe(task: str, date: str, episode: str) -> str:
|
| 161 |
+
"""One line for a status bar, so the applied correction is visible."""
|
| 162 |
+
dx, dy, dz = world_offset_m(task, date, episode)
|
| 163 |
+
s = f"calib {epoch_of(task)}"
|
| 164 |
+
if any((dx, dy, dz)):
|
| 165 |
+
s += f" world+({dx:g},{dy:g},{dz:g})m"
|
| 166 |
+
return s
|
| 167 |
+
|
| 168 |
+
# ── the world frame each session is in, as a FULL RIGID TRANSFORM ───────────
|
| 169 |
+
#
|
| 170 |
+
# WHAT THE RIG PHYSICALLY ALLOWS, which constrains this more than any fit.
|
| 171 |
+
#
|
| 172 |
+
# The OptiTrack ground plane is set with an L-bracket laid on the table, so the
|
| 173 |
+
# calibration defines +y as the normal of the SAME physical plane every time.
|
| 174 |
+
# Two calibrations of that rig can therefore differ only by
|
| 175 |
+
#
|
| 176 |
+
# yaw rotation about y (the plane normal)
|
| 177 |
+
# in-plane translation along x and z
|
| 178 |
+
#
|
| 179 |
+
# and NOT by a tilt about x or z. That is a property of the procedure, not an
|
| 180 |
+
# assumption about the data.
|
| 181 |
+
#
|
| 182 |
+
# A TILT I MEASURED, AND WHY IT WAS WRONG.
|
| 183 |
+
#
|
| 184 |
+
# Comparing the board's plane normal across sessions gave 3.38 deg for
|
| 185 |
+
# 2026-05-19, almost all of it about x — a rotation the procedure forbids. The
|
| 186 |
+
# measurement, not the constraint, was at fault: 2026-05-19's contact cloud is
|
| 187 |
+
# not planar. Split by in-plane position, its two halves give normals 6.35 deg
|
| 188 |
+
# apart, and one half agrees with the reference to 0.77 deg while the other is
|
| 189 |
+
# 6.61 deg off. Bootstrap jitter is 0.15 deg, so this is real spatial
|
| 190 |
+
# inhomogeneity — that session's contacts sample the board's relief unevenly —
|
| 191 |
+
# not sampling noise. The whole-cloud 3.38 deg was an average of two
|
| 192 |
+
# inconsistent halves. The reference sessions split to 0.56-1.52 deg, which is
|
| 193 |
+
# why the artefact showed up only here.
|
| 194 |
+
#
|
| 195 |
+
# So no tilt is applied. The reference date remains 2026-05-10; every other
|
| 196 |
+
# session declares the transform onto it, and future motherboard sessions must
|
| 197 |
+
# do the same rather than adding a fourth convention.
|
| 198 |
+
WORLD_REF_DATE = "2026-05-10"
|
| 199 |
+
|
| 200 |
+
WORLD_TRANSFORM = {
|
| 201 |
+
# date: (rotation vector in DEGREES onto the reference frame,
|
| 202 |
+
# pivot in that session's own world mm, note)
|
| 203 |
+
#
|
| 204 |
+
# Empty: the only rotation the rig can produce is yaw about y, and the yaw
|
| 205 |
+
# measured for 2026-05-19 (+2.41 deg) is not separable from the in-plane
|
| 206 |
+
# translation by the evidence available — see WORLD_RESIDUAL. A number that
|
| 207 |
+
# cannot be separated from another number is not a correction.
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
WORLD_RESIDUAL = {
|
| 211 |
+
"2026-05-19": {
|
| 212 |
+
"tilt_deg": 0.0,
|
| 213 |
+
"tilt_note": "forbidden by the L-bracket procedure; the 3.38 deg once "
|
| 214 |
+
"measured here was an artefact of a non-planar contact "
|
| 215 |
+
"cloud (in-plane halves 6.35 deg apart, vs 0.56 deg on the "
|
| 216 |
+
"reference)",
|
| 217 |
+
"yaw_deg": None, "yaw_applied": False,
|
| 218 |
+
"yaw_note": "NOT MEASURED. Matching the tracked board's projected "
|
| 219 |
+
"outline against the board segmented in a camera gave "
|
| 220 |
+
"+2.41 deg with a 95% frame-bootstrap of [0.36, 3.15], but "
|
| 221 |
+
"that interval covered only frame-to-frame noise. Varying "
|
| 222 |
+
"the camera and the hull clipping moves 2026-05-19 over "
|
| 223 |
+
"-1.84 to +3.04 deg — and moves the REFERENCE date, which "
|
| 224 |
+
"is zero by construction, over -1.83 to +3.28 deg. The "
|
| 225 |
+
"method's systematic scatter is the size of the effect, so "
|
| 226 |
+
"it has no power and the number was withdrawn.",
|
| 227 |
+
"in_plane_mm": None,
|
| 228 |
+
"status": "the (230, 0, 175) mm translation the release already applies "
|
| 229 |
+
"is the only correction; how good it is remains unmeasured",
|
| 230 |
+
},
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def world_transform(task: str, date: str):
|
| 235 |
+
"""(R, t) taking `date`'s world frame onto WORLD_REF_DATE's, in mm.
|
| 236 |
+
|
| 237 |
+
Currently the identity for every session: the only rotation the rig can
|
| 238 |
+
produce is yaw about y, and that yaw is not yet separable from the in-plane
|
| 239 |
+
translation. `world_residual` states what is known and what is not.
|
| 240 |
+
"""
|
| 241 |
+
import numpy as _np
|
| 242 |
+
from scipy.spatial.transform import Rotation as _R
|
| 243 |
+
if task != "motherboard" or date not in WORLD_TRANSFORM:
|
| 244 |
+
return _np.eye(3), _np.zeros(3)
|
| 245 |
+
rv, pivot, _ = WORLD_TRANSFORM[date]
|
| 246 |
+
R = _R.from_rotvec(_np.radians(_np.asarray(rv, float))).as_matrix()
|
| 247 |
+
c = _np.asarray(pivot, float)
|
| 248 |
+
return R, c - R @ c
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def world_residual(task: str, date: str) -> dict:
|
| 252 |
+
"""What the transform does NOT fix, so a consumer can bound their error."""
|
| 253 |
+
if task != "motherboard":
|
| 254 |
+
return {}
|
| 255 |
+
return dict(WORLD_RESIDUAL.get(date, {"tilt_deg": 0.0, "yaw_deg": 0.0,
|
| 256 |
+
"yaw_applied": False,
|
| 257 |
+
"in_plane_mm": None}))
|