• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lunarlab-gatech / robotdataprocess / 21319512660

24 Jan 2026 06:20PM UTC coverage: 76.717% (+2.0%) from 74.672%
21319512660

Pull #10

github

DanielChaseButterfield
Apply transformation methods for odometry data
Pull Request #10: (v0.2) Prototype code for ROS2 Publishing, and new ImageDataOnDisk class

872 of 1215 new or added lines in 13 files covered. (71.77%)

2 existing lines in 1 file now uncovered.

1743 of 2272 relevant lines covered (76.72%)

1.53 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

76.15
/src/robotdataprocess/data_types/OdometryData.py
1
from __future__ import annotations
2✔
2

3
from ..conversion_utils import col_to_dec_arr, dec_arr_to_float_arr
2✔
4
import csv
2✔
5
from .Data import CoordinateFrame, Data, ROSMsgLibType
2✔
6
import decimal
2✔
7
from decimal import Decimal
2✔
8
from evo.core import geometry
2✔
9
import matplotlib.pyplot as plt
2✔
10
from ..ModuleImporter import ModuleImporter
2✔
11
import numpy as np
2✔
12
from numpy.typing import NDArray
2✔
13
import os
2✔
14
import pandas as pd
2✔
15
from .PathData import PathData
2✔
16
from pathlib import Path
2✔
17
from ..ros.Ros2BagWrapper import Ros2BagWrapper
2✔
18
from rosbags.rosbag2 import Reader as Reader2
2✔
19
from rosbags.typesys import Stores, get_typestore
2✔
20
from rosbags.typesys.store import Typestore
2✔
21
from scipy.spatial.transform import Rotation as R
2✔
22
from typeguard import typechecked
2✔
23
from typing import Union, List, Tuple, Any
2✔
24
import tqdm
2✔
25

26
PATH_SLICE_STEP = 40
2✔
27

28
@typechecked
2✔
29
class OdometryData(PathData):
2✔
30

31
    # Define odometry-specific data attributes
32
    child_frame_id: str
2✔
33
    poses: list # Saved nav_msgs/msg/Pose for rosbags
2✔
34
    poses_rclpy: list # Saved nav_msgs/msg/Pose for rclpy
2✔
35

36
    def __init__(self, frame_id: str, child_frame_id: str, timestamps: Union[np.ndarray, list], 
2✔
37
                 positions: Union[np.ndarray, list], orientations: Union[np.ndarray, list], frame: CoordinateFrame):
38
        
39
        # Copy initial values into attributes
40
        super().__init__(frame_id, timestamps, positions, orientations, frame)
2✔
41
        self.child_frame_id: str = child_frame_id
2✔
42
        self.poses: list = []
2✔
43
        self.poses_rclpy: list = []
2✔
44

45
        # Check to ensure that all arrays have same length
46
        if len(self.timestamps) != len(self.positions) or len(self.positions) != len(self.orientations):
2✔
47
            raise ValueError("Lengths of timestamp, position, and orientation arrays are not equal!")
2✔
48

49
    # =========================================================================
50
    # ============================ Class Methods ============================== 
51
    # =========================================================================  
52

53
    @classmethod
2✔
54
    def from_ros2_bag(cls, bag_path: Union[Path, str], odom_topic: str, frame: CoordinateFrame):
2✔
55
        """
56
        Creates a class structure from a ROS2 bag file with an Odometry topic.
57

58
        Args:
59
            bag_path (Path | str): Path to the ROS2 bag file.
60
            odom_topic (str): Topic of the Odometry messages.
61
        Returns:
62
            OdometryData: Instance of this class.
63
        """
64

65
        # Get topic message count and typestore
66
        bag_wrapper = Ros2BagWrapper(bag_path, None)
2✔
67
        typestore: Typestore = bag_wrapper.get_typestore()
2✔
68
        num_msgs: int = bag_wrapper.get_topic_count(odom_topic)
2✔
69
        
70
        # Pre-allocate arrays (memory-mapped or otherwise)
71
        timestamps_np = np.zeros(num_msgs, dtype=Decimal)
2✔
72
        positions_np = np.zeros((num_msgs, 3), dtype=Decimal)
2✔
73
        orientations_np = np.zeros((num_msgs, 4), dtype=Decimal)
2✔
74

75
        # Setup tqdm bar & counter
76
        pbar = tqdm.tqdm(total=num_msgs, desc="Extracting Odometry...", unit=" msgs")
2✔
77
        i = 0
2✔
78

79
        # Extract the odometry information
80
        frame_id, child_frame_id = None, None
2✔
81
        with Reader2(str(bag_path)) as reader:
2✔
82

83
            # Extract frames from first message
84
            connections = [x for x in reader.connections if x.topic == odom_topic]
2✔
85
            for conn, timestamp, rawdata in reader.messages(connections=connections):  
2✔
86
                msg = typestore.deserialize_cdr(rawdata, conn.msgtype)
