# SPDX-License-Identifier: Apache-2.0 """Certify trajectories against the benchmark contract and compare with best-known solutions. usage: python tools/validate.py --problems data/problems_hard.jsonl --trajectories [--out report.json] /.npz must contain time [N], q, qd, qdd, jerk [N, 7] (rest to rest, start->goal). A trajectory is CERTIFIED iff the checks in README.md ("Contract") pass, including the inter-sample collision gap check (sample densely: >= 4096 samples recommended). """ import argparse import json import sys from pathlib import Path import numpy as np sys.path.insert(0, str(Path(__file__).resolve().parent)) from validate_core import build_model, validate # noqa: E402 DATASET = Path(__file__).resolve().parents[1] def hand_pose_error(q, goal_pose): """Position [m] and rotation [rad] error of panda_hand at q w.r.t. goal_pose (base frame).""" import pinocchio as pin model, data, state, qi, _ = build_model({"mass_kg": 0.0, "com_m": [0, 0, 0], "radius_m": 0.06}) state[qi] = q pin.framesForwardKinematics(model, data, state) m = data.oMf[model.getFrameId("panda_hand")] w, x, y, z = goal_pose["quaternion_wxyz"] rg = pin.Quaternion(w, x, y, z).toRotationMatrix() rot = float(np.linalg.norm(pin.log3(rg.T @ m.rotation))) return {"position_m": float(np.linalg.norm(m.translation - np.asarray(goal_pose["position_xyz"]))), "rotation_rad": rot} def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--problems", type=Path, required=True) ap.add_argument("--trajectories", type=Path, required=True) ap.add_argument("--out", type=Path, default=None) ap.add_argument("--ids", nargs="*", default=None) ap.add_argument("--goal-mode", choices=("joint", "pose"), default="joint", help="joint: end at the goal configuration; pose: end with panda_hand at goal_pose") ap.add_argument("--pos-tol", type=float, default=1e-3, help="pose mode: position tolerance [m]") ap.add_argument("--rot-tol", type=float, default=1e-2, help="pose mode: rotation tolerance [rad]") a = ap.parse_args() contract = json.loads((DATASET / "contract.json").read_text()) rows = [] for line in a.problems.read_text().splitlines(): p = json.loads(line) if a.ids and p["problem_id"] not in a.ids: continue f = a.trajectories / f"{p['problem_id']}.npz" if not f.exists(): rows.append({"problem_id": p["problem_id"], "submitted": False}) continue z = np.load(f) traj = {k: np.asarray(z[k], float) for k in ("time", "q", "qd", "qdd", "jerk")} goal = p["goal"] pose_err = None if a.goal_mode == "pose": pose_err = hand_pose_error(traj["q"][-1], p["goal_pose"]) goal = traj["q"][-1].tolist() # goal reached is judged by the hand pose below meta = {"payload": p["payload"], "scene": p["scene"], "start": p["start"], "goal": goal, "limits": contract["limits"], "gap_check": True} v = validate(traj, meta) if pose_err is not None: v["goal_pose_error"] = pose_err v["certified"] = bool(v.get("certified") and pose_err["position_m"] <= a.pos_tol and pose_err["rotation_rad"] <= a.rot_tol) d = float(traj["time"][-1] - traj["time"][0]) ref = p["best_known_pose"] if (a.goal_mode == "pose" and "best_known_pose" in p) else p["best_known"] rows.append({"problem_id": p["problem_id"], "submitted": True, "certified": bool(v.get("certified")), "duration_s": d, "best_known_s": ref["duration_s"], "ratio_to_best_known": d / ref["duration_s"], "checks": v}) print(p["problem_id"], "CERTIFIED" if v.get("certified") else "REJECTED", "%.4fs (best known %.4fs)" % (d, ref["duration_s"]), flush=True) sub = [r for r in rows if r["submitted"]] cert = [r for r in sub if r["certified"]] summary = {"problems": len(rows), "submitted": len(sub), "certified": len(cert), "median_ratio_to_best_known": float(np.median([r["ratio_to_best_known"] for r in cert])) if cert else None} print(json.dumps(summary, indent=2)) if a.out: a.out.write_text(json.dumps({"summary": summary, "rows": rows}, indent=2, default=float)) if __name__ == "__main__": main()