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

lunarlab-gatech / robotdataprocess / 16598293332

29 Jul 2025 01:59PM UTC coverage: 73.457% (+2.9%) from 70.588%
16598293332

push

github

web-flow
(v0.1.1) ImageData Improvements & PathData

151 of 181 new or added lines in 6 files covered. (83.43%)

1 existing line in 1 file now uncovered.

952 of 1296 relevant lines covered (73.46%)

0.73 hits per line

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

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

3
from ..conversion_utils import convert_collection_into_decimal_array
1✔
4
import csv
1✔
5
from .Data import CoordinateFrame, Data
1✔
6
import decimal
1✔
7
from decimal import Decimal
1✔
8
import matplotlib.pyplot as plt
1✔
9
import numpy as np
1✔
10
import os
1✔
11
import pandas as pd
1✔
12
from pathlib import Path
1✔
13
from ..rosbag.Ros2BagWrapper import Ros2BagWrapper
1✔
14
from rosbags.rosbag2 import Reader as Reader2
1✔
15
from rosbags.typesys import Stores, get_typestore
1✔
16
from rosbags.typesys.store import Typestore
1✔
17
from scipy.spatial.transform import Rotation as R
1✔
18
from typeguard import typechecked
1✔
19
import tqdm
1✔
20

21
class OdometryData(Data):
1✔
22

23
    # Define odometry-specific data attributes
24
    child_frame_id: str
1✔
25
    frame: CoordinateFrame
1✔
26
    positions: np.ndarray[Decimal] # meters (x, y, z)
1✔
27
    orientations: np.ndarray[Decimal] # quaternions (x, y, z, w)
1✔
28
    poses = [] # Saved nav_msgs/msg/Pose
1✔
29

30
    @typechecked
1✔
31
    def __init__(self, frame_id: str, child_frame_id: str, frame: CoordinateFrame, 
1✔
32
                 timestamps: np.ndarray | list, positions: np.ndarray | list, 
33
                 orientations: np.ndarray | list):
34
        
35
        # Copy initial values into attributes
36
        super().__init__(frame_id, timestamps)
1✔
37
        self.child_frame_id = child_frame_id
1✔
38
        self.frame = frame
1✔
39
        self.positions = convert_collection_into_decimal_array(positions)
1✔
40
        self.orientations = convert_collection_into_decimal_array(orientations)
1✔
41

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

46
    # =========================================================================
47
    # ============================ Class Methods ============================== 
48
    # =========================================================================  
49

50
    @classmethod
1✔
51
    @typechecked
1✔
52
    def from_ros2_bag(cls, bag_path: Path | str, odom_topic: str):
1✔
53
        """
54
        Creates a class structure from a ROS2 bag file with an Odometry topic.
55

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

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

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

77
        # Extract the odometry information
78
        frame_id, child_frame_id = None, None
1✔
79
        with Reader2(str(bag_path)) as reader:
1✔
80

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

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

100
                # NOTE: Doesn't support Twist information currently
101

102
                # Increment the count
103
                i += 1
1✔
104
                pbar.update(1)
1✔
105

106
        # Create an OdometryData class
107
        return cls(frame_id, child_frame_id, CoordinateFrame.FLU, timestamps_np, positions_np, orientations_np)
1✔
108
    
109
    @classmethod
1✔
110
    @typechecked
1✔
111
    def from_csv(cls, csv_path: Path | str, frame_id: str, child_frame_id: str, frame: CoordinateFrame, header_included: bool, column_to_data: list[int] | None):
1✔
112
        """
113
        Creates a class structure from a csv file.
114

115
        Args:
116
            csv_path (Path | str): Path to the CSV file.
117
            frame_id (str): The frame that this odometry is relative to.
118
            child_frame_id (str): The frame whose pose is represented by this odometry.
119
            frame (CoordinateFrame): The coordinate system convention of this data.
120
            header_included (bool): If this csv file has a header, so we can remove it.
121
            column_to_data (list[int]): Tells the algorithms which columns in the csv contain which
122
                of the following data: ['timestamp', 'x', 'y', 'z', 'qw', 'qx', 'qy', 'qz']. Thus, 
123
                index 0 of column_to_data should be the column that timestamp data is found in the 
124
                csv file. Set to None to use [0,1,2,3,4,5,6,7].
