예제 #1
0
    def __init__(self, omap_path, sparki):
        self.omap = ObstacleMap(omap_path, noise_range=1)
        self.rangefinder = Rangefinder(cone_width=deg2rad(15.),
                                       obstacle_width=1.)

        FrontEnd.__init__(self, self.omap.width, self.omap.height)

        self.sparki = sparki
        self.robot = Robot()

        # center robot
        self.robot.x = self.omap.width * 0.5
        self.robot.y = self.omap.height * 0.5

        # create particle filter
        alpha = [0.5, 0.5, 0.5, 0.5]
        self.particle_filter = ParticleFilter(num_particles=50,
                                              alpha=alpha,
                                              robot=self.robot,
                                              omap=self.omap)

        # set message callback
        self.sparki.message_callback = self.message_received

        # last timestamp received
        self.last_timestamp = 0
예제 #2
0
def sineMotion(ids, commandRate, offset, amp, freq):
    robot = Robot(expectedIds=ids, commandRate=commandRate, cropMethod=None)

    nIds = len(ids)
    motionFunction = lambda time: [offset + amp * sin(2 * pi * time * freq) for ii in range(nIds)]

    robot.run(motionFunction, runSeconds=10, interpBegin=1, resetFirst=False)
예제 #3
0
def run_training(maze_size=(6, 6),
                 trap_number=1,
                 epoch=20,
                 epsilon0=0.3,
                 alpha=0.3,
                 gamma=0.9):

    # # 可选的参数:
    # epoch = 20

    # # 随机探索的初始概率
    # epsilon0 = 0.3

    # # 松弛变量
    # alpha = 0.3

    # # 折扣因子
    # gamma = 0.9

    # # 地图大小
    # maze_size = (6, 6)

    # # 陷阱数量
    # trap_number = 1

    g = Maze(maze_size=maze_size, trap_number=trap_number)
    r = Robot(g, alpha=alpha, epsilon0=epsilon0, gamma=gamma)
    r.set_status(learning=True)

    runner = Runner(r, g)
    runner.run_training(epoch, display_direction=True)
    # runner.generate_movie(filename = "final1.mp4") # 你可以注释该行代码,加快运行速度,不过你就无法观察到视频了。

    # runner.plot_results()
    return runner
예제 #4
0
 def Process():
     toy = Robot()
     try:
         print("\n")
         print("Welcome to the Toy Robot application.\n")
         print("Proceed to enter commands. Press CTRL-C to exit.\n")
         # Loop until we receive a kill signal.
         while True:
             # BUG: Change to input() for Python 3.x
             line = raw_input("> ")
             try:
                 # Parse the command.
                 cmd = Command(line)
                 # Execute the validated command on the robot.
                 cmd.Execute(toy)
             except CommandException as ce:
                 print(ce)
             except RobotException as re:
                 print(re)
             except CompassHeadingException as he:
                 print(he)
     except KeyboardInterrupt as kb:
         print("Keyboard exit signal detected.")
         pass
     finally:
         print("Exit requested.")
         toy.Cleanup()
         print("Application successfully exited.")
     return
예제 #5
0
def newRobots(x,y):
    robot = Robot()
    robot.set_x(x)
    robot.set_y(y)
    robot.set_speedX(random.choice((-1, 1)))
    robot.set_speedY(random.choice((-1, 1)))
    robots.add_robot(robot)
예제 #6
0
 def test_raise_engage_length_value_error(self):
     # it should pass only if the result is raising a ValueError
     world_size = (5, 4)
     lost_robots = []
     with self.assertRaises(ValueError):
         robot = Robot(world_size, lost_robots, 10, 10, 'N')
         robot.engage('k' * 102)
예제 #7
0
파일: Game.py 프로젝트: art32fil/ros_2017
    def start(self):
        last_update = rospy.Time.now().to_sec()

        self.robots["robot0"] = Robot("robot0", [0, 1, 0], 4000, [4, 0])
        self.robots["robot1"] = Robot("robot1", [0, 0, 1], 4000, [-4, 0])

        R = rospy.Rate(150)

        rospy.sleep(5)
        print ("HOLD WASD to move, E to exit")

        while not (rospy.is_shutdown() or self.shutdown):
            delta_time = rospy.Time.now().to_sec() - last_update

            for k, robot1 in self.robots.items():
                if robot1.alive:
                    robot1(delta_time)
                    for k2, robot2 in self.robots.items():
                            try:
                                if k != k2:
                                    position, quaternion = self.listener.lookupTransform("/"+robot1.damage.id, "/"+robot2.id, rospy.Time())
                                    distance = math.sqrt(position[0] * position[0] + position[1] * position[1])
                                    if distance < robot1.damage.length[0] / 2.0:
                                        robot2.destroy()
                            except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):
                                continue
            R.sleep()
            last_update = rospy.Time.now().to_sec()
