File size: 11,097 Bytes
e0803b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
"""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