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.
- diffvid-1.0.1.dist-info/METADATA +275 -0
- diffvid-1.0.1.dist-info/RECORD +38 -0
- diffvid-1.0.1.dist-info/WHEEL +5 -0
- diffvid-1.0.1.dist-info/entry_points.txt +2 -0
- diffvid-1.0.1.dist-info/licenses/LICENSE +202 -0
- diffvid-1.0.1.dist-info/licenses/NOTICE +5 -0
- diffvid-1.0.1.dist-info/top_level.txt +1 -0
- rollout_diff/__init__.py +169 -0
- rollout_diff/__main__.py +5 -0
- rollout_diff/_locotrack/__init__.py +1 -0
- rollout_diff/_locotrack/cmdtop.py +47 -0
- rollout_diff/_locotrack/locotrack_model.py +1077 -0
- rollout_diff/_locotrack/nets.py +429 -0
- rollout_diff/_locotrack/utils.py +301 -0
- rollout_diff/arm_diff.py +324 -0
- rollout_diff/batch.py +692 -0
- rollout_diff/cli.py +475 -0
- rollout_diff/core.py +879 -0
- rollout_diff/explain.py +538 -0
- rollout_diff/export.py +215 -0
- rollout_diff/hub.py +207 -0
- rollout_diff/object_diff.py +672 -0
- rollout_diff/objects.py +245 -0
- rollout_diff/objlog.py +903 -0
- rollout_diff/point_diff.py +221 -0
- rollout_diff/profile.py +215 -0
- rollout_diff/report.py +758 -0
- rollout_diff/robot_mask.py +238 -0
- rollout_diff/teach.py +1374 -0
- rollout_diff/world/__init__.py +25 -0
- rollout_diff/world/changes.py +154 -0
- rollout_diff/world/compare.py +139 -0
- rollout_diff/world/config.py +28 -0
- rollout_diff/world/match.py +458 -0
- rollout_diff/world/models.py +214 -0
- rollout_diff/world/plates.py +312 -0
- rollout_diff/world/track.py +301 -0
- rollout_diff/world_diff.py +11 -0
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Point-tracking channel powered by LocoTrack-S (Cho et al., ECCV 2024; 100% Apache-2.0, 33 MB).
|
|
2
|
+
|
|
3
|
+
Tracks dense object query points forward and backward across runs A and B (~1 s/run on GPU in bf16)
|
|
4
|
+
while filtering out occluded frames and robot-arm overlap (`rob`), giving:
|
|
5
|
+
1. Motion-enriched OBJECT DIFFs: exact origin -> destination trajectory, total path length vs net
|
|
6
|
+
displacement (detects dragging/fumbling vs clean transport vs never moved even under a stuck arm),
|
|
7
|
+
and a polyline `track` rendered as a motion arrow in the HTML report.
|
|
8
|
+
2. Optional mid-run object motion/knock/drop checks (`compare_tracks`) for objects disturbed mid-run.
|
|
9
|
+
"""
|
|
10
|
+
import functools
|
|
11
|
+
|
|
12
|
+
import cv2
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
LOCOTRACK_REPO = "hamacojr/LocoTrack-pytorch-weights"
|
|
16
|
+
LOCOTRACK_FILE = "locotrack_small.ckpt"
|
|
17
|
+
LOCOTRACK_REVISION = "a8754d0edfd9e53713dcb31ee21734aac8b727cf" # pinned: a later upload to that repo is never used
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@functools.lru_cache(maxsize=1)
|
|
21
|
+
def _locotrack_model():
|
|
22
|
+
"""Load and cache LocoTrack-S (Apache-2.0, ~8.2M params, 33 MB) on CUDA or CPU."""
|
|
23
|
+
try:
|
|
24
|
+
import torch
|
|
25
|
+
from huggingface_hub import hf_hub_download
|
|
26
|
+
from ._locotrack.locotrack_model import LocoTrack
|
|
27
|
+
except ImportError as exc:
|
|
28
|
+
raise ImportError(
|
|
29
|
+
"Point tracking (--track) requires einops and huggingface-hub: pip install 'diffvid[track]'"
|
|
30
|
+
) from exc
|
|
31
|
+
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
|
32
|
+
ckpt = hf_hub_download(repo_id=LOCOTRACK_REPO, filename=LOCOTRACK_FILE, repo_type="dataset",
|
|
33
|
+
revision=LOCOTRACK_REVISION)
|
|
34
|
+
raw = torch.load(ckpt, map_location="cpu", weights_only=True) # tensors only: a changed file cannot run code
|
|
35
|
+
sd = raw.get("state_dict", raw)
|
|
36
|
+
sd = {k[6:] if k.startswith("model.") else k: v for k, v in sd.items()}
|
|
37
|
+
model = LocoTrack(model_size="small").to(dev).eval()
|
|
38
|
+
model.load_state_dict(sd, strict=True)
|
|
39
|
+
return model, dev
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def track_points(frames, q_txy, rob=None, max_frames=64, model_pair=None):
|
|
43
|
+
"""Track normalized query points `q_txy` = [(t_frac, x_norm, y_norm), ...] across `frames` (N, H, W, 3).
|
|
44
|
+
|
|
45
|
+
Returns dict with:
|
|
46
|
+
tracks: (P, T, 2) float32 normalized [x, y] in [0, 1]
|
|
47
|
+
occ: (P, T) bool occlusion mask
|
|
48
|
+
clear: (P, T) bool (visible AND outside 1-cell dilated robot mask)
|
|
49
|
+
fidx: (T,) int frame indices into `frames`
|
|
50
|
+
"""
|
|
51
|
+
import torch
|
|
52
|
+
|
|
53
|
+
if frames is None or len(frames) < 2 or not q_txy:
|
|
54
|
+
return None
|
|
55
|
+
model, dev = model_pair if model_pair is not None else _locotrack_model()
|
|
56
|
+
n, h, w = frames.shape[:3]
|
|
57
|
+
stride = max(1, int(np.ceil(n / max_frames)))
|
|
58
|
+
fidx = np.arange(0, n, stride)
|
|
59
|
+
if fidx[-1] != n - 1:
|
|
60
|
+
fidx = np.append(fidx, n - 1)
|
|
61
|
+
vid = frames[fidx]
|
|
62
|
+
T = len(vid)
|
|
63
|
+
rob_sub = rob[fidx] if rob is not None and len(rob) == n else None
|
|
64
|
+
|
|
65
|
+
ql = []
|
|
66
|
+
for tf, xn, yn in q_txy:
|
|
67
|
+
tq = int(round(np.clip(tf, 0.0, 1.0) * (T - 1)))
|
|
68
|
+
if rob_sub is not None:
|
|
69
|
+
rg = rob_sub.shape[1]
|
|
70
|
+
rx = min(rg - 1, max(0, int(xn * rg)))
|
|
71
|
+
ry = min(rg - 1, max(0, int(yn * rg)))
|
|
72
|
+
if rob_sub[tq, ry, rx] >= 0.18:
|
|
73
|
+
free = np.flatnonzero(rob_sub[:, ry, rx] < 0.18)
|
|
74
|
+
if len(free):
|
|
75
|
+
tq = int(free[np.argmin(np.abs(free - tq))])
|
|
76
|
+
ql.append([float(tq), float(np.clip(yn, 0.0, 1.0) * h), float(np.clip(xn, 0.0, 1.0) * w)])
|
|
77
|
+
|
|
78
|
+
qp = torch.tensor(ql, dtype=torch.float32, device=dev)[None]
|
|
79
|
+
use_bf16 = (dev == "cuda") and torch.cuda.is_bf16_supported()
|
|
80
|
+
with torch.no_grad(), torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
|
|
81
|
+
out = model.inference(vid[None], qp, query_chunk_size=64, resolution=(256, 256), query_format="tyx")
|
|
82
|
+
tr = out["tracks"][0].float().cpu().numpy()
|
|
83
|
+
occ = out["occlusion"][0].cpu().numpy()
|
|
84
|
+
tr_n = np.stack([tr[..., 0] / max(w, 1), tr[..., 1] / max(h, 1)], axis=-1).astype(np.float32)
|
|
85
|
+
|
|
86
|
+
clear = ~occ
|
|
87
|
+
if rob_sub is not None:
|
|
88
|
+
rg = rob_sub.shape[1]
|
|
89
|
+
k3 = np.ones((3, 3), np.uint8)
|
|
90
|
+
rob_dil = np.stack([cv2.dilate((r >= 0.18).astype(np.uint8), k3) > 0 for r in rob_sub])
|
|
91
|
+
tx = np.clip((tr_n[..., 0] * rg).astype(int), 0, rg - 1)
|
|
92
|
+
ty = np.clip((tr_n[..., 1] * rg).astype(int), 0, rg - 1)
|
|
93
|
+
tt = np.broadcast_to(np.arange(T)[None, :], tx.shape)
|
|
94
|
+
clear = clear & (~rob_dil[tt, ty, tx])
|
|
95
|
+
return dict(tracks=tr_n, occ=occ, clear=clear, fidx=fidx, n_orig=n)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def summarize_box_tracks(tr_dict, indices, fps=10):
|
|
99
|
+
"""Aggregate tracked points belonging to one object box into robust motion statistics & polyline."""
|
|
100
|
+
if tr_dict is None or not indices:
|
|
101
|
+
return None
|
|
102
|
+
tr, cl, fidx = tr_dict["tracks"], tr_dict["clear"], tr_dict["fidx"]
|
|
103
|
+
T = tr.shape[1]
|
|
104
|
+
net_ds, path_ls, starts, ends, t_moves = [], [], [], [], []
|
|
105
|
+
# Collect per-time median across clear points for clean arrow polyline
|
|
106
|
+
t_xy = []
|
|
107
|
+
for i in indices:
|
|
108
|
+
ci = np.flatnonzero(cl[i])
|
|
109
|
+
if len(ci) < 3:
|
|
110
|
+
continue
|
|
111
|
+
pts = tr[i, ci]
|
|
112
|
+
p0 = np.median(pts[:min(3, len(pts))], axis=0)
|
|
113
|
+
pe = np.median(pts[-min(3, len(pts)):], axis=0)
|
|
114
|
+
nd = float(np.linalg.norm(pe - p0))
|
|
115
|
+
if len(pts) >= 5:
|
|
116
|
+
sm = np.stack([
|
|
117
|
+
np.median(np.lib.stride_tricks.sliding_window_view(pts[:, d], 3), axis=-1) for d in (0, 1)
|
|
118
|
+
], axis=-1)
|
|
119
|
+
steps = np.linalg.norm(np.diff(sm, axis=0), axis=-1)
|
|
120
|
+
pl = float(steps[steps > 0.015].sum())
|
|
121
|
+
else:
|
|
122
|
+
pl = nd
|
|
123
|
+
net_ds.append(nd)
|
|
124
|
+
path_ls.append(pl)
|
|
125
|
+
starts.append(p0)
|
|
126
|
+
ends.append(pe)
|
|
127
|
+
d0 = np.linalg.norm(pts - p0, axis=-1)
|
|
128
|
+
mv = np.flatnonzero(d0 > 0.06)
|
|
129
|
+
if len(mv):
|
|
130
|
+
t_moves.append(float(fidx[ci[mv[0]]]) / max(fps, 1))
|
|
131
|
+
if not net_ds:
|
|
132
|
+
return None
|
|
133
|
+
|
|
134
|
+
for t in range(T):
|
|
135
|
+
ok = [i for i in indices if cl[i, t]]
|
|
136
|
+
if len(ok) >= max(2, len(indices) // 3):
|
|
137
|
+
med = np.median(tr[ok, t], axis=0)
|
|
138
|
+
t_xy.append([round(float(med[0]), 4), round(float(med[1]), 4)])
|
|
139
|
+
# Downsample polyline to at most 14 waypoints while keeping endpoints
|
|
140
|
+
if len(t_xy) > 14:
|
|
141
|
+
pick = np.linspace(0, len(t_xy) - 1, 14).astype(int)
|
|
142
|
+
t_xy = [t_xy[k] for k in pick]
|
|
143
|
+
|
|
144
|
+
p0m = np.median(starts, axis=0)
|
|
145
|
+
pem = np.median(ends, axis=0)
|
|
146
|
+
return dict(
|
|
147
|
+
net_disp=float(np.median(net_ds)),
|
|
148
|
+
path_len=float(np.median(path_ls)),
|
|
149
|
+
origin=[round(float(p0m[0]), 3), round(float(p0m[1]), 3)],
|
|
150
|
+
dest=[round(float(pem[0]), 3), round(float(pem[1]), 3)],
|
|
151
|
+
moved_at_s=round(float(np.median(t_moves)), 1) if t_moves else None,
|
|
152
|
+
polyline=t_xy,
|
|
153
|
+
n_valid=len(net_ds),
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def enrich_object_diffs(fa, fb, items, res, ra=None, rb=None, max_frames=64, model_pair=None):
|
|
158
|
+
"""Enrich detected OBJECT DIFF items with LocoTrack-S point trajectories (zero extra false items).
|
|
159
|
+
|
|
160
|
+
Queries a 3x3 cluster inside each OBJECT DIFF box backward from t=end in B (and in A for
|
|
161
|
+
'did not change in B' / 'not placed here in B' items) in one single GPU pass (~1 s), appending
|
|
162
|
+
plain-English trajectory facts and attaching `track` polylines for HTML/MP4 arrow overlays.
|
|
163
|
+
"""
|
|
164
|
+
if fb is None or not items:
|
|
165
|
+
return items
|
|
166
|
+
fps = res.get("fps", 10)
|
|
167
|
+
obj_indices = [k for k, it in enumerate(items) if it.get("kind") == "OBJECT DIFF" and it.get("box") and not it.get("info")]
|
|
168
|
+
if not obj_indices:
|
|
169
|
+
return items
|
|
170
|
+
|
|
171
|
+
q_b, map_b = [], {}
|
|
172
|
+
q_a, map_a = [], {}
|
|
173
|
+
for k in obj_indices[:6]:
|
|
174
|
+
it = items[k]
|
|
175
|
+
x0, y0, x1, y1 = it["box"]
|
|
176
|
+
detail = it.get("detail", "")
|
|
177
|
+
pts = [(1.0, x0 + fx * (x1 - x0), y0 + fy * (y1 - y0)) for fx in (0.33, 0.5, 0.67) for fy in (0.33, 0.5, 0.67)]
|
|
178
|
+
# Track B backward from end for all boxes (sees dragged/fumbled vs stationary/arrived in B)
|
|
179
|
+
if "removed / missing" not in detail:
|
|
180
|
+
start_b = len(q_b)
|
|
181
|
+
q_b.extend(pts)
|
|
182
|
+
map_b[k] = list(range(start_b, len(q_b)))
|
|
183
|
+
# Also track A backward from end when B didn't change / removed / didn't place here (sees A placing/clearing it!)
|
|
184
|
+
if ("did not change in B" in detail or "not placed here in B" in detail or "removed / missing" in detail) and fa is not None:
|
|
185
|
+
start_a = len(q_a)
|
|
186
|
+
q_a.extend(pts)
|
|
187
|
+
map_a[k] = list(range(start_a, len(q_a)))
|
|
188
|
+
|
|
189
|
+
tr_b = track_points(fb, q_b, rob=rb, max_frames=max_frames, model_pair=model_pair) if q_b else None
|
|
190
|
+
tr_a = track_points(fa, q_a, rob=ra, max_frames=max_frames, model_pair=model_pair) if q_a else None
|
|
191
|
+
|
|
192
|
+
out = [dict(it) for it in items]
|
|
193
|
+
for k in obj_indices[:6]:
|
|
194
|
+
it = out[k]
|
|
195
|
+
st_b = summarize_box_tracks(tr_b, map_b[k], fps=fps) if (k in map_b and tr_b is not None) else None
|
|
196
|
+
st_a = summarize_box_tracks(tr_a, map_a[k], fps=fps) if (k in map_a and tr_a is not None) else None
|
|
197
|
+
if st_b is not None:
|
|
198
|
+
nd, pl = st_b["net_disp"], st_b["path_len"]
|
|
199
|
+
if nd >= 0.08 or pl >= 0.14:
|
|
200
|
+
ox, oy = st_b["origin"]
|
|
201
|
+
dx, dy = st_b["dest"]
|
|
202
|
+
verb = "dragged/fumbled in B" if pl > nd + 0.10 else "tracked in B"
|
|
203
|
+
t_txt = f" from B {st_b['moved_at_s']:.1f} s" if st_b["moved_at_s"] is not None else ""
|
|
204
|
+
it["detail"] = (
|
|
205
|
+
f"{it.get('detail', '')} · {verb} ({ox:.2f},{oy:.2f})→({dx:.2f},{dy:.2f}), "
|
|
206
|
+
f"dist {nd:.2f} / path {pl:.2f}{t_txt}"
|
|
207
|
+
)
|
|
208
|
+
if len(st_b["polyline"]) >= 2:
|
|
209
|
+
it["track"] = st_b["polyline"]
|
|
210
|
+
elif "appeared / left here" in it.get("detail", "") or "moved here" in it.get("detail", ""):
|
|
211
|
+
if st_b["moved_at_s"] is not None:
|
|
212
|
+
it["detail"] = f"{it.get('detail', '')} · arrived/settled around B {st_b['moved_at_s']:.1f} s"
|
|
213
|
+
elif st_a is not None and st_a["net_disp"] >= 0.08:
|
|
214
|
+
t_txt = f" at A {st_a['moved_at_s']:.1f} s" if st_a["moved_at_s"] is not None else ""
|
|
215
|
+
it["detail"] = f"{it.get('detail', '')} · A moved object here{t_txt} (dist {st_a['net_disp']:.2f}); B stationary"
|
|
216
|
+
elif "not placed here in B" not in it.get("detail", ""):
|
|
217
|
+
it["detail"] = f"{it.get('detail', '')} · tracked stationary in B (never cleared)"
|
|
218
|
+
elif st_a is not None and (st_a["net_disp"] >= 0.08 or st_a["moved_at_s"] is not None):
|
|
219
|
+
t_txt = f" at A {st_a['moved_at_s']:.1f} s" if st_a["moved_at_s"] is not None else ""
|
|
220
|
+
it["detail"] = f"{it.get('detail', '')} · A moved object here{t_txt} (dist {st_a['net_disp']:.2f})"
|
|
221
|
+
return out
|
rollout_diff/profile.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Normal profile: learn from normal runs what normally varies, then show only what is unusual in a new run.
|
|
2
|
+
|
|
3
|
+
Comparing B with one reference A shows every place where two normal runs happen to differ (the object lands a
|
|
4
|
+
bit elsewhere, the arm takes another path), so real differences drown. Here, per moment of the reference and per
|
|
5
|
+
image cell (16 x 16), B counts as normal when at least one normal run looks like it there (3 x 3 cells and +/- 1
|
|
6
|
+
frame of tolerance). How far B is from its nearest normal run is then compared with how far the normal runs are
|
|
7
|
+
from each other (leave-one-out), and only what lasts 0.5 s counts. The result is a ranked list of UNUSUAL
|
|
8
|
+
regions with their start time and a box, plus a heat map that is empty where B behaves like some normal run.
|
|
9
|
+
|
|
10
|
+
Measured before writing this (experiments/region_nn_eval.py, spinning table, 12 normal runs): the three real
|
|
11
|
+
failures scored 90-98, normal runs about 22; the knocked-off cube was boxed on the floor from B 5.0 s (it lands at
|
|
12
|
+
4.9 s). Comparing with A alone gave failures 29 vs normal 14, with heavy overlap.
|
|
13
|
+
"""
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from .core import compare
|
|
17
|
+
|
|
18
|
+
DIMS = 64 # patch tokens are projected to 64 dims (PCA of A's patches) to keep profiles small
|
|
19
|
+
KEEP = 5 # frames (0.5 s at 10 fps): a difference must last this long
|
|
20
|
+
MERGE = 2 # frames: unusual stretches closer than this are one item
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _torch():
|
|
24
|
+
import torch
|
|
25
|
+
return torch, ("cuda" if torch.cuda.is_available() else "cpu")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def basis(p, dims=DIMS, sample=20000, seed=0):
|
|
29
|
+
"""PCA basis (384 x dims) of the reference's patch tokens."""
|
|
30
|
+
x = p.reshape(-1, p.shape[-1]).astype(np.float32)
|
|
31
|
+
if len(x) > sample:
|
|
32
|
+
x = x[np.random.default_rng(seed).choice(len(x), sample, replace=False)]
|
|
33
|
+
_, _, vt = np.linalg.svd(x - x.mean(0), full_matrices=False)
|
|
34
|
+
return vt[:dims].T.astype(np.float32)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def reduce(p, B):
|
|
38
|
+
"""(n, 256, 384) patch tokens -> (n, 16, 16, dims) float16, unit length."""
|
|
39
|
+
x = p.reshape(-1, p.shape[-1]).astype(np.float32) @ B
|
|
40
|
+
x /= np.maximum(np.linalg.norm(x, axis=1, keepdims=True), 1e-8)
|
|
41
|
+
return x.reshape(len(p), 16, 16, -1).astype(np.float16)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def aligned(res, red_b, len_a):
|
|
45
|
+
"""B's reduced patches matched to every A frame (mean over matched B frames), and a mask of A frames on the path."""
|
|
46
|
+
sa, sb = res["trim_a"][0], res["trim_b"][0]
|
|
47
|
+
X = np.zeros((len_a,) + red_b.shape[1:], np.float16)
|
|
48
|
+
mask = np.zeros(len_a, bool)
|
|
49
|
+
match = {}
|
|
50
|
+
for i, j in res["path"]:
|
|
51
|
+
match.setdefault(i + sa, []).append(j + sb)
|
|
52
|
+
for i, js in match.items():
|
|
53
|
+
x = red_b[js].astype(np.float32).mean(0)
|
|
54
|
+
X[i] = x / np.maximum(np.linalg.norm(x, axis=-1, keepdims=True), 1e-8)
|
|
55
|
+
mask[i] = True
|
|
56
|
+
return X, mask, match
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _tol_min(torch, X, Y):
|
|
60
|
+
"""Per cell of X (n, 16, 16, d): smallest cosine distance to Y's cells within one cell."""
|
|
61
|
+
Yp = torch.nn.functional.pad(Y.permute(0, 3, 1, 2), (1, 1, 1, 1), mode="replicate").permute(0, 2, 3, 1)
|
|
62
|
+
best = None
|
|
63
|
+
for du in range(3):
|
|
64
|
+
for dv in range(3):
|
|
65
|
+
d = 1 - (X * Yp[:, du:du + 16, dv:dv + 16]).sum(-1)
|
|
66
|
+
best = d if best is None else torch.minimum(best, d)
|
|
67
|
+
return best
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def nn_distance(X, mask, pool):
|
|
71
|
+
"""(len A, 256): per A frame and cell, the distance of X to the nearest pool run (3 x 3 cells, +/- 1 frame).
|
|
72
|
+
pool: list of (patches (len A, 16, 16, d), mask). NaN where X is not on the path."""
|
|
73
|
+
torch, dev = _torch()
|
|
74
|
+
n = len(X)
|
|
75
|
+
Xg = torch.as_tensor(X, device=dev).float()
|
|
76
|
+
best = torch.full((n, 16, 16), float("inf"), device=dev)
|
|
77
|
+
for Y, ymask in pool:
|
|
78
|
+
Yg = torch.as_tensor(Y, device=dev).float()
|
|
79
|
+
for dt in (-1, 0, 1):
|
|
80
|
+
src = np.arange(n) + dt
|
|
81
|
+
ok = (src >= 0) & (src < n) & mask
|
|
82
|
+
ok[ok] = ymask[src[ok]]
|
|
83
|
+
if ok.any():
|
|
84
|
+
oi = torch.as_tensor(np.flatnonzero(ok), device=dev)
|
|
85
|
+
si = torch.as_tensor(src[ok], device=dev)
|
|
86
|
+
a, b = Xg[oi], Yg[si]
|
|
87
|
+
best[oi] = torch.minimum(best[oi], torch.maximum(_tol_min(torch, a, b), _tol_min(torch, b, a)))
|
|
88
|
+
out = best.cpu().numpy().reshape(n, 256)
|
|
89
|
+
out[~mask] = np.nan
|
|
90
|
+
out[np.isinf(out)] = np.nan
|
|
91
|
+
return out
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _stats(Ds):
|
|
95
|
+
import warnings
|
|
96
|
+
with warnings.catch_warnings():
|
|
97
|
+
warnings.simplefilter("ignore", RuntimeWarning)
|
|
98
|
+
S = np.stack(Ds)
|
|
99
|
+
med = np.nanmedian(S, 0)
|
|
100
|
+
spread = 1.4826 * np.nanmedian(np.abs(S - med), 0)
|
|
101
|
+
typical = np.nanmedian(spread, 0, keepdims=True) # per cell over the whole run
|
|
102
|
+
floor = np.nanmedian(spread)
|
|
103
|
+
spread = np.fmax(np.fmax(spread, typical), floor)
|
|
104
|
+
return np.nan_to_num(med, nan=0.0).astype(np.float32), np.nan_to_num(spread, nan=floor).astype(np.float32)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def persistent(D, med, spread, keep=KEEP):
|
|
108
|
+
"""z per (A frame, cell), kept only where it lasts `keep` frames: the minimum over the next frames."""
|
|
109
|
+
z = (D - med) / spread
|
|
110
|
+
z[~np.isfinite(z)] = -np.inf
|
|
111
|
+
zp = np.full_like(z, -np.inf)
|
|
112
|
+
for i in range(len(z) - keep + 1):
|
|
113
|
+
zp[i] = z[i:i + keep].min(0)
|
|
114
|
+
return zp
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _upper(vals, mult=1.1):
|
|
118
|
+
s = sorted(float(v) for v in vals)
|
|
119
|
+
return mult * (s[-2] if len(s) >= 10 else s[-1]) # one odd normal run must not blind the check
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def build(A, goods, fps=10, log=print):
|
|
123
|
+
"""Profile from the reference A and normal runs, all as fingerprints (global, patches (n, 256, 384)).
|
|
124
|
+
goods: iterable; full patch tokens are dropped after use. Returns (profile dict, light runs for calibrate)."""
|
|
125
|
+
Bs = basis(A[1])
|
|
126
|
+
a_red = reduce(A[1], Bs)
|
|
127
|
+
pool, light = [], []
|
|
128
|
+
for n, G in enumerate(goods):
|
|
129
|
+
res = compare(A, G, fps=fps, spatial=False)
|
|
130
|
+
X, m, _ = aligned(res, reduce(G[1], Bs), len(A[0]))
|
|
131
|
+
pool.append((X, m))
|
|
132
|
+
light.append((G[0], G[1][[0, -1]])) # what calibrate needs: global + first/last patches
|
|
133
|
+
log(f" normal run {n + 1}: aligned")
|
|
134
|
+
self_a = (a_red, np.ones(len(a_red), bool))
|
|
135
|
+
D = [nn_distance(X, m, [self_a] + pool[:k] + pool[k + 1:]) for k, (X, m) in enumerate(pool)]
|
|
136
|
+
loo = []
|
|
137
|
+
for k in range(len(D)):
|
|
138
|
+
zp = persistent(D[k], *_stats(D[:k] + D[k + 1:]))
|
|
139
|
+
loo.append(float(zp.max()))
|
|
140
|
+
med, spread = _stats(D)
|
|
141
|
+
prof = dict(basis=Bs, a=a_red, good=np.stack([X for X, _ in pool]), masks=np.stack([m for _, m in pool]),
|
|
142
|
+
med=med, spread=spread, thr=_upper(loo), loo=np.array(loo, np.float32), fps=fps)
|
|
143
|
+
log(f" normal runs score up to {max(loo):.1f} when left out -> unusual above {prof['thr']:.1f}")
|
|
144
|
+
return prof, light
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def save(prof, path):
|
|
148
|
+
np.savez(path, **prof)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def load(path):
|
|
152
|
+
z = np.load(path)
|
|
153
|
+
return {k: (z[k].item() if z[k].ndim == 0 else z[k]) for k in z.files}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _box(cells):
|
|
157
|
+
ys, xs = np.nonzero(cells.reshape(16, 16))
|
|
158
|
+
return [round(xs.min() / 16, 4), round(ys.min() / 16, 4), round((xs.max() + 1) / 16, 4), round((ys.max() + 1) / 16, 4)]
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def check(prof, A, B, res):
|
|
162
|
+
"""Unusual regions of B against the profile, ranked (strongest first), in the report's spatial format.
|
|
163
|
+
A, B: fingerprints (B with full patch tokens); res: compare(A, B) (same reference as the profile)."""
|
|
164
|
+
import cv2
|
|
165
|
+
len_a = len(A[0])
|
|
166
|
+
if len_a != len(prof["a"]):
|
|
167
|
+
raise ValueError("the reference run differs from the one the profile was made with")
|
|
168
|
+
thr = float(prof["thr"])
|
|
169
|
+
X, m, match = aligned(res, reduce(B[1], prof["basis"]), len_a)
|
|
170
|
+
pool = [(prof["a"], np.ones(len_a, bool))] + list(zip(prof["good"], prof["masks"]))
|
|
171
|
+
zp = persistent(nn_distance(X, m, pool), prof["med"], prof["spread"])
|
|
172
|
+
level = zp.max(1) # per A frame: the most unusual cell
|
|
173
|
+
|
|
174
|
+
items, hot = [], np.flatnonzero(level > thr)
|
|
175
|
+
spans = []
|
|
176
|
+
for i in hot:
|
|
177
|
+
if spans and i - spans[-1][1] <= MERGE:
|
|
178
|
+
spans[-1][1] = i
|
|
179
|
+
else:
|
|
180
|
+
spans.append([i, i])
|
|
181
|
+
sa, sb = res["trim_a"][0], res["trim_b"][0]
|
|
182
|
+
step_of = {}
|
|
183
|
+
for s, (i, j) in enumerate(res["path"]):
|
|
184
|
+
step_of.setdefault(i + sa, s)
|
|
185
|
+
for i0, i1 in spans:
|
|
186
|
+
ip = i0 + int(np.argmax(level[i0:i1 + 1]))
|
|
187
|
+
c = int(np.argmax(zp[ip]))
|
|
188
|
+
cells = (zp[ip] > thr).astype(np.uint8).reshape(16, 16)
|
|
189
|
+
_, lab = cv2.connectedComponents(cells, connectivity=8)
|
|
190
|
+
region = lab == lab[c // 16, c % 16]
|
|
191
|
+
b0, b1 = min(match[i0]), max(match[i1])
|
|
192
|
+
items.append(dict(kind="UNUSUAL", a=[i0 - sa, i1 - sa], b=[b0 - sb, b1 - sb], step=step_of.get(i0, 0),
|
|
193
|
+
end_step=step_of.get(i1, 0), peak_step=step_of.get(ip, 0), score=round(float(level[ip]) / thr, 2),
|
|
194
|
+
thr=1.0, box=_box(region), frames=int(i1 - i0 + 1)))
|
|
195
|
+
items.sort(key=lambda it: -it["score"])
|
|
196
|
+
if not items: # show where B is closest to unusual, as information
|
|
197
|
+
ip = int(np.argmax(level))
|
|
198
|
+
if np.isfinite(level[ip]):
|
|
199
|
+
c = int(np.argmax(zp[ip]))
|
|
200
|
+
cell = np.zeros(256, bool)
|
|
201
|
+
cell[c] = True
|
|
202
|
+
items.append(dict(kind="MOST DIFFERENT", a=[ip - sa, ip - sa], b=[min(match[ip]) - sb] * 2,
|
|
203
|
+
step=step_of.get(ip, 0), end_step=step_of.get(ip, 0), peak_step=step_of.get(ip, 0),
|
|
204
|
+
score=round(float(level[ip]) / thr, 2), thr=1.0, box=_box(cell), frames=0, info=True))
|
|
205
|
+
|
|
206
|
+
rows = np.array([i + sa for i, _ in res["path"]])
|
|
207
|
+
rel = np.clip(zp[rows] / thr, 0, 2) # 1.0 = the level no normal run reaches
|
|
208
|
+
rel[~np.isfinite(rel)] = 0
|
|
209
|
+
curve = (rel.max(1) * 0.5).astype(np.float32) # the report draws its alarm line at 0.5
|
|
210
|
+
heat = np.clip(rel * 0.5 * 255, 0, 255).astype(np.uint8).reshape(len(rows), 16, 16)
|
|
211
|
+
peaks = [dict(step=it["peak_step"], score=it["score"], label=f"Unusual #{n + 1}", box=it["box"])
|
|
212
|
+
for n, it in enumerate(items[:3]) if it["kind"] == "UNUSUAL"]
|
|
213
|
+
return dict(curve=curve, heat=heat, end_score=float(level[np.isfinite(level)].max() / thr) if np.isfinite(level).any() else 0.0,
|
|
214
|
+
end_thr=0.5, mid_thr=0.5, setup_score=0.0, items=items, peaks=sorted(peaks, key=lambda p: p["step"]),
|
|
215
|
+
profile_runs=int(len(prof["good"])))
|