4 from scipy
import interpolate
6 import dynamic_reconfigure.client
9 from numbers
import Number
12 from std_msgs.msg
import String
21 from timeout
import timeout
22 from optimizer
import optimizer
28 REAL_PREFIX =
"/GROUND_TRUTH" 35 if(
not value.startswith(topic)):
41 attrs = re.split(
"/|\[|\]", attrs)
49 if "__iter__" in dir(res):
56 if not hasattr(res, attr):
58 res = getattr(res, attr)
62 def combine(bag_a, bag_b, output_bag_file = 'combined.bag'):
63 print "[combining bags]" 67 for topic, msg, t
in bag_a.read_messages():
68 bag_c.write(topic, msg, t)
70 for topic, msg, t
in bag_b.read_messages():
71 bag_c.write(topic, msg, t)
80 def restamp(bag, output_bag_file = 'restamped.bag', values = [], prefix = "", start_signal = {}, end_signal = {}):
81 print "[restamping {0}]".format(prefix)
92 zero = rospy.Duration(0.)
95 def check_signal(topic, msg, signal):
97 for key, val
in signal.items():
99 if (val!=
None and val == new_val)
or (val ==
None and new_val !=
None):
107 for topic, msg, t
in bag.read_messages():
110 if not any([ value.find(topic)>-1
for value
in values]):
113 if(zero == rospy.Duration(0.)):
114 zero = t - rospy.Duration(0.1)
116 if check_signal(topic, msg, start_signal):
117 zero = t - rospy.Duration(0.1)
125 new_topic =
"".join([prefix, topic])
127 output.write(new_topic, msg, t-zero)
129 if check_signal(topic, msg, end_signal):
144 topics = bag.get_type_and_topic_info()[1].keys()
146 if value.startswith(topic):
149 for _, msg, t
in bag.read_messages([topic]):
153 stamps.append(t.to_sec())
155 data = np.array(data)
156 stamps = np.array(stamps)
158 return np.array([]), np.array([])
166 t = np.append([float(
"-inf")], t)
171 def f(t_new, t = t, y = y):
173 if '__iter__' not in dir(t_new):
174 return y[max(i
for i
in range(len(t))
if t[i] <= t_new)]
178 index = max(i
for i
in range(len(t))
if t[i] <= tt)
185 y_new = np.array(y_new)
195 cmd = [
"rosbag",
"play",
"-d 2",
"-r 0.8",
198 "{0}:={1}".format(src, dst)
201 FNULL = open(os.devnull,
'w')
202 return subprocess.Popen(cmd, stdout=FNULL, stderr=subprocess.STDOUT)
205 topics =
" ".join(topics)
209 FNULL = open(os.devnull,
'w')
210 return subprocess.Popen([
"rosbag",
"record", topics,
211 "--duration={0}".format(duration),
212 "--output-name={0}".format(output_bag) ],
213 stdout=FNULL, stderr=subprocess.STDOUT)
217 if isinstance(bag, str):
219 return yaml.load(bag._get_yaml_info())
221 def start_simulation(real_bag_file, sim_bag_file, src_topic, dst_topic, values = [] , start_signal={}, end_signal={}):
228 duration = info[
"duration"] + 3
229 _timeout = int(duration + 2 + 120)
231 print "DURATION is %d" % duration
233 rec_proc =
record_bag(sim_bag_file, duration = duration)
234 play_proc =
play_bag(real_bag_file, src_topic, dst_topic)
242 while is_playing
or is_recording:
243 if rec_proc.poll()
is not None and is_recording:
245 print(
"[finished recording]")
247 if play_proc.poll()
is not None and is_playing:
249 print(
"[finished playing]")
253 e = sys.exc_info()[0]
255 print(
"Something went wrong. Error: %s" % e)
256 print(
"Killing the play/record processes")
258 if rec_proc.poll()
is None:
260 if play_proc.poll()
is None:
269 if rec_proc.poll()
is None:
271 if play_proc.poll()
is None:
274 print(
"[finished simulation]")
279 sim_bag = restamp(sim_bag, output_bag_file = 'sim-restamped.bag' , values = values, prefix = SIM_PREFIX, start_signal = start_signal, end_signal = end_signal)
280 real_bag =
restamp(real_bag, output_bag_file =
'real-restamped.bag', values = values, prefix = REAL_PREFIX, start_signal = start_signal, end_signal = end_signal)
282 combined_bag =
combine(sim_bag, real_bag)
294 t_max = float(
"-inf")
296 for value
in value_list:
297 print value, t_min, t_max
311 t_min = min(t_min, min(t))
312 t_max = max(t_max, max(t))
320 for value
in value_list:
323 print "reading {0}".format(value)
328 if len(t)>1
and (dt == int
or dt == float):
329 f = interpolate.interp1d(t, y, axis = 0, fill_value =
"extrapolate")
336 create a new time array 337 project the new samples 340 t_new = np.arange(t_min, t_max, resolution)
346 ndata = ndata.astype(dt)
348 datamap[value] = ndata
478 self._optimizer.optimize()
488 for param, value
in param_list.items():
489 if(param[-1] ==
'/'):
491 index = param.rfind(
'/')
492 node_name = param[:index]
493 param_name = param[index+1:]
495 if node_name
not in nparams:
496 nparams[node_name] = {}
498 nparams[node_name].update({param_name:value})
502 for node, config
in nparams.items():
505 service_name = node +
"/set_parameters" 510 client = dynamic_reconfigure.client.Client(node, timeout=30)
511 client.update_configuration(config)
519 config[param] = rospy.get_param(param)
528 for param
in param_list:
529 if(param[-1] ==
'/'):
531 index = param.rfind(
'/')
532 node_name = param[:index]
533 param_name = param[index+1:]
535 if node_name
not in nparams:
536 nparams[node_name] = {}
538 nparams[node_name].update({param_name:param})
542 for node, config
in nparams.items():
545 service_name = node +
"/set_parameters" 550 client = dynamic_reconfigure.client.Client(node, timeout=30)
551 desc_list = client.get_parameter_descriptions()
553 for desc_item
in desc_list:
554 param_name = desc_item[
'name']
555 if param_name
in config:
556 desc.update({config[param_name]:desc_item})
575 print "[parameters are updated]" 596 print "[calling objective function]" 598 print "[returning: {0}]".format(res)
def get_params_desc(self, param_list)
def play_bag(bag_file, src, dst)
def resample(bag, value_list, resolution=0.1)
def tune_params(self, config={})
def start_simulation(real_bag_file, sim_bag_file, src_topic, dst_topic, values=[], start_signal={}, end_signal={})
def combine(bag_a, bag_b, output_bag_file='combined.bag')
def value_of(topic, msg, value)
def record_bag(output_bag, topics=[], duration=10)
def _evaluate(self, config)
def __init__(self, param_set, value_set, real_bag_file, sim_bag_file, src_topic, dst_topic, start_signal={}, end_signal={}, resolution=0.1, objective=None)
def read_value_vector(bag, value)
def timeout(seconds=10, error_message=os.strerror(errno.ETIME))
def read_default_config(self)
def restamp(bag, output_bag_file='restamped.bag', values=[], prefix="", start_signal={}, end_signal={})
def update_params(self, param_list)