예제 #8
0
    def __init__(self,r_name,r_id,x_off,y_off,theta_off, capacity):

        Robot.__init__(self,r_name,r_id,x_off,y_off,theta_off)

        self.carrier_pub = rospy.Publisher("carrier_position",String, queue_size=10)
        self.carrier_sub = rospy.Subscriber("carrier_position", String, self.carrier_callback)
        self.picker_sub = rospy.Subscriber("picker_position", String, self.picker_callback)
        self.kiwi_sub = rospy.Subscriber("picker_kiwi_transfer", String, self.kiwi_callback)
        self.kiwi_pub = rospy.Publisher("carrier_kiwi_transfer",String, queue_size=10)
        self.queue_pub = rospy.Publisher("carrier_allocation_request", String, queue_size=10)
        self.queue_sub = rospy.Subscriber("carrier_allocation_response", String, self.queue_callback)

        self.next_robot_id = None
        self.carrier_robots = ["0,0,0","0,0,0","0,0,0","0,0,0","0,0,0","0,0,0","0,0,0","0,0,0","0,0,0","0,0,0"]
        self.picker_robots = ["0,0,0","0,0,0","0,0,0","0,0,0","0,0,0","0,0,0","0,0,0","0,0,0","0,0,0","0,0,0"]

        self.max_load = capacity
        self.previousState = self.CarrierState.WAITINGFORPICKER
        self.is_going_home = False

        #these variables are used to help the laser callback, it will help in dealing with entities/debris on
        # it's path to the picker robot
        #self.StageLaser_sub = rospy.Subscriber(self.robot_node_identifier+"/base_scan",sensor_msgs.msg.LaserScan,self.StageLaser_callback)
        self.ReadLaser = False
        self.FiveCounter = 0
        self._divertingPath_ = False
예제 #9
0
    def __init__(self):
        Robot.__init__(self)
        self.wheel_radius = 0.02
        self.encoder_ticks_per_wheel_rev = 225
        self.wheel_base_length = 0.09
        self.max_speed = 0.3
        self._x, self._y, self._heading = STARTING_LOCATION

        # for getting velocities
        self.labyrinth = Labyrinth(
            MazeGenerator(LENGTH_OF_MAZE, LENGTH_OF_MAZE))
        self.position = Position(*STARTING_LOCATION, self.wheel_radius,
                                 self.encoder_ticks_per_wheel_rev)
        self.micro_state = MicroRobotState.UNKNOWN
        self.macro_state = MacroRobotState.MAPPING
        self.clew = DFS()
        self.previous_ticks = (0, 0)
        self.angle_ticker = 0
        self.angle_pid = PIDLoop(5, 0, 0.1)
        self.power_val = 2
        self.acceptable_angle_error = .1
        self.acceptable_physical_offset = 0.01
        self.angle_ticks_needed = 100
        self.next_cell = tuple()

        # for printing the graph
        self.real_xs = []
        self.determined_xs = []
        self.real_ys = []
        self.determined_ys = []
        self.race_start = 0
        return
예제 #10
0
 def create_fleet(self):
     robot_one = Robot('Tim', 5, 25)
     robot_two = Robot('Phil', 25, 60)
     robot_three = Robot('Rodney', 15, 40)
     self.fleet_of_robots.append(robot_one)
     self.fleet_of_robots.append(robot_two)
     self.fleet_of_robots.append(robot_three)
 def __init__(self, robot_position, world_map, shared_map, shared_visited, robot_search_mode):
     self.robot = Robot([robot_position[0], robot_position[1]], shared_map, shared_visited, robot_search_mode)
     self.robot_current_position_in_world_map = [robot_position[0], robot_position[1]]
     self.world_map = world_map
     self.timestep = 11
     self.TOTAL_WAITING_TIME = 10
     self.stopped = False
예제 #12
0
	def select_a_rect_distance_search(self):

		self.load_environment()
		self.clear_components()

		self.optionDialog = DialogOption()
		self.optionDialog.display_option_message("Do you want avoid cycles")
		option_response = self.optionDialog.get_taken_option()

		message = "Please specify the numerator and denominator to complement the heuristic method"
		aSearchValueDialog = DialogASearchValues()
		aSearchValueDialog.show_request_message(message)
		numerator = aSearchValueDialog.get_numerator()
		denominator = aSearchValueDialog.get_denominator()
		
		self.robot = Robot(self,self.environment,self.dimension,self.queue_dimension,"A*h1",option_response,numerator,denominator)

		if option_response:
			self.labelSelectedSearch.setText("A* Straight Line Distance avoiding cycles")
		else:
			self.labelSelectedSearch.setText("A* Straight Line Distance with cycles")

		self.draw_environment()
		self.plainTextEditRobotStatus.appendPlainText("Ready .......")
		
		self.pushButtonMoveRobot.setEnabled(False)
		self.pushButtonLookGraph.setEnabled(True)
		self.pushButtonFastSearch.setEnabled(True)
		self.pushButtonNextStep.setEnabled(True)
예제 #13
0
 def test_robots(self):
     parser = urlparse(self.url)
     domain = parser.hostname
     isexistrobot = self.r.get(domain)
     if isexistrobot is None:
         # Collect Robots.txt
         robot = Robot(self.url)
         lst_rule = robot.get_rule()
         # Save to Redis
         self.r.set(domain, lst_rule)
         if robot.is_allowed(self.url):
             return True
         else:
             return False
     else:
         lst_rule = literal_eval(isexistrobot)
         path = parser.path
         for item in lst_rule:
             if '.' in item:
                 item = item.replace('.', '\.')
             if '*' in item:
                 item = item.replace('*', '.*')
             if '?' in item:
                 item = item.replace('?', '\?')
             ro = match(item, path)
             if ro is not None:
                 return False
         else:
             return True