2✔
87
                frame_id = msg.header.frame_id
2✔
88
                child_frame_id = msg.child_frame_id
2✔
89
                break
2✔
90

91
            # Extract individual message data
92
            connections = [x for x in reader.connections if x.topic == odom_topic]
2✔
93
            for conn, timestamp, rawdata in reader.messages(connections=connections):
2✔
94
                msg = typestore.deserialize_cdr(rawdata, conn.msgtype)
2✔
95
                
96
                timestamps_np[i] = bag_wrapper.extract_timestamp(msg)
2✔
97
                pos = msg.pose.pose.position
2✔
98
                positions_np[i] = np.array([Decimal(pos.x), Decimal(pos.y), Decimal(pos.z)])
2✔
99
                ori = msg.pose.pose.orientation
2✔
100
                orientations_np[i] = np.array([Decimal(ori.x), Decimal(ori.y), Decimal(ori.z), Decimal(ori.w)])
2✔
101

102
                # NOTE: Doesn't support Twist information currently
103

104
                # Increment the count
105
                i += 1
2✔
106
                pbar.update(1)
2✔
107

108
        # Create an OdometryData class
109
        return cls(frame_id, child_frame_id, timestamps_np, positions_np, orientations_np, frame)
2✔
110
    
111
    @classmethod
2✔
112
    def from_csv(cls, csv_path: Union[Path, str], frame_id: str, child_frame_id: str, frame: CoordinateFrame,          
2✔
113
                 header_included: bool, column_to_data: Union[List[int], None] = None, 
114
                 separator: Union[str, None] = None, filter: Union[Tuple[str, str], None] = None,
115
                 ts_in_ns: bool = False, reorder_data: bool = False):
116
        """
117
        Creates a class structure from a csv file.
118

119
        Args:
120
            csv_path (Path | str): Path to the CSV file.
121
            frame_id (str): The frame that this odometry is relative to.
122
            child_frame_id (str): The frame whose pose is represented by this odometry.
123
            frame (CoordinateFrame): The coordinate system convention of this data.
124
            header_included (bool): If this csv file has a header, so we can remove it.
125
            column_to_data (list[int]): Tells the algorithms which columns in the csv contain which
126
                of the following data: ['timestamp', 'x', 'y', 'z', 'qw', 'qx', 'qy', 'qz']. Thus, 
127
                index 0 of column_to_data should be the column that timestamp data is found in the 
128
                csv file. Set to None to use [0,1,2,3,4,5,6,7].
129
            separator (str | None): The separator used in the csv file. If None, will use a comma by default.
130
            filter: A tuple of (column_name, value), where only rows with column_name == value will be kept. If
131
                csv file has no headers, then `column_name` should be the index of the column as a string.
132
            ts_in_ns (bool): If True, assumes timestamps are in nanoseconds and converts to seconds. Otherwise,
133
                assumes timestamps are already in seconds.
134
            reorder_data (bool): If True, reorders the data to be in order of timestamps. If False, 
135
                assumes data is already ordered by timestamp.
136

137
        Returns:
138
            OdometryData: Instance of this class.
139
        """
140

141
        # If column_to_data is None, assume default
142
        if column_to_data is None:
2✔
143
            column_to_data = [0,1,2,3,4,5,6,7]
2✔
144
        else:
145
            # Check column_to_data values are valid
146
            assert np.all(np.array(column_to_data) >= 0)
2✔
147
            assert len(column_to_data) == 8
2✔
148

149
        # Read the csv file
150
        header = 0 if header_included else None
2✔
151
        df1 = pd.read_csv(str(csv_path), header=header, index_col=False, sep=separator, engine='python')
2✔
152

153
        # Rename columns to standard names
154
        rename_dict = {}
2✔
155
        desired_data = ['timestamp', 'x', 'y', 'z', 'qw', 'qx', 'qy', 'qz']
2✔
156
        for j, ind in enumerate(column_to_data):
2✔
157
            rename_dict[df1.columns[ind]] = desired_data[j]
2✔
158
        df1 = df1.rename(columns=rename_dict)
2✔
159

160
        # Using the filter if provided, remove unwanted rows
161
        if filter is not None:
2✔
162
            df1 = df1[df1[filter[0]] == filter[1]]
2✔
163

164
        # Convert columns to NDArray[Decimal]
165
        timestamps_np = np.array([Decimal(str(ts)) for ts in df1['timestamp']], dtype=object)
2✔
166
        positions_np = np.array([[Decimal(str(x)), Decimal(str(y)), Decimal(str(z))] 
2✔
167
                                 for x, y, z in zip(df1['x'], df1['y'], df1['z'])], dtype=object)
168
        orientations_np = np.array([[Decimal(str(qx)), Decimal(str(qy)), Decimal(str(qz)), Decimal(str(qw))]
2✔
169
                                    for qx, qy, qz, qw in zip(df1['qx'], df1['qy'], df1['qz'], df1['qw'])], dtype=object)
170
        
