# Mosaico SDK
The Mosaico SDK is a Python interface designed specifically for managing **Physical AI and Robotics data**. Its purpose is to handle the complete lifecycle of information, from the moment it is captured by a sensor to the moment it is used to train a neural network or analyze a robot's behavior.
The SDK is built on the philosophy that robotics data is **unique**. Whether it comes from a autonomous car, a drone, or a factory arm, this data is multi-modal, highly frequent, and deeply interconnected in space and time. The Mosaico SDK provides the infrastructure to treat this data as a *first-class citizen* rather than just a collection of generic numbers. It understands the geometric and physical semantics of complex data types such as LIDAR point clouds, IMU readings, high-resolution camera feeds, and rigid-body transformations.
## Installation
Install the SDK via `pip`:
```bash
pip install mosaicolabs
```
*Note: Requires Python 3.10 or higher.*
## Overview
The SDK is built on the following core principles:
### Middleware Independence
Mosaico is middleware-agnostic. While the SDK provides robust tools for ROS, it exists because robotics data itself is complex, regardless of the collection method. The platform serves as a standardized hub that can ingest data from:
* **Existing Frameworks**: Such as ROS 1, ROS 2, `.mcap` and `.db3` files.
* **Custom Collectors**: Proprietary data loggers or direct hardware drivers.
* **Simulators**: Synthetic data generated in virtual environments.
### Ontology
The [Mosaico Data Ontology](SDK/ontology.md) acts as the abstraction layer between your specific data collection system and your storage. Instead of saving "Topic A from Robot B" you save a `Pose`, an `IMU` reading, or an `Image`.
Once data is in the platform, its origin becomes secondary to its universal, semantic format. Moreover, the ontology is designed to be extensible with no effort, to meet the needs of any domain; the custom types are automatically validatable, serializable, and queryable alongside standard types.
### High-Performance
Leveraging [Apache Arrow](https://arrow.apache.org/) for zero-copy performance, the SDK moves massive data volumes from the network to analysis tools without the CPU overhead of traditional data conversion. Every piece of data is time-synchronized, allowing the SDK to *replay* a session from dozens of sensors in the exact chronological order they occurred.
## Key Operations
### Data Ingestion
You can push data into Mosaico through two primary pathways, both designed to ensure your data is validated and standardized before storage:
**Native Ontology Ingestion**. This approach allows you to stream data directly from your application, providing the highest level of control over serialization and real-time performance.
**Ecosystem Adapters & Bridges**. Use specialized adapters to translate data from existing middleware and log formats into Mosaico sequences. Mosaico currently supports ROS 1 bags (`.bag`) and more recent formats like `.mcap` and `.db3`.
{ width="500" }
### Data Retrieval
Retrieving data goes beyond simple downloading. It is possible to stream and merge multiple topics into a single, time-ordered timeline, which is essential for sensor fusion.
Connect directly to a specific sensor, such as just the front-facing camera, to save bandwidth and memory.
The SDK fetches data in batches, allowing you to process datasets that are much larger than your computer's RAM.
### Querying & Discovery
Mosaico allows you to find data based on *what* happened, not just *when* it happened. You can search for specific sequences by metadata tags (like `robot_id` or `location`) or query the actual contents of the sensor data (e.g., *"Find all sequences where the vehicle acceleration exceeded 4 m/s^2"*).
### Machine Learning & Analytics
The [ML Module](SDK/bridges/ml.md) transforms raw, sparse sensor streams into the tabular formats required by modern AI:
* **Flattening**: Converts nested sensor data into organized tables (e.g. [`pandas.DataFrames`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html)).
* **Temporal Resampling**: Aligns sensors running at different speeds (e.g., a 100Hz IMU and a 5Hz GPS) onto a uniform time grid with custom frame-rate for model training.
---
# Contributing
# Contributing
If you plan to contribute to the codebase, you need to set up the pre-commit hooks in addition to the standard installation. These hooks enforce code quality checks automatically on every commit.
## Prerequisites
* **Python:** Version **3.10** or newer is required.
* **Poetry:** For package management.
## Development Setup
Clone the repository and navigate to the SDK directory:
```bash
cd mosaico/mosaico-sdk-py
```
Install dependencies **and** register the pre-commit hooks in a single step:
```bash
poetry install && poetry run pre-commit install
```
The second command installs the Git hook under `.git/hooks/pre-commit`, wiring it to the rules defined in `.pre-commit-config.yaml`. From that point on, every `git commit` will automatically run **Ruff** (linting and formatting) against your staged files — the commit is blocked if any check fails, keeping the codebase consistently clean.
> **Why this matters:** Skipping `pre-commit install` means your commits will bypass all quality gates. CI will catch the issues anyway, but fixing them after the fact is more disruptive than catching them locally before pushing.
## What the hooks do
The `.pre-commit-config.yaml` currently configures the following actions via [Ruff](https://docs.astral.sh/ruff/):
- **Linting** — detects common errors, unused imports, and style violations
- **Formatting** — auto-formats code to a consistent style
## Running checks manually
You can trigger the hooks on demand without committing:
```bash
# Run on all files
poetry run pre-commit run --all-files
# Run on staged files only
poetry run pre-commit run
```
## Verify the hook is installed
After setup, confirm the hook is in place:
```bash
ls .git/hooks/pre-commit
```
You should see the file present. If it is missing, re-run `poetry run pre-commit install`.
---
# Client
??? question "API Reference"
[`mosaicolabs.comm.MosaicoClient`][mosaicolabs.comm.MosaicoClient].
The `MosaicoClient` is a resource manager designed to orchestrate distinct **Layers** of communication and processing.
This layered architecture ensures that high-throughput sensor data does not block critical control operations or application logic.
Creating a new client is done via the [`MosaicoClient.connect()`][mosaicolabs.comm.MosaicoClient.connect] factory method. It is recomended to always use the client inside a `with` context to ensure resources in all layers are cleanly released.
```python
from mosaicolabs import MosaicoClient
with MosaicoClient.connect("localhost", 6726) as client:
# Logic goes here
pass
# The connection with the server is closed automatically
```
## Control Layer
A single connection is maintained for metadata operations, schema management, and lifecycle control. This layer handles lightweight tasks such as creating sequences and querying the catalog. By using a dedicated control flow, the client ensures that critical state commands (like `sequence_finalize`) remain responsive and synchronized with the data stream.
## Data Layer
Data ingestion and retrieval are handled through a **unified single-stream connection**. By consolidating data traffic into a single pipe, the SDK reduces network overhead and ensures strict sequential ordering of data packets. This simplified approach eliminates the complexity of connection handshakes and is optimized for stable, predictable throughput in environments where network jitter must be minimized.
## Processing Layer
The SDK operates on a **Synchronous Processing Model**, where serialization and transmission occur within the calling thread’s context. For complex sensor data (like image compression or LIDAR encoding), the SDK performs inline serialization immediately prior to transmission. This "lock-step" execution ensures maximum data integrity and minimizes memory pressure, as it avoids the overhead of background thread synchronization and context switching.
## Security Layer
The Security Layer manages the confidentiality and integrity of the communication channel. It is composed of two primary mechanisms that work in tandem to harden the connection.
### 1. Encryption (TLS)
For deployments over public or shared networks, the client supports [**Transport Layer Security (TLS)**](https://docs.mosaico.dev/daemon/tls). Two connection modes are available via SDK, depending on the configuratiom of the Mosaico server:
* **One-way TLS**, server authenticated only
```python
MosaicoClient.connect("localhost", 6726, enable_tls=True)
```
* **Two-way TLS**, via providing a certificate file
```python
MosaicoClient.connect("localhost", 6726, tls_cert_path="my/cert/file/path.pem")
```
In both modes, the client automatically switches from an insecure channel to an encrypted one via `grpc+tls` protocol. The **One-way TLS** mode is available by setting `enable_tls=True` when calling [`MosaicoClient.connect()`][mosaicolabs.comm.MosaicoClient.connect], and providing no certificate.
On the other hand, the **Two-way TLS** mode is available by passing the TLS certificate path via `tls_cert_path` parameter when calling [`MosaicoClient.connect()`][mosaicolabs.comm.MosaicoClient.connect].
In such a case, there is no need to set the `enable_tls=True` flag.
### 2. Authentication (API Key)
Mosaico uses an [**API Key** system](https://docs.mosaico.dev/daemon/api_key) to authorize every operation. When a key is provided, the client automatically attaches your unique credentials to the metadata of every gRPC and Flight call. This ensures that even if your endpoint is public, only requests with a valid, non-revoked key are processed by the server.
The client supports 4 permission levels, each with increasing privileges:
| Permission | Description |
| :--- | :--- |
| [`APIKeyPermissionEnum.Read`][mosaicolabs.enum.APIKeyPermissionEnum.Read] | Read-Only access to resources |
| [`APIKeyPermissionEnum.Write`][mosaicolabs.enum.APIKeyPermissionEnum.Write] | Write access to resources (Create and update sequences)|
| [`APIKeyPermissionEnum.Delete`][mosaicolabs.enum.APIKeyPermissionEnum.Delete] | Delete access to resources (Delete sequences, sessions and topics)|
| [`APIKeyPermissionEnum.Manage`][mosaicolabs.enum.APIKeyPermissionEnum.Manage] | Full access to resources + Manage API keys (create, retrieve the status, revoke)|
```python
from mosaicolabs import MosaicoClient
# The client handles the handshake and credential injection automatically
with MosaicoClient.connect(
host="mosaico.production.cluster",
port=6726,
api_key="",
) as client:
print(client.version())
```
!!! warning "API-Key and TLS"
TLS is not mandatory for connecting via API-keys. It is recommended to enable the support for TLS in the server, to avoid sensitive credential to be sent on unencrypted channels.
### Recommended Patterns
#### Explicit Connection
Ideal for local development or scripts where credentials are managed by a secrets manager.
```python
from mosaicolabs import MosaicoClient
# The client handles the handshake and credential injection automatically
with MosaicoClient.connect(
host="mosaico.production.cluster",
port=6726,
api_key="",
tls_cert_path="/etc/mosaico/certs/ca.pem"
) as client:
print(client.version())
```
#### Environment-Based Configuration (`from_env`)
As a best practice for production and containerized environments (Docker/Kubernetes), the `MosaicoClient` supports **Zero-Config Discovery** via [`MosaicoClient.from_env`][mosaicolabs.comm.MosaicoClient.from_env]. This prevents sensitive keys from ever being hardcoded in your source files.
The client automatically searches for:
* `MOSAICO_API_KEY`: Your authentication token.
* `MOSAICO_TLS_CERT_FILE`: The path to your CA certificate.
```python
import os
from mosaicolabs import MosaicoClient
# Standardize your deployment by using environment variables
# export MOSAICO_API_KEY=...
# export MOSAICO_TLS_CERT_FILE=...
with MosaicoClient.from_env(host="mosaico.internal", port=6726) as client:
# Security is initialized automatically from the environment
print(client.version())
```
## Compression
The `MosaicoClient` supports **gRPC-level compression** to reduce bandwidth usage when transmitting data over the network. Compression is applied transparently to all record batches sent through the Data Layer.
Compression is configured via the `compression` parameter of [`MosaicoClient.connect()`][mosaicolabs.comm.MosaicoClient.connect]. It accepts either a [`GRPCCompressionAlgorithm`][mosaicolabs.enum.GRPCCompressionAlgorithm] shorthand (**algorithm only**, no level control) or a [`GRPCCompression`][mosaicolabs.comm.GRPCCompression] dataclass (full control over both **algorithm and level**).
The library supports the following compression algorithms:
| Algorithm | Description |
| :--- | :--- |
| [`GRPCCompressionAlgorithm.Null`][mosaicolabs.enum.GRPCCompressionAlgorithm.Null] | No compression (default). Data is transmitted uncompressed. |
| [`GRPCCompressionAlgorithm.Gzip`][mosaicolabs.enum.GRPCCompressionAlgorithm.Gzip] | Standard GZIP compression. Best for general-purpose use. |
| [`GRPCCompressionAlgorithm.StreamGzip`][mosaicolabs.enum.GRPCCompressionAlgorithm.StreamGzip] | Experimental stream-level GZIP. Applied to the raw gRPC stream rather than individual messages. |
When using an algorithm that supports intensity tuning, an optional [`GRPCCompressionLevel`][mosaicolabs.enum.GRPCCompressionLevel] can be specified to trade off CPU usage against compression ratio.
| Level | Description |
| :--- | :--- |
| [`GRPCCompressionLevel.Low`][mosaicolabs.enum.GRPCCompressionLevel.Low] | Fastest compression, lowest CPU overhead, largest output size. |
| [`GRPCCompressionLevel.Medium`][mosaicolabs.enum.GRPCCompressionLevel.Medium] | Balanced trade-off between speed and compression ratio. |
| [`GRPCCompressionLevel.High`][mosaicolabs.enum.GRPCCompressionLevel.High] | Highest compression ratio, greatest CPU overhead. |
If no level is specified, the underlying gRPC protocol implementation chooses a sensible default for the selected algorithm.
#### Shorthand (algorithm only)
Pass a [`GRPCCompressionAlgorithm`][mosaicolabs.enum.GRPCCompressionAlgorithm] value directly. The compression level is left to the gRPC default.
```python
from mosaicolabs import MosaicoClient
from mosaicolabs.enum import GRPCCompressionAlgorithm
with MosaicoClient.connect(
"localhost",
6726,
compression=GRPCCompressionAlgorithm.Gzip,
) as client:
# ... Perform operations
```
#### Full control (algorithm + level)
Use the [`GRPCCompression`][mosaicolabs.comm.GRPCCompression] dataclass to explicitly set both the algorithm and the compression level.
```python
from mosaicolabs import MosaicoClient
from mosaicolabs.comm import GRPCCompression
from mosaicolabs.enum import GRPCCompressionAlgorithm, GRPCCompressionLevel
with MosaicoClient.connect(
"localhost",
6726,
compression=GRPCCompression(
algorithm=GRPCCompressionAlgorithm.Gzip,
level=GRPCCompressionLevel.High,
),
) as client:
# ... Perform operations
```
!!! tip "When to enable compression"
Compression is most beneficial when the network link is the bottleneck (e.g., remote deployments over WAN or metered connections). For local or LAN deployments, the CPU overhead of compression may outweigh the bandwidth savings, so the default `GRPCCompressionAlgorithm.Null` is recommended.
!!! warning "StreamGzip is experimental"
`GRPCCompressionAlgorithm.StreamGzip` applies compression at the raw gRPC stream level. It is currently marked as **experimental** and may not be stable in all environments. Prefer `GRPCCompressionAlgorithm.Gzip` for production use.
---
# Data Models & Ontology
The **Mosaico Data Ontology** is the semantic backbone of the SDK.
It defines the structural "rules" that transform raw binary streams into meaningful physical data, such as GPS coordinates,
inertial measurements, or camera frames.
By using a strongly-typed ontology, Mosaico ensures that your data remains consistent, validatable,
and highly optimized for both high-throughput transport and complex queries.
## Core Philosophy
The ontology is designed to solve the "generic data" problem in robotics by ensuring every data object is:
1. **Validatable**: Uses Pydantic for strict runtime type checking of sensor fields.
2. **Serializable**: Automatically maps Python objects to efficient **PyArrow** schemas for high-speed binary transport.
3. **Queryable**: Injects a fluent API (`.Q`) into every class, allowing you to filter databases based on physical values (e.g., `IMU.Q.acceleration.x > 6.0`).
4. **Middleware-Agnostic**: Acts as an abstraction layer so that your analysis code doesn't care if the data originally came from ROS, a simulator, or a custom logger.
## Available Ontology Classes
The Mosaico SDK provides a comprehensive library of models that transform raw binary streams into validated, queryable Python objects. These are grouped by their physical and logical application below.
### Base Data Models
??? question "API Reference"
[Base Data Types](./API_reference/models/data_types.md)
These models serve as timestamped, metadata-aware wrappers for standard primitives. They allow simple diagnostic or scalar values to be treated as first-class members of the platform.
| Module | Classes | Purpose |
| --- | --- | --- |
| **Primitives** | [`String`][mosaicolabs.models.data.base_types.String], [`LargeString`][mosaicolabs.models.data.base_types.LargeString] | UTF-8 text data for logs or status messages. |
| **Booleans** | [`Boolean`][mosaicolabs.models.data.base_types.Boolean] | Logic flags (True/False). |
| **Signed Integers** | [`Integer8`][mosaicolabs.models.data.base_types.Integer8], [`Integer16`][mosaicolabs.models.data.base_types.Integer16], [`Integer32`][mosaicolabs.models.data.base_types.Integer32], [`Integer64`][mosaicolabs.models.data.base_types.Integer64] | Signed whole numbers of varying bit-depth. |
| **Unsigned Integers** | [`Unsigned8`][mosaicolabs.models.data.base_types.Unsigned8], [`Unsigned16`][mosaicolabs.models.data.base_types.Unsigned16], [`Unsigned32`][mosaicolabs.models.data.base_types.Unsigned32], [`Unsigned64`][mosaicolabs.models.data.base_types.Unsigned64] | Non-negative integers for counters or IDs. |
| **Floating Point** | [`Floating16`][mosaicolabs.models.data.base_types.Floating16], [`Floating32`][mosaicolabs.models.data.base_types.Floating32], [`Floating64`][mosaicolabs.models.data.base_types.Floating64] | Real numbers for high-precision physical values. |
### Geometry & Kinematics Models
??? question "API Reference"
[Geometry Models](./API_reference/models/geometry.md)
These structures define spatial relationships and the movement states of objects in 2D or 3D coordinate frames.
| Module | Classes | Purpose |
| --- | --- | --- |
| **Points & Vectors** | [`Vector2d/3d/4d`][mosaicolabs.models.data.geometry.Vector2d], [`Point2d/3d`][mosaicolabs.models.data.geometry.Point2d] | Fundamental spatial directions and locations. |
| **Rotations** | [`Quaternion`][mosaicolabs.models.data.geometry.Quaternion] | Compact, singularity-free 3D orientation (). |
| **Spatial State** | [`Pose`][mosaicolabs.models.data.geometry.Pose], [`Transform`][mosaicolabs.models.data.geometry.Transform] | Absolute positions or relative coordinate frame shifts. |
| **Motion** | [`Velocity`][mosaicolabs.models.data.kinematics.Velocity], [`Acceleration`][mosaicolabs.models.data.kinematics.Acceleration] | Linear and angular movement rates (Twists and Accels). |
| **Aggregated State** | [`MotionState`][mosaicolabs.models.data.kinematics.MotionState] | An atomic snapshot combining Pose, Velocity, and Acceleration. |
### Sensor Models
??? question "API Reference"
[Sensor Models](./API_reference/models/sensors.md)
High-level models representing physical hardware devices and their processed outputs.
| Module | Classes | Purpose |
| --- | --- | --- |
| **Inertial** | [`IMU`][mosaicolabs.models.sensors.IMU] | 6-DOF inertial data: linear acceleration and angular velocity. |
| **Navigation** | [`GPS`][mosaicolabs.models.sensors.GPS], [`GPSStatus`][mosaicolabs.models.sensors.GPSStatus], [`NMEASentence`][mosaicolabs.models.sensors.NMEASentence] | Geodetic fixes (WGS 84), signal quality, and raw NMEA strings. |
| **Vision** | [`Image`][mosaicolabs.models.sensors.Image], [`CompressedImage`][mosaicolabs.models.sensors.CompressedImage], [`CameraInfo`][mosaicolabs.models.sensors.CameraInfo], [`ROI`][mosaicolabs.models.data.ROI] | Raw pixels, encoded streams (JPEG/H264), calibration, and regions of interest. |
| **Environment** | [`Temperature`][mosaicolabs.models.sensors.Temperature], [`Pressure`][mosaicolabs.models.sensors.Pressure], [`Range`][mosaicolabs.models.sensors.Range] | Thermal readings (K), pressure (Pa), and distance intervals (m). |
| **Dynamics** | [`ForceTorque`][mosaicolabs.models.data.dynamics.ForceTorque] | 3D force and torque vectors for load sensing. |
| **Magnetic** | [`Magnetometer`][mosaicolabs.models.sensors.Magnetometer] | Magnetic field vectors measured in microTesla (). |
| **Robotics** | [`RobotJoint`][mosaicolabs.models.sensors.RobotJoint] | States (position, velocity, effort) for index-aligned actuator arrays. |
#### Futures
??? question "API Reference"
[Futures Models](./API_reference/models/futures.md)
Prospective high-level models representing emerging or not yet fully standardized sensor hardware. The `futures` module acts as a **transitional space** where experimental ontologies are introduced and iteratively refined before being promoted to the stable, production-ready ontology set.
The following sensors are supported as first-class data types in this module:
| Model | Description |
|---|---|
| **LiDAR** | 3D point cloud data from laser-based ranging sensors, supporting full spatial geometry and optional intensity/RGB fields. |
| **Radar** | Range, velocity, and azimuth measurements from radio-frequency sensors, including Doppler-based target detection. |
| **LaserScan** | 2D planar sweep data from single-line laser rangefinders, encoded as ordered range and intensity arrays. |
| **Multi-Echo LaserScan** | Extension of LaserScan supporting multiple return echoes per beam, enabling richer surface characterization. |
| **RGBD Camera** | Paired color and depth frames from structured-light or time-of-flight RGB-D sensors. |
| **Stereo Camera** | Synchronized left/right image pairs from stereo rigs, suitable for disparity estimation and 3D reconstruction. |
| **ToF Camera** | Per-pixel depth and amplitude data from time-of-flight imaging sensors. |
!!! warning "Experimental Ontologies"
The `futures` module is a transitional area where ontologies under active experimentation are hosted before graduating to the stable ontology set. Field definitions, unit conventions, and structural relationships are **not yet considered final** and will be refined based on feedback from real-world integrations and adopters. Once an ontology reaches sufficient maturity and coverage, it will be promoted out of `futures` and into the core, production-ready modules.
## MosaicoType & MosaicoField
When defining ontologies in the Mosaico SDK, every class attribute carries two pieces of information:
* **Python type** used by Pydantic for validation and IDE support.
* **PyArrow type** used for efficient columnar serialization to Parquet/Arrow.
`MosaicoType` and `MosaicoField` let you express both in a single annotation, providing a clean **single-source-of-truth API** for ontology field declarations.
You annotate each attribute once, and the Arrow schema is derived automatically at class-definition time by introspecting Pydantic's `model_fields`: no separate schema declaration to maintain, no risk of the two representations drifting apart.
Because the whole mechanism is built on top of **Pydantic model fields** via `Annotated` metadata, extending or customising field behaviour is as simple as adding standard Pydantic `Field` kwargs: no subclassing, no metaclass magic, no separate schema registry to maintain.
### MosaicoType
??? question "API Reference"
[`mosaicolabs.models.MosaicoType`][mosaicolabs.models.MosaicoType]
`MosaicoType` is a collection of `Annotated` type aliases. Each alias bundles the corresponding Python primitive type with its PyArrow counterpart as inline metadata, making the Arrow type immediately visible to the schema auto-builder without any additional configuration.
#### Scalar types
| Alias | Python type | Arrow type |
|---|---|---|
| `MosaicoType.uint8` | `int` | `pa.uint8()` |
| `MosaicoType.int8` | `int` | `pa.int8()` |
| `MosaicoType.uint16` | `int` | `pa.uint16()` |
| `MosaicoType.int16` | `int` | `pa.int16()` |
| `MosaicoType.uint32` | `int` | `pa.uint32()` |
| `MosaicoType.int32` | `int` | `pa.int32()` |
| `MosaicoType.uint64` | `int` | `pa.uint64()` |
| `MosaicoType.int64` | `int` | `pa.int64()` |
| `MosaicoType.float16` | `float` | `pa.float16()` |
| `MosaicoType.float32` | `float` | `pa.float32()` |
| `MosaicoType.float64` | `float` | `pa.float64()` |
| `MosaicoType.bool` | `bool` | `pa.bool_()` |
| `MosaicoType.string` | `str` | `pa.string()` |
| `MosaicoType.large_string` | `str` | `pa.large_string()` |
| `MosaicoType.binary` | `bytes` | `pa.binary()` |
| `MosaicoType.large_binary` | `bytes` | `pa.large_binary()` |
#### Explicit type definition
Using [`MosaicoType`][mosaicolabs.models.MosaicoType] provides precise control over the underlying PyArrow schema:
```python
from mosaicolabs import MosaicoField, MosaicoType, Serializable
class MyOntology(Serializable):
x: MosaicoType.float32
y: Optional[MosaicoType.float32] = None
```
* `x`: defined directly, will be converted in a **not nullable** PyArrow field.
* `y`: wrapped in `Optional[...]`, will be converted in a **nullable** PyArrow field.
#### Using Fallback types
You can also use standard Python type hints.
`Mosaico` automatically maps these to specific PyArrow types.
```python
class MyOntology(Serializable):
x: int
y: Optional[float] = None
```
In this scenario, the types are resolved using the following **fallback mapping**:
| Python type | PyArrow equivalent |
| ---| --- |
| `int` | `pa.int64()` |
| `float` | `pa.float64()` |
| `str` | `pa.string()` |
| `bool` | `pa.bool_()` |
| `bytes` | `pa.bytes()` |
!!! note "Note"
Just like with explicit types, using `Optional` with fallback types will correctly define the PyArrow field as **nullable**. If `Optional` is not used, the field is defined as **not nullable**.
#### List types
For list fields, `MosaicoType` exposes a [`list_()`][mosaicolabs.models.MosaicoType.list_] static method that wraps a scalar type, either a `MosaicoType` alias or a raw Python primitive, into the appropriate `pa.list_` Arrow type.
An optional `list_size` parameter produces a fixed-size list (`pa.list_(type, size)`), omitting it yields a variable-length list.
```python
from mosaicolabs import MosaicoField, MosaicoField, Serializable
class MyOntology(Serializable):
# Variable-length list of float32
scores: Optional[MosaicoType.list_(MosaicoType.float32)] = None
# Fixed-size list of 3 float32 (e.g. an RGB vector)
color: MosaicoType.list_(MosaicoType.float32, list_size=3)
# Works with raw Python primitives too
tags: MosaicoType.list_(str)
# Works with other Pydantic models with pyarrow struct
vec: MosaicoType.list_(Vector3d)
# Fallback List
vec2: List[Vector2d]
```
Using Python's built-in `list` (or `List` from `typing`) generates a **list of unfixed size** in the underlying Arrow schema.
This means:
- The list can hold **any number of elements** at runtime.
- No size constraint is enforced at the schema level.
- This is equivalent to calling `MosaicoType.list_(str)` with no `size` argument.
[`MosaicoType.list_()`][mosaicolabs.models.MosaicoType.list_] accepts an optional `size` parameter. When provided, it maps to an Arrow **fixed-size list** (`pa.list_(type, list_size=N)`), which enforces that every value in the column contains exactly `N` elements.
| | `list[str]` | `MosaicoType.list_(str)` | `MosaicoType.list_(str, 3)` |
|---|---|---|---|
| Arrow type | `pa.list_(pa.string())` | `pa.list_(pa.string())` | `pa.list_(pa.string(), 3)` |
| Size enforced | No | No | Yes, exactly 3 |
| Interoperable with Pydantic | Yes | Yes | Yes |
| Supports nested models | Yes | Yes | Yes |
Use [`MosaicoType.list_()`][mosaicolabs.models.MosaicoType.list_] with a `size` argument when:
- The list represents a **fixed-dimensional structure**, such as a vector, a coordinate
tuple, or an RGB triplet.
- You want the Arrow schema to **statically encode the size**, enabling optimised
columnar storage and stricter validation.
- You are working with **embedding vectors** or other ML features where dimensionality
is always known and constant.
If you do **not** pass a `size` argument, `MosaicoType.list_(T)` and `list[T]` produce
an identical Arrow schema. The choice then becomes a matter of style or explicitness:
```python
tags: list[str] # idiomatic Python - preferred for readability
tags: MosaicoType.list_(str) # explicit Mosaico style - equivalent result
```
!!! note "Note"
Explicit type definition and fallback types properties are hold in this case.
#### Matrix types
For 2-D matrix fields, `MosaicoType` exposes a [`matrix()`][mosaicolabs.models.MosaicoType.matrix] static method that composes two nested [`list_()`][mosaicolabs.models.MosaicoType.list_] calls to represent a rectangular grid of shape `(rows, cols)`.
Both dimensions are optional: omitting a dimension produces a variable-length axis, while supplying an integer value produces a fixed-size axis via Arrow's `pa.list_(type, list_size=N)`.
```python
from mosaicolabs import MosaicoField, Serializable
class MyOntology(Serializable):
# Fully variable matrix of float32
heatmap: Optional[MosaicoType.matrix(MosaicoType.float32)] = None
# Fixed 4×4 matrix
t: MosaicoType.matrix(MosaicoType.float32, rows=4, cols=4)
# Fixed-width rows, variable number of rows (e.g. token embeddings)
embeddings: MosaicoType.matrix(MosaicoType.float32, cols=768)
# Works with raw Python primitives too
grid: MosaicoType.matrix(int, rows=8, cols=8)
# Works also with other ontologies
onto: MosaicoType.matrix(Vector3d)
```
| | `matrix(T)` | `matrix(T, cols=N)` | `matrix(T, rows=M, cols=N)` |
|---|---|---|---|
| Arrow type | `pa.list_(pa.list_(T))` | `pa.list_(pa.list_(T, N))` | `pa.list_(pa.list_(T, N), M)` |
| Row count enforced | No | No | Yes, exactly M |
| Column count enforced | No | Yes, exactly N | Yes, exactly N |
| Interoperable with Pydantic | Yes | Yes | Yes |
| Support nested models | Yes | Yes | Yes |
Use [`MosaicoType.matrix()`][mosaicolabs.models.MosaicoType.matrix] with explicit `rows` and/or `cols` when:
- The field represents a **fixed-shape 2-D structure**.
- You want the Arrow schema to **statically encode both dimensions**, enabling optimised columnar storage and stricter validation.
- You are working with **fixed-width embedding matrices** where the column dimension (feature size) is always constant but the number of rows may vary.
If neither dimension is provided, `MosaicoType.matrix(T)` produces a fully variable nested list, equivalent to `list[list[T]]`.
!!! note "Note"
Explicit type definition and fallback type properties apply here as well.
#### Tensor3d types
For 3-D tensor fields, `MosaicoType` exposes a [`tensor3d()`][mosaicolabs.models.MosaicoType.tensor3d] static method that composes a [`matrix()`][mosaicolabs.models.MosaicoType.matrix] call with an outer [`list_()`][mosaicolabs.models.MosaicoType.list_] call to represent a volume of shape `(depth, rows, cols)`.
All three dimensions are optional and follow the same convention as `matrix()`: omitting a dimension yields a variable-length axis; supplying an integer value produces a fixed-size axis.
```python
from mosaicolabs import MosaicoField, Serializable
class MyOntology(Serializable):
# Fully variable 3-D tensor of float32
volume: Optional[MosaicoType.tensor3d(MosaicoType.float32)] = None
# Fixed-depth stack of variable matrices
f: MosaicoType.tensor3d(MosaicoType.float32, depth=16)
# Fully fixed tensor
j: MosaicoType.tensor3d(MosaicoType.float32, depth=3, rows=4, cols=5)
# Works with raw Python primitives too
cube: MosaicoType.tensor3d(int, depth=8, rows=8, cols=8)
# Works also with other Ontology model
onto: MosaicoType.tensor3d(Vector3d)
```
| | `tensor3d(T)` | `tensor3d(T, depth=D)` | `tensor3d(T, depth=D, rows=M, cols=N)` |
|---|---|---|---|
| Arrow type | `pa.list_(pa.list_(pa.list_(T)))` | `pa.list_(pa.list_(pa.list_(T)), D)` | `pa.list_(pa.list_(pa.list_(T, N), M), D)` |
| Depth enforced | No | Yes, exactly D | Yes, exactly D |
| Row count enforced | No | No | Yes, exactly M |
| Column count enforced | No | No | Yes, exactly N |
| Interoperable with Pydantic | Yes | Yes | Yes |
| Supoprt nested model | Yes | Yes | Yes |
Use [`MosaicoType.tensor3d()`][mosaicolabs.models.MosaicoType.tensor3d] with explicit dimensions when:
- The field represents a **fixed-shape volumetric structure**.
- You want the Arrow schema to **statically encode all three dimensions**, enabling stricter schema validation and more efficient columnar storage.
- You are working with **multi-channel ML features** (e.g. convolutional layer outputs) where depth, height, and width are always known and constant.
If none of the dimensions are provided, `MosaicoType.tensor3d(T)` produces a fully variable nested list, equivalent to three nested `list[list[list[T]]]`.
!!! note "Note"
Explicit type definition and fallback type properties apply here as well. When all dimensions are fixed, the Arrow schema enforces shape constraints at the column level, making `tensor3d` the recommended choice for any ML pipeline where tensor dimensionality is statically known.
#### Custom Arrow types
For specialised Arrow types not covered by the built-in aliases, you can always use [`MosaicoType.annotate()`][mosaicolabs.models.MosaicoType.annotate] method.
This utility allows you to embed a raw PyArrow type directly into your ontology while maintaining full compatibility with the Mosaico schema builder.
[`MosaicoType.annotate()`][mosaicolabs.models.MosaicoType.annotate] is a helper designed to bridge standard Python types with specific PyArrow configurations
(like timestamp precision or timezones). It requires two arguments:
* **The Python Fallback Type**: Used for runtime validation and Python-side type hinting (e.g., int, str).
* **The PyArrow Type**: The specific pyarrow type object to be used in the schema.
```python
from mosaicolabs import Serializable, MosaicoField
class MyOntology(Serializable):
ts: MosaicoType.annotate(int, pa.timestamp("us", tz="UTC")) = MosaicoField(
description="UTC timestamp.")
```
!!! info "Migration Note"
Using `MosaicoType.annotate(int, ...)` is functionally equivalent to the standard `Annotated[int, ...]`, but it provides a more explicit and optimized path for the Mosaico schema builder to resolve complex Arrow types.
### MosaicoField
??? question "API Reference"
[`mosaicolabs.models.types.MosaicoField`][mosaicolabs.models.types.MosaicoField]
`MosaicoField` is a factory function that returns a standard Pydantic `Field` instance, adding Mosaico-specific semantics on top of the native `pydantic.Field`. Because the return type is a native Pydantic `Field`, every standard Pydantic feature like validators, aliases, `model_fields` introspection, works out of the box.
#### Basic usage
```python
from mosaicolabs import MosaicoType, MosaicoField, Serializable
class MyPointOntology(Serializable):
x: MosaicoType.float32 = MosaicoField(description="X coordinate")
y: MosaicoType.float32 = MosaicoField(description="Y coordinate")
label: Optional[MosaicoType.string] = MosaicoField(
default=None, description="Point label")
score: MosaicoType.float32 = MosaicoField(nullable=True)
```
With `MosaicoField` you can define the `default` value of your attribute, the `nullable` attribute of pyarrow field and also a `description`.
In particular you can omit `nullable` if your `default = None`, in this case `nullable` will be set to `True` automatically.
### Nullability and Parquet V2
The `nullable` flag in `MosaicoField` controls whether the Arrow schema emits the field
as nullable. The default is `False`, fields are non-nullable unless explicitly stated
otherwise.
The distinction matters most when a reusable struct ontology is embedded inside a parent
ontology as an optional field. Consider a `Quaternion`: its individual components
(`x`, `y`, `z`, `w`) are logically required — a quaternion with missing components is
meaningless and cannot be constructed.
However, all four leaf fields must be declared as nullable due to how ParquetV2 handles
`null` optional columns during data reading. Consider a parent class such as `IMU`,
where `orientation` is declared as `Optional[Quaternion]`. If that column is `null` in
the Parquet file but the inner fields are **not** nullable in the schema, ParquetV2
cannot represent the absent struct correctly and instead reconstructs it as a
zero-initialised instance:
```python
# wrong — should be None
orientation = Quaternion(x=0, y=0, z=0, w=0)
```
Declaring all leaf fields as nullable prevents this silent corruption: a fully-null
struct is preserved as `None` through the read/write round-trip, matching the original
intent of the `Optional` annotation.
```python
class Quaternion(Serializable):
x: MosaicoType.float32 = MosaicoField(description="X component", nullable=True)
y: MosaicoType.float32 = MosaicoField(description="Y component", nullable=True)
z: MosaicoType.float32 = MosaicoField(description="Z component", nullable=True)
w: MosaicoType.float32 = MosaicoField(description="W component", nullable=True)
```
A parent ontology may choose to include the quaternion as an optional field — for
example, a detection without orientation data is still valid. In that case the *struct*
itself must also be nullable in the Arrow schema:
```python
class DetectionOntology(Serializable):
position: MosaicoType.float32 = MosaicoField(description="Position")
# The quaternion struct as a whole is optional in this ontology,
# but its internal fields remain required when it is present.
orientation: Optional[QuaternionOntology] = MosaicoField(nullable=True, default=None)
```
## Architecture
The ontology architecture relies on three primary abstractions: the **Factory** (`Serializable`), the **Envelope** (`Message`) and the **Mixins**
### `Serializable` (The Factory)
??? question "API Reference"
[`mosaicolabs.models.Serializable`][mosaicolabs.models.Serializable]
Every data payload in Mosaico inherits from the `Serializable` class. It manages the global registry of data types and ensures that the system knows exactly how to convert a string tag like `"imu"` back into a Python class with a specific binary schema.
`Serializable` uses the `__pydantic_init_subclass__` hook, which is automatically called whenever a developer defines a new subclass.
```python
class MyCustomSensor(Serializable): # <--- __pydantic_init_subclass__ triggers here
...
```
When this happens, `Serializable` performs the following steps automatically:
1. **Generate the schema:** Introspect `model_fields` to extract the PyArrow type embedded in each field's `Annotated` metadata via `MosaicoType` aliases or raw `Annotated[T, pa.SomeType()]` annotations and build the `__msco_pyarrow_struct__` automatically.
2. **Generates Tag:** If the class doesn't define `__ontology_tag__`, it auto-generates one from the class name (e.g., `MyCustomSensor` -> `"my_custom_sensor"`).
3. **Registers Class:** It adds the new class to the global types registry.
4. **Injects Query Proxy:** It dynamically adds a `.Q` attribute to the class, enabling the fluent query syntax (e.g., `MyCustomSensor.Q.voltage > 12.0`).
### `Message` (The Envelope)
??? question "API Reference"
[`mosaicolabs.models.Message`][mosaicolabs.models.Message]
The **`Message`** class is the universal transport envelope for all data within the Mosaico platform. It acts as the "Source of Truth" for synchronization and spatial context, combining specific sensor data (the payload) with critical middleware-level metadata. By centralizing metadata at the envelope level, Mosaico ensures that every data point—regardless of its complexity—carries a consistent temporal and spatial identity.
```python
from mosaicolabs import Message, Time, Temperature
# Create a Temperature message with unified envelope metadata
meas_time = Time.now()
temp_msg = Message(
timestamp_ns=meas_time.to_nanoseconds(), # Primary synchronization clock
frame_id="comp_case", # Spatial reference frame
seq_id=101, # Optional sequence ID for ordering
data=Temperature.from_celsius(
value=57,
variance=0.03
)
)
```
While logically a `Message` contains a `data` object, the physical representation on the wire (PyArrow/Parquet) is **flattened**,
ensuring zero-overhead access to nested data during queries while maintaining a clean, object-oriented API in Python.
* **Logical:** `Message(timestamp_ns=123, frame_id="map", data=IMU(acceleration=Vector3d(x=1.0,...)))`
* **Physical:** `Struct(timestamp_ns=123, frame_id="map", seq_id=null, acceleration, ...)`
The `Message` mechanism enables a flexible dual-usage pattern for every Mosaico ontology type, supporting both **Standalone Messages** and **Embedded Fields**.
#### Standalone Messages
Any `Serializable` type (from elementary types like `String` and `Float32` to complex sensors like `IMU`) can be used as a standalone message. When assigned to the `data` field of a `Message` envelope, the type represents an independent data stream with its own global timestamp and metadata, that can be pushed via a dedicated [`TopicWriter`][mosaicolabs.handlers.TopicWriter].
This is ideal for pushing processed signals, debug values, or simple sensor readings.
```python
# Sending a raw Vector3d as a timestamped standalone message with its own uncertainty
accel_msg = Message(
timestamp_ns=ts,
frame_id="base_link",
data=Vector3d(
x=0.0,
y=0.0,
z=9.81,
covariance=[0.01, 0, 0, 0, 0.01, 0, 0, 0, 0.01] # 3x3 Diagonal matrix
)
)
accel_writer.push(message=accel_msg)
# Sending a raw String as a timestamped standalone message
log_msg = Message(
timestamp_ns=ts,
frame_id="base_link",
data=String(data="Waypoint-miss in navigation detected!")
)
log_writer.push(message=log_msg)
```
#### Embedded Fields
`Serializable` types can also be embedded as internal fields within a larger structure. In this context, they behave as standard data types. While the parent `Message` provides the global temporal context, the embedded fields can carry their own granular attributes, such as unique uncertainty matrices.
```python
# Embedding Vector3d inside a complex IMU model
imu_payload = IMU(
# Embedded Field 1: Acceleration with its own specific uncertainty
# Here the Vector3d instance inherits the timestamp and frame_id
# from the parent IMU Message.
acceleration=Vector3d(
x=0.5, y=-0.2, z=9.8,
covariance=[0.1, 0, 0, 0, 0.1, 0, 0, 0, 0.1]
),
# Embedded Field 2: Angular Velocity
angular_velocity=Vector3d(x=0.0, y=0.0, z=0.0)
)
# Wrap the complex payload in the Message envelope
imu_writer.push(Message(timestamp_ns=ts, frame_id="imu_link", data=imu_payload))
```
### Mixins: Uncertainty & Robustness
Mosaico uses **Mixins** to inject standard uncertainty fields across different data types, ensuring a consistent interface for sensor fusion and error analysis. These fields are typically used to represent the precision of the sensor data.
#### `CovarianceMixin`
??? question "API Reference"
[`mosaicolabs.models.mixins.CovarianceMixin`][mosaicolabs.models.mixins.CovarianceMixin]
Injects multidimensional uncertainty fields, typically used for flattened covariance matrices (e.g., 3x3 or 6x6) in sensor fusion applications.
```python
class MySensor(Serializable, CovarianceMixin):
# Automatically receives covariance and covariance_type fields
...
```
#### `VarianceMixin`
??? question "API Reference"
[`mosaicolabs.models.mixins.VarianceMixin`][mosaicolabs.models.mixins.VarianceMixin]
Injects monodimensional uncertainty fields, useful for sensors with 1-dimensional uncertain data like `Temperature` or `Pressure`.
```python
class MySensor(Serializable, VarianceMixin):
# Automatically receives variance and variance_type fields
...
```
By leveraging these mixins, the platform can perform deep analysis on data quality—such as filtering for only "high-confidence" segments—without requiring unique logic for every sensor type.
### Extending with Mixins
One of the most powerful consequences of building on top of Pydantic model fields is how natural **mixin composition** becomes. Because every field, including its Arrow type metadata, lives in `model_fields`, you can split concerns into focused mixin classes and combine them freely without any additional registration or schema merging step.
```python
from mosaicolabs import BaseModel, MosaicoType, MosaicoField, Serializable
class GeometryMixin(BaseModel):
x: MosaicoType.float32 = MosaicoField(description="X coordinate")
y: MosaicoType.float32 = MosaicoField(description="Y coordinate")
z: MosaicoType.float32 = MosaicoField(description="Z coordinate")
class ConfidenceMixin(BaseModel):
confidence: MosaicoType.float32 = MosaicoField(description="Detection score [0, 1]")
class MetadataMixin(BaseModel):
label: Optional[MosaicoType.string] = MosaicoField(default=None, nullable=True)
sensor_id: MosaicoType.string = MosaicoField(description="Source sensor identifier")
ts: Annotated[int, pa.timestamp("us", tz="UTC")]
# Combine mixins, the Arrow schema aggregates all fields automatically
class DetectionOntology(Serializable, GeometryMixin, ConfidenceMixin, MetadataMixin):
pass
```
When `DetectionOntology` is defined, `__pydantic_init_subclass__` calls `_build_ontology_struct`, which walks the full `model_fields` MRO chain, extracts the PyArrow metadata from each `Annotated` annotation, and produces a single consolidated `pa.struct`, no extra code required.
This makes ontology composition **additive by default**: add a mixin to inherit its fields, remove it to drop them. The schema stays consistent with zero boilerplate.
## Querying Data Ontology with the Query (`.Q`) Proxy
The Mosaico SDK allows you to perform deep discovery directly on the physical content of your sensor streams. Every class inheriting from [`Serializable`][mosaicolabs.models.Serializable], including standard sensors, geometric primitives, and custom user models, is automatically injected with a static **`.Q` proxy** attribute.
This proxy acts as a type-safe bridge between your Python data models and the platform's search engine, enabling you to construct complex filters using standard Python dot notation.
### How the Proxy Works
The `.Q` proxy recursively inspects the model’s schema to expose every queryable field path. It identifies the data type of each field and provides only the operators valid for that type (e.g., numeric comparisons for acceleration, substring matches for frame IDs).
* **Direct Field Access**: Filter based on primary values, such as `Temperature.Q.value.gt(25.0)`.
* **Nested Navigation**: Traverse complex, embedded structures. For example, in the [`GPS`][mosaicolabs.models.sensors.GPS] model, you can drill down into the status sub-field: `GPS.Q.status.satellites.geq(8)`.
* **Mixin Integration**: Fields inherited from mixins are automatically included in the proxy. This allows you to query uncertainty metrics (from `VarianceMixin` or `CovarianceMixin`) across any model.
### Queryability Examples
The following table illustrates how the proxy flattens complex hierarchies into queryable paths:
| Type Field Path | Proxy Field Path | Source Type | Queryable Type | Supported Operators |
| --- | --- | --- | --- | --- |
| `IMU.acceleration.x` | `IMU.Q.acceleration.x` | `float` | **Numeric** | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `GPS.status.hdop` | `GPS.Q.status.hdop` | `float` | **Numeric** | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `IMU.frame_id` | `IMU.Q.frame_id` | `str` | **String** | `.eq()`, `.match()`, `.in_()`, `.lt()`, `.gt()`, `.leq()`, `.geq()` |
| `GPS.covariance_type` | `GPS.Q.covariance_type` | `int` | **Numeric** | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### Practical Usage
To execute these filters, pass the expressions generated by the proxy to the [`QueryOntologyCatalog`][mosaicolabs.models.query.builders.QueryOntologyCatalog] builder.
```python
from mosaicolabs import MosaicoClient, IMU, GPS, QueryOntologyCatalog
with MosaicoClient.connect("localhost", 6726) as client:
# orchestrate a query filtering by physical thresholds AND metadata
qresponse = client.query(
QueryOntologyCatalog(include_timestamp_range=True) # Ask for the start/end timestamps of occurrences
.with_expression(IMU.Q.acceleration.z.gt(15.0))
.with_expression(GPS.Q.status.service.eq(2))
)
# The server returns a QueryResponse grouped by Sequence for structured data management
if qresponse is not None:
for item in qresponse:
# 'item.sequence' contains the name for the matched sequence
print(f"Sequence: {item.sequence.name}")
# 'item.topics' contains only the topics and time-segments
# that satisfied the QueryOntologyCatalog criteria
for topic in item.topics:
# Access high-precision timestamps for the data segments found
start, end = topic.timestamp_range.start, topic.timestamp_range.end
print(f" Topic: {topic.name} | Match Window: {start} to {end}")
```
For a comprehensive list of all supported operators and advanced filtering strategies (such as query chaining), see the **[Full Query Documentation](./query.md)** and the Ontology types SDK Reference in the **API Reference**:
??? question "API Reference"
* [Base Data Models](./API_reference/models/data_types.md)
* [Sensors Models](./API_reference/models/sensors.md)
* [Geometry Models](./API_reference/models/geometry.md)
* [Platform Models](./API_reference/models/platform.md)
## Customizing the Ontology
The Mosaico SDK is built for extensibility, allowing you to define domain-specific data structures that can be registered to the platform and live alongside standard types.
Custom types are automatically validatable, serializable, and queryable once registered in the platform.
Follow these three steps to implement a compatible custom data type:
### 1. Inheritance and Mixins
Your custom class **must** inherit from `Serializable` to enable auto-registration, factory creation, and the queryability of the model.
To align with the Mosaico ecosystem, use the following mixins:
* **`CovarianceMixin`**: Used for data including measurement uncertainty, standardizing the storage of covariance matrices.
### 2. Define the Wire Schema
Annotate each field with a `MosaicoType` alias and wrap it with `MosaicoField`. Fields and schema are declared together in a single annotation — the `__msco_pyarrow_struct__` is derived automatically from `model_fields` at class-definition time, so there is no separate schema declaration to maintain.
#### 2.1 Serialization Format Optimization
??? question "API Reference"
[`mosaicolabs.enum.SerializationFormat`][mosaicolabs.enum.SerializationFormat]
You can optimize remote server performance by overriding the `__serialization_format__` attribute. This controls how the server compresses and organizes your data.
| Format | Identifier | Use Case Recommendation |
| --- | --- | --- |
| **Default** | `"default"` | **Standard Table**: Fixed-width data with a constant number of fields. |
| **Ragged** | `"ragged"` | **Variable Length**: Best for lists, sequences, or point clouds. |
| **Image** | `"image"` | **Blobs**: Raw or compressed images requiring specialized codec handling. |
If not explicitly set, the system defaults to `Default` format.
### Customization Example: `EnvironmentSensor`
This example demonstrates a custom sensor for environmental monitoring that tracks temperature, humidity, and pressure.
```python
# file: custom_ontology.py
from typing import Optional
import pyarrow as pa
from mosaicolabs.models import MosaicoField, MosaicoType, Serializable
class EnvironmentSensor(Serializable):
"""
Custom sensor reading for Temperature, Humidity, and Pressure.
"""
# --- 1. Define the Wire Schema ---
temperature: MosaicoType.float32
humidity: Optional[MosaicoType.float32] = MosaicoField(
default= None, nullable=True)
pressure: Optional[MosaicoType.float32] = MosaicoField(
default= None, nullable=True)
# --- Usage Example ---
from mosaicolabs.models import Message, Header, Time
# Initialize with standard metadata
meas = EnvironmentSensor(
header=Header(stamp=Time.now(), frame_id="lab_sensor_1"),
temperature=23.5,
humidity=0.45
)
# Ready for streaming or querying
# writer.push(Message(timestamp_ns=ts, data=meas))
```

Schema for defining a custom ontology model.
---
# The Query Workflow
The **Query Workflow** in Mosaico provides a high-performance, **fluent** interface for discovering and filtering data within the Mosaico Data Platform. It is designed to move beyond simple keyword searches, allowing you to perform deep, semantic queries across metadata, system catalogs, and the physical content of sensor streams.
!!! info "API-Keys"
When the connection is established via the authorization middleware (i.e. using an [API-Key](./client.md#2-authentication-api-key)), the query workflow requires the minimum [`APIKeyPermissionEnum.Read`][mosaicolabs.enum.APIKeyPermissionEnum.Read] permission.
!!! example "Try-It Out"
You can experiment yourself the Query module via the **[Querying Catalogs](https://docs.mosaico.dev/demo/querying_catalogs) Example**.
A typical query workflow involves chaining methods within specialized builders to create a unified request that the server executes atomically. In the example below, the code orchestrates a multi-domain search to isolate high-interest data segments. Specifically, it queries for:
* **Sequence Discovery**: Finds any recording session whose name contains the string `"test_drive"` **AND** where the custom user metadata indicates an `"environment.visibility"` value strictly less than 50.
* **Topic Filtering**: Restricts the search specifically to the data channel named `"/front/camera/image"`.
* **Ontology Analysis**: Performs a deep inspection of IMU sensor payloads to identify specific time segments where the **X-axis acceleration exceeds a certain threshold** while simultaneously the **Y-axis acceleration exceeds a certain threshold**.
```python
from mosaicolabs import QueryOntologyCatalog, QuerySequence, QueryTopic, IMU, MosaicoClient
# Establish a connection to the Mosaico Data Platform
with MosaicoClient.connect("localhost", 6726) as client:
# Perform a unified server-side query across multiple domains:
qresponse = client.query(
# Filter Sequence-level metadata
QuerySequence()
.with_name_match("test_drive") # Use convenience method for fuzzy name matching
.with_user_metadata("environment.visibility", lt=50), # Use convenience method for filtering user metadata
# Search on topics with specific names
QueryTopic()
.with_name("/front/camera/image"),
# Perform deep time-series discovery within sensor payloads
QueryOntologyCatalog(include_timestamp_range=True) # Request temporal bounds for matches
.with_expression(IMU.Q.acceleration.x.gt(5.0)) # Use the .Q proxy to filter the `acceleration` field
.with_expression(IMU.Q.acceleration.y.gt(4.0)),
)
# The server returns a QueryResponse grouped by Sequence for structured data management
if qresponse is not None:
for item in qresponse:
# 'item.sequence' contains the name for the matched sequence
print(f"Sequence: {item.sequence.name}")
# 'item.topics' contains only the topics and time-segments
# that satisfied the QueryOntologyCatalog criteria
for topic in item.topics:
# Access high-precision timestamps for the data segments found
start, end = topic.timestamp_range.start, topic.timestamp_range.end
print(f" Topic: {topic.name} | Match Window: {start} to {end}")
```
The provided example illustrates the core architecture of the Mosaico Query DSL. To effectively use this module, it is important to understand the two primary mechanisms that drive data discovery:
* **Query Builders (Fluent Logic Collectors)**: Specialized builders like [`QuerySequence`][mosaicolabs.models.query.builders.QuerySequence], [`QueryTopic`][mosaicolabs.models.query.builders.QueryTopic], and [`QueryOntologyCatalog`][mosaicolabs.models.query.builders.QueryOntologyCatalog] serve as containers for your search criteria. They provide a **Fluent Interface** where you can chain two types of methods:
* **Convenience Methods**: High-level helpers for common fields, such as `with_user_metadata()`, `with_name_match()`, or `with_created_timestamp()`.
* **Generic `with_expression()`**: A versatile method that accepts any expression obtained via the **`.Q` proxy**, allowing you to define complex filters for deep sensor payloads.
* **The `.Q` Proxy (Dynamic Model Inspection)**: Every [`Serializable`][mosaicolabs.models.serializable.Serializable] model in the Mosaico ontology features a static `.Q` attribute. This proxy dynamically inspects the model's underlying schema to build dot-notated field paths and intercepts attribute access (e.g., `IMU.Q.acceleration.x`). When a terminal method is called—such as `.gt()`, `.lt()`, or `.between()`—it generates a type-safe **Atomic Expression** used by the platform to filter physical sensor data or metadata fields.
By combining these mechanisms, the Query Module delivers a robust filtering experience:
* **Multi-Domain Orchestration**: Execute searches across Sequence metadata, Topic configurations, and raw Ontology sensor data in a single, atomic request.
* **Structured Response Management**: Results are returned in a [`QueryResponse`][mosaicolabs.models.query.response.QueryResponse] that is automatically grouped by `Sequence`, making it easier to manage multi-sensor datasets.
## Query Execution & The Response Model
Queries are executed via the [`query()`][mosaicolabs.comm.MosaicoClient.query] method exposed by the [`MosaicoClient`][mosaicolabs.comm.MosaicoClient] class. When multiple builders are provided, they are combined with a logical **AND**.
| Method | Return | Description |
| :--- | :--- | :--- |
| [`query(*queries, query)`][mosaicolabs.comm.MosaicoClient.query] | [`Optional[QueryResponse]`][mosaicolabs.models.query.response.QueryResponse] | Executes one or more queries against the platform catalogs. The provided queries are joined in AND condition. The method accepts a variable arguments of query builder objects or a pre-constructed [`Query`][mosaicolabs.models.query.builders.Query] object.|
The query execution returns a [`QueryResponse`][mosaicolabs.models.query.response.QueryResponse] object, which behaves like a standard Python list containing [`QueryResponseItem`][mosaicolabs.models.query.response.QueryResponseItem] objects.
| Class | Description |
| --- | --- |
| [`QueryResponseItem`][mosaicolabs.models.query.response.QueryResponseItem] | Groups all matches belonging to the same **Sequence**. Contains a `QueryResponseItemSequence` and a list of related `QueryResponseItemTopic`.|
| [`QueryResponseItemSequence`][mosaicolabs.models.query.response.QueryResponseItemSequence] | Represents a specific **Sequence** where matches were found. It includes the sequence name. |
| [`QueryResponseItemTopic`][mosaicolabs.models.query.response.QueryResponseItemTopic] | Represents a specific **Topic** where matches were found. It includes the normalized topic path and the optional `timestamp_range` (the first and last occurrence of the condition). |
```python
import sys
from mosaicolabs import MosaicoClient, QueryOntologyCatalog
from mosaicolabs.models.sensors import IMU
# Establish a connection to the Mosaico Data Platform
with MosaicoClient.connect("localhost", 6726) as client:
# Define a Deep Data Filter using the .Q Query Proxy
# We are searching for vertical impact events where acceleration.z > 15.0 m/s^2
impact_qbuilder = QueryOntologyCatalog(
IMU.Q.acceleration.z.gt(15.0),
# include_timestamp_range returns the precise start/end of the matching event
include_timestamp_range=True
)
# Execute the query via the client
results = client.query(impact_qbuilder)
# The same can be obtained by using the Query object
# results = client.query(
# query = Query(
# impact_qbuilder
# )
# )
if results is not None:
# Parse the structured QueryResponse object
# Results are automatically grouped by Sequence for easier data management
for item in results:
print(f"Sequence: {item.sequence.name}")
# Iterate through matching topics within the sequence
for topic in item.topics:
# Topic names are normalized (sequence prefix is stripped) for direct use
print(f" - Match in: {topic.name}")
# Extract the temporal bounds of the event
if topic.timestamp_range:
start = topic.timestamp_range.start
end = topic.timestamp_range.end
print(f" Occurrence: {start} ns to {end} ns")
```
* **Temporal Windows**: The `timestamp_range` provides the first and last occurrence of the queried condition within a topic, allowing you to slice data accurately for further analysis.
* **Result Normalization**: `topic.name` returns the relative topic path (e.g., `/sensors/imu`), making it immediately compatible with other SDK methods like [`topic_handler()`][mosaicolabs.comm.MosaicoClient.topic_handler].
### Restricted Queries (Chaining)
The `QueryResponse` class enables a powerful mechanism for **iterative search refinement** by allowing you to convert your current results back into a new query builder.
This approach is essential for resolving complex, multi-modal dependencies where a single monolithic query would be logically ambiguous, inefficient or technically impossible.
| Method | Return Type | Description |
| --- | --- | --- |
| [`to_query_sequence()`][mosaicolabs.models.query.response.QueryResponse.to_query_sequence] | [`QuerySequence`][mosaicolabs.models.query.builders.QuerySequence] | Returns a query builder pre-filtered to include only the **sequences** present in the response. |
| [`to_query_topic()`][mosaicolabs.models.query.response.QueryResponse.to_query_topic] | [`QueryTopic`][mosaicolabs.models.query.builders.QueryTopic] | Returns a query builder pre-filtered to include only the specific **topics** identified in the response. |
When you invoke these factory methods, the SDK generates a new query expression containing an explicit `$in` filter populated with the identifiers held in the current response. This effectively **"locks" the search domain**, allowing you to apply new criteria to a restricted subset of your data without re-scanning the entire platform catalog.
```python
from mosaicolabs import MosaicoClient, QueryTopic, QueryOntologyCatalog, GPS, String
with MosaicoClient.connect("localhost", 6726) as client:
# Broad Search: Find all sequences where a GPS sensor reached a high-precision state (status=2)
initial_response = client.query(
QueryOntologyCatalog(GPS.Q.status.status.eq(2))
)
# 'initial_response' now acts as a filtered container of matching sequences.
# Domain Locking: Restrict the search scope to the results of the initial query
if not initial_response.is_empty():
# .to_query_sequence() generates a QuerySequence pre-filled with the matching sequence names.
refined_query_builder = initial_response.to_query_sequence()
# Targeted Refinement: Search for error patterns ONLY within the restricted domain
# This ensures the platform only scans for '[ERR]' strings within sequences already validated for GPS precision.
final_response = client.query(
refined_query_builder, # The "locked" sequence domain
QueryTopic().with_name("/localization/log_string"), # Target a specific log topic
QueryOntologyCatalog(String.Q.data.match("[ERR]")) # Filter by exact data content pattern
)
```
When a specific set of topics has been identified through a data-driven query (e.g., finding every camera topic that recorded a specific event), you can use `to_query_topic()` to "lock" your next search to those specific data channels. This is particularly useful when you need to verify a condition on a very specific subset of sensors across many sequences, bypassing the need to re-identify those topics in the next step.
In the next example, we first find all topics of a specific channel from a specific sequence name pattern, and then search specifically within *those* topics for any instances where the data content matches a specific pattern.
```python
from mosaicolabs import MosaicoClient, QueryTopic
with MosaicoClient.connect("localhost", 6726) as client:
# Broad Search: Find sequences with high-precision GPS
initial_response = client.query(
QueryTopic().with_name("/localization/log_string"), # Target a specific log topic
QuerySequence().with_name_match("test_winter_2025_") # Filter by sequence name pattern
)
# Chaining: Use results to "lock" the domain and find specific log-patterns in those sequences
if not initial_response.is_empty():
final_response = client.query(
initial_response.to_query_topic(), # The "locked" topic domain
QueryOntologyCatalog(String.Q.data.match("[ERR]")) # Filter by content
)
```
#### When Chaining is Necessary
The previous example of the `GPS.status` query and the subsequent `/localization/log_string` topic search highlight exactly when *query chaining* becomes a technical necessity rather than just a recommendation. In the Mosaico Data Platform, a single `client.query()` call applies a logical **AND** across all provided builders to locate individual **data streams (topics)** that satisfy every condition simultaneously.
Because a single topic cannot physically represent two different sensor types at once, such as being both a `GPS` sensor and a `String` log, a monolithic query attempting to filter for both on the same stream will inherently return zero results. Chaining resolves this by allowing you to find the correct **Sequence** context in step one, then "locking" that domain to find a different **Topic** within that same context in step two.
```python
# AMBIGUOUS: This looks for ONE topic that is BOTH GPS and String
response = client.query(
QueryOntologyCatalog(GPS.Q.status.status.eq(DGPS_FIX)),
QueryOntologyCatalog(String.Q.data.match("[ERR]")),
QueryTopic().with_name("/localization/log_string")
)
```
## Architecture
### Query Layers
Mosaico organizes data into three distinct architectural layers, each with its own specialized Query Builder:
#### [`QuerySequence`][mosaicolabs.models.query.builders.QuerySequence] (Sequence Layer)
??? question "API Reference"
[`mosaicolabs.models.query.builders.QuerySequence`][mosaicolabs.models.query.builders.QuerySequence].
Filters recordings based on high-level session metadata, such as the sequence name or the time it was created.
**Example** Querying for sequences by name and creation date
```python
from mosaicolabs import MosaicoClient, Topic, QuerySequence
with MosaicoClient.connect("localhost", 6726) as client:
# Search for sequences by project name and creation date
qresponse = client.query(
QuerySequence()
.with_name_match("test_drive")
.with_user_metadata("project", eq="Apollo")
.with_created_timestamp(time_start=Time.from_float(1690000000.0))
)
# Inspect the response
for item in qresponse:
print(f"Sequence: {item.sequence.name}")
print(f"Topics: {[topic.name for topic in item.topics]}")
```
#### [`QueryTopic`][mosaicolabs.models.query.builders.QueryTopic] (Topic Layer)
??? question "API Reference"
[`mosaicolabs.models.query.builders.QueryTopic`][mosaicolabs.models.query.builders.QueryTopic].
Targets specific data channels within a sequence. You can search for topics by name pattern or by their specific Ontology type (e.g., "Find all GPS topics").
**Example** Querying for image topics by ontology tag, metadata key and topic creation timestamp
```python
from mosaicolabs import MosaicoClient, Image, Topic, QueryTopic
with MosaicoClient.connect("localhost", 6726) as client:
# Query for all 'image' topics created in a specific timeframe, matching some metadata (key, value) pair
qresponse = client.query(
QueryTopic()
.with_ontology_tag(Image.ontology_tag())
.with_created_timestamp(time_start=Time.from_float(170000000))
.with_user_metadata("camera_id.serial_number", eq="ABC123_XYZ")
)
# Inspect the response
if qresponse is not None:
# Results are automatically grouped by Sequence for easier data management
for item in qresponse:
print(f"Sequence: {item.sequence.name}")
print(f"Topics: {[topic.name for topic in item.topics]}")
```
#### [`QueryOntologyCatalog`][mosaicolabs.models.query.builders.QueryOntologyCatalog] (Ontology Catalog Layer)
??? question "API Reference"
[`mosaicolabs.models.query.builders.QueryOntologyCatalog`][mosaicolabs.models.query.builders.QueryOntologyCatalog].
Filters based on the **actual time-series content** of the sensors (e.g., "Find events where `acceleration.z` exceeded a specific value").
**Example** Querying for mixed sensor data
```python
from mosaicolabs import MosaicoClient, QueryOntologyCatalog, GPS, IMU
with MosaicoClient.connect("localhost", 6726) as client:
# Chain multiple sensor filters together
qresponse = client.query(
QueryOntologyCatalog()
.with_expression(GPS.Q.status.satellites.geq(8))
.with_expression(Temperature.Q.value.between([273.15, 373.15]))
.with_expression(Pressure.Q.value.geq(100000))
)
# Inspect the response
if qresponse is not None:
# Results are automatically grouped by Sequence for easier data management
for item in qresponse:
print(f"Sequence: {item.sequence.name}")
print(f"Topics: {[topic.name for topic in item.topics]}")
# Filter for a specific component value and extract the first and last occurrence times
qresponse = client.query(
QueryOntologyCatalog(include_timestamp_range=True)
.with_expression(IMU.Q.acceleration.x.lt(-4.0))
.with_expression(IMU.Q.acceleration.y.gt(5.0))
.with_expression(Pose.Q.rotation.z.geq(0.707))
)
# Inspect the response
if qresponse is not None:
# Results are automatically grouped by Sequence for easier data management
for item in qresponse:
print(f"Sequence: {item.sequence.name}")
print(f"Topics: {{topic.name:
[topic.timestamp_range.start, topic.timestamp_range.end]
for topic in item.topics}}")
```
The Mosaico Query Module offers two distinct paths for defining filters, **Convenience Methods** and **Generic Expression Method**, both of which support **method chaining** to compose multiple criteria into a single query using a logical **AND**.
#### Convenience Methods
The query layers provide high-level fluent helpers (`with_`), built directly into the query builder classes and designed for ease of use.
They allow you to filter data without deep knowledge of the internal model schema.
The builder automatically selects the appropriate field and operator (such as exact match vs. substring pattern) based on the method used.
```python
from mosaicolabs import QuerySequence, QueryTopic, RobotJoint
# Build a filter with name pattern
qbuilder = QuerySequence()
.with_name_match("test_drive")
# Execute the query
qresponse = client.query(qbuilder)
# Inspect the response
if qresponse is not None:
# Results are automatically grouped by Sequence for easier data management
for item in qresponse:
print(f"Sequence: {item.sequence.name}")
print(f"Topics: {[topic.name for topic in item.topics]}")
# Build a filter with ontology tag AND a specific creation time window
qbuilder = QueryTopic()
.with_ontology_tag(RobotJoint.ontology_tag())
.with_created_timestamp(start=t1, end=t2)
# Execute the query
qresponse = client.query(qbuilder)
# Inspect the response
if qresponse is not None:
# Results are automatically grouped by Sequence for easier data management
for item in qresponse:
print(f"Sequence: {item.sequence.name}")
print(f"Topics: {[topic.name for topic in item.topics]}")
```
* **Best For**: Standard system-level fields like Names and Timestamps.
#### Generic Expression Method
The `with_expression()` method accepts raw **Query Expressions** generated through the `.Q` proxy.
This provides full access to every supported operator (`.gt()`, `.lt()`, `.between()`, etc.) for specific fields.
```python
from mosaicolabs import QueryOntologyCatalog, IMU
# Build a filter with deep time-series data discovery and measurement time windowing
qresponse = client.query(
QueryOntologyCatalog()
.with_expression(IMU.Q.acceleration.x.gt(5.0))
.with_expression(IMU.Q.timestamp_ns.gt(1700134567))
)
# Inspect the response
if qresponse is not None:
# Results are automatically grouped by Sequence for easier data management
for item in qresponse:
print(f"Sequence: {item.sequence.name}")
print(f"Topics: {[topic.name for topic in item.topics]}")
```
* **Used For**: Accessing specific Ontology data fields (e.g., acceleration, position, etc.) in stored time-series data.
### The `.Q` Proxy Mechanism
The Query Proxy is the cornerstone of Mosaico's type-safe data discovery. Every data model in the Mosaico Ontology (e.g., `IMU`, `GPS`, `Image`) is automatically injected with a static `.Q` attribute during class initialization. This mechanism transforms static data structures into dynamic, fluent interfaces for constructing complex filters.
The proxy follows a three-step lifecycle to ensure that your queries are both semantically correct and high-performance:
1. **Intelligent Mapping**: During system initialization, the proxy inspects the sensor's schema recursively. It maps every nested field path (e.g., `"acceleration.x"`) to a dedicated *queryable* object, i.e. an object providing comparison operators and expression generation methods.
2. **Type-Aware Operators**: The proxy identifies the data type of each field (numeric, string, dictionary, or boolean) and exposes only the operators valid for that type. This prevents logical errors, such as attempting a substring `.match()` on a numeric acceleration value.
3. **Intent Generation**: When you invoke an operator (e.g., `.gt(15.0)`), the proxy generates a `QueryExpression`. This object encapsulates your search intent and is serialized into an optimized JSON format for the platform to execute.
To understand how the proxy handles nested structures, inherited attributes, and data types, consider the `IMU` ontology class:
```python
class IMU(Serializable):
acceleration: Vector3d # Composed type: contains x, y, z
angular_velocity: Vector3d # Composed type: contains x, y, z
orientation: Optional[Quaternion] = None # Composed type: contains x, y, z, w
```
The `.Q` proxy enables you to navigate the data exactly as it is defined in the model. By following the `IMU.Q` instruction, you can drill down through nested fields and inherited mixins using standard dot notation until you reach a base queryable type.
??? question "API Reference"
[`mosaicolabs.models.sensors.IMU`][mosaicolabs.models.sensors.IMU--querying-with-the-q-proxy]
The proxy automatically flattens the hierarchy, assigning the correct queryable type and operators to each leaf node:
| Proxy Field Path | Queryable Type | Supported Operators (Examples) |
| --- | --- | --- |
| **[`IMU.Q.acceleration.x/y/z`][mosaicolabs.models.sensors.IMU.acceleration--querying-with-the-q-proxy]** | **Numeric** | `.gt()`, `.lt()`, `.geq()`, `.leq()`, `.eq()`, `.between()`, `.in_()` |
| **[`IMU.Q.angular_velocity.x/y/z`][mosaicolabs.models.sensors.IMU.angular_velocity--querying-with-the-q-proxy]** | **Numeric** | `.gt()`, `.lt()`, `.geq()`, `.leq()`, `.eq()`, `.between()`, `.in_()` |
| **[`IMU.Q.orientation.x/y/z/w`][mosaicolabs.models.sensors.IMU.orientation--querying-with-the-q-proxy]** | **Numeric** | `.gt()`, `.lt()`, `.geq()`, `.leq()`, `.eq()`, `.between()`, `.in_()` |
| **[`IMU.Q.timestamp_ns`][mosaicolabs.models.Message.timestamp_ns--querying-with-the-q-proxy]** | **Numeric** | `.gt()`, `.lt()`, `.geq()`, `.leq()`, `.eq()`, `.between()`, `.in_()` |
| **[`IMU.Q.recording_timestamp_ns`][mosaicolabs.models.Message.recording_timestamp_ns--querying-with-the-q-proxy]** | **Numeric** | `.gt()`, `.lt()`, `.geq()`, `.leq()`, `.eq()`, `.between()`, `.in_()` |
| **[`IMU.Q.frame_id`][mosaicolabs.models.Message.frame_id--querying-with-the-q-proxy]** | **String** | `.eq()`, `.match()`, `.in_()`, `.lt()`, `.gt()`, `.leq()`, `.geq()` |
| **[`IMU.Q.sequence_id`][mosaicolabs.models.Message.sequence_id--querying-with-the-q-proxy]** | **Numeric** | `.gt()`, `.lt()`, `.geq()`, `.leq()`, `.eq()`, `.between()`, `.in_()` |
The following table lists the supported operators for each data type:
| Data Type | Operators |
| --- | --- |
| **Numeric** | `.eq()`, `.lt()`, `.leq()`, `.gt()`, `.geq()`, `.between()`, `.in_()` |
| **String** | `.eq()`, `.match()` (i.e. substring), `.in_()`, `.lt()`, `.gt()`, `.leq()`, `.geq()` |
| **Boolean** | `.eq(True/False)` |
| **Dictionary** | `.eq()`, `.lt()`, `.leq()`, `.gt()`, `.geq()`, `.between()`, `.ex()`|
#### Supported vs. Unsupported Types
While the `.Q` proxy is highly versatile, it enforces specific rules on which data structures can be queried:
* **Supported Types**: The proxy resolves all simple (int, float, str, bool) or composed types (like `Vector3d` or `Quaternion`). It will continue to expose nested fields as long as they lead to a primitive base type.
* **Dictionaries**: Dynamic fields, i.e. derived from dictionaries in the ontology models, are fully queryable through the proxy using bracket notation (e.g., `.Q.dict_field["key"]` or `.Q.dict_field["key.subkey.subsubkey"]`). This approach provides the flexibility to search across custom tags and dynamic properties that aren't part of a fixed schema. This dictionary-based querying logic applies to any **custom ontology model** created by the user that contains a `dict` field.
* **Syntax**: Instead of the standard dot notation used for fixed fields, you must use square brackets `["key"]` to target specific dictionary entries.
* **Nested Access**: For dictionaries containing nested structures, you can use **dot notation within the key string** (e.g., `["environment.visibility"]`) to traverse sub-fields.
* **Operator Support**: Because dictionary values are dynamic, these fields are "promiscuous," meaning they support mixed numeric, string, and boolean operators without strict SDK-level type checking.
* **Unsupported Types (Lists and Tuples)**: Any field defined as a container, such as a **List** or **Tuple** (e.g., `covariance: List[float]`), is currently skipped by the proxy generator. These fields will not appear in autocomplete and cannot be used in a query expression.
## Constraints & Limitations
While fully functional, the current implementation (v0.x) has a **Single Occurrence Constraint**.
* **Constraint**: A specific data field path may appear **only once** within a single query builder instance. You cannot chain two separate conditions on the same field (e.g., `.gt(0.5)` and `.lt(1.0)`).
```python
# INVALID: The same field (acceleration.x) is used twice in the constructor
QueryOntologyCatalog() \
.with_expression(IMU.Q.acceleration.x.gt(0.5))
.with_expression(IMU.Q.acceleration.x.lt(1.0)) # <- Error! Duplicate field path
```
* **Solution**: Use the built-in **`.between([min, max])`** operator to perform range filtering on a single field path.
* **Note**: You can still query multiple *different* fields from the same sensor model (e.g., `acceleration.x` and `acceleration.y`) in one builder.
```python
# VALID: Each expression targets a unique field path
QueryOntologyCatalog(
IMU.Q.acceleration.x.gt(0.5), # Unique field
IMU.Q.acceleration.y.lt(1.0), # Unique field
IMU.Q.angular_velocity.x.between([0, 1]), # Correct way to do ranges
include_timestamp_range=True
)
```
---
# Communication Module
## mosaicolabs.comm.MosaicoClient
```
MosaicoClient(
*,
host,
port,
timeout,
control_client,
sentinel,
enable_tls,
compression,
tls_cert,
api_key_fingerprint,
middlewares,
)
```
The gateway to the Mosaico Data Platform.
This class centralizes connection management, and serves as a factory for specialized handlers.
**Internal Constructor** (do not call this directly): The `MosaicoClient` enforces a strict factory pattern for security and proper resource setup. Please use the `connect()` method instead to obtain an initialized client.
Parameters:
| Name | Type | Description | Default |
| `host` | `str` | The remote server host. | *required* |
| `port` | `int` | The remote server port. | *required* |
| `timeout` | `int` | The connection timeout. | *required* |
| `control_client` | `FlightClient` | The primary PyArrow Flight control client. | *required* |
| `sentinel` | `object` | Private object used to verify factory-based instantiation. | *required* |
| `enable_tls` | `bool` | Enable TLS communication. | *required* |
| `compression` | `GRPCCompression` | The compression configuration for gRPC. | *required* |
| `tls_cert` | `Optional[bytes]` | The TLS certificate. | *required* |
| `api_key_fingerprint` | `Optional[str]` | The fingerprint of the API key to use for authentication. | *required* |
| `middlewares` | `dict[str, ClientMiddlewareFactory]` | The middlewares to be used for the connection. | *required* |
### connect`classmethod`
```
connect(
host,
port,
timeout=5,
enable_tls=False,
compression=Null,
tls_cert_path=None,
api_key=None,
)
```
The primary entry point to the Mosaico Data Platform.
This factory method is the **only recommended way** to obtain a valid `MosaicoClient` instance. It orchestrates the necessary handshake, and initializes the communication channel.
Parameters:
| Name | Type | Description | Default |
| `host` | `str` | The server host address (e.g., "127.0.0.1" or "mosaico.local"). | *required* |
| `port` | `int` | The server port (e.g., 6726). | *required* |
| `timeout` | `int` | Maximum time in seconds to wait for a connection response. Defaults to 5. | `5` |
| `enable_tls` | `bool` | Enable the TLS standard one-way TLS (server authenticated only) communication protocol. Defaults to False. If `tls_cert_path` is provided (not None), this flag does not have any effect. | `False` |
| `compression` | `Union[GRPCCompressionAlgorithm, GRPCCompression]` | Enable the compression of record batches sent via gRPC. Defaults to GRPCCompressionAlgorithm.Null (uncompressed). | `Null` |
| `tls_cert_path` | `Optional[str]` | Path to the TLS certificate file. Defaults to None. If `tls_cert_path=None` and `enable_tls=True`, a standard one-way TLS (server authenticated only) connection is established. | `None` |
| `api_key` | `Optional[str]` | The API key for authentication. Defaults to None. | `None` |
Returns:
| Name | Type | Description |
| `MosaicoClient` | `MosaicoClient` | An initialized and connected client ready for operations. |
Raises:
| Type | Description |
| `ConnectionError` | If the server is unreachable or the handshake fails. |
| `ValueError` | If the tls_cert_path is invalid or unable to read the certificate (if using TLS). |
| `FileNotFoundError` | If the tls_cert_path does not exist (if using TLS). |
### from_env`classmethod`
```
from_env(host, port, timeout=5)
```
Creates a MosaicoClient instance by resolving configuration from environment variables.
This method acts as a smart constructor that automatically discovers system settings. It currently focuses on security configurations, specifically resolving TLS settings and Auth API-Key if the required environment variables are present.
As the SDK evolves, this method will be expanded to automatically detect additional parameters from the environment.
Parameters:
| Name | Type | Description | Default |
| `host` | `str` | The server hostname or IP address. | *required* |
| `port` | `int` | The port number of the Mosaico service. | *required* |
| `timeout` | `int` | Maximum time in seconds to wait for a connection response. Defaults to 5. | `5` |
Returns:
| Name | Type | Description |
| `MosaicoClient` | `MosaicoClient` | A client instance pre-configured with discovered settings. |
| | `MosaicoClient` | If no specific environment variables are found, it returns a |
| | `MosaicoClient` | client with default settings. |
### sequence_handler
```
sequence_handler(sequence_name)
```
Retrieves a `SequenceHandler` for the given sequence.
Handlers are cached; subsequent calls for the same sequence return the existing object to avoid redundant handshakes.
Parameters:
| Name | Type | Description | Default |
| `sequence_name` | `str` | The unique identifier of the sequence. | *required* |
Returns:
| Type | Description |
| `Optional[SequenceHandler]` | Optional[SequenceHandler]: A handler for managing sequence operations, or None if not found. |
### topic_handler
```
topic_handler(sequence_name, topic_name)
```
Retrieves a `TopicHandler` for a specific data channel.
Parameters:
| Name | Type | Description | Default |
| `sequence_name` | `str` | The parent sequence name. | *required* |
| `topic_name` | `str` | The specific topic name. | *required* |
Returns:
| Type | Description |
| `Optional[TopicHandler]` | Optional[TopicHandler]: A handler for managing topic operations, or None if not found. |
### sequence_create
```
sequence_create(
sequence_name,
metadata,
on_error=Report,
max_batch_size_bytes=None,
max_batch_size_records=None,
)
```
Creates a new sequence on the platform and returns a `SequenceWriter` for ingestion.
Parameters:
| Name | Type | Description | Default |
| `sequence_name` | `str` | Unique name for the sequence. | *required* |
| `metadata` | `dict[str, Any]` | User-defined metadata to attach. | *required* |
| `on_error` | `SessionLevelErrorPolicy` | Behavior on write failure. Defaults to `SessionLevelErrorPolicy.Report`. | `Report` |
| `max_batch_size_bytes` | `Optional[int]` | Max bytes per Arrow batch. | `None` |
| `max_batch_size_records` | `Optional[int]` | Max records per Arrow batch. | `None` |
Returns:
| Name | Type | Description |
| `SequenceWriter` | `SequenceWriter` | An initialized writer instance. |
Raises:
| Type | Description |
| `RuntimeError` | If the method is called outside a `with` context. |
| `Exception` | If any error occurs during sequence injection. |
### sequence_delete
```
sequence_delete(sequence_name)
```
Permanently deletes a sequence and all its associated data from the server.
This operation is destructive and triggers a cascading deletion of all underlying resources, including all topics and data chunks belonging to the sequence. Once executed, all storage occupied by the sequence is freed.
Parameters:
| Name | Type | Description | Default |
| `sequence_name` | `str` | The unique name of the sequence to remove. | *required* |
Raises:
| Type | Description |
| `Exception` | If any error occurs during sequence deletion. |
### session_delete
```
session_delete(locator)
```
Permanently deletes a session and all its associated data from the server.
This operation is destructive and triggers a cascading deletion of all underlying resources, including all topics and data chunks stored in the session. Once executed, all storage occupied by the session is freed.
Parameters:
| Name | Type | Description | Default |
| `locator` | `str` | The unique locator identifier of the session to remove. The locator format is the complete '`sequence_name`:`session_identifier`'. Obtaining the locator, is possible via:- the `SequenceUpdater.session_locator` property, when updating a sequence, or;- `SequenceHandler.sessions` property and then the related `Session.locator` property. | *required* |
Raises:
| Type | Description |
| `Exception` | If any error occurs during session deletion. |
### list_sequences
```
list_sequences()
```
Retrieves a list of all sequence names available on the server.
Returns:
| Type | Description |
| `List[str]` | List[str]: The list of sequence identifiers. |
### list_sequence_notifications
```
list_sequence_notifications(sequence_name)
```
Retrieves a list of all notifications available on the server for a specific sequence.
Parameters:
| Name | Type | Description | Default |
| `sequence_name` | `str` | The name of the sequence to list notifications for. | *required* |
Returns:
| Type | Description |
| `List[Notification]` | List[Notification]: The list of sequence notifications. |
Raises:
| Type | Description |
| `Exception` | If any error occurs during sequence notification listing. |
### clear_sequence_notifications
```
clear_sequence_notifications(sequence_name)
```
Clears the notifications for a specific sequence from the server.
Parameters:
| Name | Type | Description | Default |
| `sequence_name` | `str` | The name of the sequence. | *required* |
Raises:
| Type | Description |
| `Exception` | If any error occurs during sequence notification clearing. |
### list_topic_notifications
```
list_topic_notifications(sequence_name, topic_name)
```
Retrieves a list of all notifications available on the server for a specific topic
Parameters:
| Name | Type | Description | Default |
| `sequence_name` | `str` | The name of the sequence to list notifications for. | *required* |
| `topic_name` | `str` | The name of the topic to list notifications for. | *required* |
Returns:
| Type | Description |
| `List[Notification]` | List[Notification]: The list of topic notifications. |
Raises:
| Type | Description |
| `Exception` | If any error occurs during topic notification listing. |
### clear_topic_notifications
```
clear_topic_notifications(sequence_name, topic_name)
```
Clears the notifications for a specific topic from the server.
Parameters:
| Name | Type | Description | Default |
| `sequence_name` | `str` | The name of the sequence. | *required* |
| `topic_name` | `str` | The name of the topic. | *required* |
Raises:
| Type | Description |
| `Exception` | If any error occurs during topic notification clearing. |
### query
```
query(*queries, query=None)
```
Executes one or more queries against the Mosaico database.
Multiple provided queries are joined using a logical **AND** condition.
Parameters:
| Name | Type | Description | Default |
| `*queries` | `QueryableProtocol` | Variable arguments of query builder objects (e.g., `QuerySequence`). | `()` |
| `query` | `Optional[Query]` | An alternative pre-constructed Query object. | `None` |
Returns:
| Type | Description |
| `Optional[QueryResponse]` | Optional[QueryResponse]: The query results, or None if an error occurs. |
Raises:
| Type | Description |
| `ValueError` | If conflicting query types are passed or no queries are provided. |
| `Exception` | If any error occurs during query execution. |
### version
```
version()
```
Get the version of the Mosaico server.
Returns:
| Name | Type | Description |
| `str` | `str` | The version of the Mosaico server. |
Raises:
| Type | Description |
| `Exception` | If any error occurs during version retrieval. |
### clear_sequence_handlers_cache
```
clear_sequence_handlers_cache()
```
Clears the internal cache of `SequenceHandler` objects.
### clear_topic_handlers_cache
```
clear_topic_handlers_cache()
```
Clears the internal cache of `TopicHandler` objects.
### api_key_create
```
api_key_create(permission, description, expires_at_ns=None)
```
Creates a new API key with the specified permissions.
Parameters:
| Name | Type | Description | Default |
| `permission` | `APIKeyPermissionEnum` | Permission for the key. | *required* |
| `description` | `str` | Description for the key. | *required* |
| `expires_at_ns` | `Optional[int]` | Optional expiration timestamp in nanoseconds. | `None` |
Returns:
| Name | Type | Description |
| `str` | `Optional[str]` | The generated API key token or None. |
Raises:
| Type | Description |
| `Exception` | If any error occurs during API key creation. |
### api_key_status
```
api_key_status(api_key_fingerprint=None)
```
Retrieves the status and metadata of an API key.
Parameters:
| Name | Type | Description | Default |
| `api_key_fingerprint` | `Optional[str]` | The fingerprint of the API key to query. If not provided, the fingerprint of the current API key will be used. | `None` |
Returns:
| Name | Type | Description |
| `APIKeyStatus` | `Optional[APIKeyStatus]` | An object containing the API key's status information, or None if the query fails. |
Raises:
| Type | Description |
| `Exception` | If any error occurs during API key status retrieval. |
### api_key_revoke
```
api_key_revoke(api_key_fingerprint)
```
Revokes an API key by its fingerprint.
Parameters:
| Name | Type | Description | Default |
| `api_key_fingerprint` | `str` | The fingerprint of the API key to revoke. | *required* |
Returns:
| Type | Description |
| `None` | None. |
Raises:
| Type | Description |
| `Exception` | If any error occurs during API key revocation. |
### close
```
close()
```
Gracefully shuts down the Mosaico client and releases all underlying resources.
This method ensures a clean termination of the client's lifecycle by:
- **Closing Handlers:** Invalidates and closes all cached `SequenceHandlers` and `TopicHandlers` to prevent stale data access.
- **Network Cleanup:** Closes the connection to the `mosaicod` backend.
## mosaicolabs.comm.GRPCCompression`dataclass`
```
GRPCCompression(algorithm, level=None)
```
Represents the gRPC compression configuration.
Parameters:
| Name | Type | Description | Default |
| `algorithm` | `GRPCCompressionAlgorithm` | The compression algorithm to use | *required* |
| `level` | `Optional[GRPCCompressionLevel]` | The compression level to use | `None` |
### algorithm`instance-attribute`
```
algorithm
```
The compression algorithm to use
### level`class-attribute``instance-attribute`
```
level = None
```
The compression level to use
## mosaicolabs.comm.NotificationType
Bases: `Enum`
Classification of platform-level notifications.
These identifiers distinguish the severity and intent of messages sent from the Mosaico server regarding resource states or operation failures.
Attributes:
| Name | Type | Description |
| `ERROR` | | Indicates a critical failure during resource operations, such as a writing interruption or serialization fault. |
### Error`class-attribute``instance-attribute`
```
Error = 'error'
```
Critical error notification.
## mosaicolabs.comm.Notification`dataclass`
```
Notification(
sequence_name,
type,
message,
created_datetime,
topic_name=None,
)
```
Platform diagnostic notification.
A `Notification` object represents a specific event or error report stored on the platform server. These are typically generated by ingestion tasks and are critical for debugging failures when using `SessionLevelErrorPolicy.Report`.
##### Discovery
Notifications can be retrieved at both the sequence and topic level via the Mosaico client:
- `MosaicoClient.list_sequence_notifications()`
- `MosaicoClient.list_topic_notifications()`
Attributes:
| Name | Type | Description |
| `sequence_name` | `str` | The unique identifier of the associated sequence. |
| `type` | `NotificationType` | The `NotificationType` categorization of this event. |
| `message` | `str` | A detailed string describing the event or error cause. |
| `created_datetime` | `datetime` | The timestamp when the server generated the notification. |
| `topic_name` | `Optional[str]` | Optional; the specific topic name if the notification is granular to a single data channel. |
## mosaicolabs.comm.middlewares
### MosaicoAuthMiddleware
```
MosaicoAuthMiddleware(api_key)
```
Bases: `ClientMiddleware`
Middleware adding the API token to every flight request.
Initialize the middleware
Parameters:
| Name | Type | Description | Default |
| `api_key` | `str` | The API key to use for authentication | *required* |
#### sending_headers
```
sending_headers()
```
Called before sending headers to the server
Returns:
| Name | Type | Description |
| `dict` | `Dict[str, List[str] | List[bytes]]` | Headers to be sent to the server |
#### received_headers
```
received_headers(headers)
```
Called after receiving headers from the server
Parameters:
| Name | Type | Description | Default |
| `headers` | `Dict[str, List[str] | List[bytes]]` | Headers received from the server | *required* |
### MosaicoAuthMiddlewareFactory
```
MosaicoAuthMiddlewareFactory(api_key)
```
Bases: `ClientMiddlewareFactory`
Factory to create istances of MosaicoAuthMiddleware.
Initialize the factory
Parameters:
| Name | Type | Description | Default |
| `api_key` | `str` | The API key to use for authentication | *required* |
#### api_key_fingerprint`property`
```
api_key_fingerprint
```
The fingerprint of the API key
Returns:
| Name | Type | Description |
| `str` | `str` | The fingerprint of the API key |
#### start_call
```
start_call(info)
```
Called at every flight client operation (GetFlightInfo, DoAction, ecc.)
Parameters:
| Name | Type | Description | Default |
| `info` | `CallInfo` | Information about the flight call | *required* |
Returns:
| Name | Type | Description |
| `MosaicoAuthMiddleware` | `MosaicoAuthMiddleware` | The middleware to be used for the flight call |
---
# Enum Module
## mosaicolabs.enum.SerializationFormat
Bases: `Enum`
Defines the structural format used when serializing ontology data for storage or transmission.
The format dictates how the data is organized (e.g., fixed-schema tables vs. variable-length structures) and may imply specific handling during the serialization and deserialization process.
### Default`class-attribute``instance-attribute`
```
Default = 'default'
```
Represents data that conforms to a strict, fixed-width tabular format (like a standard DataFrame or a PyArrow Table of records). Suitable for simple sensors with a constant number of fields and fixed-size data.
### Ragged`class-attribute``instance-attribute`
```
Ragged = 'ragged'
```
Represents data containing variable-length lists or sequences (e.g., point clouds, lists of detections, or non-uniform arrays). This format is typically serialized using specialized PyArrow features to handle the non-uniform structure efficiently.
### Image`class-attribute``instance-attribute`
```
Image = 'image'
```
Represents raw or compressed image data. This format signals that the data consists primarily of a binary blob (the image content) along with associated metadata (width, height, format), often requiring specialized compression/decompression handling.
## mosaicolabs.enum.SessionStatus
Bases: `Enum`
Represents the operational lifecycle state of a Session upload for a Sequence during the ingestion process (see also `SequenceWriter`).
This enumeration tracks the state of a session from its initial creation through data writing until it reaches a terminal state (Finalized or Error).
### Null`class-attribute``instance-attribute`
```
Null = 'null'
```
The initial state of a writer before server-side registration.
In this state, the local `SequenceWriter` instance has been created but the `SESSION_CREATE` handshake has not yet been performed or completed.
### Pending`class-attribute``instance-attribute`
```
Pending = 'pending'
```
The session is registered on the server and actively accepting data.
This state is entered upon successful execution of the `__enter__` method of the `SequenceWriter` class. While pending, the session allows for the creation of new topics and the ingestion of data batches.
### Finalized`class-attribute``instance-attribute`
```
Finalized = 'finalized'
```
The session has been successfully closed and its data is now immutable.
This terminal state indicates that the `SequenceWriter._finalize()` action was acknowledged by the server. Once finalized, the session is typically **locked** and cannot be deleted unless explicitly unlocked by an administrator.
### Error`class-attribute``instance-attribute`
```
Error = 'error'
```
The ingestion process failed or was explicitly aborted.
This state is reached if an exception occurs within the `with` block or during the finalization phase. Depending on the `SessionLevelErrorPolicy`, the data may have been purged (`Delete`) or retained in an **unlocked** state for debugging (`Report`).
## mosaicolabs.enum.SequenceStatus`module-attribute`
```
SequenceStatus = SessionStatus
```
Represents the operational lifecycle state of a Sequence during the ingestion process
Alias for `SessionStatus`.
## mosaicolabs.enum.TopicWriterStatus
Bases: `Enum`
Represents the operational lifecycle state of a Topic upload for a specific Session during the ingestion process (see also `TopicWriter`).
This enumeration tracks the state of a topic writer from its initial creation through data writing until it reaches a terminal state.
### Active`class-attribute``instance-attribute`
```
Active = 'active'
```
The initial state of a topic writer before server-side registration.
In this state, the local `TopicWriter` instance has been created and the `TOPIC_CREATE` handshake has completed.
### Finalized`class-attribute``instance-attribute`
```
Finalized = 'finalized'
```
The topic writer has been successfully closed and its data is now immutable.
This terminal state indicates that the `TopicWriter._finalize()` action was acknowledged by the server. Once finalized, the topic writer is **locked** and cannot be used to push records.
### FinalizedWithError`class-attribute``instance-attribute`
```
FinalizedWithError = 'finalized_with_error'
```
The topic writer has been finalized with an error.
This state is reached when the TopicWriter is used in a context and its error policy is set to `TopicLevelErrorPolicy.Finalize`.
This terminal state indicates that the `TopicWriter._finalize()` function was called with an error. Once finalized, the topic writer is **locked** and cannot be used to push records.
### IgnoredLastError`class-attribute``instance-attribute`
```
IgnoredLastError = 'ignored_last_error'
```
The topic writer is still active and can be used to push data on the platform.
This state is reached when the TopicWriter is used in a context and its error policy is set to `TopicLevelErrorPolicy.Ignore`.
This temporary state indicates that the last time the `with` context exited, it was due to an error.
### RaisedException`class-attribute``instance-attribute`
```
RaisedException = 'raised_exception'
```
The topic writer encountered an error in its `with` block. The error handling is delegated to the outer `SequenceWriter` error handling policy (`SessionLevelErrorPolicy`) , or any try-except outer block.
This state is reached when the TopicWriter is used in a context and its error policy is set to `TopicLevelErrorPolicy.Raise`.
## mosaicolabs.enum.APIKeyPermissionEnum
Bases: `Enum`
### Read`class-attribute``instance-attribute`
```
Read = 'read'
```
Read-Only access to resources
This permission allows to: - List resources - Retrieve Sequences, Topics and the related Data streams - Query the data catalogs via the `MosaicoClient.query()` method
### Write`class-attribute``instance-attribute`
```
Write = 'write'
```
Write access to resources
This permission allows to: - List resources - Retrieve Sequences, Topics and the related Data streams - Query the data catalogs via the `MosaicoClient.query()` method - Create and update Sequences
### Delete`class-attribute``instance-attribute`
```
Delete = 'delete'
```
Delete access to resources
This permission allows to: - List resources - Retrieve Sequences, Topics and the related Data streams - Query the data catalogs via the `MosaicoClient.query()` method - Create and update Sequences - Delete Sequences, Sessions and Topics
### Manage`class-attribute``instance-attribute`
```
Manage = 'manage'
```
Full access to resources
This permission allows to: - List resources - Retrieve Sequences, Topics and the related Data streams - Query the data catalogs via the `MosaicoClient.query()` method - Create and update Sequences - Delete Sequences, Sessions and Topics - Manage API keys (create, retrieve the status, revoke)
## mosaicolabs.enum.SessionLevelErrorPolicy
Bases: `Enum`
Defines the behavior of the `SequenceWriter` or the `SequenceUpdater` when an exception occurs during ingestion.
This policy determines how the platform handles partially uploaded data if the ingestion process is interrupted or fails.
### Report`class-attribute``instance-attribute`
```
Report = 'report'
```
Notify the server of the error but retain partial data.
The system will attempt to finalize the session and notify the server of the specific failure, allowing existing data chunks to remain accessible for inspection.
### Delete`class-attribute``instance-attribute`
```
Delete = 'delete'
```
Abort the sequence and instruct the server to discard all data.
This is the default "all-or-nothing" strategy. If a failure occurs, the `SequenceWriter` or the `SequenceUpdater` will send an abort command to ensure the server purges all traces of the failed ingestion, preventing inconsistent or incomplete sequences from appearing in the catalog.
## mosaicolabs.enum.TopicLevelErrorPolicy
Bases: `Enum`
Defines the behavior of the `TopicWriter` when an exception occurs during ingestion.
This policy determines how the platform handles partially uploaded data if the ingestion process is interrupted or fails.
### Finalize`class-attribute``instance-attribute`
```
Finalize = 'finalize'
```
Notify server and close the topic (`is_active = False`).
### Ignore`class-attribute``instance-attribute`
```
Ignore = 'ignore'
```
Notify server but keep topic open for future `push()` calls.
### Raise`class-attribute``instance-attribute`
```
Raise = 'raise'
```
Propagate exception to trigger session-level policy.
## mosaicolabs.enum.TopicLevelErrorPolicy
Bases: `Enum`
Defines the behavior of the `TopicWriter` when an exception occurs during ingestion.
This policy determines how the platform handles partially uploaded data if the ingestion process is interrupted or fails.
### Finalize`class-attribute``instance-attribute`
```
Finalize = 'finalize'
```
Notify server and close the topic (`is_active = False`).
### Ignore`class-attribute``instance-attribute`
```
Ignore = 'ignore'
```
Notify server but keep topic open for future `push()` calls.
### Raise`class-attribute``instance-attribute`
```
Raise = 'raise'
```
Propagate exception to trigger session-level policy.
## mosaicolabs.enum.SessionLevelErrorPolicy
Bases: `Enum`
Defines the behavior of the `SequenceWriter` or the `SequenceUpdater` when an exception occurs during ingestion.
This policy determines how the platform handles partially uploaded data if the ingestion process is interrupted or fails.
### Report`class-attribute``instance-attribute`
```
Report = 'report'
```
Notify the server of the error but retain partial data.
The system will attempt to finalize the session and notify the server of the specific failure, allowing existing data chunks to remain accessible for inspection.
### Delete`class-attribute``instance-attribute`
```
Delete = 'delete'
```
Abort the sequence and instruct the server to discard all data.
This is the default "all-or-nothing" strategy. If a failure occurs, the `SequenceWriter` or the `SequenceUpdater` will send an abort command to ensure the server purges all traces of the failed ingestion, preventing inconsistent or incomplete sequences from appearing in the catalog.
## mosaicolabs.enum.FlightAction
Bases: `Enum`
Internal enumeration of PyArrow Flight action identifiers.
This enum serves as the single source of truth for all action names used in the handshakes between the SDK and the Mosaico server.
### SEQUENCE_CREATE`class-attribute``instance-attribute`
```
SEQUENCE_CREATE = 'sequence_create'
```
Initiates the registration of a new sequence on the server.
### SESSION_CREATE`class-attribute``instance-attribute`
```
SESSION_CREATE = 'session_create'
```
Initiates the registration of a new session for an existing sequence on the server.
### SESSION_FINALIZE`class-attribute``instance-attribute`
```
SESSION_FINALIZE = 'session_finalize'
```
Marks a session as complete and makes its data immutable.
### SEQUENCE_NOTIFICATION_CREATE`class-attribute``instance-attribute`
```
SEQUENCE_NOTIFICATION_CREATE = (
"sequence_notification_create"
)
```
Sends notifications or error reports during the sequence creation phase.
### SEQUENCE_NOTIFICATION_LIST`class-attribute``instance-attribute`
```
SEQUENCE_NOTIFICATION_LIST = 'sequence_notification_list'
```
Request the list of notifications for a specific sequence
### SEQUENCE_NOTIFICATION_PURGE`class-attribute``instance-attribute`
```
SEQUENCE_NOTIFICATION_PURGE = 'sequence_notification_purge'
```
Request the deletion of the list of notifications for a specific sequence
### SESSION_DELETE`class-attribute``instance-attribute`
```
SESSION_DELETE = 'session_delete'
```
Requests the permanent removal of a session and all associated topics from the server.
### SEQUENCE_DELETE`class-attribute``instance-attribute`
```
SEQUENCE_DELETE = 'sequence_delete'
```
Requests the permanent removal of a sequence and all associated topics from the server.
### TOPIC_CREATE`class-attribute``instance-attribute`
```
TOPIC_CREATE = 'topic_create'
```
Registers a new topic within an existing sequence context.
### TOPIC_NOTIFICATION_CREATE`class-attribute``instance-attribute`
```
TOPIC_NOTIFICATION_CREATE = 'topic_notification_create'
```
Reports errors or status updates specific to an individual topic stream.
### TOPIC_NOTIFICATION_LIST`class-attribute``instance-attribute`
```
TOPIC_NOTIFICATION_LIST = 'topic_notification_list'
```
Request the list of notifications for a specific topic in a sequence
### TOPIC_NOTIFICATION_PURGE`class-attribute``instance-attribute`
```
TOPIC_NOTIFICATION_PURGE = 'topic_notification_purge'
```
Request the deletion of the list of notifications for a topic in a sequence
### TOPIC_DELETE`class-attribute``instance-attribute`
```
TOPIC_DELETE = 'topic_delete'
```
Requests the permanent removal of a specific topic from the platform.
### QUERY`class-attribute``instance-attribute`
```
QUERY = 'query'
```
Commands a multi-layer search query against the platform.
### API_KEY_CREATE`class-attribute``instance-attribute`
```
API_KEY_CREATE = 'api_key_create'
```
Creates a new API key.
### API_KEY_REVOKE`class-attribute``instance-attribute`
```
API_KEY_REVOKE = 'api_key_revoke'
```
Revokes an existing API key.
### API_KEY_STATUS`class-attribute``instance-attribute`
```
API_KEY_STATUS = 'api_key_status'
```
Checks the status of a specific API key.
### VERSION`class-attribute``instance-attribute`
```
VERSION = 'version'
```
Requests the backend version
## mosaicolabs.enum.GRPCCompressionAlgorithm
Bases: `IntEnum`
Defines the compression algorithm to be used for gRPC communication.
It is used to configure the compression algorithm for the connection when using the `GRPCCompression` dataclass, or as a shorthand when using the `MosaicoClient.connect()` method.
### Null`class-attribute``instance-attribute`
```
Null = 0
```
No compression
### Gzip`class-attribute``instance-attribute`
```
Gzip = 2
```
Uses GZIP compression
### StreamGzip`class-attribute``instance-attribute`
```
StreamGzip = 3
```
Experimental stream-level GZIP
## mosaicolabs.enum.GRPCCompressionLevel
Bases: `IntEnum`
Enumeration representing the gRPC compression level.
### Low`class-attribute``instance-attribute`
```
Low = 1
```
Low compression level
### Medium`class-attribute``instance-attribute`
```
Medium = 2
```
Medium compression level
### High`class-attribute``instance-attribute`
```
High = 3
```
High compression level
---
# Logging Module
## mosaicolabs.logging_config.setup_sdk_logging
```
setup_sdk_logging(
level="INFO",
pretty=False,
console=None,
propagate=False,
)
```
Configures the global logging strategy for the Mosaico SDK.
This function initializes the 'mosaicolabs' logger namespace and provides two distinct output modes: a high-fidelity 'pretty' mode using the Rich library, and a standard stream mode for basic environments. It ensures that existing handlers are cleared to prevent duplicate log entries during re-initialization.
Parameters:
| Name | Type | Description | Default |
| `level` | `str` | The logging threshold (e.g., "DEBUG", "INFO", "WARNING"). Defaults to "INFO". | `'INFO'` |
| `pretty` | `bool` | If True and the 'rich' package is installed, enables enhanced terminal output with colors, timestamps, and formatted tracebacks. | `False` |
| `console` | `Optional[Console]` | An optional Rich Console instance. If provided, the logger and any active UI (like progress bars) will synchronize to prevent screen flickering. Defaults to a new Console(stderr=True). | `None` |
---
# Types Module
# Types Module
## mosaicolabs.types.Time
Bases: `BaseModel`
A high-precision time representation.
The `Time` class splits a timestamp into a 64-bit integer for seconds and a 32-bit unsigned integer for nanoseconds.
Attributes:
| Name | Type | Description |
| `seconds` | `int` | Seconds since the epoch (Unix time). |
| `nanoseconds` | `int` | Nanoseconds component within the current second, ranging from 0 to 999,999,999. |
### seconds`instance-attribute`
```
seconds
```
Seconds since the epoch (Unix time).
### nanoseconds`instance-attribute`
```
nanoseconds
```
Nanoseconds component within the current second, ranging from 0 to 999,999,999.
### validate_nanosec`classmethod`
```
validate_nanosec(v)
```
Ensures nanoseconds are within the valid [0, 1e9) range.
### from_float`classmethod`
```
from_float(ftime)
```
Factory method to create a Time object from a float (seconds since epoch).
This method carefully handles floating-point artifacts by using rounding for the fractional part to ensure stable nanosecond conversion.
Parameters:
| Name | Type | Description | Default |
| `ftime` | `float` | Total seconds since epoch (e.g., from `time.time()`). | *required* |
Returns:
| Type | Description |
| `Time` | A normalized `Time` instance. |
### from_milliseconds`classmethod`
```
from_milliseconds(total_milliseconds)
```
Factory method to create a Time object from a total count of milliseconds.
Parameters:
| Name | Type | Description | Default |
| `total_milliseconds` | `int` | Total time elapsed in milliseconds. | *required* |
Returns:
| Type | Description |
| `Time` | A `Time` instance with split sec/nanosec components. |
### from_nanoseconds`classmethod`
```
from_nanoseconds(total_nanoseconds)
```
Factory method to create a Time object from a total count of nanoseconds.
Parameters:
| Name | Type | Description | Default |
| `total_nanoseconds` | `int` | Total time elapsed in nanoseconds. | *required* |
Returns:
| Type | Description |
| `Time` | A `Time` instance with split sec/nanosec components. |
### from_datetime`classmethod`
```
from_datetime(dt)
```
Factory method to create a Time object from a Python `datetime` instance.
Parameters:
| Name | Type | Description | Default |
| `dt` | `datetime` | A standard Python `datetime` object. | *required* |
Returns:
| Type | Description |
| `Time` | A `Time` instance reflecting the datetime's timestamp. |
### now`classmethod`
```
now()
```
Factory method that returns the current system UTC time in high precision.
### to_float
```
to_float()
```
Converts the high-precision time to a float.
### to_nanoseconds
```
to_nanoseconds()
```
Converts the time to a total integer of nanoseconds.
This conversion preserves full precision.
### to_milliseconds
```
to_milliseconds()
```
Converts the time to a total integer of milliseconds.
This conversion preserves full precision.
### to_datetime
```
to_datetime()
```
Converts the time to a Python UTC `datetime` object.
---
# Machine Learning Module
## mosaicolabs.ml.DataFrameExtractor
```
DataFrameExtractor(
sequence_handler, timestamp_column_name=None
)
```
Extracts and manages data from Mosaico Sequences, converting them into tabular DataFrames.
This class serves as a high-performance bridge for training ML models or performing data analysis. It extracts data from multiple sequence topics and unifies them into a single, flattened, sparse DataFrame aligned by timestamps.
Key Features:
- **Memory Efficiency**: Uses a windowed approach to process multi-gigabyte sequences in chunks without overloading RAM.
- **Flattening**: Automatically flattens nested structures (e.g., `pose.position.x`) into dot-notation columns.
- **Sparse Alignment**: Merges multiple topics with different frequencies into a single timeline (using `NaN` for missing values at specific timestamps).
Initializes the DataFrameExtractor.
Parameters:
| Name | Type | Description | Default |
| `sequence_handler` | `SequenceHandler` | An active handle to a Mosaico sequence. | *required* |
| `timestamp_column_name` | `str` | Name of the timestamp column. Defaults to `None`, in which case "timestamp_ns" will be used. | `None` |
### to_pandas_chunks
```
to_pandas_chunks(
topics=None,
window_sec=5.0,
timestamp_ns_start=None,
timestamp_ns_end=None,
)
```
Generator that yields time-windowed pandas DataFrames from the sequence.
This method leverages server-side filtering and local batch processing to maintain a low memory footprint. It handles batches that cross window boundaries by carrying over the remainder to the next chunk.
Parameters:
| Name | Type | Description | Default |
| `topics` | `List[str]` | Topics to extract. Defaults to all topics. | `None` |
| `window_sec` | `float` | Duration of each DataFrame chunk in seconds. | `5.0` |
| `timestamp_ns_start` | `int` | Global start time for extraction. | `None` |
| `timestamp_ns_end` | `int` | Global end time for extraction. | `None` |
Yields:
| Type | Description |
| `DataFrame` | pd.DataFrame: A sparse, flattened DataFrame containing data from all selected topics and their fields within the current time window. |
## mosaicolabs.ml.SyncTransformer
```
SyncTransformer(
target_fps,
policy=SyncHold(),
timestamp_column="timestamp_ns",
)
```
Bases: `BaseEstimator`, `TransformerMixin`
Stateful resampler for Mosaico DataFrames.
This class aligns heterogeneous sensor streams onto a uniform time grid. It is designed to consume the windowed outputs of the `DataFrameExtractor` sequentially, maintaining internal state to ensure signal continuity across batch boundaries.
##### Scikit-Learn Compatibility
The class implements the standard `fit`/`transform` interface, making it fully compliant with Scikit-learn `Pipeline` and `FeatureUnion` objects.
- **fit(X)**: Captures the initial timestamp from the first chunk to align the grid.
- **transform(X)**: Executes the temporal resampling logic for a single DataFrame chunk and returns a dense DataFrame.
- **fit_transform(X)**: Fits the transformer to the data and then transforms it.
Key Features:
- Fixed Frequency: Normalizes multi-rate sensors to a target FPS.
- Stateful Persistence: Carries the last known sensor state into the next chunk.
- Semantic Integrity: Correctly handles 'Late Arrivals' by yielding None for ticks preceding the first physical measurement.
Parameters:
| Name | Type | Description | Default |
| `target_fps` | `float` | The desired output frequency in Hz. | *required* |
| `policy` | `SyncPolicy` | A strategy implementing the `SyncPolicy` protocol. | `SyncHold()` |
| `timestamp_column` | `str` | The column name containing the timestamp data. | `'timestamp_ns'` |
### fit_transform
```
fit_transform(X, y=None, **fit_params)
```
Fits the transformer to the data and then transforms it.
### fit
```
fit(X, y=None)
```
Initializes the grid alignment based on the first observed timestamp.
### transform
```
transform(X)
```
Syncronizes a sparse DataFrame chunk into a dense, uniform DataFrame.
### reset
```
reset()
```
Resets the internal temporal state and cached sensor values.
## mosaicolabs.ml.SyncPolicy
Bases: `Protocol`
Protocol defining the interface for data synchronization policies.
A `SyncPolicy` determines how sparse data samples are mapped onto a standard, dense time grid. Classes implementing this protocol are used by `SyncTransformer` to resample sensor data (e.g., holding the last value, interpolating, or dropping old data).
Common implementations include:
- `SyncHold`: Zero-order hold (carries the last value forward).
- `SyncAsOf`: Tolerance-based hold (carries value forward only for a specific duration).
- `SyncDrop`: Strict interval matching (drops data outside the current grid step).
### apply
```
apply(grid, s_ts, s_val)
```
Applies the synchronization logic to sparse samples, mapping them to the target grid.
Parameters:
| Name | Type | Description | Default |
| `grid` | `ndarray` | The target dense timeline (nanosecond timestamps). | *required* |
| `s_ts` | `ndarray` | The source acquisition timestamps (sparse data). | *required* |
| `s_val` | `ndarray` | The source sensor values corresponding to `s_ts`. | *required* |
Returns:
| Type | Description |
| `ndarray` | np.ndarray: An object-array of the same length as `grid`, containing the synchronized values. Slots with no valid data are filled with `None`. |
## mosaicolabs.ml.SyncHold
Classic Last-Value-Hold (Zero-Order Hold) synchronization.
This policy carries the most recent valid sample forward to all future grid ticks until a new sample is received. It effectively creates a "step" function from the sparse samples.
### apply
```
apply(grid, s_ts, s_val)
```
Applies the Zero-Order Hold logic.
Parameters:
| Name | Type | Description | Default |
| `grid` | `ndarray` | The target dense timeline (nanosecond timestamps). | *required* |
| `s_ts` | `ndarray` | The source acquisition timestamps. | *required* |
| `s_val` | `ndarray` | The source sensor values. | *required* |
Returns:
| Type | Description |
| `ndarray` | np.ndarray: Densely populated array where each point holds the last known value. |
## mosaicolabs.ml.SyncAsOf
```
SyncAsOf(tolerance_ns)
```
Tolerance-based 'As-Of' synchronization.
Similar to `SyncHold`, but limits how far a value can be carried forward. If the time difference between the grid tick and the last sample exceeds `tolerance_ns`, the value is considered stale and the slot is left as `None`.
Parameters:
| Name | Type | Description | Default |
| `tolerance_ns` | `int` | Maximum allowed age (in nanoseconds) for a sample to be valid. | *required* |
### apply
```
apply(grid, s_ts, s_val)
```
Applies the As-Of synchronization logic with tolerance check.
Parameters:
| Name | Type | Description | Default |
| `grid` | `ndarray` | The target dense timeline. | *required* |
| `s_ts` | `ndarray` | The source acquisition timestamps. | *required* |
| `s_val` | `ndarray` | The source sensor values. | *required* |
Returns:
| Type | Description |
| `ndarray` | np.ndarray: Densely populated array, with `None` where data is missing or stale. |
## mosaicolabs.ml.SyncDrop
```
SyncDrop(step_ns)
```
Strict Interval-based 'Drop' synchronization.
Only yields a value if a sample was acquired strictly within the current grid interval `(t_grid - step_ns, t_grid]`. If no sample falls in this window, the result is `None`. This is useful for event-based matching.
Parameters:
| Name | Type | Description | Default |
| `step_ns` | `int` | The duration of the backward-looking window in nanoseconds. | *required* |
### apply
```
apply(grid, s_ts, s_val)
```
Applies the Drop synchronization logic.
Parameters:
| Name | Type | Description | Default |
| `grid` | `ndarray` | The target dense timeline. | *required* |
| `s_ts` | `ndarray` | The source acquisition timestamps. | *required* |
| `s_val` | `ndarray` | The source sensor values. | *required* |
Returns:
| Type | Description |
| `ndarray` | np.ndarray: Array containing values only for populated intervals, otherwise `None`. |
## mosaicolabs.ml.VideoDecodingTransformer
```
VideoDecodingTransformer(
topics,
stateless_codec=_StatelessDefaultCodec(),
stateful_decoding_session_type=StatefulDecodingSession,
)
```
Bases: `BaseEstimator`, `TransformerMixin`
A Scikit-Learn compatible stateful transformer that reconstructs CompressedImage byte streams into usable PIL Images chronologically before temporal synchronization.
This transformer bridges the gap between video compression mechanics (which rely on inter-frame dependencies like I/P/B frames) and machine learning batching strategies. It maintains a persistent decoding session across data chunks, ensuring that delta-frames are correctly decoded using the proper reference frames before any temporal synchronization or randomization occurs downstream.
Attributes:
| Name | Type | Description |
| `topics` | `List[str]` | A list of Mosaico topic names (e.g., "/front/camera/image") that contain the compressed image data to be decoded. |
| `_stateless_codec` | | The codec used for stateless formats like JPEG or PNG. |
| `_stateful_decoding_session_type` | | The class/factory used to instantiate the stateful session for formats like H.264 or HEVC. |
| `_session` | | The active decoding session instance. |
Initializes the VideoDecodingTransformer.
Parameters:
| Name | Type | Description | Default |
| `topics` | `List[str]` | The list of topics to target for image decoding. | *required* |
| `stateless_codec` | `optional` | An instance of a codec to handle formats that do not require state (e.g., JPEG). Defaults to _StatelessDefaultCodec(). | `_StatelessDefaultCodec()` |
| `stateful_decoding_session_type` | `optional` | The class to instantiate for state-dependent video decoding. Defaults to StatefulDecodingSession. | `StatefulDecodingSession` |
### fit_transform
```
fit_transform(X, y=None, **fit_params)
```
Fits the transformer to the data and then transforms it.
### fit
```
fit(X, y=None)
```
Initializes the persistent decoding session.
This method should be called before transforming the first chunk of data. It establishes the stateful session required to track reference frames across subsequent `transform` calls.
Parameters:
| Name | Type | Description | Default |
| `X` | `DataFrame` | The input DataFrame chunk (unused in this method but required by the Scikit-Learn API). | *required* |
| `y` | `optional` | Target values (unused). | `None` |
Returns:
| Name | Type | Description |
| `self` | `VideoDecodingTransformer` | Returns the transformer instance. |
### transform
```
transform(X)
```
Decodes the compressed image data within the DataFrame chronologically.
For each requested topic, this method extracts the raw bytes and image format. Stateful formats (H.264, HEVC) are routed through the persistent decoding session, using the topic name as the context to isolate decoder states per camera. Stateless formats (JPEG) are routed to the stateless codec.
The resulting `PIL.Image` objects are inserted into a new column named `{topic}.compressed_image.decoded`, and the original raw byte/format columns are dropped to conserve memory.
Parameters:
| Name | Type | Description | Default |
| `X` | `DataFrame` | A chronologically ordered sparse chunk from the `DataFrameExtractor`, with a new column named `{topic}.compressed_image.decoded`. | *required* |
Returns:
| Type | Description |
| `DataFrame` | pd.DataFrame: A new DataFrame containing the fully reconstructed `PIL.Image` objects in place of the raw byte streams. |
### reset
```
reset()
```
Releases the C-level decoder resources and resets the session state.
This should be called when processing is complete or if the sequence is restarted, to prevent memory leaks and ensure a clean state for the next run.
---
# ROS Custom Ontology
The following data models are specific to the ROS bridge and are not part of the official Mosaico Data Ontology yet.
## mosaicolabs.ros_bridge.data_ontology.BatteryState
Bases: `Serializable`
Represents the state of a battery power supply.
modeled after: sensor_msgs/msg/BatteryState
### voltage`class-attribute``instance-attribute`
```
voltage = MosaicoField(
description="The battery voltage in V."
)
```
The battery voltage value
### temperature`class-attribute``instance-attribute`
```
temperature = MosaicoField(
default=None,
description="The battery temperature in °C",
)
```
The optional battery temperature in °C
### current`class-attribute``instance-attribute`
```
current = MosaicoField(
default=None,
description="Optional battery charge in A.",
)
```
The optional battery current in A
### charge`class-attribute``instance-attribute`
```
charge = MosaicoField(
default=None,
description="Optional battery charge in Ah.",
)
```
The optional battery charge in Ah
### capacity`class-attribute``instance-attribute`
```
capacity = MosaicoField(
default=None,
description="Optional batterty capacity in Ah.",
)
```
The optional battery capacity in Ah
### design_capacity`class-attribute``instance-attribute`
```
design_capacity = MosaicoField(
default=None,
description="Optional battery design capacity in Ah.",
)
```
The optional battery design capacity in Ah
### percentage`class-attribute``instance-attribute`
```
percentage = MosaicoField(
description="Battery percentage in %."
)
```
The battery percentage in %
### power_supply_status`class-attribute``instance-attribute`
```
power_supply_status = MosaicoField(
description="The charging status."
)
```
The charging status
### power_supply_health`class-attribute``instance-attribute`
```
power_supply_health = MosaicoField(
description="The battery health."
)
```
The battery health
### power_supply_technology`class-attribute``instance-attribute`
```
power_supply_technology = MosaicoField(
description="The battery technology."
)
```
The battery technology
### present`class-attribute``instance-attribute`
```
present = MosaicoField(description='Battery presence.')
```
The battery presence
### location`class-attribute``instance-attribute`
```
location = MosaicoField(
description="Battery location (like the slot)."
)
```
The battery location (like the slot)
### serial_number`class-attribute``instance-attribute`
```
serial_number = MosaicoField(
description="Battery serial number."
)
```
The battery serial number
### cell_voltage`class-attribute``instance-attribute`
```
cell_voltage = MosaicoField(
default=None, description="Battery cells voltage."
)
```
The battery cells voltage
### cell_temperature`class-attribute``instance-attribute`
```
cell_temperature = MosaicoField(
default=None, description="Battery cells temperature."
)
```
The battery cells temperature
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.ros_bridge.data_ontology.FrameTransform
Bases: `Serializable`
Represents a list of transformations between two coordinates.
modeled after: tf2_msgs/msg/TFMessage
### transforms`class-attribute``instance-attribute`
```
transforms = MosaicoField(
description="List of coordinate frames transformations."
)
```
List of coordinate frames transformations.
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.ros_bridge.data_ontology.PointCloud2
Bases: `Serializable`
Represents a point cloud in ROS2.
modeled after: sensor_msgs/msg/PointCloud2
### height`class-attribute``instance-attribute`
```
height = MosaicoField(
description="The height of the point cloud."
)
```
The height of the point cloud.
### width`class-attribute``instance-attribute`
```
width = MosaicoField(
description="The width of the point cloud."
)
```
The width of the point cloud.
### fields`class-attribute``instance-attribute`
```
fields = MosaicoField(
description="The fields of the point cloud."
)
```
The fields of the point cloud.
### is_bigendian`class-attribute``instance-attribute`
```
is_bigendian = MosaicoField(
description="Whether the data is big-endian."
)
```
Whether the data is big-endian.
### point_step`class-attribute``instance-attribute`
```
point_step = MosaicoField(
description="Length of a point in bytes."
)
```
Length of a point in bytes.
### row_step`class-attribute``instance-attribute`
```
row_step = MosaicoField(
description="Length of a row in bytes."
)
```
Length of a row in bytes.
### data`class-attribute``instance-attribute`
```
data = MosaicoField(
description="The point cloud data. Expected size: row_step * height bytes."
)
```
The point cloud data. Expected size: row_step * height bytes.
### is_dense`class-attribute``instance-attribute`
```
is_dense = MosaicoField(
description="True if there are no invalid points."
)
```
True if there are no invalid points.
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.ros_bridge.data_ontology.PointField
Bases: `Serializable`
Represents a point field in a point cloud in ROS2.
modeled after: sensor_msgs/msg/PointField
### name`class-attribute``instance-attribute`
```
name = MosaicoField(description='Name of the field.')
```
The name of the point field.
### offset`class-attribute``instance-attribute`
```
offset = MosaicoField(
description="Staring position of the field."
)
```
The Offset from start of point struct.
### datatype`class-attribute``instance-attribute`
```
datatype = MosaicoField(
description="Datatype of the field."
)
```
The data type of the point field, see `PointFieldDatatype`.
### count`class-attribute``instance-attribute`
```
count = MosaicoField(
description="Number of elements in the point field."
)
```
The number of elements in the point field.
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
---
# ROS Bridge
## mosaicolabs.ros_bridge.ROSBridge
Bases: `Generic[T]`
A central registry and API for ROS message to Mosaico Ontology translation.
The `ROSBridge` serves as the orchestration hub for the ROS Bridge system. It maintains a global registry of all available `ROSAdapterBase` implementations and provides the high-level API used to transform raw ROS message containers into strongly-typed Mosaico `Message` objects.
##### Key Responsibilities
- **Adapter Discovery**: Provides methods to lookup adapters based on ROS message type strings (e.g., `sensor_msgs/msg/Imu`).
- **Type Validation**: Checks if a given ROS type or Mosaico Ontology class is currently supported by the bridge.
- **Execution Dispatch**: Acts as the primary entry point for the injection pipeline to delegate translation tasks to specific specialized adapters.
Attributes:
| Name | Type | Description |
| `_adapters` | `Dict[str, Type[ROSAdapterBase]]` | A private class-level dictionary mapping canonical ROS message type strings to their respective adapter classes. |
### get_default_adapter`classmethod`
```
get_default_adapter(ros_msg_type)
```
Retrieves the registered adapter class for a given ROS message type.
Parameters:
| Name | Type | Description | Default |
| `ros_msg_type` | `str` | The full ROS message type string (e.g., "sensor_msgs/msg/Image"). | *required* |
Returns:
| Type | Description |
| `Optional[Type[ROSAdapterBase]]` | The corresponding `ROSAdapterBase` subclass if found, otherwise `None`. |
### is_msgtype_adapted`classmethod`
```
is_msgtype_adapted(ros_msg_type)
```
Checks if a specific ROS message type has a registered translator.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if the type is supported, False otherwise. |
### is_adapted`classmethod`
```
is_adapted(mosaico_cls)
```
Checks if a specific Mosaico Ontology class has a registered adapter.
Parameters:
| Name | Type | Description | Default |
| `mosaico_cls` | `T` | The Mosaico class to check (e.g., `Image`, `Imu`). | *required* |
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if an adapter exists for this class, False otherwise. |
### from_ros_message`classmethod`
```
from_ros_message(ros_msg, **kwargs)
```
The high-level API for translating raw ROS message containers.
This method identifies the appropriate adapter based on the `msg_type` inside the `ROSMessage` and invokes its `translate` method. It is the core function called by the `RosbagInjector` during the ingestion loop.
Parameters:
| Name | Type | Description | Default |
| `ros_msg` | `ROSMessage` | The `ROSMessage` container produced by the `ROSLoader`. | *required* |
| `**kwargs` | `Any` | Arbitrary context arguments passed directly to the adapter's translate method. | `{}` |
Returns:
| Type | Description |
| `Optional[Message]` | A fully constructed Mosaico `Message` if an adapter is available, otherwise `None`. |
## mosaicolabs.ros_bridge.register_default_adapter
```
register_default_adapter(cls)
```
A class decorator for streamlined default adapter registration.
This is the recommended way to register adapters in a production environment, as it couples the adapter definition directly with its registration in the bridge.
Parameters:
| Name | Type | Description | Default |
| `cls` | `Type[ROSAdapterBase]` | The adapter class to register. | *required* |
Returns:
| Type | Description |
| `Type[ROSAdapterBase]` | The same class, unmodified, after successful registration. |
## mosaicolabs.ros_bridge.loader.ROSLoader
```
ROSLoader(
file_path,
topics=None,
typestore_name=EMPTY,
error_policy=LOG_WARN,
custom_types=None,
)
```
Unified loader for reading and deserializing ROS 1 (.bag) and ROS 2 (.mcap, .db3) data.
The `ROSLoader` acts as a resource manager that abstracts the underlying `rosbags` library. It provides a standardized Pythonic interface for filtering topics, managing custom message registries, and streaming data into the Mosaico adaptation pipeline.
##### Key Features
- **Multi-Format Support**: Automatically detects and handles ROS 1 and ROS 2 bag containers.
- **Semantic Filtering**: Supports glob-style patterns (e.g., `/sensors/*`, `*camera_info`) to include relevant data channels, with `!`-prefixed patterns for exclusion (e.g., `!/sensors/debug*`). Patterns are evaluated in ORDER (gitignore-like semantics).
- **Dynamic Schema Resolution**: Integrates with the `ROSTypeRegistry` to resolve proprietary message types on-the-fly.
- **Memory Efficient**: Implements a generator-based iteration pattern to process large bags without loading them into RAM.
Attributes:
| Name | Type | Description |
| `ACCEPTED_EXTENSIONS` | | Set of supported file extensions {'.bag', '.db3', '.mcap'}. |
Initializes the loader and prepares the type registry.
Upon initialization, the loader merges the global definitions from the `ROSTypeRegistry` with any `custom_types` provided specifically for this session.
Parameters:
| Name | Type | Description | Default |
| `file_path` | `Union[str, Path]` | Path to the bag file or directory. | *required* |
| `topics` | `Optional[Union[str, List[str]]]` | A single topic name, a list of names, or glob patterns. Patterns are evaluated in ORDER (gitignore-like semantics). If None, all available topics are loaded. | `None` |
| `typestore_name` | `Stores` | The target ROS distribution for default message schemas. See `rosbags.typesys.Stores`. | `EMPTY` |
| `error_policy` | `LoaderErrorPolicy` | How to handle errors during message iteration. | `LOG_WARN` |
| `custom_types` | `Optional[Dict[str, Union[str, Path]]]` | Local overrides for message definitions (type_name: path/to/msg). | `None` |
### duration`property`
```
duration
```
Returns the duration of the bag file in nanoseconds.
Returns:
| Name | Type | Description |
| `int` | `int` | The duration of the bag file in nanoseconds. |
### topics`property`
```
topics
```
Retrieves the list of canonical topic names that will be processed.
This property returns the result of the "Smart Filtering" process, which resolves any glob patterns (e.g., `/camera/*`) provided during initialization against the actual metadata contained within the bag file.
Returns:
| Type | Description |
| `List[str]` | List[str]: A list of topic names currently matched and scheduled for loading. |
### msg_types`property`
```
msg_types
```
Retrieves the list of ROS message types corresponding to the resolved topics.
Each entry in this list represents the schema name (e.g., `sensor_msgs/msg/Image`) required to correctly deserialize the messages for the topics returned by the `.topics` property.
Returns:
| Type | Description |
| `List[str | None]` | List[str]: A list of ROS message type strings in the same order |
| `List[str | None]` | as the resolved topics. |
### msg_count
```
msg_count(topic=None)
```
Returns the total number of messages to be processed based on active filters.
Parameters:
| Name | Type | Description | Default |
| `topic` | `Optional[str]` | If provided, returns the count for that specific topic. If None, returns the aggregate count for all filtered topics. | `None` |
Returns:
| Type | Description |
| `int` | The total message count. |
### close
```
close()
```
Explicitly closes the bag file and releases system resources.
## mosaicolabs.ros_bridge.loader.LoaderErrorPolicy
Bases: `Enum`
Defines the strategy for handling deserialization failures during bag playback.
In heterogeneous datasets, it is common to encounter corrupted messages or missing type definitions for specific topics. This policy allows the user to balance system robustness against data integrity.
Attributes:
| Name | Type | Description |
| `IGNORE` | | Silently skips any message that fails to deserialize. The pipeline continues uninterrupted without any log output. |
| `LOG_WARN` | | (Default) Logs a warning containing the topic name and error details, then skips the message and continues. |
| `RAISE` | | Immediately halts execution and raises the exception. Best used for critical data ingestion where missing even a single record is unacceptable. |
### IGNORE`class-attribute``instance-attribute`
```
IGNORE = 'ignore'
```
Silently skips any message that fails to deserialize.
### LOG_WARN`class-attribute``instance-attribute`
```
LOG_WARN = 'log_warn'
```
Logs a warning containing the topic name and error details, then skips the message and continues.
### RAISE`class-attribute``instance-attribute`
```
RAISE = 'raise'
```
Immediately halts execution and raises the exception. Best used for critical data ingestion where missing even a single record is unacceptable.
## mosaicolabs.ros_bridge.ROSMessage`dataclass`
```
ROSMessage(bag_timestamp_ns, topic, msg_type, data)
```
The standardized container for a single ROS message record yielded by the loader.
This object serves as the primary "unit of work" within the ROS Bridge pipeline. It encapsulates the raw deserialized payload along with essential storage-level metadata needed for accurate platform ingestion.
##### Life Cycle
- **Produced** by `ROSLoader` during bag iteration.
- **Consumed** by `ROSBridge` to identify the correct adapter.
- **Translated** by a `ROSAdapter` into a Mosaico `Message`.
Attributes:
| Name | Type | Description |
| `bag_timestamp_ns` | `int` | Timestamp (nanoseconds) when the message was recorded to the bag file. This is the "storage time". |
| `topic` | `str` | The specific topic string source (e.g., "/camera/left/image_raw"). |
| `msg_type` | `str` | The canonical ROS type string (e.g., "sensor_msgs/msg/Image"). |
| `data` | `Optional[Dict[str, Any]]` | The message payload converted into a standard nested Python dictionary. |
| `header` | `Optional[ROSHeader]` | An automatically parsed `ROSHeader` if the `data` payload contains a valid header field. |
### bag_timestamp_ns`instance-attribute`
```
bag_timestamp_ns
```
Timestamp (nanoseconds) when the message was written to the rosbag. This corresponds to the rosbag storage time and may differ from the time the data was originally generated.
### topic`instance-attribute`
```
topic
```
The topic string of the message source.
### msg_type`instance-attribute`
```
msg_type
```
The message ros type string.
### data`instance-attribute`
```
data
```
The message payload, converted into a standard nested Python dictionary.
### header`class-attribute``instance-attribute`
```
header = None
```
The message payload header
## mosaicolabs.ros_bridge.ROSInjectionConfig`dataclass`
```
ROSInjectionConfig(
file_path,
sequence_name,
metadata,
host="localhost",
port=6726,
ros_distro=None,
on_error=_DEFAULT_SESSION_ON_ERROR,
topics_on_error=_DEFAULT_TOPIC_ON_ERROR,
custom_msgs=None,
topics=None,
adapter_overrides=None,
log_level="INFO",
mosaico_api_key=None,
tls_cert_path=None,
enable_tls=False,
)
```
The central configuration object for the ROS Bag injection process.
This data class serves as the single source of truth for all injection settings, decoupling the orchestration logic from CLI arguments or configuration files. It encapsulates network parameters, file paths, and advanced filtering logic required to drive a successful ingestion session.
Attributes:
| Name | Type | Description |
| `file_path` | `Path` | Absolute or relative path to the input ROS bag file (.mcap, .db3, or .bag). |
| `sequence_name` | `str` | The name for the new sequence to be created on the Mosaico server. |
| `metadata` | `dict` | User-defined metadata to attach to the sequence (e.g., driver, weather, location). |
| `host` | `str` | Hostname or IP of the Mosaico server. Defaults to "localhost". |
| `port` | `int` | Port of the Mosaico server. Defaults to 6726. |
| `ros_distro` | `Optional[Stores]` | The target ROS distribution for message parsing (e.g., Stores.ROS2_HUMBLE). See `rosbags.typesys.Stores`. |
| `on_error` | `SessionLevelErrorPolicy` | Behavior when an ingestion error occurs (Delete the partial sequence or Report the error). Default: `SessionLevelErrorPolicy.Report` |
| `topics_on_error` | `Union[TopicLevelErrorPolicy, Dict[str, TopicLevelErrorPolicy]]` | Behavior when a topic write fails. Default: `TopicLevelErrorPolicy.Raise` Set to a `TopicLevelErrorPolicy` to apply the same policy to all topics. Set to a `Dict[str, TopicLevelErrorPolicy]` to apply different policies to different (subset of) topics. |
| `custom_msgs` | `Optional[List[Tuple]]` | List of custom .msg definitions to register before loading. |
| `topics` | `Optional[List[str]]` | List of topic patterns used to filter available topics. Supports shell-style glob patterns (e.g., ["/cam/*", "*camera_info"]). Patterns starting with "!" are treated as exclusions (e.g., ["!/cam/debug*"]). Patterns are evaluated in ORDER (gitignore-like semantics). If None, all available topics are loaded. |
| `adapter_overrides` | `Optional[Dict[str, Type[ROSAdapterBase]]]` | Mapping of topics to adapter overrides, allowing the use of specific adapters instead of the default for designated topics. Deafult: None |
| `log_level` | `str` | Logging verbosity level ("DEBUG", "INFO", "WARNING", "ERROR"). |
| `mosaico_api_key` | `Optional[str]` | The API key for authentication on the mosaico server. If provided it must be have at least `APIKeyPermissionEnum.Write` permission. Default: None |
| `tls_cert_path` | `Optional[str]` | Path to the TLS certificate file for secure connection on the mosaico server. Default: None |
### file_path`instance-attribute`
```
file_path
```
The path to the ROS bag file to ingest.
### sequence_name`instance-attribute`
```
sequence_name
```
The name of the sequence to create.
### metadata`instance-attribute`
```
metadata
```
Metadata to associate with the sequence.
### host`class-attribute``instance-attribute`
```
host = 'localhost'
```
The hostname of the Mosaico server.
### port`class-attribute``instance-attribute`
```
port = 6726
```
The port of the Mosaico server.
### ros_distro`class-attribute``instance-attribute`
```
ros_distro = None
```
The specific ROS distribution to use for message parsing (e.g., Stores.ROS2_HUMBLE). If None, defaults to Empty/Auto.
See `rosbags.typesys.Stores`.
### on_error`class-attribute``instance-attribute`
```
on_error = _DEFAULT_SESSION_ON_ERROR
```
the `SequenceWriter``on_error` behavior when a sequence write fails (Report vs Delete)
### topics_on_error`class-attribute``instance-attribute`
```
topics_on_error = _DEFAULT_TOPIC_ON_ERROR
```
The TopicWriter `on_error` behavior (`TopicLevelErrorPolicy`) when a topic write fails. Default is `TopicLevelErrorPolicy.Raise` for all topics. Set to a `TopicLevelErrorPolicy` to apply the same policy to all topics. Set to a `Dict[str, TopicLevelErrorPolicy]` to apply different policies to different topics.
### custom_msgs`class-attribute``instance-attribute`
```
custom_msgs = None
```
A list of tuples (package_name, path, store) to register custom .msg definitions before loading.
For example, for "my_robot_msgs/msg/Location" pass:
package_name = "my_robot_msgs"; path = path/to/Location.msg; store = Stores.ROS2_HUMBLE (e.g.) or None
See `rosbags.typesys.Stores`.
### topics`class-attribute``instance-attribute`
```
topics = None
```
List of topic patterns used to filter available topics.
Supports shell-style glob patterns (e.g., "/cam/*", "*camera_info"). Patterns starting with '!' are treated as exclusions (e.g., "!/cam/debug*").
**Pattern order matters**: - Each non-'!' pattern adds matching topics to the selection. - Each '!' pattern removes matching topics from the selection. - Later patterns override earlier ones. - If no inclusion pattern is provided, selection starts from ALL topics, and only exclusion patterns reduce the set.
If None, all topics are loaded.
### adapter_overrides`class-attribute``instance-attribute`
```
adapter_overrides = None
```
A mapping of topics to adapter overrides, allowing the use of specific adapters instead of the default for designated topics.
### log_level`class-attribute``instance-attribute`
```
log_level = 'INFO'
```
The Log Level
### mosaico_api_key`class-attribute``instance-attribute`
```
mosaico_api_key = None
```
The API key for authentication on the mosaico server. Defaults to None.
If provided it must be have at least `APIKeyPermissionEnum.Write` permission.
### tls_cert_path`class-attribute``instance-attribute`
```
tls_cert_path = None
```
Path to the TLS certificate file for secure connection on the mosaico server. Defaults to None.
### enable_tls`class-attribute``instance-attribute`
```
enable_tls = False
```
Enable the TLS commmunication protocol. Defaults to False
## mosaicolabs.ros_bridge.RosbagInjector
```
RosbagInjector(config)
```
Main controller for the ROS Bag ingestion workflow.
The `RosbagInjector` orchestrates the entire data pipeline from the physical storage to the remote Mosaico server. It manages the initialization of the registry, establishes network connections, and drives the main adaptation loop.
**Core Workflow Architecture:**
- **Registry Initialization**: Pre-loads custom message definitions via the `ROSTypeRegistry`.
- **Resource Management**: Opens the `ROSLoader` for file access and the `MosaicoClient` for networking.
- **Stream Negotiation**: Creates a `SequenceWriter` on the server and opens individual `TopicWriter` streams.
- **Adaptation Loop**: Iterates through ROS records, translates them via the `ROSBridge`, and pushes them to the server.
Attributes:
| Name | Type | Description |
| `cfg` | `ROSInjectionConfig` | The active configuration settings. |
| `console` | `Console` | The rich console instance for logging and UI output. |
| `_ignored_topics` | `Set[str]` | Cache of topics that lack a compatible adapter, used for fast-fail filtering. |
Parameters:
| Name | Type | Description | Default |
| `config` | `ROSInjectionConfig` | The fully resolved configuration object. | *required* |
### run
```
run()
```
Main execution entry point for the injection pipeline.
This method establishes the necessary contexts (Network Client, File Loader, Server Writer) and executes the processing loop. It handles graceful shutdowns in case of user interrupts and provides a summary report upon completion.
Raises:
| Type | Description |
| `KeyboardInterrupt` | If the user cancels the operation via Ctrl+C. |
| `Exception` | Any fatal error encountered during networking or file access. |
## mosaicolabs.ros_bridge.ROSTypeRegistry
A context-aware singleton registry for custom ROS message definitions.
ROS message definitions (`.msg`) are not self-contained; they often vary between distributions (e.g., `std_msgs/Header` has different fields in ROS 1 Noetic vs. ROS 2 Humble). The `ROSTypeRegistry` resolves this by implementing a **Context-Aware Singleton** that organizes schemas into "Profiles" (`rosbags.typesys.Stores`).
##### Why Use a Registry?
- **Conflict Resolution**: Prevents name collisions when processing data from mixed ROS 1 and ROS 2 sources in the same environment.
- **Proprietary Support**: Allows the system to ingest non-standard messages (e.g., custom robot state or specialized sensor payloads).
- **Cascading Logic**: Implements an "Overlay" mechanism where global definitions provide a baseline, and distribution-specific definitions provide high-precision overrides.
Attributes:
| Name | Type | Description |
| `_registry` | `Dict[str, Dict[str, str]]` | Internal private storage for definitions. The first key level represents the **Scope** (e.g., "GLOBAL", "Stores.ROS2_FOXY"), and the second level maps the **Message Type** to its raw **Definition String**. |
### register`classmethod`
```
register(msg_type, source, store=None)
```
Registers a single custom message type into the registry.
This is the primary method for adding individual schema definitions. The `source` can be a physical file path or a raw string containing the ROS `.msg` syntax.
Parameters:
| Name | Type | Description | Default |
| `msg_type` | `str` | The canonical ROS type name (e.g., "package/msg/TypeName"). | *required* |
| `source` | `Union[str, Path]` | A `Path` object to a `.msg` file or a raw text string of the definition. | *required* |
| `store` | `Optional[Union[Stores, str]]` | The target scope. If `None`, the definition is stored in the **GLOBAL** profile and becomes available to all loaders regardless of their distribution. | `None` |
Raises:
| Type | Description |
| `FileNotFoundError` | If `source` is a `Path` that does not exist on the filesystem. |
| `TypeError` | If the `source` is neither a `str` nor a `Path`. |
### register_directory`classmethod`
```
register_directory(package_name, dir_path, store=None)
```
Batch registers all `.msg` files found within a specified directory.
This helper is essential for ingesting entire ROS packages. It automatically infers the full ROS type name by combining the `package_name` with the filename (e.g., `Status.msg` becomes `package_name/msg/Status`).
Parameters:
| Name | Type | Description | Default |
| `package_name` | `str` | The name of the ROS package to use as a prefix. | *required* |
| `dir_path` | `Union[str, Path]` | The filesystem path to the directory containing `.msg` files. | *required* |
| `store` | `Optional[Union[Stores, str]]` | The target distribution scope for the entire directory. | `None` |
Raises:
| Type | Description |
| `ValueError` | If `dir_path` does not point to a valid directory. |
### get_types`classmethod`
```
get_types(store)
```
Retrieves a merged view of message definitions for a specific distribution.
This method implements the **Registry Cascade**: 1. It starts with a base layer of all **GLOBAL** definitions. 2. It overlays (overwrites) those with any **Store-Specific** definitions matching the provided `store` parameter.
This ensures that distribution-specific nuances are respected while maintaining access to shared custom types.
Parameters:
| Name | Type | Description | Default |
| `store` | `Optional[Union[Stores, str]]` | The distribution identifier (e.g., `Stores.ROS2_HUMBLE`) to fetch overrides for. | *required* |
Returns:
| Type | Description |
| `Dict[str, str]` | A flat dictionary mapping `msg_type` to `definition`, formatted for |
| `Dict[str, str]` | direct injection into `rosbags` high-level readers. |
### reset`classmethod`
```
reset()
```
Completely clears the singleton registry.
This is primarily used for **Unit Testing** and CI/CD pipelines to ensure total isolation between different test cases.
---
# Base Adapter
## mosaicolabs.ros_bridge.adapter_base
### ROSAdapterBase
Bases: `ABC`, `Generic[T]`
Abstract Base Class for converting ROS messages to Mosaico Ontology types.
The Adaptation Layer is the semantic core of the ROS Bridge. Rather than performing simple parsing, adapters actively translate raw ROS data into standardized, strongly-typed Mosaico Ontology objects.
Attributes:
| Name | Type | Description |
| `ros_msgtype` | `str | Tuple[str, ...]` | The ROS message type string (e.g., 'sensor_msgs/msg/Imu') or a tuple of supported types. |
| `__mosaico_ontology_type__` | `Type[T]` | The target Mosaico class (e.g., IMU). |
| `_REQUIRED_KEYS` | `Tuple[str, ...]` | Internal validation list for mandatory ROS message fields. |
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message instance into a Mosaico Message.
Implementation should handle recursive unwrapping, unit conversion, and validation.
Parameters:
| Name | Type | Description | Default |
| `ros_msg` | `ROSMessage` | The source container yielded by the ROSLoader. | *required* |
| `**kwargs` | `Any` | Contextual data such as calibration parameters or frame overrides. | `{}` |
Returns:
| Type | Description |
| `Message` | A Mosaico Message object containing the instantiated ontology data. |
#### from_dict`abstractmethod``classmethod`
```
from_dict(ros_data)
```
Maps the raw ROS dictionary to the EncoderTicks Pydantic model.
This method performs field validation and reconstruction.
#### schema_metadata`abstractmethod``classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extracts ROS-specific schema metadata for the Mosaico platform.
This allows preserving original ROS attributes that may not fit directly into the physical ontology fields.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
---
# geometry_msgs Adapters
## mosaicolabs.ros_bridge.adapters.geometry_msgs
Geometry Messages Adaptation Module.
This module provides specialized adapters for translating ROS `geometry_msgs` into the standardized Mosaico Ontology. It implements recursive unwrapping to handle common ROS patterns, such as "Stamped" envelopes and covariance wrappers, ensuring that spatial data is normalized before ingestion.
### PoseAdapter
Bases: `ROSAdapterBase[Pose]`
Adapter for translating ROS Pose-related messages to Mosaico `Pose`.
This adapter follows the "Adaptation, Not Just Parsing" philosophy by actively unwrapping nested ROS structures and normalizing them into strongly-typed Mosaico `Pose` objects.
**Supported ROS Types:**
- `geometry_msgs/msg/Pose`
- `geometry_msgs/msg/PoseStamped`
- `geometry_msgs/msg/PoseWithCovariance`
- `geometry_msgs/msg/PoseWithCovarianceStamped`
**Recursive Unwrapping Strategy:** The adapter checks for nested `'pose'` keys. If found (as in `PoseStamped`), it recurses to the leaf node while collecting metadata like headers and covariance matrices along the way.
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Main entry point for translating a high-level `ROSMessage`.
Parameters:
| Name | Type | Description | Default |
| `ros_msg` | `ROSMessage` | The source ROS message yielded by the loader. | *required* |
| `**kwargs` | `Any` | Additional context for the translation. | `{}` |
Returns:
| Type | Description |
| `Message` | A Mosaico `Message` containing the normalized `Pose` payload. |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Recursively parses a dictionary to extract a `Pose` object.
Strategy:
- **Recurse**: If a 'pose' key is found, dive deeper into the structure.
- **Leaf Node**: At the base level, map 'position' and 'orientation' to `Point3d` and `Quaternion`.
- **Metadata Binding**: Covariances are attached during recursion unwinding.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `Pose` | `Pose` | The constructed Mosaico Pose object. |
Raises:
| Type | Description |
| `ValueError` | If the recursive 'pose' key exists but is not a dict, or if required keys are missing. |
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### schema_metadata`abstractmethod``classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extracts ROS-specific schema metadata for the Mosaico platform.
This allows preserving original ROS attributes that may not fit directly into the physical ontology fields.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### TwistAdapter
Bases: `ROSAdapterBase[Velocity]`
Adapter for translating ROS Twist-related messages to Mosaico `Velocity`.
Commonly referred to as a "Twist," this model captures the instantaneous motion of an object split into linear and angular components.
**Supported ROS Types:**
- `geometry_msgs/msg/Twist`
- `geometry_msgs/msg/TwistStamped`
- `geometry_msgs/msg/TwistWithCovariance`
- `geometry_msgs/msg/TwistWithCovarianceStamped`
**Recursive Unwrapping Strategy:** The adapter checks for nested `'twist'` keys. If found (as in `TwistStamped`), it recurses to the leaf node while collecting metadata like headers and covariance matrices along the way.
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `Velocity` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Recursively parses the ROS data dictionary to extract a `Velocity` (Twist).
Strategy: - **Recurse**: If a 'twist' key is found, dive deeper into the structure. - **Leaf Node**: At the base level, map 'linear' and 'angular' to `Vector3`. - **Metadata Binding**: Covariances are attached during recursion unwinding.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `Velocity` | `Velocity` | The constructed Mosaico Velocity object. |
Raises:
| Type | Description |
| `ValueError` | If the recursive 'twist' key exists but is not a dict, or if required keys are missing. |
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### AccelAdapter
Bases: `ROSAdapterBase[Acceleration]`
Adapter for translating ROS Accel-related messages to Mosaico `Acceleration`.
**Supported ROS Types:**
- `geometry_msgs/msg/Accel`
- `geometry_msgs/msg/AccelStamped`
- `geometry_msgs/msg/AccelWithCovariance`
- `geometry_msgs/msg/AccelWithCovarianceStamped`
**Recursive Unwrapping Strategy:** The adapter checks for nested `'accel'` keys. If found (as in `AccelStamped`), it recurses to the leaf node while collecting metadata like headers and covariance matrices along the way.
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `Acceleration` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Recursively parses the ROS data dictionary to extract an `Acceleration`.
Strategy: - **Recurse**: If a 'accel' key is found, dive deeper into the structure. - **Leaf Node**: At the base level, map 'linear' and 'angular' to `Vector3`. - **Metadata Binding**: Covariances are attached during recursion unwinding.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `Acceleration` | `Acceleration` | The constructed Mosaico Acceleration object. |
Raises:
| Type | Description |
| `ValueError` | If the recursive 'accel' key exists but is not a dict, or if required keys are missing. |
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### Vector3Adapter
Bases: `ROSAdapterBase[Vector3d]`
Adapter for translating ROS Vector3 messages to Mosaico `Vector3d`.
**Supported ROS Types:**
- `geometry_msgs/msg/Vector3`
- `geometry_msgs/msg/Vector3Stamped`
**Recursive Unwrapping Strategy:** The adapter checks for nested `'vector'` keys. If found (as in `Vector3Stamped`), it recurses to the leaf node while collecting metadata like headers and covariance matrices along the way.
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `Vector3d` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Recursively parses the ROS data to extract a `Vector3d`.
Strategy: - **Recurse**: If a 'vector' key is found, dive deeper into the structure. - **Leaf Node**: At the base level, map 'x', 'y' and 'z' to `Vector3d`.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `Vector3d` | `Vector3d` | The constructed Mosaico Vector3d object. |
Raises:
| Type | Description |
| `ValueError` | If the recursive 'vector' key exists but is not a dict, or if required keys are missing. |
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### PointAdapter
Bases: `ROSAdapterBase[Point3d]`
Adapter for translating ROS Point messages to Mosaico `Point3d`.
**Supported ROS Types:**
- `geometry_msgs/msg/Point`
- `geometry_msgs/msg/PointStamped`
**Recursive Unwrapping Strategy:** The adapter checks for nested `'point'` keys. If found (as in `PointStamped`), it recurses to the leaf node while collecting metadata like headers and covariance matrices along the way.
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `Point3d` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Recursively parses the ROS data to extract a `Point3d`.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `Point3d` | `Point3d` | The constructed Mosaico Point3d object. |
Raises:
| Type | Description |
| `ValueError` | If the recursive 'point' key exists but is not a dict, or if required keys are missing. |
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### QuaternionAdapter
Bases: `ROSAdapterBase[Quaternion]`
Adapter for translating ROS Quaternion messages to Mosaico `Quaternion`.
**Supported ROS Types:**
- `geometry_msgs/msg/Quaternion`
- `geometry_msgs/msg/QuaternionStamped`
**Recursive Unwrapping Strategy:** The adapter checks for nested `'quaternion'` keys. If found (as in `QuaternionStamped`), it recurses to the leaf node while collecting metadata like headers and covariance matrices along the way.
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `Quaternion` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Recursively parses the ROS data to extract a `Quaternion`.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `Quaternion` | `Quaternion` | The constructed Mosaico Quaternion object. |
Raises:
| Type | Description |
| `ValueError` | If the recursive 'quaternion' key exists but is not a dict, or if required keys are missing. |
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### TransformAdapter
Bases: `ROSAdapterBase[Transform]`
Adapter for translating ROS Transform messages to Mosaico `Transform`.
**Supported ROS Types:**
- `geometry_msgs/msg/Transform`
- `geometry_msgs/msg/TransformStamped`
**Recursive Unwrapping Strategy:** The adapter checks for nested `'transform'` keys. If found (as in `TransformStamped`), it recurses to the leaf node while collecting metadata like headers and covariance matrices along the way.
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `Transform` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Parses ROS Transform data. Handles both nested 'transform' field (from Stamped) and flat structure.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `Transform` | `Transform` | The constructed Mosaico Transform object. |
Raises:
| Type | Description |
| `ValueError` | If the recursive 'transform' key exists but is not a dict, or if required keys are missing. |
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### WrenchAdapter
Bases: `ROSAdapterBase[ForceTorque]`
Adapter for translating ROS Wrench messages to Mosaico `ForceTorque`.
**Supported ROS Types:**
- `geometry_msgs/msg/Wrench`
- `geometry_msgs/msg/WrenchStamped`
**Recursive Unwrapping Strategy:** The adapter checks for nested `'wrench'` keys. If found (as in `WrenchStamped`), it recurses to the leaf node while collecting metadata like headers and covariance matrices along the way.
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `ForceTorque` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Parses ROS ForceTorque data. Handles both nested 'wrench' field (from Stamped) and flat structure.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### PolygonAdapter
Bases: `ROSAdapterBase[Polygon]`
Adapter for translating ROS Polygon messages to Mosaico `Polygon`.
**Supported ROS Types:**
- `geometry_msgs/msg/Polygon`
- `geometry_msgs/msg/PolygonStamped`
**Recursive Unwrapping Strategy:** The adapter checks for nested 'polygon' keys (as in PolygonStamped) and recursively unwraps to the base structure.
Example:
```
ros_msg = ROSMessage(
topic="/polygon",
timestamp=17000,
msg_type="geometry_msgs/msg/Polygon",
data={
"points": [
{"x": 1.0, "y": 2.0, "z": 0.0},
{"x": 3.0, "y": 4.0, "z": 0.0},
]
}
)
mosaico_polygon = PolygonAdapter.translate(ros_msg)
```
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `Polygon` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Parses ROS Polygon data. Handles both nested ('PolygonStamped') and flat structures.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `Polygon` | `Polygon` | The constructed Mosaico Polygon object. |
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### InertiaAdapter
Bases: `ROSAdapterBase[Inertia]`
Adapter for translating ROS Inertia messages to Mosaico `Inertia`.
**Supported ROS Types:**
- `geometry_msgs/msg/Inertia`
- `geometry_msgs/msg/InertiaStamped`
**Recursive Unwrapping Strategy:** The adapter checks for nested 'inertia' keys (as in InertiaStamped) and recursively unwraps to the base structure.
Example:
```
ros_msg = ROSMessage(
topic="/inertia",
timestamp=17000,
msg_type="geometry_msgs/msg/Inertia",
data={
"m": 10.0,
"com": {"x": 0.0, "y": 0.0, "z": 0.0},
"ixx": 1.0,
"ixy": 0.0,
"ixz": 0.0,
"iyy": 1.0,
"iyz": 0.0,
"izz": 1.0,
}
)
mosaico_inertia = InertiaAdapter.translate(ros_msg)
```
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `Inertia` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Parses ROS Inertia data. Handles both nested ('InertiaStamped') and flat structures.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `Inertia` | `Inertia` | The constructed Mosaico Inertia object. |
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
---
# nav_msgs Adapters
## mosaicolabs.ros_bridge.adapters.nav_msgs
### OdometryAdapter
Bases: `ROSAdapterBase[MotionState]`
Adapter for translating ROS Odometry messages to Mosaico `MotionState`.
**Supported ROS Types:**
- `nav_msgs/msg/Odometry`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `MotionState` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Parses a dictionary to extract a `MotionState` object.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `MotionState` | `MotionState` | The constructed Mosaico MotionState object. |
Raises:
| Type | Description |
| `ValueError` | If the recursive 'pose' key exists but is not a dict, or if required keys are missing. |
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
---
# override_msgs Adapters
## mosaicolabs.ros_bridge.adapters.override_msgs
### LidarAdapter
Bases: `PointCloudAdapterBase[Lidar]`
Adapter for translating ROS PointCloud2 messages to Mosaico `Lidar`. This Adapter needs to be specified in the field `adapters_override` of `RosInjectionConfig`.
**Supported ROS Types:**
- `sensor_msgs/msg/PointCloud2`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `Lidar` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Create a Lidar instance from a ROS message dictionary.
Example:
```
ros_data = {
"height": 1,
"width": 3,
"fields": [...],
"is_bigendian": False,
"point_step": 16,
"row_step": 48,
"data": [...],
"is_dense": True,
}
# Automatically resolves to a flat Mosaico Lidar with attached data
mosaico_lidar = LidarAdapter.from_dict(ros_data)
```
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
#### decode`classmethod`
```
decode(ros_data)
```
Deserialize the binary buffer of a ROS `sensor_msgs/msg/PointCloud2` message into named field arrays.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | Raw ROS message payload. Relevant keys: `data`, `height`, `width`, `fields`, `is_bigendian`, `point_step`. | *required* |
Returns:
| Type | Description |
| `dict[str, list]` | Dictionary mapping each field name to a list of decoded values. Returns empty lists for all fields if `height * width == 0`. |
Raises:
| Type | Description |
| `ValueError` | If a field exposes an unsupported `datatype`. |
### RadarAdapter
Bases: `PointCloudAdapterBase[Radar]`
Adapter for translating ROS PointCloud2 messages to Mosaico `Radar`. This Adapter needs to be specified in the field `adapters_override` of `RosInjectionConfig`.
**Supported ROS Types:**
- `sensor_msgs/msg/PointCloud2`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `Radar` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Create a Radar instance from a ROS message dictionary. Example:
```
ros_data = {
"height": 1,
"width": 3,
"fields": [...],
"is_bigendian": False,
"point_step": 16,
"row_step": 48,
"data": [...],
"is_dense": True,
}
# Automatically resolves to a flat Mosaico Radar with attached data
mosaico_radar = RadarAdapter.from_dict(ros_data)
```
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
#### decode`classmethod`
```
decode(ros_data)
```
Deserialize the binary buffer of a ROS `sensor_msgs/msg/PointCloud2` message into named field arrays.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | Raw ROS message payload. Relevant keys: `data`, `height`, `width`, `fields`, `is_bigendian`, `point_step`. | *required* |
Returns:
| Type | Description |
| `dict[str, list]` | Dictionary mapping each field name to a list of decoded values. Returns empty lists for all fields if `height * width == 0`. |
Raises:
| Type | Description |
| `ValueError` | If a field exposes an unsupported `datatype`. |
### RGBDCameraAdapter
Bases: `PointCloudAdapterBase[RGBDCamera]`
Adapter for translating ROS PointCloud2 messages to Mosaico `RGBDCamera`. This Adapter needs to be specified in the field `adapters_override` of `RosInjectionConfig`.
**Supported ROS Types:**
- `sensor_msgs/msg/PointCloud2`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `RGBDCamera` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Create a RGBDCamera instance from a ROS message dictionary.
Example:
```
ros_data = {
"height": 1,
"width": 3,
"fields": [...],
"is_bigendian": False,
"point_step": 16,
"row_step": 48,
"data": [...],
"is_dense": True,
}
# Automatically resolves to a flat Mosaico RGBDCamera with attached data
mosaico_rgbd_camera = RGBDCameraAdapter.from_dict(ros_data)
```
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
#### decode`classmethod`
```
decode(ros_data)
```
Deserialize the binary buffer of a ROS `sensor_msgs/msg/PointCloud2` message into named field arrays.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | Raw ROS message payload. Relevant keys: `data`, `height`, `width`, `fields`, `is_bigendian`, `point_step`. | *required* |
Returns:
| Type | Description |
| `dict[str, list]` | Dictionary mapping each field name to a list of decoded values. Returns empty lists for all fields if `height * width == 0`. |
Raises:
| Type | Description |
| `ValueError` | If a field exposes an unsupported `datatype`. |
### ToFCameraAdapter
Bases: `PointCloudAdapterBase[ToFCamera]`
Adapter for translating ROS PointCloud2 messages to Mosaico `ToFCamera`. This Adapter needs to be specified in the field `adapters_override` of `RosInjectionConfig`.
**Supported ROS Types:**
- `sensor_msgs/msg/PointCloud2`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `ToFCamera` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Create a ToFCamera instance from a ROS message dictionary.
Example:
```
ros_data = {
"height": 1,
"width": 3,
"fields": [...],
"is_bigendian": False,
"point_step": 16,
"row_step": 48,
"data": [...],
"is_dense": True,
}
# Automatically resolves to a flat Mosaico ToFCamera with attached data
mosaico_tof_camera = ToFCameraAdapter.from_dict(ros_data)
```
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
#### decode`classmethod`
```
decode(ros_data)
```
Deserialize the binary buffer of a ROS `sensor_msgs/msg/PointCloud2` message into named field arrays.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | Raw ROS message payload. Relevant keys: `data`, `height`, `width`, `fields`, `is_bigendian`, `point_step`. | *required* |
Returns:
| Type | Description |
| `dict[str, list]` | Dictionary mapping each field name to a list of decoded values. Returns empty lists for all fields if `height * width == 0`. |
Raises:
| Type | Description |
| `ValueError` | If a field exposes an unsupported `datatype`. |
### StereoCameraAdapter
Bases: `PointCloudAdapterBase[StereoCamera]`
Adapter for translating ROS PointCloud2 messages to Mosaico `StereoCamera`. This Adapter needs to be specified in the field `adapters_override` of `RosInjectionConfig`.
**Supported ROS Types:**
- `sensor_msgs/msg/PointCloud2`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `StereoCamera` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Create a StereoCamera instance from a ROS message dictionary.
Example:
```
ros_data = {
"height": 1,
"width": 3,
"fields": [...],
"is_bigendian": False,
"point_step": 16,
"row_step": 48,
"data": [...],
"is_dense": True,
}
# Automatically resolves to a flat Mosaico StereoCamera with attached data
mosaico_stereo_camera = StereoCameraAdapter.from_dict(ros_data)
```
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
#### decode`classmethod`
```
decode(ros_data)
```
Deserialize the binary buffer of a ROS `sensor_msgs/msg/PointCloud2` message into named field arrays.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | Raw ROS message payload. Relevant keys: `data`, `height`, `width`, `fields`, `is_bigendian`, `point_step`. | *required* |
Returns:
| Type | Description |
| `dict[str, list]` | Dictionary mapping each field name to a list of decoded values. Returns empty lists for all fields if `height * width == 0`. |
Raises:
| Type | Description |
| `ValueError` | If a field exposes an unsupported `datatype`. |
---
# sensor_msgs Adapters
## mosaicolabs.ros_bridge.adapters.sensor_msgs
### CameraInfoAdapter
Bases: `ROSAdapterBase[CameraInfo]`
Adapter for translating ROS CameraInfo messages to Mosaico `CameraInfo`.
**Supported ROS Types:**
- `sensor_msgs/msg/CameraInfo`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `CameraInfo` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Converts the raw dictionary data into the specific Mosaico type.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `CameraInfo` | `CameraInfo` | The constructed Mosaico CameraInfo object. |
Raises:
| Type | Description |
| `ValueError` | If the recursive 'roi' key exists but is not a dict, or if required keys are missing. |
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### NavSatStatusAdapter
Bases: `ROSAdapterBase[GPSStatus]`
Adapter for translating ROS NavSatStatus messages to Mosaico `GPSStatus`.
**Supported ROS Types:**
- `sensor_msgs/msg/NavSatFix`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `GPSStatus` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Converts the raw dictionary data into the specific Mosaico type.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `GPSStatus` | `GPSStatus` | The constructed Mosaico GPSStatus object. |
Raises:
| Type | Description |
| `ValueError` | If the recursive 'roi' key exists but is not a dict, or if required keys are missing. |
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### GPSAdapter
Bases: `ROSAdapterBase[GPS]`
Adapter for translating ROS NavSatFix messages to Mosaico `GPS`.
**Supported ROS Types:**
- `sensor_msgs/msg/NavSatFix`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `GPS` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Converts the raw dictionary data into the specific Mosaico type.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `GPS` | `GPS` | The constructed Mosaico GPS object. |
Raises:
| Type | Description |
| `ValueError` | If the recursive 'roi' key exists but is not a dict, or if required keys are missing. |
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### IMUAdapter
Bases: `ROSAdapterBase[IMU]`
Adapter for translating ROS Imu messages to Mosaico `IMU`.
**Supported ROS Types:**
- `sensor_msgs/msg/Imu`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `IMU` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Converts the raw dictionary data into the specific Mosaico type.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `IMU` | `IMU` | The constructed Mosaico IMU object. |
Raises:
| Type | Description |
| `ValueError` | If the recursive 'roi' key exists but is not a dict, or if required keys are missing. |
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### NMEASentenceAdapter
Bases: `ROSAdapterBase[NMEASentence]`
Adapter for translating ROS NMEASentence messages to Mosaico `NMEASentence`.
**Supported ROS Types:**
- `nmea_msgs/msg/Sentence`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `NMEASenetence` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Converts the raw dictionary data into the specific Mosaico type.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `NMEASentence` | `NMEASentence` | The constructed Mosaico NMEASentence object. |
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### ImageAdapter
Bases: `ROSAdapterBase[Image]`
Adapter for translating ROS Image messages to Mosaico `Image`.
**Supported ROS Types:**
- `sensor_msgs/msg/Image`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `Image` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data, **kwargs)
```
Converts the raw dictionary data into the specific Mosaico type.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `Image` | `Image` | The constructed Mosaico Image object. |
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### CompressedImageAdapter
Bases: `ROSAdapterBase[CompressedImage]`
Adapter for translating ROS CompressedImage messages to Mosaico `CompressedImage`.
**Supported ROS Types:**
- `sensor_msgs/msg/CompressedImage`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `CompressedImage` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Converts the raw dictionary data into the specific Mosaico type.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `CompressedImage` | `CompressedImage` | The constructed Mosaico CompressedImage object. |
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### ROIAdapter
Bases: `ROSAdapterBase[ROI]`
Adapter for translating ROS RegionOfInterest messages to Mosaico `ROI`.
**Supported ROS Types:**
- `sensor_msgs/RegionOfInterest`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `ROI` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Converts the raw dictionary data into the specific Mosaico type.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `ROI` | `ROI` | The constructed Mosaico ROI object. |
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### BatteryStateAdapter
Bases: `ROSAdapterBase[BatteryState]`
Adapter for translating ROS BatteryState messages to Mosaico `BatteryState`.
**Supported ROS Types:**
- `sensor_msgs/msg/BatteryState`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `BatteryState` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Converts the raw dictionary data into the specific Mosaico type.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `BatteryState` | `BatteryState` | The constructed Mosaico BatteryState object. |
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### RobotJointAdapter
Bases: `ROSAdapterBase[RobotJoint]`
Adapter for translating ROS JointState messages to Mosaico `RobotJoint`.
**Supported ROS Types:**
- `sensor_msgs/msg/JointState`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `RobotJoint` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Converts the raw dictionary data into the specific Mosaico type.
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### PointCloudAdapterBase
Bases: `ROSAdapterBase[PointCloudModel]`
Base adapter for translating ROS PointCloud2 message to Mosaico specific ontology.
#### decode`classmethod`
```
decode(ros_data)
```
Deserialize the binary buffer of a ROS `sensor_msgs/msg/PointCloud2` message into named field arrays.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | Raw ROS message payload. Relevant keys: `data`, `height`, `width`, `fields`, `is_bigendian`, `point_step`. | *required* |
Returns:
| Type | Description |
| `dict[str, list]` | Dictionary mapping each field name to a list of decoded values. Returns empty lists for all fields if `height * width == 0`. |
Raises:
| Type | Description |
| `ValueError` | If a field exposes an unsupported `datatype`. |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Convert a raw ROS PointCloud2 message dictionary into a typed Mosaico model.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | Raw ROS message payload as a dictionary. | *required* |
Returns:
| Type | Description |
| `PointCloudModel` | A fully populated instance of the target `PointCloudModel` subtype (e.g. `Lidar`, `Radar`, `RGBDCamera`, ...). |
Raises:
| Type | Description |
| `ValueError` | If any required message key is missing from `ros_data`, or if any required field is absent after decoding. |
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message instance into a Mosaico Message.
Implementation should handle recursive unwrapping, unit conversion, and validation.
Parameters:
| Name | Type | Description | Default |
| `ros_msg` | `ROSMessage` | The source container yielded by the ROSLoader. | *required* |
| `**kwargs` | `Any` | Contextual data such as calibration parameters or frame overrides. | `{}` |
Returns:
| Type | Description |
| `Message` | A Mosaico Message object containing the instantiated ontology data. |
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### PointCloudAdapter
Bases: `PointCloudAdapterBase[PointCloud2]`
Adapter for translating ROS PointCloud2 messages to Mosaico `PointCloud2`.
**Supported ROS Types:**
- `sensor_msgs/msg/PointCloud2`
Example:
```
ros_msg = ROSMessage(
timestamp=17000,
topic="/point_cloud",
msg_type="sensor_msgs/PointCloud2",
data = {
"height": 1,
"width": 3,
"fields": [
{"name": "x", "offset": 0, "datatype": 7, "count": 1},
{"name": "y", "offset": 4, "datatype": 7, "count": 1},
{"name": "z", "offset": 8, "datatype": 7, "count": 1},
],
"is_bigendian": False,
"point_step": 12,
"row_step": 36,
"data": ...,
"is_dense": True,
}
)
# Automatically resolves to a flat Mosaico PointCloud2 with attached metadata
mosaico_point_cloud = PointCloudAdapter.translate(ros_msg)
```
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `PointCloud2` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Converts the raw dictionary data into the specific Mosaico type.
Example:
```
ros_data = {
"height": 1, # unorganized point cloud = 1 row
"width": 3, # 3 points
"fields": [
{
"name": "x",
"offset": 0,
"datatype": 7, # FLOAT32
"count": 1
},
{
"name": "y",
"offset": 4,
"datatype": 7, # FLOAT32
"count": 1
},
{
"name": "z",
"offset": 8,
"datatype": 7, # FLOAT32
"count": 1
},
],
"is_bigendian": False,
"point_step": 12, # 3 fields * 4 bytes (float32) = 12 bytes per point
"row_step": 36, # point_step * width = 12 * 3 = 36 bytes per row
"data": ...,
"is_dense": True
}
```
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
#### decode`classmethod`
```
decode(ros_data)
```
Deserialize the binary buffer of a ROS `sensor_msgs/msg/PointCloud2` message into named field arrays.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | Raw ROS message payload. Relevant keys: `data`, `height`, `width`, `fields`, `is_bigendian`, `point_step`. | *required* |
Returns:
| Type | Description |
| `dict[str, list]` | Dictionary mapping each field name to a list of decoded values. Returns empty lists for all fields if `height * width == 0`. |
Raises:
| Type | Description |
| `ValueError` | If a field exposes an unsupported `datatype`. |
### LaserScannerAdapterBase
Bases: `ROSAdapterBase[_LT]`
Base adapter for translating ROS LaserScan and MultiEchoLaserScan messages to Mosaico `LaserScan` and `MultiEchoLaserScan` .
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Create a LaserScan/MultiEchoLaserScan instance from a ROS message dictionary.
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message instance into a Mosaico Message.
Implementation should handle recursive unwrapping, unit conversion, and validation.
Parameters:
| Name | Type | Description | Default |
| `ros_msg` | `ROSMessage` | The source container yielded by the ROSLoader. | *required* |
| `**kwargs` | `Any` | Contextual data such as calibration parameters or frame overrides. | `{}` |
Returns:
| Type | Description |
| `Message` | A Mosaico Message object containing the instantiated ontology data. |
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### LaserScanAdapter
Bases: `LaserScannerAdapterBase[LaserScan]`
Adapter for translating ROS LaserScan messages to Mosaico `LaserScan`.
**Supported ROS Types:**
- `sensor_msgs/msg/LaserScan`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `LaserScan` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Create a LaserScan instance from a ROS message dictionary.
Example:
```
ros_data = {
"angle_min": -1.57,
"angle_max": 1.57,
"angle_increment": 0.01,
"time_increment": 0.0,
"scan_time": 0.1,
"range_min": 0.2,
"range_max": 10.0,
"ranges": [1.0, 1.1, 1.2],
"intensities": [100.0, 110.0, 120.0],
}
# Automatically resolves to a flat Mosaico LaserScan with attached data
mosaico_laser_scan = LaserScanAdapter.from_dict(ros_data)
```
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### MultiEchoLaserScanAdapter
Bases: `LaserScannerAdapterBase[MultiEchoLaserScan]`
Adapter for translating ROS MultiEchoLaserScan messages to Mosaico `MultiEchoLaserScan`.
**Supported ROS Types:**
- `sensor_msgs/msg/MultiEchoLaserScan`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `MultiEchoLaserScan` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Create a MultiEchoLaserScan instance from a ROS message dictionary.
Example:
```
ros_data = {
"angle_min": -1.57,
"angle_max": 1.57,
"angle_increment": 0.01,
"time_increment": 0.0,
"scan_time": 0.1,
"range_min": 0.2,
"range_max": 10.0,
"ranges": [[1.0, 1.1, 1.2], [2.0, 2.1, 2.2], [3.0, 3.1, 3.2]],
"intensities": [[100.0, 110.0, 120.0], [200.0, 210.0, 220.0], [300.0, 310.0, 320.0]],
}
# Automatically resolves to a flat Mosaico MultiEchoLaserScanAdapter with attached data
mosaico_laser_scan = MultiEchoLaserScanAdapter.from_dict(ros_data)
```
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### MagneticFieldAdapter
Bases: `ROSAdapterBase[Magnetometer]`
Adapter for translating ROS MagneticField messages to Mosaico `Magnetometer`.
**Supported ROS Types:**
- `sensor_msgs/msg/MagneticField`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `Magnetometer` object. |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Converts the raw dictionary data into the specific Mosaico type.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `Magnetometer` | `Magnetometer` | The constructed Mosaico Magnetometer object. |
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
MagneticField messages typically do not include additional schema metadata, so this returns None unless extended in the future.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
### JoyAdapter
Bases: `ROSAdapterBase[Joy]`
Adapter for translating ROS Joy messages to Mosaico `Joy`.
**Supported ROS Types:**
- `sensor_msgs/msg/Joy`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `Joy` object. |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Converts the raw dictionary data into the specific Mosaico type.
Parameters:
| Name | Type | Description | Default |
| `ros_data` | `dict` | The raw dictionary from the ROS message. | *required* |
Returns:
| Name | Type | Description |
| `Joy` | `Joy` | The constructed Mosaico Joy object. |
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
Joy messages typically do not include additional schema metadata, so this returns None unless extended in the future.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
---
# std_msgs Adapters
## mosaicolabs.ros_bridge.adapters.std_msgs
Standard ROS Message Adapters.
This module provides adapters for translating standard ROS messages (std_msgs) into Mosaico ontology types. Instead of manually defining a class for every single primitive type (Int8, String, Bool, etc.), we use a dynamic factory pattern.
### GenericStdAdapter
Bases: `ROSAdapterBase[Serializable]`
Template for dynamic factory-based adaptation of standard ROS primitive messages.
This class provides the core translation logic for the `std_msgs` family. To avoid manual definition of dozens of repetitive classes (e.g., `Int8Adapter`, `StringAdapter`), the ROS Bridge employs a **Dynamic Factory Pattern**.
**Supported ROS Types:**
- `std_msgs/msg/String`
- `std_msgs/msg/Int8`
- `std_msgs/msg/Int16`
- `std_msgs/msg/Int32`
- `std_msgs/msg/Int64`
- `std_msgs/msg/UInt8`
- `std_msgs/msg/UInt16`
- `std_msgs/msg/UInt32`
- `std_msgs/msg/UInt64`
- `std_msgs/msg/Float32`
- `std_msgs/msg/Float64`
- `std_msgs/msg/Bool`
###### Architecture & Dynamic Generation
At module load time, the SDK iterates through a configuration mapping (`_ROS_MSGTYPE_MSCO_BASE_TYPE_MAP`) and programmatically generates concrete subclasses of `GenericStdAdapter`.
Each generated subclass is:
- **Injected** with a specific `ros_msgtype` (e.g., `"std_msgs/msg/String"`).
- **Injected** with a specific target `__mosaico_ontology_type__` (e.g., `String`).
- **Registered** automatically in the `ROSBridge` using the `@register_default_adapter` mechanism.
###### "Adaptation" Strategy
Following the philosophy of **"Adaptation, Not Just Parsing,"** these adapters do not simply extract raw values. They perform:
- **Schema Enforcement**: Validating that the ROS message contains the mandatory `'data'` field.
- **Strong Typing**: Wrapping the primitive value into a Mosaico `Serializable` object with its own metadata and queryable headers.
- **Temporal Alignment**: Preserving nanosecond-precise timestamps and optional frame information from the source bag file.
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a standard ROS message to a Mosaico Message.
Standard messages typically contain a 'data' field and metadata. This method extracts the header/timestamp and wraps the payload using the specific ontology type defined for this adapter class.
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Converts the raw dictionary data into the specific Mosaico type.
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Standard types do not carry additional schema metadata.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
---
# tf2_msgs Adapters
## mosaicolabs.ros_bridge.adapters.tf2_msgs
### FrameTransformAdapter
Bases: `ROSAdapterBase`
Adapter for translating ROS TF2 messages to Mosaico `FrameTransform`.
**Supported ROS Types:**
- `tf2_msgs/msg/TFMessage`
#### translate`classmethod`
```
translate(ros_msg, **kwargs)
```
Translates a ROS message into a Mosaico Message.
Returns:
| Name | Type | Description |
| `Message` | `Message` | The translated message containing a `FrameTransform` object. |
Raises:
| Type | Description |
| `Exception` | Wraps any translation error with context (topic name, timestamp). |
#### from_dict`classmethod`
```
from_dict(ros_data)
```
Converts the raw dictionary data into the specific Mosaico type.
#### schema_metadata`classmethod`
```
schema_metadata(ros_data, **kwargs)
```
Extract the ROS message specific schema metadata, if any.
#### ros_msg_type`abstractmethod``classmethod`
```
ros_msg_type()
```
Returns the specific ROS message type handled by this adapter.
#### ontology_data_type`classmethod`
```
ontology_data_type()
```
Returns the Ontology class type associated with this adapter.
---
# Data Retrieval
## mosaicolabs.handlers.SequenceHandler
```
SequenceHandler(
*,
sequence_model,
client,
timestamp_ns_min,
timestamp_ns_max,
)
```
Represents a client-side handle for an existing Sequence on the Mosaico platform.
The `SequenceHandler` acts as a primary container for inspecting sequence-level metadata, listing available topics, and accessing data reading interfaces like the `SequenceDataStreamer`.
Internal constructor for SequenceHandler.
**Do not call this directly.** Users should retrieve instances via `MosaicoClient.sequence_handler()`, while internal modules should use the `SequenceHandler._connect()` factory.
Parameters:
| Name | Type | Description | Default |
| `sequence_model` | `Sequence` | The underlying metadata and system info model for the sequence. | *required* |
| `client` | `FlightClient` | The active FlightClient for remote operations. | *required* |
| `timestamp_ns_min` | `Optional[int]` | The lowest timestamp (in ns) available in this sequence. | *required* |
| `timestamp_ns_max` | `Optional[int]` | The highest timestamp (in ns) available in this sequence. | *required* |
### name`property`
```
name
```
The unique name of the sequence.
Returns:
| Type | Description |
| `str` | The unique name of the sequence. |
### topics`property`
```
topics
```
The list of topic names (data channels) available within this sequence.
Returns:
| Type | Description |
| `List[str]` | The list of topic names (data channels) available within this sequence. |
### sessions`property`
```
sessions
```
The list of all the writing sessions that produced this sequence (upon creation or updates).
Returns:
| Type | Description |
| `List[Session]` | A list of `Session` instances |
### user_metadata`property`
```
user_metadata
```
The user-defined metadata dictionary associated with this sequence.
Returns:
| Type | Description |
| `Dict[str, Any]` | The ucreated_timestampdata dictionary associated with this sequence. |
### created_timestamp`property`
```
created_timestamp
```
The UTC timestamp indicating when the entity was created on the server.
Returns:
| Type | Description |
| `int` | The UTC creation timestamp. |
### updated_timestamps`property`
```
updated_timestamps
```
The list of UTC timestamps indicating when the entity was updated on the server.
Returns:
| Type | Description |
| `List[int]` | The list of UTC update timestamps. |
### total_size_bytes`property`
```
total_size_bytes
```
The total physical storage footprint of the entity on the server in bytes.
Returns:
| Type | Description |
| `int` | The total physical storage in bytes. |
### timestamp_ns_min`property`
```
timestamp_ns_min
```
The lowest timestamp (nanoseconds) recorded in the sequence across all topics.
Returns:
| Type | Description |
| `Optional[int]` | The lowest timestamp (nanoseconds) recorded in the sequence across all topics, or `None` if the sequence contains no data or the timestamps could not be derived. |
### timestamp_ns_max`property`
```
timestamp_ns_max
```
The highest timestamp (nanoseconds) recorded in the sequence across all topics.
Returns:
| Type | Description |
| `Optional[int]` | The highest timestamp (nanoseconds) recorded in the sequence across all topics, or `None` if the sequence contains no data or the timestamps could not be derived. |
### get_data_streamer
```
get_data_streamer(
topics=[],
start_timestamp_ns=None,
end_timestamp_ns=None,
)
```
Opens a reading channel for iterating over the sequence data.
The returned `SequenceDataStreamer` performs a K-way merge sort to provide a single, time-synchronized chronological stream of messages from multiple topics.
Parameters:
| Name | Type | Description | Default |
| `topics` | `List[str]` | A subset of topic names to stream. If empty, all topics in the sequence are streamed. | `[]` |
| `start_timestamp_ns` | `Optional[int]` | The **inclusive** lower bound (t >= start) for the time window in nanoseconds. The stream starts at the first message with a timestamp greater than or equal to this value. | `None` |
| `end_timestamp_ns` | `Optional[int]` | The **exclusive** upper bound (t < end) for the time window in nanoseconds. The stream stops at the first message with a timestamp strictly less than this value. | `None` |
Returns:
| Type | Description |
| `SequenceDataStreamer` | A `SequenceDataStreamer` iterator yielding `(topic_name, message)` tuples. |
Raises:
| Type | Description |
| `ValueError` | If the provided topic names do not exist or if the sequence contains no data. |
### get_topic_handler
```
get_topic_handler(topic_name, force_new_instance=False)
```
Get a specific `TopicHandler` for a child topic.
Parameters:
| Name | Type | Description | Default |
| `topic_name` | `str` | The relative name of the topic (e.g., "/camera/front"). | *required* |
| `force_new_instance` | `bool` | If `True`, bypasses the internal cache and recreates the handler. | `False` |
Returns:
| Type | Description |
| `TopicHandler` | A `TopicHandler` dedicated to the specified topic. |
Raises:
| Type | Description |
| `ValueError` | If the topic is not available in this sequence or an internal connection error occurs. |
### update
```
update(
on_error=Report,
max_batch_size_bytes=None,
max_batch_size_records=None,
)
```
Update the sequence on the platform and returns a `SequenceUpdater` for ingestion.
Parameters:
| Name | Type | Description | Default |
| `on_error` | `SessionLevelErrorPolicy` | Behavior on write failure. Defaults to `SessionLevelErrorPolicy.Report`. | `Report` |
| `max_batch_size_bytes` | `Optional[int]` | Max bytes per Arrow batch. | `None` |
| `max_batch_size_records` | `Optional[int]` | Max records per Arrow batch. | `None` |
Returns:
| Name | Type | Description |
| `SequenceUpdater` | `SequenceUpdater` | An initialized updater instance. |
Raises:
| Type | Description |
| `RuntimeError` | If the method is called outside a `with` context. |
| `Exception` | If any error occurs during sequence injection. |
### reload
```
reload()
```
Reloads the handler's data from the server. Use this method when you need to retrieve the latest sequence information, e.g. after a sequence update.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if the reload was successful, False otherwise. |
### close
```
close()
```
Gracefully closes all cached topic handlers and active data streamers.
This method should be called to release network and memory resources when the handler is no longer needed.
## mosaicolabs.handlers.TopicHandler
```
TopicHandler(
*,
client,
topic_model,
ticket,
timestamp_ns_min,
timestamp_ns_max,
)
```
Represents an existing topic on the Mosaico platform.
The `TopicHandler` provides a client-side interface for interacting with an individual data stream (topic). It allows users to inspect static metadata and system diagnostics (via the `Topic` model), and access the raw message stream through a dedicated `TopicDataStreamer`.
Internal constructor for TopicHandler.
**Do not call this directly.** Users should retrieve instances via `MosaicoClient.topic_handler()`, or by using the `get_topic_handler()` method from the `SequenceHandler` instance of the parent senquence. Internal modules should use the `TopicHandler._connect()` factory.
Parameters:
| Name | Type | Description | Default |
| `client` | `FlightClient` | The active FlightClient for remote operations. | *required* |
| `topic_model` | `Topic` | The underlying metadata and system info model for the topic. | *required* |
| `ticket` | `Ticket` | The remote resource ticket used for data retrieval. | *required* |
| `timestamp_ns_min` | `Optional[int]` | The lowest timestamp (in ns) available in this topic. | *required* |
| `timestamp_ns_max` | `Optional[int]` | The highest timestamp (in ns) available in this topic. | *required* |
### name`property`
```
name
```
The relative name of the topic (e.g., "/front_cam/image_raw").
Returns:
| Type | Description |
| `str` | The relative name of the topic. |
### sequence_name`property`
```
sequence_name
```
The name of the parent sequence containing this topic.
Returns:
| Type | Description |
| `str` | The name of the parent sequence. |
### user_metadata`property`
```
user_metadata
```
The user-defined metadata dictionary associated with this topic.
Returns:
| Type | Description |
| `Dict[str, Any]` | The user-defined metadata dictionary. |
### created_timestamp`property`
```
created_timestamp
```
The UTC timestamp indicating when the entity was created on the server.
Returns:
| Type | Description |
| `int` | The UTC timestamp indicating when the entity was created on the server. |
### locked`property`
```
locked
```
Indicates if the resource is currently locked.
A locked state typically occurs during active writing or maintenance operations, preventing deletion or structural modifications.
Returns:
| Type | Description |
| `bool` | True if the resource is currently locked, False otherwise. |
### chunks_number`property`
```
chunks_number
```
The number of physical data chunks stored for this topic.
Returns:
| Type | Description |
| `Optional[int]` | The number of physical data chunks stored for this topic, or `None` if the server did not provide detailed storage statistics. |
### ontology_tag`property`
```
ontology_tag
```
The ontology type identifier (e.g., 'imu', 'gnss').
This corresponds to the `__ontology_tag__` defined in the `Serializable` class registry.
Returns:
| Type | Description |
| `str` | The ontology type identifier. |
### serialization_format`property`
```
serialization_format
```
The format used to serialize the topic data (e.g., 'arrow', 'image').
This corresponds to the `SerializationFormat` enum.
Returns:
| Type | Description |
| `str` | The serialization format. |
### total_size_bytes`property`
```
total_size_bytes
```
The total physical storage footprint of the entity on the server in bytes.
Returns:
| Type | Description |
| `int` | The total physical storage footprint of the entity on the server in bytes. |
### timestamp_ns_min`property`
```
timestamp_ns_min
```
The lowest timestamp (nanoseconds) recorded in this topic.
Returns:
| Type | Description |
| `Optional[int]` | The lowest timestamp (nanoseconds) recorded in this topic, or `None` if the topic is empty or timestamps are unavailable. |
### timestamp_ns_max`property`
```
timestamp_ns_max
```
The highest timestamp (nanoseconds) recorded in this topic.
Returns:
| Type | Description |
| `Optional[int]` | The highest timestamp (nanoseconds) recorded in this topic, or `None` if the topic is empty or timestamps are unavailable. |
### get_data_streamer
```
get_data_streamer(
start_timestamp_ns=None, end_timestamp_ns=None
)
```
Opens a high-performance reading channel for iterating over this topic's data.
###### Stream Lifecycle Policy: Single-Active-Streamer
To optimize resource utilization and prevent backend socket exhaustion, this handler maintains at most **one active stream** at a time.
Parameters:
| Name | Type | Description | Default |
| `start_timestamp_ns` | `Optional[int]` | The **inclusive** lower bound (t >= start) in nanoseconds. The stream begins at the first message with a timestamp >= this value. | `None` |
| `end_timestamp_ns` | `Optional[int]` | The **exclusive** upper bound (t < end) in nanoseconds. The stream terminates before reaching any message with a timestamp >= this value. | `None` |
Returns:
| Name | Type | Description |
| `TopicDataStreamer` | `TopicDataStreamer` | A chronological iterator for the requested data window. |
Raises:
| Type | Description |
| `ValueError` | If the topic contains no data or the handler is in an invalid state. |
### close
```
close()
```
Terminates the active data streamer associated with this topic and releases allocated system resources.
In the Mosaico architecture, a `TopicHandler` acts as a factory for `TopicDataStreamers`. Calling `close()` ensures that any background data fetching, buffering, or network sockets held by an active streamer are immediately shut down.
## mosaicolabs.handlers.SequenceDataStreamer
```
SequenceDataStreamer(
*, sequence_name, client, topic_readers
)
```
A unified, time-ordered iterator for reading multi-topic sequences.
The `SequenceDataStreamer` performs a **K-Way Merge** across multiple topic streams to provide a single, coherent chronological view of an entire sequence. This is essential when topics have different recording rates or asynchronous sampling times.
##### Key Capabilities
- **Temporal Slicing**: Supports server-side filtering to stream data within specific time windows (t >= start and t < end).
- **Peek-Ahead**: Provides the `next_timestamp()` method, allowing the system to inspect chronological order without consuming the record—a core requirement for the K-way merge sorting algorithm.
##### The Merge Algorithm
This class manages multiple internal `TopicDataStreamer` instances. On every iteration, it:
- **Peeks** at the next available timestamp from every active topic stream.
- **Selects** the topic currently holding the lowest absolute timestamp.
- **Yields** that specific record and advances only the "winning" topic stream.
Internal constructor for SequenceDataStreamer.
**Do not call this directly.** Internal library modules should use the `SequenceDataStreamer._connect()` factory.
Parameters:
| Name | Type | Description | Default |
| `sequence_name` | `str` | The name of the sequence being streamed. | *required* |
| `client` | `FlightClient` | The active FlightClient for remote operations. | *required* |
| `topic_readers` | `Dict[str, TopicDataStreamer]` | A dictionary mapping topic names to their respective `TopicDataStreamer` instances. | *required* |
### next_timestamp
```
next_timestamp()
```
Peeks at the timestamp of the next chronological measurement without consuming the record.
Returns:
| Type | Description |
| `Optional[int]` | The minimum timestamp (nanoseconds) found across all active topics, or `None` if all streams are exhausted. |
### close
```
close()
```
Gracefully terminates all underlying topic streams and releases allocated resources.
This method iterates through all active `TopicDataStreamer` instances, ensuring that each remote connection is closed and local memory buffers are cleared.
## mosaicolabs.handlers.TopicDataStreamer
```
TopicDataStreamer(*, client, state)
```
An iterator that streams ontology records from a single topic.
The `TopicDataStreamer` wraps a PyArrow Flight `DoGet` stream to fetch `RecordBatches` from the server and reconstruct individual `Message` objects. It is designed for efficient row-by-row iteration while providing peek-ahead capabilities for time-synchronized merging.
##### Key Capabilities
- **Temporal Slicing**: Supports server-side filtering to stream data within specific time windows (t >= start and t < end).
- **Peek-Ahead**: Provides the `next_timestamp()` method, allowing the system to inspect chronological order without consuming the record—a core requirement for the K-way merge sorting performed by the `SequenceDataStreamer`.
Internal constructor for TopicDataStreamer.
**Do not call this directly.** Internal library modules should use the `TopicDataStreamer._connect()` or `TopicDataStreamer._connect_from_ticket()` factory methods instead.
Parameters:
| Name | Type | Description | Default |
| `client` | `FlightClient` | The active FlightClient used for remote operations. | *required* |
| `state` | `_TopicReadState` | The internal state object managing the Arrow reader and peek buffers. | *required* |
### ontology_tag`property`
```
ontology_tag
```
The ontology tag associated with this streamer.
Returns:
| Type | Description |
| `str` | The ontology tag. |
### name
```
name()
```
The name of the topic associated with this streamer.
Returns:
| Type | Description |
| `str` | The name of the topic. |
### next_timestamp
```
next_timestamp()
```
Peeks at the timestamp of the next record without consuming it.
Returns:
| Type | Description |
| `Optional[int]` | The next timestamp in nanoseconds, or `None` if the stream is empty. |
Raises:
| Type | Description |
| `ValueError` | if the data streamer instance has been closed. |
### close
```
close()
```
Gracefully terminates the underlying Apache Arrow Flight stream and releases buffers.
---
# Writing Data
## mosaicolabs.handlers.config.WriterConfig`dataclass`
```
WriterConfig(max_batch_size_bytes, max_batch_size_records)
```
Configuration for common settings for Sequence and Topic writers.
This dataclass defines the operational parameters for data ingestion, controlling both the error recovery strategy and the performance-critical buffering logic used by the `SequenceWriter` and `TopicWriter`.
### max_batch_size_bytes`instance-attribute`
```
max_batch_size_bytes
```
The memory threshold in bytes before a data batch is flushed to the server.
When the internal buffer of a `TopicWriter` exceeds this value, it triggers a serialization and transmission event. Larger values increase throughput by reducing network overhead but require more client-side memory.
### max_batch_size_records`instance-attribute`
```
max_batch_size_records
```
The threshold in row (record) count before a data batch is flushed to the server.
A flush is triggered whenever **either** this record limit or the `max_batch_size_bytes` limit is reached, ensuring that data is transmitted regularly even for topics with very small individual records.
## mosaicolabs.handlers.SequenceWriter
```
SequenceWriter(*, sequence_name, client, metadata, config)
```
Bases: `_BaseSessionWriter`
Orchestrates the creation and data ingestion lifecycle of a Mosaico Sequence.
The `SequenceWriter` is the central controller for high-performance data writing. It manages the transition of a sequence through its lifecycle states: **Create** -> **Write** -> **Finalize**.
Internal constructor for SequenceWriter.
**Do not call this directly.** Users must call `MosaicoClient.sequence_create()` to obtain an initialized writer.
Parameters:
| Name | Type | Description | Default |
| `sequence_name` | `str` | Unique name for the new sequence. | *required* |
| `client` | `FlightClient` | The primary control FlightClient. | *required* |
| `metadata` | `dict[str, Any]` | User-defined metadata dictionary. | *required* |
| `config` | `SessionWriterConfig` | Operational configuration (e.g., error policies, batch sizes). | *required* |
### session_status`property`
```
session_status
```
Returns the current operational status of the session corresponding to this sequence write or update.
Returns:
| Type | Description |
| `SessionStatus` | The `SessionStatus`. |
### session_locator`property`
```
session_locator
```
Returns the locator of the session corresponding to this sequence write or update. The locator format is: '`sequence_name`:`session_identifier`'.
Returns:
| Type | Description |
| `str` | The locator of the session. |
### status`property`
```
status
```
Returns the current operational status of the sequence.
Returns:
| Type | Description |
| `SequenceStatus` | The `SequenceStatus`. |
### topic_writer_exists
```
topic_writer_exists(topic_name)
```
Checks if a `TopicWriter` has already been initialized for the given name.
Parameters:
| Name | Type | Description | Default |
| `topic_name` | `str` | The name of the topic to check. | *required* |
Returns:
| Type | Description |
| `bool` | True if the topic writer exists locally, False otherwise. |
### list_topic_writers
```
list_topic_writers()
```
Returns the list of all topic names currently managed by this writer.
### get_topic_writer
```
get_topic_writer(topic_name)
```
Retrieves an existing `TopicWriter` instance from the internal cache.
This method is particularly useful when ingesting data from unified recording formats where different sensor types (e.g., Vision, IMU, Odometry) are stored chronologically in a single stream or file.
In these scenarios, messages for various topics appear in an interleaved fashion. Using `get_topic_writer` allows the developer to:
- **Reuse Buffers:** Efficiently switch between writers for different sensor streams.
- **Ensure Data Ordering:** Maintain a consistent batching logic for each topic as you iterate through a mixed-content log.
- **Optimize Throughput:** Leverage Mosaico's background I/O by routing all data for a specific identifier through a single, persistent writer instance.
Parameters:
| Name | Type | Description | Default |
| `topic_name` | `str` | The unique name or identifier of the topic writer to retrieve. | *required* |
Returns:
| Type | Description |
| `Optional[TopicWriter]` | The `TopicWriter` instance if it has been previously initialized within this `SequenceWriter` context, otherwise `None`. |
### topic_create
```
topic_create(
topic_name, metadata, ontology_type, on_error=Raise
)
```
Creates a new topic within the active sequence.
Parameters:
| Name | Type | Description | Default |
| `topic_name` | `str` | The relative name of the new topic. | *required* |
| `metadata` | `dict[str, Any]` | Topic-specific user metadata. | *required* |
| `ontology_type` | `Type[Serializable]` | The `Serializable` data model class defining the topic's schema. | *required* |
| `on_error` | `TopicLevelErrorPolicy` | The error policy to use in the `TopicWriter`. | `Raise` |
Returns:
| Type | Description |
| `Optional[TopicWriter]` | A `TopicWriter` instance configured for parallel ingestion, or `None` if creation fails. |
Raises:
| Type | Description |
| `RuntimeError` | If called outside of a `with` block. |
## mosaicolabs.handlers.TopicWriter
```
TopicWriter(
*, topic_name, sequence_name, client, state, config
)
```
Manages a high-performance data stream for a single Mosaico topic.
The `TopicWriter` abstracts the complexity of the PyArrow Flight `DoPut` protocol, handling internal buffering, serialization, and network transmission. It accumulates records in memory and automatically flushes them to the server when configured batch limits—defined by either byte size or record count—are exceeded.
Internal constructor for TopicWriter.
**Do not call this directly.** Internal library modules should use the `_create()` factory. Users must call `SequenceWriter.topic_create()` to obtain an initialized writer.
Parameters:
| Name | Type | Description | Default |
| `topic_name` | `str` | The name of the specific topic. | *required* |
| `sequence_name` | `str` | The name of the parent sequence. | *required* |
| `client` | `FlightClient` | The FlightClient used for data transmission. | *required* |
| `state` | `_TopicWriteState` | The internal state object managing buffers and streams. | *required* |
| `config` | `TopicWriterConfig` | Operational configuration for batching and error handling. | *required* |
### name`property`
```
name
```
Returns the name of the topic
### last_error`property`
```
last_error
```
Returns the last cached error, if any. The value is reset after a new successful push
- `twriter` is a `TopicWriter` instance, created with `on_error=TopicLevelErrorPolicy.Ignore`
- **Important**: this check must be done outside the `with` block: any exception inside the context would exit the context prematurely.
### is_active`property`
```
is_active
```
Returns `True` if the writing stream is open and the writer accepts new messages.
### push
```
push(message)
```
Adds a new record to the internal write buffer.
Records are accumulated in memory. If a push triggers a batch limit, the buffer is automatically serialized and transmitted to the server.
Parameters:
| Name | Type | Description | Default |
| `message` | `Message` | A pre-constructed Message object. | *required* |
Raises:
| Type | Description |
| `Exception` | If a buffer flush fails during the operation. |
## mosaicolabs.handlers.SequenceUpdater
```
SequenceUpdater(*, sequence_name, client, config)
```
Bases: `_BaseSessionWriter`
Orchestrates the sequence update and related data ingestion lifecycle of a Mosaico Sequence.
The `SequenceUpdater` is the central controller for high-performance data writing.
Internal constructor for SequenceUpdater.
**Do not call this directly.** Users must call `SequenceHandler.update()` to obtain an initialized writer.
Parameters:
| Name | Type | Description | Default |
| `sequence_name` | `str` | Unique name for the new sequence. | *required* |
| `client` | `FlightClient` | The primary control FlightClient. | *required* |
| `config` | `SessionWriterConfig` | Operational configuration (e.g., error policies, batch sizes). | *required* |
### session_status`property`
```
session_status
```
Returns the current operational status of the session corresponding to this sequence write or update.
Returns:
| Type | Description |
| `SessionStatus` | The `SessionStatus`. |
### session_locator`property`
```
session_locator
```
Returns the locator of the session corresponding to this sequence write or update. The locator format is: '`sequence_name`:`session_identifier`'.
Returns:
| Type | Description |
| `str` | The locator of the session. |
### topic_writer_exists
```
topic_writer_exists(topic_name)
```
Checks if a `TopicWriter` has already been initialized for the given name.
Parameters:
| Name | Type | Description | Default |
| `topic_name` | `str` | The name of the topic to check. | *required* |
Returns:
| Type | Description |
| `bool` | True if the topic writer exists locally, False otherwise. |
### list_topic_writers
```
list_topic_writers()
```
Returns the list of all topic names currently managed by this writer.
### get_topic_writer
```
get_topic_writer(topic_name)
```
Retrieves an existing `TopicWriter` instance from the internal cache.
This method is particularly useful when ingesting data from unified recording formats where different sensor types (e.g., Vision, IMU, Odometry) are stored chronologically in a single stream or file.
In these scenarios, messages for various topics appear in an interleaved fashion. Using `get_topic_writer` allows the developer to:
- **Reuse Buffers:** Efficiently switch between writers for different sensor streams.
- **Ensure Data Ordering:** Maintain a consistent batching logic for each topic as you iterate through a mixed-content log.
- **Optimize Throughput:** Leverage Mosaico's background I/O by routing all data for a specific identifier through a single, persistent writer instance.
Parameters:
| Name | Type | Description | Default |
| `topic_name` | `str` | The unique name or identifier of the topic writer to retrieve. | *required* |
Returns:
| Type | Description |
| `Optional[TopicWriter]` | The `TopicWriter` instance if it has been previously initialized within this `SequenceWriter` context, otherwise `None`. |
### topic_create
```
topic_create(
topic_name, metadata, ontology_type, on_error=Raise
)
```
Creates a new topic within the active sequence.
Parameters:
| Name | Type | Description | Default |
| `topic_name` | `str` | The relative name of the new topic. | *required* |
| `metadata` | `dict[str, Any]` | Topic-specific user metadata. | *required* |
| `ontology_type` | `Type[Serializable]` | The `Serializable` data model class defining the topic's schema. | *required* |
| `on_error` | `TopicLevelErrorPolicy` | The error policy to use in the `TopicWriter`. | `Raise` |
Returns:
| Type | Description |
| `Optional[TopicWriter]` | A `TopicWriter` instance configured for parallel ingestion, or `None` if creation fails. |
Raises:
| Type | Description |
| `RuntimeError` | If called outside of a `with` block. |
---
# Base Models and Mixins
## mosaicolabs.models.MosaicoType
Collection of `Annotated` type aliases mapping Python primitives to their PyArrow counterparts.
Each class attribute is an `Annotated[PythonType, pa.DataType]` alias. When used as a field annotation in a `Serializable` subclass, the embedded `pa.DataType` is extracted by `_build_ontology_struct` at class-definition time to derive the `__msco_pyarrow_struct__` automatically — no manual schema declaration required.
For Arrow types not covered by the built-in aliases, fall back to a raw `Annotated[T, pa.SomeType()]` annotation; the schema builder resolves it transparently.
Scalar aliases:
| Alias | Python type | Arrow type |
| `MosaicoType.uint8` | `int` | `pa.uint8()` |
| `MosaicoType.int8` | `int` | `pa.int8()` |
| `MosaicoType.uint16` | `int` | `pa.uint16()` |
| `MosaicoType.int16` | `int` | `pa.int16()` |
| `MosaicoType.uint32` | `int` | `pa.uint32()` |
| `MosaicoType.int32` | `int` | `pa.int32()` |
| `MosaicoType.uint64` | `int` | `pa.uint64()` |
| `MosaicoType.int64` | `int` | `pa.int64()` |
| `MosaicoType.float16` | `float` | `pa.float16()` |
| `MosaicoType.float32` | `float` | `pa.float32()` |
| `MosaicoType.float64` | `float` | `pa.float64()` |
| `MosaicoType.bool` | `bool` | `pa.bool_()` |
| `MosaicoType.string` | `str` | `pa.string()` |
| `MosaicoType.large_string` | `str` | `pa.large_string()` |
| `MosaicoType.binary` | `bytes` | `pa.binary()` |
| `MosaicoType.large_binary` | `bytes` | `pa.large_binary()` |
### annotate`staticmethod`
```
annotate(py_type, pa_type)
```
Creates a type metadata binding between a Python type and a Pyarrow DataType.
This method uses Python's `Annotated` to wrap a standard type with specific Pyarrow schema information. This allows Pydantic models to correctly serialize and deserialize data into the desired Pyarrow format.
Parameters:
| Name | Type | Description | Default |
| `py_type` | `Type` | The native Python type (e.g., int, str, or a Pydantic model). | *required* |
| `pa_type` | `DataType` | The corresponding Pyarrow data type or logical type. | *required* |
Returns:
| Name | Type | Description |
| `Annotated` | `Annotated` | A type hint containing the Python type and Pyarrow metadata. |
### list_`staticmethod`
```
list_(source_type, list_size=None)
```
Build an `Annotated[list, pa.list_(...)]` type alias for list fields.
Accepts either a `MosaicoType` alias (i.e. any type carrying `__metadata__` with a `pa.DataType`) or a raw Python primitive present in `BASE_MAPPING` (`int`, `float`, `str`, `bool`, `bytes`).
Parameters:
| Name | Type | Description | Default |
| `source_type` | `Any` | A `MosaicoType` alias or a raw Python primitive type whose PyArrow equivalent is defined in `BASE_MAPPING`. | *required* |
| `list_size` | `Optional[int]` | If provided, produces a fixed-size Arrow list (`pa.list_(type, list_size)`). If `None`, produces a variable-length Arrow list (`pa.list_(type)`). | `None` |
Returns:
| Type | Description |
| `Any` | An `Annotated[list, pa.ListType]` alias ready to be used as a |
| `Any` | field annotation in a `Serializable` subclass. |
Raises:
| Type | Description |
| `ValueError` | If `source_type` does not resolve to a valid `pa.DataType`. |
### matrix`staticmethod`
```
matrix(source_type, rows=None, cols=None)
```
Build an `Annotated[list, pa.list_(...)]` type alias for 2D matrix fields.
Composes two nested `MosaicoType.list_()` calls to represent a matrix of shape `(rows, cols)`. Both dimensions are optional: if `None`, the dimension is variable-length; if provided, it is fixed-size.
Parameters:
| Name | Type | Description | Default |
| `source_type` | `Any` | A `MosaicoType` alias or a raw Python primitive type whose PyArrow equivalent is defined in `BASE_MAPPING`. | *required* |
| `rows` | `Optional[int]` | If provided, the outer list is fixed-size. If `None`, the outer list is variable-length. | `None` |
| `cols` | `Optional[int]` | If provided, the inner list is fixed-size. If `None`, the inner list is variable-length. | `None` |
Returns:
| Type | Description |
| `Annotated` | An `Annotated[list, pa.ListType]` alias representing a 2D matrix, ready to be used as a field annotation in a `Serializable` subclass. |
Raises:
| Type | Description |
| `ValueError` | If `source_type` does not resolve to a valid `pa.DataType`. |
### tensor3d`staticmethod`
```
tensor3d(source_type, depth=None, rows=None, cols=None)
```
Build an `Annotated[list, pa.list_(...)]` type alias for 3D tensor fields.
Composes `MosaicoType.matrix()` and `MosaicoType.list_()` to represent a tensor of shape `(depth, rows, cols)`. All dimensions are optional: if `None`, the dimension is variable-length; if provided, it is fixed-size.
Parameters:
| Name | Type | Description | Default |
| `source_type` | `Any` | A `MosaicoType` alias or a raw Python primitive type whose PyArrow equivalent is defined in `BASE_MAPPING`. | *required* |
| `rows` | `Optional[int]` | If provided, the matrix rows are fixed-size. If `None`, the matrix rows are variable-length. | `None` |
| `cols` | `Optional[int]` | If provided, the matrix cols are fixed-size. If `None`, the matrix cols are variable-length. | `None` |
| `depth` | `Optional[int]` | If provided, the outer list is fixed-size. If `None`, the outer list is variable-length. | `None` |
Returns:
| Type | Description |
| `Annotated` | An `Annotated[list, pa.ListType]` alias representing a 3D tensor, ready to be used as a field annotation in a `Serializable` subclass. |
Raises:
| Type | Description |
| `ValueError` | If `source_type` does not resolve to a valid `pa.DataType`. |
## mosaicolabs.models.types.MosaicoField
```
MosaicoField(
nullable=False, default=..., description=None, **kwargs
)
```
Factory for Pydantic `FieldInfo` instances carrying Mosaico-specific Arrow metadata.
Acts as a drop-in replacement for `pydantic.Field` within `Serializable` subclasses. The `nullable` flag is stored in `json_schema_extra` and consumed by `_build_ontology_struct` when deriving the `__msco_pyarrow_struct__` at class-definition time.
Parameters:
| Name | Type | Description | Default |
| `nullable` | `bool` | Whether the corresponding Arrow field should be declared as nullable in the generated `pa.struct`. Defaults to `False`. | `False` |
| `default` | `Any | EllipsisType` | Default value for the field. Use `...` (the default) to mark the field as required. Any other value makes the field optional and sets its fallback. | `...` |
| `description` | `Optional[str]` | Human-readable description of the field, forwarded to Pydantic and surfaced in the JSON Schema output. | `None` |
| `**kwargs` | `Any` | Additional keyword arguments forwarded verbatim to `pydantic.Field`. | `{}` |
Returns:
| Type | Description |
| `Any` | A `pydantic.FieldInfo` instance with Mosaico nullability metadata |
| `Any` | attached. |
## mosaicolabs.models.Message
Bases: `BaseModel`
The universal transport envelope for Mosaico data.
The `Message` class wraps a polymorphic `Serializable` payload with middleware metadata, such as recording timestamps and headers.
Attributes:
| Name | Type | Description |
| `timestamp_ns` | `int` | Sensor acquisition timestamp in nanoseconds (event time). This represents the time at which the underlying physical event occurred — i.e., when the sensor actually captured or generated the data. |
| `data` | `Serializable` | The actual ontology data payload (e.g., an IMU or GPS instance). |
| `recording_timestamp_ns` | `Optional[int]` | Ingestion timestamp in nanoseconds (record time). This represents the time at which the message was received and persisted by the recording system (e.g., rosbag, parquet writer, logging pipeline, or database). |
| `frame_id` | `Optional[str]` | A string identifier for the coordinate frame (spatial context). |
| `sequence_id` | `Optional[int]` | An optional sequence ID, primarily used for legacy tracking. |
##### Querying with the **`.Q` Proxy**
When constructing a `QueryOntologyCatalog`, the `Message` attributes are fully queryable.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.timestamp_ns` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `.Q.recording_timestamp_ns` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `.Q.frame_id` | `String` | `.eq()`, `.match()`, `.in_()`, `.lt()`, `.gt()`, `.leq()`, `.geq()` |
| `.Q.sequence_id` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### data`instance-attribute`
```
data
```
The actual ontology data payload (e.g., an IMU or GPS instance).
### timestamp_ns`instance-attribute`
```
timestamp_ns
```
Sensor acquisition timestamp in nanoseconds (event time).
This represents the time at which the underlying physical event occurred — i.e., when the sensor actually captured or generated the data.
Ideally, this value originates from:
- the sensor hardware clock, or
- a driver-converted hardware timestamp expressed in system time.
This is the authoritative time describing *when the data happened* and should be used for:
- synchronization across sensors
- state estimation and sensor fusion
- temporal alignment
- latency analysis (when compared to recording time)
###### Querying with the **`.Q` Proxy**
The timestamp_ns field is queryable using the `.Q` proxy.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.timestamp_ns` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder represents any Mosaico ontology class (e.g., `IMU`, `GPS`, `Floating64`) or any custom user-defined class that is a subclass of `Serializable`.
### recording_timestamp_ns`class-attribute``instance-attribute`
```
recording_timestamp_ns = None
```
Ingestion timestamp in nanoseconds (record time).
This represents the time at which this message was received and persisted by the recording system (e.g., rosbag, parquet writer, logging pipeline, or database).
This timestamp reflects infrastructure timing and may include:
- transport delay
- middleware delay
- serialization/deserialization delay
- scheduling delay
It does NOT represent when the sensor measurement occurred.
Typical usage:
- latency measurement (recording_timestamp_ns - timestamp_ns)
- debugging transport or pipeline delays
- ordering messages by arrival time
If not explicitly set, this value may be None.
###### Querying with the **`.Q` Proxy**
The recording_timestamp_ns field is queryable using the `.Q` proxy.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.recording_timestamp_ns` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder represents any Mosaico ontology class (e.g., `IMU`, `GPS`, `Floating64`) or any custom user-defined class that is a subclass of `Serializable`
### frame_id`class-attribute``instance-attribute`
```
frame_id = None
```
A string identifier for the coordinate frame (spatial context).
###### Querying with the **`.Q` Proxy**
The frame_id field is queryable using the `.Q` proxy.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.frame_id` | `String` | `.eq()`, `.match()`, `.in_()`, `.lt()`, `.gt()`, `.leq()`, `.geq()` |
The `` placeholder represents any Mosaico ontology class (e.g., `IMU`, `GPS`, `Floating64`) or any custom user-defined class that is a subclass of `Serializable`
### sequence_id`class-attribute``instance-attribute`
```
sequence_id = None
```
An optional sequence ID, primarily used for legacy tracking.
###### Querying with the **`.Q` Proxy**
The sequence_id field is queryable using the `.Q` proxy.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.sequence_id` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder represents any Mosaico ontology class (e.g., `IMU`, `GPS`, `Floating64`) or any custom user-defined class that is a subclass of `Serializable`
### model_post_init
```
model_post_init(context)
```
Validates the message structure after initialization.
Ensures that there are no field name collisions between the envelope (e.g., `timestamp_ns`) and the data payload.
### ontology_type
```
ontology_type()
```
Retrieves the class type of the ontology object stored in the `data` field.
### ontology_tag
```
ontology_tag()
```
Returns the unique ontology tag name associated with the object in the data field.
### get_data
```
get_data(target_type)
```
Safe, type-hinted accessor for the data payload.
Parameters:
| Name | Type | Description | Default |
| `target_type` | `Type[TSerializable]` | The expected `Serializable` subclass type. | *required* |
Returns:
| Type | Description |
| `Optional[TSerializable]` | The data object cast to the requested type. |
Raises:
| Type | Description |
| `TypeError` | If the actual data type does not match the requested `target_type`. |
### from_dataframe_row`staticmethod`
```
from_dataframe_row(
row, topic_name, timestamp_column_name="timestamp_ns"
)
```
Reconstructs a `Message` object from a flattened DataFrame row.
In the Mosaico Data Platform, DataFrames represent topics using a nested naming convention: `{topic}.{tag}.{field}`. This method performs **Smart Reconstruction** by:
- **Topic Validation**: Verifying if any columns associated with the `topic_name` exist in the row.
- **Tag Inference**: Inspecting the column headers to automatically determine the original ontology tag (e.g., `"imu"`).
- **Data Extraction**: Stripping prefixes and re-nesting the flat columns into their original dictionary structures.
- **Type Casting**: Re-instantiating the specific `Serializable` subclass and wrapping it in a `Message` envelope.
Parameters:
| Name | Type | Description | Default |
| `row` | `Series` | A single row from a Pandas DataFrame, representing a point in time across one or more topics. | *required* |
| `topic_name` | `str` | The name of the specific topic to extract from the row. | *required* |
| `timestamp_column_name` | `str` | The name of the column containing the timestamp. | `'timestamp_ns'` |
Returns:
| Type | Description |
| `Optional[Message]` | A reconstructed `Message` instance containing the typed ontology data, or `None` if the topic is not present or the data is incomplete. |
## mosaicolabs.models.Serializable
Bases: `BaseModel`, `_QueryProxyMixin`
The base class for all Mosaico ontology data payloads.
This class serves as the root for every sensor and data type in the Mosaico ecosystem. By inheriting from `Serializable`, data models are automatically compatible with the platform's storage, querying, and serialization engines.
##### Dynamic Attributes Injection
When you define a subclass, several key attributes are automatically managed or required. Understanding these is essential for customizing how your data is treated by the platform:
-
**`__serialization_format__`**: Determines the batching strategy and storage optimization.
- **Role**: It tells the `SequenceWriter` whether to flush data based on byte size (optimal for heavy data like `Images`) or record count (optimal for light telemetry like `IMU`).
- **Default**: `SerializationFormat.Default`.
-
**`__ontology_tag__`**: The unique string identifier for the class (e.g., `"imu"`, `"gps_raw"`).
- **Role**: This tag is used in the global registry to reconstruct objects from raw platform data.
- **Generation**: If not explicitly provided, it is auto-generated by converting the class name from `CamelCase` to `snake_case`.
-
**`__class_type__`**: A reference to the concrete class itself.
- **Role**: Injected during initialization to facilitate polymorphic instantiation and safe type-checking when extracting data from a `Message`.
##### Requirements for Custom Ontologies
To create a valid custom ontology, your subclass must:
- Inherit from `Serializable`.
- Define the attributes using `MosaicoType` and `MosaicoField`
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.models.CovarianceMixin
Bases: `BaseModel`
A mixin that adds uncertainty fields (`covariance` and `covariance_type`) to data models.
This is particularly useful for complex sensors like IMUs, Odometry, or GNSS receivers that provide multidimensional uncertainty matrices along with their primary measurements.
##### Dynamic Schema Injection
This mixin uses the `__init_subclass__` hook to perform a **Schema Append** operation:
- It inspects the child class's existing `__msco_pyarrow_struct__`.
- It appends a `covariance` and `covariance_type` fields.
- It reconstructs the final `pa.struct` for the class.
Attributes:
| Name | Type | Description |
| `covariance` | `Optional[list_(float64)]` | Optional list of 64-bit floats representing the flattened matrix. |
| `covariance_type` | `Optional[int16]` | Optional 16-bit integer representing the covariance enum. |
##### Querying with the **`.Q` Proxy**
When constructing a `QueryOntologyCatalog`, the class fields are queryable across any model inheriting from this mixin, according to the following table:
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.covariance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `.Q.covariance` | ***Non-Queryable*** | None |
### covariance`class-attribute``instance-attribute`
```
covariance = MosaicoField(
default=None,
nullable=True,
description="The covariance matrix (flattened) of the data.",
)
```
Optional list of 64-bit floats representing the flattened matrix.
###### Querying with the **`.Q` Proxy**
### covariance_type`class-attribute``instance-attribute`
```
covariance_type = MosaicoField(
default=None,
nullable=True,
description="Enum integer representing the covariance parameterization.",
)
```
Optional 16-bit integer representing the covariance enum.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional covariance type attribute.
###### Querying with the **`.Q` Proxy**
The `covariance_type` field is fully queryable via the **`.Q` Proxy**. The `` placeholder in the path represents any Mosaico class that exposes covariance information, either directly or through its internal fields.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.covariance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `CovarianceMixin` is integrated into your data structure:
- **Direct Inheritance**: Represents any class (e.g., `Vector3d`, `Quaternion`) that inherits directly from `CovarianceMixin`.
- **Composition (Nested Fields)**: When a complex model (like `IMU`) contains fields that are themselves covariance-aware, the proxy allows you to "drill down" to that specific attribute. For example, since `IMU.acceleration` is a `Vector3d`, you access its covariance type via `IMU.Q.acceleration.covariance_type`.
## mosaicolabs.models.VarianceMixin
Bases: `BaseModel`
A mixin that adds 1-dimensional uncertainty fields (`variance` and `variance_type`).
Recommended for sensors with scalar uncertain outputs, such as ultrasonic rangefinders, temperature sensors, or individual encoders.
##### Dynamic Schema Injection
This mixin uses the `__init_subclass__` hook to perform a **Schema Append** operation:
- It inspects the child class's existing `__msco_pyarrow_struct__`.
- It appends a `variance` and `variance_type` field.
- It reconstructs the final `pa.struct` for the class.
##### Querying with the **`.Q` Proxy**
When constructing a `QueryOntologyCatalog`, the class fields are queryable across any model inheriting from this mixin, according to the following table:
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.variance` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `.Q.variance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### variance`class-attribute``instance-attribute`
```
variance = MosaicoField(
default=None,
nullable=True,
description="The variacne of the data.",
)
```
Optional 64-bit float representing the variance of the data.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional variance attribute.
###### Querying with the **`.Q` Proxy**
The `variance` field is queryable with the **`.Q` Proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.variance` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `VarianceMixin` is integrated into the data structure:
- **Direct Inheritance**: Used for classes like `Pressure` or `Temperature` that inherit directly from `VarianceMixin` to represent 1D uncertainty.
- **Composition (Nested Access)**: If a complex model contains a field that is a subclass of `VarianceMixin`, the proxy allows you to traverse the hierarchy to that specific attribute.
### variance_type`class-attribute``instance-attribute`
```
variance_type = MosaicoField(
default=None,
nullable=True,
description="Enum integer representing the variance parameterization.",
)
```
Optional 16-bit integer representing the variance parameterization.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional covariance type attribute.
###### Querying with the **`.Q` Proxy**
The `variance_type` field is fully queryable via the **`.Q` Proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.variance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `VarianceMixin` is integrated into the data structure:
- **Direct Inheritance**: Used for classes like `Pressure` or `Temperature` that inherit directly from `VarianceMixin` to represent 1D uncertainty.
- **Composition (Nested Access)**: If a complex model contains a field that is a subclass of `VarianceMixin`, the proxy allows you to traverse the hierarchy to that specific attribute.
## mosaicolabs.models.BaseModel
Bases: `BaseModel`
The root base class for SDK data models.
It inherits from `pydantic.BaseModel` to provide runtime type checking and initialization logic. It adds a hook for defining the corresponding PyArrow structure (`__msco_pyarrow_struct__`), enabling the SDK to auto-generate Flight schemas.
---
# Data Types
## mosaicolabs.models.data.base_types
This module provides specialized wrapper classes for standard Python primitive types, including Integers, Floating-point numbers, Booleans, and Strings.
In the Mosaico ecosystem, raw primitives cannot be transmitted directly because the platform requires structured metadata and explicit serialization schemas. These wrappers elevate basic data types to "first-class citizens" of the messaging system by inheriting from `Serializable`.
**Key Features:** * **Explicit Serialization**: Each class defines a precise `pyarrow.StructType` schema, ensuring consistent bit-width (e.g., 8-bit vs 64-bit) across the entire data platform. * **Registry Integration**: Wrapped types are automatically registered in the Mosaico ontology, allowing them to be used in platform-side Queries.
### Integer8
Bases: `Serializable`
A wrapper for a signed 8-bit integer.
Attributes:
| Name | Type | Description |
| `data` | `int8` | The underlying 8-bit integer value. |
###### Querying with the **`.Q` Proxy**
The fields of this class are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### data`class-attribute``instance-attribute`
```
data = MosaicoField(description='8-bit Integer data.')
```
The underlying integer value.
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `Integer8.Q.data` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### Integer16
Bases: `Serializable`
A wrapper for a signed 16-bit integer.
Attributes:
| Name | Type | Description |
| `data` | `int16` | The underlying 16-bit integer value. |
###### Querying with the **`.Q` Proxy**
The fields of this class are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### data`class-attribute``instance-attribute`
```
data = MosaicoField(description='16-bit Integer data.')
```
The underlying integer value.
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `Integer16.Q.data` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### Integer32
Bases: `Serializable`
A wrapper for a signed 32-bit integer.
Attributes:
| Name | Type | Description |
| `data` | `int32` | The underlying 32-bit integer value. |
###### Querying with the **`.Q` Proxy**
The fields of this class are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### data`class-attribute``instance-attribute`
```
data = MosaicoField(description='32-bit Integer data.')
```
The underlying integer value.
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `Integer32.Q.data` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### Integer64
Bases: `Serializable`
A wrapper for a signed 64-bit integer.
Attributes:
| Name | Type | Description |
| `data` | `int64` | The underlying 64-bit integer value. |
###### Querying with the **`.Q` Proxy**
The fields of this class are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### data`class-attribute``instance-attribute`
```
data = MosaicoField(description='64-bit Integer data.')
```
The underlying integer value.
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `Integer64.Q.data` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### Unsigned8
Bases: `Serializable`
A wrapper for an unsigned 8-bit integer.
Attributes:
| Name | Type | Description |
| `data` | `uint8` | The underlying unsigned 8-bit integer value. |
Raises:
| Type | Description |
| `ValueError` | If `data` is initialized with a negative value. |
###### Querying with the **`.Q` Proxy**
The fields of this class are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### data`class-attribute``instance-attribute`
```
data = MosaicoField(description='8-bit Unsigned data.')
```
The underlying unsigned integer value.
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `Unsigned8.Q.data` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### model_post_init
```
model_post_init(context)
```
Validates that the input data is non-negative.
Raises:
| Type | Description |
| `ValueError` | If data < 0. |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### Unsigned16
Bases: `Serializable`
A wrapper for an unsigned 16-bit integer.
Attributes:
| Name | Type | Description |
| `data` | `uint16` | The underlying unsigned 16-bit integer value. |
Raises:
| Type | Description |
| `ValueError` | If `data` is initialized with a negative value. |
###### Querying with the **`.Q` Proxy**
The fields of this class are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### data`class-attribute``instance-attribute`
```
data = MosaicoField(description='16-bit Unsigned data.')
```
The underlying unsigned integer value.
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `Unsigned16.Q.data` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### model_post_init
```
model_post_init(context)
```
Validates that the input data is non-negative.
Raises:
| Type | Description |
| `ValueError` | If data < 0. |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### Unsigned32
Bases: `Serializable`
A wrapper for an unsigned 32-bit integer.
Attributes:
| Name | Type | Description |
| `data` | `uint32` | The underlying unsigned 32-bit integer value. |
Raises:
| Type | Description |
| `ValueError` | If `data` is initialized with a negative value. |
###### Querying with the **`.Q` Proxy**
The fields of this class are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### data`class-attribute``instance-attribute`
```
data = MosaicoField(description='32-bit Unsigned data.')
```
The underlying unsigned integer value.
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `Unsigned32.Q.data` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### model_post_init
```
model_post_init(context)
```
Validates that the input data is non-negative.
Raises:
| Type | Description |
| `ValueError` | If data < 0. |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### Unsigned64
Bases: `Serializable`
A wrapper for an unsigned 64-bit integer.
Attributes:
| Name | Type | Description |
| `data` | `uint64` | The underlying unsigned 64-bit integer value. |
Raises:
| Type | Description |
| `ValueError` | If `data` is initialized with a negative value. |
###### Querying with the **`.Q` Proxy**
The fields of this class are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### data`class-attribute``instance-attribute`
```
data = MosaicoField(description='64-bit Unsigned data.')
```
The underlying unsigned integer value.
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `Unsigned64.Q.data` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### model_post_init
```
model_post_init(context)
```
Validates that the input data is non-negative.
Raises:
| Type | Description |
| `ValueError` | If data < 0. |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### Floating16
Bases: `Serializable`
A wrapper for a 16-bit single-precision floating-point number.
Attributes:
| Name | Type | Description |
| `data` | `float16` | The underlying single-precision float. |
###### Querying with the **`.Q` Proxy**
The fields of this class are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### data`class-attribute``instance-attribute`
```
data = MosaicoField(
description="16-bit Floating-point data."
)
```
The underlying single-precision float.
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `Floating16.Q.data` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### Floating32
Bases: `Serializable`
A wrapper for a 32-bit single-precision floating-point number.
Attributes:
| Name | Type | Description |
| `data` | `float32` | The underlying single-precision float. |
###### Querying with the **`.Q` Proxy**
The fields of this class are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### data`class-attribute``instance-attribute`
```
data = MosaicoField(
description="32-bit Floating-point data."
)
```
The underlying single-precision float.
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `Floating32.Q.data` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### Floating64
Bases: `Serializable`
A wrapper for a 64-bit single-precision floating-point number.
Attributes:
| Name | Type | Description |
| `data` | `float64` | The underlying single-precision float. |
###### Querying with the **`.Q` Proxy**
The fields of this class are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### data`class-attribute``instance-attribute`
```
data = MosaicoField(
description="64-bit Floating-point data."
)
```
The underlying single-precision float.
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `Floating64.Q.data` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### Boolean
Bases: `Serializable`
A wrapper for a standard boolean value.
Attributes:
| Name | Type | Description |
| `data` | `bool` | The underlying boolean value. |
###### Querying with the **`.Q` Proxy**
The fields of this class are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### data`class-attribute``instance-attribute`
```
data = MosaicoField(description='Boolean data.')
```
The underlying boolean value.
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `Boolean.Q.data` | `Bool` | `.eq()` |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### String
Bases: `Serializable`
A wrapper for a standard UTF-8 encoded string.
Attributes:
| Name | Type | Description |
| `data` | `string` | The underlying string data. |
###### Querying with the **`.Q` Proxy**
The fields of this class are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### data`class-attribute``instance-attribute`
```
data = MosaicoField(description='String data.')
```
The underlying string data.
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `String.Q.data` | `String` | `.eq()`, `.match()`, `.in_()`, `.lt()`, `.gt()`, `.leq()`, `.geq()` |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### LargeString
Bases: `Serializable`
A wrapper for a Large UTF-8 encoded string.
Use this class when string data is expected to exceed 2GB in size, necessitating the use of 64-bit offsets in the underlying PyArrow implementation.
Attributes:
| Name | Type | Description |
| `data` | `large_string` | The underlying large string data. |
###### Querying with the **`.Q` Proxy**
The fields of this class are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### data`class-attribute``instance-attribute`
```
data = MosaicoField(description='Large string data.')
```
The underlying large string data.
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `LargeString.Q.data` | `String` | `.eq()`, `.match()`, `.in_()`, `.lt()`, `.gt()`, `.leq()`, `.geq()` |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.models.data.ROI
Bases: `Serializable`
Represents a rectangular Region of Interest (ROI) within a 2D coordinate system.
This class is primarily used in imaging and computer vision pipelines to define sub-windows for processing or rectification.
Attributes:
| Name | Type | Description |
| `offset` | `Vector2d` | A `Vector2d` representing the top-left (leftmost, topmost) pixel coordinates of the ROI. |
| `height` | `uint32` | The vertical extent of the ROI in pixels. |
| `width` | `uint32` | The horizontal extent of the ROI in pixels. |
| `do_rectify` | `Optional[bool]` | Optional flag; `True` if a sub-window is captured and requires rectification. |
##### Querying with the **`.Q` Proxy**
This class fields are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
### offset`class-attribute``instance-attribute`
```
offset = MosaicoField(
description="(Leftmost, Rightmost) pixels of the ROI."
)
```
The top-left pixel coordinates of the ROI.
###### Querying with the **`.Q` Proxy**
Offset components are queryable through the `offset` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `ROI.Q.offset.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `ROI.Q.offset.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### height`class-attribute``instance-attribute`
```
height = MosaicoField(
description="Height pixel of the ROI."
)
```
Height of the ROI in pixels.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `ROI.Q.height` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### width`class-attribute``instance-attribute`
```
width = MosaicoField(description='Width pixel of the ROI.')
```
Width of the ROI in pixels.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `ROI.Q.width` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### do_rectify`class-attribute``instance-attribute`
```
do_rectify = MosaicoField(
default=None,
description="False if the full image is captured (ROI not used) and True if a subwindow is captured (ROI used) (optional). False if Null",
)
```
Flag indicating if the ROI requires rectification.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `ROI.Q.do_rectify` | `Boolean` | `.eq()` |
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
---
# Futures Models
## mosaicolabs.models.futures.laser._LaserScanBase
Bases: `BaseModel`
Internal generic base model shared by laser scan ontologies.
Encodes the scan geometry, timing metadata, and range and intensity arrays that are common to both single-return and multi-echo laser scanners.
**This class is not intended to be instantiated directly**. Use one of the concrete subclasses: `LaserScan` or `MultiEchoLaserScan`.
Attributes:
| Name | Type | Description |
| `angle_min` | `float32` | Start angle of the scan in radians. |
| `angle_max` | `float32` | End angle of the scan in radians. |
| `angle_increment` | `float32` | Angular step between consecutive beams in radians. |
| `time_increment` | `float32` | Time elapsed between consecutive beam measurements in seconds. |
| `scan_time` | `float32` | Total duration of one full scan in seconds. |
| `range_min` | `float32` | Minimum valid range value in meters; measurements below this threshold should be discarded. |
| `range_max` | `float32` | Maximum valid range value in meters; measurements above this threshold should be discarded. |
| `ranges` | `float32` | Range measurements for each beam. Shape depends on `T`. |
| `intensities` | `float32` | Intensity measurements for each beam, co-indexed with `ranges` (optional). Shape depends on `T`. |
##### Querying with the **`.Q` Proxy**
Scalar fields on this model are fully queryable via the **`.Q` proxy**. List-typed fields (`ranges`, `intensities`) are **not queryable**.
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.angle_min` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `LaserScan.Q.angle_max` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `LaserScan.Q.angle_increment` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `LaserScan.Q.time_increment` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `LaserScan.Q.scan_time` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `LaserScan.Q.range_min` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `LaserScan.Q.range_max` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### angle_min`class-attribute``instance-attribute`
```
angle_min = MosaicoField(
description="start angle of the scan in rad."
)
```
Start angle of the scan in radians.
Defines the angular position of the first beam in the sweep.Together with `angle_max` and `angle_increment`, it fully characterises the angular coverage of the scan.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.angle_min` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### angle_max`class-attribute``instance-attribute`
```
angle_max = MosaicoField(
description="end angle of the scan in rad."
)
```
End angle of the scan in radians.
Defines the angular position of the last beam in the sweep. The total field of view of the scanner is `angle_max - angle_min`.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.angle_max` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### angle_increment`class-attribute``instance-attribute`
```
angle_increment = MosaicoField(
description="angular distance between measurements in rad."
)
```
Angular step between consecutive beams in radians.
The number of beams in a sweep can be derived as `round((angle_max - angle_min) / angle_increment) + 1`. A negative value indicates a clockwise scan direction.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.angle_increment` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### time_increment`class-attribute``instance-attribute`
```
time_increment = MosaicoField(
description="time between measurements in seconds."
)
```
Time elapsed between consecutive beam measurements, in seconds.
If the scanner is moving, this will be used in interpoling position of 3D points.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.time_increment` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### scan_time`class-attribute``instance-attribute`
```
scan_time = MosaicoField(
description="time between scans in seconds."
)
```
Time between scans in seconds.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.scan_time` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### range_min`class-attribute``instance-attribute`
```
range_min = MosaicoField(
description="minimum range value in meters."
)
```
Minimum valid range value, in meters.
Measurements strictly below this threshold are outside the sensor's reliable operating range and should be discarded or treated as invalid during downstream processing.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.range_min` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### range_max`class-attribute``instance-attribute`
```
range_max = MosaicoField(
description="maximum range value in meters."
)
```
Maximum valid range value, in meters.
Measurements strictly above this threshold exceed the sensor's maximum detection distance and should be discarded or treated as invalid during downstream processing.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.range_max` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
## mosaicolabs.models.futures.LaserScan
Bases: `_LaserScanBase`, `Serializable`
Single-return 2D laser scan data.
This model represents one sweep of a single-return laser range finder. Each beam yields exactly one range measurement, corresponding to the strongest or first detected echo.
`ranges` and `intensities` are flat `List[float]` whose *i*-th element corresponds to the beam at angular position `angle_min + i * angle_increment`.
Attributes:
| Name | Type | Description |
| `angle_min` | `float32` | Start angle of the scan in radians. |
| `angle_max` | `float32` | End angle of the scan in radians. |
| `angle_increment` | `float32` | Angular step between consecutive beams in radians. |
| `time_increment` | `float32` | Time between consecutive beam measurements in seconds. |
| `scan_time` | `float32` | Total duration of one full scan in seconds. |
| `range_min` | `float32` | Minimum valid range threshold in meters. |
| `range_max` | `float32` | Maximum valid range threshold in meters. |
| `ranges` | `SingleRange` | Measured distance per beam in meters. |
| `intensities` | `Optional[SingleRange]` | Signal amplitude per beam (optional). |
##### Querying with the **`.Q` Proxy**
Scalar fields are fully queryable via the **`.Q` proxy**. `ranges` and `intensities` are **not queryable**.
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.angle_min` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `LaserScan.Q.angle_max` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `LaserScan.Q.angle_increment` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `LaserScan.Q.time_increment` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `LaserScan.Q.scan_time` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `LaserScan.Q.range_min` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `LaserScan.Q.range_max` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### angle_min`class-attribute``instance-attribute`
```
angle_min = MosaicoField(
description="start angle of the scan in rad."
)
```
Start angle of the scan in radians.
Defines the angular position of the first beam in the sweep.Together with `angle_max` and `angle_increment`, it fully characterises the angular coverage of the scan.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.angle_min` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### angle_max`class-attribute``instance-attribute`
```
angle_max = MosaicoField(
description="end angle of the scan in rad."
)
```
End angle of the scan in radians.
Defines the angular position of the last beam in the sweep. The total field of view of the scanner is `angle_max - angle_min`.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.angle_max` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### angle_increment`class-attribute``instance-attribute`
```
angle_increment = MosaicoField(
description="angular distance between measurements in rad."
)
```
Angular step between consecutive beams in radians.
The number of beams in a sweep can be derived as `round((angle_max - angle_min) / angle_increment) + 1`. A negative value indicates a clockwise scan direction.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.angle_increment` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### time_increment`class-attribute``instance-attribute`
```
time_increment = MosaicoField(
description="time between measurements in seconds."
)
```
Time elapsed between consecutive beam measurements, in seconds.
If the scanner is moving, this will be used in interpoling position of 3D points.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.time_increment` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### scan_time`class-attribute``instance-attribute`
```
scan_time = MosaicoField(
description="time between scans in seconds."
)
```
Time between scans in seconds.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.scan_time` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### range_min`class-attribute``instance-attribute`
```
range_min = MosaicoField(
description="minimum range value in meters."
)
```
Minimum valid range value, in meters.
Measurements strictly below this threshold are outside the sensor's reliable operating range and should be discarded or treated as invalid during downstream processing.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.range_min` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### range_max`class-attribute``instance-attribute`
```
range_max = MosaicoField(
description="maximum range value in meters."
)
```
Maximum valid range value, in meters.
Measurements strictly above this threshold exceed the sensor's maximum detection distance and should be discarded or treated as invalid during downstream processing.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.range_max` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### ranges`class-attribute``instance-attribute`
```
ranges = MosaicoField(
description="range data in meters. Ranges need to be between range min and max otherwise discarded."
)
```
Range measurements for each beam.
A flat list of `float` values, one per beam, representing the measured distance in meters.
Values outside the `[range_min, range_max]` interval should be considered invalid.
### intensities`class-attribute``instance-attribute`
```
intensities = MosaicoField(
default=None, description="intensity data."
)
```
Intensity measurements for each beam (optional).
A flat list of `float` values, carries the signal amplitude of each beam.
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.models.futures.MultiEchoLaserScan
Bases: `_LaserScanBase`, `Serializable`
Multi-echo 2D laser scan data.
This model represents one sweep of a multi-echo laser range finder. Multi-echo scanners record several range returns per beam, allowing the sensor to detect overlapping surfaces, semi-transparent objects such as vegetation or rain drops, and retroreflective targets simultaneously.
`ranges` and `intensities` are `List[List[float]]` arrays where the *i*-th inner list contains all echo returns for the beam at angular position `angle_min + i * angle_increment`, ordered from nearest to farthest. An empty inner list indicates no valid return for that beam.
Attributes:
| Name | Type | Description |
| `angle_min` | `float32` | Start angle of the scan in radians. |
| `angle_max` | `float32` | End angle of the scan in radians. |
| `angle_increment` | `float32` | Angular step between consecutive beams in radians. |
| `time_increment` | `float32` | Time between consecutive beam measurements in seconds. |
| `scan_time` | `float32` | Total duration of one full scan in seconds. |
| `range_min` | `float32` | Minimum valid range threshold in meters. |
| `range_max` | `float32` | Maximum valid range threshold in meters. |
| `ranges` | `MultiRange` | List of echo distances per beam in meters; may contain multiple returns per beam. |
| `intensities` | `Optional[MultiRange]` | List of echo amplitudes per beam, co-indexed with `ranges` (optional). |
##### Querying with the **`.Q` Proxy**
Scalar fields are fully queryable via the **`.Q` proxy**. `ranges` and `intensities` are **not queryable**.
| Field Access Path | Queryable Type | Supported Operators |
| `MultiEchoLaserScan.Q.angle_min` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MultiEchoLaserScan.Q.angle_max` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MultiEchoLaserScan.Q.angle_increment` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MultiEchoLaserScan.Q.time_increment` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MultiEchoLaserScan.Q.scan_time` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MultiEchoLaserScan.Q.range_min` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MultiEchoLaserScan.Q.range_max` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### angle_min`class-attribute``instance-attribute`
```
angle_min = MosaicoField(
description="start angle of the scan in rad."
)
```
Start angle of the scan in radians.
Defines the angular position of the first beam in the sweep.Together with `angle_max` and `angle_increment`, it fully characterises the angular coverage of the scan.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.angle_min` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### angle_max`class-attribute``instance-attribute`
```
angle_max = MosaicoField(
description="end angle of the scan in rad."
)
```
End angle of the scan in radians.
Defines the angular position of the last beam in the sweep. The total field of view of the scanner is `angle_max - angle_min`.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.angle_max` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### angle_increment`class-attribute``instance-attribute`
```
angle_increment = MosaicoField(
description="angular distance between measurements in rad."
)
```
Angular step between consecutive beams in radians.
The number of beams in a sweep can be derived as `round((angle_max - angle_min) / angle_increment) + 1`. A negative value indicates a clockwise scan direction.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.angle_increment` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### time_increment`class-attribute``instance-attribute`
```
time_increment = MosaicoField(
description="time between measurements in seconds."
)
```
Time elapsed between consecutive beam measurements, in seconds.
If the scanner is moving, this will be used in interpoling position of 3D points.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.time_increment` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### scan_time`class-attribute``instance-attribute`
```
scan_time = MosaicoField(
description="time between scans in seconds."
)
```
Time between scans in seconds.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.scan_time` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### range_min`class-attribute``instance-attribute`
```
range_min = MosaicoField(
description="minimum range value in meters."
)
```
Minimum valid range value, in meters.
Measurements strictly below this threshold are outside the sensor's reliable operating range and should be discarded or treated as invalid during downstream processing.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.range_min` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### range_max`class-attribute``instance-attribute`
```
range_max = MosaicoField(
description="maximum range value in meters."
)
```
Maximum valid range value, in meters.
Measurements strictly above this threshold exceed the sensor's maximum detection distance and should be discarded or treated as invalid during downstream processing.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `LaserScan.Q.range_max` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### ranges`class-attribute``instance-attribute`
```
ranges = MosaicoField(
description="range data in meters. Ranges need to be between range min and max otherwise discarded."
)
```
Range measurements for each beam.
A list of lists, where the *i*-th inner list contains all echo distances returned by the *i*-th beam, ordered from nearest to farthest. An empty inner list indicates no valid return for that beam.
Values outside the `[range_min, range_max]` interval should be considered invalid.
### intensities`class-attribute``instance-attribute`
```
intensities = MosaicoField(
default=None, description="intensity data."
)
```
Intensity measurements for each beam. (optional).
A flat list of list of `float` value carries the signal amplitude of each returned echo.
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.models.futures.Radar
Bases: `Serializable`
Radar Ontology.
This model represents a set of detections acquired from a Radar sensor. Each detection corresponds to a target or a reflection point in the sensor's field of view, characterised by its position, optional velocity, and signal-quality metrics.
Each field is a flat list whose *i*-th element corresponds to the *i*-th detection in the scan.
Unlike a LiDAR, Radar detections are inherently sparse and carry additional electromagnetic attributes such as Radar Cross Section (RCS), Signal-to-Noise Ratio (SNR), and Doppler velocity, which are not available from purely optical sensors.
Attributes:
| Name | Type | Description |
| `x` | `list_(float32)` | X coordinates of each detection in meters. |
| `y` | `list_(float32)` | Y coordinates of each detection in meters. |
| `z` | `list_(float32)` | Z coordinates of each detection in meters. |
| `range` | `Optional[list_(float32)]` | Radial distance from the sensor origin to each detection in meters (optional). |
| `azimuth` | `Optional[list_(float32)]` | Azimuth angle in radians for each detection (optional). |
| `elevation` | `Optional[list_(float32)]` | Elevation angle in radians for each detection (optional). |
| `rcs` | `Optional[list_(float32)]` | Radar Cross Section of each detection in dBm (optional). |
| `snr` | `Optional[list_(float32)]` | Signal-to-Noise Ratio of each detection in dB (optional). |
| `doppler_velocity` | `Optional[list_(float32)]` | Doppler radial velocity of each detection in m/s (optional). |
| `vx` | `Optional[list_(float32)]` | X component of the velocity of each detection in m/s (optional). |
| `vy` | `Optional[list_(float32)]` | Y component of the velocity of each detection in m/s (optional). |
| `vx_comp` | `Optional[list_(float32)]` | Ego-motion-compensated X velocity of each detection in m/s (optional). |
| `vy_comp` | `Optional[list_(float32)]` | Ego-motion-compensated Y velocity of each detection in m/s (optional). |
| `ax` | `Optional[list_(float32)]` | X component of the acceleration of each detection in m/s² (optional). |
| `ay` | `Optional[list_(float32)]` | Y component of the acceleration of each detection in m/s² (optional). |
| `radial_speed` | `Optional[list_(float32)]` | Radial speed of each detection in m/s (optional). |
### x`class-attribute``instance-attribute`
```
x = MosaicoField(description='x coordinates in meters.')
```
X coordinates of each detection, in meters.
### y`class-attribute``instance-attribute`
```
y = MosaicoField(description='y coordinates in meters.')
```
Y coordinates of each detection, in meters.
### z`class-attribute``instance-attribute`
```
z = MosaicoField(description='z coordinates in meters.')
```
Z coordinates of each detection, in meters.
### range`class-attribute``instance-attribute`
```
range = MosaicoField(
default=None, description="radial distance in meters."
)
```
Radial distance from the sensor origin to each detection, in meters.
Represents the straight-line distance along the beam axis.
### azimuth`class-attribute``instance-attribute`
```
azimuth = MosaicoField(
default=None, description="azimuth angle in radians."
)
```
Horizontal (azimuth) angle of each detection in radians.
Measured in the sensor's horizontal plane, typically from 0 to 2π, with 0 aligned to the sensor's forward axis.
### elevation`class-attribute``instance-attribute`
```
elevation = MosaicoField(
default=None, description="elevation angle in radians."
)
```
Vertical (elevation) angle of each detection in radians.
Measured from the sensor's horizontal plane; positive values point upward.
### rcs`class-attribute``instance-attribute`
```
rcs = MosaicoField(
default=None, description="radar cross section in dBm."
)
```
Radar Cross Section (RCS) of each detection, in dBm.
Quantifies the effective scattering area of the target as seen by the sensor. Higher values typically correspond to larger or more reflective objects. Useful for target classification and false-positive filtering.
### snr`class-attribute``instance-attribute`
```
snr = MosaicoField(
default=None, description="signal to noise ratio in dB."
)
```
Signal-to-Noise Ratio (SNR) of each detection, in dB.
Indicates the quality of the received echo relative to background noise. Low-SNR detections are generally less reliable and may be filtered out during object-level processing.
### doppler_velocity`class-attribute``instance-attribute`
```
doppler_velocity = MosaicoField(
default=None, description="doppler velocity in m/s."
)
```
Doppler radial velocity of each detection, in m/s.
Represents the component of the target's velocity along the sensor's line of sight, derived directly from the frequency shift of the returned signal. Positive values conventionally indicate motion away from the sensor.
### vx`class-attribute``instance-attribute`
```
vx = MosaicoField(
default=None, description="x velocity in m/s."
)
```
X component of the estimated velocity of each detection, in m/s.
Expressed in the sensor frame. This is a Cartesian decomposition of the target velocity, as opposed to the purely radial `doppler_velocity`.
### vy`class-attribute``instance-attribute`
```
vy = MosaicoField(
default=None, description="y velocity in m/s."
)
```
Y component of the estimated velocity of each detection, in m/s.
Expressed in the sensor frame. See `vx` for further context.
### vx_comp`class-attribute``instance-attribute`
```
vx_comp = MosaicoField(
default=None,
description="x compensated velocity in m/s.",
)
```
Ego-motion-compensated X velocity of each detection, in m/s.
Obtained by subtracting the host vehicle's own velocity from `vx`, yielding the detection's absolute velocity in the world frame along the X axis.
### vy_comp`class-attribute``instance-attribute`
```
vy_comp = MosaicoField(
default=None,
description="y compensated velocity in m/s.",
)
```
Ego-motion-compensated Y velocity of each detection, in m/s.
Analogous to `vx_comp` along the Y axis. See `vx_comp` for further context.
### ax`class-attribute``instance-attribute`
```
ax = MosaicoField(
default=None, description="x acceleration in m/s^2."
)
```
X component of the estimated acceleration of each detection, in m/s².
Available only on sensors that track detections across multiple scans and report per-point kinematic state (e.g. high-level object-list outputs).
### ay`class-attribute``instance-attribute`
```
ay = MosaicoField(
default=None, description="y acceleration in m/s^2."
)
```
Y component of the estimated acceleration of each detection, in m/s².
Analogous to `ax` along the Y axis. See `ax` for further context.
### radial_speed`class-attribute``instance-attribute`
```
radial_speed = MosaicoField(
default=None, description="radial speed in m/s."
)
```
Radial speed of each detection, in m/s.
Represents the magnitude of the velocity component along the line of sight, without sign convention. Distinct from `doppler_velocity`, which may carry a directional sign depending on the sensor's convention.
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.models.futures.Lidar
Bases: `Serializable`
LiDAR Ontology.
This model represents a 3D point cloud acquired from a LiDAR sensor. Each field is a flat list whose *i*-th element corresponds to the *i*-th point in the scan. All lists within a single instance are therefore guaranteed to have the same length.
Attributes:
| Name | Type | Description |
| `x` | `list_(float32)` | X coordinates of each point in meters. |
| `y` | `list_(float32)` | Y coordinates of each point in meters. |
| `z` | `list_(float32)` | Z coordinates of each point in meters. |
| `intensity` | `Optional[list_(float32)]` | Strength of the returned signal for each point (optional). |
| `reflectivity` | `Optional[list_(uint16)]` | Surface reflectivity per point (optional). |
| `beam_id` | `Optional[list_(uint16)]` | Laser beam index (ring / channel / line) that fired each point (optional). |
| `range` | `Optional[list_(float32)]` | Distance from the sensor origin to each point in meters (optional). |
| `near_ir` | `Optional[list_(float32)]` | Near-infrared ambient light reading per point, useful as a noise/ambient estimate (optional). |
| `azimuth` | `Optional[list_(float32)]` | Azimuth angle in radians for each point (optional). |
| `elevation` | `Optional[list_(float32)]` | Elevation angle in radians for each point (optional). |
| `confidence` | `Optional[list_(uint8)]` | Per-point validity or confidence flags as a manufacturer-specific bitmask (optional). |
| `return_type` | `Optional[list_(uint8)]` | Single/dual return classification, manufacturer-specific (optional). |
| `point_timestamp` | `Optional[list_(float64)]` | Per-point acquisition time offset from the scan start, in seconds (optional). |
### x`class-attribute``instance-attribute`
```
x = MosaicoField(description='x coordinates in meters')
```
X coordinates of each point in the cloud, in meters.
### y`class-attribute``instance-attribute`
```
y = MosaicoField(description='y coordinates in meters')
```
Y coordinates of each point in the cloud, in meters.
### z`class-attribute``instance-attribute`
```
z = MosaicoField(description='z coordinates in meters')
```
Z coordinates of each point in the cloud, in meters.
### intensity`class-attribute``instance-attribute`
```
intensity = MosaicoField(
default=None,
description="Surface reflectivity per point.",
)
```
Strength of the returned laser signal for each point.
### reflectivity`class-attribute``instance-attribute`
```
reflectivity = MosaicoField(
default=None,
description="Surface reflectivity per point.",
)
```
Surface reflectivity per point.
Encodes the estimated reflectance of the surface that produced each return, independently of the distance. Manufacturer-specific scaling applies.
### beam_id`class-attribute``instance-attribute`
```
beam_id = MosaicoField(
default=None,
description="Laser beam index (ring / channel / line) that fired each point.",
)
```
Laser beam index (ring / channel / line) that fired each point.
Identifies which physical emitter in the sensor array produced the return. Equivalent to the `ring` field commonly found in ROS `PointCloud2` messages from multi-beam sensors such as Velodyne or Ouster.
### range`class-attribute``instance-attribute`
```
range = MosaicoField(
default=None,
description="Distance from the sensor origin to each point, in meters.",
)
```
Distance from the sensor origin to each point, in meters.
Represents the raw radial distance along the beam axis, before projection onto Cartesian coordinates. Not always provided by all sensor drivers.
### near_ir`class-attribute``instance-attribute`
```
near_ir = MosaicoField(
default=None,
description="Near-infrared ambient light reading per point.",
)
```
Near-infrared ambient light reading per point.
Captured passively by the sensor between laser pulses. Useful as a proxy for ambient illumination or for filtering sun-noise artefacts. Exposed as the `ambient` channel in Ouster drivers.
### azimuth`class-attribute``instance-attribute`
```
azimuth = MosaicoField(
default=None,
description="Horizontal (azimuth) angle of each point in radians.",
)
```
Horizontal (azimuth) angle of each point in radians.
### elevation`class-attribute``instance-attribute`
```
elevation = MosaicoField(
default=None,
description="Vertical (elevation) angle of each point in radians.",
)
```
Vertical (elevation) angle of each point in radians.
### confidence`class-attribute``instance-attribute`
```
confidence = MosaicoField(
default=None,
description="Per-point validity or confidence flags.",
)
```
Per-point validity or confidence flags.
Stored as a manufacturer-specific bitmask (equivalent to the `tag` or `flags` fields in Ouster point clouds). Individual bits may signal saturated returns, calibration issues, or other quality indicators.
### return_type`class-attribute``instance-attribute`
```
return_type = MosaicoField(
default=None,
description="Single/dual return classification per point.",
)
```
Single/dual return classification per point.
Indicates whether a point originates from the first return, last return, strongest return, etc. Encoding is manufacturer-specific.
### point_timestamp`class-attribute``instance-attribute`
```
point_timestamp = MosaicoField(
default=None,
description="Per-point acquisition time offset from the scan start, in seconds.",
)
```
Per-point acquisition time offset from the scan start, in seconds.
Allows precise temporal localisation of individual points within a single sweep, which is important for motion-distortion correction during point-cloud registration.
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.models.futures.depth_camera._DepthCameraBase
Bases: `BaseModel`
Internal base model shared by all depth camera ontologies.
Defines the spatial core and common optional channels that every depth camera variant exposes, regardless of the underlying acquisition technology.
**This class is not intended to be instantiated directly**. Use one of the concrete subclasses: `RGBDCamera`, `ToFCamera`, or `StereoCamera`.
Attributes:
| Name | Type | Description |
| `x` | `list_(float32)` | Horizontal positions of each point, derived from depth, in meters. |
| `y` | `list_(float32)` | Vertical positions of each point, derived from depth, in meters. |
| `z` | `list_(float32)` | Depth values (distance along the optical axis) of each point, in meters. |
| `rgb` | `Optional[list_(float32)]` | Packed RGB colour value per point (optional). |
| `intensity` | `Optional[list_(float32)]` | Signal amplitude or intensity per point (optional). |
### x`class-attribute``instance-attribute`
```
x = MosaicoField(
description="Horizontal position derived from depth."
)
```
Horizontal position of each point derived from the depth map, in meters.
### y`class-attribute``instance-attribute`
```
y = MosaicoField(
description="Vertical position derived from depth."
)
```
Vertical position of each point derived from the depth map, in meters.
### z`class-attribute``instance-attribute`
```
z = MosaicoField(
description="Depth value directly (distance along optical axis)."
)
```
Depth value of each point, in meters.
Represents the distance along the camera's optical axis (Z-forward convention). This is the primary measurement from which `x` and `y` are projected using the sensor's intrinsic parameters.
### rgb`class-attribute``instance-attribute`
```
rgb = MosaicoField(
default=None, description="Packed RGB color value."
)
```
Packed RGB colour value per point.
Each element encodes the red, green, and blue channels of the pixel co-registered with the corresponding depth sample. The packing convention `rgb` field (bits 16–23 = R, 8–15 = G, 0–7 = B, stored as a float32 reinterpretation of a uint32). There are useful utilities for `pack_rgb()` and `unpack_rgb()` rgb in in the internal of depth camera.
### intensity`class-attribute``instance-attribute`
```
intensity = MosaicoField(
default=None, description="Signal amplitude/intensity."
)
```
Signal amplitude or intensity per point.
## mosaicolabs.models.futures.depth_camera.pack_rgb
```
pack_rgb(r, g, b)
```
Packs three RGB channels (8-bit each) into a single float32 value.
This utility combines Red, Green, and Blue components into a 32-bit integer and then bit-casts the result into a float. This is a standard technique used in point cloud processing to store color data efficiently within a single field.
Parameters:
| Name | Type | Description | Default |
| `r` | `int` | Red intensity (0-255). | *required* |
| `g` | `int` | Green intensity (0-255). | *required* |
| `b` | `int` | Blue intensity (0-255). | *required* |
Returns:
| Type | Description |
| `float` | The RGB color encoded as a 32-bit float. |
## mosaicolabs.models.futures.depth_camera.unpack_rgb
```
unpack_rgb(packed_rgb)
```
Unpacks a float32 value back into its original RGB components.
This is the inverse operation of `pack_rgb()`. It reinterprets the float's bits as an unsigned 32-bit integer and extracts the individual color bytes.
Parameters:
| Name | Type | Description | Default |
| `packed_rgb` | `float` | The encoded float value containing RGB data. | *required* |
Returns:
| Type | Description |
| `Tuple[int, int, int]` | A tuple of `(red, green, blue)`, where each value is between 0 and 255. |
## mosaicolabs.models.futures.RGBDCamera
Bases: `_DepthCameraBase`, `Serializable`
RGB-D camera ontology.
This model represents a registered depth-and-colour point cloud produced by an RGB-D sensor (e.g. Intel RealSense D-series, Microsoft Azure Kinect). Each point carries a 3D position in the camera frame together with an optional packed RGB colour value and an optional intensity channel.
RGB-D sensors typically fuse a structured-light or active-infrared depth map with a co-located colour camera, yielding a dense, pixel-aligned point cloud at video frame rates.
Each field is a flat list whose *i*-th element corresponds to the *i*-th point in the frame. All lists within a single instance are therefore guaranteed to have the same length.
Attributes:
| Name | Type | Description |
| `x` | `list_(float32)` | Horizontal positions of each point, derived from depth, in meters. |
| `y` | `list_(float32)` | Vertical positions of each point, derived from depth, in meters. |
| `z` | `list_(float32)` | Depth values (distance along the optical axis) of each point, in meters. |
| `rgb` | `Optional[list_(float32)]` | Packed RGB colour value per point (optional). |
| `intensity` | `Optional[list_(float32)]` | Signal amplitude or intensity per point (optional). |
Example:
```
from mosaicolabs import MosaicoClient
from mosaicolabs.models.futures import RGBDCamera
with MosaicoClient.connect("localhost", 6726) as client:
# Fetch all sequences that contain at least one RGB-D camera topic
sequences = client.get_sequences(ontology=RGBDCamera)
for sequence in sequences:
print(f"Sequence: {sequence.name}")
print(f"Topics: {[topic.name for topic in sequence.topics]}")
```
### x`class-attribute``instance-attribute`
```
x = MosaicoField(
description="Horizontal position derived from depth."
)
```
Horizontal position of each point derived from the depth map, in meters.
### y`class-attribute``instance-attribute`
```
y = MosaicoField(
description="Vertical position derived from depth."
)
```
Vertical position of each point derived from the depth map, in meters.
### z`class-attribute``instance-attribute`
```
z = MosaicoField(
description="Depth value directly (distance along optical axis)."
)
```
Depth value of each point, in meters.
Represents the distance along the camera's optical axis (Z-forward convention). This is the primary measurement from which `x` and `y` are projected using the sensor's intrinsic parameters.
### rgb`class-attribute``instance-attribute`
```
rgb = MosaicoField(
default=None, description="Packed RGB color value."
)
```
Packed RGB colour value per point.
Each element encodes the red, green, and blue channels of the pixel co-registered with the corresponding depth sample. The packing convention `rgb` field (bits 16–23 = R, 8–15 = G, 0–7 = B, stored as a float32 reinterpretation of a uint32). There are useful utilities for `pack_rgb()` and `unpack_rgb()` rgb in in the internal of depth camera.
### intensity`class-attribute``instance-attribute`
```
intensity = MosaicoField(
default=None, description="Signal amplitude/intensity."
)
```
Signal amplitude or intensity per point.
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.models.futures.StereoCamera
Bases: `_DepthCameraBase`, `Serializable`
Stereo camera ontology.
This model represents a dense point cloud produced by a passive stereo camera system (e.g. Stereolabs ZED, Luxonis OAK-D, Carnegie Robotics MultiSense). Depth is estimated by computing the horizontal disparity between a rectified left/right image pair and projecting it into 3D space using the known baseline and intrinsic parameters.
In addition to the common spatial and colour channels inherited from `_DepthCamera`, this model exposes two stereo-specific fields: `luma`, which carries the luminance of the source rectified image pixel, and `cost`, which encodes the confidence of the disparity estimate at each point.
Each field is a flat list whose *i*-th element corresponds to the *i*-th pixel in the disparity map (in row-major order). All lists within a single instance are therefore guaranteed to have the same length.
Attributes:
| Name | Type | Description |
| `x` | `list_(float32)` | Horizontal positions of each point in meters. |
| `y` | `list_(float32)` | Vertical positions of each point in meters. |
| `z` | `list_(float32)` | Depth values (distance along the optical axis) of each point, in meters. |
| `rgb` | `Optional[list_(float32)]` | Packed RGB colour value per point (optional). |
| `intensity` | `Optional[list_(float32)]` | Signal amplitude or intensity per point (optional). |
| `luma` | `Optional[list_(uint8)]` | Luminance of the corresponding pixel in the rectified image (optional). |
| `cost` | `Optional[list_(uint8)]` | Stereo matching cost per point; lower values indicate higher disparity confidence (optional). |
Example:
```
from mosaicolabs import MosaicoClient
from mosaicolabs.models.futures import StereoCamera
with MosaicoClient.connect("localhost", 6726) as client:
# Fetch all sequences that contain at least one stereo camera topic
sequences = client.get_sequences(ontology=StereoCamera)
for sequence in sequences:
print(f"Sequence: {sequence.name}")
print(f"Topics: {[topic.name for topic in sequence.topics]}")
```
### x`class-attribute``instance-attribute`
```
x = MosaicoField(
description="Horizontal position derived from depth."
)
```
Horizontal position of each point derived from the depth map, in meters.
### y`class-attribute``instance-attribute`
```
y = MosaicoField(
description="Vertical position derived from depth."
)
```
Vertical position of each point derived from the depth map, in meters.
### z`class-attribute``instance-attribute`
```
z = MosaicoField(
description="Depth value directly (distance along optical axis)."
)
```
Depth value of each point, in meters.
Represents the distance along the camera's optical axis (Z-forward convention). This is the primary measurement from which `x` and `y` are projected using the sensor's intrinsic parameters.
### rgb`class-attribute``instance-attribute`
```
rgb = MosaicoField(
default=None, description="Packed RGB color value."
)
```
Packed RGB colour value per point.
Each element encodes the red, green, and blue channels of the pixel co-registered with the corresponding depth sample. The packing convention `rgb` field (bits 16–23 = R, 8–15 = G, 0–7 = B, stored as a float32 reinterpretation of a uint32). There are useful utilities for `pack_rgb()` and `unpack_rgb()` rgb in in the internal of depth camera.
### intensity`class-attribute``instance-attribute`
```
intensity = MosaicoField(
default=None, description="Signal amplitude/intensity."
)
```
Signal amplitude or intensity per point.
### luma`class-attribute``instance-attribute`
```
luma = MosaicoField(
default=None,
description="Luminance of the corresponding pixel in the rectified image.",
)
```
Luminance of the corresponding pixel in the rectified image.
### cost`class-attribute``instance-attribute`
```
cost = MosaicoField(
default=None,
description="Stereo matching cost (disparity confidence measure, 0 = high confidence).",
)
```
Stereo matching cost per point; lower values indicate higher disparity confidence.
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.models.futures.ToFCamera
Bases: `_DepthCameraBase`, `Serializable`
Time-of-Flight (ToF) camera ontology.
This model represents a point cloud produced by a Time-of-Flight sensor (e.g. PMD Flexx2, ifm O3R, Sony DepthSense). ToF sensors measure depth by emitting amplitude-modulated infrared light and computing the phase shift of the returning signal, yielding per-pixel depth, amplitude, and noise estimates in a single acquisition.
In addition to the common spatial and colour channels inherited from `_DepthCamera`, this model exposes two ToF-specific fields: `noise`, which quantifies the per-pixel measurement uncertainty, and `grayscale`, which carries the passive greyscale amplitude captured alongside the active depth measurement.
Each field is a flat list whose *i*-th element corresponds to the *i*-th pixel in the depth frame (in row-major order). All lists within a single instance are therefore guaranteed to have the same length.
Attributes:
| Name | Type | Description |
| `x` | `list_(float32)` | Horizontal positions of each point, derived from depth, in meters. |
| `y` | `list_(float32)` | Vertical positions of each point, derived from depth, in meters. |
| `z` | `list_(float32)` | Depth values (distance along the optical axis) of each point, in meters. |
| `rgb` | `Optional[list_(float32)]` | Packed RGB colour value per point (optional). |
| `intensity` | `Optional[list_(float32)]` | Signal amplitude or intensity per point (optional). |
| `noise` | `Optional[list_(float32)]` | Per-pixel noise estimate of the depth measurement (optional). |
| `grayscale` | `Optional[list_(float32)]` | Passive greyscale amplitude per pixel (optional). |
### x`class-attribute``instance-attribute`
```
x = MosaicoField(
description="Horizontal position derived from depth."
)
```
Horizontal position of each point derived from the depth map, in meters.
### y`class-attribute``instance-attribute`
```
y = MosaicoField(
description="Vertical position derived from depth."
)
```
Vertical position of each point derived from the depth map, in meters.
### z`class-attribute``instance-attribute`
```
z = MosaicoField(
description="Depth value directly (distance along optical axis)."
)
```
Depth value of each point, in meters.
Represents the distance along the camera's optical axis (Z-forward convention). This is the primary measurement from which `x` and `y` are projected using the sensor's intrinsic parameters.
### rgb`class-attribute``instance-attribute`
```
rgb = MosaicoField(
default=None, description="Packed RGB color value."
)
```
Packed RGB colour value per point.
Each element encodes the red, green, and blue channels of the pixel co-registered with the corresponding depth sample. The packing convention `rgb` field (bits 16–23 = R, 8–15 = G, 0–7 = B, stored as a float32 reinterpretation of a uint32). There are useful utilities for `pack_rgb()` and `unpack_rgb()` rgb in in the internal of depth camera.
### intensity`class-attribute``instance-attribute`
```
intensity = MosaicoField(
default=None, description="Signal amplitude/intensity."
)
```
Signal amplitude or intensity per point.
### noise`class-attribute``instance-attribute`
```
noise = MosaicoField(
default=None, description="Noise value per pixel."
)
```
Per-pixel noise estimate of the depth measurement.
High noise values typically indicate low-confidence depth samples caused by low signal return, multi-path interference, or motion blur, and should be treated with caution during downstream processing.
### grayscale`class-attribute``instance-attribute`
```
grayscale = MosaicoField(
default=None, description="Grayscale amplitude."
)
```
Passive greyscale amplitude per pixel.
Captured by the sensor's infrared photodiodes independently of the active modulation cycle. Provides a texture channel that can be used for feature extraction or visual odometry without requiring a separate colour camera.
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
---
# Geometry Models
## mosaicolabs.models.data.geometry
This module defines the fundamental building blocks for spatial representation, including vectors, points, quaternions, and rigid-body transforms.
The module follows a **Two-Tier Architecture** to optimize both internal efficiency and public usability:
- **Internal Structs (`_Struct`)**: Pure data containers that define the physical memory layout and the PyArrow schema. These are intended for embedding within larger composite objects (like a `Pose` or `Transform`) to avoid attaching redundant metadata headers or timestamps to every inner field.
- **Public Classes**: High-level models that combine spatial data with Mosaico's transport and serialization logic. These inherit from the internal structs and inject support for auto-registration (`Serializable`), and uncertainty tracking (`CovarianceMixin`).
### Vector2d
Bases: `_Vector2dStruct`, `Serializable`, `CovarianceMixin`
A public 2D Vector for platform-wide transmission.
This class combines the [x, y] coordinates with full Mosaico transport logic. It is used to represent quantities such as velocity, acceleration, or directional forces.
Attributes:
| Name | Type | Description |
| `x` | `float64` | Vector X component. |
| `y` | `float64` | Vector Y component. |
| `covariance` | `Optional[list_(float64)]` | Optional flattened 2x2 covariance matrix representing the uncertainty of the vector measurement. |
| `covariance_type` | `Optional[int16]` | Enum integer representing the parameterization of the covariance matrix. |
###### Querying with the **`.Q` Proxy**
This class fields are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### covariance`class-attribute``instance-attribute`
```
covariance = MosaicoField(
default=None,
nullable=True,
description="The covariance matrix (flattened) of the data.",
)
```
Optional list of 64-bit floats representing the flattened matrix.
###### Querying with the **`.Q` Proxy**
#### covariance_type`class-attribute``instance-attribute`
```
covariance_type = MosaicoField(
default=None,
nullable=True,
description="Enum integer representing the covariance parameterization.",
)
```
Optional 16-bit integer representing the covariance enum.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional covariance type attribute.
###### Querying with the **`.Q` Proxy**
The `covariance_type` field is fully queryable via the **`.Q` Proxy**. The `` placeholder in the path represents any Mosaico class that exposes covariance information, either directly or through its internal fields.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.covariance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `CovarianceMixin` is integrated into your data structure:
- **Direct Inheritance**: Represents any class (e.g., `Vector3d`, `Quaternion`) that inherits directly from `CovarianceMixin`.
- **Composition (Nested Fields)**: When a complex model (like `IMU`) contains fields that are themselves covariance-aware, the proxy allows you to "drill down" to that specific attribute. For example, since `IMU.acceleration` is a `Vector3d`, you access its covariance type via `IMU.Q.acceleration.covariance_type`.
#### x`class-attribute``instance-attribute`
```
x = MosaicoField(
nullable=True, description="Vector x component."
)
```
The Vector X component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### y`class-attribute``instance-attribute`
```
y = MosaicoField(
nullable=True, description="Vector y component."
)
```
The Vector Y component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
#### from_list`classmethod`
```
from_list(data)
```
Creates a struct instance from a raw list.
Parameters:
| Name | Type | Description | Default |
| `data` | `list[float]` | A list containing exactly 2 float values: [x, y]. | *required* |
Raises:
| Type | Description |
| `ValueError` | If the input list does not have a length of 2. |
### Vector3d
Bases: `_Vector3dStruct`, `Serializable`, `CovarianceMixin`
A public 3D Vector for platform-wide transmission.
This class combines the [x, y, z] coordinates with full Mosaico transport logic. It is used to represent quantities such as velocity, acceleration, or directional forces.
Attributes:
| Name | Type | Description |
| `x` | `float64` | Vector X component. |
| `y` | `float64` | Vector Y component. |
| `z` | `float64` | Vector Z component. |
| `covariance` | `Optional[list_(float64)]` | Optional flattened 3x3 covariance matrix representing the uncertainty of the vector measurement. |
| `covariance_type` | `Optional[int16]` | Enum integer representing the parameterization of the covariance matrix. |
###### Querying with the **`.Q` Proxy**
This class fields are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### covariance`class-attribute``instance-attribute`
```
covariance = MosaicoField(
default=None,
nullable=True,
description="The covariance matrix (flattened) of the data.",
)
```
Optional list of 64-bit floats representing the flattened matrix.
###### Querying with the **`.Q` Proxy**
#### covariance_type`class-attribute``instance-attribute`
```
covariance_type = MosaicoField(
default=None,
nullable=True,
description="Enum integer representing the covariance parameterization.",
)
```
Optional 16-bit integer representing the covariance enum.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional covariance type attribute.
###### Querying with the **`.Q` Proxy**
The `covariance_type` field is fully queryable via the **`.Q` Proxy**. The `` placeholder in the path represents any Mosaico class that exposes covariance information, either directly or through its internal fields.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.covariance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `CovarianceMixin` is integrated into your data structure:
- **Direct Inheritance**: Represents any class (e.g., `Vector3d`, `Quaternion`) that inherits directly from `CovarianceMixin`.
- **Composition (Nested Fields)**: When a complex model (like `IMU`) contains fields that are themselves covariance-aware, the proxy allows you to "drill down" to that specific attribute. For example, since `IMU.acceleration` is a `Vector3d`, you access its covariance type via `IMU.Q.acceleration.covariance_type`.
#### x`class-attribute``instance-attribute`
```
x = MosaicoField(
nullable=True, description="Vector x component."
)
```
The Vector X component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### y`class-attribute``instance-attribute`
```
y = MosaicoField(
nullable=True, description="Vector y component."
)
```
The Vector Y component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### z`class-attribute``instance-attribute`
```
z = MosaicoField(
nullable=True, description="Vector z component."
)
```
The Vector Z component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
#### from_list`classmethod`
```
from_list(data)
```
Creates a struct instance from a raw list.
Parameters:
| Name | Type | Description | Default |
| `data` | `list[float]` | A list containing exactly 3 float values: [x, y, z]. | *required* |
Raises:
| Type | Description |
| `ValueError` | If the input list does not have a length of 3. |
### Vector4d
Bases: `_Vector4dStruct`, `Serializable`, `CovarianceMixin`
A public 4D Vector for platform-wide transmission.
This class combines the [x, y, z, w] coordinates with full Mosaico transport logic. It is used to represent quantities such as velocity, acceleration, or directional forces.
Attributes:
| Name | Type | Description |
| `x` | `float64` | Vector X component. |
| `y` | `float64` | Vector Y component. |
| `z` | `float64` | Vector Z component. |
| `w` | `float64` | Vector W component. |
| `covariance` | `Optional[list_(float64)]` | Optional flattened 4x4 covariance matrix representing the uncertainty of the vector measurement. |
| `covariance_type` | `Optional[int16]` | Enum integer representing the parameterization of the covariance matrix. |
###### Querying with the **`.Q` Proxy**
This class fields are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### covariance`class-attribute``instance-attribute`
```
covariance = MosaicoField(
default=None,
nullable=True,
description="The covariance matrix (flattened) of the data.",
)
```
Optional list of 64-bit floats representing the flattened matrix.
###### Querying with the **`.Q` Proxy**
#### covariance_type`class-attribute``instance-attribute`
```
covariance_type = MosaicoField(
default=None,
nullable=True,
description="Enum integer representing the covariance parameterization.",
)
```
Optional 16-bit integer representing the covariance enum.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional covariance type attribute.
###### Querying with the **`.Q` Proxy**
The `covariance_type` field is fully queryable via the **`.Q` Proxy**. The `` placeholder in the path represents any Mosaico class that exposes covariance information, either directly or through its internal fields.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.covariance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `CovarianceMixin` is integrated into your data structure:
- **Direct Inheritance**: Represents any class (e.g., `Vector3d`, `Quaternion`) that inherits directly from `CovarianceMixin`.
- **Composition (Nested Fields)**: When a complex model (like `IMU`) contains fields that are themselves covariance-aware, the proxy allows you to "drill down" to that specific attribute. For example, since `IMU.acceleration` is a `Vector3d`, you access its covariance type via `IMU.Q.acceleration.covariance_type`.
#### x`class-attribute``instance-attribute`
```
x = MosaicoField(
nullable=True, description="Vector x component."
)
```
The Vector X component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### y`class-attribute``instance-attribute`
```
y = MosaicoField(
nullable=True, description="Vector y component."
)
```
The Vector Y component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### z`class-attribute``instance-attribute`
```
z = MosaicoField(
nullable=True, description="Vector z component."
)
```
The Vector Z component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### w`class-attribute``instance-attribute`
```
w = MosaicoField(
nullable=True, description="Vector w component."
)
```
The Vector W component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.w` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
#### from_list`classmethod`
```
from_list(data)
```
Creates a struct instance from a raw list.
Parameters:
| Name | Type | Description | Default |
| `data` | `list[float]` | A list containing exactly 4 float values: [x, y, z, w]. | *required* |
Raises:
| Type | Description |
| `ValueError` | If the input list does not have a length of 4. |
### Point2d
Bases: `_Vector2dStruct`, `Serializable`, `CovarianceMixin`
Semantically represents a specific location (Point) in 2D space.
Structurally identical to a 2D Vector, but distinguished within the Mosaico API to clarify intent in spatial operations. Use this class for 2D coordinate data that requires Mosaico transport logic.
Attributes:
| Name | Type | Description |
| `x` | `float64` | Point X coordinate. |
| `y` | `float64` | Point Y coordinate. |
| `covariance` | `Optional[list_(float64)]` | Optional flattened 2x2 covariance matrix representing the uncertainty of the point measurement. |
| `covariance_type` | `Optional[int16]` | Enum integer representing the parameterization of the covariance matrix. |
###### Querying with the **`.Q` Proxy**
This class fields are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### covariance`class-attribute``instance-attribute`
```
covariance = MosaicoField(
default=None,
nullable=True,
description="The covariance matrix (flattened) of the data.",
)
```
Optional list of 64-bit floats representing the flattened matrix.
###### Querying with the **`.Q` Proxy**
#### covariance_type`class-attribute``instance-attribute`
```
covariance_type = MosaicoField(
default=None,
nullable=True,
description="Enum integer representing the covariance parameterization.",
)
```
Optional 16-bit integer representing the covariance enum.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional covariance type attribute.
###### Querying with the **`.Q` Proxy**
The `covariance_type` field is fully queryable via the **`.Q` Proxy**. The `` placeholder in the path represents any Mosaico class that exposes covariance information, either directly or through its internal fields.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.covariance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `CovarianceMixin` is integrated into your data structure:
- **Direct Inheritance**: Represents any class (e.g., `Vector3d`, `Quaternion`) that inherits directly from `CovarianceMixin`.
- **Composition (Nested Fields)**: When a complex model (like `IMU`) contains fields that are themselves covariance-aware, the proxy allows you to "drill down" to that specific attribute. For example, since `IMU.acceleration` is a `Vector3d`, you access its covariance type via `IMU.Q.acceleration.covariance_type`.
#### x`class-attribute``instance-attribute`
```
x = MosaicoField(
nullable=True, description="Vector x component."
)
```
The Vector X component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### y`class-attribute``instance-attribute`
```
y = MosaicoField(
nullable=True, description="Vector y component."
)
```
The Vector Y component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
#### from_list`classmethod`
```
from_list(data)
```
Creates a struct instance from a raw list.
Parameters:
| Name | Type | Description | Default |
| `data` | `list[float]` | A list containing exactly 2 float values: [x, y]. | *required* |
Raises:
| Type | Description |
| `ValueError` | If the input list does not have a length of 2. |
### Point3d
Bases: `_Vector3dStruct`, `Serializable`, `CovarianceMixin`
Semantically represents a specific location (Point) in 3D space.
The `Point3d` class is used to instantiate a 3D coordinate message for transmission over the platform. It is structurally identical to a 3D Vector but is used to denote state rather than direction.
Attributes:
| Name | Type | Description |
| `x` | `float64` | Point X coordinate. |
| `y` | `float64` | Point Y coordinate. |
| `z` | `float64` | Point Z coordinate. |
| `covariance` | `Optional[list_(float64)]` | Optional flattened 3x3 covariance matrix representing the uncertainty of the point measurement. |
| `covariance_type` | `Optional[int16]` | Enum integer representing the parameterization of the covariance matrix. |
###### Querying with the **`.Q` Proxy**
This class fields are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### covariance`class-attribute``instance-attribute`
```
covariance = MosaicoField(
default=None,
nullable=True,
description="The covariance matrix (flattened) of the data.",
)
```
Optional list of 64-bit floats representing the flattened matrix.
###### Querying with the **`.Q` Proxy**
#### covariance_type`class-attribute``instance-attribute`
```
covariance_type = MosaicoField(
default=None,
nullable=True,
description="Enum integer representing the covariance parameterization.",
)
```
Optional 16-bit integer representing the covariance enum.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional covariance type attribute.
###### Querying with the **`.Q` Proxy**
The `covariance_type` field is fully queryable via the **`.Q` Proxy**. The `` placeholder in the path represents any Mosaico class that exposes covariance information, either directly or through its internal fields.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.covariance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `CovarianceMixin` is integrated into your data structure:
- **Direct Inheritance**: Represents any class (e.g., `Vector3d`, `Quaternion`) that inherits directly from `CovarianceMixin`.
- **Composition (Nested Fields)**: When a complex model (like `IMU`) contains fields that are themselves covariance-aware, the proxy allows you to "drill down" to that specific attribute. For example, since `IMU.acceleration` is a `Vector3d`, you access its covariance type via `IMU.Q.acceleration.covariance_type`.
#### x`class-attribute``instance-attribute`
```
x = MosaicoField(
nullable=True, description="Vector x component."
)
```
The Vector X component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### y`class-attribute``instance-attribute`
```
y = MosaicoField(
nullable=True, description="Vector y component."
)
```
The Vector Y component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### z`class-attribute``instance-attribute`
```
z = MosaicoField(
nullable=True, description="Vector z component."
)
```
The Vector Z component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
#### from_list`classmethod`
```
from_list(data)
```
Creates a struct instance from a raw list.
Parameters:
| Name | Type | Description | Default |
| `data` | `list[float]` | A list containing exactly 3 float values: [x, y, z]. | *required* |
Raises:
| Type | Description |
| `ValueError` | If the input list does not have a length of 3. |
### Quaternion
Bases: `_Vector4dStruct`, `Serializable`, `CovarianceMixin`
Represents a rotation in 3D space using normalized quaternions.
Structurally identical to a 4D vector [x, y, z, w], but semantically denotes an orientation. This representation avoids the gimbal lock issues associated with Euler angles.
Attributes:
| Name | Type | Description |
| `x` | `float64` | Vector X component. |
| `y` | `float64` | Vector Y component. |
| `z` | `float64` | Vector Z component. |
| `w` | `float64` | Vector W component. |
| `covariance` | `Optional[list_(float64)]` | Optional flattened 4x4 covariance matrix representing the uncertainty of the quaternion measurement. |
| `covariance_type` | `Optional[int16]` | Enum integer representing the parameterization of the covariance matrix. |
###### Querying with the **`.Q` Proxy**
This class fields are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### covariance`class-attribute``instance-attribute`
```
covariance = MosaicoField(
default=None,
nullable=True,
description="The covariance matrix (flattened) of the data.",
)
```
Optional list of 64-bit floats representing the flattened matrix.
###### Querying with the **`.Q` Proxy**
#### covariance_type`class-attribute``instance-attribute`
```
covariance_type = MosaicoField(
default=None,
nullable=True,
description="Enum integer representing the covariance parameterization.",
)
```
Optional 16-bit integer representing the covariance enum.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional covariance type attribute.
###### Querying with the **`.Q` Proxy**
The `covariance_type` field is fully queryable via the **`.Q` Proxy**. The `` placeholder in the path represents any Mosaico class that exposes covariance information, either directly or through its internal fields.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.covariance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `CovarianceMixin` is integrated into your data structure:
- **Direct Inheritance**: Represents any class (e.g., `Vector3d`, `Quaternion`) that inherits directly from `CovarianceMixin`.
- **Composition (Nested Fields)**: When a complex model (like `IMU`) contains fields that are themselves covariance-aware, the proxy allows you to "drill down" to that specific attribute. For example, since `IMU.acceleration` is a `Vector3d`, you access its covariance type via `IMU.Q.acceleration.covariance_type`.
#### x`class-attribute``instance-attribute`
```
x = MosaicoField(
nullable=True, description="Vector x component."
)
```
The Vector X component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### y`class-attribute``instance-attribute`
```
y = MosaicoField(
nullable=True, description="Vector y component."
)
```
The Vector Y component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### z`class-attribute``instance-attribute`
```
z = MosaicoField(
nullable=True, description="Vector z component."
)
```
The Vector Z component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### w`class-attribute``instance-attribute`
```
w = MosaicoField(
nullable=True, description="Vector w component."
)
```
The Vector W component
###### Querying with the **`.Q` Proxy**
This field is queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.w` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
#### from_list`classmethod`
```
from_list(data)
```
Creates a struct instance from a raw list.
Parameters:
| Name | Type | Description | Default |
| `data` | `list[float]` | A list containing exactly 4 float values: [x, y, z, w]. | *required* |
Raises:
| Type | Description |
| `ValueError` | If the input list does not have a length of 4. |
### Transform
Bases: `Serializable`, `CovarianceMixin`
Represents a rigid-body transformation between two coordinate frames.
A transform consists of a translation followed by a rotation. It is typically used to describe the kinematic relationship between components (e.g., "Camera to Robot Base").
Attributes:
| Name | Type | Description |
| `translation` | `Vector3d` | A `Vector3d` describing the linear shift. |
| `rotation` | `Quaternion` | A `Quaternion` describing the rotational shift. |
| `target_frame_id` | `Optional[string]` | The identifier of the destination coordinate frame. |
| `covariance` | `Optional[list_(float64)]` | Optional flattened 7x7 composed covariance matrix representing the uncertainty of the Translation+Rotation. |
| `covariance_type` | `Optional[int16]` | Enum integer representing the parameterization of the covariance matrix. |
###### Querying with the **`.Q` Proxy**
This class fields are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### translation`class-attribute``instance-attribute`
```
translation = MosaicoField(
description="3D translation vector."
)
```
The 3D translation vector component.
###### Querying with the **`.Q` Proxy**
Translation components are queryable through the `translation` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `Transform.Q.translation.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Transform.Q.translation.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Transform.Q.translation.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### rotation`class-attribute``instance-attribute`
```
rotation = MosaicoField(
description="Quaternion representing rotation."
)
```
The rotation quaternion component (x, y, z, w).
###### Querying with the **`.Q` Proxy**
Rotation components are queryable through the `rotation` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `Transform.Q.rotation.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Transform.Q.rotation.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Transform.Q.rotation.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Transform.Q.rotation.w` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### target_frame_id`class-attribute``instance-attribute`
```
target_frame_id = MosaicoField(
default=None, description="Target frame identifier."
)
```
Target coordinate frame identifier.
| Field Access Path | Queryable Type | Supported Operators |
| `Transform.Q.target_frame_id` | `String` | `.eq()`, `.match()`, `.in_()`, `.lt()`, `.gt()`, `.leq()`, `.geq()` |
#### covariance`class-attribute``instance-attribute`
```
covariance = MosaicoField(
default=None,
nullable=True,
description="The covariance matrix (flattened) of the data.",
)
```
Optional list of 64-bit floats representing the flattened matrix.
###### Querying with the **`.Q` Proxy**
#### covariance_type`class-attribute``instance-attribute`
```
covariance_type = MosaicoField(
default=None,
nullable=True,
description="Enum integer representing the covariance parameterization.",
)
```
Optional 16-bit integer representing the covariance enum.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional covariance type attribute.
###### Querying with the **`.Q` Proxy**
The `covariance_type` field is fully queryable via the **`.Q` Proxy**. The `` placeholder in the path represents any Mosaico class that exposes covariance information, either directly or through its internal fields.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.covariance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `CovarianceMixin` is integrated into your data structure:
- **Direct Inheritance**: Represents any class (e.g., `Vector3d`, `Quaternion`) that inherits directly from `CovarianceMixin`.
- **Composition (Nested Fields)**: When a complex model (like `IMU`) contains fields that are themselves covariance-aware, the proxy allows you to "drill down" to that specific attribute. For example, since `IMU.acceleration` is a `Vector3d`, you access its covariance type via `IMU.Q.acceleration.covariance_type`.
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### Pose
Bases: `Serializable`, `CovarianceMixin`
Represents the position and orientation of an object in a global or local frame.
While similar to a `Transform`, a `Pose` semantically denotes the **state** of an object (its current location and heading) rather than the mathematical shift between two frames.
Attributes:
| Name | Type | Description |
| `position` | `Point3d` | A `Point3d` representing the object's coordinates. |
| `orientation` | `Quaternion` | A `Quaternion` representing the object's heading. |
| `covariance` | `Optional[list_(float64)]` | Optional flattened 7x7 composed covariance matrix representing the uncertainty of the Translation+Rotation. |
| `covariance_type` | `Optional[int16]` | Enum integer representing the parameterization of the covariance matrix. |
###### Querying with the **`.Q` Proxy**
This class fields are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### position`class-attribute``instance-attribute`
```
position = MosaicoField(
description="3D translation vector."
)
```
The 3D position vector component.
###### Querying with the **`.Q` Proxy**
Position components are queryable through the `position` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `Pose.Q.position.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Pose.Q.position.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Pose.Q.position.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### orientation`class-attribute``instance-attribute`
```
orientation = MosaicoField(
description="Quaternion representing rotation."
)
```
The orientation quaternion component (x, y, z, w).
###### Querying with the **`.Q` Proxy**
Rotation components are queryable through the `orientation` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `Pose.Q.orientation.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Pose.Q.orientation.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Pose.Q.orientation.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Pose.Q.orientation.w` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### covariance`class-attribute``instance-attribute`
```
covariance = MosaicoField(
default=None,
nullable=True,
description="The covariance matrix (flattened) of the data.",
)
```
Optional list of 64-bit floats representing the flattened matrix.
###### Querying with the **`.Q` Proxy**
#### covariance_type`class-attribute``instance-attribute`
```
covariance_type = MosaicoField(
default=None,
nullable=True,
description="Enum integer representing the covariance parameterization.",
)
```
Optional 16-bit integer representing the covariance enum.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional covariance type attribute.
###### Querying with the **`.Q` Proxy**
The `covariance_type` field is fully queryable via the **`.Q` Proxy**. The `` placeholder in the path represents any Mosaico class that exposes covariance information, either directly or through its internal fields.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.covariance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `CovarianceMixin` is integrated into your data structure:
- **Direct Inheritance**: Represents any class (e.g., `Vector3d`, `Quaternion`) that inherits directly from `CovarianceMixin`.
- **Composition (Nested Fields)**: When a complex model (like `IMU`) contains fields that are themselves covariance-aware, the proxy allows you to "drill down" to that specific attribute. For example, since `IMU.acceleration` is a `Vector3d`, you access its covariance type via `IMU.Q.acceleration.covariance_type`.
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### Polygon
Bases: `Serializable`
Polygon geometry defined by a list of points.
Each point represents a vertex of the polygon in 3D space.
Attributes:
| Name | Type | Description |
| `points` | `list_(Point3d)` | List of polygon vertices. |
###### Querying with the **`.Q` Proxy**
The points field is not queryable via the `.Q` proxy (lists are not supported yet).
#### points`class-attribute``instance-attribute`
```
points = MosaicoField(
description="List of polygon vertices as 3D points."
)
```
List of polygon vertices as 3D points.
###### Querying with the **`.Q` Proxy**
The points field is not queryable via the `.Q` proxy (lists are not supported yet).
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.models.data.kinematics
Kinematics Data Structures.
This module defines structures for analyzing motion: 1. **Velocity (Twist)**: Linear and angular speed. 2. **Acceleration**: Linear and angular acceleration. 3. **MotionState**: A complete snapshot of an object's kinematics (Pose + Velocity + Acceleration).
These can be assigned to Message.data field to send data to the platform.
### Velocity
Bases: `Serializable`, `CovarianceMixin`
Represents 6-Degree-of-Freedom Velocity, commonly referred to as a Twist.
The `Velocity` class describes the instantaneous motion of an object, split into linear and angular components.
Attributes:
| Name | Type | Description |
| `linear` | `Optional[Vector3d]` | Optional `Vector3d` linear velocity vector. |
| `angular` | `Optional[Vector3d]` | Optional `Vector3d` angular velocity vector. |
| `covariance` | `Optional[list_(float64)]` | Optional flattened 3x3 covariance matrix representing the uncertainty of the point measurement. |
| `covariance_type` | `Optional[int16]` | Enum integer representing the parameterization of the covariance matrix. |
###### Querying with the **`.Q` Proxy**
This class fields are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### linear`class-attribute``instance-attribute`
```
linear = MosaicoField(
default=None, description="3D linear velocity vector."
)
```
3D linear velocity vector
###### Querying with the **`.Q` Proxy**
Linear components are queryable through the `linear` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `Velocity.Q.linear.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Velocity.Q.linear.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Velocity.Q.linear.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### angular`class-attribute``instance-attribute`
```
angular = MosaicoField(
default=None, description="3D angular velocity vector."
)
```
3D angular velocity vector
###### Querying with the **`.Q` Proxy**
Angular components are queryable through the `angular` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `Velocity.Q.angular.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Velocity.Q.angular.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Velocity.Q.angular.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### covariance`class-attribute``instance-attribute`
```
covariance = MosaicoField(
default=None,
nullable=True,
description="The covariance matrix (flattened) of the data.",
)
```
Optional list of 64-bit floats representing the flattened matrix.
###### Querying with the **`.Q` Proxy**
#### covariance_type`class-attribute``instance-attribute`
```
covariance_type = MosaicoField(
default=None,
nullable=True,
description="Enum integer representing the covariance parameterization.",
)
```
Optional 16-bit integer representing the covariance enum.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional covariance type attribute.
###### Querying with the **`.Q` Proxy**
The `covariance_type` field is fully queryable via the **`.Q` Proxy**. The `` placeholder in the path represents any Mosaico class that exposes covariance information, either directly or through its internal fields.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.covariance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `CovarianceMixin` is integrated into your data structure:
- **Direct Inheritance**: Represents any class (e.g., `Vector3d`, `Quaternion`) that inherits directly from `CovarianceMixin`.
- **Composition (Nested Fields)**: When a complex model (like `IMU`) contains fields that are themselves covariance-aware, the proxy allows you to "drill down" to that specific attribute. For example, since `IMU.acceleration` is a `Vector3d`, you access its covariance type via `IMU.Q.acceleration.covariance_type`.
#### check_at_least_one_exists
```
check_at_least_one_exists()
```
Ensures the velocity object is not empty.
Raises:
| Type | Description |
| `ValueError` | If both `linear` and `angular` are None. |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### Acceleration
Bases: `Serializable`, `CovarianceMixin`
Represents 6-Degree-of-Freedom Acceleration.
This class provides a standardized way to transmit linear and angular acceleration data to the platform.
Attributes:
| Name | Type | Description |
| `linear` | `Optional[Vector3d]` | Optional 3D linear acceleration vector ($a_x, a_y, a_z$). |
| `angular` | `Optional[Vector3d]` | Optional 3D angular acceleration vector ($lpha_x, lpha_y, lpha_z$). |
| `covariance` | `Optional[list_(float64)]` | Optional flattened 3x3 covariance matrix representing the uncertainty of the point measurement. |
| `covariance_type` | `Optional[int16]` | Enum integer representing the parameterization of the covariance matrix. |
###### Querying with the **`.Q` Proxy**
This class fields are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### linear`class-attribute``instance-attribute`
```
linear = MosaicoField(
default=None,
description="3D linear acceleration vector.",
)
```
3D linear acceleration vector
###### Querying with the **`.Q` Proxy**
Linear components are queryable through the `linear` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `Acceleration.Q.linear.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Acceleration.Q.linear.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Acceleration.Q.linear.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### angular`class-attribute``instance-attribute`
```
angular = MosaicoField(
default=None,
description="3D angular acceleration vector.",
)
```
3D angular acceleration vector
###### Querying with the **`.Q` Proxy**
Angular components are queryable through the `angular` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `Acceleration.Q.angular.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Acceleration.Q.angular.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Acceleration.Q.angular.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### covariance`class-attribute``instance-attribute`
```
covariance = MosaicoField(
default=None,
nullable=True,
description="The covariance matrix (flattened) of the data.",
)
```
Optional list of 64-bit floats representing the flattened matrix.
###### Querying with the **`.Q` Proxy**
#### covariance_type`class-attribute``instance-attribute`
```
covariance_type = MosaicoField(
default=None,
nullable=True,
description="Enum integer representing the covariance parameterization.",
)
```
Optional 16-bit integer representing the covariance enum.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional covariance type attribute.
###### Querying with the **`.Q` Proxy**
The `covariance_type` field is fully queryable via the **`.Q` Proxy**. The `` placeholder in the path represents any Mosaico class that exposes covariance information, either directly or through its internal fields.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.covariance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `CovarianceMixin` is integrated into your data structure:
- **Direct Inheritance**: Represents any class (e.g., `Vector3d`, `Quaternion`) that inherits directly from `CovarianceMixin`.
- **Composition (Nested Fields)**: When a complex model (like `IMU`) contains fields that are themselves covariance-aware, the proxy allows you to "drill down" to that specific attribute. For example, since `IMU.acceleration` is a `Vector3d`, you access its covariance type via `IMU.Q.acceleration.covariance_type`.
#### check_at_least_one_exists
```
check_at_least_one_exists()
```
Ensures the acceleration object is not empty.
Raises:
| Type | Description |
| `ValueError` | If both `linear` and `angular` are None. |
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### MotionState
Bases: `Serializable`, `CovarianceMixin`
Aggregated Kinematic State.
`MotionState` groups `Pose`, `Velocity`, and optional `Acceleration` into a single atomic update.
This is the preferred structure for:
- **Trajectory Tracking**: Recording the high-fidelity path of a robot or vehicle.
- **State Estimation**: Logging the output of Kalman filters or SLAM algorithms.
- **Ground Truth**: Storing reference data from simulation environments.
Attributes:
| Name | Type | Description |
| `pose` | `Pose` | The 6D pose representing current position and orientation. |
| `velocity` | `Velocity` | The 6D velocity (Twist). |
| `target_frame_id` | `string` | A string identifier for the target coordinate frame. |
| `acceleration` | `Optional[Acceleration]` | Optional 6D acceleration. |
| `covariance` | `Optional[list_(float64)]` | Optional flattened NxN composed covariance matrix representing the uncertainty of the Pose+Velocity+[Acceleration] measurement. |
| `covariance_type` | `Optional[int16]` | Enum integer representing the parameterization of the covariance matrix. |
###### Querying with the **`.Q` Proxy**
This class fields are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### pose`class-attribute``instance-attribute`
```
pose = MosaicoField(
description="6D pose with optional time and covariance info."
)
```
The 6D pose representing current position and orientation.
###### Querying with the **`.Q` Proxy**
Pose components are queryable through the `pose` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `MotionState.Q.pose.position.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MotionState.Q.pose.position.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MotionState.Q.pose.position.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MotionState.Q.pose.orientation.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MotionState.Q.pose.orientation.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MotionState.Q.pose.orientation.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MotionState.Q.pose.orientation.w` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### velocity`class-attribute``instance-attribute`
```
velocity = MosaicoField(
description="6D velocity with optional time and covariance info."
)
```
The 6D velocity (Twist) describing instantaneous motion.
###### Querying with the **`.Q` Proxy**
Velocity components are queryable through the `velocity` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `MotionState.Q.velocity.linear.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MotionState.Q.velocity.linear.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MotionState.Q.velocity.linear.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MotionState.Q.velocity.angular.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MotionState.Q.velocity.angular.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MotionState.Q.velocity.angular.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### target_frame_id`class-attribute``instance-attribute`
```
target_frame_id = MosaicoField(
description="Target frame identifier."
)
```
Identifier for the destination coordinate frame.
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `MotionState.Q.target_frame_id` | `String` | `.eq()`, `.match()`, `.in_()`, `.lt()`, `.gt()`, `.leq()`, `.geq()` |
#### acceleration`class-attribute``instance-attribute`
```
acceleration = MosaicoField(
default=None,
description="6D acceleration with optional time and covariance info.",
)
```
Optional 6D acceleration components.
###### Querying with the **`.Q` Proxy**
Acceleration components are queryable through the `acceleration` field prefix if present.
| Field Access Path | Queryable Type | Supported Operators |
| `MotionState.Q.acceleration.linear.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MotionState.Q.acceleration.linear.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MotionState.Q.acceleration.linear.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MotionState.Q.acceleration.angular.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MotionState.Q.acceleration.angular.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `MotionState.Q.acceleration.angular.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### covariance`class-attribute``instance-attribute`
```
covariance = MosaicoField(
default=None,
nullable=True,
description="The covariance matrix (flattened) of the data.",
)
```
Optional list of 64-bit floats representing the flattened matrix.
###### Querying with the **`.Q` Proxy**
#### covariance_type`class-attribute``instance-attribute`
```
covariance_type = MosaicoField(
default=None,
nullable=True,
description="Enum integer representing the covariance parameterization.",
)
```
Optional 16-bit integer representing the covariance enum.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional covariance type attribute.
###### Querying with the **`.Q` Proxy**
The `covariance_type` field is fully queryable via the **`.Q` Proxy**. The `` placeholder in the path represents any Mosaico class that exposes covariance information, either directly or through its internal fields.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.covariance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `CovarianceMixin` is integrated into your data structure:
- **Direct Inheritance**: Represents any class (e.g., `Vector3d`, `Quaternion`) that inherits directly from `CovarianceMixin`.
- **Composition (Nested Fields)**: When a complex model (like `IMU`) contains fields that are themselves covariance-aware, the proxy allows you to "drill down" to that specific attribute. For example, since `IMU.acceleration` is a `Vector3d`, you access its covariance type via `IMU.Q.acceleration.covariance_type`.
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.models.data.dynamics
This module defines specialized ontology structures for representing physical dynamics, specifically linear forces and rotational moments (torques).
The primary structure, `ForceTorque`, implements a standard "Wrench" representation. These models are designed to be assigned to the `data` field of a `Message` for transmission to the platform.
**Key Features:** * **Wrench Representation**: Combines 3D linear force and 3D rotational torque into a single, synchronized state. * **Uncertainty Quantification**: Inherits from `CovarianceMixin` to support $6 imes 6$ covariance matrices, allowing for the transmission of sensor noise characteristics or estimation confidence.
### ForceTorque
Bases: `Serializable`, `CovarianceMixin`
Represents a Wrench (Force and Torque) applied to a rigid body.
The `ForceTorque` class is used to describe the total mechanical action (wrench) acting on a body at a specific reference point. By combining linear force and rotational torque, it provides a complete description of dynamics for simulation and telemetry.
Attributes:
| Name | Type | Description |
| `force` | `Vector3d` | A `Vector3d` representing the linear force vector in Newtons ($N$). |
| `torque` | `Vector3d` | A `Vector3d` representing the rotational moment vector in Newton-meters (Nm). |
| `covariance` | `Optional[list_(float64)]` | Optional flattened 6x6 composed covariance matrix representing the uncertainty of the force-torque measurement. |
| `covariance_type` | `Optional[int16]` | Enum integer representing the parameterization of the covariance matrix. |
###### Querying with the **`.Q` Proxy**
This class fields are queryable when constructing a `QueryOntologyCatalog` via the **`.Q` proxy**. Check the fields documentation for detailed description.
#### force`class-attribute``instance-attribute`
```
force = MosaicoField(description='3D linear force.')
```
3D linear force vector
###### Querying with the **`.Q` Proxy**
Force components are queryable through the `force` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `ForceTorque.Q.force.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `ForceTorque.Q.force.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `ForceTorque.Q.force.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### torque`class-attribute``instance-attribute`
```
torque = MosaicoField(description='3D torque vector.')
```
3D torque vector
###### Querying with the **`.Q` Proxy**
Torque components are queryable through the `torque` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `ForceTorque.Q.torque.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `ForceTorque.Q.torque.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `ForceTorque.Q.torque.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### covariance`class-attribute``instance-attribute`
```
covariance = MosaicoField(
default=None,
nullable=True,
description="The covariance matrix (flattened) of the data.",
)
```
Optional list of 64-bit floats representing the flattened matrix.
###### Querying with the **`.Q` Proxy**
#### covariance_type`class-attribute``instance-attribute`
```
covariance_type = MosaicoField(
default=None,
nullable=True,
description="Enum integer representing the covariance parameterization.",
)
```
Optional 16-bit integer representing the covariance enum.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional covariance type attribute.
###### Querying with the **`.Q` Proxy**
The `covariance_type` field is fully queryable via the **`.Q` Proxy**. The `` placeholder in the path represents any Mosaico class that exposes covariance information, either directly or through its internal fields.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.covariance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `CovarianceMixin` is integrated into your data structure:
- **Direct Inheritance**: Represents any class (e.g., `Vector3d`, `Quaternion`) that inherits directly from `CovarianceMixin`.
- **Composition (Nested Fields)**: When a complex model (like `IMU`) contains fields that are themselves covariance-aware, the proxy allows you to "drill down" to that specific attribute. For example, since `IMU.acceleration` is a `Vector3d`, you access its covariance type via `IMU.Q.acceleration.covariance_type`.
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### Inertia
Bases: `Serializable`
Inertia properties of a rigid body.
Includes mass, center of mass, and inertia tensor.
Attributes:
| Name | Type | Description |
| `mass` | `float64` | Mass of the object. |
| `center_of_mass` | `Vector3d` | Center of mass position. |
| `inertia` | `list_(float64, list_size=6)` | Inertia tensor (flattened 3x3 matrix). |
###### Querying with the **`.Q` Proxy**
Only scalar fields are queryable.
#### mass`class-attribute``instance-attribute`
```
mass = MosaicoField(description='Mass of the object.')
```
Mass of the object.
###### Querying with the **`.Q` Proxy**
The mass field is queryable.
| Field Access Path | Queryable Type | Supported Operators |
| `Inertia.Q.mass` | Numeric | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### center_of_mass`class-attribute``instance-attribute`
```
center_of_mass = MosaicoField(
description="Center of mass of the object."
)
```
Center of mass of the object.
###### Querying with the **`.Q` Proxy**
The center of mass is queryable via its components.
| Field Access Path | Queryable Type | Supported Operators |
| `Inertia.Q.center_of_mass.x` | Numeric | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Inertia.Q.center_of_mass.y` | Numeric | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Inertia.Q.center_of_mass.z` | Numeric | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
#### inertia`class-attribute``instance-attribute`
```
inertia = MosaicoField(
description="Inertia tensor components [ixx, ixy, ixz, iyy, iyz, izz]."
)
```
Inertia tensor represented by its 6 unique components [ixx, ixy, ixz, iyy, iyz, izz].
###### Querying with the **`.Q` Proxy**
This field is not queryable via the `.Q` proxy (lists are not supported yet).
#### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
#### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
---
# Platform Models
## mosaicolabs.models.platform.Topic`dataclass`
```
Topic(
user_metadata,
name,
sequence_name,
created_timestamp,
ontology_tag,
chunks_number,
serialization_format,
locked,
total_size_bytes,
)
```
Represents a read-only view of a server-side Topic platform resource.
The `Topic` class provides access to topic-specific system metadata, such as the ontology tag (e.g., 'imu', 'camera') and the serialization format. It serves as a metadata-rich view of an individual data stream within the platform catalog.
##### Querying with **Query Builders**
Querying Topic specific attributes (like `user_metadata` or `name`) can be made using the QueryTopic() query builder.
### user_metadata`instance-attribute`
```
user_metadata
```
Custom user-defined key-value pairs associated with the entity.
###### Querying with **Query Builders**
Querying the `user_metadata` attribute can be made using the `QueryTopic.with_user_metadata()` query builder.
### name`instance-attribute`
```
name
```
The unique identifier or resource name of the entity.
###### Querying with **Query Builders**
The `name` attribute is queryable when constructing a `QueryTopic` via the convenience methods:
- `QueryTopic.with_name()`
- `QueryTopic.with_name_match()`
### sequence_name`instance-attribute`
```
sequence_name
```
The name of the parent sequence containing this topic.
###### Querying with **Query Builders**
The `sequence_name` attribute is queryable queryable when constructing a `QuerySequence` via the convenience methods:
- `QuerySequence.with_name()`
- `QuerySequence.with_name_match()`
### created_timestamp`instance-attribute`
```
created_timestamp
```
The UTC timestamp indicating when the entity was created on the server.
###### Querying with **Query Builders**
The `created_timestamp` attribute is queryable when constructing a `QueryTopic` via the convenience method:
- `QueryTopic.with_created_timestamp()`
### ontology_tag`instance-attribute`
```
ontology_tag
```
The ontology type identifier (e.g., 'imu', 'gnss').
This corresponds to the `__ontology_tag__` defined in the `Serializable` class registry.
###### Querying with **Query Builders**
The `ontology_tag` attribute is queryable when constructing a `QueryTopic` via the convenience method:
- `QueryTopic.with_ontology_tag()`.
### chunks_number`instance-attribute`
```
chunks_number
```
The number of physical data chunks stored for this topic.
May be `None` if the server did not provide detailed storage statistics.
###### Querying with **Query Builders**
The `chunks_number` attribute is not queryable.
### serialization_format`instance-attribute`
```
serialization_format
```
The format used to serialize the topic data (e.g., 'arrow', 'image').
This corresponds to the `SerializationFormat` enum.
###### Querying with **Query Builders**
The `serialization_format` attribute is not queryable.
### locked`instance-attribute`
```
locked
```
Indicates if the topic resource is locked on the server.
A locked state typically occurs after data writing is completed, preventing structural modifications.
###### Querying with **Query Builders**
The `locked` attribute is not queryable.
### total_size_bytes`instance-attribute`
```
total_size_bytes
```
The total physical storage footprint of the entity on the server in bytes.
###### Querying with **Query Builders**
The `total_size_bytes` attribute is not queryable.
## mosaicolabs.models.platform.Session`dataclass`
```
Session(
locator,
created_timestamp,
locked,
completed_timestamp,
topics,
)
```
Represents a read-only view of a server-side writing Session platform resource.
The `Session` class is designed to hold system-level metadata. It serves as the primary metadata container for a logical grouping of topics written in the writing session.
##### Querying with the **`.Q` Proxy**
The session fields are not queryable via the **`.Q` proxy**.
### locator`instance-attribute`
```
locator
```
The session locator.
The locator is in the form '`sequence_name`:`session_identifier`', e.g.: 'test-sequence-datastream:01KQ9XQ0HJ3V39F87CBP6PYA1T'
### created_timestamp`instance-attribute`
```
created_timestamp
```
The UTC timestamp [ns] when the writing session started
### locked`instance-attribute`
```
locked
```
The locked/unlocked status of the session
### completed_timestamp`instance-attribute`
```
completed_timestamp
```
The UTC timestamp [ns] of the session finalization.
### topics`instance-attribute`
```
topics
```
The list of topics recorded during this writing session
## mosaicolabs.models.platform.Sequence`dataclass`
```
Sequence(
user_metadata,
created_timestamp,
name,
total_size_bytes,
sessions,
)
```
Represents a read-only view of a server-side Sequence platform resource.
The `Sequence` class is designed to hold system-level metadata and enable fluid querying of user-defined properties. It serves as the primary metadata container for a logical grouping of related topics.
##### Querying with **Query Builders**
Querying Sequence specific attributes (like `user_metadata` or `name`) can be made using the QuerySequence() query builder.
### user_metadata`instance-attribute`
```
user_metadata
```
Custom user-defined key-value pairs associated with the entity.
###### Querying with **Query Builders**
The `user_metadata` attribute is queryable when constructing a `QuerySequence` via the convenience method:
- `QuerySequence.with_user_metadata()`
### created_timestamp`instance-attribute`
```
created_timestamp
```
The UTC timestamp when the sequence was created.
###### Querying with **Query Builders**
```
The `created_timestamp` attribute is queryable when constructing a [`QuerySequence`][mosaicolabs.models.query.QuerySequence]
via the convenience method:
* [`QuerySequence.with_created_timestamp()`][mosaicolabs.models.query.builders.QuerySequence.with_created_timestamp]
Example:
```python
from mosaicolabs import MosaicoClient, QuerySequence, Time
with MosaicoClient.connect("localhost", 6726) as client:
# Filter for a specific sequence creation time
qresponse = client.query(
QuerySequence().with_created_timestamp(time_start=Time.from_float(1765432100)),
)
# Inspect the response
if qresponse is not None:
# Results are automatically grouped by Sequence for easier data management
for item in qresponse:
print(f"Sequence: {item.sequence.name}")
print(f"Topics: {[topic.name for topic in item.topics]}")
```
```
### name`instance-attribute`
```
name
```
The name of the sequence.
###### Querying with **Query Builders**
```
The `name` attribute is queryable when constructing a [`QuerySequence`][mosaicolabs.models.query.QuerySequence]
via the convenience methods:
* [`QuerySequence.with_name()`][mosaicolabs.models.query.builders.QuerySequence.with_name]
* [`QuerySequence.with_name_match()`][mosaicolabs.models.query.builders.QuerySequence.with_name_match]
Example:
```python
from mosaicolabs import MosaicoClient, QuerySequence
with MosaicoClient.connect("localhost", 6726) as client:
# Filter for a specific data value (using constructor)
qresponse = client.query(
QuerySequence().with_name_match("test_winter_2025_01_"),
)
# Inspect the response
if qresponse is not None:
# Results are automatically grouped by Sequence for easier data management
for item in qresponse:
print(f"Sequence: {item.sequence.name}")
print(f"Topics: {[topic.name for topic in item.topics]}")
```
```
### total_size_bytes`instance-attribute`
```
total_size_bytes
```
The aggregated total size of the sequence in bytes
###### Querying with **Query Builders**
```
The `total_size_bytes` attribute is not queryable.
```
### sessions`instance-attribute`
```
sessions
```
The list of sessions in the sequence
###### Querying with **Query Builders**
```
The `sessions` attribute is not queryable.
```
### topics`property`
```
topics
```
Returns the list of names for all topics contained within this sequence.
###### Querying with **Query Builders**
The `topics` property is queryable via the `QueryTopic` builder, through the convenience methods:
- `QueryTopic.with_name()`
- `QueryTopic.with_name_match()`
### updated_timestamps`property`
```
updated_timestamps
```
The UTC timestamps indicating when the entity was updated on the server.
###### Querying with **Query Builders**
The `updated_timestamps` property is not queryable.
---
# Sensors Models
## mosaicolabs.models.sensors.IMU
Bases: `Serializable`
Inertial Measurement Unit data.
This model aggregates raw or estimated motion data from accelerometers and gyroscopes, providing a high-frequency snapshot of an object's inertial state.
Attributes:
| Name | Type | Description |
| `acceleration` | `Vector3d` | Linear acceleration vector [ax, ay, az] in $m/s^2$. |
| `angular_velocity` | `Vector3d` | Angular velocity vector [wx, wy, wz] in $rad/s$. |
| `orientation` | `Optional[Quaternion]` | Optional estimated orientation expressed as a quaternion. |
##### Querying with the **`.Q` Proxy**
This class is fully queryable via the **`.Q` proxy**. You can filter IMU data based on physical thresholds or metadata within a `QueryOntologyCatalog`.
### acceleration`class-attribute``instance-attribute`
```
acceleration = MosaicoField(
description="Linear acceleration vector [ax, ay, az] in m/s^2."
)
```
Linear acceleration component.
###### Querying with the **`.Q` Proxy**
Acceleration components are queryable through the `acceleration` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `IMU.Q.acceleration.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `IMU.Q.acceleration.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `IMU.Q.acceleration.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### angular_velocity`class-attribute``instance-attribute`
```
angular_velocity = MosaicoField(
description="Angular velocity vector [wx, wy, wz] in rad/s."
)
```
Angular velocity component.
###### Querying with the **`.Q` Proxy**
Angular velocities components are queryable through the `angular_velocity` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `IMU.Q.angular_velocity.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `IMU.Q.angular_velocity.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `IMU.Q.angular_velocity.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### orientation`class-attribute``instance-attribute`
```
orientation = MosaicoField(
default=None,
description="Estimated orientation [qx, qy, qz, qw].",
)
```
Estimated orientation [qx, qy, qz, qw] (optional).
###### Querying with the **`.Q` Proxy**
Estimated orientation components are queryable through the `orientation` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `IMU.Q.orientation.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `IMU.Q.orientation.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `IMU.Q.orientation.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `IMU.Q.orientation.w` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.models.sensors.Joy
Bases: `Serializable`
Joystick input data.
This class represents the state of a joystick, including axis values and button states.
Attributes:
| Name | Type | Description |
| `axes` | `list_(float32)` | Continuous axis values (e.g., joystick positions). |
| `buttons` | `list_(int32)` | Discrete button states (pressed or not pressed). |
##### Querying with the **`.Q` Proxy**
Joystick data cannot be queried via the `.Q` proxy since list fields are not supported yet.
### axes`class-attribute``instance-attribute`
```
axes = MosaicoField(
description="The axes measurements from a joystick."
)
```
Continuous axis values of the joystick.
###### Querying with the **`.Q` Proxy**
The axes field is not queryable via the `.Q` proxy (lists are not supported yet).
### buttons`class-attribute``instance-attribute`
```
buttons = MosaicoField(
description="The buttons measurements from a joystick."
)
```
Discrete button states (1 = pressed, 0 = released).
###### Querying with the **`.Q` Proxy**
The buttons field is not queryable via the `.Q` proxy (lists are not supported yet).
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.models.sensors.GPSStatus
Bases: `Serializable`
Status of the GNSS receiver and satellite fix.
This class encapsulates quality metrics and operational state of the GNSS receiver, including fix type, satellite usage, and precision dilution factors.
Attributes:
| Name | Type | Description |
| `status` | `int8` | Fix status indicator (e.g., No Fix, 2D, 3D). |
| `service` | `uint16` | Service used for the fix (e.g., GPS, GLONASS, Galileo). |
| `satellites` | `Optional[int8]` | Number of satellites currently visible or used in the solution. |
| `hdop` | `Optional[float64]` | Horizontal Dilution of Precision (lower is better). |
| `vdop` | `Optional[float64]` | Vertical Dilution of Precision (lower is better). |
##### Querying with the **`.Q` Proxy**
This class is fully queryable via the **`.Q` proxy**. You can filter status data based on fix quality or precision metrics within a `QueryOntologyCatalog`.
### status`class-attribute``instance-attribute`
```
status = MosaicoField(description='Fix status.')
```
Fix status.
###### Querying with the **`.Q` Proxy**
The fix status is queryable via the `status` field.
| Field Access Path | Queryable Type | Supported Operators |
| `GPSStatus.Q.status` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### service`class-attribute``instance-attribute`
```
service = MosaicoField(
description="Service used (GPS, GLONASS, etc)."
)
```
Service used (GPS, GLONASS, etc).
###### Querying with the **`.Q` Proxy**
The service identifier is queryable via the `service` field.
| Field Access Path | Queryable Type | Supported Operators |
| `GPSStatus.Q.service` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### satellites`class-attribute``instance-attribute`
```
satellites = MosaicoField(
default=None, description="Satellites visible/used."
)
```
Satellites visible/used.
###### Querying with the **`.Q` Proxy**
Satellite count is queryable via the `satellites` field.
| Field Access Path | Queryable Type | Supported Operators |
| `GPSStatus.Q.satellites` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### hdop`class-attribute``instance-attribute`
```
hdop = MosaicoField(
default=None,
description="Horizontal Dilution of Precision.",
)
```
Horizontal Dilution of Precision.
###### Querying with the **`.Q` Proxy**
HDOP values are queryable via the `hdop` field.
| Field Access Path | Queryable Type | Supported Operators |
| `GPSStatus.Q.hdop` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### vdop`class-attribute``instance-attribute`
```
vdop = MosaicoField(
default=None,
description="Vertical Dilution of Precision.",
)
```
Vertical Dilution of Precision.
###### Querying with the **`.Q` Proxy**
VDOP values are queryable via the `vdop` field.
| Field Access Path | Queryable Type | Supported Operators |
| `GPSStatus.Q.vdop` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.models.sensors.GPS
Bases: `Serializable`
Processed GNSS fix containing Position, Velocity, and Status.
This class serves as the primary container for geodetic location data (WGS 84) and receiver state information.
Attributes:
| Name | Type | Description |
| `position` | `Point3d` | Lat/Lon/Alt (WGS 84) represented as a `Point3d`. |
| `velocity` | `Optional[Vector3d]` | Velocity vector [North, East, Alt] in $m/s$. |
| `status` | `Optional[GPSStatus]` | Receiver status info including fix type and satellite count. |
##### Querying with the **`.Q` Proxy**
This class is fully queryable via the **`.Q` proxy**. You can filter GPS data based on geodetic coordinates or signal quality within a `QueryOntologyCatalog`.
### position`class-attribute``instance-attribute`
```
position = MosaicoField(description="Lat/Lon/Alt (WGS 84).")
```
Lat/Lon/Alt (WGS 84).
###### Querying with the **`.Q` Proxy**
Position components are queryable through the `position` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `GPS.Q.position.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `GPS.Q.position.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `GPS.Q.position.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### velocity`class-attribute``instance-attribute`
```
velocity = MosaicoField(
default=None,
description="Velocity vector [North, East, Alt] m/s.",
)
```
Velocity vector [North, East, Alt] m/s.
###### Querying with the **`.Q` Proxy**
Velocity components are queryable through the `velocity` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `GPS.Q.velocity.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `GPS.Q.velocity.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `GPS.Q.velocity.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### status`class-attribute``instance-attribute`
```
status = MosaicoField(
default=None, description="Receiver status info."
)
```
Receiver status information.
###### Querying with the **`.Q` Proxy**
Status components are queryable through the `status` field prefix.
| Field Access Path | Queryable Type | Supported Operators |
| `GPS.Q.status.satellites` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `GPS.Q.status.hdop` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `GPS.Q.status.vdop` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `GPS.Q.status.status` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `GPS.Q.status.service` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.models.sensors.NMEASentence
Bases: `Serializable`
Raw NMEA 0183 sentence string.
Attributes:
| Name | Type | Description |
| `sentence` | `string` | The NMEA 0183 sentence string. |
##### Querying with the **`.Q` Proxy**
This class is fully queryable via the **`.Q` proxy**. You can filter NMEA data based on the sentence content within a `QueryOntologyCatalog`.
| Field Access Path | Queryable Type | Supported Operators |
| `NMEASentence.Q.sentence` | `String` | `.eq()`, `.match()`, `.in_()`, `.lt()`, `.gt()`, `.leq()`, `.geq()` |
### sentence`class-attribute``instance-attribute`
```
sentence = MosaicoField(description='Raw ASCII sentence.')
```
Raw ASCII sentence.
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.models.sensors.Magnetometer
Bases: `Serializable`
Magnetic field measurement data.
This class represents the magnetic field measurements from a magnetometer sensor.
Attributes:
| Name | Type | Description |
| `magnetic_field` | `Vector3d` | Magnetic field vector [mx, my, mz] in microTesla. |
##### Querying with the **`.Q` Proxy**
This class is fully queryable via the **`.Q` proxy**. You can filter magnetometer data based on magnetic field values within a `QueryOntologyCatalog`.
### magnetic_field`class-attribute``instance-attribute`
```
magnetic_field = MosaicoField(
description="Magnetic field vector [mx, my, mz] in microTesla."
)
```
Magnetic field vector [mx, my, mz] in microTesla.
###### Querying with the **`.Q` Proxy**
The magnetic field vector is queryable via the `magnetic_field` field.
| Field Access Path | Queryable Type | Supported Operators |
| `Magnetometer.Q.magnetic_field.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Magnetometer.Q.magnetic_field.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `Magnetometer.Q.magnetic_field.z` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.models.sensors.Pressure
Bases: `Serializable`, `VarianceMixin`
Represents a physical pressure value. The internal representation is always stored in **Pascals (Pa)**.
Users are encouraged to use the `from_*` factory methods when initializing pressure values expressed in units other than Pascals.
Attributes:
| Name | Type | Description |
| `value` | `float` | Pressure value in **Pascals (Pa)**. When using the constructor directly, the value **must** be provided in Pascals. |
| `variance` | `Optional[float]` | The variance of the data. |
| `variance_type` | `Optional[int]` | Enum integer representing the variance parameterization. |
##### Querying with the **`.Q` Proxy**
This class is fully queryable via the **`.Q` proxy**. You can filter pressure data based on pressure values within a `QueryOntologyCatalog`.
### variance`class-attribute``instance-attribute`
```
variance = MosaicoField(
default=None,
nullable=True,
description="The variacne of the data.",
)
```
Optional 64-bit float representing the variance of the data.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional variance attribute.
###### Querying with the **`.Q` Proxy**
The `variance` field is queryable with the **`.Q` Proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.variance` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `VarianceMixin` is integrated into the data structure:
- **Direct Inheritance**: Used for classes like `Pressure` or `Temperature` that inherit directly from `VarianceMixin` to represent 1D uncertainty.
- **Composition (Nested Access)**: If a complex model contains a field that is a subclass of `VarianceMixin`, the proxy allows you to traverse the hierarchy to that specific attribute.
### variance_type`class-attribute``instance-attribute`
```
variance_type = MosaicoField(
default=None,
nullable=True,
description="Enum integer representing the variance parameterization.",
)
```
Optional 16-bit integer representing the variance parameterization.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional covariance type attribute.
###### Querying with the **`.Q` Proxy**
The `variance_type` field is fully queryable via the **`.Q` Proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.variance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `VarianceMixin` is integrated into the data structure:
- **Direct Inheritance**: Used for classes like `Pressure` or `Temperature` that inherit directly from `VarianceMixin` to represent 1D uncertainty.
- **Composition (Nested Access)**: If a complex model contains a field that is a subclass of `VarianceMixin`, the proxy allows you to traverse the hierarchy to that specific attribute.
### value`class-attribute``instance-attribute`
```
value = MosaicoField(
description="The absolute pressure reading from the sensor in Pascals."
)
```
The absolute pressure reading from the sensor in Pascals.
###### Querying with the **`.Q` Proxy**
The pressure value is queryable via the `value` field.
| Field Access Path | Queryable Type | Supported Operators |
| `Pressure.Q.value` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### from_atm`classmethod`
```
from_atm(*, value, variance=None, variance_type=None)
```
Creates a `Pressure` instance using the value in Atm and converting it in Pascal using the formula `Pascal = Atm * 101325`.
Parameters:
| Name | Type | Description | Default |
| `value` | `float` | The pressure value in Atm. | *required* |
| `variance` | `Optional[float]` | The variance of the data. | `None` |
| `variance_type` | `Optional[int]` | Enum integer representing the variance parameterization. | `None` |
Returns:
| Name | Type | Description |
| `Pressure` | `Pressure` | A `Pressure` instance with value in Pascal. |
### from_bar`classmethod`
```
from_bar(*, value, variance=None, variance_type=None)
```
Creates a `Pressure` instance using the value in Bar and converting it in Pascal using the formula `Pascal = Bar * 100000`.
Parameters:
| Name | Type | Description | Default |
| `value` | `float` | The pressure value in Bar. | *required* |
| `variance` | `Optional[float]` | The variance of the data. | `None` |
| `variance_type` | `Optional[int]` | Enum integer representing the variance parameterization. | `None` |
Returns:
| Name | Type | Description |
| `Pressure` | `Pressure` | A `Pressure` instance with value in Pascal. |
### from_psi`classmethod`
```
from_psi(*, value, variance=None, variance_type=None)
```
Creates a `Pressure` instance using the value in Psi and converting it in Pascal using the formula `Pascal = Psi * 6894.7572931783`.
Parameters:
| Name | Type | Description | Default |
| `value` | `float` | The pressure value in Psi. | *required* |
| `variance` | `Optional[float]` | The variance of the data. | `None` |
| `variance_type` | `Optional[int]` | Enum integer representing the variance parameterization. | `None` |
Returns:
| Name | Type | Description |
| `Pressure` | `Pressure` | A `Pressure` instance with value in Pascal. |
### to_atm
```
to_atm()
```
Converts and returns the `Pressure` value in Atm using the formula `Atm = Pascal / 101325`.
Returns:
| Name | Type | Description |
| `float` | `float` | The `Pressure` value in Atm. |
### to_bar
```
to_bar()
```
Converts and returns the `Pressure` value in Bar using the formula `Bar = Pascal / 100000`.
Returns:
| Name | Type | Description |
| `float` | `float` | The `Pressure` value in Bar. |
### to_psi
```
to_psi()
```
Converts and returns the `Pressure` value in Psi using the formula `Psi = Pascal / 6894.7572931783`.
Returns:
| Name | Type | Description |
| `float` | `float` | The `Pressure` value in Psi. |
## mosaicolabs.models.sensors.Range
Bases: `Serializable`, `VarianceMixin`
Represents a range measurement that defines a valid distance interval between the minimum and the maximum value. This with also the field of view, the radiation type and the range value. The internal representation is always stored in **meters (m)**.
Attributes:
| Name | Type | Description |
| `radiation_type` | `int` | Which type of radiation the sensor used. |
| `field_of_view` | `float` | The arc angle, in **Radians (rad)**, over which the distance reading is valid. |
| `min_range` | `float` | Minimum range value in **Meters (m)**. Fixed distance means that the minimum range must be equal to the maximum range. |
| `max_range` | `float` | Maximum range value in **Meters (m)**. Fixed distance means that the minimum range must be equal to the maximum range. |
| `range` | `float` | Range value in **Meters (m)**. |
| `variance` | `Optional[float]` | The variance of the data. |
| `variance_type` | `Optional[int]` | Enum integer representing the variance parameterization. |
##### Querying with the **`.Q` Proxy**
This class is fully queryable via the **`.Q` proxy**. You can filter range data based on range parameters within a `QueryOntologyCatalog`.
### variance`class-attribute``instance-attribute`
```
variance = MosaicoField(
default=None,
nullable=True,
description="The variacne of the data.",
)
```
Optional 64-bit float representing the variance of the data.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional variance attribute.
###### Querying with the **`.Q` Proxy**
The `variance` field is queryable with the **`.Q` Proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.variance` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `VarianceMixin` is integrated into the data structure:
- **Direct Inheritance**: Used for classes like `Pressure` or `Temperature` that inherit directly from `VarianceMixin` to represent 1D uncertainty.
- **Composition (Nested Access)**: If a complex model contains a field that is a subclass of `VarianceMixin`, the proxy allows you to traverse the hierarchy to that specific attribute.
### variance_type`class-attribute``instance-attribute`
```
variance_type = MosaicoField(
default=None,
nullable=True,
description="Enum integer representing the variance parameterization.",
)
```
Optional 16-bit integer representing the variance parameterization.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional covariance type attribute.
###### Querying with the **`.Q` Proxy**
The `variance_type` field is fully queryable via the **`.Q` Proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.variance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `VarianceMixin` is integrated into the data structure:
- **Direct Inheritance**: Used for classes like `Pressure` or `Temperature` that inherit directly from `VarianceMixin` to represent 1D uncertainty.
- **Composition (Nested Access)**: If a complex model contains a field that is a subclass of `VarianceMixin`, the proxy allows you to traverse the hierarchy to that specific attribute.
### radiation_type`class-attribute``instance-attribute`
```
radiation_type = MosaicoField(
description="Which type of radiation the sensor used."
)
```
Which type of radiation the sensor used.
###### Querying with the **`.Q` Proxy**
The radiation_type is queryable via the `radiation_type` field.
| Field Access Path | Queryable Type | Supported Operators |
| `Range.Q.radiation_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### field_of_view`class-attribute``instance-attribute`
```
field_of_view = MosaicoField(
description="The arc angle, in radians, over which the distance reading is valid."
)
```
The arc angle, in radians, over which the distance reading is valid.
###### Querying with the **`.Q` Proxy**
The field_of_view is queryable via the `field_of_view` field.
| Field Access Path | Queryable Type | Supported Operators |
| `Range.Q.field_of_view` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### min_range`class-attribute``instance-attribute`
```
min_range = MosaicoField(
description="Minimum range value in meters. Fixed distance means that the minimum rangemust be equal to the maximum range."
)
```
Minimum range value in meters. Fixed distance means that the minimum range must be equal to the maximum range.
###### Querying with the **`.Q` Proxy**
The min_range is queryable via the `min_range` field.
| Field Access Path | Queryable Type | Supported Operators |
| `Range.Q.min_range` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### max_range`class-attribute``instance-attribute`
```
max_range = MosaicoField(
description="Maximum range value in meters. Fixed distance means that the minimum rangemust be equal to the maximum range."
)
```
Maximum range value in meters. Fixed distance means that the minimum range must be equal to the maximum range.
###### Querying with the **`.Q` Proxy**
The max_range is queryable via the `max_range` field.
| Field Access Path | Queryable Type | Supported Operators |
| `Range.Q.max_range` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### range`class-attribute``instance-attribute`
```
range = MosaicoField(description='Range value in meters.')
```
Range value in meters.
###### Querying with the **`.Q` Proxy**
The range is queryable via the `range` field.
| Field Access Path | Queryable Type | Supported Operators |
| `Range.Q.range` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### validate_min_and_max_range
```
validate_min_and_max_range()
```
Ensures that `min_range` is smaller or equal to `max_range`.
### validate_range
```
validate_range()
```
Ensures that `range` is between `min_range` and `max_range`.
## mosaicolabs.models.sensors.Temperature
Bases: `Serializable`, `VarianceMixin`
Represents a thermodynamic temperature. The internal representation is always stored in **Kelvin (K)**.
Users are encouraged to use the `from_*` factory methods when initializing temperature values expressed in units other than Kelvin.
Attributes:
| Name | Type | Description |
| `value` | `float` | Temperature value in **Kelvin (K)**. When using the constructor directly, the value **must** be provided in Kelvin. |
| `variance` | `Optional[float]` | The variance of the data. |
| `variance_type` | `Optional[int]` | Enum integer representing the variance parameterization. |
##### Querying with the **`.Q` Proxy**
This class is fully queryable via the **`.Q` proxy**. You can filter temperature data based on temperature values within a `QueryOntologyCatalog`.
### variance`class-attribute``instance-attribute`
```
variance = MosaicoField(
default=None,
nullable=True,
description="The variacne of the data.",
)
```
Optional 64-bit float representing the variance of the data.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional variance attribute.
###### Querying with the **`.Q` Proxy**
The `variance` field is queryable with the **`.Q` Proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.variance` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `VarianceMixin` is integrated into the data structure:
- **Direct Inheritance**: Used for classes like `Pressure` or `Temperature` that inherit directly from `VarianceMixin` to represent 1D uncertainty.
- **Composition (Nested Access)**: If a complex model contains a field that is a subclass of `VarianceMixin`, the proxy allows you to traverse the hierarchy to that specific attribute.
### variance_type`class-attribute``instance-attribute`
```
variance_type = MosaicoField(
default=None,
nullable=True,
description="Enum integer representing the variance parameterization.",
)
```
Optional 16-bit integer representing the variance parameterization.
This field is injected into the model via composition, ensuring that sensor data is paired with the optional covariance type attribute.
###### Querying with the **`.Q` Proxy**
The `variance_type` field is fully queryable via the **`.Q` Proxy**.
| Field Access Path | Queryable Type | Supported Operators |
| `.Q.variance_type` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
The `` placeholder adapts based on how the `VarianceMixin` is integrated into the data structure:
- **Direct Inheritance**: Used for classes like `Pressure` or `Temperature` that inherit directly from `VarianceMixin` to represent 1D uncertainty.
- **Composition (Nested Access)**: If a complex model contains a field that is a subclass of `VarianceMixin`, the proxy allows you to traverse the hierarchy to that specific attribute.
### value`class-attribute``instance-attribute`
```
value = MosaicoField(
description="Temperature value in Kelvin."
)
```
Temperature value in Kelvin.
###### Querying with the **`.Q` Proxy**
The temperature value is queryable via the `value` field.
| Field Access Path | Queryable Type | Supported Operators |
| `Temperature.Q.value` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### from_celsius`classmethod`
```
from_celsius(*, value, variance=None, variance_type=None)
```
Creates a `Temperature` instance using the value in Celsius and converting it in Kelvin using the formula `Kelvin = Celsius + 273.15`.
Parameters:
| Name | Type | Description | Default |
| `value` | `float` | The temperature value in Celsius. | *required* |
| `variance` | `Optional[float]` | The variance of the data. | `None` |
| `variance_type` | `Optional[int]` | Enum integer representing the variance parameterization. | `None` |
Returns:
| Name | Type | Description |
| `Temperature` | `Temperature` | A `Temperature` instance with value in Kelvin. |
### from_fahrenheit`classmethod`
```
from_fahrenheit(
*, value, variance=None, variance_type=None
)
```
Creates a `Temperature` instance using the value in Fahrenheit and converting it in Kelvin using the formula `Kelvin = (Fahrenheit - 32) * 5 / 9 + 273.15`.
Parameters:
| Name | Type | Description | Default |
| `value` | `float` | The temperature value in Celsius. | *required* |
| `variance` | `Optional[float]` | The variance of the data. | `None` |
| `variance_type` | `Optional[int]` | Enum integer representing the variance parameterization. | `None` |
Returns:
| Name | Type | Description |
| `Temperature` | `Temperature` | A `Temperature` instance with value in Kelvin. |
### to_celsius
```
to_celsius()
```
Converts and returns the `Temperature` value in Celsius using the formula `Celsius = Kelvin - 273.15`.
Returns:
| Name | Type | Description |
| `float` | `float` | The `Temperature` value in Celsius. |
### to_fahrenheit
```
to_fahrenheit()
```
Converts and returns the `Temperature` value in Fahrenheit using the formula `Fahrenheit = (Kelvin - 273.15) * 9 / 5 + 32`.
Returns:
| Name | Type | Description |
| `float` | `float` | The `Temperature` value in Fahrenheit. |
## mosaicolabs.models.sensors.RobotJoint
Bases: `Serializable`
Snapshot of robot joint states.
Arrays must be index-aligned (e.g., names[0] corresponds to positions[0]).
Attributes:
| Name | Type | Description |
| `names` | `list_(string)` | Names of the different robot joints |
| `positions` | `list_(float64)` | Positions ([rad] or [m]) of the different robot joints |
| `velocities` | `list_(float64)` | Velocities ([rad/s] or [m/s]) of the different robot joints |
| `efforts` | `list_(float64)` | Efforts ([N] or [N/m]) applied to the different robot joints |
##### Querying with the **`.Q` Proxy**
The robot joint states cannot be queried via the `.Q` proxy.
### names`class-attribute``instance-attribute`
```
names = MosaicoField(
description="Names of the different robot joints"
)
```
Names of the different robot joints
###### Querying with the **`.Q` Proxy**
The names are not queryable via the `.Q` proxy (Lists are not supported yet).
### positions`class-attribute``instance-attribute`
```
positions = MosaicoField(
description="Positions ([rad] or [m]) of the different robot joints"
)
```
Positions ([rad] or [m]) of the different robot joints
###### Querying with the **`.Q` Proxy**
The positions are not queryable via the `.Q` proxy (Lists are not supported yet).
### velocities`class-attribute``instance-attribute`
```
velocities = MosaicoField(
description="Velocities ([rad/s] or [m/s]) of the different robot joints"
)
```
Velocities ([rad/s] or [m/s]) of the different robot joints
###### Querying with the **`.Q` Proxy**
The velocities are not queryable via the `.Q` proxy (Lists are not supported yet).
### efforts`class-attribute``instance-attribute`
```
efforts = MosaicoField(
description="Efforts ([N] or [N*m]) applied to the different robot joints"
)
```
Efforts ([N] or [N*m]) applied to the different robot joints
###### Querying with the **`.Q` Proxy**
The efforts are not queryable via the `.Q` proxy (Lists are not supported yet).
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
## mosaicolabs.models.sensors.Image
Bases: `Serializable`
Represents raw, uncompressed image data.
This class provides a flattened, row-major binary representation of an image. It is designed to handle: 1. **Arbitrary Data Types**: From standard uint8 RGB to float32 Depth and uint16 IR. 2. **Memory Layouts**: Explicit control over `stride` (stride) and endianness (`is_bigendian`). 3. **Transport**: Can act as a container for RAW bytes or wrap them in lossless containers (PNG).
Attributes:
| Name | Type | Description |
| `data` | `bytes` | The flattened image memory buffer. |
| `format` | `ImageFormat` | The format used for serialization ('png' or 'raw'). |
| `width` | `int` | The width of the image in pixels. |
| `height` | `int` | The height of the image in pixels. |
| `stride` | `int` | Bytes per row. Essential for alignment. |
| `encoding` | `str` | Pixel format (e.g., 'bgr8', 'mono16'). |
| `is_bigendian` | `bool` | True if data is Big-Endian. Defaults to system endianness if null. |
##### Querying with the **`.Q` Proxy**
This class is fully queryable via the **`.Q` proxy**. You can filter image data based on image parameters within a `QueryOntologyCatalog`.
### data`class-attribute``instance-attribute`
```
data = MosaicoField(
description="The flattened image memory buffer."
)
```
The flattened image memory buffer.
###### Querying with the **`.Q` Proxy**
The data is not queryable via the `data` field (bytes are not comparable).
### format`class-attribute``instance-attribute`
```
format = MosaicoField(
description="Container format (e.g., 'raw', 'png')."
)
```
The format used for serialization ('png' or 'raw').
###### Querying with the **`.Q` Proxy**
The format is queryable via the `format` field.
| Field Access Path | Queryable Type | Supported Operators |
| `Image.Q.format` | `String` | `.eq()`, `.match()`, `.in_()`, `.lt()`, `.gt()`, `.leq()`, `.geq()` |
### width`class-attribute``instance-attribute`
```
width = MosaicoField(description='Image width in pixels.')
```
The width of the image in pixels.
###### Querying with the **`.Q` Proxy**
The width is queryable via the `width` field.
| Field Access Path | Queryable Type | Supported Operators |
| `Image.Q.width` | `Numeric` | `.eq()`, `.gt()`, `.gte()`, `.lt()`, `.lte()`, `.between()` |
### height`class-attribute``instance-attribute`
```
height = MosaicoField(description="Image height in pixels.")
```
The height of the image in pixels.
###### Querying with the **`.Q` Proxy**
The height is queryable via the `height` field.
| Field Access Path | Queryable Type | Supported Operators |
| `Image.Q.height` | `Numeric` | `.eq()`, `.gt()`, `.gte()`, `.lt()`, `.lte()`, `.between()` |
### stride`class-attribute``instance-attribute`
```
stride = MosaicoField(
description="Bytes per row. Essential for alignment."
)
```
The number of bytes per row of the image.
###### Querying with the **`.Q` Proxy**
The stride is queryable via the `stride` field.
| Field Access Path | Queryable Type | Supported Operators |
| `Image.Q.stride` | `Numeric` | `.eq()`, `.gt()`, `.gte()`, `.lt()`, `.lte()`, `.between()` |
### encoding`class-attribute``instance-attribute`
```
encoding = MosaicoField(
description="Pixel format (e.g., 'bgr8', 'mono16')."
)
```
The pixel encoding (e.g., 'bgr8', 'mono16'). Optional field.
###### Querying with the **`.Q` Proxy**
The encoding is queryable via the `encoding` field.
| Field Access Path | Queryable Type | Supported Operators |
| `Image.Q.encoding` | `String` | `.eq()`, `.match()`, `.in_()`, `.lt()`, `.gt()`, `.leq()`, `.geq()` |
### is_bigendian`class-attribute``instance-attribute`
```
is_bigendian = MosaicoField(
default=None,
description="True if data is Big-Endian. Defaults to system endianness if null.",
)
```
Store if the original data is Big-Endian. Optional field.
###### Querying with the **`.Q` Proxy**
The is_bigendian is queryable via the `is_bigendian` field.
| Field Access Path | Queryable Type | Supported Operators |
| `Image.Q.is_bigendian` | `Boolean` | `.eq()`, `.neq()` |
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### from_linear_pixels`classmethod`
```
from_linear_pixels(
data,
stride,
height,
width,
encoding,
is_bigendian=None,
format=_DEFAULT_IMG_FORMAT,
)
```
Encodes linear pixel uint8 data into the storage container.
**The "Wide Grayscale" Trick:** When saving complex types (like `float32` depth or `uint16` raw) into standard image containers like PNG, we cannot rely on standard RGB encoders as they might apply color corrections or bit-depth reductions.
Instead, this method treats the data as a raw byte stream. It reshapes the stream into a 2D "Grayscale" image where: - `Image_Height` = `Original_Height` - `Image_Width` = `Stride` (The full row stride in bytes)
This guarantees that every bit of the original memory (including padding) is preserved losslessly.
Parameters:
| Name | Type | Description | Default |
| `data` | `List[int]` | Flattened list of bytes (uint8). | *required* |
| `stride` | `int` | Row stride in bytes. | *required* |
| `height` | `int` | Image height. | *required* |
| `width` | `int` | Image width. | *required* |
| `encoding` | `str` | Pixel format string. | *required* |
| `format` | `ImageFormat` | Target container ('raw' or 'png'). | `_DEFAULT_IMG_FORMAT` |
Returns:
| Name | Type | Description |
| `Image` | `Image` | An instantiated object. |
### to_linear_pixels
```
to_linear_pixels()
```
Decodes the storage container back to a linear byte list.
Reverses the "Wide Grayscale" encoding to return the original, flattened memory buffer.
Returns:
| Type | Description |
| `List[int]` | List[int]: A list of uint8 integers representing the raw memory. |
### to_pillow
```
to_pillow()
```
Converts the raw binary data into a standard PIL Image.
This method performs the heavy lifting of interpretation: 1. **Decoding**: Unpacks the transport container (e.g., PNG -> bytes). 2. **Casting**: Interprets bytes according to `self.encoding` (e.g., as float32). 3. **Endianness**: Swaps bytes if the source endianness differs from the local CPU. 4. **Color Swap**: Converts BGR (common in OpenCV/Robotics) to RGB (required by PIL).
Returns:
| Type | Description |
| `Image` | PILImage.Image: A visualizable image object. |
Raises:
| Type | Description |
| `NotImplementedError` | If the encoding is unknown. |
| `ValueError` | If data size doesn't match dimensions. |
### from_pillow`classmethod`
```
from_pillow(
pil_image, target_encoding=None, output_format=None
)
```
Factory method to create an Image from a PIL object.
Automatically handles:
- Data flattening (row-major).
- Stride calculation.
- RGB to BGR conversion (if target_encoding requires it).
- Type casting (e.g., float -> uint8).
Parameters:
| Name | Type | Description | Default |
| `pil_image` | `Image` | Source image. | *required* |
| `target_encoding` | `Optional[str]` | Target pixel format (e.g., "bgr8"). | `None` |
| `output_format` | `Optional[ImageFormat]` | ('raw' or 'png'). | `None` |
Returns:
| Name | Type | Description |
| `Image` | `Image` | Populated data object. |
## mosaicolabs.models.sensors.CompressedImage
Bases: `Serializable`
Represents image data stored as a compressed binary blob (e.g. JPEG, PNG, H264, ...).
This class acts as a data container for encoded streams. It distinguishes between: 1. **Stateless Formats (JPEG, PNG, TIFF)**: Can be decoded directly via `.to_image()`. 2. **Stateful Formats (H.264, HEVC)**: Require a `StatefulDecodingSession` to maintain reference frames across multiple messages.
Attributes:
| Name | Type | Description |
| `data` | `bytes` | The compressed binary payload. |
| `format` | `str` | The format identifier string (e.g., 'jpeg', 'png'). |
##### Querying with the **`.Q` Proxy**
This class is fully queryable via the **`.Q` proxy**. You can filter image data based on image parameters within a `QueryOntologyCatalog`.
Example "Reading H264 `CompressedImage`":
```
from mosaicolabs import MosaicoClient, CompressedImage, StatefulDecodingSession
with MosaicoClient.connect("localhost", 6726) as client:
seq_handler = client.sequence_handler("multi_camera_mission")
# Initialize the session contextually with the data streamer
decoding_session = StatefulDecodingSession()
# Iterate through interleaved topics
for topic, msg in seq_handler.get_data_streamer():
img = msg.get_data(CompressedImage)
if img is None:
# It is not a CompressedImage
continue
if img.format in [ImageFormat.H264, ImageFormat.HEVC]:
# Use the session for stateful video decoding
# The 'context' parameter ensures we use the correct reference frames for this topic
pil_img = decoding_session.decode(
img_data=img.data,
format=img.format,
context=topic
)
else:
# Use standard stateless decoding for JPEG/PNG
pil_img = img.to_image()
if pil_img:
pil_img.show()
decoding_session.close()
```
### data`class-attribute``instance-attribute`
```
data = MosaicoField(
description="The serialized (compressed) image data as bytes."
)
```
The serialized (compressed) image data as bytes.
###### Querying with the **`.Q` Proxy**
The data is not queryable via the `data` field (bytes are not comparable).
### format`class-attribute``instance-attribute`
```
format = MosaicoField(
description="The compression format (e.g., 'jpeg', 'png')."
)
```
The compression format (e.g., 'jpeg', 'png').
###### Querying with the **`.Q` Proxy**
| Field Access Path | Queryable Type | Supported Operators |
| `CompressedImage.Q.format` | `String` | `.eq()`, `.match()`, `.in_()`, `.lt()`, `.gt()`, `.leq()`, `.geq()` |
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
### to_image
```
to_image(codec=None, **kwargs)
```
Decompresses the stored binary data into a usable PIL Image object.
This method serves as the standard interface for converting compressed binary blobs back into pixel data. It defaults to a stateless decoding approach suitable for independent image frames.
Parameters:
| Name | Type | Description | Default |
| `codec` | `Optional[Any]` | An optional codec instance implementing the `.decode(img_bytes, format, **kwargs)` interface. If `None`, it defaults to `_StatelessDefaultCodec`. This allows for the injection of custom, optimized, or hardware-accelerated decoders. | `None` |
| `**kwargs` | `Any` | Arbitrary keyword arguments passed directly to the codec's decode method (e.g., quality hints or specific decoder flags). | `{}` |
Returns:
| Type | Description |
| `Optional[Image]` | Optional[PILImage.Image]: A ready-to-use Pillow image object. Returns `None` if the data is empty, the format is stateful (and no compatible codec was provided), or decoding fails. |
Example "Reading PNG `CompressedImage`":
```
from mosaicolabs import MosaicoClient, CompressedImage
with MosaicoClient.connect("localhost", 6726) as client:
seq_handler = client.sequence_handler("multi_camera_mission")
# Iterate through interleaved topics
for topic, msg in seq_handler.get_data_streamer():
img = msg.get_data(CompressedImage)
if img is None:
# It is not a CompressedImage
continue
# Standard usage for JPEG/PNG
pil_img = img.to_image()
```
Example "Reading H264 `CompressedImage`":
```
from mosaicolabs import MosaicoClient, CompressedImage, StatefulDecodingSession
with MosaicoClient.connect("localhost", 6726) as client:
seq_handler = client.sequence_handler("multi_camera_mission")
# Initialize the session contextually with the data streamer
decoding_session = StatefulDecodingSession()
# Iterate through interleaved topics
for topic, msg in seq_handler.get_data_streamer():
img = msg.get_data(CompressedImage)
if img is None:
# It is not a CompressedImage
continue
if img.format in [ImageFormat.H264, ImageFormat.HEVC]:
# Use the session for stateful video decoding
# The 'context' parameter ensures we use the correct reference frames for this topic
pil_img = decoding_session.decode(
img_data=img.data,
format=img.format,
context=topic
)
else:
# Use standard stateless decoding for JPEG/PNG
pil_img = img.to_image()
if pil_img:
pil_img.show()
decoding_session.close()
```
### from_image`classmethod`
```
from_image(image, format=PNG, **kwargs)
```
Factory method to create a CompressedImage from a PIL Image.
NOTE: The function use the _DefaultCodec which is valid for stateless formats only ('png', 'jpeg', ...). If dealing with a stateful compressed image, the conversion must be made via user defined encoding algorithms.
Parameters:
| Name | Type | Description | Default |
| `image` | `Image` | The source Pillow image. | *required* |
| `format` | `ImageFormat` | The target compression format (default: 'jpeg'). | `PNG` |
| `**kwargs` | `Any` | Additional arguments passed to the codec's encode method (e.g., quality=90). | `{}` |
Returns:
| Name | Type | Description |
| `CompressedImage` | `CompressedImage` | A new instance containing the compressed bytes. |
Raises:
| Type | Description |
| `ValueError` | If no codec is found or encoding fails. |
## mosaicolabs.models.sensors.StatefulDecodingSession
```
StatefulDecodingSession()
```
Manages the stateful decoding of video streams for a specific reading session.
Unlike standard image formats (JPEG/PNG), video encodings like H.264 and HEVC utilize temporal compression (P-frames and B-frames), which require a persistent decoding state (reference frames).
This class maintains unique `av.CodecContext` instances for each provided context string (typically the `topic_name`), ensuring that interleaved frames from multiple video topics do not interfere with each other.
### decode
```
decode(*, img_bytes, format, context)
```
Decodes stateful compressed image data (video frames) using a persistent temporal context.
It utilizes the `context` string to look up or initialize a persistent `av.CodecContext`. This ensures that P-frames and B-frames are correctly applied to the reference frames of their specific stream.
Parameters:
| Name | Type | Description | Default |
| `img_bytes` | `bytes` | The raw compressed binary blob extracted from a `CompressedImage` message. | *required* |
| `format` | `ImageFormat` | The encoding format. Expected to be a stateful format supported by the session (e.g., `ImageFormat.H264` or `ImageFormat.HEVC`). | *required* |
| `context` | `str` | A unique identifier for the data stream, typically the `topic_name`. This key isolates the decoding state to prevent memory corruption when frames from multiple sources are interleaved in the same processing loop. | *required* |
Returns:
| Type | Description |
| `Optional[Image]` | Optional[PILImage.Image]: - A `PIL.Image.Image` object containing the decoded frame. - `None` if the format is unsupported, the data is corrupted, or the frame is a non-visual packet (e.g., internal metadata). |
### close
```
close()
```
Explicitly release resources (optional, GC usually handles this).
## mosaicolabs.models.sensors.ImageFormat
Bases: `str`, `Enum`
Defines the supported encoding and container formats for image data.
The enum differentiates between **Stateless** formats (independent frames) and **Stateful** formats (video streams with temporal dependencies).
### RAW`class-attribute``instance-attribute`
```
RAW = 'raw'
```
Uncompressed pixel data. Represents a raw buffer of pixels (e.g., RGB, BGR, or Grayscale).
### PNG`class-attribute``instance-attribute`
```
PNG = 'png'
```
Portable Network Graphics. A lossless compression format suitable for masks, overlays, and synthetic data where pixel perfection is required.
### JPEG`class-attribute``instance-attribute`
```
JPEG = 'jpeg'
```
Joint Photographic Experts Group. The standard lossy compression format for natural images, balancing file size and visual quality.
### TIFF`class-attribute``instance-attribute`
```
TIFF = 'tiff'
```
Tagged Image File Format. Preferred for high-bit depth (16-bit) or scientific data where metadata preservation is critical.
### H264`class-attribute``instance-attribute`
```
H264 = 'h264'
```
Advanced Video Coding (AVC). A stateful format using inter-frame compression. Requires a `StatefulDecodingSession` to maintain temporal context.
### HEVC`class-attribute``instance-attribute`
```
HEVC = 'hevc'
```
High Efficiency Video Coding (H.265). A high-performance stateful format. Requires a `StatefulDecodingSession` and provides superior compression to H.264.
## mosaicolabs.models.sensors.CameraInfo
Bases: `Serializable`
Meta-information for interpreting images from a calibrated camera.
This structure mirrors standard robotics camera models (e.g., ROS `sensor_msgs/CameraInfo`). It enables pipelines to rectify distorted images or project 3D points onto the 2D image plane.
Attributes:
| Name | Type | Description |
| `height` | `uint32` | Height in pixels of the image with which the camera was calibrated |
| `width` | `uint32` | Width in pixels of the image with which the camera was calibrated |
| `distortion_model` | `string` | The distortion model used |
| `distortion_parameters` | `list_(float64)` | The distortion coefficients (k1, k2, t1, t2, k3...). Size depends on the model. |
| `intrinsic_parameters` | `list_(float64, list_size=9)` | The 3x3 Intrinsic Matrix (K) flattened row-major. |
| `rectification_parameters` | `list_(float64, list_size=9)` | The 3x3 Rectification Matrix (R) flattened row-major. |
| `projection_parameters` | `list_(float64, list_size=12)` | The 3x4 Projection Matrix (P) flattened row-major. |
| `binning` | `Optional[Vector2d]` | Hardware binning factor (x, y). If null, assumes (0, 0) (no binning). |
| `roi` | `Optional[ROI]` | Region of Interest. Used if the image is a sub-crop of the full resolution. |
##### Querying with the **`.Q` Proxy**
This class is fully queryable via the **`.Q` proxy**. You can filter camera data based on camera parameters within a `QueryOntologyCatalog`.
### height`class-attribute``instance-attribute`
```
height = MosaicoField(
description="Height in pixels of the image with which the camera was calibrated."
)
```
Height in pixels of the image with which the camera was calibrated
###### Querying with the **`.Q` Proxy**
The height is queryable via the `height` field.
| Field Access Path | Queryable Type | Supported Operators |
| `CameraInfo.Q.height` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### width`class-attribute``instance-attribute`
```
width = MosaicoField(
description="Width in pixels of the image with which the camera was calibrated."
)
```
Width in pixels of the image with which the camera was calibrated
###### Querying with the **`.Q` Proxy**
The width is queryable via the `width` field.
| Field Access Path | Queryable Type | Supported Operators |
| `CameraInfo.Q.width` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### distortion_model`class-attribute``instance-attribute`
```
distortion_model = MosaicoField(
description="The distortion model used (e.g., 'plumb_bob', 'rational_polynomial')."
)
```
The distortion model used
###### Querying with the **`.Q` Proxy**
The distortion model is queryable via the `distortion_model` field.
| Field Access Path | Queryable Type | Supported Operators |
| `CameraInfo.Q.distortion_model` | `String` | `.eq()`, `.match()`, `.in_()`, `.lt()`, `.gt()`, `.leq()`, `.geq()` |
### distortion_parameters`class-attribute``instance-attribute`
```
distortion_parameters = MosaicoField(
description="The distortion coefficients (k1, k2, t1, t2, k3...). Size depends on the model."
)
```
The distortion coefficients (k1, k2, t1, t2, k3...). Size depends on the model.
###### Querying with the **`.Q` Proxy**
The distortion parameters are not queryable via the `.Q` proxy (Lists are not supported yet).
### intrinsic_parameters`class-attribute``instance-attribute`
```
intrinsic_parameters = MosaicoField(
description="The 3x3 Intrinsic Matrix (K) flattened row-major. Projects 3D points in the camera coordinate frame to 2D pixel coordinates."
)
```
The 3x3 Intrinsic Matrix (K) flattened row-major.
###### Querying with the **`.Q` Proxy**
The intrinsic parameters are not queryable via the `.Q` proxy (Lists are not supported yet).
### rectification_parameters`class-attribute``instance-attribute`
```
rectification_parameters = MosaicoField(
description="The 3x3 Rectification Matrix (R) flattened row-major. Used for stereo cameras to align the two image planes."
)
```
The 3x3 Rectification Matrix (R) flattened row-major.
###### Querying with the **`.Q` Proxy**
The rectification parameters cannot be queried via the `.Q` proxy (Lists are not supported yet).
### projection_parameters`class-attribute``instance-attribute`
```
projection_parameters = MosaicoField(
description="The 3x4 Projection Matrix (P) flattened row-major. Projects 3D world points directly into the rectified image pixel coordinates."
)
```
The 3x4 Projection Matrix (P) flattened row-major.
###### Querying with the **`.Q` Proxy**
The projection parameters cannot be queried via the `.Q` proxy (Lists are not supported yet).
### binning`class-attribute``instance-attribute`
```
binning = MosaicoField(
default=None,
description="Hardware binning factor (x, y). If null, assumes (0, 0) (no binning).",
)
```
Hardware binning factor (x, y). If null, assumes (0, 0) (no binning).
###### Querying with the **`.Q` Proxy**
The binning parameters are queryable via the `binning` field.
| Field Access Path | Queryable Type | Supported Operators |
| `CameraInfo.Q.binning.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `CameraInfo.Q.binning.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### roi`class-attribute``instance-attribute`
```
roi = MosaicoField(
default=None,
description="Region of Interest. Used if the image is a sub-crop of the full resolution.",
)
```
Region of Interest. Used if the image is a sub-crop of the full resolution.
###### Querying with the **`.Q` Proxy**
The roi parameters are queryable via the `roi` field.
| Field Access Path | Queryable Type | Supported Operators |
| `CameraInfo.Q.roi.offset.x` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `CameraInfo.Q.roi.offset.y` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `CameraInfo.Q.roi.width` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
| `CameraInfo.Q.roi.height` | `Numeric` | `.eq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` |
### is_registered`classmethod`
```
is_registered()
```
Checks if a class is registered.
Returns:
| Name | Type | Description |
| `bool` | `bool` | True if registered. |
### ontology_tag`classmethod`
```
ontology_tag()
```
Retrieves the unique identifier (tag) for the current ontology class, automatically generated during class definition.
This method provides the string key used by the Mosaico platform to identify and route specific data types within the ontology registry. It abstracts away the internal naming conventions, ensuring that you always use the correct identifier for queries and serialization.
Returns:
| Type | Description |
| `str` | The registered string tag for this class (e.g., `"imu"`, `"gps"`). |
Raises:
| Type | Description |
| `Exception` | If the class was not properly initialized via `__pydantic_init_subclass__`. |
---
# Query Builders
## mosaicolabs.models.query.builders
This module provides the high-level "Fluent" API for constructing complex searches across the Mosaico Data Platform.
It implements a Domain-Specific Language that allows users to filter **Sequences**, **Topics**, and **Ontology** data using a type-safe, method-chaining interface.
**Key Components:**
- **`Query`**: The root container that aggregates multiple specialized sub-queries.
- **`QueryOntologyCatalog`**: For fine-grained filtering based on sensor-specific field values (e.g., `IMU.Q.acceleration.x > 9.8`).
- **`QueryTopic`**: Specifically for filtering topic-level metadata.
- **`QuerySequence`**: Specifically for filtering sequence-level metadata.
### QueryOntologyCatalog
```
QueryOntologyCatalog(
*expressions, include_timestamp_range=None
)
```
A top-level query object for the Data Catalog that combines multiple sensor-field expressions.
This builder allows for fine-grained filtering based on the actual values contained within sensor payloads (e.g., IMU acceleration, GPS coordinates, or custom telemetry). It produces a "flat" dictionary output where field paths utilize dot-notation (e.g., `"imu.acceleration.x"`).
This class is designed to work with the **`.Q` query proxy** injected into every `Serializable` data ontology model. You can use this proxy on any registered sensor class (like `IMU`, `Vector3d`, `Point3d`), etc. to create type-safe expressions.
The constructor initializes the query with an optional list of `_QueryCatalogExpression` objects, generated via `.Q.` proxy, where model is any of the available data ontology (e.g. IMU.Q, GPS.Q, String.Q, etc.)
Parameters:
| Name | Type | Description | Default |
| `*expressions` | `_QueryExpression` | A variable number of expressions, generated via the `.Q` proxy on an ontology model. | `()` |
| `include_timestamp_range` | `Optional[bool]` | If `True`, the server will return the `start` and `end` timestamps corresponding to the temporal bounds of the matched data. | `None` |
Raises:
| Type | Description |
| `TypeError` | If an expression is not of the supported type. |
| `ValueError` | If an operator does not start with the required '$' prefix. |
| `NotImplementedError` | If a duplicate key (field path) is detected within the same query. |
#### with_expression
```
with_expression(expr)
```
Adds a new `_QueryCatalogExpression` expression to the query using a fluent interface.
Parameters:
| Name | Type | Description | Default |
| `expr` | `_QueryExpression` | A valid expression generated via the `.Q` proxy on an ontology model, e.g., `GPS.Q.status.satellites.leq(10)`. | *required* |
Returns:
| Type | Description |
| `QueryOntologyCatalog` | The `QueryOntologyCatalog` instance for method chaining. |
#### name
```
name()
```
Returns the top-level key ('ontology') used for nesting inside a root `Query`.
#### to_dict
```
to_dict()
```
Serializes the ontology expressions into a flat dictionary for the platform API.
Returns:
| Type | Description |
| `Dict[str, Any]` | A dictionary containing all merged sensor-field expressions. |
### QueryTopic
```
QueryTopic()
```
A top-level query object for Topic data that combines multiple expressions with a logical AND.
This builder handles the complex partitioning required to query both flat system fields (like `name` or `ontology_tag`) and nested dictionary fields (like `user_metadata`). The resulting dictionary output preserves this hierarchical structure for server-side processing.
The constructor initializes an empty query builder
#### with_user_metadata
```
with_user_metadata(key, **operator_kwargs)
```
Appends a metadata filter to the query using a fluent, operator-based interface.
This method simplifies metadata discovery by allowing direct filtering on the `user_metadata` dictionary of the Topic. Each call adds a logical AND condition to the query.
Parameters:
| Name | Type | Description | Default |
| `key` | `str` | The metadata key to filter on (e.g., "sensor_id"). Supports dot-notation for nested dictionary access (e.g., "calibration.focal_length"). | *required* |
| `**operator_kwargs` | `Any` | A single keyword argument where the key is the operator and the value is the comparison target, e.g. `eq="value"`, `lt=100`, `ex=False`, etc. | `{}` |
Raises:
| Type | Description |
| `ValueError` | If no operator is provided, if multiple operators are provided in a single call, or if an unsupported operator is used. |
Returns:
| Name | Type | Description |
| `QueryTopic` | `QueryTopic` | The current instance to support method chaining. |
#### with_name
```
with_name(name)
```
Adds an exact match filter for the topic 'name' field.
Parameters:
| Name | Type | Description | Default |
| `name` | `str` | The exact name of the topic to match. | *required* |
Returns:
| Type | Description |
| `QueryTopic` | The `QueryTopic` instance for method chaining. |
#### with_name_match
```
with_name_match(name)
```
Adds a partial (fuzzy) match filter for the topic 'name' field.
This performs an 'in-between' search (equivalent to %name%) on the full `sequence/topic` path.
Parameters:
| Name | Type | Description | Default |
| `name` | `str` | The string pattern to search for within the topic name. | *required* |
Returns:
| Type | Description |
| `QueryTopic` | The `QueryTopic` instance for method chaining. |
#### with_ontology_tag
```
with_ontology_tag(ontology_tag)
```
Adds an exact match filter for the 'ontology_tag' field.
This filter restricts the search to topics belonging to a specific data type identifier (e.g., 'imu', 'gnss').
Parameters:
| Name | Type | Description | Default |
| `ontology_tag` | `str` | The string tag (e.g., 'imu', 'gps') to filter by. | *required* |
Returns:
| Type | Description |
| `QueryTopic` | The `QueryTopic` instance for method chaining. |
#### with_created_timestamp
```
with_created_timestamp(time_start=None, time_end=None)
```
Adds a filter for the 'created_at_ns' field using high-precision Time.
Parameters:
| Name | Type | Description | Default |
| `time_start` | `Optional[Time]` | Optional lower bound (inclusive). | `None` |
| `time_end` | `Optional[Time]` | Optional upper bound (inclusive). | `None` |
Returns:
| Type | Description |
| `QueryTopic` | The `QueryTopic` instance for method chaining. |
Raises:
| Type | Description |
| `ValueError` | If both bounds are None or if `time_start > time_end`. |
#### name
```
name()
```
Returns the top-level key ('topic') used when nesting this query inside a root `Query`.
#### to_dict
```
to_dict()
```
Serializes the query into a nested dictionary for the platform API.
This method partitions expressions into two groups:
- **System Fields**: Standard fields like `name` are kept in the root dictionary.
- **Metadata Fields**: Fields starting with a dictionary-type model key (e.g., `user_metadata`) are stripped of their prefix and nested under that key.
Returns:
| Type | Description |
| `Dict[str, Any]` | A dictionary representation of the query, e.g., `{"locator": {"$eq": "..."}, "user_metadata": {"key": {"$eq": "..."}}}`. |
### QuerySequence
```
QuerySequence()
```
A top-level query object for Sequence data that combines multiple expressions with a logical AND.
This builder handles the complex partitioning required to query both flat system fields (like `name`) and nested dictionary fields (like `user_metadata`). The resulting dictionary output preserves this hierarchical structure for server-side processing.
The constructor initializes an empty query builder
#### with_user_metadata
```
with_user_metadata(key, **operator_kwargs)
```
Appends a metadata filter to the query using a fluent, operator-based interface.
This method simplifies metadata discovery by allowing direct filtering on the `user_metadata` dictionary of the Sequence. Each call adds a logical AND condition to the query.
Parameters:
| Name | Type | Description | Default |
| `key` | `str` | The metadata key to filter on (e.g., "project"). Supports dot-notation for nested dictionary access (e.g., "vehicle.id"). | *required* |
| `**operator_kwargs` | `Any` | A single keyword argument where the key is the operator and the value is the comparison target, e.g. `eq="value"`, `lt=100`, etc. | `{}` |
Raises:
| Type | Description |
| `ValueError` | If no operator is provided, if multiple operators are provided in a single call, or if an unsupported operator is used. |
Returns:
| Name | Type | Description |
| `QuerySequence` | `QuerySequence` | The current instance to support method chaining. |
#### with_name
```
with_name(name)
```
Adds an exact match filter for the sequence 'name' field.
Parameters:
| Name | Type | Description | Default |
| `name` | `str` | The exact name of the sequence to match. | *required* |
Returns:
| Type | Description |
| `QuerySequence` | The `QuerySequence` instance for method chaining. |
#### with_name_match
```
with_name_match(name)
```
Adds a partial (fuzzy) match filter for the sequence 'name' field.
This performs an 'in-between' search (equivalent to %name%) on the sequence name.
Parameters:
| Name | Type | Description | Default |
| `name` | `str` | The string pattern to search for within the sequence name. | *required* |
Returns:
| Type | Description |
| `QuerySequence` | The `QuerySequence` instance for method chaining. |
#### with_created_timestamp
```
with_created_timestamp(time_start=None, time_end=None)
```
Adds a filter for the 'created_at_ns' field using high-precision Time.
Parameters:
| Name | Type | Description | Default |
| `time_start` | `Optional[Time]` | Optional lower bound (inclusive). | `None` |
| `time_end` | `Optional[Time]` | Optional upper bound (inclusive). | `None` |
Returns:
| Type | Description |
| `QuerySequence` | The `QuerySequence` instance for method chaining. |
Raises:
| Type | Description |
| `ValueError` | If both bounds are `None` or if `time_start > time_end`. |
#### name
```
name()
```
Returns the top-level key ('sequence') used for nesting inside a root `Query`.
#### to_dict
```
to_dict()
```
Serializes the query into a nested dictionary for the platform API.
This method partitions expressions into:
- **Normal Fields**: Fields like `name` are kept in a flat dictionary.
- **Metadata Fields**: Fields targeting `user_metadata` are collected and nested.
Returns:
| Type | Description |
| `Dict[str, Any]` | A dictionary representation preserving the hierarchical structure. |
### Query
```
Query(*queries)
```
A top-level "root" query object that aggregates multiple specialized sub-queries into a single request body.
This class serves as the final envelope for multi-domain queries, ensuring that different query types (Topic, Sequence, Ontology) do not overwrite each other.
Initializes the root query with a set of sub-queries.
Parameters:
| Name | Type | Description | Default |
| `*queries` | `QueryableProtocol` | A variable number of sub-query objects (e.g., `QueryTopic()`, `QuerySequence()`). | `()` |
Raises:
| Type | Description |
| `ValueError` | If duplicate query types are detected in the initial arguments. |
#### append
```
append(*queries)
```
Adds additional sub-queries to the existing root query.
Parameters:
| Name | Type | Description | Default |
| `*queries` | `QueryableProtocol` | Additional sub-query instances. | `()` |
Raises:
| Type | Description |
| `ValueError` | If an appended query type is already present in the request. |
#### to_dict
```
to_dict()
```
Serializes the entire multi-domain query into the final JSON dictionary.
It orchestrates the conversion by calling the `.name()` and `.to_dict()` methods of each contained sub-query.
Returns:
| Type | Description |
| `Dict[str, Any]` | The final aggregated query dictionary. |
---
# Internal Types
## mosaicolabs.models.query.protocols.QueryableProtocol
Bases: `Protocol`
Structural protocol for classes that integrate into a multi-domain `Query`.
A class implicitly satisfies this protocol if it provides a unique identification tag via `name()` and a serialization method via `to_dict()`. This protocol ensures that the root `Query` or the can orchestrate complex requests without knowing the specific internal logic of each sub-query.
##### Reference Implementations
The following classes are standard examples of this protocol:
- `QueryTopic`: Filters Topic-level metadata.
- `QuerySequence`: Filters Sequence-level metadata.
- `QueryOntologyCatalog`: Filters fine-grained sensor field data.
### name
```
name()
```
Returns the unique key identifying this sub-query within the root request.
Examples include `"topic"`, `"sequence"`, or `"ontology"`.
### to_dict
```
to_dict()
```
Serializes the internal expressions into a platform-compatible dictionary.
## mosaicolabs.models.query.expressions._QueryExpression
```
_QueryExpression(full_path, op, value)
```
Base class for all atomic comparison operations in the Mosaico Query DSL.
A `_QueryExpression` represents the smallest indivisible unit of a query. It is typically not instantiated directly by the user, but is instead the result of a terminal method call on a queryable field (e.g., `.gt()`, `.eq()`, `.between()`) via the **`.Q` query proxy**.
The class manages the expression lifecycle in a Query:
- **Generation**: A user calls `IMU.Q.acceleration.x.gt(9.8)`, which generates a `_QueryCatalogExpression` (a subclass of this class).
- **Validation**: A Builder receives the expression and validates its type, operator format, and key uniqueness.
- **Serialization**: The builder calls `.to_dict()` on the expression to transform it into the specific JSON format expected by the platform.
Attributes:
| Name | Type | Description |
| `full_path` | | The complete, dot-separated path to the target field on the platform. |
| `op` | | The Mosaico-compliant operator string (e.g., `"$eq"`, `"$gt"`, `"$between"`). |
| `value` | | The comparison value or data structure (e.g., a constant, a list for `$in`, or a range for `$between`). |
Initializes an atomic comparison.
Parameters:
| Name | Type | Description | Default |
| `full_path` | `str` | The dot-separated field path used in the final query dictionary. | *required* |
| `op` | `str` | The short-string operation identifier (must start with `$`). | *required* |
| `value` | `Any` | The constant value for the comparison. | *required* |
### to_dict
```
to_dict()
```
Converts the expression into its final dictionary format.
## mosaicolabs.models.query.expressions._QueryTopicExpression
```
_QueryTopicExpression(full_path, op, value)
```
Bases: `_QueryExpression`
An atomic comparison unit specialized for the **Topic Catalog** context.
This class is utilized exclusively by the `QueryTopic` builder to filter topics based on system attributes (like `name` or `ontology_tag`) and nested user metadata.
The `QueryTopic` class enforces that all provided expressions are instances of this type to prevent cross-domain query contamination.
**Internal Translation Example:**
| User Call | Internal Translation |
| `QueryTopic().with_user_metadata("calibrated", eq=True)` | `_QueryTopicExpression("user_metadata.calibrated", "$eq", True)` |
| `QueryTopic().with_name("camera_front")` | `_QueryTopicExpression("name", "$eq", "camera_front")` |
| `QueryTopic().with_ontology_tag("imu")` | `_QueryTopicExpression("ontology_tag", "$eq", "imu")` |
Initializes an atomic comparison.
Parameters:
| Name | Type | Description | Default |
| `full_path` | `str` | The dot-separated field path used in the final query dictionary. | *required* |
| `op` | `str` | The short-string operation identifier (must start with `$`). | *required* |
| `value` | `Any` | The constant value for the comparison. | *required* |
### to_dict
```
to_dict()
```
Converts the expression into its final dictionary format.
## mosaicolabs.models.query.expressions._QuerySequenceExpression
```
_QuerySequenceExpression(full_path, op, value)
```
Bases: `_QueryExpression`
An atomic comparison unit specialized for the **Sequence Catalog** context.
This class represents filters targeting high-level sequence containers. It is the only expression type accepted by the `QuerySequence` builder.
It handles fields such as the sequence `name`, `created_timestamp`, or custom entries within the sequence's `user_metadata`.
**Internal Translation Example:**
| User Call | Internal Translation |
| `QuerySequence().with_user_metadata("project", eq="Apollo")` | `_QuerySequenceExpression("user_metadata.project", "$eq", "Apollo")` |
| `QuerySequence().with_name("Apollo")` | `_QuerySequenceExpression("name", "$eq", "Apollo")` |
| `QuerySequence().with_created_timestamp(Time.from_float(1704067200.0))` | `_QuerySequenceExpression("created_timestamp", "$between", [1704067200.0, None])` |
Initializes an atomic comparison.
Parameters:
| Name | Type | Description | Default |
| `full_path` | `str` | The dot-separated field path used in the final query dictionary. | *required* |
| `op` | `str` | The short-string operation identifier (must start with `$`). | *required* |
| `value` | `Any` | The constant value for the comparison. | *required* |
### to_dict
```
to_dict()
```
Converts the expression into its final dictionary format.
## mosaicolabs.models.query.expressions._QueryCatalogExpression
```
_QueryCatalogExpression(full_path, op, value)
```
Bases: `_QueryExpression`
An atomic comparison unit specialized for **Data Ontology** (Sensor Payload) filtering.
This expression type is used by the `QueryOntologyCatalog` builder to filter actual sensor data values across the entire platform.
Because ontology queries target specific fields within a sensor payload (e.g., accelerometer readings), these expressions use fully qualified dot-notated paths prefixed by the ontology tag.
**Internal Translation Example:**
| User Call | Internal Translation |
| `IMU.Q.acceleration.x.gt(9.8)` | `_QueryCatalogExpression("imu.acceleration.x", "$gt", 9.8)` |
| `IMU.Q.acceleration.y.gt(9.8)` | `_QueryCatalogExpression("imu.acceleration.y", "$gt", 9.8)` |
| `IMU.Q.acceleration.z.gt(9.8)` | `_QueryCatalogExpression("imu.acceleration.z", "$gt", 9.8)` |
| `IMU.Q.acceleration.x.gt(9.8)` | `_QueryCatalogExpression("imu.acceleration.x", "$gt", 9.8)` |
Initializes an atomic comparison.
Parameters:
| Name | Type | Description | Default |
| `full_path` | `str` | The dot-separated field path used in the final query dictionary. | *required* |
| `op` | `str` | The short-string operation identifier (must start with `$`). | *required* |
| `value` | `Any` | The constant value for the comparison. | *required* |
### to_dict
```
to_dict()
```
Converts the expression into its final dictionary format.
---
# Query Response
## mosaicolabs.models.query.response
### TimestampRange`dataclass`
```
TimestampRange(start, end)
```
Represents a temporal window defined by a start and end timestamp.
This utility class is used to define the bounds of sensor data or sequences within the Mosaico archive.
Attributes:
| Name | Type | Description |
| `start` | `int` | The beginning of the range (inclusive), typically in nanoseconds. |
| `end` | `int` | The end of the range (inclusive), typically in nanoseconds. |
### QueryResponseItemSequence`dataclass`
```
QueryResponseItemSequence(name)
```
Metadata container for a single sequence discovered during a query.
Attributes:
| Name | Type | Description |
| `name` | `str` | The unique identifier of the sequence in the Mosaico database. |
### QueryResponseItemTopic`dataclass`
```
QueryResponseItemTopic(name, timestamp_range)
```
Metadata for a specific topic (sensor stream) within a sequence.
Contains information about the topic's identity and its available time range in the archive.
Attributes:
| Name | Type | Description |
| `name` | `str` | The name of the topic (e.g., 'front_camera/image_raw'). |
| `timestamp_range` | `Optional[TimestampRange]` | The availability window of the data for this specific topic. |
### QueryResponseItem`dataclass`
```
QueryResponseItem(sequence, topics)
```
A unified result item representing a sequence and its associated topics.
This serves as the primary unit of data returned when querying the Mosaico metadata catalog.
Attributes:
| Name | Type | Description |
| `sequence` | `QueryResponseItemSequence` | The parent sequence metadata. |
| `topics` | `List[QueryResponseItemTopic]` | The list of topics available within this sequence that matched the query criteria. |
### QueryResponse`dataclass`
```
QueryResponse(items=list())
```
An iterable collection of results returned by a Mosaico metadata query.
This class provides convenience methods to transform search results back into query builders, enabling a fluid, multi-stage filtering workflow.
Attributes:
| Name | Type | Description |
| `items` | `List[QueryResponseItem]` | The list of items matching the query. |
#### to_query_sequence
```
to_query_sequence()
```
Converts the current response into a QuerySequence builder.
This allows for further filtering or operations on the specific set of sequences returned in this response.
Returns:
| Name | Type | Description |
| `QuerySequence` | `QuerySequence` | A builder initialized with an '$in' filter on the sequence names. |
Raises:
| Type | Description |
| `ValueError` | If the response is empty. |
#### to_query_topic
```
to_query_topic()
```
Converts the current response into a QueryTopic builder.
Useful for narrowing down a search to specific topics found within the retrieved sequences.
Returns:
| Name | Type | Description |
| `QueryTopic` | `QueryTopic` | A builder initialized with an '$in' filter on the topic names. |
Raises:
| Type | Description |
| `ValueError` | If the response is empty. |
#### is_empty
```
is_empty()
```
Returns True if the response contains no results.
---
# Machine Learning & Analytics
The **Mosaico ML** module serves as the high-performance bridge between the Mosaico Data Platform and the modern Data Science ecosystem. While the platform is optimized for high-speed raw message streaming, this module provides the abstractions necessary to transform asynchronous sensor data into tabular formats compatible with **Physical AI**, **Deep Learning**, and **Predictive Analytics**.
Working with robotics and multi-modal datasets presents three primary technical hurdles that the ML module is designed to solve:
* **Heterogeneous Sampling**: Sensors like LIDAR (low frequency), IMU (high frequency), and GPS (intermittent) operate at different rates.
* **High Volume**: Datasets often exceed the available system RAM.
* **Nested Structures**: Robotics data is typically deeply nested with coordinate transformations and covariance matrices.
## From Sequences to DataFrames
??? question "API Reference"
[`mosaicolabs.ml.DataFrameExtractor`][mosaicolabs.ml.DataFrameExtractor]
The [`DataFrameExtractor`][mosaicolabs.ml.DataFrameExtractor] is a specialized utility designed to convert Mosaico sequences into tabular formats. Unlike standard streamers that instantiate individual Python objects, this extractor operates at the **Batch Level** by pulling raw `RecordBatch` objects directly from the underlying stream to maximize throughput.
### Key Technical Features
* **Recursive Flattening**: Automatically "unpacks" deeply nested Mosaico Ontology structures into primitive columns.
* **Semantic Naming**: Columns use a `{topic_name}.{ontology_tag}.{field_path}` convention (e.g., `/front/camera/imu.imu.acceleration.x`) to remain self-describing.
* **Namespace Isolation**: Topic names are included in column headers to prevent collisions when multiple sensors of the same type are present.
* **Memory-Efficient Windowing**: Uses a generator-based approach to yield data in time-based "chunks" (e.g., 5-second windows) while handling straddling batches via a carry-over buffer.
* **Sparse Merging**: Creates a "sparse" DataFrame containing the union of all timestamps, using `NaN` for missing sensor readings at specific intervals.
This example demonstrates iterating through a sequence in 10-second tabular chunks.
```python
from mosaicolabs import MosaicoClient
from mosaicolabs.ml import DataFrameExtractor
with MosaicoClient.connect("localhost", 6726):
# Initialize from an existing SequenceHandler
seq_handler = client.sequence_handler("drive_session_01")
extractor = DataFrameExtractor(seq_handler)
# Iterate through 10-second chunks
for df in extractor.to_pandas_chunks(window_sec=10.0):
# 'df' is a pandas DataFrame with semantic columns
# Example: df["/front/camera/imu.imu.acceleration.x"]
print(f"Processing chunk with {len(df)} rows")
```
For complex types like images that require specialized decoding, Mosaico allows you to "inflate" a flattened DataFrame row back into a strongly-typed `Message` object.
```python
from mosaicolabs import MosaicoClient
from mosaicolabs.ml import DataFrameExtractor
from mosaicolabs.models import Message, Image
with MosaicoClient.connect("localhost", 6726):
# Initialize from an existing SequenceHandler
seq_handler = client.sequence_handler("drive_session_01")
extractor = DataFrameExtractor(seq_handler)
# Get data chunks
for df in extractor.to_pandas_chunks(topics=["/sensors/front/image_raw"]):
for _, row in df.iterrows():
# Reconstruct the full Message (envelope + payload) from a row
img_msg = Message.from_dataframe_row(
row=row,
topic_name="/sensors/front/image_raw",
)
if img_msg:
img = img_msg.get_data(Image).to_pillow()
# Access typed fields with IDE autocompletion
print(f"Time: {img_msg.timestamp_ns}")
img.show()
```
## Video Decoding for ML Pipelines
??? question "API Reference"
[`mosaicolabs.ml.VideoDecodingTransformer`][mosaicolabs.ml.VideoDecodingTransformer]
When handling multi-camera robotics datasets, managing image data presents a fundamental architectural conflict between video compression mechanics and machine learning dataloader strategies.
Stateful video compression formats like H.264 and HEVC rely on inter-frame dependencies to achieve high compression ratios. They transmit a complete image (an I-frame or Keyframe) followed by a sequence of delta-frames (P-frames or B-frames) that encode only the pixel differences from the preceding frames.
This creates a critical issue for ML pipelines:
* **Randomization Conflict:** If a dataloader shuffles or randomizes DataFrame rows before decoding, the decoder receives delta-frames without the necessary reference buffers, resulting in severe visual artifacts or outright crashes.
* **Synchronization Conflict:** If [temporal synchronization](#sparse-to-dense-representation) (like [`SyncTransformer`][mosaicolabs.ml.SyncTransformer] with a `SyncHold` policy) is applied *before* decoding, the exact same compressed delta-frame bytes are fed into the decoder multiple times, instantly corrupting the C-level state machine of the codec.
To resolve this, the ML module introduces the [`VideoDecodingTransformer`][mosaicolabs.ml.VideoDecodingTransformer], which enforces a strict **"Decode First, Sync Second, Shuffle Last"** architecture.
### Key Technical Features
* **Stateful Chronological Decoding**: The transformer maintains a persistent [`StatefulDecodingSession`][mosaicolabs.models.sensors.StatefulDecodingSession] across sequential DataFrame chunks. It unpacks the raw byte streams into fully reconstructed `PIL.Image` objects while the timeline is still perfectly sequential and unaltered.
* **Intelligent Format Routing**: The transformer inspects the [`ImageFormat`][mosaicolabs.models.sensors.ImageFormat] metadata of each row. Stateful streams (H.264, HEVC) are securely routed to the isolated, stateful C-level decoders, while stateless formats (JPEG, PNG) automatically fall back to lightweight stateless codecs.
* **Lazy Resource Allocation**: To ensure complete compatibility with [Scikit-Learn](https://pypi.org/project/scikit-learn/)'s `clone` utility and multiprocessing tools like `joblib`, the underlying C-level FFmpeg/PyAV pointers are never instantiated during `__init__`. The session is lazily allocated during the `fit()` phase, preventing pickling errors when distributing ML pipelines across multiple CPU cores.
* **Aggressive Memory Management**: Immediately after reconstructing the `PIL.Image`, the transformer drops the raw `compressed_image.data` byte columns from the Pandas DataFrame. This actively mitigates RAM saturation before the data reaches the downstream model.
* **Zero-Bloat Soft Dependency**: The transformer uses a soft-dependency architecture. If `scikit-learn` is installed, it inherits natively from `BaseEstimator` and `TransformerMixin`. If not, it safely falls back to dummy classes, ensuring Mosaico remains lightweight for users who only require core extraction features.
### Pipeline Integration
Because the `VideoDecodingTransformer` implements the standard Scikit-Learn `fit`/`transform` contract, it can be chained with the `SyncTransformer`. Once the data exits this pipeline, it is dense, fully synchronized, completely decoded, and safe to shuffle for PyTorch or TensorFlow dataloaders.
```python
from sklearn.pipeline import Pipeline
from mosaicolabs import MosaicoClient
from mosaicolabs.ml import DataFrameExtractor, SyncTransformer, VideoDecodingTransformer
from mosaicolabs.ml.sync_policies import SyncHold
# 1. Define the execution pipeline order (Decode -> Sync)
pipeline = Pipeline([
('decoder', VideoDecodingTransformer(topics=["/front/camera/image"])),
])
with MosaicoClient.connect("localhost", 6726) as client:
seq_handler = client.sequence_handler("multi_camera_mission")
extractor = DataFrameExtractor(seq_handler)
# 2. Process sequential row-based chunks
for sparse_chunk in extractor.to_pandas_chunks(
topics=["/front/camera/image", "/chassis/imu"],
batch_size=2048
):
# The decoder reconstructs video frames chronologically.
decoded_chunk = pipeline.transform(sparse_chunk)
# 'decoded_chunk' now contains arrays of usable PIL.Image objects.
# It is now perfectly safe to shuffle, batch, or convert to PyTorch Tensors.
del decoded_chunk # Explicitly signal for garbage collection
```
## Sparse to Dense Representation
??? question "API Reference"
[`mosaicolabs.ml.SyncTransformer`][mosaicolabs.ml.SyncTransformer]
The [`SyncTransformer`][mosaicolabs.ml.SyncTransformer] is a temporal resampler designed to solve the **Heterogeneous Sampling** problem inherent in robotics and Physical AI.
It aligns multi-rate sensor streams (for example, an IMU at 100Hz and a GPS at 5Hz) onto a uniform, fixed-frequency grid to prepare them for machine learning models.
The `SyncTransformer` operates as a processor that bridges the gaps between windowed chunks yielded by the [`DataFrameExtractor`][mosaicolabs.ml.DataFrameExtractor].
Unlike standard resamplers that treat each data batch in isolation, this transformer maintains internal state to ensure signal continuity across batch boundaries.
### Key Design Principles
* **Stateful Continuity**: It maintains an internal cache of the last known sensor values and the next expected grid tick, allowing signals to bridge the gap between independent DataFrame chunks.
* **Semantic Integrity**: It respects the physical reality of data acquisition by yielding `None` for grid ticks that occur before a sensor's first physical measurement, avoiding data "hallucination".
* **Vectorized Performance**: Internal kernels leverage high-speed lookups for high-throughput processing.
* **Protocol-Based Extensibility**: The mathematical logic for resampling is decoupled through a [`SyncPolicy`][mosaicolabs.ml.SyncPolicy] protocol, allowing for custom kernel injection.
### Implementation and Stateful Lifecycle
Architecturally, the [`SyncTransformer`][mosaicolabs.ml.SyncTransformer] is implemented as a **stateful state-machine** designed to maintain signal continuity across independent data chunks. Unlike standard library resamplers that often treat each input batch as an isolated event, this transformer is engineered to "stitch" the temporal gaps between the windowed DataFrames yielded by the [`DataFrameExtractor`][mosaicolabs.ml.DataFrameExtractor].
#### Internal State Management
The transformer maintains two critical internal buffers that persist for its entire lifecycle:
* **`_next_timestamp_ns`**: A scalar value tracking the exact nanosecond where the next grid tick must occur. This prevents temporal drift across hours of recording by ensuring the fixed-frequency grid remains globally aligned.
* **`_last_values`**: A dictionary that caches the final (timestamp, value) tuple for every topic processed in the previous chunk.
#### The Transformation Pipeline
When [`transform()`][mosaicolabs.ml.SyncTransformer.transform] is called on a new `sparse_chunk`, the following internal operations occur:
1. **Grid Synthesis**: The transformer generates a new time grid starting precisely from `_next_timestamp_ns` and extending to the end of the current chunk.
2. **Data Prepending**: Through the `_prepare_data` method, the transformer retrieves the last known value of each topic and **prepends** it to the current chunk's arrays. This ensures that the resampling algorithm (e.g., [`SyncHold`][mosaicolabs.ml.SyncHold]) has a reference point to fill the gap at the very beginning of the new window.
3. **Policy Delegation**: The actual mathematical mapping is delegated to the configured [`SyncPolicy`][mosaicolabs.ml.SyncPolicy], which yields the final dense values for the synthesized grid.
!!! danger "The 'Re-instantiation' Trap"
A common architectural error is re-instantiating the `SyncTransformer` inside a processing loop. Because the transformer is stateful, **it must be instantiated once outside the loop** to function correctly.
Re-instantiating the transformer inside the loop destroys the internal cache, causing signal discontinuities and potential data "hallucination" at the start of every chunk.
```python
# ERROR: Transformer is created inside the loop
for sparse_chunk in extractor.to_pandas_chunks():
# This resets the grid and last_values every iteration!
transformer = SyncTransformer(target_fps=50)
dense_chunk = transformer.transform(sparse_chunk)
```
#### Correct Pattern (Persistent State)
By keeping the instance outside the loop, the transformer correctly bridges the gap between `sparse_chunk_N` and `sparse_chunk_N+1`.
```python
# CORRECT: Instantiate once
transformer = SyncTransformer(target_fps=50)
for sparse_chunk in extractor.to_pandas_chunks():
# transform() updates internal state and prepares it for the next call
dense_chunk = transformer.transform(sparse_chunk)
```
If you need to reuse the same transformer instance for a different recording or sequence, you must call the [`.reset()`][mosaicolabs.ml.SyncTransformer.reset] method to clear the internal buffers and prepare for a new grid alignment.
### Implemented Synchronization Policies
??? question "API Reference"
[`mosaicolabs.ml.SyncPolicy`][mosaicolabs.ml.SyncPolicy]
Each policy defines a specific logic for how the transformer bridges temporal gaps between sparse data points.
#### 1. **[`SyncHold`][mosaicolabs.ml.SyncHold]** (Last-Value-Hold)
* **Behavior**: Finds the most recent valid measurement and "holds" it constant until a new one arrives.
* **Best For**: Sensors where states remain valid until explicitly changed, such as robot joint positions or battery levels.
#### 2. **[`SyncAsOf`][mosaicolabs.ml.SyncAsOf]** (Staleness Guard)
* **Behavior**: Carries the last known value forward only if it has not exceeded a defined maximum "tolerance" (fresher than a specific age).
* **Best For**: High-speed signals that become unreliable if not updated frequently, such as localization coordinates.
#### 3. **[`SyncDrop`][mosaicolabs.ml.SyncDrop]** (Interval Filter)
* **Behavior**: Ensures a grid tick only receives a value if a new measurement actually occurred within that specific grid interval; otherwise, it returns `None`.
* **Best For**: Downsampling high-frequency data where a strict 1-to-1 relationship between windows and unique hardware events is required.
### Memory & Performance Best Practices
The memory footprint of your ML pipeline is primarily governed by the product of two variables: the temporal window size (`window_sec`) in [`DataFrameExtractor.to_pandas_chunks()`][mosaicolabs.ml.DataFrameExtractor.to_pandas_chunks] and the synthesis frequency (`target_fps`) in [`SyncTransformer.transform()`][mosaicolabs.ml.SyncTransformer.transform].
#### Resource Consumption Matrix
| Parameter Configuration | Memory Impact | CPU Impact | Use Case |
| :--- | :--- | :--- | :--- |
| **Small Window / Low FPS** (1s / 10Hz) | **Minimal**: Lowest RAM overhead per chunk. | Low | Real-time monitoring, low-power edge devices. |
| **Large Window / Low FPS** (60s / 10Hz) | **Moderate**: High memory usage in the `DataFrameExtractor` due to large sparse buffers. | Moderate | Batch analysis where global context is needed before transformation. |
| **Small Window / High FPS** (1s / 1000Hz) | **High**: Rapid creation of many dense rows. Heavy overhead on Python's Garbage Collector. | High | High-fidelity signal processing (e.g., vibration analysis). |
| **Large Window / High FPS** (60s / 1000Hz) | **Critical**: Risk of `MemoryError`. Can generate millions of rows in a single `transform()` call. | Very High | Deep Learning training on high-end workstations with 64GB+ RAM. |
#### Optimization Strategies
1. **Avoid the "Full Load" Trap**:
The `DataFrameExtractor` is designed for (batched) streaming. If you set `window_sec` to a value greater than the total sequence duration, the extractor will fall back to a "Full Load" mode, attempting to load the entire recording into RAM, which can mean multi-GB batch for heavy datasets.
2. **The Rule of 100k Rows**:
As a general architectural guideline, aim for a configuration where `window_sec * target_fps < 100,000` rows per chunk (for time-series). This keeps the Pandas operations within the L3 cache limits of most modern CPUs and ensures the garbage collector can keep up with the loop iterations.
3. **Downsampling before Transformation**:
If you have high-frequency raw data (e.g., IMU at 400Hz) but only need 50Hz for your ML model, use the `SyncDrop` policy. It is significantly faster than `SyncHold` because it discards redundant intermediate samples before the dense grid is synthesized, reducing the internal array sizes during the `_prepare_data` phase.
4. **Garbage Collection in Long Loops**:
When processing sequences that span several hours, Python's automatic reference counting may not trigger fast enough. If you observe a "memory leak" (steadily increasing RAM usage), explicitly delete the `dense_chunk` at the end of your loop:
```python
for sparse_chunk in extractor.to_pandas_chunks():
dense_chunk = transformer.transform(sparse_chunk)
# ... process ...
del dense_chunk # Explicitly signal for GC
```
### Scikit-Learn Compatibility
By implementing the standard `fit`/`transform` interface, the [`SyncTransformer`][mosaicolabs.ml.SyncTransformer] makes robotics data a "first-class citizen" of the [Scikit-learn](https://pypi.org/project/scikit-learn/) ecosystem. This allows for the plug-and-play integration of multi-rate sensor data into standard [pipelines](https://scikit-learn.org/stable/api/sklearn.pipeline.html).
```python
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from mosaicolabs import MosaicoClient
from mosaicolabs.ml import DataFrameExtractor, SyncTransformer, SynchHold
# Define a pipeline for physical AI preprocessing
pipeline = Pipeline([
('sync', SyncTransformer(target_fps=30.0, policy=SynchHold())),
('scaler', StandardScaler())
])
with MosaicoClient.connect("localhost", 6726):
# Initialize from an existing SequenceHandler
seq_handler = client.sequence_handler("drive_session_01")
extractor = DataFrameExtractor(seq_handler)
# Process sequential chunks while maintaining signal continuity
for sparse_chunk in extractor.to_pandas_chunks(window_sec=5.0):
# The transformer automatically carries state across sequential calls
normalized_dense_chunk = pipeline.transform(sparse_chunk)
```
---
# ROS
The **ROS Bridge** module serves as the ingestion gateway for ROS (Robot Operating System) data into the Mosaico Data Platform. Its primary function is to solve the interoperability challenges associated with ROS bag files—specifically format fragmentation (ROS 1 `.bag` vs. ROS 2 `.mcap`/`.db3`) and the lack of strict schema enforcement in custom message definitions.
!!! info "API-Keys"
When the connection is established via the authorization middleware (i.e. using an [API-Key](../client.md#2-authentication-api-key)), the ROS Ingestion employs the mosaico [Writing Workflow](../handling/writing.md), which is allowed only if the key has at least [`APIKeyPermissionEnum.Write`][mosaicolabs.enum.APIKeyPermissionEnum.Write] permission.
The core philosophy of the module is **"Adaptation, Not Just Parsing."** Rather than simply extracting raw dictionaries from ROS messages, the bridge actively translates them into the standardized **Mosaico Ontology**. For example, a [`geometry_msgs/Pose`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/Pose.html) is validated, normalized, and instantiated as a strongly-typed [`mosaicolabs.models.data.Pose`][mosaicolabs.models.data.Pose] object before ingestion.
!!! example "Try-It Out"
You can experiment yourself the ROS Bridge ingestion via the **[ROS Ingestion](https://docs.mosaico.dev/demo/ros_ingestion) Example**.
## Architecture
The module is composed of four distinct layers that handle the pipeline from raw file access to server transmission.
### The Loader (`ROSLoader`)
The [`ROSLoader`][mosaicolabs.ros_bridge.loader.ROSLoader] acts as the abstraction layer over the physical bag files. It utilizes the [`rosbags`](https://pypi.org/project/rosbags/) library to provide a unified interface for reading both ROS 1 and ROS 2 formats (`.bag`, `.db3`, `.mcap`).
* **Responsibilities:** File I/O, raw deserialization, and topic filtering (supporting glob patterns like `/cam/*`).
* **Error Handling:** It implements configurable policies (`IGNORE`, `LOG_WARN`, `RAISE`) to handle corrupted messages or deserialization failures without crashing the entire pipeline.
### The Orchestrator (`RosbagInjector`)
The **[`RosbagInjector`][mosaicolabs.ros_bridge.RosbagInjector]** is the central command center of the ROS Bridge module. It is designed to be the primary entry point for developers who want to embed high-performance ROS ingestion directly into their Python applications or automation scripts.
The ingestor orchestrates the interaction between the **[`ROSLoader`][mosaicolabs.ros_bridge.loader.ROSLoader]** (file access), the **[`ROSBridge`][mosaicolabs.ros_bridge.ROSBridge]** (data adaptation), and the **[`MosaicoClient`][mosaicolabs.comm.MosaicoClient]** (network transmission). It handles the complex lifecycle of a data upload—including connection management, batching, and transaction safety—while providing real-time feedback through a visual CLI interface.
#### Core Workflow Execution: `run()`
The `run()` method is the heart of the ingestor. When called, it initiates a multi-phase pipeline:
1. **Handshake & Registry**: Establishes a connection to the Mosaico server and registers any provided custom `.msg` definitions into the global [`ROSTypeRegistry`][mosaicolabs.ros_bridge.ROSTypeRegistry].
2. **Sequence Creation**: Requests the server to initialize a new data sequence based on the provided name and metadata.
3. **Adaptive Streaming**: Iterates through the ROS bag records. For each message, it identifies the correct adapter, translates the ROS dictionary into a Mosaico object, and pushes it into an optimized write buffer.
4. **Transaction Finalization**: Once the bag is exhausted, it flushes all remaining buffers and signals the server to commit the sequence.
#### Configuring the Ingestion
The behavior of the ingestor is entirely driven by the **[`ROSInjectionConfig`][mosaicolabs.ros_bridge.ROSInjectionConfig]**. This configuration object ensures that the ingestion logic is decoupled from the user interface, allowing for consistent behavior whether triggered via the CLI or a complex script.
#### Practical Example: Programmatic Usage
```python
from pathlib import Path
from mosaicolabs import SessionLevelErrorPolicy, TopicLevelErrorPolicy
from mosaicolabs.ros_bridge import RosbagInjector, ROSInjectionConfig, Stores
def run_injection():
# Define the Injection Configuration
# This data class acts as the single source for the operation.
config = ROSInjectionConfig(
# Input Data
file_path=Path("data/session_01.db3"),
# Target Platform Metadata
sequence_name="test_ros_sequence",
metadata={
"driver_version": "v2.1",
"weather": "sunny",
"location": "test_track_A"
},
# Topic Filtering (supports glob patterns)
# This will only upload topics starting with '/cam'
topics=["/cam*"],
# ROS Configuration
# Specifying the distro ensures correct parsing of standard messages
# (.db3 sqlite3 rosbags need the specification of distro)
ros_distro=Stores.ROS2_HUMBLE,
# Custom Message Registration
# Register proprietary messages before loading to prevent errors
custom_msgs=[
(
"my_custom_pkg", # ROS Package Name
Path("./definitions/my_pkg/"), # Path to directory containing .msg files
Stores.ROS2_HUMBLE, # Scope (valid for this distro)
) # registry will automatically infer type names as `my_custom_pkg/msg/{filename}`
],
# Adapter Overrides
# Use specific adapters for designated topics instead of the default.
# In this case, instead to use PointCloudAdapter for depth camera,
# MyCustomRGBDAdapter will be used for the specified topic.
adapter_override={
"/camera/depth/points": MyCustomRGBDAdapter,
},
# Execution Settings
log_level="WARNING", # Reduce verbosity for automated scripts
# Session Level Error Handling
on_error=SessionLevelErrorPolicy.Report # Report the error and terminate the session
# Topic Level Error Handling
topics_on_error=TopicLevelErrorPolicy.Raise # Re-raise any exception
)
# Instantiate the Controller
ingestor = RosbagInjector(config)
# Execute
# The run method handles connection, loading, and uploading automatically.
# It raises exceptions for fatal errors, allowing you to wrap it in try/except blocks.
try:
ingestor.run()
print("Injection job completed successfully.")
except Exception as e:
print(f"Injection job failed: {e}")
# Use as script or call the injection function in your code
if __name__ == "__main__":
run_injection()
```
### The Adaptation Layer (`ROSBridge` & Adapters)
This layer represents the default semantic core of the module, translating raw ROS data into the Mosaico Ontology.
* **[`ROSAdapterBase`][mosaicolabs.ros_bridge.adapter_base.ROSAdapterBase]:** An abstract base class that establishes the **default** contracts for converting specific ROS message types into their corresponding Mosaico Ontology types.
* **Concrete Adapters:** The library provides built-in implementations for common standards, such as [`IMUAdapter`][mosaicolabs.ros_bridge.adapters.sensor_msgs.IMUAdapter] (mapping `sensor_msgs/Imu` to [`IMU`][mosaicolabs.models.sensors.IMU]) and [`ImageAdapter`][mosaicolabs.ros_bridge.adapters.sensor_msgs.ImageAdapter] (mapping `sensor_msgs/Image` to [`Image`][mosaicolabs.models.sensors.Image]). These adapters include advanced logic for recursive unwrapping, automatically extracting data from complex nested wrappers like [`PoseWithCovarianceStamped`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/PoseWithCovarianceStamped.html). Developers can also implement custom adapters to handle non-standard or proprietary types.
* **[`ROSBridge`][mosaicolabs.ros_bridge.ROSBridge]:** A central registry and dispatch mechanism that maps ROS message type strings (e.g., [`sensor_msgs/msg/Imu`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/Imu.html)) to their corresponding default adapter classes, ensuring the correct translation logic is applied for each message.
#### Extending the Bridge (Custom Adapters)
Users can extend the bridge to support new ROS message types by implementing a custom adapter and registering it.
1. **Inherit from `ROSAdapterBase`**: Define the input ROS type string and the target Mosaico Ontology type.
2. **Implement `from_dict`**: Define the logic to convert the [`ROSMessage.data`][mosaicolabs.ros_bridge.ROSMessage] dictionary into an intance of the target ontology object.
3. **Register**: Decorate the class with [`@register_default_adapter`][mosaicolabs.ros_bridge.register_default_adapter].
```python
from mosaicolabs.ros_bridge import ROSAdapterBase, register_default_adapter, ROSMessage
from mosaicolabs.models import Message
from my_ontology import MyCustomData # Assuming this class exists
@register_default_adapter
class MyCustomAdapter(ROSAdapterBase[MyCustomData]):
ros_msgtype = "my_pkg/msg/MyCustomType"
__mosaico_ontology_type__ = MyCustomData
@classmethod
def from_dict(cls, ros_data: dict, **kwargs) -> MyCustomData:
# Transformation logic here
return MyCustomData(...)
```
#### Override Adapters
This section explains how to extend the bridge's capabilities by implementing and registering Override Adapters.
##### Overriding and Extending Adapters
While the ROS Bridge provides a robust set of default adapters for standard message types, real-world robotics often involve proprietary message definitions or non-standard uses of common types.
Through the **`adapter_override`** parameter in the `ROSInjectionConfig`, you can explicitly map a specific topic to a chosen adapter. This is particularly useful for types like [`sensor_msgs/msg/PointCloud2`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/PointCloud2.html), where, for example, different LiDAR vendors may encode data in unique ways that require specialized parsing logic.
!!! important "Override adapter usage"
Use adapter overrides for versatile message types like [`sensor_msgs/msg/PointCloud2`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/PointCloud2.html), where different sensors (LiDAR, Radar, etc.) share the same ROS type but require unique parsing logic. Overrides should be defined and used when a given ROS message type has its own **default adapter** registered in the `ROSBridge` registry, but such an adapter cannot satisfy topic-specific requirements. If your message type is used consistently across all topics, simply use the [`@register_default_adapter`][mosaicolabs.ros_bridge.register_default_adapter] decorator to establish a global fallback.
##### Available Adapters override
Built-in adapters are provided for the most common sensor types and are ready to use out of the box:
| Sensor type | Adapter class |
|---------------|-----------------------|
| LiDAR | [`LidarAdapter`][mosaicolabs.ros_bridge.adapters.override_msgs.LidarAdapter] |
| Radar | [`RadarAdapter`][mosaicolabs.ros_bridge.adapters.override_msgs.RadarAdapter] |
| RGBD Camera | [`RGBDCameraAdapter`][mosaicolabs.ros_bridge.adapters.override_msgs.RGBDCameraAdapter] |
| ToF Camera | [`ToFCameraAdapter`][mosaicolabs.ros_bridge.adapters.override_msgs.ToFCameraAdapter] |
| Stereo Camera | [`StereoCameraAdapter`][mosaicolabs.ros_bridge.adapters.override_msgs.StereoCameraAdapter] |
All of them extend [`PointCloudAdapterBase`][mosaicolabs.ros_bridge.adapters.sensor_msgs.PointCloudAdapterBase], which exposes the following interface:
- **`decode`**: deserializes the binary buffer of a `PointCloud2` message into named field arrays.
- **`_build`** *(abstract)*: constructs and returns an instance of the target ontology object from the decoded fields. Must be overridden in every concrete subclass.
- **`from_dict`**: validates that all required fields of the ontology are present before delegating to `_build`. A field is considered required when its [`MosaicoField`][mosaicolabs.models.MosaicoField] declaration has no explicit default (i.e. `default=...`) or it is declared **no Optional**.
##### Implementing a Custom PointCloud2 Adapter Override
To create a custom `PointCloud2` adapter, inherit from [`PointCloudAdapterBase`][mosaicolabs.ros_bridge.adapters.sensor_msgs.PointCloudAdapterBase].
You only need to define:
- `_build`: the mapping logic from decoded field arrays to your ontology instance.
- `_REQUIRED_FIELDS`: the list of fields that must be present in the decoded payload.
- `__mosaico_ontology_type__`: the target ontology class.
All core business logic is encapsulated inside `PointCloudAdapterBase`.
The following example shows a custom LiDAR adapter whose encoding differs from the generic [`LidarAdapter`][mosaicolabs.ros_bridge.adapters.override_msgs.LidarAdapter] already provided by Mosaico.
Note that the adapter is **not** registered as default, since `sensor_msgs/msg/PointCloud2` already has one.
```python
from typing import Any, Optional, Type
from mosaicolabs.ros_bridge import PointCloudAdapterBase, ROSMessage
from mosaicolabs.models import Message
from my_ontology import MyLidar # Your target Ontology class
class MyLidarAdapter(PointCloudAdapterBase[MyVelodyneLidar]):
# Define the target Mosaico Ontology class
__mosaico_ontology_type__: Type[MyLidar] = MyVelodyneLidar
_REQUIRED_FIELDS = [
name for name, field in MyLidar.model_fields.items()
if field.is_required()
]
@classmethod
def _build(cls, decoded_fields: dict[str, list]) -> MyLidar:
return MyLidar(...)
@classmethod
def translate(
cls,
ros_msg: ROSMessage,
**kwargs: Any,
) -> Message:
"""
Optional: Override the high-level translation if you need to
manipulate the ROSMessage envelope before processing.
"""
# Optionally add pre/post processing logic around the base translation.
return super().translate(ros_msg, **kwargs)
@classmethod
def from_dict(cls, ros_data: dict) -> MyLidar:
"""
The primary transformation logic.
Converts the deserialized ROS dictionary into a Mosaico object.
"""
# Core transformation logic: map raw ROS fields to your ontology type.
return super().from_dict(ros_data)
@classmethod
def schema_metadata(cls, ros_data: dict, **kwargs: Any) -> Optional[dict]:
"""
Optional: Extract specific metadata from the ROS message
to be stored in the Mosaico schema registry.
"""
return None
```
!!! tip "Optional overrides"
Only `_build` is mandatory. Override `translate`, `from_dict`, or `schema_metadata` only when the default behaviour of the base class does not meet your needs.
##### Registering the Override
Once implemented, the adapter is registered against a specific topic via `adapter_override` in [ROSInjectionConfig][mosaicolabs.ros_bridge.ROSInjectionConfig]:
```python
from .my_adapter import MyLidarAdapter
...
config = ROSInjectionConfig(
file_path=Path("sensor_data.mcap"),
sequence_name="custom_lidar_run",
# Explicitly tell the bridge to use your custom adapter for this topic
adapter_override={
"/lidar/front/pointcloud": MyLidarAdapter,
}
)
...
ingestor = RosbagInjector(config)
ingestor.run()
```
With this configuration, all the [`sensor_msgs/msg/PointCloud2`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/PointCloud2.html) message received on `/lidar/front/pointcloud`, will be processed exclusively by `MyLidarAdapter`. All other topics continue to use the standard resolution logic.
By using this pattern, you can maintain a clean separation between your raw ROS data and your high-level Mosaico data models, ensuring that even the most "exotic" sensor data is correctly ingested and indexed.
##### Implementing a Custom Adapter Override
To create a custom adapter that overrides a existing ROS message, you must inherit from `ROSAdapterBase` and define the transformation logic.
Follow the steps described [here](#extending-the-bridge-custom-adapters) with the only caveat not to register the adapter with `@register_default_adapter` but insted [register the override](#registering-the-override)
#### CLI Usage
The module includes a command-line interface for quick ingestion tasks. The full list of options can be retrieved by running `mosaicolabs.ros_injector -h`
```bash
# Basic Usage
mosaicolabs.ros_injector ./data.mcap --name "Test_Run_01"
# Advanced Usage: Filtering topics and adding metadata
mosaicolabs.ros_injector ./data.db3 \
--name "Test_Run_01" \
--topics /camera/front/* /gps/fix \
--metadata ./metadata.json \
--ros-distro ros2_humble
```
### The Type Registry (`ROSTypeRegistry`)
The **[`ROSTypeRegistry`][mosaicolabs.ros_bridge.ROSTypeRegistry]** is a context-aware singleton designed to manage the schemas required to decode ROS data. ROS message definitions are frequently external to the data files themselves—this is especially true for ROS 2 `.db3` (SQLite) formats and proprietary datasets containing custom sensors. Without these definitions, the bridge cannot deserialize the raw binary "blobs" into readable dictionaries.
* **Schema Resolution**: It allows the [`ROSLoader`][mosaicolabs.ros_bridge.loader.ROSLoader] to resolve custom `.msg` definitions on-the-fly during bag playback.
* **Version Isolation (Stores)**: ROS messages often vary across distributions (e.g., a "Header" in ROS 1 Noetic is structurally different from ROS 2 Humble). The registry uses a "Profile" system to store these version-specific definitions separately, preventing cross-distribution conflicts.
* **Global vs. Scoped Definitions**: You can register definitions **Globally** (available to all loaders) or **Scoped** to a specific distribution.
#### Pre-loading Definitions
While you can pass custom messages via [`ROSInjectionConfig`][mosaicolabs.ros_bridge.ROSInjectionConfig], it can become cumbersome for large-scale projects with hundreds of proprietary types. The recommended approach is to pre-load the registry at the start of your application. This makes the definitions available to all subsequent loaders automatically.
| Method | Scope | Description |
| --- | --- | --- |
| **`register(...)`** | Single Message | Registers a single custom type. The source can be a path to a `.msg` file or a raw string containing the definition. |
| **`register_directory(...)`** | Batch Package | Scans a directory for all `.msg` files and registers them under a specific package name (e.g., `my_pkg/msg/Sensor`). |
| **`get_types(...)`** | Internal | Implements a "Cascade" logic: merges Global definitions with distribution-specific overrides for a loader. |
| **`reset()`** | Utility | Clears all stored definitions. Primarily used for unit testing to ensure process isolation. |
#### Centralized Registration Example
A clean way to manage large projects is to centralize your message registration in a single setup function (e.g., `setup_registry.py`):
```python
from pathlib import Path
from mosaicolabs.ros_bridge import ROSTypeRegistry, Stores
def initialize_project_schemas():
# 1. Register a proprietary message valid for all ROS versions
ROSTypeRegistry.register(
msg_type="common_msgs/msg/SystemHeartbeat",
source=Path("./definitions/Heartbeat.msg")
)
# 2. Batch register an entire package for ROS 2 Humble
ROSTypeRegistry.register_directory(
package_name="robot_v3_msgs",
dir_path=Path("./definitions/robot_v3/msgs"),
store=Stores.ROS2_HUMBLE
)
```
Once registered, the [`RosbagInjector`][mosaicolabs.ros_bridge.RosbagInjector] (and the underlying [`ROSLoader`][mosaicolabs.ros_bridge.loader.ROSLoader]) automatically detects and uses these definitions. There is no longer the need to pass the `custom_msgs` list in the [`ROSInjectionConfig`][mosaicolabs.ros_bridge.ROSInjectionConfig].
```python
# main_injection.py
import setup_registry # Runs the registration logic above
from mosaicolabs.ros_bridge import RosbagInjector, ROSInjectionConfig, Stores
from pathlib import Path
# Initialize registry
setup_registry.initialize_project_schemas()
# Configure injection WITHOUT listing custom messages again
config = ROSInjectionConfig(
file_path=Path("mission_data.mcap"),
sequence_name="mission_01",
metadata={"operator": "Alice"},
ros_distro=Stores.ROS2_HUMBLE, # Loader will pull the Humble-specific types we registered
# custom_msgs=[] <-- No longer needed!
)
ingestor = RosbagInjector(config)
ingestor.run()
```
### Testing & Validation
The ROS Bag Injection module has been validated against a variety of standard datasets to ensure compatibility with different ROS distributions, message serialization formats (CDR/ROS 1), and bag container formats (`.bag`, `.mcap`, `.db3`).
#### Recommended Dataset for Verification
For evaluating Mosaico capabilities, we recommend the **[NVIDIA NGC Catalog - R2B Dataset 2024](https://catalog.ngc.nvidia.com/orgs/nvidia/teams/isaac/resources/r2bdataset2024?version=1)**. This dataset has been verified to be fully compatible with the injection pipeline.
The following table details the injection performance for the **NVIDIA R2B Dataset 2024**. These benchmarks were captured on a system running **macOS 26.2** with an **Apple M2 Pro (10 cores, 16GB RAM)**.
#### NVIDIA R2B Dataset 2024 Injection Performance
| Sequence Name | Compression Factor | Injection Time | Hardware Architecture | Notes |
| --- | --- | --- | --- | --- |
| **`r2b_galileo2`** | ~70% | ~40 sec | Apple M2 Pro (16GB) | High compression achieved for telemetry data. |
| **`r2b_galileo`** | ~1% | ~30 sec | Apple M2 Pro (16GB) | Low compression due to pre-compressed source images. |
| **`r2b_robotarm`** | ~66% | ~50 sec | Apple M2 Pro (16GB) | High efficiency for high-frequency state updates. |
| **`r2b_whitetunnel`** | ~1% | ~30 sec | Apple M2 Pro (16GB) | Low compression; contains topics with no available adapter. |
#### Understanding Performance Factors
* **Compression Factors**: Sequences like `r2b_galileo2` achieve high ratios (~70%) because Mosaico optimizes the underlying columnar storage for scalar telemetry. Conversely, sequences with pre-compressed video feeds show minimal gains (~1%) because the data is already in a dense format.
* **Injection Time**: This metric includes the overhead of local MCAP/DB3 deserialization via [`ROSLoader`][mosaicolabs.ros_bridge.loader.ROSLoader], semantic translation through the [`ROSBridge`][mosaicolabs.ros_bridge.ROSBridge], and the transmission to the Mosaico server.
#### Known Issues & Limitations
While the underlying `rosbags` library supports the majority of standard ROS 2 bag files, specific datasets with non-standard serialization alignment or proprietary encodings may encounter compatibility issues.
**NVIDIA Isaac ROS Benchmark Dataset (2023)**
* **Source:** [NVIDIA NGC Catalog - R2B Dataset 2023](https://catalog.ngc.nvidia.com/orgs/nvidia/teams/isaac/resources/r2bdataset2023)
* **Issue:** Deserialization failure during ingestion.
* **Technical Details:** The ingestion process fails within the [`AnyReader.deserialize`](https://ternaris.gitlab.io/rosbags/api/rosbags.highlevel.html#rosbags.highlevel.AnyReader.deserialize) method of the [`rosbags`](https://ternaris.gitlab.io/rosbags/index.html) library. The internal CDR deserializer triggers an assertion error indicating a mismatch in the expected data length vs. the raw payload size.
* **Error Signature:**
```python
# In rosbags.serde.cdr:
assert pos + 4 + 3 >= len(rawdata)
```
* **Recommendation:** This issue originates in the upstream parser handling of this specific dataset's serialization alignment. It is currently recommended to exclude this dataset or transcode it using standard ROS 2 tools before ingestion.
## Supported Message Types
***ROS-Specific Data Models***
In addition to mapping standard ROS messages to the core Mosaico ontology, the `ros-bridge` module implements two specialized data models. These are defined specifically for this module to handle ROS-native concepts that are not yet part of the official Mosaico standard:
* **`FrameTransform`**: Designed to handle coordinate frame transformations (modeled after [`tf2_msgs/msg/TFMessage`](https://docs.ros2.org/foxy/api/tf2_msgs/msg/TFMessage.html)). It encapsulates a list of [`Transform`][mosaicolabs.models.data.geometry.Transform] objects to manage spatial relationships.
* **`BatteryState`**: Modeled after [`sensor_msgs/msg/BatteryState`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/BatteryState.html)), this class captures comprehensive power supply metrics. It includes core data (voltage, current, capacity, percentage) and detailed metadata such as power supply health, technology status, and individual cell readings.
* **`PointCloud2`**: Modeled after [`sensor_msgs/msg/PointCloud2`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/PointCloud2.html),
this class captures raw point cloud data including field layout, endianness, and binary payload.
It includes the companion `PointField` model to describe each data channel (e.g., `x`, `y`, `z`, `intensity`).
> **Note:** Although these are provisional additions, both `FrameTransform`, `BatteryState`, and `PointCloud2` inherit from [`Serializable`][mosaicolabs.models.Serializable]. This ensures they remain fully compatible with Mosaico’s existing serialization infrastructure.
### Supported Message Types Table
| ROS Message Type | Mosaico Ontology Type | Adapter |
| :--- | :--- | :--- |
| [`geometry_msgs/msg/Pose`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/Pose.html), [`PoseStamped`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/PoseStamped.html)... | [`Pose`][mosaicolabs.models.data.geometry.Pose] | `PoseAdapter` |
| [`geometry_msgs/msg/Twist`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/Twist.html), [`TwistStamped`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/TwistStamped.html)... | [`Velocity`][mosaicolabs.models.data.kinematics.Velocity] | `TwistAdapter` |
| [`geometry_msgs/msg/Accel`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/Accel.html), [`AccelStamped`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/AccelStamped.html)... | [`Acceleration`][mosaicolabs.models.data.kinematics.Acceleration] | `AccelAdapter` |
| [`geometry_msgs/msg/Vector3`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/Vector3.html), [`Vector3Stamped`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/Vector3Stamped.html) | [`Vector3d`][mosaicolabs.models.data.geometry.Vector3d] | `Vector3Adapter` |
| [`geometry_msgs/msg/Point`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/Point.html), [`PointStamped`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/PointStamped.html) | [`Point3d`][mosaicolabs.models.data.geometry.Point3d] | `PointAdapter` |
| [`geometry_msgs/msg/Quaternion`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/Quaternion.html), [`QuaternionStamped`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/QuaternionStamped.html) | [`Quaternion`][mosaicolabs.models.data.geometry.Quaternion] | `QuaternionAdapter` |
| [`geometry_msgs/msg/Transform`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/Transform.html), [`TransformStamped`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/TransformStamped.html) | [`Transform`][mosaicolabs.models.data.geometry.Transform] | `TransformAdapter` |
| [`geometry_msgs/msg/Wrench`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/Wrench.html), [`WrenchStamped`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/WrenchStamped.html) | [`ForceTorque`][mosaicolabs.models.data.dynamics.ForceTorque] | `WrenchAdapter` |
| [`geometry_msgs/msg/Polygon`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/Polygon.html), [`PolygonStamped`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/PolygonStamped.html) | [`Polygon`][mosaicolabs.models.data.geometry.Polygon] | `PolygonAdapter` |
| [`geometry_msgs/msg/Inertia`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/Inertia.html), [`InertiaStamped`](https://docs.ros2.org/foxy/api/geometry_msgs/msg/InertiaStamped.html) | [`Inertia`][mosaicolabs.models.data.dynamics.Inertia] | `InertiaAdapter` |
| [`nav_msgs/msg/Odometry`](https://docs.ros2.org/foxy/api/nav_msgs/msg/Odometry.html) | [`MotionState`][mosaicolabs.models.data.kinematics.MotionState] | `OdometryAdapter` |
| [`nmea_msgs/msg/Sentence`](https://docs.ros2.org/foxy/api/nmea_msgs/msg/Sentence.html) | [`NMEASentence`][mosaicolabs.models.sensors.NMEASentence] | `NMEASentenceAdapter` |
| [`sensor_msgs/msg/Image`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/Image.html), [`CompressedImage`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/CompressedImage.html) | [`Image`][mosaicolabs.models.sensors.Image], [`CompressedImage`][mosaicolabs.models.sensors.CompressedImage] | `ImageAdapter`, `CompressedImageAdapter` |
| [`sensor_msgs/msg/Imu`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/Imu.html) | [`IMU`][mosaicolabs.models.sensors.IMU] | `IMUAdapter` |
| [`sensor_msgs/msg/MagneticField`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/MagneticField.html) | [`Magnetometer`][mosaicolabs.models.sensors.Magnetometer] | `MagneticFieldAdapter` |
| [`sensor_msgs/msg/Joy`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/Joy.html) | [`Joy`][mosaicolabs.models.sensors.Joy] | `JoyAdapter` |
| [`sensor_msgs/msg/NavSatFix`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/NavSatFix.html) | [`GPS`][mosaicolabs.models.sensors.GPS], [`GPSStatus`][mosaicolabs.models.sensors.GPSStatus] | `GPSAdapter`, `NavSatStatusAdapter` |
| [`sensor_msgs/msg/CameraInfo`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/CameraInfo.html) | [`CameraInfo`][mosaicolabs.models.sensors.CameraInfo] | `CameraInfoAdapter` |
| [`sensor_msgs/msg/RegionOfInterest`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/RegionOfInterest.html) | [`ROI`][mosaicolabs.models.data.ROI] | `ROIAdapter` |
| [`sensor_msgs/msg/JointState`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/JointState.html) | [`RobotJoint`][mosaicolabs.models.sensors.RobotJoint] | `RobotJointAdapter` |
| [`sensor_msgs/msg/BatteryState`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/BatteryState.html) | [`BatteryState`][mosaicolabs.ros_bridge.data_ontology.BatteryState] (ROS-specific)| `BatteryStateAdapter` |
| [`std_msgs/msg/String`](https://docs.ros2.org/foxy/api/std_msgs/msg/String.html)| [`String`][mosaicolabs.models.data.String]| `_GenericStdAdapter` |
| [`std_msgs/msg/Int8(16,32,64)`](https://docs.ros2.org/foxy/api/std_msgs/msg/Int8.html) | [`Integer8(16,32,64)`][mosaicolabs.models.data.Integer8]| `_GenericStdAdapter` |
| [`std_msgs/msg/UInt8(16,32,64)`](https://docs.ros2.org/foxy/api/std_msgs/msg/UInt8.html) | [`Unsigned8(16,32,64)`][mosaicolabs.models.data.Unsigned8]| `_GenericStdAdapter` |
| [`std_msgs/msg/Float32(64)`](https://docs.ros2.org/foxy/api/std_msgs/msg/Float32.html) | [`Floating32(64)`][mosaicolabs.models.data.Floating32]| `_GenericStdAdapter` |
| [`std_msgs/msg/Bool`](https://docs.ros2.org/foxy/api/std_msgs/msg/Bool.html) | [`Boolean`][mosaicolabs.models.data.Boolean]| `_GenericStdAdapter` |
| [`tf2_msgs/msg/TFMessage`](https://docs.ros2.org/foxy/api/tf2_msgs/msg/TFMessage.html) | [`FrameTransform`][mosaicolabs.ros_bridge.data_ontology.FrameTransform] (ROS-specific)| `FrameTransformAdapter` |
| [`sensor_msgs/msg/PointCloud2`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/PointCloud2.html) | [`PointCloud2`][mosaicolabs.ros_bridge.data_ontology.PointCloud2] (ROS-specific)| `PointCloudAdapter` |
---
# Writing & Reading Data
The **Data Handling** module serves as the high-performance operational core of the Mosaico SDK, providing a unified interface for moving multi-modal sensor data between local applications and the Mosaico Data Platform. Engineered to solve the "Big Data" challenges of robotics and autonomous systems, this module abstracts the complexities of network I/O, buffering, and high-precision temporal alignment.
### Asymmetric Architecture
The SDK employs a specialized architecture that separates concerns into **Writers/Updaters** and **Handlers**, ensuring each layer is optimized for its unique traffic pattern:
* **Ingestion (Writing/Updating)**: Designed for low-latency, high-throughput ingestion of 4K video, high-frequency IMU telemetry, and dense point clouds.
* **Discovery & Retrieval (Reading)**: Architected to separate metadata-based resource discovery from high-volume data transmission. This separation allows developers to inspect sequence and topic catalogs—querying metadata and temporal bounds—before committing to a high-bandwidth data stream.
### Memory-Efficient Data Flow
The Mosaico SDK is engineered to handle massive data volumes without exhausting local system resources, enabling the processing of datasets that span terabytes while maintaining a minimal and predictable memory footprint.
* **Smart Batching & Buffering**: Both reading and writing operations are executed in memory-limited batches rather than loading or sending entire sequences at once.
* **Automated Lifecycle**: In reading workflows, processed batches are automatically discarded and replaced with new data from the server. In writing workflows, buffers are automatically flushed based on configurable size or record limits.
* **Stream Persistence**: Integrated **Error Policies** allow developers to prioritize either a "clean slate" data state or "recovery" of partial data in the event of an application crash.
---
# The Reading Workflow
The **Reading Workflow** in Mosaico is architected to separate resource discovery from high-volume data transmission. This is achieved through two distinct layers: **Handlers**, which serve as metadata proxies, and **Streamers**, which act as the high-performance data engines.
!!! info "API-Keys"
When the connection is established via the authorization middleware (i.e. using an [API-Key](../client.md#2-authentication-api-key)), the reading workflow requires the minimum [`APIKeyPermissionEnum.Read`][mosaicolabs.enum.APIKeyPermissionEnum.Read] permission.
!!! example "Try-It Out"
You can experiment yourself the Handlers module via the **[Data Discovery and Inspection](https://docs.mosaico.dev/demo/querying_catalogs) Example**.
### Handlers: The Catalog Layer
Handlers are lightweight objects that represent a server-side resource. Their primary role is to provide immediate access to system information and user-defined metadata **without downloading the actual sensor data**. They act as the "Catalog" layer of the SDK, allowing you to inspect the contents of the platform before committing to a high-bandwidth data stream.
Mosaico provides two specialized handler types: `SequenceHandler` and `TopicHandler`.
#### `SequenceHandler`
??? question "API Reference"
[`mosaicolabs.handlers.SequenceHandler`][mosaicolabs.handlers.SequenceHandler].
Represents a complete recording session. It provides a holistic view, allowing you to inspect all available topic names, global sequence metadata, and the overall temporal bounds (earliest and latest timestamps) of the session.
Spawning a new sequence handler is done via the [`MosaicoClient.sequence_handler()`][mosaicolabs.comm.MosaicoClient.sequence_handler] factory method.
This example demonstrates how to use a Sequence handler to inspect metadata.
```python
import sys
from mosaicolabs import MosaicoClient
with MosaicoClient.connect("localhost", 6726) as client:
# Use a Handler to inspect the catalog
seq_handler = client.sequence_handler("mission_alpha")
if seq_handler:
print(f"Sequence: {seq_handler.name}")
print(f"\t| Topics: {seq_handler.topics}")
print(f"\t| User metadata: {seq_handler.user_metadata}")
print(f"\t| Timestamp span: {seq_handler.timestamp_ns_min} - {seq_handler.timestamp_ns_max}")
print(f"\t| Created {seq_handler.sequence_info.created_datetime}")
print(f"\t| Size (MB) {seq_handler.sequence_info.total_size_bytes/(1024*1024)}")
# Once done, close the reading channel (recommended)
seq_handler.close()
```
#### `TopicHandler`
??? question "API Reference"
[`mosaicolabs.handlers.TopicHandler`][mosaicolabs.handlers.TopicHandler].
Represents a specific data channel within a sequence (e.g., a single IMU or Camera). It provides granular system info, such as the specific ontology model used and the data volume of that individual stream.
Spawning a new topic handler is done via the [`MosaicoClient.topic_handler()`][mosaicolabs.comm.MosaicoClient.topic_handler] factory method, or via [`SequenceHandler.get_topic_handler()`][mosaicolabs.handlers.SequenceHandler.get_topic_handler] factory method.
This example demonstrates how to use a Topic handler to inspect metadata.
```python
import sys
from mosaicolabs import MosaicoClient
with MosaicoClient.connect("localhost", 6726) as client:
# Use a Handler to inspect the catalog
top_handler = client.topic_handler("mission_alpha", "/front/imu")
# Note that the same handler can be retrieve via the SequenceHandler of the parent sequence:
# seq_handler = client.sequence_handler("mission_alpha")
# top_handler = seq_handler.get_topic_handler("/front/imu")
if top_handler:
print(f"Sequence:Topic: {top_handler.sequence_name}:{top_handler.name}")
print(f"\t| User metadata: {top_handler.user_metadata}")
print(f"\t| Timestamp span: {top_handler.timestamp_ns_min} - {top_handler.timestamp_ns_max}")
print(f"\t| Created {top_handler.topic_info.created_datetime}")
print(f"\t| Size (MB) {top_handler.topic_info.total_size_bytes/(1024*1024)}")
# Once done, close the reading channel (recommended)
top_handler.close()
```
### Streamers: The Data Engines
Both handlers serve as **factories**; once you have identified the resource you need, the handler is used to spawn the appropriate Streamer to begin data consumption.
Streamers are the active components that manage the physical data exchange between the server and your application. They handle the complexities of network buffering, batch management, and the de-serialization of raw bytes into Mosaico `Message` objects.
#### `SequenceDataStreamer` (Unified Replay)
??? question "API Reference"
[`mosaicolabs.handlers.SequenceDataStreamer`][mosaicolabs.handlers.SequenceDataStreamer].
The **`SequenceDataStreamer`** is a unified engine designed specifically for sensor fusion and full-system replay. It allows you to consume multiple data streams as if they were a single, coherent timeline.
Spawning a new sequence data streamer is done via the [`SequenceHandler.get_data_streamer()`][mosaicolabs.handlers.SequenceHandler.get_data_streamer] factory method.
When streaming data, the streamer employs the following technical mechanisms:
* **K-Way Merge Sorting**: The streamer monitors the timestamps across all requested topics simultaneously. On every iteration, it "peeks" at the next available message from each topic and yields the one with the lowest timestamp.
* **Strict Chronological Order**: This sorting ensures that messages are delivered in exact acquisition order, effectively normalizing topics that may operate at vastly different frequencies (e.g., high-rate IMU vs. low-rate GPS).
* **Temporal Slicing**: You can request a "windowed" extraction by specifying `start_timestamp_ns` and `end_timestamp_ns`. This is highly efficient as it avoids downloading the entire sequence, focusing only on the specific event or time range of interest.
* **Smart Buffering**: To maintain memory efficiency, the streamer retrieves data in memory-limited batches. As you iterate, processed batches are discarded and replaced with new data from the server, allowing you to stream sequences that exceed your available RAM.
This example demonstrates how to initiate and use the Sequence data stream.
```python
import sys
from mosaicolabs import MosaicoClient
with MosaicoClient.connect("localhost", 6726) as client:
# Use a Handler to inspect the catalog
seq_handler = client.sequence_handler("mission_alpha")
if seq_handler:
# Start a Unified Stream (K-Way Merge) for multi-sensor replay
# We only want GPS and IMU data for this synchronized analysis
streamer = seq_handler.get_data_streamer(
topics=["/gps", "/imu"], # Optionally filter topics
# Optionally set the time window to extract
start_timestamp_ns=1738508778000000000,
end_timestamp_ns=1738509618000000000
)
# Check the start message timestamp
print(f"Recording starts at: {streamer.next_timestamp()}")
for topic, msg in streamer:
# Processes GPS and IMU in perfect chronological order
print(f"[{topic}] at {msg.timestamp_ns}: {type(msg.data).__name__}")
# Once done, close the reading channel (recommended)
seq_handler.close()
```
#### `TopicDataStreamer` (Targeted Access)
??? question "API Reference"
[`mosaicolabs.handlers.TopicDataStreamer`][mosaicolabs.handlers.TopicDataStreamer].
The **`TopicDataStreamer`** provides a dedicated, high-throughput channel for interacting with a single data resource. By bypassing the complex synchronization logic required for merging multiple topics, it offers the lowest possible overhead for tasks requiring isolated data streams, such as training models on specific camera frames or IMU logs.
Spawning a new topic data streamer is done via the [`TopicHandler.get_data_streamer()`][mosaicolabs.handlers.TopicHandler.get_data_streamer] factory method.
To ensure efficiency, the streamer supports the following features:
* **Temporal Slicing**: Much like the `SequenceDataStreamer`, you can extract data in a time-windowed fashion by specifying `start_timestamp_ns` and `end_timestamp_ns`. This ensures that only the relevant portion of the stream is retrieved rather than the entire dataset.
* **Smart Buffering**: Data is not downloaded all at once; instead, the SDK retrieves information in memory-limited batches, substituting old data with new batches as you iterate to maintain a constant, minimal memory footprint.
This example demonstrates how to initiate and use the Topic data stream.
```python
import sys
from mosaicolabs import MosaicoClient, IMU
with MosaicoClient.connect("localhost", 6726) as client:
# Retrieve the topic handler using (e.g.) MosaicoClient
top_handler = client.topic_handler("mission_alpha", "/front/imu")
if top_handler:
# Start a Targeted Stream for single-sensor replay
imu_stream = top_handler.get_data_streamer(
# Optionally set the time window to extract
start_timestamp_ns=1738508778000000000,
end_timestamp_ns=1738509618000000000
)
# Peek at the start time
print(f"Recording starts at: {imu_stream.next_timestamp()}")
# Direct, low-overhead loop
for imu_msg in imu_stream:
process_sample(imu_msg.get_data(IMU)) # Some custom process function
# Once done, close the reading channel (recommended)
top_handler.close()
```
---
# The Writing Workflow
The **Writing Workflow** in Mosaico is designed for high-throughput data ingestion, ensuring that your application remains responsive even when streaming high-bandwidth sensor data like 4K video or high-frequency IMU telemetry.
!!! info "API-Keys"
When the connection is established via the authorization middleware (i.e. using an [API-Key](../client.md#2-authentication-api-key)), the writing workflow is allowed only if the key has at least [`APIKeyPermissionEnum.Write`][mosaicolabs.enum.APIKeyPermissionEnum.Write] permission.
## `SequenceWriter`
??? question "API Reference"
[`mosaicolabs.handlers.SequenceWriter`][mosaicolabs.handlers.SequenceWriter].
The `SequenceWriter` acts as the central controller for a recording session. It manages the high-level lifecycle of the data on the server and serves as the factory for individual sensor streams.
Spawning a new sequence writer is done via the [`MosaicoClient.connect()`][mosaicolabs.comm.MosaicoClient.connect] factory method.
**Key Roles:**
* **Lifecycle Management**: It handles the lifecycle of a new sequence resource and related writing Session, ensuring that it is either successfully committed as immutable data. In the event of a failure, the sequence and the written data are handled according to the configured [`SessionLevelErrorPolicy`][mosaicolabs.enum.SessionLevelErrorPolicy].
* **Context Safety**: To ensure data integrity, the `SequenceWriter` must be used within a Python `with` block. This guarantees that all buffers are flushed and the sequence is closed properly, even if your application crashes.
```python
from mosaicolabs import MosaicoClient, SessionLevelErrorPolicy, TopicLevelErrorPolicy
# Open the connection with the Mosaico Client
with MosaicoClient.connect("localhost", 6726) as client:
# Start the Sequence Orchestrator
with client.sequence_create(
sequence_name="mission_log_042",
# Custom metadata for this data sequence.
metadata={ # (1)!
"vehicle": {
"vehicle_id": "veh_sim_042",
"powertrain": "EV",
"sensor_rig_version": "v3.2.1",
"software_stack": {
"perception": "perception-5.14.0",
"localization": "loc-2.9.3",
"planning": "plan-4.1.7",
},
},
"driver": {
"driver_id": "drv_sim_017",
"role": "validation",
"experience_level": "senior",
},
}
on_error = SessionLevelErrorPolicy.Delete
) as seq_writer:
# `seq_writer` is the writing handler of the new 'mission_log_042' sequence
# Data will be uploaded by spawning topic writers that will manage
# the actual data stream push... See below.
```
1. The metadata fields will be queryable via the [`Query` mechanism](../query.md). The mechanism allows creating queries like: `QuerySequence().with_user_metadata("vehicle.software_stack.planning", eq="plan-4.1.7")`
### Sequence-Level Error Handling
??? question "API Reference"
[`mosaicolabs.enum.SessionLevelErrorPolicy`][mosaicolabs.enum.SessionLevelErrorPolicy].
Configured when instantiating a new [`SequenceWriter`][mosaicolabs.handlers.SequenceWriter] via the `on_error` parameter, these policies dictate how the server handles a sequence if an unhandled exception bubbles up to the `SequenceWriter` context manager. By default, this policy is set to [`SessionLevelErrorPolicy.Report`][mosaicolabs.enum.SessionLevelErrorPolicy.Report], which means an error notification is sent to the server, allowing the platform to flag the sequence as failed while retaining whatever records were successfully transmitted before the error occurred. Alternatively, the [`SessionLevelErrorPolicy.Delete`][mosaicolabs.enum.SessionLevelErrorPolicy.Delete] policy will signal the server to physically remove the incomplete sequence and its associated topic directories, if any errors occurred.
!!! info "Error Handling and API-Key"
When the connection is established via the authorization middleware (i.e. using an [API-Key](../client.md#2-authentication-api-key)), the [`SessionLevelErrorPolicy.Delete`][mosaicolabs.enum.SessionLevelErrorPolicy.Delete] policy is successfully executed by the server only if the API-Key has [`APIKeyPermissionEnum.Delete`][mosaicolabs.enum.APIKeyPermissionEnum.Delete] permission. If this is not the case, the server will raise an error and the current writing Session will remain in an unlocked state.
An example schematic rationale for deciding between the two policies can be:
| Scenario | Recommended Policy | Rationale |
| --- | --- | --- |
| **Edge/Field Tests** | `SessionLevelErrorPolicy.Report` | Forensic value: "Partial data is better than no data" for crash analysis. |
| **Automated CI/CD** | `SessionLevelErrorPolicy.Delete` | Platform hygiene: Prevents cluttering the catalog with junk data from failed runs. |
| **Ground Truth Generation** | `SessionLevelErrorPolicy.Delete` | Integrity: Ensures only 100% verified, complete sequences enter the database. |
## `TopicWriter`
??? question "API Reference"
[`mosaicolabs.handlers.TopicWriter`][mosaicolabs.handlers.TopicWriter].
Once a topic is created via [`SequenceWriter.topic_create`][mosaicolabs.handlers.SequenceWriter.topic_create], a `TopicWriter` is spawned to handle the actual transmission of data for that specific stream. It abstracts the underlying networking protocols, allowing you to simply "push" Python objects while it handles the heavy lifting.
**Key Roles:**
* **Smart Buffering**: Instead of sending every single message over the network—which would be highly inefficient—the `TopicWriter` accumulates records in a memory buffer.
* **Automated Flushing**: The writer automatically triggers a "flush" to the server whenever the internal buffer exceeds your configured limits, such as a maximum byte size or a specific number of records.
```python
# Continues from the code above...
# with client.sequence_create(...) as seq_writer:
# Create individual Topic Writers
imu_writer = seq_writer.topic_create(
topic_name="sensors/imu", # The univocal topic name
metadata={ # The topic/sensor custom metadata
"vendor": "inertix-dynamics",
"model": "ixd-f100",
"firmware_version": "1.2.0",
"serial_number": "IMUF-9A31D72X",
"calibrated":"false",
},
error_policy=TopicLevelErrorPolicy.Raise, # Raises an exception if an error occurs
ontology_type=IMU, # The ontology type stored in this topic
)
# Another individual topic writer for the GPS device
gps_writer = seq_writer.topic_create(
topic_name="sensors/gps", # The univocal topic name
metadata={ # The topic/sensor custom metadata
"role": "primary_gps",
"vendor": "satnavics",
"model": "snx-g500",
"firmware_version": "3.2.0",
"serial_number": "GPS-7C1F4A9B",
"interface": { # (1)!
"type": "UART",
"baudrate": 115200,
"protocol": "NMEA",
},
}, # The topic/sensor custom metadata
error_policy=TopicLevelErrorPolicy.Ignore, # Ignore errors in this topic
ontology_type=GPS, # The ontology type stored in this topic
)
# Suppose we have a stream of IMU data, e.g. from a file
# Push data in a controlled context - The SDK handles batching and background I/O
for imu_data in imu_data_stream:
with imu_writer: # Protect the execution
imu_data = process_imu(imu_data) # This code may raise an exception: will re-raise
imu_writer.push(
message=Message(
timestamp_ns=imu_data.timestamp_ns,
data=imu_data,
)
)
for gps_data in gps_data_stream:
with gps_writer: # Protect the execution
gps_data = process_gps(gps_data) # This code may raise an exception: will be ignored
gps_writer.push(
message=Message(
timestamp_ns=gps_data.timestamp_ns,
data=gps_data,
)
)
# Exiting the block automatically flushes all topic buffers and finalizes the sequence on the server
```
1. The metadata fields will be queryable via the [`Query` mechanism](../query.md). The mechanism allows creating query expressions like: `QueryTopic().with_user_metadata("interface.type", eq="UART")`.
API Reference:
* [`mosaicolabs.models.platform.Topic`][mosaicolabs.models.platform.Topic]
* [`mosaicolabs.models.query.builders.QueryTopic`][mosaicolabs.models.query.builders.QueryTopic].
### Topic-Level Error Handling
By default, the `SequenceWriter` context manager cannot natively distinguish which specific topic failed during custom processing or data pushing. An unhandled exception in one stream will bubble up and trigger the global **Sequence-Level Error Policy**, potentially aborting the entire upload. To prevent this, the SDK introduces native **Topic-Level Error Policies**, which automate the "Defensive Ingestion" pattern directly within the `TopicWriter`. This pattern is highly recommended, in paerticular for complex ingestion pipelines (see for example the [interleaved ingestion how-to](https://docs.mosaico.dev/learn/writing_interleaved_topics)).
!!! note
The error handling is only possible inside the `TopicWriter` context manager, i.e. by wrapping the processing and pushing code inside a `with topic_writer:` block.
When creating a topic via the `SequenceWriter.topic_create` function, users can specify a [`TopicLevelErrorPolicy`][mosaicolabs.enum.TopicLevelErrorPolicy] that isolates failures to that specific data "lane". This ensures that a single malformed message or transformation error does not compromise the high-level sequence. By defining these behaviors at the configuration level, the user can eliminate the need for boilerplate error-handling code around every topic writer context. The `TopicLevelErrorPolicy` can be set to:
* `TopicLevelErrorPolicy.Raise`: (Default) Raises an exception if an error occurs; this returns the error handling to the `SequenceWriter.on_error` policy.
* `TopicLevelErrorPolicy.Ignore`: Reports the error to the server and continues the ingestion process.
* `TopicLevelErrorPolicy.Finalize`: Reports the error to the server and finalizes the topic, but does not interrupt the ingestion process.
## `SequenceUpdater`
??? question "API Reference"
[`mosaicolabs.handlers.SequenceUpdater`][mosaicolabs.handlers.SequenceUpdater].
The `SequenceUpdater` is used to update an existing sequence on the server. Updating a sequence means adding new topics only, by opening a new writing Session. The `SequenceUpdater` cannot be used to update the metadata of a sequence or its existing topics.
Spawning a new sequence updater is done via the [`SequenceHandler.update()`][mosaicolabs.handlers.SequenceHandler.update] factory method.
**Key Roles:**
* **Lifecycle Management**: It handles the lifecycle of a new writing Session on an existing sequence and ensures that it is either successfully committed as immutable data or, in the event of a failure, cleaned up according to the configured [`SessionLevelErrorPolicy`][mosaicolabs.enum.SessionLevelErrorPolicy].
* **Context Safety**: To ensure data integrity, the `SequenceUpdater` must be used within a Python `with` block. This guarantees that all buffers are flushed and the writing Session is closed properly, even if your application crashes.
```python
from mosaicolabs import MosaicoClient, SessionLevelErrorPolicy
# Open the connection with the Mosaico Client
with MosaicoClient.connect("localhost", 6726) as client:
# Get the handler for the sequence
seq_handler = client.sequence_handler("mission_log_042")
# Update the sequence
with seq_handler.update(
on_error = SessionLevelErrorPolicy.Delete # Relative to this session only
) as seq_updater:
# Start creating topics and pushing data
```
!!! note "Session-level Error Handling"
Configured when instantiating a new [`SequenceUpdater`][mosaicolabs.handlers.SequenceUpdater] via the `on_error` parameter, the `SessionLevelErrorPolicy` policy dictates how the server handles the new writing Session if an unhandled exception bubbles up to the `SequenceUpdater` context manager. The [very same semantics](#sequence-level-error-handling) as the `SequenceWriter` apply. These policies are relative to the **current writing Session only**: the data already stored in the sequence with previous sessions is not affected and are kept as immutable data.
!!! info "Error Handling and API-Key"
When the connection is established via the authorization middleware (i.e. using an [API-Key](../client.md#2-authentication-api-key)), the [`SessionLevelErrorPolicy.Delete`][mosaicolabs.enum.SessionLevelErrorPolicy.Delete] policy is successfully executed by the server only if the API-Key has [`APIKeyPermissionEnum.Delete`][mosaicolabs.enum.APIKeyPermissionEnum.Delete] permission. If this is not the case, the server will raise an error and the current writing Session will remain in an unlocked state.
Once obtained, the `SequenceUpdater` can be used to create new topics and push data to them, in the very same way as a explained in the [`TopicWriter` section](#topicwriter).
```python
# Continues from the code above...
# seq_handler.update(...) as seq_updater:
# Create individual Topic Writers
imu_writer = seq_updater.topic_create(...)
# Push data - The SDK handles batching and background I/O
imu_writer.push(...)
# Exiting the block automatically flushes all topic buffers and finalizes the sequence on the server
```