예제 #14
0
 def setUp(self):
     self.robot = Robot()
     self.tests_data = {}
     self.images_data = {}
     for image_file in os.listdir(TESTS_DATA_PATH):
         self.tests_data[os.path.splitext(image_file)[0]] = cv2.imread(TESTS_DATA_PATH + image_file)
     for image_file in os.listdir(IMAGE_DATA_PATH):
         self.images_data[os.path.splitext(image_file)[0]] = cv2.imread(IMAGE_DATA_PATH + image_file)
예제 #15
0
 def test_raise_value_error(self):
     # it should pass only if the result is raising a ValueError
     world_size = (5, 4)
     lost_robots = []
     with self.assertRaises(ValueError):
         wrong_x_robot = Robot(world_size, lost_robots, 55, 20, 'N')
         wrong_y_robot = Robot(world_size, lost_robots, 20, 55, 'E')
         wrong_direction_robot = Robot(world_size, lost_robots, 20, 20, 'K')
예제 #16
0
 def test_robot_random(self):
     game = Game('X', 'O')
     robot = Robot()
     score = game.get_score_of_grid(game.grid)
     x, y = robot.get_random_move_robot(game)
     robot.do_move_robot(game, x, y)
     new_score = game.get_score_of_grid(game.grid)
     self.assertTrue(score['O'] < new_score['O'])
예제 #17
0
def grasp_centroid_data():
    wd = '/home/lou00015/data/gsp/'
    cid = vrep.simxStart('127.0.0.1', 19997, True, True, 5000, 5)
    eid = 0
    nb_grasp = 25
    if cid != -1:
        pos = [0, 0, 0.15]
        while True:
            vrep.simxStartSimulation(cid, vrep.simx_opmode_blocking)
            panda = Robot(cid)
            obj_name, obj_hdl = add_object(cid, 'imported_part_0', pos)
            time.sleep(1.0)
            cloud = panda.get_pointcloud()
            centroid = np.average(cloud, axis=0)
            print('centroid: ', centroid)
            if len(cloud) == 0:
                print('no cloud found')
                continue
            elif centroid[2] > 0.045:
                print('perception error')
                continue
            np.save(wd + 'cloud_' + str(eid) + '.npy', cloud) # save point cloud
            cloud = np.delete(cloud, np.where(cloud[:,2]<0.015), axis=0)
            pose_set, pt_set = grasp_pose_generation(45, cloud, nb_grasp)
            pose = pose_set[10]
            pt = centroid
            emptyBuff = bytearray()
            landing_mtx = [pose[0][0],pose[0][1],pose[0][2],pt[0],
                           pose[1][0],pose[1][1], pose[1][2],pt[1],
                           pose[2][0],pose[2][1],pose[2][2],pt[2]]
            np.save(wd + 'action_' + str(eid) + '.npy', landing_mtx) # save action
            vrep.simxCallScriptFunction(cid, 'landing', vrep.sim_scripttype_childscript, 'setlanding', [], landing_mtx, [], emptyBuff, vrep.simx_opmode_blocking)
            ending_mtx = [pose[0][0], pose[0][1], pose[0][2], pt[0],
                          pose[1][0], pose[1][1], pose[1][2], pt[1],
                          pose[2][0], pose[2][1], pose[2][2], pt[2]+0.15]
            vrep.simxCallScriptFunction(cid, 'ending', vrep.sim_scripttype_childscript, 'setending', [], ending_mtx,
                                        [], emptyBuff, vrep.simx_opmode_blocking)
            time.sleep(1.0)
            print('executing experiment %d: ' % (eid))
            print('at: ', pt)
            vrep.simxCallScriptFunction(cid, 'Sphere', vrep.sim_scripttype_childscript, 'grasp', [], [], [], emptyBuff, vrep.simx_opmode_blocking)
            while True:
                res, finish = vrep.simxGetIntegerSignal(cid, "finish", vrep.simx_opmode_oneshot_wait)
                if finish == 18:
                    res, end_pos = vrep.simxGetObjectPosition(cid, obj_hdl, -1, vrep.simx_opmode_blocking)
                    break
            if end_pos[2]>0.05:
                label = 1
            else:
                label = 0
            print(label)
            f = open(wd + 'label.txt', 'a+')
            f.write(str(label))
            f.close()
            eid += 1
    else:
        print('Failed to connect to simulation (V-REP remote API server). Exiting.')
    exit()
예제 #18
0
 def test_positive_robot_3(self):
     bot = Robot()
     Command("place 3,2,E").Execute(bot)
     Command("MOVE").Execute(bot)
     self.assertEqual(bot.IsPlaced(), True)
     self.assertEqual(bot.GetPosition()[0], 4)
     self.assertEqual(bot.GetPosition()[1], 2)
     self.assertEqual(bot.GetPosition()[2], "E")
     return
