def test_a_star_search(self):
        print("Starting A* search test")
        print("---------------------------------------------")
        with TimeoutAlarm(
                60,
                error_message=
                "A* Search and Uniform Cost Search cannot find the solution within 60s"
        ):
            puzzle = EightPuzzleState([3, 0, 5, 6, 2, 4, 7, 8, 1])
            problem = PuzzleSearchProblem(puzzle)
            path_a_start, step_a_star = search.a_start_search(problem)
            path_ucs, step_ucs = search.uniform_cost_search(problem)
            print("Test A* on: \n")
            print(puzzle)
            self.print_result("A*", step_a_star,
                              problem.get_costs(path_a_start), path_a_start)

            curr = puzzle
            for a in path_a_start:
                curr = curr.next_state(a)
            self.assertTrue(curr.is_goal(), "The final state is not goal test")
            self.assertEqual(problem.get_costs(path_a_start), 43,
                             "The answer may not the optimal one")
            self.assertLessEqual(
                step_a_star, step_ucs,
                "The A* steps should be less or equal compared with UCS")
        print("=============================================")
Ejemplo n.º 2
0
def main():
    os.mkdir('./csv')
    fname = "benchmarks.csv"  # CSV with the averages
    with open('csv/' + fname, 'w+') as csvwritefile:
        writer = csv.writer(csvwritefile, quoting=csv.QUOTE_MINIMAL)
        writer.writerow([
            'Algorithm', 'Heuristics', 'w1', 'w2', 'Run Time', 'Path Length',
            'Cost/Optimal', 'Nodes Expanded', 'Memory Used'
        ])

    s_paths = np.zeros([5, 10])
    a_star_admissible = partial(a_star, heuristic=manhattan_distance_a)
    for name, hs, w1, w2, a in algorithms():
        for map_num in range(1, 6):
            for sg_pair in range(0, 10):
                (grid, start, goal) = input_file(map_path(map_num, sg_pair))
                s_path = s_paths[map_num - 1, sg_pair]
                if s_path == 0:  # Lazily create shortest paths
                    for f, g, h, bp, s in uniform_cost_search(
                            grid, grid[start], grid[goal]):
                        pass
                    s_paths[map_num - 1,
                            sg_pair] = s_path = path_cost(grid, bp, s)
                algo = partial(a, grid, grid[start], grid[goal])

                print("Forking to run {0}".format(name))
                newpid = os.fork(
                )  # Fork the process so we get a separate memory footprint
                if newpid is 0:
                    benchmarks = run_algo(algo, grid, s_path)
                    with open(
                            'csv/' + name + str(hs) + str(w1) + str(w2) +
                            '.csv', 'a') as csvfile:
                        writer = csv.writer(csvfile,
                                            delimiter=' ',
                                            quotechar='|',
                                            quoting=csv.QUOTE_MINIMAL)
                        writer.writerow(list(benchmarks))
                    os._exit(0)
                else:
                    os.wait4(newpid, 0)

        with open('csv/' + fname, 'a') as csvwritefile:
            with open('csv/' + name + str(hs) + str(w1) + str(w2) + '.csv',
                      'r') as csvreadfile:
                # reader = csv.reader(csvreadfile, quoting=csv.QUOTE_MINIMAL)
                writer = csv.writer(csvwritefile, quoting=csv.QUOTE_MINIMAL)
                m = np.genfromtxt(csvreadfile, dtype='float', delimiter=' ')
                # m = np.array([r for r in reader])
                row = [name, hs, w1, w2]
                for c in m.T:
                    row.append(np.mean(c))
                writer.writerow(row)