125
        Returns:
126
            OdometryData: Instance of this class.
127
        """
128

129
        # If column_to_data is None, assume default:
130
        if column_to_data is None:
1✔
131
            column_to_data = [0,1,2,3,4,5,6,7]
1✔
132
        else:
133
            # Check column_to_data values are valid
NEW
134
            assert np.all(column_to_data >= 0)
×
135

136
        # Determine column names to apply
137
        column_names = []
1✔
138
        desired_data = ['timestamp', 'x', 'y', 'z', 'qw', 'qx', 'qy', 'qz']
1✔
139
        i = 0
1✔
140
        while not np.all([x == -1 for x in column_to_data]):
1✔
141
            if i in column_to_data: # This column has relevant data
1✔
142
                index_in_column_to_data = column_to_data.index(i)
1✔
143
                column_names.append(desired_data[index_in_column_to_data])
1✔
144
                column_to_data[index_in_column_to_data] = -1
1✔
145
                
146
            else: # This column should be ignored
NEW
147
                column_names.append("unused_" + str(i))
×
148

149
            # Increase count
150
            i += 1
1✔
151

152
        # Read the csv file
153
        header = 0 if header_included else None
1✔
154
        df1 = pd.read_csv(str(csv_path), header=header, names=column_names, index_col=False)
1✔
155

156
        # Convert columns to np.ndarray[Decimal]
157
        timestamps_np = np.array([Decimal(str(ts)) for ts in df1['timestamp']], dtype=object)
1✔
158
        positions_np = np.array([[Decimal(str(x)), Decimal(str(y)), Decimal(str(z))] 
1✔
159
                                 for x, y, z in zip(df1['x'], df1['y'], df1['z'])], dtype=object)
160
        orientations_np = np.array([[Decimal(str(qx)), Decimal(str(qy)), Decimal(str(qz)), Decimal(str(qw))]
1✔
161
                                    for qx, qy, qz, qw in zip(df1['qx'], df1['qy'], df1['qz'], df1['qw'])], dtype=object)
162

163
        # Create an OdometryData class
164
        return cls(frame_id, child_frame_id, frame, timestamps_np, positions_np, orientations_np)
1✔
165
    
166
    @classmethod
1✔
167
    @typechecked
1✔
168
    def from_txt_file(cls, file_path: Path | str, frame_id: str, child_frame_id: str, frame: CoordinateFrame):
1✔
169
        """
170
        Creates a class structure from a text file, where the order of values
171
        in the files follows ['timestamp', 'x', 'y', 'z', 'qw', 'qx', 'qy', 'qz'].
172

173
        Args:
174
            file_path (Path | str): Path to the file containing the odometry data.
175
            frame_id (str): The frame where this odometry is relative to.
176
            child_frame_id (str): The frame whose pose is represented by this odometry.
177
            frame (CoordinateFrame): The coordinate system convention of this data.
178
        Returns:
179
            OdometryData: Instance of this class.
180
        """
181
        
182
        # Count the number of lines in the file
183
        line_count = 0
1✔
184
        with open(str(file_path), 'r') as file:
1✔
185
            for _ in file: 
1✔
186
                line_count += 1
1✔
187

188
        # Setup arrays to hold data
189
        timestamps_np = np.zeros((line_count), dtype=object)
1✔
190
        positions_np = np.zeros((line_count, 3), dtype=object)
1✔
191
        orientations_np = np.zeros((line_count, 4), dtype=object)
1✔
192

193
        # Open the txt file and read in the data
194
        with open(str(file_path), 'r') as file:
1✔
195
            for i, line in enumerate(file):
1✔
196
                line_split = line.split(' ')
1✔
197
                timestamps_np[i] = line_split[0]
1✔
198
                positions_np[i] = line_split[1:4]
1✔
199
                orientations_np[i] =  line_split[5:8] + [line_split[4]]
1✔
200
        
201
        # Create an OdometryData class
202
        return cls(frame_id, child_frame_id, frame, timestamps_np, positions_np, orientations_np)
1✔
203
    
204
    # =========================================================================
205
    # ========================= Manipulation Methods ========================== 
206
    # =========================================================================  
207
    
208
    def add_folded_guassian_noise_to_position(self, xy_noise_std_per_frame: float,
1✔
209
            z_noise_std_per_frame: float):
210
        """