예제 #19
0
class Simulation():
    def __init__(self):
        self.town = Town(maxShops = 10)
        self.town.render(DisplayDriver.engine)
        self.robot = Robot(random.choice(list(self.town.shopDict)), town = self.town)
        self.robot.render(DisplayDriver.engine)

    def tick(self):
        self.robot.tick()
예제 #20
0
def test_different_parameter(alpha_test, gamma_test, epsilon_test, epoch_test):
    g = Maze(maze_size=maze_size, trap_number=trap_number)
    r = Robot(g, alpha=alpha_test, epsilon0=epsilon_test, gamma=gamma_test)
    r.set_status(learning=True)

    runner = Runner(r, g)
    runner.run_training(epoch_test, display_direction=True)
    print("alpha: {}, gamma: {}, epsilon: {}, epoch: {}".format(
        alpha_test, gamma_test, epsilon_test, epoch_test))
    runner.plot_results()
예제 #21
0
    def __init__(self, grid_size, discount, robot_state, beta, robot_goal,
                 obs_sizes, true_env):
        self.human = Human(true_env, beta, discount, robot_goal, grid_size)
        robot_env = np.zeros((grid_size[0], grid_size[1]))
        self.robot = Robot(robot_env, robot_state, robot_goal, grid_size,
                           discount)

        robot_action = self.robot.optimal_policy()
        self.infer = Inference(grid_size, discount, robot_state, beta,
                               robot_goal, robot_action, obs_sizes)
예제 #22
0
    def test__str__(self):
        """
		verifie la methode __str__
		"""
        robot1 = Robot(1, 1, "robot1")

        sa = "test : <Robot robot1 (1, 1)>"
        so = "test : " + robot1.__str__()
        self.assertEqual(sa, so)
        pass
예제 #23
0
class Simulation():
    def __init__(self):
        self.town = Town(maxShops=10)
        self.town.render(DisplayDriver.engine)
        self.robot = Robot(random.choice(list(self.town.shopDict)),
                           town=self.town)
        self.robot.render(DisplayDriver.engine)

    def tick(self):
        self.robot.tick()
예제 #24
0
def main():
    if len(sys.argv) < 3:
        print 'Usage: %s input_gait_file output_position_file' % sys.argv[0]
        sys.exit(1)

    gaitFile = sys.argv[1]
    posFile  = sys.argv[2]


    strategy = TimedFileStrategy(posFile = gaitFile)

    motionFunction, logInfo = strategy.getNext()

    #runman = RunManager()
    #runman.do_many_runs(strategy, SineModel5.typicalRanges)

    #timeScale = .3
    #motionFunctionScaled = scaleTime(motionFunction, timeScale)
    wiiTrack = WiiTrackFastClient("localhost", 8080)
    time.sleep(.5)
    position,age = wiiTrack.getPosAge()
    if age is None:
        raise Exception('Could not get position from wiiTrack.')

    robot = Robot(loud = True)
    bucket = []

    def foo():
        savePosition(wiiTrack, bucket)

    robot.run(motionFunction, runSeconds = 10, resetFirst = True,
              interpBegin = 2, interpEnd = 2, extraLogInfoFn = foo)

    print 'Positions:'
    print len(bucket)

    relTimeBucket = []
    for ii, line in enumerate(bucket):
        delta = line[0] - bucket[0][0]
        relTime = delta.seconds + delta.microseconds/1e6
        relTimeBucket.append((relTime, line[1], line[2]))


    ff = open (posFile, 'w')
    ff.write('# time (junk junk)x9 pos.x pos.y 0 age\n')
    for ii, timePosAge in enumerate(relTimeBucket):
        timeOfPosition, position, age = timePosAge
        line = '%.3f' % timeOfPosition
        line += ' -1 -1' * 9
        line += ' %.1f %.1f %.1f' % (position[0], position[1], 0)
        line += ' %f' % age
        ff.write(line + '\n')
    ff.close()
    print 'Wrote position file:', posFile
예제 #25
0
 def __init__(self,
              parent=None,
              instanceName=None,
              instanceType = Sensation.InstanceType.SubInstance,
              level=0):
     print("We are in TensorFlowClassification, not Robot")
     Robot.__init__(self,
                    parent=parent,
                    instanceName=instanceName,
                    instanceType=instanceType,
                    level=level)
예제 #26
0
 def __init__(self,
              parent=None,
              instanceName=None,
              instanceType = Sensation.InstanceType.Real,
              level=0):
     print("We are in Connection, not Robot")
     Robot.__init__(self,
                    parent=parent,
                    instanceName=instanceName,
                    instanceType=instanceType,
                    level=level)
예제 #27
0
    def __init__(self,omap_path,sparki):
        self.omap = OccupancyGrid(omap_path)
    
        FrontEnd.__init__(self,self.omap.width,self.omap.height)

        self.sparki = sparki
        self.robot = Robot()
        
        # center robot
        self.robot.x = self.omap.width*0.5
        self.robot.y = self.omap.height*0.5
예제 #28
0
파일: Hearing.py 프로젝트: korhore/Wall-E
 def __init__(self,
              parent=None,
              instanceName=None,
              instanceType = Sensation.InstanceType.SubInstance,
              level=0):
     Robot.__init__(self,
                    parent=parent,
                    instanceName=instanceName,
                    instanceType=instanceType,
                    level=level)
     print("We are in Hearing, not Robot")
