Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions t4scene/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
18 changes: 17 additions & 1 deletion t4scene/python/t4scene/data/scene.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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,
Expand Down
92 changes: 81 additions & 11 deletions t4scene/python/t4scene/protobuf/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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:
Expand All @@ -98,23 +131,23 @@ 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",
"CylinderAnnotations",
"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):
Expand Down Expand Up @@ -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"] = (
Expand All @@ -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
Expand All @@ -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
Loading