Download generate.py from ml303/vector-g1-sidestep: direct link, hf CLI and curl.
- Browser
- Download file 10.9 kB
-
https://huggingface.co/datasets/ml303/vector-g1-sidestep/resolve/main/generate.py
- Command line
-
hf download hf://datasets/ml303/vector-g1-sidestep/generate.py
-
curl -L -o generate.py https://huggingface.co/datasets/ml303/vector-g1-sidestep/resolve/main/generate.py
10.9 kB
| #!/usr/bin/env python3 | |
| """Generate reproducible, kinematic Unitree G1 side-step reference clips. | |
| The output represents an inverse-kinematics reference trajectory. It is useful | |
| for exercising the dataset schema and replay pipeline. It is not a dynamic | |
| simulation, a controller, or evidence that the motion transfers to hardware. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import mujoco | |
| import numpy as np | |
| FPS = 50 | |
| LEFT_FOOT = "left_foot" | |
| RIGHT_FOOT = "right_foot" | |
| PELVIS = "pelvis" | |
| TORSO = "torso_link" | |
| LEFT_LEG = ( | |
| "left_hip_pitch_joint", "left_hip_roll_joint", "left_hip_yaw_joint", | |
| "left_knee_joint", "left_ankle_pitch_joint", "left_ankle_roll_joint", | |
| ) | |
| RIGHT_LEG = ( | |
| "right_hip_pitch_joint", "right_hip_roll_joint", "right_hip_yaw_joint", | |
| "right_knee_joint", "right_ankle_pitch_joint", "right_ankle_roll_joint", | |
| ) | |
| def smoothstep(progress: float) -> float: | |
| """Return a position profile with zero velocity at both endpoints.""" | |
| clamped = np.clip(progress, 0.0, 1.0) | |
| return clamped * clamped * (3.0 - 2.0 * clamped) | |
| def phase(time_s: float, start_s: float, duration_s: float) -> float: | |
| return smoothstep((time_s - start_s) / duration_s) | |
| def lowest_sole_point(model: mujoco.MjModel, data: mujoco.MjData) -> float: | |
| """Return the lowest collision-sphere point of either G1 foot in world Z.""" | |
| lowest = np.inf | |
| for site_name in (LEFT_FOOT, RIGHT_FOOT): | |
| site_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_SITE, site_name) | |
| foot_body_id = model.site_bodyid[site_id] | |
| for geom_id, body_id in enumerate(model.geom_bodyid): | |
| if body_id != foot_body_id: | |
| continue | |
| if model.geom_type[geom_id] != mujoco.mjtGeom.mjGEOM_SPHERE: | |
| continue | |
| lowest = min(lowest, data.geom_xpos[geom_id, 2] - model.geom_size[geom_id, 0]) | |
| if not np.isfinite(lowest): | |
| raise ValueError("could not find the G1 foot collision spheres") | |
| return lowest | |
| def joint_layout(model: mujoco.MjModel) -> tuple[list[str], np.ndarray, np.ndarray]: | |
| names = [] | |
| qpos_addresses = [] | |
| dof_addresses = [] | |
| for joint_id in range(model.njnt): | |
| if model.jnt_type[joint_id] == mujoco.mjtJoint.mjJNT_FREE: | |
| continue | |
| names.append(mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_JOINT, joint_id)) | |
| qpos_addresses.append(model.jnt_qposadr[joint_id]) | |
| dof_addresses.append(model.jnt_dofadr[joint_id]) | |
| return names, np.asarray(qpos_addresses), np.asarray(dof_addresses) | |
| def site_position(data: mujoco.MjData, site_id: int) -> np.ndarray: | |
| return data.site_xpos[site_id].copy() | |
| def site_rotation(data: mujoco.MjData, site_id: int) -> np.ndarray: | |
| return data.site_xmat[site_id].reshape(3, 3).copy() | |
| def orientation_error(current: np.ndarray, target: np.ndarray) -> np.ndarray: | |
| """Small-angle rotation from current orientation to target orientation.""" | |
| relative = target @ current.T | |
| return 0.5 * np.array(( | |
| relative[2, 1] - relative[1, 2], | |
| relative[0, 2] - relative[2, 0], | |
| relative[1, 0] - relative[0, 1], | |
| )) | |
| def solve_frame( | |
| model: mujoco.MjModel, | |
| data: mujoco.MjData, | |
| leg_limits: np.ndarray, | |
| variable_qpos: np.ndarray, | |
| variable_dofs: np.ndarray, | |
| foot_site_ids: tuple[int, int], | |
| foot_targets: tuple[np.ndarray, np.ndarray], | |
| foot_rotations: tuple[np.ndarray, np.ndarray], | |
| pelvis_target_y: float, | |
| ) -> None: | |
| """Hold both foot sites level while shifting the free-base pelvis laterally.""" | |
| position_jacobian = np.empty((3, model.nv)) | |
| rotation_jacobian = np.empty((3, model.nv)) | |
| regularization = 5e-5 | |
| # The previous frame is a warm start. A modest iteration limit retains a | |
| # smooth sequence and makes a solver failure visible to the caller. | |
| for _ in range(120): | |
| mujoco.mj_forward(model, data) | |
| errors = [] | |
| jacobians = [] | |
| for site_id, target_pos, target_rot in zip( | |
| foot_site_ids, foot_targets, foot_rotations, strict=True | |
| ): | |
| mujoco.mj_jacSite(model, data, position_jacobian, rotation_jacobian, site_id) | |
| errors.extend((target_pos - site_position(data, site_id)) * 12.0) | |
| errors.extend(orientation_error(site_rotation(data, site_id), target_rot) * 2.0) | |
| jacobians.append(position_jacobian[:, variable_dofs] * 12.0) | |
| jacobians.append(rotation_jacobian[:, variable_dofs] * 2.0) | |
| # The pelvis target creates a visible, intentional weight shift while | |
| # the foot constraints determine the compensating leg configuration. | |
| errors.append((pelvis_target_y - data.qpos[1]) * 1.5) | |
| pelvis_row = np.zeros((1, len(variable_dofs))) | |
| pelvis_row[0, 0] = 1.5 | |
| jacobians.append(pelvis_row) | |
| jacobian = np.concatenate(jacobians) | |
| error = np.asarray(errors) | |
| if np.max(np.abs(error)) < 1e-6: | |
| return | |
| delta = np.linalg.solve( | |
| jacobian.T @ jacobian + regularization * np.eye(len(variable_dofs)), | |
| jacobian.T @ error, | |
| ) | |
| data.qpos[variable_qpos] += np.clip(delta, -0.03, 0.03) | |
| leg_qpos = variable_qpos[2:] | |
| data.qpos[leg_qpos] = np.clip(data.qpos[leg_qpos], leg_limits[:, 0], leg_limits[:, 1]) | |
| raise RuntimeError( | |
| f"inverse kinematics did not converge for one frame, max residual={np.max(np.abs(error)):.6f}" | |
| ) | |
| def trajectory_times(settings: dict, clip: dict) -> np.ndarray: | |
| motion = settings["motion"] | |
| duration = ( | |
| motion["pre_hold_s"] + motion["weight_shift_s"] + clip["swing_duration_s"] | |
| + motion["post_shift_s"] + motion["final_hold_s"] | |
| ) | |
| return np.arange(round(duration * settings["fps"]) + 1) / settings["fps"] | |
| def generate_clip(model: mujoco.MjModel, settings: dict, clip: dict) -> dict[str, np.ndarray]: | |
| data = mujoco.MjData(model) | |
| mujoco.mj_resetDataKeyframe(model, data, 0) | |
| motion = settings["motion"] | |
| for side_name in ("left", "right"): | |
| for joint_name, value in motion["initial_leg_angles_rad"].items(): | |
| joint = model.joint(f"{side_name}_{joint_name}_joint") | |
| data.qpos[joint.qposadr[0]] = value | |
| mujoco.mj_forward(model, data) | |
| # Align the crouched starting pose to the plane using the collision sphere bottoms. | |
| data.qpos[2] -= lowest_sole_point(model, data) | |
| mujoco.mj_forward(model, data) | |
| initial_qpos = data.qpos.copy() | |
| names, qpos_addresses, dof_addresses = joint_layout(model) | |
| leg_names = LEFT_LEG + RIGHT_LEG | |
| leg_limits = np.array([model.joint(name).range for name in leg_names]) | |
| leg_indices = np.asarray([names.index(name) for name in leg_names]) | |
| variable_qpos = np.concatenate((np.array((1, 2)), qpos_addresses[leg_indices])) | |
| variable_dofs = np.concatenate((np.array((1, 2)), dof_addresses[leg_indices])) | |
| left_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_SITE, LEFT_FOOT) | |
| right_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_SITE, RIGHT_FOOT) | |
| initial_left = site_position(data, left_id) | |
| initial_right = site_position(data, right_id) | |
| rotations = (site_rotation(data, left_id), site_rotation(data, right_id)) | |
| times = trajectory_times(settings, clip) | |
| frames = len(times) | |
| joint_pos = np.empty((frames, len(names))) | |
| pelvis_pos = np.empty((frames, 3)) | |
| pelvis_quat = np.empty((frames, 4)) | |
| torso_pos = np.empty((frames, 3)) | |
| torso_quat = np.empty((frames, 4)) | |
| contact = np.zeros((frames, 2), dtype=bool) | |
| pelvis_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY, PELVIS) | |
| torso_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY, TORSO) | |
| shift_end = motion["pre_hold_s"] + motion["weight_shift_s"] | |
| swing_end = shift_end + clip["swing_duration_s"] | |
| target_left_y = initial_left[1] + clip["step_width_m"] | |
| # Shift onto the right side, follow the swinging foot, then settle between the feet. | |
| support_y = initial_right[1] + motion["support_offset_y_m"] | |
| landing_y = support_y + clip["step_width_m"] * motion["pelvis_travel_fraction"] | |
| final_y = (target_left_y + initial_right[1]) / 2.0 | |
| for frame, time_s in enumerate(times): | |
| swing = phase(time_s, shift_end, clip["swing_duration_s"]) | |
| lift = np.sin(np.pi * swing) ** 2 | |
| left_target = initial_left.copy() | |
| left_target[1] += clip["step_width_m"] * swing | |
| left_target[2] += motion["clearance_m"] * lift | |
| if time_s < shift_end: | |
| pelvis_y = initial_qpos[1] + (support_y - initial_qpos[1]) * phase( | |
| time_s, motion["pre_hold_s"], motion["weight_shift_s"] | |
| ) | |
| elif time_s < swing_end: | |
| pelvis_y = support_y + (landing_y - support_y) * swing | |
| else: | |
| pelvis_y = landing_y + (final_y - landing_y) * phase( | |
| time_s, swing_end, motion["post_shift_s"] | |
| ) | |
| try: | |
| solve_frame( | |
| model, data, leg_limits, variable_qpos, variable_dofs, | |
| (left_id, right_id), (left_target, initial_right), rotations, pelvis_y, | |
| ) | |
| except RuntimeError as error: | |
| raise RuntimeError(f"{clip['id']} at {time_s:.2f}s: {error}") from error | |
| mujoco.mj_forward(model, data) | |
| joint_pos[frame] = data.qpos[qpos_addresses] | |
| pelvis_pos[frame] = data.xpos[pelvis_id] | |
| pelvis_quat[frame] = data.xquat[pelvis_id] | |
| torso_pos[frame] = data.xpos[torso_id] | |
| torso_quat[frame] = data.xquat[torso_id] | |
| contact[frame] = (left_target[2] <= initial_left[2] + 1e-9, True) | |
| return { | |
| "time_s": times, | |
| "joint_names": np.asarray(names), | |
| "joint_pos_rad": joint_pos, | |
| "pelvis_pos_m": pelvis_pos, | |
| "pelvis_quat_wxyz": pelvis_quat, | |
| "torso_pos_m": torso_pos, | |
| "torso_quat_wxyz": torso_quat, | |
| "foot_contact_planned": contact, | |
| } | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--scene", type=Path, required=True, help="Pinned Menagerie scene.xml") | |
| parser.add_argument("--output", type=Path, required=True, help="Directory for generated NPZ clips") | |
| parser.add_argument( | |
| "--settings", type=Path, default=Path(__file__).with_name("settings.json"), | |
| help="Generator settings JSON", | |
| ) | |
| args = parser.parse_args() | |
| settings = json.loads(args.settings.read_text()) | |
| if settings["fps"] != FPS: | |
| raise ValueError(f"This generator writes {FPS} Hz clips only") | |
| model = mujoco.MjModel.from_xml_path(str(args.scene)) | |
| args.output.mkdir(parents=True, exist_ok=True) | |
| for clip in settings["clips"]: | |
| arrays = generate_clip(model, settings, clip) | |
| np.savez(args.output / f"{clip['id']}.npz", **arrays) | |
| if __name__ == "__main__": | |
| main() | |