Ejemplo n.º 3
0
    def plan(self, grid_2D, agent_position, goal_position, save_maze=True):

        # current_position = {'z': int(self.zpos - self.origin_coord['z']), 'x': int(self.xpos - self.origin_coord['x'])}
        # print('current_position', current_position)

        frontier = []

        maze_map_dict = {}
        for z in range(agent_position[0] - self.scanning_range,
                       agent_position[0] + self.scanning_range +
                       1):  # 0, self.envsize):
            for x in range(agent_position[1] - self.scanning_range,
                           agent_position[1] + self.scanning_range + 1):
                if x >= 0 and x < self.envsize and z >= 0 and z < self.envsize:
                    item = grid_2D[z][x]
                    # if maze_map_dict.get(self.state_to_string(z, x)) is None:
                    #     maze_map_dict[self.state_to_string(z, x)] = set()
                    # maze_map_dict[self.state_to_string(z, x)].add(self.get_passable_neighbours(grid_2D, z, x))        import ipdb; ipdb.set_trace()
                    # import ipdb; ipdb.set_trace()

                    if self.is_passable(item):
                        maze_map_dict[self.state_to_string(
                            z,
                            x)] = self.get_passable_neighbours(grid_2D, z, x)

        print(maze_map_dict)

        print(maze_map_dict[self.state_to_string(*(agent_position))])
        print(maze_map_dict[self.state_to_string(*(goal_position))])
        # import ipdb; ipdb.set_trace()

        maze_map = search.UndirectedGraph(maze_map_dict)

        # initial_position = (self.range_z//2, self.range_x//2)

        maze_problem = search.GraphProblem(
            self.state_to_string(*(agent_position)),
            self.state_to_string(*(goal_position)), maze_map)
        # print('maze_map', maze_map)
        solution_node = search.uniform_cost_search(problem=maze_problem,
                                                   display=True)  #, h=None)
        print('solution_node', solution_node)

        if solution_node is not None:
            solution_path = [solution_node.state]
            current_node = solution_node.parent
            solution_path.append(current_node.state)
            while current_node.state != maze_problem.initial:
                current_node = current_node.parent
                solution_path.append(current_node.state)
        return solution_path
Ejemplo n.º 4
0
def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("environment", help="list of roads and info")
    parser.add_argument("query", help="initial and final locations")
    parser.add_argument("output", help="file to output results")
    args = parser.parse_args()

    f1 = file_read(args.environment)
    f2 = file_read(args.query)

    outFile = os.path.join(os.path.dirname(sys.argv[1]), args.output)

    f3 = open(outFile, "w")

    #     f1 = file_read(environmentFile)
    #     f2 = file_read(queryFile)
    #     f3 = open(os.path.join(cwd, outputFile), "w")

    #String preprocessing done
    t1 = time.time()

    junction = junction_read(f1)
    queries = queries_read(f2)

    #Search algorithm starts here
    for q in queries:

        cost, path = search.uniform_cost_search(junction, q)

        if path == None:

            f3.write(str('no-path' + '\n'))

        else:

            f3.write(str(cost) + ' ; ')

            for i in range(len(path) - 1):
                f3.write(str(path[i]) + ' - ')

            f3.write(str(path[i + 1]) + '\n')

    t2 = time.time()
    #     f3.write(str(['Time taken: ', float(t2-t1) * 1000., 'ms']))
    #     print('Time taken: ', float(t2-t1) * 1000., 'ms')

    sys.stdout.write('\nOutput file stored as ' + str(outFile) + '\n')

    return 0
Ejemplo n.º 5
0
def main():
    """Default function to be called when the program executes."""

    # Create an instance of the Search class with arguments from argparse
    searcher = Search(start, stop, args.grid)

    # Return the correct searching algorithm for a given specification
    if args.alg == 'bfs':
        search = aima.breadth_first_search(searcher)
    elif args.alg == 'ucs':
        search = aima.uniform_cost_search(searcher)
    else:
        search = aima.astar_search(searcher)
    return search.path()
    def test_unit_cost_search(self):
        print("Starting uniform cost search test"
              "If it cannot finish within 30s, "
              "please kill the job and review your code")
        print("---------------------------------------------")
        puzzle = EightPuzzleState([3, 0, 5, 6, 2, 4, 7, 8, 1])
        problem = PuzzleSearchProblem(puzzle)
        path, step = search.uniform_cost_search(problem)
        print("Test UCS on: \n")
        print(puzzle)
        self.print_result("UCS", step, problem.get_costs(path), path)

        curr = puzzle
        for a in path:
            curr = curr.next_state(a)
        self.assertTrue(curr.is_goal(), "The final state is not goal test")
        self.assertEqual(problem.get_costs(path), 43,
                         "The answer may not the optimal one")
        print("=============================================")
