diffvid 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
rollout_diff/core.py ADDED
@@ -0,0 +1,879 @@
1
+ """rollout-diff core: read runs, fingerprint frames, line two runs up in time, label the differences.
2
+
3
+ A run is either a video file ("run.mp4") or one episode of a LeRobot v3 dataset folder ("folder#7").
4
+ """
5
+ import functools
6
+ import json
7
+ import math
8
+ from pathlib import Path
9
+
10
+ import cv2
11
+ import numpy as np
12
+
13
+ # Defaults measured on two datasets (see PLAN.md): path cost p99 between good runs.
14
+ ALIKE = {"global": 0.22, "residual": 0.80}
15
+ IDLE = {"global": 0.02, "residual": 0.03}
16
+ # Spatial emergent diff defaults (measured across spin + BotFails).
17
+ SPATIAL_END_THR = 0.44 # persistent outcome diff (good 0.28-0.39, failures 0.48-0.87)
18
+ SPATIAL_MID_THR = 0.52 # mid-run transient trajectory/region diff (>= 0.5 s)
19
+ SPATIAL_SETUP_THR = 0.50 # initial t=0 scene setup diff (informational context)
20
+ SPATIAL_SPOT_CELL = 0.30 # once a run has an END DIFF: cells from here can belong to a listed spot
21
+ SPATIAL_SPOT_THR = 0.35 # ... and a spot besides the hottest needs a cell this high
22
+ SPATIAL_SPOT_CELLS = 3 # ... and this many cells (1-2 cell spots on the 16x16 grid were mostly fragments)
23
+ SPATIAL_SPOT_GAP_S = 2.0 # nearby cells that became different more than this apart are separate spots
24
+ SPATIAL_CHROMA_SCALE = 60.0 # CIE Lab Delta ab divisor to match [0..1] DINOv2 cosine distance scale
25
+ SPATIAL_ROBOT_RING = 1 # cells around the robot that are not compared either (the patch tolerance leaks into them)
26
+
27
+
28
+ # ---------------------------------------------------------------- reading runs
29
+ def _resize(f, size, width):
30
+ if size:
31
+ return cv2.resize(f, (size, size), interpolation=cv2.INTER_AREA)
32
+ h, w = f.shape[:2]
33
+ return cv2.resize(f, (width, round(h * width / w)), interpolation=cv2.INTER_AREA)
34
+
35
+
36
+ def _read(cap, first, n, step, size, width, source=None):
37
+ try:
38
+ if first > 0:
39
+ cap.set(cv2.CAP_PROP_POS_FRAMES, first)
40
+ frames = []
41
+ for k in range(n):
42
+ if k % step != 0:
43
+ if not cap.grab():
44
+ break
45
+ continue
46
+ ok, f = cap.read()
47
+ if not ok:
48
+ break
49
+ frames.append(cv2.cvtColor(_resize(f, size, width), cv2.COLOR_BGR2RGB))
50
+ finally:
51
+ cap.release()
52
+ if not frames:
53
+ raise ValueError(f"Could not read any frames from video: {source or '<video>'}")
54
+ return np.stack(frames)
55
+
56
+
57
+ def episode_frames(ep, fps=10, size=224, root=None, cam="side", width=384):
58
+ """RGB frames of one episode of a local or Hugging Face Hub LeRobot dataset (v2.x or v3.0),
59
+ resampled to `fps`. size: squash to size x size; size=None keeps aspect at `width`."""
60
+ from .hub import resolve_lerobot_episode
61
+ meta = resolve_lerobot_episode(root, int(ep), cam=cam)
62
+ vpath = Path(meta["video_path"])
63
+ if not vpath.exists():
64
+ raise FileNotFoundError(f"Episode video file not found: {vpath}")
65
+ cap = cv2.VideoCapture(str(vpath))
66
+ if not cap.isOpened():
67
+ cap.release()
68
+ raise ValueError(f"Could not open video file: {vpath}")
69
+ src_fps = meta["src_fps"] or cap.get(cv2.CAP_PROP_FPS) or fps
70
+ length = meta["length"] if meta["length"] is not None else int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
71
+ return _read(cap, meta["first_frame"], length, max(1, round(src_fps / fps)), size, width, source=vpath)
72
+
73
+
74
+ def video_frames(path, fps=10, size=224, width=384):
75
+ """RGB frames of a whole video file, resampled to `fps`."""
76
+ p = Path(path)
77
+ if not p.exists():
78
+ raise FileNotFoundError(f"Video file not found: {path}")
79
+ cap = cv2.VideoCapture(str(p))
80
+ if not cap.isOpened():
81
+ cap.release()
82
+ raise ValueError(f"Could not open video file: {path}")
83
+ src_fps = cap.get(cv2.CAP_PROP_FPS) or fps
84
+ n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
85
+ return _read(cap, 0, n, max(1, round(src_fps / fps)), size, width, source=p)
86
+
87
+
88
+ def load_run(spec, fps=10, cam="side"):
89
+ """'run.mp4' or 'lerobot_folder#episode' -> frames at `fps`, aspect kept (width 384)."""
90
+ if "#" in str(spec):
91
+ root, ep = str(spec).rsplit("#", 1)
92
+ return episode_frames(int(ep), fps, size=None, root=root, cam=cam)
93
+ return video_frames(spec, fps, size=None)
94
+
95
+
96
+ # ---------------------------------------------------------------- fingerprints
97
+ @functools.lru_cache(maxsize=1)
98
+ def _dinov2():
99
+ import torch
100
+ from .world.models import quiet_model_load, select_device
101
+ dev = select_device()
102
+ with quiet_model_load():
103
+ m = torch.hub.load("facebookresearch/dinov2", "dinov2_vits14", verbose=False).to(dev).eval()
104
+ return m.half() if dev == "cuda" else m
105
+
106
+
107
+ def fingerprints(frames):
108
+ """DINOv2-small (Apache-2.0): global token (N, 384) and patch tokens (N, 256, 384), one forward pass.
109
+ Frames of any size are squashed to 224 x 224 first."""
110
+ import torch
111
+ if frames.shape[1:3] != (224, 224):
112
+ frames = np.stack([cv2.resize(f, (224, 224), interpolation=cv2.INTER_AREA) for f in frames])
113
+ model = _dinov2()
114
+ dev = next(model.parameters()).device
115
+ use_half = next(model.parameters()).dtype == torch.float16
116
+ mean = torch.tensor([0.485, 0.456, 0.406], device=dev).view(1, 3, 1, 1)
117
+ std = torch.tensor([0.229, 0.224, 0.225], device=dev).view(1, 3, 1, 1)
118
+ g, p = [], []
119
+ with torch.no_grad():
120
+ for s in range(0, len(frames), 32):
121
+ x = torch.as_tensor(frames[s:s + 32], device=dev).permute(0, 3, 1, 2).float() / 255
122
+ x = (x - mean) / std
123
+ out = model.forward_features(x.half() if use_half else x)
124
+ g.append(torch.nn.functional.normalize(out["x_norm_clstoken"].float(), dim=-1).cpu())
125
+ p.append(torch.nn.functional.normalize(out["x_norm_patchtokens"].float(), dim=-1).cpu())
126
+ return torch.cat(g).numpy(), torch.cat(p).numpy()
127
+
128
+
129
+ def residual_fp(*patch_runs):
130
+ """Fingerprints that see the robot, not the scene: patch tokens minus the static scene (median patch
131
+ token over all given runs), pooled 2x2 (16x16 -> 8x8 patches), flattened, normalised.
132
+ Needed when the scene dominates the picture (busybox top camera: global token changes only
133
+ 0.004-0.01 per frame, residual 0.11-0.19)."""
134
+ med = np.median(np.concatenate(patch_runs), 0)
135
+ out = []
136
+ for p in patch_runs:
137
+ r = (p - med).reshape(len(p), 8, 2, 8, 2, -1).mean((2, 4)).reshape(len(p), -1)
138
+ out.append(r / np.maximum(np.linalg.norm(r, axis=1, keepdims=True), 1e-8))
139
+ return out
140
+
141
+
142
+ def trim_idle(g, thr=0.02, lag=1):
143
+ """Index range [s, e) without the still frames at the start and the end.
144
+
145
+ A frame is 'moving' when its fingerprint changes more than `thr` over `lag` frames (0.1 s), OR more
146
+ than `1.5 * thr` over `5 * lag` frames (0.5 s) so slow/hesitating motion near the start or end is not
147
+ chopped off as idle.
148
+ """
149
+ moving = np.flatnonzero(1 - (g[lag:] * g[:-lag]).sum(1) > thr)
150
+ s = int(moving[0]) if len(moving) else len(g)
151
+ e = int(moving[-1]) + lag + 1 if len(moving) else 0
152
+ slow_lag = 5 * lag
153
+ if len(g) > slow_lag:
154
+ slow = np.flatnonzero(1 - (g[slow_lag:] * g[:-slow_lag]).sum(1) > 1.5 * thr)
155
+ if len(slow):
156
+ s = min(s, int(slow[0]))
157
+ e = max(e, int(slow[-1]) + slow_lag + 1)
158
+ if s >= e:
159
+ return 0, len(g)
160
+ return s, min(e, len(g))
161
+
162
+
163
+ # ---------------------------------------------------------------- alignment + labels
164
+ def dtw(D, radius=0.1, open_end=True, margin=0.15):
165
+ """Banded DTW on the cost table D (rows = A frames, cols = B frames). Returns the path [(i, j)].
166
+
167
+ Band: |j - i*(M-1)/(N-1)| <= r around the slanted diagonal, r = max(|N-M|, radius*max(N, M)),
168
+ so the end stays reachable when the lengths differ. open_end: the path may end at (i, M-1)
169
+ before A's end (B stopped early, the rest of A is then MISSING), but only when that is clearly
170
+ cheaper per step than the full end: by more than `margin` (good runs end alike, so they keep
171
+ the full end; measured on 45 good pairs).
172
+ """
173
+ N, M = D.shape
174
+ r = max(abs(N - M), radius * max(N, M))
175
+ C = np.full((N + 1, M + 1), np.inf)
176
+ C[0, 0] = 0.0
177
+ for i in range(1, N + 1):
178
+ c = (i - 1) * (M - 1) / max(N - 1, 1)
179
+ for j in range(max(1, math.ceil(c - r) + 1), min(M, math.floor(c + r) + 1) + 1):
180
+ C[i, j] = D[i - 1, j - 1] + min(C[i - 1, j], C[i, j - 1], C[i - 1, j - 1])
181
+ per_step = C[1:, M] / (np.arange(1, N + 1) + M)
182
+ i = N
183
+ if open_end and per_step.min() < (1 - margin) * per_step[-1]:
184
+ i = int(np.argmin(per_step)) + 1
185
+ j, path = M, []
186
+ while (i, j) != (0, 0):
187
+ path.append((i - 1, j - 1))
188
+ i, j = min([(i - 1, j - 1), (i - 1, j), (i, j - 1)], key=lambda t: C[t])
189
+ return path[::-1]
190
+
191
+
192
+ def label(path, D, alike):
193
+ """One A frame <-> many B frames is SLOWER (alike) or EXTRA (not alike);
194
+ many A <-> one B is FASTER or MISSING; the rest of A after an early end is MISSING.
195
+ Returns (kind, axis, first, last, extra_frames, mean_cost) with frame numbers on that axis."""
196
+ hunks = []
197
+ for axis, (same_kind, new_kind) in ((0, ("SLOWER", "EXTRA")), (1, ("FASTER", "MISSING"))):
198
+ runs = {}
199
+ for i, j in path:
200
+ runs.setdefault((i, j)[axis], []).append((i, j))
201
+ keys = sorted(k for k, v in runs.items() if len(v) > 1)
202
+ groups, cur = [], [] # neighbouring stretched frames -> one hunk
203
+ for k in keys:
204
+ if cur and k != cur[-1] + 1:
205
+ groups.append(cur)
206
+ cur = []
207
+ cur.append(k)
208
+ if cur:
209
+ groups.append(cur)
210
+ for g in groups:
211
+ pairs = [pq for k in g for pq in runs[k][1:]] # the extra pairs only
212
+ cost = float(np.mean([D[pq] for pq in pairs]))
213
+ hunks.append((same_kind if cost <= alike else new_kind, "A" if axis == 0 else "B",
214
+ g[0], g[-1], len(pairs), cost))
215
+ last_a = path[-1][0]
216
+ if last_a < D.shape[0] - 1:
217
+ hunks.append(("MISSING", "A", last_a + 1, D.shape[0] - 1, D.shape[0] - 1 - last_a, float("nan")))
218
+ return sorted(hunks, key=lambda h: h[2])
219
+
220
+
221
+ def group_hunks(hunks, path, gap=5):
222
+ """One item per place in A where time was won or lost, for the report.
223
+
224
+ Neighbouring SLOWER/EXTRA hunks (A frames at most `gap` apart) become one 'MORE TIME' item: how many
225
+ seconds B spent there, split into slower (looks alike) and extra (looks different). The split is
226
+ fragile near the threshold, the total is not. FASTER -> 'LESS TIME', MISSING inside -> 'SKIPPED',
227
+ MISSING after B's end -> 'ENDS EARLY'. Frame numbers: A/B frames on the path (trimmed runs)."""
228
+ items = []
229
+ for kind, ax, k0, k1, n, cost in hunks:
230
+ if ax == "A" and kind in ("SLOWER", "EXTRA"):
231
+ last = items[-1] if items else None
232
+ if last and last["kind"] == "MORE TIME" and k0 - last["a"][1] <= gap:
233
+ last["a"][1] = k1
234
+ last[kind.lower()] += n
235
+ continue
236
+ items.append({"kind": "MORE TIME", "a": [k0, k1], "slower": n * (kind == "SLOWER"),
237
+ "extra": n * (kind == "EXTRA")})
238
+ elif kind == "FASTER":
239
+ items.append({"kind": "LESS TIME", "b": [k0, k1], "frames": n})
240
+ elif np.isnan(cost):
241
+ items.append({"kind": "ENDS EARLY", "a": [k0, k1], "frames": n})
242
+ else:
243
+ items.append({"kind": "SKIPPED", "b": [k0, k1], "frames": n})
244
+ for it in items: # where the item is on the path and in the other run
245
+ if "a" in it:
246
+ js = [j for i, j in path if it["a"][0] <= i <= it["a"][1]]
247
+ it["b"] = [min(js), max(js)] if js and it["kind"] != "ENDS EARLY" else None
248
+ it["step"] = next(s for s, (i, _) in enumerate(path) if i >= it["a"][0]) if it["kind"] != "ENDS EARLY" else len(path) - 1
249
+ else:
250
+ iss = [i for i, j in path if it["b"][0] <= j <= it["b"][1]]
251
+ it["a"] = [min(iss), max(iss)]
252
+ it["step"] = next(s for s, (_, j) in enumerate(path) if j >= it["b"][0])
253
+ it["frames"] = it.get("frames", it.get("slower", 0) + it.get("extra", 0))
254
+ return items
255
+
256
+
257
+ # ---------------------------------------------------------------- spatial diff (where & when)
258
+ def lab_grid(frames, grid=16):
259
+ """(N, grid, grid, 2) float32 CIE Lab (a*, b*) chroma per patch; None on blank/synthetic frames."""
260
+ if frames is None or len(frames) == 0 or frames.max() == 0:
261
+ return None
262
+ out = np.empty((len(frames), grid, grid, 2), np.float32)
263
+ for k, f in enumerate(frames):
264
+ small = cv2.resize(f, (grid, grid), interpolation=cv2.INTER_AREA)
265
+ out[k] = cv2.cvtColor(small, cv2.COLOR_RGB2LAB).astype(np.float32)[..., 1:]
266
+ return out
267
+
268
+
269
+ def _tol_min_cos(X, Y, rad=1):
270
+ """Per cell of X (S, G, G, D): smallest cosine distance to Y within a (2*rad+1)^2 window."""
271
+ if rad == 0:
272
+ return 1.0 - (X * Y).sum(-1)
273
+ G = X.shape[1]
274
+ Yp = np.pad(Y, ((0, 0), (rad, rad), (rad, rad), (0, 0)), mode="edge")
275
+ best = np.full(X.shape[:3], np.inf, np.float32)
276
+ for du in range(2 * rad + 1):
277
+ for dv in range(2 * rad + 1):
278
+ best = np.minimum(best, 1.0 - (X * Yp[:, du:du + G, dv:dv + G]).sum(-1))
279
+ return best
280
+
281
+
282
+ def _tol_min_l2(X, Y, rad=1):
283
+ """Per cell of X (S, G, G, C): smallest L2 distance to Y within a (2*rad+1)^2 window."""
284
+ if rad == 0:
285
+ return np.linalg.norm(X - Y, axis=-1)
286
+ G = X.shape[1]
287
+ Yp = np.pad(Y, ((0, 0), (rad, rad), (rad, rad), (0, 0)), mode="edge")
288
+ best = np.full(X.shape[:3], np.inf, np.float32)
289
+ for du in range(2 * rad + 1):
290
+ for dv in range(2 * rad + 1):
291
+ best = np.minimum(best, np.linalg.norm(X - Yp[:, du:du + G, dv:dv + G], axis=-1))
292
+ return best
293
+
294
+
295
+ def _medfilt1d(x, k=3):
296
+ if k <= 1 or len(x) < 3:
297
+ return x.copy()
298
+ pad = k // 2
299
+ xp = np.pad(x, (pad, pad), mode="edge")
300
+ return np.median(np.lib.stride_tricks.sliding_window_view(xp, k), axis=-1)
301
+
302
+
303
+ def _hot_region(grid_map, rel=0.60, floor=0.30):
304
+ """Connected component around the peak cell -> normalized [x0, y0, x1, y1] box and boolean mask."""
305
+ G = grid_map.shape[0]
306
+ peak = float(grid_map.max())
307
+ r, c = np.unravel_index(int(np.argmax(grid_map)), grid_map.shape)
308
+ thr = max(floor, rel * peak)
309
+ mask = (grid_map >= thr).astype(np.uint8)
310
+ _, labels = cv2.connectedComponents(mask, connectivity=8)
311
+ comp = labels == labels[r, c]
312
+ if not comp.any():
313
+ comp = np.zeros_like(grid_map, dtype=bool)
314
+ comp[r, c] = True
315
+ ys, xs = np.nonzero(comp)
316
+ box = [round(float(xs.min()) / G, 4), round(float(ys.min()) / G, 4),
317
+ round(float(xs.max() + 1) / G, 4), round(float(ys.max() + 1) / G, 4)]
318
+ return box, comp
319
+
320
+
321
+ def _combined_patch_diff(Xa, Xb, La=None, Lb=None, rad=1, chroma_scale=SPATIAL_CHROMA_SCALE):
322
+ dp = np.maximum(_tol_min_cos(Xa, Xb, rad), _tol_min_cos(Xb, Xa, rad))
323
+ if La is not None and Lb is not None:
324
+ dc = np.maximum(_tol_min_l2(La, Lb, rad), _tol_min_l2(Lb, La, rad)) / chroma_scale
325
+ return np.maximum(dp, np.minimum(dc, 1.5))
326
+ return dp
327
+
328
+
329
+ def robot_cover(mask_fn, frames, grid=16, chunk=32):
330
+ """(N, grid, grid) share of each patch the robot covers, per frame, from a robot cut-out model
331
+ `mask_fn(frames, idx, run_motion) -> (K, H, W) bool` (the same hook as world_diff's mask_model)."""
332
+ from .world.plates import _frame_motion_envelope
333
+ mot = _frame_motion_envelope(frames)
334
+ out = []
335
+ for s in range(0, len(frames), chunk):
336
+ for m in mask_fn(frames, np.arange(s, min(s + chunk, len(frames))), mot):
337
+ out.append(cv2.resize(m.astype(np.float32), (grid, grid), interpolation=cv2.INTER_AREA))
338
+ return np.stack(out)
339
+
340
+
341
+ def _robot_cells(cover, thr=0.1):
342
+ """(S, G, G) robot cover -> cells not to compare: touched by the robot, plus a SPATIAL_ROBOT_RING-cell ring (the
343
+ 3x3 patch tolerance lets a neighbouring arm cell leak in)."""
344
+ k = np.ones((2 * SPATIAL_ROBOT_RING + 1,) * 2, np.uint8)
345
+ return np.stack([cv2.dilate((c > thr).astype(np.uint8), k) > 0 for c in cover])
346
+
347
+
348
+ def _end_spots(end_map, M_seen, tb, fps, end_thr):
349
+ """Separate end spots of a run that differs at the end, hottest first, plus each cell's onset step (when it
350
+ became different for good: last step its smoothed value was below half its end value). Cells >= SPATIAL_SPOT_CELL
351
+ join a spot through cells up to 2 apart (bridges one-cell gaps) whose onsets (in B time `tb`) are
352
+ <= SPATIAL_SPOT_GAP_S apart. The hottest spot is always kept; others need SPATIAL_SPOT_CELLS cells and a cell
353
+ >= SPATIAL_SPOT_THR. Tuned on BotFails dish runs (the 3 misplaced plates of anomaly 5 -> 3 spots)."""
354
+ S, (H, W) = len(M_seen), end_map.shape
355
+ k = min(5, S if S % 2 == 1 else max(1, S - 1))
356
+ cells = end_map >= SPATIAL_SPOT_CELL
357
+ onset = np.zeros(end_map.shape, int)
358
+ for y, x in zip(*np.nonzero(cells)):
359
+ below = np.flatnonzero(_medfilt1d(M_seen[:, y, x], k=k) < 0.5 * end_map[y, x])
360
+ onset[y, x] = min(int(below[-1] + 1) if len(below) else 0, S - 1)
361
+ gap = SPATIAL_SPOT_GAP_S * fps
362
+ lab, n = np.zeros(end_map.shape, int), 0
363
+ for y, x in zip(*np.nonzero(cells)): # flood fill: neighbours that changed at about the same time
364
+ if lab[y, x]:
365
+ continue
366
+ n += 1
367
+ lab[y, x], todo = n, [(y, x)]
368
+ while todo:
369
+ cy, cx = todo.pop()
370
+ for ny in range(max(0, cy - 2), min(H, cy + 3)):
371
+ for nx in range(max(0, cx - 2), min(W, cx + 3)):
372
+ if cells[ny, nx] and not lab[ny, nx] and abs(int(tb[onset[ny, nx]]) - int(tb[onset[cy, cx]])) <= gap:
373
+ lab[ny, nx] = n
374
+ todo.append((ny, nx))
375
+ parts = sorted((lab == i for i in range(1, n + 1)), key=lambda p: -float(end_map[p].max()))
376
+ return parts[:1] + [p for p in parts[1:] if int(p.sum()) >= SPATIAL_SPOT_CELLS
377
+ and float(end_map[p].max()) >= SPATIAL_SPOT_THR], onset
378
+
379
+
380
+ def spatial_diff(pa, pb, path, trim_a, trim_b, fps, la=None, lb=None,
381
+ end_thr=SPATIAL_END_THR, mid_thr=SPATIAL_MID_THR, setup_thr=SPATIAL_SETUP_THR, rad=1,
382
+ ra=None, rb=None):
383
+ """Locate WHERE (16x16 grid) and WHEN along the DTW path B diverges visually from A.
384
+
385
+ Uses baseline-subtracted emergent diff: M_new(s) = max(0, M(s) - M_init), where M(s) combines
386
+ bidirectional 3x3-tolerant DINOv2 patch cosine distance and CIE Lab chroma distance. Emits up to
387
+ three objective spatial categories:
388
+ - SETUP DIFF (info): regions that already differed at t=0 before motion began
389
+ - MID-RUN DIFF: localized region/trajectory divergence lasting >= 0.5 s mid-run
390
+ - END DIFF: persistent divergence that stays different until the end of the run
391
+ `ra`, `rb` (from `robot_cover`): cells the robot covers in A's or B's frame are not compared, so an arm in
392
+ another pose is not a difference.
393
+ """
394
+ G = int(round(pa.shape[1] ** 0.5))
395
+ pa_g = pa.reshape(len(pa), G, G, -1).astype(np.float32)
396
+ pb_g = pb.reshape(len(pb), G, G, -1).astype(np.float32)
397
+ sa, sb = trim_a[0], trim_b[0]
398
+ ia = np.array([i + sa for i, _ in path], dtype=int)
399
+ jb = np.array([j + sb for _, j in path], dtype=int)
400
+
401
+ # Baseline initial setup diff from the first few frames of A and B
402
+ k0 = min(3, len(pa_g), len(pb_g))
403
+ La0 = la[:k0] if la is not None else None
404
+ Lb0 = lb[:k0] if lb is not None else None
405
+ M0 = np.median(_combined_patch_diff(pa_g[:k0], pb_g[:k0], La0, Lb0, rad=rad), axis=0, keepdims=True)
406
+
407
+ La = la[ia] if la is not None else None
408
+ Lb = lb[jb] if lb is not None else None
409
+ M = _combined_patch_diff(pa_g[ia], pb_g[jb], La, Lb, rad=rad)
410
+ M_new = np.clip(M - M0, 0.0, None)
411
+ M_seen = M_new # for END DIFF timing: a cell hidden by the arm keeps its last seen value
412
+ if ra is not None and rb is not None:
413
+ skip = _robot_cells(np.maximum(ra[ia], rb[jb]))
414
+ M_new[skip] = 0.0
415
+ M0 = M0 * ~_robot_cells(np.maximum(ra[:k0], rb[:k0]).max(0, keepdims=True))
416
+ last = np.where(skip, 0, np.arange(len(skip))[:, None, None])
417
+ np.maximum.accumulate(last, axis=0, out=last)
418
+ M_seen = np.take_along_axis(M_new, last, axis=0)
419
+
420
+ S = len(path)
421
+ flat = M_new.reshape(S, -1)
422
+ k_top = min(4, flat.shape[1])
423
+ curve = np.sort(flat, axis=1)[:, -k_top:].mean(1).astype(np.float32)
424
+ heat = np.clip(M_new * 255.0, 0, 255).astype(np.uint8)
425
+
426
+ items = []
427
+
428
+ # 1. SETUP DIFF (informational): regions already different at t=0
429
+ setup_map = M0[0]
430
+ setup_score = float(np.sort(setup_map.ravel())[-k_top:].mean())
431
+ if setup_score >= setup_thr:
432
+ sbox, _ = _hot_region(setup_map, rel=0.60, floor=0.35)
433
+ items.append(dict(
434
+ kind="SETUP DIFF",
435
+ a=[0, 0],
436
+ b=[0, 0],
437
+ step=0,
438
+ end_step=0,
439
+ peak_step=0,
440
+ score=round(setup_score, 3),
441
+ thr=round(float(setup_thr), 3),
442
+ box=sbox,
443
+ frames=0,
444
+ info=True,
445
+ ))
446
+
447
+ # 2. END DIFF: persistent outcome difference over the last 0.5 s of the aligned path
448
+ tail = max(1, min(S, max(2, fps // 2)))
449
+ end_map = np.median(M_new[-tail:], axis=0)
450
+ # If DTW open_end stopped A early (B ended early), also compare A's true final frames against B's true final frames
451
+ len_a_tr = trim_a[1] - trim_a[0]
452
+ if len(path) and path[-1][0] < len_a_tr - tail and len(pa_g) >= tail and len(pb_g) >= tail:
453
+ la_e = la[-tail:] if la is not None else None
454
+ lb_e = lb[-tail:] if lb is not None else None
455
+ M_te = np.clip(_combined_patch_diff(pa_g[-tail:], pb_g[-tail:], la_e, lb_e, rad=rad) - M0, 0.0, None)
456
+ if ra is not None and rb is not None:
457
+ M_te[_robot_cells(np.maximum(ra[-tail:], rb[-tail:]))] = 0.0
458
+ end_map = np.maximum(end_map, np.median(M_te, axis=0))
459
+ end_score = float(np.sort(end_map.ravel())[-k_top:].mean())
460
+ end_s0 = S
461
+ if end_score >= end_thr:
462
+ # Whether the run differs at the end is decided above and stays strict. Once it does, every spot that differs
463
+ # is listed (from a lower bar), each with its own box and start time. Touching spots are split by WHEN each
464
+ # cell became different for good: plates put down one after another touch, but change seconds apart.
465
+ parts, onset = _end_spots(end_map, M_seen, jb, fps, end_thr)
466
+ # Merge secondary spots whose bounding boxes substantially overlap an earlier hotter spot (avoids splitting
467
+ # one continuous spill+wipe into 4 overlapping fragments while preserving touching side-by-side objects).
468
+ def _b_iou(b1, b2):
469
+ ix0, iy0 = max(b1[0], b2[0]), max(b1[1], b2[1])
470
+ ix1, iy1 = min(b1[2], b2[2]), min(b1[3], b2[3])
471
+ inter = max(0.0, ix1 - ix0) * max(0.0, iy1 - iy0)
472
+ if inter <= 0.0:
473
+ return 0.0
474
+ a1 = (b1[2] - b1[0]) * (b1[3] - b1[1])
475
+ a2 = (b2[2] - b2[0]) * (b2[3] - b2[1])
476
+ return inter / max(a1 + a2 - inter, 1e-6)
477
+ merged_parts = []
478
+ for part in parts:
479
+ ys, xs = np.nonzero(part)
480
+ b = [float(xs.min()) / G, float(ys.min()) / G, float(xs.max() + 1) / G, float(ys.max() + 1) / G]
481
+ hit_k = next((k for k, (_, kb) in enumerate(merged_parts) if _b_iou(b, kb) >= 0.18), None)
482
+ if hit_k is not None:
483
+ mp = merged_parts[hit_k][0] | part
484
+ mys, mxs = np.nonzero(mp)
485
+ mb = [float(mxs.min()) / G, float(mys.min()) / G, float(mxs.max() + 1) / G, float(mys.max() + 1) / G]
486
+ merged_parts[hit_k] = (mp, mb)
487
+ else:
488
+ merged_parts.append((part, b))
489
+ parts = [p for p, _ in merged_parts]
490
+ for n_part, part in enumerate(parts):
491
+ ys, xs = np.nonzero(part)
492
+ box = [round(float(xs.min()) / G, 4), round(float(ys.min()) / G, 4),
493
+ round(float(xs.max() + 1) / G, 4), round(float(ys.max() + 1) / G, 4)]
494
+ s0 = int(np.median(onset[part]))
495
+ if float(end_map[part].max()) >= end_thr: # weaker spots don't shorten the MID-RUN search
496
+ end_s0 = min(end_s0, s0)
497
+ items.append(dict(
498
+ kind="END DIFF",
499
+ a=[int(ia[s0] - sa), int(ia[-1] - sa)],
500
+ b=[int(jb[s0] - sb), int(jb[-1] - sb)],
501
+ step=s0,
502
+ end_step=S - 1,
503
+ peak_step=S - 1,
504
+ score=round(end_score if n_part == 0 else float(np.sort(end_map[part])[-k_top:].mean()), 3),
505
+ thr=round(float(end_thr), 3),
506
+ box=box,
507
+ frames=int(S - s0),
508
+ ))
509
+
510
+ # 3. MID-RUN DIFF: transient trajectory/arm/object divergences lasting >= 0.5 s before end_s0
511
+ if end_s0 > 2:
512
+ c_sm = _medfilt1d(curve[:end_s0], k=min(3, end_s0 if end_s0 % 2 == 1 else max(1, end_s0 - 1)))
513
+ hot = np.flatnonzero(c_sm >= mid_thr)
514
+ min_len = max(3, round(0.5 * fps))
515
+ gap_merge = max(2, fps // 3)
516
+ spans = []
517
+ for idx in hot:
518
+ idx = int(idx)
519
+ if spans and idx - spans[-1][1] <= gap_merge:
520
+ spans[-1][1] = idx
521
+ else:
522
+ spans.append([idx, idx])
523
+ mid_items = []
524
+ for s0, s1 in spans:
525
+ if s1 - s0 + 1 < min_len:
526
+ continue
527
+ peak_s = int(s0 + np.argmax(curve[s0:s1 + 1]))
528
+ span_map = np.median(M_new[s0:s1 + 1], axis=0)
529
+ use_map = span_map if span_map.max() >= 0.30 else M_new[peak_s]
530
+ mbox, mcomp = _hot_region(use_map, rel=0.60, floor=0.30)
531
+ # When robot-masked, drop 1-2 cell edge/cable specks (requires >= SPATIAL_SPOT_CELLS unless very strong)
532
+ if ra is not None and rb is not None and int(mcomp.sum()) < SPATIAL_SPOT_CELLS and float(curve[peak_s]) < 0.80:
533
+ continue
534
+ cand = dict(
535
+ kind="MID-RUN DIFF",
536
+ a=[int(ia[s0] - sa), int(ia[s1] - sa)],
537
+ b=[int(jb[s0] - sb), int(jb[s1] - sb)],
538
+ step=s0,
539
+ end_step=s1,
540
+ peak_step=peak_s,
541
+ score=round(float(curve[peak_s]), 3),
542
+ thr=round(float(mid_thr), 3),
543
+ box=mbox,
544
+ frames=int(s1 - s0 + 1),
545
+ )
546
+ # Merge repeated mid-run flickers at the same spatial spot within <= 3.0 s
547
+ if mid_items:
548
+ prev = mid_items[-1]
549
+ pbox = prev["box"]
550
+ ix0, iy0 = max(mbox[0], pbox[0]), max(mbox[1], pbox[1])
551
+ ix1, iy1 = min(mbox[2], pbox[2]), min(mbox[3], pbox[3])
552
+ inter = max(0.0, ix1 - ix0) * max(0.0, iy1 - iy0)
553
+ a1 = (mbox[2] - mbox[0]) * (mbox[3] - mbox[1])
554
+ a2 = (pbox[2] - pbox[0]) * (pbox[3] - pbox[1])
555
+ iou = inter / max(a1 + a2 - inter, 1e-6)
556
+ if (s0 - prev["end_step"]) <= 3 * fps and iou >= 0.25:
557
+ prev["a"][1] = max(prev["a"][1], cand["a"][1])
558
+ prev["b"][1] = max(prev["b"][1], cand["b"][1])
559
+ prev["end_step"] = max(prev["end_step"], cand["end_step"])
560
+ prev["frames"] = int(prev["end_step"] - prev["step"] + 1)
561
+ prev["box"] = [round(min(pbox[0], mbox[0]), 4), round(min(pbox[1], mbox[1]), 4),
562
+ round(max(pbox[2], mbox[2]), 4), round(max(pbox[3], mbox[3]), 4)]
563
+ if cand["score"] > prev["score"]:
564
+ prev["score"] = cand["score"]
565
+ prev["peak_step"] = cand["peak_step"]
566
+ continue
567
+ mid_items.append(cand)
568
+ items.extend(mid_items)
569
+
570
+ # Order execution diffs chronologically (keep SETUP DIFF first if present)
571
+ items.sort(key=lambda it: (0 if it["kind"] == "SETUP DIFF" else 1, it["step"]))
572
+
573
+ # Up to 3 well-separated keyframes for the HTML summary strip, only for reported differences (raw peaks below
574
+ # the alarm levels drew boxes on quiet runs)
575
+ min_sep = max(fps * 2, S // 6, 1)
576
+ candidates = []
577
+ for it in items:
578
+ if it["kind"] == "END DIFF":
579
+ candidates.append((it["step"], float(it["score"]), "End diff starts", it["box"]))
580
+ candidates.append((S - 1, float(it["score"]), "End state", it["box"]))
581
+ elif it["kind"] == "MID-RUN DIFF":
582
+ candidates.append((it["peak_step"], float(it["score"]), "Mid-run diff", None))
583
+ peaks = []
584
+ for s, sc, lbl, box in candidates:
585
+ if all(abs(s - p["step"]) >= min_sep for p in peaks):
586
+ pbox = box or _hot_region(M_new[s], rel=0.60, floor=0.25)[0]
587
+ peaks.append(dict(step=int(s), score=round(float(sc), 3), label=lbl, box=pbox))
588
+ if len(peaks) >= 3:
589
+ break
590
+ peaks.sort(key=lambda p: p["step"])
591
+
592
+ return dict(curve=curve, heat=heat, end_score=round(end_score, 3), end_thr=round(float(end_thr), 3),
593
+ mid_thr=round(float(mid_thr), 3), setup_score=round(setup_score, 3),
594
+ items=items, peaks=peaks)
595
+
596
+
597
+ def task_patches(first, last, k=16):
598
+ """Where the task acts: the k patches that differ most between the reference's first and last frame.
599
+ Meaningful only when the robot is back in its start pose at the end (then only the task's effect differs)."""
600
+ return np.argsort(1 - (first * last).sum(-1))[-k:]
601
+
602
+
603
+ def end_distance(a_last, b_last, task):
604
+ """How different B's final view is from A's, on the task patches only (mean 1 - cosine)."""
605
+ return float((1 - (a_last[task] * b_last[task]).sum(-1)).mean())
606
+
607
+
608
+ def timing(res):
609
+ """For every frame of A (untrimmed numbering): the time in B (s) when it happens; NaN where A is not on the path."""
610
+ sa, sb, fps = res["trim_a"][0], res["trim_b"][0], res["fps"]
611
+ total, count = np.zeros(res["len_a"]), np.zeros(res["len_a"])
612
+ for i, j in res["path"]:
613
+ total[i + sa] += j + sb
614
+ count[i + sa] += 1
615
+ t = np.full(res["len_a"], np.nan)
616
+ t[count > 0] = total[count > 0] / count[count > 0] / fps
617
+ return t
618
+
619
+
620
+ def durations(t, w):
621
+ """How long B needs for every window of w frames of A."""
622
+ return t[w:] - t[:-w]
623
+
624
+
625
+ def _fp(run):
626
+ """Frames -> (global, patch) fingerprints; an already fingerprinted run (a tuple) is passed through."""
627
+ return run if isinstance(run, tuple) else fingerprints(run)
628
+
629
+
630
+ def _build_peaks(items, M_new, fps, S):
631
+ min_sep = max(fps * 2, S // 6, 1)
632
+ candidates = []
633
+ for it in items:
634
+ k = it["kind"]
635
+ if k in ("END DIFF", "OBJECT DIFF"):
636
+ candidates.append((it["step"], float(it["score"]), "Object diff" if k == "OBJECT DIFF" else "End diff starts", it.get("box")))
637
+ candidates.append((S - 1, float(it["score"]), "End state", it.get("box")))
638
+ elif k in ("MID-RUN DIFF", "ARM DIFF"):
639
+ candidates.append((it["peak_step"], float(it["score"]), "Arm diff" if k == "ARM DIFF" else "Mid-run diff", it.get("box")))
640
+ peaks = []
641
+ for s, sc, lbl, box in candidates:
642
+ if all(abs(s - p["step"]) >= min_sep for p in peaks):
643
+ pbox = box or _hot_region(M_new[s], rel=0.60, floor=0.25)[0]
644
+ peaks.append(dict(step=int(s), score=round(float(sc), 3), label=lbl, box=pbox))
645
+ if len(peaks) >= 3:
646
+ break
647
+ peaks.sort(key=lambda p: p["step"])
648
+ return peaks
649
+
650
+
651
+ START_SCENE_MEAN_THR = 0.28 # mean 3x3-tolerant frame-0 patch distance (same-scene max across 74 pairs: 0.210)
652
+ START_SCENE_GLOBAL_THR = 0.35 # global frame-0 DINOv2 cosine distance (same-scene max across 74 pairs: 0.315)
653
+
654
+
655
+ def start_scene_score(first_a, first_b, first_ga=None, first_gb=None, rad=1):
656
+ """How much the initial frames of A and B differ across the whole scene.
657
+
658
+ Returns `(mean_patch_dist, global_dist)`. Using whole-frame mean patch distance (>= 0.28) and global
659
+ DINOv2 distance (>= 0.35) avoids false alarms from minor arm/lighting shifts on same-scene pairs
660
+ (0/74 flagged across fixed-camera benchmarks) while warning on different backgrounds or major layout changes.
661
+ """
662
+ g_dist = 0.0
663
+ if first_ga is not None and first_gb is not None:
664
+ g_dist = float(1.0 - np.dot(np.asarray(first_ga, np.float32), np.asarray(first_gb, np.float32)))
665
+ if first_a is None or first_b is None or first_a.ndim != 2 or first_a.shape[0] != 256 or first_b.shape != first_a.shape:
666
+ return 0.0, g_dist
667
+ G = 16
668
+ xa = first_a.reshape(1, G, G, -1).astype(np.float32)
669
+ xb = first_b.reshape(1, G, G, -1).astype(np.float32)
670
+ dm = np.maximum(_tol_min_cos(xa, xb, rad=rad), _tol_min_cos(xb, xa, rad=rad))[0]
671
+ return float(dm.mean()), g_dist
672
+
673
+
674
+ def compare(fa, fb, fps=10, fp="global", alike=None, idle=None, spatial=True,
675
+ spatial_thr=SPATIAL_END_THR, mid_thr=SPATIAL_MID_THR, robot=None,
676
+ channels=False, arm_diff=False, track=False, spec_a=None, spec_b=None, goods=None, log=None):
677
+ """Line up run B against run A (frames, or fingerprints from `fingerprints` to skip the model).
678
+ Returns a dict with the path, labels, grouped items, trims, and (when full patches are available)
679
+ spatial diff maps + SETUP DIFF / MID-RUN DIFF / END DIFF items. `robot`: a robot cut-out model (see
680
+ `robot_cover`); the spatial diff then skips the cells the robot covers. When `channels=True`, also runs
681
+ the OBJECT DIFF (32x32 robot-free plates) and LeRobot joint-state ARM DIFF (plus visual arm-mask
682
+ diff when `arm_diff=True`, and LocoTrack-S Apache-2.0 point-track enrichment when `track=True`)."""
683
+ _log = log or (lambda _msg: None)
684
+ dev_note = ""
685
+ if log is not None and not (isinstance(fa, tuple) and isinstance(fb, tuple)):
686
+ try:
687
+ import torch
688
+ dev_note = f" on {torch.cuda.get_device_name(0)}" if torch.cuda.is_available() else " on CPU"
689
+ except Exception:
690
+ pass
691
+ _log(f"Stage: extracting DINOv2-small fingerprints{dev_note} "
692
+ f"(A: {len(fa[0]) if isinstance(fa, tuple) else len(fa)} frames, "
693
+ f"B: {len(fb[0]) if isinstance(fb, tuple) else len(fb)} frames) ...")
694
+ ga, pa = _fp(fa)
695
+ gb, pb = _fp(fb)
696
+ ends = dict(first_a=pa[0], first_b=pb[0], last_a=pa[-1], last_b=pb[-1]) # patch tokens for start/end checks
697
+ start_mean, start_glob = start_scene_score(pa[0], pb[0], ga[0], gb[0])
698
+ start_diff = max(start_mean, start_glob)
699
+ start_warn = (
700
+ f"Start scenes differ (frame-0 patch mean {start_mean:.2f}, global {start_glob:.2f}) — "
701
+ "runs appear to have different starting layouts; rollout-diff works best on same-scene pairs."
702
+ ) if (start_mean >= START_SCENE_MEAN_THR or start_glob >= START_SCENE_GLOBAL_THR) else None
703
+ _log(f" fingerprints ready (start-scene diff {start_diff:.2f})")
704
+ if fp == "residual":
705
+ ga, gb = residual_fp(pa, pb)
706
+ alike = ALIKE[fp] if alike is None else alike
707
+ idle = IDLE[fp] if idle is None else idle
708
+ lag = max(1, fps // 10)
709
+ _log("Stage: trimming idle edges & DTW time alignment ...")
710
+ sa, ea = trim_idle(ga, thr=idle, lag=lag)
711
+ sb, eb = trim_idle(gb, thr=idle, lag=lag)
712
+ D = 1 - ga[sa:ea] @ gb[sb:eb].T
713
+ path = dtw(D)
714
+ hunks = label(path, D, alike)
715
+ tim_items = group_hunks(hunks, path)
716
+ _log(f" aligned {len(path)} steps (active A {sa / fps:.1f}-{ea / fps:.1f}s, "
717
+ f"B {sb / fps:.1f}-{eb / fps:.1f}s, {len(tim_items)} timing hunk(s))")
718
+ sp = None
719
+ if spatial and len(pa) == len(ga) and len(pb) == len(gb) and pa.ndim == 3 and pa.shape[1] == 256:
720
+ la = lab_grid(fa) if isinstance(fa, np.ndarray) else None
721
+ lb = lab_grid(fb) if isinstance(fb, np.ndarray) else None
722
+ ra = rb = None
723
+ kf_a = kf_b = None
724
+ if robot is not None and isinstance(fa, np.ndarray) and isinstance(fb, np.ndarray):
725
+ _log("Stage: segmenting robot arm masks (A & B) ...")
726
+ ra, rb = robot_cover(robot, fa), robot_cover(robot, fb)
727
+ elif channels and isinstance(fa, np.ndarray) and isinstance(fb, np.ndarray):
728
+ from .robot_mask import estimate_robot_cover
729
+ _log("Stage: segmenting robot arm masks (built-in Apache-2.0 Grounding DINO + SAM 2.1) ...")
730
+ ra, kf_a = estimate_robot_cover(fa, log=_log, return_keyframes=True)
731
+ rb, kf_b = estimate_robot_cover(fb, log=_log, return_keyframes=True)
732
+ _log("Stage: computing 16x16 spatial visual diff (DINOv2 + CIE Lab) ...")
733
+ sp = spatial_diff(pa, pb, path, (sa, ea), (sb, eb), fps, la=la, lb=lb,
734
+ end_thr=spatial_thr, mid_thr=mid_thr, ra=ra, rb=rb)
735
+ _log(f" spatial diff ready (end score {sp['end_score']:.2f}, {len(sp['items'])} spot(s))")
736
+ if channels and isinstance(fa, np.ndarray) and isinstance(fb, np.ndarray):
737
+ from .arm_diff import compare_arms
738
+ from .object_diff import compare_objects, merge_channel_items
739
+ stub = dict(path=path, trim_a=(sa, ea), trim_b=(sb, eb), fps=fps)
740
+ extra_g = []
741
+ for gf in (goods or []):
742
+ if not isinstance(gf, np.ndarray):
743
+ continue
744
+ if robot is not None:
745
+ gr = robot_cover(robot, gf)
746
+ else:
747
+ from .robot_mask import estimate_robot_cover
748
+ gr = estimate_robot_cover(gf, log=_log)
749
+ extra_g.append((gf, gr))
750
+ _log(f"Stage: running 32x32 robot-free OBJECT DIFF"
751
+ + (f" (+{len(extra_g)} extra good ref(s))" if extra_g else "") + " ...")
752
+ obj_items = compare_objects(fa, fb, stub, mask_model=robot, ra=ra, rb=rb,
753
+ extra_goods=extra_g, log=_log, kf_a=kf_a, kf_b=kf_b)
754
+ _log(f" found {len(obj_items)} object diff(s)")
755
+ if track and obj_items:
756
+ from .point_diff import enrich_object_diffs
757
+ _log(f"Stage: tracking {len(obj_items)} differing object(s) with LocoTrack-S ...")
758
+ prev_det = [it.get("detail", "") for it in obj_items]
759
+ obj_items = enrich_object_diffs(fa, fb, obj_items, stub, ra=ra, rb=rb)
760
+ n_ann = sum(1 for old_d, it in zip(prev_det, obj_items) if it.get("detail", "") != old_d)
761
+ n_arr = sum(1 for it in obj_items if it.get("track"))
762
+ _log(f" LocoTrack-S tracked {n_ann}/{len(obj_items)} object(s) ({n_arr} motion arrow(s))")
763
+ elif track:
764
+ _log("Stage: skipping LocoTrack-S (no differing objects to track)")
765
+ merged = merge_channel_items(sp["items"], obj_items=obj_items, fps=fps)
766
+ has_end = any(it["kind"] in ("END DIFF", "OBJECT DIFF") for it in merged)
767
+ extra_ra = [gr for _, gr in extra_g if gr is not None]
768
+ _log("Stage: checking ARM DIFF & merging channels ...")
769
+ arm_items = compare_arms(fa, fb, stub, ra=ra, rb=rb, pa=pa, pb=pb, la=la, lb=lb,
770
+ spec_a=spec_a, spec_b=spec_b, has_end_diff=has_end,
771
+ joints_only=not arm_diff, extra_ra=extra_ra)
772
+ merged = merge_channel_items(merged, arm_items=arm_items, fps=fps)
773
+ merged.sort(key=lambda it: (0 if it["kind"] == "SETUP DIFF" else 1, it["step"]))
774
+ sp["items"] = merged
775
+ sp["peaks"] = _build_peaks(merged, sp["heat"].astype(np.float32) / 255.0, fps, len(path))
776
+ _log(f" channels merged ({len(arm_items)} arm diff(s) -> {len(merged)} total visual item(s))")
777
+ return dict(path=path, hunks=hunks, items=tim_items, trim_a=(sa, ea), trim_b=(sb, eb),
778
+ len_a=len(ga), len_b=len(gb), fps=fps, fp=fp, alike=alike,
779
+ cost=[float(D[p]) for p in path], spatial=sp,
780
+ spatial_items=sp["items"] if sp else [],
781
+ start_scene_score=round(start_diff, 3), start_scene_warning=start_warn, **ends)
782
+
783
+
784
+ # ---------------------------------------------------------------- calibration from good runs
785
+ MIN_EXTRA = 0.2 # s; a step must take at least this much longer before the timing check looks at it
786
+ SCALES = (1, 2, 3) # window sizes in seconds for the timing check
787
+
788
+
789
+ def _band(rows, fps):
790
+ import warnings
791
+ rows = np.stack(rows)
792
+ with warnings.catch_warnings(): # windows outside the moving part have no data (NaN)
793
+ warnings.simplefilter("ignore", RuntimeWarning)
794
+ med = np.nanmedian(rows, 0)
795
+ spread = 1.4826 * np.nanmedian(np.abs(rows - med), 0)
796
+ return med, np.maximum(spread, 1 / fps) # below one frame the timing cannot be measured
797
+
798
+
799
+ def _worst(d, med, spread):
800
+ excess = d - med
801
+ z = np.where(excess >= MIN_EXTRA, excess / spread, 0.0)
802
+ z = np.nan_to_num(z)
803
+ k = int(np.argmax(z))
804
+ return float(z[k]), k
805
+
806
+
807
+ def _robust_upper(vals, mult=1.1):
808
+ """Upper alarm threshold: max(vals)*mult for small sets; drops the single top outlier when N >= 10
809
+ so one mislabelled calibration run cannot blind the detector."""
810
+ s = sorted(float(v) for v in vals)
811
+ ref = s[-2] if len(s) >= 10 else s[-1]
812
+ return mult * ref
813
+
814
+
815
+ def calibrate(ref_frames, good, fps=10, fp="global", log=print):
816
+ """Learn what 'normal' looks like from good runs, all compared to one reference run.
817
+
818
+ good: list of frame arrays of good runs. Returns a dict that `check_floor` uses:
819
+ alike p99 path cost between the reference and good runs
820
+ timing per window size: median time per A window, robust spread, alarm threshold
821
+ (leave-one-out over the good runs: robust upper bound x1.1)
822
+ end task patches (reference first vs last frame) and the threshold for 'the final view
823
+ differs' there (robust upper bound x1.1).
824
+ spatial learned spatial end-diff threshold (when full patches are available)."""
825
+ if len(good) < 3:
826
+ raise ValueError("calibrate needs at least 3 good runs besides the reference")
827
+ costs, T, lasts, sp_ends = [], [], [], []
828
+ ref = _fp(ref_frames)
829
+ ref_lab = lab_grid(ref_frames) if isinstance(ref_frames, np.ndarray) else None
830
+ for n, fb in enumerate(good):
831
+ res = compare(ref, fb, fps=fps, fp=fp, spatial=False)
832
+ costs += res["cost"]
833
+ T.append(timing(res))
834
+ lasts.append(res["last_b"])
835
+ if len(ref[1]) == len(ref[0]) and ref[1].ndim == 3 and ref[1].shape[1] == 256:
836
+ _, pb = _fp(fb)
837
+ if len(pb) == res["len_b"] and pb.ndim == 3 and pb.shape[1] == 256:
838
+ lb = lab_grid(fb) if isinstance(fb, np.ndarray) else None
839
+ sp = spatial_diff(ref[1], pb, res["path"], res["trim_a"], res["trim_b"], fps, la=ref_lab, lb=lb)
840
+ sp_ends.append(sp["end_score"])
841
+ log(f" good run {n + 1}/{len(good)}: {res['len_b'] / fps:.1f} s, path cost median {np.median(res['cost']):.3f}")
842
+ task = task_patches(res["first_a"], res["last_a"])
843
+ ends = [end_distance(res["last_a"], last, task) for last in lasts]
844
+ timing_floor = []
845
+ for s in SCALES:
846
+ w = round(s * fps)
847
+ D = [durations(t, w) for t in T]
848
+ loo = [_worst(D[k], *_band(D[:k] + D[k + 1:], fps))[0] for k in range(len(D))]
849
+ med, spread = _band(D, fps)
850
+ timing_floor.append(dict(seconds=s, w=w, thr=_robust_upper(loo, 1.1), med=med.tolist(), spread=spread.tolist()))
851
+ out = dict(fps=fps, fp=fp, alike=float(np.percentile(costs, 99)), runs=len(good), len_ref=len(ref[0]),
852
+ timing=timing_floor, end=dict(task=task.tolist(), thr=_robust_upper(ends, 1.1), good=ends))
853
+ if sp_ends:
854
+ out["spatial"] = dict(end_thr=round(_robust_upper(sp_ends, 1.15), 3), good=sp_ends)
855
+ return out
856
+
857
+
858
+ def check_floor(res, floor, end_check=False):
859
+ """Timing check (and, if asked, the experimental end-state check) of one comparison against a
860
+ calibration. Returns extra items."""
861
+ fps, t, out = res["fps"], timing(res), []
862
+ for sc in floor["timing"]:
863
+ med, spread = np.array(sc["med"], float), np.array(sc["spread"], float)
864
+ d = durations(t, sc["w"])
865
+ if len(d) != len(med):
866
+ raise ValueError("the reference run differs from the one used for calibration")
867
+ z, k = _worst(d, med, spread)
868
+ if z > sc["thr"]:
869
+ out.append(dict(kind="SLOW STEP", a=[k, k + sc["w"]], took=float(d[k]), normal=float(med[k]),
870
+ spread=float(spread[k]), z=z, seconds=float(d[k] - med[k])))
871
+ if out: # report the window size that stands out most
872
+ out = [max(out, key=lambda it: it["z"] / next(s["thr"] for s in floor["timing"]
873
+ if s["w"] == it["a"][1] - it["a"][0]))]
874
+ if end_check:
875
+ d = end_distance(res["last_a"], res["last_b"], np.array(floor["end"]["task"]))
876
+ if d > floor["end"]["thr"]:
877
+ out.append(dict(kind="END DIFFERS", a=[res["len_a"] - 1, res["len_a"] - 1], seconds=0.0,
878
+ dist=d, thr=floor["end"]["thr"]))
879
+ return out