예제 #29
0
def make_default_robot(robot_name, path_color):
	robot = Robot(initial_position, cmdargs, env, path_color=path_color, name=robot_name, objective=objective);
	robot.put_sensor('radar', radar);
	robot.put_sensor('gps', GpsSensor(robot));
	robot.put_sensor('params', {'name': robot_name});
	robot.debug_info['ped_id'] = cmdargs.ped_id_to_replace;

	return robot
예제 #30
0
def sluchaj_wejscie_z_gniazda(sock): # thread
    parser = CompParser()
    robot = Robot()
    global dzialaj
    while dzialaj:
        odebrane_dane = sock.otrzymaj_dane(ile=20)
        print odebrane_dane
        x, y, przyciskPSP2Stan = parser.parsuj_klawisze(dane=odebrane_dane)
        robot.reaguj(int(x), int(y), przyciskPSP2Stan)
        # krotszy niz na psp ; 50razy/sek cos odczytam; ale w pesymistycznym
        # przypadku tylko 25 razy na sek ;/
        time.sleep(0.002)
예제 #31
0
def sluchaj_wejscie_z_gniazda(sock):  # thread
    parser = CompParser()
    robot = Robot()
    global dzialaj
    while dzialaj:
        odebrane_dane = sock.otrzymaj_dane(ile=20)
        print odebrane_dane
        x, y, przyciskPSP2Stan = parser.parsuj_klawisze(dane=odebrane_dane)
        robot.reaguj(int(x), int(y), przyciskPSP2Stan)
        # krotszy niz na psp ; 50razy/sek cos odczytam; ale w pesymistycznym
        # przypadku tylko 25 razy na sek ;/
        time.sleep(0.002)
예제 #32
0
def generate_ground_truth(motions, landmarks, worldSize):

	myrobot = Robot({'landmarks':landmarks, 'worldSize':worldSize})
    	myrobot.set_noise({'bearing':bearing_noise, 'steering': steering_noise, 'distance': distance_noise})

    	Z = []
    	T = len(motions)

    	for t in range(T):
        	myrobot = myrobot.move(motions[t])
        	Z.append(myrobot.sense())
    	return [myrobot, Z]
예제 #33
0
    def __init__(self, sparki, omap_path):
        self.omap = OccupancyMap(omap_path)
        FrontEnd.__init__(self, self.omap.width, self.omap.height)
        self.sparki = sparki
        self.robot = Robot()

        # center robot
        self.robot.x = self.omap.width * 0.5
        self.robot.y = self.omap.height * 0.5

        # zero out robot velocities
        self.robot.lin_vel = 0
        self.robot.ang_vel = 0
예제 #34
0
    def __init__(self, omap_path, sparki):
        self.omap = ObstacleMap(omap_path)
        self.ogrid = OccupancyGrid()

        FrontEnd.__init__(self, self.omap.width, self.omap.height)

        self.sparki = sparki
        self.robot = Robot()
        self.rfinder = RangeFinder(self.ogrid, self.robot)

        # center robot
        self.robot.x = self.omap.width * 0.5
        self.robot.y = self.omap.height * 0.5
예제 #35
0
class RobotTests(unittest.TestCase):
    def setUp(self):
        self.mega_man = Robot("Mega Man", battery=50)

    def test_charge(self):
        self.mega_man.charge()
        self.assertEqual(self.mega_man.battery, 100)

    def test_say_name(self):
        self.assertEqual(
            self.mega_man.say_name(),
            "BEEP BOOP BEEP BOOP.  I AM MEGA MAN")
        self.assertEqual(self.mega_man.battery, 49)
예제 #36
0
def main():
    """
    Main function
    """
    try:
        # Instantiate odometry. Default value will be 0,0,0
        # robot = Robot(init_position=args.pos_ini)
        robot = Robot()

        if is_debug:
            start_robot_drawer(robot.finished, robot)
        else:
            start_robot_logger(robot.finished, robot,
                               "./out/trayectoria_1.csv")

        print("X value at the beginning from main X= %d" % (robot.x.value))

        # 1. launch updateOdometry Process()
        robot.startOdometry()

        # 2. perform trajectory
        path_1_odometry(robot)

        # 3. wrap up and close stuff ...
        # This currently unconfigure the sensors, disable the motors,
        # and restore the LED to the control of the BrickPi3 firmware.
        robot.stopOdometry()

    except KeyboardInterrupt:
        # except the program gets interrupted by Ctrl+C on the keyboard.
        # THIS IS IMPORTANT if we want that motors STOP when we Ctrl+C ...
        robot.stopOdometry()
예제 #37
0
    def __init__(self,r_name,r_id,x_off,y_off,theta_off,capacity):
        Robot.__init__(self,r_name,r_id,x_off,y_off,theta_off)

        self.max_load = capacity

        self.timeLastAdded = time.clock()
        self.disableSideLaser = False

        self.picker_pub = rospy.Publisher("picker_position",String, queue_size=10)
        self.kiwi_sub = rospy.Subscriber("carrier_kiwi_transfer", String, self.kiwi_callback)
        self.kiwi_pub = rospy.Publisher("picker_kiwi_transfer",String, queue_size=10)

        self.picker_sub = rospy.Subscriber("picker_position", String, self.picker_callback)
        self.picker_robots = ["0,0,0","0,0,0","0,0,0","0,0,0","0,0,0","0,0,0"]