Ejemplo n.º 7
0
    def test_unit_cost_search(self):
        print("Starting uniform cost search test")
        print("---------------------------------------------")
        with Timer(30,
                   error_message=
                   "Uniform Cost Search cannot find the solution within 30s"):
            puzzle = EightPuzzleState([3, 0, 5, 6, 2, 4, 7, 8, 1])
            problem = PuzzleSearchProblem(puzzle)
            path, step = search.uniform_cost_search(problem)
            print("Test UCS on: \n")
            print(puzzle)
            self.print_result("UCS", step, problem.get_costs(path), path)

            curr = puzzle
            for a in path:
                curr = curr.next_state(a)
            self.assertTrue(curr.is_goal(), "The final state is not goal test")
            self.assertEqual(problem.get_costs(path), 43,
                             "The answer may not the optimal one")
        print("=============================================")
    def test_a_star_search(self):
        print("Starting A* search test, "
              "If it cannot finish within 60s, "
              "please kill the job and review your code")
        print("---------------------------------------------")
        puzzle = EightPuzzleState([3, 0, 5, 6, 2, 4, 7, 8, 1])
        problem = PuzzleSearchProblem(puzzle)
        path_a_start, step_a_star = search.a_start_search(problem)
        path_ucs, step_ucs = search.uniform_cost_search(problem)
        print("Test A* on: \n")
        print(puzzle)
        self.print_result("A*", step_a_star, problem.get_costs(path_a_start),
                          path_a_start)

        curr = puzzle
        for a in path_a_start:
            curr = curr.next_state(a)
        self.assertTrue(curr.is_goal(), "The final state is not goal test")
        self.assertEqual(problem.get_costs(path_a_start), 43,
                         "The answer may not the optimal one")
        self.assertLessEqual(
            step_a_star, step_ucs,
            "The A* steps should be less or equal compared with UCS")
        print("=============================================")
Ejemplo n.º 9
0
 
 print
 print '-' * 50
 print "Running BREADTH-FIRST-TREE-SEARCH"
 print '-' * 50
 
 bfts = breadth_first_search(ep, search_type=uninformed_tree_search)
 
 print "Solution", bfts.solution()
 
 print
 print '-' * 50
 print "Running UNIFORM-COST-TREE-SEARCH"
 print '-' * 50
 
 ucts = uniform_cost_search(ep, search_type=best_first_tree_search)
 
 print "Solution", ucts.solution()
 
 print
 print '-' * 50
 print "Running GREEDY-BEST-FIRST-TREE-SEARCH USING # MISPLACED TILES HEURISTIC"
 print '-' * 50
 
 gbfts = greedy_best_first_search(ep, misplaced_tiles_heuristic, search_type=best_first_tree_search)
 
 print "Solution", gbfts.solution()
 
 print
 print '-' * 50
 print "Running A*-TREE-SEARCH USING # MISPLACED TILES HEURISTIC"
Ejemplo n.º 10
0
    print('-' * 50)
    print("Q2: BREADTH-FIRST-TREE-SEARCH")
    print('-' * 50)

    bfts = breadth_first_search(travel_problem, search_type=uninformed_tree_search)

    print("Solution", bfts.solution())

    print()
    print('-' * 50)
    print("Q3: UNIFORM-COST-GRAPH-SEARCH")
    print('-' * 50)

    #todo()  # Something like ucs = uniform_cost_search(travel_problem, search_type=...)
    #calling uniform cost search function
    ucs = uniform_cost_search(travel_problem, search_type=best_first_tree_search)
    print("Solution", ucs.solution())

    print()
    print('-' * 50)
    print("Q4: GREEDY-BEST-FIRST-TREE-SEARCH")
    print('-' * 50)

    gbfs = greedy_best_first_search(travel_problem, city_h, search_type=best_first_tree_search)

    print("Solution", gbfs.solution())

    print()
    print('-' * 50)
    print("Q5: A*-TREE-SEARCH")
    print('-' * 50)
Ejemplo n.º 11
0
'''
Created on Oct 2, 2016

@author: farida
'''
from search import romania_map, GraphProblem, breadth_first_tree_search,\
    depth_first_graph_search, iterative_deepening_search,\
    recursive_best_first_search, breadth_first_search, uniform_cost_search,\
    depth_limited_search

