示例#1
0
 def test_read_instructions_three_robots_oneloss_oneavoidance(self):
     dir_name = self._create_dir()
     filepath = f'{dir_name}/allgood'
     afile = (
         f'{filepath}_2',
         '''5 3\n\n1 1 E\nRFRFRFRF\n\n3 2 N\nFRRFLLFFRRFLL\n\n0 3 W\nLLFFFLFLFL\n'''
     )
     expectations = (
         ('::Start[1,1,E] ::TurnRight ::MoveForward ::TurnRight ::MoveForward ::TurnRight ::MoveForward ::TurnRight ::MoveForward',
          '1 1 E'),
         ('::Start[3,2,N] ::MoveForward ::TurnRight ::TurnRight ::MoveForward ::TurnLeft ::TurnLeft ::MoveForward ::MoveForward ::TurnRight ::TurnRight ::MoveForward ::TurnLeft ::TurnLeft',
          '3 3 N LOST'),
         ('::Start[0,3,W] ::TurnLeft ::TurnLeft ::MoveForward ::MoveForward ::MoveForward ::TurnLeft ::MoveForward ::TurnLeft ::MoveForward ::TurnLeft',
          '2 3 S'),
     )
     with open(afile[0], 'a') as fl:
         fl.write(afile[1])
     inst_file_processor = InstructionsFile(afile[0])
     inst_file_processor.initialise_instructions()
     grid_extents = inst_file_processor.grid_extents
     self.assertEqual(grid_extents.coord_x, 5)
     self.assertEqual(grid_extents.coord_y, 3)
     grid = Grid(grid_extents)
     count = 0
     for robot_instruction in inst_file_processor.next_instructions():
         self.assertEqual(str(robot_instruction), expectations[count][0])
         robot = Robot()
         for inst in robot_instruction.instruction_list:
             inst.do(grid, robot)
             if robot.is_lost:
                 break
         self.assertEqual(str(robot), expectations[count][1])
         count += 1
     self.assertEqual(count, 3)
示例#2
0
def run_cli():
    cli_robot = Robot()
    print "Enter your robot command (press q to quit):"

    while True:
        shell_command = raw_input('>')
        shell_command = shell_command.strip().lower()
        if not shell_command:
            continue
        if shell_command == 'q':
            break

        words = shlex.split(shell_command)

        # Grab the arguments
        args = words[1:] if len(words) > 1 else []

        # Grab the method
        method_name = words[0]
        try:
            method = getattr(cli_robot, words[0])
            result = method(*args)
            if result:
                print "The coordinate of the robot is (%s, %s) and facing %s" % result
        except:
            print "Class {} does not implement {} command".format(
                cli_robot.__class__.__name__, method_name.upper())
示例#3
0
 def test_move(self, mock_calc_x_y_vec, mock_is_within_boundary):
     mock_is_within_boundary.return_value = True
     mock_calc_x_y_vec.return_value = (0, 1)
     test_robot = Robot()
     test_robot.place(1, 1, NORTH)
     test_robot.move()
     result = test_robot.report()
     self.assertEqual((1, 2, NORTH), result)
示例#4
0
 def __init__(self):
     threading.Thread.__init__(self)
     self.manager = SimulationManager()         
     self.client_id = self.manager.launchSimulation(gui=True)
     p.connect(p.DIRECT)
     self.robot = Robot(self.manager, self.client_id)
     self.createScene()
     self.initUI()
示例#5
0
class TestClass:
    garage = Garage(3)

    # Create the robots
    r2d2 = Robot("R2D2", 20, 40, 0, "Anakin")
    c3po = Robot("C3PO", 30, 50, 0, "Vader")
    bb8 = Robot("BB8", 10, 45, 0, "Rei")

    # Park the robots
    garage.park_robot(r2d2)
    garage.park_robot(c3po)
    garage.park_robot(bb8)

    # Create procedures
    procedures = [
        Procedure(50, robots=[r2d2, bb8]),
        Procedure(60, robots=[r2d2, c3po]),
        Procedure(100, robots=[r2d2, c3po, bb8]),
        Procedure(150, robots=[bb8]),
        Procedure(200, robots=[r2d2])
    ]

    # Test the capacity of the created garage
    def test_garage(self):
        assert self.garage.capacity == 3

    # Test the robots actions and the manage
    # of the energy and happiness
    def test_robot_move(self):
        self.r2d2.move()
        assert self.r2d2.energy == 39 and self.r2d2.happiness == 19

    def test_robot_work(self):
        self.c3po.work()
        assert self.c3po.energy == 49 and self.c3po.happiness == 31

    def test_robot_hibernate(self):
        self.bb8.hibernate()
        assert self.bb8.happiness == 9 and self.bb8.energy == 46

    # Test that the parked robots are in the garage
    def test_robot_list(self):
        flag = True
        for i in self.garage.robots:
            print(i)
        assert flag == True
