yxma commited on
Commit
52214bd
·
verified ·
1 Parent(s): 839a322

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

Browse files
Files changed (1) hide show
  1. toolbox/calib_epoch.py +94 -16
toolbox/calib_epoch.py CHANGED
@@ -41,6 +41,7 @@ dataset already publishes.
41
  from __future__ import annotations
42
 
43
  import json
 
44
  from functools import lru_cache
45
  from pathlib import Path
46
 
@@ -53,14 +54,65 @@ RELEASE = Path("/media/yxma/Disk1/twm/release")
53
  # worth naming; the directory names themselves are historical accidents.
54
  # Verified equal to the published `data/<task>/calibration/` for both tasks.
55
  CALIB_DIRS = {
56
- "motherboard": REPO / "calibration" / "result backup", # May-12 epoch
57
- "pushT": REPO / "calibration" / "result", # June-26 epoch
58
  }
59
  EXPECTED_EPOCH = {"motherboard": "2026-05-12", "pushT": "2026-06-26"}
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
- def calib_dir(task: str, *, up_axis: str | None = None) -> Path:
63
- """Directory of camera extrinsics valid for `task`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
  Looked up in this order, so the module works outside the repository it
66
  lives in:
@@ -115,6 +167,13 @@ def calib_dir(task: str, *, up_axis: str | None = None) -> Path:
115
  cand = Path(rel) / task / "calibration"
116
  if cand.is_dir():
117
  return _ok(cand)
 
 
 
 
 
 
 
118
  try:
119
  d = CALIB_DIRS[task]
120
  except KeyError:
@@ -130,6 +189,9 @@ def calib_dir(task: str, *, up_axis: str | None = None) -> Path:
130
  return _ok(d)
131
 
132
 
 
 
 
133
  def calib_dir_for_path(p: str | Path, *, up_axis: str = "y") -> Path:
134
  """Epoch dir inferred from any path containing a task-name component.
135
 
@@ -143,30 +205,42 @@ def calib_dir_for_path(p: str | Path, *, up_axis: str = "y") -> Path:
143
  failure: raises, listing the known tasks, so the caller passes explicit
144
  calibration paths instead of silently viewing through the wrong epoch.
