File size: 6,458 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
#!/usr/bin/env python3
"""Validate MT and Isaac NPZ files produced by this repository."""

from __future__ import annotations

import argparse
from pathlib import Path

import numpy as np

from converter_common import MT_BODY_NAMES, MT_JOINT_NAMES


MT_FIELDS = {
    "root_pos",
    "root_rot",
    "dof_pos",
    "local_body_pos",
    "joint_names",
    "body_names",
    "fps",
}
ISAAC_FIELDS = {
    "fps",
    "joint_pos",
    "joint_vel",
    "body_pos_w",
    "body_quat_w",
    "body_lin_vel_w",
    "body_ang_vel_w",
}


def infer_format(keys: set[str]) -> str:
    if MT_FIELDS.issubset(keys):
        return "mt"
    if ISAAC_FIELDS.issubset(keys):
        return "isaac"
    raise ValueError(f"Cannot infer format from fields: {sorted(keys)}")


def require_shape(
    data: np.lib.npyio.NpzFile,
    name: str,
    expected: tuple[int, ...],
) -> None:
    actual = data[name].shape
    if actual != expected:
        raise ValueError(f"{name}: expected shape {expected}, found {actual}")


def require_float32(data: np.lib.npyio.NpzFile, fields: list[str]) -> None:
    for name in fields:
        if data[name].dtype != np.float32:
            raise ValueError(
                f"{name}: expected dtype float32, found {data[name].dtype}"
            )
        if not np.isfinite(data[name]).all():
            raise ValueError(f"{name}: contains NaN or Inf")


def validate_mt(data: np.lib.npyio.NpzFile) -> None:
    missing = MT_FIELDS - set(data.files)
    if missing:
        raise ValueError(f"Missing MT fields: {sorted(missing)}")

    frame_count = data["dof_pos"].shape[0]
    if frame_count < 1:
        raise ValueError("MT motion contains no frames")

    require_shape(data, "root_pos", (frame_count, 3))
    require_shape(data, "root_rot", (frame_count, 4))
    require_shape(data, "dof_pos", (frame_count, 29))
    require_shape(data, "local_body_pos", (frame_count, 27, 3))
    require_shape(data, "joint_names", (29,))
    require_shape(data, "body_names", (27,))
    require_shape(data, "fps", (1,))
    require_float32(
        data, ["root_pos", "root_rot", "dof_pos", "local_body_pos"]
    )

    if data["fps"].dtype != np.int64 or int(data["fps"][0]) <= 0:
        raise ValueError("fps must be a positive int64 array with shape (1,)")
    if data["joint_names"].tolist() != MT_JOINT_NAMES:
        raise ValueError("joint_names does not match the MT joint order")
    if data["body_names"].tolist() != MT_BODY_NAMES:
        raise ValueError("body_names does not match the MT body order")

    quat_norm = np.linalg.norm(data["root_rot"], axis=-1)
    if not np.allclose(quat_norm, 1.0, atol=1e-4):
        raise ValueError("root_rot contains non-unit quaternions")
    if not np.allclose(data["local_body_pos"][:, 0], 0.0, atol=1e-4):
        raise ValueError("pelvis local_body_pos is not approximately zero")


def validate_isaac(data: np.lib.npyio.NpzFile) -> None:
    missing = ISAAC_FIELDS - set(data.files)
    if missing:
        raise ValueError(f"Missing Isaac fields: {sorted(missing)}")

    frame_count = data["joint_pos"].shape[0]
    if frame_count < 1:
        raise ValueError("Isaac motion contains no frames")

    require_shape(data, "fps", (1,))
    require_shape(data, "joint_pos", (frame_count, 29))
    require_shape(data, "joint_vel", (frame_count, 29))
    require_shape(data, "body_pos_w", (frame_count, 30, 3))
    require_shape(data, "body_quat_w", (frame_count, 30, 4))
    require_shape(data, "body_lin_vel_w", (frame_count, 30, 3))
    require_shape(data, "body_ang_vel_w", (frame_count, 30, 3))
    require_float32(
        data,
        [
            "joint_pos",
            "joint_vel",
            "body_pos_w",
            "body_quat_w",
            "body_lin_vel_w",
            "body_ang_vel_w",
        ],
    )

    if data["fps"].dtype != np.int64 or int(data["fps"][0]) <= 0:
        raise ValueError("fps must be a positive int64 array with shape (1,)")
    quat_norm = np.linalg.norm(data["body_quat_w"], axis=-1)
    if not np.allclose(quat_norm, 1.0, atol=1e-4):
        raise ValueError("body_quat_w contains non-unit quaternions")
    if not np.allclose(
        data["body_pos_w"][:, 0], data["body_pos_w"][:, 3], atol=1e-6
    ):
        raise ValueError("pelvis_contour_link must duplicate pelvis position")
    if not np.allclose(
        data["body_quat_w"][:, 0], data["body_quat_w"][:, 3], atol=1e-6
    ):
        raise ValueError("pelvis_contour_link must duplicate pelvis rotation")


def validate_file(path: Path, expected_format: str) -> str:
    with np.load(path, allow_pickle=False) as data:
        actual_format = infer_format(set(data.files))
        if expected_format != "auto" and actual_format != expected_format:
            raise ValueError(
                f"expected {expected_format}, inferred {actual_format}"
            )
        if actual_format == "mt":
            validate_mt(data)
        else:
            validate_isaac(data)
    return actual_format


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Validate MT/Isaac NPZ files")
    parser.add_argument("path", type=Path, help="NPZ file or directory")
    parser.add_argument(
        "--format", choices=("auto", "mt", "isaac"), default="auto"
    )
    parser.add_argument(
        "--limit", type=int, help="Validate only the first N files"
    )
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    target = args.path.expanduser().resolve()
    if target.is_file():
        paths = [target]
    elif target.is_dir():
        paths = sorted(target.rglob("*.npz"))
    else:
        raise SystemExit(f"Path not found: {target}")

    if args.limit is not None:
        if args.limit <= 0:
            raise SystemExit("--limit must be positive")
        paths = paths[: args.limit]
    if not paths:
        raise SystemExit(f"No NPZ files found: {target}")

    failures = []
    counts = {"mt": 0, "isaac": 0}
    for path in paths:
        try:
            actual_format = validate_file(path, args.format)
            counts[actual_format] += 1
        except Exception as error:
            failures.append((path, error))
            print(f"FAIL\t{path}\t{error}")

    print(
        f"Validated {len(paths)} file(s): "
        f"mt={counts['mt']}, isaac={counts['isaac']}, "
        f"failed={len(failures)}"
    )
    if failures:
        raise SystemExit(1)


if __name__ == "__main__":
    main()