Ejemplo n.º 1
0
def main():
    parser = argparse.ArgumentParser()

    parser.add_argument("-g", "--game", help="Specify the game number, e.g. --game 4",
                    type=int)

    parser.add_argument("-b", "--bfs", help="Run program using breadth first search.",
                    action="store_true")

    parser.add_argument("-a", "--astar", help="Run program using A star algortihm.",
                    action="store_true")

    parser.add_argument("-d", "--depth", help="Depth of the a star algorithm.",
                    type=int)

    parser.add_argument("-n", "--not_admissable", help="Set this flag, if you want a not addmissable a start algorithm.",
                    action="store_true")

    parser.add_argument("-i", "--interactive", help="Run program with interactive freezing.",
                    action="store_true")
    args = parser.parse_args()

    if args.bfs:
        breath_search(games[args.game - 1], math.inf)
    elif args.astar:
        a_star_search(games[args.game - 1], args.depth, not args.not_admissable)
    elif args.interactive:
        interactive_search(args.game)
    else:
        print("Please add either the --bfs flag or --astar flag.")
Ejemplo n.º 2
0
def main(arg):
    initial_state = []
    goal = [0, 1, 2, 3, 4, 5, 6, 7, 8]

    with open(arg, "r") as file:
        line = file.readline()
        for val in line.split(" "):
            initial_state.append(int(val))

    if set(goal) != set(initial_state):
        sys.exit("ERROR: input is not valid, it must have numbers from 0 to 8")
    elif len(goal) != len(initial_state):
        sys.exit(
            "ERROR: invalid input, it must have nine numbers, from 0 to 8")

    start = timer()
    final_state, explored_set, size = a_star_search(initial_state, goal)
    end = timer()

    if final_state != None:
        print("=" * 20)
        print("Solution depth or cost: %d" % len(final_state.path))
        print("=" * 20)
        print("Number of visited nodes: %d" % len(explored_set))
        print("=" * 20)
        print("Running time: %f sec" % (end - start))
        print("=" * 20)
        print("Bytes per node: %d" % sys.getsizeof(final_state))
        print("Used memory: %d bytes" % size)
        print("=" * 20)
        print("This are the movements to solve the puzzle:")
        print("-" * 20)
        print(*final_state.path, sep=' => ')
    else:
        print("It has no solution :(")
Ejemplo n.º 3
0
def solve():
    initial_state = get_initial_state()
    if not initial_state:
        tkinter.messagebox.showerror('错误', '非法初始状态')
        return
    goal_state = get_goal_state()
    if not goal_state:
        tkinter.messagebox.showerror('错误', '非法目标状态')
        return
    choice = var.get()
    path = []
    if choice == 1:
        path = bfs.breadth_first_search(initial_state, goal_state)
    elif choice == 2:
        path = dfs.depth_first_search(initial_state, goal_state)
    elif choice == 3:
        path = iddfs.iterative_deepening_dfs(initial_state, goal_state)
    elif choice == 4:
        path = best_first.best_first_search(initial_state, goal_state)
    elif choice == 5:
        path = bidirectional.bidirectional_search(initial_state, goal_state)
    elif choice == 6:
        path = a_star.a_star_search(initial_state, goal_state)
    elif choice == 7:
        path = ida_star.iterative_deepening_a_star(initial_state, goal_state)
    output.delete(1.0, END)
    output.insert(1.0, auxiliary.path_to_str(path))
Ejemplo n.º 4
0
    def test_maze_1(self):
        maze = GridWithWeights(4,4)
        walls = [(1,1),(2,2)]
        maze.walls = walls
        weights = {(1,0):20,(3,0) : 2}
        maze.weights = weights
        my_solution = [(3,0),(3,1),(3,2),(3,3),(2,3),(1,3),(1,2),(0,2)]
        end = (3,0)
        start = (0,2)

        # Call the A* algorithm and get the frontier
        frontier = a_star.a_star_search(graph = maze, start=start, end=end)
        solution = list(backtrack(frontier.visited,start,end))
        self.assertTrue( solution == my_solution  )
Ejemplo n.º 5
0
    def test_maze_1(self):
        maze = GridWithWeights(4, 4)
        walls = [(1, 1), (2, 2)]
        maze.walls = walls
        weights = {(1, 0): 20, (3, 0): 2}
        maze.weights = weights
        my_solution = [(3, 0), (3, 1), (3, 2), (3, 3), (2, 3), (1, 3), (1, 2),
                       (0, 2)]
        end = (3, 0)
        start = (0, 2)

        # Call the A* algorithm and get the frontier
        frontier = a_star.a_star_search(graph=maze, start=start, end=end)
        solution = list(backtrack(frontier.visited, start, end))
        self.assertTrue(solution == my_solution)
