def solve(): """ Solve the puzzle by getting the required parameters from the request args. """ algorithm = request.args['algorithm'] arr = list(map(int, request.args['input[]'][1:-1].split(','))) print(algorithm) agent = None if algorithm == "BFS": agent = BFS() elif algorithm == "DFS": agent = DFS() elif algorithm == "A start (Euclidean)": agent = AStar(Euclidean) elif algorithm == "A start (Manhatten)": agent = AStar(Manhatten) else: return arr start = timeit.default_timer() res = agent.search(arr) end = timeit.default_timer() res['time'] = end - start ret = jsonify(res) return ret
from bfs import BFS from romenia_map import ROMENIA bfs = BFS(ROMENIA, start='Arad') print bfs.search('Bucharest') == 'Bucharest'
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) b = BFS(n, Sx, Sy, Tx, Ty) # game loop running = True while running: if b.q: # returns current node and previous node t, prev = b.search() placeEntity(knight, t[1], t[0], gameDisplay) markVisited(prev[1], prev[0], gameDisplay) pygame.display.update() time.sleep(1) if t == (Tx, Ty): createChessboard(gameDisplay, n) placeEntity(queen, Ty, Tx, gameDisplay) placeEntity(knight, Sy, Sx, gameDisplay) path = b.createPath() for i, j in path[1:]: markVisited(j, i, gameDisplay) pygame.display.update() continue if b.q == []: createChessboard(gameDisplay, n) cross = pygame.image.load("cross.jpg") placeEntity(cross, Ty, Tx, gameDisplay) placeEntity(knight, Sy, Sx, gameDisplay) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False break print("Target position ", (Tx, Ty), " reached: ", b.visited[Tx][Ty]) pygame.quit()
def run(self): R = len(self.content['starts']) # robots N = self.content['N'] # grid size # We use a breadth-first search to determine the horizon, i.e., # upper complexity bound, of the problem, based on the maximum distance # of a goal from the start positions of the paths. distance_to_target = [] bfs = BFS(N, self.content['starts'], self.content['obstacles']) for i, source in enumerate(bfs.starts): bfs.search(source) distance_to_target.append(bfs.G[tuple( self.content['goals'][i])]['d']) H_MIN = max(distance_to_target) # horizon H_MAX = int(H_MIN * self.h_mult) H_MAX_ORIG = H_MAX logging.log(logging.INFO, 'BFS lower bound: {}.'.format(H_MIN)) logging.log(logging.INFO, 'Setting H_MAX to h_mult * {}: {}'.format(H_MIN, H_MAX)) if self.search == 'binary': H = (H_MAX - H_MIN) // 2 + H_MIN elif self.search == 'linear': H = H_MIN else: logging.log(logging.ERROR, 'Search method is not one of "linear", "binary".') exit() logging.log(logging.INFO, 'Beginning search with horizon: {}'.format(H)) # H denotes the horizon (makespan) we are currently checking. # If H is too small, there will be no solution and the solver will # return *unsat*. H_MAX is the maximum possible horizon of the problem, # as computed above using BFS. while H < H_MAX: # make the EF-SMT instance here plan = [[[ Symbol('p_%d^%d-0' % (i, j), INT), Symbol('p_%d^%d-1' % (i, j), INT) ] for j in range(H)] for i in range(R)] attack = [[Symbol('a_%d-0' % i, INT), Symbol('a_%d-1' % i, INT)] for i in range(H)] # There is an implicit "exists" quantifier out front on the plan # variables. We are asking the solver to determine if there exists a # model for the plan variables s.t. the plan is a valid MAPF # solution, and s.t. forall choices (in (Z^2)^H) for the attack # variables, the attack is not a valid attack on the plan. formula = ForAll( [symvar for coordinate in attack for symvar in coordinate], And( IsPlan(plan, N, self.content['starts'], self.content['goals'], self.content['safes'] + self.content['obstacles']), Not( IsAttack(attack, plan, N, self.content['obstacles'], self.content['safes'])))) try: model = self.get_model(formula) except timeout_decorator.TimeoutError: model = None # If the solver returns a sat result, we ask for a satisfying model. # The makespan of the MAPF solution will be H (<= H_MAX). if model: control = [[[ model.get_py_value(plan[i][j][0]), model.get_py_value(plan[i][j][1]) ] for j in range(H)] for i in range(R)] self.content['control'] = list(zip(*control)) logging.log(logging.INFO, 'Found solution for horizon: {}'.format(H)) if self.search == 'linear': break else: H_MAX = H H = (H_MAX - H_MIN) // 2 + H_MIN else: logging.log(logging.INFO, 'UNSAT for H={}, updating H.'.format(H)) if self.search == 'linear': H += 1 else: H_MIN = H + 1 H = (H_MAX - H_MIN) // 2 + H_MIN if 'control' not in self.content: logging.log(logging.INFO, 'UNSAT for H_MAX={}.'.format(H_MAX_ORIG))
b_map2 = "generatedpaths/bfs/map2.txt" b_map3 = "generatedpaths/bfs/map3.txt" d_map1 = "generatedpaths/dfs/map1.txt" d_map2 = "generatedpaths/dfs/map2.txt" d_map3 = "generatedpaths/dfs/map3.txt" print "\nBFS - Map1" world = World(Util.read_file(map1), b_map1) bfs_search = BFS(world) print timeit.Timer(bfs_search.search).timeit(1) print "\nBFS - Map2" world = World(Util.read_file(map2), b_map2) bfs_search = BFS(world) bfs_search.search() print timeit.Timer(bfs_search.search).timeit(1) print "\nBFS - Map3" world = World(Util.read_file(map3), b_map3) bfs_search = BFS(world) bfs_search.search() print timeit.Timer(bfs_search.search).timeit(1) print "\nDFS - Map1" world = World(Util.read_file(map1), d_map1) dfs_search = DFS(world) dfs_search.search() print timeit.Timer(dfs_search.search).timeit(1) print "\nDFS - Map2"
from bfs import BFS from romenia_map import ROMENIA bfs = BFS(ROMENIA, start="Arad") print bfs.search("Bucharest") == "Bucharest"
def solveBFS(rubik): aux = time.time() solution_BFS = BFS.search(rubik, lambda x: x == RubikPuzzle()) t["BFS: "] = (time.time() - aux) * 1000 aux = 0 return solution_BFS
def test_bfs(self): agent = BFS() steps = agent.search([1, 2, 5, 3, 4, 0, 6, 7, 8]) print("Solved in {} steps".format(len(steps))) print(steps)