def __init__(self, tracker, my_id, target_id, time_step, max_pivot_input=50, forward_speed=70, pivot_threshold=30, proportional_gain=5, integrator_gain=0, reversed=False, comm_port=None): # system work horses self.controller = Controller(time_step, max_pivot_input, forward_speed, pivot_threshold, proportional_gain, integrator_gain, reversed, comm_port) self.navigator = Navigator() self.tracker = tracker self.id = my_id self.target_id = target_id # state parameters self.current_heading = 0 self.pos = [0, 0] self.target_pos = [0, 0] self.desired_heading = 0
def test_should_navigate_to_next_waypoint_with_kink_in_route(self): destination = Waypoint(Position(10.03, 10.03), 10) gps = FakeMovingGPS([ Position(10, 10), Position(10.01, 10.01), Position(10.025, 10.015), Position(10.03, 10.03) ]) sensors = FakeSensors(gps, 1, 45) steerer = Steerer(self.servo, self.logger, CONFIG['steerer']) helm = Helm(self.exchange, sensors, steerer, self.logger, CONFIG['helm']) navigator = Navigator(sensors, Globe(), self.exchange, self.logger, CONFIG['navigator']) self.exchange.publish(Event(EventName.navigate, waypoint=destination)) self.ticks(number=14, duration=200) self.logger.info.assert_has_calls([ call( 'Navigator, steering to +10.030000,+10.030000, bearing 44.6, distance 4681.8m, review after 600s' ), call( 'Navigator, steering to +10.030000,+10.030000, bearing 44.6, distance 3121.2m, review after 600s' ), call( 'Navigator, steering to +10.030000,+10.030000, bearing 71.3, distance 1734.0m, review after 600s' ), call('Navigator, arrived at +10.030000,+10.030000') ])
def _setup_view(self) -> None: """ Set up components of the GUI """ self._navigator = Navigator(self._master, self.handle_move_callback, self.handle_jump_callback, bg=self._bg) self._navigator.pack(side=tk.TOP) frame = tk.Frame(self._master, bg=self._bg) frame.pack(side=tk.TOP) self._classifier = Classifier(frame, self.handle_select_callback, bg=self._bg) self._classifier.pack(side=tk.LEFT) self._preview = Preview(frame, PREVIEW_WIDTH, PREVIEW_HEIGHT, callback=self._handle_preview_click) self._preview.pack(side=tk.LEFT) self._master.config(bg=self._bg) self._master.title("poprev") self._master.protocol("WM_DELETE_WINDOW", self._exit)
def test_change_image(self): tool = AnnotationTool() tool.load_app(True) tool.file_list = [] tool.annotations = [] tool.current_file = 0 tool.class_list = ['winston', 'prince', 'duckie'] tool.colorspace = ['#0000FF', '#FF0000', '#00FF00'] tool.num_pages = 1 tool.class_count = [5, 5, 5] for i in range(5): a = Annotation() a.rotation = 3 tool.file_list.append('file%d.jpg' % i) for p in range(3): roi = ROI() roi.push(0,0) roi.push(100.0,100.0) a.push(roi, p%len(tool.class_list)) tool.annotations.append(a) tool.img = MockImg() tool._draw_workspace() navigator = Navigator(tool) self.assertEqual(tool.current_file, 0) navigator.change_image(1) self.assertEqual(tool.current_file, 1)
def main(): robot = Robot() navigator = Navigator(robot) navigator.drive()
def process_thread(thread_id, opts, reddit_scraper): thread = reddit_scraper.submission(id=thread_id) if thread.num_comments > opts.max_comments: print 'too many comments: %d' % thread.num_comments print 'skipping thread id %s' % thread_id return 2 print thread_id#keep until certain bug issue is gone start = datetime.datetime.now() print '+------------------------------------------------------+' print 'PROCESSING %s, id=%s, in /r/%s' % (thread.title, thread.id, thread.subreddit.display_name) print 'created %s' % datetime.datetime.fromtimestamp(thread.created).strftime('%x %X') print 'author: %s' % str(thread.author) print 'score: %d, num_comments: %d' % (thread.score, thread.num_comments) print '' nav = Navigator(thread, opts) if opts.skip_comments: nav.store_thread_data() else: nav.navigate() end = datetime.datetime.now() print 'FINISHED thread w/id=%s, navigated %d comments, %d deleted'\ % (thread.id, nav.traversed_comments, nav.deleted_comments) print 'thread scraping time: %d seconds' % (end-start).seconds print '+------------------------------------------------------+'
def test_should_steer_repeatedly_during_navigation(self): logger = Mock() destination = Waypoint(Position(10.0003, 10.0003), 10) gps = FakeMovingGPS([ Position(10, 10), Position(10.0001, 10.00015), Position(10.00025, 10.0002), Position(10.0003, 10.0003) ]) sensors = FakeSensors(gps, 1, 45) steerer = Steerer(self.servo, logger, CONFIG['steerer']) helm = Helm(self.exchange, sensors, steerer, logger, CONFIG['helm']) navigator = Navigator(sensors, Globe(), self.exchange, logger, CONFIG['navigator']) self.exchange.publish(Event(EventName.navigate, waypoint=destination)) self.ticks(number=7, duration=20) logger.debug.assert_has_calls([ call( 'Navigator, distance from waypoint +46.819018, combined tolerance +10.000000' ), call( 'Navigator, distance from waypoint +27.647432, combined tolerance +10.000000' ), call( 'Steerer, steering 36.4, heading 45.0, rate of turn +1.0, rudder +0.0, new rudder +4.6' ), call( 'Steerer, steering 36.4, heading 45.0, rate of turn +1.0, rudder +4.6, new rudder +9.2' ), call( 'Navigator, distance from waypoint +12.281099, combined tolerance +10.000000' ), call( 'Steerer, steering 63.1, heading 45.0, rate of turn +1.0, rudder +9.2, new rudder +0.4' ), call( 'Navigator, distance from waypoint +0.000000, combined tolerance +10.000000' ), call( 'Steerer, steering 63.1, heading 45.0, rate of turn +1.0, rudder +0.4, new rudder -8.3' ), call( 'Steerer, steering 63.1, heading 45.0, rate of turn +1.0, rudder -8.3, new rudder -17.1' ) ]) logger.info.assert_has_calls([ call( 'Navigator, steering to +10.000300,+10.000300, bearing 44.6, distance 46.8m, review after 23s' ), call( 'Navigator, steering to +10.000300,+10.000300, bearing 36.4, distance 27.6m, review after 13s' ), call( 'Navigator, steering to +10.000300,+10.000300, bearing 63.1, distance 12.3m, review after 6s' ), call('Navigator, arrived at +10.000300,+10.000300') ])
def basic(): bot = Navigator.Navigator() bot.startSafe() bot.drive(0, 0) time.sleep(5) bot.destroy() return 'wow'
def __init__(self, maze_dim): self.maze_dim = maze_dim self.navigator = Navigator(maze_dim) self.update_walls_initial_conditions() self.define_goal() self.generate_maze()
def __init__(self, maze_dim): ''' Use the initialization function to set up attributes that your robot will use to learn and navigate the maze. Some initial attributes are provided based on common information, including the size of the maze the robot is placed in. ''' self.navigator = Navigator(maze_dim) self.racing = False self.race_time_step = 0
def __init__(self, this_parameters, sonar): Robot.__init__(self, this_parameters, sonar) self.navigator = Navigator() self.guard_fatness = 5 self.fixed_params = { 'omega_max': self.parameters.omega_max, 'vel_max': self.parameters.vel_max, 'slowdown_radius': self.parameters.displacement_slowdown, 'guard_fatness': self.guard_fatness, 'flee_threshold': self.parameters.avoid_threshold }
def _draw_workspace(self): ''' This draws the main project in the background frame Parameters ---------- None Attributes ---------- background : tkinter Frame object This is the frame that covers the entire window object Raises ------ None Returns ------- complete : bool Returns True for unittesting ''' self.app_menu._draw_menu() self.background.destroy() # Build Background Frame self.background = Frame(self.window, bg="gray", width=self.window_width, height=self.window_height) self.background.place(x=0, y=0, width = self.window_width, height = self.window_height) if self.annotations: self.num_pages = int(len(self.annotations)/self.img_per_page) # Draw Toolbar on Left toolbar = Toolbar(self) # Draw Canvas on Right self.draw_canvas() if len(self.annotations): self.navigator = Navigator(self) return True
def __init__(self, gps=False, servo_port=SERVO_PORT): # devices self._gps = gps self.windsensor = WindSensor(I2C(WINDSENSOR_I2C_ADDRESS)) self.compass = Compass(I2C(COMPASS_I2C_ADDRESS), I2C(ACCELEROMETER_I2C_ADDRESS)) self.red_led = GpioWriter(17, os) self.green_led = GpioWriter(18, os) # Navigation self.globe = Globe() self.timer = Timer() self.application_logger = self._rotating_logger(APPLICATION_NAME) self.position_logger = self._rotating_logger("position") self.exchange = Exchange(self.application_logger) self.timeshift = TimeShift(self.exchange, self.timer.time) self.event_source = EventSource(self.exchange, self.timer, self.application_logger, CONFIG['event source']) self.sensors = Sensors(self.gps, self.windsensor, self.compass, self.timer.time, self.exchange, self.position_logger, CONFIG['sensors']) self.gps_console_writer = GpsConsoleWriter(self.gps) self.rudder_servo = Servo(serial.Serial(servo_port), RUDDER_SERVO_CHANNEL, RUDDER_MIN_PULSE, RUDDER_MIN_ANGLE, RUDDER_MAX_PULSE, RUDDER_MAX_ANGLE) self.steerer = Steerer(self.rudder_servo, self.application_logger, CONFIG['steerer']) self.helm = Helm(self.exchange, self.sensors, self.steerer, self.application_logger, CONFIG['helm']) self.course_steerer = CourseSteerer(self.sensors, self.helm, self.timer, CONFIG['course steerer']) self.navigator = Navigator(self.sensors, self.globe, self.exchange, self.application_logger, CONFIG['navigator']) self.self_test = SelfTest(self.red_led, self.green_led, self.timer, self.rudder_servo, RUDDER_MIN_ANGLE, RUDDER_MAX_ANGLE) # Tracking self.tracking_logger = self._rotating_logger("track") self.tracking_sensors = Sensors(self.gps, self.windsensor, self.compass, self.timer.time, self.exchange, self.tracking_logger, CONFIG['sensors']) self.tracker = Tracker(self.tracking_logger, self.tracking_sensors, self.timer)
def __init__(self): self.globe = Globe() self.console_logger = self._console_logger() self.exchange = Exchange(self.console_logger) self.gps = SimulatedGPS(CHORLTON.position,0,0.1) self.vehicle = SimulatedVehicle(self.gps, self.globe,self.console_logger,single_step=False) self.timeshift = TimeShift(self.exchange,self.vehicle.timer.time) self.event_source = EventSource(self.exchange,self.vehicle.timer,self.console_logger,CONFIG['event source']) self.sensors = Sensors(self.vehicle.gps, self.vehicle.windsensor,self.vehicle.compass,self.vehicle.timer.time,self.exchange,self.console_logger,CONFIG['sensors']) self.steerer = Steerer(self.vehicle.rudder,self.console_logger,CONFIG['steerer']) self.helm = Helm(self.exchange, self.sensors, self.steerer, self.console_logger, CONFIG['helm']) self.course_steerer = CourseSteerer(self.sensors,self.helm,self.vehicle.timer, CONFIG['course steerer']) self.navigator_simulator = Navigator(self.sensors,self.globe,self.exchange,self.console_logger,CONFIG['navigator']) self.tracking_timer = Timer() self.tracker_simulator = Tracker(self.console_logger,self.sensors,self.tracking_timer)
def main(): navigator = Navigator() while (True): os.system("clear") navigator.show_map() cmd = Keyboard.read() if cmd == Keyboard.CLOSE: # print "Do you want to save the map? Press 's' to save." # if Keyboard.read() == Keyboard.SAVE: # print "Saving the map..." # navigator.save_map() # else: # print "Close without saving the map." exit(1) navigator.move(cmd)
class MyClass(object): nav = Navigator() def __init__(self): self.nav._add_actor(Actor("Class Method", self.print_y)) self.nav._add_actor(Actor("Instance Method", self.print_x)) def print_x(self): ui.text_success("I belong to instance of {}".format( self.__class__.__name__)) @classmethod def print_y(cls): ui.text_success("I staticly belong to {}".format(cls.__name__)) @staticmethod @nav.route("Static Method") def print_0(): ui.text_success("I'm entirely static (and ecstatic :) )")
def d_connect(self): """Initializes drone, navigator, and camera objects, draws the map and its components, and makes available route-selection buttons""" self.drone = Drone() self.drone.startup() self.drone.reset() self.navigator = Navigator(self.drone) self.camera = Camera( self.drone, self.cam_width, self.cam_height, self.camera_event) self.camera.start() self.senActivate() self.render_map() self.act_drone_loc() for radio in self.radios: radio.config(bg= self.control_color_back,state=tk.NORMAL) self.route_selctn()
def setUp(self): self.mock_logger = Mock() self.mock_logger.error = Mock(side_effect=print_msg) self.exchange = Exchange(self.mock_logger) self.timer = StubTimer() self.timeshift = TimeShift(self.exchange, self.timer.time) self.event_source = EventSource(self.exchange, self.timer, self.mock_logger, {'tick interval': 0.2}) gps = FakeMovingGPS([ Position(10, 10), Position(11, 11), Position(12, 12), Position(13, 13) ]) self.navigator = Navigator(gps, Globe(), self.exchange, self.mock_logger, { 'min time to steer': 5, 'max time to steer': 20 })
def __init__(self, device, model, item_scorer, navigation_model, hcp=4): self.device = device self.cmd_memory = flist() self.item_scorer = item_scorer self.navigator = Navigator(navigation_model) self.utils = None self.hcp = hcp self.step_count = 0 self.total_score = 0 self.current_score = 0 self.recipe = '' self.reading = False self.model = model self.description = 'nothing' self.description_updated = True self.inventory = 'nothing' self.inventory_updated = False self.info = None
def runPipeline(config): """Sets internal arguments from the config file and runs pipeline stages accordingly. Args: config: options from the json config file, else default values. """ if config['aggregate']: aggregator.aggregate(config) if config['generate']: generator.generate(config) if config['evaluate']: if not path.exists(config['sensitive_aggregates_path']): logging.info(f'Missing sensitive aggregates; aggregating...') aggregator.aggregate(config) if not path.exists(config['synthetic_microdata_path']): logging.info(f'Missing synthetic microdata; generating...') generator.generate(config) evaluator.evaluate(config) if config['navigate']: if not path.exists(config['sensitive_aggregates_path']): logging.info(f'Missing sensitive aggregates; aggregating...') aggregator.aggregate(config) if not path.exists(config['synthetic_microdata_path']): logging.info(f'Missing synthetic microdata; generating...') generator.generate(config) navigator = Navigator(config) navigator.process() json.dump(config, open( path.join(config['output_dir'], config['prefix'] + '_config.json'), 'w'), indent=1)
def test_init(self): tool = AnnotationTool() tool.load_app(True) tool.file_list = [] tool.annotations = [] tool.class_list = ['winston', 'prince', 'duckie'] tool._draw_workspace() navigator = Navigator(tool) self.assertEqual(tool, navigator.root_app) background = tool.window.winfo_children()[2] navigator = background.winfo_children()[2] self.assertEqual(len(navigator.winfo_children()), 2) canvas = navigator.winfo_children()[0] scrollbar = navigator.winfo_children()[1] self.assertEqual(canvas.cget('width'), '200') self.assertEqual(canvas.cget('height'), '718') self.assertEqual(scrollbar.winfo_name(), '!scrollbar')
def start(self): print("START") try: if DEBUG: self.__dump( json.dumps({'start': cherrypy.request.json}, indent=4), f"{datetime.now().strftime('%H:%M:%S.%f')}_start.json") data = datatype.GameRequest(**cherrypy.request.json) max_distance = data.board.width + data.board.height distance_food_weights = { i: int((0.8**i) * 100) for i in range(1, max_distance) } self.navigator = Navigator(distance_food_weights, mode=NAVIGATOR_MODE, is_debug=DEBUG) self.stats = [] except Exception as e: print(f'Exception: {str(e)}') return "ok"
def main(): env = GridEnv() try: while True: env.reset() goal = env.find_goals()[0] path = a_star(env, env.get_agent_pos(), goal) nav = Navigator(env, path) print("Executing plan...") while (nav.has_next()): nav.do_next_step() env.render() time.sleep(0.1) print("Plan completed") pos = env.get_agent_pos() if pos[0] == goal[0] and pos[1] == goal[1]: print("Goal reached") else: print("Goal not reached") print() except KeyboardInterrupt: print("program exited...") print("done")
def create_navigator(self, frame_id): return Navigator(frame_id, self)
#!/usr/bin/env python import roslib import rospy import sys from navigator import Navigator from position import Position try: rospy.init_node('sdp_navigator') nav = Navigator() # Pass arguments:Point[0],Point[1],Quaternion[2] myarg = rospy.myargv(argv=sys.argv) command = myarg[1] x = float(myarg[2]) y = float(myarg[3]) angle = float(myarg[4]) position = Position(x, y, angle) if myarg[1] == 'pose': nav.set_initial_position(position) elif myarg[1] == 'goal': nav.go_to(position) rospy.loginfo("done") except Exception as e: print("error: ", e)
for key, pageinfo in spine.items(): if key.strip().lower() in ['itemref', 'opf:itemref']: if isinstance(pageinfo, OrderedDict): idref = pageinfo.get('@idref') yield idref, self.manifest.get(idref) if isinstance(pageinfo, list): for pageref in pageinfo: idref = pageref.get('@idref') yield idref, self.manifest.get(idref) def pages(self): for page_id, pageinfo in self.load_spine(): page = os.path.join(self.root, pageinfo.get('@href')) yield page_id, self.read_from_epub(page) if __name__ == '__main__': try: path = "/home/sofycomps/work/" epubs = os.path.join(path, 'input', '*.epub') epubs_dir = glob.glob(epubs) for epubfile in epubs_dir: with Books150(epubfile) as eReader: opfpath = eReader.locate_opf() eReader.load_opf(opfpath) pages = eReader.pages() nav = Navigator(pages) pdb.set_trace() except Exception as e: print(traceback.format_exc())
def __init__(self): self.nav = Navigator() self.start_server()
""" An example of using default values in prompt """ from navigator import Navigator, ui nav = Navigator(intro="Defaults example", done_name="Quit", default_choice=1) @nav.route("Default action", "if you press enter without entering a choice this will be called") def default_choice(): ui.text_success("I'm the default") @nav.route("Question with default", "Will prompt wil a default valid input") def question_with_default(): ui.prompt("Are you sure?", default="Yes") @nav.route("Question without default", "Will prompt without a default value, and insist on a valid input") def question_without_default(): ui.prompt("Are you sure?") if __name__ == "__main__": nav.run()
def _receive_statistics(msPerLoop, msPerPacket, numPackets): print('Received statistics {} ms per loop, {} ms per packet, {} packets'.format(msPerLoop, msPerPacket, int(numPackets))) if __name__ == '__main__': arduino_interface = ArduinoInterface('/dev/ttyACM0', 115200, timeout=1.0) camera = Camera() driver = Driver(arduino_interface) #ipaths = int(input("Enter start: ").strip()) #ipathm = int(input("Enter middle: ").strip()) #ipathe = int(input("Enter end: ").strip()) ipaths, ipathm, ipathe = 10, 5, 3 if ipaths == 7 or ipaths == 11: cur_speed = 15 navigator = Navigator((int(ipaths), int(ipathm), int(ipathe))) #navigator = Navigator((1, 5, 10)) # TODO: PROVIDE MAP # navigator.plan_route(...) camera.start() time.sleep(2) driver.set_speed_limit(10.0) # TODO: DIFFERENTIATE BETWEEN SPEED LIMIT AND DESIRED SPEED pixel_data = np.empty(shape=(IMAGE_HEIGHT, IMAGE_WIDTH, 3), dtype='uint8') #arduino_interface.turn_statistics_on(10, _receive_statistics) try: while True: # Process the serial port. arduino_interface.process_buffer()
# noinspection PyUnreachableCode if False: # noinspection PyUnresolvedReferences from _stubs import * from navigator import Navigator ext.navigator = Navigator(COMP()) def onKeyboardShortcut(info: dict): pass def onPickItem(info: dict): ext.navigator.onOpPickerPickItem(info.get('item')) def onRolloverItem(info: dict): pass