211
        This method simulates odometry drift by adding folded gaussian noise
212
        to the odometry positions on a per frame basis. It also accumulates
213
        it over time. NOTE: It completely ignores the timestamps, and the "folded
214
        guassian noise" distribution stds might not align with the stds of the 
215
        guassian used internally, so this is not a robust function at all.
216

217
        Args:
218
            xy_noise_std_per_frame (float): Standard deviation of the gaussian 
219
                distribution for xy, whose output is then run through abs().
220
            z_noise_std_per_frame (float): Same as above, but for z.
221
        """
222

223
        # Track cumulative noise for each field
224
        cumulative_noise_pos = {'x': 0.0, 'y': 0.0, 'z': 0.0}
×
225

226
        # For each position
227
        for i in range(len(self.timestamps)):
×
228

229
            # Sample noise and accumulate
230
            noise_pos = {'x': np.random.normal(0, xy_noise_std_per_frame),
×
231
                        'y': np.random.normal(0, xy_noise_std_per_frame),
232
                        'z': np.random.normal(0, z_noise_std_per_frame)}
233
            for key in cumulative_noise_pos:
×
234
                cumulative_noise_pos[key] += abs(noise_pos[key])
×
235

236
            # Update positions
237
            self.positions[i][0] += Decimal(cumulative_noise_pos['x'])
×
238
            self.positions[i][1] += Decimal(cumulative_noise_pos['y'])
×
239
            self.positions[i][2] += Decimal(cumulative_noise_pos['z'])
×
240

241
    def shift_position(self, x_shift: float, y_shift: float, z_shift: float):
1✔
242
        """
243
        Shifts the positions of the odometry.
244

245
        Args:
246
            x_shift (float): Shift in x-axis.
247
            y_shift (float): Shift in y_axis.
248
            z_shift (float): Shift in z_axis.
249
        """
250
        self.positions[:,0] += Decimal(x_shift)
×
251
        self.positions[:,1] += Decimal(y_shift)
×
252
        self.positions[:,2] += Decimal(z_shift)
×
253

254
    def shift_to_start_at_identity(self):
1✔
255
        """
256
        Alter the positions and orientations based so that the first pose 
257
        starts at Identity.
258
        """
259

260
        # Get pose of first robot position w.r.t world
261
        R_o = R.from_quat(self.orientations[0]).as_matrix()
1✔
262
        T_o = np.expand_dims(self.positions[0], axis=1)
1✔
263
        
264
        # Calculate the inverse (pose of world w.r.t first robot location)
265
        R_inv = R_o.T
1✔
266

267
        # Rotate positions and orientations
268
        self.positions = (R_inv @ (self.positions.T - T_o).astype(float)).T
1✔
269
        for i in range(self.len()):
1✔
270
            self.orientations[i] = R.from_matrix((R_inv @ R.from_quat(self.orientations[i]).as_matrix())).as_quat()
1✔
271

272
    # =========================================================================
273
    # ============================ Export Methods ============================= 
274
    # =========================================================================  
275

276
    def to_csv(self, csv_path: Path | str):
1✔
277
        """
278
        Writes the odometry data to a .csv file. Note that data will be
279
        saved in the following order: timestamp, pos.x, pos.y, pos.z,
280
        ori.w, ori.x, ori.y, ori.z. Timestamp is in seconds.
281

282
        Args:
283
            csv_path (Path | str): Path to the output csv file.
284
            odom_topic (str): Topic of the Odometry messages.
285
        Returns:
286
            OdometryData: Instance of this class.
287
        """
288

289
        # setup tqdm 
290
        pbar = tqdm.tqdm(total=None, desc="Saving to csv... ", unit=" frames")
1✔
291

292
        # Check that file path doesn't already exist
293
        file_path = Path(csv_path)
1✔
294
        if os.path.exists(file_path):
1✔
295
            raise ValueError(f"Output file already exists: {file_path}")
×
296
        
297
        # Open csv file
298
        with open(file_path, 'w', newline='') as csvfile:
1✔
299
            writer = csv.writer(csvfile, delimiter=',')
1✔
300

301
            # Write the first row
302
            writer.writerow(['timestamp', 'x', 'y', 'z', 'qw', 'qx', 'qy', 'qz'])
1✔
303
                
304
            # Write message data to the csv file
305
            for i in range(len(self.timestamps)):
1✔
306
                writer.writerow([str(self.timestamps[i]), 
1✔
307
                    str(self.positions[i][0]), str(self.positions[i][1]), str(self.positions[i][2]),
308
                    str(self.orientations[i][3]), str(self.orientations[i][0]), str(self.orientations[i][1]), 
309
                    str(self.orientations[i][2])])
310
                pbar.update(1)
1✔
311

312
    # =========================================================================
313
    # ============================ Visualization ============================== 
314
    # =========================================================================  
315

316
    @typechecked
1✔
317
    def visualize(self, otherList: list[OdometryData], titles: list[str]):
1✔
318
        """
