def test_dfs():
    with open('/home/douglascorrea/FIA/DFS.csv', 'wb') as file:
        for i in range(len(shuffle_number)):
            times = []
            memory = []
            average_time = 0
            average_memory = 0
            print("Moves: " + str(shuffle_number[i]))
            file.write(str(shuffle_number[i]) + '\n')
            for j in range(test_number):
                print(j)
                print(boards[i][j])
                dfs_alg = dfs.DFS(boards[i][j], board_size)

                start = time.time()
                dfs_alg.DFS_algorithm()
                end = time.time()

                times.append(end - start)
                memory.append(dfs_alg.get_memory_usage())

            file.write(' ' + ',')
            for t in times:
                file.write(str(t) + ',')
                average_time += t
            file.write(str(average_time / 10) + '\n' + ' ,')
            for m in memory:
                file.write(str(m) + ',')
                average_memory += m
            file.write(str(average_memory / 10) + '\n')
Exemple #2
0
    def __init__(self, img_assets: List[pygame.Surface], resources):

        self.img_assets = img_assets
        self.state = img_assets['up'][0]
        self.direction = 'up'
        self.ai = dfs.DFS((50, 50), resources)
        self.move_counter = 0
        self.pos = [
            self.ai.interface.player_pos.x * 16,
            self.ai.interface.player_pos.y * 16
        ]
        self.dest = self.ai.interface.player_pos
        self.graph_surf = pygame.Surface((800, 800), pygame.SRCALPHA)
        self.graph_surf.fill((0, 0, 0, 0))
        self.last_drawn = self.pos[0] + 8, self.pos[1] + 8
Exemple #3
0
 def __init__(self, csvFile, nodes, edges, inicio, destino, nIndividuals,
              limitGen, MapObject, code):
     self.csv = csvFile
     self.matrix = []
     self.n_individuals = nIndividuals  #7
     self.population = []
     self.fitness = []
     self.nodes = nodes
     self.edges = edges
     self.edgesV = {}  #edges vizinhas
     self.limit = limitGen  #20 # generation limit
     self.criterion = False
     self.bestFitness = 0
     self.fitnessDesired = 10000
     self.inicio = inicio
     self.destino = destino
     self.map = MapObject  #Map.Map('SUMO/map')
     self.map.run()
     self.code = code
     self.bfs = bfs.Graph()
     self.dfs = dfs.DFS()
def main():
    # get number of args passed in via command line
    num_args = len(sys.argv)

    # ensure we have valid input
    if num_args == 1:
        print "Usage: 'python puzzlesolver.py [config_filename] [search_algorithm_name] [optional: heuristic] "
        print "     to run test suite:  'python puzzlesolver.py -t'"
        return
    # check if we are running the test suite
    if sys.argv[1] == "-t":
        # run the test suite
        runTests()
        return

    # if we get this far, then we are running a specific algorithm
    if num_args < 3 or num_args > 4:
        print "Usage: 'python puzzlesolver.py [config_filename] [search_algorithm_name] [optional: heuristic] "
        print "     to run test suite:  'python puzzlesolver.py -t'"


    # otherwise, parse the args, and
    # take 2 input args... plus an optional one....
    # FIRST ARG --> a configuration file
    config_file = sys.argv[1]
    # SECOND ARG --> Keyword to specify which algorithm to use: bfs, dfs, iddfs, unicost, greedy, astar, diastar
    algorithm = sys.argv[2]
    # THIRD ARG --> Heuristic
    if num_args == 4:
        heuristic = sys.argv[3]

    """ parse the config file based on what's in the first line"""
    # do that here.... need to write a function just to get first line and then call the appropriate
    # parse based on what's sent in

    # grab all the data and store it as a single string
    with open(config_file, 'r') as f:
        data_as_string = f.read()

    # split the data we've just read on newline, so we can index into it
    data_array = data_as_string.split("\n")

    # ensure that we actually have pancake data
    puzzle_name = data_array[0]
    puzzle = None
    # check which puzzle we have and open the correct file for it
    if "jugs" in puzzle_name:
         # then it's the jug puzzle
        puzzle = jugs.WaterJugs()
        puzzle.parseInput(config_file)
    elif "pancake" in puzzle_name:
        # then it's burnt pancakes puzzle
        puzzle = pancakes.BurntPancakes()
        puzzle.parseInput(config_file)
    elif "cities" in puzzle_name:
        # then it's path planning
        puzzle = paths.PathPlanning()
        puzzle.parseInput(config_file)
    else:
        # else it's nothing, and we have an invalid file
        print "Invalid data file. Please make sure your file has the correct format."
        return


    # determine which algorithm to initialize
    if algorithm == "bfs":
        print "---- START BFS ----"
        search = breadth_first_search.BFS(puzzle)
        search.bfs()
        print "---- END BFS ----"

    elif algorithm == "dfs":
        print "---- START DFS ----"
        search = depth_first_search.DFS(puzzle)
        search.dfs()
        print "---- END DFS ----"

    elif algorithm == "iddfs":
        print "---- START IDDFS ----"
        search = iterative_deepending_dfs.IDDFS(puzzle, 1, 1)
        search.iddfs()
        print "---- END IDDFS ----"

    elif algorithm == "unicost":
        print "----- START UNICOST ----"
        search = unicost_search.Unicost(puzzle)
        search.unicost()
        print "----- END UNICOST ----"

    elif algorithm == "greedy":
        print "----- START GREEDY -----"
        search = greedy_search.Greedy(puzzle)
        search.greedy()
        print "----- END GREEDY -----"

    elif algorithm == "astar":
        print "----- START ASTAR -----"
        search = astar_search.AStar(puzzle)
        search.astar()
        print "----- END ASTAR -----"

    elif algorithm == "idastar":
        print "----- START IDASTAR -----"
        search = idastar_search.IDAStar(puzzle, 5)
        search.idastar()
        print "----- END IDASTAR -----"
    else:
        print "Invalid algorithm name."


    return