171
        # If timestamps are in ns, convert to s
172
        if ts_in_ns:
2✔
173
            timestamps_np = timestamps_np / Decimal('1e9')
2✔
174

175
        # Reorder the data if needed
176
        if reorder_data:
2✔
NEW
177
            print("Warning: This code is not tested yet!")
×
NEW
178
            sort_indices = np.argsort(timestamps_np)
×
NEW
179
            timestamps_np = timestamps_np[sort_indices]
×
NEW
180
            positions_np = positions_np[sort_indices]
×
NEW
181
            orientations_np = orientations_np[sort_indices]
×
182

183
        # Create an OdometryData class
184
        return cls(frame_id, child_frame_id, timestamps_np, positions_np, orientations_np, frame)
2✔
185
    
186
    @classmethod
2✔
187
    def from_txt_file(cls, file_path: Union[Path, str], frame_id: str, child_frame_id: str, frame: CoordinateFrame,
2✔
188
                      header_included: bool, column_to_data: Union[List[int], None] = None):
189
        """
190
        Creates and OdometryData class from a text file.
191

192
        Args:
193
            file_path (Path | str): Path to the file containing the odometry data.
194
            frame_id (str): The frame where this odometry is relative to.
195
            child_frame_id (str): The frame whose pose is represented by this odometry.
196
            frame (CoordinateFrame): The coordinate system convention of this data.
197
            header_included (bool): If this text file has a header, so we can remove it.
198
            column_to_data (list[int]): Tells the algorithms which columns in the text file contain which
199
                of the following data: ['timestamp', 'x', 'y', 'z', 'qw', 'qx', 'qy', 'qz']. Thus, 
200
                index 0 of column_to_data should be the column that timestamp data is found in the 
201
                text file. Set to None to use [0,1,2,3,4,5,6,7].
202
        Returns:
203
            OdometryData: Instance of this class.
204
        """
205
        
206
        # If column_to_data is None, assume default
207
        if column_to_data is None:
2✔
208
            column_to_data = [0,1,2,3,4,5,6,7]
2✔
209
        else:
210
            # Check column_to_data values are valid
211
            assert np.all(np.array(column_to_data) >= 0)
2✔
212
            assert len(column_to_data) == 8
2✔
213

214
        # Count the number of lines in the file
215
        line_count = 0
2✔
216
        with open(str(file_path), 'r') as file:
2✔
217
            for _ in file: 
2✔
218
                line_count += 1
2✔
219

220
        # Setup arrays to hold data
221
        timestamps_np = np.zeros((line_count), dtype=object)
2✔
222
        positions_np = np.zeros((line_count, 3), dtype=object)
2✔
223
        orientations_np = np.zeros((line_count, 4), dtype=object)
2✔
224

225
        # Open the txt file and read in the data
226
        with open(str(file_path), 'r') as file:
2✔
227
            for i, line in enumerate(file):
2✔
228
                line_split = line.split(' ')
2✔
229
                timestamps_np[i] = line_split[column_to_data[0]]
2✔
230
                positions_np[i] = np.array([line_split[column_to_data[1]], line_split[column_to_data[2]], line_split[column_to_data[3]]])
2✔
231
                orientations_np[i] =  np.array([line_split[column_to_data[5]], line_split[column_to_data[6]], line_split[column_to_data[7]], line_split[column_to_data[4]]])
2✔
232

233
        # Remove the header
234
        if header_included:
2✔
235
            timestamps_np = timestamps_np[1:]
2✔
236
            positions_np = positions_np[1:]
2✔
237
            orientations_np = orientations_np[1:]
2✔
238
        
239
        # Create an OdometryData class
240
        return cls(frame_id, child_frame_id, timestamps_np, positions_np, orientations_np, frame)
2✔
241
    
242
    # =========================================================================
243
    # ========================= Manipulation Methods ========================== 
244
    # =========================================================================  
245
    
246
    def add_folded_guassian_noise_to_position(self, xy_noise_std_per_frame: float,
2✔
247
            z_noise_std_per_frame: float):
248
        """
249
        This method simulates odometry drift by adding folded gaussian noise
250
        to the odometry positions on a per frame basis. It also accumulates
251
        it over time. NOTE: It completely ignores the timestamps, and the "folded
252
        guassian noise" distribution stds might not align with the stds of the 
253
        guassian used internally, so this is not a robust function at all.
254

255
        Args:
256
            xy_noise_std_per_frame (float): Standard deviation of the gaussian 
257
                distribution for xy, whose output is then run through abs().
258
            z_noise_std_per_frame (float): Same as above, but for z.
259
        """
260

261
        # Track cumulative noise for each field
262
        cumulative_noise_pos = {'x': 0.0, 'y': 0.0, 'z': 0.0}
×
263

264
        # For each position
265
        for i in range(len(self.timestamps)):
×
266

267
            # Sample noise and accumulate