示例#6
0
 def test_right(self, mock_calc_right_transition, mock_is_within_boundary):
     mock_is_within_boundary.return_value = True
     mock_calc_right_transition.return_value = EAST
     test_robot = Robot()
     test_robot.place(1, 1, NORTH)
     test_robot.right()
     result = test_robot.report()
     self.assertEqual((1, 1, EAST), result)
示例#7
0
 def setup_class(self, tmpdir):
     # self.ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
     self.ROOT_DIR = tmpdir.strpath
     self.USER_CONFIG = self.ROOT_DIR + '/dockers/user_config.json'
     os.makedirs(self.ROOT_DIR + "/dockers")
     with open(self.USER_CONFIG, 'w') as f:
         f.write("{}")
     self.robot = Robot(root_dir=self.ROOT_DIR,
                        user_config=self.USER_CONFIG,
                        domain="tests.com")
     self.robot.domain = "tests.com"
示例#8
0
    def populate_data(self):
        self.state.garage = Garage(3)

        # Create the robots
        r2d2 = Robot("R2D2", 20, 40, 0, "Anakin")
        c3po = Robot("C3PO", 30, 50, 0, "Vader")
        bb8 = Robot("BB8", 10, 45, 0, "Rei")

        # Park the robots
        self.state.garage.park_robot(r2d2)
        self.state.garage.park_robot(c3po)
        self.state.garage.park_robot(bb8)

        # Create procedures
        self.state.procedures = [
            Procedure(50, robots=[r2d2, bb8]),
            Procedure(60, robots=[r2d2, c3po]),
            Procedure(100, robots=[r2d2, c3po, bb8]),
            Procedure(150, robots=[bb8]),
            Procedure(200, robots=[r2d2])
        ]
示例#9
0
def make_data(N, num_landmarks, world_size, measurement_range, motion_noise,
              measurement_noise, distance):

    # check if data has been made
    complete = False

    while not complete:

        data = []

        # make robot and landmarks
        r = Robot(world_size, measurement_range, motion_noise,
                  measurement_noise)
        r.make_landmarks(num_landmarks)
        seen = [False for row in range(num_landmarks)]

        # guess an initial motion
        orientation = random.random() * 2.0 * pi
        dx = cos(orientation) * distance
        dy = sin(orientation) * distance

        for k in range(N - 1):

            # collect sensor measurements in a list, Z
            Z = r.sense()

            # check off all landmarks that were observed
            for i in range(len(Z)):
                seen[Z[i][0]] = True

            # move
            while not r.move(dx, dy):
                # if we'd be leaving the robot world, pick instead a new direction
                orientation = random.random() * 2.0 * pi
                dx = cos(orientation) * distance
                dy = sin(orientation) * distance

            # collect/memorize all sensor and motion data
            data.append([Z, [dx, dy]])

        # we are done when all landmarks were observed; otherwise re-run
        complete = (sum(seen) == num_landmarks)

    print(' ')
    print('Landmarks: ', r.landmarks)
    print(r)

    return data
示例#10
0
    def get_robots_output(self):
        """ Given a set of commands and plateau dimensions parses this values
            run robot commands, and yield the current coordinates and
            orientations.

        """
        while self.commands:
            coordinates_and_orientation = self.commands.pop(0)
            coordinates = list(
                map(int,
                    coordinates_and_orientation.split(' ')[:2]))
            orientation = coordinates_and_orientation.split(' ')[-1]
            robot_commands = self.commands.pop(0)

            robot = Robot(coordinates, orientation, self.plateau_dimensions)
            [robot.run(command) for command in robot_commands]
            yield robot.get_coordinate_and_orientation_text()
示例#11
0
 def run_main(self):
     parsedargs = self.buildArgParser()
     input_file = parsedargs.input_file
     print(f'===== {input_file} =====')
     inst_file_processor = InstructionsFile(input_file)
     try:
         inst_file_processor.initialise_instructions()
         grid = Grid(inst_file_processor.grid_extents)
         for robot_instructions in inst_file_processor.next_instructions():
             robot = Robot()
             self.do_instructions(grid, robot, robot_instructions)
             print(str(robot))
         print()
     except ExceptionFileParseCritical as ex:
         print(ex)
         print(ex.path)
         if ex.line_num is not None:
             print(f'@{ex.line_num}: "{ex.line}"')
         print()
         exit(ex.code)
