File size: 10,660 Bytes
2b01b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Offline contracts: exact alignment and lossless source/action preservation."""

import json
import tempfile
import unittest
from pathlib import Path

import h5py
import numpy as np
from scipy.spatial.transform import Rotation

from oxt_array_mapping import CameraAlignmentError, align_camera_rows, build_arrays


class MappingTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.addCleanup(self.temp.cleanup)
        self.path = Path(self.temp.name) / "trajectory.h5"
        self.base = 1792185584000000000
        self.times = self.base + np.array([0, 70000001, 150000003, 240000007], dtype=np.int64)
        self.camera_ms = {
            "16478870": self.base // 1000000 + np.array([2, 72, 152, 242]),
            "36087771": self.base // 1000000 + np.array([4, 74, 154, 244]),
        }
        state_pose = np.array([[1., 2., 3., 0., np.pi / 2, 0.],
                               [2., 3., 4., .2, -.3, .4],
                               [3., 4., 5., 0., 0., 0.],
                               [4., 5., 6., -.4, .2, -.1]])
        action_pose = state_pose.copy()
        action_pose[:, :3] += [10., 20., 30.]
        self.wrench = np.arange(24, dtype=np.float64).reshape(4, 6) - 8.
        with h5py.File(self.path, "w") as h:
            h["observation/timestamp/control/step_start_unix_ns"] = self.times
            for serial, values in self.camera_ms.items():
                h["observation/timestamp/cameras/" + serial + "_frame_received"] = values
            h["observation/robot_state/joint_positions"] = np.arange(28, dtype=np.float64).reshape(4, 7) / 10
            h["action/joint_position"] = np.arange(28, dtype=np.float64).reshape(4, 7) + 100
            h["observation/robot_state/gripper_position"] = [0., .2, .7, 1.]
            for prefix, pose in [("action", action_pose), ("observation/robot_state", state_pose)]:
                h[prefix + "/cartesian_position"] = pose
                shifted = pose.copy()
                shifted[:, :3] += Rotation.from_euler("xyz", pose[:, 3:]).apply(np.tile([0, 0, .063], (4, 1)))
                h[prefix + "/cartesian_position_with_ft_offset"] = shifted
            h["action/command_dispatched"] = [False, True, True, False]
            h["observation/ft_sensor/wrench"] = self.wrench
            h["observation/ft_sensor/sample_index"] = np.array([2, 9, 18, 25], dtype=np.int64)
            h["diagnostics/signed_small"] = np.array([-8, -1, 0, 3], dtype=np.int16)
            h["diagnostics/optional_nan"] = np.array([np.nan, 2., 3., 4.], dtype=np.float32)
            h.create_dataset("action/controller_metadata_json", data=['{"note":"触觉"}', '{}', '{"k":2}', '{"k":3}'], dtype=h5py.string_dtype("utf-8"))
            h.create_dataset("diagnostics/fixed_string", data=np.array([b"a", b"bb", b"ccc", b"d"], dtype="S3"))

    def sdk_times(self, keep=None):
        if keep is None:
            keep = [0, 1, 2, 3]
        return {serial: values[keep] * 1000000 + 12345 for serial, values in self.camera_ms.items()}

    def test_two_camera_exact_match_drops_missing_final_row(self):
        rows, indices, report = align_camera_rows(self.path, self.sdk_times([0, 1, 2]))
        np.testing.assert_array_equal(rows, [0, 1, 2])
        self.assertEqual(report["dropped_control_rows"], [3])
        for serial in indices:
            np.testing.assert_array_equal(indices[serial], [0, 1, 2])
            self.assertEqual(report["cameras"][serial]["unmatched_control_rows"], [3])
        json.dumps(report, allow_nan=False)

    def test_intersection_preserves_real_frame_indices_with_internal_holes(self):
        sdk = self.sdk_times()
        sdk["16478870"] = sdk["16478870"][[0, 2, 3]]
        sdk["36087771"] = sdk["36087771"][[0, 1, 3]]
        rows, indices, report = align_camera_rows(self.path, sdk)
        np.testing.assert_array_equal(rows, [0, 3])
        np.testing.assert_array_equal(indices["16478870"], [0, 2])
        np.testing.assert_array_equal(indices["36087771"], [0, 2])
        self.assertEqual(report["dropped_control_rows"], [1, 2])

    def test_mismatched_clock_raises_diagnostics_not_nearest_guess(self):
        sdk = {key: times + 1000000 for key, times in self.sdk_times().items()}
        with self.assertRaises(CameraAlignmentError) as caught:
            align_camera_rows(self.path, sdk)
        self.assertEqual(caught.exception.report["dropped_control_rows"], [0, 1, 2, 3])
        self.assertIn("No control row", str(caught.exception))
        json.dumps(caught.exception.report)

    def test_rejects_ambiguous_milliseconds_and_missing_camera(self):
        sdk = self.sdk_times()
        sdk["16478870"][1] = sdk["16478870"][0] + 1
        with self.assertRaisesRegex(CameraAlignmentError, "milliseconds.*strictly increasing"):
            align_camera_rows(self.path, sdk)
        with self.assertRaisesRegex(CameraAlignmentError, "both recorded"):
            align_camera_rows(self.path, {"16478870": sdk["16478870"]})
        with h5py.File(self.path, "r+") as h:
            ds = h["observation/timestamp/cameras/16478870_frame_received"]
            ds[1] = ds[0]
        with self.assertRaisesRegex(CameraAlignmentError, "H5 frame_received_ms.*strictly increasing"):
            align_camera_rows(self.path, self.sdk_times())

    def test_preserves_true_actions_native_types_strings_and_flags(self):
        rows = np.array([0, 2, 3])
        arrays, metadata = build_arrays(self.path, rows, "Insert the pen.")
        np.testing.assert_array_equal(arrays["source_control_row"], rows)
        np.testing.assert_array_equal(arrays["command_dispatched"], [False, True, False])
        self.assertFalse(np.array_equal(arrays["action_joint_position"], arrays["right_arm_joints"]))
        self.assertFalse(np.array_equal(arrays["action_eef_pose"], arrays["right_wrist_pose"]))
        self.assertEqual(arrays["native__diagnostics__signed_small"].dtype, np.dtype("int16"))
        self.assertEqual(arrays["native__diagnostics__optional_nan"].dtype, np.dtype("float32"))
        self.assertTrue(np.isnan(arrays["native__diagnostics__optional_nan"][0]))
        self.assertEqual(arrays["native__action__controller_metadata_json"][0], '{"note":"触觉"}')
        self.assertEqual(arrays["native__action__controller_metadata_json"].dtype.kind, "U")
        self.assertEqual(arrays["native__diagnostics__fixed_string"].tolist(), ["a", "ccc", "d"])
        with h5py.File(self.path, "r") as h:
            for name, field in metadata["native_fields"].items():
                ds = h[field["source_path"]]
                expected = np.asarray(ds.asstr()[rows], dtype=str) if h5py.check_string_dtype(ds.dtype) else ds[rows]
                np.testing.assert_array_equal(arrays[name], expected)
        json.dumps(metadata, allow_nan=False)

    def test_pose_rotvec_and_recorded_63mm_are_separate_from_flange(self):
        arrays, metadata = build_arrays(self.path, [0, 1], "Wipe the board.")
        np.testing.assert_allclose(arrays["right_wrist_pose"][0], [1, 2, 3, 0, np.pi / 2, 0], atol=1e-14)
        np.testing.assert_allclose(arrays["state_eef_pose_with_ft_offset"][0], [1.063, 2, 3, 0, np.pi / 2, 0], atol=1e-14)
        # Arbitrary rotation is checked through a matrix, not equality of angle parameterizations.
        expected_matrix = Rotation.from_euler("xyz", [.2, -.3, .4]).as_matrix()
        np.testing.assert_allclose(Rotation.from_rotvec(arrays["right_wrist_pose"][1, 3:]).as_matrix(), expected_matrix, atol=1e-14)
        np.testing.assert_allclose(arrays["action_eef_pose"][0, :3], [11, 22, 33])
        np.testing.assert_allclose(arrays["action_eef_pose_with_ft_offset"][0, :3], [11.063, 22, 33])
        self.assertIn("pending", metadata["pose_semantics"]["canonical_wrist_transform_status"])

    def test_timestamp_subtraction_preserves_ns_and_original_episode_origin(self):
        arrays, metadata = build_arrays(self.path, [1, 3], "Press the button.")
        np.testing.assert_array_equal(arrays["timestamp_unix_ns"], self.times[[1, 3]])
        np.testing.assert_array_equal(arrays["timestamps"], np.array([70000001., 240000007.]) / 1e9)
        self.assertEqual(metadata["timestamp_origin_unix_ns"], self.base)

    def test_tactile_uses_torque_only_and_keeps_all_six_channels(self):
        arrays, metadata = build_arrays(self.path, [0, 1, 2, 3], "Hang the tape.")
        np.testing.assert_array_equal(arrays["ft_wrench"], self.wrench)
        np.testing.assert_array_equal(arrays["supplementary_tactile"], self.wrench)
        np.testing.assert_array_equal(arrays["right_tactile_data_wrist_torque"], self.wrench[:, None, 3:])
        self.assertEqual(arrays["right_tactile_area_wrist_torque"].tolist(), [[15]] * 4)
        self.assertEqual(arrays["right_tactile_sensor_wrist_torque"].tolist(), ["SRIM3813A1"] * 4)
        self.assertEqual(arrays["right_hand_joints_idx"].tolist(), [[28]] * 4)
        self.assertFalse(metadata["ft_semantics"]["software_gravity_compensation"])

    def test_camera_metadata_requires_exact_selected_timestamps(self):
        sdk = self.sdk_times([0, 2, 3])
        rows, indices, _ = align_camera_rows(self.path, sdk)
        selected = {s: sdk[s][idx] for s, idx in indices.items()}
        arrays, _ = build_arrays(self.path, rows, "Hang the tape.", indices, selected)
        for serial in indices:
            np.testing.assert_array_equal(arrays["camera_frame_index__" + serial], indices[serial])
            np.testing.assert_array_equal(arrays["camera_timestamp_unix_ns__" + serial], selected[serial])
        selected["16478870"] = selected["16478870"] + 1000000
        with self.assertRaisesRegex(ValueError, "does not exactly match"):
            build_arrays(self.path, rows, "Hang the tape.", indices, selected)

    def test_invalid_row_requests_are_rejected(self):
        for rows in [[], [2, 1], [1, 1], [-1, 0], [0, 4], [0., 1.], [True, False]]:
            with self.subTest(rows=rows), self.assertRaises(ValueError):
                build_arrays(self.path, rows, "Task.")

    def test_never_silently_drops_non_row_aligned_source_dataset(self):
        with h5py.File(self.path, "r+") as h:
            h["unhandled_static_data"] = [1, 2]
        with self.assertRaisesRegex(ValueError, "non-row-aligned"):
            build_arrays(self.path, [0, 1], "Task.")

    def test_flattened_name_collision_is_rejected(self):
        with h5py.File(self.path, "r+") as h:
            h["x/y"] = [1, 2, 3, 4]
            h["x__y"] = [5, 6, 7, 8]
        with self.assertRaisesRegex(ValueError, "collision"):
            build_arrays(self.path, [0, 1], "Task.")


if __name__ == "__main__":
    unittest.main()