268
            noise_pos = {'x': np.random.normal(0, xy_noise_std_per_frame),
×
269
                        'y': np.random.normal(0, xy_noise_std_per_frame),
270
                        'z': np.random.normal(0, z_noise_std_per_frame)}
271
            for key in cumulative_noise_pos:
×
272
                cumulative_noise_pos[key] += abs(noise_pos[key])
×
273

274
            # Update positions
275
            self.positions[i][0] += Decimal(cumulative_noise_pos['x'])
×
276
            self.positions[i][1] += Decimal(cumulative_noise_pos['y'])
×
277
            self.positions[i][2] += Decimal(cumulative_noise_pos['z'])
×
278

279
        # Empty poses as they might need to be recalculated
NEW
280
        self.poses = []
×
NEW
281
        self.poses_rclpy = []
×
282

283
    def shift_position(self, x_shift: float, y_shift: float, z_shift: float):
2✔
284
        """
285
        Shifts the positions of the odometry.
286

287
        Args:
288
            x_shift (float): Shift in x-axis.
289
            y_shift (float): Shift in y_axis.
290
            z_shift (float): Shift in z_axis.
291
        """
292
        self.positions[:,0] += Decimal(x_shift)
×
293
        self.positions[:,1] += Decimal(y_shift)
×
294
        self.positions[:,2] += Decimal(z_shift)
×
295

296
        # Empty poses as they might need to be recalculated
NEW
297
        self.poses = []
×
NEW
298
        self.poses_rclpy = []
×
299

300
    def shift_to_start_at_identity(self):
2✔
301
        """
302
        Alter the positions and orientations based so that the first pose 
303
        starts at Identity.
304
        """
305

306
        # Get pose of first robot position w.r.t world
307
        R_o = R.from_quat(self.orientations[0]).as_matrix()
2✔
308
        T_o = np.expand_dims(self.positions[0], axis=1)
2✔
309
        
310
        # Calculate the inverse (pose of world w.r.t first robot location)
311
        R_inv = R_o.T
2✔
312

313
        # Rotate positions and orientations
314
        self.positions = (R_inv @ (self.positions.T - T_o).astype(float)).T
2✔
315
        for i in range(self.len()):
2✔
316
            self.orientations[i] = R.from_matrix((R_inv @ R.from_quat(self.orientations[i]).as_matrix())).as_quat()
2✔
317

318
        # Convert back to decimal array
319
        self.positions = col_to_dec_arr(self.positions)
2✔
320
        self.orientations = col_to_dec_arr(self.orientations)
2✔
321

322
        # Empty poses as they might need to be recalculated
323
        self.poses = []
2✔
324
        self.poses_rclpy = []
2✔
325

326
    def crop_data(self, start: Decimal, end: Decimal):
2✔
327
        """ Will crop the data so only values within [start, end] inclusive are kept. """
328

329
        # Create boolean mask of data to keep
330
        mask = (self.timestamps >= start) & (self.timestamps <= end)
2✔
331

332
        # Apply mask
333
        self.timestamps = self.timestamps[mask]
2✔
334
        self.positions = self.positions[mask]
2✔
335
        self.orientations = self.orientations[mask]
2✔
336

337
        # Empty poses as they might need to be recalculated
338
        self.poses = []
2✔
339
        self.poses_rclpy = []
2✔
340

341
    # =========================================================================
342
    # ============================ Export Methods ============================= 
343
    # =========================================================================  
344

345
    def to_csv(self, csv_path: Union[Path, str], write_header: bool = True):
2✔
346
        """
347
        Writes the odometry data to a .csv file. Note that data will be
348
        saved in the following order: timestamp, pos.x, pos.y, pos.z,
349
        ori.w, ori.x, ori.y, ori.z. Timestamp is in seconds.
350

351
        Args:
352
            csv_path (Path | str): Path to the output csv file.
353
            odom_topic (str): Topic of the Odometry messages.
354
            write_header (bool): If false, skip the header row.
355
        Returns:
356
            OdometryData: Instance of this class.
357
        """
358

359
        # setup tqdm 
360
        pbar = tqdm.tqdm(total=None, desc="Saving to csv... ", unit=" frames")
2✔
361

362
        # Check that file path doesn't already exist
363
        file_path = Path(csv_path)
2✔
364
        if os.path.exists(file_path):
2✔
365
            raise ValueError(f"Output file already exists: {file_path}")
×
366
        
367
        # Open csv file
368
        with open(file_path, 'w', newline='') as csvfile:
2✔
369
            writer = csv.writer(csvfile, delimiter=',')
2✔
370

371
            # Write the first row
372
            if write_header:
2✔
373
                writer.writerow(['timestamp', 'x', 'y', 'z', 'qw', 'qx', 'qy', 'qz'])
2✔
374
                
375
            # Write message data to the csv file
376
            for i in range(len(self.timestamps)):