예제 #38
0
 def test_generate_map_obstacle_rate(self):
     size_x = 5
     obstacle_rate = 0.25
     r = Robot()
     r.set_size(size_x)
     r.set_obstacle_rate(obstacle_rate)
     r.generate_map()
     map_mat = r.get_map()
     self.assertEqual(map_mat.shape, (size_x, size_x))
     spaces_count = np.count_nonzero(map_mat)
     self.assertGreater(spaces_count, 0)
예제 #39
0
 def test_state_to_coordinates(self):
     size_x = 5
     obstacle_rate = 0.25
     r = Robot()
     r.set_size(size_x)
     r.set_obstacle_rate(obstacle_rate)
     r.generate_map()
     map_mat = r.get_map()
     current_state = 0
     for i in range(size_x):
         for j in range(size_x):
             if map_mat[i][j] == 0:
                 self.assertEqual(r.state_to_coordinates(current_state),
                                  (i, j))
                 current_state += 1
예제 #40
0
class Localizer:
    def __init__(self):
        self.map = LandmarkMap(color='C7', marker='x')
        self.robot_model = Robot(color='C7')

    def measurement_callback(self, r, phi):
        x, y = Robot.world_t_sensor(self.robot_model.pose, r, phi)
        self.map.addLandmarks(x, y)

    def odometry_callback(self, v, omega, t=1):
        self.robot_model.move(v, omega, t)

    def plot(self):
        self.robot_model.plot()
        self.map.plot()
예제 #41
0
 def __init__(self, position, id, scale):
     Robot.__init__(self,position,id,scale)
         
     self.type = randint(0,1)
     
     if self.type == 0:
         taskMgr.add( self.randomWalk, 'walk')
         self.destination = Point2()
         self.setRandomPoint( self.destination )
     else:
         taskMgr.add( self.hunt, 'hunt')
         self.target = None
             
     self.time = 0
     self.bulletTime = 0
예제 #42
0
파일: run.py 프로젝트: RandomLab/craft
    def update_robot(self, unused_addr, args):
        print("update robot")
        self.robot.run()
        score = Robot.count("Soja")
        self.playerListBox.delete(0, tk.END)
        #self.playerListBox.insert(tk.END, player_name + " " + str(score))
        print(self.players_list)
        for p in self.players_list:
            self.playerListBox.insert(tk.END, p + " " + str(self.players_list[p]))

        msg = osc_message_builder.OscMessageBuilder(address="/player")
        msg.add_arg(player_name)
        msg.add_arg(score) #
        msg = msg.build()
        self.to_client_client.send(msg)

        if self.robot.win:
            # I am the winner
            # lets tel that to ohters
            msg = osc_message_builder.OscMessageBuilder(address="/winner")
            msg.add_arg(player_name)
            msg.add_arg(score)
            msg = msg.build()
            #self.to_client_client.send(msg)
            self.to_server_client.send(msg)
            alert(text = "Vous avez gagné la partie !")
예제 #43
0
파일: Main.py 프로젝트: maddockm/ECU178A4
class Simulation():
    def __init__(self):
        self.robot = Robot([640/2,640/2])
        self.robot.render(DisplayDriver.engine)
        #r.setBearing(random.random()*360)

        self.robot.velocity = 100

        #DisplayDriver.eventManager.bind(MOUSEMOTION,mouseMoved)
        DisplayDriver.engine.addTask(r.tick)


    def mouseMoved(event):
        pos = event.pos

        self.robot.setBearing(Point(pos).getBearing(r.getPos()))
예제 #44
0
파일: Main.py 프로젝트: JJM07/ECU178A4
class Simulation():
    def __init__(self):
        self.town = Town(maxShops = 10)
        self.town.render(DisplayDriver.engine)
        self.robot = Robot(random.choice(list(self.town.shopDict)), town = self.town)
        self.robot.render(DisplayDriver.engine)

        self.consumeText = OnscreenText(pos = [Globals.RESOLUTION[0]-200,0], text = '', size = 20)
        self.consumeText.render(DisplayDriver.engine)

        self.distanceText = OnscreenText(pos = [Globals.RESOLUTION[0]-200,20], text = '', size = 20)
        self.distanceText.render(DisplayDriver.engine)

        self.contraintsText = OnscreenText(pos = [Globals.RESOLUTION[0]-200,30], text = '', size = 20)
        self.contraintsText.render(DisplayDriver.engine)



    def tick(self):
        self.robot.tick()
        self.distanceText.setText('Distance: %sm' %(int(self.robot.getDistanceTraveled())))
        self.consumeText.setText('Fuel Used: %s' %(int(self.robot.getFuelUsed())))

        try:
            self.contraintsText.setText('Distance/Fuel: %s' %(round(self.robot.getDistanceTraveled()/self.robot.getFuelUsed(), 2)))
        except ZeroDivisionError:
            pass
