Example #1
0
def main():

    robot = Robot()

    navigator = Navigator(robot)

    navigator.drive()
Example #2
0
    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)
Example #3
0
    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
Example #4
0
    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 __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 recover_commander(self):
        point = Point()
        point.x = random.uniform(.0, .9)
        point.y = .0
        point.z = .0

        orientation = Navigator.angle_to_quaternion(0)

        rospy.loginfo("Execution recovery behavior")
        Navigator.navigate(point, orientation)
    def navigate_commander(self):
        point = Point()
        point.x = random.random()
        point.y = .0
        point.z = .0

        orientation = Navigator.angle_to_quaternion(random.randint(0, 360))

        position_delta = Navigator.position_delta(self.last_pose.position, point)
        orientation_delta = Navigator.orientation_delta(self.last_pose.orientation, orientation)
        Navigator.navigate(position_delta, orientation_delta)
Example #8
0
 def __init__(self):
     # Navigator
     navigator = Navigator()
     handlers  = navigator.get_handlers()
     # Resources
     settings = dict(
         template_path = os.path.join(os.path.dirname(__file__), options.templates),
         static_path = os.path.join(os.path.dirname(__file__), options.static), # 指定 static path
         debug = True    # TODO: Comment this when the site is done
     )
     tornado.web.Application.__init__(self, handlers, **settings)
Example #9
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
        }
Example #10
0
File: test.py Project: lamda/RecNet
 def test_navigator(self):
     wiki = DataSet('wiki', 'data/test/wiki/', ['graph'], n_vals=[5])
     paper = DataSet('paper', 'data/test/paper/', ['graph'], n_vals=[5])
     nav = Navigator([wiki, paper])
     nav.run()
     for d in nav.data_sets:
         with io.open(d.folder + '/paths_compare.txt', encoding='utf-8')\
                 as infile:
             paths_compare = infile.read()
         with io.open(d.folder + '/paths.txt', encoding='utf-8') as infile:
             paths = infile.read()
         # compare the resulting paths
         # exclude the random paths from the comparison
         self.assertEqual(paths_compare[paths_compare.find('--------titl'):],
                          paths[paths.find('--------titl'):])
Example #11
0
    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')
        ])
Example #12
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')
        ])
Example #13
0
 def __init__(self):
     if Jaime.instance:
         raise Exception("Can't call to constructor with another instance created")
     
     self.tabs_widget = QTabWidget()
     self.view = QWebView()
     self.page = QWebPage()
     self.config = SafeConfigParser()        
     Logger.getLoggerFor(self.__class__)
     
     self.tabs_widget.insertTab(0,self.view,'label')
     self.tabs = {}        
     
     self.graph_file = None
     
     self.close_tab_timer = QTimer()
     self.close_tab_timer.setSingleShot(False)
     #cada 30 segundos se cierra un tab
     self.close_tab_timer.setInterval(10000)
     self.view.setPage(self.page)
     self.tabs['mainTab'] = self.view
     
     self.network_manager = CustomNetworkAccessManager.getInstance()        
     self.navigator = Navigator.getInstance()
     self.route_node = YahooRouteNode.getInstance()
     self.graph_parser = GraphParser.getInstance()        
     self.page.setNetworkAccessManager(self.network_manager)
Example #14
0
def basic():
    bot = Navigator.Navigator()
    bot.startSafe()
    bot.drive(0, 0)
    time.sleep(5)
    bot.destroy()
    return 'wow'
Example #15
0
class NavigatorTest(unittest.TestCase):
    
    def setUp(self):
        self._nav = Navigator()
        self._nav._search_repos = Mock(return_value=TestData.SEARCH)
        self._nav._fetch_commits = Mock(return_value=TestData.COMMITS)

    def test_normal_lookup(self):
        results = self._nav.lookup('test')
        self.assertEqual(len(results), 5)
        first = results[0]
        self.assertEqual(set(first.keys()), set([
            'repo_full_name', 
            'name', 
            'created_at',
            'latest_commit',
            'owner_avatar_url',
            'owner_url',
            'owner_login',
            ])
        )
        self.assertEqual(set(first['latest_commit'].keys()), set([
            'message', 
            'hash', 
            'author',
            ])
        )

    def test_lookup_with_no_results(self):
        self._nav._search_repos = Mock(return_value=[])
        results = self._nav.lookup('test')
        self.assertEqual(results, [])
    
    def test_lookup_with_less_than_five_results(self):
        self._nav._search_repos = Mock(return_value=TestData.SEARCH[:4])
        self._nav._fetch_commits = Mock(return_value=TestData.COMMITS[:4])
        results = self._nav.lookup('test')
        self.assertEqual(len(results), 4)

    def test_rate_limit_reached(self):
        with self.assertRaises(RateLimitException):
            res = [self._nav.lookup(i) for i in range(10)]

    def test_bypass_api_limit_for_cached_data(self):
        res = [self._nav.lookup(i) for i in [1]*10]
        self.assertEqual(len(res), 10)