2✔
377
                writer.writerow([str(self.timestamps[i]), 
2✔
378
                    str(self.positions[i][0]), str(self.positions[i][1]), str(self.positions[i][2]),
379
                    str(self.orientations[i][3]), str(self.orientations[i][0]), str(self.orientations[i][1]), 
380
                    str(self.orientations[i][2])])
381
                pbar.update(1)
2✔
382

383
    # =========================================================================
384
    # =========================== Frame Conversions =========================== 
385
    # ========================================================================= 
386
    def to_FLU_frame(self):
2✔
387
        # If we are already in the FLU frame, return
388
        if self.frame == CoordinateFrame.FLU:
2✔
389
            print("Data already in FLU coordinate frame, returning...")
2✔
390
            return
2✔
391

392
        # If in NED, run the conversion
393
        elif self.frame == CoordinateFrame.NED:
2✔
394
            # Define the rotation matrix
395
            R_NED = np.array([[1,  0,  0],
2✔
396
                              [0, -1,  0],
397
                              [0,  0, -1]])
398

399
            # Do a change of basis to update the frame
400
            self._convert_frame(R_NED)
2✔
401

402
            # Update frame
403
            self.frame = CoordinateFrame.FLU
2✔
404

405
            # Empty poses as they might need to be recalculated
406
            self.poses = []
2✔
407
            self.poses_rclpy = []
2✔
408

409
        # Otherwise, throw an error
410
        else:
411
            raise RuntimeError(f"OdometryData class is in an unexpected frame: {self.frame}!")
2✔
412
    
413
    def apply_transformation_left_side(self, H: np.ndarray):
2✔
414
        """
415
        Applies a rigid-body transformation to the entire path.
416
        In terms of transfomration matricies, this multiplies this odometry
417
        on the left side.
418

419
        Args:
420
            H: The 4x4 transformation matrix
421
        """ 
422

423
        # Apply the transformation
424
        H_self = np.eye(4).reshape(1, 4, 4).repeat(self.len(), axis=0)  # shape (N,4,4)
2✔
425
        H_self[:, :3, :3] = R.from_quat(self.orientations).as_matrix()    
2✔
426
        H_self[:, :3, 3] = self.positions
2✔
427
        H_output = H @ H_self
2✔
428

429
        # Extract results and save
430
        self.positions = H_output [:, :3, 3]
2✔
431
        self.orientations = R.from_matrix(H_output[:, :3, :3]).as_quat()      
2✔
432

433
        # Empty poses as they might need to be recalculated
434
        self.poses = []
2✔
435
        self.poses_rclpy = []
2✔
436

437
    def apply_transformation_right_side(self, H: np.ndarray):
2✔
438
        """
439
        Applies a rigid-body transformation to the entire path.
440
        In terms of transformation matrices, this multiplies this odometry
441
        on the right side (row-vector convention).
442

443
        Args:
444
            H: The 4x4 transformation matrix
445
        """ 
446

447
        # Apply the transformation
448
        H_self = np.eye(4).reshape(1, 4, 4).repeat(self.len(), axis=0)  # shape (N,4,4)
2✔
449
        H_self[:, :3, :3] = R.from_quat(self.orientations).as_matrix()    
2✔
450
        H_self[:, :3, 3] = self.positions
2✔
451
        H_output = H_self @ H
2✔
452

453
        # Extract results and save
454
        self.positions = H_output [:, :3, 3]
2✔
455
        self.orientations = R.from_matrix(H_output[:, :3, :3]).as_quat()      
2✔
456

457
        # Empty poses as they might need to be recalculated
458
        self.poses = []
2✔
459
        self.poses_rclpy = []
2✔
460

461
    def _convert_frame(self, R_frame: np.ndarray):
2✔
462
        """ Uses a change of basis to update the positions and orientations. """
463
        R_frame_Q = R.from_matrix(R_frame)
2✔
464
        self.positions = (R_frame @ self.positions.T).T
2✔
465
        self._ori_change_of_basis(R_frame_Q)
2✔
466

467
        # Empty poses as they might need to be recalculated
468
        self.poses = []
2✔
469
        self.poses_rclpy = []
2✔
470

471
    def _ori_apply_rotation(self, R_i: R):
2✔
472
        """ Applies a rotation (not a change of basis) to orientations, thus stays in the same frame. """
473
        for i in range(self.len()):
2✔
474
            self.orientations[i] = (R_i * R.from_quat(self.orientations[i])).as_quat()
2✔
475

476
        # Empty poses as they might need to be recalculated
477
        self.poses = []
2✔
478
        self.poses_rclpy = []
2✔
479

480
    def _ori_change_of_basis(self, R_i: R):
2✔
481
        """ Applies a change of basis to orientations """
482
        for i in range(self.len()):
2✔
483
            self.orientations[i] = (R_i * R.from_quat(self.orientations[i]) * R_i.inv()).as_quat()
2✔
484
    
485
        # Empty poses as they might need to be recalculated
486
        self.poses = []
2✔
487
        self.poses_rclpy = []
2✔
488

489
    # =========================================================================