print("Romania Locations:")
print("==================")
print(romania_map.locations)

print("Romania Map:")
print("=============")
print(romania_map.dict)

romania_problem = GraphProblem('Arad', 'Bucharest', romania_map)

print("Search Algorithms Results:")
print("==========================")
print(breadth_first_search(romania_problem).solution())
#print(breadth_first_search(romania_problem).path_cost)
print(uniform_cost_search(romania_problem).solution())
#print(uniform_cost_search(romania_problem).path_cost)
print(depth_first_graph_search(romania_problem).solution())
print(depth_first_graph_search(romania_problem).path_cost)
Ejemplo n.º 12
0
import search
from graph import Graph

if __name__ == "__main__":
    # Setting graph we initiated to search class...
    graph = Graph()
    search.graph = graph

    search.depth_first_search()
    search.breath_first_search()
    search.iterative_deepening_search()
    search.uniform_cost_search()
    search.greedy_best_first_search()
    search.a_star_search()
Ejemplo n.º 13
0
        sorted_list = sorted(new_state, key=lambda x: [x[0], x[1]])
        return tuple(sorted_list)

    def goal_test(self, state):
        if len(state) < 1:
            return True
        return False

    def path_cost(self, c, state1, action, state2):
        diff = len(state2) - len(state1)
        return c + diff

    def is_inbounds(self, location):
        '''Checks to make sure that the location is inbounds'''
        x,y = location
        return not (x < 0 or x >= self.size or y < 0 or y >= self.size)

if __name__ == "__main__":
    initial_state = tuple([(0,0), (1,1), (2,0), (3,3), (4,2), (4,4)])
    size = 5

    # initial_state = [(0,3), (1,2), (1,4), (2,3), (3,7), (4,6), (4,3), (5,2), (5,4), (6,3), (5,9), (6,8), (6,9), (7,8), (7,10), (8,0), (8,5), (8,9), (9,1), (9,4), (9,6), (10,0), (10,5)]
    initial_state = sorted(initial_state, key=lambda x: [x[0], x[1]])
    initial_state = tuple(initial_state)

    problem = CleanBoardProblem(initial_state, [], size)
    # problem.result(initial_state, (0,1))

    problem = CleanBoardProblem(initial_state, [], size)
    goal1 = uniform_cost_search(problem)
Ejemplo n.º 14
0
    algo = sys.argv[2]

    map_dict, heuristic, start, goal = parse(input_file)
    problem = MapProblem(start, goal, map_dict, heuristic)
    if algo == 'BFTS':
        goal_node = breadth_first_tree_search(problem)
    elif algo == 'DFTS':
        goal_node = depth_first_tree_search(problem)
    elif algo == 'DFGS':
        goal_node = depth_first_graph_search(problem)
    elif algo == 'BFGS':
        goal_node = breadth_first_graph_search(problem)
    elif algo == 'UCTS':
        goal_node = uniform_cost_tree_search(problem)
    elif algo == 'UCGS':
        goal_node = uniform_cost_search(problem)
    elif algo == 'GBFTS':
        goal_node = greedy_best_first_tree_search(problem)
    elif algo == 'GBFGS':
        goal_node = greedy_best_first_graph_search(problem, problem.h)
    elif algo == 'ASTS':
        goal_node = astar_tree_search(problem, h=problem.h)
    elif algo == 'ASGS':
        goal_node = astar_search(problem, h=problem.h)
    else:
        goal_node = None

    # Do not change the code below.
    if goal_node is not None:
        print("Solution path", goal_node.solution())
        print("Solution cost", goal_node.path_cost)
