File size: 16,000 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
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
"""Lossless row selection plus explicitly labelled OXT-compatible state arrays.

This module reads offline trajectory HDF5 files. It neither decodes camera
files nor transforms sensor wrenches, calibrates a TCP, or controls hardware.
"""

from pathlib import Path

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


_CONTROL_TIME = "observation/timestamp/control/step_start_unix_ns"
_CAMERA_PREFIX = "observation/timestamp/cameras/"


class CameraAlignmentError(ValueError):
    """Exact camera alignment failed; ``report`` contains JSON-safe diagnostics."""

    def __init__(self, message, report):
        super().__init__(message)
        self.report = report


def _integer_vector(value, name, nonnegative=True):
    array = np.asarray(value)
    if array.ndim != 1 or array.dtype.kind not in "iu" or not len(array):
        raise ValueError(name + " must be a nonempty one-dimensional integer array")
    if array.dtype.kind == "u" and np.any(array > np.iinfo(np.int64).max):
        raise ValueError(name + " exceeds int64 range")
    array = array.astype(np.int64, copy=True)
    if nonnegative and np.any(array < 0):
        raise ValueError(name + " must be nonnegative")
    return array


def _strictly_increasing(array, name):
    # Comparisons avoid overflow possible with np.diff on arbitrary int64 input.
    if np.any(array[1:] <= array[:-1]):
        raise ValueError(name + " must be unique and strictly increasing")


def _camera_serials(h5):
    if _CAMERA_PREFIX.rstrip("/") not in h5:
        raise ValueError("Trajectory has no camera timestamps")
    suffix = "_frame_received"
    return sorted(name[:-len(suffix)] for name in h5[_CAMERA_PREFIX]
                  if name.endswith(suffix))


def align_camera_rows(h5_path, camera_timestamps):
    """Intersect exact IMAGE-time matches from both physical camera streams.

    ``camera_timestamps`` maps each recorded serial to its complete decoded SDK
    IMAGE timestamp array, in integer Unix nanoseconds and original frame order.
    SDK times are floored to milliseconds to match DROID's recorded precision.
    Both raw nanoseconds and floored milliseconds must be unique and strictly
    increasing; the HDF5 millisecond sequences must be likewise unambiguous.

    Return ``(control_rows, frame_indices_by_serial, report)``. Missing camera
    rows are explicitly reported and removed from the intersection. If there
    is no common exact match, raise CameraAlignmentError with diagnostics;
    no nearest-neighbour, clock-offset, or frame-repeat guess is attempted.
    """
    report = {
        "method": "exact SDK IMAGE unix_ns // 1000000 == H5 frame_received_ms",
        "cameras": {},
        "interpolation": "none",
    }
    try:
        if not isinstance(camera_timestamps, dict):
            raise ValueError("camera_timestamps must map both serials to SDK timestamps")
        with h5py.File(h5_path, "r") as h5:
            serials = _camera_serials(h5)
            report["recorded_serials"] = serials
            report["provided_serials"] = sorted(str(k) for k in camera_timestamps)
            if len(serials) != 2 or set(camera_timestamps) != set(serials):
                raise ValueError("Exactly both recorded physical camera serials are required")
            control_time = _integer_vector(h5[_CONTROL_TIME][:], _CONTROL_TIME)
            _strictly_increasing(control_time, _CONTROL_TIME)
            count = len(control_time)
            report["original_control_rows"] = count
            per_camera_indices = {}
            all_matched = np.ones(count, dtype=bool)
            for serial in serials:
                sdk_ns = _integer_vector(camera_timestamps[serial], serial + " SDK timestamp_ns")
                _strictly_increasing(sdk_ns, serial + " SDK timestamp_ns")
                sdk_ms = sdk_ns // 1000000
                _strictly_increasing(sdk_ms, serial + " SDK milliseconds")
                h5_ms = _integer_vector(h5[_CAMERA_PREFIX + serial + "_frame_received"][:],
                                        serial + " H5 frame_received_ms")
                _strictly_increasing(h5_ms, serial + " H5 frame_received_ms")
                if len(h5_ms) != count:
                    raise ValueError(serial + " H5 camera rows differ from control row count")
                indices = np.searchsorted(sdk_ms, h5_ms)
                valid = indices < len(sdk_ms)
                valid[valid] &= sdk_ms[indices[valid]] == h5_ms[valid]
                indices = indices.astype(np.int64)
                indices[~valid] = -1
                per_camera_indices[serial] = indices
                all_matched &= valid
                report["cameras"][serial] = {
                    "sdk_frames": len(sdk_ns),
                    "matched_control_rows": int(valid.sum()),
                    "unmatched_control_rows": np.flatnonzero(~valid).tolist(),
                    "sdk_unix_ns_range": [int(sdk_ns[0]), int(sdk_ns[-1])],
                    "h5_unix_ms_range": [int(h5_ms[0]), int(h5_ms[-1])],
                }
            rows = np.flatnonzero(all_matched).astype(np.int64)
            report["selected_control_rows"] = rows.tolist()
            report["selected_row_count"] = len(rows)
            report["dropped_control_rows"] = np.flatnonzero(~all_matched).tolist()
            if not len(rows):
                raise ValueError("No control row has an exact timestamp match in both cameras")
            result = {serial: indices[rows].copy()
                      for serial, indices in per_camera_indices.items()}
            for serial, indices in result.items():
                _strictly_increasing(indices, serial + " matched frame indices")
                report["cameras"][serial]["selected_frame_indices"] = indices.tolist()
                report["cameras"][serial]["unused_sdk_frame_count"] = (
                    report["cameras"][serial]["sdk_frames"] - len(indices)
                )
            return rows, result, report
    except (KeyError, TypeError, ValueError) as error:
        report["error"] = str(error)
        raise CameraAlignmentError(str(error), report) from error