319
        Visualizes this OdometryData (and all others included in otherList)
320
        on a single plot.
321

322
        Args:
323
            otherList (list[OdometryData]): All other OdometryData objects whose
324
                odometry should also be visualized on this plot.
325
            titles (list[str]): Titles for each OdometryData object, starting 
326
                with self.
327
        """
328

329
        def draw_axes(data: OdometryData, label_prefix=""):
×
330
            """Helper function that visualizes orientation along the trajectory path with axes."""
331
            axes_interval = 5000
×
332
            axes_length = 5
×
333

334
            for i in range(0, data.len(), axes_interval):
×
335
                # Extract data
336
                pos = data.positions[i].astype(np.float64)
×
337
                quat = data.orientations[i].astype(np.float64)
×
338
                rot = R.from_quat(quat, scalar_first=False)
×
339

340
                # Define unit vectors for X, Y, Z in local frame
341
                x_axis = rot.apply([1, 0, 0])
×
342
                y_axis = rot.apply([0, 1, 0])
×
343
                z_axis = rot.apply([0, 0, 1])
×
344

345
                # Plot axes
346
                ax.quiver(*pos, *x_axis, length=axes_length, color='r', normalize=True, linewidth=0.8)
×
347
                ax.quiver(*pos, *y_axis, length=axes_length, color='g', normalize=True, linewidth=0.8)
×
348
                ax.quiver(*pos, *z_axis, length=axes_length, color='b', normalize=True, linewidth=0.8)
×
349

350
        # Ensure that the lists are of the proper sizes
351
        if (len(otherList) + 1) != len(titles):
×
352
            raise ValueError("Length of titles should be one more than length of otherlist!")
×
353

354
        # Build a 3D plot
355
        fig = plt.figure()
×
356
        ax = fig.add_subplot(111, projection='3d')
×
357

358
        ax.plot(self.positions[:,0].astype(np.float64), 
×
359
                self.positions[:,1].astype(np.float64), 
360
                self.positions[:,2].astype(np.float64), label=titles[0])
361
        for i, other in enumerate(otherList):
×
362
            ax.plot(other.positions[:,0].astype(np.float64), 
×
363
                    other.positions[:,1].astype(np.float64), 
364
                    other.positions[:,2].astype(np.float64), 
365
                    label=titles[1+i])
366

367
        # Draw orientation axes (X = red, Y = green, Z = blue)
368
        draw_axes(self)
×
369
        for other in otherList:
×
370
            draw_axes(other)
×
371

372
        # Set labels
373
        ax.set_title("Trajectory Comparison with Full Orientation")
×
374
        ax.set_xlabel("X (m)")
×
375
        ax.set_ylabel("Y (m)")
×
376
        ax.set_zlabel("Z (m)")
×
377
        ax.legend()
×
378

379
        # Concatenate all x, y and z values together
380
        all_x = self.positions[:,0]
×
381
        all_y = self.positions[:,1]
×
382
        all_z = self.positions[:,2]
×
383
        for other in otherList:
×
384
            all_x = np.concatenate((all_x, other.positions[:,0]))
×
385
            all_y = np.concatenate((all_y, other.positions[:,1]))
×
386
            all_z = np.concatenate((all_z, other.positions[:,2]))
×
387
        all_x = all_x.astype(np.float64)
×
388
        all_y = all_y.astype(np.float64)
×
389
        all_z = all_z.astype(np.float64)
×
390

391
        # Set an equal scale for all axes
392
        x_center = (all_x.max() + all_x.min()) / 2
×
393
        y_center = (all_y.max() + all_y.min()) / 2
×
394
        z_center = (all_z.max() + all_z.min()) / 2
×
395
        max_range = max(all_x.max() - all_x.min(), all_y.max() - all_y.min(), all_z.max() - all_z.min()) / 2
×
396
        ax.set_xlim(x_center - max_range, x_center + max_range)
×
397
        ax.set_ylim(y_center - max_range, y_center + max_range)
×
398
        ax.set_zlim(z_center - max_range, z_center + max_range)
×
399

400
        # Show the plot
401
        plt.tight_layout()
×
402
        plt.show()
×
403

404
    # =========================================================================
405
    # =========================== Frame Conversions =========================== 
406
    # ========================================================================= 
407
    def to_FLU_frame(self):
1✔
408
        # If we are already in the FLU frame, return
409
        if self.frame == CoordinateFrame.FLU:
1✔
410
            print("Data already in FLU coordinate frame, returning...")
1✔
411
            return
1✔
412

413
        # If in NED, run the conversion
414
        elif self.frame == CoordinateFrame.NED:
1✔
415
            # Define the rotation matrix
416
            R_NED = np.array([[1,  0,  0],
1✔
417
                              [0, -1,  0],
418
                              [0,  0, -1]])
419
            R_NED_Q = R.from_matrix(R_NED)
1✔
420

421
            # Do a change of basis
422
            self.positions = (R_NED @ self.positions.T).T
1✔
423
            for i in range(self.len()):
1✔
424
                self.orientations[i] = (R_NED_Q * R.from_quat(self.orientations[i]) * R_NED_Q.inv()).as_quat()
1✔
425

426
            # Update frame
427
            self.frame = CoordinateFrame.FLU
1✔
428

429
        # Otherwise, throw an error
430
        else:
431
            raise RuntimeError(f"OdometryData class is in an unexpected frame: {self.frame}!")
1✔
432

433
    # =========================================================================
434
    # =========================== Conversion to ROS =========================== 
435
    # ========================================================================= 
436

437
    @typechecked
1✔
438
    @staticmethod
1✔
439
    def get_ros_msg_type(msg_type: str = "Odometry") -> str:
1✔
440
        """ Return the __msgtype__ for an Imu msg. """
441
        typestore = get_typestore(Stores.ROS2_HUMBLE)
1✔
442
        if msg_type == "Odometry":
1✔
443
            return typestore.types['nav_msgs/msg/Odometry'].__msgtype__
1✔
444
        elif msg_type == "Path":
1✔
445
            return typestore.types['nav_msgs/msg/Path'].__msgtype__
1✔
446
        else:
447
            raise ValueError(f"Unsupported msg_type for OdometryData: {msg_type}")
×
448
    
449
    @typechecked
1✔
450
    def extract_seconds_and_nanoseconds(self, i: int):
1✔
451
        seconds = int(self.timestamps[i])
1✔
452
        nanoseconds = (self.timestamps[i] - self.timestamps[i].to_integral_value(rounding=decimal.ROUND_DOWN)) \
1✔
453
                        * Decimal("1e9").to_integral_value(decimal.ROUND_HALF_EVEN)
454
        return seconds, nanoseconds
1✔
455
    
456
    def calculate_stamped_poses(self):
1✔
457
        """ Pre-calculates all stamped poses if they aren't calculated yet."""