Ejemplo n.º 15
0
print('Testing blocked')
grid = maps.gen_blocked(grid)
i = 0
while i < 10:
    print('Start/Goal Pair: ' + str(i))
    g = None
    h = None
    parent = None
    curr = None

    try:
        print('Testing start_goal')
        (start, goal) = maps.gen_start_goal_pair(grid)

        print('Testing Uniform Cost Search')
        ucs = uniform_cost_search(grid, start, goal)
        for (f, g, h, parent, curr) in ucs:
            pass
        print(g[goal])
        # output_image(grid, "ucs.png", start, goal, path(parent, curr))

        print('Testing A* Search')
        astar = a_star(grid, start, goal, manhattan_distance_a)
        for (f, g, h, parent, curr) in astar:
            pass
        print(g[goal])
        # output_image(grid, "a_star.png", start, goal, path(parent, curr))

        print('Testing A* Weighted Search')
        astar_w = a_star(grid, start, goal, diagonal_distance_n, w=2)
        for (f, g, h, parent, curr) in astar_w:
Ejemplo n.º 16
0
def on_step():
    global inp
    robot.count += 1
    inp = io.SensorInput(cheat=True)


    # discretize sonar readings
    # each element in discrete_sonars is a tuple (d, cells)
    # d is the distance measured by the sonar
    # cells is a list of grid cells (r,c) between the sonar and the point d meters away
    discrete_sonars = []
    for (sonar_pose, distance) in zip(sonarDist.sonar_poses,inp.sonars):
        if NOISE_ON:
            distance = noiseModel.noisify(distance, grid_square_size)
        if distance >= 5:
            sensor_indices = robot.map.point_to_indices(inp.odometry.transformPose(sonar_pose).point())
            hit_indices = robot.map.point_to_indices(sonarDist.sonar_hit(1, sonar_pose, inp.odometry))
            ray = util.line_indices(sensor_indices, hit_indices)
            discrete_sonars.append((distance, ray))
            continue
        sensor_indices = robot.map.point_to_indices(inp.odometry.transformPose(sonar_pose).point())
        hit_indices = robot.map.point_to_indices(sonarDist.sonar_hit(distance, sonar_pose, inp.odometry))
        ray = util.line_indices(sensor_indices, hit_indices)
        discrete_sonars.append((distance, ray))


    # figure out where robot is
    start_point = inp.odometry.point()
    startCell = robot.map.point_to_indices(start_point)

    def plan_wont_work():
        for point in robot.plan:
            if not robot.map.is_passable(point):
                return True
        return False

    # if necessary, make new plan
    if robot.plan is None or plan_wont_work(): #discrete_sonars[3][0] < 0.3: ###### or if the robot is about to crash into a wall
        print('REPLANNING')
        robot.plan = search.uniform_cost_search(robot.successors,
                              robot.map.point_to_indices(inp.odometry.point()),
                              lambda x: x == robot.goalIndices,
                              lambda x: 0)


    # make the path less jittery

    #print(robot.plan)
    to_remove = []
    if robot.plan is not None:
        for i in range(len(robot.plan)-2):
            line = util.LineSeg(util.Point(robot.plan[i][0], robot.plan[i][1]), util.Point(robot.plan[i+1][0], robot.plan[i+1][1]))
            if line.dist_to_point(util.Point(robot.plan[i+2][0], robot.plan[i+2][1])) < 0.1:
                to_remove.append(robot.plan[i+1])
    print(to_remove)
    for i in to_remove:
        robot.plan.remove(i)

    #print(robot.plan)
    #print()

    # graphics (draw robot's plan, robot's location, goal_point)
    # do not change this block
    for w in robot.windows:
        w.redraw_world()
    robot.windows[-1].mark_cells(robot.plan,'blue')
    robot.windows[-1].mark_cell(robot.map.point_to_indices(inp.odometry.point()),'gold')
    robot.windows[-1].mark_cell(robot.map.point_to_indices(goal_point),'green')


    # update map
    for (d,cells) in discrete_sonars:
        #print(cells)
        if d < 5:
            robot.map.sonar_hit(cells[-1])
        for i in range(len(cells)-1):
            robot.map.sonar_pass(cells[i])


    # if we are within 0.1m of the goal point, we are done!
    if start_point.distance(goal_point) <= 0.1:
        io.Action(fvel=0,rvel=0).execute()
        code = checkoff.generate_code(globals())
        if isinstance(code, bytes):
            code = code.decode()
        raise Exception('Goal Reached!\n\n%s' % code)

    # otherwise, figure out where to go, and drive there
    destination_point = robot.map.indices_to_point(robot.plan[0])
    while start_point.isNear(destination_point,0.1) and len(robot.plan)>1:
        robot.plan.pop(0)
        destination_point = robot.map.indices_to_point(robot.plan[0])

    currentAngle = inp.odometry.theta
    angleDiff = start_point.angleTo(destination_point)-currentAngle
    angleDiff = util.fix_angle_plus_minus_pi(angleDiff)
    fv = rv = 0
    if start_point.distance(destination_point) > 0.1:
        if abs(angleDiff) > 0.1:
            rv = 4*angleDiff
        else:
            fv = 4*start_point.distance(destination_point)
    io.set_forward(fv)
    io.set_rotational(rv)


    # render the drawing windows
    # do not change this block
    for w in robot.windows:
        w.render()
