diff --git a/CHANGELOG.md b/CHANGELOG.md index e892994..18835e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ compatibility. ## Unreleased +- `T4Scene.from_proto(message, rows=(start, stop))` decodes one window of a + stored Scene without decoding or validating its other rows; `slice_model_data` cuts a + nonempty `model_data` payload to the window. Decoding also + shares the arrays of a camera calibration that repeats across rows. See + [reading a Scene back](t4scene/python/README.md#save-a-scene-and-read-it-back). - The ROS2 generator can build a recorded window with a receipt cutoff for history and current inputs and the full recording for future labels. Regenerating a dataset with `build_recorded_window()` can exclude late diff --git a/t4scene/python/README.md b/t4scene/python/README.md index 3354add..d6609cd 100644 --- a/t4scene/python/README.md +++ b/t4scene/python/README.md @@ -129,6 +129,22 @@ restored = T4Scene.from_proto(t4_scene_pb2.T4Scene.FromString(path.read_bytes()) print(restored.scene_metadata.scene_id) # drive-01 ``` +To read a window of a long stored Scene, pass its rows to `from_proto`: + +```python +message = t4_scene_pb2.T4Scene.FromString(path.read_bytes()) +window = T4Scene.from_proto(message, rows=(120, 231), current_index=150) +``` + +The result equals decoding the whole Scene, setting `current_index` and calling +`slice_time(120, 231)`. Camera, LiDAR and track-ID rows outside the window are +not decoded, and only the window is validated, so the cost follows the window +instead of the file. `current_index` is an index into the stored rows and +defaults to the stored one. A Scene with nonempty `model_data` needs a +`slice_model_data(payload, start, stop)` callback, as `slice_time` does; it gets +the window's bounds in the stored rows. +See the [window examples](tests/test_scene_window_decode.py). + Serialization takes a CPU snapshot of tensor data. If your Scene has loaded map geometry, export the map once and use the resource store when encoding each Scene. See [working with maps](maps.md#exchange-a-map-once). diff --git a/t4scene/python/t4scene/data/scene.py b/t4scene/python/t4scene/data/scene.py index 11b7a26..11366cf 100644 --- a/t4scene/python/t4scene/data/scene.py +++ b/t4scene/python/t4scene/data/scene.py @@ -116,9 +116,18 @@ def from_proto( *, map_resources: MapResourceStore | None = None, validate: bool = True, + rows: tuple[int, int] | None = None, + current_index: int | None = None, + slice_model_data: Callable[[ModelData, int, int], ModelData | None] | None = None, ) -> T4Scene: """Decode a Protobuf message into a NumPy-backed T4Scene. + ``rows=(start, stop)`` decodes only that window, with ``current_index`` + (an index into the stored rows) as its current row when given. The result + equals decoding everything and calling ``slice_time(start, stop)``, without + decoding or validating the other rows. Nonempty model_data needs the + ``slice_model_data(payload, start, stop)`` callback of ``slice_time``. + The codec decodes and validates data, resolving map references when a store is supplied and retaining an explicit MapReference otherwise. The result does not depend on the message's lifetime. @@ -127,7 +136,14 @@ def from_proto( """ from t4scene.protobuf import from_proto - return from_proto(message, map_resources=map_resources, validate=validate) + return from_proto( + message, + map_resources=map_resources, + validate=validate, + rows=rows, + current_index=current_index, + slice_model_data=slice_model_data, + ) def reanchor( self, diff --git a/t4scene/python/t4scene/protobuf/blocks.py b/t4scene/python/t4scene/protobuf/blocks.py index 9d1c4d5..348850e 100644 --- a/t4scene/python/t4scene/protobuf/blocks.py +++ b/t4scene/python/t4scene/protobuf/blocks.py @@ -54,6 +54,35 @@ def _read_strings(message): return [row.value if row.HasField("value") else None for row in message.values] +class _StringRows: + """A StringColumn whose rows are decoded when read. + + A slice returns a list, as slicing the decoded column does, so cutting a + window out of a long column decodes only the rows of the window. + """ + + __slots__ = ("_rows",) + + def __init__(self, message): + self._rows = message.values + + def __len__(self): + return len(self._rows) + + def __getitem__(self, index): + if isinstance(index, slice): + return _read_strings_rows(self._rows[index]) + row = self._rows[index] + return row.value if row.HasField("value") else None + + def __iter__(self): + return iter(_read_strings_rows(self._rows)) + + +def _read_strings_rows(rows): + return [row.value if row.HasField("value") else None for row in rows] + + def write_block(source, target, *, exclude=()): """Encode explicit schema fields, preserving optional collection rows.""" target.SetInParent() @@ -86,7 +115,11 @@ def write_block(source, target, *, exclude=()): raise ValueError(f"unsupported block: {kind}") -def read_fields(message, *, exclude=()): +def read_fields(message, *, exclude=(), lazy_strings=False): + """Decode the set fields of ``message``. + + ``lazy_strings`` leaves string columns undecoded until their rows are read. + """ values = {} for field, value in message.ListFields(): if field.name in exclude: @@ -98,7 +131,7 @@ def read_fields(message, *, exclude=()): if kind in NUMERIC_KINDS: decoded = read_numeric(message, field, value) elif kind == "StringColumn": - decoded = _read_strings(value) + decoded = _StringRows(value) if lazy_strings else _read_strings(value) elif kind in _BLOCK_TYPES: if kind in ( "BoxAnnotations", @@ -106,15 +139,15 @@ def read_fields(message, *, exclude=()): "PolygonAnnotations", ) and not value.HasField("positions"): raise ValueError("annotations require positions") - decoded = read_block(value, _BLOCK_TYPES[kind]) + decoded = read_block(value, _BLOCK_TYPES[kind], lazy_strings=lazy_strings) else: raise ValueError(f"unsupported block: {kind}") values[field.name] = decoded return values -def read_block(message, cls): - return cls(**read_fields(message)) +def read_block(message, cls, *, lazy_strings=False): + return cls(**read_fields(message, lazy_strings=lazy_strings)) def write_blocks(scene, message, map_resources): @@ -149,7 +182,8 @@ def write_blocks(scene, message, map_resources): write_block(lidar, row.value) -def read_blocks(message, map_resources, *, timestamps_ns): +def read_blocks(message, map_resources, *, timestamps_ns, sensors=True): + """Decode the map, routes and signals, and the sensor rows unless ``sensors`` is false.""" result = {} if message.HasField("map"): result["map"] = ( @@ -164,17 +198,53 @@ def read_blocks(message, map_resources, *, timestamps_ns): if not message.traffic_lights.HasField(name): raise ValueError(f"traffic light sequence requires {name}") result["traffic_lights"] = read_block(message.traffic_lights, TrafficLightSequence) + if sensors: + result.update(read_sensors(message)) + return result + + +_CALIBRATION = ("camera2ego_rotation", "camera2ego_translation", "intrinsics", "distortion") + + +def _read_camera(value, calibrations): + """Decode one camera, sharing the arrays of a calibration seen before. + + A camera without an image differs between rows only in its time, and its + decoded arrays are read-only, so one decoded calibration serves every row. + """ + present = tuple(field.name for field, _ in value.ListFields()) + if "image" in present or "annotations" in present: + # A required constructor argument can still have proto3's default + # value; ListFields() omits an empty name. + return Camera(name=value.name, **read_fields(value, exclude=("name",))) + key = ( + value.name, + present, + *(getattr(value, name).SerializeToString(deterministic=True) for name in _CALIBRATION), + ) + shared = calibrations.get(key) + if shared is None: + shared = calibrations[key] = read_fields(value, exclude=("name", "timestamp_ns")) + return Camera( + name=value.name, + timestamp_ns=value.timestamp_ns if "timestamp_ns" in present else None, + **shared, + ) + + +def read_sensors(message, start=0, stop=None): + """Decode the camera and LiDAR rows in ``[start, stop)``; no other row is touched.""" + result = {} if message.HasField("cameras"): + calibrations = {} registers = [] - for row in message.cameras.rows: + for row in message.cameras.rows[start:stop]: if not row.HasField("value"): registers.append(None) continue register = {} for value in row.value.cameras: - # A required constructor argument can still have proto3's default - # value; ListFields() omits an empty name. - camera = Camera(name=value.name, **read_fields(value, exclude=("name",))) + camera = _read_camera(value, calibrations) if camera.name in register: raise ValueError("duplicate camera name") register[camera.name] = camera @@ -183,6 +253,6 @@ def read_blocks(message, map_resources, *, timestamps_ns): if message.HasField("lidar"): result["lidar"] = [ read_block(row.value, Lidar) if row.HasField("value") else None - for row in message.lidar.rows + for row in message.lidar.rows[start:stop] ] return result diff --git a/t4scene/python/t4scene/protobuf/scene.py b/t4scene/python/t4scene/protobuf/scene.py index db3afde..60034d4 100644 --- a/t4scene/python/t4scene/protobuf/scene.py +++ b/t4scene/python/t4scene/protobuf/scene.py @@ -1,17 +1,23 @@ """Convert the experimental public Scene without silently dropping fields.""" +from collections.abc import Callable from copy import copy +from dataclasses import fields +from operator import index + +import numpy as np from t4scene.data.tags import normalize_tags from t4scene.data.ego import EgoSequence from t4scene.data.objects import AnnotationSequence -from t4scene.data.scene import SceneMetadata, T4Scene +from t4scene.data.scene import ModelData, SceneMetadata, T4Scene from ._generated import t4_scene_pb2 as pb from .blocks import ( read_block, read_blocks, read_fields, + read_sensors, write_block, write_blocks, ) @@ -69,19 +75,117 @@ def to_proto( return result +def _window_edges(offsets, start, stop, rows, size, name): + """Return the packed boundaries of rows ``[start, stop)`` as indices. + + ``slice_time`` uses them to index a column, where a negative or decreasing + stored value would silently select other rows. Only the boundaries of the + window are checked; one at either end of the column must be that end, or + the window would silently drop packed values. + """ + if offsets is None: + raise ValueError(f"{name} are required") + edges = np.asarray(offsets) + if edges.ndim != 1 or len(edges) != rows + 1 or edges.dtype.kind not in "iu": + raise ValueError(f"{name} must hold one integer boundary per row and a final one") + part = edges[start : stop + 1] + if np.ma.getmaskarray(offsets[start : stop + 1]).any() or ( + part[0] < 0 or part[-1] > size or np.any(part[1:] < part[:-1]) + ): + raise ValueError(f"{name} must be increasing boundaries inside their column") + if (start == 0 and part[0] != 0) or (stop == rows and part[-1] != size): + raise ValueError(f"{name} must start at zero and end at their column's length") + return int(part[0]), int(part[-1]) + + +def _window_rows(rows): + """Return the window bounds as Python integers, so NumPy scalars cannot overflow.""" + start, stop = rows + if isinstance(start, (bool, np.bool_)) or isinstance(stop, (bool, np.bool_)): + raise TypeError("window rows must be integers") + return index(start), index(stop) + + +def _check_window_offsets(scene, start, stop): + """Check every packed offset that cutting rows ``[start, stop)`` will index with.""" + count = len(scene.timestamps_ns) + if not 0 <= start < stop <= count: + raise ValueError("window rows must be in bounds") + annotations = scene.annotations + if annotations is not None: + for kind, group in annotations.values.iter_groups(): + name = {"boxes": "box", "cylinders": "cylinder", "polygons": "polygon"}[kind] + lo, hi = _window_edges( + getattr(annotations, name + "_offsets"), + start, + stop, + count, + len(group), + f"annotation {name} offsets", + ) + if kind == "polygons" and group.vertices is not None: + _window_edges( + group.offsets, lo, hi, len(group), len(group.vertices), "polygon vertex offsets" + ) + signals = scene.traffic_lights + if signals is not None: + values = signals.values + groups = 0 if values.group_ids is None else len(values.group_ids) + lo, hi = _window_edges( + signals.group_offsets, start, stop, count, groups, "traffic light group offsets" + ) + if values.group_ids is not None: + elements = [ + len(getattr(values, field.name)) + for field in fields(values) + if field.name.startswith("element_") + and field.name != "element_offsets" + and getattr(values, field.name) is not None + ] + _window_edges( + values.element_offsets, + lo, + hi, + groups, + min(elements, default=0), + "traffic light element offsets", + ) + + def from_proto( - message: pb.T4Scene, *, map_resources: MapResourceStore | None = None, validate: bool = True + message: pb.T4Scene, + *, + map_resources: MapResourceStore | None = None, + validate: bool = True, + rows: tuple[int, int] | None = None, + current_index: int | None = None, + slice_model_data: Callable[[ModelData, int, int], ModelData | None] | None = None, ) -> T4Scene: """Decode and validate the public Scene. ``validate=False`` skips Scene semantics. Wire structure checks remain enabled. + ``rows=(start, stop)`` decodes only that window. The result equals + ``from_proto(message).slice_time(start, stop)``, but camera, LiDAR and string + rows outside the window are never decoded, and only the window is validated. + The packed offsets that select the window are always checked, so a malformed + stored offset cannot return another row's observations. + ``current_index`` then replaces the message's current row, as an index into + the stored rows, before the window is cut; the window must contain it. A + message with nonempty ``model_data`` needs ``slice_model_data(payload, start, + stop)``, which receives the decoded payload and the window's bounds in the + stored rows, as in ``slice_time``; its result becomes the window's payload + and None discards it. + Unknown protobuf fields are not retained by the NumPy representation; this converter is not a forward-compatible relay for newer schema versions. """ for name in ("scene_metadata", "timestamps_ns"): if not message.HasField(name): raise ValueError(f"missing required Scene field: {name}") + if rows is None and (current_index is not None or slice_model_data is not None): + raise ValueError("current_index and slice_model_data require rows") + window = rows is not None metadata = message.scene_metadata columns = read_fields( message, @@ -104,22 +208,30 @@ def from_proto( for name in ("values", "available"): if not block.HasField(name): raise ValueError(f"missing required annotations field: {name}") - annotations = read_block(block, AnnotationSequence) + annotations = read_block(block, AnnotationSequence, lazy_strings=window) scene = T4Scene( scene_metadata=SceneMetadata( scene_id=metadata.scene_id, recording_id=metadata.recording_id if metadata.HasField("recording_id") else None, tags=tuple(metadata.tags), ), - current_index=message.current_index, + current_index=message.current_index if current_index is None else current_index, model_data=model_data_from_proto(message.model_data) if message.HasField("model_data") else None, ego=read_block(message.ego, EgoSequence) if message.HasField("ego") else None, annotations=annotations, - **read_blocks(message, map_resources, timestamps_ns=columns["timestamps_ns"]), + **read_blocks( + message, map_resources, timestamps_ns=columns["timestamps_ns"], sensors=not window + ), **columns, ) + if window: + start, stop = _window_rows(rows) + _check_window_offsets(scene, start, stop) + scene = scene.slice_time(start, stop, slice_model_data=slice_model_data) + for name, values in read_sensors(message, start, stop).items(): + setattr(scene, name, values) if validate: scene.validate() return scene diff --git a/t4scene/python/tests/test_scene_window_decode.py b/t4scene/python/tests/test_scene_window_decode.py new file mode 100644 index 0000000..f6faedd --- /dev/null +++ b/t4scene/python/tests/test_scene_window_decode.py @@ -0,0 +1,216 @@ +"""Decoding a window of a stored Scene equals decoding all of it and slicing.""" + +import numpy as np +import pytest + +from t4scene import T4Scene +from t4scene.data.camera import Camera, Cameras +from t4scene.data.lidar import Lidar +from t4scene.protobuf import t4_scene_pb2 as pb + + +def stored(scene): + """The packed Scene with sensor rows, as a reader gets it from a file.""" + rotation = np.array([[0.0, 0.0, 1.0], [-1.0, 0.0, 0.0], [0.0, -1.0, 0.0]]) + count = len(scene.timestamps_ns) + scene.cameras = [ + None + if i == 2 + else Cameras( + { + name: Camera( + name, + camera2ego_rotation=rotation, + camera2ego_translation=np.array([1.0, side, 2.0]), + intrinsics=np.diag([1000.0, 1000.0, 1.0]), + distortion=np.zeros(5), + timestamp_ns=i * 10 + 3, + ) + for name, side in (("front", 0.0), ("left", 0.5)) + } + ) + for i in range(count) + ] + scene.lidar = [None if i == 1 else Lidar(timestamp_ns=i * 10 + 1) for i in range(count)] + scene.validate() + return pb.T4Scene.FromString(scene.to_proto().SerializeToString()) + + +def wire(scene): + return scene.to_proto().SerializeToString(deterministic=True) + + +@pytest.mark.parametrize("rows", [(0, 5), (1, 4), (3, 4), (2, 5), (0, 3)]) +def test_window_equals_whole_decode_then_slice(rows, packed_scene): + message = stored(packed_scene) + current = rows[1] - 1 + whole = T4Scene.from_proto(message) + whole.current_index = current + expected = whole.slice_time(*rows) + window = T4Scene.from_proto(message, rows=rows, current_index=current) + assert wire(window) == wire(expected) + assert window.current_index == expected.current_index + for group in ("boxes", "polygons"): + ids = getattr(window.annotations.values, group).track_ids + assert isinstance(ids, list) + assert ids == list(getattr(expected.annotations.values, group).track_ids) + assert [row is None for row in window.cameras] == [row is None for row in expected.cameras] + assert [row is None for row in window.lidar] == [row is None for row in expected.lidar] + + +def test_window_keeps_the_stored_current_row_by_default(packed_scene): + message = stored(packed_scene) + window = T4Scene.from_proto(message, rows=(2, 5)) + assert window.current_index == message.current_index - 2 == 1 + + +def test_window_decodes_no_sensor_row_outside_it(monkeypatch, packed_scene): + from t4scene.protobuf import blocks + + message = stored(packed_scene) + decoded = [] + read_camera = blocks._read_camera + + def counting(value, calibrations): + decoded.append(value.timestamp_ns) + return read_camera(value, calibrations) + + monkeypatch.setattr(blocks, "_read_camera", counting) + T4Scene.from_proto(message, rows=(3, 5)) + assert decoded == [33, 33, 43, 43] + + +def test_rows_share_one_decoded_calibration(packed_scene): + scene = T4Scene.from_proto(stored(packed_scene)) + first, last = scene.cameras[0]["front"], scene.cameras[4]["front"] + assert first is not last and first.timestamp_ns != last.timestamp_ns + assert first.intrinsics is last.intrinsics + assert not first.intrinsics.flags.writeable + assert scene.cameras[0]["left"].camera2ego_translation[1] == 0.5 + + +@pytest.mark.parametrize( + ("rows", "current"), [((0, 3), None), ((4, 5), 3), ((0, 6), None), ((3, 3), None)] +) +def test_window_must_contain_the_current_row(rows, current, packed_scene): + with pytest.raises(ValueError): + T4Scene.from_proto(stored(packed_scene), rows=rows, current_index=current) + + +def test_current_index_and_model_data_callback_need_a_window(packed_scene): + message = stored(packed_scene) + with pytest.raises(ValueError, match="require rows"): + T4Scene.from_proto(message, current_index=1) + with pytest.raises(ValueError, match="require rows"): + T4Scene.from_proto(message, slice_model_data=lambda *args: None) + + +def test_model_data_callback_cuts_the_payload_to_the_window(packed_scene): + packed_scene.model_data = {"rows": np.arange(5), "anchor": np.array([3])} + message = stored(packed_scene) + with pytest.raises(ValueError, match="slice_model_data"): + T4Scene.from_proto(message, rows=(0, 5)) + calls = [] + + def cut(data, start, stop): + calls.append((start, stop)) + return {"rows": data["rows"][start:stop], "anchor": data["anchor"] - start} + + window = T4Scene.from_proto(message, rows=(1, 4), current_index=3, slice_model_data=cut) + assert calls == [(1, 4)] + assert window.current_index == 2 + whole = T4Scene.from_proto(message) + whole.current_index = 3 + assert wire(window) == wire(whole.slice_time(1, 4, slice_model_data=cut)) + np.testing.assert_array_equal(window.model_data["rows"], [1, 2, 3]) + dropped = T4Scene.from_proto(message, rows=(1, 4), slice_model_data=lambda *args: None) + assert dropped.model_data is None + + +def test_window_validation_covers_the_window_only(packed_scene): + packed_scene.goal_poses_3d[0] = np.nan + message = pb.T4Scene.FromString(packed_scene.to_proto(validate=False).SerializeToString()) + with pytest.raises(ValueError): + T4Scene.from_proto(message) + T4Scene.from_proto(message, rows=(1, 5)) + with pytest.raises(ValueError): + T4Scene.from_proto(message, rows=(0, 5)) + T4Scene.from_proto(message, rows=(0, 5), validate=False) + + +def set_offsets(array, values): + array.data = np.array(values, dtype="