Example #16
0
class Experiment:
    def __init__(self, args):
        self._args = args

    def generate_map(self):
        if self._args.model:
            self.map_points = self._load_map_points_from_model()
        else:
            self.map_points = self._generate_random_map_points()

    def _load_map_points_from_model(self):
        model = storage.load(self._args.model)[0]
        return model.normalized_observed_reductions

    def _generate_random_map_points(self):
        samples, _labels = make_classification(
            n_features=2, n_redundant=0, n_informative=1,
            n_clusters_per_class=1, n_samples=1000)
        return self._normalize(samples)

    def _normalize(self, points):
        min_value = min([min(point) for point in points])
        max_value = max([max(point) for point in points])
        return (points - min_value) / (max_value - min_value)

    def create_navigator(self):
        self.navigator = Navigator(map_points=self.map_points)

    def generate_new_path(self):
        departure = random.choice(self.map_points)
        self._generate_path(departure)

    def extend_path(self):
        departure = self.path[-1]
        self._generate_path(departure)

    def _get_slider_value(self, name):
        return float(self.window.sliders[name].value()) / SLIDER_PRECISION

    def _generate_path(self, departure):
        self.path_segments = self.navigator.generate_path(
            departure,
            num_segments=10,
            novelty=self._get_slider_value("novelty"),
            extension=self._get_slider_value("extension"),
            location_preference=self._get_slider_value("location_preference"))
        self.path = interpolation.interpolate(
            self.path_segments,
            resolution=100)
        self.path_followers = [
            PathFollower(self.path, dynamics=dynamics.constant_dynamics()),
            PathFollower(self.path, dynamics=dynamics.sine_dynamics()),
            ]

    def proceed(self, time_increment):
        for path_follower in self.path_followers:
            path_follower.proceed(time_increment * VELOCITY)
    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
Example #18
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
        }
Example #19
0
    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
Example #20
0
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 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)
Example #22
0
    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
Example #23
0
    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)
Example #24
0
    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')
Example #25
0
class Server(object):
    def __init__(self, host=HOST, port=PORT):
        self._host = host
        self._port = port
        self._app = Flask(__name__)
        self._add_routes()
        self._navigator = Navigator()

    def index(self):
        msg = ('Currently the only supported API endpoint is:\n\n'
               'GET /navigator?search_term=<search_term>\n')
        return msg, 200, {'Content-Type': 'text/plain; charset=utf-8'}

    def navigator(self):
        search_term = request.args.get('search_term')
        if not search_term:
            return self._response(
                400, {'error': 'you must provide a search_term param'})

        try:
            repos = self._navigator.lookup(search_term)
            return self._template(search_term, repos)
        except RateLimitException:
            return self._response(429, {'error': 'github api limit reached'})

    def _response(self, status, data=None):
        data = data or []
        return Response(json.dumps(data),
                        status=status,
                        mimetype='application/json')

    def _template(self, search_term, repositories):
        return render_template(
            'template.html',
            search_term=search_term,
            repositories=repositories,
        )

    def run(self):
        self._app.run(host=self._host, port=self._port)

    def _add_routes(self):
        self._app.add_url_rule('/', endpoint='index', view_func=self.index)
        self._app.add_url_rule('/navigator',
                               endpoint='navigator',
                               view_func=self.navigator)

    def _test_client(self):
        return self._app.test_client()