145
  """
146
- parts = set(Path(p).parts) | set(Path(p).resolve().parts)
 
147
  hits = [t for t in CALIB_DIRS if t in parts]
148
  if len(hits) == 1:
149
- return calib_dir(hits[0], up_axis=up_axis)
 
 
 
 
 
150
  raise KeyError(
151
  f"cannot infer task from {str(p)!r} (matches: {hits or 'none'}); pass "
152
  f"explicit --cam_calib/--gel_* paths. Known tasks: {sorted(CALIB_DIRS)}")
153
 
154
 
155
- def epoch_of(task: str) -> str:
156
  """The calibration date actually on disk for `task` (from the files)."""
157
- p = calib_dir(task) / "T_mocap_to_cam_middle.json"
158
  created = json.loads(p.read_text()).get("created_at") or ""
159
  return created[:10]
160
 
161
 
162
- def check_epoch(task: str) -> None:
163
- """Fail loudly if the directory does not hold the epoch it should."""
164
- got, want = epoch_of(task), EXPECTED_EPOCH.get(task)
 
 
 
 
 
165
  if want and got != want:
 
166
  raise ValueError(
167
- f"{task}: calibration dir holds the {got} epoch, expected {want} "
168
- f"({calib_dir(task)}). Using another epoch's extrinsics puts the "
169
- f"projected sensor off the sensor.")
170
 
171
 
172
  @lru_cache(maxsize=None)
@@ -224,7 +298,7 @@ def world_offset_m(task: str, date: str, episode: str, *,
224
  stored = eps[key].get("up_axis") or "y"
225
  off = np.asarray([float(off[0]), float(off[1]), float(off[2])], float)
226
  if stored != up_axis:
227
- from react_toolbox.frames import YUP_TO_ZUP
228
  M = np.asarray(YUP_TO_ZUP, float)
229
  off = (M if up_axis == "z" else M.T) @ off
230
  return (float(off[0]), float(off[1]), float(off[2]))
@@ -234,7 +308,11 @@ def describe(task: str, date: str, episode: str) -> str:
234
  """One line for a status bar, so the applied correction is visible."""
235
  # a status line for the raw-H5 render paths, so: the Y-up convention
236
  dx, dy, dz = world_offset_m(task, date, episode, up_axis="y")
237
- s = f"calib {epoch_of(task)}"
 
 
 
 
238
  if any((dx, dy, dz)):
239
  s += f" world+({dx:g},{dy:g},{dz:g})m"
240
  return s
 
41
  from __future__ import annotations
42
 
43
  import json
44
+ import re
45
  from functools import lru_cache
46
  from pathlib import Path
47
 
 
54
  # worth naming; the directory names themselves are historical accidents.
55
  # Verified equal to the published `data/<task>/calibration/` for both tasks.
56
  CALIB_DIRS = {
57
+ "motherboard": REPO / "calibration" / "epoch_2026-05-12",
58
+ "pushT": REPO / "calibration" / "epoch_2026-06-26",
59
  }
60
  EXPECTED_EPOCH = {"motherboard": "2026-05-12", "pushT": "2026-06-26"}
61
 
62
+ # The epochs themselves, named by the date each was MEASURED.
63
+ EPOCH_DIRS = {
64
+ "2026-05-12": REPO / "calibration" / "epoch_2026-05-12",
65
+ "2026-06-26": REPO / "calibration" / "epoch_2026-06-26",
66
+ "2026-09-09": REPO / "calibration" / "epoch_2026-09-09",
67
+ }
68
+
69
+ # Which epoch each RECORDING SESSION belongs to. `task -> epoch` cannot answer
70
+ # this. The cameras were recalibrated between sessions, and a calibration is
71
+ # measured near its sessions rather than before them: the May recordings are
72
+ # covered by the May-12 measurement, pushT's 2026-06-18 by the June-26 one.
73
+ # Date order therefore does not determine the answer, so a session declares
74
+ # its epoch and nothing infers it.
75
+ #
76
+ # The 2026-09-09 motherboard session declares the epoch measured that same
77
+ # day at 07:41, by the operator's decision. Recorded on: the recorder's live
78
+ # overlay ran on the June-26 epoch during collection, and projecting each
79
+ # GelSight centre into all three views on a mid-episode frame puts June-26 on
80
+ # the sensors while 2026-09-09 sits 20-40 px away and May-12 30-60 px away.
81
+ # Both solves fit their own points equally well (0.5-0.7 px RMSE) and share an
82
+ # identical gel-to-rigid transform, so the two disagree only about where the
83
+ # cameras were. Re-check with the projection comparison if the previews ever
84
+ # look off.
85
+ CALIB_SESSIONS = {
86
+ ("motherboard", "2026-05-10"): "2026-05-12",
87
+ ("motherboard", "2026-05-11"): "2026-05-12",
88
+ ("motherboard", "2026-05-19"): "2026-05-12",
89
+ ("motherboard", "2026-09-09"): "2026-09-09",
90
+ ("pushT", "2026-06-18"): "2026-06-26",
91
+ }
92
+
93
 
94
+ def session_epoch(task: str, date: str) -> str:
95
+ """The epoch a recording session declares.
96
+
97
+ Raises for an undeclared session rather than falling back to the task
98
+ default: the fallback is exactly how a session ships through another
99
+ session's extrinsics with nobody noticing.
100
+ """
101
+ try:
102
+ return CALIB_SESSIONS[(task, date)]
103
+ except KeyError:
104
+ known = sorted(d for t, d in CALIB_SESSIONS if t == task)
105
+ raise KeyError(
106
+ f"{task}: session {date!r} does not declare a calibration epoch. "
107
+ f"Declared sessions: {known}. Add it to calib_epoch.CALIB_SESSIONS "
108
+ f"— do not fall back to another session's extrinsics.") from None
109
+
110
+
111
+
112
+ def calib_dir(task: str, *, date: str | None = None,
113
+ up_axis: str | None = None) -> Path:
114
+ """Directory of camera extrinsics valid for `task` — and for `date`,
115
+ when the caller knows which session it is reading (`CALIB_SESSIONS`).
116
 
117
  Looked up in this order, so the module works outside the repository it
118
  lives in:
 
