"""Measure joint margins, foot clearance and stance drift for saved G1 clips.""" import argparse import hashlib import json from pathlib import Path import mujoco import numpy as np # A geometric proximity band for this report, expressed in millimetres. FLOOR_BAND_MM = 1.0 def foot_metrics(points_mm, planned): """points_mm contains the bottoms of four sole spheres, in world coordinates.""" heights = points_mm[:, :, 2] lowest = heights.min(axis=1) near_floor = lowest <= FLOOR_BAND_MM # Each touchdown starts a new reference for all four points on that foot. edges = np.flatnonzero(np.diff(np.r_[False, planned, False])) max_drift = 0.0 for begin, end in edges.reshape(-1, 2): displacement = points_mm[begin:end, :, :2] - points_mm[begin, :, :2] max_drift = max(max_drift, float(np.linalg.norm(displacement, axis=-1).max())) return { "planned_stance_frames": int(planned.sum()), "planned_stance_runs": len(edges) // 2, "max_stance_drift_mm": max_drift, "max_stance_abs_height_mm": float(np.abs(heights[planned]).max()) if planned.any() else None, "max_floor_penetration_mm": max(0.0, -float(lowest.min())), "peak_clearance_mm": float(lowest.max()), "stance_above_band_frames": np.flatnonzero(planned & ~near_floor).tolist(), "swing_in_band_frames": np.flatnonzero(~planned & near_floor).tolist(), "swing_at_or_below_floor_frames": np.flatnonzero(~planned & (lowest <= 0)).tolist(), } def inspect(model, clip_path): with np.load(clip_path, allow_pickle=False) as clip: times = clip["time_s"] names = clip["joint_names"].tolist() angles = clip["joint_pos_rad"] pelvis = clip["pelvis_pos_m"] quat = clip["pelvis_quat_wxyz"] planned = clip["foot_contact_planned"] frames = len(times) if frames < 2 or times[0] != 0 or not np.allclose(np.diff(times), 0.02): raise ValueError(f"{clip_path}: expected a 50 Hz timeline starting at zero") joints = np.array([model.joint(name).id for name in names]) hinges = np.flatnonzero(model.jnt_type == mujoco.mjtJoint.mjJNT_HINGE) if len(joints) != 29 or not np.array_equal(np.sort(joints), hinges): raise ValueError(f"{clip_path}: expected all 29 G1 hinges exactly once") if angles.shape != (frames, 29) or pelvis.shape != (frames, 3) or quat.shape != (frames, 4): raise ValueError(f"{clip_path}: unexpected pose dimensions") if not all(np.isfinite(field).all() for field in (angles, pelvis, quat)): raise ValueError(f"{clip_path}: non-finite pose") if planned.dtype != bool or planned.shape != (frames, 2): raise ValueError(f"{clip_path}: expected left/right boolean contact labels") low, high = model.jnt_range[joints].T margins = np.minimum(angles - low, high - angles) closest_frame, closest_joint = np.unravel_index(margins.argmin(), margins.shape) joint_check = { "outside_limit_values": int((margins < 0).sum()), "min_margin_rad": float(margins.min()), "closest_joint": names[closest_joint], "closest_frame": int(closest_frame), } sides = ("left", "right") soles = [] for side in sides: body = model.body(f"{side}_ankle_roll_link").id geoms = np.flatnonzero((model.geom_bodyid == body) & (model.geom_type == mujoco.mjtGeom.mjGEOM_SPHERE)) if len(geoms) != 4: raise ValueError(f"{side} foot must have four sole spheres") soles.append(geoms) soles = np.array(soles) data = mujoco.MjData(model) points = np.empty((frames, 2, 4, 3)) root = model.joint("floating_base_joint").qposadr[0] addresses = model.jnt_qposadr[joints] for frame in range(frames): data.qpos[root : root + 3] = pelvis[frame] data.qpos[root + 3 : root + 7] = quat[frame] data.qpos[addresses] = angles[frame] mujoco.mj_forward(model, data) points[frame] = data.geom_xpos[soles] points[frame, :, :, 2] -= model.geom_size[soles, 0] feet = {side: foot_metrics(points[:, i] * 1000, planned[:, i]) for i, side in enumerate(sides)} return { "file": clip_path.name, "sha256": hashlib.sha256(clip_path.read_bytes()).hexdigest(), "frames": frames, "joints": joint_check, "feet": feet, } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--scene", type=Path, required=True, help="Pinned Menagerie unitree_g1/scene.xml") args = parser.parse_args() folder = Path(__file__).resolve().parent settings = json.loads((folder / "settings.json").read_text()) model = mujoco.MjModel.from_xml_path(str(args.scene)) clips = [inspect(model, folder / "clips" / (item["id"] + ".npz")) for item in settings["clips"]] print(json.dumps({"mujoco": mujoco.__version__, "floor_band_mm": FLOOR_BAND_MM, "clips": clips}, indent=2)) if __name__ == "__main__": main()