def worker(line): try: result = execCommand(split(line), True) print '' if result is None else '%s\n' % str(result) except HandledException as e: err('%s\n' % e)
def get(desc='', type=None, **KwArgs): r"""Helps to interactively get user input. Args: desc (str): The description for input. type (type / CustomType): The type of the input (defaults to None). Notes: * When 'desc' is not provided, the Kwarg 'name' and 'type_str' are expected; which will be used to generate a description. * KwArgs acts as a data container for unexpected attibutes that are used by underlying helpers. """ if not desc: desc = '{name}, {type_str}'.format(**KwArgs) if 'default' in KwArgs: desc += ' (%s)' % KwArgs['default'] while True: try: got = raw_input('%s: ' % desc) except EOFError: got = None if not got and 'default' in KwArgs: return KwArgs['default'] try: return type(got) if type else got except ValueError: err('<invalid value>') except TypeError: err('<invalid value>')
def _setup_collision_type(self, static_collision_type): if static_collision_type == "all": static_dict = { "accelerometer": range(3), "joint_angles": range(7), "joint_velocities": range(7), "joint_efforts": range(7), "r_finger_periph_pressure": range(1), "r_finger_pad_pressure": range(1), "l_finger_periph_pressure": range(1), "l_finger_pad_pressure": range(1), "gripper_pose": range(7) } elif static_collision_type in self.perception_names: static_dict = { static_collision_type: range(self.perception_lengths[static_collision_type]) } elif static_collision_type == "pressure": static_dict = { "r_finger_periph_pressure": range(1), "r_finger_pad_pressure": range(1), "l_finger_periph_pressure": range(1), "l_finger_pad_pressure": range(1) } elif type(static_collision_type) == type({}): static_dict = static_collision_type else: err("Bad static_collision_type") self.static_dict = static_dict
def init(argv): flag = argv.pop(0) if argv[0][0] == '-' else None if flag == '-h': help_text = get_help_text(argv) if help_text is None: err('Can\'t help :(') else: print help_text else: try: execCommand(argv, flag == '-p') # Check: Should the dispatch mode log the return value? It isn't logging it now to keep the console from excess output. except HandledException as e: Member = e.Info.get('Member') if Member: alias = Member.Config.get('alias') name = Member.Config['name'] if name == '__main__': name = 'Members' label = '%s%s' % (name, ', %s' % alias if alias else '') e = '%s\n\n%s\n%s\n%s' % (str(e), label, '-' * len(label), getMemberHelp(Member)) err(e, 1)
def begin_collision_detection(self, dynamic_detection=False, callback=None, static_collision_type=None, debug=False): if not self.perception_started: err("Perception hasn't been started!") return False # if not self.detect_ready: # err("ready_collision_detection hasn't been called") # return False self.is_dynamic = dynamic_detection self.callback = callback if not dynamic_detection: self._setup_collision_type(static_collision_type) self.collision_detected = False self.collision_finished = False self.debug = debug self.collision_type = "No collision" self.cur_iter = 0 self.cur_inds = {} for k in self.perceptions: self.cur_inds[k] = 0 self.i_data_buffers = {} self.t_data_buffers = {} for k in self.perceptions: self.i_data_buffers[k] = [ np.zeros( (self.impact_fgc.filter_len, self.impact_fgc.filter_len)) for i in range(self.perception_lengths[k]) ] self.t_data_buffers[k] = [ np.zeros((self.type_fgc.filter_len, self.type_fgc.filter_len)) for i in range(self.perception_lengths[k]) ] self.end_monitor_lock = threading.Lock() self.data_thread_spawner_lock1 = threading.Lock() self.data_thread_spawner_lock2 = threading.Lock() self.data_thread_spawner = RateCaller(self._data_spawn_thread, self.SAMPLING_RATE) self.data_thread_spawner.run() self.beg_time = rospy.Time.now().to_sec() self.t_sum, self.t_num = 0., 0. self.normal_dict_counts = [] self.temp_dict = {} for k in self.perceptions: self.temp_dict[k] = [[] for i in range(self.perception_lengths[k])] return True
def help(route): r"""Displays help for the given route. Args: route (str): A route that resolves a member. """ help_text = getRouteHelp(route.split('/') if route else []) if help_text is None: err('Can\'t help :(') else: print '\n%s' % help_text
def load(self, filename): try: log("Loading random forest classifier from pickle...") num_trees, projection_basis = self.fos.load_pickle(filename.split(".")[0] + "_split_index.pickle") self.rfb = rf.RFBreiman(number_of_learners=num_trees) fns = [self.fos.get_pickle_name(filename.split(".")[0] + "_%03d.pickle" % (i)) for i in range(num_trees)] self.rfb.learners = pool_loading(fns) log("Classifier loaded") except Exception as e: err("Problem loading classifier (Has it been built?)") print e sys.exit()
def start_data_capture(self, duration=None): if not self.perception_started: err("Perception hasn't been started!") return False self.logger = RateCaller(self._gather_perception, self.SAMPLING_RATE) for k in self.perceptions: self.datasets[k] += [[]] self.logger.run() if not duration is None: threading.Timer(self.stop_data_capture, duration) return True
def main(targets, buildfunc): retcode = [0] # a list so that it can be reassigned from done() if vars.SHUFFLE: random.shuffle(targets) locked = [] def done(t, rv): if rv: err('%s: exit code was %r\n' % (t, rv)) retcode[0] = 1 for i in range(len(targets)): t = targets[i] if os.path.exists('%s/all.do' % t): # t is a directory, but it has a default target targets[i] = '%s/all' % t for t in targets: jwack.get_token(t) lock = state.Lock(t) lock.trylock() if not lock.owned: log('%s (locked...)\n' % relpath(t, vars.STARTDIR)) locked.append(t) else: jwack.start_job(t, lock, lambda: buildfunc(t), lambda t,rv: done(t,rv)) while locked or jwack.running(): jwack.wait_all() if locked: t = locked.pop(0) lock = state.Lock(t) while not lock.owned: lock.wait() lock.trylock() assert(lock.owned) relp = relpath(t, vars.STARTDIR) log('%s (...unlocked!)\n' % relp) if state.stamped(t) == None: err('%s: failed in another thread\n' % relp) retcode[0] = 2 lock.unlock() else: jwack.start_job(t, lock, lambda: buildfunc(t), lambda t,rv: done(t,rv)) return retcode[0]
def begin_collision_detection(self, dynamic_detection=False, callback=None, static_collision_type=None, debug=False): if not self.perception_started: err("Perception hasn't been started!") return False # if not self.detect_ready: # err("ready_collision_detection hasn't been called") # return False self.is_dynamic = dynamic_detection self.callback = callback if not dynamic_detection: self._setup_collision_type(static_collision_type) self.collision_detected = False self.collision_finished = False self.debug = debug self.collision_type = "No collision" self.cur_iter = 0 self.cur_inds = {} for k in self.perceptions: self.cur_inds[k] = 0 self.i_data_buffers = {} self.t_data_buffers = {} for k in self.perceptions: self.i_data_buffers[k] = [ np.zeros((self.impact_fgc.filter_len, self.impact_fgc.filter_len)) for i in range(self.perception_lengths[k])] self.t_data_buffers[k] = [ np.zeros((self.type_fgc.filter_len, self.type_fgc.filter_len)) for i in range(self.perception_lengths[k])] self.end_monitor_lock = threading.Lock() self.data_thread_spawner_lock1 = threading.Lock() self.data_thread_spawner_lock2 = threading.Lock() self.data_thread_spawner = RateCaller(self._data_spawn_thread, self.SAMPLING_RATE ) self.data_thread_spawner.run() self.beg_time = rospy.Time.now().to_sec() self.t_sum, self.t_num = 0., 0. self.normal_dict_counts = [] self.temp_dict = {} for k in self.perceptions: self.temp_dict[k] = [[] for i in range(self.perception_lengths[k])] return True
def load(self, filename): try: log("Loading random forest classifier from pickle...") num_trees, projection_basis = self.fos.load_pickle( filename.split(".")[0] + "_split_index.pickle") self.rfb = rf.RFBreiman(number_of_learners=num_trees) fns = [ self.fos.get_pickle_name( filename.split(".")[0] + "_%03d.pickle" % (i)) for i in range(num_trees) ] self.rfb.learners = pool_loading(fns) log("Classifier loaded") except Exception as e: err("Problem loading classifier (Has it been built?)") print e sys.exit()
def init(): if Settings.get('helper_tasks', True): import helper_tasks helper_tasks.main() while True: try: line = raw_input('>') if line: result = execCommand(split(line), True) print '' if result is None else '%s\n' % str(result) except HandledException as e: err('%s\n' % e) except EOFError: # ^z (null character) was passed exit()
def _setup_collision_type(self, static_collision_type): if static_collision_type == "all": static_dict = {"accelerometer" : range(3), "joint_angles" : range(7), "joint_velocities" : range(7), "joint_efforts" : range(7), "r_finger_periph_pressure" : range(1), "r_finger_pad_pressure" : range(1), "l_finger_periph_pressure" : range(1), "l_finger_pad_pressure" : range(1), "gripper_pose" : range(7)} elif static_collision_type in self.perception_names: static_dict = {static_collision_type : range( self.perception_lengths[static_collision_type])} elif static_collision_type == "pressure": static_dict = {"r_finger_periph_pressure" : range(1), "r_finger_pad_pressure" : range(1), "l_finger_periph_pressure" : range(1), "l_finger_pad_pressure" : range(1)} elif type(static_collision_type) == type({}): static_dict = static_collision_type else: err("Bad static_collision_type") self.static_dict = static_dict
def predict(self, instance): err("Classifier not implemented!") return 0.
def train(self, compiled_dataset): err("Classifier not implemented!")
def done(t, rv): if rv: err('%s: exit code was %r\n' % (t, rv)) retcode[0] = 1
def build(t): try: return _build(t) except BuildError, e: err('%s\n' % e)
def load(self, filename): err("Classifier not implemented!")
def build(self, compiled_dataset, filename): err("Classifier not implemented!")
def dirty_deps(t, depth, fromdir=None): if _dirty_deps(t, depth, fromdir): state.unstamp(t, fromdir) return True return False def maybe_build(t): if dirty_deps(t, depth = ''): builder.build(t) if not vars.TARGET: err('redo-ifchange: error: must be run from inside a .do\n') sys.exit(100) rv = 202 try: want_build = [] for t in sys.argv[1:]: state.add_dep(vars.TARGET, 'm', t) if dirty_deps(t, depth = ''): want_build.append(t) rv = builder.main(want_build, maybe_build) except KeyboardInterrupt: sys.exit(200) sys.exit(rv)
#!/usr/bin/python import sys, os import vars, state from helpers import err, mkdirp if not vars.TARGET: err('redo-ifcreate: error: must be run from inside a .do\n') sys.exit(100) try: for t in sys.argv[1:]: if os.path.exists(t): err('redo-ifcreate: error: %r already exists\n' % t) sys.exit(1) else: state.add_dep(vars.TARGET, 'c', t) except KeyboardInterrupt: sys.exit(200)