458

459
        if len(self.poses) != self.len():
1✔
460
            # Get ROS2 message types
461
            typestore = get_typestore(Stores.ROS2_HUMBLE)
1✔
462
            Header = typestore.types['std_msgs/msg/Header']
1✔
463
            Time = typestore.types['builtin_interfaces/msg/Time']
1✔
464
            PoseStamped = typestore.types['geometry_msgs/msg/PoseStamped']
1✔
465
            Pose = typestore.types['geometry_msgs/msg/Pose']
1✔
466
            Point = typestore.types['geometry_msgs/msg/Point']
1✔
467
            Quaternion = typestore.types['geometry_msgs/msg/Quaternion']
1✔
468

469
            # Pre-calculate all the poses
470
            for i in range(self.len()):
1✔
471
                seconds, nanoseconds = self.extract_seconds_and_nanoseconds(i)
1✔
472
                self.poses.append(PoseStamped(Header(stamp=Time(sec=int(seconds), 
1✔
473
                                                                nanosec=int(nanoseconds)),
474
                                                    frame_id=self.frame_id),
475
                                            pose=Pose(position=Point(x=self.positions[i][0],
476
                                                                    y=self.positions[i][1],
477
                                                                    z=self.positions[i][2]),
478
                            orientation=Quaternion(x=self.orientations[i][0],
479
                                                    y=self.orientations[i][1],
480
                                                    z=self.orientations[i][2],
481
                                                    w=self.orientations[i][3]))))
