#!/usr/bin/env python3 """Data Validation engine (stage 4) — runs in the retarget venv (numpy<2 + h5py + scipy). Operates on the transformed output (store//transform/retargeted/*/retargeted.hdf5) which the retarget engine already annotates with rich QA (`qa`, `m4`, `ik_errors_*`). This script: mode=qa → per-clip Trajectory Quality & Hygiene report (feasibility + motion + integrity) mode=correct → clamp joint limits + smooth vel/acc/jerk → corrected hdf5 (no retime) mode=similarity → transformed-ego vs teleop action-distribution distance + score Writes JSON to --out (the API reads it back). Invoked exactly like transform_batch.py. """ from __future__ import annotations import argparse import glob import json import os import xml.etree.ElementTree as ET import numpy as np # ---- tunable thresholds (placeholder defaults; surfaced in the report so the UI can show them) ---- TH = { "ik_ok_m": 0.02, # per-frame IK error under this (m) = frame "solved" "ik_success_min": 0.90, # >= this fraction of frames solved → feasibility OK "limit_viol_warn": 0.001, # fraction of (frame×joint) samples out of joint range "limit_viol_fail": 0.02, "selfcol_min_dist_m": 0.02, # min link clearance (m) below which = collision risk "continuity_max_drad": 0.5, # max per-frame per-joint jump (rad) before "teleport" "chatter_warn": 2.0, # oscillation rate (from retarget qa) warn level } FINGER_NAMES = ("left_finger", "right_finger", "finger") def joint_limits(xml_path: str) -> dict: """Parse from yam_real.xml → {base_name: (lo, hi)} (radians).""" out = {} try: root = ET.parse(xml_path).getroot() for j in root.iter("joint"): name, rng = j.get("name"), j.get("range") if name and rng: lo, hi = (float(x) for x in rng.split()) out[name] = (lo, hi) except Exception: pass return out def limits_vector(joint_names: list, lims: dict) -> np.ndarray: """Build (14, 2) lo/hi aligned to the clip's joint_names (strip R_/L_ prefix → base).""" rows = [] for jn in joint_names: base = jn.split("_", 1)[1] if (jn.startswith("R_") or jn.startswith("L_")) else jn if base in lims: rows.append(lims[base]) elif any(f in base for f in FINGER_NAMES): # fingers: use whichever finger range exists fr = next((lims[k] for k in lims if "finger" in k), (-1e9, 1e9)) rows.append(fr) else: rows.append((-1e9, 1e9)) return np.array(rows, dtype=float) def _attr_json(h, key): v = h.attrs.get(key) if v is None: return {} try: return json.loads(v if isinstance(v, str) else v.decode()) except Exception: return {} def qa_one(path: str, lims: dict) -> dict: import h5py with h5py.File(path, "r") as h: jp = np.asarray(h["joint_positions"][:], dtype=float) # (T, 14) ts = np.asarray(h["timestamps"][:], dtype=float) if "timestamps" in h else None fps = float(h.attrs.get("fps", 30.0)) jn = json.loads(h.attrs.get("joint_names", "[]")) ik_L = np.asarray(h["ik_errors_L"][:], dtype=float) if "ik_errors_L" in h else None ik_R = np.asarray(h["ik_errors_R"][:], dtype=float) if "ik_errors_R" in h else None qa = _attr_json(h, "qa") m4 = _attr_json(h, "m4") clip = h.attrs.get("clip", os.path.basename(os.path.dirname(path))) task = h.attrs.get("task", "") T = jp.shape[0] dt = 1.0 / fps if fps else 1.0 / 30 # --- integrity --- finite = bool(np.isfinite(jp).all()) dframe = np.abs(np.diff(jp, axis=0)) if T > 1 else np.zeros((0, jp.shape[1])) max_jump = float(dframe.max()) if dframe.size else 0.0 frame_drops = 0 if ts is not None and ts.size > 2: gaps = np.diff(ts) frame_drops = int(np.sum(gaps > 1.8 * np.median(gaps))) # --- feasibility --- lo_hi = limits_vector(jn, lims) if jn else np.tile([-1e9, 1e9], (jp.shape[1], 1)) below = jp < lo_hi[:, 0] above = jp > lo_hi[:, 1] viol = below | above limit_viol_frac = float(viol.mean()) if viol.size else 0.0 per_joint_viol = viol.mean(axis=0).tolist() if viol.size else [] def ik_frac(ik): return float(np.mean(ik <= TH["ik_ok_m"])) if ik is not None and ik.size else None ik_success = [f for f in (ik_frac(ik_R), ik_frac(ik_L)) if f is not None] ik_success_min = min(ik_success) if ik_success else None # self-collision from the retarget qa (min link clearance across arms) selfcol_dists = [] for arm in ("R", "L"): d = ((qa.get("arms", {}).get(arm, {}) or {}).get("metrics", {}) or {}).get("selfcol_min_dist") if d is not None: selfcol_dists.append(float(d)) selfcol_min = min(selfcol_dists) if selfcol_dists else None # --- motion (finite-diff on joints; peaks; plus retarget smoothness/chatter/saturation) --- vel = np.diff(jp, axis=0) / dt if T > 1 else np.zeros((0, jp.shape[1])) acc = np.diff(vel, axis=0) / dt if vel.shape[0] > 1 else np.zeros((0, jp.shape[1])) jerk = np.diff(acc, axis=0) / dt if acc.shape[0] > 1 else np.zeros((0, jp.shape[1])) peak_vel = float(np.abs(vel).max()) if vel.size else 0.0 peak_acc = float(np.abs(acc).max()) if acc.size else 0.0 peak_jerk = float(np.abs(jerk).max()) if jerk.size else 0.0 def arm_metric(key): vals = [] for arm in ("R", "L"): v = ((qa.get("arms", {}).get(arm, {}) or {}).get("metrics", {}) or {}).get(key) if v is not None: vals.append(float(v)) return vals ldlj = arm_metric("ldlj") # log dimensionless jerk (smoothness; more negative = jerkier) chatter = arm_metric("chatter_rate") saturation = arm_metric("saturation_frac") # --- verdict: blend our checks with the retarget's own qa_verdict --- reasons = [] verdict = "PASS" def demote(level, why): nonlocal verdict order = {"PASS": 0, "WARN": 1, "FAIL": 2} if order[level] > order[verdict]: verdict = level reasons.append(why) if not finite: demote("FAIL", "non-finite joint values") if max_jump > TH["continuity_max_drad"]: demote("WARN", f"discontinuity {max_jump:.2f} rad/frame") if limit_viol_frac > TH["limit_viol_fail"]: demote("FAIL", f"joint-limit violation {limit_viol_frac*100:.1f}%") elif limit_viol_frac > TH["limit_viol_warn"]: demote("WARN", f"minor limit violation {limit_viol_frac*100:.2f}%") if ik_success_min is not None and ik_success_min < TH["ik_success_min"]: demote("FAIL" if ik_success_min < 0.8 else "WARN", f"IK solved {ik_success_min*100:.0f}%") if selfcol_min is not None and selfcol_min < TH["selfcol_min_dist_m"]: demote("WARN", f"self-collision clearance {selfcol_min*100:.1f}cm") if chatter and max(chatter) > TH["chatter_warn"]: demote("WARN", f"chatter {max(chatter):.1f}") rv = qa.get("verdict") if rv == "FAIL": demote("WARN", "retarget QA flagged FAIL") # respect but don't hard-fail on retarget-only return { "clip": clip, "task": task, "n_frames": T, "fps": fps, "verdict": verdict, "reasons": reasons, "feasibility": { "limit_viol_frac": round(limit_viol_frac, 4), "per_joint_viol": [round(x, 4) for x in per_joint_viol], "ik_success_min": None if ik_success_min is None else round(ik_success_min, 3), "selfcol_min_dist_m": None if selfcol_min is None else round(selfcol_min, 4), }, "motion": { "peak_vel": round(peak_vel, 3), "peak_acc": round(peak_acc, 2), "peak_jerk": round(peak_jerk, 1), "ldlj": [round(x, 2) for x in ldlj], "chatter": [round(x, 2) for x in chatter], "saturation": [round(x, 3) for x in saturation], }, "integrity": {"finite": finite, "max_jump_rad": round(max_jump, 3), "frame_drops": frame_drops}, "retarget_verdict": rv, } def run_qa(retargeted_dir: str, xml_path: str) -> dict: lims = joint_limits(xml_path) files = sorted(glob.glob(os.path.join(retargeted_dir, "*", "retargeted.hdf5"))) clips = [] for f in files: try: clips.append(qa_one(f, lims)) except Exception as e: clips.append({"clip": os.path.basename(os.path.dirname(f)), "verdict": "FAIL", "reasons": [f"read error: {e}"], "error": str(e)}) counts = {v: sum(1 for c in clips if c.get("verdict") == v) for v in ("PASS", "WARN", "FAIL")} certified = [c["clip"] for c in clips if c.get("verdict") in ("PASS", "WARN")] return { "mode": "qa", "n_clips": len(clips), "counts": counts, "certified": certified, "clips": clips, "thresholds": TH, } def _peak_jerk(jp: np.ndarray, dt: float) -> float: if jp.shape[0] < 4: return 0.0 j = np.diff(jp, n=3, axis=0) / (dt ** 3) return float(np.abs(j).max()) if j.size else 0.0 def correct_one(path: str, lims: dict) -> dict: """Clamp to joint limits + smooth (Savitzky-Golay) — no retime. Writes corrected.hdf5 alongside.""" import h5py from scipy.signal import savgol_filter with h5py.File(path, "r") as h: jp = np.asarray(h["joint_positions"][:], dtype=float) jn = json.loads(h.attrs.get("joint_names", "[]")) fps = float(h.attrs.get("fps", 30.0)) clip = h.attrs.get("clip", os.path.basename(os.path.dirname(path))) keep = {k: np.asarray(h[k][:]) for k in h.keys() if k != "joint_positions"} attrs = dict(h.attrs) T = jp.shape[0] dt = 1.0 / fps if fps else 1.0 / 30 lo_hi = limits_vector(jn, lims) if jn else np.tile([-1e9, 1e9], (jp.shape[1], 1)) before = {"limit_viol_frac": round(float(((jp < lo_hi[:, 0]) | (jp > lo_hi[:, 1])).mean()), 4), "peak_jerk": round(_peak_jerk(jp, dt), 1)} clamped = np.clip(jp, lo_hi[:, 0], lo_hi[:, 1]) win = min(T if T % 2 else T - 1, 7) # odd window ≤ T, ≤ 7 if win >= 5 and T > win: smoothed = savgol_filter(clamped, win, 3, axis=0) smoothed = np.clip(smoothed, lo_hi[:, 0], lo_hi[:, 1]) # re-clamp after smoothing else: smoothed = clamped after = {"limit_viol_frac": round(float(((smoothed < lo_hi[:, 0]) | (smoothed > lo_hi[:, 1])).mean()), 4), "peak_jerk": round(_peak_jerk(smoothed, dt), 1)} out_path = os.path.join(os.path.dirname(path), "corrected.hdf5") with h5py.File(out_path, "w") as o: o.create_dataset("joint_positions", data=smoothed) for k, v in keep.items(): o.create_dataset(k, data=v) for k, v in attrs.items(): o.attrs[k] = v o.attrs["corrected"] = True o.attrs["smooth_window"] = int(win) return {"clip": clip, "before": before, "after": after, "jerk_reduction": round(before["peak_jerk"] - after["peak_jerk"], 1), "smooth_window": int(win), "output": out_path} def run_correct(retargeted_dir: str, xml_path: str) -> dict: lims = joint_limits(xml_path) files = sorted(glob.glob(os.path.join(retargeted_dir, "*", "retargeted.hdf5"))) clips, tot_j = [], 0.0 for f in files: try: c = correct_one(f, lims) clips.append(c) tot_j += max(0.0, c["jerk_reduction"]) except Exception as e: clips.append({"clip": os.path.basename(os.path.dirname(f)), "error": str(e)}) ok = [c for c in clips if "error" not in c] return {"mode": "correct", "n_clips": len(clips), "corrected": len(ok), "mean_jerk_reduction": round(tot_j / max(1, len(ok)), 1), "clips": clips} def _ego_actions(retargeted_dir: str, max_frames: int = 60000) -> np.ndarray: import h5py arrs, n = [], 0 for f in sorted(glob.glob(os.path.join(retargeted_dir, "*", "retargeted.hdf5"))): with h5py.File(f, "r") as h: a = np.asarray(h["joint_positions"][:], dtype=float) arrs.append(a); n += a.shape[0] if n >= max_frames: break return np.concatenate(arrs) if arrs else np.zeros((0, 14)) def _teleop_actions(teleop_dir: str, max_frames: int = 60000) -> np.ndarray: import pyarrow.parquet as pq arrs, n = [], 0 for f in sorted(glob.glob(os.path.join(teleop_dir, "**", "*.parquet"), recursive=True)): try: col = pq.read_table(f, columns=["action"]).column("action").to_pylist() except Exception: continue a = np.array(col, dtype=float) if a.ndim != 2: continue arrs.append(a); n += a.shape[0] if n >= max_frames: break return np.concatenate(arrs) if arrs else np.zeros((0, 14)) def run_similarity(retargeted_dir: str, teleop_dir: str) -> dict: """Task-agnostic execution similarity: do transformed-ego action distributions look like expert teleop? Per-joint Wasserstein (action + velocity) + range coverage + histograms.""" from scipy.stats import wasserstein_distance ego = _ego_actions(retargeted_dir) tel = _teleop_actions(teleop_dir) if ego.size == 0 or tel.size == 0: return {"mode": "similarity", "error": "no ego or teleop actions", "ego_frames": int(ego.shape[0]), "teleop_frames": int(tel.shape[0])} D = min(ego.shape[1], tel.shape[1]) per_joint = [] for j in range(D): e, t = ego[:, j], tel[:, j] s = t.std() or 1.0 wd = wasserstein_distance(e / s, t / s) ev, tv = np.diff(e), np.diff(t) sv = tv.std() or 1.0 wdv = wasserstein_distance(ev / sv, tv / sv) if ev.size and tv.size else 0.0 lo, hi = np.percentile(t, [1, 99]) cov = float(np.mean((e >= lo) & (e <= hi))) # shared-range histograms for the UI overlay rlo, rhi = float(min(e.min(), t.min())), float(max(e.max(), t.max())) be, _ = np.histogram(e, bins=20, range=(rlo, rhi), density=True) bt, edges = np.histogram(t, bins=20, range=(rlo, rhi), density=True) per_joint.append({ "joint": j, "w_action": round(float(wd), 3), "w_vel": round(float(wdv), 3), "sim": round(float(np.exp(-wd)), 3), "coverage": round(cov, 3), "hist": {"edges": [round(x, 3) for x in edges.tolist()], "ego": [round(x, 3) for x in be.tolist()], "teleop": [round(x, 3) for x in bt.tolist()]}, }) score = float(np.mean([p["sim"] for p in per_joint])) coverage = float(np.mean([p["coverage"] for p in per_joint])) verdict = "PASS" if (score >= 0.6 and coverage >= 0.7) else ("WARN" if score >= 0.4 else "FAIL") return {"mode": "similarity", "score": round(score, 3), "coverage": round(coverage, 3), "verdict": verdict, "ego_frames": int(ego.shape[0]), "teleop_frames": int(tel.shape[0]), "n_joints": D, "per_joint": per_joint} def main(): ap = argparse.ArgumentParser() ap.add_argument("--mode", default="qa", choices=["qa", "correct", "similarity"]) ap.add_argument("--retargeted", required=True, help="store//transform/retargeted") ap.add_argument("--xml", default=os.path.join(os.path.dirname(__file__), "yam_real.xml")) ap.add_argument("--teleop", default="", help="teleop actions .npy (for similarity)") ap.add_argument("--thresholds", default="", help="JSON overrides merged into TH") ap.add_argument("--out", required=True) a = ap.parse_args() if a.thresholds: try: TH.update({k: float(v) for k, v in json.loads(a.thresholds).items() if k in TH}) except Exception: pass if a.mode == "qa": rep = run_qa(a.retargeted, a.xml) elif a.mode == "correct": rep = run_correct(a.retargeted, a.xml) elif a.mode == "similarity": rep = run_similarity(a.retargeted, a.teleop) else: rep = {"mode": a.mode, "error": "unknown mode"} with open(a.out, "w") as f: json.dump(rep, f, indent=2) print(json.dumps({"mode": a.mode, "n_clips": rep.get("n_clips"), "counts": rep.get("counts"), "out": a.out})) if __name__ == "__main__": main()