예제 #45
0
파일: Main.py 프로젝트: maddockm/ECU178A4
 def new(self, event=None):
     if self.t:
         self.t.destroy()
         self.r.destroy()
     self.t = Town(maxShops=15)
     self.t.render(DisplayDriver.engine)
     self.r = Robot(random.choice(list(self.t.shopDict)), town = self.t)
     self.r.calcPath()
     self.r.render(DisplayDriver.engine)
예제 #46
0
파일: Main.py 프로젝트: maddockm/ECU178A4
    def __init__(self):
        self.robot = Robot([640/2,640/2])
        self.robot.render(DisplayDriver.engine)
        #r.setBearing(random.random()*360)

        self.robot.velocity = 100

        #DisplayDriver.eventManager.bind(MOUSEMOTION,mouseMoved)
        DisplayDriver.engine.addTask(r.tick)
예제 #47
0
 def loadRobot(self, file):
     robotLines = file.readlines()
 
     start = None
 
     for i,line in enumerate(robotLines):
         if line.startswith('robot'):
             start = i
         elif line.startswith('endrobot'):
             points = self.processPolygon(robotLines, start, i)
             self.robot = Robot(points)
예제 #48
0
    def __init__(self,
                 socket, 
                 address,
                 parent=None,
                 instance=None,
                 is_virtualInstance=False,
                 is_subInstance=False,
                 level=0):

        Robot.__init__(self,
                       parent=parent,
                       instance=instance,
                       is_virtualInstance=is_virtualInstance,
                       is_subInstance=is_subInstance,
                       level=level)
        
        print("We are in SocketServer, not Robot")
        self.socket=socket
        self.address=address
        self.name = str(address)
예제 #49
0
    def __init__(self,
                 parent=None,
                 instanceName=None,
                 instanceType = Sensation.InstanceType.SubInstance,
                 level=0):
        print("We are in RaspberryPiCamera, not Robot")
        Robot.__init__(self,
                       parent=parent,
                       instanceName=instanceName,
                       instanceType=instanceType,
                       level=level)
        

          
        # from settings
        self.camera = picamera.PiCamera()
        self.camera.rotation = 180
        self.lastImage = None

        self.running=False
        self.debug_time=time.time()
    def test_walking_angular_turn(self):
        r = Robot("Tamara", [0, 0], 0)
        r.forward_multiplicator = 1
        r.sideward_multiplicator = 1
        r.angular_multiplicator = 1
        r.forward = 0
        r.sideward = 0
        r.angular = 10
        self.worldService.update_robot(r, 1)

        self.assertAlmostEqual(10, r.orientation)
예제 #51
0
def main22():
    if len(sys.argv) > 2 and sys.argv[1] == '-filt':
        filtFile = sys.argv[2]
        strategy = FileStrategy(filtFile = filtFile)
        motionFunction, logInfo = strategy.getNext()
    elif len(sys.argv) > 2 and sys.argv[1] == '-sine':
        sineModel5Params = [eval(xx) for xx in sys.argv[2].split()]
        print 'Using SineModel5 with params: ', sineModel5Params
        motionFunction = lambda time: SineModel5().model(time,
                                                         parameters = sineModel5Params)
    else:
        #filtFile = '../results/hyperneatTo20gens_101/neat_110115_175446_00014_008_filt'
        filtFile = '../results/hyperneatTo20gens_101/neat_110115_175446_00004_007_filt'
        strategy = FileStrategy(filtFile = filtFile)
        motionFunction, logInfo = strategy.getNext()
    	

    
    #runman = RunManager()
    #runman.do_many_runs(strategy, SineModel5.typicalRanges)

    #timeScale = .3
    #motionFunctionScaled = scaleTime(motionFunction, timeScale)
    wiiTrack = WiiTrackFastClient("localhost", 8080)
    time.sleep(.5)
    position,age = wiiTrack.getPosAge()
    if age is None:
        raise Exception('Could not get position from wiiTrack.')

    robot = Robot(loud = True)
    bucket = []

    def foo():
        savePosition(wiiTrack, bucket)

    robot.run(motionFunction, runSeconds = 8, resetFirst = False,
              interpBegin = 2, interpEnd = 2, extraLogInfoFn = foo)
    
    print bucket    
    def test_walking_simple_axis_left(self):
        r = Robot("Tamara", [0, 0], 180)
        r.forward_multiplicator = 1
        r.sideward_multiplicator = 1
        r.angular_multiplicator = 1
        r.forward = 1
        r.sideward = 0
        r.angular = 0
        self.worldService.update_robot(r, 1)

        self.assertAlmostEqual(-1, r.xy[0])
        self.assertAlmostEqual(0, r.xy[1])
예제 #53
0
파일: Main.py 프로젝트: JJM07/ECU178A4
    def __init__(self):
        self.town = Town(maxShops = 10)
        self.town.render(DisplayDriver.engine)
        self.robot = Robot(random.choice(list(self.town.shopDict)), town = self.town)
        self.robot.render(DisplayDriver.engine)

        self.consumeText = OnscreenText(pos = [Globals.RESOLUTION[0]-200,0], text = '', size = 20)
        self.consumeText.render(DisplayDriver.engine)

        self.distanceText = OnscreenText(pos = [Globals.RESOLUTION[0]-200,20], text = '', size = 20)
        self.distanceText.render(DisplayDriver.engine)

        self.contraintsText = OnscreenText(pos = [Globals.RESOLUTION[0]-200,30], text = '', size = 20)
        self.contraintsText.render(DisplayDriver.engine)