Ejemplo n.º 17
0
    def actions(self, state):
        acts = []
        acts.extend(i for i in range(4) if state[4]==state[i])
        acts.extend((i,j) for i in range(4) for j in range(4)\
                    if i<j and state[i]==state[j] and state[j]==state[4])
        return acts

    def result(self, state, action):
        ps = list(state)
        if isinstance(action,int):
            ps[action] = not ps[action]
        else:
            ps[action[0]] = not ps[action[0]]
            ps[action[1]] = not ps[action[1]]
        ps[4] = not ps[4]
        return tuple(ps)

    def path_cost(self, c, state1, action, state2):
        if isinstance(action, int):
            return c+TIME[action]
        else:
            return c+TIME[action[1]]

    def value(self, state):
        """we have no good heuristics"""
        return 0

if __name__ == "__main__":
    t = Torch()
    print(uniform_cost_search(t).solution())
Ejemplo n.º 18
0
'''
from search import romania_map, GraphProblem, breadth_first_tree_search,\
    depth_first_graph_search, iterative_deepening_search,\
    recursive_best_first_search, breadth_first_search, uniform_cost_search,\
    depth_limited_search


print("Romania Locations:")
print("==================")
print(romania_map.locations)

print("Romania Map:")
print("=============")
print(romania_map.dict)

romania_problem = GraphProblem('Arad', 'Bucharest', romania_map)

print("Search Algorithms Results:")
print("==========================")
print(breadth_first_search(romania_problem).solution())
#print(breadth_first_search(romania_problem).path_cost)
print(uniform_cost_search(romania_problem).solution())
#print(uniform_cost_search(romania_problem).path_cost)
print(depth_first_graph_search(romania_problem).solution())
print(depth_first_graph_search(romania_problem).path_cost)





Ejemplo n.º 19
0
    print()
    print('-' * 50)
    print("Running BREADTH-FIRST-TREE-SEARCH")
    print('-' * 50)

    bfts = breadth_first_search(ep, search_type=uninformed_tree_search)

    print("Solution", bfts.solution())

    print()
    print('-' * 50)
    print("Running UNIFORM-COST-TREE-SEARCH")
    print('-' * 50)

    ucts = uniform_cost_search(ep, search_type=best_first_tree_search)

    print("Solution", ucts.solution())

    print()
    print('-' * 50)
    print(
        "Running GREEDY-BEST-FIRST-TREE-SEARCH USING # MISPLACED TILES HEURISTIC"
    )
    print('-' * 50)

    gbfts = greedy_best_first_search(ep,
                                     misplaced_tiles_heuristic,
                                     search_type=best_first_tree_search)

    print("Solution", gbfts.solution())
Ejemplo n.º 20
0
     elif node.state == 'F':
         return 10
     elif node.state == 'G':
         return 0
     elif node.state == 'S':
         return 8
 
 travel_problem = TravelProblem('S', 'G', city_map)
 
     
 print
 print '-' * 50
 print "Running UNIFORM-COST-GRAPH-SEARCH"
 print '-' * 50
 
 ucs = uniform_cost_search(travel_problem, search_type=best_first_graph_search)
 
 print "Solution", ucs.solution()
 
 print
 print '-' * 50
 print "Running GREEDY-BEST-FIRST-TREE-SEARCH"
 print '-' * 50
 
 gbfs = greedy_best_first_search(travel_problem, city_h, search_type=best_first_tree_search)
 
 print "Solution", gbfs.solution()
 
    
 print
 print '-' * 50