yxma commited on
Commit
fbde5a6
·
verified ·
1 Parent(s): d7dffc3

toolbox: publish synth_actions.py

Browse files
Files changed (1) hide show
  1. toolbox/synth_actions.py +389 -0
toolbox/synth_actions.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Synthetic probe trajectories for a world model, paced by the real data.
2
+
3
+ WHY THESE EXIST
4
+
5
+ Twelve controlled action sequences — six pure translations along +/-x, +/-y,
6
+ +/-z and six pure rotations about the same axes. There is no ground-truth
7
+ future image for any of them, so they are judged two ways: by eye, and against
8
+ the GT sensor-pose projection drawn on the start frame. A model that moves the
9
+ hand the wrong way, or the right way by the wrong amount, is visible against
10
+ that overlay in a way it never is against a scalar loss.
11
+
12
+ Axis-aligned on purpose. When a probe fails you want to be able to say WHICH
13
+ direction failed; a random direction gives you a number and no handle.
14
+
15
+ PACED BY THE DATASET, AND THE PACING IS A MEASUREMENT
16
+
17
+ "Roughly like the dataset" is not checkable, so the distribution is stated.
18
+ Over 480,008 published rows at 30 Hz, per step:
19
+
20
+ |dp| p25 0.971 p50 2.813 p90 10.158 mm
21
+ |dtheta| p25 0.320 p50 0.699 p90 2.296 deg
22
+
23
+ SPEED IS DRAWN, AND THAT IS A FIX
24
+
25
+ The first version set `n = amplitude / p50`, so the speed was not chosen at
26
+ all — it was whatever the amplitude implied. Every probe long enough to clear
27
+ the 1.5 s floor therefore ran at EXACTLY the median: of the 60 published
28
+ probes, 48 sat within 1% of 2.813 mm/step and not one was faster than p50.
29
+ The test that was supposed to cover this asserted `p25 <= v <= p90`, which a
30
+ constant passes.
31
+
32
+ Now `_pace` draws the speed uniformly in PERCENTILE over SPEED_PCT_RANGE
33
+ (p45-p85). Uniform in percentile rather than in mm/step because the
34
+ distribution spans a decade between p25 and p90, and a uniform draw in value
35
+ would put most probes in a tail the dataset barely occupies.
36
+
37
+ THE CONSTRAINT THAT DOES NOT FIT, AND WHAT GIVES
38
+
39
+ A 1.5 s horizon caps the speed at `amplitude / 45`. At the small end of the
40
+ requested amplitudes that bites: 0.1 m over 45 steps is 2.22 mm/step (p44)
41
+ and 18 degrees is 0.40 deg/step (p32). Those probes cannot be faster without
42
+ breaking the horizon, so they are the slowest in the set, and the draw is
43
+ over [p45, min(p85, feasible)].
44
+
45
+ The horizon wins over the speed band because it is the harder requirement — a
46
+ model asked to roll out only 35 steps is being asked an easier question. The
47
+ amplitude range wins too, because it was specified explicitly; sampling the
48
+ speed FIRST and letting it dictate the amplitude would have made 0.1 m
49
+ unreachable. Every trajectory records the percentile its speed actually lands
50
+ on, so "does this look like the dataset" is a number you can read rather than
51
+ a claim in a docstring.
52
+
53
+ SPEED IS UNIFORM WITHIN A TRAJECTORY
54
+
55
+ Constant velocity from start to end — not because that is realistic, it is
56
+ not, but because a failure should be attributable to direction and magnitude.
57
+ An acceleration profile shared by nothing else in the set would be a third
58
+ variable. This is unrelated to the paragraph above: the speed varies BETWEEN
59
+ probes and is constant WITHIN one.
60
+
61
+ WHICH POINT A ROTATION TURNS ABOUT
62
+
63
+ The gel centre, not the marker cluster. See `make_rotation_set` — getting
64
+ this wrong made every "pure rotation" clip translate across the screen.
65
+ """
66
+ from __future__ import annotations
67
+
68
+ import numpy as np
69
+
70
+ FPS = 30.0
71
+ MIN_HORIZON_S = 1.5
72
+ MIN_STEPS = int(np.ceil(MIN_HORIZON_S * FPS)) # 45
73
+
74
+ # Measured over the published release, 30 Hz rows, both sensors, both tasks.
75
+ # Stated here so a caller can see what "dataset-paced" was checked against;
76
+ # `scripts/test_synth_actions.py` asserts the generated speeds land inside it.
77
+ DP_PCT = {25: 0.971, 50: 2.813, 90: 10.158} # mm / step
78
+ DA_PCT = {25: 0.320, 50: 0.699, 90: 2.296} # deg / step
79
+
80
+ AXES = ((0, +1, "+x"), (0, -1, "-x"),
81
+ (1, +1, "+y"), (1, -1, "-y"),
82
+ (2, +1, "+z"), (2, -1, "-z"))
83
+
84
+ # Each gel carries an exclusion circle of this DIAMETER, so the two centres
85
+ # must stay at least this far apart at every step. Measured over 194,445
86
+ # published rows the centres sit 0.225 m apart at the median and closer than
87
+ # 0.12 m on 1.67% of frames — so this forbids the physically impossible and
88
+ # rejects a little, rather than rejecting most of the data.
89
+ COLLISION_DIAMETER_M = 0.12
90
+
91
+ # The band a probe's speed is drawn from, in percentiles of the measured
92
+ # per-step distribution. The floor is p45 rather than p25 because a probe that
93
+ # crawls tests nothing a model finds hard; the ceiling is p85 because the 1.5 s
94
+ # horizon and the 0.4 m amplitude cap between them make p86 the fastest
95
+ # trajectory this set can contain (0.40 m / 45 steps = 8.89 mm/step).
96
+ SPEED_PCT_RANGE = (45.0, 85.0)
97
+
98
+ TRANSLATION_M = (0.10, 0.40) # requested amplitude range
99
+ ROTATION_DEG = (18.0, 90.0) # pi/10 .. pi/2
100
+
101
+
102
+ def _speed_percentile(v: float, table: dict) -> float:
103
+ """Where `v` sits in the measured distribution, by log interpolation.
104
+
105
+ Log, because the distribution spans a decade between p25 and p90 and a
106
+ linear reading would call almost everything "below p50".
107
+ """
108
+ ks = sorted(table)
109
+ xs = np.log([table[k] for k in ks])
110
+ return float(np.interp(np.log(max(v, 1e-9)), xs, ks))
111
+
112
+
113
+ def _speed_at_percentile(pct: float, table: dict) -> float:
114
+ """Inverse of `_speed_percentile`: the per-step magnitude at `pct`."""
115
+ ks = sorted(table)
116
+ return float(np.exp(np.interp(pct, ks, np.log([table[k] for k in ks]))))
117
+
118
+
119
+ def _pace(rng, amplitude: float, table: dict) -> tuple[int, float, float]:
120
+ """Steps, per-step magnitude and its percentile, at a RANDOM speed.
121
+
122
+ The speed used to be `amplitude / p50`, which is not a speed choice at
123
+ all: every probe long enough to clear the 1.5 s floor came out at exactly
124
+ the median. 48 of the 60 published probes sat within 1% of 2.813 mm/step
125
+ and none was faster than p50. The `p25 <= v <= p90` test passed the whole
126
+ time, because a range check cannot see a constant.
127
+
128
+ So the speed is drawn, uniformly in PERCENTILE (not in value): the
129
+ distribution spans a decade between p25 and p90, and drawing uniformly in
130
+ mm/step would put most samples in the fast tail where the dataset has
131
+ almost no mass.
132
+
133
+ THE HORIZON CAPS THE SPEED, and that is not negotiable. Covering
134
+ `amplitude` in at least MIN_STEPS bounds v <= amplitude / MIN_STEPS: at
135
+ the smallest requested amplitude (0.1 m, 18 deg) the fastest legal probe
136
+ is 2.22 mm/step and 0.40 deg/step — the dataset's p44 and p32. So the
137
+ draw is over [lo, min(hi, feasible)], and where that interval is empty the
138
+ fastest feasible speed is used. The alternative — sampling the speed
139
+ first and letting it dictate the amplitude — would have made 0.1 m
140
+ unreachable, and the amplitude range was requested explicitly.
141
+
142
+ Returns the REALISED numbers, after the integer-step rounding, so the
143
+ recorded percentile is the one the trajectory actually has.
144
+ """
145
+ lo, hi = SPEED_PCT_RANGE
146
+ feasible = _speed_percentile(amplitude / MIN_STEPS, table)
147
+ hi = min(hi, feasible)
148
+ lo = min(lo, hi)
149
+ v = _speed_at_percentile(float(rng.uniform(lo, hi)), table)
150
+ n = int(max(MIN_STEPS, round(amplitude / v)))
151
+ step = amplitude / n
152
+ return n, step, _speed_percentile(step, table)
153
+
154
+
155
+ def make_translation_set(start_pose7, seed: int = 0,
156
+ amp_range=TRANSLATION_M) -> list[dict]:
157
+ """Six pure translations, one per signed axis. Orientation held fixed."""
158
+ rng = np.random.default_rng(seed)
159
+ p0 = np.asarray(start_pose7, float)
160
+ out = []
161
+ for axis, sign, name in AXES:
162
+ amp = float(rng.uniform(*amp_range))
163
+ n, step_mm, pct = _pace(rng, amp * 1000.0, DP_PCT)
164
+ step = step_mm / 1000.0
165
+ poses = np.repeat(p0[None, :], n + 1, axis=0)
166
+ poses[:, axis] = p0[axis] + sign * step * np.arange(n + 1)
167
+ out.append({
168
+ "name": f"trans{name}",
169
+ "kind": "translation", "axis": name,
170
+ "poses": poses, # (n+1, 7) absolute, world
171
+ "n_steps": n,
172
+ "horizon_s": n / FPS,
173
+ "amplitude_m": amp,
174
+ "per_step_mm": step_mm,
175
+ "speed_percentile": pct,
176
+ })
177
+ return out
178
+
179
+
180
+ def make_rotation_set(start_pose7, gel_center_mm, seed: int = 0,
181
+ amp_range=ROTATION_DEG) -> list[dict]:
182
+ """Six pure rotations about the signed world axes, PIVOTING ON THE GEL.
183
+
184
+ About WORLD axes, not the sensor's own: the probe is "turn the hand this
185
+ way in the room", which is what a viewer can judge from a camera image.
186
+ A body-frame rotation would be correct too but its meaning on screen
187
+ changes with the starting orientation, so a failure would not be
188
+ comparable across start frames.
189
+
190
+ WHICH POINT STAYS STILL — the bug this argument exists to prevent.
191
+
192
+ A 7-vec pose is the RIGID BODY's: the OptiTrack marker cluster. The gel
193
+ centre sits 65.7 mm away from it (`gel_center_in_rigid_mm`), and the gel
194
+ is what every picture in this project draws — the triad, the force disc,
195
+ the collision circle, the projection fingerprint. Holding the rigid
196
+ POSITION fixed and turning the quaternion therefore swings the gel
197
+ through an arc: measured 30.7 to 52.8 mm across the six probes, plainly
198
+ visible as translation in a clip labelled "pure rotation".
199
+
200
+ That was not a rendering fault — the renderer drew the gel exactly where
201
+ the poses put it. The trajectory was rotating about the wrong point.
202
+
203
+ So the gel centre is what is held fixed, and the rigid position is solved
204
+ for: `p_i = c_world - R_i @ gel_center_in_rigid`. `gel_center_mm` is
205
+ REQUIRED, not defaulted to the origin, because a caller that omits it is
206
+ not choosing "pivot on the marker" — it is unaware there is a choice.
207
+ """
208
+ from scipy.spatial.transform import Rotation
209
+
210
+ rng = np.random.default_rng(seed + 1000)
211
+ p0 = np.asarray(start_pose7, float)
212
+ q0 = Rotation.from_quat(p0[3:7])
213
+ c = np.asarray(gel_center_mm, float)
214
+ pivot = p0[:3] * 1000.0 + q0.as_matrix() @ c # gel centre, world mm
215
+ out = []
216
+ for axis, sign, name in AXES:
217
+ amp = float(rng.uniform(*amp_range))
218
+ n, step, pct = _pace(rng, amp, DA_PCT)
219
+ poses = np.repeat(p0[None, :], n + 1, axis=0)
220
+ vec = np.zeros(3)
221
+ vec[axis] = sign
222
+ for i in range(n + 1):
223
+ dq = Rotation.from_rotvec(np.radians(step * i) * vec)
224
+ qi = dq * q0 # world-frame pre-multiply
225
+ poses[i, 3:7] = qi.as_quat()
226
+ # ...and put the rigid origin wherever it must be for the GEL to
227
+ # stay on `pivot`. This is the whole fix.
228
+ poses[i, :3] = (pivot - qi.as_matrix() @ c) / 1000.0
229
+ out.append({
230
+ "name": f"rot{name}",
231
+ "kind": "rotation", "axis": name,
232
+ "poses": poses,
233
+ "n_steps": n,
234
+ "horizon_s": n / FPS,
235
+ "amplitude_deg": amp,
236
+ "pivot_world_mm": pivot,
237
+ "per_step_deg": step,
238
+ "speed_percentile": pct,
239
+ })
240
+ return out
241
+
242
+
243
+ def make_probe_sets(start_pose7, gel_center_mm, seed: int = 0) -> list[dict]:
244
+ """Both sets, twelve trajectories, in one call.
245
+
246
+ `gel_center_mm` is the moving hand's — the rotations pivot on it, see
247
+ `make_rotation_set`.
248
+ """
249
+ return make_translation_set(start_pose7, seed) + \
250
+ make_rotation_set(start_pose7, gel_center_mm, seed)
251
+
252
+
253
+ # ── sampling a start, and keeping the probe in view ─────────────────────────
254
+
255
+ def poses_in_view(poses7, gel_center_mm, cams, margin_px: float = 0.0):
256
+ """Per-step, per-camera: is the projected gel centre inside the image?
257
+
258
+ Returns (all_in_view, per_camera_fraction). The margin lets a caller
259
+ demand the marker stay clear of the border, where a viewer cannot judge
260
+ direction because half the neighbourhood is missing.
261
+ """
262
+ from .calibration import project_gel_to_pixel
263
+
264
+ frac = {}
265
+ for name, cam in cams.items():
266
+ K = cam["intrinsics"]
267
+ w, h = K.get("width", 640), K.get("height", 480)
268
+ ok = 0
269
+ for q in np.asarray(poses7, float):
270
+ uv = project_gel_to_pixel(q, gel_center_mm, cam)
271
+ if uv is None:
272
+ continue
273
+ if (margin_px <= uv[0] < w - margin_px
274
+ and margin_px <= uv[1] < h - margin_px):
275
+ ok += 1
276
+ frac[name] = ok / max(len(poses7), 1)
277
+ return (all(v == 1.0 for v in frac.values()) if frac else False), frac
278
+
279
+
280
+ def gel_centre_world(pose7, gel_center_mm):
281
+ """Gel centre in world millimetres, for one pose or many."""
282
+ from scipy.spatial.transform import Rotation
283
+
284
+ p = np.atleast_2d(np.asarray(pose7, float))
285
+ R = Rotation.from_quat(p[:, 3:7]).as_matrix()
286
+ out = p[:, :3] * 1000.0 + np.einsum("nij,j->ni", R, np.asarray(gel_center_mm, float))
287
+ return out[0] if np.ndim(pose7) == 1 else out
288
+
289
+
290
+ def min_separation_m(moving_poses, moving_gel, static_pose, static_gel):
291
+ """Closest approach between the two gel centres over a trajectory."""
292
+ a = gel_centre_world(moving_poses, moving_gel)
293
+ b = gel_centre_world(static_pose, static_gel)
294
+ return float(np.min(np.linalg.norm(a - b, axis=1)) / 1000.0)
295
+
296
+
297
+ def sample_probe(poses_by_side, cal, seed: int = 0, context: int = 4,
298
+ view: str = "middle", allow_leaving_view: bool = False,
299
+ margin_px: float = 8.0, max_tries: int = 200,
300
+ collision_m: float = COLLISION_DIAMETER_M,
301
+ moving_side: str | None = None):
302
+ """Pick a context window, a moving hand, and twelve probes for it.
303
+
304
+ ONE HAND MOVES. The other holds its pose for the whole horizon. Every
305
+ probe in the first version moved the LEFT sensor, so half the rig was
306
+ never exercised and a left-specific defect would have been invisible;
307
+ `moving_side` is drawn at random unless pinned.
308
+
309
+ THE MODEL INPUT IS SEVERAL FRAMES, so this returns `context_rows` — the
310
+ consecutive rows a TWM conditions on — not a single index.
311
+
312
+ ACTIONS AND START FRAMES ARE INDEPENDENT. The twelve trajectories come
313
+ from the moving hand's start pose alone; a frame is accepted or rejected
314
+ against them, never adjusted to fit. Nudging a trajectory to keep it on
315
+ screen would make two probes named `+x` mean different things.
316
+
317
+ TWO REJECTION RULES, both defaults:
318
+ * the projected gel must stay in view — a marker that leaves the image
319
+ asks about a configuration the training data never contains, and the
320
+ answer is unreadable rather than wrong. `allow_leaving_view=True` is
321
+ for deliberate OOD probing.
322
+ * the two gel centres must stay `collision_m` apart — hands cannot pass
323
+ through each other, and a probe that says they do is not a test of
324
+ the model, it is a test of whether it will hallucinate.
325
+
326
+ `poses_by_side` is {"left": (T,7), "right": (T,7)}; `cal` is a
327
+ `load_calibration` result, which carries both gel centres and the cameras.
328
+ """
329
+ rng = np.random.default_rng(seed)
330
+ P = {s: np.asarray(poses_by_side[s], float) for s in ("left", "right")}
331
+ n = min(len(P["left"]), len(P["right"]))
332
+ valid = np.ones(n, bool)
333
+ for s in ("left", "right"):
334
+ q = P[s][:n]
335
+ valid &= np.isfinite(q).all(1) & (np.linalg.norm(q[:, 3:], axis=1) > 0.5)
336
+ usable = np.flatnonzero(
337
+ np.convolve(valid.astype(int), np.ones(context, int), "valid") == context)
338
+ if len(usable) == 0:
339
+ raise ValueError(f"no run of {context} rows with BOTH sensors tracked")
340
+
341
+ rejected = {"view": 0, "collision": 0}
342
+ for _ in range(max_tries):
343
+ side = moving_side or ("left" if rng.random() < 0.5 else "right")
344
+ other = "right" if side == "left" else "left"
345
+ s0 = int(rng.choice(usable))
346
+ rows = np.arange(s0, s0 + context)
347
+ start = P[side][rows[-1]]
348
+ held = P[other][rows[-1]]
349
+ probes = make_probe_sets(start, cal[f"gel_{side}"],
350
+ seed=int(rng.integers(1 << 30)))
351
+
352
+ ok_all = True
353
+ for p in probes:
354
+ sep = min_separation_m(p["poses"], cal[f"gel_{side}"],
355
+ held, cal[f"gel_{other}"])
356
+ p["min_separation_m"] = sep
357
+ in_view, frac = poses_in_view(p["poses"], cal[f"gel_{side}"],
358
+ {view: cal["cams"][view]}, margin_px)
359
+ p["in_view"], p["view_fraction"] = in_view, frac
360
+ p["moving_side"], p["held_side"] = side, other
361
+ if sep < collision_m:
362
+ p["reject"] = "collision"
363
+ ok_all = False
364
+ elif not in_view and not allow_leaving_view:
365
+ p["reject"] = "leaves view"
366
+ ok_all = False
367
+ else:
368
+ p["reject"] = None
369
+ if ok_all or (allow_leaving_view
370
+ and all(p["reject"] != "collision" for p in probes)):
371
+ return {"context_rows": rows, "moving_side": side,
372
+ "held_side": other, "start_pose": start,
373
+ "held_pose": held, "probes": probes,
374
+ "in_view_enforced": not allow_leaving_view,
375
+ "collision_m": collision_m}
376
+ for p in probes:
377
+ if p["reject"] == "collision":
378
+ rejected["collision"] += 1
379
+ elif p["reject"]:
380
+ rejected["view"] += 1
381
+
382
+ raise ValueError(
383
+ f"no start frame satisfies all 12 probes after {max_tries} tries "
384
+ f"(rejections: {rejected['view']} for leaving the {view} view, "
385
+ f"{rejected['collision']} for coming within {collision_m} m of the "
386
+ f"other hand). Either shrink amp_range, or pass "
387
+ f"allow_leaving_view=True to probe out of distribution deliberately "
388
+ f"— the collision rule has no opt-out, because hands do not pass "
389
+ f"through each other.")