|
| 1 | +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +"""Known-answer tests of the diversity metrics.""" |
| 5 | + |
| 6 | +import h5py |
| 7 | +import json |
| 8 | +import numpy as np |
| 9 | +from pathlib import Path |
| 10 | + |
| 11 | +import pytest |
| 12 | + |
| 13 | +from autodata_metrics import REGISTERED_METRICS, build_report |
| 14 | +from autodata_metrics.diversity import _digest, _sample |
| 15 | +from autodata_metrics.evidence import Evidence |
| 16 | + |
| 17 | + |
| 18 | +def _write(path: Path, episodes: list[dict[str, np.ndarray]]) -> str: |
| 19 | + with h5py.File(path, "w") as h5_file: |
| 20 | + data = h5_file.create_group("data") |
| 21 | + data.attrs["env_args"] = json.dumps({"env_name": "Test-v0"}) |
| 22 | + for index, arrays in enumerate(episodes): |
| 23 | + for key, array in arrays.items(): |
| 24 | + data.create_dataset(f"demo_{index}/{key}", data=array) |
| 25 | + return str(path) |
| 26 | + |
| 27 | + |
| 28 | +def _row(dataset: str, name: str) -> dict: |
| 29 | + return build_report(dataset, metrics={name: REGISTERED_METRICS[name]})["metrics"][name] |
| 30 | + |
| 31 | + |
| 32 | +def _starts(**positions: list[float]) -> dict[str, np.ndarray]: |
| 33 | + """An episode whose objects start at the given xy, or xyz.""" |
| 34 | + poses = { |
| 35 | + f"initial_state/rigid_object/{name}/root_pose": [[*position, *[0.0] * (3 - len(position)), 1.0, 0.0, 0.0, 0.0]] |
| 36 | + for name, position in positions.items() |
| 37 | + } |
| 38 | + return {"actions": np.zeros((2, 7)), **poses} |
| 39 | + |
| 40 | + |
| 41 | +def _poses(positions: np.ndarray) -> np.ndarray: |
| 42 | + poses = np.tile(np.eye(4), (len(positions), 1, 1)) |
| 43 | + poses[:, :3, 3] = positions |
| 44 | + return poses |
| 45 | + |
| 46 | + |
| 47 | +def _moving(**tracks: np.ndarray) -> dict[str, np.ndarray]: |
| 48 | + """An episode whose hands follow the given tracks.""" |
| 49 | + first = next(iter(tracks.values())) |
| 50 | + return { |
| 51 | + "actions": np.pad(first, ((0, 0), (0, 4))), |
| 52 | + **{f"obs/datagen_info/eef_pose/{hand}": _poses(track) for hand, track in tracks.items()}, |
| 53 | + } |
| 54 | + |
| 55 | + |
| 56 | +def test_start_layout_spread_counts_every_object_so_pinning_one_lowers_it(tmp_path): |
| 57 | + # x moves 2 cm and rises 10 cm, which does not count, and y moves 10 cm per episode while the table stays; a pair's |
| 58 | + # distance is the root-sum-square of the objects' horizontal ones. |
| 59 | + varied = [_starts(x=[0.02 * i, 0.0, 0.1 * i], y=[0.0, 0.1 * i], table=[0.5, 0.5]) for i in range(4)] |
| 60 | + pinned = [_starts(x=[0.0, 0.0], y=[0.0, 0.1 * i], table=[0.5, 0.5]) for i in range(4)] |
| 61 | + mean_step = np.mean([j - i for i in range(4) for j in range(i + 1, 4)]) |
| 62 | + |
| 63 | + varied_row = _row(_write(tmp_path / "varied.hdf5", varied), "start_layout_spread") |
| 64 | + pinned_row = _row(_write(tmp_path / "pinned.hdf5", pinned), "start_layout_spread") |
| 65 | + |
| 66 | + assert varied_row["value"] == pytest.approx(1000 * np.hypot(0.02, 0.1) * mean_step) |
| 67 | + assert pinned_row["value"] == pytest.approx(1000 * 0.1 * mean_step) |
| 68 | + |
| 69 | + |
| 70 | +def test_a_deformable_object_starts_at_its_nodes_centroid(tmp_path): |
| 71 | + # A rope's first node stays at the origin while its second lies 0, 10 and 20 cm away: its centroid moves 5 cm a step. |
| 72 | + episodes = [ |
| 73 | + { |
| 74 | + "actions": np.zeros((2, 7)), |
| 75 | + "initial_state/deformable_object/rope/nodal_position": [[[0.0] * 3, [0.1 * i, 0, 0]]], |
| 76 | + } |
| 77 | + for i in range(3) |
| 78 | + ] |
| 79 | + |
| 80 | + row = _row(_write(tmp_path / "d.hdf5", episodes), "start_layout_spread") |
| 81 | + |
| 82 | + assert row["value"] == pytest.approx((50.0 + 100.0 + 50.0) / 3) |
| 83 | + |
| 84 | + |
| 85 | +_LINE = np.linspace([0.0, 0.0, 0.0], [0.1, 0.0, 0.0], 11) |
| 86 | +_WITH_BALL, _WITHOUT_BALL = _starts(cube=[0.0, 0.0], ball=[0.1, 0.0]), _starts(cube=[0.1, 0.0]) |
| 87 | +_TWO_HANDS, _ONE_HAND = _moving(left=_LINE, right=_LINE), _moving(left=_LINE) |
| 88 | + |
| 89 | + |
| 90 | +@pytest.mark.parametrize( |
| 91 | + "name, episodes, reason", |
| 92 | + [ |
| 93 | + ("start_layout_spread", [_WITH_BALL], "needs two episodes"), |
| 94 | + ("start_layout_spread", [_WITH_BALL, _WITHOUT_BALL], "rigid_object/ball has no start pose in episode demo_1"), |
| 95 | + ("start_layout_spread", [_WITHOUT_BALL, _WITH_BALL], "rigid_object/ball has no start pose in episode demo_0"), |
| 96 | + ("workspace_spread", [_TWO_HANDS, _ONE_HAND], "episode demo_1 records no pose of right"), |
| 97 | + ("workspace_spread", [_ONE_HAND, _TWO_HANDS], "episode demo_0 records no pose of right"), |
| 98 | + ], |
| 99 | +) |
| 100 | +def test_a_spread_says_why_it_does_not_apply(tmp_path, name, episodes, reason): |
| 101 | + # Two episodes that hold the same actions are read in the opposite order once reversed, so in one of the two orders |
| 102 | + # a spread reads first the episode missing what the other records. |
| 103 | + row = _row(_write(tmp_path / "d.hdf5", episodes), name) |
| 104 | + |
| 105 | + assert row["status"] == "not_applicable" and row["reason"] == reason |
| 106 | + |
| 107 | + |
| 108 | +def test_repeated_episodes_spread_through_the_episodes_a_spread_reads(tmp_path): |
| 109 | + # 40 distinct episodes, 30 copies each: the 1,000 read include every one. |
| 110 | + episodes = [{"actions": np.full((2, 7), float(k))} for k in range(40) for _ in range(30)] |
| 111 | + path = _write(tmp_path / "d.hdf5", episodes) |
| 112 | + |
| 113 | + with h5py.File(path, "r") as h5_file: |
| 114 | + sample = _sample(Evidence(h5_file)) |
| 115 | + distinct = {_digest(episode) for episode in sample} |
| 116 | + |
| 117 | + assert len(sample) == 1000 and len(distinct) == 40 |
| 118 | + |
| 119 | + |
| 120 | +def test_the_workspace_refuses_a_hand_that_moves_more_than_8_cm_in_one_step(tmp_path): |
| 121 | + # The right hand moves 1 mm a step but once 9 cm, 0.5% of its steps; the left, which sorts first, stands still. |
| 122 | + steps = np.array([0.001] * 199 + [0.09]) |
| 123 | + episodes = [ |
| 124 | + _moving(right=np.stack([np.concatenate([[0.0], np.cumsum(steps)]), np.full(201, side), np.zeros(201)], axis=1)) |
| 125 | + | _moving(left=np.zeros((201, 3))) |
| 126 | + for side in (0.0, 0.1) |
| 127 | + ] |
| 128 | + |
| 129 | + row = _row(_write(tmp_path / "d.hdf5", episodes), "workspace_spread") |
| 130 | + |
| 131 | + assert row["status"] == "not_applicable" and "right moves 9 cm in one recorded step" in row["reason"] |
| 132 | + |
| 133 | + |
| 134 | +def test_workspace_counts_a_retraced_path_once(tmp_path): |
| 135 | + # Against a 30 cm line, the line with a 10 cm branch and the line traced five times with the same branch visit the |
| 136 | + # same space. |
| 137 | + line = np.linspace([0.0, 0.0, 0.0], [0.3, 0.0, 0.0], 31) |
| 138 | + branch = np.linspace([0.3, 0.0, 0.0], [0.3, 0.1, 0.0], 11)[1:] |
| 139 | + once = np.concatenate([line, branch]) |
| 140 | + retraced = np.concatenate([line, line[-2::-1], line[1:], line[-2::-1], line[1:], branch]) |
| 141 | + |
| 142 | + values = [ |
| 143 | + _row(_write(tmp_path / f"{i}.hdf5", [_moving(arm=line), _moving(arm=other)]), "workspace_spread") |
| 144 | + for i, other in enumerate((once, retraced)) |
| 145 | + ] |
| 146 | + |
| 147 | + assert values[0]["value"] == pytest.approx(values[1]["value"], abs=0.01) |
| 148 | + |
| 149 | + |
| 150 | +def test_the_workspace_is_how_far_apart_two_episodes_hands_run(tmp_path): |
| 151 | + # In one episode both hands sweep 10 cm along x, recorded at 0, 5 and 10 cm; in the other, the left hand rests |
| 152 | + # 10 cm beyond the sweep's end and the right 3 cm beside its middle. An offset of 1.25 mm keeps the sweep's 2.5 mm |
| 153 | + # samples off the 5 mm cell edges, so it keeps a point every 5 mm. The left sweep's points lie 150 mm from the |
| 154 | + # resting hand on average, which lies 100 mm from the nearest of them: 125 mm. The right sweep's points at x [mm] lie |
| 155 | + # hypot(30, x - 52.5) mm from the resting hand, which lies hypot(30, 2.5) mm from the nearest of them. |
| 156 | + offset = np.full(3, 0.00125) |
| 157 | + sweep = offset + [[0.0, 0.0, 0.0], [0.05, 0.0, 0.0], [0.1, 0.0, 0.0]] |
| 158 | + beyond = np.tile(offset + [0.2, 0.0, 0.0], (3, 1)) |
| 159 | + beside = np.tile(offset + [0.0525, 0.03, 0.0], (3, 1)) |
| 160 | + right = 0.5 * (np.mean([np.hypot(30.0, x - 52.5) for x in range(0, 101, 5)]) + np.hypot(30.0, 2.5)) |
| 161 | + episodes = [_moving(left=sweep, right=sweep), _moving(left=beyond, right=beside)] |
| 162 | + |
| 163 | + row = _row(_write(tmp_path / "d.hdf5", episodes), "workspace_spread") |
| 164 | + |
| 165 | + assert row["value"] == pytest.approx(0.5 * (125.0 + right), rel=1e-9) |
| 166 | + |
| 167 | + |
| 168 | +def test_the_workspace_does_not_depend_on_the_order_of_episodes(tmp_path): |
| 169 | + # 64 episodes make 2,016 pairs, more than the workspace measures; which ones depends on content, not order. |
| 170 | + starts = np.random.default_rng(0).uniform(-0.3, 0.3, (64, 3)) |
| 171 | + episodes = [_moving(arm=np.linspace(start, start + [0.1, 0.0, 0.0], 6)) for start in starts] |
| 172 | + |
| 173 | + values = [ |
| 174 | + _row(_write(tmp_path / f"{label}.hdf5", ordered), "workspace_spread")["value"] |
| 175 | + for label, ordered in (("forward", episodes), ("reversed", episodes[::-1])) |
| 176 | + ] |
| 177 | + |
| 178 | + assert values[0] == pytest.approx(values[1], rel=1e-12) |
0 commit comments