示例#12
0
    def create_robot():
        print("-> Create a robot")
        print("   ##############")

        name = input("Robot name: ")

        try:
            energy = int(input("Robot energy (range 0-100): "))
            while 0 > energy or energy > 100:
                print(
                    "-> ERROR: Energy has to be more than 0 and less than 100")
                energy = int(input("Robot energy (range 0-100): "))
        except ValueError:
            print("-> ERROR: Invalid energy value")
            return None

        try:
            happiness = int(input("Robot happiness (range 0-50): "))
            while 0 > happiness or happiness > 50:
                print("-> ERROR: Happiness has to be more than 0 and less "
                      "than 50")
                happiness = int(input("Robot happiness (range 0-50): "))
        except ValueError:
            print("-> ERROR: Invalid happiness value")
            return None

        try:
            procedure = int(input("Robot procedure time (in milliseconds): "))
            while procedure < 0:
                print("-> ERROR: Procedure time has to be more than 0")
                procedure = int(
                    input("Robot procedure time (in milliseconds): "))
        except ValueError:
            print("-> ERROR: Invalid procedure time")
            return None

        owner = input("Robot owner: ")

        return Robot(name, energy, happiness, procedure, owner)
示例#13
0
def test_sense():
    world_size = 10.0  # size of world (square)
    measurement_range = 5.0  # range at which we can sense landmarks
    motion_noise = 0.2  # noise in robot motion
    measurement_noise = 0.2  # noise in the measurements

    # instantiate a robot, r
    rob = Robot(world_size, measurement_range, motion_noise, measurement_noise)
    num_landmarks = 3
    rob.make_landmarks(num_landmarks)

    # print out our robot's exact location
    print(rob)

    # display the world including these landmarks
    display_world(int(world_size), [rob.x, rob.y], rob.landmarks)

    # print the locations of the landmarks
    print('Landmark locations [x,y]: ', rob.landmarks)

    measurements = rob.sense()
    assert len(measurements) == 3, "rob did not sense all 3 landmarks"
    print(measurements)
示例#14
0
 def test_read_instructions_one_robot_noloss(self):
     dir_name = self._create_dir()
     filepath = f'{dir_name}/allgood'
     afile = (f'{filepath}_0', '''5 3\n1 1 E\nRFRFRFRF\n''')
     with open(afile[0], 'a') as fl:
         fl.write(afile[1])
     inst_file_processor = InstructionsFile(afile[0])
     inst_file_processor.initialise_instructions()
     grid_extents = inst_file_processor.grid_extents
     self.assertEqual(grid_extents.coord_x, 5)
     self.assertEqual(grid_extents.coord_y, 3)
     grid = Grid(grid_extents)
     count = 0
     for robot_instruction in inst_file_processor.next_instructions():
         self.assertEqual(
             str(robot_instruction),
             '::Start[1,1,E] ::TurnRight ::MoveForward ::TurnRight ::MoveForward ::TurnRight ::MoveForward ::TurnRight ::MoveForward'
         )
         robot = Robot()
         for inst in robot_instruction.instruction_list:
             inst.do(grid, robot)
         self.assertEqual(str(robot), '1 1 E')
         count += 1
     self.assertEqual(count, 1)
示例#15
0
 def test_read_instructions_one_robot_getslost(self):
     dir_name = self._create_dir()
     filepath = f'{dir_name}/allgood'
     afile = (f'{filepath}_1', '''5 3\n3 2 N\nFRRFLLFFRRFLL\n''')
     with open(afile[0], 'a') as fl:
         fl.write(afile[1])
     inst_file_processor = InstructionsFile(afile[0])
     inst_file_processor.initialise_instructions()
     grid_extents = inst_file_processor.grid_extents
     self.assertEqual(grid_extents.coord_x, 5)
     self.assertEqual(grid_extents.coord_y, 3)
     grid = Grid(grid_extents)
     count = 0
     for robot_instruction in inst_file_processor.next_instructions():
         self.assertEqual(
             len(robot_instruction.instruction_list),
             14)  # 14 instructions (13 moves + 1 start instruction).
         self.assertEqual(
             str(robot_instruction),
             '::Start[3,2,N] ::MoveForward ::TurnRight ::TurnRight ::MoveForward ::TurnLeft ::TurnLeft ::MoveForward ::MoveForward ::TurnRight ::TurnRight ::MoveForward ::TurnLeft ::TurnLeft'
         )
         robot = Robot()
         for inst in robot_instruction.instruction_list[:
                                                        8]:  # First 8 instructions are good.
             inst.do(grid, robot)
         robot_instruction.instruction_list[8].do(
             grid, robot)  # Next instruction leads to robot being lost.
         self.assertEqual(str(robot), '3 3 N LOST')
         robot_instruction.instruction_list[9].do(grid, robot)
         robot_instruction.instruction_list[10].do(grid, robot)
         with self.assertRaises(Exception) as exception_context:
             robot_instruction.instruction_list[11].do(grid, robot)
         for inst in robot_instruction.instruction_list[12:]:
             inst.do(grid, robot)
         count += 1
     self.assertEqual(count, 1)