490
    # =========================== Conversion to ROS =========================== 
491
    # ========================================================================= 
492

493
    @staticmethod
2✔
494
    def get_ros_msg_type(lib_type: ROSMsgLibType, msg_type: str = "Odometry") -> Any:
2✔
495
        """ Return the __msgtype__ for an Odometry msg. """
496
        if lib_type == ROSMsgLibType.ROSBAGS:
2✔
497
            typestore = get_typestore(Stores.ROS2_HUMBLE)
2✔
498
            if msg_type == "Odometry":
2✔
499
                return typestore.types['nav_msgs/msg/Odometry'].__msgtype__
2✔
500
            elif msg_type == "Path":
2✔
501
                return typestore.types['nav_msgs/msg/Path'].__msgtype__
2✔
502
            else:
NEW
503
                raise ValueError(f"Unsupported msg_type for OdometryData: {msg_type}")
×
504
        elif lib_type == ROSMsgLibType.RCLPY:
2✔
505
            if msg_type == "Path":
2✔
506
                return ModuleImporter.get_module_attribute('nav_msgs.msg', 'Path')
2✔
507
            else:
NEW
508
                raise ValueError(f"Unsupported msg_type for OdometryData: {msg_type}")
×
NEW
509
        elif lib_type == ROSMsgLibType.ROSPY:
×
NEW
510
            if msg_type == "maplab_msg/OdometryWithImuBiases":
×
NEW
511
                return ModuleImporter.get_module_attribute('maplab_msgs.msg', 'OdometryWithImuBiases')
×
NEW
512
            elif msg_type == "Path":
×
NEW
513
                return ModuleImporter.get_module_attribute('nav_msgs.msg', 'Path')
×
514
            else:
NEW
515
                raise ValueError(f"Unsupported msg_type for OdometryData: {msg_type}")
×
516
        else:
NEW
517
            raise NotImplementedError(f"Unsupported ROSMsgLibType {lib_type} for OdometryData.get_ros_msg_type()!")
×
518
    
519
    def _extract_seconds_and_nanoseconds(self, i: int):
2✔
520
        seconds = int(self.timestamps[i])
2✔
521
        nanoseconds = (self.timestamps[i] - self.timestamps[i].to_integral_value(rounding=decimal.ROUND_DOWN)) \
2✔
522
                        * Decimal("1e9").to_integral_value(decimal.ROUND_HALF_EVEN)
523
        return seconds, nanoseconds
2✔
524
    
525
    def get_ros_msg(self, lib_type: ROSMsgLibType, i: int, msg_type: str = "Odometry"):
2✔
526
        """
527
        Gets an Image ROS2 Humble message corresponding to the odometry in index i.
528
        
529
        Args:
530
            i (int): The index of the odometry data to convert.
531
        Raises:
532
            ValueError: If i is outside the data bounds.
533
        """
534

535
        # Check to make sure index is within data bounds
536
        if i < 0 or i >= self.len():
2✔
537
            raise IndexError(f"Index {i} is out of bounds!")
×
538
        
539
        # Extract seconds and nanoseconds
540
        seconds, nanoseconds = self._extract_seconds_and_nanoseconds(i)
2✔
541

542
        # Write the data into the new msg
543
        if lib_type == ROSMsgLibType.ROSBAGS:
2✔
544
            typestore = get_typestore(Stores.ROS2_HUMBLE)
2✔
545

546
            Odometry = typestore.types['nav_msgs/msg/Odometry']
2✔
547
            Header = typestore.types['std_msgs/msg/Header']
2✔
548
            Time = typestore.types['builtin_interfaces/msg/Time']
2✔
549
            PoseWithCovariance = typestore.types['geometry_msgs/msg/PoseWithCovariance']
2✔
550
            TwistWithCovariance = typestore.types['geometry_msgs/msg/TwistWithCovariance']
2✔
551
            Twist = typestore.types['geometry_msgs/msg/Twist']
2✔
552
            Vector3 = typestore.types['geometry_msgs/msg/Vector3']
2✔
553
            Path = typestore.types['nav_msgs/msg/Path']
2✔
554
            Pose = typestore.types['geometry_msgs/msg/Pose']
2✔
555
            Point = typestore.types['geometry_msgs/msg/Point']
2✔
556
            Quaternion = typestore.types['geometry_msgs/msg/Quaternion']
2✔
557

558
            if msg_type == "Odometry":
2✔
559
            
560
                return Odometry(Header(stamp=Time(sec=int(seconds), 
2✔
561
                                                nanosec=int(nanoseconds)), 
562
                                frame_id=self.frame_id),
563
                                child_frame_id=self.child_frame_id,
564
                                pose=PoseWithCovariance(pose=Pose(position=Point(x=self.positions[i][0],
565
                                                                    y=self.positions[i][1],
566
                                                                    z=self.positions[i][2]),
567
                                                        orientation=Quaternion(x=self.orientations[i][0],
568
                                                                                y=self.orientations[i][1],
569
                                                                                z=self.orientations[i][2],
570
                                                                                w=self.orientations[i][3])),
571
                                                        covariance=np.zeros(36)),
572
                                twist=TwistWithCovariance(twist=Twist(linear=Vector3(x=0, # Currently doesn't support Twist
573
                                                                                    y=0,
574
                                                                                    z=0,),
575
                                                                    angular=Vector3(x=0,
576
                                                                                    y=0,
577
                                                                                    z=0,)),
578
                                                        covariance=np.zeros(36)))
