bag_parser.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 import glob
3 import os
4 import sys
5 import rosbag
6 import numpy as np
7 import rospkg
8 
9 class BagParser():
10  '''
11  Provides functionality to parse a ROS bag which holds
12  an actionlib feedback message.
13  '''
14  def __init__(self, pkg, rel_path, prefix):
15  rospack = rospkg.RosPack()
16  self._dir = rospack.get_path(pkg) + "/" + rel_path
17  self._prefix = prefix
18 
19 
20  def getAllBags(self, elements):
21  '''
22  Get all data from bags in the directory.
23 
24  @param elements attributes to extract from each bag (list)
25  @returns list of bag data dictionaries.
26  '''
27  bag_data = []
28  for num in range(len(glob.glob(self._dir + "/" + self._prefix + "*.bag"))):
29  bag = rosbag.Bag(self._dir + "/" + self._prefix + "_" + str(num + 1) + ".bag")
30  bag_data.append(self.getBagContents(elements, bag))
31 
32  return bag_data
33 
34 
35  def getBagContents(self, elements, bag):
36  '''
37  Get all messages in the bag in the format msg.feedback.elements[i], plus the respective time.
38 
39  @param elements elements to extract from each bag (list)
40  @param bag a rosbag.Bag instance.
41  @returns A dictionary with the data mapping {elements[i]: value}
42  '''
43  data = {}
44  data['t'] = []
45 
46  for element in elements:
47  data[element] = []
48 
49  for topic, msg, time in bag.read_messages():
50  data['t'].append(time.to_sec())
51 
52  for element in elements:
53  msg_element = getattr(msg, element)
54  list_data = self.msgToList(msg_element)
55  if list_data is None:
56  raise RuntimeError("Got unsupported msg type " + msg_element._type)
57  data[element].append(list_data)
58 
59  for key in data:
60  data[key] = np.asarray(data[key])
61 
62  return data
63 
64 
65  def msgToList(self, msg):
66  '''
67  Convert the given message to a list.
68  '''
69  if type(msg) is float or type(msg) is int:
70  return msg
71  if msg._type == 'geometry_msgs/WrenchStamped':
72  return self.wrenchMsgToList(msg.wrench)
73  elif msg._type == 'geometry_msgs/Wrench':
74  return self.wrenchMsgToList(msg)
75  elif msg._type == 'geometry_msgs/PoseStamped':
76  return self.poseMsgToList(msg.pose)
77  elif msg._type == 'geometry_msgs/Pose':
78  return self.poseMsgToList(msg)
79  else:
80  return None
81 
82 
83  def wrenchMsgToList(self, msg):
84  '''
85  Convert a wrench message to a list
86  '''
87  w = [msg.force.x, msg.force.y, msg.force.y,
88  msg.torque.x, msg.torque.y, msg.torque.z]
89  return w
90 
91  def poseMsgToList(self, msg):
92  '''
93  Convert a pose message to list
94  '''
95  p = [msg.position.x, msg.position.y, msg.position.z,
96  msg.orientation.x, msg.orientation.y, msg.orientation.z, msg.orientation.w]
97  return p
def getBagContents(self, elements, bag)
Definition: bag_parser.py:35
def __init__(self, pkg, rel_path, prefix)
Definition: bag_parser.py:14


generic_control_toolbox
Author(s): diogo
autogenerated on Mon Feb 28 2022 22:24:37