def _read_rows(dataset, rows, total):
    if not dataset.shape or dataset.shape[0] != total:
        raise ValueError("Cannot preserve non-row-aligned dataset: " + dataset.name)
    string_info = h5py.check_string_dtype(dataset.dtype)
    if string_info is not None:
        # Fixed NumPy Unicode is accepted by Zarr without an object codec.
        # Decoding preserves UTF-8/ASCII content; metadata retains HDF5 dtype.
        value = np.asarray(dataset.asstr()[rows], dtype=str)
    elif dataset.dtype.kind in "biufc":
        value = np.asarray(dataset[rows]).copy()
    else:
        raise ValueError("Unsupported raw dataset dtype at " + dataset.name + ": " + str(dataset.dtype))
    return value


def _pose_rotvec(pose, name):
    if pose.ndim != 2 or pose.shape[1] != 6 or not np.isfinite(pose).all():
        raise ValueError(name + " must contain finite xyz/Euler-xyz poses with shape (T,6)")
    return np.concatenate((pose[:, :3], Rotation.from_euler("xyz", pose[:, 3:]).as_rotvec()), axis=1)


def build_arrays(h5_path, rows, task_instruction, camera_indices=None,
                 camera_timestamp_ns=None):
    """Return ``(flat_data_arrays, JSON_serializable_metadata)`` for selected rows.

    Standard wrist poses retain the original robot-model EEF/flange reference,
    with Euler xyz converted to rotation vectors. No canonical wrist/TCP or FT
    transformation is inferred. ``native__`` arrays preserve every original
    row-aligned dataset, including strings, exact timestamps and optional NaNs.

    Camera dictionaries, when provided, contain *already selected* frame
    indices/timestamps, each with length ``len(rows)``. Their serials must match
    both recorded cameras. Nanosecond timestamps are checked against the
    selected H5 milliseconds. Original file attributes and high-rate FT sidecar
    preservation are the export orchestrator's responsibility.
    """
    rows = _integer_vector(rows, "rows")
    _strictly_increasing(rows, "rows")
    if not isinstance(task_instruction, str) or not task_instruction.strip():
        raise ValueError("task_instruction must be a nonempty concrete task string")
    arrays, native_fields = {}, {}
    with h5py.File(h5_path, "r") as h5:
        all_time = _integer_vector(h5[_CONTROL_TIME][:], _CONTROL_TIME)
        _strictly_increasing(all_time, _CONTROL_TIME)
        total = len(all_time)
        if rows[-1] >= total:
            raise ValueError("rows contains an index outside the trajectory")

        def preserve(path, dataset):
            if not isinstance(dataset, h5py.Dataset):
                return
            name = "native__" + path.replace("/", "__")
            if name in arrays:
                raise ValueError("Flattened native field name collision: " + name)
            arrays[name] = _read_rows(dataset, rows, total)
            native_fields[name] = {"source_path": path, "source_dtype": str(dataset.dtype)}

        h5.visititems(preserve)

        def original(path, shape=None, finite=False):
            value = arrays["native__" + path.replace("/", "__")].copy()
            if shape is not None and value.shape != (len(rows),) + shape:
                raise ValueError(path + " has unexpected shape " + str(value.shape))
            if finite and (value.dtype.kind not in "biuf" or not np.isfinite(value).all()):
                raise ValueError(path + " must contain finite numeric values")
            return value

        timestamps = all_time[rows]
        arrays.update({
            "timestamps": (timestamps - all_time[0]).astype(np.float64) / 1e9,
            "timestamp_unix_ns": timestamps.copy(),
            "source_control_row": rows.copy(),
            "right_arm_joints": original("observation/robot_state/joint_positions", (7,), True),
            "right_wrist_pose": _pose_rotvec(original("observation/robot_state/cartesian_position"), "state EEF"),
            "right_hand_joints": original("observation/robot_state/gripper_position", (), True)[:, None],
            "right_hand_joints_idx": np.full((len(rows), 1), 28, dtype=np.int64),
            "sub_task_instruction": np.full(len(rows), task_instruction, dtype="U" + str(len(task_instruction))),
            "action_joint_position": original("action/joint_position", (7,), True),
            "action_eef_pose": _pose_rotvec(original("action/cartesian_position"), "action EEF"),
            "action_eef_pose_with_ft_offset": _pose_rotvec(original("action/cartesian_position_with_ft_offset"), "offset action EEF"),
            "state_eef_pose_with_ft_offset": _pose_rotvec(original("observation/robot_state/cartesian_position_with_ft_offset"), "offset state EEF"),
            "command_dispatched": original("action/command_dispatched", ()),
        })
        if arrays["command_dispatched"].dtype.kind != "b":
            raise ValueError("action/command_dispatched must be boolean")
        wrench = original("observation/ft_sensor/wrench", (6,), True)
        arrays.update({
            "ft_wrench": wrench.copy(),
            "supplementary_tactile": wrench.copy(),
            "right_tactile_data_wrist_torque": wrench[:, None, 3:].copy(),
            "right_tactile_area_wrist_torque": np.full((len(rows), 1), 15, dtype=np.int64),
            "right_tactile_sensor_wrist_torque": np.full(len(rows), "SRIM3813A1", dtype="U10"),
            "right_tactile_type_wrist_torque": np.full(len(rows), "state", dtype="U5"),
        })
        serials = _camera_serials(h5) if camera_indices is not None or camera_timestamp_ns is not None else []
        for supplied, label, prefix in (
                (camera_indices, "camera_indices", "camera_frame_index__"),
                (camera_timestamp_ns, "camera_timestamp_ns", "camera_timestamp_unix_ns__")):
            if supplied is None:
                continue
            if not isinstance(supplied, dict) or len(serials) != 2 or set(supplied) != set(serials):
                raise ValueError(label + " must include exactly both recorded camera serials")
            for serial in serials:
                values = _integer_vector(supplied[serial], label + "[" + serial + "]")
                if len(values) != len(rows):
                    raise ValueError(label + " arrays must already be selected and have len(rows) entries")
                _strictly_increasing(values, label + "[" + serial + "]")
                if supplied is camera_timestamp_ns:
                    h5_ms = original(_CAMERA_PREFIX + serial + "_frame_received", ())
                    if not np.array_equal(values // 1000000, h5_ms):
                        raise ValueError(serial + " SDK timestamp does not exactly match selected H5 milliseconds")
                arrays[prefix + serial] = values

    metadata = {
        "schema": "droid-native-to-oxt-arrays-v1",
        "source_h5": str(Path(h5_path).resolve()),
        "original_control_rows": total,
        "selected_control_rows": rows.tolist(),
        "timestamp_origin_unix_ns": int(all_time[0]),
        "timestamp_semantics": "Host control step_start Unix nanoseconds; relative seconds subtract original episode first row before float conversion. No clock correction or resampling.",
        "pose_semantics": {
            "representation": "xyz metres + rotation vector radians (scipy Euler xyz conversion)",
            "right_wrist_pose_reference": "original robot model EEF/flange; local FR3 configuration names panda_link8",
            "canonical_wrist_transform_status": "pending; no canonical wrist or complete TCP transform inferred",
            "action_eef_pose": "original requested EEF target before IK; distinct from future observed state and not FK of the joint target",
            "offset_fields": "already recorded original EEF local +Z 0.063 m point; orientation unchanged; not full Robotiq TCP",
        },
        "action_semantics": "Real original DROID joint and EEF targets are retained. command_dispatched=false indicates a hypothetical hold, not a sent command; true does not prove asynchronous acceptance.",
        "hand_semantics": "Single normalized closure 0=open, 1=closed, joint index 28; no conversion to physical width.",
        "ft_semantics": {
            "sensor": "SRIM3813A1",
            "channels": ["Fx", "Fy", "Fz", "Mx", "My", "Mz"],
            "units": ["N", "N", "N", "Nm", "Nm", "Nm"],
            "units_source": "assumed from device stored calibration",
            "frame": "sensor native measurement frame; sensor-to-EEF transform unavailable",
            "standard_tactile_group": "Only recorded Mx, My, Mz in wrist_torque; area 15. No inferred force magnitude or force-axis reduction.",
            "software_bias_subtraction": False,
            "software_gravity_compensation": False,
            "alignment": "Original latest-persisted per-control snapshot, selected without interpolation; native sample_index identifies full sidecar row.",
            "high_rate_sidecar": "Must also preserve original ft_sensor.h5 independently; these row-aligned arrays do not contain all high-rate samples.",
        },
        "supplementary_tactile_note": {
            "SRIM3813A1_native_wrench": {
                "type": "state", "shape": [6], "sensor_num": 1, "sensor_dimension": 6,
                "array_key": "supplementary_tactile",
                "sensor_description": "One device-calibrated six-axis native sensor-frame wrench, flattened as Fx,Fy,Fz,Mx,My,Mz in N,N,N,Nm,Nm,Nm; no software compensation or coordinate transform.",
                "sensor_idx_description": {"sensor_idx_0": "All six columns belong to the same SRI M3813A1 wrist-mounted sensor."},
            }
        },
        "native_fields": native_fields,
        "fields": {name: {"shape": list(array.shape), "dtype": str(array.dtype)}
                   for name, array in arrays.items()},
    }
    return arrays, metadata