579
            elif msg_type == "Path":
2✔
580

581
                # Pre-calculate all the poses
582
                if len(self.poses) != self.len():
2✔
583
                    PoseStamped = typestore.types['geometry_msgs/msg/PoseStamped']
2✔
584

585
                    for j in range(self.len()):
2✔
586
                        sec, nanosec = self._extract_seconds_and_nanoseconds(j)
2✔
587
                        self.poses.append(PoseStamped(Header(stamp=Time(sec=int(sec), 
2✔
588
                                                                        nanosec=int(nanosec)),
589
                                                            frame_id=self.frame_id),
590
                                                    pose=Pose(position=Point(x=self.positions[j][0],
591
                                                                            y=self.positions[j][1],
592
                                                                            z=self.positions[j][2]),
593
                                    orientation=Quaternion(x=self.orientations[j][0],
594
                                                            y=self.orientations[j][1],
595
                                                            z=self.orientations[j][2],
596
                                                            w=self.orientations[j][3]))))
597

598
                return Path(Header(stamp=Time(sec=int(seconds), 
2✔
599
                                            nanosec=int(nanoseconds)),
600
                                frame_id=self.frame_id),
601
                                poses=self.poses[0:i+1:PATH_SLICE_STEP])
602
            else:
NEW
603
                raise ValueError(f"Unsupported msg_type for OdometryData: {msg_type} with ROSMsgLibType.ROSBAGS")
×
604
            
605
        elif lib_type == ROSMsgLibType.ROSPY or lib_type == ROSMsgLibType.RCLPY:
2✔
606
            if msg_type == "maplab_msg/OdometryWithImuBiases":
2✔
607
                
NEW
608
                if lib_type == ROSMsgLibType.RCLPY:
×
NEW
609
                    raise ValueError("maplab_msg/OdometryWithImuBiases is not supported for RCLPY!")
×
610

NEW
611
                rospy = ModuleImporter.get_module('rospy')
×
NEW
612
                OdometryWithImuBiases = ModuleImporter.get_module_attribute('maplab_msgs.msg', 'OdometryWithImuBiases')
×
NEW
613
                PoseWithCovariance = ModuleImporter.get_module_attribute('geometry_msgs.msg', 'PoseWithCovariance')
×
NEW
614
                TwistWithCovariance = ModuleImporter.get_module_attribute('geometry_msgs.msg', 'TwistWithCovariance')
×
NEW
615
                Point = ModuleImporter.get_module_attribute('geometry_msgs.msg', 'Point')
×
NEW
616
                Quaternion = ModuleImporter.get_module_attribute('geometry_msgs.msg', 'Quaternion')
×
NEW
617
                Vector3 = ModuleImporter.get_module_attribute('geometry_msgs.msg', 'Vector3')
×
NEW
618
                Header = ModuleImporter.get_module_attribute('std_msgs.msg', 'Header')
×
619

NEW
620
                msg = OdometryWithImuBiases()
×
NEW
621
                msg.header = Header()
×
NEW
622
                msg.header.stamp = rospy.Time(secs=seconds, nsecs=int(nanoseconds))
×
NEW
623
                msg.header.frame_id = self.frame_id
×
NEW
624
                msg.child_frame_id = self.child_frame_id
×
NEW
625
                msg.pose = PoseWithCovariance()
×
NEW
626
                msg.pose.pose.position = Point()
×
NEW
627
                msg.pose.pose.position.x = float(self.positions[i][0])
×
NEW
628
                msg.pose.pose.position.y = float(self.positions[i][1])
×
NEW
629
                msg.pose.pose.position.z = float(self.positions[i][2])
×
NEW
630
                msg.pose.pose.orientation = Quaternion()
×
NEW
631
                msg.pose.pose.orientation.x = float(self.orientations[i][0])
×
NEW
632
                msg.pose.pose.orientation.y = float(self.orientations[i][1])
×
NEW
633
                msg.pose.pose.orientation.z = float(self.orientations[i][2])
×
NEW
634
                msg.pose.pose.orientation.w = float(self.orientations[i][3])
×
NEW
635
                msg.pose.covariance = np.zeros(36) # NOTE: Assumes covariance of zero.
×
NEW
636
                msg.twist = TwistWithCovariance()
×
NEW
637
                msg.twist.twist.linear = Vector3()
×
NEW
638
                msg.twist.twist.linear.x = 0.0  # NOTE: Currently doesn't support Twist