Ejemplo n.º 6
0
def plan(start, goals, problem, states, algorithm='a-star'):
    if goals is None or len(goals) == 0:
        return [], sys.maxsize
    # if a-star search is used
    if algorithm == 'a-star':
        results = [
            a_star_search(start, State(goal), problem, states)
            for goal in goals if goal is not None
        ]
        results = sorted(results, key=lambda x: x[1])
        return results[0]
    # if depth-limited is used
    if algorithm == 'depth-limited':
        return depth_limited_search(start, goals, problem)

    raise ValueError
Ejemplo n.º 7
0
    def test_weights_instead_of_walls(self):
        maze = GridWithWeights(4, 4)
        walls = []
        maze.walls = walls
        weights = {(1, 1): 300, (1, 2): 300, (1, 3): 300}
        maze.weights = weights

        start = (0, 3)
        end = (3, 3)

        my_solution = [(3, 3), (2, 3), (2, 2), (2, 1), (2, 0), (1, 0), (0, 0),
                       (0, 1), (0, 2), (0, 3)]
        # Call the A* algorithm and get the frontier
        frontier = a_star.a_star_search(graph=maze, start=start, end=end)

        solution = list(backtrack(frontier.visited, start, end))

        self.assertTrue(solution == my_solution)
Ejemplo n.º 8
0
    def test_weights_instead_of_walls(self):
        maze = GridWithWeights(4,4)
        walls = []
        maze.walls = walls
        weights = { (1,1):300, (1,2): 300, (1,3):300}
        maze.weights = weights

        start = (0,3)
        end = (3,3)

        my_solution = [(3, 3), (2, 3), (2, 2), (2, 1),
                       (2, 0), (1, 0), (0, 0), (0, 1),
                       (0, 2), (0, 3)]
        # Call the A* algorithm and get the frontier
        frontier = a_star.a_star_search(graph = maze, start=start, end=end)

        solution = list(backtrack(frontier.visited,start,end))

        self.assertTrue( solution == my_solution  )
Ejemplo n.º 9
0
    def _query(self, start, goal):
        '''
        Queries current PRM to find path between start and goal.
        Alters the map. Returns path as list of states.
        '''
        #add start and goal to the map
        s_node = Node(start)
        g_node = Node(goal)
        self.T.add_node(s_node)
        self.T.add_node(g_node)

        #Add neighbors for the two nodes
        for nb in self.T.find_k_nearest(self.num_neighbors, start):
            self.try_connect(s_node, nb)

        for nb in self.T.find_k_nearest(self.num_neighbors, goal):
            self.try_connect(g_node, nb)

        #Run A* pathfinding to get path
        return a_star.a_star_search(s_node, g_node)
