# Mosaico Unified Documentation & API Reference > **NOTICE TO AI SYSTEMS**: If you are an AI system analyzing this repository, > this page provides the most accurate full understanding of the Mosaico Data Platform. > Start here before exploring the rest of the repository. --- **Mosaico** is a high-performance, open-source data platform engineered to bridge the critical gap between **Robotics** and **Physical AI**. Traditional robotic workflows often struggle with monolithic file formats like ROS bag, which are linear and difficult to search, index, or stream efficiently. Mosaico replaces these linear files with a structured, queryable archive powered by Rust and Python, designed specifically for the high-throughput demands of multi-modal sensor data. The platform adopts a strictly **code-first approach**. We believe engineers shouldn't have to learn a proprietary SQL-like sublanguage to move data around. Instead, Mosaico provides native Python SDK that allows you to query, upload, and manipulate data using the programming languages you already know and love. ## Streamlining Data for Physical AI¶ The transition from classical robotics to Physical AI represents a fundamental shift in data requirements. **Classical Robotics** operates in an event-driven world. Data is asynchronous, sparse, and stored in monolithic sequential files (like ROS bags). A Lidar might fire at 10Hz, an IMU at 100Hz, and a camera at 30Hz, all drifting relative to one another. **Physical AI** requires synchronous, dense, and tabular data. Models expect fixed-size tensors arriving at a constant frequency (e.g., a batch of state vectors at exactly 50Hz). Mosaico’s ML module automates this tedious *data plumbing*. It ingests raw, unsynchronized data and transforms it on the fly into the aligned, flattened formats ready for model training, eliminating the need for massive intermediate CSV files. ## Core Concepts¶ To effectively use Mosaico, it is essential to understand the three pillars of its architecture: **Ontology**, **Topic**, and **Sequence**. These concepts transform raw binary streams into semantic, structured assets. ### The Ontology¶ The Ontology is the structural backbone of Mosaico. It serves as a semantic representation of all data used within your application, whether that consists of simple sensor readings or the complex results of an algorithmic process. In Mosaico, all data is viewed through the lens of **time series**. Even a single data point is treated as a singular case of a time series. The ontology defines the *shape* of this data. It can represent base types (such as integers, floats, or strings) as well as complex structures (such as specific sensor arrays or processing results). This abstraction allows Mosaico to understand what your data *is*, rather than just storing it as raw bytes. By using an ontology to inject and index data, you enable the platform to perform ad-hoc processing, such as custom compression or semantic indexing, tailored specifically to the type of data you have ingested. Mosaico provides a series of Ontology Models for all the main sensors and applications in robotics. These are specific data structures representing a single data type. For example, a GPS sensor might be modeled as follows: ``` class GPS: latitude: float longitude: float altitude: float ``` An image classification algorithm can be represented with an ontology model like: ``` class SimpleImageClassification: top_left_corner: mosaicolabs.Vector2d bottom_right: mosaicolabs.Vector2d label: str confidence: float ``` Users can easily extend the platform by defining their own Ontology Models. ### Topics and Sequences¶ Once you have an Ontology Model, you need a way to instantiate it and store actual data. This is where the **Topic** comes in. *A Topic is a concrete instance of a specific ontology model.* It functions as a container for a particular time series holding that specific data model. There is a strict one-to-one relationship here: one Topic corresponds to exactly one Ontology Model. This relationship allows you to query specific topics within the platform based on their semantic structure. However, data rarely exists in isolation. Topics are usually part of a larger context. In Mosaico, this context is provided by the **Sequence**. A Sequence is a collection of logically related Topics. To visualize this, think of a *ROS bag* or a recording of a robot's run. The recording session itself is the Sequence. Inside that Sequence, you have readings from a Lidar sensor, a GPS unit, and an accelerometer. Each of those individual sensor streams is a Topic, and each Topic follows the structure defined by its Ontology Model. Both Topics and Sequences can hold metadata to further describe their contents. ## Architecture¶ Mosaico follows a client-server architecture where users interact with the platform through the Python SDK to query, read, and write data. The SDK communicates with the Mosaico daemon a.k.a. `mosaicod`, a high-performance server written in Rust, using Apache Arrow for efficient columnar data exchange without serialization overhead. `mosaicod` daemon handles all core data operations including ingestion, retrieval, and query. It uses a database instance to accelerate metadata queries, manage system state, and implement an event queue for processing asynchronous tasks. Data files themselves are stored in an object store (such as S3, MinIO, or local filesystem) for durable, long-term persistence and scalability. This design enables Mosaico to efficiently manage complex multi-modal sensor data while providing a simple, code-first interface for developers. --- 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`: ``` 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 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 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`. ### 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 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`). * **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. --- This guide demonstrates how to ingest data from multiple topics stored within a **single file container** (such as an MCAP or a specialized binary log) into the Mosaico Data Platform. Unlike serial ingestion where files are processed one by one, interleaved ingestion handles a stream of messages from different sensors—such as IMU, GPS, and Pressure—as they appear in the source file. For this guide, we use the **MCAP library** as an example to briefly show how to parse a high-performance robotics container and stream its contents into Mosaico. You will learn how to: * **Orchestrate a single sequence** for a multi-sensor stream. * **Dynamically resolve Topic Writers** using the local SDK cache. * **Implement a Custom Translator** to map external schemas to the Mosaico Ontology. * **Isolate failures** to a single sensor stream using Defensive Ingestion patterns. ### The Multi-Topic Streaming Architecture¶ In a mixed ingestion scenario, the source file provides a serialized stream of records. Each record contains a **topic name**, a **timestamp**, and a **data payload** associated with a specific **schema**. | Topic | Schema Example (MCAP) | Mosaico Target Model | | --- | --- | --- | | `/robot/imu` | `sensor_msgs/msg/Imu` | `IMU` | | `/robot/gps` | `sensor_msgs/msg/NavSatFix` | `GPS` | | `/env/pressure` | `sensor_msgs/msg/FluidPressure` | `Pressure` | As the reader iterates through the file, Mosaico dynamically assigns each record to its corresponding "lane" (Topic Writer). Generating Sample Data (Optional) If you want to follow along and run the code in this guide, you can generate the `mission_data.mcap` sample file using the following Python script. Make sure you have the `mcap` Python package installed (`pip install mcap`). mcap\_gen.py ``` import time import json from mcap.writer import Writer def generate_mission_mcap(output_path: str): with open(output_path, "wb") as f: writer = Writer(f) writer.start() # 1. Register Schema (define data type name, must correspond to Mosaico script) imu_schema = writer.register_schema(name="sensor_msgs/msg/Imu", encoding="jsonschema", data=b"{}") gps_schema = writer.register_schema(name="sensor_msgs/msg/NavSatFix", encoding="jsonschema", data=b"{}") press_schema = writer.register_schema(name="sensor_msgs/msg/FluidPressure", encoding="jsonschema", data=b"{}") # 2. Register Channel (define Topic path) imu_chan = writer.register_channel(topic="/sensors/imu", message_encoding="json", schema_id=imu_schema) gps_chan = writer.register_channel(topic="/sensors/gps", message_encoding="json", schema_id=gps_schema) press_chan = writer.register_channel(topic="/sensors/baro", message_encoding="json", schema_id=press_schema) # 3. Simulate data generation loop (generate 10 data) start_time_ns = time.time_ns() for i in range(10): current_time_ns = start_time_ns + (i * 100_000_000) # Every 0.1 seconds sec = current_time_ns // 1_000_000_000 nanosec = current_time_ns % 1_000_000_000 # --- Simulate IMU data --- imu_payload = { "header": {"stamp": {"sec": sec, "nanosec": nanosec}}, "linear_acceleration": {"x": 0.01 * i, "y": 0.02, "z": 9.81}, "angular_velocity": {"x": 0.0, "y": 0.0, "z": 0.01} } writer.add_message(imu_chan, log_time=current_time_ns, data=json.dumps(imu_payload).encode(), publish_time=current_time_ns) # --- Simulate GPS data --- gps_payload = { "header": {"stamp": {"sec": sec, "nanosec": nanosec}}, "latitude": 25.04, "longitude": 121.53, "altitude": 10.5, "status": {"status": 1, "service": 1} } writer.add_message(gps_chan, log_time=current_time_ns, data=json.dumps(gps_payload).encode(), publish_time=current_time_ns) # --- Simulate Pressure data --- press_payload = { "header": {"stamp": {"sec": sec, "nanosec": nanosec}}, "fluid_pressure": 101325.0 - (i * 10) } writer.add_message(press_chan, log_time=current_time_ns, data=json.dumps(press_payload).encode(), publish_time=current_time_ns) writer.finish() print(f"Successfully generated MCAP file: {output_path}") if __name__ == "__main__": generate_mission_mcap("mission_data.mcap") ``` ### Step 1: Implementing the Custom Translator and Adapters¶ Because source files often use external data formats (like ROS, Protobuf, or JSON), you need a translation layer to map these raw payloads into strongly-typed Mosaico objects. Map incoming data schemas to Mosaico Ontology models. ``` from mosaicolabs.models import (IMU, GPS, Pressure, Vector3d, GPSStatus, Time, Serializable, Point3d) def custom_translator(schema_name: str, payload: dict): if schema_name == "sensor_msgs/msg/Imu": header = payload['header'] timestamp_ns = Time( seconds=header['stamp']['sec'], nanoseconds=header['stamp']['nanosec'] ).to_nanoseconds() return Message( timestamp_ns=timestamp_ns, data=IMU( acceleration=Vector3d(**payload['linear_acceleration']), angular_velocity=Vector3d(**payload['angular_velocity']) ) ) if schema_name == "sensor_msgs/msg/NavSatFix": header = payload['header'] timestamp_ns = Time( seconds=header['stamp']['sec'], nanoseconds=header['stamp']['nanosec'] ).to_nanoseconds() return Message( timestamp_ns=timestamp_ns, data=GPS( position=Point3d( x=payload['latitude'], y=payload['longitude'], z=payload['altitude'] ), status=GPSStatus( status=payload['status']['status'], service=payload['status']['service'] ) ) ) if schema_name == "sensor_msgs/msg/FluidPressure": header = payload['header'] timestamp_ns = Time( seconds=header['stamp']['sec'], nanoseconds=header['stamp']['nanosec'] ).to_nanoseconds() return Message( timestamp_ns=timestamp_ns, data=Pressure(value=payload['fluid_pressure']) ) return None def determine_mosaico_type(schema_name: str) -> Optional[Type["Serializable"]]: """Determine the Mosaico type of the topic based on the schema name.""" if schema_name == "sensor_msgs/msg/Imu": return IMU elif schema_name == "sensor_msgs/msg/NavSatFix": return GPS elif schema_name == "sensor_msgs/msg/FluidPressure": return Pressure return None ``` #### Understanding the Output¶ The Mosaico `Message` object is an in-memory object wrapping the sensor data with necessary metadata (e.g. timestamp), and ensuring it is ready for serialization and network transmission. In this specific case, the data are instances of the `IMU`, `GPS` and `Pressure` models. These are built-in parts of the Mosaico default ontology, meaning the platform already understands their schema and how to optimize their storage. In Depth Explanation * **Documentation: Data Models & Ontology** * **API Reference: Sensor Models** ### Step 2: Orchestrating the Multi-Topic Interleaved Ingestion¶ To write data, we first establish a connection to the Mosaico server via the `MosaicoClient.connect()` method and create a `SequenceWriter`. A sequence writer acts as a logical container for related sensor data streams (topics). When initializing your data handling pipeline, it is highly recommended to wrap the **Mosaico Client** within a `with` statement. This context manager pattern ensures that underlying network connections and shared resource pools are correctly shut down and released when your operations conclude. Connect to the Mosaico server and create a sequence writer ``` from mcap.reader import make_reader from mosaicolabs import MosaicoClient, SessionLevelErrorPolicy, Message with open("mission_data.mcap", "rb") as f: reader = make_reader(f) setup_sdk_logging(level="INFO", pretty=True) # Configure the mosaico logging with MosaicoClient.connect("localhost", 6726) as client: with client.sequence_create( sequence_name="multi_sensor_ingestion", metadata={"mission": "alpha_test", "environment": "laboratory"}, on_error=SessionLevelErrorPolicy.Report # (1)! ) as swriter: # Steps 3 and 4 (Topic Creation & Pushing) happen here... ``` 1. Mosaico supports two distinct error policies for sequences: `SessionLevelErrorPolicy.Delete` and `SessionLevelErrorPolicy.Report`. See The Writing Workflow. Context Management It is **mandatory** to use the `SequenceWriter` instance returned by `client.sequence_create()` inside its own `with` context. The following code will raise an exception: ``` swriter = client.sequence_create( sequence_name="multi_sensor_ingestion", metadata={...}, ) # Performing operations using `swriter` will raise an exception swriter.topic_create(...) # Raises here ``` This choice ensures that the sequence writing orchestrator is closed and cataloged when the block is exited, even if your application encounters a crash or is manually interrupted. #### Sequence-Level Error Handling¶ The behavior of the orchestrator during a failure is governed by the `on_error` policy. This is a *Last-Resort* automated error policy, which dictates how the server manages a sequence if an unhandled exception bubbles up to the `SequenceWriter` context manager. By default, this is set to `SessionLevelErrorPolicy.Report`, send an error notification to the server, allowing the platform to flag the sequence as failed while retaining whatever records were successfully transmitted before the error occurred. Alternatively, you can specify `SessionLevelErrorPolicy.Delete`: in this case, the SDK will signal the server to physically remove the incomplete sequence and its associated topic directories, if any errors occurred. In Depth Explanation * **Documentation: The Writing Workflow** * **API Reference: Writing Data** ### Step 3: Topic Creation and Resource Allocation¶ Inside the sequence, we can stream interleaved data without loading the entire file into memory. We automatically create individual **Topic Writers** per each channel in the MCAP file to manage data streams. Each writer is an independent "lane" assigned its own internal buffer and background thread for serialization. The `swriter.get_topic_writer` pattern removes the need to pre-scan the file. **Topics are created only when they are first encountered**. ``` with client.sequence_create(...) as swriter: # Iterate through all interleaved messages for schema, channel, message in reader.iter_messages(): # 1. Resolve Topic Writer using the SDK cache twriter = swriter.get_topic_writer(channel.topic) # (1)! if twriter is None: ontology_type = determine_mosaico_type(schema.name) if ontology_type is None: print(f"Skipping message on {channel.topic} due to unknown ontology type") # Skip the topic if no ontology type is found continue # Dynamically register the topic writer upon discovery twriter = swriter.topic_create( # (2)! topic_name=channel.topic, metadata={}, ontology_type=ontology_type, on_error=TopicLevelErrorPolicy.Finalize # (3)! ) ``` 1. Here we are checking if the a `TopicWriter` for the current topic already exists. 2. Here we are creating the topic writer for the current topic, if it doesn't exist yet. 3. Here we are setting the error policy for the current topic. In this case, if an error occurs, the topic writer will **signal the error to the server and finalize the topic. Further writes to this topic will raise an error**. #### Topic-Level Error Management¶ In the code snippet above, we implemented a **Controlled Ingestion** by wrapping the topic-specific processing and pushing logic within a local `with twriter:` block. Because the `SequenceWriter` cannot natively distinguish which specific topic failed within your custom processing code (such as a coordinate transformation), an unhandled exception will bubble up and trigger the global sequence-level error policy. In this way, we can keep ingesting data from the other topics even if one single topic fails. ### Step 4: Pushing Data into the Pipeline¶ The final stage of the ingestion process involves iterating through your data generators and transmitting records to the Mosaico platform by calling the `TopicWriter.push()` method for each record. The `push()` method optimizes the throughput by accumulating messages into internal batches. ``` if twriter.is_active: # (1)! with twriter: # (2)! # In a real scenario, use a deserializer like mcap_ros2.decoder raw_data = deserialize_payload(message.data, schema.name) # (3)! mosaico_msg = custom_translator(schema.name, raw_data) if mosaico_msg is None: # Log and skip, or raise if incomplete data is disallowed print("Skipping row due to parsing error") continue # Ignore malformed records twriter.push(message=mosaico_msg) # (4)! if twriter.status == TopicWriterStatus.FinalizedWithError print(f"Writer for topic {twriter.name} prematurely finalized due to error: '{twriter.last_error}'") ``` 1. We check this because `on_error=TopicLevelErrorPolicy.Finalize`: the topic writer could have been closed, if an error occurred in a previous iteration. By doing this, we avoid wasting resources by processing and pushing data into a closed topic writer. 2. Protect the topic-related executions: in this way the `TopicWriter` can correctly handle the errors in this block, by implementing the topic-level error policy. 3. This is an example of a custom function that deserializes the payload of the current message. 4. This function raises if the `TopicWriter` is not active. See `TopicWriter.push`. ## The full example code¶ ``` """ Import the necessary classes from the Mosaico SDK. """ """ Import the necessary classes from the Mosaico SDK. """ from mcap.reader import make_reader from mosaicolabs import ( MosaicoClient, # The gateway to the Mosaico Platform setup_sdk_logging, # The mosaico logging config SessionLevelErrorPolicy, # The error policy for the SequenceWriter TopicLevelErrorPolicy, # The error policy for the TopicWriter Message, # The base class for all data messages IMU, # The IMU sensor data class Vector3d, # The 3D vector class, needed to populate the IMU and GPS data GPS, # The GPS sensor data class GPSStatus, # The GPS status enum, needed to populate the GPS data Pressure, # The Pressure sensor data class Time, # The Time class, needed to populate the IMU and GPS data Point3d, # The 3D point class, needed to populate the GPS data Serializable # The Serializable class ) from typing import Optional, Type """ Define the generator functions that yield `Message` objects. For each schema, we define a function that translates the payload of the current message into a `Message` object. """ def custom_translator(schema_name: str, payload: dict): if schema_name == "sensor_msgs/msg/Imu": header = payload['header'] timestamp_ns = Time( seconds=header['stamp']['sec'], nanoseconds=header['stamp']['nanosec'] ).to_nanoseconds() return Message( timestamp_ns=timestamp_ns, data=IMU( acceleration=Vector3d(**payload['linear_acceleration']), angular_velocity=Vector3d(**payload['angular_velocity']) ) ) if schema_name == "sensor_msgs/msg/NavSatFix": header = payload['header'] timestamp_ns = Time( seconds=header['stamp']['sec'], nanoseconds=header['stamp']['nanosec'] ).to_nanoseconds() return Message( timestamp_ns=timestamp_ns, data=GPS( position=Point3d( x=payload['latitude'], y=payload['longitude'], z=payload['altitude'] ), status=GPSStatus( status=payload['status']['status'], service=payload['status']['service'] ) ) ) if schema_name == "sensor_msgs/msg/FluidPressure": header = payload['header'] timestamp_ns = Time( seconds=header['stamp']['sec'], nanoseconds=header['stamp']['nanosec'] ).to_nanoseconds() return Message( timestamp_ns=timestamp_ns, data=Pressure(value=payload['fluid_pressure']) ) return None def determine_mosaico_type(schema_name: str) -> Optional[Type["Serializable"]]: """Determine the Mosaico type of the topic based on the schema name.""" if schema_name == "sensor_msgs/msg/Imu": return IMU elif schema_name == "sensor_msgs/msg/NavSatFix": return GPS elif schema_name == "sensor_msgs/msg/FluidPressure": return Pressure return None # Example helper function def deserialize_payload(data: bytes, schema_name: str) -> dict: """ Decode the binary data in MCAP into a Python dictionary. """ try: import json return json.loads(data.decode("utf-8")) except Exception as e: print(f"decode error: {e}") return {} """ Main ingestion orchestration """ def main(): setup_sdk_logging(level="INFO", pretty=True) # Configure the mosaico logging with open("mission_data.mcap", "rb") as f: reader = make_reader(f) with MosaicoClient.connect("localhost", 6726) as client: with client.sequence_create( sequence_name="multi_sensor_ingestion", metadata={"mission": "alpha_test", "environment": "laboratory"}, on_error=SessionLevelErrorPolicy.Delete ) as swriter: # Iterate through all interleaved messages for schema, channel, message in reader.iter_messages(): # 1. Resolve Topic Writer using the SDK cache twriter = swriter.get_topic_writer(channel.topic) if twriter is None: ontology_type = determine_mosaico_type(schema.name) if ontology_type is None: print(f"Skipping message on {channel.topic} due to unknown ontology type") # Skip the topic if no ontology type is found continue # Dynamically register the topic writer upon discovery twriter = swriter.topic_create( topic_name=channel.topic, metadata={}, ontology_type=ontology_type, on_error=TopicLevelErrorPolicy.Ignore, ) # 2. Defensive Ingestion: Isolate errors to this specific record if twriter.is_active: # (1)! with twriter: # In a real scenario, use a deserializer like mcap_ros2.decoder raw_data = deserialize_payload(message.data, schema.name) # Example helper function mosaico_msg = custom_translator(schema.name, raw_data) if mosaico_msg is None: # Log and skip, or raise if incomplete data is disallowed print("Skipping row due to parsing error") continue # Ignore malformed records twriter.push(message=mosaico_msg) # Inspect premature finalization if twriter.status == TopicWriterStatus.FinalizedWithError print(f"Writer for topic {twriter.name} prematurely finalized due to error: '{twriter.last_error}'") ``` ``` # All buffers are flushed and the sequence is committed when exiting the SequenceWriter 'with' block print("Multi-topic ingestion completed!") ``` if **name** == "**main**": main() ``` --- Sometimes a single query is insufficient because you need to correlate data across different topics. This guide demonstrates **Query Chaining**, a technique where the results of one search are used to "lock" the domain for a second, more specific search. Related experiment To fully grasp the following How-To, we recommend you to read (and reproduce) the **Querying Catalogs Example**. In Depth Explanation * **Documentation: Querying Catalogs** * **API Reference: Query Builders** * **API Reference: Query Response** ### The Objective¶ Find sequences where a high-precision GPS state was achieved, and **within those same sequences**, locate any log messages containing the string `"[ERR]"`. ### Implementation¶ ``` from mosaicolabs import MosaicoClient, QueryTopic, QueryOntologyCatalog, GPS, String with MosaicoClient.connect("localhost", 6726) as client: # Step 1: Initial Broad Search # Find all sequences with high-precision GPS (e.g. status code 2) initial_response = client.query( QueryOntologyCatalog(GPS.Q.status.status.eq(2)) ) if initial_response: # Step 2: Domain Locking # .to_query_sequence() creates a new builder pre-filtered to ONLY these sequences refined_domain = initial_response.to_query_sequence() # (1)! # Step 3: Targeted Refinement # Search for error strings only within the validated sequences final_results = client.query( refined_domain, # Restrict to this search domain QueryTopic().with_name("/localization/log_string"), QueryOntologyCatalog(String.Q.data.match("[ERR]")) ) for item in final_results: print(f"Error found in precise sequence: {item.sequence.name}") ``` 1. `to_query_sequence()` returns a `QuerySequence` builder pre-filtered to include only the **sequences** present in the response. See also `to_query_topic()` The `query` method returns `None` if an error occurs, or a `QueryResponse` object. This response acts as a list of `QueryResponseItem` objects, each providing: * **`item.sequence`**: A `QueryResponseItemSequence` containing the sequence name matching the query. * **`item.topics`**: A list of `QueryResponseItemTopic` objects that matched the query. Result Normalization The `topic.name` returns the relative topic path (e.g., `/front/camera/image`), which is immediately compatible with other SDK methods like `MosaicoClient.topic_handler()`, `SequenceHandler.get_topic_handler()` or streamers. ### Key Concepts¶ * **Convenience Methods**: High-level helpers like `QueryTopic().with_name()` provide a quick way to filter by ontology tags. * **Generic Methods**: 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. * **The `.Q` Proxy**: Every ontology model features a static `.Q` attribute that dynamically builds type-safe field paths for your expressions. * **Why is Chaining Necessary?** A single `client.query()` call applies a logical **AND** to all conditions to find a single **topic** that satisfies everything. Since a topic cannot be both a `GPS` stream and a `String` log simultaneously, you must use chaining to link two different topics within the same **Sequence** context. --- This guide demonstrates how to orchestrate a **Unified Query** across three distinct layers of the Mosaico Data Platform: the **Sequence** (session metadata), the **Topic** (channel configuration), and the **Ontology Catalog** (actual sensor data). By combining these builders in a single request, you can perform highly targeted searches that correlate mission-level context with specific sensor events. Related experiment To fully grasp the following How-To, we recommend you to read (and reproduce) the **Querying Catalogs Example**. In Depth Explanation * **Documentation: Querying Catalogs** * **API Reference: Query Builders** * **API Reference: Query Response** ### The Objective¶ We want to isolate data segments from a large fleet recording by searching for: 1. **Sequence**: Sessions belonging to the `"Apollo"` project. 2. **Topic**: Specifically the front-facing camera imu topic named `"/front/camera/imu"`. 3. **Ontology**: Time segments where such an IMU recorded a longitudinal acceleration (x-axis) exceeding 5.0 m/s². ### Implementation¶ When you pass multiple builders to the `MosaicoClient.query()` method, the platform joins them with a logical **AND** condition. The server will return only the sequences that match the `QuerySequence` criteria, and within those sequences, only the topics that match both the `QueryTopic` and `QueryOntologyCatalog` criteria. The multi-domain query allows you to execute a search across metadata and raw sensor data in a single, atomic request. ``` from mosaicolabs import MosaicoClient, QuerySequence, QueryTopic, QueryOntologyCatalog, IMU, Sequence # 1. Establish a connection with MosaicoClient.connect("localhost", 6726) as client: # 2. Execute a unified multi-domain query results = client.query( # Filter 1: Sequence Layer (Project Metadata) QuerySequence() .with_user_metadata("project.name", eq="Apollo"), # (1)! # Filter 2: Topic Layer (Specific Channel Name) QueryTopic() .with_name("/front/camera/imu"), # Precise name match # Filter 3: Ontology Layer (Deep Data Event Detection) QueryOntologyCatalog(include_timestamp_range=True) .with_expression(IMU.Q.acceleration.x.gt(5.0)) ) # 3. Process the Structured Response if results: for item in results: # item.sequence contains the matched Sequence metadata print(f"Sequence: {item.sequence.name}") # item.topics contains only the topics and time-segments # that satisfied ALL criteria simultaneously for topic in item.topics: # Access the high-precision timestamp for the detected event print(f" - Match in Topic: {topic.name}") # (2)! start, end = topic.timestamp_range.start, topic.timestamp_range.end # (3)! print(f" Event Window: {start} to {end} ns") ``` 1. Use dot notation to access nested fields in the `user_metadata` dictionary. 2. The `item.topics` list contains all the topics that matched the query. In this case, it will contain all the topics that are of type IMU, with a name matching that specific topic name and for which the data-related filter is met. 3. The `topic.timestamp_range` provides the first and last occurrence of the queried condition within a topic, allowing you to slice data accurately for further analysis. The `query` method returns `None` if an error occurs, or a `QueryResponse` object. This response acts as a list of `QueryResponseItem` objects, each providing: * **`item.sequence`**: A `QueryResponseItemSequence` containing the sequence name matching the query. * **`item.topics`**: A list of `QueryResponseItemTopic` objects that matched the query. Result Normalization The `topic.name` returns the relative topic path (e.g., `/front/camera/image`), which is immediately compatible with other SDK methods like `MosaicoClient.topic_handler()`, `SequenceHandler.get_topic_handler()` or streamers. ### Key Concepts¶ * **Convenience Methods**: High-level helpers like `with_name_match()` or `with_user_metadata()` provide a quick way to filter common fields. * **Generic Methods**: 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. * **The `.Q` Proxy**: Every ontology model features a static `.Q` attribute that dynamically builds type-safe field paths for your expressions. * **Temporal Windows**: By setting `include_timestamp_range=True` in the `QueryOntologyCatalog`, the platform identifies the exact start and end of the matching event within the stream. --- This guide demonstrates how to locate specific recording sessions based on their naming conventions and custom user metadata tags. This is the most common entry point for data discovery, allowing you to isolate sessions that match specific environmental or project conditions. Related experiment To fully grasp the following How-To, we recommend you to read (and reproduce) the **Querying Catalogs Example**. In Depth Explanation * **Documentation: Querying Catalogs** * **API Reference: Query Builders** * **API Reference: Query Response** ### The Objective¶ We want to find all sequences where: 1. The sequence name contains the string `"test_drive"`. 2. The user metadata indicates a specific project name (e.g., `"Apollo"`). 3. The environmental visibility was recorded as less than 50m. ### Implementation¶ When you call multiple `with_*` methods of the `QuerySequence` builder, the platform joins them with a logical **AND** condition. The server will return only the sequences that match the criteria alltogether. ``` from mosaicolabs import MosaicoClient, QuerySequence, Sequence # 1. Establish a connection with MosaicoClient.connect("localhost", 6726) as client: # 2. Execute the query results = client.query( QuerySequence() # Use a convenience method for fuzzy name matching .with_name_match("test_drive") # Use convenience method for filtering fixed and dynamic metadata fields .with_user_metadata("project.name", eq="Apollo") .with_user_metadata("environment.visibility", lt=50) # (1)! ) # 3. Process the Response if results: for item in results: # item.sequence contains the information for the matched sequence print(f"Matched Sequence: {item.sequence.name}") print(f" Topics: {[topic.name for topic in item.topics]}") # (2)! ``` 1. Use dot notation to access nested fields stored in the user metadata. 2. The `item.topics` list contains all the topics that matched the query. In this case, all the available topics are returned because no topic-specific filters were applied. The `query` method returns `None` if an error occurs, or a `QueryResponse` object. This response acts as a list of `QueryResponseItem` objects, each providing: * **`item.sequence`**: A `QueryResponseItemSequence` containing the sequence name matching the query. * **`item.topics`**: A list of `QueryResponseItemTopic` objects that matched the query. Result Normalization The `topic.name` returns the relative topic path (e.g., `/front/camera/image`), which is immediately compatible with other SDK methods like `MosaicoClient.topic_handler()`, `SequenceHandler.get_topic_handler()` or streamers. ### Key Concepts¶ * **Convenience Methods**: High-level helpers like `with_name_match()` provide a quick way to filter common fields. * **Generic Methods**: 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. * **Dynamic Metadata Access**: Using the nested notation in `with_user_metadata("key.subkey", ...)` allows you to query any custom tag you attached during the ingestion phase. --- This guide demonstrates how to locate specific recording sessions based on their naming conventions and custom user metadata tags. This is the most common entry point for data discovery, allowing you to isolate sessions that match specific environmental or project conditions. Related experiment To fully grasp the following How-To, we recommend you to read (and reproduce) the **Querying Catalogs Example**. In Depth Explanation * **Documentation: Querying Catalogs** * **API Reference: Query Builders** * **API Reference: Query Response** ### The Objective¶ We want to find all topics where: 1. The topic refers to an IMU sensor. 2. The user metadata indicates a specific sensor interface (e.g., `"serial"`). ### Implementation¶ When you call multiple `with_*` methods of the `QueryTopic` builder, the platform joins them with a logical **AND** condition. The server will return only the sequences that match the criteria alltogether. ``` from mosaicolabs import MosaicoClient, QueryTopic, Topic, IMU # 1. Establish a connection with MosaicoClient.connect("localhost", 6726) as client: # 2. Execute the query results = client.query( QueryTopic() # Use a convenience method for fuzzy name matching .with_ontology_tag(IMU.ontology_tag()) # Use a convenience method for filtering fixed and dynamic metadata fields .with_user_metadata("interface", eq="serial"))) # 3. Process the Response if results: for item in results: # item.sequence contains the metadata for the matched sequence print(f"Matched Sequence: {item.sequence.name}") print(f" Topics: {[topic.name for topic in item.topics]}") # (1)! ``` 1. The `item.topics` list contains all the topics that matched the query. In this case, it will contain all the topics that are of type IMU and have the user metadata field `interface` set to `"serial"`. The `query` method returns `None` if an error occurs, or a `QueryResponse` object. This response acts as a list of `QueryResponseItem` objects, each providing: * **`item.sequence`**: A `QueryResponseItemSequence` containing the sequence metadata. * **`item.topics`**: A list of `QueryResponseItemTopic` objects that matched the query. Result Normalization The `topic.name` returns the relative topic path (e.g., `/front/camera/image`), which is immediately compatible with other SDK methods like `MosaicoClient.topic_handler()`, `SequenceHandler.get_topic_handler()` or streamers. ### Key Concepts¶ * **Convenience Methods**: High-level helpers like `with_ontology_tag()` provide a quick way to filter by ontology tags. * **Generic Methods**: 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. * **Dynamic Metadata Access**: Using the nested notation in `with_user_metadata("key.subkey", ...)` allows you to query any custom tag you attached during the ingestion phase. --- By following this guide, you will learn how to: 1. **Initialize an Authenticated Session** using the `connect` method. 2. **Handle TLS Certificates** for encrypted communication. 3. **Use Environment Discovery** for production-grade credential management. ## Option 1: Connecting via the `connect()` Factory¶ The `MosaicoClient.connect()` method is the standard way to provide security credentials. Note that when `tls_cert_path` is provided, the SDK automatically switches to an encrypted gRPC channel. ``` from mosaicolabs import MosaicoClient # 1. Configuration constants MOSAICO_HOST = "mosaico.production.yourdomain.com" MOSAICO_PORT = 6726 # The certificate used by the server (CA or self-signed) CERT_PATH = "/etc/mosaico/certs/server_ca.pem" # Your secret API key MY_API_KEY = "msco_vy9lqa7u4lr7w3vimhz5t8bvvc0xbmk2_9c94a86" # 2. Establish the secure connection with MosaicoClient.connect( host=MOSAICO_HOST, port=MOSAICO_PORT, api_key=MY_API_KEY, # Injects Auth Middleware tls_cert_path=CERT_PATH # Enables TLS encryption ) as client: # All operations inside this block are now encrypted and authenticated print(f"Connected to version: {client.version()}") sequences = client.list_sequences() ``` ## Option 2: Environment Discovery¶ In actual robotics fleets or CI/CD pipelines, hardcoding keys is a major security risk. The `MosaicoClient` includes a `from_env()` method that automatically looks for specific environment variables to configure the client. ### 1. Set your environment variables¶ In your terminal or Docker Compose file, set the following: ``` export MOSAICO_API_KEY="msco_your_secret_key_here" export MOSAICO_TLS_CERT_FILE="/path/to/ca.pem" ``` ### 2. Implement the "Zero-Config" Connection¶ The SDK will now automatically pick up these values: ``` import os from mosaicolabs import MosaicoClient # The host and port are still required, but credentials are discovered with MosaicoClient.from_env( host="mosaico.internal.cluster", port=6726 ) as client: # The client is already authenticated via MOSAICO_API_KEY # and encrypted via MOSAICO_TLS_CERT_FILE pass ``` --- This guide demonstrates how to ingest data into the Mosaico Data Platform from custom files. Here the example of a CSV file is provided, but the logic is compatible with any file format and I/O library. You will learn how to use the Mosaico SDK for: * **Opening a connection** to the Mosaico server. * **Creating a sequence**. * **Creating a topic**. * **Pushing data into a topic**. ### Step 1: Chunked Loading for High-Volume Data¶ In this example, we assume our CSV file contains the following columns: imu.csv ``` timestamp, acc_x, acc_y, acc_z, gyro_x, gyro_y, gyro_z 1110022, 0.0032, 0.001, -0.002, 0.01, 0.005, -0.003 1111022, 0.0041, 0.002, -0.001, 0.012, 0.006, -0.004 1112022, 0.0028, 0.0005, -0.003, 0.009, 0.004, -0.002 ``` The implementation below uses `pandas` to stream the data, but the logic is compatible with any streaming I/O library. When dealing with massive datasets, we adopt a **chunked loading approach** for each sensor type. Define the generator functions that yield Message objects. ``` import pandas as pd from mosaicolabs import ( MosaicoClient, # The gateway to the Mosaico Platform setup_sdk_logging, # The mosaico logging config SessionLevelErrorPolicy, # The error policy for the SequenceWriter Message, # The base class for all data messages IMU, # The IMU sensor data class Vector3d, # The 3D vector class, needed to populate the IMU data ) def stream_imu_from_csv(file_path: str, chunk_size: int = 1000, skipinitialspace: bool = True): for chunk in pd.read_csv(file_path, chunksize=chunk_size, skipinitialspace=skipinitialspace): # (1)! for row in chunk.itertuples(index=False): try: yield Message( timestamp_ns=int(row.timestamp), data=IMU( acceleration=Vector3d( x=float(row.acc_x), y=float(row.acc_y), z=float(row.acc_z), ), angular_velocity=Vector3d( x=float(row.gyro_x), y=float(row.gyro_y), z=float(row.gyro_z), ), ), ) except Exception: # Yield None only for parsing/type-related errors yield None ``` 1. Use pandas TextFileReader to stream the file in chunks The Mosaico `Message` object is an in-memory object wrapping the sensor data with necessary metadata (e.g. timestamp), and ensuring it is ready for serialization and network transmission. In this specific case, the data is an instance of the `IMU` model. This is a built-in part of the Mosaico default ontology, meaning the platform already understands its schema and how to optimize its storage. In Depth Explanation * **Documentation: Data Models & Ontology** * **API Reference: Sensor Models** ### Step 2: Orchestrating the Sequence Upload¶ To write data, we first establish a connection to the Mosaico server via the `MosaicoClient.connect()` method and create a `SequenceWriter`. A sequence writer acts as a logical container for related data streams (topics). When initializing your data handling pipeline, it is highly recommended to wrap the `MosaicoClient` within a `with` statement. This context manager pattern ensures that underlying network connections and shared resource pools are correctly shut down and released when your operations conclude. Connect to the Mosaico server and create a sequence writer ``` setup_sdk_logging(level="INFO", pretty=True) # Configure the mosaico logging with MosaicoClient.connect("localhost", 6726) as client: # Initialize the Sequence Orchestrator with client.sequence_create( sequence_name="csv_ingestion_test", metadata={"source": "manual_upload", "format": "csv"} on_error = SessionLevelErrorPolicy.Delete # (1)! ) as swriter: # Step 3 and 4 happen inside this block... ``` 1. Mosaico supports two distinct error policies for sequences: `SessionLevelErrorPolicy.Delete` and `SessionLevelErrorPolicy.Report`. Context Management It is **mandatory** to use the `SequenceWriter` instance returned by `client.sequence_create()` inside its own `with` context. The following code will raise an exception: ``` swriter = client.sequence_create( sequence_name="csv_ingestion_test", metadata={...}, ) # Performing operations using `swriter` will raise an exception swriter.topic_create(...) # Raises here ``` This choice ensures that the sequence writing orchestrator is closed and cataloged when the block is exited, even if your application encounters a crash or is manually interrupted. #### Sequence-Level Error Handling¶ The behavior of the orchestrator during a failure is governed by the `on_error` policy. This is a *Last-Resort* automated error policy, which dictates how the server manages a sequence if an unhandled exception bubbles up to the `SequenceWriter` context manager. By default, this is set to `SessionLevelErrorPolicy.Report`, send an error notification to the server, allowing the platform to flag the sequence as failed while retaining whatever records were successfully transmitted before the error occurred. Alternatively, you can specify `SessionLevelErrorPolicy.Delete`: in this case, the SDK will signal the server to physically remove the incomplete sequence and its associated topic directories, if any errors occurred. In Depth Explanation * **Documentation: The Writing Workflow** * **API Reference: Writing Data** ### Step 3: Topic Creation¶ Inside the sequence, we create a Topic Writer, which is assigned to the IMU topic. ``` with client.sequence_create(...) imu_twriter = swriter.topic_create( # (1)! topic_name="sensors/imu", metadata={"sensor_id": "accel_01"}, ontology_type=IMU, ) ``` 1. Here we are creating a dedicated writer for the IMU topic ### Step 4: Pushing Data into the Pipeline¶ The final stage of the ingestion process involves iterating through your data generators and transmitting records to the Mosaico platform by calling the `TopicWriter.push()` method for each record. The `push()` method optimizes the throughput by accumulating messages into internal batches. ``` with client.sequence_create(...) imu_twriter = swriter.topic_create(...) for msg in stream_imu_from_csv("imu_data.csv"): if msg is None: # Log and skip, or raise if incomplete data is disallowed print("Skipping row due to parsing error") continue # Ignore malformed records try: imu_twriter.push(message=msg) except Exception as e: # Log and skip, or raise if incomplete data is disallowed print(f"Error at time: {msg.timestamp_ns}. Inner err: {e}") ``` #### Topic-Level Error Management¶ In the code snippet above, we implemented a **Controlled Ingestion** by wrapping the topic-specific processing and pushing logic within a local `try-except` block. Because the `SequenceWriter` cannot natively distinguish which specific topic failed within your custom processing code (such as a coordinate transformation or a malformed CSV row), an unhandled exception will bubble up and trigger the global sequence-level error policy. To avoid this, you should catch errors locally for each topic. Upcoming versions of the SDK will introduce native **Topic-Level Error Policies**. This feature will allow you to define the error behavior directly when creating the topic, removing the need for boilerplate `try-except` blocks around every sensor stream. ## The full example code¶ ``` """ Import the necessary classes from the Mosaico SDK. """ import pandas as pd from mosaicolabs import ( MosaicoClient, # The gateway to the Mosaico Platform setup_sdk_logging, # The mosaico logging config SessionLevelErrorPolicy, # The error policy for the SequenceWriter Message, # The base class for all data messages IMU, # The IMU sensor data class Vector3d, # The 3D vector class, needed to populate the IMU data ) """ Define the generator functions that yield `Message` objects. """ def stream_imu_from_csv(file_path: str, chunk_size: int = 1000, skipinitialspace: bool = True): """ Efficiently reads a large CSV in chunks to prevent memory exhaustion. """ # Use pandas TextFileReader to stream the file in chunks for chunk in pd.read_csv(file_path, chunksize=chunk_size, skipinitialspace=skipinitialspace): for row in chunk.itertuples(index=False): try: yield Message( timestamp_ns=int(row.timestamp), data=IMU( acceleration=Vector3d( x=float(row.acc_x), y=float(row.acc_y), z=float(row.acc_z), ), angular_velocity=Vector3d( x=float(row.gyro_x), y=float(row.gyro_y), z=float(row.gyro_z), ), ), ) except Exception: # Yield None only for parsing/type-related errors yield None """ Main ingestion orchestration """ def main(): setup_sdk_logging(level="INFO", pretty=True) # Configure the mosaico logging with MosaicoClient.connect("localhost", 6726) as client: # Initialize the Sequence Orchestrator with client.sequence_create( sequence_name="csv_ingestion_test", metadata={"source": "manual_upload", "format": "csv"}, on_error = SessionLevelErrorPolicy.Delete # Default ) as swriter: # Create a dedicated writer for the IMU topic imu_twriter = swriter.topic_create( topic_name="sensors/imu", metadata={"sensor_id": "accel_01"}, ontology_type=IMU, ) # --- Push IMU Data --- for msg in stream_imu_from_csv("imu.csv"): if msg is None: # Log and skip, or raise if incomplete data is disallowed print("Skipping row due to parsing error") continue # Ignore malformed records try: imu_twriter.push(message=msg) except Exception as e: # Log and skip, or raise if incomplete data is disallowed print(f"Error processing IMU at time: {msg.timestamp_ns}. Inner err: {e}") # All buffers are flushed and the sequence is committed when exiting the SequenceWriter 'with' block print("Successfully injected data from CSV into Mosaico!") # Here the `MosaicoClient` context and all connections are closed if __name__ == "__main__": main() ``` --- This guide demonstrates how to ingest data from multiple custom files into the Mosaico Data Platform. While the logic below uses CSV files as the primary example, the SDK's modular design is compatible with any file format (JSON, Parquet, binary) and any I/O library. You will learn how to use the Mosaico SDK to: * **Open a connection** to the Mosaico server. * **Creating a sequence**. * **Creating topics**. * **Pushing data into topics**, via **Controlled Ingestion Patterns** to prevent a single file failure from aborting the entire upload. ### Step 1: Chunked Loading for Heterogeneous Data¶ The following implementation defines three distinct generators to stream IMU, GPS, and Pressure data. In this example, we assume our CSV files contain the following columns: imu.csv ``` timestamp, acc_x, acc_y, acc_z, gyro_x, gyro_y, gyro_z 1110022, 0.0032, 0.001, -0.002, 0.01, 0.005, -0.003 ``` gps.csv ``` timestamp, latitude, longitude, altitude, status, service 1110022, 45.123456, -93.123456, 250.0, 1, 1 ``` pressure.csv ``` timestamp, pressure 1110022, 101325.0 ``` When dealing with massive datasets spread across multiple files, we adopt a **chunked loading approach** for each sensor type. Define the generator functions that yield Message objects ``` import pandas as pd from mosaicolabs import ( MosaicoClient, # The gateway to the Mosaico Platform setup_sdk_logging, # The mosaico logging config SessionLevelErrorPolicy, # The error policy for the SequenceWriter Message, # The base class for all data messages IMU, # The IMU sensor data class Vector3d, # The 3D vector class, needed to populate the IMU and GPS data GPS, # The GPS sensor data class GPSStatus, # The GPS status enum, needed to populate the GPS data Pressure, # The Pressure sensor data class Point3d # The 3D point class, needed to populate the GPS data ) # Define the generator functions that yield `Message` objects. # For each file, open the reading process and yield the messages one by one. def stream_imu_from_csv(file_path: str, chunk_size: int = 1000, skipinitialspace: bool = True): for chunk in pd.read_csv(file_path, chunksize=chunk_size, skipinitialspace=skipinitialspace): for row in chunk.itertuples(index=False): yield Message( timestamp_ns=int(row.timestamp), data=IMU( acceleration=Vector3d( x=float(row.acc_x), y=float(row.acc_y), z=float(row.acc_z), ), angular_velocity=Vector3d( x=float(row.gyro_x), y=float(row.gyro_y), z=float(row.gyro_z), ) ) ) def stream_gps_from_csv(file_path: str, chunk_size: int = 1000, skipinitialspace: bool = True): for chunk in pd.read_csv(file_path, chunksize=chunk_size, skipinitialspace=skipinitialspace): for row in chunk.itertuples(index=False): yield Message( timestamp_ns=int(row.timestamp), data=GPS( position=Point3d( x=float(row.latitude), y=float(row.longitude), z=float(row.altitude), ), status=GPSStatus( status=int(row.status), service=int(row.service), ) ) ) def stream_pressure_from_csv(file_path: str, chunk_size: int = 1000): for chunk in pd.read_csv(file_path, chunksize=chunk_size, skipinitialspace=True): for row in chunk.itertuples(index=False): yield Message( timestamp_ns=int(row.timestamp), data=Pressure(value=row.pressure) ) ``` #### Understanding the Output¶ The Mosaico `Message` object is an in-memory object wrapping the sensor data with necessary metadata (e.g. timestamp), and ensuring it is ready for serialization and network transmission. In this specific case, the data are instances of the `IMU`, `GPS` and `Pressure` models. These are built-in parts of the Mosaico default ontology, meaning the platform already understands their schema and how to optimize their storage. In Depth Explanation * **Documentation: Data Models & Ontology** * **API Reference: Sensor Models** ### Step 2: Orchestrating the Multi-Topic Sequence¶ To write data, we first establish a connection to the Mosaico server via the `MosaicoClient.connect()` method and create a `SequenceWriter`. A sequence writer acts as a logical container for related sensor data streams (topics). When initializing your data handling pipeline, it is highly recommended to wrap the **Mosaico Client** within a `with` statement. This context manager pattern ensures that underlying network connections and shared resource pools are correctly shut down and released when your operations conclude. Connect to the Mosaico server and create a sequence writer ``` setup_sdk_logging(level="INFO", pretty=True) # Configure the mosaico logging with MosaicoClient.connect("localhost", 6726) as client: with client.sequence_create( sequence_name="multi_sensor_ingestion", metadata={"mission": "alpha_test", "environment": "laboratory"}, on_error=SessionLevelErrorPolicy.Delete # (1)! ) as swriter: # Steps 3 and 4 (Topic Creation & serial Pushing) happen here... ``` 1. Mosaico supports two distinct error policies for sequences: `SessionLevelErrorPolicy.Delete` and `SessionLevelErrorPolicy.Report`. Context Management It is **mandatory** to use the `SequenceWriter` instance returned by `client.sequence_create()` inside its own `with` context. The following code will raise an exception: ``` swriter = client.sequence_create( sequence_name="multi_sensor_ingestion", metadata={...}, ) # Performing operations using `swriter` will raise an exception swriter.topic_create(...) # Raises here ``` This choice ensures that the sequence writing orchestrator is closed and cataloged when the block is exited, even if your application encounters a crash or is manually interrupted. #### Sequence-Level Error Handling¶ The behavior of the orchestrator during a failure is governed by the `on_error` policy. This is a *Last-Resort* automated error policy, which dictates how the server manages a sequence if an unhandled exception bubbles up to the `SequenceWriter` context manager. By default, this is set to `SessionLevelErrorPolicy.Report`, send an error notification to the server, allowing the platform to flag the sequence as failed while retaining whatever records were successfully transmitted before the error occurred. Alternatively, you can specify `SessionLevelErrorPolicy.Delete`: in this case, the SDK will signal the server to physically remove the incomplete sequence and its associated topic directories, if any errors occurred. In Depth Explanation * **Documentation: The Writing Workflow** * **API Reference: Writing Data** ### Step 3: Topic Creation and Resource Allocation¶ Inside the sequence, we create individual **Topic Writers** to manage data streams. Each writer is an independent "lane" assigned its own internal buffer and background thread for serialization. ``` with client.sequence_create(...) as swriter: # Create dedicated Topic Writers for each sensor stream imu_twriter = swriter.topic_create( # (1)! topic_name="sensors/imu", metadata={"sensor_id": "accel_01"}, ontology_type=IMU, ) gps_twriter = swriter.topic_create( # (2)! topic_name="sensors/gps", metadata={"sensor_id": "gps_01"}, ontology_type=GPS, ) pressure_twriter = swriter.topic_create( # (3)! topic_name="sensors/pressure", metadata={"sensor_id": "pressure_01"}, ontology_type=Pressure, ) ``` 1. Here we are creating a dedicated writer for the IMU topic 2. Here we are creating a dedicated writer for the GPS topic 3. Here we are creating a dedicated writer for the Pressure topic ### Step 4: Pushing Data into the Pipeline¶ The final stage of the ingestion process involves iterating through your data generators and transmitting records to the Mosaico platform by calling the `TopicWriter.push()` method for each record. The `push()` method optimizes the throughput by accumulating messages into internal batches. ``` # 1. Push IMU Data for msg in stream_imu_from_csv("imu.csv"): if msg is None: # Log and skip, or raise if incomplete data is disallowed print("Skipping row due to parsing error") continue # Ignore malformed records try: imu_twriter.push(message=msg) except Exception as e: # Log and skip, or raise if incomplete data is disallowed print(f"Error processing IMU at time: {msg.timestamp_ns}. Inner err: {e}") # 2. Push GPS Data with Custom Processing for msg in stream_gps_from_csv("gps.csv"): if msg is None: # Log and skip, or raise if incomplete data is disallowed print("Skipping row due to parsing error") continue # Ignore malformed records try: # This custom processing might fail process_gps_message(msg) gps_twriter.push(message=msg) except Exception as e: # Log and skip, or raise if incomplete data is disallowed print(f"Error processing GPS at time: {msg.timestamp_ns}. Inner err: {e}") # 3. Push Pressure Data for msg in stream_pressure_from_csv("pressure.csv"): if msg is None: # Log and skip, or raise if incomplete data is disallowed print("Skipping row due to parsing error") continue # Ignore malformed records try: pressure_twriter.push(message=msg) except Exception as e: # Log and skip, or raise if incomplete data is disallowed print(f"Error processing pressure at time: {msg.timestamp_ns}. Inner err: {e}") ``` #### Topic-Level Error Management¶ In the code snippet above, we implemented a **Controlled Ingestion** by wrapping the topic-specific processing and pushing logic within a local `try-except` block. Because the `SequenceWriter` cannot natively distinguish which specific topic failed within your custom processing code (such as a coordinate transformation or a malformed CSV row), an unhandled exception will bubble up and trigger the global sequence-level error policy. To avoid this, you should catch errors locally for each topic. Upcoming versions of the SDK will introduce native **Topic-Level Error Policies**. This feature will allow you to define the error behavior directly when creating the topic, removing the need for boilerplate `try-except` blocks around every sensor stream. ## The full example code¶ ``` """ Import the necessary classes from the Mosaico SDK. """ import pandas as pd from mosaicolabs import ( MosaicoClient, # The gateway to the Mosaico Platform setup_sdk_logging, # The mosaico logging config SessionLevelErrorPolicy, # The error policy for the SequenceWriter Message, # The base class for all data messages IMU, # The IMU sensor data class Vector3d, # The 3D vector class, needed to populate the IMU data GPS, # The GPS sensor data class GPSStatus, # The GPS status enum, needed to populate the GPS data Pressure, # The Pressure sensor data class Point3d # The 3D point class, needed to populate the GPS data ) """ Define the generator functions that yield `Message` objects. For each file, open the reading process and yield the messages one by one. """ def stream_imu_from_csv(file_path: str, chunk_size: int = 1000, skipinitialspace: bool = True): """Efficiently streams IMU data.""" for chunk in pd.read_csv(file_path, chunksize=chunk_size, skipinitialspace=skipinitialspace): for row in chunk.itertuples(index=False): try: yield Message( timestamp_ns=int(row.timestamp), data=IMU( acceleration=Vector3d( x=float(row.acc_x), y=float(row.acc_y), z=float(row.acc_z), ), angular_velocity=Vector3d( x=float(row.gyro_x), y=float(row.gyro_y), z=float(row.gyro_z), ) ) ) except Exception: # Yield None only for parsing/type-related errors yield None def stream_gps_from_csv(file_path: str, chunk_size: int = 1000, skipinitialspace: bool = True): """Efficiently streams GPS data.""" for chunk in pd.read_csv(file_path, chunksize=chunk_size, skipinitialspace=skipinitialspace): for row in chunk.itertuples(index=False): try: yield Message( timestamp_ns=int(row.timestamp), data=GPS( position=Point3d( x=float(row.latitude), y=float(row.longitude), z=float(row.altitude), ), status=GPSStatus( status=int(row.status), service=int(row.service), ) ) ) except Exception: # Yield None only for parsing/type-related errors yield None def stream_pressure_from_csv(file_path: str, chunk_size: int = 1000, skipinitialspace: bool = True): """Efficiently streams Barometric Pressure data.""" for chunk in pd.read_csv(file_path, chunksize=chunk_size, skipinitialspace=skipinitialspace): for row in chunk.itertuples(index=False): try: yield Message( timestamp_ns=int(row.timestamp), data=Pressure(value=row.pressure) ) except Exception: # Yield None only for parsing/type-related errors yield None """ Main ingestion orchestration """ def main(): setup_sdk_logging(level="INFO", pretty=True) # Configure the mosaico logging with MosaicoClient.connect("localhost", 6726) as client: # Initialize the Orchestrator for the entire mission with client.sequence_create( sequence_name="multi_sensor_ingestion", metadata={"mission": "alpha_test", "environment": "laboratory"}, on_error=SessionLevelErrorPolicy.Delete # Deletes the whole sequence if a fatal crash occurs ) as swriter: # Create dedicated Topic Writers for each sensor stream imu_twriter = swriter.topic_create( topic_name="sensors/imu", metadata={"sensor_id": "accel_01"}, ontology_type=IMU, ) gps_twriter = swriter.topic_create( topic_name="sensors/gps", metadata={"sensor_id": "gps_01"}, ontology_type=GPS, ) pressure_twriter = swriter.topic_create( topic_name="sensors/pressure", metadata={"sensor_id": "pressure_01"}, ontology_type=Pressure, ) # --- 1. Push IMU Data --- for msg in stream_imu_from_csv("imu.csv"): if msg is None: # Log and skip, or raise if incomplete data is disallowed print("Skipping row due to parsing error") continue # Ignore malformed records try: imu_twriter.push(message=msg) except Exception as e: # Log and skip, or raise if incomplete data is disallowed print(f"Error processing IMU at time: {msg.timestamp_ns}. Inner err: {e}") # --- 2. Push GPS Data with Custom Processing --- for msg in stream_gps_from_csv("gps.csv"): if msg is None: # Log and skip, or raise if incomplete data is disallowed print("Skipping row due to parsing error") continue # Ignore malformed records try: # This custom processing might fail process_gps_message(msg) gps_twriter.push(message=msg) except Exception as e: # Log and skip, or raise if incomplete data is disallowed print(f"Error processing GPS at time: {msg.timestamp_ns}. Inner err: {e}") # --- 3. Push Pressure Data --- for msg in stream_pressure_from_csv("pressure.csv"): if msg is None: # Log and skip, or raise if incomplete data is disallowed print("Skipping row due to parsing error") continue # Ignore malformed records try: pressure_twriter.push(message=msg) except Exception as e: # Log and skip, or raise if incomplete data is disallowed print(f"Error processing pressure at time: {msg.timestamp_ns}. Inner err: {e}") # All buffers are flushed and the sequence is committed when exiting the SequenceWriter 'with' block print("Multi-topic ingestion completed!") if __name__ == "__main__": main() ``` --- This guide demonstrates how to interact with the Mosaico Data Platform to retrieve the data stream that has been previously ingested. You will learn how to use the Mosaico SDK to: * **Obtain a `SequenceDataStreamer`** to consume recordings from a sequence. * **Obtain a `TopicDataStreamer`** to consume recordings from a topic. Prerequisites To fully grasp the following How-To, we recommend you to read (and reproduce) the **Reading a Sequence and its Topics Example**. In Depth Explanation * **Documentation: The Reading Workflow** * **API Reference: Data Retrieval** ### Unified Multi-Sensor Replay¶ A `SequenceDataStreamer` is designed for sensor fusion and full-system replay. It allows you to consume synchronized multiple data streams—such as high-rate IMU data and low-rate GPS fixes—as if they were a single, coherent timeline. ``` from mosaicolabs import MosaicoClient with MosaicoClient.connect("localhost", 6726) as client: seq_handler = client.sequence_handler("mission_alpha") if seq_handler: # Initialize a Unified Stream for synchronized multi-sensor analysis streamer = seq_handler.get_data_streamer( # Filter specific topics topics=["/gps", "/imu"], # Define the optional temporal window: Only data in this range will be streamed start_timestamp_ns=1738508778000000000, end_timestamp_ns=1738509618000000000, ) print(f"Streaming starts at: {streamer.next_timestamp()}") # Consume the stream. The loop yields messages from both topics in perfect chronological order for topic, msg in streamer: print(f"[{topic}] at {msg.timestamp_ns}: {type(msg.data).__name__}") # Finalize the reading channel to release server resources seq_handler.close() ``` ### Targeted Access¶ A `TopicDataStreamer` provides a dedicated channel for interacting with a single data resource. ``` from mosaicolabs import MosaicoClient, IMU with MosaicoClient.connect("localhost", 6726) as client: # Access a specific topic handler directly via the client top_handler = client.topic_handler("mission_alpha", "/front/imu") if top_handler: # Start a Targeted Stream for isolated, low-overhead replay imu_stream = top_handler.get_data_streamer( # Define the optional temporal window: Only data in this range will be streamed start_timestamp_ns=1738508778000000000, end_timestamp_ns=1738509618000000000, ) # Query the next timestamp, without consuming the message print(f"First sample at: {imu_stream.next_timestamp()}") # Direct loop for maximum efficiency for imu_msg in imu_stream: # Access the strongly-typed IMU data directly process_sample(imu_msg.get_data(IMU)) # Finalize the topic channel top_handler.close() ``` ### Streamer Comparison¶ | Feature | `SequenceDataStreamer` | `TopicDataStreamer` | | --- | --- | --- | | **Primary Use Case** | Multi-sensor fusion & system-wide replay | Isolated sensor analysis & ML training | | **Logic Overhead** | K-Way Merge Sorting | Direct Stream | | **Output Type** | Tuple of `(topic_name, message)` | Single `message` object | | **Temporal Slicing** | Supported | Supported | --- This guide demonstrates how to programmatically explore the Mosaico Data Platform to discover ingested sequences and inspect their internal structures. By following this guide, you will learn how to: 1. **List all sequences** available on a remote server. 2. **Access high-level metadata** (size, creation time, duration) for a specific recording session. 3. **Drill down into individual topics** to identify sensor types and sampling spans. Prerequisites This tutorial assumes you have already ingested data into your Mosaico instance, using the example described in the ROS Injection guide. Experiment Yourself This guide is **fully executable**. 1. **Start the Mosaico Infrastructure** 2. **Run the example** ``` mosaicolabs.examples data_inspection ``` Full Code The full code of the example is available **here**. In Depth Explanation * **Documentation: The Reading Workflow** * **API Reference: Data Retrieval** ## Step 1: Connecting to the Catalog¶ The first step is establishing a control connection. We use the `MosaicoClient` within a context manager to ensure that network resources and internal connection pools are gracefully released when the script finishes. ``` from mosaicolabs import MosaicoClient # Connect to the gateway of the Mosaico Data Platform with MosaicoClient.connect(host=MOSAICO_HOST, port=MOSAICO_PORT) as client: # Retrieve a simple list of all unique sequence identifiers seq_list = client.list_sequences() print(f"Discovered {len(seq_list)} sequences on the server.") ``` ## Step 2: Inspecting Sequence Metadata¶ A **Sequence** represents a holistic recording session. To inspect its metadata without downloading bulk data, we request a `SequenceHandler`. This object acts as a "lazy" proxy to the server-side resource. ``` # Assuming we are iterating through the seq_list from Step 1 for sequence_name in seq_list: shandler = client.sequence_handler(sequence_name) if shandler: # Access physical and logical diagnostics size_mb = shandler.total_size_bytes / (1024 * 1024) print(f"Sequence: {shandler.name}") print(f"• Remote Size: {size_mb:.2f} MB") print(f"• Created At: {shandler.created_datetime}") # Determine the global temporal bounds of the entire session start, end = shandler.timestamp_ns_min, shandler.timestamp_ns_max print(f"• Time Span: {start} to {end} ns") ``` ## Step 3: Inspecting Individual Topics¶ Inside a sequence, data is partitioned into **Topics**, each corresponding to a specific sensor stream or data channel. We can use the `SequenceHandler` to spawn a `TopicHandler` for granular inspection. ``` # Iterate through all data channels in this sequence for topic_name in shandler.topics: # Obtain a handler for the specific sensor stream thandler = shandler.get_topic_handler(topic_name) # Identify the semantic type of the data (e.g., 'imu', 'image') ontology = thandler.ontology_tag # Calculate duration for this specific sensor duration_sec = 0 if thandler.timestamp_ns_min and thandler.timestamp_ns_max: duration_sec = (thandler.timestamp_ns_max - thandler.timestamp_ns_min) / 1e9 print(f" - [{ontology}] {topic_name}: {duration_sec:.2f}s of data") ``` ## Comparisons¶ ### Sequence vs. Topic Handlers¶ | Feature | Sequence Handler | Topic Handler | | --- | --- | --- | | **Scope** | Entire Recording Session | Single Sensor | | **Metadata** | Mission-wide (e.g., driver, weather) | Sensor-specific (e.g., model, serial) | | **Time Bounds** | Global min/max of all topics | Min/max for that specific stream | | **Topics** | List of all available streams | N/A | ### Catalog Layer vs. Data Layer (Handlers vs Streamers)¶ | Feature | Handlers (Catalog Layer) | Streamers (Data Layer) | | --- | --- | --- | | **Primary Use** | Metadata inspection & discovery | High-volume data retrieval | | **Object Type** | `SequenceHandler` / `TopicHandler` | `SequenceDataStreamer` / `TopicDataStreamer` | | **Data Scope** | Size, Timestamps, Ontology Tags | Raw sensor messages | --- The Mosaico SDK is designed with a **code-first philosophy**. To help you move from architectural concepts to production implementation, we provide a suite of pedagogical examples. These examples aren't just snippets; they are **fully executable blueprints** that demonstrate high-performance data handling, zero-copy serialization with Apache Arrow, and deep discovery via our type-safe query engine. We provide a specialized CLI utility to run these examples without manual configuration. This runner automatically injects connection parameters into the example logic, allowing you to point the samples at your specific Mosaico instance. ### Basic Usage¶ From your terminal, use the `mosaicolabs.examples` command followed by the name of the example: ``` # Run the ROS Ingestion example mosaicolabs.examples ros_injection ``` ### Configuration Options¶ The CLI supports several global flags to control the execution environment: | Option | Default | Description | | --- | --- | --- | | `--host` | `localhost` | The hostname of your Mosaico Server. | | `--port` | `6726` | The Flight port of your Mosaico Server. | | `--log-level` | `INFO` | Set verbosity (`DEBUG`, `INFO`, `WARNING`, `ERROR`). | **Example with custom server:** ``` mosaicolabs.examples data_inspection --host 192.168.1.50 --port 6276 --log-level DEBUG ``` ### Available Blueprints¶ We recommend exploring the examples in the following order to understand the platform's flow: #### ROS Ingestion¶ * **CLI Name**: `ros_injection` * **Purpose**: The "Hello World" of Mosaico. This example automates the download of the NVIDIA R2B Dataset 2024 and performs a high-performance injection from `.mcap` files. * **Key Concept**: Demonstrates **Adaptation Logic**—translating raw ROS dictionaries into strongly-typed Mosaico Ontology models. #### Data Discovery and Inspection¶ * **CLI Name**: `data_inspection` * **Purpose**: Learn how to browse the server-side catalog. * **Key Concept**: Explains the **Lazy Handler** pattern. You will see how to retrieve sequence metadata (size, timestamps) and topic details without downloading bulk sensor data. #### Deep Querying¶ * **CLI Name**: `query_catalogs` * **Purpose**: Move beyond simple time-based retrieval. * **Key Concept**: Showcases the **`.Q` Query Proxy**. You will learn to search for specific physical events (e.g., "Find IMU lateral acceleration >= 1.0 m/s^2") across your entire dataset. ### Infrastructure Prerequisite¶ Before running any example, ensure your Mosaico infrastructure is active. The easiest way to start is using the provided **Quick Start environment**. Please, refer to the **daemon Setup** for setting up the environment. ### Ready to start?¶ We recommend beginning with the **ROS Ingestion Guide** to populate your local server with high-fidelity robotics data. The other examples will run on the data ingested via the ROS Ingestion example. --- This guide demostrates how to extend the Mosaico Data Platform with custom data models. While Mosaico provides a rich default ontology for robotics (IMU, GPS, Images, etc.), specialized hardware often requires proprietary data structures. By following this guide, you will be able to: * **Define** strongly-typed data models using Python and Apache Arrow. * **Register** these models so they are recognized by the Mosaico Ecosystem. * **Integrate** them into the ingestion and retrieval pipelines. Full Code The full code of the example is available **here**. In Depth Explanation * **Documentation: Data Models & Ontology** * **API Reference: Base Models and Mixins** ### Step 1: Define the Custom Data Model¶ In Mosaico, data models are defined by inheriting from the **`Serializable`** base class. This ensures that your model can be automatically translated into the platform's high-performance storage format. For this example, we will create a model for **`EncoderTicks`**, found in the NVIDIA R2B Dataset 2024. ``` import pyarrow as pa from mosaicolabs import Serializable class EncoderTicks( Serializable, # Automatically registers the model via `Serializable.__init_subclass__` ): """ Custom model for hardware-level encoder tick readings. """ # --- Wire Schema Definition (Apache Arrow) --- # This defines the high-performance binary storage format on the server. __msco_pyarrow_struct__ = pa.struct([ pa.field("left_ticks", pa.uint32(), nullable=False), pa.field("right_ticks", pa.uint32(), nullable=False), pa.field("encoder_timestamp", pa.uint64(), nullable=False), ]) # --- Data Fields --- # Names and types must strictly match the Apache Arrow schema above. left_ticks: int right_ticks: int encoder_timestamp: int ``` ### Step 2: Ensure "Discovery" via Module Import¶ It is a common pitfall to define a class and expect the platform to "see" it immediately. Mosaico utilizes the `Serializable.__init_subclass__` hook to perform **automatic registration** the moment the class is loaded into memory by the Python interpreter. For your custom type to be available in your application (especially during ingestion or when using the `ROSBridge`), you **must** ensure the module containing the class is imported. #### Best Practice: The Registry Pattern¶ Create a dedicated `models.py` or `ontology/` package for your project and import it at your application's entry point. ``` # app/main.py import my_project.ontology.encoders as encoders # <-- This triggers the registration from mosaicolabs import MosaicoClient def run_ingestion(): with MosaicoClient.connect(...) as client: # Now 'EncoderTicks' is a valid ontology_type for topic creation with client.sequence_create(name="test") as sw: tw = sw.topic_create("ticks", ontology_type=encoders.EncoderTicks) # ... ``` ### Step 3: Verifying Registration¶ If you are unsure whether your model has been correctly "seen" by the ecosystem, you can check the internal registry of the `Serializable` class. ``` from mosaicolabs import Serializable import my_project.ontology.encoders as encoders # <-- This triggers the registration if encoders.EncoderTicks.is_registered(): print("Registration successful!") ``` --- By following this guide, you will learn how to: 1. **Perform Fuzzy Searches**: Find topics based on partial name matches. 2. **Filter by Sensor Type**: Isolate all topics belonging to a specific ontology (e.g., all IMUs). 3. **Execute Multi-Domain Queries**: Correlate sensor names with physical events (e.g., "Find the front camera IMU data where acceleration on the y-axis exceeded 1.0 m/s^2"). Prerequisites This tutorial assumes you have already ingested data into your Mosaico instance, using the example described in the ROS Injection guide. Experiment Yourself This guide is **fully executable**. 1. **Start the Mosaico Infrastructure** 2. **Run the example** ``` mosaicolabs.examples query_catalogs ``` Full Code The full code of the example is available **here**. In Depth Explanation * **Documentation: Querying Catalogs** * **API Reference: Query Builders** * **API Reference: Query Response** ## The Query Philosophy: Chaining & Builders¶ Mosaico uses specialized **Query Builders** that provide a "fluent" interface. When you pass multiple builders to the `client.query()` method, the platform joins them with a logical **AND** condition—returning only results that satisfy every criteria simultaneously. ## Step 1: Finding Topics by Name Match¶ The `QueryTopic` builder allows you to search for data channels without knowing their exact full path. ``` from mosaicolabs import MosaicoClient, QueryTopic with MosaicoClient.connect(host="localhost", port=6726) as client: # Use a convenience method for fuzzy name matching (equivalent to SQL %match%) results = client.query( QueryTopic().with_name_match("image_raw") # (1)! ) if results: for item in results: print(f"Sequence: {item.sequence.name}") for topic in item.topics: print(f" - Matched: {topic.name}") ``` 1. The `with_name_match()` method allows you to filter for topics that match a pattern. In this case, we are filtering for topics that contain *"image\_raw"* in their name. This is equivalent to using the SQL `LIKE` operator with a wildcard. ### Understanding the Response Structure¶ The `query()` method returns a `QueryResponse` object, which is hierarchically grouped to make data management easy: | Object | Purpose | | --- | --- | | **`item.sequence`** | Contains the name of the sequence where the match was found. | | **`item.topics`** | A list of only the topics within that sequence that satisfied the criteria. | | **`topic.timestamp_range`** | Provides the `start` and `end` nanoseconds for the matching event. | Result Normalization The `topic.name` returns the relative topic path (e.g., `/front/camera/image`), which is immediately compatible with other SDK methods like `MosaicoClient.topic_handler()`. ## Step 2: Filtering by Ontology (Sensor Type)¶ Instead of hardcoding strings, Mosaico allows you to query by the **semantic type** of the data. This ensures that if you rename a topic, your analysis scripts won't break as long as the sensor type remains the same. ``` from mosaicolabs import IMU, QueryTopic # Retrieve the unique ontology tag dynamically from the class results = client.query( QueryTopic().with_ontology_tag(IMU.ontology_tag()) # (1)! ) # This returns every IMU topic across all sequences in the database. ``` 1. The `ontology_tag()` method returns the unique identifier for the ontology class. ## Step 3: Multi-Domain Queries (Physics + Metadata)¶ This is the most powerful feature of the platform. We use the **`.Q` Query Proxy**, a type-safe bridge that allows you to construct filters using standard Python dot notation. In this example, we identify specific time segments where a specific IMU sensor recorded a lateral acceleration (y-axis) greater than or equal to 1.0 m/s^2. ``` from mosaicolabs import IMU, QueryOntologyCatalog, QueryTopic results = client.query( # Layer 1: Physics (Ontology Catalog) QueryOntologyCatalog( IMU.Q.acceleration.y.geq(1.0), include_timestamp_range=True # (1)! ), # Layer 2: Configuration (Topic Name) QueryTopic().with_name("/front_stereo_imu/imu") # (2)! ) ``` 1. The `include_timestamp_range=True` flag tells the server to return the first and last timestamps of the queried condition within a topic, allowing you to slice data accurately for further analysis. 2. The `with_name()` method allows you to filter by topic name. In this case, we are (exactly) filtering for the `/front_stereo_imu/imu` topic. You can also use the `with_name_match()` method to filter for topics that match a pattern. **Architect's Note:** Notice how we pass two different builders. The server will only return the `/front_stereo_imu/imu` topic, and only if it contains values >= 1.0. ## Practical Application: Replaying the "Impact"¶ Once you have the results, you can immediately slice the data for playback: ``` if results: for item in results: for topic in item.topics: # Slice the sequence to only the relevant 2 seconds of the event streamer = client.sequence_handler(item.sequence.name).get_data_streamer( topics=[topic.name], start_timestamp_ns=topic.timestamp_range.start - 1_000_000_000, end_timestamp_ns=topic.timestamp_range.end + 1_000_000_000 ) # Replay the high-acceleration event... ``` --- This tutorial demonstrates a complete Mosaico data ingestion using the NVIDIA R2B Dataset 2024. You will learn how to automate the transition from monolithic ROS bags (.mcap) to a structured, queryable archive. By following this guide, you will: * **Automate Asset Preparation**: Programmatically download and manage remote datasets. * **Implement Adaptation Logic**: Translate raw ROS types into the strongly-typed Mosaico Ontology. * **Execute Ingestion**: Use the `RosbagInjector` to handle batching and network transmission. * **Verify Integrity**: Programmatically inspect the server to ensure the data is cataloged. Experiment Yourself This guide is **fully executable**. 1. **Start the Mosaico Infrastructure** 2. **Run the example** ``` mosaicolabs.examples ros_injection ``` Full Code The full code of the example is available **here**. In Depth Explanation * **How-To: Customizing the Data Ontology** * **Documentation: The ROS Bridge** * **API Reference: The ROS Bridge** ## Step 1: Custom Ontology Definition (`isaac.py`)¶ In Mosaico, data is strongly typed. When dealing with specialized hardware like the NVIDIA Isaac Nova encoders, with custom data models, not available in the SDK, we must define a model that the platform understands. ### The Data Model¶ The `EncoderTicks` class defines the physical storage format. ``` import pyarrow as pa from mosaicolabs import Serializable class EncoderTicks(Serializable): # (1)! # --- Wire Schema Definition --- __msco_pyarrow_struct__ = pa.struct([ pa.field("left_ticks", pa.uint32(), nullable=False), pa.field("right_ticks", pa.uint32(), nullable=False), pa.field("encoder_timestamp", pa.uint64(), nullable=False), ]) # --- Pydantic Fields --- left_ticks: int # (2)! right_ticks: int encoder_timestamp: int ``` 1. Inheriting from `Serializable` automatically registers your model in the Mosaico ecosystem, making it dispatchable to the data platform, and enables the `.Q` query proxy. 2. The field names in the `pa.struct` **must match exactly** the names of the Python attributes. In Depth Explanation * **How-To: Customizing the Data Ontology** * **Documentation: Data Models & Ontology** ## Step 2: Implementing the ROS Adapter (`isaac_adapters.py`)¶ The translation between the raw ROS dictionary and the Mosaico ontology data model is made via *adapters*. Being a custom message type, `"isaac_ros_nova_interfaces/msg/EncoderTicks"` does not have a default adapter. Therefore we must define one: the `ROSAdapterBase` class provides the necessary infrastructure for this. We just need to implement the `from_dict` method, which is responsible for converting the raw ROS message dictionary into our custom ontology model. ### The Adapter Implementation¶ ``` from mosaicolabs.ros_bridge import ROSMessage, ROSAdapterBase, register_default_adapter from mosaicolabs.ros_bridge.adapters.helpers import _validate_msgdata from .isaac import EncoderTicks @register_default_adapter class EncoderTicksAdapter(ROSAdapterBase[EncoderTicks]): ros_msgtype = ("isaac_ros_nova_interfaces/msg/EncoderTicks",) # (1)! __mosaico_ontology_type__ = EncoderTicks # (2)! _REQUIRED_KEYS = ("left_ticks", "right_ticks", "encoder_timestamp") # (3)! @classmethod def from_dict(cls, ros_data: dict) -> EncoderTicks: # (4)! """ Convert a ROS message dictionary to an EncoderTicks object. """ _validate_msgdata(cls, ros_data) return EncoderTicks( left_ticks=ros_data["left_ticks"], right_ticks=ros_data["right_ticks"], encoder_timestamp=ros_data["encoder_timestamp"], ) @classmethod def translate(cls, ros_msg: ROSMessage, **kwargs: Any) -> Message: # (5)! """ Translates a ROS EncoderTicks message into a Mosaico Message container. """ return super().translate(ros_msg, **kwargs) ``` 1. A tuple of strings representing the ROS message types that this adapter can handle. 2. The Mosaico ontology type that this adapter can handle. 3. A tuple of strings representing the required keys in the ROS message. This is used by the `_validate_msgdata` method to check that the ROS message does contains the required fields. 4. This is the heart of the translator. It takes a Python dictionary and maps the keys to our `EncoderTicks` ontology model. 5. This method is called by the `RosbagInjector` class for each message in the bag. It is responsible for converting the raw ROS message dictionary into the Mosaico message, wrapping the custom ontology model. **Key Operation**: The `@register_default_adapter` decorator ensures the `RosbagInjector` automatically knows how to handle this message type during the ingestion loop. ## Step 3: Orchestrating the Ingestion Loop¶ In a real-world scenario, you often need to ingest a batch of files. The `main.py` implementation uses a 3-phase loop to manage this workflow. ### Phase 1: Asset Preparation¶ Before we can ingest data, we need the raw file. This phase downloads a verified dataset from NVIDIA. ``` for bag_path in BAG_FILES_PATH: bag_file_url = BASE_BAGFILE_URL + bag_path # This utility handles downloads with visual progress bars out_bag_file = download_asset(bag_file_url, ASSET_DIR) ``` ### Phase 2: High-Performance Ingestion¶ Configure and run the injector. This layer handles connection pooling, asynchronous serialization, and batching. ``` config = ROSInjectionConfig( host=MOSAICO_HOST, port=MOSAICO_PORT, file_path=out_bag_file, sequence_name=out_bag_file.stem, # Sequence name derived from filename # Some example metadata for the sequence metadata={ "source_url": BAGFILE_URL, "ingested_via": "mosaico_example_ros_injection", "download_time_utc": str(downloaded_time), }, log_level="INFO", ) # Handles connection, loading, adaptation, and batching injector = RosbagInjector(config) injector.run() # Starts the ingestion process ``` ### Phase 3: Verification & Retrieval¶ Programmatically confirm the sequence is available on the server using a context manager. ``` with MosaicoClient.connect(host=MOSAICO_HOST, port=MOSAICO_PORT) as client: # (1)! seq_list = client.list_sequences() # (2)! if config.sequence_name in seq_list: print(f"Success: '{config.sequence_name}' is now queryable.") ``` 1. Establishes a secure connection to the platform. 2. Asks for the lists of sequences on the server In Depth Explanation * **How-To: Data Discovery and Inspection** * **Documentation: The Reading Workflow** * **API Reference: Data Retrieval** --- API Reference: `mosaicolabs.comm.MosaicoClient`. The `MosaicoClient` is a resource manager designed to orchestrate three 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()` factory method. It is recomended to always use the client inside a `with` context to ensure resources in all layers are cleanly released. ``` from mosaicolabs import MosaicoClient with MosaicoClient.connect("localhost", 6726) as client: # Logic goes here pass # Pools and connections are closed automatically ``` ## Control Layer¶ A single, dedicated connection is maintained for metadata operations. This layer handles lightweight tasks such as creating sequences, querying the catalog, and managing schema definitions. By isolating control traffic, the client ensures that critical commands (like `sequence_finalize`) are never queued behind heavy data transfers. ## Data Layer¶ For high-bandwidth data ingestion (e.g., uploading 4x 1080p cameras simultaneously), the client maintains a **Connection Pool** of multiple Flight clients. The SDK automatically stripes writes across these connections in a round-robin fashion, allowing the application to saturate the available network bandwidth. ## Processing Layer¶ Serialization of complex sensor data (like compressing images or encoding LIDAR point clouds) is CPU-intensive. The SDK uses an **Executor Pool** of background threads to offload these tasks. This ensures that while one thread is serializing the *next* batch of data, another thread is already transmitting the *previous* batch over the network. As a senior architect, it is vital to emphasize that the **Security Layer** is not an "add-on" but a foundational component of the `MosaicoClient` lifecycle. In robotics, where data often moves from edge devices to centralized clusters, this layer ensures that your Physical AI assets remain protected against unauthorized access and intercept. ## 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)**. By providing a `tls_cert_path`, the client automatically switches from an insecure channel to an encrypted one. The SDK handles the heavy lifting of reading the certificate bytes and configuring the underlying Flight/gRPC drivers to verify the server's identity and encrypt the data stream. ### 2. Authentication (API Key)¶ Mosaico uses an **API Key** system 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` | Read-Only access to resources | | `APIKeyPermissionEnum.Write` | Write access to resources (Create and update sequences) | | `APIKeyPermissionEnum.Delete` | Delete access to resources (Delete sequences, sessions and topics) | | `APIKeyPermissionEnum.Manage` | Full access to resources + Manage API keys (create, retrieve the status, revoke) | ``` 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()) ``` 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. ``` 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`. 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. ``` 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()) ``` --- 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¶ API Reference: Base Data Types 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`, `LargeString` | UTF-8 text data for logs or status messages. | | **Booleans** | `Boolean` | Logic flags (True/False). | | **Signed Integers** | `Integer8`, `Integer16`, `Integer32`, `Integer64` | Signed whole numbers of varying bit-depth. | | **Unsigned Integers** | `Unsigned8`, `Unsigned16`, `Unsigned32`, `Unsigned64` | Non-negative integers for counters or IDs. | | **Floating Point** | `Floating16`, `Floating32`, `Floating64` | Real numbers for high-precision physical values. | ### Geometry & Kinematics Models¶ API Reference: Geometry Models 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`, `Point2d/3d` | Fundamental spatial directions and locations. | | **Rotations** | `Quaternion` | Compact, singularity-free 3D orientation (). | | **Spatial State** | `Pose`, `Transform` | Absolute positions or relative coordinate frame shifts. | | **Motion** | `Velocity`, `Acceleration` | Linear and angular movement rates (Twists and Accels). | | **Aggregated State** | `MotionState` | An atomic snapshot combining Pose, Velocity, and Acceleration. | ### Sensor Models¶ API Reference: Sensor Models High-level models representing physical hardware devices and their processed outputs. | Module | Classes | Purpose | | --- | --- | --- | | **Inertial** | `IMU` | 6-DOF inertial data: linear acceleration and angular velocity. | | **Navigation** | `GPS`, `GPSStatus`, `NMEASentence` | Geodetic fixes (WGS 84), signal quality, and raw NMEA strings. | | **Vision** | `Image`, `CompressedImage`, `CameraInfo`, `ROI` | Raw pixels, encoded streams (JPEG/H264), calibration, and regions of interest. | | **Environment** | `Temperature`, `Pressure`, `Range` | Thermal readings (K), pressure (Pa), and distance intervals (m). | | **Dynamics** | `ForceTorque` | 3D force and torque vectors for load sensing. | | **Magnetic** | `Magnetometer` | Magnetic field vectors measured in microTesla (). | | **Robotics** | `RobotJoint` | States (position, velocity, effort) for index-aligned actuator arrays. | ## Architecture¶ The ontology architecture relies on three primary abstractions: the **Factory** (`Serializable`), the **Envelope** (`Message`) and the **Mixins** ### `Serializable` (The Factory)¶ API Reference: `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 `__init_subclass__` hook, which is automatically called whenever a developer defines a new subclass. ``` class MyCustomSensor(Serializable): # <--- __init_subclass__ triggers here ... ``` When this happens, `Serializable` performs the following steps automatically: 1. **Validates Schema:** Checks if the subclass defined the PyArrow struct schema (`__msco_pyarrow_struct__`). If missing, it raises an error at definition time (import time), preventing runtime failures later. 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)¶ API Reference: `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. ``` 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`. This is ideal for pushing processed signals, debug values, or simple sensor readings. ``` # 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. ``` # 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`¶ API Reference: `mosaicolabs.models.mixins.CovarianceMixin` Injects multidimensional uncertainty fields, typically used for flattened covariance matrices (e.g., 3x3 or 6x6) in sensor fusion applications. ``` class MySensor(Serializable, CovarianceMixin): # Automatically receives covariance and covariance_type fields ... ``` #### `VarianceMixin`¶ API Reference: `mosaicolabs.models.mixins.VarianceMixin` Injects monodimensional uncertainty fields, useful for sensors with 1-dimensional uncertain data like `Temperature` or `Pressure`. ``` 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. ## 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`, 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` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `GPS.status.hdop` | `GPS.Q.status.hdop` | `float` | **Numeric** | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `IMU.frame_id` | `IMU.Q.frame_id` | `str` | **String** | `.eq()`, `.neq()`, `.match()`, `.in_()` | | `GPS.covariance_type` | `GPS.Q.covariance_type` | `int` | **Numeric** | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | ### Practical Usage¶ To execute these filters, pass the expressions generated by the proxy to the `QueryOntologyCatalog` builder. ``` 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** and the Ontology types SDK Reference in the **API Reference**: * Base Data Models * Sensors Models * Geometry Models * Platform Models ## 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 (`__msco_pyarrow_struct__`)¶ You must define a class-level `__msco_pyarrow_struct__` using `pyarrow.struct`. This explicitly dictates how your Python object is serialized into high-performance Apache Arrow/Parquet buffers for network transmission and storage. #### 2.1 Serialization Format Optimization¶ API Reference: `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. ### 3. Define Class Fields¶ Define the Python attributes for your class using standard type hints. Note that the names of your Python class fields **must match exactly** the field names defined in your `__msco_pyarrow_struct__` schema. ### Customization Example: `EnvironmentSensor`¶ This example demonstrates a custom sensor for environmental monitoring that tracks temperature, humidity, and pressure. ``` # file: custom_ontology.py from typing import Optional import pyarrow as pa from mosaicolabs.models import Serializable class EnvironmentSensor(Serializable): """ Custom sensor reading for Temperature, Humidity, and Pressure. """ # --- 1. Define the Wire Schema (PyArrow Layout) --- __msco_pyarrow_struct__ = pa.struct( [ pa.field("temperature", pa.float32(), nullable=False), pa.field("humidity", pa.float32(), nullable=True), pa.field("pressure", pa.float32(), nullable=True), ] ) # --- 2. Define Python Fields (Must match schema exactly) --- temperature: float humidity: Optional[float] = None pressure: Optional[float] = None # --- 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 **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, asynchronous 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. It utilizes a "Multi-Lane" approach where each sensor stream operates in isolation with dedicated system resources. * **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. * **Asynchronous Processing**: The SDK offloads CPU-intensive tasks, such as image serialization and network I/O, to background threads within the `MosaicoClient`. * **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** 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. API-Keys When the connection is established via the authorization middleware (i.e. using an API-Key), the reading workflow requires the minimum `APIKeyPermissionEnum.Read` permission. Try-It Out You can experiment yourself the Handlers module via the **Data Discovery and Inspection 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`¶ API Reference: `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()` factory method. This example demonstrates how to use a Sequence handler to inspect metadata. ``` 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`¶ API Reference: `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()` factory method, or via `SequenceHandler.get_topic_handler()` factory method. This example demonstrates how to use a Topic handler to inspect metadata. ``` 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)¶ API Reference: `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()` 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. ``` 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)¶ API Reference: `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()` 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. ``` 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** 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. The architecture is built around a **"Multi-Lane"** approach, where each sensor stream operates in its own isolated lane with dedicated system resources. API-Keys When the connection is established via the authorization middleware (i.e. using an API-Key), the writing workflow is allowed only if the key has at least `APIKeyPermissionEnum.Write` permission. ## `SequenceWriter`¶ API Reference: `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()` 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`. * **Resource Distribution**: The writer pulls network connections from the **Connection Pool** and background threads from the **Executor Pool**, assigning them to individual topics. This isolation prevents a slow network connection on one topic from bottlenecking others. * **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. ``` 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. The mechanism allows creating queries like: `QuerySequence().with_user_metadata("vehicle.software_stack.planning", eq="plan-4.1.7")` ### Sequence-Level Error Handling¶ API Reference: `mosaicolabs.enum.SessionLevelErrorPolicy`. Deprecated OnErrorPolicy In release 0.3.0, the `OnErrorPolicy` is declared **`deprecated`** in favor of the `SessionLevelErrorPolicy`. The support for the class will be removed in the release 0.4.0. No changes are made to the enum values of the new class `SessionLevelErrorPolicy`, which are identical to the ones of the deprecated class. Configured when instantiating a new `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`, 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` policy will signal the server to physically remove the incomplete sequence and its associated topic directories, if any errors occurred. Error Handling and API-Key When the connection is established via the authorization middleware (i.e. using an API-Key), the `SessionLevelErrorPolicy.Delete` policy is successfully executed by the server only if the API-Key has `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`¶ API Reference: `mosaicolabs.handlers.TopicWriter`. Once a topic is created via `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. * **Asynchronous Serialization**: For CPU-intensive data (like encoding images), the writer can offload the serialization process to background threads, ensuring your main application loop stays fast. ``` # Continues from the code above... # with client.sequence_create(...) as seq_writer: # Create individual Topic Writers # Each writer gets its own assigned resources from the pools 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, finalizes the sequence on the server # and closes all connections and pools ``` 1. The metadata fields will be queryable via the `Query` mechanism. The mechanism allows creating query expressions like: `QueryTopic().with_user_metadata("interface.type", eq="UART")`. API Reference: * `mosaicolabs.models.platform.Topic` * `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). !!! 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` 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`¶ API Reference: `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()` 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`. * **Resource Distribution**: The writer pulls network connections from the **Connection Pool** and background threads from the **Executor Pool**, assigning them to individual topics. This isolation prevents a slow network connection on one topic from bottlenecking others. * **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. ``` 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 ``` Session-level Error Handling Configured when instantiating a new `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 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. Error Handling and API-Key When the connection is established via the authorization middleware (i.e. using an API-Key), the `SessionLevelErrorPolicy.Delete` policy is successfully executed by the server only if the API-Key has `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. ``` # Continues from the code above... # seq_handler.update(...) as seq_updater: # Create individual Topic Writers # Each writer gets its own assigned resources from the pools 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, finalizes the sequence on the server # and closes all connections and pools ``` --- 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. API-Keys When the connection is established via the authorization middleware (i.e. using an API-Key), the query workflow requires the minimum `APIKeyPermissionEnum.Read` permission. Try-It Out You can experiment yourself the Query module via the **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**. ``` 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`, `QueryTopic`, and `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` 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` 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()` method exposed by the `MosaicoClient` class. When multiple builders are provided, they are combined with a logical **AND**. | Method | Return | Description | | --- | --- | --- | | `query(*queries, query)` | `Optional[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` object. | The query execution returns a `QueryResponse` object, which behaves like a standard Python list containing `QueryResponseItem` objects. | Class | Description | | --- | --- | | `QueryResponseItem` | Groups all matches belonging to the same **Sequence**. Contains a `QueryResponseItemSequence` and a list of related `QueryResponseItemTopic`. | | `QueryResponseItemSequence` | Represents a specific **Sequence** where matches were found. It includes the sequence name. | | `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). | ``` 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()`. ### 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()` | `QuerySequence` | Returns a query builder pre-filtered to include only the **sequences** present in the response. | | `to_query_topic()` | `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. ``` 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. ``` 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. ``` # 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` (Sequence Layer)¶ API Reference: `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 ``` 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` (Topic Layer)¶ API Reference: `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 ``` 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` (Ontology Catalog Layer)¶ API Reference: `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 ``` 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. ``` 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. ``` 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: ``` 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. The proxy automatically flattens the hierarchy, assigning the correct queryable type and operators to each leaf node: (API Reference: `mosaicolabs.models.sensors.IMU`) | Proxy Field Path | Queryable Type | Supported Operators (Examples) | | --- | --- | --- | | **`IMU.Q.acceleration.x/y/z`** | **Numeric** | `.gt()`, `.lt()`, `.geq()`, `.leq()`, `.eq()`, `.between()`, `.in_()` | | **`IMU.Q.angular_velocity.x/y/z`** | **Numeric** | `.gt()`, `.lt()`, `.geq()`, `.leq()`, `.eq()`, `.between()`, `.in_()` | | **`IMU.Q.orientation.x/y/z/w`** | **Numeric** | `.gt()`, `.lt()`, `.geq()`, `.leq()`, `.eq()`, `.between()`, `.in_()` | | **`IMU.Q.timestamp_ns`** | **Numeric** | `.gt()`, `.lt()`, `.geq()`, `.leq()`, `.eq()`, `.between()`, `.in_()` | | **`IMU.Q.recording_timestamp_ns`** | **Numeric** | `.gt()`, `.lt()`, `.geq()`, `.leq()`, `.eq()`, `.between()`, `.in_()` | | **`IMU.Q.frame_id`** | **String** | `.eq()`, `.neq()`, `.match()`, `in_()` | | **`IMU.Q.sequence_id`** | **Numeric** | `.gt()`, `.lt()`, `.geq()`, `.leq()`, `.eq()`, `.between()`, `.in_()` | The following table lists the supported operators for each data type: | Data Type | Operators | | --- | --- | | **Numeric** | `.eq()`, `.neq()`, `.lt()`, `.leq()`, `.gt()`, `.geq()`, `.between()`, `.in_()` | | **String** | `.eq()`, `.neq()`, `.match()` (i.e. substring), `.in_()` | | **Boolean** | `.eq(True/False)` | | **Dictionary** | `.eq()`, `.lt()`, `.leq()`, `.gt()`, `.geq()`, `.between()` | #### 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)`). ``` # 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. ``` # 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 ) ``` --- 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¶ API Reference: `mosaicolabs.ml.DataFrameExtractor` The `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. ``` 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. ``` 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() ``` ## Sparse to Dense Representation¶ API Reference: `mosaicolabs.ml.SyncTransformer` The `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`. 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 `SynchPolicy` protocol, allowing for custom kernel injection. ### Implemented Synchronization Policies¶ API Reference: `mosaicolabs.ml.SyncPolicy` Each policy defines a specific logic for how the transformer bridges temporal gaps between sparse data points. #### 1. **`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`** (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`** (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. ### Scikit-Learn Compatibility¶ By implementing the standard `fit`/`transform` interface, the `SyncTransformer` makes robotics data a "first-class citizen" of the Scikit-learn ecosystem. This allows for the plug-and-play integration of multi-rate sensor data into standard pipelines. ``` 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) ``` --- 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. API-Keys When the connection is established via the authorization middleware (i.e. using an API-Key), the ROS Ingestion employs the mosaico Writing Workflow, which is allowed only if the key has at least `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` is validated, normalized, and instantiated as a strongly-typed `mosaicolabs.models.data.Pose` object before ingestion. Try-It Out You can experiment yourself the ROS Bridge ingestion via the **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` acts as the abstraction layer over the physical bag files. It utilizes the `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`** 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`** (file access), the **`ROSBridge`** (data adaptation), and the **`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`. 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 asynchronous 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`**. 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¶ ``` 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`:** 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` (mapping `sensor_msgs/Imu` to `IMU`) and `ImageAdapter` (mapping `sensor_msgs/Image` to `Image`). These adapters include advanced logic for recursive unwrapping, automatically extracting data from complex nested wrappers like `PoseWithCovarianceStamped`. Developers can also implement custom adapters to handle non-standard or proprietary types. * **`ROSBridge`:** A central registry and dispatch mechanism that maps ROS message type strings (e.g., `sensor_msgs/msg/Imu`) 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` dictionary into an intance of the target ontology object. 3. **Register**: Decorate the class with `@register_default_adapter`. ``` 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`, where, for example, different LiDAR vendors may encode data in unique ways that require specialized parsing logic. Override adapter usage Use adapter overrides for versatile message types like `sensor_msgs/msg/PointCloud2`, 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` decorator to establish a global fallback. ##### Implementing a Custom Adapter Override¶ To create a custom adapter, you must inherit from `ROSAdapterBase` and define the transformation logic. Here is a structural example of a custom LiDAR adapter; note that the adapter is not registered as **default**, since the message type `sensor_msgs/msg/PointCloud2` already has it: ``` from typing import Any, Optional, Type, Tuple from mosaicolabs.ros_bridge import ROSAdapterBase, ROSMessage from mosaicolabs.models import Message from my_ontology import MyLidar # Your target Ontology class class MyCustomLidarAdapter(ROSAdapterBase[MyLidar]): # Define which ROS type this adapter handles ros_msgtype: str | Tuple[str, ...] = "sensor_msgs/msg/PointCloud2" # Define the target Mosaico Ontology class __mosaico_ontology_type__: Type[MyLidar] = 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 MyLidar( # ... map ros_data fields to MyLidar fields ) @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 ``` ##### Key Methods¶ **`from_dict(ros_data)`**: This is the most important method. It receives the ROS message as a Python dictionary and must return an instance of your target Mosaico Ontology class. **`translate(ros_msg)`**: This is the entry point called by the ROSBridge. It just calls `from_dict`, but you can override it if you need access to the message metadata during conversion. **`schema_metadata(ros_data)`**: Use this to extract metadata information about the sensor configuration that is useful for the platform to know. ##### Registering the Override¶ Once implemented, the adapter is registered against a specific topic via `adapter_override` in ROSInjectionConfig: ``` from .my_adapter import MyCustomLidarAdapter ... 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": MyCustomLidarAdapter, } ) ... ingestor = RosbagInjector(config) ingestor.run() ``` With this configuration, all the `sensor_msgs/msg/PointCloud2` message received on `/lidar/front/pointcloud`, will be processed exclusively by `MyCustomLidarAdapter`. 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. #### 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` ``` # 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`** 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` 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`, 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`): ``` 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` (and the underlying `ROSLoader`) automatically detects and uses these definitions. There is no longer the need to pass the `custom_msgs` list in the `ROSInjectionConfig`. ``` # 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**. 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`, semantic translation through the `ROSBridge`, and the asynchronous transmission to the Mosaico server. * **Hardware Impact**: On the **Apple M2 Pro**, the `RosbagInjector` utilizes multi-threading for the **Adaptation Layer**, allowing serialization tasks to run in parallel while the main thread manages the Flight stream. #### 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 * **Issue:** Deserialization failure during ingestion. * **Technical Details:** The ingestion process fails within the `AnyReader.deserialize` method of the `rosbags` library. The internal CDR deserializer triggers an assertion error indicating a mismatch in the expected data length vs. the raw payload size. * **Error Signature:** ``` # 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`). It encapsulates a list of `Transform` objects to manage spatial relationships. * **`BatteryState`**: Modeled after `sensor_msgs/msg/BatteryState`), 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`, 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`. 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`, `PoseStamped`... | `Pose` | `PoseAdapter` | | `geometry_msgs/msg/Twist`, `TwistStamped`... | `Velocity` | `TwistAdapter` | | `geometry_msgs/msg/Accel`, `AccelStamped`... | `Acceleration` | `AccelAdapter` | | `geometry_msgs/msg/Vector3`, `Vector3Stamped` | `Vector3d` | `Vector3Adapter` | | `geometry_msgs/msg/Point`, `PointStamped` | `Point3d` | `PointAdapter` | | `geometry_msgs/msg/Quaternion`, `QuaternionStamped` | `Quaternion` | `QuaternionAdapter` | | `geometry_msgs/msg/Transform`, `TransformStamped` | `Transform` | `TransformAdapter` | | `geometry_msgs/msg/Wrench`, `WrenchStamped` | `ForceTorque` | `WrenchAdapter` | | `nav_msgs/msg/Odometry` | `MotionState` | `OdometryAdapter` | | `nmea_msgs/msg/Sentence` | `NMEASentence` | `NMEASentenceAdapter` | | `sensor_msgs/msg/Image`, `CompressedImage` | `Image`, `CompressedImage` | `ImageAdapter`, `CompressedImageAdapter` | | `sensor_msgs/msg/Imu` | `IMU` | `IMUAdapter` | | `sensor_msgs/msg/NavSatFix` | `GPS`, `GPSStatus` | `GPSAdapter`, `NavSatStatusAdapter` | | `sensor_msgs/msg/CameraInfo` | `CameraInfo` | `CameraInfoAdapter` | | `sensor_msgs/msg/RegionOfInterest` | `ROI` | `ROIAdapter` | | `sensor_msgs/msg/JointState` | `RobotJoint` | `RobotJointAdapter` | | `sensor_msgs/msg/BatteryState` | `BatteryState` (ROS-specific) | `BatteryStateAdapter` | | `std_msgs/msg/String` | `String` | `_GenericStdAdapter` | | `std_msgs/msg/Int8(16,32,64)` | `Integer8(16,32,64)` | `_GenericStdAdapter` | | `std_msgs/msg/UInt8(16,32,64)` | `Unsigned8(16,32,64)` | `_GenericStdAdapter` | | `std_msgs/msg/Float32(64)` | `Floating32(64)` | `_GenericStdAdapter` | | `std_msgs/msg/Bool` | `Boolean` | `_GenericStdAdapter` | | `tf2_msgs/msg/TFMessage` | `FrameTransform` (ROS-specific) | `FrameTransformAdapter` | | `sensor_msgs/msg/PointCloud2` | `PointCloud2` (ROS-specific) | `PointCloudAdapter` | --- # 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: ``` cd mosaico/mosaico-sdk-py ``` Install dependencies **and** register the pre-commit hooks in a single step: ``` 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: * **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: ``` # 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: ``` ls .git/hooks/pre-commit ``` You should see the file present. If it is missing, re-run `poetry run pre-commit install`. --- # Custom Actions¶ Mosaico implements its own administrative protocols directly on top of Apache Arrow Flight. Rather than relying on a separate control channel abstraction, Mosaico leverages the Flight `DoAction` RPC mechanism to handle discrete lifecycle events, administrative interfaces, and resource management. Unlike streaming endpoints designed for continuous data throughput, these custom actions manage the platform's overarching state. While individual calls are synchronous, they often initiate or conclude multi-step processes, such as topic upload, that govern the long-term integrity of data within the platform. All custom actions follow a standardized pattern: they expect a JSON-serialized payload defining the request parameters and return a JSON-serialized response containing the result. ## Sequence Management¶ Sequences are the fundamental containers for data recordings in Mosaico. These custom actions enforce a strict lifecycle state machine to guarantee data integrity. | Action | Description | Permission | | --- | --- | --- | | `sequence_create` | Initializes a new, empty sequence. | `write` | | `sequence_delete` | Permanently removes a sequence from the platform. | `delete` | ## Topic Management¶ Topics represent the individual sensor streams (e.g., `camera/front`, `gps`) contained within a sequence. | Action | Description | Permission | | --- | --- | --- | | `topic_create` | Registers a new topic. | `write` | | `topic_delete` | Removes a specific topic from a sequence. | `delete` | ## Session Management¶ Uploading data to the platform is made through sessions. Within a session it is possible to load one or more topics. Once closed, it becomes immutable. | Action | Description | Permission | | --- | --- | --- | | `session_create` | Start a new upload session. | `write` | | `session_finalize` | Moves the session status from *uploading* to *archived*. This action locks the session, marking it as immutable. Once finalized, no further data can be added or modified. | `write` | | `session_delete` | Removes a specific session and all its data. | `delete` | ## Notification System¶ The platform includes a tagging mechanism to attach alerts or informational messages to resources. For example, if an exception is raised during an upload, the notification system automatically registers the event, ensuring the failure is logged and visible for troubleshooting. | Action | Description | Permission | | --- | --- | --- | | `*_notification_create` | Attaches a notification to a Sequence or Topic, such as logging an error or status update. | `write` | | `*_notification_list` | Retrieves the history of active notifications for a resource, allowing clients to review alerts. | `read` | | `*_notification_purge` | Clears the notification history for a resource, useful for cleanup after resolution. | `delete` | Here, `*` can be either `sequence` or `topic`. ## Query¶ | Action | Description | Permission | | --- | --- | --- | | `query` | This action serves as the gateway to the query system. It accepts a complex filter object and returns a list of resources that match the criteria. | `read` | ## Misc¶ | Action | Description | Permission | | --- | --- | --- | | `version` | Retrieves the current daemon version. | `read` | --- # API keys¶ In Mosaico, access control is managed through **API keys**. An API key securely binds a unique token to a specific set of permissions. Scope of access It is important to note that API keys in Mosaico act as a *loose, coarse-grained access mechanism*. They are designed strictly to limit the *types of operations* a user can perform across the platform as a whole. This mechanism *does not support fine-grained policies*. You cannot use an API key to restrict access to specific resources, such as individual topics or sequences. For example, if an API key is granted the `read` permission, the client is allowed to read data globally across the entire platform, rather than being restricted to a single topic or a specific subset of data. ## Properties¶ Each API key in Mosaico acts as a single access control rule and consists of the following properties: | Property | Status | Description | | --- | --- | --- | | **Token** | Required | The unique token provided by the client to authenticate with the Mosaico platform. | | **Permissions** | Required | Which privileges (e.g., `read`, `write`) are granted through the API key. | | **Description** | Required | A human-readable text string explaining the specific purpose or use case of the policy. | | **Creation Time** | Auto-generated | The exact timestamp when the API key and its associated policy were generated. | | **Expiration Time** | Optional | A predetermined date and time after which the API key automatically becomes invalid. | ## Token Structure¶ Mosaico API key token follow a strict three-part format separated by underscores (`_`): ``` [HEADER]_[PAYLOAD]_[FINGERPRINT] ``` **Example** ``` msco_vrfeceju4lqivysxgaseefa3tsxs0vrl_1b676530 ``` **Header**. A fixed prefix that easily identifies the token as a Mosaico API key. This helps developers quickly spot Mosaico tokens in configuration files or environment variables. **Payload**. The actual secret token. It is a 32-byte string consisting entirely of lowercase, alphanumeric ASCII characters. **This payload must be kept secret and should never be exposed in client-side code.** **Fingerprint**. An hash of the payload. Mosaico uses the fingerprint to identify the key within the system without needing to handle or log the raw secret payload. It is primarily used for administrative actions, such as checking the key's status or revoking it. ## Available Permissions¶ Permissions dictate the exact global operations an API key can execute. | Permission | Action Allowed | Typical Use Case | | --- | --- | --- | | `read` | Retrieve and view data from anywhere on the Mosaico platform. | Front-end dashboards, data analytics integrations, or public-facing read-only APIs. | | `write` | Create new data or update existing data anywhere on the platform. | Ingestion scripts, user input forms, or webhooks pushing data to Mosaico. | | `delete` | Permanently remove data from the platform. | Data lifecycle management, GDPR compliance scripts, or cleanup tasks. | | `manage` | Perform administrative operations on the platform. | Rotating/revoking API keys, managing users, or running automated maintenance tasks. | Mosaico follows a hierarchical structure between them. Each permission automatically inherits all the privileges of the previous one (e.g. `write` has also `read` privileges, `manage` inherits `read`, `write` and `delete` privileges). --- # CLI Reference¶ ## mosaicod run¶ Start the server locally ``` mosaicod run [OPTIONS] ``` ### Options¶ | Option | Default | Description | | --- | --- | --- | | `--host ` | `127.0.0.1` | Specify a host address. | | `--port ` | `6726` | Port to listen on. | | `--local-store ` | `None` | Enable storage of objects on the local filesystem at the specified directory path. | | `--tls` | `false` | Enable TLS. When enabled, the following envirnoment variables needs to be set `MOSAICOD_TLS_CERT_FILE` and `MOSAICOD_TLS_PRIVATE_KEY_FILE` | | `--api-key` | `false` | Require API keys to operate. When enabled the system will require API keys to perform any actions. | ## mosaicod api-key¶ Manage API keys. ### Subcommands¶ | Command | Description | | --- | --- | | `create` | Create a new API key with a custom scope | | `revoke` | Revoke an existing API key | | `status` | Check the status of an API key | | `list` | List all API keys | ### mosaicod api-key create¶ Create a new API key. ``` mosaicod api-key create --permission [read|write|delete|manage] [OPTIONS] ``` | Option | Default | Description | | --- | --- | --- | | `-d, --description` | | Set a description for the API key to make it easily recognizable. | | `--expires-in ` | | Define a time duration, using the ISO8601 format, after which the key in no longer valid (e.g. `P1Y2M3D` 1 year 2 months and 3 days) | | `--expires-at ` | | Define a datetime, using the rfc3339 format, after which the key in no longer valid (e.g `2026-03-27T12:20:00Z`) | ### mosaicod api-key revoke¶ Revoke an existing API key. ``` mosaicod api-key revoke ``` The fingerprint are the last 8 digits of the API key. ### mosaicod api-key status¶ Check the status of an API key. ``` mosaicod api-key status ``` The fingerprint are the last 8 digits of the API key. ### mosaicod api-key list¶ List all API keys. ``` mosaicod api-key list ``` ## Common Options¶ Each `mosaicod` command shares the following common options: | Options | Default | Description | | --- | --- | --- | | `--log-format ` | `pretty` | Set the log output format. Available values are: `json`, `pretty`, `plain` | | `--log-level ` | `warning` | Set the log level. Possible values: warning, info, debug | --- The **Mosaico Daemon**, a.k.a. `mosaicod`, acts as engine of the data platform. Developed in **Rust**, it is engineered to be the high-performance arbiter for all data interactions, guaranteeing that every byte of robotics data is strictly typed, atomically stored, and efficiently retrievable. It functions on a standard client-server model, mediating between your high-level applications (via the SDKs) and the low-level storage infrastructure. ## Architectural Design¶ `mosaicod` is architected atop the Apache Arrow Flight protocol. Apache Arrow Flight is a general-purpose, high-performance client-server framework developed for the exchange of massive datasets. It operates directly on Apache Arrow columnar data, enabling efficient transport over gRPC without the overhead of serialization. Unlike traditional REST APIs which serialize data into text-based JSON, Flight is designed specifically for high-throughput data systems. This architectural choice provides Mosaico with three critical advantages: **Zero-Copy Serialization.** Data is transmitted in the Arrow columnar format, the exact same format used in-memory by modern analytics tools like pandas and Polars. This eliminates the CPU-heavy cost of serializing and deserializing data at every hop. **Parallelized Transport.** Operations are not bound to a single pipe; data transfer can be striped across multiple connections to saturate available bandwidth. **Snapshot-Based Schema Enforcement.** Data types are not guessed, nor are they forced into a rigid global model. Instead, the protocol enforces a rigorous schema handshake that validates data against a specific schema snapshot stored with the sequence. ### Resource Addressing¶ Mosaico treats every entity in the system, whether it's a Sequence or a Topic, as a uniquely addressable resource. These resources are identified by a **Resource Locator**, a uniform logical path that remains consistent across all channels. Mosaico uses two types of resource locators: * A **Sequence Locator** identifies a recording session by its sequence name (e.g., `run_2023_01`). * A **Topic Locator** identifies a specific data stream using a hierarchical path that includes the sequence name and topic path (e.g., `run_2023_01/sensors/lidar_front`). ### Flight Endpoints¶ The daemon exposes Apache Arrow Flight endpoints that handle various operations using Flight's core methods: `list_flights` and `get_flight_info` for discovery and metadata management, `do_put` for high-speed data ingestion, and `do_get` for efficient data retrieval. This design ensures administrative operations don't interfere with data throughput while maintaining low-latency columnar data access. ### Storage Architecture¶ `mosaicod` uses an RDBMS to perform fast queries on metadata, manage system state such as sequence and topic definitions, and handle the event queue for processing asynchronous tasks like background data processing or notifications. An object store (such as S3, MinIO, or local filesystem) provides long-term storage for resilience and durability, holding the bulk sensor data, images, point clouds, and immutable schema snapshots that define data structures. Database Durability and Recovery The DBMS state is not strictly required for data durability. The object store is the source of truth for all data, while the database serves as a metadata catalog for efficient querying and management. If the metadata database is corrupted or destroyed, `mosaicod` can rebuild the entire catalog by rescanning the durable object storage. This design ensures that while the DBMS is used to create relations between datasets, the store guarantees long-term durability and recovery, protecting your data against catastrophic infrastructure failure. --- # Ingestion¶ Data ingestion in Mosaico is explicitly engineered to handle write-heavy workloads, enabling the system to absorb high-bandwidth sensor data, such as 4K video streams or high-frequency Lidar point clouds, without contending with administrative traffic. ## Sessions¶ We have intentionally moved away from traditional versioning. While versioning is a common pattern, it often introduces significant architectural complexity and degrades the developer experience when querying historical data. For instance, if multiple versions of a single sequence exist, the query engine faces an ambiguous choice: should it return the latest state, the most stable state, or a specific point-in-time snapshot? Consider a scenario where you are tracking a temperature sensor. If you have versioned sequences, a query for a given temperature becomes problematic: do you search across Version 1.2 or Version 2.0? Has the data changed across versions? Mosaico eliminates this ambiguity by focusing on **Sessions** rather than versions. A session represents an immutable **data layer** within Mosaico. It acts as a logical container for topics that are uploaded together as a single unit. To visualize the hierarchy, think of a sequence as the primary data container. Sessions then represent specific, immutable layers of data within that sequence, while topics serve as a specific instance of an ontology model. This design allows for high-concurrency environments; you can upload multiple sessions simultaneously without the risk of data races or state corruption. Sessions are the primary mechanism used to update and evolve sequences. This model is particularly powerful for parallel workloads that need to contribute data to the same base layer. Because sessions are independent and immutable, separate workloads can operate in isolation. For example, one process might be cleaning a dataset while another is appending real-time logs; both can work based on the same base data layer and commit their results as independent sessions without interfering with one another. ### An example¶ To illustrate the session workflow in practice, imagine you are managing a dataset for autonomous driving. When you first initialize a sequence, you perform a bulk upload of raw sensor data collected during a drive. This initial upload constitutes your first session, containing the base telemetry and camera streams: ``` [ SESSION: BASE DATA ] topolino_amaranto_25032026/camera/front topolino_amaranto_25032026/camera/back topolino_amaranto_25032026/car/gps topolino_amaranto_25032026/car/imu ``` Once this base layer is established, you can trigger two independent processing workloads. The first workload focuses on computer vision, analyzing the front and back camera streams to generate object detection labels. Simultaneously, a second workload runs a visual odometry algorithm, fusing data from the cameras, IMU, and GPS to calculate the precise trajectory of the vehicle. Because Mosaico supports concurrent sessions, these two tasks do not need to wait for one another or risk overwriting the base data. The vision task commits its results as one session, and the odometry task commits its results as another. The final state of your sequence is now an enriched, multi-layered data container. When you query this sequence, the engine provides a unified view that includes the original raw sensors plus the newly generated analytical topics: ``` [ SESSION: BASE DATA ] topolino_amaranto_25032026/camera/front topolino_amaranto_25032026/camera/back topolino_amaranto_25032026/car/gps topolino_amaranto_25032026/car/imu [ SESSION: LABELING DATA ] topolino_amaranto_25032026/labels/object_detection [ SESSION: VISUAL ODOMETRY ] topolino_amaranto_25032026/tracks/visual_odometry ``` This approach allows your data to grow *horizontally* with new topics while maintaining the absolute immutability of the original sensor readings. ## Ingestion Protocol¶ The data ingestion protocol in Mosaico follows a structured, multi-step flow designed to ensure type safety and prevent race conditions in high-concurrency environments. The process begins with `sequence_create`, which establishes the primary data container. Because Mosaico uses a session-based update model, you must then initialize a specific *data layer* using `session_create`, returning a session UUID that serves as the active context for all subsequent uploads within that specific batch. Within this active session, you define individual data streams via `topic_create`, where each topic is assigned a unique path (e.g., `my_sequence/topic/1`) and returns its own topic UUID. Data is then transmitted using the Arrow Flight `do_put` operation, starting with an Arrow schema for structural validation and followed by a stream of `RecordBatch` payloads. By passing the topic UUID to `do_put`, the system ensures the incoming binary stream is mapped correctly to the intended topic and session layer. Once all topics and their respective data streams are uploaded, the session must be formally committed with `session_finalize`. This action triggers server-side validation against registered ontologies, chunks the data for efficient storage, and locks the session to make the data permanent and available for downstream queries. Here is a simplified example of the ingestion flow using a pyhton-like pseudocode: Ingestion protocol ``` # Initialize the Sequence and the Session layer sequence_create("my_sequence", metadata) ss_uuid = session_create("my_sequence") # Create topics within the session and stream data t1_uuid = topic_create(ss_uuid, "my_sequence/topic/1", metadata) # (1)! do_put(t1_uuid, data_stream) t2_uuid = topic_create(ss_uuid, "my_sequence/topic/2", metadata) do_put(t2_uuid, data_stream) # Commit the session to make data immutable session_finalize(ss_uuid) # (2)! ``` 1. The `topic_create` action returns a UUID that must be passed to the `do_put` call to route the data stream correctly. 2. During finalization, all resources are consolidated and locked. Alternatively, you can call `session_delete(ss_uuid)` to discard the upload. Or call `sequence_delete(sq_uuid)` to discard the entire sequence if you want to start over. Why UUIDs? UUIDs are employed throughout the protocol to prevent contentious uploads. For instance, if two users attempt to create a resource with the same name simultaneously, the system ensures only one successfully receives a UUID. This identifier acts as a "token of authority," ensuring that subsequent `do_put` or `finalize` operations are performed only by the user who initiated the resource. UUID are available to clients only during the `*_create` actions. Possessing a UUID is a prerequisite for performing any further operations on that resource, such as uploading data or finalizing the session. This design choice ensures that only the creator of a resource can modify it. ### Updating a Sequence¶ To extend a sequence with new data, you follow a nearly identical flow to the initial ingestion, but you omit the `sequence_create`. This process leverages Mosaico's session model to layer new information onto the established sequence without modifying the original data. Here is a simplified example of the update flow using a pyhton-like pseudocode: Extending a sequence with new data ``` # Initialize a NEW Session layer for the existing sequence ss_uuid = session_create("my_sequence") # Create new topics (e.g., processed labels) within this session t3_uuid = topic_create(ss_uuid, "my_sequence/labels/object_detection", metadata) # (1)! do_put(t3_uuid, processed_data_stream) # Commit the new session to merge the layer into the sequence session_finalize(ss_uuid) ``` 1. Even though the sequence already exists, the `topic_create` call within a new session ensures this specific data stream is tracked as a new, immutable contribution. Concurrency Because each upload is encapsulated in its own session, multiple workers can extend the same sequence simultaneously. Mosaico handles the isolation of these sessions, ensuring that `session_finalize` only commits the specific topics and data associated with that worker's session UUID. ### Aborting an Upload¶ If you encounter an error *during the ingestion process* or simply want to discard all the data just uploaded, there is a straightforward way to abort the sequence. Here is a simplified example of the abort flow using a pyhton-like pseudocode: Aborting an upload ``` # Initialize the Sequence and the Session layer sequence_create("my_sequence", metadata) ss_uuid = session_create("my_sequence") # Create topics within the session and stream data t1_uuid = topic_create(ss_uuid, "my_sequence/topic/1", metadata) # (1)! do_put(t1_uuid, data_stream) t2_uuid = topic_create(ss_uuid, "my_sequence/topic/2", metadata) do_put(t2_uuid, data_stream) # Delete the session to discard all uploaded topics data session_delete(ss_uuid) # You can delete the dangling sequence since there are no data associated # or avoid deletion and start a new session to upload new data with a `session_create` sequence_delete() ``` Permissions If **API key management** is enabled, the `sequence_delete` and `session_delete` actions require a key with at least `delete` privileges. ## Chunking & Indexing Strategy¶ The backend automatically manages *chunking* to efficiently handle intra-sequence queries and prevent memory overload from ingesting large data streams. As data streams in, the server buffers the incoming data until a full chunk is accumulated, then writes it to disk as an optimal storage unit called a *chunk*. Configuring Chunk Size The chunk size is configurable via the `MOSAICOD_MAX_CHUNK_SIZE_IN_BYTES` environment variable. Setting this value to `0` disables automatic chunking, allowing for unlimited chunk sizes. However, it is generally recommended to set a reasonable chunk size to balance memory usage and query performance. See the environment variables section for more details. For each chunk written to disk, the server calculates and stores *skip indices* in the metadata database. These indices include ontology-specific statistics, such as type-specific metadata (e.g., coordinate bounding boxes for GPS data or value ranges for sensors). This allows the query engine to perform content-based filtering without needing to read the entire bulk data. --- # Setup¶ ## Running with Containers¶ For rapid prototyping, we provide a standard Docker Compose configuration. This creates an isolated network environment containing the `mosaicod` server and its required PostgreSQL database. Daemon compose file ``` name: "mosaico" services: database: image: postgres:18 container_name: postgres hostname: db environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: password POSTGRES_DB: mosaico networks: - mosaico volumes: - pg-data:/var/lib/postgresql healthcheck: # (3)! test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 5s timeout: 5s retries: 5 mosaicod: image: ghcr.io/mosaico-labs/mosaicod container_name: mosaicod networks: - mosaico environment: # (4)! MOSAICOD_DB_URL: postgresql://postgres:password@db:5432/mosaico volumes: - mosaico-data:/data command: | # (1)! run --host 127.0.0.1 --port 6726 --log-level info --local-store /data depends_on: database: condition: service_healthy ports: - "127.0.0.1:6726:6726" # (2)! volumes: pg-data: mosaico-data: networks: mosaico: ``` 1. Here you can list any additional command line options for `mosaicod`. In this example, we configure the server to use the local filesystem for storage, which is mounted to the `/data` directory in the container. This allows you to persist data across container restarts and easily access it from the host machine. If you prefer to use S3-compatible storage, simply remove the `--local-store` option and set the appropriate environment variables for your object storage configuration. 2. Remove `127.0.0.1` to expose this service to external networks. By default, this configuration restricts access to the local machine for security reasons. If you need to access the server from other machines on the network, you can modify the port mapping to allow external connections. 3. The `healthcheck` ensures that the `mosaicod` service only starts after the PostgreSQL database is ready to accept connections. This prevents startup errors related to database connectivity. 4. Additional environment variables can be set here to configure the daemon's behavior, see environment variables for a complete list of options. This configuration provisions both Postgres and mosaicod within a private Docker network. Only the daemon instance is exposed to the host. Security In this basic prototyping setup, TLS and API key management are disabled. The port mapping is restricted to `127.0.0.1`. If you need to access this from an external network, consider configuring `mosaicod` to enable TLS or use a reverse proxy to handle SSL termination. ## Building from Source¶ While Docker images are available for each release, you can compile `mosaicod` from source if you need a specific version not available as a pre-built image. Building from source requires a Rust toolchain. The project uses `sqlx` for compile-time query verification, which normally requires a live database connection. However, Mosaico supports a simpler offline build mode that uses cached query metadata from the `.sqlx` directory, removing the need for a database during compilation. ### Offline Build¶ You can run a offline build using cached sqlx queries with a single command. ``` SQLX_OFFLINE=true cargo build --release ``` ### Online Build¶ If you need to modify the database schema, a running PostgreSQL instance is required. This allows `sqlx` to verify queries against a live database during compilation. You can use the provided Docker Compose file in `docker/devel` which sets up an instance of MinIO and a PostgreSQL database. First, start the development environment: ``` cd docker/devel # Start the services in the background docker compose up -d # To stop and remove the volumes (which clears all data), run: docker compose down -v ``` Apply database migrations to the running PostgreSQL instance. This ensures that the database schema is up-to-date and allows `sqlx` to verify queries during compilation. Next, from the root of the `mosaicod` workspace, install the necessary tools, configure the environment, and run the build. ``` cd mosaicod # Install the SQLx command-line tool cargo install sqlx-cli # Copy the development environment variables for the database connection cp env.devel .env # Apply the database migrations cd crates/mosaicod-db cargo sqlx migrate run # And finally you can build mosaicod cargo build --release --bin mosaicod ``` ## Configuration¶ The server supports S3-compatible object storage by default but can be configured for local storage via command line options. ### Database¶ Mosaico requires a connection to a running **PostgreSQL** instance, which is defined via the `MOSAICOD_DB_URL` environment variable. ### Remote Storage Configuration¶ For production deployments, `mosaicod` should be configured to use an S3-compatible object store (such as AWS S3, Google Cloud Storage, Hetzner Object Store, etc) for durable, long-term storage. This is configured setting the proper environment variables for your object store provider. ### Local Storage Configuration¶ This command will start a `mosaicod` instance using the local filesystem as storage layer. ``` mosaicod run --local-store /tmp/mosaicod ``` --- # Queries¶ Mosaico distinguishes itself from simple file stores with a powerful **Query System** capable of filtering data based on both high-level metadata and content values. The query engine operates through the `query` action, accepting structured JSON-based filter expressions that can span the entire data hierarchy. ## Query Architecture¶ The query engine is designed around a three-tier filtering model that allows you to construct complex, multi-dimensional searches: **Sequence Filtering.** Target recordings by structural attributes like sequence name, creation timestamp, or user-defined metadata tags. This level allows you to narrow down which recording sessions are relevant to your search. **Topic Filtering.** Refine your search to specific data streams within sequences. You can filter by topic name, ontology tag (the data type), serialization format, or topic-level user metadata. **Ontology Filtering.** Query the actual physical values recorded inside the sensor data without scanning terabytes of files. The engine leverages statistical indices computed during ingestion, min/max bounds stored in the metadata cache for each chunk, to rapidly include or exclude entire segments of data. ## Filter Domains¶ ### Sequence Filter¶ The sequence filter allows you to target specific recording sessions based on their metadata: | Field | Description | | --- | --- | | `sequence.name` | The sequence identifier (supports text operations) | | `sequence.created_at` | The creation timestamp in nanoseconds (supports timestamp operations) | | `sequence.user_metadata.` | Custom user-defined metadata attached to the sequence | ### Topic Filter¶ The topic filter narrows the search to specific data streams within matching sequences: | Field | Description | | --- | --- | | `topic.name` | The topic path within the sequence (supports text operations) | | `topic.created_at` | The topic creation timestamp in nanoseconds (supports timestamp operations) | | `topic.ontology_tag` | The data type identifier (e.g., `Lidar`, `Camera`, `IMU`) | | `topic.serialization_format` | The binary layout format (`Default`, `Ragged`, or `Image`) | | `topic.user_metadata.` | Custom user-defined metadata attached to the topic | ### Ontology Filter¶ The ontology filter queries the actual sensor data values. Fields are specified using dot notation: `.`. For example, to query IMU acceleration data: `imu.acceleration.x`, where `imu` is the ontology tag and `acceleration.x` is the field path within that data model. #### Timestamp query support¶ If `include_timestamp_range` is set to `true` the response will also return timestamps ranges for each query. ## Supported Operators¶ The query engine supports a rich set of comparison operators. Each operator is prefixed with `$` in the JSON syntax: | Operator | Description | | --- | --- | | `$eq` | Equal to (supports all types) | | `$neq` | Not equal to (supports all types) | | `$lt` | Less than (numeric and timestamp only) | | `$gt` | Greater than (numeric and timestamp only) | | `$leq` | Less than or equal to (numeric and timestamp only) | | `$geq` | Greater than or equal to (numeric and timestamp only) | | `$between` | Within a range `[min, max]` inclusive (numeric and timestamp only) | | `$in` | Value is in a set of options (supports integers and text) | | `$match` | Matches a pattern (text only, supports SQL LIKE patterns with `%` wildcards) | | `$ex` | Field exists | | `$nex` | Field does not exist | ## Query Syntax¶ Queries are submitted as JSON objects. Each field is mapped to an operator and value. Multiple conditions are combined with implicit AND logic. ``` { "sequence": { "name": { "$match": "test_run_%" }, "user_metadata": { "driver": { "$eq": "Alice" } } }, "topic": { "ontology_tag": { "$eq": "imu" } }, "ontology": { "imu.acceleration.x": { "$gt": 5.0 }, "imu.acceleration.y": { "$between": [-2.0, 2.0] }, "include_timestamp_range": true, // (1)! } } ``` 1. This filed is optional, if set to `true` the query returns the timestamp ranges This query searches for: * Sequences with names matching `test_run_%` pattern * Where the user metadata field `driver` equals `"Alice"` * Containing topics with ontology tag `imu` * Where the IMU's x-axis acceleration exceeds 5.0 * And the y-axis acceleration is between -2.0 and 2.0 ## Response Structure¶ The query response is hierarchically grouped by sequence. For each matching sequence, it provides the list of topics that satisfied the filter criteria, along with optional timestamp ranges indicating when the ontology conditions were met. Query response example ``` { "items": [ { "sequence": "test_run_01", "topics": [ { "locator": "test_run_01/sensors/imu", "timestamp_range": [1000000000, 2000000000] }, { "locator": "test_run_01/sensors/gps", "timestamp_range": [1000000000, 2000000000] } ] }, { "sequence": "test_run_02", "topics": [ { "locator": "test_run_02/camera/front", "timestamp_range": [1500000000, 2500000000] }, { "locator": "test_run_02/lidar/point_cloud", "timestamp_range": [1500000000, 2500000000] } ] } ] } ``` ### Timestamps¶ It returns the time window `[min, max]` where the filter conditions were met for that topic, with `min` being the timestamp of the first matching event and max being the timestamp of the last matching event. This allows you to retrieve only the relevant data slices using the retrieval protocol. Note The `timestamp_range` field is included only when ontology filters are applied and `include_timestamp_range` is set to `true` inside the `ontology` filter. ## Performance Characteristics¶ The query engine is optimized for high performance by minimizing unnecessary data retrieval and I/O operations. During execution, the engine uses index-based pruning to evaluate precomputed min/max statistics and skip indices, allowing it to bypass irrelevant data chunks without reading the underlying files. Performance is further improved by executing metadata cache queries, such as sequence and topic filters, directly within the database, which ensures sub-second response times even across thousands of sequences. The system employs **lazy evaluation** to keep network payloads lightweight; instead of returning raw data immediately, queries return locators and timestamp ranges. This architecture allows client applications to fetch only the required data slices via the retrieval protocol as needed. --- # Retrieval¶ Unlike simple file downloads, this protocol provides an interface for requesting precise data slices, dynamically assembled and streamed back as optimized stream of Arrow record batches. ## The Retrieval Protocol¶ Accessing data requires specifying the Locator, which defines the topic path, and an optional time range in nanoseconds. Upon receiving a request, the server performs an index lookup in the metadata cache to identify physical data chunks intersecting the requested time window. This is followed by pruning, discarding chunks outside the query bounds to avoid redundant I/O. Once relevant segments are identified, the server streams the data by opening underlying files and delivering it in a high-throughput pipeline. In the protocol, the `get_flight_info` call returns a list of resources, each containing an endpoint (the name of the topic or sequence, such as `my_sequence` or `my_sequence/my/topic`) and a ticket, an opaque binary blob used by the server in the `do_get` call to extract and stream the data. Calling `get_flight_info` on a sequence returns all topics associated with that sequence, whereas calling it on a specific topic returns only the endpoint and ticket for that topic. Retrieval protocol ``` # Define the locator and the temporal slice locator = "my_sequence/topic/1" time_range = (start_ns, end_ns) # Optional: defaults to full history # Resolve the locator into endpoint and tickets flight_info = get_flight_info(locator, time_range) for endpoint in flight_info.endpoints: # Use the ticket to stream the actual data batches data_stream = do_get(endpoint.ticket) for batch in data_stream: process(batch) ``` ## Sequence List¶ To find the list of all sequences available in the system, you can call `list_flights` with the root locator: List sequences ``` # List all sequences in the system flight_info = list_flights("") # or list_flights("/") ``` This will return the list of all sequence resource locators available in the platform, which can then be used to retrieve specific topics or data slices. ## Metadata Context Headers¶ To provide full context, the data stream is prefixed with a schema message containing embedded custom metadata. Mosaico injects context into this header for client reconstruction of the environment. This includes `user_metadata`, preserving original project context like experimental tags or vehicle IDs, and the `ontology_tag`, informing the client of sensor data types (e.g., `lidar`, `camera`) for type-safe deserialization. The `serialization_format` guides interpretation of the underlying serialization protocol used. Now the supported formats include: * `Default`: The standard format. * `Ragged`: Optimized for variable-length lists. * `Image`: An optimized array format for high-resolution visual data. --- # TLS Support¶ Securing your Mosaico instance is straightforward, as TLS (Transport Layer Security) is fully supported out of the box. Enabling TLS ensures that all communications with the daemon are encrypted and secure. To activate it, simply append the `--tls` flag to your `mosaicod run` command. When the `--tls` flag is used, `mosaicod` requires a valid certificate and private key. It looks for these credentials via the following environment variables: * `MOSAICOD_TLS_CERT_FILE`: The path to the PEM-encoded X.509 certificate. * `MOSAICOD_TLS_PRIVATE_KEY_FILE`: The path to the file containing the PEM-encoded RSA private key. Use a reverse proxy for TLS termination If you prefer to manage TLS termination separately, you can run `mosaicod` without the `--tls` flag and use a reverse proxy (like Nginx or Caddy) to handle SSL termination. This allows you to centralize TLS management and offload encryption tasks from the daemon. ## Generate a Self-Signed Certificate¶ Run the following command to generate a `cert.pem` a `key.pem` and a `ca.pem` file: ``` # Generate the root CA openssl genrsa -out ca.key 4096 openssl req -x509 -new -nodes -key ca.key -sha256 -days 365 \ -subj "/CN=MyTestCA" -out ca.pem # Generate the server private key openssl genrsa -out key.pem 4096 # Create a certificate signing request (CSR) for the server openssl req -new -key key.pem -out server.csr \ -subj "/CN=localhost" \ -addext "subjectAltName=DNS:localhost,IP:127.0.0.1" # Sign the server CSR with the root CA to create the end-entity certificate openssl x509 -req -in server.csr -CA ca.pem -CAkey ca.key -CAcreateserial \ -out cert.pem -days 365 -sha256 \ -extfile <(printf "basicConstraints=CA:FALSE\nkeyUsage=digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\nsubjectAltName=DNS:localhost,IP:127.0.0.1") ``` The scripts will generate the following files | File | Description | | --- | --- | | `ca.key` | The private key for the Certificate Authority; used only to sign other certificates and **must be kept secret**. | | `ca.pem` | The public certificate for the Authority; provided to clients so they can verify the server's identity. | | `ca.srl` | A text file containing the next serial number to be assigned by the CA; safe to ignore or delete. | | `key.pem` | The private key for the mosaicod server; used to decrypt traffic and prove ownership of the server certificate. | | `cert.pem` | The end-entity certificate for the server. | | `server.csr` | A temporary Certificate Signing Request file used to bridge the public key and the identity during generation. | Use `cert.pem` and `key.pem` for server-side TLS identity in the mosaicod daemon, while distributing `ca.pem` to clients as the trusted root certificate. Test certificate The certificates produced by the command above is strictly for local development or testing. Do not use it in production. --- # Release Cycle¶ This document describes briefly how the release process is handled for Mosaico project. ## Monorepo¶ Mosaico utilizes a monorepo structure to simplify integration and testing between `mosaicod` daemon and Python SDK. While these components reside in the same repository, they are decoupled: each component maintains its own release schedule and both follow semantic versioning. ## Development workflow¶ The development workflow relies on a specific set of branches and tags to manage stability and feature development. * `main`: the primary integration branch. All stable features and fixes eventually land here. Official release tags are cut directly from main once sufficient changes have been accumulated. * `issue/`: feature or bug-fix branches linked to a specific GitHub issue. Branched from *main* and merged back via pull request upon completion. * `release/[mosaicod|mosaico-py]/vX.Y.`: maintenance branches for *critical hotfixes*. Created from an existing version tag *when a patch is required* for an older release. The final commit is tagged with the incremented version. Relevant fixes should be cherry-picked or merged back into main if applicable. These branches might be used in the future to support pre-release stages. ## Tags¶ We use specific tag prefixes to trigger CI/CD pipelines and distinguish between *stable releases* of the daemon and the SDK | Component | Tag | | --- | --- | | Daemon | `mosaicod/vX.Y.Z` | | Python SDK | `mosaico-py/vX.Y.Z` | --- ## mosaicolabs.comm.MosaicoClient ¶ ``` MosaicoClient( *, host, port, timeout, control_client, connection_pool, executor_pool, sentinel, tls_cert, api_key_fingerprint, middlewares, ) ``` The gateway to the Mosaico Data Platform. This class centralizes connection management, resource pooling, and serves as a factory for specialized handlers. It is designed to manage the lifecycle of both network connections and asynchronous executors efficiently. Context Manager Usage The `MosaicoClient` is best used as a context manager to ensure all internal pools and connections are gracefully closed. ``` from mosaicolabs import MosaicoClient with MosaicoClient.connect( "localhost", 6726, api_key="msco_s3l8gcdwuadege3pkhou0k0n2t5omfij_f9010b9e", ) as client: sequences = client.list_sequences() print(f"Available data: {sequences}") ``` **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. Sentinel Enforcement This constructor checks for a private internal sentinel. Attempting to instantiate this class manually will result in a `RuntimeError`. 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* | | `connection_pool` | `Optional[_ConnectionPool]` | Internal pool for data connections. | *required* | | `executor_pool` | `Optional[_ExecutorPool]` | Internal pool for async I/O. | *required* | | `sentinel` | `object` | Private object used to verify factory-based instantiation. | *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, 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, initializes the primary control channel, and prepares the internal resource pools. Factory Pattern Direct instantiation via `__init__` is restricted through a sentinel pattern and will raise a `RuntimeError`. This ensures that every client in use has been correctly configured with a valid network connection. Note If using the Authorization middleware (via an API-Key), this method requires the minimum `APIKeyPermissionEnum.Read` permission. 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` | | `tls_cert_path` | `Optional[str]` | Path to the TLS certificate file. Defaults to None. | `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). | Example ``` from mosaicolabs import MosaicoClient # Establish a connection to the Mosaico Data Platform with MosaicoClient.connect( "localhost", 6726, api_key="msco_vy9lqa7u4lr7w3vimhz5t8bvvc0xbmk2_9c94a86", ) as client: # Perform operations using the client pass ``` ### 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. | Example ``` # If MOSAICOD_TLS_CERT_FILE is set in the shell: client = MosaicoClient.from_env("localhost", 6276) ``` ### 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. Note If using the Authorization middleware (via an API-Key), this method requires the minimum `APIKeyPermissionEnum.Read` permission. 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. | Example ``` from mosaicolabs import MosaicoClient # Establish a connection to the Mosaico Data Platform with MosaicoClient.connect("localhost", 6726) as client: # Retrieve a sequence handler sequence_handler = client.sequence_handler("my_sequence") if sequence_handler: # Print sequence details print(f"Sequence: {sequence_handler.name}") print(f"Created: {sequence_handler.created_datetime}") print(f"Topic list: {sequence_handler.topics}") print(f"User Metadata: {sequence_handler.user_metadata}") print(f"Size (MB): {sequence_handler.total_size_bytes / 1024 / 1024}") ``` ### topic\_handler ¶ ``` topic_handler(sequence_name, topic_name) ``` Retrieves a `TopicHandler` for a specific data channel. Note If using the Authorization middleware (via an API-Key), this method requires the minimum `APIKeyPermissionEnum.Read` permission. 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. | Example ``` from mosaicolabs import MosaicoClient # Establish a connection to the Mosaico Data Platform with MosaicoClient.connect("localhost", 6726) as client: # Retrieve a topic handler topic_handler = client.topic_handler("my_sequence", "/front/camera/image_raw) if topic_handler: # Print topic details print(f"Topic: {topic_handler.sequence_name}:{topic_handler.name}") print(f"Ontology Tag: {topic_handler.ontology_tag}") print(f"Created: {topic_handler.created_datetime}") print(f"User Metadata: {topic_handler.user_metadata}") print(f"Size (MB): {topic_handler.total_size_bytes / 1024 / 1024}") ``` ### 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. Important The function **must** be called inside a with context, otherwise a RuntimeError is raised. Note If using the Authorization middleware (via an API-Key), this method requires at least `APIKeyPermissionEnum.Write` permission. 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 | OnErrorPolicy` | Behavior on write failure. Defaults to `SessionLevelErrorPolicy.Report`. Deprecated: `OnErrorPolicy` is deprecated since v0.3.0; use `SessionLevelErrorPolicy` instead. It will be removed in v0.4.0. | `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. | Example ``` from mosaicolabs import MosaicoClient, SessionLevelErrorPolicy # 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={ "driver": { "driver_id": "drv_sim_017", "role": "validation", "experience_level": "senior", }, "location": { "city": "Milan", "country": "IT", "facility": "Downtown", "gps": { "lat": 45.46481, "lon": 9.19201, }, }, } on_error = SessionLevelErrorPolicy.Delete ) as seq_writer: # Start creating topics and pushing data... # (1)! ``` 1. See also: * `SequenceWriter.topic_create()` * `TopicWriter.push()` ### 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. Note If using the Authorization middleware (via an API-Key), this method requires at least `APIKeyPermissionEnum.Delete` permission. 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(session_uuid) ``` 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. Note If using the Authorization middleware (via an API-Key), this method requires at least `APIKeyPermissionEnum.Delete` permission. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `session_uuid` | `str` | The unique identifier of the session to remove. | *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. | Example ``` from mosaicolabs import MosaicoClient with MosaicoClient.connect("localhost", 6726) as client: sequences = client.list_sequences() print(f"Available sequences: {sequences}") ``` ### list\_sequence\_notifications ¶ ``` list_sequence_notifications(sequence_name) ``` Retrieves a list of all notifications available on the server for a specific sequence. Note If using the Authorization middleware (via an API-Key), this method requires the minimum `APIKeyPermissionEnum.Read` permission. 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. | Example ``` from mosaicolabs import MosaicoClient with MosaicoClient.connect("localhost", 6726) as client: sequence_notifications = client.list_sequence_notifications("my_sequence") for notification in sequence_notifications: print(f"Notification Type: {notification.type}") print(f"Notification Message: {notification.message}") print(f"Notification Created: {notification.created_datetime}") ``` ### clear\_sequence\_notifications ¶ ``` clear_sequence_notifications(sequence_name) ``` Clears the notifications for a specific sequence from the server. Note If using the Authorization middleware (via an API-Key), this method requires at least `APIKeyPermissionEnum.Delete` permission. 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 Note If using the Authorization middleware (via an API-Key), this method requires the minimum `APIKeyPermissionEnum.Read` permission. 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. | Example ``` from mosaicolabs import MosaicoClient with MosaicoClient.connect("localhost", 6726) as client: topic_notifications = client.list_topic_notifications("my_sequence", "my_topic") for notification in topic_notifications: print(f"Notification Type: {notification.type}") print(f"Notification Message: {notification.message}") print(f"Notification Created: {notification.created_datetime}") ``` ### clear\_topic\_notifications ¶ ``` clear_topic_notifications(sequence_name, topic_name) ``` Clears the notifications for a specific topic from the server. Note If using the Authorization middleware (via an API-Key), this method requires at least `APIKeyPermissionEnum.Delete` permission. 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. Note If using the Authorization middleware (via an API-Key), this method requires the minimum `APIKeyPermissionEnum.Read` permission. 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. | Query with variadic arguments ``` from mosaicolabs import QueryOntologyCatalog, QuerySequence, Query, IMU, MosaicoClient # Establish a connection to the Mosaico Data Platform with MosaicoClient.connect("localhost", 6726) as client: # Perform the server side query results = client.query( # Append a filter for sequence metadata QuerySequence() .with_user_metadata("environment.visibility", lt=50) .with_name_match("test_drive"), # Append a filter with deep time-series data discovery and measurement time windowing QueryOntologyCatalog() .with_expression(IMU.Q.acceleration.x.gt(5.0)) .with_expression(IMU.Q.timestamp_ns.gt(1700134567)) ) # Inspect the results if results is not None: # Results are automatically grouped by Sequence for easier data management for item in results: print(f"Sequence: {item.sequence.name}") ``` Query with `Query` object ``` from mosaicolabs import QueryOntologyCatalog, QuerySequence, Query, IMU, MosaicoClient # Establish a connection to the Mosaico Data Platform with MosaicoClient.connect("localhost", 6726) as client: # Build a filter with name pattern and metadata-related expression query = Query( # Append a filter for sequence metadata QuerySequence() .with_user_metadata("environment.visibility", lt=50) .with_name_match("test_drive"), # Append a filter with deep time-series data discovery and measurement time windowing QueryOntologyCatalog() .with_expression(IMU.Q.acceleration.x.gt(5.0)) .with_expression(IMU.Q.timestamp_ns.gt(1700134567)) ) # Perform the server side query results = client.query(query=query) # Inspect the results if results is not None: # Results are automatically grouped by Sequence for easier data management for item in results: print(f"Sequence: {item.sequence.name}") ``` ### version ¶ ``` version() ``` Get the version of the Mosaico server. Note If using the Authorization middleware (via an API-Key), this method requires the minimum `APIKeyPermissionEnum.Read` permission. 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. Note Requires the client to have `APIKeyPermissionEnum.Manage` permission. You can also optionally set an expiration time and a description for the key. 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. | Example ``` from mosaicolabs import MosaicoClient, APIKeyPermissionEnum # Open the connection with the Mosaico Client with MosaicoClient.connect("localhost", 6726, api_key="") as client: # Create a new API key with read and write permissions api_key = client.api_key_create( permission=APIKeyPermissionEnum.Write, description="API key for data ingestion", ) ``` ### api\_key\_status ¶ ``` api_key_status(api_key_fingerprint=None) ``` Retrieves the status and metadata of an API key. Note Requires the client to have `APIKeyPermissionEnum.Manage` permission. 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. Note Requires the client to have `APIKeyPermissionEnum.Manage` permission. 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:** Terminated the connection pool to the `mosaicod` backend. \* **Thread Termination:** Shuts down the internal thread executor pool responsible for asynchronous data fetching and background streaming. Note If using the client as a context manager (via `with MosaicoClient.connect(...)`), this method is invoked automatically on exit. Explicit calls are required only for manual lifecycle management. Example ``` from mosaicolabs import MosaicoClient # Manual connection management client = MosaicoClient.connect("localhost", 6726) # High-performance streaming or ML extraction qresp = client.query(...) # Do something else... # Ensure resources are consistently freed. client.close() ``` ## 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 asynchronous 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()` Example ``` with MosaicoClient.connect("localhost", 6726) as client: # Retrieve notifications for a problematic sequence errors = client.list_sequence_notifications("mission_alpha") for error in errors: print(f"[{error.created_datetime}] {error.type}: {error.message}") ``` 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 | --- ## 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. Note The `FinalizedWithError`, `IgnoredLastError` and `RaisedException` values can only be tracked if the `TopicWriter` is used in a `with` context. ### 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. Note When the connection is established via the authorization middleware (i.e. using an API Key), this policy requires the minimum `APIKeyPermissionEnum.Read` permission. Lock Status Unlike standard successful finalization, a session finalized via a `Report` policy is **not placed in a locked state**. This means the sequence remains mutable at a system level and can be **deleted in a later moment** once debugging or triage is complete. ### 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. Note When the connection is established via the authorization middleware (i.e. using an API Key), this policy is successfully executed by the server only if the API Key has `APIKeyPermissionEnum.Delete` permission. ## 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.OnErrorPolicy ¶ Bases: `Enum` Defines the behavior of the `SequenceWriter` 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 sequence and notify the server of the specific failure, allowing existing data chunks to remain accessible for inspection. Note When the connection is established via the authorization middleware (i.e. using an API Key), this policy requires the minimum `APIKeyPermissionEnum.Read` permission. Lock Status Unlike standard successful finalization, a sequence finalized via a `Report` policy is **not placed in a locked state**. This means the sequence remains mutable at a system level and can be **deleted in a later moment** once debugging or triage is complete. ### Delete `class-attribute` `instance-attribute` ¶ ``` Delete = 'delete' ``` Delete the sequence and instruct the server to discard all data. This is the default "all-or-nothing" strategy. If a failure occurs, the `SequenceWriter` 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. Note When the connection is established via the authorization middleware (i.e. using an API Key), this policy is successfully executed by the server only if the API Key has `APIKeyPermissionEnum.Delete` permission. ## 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. Note When the connection is established via the authorization middleware (i.e. using an API Key), this policy requires the minimum `APIKeyPermissionEnum.Read` permission. Lock Status Unlike standard successful finalization, a session finalized via a `Report` policy is **not placed in a locked state**. This means the sequence remains mutable at a system level and can be **deleted in a later moment** once debugging or triage is complete. ### 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. Note When the connection is established via the authorization middleware (i.e. using an API Key), this policy is successfully executed by the server only if the API Key has `APIKeyPermissionEnum.Delete` permission. ## 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. Internal Use Only This class is part of the internal communication protocol. End-users should never need to use these identifiers directly, as they are abstracted by the public methods in `MosaicoClient`, `SequenceWriter`, and `TopicWriter`. ### 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 asynchronous 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 --- # 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. Precision Loss Converting to a 64-bit float may result in the loss of nanosecond precision due to mantissa limitations. ### 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. Microsecond Limitation Python's `datetime` objects typically support microsecond precision; nanosecond data below that threshold will be truncated. --- ## 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` | Example ``` from mosaicolabs import setup_sdk_logging from rich.console import Console console = Console(stderr=True) setup_sdk_logging( level="INFO", pretty=True, console=console ) with MosaicoClient.connect(host="localhost", port=6726) as client: # Perform operations ``` Notes * When 'pretty' is enabled, the logger name is styled in 'dim white' to keep focus on the message content. * Propagation is disabled (propagate=False) to prevent logs from bubbling up to the root logger and causing duplicate output in test runners like pytest. --- ## mosaicolabs.handlers.SequenceHandler ¶ ``` SequenceHandler( *, sequence_model, client, connection_pool_allocator, executor_pool_allocator, 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`. Obtaining a Handler Users should not instantiate this class directly. The recommended way to obtain a handler is via the `MosaicoClient.sequence_handler()` factory method. 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. | Example ``` 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 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 ) # Peek at the start time (without consuming data) print(f"Recording starts at: {streamer.next_timestamp()}") # Start timed data-stream for topic, msg in streamer: print(f"[{topic}] at {msg.timestamp_ns}: {type(msg.data).__name__}") # Once done, close the resources, topic handler and related reading channels (recommended). seq_handler.close() ``` Important Every call to `get_data_streamer()` will automatically invoke `close()` on any previously spawned `SequenceDataStreamer` instance and its associated Apache Arrow Flight channels before initializing the new stream. Example: ``` seq_handler = client.sequence_handler("mission_alpha") # Opens first stream streamer_v1 = seq_handler.get_data_streamer(start_timestamp_ns=T1) # Calling this again automatically CLOSES streamer_v1 and opens a new channel streamer_v2 = seq_handler.get_data_streamer(start_timestamp_ns=T2) # Using `streamer_v1` will raise a ValueError for topic, msg in streamer_v1 # raises here! pass ``` ### 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. | Example ``` import sys from mosaicolabs import MosaicoClient with MosaicoClient.connect("localhost", 6726) as client: seq_handler = client.sequence_handler("mission_alpha") if seq_handler: # Use a Handler to inspect the catalog top_handler = seq_handler.get_topic_handler("/front/imu") if top_handler: print(f"Sequence: {top_handler.sequence_name}") print(f" |Topic: {top_handler.sequence_name}:{top_handler.name}") print(f" |User metadata: {top_handler.user_metadata}") print(f" |Timestamp span: {top_handler.timestamp_ns_min} - {top_handler.timestamp_ns_max}") print(f" |Created {top_handler.created_datetime}") print(f" |Size (MB) {top_handler.total_size_bytes/(1024*1024)}") # Once done, close the resources, topic handler and related reading channels (recommended). seq_handler.close() ``` ### 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. Important The function **must** be called inside a with context, otherwise a RuntimeError is raised. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `on_error` | `SessionLevelErrorPolicy | OnErrorPolicy` | Behavior on write failure. Defaults to `SessionLevelErrorPolicy.Report`. Deprecated: `OnErrorPolicy` is deprecated since v0.3.0; use `SessionLevelErrorPolicy` instead. It will be removed in v0.4.0. | `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. | Example ``` 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 ) as seq_updater: # Start creating topics and pushing data # (1)! # Exiting the block automatically flushes all topic buffers, finalizes the sequence on the server # and closes all connections and pools ``` 1. See also: * `SequenceUpdater.topic_create()` * `TopicWriter.push()` ### 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. Note This method does not close any active topic handlers or data streamers. The function does not affect actual sequence data-streams. Therefore, it is safe to call this method multiple times without closing any active resources. Returns: | Name | Type | Description | | --- | --- | --- | | `bool` | `bool` | True if the reload was successful, False otherwise. | Example ``` 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: # Perform operations, typically updating the sequence on the server # ... # (1)! # Refresh the handler's data from the server if not seq_handler.reload(): print("Failed to reload sequence handler") ``` 1. See also: `SequenceUpdater` ### 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. Example ``` 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: # Perform operations # ... # Once done, close the resources, topic handler and related reading channels (recommended). seq_handler.close() ``` ## 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`. Obtaining a Handler Direct instantiation of this class is discouraged. Use the `MosaicoClient.topic_handler()` factory method to retrieve an initialized handler. 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. | Example ``` 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: 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 (without consuming data) print(f"Recording starts at: {streamer.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() ``` Important Every call to `get_data_streamer()` will automatically invoke `close()` on any previously spawned `TopicDataStreamer` instance and its associated Apache Arrow Flight channel before initializing the new stream. Example: ``` top_handler = client.topic_handler("mission_alpha", "/front/imu") # Opens first stream streamer_v1 = top_handler.get_data_streamer(start_timestamp_ns=T1) # Calling this again automatically CLOSES streamer_v1 and opens a new channel streamer_v2 = top_handler.get_data_streamer(start_timestamp_ns=T2) # Using `streamer_v1` will raise a ValueError for msg in streamer_v1 # raises here! pass ``` ### 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. Note * If no streamer has been spawned (via `get_data_streamer`), this method performs no operation and returns safely. * Explicitly closing handlers is a best practice when iterating through large datasets to prevent resource accumulation. Example ``` from mosaicolabs import MosaicoClient with MosaicoClient.connect("localhost", 6726) as client: # Access a specific sensor topic (e.g., IMU) top_handler = client.topic_handler("mission_alpha", "/front/imu") if top_handler: # Initialize a high-performance data stream imu_stream = top_handler.get_data_streamer( start_timestamp_ns=1738508778000000000, end_timestamp_ns=1738509618000000000 ) # Consume data for ML training or analysis # for msg in imu_stream: ... # Release the streaming channel and backend resources top_handler.close() ``` ## 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: 1. **Peeks** at the next available timestamp from every active topic stream. 2. **Selects** the topic currently holding the lowest absolute timestamp. 3. **Yields** that specific record and advances only the "winning" topic stream. Obtaining a Streamer Do not instantiate this class directly. Use the `SequenceHandler.get_data_streamer()` method to obtain a configured instance. Internal constructor for SequenceDataStreamer. **Do not call this directly.** Internal library modules should use the `SequenceDataStreamer._connect()` factory. Example ``` 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 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 ) # Start timed data-stream for topic, msg in streamer: # Do some processing... # Once done, close the resources, topic handler and related reading channels (recommended). seq_handler.close() ``` 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. | Example ``` 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 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 ) # Peek at the start time (without consuming data) print(f"Recording starts at: {streamer.next_timestamp()}") # Do some processing... # Once done, close the resources, topic handler and related reading channels (recommended). seq_handler.close() ``` ### 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. Automatic Cleanup In standard workflows, you do not need to call this manually. This function is **automatically invoked** by the `SequenceHandler.close()` method, which in turn is triggered by the `__exit__` logic of the parent `SequenceHandler` when used within a `with` context. ## 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`. Obtaining a Streamer Users should typically not instantiate this class directly. The recommended way to obtain a streamer is via the `TopicHandler.get_data_streamer()` method. 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. Example ``` 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: 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 (without consuming data) print(f"Recording starts at: {streamer.next_timestamp()}") # Direct, low-overhead loop for imu_msg in imu_stream: # Do some processing... # Once done, close the reading channel (recommended) top_handler.close() ``` 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. | Example ``` 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: 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 (without consuming data) print(f"Recording starts at: {streamer.next_timestamp()}") # Do some processing... # Once done, close the reading channel (recommended) top_handler.close() ``` ### close ¶ ``` close() ``` Gracefully terminates the underlying Apache Arrow Flight stream and releases buffers. Automatic Lifecycle Management In most production workflows, manual invocation is not required. This method is **automatically called** by the parent `TopicHandler.close()`. If the handler is managed within a `with` context, the SDK ensures a top-down cleanup of the handler and its associated streamers upon exit. Example ``` # Manual resource management (if not using 'with' block) streamer = topic_handler.get_data_streamer() try: for meas in streamer: process_robot_data(meas) finally: streamer.close() ``` --- ## mosaicolabs.handlers.config.WriterConfig `dataclass` ¶ ``` WriterConfig(max_batch_size_bytes, max_batch_size_records) ``` Configuration for common settings for Sequence and Topic writers. Internal Usage This is currently **not a user-facing class**. It is extended by the `SessionWriterConfig`. 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, connection_pool, executor_pool, 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**. ##### Key Responsibilities¶ * **Lifecycle Management**: Coordinates creation, finalization, or abort signals with the server. * **Resource Distribution**: Implements a "Multi-Lane" architecture by distributing network connections from a Connection Pool and thread executors from an Executor Pool to individual `TopicWriter` instances. This ensures strict isolation and maximum parallelism between diverse data streams. Usage Pattern This class **must** be used within a `with` statement (Context Manager). The context entry triggers sequence registration on the server, while the exit handles automatic finalization or error cleanup based on the configured `SessionLevelErrorPolicy`. Obtaining a Writer Do not instantiate this class directly. Use the `MosaicoClient.sequence_create()` factory method. Internal constructor for SequenceWriter. **Do not call this directly.** Users must call `MosaicoClient.sequence_create()` to obtain an initialized writer. Example ``` from mosaicolabs import MosaicoClient, SessionLevelErrorPolicy # Open the connection with the Mosaico Client with MosaicoClient.connect("localhost", 6726) as client: # Start the Sequence Orchestrator with client.sequence_create( # (1)! sequence_name="mission_log_042", # Custom metadata for this data sequence. metadata={ "driver": { "driver_id": "drv_sim_017", "role": "validation", "experience_level": "senior", }, "location": { "city": "Milan", "country": "IT", "facility": "Downtown", "gps": { "lat": 45.46481, "lon": 9.19201, }, }, } on_error = SessionLevelErrorPolicy.Delete ) as seq_writer: # Start creating topics and pushing data # (2)! # Exiting the block automatically flushes all topic buffers, finalizes the sequence on the server # and closes all connections and pools ``` 1. See also: `MosaicoClient.sequence_create()` 2. See also: * `SequenceWriter.topic_create()` * `TopicWriter.push()` Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `sequence_name` | `str` | Unique name for the new sequence. | *required* | | `client` | `FlightClient` | The primary control FlightClient. | *required* | | `connection_pool` | `Optional[_ConnectionPool]` | Shared pool of data connections for parallel writing. | *required* | | `executor_pool` | `Optional[_ExecutorPool]` | Shared pool of thread executors for asynchronous I/O. | *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\_uuid `property` ¶ ``` session_uuid ``` Returns the UUID of the session corresponding to this sequence write or update. Returns: | Type | Description | | --- | --- | | `str` | The UUID 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`. | Example Processing a generic interleaved sensor log (like a ROS bag or a custom JSON log): ``` from mosaicolabs import SequenceWriter, IMU, Image # Topic to Ontology Mapping: Defines the schema for each sensor stream # Example: {"/camera": Image, "/imu": IMU} topic_to_ontology = { ... } # Adapter Factory: Maps raw sensor payloads to Mosaico Ontology instances # Example: {"/imu": lambda p: IMU(acceleration=Vector3d.from_list(p['acc']), ...)} adapter = { ... } with client.sequence_create("physical_ai_trial_01") as seq_writer: # log_iterator represents an interleaved stream (e.g., ROSbags, MCAP, or custom logs). for ts, topic, payload in log_iterator: # Access the topic-specific buffer. # get_topic_writer retrieves a persistent writer from the internal cache twriter = seq_writer.get_topic_writer(topic) if twriter is None: # Dynamic Topic Registration. # If the topic is encountered for the first time, register it using the # pre-defined Ontology type to ensure data integrity. twriter = seq_writer.topic_create( topic_name=topic, ontology_type=topic_to_ontology[topic] ) # Data Transformation & Ingestion. # The adapter converts the raw payload into a validated Mosaico object. # push() handles high-performance batching and asynchronous I/O to the rust backend. twriter.push( # (1)! message=Message( timestamp_ns=ts, data=adapter[topic](payload), ) ) # SequenceWriter automatically calls _finalize() on all internal TopicWriters, # guaranteeing that every sensor measurement is safely committed to the platform. ``` 1. See also: `TopicWriter.push()` ### topic\_create ¶ ``` topic_create( topic_name, metadata, ontology_type, on_error=Raise ) ``` Creates a new topic within the active sequence. This method performs a "Multi-Lane" resource assignment, granting the new `TopicWriter`, its own connection from the pool and a dedicated executor for background serialization and I/O. 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. | Example ``` with MosaicoClient.connect("localhost", 6726) as client: # Start the Sequence Orchestrator with client.sequence_create(...) as seq_writer: # (1)! # Create individual Topic Writers # Each writer gets its own assigned resources from the pools 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", }, 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": { # (2)! "type": "UART", "baudrate": 115200, "protocol": "NMEA", }, }, # The topic/sensor custom metadata ontology_type=GPS, # The ontology type stored in this topic ) # Push data imu_writer.push( # (3)! message=Message( timestamp_ns=1700000000000, data=IMU(acceleration=Vector3d(x=0, y=0, z=9.81), ...), ) ) # ... # Exiting the block automatically flushes all topic buffers, finalizes the sequence on the server # and closes all connections and pools ``` 1. See also: `MosaicoClient.sequence_create()` 2. The metadata fields will be queryable via the `Query` mechanism. The mechanism allows creating query expressions like: `QueryTopic().with_user_metadata("interface.type", eq="UART")`. See also: * `mosaicolabs.models.platform.Topic` * `mosaicolabs.models.query.builders.QueryTopic`. 3. See also: `TopicWriter.push()` ## 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. ##### Performance & Parallelism¶ If an executor pool is provided by the parent client, the `TopicWriter` performs data serialization on background threads, preventing I/O operations from blocking the main application logic. Obtaining a Writer End-users should not instantiate this class directly. Use the `SequenceWriter.topic_create()` factory method to obtain an active writer. 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. Example ``` with MosaicoClient.connect("localhost", 6726) as client: # Start the Sequence Orchestrator with client.sequence_create(...) as seq_writer: # (1)! # Create individual Topic Writers # Each writer gets its own assigned resources from the pools imu_writer = seq_writer.topic_create( # (2)! 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", }, ontology_type=IMU, # The ontology type stored in this topic ) # Push data... imu_writer.push( # (3)! message=Message( data=IMU(acceleration=Vector3d(x=0, y=0, z=9.81), ...), timestamp_ns=1700000000000, ) ) # Exiting the seq_writer `with` block, the `_finalize()` method of all topic writers is called. ``` 1. See also: `MosaicoClient.sequence_create()` 2. See also: `SequenceWriter.topic_create()` 3. See also: `TopicWriter.push()` 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 Example ``` with twriter: # (1)! mosaico_msg = custom_translator(twriter.name, raw_data) # Example helper function twriter.push(message=mosaico_msg) # Inspect failed processing/ingestion if twriter.status == TopicWriterStatus.IgnoredLastError # (2)! print(f"Error raised during last ingestion operation for topic {twriter.name}. Inner err: '{twriter.last_error}'") ``` 1. `twriter` is a `TopicWriter` instance, created with `on_error=TopicLevelErrorPolicy.Ignore` 2. **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. | Example ``` with MosaicoClient.connect("localhost", 6726) as client: # Start the Sequence Orchestrator with client.sequence_create(...) as seq_writer: # (1)! # Create individual Topic Writers # Each writer gets its own assigned resources from the pools imu_writer = seq_writer.topic_create( # (2)! 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", }, 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": { "type": "UART", "baudrate": 115200, "protocol": "NMEA", }, }, # The topic/sensor custom metadata ontology_type=GPS, # The ontology type stored in this topic ) gps_msg = Message(timestamp_ns=1700000000100, data=GPS(...)) gps_writer.push(message=gps_msg) # Exiting the seq_writer `with` block, the `_finalize()` method of all topic writers is called. ``` 1. See also: `MosaicoClient.sequence_create()` 2. See also: `SequenceWriter.topic_create()` ## mosaicolabs.handlers.SequenceUpdater ¶ ``` SequenceUpdater( *, sequence_name, client, connection_pool, executor_pool, 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. ##### Key Responsibilities¶ * **Lifecycle Management**: Coordinates new session creation, finalization, or abort signals with the server. * **Resource Distribution**: Implements a "Multi-Lane" architecture by distributing network connections from a Connection Pool and thread executors from an Executor Pool to individual `TopicWriter` instances. This ensures strict isolation and maximum parallelism between diverse data streams. Usage Pattern This class **must** be used within a `with` statement (Context Manager). The context entry triggers sequence registration on the server, while the exit handles automatic finalization or error cleanup based on the configured `SessionLevelErrorPolicy`. Obtaining a Writer Do not instantiate this class directly. Use the `SequenceHandler.update()` factory method. Internal constructor for SequenceUpdater. **Do not call this directly.** Users must call `SequenceHandler.update()` to obtain an initialized writer. Example ``` 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( # (1)! on_error = SessionLevelErrorPolicy.Delete ) as seq_updater: # Start creating topics and pushing data # (2)! # Exiting the block automatically flushes all topic buffers, finalizes the sequence on the server # and closes all connections and pools ``` 1. See also: `SequenceHandler.update()` 2. See also: * `SequenceUpdater.topic_create()` * `TopicWriter.push()` Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `sequence_name` | `str` | Unique name for the new sequence. | *required* | | `client` | `FlightClient` | The primary control FlightClient. | *required* | | `connection_pool` | `Optional[_ConnectionPool]` | Shared pool of data connections for parallel writing. | *required* | | `executor_pool` | `Optional[_ExecutorPool]` | Shared pool of thread executors for asynchronous I/O. | *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\_uuid `property` ¶ ``` session_uuid ``` Returns the UUID of the session corresponding to this sequence write or update. Returns: | Type | Description | | --- | --- | | `str` | The UUID 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`. | Example Processing a generic interleaved sensor log (like a ROS bag or a custom JSON log): ``` from mosaicolabs import SequenceWriter, IMU, Image # Topic to Ontology Mapping: Defines the schema for each sensor stream # Example: {"/camera": Image, "/imu": IMU} topic_to_ontology = { ... } # Adapter Factory: Maps raw sensor payloads to Mosaico Ontology instances # Example: {"/imu": lambda p: IMU(acceleration=Vector3d.from_list(p['acc']), ...)} adapter = { ... } with client.sequence_create("physical_ai_trial_01") as seq_writer: # log_iterator represents an interleaved stream (e.g., ROSbags, MCAP, or custom logs). for ts, topic, payload in log_iterator: # Access the topic-specific buffer. # get_topic_writer retrieves a persistent writer from the internal cache twriter = seq_writer.get_topic_writer(topic) if twriter is None: # Dynamic Topic Registration. # If the topic is encountered for the first time, register it using the # pre-defined Ontology type to ensure data integrity. twriter = seq_writer.topic_create( topic_name=topic, ontology_type=topic_to_ontology[topic] ) # Data Transformation & Ingestion. # The adapter converts the raw payload into a validated Mosaico object. # push() handles high-performance batching and asynchronous I/O to the rust backend. twriter.push( # (1)! message=Message( timestamp_ns=ts, data=adapter[topic](payload), ) ) # SequenceWriter automatically calls _finalize() on all internal TopicWriters, # guaranteeing that every sensor measurement is safely committed to the platform. ``` 1. See also: `TopicWriter.push()` ### topic\_create ¶ ``` topic_create( topic_name, metadata, ontology_type, on_error=Raise ) ``` Creates a new topic within the active sequence. This method performs a "Multi-Lane" resource assignment, granting the new `TopicWriter`, its own connection from the pool and a dedicated executor for background serialization and I/O. 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. | Example ``` with MosaicoClient.connect("localhost", 6726) as client: # Start the Sequence Orchestrator with client.sequence_create(...) as seq_writer: # (1)! # Create individual Topic Writers # Each writer gets its own assigned resources from the pools 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", }, 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": { # (2)! "type": "UART", "baudrate": 115200, "protocol": "NMEA", }, }, # The topic/sensor custom metadata ontology_type=GPS, # The ontology type stored in this topic ) # Push data imu_writer.push( # (3)! message=Message( timestamp_ns=1700000000000, data=IMU(acceleration=Vector3d(x=0, y=0, z=9.81), ...), ) ) # ... # Exiting the block automatically flushes all topic buffers, finalizes the sequence on the server # and closes all connections and pools ``` 1. See also: `MosaicoClient.sequence_create()` 2. The metadata fields will be queryable via the `Query` mechanism. The mechanism allows creating query expressions like: `QueryTopic().with_user_metadata("interface.type", eq="UART")`. See also: * `mosaicolabs.models.platform.Topic` * `mosaicolabs.models.query.builders.QueryTopic`. 3. See also: `TopicWriter.push()` --- ## 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `.Q.recording_timestamp_ns` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `.Q.frame_id` | `String` | `.eq()`, `.neq()`, `.match()`, `.in_()` | | `.Q.sequence_id` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico ontology class (e.g., `IMU`, `GPS`, `Floating64`) or any custom user-defined class that is a subclass of `Serializable`. Example ``` from mosaicolabs import MosaicoClient, IMU, Floating64, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter IMU data by a specific acquisition second qresponse = client.query( QueryOntologyCatalog(IMU.Q.timestamp_ns.lt(1770282868)) ) # 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 primitive Floating64 telemetry by frame identifier qresponse = client.query( QueryOntologyCatalog(Floating64.Q.frame_id.eq("robot_base")) ) # 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]}") ``` ### 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()`, `.neq()`, `.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`. Example ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter IMU data by a specific acquisition second qresponse = client.query( QueryOntologyCatalog(IMU.Q.timestamp_ns.lt(1770282868)) ) # 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]}") ``` ### 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()`, `.neq()`, `.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` Example ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter IMU data by a specific recording second qresponse = client.query( QueryOntologyCatalog(IMU.Q.recording_timestamp_ns.lt(1770282868)) ) # 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]}") ``` ### 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()`, `.neq()`, `.in_()`, `.match()` | The `` placeholder represents any Mosaico ontology class (e.g., `IMU`, `GPS`, `Floating64`) or any custom user-defined class that is a subclass of `Serializable` Example ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter IMU data by a specific frame_id qresponse = client.query( QueryOntologyCatalog(IMU.Q.frame_id.eq("base_link")) ) # 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]}") ``` ### 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()`, `.neq()`, `.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` Example ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter IMU data by a specific sequence_id qresponse = client.query( QueryOntologyCatalog(IMU.Q.sequence_id.eq(123)) ) # 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]}") ``` ### 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`. | Example ``` # Get the IMU data from the message image_data = message.get_data(Image) print(f"Timestamp: {message.timestamp_ns}") print(f"Image size: {image_data.height}x{image_data.width}") # Show the image image_data.to_pillow().show() # Get the Floating64 data from the message floating64_data = message.get_data(Floating64) print(f"Timestamp: {message.timestamp_ns}") print(f"Data value: {floating64_data.data}") ``` ### 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: 1. **Topic Validation**: Verifying if any columns associated with the `topic_name` exist in the row. 2. **Tag Inference**: Inspecting the column headers to automatically determine the original ontology tag (e.g., `"imu"`). 3. **Data Extraction**: Stripping prefixes and re-nesting the flat columns into their original dictionary structures. 4. **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. | Example ``` # Obtain a dataframe with DataFrameExtractor from mosaicolabs import MosaicoClient, IMU, Image from mosaicolabs.ml import DataFrameExtractor, SyncTransformer with MosaicoClient.connect("localhost", 6726) as client: sequence_handler = client.get_sequence_handler("example_sequence") for df in DataFrameExtractor(sequence_handler).to_pandas_chunks( topics = ["/front/imu", "/front/camera/image_raw"] ): # Do something with the dataframe. # For example, you can sync the data using the `SyncTransformer`: sync_transformer = SyncTransformer( target_fps = 30, # resample at 30 Hz and fill the Nans with a Hold policy ) synced_df = sync_transformer.transform(df) # Reconstruct the image message from a dataframe row image_msg = Message.from_dataframe_row(synced_df, "/front/camera/image_raw") image_data = image_msg.get_data(Image) # Show the image image_data.to_pillow().show() # ... ``` ## 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: 1. Inherit from `Serializable`. 2. Define a `__msco_pyarrow_struct__` attribute using `pa.StructType` to specify the physical schema. 3. Define the class fields (using Pydantic syntax) matching the Arrow structure. Automatic Registration Any subclass of `Serializable` is automatically registered in the global Mosaico registry upon definition. This enables the use of the factory methods and the `.Q` query proxy immediately. ### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ## 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: 1. It inspects the child class's existing `__msco_pyarrow_struct__`. 2. It appends a `covariance` and `covariance_type` fields. 3. It reconstructs the final `pa.struct` for the class. Collision Safety The mixin performs a collision check during class definition. If the child class already defines a `covariance` or `covariance_type` field in its PyArrow struct, a `ValueError` will be raised to prevent schema corruption. Attributes: | Name | Type | Description | | --- | --- | --- | | `covariance` | `Optional[List[float]]` | Optional list of 64-bit floats representing the flattened matrix. | | `covariance_type` | `Optional[int]` | 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `.Q.covariance` | ***Non-Queryable*** | None | Universal Compatibility 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`. Example ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter IMU data by a specific acquisition second # `FROM_CALIBRATED_PROCEDURE` is some enum value defined by the user qresponse = client.query( QueryOntologyCatalog(IMU.Q.acceleration.covariance_type.eq(FROM_CALIBRATED_PROCEDURE)) ) # 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]}") ``` ### covariance `class-attribute` `instance-attribute` ¶ ``` covariance = None ``` Optional list of 64-bit floats representing the flattened matrix. ###### Querying with the **`.Q` Proxy**¶ Non-Queryable The field is not queryable with the **`.Q` Proxy**. ### covariance\_type `class-attribute` `instance-attribute` ¶ ``` covariance_type = None ``` 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()`, `.neq()`, `.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`. Filtering by Calibration Type This example demonstrates searching for data segments where the acceleration was derived from a specific calibrated procedure. ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog # Assume FROM_CALIBRATED_PROCEDURE is a user-defined integer constant with MosaicoClient.connect("localhost", 6726) as client: # Target the covariance_type nested within the acceleration field qbuilder = QueryOntologyCatalog( IMU.Q.acceleration.covariance_type.eq(FROM_CALIBRATED_PROCEDURE) ) results = client.query(qbuilder) if results: for item in results: print(f"Sequence: {item.sequence.name}") print(f"Matching Topics: {[topic.name for topic in item.topics]}") ``` ## 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: 1. It inspects the child class's existing `__msco_pyarrow_struct__`. 2. It appends a `variance` and `variance_type` field. 3. It reconstructs the final `pa.struct` for the class. Collision Safety The mixin performs a collision check during class definition. If the child class already defines a `variance` or `variance_type` field in its PyArrow struct, a `ValueError` will be raised to prevent schema corruption. ##### 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `.Q.variance_type` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility 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. Example ``` from mosaicolabs import MosaicoClient, Pressure, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter Pressure data by a specific variance value qresponse = client.query( QueryOntologyCatalog(Pressure.Q.variance.lt(0.76)) ) # 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 Pressure data by a specific variance type # `FROM_CALIBRATED_PROCEDURE` is some enum value defined by the user qresponse = client.query( QueryOntologyCatalog(Pressure.Q.variance_type.eq(FROM_CALIBRATED_PROCEDURE)) ) # 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]}") ``` ### variance `class-attribute` `instance-attribute` ¶ ``` variance = None ``` 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()`, `.neq()`, `.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. Example ``` from mosaicolabs import MosaicoClient, Pressure, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter Pressure data by a specific acquisition second qresponse = client.query( QueryOntologyCatalog(Pressure.Q.variance.lt(0.76)) ) # 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]}") ``` ### variance\_type `class-attribute` `instance-attribute` ¶ ``` variance_type = None ``` 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()`, `.neq()`, `.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. Filtering by Precision The following examples demonstrate how to filter sensor data based on the magnitude of the variance or the specific procedure used to calculate it. ``` from mosaicolabs import MosaicoClient, Pressure, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter by variance threshold results = client.query(QueryOntologyCatalog( Pressure.Q.variance.lt(0.76) )) if results: for item in results: print(f"Sequence: {item.sequence.name}") print(f"Topics: {[topic.name for topic in item.topics]}") ``` ## 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. Note This class has been added mainly for wrapping pydantic, toward future implementation where other fields mapping and checks are implemented --- ## 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` | `int` | 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. Example ``` from mosaicolabs import MosaicoClient, Integer8, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Integer8.Q.data.gt(123))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Integer8.Q.data.gt(123), include_timestamp_range=True) ) # 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}}") ``` #### data `instance-attribute` ¶ ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Integer8, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Integer8.Q.data.gt(-10))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Integer8.Q.data.gt(123), include_timestamp_range=True) ) # 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}}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### Integer16 ¶ Bases: `Serializable` A wrapper for a signed 16-bit integer. Attributes: | Name | Type | Description | | --- | --- | --- | | `data` | `int` | 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. Example ``` from mosaicolabs import MosaicoClient, Integer16, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Integer16.Q.data.gt(123))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Integer16.Q.data.gt(123), include_timestamp_range=True) ) # 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}}") ``` #### data `instance-attribute` ¶ ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Integer16, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Integer16.Q.data.gt(-10))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Integer16.Q.data.gt(123), include_timestamp_range=True) ) # 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}}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### Integer32 ¶ Bases: `Serializable` A wrapper for a signed 32-bit integer. Attributes: | Name | Type | Description | | --- | --- | --- | | `data` | `int` | 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. Example ``` from mosaicolabs import MosaicoClient, Integer32, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Integer32.Q.data.gt(123))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Integer32.Q.data.gt(123), include_timestamp_range=True) ) # 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}}") ``` #### data `instance-attribute` ¶ ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Integer32, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Integer32.Q.data.gt(-10))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Integer32.Q.data.gt(123), include_timestamp_range=True) ) # 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}}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### Integer64 ¶ Bases: `Serializable` A wrapper for a signed 64-bit integer. Attributes: | Name | Type | Description | | --- | --- | --- | | `data` | `int` | 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. Example ``` from mosaicolabs import MosaicoClient, Integer64, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Integer64.Q.data.gt(123))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Integer64.Q.data.gt(123), include_timestamp_range=True) ) # 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}}") ``` #### data `instance-attribute` ¶ ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Integer64, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Integer64.Q.data.gt(123))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Integer64.Q.data.gt(123), include_timestamp_range=True) ) # 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}}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### Unsigned8 ¶ Bases: `Serializable` A wrapper for an unsigned 8-bit integer. Attributes: | Name | Type | Description | | --- | --- | --- | | `data` | `int` | 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. Example ``` from mosaicolabs import MosaicoClient, Unsigned8, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Unsigned8.Q.data.gt(123))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Unsigned8.Q.data.gt(123), include_timestamp_range=True) ) # 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}}") ``` #### data `instance-attribute` ¶ ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Unsigned8, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Unsigned8.Q.data.leq(253))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Unsigned8.Q.data.gt(123), include_timestamp_range=True) ) # 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}}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### Unsigned16 ¶ Bases: `Serializable` A wrapper for an unsigned 16-bit integer. Attributes: | Name | Type | Description | | --- | --- | --- | | `data` | `int` | 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. Example ``` from mosaicolabs import MosaicoClient, Unsigned16, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Unsigned16.Q.data.gt(123))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Unsigned16.Q.data.gt(123), include_timestamp_range=True) ) # 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}}") ``` #### data `instance-attribute` ¶ ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Unsigned16, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Unsigned16.Q.data.eq(2))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Unsigned16.Q.data.gt(123), include_timestamp_range=True) ) # 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}}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### Unsigned32 ¶ Bases: `Serializable` A wrapper for an unsigned 32-bit integer. Attributes: | Name | Type | Description | | --- | --- | --- | | `data` | `int` | 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. Example ``` from mosaicolabs import MosaicoClient, Unsigned32, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Unsigned32.Q.data.gt(123))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Unsigned32.Q.data.gt(123), include_timestamp_range=True) ) # 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}}") ``` #### data `instance-attribute` ¶ ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Unsigned32, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Unsigned32.Q.data.gt(123))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Unsigned32.Q.data.gt(123), include_timestamp_range=True) ) # 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}}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### Unsigned64 ¶ Bases: `Serializable` A wrapper for an unsigned 64-bit integer. Attributes: | Name | Type | Description | | --- | --- | --- | | `data` | `int` | 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. Example ``` from mosaicolabs import MosaicoClient, Unsigned64, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Unsigned64.Q.data.gt(123))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Unsigned64.Q.data.gt(123), include_timestamp_range=True) ) # 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}}") ``` #### data `instance-attribute` ¶ ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Unsigned64, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Unsigned64.Q.data.gt(123))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Unsigned64.Q.data.gt(123), include_timestamp_range=True) ) # 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}}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### Floating16 ¶ Bases: `Serializable` A wrapper for a 16-bit single-precision floating-point number. Attributes: | Name | Type | Description | | --- | --- | --- | | `data` | `float` | 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. Example ``` from mosaicolabs import MosaicoClient, Floating16, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Floating16.Q.data.gt(123.45))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Floating16.Q.data.gt(123.45), include_timestamp_range=True) ) # 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}}") ``` #### data `instance-attribute` ¶ ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Floating16, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Floating16.Q.data.leq(123.4))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Floating16.Q.data.gt(123.45), include_timestamp_range=True) ) # 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}}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### Floating32 ¶ Bases: `Serializable` A wrapper for a 32-bit single-precision floating-point number. Attributes: | Name | Type | Description | | --- | --- | --- | | `data` | `float` | 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. Example ``` from mosaicolabs import MosaicoClient, Floating32, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Floating32.Q.data.gt(123.45))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Floating32.Q.data.gt(123.45), include_timestamp_range=True) ) # 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}}") ``` #### data `instance-attribute` ¶ ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Floating32, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Floating32.Q.data.leq(123.4))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Floating32.Q.data.gt(123.45), include_timestamp_range=True) ) # 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}}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### Floating64 ¶ Bases: `Serializable` A wrapper for a 64-bit single-precision floating-point number. Attributes: | Name | Type | Description | | --- | --- | --- | | `data` | `float` | 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. Example ``` from mosaicolabs import MosaicoClient, Floating64, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Floating64.Q.data.gt(123.45))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Floating64.Q.data.gt(123.45), include_timestamp_range=True) ) # 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}}") ``` #### data `instance-attribute` ¶ ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Floating64, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Floating64.Q.data.leq(123.4))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Floating64.Q.data.gt(123.45), include_timestamp_range=True) ) # 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}}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### 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. Example ``` from mosaicolabs import MosaicoClient, Boolean, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Boolean.Q.data.eq(True))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Boolean.Q.data.eq(True), include_timestamp_range=True) ) # 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}}") ``` #### data `instance-attribute` ¶ ``` 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()` | Example ``` from mosaicolabs import MosaicoClient, Boolean, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(Boolean.Q.data.eq(True))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Boolean.Q.data.eq(True), include_timestamp_range=True) ) # 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}}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### String ¶ Bases: `Serializable` A wrapper for a standard UTF-8 encoded string. Attributes: | Name | Type | Description | | --- | --- | --- | | `data` | `str` | 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. Example ``` from mosaicolabs import MosaicoClient, String, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(String.Q.data.eq("hello"))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(String.Q.data.eq("hello"), include_timestamp_range=True) ) # 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}}") ``` #### data `instance-attribute` ¶ ``` 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()`, `.neq()`, `.match()`, `.in_()` | Example ``` from mosaicolabs import MosaicoClient, String, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for strings containing a specific log pattern qresponse = client.query(QueryOntologyCatalog(String.Q.data.match("[ERR]"))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(String.Q.data.eq("hello"), include_timestamp_range=True) ) # 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}}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### 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` | `str` | 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. Example ``` from mosaicolabs import MosaicoClient, LargeString, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value qresponse = client.query(QueryOntologyCatalog(LargeString.Q.data.eq("hello"))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(LargeString.Q.data.eq("hello"), include_timestamp_range=True) ) # 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}}") ``` #### data `instance-attribute` ¶ ``` 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()`, `.neq()`, `.match()`, `.in_()` | Example ``` from mosaicolabs import MosaicoClient, LargeString, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for large strings containing a specific log pattern qresponse = client.query(QueryOntologyCatalog(LargeString.Q.data.match("CRITICAL_ERR_"))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(LargeString.Q.data.eq("hello"), include_timestamp_range=True) ) # 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}}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ## 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` | `int` | The vertical extent of the ROI in pixels. | | `width` | `int` | 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. Example ``` from mosaicolabs import MosaicoClient, ROI, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter ROIs with offset X-component AND offset Y-component qresponse = client.query( QueryOntologyCatalog(ROI.Q.offset.x.gt(5.0)) .with_expression(ROI.Q.offset.y.lt(10)) ) # 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(ROI.Q.offset.x.gt(5.0), include_timestamp_range=True) .with_expression(ROI.Q.offset.y.lt(10)) ) # 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}}") ``` ### offset `instance-attribute` ¶ ``` offset ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `ROI.Q.offset.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, ROI, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for ROIs starting between the 10th and 350th pixel vertically qresponse = client.query( QueryOntologyCatalog(ROI.Q.offset.x.gt(100)) .with_expression(ROI.Q.offset.y.between(10, 350)) ) # 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(ROI.Q.offset.x.gt(100), include_timestamp_range=True) .with_expression(ROI.Q.offset.y.between(10, 350)) ) # 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}}") ``` ### height `instance-attribute` ¶ ``` height ``` Height of the ROI in pixels. ###### Querying with the **`.Q` Proxy**¶ | Field Access Path | Queryable Type | Supported Operators | | --- | --- | --- | | `ROI.Q.height` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, ROI, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for ROIs with height beyond 100 pixels qresponse = client.query( QueryOntologyCatalog(ROI.Q.height.gt(100)) ) # 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(ROI.Q.height.gt(100), include_timestamp_range=True) ) # 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}}") ``` ### width `instance-attribute` ¶ ``` width ``` Width of the ROI in pixels. ###### Querying with the **`.Q` Proxy**¶ | Field Access Path | Queryable Type | Supported Operators | | --- | --- | --- | | `ROI.Q.width` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, ROI, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for ROIs with width below (or equal to) 250 pixels qresponse = client.query( QueryOntologyCatalog(ROI.Q.width.leq(250)) ) # 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(ROI.Q.width.gt(100), include_timestamp_range=True) ) # 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}}") ``` ### do\_rectify `class-attribute` `instance-attribute` ¶ ``` do_rectify = None ``` 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()` | Example ``` from mosaicolabs import MosaicoClient, ROI, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for explicitly non-rectified ROIs (not None) qresponse = client.query( QueryOntologyCatalog(ROI.Q.do_rectify.eq(False)) ) # 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]}") ``` ### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` --- ## 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` | `float` | Vector X component. | | `y` | `float` | Vector Y component. | | `covariance` | `Optional[List[float]]` | Optional flattened 2x2 covariance matrix representing the uncertainty of the vector measurement. | | `covariance_type` | `Optional[int]` | 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. Example ``` from mosaicolabs import MosaicoClient, Vector2d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query( QueryOntologyCatalog(Vector2d.Q.y.leq(123.4)) .with_expression(Vector2d.Q.timestamp_ns.between([1770282868, 1770290127])) ) # 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(Vector2d.Q.y.leq(123.4), include_timestamp_range=True) ) # 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}}") ``` #### covariance `class-attribute` `instance-attribute` ¶ ``` covariance = None ``` Optional list of 64-bit floats representing the flattened matrix. ###### Querying with the **`.Q` Proxy**¶ Non-Queryable The field is not queryable with the **`.Q` Proxy**. #### covariance\_type `class-attribute` `instance-attribute` ¶ ``` covariance_type = None ``` 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()`, `.neq()`, `.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`. Filtering by Calibration Type This example demonstrates searching for data segments where the acceleration was derived from a specific calibrated procedure. ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog # Assume FROM_CALIBRATED_PROCEDURE is a user-defined integer constant with MosaicoClient.connect("localhost", 6726) as client: # Target the covariance_type nested within the acceleration field qbuilder = QueryOntologyCatalog( IMU.Q.acceleration.covariance_type.eq(FROM_CALIBRATED_PROCEDURE) ) results = client.query(qbuilder) if results: for item in results: print(f"Sequence: {item.sequence.name}") print(f"Matching Topics: {[topic.name for topic in item.topics]}") ``` #### x `instance-attribute` ¶ ``` x ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector2dStruct` (i.e. `Vector2d`, `Point2d`) or any custom user-defined class that is a subclass of `Serializable` and derives from `_Vector2dStruct` or its child classes. Example ``` from mosaicolabs import MosaicoClient, Vector2d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector2d.Q.x.leq(123.4))) # 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(Vector2d.Q.x.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Point2d.Q.x.leq(123.4))) # 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]}") ``` #### y `instance-attribute` ¶ ``` y ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector2dStruct` (i.e. `Vector2d`, `Point2d`) or any custom user-defined class that inherits from `Serializable` and derives from `_Vector2dStruct` or its child classes. Example ``` from mosaicolabs import MosaicoClient, Vector2d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector2d.Q.y.leq(123.4))) # 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(Vector2d.Q.y.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Point2d.Q.y.leq(123.4))) # 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]}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` #### 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` | `float` | Vector X component. | | `y` | `float` | Vector Y component. | | `z` | `float` | Vector Z component. | | `covariance` | `Optional[List[float]]` | Optional flattened 3x3 covariance matrix representing the uncertainty of the vector measurement. | | `covariance_type` | `Optional[int]` | 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. Example ``` from mosaicolabs import MosaicoClient, Vector3d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query( QueryOntologyCatalog(Vector3d.Q.y.leq(123.4)) .with_expression(Vector3d.Q.timestamp_ns.between([1770282868, 1770290127])) ) # 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(Vector3d.Q.z.leq(123.4), include_timestamp_range=True) ) # 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}}") ``` #### covariance `class-attribute` `instance-attribute` ¶ ``` covariance = None ``` Optional list of 64-bit floats representing the flattened matrix. ###### Querying with the **`.Q` Proxy**¶ Non-Queryable The field is not queryable with the **`.Q` Proxy**. #### covariance\_type `class-attribute` `instance-attribute` ¶ ``` covariance_type = None ``` 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()`, `.neq()`, `.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`. Filtering by Calibration Type This example demonstrates searching for data segments where the acceleration was derived from a specific calibrated procedure. ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog # Assume FROM_CALIBRATED_PROCEDURE is a user-defined integer constant with MosaicoClient.connect("localhost", 6726) as client: # Target the covariance_type nested within the acceleration field qbuilder = QueryOntologyCatalog( IMU.Q.acceleration.covariance_type.eq(FROM_CALIBRATED_PROCEDURE) ) results = client.query(qbuilder) if results: for item in results: print(f"Sequence: {item.sequence.name}") print(f"Matching Topics: {[topic.name for topic in item.topics]}") ``` #### x `instance-attribute` ¶ ``` x ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector3dStruct` (i.e. `Vector3d`, `Point3d`) or any custom user-defined class that inherits from `Serializable` and derives from `_Vector3dStruct` or its child classes. Example ``` from mosaicolabs import MosaicoClient, Vector3d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector3d.Q.x.leq(123.4))) # 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(Vector3d.Q.x.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Point3d.Q.x.leq(123.4))) # 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]}") ``` #### y `instance-attribute` ¶ ``` y ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector3dStruct` (i.e. `Vector3d`, `Point3d`) or any custom user-defined class that inherits from `Serializable` and derives from `_Vector3dStruct` or its child classes. Example ``` from mosaicolabs import MosaicoClient, Vector3d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector3d.Q.y.leq(123.4))) # 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(Vector3d.Q.y.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Point3d.Q.y.leq(123.4))) # 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]}") ``` #### z `instance-attribute` ¶ ``` z ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector3dStruct` (i.e. `Vector3d`, `Point3d`) or any custom user-defined `Serializable` class. Example ``` from mosaicolabs import MosaicoClient, Vector3d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector3d.Q.z.leq(123.4))) # 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(Vector3d.Q.z.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Point3d.Q.z.leq(123.4))) # 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]}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` #### 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` | `float` | Vector X component. | | `y` | `float` | Vector Y component. | | `z` | `float` | Vector Z component. | | `w` | `float` | Vector W component. | | `covariance` | `Optional[List[float]]` | Optional flattened 4x4 covariance matrix representing the uncertainty of the vector measurement. | | `covariance_type` | `Optional[int]` | 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. Example ``` from mosaicolabs import MosaicoClient, Vector4d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query( QueryOntologyCatalog(Vector4d.Q.y.leq(123.4)) .with_expression(Vector4d.Q.timestamp_ns.between([1770282868, 1770290127])) ) # 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(Vector4d.Q.y.leq(123.4), include_timestamp_range=True) ) # 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}}") ``` #### covariance `class-attribute` `instance-attribute` ¶ ``` covariance = None ``` Optional list of 64-bit floats representing the flattened matrix. ###### Querying with the **`.Q` Proxy**¶ Non-Queryable The field is not queryable with the **`.Q` Proxy**. #### covariance\_type `class-attribute` `instance-attribute` ¶ ``` covariance_type = None ``` 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()`, `.neq()`, `.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`. Filtering by Calibration Type This example demonstrates searching for data segments where the acceleration was derived from a specific calibrated procedure. ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog # Assume FROM_CALIBRATED_PROCEDURE is a user-defined integer constant with MosaicoClient.connect("localhost", 6726) as client: # Target the covariance_type nested within the acceleration field qbuilder = QueryOntologyCatalog( IMU.Q.acceleration.covariance_type.eq(FROM_CALIBRATED_PROCEDURE) ) results = client.query(qbuilder) if results: for item in results: print(f"Sequence: {item.sequence.name}") print(f"Matching Topics: {[topic.name for topic in item.topics]}") ``` #### x `instance-attribute` ¶ ``` x ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector4dStruct` (i.e. `Vector4d`, `Quaternion`) or any custom user-defined class that inherits from `Serializable` and derives from `_Vector4dStruct` or its child classes. Example ``` from mosaicolabs import MosaicoClient, Vector4d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector4d.Q.x.leq(123.4))) # 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(Vector4d.Q.x.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Quaternion.Q.x.leq(0.4))) # 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]}") ``` #### y `instance-attribute` ¶ ``` y ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector4dStruct` (i.e. `Vector4d`, `Quaternion`) or any custom user-defined class that inherits from `Serializable` and derives from `_Vector4dStruct` or its child classes. Example ``` from mosaicolabs import MosaicoClient, Vector4d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector4d.Q.y.leq(123.4))) # 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(Vector4d.Q.y.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Quaternion.Q.y.leq(0.4))) # 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]}") ``` #### z `instance-attribute` ¶ ``` z ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector4dStruct` (i.e. `Vector4d`, `Quaternion`) or any custom user-defined class that inherits from `Serializable` and derives from `_Vector4dStruct` or its child classes. Example ``` from mosaicolabs import MosaicoClient, Vector4d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector4d.Q.z.leq(123.4))) # 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(Vector4d.Q.z.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Quaternion.Q.z.leq(0.4))) # 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]}") ``` #### w `instance-attribute` ¶ ``` w ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector4dStruct` (i.e. `Vector4d`, `Quaternion`) or any custom user-defined class that inherits from `Serializable` and derives from `_Vector4dStruct` or its child classes. Example ``` from mosaicolabs import MosaicoClient, Vector4d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector4d.Q.w.leq(123.4))) # 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(Vector4d.Q.w.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Quaternion.Q.w.leq(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 for topic in item.topics]}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` #### 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` | `float` | Point X coordinate. | | `y` | `float` | Point Y coordinate. | | `covariance` | `Optional[List[float]]` | Optional flattened 2x2 covariance matrix representing the uncertainty of the point measurement. | | `covariance_type` | `Optional[int]` | 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. Example ``` from mosaicolabs import MosaicoClient, Point2d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query( QueryOntologyCatalog(Point2d.Q.y.leq(123.4)) .with_expression(Point2d.Q.timestamp_ns.between([1770282868, 1770290127])) ) # 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(Point2d.Q.y.leq(123.4), include_timestamp_range=True) ) # 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}}") ``` #### covariance `class-attribute` `instance-attribute` ¶ ``` covariance = None ``` Optional list of 64-bit floats representing the flattened matrix. ###### Querying with the **`.Q` Proxy**¶ Non-Queryable The field is not queryable with the **`.Q` Proxy**. #### covariance\_type `class-attribute` `instance-attribute` ¶ ``` covariance_type = None ``` 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()`, `.neq()`, `.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`. Filtering by Calibration Type This example demonstrates searching for data segments where the acceleration was derived from a specific calibrated procedure. ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog # Assume FROM_CALIBRATED_PROCEDURE is a user-defined integer constant with MosaicoClient.connect("localhost", 6726) as client: # Target the covariance_type nested within the acceleration field qbuilder = QueryOntologyCatalog( IMU.Q.acceleration.covariance_type.eq(FROM_CALIBRATED_PROCEDURE) ) results = client.query(qbuilder) if results: for item in results: print(f"Sequence: {item.sequence.name}") print(f"Matching Topics: {[topic.name for topic in item.topics]}") ``` #### x `instance-attribute` ¶ ``` x ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector2dStruct` (i.e. `Vector2d`, `Point2d`) or any custom user-defined class that is a subclass of `Serializable` and derives from `_Vector2dStruct` or its child classes. Example ``` from mosaicolabs import MosaicoClient, Vector2d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector2d.Q.x.leq(123.4))) # 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(Vector2d.Q.x.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Point2d.Q.x.leq(123.4))) # 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]}") ``` #### y `instance-attribute` ¶ ``` y ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector2dStruct` (i.e. `Vector2d`, `Point2d`) or any custom user-defined class that inherits from `Serializable` and derives from `_Vector2dStruct` or its child classes. Example ``` from mosaicolabs import MosaicoClient, Vector2d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector2d.Q.y.leq(123.4))) # 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(Vector2d.Q.y.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Point2d.Q.y.leq(123.4))) # 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]}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` #### 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` | `float` | Point X coordinate. | | `y` | `float` | Point Y coordinate. | | `z` | `float` | Point Z coordinate. | | `covariance` | `Optional[List[float]]` | Optional flattened 3x3 covariance matrix representing the uncertainty of the point measurement. | | `covariance_type` | `Optional[int]` | 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. Example ``` from mosaicolabs import MosaicoClient, Point3d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query( QueryOntologyCatalog(Point3d.Q.y.leq(123.4)) .with_expression(Point3d.Q.timestamp_ns.between([1770282868, 1770290127])) ) # 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(Point3d.Q.z.leq(123.4), include_timestamp_range=True) ) # 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}}") ``` #### covariance `class-attribute` `instance-attribute` ¶ ``` covariance = None ``` Optional list of 64-bit floats representing the flattened matrix. ###### Querying with the **`.Q` Proxy**¶ Non-Queryable The field is not queryable with the **`.Q` Proxy**. #### covariance\_type `class-attribute` `instance-attribute` ¶ ``` covariance_type = None ``` 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()`, `.neq()`, `.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`. Filtering by Calibration Type This example demonstrates searching for data segments where the acceleration was derived from a specific calibrated procedure. ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog # Assume FROM_CALIBRATED_PROCEDURE is a user-defined integer constant with MosaicoClient.connect("localhost", 6726) as client: # Target the covariance_type nested within the acceleration field qbuilder = QueryOntologyCatalog( IMU.Q.acceleration.covariance_type.eq(FROM_CALIBRATED_PROCEDURE) ) results = client.query(qbuilder) if results: for item in results: print(f"Sequence: {item.sequence.name}") print(f"Matching Topics: {[topic.name for topic in item.topics]}") ``` #### x `instance-attribute` ¶ ``` x ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector3dStruct` (i.e. `Vector3d`, `Point3d`) or any custom user-defined class that inherits from `Serializable` and derives from `_Vector3dStruct` or its child classes. Example ``` from mosaicolabs import MosaicoClient, Vector3d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector3d.Q.x.leq(123.4))) # 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(Vector3d.Q.x.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Point3d.Q.x.leq(123.4))) # 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]}") ``` #### y `instance-attribute` ¶ ``` y ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector3dStruct` (i.e. `Vector3d`, `Point3d`) or any custom user-defined class that inherits from `Serializable` and derives from `_Vector3dStruct` or its child classes. Example ``` from mosaicolabs import MosaicoClient, Vector3d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector3d.Q.y.leq(123.4))) # 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(Vector3d.Q.y.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Point3d.Q.y.leq(123.4))) # 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]}") ``` #### z `instance-attribute` ¶ ``` z ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector3dStruct` (i.e. `Vector3d`, `Point3d`) or any custom user-defined `Serializable` class. Example ``` from mosaicolabs import MosaicoClient, Vector3d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector3d.Q.z.leq(123.4))) # 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(Vector3d.Q.z.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Point3d.Q.z.leq(123.4))) # 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]}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` #### 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` | `float` | Vector X component. | | `y` | `float` | Vector Y component. | | `z` | `float` | Vector Z component. | | `w` | `float` | Vector W component. | | `covariance` | `Optional[List[float]]` | Optional flattened 4x4 covariance matrix representing the uncertainty of the quaternion measurement. | | `covariance_type` | `Optional[int]` | 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. Example ``` from mosaicolabs import MosaicoClient, Quaternion, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query( QueryOntologyCatalog(Quaternion.Q.w.leq(0.707)) .with_expression(Quaternion.Q.timestamp_ns.between([1770282868, 1770290127])) ) # 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(Quaternion.Q.w.leq(0.707), include_timestamp_range=True) ) # 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}}") ``` #### covariance `class-attribute` `instance-attribute` ¶ ``` covariance = None ``` Optional list of 64-bit floats representing the flattened matrix. ###### Querying with the **`.Q` Proxy**¶ Non-Queryable The field is not queryable with the **`.Q` Proxy**. #### covariance\_type `class-attribute` `instance-attribute` ¶ ``` covariance_type = None ``` 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()`, `.neq()`, `.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`. Filtering by Calibration Type This example demonstrates searching for data segments where the acceleration was derived from a specific calibrated procedure. ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog # Assume FROM_CALIBRATED_PROCEDURE is a user-defined integer constant with MosaicoClient.connect("localhost", 6726) as client: # Target the covariance_type nested within the acceleration field qbuilder = QueryOntologyCatalog( IMU.Q.acceleration.covariance_type.eq(FROM_CALIBRATED_PROCEDURE) ) results = client.query(qbuilder) if results: for item in results: print(f"Sequence: {item.sequence.name}") print(f"Matching Topics: {[topic.name for topic in item.topics]}") ``` #### x `instance-attribute` ¶ ``` x ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector4dStruct` (i.e. `Vector4d`, `Quaternion`) or any custom user-defined class that inherits from `Serializable` and derives from `_Vector4dStruct` or its child classes. Example ``` from mosaicolabs import MosaicoClient, Vector4d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector4d.Q.x.leq(123.4))) # 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(Vector4d.Q.x.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Quaternion.Q.x.leq(0.4))) # 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]}") ``` #### y `instance-attribute` ¶ ``` y ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector4dStruct` (i.e. `Vector4d`, `Quaternion`) or any custom user-defined class that inherits from `Serializable` and derives from `_Vector4dStruct` or its child classes. Example ``` from mosaicolabs import MosaicoClient, Vector4d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector4d.Q.y.leq(123.4))) # 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(Vector4d.Q.y.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Quaternion.Q.y.leq(0.4))) # 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]}") ``` #### z `instance-attribute` ¶ ``` z ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector4dStruct` (i.e. `Vector4d`, `Quaternion`) or any custom user-defined class that inherits from `Serializable` and derives from `_Vector4dStruct` or its child classes. Example ``` from mosaicolabs import MosaicoClient, Vector4d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector4d.Q.z.leq(123.4))) # 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(Vector4d.Q.z.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Quaternion.Q.z.leq(0.4))) # 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]}") ``` #### w `instance-attribute` ¶ ``` w ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Universal Compatibility The `` placeholder represents any Mosaico class derived by `_Vector4dStruct` (i.e. `Vector4d`, `Quaternion`) or any custom user-defined class that inherits from `Serializable` and derives from `_Vector4dStruct` or its child classes. Example ``` from mosaicolabs import MosaicoClient, Vector4d, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Vector4d.Q.w.leq(123.4))) # 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(Vector4d.Q.w.leq(123.4), include_timestamp_range=True) ) # 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}}") # Filter for a specific component value. qresponse = client.query(QueryOntologyCatalog(Quaternion.Q.w.leq(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 for topic in item.topics]}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` #### 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[str]` | The identifier of the destination coordinate frame. | | `covariance` | `Optional[List[float]]` | Optional flattened 7x7 composed covariance matrix representing the uncertainty of the Translation+Rotation. | | `covariance_type` | `Optional[int]` | 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. Example ``` from mosaicolabs import MosaicoClient, Transform, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific component value. qresponse = client.query( QueryOntologyCatalog(Transform.Q.translation.x.gt(5.0)) .with_expression(Transform.Q.rotation.w.lt(0.707)) .with_expression(Transform.Q.timestamp_ns.between([1770282868, 1770290127])) ) # 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(Transform.Q.translation.x.gt(5.0), include_timestamp_range=True) ) # 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}}") ``` #### translation `instance-attribute` ¶ ``` translation ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Transform.Q.translation.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Transform.Q.translation.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Transform, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Find transforms where the linear X-translation exceeds 5 meters qresponse = client.query( QueryOntologyCatalog(Transform.Q.translation.x.gt(5.0)) .with_expression(Transform.Q.translation.z.lt(150.3)) ) # 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(Transform.Q.translation.x.gt(5.0), include_timestamp_range=True) ) # 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}}") ``` #### rotation `instance-attribute` ¶ ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Transform.Q.rotation.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Transform.Q.rotation.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Transform.Q.rotation.w` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Transform, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for specific orientation states qresponse = client.query( QueryOntologyCatalog(Transform.Q.rotation.w.geq(0.707)) .with_expression(Transform.Q.rotation.z.lt(0.4)) ) # 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(Transform.Q.rotation.x.gt(5.0), include_timestamp_range=True) .with_expression(Transform.Q.rotation.z.lt(0.4)) ) # 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}}") ``` #### target\_frame\_id `class-attribute` `instance-attribute` ¶ ``` target_frame_id = None ``` Target coordinate frame identifier. | Field Access Path | Queryable Type | Supported Operators | | --- | --- | --- | | `Transform.Q.target_frame_id` | `String` | `.eq()`, `.neq()`, `.match()`, `.in_()` | Example ``` from mosaicolabs import MosaicoClient, Transform, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for specific target frame id qresponse = client.query( QueryOntologyCatalog(Transform.Q.target_frame_id.eq("camera_link")) ) # 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(Transform.Q.target_frame_id.eq("camera_link"), include_timestamp_range=True) ) # 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}}") ``` #### covariance `class-attribute` `instance-attribute` ¶ ``` covariance = None ``` Optional list of 64-bit floats representing the flattened matrix. ###### Querying with the **`.Q` Proxy**¶ Non-Queryable The field is not queryable with the **`.Q` Proxy**. #### covariance\_type `class-attribute` `instance-attribute` ¶ ``` covariance_type = None ``` 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()`, `.neq()`, `.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`. Filtering by Calibration Type This example demonstrates searching for data segments where the acceleration was derived from a specific calibrated procedure. ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog # Assume FROM_CALIBRATED_PROCEDURE is a user-defined integer constant with MosaicoClient.connect("localhost", 6726) as client: # Target the covariance_type nested within the acceleration field qbuilder = QueryOntologyCatalog( IMU.Q.acceleration.covariance_type.eq(FROM_CALIBRATED_PROCEDURE) ) results = client.query(qbuilder) if results: for item in results: print(f"Sequence: {item.sequence.name}") print(f"Matching Topics: {[topic.name for topic in item.topics]}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### 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[float]]` | Optional flattened 7x7 composed covariance matrix representing the uncertainty of the Translation+Rotation. | | `covariance_type` | `Optional[int]` | 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. Example ``` from mosaicolabs import MosaicoClient, Pose, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter Poses with position X-component AND orientation W-component qresponse = client.query( QueryOntologyCatalog(Pose.Q.position.x.gt(5.0)) .with_expression(Pose.Q.orientation.w.lt(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 for topic in item.topics]}") # Filter for a specific component value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(Pose.Q.position.x.gt(5.0), include_timestamp_range=True) .with_expression(Pose.Q.orientation.w.lt(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}}") ``` #### position `instance-attribute` ¶ ``` position ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Pose.Q.position.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Pose.Q.position.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Pose, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Find poses where the linear X-position exceeds 5 meters qresponse = client.query( QueryOntologyCatalog(Pose.Q.position.x.gt(123450.0)) ) # 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(Pose.Q.position.x.gt(5.0), include_timestamp_range=True) ) # 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}}") ``` #### orientation `instance-attribute` ¶ ``` orientation ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Pose.Q.orientation.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Pose.Q.orientation.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Pose.Q.orientation.w` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Pose, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for specific orientation states qresponse = client.query( QueryOntologyCatalog(Pose.Q.orientation.w.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 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(Pose.Q.orientation.w.geq(0.707)) .with_expression(Pose.Q.orientation.x.lt(0.1)) ) # 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}}") ``` #### covariance `class-attribute` `instance-attribute` ¶ ``` covariance = None ``` Optional list of 64-bit floats representing the flattened matrix. ###### Querying with the **`.Q` Proxy**¶ Non-Queryable The field is not queryable with the **`.Q` Proxy**. #### covariance\_type `class-attribute` `instance-attribute` ¶ ``` covariance_type = None ``` 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()`, `.neq()`, `.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`. Filtering by Calibration Type This example demonstrates searching for data segments where the acceleration was derived from a specific calibrated procedure. ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog # Assume FROM_CALIBRATED_PROCEDURE is a user-defined integer constant with MosaicoClient.connect("localhost", 6726) as client: # Target the covariance_type nested within the acceleration field qbuilder = QueryOntologyCatalog( IMU.Q.acceleration.covariance_type.eq(FROM_CALIBRATED_PROCEDURE) ) results = client.query(qbuilder) if results: for item in results: print(f"Sequence: {item.sequence.name}") print(f"Matching Topics: {[topic.name for topic in item.topics]}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ## 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[float]]` | Optional flattened 3x3 covariance matrix representing the uncertainty of the point measurement. | | `covariance_type` | `Optional[int]` | Enum integer representing the parameterization of the covariance matrix. | Input Validation A valid `Velocity` object must contain at least a `linear` or an `angular` component; providing neither will raise a `ValueError`. ###### 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. Example ``` from mosaicolabs import MosaicoClient, Velocity, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter Velocities with linear X-component AND angular Z-component qresponse = client.query( QueryOntologyCatalog(Velocity.Q.linear.x.gt(5.0)) .with_expression(Velocity.Q.angular.z.lt(10)) ) # 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(Velocity.Q.linear.x.gt(5.0), include_timestamp_range=True) .with_expression(Velocity.Q.angular.z.lt(10)) ) # 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}}") ``` #### linear `class-attribute` `instance-attribute` ¶ ``` linear = None ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Velocity.Q.linear.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Velocity.Q.linear.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Velocity, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Find velocities where the linear X component exceeds 25 m/s qresponse = client.query( QueryOntologyCatalog(Velocity.Q.linear.x.gt(25.0)) ) # 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(Velocity.Q.linear.x.gt(5.0), include_timestamp_range=True) ) # 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}}") ``` #### angular `class-attribute` `instance-attribute` ¶ ``` angular = None ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Velocity.Q.angular.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Velocity.Q.angular.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Velocity, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Find velocities where the angular X component exceeds 2 rad//s qresponse = client.query( QueryOntologyCatalog(Velocity.Q.angular.x.gt(2.0)) ) # 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(Velocity.Q.angular.x.gt(2.0), include_timestamp_range=True) ) # 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}}") ``` #### covariance `class-attribute` `instance-attribute` ¶ ``` covariance = None ``` Optional list of 64-bit floats representing the flattened matrix. ###### Querying with the **`.Q` Proxy**¶ Non-Queryable The field is not queryable with the **`.Q` Proxy**. #### covariance\_type `class-attribute` `instance-attribute` ¶ ``` covariance_type = None ``` 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()`, `.neq()`, `.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`. Filtering by Calibration Type This example demonstrates searching for data segments where the acceleration was derived from a specific calibrated procedure. ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog # Assume FROM_CALIBRATED_PROCEDURE is a user-defined integer constant with MosaicoClient.connect("localhost", 6726) as client: # Target the covariance_type nested within the acceleration field qbuilder = QueryOntologyCatalog( IMU.Q.acceleration.covariance_type.eq(FROM_CALIBRATED_PROCEDURE) ) results = client.query(qbuilder) if results: for item in results: print(f"Sequence: {item.sequence.name}") print(f"Matching Topics: {[topic.name for topic in item.topics]}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### 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[float]]` | Optional flattened 3x3 covariance matrix representing the uncertainty of the point measurement. | | `covariance_type` | `Optional[int]` | Enum integer representing the parameterization of the covariance matrix. | Input Validation Similar to the `Velocity` class, an `Acceleration` instance requires at least one non-null component (`linear` or `angular`). ###### 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. Example ``` from mosaicolabs import MosaicoClient, Acceleration, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter Accelerations with linear X-component AND angular Z-component qresponse = client.query( QueryOntologyCatalog(Acceleration.Q.linear.x.gt(5.0)) .with_expression(Acceleration.Q.angular.z.lt(10)) ) # 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(Acceleration.Q.linear.x.gt(5.0), include_timestamp_range=True) .with_expression(Acceleration.Q.angular.z.lt(10)) ) # 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}}") ``` #### linear `class-attribute` `instance-attribute` ¶ ``` linear = None ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Acceleration.Q.linear.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Acceleration.Q.linear.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Acceleration, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Find accelerations where the linear X component exceeds 5 m/s^2 qresponse = client.query( QueryOntologyCatalog(Acceleration.Q.linear.x.gt(5.0)) ) # 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(Acceleration.Q.linear.x.gt(5.0), include_timestamp_range=True) ) # 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}}") ``` #### angular `class-attribute` `instance-attribute` ¶ ``` angular = None ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Acceleration.Q.angular.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Acceleration.Q.angular.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Acceleration, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Find accelerations where the angular X component exceeds 1 rad/s^2 qresponse = client.query( QueryOntologyCatalog(Acceleration.Q.angular.x.gt(1.0)) ) # 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(Acceleration.Q.angular.x.gt(1.0), include_timestamp_range=True) ) # 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}}") ``` #### covariance `class-attribute` `instance-attribute` ¶ ``` covariance = None ``` Optional list of 64-bit floats representing the flattened matrix. ###### Querying with the **`.Q` Proxy**¶ Non-Queryable The field is not queryable with the **`.Q` Proxy**. #### covariance\_type `class-attribute` `instance-attribute` ¶ ``` covariance_type = None ``` 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()`, `.neq()`, `.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`. Filtering by Calibration Type This example demonstrates searching for data segments where the acceleration was derived from a specific calibrated procedure. ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog # Assume FROM_CALIBRATED_PROCEDURE is a user-defined integer constant with MosaicoClient.connect("localhost", 6726) as client: # Target the covariance_type nested within the acceleration field qbuilder = QueryOntologyCatalog( IMU.Q.acceleration.covariance_type.eq(FROM_CALIBRATED_PROCEDURE) ) results = client.query(qbuilder) if results: for item in results: print(f"Sequence: {item.sequence.name}") print(f"Matching Topics: {[topic.name for topic in item.topics]}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### 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` | `str` | A string identifier for the target coordinate frame. | | `acceleration` | `Optional[Acceleration]` | Optional 6D acceleration. | | `covariance` | `Optional[List[float]]` | Optional flattened NxN composed covariance matrix representing the uncertainty of the Pose+Velocity+[Acceleration] measurement. | | `covariance_type` | `Optional[int]` | 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. Example ``` from mosaicolabs import MosaicoClient, MotionState, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter MotionStates with position X-component AND angular velocity Z-component qresponse = client.query( QueryOntologyCatalog(MotionState.Q.pose.position.x.gt(123456.9)) .with_expression(MotionState.Q.velocity.angular.z.lt(10)) ) # 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(MotionState.Q.pose.position.x.gt(123456.9), include_timestamp_range=True) .with_expression(MotionState.Q.velocity.angular.z.lt(10)) ) # 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}}") ``` #### pose `instance-attribute` ¶ ``` pose ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `MotionState.Q.pose.position.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `MotionState.Q.pose.position.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `MotionState.Q.pose.orientation.x` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `MotionState.Q.pose.orientation.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `MotionState.Q.pose.orientation.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `MotionState.Q.pose.orientation.w` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, MotionState, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter snapshots where the object is beyond a specific X-coordinate qresponse = client.query( QueryOntologyCatalog(MotionState.Q.pose.position.x.gt(500.0)) ) # 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(MotionState.Q.pose.position.x.gt(500.0), include_timestamp_range=True) ) # 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}}") ``` #### velocity `instance-attribute` ¶ ``` velocity ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `MotionState.Q.velocity.linear.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `MotionState.Q.velocity.linear.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `MotionState.Q.velocity.angular.x` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `MotionState.Q.velocity.angular.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `MotionState.Q.velocity.angular.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, MotionState, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Find states where linear velocity in X exceeds 2.5 m/s qresponse = client.query( QueryOntologyCatalog(MotionState.Q.velocity.linear.x.gt(2.5)) ) # 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(MotionState.Q.velocity.linear.x.gt(5.0), include_timestamp_range=True) .with_expression(MotionState.Q.velocity.angular.z.lt(10)) ) # 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}}") ``` #### target\_frame\_id `instance-attribute` ¶ ``` target_frame_id ``` 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()`, `.neq()`, `.match()`, `.in_()` | Example ``` from mosaicolabs import MosaicoClient, MotionState, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Find states where target_frame_id is some link qresponse = client.query( QueryOntologyCatalog(MotionState.Q.target_frame_id.eq("moving_base")) ) # 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]}") ``` #### acceleration `class-attribute` `instance-attribute` ¶ ``` acceleration = None ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `MotionState.Q.acceleration.linear.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `MotionState.Q.acceleration.linear.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `MotionState.Q.acceleration.angular.x` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `MotionState.Q.acceleration.angular.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `MotionState.Q.acceleration.angular.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, MotionState, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Find states where centripetal acceleration exceeds 5 m/s^2 qresponse = client.query( QueryOntologyCatalog(MotionState.Q.acceleration.linear.y.gt(5.0)) ) # 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(MotionState.Q.acceleration.linear.y.gt(5.0), include_timestamp_range=True) .with_expression(MotionState.Q.acceleration.angular.z.lt(10)) ) # 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}}") ``` #### covariance `class-attribute` `instance-attribute` ¶ ``` covariance = None ``` Optional list of 64-bit floats representing the flattened matrix. ###### Querying with the **`.Q` Proxy**¶ Non-Queryable The field is not queryable with the **`.Q` Proxy**. #### covariance\_type `class-attribute` `instance-attribute` ¶ ``` covariance_type = None ``` 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()`, `.neq()`, `.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`. Filtering by Calibration Type This example demonstrates searching for data segments where the acceleration was derived from a specific calibrated procedure. ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog # Assume FROM_CALIBRATED_PROCEDURE is a user-defined integer constant with MosaicoClient.connect("localhost", 6726) as client: # Target the covariance_type nested within the acceleration field qbuilder = QueryOntologyCatalog( IMU.Q.acceleration.covariance_type.eq(FROM_CALIBRATED_PROCEDURE) ) results = client.query(qbuilder) if results: for item in results: print(f"Sequence: {item.sequence.name}") print(f"Matching Topics: {[topic.name for topic in item.topics]}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ## 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[float]]` | Optional flattened 6x6 composed covariance matrix representing the uncertainty of the force-torque measurement. | | `covariance_type` | `Optional[int]` | Enum integer representing the parameterization of the covariance matrix. | Unit Standards To ensure platform-wide consistency, all force components should be specified in **Newtons** and torque in **Newton-meters**. ###### 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. Example ``` from mosaicolabs import MosaicoClient, ForceTorque, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter ForceTorques with force X-component AND torque Z-component qresponse = client.query( QueryOntologyCatalog(ForceTorque.Q.force.x.gt(5.0)) .with_expression(ForceTorque.Q.torque.z.lt(10)) ) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(ForceTorque.Q.force.x.gt(5.0), include_timestamp_range=True) ) # 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}}") ``` #### force `instance-attribute` ¶ ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `ForceTorque.Q.force.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `ForceTorque.Q.force.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, ForceTorque, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Find where the linear X-force exceeds 50N qresponse = client.query(QueryOntologyCatalog(ForceTorque.Q.force.x.gt(50.0))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(ForceTorque.Q.force.x.gt(5.0), include_timestamp_range=True) ) # 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}}") ``` #### torque `instance-attribute` ¶ ``` torque ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `ForceTorque.Q.torque.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `ForceTorque.Q.torque.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, ForceTorque, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Find where the linear Y-torque is small qresponse = client.query(QueryOntologyCatalog(ForceTorque.Q.torque.y.lt(0.02))) # 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 data value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(ForceTorque.Q.torque.y.gt(5.0), include_timestamp_range=True) ) # 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}}") ``` #### covariance `class-attribute` `instance-attribute` ¶ ``` covariance = None ``` Optional list of 64-bit floats representing the flattened matrix. ###### Querying with the **`.Q` Proxy**¶ Non-Queryable The field is not queryable with the **`.Q` Proxy**. #### covariance\_type `class-attribute` `instance-attribute` ¶ ``` covariance_type = None ``` 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()`, `.neq()`, `.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`. Filtering by Calibration Type This example demonstrates searching for data segments where the acceleration was derived from a specific calibrated procedure. ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog # Assume FROM_CALIBRATED_PROCEDURE is a user-defined integer constant with MosaicoClient.connect("localhost", 6726) as client: # Target the covariance_type nested within the acceleration field qbuilder = QueryOntologyCatalog( IMU.Q.acceleration.covariance_type.eq(FROM_CALIBRATED_PROCEDURE) ) results = client.query(qbuilder) if results: for item in results: print(f"Sequence: {item.sequence.name}") print(f"Matching Topics: {[topic.name for topic in item.topics]}") ``` #### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` --- ## mosaicolabs.models.platform.Topic ¶ Bases: `BaseModel`, `_QueryProxyMixin` 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. Data Retrieval This class provides a server-side **metadata-only** view of the topic. To retrieve the actual time-series messages contained within the topic, you must use the `TopicHandler.get_data_streamer()` method from a `TopicHandler` instance. ##### Querying with the **`.Q` Proxy**¶ Warning: Deprecated Querying the topic user-custom metadata via the `user_metadata` field of this class is deprecated. Use the `QueryTopic.with_user_metadata()` builder instead. Example ``` from mosaicolabs import MosaicoClient, Topic, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic() .with_user_metadata("update_rate_hz", gt=100) .with_user_metadata("interface.type", eq="canbus") ) # 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]}") ``` ### user\_metadata `instance-attribute` ¶ ``` user_metadata ``` Custom user-defined key-value pairs associated with the entity. ###### Querying with the **`.Q` Proxy**¶ Warning: Deprecated Querying the topic user-custom metadata via the `user_metadata` field of this class is deprecated. Use the `QueryTopic.with_user_metadata()` builder instead. ### name `property` ¶ ``` name ``` The unique identifier or resource name of the entity. ###### Querying with **Query Builders**¶ The `name` property is queryable when constructing a `QueryTopic` via the convenience methods: * `QueryTopic.with_name()` * `QueryTopic.with_name_match()` Example ``` from mosaicolabs import MosaicoClient, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic().with_name("/front/imu"), ) # 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]}") ``` ### created\_timestamp `property` ¶ ``` created_timestamp ``` The UTC timestamp indicating when the entity was created on the server. ###### Querying with **Query Builders**¶ The `created_timestamp` property is queryable when constructing a `QueryTopic` via the convenience method: * `QueryTopic.with_created_timestamp()` Example ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic, Time with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific topic creation time qresponse = client.query( QueryTopic().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]}") ``` ### 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. ###### Querying with **Query Builders**¶ The `ontology_tag` property is queryable when constructing a `QueryTopic` via the convenience method `QueryTopic.with_ontology_tag()`. Example ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic().with_ontology_tag(IMU.ontology_tag()), ) # 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]}") ``` ### sequence\_name `property` ¶ ``` sequence_name ``` The name of the parent sequence containing this topic. ###### Querying with **Query Builders**¶ The `sequence_name` property is not queryable directly. Use `QuerySequence` to query for sequences. Example ``` from mosaicolabs import MosaicoClient, Topic, QuerySequence with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QuerySequence().with_name("test_winter_20260129_103000") ) # 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]}") ``` ### chunks\_number `property` ¶ ``` 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` property is not queryable. ### serialization\_format `property` ¶ ``` 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` property is not queryable. ### locked `property` ¶ ``` 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` property is not queryable. ### total\_size\_bytes `property` ¶ ``` total_size_bytes ``` The total physical storage footprint of the entity on the server in bytes. ###### Querying with **Query Builders**¶ The `total_size_bytes` property is not queryable. ## mosaicolabs.models.platform.Session `dataclass` ¶ ``` Session( uuid, 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. Data Retrieval This class provides a server-side **metadata-only** view of the session. To retrieve the actual time-series data contained within the topics of the session, you must use the `TopicHandler.get_data_streamer()` method from a `TopicHandler` instance. ##### Querying with the **`.Q` Proxy**¶ The session fields are not queryable via the **`.Q` proxy**. ### uuid `instance-attribute` ¶ ``` uuid ``` The session UUID ### 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 ¶ Bases: `BaseModel`, `_QueryProxyMixin` 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. Data Retrieval This class provides a server-side **metadata-only** view of the sequence. To retrieve the actual time-series data contained within the sequence, you must use the `SequenceHandler.get_data_streamer()` method from a `SequenceHandler` instance. ##### Querying with the **`.Q` Proxy**¶ Warning: Deprecated Querying the sequence user-custom metadata via the `user_metadata` field of this class is deprecated. Use the `QuerySequence.with_user_metadata()` builder instead. Example ``` from mosaicolabs import MosaicoClient, Sequence, QuerySequence with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QuerySequence() .with_user_metadata("project", eq="Apollo") .with_user_metadata("vehicle.software_stack.planning", eq="plan-4.1.7") ) # 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]}") ``` ### user\_metadata `instance-attribute` ¶ ``` user_metadata ``` Custom user-defined key-value pairs associated with the entity. ###### Querying with the **`.Q` Proxy**¶ Warning: Deprecated Querying the sequence user-custom metadata via the `user_metadata` field of this class is deprecated. Use the `QuerySequence.with_user_metadata()` builder instead. ### topics `property` ¶ ``` topics ``` Returns the list of names for all topics contained within this sequence. Accessing Topic Data This property returns string identifiers. To interact with topic data or metadata, use the `MosaicoClient.topic_handler()` factory. ###### Querying with **Query Builders**¶ The `topics` property is not queryable directly. Use `QueryTopic` to query for topics. Example ``` from mosaicolabs import MosaicoClient, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic().with_name("/sensors/camera/front/image_raw") ) # 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 `property` ¶ ``` name ``` The unique identifier or resource name of the entity. ###### Querying with **Query Builders**¶ The `name` property is queryable when constructing a `QuerySequence` via the convenience methods: * `QuerySequence.with_name()` * `QuerySequence.with_name_match()` Example ``` 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]}") ``` ### created\_timestamp `property` ¶ ``` created_timestamp ``` The UTC timestamp indicating when the entity was created on the server. ###### Querying with **Query Builders**¶ The `created_timestamp` property is queryable when constructing a `QuerySequence` via the convenience method: * `QuerySequence.with_created_timestamp()` Example ``` 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]}") ``` ### 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. ### sessions `property` ¶ ``` sessions ``` The list of sessions associated with this sequence. ###### Querying with **Query Builders**¶ The `sessions` property is not queryable. ### total\_size\_bytes `property` ¶ ``` total_size_bytes ``` The total physical storage footprint of the entity on the server in bytes. ###### Querying with **Query Builders**¶ The `total_size_bytes` property is not queryable. --- ## 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`. Example ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Find high-acceleration events (e.g., impacts) on the X-axis qresponse = client.query( QueryOntologyCatalog(IMU.Q.acceleration.x.gt(15.0)) .with_expression(IMU.Q.angular_velocity.z.gt(1.0)), ) # 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(IMU.Q.acceleration.x.gt(15.0), include_timestamp_range=True) .with_expression(IMU.Q.angular_velocity.z.gt(1.0)), ) # 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}}") ``` ### acceleration `instance-attribute` ¶ ``` acceleration ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `IMU.Q.acceleration.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `IMU.Q.acceleration.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for high-impact events qresponse = client.query( QueryOntologyCatalog(IMU.Q.acceleration.z.gt(19.6)) ) # 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(IMU.Q.acceleration.z.gt(19.6), include_timestamp_range=True) ) # 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}}") ``` ### angular\_velocity `instance-attribute` ¶ ``` angular_velocity ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `IMU.Q.angular_velocity.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `IMU.Q.angular_velocity.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for high-turns events qresponse = client.query( QueryOntologyCatalog(IMU.Q.angular_velocity.z.gt(1.0)) ) # 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(IMU.Q.angular_velocity.z.gt(1.0), include_timestamp_range=True) ) # 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}}") ``` ### orientation `class-attribute` `instance-attribute` ¶ ``` orientation = None ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `IMU.Q.orientation.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `IMU.Q.orientation.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `IMU.Q.orientation.w` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, IMU, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for orientation component values qresponse = client.query( QueryOntologyCatalog(IMU.Q.orientation.z.gt(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 for topic in item.topics]}") # Filter for a specific component value and extract the first and last occurrence times qresponse = client.query( QueryOntologyCatalog(IMU.Q.orientation.z.gt(0.707), include_timestamp_range=True) ) # 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}}") ``` ### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ## 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` | `int` | Fix status indicator (e.g., No Fix, 2D, 3D). | | `service` | `int` | Service used for the fix (e.g., GPS, GLONASS, Galileo). | | `satellites` | `Optional[int]` | Number of satellites currently visible or used in the solution. | | `hdop` | `Optional[float]` | Horizontal Dilution of Precision (lower is better). | | `vdop` | `Optional[float]` | 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`. Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, GPSStatus with MosaicoClient.connect("localhost", 6726) as client: # Filter for high-quality fixes (low HDOP) qresponse = client.query( QueryOntologyCatalog(GPSStatus.Q.hdop.lt(2.0)) .with_expression(GPSStatus.Q.satellites.geq(6)), ) # 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(GPSStatus.Q.hdop.lt(2.0), include_timestamp_range=True) .with_expression(GPSStatus.Q.satellites.geq(6)) ) # 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}}") ``` ### status `instance-attribute` ¶ ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, GPSStatus with MosaicoClient.connect("localhost", 6726) as client: # Filter for valid fixes qresponse = client.query( QueryOntologyCatalog(GPSStatus.Q.status.gt(0)) ) # 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(GPSStatus.Q.status.gt(0), include_timestamp_range=True) ) # 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}}") ``` ### service `instance-attribute` ¶ ``` service ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, GPSStatus with MosaicoClient.connect("localhost", 6726) as client: # Filter for specific service ID qresponse = client.query( QueryOntologyCatalog(GPSStatus.Q.service.eq(1)) ) # 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(GPSStatus.Q.service.eq(1), include_timestamp_range=True) ) # 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}}") ``` ### satellites `class-attribute` `instance-attribute` ¶ ``` satellites = None ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, GPSStatus with MosaicoClient.connect("localhost", 6726) as client: # Filter for fixes with at least 6 satellites qresponse = client.query( QueryOntologyCatalog(GPSStatus.Q.satellites.geq(6)) ) # 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(GPSStatus.Q.satellites.geq(6), include_timestamp_range=True) ) # 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}}") ``` ### hdop `class-attribute` `instance-attribute` ¶ ``` hdop = None ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, GPSStatus with MosaicoClient.connect("localhost", 6726) as client: # Filter for excellent horizontal precision qresponse = client.query( QueryOntologyCatalog(GPSStatus.Q.hdop.lt(1.5)) ) # 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(GPSStatus.Q.hdop.lt(1.5), include_timestamp_range=True) ) # 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}}") ``` ### vdop `class-attribute` `instance-attribute` ¶ ``` vdop = None ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, GPSStatus with MosaicoClient.connect("localhost", 6726) as client: # Filter for good vertical precision qresponse = client.query( QueryOntologyCatalog(GPSStatus.Q.vdop.lt(2.0)) ) # 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(GPSStatus.Q.vdop.lt(2.0), include_timestamp_range=True) ) # 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}}") ``` ### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ## 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`. Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, GPS with MosaicoClient.connect("localhost", 6726) as client: # Find data collected above 1000m altitude qresponse = client.query( QueryOntologyCatalog(GPS.Q.position.z.gt(1000.0)) .with_expression(GPS.Q.status.satellites.geq(6)), ) # 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(GPS.Q.position.z.gt(1000.0), include_timestamp_range=True) .with_expression(GPS.Q.status.satellites.geq(6)), ) # 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}}") ``` ### position `instance-attribute` ¶ ``` position ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `GPS.Q.position.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `GPS.Q.position.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, GPS with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific latitude range qresponse = client.query( QueryOntologyCatalog(GPS.Q.position.x.between([45.0, 46.0])) ) # 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(GPS.Q.position.x.between([45.0, 46.0]), include_timestamp_range=True) ) # 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}}") ``` ### velocity `class-attribute` `instance-attribute` ¶ ``` velocity = None ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `GPS.Q.velocity.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `GPS.Q.velocity.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, GPS with MosaicoClient.connect("localhost", 6726) as client: # Filter for high vertical velocity qresponse = client.query( QueryOntologyCatalog(GPS.Q.velocity.z.gt(5.0)) ) # 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(GPS.Q.velocity.z.gt(5.0), include_timestamp_range=True) ) # 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}}") ``` ### status `class-attribute` `instance-attribute` ¶ ``` status = None ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `GPS.Q.status.hdop` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `GPS.Q.status.vdop` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `GPS.Q.status.status` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `GPS.Q.status.service` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, GPS with MosaicoClient.connect("localhost", 6726) as client: # Filter for high-precision fixes with at least 8 satellites qresponse = client.query( QueryOntologyCatalog(GPS.Q.status.satellites.geq(8)) ) # 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(GPS.Q.status.status.eq(1), include_timestamp_range=True) ) # 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}}") ``` ### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ## mosaicolabs.models.sensors.NMEASentence ¶ Bases: `Serializable` Raw NMEA 0183 sentence string. Attributes: | Name | Type | Description | | --- | --- | --- | | `sentence` | `str` | 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()`, `.neq()`, `.match()`, `.in_()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, NMEASentence with MosaicoClient.connect("localhost", 6726) as client: # Filter for NMEA sentences containing "GPGGA" qresponse = client.query( QueryOntologyCatalog(NMEASentence.Q.sentence.match("GPGGA")) ) # 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(NMEASentence.Q.sentence.match("GPGGA"), include_timestamp_range=True) ) # 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}}") ``` ### sentence `instance-attribute` ¶ ``` 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ## 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`. Example ``` from mosaicolabs import MosaicoClient, Magnetometer, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for magnetic field values within a specific range qresponse = client.query( QueryOntologyCatalog(Magnetometer.Q.magnetic_field.x.between(-100, 100)) ) # 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(Magnetometer.Q.magnetic_field.x.between(-100, 100), include_timestamp_range=True) ) # 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}}") ``` ### magnetic\_field `instance-attribute` ¶ ``` magnetic_field ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Magnetometer.Q.magnetic_field.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `Magnetometer.Q.magnetic_field.z` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Magnetometer, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for magnetic field values within a specific range qresponse = client.query( QueryOntologyCatalog(Magnetometer.Q.magnetic_field.x.between(-100, 100)) ) # 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(Magnetometer.Q.magnetic_field.x.between(-100, 100), include_timestamp_range=True) ) # 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}}") ``` ### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ## 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`. Example ``` from mosaicolabs import MosaicoClient, Pressure, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for pressure values within a specific range qresponse = client.query( QueryOntologyCatalog(Pressure.Q.value.between([100000, 200000])) ) # 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(Pressure.Q.value.between([100000, 200000]), include_timestamp_range=True) ) # 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}}") ``` ### variance `class-attribute` `instance-attribute` ¶ ``` variance = None ``` 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()`, `.neq()`, `.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. Example ``` from mosaicolabs import MosaicoClient, Pressure, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter Pressure data by a specific acquisition second qresponse = client.query( QueryOntologyCatalog(Pressure.Q.variance.lt(0.76)) ) # 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]}") ``` ### variance\_type `class-attribute` `instance-attribute` ¶ ``` variance_type = None ``` 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()`, `.neq()`, `.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. Filtering by Precision The following examples demonstrate how to filter sensor data based on the magnitude of the variance or the specific procedure used to calculate it. ``` from mosaicolabs import MosaicoClient, Pressure, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter by variance threshold results = client.query(QueryOntologyCatalog( Pressure.Q.variance.lt(0.76) )) if results: for item in results: print(f"Sequence: {item.sequence.name}") print(f"Topics: {[topic.name for topic in item.topics]}") ``` ### value `instance-attribute` ¶ ``` value ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Pressure, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for pressure values within a specific range qresponse = client.query( QueryOntologyCatalog(Pressure.Q.value.between([100000, 200000])) ) # 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(Pressure.Q.value.between([100000, 200000]), include_timestamp_range=True) ) # 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}}") ``` ### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### 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`. Example ``` from mosaicolabs import MosaicoClient, Range, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for range data based on range parameters qresponse = client.query( QueryOntologyCatalog(Range.Q.range.between(0.0, 10.0)) .with_epression(Range.Q.radiation_type.eq(0)) .with_epression(Range.Q.max_range.between(70.0, 90.0)), ) # 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(Range.Q.range.between(0.0, 10.0), include_timestamp_range=True) .with_epression(Range.Q.radiation_type.eq(0)) .with_epression(Range.Q.max_range.between(70.0, 90.0)), ) # 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}}") ``` ### variance `class-attribute` `instance-attribute` ¶ ``` variance = None ``` 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()`, `.neq()`, `.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. Example ``` from mosaicolabs import MosaicoClient, Pressure, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter Pressure data by a specific acquisition second qresponse = client.query( QueryOntologyCatalog(Pressure.Q.variance.lt(0.76)) ) # 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]}") ``` ### variance\_type `class-attribute` `instance-attribute` ¶ ``` variance_type = None ``` 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()`, `.neq()`, `.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. Filtering by Precision The following examples demonstrate how to filter sensor data based on the magnitude of the variance or the specific procedure used to calculate it. ``` from mosaicolabs import MosaicoClient, Pressure, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter by variance threshold results = client.query(QueryOntologyCatalog( Pressure.Q.variance.lt(0.76) )) if results: for item in results: print(f"Sequence: {item.sequence.name}") print(f"Topics: {[topic.name for topic in item.topics]}") ``` ### radiation\_type `instance-attribute` ¶ ``` radiation_type ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Range, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for range data based on radiation type qresponse = client.query( QueryOntologyCatalog(Range.Q.radiation_type.eq(0)) ) # 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]}") ``` ### field\_of\_view `instance-attribute` ¶ ``` field_of_view ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Range, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for range data based on field of view qresponse = client.query( QueryOntologyCatalog(Range.Q.field_of_view.between(0.0, 1.0)) ) # 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]}") ``` ### min\_range `instance-attribute` ¶ ``` min_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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Range, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for range data based on minimum range qresponse = client.query( QueryOntologyCatalog(Range.Q.min_range.between(0.0, 10.0)) ) # 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]}") ``` ### max\_range `instance-attribute` ¶ ``` max_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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Range, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for range data based on maximum range qresponse = client.query( QueryOntologyCatalog(Range.Q.max_range.between(0.0, 10.0)) ) # 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]}") ``` ### range `instance-attribute` ¶ ``` range ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Range, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for range data based on range qresponse = client.query( QueryOntologyCatalog(Range.Q.range.between(0.0, 10.0)) ) # 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(Range.Q.range.between(0.0, 10.0), include_timestamp_range=True) ) # 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}}") ``` ### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### 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`. Example ``` from mosaicolabs import MosaicoClient, Temperature, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for temperature values within a specific range qresponse = client.query( QueryOntologyCatalog(Temperature.Q.value.between([273.15, 373.15])) .with_expression(Temperature.Q.timestamp_ns.between(1700000000, 1800000000)), ) # 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(Temperature.Q.value.between([273.15, 373.15]), include_timestamp_range=True) ) # 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]}") ``` ### variance `class-attribute` `instance-attribute` ¶ ``` variance = None ``` 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()`, `.neq()`, `.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. Example ``` from mosaicolabs import MosaicoClient, Pressure, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter Pressure data by a specific acquisition second qresponse = client.query( QueryOntologyCatalog(Pressure.Q.variance.lt(0.76)) ) # 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]}") ``` ### variance\_type `class-attribute` `instance-attribute` ¶ ``` variance_type = None ``` 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()`, `.neq()`, `.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. Filtering by Precision The following examples demonstrate how to filter sensor data based on the magnitude of the variance or the specific procedure used to calculate it. ``` from mosaicolabs import MosaicoClient, Pressure, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter by variance threshold results = client.query(QueryOntologyCatalog( Pressure.Q.variance.lt(0.76) )) if results: for item in results: print(f"Sequence: {item.sequence.name}") print(f"Topics: {[topic.name for topic in item.topics]}") ``` ### value `instance-attribute` ¶ ``` value ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, Temperature, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for temperature values within a specific range qresponse = client.query( QueryOntologyCatalog(Temperature.Q.value.between([273.15, 373.15])) ) # 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(Temperature.Q.value.between([273.15, 373.15]), include_timestamp_range=True) ) # 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}}") ``` ### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### 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[str]` | Names of the different robot joints | | `positions` | `List[float]` | Positions ([rad] or [m]) of the different robot joints | | `velocities` | `List[float]` | Velocities ([rad/s] or [m/s]) of the different robot joints | | `efforts` | `List[float]` | 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 `instance-attribute` ¶ ``` names ``` 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 `instance-attribute` ¶ ``` positions ``` 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 `instance-attribute` ¶ ``` velocities ``` 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 `instance-attribute` ¶ ``` efforts ``` 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ## 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`. Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, Image with MosaicoClient.connect("localhost", 6726) as client: # Filter for image data based on image parameters qresponse = client.query( QueryOntologyCatalog(Image.Q.width.between(1500, 2000)) .with_expression(Image.Q.height.between(1500, 2000)) .with_expression(Image.Q.format.eq("png")), ) # 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]}") ``` ### data `instance-attribute` ¶ ``` data ``` The flattened image memory buffer. ###### Querying with the **`.Q` Proxy**¶ The data is not queryable via the `data` field (bytes are not comparable). ### format `instance-attribute` ¶ ``` format ``` 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()`, `.neq()`, `.match()`, `.in_()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, Image with MosaicoClient.connect("localhost", 6726) as client: # Filter for image data based on format qresponse = client.query( QueryOntologyCatalog(Image.Q.format.eq(ImageFormat.PNG)) ) # 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]}") ``` ### width `instance-attribute` ¶ ``` width ``` 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` | `Integer` | `.eq()`, `.neq()`, `.gt()`, `.gte()`, `.lt()`, `.lte()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, Image with MosaicoClient.connect("localhost", 6726) as client: # Filter for image data based on width qresponse = client.query( QueryOntologyCatalog(Image.Q.width.between(0, 100)) ) # 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]}") ``` ### height `instance-attribute` ¶ ``` height ``` 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` | `Integer` | `.eq()`, `.neq()`, `.gt()`, `.gte()`, `.lt()`, `.lte()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, Image with MosaicoClient.connect("localhost", 6726) as client: # Filter for image data based on height qresponse = client.query( QueryOntologyCatalog(Image.Q.height.between(0, 100)) ) # 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]}") ``` ### stride `instance-attribute` ¶ ``` stride ``` 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` | `Integer` | `.eq()`, `.neq()`, `.gt()`, `.gte()`, `.lt()`, `.lte()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, Image with MosaicoClient.connect("localhost", 6726) as client: # Filter for image data based on stride qresponse = client.query( QueryOntologyCatalog(Image.Q.stride.between(0, 100)) ) # 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]}") ``` ### encoding `instance-attribute` ¶ ``` encoding ``` 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()`, `.neq()`, `.match()`, `.in_()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, Image with MosaicoClient.connect("localhost", 6726) as client: # Filter for image data based on encoding qresponse = client.query( QueryOntologyCatalog(Image.Q.encoding.eq("bgr8")) ) # 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]}") ``` ### is\_bigendian `class-attribute` `instance-attribute` ¶ ``` is_bigendian = None ``` 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()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, Image with MosaicoClient.connect("localhost", 6726) as client: # Filter for image data based on is_bigendian qresponse = client.query( QueryOntologyCatalog(Image.Q.is_bigendian.eq(True)) ) # 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]}") ``` ### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### 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 `instance-attribute` ¶ ``` data ``` 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 `instance-attribute` ¶ ``` format ``` The compression format (e.g., 'jpeg', 'png'). ###### Querying with the **`.Q` Proxy**¶ | Field Access Path | Queryable Type | Supported Operators | | --- | --- | --- | | `CompressedImage.Q.format` | `String` | `.eq()`, `.neq()`, `.match()`, `.in_()` | Example ``` from mosaicolabs import MosaicoClient, CompressedImage, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter for image data based on image parameters qresponse = client.query( QueryOntologyCatalog(CompressedImage.Q.format.eq("jpeg")) ) # 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]}") ``` ### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ### 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). | `{}` | Warning **Stateless Default**: The default codec cannot maintain temporal state. For stateful formats like **H.264** or **HEVC**, calling this method without a specialized `codec` will return `None`. For multi-topic video sequences, use `StatefulDecodingSession.decode()` instead to prevent memory corruption and visual artifacts caused by interleaved P-frames. 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. Supported Formats * `ImageFormat.H264` * `ImageFormat.HEVC` Example ``` 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.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() ``` ### 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). | Note The first few calls to this method for a new `context` may return `None` if the stream starts with inter-frames (P/B) before hitting an IDR-frame (I-frame/Keyframe). ### 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` | `int` | Height in pixels of the image with which the camera was calibrated | | `width` | `int` | Width in pixels of the image with which the camera was calibrated | | `distortion_model` | `str` | The distortion model used | | `distortion_parameters` | `list[float]` | The distortion coefficients (k1, k2, t1, t2, k3...). Size depends on the model. | | `intrinsic_parameters` | `list[float]` | The 3x3 Intrinsic Matrix (K) flattened row-major. | | `rectification_parameters` | `list[float]` | The 3x3 Rectification Matrix (R) flattened row-major. | | `projection_parameters` | `list[float]` | 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`. Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, CameraInfo with MosaicoClient.connect("localhost", 6726) as client: # Filter for camera data based on camera parameters qresponse = client.query( QueryOntologyCatalog(CameraInfo.Q.height.between(1080, 2160)) ) # 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]}") ``` ### height `instance-attribute` ¶ ``` height ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, CameraInfo with MosaicoClient.connect("localhost", 6726) as client: # Filter for camera data based on camera parameters qresponse = client.query( QueryOntologyCatalog(CameraInfo.Q.height.between(1080, 2160)) ) # 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]}") ``` ### width `instance-attribute` ¶ ``` width ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, CameraInfo with MosaicoClient.connect("localhost", 6726) as client: # Filter for camera data based on camera parameters qresponse = client.query( QueryOntologyCatalog(CameraInfo.Q.width.between(1920, 3840)) ) # 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]}") ``` ### distortion\_model `instance-attribute` ¶ ``` distortion_model ``` 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` | `Categorical` | `.eq()`, `.neq()`, `.in_()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, CameraInfo with MosaicoClient.connect("localhost", 6726) as client: # Filter for camera data based on camera parameters qresponse = client.query( QueryOntologyCatalog(CameraInfo.Q.distortion_model.eq("plumb_bob")) ) # 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]}") ``` ### distortion\_parameters `instance-attribute` ¶ ``` distortion_parameters ``` 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 `instance-attribute` ¶ ``` intrinsic_parameters ``` 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 `instance-attribute` ¶ ``` rectification_parameters ``` 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 `instance-attribute` ¶ ``` projection_parameters ``` 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 = None ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `CameraInfo.Q.binning.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, CameraInfo with MosaicoClient.connect("localhost", 6726) as client: # Filter for camera data based on camera parameters qresponse = client.query( QueryOntologyCatalog(CameraInfo.Q.binning.x.eq(2)) ) # 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]}") ``` ### roi `class-attribute` `instance-attribute` ¶ ``` roi = None ``` 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()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `CameraInfo.Q.roi.offset.y` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `CameraInfo.Q.roi.width` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | | `CameraInfo.Q.roi.height` | `Numeric` | `.eq()`, `.neq()`, `.lt()`, `.gt()`, `.leq()`, `.geq()`, `.in_()`, `.between()` | Example ``` from mosaicolabs import MosaicoClient, QueryOntologyCatalog, CameraInfo with MosaicoClient.connect("localhost", 6726) as client: # Filter for camera data based on camera parameters qresponse = client.query( QueryOntologyCatalog(CameraInfo.Q.roi.offset.x.eq(2)) ) # 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]}") ``` ### 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` --- ## 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. Example ``` from mosaicolabs import MosaicoClient, Topic, QuerySequence with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryOntologyCatalog(IMU.Q.acceleration.x.lt(-4.0)) # Using constructor .with_expression(IMU.Q.acceleration.y.gt(5.0)) # Using with_expression ) # 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(IMU.Q.acceleration.x.lt(-4.0), include_timestamp_range=True) .with_expression(IMU.Q.acceleration.y.gt(5.0)) ) # 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 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. Example ``` from mosaicolabs import MosaicoClient, Topic, QuerySequence 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(GPS.Q.position.x.between([44.0, 45.0])) ) # 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)) ) # 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}}") ``` 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. Example Output `{"imu.timestamp_ns": {"$between": [...]}, "imu.acceleration.x": {"$leq": 10}}` Returns: | Type | Description | | --- | --- | | `Dict[str, Any]` | A dictionary containing all merged sensor-field expressions. | ### QueryTopic ¶ ``` QueryTopic(*expressions) ``` 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. Example ``` from mosaicolabs import MosaicoClient, Image, Topic, QuerySequence 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(1700000000)) .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]}") ``` The constructor initializes the query with an optional list of `_QueryTopicExpression` objects, generated via `Topic.Q.` proxy. Deprecated The constructor is deprecated. Use the `with_user_metadata()` convenience method instead, if wanting to query the user metadata. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `*expressions` | `_QueryExpression` | A variable number of `Topic.Q` (`_QueryTopicExpression`) expression objects. | `()` | Raises: | Type | Description | | --- | --- | | `TypeError` | If an expression is not of the supported `Topic.Q` type. | | `ValueError` | If an operator does not follow the required internal '$' prefix format. | | `NotImplementedError` | If a duplicate key is detected, as the current implementation enforces unique keys per query. | #### with\_expression ¶ ``` with_expression(expr) ``` Adds a new expression to the query using a fluent interface. Deprecated API This is the old way to add filters for nested metadata. Use the `with_user_metadata` convenience method Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `expr` | `_QueryExpression` | A `_QueryTopicExpression` constructed via a `Topic.Q` proxy. | *required* | Returns: | Type | Description | | --- | --- | | `QueryTopic` | The `QueryTopic` instance for method chaining. | #### 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. Note The previous method using `Topic.Q.user_metadata` is maintained for backward compatibility but is scheduled for removal in release **0.4.0**. 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`, 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. | Operators Supported * `eq`: Equal to * `neq`: Not equal to * `gt`: Greater than * `geq`: Greater than or equal to * `lt`: Less than * `leq`: Less than or equal to * `between`: Range filter (expects a list of [min, max]) Example ``` # Find sequences for 'Apollo' project with visibility under 100m query = ( QueryTopic() .with_user_metadata("sensor_id", eq="ABC123_XYZ") .with_user_metadata("calibration.focal_length", between=(14, 24)) ) results = client.query(query) ``` 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. Example ``` from mosaicolabs import MosaicoClient, Topic, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Target a specific known topic path qresponse = client.query( QueryTopic().with_name("vehicle/front/camera") ) # 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]}") ``` 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. Example ``` from mosaicolabs import MosaicoClient, Topic, QuerySequence with MosaicoClient.connect("localhost", 6726) as client: # Search for all topics containing the word 'camera' qresponse = client.query( QueryTopic().with_name_match("camera") ) # 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]}") ``` 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'). Example ``` from mosaicolabs import MosaicoClient, Topic, QuerySequence with MosaicoClient.connect("localhost", 6726) as client: # Filter for IMU-only data streams qresponse = client.query( QueryTopic().with_ontology_tag(IMU.ontology_tag()) ) # 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]}") ``` **Note**: To ensure compatibility and avoid hardcoding strings, it is highly recommended to retrieve the tag dynamically using the `ontology_tag()` method of the desired ontology class. 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. Example ``` from mosaicolabs import MosaicoClient, Topic, QuerySequence with MosaicoClient.connect("localhost", 6726) as client: # Find sequences created during a specific day qresponse = client.query( QueryTopic().with_created_timestamp( time_start=Time.from_float(1704067200.0), # 2024-01-01 time_end=Time.from_float(1704153600.0) # 2024-01-02 ) ) # 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]}") ``` 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: 1. **System Fields**: Standard fields like `name` are kept in the root dictionary. 2. **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(*expressions) ``` 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. Example ``` 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_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]}") ``` The constructor initializes the query with an optional list of `_QuerySequenceExpression` objects, generated via `Sequence.Q.` proxy. Deprecated The constructor is deprecated. Use the `with_user_metadata()` convenience method instead, if wanting to query the user metadata. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `*expressions` | `_QueryExpression` | A variable number of `Sequence.Q` (`_QuerySequenceExpression`) objects. | `()` | Raises: | Type | Description | | --- | --- | | `TypeError` | If an expression is not of the supported `Sequence.Q` type. | | `ValueError` | If an operator does not follow the required internal '$' prefix format. | | `NotImplementedError` | If a duplicate key is detected, as the current implementation enforces unique keys per query. | #### with\_expression ¶ ``` with_expression(expr) ``` Adds a new expression to the query using a fluent interface. Deprecated API This is the old way to add filters for nested metadata. Use the `with_user_metadata` convenience method Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `expr` | `_QueryExpression` | A `_QuerySequenceExpression` constructed via a `Sequence.Q` proxy. | *required* | Returns: | Type | Description | | --- | --- | | `QuerySequence` | The `QuerySequence` instance for method chaining. | #### 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. Note The previous method using `Sequence.Q.user_metadata` is maintained for backward compatibility but is scheduled for removal in release **0.4.0**. 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. | Operators Supported * `eq`: Equal to * `neq`: Not equal to * `gt`: Greater than * `geq`: Greater than or equal to * `lt`: Less than * `leq`: Less than or equal to * `between`: Range filter (expects a list of [min, max]) Example ``` # Find sequences for 'Apollo' project with visibility under 100m query = ( QuerySequence() .with_user_metadata("project", eq="Apollo") .with_user_metadata("environment.visibility", lt=100) ) results = client.query(query) ``` 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. Example ``` from mosaicolabs import MosaicoClient, Topic, QuerySequence with MosaicoClient.connect("localhost", 6726) as client: # Find all sequences with name equal to 'test_winter_01' qresponse = client.query( QuerySequence().with_name("test_winter_01") ) # Inspect the response for item in qresponse: print(f"Sequence: {item.sequence.name}") print(f"Topics: {[topic.name for topic in item.topics]}") ``` 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. Example ``` from mosaicolabs import MosaicoClient, Topic, QuerySequence with MosaicoClient.connect("localhost", 6726) as client: # Find all sequences with name containing 'calibration_run_' qresponse = client.query( QuerySequence().with_name_match("calibration_run_") ) # Inspect the response for item in qresponse: print(f"Sequence: {item.sequence.name}") print(f"Topics: {[topic.name for topic in item.topics]}") ``` 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. Example ``` from mosaicolabs import MosaicoClient, Topic, QuerySequence with MosaicoClient.connect("localhost", 6726) as client: # Find sequences created during a specific time range qresponse = client.query( QuerySequence().with_created_timestamp( time_start=Time.from_float(1704067200.0), # 2024-01-01 time_end=Time.from_float(1704153600.0) # 2024-01-02 ) ) # Inspect the response for item in qresponse: print(f"Sequence: {item.sequence.name}") print(f"Topics: {[topic.name for topic in item.topics]}") ``` 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: 1. **Normal Fields**: Fields like `name` are kept in a flat dictionary. 2. **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. Example ``` from mosaicolabs import QueryOntologyCatalog, QuerySequence, Query, IMU, MosaicoClient # Establish a connection to the Mosaico Data Platform with MosaicoClient.connect("localhost", 6726) as client: # Build a filter with name pattern and metadata-related expression query = Query( # Append a filter for sequence metadata QuerySequence() .with_user_metadata("environment.visibility", lt=50) .with_name_match("test_drive"), # Append a filter with deep time-series data discovery and measurement time windowing QueryOntologyCatalog(include_timestamp_range=True) .with_expression(IMU.Q.acceleration.x.gt(5.0)) .with_expression(IMU.Q.timestamp_ns.gt(1700134567)) ) # Perform the server side query qresponse = client.query(query=query) # 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}}") ``` 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. | Example ``` from mosaicolabs import QueryOntologyCatalog, QuerySequence, Query, IMU, MosaicoClient # Build a filter with name pattern and metadata-related expression query = Query( # Append a filter for sequence metadata QuerySequence() .with_user_metadata("environment.visibility", lt=50) .with_name_match("test_drive") ) # Append a filter with deep time-series data discovery and measurement time windowing query.append( QueryOntologyCatalog() .with_expression(IMU.Q.acceleration.x.gt(5.0)) .with_expression(IMU.Q.timestamp_ns.gt(1700134567)) ) ``` #### 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. Example Output ``` { "topic": { ... topic filters ... }, "sequence": { ... sequence filters ... }, "ontology": { ... ontology filters ... } } ``` Returns: | Type | Description | | --- | --- | | `Dict[str, Any]` | The final aggregated query dictionary. | --- ## 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. ### with\_expression ¶ ``` with_expression(expr) ``` Appends a new filter expression using a fluent interface. Parameters: | Name | Type | Description | Default | | --- | --- | --- | --- | | `expr` | `_QueryExpression` | A valid `_QueryExpression` | *required* | ### 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: 1. **Generation**: A user calls `IMU.Q.acceleration.x.gt(9.8)`, which generates a `_QueryCatalogExpression` (a subclass of this class). 2. **Validation**: A Builder receives the expression and validates its type, operator format, and key uniqueness. 3. **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. Example `{"gps.status.service": {"$eq": 0}}` ## 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. Example `{"gps.status.service": {"$eq": 0}}` ## 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. Example `{"gps.status.service": {"$eq": 0}}` ## 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. Example `{"gps.status.service": {"$eq": 0}}` --- ## 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. Example ``` from mosaicolabs import MosaicoClient, IMU, Floating64, QueryOntologyCatalog with MosaicoClient.connect("localhost", 6726) as client: # Filter IMU data by a specific acquisition second qresponse = client.query( QueryOntologyCatalog(IMU.Q.timestamp_ns.lt(1770282868)) ) # 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 primitive Floating64 telemetry by frame identifier qresponse = client.query( QueryOntologyCatalog(Floating64.Q.frame_id.eq("robot_base")) ) # 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]}") ``` 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. Example This demonstrates query chaining to narrow your search to specific sequences and topics. This is necessary when criteria span different data channels; otherwise, the resulting filters chained in `AND` in a single query would produce an empty result. ``` from mosaicolabs import MosaicoClient, QuerySequence with MosaicoClient.connect("localhost", 6726) as client: # Broad Search: Find sequences with high-precision GPS initial_response = client.query(QueryOntologyCatalog(GPS.Q.status.status.eq(2))) # Chaining: Use results to "lock" the domain and find specific data in those sequences # on different data channels if not initial_response.is_empty(): final_response = client.query( initial_response.to_query_sequence(), # The "locked" sequence domain QueryTopic().with_name("/localization/log_string"), # Target a specific log topic QueryOntologyCatalog(String.Q.data.match("[ERR]")) # Filter by content ) ``` 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. Example ``` 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 content ) # 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 ) ``` 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. --- ## mosaicolabs.ml.DataFrameExtractor ¶ ``` DataFrameExtractor(sequence_handler) ``` 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* | ### 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. Important This function must be iterated (e.g. called in a for loop) Warning Setting `window_sec` to a very large value might disable windowing. The extractor will attempt to load the entire requested time range into memory. This is only recommended for small sequences or systems with high RAM capacity. 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. | Example ``` # Obtain a dataframe with DataFrameExtractor from mosaicolabs import MosaicoClient, IMU, Image from mosaicolabs.ml import DataFrameExtractor, SyncTransformer with MosaicoClient.connect("localhost", 6726) as client: sequence_handler = client.get_sequence_handler("example_sequence") for df in DataFrameExtractor(sequence_handler).to_pandas_chunks( topics = ["/front/imu", "/front/camera/image_raw"] ): # Do something with the dataframe. # For example, you can sync the data using the `SyncTransformer`: sync_transformer = SyncTransformer( target_fps = 30, # resample at 30 Hz and fill the Nans with a Hold policy ) synced_df = sync_transformer.transform(df) # Reconstruct the image message from a dataframe row image_msg = Message.from_dataframe_row(synced_df, "/front/camera/image_raw") image_data = image_msg.get_data(Image) # Show the image image_data.to_pillow().show() # ... ``` ## mosaicolabs.ml.SyncTransformer ¶ ``` SyncTransformer( target_fps, policy=SyncHold(), timestamp_column="timestamp_ns", ) ``` 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 ¶ ``` 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. **Example with generic dataframe** ``` from mosaicolabs.ml import SyncTransformer, SyncHold # 5 Hz Target (200ms steps) transformer = SyncTransformer(target_fps=5, policy=SyncHold()) # Define a sparse dataframe with two sensors: # `sensor_a` starts at 0, `sensor_b` arrives at 600ms sparse_data = { "timestamp_ns": [ 0, 600_000_000, 900_000_000, 1_200_000_000, 1_500_000_000, ], "val1": [10.0, 11.0, None, 12.0, 13.0], "val2": [None, 1.0, 2.0, None, 3.0], } df = pd.DataFrame(sparse_data) dense_df = transformer.fit(df).transform(df) # Expected output # "timestamp_ns", "sensor_a", "sensor_b" # 0, 10.0, None # <- avoid hallucination on `sensor_b` # 200_000_000, 10.0, None # <- avoid hallucination on `sensor_b` # 400_000_000, 10.0, None # <- avoid hallucination on `sensor_b` # 600_000_000, 11.0, 1.0 # 800_000_000, 11.0, 2.0 # 1_000_000_000, 11.0, 2.0 # 1_200_000_000, 12.0, 2.0 # 1_400_000_000, 12.0, 2.0 ``` **Example with Mosaico dataframe** ``` # Obtain a dataframe with DataFrameExtractor from mosaicolabs import MosaicoClient, IMU, Image from mosaicolabs.ml import DataFrameExtractor, SyncTransformer with MosaicoClient.connect("localhost", 6726) as client: sequence_handler = client.get_sequence_handler("example_sequence") for df in DataFrameExtractor(sequence_handler).to_pandas_chunks( topics = ["/front/imu", "/front/camera/image_raw"] ): # Synch the data at 30 Hz: sync_transformer = SyncTransformer( target_fps = 30, # resample at 30 Hz and fill the Nans with a `Hold` policy ) synced_df = sync_transformer.transform(df) # Do something with the synced dataframe # ... ``` ### fit\_transform ¶ ``` fit_transform(X, y=None) ``` Fits the transformer to the data and then transforms it. ### 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.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. --- ## 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. Example ``` # Internal usage within the ROS Bridge ros_msg = ROSMessage( timestamp=17000, topic="/pose", msg_type="geometry_msgs/msg/PoseStamped", data={ "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "pose": { "position": {"x": 1.0, "y": 2.0, "z": 0.0}, "orientation": {"x": 0, "y": 0, "z": 0, "w": 1} }, } } # Automatically resolves to a flat Mosaico Pose with attached metadata mosaico_pose = PoseAdapter.translate(ros_msg) ``` #### 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. Example ``` ros_data= { "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "pose": { "position": {"x": 1.0, "y": 2.0, "z": 0.0}, "orientation": {"x": 0, "y": 0, "z": 0, "w": 1} }, } # Automatically resolves to a flat Mosaico Pose with attached metadata mosaico_pose = PoseAdapter.from_dict(ros_data) ``` 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. Example ``` ros_msg= ROSMessage( timestamp=1700000000000, topic="/cmd_vel", msg_type="geometry_msgs/msg/TwistStamped", data= { "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "twist": { "linear": {"x": 5.0, "y": 0.0, "z": 0.0}, "angular": {"x": 0.0, "y": 0.0, "z": 1.0} }, "covariance": [0.1] * 36 ) # Automatically resolves to a flat Mosaico Velocity with attached metadata mosaico_velocity = TwistAdapter.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 `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. Example ``` ros_data= { "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "twist": { "linear": {"x": 5.0, "y": 0.0, "z": 0.0}, "angular": {"x": 0.0, "y": 0.0, "z": 1.0} }, "covariance": [0.1] * 36 } # Automatically resolves to a flat Mosaico Velocity with attached metadata mosaico_velocity = TwistAdapter.from_dict(ros_data) ``` 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. Example ``` ros_msg = ROSMessage( topic="/accel", timestamp=17000, msg_type="geometry_msgs/msg/AccelStamped", data= { "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "accel": { "linear": {"x": 5.0, "y": 0.0, "z": 0.0}, "angular": {"x": 0.0, "y": 0.0, "z": 1.0} }, "covariance": [0.1] * 36 } # Automatically resolves to a flat Mosaico Acceleration with attached metadata mosaico_acceleration = AccelAdapter.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 `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. Example ``` ros_data= { "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "accel": { "linear": {"x": 5.0, "y": 0.0, "z": 0.0}, "angular": {"x": 0.0, "y": 0.0, "z": 1.0} }, "covariance": [0.1] * 36 } # Automatically resolves to a flat Mosaico Acceleration with attached metadata mosaico_acceleration = AccelAdapter.from_dict(ros_data) ``` 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. Example ``` ros_msg = ROSMessage( topic="/vector3", timestamp=17000, msg_type="geometry_msgs/msg/Vector3Stamped", data= { "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "vector": {"x": 5.0, "y": 0.0, "z": 0.0}, } # Automatically resolves to a flat Mosaico Vector3 with attached metadata mosaico_vector3 = Vector3Adapter.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 `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`. Example ``` ros_data= { "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "vector": {"x": 5.0, "y": 0.0, "z": 0.0}, } # Automatically resolves to a flat Mosaico Vector3d with attached metadata mosaico_vector3d = Vector3Adapter.from_dict(ros_data) ``` 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. Example ``` ros_msg = ROSMessage( topic="/point", timestamp=17000, msg_type="geometry_msgs/msg/PointStamped", data= { "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "point": {"x": 5.0, "y": 0.0, "z": 0.0}, } # Automatically resolves to a flat Mosaico Point3d with attached metadata mosaico_point3d = PointAdapter.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 `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`. Strategy * **Recurse**: If a 'point' key is found, dive deeper into the structure. * **Leaf Node**: At the base level, map 'x', 'y' and 'z' to `Point3d`. Example ``` ros_data= { "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "point": {"x": 5.0, "y": 0.0, "z": 0.0}, } # Automatically resolves to a flat Mosaico Point3d with attached metadata mosaico_point3d = PointAdapter.from_dict(ros_data) ``` 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. Example ``` ros_msg = ROSMessage( topic="/quaternion", timestamp=17000, msg_type="geometry_msgs/msg/QuaternionStamped", data= { "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "quaternion": {"x": 5.0, "y": 0.0, "z": 0.0, "w": 1.0}, } # Automatically resolves to a flat Mosaico Quaternion with attached metadata mosaico_quaternion = QuaternionAdapter.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 `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`. Strategy * **Recurse**: If a 'quaternion' key is found, dive deeper into the structure. * **Leaf Node**: At the base level, map 'x', 'y', 'z' and 'w' to `Quaternion`. Example ``` ros_data= { "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "quaternion": {"x": 5.0, "y": 0.0, "z": 0.0, "w": 1.0}, } # Automatically resolves to a flat Mosaico Quaternion with attached metadata mosaico_quaternion = QuaternionAdapter.from_dict(ros_data) ``` 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. Example ``` ros_msg = ROSMessage( topic="/transform", timestamp=17000, msg_type="geometry_msgs/msg/TransformStamped", data= { "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "transform": {"translation": {"x": 5.0, "y": 0.0, "z": 0.0}, "rotation": {"x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0}}, } # Automatically resolves to a flat Mosaico Transform with attached metadata mosaico_transform = TransformAdapter.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 `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. Strategy * **Recurse**: If a 'transform' key is found, dive deeper into the structure. * **Leaf Node**: At the base level, map 'translation' and 'rotation' to `Transform`. Example ``` ros_data= { "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "transform": {"translation": {"x": 5.0, "y": 0.0, "z": 0.0}, "rotation": {"x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0}}, } # Automatically resolves to a flat Mosaico Transform with attached metadata mosaico_transform = TransformAdapter.from_dict(ros_data) ``` 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. Example ``` ros_msg = ROSMessage( topic="/wrench", timestamp=17000, msg_type="geometry_msgs/msg/WrenchStamped", data= { "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "wrench": {"force": {"x": 5.0, "y": 0.0, "z": 0.0}, "torque": {"x": 0.0, "y": 0.0, "z": 0.0}}, } # Automatically resolves to a flat Mosaico ForceTorque with attached metadata mosaico_wrench = WrenchAdapter.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 `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. Strategy * **Recurse**: If a 'wrench' key is found, dive deeper into the structure. * **Leaf Node**: At the base level, map 'force' and 'torque' to `ForceTorque`. Example ``` ros_data= { "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "wrench": {"force": {"x": 5.0, "y": 0.0, "z": 0.0}, "torque": {"x": 0.0, "y": 0.0, "z": 0.0}}, } # Automatically resolves to a flat Mosaico ForceTorque with attached metadata mosaico_wrench = WrenchAdapter.from_dict(ros_data) ``` #### 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. --- ## 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` Example ``` ros_msg = ROSMessage( timestamp=17000, topic="/odometry", msg_type="nav_msgs/msg/Odometry", data= { "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "pose": { "position": {"x": 1.0, "y": 2.0, "z": 0.0}, "orientation": {"x": 0, "y": 0, "z": 0, "w": 1} }, "twist": { "linear": {"x": 0.0, "y": 0.0, "z": 0.0}, "angular": {"x": 0.0, "y": 0.0, "z": 0.0} }, "child_frame_id": "base_link" } ) # Automatically resolves to a flat Mosaico MotionState with attached metadata mosaico_odometry = OdometryAdapter.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 `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. Example ``` ros_data= { "header": {"frame_id": "map", "stamp": {"sec": 17000, "nanosec": 0}}, "pose": { "position": {"x": 1.0, "y": 2.0, "z": 0.0}, "orientation": {"x": 0, "y": 0, "z": 0, "w": 1} }, "twist": { "linear": {"x": 0.0, "y": 0.0, "z": 0.0}, "angular": {"x": 0.0, "y": 0.0, "z": 0.0} }, "child_frame_id": "base_link" } # Automatically resolves to a flat Mosaico MotionState with attached metadata mosaico_odometry = OdometryAdapter.from_dict(ros_data) ``` 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. --- ## 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` Example ``` ros_msg = ROSMessage( timestamp=17000, topic="/camera_info", msg_type="sensor_msgs/msg/CameraInfo", data= { "height": 480, "width": 640, "binning_x": 1, "binning_y": 1, "roi": { "x_offset": 0, "y_offset": 0, "height": 480, "width": 640, "do_rectify": False, }, "distortion_model": "plumb_bob", "d": [0.0, 0.0, 0.0, 0.0, 0.0], "k": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], "p": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], "r": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], } ) # Automatically resolves to a flat Mosaico CameraInfo with attached metadata mosaico_camera_info = CameraInfoAdapter.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 `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. Example ``` ros_data= { "height": 480, "width": 640, "binning_x": 1, "binning_y": 1, "roi": { "x_offset": 0, "y_offset": 0, "height": 480, "width": 640, "do_rectify": False, }, "distortion_model": "plumb_bob", "d": [0.0, 0.0, 0.0, 0.0, 0.0], "k": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], "p": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], "r": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], } # Automatically resolves to a flat Mosaico CameraInfo with attached metadata mosaico_camera_info = CameraInfoAdapter.from_dict(ros_data) ``` 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` Example ``` ros_msg = ROSMessage( timestamp=17000, topic="/gps_status", msg_type="sensor_msgs/msg/NavSatFix", data= { "status": 0, "service": 1, } ) # Automatically resolves to a flat Mosaico GPSStatus with attached metadata mosaico_gps_status = NavSatStatusAdapter.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 `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. Example ``` ros_data= { "status": 0, "service": 1, } # Automatically resolves to a flat Mosaico GPSStatus with attached metadata mosaico_gps_status = NavSatStatusAdapter.from_dict(ros_data) ``` 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` Example ``` ros_msg = ROSMessage( timestamp=17000, topic="/gps", msg_type="sensor_msgs/msg/NavSatFix", data= { "latitude": 45.5, "longitude": -122.5, "altitude": 100.0, "status": { "status": 0, "service": 1, }, } ) # Automatically resolves to a flat Mosaico GPS with attached metadata mosaico_gps = GPSAdapter.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 `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. Example ``` ros_data= { "latitude": 45.5, "longitude": -122.5, "altitude": 100.0, "status": { "status": 0, "service": 1, }, } # Automatically resolves to a flat Mosaico GPS with attached metadata mosaico_gps = GPSAdapter.from_dict(ros_data) ``` 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` Example ``` ros_msg = ROSMessage( timestamp=17000, topic="/imu", msg_type="sensor_msgs/msg/Imu", data= { "linear_acceleration": {"x": 0.0, "y": 0.0, "z": 0.0}, "angular_velocity": {"x": 0.0, "y": 0.0, "z": 0.0}, "orientation": {"x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0}, "orientation_covariance": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], "linear_acceleration_covariance": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], "angular_velocity_covariance": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], "header": {"seq": 0, "stamp": {"sec": 0, "nanosec": 0}, "frame_id": "robot_link"}, } ) # Automatically resolves to a flat Mosaico IMU with attached metadata mosaico_imu = IMUAdapter.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 `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. Example ``` ros_data= { "linear_acceleration": {"x": 0.0, "y": 0.0, "z": 0.0}, "angular_velocity": {"x": 0.0, "y": 0.0, "z": 0.0}, "orientation": {"x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0}, "orientation_covariance": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], "linear_acceleration_covariance": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], "angular_velocity_covariance": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], "header": {"seq": 0, "stamp": {"sec": 0, "nanosec": 0}, "frame_id": "robot_link"}, } # Automatically resolves to a flat Mosaico IMU with attached metadata mosaico_imu = IMUAdapter.from_dict(ros_data) ``` 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` Example ``` ros_msg = ROSMessage( timestamp=17000, topic="/gps/fix", msg_type="sensor_msgs/msg/GPSFix", data= { "sentence": "GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47", } ) # Automatically resolves to a flat Mosaico GPS with attached metadata mosaico_gps = NMEASentenceAdapter.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 `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. Example ``` ros_data= { "sentence": "GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47", } # Automatically resolves to a flat Mosaico NMEASentence with attached metadata mosaico_nmea_sentence = NMEASentenceAdapter.from_dict(ros_data) ``` 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` Example ``` ros_msg = ROSMessage( timestamp=17000, topic="/image", msg_type="sensor_msgs/msg/Image", data= { "data": [...], "width": 1, "height": 1, "step": 4, "encoding": "bgr8", } ) # Automatically resolves to a flat Mosaico Image with attached metadata mosaico_image = ImageAdapter.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 `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. Example ``` ros_data= { "data": [...], "width": 1, "height": 1, "step": 4, "encoding": "bgr8", } # Automatically resolves to a flat Mosaico Image with attached metadata mosaico_image = ImageAdapter.from_dict(ros_data) ``` 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` Example ``` ros_msg = ROSMessage( timestamp=17000, topic="/compressed_image", msg_type="sensor_msgs/msg/CompressedImage", data= { "data": [...], "format": "jpeg", } ) # Automatically resolves to a flat Mosaico CompressedImage with attached metadata mosaico_compressed_image = CompressedImageAdapter.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 `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. Example ``` ros_data= { "data": [...], "format": "jpeg", } # Automatically resolves to a flat Mosaico CompressedImage with attached metadata mosaico_compressed_image = CompressedImageAdapter.from_dict(ros_data) ``` 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` Example ``` ros_msg = ROSMessage( timestamp=17000, topic="/roi", msg_type="sensor_msgs/RegionOfInterest", data= { "height": 1, "width": 1, "x_offset": 0, "y_offset": 0, } ) # Automatically resolves to a flat Mosaico ROI with attached metadata mosaico_roi = ROIAdapter.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 `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. Example ``` ros_data= { "height": 1, "width": 1, "x_offset": 0, "y_offset": 0, } # Automatically resolves to a flat Mosaico ROI with attached metadata mosaico_roi = ROIAdapter.from_dict(ros_data) ``` 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` Example ``` ros_msg = ROSMessage( timestamp=17000, topic="/battery_state", msg_type="sensor_msgs/msg/BatteryState", data= { "voltage": 12.6, "capacity": 100, "cell_temperature": 25, "cell_voltage": [12.6], "location": "battery", "charge": 100, "current": 0, "design_capacity": 100, "location": "battery", "percentage": 100, "power_supply_health": "good", "power_supply_status": "charging", "power_supply_technology": "li-ion", "present": True, "serial_number": "1234567890", "temperature": 25, } ) # Automatically resolves to a flat Mosaico BatteryState with attached metadata mosaico_battery_state = BatteryStateAdapter.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 `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. Example ``` ros_data= { "voltage": 12.6, "capacity": 100, "cell_temperature": 25, "cell_voltage": [12.6], "location": "battery", "charge": 100, "current": 0, "design_capacity": 100, "location": "battery", "percentage": 100, "power_supply_health": "good", "power_supply_status": "charging", "power_supply_technology": "li-ion", "present": True, "serial_number": "1234567890", "temperature": 25, } # Automatically resolves to a flat Mosaico BatteryState with attached metadata mosaico_battery_state = BatteryStateAdapter.from_dict(ros_data) ``` 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` Example ``` ros_msg = ROSMessage( timestamp=17000, topic="/joint_states", msg_type="sensor_msgs/msg/JointState", data={ "header": { "stamp": { "sec": 17000, "nanosec": 0, }, "frame_id": "", }, "name": ["joint1", "joint2"], "position": [0.0, 0.0], "velocity": [0.0, 0.0], "effort": [0.0, 0.0], }, ) # Automatically resolves to a flat Mosaico RobotJoint with attached metadata mosaico_robot_joint = RobotJointAdapter.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 `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. Example ``` ros_data={ "header": { "stamp": { "sec": 17000, "nanosec": 0, }, "frame_id": "", }, "name": ["joint1", "joint2"], "position": [0.0, 0.0], "velocity": [0.0, 0.0], "effort": [0.0, 0.0], } # Automatically resolves to a flat Mosaico RobotJoint with attached metadata mosaico_robot_joint = RobotJointAdapter.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. ### PointCloudAdapter ¶ Bases: `ROSAdapterBase[PointCloud2]` ``` Adapter for translating ROS PointCloud2 messages to Mosaico `PointCloud2`. **Supported ROS Types:** - [`sensor_msgs/msg/PointCloud2`](https://docs.ros2.org/foxy/api/sensor_msgs/msg/PointCloud2.html) Example: ```python 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": b'€?' # x=1.0 b'@' # y=2.0 b'@@' # z=3.0 b'€?' # x=1.0 b'@' # y=2.0 b'@@' # z=3.0 b'€?' # x=1.0 b'@' # y=2.0 b'@@', # z=3.0 "is_dense": True, } ) # Automatically resolves to a flat Mosaico PointCloud2 with attached metadata mosaico_point_cloud = PointCloudAdapter.translate(ros_msg) ``` ``` #### from\_dict `classmethod` ¶ ``` from_dict(ros_data) ``` Converts the raw dictionary data into the specific Mosaico type. Example ```python 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": b'€?' # x=1.0 b'@' # y=2.0 b'@@' # z=3.0 } #### 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. --- ## 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. Architecture * `_ROS_MSGTYPE_MSCO_BASE_TYPE_MAP` defines the relationship between a ROS message type string (e.g., "std\_msgs/msg/String") and the corresponding Mosaico Serializable class (e.g., `String`). * `GenericStdAdapter` implements the common `translate` and `from_dict` logics shared by all standard types (wrapping the 'data' field). * At module load time, we iterate through the mapping, dynamically create a unique subclass of `GenericStdAdapter` for each type and register it in the ROSBridge. ### 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: 1. **Injected** with a specific `ros_msgtype` (e.g., `"std_msgs/msg/String"`). 2. **Injected** with a specific target `__mosaico_ontology_type__` (e.g., `String`). 3. **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. Example ``` # Logic effectively generated by the factory: class StringStdAdapter(GenericStdAdapter): ros_msgtype = "std_msgs/msg/String" __mosaico_ontology_type__ = String # Usage within the Bridge: ros_msg = ROSMessage( timestamp=1707760800.123456789, topic="/log", msg_type="std_msgs/msg/String", data={"data": "System OK"} ) mosaico_string = StringStdAdapter.translate(ros_msg) ``` #### 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. --- ## 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` Example ``` ros_msg = ROSMessage( timestamp=17000, topic="/tf", msg_type="tf2_msgs/msg/TFMessage", data={ "transforms": [ { "header": { "stamp": { "sec": 17000, "nanosec": 0, }, "frame_id": "map", "child_frame_id": "base_link", }, "transform": { "translation": { "x": 0.0, "y": 0.0, "z": 0.0, }, "rotation": { "x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0, }, }, } ] }, ) # Automatically resolves to a flat Mosaico FrameTransform with attached metadata mosaico_frame_transform = FrameTransformAdapter.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 `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. Example ``` ros_data={ "transforms": [ { "header": { "stamp": { "sec": 17000, "nanosec": 0, }, "frame_id": "map", "child_frame_id": "base_link", }, "transform": { "translation": { "x": 0.0, "y": 0.0, "z": 0.0, }, "rotation": { "x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0, }, }, } ] } # Automatically resolves to a flat Mosaico FrameTransform with attached metadata mosaico_frame_transform = FrameTransformAdapter.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. --- 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 Note This model is still not included in the default ontology of Mosaico and is defined specifically for the ros-bridge module ### voltage `instance-attribute` ¶ ``` voltage ``` The battery voltage value ### temperature `instance-attribute` ¶ ``` temperature ``` The optional battery temperature in °C ### current `instance-attribute` ¶ ``` current ``` The optional battery current in A ### charge `instance-attribute` ¶ ``` charge ``` The optional battery charge in Ah ### capacity `instance-attribute` ¶ ``` capacity ``` The optional battery capacity in Ah ### design\_capacity `instance-attribute` ¶ ``` design_capacity ``` The optional battery design capacity in Ah ### percentage `instance-attribute` ¶ ``` percentage ``` The battery percentage in % ### power\_supply\_status `instance-attribute` ¶ ``` power_supply_status ``` The charging status ### power\_supply\_health `instance-attribute` ¶ ``` power_supply_health ``` The battery health ### power\_supply\_technology `instance-attribute` ¶ ``` power_supply_technology ``` The battery technology ### present `instance-attribute` ¶ ``` present ``` The battery presence ### location `instance-attribute` ¶ ``` location ``` The battery location (like the slot) ### serial\_number `instance-attribute` ¶ ``` serial_number ``` The battery serial number ### cell\_voltage `class-attribute` `instance-attribute` ¶ ``` cell_voltage = None ``` The battery cells voltage ### cell\_temperature `class-attribute` `instance-attribute` ¶ ``` cell_temperature = None ``` 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ## mosaicolabs.ros\_bridge.data\_ontology.FrameTransform ¶ Bases: `Serializable` Represents a list of transformations between two coordinates. modeled after: tf2\_msgs/msg/TFMessage Note This model is not included in the default ontology of Mosaico and is defined specifically for the ros-bridge module ### transforms `instance-attribute` ¶ ``` transforms ``` 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ## mosaicolabs.ros\_bridge.data\_ontology.PointCloud2 ¶ Bases: `Serializable` Represents a point cloud in ROS2. modeled after: sensor\_msgs/msg/PointCloud2 Note This model is still not included in the default ontology of Mosaico and is defined specifically for the ros-bridge module ### height `instance-attribute` ¶ ``` height ``` The height of the point cloud. ### width `instance-attribute` ¶ ``` width ``` The width of the point cloud. ### fields `instance-attribute` ¶ ``` fields ``` The fields of the point cloud. ### is\_bigendian `instance-attribute` ¶ ``` is_bigendian ``` Whether the data is big-endian. ### point\_step `instance-attribute` ¶ ``` point_step ``` Length of a point in bytes. ### row\_step `instance-attribute` ¶ ``` row_step ``` Length of a row in bytes. ### data `instance-attribute` ¶ ``` data ``` The point cloud data. Expected size: row\_step \* height bytes. ### is\_dense `instance-attribute` ¶ ``` is_dense ``` 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` ## 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 `instance-attribute` ¶ ``` name ``` The name of the point field. ### offset `instance-attribute` ¶ ``` offset ``` The Offset from start of point struct. ### datatype `instance-attribute` ¶ ``` datatype ``` The data type of the point field, see `PointFieldDatatype`. ### count `instance-attribute` ¶ ``` count ``` 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 `__init_subclass__`. | **Practical Application: Topic Filtering** This method is particularly useful when constructing `QueryTopic` requests. By using the convenience method `QueryTopic.with_ontology_tag()`, you can filter topics by data type without hardcoding strings that might change. Example: ``` from mosaicolabs import MosaicoClient, Topic, IMU, QueryTopic with MosaicoClient.connect("localhost", 6726) as client: # Filter for a specific data value (using constructor) qresponse = client.query( QueryTopic( Topic.with_ontology_tag(IMU.ontology_tag()), ) ) # 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]}") ``` --- ## 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. Example ``` # Within an ingestion loop mosaico_msg = ROSBridge.from_ros_message(raw_ros_container) if mosaico_msg: writer.push(mosaico_msg) ``` 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. Example ``` from mosaicolabs.ros_bridge import register_default_adapter, ROSAdapterBase @register_default_adapter class MySensorAdapter(ROSAdapterBase): ros_msgtype = "sensor_msgs/msg/Temperature" # ... ``` 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/*`) to load only relevant data channels. * **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. Example ``` from rosbags.typesys import Stores from mosaicolabs.ros_bridge import ROSLoader, LoaderErrorPolicy # Initialize to read only IMU and GPS data from an MCAP file with ROSLoader( file_path="mission_01.mcap", topics=["/imu*", "/gps/fix"], typestore_name=Stores.ROS2_HUMBLE, error_policy=LoaderErrorPolicy.RAISE ) as loader: for msg, exc in loader: if not exc: print(f"Read {msg.msg_type} from {msg.topic}") ``` 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. | `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. Example ``` with ROSLoader(file_path="data.mcap", topics=["/sensors/*"]) as loader: # If the bag contains /sensors/imu and /sensors/gps, # this property returns ['/sensors/imu', '/sensors/gps'] print(f"Loading topics: {loader.topics}") ``` 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. Example ``` with ROSLoader(file_path="data.mcap") as loader: for topic, msg_type in zip(loader.topics, loader.msg_types): print(f"Topic {topic} requires schema: {msg_type}") ``` 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¶ 1. **Produced** by `ROSLoader` during bag iteration. 2. **Consumed** by `ROSBridge` to identify the correct adapter. 3. **Translated** by a `ROSAdapter` into a Mosaico `Message`. Example ``` # Manual construction (usually handled by the loader) msg = ROSMessage( bag_timestamp_ns=1625000000000000000, topic="/odom", msg_type="nav_msgs/msg/Odometry", data={"header": {...}, "pose": {...}} ) print(f"Processing {msg.msg_type} from {msg.topic}") if msg.header: print(f"Frame: {msg.header.frame_id}") ``` 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, ) ``` 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` | `Union[SessionLevelErrorPolicy, OnErrorPolicy]` | Behavior when an ingestion error occurs (Delete the partial sequence or Report the error). Default: `SessionLevelErrorPolicy.Report` Deprecated: `OnErrorPolicy` is deprecated since v0.3.0; use `SessionLevelErrorPolicy` instead. It will be removed in v0.4.0. | | `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 topics to filter, supporting glob patterns (e.g., ["/cam/\*"]). | | `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 | Example ``` from pathlib import Path from rosbags.typesys import Stores from mosaicolabs.enum import SessionLevelErrorPolicy from mosaicolabs.ros_bridge import ROSInjectionConfig config = ROSInjectionConfig( file_path=Path("recording.mcap"), sequence_name="test_drive_01", metadata={"environment": "urban", "vehicle": "robot_alpha"}, ros_distro=Stores.ROS2_FOXY, on_error=SessionLevelErrorPolicy.Delete, topics_on_error=TopicLevelErrorPolicy.Finalize, ) ``` ### 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 ``` A list of specific topics to filter (supports glob patterns). If None, all compatible 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. ### 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. ## 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:** 1. **Registry Initialization**: Pre-loads custom message definitions via the `ROSTypeRegistry`. 2. **Resource Management**: Opens the `ROSLoader` for file access and the `MosaicoClient` for networking. 3. **Stream Negotiation**: Creates a `SequenceWriter` on the server and opens individual `TopicWriter` streams. 4. **Adaptation Loop**: Iterates through ROS records, translates them via the `ROSBridge`, and pushes them to the server. Example ``` from mosaicolabs.ros_bridge import RosbagInjector, ROSInjectionConfig # Define configuration config = ROSInjectionConfig(file_path=Path("data.db3"), sequence_name="auto_ingest") # Initialize and run injector = RosbagInjector(config) injector.run() # This handles the full lifecycle including cleanup on failure ``` 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. Example ``` # Register a proprietary battery message for a specific distro ROSTypeRegistry.register( msg_type="limo_msgs/msg/BatteryState", source=Path("./msgs/BatteryState.msg"), store=Stores.ROS2_HUMBLE ) # Register a simple custom type globally using a raw string ROSTypeRegistry.register( msg_type="custom_msgs/msg/SimpleFlag", source="bool flag_active\nstring label" ) ``` 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`). Example ``` # Register all messages in a local workspace for ROS1 ROSTypeRegistry.register_directory( package_name="robot_logic", dir_path="./src/robot_logic/msg", store=Stores.ROS1_NOETIC ) ``` 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. ---