def cmd_start(self, args, message): """/start""" msg = wrap(""" Authenticate yourself via /auth and follow the instructions. Afterwards you can send me photos or images, which I will upload and link to in the IRC channel {conf.irc.channel} on {conf.irc.host}. Contact {conf.telegram.username_for_help} in case you are having problems. """).format(conf=self.conf) if message.sender.id in (self.conf.telegram.admin or []): msg = msg + "\n\n" + wrap(""" More commands: /get_id - get your id More commands for admins: /blacklist [add | remove] <id> - modify the blacklist """) return msg
def fill(text, width, initindent = '', hangindent = ''): '''fill many paragraphs with optional indentation.''' global para_re, space_re if para_re is None: para_re = re.compile('(\n\n|\n\\s*[-*]\\s*)', re.M) space_re = re.compile(r' +') def findparas(): start = 0 while True: m = para_re.search(text, start) if not m: uctext = unicode(text[start:], encoding.encoding) w = len(uctext) while 0 < w and uctext[w - 1].isspace(): w -= 1 yield (uctext[:w].encode(encoding.encoding), uctext[w:].encode(encoding.encoding)) break yield text[start:m.start(0)], m.group(1) start = m.end(1) return "".join([util.wrap(space_re.sub(' ', util.wrap(para, width)), width, initindent, hangindent) + rest for para, rest in findparas()])
def fill(text, width, initindent='', hangindent=''): '''fill many paragraphs with optional indentation.''' global para_re, space_re if para_re is None: para_re = re.compile('(\n\n|\n\\s*[-*]\\s*)', re.M) space_re = re.compile(r' +') def findparas(): start = 0 while True: m = para_re.search(text, start) if not m: uctext = unicode(text[start:], encoding.encoding) w = len(uctext) while 0 < w and uctext[w - 1].isspace(): w -= 1 yield (uctext[:w].encode(encoding.encoding), uctext[w:].encode(encoding.encoding)) break yield text[start:m.start(0)], m.group(1) start = m.end(1) return "".join([ util.wrap(space_re.sub(' ', util.wrap(para, width)), width, initindent, hangindent) + rest for para, rest in findparas() ])
def set_mute(self, mute_state): if mute_state: self.connection.send(util.wrap(util.CMD_MUTEON)) self.connection.recv(util.BUFFER_SIZE) self.volume = False else: self.connection.send(util.wrap(util.CMD_MUTEOFF)) self.connection.recv(util.BUFFER_SIZE) self.volume = self.get_device_volume()
def pause(self): # Force this to toggle. if self.state == "pause": self.connection.send(util.wrap(util.CMD_PAUSE)) self.connection.recv(util.BUFFER_SIZE) self.state = "play" elif self.state == "play": self.connection.send(util.wrap(util.CMD_PAUSE)) self.connection.recv(util.BUFFER_SIZE) self.state = "pause"
def cbComputeActionGA3C(self, event): if self.operation_mode.mode!=self.operation_mode.NN: print 'Not in NN mode' print self.operation_mode.mode return # construct agent_state x = self.pose.pose.position.x; y = self.pose.pose.position.y v_x = self.vel.x; v_y = self.vel.y radius = self.veh_data['radius']; turning_dir = 0.0 heading_angle = self.psi pref_speed = self.veh_data['pref_speed'] goal_x = self.goal.pose.position.x; goal_y = self.goal.pose.position.y # in case current speed is larger than desired speed v = np.linalg.norm(np.array([v_x, v_y])) if v > pref_speed: v_x = v_x * pref_speed / v v_y = v_y * pref_speed / v host_agent = agent.Agent(x, y, goal_x, goal_y, radius, pref_speed, heading_angle, 0) host_agent.vel_global_frame = np.array([v_x, v_y]) # host_agent.print_agent_info() other_agents_state = copy.deepcopy(self.other_agents_state) obs = host_agent.observe(other_agents_state)[1:] obs = np.expand_dims(obs, axis=0) # print "obs:", obs predictions = self.nn.predict_p(obs)[0] # print "predictions:", predictions # print "best action index:", np.argmax(predictions) raw_action = copy.deepcopy(self.actions[np.argmax(predictions)]) action = np.array([pref_speed*raw_action[0], util.wrap(raw_action[1] + self.psi)]) # print "raw_action:", raw_action # print "action:", action # if close to goal kp_v = 0.5 kp_r = 1 if host_agent.dist_to_goal < 2.0: # and self.percentComplete>=0.9: # print "somewhat close to goal" pref_speed = max(min(kp_v * (host_agent.dist_to_goal-0.1), pref_speed), 0.0) action[0] = min(raw_action[0], pref_speed) turn_amount = max(min(kp_r * (host_agent.dist_to_goal-0.1), 1.0), 0.0) * raw_action[1] action[1] = util.wrap(turn_amount + self.psi) if host_agent.dist_to_goal < 0.3: self.stop_moving_flag = True else: self.stop_moving_flag = False # print 'chosen action (rel angle)', action[0], action[1] self.update_action(action)
def render(self): wrapped = [] for line in self.buffer: wrapped.extend(util.wrap(line, self.w)) self.clear() y = 0 for line in wrapped: self.draw(line, y, 0) y += 1 # TODO # have to have a more intelligent calculation (taking into # account line wrapping) of where the cursor is... that might # take some work, or really we'll just need to move the wrapping # into this class if self.focused: if self.editable and self.cx == self.w: self.showCursor(self.cy + 1, 0) elif self.editable: self.showCursor(self.cy, self.cx) else: self.hideCursor() else: self.hideCursor()
def cbComputeAction(self, event): tol = 1e-1 x = self.pose.position.x y = self.pose.position.y goal_x = self.global_goal.pose.position.x goal_y = self.global_goal.pose.position.y self.goalReached(tol, x, y, goal_x, goal_y) if self.new_global_goal_received: #tb3 state v_x = self.vel.x v_y = self.vel.y heading_angle = self.psi host_agent = agent.Agent(x, y, goal_x, goal_y, self.radius, self.pref_speed, heading_angle, 0) host_agent.vel_global_frame = np.array([v_x, v_y]) # Convert agent states into observation vector obs = host_agent.observe(self.other_agents_state)[1:] obs = np.expand_dims(obs, axis=0) predictions = self.nn.predict_p(obs)[0] raw_action = self.possible_actions.actions[np.argmax(predictions)] #action = np.array([host_agent.pref_speed*raw_action[0], util.wrap(raw_action[1] + host_agent.heading_global_frame)]) action = np.array([ self.pref_speed * raw_action[0], util.wrap(raw_action[1] + self.psi) ]) self.tb3Move(action)
def formatoption(block, width): desc = " ".join(map(str.strip, block["lines"])) colwidth = encoding.colwidth(block["optstr"]) usablewidth = width - 1 hanging = block["optstrwidth"] initindent = "%s%s " % (block["optstr"], " " * ((hanging - colwidth))) hangindent = " " * (encoding.colwidth(initindent) + 1) return " %s\n" % (util.wrap(desc, usablewidth, initindent=initindent, hangindent=hangindent))
def next(self): # The Exstreamers have built-in rules as to what happens if you hit next and # there is no playlist running (inevitably something will start playing). We # are going to override that to stay more in control. It's not a terribly # common scenario, anyway. if self.state == "play": self.connection.send(util.wrap(util.CMD_NEXT)) self.connection.recv(util.BUFFER_SIZE)
def listexts(header, exts, maxlength): """return a text listing of the given extensions""" if not exts: return "" result = "\n%s\n\n" % header for name, desc in sorted(exts.iteritems()): desc = util.wrap(desc, maxlength + 4) result += " %s %s\n" % (name.ljust(maxlength), desc) return result
def add_changes_markup(dom, ins_nodes, del_nodes): """ Add <ins> and <del> tags to the dom to show changes. """ # add markup for inserted and deleted sections for node in reversed(del_nodes): # diff algorithm deletes nodes in reverse order, so un-reverse the # order for this iteration insert_or_append(node.orig_parent, node, node.orig_next_sibling) wrap(node, 'del') for node in ins_nodes: wrap(node, 'ins') # Perform post-processing and cleanup. remove_nesting(dom, 'del') remove_nesting(dom, 'ins') sort_del_before_ins(dom) merge_adjacent(dom, 'del') merge_adjacent(dom, 'ins')
def set_volume(self, vol): # Volume levels are defined 0 thru 20 (off thru max). # We will accept a volume percentage (0% thru 100%). if(vol > 100 or vol < 0): raise InvalidVolumeLevel('That volume is out of range.') converted_vol = util.round_to_base(vol, 5) / 5 # convert to base 0 thru 20 self.connection.send(util.wrap(util.CMD_SETVOLUME, converted_vol)) self.connection.recv(util.BUFFER_SIZE) self.volume = vol
def listexts(header, exts, maxlength): '''return a text listing of the given extensions''' if not exts: return '' result = '\n%s\n\n' % header for name, desc in sorted(exts.iteritems()): desc = util.wrap(desc, maxlength + 4) result += ' %s %s\n' % (name.ljust(maxlength), desc) return result
def formatoption(block, width): desc = ' '.join(map(str.strip, block['lines'])) colwidth = encoding.colwidth(block['optstr']) usablewidth = width - 1 hanging = block['optstrwidth'] initindent = '%s%s ' % (block['optstr'], ' ' * ((hanging - colwidth))) hangindent = ' ' * (encoding.colwidth(initindent) + 1) return ' %s\n' % (util.wrap( desc, usablewidth, initindent=initindent, hangindent=hangindent))
def _dump_no_context_info(command, args): all_cls = {cls.name(): cls for cls in ZephyrBinaryRunner.get_runners() if command.name in cls.capabilities().commands} log.inf('All Zephyr runners which support {}:'.format(command.name), colorize=True) for line in util.wrap(', '.join(all_cls.keys()), INDENT): log.inf(line) if not args.runner: log.inf('Add -r RUNNER to print more information about any runner.', colorize=True)
def formatoption(block, width): desc = ' '.join(map(str.strip, block['lines'])) colwidth = encoding.colwidth(block['optstr']) usablewidth = width - 1 hanging = block['optstrwidth'] initindent = '%s%s ' % (block['optstr'], ' ' * ((hanging - colwidth))) hangindent = ' ' * (encoding.colwidth(initindent) + 1) return ' %s\n' % (util.wrap(desc, usablewidth, initindent=initindent, hangindent=hangindent))
def predict_action(self, obs): #QUery the policy based on obs vector predictions = self.nn.predict_p(obs)[0] raw_action = self.possible_actions.actions[np.argmax(predictions)] action = np.array([ host_agent.pref_speed * raw_action[0], util.wrap(raw_action[1] + host_agent.heading_global_frame) ]) # print "action:", action # Action contains: [new forward speed, change in heading angle] return action
def render(self): """ redraw what's in the visible range, based on our size and firstVisible """ if self.lines is None: self.lines = util.wrap(self.text, self.w) self.clear() for i in range(self.firstVisible, min(len(self.lines), self.firstVisible + self.h)): self.draw(self.lines[i], i - self.firstVisible, 0);
def control(self, event): possible_actions = network.Actions() num_actions = possible_actions.num_actions nn = network.NetworkVP_rnn(network.Config.DEVICE, 'network', num_actions) nn.simple_load( '/home/yeguo/turtlebot3_ws/src/cadrl_ros/checkpoints/network_01900000' ) host_agent = agent.Agent(self.host_pos_x, self.host_pos_y, self.host_goal_x, self.host_goal_y, self.radius, self.pref_speed, self.host_heading_angle, 0) host_agent.vel_global_frame = np.array([self.host_vx, self.host_vy]) other_agents = [] #other_agents.append(agent.Agent(self.tb3_0_pos_x, self.tb3_0_pos_y, self.tb3_0_goal_x, self.tb3_0_goal_y, self.radius, self.pref_speed, self.other_agents_heading_angle, 1)) other_agents.append( agent.Agent(self.tb3_1_pos_x, self.tb3_1_pos_y, self.tb3_1_goal_x, self.tb3_1_goal_y, self.radius, self.pref_speed, self.other_agents_heading_angle, 2)) #other_agents.append(agent.Agent(self.tb3_2_pos_x, self.tb3_2_pos_y, self.tb3_2_goal_x, self.tb3_2_goal_y, self.radius, self.pref_speed, self.other_agents_heading_angle, 3)) obs = host_agent.observe(other_agents)[1:] obs = np.expand_dims(obs, axis=0) predictions = nn.predict_p(obs, None)[0] raw_action = possible_actions.actions[np.argmax(predictions)] action = np.array([ host_agent.pref_speed * raw_action[0], util.wrap(raw_action[1] + host_agent.heading_global_frame) ]) print "action:", action command = Twist() command.linear.x = action[0] yaw_error = action[1] - self.psi if yaw_error > np.pi: yaw_error -= 2 * np.pi if yaw_error < -np.pi: yaw_error += 2 * np.pi command.angular.z = 2 * yaw_error print "host command:", command self.host_cmd_vel_pub.publish(command) #control agents tb3_0_command = Twist() tb3_0_command.linear.x = 0.05 self.tb3_0_cmd_vel_pub.publish(tb3_0_command) tb3_1_command = Twist() tb3_1_command.linear.x = 0.05 self.tb3_1_cmd_vel_pub.publish(tb3_1_command) tb3_2_command = Twist() tb3_2_command.linear.x = 0.05 self.tb3_2_cmd_vel_pub.publish(tb3_2_command)
def rotate_and_shift_mps(mps, start_pos, start_theta): # start_pos = [x, y] (2-element np.array) # start_theta = angle (float) rotation_matrix = np.array([[np.cos(start_theta), np.sin(start_theta)], [-np.sin(start_theta), np.cos(start_theta)]]) rotated_mps = np.empty_like(mps) rotated_mps[:, :, :2] = np.dot(mps[:, :, :2], rotation_matrix) rotated_mps[:, :, 2] = util.wrap(mps[:, :, 2] + start_theta) rotated_and_shifted_mps = np.empty_like(mps) rotated_and_shifted_mps[:, :, :2] = rotated_mps[:, :, :2] + start_pos rotated_and_shifted_mps[:, :, 2] = rotated_mps[:, :, 2] return rotated_and_shifted_mps
def run(self): # print 'Epoch:', self.index # print 'Start Pos:', start_x, start_y index = 0 host_agent = agent.Agent(self.start_x, self.start_y, self.goal_x, self.goal_y, self.radius, self.pref_speed, self.heading_angle, index) host_agent.vel_global_frame = np.array( [self.velocity_x, self.velocity_y]) # Sample observation data in a format easily generated from sensors other_agents_x = self.other_agents_x #[ 4, 7] other_agents_y = self.other_agents_y #[ 2, 2] other_agents_r = self.other_agents_r #[ 1, 2.5] other_agents_vx = self.other_agents_vx #[ 0, 0] other_agents_vy = self.other_agents_y #[ 0, 0] num_other_agents = len(other_agents_x) # Create Agent objects for each observed dynamic obstacle other_agents = [] for i in range(num_other_agents): x = other_agents_x[i] y = other_agents_y[i] v_x = other_agents_vx[i] v_y = other_agents_vy[i] radius = other_agents_r[i] # dummy info - unobservable states not used by NN, just needed to create Agent object heading_angle = np.arctan2(v_y, v_x) pref_speed = np.linalg.norm(np.array([v_x, v_y])) goal_x = x + 5.0 goal_y = y + 5.0 other_agents.append( agent.Agent(x, y, goal_x, goal_y, radius, pref_speed, heading_angle, i + 1)) obs = host_agent.observe(other_agents)[1:] obs = np.expand_dims(obs, axis=0) predictions = self.nn.predict_p(obs, None)[0] raw_action = self.a.actions[np.argmax(predictions)] action = np.array([ host_agent.pref_speed * raw_action[0], util.wrap(raw_action[1] + host_agent.heading_global_frame) ]) return action
def get_agentCMD(self): host_agent, goal_x, goal_y = self.get_agentState() other_agents = self.observe_others(goal_x, goal_y) #convert agent state into obs vector obs = host_agent.observe(other_agents)[1:] obs = np.expand_dims(obs, axis=0) #QUery the policy based on obs vector predictions = self.nn.predict_p(obs)[0] raw_action = self.possible_actions.actions[np.argmax(predictions)] action = np.array([ host_agent.pref_speed * raw_action[0], util.wrap(raw_action[1] + host_agent.heading_global_frame) ]) print "action:", action # Action contains: [new forward speed, change in heading angle] self.control_vel(action)
def husky_compute_actions(self, event): x = self.pose[0] y = self.pose[1] heading_angle = self.pose[2] goal_x = self.goal_x goal_y = self.goal_y radius = self.radius pref_speed = self.pref_speed distance = sqrt((self.pose[0] - self.goals[-1][0])**2 + (self.pose[1] - self.goals[-1][1])**2) if distance < 2: pref_speed = 0.3 index = self.index vx = self.vel * np.cos(heading_angle) vy = self.vel * np.sin(heading_angle) host_agent = agent.Agent(x, y, goal_x, goal_y, radius, pref_speed, heading_angle, index) host_agent.vel_global_frame = np.array([vx, vy]) # host_agent.print_agent_info() other_agents_state = copy.deepcopy(self.other_agent) obs = host_agent.observe(other_agents_state)[1:] obs = np.expand_dims(obs, axis=0) # print "obs:", obs predictions = self.nn.predict_p(obs)[0] raw_action = copy.deepcopy(self.actions[np.argmax(predictions)]) action = np.array([ pref_speed * raw_action[0], util.wrap(raw_action[1] + self.pose[2]) ]) distance = sqrt((self.pose[0] - self.goals[-1][0])**2 + (self.pose[1] - self.goals[-1][1])**2) if distance < 0.5: action = [0, 0] rospy.signal_shutdown('Done') self.desired_action = action return
def run_(self): # Create unused authcode and register callback authcode = self.irc_bot.new_auth_callback(self.do_authentication) msg = wrap(""" Your Authcode is: {authcode} Within {conf.irc.auth_timeout}s, send "{nick} auth {authcode}" in {conf.irc.channel} on {conf.irc.host} with your usual nickname. If you want the bot to use a different name than your current IRC name, add an additional argument which will be stored instead (for the slack <-> IRC proxy). Example: "{nick} auth {authcode} my_actual_name" You can re-authenticate any time to overwrite the stored nick. """).format(conf=self.conf, authcode=authcode, nick=self.irc_bot.nick) self.tg_bot.send_message(self.message.chat.id, msg) # Register callback ... l.info("initiated authentication for {0.sender}, authcode: {1}", self.message, authcode) # ... and wait until do_authentication gets called, or timeout start_time = time.time() while time.time() < start_time + (self.conf.irc.auth_timeout or 300): if self.authenticated: break time.sleep(0.5) else: l.info("authentication timed out for {0.sender}", self.message) self.tg_bot.send_message(self.message.chat.id, "Authentication timed out") # Finish thread self.irc_bot.remove_auth_callback(authcode)
def create_prompts(self) -> None: self.main_prompt = modify(""" _ __ _ | |/ / | | | ' /_ _ _ __ ___| | __ | <| | | | '__/ __| |/ / | . \\ |_| | | \\__ \\ < |_|\\_\\__,_|_| |___/_|\\_\\ _____ _ _ _ / ____(_) | | | | | (___ _ _ __ ___ _ _| | __ _| |_ ___ _ __ \\___ \\| | '_ ` _ \\| | | | |/ _` | __/ _ \\| '__| ____) | | | | | | | |_| | | (_| | || (_) | | |_____/|_|_| |_| |_|\\__,_|_|\\__,_|\\__\\___/|_| __ ___ _ _ ____ /_ |/ _ \\| || ||___ \\ | | (_) | || |_ __) | | |\\__, |__ _|__ < | | / / | | ___) | |_| /_/ |_||____/ """, Color.YELLOW, Style.BOLD) + \ " " + color("1. ", Color.CYAN) + \ modify("Start", Color.YELLOW, Style.UNDERLINE) + " " + \ color("2. ", Color.CYAN) + \ modify("About Kursk Simulator", Color.YELLOW, Style.UNDERLINE) + " " + \ color("3. ", Color.CYAN) + modify("Quit", Color.YELLOW, Style.UNDERLINE) + "\n" about_message = wrap(""" Kursk Simulator: 1943 is a tank gunnery simulator built in Python. Tank armour layouts and weapon penetration are modeled based on historical data collected by the Allied governments after WWII. Kursk Simulator models the overmatch mechanics (the interactions between weapons and armour that determine the penetration, or non-penetration of a shell through armour) of tank gunnery, with a simplified and stylized model based on elementary physics. """) self.about_prompt = self.main_prompt + "\n" + about_message
def testWrap(self): self.assertEqual("This\nis", util.wrap("This\nis", 80)) self.assertEqual("This is ", util.wrap("This is", 80)) self.assertEqual("This\nis ", util.wrap("This is", 3)) self.assertEqual("This\nis\n", util.wrap("This is\n", 3))
def previous(self): # See comment of next() if self.state == "play": self.connection.send(util.wrap(util.CMD_PREVIOUS)) self.connection.recv(util.BUFFER_SIZE)
def cbComputeActionGA3C(self, event): if self.operation_mode.mode!=self.operation_mode.NN or self.stop_moving_flag: # print 'Not in NN mode' # print self.operation_mode.mode return # construct agent_state x = self.pose.pose.position.x; y = self.pose.pose.position.y v_x = self.vel.x; v_y = self.vel.y radius = self.veh_data['radius']; turning_dir = 0.0 heading_angle = self.psi pref_speed = self.veh_data['pref_speed'] goal_x = self.sub_goal.x goal_y = self.sub_goal.y marker_goal = [goal_x, goal_y] self.visualize_subgoal(marker_goal, None) # in case current speed is larger than desired speed # print goal_x+goal_y v = np.linalg.norm(np.array([v_x, v_y])) if v > pref_speed: v_x = v_x * pref_speed / v v_y = v_y * pref_speed / v host_agent = agent.Agent(x, y, goal_x, goal_y, radius, pref_speed, heading_angle, 0) host_agent.vel_global_frame = np.array([v_x, v_y]) # host_agent.print_agent_info() other_agents_state = copy.deepcopy(self.other_agents_state) obs = host_agent.observe(other_agents_state)[1:] obs = np.expand_dims(obs, axis=0) #predictions = self.nn.predict_p(obs,None)[0] predictions = self.nn.predict_p(obs)[0] raw_action = copy.deepcopy(self.actions[np.argmax(predictions)]) action = np.array([pref_speed*raw_action[0], util.wrap(raw_action[1] + self.psi)]) # if close to goal kp_v = 0.5 kp_r = 1 if host_agent.dist_to_goal < 2.0: # and self.percentComplete>=0.9: # print "somewhat close to goal" pref_speed = max(min(kp_v * (host_agent.dist_to_goal-0.1), pref_speed), 0.0) action[0] = min(raw_action[0], pref_speed) turn_amount = max(min(kp_r * (host_agent.dist_to_goal-0.1), 1.0), 0.0) * raw_action[1] action[1] = util.wrap(turn_amount + self.psi) if host_agent.dist_to_goal < 0.3: # current goal, reached, increment for next goal print("===============\ngoal reached: "+str([goal_x, goal_y])) self.stop_moving_flag = True self.new_global_goal_received = False self.stop_moving() # self.goal_idx += 1 else: self.stop_moving_flag = False self.update_action(action)
def write(self, write_buf, encode_hdlc=False): if encode_hdlc: write_buf = util.wrap(write_buf) self.port.write(write_buf)
def formatblock(block, width): """Format a block according to width.""" if width <= 0: width = 78 indent = ' ' * block['indent'] if block['type'] == 'admonition': admonition = _admonitiontitles[block['admonitiontitle']] hang = len(block['lines'][-1]) - len(block['lines'][-1].lstrip()) defindent = indent + hang * ' ' text = ' '.join(map(str.strip, block['lines'])) return '%s\n%s' % ( indent + admonition, util.wrap( text, width=width, initindent=defindent, hangindent=defindent)) if block['type'] == 'margin': return '' if block['type'] == 'literal': indent += ' ' return indent + ('\n' + indent).join(block['lines']) if block['type'] == 'section': underline = encoding.colwidth(block['lines'][0]) * block['underline'] return "%s%s\n%s%s" % (indent, block['lines'][0], indent, underline) if block['type'] == 'definition': term = indent + block['lines'][0] hang = len(block['lines'][-1]) - len(block['lines'][-1].lstrip()) defindent = indent + hang * ' ' text = ' '.join(map(str.strip, block['lines'][1:])) return '%s\n%s' % ( term, util.wrap( text, width=width, initindent=defindent, hangindent=defindent)) subindent = indent if block['type'] == 'bullet': if block['lines'][0].startswith('| '): # Remove bullet for line blocks and add no extra # indention. block['lines'][0] = block['lines'][0][2:] else: m = _bulletre.match(block['lines'][0]) subindent = indent + m.end() * ' ' elif block['type'] == 'field': keywidth = block['keywidth'] key = block['key'] subindent = indent + _fieldwidth * ' ' if len(key) + 2 > _fieldwidth: # key too large, use full line width key = key.ljust(width) elif keywidth + 2 < _fieldwidth: # all keys are small, add only two spaces key = key.ljust(keywidth + 2) subindent = indent + (keywidth + 2) * ' ' else: # mixed sizes, use fieldwidth for this one key = key.ljust(_fieldwidth) block['lines'][0] = key + block['lines'][0] elif block['type'] == 'option': m = _optionre.match(block['lines'][0]) option, arg, rest = m.groups() subindent = indent + (len(option) + len(arg)) * ' ' text = ' '.join(map(str.strip, block['lines'])) return util.wrap(text, width=width, initindent=indent, hangindent=subindent)
def formatblock(block, width): """Format a block according to width.""" if width <= 0: width = 78 indent = ' ' * block['indent'] if block['type'] == 'admonition': admonition = _admonitiontitles[block['admonitiontitle']] if not block['lines']: return indent + admonition + '\n' hang = len(block['lines'][-1]) - len(block['lines'][-1].lstrip()) defindent = indent + hang * ' ' text = ' '.join(map(str.strip, block['lines'])) return '%s\n%s\n' % ( indent + admonition, util.wrap( text, width=width, initindent=defindent, hangindent=defindent)) if block['type'] == 'margin': return '\n' if block['type'] == 'literal': indent += ' ' return indent + ('\n' + indent).join(block['lines']) + '\n' if block['type'] == 'section': underline = encoding.colwidth(block['lines'][0]) * block['underline'] return "%s%s\n%s%s\n" % (indent, block['lines'][0], indent, underline) if block['type'] == 'table': table = block['table'] # compute column widths widths = [max([encoding.colwidth(e) for e in c]) for c in zip(*table)] text = '' span = sum(widths) + len(widths) - 1 indent = ' ' * block['indent'] hang = ' ' * (len(indent) + span - widths[-1]) for row in table: l = [] for w, v in zip(widths, row): pad = ' ' * (w - encoding.colwidth(v)) l.append(v + pad) l = ' '.join(l) l = util.wrap(l, width=width, initindent=indent, hangindent=hang) if not text and block['header']: text = l + '\n' + indent + '-' * (min(width, span)) + '\n' else: text += l + "\n" return text if block['type'] == 'definition': term = indent + block['lines'][0] hang = len(block['lines'][-1]) - len(block['lines'][-1].lstrip()) defindent = indent + hang * ' ' text = ' '.join(map(str.strip, block['lines'][1:])) return '%s\n%s\n' % ( term, util.wrap( text, width=width, initindent=defindent, hangindent=defindent)) subindent = indent if block['type'] == 'bullet': if block['lines'][0].startswith('| '): # Remove bullet for line blocks and add no extra # indention. block['lines'][0] = block['lines'][0][2:] else: m = _bulletre.match(block['lines'][0]) subindent = indent + m.end() * ' ' elif block['type'] == 'field': key = block['key'] subindent = indent + _fieldwidth * ' ' if len(key) + 2 > _fieldwidth: # key too large, use full line width key = key.ljust(width) else: # key fits within field width key = key.ljust(_fieldwidth) block['lines'][0] = key + block['lines'][0] elif block['type'] == 'option': return formatoption(block, width) text = ' '.join(map(str.strip, block['lines'])) return util.wrap( text, width=width, initindent=indent, hangindent=subindent) + '\n'
def write(self, write_buf, encode_hdlc = False): if encode_hdlc: write_buf = util.wrap(write_buf) self.w_handle.write(write_buf)
def get_device_volume(self): self.connection.send(util.wrap(util.CMD_GETVOLUME)) raw_vol = self.connection.recv(util.BUFFER_SIZE) vol_xml = etree.fromstring(raw_vol) # create xml representation return int(vol_xml.text) * 5 # convert to percentage
def _wrap(s, width, indent, subindent=None): subindent = subindent or indent return util.wrap(s, width, indent=indent, subindent=subindent)
def cbComputeActionGA3C(self, event): feasible_actions = copy.deepcopy(self.feasible_actions) if self.operation_mode.mode != self.operation_mode.NN: print 'Not in NN mode' print self.operation_mode.mode return if len(feasible_actions.angles) == 0 \ or len(feasible_actions.path_lengths)==0: print 'Invalid Feasible Actions' # print feasible_actions return # construct agent_state x = self.pose.pose.position.x y = self.pose.pose.position.y v_x = self.vel.x v_y = self.vel.y radius = self.veh_data['radius'] turning_dir = 0.0 heading_angle = self.psi pref_speed = self.veh_data['pref_speed'] goal_x = self.goal.pose.position.x goal_y = self.goal.pose.position.y # in case current speed is larger than desired speed v = np.linalg.norm(np.array([v_x, v_y])) if v > pref_speed: v_x = v_x * pref_speed / v v_y = v_y * pref_speed / v host_agent = agent.Agent(x, y, goal_x, goal_y, radius, pref_speed, heading_angle, 0) host_agent.vel_global_frame = np.array([v_x, v_y]) # host_agent.print_agent_info() other_agents_state = copy.deepcopy(self.other_agents_state) obs = host_agent.observe(other_agents_state)[1:] obs = np.expand_dims(obs, axis=0) # print "obs:", obs predictions = self.nn.predict_p(obs, None)[0] # print "predictions:", predictions # print "best action index:", np.argmax(predictions) raw_action = copy.deepcopy(self.actions[np.argmax(predictions)]) action = np.array( [pref_speed * raw_action[0], util.wrap(raw_action[1] + self.psi)]) # print "raw_action:", raw_action # print "action:", action # feasible_actions angles = (np.array(feasible_actions.angles) + np.pi) % (2 * np.pi) - np.pi max_ranges = np.array(feasible_actions.max_speeds) - 0.3 path_lengths = np.array(feasible_actions.path_lengths) # Sort the feasible actions by increasing angle order_inds = np.argsort(angles) max_ranges = max_ranges[order_inds] angles = angles[order_inds] path_lengths = path_lengths[order_inds] # Find which index corresponds to straight in front, and 90 deg each side zero_ind = np.digitize([self.psi + 0.01], angles) - 1 self.d_min = max_ranges[zero_ind] # self.d_min = 100.0 # if close to goal kp_v = 0.5 kp_r = 1 if host_agent.dist_to_goal < 2.0: # and self.percentComplete>=0.9: # print "somewhat close to goal" pref_speed = max( min(kp_v * (host_agent.dist_to_goal - 0.1), pref_speed), 0.0) action[0] = min(raw_action[0], pref_speed) turn_amount = max(min(kp_r * (host_agent.dist_to_goal - 0.1), 1.0), 0.0) * raw_action[1] action[1] = util.wrap(turn_amount + self.psi) if host_agent.dist_to_goal < 0.3: self.stop_moving_flag = True else: self.stop_moving_flag = False # print 'chosen action (rel angle)', action[0], action[1] self.update_action(action)
def formatblock(block, width): """Format a block according to width.""" if width <= 0: width = 78 indent = ' ' * block['indent'] if block['type'] == 'admonition': admonition = _admonitiontitles[block['admonitiontitle']] hang = len(block['lines'][-1]) - len(block['lines'][-1].lstrip()) defindent = indent + hang * ' ' text = ' '.join(map(str.strip, block['lines'])) return '%s\n%s\n' % (indent + admonition, util.wrap(text, width=width, initindent=defindent, hangindent=defindent)) if block['type'] == 'margin': return '\n' if block['type'] == 'literal': indent += ' ' return indent + ('\n' + indent).join(block['lines']) + '\n' if block['type'] == 'section': underline = encoding.colwidth(block['lines'][0]) * block['underline'] return "%s%s\n%s%s\n" % (indent, block['lines'][0],indent, underline) if block['type'] == 'table': table = block['table'] # compute column widths widths = [max([encoding.colwidth(e) for e in c]) for c in zip(*table)] text = '' span = sum(widths) + len(widths) - 1 indent = ' ' * block['indent'] hang = ' ' * (len(indent) + span - widths[-1]) for row in table: l = [] for w, v in zip(widths, row): pad = ' ' * (w - encoding.colwidth(v)) l.append(v + pad) l = ' '.join(l) l = util.wrap(l, width=width, initindent=indent, hangindent=hang) if not text and block['header']: text = l + '\n' + indent + '-' * (min(width, span)) + '\n' else: text += l + "\n" return text if block['type'] == 'definition': term = indent + block['lines'][0] hang = len(block['lines'][-1]) - len(block['lines'][-1].lstrip()) defindent = indent + hang * ' ' text = ' '.join(map(str.strip, block['lines'][1:])) return '%s\n%s\n' % (term, util.wrap(text, width=width, initindent=defindent, hangindent=defindent)) subindent = indent if block['type'] == 'bullet': if block['lines'][0].startswith('| '): # Remove bullet for line blocks and add no extra # indention. block['lines'][0] = block['lines'][0][2:] else: m = _bulletre.match(block['lines'][0]) subindent = indent + m.end() * ' ' elif block['type'] == 'field': key = block['key'] subindent = indent + _fieldwidth * ' ' if len(key) + 2 > _fieldwidth: # key too large, use full line width key = key.ljust(width) else: # key fits within field width key = key.ljust(_fieldwidth) block['lines'][0] = key + block['lines'][0] elif block['type'] == 'option': return formatoption(block, width) text = ' '.join(map(str.strip, block['lines'])) return util.wrap(text, width=width, initindent=indent, hangindent=subindent) + '\n'
def _dump_context(command, args, runner_args, cached_runner_var): build_dir = _build_dir(args, die_if_none=False) # Try to figure out the CMake cache file based on the build # directory or an explicit argument. if build_dir is not None: cache_file = path.abspath( path.join(build_dir, args.cmake_cache or cmake.DEFAULT_CACHE)) elif args.cmake_cache: cache_file = path.abspath(args.cmake_cache) else: cache_file = None # Load the cache itself, if possible. if cache_file is None: log.wrn('No build directory (--build-dir) or CMake cache ' '(--cache-file) given or found; output will be limited') cache = None else: try: cache = cmake.CMakeCache(cache_file) except Exception: log.die('Cannot load cache {}.'.format(cache_file)) # If we have a build directory, try to ensure build artifacts are # up to date. If that doesn't work, still try to print information # on a best-effort basis. if build_dir and not args.skip_rebuild: try: cmake.run_build(build_dir) except CalledProcessError: msg = 'Failed re-building application; cannot load context. ' if args.build_dir: msg += 'Is {} the right --build-dir?'.format(args.build_dir) else: msg += textwrap.dedent('''\ Use --build-dir (-d) to specify a build directory; the one used was {}.'''.format(build_dir)) log.die('\n'.join(textwrap.wrap(msg, initial_indent='', subsequent_indent=INDENT, break_on_hyphens=False))) if cache is None: _dump_no_context_info(command, args) if not args.runner: return if args.runner: # Just information on one runner was requested. _dump_one_runner_info(cache, args, build_dir, INDENT) return board = cache['CACHED_BOARD'] all_cls = {cls.name(): cls for cls in ZephyrBinaryRunner.get_runners() if command.name in cls.capabilities().commands} available = [r for r in cache.get_list('ZEPHYR_RUNNERS') if r in all_cls] available_cls = {r: all_cls[r] for r in available if r in all_cls} default_runner = cache.get(cached_runner_var) cfg = cached_runner_config(build_dir, cache) log.inf('All Zephyr runners which support {}:'.format(command.name), colorize=True) for line in util.wrap(', '.join(all_cls.keys()), INDENT): log.inf(line) log.inf('(Not all may work with this build, see available runners below.)', colorize=True) if cache is None: log.warn('Missing or invalid CMake cache {}; there is no context.', 'Use --build-dir to specify the build directory.') return log.inf('Build directory:', colorize=True) log.inf(INDENT + build_dir) log.inf('Board:', colorize=True) log.inf(INDENT + board) log.inf('CMake cache:', colorize=True) log.inf(INDENT + cache_file) if not available: # Bail with a message if no runners are available. msg = ('No runners available for {}. ' 'Consult the documentation for instructions on how to run ' 'binaries on this target.').format(board) for line in util.wrap(msg, ''): log.inf(line, colorize=True) return log.inf('Available {} runners:'.format(command.name), colorize=True) log.inf(INDENT + ', '.join(available)) log.inf('Additional options for available', command.name, 'runners:', colorize=True) for runner in available: _dump_runner_opt_help(runner, all_cls[runner]) log.inf('Default {} runner:'.format(command.name), colorize=True) log.inf(INDENT + default_runner) _dump_runner_config(cfg, '', INDENT) log.inf('Runner-specific information:', colorize=True) for runner in available: log.inf('{}{}:'.format(INDENT, runner), colorize=True) _dump_runner_cached_opts(cache, runner, INDENT * 2, INDENT * 3) _dump_runner_caps(available_cls[runner], INDENT * 2) if len(available) > 1: log.inf('(Add -r RUNNER to just print information about one runner.)', colorize=True)
########## 6 parent deck pulls new cards from all children instead of sequentially (ie. mostly first) def my_fillNew( self, _old ): '''If 'new card merged fill' is enabled for the current deck, when we refill we pull from all child decks, sort combined pool of cards, then limit. If disabled, do the standard sequential fill method''' C = partial( cfg, None, self.col.decks.active()[0] ) if not C('new card merged fill'): return _old( self ) if self._newQueue: return True if not self.newCount: return False self._newQueue = self.col.db.all('''select id, due from cards where did in %s and queue = 0 and due >= ? order by due limit ?''' % self._deckLimit(), C('new card merged fill min due'), self.queueLimit ) if self._newQueue: return True sched.Scheduler._fillNew = wrap( sched.Scheduler._fillNew, my_fillNew, 'around' ) ########## handle skipping for 1-2 seenMorphs = set() def markFocusSeen( self, n ): '''Mark a focusMorph as already seen so future new cards with the same focus will be skipped. Also prints number of cards to be skipped if enabled''' global seenMorphs try: if not focus( n ): return q = u'%s:%s' % ( focusName( n ), focus( n ) ) except KeyError: return seenMorphs.add( focus(n) ) numSkipped = len( self.mw.col.findNotes( q ) ) -1 if numSkipped and cfg1('print number of alternatives skipped'):
:param day_mae_mse: :return: ''' maes = np.vstack((mae_mse[0] for mae_mse in mae_mse_by_hours)).T mses = np.vstack((mae_mse[1] for mae_mse in mae_mse_by_hours)).T level_datas = np.hstack((level_data for level_data in level_by_hours)) day_maes = np.vstack((mae_mse[0] for mae_mse in day_mae_mse)).T day_mses = np.vstack((mae_mse[1] for mae_mse in day_mae_mse)).T results = np.hstack((maes, mses, level_datas, day_maes, day_mses)) return results if __name__ == '__main__': data = process_all() coll=Connect_DB() mongo_data= ReadOneStation(coll,start_time,end_time) wrap(data,mongo_data) # 使用偏函数 固定data,便于之后map操作 #data = np.load('2015_12_30.npz')['arr_0'] cal_mae_mse = partial(calculate_mae_mse, data) cal_level = partial(calculate_level, data) cal_day_mae_mse = partial(calculate_day_mae_mse, data) mae_mse_by_hours = map(cal_mae_mse, gaps) level_by_hours = map(cal_level, gaps) day_mae_mse = map(cal_day_mae_mse, day_gaps) results = h_stack_data(mae_mse_by_hours, level_by_hours, day_mae_mse) insert_to_mongo(db, results)
def main(): args = parser.parse_args() sequence = args.file.read() header, _, remain = sequence.partition("\n") if (header.startswith(">")): sequence = remain else: header = None sequence = sequence.replace("\n", "").upper() isDna = detectDNA(sequence) if (isDna is None): eprint("ERROR: Could not detect DNA/RNA") sys.exit(1) if (isDna): sequence = dnaToRna(sequence) #print("IN SEQ ",sequence) #print("IN SEQ ",complement(sequence)); allTranslated = [] for name, seq in permute(sequence, args.regenerateFromThreePrime): #print("translating",name.ljust(2),subdivide(seq)); translated = translate(seq) unbrokenLength = countWithoutStop(translated) if args.readingframe: if int(name) == args.readingframe: allTranslated.append((unbrokenLength, name, translated)) else: allTranslated.append((unbrokenLength, name, translated)) def getKey(item): return item[0] if (not args.orderByFrame): allTranslated.sort(key=getKey, reverse=True) for trans in allTranslated[1:]: unbrokenLength, name, translated = trans longest = allTranslated[0][0] warnSize = args.warnLength.strip() if args.warnLength.endswith("%"): warnSize = longest * float(warnSize.strip("%")) / 100 warnSize = int(warnSize) if (unbrokenLength >= warnSize): name, _, _ = header.partition(" ") name = name.strip(">") sys.stderr.write( "Translate: long frame detected in %s length:%d (longest: %d)\n" % (name, unbrokenLength, allTranslated[0][0])) if (args.readingFrameOnly): if (header): print(header, "[longest reading frame only]") print( util.wrap(extractLongestReadingFrame(allTranslated[0][2]), args.wrap)) elif (not args.showAll): if (header): print(header) print(util.wrap(allTranslated[0][2], args.wrap)) else: #showall for trans in allTranslated: unbrokenLength, name, translated = trans print("Frame %s (max length %d)" % (name, unbrokenLength)) if (header): print(header) print(translated) print()
def stop(self): # We can stop at any time; this command will always execute. self.connection.send(util.wrap(util.CMD_STOP)) self.connection.recv(util.BUFFER_SIZE) self.state = "stop"
d['goals'][ name ] = { 'total':numUniqueReq, 'known':numUniqueKnown, 'freqTotal':numFreqReq, 'freqKnown':numFreqKnown } saveStats( d ) mw.progress.finish() return d def getStatsLink(): d = loadStats() if not d: return ( 'K ???', '????' ) name = 'K %d' % d['totalKnown'] lines = [] for goalName, g in sorted( d['goals'].items() ): #lines.append( '%s %d/%d %d%%' % ( goalName, g['known'], g['total'], 100.*g['known']/g['total'] ) ) #lines.append( '%s %d%%' % ( goalName, 100.*g['known']/g['total'] ) ) lines.append( '%s %d%% %d%%' % ( goalName, 100.*g['known']/g['total'], 100.*g['freqKnown']/g['freqTotal'] ) ) details = '\n'.join( lines ) return ( name, details ) def my_centerLinks( self, _old ): name, details = getStatsLink() links = [ ["decks", _("Decks"), _("Shortcut key: %s") % "D"], ["add", _("Add"), _("Shortcut key: %s") % "A"], ["browse", _("Browse"), _("Shortcut key: %s") % "B"], ["morph", _(name), _(details)], ] return self._linkHTML( links ) toolbar.Toolbar._centerLinks = wrap( toolbar.Toolbar._centerLinks, my_centerLinks, 'around' )
def formatblock(block, width): """Format a block according to width.""" if width <= 0: width = 78 indent = ' ' * block['indent'] if block['type'] == 'admonition': admonition = _admonitiontitles[block['admonitiontitle']] hang = len(block['lines'][-1]) - len(block['lines'][-1].lstrip()) defindent = indent + hang * ' ' text = ' '.join(map(str.strip, block['lines'])) return '%s\n%s' % (indent + admonition, util.wrap(text, width=width, initindent=defindent, hangindent=defindent)) if block['type'] == 'margin': return '' if block['type'] == 'literal': indent += ' ' return indent + ('\n' + indent).join(block['lines']) if block['type'] == 'section': underline = encoding.colwidth(block['lines'][0]) * block['underline'] return "%s%s\n%s%s" % (indent, block['lines'][0],indent, underline) if block['type'] == 'definition': term = indent + block['lines'][0] hang = len(block['lines'][-1]) - len(block['lines'][-1].lstrip()) defindent = indent + hang * ' ' text = ' '.join(map(str.strip, block['lines'][1:])) return '%s\n%s' % (term, util.wrap(text, width=width, initindent=defindent, hangindent=defindent)) subindent = indent if block['type'] == 'bullet': if block['lines'][0].startswith('| '): # Remove bullet for line blocks and add no extra # indention. block['lines'][0] = block['lines'][0][2:] else: m = _bulletre.match(block['lines'][0]) subindent = indent + m.end() * ' ' elif block['type'] == 'field': keywidth = block['keywidth'] key = block['key'] subindent = indent + _fieldwidth * ' ' if len(key) + 2 > _fieldwidth: # key too large, use full line width key = key.ljust(width) elif keywidth + 2 < _fieldwidth: # all keys are small, add only two spaces key = key.ljust(keywidth + 2) subindent = indent + (keywidth + 2) * ' ' else: # mixed sizes, use fieldwidth for this one key = key.ljust(_fieldwidth) block['lines'][0] = key + block['lines'][0] elif block['type'] == 'option': return formatoption(block, width) text = ' '.join(map(str.strip, block['lines'])) return util.wrap(text, width=width, initindent=indent, hangindent=subindent)
def getStatsLink(): d = loadStats() if not d: return ('K ???', '????') name = 'K %d' % d['totalKnown'] lines = [] for goalName, g in sorted(d['goals'].items()): #lines.append( '%s %d/%d %d%%' % ( goalName, g['known'], g['total'], 100.*g['known']/g['total'] ) ) #lines.append( '%s %d%%' % ( goalName, 100.*g['known']/g['total'] ) ) lines.append('%s %d%% %d%%' % (goalName, 100. * g['known'] / g['total'], 100. * g['freqKnown'] / g['freqTotal'])) details = '\n'.join(lines) return (name, details) def my_centerLinks(self, _old): name, details = getStatsLink() links = [ ["decks", _("Decks"), _("Shortcut key: %s") % "D"], ["add", _("Add"), _("Shortcut key: %s") % "A"], ["browse", _("Browse"), _("Shortcut key: %s") % "B"], ["morph", _(name), _(details)], ] return self._linkHTML(links) toolbar.Toolbar._centerLinks = wrap(toolbar.Toolbar._centerLinks, my_centerLinks, 'around')
def help(self): """ Write option help out to the provide ui/shell. The help output consists of a usage string, a short command description, a detailed/long command description (formated from ReST - ReStructured Text), optional list of valid sub-commands, and a list of option groups (each option group represents the options of this or parent commands). Example:: usage: app cmd [options] an example short description A longer description of the sub-command 'cmd' handled by the base application 'app'. commands: sub-cmd a short description of the sub-cmd cmd options: -a --alpha description of the 'alpha' option -b --bravo INT description of the 'bravo' option app options: -c --charlie description of the 'charlie' option The above example shows the help generated for a command 'cmd' handled by the base command (or application) 'app'. The command 'cmd' also has a sub-command named 'sub-cmd'. """ self.ui.write('usage: %s %s\n\n' % (self._parent_usage(), self.usage)) self.ui.write('%s\n\n' % self.short_desc()) long_desc = self.long_desc() if long_desc: long_desc = self.ui.rst(long_desc, indent=' ') if long_desc: self.ui.write('%s\n\n' % long_desc) cmds = {} for name, cmd in self.cmdtable.iteritems(): name = ' %s ' % name.split('|')[0] cmds[name] = cmd.short_desc() cmds = [(key, cmds[key]) for key in sorted(cmds.iterkeys())] groups = [] indent = 0 if cmds: groups.append(('commands', cmds)) indent = max(len(c[0]) for c in cmds) indent_, groups_ = self._option_help() groups.extend(groups_) indent = max(indent, indent_) hanging = indent * ' ' for group in groups: self.ui.write('%s:\n\n' % group[0]) for opt in group[1]: self.ui.write('%s\n' % util.wrap( opt[1], self.ui.termwidth(), opt[0].ljust(indent), hanging)) self.ui.write('\n')
def update_state(self, action, dt): if self.is_at_goal or self.ran_out_of_time or self.in_collision: if self.is_at_goal: self.was_at_goal_already = True if self.in_collision: self.was_in_collision_already = True self.vel_global_frame = np.array([0.0, 0.0]) return # self.past_actions = np.roll(self.past_actions,1,axis=0) # self.past_actions[0,:] = action if self.action_time_lag > 0: # Store current action in dictionary, then look up the past action that should be executed this step self.chosen_action_dict[self.t] = action # print "-------------" # print "Agent id: %i" %self.id # print "Current t:", self.t # print "Current action:", action timestamp_of_action_to_execute = self.t - self.action_time_lag # print "timestamp_of_action_to_execute:", timestamp_of_action_to_execute if timestamp_of_action_to_execute < 0: # print "storing up actions...." action_to_execute = np.array([0.0, 0.0]) else: nearest_timestamp, _ = util.find_nearest( np.array(self.chosen_action_dict.keys()), timestamp_of_action_to_execute) # print "nearest_timestamp:", nearest_timestamp action_to_execute = self.chosen_action_dict[ nearest_timestamp[0]] # print "action_to_execute:", action_to_execute else: action_to_execute = action selected_speed = action_to_execute[0] * self.pref_speed selected_heading = util.wrap( action_to_execute[1] + self.heading_global_frame) # in global frame dx = selected_speed * np.cos(selected_heading) * dt dy = selected_speed * np.sin(selected_heading) * dt self.pos_global_frame += np.array([dx, dy]) self.vel_global_frame[0] = selected_speed * np.cos(selected_heading) self.vel_global_frame[1] = selected_speed * np.sin(selected_heading) self.speed_global_frame = selected_speed self.heading_global_frame = selected_heading # Compute heading w.r.t. ref_prll, ref_orthog coordinate axes self.ref_prll, self.ref_orth = self.get_ref() ref_prll_angle_global_frame = np.arctan2(self.ref_prll[1], self.ref_prll[0]) self.heading_ego_frame = util.wrap(self.heading_global_frame - ref_prll_angle_global_frame) # Compute velocity w.r.t. ref_prll, ref_orthog coordinate axes cur_speed = np.linalg.norm(self.vel_global_frame) v_prll = cur_speed * np.cos(self.heading_ego_frame) v_orthog = cur_speed * np.sin(self.heading_ego_frame) self.vel_ego_frame = np.array([v_prll, v_orthog]) # Update time left so agent does not run around forever self.time_remaining_to_reach_goal -= dt self.t += dt if self.time_remaining_to_reach_goal <= 0.0 and not Config.ROBOT_MODE: self.ran_out_of_time = True self._update_state_history() self._check_if_at_goal() return
def formatblock(block, width): """Format a block according to width.""" if width <= 0: width = 78 indent = " " * block["indent"] if block["type"] == "admonition": admonition = _admonitiontitles[block["admonitiontitle"]] hang = len(block["lines"][-1]) - len(block["lines"][-1].lstrip()) defindent = indent + hang * " " text = " ".join(map(str.strip, block["lines"])) return "%s\n%s\n" % ( indent + admonition, util.wrap(text, width=width, initindent=defindent, hangindent=defindent), ) if block["type"] == "margin": return "\n" if block["type"] == "literal": indent += " " return indent + ("\n" + indent).join(block["lines"]) + "\n" if block["type"] == "section": underline = encoding.colwidth(block["lines"][0]) * block["underline"] return "%s%s\n%s%s\n" % (indent, block["lines"][0], indent, underline) if block["type"] == "table": table = block["table"] # compute column widths widths = [max([encoding.colwidth(e) for e in c]) for c in zip(*table)] text = "" span = sum(widths) + len(widths) - 1 indent = " " * block["indent"] hang = " " * (len(indent) + span - widths[-1]) for row in table: l = [] for w, v in zip(widths, row): pad = " " * (w - encoding.colwidth(v)) l.append(v + pad) l = " ".join(l) l = util.wrap(l, width=width, initindent=indent, hangindent=hang) if not text and block["header"]: text = l + "\n" + indent + "-" * (min(width, span)) + "\n" else: text += l + "\n" return text if block["type"] == "definition": term = indent + block["lines"][0] hang = len(block["lines"][-1]) - len(block["lines"][-1].lstrip()) defindent = indent + hang * " " text = " ".join(map(str.strip, block["lines"][1:])) return "%s\n%s\n" % (term, util.wrap(text, width=width, initindent=defindent, hangindent=defindent)) subindent = indent if block["type"] == "bullet": if block["lines"][0].startswith("| "): # Remove bullet for line blocks and add no extra # indention. block["lines"][0] = block["lines"][0][2:] else: m = _bulletre.match(block["lines"][0]) subindent = indent + m.end() * " " elif block["type"] == "field": keywidth = block["keywidth"] key = block["key"] subindent = indent + _fieldwidth * " " if len(key) + 2 > _fieldwidth: # key too large, use full line width key = key.ljust(width) elif keywidth + 2 < _fieldwidth: # all keys are small, add only two spaces key = key.ljust(keywidth + 2) subindent = indent + (keywidth + 2) * " " else: # mixed sizes, use fieldwidth for this one key = key.ljust(_fieldwidth) block["lines"][0] = key + block["lines"][0] elif block["type"] == "option": return formatoption(block, width) text = " ".join(map(str.strip, block["lines"])) return util.wrap(text, width=width, initindent=indent, hangindent=subindent) + "\n"