File size: 7,008 Bytes
a2e2083
eb0ddd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Loader for the OneHundredStyle-G1 dataset (needs only numpy).

A clip is a float32 array of shape (T, 281) sampled at 50 Hz, world frame z-up:

    columns   field          shape       notes
    0:3       root_pos       (T, 3)      pelvis position [m]
    3:7       root_quat      (T, 4)      pelvis orientation (w, x, y, z)
    7:36      joint_pos      (T, 29)     [rad], order = JOINT_NAMES
    36:39     root_lin_vel   (T, 3)      world frame [m/s]
    39:42     root_ang_vel   (T, 3)      world frame [rad/s]
    42:71     joint_vel      (T, 29)     [rad/s], order = JOINT_NAMES
    71:281    body_pos/quat  (T, 30, 7)  per body: position (3) + quaternion wxyz (4),
                                         world frame, order = BODY_NAMES

    python scripts/style100.py                # dataset summary
    python scripts/style100.py Zombie_FW      # one clip
"""
from __future__ import annotations

import json
import sys
from dataclasses import dataclass
from pathlib import Path

import numpy as np

ROOT = Path(__file__).resolve().parent.parent
FPS = 50
FRAME_DIM = 281

# Breadth-first joint order (the one Isaac Lab reports for the G1); MuJoCo orders joints differently.
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",
]

BODY_NAMES = [
    "pelvis", "left_hip_pitch_link", "right_hip_pitch_link", "waist_yaw_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",
]

# The ten takes of 100STYLE (not every style has TR2 / TR3).
TAKES = {
    "BR": "backward run", "BW": "backward walk", "FR": "forward run", "FW": "forward walk", "ID": "idle",
    "SR": "sidestep run", "SW": "sidestep walk", "TR1": "transitions 1", "TR2": "transitions 2",
    "TR3": "transitions 3",
}


def _partner(name: str) -> str:
    """Left / right counterpart of a joint or body; central ones map to themselves."""
    if name.startswith("left_"):
        return "right_" + name[5:]
    if name.startswith("right_"):
        return "left_" + name[6:]
    return name


# Mirror across the sagittal (x-z) plane: swap left and right, negate the roll and yaw joints.
_JOINT_SWAP = np.array([JOINT_NAMES.index(_partner(j)) for j in JOINT_NAMES])
_JOINT_SIGN = np.array([-1.0 if ("_roll_" in j or "_yaw_" in j) else 1.0 for j in JOINT_NAMES], dtype=np.float32)
_BODY_SWAP = np.array([BODY_NAMES.index(_partner(b)) for b in BODY_NAMES])


@dataclass(frozen=True)
class Clip:
    root_pos: np.ndarray      # (T, 3)
    root_quat: np.ndarray     # (T, 4) wxyz
    joint_pos: np.ndarray     # (T, 29)
    root_lin_vel: np.ndarray  # (T, 3) world
    root_ang_vel: np.ndarray  # (T, 3) world
    joint_vel: np.ndarray     # (T, 29)
    body_pos: np.ndarray      # (T, 30, 3) world
    body_quat: np.ndarray     # (T, 30, 4) wxyz, world

    def __len__(self) -> int:
        return len(self.root_pos)


def split(raw: np.ndarray) -> Clip:
    """Named views of a (T, 281) array (no copies)."""
    if raw.ndim != 2 or raw.shape[1] != FRAME_DIM:
        raise ValueError(f"expected shape (T, {FRAME_DIM}), got {raw.shape}")
    body = raw[:, 71:].reshape(len(raw), len(BODY_NAMES), 7)
    return Clip(raw[:, 0:3], raw[:, 3:7], raw[:, 7:36], raw[:, 36:39], raw[:, 39:42], raw[:, 42:71],
                body[..., :3], body[..., 3:])


def mirror(raw: np.ndarray) -> np.ndarray:
    """Left-right mirror image of a (T, 281) clip, as a new array of the same layout.

    Reflects the motion across the x-z plane of the world frame (y -> -y) and swaps the left and
    right limbs, so a clip that leads with the left foot leads with the right foot afterwards.
    Positions, orientations, velocities and body poses stay consistent with each other.
    """
    out = np.array(raw, dtype=np.float32, copy=True)
    c, m = split(raw), split(out)
    m.root_pos[:, 1] *= -1.0
    m.root_quat[:, [1, 3]] *= -1.0                      # (w, x, y, z) -> (w, -x, y, -z)
    m.joint_pos[:] = c.joint_pos[:, _JOINT_SWAP] * _JOINT_SIGN
    m.root_lin_vel[:, 1] *= -1.0
    m.root_ang_vel[:, [0, 2]] *= -1.0                   # angular velocity is a pseudo-vector
    m.joint_vel[:] = c.joint_vel[:, _JOINT_SWAP] * _JOINT_SIGN
    m.body_pos[:] = c.body_pos[:, _BODY_SWAP]
    m.body_pos[..., 1] *= -1.0
    m.body_quat[:] = c.body_quat[:, _BODY_SWAP]
    m.body_quat[..., [1, 3]] *= -1.0
    return out


def load_clip(path, mirrored: bool = False) -> Clip:
    """Load one clip as named arrays; ``mirrored=True`` returns its left-right mirror image."""
    path = Path(path)
    raw = np.load(path if path.is_absolute() or path.exists() else ROOT / path)
    return split(mirror(raw) if mirrored else raw)


def load_metadata(root=ROOT) -> list[dict]:
    """One dict per clip, in file order (see the dataset card for the fields)."""
    with open(Path(root) / "metadata.jsonl") as f:
        return [json.loads(line) for line in f]


def main():
    clips = load_metadata()
    if len(sys.argv) > 1:
        row = next((c for c in clips if c["id"] == sys.argv[1]), None)
        if row is None:
            raise SystemExit(f"unknown clip id: {sys.argv[1]}")
        clip = load_clip(ROOT / row["file"])
        print(json.dumps(row, indent=1))
        for name, value in vars(clip).items():
            print(f"{name:13s} {value.shape}")
        return
    frames = sum(c["n_frames"] for c in clips)
    print(f"{len(clips)} clips of {len({c['style'] for c in clips})} styles, {frames} frames "
          f"({frames / FPS / 3600:.1f} h at {FPS} Hz)")
    for take, label in TAKES.items():
        rows = [c for c in clips if c["take"] == take]
        print(f"  {take:4s} {label:14s} {len(rows):3d} clips  {sum(c['n_frames'] for c in rows) / FPS / 60:6.1f} min")


if __name__ == "__main__":
    main()