Пример #1
0
def question6():
    maze_dimension = 200
    n = 50
    probability = [0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4]
    manhattan_avg = []
    euclid_avg = []
    for p in probability:

        manhattan_nodes = 0
        euclid_nodes = 0

        for count in range(n):

            maze = maze_generator(maze_dimension, p)
            expanded_nodes3 = a_star(maze, "euclid", display=False)[1]
            expanded_nodes4 = a_star(maze, "manhattan", display=False)[1]
            manhattan_nodes = manhattan_nodes + len(expanded_nodes4)
            euclid_nodes = euclid_nodes + len(expanded_nodes3)

        manhattan_avg.append(manhattan_nodes / n)
        euclid_avg.append(euclid_nodes / n)

    plt.plot(probability, manhattan_avg, label="MANHATTAN")
    plt.plot(probability, euclid_avg, label="EUCLID")
    plt.ylabel('Nodes Expanded')
    plt.xlabel('Probability (p)')
    plt.legend()
    plt.show()
Пример #2
0
def question2(dim=100, p=0.2):
    sf = 0
    while not (sf):
        maze = maze_generator(dim, p)
        sf, expanded_nodes1, final_path1, fringe1 = a_star(maze, "manhattan")

    sf, expanded_nodes1, final_path1, fringe1 = depth_first_search(maze, True)
    sf, expanded_nodes2, final_path, fringe2 = a_star(maze, "euclid", True)
    sf, expanded_nodes3, final_path, fringe3 = a_star(maze, "manhattan", True)
    sf, expanded_nodes4, final_path1, fringe4 = breadth_first_search(
        maze, True)
Пример #3
0
def question1_question3(n):

    # This function calculates the running times for different dimensions for all p
    # for each p for each dim, the function takes an average of n mazes
    # The output is a dictionary of the form {p=0.1:{dim=500:{"dfs":(time_avg=20s,count of successful paths=a<n)}}}
    # The dictionary is stored in the file data/q1,3.pickle

    final_dict={}
    for p in [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]:
        stats={}
        for dim in np.arange(7000,15000,100):
                #int(input("Enter the dimension for maze : \n"))
                dfs_times=[]
                bfs_times=[]
                a_euclid_times=[]
                a_manhattan_times=[]
                dfs_count=0
                bfs_count=0
                a_euclid_count=0
                a_manhattan_count=0
                for rep in range(n):
                    maze = maze_generator(dim, p)
                    t=time()
                    dfs_count+=depth_first_search(maze,display=False)
                    dfs_times.append(time()-t)

                    t=time()
                    a_euclid_count+=a_star(maze,"euclid",display=False)
                    a_euclid_times.append(time()-t)

                    t=time()
                    a_manhattan_count+=a_star(maze,"manhattan", display=False)
                    a_manhattan_times.append(time()-t)

                    t=time()
                    bfs_count+=breadth_first_search(maze,display=False)
                    bfs_times.append(time()-t)


                dfs_avg=np.mean(dfs_times)
                bfs_avg=np.mean(bfs_times)
                a_euclid_avg=np.mean(a_euclid_times)
                a_manhattan_avg=np.mean(a_manhattan_times)
                stats[dim]={"dfs":(dfs_avg,dfs_count), "bfs":(bfs_avg,bfs_count),
                     "a_euclid":(a_euclid_avg,a_euclid_count), "a_manhattan":(a_manhattan_avg, a_manhattan_count) }
        final_dict[p]=stats
    print(final_dict)
    with open("data/q1,3.pickle","wb+") as f:
        pickle.dump(final_dict,f)
Пример #4
0
def question3(dim=200):
    P = list(np.arange(0, 1.01, 0.05))
    trials = 1000
    success_avg = []
    for p in P:
        count = 0
        for i in range(trials):
            sys.stdout.write("\r p: %f rep: %f" % (p, i))
            maze = maze_generator(dim, p)
            if p < 0.1:
                sf, en, path = depth_first_search(maze, display=False)
            elif p >= 0.5:
                sf, en, path = breadth_first_search(maze, display=False)
            else:
                sf, en, path = a_star(maze, "euclid", display=False)
            count += sf
        success_avg.append(count / trials)

    path = "figs/graphs/q3/"
    os.makedirs(path, exist_ok=True)
    figno = 0
    plt.figure(figno)
    plt.plot(P, success_avg)
    plt.xlabel("P")
    plt.ylabel("Probability of there existing a path to the goal")
    plt.title("Question 3")
    plt.savefig(path + "p vs success_prob.jpg")
Пример #5
0
    def make_move(self):
        if is_mixed() is False:  # use A star
            global device
            move = a_star(self.checkers, ai_terminal, human.checkers)

            target = move[0]
            new = move[1]
            print("target, new:", target.pos, new.pos)

            pygame.draw.circle(screen, white, target.pos, 20, 0)
            pygame.draw.circle(screen, black, target.pos, 20, 1)
            pygame.draw.circle(screen, blue, new.pos, 20, 0)
            for i in range(10):
                if self.checkers[i].pos == target.pos:
                    self.checkers[i] = new
            print("ai has made a a_star move")
        else:  # use minimax, return the checker object that will be moved (target), and the new checker object (new) or position
            move = alpha_beta(self.checkers, ai_terminal, human_terminal,
                              human.checkers)
            target = move[0]
            new = move[1]
            print("target, new:", target.pos, new.pos)

            pygame.draw.circle(screen, white, target.pos, 20, 0)
            pygame.draw.circle(screen, black, target.pos, 20, 1)
            pygame.draw.circle(screen, blue, new.pos, 20, 0)
            for i in range(10):
                if self.checkers[i].pos == target.pos:
                    self.checkers[i] = new
            print("ai has made a minimax move")

        return target.pos, new.pos