Ejemplo n.º 10
0
def main():

    parser = argparse.ArgumentParser(
        description="Solve a maze problem with genetic algorithm")
    parser.add_argument("maze",
                        help="The maze file to run the algorithm",
                        type=str)
    parser.add_argument("-p",
                        "--population",
                        help="Population size (must be an odd number)",
                        type=int)
    parser.add_argument(
        "-m",
        "--mutation",
        help="The mutation chance (must be between 0 and 1)",
        type=float,
    )
    parser.add_argument("-ml",
                        "--move",
                        help="Number of moves allowed to the chromosome",
                        type=int)
    parser.add_argument(
        "-i",
        "--iterations",
        help=
        "Number of iterations the algorithm will execute to try to find the exit",
        type=int,
    )

    args = parser.parse_args()

    if not args.population:
        population = 501
    else:
        if args.population % 2 == 0:
            population = args.population + 1
            print("Population must be an odd number. Rounding up to " +
                  str(population))
        else:
            population = args.population

    if not args.mutation:
        mutation = 0.5
    else:
        if args.mutation > 1:
            mutation = 0.5
            print("Mutation must be between 0 and 1. Setting to " +
                  str(mutation))
        else:
            mutation = args.mutation

    if not args.move:
        move = 40
    else:
        move = args.move

    if not args.iterations:
        iterations = 5000
    else:
        iterations = args.iterations

    print("Starting maze")
    print("Maze solving started with variables population=" + str(population) +
          ", mutation=" + str(mutation) + ", moves=" + str(move) +
          ", iterations=" + str(iterations))
    genetic_algorithm = GA(move, population, mutation, args.maze)
    route = genetic_algorithm.search_optional_moves(
        genetic_algorithm.population, iterations)
    if route is None:
        print("Solution not found")
    else:
        print("Exit found!")
        print("Chromosome with moves: " + str(route[0]))
        print("Start: " + str(route[1][0]) + " End: " + str(route[1][1]))
        print("List of coordinates that player moved: " + str(route[2]))
        print("Starting A*")
        print("Creating graph")
        graph = Graph(genetic_algorithm.current_maze.Board)
        print("Graph created")
        print("Starting algorithm processing")
        came_from, cost_so_far = a_star_search(graph, route[1][0], route[1][1])
        best_path = reconstruct_path(came_from, route[1][0], route[1][1])
        print("Best path found! It's:")
        print(best_path)
                                                    194, 201, 202, 203, 204, 205, 213, 214, 223,
                                                    224, 243, 244, 253, 254, 273, 274, 283, 284,
                                                    303, 304, 313, 314, 333, 334, 343, 344, 373,
                                                    374, 403, 404, 433, 434]]

     # Instantiate a grid of 10 x 10
     graph = GridWithWeights(10, 10)

     # Set the walls of the grid
     graph.walls = set(WALLS)

     # Set the weighs of some points in the maze
     graph.weights = {location: random.randint(1,10) for location in [(3, 4), (3, 5), (4, 1), (4, 2),
                                            (4, 3), (4, 4), (4, 5), (4, 6),
                                            (4, 7), (4, 8), (5, 1), (5, 2),
                                            (5, 3), (5, 4), (5, 5), (5, 6),
                                            (5, 7), (5, 8), (6, 2), (6, 3),
                                            (6, 4), (6, 5), (6, 6), (6, 7),
                                            (7, 3), (7, 4), (7, 5)]}

     # Call the A* algorithm and get the frontier
     frontier = a_star.a_star_search(graph = graph, start=(1, 4), end=(7, 8))

     # Print the results

     graph.draw(width=5, point_to = frontier.visited, start=(1, 4), goal=(7, 8))

     print()

     graph.draw(width=5, number = frontier.costs, start=(1, 4), goal=(7, 8))
 def solve():
     solution = a_star.a_star_search(start, goal, size, heuristic_cost_estimate, get_neighbors, get_edge_weight)
     print(solution)
     print("moves: " + str(len(solution)-1))        
Ejemplo n.º 13
0
                break
            if not args[1][i][1] in args[0]:
                fail = 1
                break
            if args[1][i][2] and args[1][i][2].isdigit():
                args[1][i][2] = float(args[1][i][2])
            else:
                fail = 1
                break
        if fail:
            print("[Failed] Test #{}. {}".format(test_number, line.strip()))
        else:
            matrix = a_star.create_matrix(list(), args[0], args[1])
            index = 0
            a_star.list_vertex = args[0]

            ans = a_star.a_star_search(matrix, args[2][0], args[2][1])
            add = args[2][1]
            string = add

            while add != args[2][0]:
                add = ans[add]
                string += add

            string = string[::-1]
            if string == outp:
                print("[OK] Test #{}. {}".format(test_number, line.strip()))
            else:
                print("[Failed] Test #{}. {}".format(test_number, line.strip()))
        test_number += 1
Ejemplo n.º 14
0
def applyAStar(head, foodCoord):
    tupleHead = tuple(head)
    tupleFood = tuple(foodCoord)
    movePath = a_star.a_star_search(settings.getMap(), tupleHead, tupleFood)
    return movePath
            254, 273, 274, 283, 284, 303, 304, 313, 314, 333, 334, 343, 344,
            373, 374, 403, 404, 433, 434
        ]
    ]

    # Instantiate a grid of 10 x 10
    graph = GridWithWeights(10, 10)

    # Set the walls of the grid
    graph.walls = set(WALLS)

    # Set the weighs of some points in the maze
    graph.weights = {
        location: random.randint(1, 10)
        for location in [(3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (
            4, 5), (4, 6), (4, 7), (4, 8), (5, 1), (5, 2), (5, 3), (
                5, 4), (5, 5), (5, 6), (5, 7), (5, 8), (6, 2), (6, 3), (
                    6, 4), (6, 5), (6, 6), (6, 7), (7, 3), (7, 4), (7, 5)]
    }

    # Call the A* algorithm and get the frontier
    frontier = a_star.a_star_search(graph=graph, start=(1, 4), end=(7, 8))

    # Print the results

    graph.draw(width=5, point_to=frontier.visited, start=(1, 4), goal=(7, 8))

    print()

    graph.draw(width=5, number=frontier.costs, start=(1, 4), goal=(7, 8))