Exemple #5
0
    def confirmAllPuzzlesRunOnAllSearches(self):
        # MODEL PANCAKES
        pancake_puzzle = Pancakes.BurntPancakes()
        pancake_puzzle.parseInput("small_pancakes.config")
        init_state = pancake_puzzle.initial_state
        successor_states = pancake_puzzle.getSuccessorStates(init_state)
        successor_state_costs = []
        for elem in successor_states:
            cost = pancake_puzzle.getPathCost(init_state, elem)
            successor_state_costs.append(cost)
        successor_state_heuristics = []
        for elem in successor_states:
            heuristic = pancake_puzzle.getHeuristic(init_state, elem)
            successor_state_heuristics.append(heuristic)


        # MODEL WATERJUGS
        # parse the water jugs data
        jug_puzzle = WJ.WaterJugs()
        jug_puzzle.parseInput("jugs.config")
        #print jug_puzzle.getHeuristic((0,0),(4,2))
        #wj_tests.WaterJugsTests()

        print "\n============ BREADTH FIRST SEARCH ============"
        print "\n ---- WATER JUG BFS ----"
        bfs = bread_first_search.BFS(jug_puzzle)
        bfs.bfs()

        # MODEL PATH-PLANNING
        path_puzzle = PATH.PathPlanning()
        path_puzzle.parseInput("cities.config")
        print "\n --- PATH PLANNING BFS ---"
        arlington_successors = path_puzzle.getSuccessorStates('Arlington')
        berkshire_successors = path_puzzle.getSuccessorStates('Berkshire')
        chelmsford_successors = path_puzzle.getSuccessorStates('Chelmsford')
        print path_puzzle.getHeuristic(('Berkshire', 4), ('Chelmsford', 10))
        bfs_paths = bread_first_search.BFS(path_puzzle)
        bfs_paths.bfs()

        print "\n ---- PANCAKES BFS ----"
        pancake_bfs = bread_first_search.BFS(pancake_puzzle)
        pancake_bfs.bfs()

        print "\n\n\n ============ DEPTH FIRST SEARCH ============"
        print "\n ---- WATER JUG DFS ----"
        dfs_jugs = depth_first_search.DFS(jug_puzzle)
        dfs_jugs.dfs()
        print "\n --- PATH PLANNING DFS ---"
        dfs_paths = depth_first_search.DFS(path_puzzle)
        dfs_paths.dfs()
        print "\n --- BURNT PANCAKES DFS ---"
        dfs_pancakes = depth_first_search.DFS(pancake_puzzle)
        dfs_pancakes.dfs()

        print "\n\n\n ============ ITERATIVE-DEEPENING DEPTH FIRST SEARCH ============"
        print "\n ---- WATER JUG IDDFS ----"
        iddfs_jugs = iterative_deepening_dfs.IDDFS(jug_puzzle, max_depth=1, deepening_constant=1)
        iddfs_jugs.iddfs()
        print "\n --- PATH PLANNING IDDFS ---"
        iddfs_paths = iterative_deepening_dfs.IDDFS(path_puzzle, max_depth=1, deepening_constant=1)
        iddfs_paths.iddfs()
        print "\n --- BURNT PANCAKES IDDFS ---"
        iddfs_pancakes = iterative_deepening_dfs.IDDFS(pancake_puzzle, max_depth=1, deepening_constant=1)
        iddfs_pancakes.iddfs()

        print "\n\n\n ============ UNICOST SEARCH ============"
        print "\n ---- WATER JUG UNICOST ----"
        unicost_jugs = UC.Unicost(jug_puzzle)
        unicost_jugs.unicost()
        print "\n --- PATH PLANNING UNICOST ---"
        unicost_paths = UC.Unicost(path_puzzle)
        unicost_paths.unicost()
        print "\n --- BURNT PANCAKES UNICOST ---"
        unicost_pancakes = UC.Unicost(pancake_puzzle)
        unicost_pancakes.unicost()

        print "\n\n\n ============ GREEDY SEARCH ============"
        print "\n ---- WATER JUG GREEDY ----"
        greedy_jugs = greedy_search.Greedy(jug_puzzle)
        greedy_jugs.greedy()
        print "\n --- PATH PLANNING GREEDY ---"
        greedy_paths = greedy_search.Greedy(path_puzzle)
        greedy_paths.greedy()
        print "\n --- BURNT PANCAKES GREEDY ---"
        greedy_pancakes = greedy_search.Greedy(pancake_puzzle)
        greedy_pancakes.greedy()


        print "\n\n\n ============ A* SEARCH ============"
        print "\n ---- WATER JUG A* ----"
        astar_jugs = astar_search.AStar(jug_puzzle)
        astar_jugs.astar()
        print "\n --- PATH PLANNING A* ---"
        astar_paths = astar_search.AStar(path_puzzle)
        astar_paths.astar()
        print "\n --- BURNT PANCAKES A* ---"
        astar_pancakes = astar_search.AStar(pancake_puzzle)
        astar_pancakes.astar()


        print "\n\n\n ============ Iterative Deepening A* SEARCH ============"
        print "\n ---- WATER JUG Iterative Deepening A* ----"
        idastar_jugs = iterative_deepening_astar.IDAStar(jug_puzzle, max_depth=4, deepening_constant=4)
        idastar_jugs.idastar()
        print "\n --- PATH PLANNING Iterative Deepening A* ---"
        idastar_paths = iterative_deepening_astar.IDAStar(path_puzzle, max_depth=5, deepening_constant=5)
        idastar_paths.idastar()
        print "\n --- BURNT PANCAKES Iterative Deepening A* ---"
        idastar_pancakes = iterative_deepening_astar.IDAStar(pancake_puzzle, max_depth=5, deepening_constant=5)
        idastar_pancakes.idastar()
