Kavin60606 commited on
Commit
f7d3f89
·
verified ·
1 Parent(s): e9d1713

Upload validate_batch.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. validate_batch.py +381 -0
validate_batch.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Data Validation engine (stage 4) — runs in the retarget venv (numpy<2 + h5py + scipy).
3
+
4
+ Operates on the transformed output (store/<run>/transform/retargeted/*/retargeted.hdf5) which the
5
+ retarget engine already annotates with rich QA (`qa`, `m4`, `ik_errors_*`). This script:
6
+
7
+ mode=qa → per-clip Trajectory Quality & Hygiene report (feasibility + motion + integrity)
8
+ mode=correct → clamp joint limits + smooth vel/acc/jerk → corrected hdf5 (no retime)
9
+ mode=similarity → transformed-ego vs teleop action-distribution distance + score
10
+
11
+ Writes JSON to --out (the API reads it back). Invoked exactly like transform_batch.py.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import glob
17
+ import json
18
+ import os
19
+ import xml.etree.ElementTree as ET
20
+
21
+ import numpy as np
22
+
23
+ # ---- tunable thresholds (placeholder defaults; surfaced in the report so the UI can show them) ----
24
+ TH = {
25
+ "ik_ok_m": 0.02, # per-frame IK error under this (m) = frame "solved"
26
+ "ik_success_min": 0.90, # >= this fraction of frames solved → feasibility OK
27
+ "limit_viol_warn": 0.001, # fraction of (frame×joint) samples out of joint range
28
+ "limit_viol_fail": 0.02,
29
+ "selfcol_min_dist_m": 0.02, # min link clearance (m) below which = collision risk
30
+ "continuity_max_drad": 0.5, # max per-frame per-joint jump (rad) before "teleport"
31
+ "chatter_warn": 2.0, # oscillation rate (from retarget qa) warn level
32
+ }
33
+
34
+ FINGER_NAMES = ("left_finger", "right_finger", "finger")
35
+
36
+
37
+ def joint_limits(xml_path: str) -> dict:
38
+ """Parse <joint name range> from yam_real.xml → {base_name: (lo, hi)} (radians)."""
39
+ out = {}
40
+ try:
41
+ root = ET.parse(xml_path).getroot()
42
+ for j in root.iter("joint"):
43
+ name, rng = j.get("name"), j.get("range")
44
+ if name and rng:
45
+ lo, hi = (float(x) for x in rng.split())
46
+ out[name] = (lo, hi)
47
+ except Exception:
48
+ pass
49
+ return out
50
+
51
+
52
+ def limits_vector(joint_names: list, lims: dict) -> np.ndarray:
53
+ """Build (14, 2) lo/hi aligned to the clip's joint_names (strip R_/L_ prefix → base)."""
54
+ rows = []
55
+ for jn in joint_names:
56
+ base = jn.split("_", 1)[1] if (jn.startswith("R_") or jn.startswith("L_")) else jn
57
+ if base in lims:
58
+ rows.append(lims[base])
59
+ elif any(f in base for f in FINGER_NAMES):
60
+ # fingers: use whichever finger range exists
61
+ fr = next((lims[k] for k in lims if "finger" in k), (-1e9, 1e9))
62
+ rows.append(fr)
63
+ else:
64
+ rows.append((-1e9, 1e9))
65
+ return np.array(rows, dtype=float)
66
+
67
+
68
+ def _attr_json(h, key):
69
+ v = h.attrs.get(key)
70
+ if v is None:
71
+ return {}
72
+ try:
73
+ return json.loads(v if isinstance(v, str) else v.decode())
74
+ except Exception:
75
+ return {}
76
+
77
+
78
+ def qa_one(path: str, lims: dict) -> dict:
79
+ import h5py
80
+ with h5py.File(path, "r") as h:
81
+ jp = np.asarray(h["joint_positions"][:], dtype=float) # (T, 14)
82
+ ts = np.asarray(h["timestamps"][:], dtype=float) if "timestamps" in h else None
83
+ fps = float(h.attrs.get("fps", 30.0))
84
+ jn = json.loads(h.attrs.get("joint_names", "[]"))
85
+ ik_L = np.asarray(h["ik_errors_L"][:], dtype=float) if "ik_errors_L" in h else None
86
+ ik_R = np.asarray(h["ik_errors_R"][:], dtype=float) if "ik_errors_R" in h else None
87
+ qa = _attr_json(h, "qa")
88
+ m4 = _attr_json(h, "m4")
89
+ clip = h.attrs.get("clip", os.path.basename(os.path.dirname(path)))
90
+ task = h.attrs.get("task", "")
91
+
92
+ T = jp.shape[0]
93
+ dt = 1.0 / fps if fps else 1.0 / 30
94
+
95
+ # --- integrity ---
96
+ finite = bool(np.isfinite(jp).all())
97
+ dframe = np.abs(np.diff(jp, axis=0)) if T > 1 else np.zeros((0, jp.shape[1]))
98
+ max_jump = float(dframe.max()) if dframe.size else 0.0
99
+ frame_drops = 0
100
+ if ts is not None and ts.size > 2:
101
+ gaps = np.diff(ts)
102
+ frame_drops = int(np.sum(gaps > 1.8 * np.median(gaps)))
103
+
104
+ # --- feasibility ---
105
+ lo_hi = limits_vector(jn, lims) if jn else np.tile([-1e9, 1e9], (jp.shape[1], 1))
106
+ below = jp < lo_hi[:, 0]
107
+ above = jp > lo_hi[:, 1]
108
+ viol = below | above
109
+ limit_viol_frac = float(viol.mean()) if viol.size else 0.0
110
+ per_joint_viol = viol.mean(axis=0).tolist() if viol.size else []
111
+
112
+ def ik_frac(ik):
113
+ return float(np.mean(ik <= TH["ik_ok_m"])) if ik is not None and ik.size else None
114
+ ik_success = [f for f in (ik_frac(ik_R), ik_frac(ik_L)) if f is not None]
115
+ ik_success_min = min(ik_success) if ik_success else None
116
+
117
+ # self-collision from the retarget qa (min link clearance across arms)
118
+ selfcol_dists = []
119
+ for arm in ("R", "L"):
120
+ d = ((qa.get("arms", {}).get(arm, {}) or {}).get("metrics", {}) or {}).get("selfcol_min_dist")
121
+ if d is not None:
122
+ selfcol_dists.append(float(d))
123
+ selfcol_min = min(selfcol_dists) if selfcol_dists else None
124
+
125
+ # --- motion (finite-diff on joints; peaks; plus retarget smoothness/chatter/saturation) ---
126
+ vel = np.diff(jp, axis=0) / dt if T > 1 else np.zeros((0, jp.shape[1]))
127
+ acc = np.diff(vel, axis=0) / dt if vel.shape[0] > 1 else np.zeros((0, jp.shape[1]))
128
+ jerk = np.diff(acc, axis=0) / dt if acc.shape[0] > 1 else np.zeros((0, jp.shape[1]))
129
+ peak_vel = float(np.abs(vel).max()) if vel.size else 0.0
130
+ peak_acc = float(np.abs(acc).max()) if acc.size else 0.0
131
+ peak_jerk = float(np.abs(jerk).max()) if jerk.size else 0.0
132
+
133
+ def arm_metric(key):
134
+ vals = []
135
+ for arm in ("R", "L"):
136
+ v = ((qa.get("arms", {}).get(arm, {}) or {}).get("metrics", {}) or {}).get(key)
137
+ if v is not None:
138
+ vals.append(float(v))
139
+ return vals
140
+ ldlj = arm_metric("ldlj") # log dimensionless jerk (smoothness; more negative = jerkier)
141
+ chatter = arm_metric("chatter_rate")
142
+ saturation = arm_metric("saturation_frac")
143
+
144
+ # --- verdict: blend our checks with the retarget's own qa_verdict ---
145
+ reasons = []
146
+ verdict = "PASS"
147
+
148
+ def demote(level, why):
149
+ nonlocal verdict
150
+ order = {"PASS": 0, "WARN": 1, "FAIL": 2}
151
+ if order[level] > order[verdict]:
152
+ verdict = level
153
+ reasons.append(why)
154
+
155
+ if not finite:
156
+ demote("FAIL", "non-finite joint values")
157
+ if max_jump > TH["continuity_max_drad"]:
158
+ demote("WARN", f"discontinuity {max_jump:.2f} rad/frame")
159
+ if limit_viol_frac > TH["limit_viol_fail"]:
160
+ demote("FAIL", f"joint-limit violation {limit_viol_frac*100:.1f}%")
161
+ elif limit_viol_frac > TH["limit_viol_warn"]:
162
+ demote("WARN", f"minor limit violation {limit_viol_frac*100:.2f}%")
163
+ if ik_success_min is not None and ik_success_min < TH["ik_success_min"]:
164
+ demote("FAIL" if ik_success_min < 0.8 else "WARN", f"IK solved {ik_success_min*100:.0f}%")
165
+ if selfcol_min is not None and selfcol_min < TH["selfcol_min_dist_m"]:
166
+ demote("WARN", f"self-collision clearance {selfcol_min*100:.1f}cm")
167
+ if chatter and max(chatter) > TH["chatter_warn"]:
168
+ demote("WARN", f"chatter {max(chatter):.1f}")
169
+ rv = qa.get("verdict")
170
+ if rv == "FAIL":
171
+ demote("WARN", "retarget QA flagged FAIL") # respect but don't hard-fail on retarget-only
172
+
173
+ return {
174
+ "clip": clip, "task": task, "n_frames": T, "fps": fps,
175
+ "verdict": verdict, "reasons": reasons,
176
+ "feasibility": {
177
+ "limit_viol_frac": round(limit_viol_frac, 4),
178
+ "per_joint_viol": [round(x, 4) for x in per_joint_viol],
179
+ "ik_success_min": None if ik_success_min is None else round(ik_success_min, 3),
180
+ "selfcol_min_dist_m": None if selfcol_min is None else round(selfcol_min, 4),
181
+ },
182
+ "motion": {
183
+ "peak_vel": round(peak_vel, 3), "peak_acc": round(peak_acc, 2), "peak_jerk": round(peak_jerk, 1),
184
+ "ldlj": [round(x, 2) for x in ldlj], "chatter": [round(x, 2) for x in chatter],
185
+ "saturation": [round(x, 3) for x in saturation],
186
+ },
187
+ "integrity": {"finite": finite, "max_jump_rad": round(max_jump, 3), "frame_drops": frame_drops},
188
+ "retarget_verdict": rv,
189
+ }
190
+
191
+
192
+ def run_qa(retargeted_dir: str, xml_path: str) -> dict:
193
+ lims = joint_limits(xml_path)
194
+ files = sorted(glob.glob(os.path.join(retargeted_dir, "*", "retargeted.hdf5")))
195
+ clips = []
196
+ for f in files:
197
+ try:
198
+ clips.append(qa_one(f, lims))
199
+ except Exception as e:
200
+ clips.append({"clip": os.path.basename(os.path.dirname(f)), "verdict": "FAIL",
201
+ "reasons": [f"read error: {e}"], "error": str(e)})
202
+ counts = {v: sum(1 for c in clips if c.get("verdict") == v) for v in ("PASS", "WARN", "FAIL")}
203
+ certified = [c["clip"] for c in clips if c.get("verdict") in ("PASS", "WARN")]
204
+ return {
205
+ "mode": "qa",
206
+ "n_clips": len(clips),
207
+ "counts": counts,
208
+ "certified": certified,
209
+ "clips": clips,
210
+ "thresholds": TH,
211
+ }
212
+
213
+
214
+ def _peak_jerk(jp: np.ndarray, dt: float) -> float:
215
+ if jp.shape[0] < 4:
216
+ return 0.0
217
+ j = np.diff(jp, n=3, axis=0) / (dt ** 3)
218
+ return float(np.abs(j).max()) if j.size else 0.0
219
+
220
+
221
+ def correct_one(path: str, lims: dict) -> dict:
222
+ """Clamp to joint limits + smooth (Savitzky-Golay) — no retime. Writes corrected.hdf5 alongside."""
223
+ import h5py
224
+ from scipy.signal import savgol_filter
225
+ with h5py.File(path, "r") as h:
226
+ jp = np.asarray(h["joint_positions"][:], dtype=float)
227
+ jn = json.loads(h.attrs.get("joint_names", "[]"))
228
+ fps = float(h.attrs.get("fps", 30.0))
229
+ clip = h.attrs.get("clip", os.path.basename(os.path.dirname(path)))
230
+ keep = {k: np.asarray(h[k][:]) for k in h.keys() if k != "joint_positions"}
231
+ attrs = dict(h.attrs)
232
+ T = jp.shape[0]
233
+ dt = 1.0 / fps if fps else 1.0 / 30
234
+ lo_hi = limits_vector(jn, lims) if jn else np.tile([-1e9, 1e9], (jp.shape[1], 1))
235
+
236
+ before = {"limit_viol_frac": round(float(((jp < lo_hi[:, 0]) | (jp > lo_hi[:, 1])).mean()), 4),
237
+ "peak_jerk": round(_peak_jerk(jp, dt), 1)}
238
+
239
+ clamped = np.clip(jp, lo_hi[:, 0], lo_hi[:, 1])
240
+ win = min(T if T % 2 else T - 1, 7) # odd window ≤ T, ≤ 7
241
+ if win >= 5 and T > win:
242
+ smoothed = savgol_filter(clamped, win, 3, axis=0)
243
+ smoothed = np.clip(smoothed, lo_hi[:, 0], lo_hi[:, 1]) # re-clamp after smoothing
244
+ else:
245
+ smoothed = clamped
246
+
247
+ after = {"limit_viol_frac": round(float(((smoothed < lo_hi[:, 0]) | (smoothed > lo_hi[:, 1])).mean()), 4),
248
+ "peak_jerk": round(_peak_jerk(smoothed, dt), 1)}
249
+
250
+ out_path = os.path.join(os.path.dirname(path), "corrected.hdf5")
251
+ with h5py.File(out_path, "w") as o:
252
+ o.create_dataset("joint_positions", data=smoothed)
253
+ for k, v in keep.items():
254
+ o.create_dataset(k, data=v)
255
+ for k, v in attrs.items():
256
+ o.attrs[k] = v
257
+ o.attrs["corrected"] = True
258
+ o.attrs["smooth_window"] = int(win)
259
+ return {"clip": clip, "before": before, "after": after,
260
+ "jerk_reduction": round(before["peak_jerk"] - after["peak_jerk"], 1),
261
+ "smooth_window": int(win), "output": out_path}
262
+
263
+
264
+ def run_correct(retargeted_dir: str, xml_path: str) -> dict:
265
+ lims = joint_limits(xml_path)
266
+ files = sorted(glob.glob(os.path.join(retargeted_dir, "*", "retargeted.hdf5")))
267
+ clips, tot_j = [], 0.0
268
+ for f in files:
269
+ try:
270
+ c = correct_one(f, lims)
271
+ clips.append(c)
272
+ tot_j += max(0.0, c["jerk_reduction"])
273
+ except Exception as e:
274
+ clips.append({"clip": os.path.basename(os.path.dirname(f)), "error": str(e)})
275
+ ok = [c for c in clips if "error" not in c]
276
+ return {"mode": "correct", "n_clips": len(clips), "corrected": len(ok),
277
+ "mean_jerk_reduction": round(tot_j / max(1, len(ok)), 1), "clips": clips}
278
+
279
+
280
+ def _ego_actions(retargeted_dir: str, max_frames: int = 60000) -> np.ndarray:
281
+ import h5py
282
+ arrs, n = [], 0
283
+ for f in sorted(glob.glob(os.path.join(retargeted_dir, "*", "retargeted.hdf5"))):
284
+ with h5py.File(f, "r") as h:
285
+ a = np.asarray(h["joint_positions"][:], dtype=float)
286
+ arrs.append(a); n += a.shape[0]
287
+ if n >= max_frames:
288
+ break
289
+ return np.concatenate(arrs) if arrs else np.zeros((0, 14))
290
+
291
+
292
+ def _teleop_actions(teleop_dir: str, max_frames: int = 60000) -> np.ndarray:
293
+ import pyarrow.parquet as pq
294
+ arrs, n = [], 0
295
+ for f in sorted(glob.glob(os.path.join(teleop_dir, "**", "*.parquet"), recursive=True)):
296
+ try:
297
+ col = pq.read_table(f, columns=["action"]).column("action").to_pylist()
298
+ except Exception:
299
+ continue
300
+ a = np.array(col, dtype=float)
301
+ if a.ndim != 2:
302
+ continue
303
+ arrs.append(a); n += a.shape[0]
304
+ if n >= max_frames:
305
+ break
306
+ return np.concatenate(arrs) if arrs else np.zeros((0, 14))
307
+
308
+
309
+ def run_similarity(retargeted_dir: str, teleop_dir: str) -> dict:
310
+ """Task-agnostic execution similarity: do transformed-ego action distributions look like
311
+ expert teleop? Per-joint Wasserstein (action + velocity) + range coverage + histograms."""
312
+ from scipy.stats import wasserstein_distance
313
+ ego = _ego_actions(retargeted_dir)
314
+ tel = _teleop_actions(teleop_dir)
315
+ if ego.size == 0 or tel.size == 0:
316
+ return {"mode": "similarity", "error": "no ego or teleop actions",
317
+ "ego_frames": int(ego.shape[0]), "teleop_frames": int(tel.shape[0])}
318
+
319
+ D = min(ego.shape[1], tel.shape[1])
320
+ per_joint = []
321
+ for j in range(D):
322
+ e, t = ego[:, j], tel[:, j]
323
+ s = t.std() or 1.0
324
+ wd = wasserstein_distance(e / s, t / s)
325
+ ev, tv = np.diff(e), np.diff(t)
326
+ sv = tv.std() or 1.0
327
+ wdv = wasserstein_distance(ev / sv, tv / sv) if ev.size and tv.size else 0.0
328
+ lo, hi = np.percentile(t, [1, 99])
329
+ cov = float(np.mean((e >= lo) & (e <= hi)))
330
+ # shared-range histograms for the UI overlay
331
+ rlo, rhi = float(min(e.min(), t.min())), float(max(e.max(), t.max()))
332
+ be, _ = np.histogram(e, bins=20, range=(rlo, rhi), density=True)
333
+ bt, edges = np.histogram(t, bins=20, range=(rlo, rhi), density=True)
334
+ per_joint.append({
335
+ "joint": j, "w_action": round(float(wd), 3), "w_vel": round(float(wdv), 3),
336
+ "sim": round(float(np.exp(-wd)), 3), "coverage": round(cov, 3),
337
+ "hist": {"edges": [round(x, 3) for x in edges.tolist()],
338
+ "ego": [round(x, 3) for x in be.tolist()],
339
+ "teleop": [round(x, 3) for x in bt.tolist()]},
340
+ })
341
+ score = float(np.mean([p["sim"] for p in per_joint]))
342
+ coverage = float(np.mean([p["coverage"] for p in per_joint]))
343
+ verdict = "PASS" if (score >= 0.6 and coverage >= 0.7) else ("WARN" if score >= 0.4 else "FAIL")
344
+ return {"mode": "similarity", "score": round(score, 3), "coverage": round(coverage, 3),
345
+ "verdict": verdict, "ego_frames": int(ego.shape[0]), "teleop_frames": int(tel.shape[0]),
346
+ "n_joints": D, "per_joint": per_joint}
347
+
348
+
349
+ def main():
350
+ ap = argparse.ArgumentParser()
351
+ ap.add_argument("--mode", default="qa", choices=["qa", "correct", "similarity"])
352
+ ap.add_argument("--retargeted", required=True, help="store/<run>/transform/retargeted")
353
+ ap.add_argument("--xml", default=os.path.join(os.path.dirname(__file__), "yam_real.xml"))
354
+ ap.add_argument("--teleop", default="", help="teleop actions .npy (for similarity)")
355
+ ap.add_argument("--thresholds", default="", help="JSON overrides merged into TH")
356
+ ap.add_argument("--out", required=True)
357
+ a = ap.parse_args()
358
+
359
+ if a.thresholds:
360
+ try:
361
+ TH.update({k: float(v) for k, v in json.loads(a.thresholds).items() if k in TH})
362
+ except Exception:
363
+ pass
364
+
365
+ if a.mode == "qa":
366
+ rep = run_qa(a.retargeted, a.xml)
367
+ elif a.mode == "correct":
368
+ rep = run_correct(a.retargeted, a.xml)
369
+ elif a.mode == "similarity":
370
+ rep = run_similarity(a.retargeted, a.teleop)
371
+ else:
372
+ rep = {"mode": a.mode, "error": "unknown mode"}
373
+
374
+ with open(a.out, "w") as f:
375
+ json.dump(rep, f, indent=2)
376
+ print(json.dumps({"mode": a.mode, "n_clips": rep.get("n_clips"), "counts": rep.get("counts"),
377
+ "out": a.out}))
378
+
379
+
380
+ if __name__ == "__main__":
381
+ main()