class NavigationServer():
    def __init__(self):
        self.nav = Navigator()
        self.start_server()

    def start_server(self):
        s = socket.socket()
        port = 12345
        s.bind(('', port))
        s.listen(1)
        self.client, addr = s.accept()
        print("Socket Up and running with a connection from", addr)
        while True:
            rcData = self.client.recv(1024).decode()
            json_data = self.decode_json(rcData)
            position = Position(**json_data["position"])
            self.nav.go_to(position, self.send_arrived_msg)

    def send_arrived_msg(self):
        self.client.send("Arrived".encode())

    def decode_json(self, data):
        json_data = json.loads(data)
        return json_data
Example #27
0
    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"
Example #28
0
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 step(self, observation, info: Dict[str, Any], detailed_commands=False):
        self.info = info
        self.reading = 'and start reading' in observation

        # retrieve the information about the inventory, description, recipe and location (different approaches for different HCPs)
        self.inventory, self.description = self._get_inventory_and_description(observation, info)
        inventory = [self.remove_articles(inv.strip()) for inv in self.inventory.strip().split('\n') if not 'carrying' in inv]
        self.recipe = self._get_recipe(observation)
        location = Navigator.extract_location(self.description)

        nav_commands = self.navigator.get_navigational_commands(self.description)

        items = None
        if self._know_recipe():
            items, utils = self.item_scorer(recipe=self.recipe,
                                            inventory=self.inventory)
            # update the needed utils
            self._update_util_locations(self.description, utils, location)
        state_description = self.build_state_description(self.description, items, location, observation, inventory)
        possible_commands = self.get_commands(self.description, items, location, inventory, nav_commands)
        score, prob, value, high_level_command, index = self.model(state_description, possible_commands)
        cmds = flist()
        cmds.append(self.command_to_action(command=high_level_command,
                                           items=items,
                                           inventory=inventory,
                                           description=self.description))

        learning_info = LearningInfo(score=score,
                                     prob=prob,
                                     value=value,
                                     action=high_level_command,
                                     index=index,
                                     possible_actions=possible_commands)

        self.reading = (high_level_command == 'examine cookbook')
        self.step_count += 1
        self.cmd_memory.append(high_level_command)

        if detailed_commands:
            hl2ll = {hl_cmd: self.command_to_action(command=hl_cmd,
                                                    items=items,
                                                    inventory=inventory,
                                                    description=self.description)
                     for hl_cmd in possible_commands}

            return cmds, learning_info, hl2ll

        return cmds, learning_info
Example #30
0
 def run(self):
     response = dict(protocol='')
     traced_back = ''
     try:
         response['protocol'] = self.request.get_parameter('protocol')
         import navigator
         reload(navigator)
         from navigator import Navigator
         view = Navigator.get_view(self.request.get_parameter('protocol'))
         return_dict = view(self.request)
         if type(return_dict) == dict:
             response.update(view(self.request))
     except Exception, exception:
         response['status'] = dict(code=str(exception.__class__.__name__), reason=unicode(exception))
         import traceback
         traced_back = traceback.format_exc()
Example #31
0
    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 setup(self):

     #################################
     # We start with a map built from a to-scale image of the floor-plan
     # of the location of the robot.  Then we localize in that 'perfect'
     # representation of the space.  (The location of the 'real world'
     # marker in the map was determined manually by placing the marker
     # on an easily identifiable feature of the image, like a pillar.)
     #################################
     # cropped map (only the downstairs lab area)
     ################################
     self.nav = Navigator(cols=26,  # approx 40cm each
  		       rows=38, # approx 40cm each
  		       widthMM=float(10383),  # map width in mm
  		       heightMM=float(15184), # map height in mm
     # lab-map-crop-scaled.png has 202x308 pixels
     # map scale information:
     #   xScale 0.0514 (m/pixel), yScale 0.0493 (m/pixel)
  		       image='map-images/lab-map-crop-scaled.png',
  		       gridResize = 2)   
     self.nav.placeMarker(row=29,col=6,name="A",angle=0, redraw=1)
     self.nav.placeMarker(row=19,col=13,name="B",angle=3.14, redraw=1)
     self.nav.setGoal(row=4,col=22)
################################
# full map (entire floor of the downstairs lab area)
################################
#     self.nav = Navigator(cols=64,  # approx 40cm each
#  		       rows=124, # approx 40cm
#  		       widthMM=float(25724),  # map width in mm 
#  		       heightMM=float(49537), # map height in mm 
## lab-map-scaled.png has 500x1004 pixels
## map scale information:
##   width 152 pixels = 782cm
##   height 227 pixels = 1120cm
#  		       image='map-images/lab-map-scaled.png',
#  		       imageResize = 0.90)   
#     self.nav.placeMarker(row=30,col=6,name="A",angle=0, redraw=1)
#     self.nav.placeMarker(row=19,col=14,name="B",angle=3.14, redraw=1)
#     self.nav.setGoal(row=4,col=22)
################################
     # then we use update the robot's location
     self.nav.updateRobotLocation(self.robot)
     try:
       self.pathList = self.nav.findPath()
     except:
       pass
Example #33
0
 def run(self):
     response = dict(protocol='')
     traced_back = ''
     try:
         response['protocol'] = self.request.get_parameter('protocol')
         import navigator
         reload(navigator)
         from navigator import Navigator
         view = Navigator.get_view(self.request.get_parameter('protocol'))
         return_dict = view(self.request)
         if type(return_dict) == dict:
             response.update(view(self.request))
     except Exception, exception:
         response['status'] = dict(code=str(exception.__class__.__name__),
                                   reason=unicode(exception))
         import traceback
         traced_back = traceback.format_exc()
Example #34
0
class RobotHA(Robot):
    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 situate(self, some_map, pose, goal):
        Robot.situate(self, some_map, pose, goal)
        self.fixed_params['goal_radius'] = self.goal.radius

    def control_policy(self):
        """return appropriate control vectors"""
        control_x = np.array([0, 0, 0])
        pos_guess, vel_guess = self.estimate_state()
        displacement = (self.goal.location - pos_guess)[0:2]
        phi_guess = pos_guess[2]

        estimated_state = {
            'phi_guess': phi_guess,
            'vel_guess': vel_guess,
            'goal_vector': displacement,
            'flee_vector': self.flee_vector(),
            'obst_distance': self.last_scan.obst_distance
        }

        robot_state = self.fixed_params.copy()
        robot_state.update(estimated_state)
        robot_state.update(self.navigator.state)

        policy = self.navigator.update(robot_state)
        if self.navigator.current_behavior.name == "Goal-reached":
            self.goal_attained = True

        control_v = self.vcontroller(policy(**robot_state))

        return control_x, control_v
Example #35
0
class RobotHA(Robot):
    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 situate(self, some_map, pose, goal):
        Robot.situate(self, some_map, pose, goal)
        self.fixed_params['goal_radius'] = self.goal.radius

    def control_policy(self):
        """return appropriate control vectors"""
        control_x = np.array([0, 0, 0])
        pos_guess, vel_guess = self.estimate_state()
        displacement = (self.goal.location - pos_guess)[0:2]
        phi_guess = pos_guess[2]

        estimated_state = {'phi_guess': phi_guess
            , 'vel_guess': vel_guess
            , 'goal_vector': displacement
            , 'flee_vector': self.flee_vector()
            , 'obst_distance': self.last_scan.obst_distance
        }

        robot_state = self.fixed_params.copy()
        robot_state.update(estimated_state)
        robot_state.update(self.navigator.state)

        policy = self.navigator.update(robot_state)
        if self.navigator.current_behavior.name == "Goal-reached":
            self.goal_attained = True

        control_v = self.vcontroller(policy(**robot_state))

        return control_x, control_v
Example #36
0
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()
Example #38
0
 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
                                })
Example #39
0
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)
Example #40
0
 def create_navigator(self, frame_id):
     return Navigator(frame_id, self)
Example #41
0
Student ID: 51123994
License: BSD

Acknowledgments:

Following PEP8.

Some notes:
"""

import rospy
from navigator import Navigator


if __name__ == "__main__":
    rospy.init_node("t2_navguy")

    # Get the starting position we want to hit
    start_pos = rospy.get_param("start_pos", [0.0, 0.0])

    t2 = Navigator(start_pos)

    rate = rospy.Rate(20.0)

    try:
        while not rospy.is_shutdown():
            t2.run()
            rate.sleep()
    except:
        pass
Example #42
0
    rospy.init_node("t3_navguy")

    # Get the starting position we want to hit
    start_pos = rospy.get_param("start_pos", [0.0, 0.0])
    # Read the rest of the targets we want to hit
    p1 = rospy.get_param("p1", [0.0, 0.0])
    p2 = rospy.get_param("p2", [0.0, 0.0])
    p3 = rospy.get_param("p3", [0.0, 0.0])
    p4 = rospy.get_param("p4", [0.0, 0.0])
    p5 = rospy.get_param("p5", [0.0, 0.0])
    p6 = rospy.get_param("p6", [0.0, 0.0])

    target_list = list()
    target_list.append(p1)
    target_list.append(p2)
    target_list.append(p3)
    target_list.append(p4)
    target_list.append(p5)
    target_list.append(p6)

    t3 = Navigator(start_pos, target_list)

    rate = rospy.Rate(20.0)

    try:
        while not rospy.is_shutdown():
            t3.run()
            rate.sleep()
    except:
        pass
Example #43
0
"""
    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()
Example #44
0
 def create_navigator(self):
     self.navigator = Navigator(map_points=self.map_points)
class BrainTestNavigator(Brain):

  def setup(self):

     #################################
     # We start with a map built from a to-scale image of the floor-plan
     # of the location of the robot.  Then we localize in that 'perfect'
     # representation of the space.  (The location of the 'real world'
     # marker in the map was determined manually by placing the marker
     # on an easily identifiable feature of the image, like a pillar.)
     #################################
     # cropped map (only the downstairs lab area)
     ################################
     self.nav = Navigator(cols=26,  # approx 40cm each
  		       rows=38, # approx 40cm each
  		       widthMM=float(10383),  # map width in mm
  		       heightMM=float(15184), # map height in mm
     # lab-map-crop-scaled.png has 202x308 pixels
     # map scale information:
     #   xScale 0.0514 (m/pixel), yScale 0.0493 (m/pixel)
  		       image='map-images/lab-map-crop-scaled.png',
  		       gridResize = 2)   
     self.nav.placeMarker(row=29,col=6,name="A",angle=0, redraw=1)
     self.nav.placeMarker(row=19,col=13,name="B",angle=3.14, redraw=1)
     self.nav.setGoal(row=4,col=22)
################################
# full map (entire floor of the downstairs lab area)
################################
#     self.nav = Navigator(cols=64,  # approx 40cm each
#  		       rows=124, # approx 40cm
#  		       widthMM=float(25724),  # map width in mm 
#  		       heightMM=float(49537), # map height in mm 
## lab-map-scaled.png has 500x1004 pixels
## map scale information:
##   width 152 pixels = 782cm
##   height 227 pixels = 1120cm
#  		       image='map-images/lab-map-scaled.png',
#  		       imageResize = 0.90)   
#     self.nav.placeMarker(row=30,col=6,name="A",angle=0, redraw=1)
#     self.nav.placeMarker(row=19,col=14,name="B",angle=3.14, redraw=1)
#     self.nav.setGoal(row=4,col=22)
################################
     # then we use update the robot's location
     self.nav.updateRobotLocation(self.robot)
     try:
       self.pathList = self.nav.findPath()
     except:
       pass

  def step(self):

    # then we use update the robot's location
    self.nav.updateRobotLocation(self.robot)

    # if we have already arrived at the next subgoal we remove it and
    # move on to the next.
    if (self.pathList[0] == (self.nav.getCurrentRow(),self.nav.getCurrentCol())):
      print "I reached old subgoal",self.pathList[0]
      del self.pathList[0]

    print "current Location",self.nav.getCurrentRow(),self.nav.getCurrentCol()
    print "next subgoal",self.pathList[0]

    translation, rotate = self.nav.determineMove(self.pathList[0])
    self.robot.move(translation,rotate)
Example #46
0
		canvas.drawLine((points[i][0], points[i][1], points[(i + 1)%n][0], points[(i + 1)%n][1]));

#
# initialize device
#
leftMotorPort=LEFT_MOTOR
rightMotorPort=RIGHT_MOTOR

robot = Robot(leftMotorPort,
		rightMotorPort,
		leftTouchPort=LEFT_TOUCH,
		rightTouchPort=RIGHT_TOUCH,
		sonarPort=SONAR_SENSOR)

encoder = Encoder()
navigator = Navigator()

#
# intialize environment
#
canvas = Canvas();
mymap = Map(canvas);
# Definitions of walls
# a: O to A
# b: A to B
# c: C to D
# d: D to E
# e: E to F
# f: F to G
# g: G to H
# h: H to O