示例#16
0
Dis_crate = (1, 2, 3, 4)
Rot_crate = ('LEFT', 'RIGHT', 'RIGHT', 'LEFT')
STAGE_1_NODE_COUNT = {0: 3, 1: 2, 2: 2, 3: 1}
# Stage 2
Pos_cover = 1
Direct = [['RIGHT', 'RIGHT', 'LEFT'], ['LEFT', 'LEFT', 'LEFT'],
          ['RIGHT', 'LEFT', 'LEFT'], ['LEFT', 'RIGHT', 'LEFT']]
# Blue, yellow, green, red
# Stage 3
Pos_shipyard = 1

# Main
SPEED = 100
COLOURS = {2: "B", 3: "G", 4: "Y", 5: "R"}
current_colour = ""
ROBOT = Robot()
"""Methods in direct relation to path-finding / highest level of logic"""

# Stage 1


def backtrack_to_nearest_node(pos):
    ROBOT.follow_black_line_degrees(Dis_crate[pos], SPEED, -1)
    back_rotate = 'LEFT'
    if Rot_crate[pos] == 'LEFT' or pos == 2:
        back_rotate = 'RIGHT'
    ROBOT.turn(back_rotate)
    if x == 2:  # special case for transition between p2 and p3
        ROBOT.follow_until_next_node()
        ROBOT.turn('AROUND')
    else:
import threading
import time
from src.robot import Robot
import brickpi
import sys

#initialize the interface
interface = brickpi.Interface()
interface.initialize()
config = str(sys.argv[1])
Robot = Robot(interface, pid_config_file=config)

Robot.approach_object(30, 0)
time.sleep(0.5)

interface.terminate()
示例#18
0
 def test_no_initial_placement(self):
     test_robot = Robot()
     test_robot.move()
     result = test_robot.report()
     self.assertEqual((None, None, None), result)
