Download tools/test_oxt_array_mapping.py from Alan0928/franka_ft_oxt: direct link, hf CLI and curl.
- Browser
- Download file 10.7 kB
-
https://huggingface.co/datasets/Alan0928/franka_ft_oxt/resolve/main/tools/test_oxt_array_mapping.py
- Command line
-
hf download hf://datasets/Alan0928/franka_ft_oxt/tools/test_oxt_array_mapping.py
-
curl -L -o test_oxt_array_mapping.py https://huggingface.co/datasets/Alan0928/franka_ft_oxt/resolve/main/tools/test_oxt_array_mapping.py
10.7 kB
| """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() | |