def compareHeuristics(): timeList = [] while (len(timeList) < 10): time.time() signal.signal(signal.SIGALRM, handler) signal.alarm(1) map = None map = generateMap(int(100),0.15) # Setting up map map[0][0]=0 map[len(map)-1][len(map)-1] = 0 start_time = time.time() time.time() signal.signal(signal.SIGALRM, handler) signal.alarm(1) try: path = astar(map,1) except IOError: path = None if path is None: print("path does not exist") else: print(path) print("--- %s seconds ---" % (time.time() - start_time)) timeList.append((time.time() - start_time)) print(timeList) print("Avg time: "+str(sum(timeList)/len(timeList)))
def get_distance_from_to_key(grid, from_key, to_key): ''' BFS to find distance from one key to another ''' global DIRECTIONS # Locations current_location = from_key[0] end_location = to_key[0] def is_goal_fn(node): return node == end_location def heuristic(node: Node): return node.manhattan_distance(end_location) def cost(a, b): return 1 visited = set() def get_neighbors(node): neighbors = [] for d in DIRECTIONS: new = node + d if new not in visited and grid[new] != '#': neighbors.append(new) visited.add(new) return neighbors def get_key_fn(node: Node): return node.to_tuple() return (end_location, astar(current_location, is_goal_fn, heuristic, cost, get_neighbors, get_key_fn))
def calculateAvgPathLength(): i = 100 i2 = i solvable = 0 unsolvable = 0 pathLen = [] while (i > 0): map = None map = generateMap(int(100),0.3) printMap(map) map[0][0] = 0 map[99][99] = 0 time.time() signal.signal(signal.SIGALRM, handler) signal.alarm(1) try: path = astar(map,int(1)) except IOError: time.time() unsolvable = unsolvable + 1 continue print(path) if path is None: unsolvable = unsolvable + 1 else: pathLen.append(len(path)) solvable = solvable + 1 i=i-1 print("Generated: "+ str(i2) +"maps and # solvable: " + str(solvable)) print(pathLen) print("Avg Path Length: "+ str(sum(pathLen)/len(pathLen)))
def genetic_algorithm(algo): dim = 15 prob = .4 count = 0 # Population will hold our valid hard mazes population = [] # While loop halts when we have 100 hard mazes in the population while count != 100: # create a random map map = generateMap(dim, prob) if (algo == "dfs"): result = dfs(map) else: temp = copy.deepcopy(map) temp[0][0] = 0 temp[len(temp) - 1][len(temp) - 1] = 0 start_time = time.time() signal.signal(signal.SIGALRM, handler) signal.alarm(1) try: result = astar(temp, 0) except IOError: result = None if (result == None): continue else: # if w ehave a valid solvable maze then add to population result.append(map) population.append(result) count = count + 1 #print("Population count "+ str(count)) count = 0 # while loop halts once we have costruced 50 valid children while count != 50: # sort the population by our heuristic and reverse so the highest score is first population = sorted(population, key=itemgetter(1), reverse=True) # dad is the best hard maze we have dad = population[0] # mom is the second best hard maze we have mom = population[1] # set up child as 2D array which is how enivroments are used in backend kid = [[0 for x in range(dim)] for y in range(dim)] map1 = dad[2] map2 = mom[2] # Thsi snippet of code perform recombination # we take the first half of dad and second half of mom and populate the child accrodingly go = 0 stop = (dim * dim) / 2 for x in range(dim): for y in range(dim): if (go < stop): kid[x][y] = map1[x][y] else: kid[x][y] = map2[x][y] go = go + 1 # We run whichever algo the user had chosen on the newly created kid maze if algo == "dfs": final = dfs(kid) else: kid[0][0] = 0 kid[len(kid) - 1][len(kid) - 1] = 0 start_time = time.time() signal.signal(signal.SIGALRM, handler) signal.alarm(1) try: final = astar(kid, 0) except IOError: final = None # if child is not solvable we get rid of dad and try again with a differnt set of mazes if (final == None): population.pop(0) # if child is valid we append the kid and pop the worst in popualtion # Later the kid will be placed in the right position during out sorting phase else: population.pop() population.append(final) count = count + 1 # we return the most fit maze or hardest maze in our population as our answer return population[0]
def main(): inputDim = input("Enter dimension of map: ") inputP = input("Enter probability 0<p<1: ") map=generateMap(int(inputDim),float(inputP)) mazeVisual(map) count = 2 search = input("Choose search option: visuals, dfs, bfs, a*, bi-bfs, all \n") if (search == "dfs"): start_time = time.time() result = dfs(map)[0] print("--- %s seconds ---" % (time.time() - start_time)) if (result == None): print("NO DFS PATH FOUND") visual(map, result[0], "DFS", count) elif (search == "bfs"): start_time = time.time() result = bfs(map) print("--- %s seconds ---" % (time.time() - start_time)) if (result == None): print("NO BFS PATH FOUND") return visual(map, result, "BFS", count) elif (search == "a*" or search == "a" ): # Setting up map map[0][0]=0 map[len(map)-1][len(map)-1] = 0 flag = input("Enter number: (0) Manhattan (1) Euclidean \n") # 1 for Euclidean # 0 for Manhattan start_time = time.time() time.time() signal.signal(signal.SIGALRM, handler) signal.alarm(25) try: path = astar(map,flag)[0] except IOError: path = None if path is None: print("A* path does not exist") return #else: print("--- %s seconds ---" % (time.time() - start_time)) result = path visual(map, result, "A*", count) elif (search == "bi-bfs"): start_time = time.time() result = bi_bfs(map) print("--- %s seconds ---" % (time.time() - start_time)) if (result == None): print("NO BI-BFS PATH FOUND") visual(map, result, "BI-DIRECTIONAL BFS", count) elif (search == "all"): start_time = time.time() path = dfs(map)[0] print("dfs path length: "+ str(len(path))) print("--- dfs took %s seconds ---" % (time.time() - start_time)) start_time = time.time() path = bfs(map) print("bfs path length: "+ str(len(path))) print("--- bfs took %s seconds ---" % (time.time() - start_time)) # Setting up map map[0][0]=0 map[len(map)-1][len(map)-1] = 0 start_time = time.time() time.time() signal.signal(signal.SIGALRM, handler) signal.alarm(3) try: path = astar(map,0)[0] except IOError: path = None if path is None: print("NO PATH FOUND FOR A* MANHATTAN") else: print("a* manhatttan path length: "+ str(len(path))) print("--- a* manhatttan took %s seconds ---" % (time.time() - start_time)) # Setting up map map[0][0]=0 map[len(map)-1][len(map)-1] = 0 start_time = time.time() time.time() #signal.signal(signal.SIGALRM, handler) #signal.alarm(3) try: path = astar(map,1)[0] except IOError: path = None if path is None: print("NO PATH FOUND FOR A* EUCLIDEAN") else: print("a* euclidean path length: "+ str(len(path))) print("--- a* euclidean took %s seconds ---" % (time.time() - start_time)) start_time = time.time() path = bi_bfs(map) print("bi-bfs path length: "+ str(len(path))) elif (search == "visuals"): temp = copy.deepcopy(map) temp[0][0]=0 temp[len(map)-1][len(map)-1] = 0 result1 = dfs(map) result2 = bfs(map) result3 = bi_bfs(map) result4 = astar(temp, 0) result5 = astar(temp, 1) if (result1 == None): print("NO DFS PATH FOUND") else: visual(map, result1[0], "DFS", count) count = count + 1 if (result2 == None): print("NO BFS PATH FOUND") else: visual(map, result2, "BFS", count) count = count + 1 if (result3 == None): print("NO BI-BFS PATH FOUND") else: visual(map, result3, "BI-BFS", count) count = count + 1 if (result4 == None): print("NO A* EUCLIDEAN PATH FOUND") else: visual(temp, result4[0], "A* EUCLIDEAN", count) count = count + 1 if (result5 == None): print("NO A* MANHATTAN PATH FOUND") else: visual(temp, result5[0], "A* MANHATTAN", count) count = count + 1 plt.show()
empty = node[1] neighbors = [] # move in every direction, create a new state where the empty node is at current + d for d in DIRECTIONS: new_empty = empty + d if new_empty.x > 36 or new_empty.x < 0 or new_empty.y > 24 or new_empty.y < 0: continue if new_empty in full_nodes: continue # if wanted data is the one we just moved, reflect that in the new node new_wanted = wanted if new_empty == wanted: new_wanted = empty new = (new_wanted, new_empty) neighbors.append(new) return neighbors s = time.time() answer = astar(start, is_goal_fn, heuristic_fn, lambda x, y: 1, get_neighbors_fn, get_key_fn) print(answer) print(time.time() - s)
# elevator cant be outside of building if elevator + d < 0 or elevator + d > 3: continue # create a copy of the existing state so that we don't share references of sets within new_floors = copy_state(floors) # try to make the move for c in combo: new_floors[elevator].remove(c) new_floors[elevator + d].add(c) # don't add if invalid config if not is_valid(new_floors): continue neighbors.append( (new_floors, elevator + d, current_steps + 1)) return neighbors steps = astar(start=(floors, 0, 0), is_goal_fn=lambda x: is_done(x[0]), heuristic_fn=heuristic, cost_fn=lambda a, b: 1, get_neighbors_fn=get_neighbors, get_key_fn=lambda x: (get_string_rep(x[0]), x[2])) print(steps) print(time.time() - start)
def get_shortest_path(grid, starting_position, distance_map): ''' Get shortest path to getting all keys ''' #### # A* NODE IS TUPLE -> (string of current keys, current cost, current location) # Indexed by: (0 , 1 , 2 ) #### num_keys = sum(1 for i in grid.values() if i in string.digits) min_dist = 100000 for this_char in distance_map: distances = distance_map[this_char] for other_char_key in distances: other_char_pos, distance_to_other = distance_map[this_char][ other_char_key] if distance_to_other < min_dist: min_dist = distance_to_other finalNode = None def is_goal_fn(node): nonlocal finalNode is_goal = len(node[0]) == num_keys + 1 if is_goal: finalNode = node return is_goal def heuristic(node): return min_dist * (num_keys - len(node[0])) def cost(a, b): return b[1] - a[1] def get_neighbors(node): keys_acquired = set(node[0]) this_char = grid[node[2]] distances_from_here = distance_map[this_char] keys_available = [] for other_char_key in distances_from_here: if other_char_key[1] == '.' and len(keys_acquired) != num_keys: continue other_char_pos, distance_to_other = distance_map[this_char][ other_char_key] # If all of the keys on this path have been acquired, it's a viable path if other_char_key[1] not in keys_acquired: keys_available.append( (other_char_pos, distance_to_other, other_char_key[1])) neighbors = [] for key_point, distance_to, key_char in keys_available: new_node = ("".join(sorted(node[0])) + key_char, node[1] + distance_to, key_point) neighbors.append(new_node) return neighbors def get_key_fn(node): return node[0] return (astar(("", 0, starting_position), is_goal_fn, heuristic, cost, get_neighbors, get_key_fn), finalNode)
(not is_left and direction == 0)): tile_array = node[0][:] new_tile = (possible_next_tile, ori_ind) tile_array.append(new_tile) remaining_tiles = node[1] - set([possible_next_tile]) new_node = (tile_array, remaining_tiles) neighbors.append(new_node) break return neighbors grid_layout_flat = astar(start=entry, is_goal_fn=is_goal_fn, heuristic_fn=heuristic_fn, cost_fn=lambda a, b: 1, get_neighbors_fn=get_neighbors_fn, get_key_fn=lambda n: str(n), include_final_node=True)[1][0] final = array([]) gridz = [grids[i[0]][i[1]] for i in grid_layout_flat] for y in range(width): row = array([]) for x in range(width): grid_no, ori = grid_layout_flat[x + (width * y)] cell = grids[grid_no][ori] cell = cell[1:-1]