"""Per-episode calibration refinement v2 (DIAGNOSIS P1.1 timing, P1.2 extrinsics, P1.3 objective, P1.5 wrist) -> data//calib_refined_v2.json (interface in README / render_episode.py). Stages (all objectives at half the MP4 resolution, dutils.scale_K convention, see refine_v2_lib): 0. step selection per exterior camera: out/gt//steps.json when GT masks exist, else the in-view (render area >= 5 %) / moving (EE speed >= 0.1 m/s) selector, spread over the episode. 1. extrinsic stage per exterior camera (round 1): candidate base poses = superset pose (+ same-day GT-neighbour pose(s) of the same serial and the h5 pose when the superset source is 'Pred' / missing; session delta from calib/session_deltas.json as start when present); per candidate a coarse Nelder-Mead over (rx, ry, tx, ty) with an explicit 0.5 deg / 5 mm simplex; every candidate within CAND_FINE_RATIO (1.5x) of the best coarse loss (max 2) -> 6-DoF NM (5 mm / 0.5 deg simplex), best final loss wins (official pose on a 3 % tie) -> polish (1 mm / 0.1 deg). Soft prior on the camera-frame delta: GT source 2 cm / 2 deg, Pred 8 cm / 5 deg (weight PRIOR_FRAC x start metric); hard bound 15 cm / 15 deg -> 'failed'. 2. time stage: one offset d shared by both exterior cameras, total = 37 ms + d, |d| <= 70 ms, 5-ms grid of the per-camera, median-normalised data term + Gaussian prior (sigma 25 ms), parabolic vertex; sweep classified V / flat / edge / multi (flat / edge -> prior, d = 0). 3. rounds: ext -> time -> ext -> time (-> ext polish when the time moved). 4. wrist stage: 6-DoF camera-frame delta on top of the h5 hand-eye, gripper-only render vs wrist GT (fallback: dark pixels + edge chamfer with a held-object guard), steps spanning open and closed gripper. Flip test (2026-10-17b): starts = identity, 180-deg roll, roll +- the 63 mm stereo baseline along camera x; every start with >= 3 supporting steps (IoU >= GT_SUPPORT_IOU) is refined by NM on ITS OWN supporting steps and the flipped hypothesis wins only when its post-NM mean IoU beats the identity one by WRIST_FLIP_MARGIN_IOU (wrist GT masks are render-seeded, so a flipped session carries both kinds of masks). Rescue pass: with < 8 scorable steps or no open/closed diversity, the non-usable GT steps (SAM3 status failed/marginal, gated against the DEFAULT render) are scored at the solution and adopted when IoU >= GT_RESCUE_IOU, then the fit is repeated. wrist_delta is written as the TOTAL correction (delta @ flip start) and wrist_flipped as a flag. GT objective (ext + wrist): far-trimmed IoU -- GT pixels farther than --gt-trim-far px (default 60 at 1280x720) from the rendered silhouette are dropped from the union (cables / blobs / held objects); identical to the plain IoU when the GT has no far pixels. Quality status (gt mode) is robust to inconsistent GT steps: judged on the median step IoU when >= 60 % of the steps have IoU >= 0.5, or on precision >= 0.85 + r2g <= 1.5 eval px when the GT far-fraction is >= 0.05; cameras with iou_after < 0.8, r2g_after > 3 eval px and a flat time sweep get the note 'nonrigid_suspect'. Never reads calib_refined.json (v1) or an existing v2 file; always starts from the base poses. Usage: python scripts/refine_v2.py [--no-wrist] [--force] [--workers 8] [--no-gt] [--supersample 1] [--rounds 2] [--time-bound 70] [--gt-trim-far 60] [--eval-benchmark] [--log-dir out/refine_v2] Runs the pool of render workers (spawn); use sbatch (scripts/sbatch_refine_v2.sh), not the login node. """ import argparse import json import os import sys import time from pathlib import Path import cv2 import h5py import numpy as np HERE = Path(__file__).resolve().parent if str(HERE) not in sys.path: sys.path.insert(0, str(HERE)) import refine_v2_lib as L # noqa: E402 import render_episode as RE # noqa: E402 try: # the at-scale GT selector (same in-view / speed rule); optional import gt_masks_scale as GMS # noqa: E402 except Exception: # noqa: BLE001 GMS = None from dutils import ROOT, mat_to_pose6, pose6_to_mat # noqa: E402 cv2.setNumThreads(1) log = L.log IDX_COARSE = [3, 4, 0, 1] # rx, ry, tx, ty SC_COARSE = [np.deg2rad(0.5), np.deg2rad(0.5), 0.005, 0.005] SC_COARSE_BIG = [np.deg2rad(2.0), np.deg2rad(2.0), 0.02, 0.02] IDX_ALL = [0, 1, 2, 3, 4, 5] SC_FINE = [0.005] * 3 + [np.deg2rad(0.5)] * 3 SC_POLISH = [0.001] * 3 + [np.deg2rad(0.1)] * 3 SC_ROUND2 = [0.002] * 3 + [np.deg2rad(0.2)] * 3 SC_WRIST = [0.005] * 3 + [np.deg2rad(1.0)] * 3 SC_WRIST_POLISH = [0.001] * 3 + [np.deg2rad(0.2)] * 3 def _f(v, nd=3): return None if v is None or (isinstance(v, float) and not np.isfinite(v)) else round(float(v), nd) def benchmark_exclusions(uuid, sample_json=None, margin=1): """Frames of out/diag/sample.json (the fixed SAM3 benchmark) +- margin for this episode -> set().""" p = Path(sample_json) if sample_json else ROOT / "out/diag/sample.json" try: d = json.load(open(p)) except (OSError, ValueError): return set() out = set() for e in d.get("episodes", []): if e.get("uuid") == uuid: for f in e.get("frames", []): for k in range(-margin, margin + 1): out.add(int(f) + k) return out # ----------------------------------------------------------------------------- objective wrapper class ExtObjective: """Camera-frame delta x (6) on top of T_base (base->cam): T = pose6_to_mat(x) @ T_base.""" def __init__(self, pool, serial, steps, dt_total, T_base, mode, opts, sigma, prior_w, hard=(L.EXT_HARD_T_M, L.EXT_HARD_R_RAD)): self.pool, self.serial, self.steps = pool, str(serial), list(steps) self.dt_total, self.T_base, self.mode, self.opts = float(dt_total), np.asarray(T_base), mode, dict(opts) self.sigma, self.prior_w, self.hard = sigma, float(prior_w), hard self.nfev = 0 self.penalty = None # set by fix_steps(): invalid steps then count with this loss def data(self, x, steps=None, dt_total=None, penalty="default"): T = pose6_to_mat(x) @ self.T_base res = self.pool.evaluate(self.serial, self.steps if steps is None else steps, self.dt_total if dt_total is None else dt_total, T=T, mode=self.mode, opts=self.opts) return L.aggregate(res, penalty=self.penalty if penalty == "default" else penalty), res def fix_steps(self, x): """Restrict the step set to the steps valid at x and penalise later drop-outs. -> (agg, n_dropped)""" agg, res = self.data(x, penalty=None) valid = [r["step"] for r in res if r.get("valid")] n_drop = len(self.steps) - len(valid) if valid: self.steps = valid self.penalty = L.invalid_penalty(self.mode, self.opts) return agg, n_drop def prior(self, x): t = float(np.linalg.norm(x[:3])) r = L.rot_angle(x[3:]) return self.prior_w * 0.5 * ((t / self.sigma[0]) ** 2 + (r / self.sigma[1]) ** 2) def total(self, x): self.nfev += 1 if np.linalg.norm(x[:3]) > self.hard[0] or L.rot_angle(x[3:]) > self.hard[1]: return L.BIG agg, _ = self.data(x) if agg is None or agg["n_valid"] < L.MIN_VALID_STEPS: return L.BIG return agg["loss"] + self.prior(x) class WristObjective: """Camera-frame delta x on top of the flip-test start F: D_total = pose6_to_mat(x) @ F.""" def __init__(self, pool, serial, steps, dt_total, F, mode, opts, sigma=L.WRIST_PRIOR_SIGMA, prior_w=0.0, hard=(L.WRIST_HARD_T_M, L.WRIST_HARD_R_RAD)): self.pool, self.serial, self.steps = pool, str(serial), list(steps) self.dt_total, self.F, self.mode, self.opts = float(dt_total), np.asarray(F), mode, dict(opts) self.sigma, self.prior_w, self.hard = sigma, float(prior_w), hard self.nfev = 0 self.penalty = L.invalid_penalty(mode, opts) def data(self, x, penalty="default"): D = pose6_to_mat(x) @ self.F res = self.pool.evaluate(self.serial, self.steps, self.dt_total, T=None, D=D, mode=self.mode, opts=self.opts) return L.aggregate(res, penalty=self.penalty if penalty == "default" else penalty), res def prior(self, x): t = float(np.linalg.norm(x[:3])) r = L.rot_angle(x[3:]) return self.prior_w * 0.5 * ((t / self.sigma[0]) ** 2 + (r / self.sigma[1]) ** 2) def total(self, x): self.nfev += 1 if np.linalg.norm(x[:3]) > self.hard[0] or L.rot_angle(x[3:]) > self.hard[1]: return L.BIG agg, _ = self.data(x) if agg is None or agg["n_valid"] < L.MIN_VALID_STEPS: return L.BIG return agg["loss"] + self.prior(x) # ----------------------------------------------------------------------------- refiner class Refiner: def __init__(self, ep_dir, args): self.args = args self.ep_dir = Path(ep_dir).resolve() self.meta = json.load(open(self.ep_dir / "metadata.json")) self.uuid = self.meta["uuid"] self.out_path = self.ep_dir / "calib_refined_v2.json" self.log_dir = Path(args.log_dir) if args.log_dir else ROOT / "out/refine_v2" self.log_dir.mkdir(parents=True, exist_ok=True) self.debug = dict(version=L.VERSION, uuid=self.uuid, args=vars(args), stages=[]) self.t0 = time.time() self.grays = {} # serial -> {step: gray_small} self.pushed = {} # serial -> set(steps) self.gt_small = {} # serial -> {step: bool mask} (GT mode) tf = float(getattr(args, "gt_trim_far", L.GT_TRIM_FAR_FULL) or 0.0) self.trim_far_eval = tf * L.EVAL_SCALE if tf > 0 else 0.0 # eval-res px # -- helpers ------------------------------------------------------------------------ def stage(self, name, **kw): kw["t_s"] = round(time.time() - self.t0, 1) self.debug["stages"].append(dict(name=name, **kw)) def ensure_frames(self, serial, steps): have = self.grays.setdefault(serial, {}) missing = [int(s) for s in steps if int(s) not in have] if not missing: return video = self.ep_dir / f"recordings/MP4/{serial}.mp4" wh_eval = self.cams[serial]["wh_eval"] t = time.time() got, n_dec = L.decode_frames_small(video, missing, wh_eval) have.update(got) lost = [s for s in missing if s not in got] log(f" decoded {len(got)} frames of {serial} ({n_dec} read, {time.time() - t:.1f} s)" + (f"; MISSING steps {lost[:8]}{'...' if len(lost) > 8 else ''}" if lost else "")) def push(self, serial, steps, gt=False): cam = self.cams[serial] self.ensure_frames(serial, steps) done = self.pushed.setdefault(serial, set()) fds = {} for s in steps: s = int(s) if s in done or s not in self.grays[serial]: continue gts = None if gt: gts = self.gt_small.get(serial, {}).get(s) if gts is None: gts = L.load_gt_small(L.gt_mask_path(self.uuid, serial, s, self.args.gt_root), cam["wh_eval"]) if gts is not None: self.gt_small.setdefault(serial, {})[s] = gts fds[s] = L.build_frame_data(self.grays[serial][s], gts) done.add(s) if fds: self.pool.push_frames(serial, fds) return [int(s) for s in steps if int(s) in self.grays[serial]] def opts_for(self, cam, mode, coarse=False): o = dict(supersample=int(self.args.supersample), min_edge=int(cam["min_edge"]), band=L.BAND_PX, lam=L.LAMBDA_R2G) o["clip"] = L.COARSE_CLIP_PX if coarse else L.BAND_PX if mode == "gt": o["trim_far"] = float(self.trim_far_eval) return o # -- candidates --------------------------------------------------------------------- def base_candidates(self, serial): base = np.asarray(self.sess.ext_base_pose6[serial], dtype=float) src = self.sess.ext_base_source[serial] prior_kind = "GT" if src == "superset-GT" else "Pred" x0, tag = np.zeros(6), src sd = L.load_session_delta(self.uuid, serial) if sd is not None: dt_, dr_ = L.pose_dist(sd["official_pose6"], base) if dt_ < 0.001 and dr_ < np.deg2rad(0.1) and sd.get("delta") is not None: x0 = np.asarray(sd["delta"], dtype=float) tag = f"session:{sd['session_id']}" log(f" {serial}: session delta start from {tag} (|t| {np.linalg.norm(x0[:3]) * 1e3:.1f} mm)") cands = [dict(pose6=base, source=tag, x0=x0, prior=prior_kind, kind="official")] if prior_kind == "Pred": for nb in L.gt_neighbor_candidates(self.uuid, serial): cands.append(dict(pose6=np.asarray(nb["pose6"], dtype=float), source=f"gt_neighbor:{nb['uuid']}", x0=np.zeros(6), prior="Pred", kind="gt_neighbor", note=f"{nb['hours']:.1f} h away, {nb['n_same_pose']} same-pose eps that day")) if serial in self.sess.h5_ext and not src.startswith("h5"): cands.append(dict(pose6=np.asarray(self.sess._h5_base_pose6(serial), dtype=float), source="h5", x0=np.zeros(6), prior="Pred", kind="h5")) # dedupe (3 mm / 0.3 deg) out = [] for c in cands: if all(max(L.pose_dist(c["pose6"], o["pose6"])[0] / 0.003, L.pose_dist(c["pose6"], o["pose6"])[1] / np.deg2rad(0.3)) >= 1.0 for o in out): out.append(c) else: log(f" {serial}: candidate {c['source']} duplicates an earlier pose; dropped") return out def rescue_candidates(self, serial, existing): """GT-neighbour + h5 poses for a camera whose official pose (any source) leaves the robot unscorable in every selected step (gross official calibration, e.g. REAL+4f8ca688 05-27, RAIL 24259877 06-26).""" out = [] have = [np.asarray(c["pose6"], dtype=float) for c in existing] for nb in L.gt_neighbor_candidates(self.uuid, serial): out.append(dict(pose6=np.asarray(nb["pose6"], dtype=float), source=f"gt_neighbor:{nb['uuid']}", x0=np.zeros(6), prior="Pred", kind="gt_neighbor", note=f"rescue; {nb['hours']:.1f} h away, {nb['n_same_pose']} same-pose eps")) if serial in self.sess.h5_ext: out.append(dict(pose6=np.asarray(self.sess._h5_base_pose6(serial), dtype=float), source="h5", x0=np.zeros(6), prior="Pred", kind="h5", note="rescue")) keep = [] for c in out: if all(max(L.pose_dist(c["pose6"], o)[0] / 0.003, L.pose_dist(c["pose6"], o)[1] / np.deg2rad(0.3)) >= 1.0 for o in have): keep.append(c) have.append(c["pose6"]) log(f" {serial}: official pose unscorable -> rescue candidates {[c['source'] for c in keep]}") return keep # -- step selection ----------------------------------------------------------------- def gt_steps_for(self, serial, n_max, wrist=False): lst = L.usable_gt_steps(self.uuid, serial, self.args.gt_root) lst = [(s, r) for s, r in lst if 0 <= s < self.sess.n - 1] if not lst: return [], {} if wrist: g = self.sess.gs steps = [s for s, _ in lst] if len(steps) > n_max: lo, hi = 2, self.sess.n - 3 half = n_max // 2 op = [s for s in steps if g[s] < 0.3] cl = [s for s in steps if g[s] > 0.5] sel = L.select_spread(op, {s: 1.0 for s in op}, half, lo, hi) sel += L.select_spread(cl, {s: 1.0 for s in cl}, n_max - len(sel), lo, hi) rest = [s for s in steps if s not in sel] sel += L.select_spread(rest, {s: 1.0 for s in rest}, n_max - len(sel), lo, hi) steps = sorted(set(sel)) return steps, dict(n_gt_usable=len(lst), n_selected=len(steps)) # exterior: prefer moving steps, spread steps = [s for s, _ in lst] if len(steps) > n_max: lo, hi = 2, self.sess.n - 3 mov = [s for s in steps if self.speed[s] >= L.MIN_SPEED_MPS] sel = L.select_spread(mov, {s: float(self.speed[s]) for s in mov}, n_max, lo, hi) rest = [s for s in steps if s not in sel] sel += L.select_spread(rest, {s: float(self.speed[s]) for s in rest}, n_max - len(sel), lo, hi) steps = sorted(set(sel)) return steps, dict(n_gt_usable=len(lst), n_selected=len(steps), n_selected_moving=int(sum(self.speed[s] >= L.MIN_SPEED_MPS for s in steps))) def probe_steps(self): n = self.sess.n hi = min(n - 3, self.n_frames_min - 1) if self.n_frames_min else n - 3 stride = max(1, (hi - 2) // 200) return list(range(2, hi + 1, stride)) def gms_steps(self): """Steps from scripts/gt_masks_scale.select_steps (official pose, default time) for every camera; {} when the module is unavailable or fails.""" if getattr(self, "_gms_steps", None) is None: self._gms_steps, self._gms_meta = {}, {} if GMS is not None and not self.args.local_selector: t = time.time() try: steps, recs, meta = GMS.select_steps_detailed(str(self.ep_dir), self.sess, exclude=self.exclude) self._gms_steps = {str(k): [int(v) for v in vals] for k, vals in steps.items()} self._gms_meta = {str(k): dict(v, roles={r["step"]: r.get("role") for r in recs.get(k, [])}) for k, v in (meta.get("serials") or {}).items()} log(f" gt_masks_scale.select_steps: {{{', '.join(f'{k}: {len(v)}' for k, v in self._gms_steps.items())}}} " f"({time.time() - t:.1f} s)") except Exception as e: # noqa: BLE001 log(f" gt_masks_scale.select_steps failed ({e!r}); local selector") return self._gms_steps def canny_steps_for(self, serial, T_base, official=False): cam = self.cams[serial] if official: g = self.gms_steps() if g.get(serial): m = dict(self._gms_meta.get(serial, {})) roles = m.pop("roles", {}) steps = [int(s) for s in g[serial] if 0 <= s < self.sess.n - 1] info = dict(selector="gt_masks_scale", n_selected=len(steps), n_selected_moving=int(sum(roles.get(s) == "moving" for s in steps)), flags=m.get("flags"), n_inview=m.get("n_inview"), n_inview_moving=m.get("n_inview_moving")) return steps, info probe = [s for s in self.probe_steps() if s not in self.exclude] ar = self.pool.areas(serial, probe, L.TIME_DEFAULT_MS, T_base) npx = cam["wh_eval"][0] * cam["wh_eval"][1] area_frac = {s: a[0] / npx for s, a in ar.items()} ring = {s: a[1] for s, a in ar.items()} steps, info = L.select_ext_steps(area_frac, self.speed, self.args.n_steps, self.sess.n) info["selector"] = "local" info["n_ring_ok"] = int(sum(1 for s in steps if ring[s] >= cam["min_edge"])) info["area_frac_sel"] = [round(area_frac[s], 3) for s in steps] return steps, info # -- exterior stage ------------------------------------------------------------------- def fit_camera_round1(self, serial): cam = self.cams[serial] cands = self.base_candidates(serial) log(f"cam {serial} [{cam['source']}] candidates: {[c['source'] for c in cands]}") gt_steps, gt_info = ([], {}) if self.gt_mode: gt_steps, gt_info = self.gt_steps_for(serial, self.args.n_steps) if len(gt_steps) < 4: log(f" {serial}: only {len(gt_steps)} usable GT steps -> Canny objective for this camera") gt_steps = [] rescued = False ci = 0 while ci < len(cands): c = cands[ci] ci += 1 T_base = np.linalg.inv(pose6_to_mat(c["pose6"])) c["T_base"] = T_base if gt_steps: steps, info, mode = list(gt_steps), dict(gt_info), "gt" else: steps, info = self.canny_steps_for(serial, T_base, official=(c["kind"] == "official")) mode = "canny" c["steps"], c["sel_info"], c["mode"] = steps, info, mode if not steps: c["infeasible"] = "no in-view steps at this base pose" log(f" cand {c['source']}: {c['infeasible']} ({info})") if not rescued and ci == len(cands) and not any("x1" in k for k in cands): rescued = True cands += self.rescue_candidates(serial, cands) continue steps = self.push(serial, steps, gt=(mode == "gt")) c["steps"] = steps sig = L.EXT_PRIOR_SIGMA[c["prior"]] obj = ExtObjective(self.pool, serial, steps, self.dt_total, T_base, mode, self.opts_for(cam, mode, coarse=True), sig, 0.0) agg0, res0 = obj.data(c["x0"], penalty=None) n_strict = agg0["n_valid"] if agg0 else 0 relaxed = False if mode == "canny": # min-edge ladder: first rung at which >= 50 % of the selected steps are scorable scale_px = cam["wh_eval"][0] * cam["wh_eval"][1] / L.REF_EVAL_PX for rung in L.MIN_EDGE_LADDER[1:]: if agg0 is not None and agg0["n_valid"] >= max(L.MIN_VALID_STEPS, len(steps) // 2): break relaxed = True obj.opts["min_edge"] = int(round(rung * scale_px)) agg0, res0 = obj.data(c["x0"], penalty=None) if agg0 is None or agg0["n_valid"] < L.MIN_VALID_STEPS: c["infeasible"] = f"no scorable steps at start ({agg0})" log(f" cand {c['source']}: {c['infeasible']}; why={[r.get('why') for r in res0][:6]}") if not rescued and ci == len(cands) and not any("x1" in k for k in cands): rescued = True cands += self.rescue_candidates(serial, cands) continue agg0, n_drop = obj.fix_steps(c["x0"]) # steps valid at the start; later drop-outs are penalised c["relaxed_min_edge"] = relaxed c["n_valid_strict"] = n_strict c["n_dropped_at_start"] = n_drop c["steps"] = list(obj.steps) steps = c["steps"] c["min_edge_used"] = obj.opts["min_edge"] obj.prior_w = L.PRIOR_FRAC * max(agg0["loss"], L.PRIOR_FLOOR[mode]) x1, f1, nfev1, msg1 = L.run_nm(obj.total, c["x0"], IDX_COARSE, SC_COARSE, self.args.coarse_fev) agg1, _ = obj.data(x1) bad = (mode == "canny" and agg1["loss"] > 6.0) or (mode == "gt" and agg1.get("mean_iou", 0) < 0.6) if bad: x1b, f1b, nfev1b, _ = L.run_nm(obj.total, x1, IDX_COARSE, SC_COARSE_BIG, self.args.coarse_fev) agg1b, _ = obj.data(x1b) if agg1b is not None and agg1b["loss"] < agg1["loss"]: x1, f1, agg1 = x1b, f1b, agg1b nfev1 += nfev1b c.update(x1=x1, agg0=agg0, agg1=agg1, nfev1=nfev1, prior_w=obj.prior_w, sigma=sig) log(f" cand {c['source']}: {mode} steps {len(steps)} ({c['sel_info'].get('n_selected_moving', '?')} moving" f"{f', min_edge {obj.opts[chr(109)+chr(105)+chr(110)+chr(95)+chr(101)+chr(100)+chr(103)+chr(101)]}: {n_strict} valid at 3000' if relaxed else ''}{f', {n_drop} unscorable dropped' if n_drop else ''})" f" start {agg0['loss']:.3f} (valid {agg0['n_valid']}) -> coarse4 " f"{agg1['loss']:.3f} (valid {agg1['n_valid']}, nfev {nfev1}) |t| {np.linalg.norm(x1[:3]) * 1e3:.1f} mm " f"rot {np.rad2deg(L.rot_angle(x1[3:])):.2f} deg" + (f" iou {agg1['mean_iou']:.3f}" if "mean_iou" in agg1 else "")) feas = [c for c in cands if "x1" in c] cam["candidates"] = [dict(source=c["source"], kind=c["kind"], infeasible=c.get("infeasible"), start=_f(c["agg0"]["loss"]) if "agg0" in c else None, coarse=_f(c["agg1"]["loss"]) if "agg1" in c else None, n_valid=c["agg1"]["n_valid"] if "agg1" in c else None, n_valid_strict=c.get("n_valid_strict"), relaxed_min_edge=c.get("relaxed_min_edge"), steps=c.get("steps"), sel_info=c.get("sel_info"), nfev=c.get("nfev1"), x1=c["x1"].tolist() if "x1" in c else None) for c in cands] if not feas: cam["status"] = "failed" cam["fail_reason"] = "no candidate base pose with scorable in-view steps" cam["x"] = np.zeros(6) cam["chosen"] = cands[0] cam["T_base"] = np.linalg.inv(pose6_to_mat(cands[0]["pose6"])) cam["mode"] = cands[0].get("mode", "canny") cam["steps"] = cands[0].get("steps") or [] log(f"cam {serial}: FAILED - {cam['fail_reason']}") return best = min(feas, key=lambda c: c["agg1"]["loss"]) off = next((c for c in feas if c["kind"] == "official"), None) if off is not None and best is not off and off["agg1"]["loss"] <= best["agg1"]["loss"] * 1.03: best = off # tie -> keep the official pose # 6-DoF fine stage on every candidate within CAND_FINE_RATIO of the best coarse loss (the 4-DoF coarse stage can # stall on a candidate that needs a 5-cm move); the best FINAL data loss wins, official pose kept on a 3 % tie runners = [best] + [c for c in sorted(feas, key=lambda c: c["agg1"]["loss"]) if c is not best and c["agg1"]["loss"] <= best["agg1"]["loss"] * L.CAND_FINE_RATIO][:L.CAND_FINE_MAX - 1] fine = [] for c in runners: opts = self.opts_for(cam, c["mode"]) opts["min_edge"] = c["min_edge_used"] obj_c = ExtObjective(self.pool, serial, c["steps"], self.dt_total, c["T_base"], c["mode"], opts, c["sigma"], c["prior_w"]) obj_c.penalty = L.invalid_penalty(c["mode"], opts) x2c, f2c, nfev2c, _ = L.run_nm(obj_c.total, c["x1"], IDX_ALL, SC_FINE, self.args.fine_fev) agg2c, _ = obj_c.data(x2c) fine.append(dict(c=c, obj=obj_c, x2=x2c, f2=f2c, nfev2=nfev2c, agg2=agg2c)) c["fine_loss"] = _f(agg2c["loss"], 4) if agg2c else None if len(runners) > 1: log(f" cand {c['source']}: fine6 {c['agg1']['loss']:.3f} -> {agg2c['loss'] if agg2c else float('nan'):.3f} (nfev {nfev2c})" + (f" iou {agg2c['mean_iou']:.3f}" if agg2c and 'mean_iou' in agg2c else "")) bestf = min(fine, key=lambda d: d["agg2"]["loss"] if d["agg2"] else L.BIG) offf = next((d for d in fine if d["c"]["kind"] == "official"), None) if offf is not None and bestf is not offf and offf["agg2"] and bestf["agg2"] and offf["agg2"]["loss"] <= bestf["agg2"]["loss"] * 1.03: bestf = offf best, obj, x2, f2, nfev2 = bestf["c"], bestf["obj"], bestf["x2"], bestf["f2"], sum(d["nfev2"] for d in fine) cam["chosen"] = best cam["T_base"] = best["T_base"] cam["mode"] = best["mode"] cam["steps"] = best["steps"] cam["min_edge_used"] = best["min_edge_used"] cam["obj"] = obj for cc in cam["candidates"]: cc["fine"] = next((c.get("fine_loss") for c in feas if c["source"] == cc["source"]), None) agg_s, _ = obj.data(best["x1"]) x3, f3, nfev3, _ = L.run_nm(obj.total, x2, IDX_ALL, SC_POLISH, self.args.polish_fev) agg3, _ = obj.data(x3) cam["x"] = x3 cam["nfev"] = dict(coarse=best["nfev1"], fine=nfev2, polish=nfev3) cam["status"] = "fit" log(f"cam {serial}: chose {best['source']}; fine6 {agg_s['loss']:.3f} -> {f2 - obj.prior(x2):.3f} (nfev {nfev2}) -> polish " f"{agg3['loss']:.3f} (nfev {nfev3}) | delta |t| {np.linalg.norm(x3[:3]) * 1e3:.1f} mm rot {np.rad2deg(L.rot_angle(x3[3:])):.2f} deg" + (f" iou {agg3['mean_iou']:.3f} r2g {agg3['mean_r2g']:.2f}" if "mean_iou" in agg3 else "")) def refit_camera(self, serial, scales, maxfev, label): cam = self.cams[serial] if cam.get("status") != "fit": return obj = cam["obj"] obj.dt_total = self.dt_total agg_a, _ = obj.data(cam["x"]) x, f, nfev, _ = L.run_nm(obj.total, cam["x"], IDX_ALL, scales, maxfev) agg_b, _ = obj.data(x) cam["x"] = x cam["nfev"][label] = nfev log(f"cam {serial} {label} (dt {self.dt_total:+.1f}): {agg_a['loss']:.3f} -> {agg_b['loss']:.3f} (nfev {nfev}) " f"|t| {np.linalg.norm(x[:3]) * 1e3:.1f} mm rot {np.rad2deg(L.rot_angle(x[3:])):.2f} deg") # -- time stage ----------------------------------------------------------------------- def time_sweep(self, label): B = float(self.args.time_bound) grid = np.arange(-B, B + 1e-6, L.TIME_GRID_MS) per_cam = {} for serial, cam in self.cams.items(): if cam.get("status") != "fit": continue obj = cam["obj"] steps = list(cam["steps"]) mov = [s for s in steps if self.speed[s] >= L.MIN_SPEED_MPS] steps_t = steps for vmin, nmin in L.TIME_SPEED_LADDER: cand = [s for s in steps if self.speed[s] >= vmin] if len(cand) >= nmin: steps_t = cand break T = pose6_to_mat(cam["x"]) @ cam["T_base"] valid = set(steps_t) if cam["mode"] == "canny": for d in (-B, 0.0, B): res = self.pool.evaluate(serial, steps_t, L.TIME_DEFAULT_MS + d, T=T, mode=cam["mode"], opts=obj.opts) valid &= {r["step"] for r in res if r.get("valid")} if len(valid) < L.MIN_VALID_STEPS: res = self.pool.evaluate(serial, steps_t, L.TIME_DEFAULT_MS, T=T, mode=cam["mode"], opts=obj.opts) valid = {r["step"] for r in res if r.get("valid")} steps_v = [s for s in steps_t if s in valid] if len(steps_v) < L.MIN_VALID_STEPS: per_cam[serial] = dict(curve=[float("nan")] * len(grid), cls="none", info={}, n_steps=len(steps_v), n_moving=len(mov)) continue curve = [] pen = L.invalid_penalty(cam["mode"], obj.opts) for d in grid: res = self.pool.evaluate(serial, steps_v, L.TIME_DEFAULT_MS + d, T=T, mode=cam["mode"], opts=obj.opts) agg = L.aggregate(res, penalty=pen) curve.append(agg["loss"] if agg is not None and agg["n_valid"] >= L.MIN_VALID_STEPS else float("nan")) cls, info = L.classify_sweep(curve, grid) per_cam[serial] = dict(curve=[_f(v, 4) for v in curve], cls=cls, info=info, n_steps=len(steps_v), n_moving=len(mov), steps=steps_v) good = [s for s in per_cam if np.isfinite(np.array(per_cam[s]["curve"], dtype=float)).sum() >= 3] prior_term = L.TIME_PRIOR_W * 0.5 * (grid / L.TIME_SIGMA_MS) ** 2 out = dict(grid_ms=grid.tolist(), per_cam=per_cam, n_steps=int(sum(per_cam[s]["n_steps"] for s in per_cam))) if not good: out.update(d_ms=0.0, cls="none", prior_used=True, total=None) log(f"time {label}: no camera with a usable curve -> prior (d = 0)") else: normed = [] for s in good: c = np.array(per_cam[s]["curve"], dtype=float) med = float(np.nanmedian(c)) normed.append(c / max(med, 1e-9)) total = np.nanmean(np.stack(normed), axis=0) + prior_term cls, info = L.classify_sweep(total, grid) i0 = int(np.nanargmin(total)) if cls in ("flat", "edge", "none"): d, prior_used = 0.0, True else: d, prior_used = L.parabolic_vertex(grid[i0 - 1:i0 + 2], total[i0 - 1:i0 + 2]), False d = float(np.clip(d, -B, B)) out.update(d_ms=float(d), cls=cls, info=info, prior_used=prior_used, total=[_f(v, 4) for v in total]) log(f"time {label}: per-cam " + ", ".join(f"{s}:{per_cam[s]['cls']}(argmin {per_cam[s]['info'].get('argmin_ms', '?')}, " f"rel {per_cam[s]['info'].get('range_rel', float('nan')):.2f}, n {per_cam[s]['n_steps']})" for s in per_cam) + f" | total {cls} argmin {grid[i0]:+.0f} -> d = {d:+.1f} ms (total offset {L.TIME_DEFAULT_MS + d:+.1f} ms)" + (" [prior used]" if prior_used else "")) return out # -- quality ------------------------------------------------------------------------- def finalize_camera(self, serial): cam = self.cams[serial] official = np.asarray(self.sess.ext_base_pose6[serial], dtype=float) mode = cam.get("mode", "canny") mname = {"canny": "canny_sym_band_chamfer_px@half", "gt": "gt_loss=(1-iou)+0.02*r2g@half"}[mode] q = dict(status="failed", metric_before=None, metric_after=None, metric_name=mname, n_steps=int(len(cam.get("steps") or [])), notes="", extra={}) chosen = cam.get("chosen") base_pose6, base_src = official, self.sess.ext_base_source[serial] x = np.zeros(6) notes = [] if cam.get("status") == "fit": obj = cam["obj"] obj.dt_total = self.dt_total # before: official pose, identity, default time, same steps / objective obj_off = ExtObjective(self.pool, serial, obj.steps, L.TIME_DEFAULT_MS, np.linalg.inv(pose6_to_mat(official)), mode, obj.opts, obj.sigma, 0.0) agg_before, _ = obj_off.data(np.zeros(6), penalty=None) agg_base, _ = obj.data(np.zeros(6)) # chosen base, identity, final time agg_after, _ = obj.data(cam["x"]) cam["steps"] = list(obj.steps) x = np.asarray(cam["x"], dtype=float) t_mm = float(np.linalg.norm(x[:3]) * 1e3) rot_deg = float(np.rad2deg(L.rot_angle(x[3:]))) q["metric_before"] = _f(agg_before["loss"], 4) if agg_before else None q["metric_after"] = _f(agg_after["loss"], 4) if agg_after else None q["extra"].update(metric_at_chosen_base=_f(agg_base["loss"], 4) if agg_base else None, n_valid_before=agg_before["n_valid"] if agg_before else 0, n_valid_after=agg_after["n_valid"] if agg_after else 0, delta_t_mm=round(t_mm, 2), delta_rot_deg=round(rot_deg, 3), nfev=cam.get("nfev"), mode=mode, min_edge=cam.get("min_edge_used"), candidates=cam.get("candidates"), steps=[int(s) for s in cam["steps"]], chosen_source=chosen["source"], prior_sigma=[chosen["sigma"][0], float(np.rad2deg(chosen["sigma"][1]))], prior_w=_f(chosen["prior_w"], 4)) if agg_after and "mean_iou" in agg_after: q["extra"].update(iou_after=_f(agg_after["mean_iou"]), r2g_after=_f(agg_after.get("mean_r2g")), iou_before=_f(agg_before["mean_iou"]) if agg_before and "mean_iou" in agg_before else None, r2g_before=_f(agg_before.get("mean_r2g")) if agg_before else None, iou_at_chosen_base=_f(agg_base["mean_iou"]) if agg_base and "mean_iou" in agg_base else None, iou_full_after=_f(agg_after.get("mean_iou_full")), prec_after=_f(agg_after.get("mean_prec")), far_frac_after=_f(agg_after.get("mean_far_frac")), median_iou_after=_f(agg_after.get("median_iou")), n_iou_lt_0p5_after=agg_after.get("n_iou_lt_0p5"), trim_far_eval_px=float(self.trim_far_eval)) if agg_after is None or agg_after["n_valid"] < L.MIN_VALID_STEPS: q["status"] = "failed" notes.append("no scorable steps at the solution") elif t_mm > L.EXT_HARD_T_M * 1e3 or rot_deg > np.rad2deg(L.EXT_HARD_R_RAD): q["status"] = "failed" notes.append(f"delta beyond hard bound ({t_mm:.0f} mm / {rot_deg:.1f} deg)") else: after = agg_after["loss"] if mode == "canny": bad = after > L.CANNY_FAILED_PX degraded = after > L.CANNY_DEGRADED_PX else: iou = agg_after.get("mean_iou", 0.0) bad = iou < L.GT_FAILED_IOU degraded = iou < L.GT_DEGRADED_IOU if degraded: # robust re-judgement: inconsistent GT steps (SAM3 blobs where the robot is out of view) or # GT with far extra pixels (cables) must not flag a well-aligned camera med = agg_after.get("median_iou", iou) frac_good = agg_after.get("frac_iou_ge_0p5", 1.0) n_lt = agg_after.get("n_iou_lt_0p5", 0) prec = agg_after.get("mean_prec") far = agg_after.get("mean_far_frac") r2g_a = agg_after.get("mean_r2g") robust = None if med >= L.GT_DEGRADED_IOU and frac_good >= 0.6: robust = (f"robust quality: mean IoU {iou:.3f} but median {med:.3f} with {n_lt}/{agg_after['n_valid']} steps " f"below 0.5 (inconsistent GT) -> judged on the median") elif (prec is not None and prec >= 0.85 and r2g_a is not None and r2g_a <= 1.5 and far is not None and far >= 0.05): robust = (f"robust quality: IoU {iou:.3f} with GT far-fraction {far:.2f}, precision {prec:.3f}, " f"r2g {r2g_a:.2f} px -> render inside the GT, extra GT ignored") if robust is not None: bad, degraded = False, False notes.append(robust) q["extra"]["robust_quality"] = True if bad: q["status"] = "failed" notes.append(f"metric after {after:.3f} beyond the failure threshold") else: base_pose6, base_src = np.asarray(chosen["pose6"], dtype=float), chosen["source"] if agg_base is not None and agg_base["n_valid"] >= L.MIN_VALID_STEPS and after >= agg_base["loss"] - 1e-6: x = np.zeros(6) notes.append("delta did not lower the objective -> identity") q["status"] = "degraded" if degraded else "ok" if degraded: notes.append(f"metric after {after:.3f} above the degraded threshold") if len(cam["steps"]) < L.MIN_STEPS_OK: q["status"] = "degraded" notes.append(f"only {len(cam['steps'])} steps") if agg_after["n_valid"] < L.MIN_STEPS_OK: q["status"] = "degraded" notes.append(f"only {agg_after['n_valid']} scorable steps") if chosen.get("relaxed_min_edge"): notes.append("min_edge relaxed to 1500@640x360") if chosen["kind"] != "official": notes.append(f"base pose substituted: {chosen['source']} ({chosen.get('note', '')})") sweep_cls = None if self.time_result and self.time_result.get("per_cam", {}).get(serial): sweep_cls = self.time_result['per_cam'][serial]['cls'] notes.append(f"time sweep {sweep_cls}") if (mode == "gt" and agg_after.get("mean_iou", 1.0) < L.NONRIGID_IOU and (agg_after.get("mean_r2g") or 0.0) > L.NONRIGID_R2G and sweep_cls in ("flat", "none")): notes.append(f"nonrigid_suspect: iou {agg_after['mean_iou']:.3f} < {L.NONRIGID_IOU} with r2g " f"{agg_after['mean_r2g']:.2f} px and a {sweep_cls} time sweep (camera/robot not rigid, e.g. mobile cart)") q["extra"]["nonrigid_suspect"] = True if q["status"] == "failed": notes.append("kept official base pose + identity delta") else: notes.append(cam.get("fail_reason", "not fitted")) q["extra"].update(candidates=cam.get("candidates")) if q["status"] == "failed": x = np.zeros(6) base_pose6, base_src = official, self.sess.ext_base_source[serial] q["notes"] = "; ".join(notes) cam["final"] = dict(pose6=base_pose6, source=base_src, delta=x, quality=q) log(f"cam {serial}: {q['status'].upper()} before {q['metric_before']} after {q['metric_after']} ({mname}); " f"base {base_src}; delta {np.round(x[:3] * 1e3, 1).tolist()} mm {np.round(np.rad2deg(x[3:]), 2).tolist()} deg; {q['notes']}") # -- wrist stage ----------------------------------------------------------------------- def _wrist_fit(self, ws, F, steps, raw_start, mode, opts, label, x_start=None): """NM (fine -> polish) of the camera-frame delta on top of the start pose F over `steps`. raw_start: per-step records at F (for the start loss); x_start: initial delta (default 0).""" pen = L.invalid_penalty(mode, opts) agg0 = L.aggregate([x for x in raw_start if x["step"] in set(steps) and x.get("valid")], penalty=pen) start_loss = agg0["loss"] if agg0 else L.PRIOR_FLOOR[mode] obj = WristObjective(self.pool, ws, steps, self.dt_total, F, mode, opts, prior_w=L.PRIOR_FRAC * max(start_loss, L.PRIOR_FLOOR[mode])) x0 = np.zeros(6) if x_start is None else np.asarray(x_start, dtype=float) x1, f1, n1, _ = L.run_nm(obj.total, x0, IDX_ALL, SC_WRIST, self.args.fine_fev) x2, f2, n2, _ = L.run_nm(obj.total, x1, IDX_ALL, SC_WRIST_POLISH, self.args.polish_fev) agg2, res2 = obj.data(x2) t_mm = float(np.linalg.norm(x2[:3]) * 1e3) rot_deg = float(np.rad2deg(L.rot_angle(x2[3:]))) log(f"wrist {ws} NM [{label}] {len(steps)} steps: start {start_loss:.3f} -> NM {f1 - obj.prior(x1):.3f} (nfev {n1}) -> polish " f"{agg2['loss'] if agg2 else float('nan'):.3f} (nfev {n2}) |t| {t_mm:.1f} mm rot {rot_deg:.2f} deg" + (f" iou {agg2['mean_iou']:.3f} (median {agg2.get('median_iou', float('nan')):.3f}, valid {agg2['n_valid']}/{len(steps)})" if agg2 and 'mean_iou' in agg2 else "")) return dict(label=label, x=x2, F=np.asarray(F), steps=list(steps), agg0=agg0, agg=agg2, res=res2, nfev=n1 + n2, t_mm=t_mm, rot_deg=rot_deg) def wrist_stage(self): ws = self.sess.wrist_serial q = dict(status="failed", metric_before=None, metric_after=None, metric_name="", n_steps=0, notes="", extra={}) res = dict(delta=np.zeros(6), flipped=False, quality=q) if not self.want_wrist: q["notes"] = self.wrist_skip_reason or "wrist disabled" return res if ws not in self.sess.K_mp4 or ws not in self.sess.mp4_wh: q["notes"] = "no intrinsics / MP4 size for the wrist camera" return res K_eval, wh_eval, min_edge = L.eval_geometry(self.sess.K_mp4[ws], self.sess.mp4_wh[ws], L.EVAL_SCALE) self.cams[ws] = dict(K_eval=K_eval, wh_eval=wh_eval, min_edge=min_edge, source="h5-handeye", wrist=True) self.pool.set_camera(ws, K_eval, wh_eval) n_lim = self.n_frames_min or self.sess.n mode = "dark" steps, info = [], {} if self.gt_mode: steps, info = self.gt_steps_for(ws, self.args.n_steps, wrist=True) if len(steps) >= 4: mode = "gt" else: log(f"wrist {ws}: only {len(steps)} usable GT steps -> dark-pixel fallback") steps = [] if not steps: g = self.gms_steps() if g.get(ws): steps = [int(s) for s in g[ws] if 0 <= s < self.sess.n - 1] info = dict(selector="gt_masks_scale", n_selected=len(steps), n_sel_open=int(sum(self.sess.gs[s] < 0.3 for s in steps)), n_sel_closed=int(sum(self.sess.gs[s] > 0.5 for s in steps))) else: steps, info = L.select_wrist_steps(self.sess.gs, self.sess.n, self.args.n_steps) info["selector"] = "local" steps = [s for s in steps if s not in self.exclude] steps = [s for s in steps if s < n_lim] steps = self.push(ws, steps, gt=(mode == "gt")) q["metric_name"] = {"gt": "gt_loss=(1-iou)+0.02*r2g@half(gripper-only)", "dark": "dark_loss=(1-iou_dark)+0.02*r2r@half(gripper-only)"}[mode] q["n_steps"] = len(steps) min_edge = int(round(L.WRIST_MIN_EDGE_PX * wh_eval[0] * wh_eval[1] / L.REF_EVAL_PX)) opts = dict(supersample=int(self.args.supersample), min_edge=min_edge, band=L.BAND_PX, clip=L.BAND_PX, lam=L.LAMBDA_R2G, grip_only=True) if mode == "gt": opts["trim_far"] = float(self.trim_far_eval) pen = L.invalid_penalty(mode, opts) # ---- flip test: identity vs 180-deg roll about the optical axis, the roll alone and with the stereo # baseline added along +-x (a rolled ZED Mini has its left lens where the right one was) starts = {"identity": np.zeros(6)} for name, tx in (("flip", 0.0), ("flip+x", L.WRIST_FLIP_BASELINE_M), ("flip-x", -L.WRIST_FLIP_BASELINE_M)): p6 = np.array(RE.WRIST_FLIP_POSE6, dtype=float) p6[0] += tx starts[name] = p6 raw, support, ftest = {}, {}, {} for name, p6 in starts.items(): r = self.pool.evaluate(ws, steps, self.dt_total, T=None, D=pose6_to_mat(p6), mode=mode, opts=opts) raw[name] = r support[name] = [x["step"] for x in r if x.get("valid") and float(x.get("iou", 0.0)) >= L.GT_SUPPORT_IOU] agg = L.aggregate(r, penalty=None) ftest[name] = dict(loss=_f(agg["loss"], 4) if agg else None, iou=_f(agg.get("mean_iou")) if agg else None, n_valid=agg["n_valid"] if agg else 0, n_support=len(support[name]), iou_support=_f(np.mean([float(x.get("iou", 0.0)) for x in r if x["step"] in set(support[name])])) if support[name] else None) log(f"wrist {ws} flip test {name:9s}: " + (f"loss {agg['loss']:.3f} valid {agg['n_valid']}/{len(steps)} iou {agg.get('mean_iou', float('nan')):.3f} " f"support {len(support[name])}" if agg else f"no valid steps ({[x.get('why') for x in r][:6]})")) q["extra"].update(mode=mode, steps=[int(s) for s in steps], sel_info=info, flip_test=ftest, trim_far_eval_px=float(self.trim_far_eval)) valid_id = [x["step"] for x in raw["identity"] if x.get("valid")] flip_names = [n for n in starts if n != "identity"] best_flip = max(flip_names, key=lambda n: (len(support[n]), ftest[n]["iou_support"] or 0.0)) flip_feasible = len(support[best_flip]) >= L.MIN_VALID_STEPS if not valid_id and not flip_feasible: q["notes"] = "no scorable wrist steps (identity and flip starts)" q["extra"]["flip_test"] = ftest return res q["metric_before"] = _f(ftest["identity"]["loss"], 4) fits = {} if valid_id: steps_id = list(valid_id) if flip_feasible and len(support["identity"]) >= L.MIN_VALID_STEPS: steps_id = list(support["identity"]) # GT is split between the two hypotheses: judge each on its own steps fits["identity"] = self._wrist_fit(ws, np.eye(4), steps_id, raw["identity"], mode, opts, "identity") if flip_feasible: fits[best_flip] = self._wrist_fit(ws, pose6_to_mat(starts[best_flip]), list(support[best_flip]), raw[best_flip], mode, opts, best_flip) iou_of = lambda f: (f["agg"] or {}).get("mean_iou", -1.0) if f["agg"] and f["agg"]["n_valid"] >= L.MIN_VALID_STEPS else -1.0 chosen = "identity" if "identity" in fits else best_flip flipped = False if best_flip in fits and ("identity" not in fits or iou_of(fits[best_flip]) >= iou_of(fits["identity"]) + L.WRIST_FLIP_MARGIN_IOU): chosen, flipped = best_flip, True fit = fits[chosen] nfev_total = sum(f["nfev"] for f in fits.values()) q["extra"]["hypotheses"] = {n: dict(n_steps=len(f["steps"]), iou=_f(iou_of(f)), loss=_f(f["agg"]["loss"], 4) if f["agg"] else None, t_mm=round(f["t_mm"], 2), rot_deg=round(f["rot_deg"], 3)) for n, f in fits.items()} if len(fits) > 1: log(f"wrist {ws}: hypotheses " + ", ".join(f"{n}: iou {iou_of(f):.3f} on {len(f['steps'])} steps" for n, f in fits.items()) + f" -> {chosen}{' (FLIPPED)' if flipped else ''}") notes = [] # ---- rescue pass: few steps or no open/closed diversity -> adopt non-usable GT steps consistent with the solution if mode == "gt": gs = self.sess.gs n_open = sum(1 for s in fit["steps"] if gs[s] < 0.3) n_closed = sum(1 for s in fit["steps"] if gs[s] > 0.5) need = len(fit["steps"]) < L.WRIST_MIN_STEPS_FULL or n_open == 0 or n_closed == 0 if need: have = set(fit["steps"]) cands = [(s_, rec) for s_, rec in L.usable_gt_steps(self.uuid, ws, self.args.gt_root, statuses=None) if s_ not in have and s_ not in self.exclude and 0 <= s_ < min(n_lim, self.sess.n - 1)] resc = dict(reason=("few_steps" if len(fit["steps"]) < L.WRIST_MIN_STEPS_FULL else "") + ("" if n_open else " no_open") + ("" if n_closed else " no_closed"), candidates=[int(s_) for s_, _ in cands], added=[], statuses={str(s_): rec.get("status") for s_, rec in cands}) if cands: pushed = self.push(ws, [s_ for s_, _ in cands], gt=True) D = pose6_to_mat(fit["x"]) @ fit["F"] r = self.pool.evaluate(ws, pushed, self.dt_total, T=None, D=D, mode="gt", opts=opts) resc["iou_at_solution"] = {str(x["step"]): _f(x.get("iou")) for x in r} add = [x["step"] for x in r if x.get("valid") and float(x.get("iou", 0.0)) >= L.GT_RESCUE_IOU] resc["added"] = [int(s_) for s_ in add] log(f"wrist {ws} rescue ({resc['reason'].strip()}): {len(cands)} non-usable GT steps, iou at solution " f"{[(x['step'], round(float(x.get('iou', 0.0)), 2)) for x in r]} -> adopt {add}") if add: steps2 = sorted(set(fit["steps"]) | set(add)) raw2 = self.pool.evaluate(ws, steps2, self.dt_total, T=None, D=D, mode="gt", opts=opts) fit2 = self._wrist_fit(ws, fit["F"], steps2, raw2, mode, opts, f"{chosen}+rescue", x_start=fit["x"]) resc["iou_before_refit"] = _f(iou_of(fit)); resc["iou_after_refit"] = _f(iou_of(fit2)) nfev_total += fit2["nfev"] fit = fit2 notes.append(f"rescued {len(add)} GT steps with status {sorted(set(resc['statuses'].get(str(s_)) for s_ in add))} (IoU >= {L.GT_RESCUE_IOU} at the first-pass solution)") q["extra"]["rescue"] = resc if not n_open or not n_closed: n_open2 = sum(1 for s_ in fit["steps"] if gs[s_] < 0.3) n_closed2 = sum(1 for s_ in fit["steps"] if gs[s_] > 0.5) if not n_open2 or not n_closed2: notes.append(f"no gripper open/closed diversity in the fit steps (open {n_open2}, closed {n_closed2}); weakly constrained") x2, F, agg2 = fit["x"], fit["F"], fit["agg"] steps = list(fit["steps"]) q["n_steps"] = len(steps) t_mm, rot_deg = fit["t_mm"], fit["rot_deg"] q["metric_after"] = _f(agg2["loss"], 4) if agg2 else None q["extra"].update(delta_t_mm=round(t_mm, 2), delta_rot_deg=round(rot_deg, 3), nfev=dict(total=int(nfev_total)), metric_at_start=_f(fit["agg0"]["loss"], 4) if fit["agg0"] else None, n_valid_after=agg2["n_valid"] if agg2 else 0, iou_before=_f(ftest["identity"]["iou"]), iou_after=_f(agg2["mean_iou"]) if agg2 and "mean_iou" in agg2 else None, median_iou_after=_f(agg2.get("median_iou")) if agg2 else None, r2g_after=_f(agg2.get("mean_r2g", agg2.get("mean_r2r"))) if agg2 else None, far_frac_after=_f(agg2.get("mean_far_frac")) if agg2 else None, chosen_start=chosen, fitted_delta_rel_start=x2.tolist(), steps=[int(s_) for s_ in steps], n_open=int(sum(1 for s_ in steps if self.sess.gs[s_] < 0.3)), n_closed=int(sum(1 for s_ in steps if self.sess.gs[s_] > 0.5))) if agg2 is None or agg2["n_valid"] < L.MIN_VALID_STEPS: notes.append("no scorable steps at the solution") elif t_mm > L.WRIST_HARD_T_M * 1e3 or rot_deg > np.rad2deg(L.WRIST_HARD_R_RAD): notes.append(f"delta beyond hard bound ({t_mm:.0f} mm / {rot_deg:.1f} deg)") else: iou = agg2.get("mean_iou", 0.0) lo, hi = (L.GT_FAILED_IOU, L.GT_DEGRADED_IOU) if mode == "gt" else (L.DARK_FAILED_IOU, L.DARK_DEGRADED_IOU) if iou < lo: notes.append(f"iou after {iou:.3f} below the failure threshold {lo}") else: q["status"] = "degraded" if (iou < hi or agg2["n_valid"] < L.MIN_STEPS_OK) else "ok" if iou < hi: notes.append(f"iou after {iou:.3f} below {hi}") if agg2["n_valid"] < L.MIN_STEPS_OK: notes.append(f"only {agg2['n_valid']} scorable steps") if mode == "dark": notes.append("dark-pixel fallback objective (no wrist GT)") res["flipped"] = bool(flipped) res["delta"] = mat_to_pose6(pose6_to_mat(x2) @ F) if flipped else np.asarray(x2, dtype=float).copy() if flipped: notes.append(f"wrist video rotated 180 deg vs h5 hand-eye (start {chosen}: roll 180 deg" f"{' + baseline ' + ('+' if '+' in chosen else '-') + f'{L.WRIST_FLIP_BASELINE_M * 1e3:.0f} mm' if 'x' in chosen else ''}); " f"folded into wrist_delta; {len(steps)} supporting steps of {len(valid_id)} valid") if q["status"] == "failed": notes.append("kept identity wrist_delta" + (" (flip test preferred the 180-deg roll)" if flipped else "")) q["notes"] = "; ".join(notes) res["quality"] = q log(f"wrist {ws}: {q['status'].upper()} before {q['metric_before']} after {q['metric_after']} flipped={res['flipped']}; {q['notes']}") return res # -- main ------------------------------------------------------------------------------ def run(self): args = self.args if self.out_path.exists() and not args.force: log(f"{self.out_path} exists; use --force to re-fit") return 0 ws = str(self.meta.get("wrist_cam_serial")) self.want_wrist = (not args.no_wrist) and (self.ep_dir / f"recordings/MP4/{ws}.mp4").exists() self.wrist_skip_reason = None if self.want_wrist else ("--no-wrist" if args.no_wrist else "no wrist MP4") try: self.sess = RE.EpisodeSession(str(self.ep_dir), wrist=self.want_wrist, calib_v2=L.NO_V2) except KeyError as e: log(f"wrist disabled: {e}") self.want_wrist, self.wrist_skip_reason = False, f"no h5 wrist extrinsics ({e})" self.sess = RE.EpisodeSession(str(self.ep_dir), wrist=False, calib_v2=L.NO_V2) sess = self.sess with h5py.File(self.ep_dir / "trajectory.h5", "r") as f: cart = f["observation/robot_state/cartesian_position"][:, :3] self.speed = L.ee_speed_per_step(cart, sess.t_state) self.gt_mode = (not args.no_gt) and L.gt_available(self.uuid, args.gt_root) self.exclude = benchmark_exclusions(self.uuid) # keep the SAM3 benchmark frames out of every fit if self.exclude: log(f"excluding {len(self.exclude)} benchmark frames (+-1) from the fit") self.dt_total = L.TIME_DEFAULT_MS self.time_result = None self.n_frames_min = None frame_check = {} for s in list(sess.mp4_wh): w_, h_, nfr = RE.video_size(self.ep_dir / f"recordings/MP4/{s}.mp4") frame_check[s] = dict(frames=nfr, steps=int(sess.n), diff=int(nfr - (sess.n - 1))) if nfr > 0: self.n_frames_min = nfr if self.n_frames_min is None else min(self.n_frames_min, nfr) mono = {s: bool(np.all(np.diff(sess.cap_ts[s]) > 0)) for s in sess.cap_ts if s in sess.mp4_wh} frame_check["capture_monotonic"] = mono bad_frames = [s for s, v in frame_check.items() if isinstance(v, dict) and abs(v.get("diff", 0)) > 2] if bad_frames or not all(mono.values()): log(f"WARNING: frame/step mismatch {frame_check} (i<->i mapping kept, steps >= n_frames skipped)") log(f"{self.uuid}: n={sess.n} steps, cams {sess.serials}, wrist {ws} ({'on' if self.want_wrist else 'off'}), " f"objective {'SAM3-GT' if self.gt_mode else 'Canny-DT'}, arm {sess.arm_type}, mount md5 {sess.rr.mount_params.get('md5')}") ext_serials = [s for s in sess.serials if s != ws and s in sess.mp4_wh and s in sess.K_mp4] skipped = [s for s in sess.serials if s != ws and s not in ext_serials] t_pool = time.time() self.pool = L.RenderPool(self.ep_dir, args.workers, wrist=self.want_wrist) log(f"render pool: {args.workers} workers ready in {time.time() - t_pool:.1f} s") self.cams = {} try: for s in ext_serials: K_eval, wh_eval, min_edge = L.eval_geometry(sess.K_mp4[s], sess.mp4_wh[s], L.EVAL_SCALE) self.cams[s] = dict(K_eval=K_eval, wh_eval=wh_eval, min_edge=min_edge, source=sess.ext_base_source[s], status="init") self.pool.set_camera(s, K_eval, wh_eval) if sess.K_quality.get(s, "ok") != "ok": log(f"WARNING {s}: {sess.K_quality[s]}") # ---- round 1: ext -> time t = time.time() for s in ext_serials: self.fit_camera_round1(s) self.stage("ext_round1", n_eval=self.pool.n_eval, n_render=self.pool.n_render, secs=round(time.time() - t, 1)) t = time.time() tr = self.time_sweep("round1") self.dt_total = L.TIME_DEFAULT_MS + tr["d_ms"] self.time_result = tr self.stage("time_round1", d_ms=tr["d_ms"], cls=tr["cls"], secs=round(time.time() - t, 1)) # ---- further rounds for r in range(2, int(args.rounds) + 1): t = time.time() for s in ext_serials: self.refit_camera(s, SC_ROUND2, args.round2_fev, f"round{r}") self.stage(f"ext_round{r}", n_eval=self.pool.n_eval, n_render=self.pool.n_render, secs=round(time.time() - t, 1)) t = time.time() tr2 = self.time_sweep(f"round{r}") moved = abs(tr2["d_ms"] - tr["d_ms"]) tr = tr2 self.dt_total = L.TIME_DEFAULT_MS + tr["d_ms"] self.time_result = tr self.stage(f"time_round{r}", d_ms=tr["d_ms"], cls=tr["cls"], secs=round(time.time() - t, 1)) if moved > 2.0: for s in ext_serials: self.refit_camera(s, SC_POLISH, args.polish_fev, f"polish{r}") # ---- quality for s in ext_serials: self.finalize_camera(s) # ---- wrist t = time.time() wres = self.wrist_stage() self.stage("wrist", secs=round(time.time() - t, 1), n_eval=self.pool.n_eval, n_render=self.pool.n_render) finally: self.pool.close() # ---- assemble quality = {} ext_base_pose6, ext_base_source, ext_delta = {}, {}, {} for s in ext_serials: fin = self.cams[s]["final"] ext_base_pose6[s] = [float(v) for v in fin["pose6"]] ext_base_source[s] = str(fin["source"]) ext_delta[s] = [float(v) for v in fin["delta"]] quality[s] = fin["quality"] for s in skipped: ext_base_pose6[s] = [float(v) for v in sess.ext_base_pose6[s]] ext_base_source[s] = str(sess.ext_base_source[s]) ext_delta[s] = [0.0] * 6 quality[s] = dict(status="failed", metric_before=None, metric_after=None, metric_name="", n_steps=0, notes="no MP4 or no intrinsics for this camera; superset pose + identity") quality[ws] = wres["quality"] tq = dict(sweep_class=str(self.time_result["cls"]), n_steps=int(self.time_result["n_steps"]), prior_used=bool(self.time_result["prior_used"]), d_ms=round(float(self.time_result["d_ms"]), 2), default_ms=L.TIME_DEFAULT_MS, bound_ms=float(args.time_bound), sigma_ms=L.TIME_SIGMA_MS, per_cam={s: dict(cls=v["cls"], n_steps=v["n_steps"], argmin_ms=v["info"].get("argmin_ms"), range_rel=_f(v["info"].get("range_rel"))) for s, v in self.time_result["per_cam"].items()}, frame_check=frame_check) status_all = [quality[s]["status"] for s in ext_serials] out = dict(version=2, time_offset_ms=round(float(self.dt_total), 2), ext_base_pose6=ext_base_pose6, ext_base_source=ext_base_source, ext_delta=ext_delta, wrist_delta={ws: [float(v) for v in wres["delta"]]}, wrist_flipped=bool(wres["flipped"]), quality=quality, time_quality=tq, gt_masks_used=bool(self.gt_mode), mount_params_md5=sess.rr.mount_params.get("md5"), fit_meta=dict(version=L.VERSION, written=time.strftime("%Y-%m-%d %H:%M:%S"), runtime_s=round(time.time() - self.t0, 1), workers=int(args.workers), supersample=int(args.supersample), eval_scale=L.EVAL_SCALE, n_eval=int(self.pool.n_eval), n_render=int(self.pool.n_render), arm_urdf_md5=sess.rr.arm_md5, gripper_urdf_md5=sess.rr.gripper_md5, arm_type=sess.arm_type, K_source={s: sess.K_source.get(s) for s in list(ext_serials) + [ws]}, K_quality={s: sess.K_quality.get(s) for s in list(ext_serials) + [ws]}, ext_status=status_all, mp4_wh={s: list(v) for s, v in sess.mp4_wh.items()})) L.atomic_write_json(self.out_path, out) self.debug.update(result=out, time_sweep=self.time_result, cams={s: dict(candidates=self.cams[s].get("candidates"), steps=self.cams[s].get("steps"), mode=self.cams[s].get("mode"), nfev=self.cams[s].get("nfev")) for s in ext_serials}) L.atomic_write_json(self.log_dir / f"{self.uuid}.json", self.debug) log(f"wrote {self.out_path} (time {self.dt_total:+.1f} ms [{tq['sweep_class']}], ext {dict(zip(ext_serials, status_all))}, " f"wrist {quality[ws]['status']}, flipped {out['wrist_flipped']}) in {time.time() - self.t0:.0f} s; " f"{self.pool.n_eval} evals / {self.pool.n_render} renders; log {self.log_dir / (self.uuid + '.json')}") return 0 # ----------------------------------------------------------------------------- benchmark evaluation def eval_benchmark(ep_dir, bench_root=None, out_json=None, fitted_steps=None): """Before/after IoU and r2g (render-edge -> GT-edge mean distance, px at native res) on the SAM3 benchmark frames out/diag/gtmask///_gt.png (statuses ok/single/low_conf/ render_far_off/render_missing_robot). 'before' = superset pose + identity + 37 ms; 'after' = data//calib_refined_v2.json. Returns the rows + summary (also printed).""" ep_dir = Path(ep_dir) meta = json.load(open(ep_dir / "metadata.json")) uuid = meta["uuid"] bench_root = Path(bench_root) if bench_root else ROOT / "out/diag/gtmask" gdir = bench_root / uuid if not gdir.exists(): log(f"benchmark: no GT masks under {gdir}") return None usable = ("ok", "single", "low_conf", "render_far_off", "render_missing_robot") RE.VERBOSE = False sessions = {} for tag, kw in (("before", dict(calib_v2=L.NO_V2)), ("after", {})): try: sessions[tag] = RE.EpisodeSession(str(ep_dir), wrist=True, **kw) except KeyError: sessions[tag] = RE.EpisodeSession(str(ep_dir), wrist=False, **kw) rows = [] fitted_steps = fitted_steps or {} for sdir in sorted(p for p in gdir.iterdir() if p.is_dir() and p.name.isdigit()): serial = sdir.name for gp in sorted(sdir.glob("*_gt.png")): step = int(gp.name[:4]) pj = sdir / f"{step:04d}_prompt.json" status = None if pj.exists(): try: status = json.load(open(pj)).get("status") except (OSError, ValueError): status = None if status is not None and status not in usable: continue gt = cv2.imread(str(gp), cv2.IMREAD_GRAYSCALE) if gt is None: continue gt = gt > 128 row = dict(uuid=uuid, serial=serial, step=step, status=status, cam="wrist" if serial == str(meta.get("wrist_cam_serial")) else "ext", in_fit=bool(step in set(fitted_steps.get(serial, []))), gt_px=int(gt.sum())) dt_gt = L.dist_to(L.edge_mask(gt)) if gt.any() else None for tag, s in sessions.items(): if serial not in s.cap_ts or step >= s.n or serial not in s.K_mp4: continue if serial == s.wrist_serial and not hasattr(s, "X_handeye"): continue wh = s.mp4_wh.get(serial, tuple(s.wh[serial])) if (gt.shape[1], gt.shape[0]) != tuple(wh): gt_r = cv2.resize(gt.astype(np.uint8), tuple(wh), interpolation=cv2.INTER_NEAREST) > 0 dt_r = L.dist_to(L.edge_mask(gt_r)) if gt_r.any() else None else: gt_r, dt_r = gt, dt_gt T = s.set_step(serial, step, interp=True) _, mask = s.rr.render(T, s.K_mp4[serial], wh) inter = int((mask & gt_r).sum()) union = int((mask | gt_r).sum()) e_r = L.edge_mask(mask) row[f"iou_{tag}"] = inter / union if union else float("nan") row[f"r2g_{tag}"] = float(dt_r[e_r].mean()) if (dt_r is not None and e_r.any()) else float("nan") row[f"area_{tag}"] = int(mask.sum()) rows.append(row) summ = {} for cam in ("ext", "wrist"): sub = [r for r in rows if r["cam"] == cam] if not sub: continue for tag in ("before", "after"): iou = np.array([r.get(f"iou_{tag}", np.nan) for r in sub], dtype=float) r2g = np.array([r.get(f"r2g_{tag}", np.nan) for r in sub], dtype=float) ok = np.isfinite(iou) if ok.sum() == 0: continue summ[f"{cam}_{tag}"] = dict(n=int(ok.sum()), iou_p10_p50_p90=[_f(v) for v in np.nanpercentile(iou[ok], [10, 50, 90])], r2g_p10_p50_p90=[_f(v, 2) for v in np.nanpercentile(r2g[ok], [10, 50, 90])], n_in_fit=int(sum(r["in_fit"] for r in sub))) for tag in ("before", "after"): held = [r for r in sub if not r["in_fit"] and np.isfinite(r.get(f"iou_{tag}", np.nan))] if held: iou = np.array([r[f"iou_{tag}"] for r in held]) r2g = np.array([r[f"r2g_{tag}"] for r in held]) summ[f"{cam}_{tag}_heldout"] = dict(n=len(held), iou_p10_p50_p90=[_f(v) for v in np.nanpercentile(iou, [10, 50, 90])], r2g_p10_p50_p90=[_f(v, 2) for v in np.nanpercentile(r2g, [10, 50, 90])]) for k, v in summ.items(): log(f"benchmark {uuid} {k}: {v}") for r in rows: log(f" bench {r['serial']} step {r['step']:4d} {r['status'] or '?':<22s} iou {r.get('iou_before', float('nan')):.3f} -> " f"{r.get('iou_after', float('nan')):.3f} r2g {r.get('r2g_before', float('nan')):6.2f} -> {r.get('r2g_after', float('nan')):6.2f}" f"{' (fit step)' if r['in_fit'] else ''}") out = dict(uuid=uuid, rows=rows, summary=summ, calib_v2=str(ep_dir / "calib_refined_v2.json")) if out_json: L.atomic_write_json(out_json, out) return out # ----------------------------------------------------------------------------- CLI def main(argv=None): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("ep_dir") ap.add_argument("--no-wrist", action="store_true", help="skip the wrist stage") ap.add_argument("--force", action="store_true", help="re-fit even if calib_refined_v2.json exists") ap.add_argument("--workers", type=int, default=int(os.environ.get("SLURM_CPUS_PER_TASK", 8))) ap.add_argument("--no-gt", action="store_true", help="ignore out/gt masks (Canny objective)") ap.add_argument("--gt-root", default=None, help="GT mask root (default out/gt)") ap.add_argument("--supersample", type=int, default=1, help="render at k x the objective resolution (soft masks)") ap.add_argument("--rounds", type=int, default=2, help="ext -> time alternation rounds") ap.add_argument("--time-bound", type=float, default=L.TIME_BOUND_MS, help="hard bound |d| ms on the time correction") ap.add_argument("--gt-trim-far", type=float, default=L.GT_TRIM_FAR_FULL, help="GT px (at 1280x720) farther than this from the render are dropped from the IoU union (0 = plain IoU)") ap.add_argument("--n-steps", type=int, default=L.N_STEPS_EXT, help="steps per camera") ap.add_argument("--local-selector", action="store_true", help="do not use gt_masks_scale.select_steps (local rule only)") ap.add_argument("--coarse-fev", type=int, default=120) ap.add_argument("--fine-fev", type=int, default=300) ap.add_argument("--polish-fev", type=int, default=120) ap.add_argument("--round2-fev", type=int, default=200) ap.add_argument("--log-dir", default=None, help="debug log json dir (default out/refine_v2)") ap.add_argument("--eval-benchmark", action="store_true", help="after fitting, evaluate out/diag/gtmask frames before/after") ap.add_argument("--bench-root", default=None) ap.add_argument("--eval-only", action="store_true", help="only run the benchmark evaluation of the existing v2 file") args = ap.parse_args(argv) rc = 0 fitted = {} if not args.eval_only: ref = Refiner(args.ep_dir, args) rc = ref.run() if getattr(ref, "cams", None): fitted = {s: list(c.get("steps") or []) for s, c in ref.cams.items()} if args.eval_benchmark or args.eval_only: uuid = json.load(open(Path(args.ep_dir) / "metadata.json"))["uuid"] log_dir = Path(args.log_dir) if args.log_dir else ROOT / "out/refine_v2" log_dir.mkdir(parents=True, exist_ok=True) eval_benchmark(args.ep_dir, args.bench_root, log_dir / f"{uuid}_bench.json", fitted_steps=fitted) return rc if __name__ == "__main__": sys.exit(main())