Пример #6
0
def launch_game(surface):
    grid = Grid(SIZE, SIZE, CELL_SIZE)
    grid.create()

    beginning = None
    destination = None

    algo_kickoff = False
    over = False
    while not over:

        grid.draw(surface)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                over = True

            if algo_kickoff:
                continue

            if pygame.mouse.get_pressed(3)[0]:  # left click
                pos = pygame.mouse.get_pos()
                node = grid.get_mouse_pos(pos)
                if not beginning:
                    node.set_beginning()
                    beginning = node
                elif not destination and node != beginning:
                    node.set_destination()
                    destination = node
                elif node != beginning and node != destination:
                    node.set_wall()

            elif pygame.mouse.get_pressed(3)[2]:  # right click
                pos = pygame.mouse.get_pos()
                node = grid.get_mouse_pos(pos)
                node.set_free()

                if node == beginning:
                    beginning = None
                if node == destination:
                    destination = None

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN and not algo_kickoff:
                    algo_kickoff = True
                    a_star(screen, grid, beginning, destination)
Пример #7
0
def main():  #{
    opcao = 0

    while opcao != 5:
        print('1 - Quarto')
        print('2 - Banheiro')
        print('3 - Sala')
        print('4 - Cozinha')
        print('5 - Sair')
        print()
        opcao = int(input('Opção: '))

        if opcao == 1:
            a, b = 36, 11
        elif opcao == 2:
            a, b = 42, 26
        elif opcao == 3:
            a, b = 10, 22
        elif opcao == 4:
            a, b = 13, 6
        elif opcao == 0:
            a = int(input('a = '))
            b = int(input('b = '))
        elif opcao == 5:
            print("\n" * 2)
            print('Saindo.')
            print("\n" * 2)
            break
        elif opcao != 5 and opcao != 4 and opcao != 3 and opcao != 2 and opcao != 1 and opcao != 0:
            print("\n")
            print('****OPÇÃO INVÁLIDA!!!****')
            print("\n")
            continue

        start, end = (0, 24), (a, b)
        veio_de, custo_total = a_star(planta, start, end)
        print("\n" * 3)
        mostrar_grid(planta)
        print("\n" * 3)
        mostrar_grid(planta,
                     largura=2,
                     aponta_para=veio_de,
                     inicio=start,
                     final=end)
        print("\n" * 3)
        mostrar_grid(planta,
                     largura=3,
                     numero=custo_total,
                     inicio=start,
                     final=end)
        print("\n" * 3)
        mostrar_grid(planta,
                     largura=2,
                     caminho=reconstruir_caminho(veio_de,
                                                 inicio=start,
                                                 final=end))
        print()
Пример #8
0
def fitness_function(maze, algo, fitness_func):
    if algo == "BFS":
        sf, expanded, path, fringe = breadth_first_search(maze, display=False)
    elif algo == "DFS":
        sf, expanded, path, fringe = depth_first_search(maze, display=False)
    elif algo == "Astar-euclidean":
        sf, expanded, path, fringe = a_star(maze, "euclid", display=False)
    else:
        sf, expanded, path, fringe = a_star(maze, "manhattan", display=False)
    if sf:
        if fitness_func == "expanded":
            return (expanded.shape)[0]
        elif fitness_func == "path":
            return (path.shape)[0]
        else:
            return fringe
    else:
        return 0
Пример #9
0
    def run_algorithm(self, algo):
        """
        The algorithm we are gonna run. BFS, Dijkstra, DFS etc.
        :param start_tile: Start node. Tile object.
        :param end_tile: Goal node. Tile object.
        :return: int total cost
        """
        if algo == "bfs":
            (cf, suc, hbn) = bfs(self.start, self.end)                  # Sets all necessary lists and
            path = reconstruct_path(cf, self.start, self.end)           # and dictionaries for bfs,
            cost = 0                                                    # and sums the total cost of the
            for tile in path:                                           # calculated path.
                cost += tile.weight
            print("Total cost: ", cost)

        elif algo == "d":
            (cf, csf, suc, hbn) = dijkstra(self.start, self.end)        # Sets all necessary lists and
            path = reconstruct_path(cf, self.start, self.end)           # and dictionaries for dijkstra,
            cost = csf[self.end]                                        # and sums the total cost of the
            print("Total cost: ", cost)                                 # calculated path.
        elif algo == "a":
            (cf, csf, suc, hbn) = a_star(self.start, self.end)          # Sets all necessary lists and
            cost = csf[self.end]                                        # and dictionaries for a* pathinder,
            print("Total cost: ", cost)                                 # and sums the total cost of the
            path = reconstruct_path(cf, self.start, self.end)           # calculated path.

        if suc:                                                         # Only if the end was found (success).
            for tile, came_from in cf.items():                          # Iterate through visited tiles,
                if came_from is None:                                   # from end to start.
                    pass
                else:
                    if tile.char == 'B':
                        break
                    if tile.char != 'A' and tile.char != 'B' and not tile.visited:
                        pass
                    else:                                               # Draw the visited tile
                        self.canvas.after(25, self.draw_tile(tile, tile.color_visited, 'black'))

            for tile in hbn:                                            # Draw tiles that has been considered
                if tile.char != 'A' and tile.char != 'B' and not tile.visited:  # visited, but visited.
                    self.canvas.after(25, self.redraw_oval(tile, "#999", "black"))

            for tile in path:                                           # Draw the calculated path.
                self.canvas.after(25, self.redraw_oval(tile, "black", "black"))

            """
                                                                        # Draw the calculated path reversed.
            current = cf[self.end]
            while current != self.start:
                self.canvas.after(25, self.redraw_oval(current, "black", "black"))
                current = cf[current]
            """
            return cost
