def main( ) : if validInput( sys.argv ) : fileName = sys.argv[1] board = helper.loadState( fileName ) print "Puzzle: " + fileName time0 = time.clock() if (sys.argv[2] == "bfs" ) : metrics = algorithms.BFS( board ) elif (sys.argv[2] == "dfs" ) : metrics = algorithms.DFS( board ) elif (sys.argv[2] == "id" ) : metrics = algorithms.IDS( board ) elif (sys.argv[2] == "astar") : metrics = algorithms.aStar( board ) time1 = time.clock() delTime = time1-time0 print "Nodes Explored: " + str(metrics[0]) print "Solution Length: " + str(metrics[1]) print "Time Elapsed: " + str(delTime) + " sec" print "" else : print "invalid input" print ""
def plotSearchAlgorithms(dim, p): start = (0, 0) goal = (dim - 1, dim - 1) grid = gd.generateGrid(dim, p) solved = [False for _ in range(5)] solved[0], DFSPath = algos.DFS(grid, start, goal) solved[1], BFSPath, _ = algos.BFS(grid, start, goal) solved[2], BDBFSPath = algos.BDBFS(grid, start, goal) solved[3], AStarPathEuclidean, _ = algos.aStar(grid, start, goal, h.Euc) solved[4], AStarPathManhattan, _ = algos.aStar(grid, start, goal, h.Manhattan) paths = { "DFS": DFSPath, "BFS": BFSPath, "BDBFS": BDBFSPath, "A* Euclidean": AStarPathEuclidean, "A* Manhattan": AStarPathManhattan } # if solvable, then all search algorithms should work, and so plot all of them one at a time if all(solved): print("Close window after each search algorithm to see next one") for i, path in enumerate(paths): print(path) for y, x in paths.get(path): grid[y][x] = 3 pyplot.matshow(grid) pyplot.title(path) pyplot.show() for y, x in paths.get(path): grid[y][x] = 0 # otherwise just show the unsolvable grid else: pyplot.matshow(grid) pyplot.title("Unsolvable") pyplot.show()
def event_check(surface, grid): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() mouse_pos = pygame.mouse.get_pos() row, col = get_mouse_pos(mouse_pos) if row < ST.ROWS and col < ST.COLS: #mouse over grid # Set button colors ST.RUN_COLOR = ST.RUN_DE_COLOR ST.RESET_COLOR = ST.RESET_DE_COLOR ST.RAND_COLOR = ST.RAND_DE_COLOR ST.SL_COLOR = ST.SPEED_DE_COLOR ST.SR_COLOR = ST.SPEED_DE_COLOR ST.RUN_FONT_COLOR = ST.FONT_DE_COLOR ST.RESET_FONT_COLOR = ST.FONT_DE_COLOR ST.RAND_FONT_COLOR = ST.FONT_DE_COLOR ST.SL_FONT_COLOR = ST.FONT_DE_COLOR ST.SR_FONT_COLOR = ST.FONT_DE_COLOR if ST.ALG_CHOICE == 'BFS': ST.BFS_COLOR = ST.ALG_SEL_COLOR ST.ASTAR_COLOR = ST.ALG_DE_COLOR ST.BFS_FONT_COLOR = ST.FONT_DE_COLOR ST.ASTAR_FONT_COLOR = ST.FONT_SEL_COLOR else: ST.BFS_COLOR = ST.ALG_DE_COLOR ST.ASTAR_COLOR = ST.ALG_SEL_COLOR ST.BFS_FONT_COLOR = ST.FONT_SEL_COLOR ST.ASTAR_FONT_COLOR = ST.FONT_DE_COLOR clicked_cube = grid[row][col] if pygame.mouse.get_pressed()[0]: if ST.START_CUBE == None and clicked_cube != ST.END_CUBE: ST.START_CUBE = clicked_cube ST.START_CUBE.set_start() elif ST.END_CUBE == None and clicked_cube != ST.START_CUBE: ST.END_CUBE = clicked_cube ST.END_CUBE.set_end() elif clicked_cube and clicked_cube != ST.START_CUBE and clicked_cube != ST.END_CUBE: clicked_cube.set_wall() if pygame.mouse.get_pressed()[2]: if clicked_cube == ST.START_CUBE: ST.START_CUBE.reset() ST.START_CUBE = None elif clicked_cube == ST.END_CUBE: ST.END_CUBE.reset() ST.END_CUBE = None elif clicked_cube: clicked_cube.reset() else: # mouse over buttons if ST.RUN_BUTTON.collidepoint(mouse_pos): print('HOVERING ON RUN BUTTON') ST.RUN_COLOR = ST.RUN_SEL_COLOR ST.RUN_FONT_COLOR = ST.FONT_SEL_COLOR if event.type == pygame.MOUSEBUTTONDOWN: ST.RUN_COLOR = ST.RUN_DE_COLOR ST.RUN_FONT_COLOR = ST.FONT_DE_COLOR if ST.START_CUBE and ST.END_CUBE: if ST.ALG_CHOICE == 'BFS': alg.BFS(grid, surface) else: alg.aStar(grid, surface) else: print('START AND END NOT SELECTED') elif ST.RESET_BUTTON.collidepoint(mouse_pos): print('HOVERING ON RESET BUTTON') ST.RESET_COLOR = ST.RESET_SEL_COLOR ST.RESET_FONT_COLOR = ST.FONT_SEL_COLOR if event.type == pygame.MOUSEBUTTONDOWN: print('RESET') ST.RESET_COLOR = ST.RESET_DE_COLOR ST.RESET_FONT_COLOR = ST.FONT_DE_COLOR grid = win.init_grid() ST.START_CUBE = None ST.END_CUBE = None elif ST.BFS_BUTTON.collidepoint(mouse_pos): print('HOVERING ON BFS BUTTON') ST.BFS_COLOR = ST.ALG_SEL_COLOR ST.BFS_FONT_COLOR = ST.FONT_DE_COLOR if event.type == pygame.MOUSEBUTTONDOWN: print('SELECT BFS ALG') ST.ALG_CHOICE = 'BFS' ST.ASTAR_COLOR = ST.ALG_DE_COLOR ST.ASTAR_FONT_COLOR = ST.FONT_SEL_COLOR elif ST.ASTAR_BUTTON.collidepoint(mouse_pos): print('HOVERING ON ASTAR BUTTON') ST.ASTAR_COLOR = ST.ALG_SEL_COLOR ST.ASTAR_FONT_COLOR = ST.FONT_DE_COLOR if event.type == pygame.MOUSEBUTTONDOWN: print('SELECT ASTAR ALG') ST.ALG_CHOICE = 'ASTAR' ST.BFS_COLOR = ST.ALG_DE_COLOR ST.BFS_FONT_COLOR = ST.FONT_SEL_COLOR elif ST.RAND_BUTTON.collidepoint(mouse_pos): print('HOVERING ON WALL BUTTON') ST.RAND_COLOR = ST.RAND_SEL_COLOR ST.RAND_FONT_COLOR = ST.FONT_SEL_COLOR if event.type == pygame.MOUSEBUTTONDOWN: print('SELECT RANDOM WALLS') ST.RAND_COLOR = ST.RAND_DE_COLOR ST.RAND_FONT_COLOR = ST.FONT_DE_COLOR grid = win.generate_random_walls(grid) elif ST.S_LEFT.collidepoint(mouse_pos): print('SPEED LEFT') ST.SL_COLOR = ST.SPEED_SEL_COLOR ST.SL_FONT_COLOR = ST.FONT_SEL_COLOR if event.type == pygame.MOUSEBUTTONDOWN: print('select left increase') ST.SL_COLOR = ST.SPEED_DE_COLOR ST.SL_FONT_COLOR = ST.FONT_DE_COLOR if ST.SPEED > 1: ST.SPEED -= 1 ST.DELAY = 500 - (ST.SPEED * ST.SPEED_FACTOR) elif ST.S_RIGHT.collidepoint(mouse_pos): print('SPEED RIGHT') ST.SR_COLOR = ST.SPEED_SEL_COLOR ST.SR_FONT_COLOR = ST.FONT_SEL_COLOR if event.type == pygame.MOUSEBUTTONDOWN: print('select right increase') ST.SR_COLOR = ST.SPEED_DE_COLOR ST.SR_FONT_COLOR = ST.FONT_DE_COLOR if ST.SPEED < 10: ST.SPEED += 1 ST.DELAY = 500 - (ST.SPEED * ST.SPEED_FACTOR) else: print('OFF RUN BUTTON') ST.RUN_COLOR = ST.RUN_DE_COLOR ST.RESET_COLOR = ST.RESET_DE_COLOR ST.RAND_COLOR = ST.RAND_DE_COLOR ST.SL_COLOR = ST.SPEED_DE_COLOR ST.SR_COLOR = ST.SPEED_DE_COLOR ST.RUN_FONT_COLOR = ST.FONT_DE_COLOR ST.RESET_FONT_COLOR = ST.FONT_DE_COLOR ST.RAND_FONT_COLOR = ST.FONT_DE_COLOR ST.SL_FONT_COLOR = ST.FONT_DE_COLOR ST.SR_FONT_COLOR = ST.FONT_DE_COLOR if ST.ALG_CHOICE == 'BFS': ST.ASTAR_COLOR = ST.ALG_DE_COLOR ST.ASTAR_FONT_COLOR = ST.FONT_SEL_COLOR else: ST.BFS_COLOR = ST.ALG_DE_COLOR ST.BFS_FONT_COLOR = ST.FONT_SEL_COLOR return grid
import algorithms from heuristics import getHeuristic if __name__ == "__main__": # Defina o estado inicial e o estado final estadoInicial = None estadoFinal = None # Defina qual heuristica utilizar heuristica = getHeuristic # A* print("Algoritmo A*...") caminho = algorithms.aStar(estadoInicial, estadoFinal, heuristica) for estado in caminho: print('Estado:', estado, 'Heurística:', heuristica(estado, estadoFinal)) print("Quantidade de Movimentos:", len(caminho))
def run(): # Create graph and connect it. g = Graph(WIDTH, HEIGHT, DEPTH, SURF) connectGraph(g) g.SURF = SURF g.WIDTH = WIDTH g.HEIGHT = HEIGHT g.paths = {} # Shuffle netlist. random.shuffle(netlist) # Disconnect gates. disconnectVertex(g, gateList) for i in gateList: g.vertDict[i].gate = True # Compute number of paths per gate. pGate = numberOfPaths(netlist, gateList) selectedNeighbors = [] for i in range(len(pGate)): cur = g.vertDict[gateList[i]] if len(cur.adjacent) < pGate[i]: selectedNeighbors.append([]) continue selectedNeighbors.append(random.sample(cur.adjacent, pGate[i])) disconnectVertex(g, selectedNeighbors[i]) # Mark different paths with p p = 1 # Count found paths f = 0 # Count costs total c = 0 totalTime = 0 # Keep track of what nodes have 'started' in a path startList = [] """ SOLVE """ for n in netlist: startTime = time.time() start = g.vertDict[gateList[n[0]]] target = g.vertDict[gateList[n[1]]] # Allow connections to target gate (but only from non-gates and from # vertices without a pre-existing path. connectVertex(g, target.id) # Allow connections to neighbors of the target and start gates, # exept from nodes with a path for nb in computeNeighbors(g, start.id): if not g.vertDict[nb].path and not g.vertDict[nb].gate: connectNonPathVertex(g, nb) for nb in computeNeighbors(g, target.id): if not g.vertDict[nb].path and not g.vertDict[nb].gate: connectNonPathVertex(g, nb) # Compute path between start and target. algorithms.aStar(g, start, target) # Extract the previously computed path from graph g path = [] path.append(target.id) tracePath(g, target, path) # Disconnect connections to the vertices in path disconnectVertex(g, path) # Assign all vertices in the path (not the gates) the path id for i in path[1:-1]: g.vertDict[i].path = p p += 1 # Disconnect connections to specific neighbors of start and target pGate[n[0]] -= 1 if pGate[n[0]]: disconnectVertex(g, selectedNeighbors[gateList.index(start.id)]) pGate[n[1]] -= 1 if pGate[n[1]]: disconnectVertex(g, selectedNeighbors[gateList.index(target.id)]) g.paths[p] = path if len(path) > 1: f += 1 # Prepare graph for next search. for v in g: v.previous = None g.cost = 0 for v in g: if v.path and not v.gate: g.cost += 1 g.found = f return g
fringe = [] expanded = [] pathFound = [] # Call algorithms if algo == 'B': pathFound = algorithms.bfs(root, goalState, forbidden, fringe, expanded) elif algo == 'D': pathFound = algorithms.dfs(root, goalState, forbidden, fringe, expanded) elif algo == 'I': pathFound = algorithms.ids(root, goalState, forbidden, fringe, expanded) elif algo == 'G': pathFound = algorithms.greedy(root, goalState, forbidden, fringe, expanded) elif algo == 'A': pathFound = algorithms.aStar(root, goalState, forbidden, fringe, expanded) elif algo == 'H': pathFound = algorithms.hillClimbing(root, goalState, forbidden, fringe, expanded) else: sys.exit(0) # Format output foundSolution = True if expanded[-1].data != goalState: foundSolution = False pathFoundValues = [] for i in range(len(pathFound)): pathFoundValues.append("".join(pathFound[i].data))
for line in fh.readlines(): line = line.strip() line = line.split(" ") for word in line: initial_state.append(int(word)) # defining the # of rows and finding the # of column rows = 2 column = int(len(initial_state) / rows) #call boundaries function first_row, last_row, first_column, last_column = nodes.boundaries( initial_state, rows, column) #save the starting time start = timeit.default_timer() #Call aStar for h1 result, closed = algorithms.aStar(initial_state, goal_1, goal_2, heuristic.h1) # ##################################### For Analysis #################################### # if result == None : # Tot_Len_No_Sol_aStar_h1+=1 # else: # Tot_Len_Sol_aStar_h1 += len(result) # Tot_Len_Sch_aStar_h1 += len(closed) ####################################################################################### #create the solution and search files output.giveOutput(result, closed, counter, "astar", 'h1') #save the starting time start = timeit.default_timer() #Call aStar for h2 result, closed = algorithms.aStar(initial_state, goal_1, goal_2,