示例#19
0
        parser = parse_args(**tools)
        args = parser.parse_args()

        if not args.actions:
            print("No action selected, exiting...")
            sys.exit(1)

        log.debug(args)

        tool_check()

        drrobot = Robot(root_dir=ROOT_DIR,
                        user_config=USER_CONFIG,
                        **tools,
                        dns=getattr(args, 'dns', None),
                        proxy=getattr(args, 'proxy', None),
                        domain=getattr(args, 'domain', None),
                        verbose=getattr(args, 'verbose'),
                        dbfile=getattr(args, 'dbfile'),
                        verify=getattr(args, 'verify', None))

        if not exists(join_abs(ROOT_DIR, "dbs")):
            makedirs(join_abs(ROOT_DIR, "dbs"))

        if getattr(args, 'domain', None):
            if not exists(join_abs(ROOT_DIR, "output", getattr(args,
                                                               'domain'))):
                makedirs(join_abs(ROOT_DIR, "output", getattr(args, 'domain')))

            if not exists(
                    join_abs(ROOT_DIR, "output", getattr(args, 'domain'),
示例#20
0
import threading
import time
from src.robot import Robot
import brickpi

#Initialize the interface
interface=brickpi.Interface()
interface.initialize()

Robot = Robot(interface, pid_config_file="carpet_config.json")

Robot.travel_straight(40)
time.sleep(5)
Robot.travel_straight(-40)
time.sleep(5)
Robot.rotate_left(90)
time.sleep(5)
Robot.rotate_right(90)

interface.terminate()
示例#21
0
'''
Test file for the robot.
'''
from src.robot import Robot
import threading
import time

port = '/dev/ttyACM0'  # default usb port
#port = '/dev/rfcomm0'       # default bluetooth port

ballbot = Robot(port)  #make a robot/ballbot
running = True  #set the running flag


# Function where the ballbot receives data
def ballbot_update():
    while running:
        ballbot.receive()
        #print(ballbot.x, ballbot.y, ballbot.z, ballbot.roll, ballbot.pitch, ballbot.yaw)
        time.sleep(0.05)


# Controller update
dt = 5


def controller_update():
    for i in range(0, dt):
        print(dt - i)
        time.sleep(1)
    ballbot.set_attitude_mode()  # go to attitude mode
import threading
import time
import sys
from src.robot import Robot
import brickpi

#Initialize the interface
interface=brickpi.Interface()
interface.initialize()
interface.startLogging("motor_position_1.log")

Robot = Robot(interface,'carpet_config.json')


Robot.interactive_mode()

interface.stopLogging()
interface.terminate()
示例#23
0
import sys
from src.grid import Grid
from src.robot import Robot
from src.cleaner_algorithm import dfs

if __name__ == '__main__':

    debug = False
    # To print all robot movement
    if len(sys.argv) > 1 and sys.argv[1].startswith('debug'):
        debug = True

    grid = Grid([
        [1, 0, 0, 0, 0, 0, 0, 1],
        [0, 0, 0, 1, 0, 0, 0, 0],
        [0, 2, 0, 0, 0, 0, 1, 0],
        [2, 2, 2, 0, 2, 2, 2, 2],
        [0, 1, 0, 3, 0, 1, 0, 1],
    ], debug)
    robot = Robot(grid, debug)

    grid.print_room()

    # -------------------
    dfs(robot)

    # ----------------
    grid.print_room()
示例#24
0
 def test_place(self, mock_is_within_boundary):
     mock_is_within_boundary.return_value = True
     test_robot = Robot()
     test_robot.place(1, 1, SOUTH)
     result = test_robot.report()
     self.assertEqual((1, 1, SOUTH), result)
示例#25
0
       [168,84,"F"],
       [210,84,"G"],
       [210,0,"H"]]

POINTS = [(84,30),
          (180,30),
          (180,53),
          (138,54),
          (138,168),
          (114,168),
          (114,84),
          (84,84),
          (84,30),
          (0,0)]

Robot = Robot(interface,
              pid_config_file="carpet_config.json",
              Map=MAP,
              mcl=True,
              x=20,
              y=20,
              mode="continuous",
              theta=90,
              threading=True
              )

Robot.interactive_mode()

interface.stopLogging()
interface.terminate()
示例#26
0
 def __init__(self, **kwargs):
     self.robot = Robot(**kwargs)
     self.state = CmdUI.STATE_CHAT
     self.buffer = None
     self.output = []
示例#27
0
MAP = [[0, 0, "O"], [0, 168, "A"], [84, 168, "B"], [84, 126, "C"],
       [84, 210, "D"], [168, 210, "E"], [168, 84, "F"], [210, 84, "G"],
       [210, 0, "H"]]

POINTS = [(86, 30), (180, 30), (180, 53), (138, 54), (138, 168), (114, 168),
          (114, 84), (86, 84), (86, 30)]

Canvas = Canvas()
Map = Map(Canvas)

Robot = Robot(interface,
              pid_config_file="carpet_config.json",
              Map=MAP,
              mcl=True,
              x=86,
              y=30,
              mode="continuous",
              theta=0,
              threading=True,
              canvas=Canvas)

Map.add_wall((0, 0, 0, 168))  # a
Map.add_wall((0, 168, 84, 168))  # b
Map.add_wall((84, 126, 84, 210))  # c
Map.add_wall((84, 210, 168, 210))  # d
Map.add_wall((168, 210, 168, 84))  # e
Map.add_wall((168, 84, 210, 84))  # f
Map.add_wall((210, 84, 210, 0))  # g
Map.add_wall((210, 0, 0, 0))  # h
Map.draw()
示例#28
0
import threading
import time
from src.robot import Robot
import brickpi

#Initialize the interface
interface = brickpi.Interface()
interface.initialize()

Robot = Robot(interface, pid_config_file="paper_config.json")
for i in range(4):
    time.sleep(1)
    Robot.travel_straight(40)
    time.sleep(1)
    Robot.rotate_left(90)

interface.terminate()
示例#29
0
    def add_robot(self, genome, name="Robot"):

        self.robot_list.append(Robot(self, genome, name))
示例#30
0
import threading
import time
import sys
from src.robot import Robot
import brickpi

#Initialize the interface
interface=brickpi.Interface()
interface.initialize()
interface.startLogging("motor_position_1.log")

Robot = Robot(interface,'paper_config.json')


Robot.set_robot_pose(float(sys.argv[1]))

interface.stopLogging()
interface.terminate()