Пример #10
0
def pathfind():
  if not start or not end:
    print('Please mark both endpoint nodes.')
    return
  path = a_star(grid, start, end)
  if not path:
    print('No possible paths.')
    return
  else:
    distance = round(path[-1].f_score, 2)
    if distance % 1 == 0:
      distance = int(distance)
    print('Path found with distance ' + str(distance) + '.')
  for node in path:
    if node != start and node != end:
      node.type = 'path'
  update_grid(display, grid)
Пример #11
0
    def run_algorithm(self, algo):
        """
        Main algorithm function.
        :param algo: String, choosen algorithm
        :return: None
        """

        #Breadth-first search algorithm
        if algo == 'bfs':

            cf, hbxt = bfs(self.start_tile, self.end_tile)

        #Dijkstra's algorithm
        elif algo == 'dijkstra':
            cf, csf, hbxt = dijkstra(self.start_tile, self.end_tile)
            self.cost = csf[self.end_tile]

        #A* algorithm
        elif algo == 'a_star':
            cf, csf, hbxt = a_star(self.start_tile, self.end_tile)
            self.cost = csf[self.end_tile]

        self.draw_paths(cf, hbxt, algo)
def handle_ai_game_event(game, font, clock, screen, main_menu, load_level_menu,
                         heuristic, is_goal_func):
    """
    handles game event using AI. if a path of unperformed actions(the output of A*) exists, it performs the next action in the path
    using a global index. otherwise it calls A* and gets such path of instructions.
    :param game:
    :param font:
    :param clock:
    :param screen:
    :param main_menu:
    :param load_level_menu:
    :param heuristic:
    :param is_goal_func:
    :return: the number of nodes opened in A* (for analysis)
    """
    global ai_spot_counter, ai_path_size, ai_path
    # if we finish the current path, construct a new one
    open_nodes = 0
    if (ai_spot_counter // LOOP_AT_EACH_MOVE_UPDATE >= ai_path_size):
        ai_path, ai_path_size, open_nodes = a_star(
            start=game,
            is_goal=is_goal_func,
            heuristic=heuristic,
            g_function=g_function_by_steps)
        if ai_path_size > REAL_PATH_LEN:
            ai_path = ai_path[0:REAL_PATH_LEN]
            ai_path_size = len(ai_path)
        ai_spot_counter = 0
    # AI couldn't find a path
    if len(ai_path) == 0:
        return open_nodes

    real_spot_at_path = ai_spot_counter // LOOP_AT_EACH_MOVE_UPDATE
    cur_action = ai_path[real_spot_at_path]
    play_single_action(game, cur_action, player_num=AI_PLAYER_NUM)
    ai_spot_counter += 1
    return open_nodes
Пример #13
0
def main(argv):
    # if we get an error when trying to solve the maze, we will catch it and display the error message
    try:
        maze_path = argv.infile
        output_path = argv.outfile
        algorithm = argv.algorithm
        compare = argv.compare

        # load the image and convert to RGB format
        print("Loading image...")
        maze_image = Image.open(maze_path)
        maze_image = maze_image.convert("RGB")

        print("Creating maze...")
        t0 = time.time()
        to_solve = Maze(maze_image)
        t1 = time.time()
        scan_total = t1 - t0

        print("Found", to_solve.get_num_nodes(), "nodes")
        print("Time elapsed:", scan_total)

        print()
        print("Solving maze...")

        # if we are just using one algorithm
        if not compare:
            # breadth-first search
            if algorithm == "bfs":
                print("Algorithm = BFS")
                t0 = time.time()
                solved, explored_count, path = breadth_first_search(to_solve)
                t1 = time.time()
            # depth-first search
            elif algorithm == "dfs":
                print("Algorithm = DFS")
                t0 = time.time()
                solved, explored_count, path = depth_first_search(to_solve)
                t1 = time.time()
            # A*
            elif algorithm == "a*":
                print("Algorithm = A*")
                t0 = time.time()
                solved, explored_count, path = a_star(to_solve)
                t1 = time.time()
            # Wall follow method
            elif algorithm == "wall":
                print("Algorithm = right-hand wall follow method")
                t0 = time.time()
                solved, explored_count, path = wall_follower(to_solve)
                t1 = time.time()
            else:
                raise Exception("You must specify an algorithm.")

            solve_total = t1 - t0

            # print out our data and draw our image, if there is a solution to the maze
            if solved:
                print("Nodes explored:", explored_count)
                print("Path length:", len(path), "nodes")
                print("Time elapsed:", solve_total)
                print()
                print("Drawing image...")
                # our draw_solution function will also calculate the distance traversed in the path
                solution_img, total_distance = draw_solution(maze_image, path)
                solution_img.save(output_path)
                print("Path length as calculated by draw_solution:",
                      total_distance, "pixels")
            else:
                print("No solution.")

        # otherwise, we have algorithms to compare
        else:
            # todo: generalize this since we are accruing more algorithms
            a_star_time = None
            a_star_solved = False

            bfs_time = None
            bfs_solved = False

            dfs_time = None
            dfs_solved = False

            wall_time = None
            wall_solved = False

            # track the shortest explored path and the path that was found quickest
            fewest_nodes = [float("inf"), ""]
            fewest_considered = [float("inf"), ""]
            fastest_compute_time = [float("inf"), ""]

            # iterate through each algorithm in the comparison list
            for algorithm in compare:
                # check which algorithm we want and verify that we haven't supplied the same algorithm more than once
                # by checking whether our time variable has been modified
                if algorithm == "a*" and a_star_time is None:
                    print("Running A* ...")
                    t0 = time.time()
                    a_star_solved, a_star_explored_count, a_star_path = a_star(
                        to_solve)
                    t1 = time.time()
                    a_star_time = t1 - t0

                    print("Time:", a_star_time)
                    print("Nodes considered:", a_star_explored_count)
                    print("Nodes in path:", len(a_star_path))
                    print()

                    if len(a_star_path) < fewest_nodes[0]:
                        fewest_nodes = [len(a_star_path), "A*"]

                    if a_star_explored_count < fewest_considered[0]:
                        fewest_considered = [a_star_explored_count, "A*"]

                    if a_star_time < fastest_compute_time[0]:
                        fastest_compute_time = [a_star_time, "A*"]
                elif algorithm == "bfs" and bfs_time is None:
                    print("Running BFS ...")
                    t0 = time.time()
                    bfs_solved, bfs_explored_count, bfs_path = breadth_first_search(
                        to_solve)
                    t1 = time.time()
                    bfs_time = t1 - t0

                    print("Time:", bfs_time)
                    print("Nodes considered:", bfs_explored_count)
                    print("Nodes in path:", len(bfs_path))
                    print()

                    if len(bfs_path) < fewest_nodes[0]:
                        fewest_nodes = [len(bfs_path), "BFS"]

                    if bfs_explored_count < fewest_considered[0]:
                        fewest_considered = [bfs_explored_count, "BFS"]

                    if bfs_time < fastest_compute_time[0]:
                        fastest_compute_time = [bfs_time, "BFS"]
                elif algorithm == "dfs" and dfs_time is None:
                    print("Running DFS ...")
                    t0 = time.time()
                    dfs_solved, dfs_explored_count, dfs_path = depth_first_search(
                        to_solve)
                    t1 = time.time()
                    dfs_time = t1 - t0

                    print("Time:", dfs_time)
                    print("Nodes considered:", dfs_explored_count)
                    print("Nodes in path:", len(dfs_path))
                    print()

                    if len(dfs_path) < fewest_nodes[0]:
                        fewest_nodes = [len(dfs_path), "DFS"]

                    if dfs_explored_count < fewest_considered[0]:
                        fewest_considered = [dfs_explored_count, "DFS"]

                    if dfs_time < fastest_compute_time[0]:
                        fastest_compute_time = [dfs_time, "DFS"]
                elif algorithm == "wall" and wall_time is None:
                    print("Running wall algorithm...")
                    t0 = time.time()
                    wall_solved, wall_explored_count, wall_path = wall_follower(
                        to_solve)
                    t1 = time.time()
                    wall_time = t1 - t0

                    print("Time:", wall_time)
                    print("Nodes in path:", len(wall_path))
                    print()

                    if len(wall_path) < fewest_nodes[0]:
                        fewest_nodes = [len(wall_path), "wall"]

                    if wall_explored_count < fewest_considered[0]:
                        fewest_considered = [wall_explored_count, "wall"]

                    if wall_time < fastest_compute_time[0]:
                        fastest_compute_time = [wall_time, "wall"]
                else:
                    raise Exception("Invalid algorithm for comparison")

            solved = a_star_solved or bfs_solved or dfs_solved or wall_solved

            if solved:
                # set up our list to track which algorithm has the shortest length; if the lengths of two algorithms are
                # identical, we must have a perfect maze, or at least there is no algorithm that performs best
                shortest_length = [float("inf"), ""]
                paths_equal = False

                if dfs_time is not None and dfs_solved:
                    print("Drawing path generated by DFS (red)...")
                    maze_image, dfs_path_length = draw_solution(
                        maze_image, dfs_path, (255, 0, 0))

                    if dfs_path_length < shortest_length[0]:
                        shortest_length = [dfs_path_length, "DFS"]
                if bfs_time is not None and bfs_solved:
                    print("Drawing path generated by BFS (green)...")
                    maze_image, bfs_path_length = draw_solution(
                        maze_image, bfs_path, (0, 255, 0))

                    if bfs_path_length < shortest_length[0]:
                        shortest_length = [bfs_path_length, "BFS"]
                    elif bfs_path_length == shortest_length[0]:
                        paths_equal = True
                if a_star_time is not None and a_star_solved:
                    print("Drawing path generated by A* (blue)...")
                    maze_image, a_star_path_length = draw_solution(
                        maze_image, a_star_path, (0, 0, 255))

                    if a_star_path_length < shortest_length[0]:
                        shortest_length = [a_star_path_length, "A*"]
                    elif a_star_path_length == shortest_length[0]:
                        paths_equal = True
                if wall_time is not None and wall_solved:
                    print(
                        "Drawing path generated by the wall algorithm (purple)..."
                    )
                    maze_image, wall_path_length = draw_solution(
                        maze_image, wall_path, (127, 0, 127))

                    if wall_path_length < shortest_length[0]:
                        shortest_length = [wall_path_length, "wall"]
                    elif wall_path_length == shortest_length[0]:
                        paths_equal = True

                print()
                print("Summary:")
                print("Algorithm that considered the fewest nodes was",
                      fewest_considered[1], "(considered",
                      fewest_considered[0], "nodes)")
                print("Path with fewest nodes was found by", fewest_nodes[1],
                      "(length of", fewest_nodes[0], "nodes)")

                if not paths_equal:
                    print("Path with shortest length was found by",
                          shortest_length[1], "(length of", fewest_nodes[0],
                          "pixels)")

                print("Fastest path calculation was performed by",
                      fastest_compute_time[1], "(took",
                      fastest_compute_time[0], "seconds)")
                print()

                # save the resultant image
                maze_image.save(output_path)

            # otherwise, if there was no solution, alert the user
            else:
                print("No solution")

        # close our image
        maze_image.close()
        print("Done.")

    except Exception as e:
        print(f"**** Error: {e}")

    finally:
        return 0
Пример #14
0
from depth_first_search import *
from breadth_first_search import *
from a_star import *
from time import time

#Set -1 for traversed Elements

maze_probability = 0.2
maze_dimension = 100
#maze = maze_generator(maze_dimension, maze_probability)
maze = maze_generator(maze_dimension, 0)
t = time()

#change diplay to True to see the image of the path.
#change second paramater of a_star to either "euclid" or "manhattan"

#### each of the search algorithm returns
#### i) success_flag: 1 indicates goal was found, 0 indicates otherwise.
#### ii) expanded_nodes: numpy array which holds the list of nodes that were explore/expanded.
#### iii) final_path: numpy array which holds the list of nodes that belong to the path from start to goal.
#### iv) fringe: maximum size of the fringe at any point during the algorithm.
####                  The array is empty if success_flag is 0.

#success_flag, expanded_nodes1, final_path1, fringe1 = depth_first_search(maze)
success_flag, expanded_nodes2, final_path, fringe2 = a_star(maze, "euclid")
success_flag, expanded_nodes3, final_path, fringe3 = a_star(maze, "manhattan")
success_flag, expanded_nodes4, final_path1, fringe4 = breadth_first_search(
    maze)

print(fringe2, fringe3, fringe4)
print("running time: ", time() - t)
Пример #15
0
        a[max_i][max_j] = 5

        update()  # <<<---

        for i in range(players):
            x[i], y[i] = 0, 2
            draw_player(0, 0, i)

        in_game = True
        restart_dfs = False
        restart_prim = False
        restart_kruskal = False

    if solve_dfs:
        solve(dfs_walk(True), n + 1, m + 1)
        update()  # <<<---
        solve_dfs = False

    if solve_bfs:
        solve(bfs(True), n + 1, m + 1)
        update()  # <<<---
        solve_bfs = False

    if solve_a_star:
        solve(a_star(True), n + 1, m + 1)
        update()  # <<<---
        solve_a_star = False

    pygame.display.update()

pygame.quit()
Пример #16
0
print("Start is:", start_pos[0], ",", start_pos[1])
print("Algorithms available:")
print("\t(L)azy Theta")
print("\t(T)heta")
print("\t(A)-Star")
print("\t(D)ijkstra")
print("\t(U)niform Cost Search")
print("\t(B)asic Link")
while (True):
    choice = input("Input algorithm to run on grid: ").lower()
    if choice == 'l':
        lazy_theta(grid_read)
        break
    elif choice == 't':
        theta(grid_read)
        break
    elif choice == 'a':
        a_star(grid_read)
        break
    elif choice == 'd':
        dijkstra(grid_read)
        break
    elif choice == 'u':
        ucs(grid_read)
        break
    elif choice == 'b':
        basic_link(grid_read)
        break
    else:
        print("Invalid choice")
Пример #17
0
def question1():
    algos = ["DFS", "BFS", "Astar-Euclidean", "Astar-Manhattan"]
    P = list(np.arange(0, 1.1, 0.1))
    final_stats = {}
    for algo in algos:
        stats = {}
        for p in P:
            dim = 100
            vals = {}
            while dim < 2500:
                flag = 0
                success_count = 0
                times = []
                for i in range(30):
                    sys.stdout.write("\r algo: %s p: %f dim %i rep: %i" %
                                     (algo, p, dim, i))
                    maze = maze_generator(dim, p)
                    t = time()
                    if algo == "BFS":
                        sf, en, path = breadth_first_search(maze,
                                                            display=False)
                    if algo == "DFS":
                        sf, en, path = depth_first_search(maze, display=False)
                    if algo == "Astar-Euclidean":
                        sf, en, path = a_star(maze, "euclid", display=False)
                    if algo == "Astar-Manhattan":
                        sf, en, path = a_star(maze, "manhattan", display=False)
                    exec_time = time() - t
                    success_count += sf
                    if exec_time > 60:
                        flag = 1
                        break
                    else:
                        times.append(exec_time)
                if flag:
                    break
                else:
                    vals[dim] = [np.max(times), success_count]
                dim += 100
            stats[p] = vals
        final_stats[algo] = stats

    #plot max-dimension vs P graph for all algorithms.

    path = "figs/graphs/q1/"
    os.makedirs(path, exist_ok=True)

    figno += 1
    plt.figure(figno)
    colors = ["red", "green", "blue", "black"]
    plt.xlabel("P")
    plt.ylabel("Max Dimension")

    STATS = {}
    file_string = ""
    for algo_no, algo in enumerate(algos):
        file_string += (algo + ":\n")
        PSTATS = {}
        MAXDIMS = []
        for p, p_stats in final_stats[algo].items():
            DIMS = []
            TIMES = []
            for dim, dim_stats in p_stats.items():
                DIMS.append(dim)
                TIMES.append(dim_stats[0])
            PSTATS[p] = [DIMS, TIMES]
            max_dim = np.max(list(p_stats.keys()))
            MAXDIMS.append(max_dim)
            t, count = p_stats[max_dim]
            file_string += ("\n---P:" + str(p) + "Max dimension:" +
                            str(max_dim))
        file_string += "\n\n"
        STATS[algo] = PSTATS
        plt.plot(P, MAXDIMS, color=colors[algo_no])
    with open("data/q1.txt", "w") as f:
        f.write(file_string)
    plt.legend(tuple(algos), loc="upper right")
    plt.title("Max Dimensions for time<60s")
    plt.savefig(path + "All - P vs max-dim.jpg")

    #write individual running time graphs

    colors = [
        "blue", "red", "green", "maroon", "brown", "olive", "teal", "purple",
        "magenta", "cyan", "orange"
    ]
    legend = tuple(["p=" + str(p) for p in P])
    for algo in algos:
        figno += 1
        plt.figure(figno)
        for p, p_stats in STATS[algo].items():
            plt.plot(p_stats[0], p_stats[1], color=colors[int(p * 10)])
        plt.axhline(y=60, color="black")
        plt.xlabel("Dimension")
        plt.ylabel("Time")
        plt.legend(legend, loc="lower right")
        plt.title(algo)
        plt.savefig(path + algo + "-dim vs t.jpg")
Пример #18
0
        total_poly_edge += poly.line_segs
        total_nodes += poly.nodes

    for poly_seg in total_poly_edge:
        if intersect((start.node, goal.node), poly_seg):
            direct_edge = False
            break

    if direct_edge:
        ax2.plot([goal.node[0], start.node[0]], [goal.node[1], start.node[1]],
                 'ro-',
                 lw=5)

    elif not valid_route:
        print "No possible route!"
    else:
        valid_edge = calc_valid_edge(polys, total_nodes, total_poly_edge)

        for edge in valid_edge:
            ax2.plot([edge[0][0], edge[1][0]], [edge[0][1], edge[1][1]], 'b--')

        shortest_path = a_star(start, goal, total_nodes)

        for i in range(len(shortest_path) - 1):
            ax2.plot([shortest_path[i].node[0], shortest_path[i + 1].node[0]],
                     [shortest_path[i].node[1], shortest_path[i + 1].node[1]],
                     'ro-',
                     lw=5)

    plt.show()
Пример #19
0
def ques4(n):
    # This function calculates the average length of the path for a certain dimension for all p
    # For each value of p, the function takes an average of n mazes
    # The output is a graph which contains the average length as the value for a key 'p'
    print("Question 4 has started.....")
    dfs_avg = {}
    bfs_avg = {}
    a_euclid_avg = {}
    a_manhattan_avg = {}

    p_values = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
    for p in p_values:
        dim = 200

        dfs_lengths = []
        bfs_lengths = []
        a_euclid_lengths = []
        a_manhattan_lengths = []
        dfs_count = 0
        bfs_count = 0
        a_euclid_count = 0
        a_manhattan_count = 0
        for rep in range(n):
            maze = maze_generator(dim, p)
            dfs_count = len(depth_first_search(maze, display=False)[2])
            dfs_lengths.append(dfs_count)

            bfs_count = len(breadth_first_search(maze, display=False)[2])
            bfs_lengths.append(bfs_count)

            a_euclid_count = len(a_star(maze, "euclid", display=False)[2])
            a_euclid_lengths.append(a_euclid_count)

            a_manhattan_count = len(
                a_star(maze, "manhattan", display=False)[2])
            a_manhattan_lengths.append(a_manhattan_count)

        if dfs_lengths:
            dfs_avg[p] = np.mean(dfs_lengths)
#        print("DFS AVERAGE LENGTHS for p = {}".format(p))
#        if p in dfs_avg.keys():
#            print(dfs_avg[p])

        if bfs_lengths:
            bfs_avg[p] = np.mean(bfs_lengths)
#        print("BFS AVERAGE LENGTHS for p = {}".format(p))
#        if p in bfs_avg.keys():
#            print(bfs_avg[p])

        if a_euclid_lengths:
            a_euclid_avg[p] = np.mean(a_euclid_lengths)
#        print("A* Euclidean distance AVERAGE LENGTHS for p = {}".format(p))
#        if p in a_euclid_avg.keys():
#            print(a_euclid_avg[p])

        if a_manhattan_lengths:
            a_manhattan_avg[p] = np.mean(a_manhattan_lengths)


#        print("A* Manhattan distance AVERAGE LENGTHS for p = {}".format(p))
#        if p in a_manhattan_avg.keys():
#            print(a_manhattan_avg[p])

    fig = plt.figure()
    axes = fig.add_axes([0, 0, 1, 1])
    axes.plot(dfs_avg.keys(), list(dfs_avg.values()), label='dfs')
    axes.plot(bfs_avg.keys(), list(bfs_avg.values()), 'r', label='bfs')
    axes.plot(a_euclid_avg.keys(),
              list(a_euclid_avg.values()),
              'b',
              label='a_euclid')
    axes.plot(a_manhattan_avg.keys(),
              list(a_manhattan_avg.values()),
              color='orange',
              label='a_manhattan')
    axes.set_xlim([0, 1])
    axes.legend()
    plt.show()
Пример #20
0
    def useCheat(self, reuse=False):
        if len(self.path) == 0 or not reuse:
            astar = a_star(self.scene.map, start=self.scene.robot_pos, goal=self.scene.goal_pos)
            self.path = astar.findPath(self.scene.robot_pos, self.scene.goal_pos)

        self.followPath()
Пример #21
0
def genetic_algo(dim,
                 algo,
                 maze_count,
                 mutation_count,
                 iteration_count,
                 fitness_func,
                 init_count,
                 display=False):
    mazes = []
    sys.stdout.write(
        "\r\n ---  Generating inital mazes                       ")
    for i in range(init_count):
        if i < init_count / 3:
            maze = maze_generator(dim, 0.1)
        elif i < init_count * 2 / 3:
            maze = maze_generator(dim, 0.2)
        else:
            maze = maze_generator(dim, 0.3)
        mazes.append(maze)
    mazes.append(maze_generator(dim, 0))
    new_mazes = []
    for mn, maze in enumerate(mazes):
        flag = 0
        for mn2, maze2 in enumerate(mazes):
            if mn != mn2:
                if np.array_equal(maze, maze2):
                    flag = 1
                    break
        if not (flag):
            new_mazes.append(maze)
    mazes = new_mazes
    mazes = sorted(mazes,
                   key=lambda x: fitness_function(x, algo, fitness_func),
                   reverse=True)
    mazes = mazes[:maze_count]

    sys.stdout.write("\r\n Initial Mazes generated")
    for i in range(iteration_count):
        sys.stdout.write("\r \n ---Performing iteration %d" % i)
        mazes = crossover(mazes, dim, maze_count)
        mazes = mutations(mazes, maze_count, dim, mutation_count)
        mazes = sorted(mazes,
                       key=lambda x: fitness_function(x, algo, fitness_func),
                       reverse=True)
        mazes = mazes[:maze_count]

    mazes = mazes[:3]
    if display:
        path = "figs/question2/dim=" + str(dim) + ",maze_count=" + str(
            maze_count
        ) + ",mut_count=" + str(mutation_count) + ",iter_count=" + str(
            iteration_count) + ",init_count=" + str(init_count) + "/" + str(
                algo) + "/" + str(fitness_func) + "/"
        os.makedirs(path, exist_ok=True)
        for maze_no, maze in enumerate(mazes):

            if algo == "BFS":
                sf, expanded, p, fringe = breadth_first_search(
                    maze, display=True, sol_path=path, figname=str(maze_no))
            elif algo == "DFS":
                sf, expanded, p, fringe = depth_first_search(
                    maze, display=True, sol_path=path, figname=str(maze_no))
            elif algo == "Astar-euclidean":
                sf, expanded, p, fringe = a_star(maze,
                                                 "euclid",
                                                 display=True,
                                                 sol_path=path,
                                                 figname=str(maze_no))
            else:
                sf, expanded, p, fringe = a_star(maze,
                                                 "manhattan",
                                                 display=True,
                                                 sol_path=path,
                                                 figname=str(maze_no))

            with open(path + str(maze_no) + ".pickle", "wb+") as f:
                pickle.dump(maze, f)
            with open(path + str(maze_no) + ".txt", "w") as f:
                f.write(
                    str(fitness_func) + ": " +
                    str(fitness_function(maze, algo, fitness_func)))

    return mazes
Пример #22
0
from maze_generator import *
from maze_plot import *
from depth_first_search import *
from breadth_first_search import *
from a_star import *
from time import time
#Set -1 for traversed Elements
#Set -2 for current element being traversed, or for the current wavefront in case of BFS

maze_probability = 0.3
maze_dimension = 5000#int(input("Enter the dimension for maze : \n"))
#maze = maze_generator(maze_dimension, maze_probability)
maze=maze_generator(500,0.2)
t=time()

#each of depth_first_search, breadth_first_search, a_star returns 1 if a path was found and 0 otherwise.
#change diplay to True to see the image of the path.
#change second paramater to either "euclid" or "manhattan"

#print(depth_first_search(maze,display=False))
print("A-Star :")
#print(a_star(maze,"euclid",display=True))
print(a_star(maze,"manhattan",display=True))
print("BFS :")
print(breadth_first_search(maze,display=True))

print("running time: ", time()-t)
Пример #23
0
    file_nodes = "../results/nodes.csv"
    file_edges = "../results/edges.csv"
    file_param = "../results/params.json"
    ## read obstacles from file
    obstacles = read_obstacles(file_obstacles)
    ## read params from file
    PARAM = read_params(file_param)
    ## Run RRT algo to create a Tree of nodes and edges
    x_start = Nodes(PARAM['x_start']['x'], PARAM['x_start']['y'], 1)
    x_goal = Nodes(PARAM['x_goal']['x'], PARAM['x_goal']['y'])
    print("\nFiles and parameters read...")
    print("\nRunning Algo...")
    if PARAM["algo"] == "PRM":
        T = PRM(obstacles, x_start, x_goal, PARAM['num_samples'],
                PARAM['k_neighbors'], PARAM['X'])
    else:
        T = RRT(obstacles, x_start, x_goal, PARAM['max_tree_size'], PARAM['X'])
    print("\nAlgo completed...")
    if T.size >= PARAM['max_tree_size']:
        print("\nMax tree size reached!!")
    nodes = T.nodes
    edges = T.edges
    print("\nWriting nodes and edges to file...")
    write_nodes(nodes, file_nodes)
    write_edges(edges, file_edges)
    ## Find the optimal path using A* and write it to file
    print("\nComputing Optimal Path")
    path = a_star(nodes, edges)
    write_path(path, file_path)
    print("\nSUCCESS")
Пример #24
0
from maze_generator import *
from maze_plot import *
from depth_first_search import *
from breadth_first_search import *
from a_star import *
from time import time
#Set -1 for traversed Elements
#Set -2 for current element being traversed, or for the current wavefront in case of BFS

maze_probability = 0.3
maze_dimension = 5000#int(input("Enter the dimension for maze : \n"))
#maze = maze_generator(maze_dimension, maze_probability)
maze=maze_generator(500,0.2)
t=time()

#each of depth_first_search, breadth_first_search, a_star returns 1 if a path was found and 0 otherwise.
#change diplay to True to see the image of the path.
#change second paramater to either "euclid" or "manhattan"

#print(depth_first_search(maze,display=False))
print("A-Star :")
print(a_star(maze,"euclid",display=True))
#print(a_star(maze,"manhattan",display=True))
#print("BFS :")
#print(breadth_first_search(maze,display=True))

print("running time: ", time()-t)
Пример #25
0
def ques5(n):
    print("Question 5 has started.....")
    dfs_avg = {}
    a_euclid_avg = {}
    a_manhattan_avg = {}

    p_values = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
    for p in p_values:
        dim = 200

        dfs_lengths = []
        a_euclid_lengths = []
        a_manhattan_lengths = []
        dfs_count = 0
        a_euclid_count = 0
        a_manhattan_count = 0
        for rep in range(n):
            maze = maze_generator(dim, p)
            dfs_count = len(depth_first_search(maze, display=False)[2])
            dfs_lengths.append(dfs_count)

            a_euclid_count = len(a_star(maze, "euclid", display=False)[2])
            a_euclid_lengths.append(a_euclid_count)

            a_manhattan_count = len(
                a_star(maze, "manhattan", display=False)[2])
            a_manhattan_lengths.append(a_manhattan_count)

        if dfs_lengths:
            dfs_avg[p] = np.mean(dfs_lengths)
#        print("DFS AVERAGE LENGTHS for p = {}".format(p))
#        if p in dfs_avg.keys():
#            print(dfs_avg[p])

        if a_euclid_lengths:
            a_euclid_avg[p] = np.mean(a_euclid_lengths)
#        print("A* Euclidean distance AVERAGE LENGTHS for p = {}".format(p))
#        if p in a_euclid_avg.keys():
#            print(a_euclid_avg[p])

        if a_manhattan_lengths:
            a_manhattan_avg[p] = np.mean(a_manhattan_lengths)


#        print("A* Manhattan distance AVERAGE LENGTHS for p = {}".format(p))
#        if p in a_manhattan_avg.keys():
#            print(a_manhattan_avg[p])

    fig1 = plt.figure()
    axes1 = fig1.add_axes([0, 0, 1, 1])
    axes1.plot(dfs_avg.keys(), list(dfs_avg.values()), label='dfs')
    axes1.plot(a_euclid_avg.keys(),
               list(a_euclid_avg.values()),
               'b',
               label='a_euclid')
    axes1.plot(a_manhattan_avg.keys(),
               list(a_manhattan_avg.values()),
               color='orange',
               label='a_manhattan')
    axes1.legend()
    plt.show()
Пример #26
0
 def mainy():
     global val
     print(val, "mainly")
     fire_main(canvas, plan, fire_pos, col_len, row_len, val, root)
     a_star(canvas, plan, entrance_pos, exit_pos, col_len, row_len, root)
from maze_generator import *
from breadth_first_search import *
from a_star import *
import numpy as np

if __name__ == "__main__":
    maze = maze_generator(200, 0)
    for i in range(0):

        loc = np.random.choice(200, 2)
        maze[tuple(loc)] = 1
    sf, e, p, f = a_star(maze, "euclid", display=True)