def runFastTests(): puzzle = puzzle15_32 goal = puzzle15_goal print(puzzle) solve_puzzle8_21_1 = AStar(puzzle, goal, 0) solve_puzzle8_21_2 = AStar(puzzle, goal, 1) solve_puzzle8_21_3 = AStar(puzzle, goal, 0, True) solve_puzzle8_21_4 = AStar(puzzle, goal, 1, True) print("\nSAMPLE PUZZLE STRAIGHT LINE") solution = solve_puzzle8_21_1.search() print("Moves Taken: " + str(len(solution.moves)) + " moves") solution.printSolution() print("\nSAMPLE PUZZLE MANHATTAN") solution = solve_puzzle8_21_2.search() print("Moves Taken: " + str(len(solution.moves)) + " moves") solution.printSolution() print("\nSAMPLE PUZZLE STRAIGHT LINE WITH LINEAR CONFLICT") solution = solve_puzzle8_21_3.search() print("Moves Taken: " + str(len(solution.moves)) + " moves") solution.printSolution() print("\nSAMPLE PUZZLE MANHATTAN WITH LINEAR CONFLICT") solution = solve_puzzle8_21_4.search() print("Moves Taken: " + str(len(solution.moves)) + " moves") solution.printSolution()
def main(): # Task 1 map = Map_Obj(1) start_state = (map, map.get_start_pos()[0], map.get_start_pos()[1]) a_star = AStar(start_state, walking_distance, generate_adjacent_states, goal_evaluate) node_path = a_star.run() pos_path = [] for node in node_path: pos_path.append([node.state[1], node.state[2]]) print('Positions in the path of task 1:') print(pos_path) visualise_path_map(map, pos_path) # Task 2 map = Map_Obj(2) start_state = (map, map.get_start_pos()[0], map.get_start_pos()[1]) a_star = AStar(start_state, walking_distance, generate_adjacent_states, goal_evaluate) node_path = a_star.run() pos_path = [] for node in node_path: pos_path.append([node.state[1], node.state[2]]) print('Positions in the path of task 2:') print(pos_path) visualise_path_map(map, pos_path)
def _add_new_env(self): ''' Add a new environment to the environment list. ''' # Generate a random map and make sure that all non-obstacle # positions can reach the goal. while True: model_settings = { 'height': self.height, 'width': self.width, 'obs_count': self.num_obstacle, 'random_seed': self.seed, 'device': self.device } self.seed += 1 new_env = PathPlanningEnv(**model_settings) astar = AStar(new_env.grid[2, :, :], (new_env.goal_row, new_env.goal_col)) all_reachable = True for row in range(self.height): for col in range(self.width): if new_env.grid[2,row,col] == 0 \ and new_env.grid[1,row,col] != 1 \ and not astar.plan(row, col): all_reachable = False if all_reachable: break self.envs.append(new_env)
def call_AStar(output_file): """ AStar ~ Deschid fisierul ~ Verific datele de intrare ~ Creez obiectul de tip AStar ~ Apelez functia Solve ~ Afisez solutia """ g = open((output_folder + '/' + output_file), 'w') if not isInRange(matrix, robinet_x, robinet_y) or not isInRange( matrix, canal_x, canal_y): g.write('Datele de input sunt gresite. Problema nu are solutii') else: g.write('AStar\n') for heuristic in heuristics: g.write('\n\n\n' + heuristic + '\n\n') a = AStar(heuristic, deepcopy(matrix), robinet_x, robinet_y, canal_x, canal_y, timeout) paths = a.Solve(solutions_number) print_paths(paths, g) g.write( '\n\n\n\n ______________________________________________________ \n\n\n\n' ) g.close()
def main(): io_handler = IOHandler() input_values = io_handler.read_input_file() strategy = io_handler.get_strategy strategy_param = io_handler.get_strategy_param if strategy == 'bfs': bfs = BFS(strategy_param, input_values) bfs.solve_puzzle() io_handler.write_result_file(bfs.solution_length, bfs.solution_path) io_handler.write_stat_file(bfs.solution_length, bfs.number_of_visited_nodes, bfs.number_of_processed_nodes, \ bfs.recursion_depth, bfs.solution_time) elif strategy == 'dfs': dfs = DFS(strategy_param, input_values) dfs.solve_puzzle() if dfs.solution_length == -1: io_handler.write_wrong_result_file(dfs.solution_length) io_handler.write_wrong_stat_file(dfs.solution_length) else: io_handler.write_result_file(dfs.solution_length, dfs.solution_path) io_handler.write_stat_file(dfs.solution_length, dfs.number_of_visited_nodes, dfs.number_of_processed_nodes,\ dfs.recursion_depth, dfs.solution_time) elif strategy == 'astr': a_star = AStar(strategy_param, input_values) a_star.solve_puzzle() io_handler.write_result_file(a_star.solution_length, a_star.solution_path) io_handler.write_stat_file(a_star.solution_length, a_star.number_of_visited_nodes, \ a_star.number_of_processed_nodes, a_star.recursion_depth, a_star.solution_time) else: print('nieprawdiłowa nazwa strategii')
def newPath2(self, startTime): timeList = [] for queue in self.queueList: timeList.append(queue.endTime) newMap = Array2D.Array2D(self.width, self.height) for x in range(len(self.destList)): newAstar = AStar.AStar(newMap, self.startPoint, self.destList[x].position) newAstar.addAllObastacleArea(self.obstacleList) pathList = newAstar.start() if pathList is not None and len(pathList) > 0: print("路径重新规划") else: print("位置已在障碍物区域内部,无法重新规划") # user.inFlag = False distance = self.calPathLength(pathList) totalTime = round(distance / common_utils.calRandSpeed(), 3) * 1000 # 重新规划到达闸机时间 destTime = startTime + totalTime print("calculate destTime:", x, ":", destTime) # 将各闸机口给出的时间 存储到临时列表中,方便计算最早到闸机口时间 if destTime > timeList[x]: timeList[x] = destTime print("updated destTime:", timeList[x]) minTime = 0 for x in range(len(timeList)): if minTime == 0: minTime = timeList[x] if minTime > timeList[x]: minTime = timeList[x] index = x return self.destList[index].id
def use_lizard(self, action, game_map, player_info): max_ = speed_bracket[player_info.damage] if action == Commands.USE_LIZARD: if not itemize_command(action) in player_info.power_ups: return { "player_info": player_info, "game_map": game_map, "progression": False, "additional_score": -1000 } y = player_info.position.y x = player_info.position.x + player_info.speed progress = True # goes deeper into the game tree? if not x in game_map[y].keys(): x = [i for i in game_map[y].keys()][-1] progress = False a = AStar() path = a.forward(player_info.position, Position(y, x), game_map) p_speed = 0 # plaussible speeds if not player_info.boosting: if "BOOST" in player_info.power_ups: p_speed = max_ - player_info.speed else: n_speed = max_ if player_info.boosting else speeds[ player_info.speed].right p_speed = n_speed if n_speed else player_info.speed score = 0 if True: score += 4 player_info.power_ups.remove(itemize_command(action)) score -= abs((player_info.position.x + player_info.speed) - (player_info.position.x + p_speed)) score -= abs((player_info.position.x + player_info.speed) - [i for i in game_map[y].keys()][-1]) # walking the paths to collect damages/speed-deduction and points path_walk = self.walk_path(path, game_map, is_lizard=True) score += len( path_walk["powerups"] ) * 4 # <-- actually using of powerups will justify this more score += self.compute_wall_damages(path_walk["obstacles"], player_info) player_info.power_ups += path_walk["powerups"] if progress: player_info.position = Position(y, x) return { "player_info": player_info, "game_map": game_map, "progression": progress, "additional_score": score }
def test_astar(tests): astar = AStar() for t in tests: astar.test(t[0], t[1]) astar.runTests() print_break()
def __init__(self, side, field: np.ndarray, my_player, enemy): self.side = side self.me = my_player self.enemy: PublicPlayer = enemy self.field = field self.a_star = AStar() self.obj_dist = ObjectDistance(self.field, self.side) self.defence_line = self.get_defenceline()
def tournament(args): i, steps, (name_a, h_a), (name_b, h_b) = args boards = Board.scrambled(steps, True) # fixed length agents = [AStar(h) for h in [h_a, h_b]] results = [agent.run(boards[-1]) for agent in agents] print(f"Round {i}, {name_a}: {results[0][1:]}") print(f"Round {i}, {name_b}: {results[1][1:]}") return results
def act(self, ant): # Create a path to the home node at 0,0 aStar = AStar(ant.tiles, ant.tiles[ant.x][ant.y], ant.tiles[0][0]) path = aStar.takeStep() if path != None: while aStar.done == False: path = aStar.takeStep() ant.path = path
def start_activity(self): self.markov = False self.place_to_go = self.getPlaceToGo() self.movements = AStar(self, self.pos, self.place_to_go).process() time_in_state = self.model.getTimeInState(self)[list( self.positionByState.keys()).index(self.state)] self.time_activity = int(time_in_state * 60 * 100 / self.model.clock.timeByStep)
def accelerate(self, action, game_map, player_info): max_ = speed_bracket[player_info.damage] if action == Commands.ACCELERATE: n_speed = None if not player_info.boosting: n_speed = speeds[player_info.speed].right if player_info.boosting or not n_speed or n_speed > max_: return { "player_info": player_info, "game_map": game_map, "progression": None, "additional_score": -1000 } player_info.speed = n_speed y = player_info.position.y x = player_info.position.x + n_speed progress = True # goes deeper into the game tree? if not x in game_map[y].keys(): x = [i for i in game_map[y].keys()][-1] progress = False a = AStar() path = a.forward(player_info.position, Position(y, x), game_map) p_speed = 0 # plaussible speeds if not player_info.boosting: if "BOOST" in player_info.power_ups: p_speed = max_ - player_info.speed else: p_speed = n_speed score = 0 score -= abs((player_info.position.x + n_speed) - (player_info.position.x + p_speed)) score -= abs((player_info.position.x + n_speed) - [i for i in game_map[y].keys()][-1]) # walking the paths to collect damages/speed-deduction and points path_walk = self.walk_path(path, game_map, is_lizard=False) score += len( path_walk["powerups"] ) * 4 # <-- actually using of powerups will justify this more score += self.compute_wall_damages(path_walk["obstacles"], player_info) player_info.power_ups += path_walk["powerups"] if progress: player_info.position = Position(y, x) return { "player_info": player_info, "game_map": game_map, "progression": progress, "additional_score": score }
def calcAStar(gridMap): aStar = AStar() # shortest path algorithm class pathWaypoints = aStar.findPath(gridMap) if not pathWaypoints == None: for gridCell in pathWaypoints: if not gridCell == None: gridMap.setGridCell(gridCell.position.x, gridCell.position.y, CellConstants.PATH, CellConstants.NORMAL_CELL)
def CalcPath(self, start, goal): astar = AStar(self.nodes) print('Calculating Shortest Path') coords = astar.GetPath(start, goal) if coords == None: post({'astar': False}, 'astar') coords = {} #print(coords) post({'coords': coords}, 'coords')
def openFile(self): """Funció per obrir el fitxer de transport per treballar""" fitxer = QtGui.QFileDialog.getOpenFileName( self, "Selecciona un fitxer de Transport", ".", "*.yaml") if not fitxer or fitxer == "": return self.trans = Transport.loadFile(str(fitxer)) self.loadStations() self.mF.setTrans(self.trans) self.a = AStar(self.trans) self.unLockForm()
def remove_isolated_paths(self): for path_coords in [(i, j) for i in range(len(self.grid)) for j in range(len(self.grid[i])) if self.grid[i, j] == self.path_value]: if path_coords not in [self.entry_coords, self.exit_coords]: if AStar(self.grid, path_coords, self.entry_coords, use_euclidean_distance=False).get_shortest_path( ) is None: self.grid[path_coords] = self.obstacle_value
def turn_right(self, action, game_map, player_info): max_ = speed_bracket[player_info.damage] if action == Commands.TURN_RIGHT: y = player_info.position.y + 1 if not y in game_map.keys() or max_ == 0: return { "player_info": player_info, "game_map": game_map, "progression": False, "additional_score": -10000 } x = player_info.position.x + player_info.speed - 1 progress = True if not x in game_map[y].keys(): x = [i for i in game_map[y].keys()][-1] progress = False a = AStar() path = a.forward(player_info.position, Position(y, x), game_map) p_speed = 0 # plaussible speeds if not player_info.boosting: if "BOOST" in player_info.power_ups: p_speed = max_ - player_info.speed - 1 else: n_speed = max_ if player_info.boosting else speeds[ player_info.speed].right p_speed = n_speed - 1 if n_speed else player_info.speed - 1 score = 0 score -= abs((player_info.position.x + player_info.speed) - (player_info.position.x + p_speed)) score -= abs((player_info.position.x + player_info.speed) - [i for i in game_map[y].keys()][-1]) # walking the paths to collect damages/speed-deduction and points path_walk = self.walk_path(path, game_map, is_lizard=False) score += len( path_walk["powerups"] ) * 4 # <-- actually using of powerups will justify this more score += self.compute_wall_damages(path_walk["obstacles"], player_info) player_info.power_ups += path_walk["powerups"] if progress: player_info.position = Position(y, x) return { "player_info": player_info, "game_map": game_map, "progression": progress, "additional_score": score }
def generate_dataset(self, dataset_size: int): generator = AStar(self.generator) X, y = [Board.ordered()], [[0]] while len(X) < dataset_size: boards = Board.scrambled(self.max_steps, True) path, pathLength, _, _ = generator.run(boards[-1]) for i, board in enumerate(path[:-1]): X.append(board) y.append([min(pathLength - 1 - i, self.max_steps)]) # to ensure consistent shape X = [self.network.transform(board) for board in X] return [nd.array(a, ctx=self.cfg.context) for a in (X, y)]
def act(self, ant): # Select a random water tile from the ones it knows about ran = random.randint(0, len(ant.knownWater) - 1) randomWater = ant.knownWater[ran] # Create a path to that tile. aStar = AStar(ant.tiles, ant.tiles[ant.x][ant.y], randomWater) path = aStar.takeStep() if path != None: while aStar.done == False: path = aStar.takeStep() ant.path = path
def __init__(self, X, Y, height=100.0, metric='euclidean', p=2, smoothing=0.5, maxdrift=100, silent=True): if not silent: print("[DTW] Calculating Distance Matrix", len(X), len(Y)) cost = sp_spatial.distance.cdist(X, Y, metric=metric, p=p) im, jm = cost.shape[0], cost.shape[1] def neighbor_func(n): ns = [] r = n[0] != im - 1 and ((n[0] / im) - (n[1] / jm)) * ((im + jm) / 2) < maxdrift d = n[1] != jm - 1 and ((n[1] / jm) - (n[0] / im)) * ((im + jm) / 2) < maxdrift if r: ns.append((n[0] + 1, n[1])) if d: ns.append((n[0], n[1] + 1)) if r and d: ns.append((n[0] + 1, n[1] + 1)) return ns def dist_func(n, m): return np.sqrt(np.sum( (np.array(n) - np.array(m))**2.0)) + height * cost[m[0], m[1]] if not silent: print("[DTW] Performing Path Search", len(X)) astar = AStar(neighbor_func, dist_func, dist_func, bias=0.0, silent=silent) path = np.array(astar((0, 0), (im - 1, jm - 1))).astype(np.float) path[0] = ((1 - smoothing) * path[0] + (smoothing) * path[1]) path[1:-1] = (0.5 * (1 - smoothing) * path[:-2] + (smoothing) * path[1:-1] + 0.5 * (1 - smoothing) * path[2:]) path[-1] = ((1 - smoothing) * path[-1] + (smoothing) * path[-2]) for i in range(1, len(path)): if path[i, 1] <= path[i - 1, 1]: path[i, 1] = path[i - 1, 1] + 1e-5 self.path = path
def initializeMethod(method_type): if (method_type == UCS_type): return UCSearch(start, goal) elif (method_type == BFS_type): return BFSearch(start, goal) elif (method_type == Astar_type): return AStar(start, goal, OctileDist(), 4, 4) elif (method_type == IDS_type): return IDSearch(start, goal, 50) else: print("Method not recognized...") exit()
def act(self, ant): # Select a random food tile from the ones it knows about. ran = random.randint(0, len(ant.knownFood) - 1) randomFood = ant.knownFood[ran] # Build a path to that tile aStar = AStar(ant.tiles, ant.tiles[ant.x][ant.y], randomFood) path = aStar.takeStep() if path != None: while aStar.done == False: path = aStar.takeStep() ant.path = path
def create_solution_path(self): solution_path_dictionary = {self.entry_coords: None} current_location = self.entry_coords previous_move = None prior_move = None instructions = self.create_instructions_how_to_get_from_a_to_b( self.entry_coords, self.exit_coords) while current_location != self.exit_coords: available_moves = {} for move_direction in list( self.move_definitions_dictionary.keys()): coords_of_move = tuple([ current_location[k] + self.move_definitions_dictionary[move_direction][k] for k in range(len(current_location)) ]) self.set_field_coords(coords_of_move) if self.check_if_coords_are_inside_the_grid(self.grid): if self.grid[coords_of_move] != self.obstacle_value: if coords_of_move not in list( solution_path_dictionary.keys()): if self.check_if_next_move_does_not_intersect_with_current_path( self.path_matrix, self.obstacle_value): if AStar( self. construct_modified_path_matrix_for_pathfinding_algorithm( ), coords_of_move, self.exit_coords, use_euclidean_distance=False ).get_shortest_path() is not None: available_moves[ move_direction] = coords_of_move list_of_choices = self.prepare_weighted_list_of_moves_options_for_generator( available_moves, list(instructions.keys()), stairs_move=self.get_next_stairs_move_based_on_two_moves( prior_move, previous_move)) chosen_move = rnd.choice(list_of_choices) instructions = self.update_instructions(instructions, chosen_move) new_path_field_coords = available_moves[chosen_move] solution_path_dictionary[new_path_field_coords] = chosen_move self.path_matrix[new_path_field_coords] = self.obstacle_value current_location = new_path_field_coords prior_move = previous_move previous_move = chosen_move return list(solution_path_dictionary.keys())
def runCustomPuzzle(puzzle, size): # Make puzzle realSize = int(math.sqrt(size + 1)) puzList = list(puzzle) if size + 1 != len(puzList): print("\nPUZZLE SIZE AND NUMBER OF TILES INPUT DO NOT MATCH\n") return puzArray = [[int(puzList[j * realSize + i]) for i in range(realSize)] for j in range(realSize)] customPuzzle = SlidingPuzzle(realSize, puzArray) customGoal = SlidingPuzzle(realSize) customGoal.setAsGoal() solver_1 = AStar(customPuzzle, customGoal, 0) solver_2 = AStar(customPuzzle, customGoal, 1) solver_3 = AStar(customPuzzle, customGoal, 0, True) solver_4 = AStar(customPuzzle, customGoal, 1, True) # Solve puzzle print("\nCUSTOM PUZZLE STRAIGHT LINE") solution = solver_1.search() print("Moves Taken: " + str(len(solution.moves)) + " moves") print("\nCUSTOM PUZZLE MANHATTAN") solution = solver_2.search() print("Moves Taken: " + str(len(solution.moves)) + " moves") print("\nCUSTOM PUZZLE STRAIGHT LINE WITH LINEAR CONFLICT") solution = solver_3.search() print("Moves Taken: " + str(len(solution.moves)) + " moves") print("\nCUSTOM PUZZLE MANHATTAN WITH LINEAR CONFLICT") solution = solver_4.search() print("Moves Taken: " + str(len(solution.moves)) + " moves")
def __init__(self, board): self.visible = False self.limit = board.matrix_dimension[1] - 1 self.initial_position = self.random_position() self.position_x = self.initial_position[0] self.position_y = self.initial_position[1] self.star = AStar(board) # self.star = AStar2(board) self.smell_distance = 2 self.smell_positions = [] self.live = True self.smell_visible = False self.image = "../res/images/wumpus/wumpus.png" self.smell = "../res/images/wumpus/smell.png" self.srt = '({}, {})'
def solve_tile_puzzle(selected_algo, n, board): logic = TilePuzzleLogic(n) result = None if selected_algo == 1: idfs = IDFS(logic) result = idfs.search(State(board)) elif selected_algo == 2: bfs = BFS_Seaerch(logic) result = bfs.search(State(board)) elif selected_algo == 3: a_star = AStar(logic) result = a_star.search(HeuristicState(board)) else: raise Exception('Bad input! no such search algorithm') write_results(result)
def dist_goal(self, score1, goal, character, world): """ Returns the world score based on if the character is at or next to the goal :param score1: value given that the character is at or next to the goal for a range of 2 :param world: the game state :param character: the player to evaluate :return: an integer score value """ if character is not None: m_x = character.x m_y = character.y else: return -999 if self.path is None: astar = AStar([m_x, m_y], goal, world, False) self.path = astar.a_star() position_val = 0 multiplier = len(self.path) minimum_dist = 1 blocked_positions = [] for x in range(-1, 2): for y in range(-1, 2): if [x, y] != [0, 0]: nx = m_x + x ny = m_y + y if 0 < nx < world.width() and 0 < ny < world.height( ) and world.wall_at(nx, ny): blocked_positions.append([m_x + 2 * x, m_y + 2 * y]) blocked_positions.append([m_x + 3 * x, m_y + 3 * y]) while position_val == 0: for point in self.path: if not blocked_positions.__contains__(point): x_diff = point[0] - m_x y_diff = point[1] - m_y sq_dist = x_diff * x_diff + y_diff * y_diff lin_dist = sq_dist**.5 if 0 < lin_dist <= minimum_dist: position_val += (1.0 / lin_dist) * multiplier multiplier -= 1 minimum_dist += 1 val = position_val * score1 print("val at " + str(m_x) + ", " + str(m_y) + " is " + str(val)) return (1 / position_val) * score1
def AStarAlgo(state, heuristic): a = AStar() a.init() start = timeit.default_timer() aAlgo = a.doAStar(state, "1,2,5,3,4,0,6,7,8", heuristic) path = aAlgo[0][0] depth = aAlgo[0][1] explored = aAlgo[1] stop = timeit.default_timer() print('============= Time =============') print(stop - start) print('============= Depth =============') print(depth) print('============= Explored =============') print(explored) print('============= Path =============') for i in path: printBoard(i.split(','))
def getNewDest(self, user, startTime): # 需要从新规划 minTime = 0 newDest = 0 newMap = Array2D.Array2D(self.width, self.height) if self.isNeedNewPlan(user): print("流量控制:需要重新规划") for dest in self.destList: if user.destId == dest.id: continue newAstar = AStar.AStar(newMap, user.currPosition, dest.position) newAstar.addAllObastacleArea(self.obstacleList) pathList = newAstar.start() if pathList is not None and len(pathList) > 0: print("路径重新规划") else: print("位置已在障碍物区域内部,无法重新规划") user.inFlag = False distance = self.calPathLength(pathList) totalTime = round(distance / user.speed, 3) * 1000 destTime = startTime + totalTime if minTime == 0: minTime = destTime if minTime > destTime: minTime = destTime newDest = dest user.destId = newDest.id user.destPosition = newDest.destPosition user.destChanged = True # user.pathList = minPathList # user.startTime = startTime # user.currentTime = getCurrentTime() # user.distance = self.calPathLength(user.pathList) # user.totalTime = round(user.distance / user.speed, 3) * 1000 # user.destTime = user.startTime + user.totalTime return True else: print("user pathlist size:", len(user.pathList)) print("流量控制:不。。。需要重新规划") return False