def main_1(): dim = 3 goal = Puzzle( np.insert(np.arange(1, dim * dim), dim * dim - 1, 0).reshape(dim, dim)) time1 = [] time2 = [] space1 = [] space2 = [] for i in range(15): while True: start = Puzzle( np.random.permutation(np.arange(dim * dim)).reshape( (dim, dim))) if start.solvable(): break t_1 = time.time() p1 = Astar('manhattan', start, goal) h1 = p1.search() t_2 = time.time() t_f = t_2 - t_1 time1.append(t_f) space1.append(np.mean([j for i, j in h1])) t_11 = time.time() p2 = Astar('hamming', start, goal) h2 = p2.search() t_22 = time.time() t_ff = t_22 - t_11 time2.append(t_ff) space2.append(np.mean([j for i, j in h2])) a = plt.plot(time1, 'blue') b = plt.plot(time2, 'red') plt.legend(['Manhattan', 'Hamming']) plt.xlabel('puzzle') plt.ylabel('tiempo') plt.title('Tiempo A*') plt.show() a = plt.plot(space1, 'blue') b = plt.plot(space2, 'red') plt.legend(['Manhattan', 'Hamming']) plt.xlabel('puzzle') plt.ylabel('espacio') plt.title('Espacio A*') plt.show() print(time1) print(space1) print(time2) print(space2)
def run(n, a, display): # s = ( (1,2,4,7,5,3,0,8,6),(2,0) ) # t = ( (1,2,3,4,5,6,7,8,0),(2,2) ) for i in range(n * n): if a[i] == 0: idx = i s = (tuple(a), (idx // n, idx % n)) a = [] for i in range(1, n * n): a.append(i) a.append(0) t = (tuple(a), (n - 1, n - 1)) algo = Astar(n, s, t) while True: if not algo.found: idx = algo.search() drawBoard(n, idx[0], display) if idx == t: path = algo.createPath() time.sleep(3) for idx in path: drawBoard(n, idx[0], display) time.sleep(2) for event in pygame.event.get(): if event.type == pygame.QUIT: exit()
def test_astar1(self): nodes1 = { "A": [("B", 2), ("D", 3)], "B": [("A", 2), ("D", 5), ("C", 2)], "C": [("B", 2), ("F", 1)], "D": [("A", 3), ("B", 5), ("E", 8), ("G", 7)], "E": [("D", 8), ("G", 5)], "F": [("C", 1), ("H", 3)], "G": [("E", 5), ("D", 7), ("H", 2)], "H": [("G", 2), ("F", 3)] } astar1 = Astar(nodes1, "A", "H") result1 = astar1.search() self.assertEqual(result1, ['A', 'B', 'C', 'F', 'H'])
def draw_random_graph(n): """ vytvoří náhdný graf o n nodech a přetvoří ho do datové struktury grafu pomocí slovníku a nalezne v něm cestu""" try: p = 0.15 if n < 80 else 0.05 G = ER(n, p) a = nx.convert.to_dict_of_lists(G) dict_values = a.items() new_a = {str(key): value for key, value in dict_values} dict_values2 = new_a.items() for key, value in dict_values2: new_a[key] = [(str(v), random.randint(1, 2)) for v in value] astar = Astar(new_a, str(random.randint(0, n)), str(random.randint(0, n))) #print(astar.search()) shortest_path = [int(i) for i in astar.search()] print(shortest_path) node_colors = [ "blue" if n in shortest_path else "red" for n in G.nodes() ] pos = nx.spring_layout(G) nx.draw_networkx(G, pos, node_color=node_colors) for i in range(0, len(shortest_path)): if i + 1 == len(shortest_path): break nx.draw_networkx_edges(G, pos, edgelist=[(shortest_path[i], shortest_path[i + 1])], edge_color="blue", width=2) except: print("cesta neexistuje")
def animate_astar(self): a,path =Astar.search(self,self.maze,1,self.start_node,self.end_node) for a in a: pygame.draw.rect(self.screen,self.less_red,(a.position[0]*30,a.position[1]*30,29,29)) pygame.display.update() self.clock.tick(60) draw = [] for i,j in enumerate(path): for k,l in enumerate(j): if l is not -1: draw.append((i,k)) for i in draw[::-1]: pygame.draw.rect(self.screen,self.red,(i[0]*30,i[1]*30,29,29)) self.clock.tick(200) pygame.display.update()
def test_astar2(self): nodes2 = { "A": [("B", 2), ("E", 2)], "B": [("A", 2), ("C", 2)], "C": [("B", 2), ("D", 2)], "D": [("C", 2), ("G", 2)], "E": [("A", 2), ("J", 3)], "F": [("B", 2), ("K", 2), ("G", 2)], "G": [("F", 2), ("D", 2), ("L", 4), ("H", 3)], "H": [("G", 3), ("I", 2)], "I": [("H", 2), ("M", 3)], "J": [("E", 3), ("O", 4)], "K": [("F", 2), ("O", 2)], "L": [("G", 4), ("M", 1), ("P", 5)], "M": [("I", 3), ("L", 1)], "O": [("K", 2), ("J", 4)], "P": [("L", 5)] } astar2 = Astar(nodes2, "A", "P") result2 = astar2.search() self.assertEqual(result2, ['A', 'B', 'C', 'D', 'G', 'L', 'P'])
use_astar = True elif op in ("-d", "--dstar"): use_dstar = True if use_astar is None and use_dstar is None: print("Error: You need to select one algorithm to plan path: Astar or Dstar!") sys.exit() else: print('Space: ', space_boundary) print('Agents number: ', agents_num) print('Safe Radius: ', safe_R) print('Seed: ', seed) env = Env(space_boundary = space_boundary, agents_num=agents_num, seed = seed, safe_R = safe_R) if use_astar: print('Algorithm: Astar') astar = Astar(env.agents_pos[:, 0], env.agents_targ[:, 0], env.agents_pos, env.space_boundary, env.walk_dirs) pathData = astar.search() pathsData = {"Plan Path": pathData} draw_path(env.space_boundary ,env.agents_pos, pathsData, env.agents_targ, title = "Path Plan with A*") elif use_dstar: print('Algorithm: Dstar') space_map = Map(env.space_boundary, env.walk_dirs) dstar = Dstar(space_map, env.space_boundary) paths = dstar.search( env.agents_pos[:, 0], env.agents_targ[:, 0], env.agents_pos) pathsData = {"Path Without Obstacle": paths[0], "Path With Obstacle": paths[1]} draw_path(env.space_boundary ,env.agents_pos, pathsData, env.agents_targ, title = "Path Plan with D*") print("Finish!") sys.exit()
numlist = line.split(' ') if len(numlist) < 15: return problems.append(Puzzle([int(x) for x in numlist[1:]])) print('%5s%10s%10s%10s%10s' % ('#prob', '#exp', '#gen', '|sol|', 'tiempo')) problems = [] load_problems(problems) total_time = 0 total_cost = 0 total_expansions = 0 total_problems = len(problems) # cambiar si quieres menos problemas for prob in range(0, total_problems): init = problems[prob] # problema aleatorio s = Astar(init, heuristic, 1) result = s.search() print('%5d%10d%10d%10d%10.2f' % (prob + 1, s.expansions, len( s.generated), result.g, s.end_time - s.start_time)) total_time += s.end_time - s.start_time total_expansions += s.expansions total_cost += result.g if show_solutions: print(result.trace()) print('Total time: %.3f' % (total_time)) print('Expansiones totales: %d' % (total_expansions)) print('Total cost: %.3d' % (total_cost))
# ], (8,12), (2,6)) # start = State(arena.start, None, "right", None, 0) arena_str = input() arena_obj = json.loads(arena_str) arena = Arena(arena_obj["world"], (arena_obj["snake"]["x"], arena_obj["snake"]["y"]), (arena_obj["food"]["x"], arena_obj["food"]["y"])) start = State(arena.start, None, arena_obj["direction"], None, 0) end = State(arena.food, None, None, None, None) if (arena_obj["method"] == "dijkstra"): solution = DSP.search(arena, start, end) elif (arena_obj["method"] == "greedy"): solution = GBFS.search(arena, start, end) else: solution = Astar.search(arena, start, end) result = {} if solution == None: result["status"] = "failure" result["message"] = "The snake cannot reach its food" else: result["status"] = "success" path = Utils.get_path(solution) path_str = "" for step in path: path_str += step.print(recursive=False) + "," path_str = "[" + path_str[:-1] + "]" result["solution"] = json.loads(path_str) print(json.dumps(result))
def main(): pygame.init() # Taking input from user n = int(input("Enter grid size:")) Sx, Sy = [int(x) for x in input("Enter knight coords:").split()] Tx, Ty = [int(x) for x in input("Enter queen coords:").split()] # Setting up the screen and images res = (n*pixels,n*pixels) gameDisplay = pygame.display.set_mode(res) queen = pygame.image.load("queen.png") knight = pygame.image.load("knight.png") # Initializing the board and the algo createChessboard(gameDisplay,n) placeEntity(queen,Ty,Tx,gameDisplay) d = Astar(n,Sx,Sy,Tx,Ty) # game loop running = True while running: if not d.found: # returns current node and previous node t, prev = d.search() placeEntity(knight,t[1],t[0],gameDisplay) markVisited(prev[1],prev[0],gameDisplay) pygame.display.update() time.sleep(.2) if t == (Tx,Ty): createChessboard(gameDisplay,n) placeEntity(queen,Ty,Tx,gameDisplay) placeEntity(knight,Sy,Sx,gameDisplay) path = d.createPath() for i,j in path[1:]: markVisited(j,i,gameDisplay) pygame.display.update() continue for event in pygame.event.get(): if event.type == pygame.QUIT: running = False break print("Target position ",(Tx,Ty)," reached: ",d.visited[Tx][Ty]) pygame.quit()