"""Shared definitions and utilities for BONES-SEED G1 converters.""" from __future__ import annotations from functools import lru_cache from pathlib import Path import mujoco import numpy as np from scipy.spatial.transform import Rotation as R MT_JOINT_NAMES = [ "left_hip_pitch_joint", "left_hip_roll_joint", "left_hip_yaw_joint", "left_knee_joint", "left_ankle_pitch_joint", "left_ankle_roll_joint", "right_hip_pitch_joint", "right_hip_roll_joint", "right_hip_yaw_joint", "right_knee_joint", "right_ankle_pitch_joint", "right_ankle_roll_joint", "waist_yaw_joint", "waist_roll_joint", "waist_pitch_joint", "left_shoulder_pitch_joint", "left_shoulder_roll_joint", "left_shoulder_yaw_joint", "left_elbow_joint", "left_wrist_roll_joint", "left_wrist_pitch_joint", "left_wrist_yaw_joint", "right_shoulder_pitch_joint", "right_shoulder_roll_joint", "right_shoulder_yaw_joint", "right_elbow_joint", "right_wrist_roll_joint", "right_wrist_pitch_joint", "right_wrist_yaw_joint", ] ISAAC_JOINT_NAMES = [ "left_hip_pitch_joint", "right_hip_pitch_joint", "waist_yaw_joint", "left_hip_roll_joint", "right_hip_roll_joint", "waist_roll_joint", "left_hip_yaw_joint", "right_hip_yaw_joint", "waist_pitch_joint", "left_knee_joint", "right_knee_joint", "left_shoulder_pitch_joint", "right_shoulder_pitch_joint", "left_ankle_pitch_joint", "right_ankle_pitch_joint", "left_shoulder_roll_joint", "right_shoulder_roll_joint", "left_ankle_roll_joint", "right_ankle_roll_joint", "left_shoulder_yaw_joint", "right_shoulder_yaw_joint", "left_elbow_joint", "right_elbow_joint", "left_wrist_roll_joint", "right_wrist_roll_joint", "left_wrist_pitch_joint", "right_wrist_pitch_joint", "left_wrist_yaw_joint", "right_wrist_yaw_joint", ] MT_BODY_NAMES = [ "pelvis", "left_hip_pitch_link", "left_hip_roll_link", "left_hip_yaw_link", "left_knee_link", "left_ankle_pitch_link", "left_ankle_roll_link", "right_hip_pitch_link", "right_hip_roll_link", "right_hip_yaw_link", "right_knee_link", "right_ankle_pitch_link", "right_ankle_roll_link", "torso_link", "left_shoulder_pitch_link", "left_shoulder_roll_link", "left_shoulder_yaw_link", "left_elbow_link", "left_wrist_roll_link", "right_shoulder_pitch_link", "right_shoulder_roll_link", "right_shoulder_yaw_link", "right_elbow_link", "right_wrist_roll_link", "head_mimic", "left_hand_mimic", "right_hand_mimic", ] ISAAC_BODY_NAMES = [ "pelvis", "left_hip_pitch_link", "right_hip_pitch_link", "pelvis_contour_link", "left_hip_roll_link", "right_hip_roll_link", "waist_roll_link", "left_hip_yaw_link", "right_hip_yaw_link", "torso_link", "left_knee_link", "right_knee_link", "left_shoulder_pitch_link", "right_shoulder_pitch_link", "left_ankle_pitch_link", "right_ankle_pitch_link", "left_shoulder_roll_link", "right_shoulder_roll_link", "left_ankle_roll_link", "right_ankle_roll_link", "left_shoulder_yaw_link", "right_shoulder_yaw_link", "left_elbow_link", "right_elbow_link", "left_wrist_roll_link", "right_wrist_roll_link", "left_wrist_pitch_link", "right_wrist_pitch_link", "left_wrist_yaw_link", "right_wrist_yaw_link", ] ROOT_TRANSLATION_COLUMNS = [ "root_translateX", "root_translateY", "root_translateZ", ] ROOT_ROTATION_COLUMNS = [ "root_rotateX", "root_rotateY", "root_rotateZ", ] def validate_fps(source_fps: int, target_fps: int) -> None: if source_fps <= 0 or target_fps <= 0: raise ValueError("source_fps and target_fps must both be positive") def load_csv_motion(csv_path: str | Path) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """Load root position, root quaternion (xyzw), and MT-order DOF positions.""" csv_path = Path(csv_path) if not csv_path.is_file(): raise FileNotFoundError(f"CSV file not found: {csv_path}") data = np.genfromtxt(csv_path, delimiter=",", names=True) data = np.atleast_1d(data) if data.size == 0 or data.dtype.names is None: raise ValueError(f"CSV contains no motion frames: {csv_path}") required_columns = ( ROOT_TRANSLATION_COLUMNS + ROOT_ROTATION_COLUMNS + [f"{name}_dof" for name in MT_JOINT_NAMES] ) missing = [name for name in required_columns if name not in data.dtype.names] if missing: raise ValueError( f"CSV is missing {len(missing)} required column(s): {', '.join(missing)}" ) root_pos = np.column_stack([data[name] for name in ROOT_TRANSLATION_COLUMNS]) root_pos = root_pos.astype(np.float32) / 100.0 root_euler_xyz_deg = np.column_stack( [data[name] for name in ROOT_ROTATION_COLUMNS] ) root_rot_xyzw = R.from_euler( "xyz", root_euler_xyz_deg, degrees=True ).as_quat().astype(np.float32) dof_pos_deg = np.column_stack( [data[f"{name}_dof"] for name in MT_JOINT_NAMES] ).astype(np.float32) dof_pos = np.deg2rad(dof_pos_deg).astype(np.float32) for name, value in ( ("root_pos", root_pos), ("root_rot_xyzw", root_rot_xyzw), ("dof_pos", dof_pos), ): if not np.isfinite(value).all(): raise ValueError(f"{name} contains NaN or Inf: {csv_path}") return root_pos, root_rot_xyzw, dof_pos @lru_cache(maxsize=8) def load_g1_model(g1_xml: str) -> mujoco.MjModel: """Load and validate a G1 MJCF model, cached once per worker process.""" xml_path = Path(g1_xml).expanduser().resolve() if not xml_path.is_file(): raise FileNotFoundError(f"G1 MJCF file not found: {xml_path}") model = mujoco.MjModel.from_xml_path(str(xml_path)) expected_nq = 7 + len(MT_JOINT_NAMES) if model.nq != expected_nq: raise ValueError( f"Expected G1 model nq={expected_nq}, but {xml_path} has nq={model.nq}" ) model_joint_names = [] for joint_id in range(model.njnt): if model.jnt_type[joint_id] == mujoco.mjtJoint.mjJNT_FREE: continue name = mujoco.mj_id2name( model, mujoco.mjtObj.mjOBJ_JOINT, joint_id ) if name: model_joint_names.append(name) if model_joint_names != MT_JOINT_NAMES: raise ValueError( "G1 MJCF joint order does not match the expected MT order.\n" f"Expected: {MT_JOINT_NAMES}\n" f"Found: {model_joint_names}" ) return model def require_body_id(model: mujoco.MjModel, body_name: str) -> int: body_id = mujoco.mj_name2id( model, mujoco.mjtObj.mjOBJ_BODY, body_name ) if body_id < 0: raise ValueError(f"G1 MJCF is missing required body: {body_name}") return body_id def output_frame_count(frame_count: int, source_fps: int, target_fps: int) -> int: return max(1, int(round(frame_count * target_fps / source_fps))) def interpolate_linear(array: np.ndarray, new_frame_count: int) -> np.ndarray: """Linearly resample an array along its first dimension.""" old_frame_count = len(array) if new_frame_count == old_frame_count: return array.copy() if old_frame_count == 1: return np.repeat(array, new_frame_count, axis=0) new_times = np.linspace(0, old_frame_count - 1, new_frame_count) result = np.empty( (new_frame_count,) + array.shape[1:], dtype=np.float32 ) for index, time in enumerate(new_times): lower = int(np.floor(time)) upper = min(lower + 1, old_frame_count - 1) fraction = time - lower result[index] = array[lower] + fraction * ( array[upper] - array[lower] ) return result def interpolate_quaternions( quaternions: np.ndarray, new_frame_count: int ) -> np.ndarray: """SLERP quaternion arrays along the first dimension.""" old_frame_count = len(quaternions) if new_frame_count == old_frame_count: result = quaternions.copy() elif old_frame_count == 1: result = np.repeat(quaternions, new_frame_count, axis=0) else: result = np.empty( (new_frame_count,) + quaternions.shape[1:], dtype=np.float32 ) new_times = np.linspace(0, old_frame_count - 1, new_frame_count) for index, time in enumerate(new_times): lower = int(np.floor(time)) upper = min(lower + 1, old_frame_count - 1) fraction = time - lower q0 = quaternions[lower] q1 = quaternions[upper] dot = np.sum(q0 * q1, axis=-1, keepdims=True) q1 = np.where(dot < 0.0, -q1, q1) dot = np.clip(np.abs(dot), 0.0, 1.0) theta = np.arccos(dot) sin_theta = np.sin(theta) small = sin_theta < 1e-6 denominator = np.maximum(sin_theta, 1e-6) weight0 = np.where( small, 1.0 - fraction, np.sin((1.0 - fraction) * theta) / denominator, ) weight1 = np.where( small, fraction, np.sin(fraction * theta) / denominator, ) result[index] = weight0 * q0 + weight1 * q1 norms = np.linalg.norm(result, axis=-1, keepdims=True) if np.any(norms < 1e-8): raise ValueError("Encountered a zero-length quaternion during resampling") return (result / norms).astype(np.float32) def finite_difference(array: np.ndarray, fps: int) -> np.ndarray: """Compute a time derivative using forward/backward and central differences.""" derivative = np.zeros_like(array, dtype=np.float32) if len(array) == 1: return derivative dt = 1.0 / fps derivative[0] = (array[1] - array[0]) / dt derivative[-1] = (array[-1] - array[-2]) / dt if len(array) > 2: derivative[1:-1] = (array[2:] - array[:-2]) / (2.0 * dt) return derivative def body_angular_velocity_wxyz( body_quat_wxyz: np.ndarray, fps: int ) -> np.ndarray: """Compute world-frame body angular velocity from wxyz quaternions.""" angular_velocity = np.zeros( body_quat_wxyz.shape[:-1] + (3,), dtype=np.float32 ) if len(body_quat_wxyz) == 1: return angular_velocity dt = 1.0 / fps for frame in range(len(body_quat_wxyz) - 1): q0_xyzw = body_quat_wxyz[frame][:, [1, 2, 3, 0]] q1_xyzw = body_quat_wxyz[frame + 1][:, [1, 2, 3, 0]] rotation0 = R.from_quat(q0_xyzw) rotation1 = R.from_quat(q1_xyzw) delta = rotation1 * rotation0.inv() angular_velocity[frame] = delta.as_rotvec() / dt angular_velocity[-1] = angular_velocity[-2] return angular_velocity def ensure_output_parent(output_path: str | Path) -> Path: output_path = Path(output_path) output_path.parent.mkdir(parents=True, exist_ok=True) return output_path