167
  cand = Path(rel) / task / "calibration"
168
  if cand.is_dir():
169
  return _ok(cand)
170
+ if date is not None:
171
+ d = EPOCH_DIRS[session_epoch(task, date)]
172
+ if not d.is_dir():
173
+ raise FileNotFoundError(
174
+ f"calibration dir for the {session_epoch(task, date)} epoch "
175
+ f"({task}/{date}) is missing: {d}")
176
+ return _ok(d)
177
  try:
178
  d = CALIB_DIRS[task]
179
  except KeyError:
 
189
  return _ok(d)
190
 
191
 
192
+ _DATE_PART = re.compile(r"\d{4}-\d{2}-\d{2}")
193
+
194
+
195
  def calib_dir_for_path(p: str | Path, *, up_axis: str = "y") -> Path:
196
  """Epoch dir inferred from any path containing a task-name component.
197
 
 
205
  failure: raises, listing the known tasks, so the caller passes explicit
206
  calibration paths instead of silently viewing through the wrong epoch.
207
  """
208
+ all_parts = list(Path(p).parts) + list(Path(p).resolve().parts)
209
+ parts = set(all_parts)
210
  hits = [t for t in CALIB_DIRS if t in parts]
211
  if len(hits) == 1:
212
+ # A recording path carries its session date as a component
213
+ # (<task>/<YYYY-MM-DD>/episode_NNN.h5). Use it: the epoch is per
214
+ # session, and the task default is the wrong answer for any session
215
+ # recorded after the rig was recalibrated.
216
+ dates = [q for q in all_parts if _DATE_PART.fullmatch(q)]
217
+ return calib_dir(hits[0], date=dates[0] if dates else None, up_axis=up_axis)
218
  raise KeyError(
219
  f"cannot infer task from {str(p)!r} (matches: {hits or 'none'}); pass "
220
  f"explicit --cam_calib/--gel_* paths. Known tasks: {sorted(CALIB_DIRS)}")
221
 
222
 
223
+ def epoch_of(task: str, date: str | None = None) -> str:
224
  """The calibration date actually on disk for `task` (from the files)."""
225
+ p = calib_dir(task, date=date) / "T_mocap_to_cam_middle.json"
226
  created = json.loads(p.read_text()).get("created_at") or ""
227
  return created[:10]
228
 
229
 
230
+ def check_epoch(task: str, date: str | None = None) -> None:
231
+ """Fail loudly if the directory does not hold the epoch it should.
232
+
233
+ With a `date` it is the SESSION's declared epoch that must be there;
234
+ without one, the task default.
235
+ """
236
+ got = epoch_of(task, date=date)
237
+ want = session_epoch(task, date) if date is not None else EXPECTED_EPOCH.get(task)
238
  if want and got != want:
239
+ where = f"{task}/{date}" if date is not None else task
240
  raise ValueError(
241
+ f"{where}: calibration dir holds the {got} epoch, expected {want} "
242
+ f"({calib_dir(task, date=date)}). Using another epoch's extrinsics "
243
+ f"puts the projected sensor off the sensor.")
244
 
245
 
246
  @lru_cache(maxsize=None)
 
298
  stored = eps[key].get("up_axis") or "y"
299
  off = np.asarray([float(off[0]), float(off[1]), float(off[2])], float)
300
  if stored != up_axis:
301
+ from .frames import YUP_TO_ZUP
302
  M = np.asarray(YUP_TO_ZUP, float)
303
  off = (M if up_axis == "z" else M.T) @ off
304
  return (float(off[0]), float(off[1]), float(off[2]))
 
308
  """One line for a status bar, so the applied correction is visible."""
309
  # a status line for the raw-H5 render paths, so: the Y-up convention
310
  dx, dy, dz = world_offset_m(task, date, episode, up_axis="y")
311
+ # The session's epoch, not the task default: this line exists so a viewer
312
+ # can catch a wrong epoch without trusting the pipeline, and a label that
313
+ # names a different epoch than the one that drew the axes is worse than
314
+ # no label at all.
315
+ s = f"calib {epoch_of(task, date)}"
316
  if any((dx, dy, dz)):
317
  s += f" world+({dx:g},{dy:g},{dz:g})m"
318
  return s