482

483
    @typechecked
1✔
484
    def get_ros_msg(self, i: int, msg_type: str = "Odometry"):
1✔
485
        """
486
        Gets an Image ROS2 Humble message corresponding to the odometry in index i.
487
        
488
        Args:
489
            i (int): The index of the odometry data to convert.
490
        Raises:
491
            ValueError: If i is outside the data bounds.
492
        """
493

494
        # Calculate the Stamped Poses
495
        self.calculate_stamped_poses()
1✔
496

497
        # Make sure our data is in the FLU frame, otherwise throw an error
498
        if self.frame != CoordinateFrame.FLU:
1✔
NEW
499
            raise RuntimeError("Convert this Odometry Data to a FLU frame before writing to a ROS2 bag!")
×
500

501
        # Check to make sure index is within data bounds
502
        if i < 0 or i >= self.len():
1✔
503
            raise IndexError(f"Index {i} is out of bounds!")
×
504

505
        # Get ROS2 message classes
506
        typestore = get_typestore(Stores.ROS2_HUMBLE)
1✔
507
        Odometry = typestore.types['nav_msgs/msg/Odometry']
1✔
508
        Header = typestore.types['std_msgs/msg/Header']
1✔
509
        Time = typestore.types['builtin_interfaces/msg/Time']
1✔
510
        PoseWithCovariance = typestore.types['geometry_msgs/msg/PoseWithCovariance']
1✔
511
        TwistWithCovariance = typestore.types['geometry_msgs/msg/TwistWithCovariance']
1✔
512
        Twist = typestore.types['geometry_msgs/msg/Twist']
1✔
513
        Vector3 = typestore.types['geometry_msgs/msg/Vector3']
1✔
514
        Path = typestore.types['nav_msgs/msg/Path']
1✔
515
        Pose = typestore.types['geometry_msgs/msg/Pose']
1✔
516
        Point = typestore.types['geometry_msgs/msg/Point']
1✔
517
        Quaternion = typestore.types['geometry_msgs/msg/Quaternion']
1✔
518

519
        # Write the data into the new msg
520
        if msg_type == "Odometry":
1✔
521
            seconds, nanoseconds = self.extract_seconds_and_nanoseconds(i)
1✔
522
            return Odometry(Header(stamp=Time(sec=int(seconds), 
1✔
523
                                              nanosec=int(nanoseconds)), 
524
                            frame_id=self.frame_id),
525
                            child_frame_id=self.child_frame_id,
526
                            pose=PoseWithCovariance(pose=Pose(position=Point(x=self.positions[i][0],
527
                                                                 y=self.positions[i][1],
528
                                                                 z=self.positions[i][2]),
529
                                                    orientation=Quaternion(x=self.orientations[i][0],
530
                                                                            y=self.orientations[i][1],
531
                                                                            z=self.orientations[i][2],
532
                                                                            w=self.orientations[i][3])),
533
                                                    covariance=np.zeros(36)),
534
                            twist=TwistWithCovariance(twist=Twist(linear=Vector3(x=0, # Currently doesn't support Twist
535
                                                                                y=0,
536
                                                                                z=0,),
537
                                                                angular=Vector3(x=0,
538
                                                                                y=0,
539
                                                                                z=0,)),
540
                                                    covariance=np.zeros(36)))
541
        elif msg_type == "Path":
1✔
542
            seconds, nanoseconds = self.extract_seconds_and_nanoseconds(i)
1✔
543
            return Path(Header(stamp=Time(sec=int(seconds), 
1✔
544
                                          nanosec=int(nanoseconds)),
545
                               frame_id=self.frame_id),
546
                               poses=self.poses[0:i+1:10])
547
        else:
548
            raise ValueError(f"Unsupported msg_type for OdometryData: {msg_type}")
1✔
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