예제 #54
0
class MessageParser:
    """Parses JSON messages an performs the according SwankRatsRobot action"""

    def __init__(self):
        self.id = 123
        self.robot = Robot()
        self.currentState = StateClasses.Stop()

    def parse(self, jsonString):
        data = json.loads(jsonString)

        if data["to"] == "robot":
            self.execute(data["cmd"], data["params"]["started"])
        elif data["to"] == "server" and data["cmd"] == "stop":
            self.currentState = StateClasses.Stop()

        self.robot.set(self.currentState.getLeft(), self.currentState.getRight())
        json.dumps(data)

    def execute(self, key, pressed):
        if pressed:
            self.currentState = self.currentState.press(key)
        else:
            self.currentState = self.currentState.release(key)
예제 #55
0
파일: Game.py 프로젝트: 11elangelm/Mini-5
 def __init__(self,dimension = [0,0]):#requiere dimension del campo
     rx = dimension[0]*random()#inicializamos posicion x
     ry = dimension[1]*random()#inicializamos posicion y
     self.robot = Robot(pos = [rx,ry])#posicion
     
     self.robot.setAngle(random()*360)#colocamos un angulo aleatorio
     
     px = dimension[0]*random()#posicion x pelota
     py = dimension[1]*random()#posicion y pelota
     self.pelota = Pelota(pos = [px,py])
     
     #colocamos la porteria a la derecha por defecto
     x = dimension[0]#porteria en la derecha
     yini = dimension[1]/2.0-dimension[1]/6.0#se coloca a un tercio de altura
     yfin = dimension[1]/2.0+dimension[1]/6.0#que llegue hasta dos tercios 
     self.porteria = Porteria(init=[x,yini],end=[x,yfin])
예제 #56
0
파일: Main.py 프로젝트: freshollie/ECU178A4
    def generate(self):

        self.town = Town(maxShops = 13)
        self.town.render(DisplayDriver.engine)

        self.robot = Robot(town = self.town, shoppingList = self.getShoppingList())
        self.robot.render(DisplayDriver.engine)

        self.consumeText = OnscreenText(pos = [Globals.RESOLUTION[0]-200,0], text = '', size = 20)
        self.consumeText.render(DisplayDriver.engine)

        self.distanceText = OnscreenText(pos = [Globals.RESOLUTION[0]-200,20], text = '', size = 20)
        self.distanceText.render(DisplayDriver.engine)

        self.contraintsText = OnscreenText(pos = [Globals.RESOLUTION[0]-200,30], text = '', size = 20)
        self.contraintsText.render(DisplayDriver.engine)
예제 #57
0
 def __init__(self):
     '''Uses VPython to visualize, manipulate and simulate the Quadruped live.'''
     self.bodies = []
     self.cWorld = myWorld()
     self.createUI(self.cWorld.world._getScene())
     
     # terrain for future implementation
     #self.myWorld = e.Heightmap(self.cWorld.world)
     #self.Terrain = self.myWorld.makeWorld()
     
     self.cRobot = Robot(self.cWorld.world, vpyode._bigSpace, 50)
     self.cCtrl = ControlWindow(self.cWorld.world._getScene(), self.cRobot, self.cWorld)
     
     self.cRobot.dropRobot()
     
     self.dt = 1.0/const.framerate
     self.refresh = 0
     
     self.bodies.append(e.drop_object(self.cWorld.world, self.cRobot.center))
	def __init__(self,propsfile):
		self.canvas = Tk()
		
		self.props = json.load(open(propsfile))
		self.worldMap = WorldMap(propsfile)
		
		self.wg = WorldGrid(self.canvas,self.props,self.worldMap)
		self.wg.registerCallBack(self.processEvent)
		
		self.robot = Robot(self.props,self.worldMap)
		self.robot.registerSenseCallBack(self.sense)
		self.robot.registerMoveCallBack(self.move)
		
		self.rRow = -1
		self.rCol = -1

		self.randomizeRobotPosition()
		self.robot.sense()
		self.shadeSquares()
	def select_uniform_cost_search(self):

		self.load_environment()
		self.clear_components()

		self.optionDialog = DialogOption()
		self.optionDialog.display_option_message("Do you want avoid cycles")
		option_response = self.optionDialog.get_taken_option()
		
		self.robot = Robot(self,self.environment,self.dimension,self.queue_dimension,"UniformCost",option_response)

		if option_response:
			self.labelSelectedSearch.setText("UniformCost avoiding cycles")
		else:
			self.labelSelectedSearch.setText("UniformCost with cycles")

		self.draw_environment()
		self.plainTextEditRobotStatus.appendPlainText("Ready .......")
		
		self.pushButtonMoveRobot.setEnabled(False)
		self.pushButtonLookGraph.setEnabled(True)
		self.pushButtonFastSearch.setEnabled(True)
		self.pushButtonNextStep.setEnabled(True)