×
NEW
639
                msg.twist.twist.linear.y = 0.0
×
NEW
640
                msg.twist.twist.linear.z = 0.0
×
NEW
641
                msg.twist.twist.angular = Vector3()
×
NEW
642
                msg.twist.twist.angular.x = 0.0
×
NEW
643
                msg.twist.twist.angular.y = 0.0
×
NEW
644
                msg.twist.twist.angular.z = 0.0
×
NEW
645
                msg.twist.covariance = np.zeros(36)
×
NEW
646
                msg.accel_bias = Vector3() # NOTE: Assumes IMU biases are zero
×
NEW
647
                msg.accel_bias.x = 0.0
×
NEW
648
                msg.accel_bias.y = 0.0
×
NEW
649
                msg.accel_bias.z = 0.0
×
NEW
650
                msg.gyro_bias = Vector3()
×
NEW
651
                msg.gyro_bias.x = 0.0
×
NEW
652
                msg.gyro_bias.y = 0.0
×
NEW
653
                msg.gyro_bias.z = 0.0
×
NEW
654
                msg.odometry_state = 0 # NOTE: Assumes default state
×
NEW
655
                return msg
×
656

657
            elif msg_type == "Path":
2✔
658
                
659
                Path = ModuleImporter.get_module_attribute('nav_msgs.msg', 'Path')
2✔
660
                Header = ModuleImporter.get_module_attribute('std_msgs.msg', 'Header')
2✔
661

662
                # Pre-calculate all the poses
663
                if len(self.poses_rclpy) != self.len():
2✔
664

665
                    PoseStamped = ModuleImporter.get_module_attribute('geometry_msgs.msg', 'PoseStamped')
2✔
666
                    Pose = ModuleImporter.get_module_attribute('geometry_msgs.msg', 'Pose')
2✔
667
                    Point = ModuleImporter.get_module_attribute('geometry_msgs.msg', 'Point')
2✔
668
                    Quaternion = ModuleImporter.get_module_attribute('geometry_msgs.msg', 'Quaternion')
2✔
669

670
                    for j in range(self.len()):
2✔
671
                        sec, nanosec = self._extract_seconds_and_nanoseconds(j)
2✔
672
                        pose_msg = PoseStamped()
2✔
673
                        pose_msg.header = Header()
2✔
674
                        if lib_type == ROSMsgLibType.RCLPY:
2✔
675
                            Time = ModuleImporter.get_module_attribute('rclpy.time', 'Time')
2✔
676
                            pose_msg.header.stamp = Time(seconds=seconds, nanoseconds=int(nanoseconds)).to_msg()
2✔
677
                        else:
NEW
678
                            rospy = ModuleImporter.get_module('rospy')
×
NEW
679
                            pose_msg.header.stamp = rospy.Time(secs=int(seconds), nsecs=int(nanoseconds))
×
680
                        pose_msg.header.frame_id = self.frame_id
2✔
681
                        pose_msg.pose = Pose()
2✔
682
                        pose_msg.pose.position = Point()
2✔
683
                        pose_msg.pose.position.x = float(self.positions[j][0])
2✔
684
                        pose_msg.pose.position.y = float(self.positions[j][1])
2✔
685
                        pose_msg.pose.position.z = float(self.positions[j][2])
2✔
686
                        pose_msg.pose.orientation = Quaternion()
2✔
687
                        pose_msg.pose.orientation.x = float(self.orientations[j][0])
2✔
688
                        pose_msg.pose.orientation.y = float(self.orientations[j][1])
2✔
689
                        pose_msg.pose.orientation.z = float(self.orientations[j][2])
2✔
690
                        pose_msg.pose.orientation.w = float(self.orientations[j][3])
2✔
691
                        self.poses_rclpy.append(pose_msg)
2✔
692

693
                msg = Path()
2✔
694
                msg.header = Header()
2✔
695
                if lib_type == ROSMsgLibType.RCLPY:
2✔
696
                    Time = ModuleImporter.get_module_attribute('rclpy.time', 'Time')
2✔
697
                    msg.header.stamp = Time(seconds=seconds, nanoseconds=int(nanoseconds)).to_msg()
2✔
698
                else:
NEW
699
                    rospy = ModuleImporter.get_module('rospy')
×
NEW
700
                    msg.header.stamp = rospy.Time(secs=int(seconds), nsecs=int(nanoseconds))
×
701
                msg.header.frame_id = self.frame_id
2✔
702
                msg.poses = self.poses_rclpy[0:i+1:PATH_SLICE_STEP]
2✔
703
                return msg
2✔
704
            
705
            else:
NEW
706
                raise ValueError(f"Unsupported msg_type for OdometryData: {msg_type} with ROSMsgLibType.ROSPY or ROSMsgLibType.RCLPY.")
×
707
        else:
708
            raise NotImplementedError(f"Unsupported ROSMsgLibType {lib_type} for OdometryData.get_ros_msg()!")
2✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc