def preproc(self, world, game):
     print 'world %d x %d' % (world.width, world.height)
     pprint(map(list, zip(*world.tiles_x_y)))
     print world.waypoints
     print '====================='
     self.navigator = Navigator(world)
     self.physics = Physics(world, game)
示例#2
0
def main():
	
	# read settings from settings file
	fs.read_settings_file()

	# run app at homepage
	App = QApplication(sys.argv)
	navigator = Navigator()
	navigator.show_homepage()
	sys.exit(App.exec())
示例#3
0
 def __init__(self, height):
     self.pidInput = rospy.Publisher('pid_input',
                                     controller_msg,
                                     queue_size=10)
     self.height = height
     rospy.Subscriber('/pid/controller_command', controller_msg,
                      self.HandlePID)
     rospy.Subscriber('/mavros/global_position/rel_alt', Float64,
                      self.HandleAltitude)
     self.myNavigator = Navigator()
示例#4
0
def simplest():
    def print_simplest(list):
        for elem in list:
            print(f"Index[{elem.index}] full path : {elem.full_path}")
    
    viz = Simplest()
    nav = Navigator()
    while viz.update(nav.read_next()):
        pass
    list = viz.visualize()
    print_simplest(list)
示例#5
0
def main(stdscr):
    logging.basicConfig(
        level=logging.DEBUG,
        filename='app.log',
        filemode='w',
        format='%(name)s - %(levelname)s - [%(filename)s:%(lineno)s - %(funcName)20s() ] - %(message)s')
    print('Initializing...')
    display = Display()
    navigator = Navigator(display)
    choice_handler = ChoiceHandler(navigator)
    json_handler = JsonHandler(navigator)
    data_handler = EcsManager(choice_handler, json_handler)
    while True:
        data_handler.update()
    def __init__(self):
        self.vision = Vision(RobotController.model_xml,
                             RobotController.model_bin,
                             self,
                             is_headless=True,
                             live_stream=True,
                             confidence_interval=0.5)

        self.received_frame = None
        self.qr_reader = QRReader()
        self.last_qr_approached = None
        self.current_qr_approached = None
        self.approach_complete = True
        self.retrying_approach = False
        self.standby_mode = True
        self.standby_invoked = True
        self.serial_io = SerialIO('/dev/ttyACM0', 115200, self)
        self.actions = {}
        self.watered = False

        if config.RESPOND_TO_API:
            host = config.API_HOST
            if config.API_SECURE:
                host = "wss://" + host
            else:
                host = "ws://" + host

            self.remote = Remote(config.UUID, host)
            self.remote.add_callback(RPCType.MOVE_IN_DIRECTION,
                                     self.remote_move)
            self.remote.add_callback(RPCType.EVENTS, self.on_events_received)
            self.remote.add_callback(RPCType.SET_STANDBY, self.set_standby)

            rm_thread = threading.Thread(target=self.thread_remote,
                                         name="remote",
                                         daemon=True)
            rm_thread.start()
            # rm_thread.join()

        # Create the navigation system
        self.navigator = Navigator(self, verbose=True)

        threading.Thread(target=self.vision.start, name="vision").start()
示例#7
0
    def __init_properties(self, document):
        self.__dict__['__cx'].add_global('window', self)
        self.__dict__['__cx'].add_global('self'  , self)
        self.__dict__['__cx'].execute("window.window = window;")

        self.__dict__['__cx'].add_global('document', document)
        self.__dict__['__cx'].execute("window.document = document;")
        
        self.__dict__['__cx'].add_global('location', document.location)
        self.__dict__['__cx'].execute("window.location = location;")

        self.__dict__['__cx'].add_global("ActiveXObject", ActiveXObject)

        self.__dict__['__cx'].add_global("navigator", Navigator())
        self.__dict__['__cx'].execute("window.navigator = navigator;")
        
        self.__dict__['__cx'].add_global("screen", unknown())
        self.__dict__['__cx'].execute("window.screen = screen;")

        if 'top_window' in self.__dict__['__root'].__dict__:
            if self.__dict__['__referrer']:
                top = self.__dict__['__referrer']
            else:
                top = self.__dict__['__root'].top_window
        else:
            top = self

        self.__dict__['__cx'].add_global("top", top)
        self.__dict__['__cx'].execute("window.top = top;")

        self.__dict__['__cx'].add_global("parent", top)
        self.__dict__['__cx'].execute("window.parent = parent;")

        self.__dict__['__cx'].add_global("history", History(document))
        self.__dict__['__cx'].execute("window.history = history;")

        self.__dict__['__cx'].execute("window.innerWidth = 400;")
        self.__dict__['__cx'].execute("window.innerHeight = 200;")
        self.__dict__['__cx'].execute("window.name = '';")
        
        self.__init_undefined_properties()
示例#8
0
def graphwise():
    #setup
    viz = Graphwise()
    nav = Navigator()
    grayscale = True
    DNA_ish = not True
    wid, hi = 400,400
    gif_path = f'result/{"DNA" if DNA_ish else "graphwise"}_{"gray" if grayscale else "rgb"}.gif'
    gif_duration = 4 #seconds
    images = []
    cv_cvt_format = cv.COLOR_GRAY2RGB if grayscale else cv.COLOR_BGR2RGB
    def cv_img_to_PIL_img(cv_img):
        return Image.fromarray(cv.cvtColor(cv_img, cv_cvt_format))

    #main logic
    while viz.update(nav.read_next()):
        cv_img = viz.visualize(wid, hi, grayscale=grayscale, DNA_ish=DNA_ish)
        images.append(cv_img_to_PIL_img(cv_img))
        pass

    #view results
    stat = viz.stat()

    print(f"[Statistics]")
    print(f"\tFile count [{stat[0]}]")
    print(f"\tDirectory count(including root) [{stat[1]}]")
    print(f"\tMaximum file size : [{stat[2]}bytes]")
    print(f"\tTotal file size : [{stat[3]}bytes]")

    if images:
        print("Creating gif...")
        images[0].save(gif_path, save_all=True, append_images=images[1:], optimize=True, duration=int((gif_duration*1000)/len(images)), loop=0)
        print("GIF saving done")
    

    cv.imshow("Result", viz.visualize(wid, hi, grayscale=grayscale, DNA_ish=DNA_ish))
    cv.waitKey(0)
示例#9
0
map['x'] = map_x
map['y'] = map_y

nav_bot_name = str(input("Nav bot name: "))
nav_bot_x = int(input("Nav bot x coordinate: "))
nav_bot_y = int(input("Nav bot y coordinate: "))
nav_bot_dir = str(input("Nav bot direction: "))
nav_bot_inst = str(input("Nav bot movement: "))

fight_bot_name = str(input("Fight bot name: "))
fight_bot_x = int(input("Fight bot x coordinate: "))
fight_bot_y = int(input("Fight bot y coordinate: "))
fight_bot_dir = str(input("Fight bot direction: "))
fight_bot_inst = str(input("Fight bot movement: "))

nav_bot = Navigator(nav_bot_name, nav_bot_x, nav_bot_y, Direction[nav_bot_dir])
for m in [char for char in nav_bot_inst]:
    nav_bot.navigate()
    set_movement(m, nav_bot, map)
nav_bot.reply("I am robot")

fight_bot = Fighter(fight_bot_name, fight_bot_x, fight_bot_y, Direction[fight_bot_dir])
for m in [char for char in fight_bot_inst]:
    fight_bot.fight()
    set_movement(m, fight_bot, map)
fight_bot.reply()

tokota_bot = Tokota("XT009", 0, 0, Direction.N)

print(nav_bot.get_x())
print(nav_bot.get_y())
示例#10
0
from behave import given, when, then
from Navigator import Navigator

nav = Navigator()


@given('I have Python {version} installed')
def impl(context, version):
    version = version.split(".")  # Create a list from the string
    context.version = version  # Save the list


@when('I try to check my version')
def impl(context):
    context.actual = str(
        nav.checkVersion(*context.version))  # Unpack the list arguments


@then('I should see "{expected}" in my message')
def impl(context, expected):
    try:
        if (expected == "Nothing"):
            assert "" in context.actual  # We aren't expecting anything
        else:
            assert expected in context.actual

    except AssertionError as e:
        e.args += ('Expected: ' + expected + ' Actual: ' + context.actual)
        raise e.args
示例#11
0
def main():
    clearConsole()

    nav = Navigator()
    courses = []

    major, minor, micro = sys.version_info[:3]
    message = checkVersion(major, minor, micro)

    if message != "":
        print message

    if "Error" in message:
        sys.exit(1)

    username = getpass('PID: ')
    password = getpass()

    print "Logging In.. "
    sys.stdout.flush()

    while (nav.login(username, password) is False):
        print "Please Try Again"

        username = raw_input('PID: ')
        password = getpass()

    clearConsole()

    automate = raw_input("Automate?: ")

    if automate:
        errors = ""
        CRN = "92074"
        TERM = "09"
        YEAR = "2013"
        SUBJ = "CS"
        CRSE = "2114"
    else:
        errors = 1

    print "Logged In"

    print "Please Enter The Following Information:"

    error_checker = ErrorCheck()

    while (errors):

        CRN = raw_input('CRN: ') or ""  # or "92083"
        TERM = raw_input('TERM (F, S, S1, or S2) (F - Default): '
                         ) or "09"  # Default TERM if nothing is given
        YEAR = raw_input('YEAR (2013 - Default): '
                         ) or "2013"  # Default YEAR if nothing is given
        SUBJ = raw_input('SUBJ: ') or ""
        CRSE = raw_input('CRSE: ') or ""

        print "\nChecking for Errors in Course Information..\n"

        errors = error_checker.obviousChecks(crn=CRN, subj=SUBJ, crse=CRSE)

        if (errors):
            print "Sorry, There Were Some Errors: \n"
            print "Error(s): "
            for error in errors:
                print error
            print "Please Try Again"

    clearConsole()
    print "Everything Looks Good.."
    print "Searching for Class Information.."

    if ((SUBJ and CRSE) or CRN):
        course_info = nav.find(subj=SUBJ,
                               crse=CRSE,
                               term=TERM,
                               year=YEAR,
                               crn=CRN)
    else:
        print "Sorry.. You Didn't Enter Enough Information"
        sys.exit(0)

    if course_info is None:
        print "Sorry.. No Sections were Found"
        answer = raw_input("Try Again..? ")
        sys.exit(0)
    else:
        course_info = Cleaner(course_info)

    print "Here's What I Found.."

    print course_info

    answer = YesNo(
        raw_input("Do You Wish to Add a Course? Enter (y)es or (n)o: "))

    if answer == "Yes":
        CRN = raw_input("Please Enter the CRN: ")
        courses.append(CRN)
    else:
        sys.exit(0)
示例#12
0
class SimpleViewer(avango.script.Script):

    SceneGraph = avango.gua.SFSceneGraph()
    Navigator = Navigator()
    Viewer = avango.gua.nodes.Viewer()
    Shell = GuaVE()

    def __init__(self):
        self.super(SimpleViewer).__init__()
        self.window_size = avango.gua.Vec2ui(1920, 1080)

        # create resolve pass
        self.res_pass = avango.gua.nodes.ResolvePassDescription()
        self.res_pass.EnableSSAO.value = True
        self.res_pass.SSAOIntensity.value = 4.0
        self.res_pass.SSAOFalloff.value = 10.0
        self.res_pass.SSAORadius.value = 7.0
        self.res_pass.EnvironmentLightingColor.value = avango.gua.Color(
            0.1, 0.1, 0.1)
        self.res_pass.ToneMappingMode.value = avango.gua.ToneMappingMode.UNCHARTED
        self.res_pass.Exposure.value = 1.0
        self.res_pass.BackgroundColor.value = avango.gua.Color(0.0, 0.0, 0.0)
        self.res_pass.BackgroundMode.value = avango.gua.BackgroundMode.COLOR

        # create anti-aliasing pass
        self.anti_aliasing = avango.gua.nodes.SSAAPassDescription()

        # create pipeline description
        self.pipeline_description = avango.gua.nodes.PipelineDescription(
            Passes=[
                avango.gua.nodes.TriMeshPassDescription(),
                avango.gua.nodes.LightVisibilityPassDescription(),
                self.res_pass, self.anti_aliasing
            ])

        # create window
        self.window = avango.gua.nodes.GlfwWindow(
            Size=self.window_size, LeftResolution=self.window_size)
        avango.gua.register_window("window", self.window)

    def run(self, locals, globals, show_guave_banner=True):
        self.Shell.start(locals, globals, show_guave_banner)
        self.Viewer.run()

    def list_variabels(self):
        self.Shell.list_variables()

    def start_navigation(self):
        self.navigation.Transform.connect_from(self.Navigator.OutTransform)

    def set_background_image(self, path):
        self.res_pass.BackgroundMode.value = avango.gua.BackgroundMode.SKYMAP_TEXTURE
        self.res_pass.BackgroundTexture.value = path

    @field_has_changed(SceneGraph)
    def update_scenegraph(self):

        self.navigation = avango.gua.nodes.TransformNode(Name="navigation")

        cam = avango.gua.nodes.CameraNode(
            Name="cam",
            LeftScreenPath="/navigation/screen",
            SceneGraph=self.SceneGraph.value.Name.value,
            Resolution=self.window_size,
            OutputWindowName="window",
            Transform=avango.gua.make_trans_mat(0.0, 0.0, 1.0))

        cam.PipelineDescription.value = self.pipeline_description

        screen = avango.gua.nodes.ScreenNode(Name="screen",
                                             Width=1.6,
                                             Height=1.0)

        self.navigation.Children.value = [cam, screen]

        self.SceneGraph.value.Root.value.Children.value.append(self.navigation)

        self.Navigator.OutTransform.connect_from(cam.Transform)
        self.Navigator.RotationSpeed.value = 0.2
        self.Navigator.MotionSpeed.value = 0.04

        self.Viewer.SceneGraphs.value = [self.SceneGraph.value]
        self.Viewer.Windows.value = [self.window]
    def test_update_state(self):
        mock_world = MockWorld.create('map04')
        mock_game = MockGame()
        navigator = Navigator(mock_world)
        self.assertFalse(navigator.pathfinder is None)
        self.assertFalse(navigator.pathfinder.graph is None)
        self.assertEqual(len(navigator.pathfinder.graph),
                         mock_world.height * mock_world.width)
        self.assertFalse(navigator.is_on_extra_path)

        mock_car = MockCar()
        mock_car.x = 10800
        mock_car.y = 12400
        mock_car.next_waypoint_index = 1
        car = MyCar(mock_car, mock_game.track_tile_size)
        navigator.update_state(car)
        anchor_point = navigator.get_anchor_point(car, mock_world, mock_game)
        self.assertEqual(anchor_point, (600.0, 12600.0))
        self.assertEqual(navigator._prev_path_tile_idx, 0)
        self.assertFalse(navigator.is_on_extra_path)

        mock_car.x = 10000
        mock_car.y = 12400
        mock_car.next_waypoint_index = 1
        car = MyCar(mock_car, mock_game.track_tile_size)
        navigator.update_state(car)
        self.assertEqual(navigator._prev_path_tile_idx, 1)
        self.assertFalse(navigator.is_on_extra_path)

        mock_car.x = 9200
        mock_car.y = 12400
        mock_car.next_waypoint_index = 1
        car = MyCar(mock_car, mock_game.track_tile_size)
        navigator.update_state(car)
        self.assertEqual(navigator._prev_path_tile_idx, 2)
        self.assertFalse(navigator.is_on_extra_path)

        mock_car.x = 2000
        mock_car.y = 12400
        mock_car.next_waypoint_index = 1
        car = MyCar(mock_car, mock_game.track_tile_size)
        navigator.update_state(car)
        self.assertEqual(navigator._prev_path_tile_idx, 11)
        self.assertFalse(navigator.is_on_extra_path)

        mock_car.x = 1200
        mock_car.y = 12400
        mock_car.next_waypoint_index = 2
        car = MyCar(mock_car, mock_game.track_tile_size)
        self.assertEqual(car.cur_tile, (1, 15))
        navigator.update_state(car)
        self.assertFalse(navigator.is_on_extra_path)
        self.assertEqual(navigator._prev_path_tile_idx, 12)

        mock_car.x = 1200
        mock_car.y = 11600
        mock_car.next_waypoint_index = 2
        car = MyCar(mock_car, mock_game.track_tile_size)
        self.assertEqual(car.cur_tile, (1, 14))
        navigator.update_state(car)
        self.assertTrue(navigator.is_on_extra_path)
        self.assertEqual(navigator._prev_path_tile_idx, 13)
示例#14
0
 def __init__(self, root, dim=None, appName='BreadInterface'):
     # init the app components
     # self.settings = Settings(appName)
     self.navigator = Navigator(root, dim)
     self.appName = appName