Exemple #6
0
 def wj_dfs(self):
     dfs = depth_first_search.DFS(self.waterjugs_puzzle)
     dfs.dfs()
     return
Exemple #7
0
import bfs
import dfs
import iddfs
import astar
"""
main.py declares a start state, a goal state and a size of a board.
It then creates 4 objects, one of each class of 4 different searches,
declaring their arguments, as stated above.
It then calls methods in within these classes to perform the searches.
"""
if __name__ == "__main__":
    start_state = [(4, 1), (4, 2), (4, 3), (4, 4)]
    goal_state = [(2, 2), (3, 2), (4, 2), (1, 1)]
    board_size = (4, 4)
    breadth = bfs.BFS(start_state, goal_state, board_size)
    #breadth.bfs_graph()
    #breadth.bfs_tree()
    depth = dfs.DFS(start_state, goal_state, board_size)
    depth.dfs_graph()
    #depth.dfs_tree_not_randomised()
    #depth.dfs_tree_randomised()
    iddfs = iddfs.IDDFS(start_state, goal_state, board_size)
    #iddfs.iddfs()
    astar = astar.AStar(start_state, goal_state, board_size)
    #astar.astar('distance')
Exemple #8
0
    def run(self):
        # RODA ATE A TECLA ESC SER PRESSIONADA
        keys = pygame.key.get_pressed()
        current_time = pygame.time.get_ticks()
        waittime = 0
        while not keys[pygame.K_ESCAPE]:
            current_time = pygame.time.get_ticks()
            if current_time > waittime:
                pygame.event.clear()
                keys = pygame.key.get_pressed()
                waittime += 20

            # Incrementa Iteracoes
            if pyf.spriteClicked(self.plus):
                if not self.mouse_state_plus:
                    self.mouse_state_plus = True
                    if c.IT >= 1000:
                        c.IT += 1000
                    elif c.IT >= 100:
                        c.IT += 100
                    elif c.IT >= 10:
                        c.IT += 10
                    else:
                        c.IT += 1
                pyf.changeLabel(self.number_shuffler_label, str(c.IT))
            else:
                self.mouse_state_plus = False
            # Decrementa Iteracoes
            if pyf.spriteClicked(self.minus):
                if not self.mouse_state_minus:
                    self.mouse_state_minus = True
                    if c.IT > 1000:
                        c.IT -= 1000
                    elif c.IT > 100:
                        c.IT -= 100
                    elif c.IT > 10:
                        c.IT -= 10
                    elif c.IT > 0:
                        c.IT -= 1
                pyf.changeLabel(self.number_shuffler_label, str(c.IT))
            else:
                self.mouse_state_minus = False
            # Botao Shuffle
            if pyf.spriteClicked(
                    self.shuffle_button
            ):  # ao clicar o sprite do shuffler chama o metodo para embaralhar
                self.initial_position()
                self.shuffler_method(c.IT)

            # Botoes Algoritmos
            move_list = []

            # BFS
            if pyf.spriteClicked(self.BFS_button):
                bfs_alg = bfs.BFS(self.shuffler.get_matrix(), self.nmax)
                start = time.time()
                bfs_alg.BFS_algorithm()
                end = time.time()

                if end - start < 1:
                    pyf.changeLabel(
                        self.text_time2, "{0:.3f}".format(
                            (end - start) * 1000) + "ms")
                else:
                    pyf.changeLabel(self.text_time2,
                                    "{0:.3f}".format(end - start) + "s")

                pyf.changeLabel(
                    self.text_memory2,
                    "{0:.0f}".format(bfs_alg.get_memory_usage()) + " bytes")
                move_list = bfs_alg.get_solution_path()
                self.move_numbers(move_list, True)
                self.shuffler.reset_matrix()

            # DFS
            if pyf.spriteClicked(self.DFS_button):
                dfs_alg = dfs.DFS(self.shuffler.get_matrix(), self.nmax)
                start = time.time()
                dfs_alg.DFS_algorithm()
                end = time.time()

                if end - start < 1:
                    pyf.changeLabel(
                        self.text_time2, "{0:.3f}".format(
                            (end - start) * 1000) + "ms")
                else:
                    pyf.changeLabel(self.text_time2,
                                    "{0:.3f}".format(end - start) + "s")

                pyf.changeLabel(
                    self.text_memory2,
                    "{0:.0f}".format(dfs_alg.get_memory_usage()) + "bytes")
                move_list = dfs_alg.get_solution_path()
                self.move_numbers(move_list, True)
                self.shuffler.reset_matrix()

            # DFS_IT
            if pyf.spriteClicked(self.DFS_IT_button):
                # modificar manualmente a profundidade máxima inicial
                dfs_it_alg = it_dfs.IT_DFS(self.shuffler.get_matrix(),
                                           self.nmax)
                start = time.time()
                dfs_it_alg.IT_DFS_algorithm()
                end = time.time()

                if end - start < 1:
                    pyf.changeLabel(
                        self.text_time2, "{0:.3f}".format(
                            (end - start) * 1000) + "ms")
                else:
                    pyf.changeLabel(self.text_time2,
                                    "{0:.3f}".format(end - start) + "s")

                pyf.changeLabel(
                    self.text_memory2,
                    "{0:.0f}".format(dfs_it_alg.get_memory_usage()) + "bytes")
                move_list = dfs_it_alg.get_solution_path()
                self.move_numbers(move_list, True)
                self.shuffler.reset_matrix()

            # A_STAR H1
            if pyf.spriteClicked(self.A1_button):
                astar_alg = a_star.A_STAR(self.shuffler.get_matrix(),
                                          self.nmax)
                start = time.time()
                astar_alg.a_star_algorithm(utils.chessboard_heuristic)
                end = time.time()

                if end - start < 1:
                    pyf.changeLabel(
                        self.text_time2, "{0:.3f}".format(
                            (end - start) * 1000) + "ms")
                else:
                    pyf.changeLabel(self.text_time2,
                                    "{0:.3f}".format(end - start) + "s")

                pyf.changeLabel(
                    self.text_memory2,
                    "{0:.0f}".format(astar_alg.get_memory_usage()) + "bytes")
                move_list = astar_alg.get_solution_path()
                self.move_numbers(move_list, True)
                self.shuffler.reset_matrix()

            # A_STAR H2
            if pyf.spriteClicked(self.A2_button):
                astar_alg = a_star.A_STAR(self.shuffler.get_matrix(),
                                          self.nmax)
                start = time.time()
                astar_alg.a_star_algorithm(utils.manhattan_heuristic)
                end = time.time()

                if end - start < 1:
                    pyf.changeLabel(
                        self.text_time2, "{0:.3f}".format(
                            (end - start) * 1000) + "ms")
                else:
                    pyf.changeLabel(self.text_time2,
                                    "{0:.3f}".format(end - start) + "s")

                pyf.changeLabel(
                    self.text_memory2,
                    "{0:.0f}".format(astar_alg.get_memory_usage()) + "bytes")
                move_list = astar_alg.get_solution_path()
                self.move_numbers(move_list, True)
                self.shuffler.reset_matrix()

        pyf.endWait()