示例#15
0
def demo():
    printWelcomeMsg()

    while True:
        print('\n================= MAIN MENU =================\n')
        buildingId = int(input('Please enter building ID: '))
        buildingName = algorithms.buildingDict[buildingId]
        buildingStorey = int(input('Please enter building storey: '))
        myMap = algorithms.downloadAndParseMap(buildingId, buildingName,
                                               buildingStorey)
        print(
            'Please enter an option:\n    1. Path Finding\n    2. Giving Direction (cumulative)\n    3. Quit Test'
        )
        testType = input()

        if testType == '1':
            while True:
                print('\n=============== NEW TEST CASE ===============\n')
                srcNodeId = int(
                    input(
                        'Please enter origin node ID (enter \'0\' to return to the main menu): '
                    ))
                if srcNodeId == 0:
                    break

                destNodeId = int(
                    input(
                        'Please enter destination node ID (enter \'0\' to return to the main menu): '
                    ))
                if destNodeId == 0:
                    break

                result = algorithms.computeRoute(myMap, srcNodeId, destNodeId)
                for i in range(len(result) - 1):
                    print(str(result[i]) + ' -> ', end="")
                print(result[len(result) - 1])
        elif testType == '2':
            srcNodeId = int(input('Please enter origin node ID: '))
            destNodeId = int(input('Please enter destination node ID: '))
            currentX = int(
                input('Please enter the x-coordinate of current location: '))
            currentY = int(
                input('Please enter the y-coordinate of current location: '))
            currentBearing = int(
                input(
                    'Please enter the bearing (w.r.t. geographical north) of current location: '
                ))
            route = algorithms.computeRoute(myMap, srcNodeId, destNodeId)
            navigator = Navigator(myMap, route, currentX, currentY,
                                  currentBearing, 50)

            while True:
                print('\n=============== NEW TEST CASE ===============\n')
                currentX = int(
                    input(
                        'Please enter the x-coordinate of current location: '))
                currentY = int(
                    input(
                        'Please enter the y-coordinate of current location: '))
                currentBearing = int(
                    input(
                        'Please enter the bearing (w.r.t. geographical north) of current location: '
                    ))

                navigator.updateLocation(currentX, currentY, currentBearing)
                if navigator.clearedRouteIdx == len(navigator.route) - 1:
                    print('You have reached the destination node.')
                    break
                naviInfo = navigator.getNaviInfo()
                print('Next node ID is ' +
                      str(navigator.route[navigator.clearedRouteIdx + 1]) +
                      '.')
                print('Distance from next node is ' + str(naviInfo[0]) +
                      ' centimeters.')
                bearing = (naviInfo[1] -
                           (currentBearing + myMap.northAt) % 360 + 360) % 360
                print('Bearing of next node from current location is ' +
                      str(bearing) + ' degrees.')
        else:
            break
    return
示例#16
0
# load a path file
#p = Path("Path-around-table.json")
p = Path("Path-around-table-and-back.json")
#p = Path("Path-from-bed.json")
#p = Path("Path-to-bed.json")
path = p.getPath()

print("Path length = " + str(len(path)))
print("First point = " + str(path[0]['X']) + ", " + str(path[0]['Y']))

# make a robot to move around
robot = Robot()
converter = AngleConverter()
pathHandler = PathHandler()
navigator = Navigator()
goal = Goal()

#### Intialize variables
position = robot.getPosition()
speed = 0.25
heading = 0
nextPoint = 0
dropOut = 0
lookAheadDistance = 0.85

while (goal.notGoal(position, nextPoint, path)):

    ### get current status (position, heading)
    position = robot.getPosition()
    heading = converter.convertToDegree(robot.getHeading())
示例#17
0
from PathHandler import PathHandler
from Navigator import Navigator

# Settings
maxSpeed = 0.5
lookAheadDistance = 0.8
lookAheadSwitchDistance = 0.5
maxTurnRate = 1.2
damperLength = 5

#### Intialize
robot = Robot()
p = Path("Path-around-table-and-back.json")
path = p.getPath()
pathHandler = PathHandler()
navigator = Navigator(maxSpeed, maxTurnRate, damperLength)
robot.setMotion(0, 0)
position = robot.getPosition()
heading = 0
nextPoint = 0

while (navigator.notGoal(position, nextPoint, path)):

    ### get current status (position, heading)
    position = robot.getPosition()
    heading = navigator.convertToDegree(robot.getHeading())

    ### get next point
    nextPoint = pathHandler.getNextPathPoint(position, path, nextPoint,
                                             lookAheadDistance,
                                             lookAheadSwitchDistance)