def solve(problem): nodeCount = 0 maxDepth = 0 current = Node(heuristic(problem.startnum, problem), problem.startnum, 0, None, None) frontier = queue.PriorityQueue() #sorted on cost of operation frontier.put(current) explored = set() #set frontierSet = set() frontierSet.add(current) start_time = time.time() best = current while time.time( ) - start_time < problem.time - 0.0001: #while we have time if frontier.empty(): break current = frontier.get() if goal_test(current.data, problem.targetnum): break #success explored.add(current) # bookkeeping depth = current.depth + 1 if depth > maxDepth: maxDepth = depth # apply all operations to the current node for op in problem.ops: child = problem.evalOp(current.data, op) if child not in explored or frontierSet: nodeCount += 1 # bookkeeping child_node = Node(heuristic(child, problem), child, depth, current, op) # maintain best so far if closer(best.data, child, problem.targetnum): best = child_node frontier.put(child_node) frontierSet.add(child) # if we run out of time, make sure we are returning the best solution if heuristic(current.data, problem) < heuristic(best.data, problem): best = current # return the answer and bookkeeping information return (best.data, best.depth, time.time() - start_time, nodeCount, maxDepth, best)
def make_deliveries(self): """ Makes deliveries to destinations ordered by set heuristic and accommodates for robot's carrying capacity """ package_number = 0 curr_load = self.capacity self.destinations = heuristic('manhattan', self.control_center, self.destinations) # self.destinations = heuristic('dynamic', self.control_center, self.destinations, dynamic_name='chebyshev') while package_number < len(self.destinations): goal_x, goal_y = self.destinations[ package_number].x, self.destinations[package_number].y if curr_load == 0: result = self.move_to_goal(self.control_center.x, self.control_center.y) rospy.loginfo("RETURNING TO CONTROL CENTER") curr_load = self.capacity else: result = self.move_to_goal(goal_x, goal_y) rospy.loginfo("DELIVERED PACKAGE " + str(package_number + 1)) curr_load -= 1 package_number += 1 # return to control-center result = self.move_to_goal(self.control_center.x, self.control_center.y) rospy.loginfo("COMPLETED ALL DELIVERIES") if result: rospy.loginfo("Goal execution done!") else: rospy.loginfo("Something went wrong!")
def __init__(self, parent=None, board=None, depth=0): self.board = board self.parent = parent self.n = int(len(board)**(1 / 2)) self.h = heuristic([board[i:i + self.n] for i in range(0, self.n)]) self.g = depth self.f = self.h + self.g
def __init__(self, board, goal, parent, hc): self.board = board self.size = len(board) self.parent = parent print parent self.h = heuristics.heuristic(board, goal, self.size, hc) print 'H---: {}'.format(self.h) self.g = heuristics.get_depth(parent) print 'G---: {}'.format(self.g) self.f = self.g + self.h print 'F---: {}'.format(self.f)
def _iterative_worker_mtd(k, w, b, color, best_move_list, timeout_event): guess = heuristic(k, w, b, 0, 0, tt_ab) i = 0 for depth in range(2, MAX_DEPTH + 2): curr_guess, best_move = mtdf(k, w, b, depth, guess, color, timeout_event) if timeout_event.isSet(): break if best_move is not None: best_move_list[0] = best_move i += 1 if i % 2 == 0: guess = curr_guess print(color, depth, best_move_list[0], guess)
def minmax(board, depth, player): value = None move = None possible_moves = get_all_possibilities(board, player) #check whether game has ended, player out of moves if len(possible_moves) > 0: #check whether given depth is achieved if depth > 0: #maximizing player if player == constants.MAX_PLAYER: # assign worst value for max value = float('-inf') #recursion for possible moves for p in possible_moves: new_value, new_move = minmax(p, depth - 1, constants.MIN_PLAYER) #assign better outcome if new_value > value: value = new_value move = copy.deepcopy(p) else: #minimizing player #assign worst value for min value = float('inf') # #recursion for possible moves for p in possible_moves: new_value, new_move = minmax(p, depth - 1, constants.MAX_PLAYER) #assign better outcome if new_value < value: value = new_value move = copy.deepcopy(p) else: # leaves, assign value based on heuristic value = heuristic(board) move = copy.deepcopy(board) else: #end of the game player is out of moves, if player == constants.MAX_PLAYER: value = -10000 move = copy.deepcopy(board) else: value = 10000 move = copy.deepcopy(board) return value, move
def main(dataFolder): car = Car.getCar(dataFolder + "/vehicle.ini") distances = MatrixFromFile(dataFolder + "/distances.txt") times = MatrixFromFile(dataFolder + "/times.txt") visits = Visits(dataFolder + "/visits.csv") context = (distances, times, car) result = heuristic(visits, context) writeToCsv(result, RESULTS_DIR + 'result1.csv') print("Le fichier de resultat s'appel result1.csv") better_result = metaHeuristic3(result, context) print(result) print(better_result) writeToCsv(better_result, RESULTS_DIR + 'better_result.csv') print("Le fichier de resultat s'appel better_result1.csv")
def recursive_dls(current, problem, limit): global node_count node_count += 1 if goal_test(current.data, problem.targetnum): return current elif limit == 0: return current else: for op in problem.ops: child = problem.evalOp(current.data, op) child_node = Node(heuristic(child, problem), child, current.depth + 1, current, op) next_node = recursive_dls(child_node, problem, limit - 1) if cut_off(next_node, problem.targetnum, problem): break return next_node
def solve(problem): global node_count global start_time global best start_time = time.time() depth = 0 best = Node(heuristic(problem.startnum, problem), problem.startnum, 0, None, None) result = best node_count = 0 while True: # we exit due to time below if cut_off(result, problem.targetnum, problem): #cut search here: inc or found goal break result = depth_limited_search(problem, depth) depth += 1 if closer(best.data, result.data, problem.targetnum ): #update best so far (if last iteration finds answer) best = result return (best.data, best.depth, time.time() - start_time, node_count, depth, best)
def generate_ordered_moves(k, w, b, color, depth, max_depth): possible_moves = generate_player_moves(k, w, b, color) ordered_moves = [] reverse = False if color == 'w' else False if depth > 1: # FIXME for origin, destination in possible_moves: advance_state(k, w, b, origin, destination) captures = get_capture_victims(k, w, b, color, destination) apply_captures(k, w, b, captures) ordered_moves.append((origin, destination, heuristic(k, w, b, depth, max_depth, tt_ab))) revert_state(k, w, b, origin, destination) revert_captures(k, w, b, captures) ordered_moves = sorted(ordered_moves, key=lambda x: x[2], reverse=reverse) # if len(ordered_moves) > 40: # ordered_moves = ordered_moves[0:40] else: for origin, destination in possible_moves: ordered_moves.append((origin, destination, 0)) return ordered_moves
def bfs(start_node: List[List[int]], goal_node: List[List[int]], max_length: int) -> "solution path": """Breadth-first search (BFS) function. Args: start_node: The beginning node. goal_node: The node to try and reach. Returns: The path (list) taken to reach the node if any. """ d = deque([start_node, []]) explored = {} level = 0 # Return empty path if start is equal to goal if start_node == goal_node: return '0\t' + str(goal_node).replace("[", "").replace( ",", "").replace("]", ""), get_search_path( {getNodeVal(start_node): (heuristic(start_node), start_node)}) # Keep exploring while the queue has nodes while len(d) > 0: path = d.popleft() if level == 0: node = path else: # To keep track of levels an empty node gets popped between levels which will cause an exception try: node = path[-1] except Exception: node = [] pass if len(node) == 0: level += 1 # Return empty list if max length was reached d.append(node) else: val = getNodeVal(node) if val not in explored: # Mark node as explored explored[val] = (heuristic(node), node) if len(explored.keys()) >= max_length: return 'no solution', get_search_path(explored) all_moves = [] for row in range(len(node)): for col in range(len(node)): child = toggle(node, row, col) new_path = list(path) if level != 0 else list([path]) new_path.append(child) all_moves.append(new_path) if child == goal_node: level += 1 # print(level) return get_solution_path( new_path), get_search_path(explored) # sorts the list of possible moves and breaks ties with the helper function find_First_white_token all_moves.sort(key=lambda x: (heuristic(x[-1]), find_first_white_token(x[-1]))) for path in all_moves: d.append(path) # No solution found return 'no solution', get_search_path(explored)
def depth_limited_search(problem, limit): n = Node(heuristic(problem.startnum, problem), problem.startnum, 0, None, None) return recursive_dls(n, problem, limit)
import numpy as np import heuristics import localsearch class ProblemStor: N = 10 T = 100 d = 20 c = np.array([34, 25, 14, 21, 16, 3, 10, 5, 7, 10]) U = np.array([42, 18, 90, 94, 49, 49, 34, 90, 37, 11]) class ProblemData: N = 4 T = 100 d = 10 c = np.array([5, 6, 7, 9]) U = np.array([3, 4, 5, 7]) problem = ProblemStor() #problem = ProblemData() J, x, z = heuristics.heuristic(problem) print('Heuristics: J = %d\n\nLocal search:' % J) J, x, z = localsearch.localsearch(problem, z, 1000)
def minimax_alpha_beta_DLS(self, grid, depth, players_turn, first_move, start_time, alpha, beta): """ Recursive Depth-Limited minimax search with alpha-beta-pruning. Returns (best_score, best_move) found, given the specified depth. """ if time.clock() - start_time > 0.2: print "Time's up!" raise Exception("Time exeption") if depth == 0: return heuristic(grid), first_move if players_turn: #This is the maximizing player moves = grid.getAvailableMoves() if moves == []: return heuristic(grid), first_move max_value = (-float('inf'), None) for move in moves: child = grid.clone() child.move(move) if first_move == None: value = self.minimax_alpha_beta_DLS( child, depth - 1, False, move, start_time, alpha, beta) else: value = self.minimax_alpha_beta_DLS( child, depth - 1, False, first_move, start_time, alpha, beta) max_value = max(max_value, value) alpha = max(alpha, max_value[0]) if beta <= alpha: #print "Beta cuf off!" break #cut of branch return max_value else: # Minimizing player cells = grid.getAvailableCells() min_value = (float('inf'), None) for cell in cells: child = grid.clone() child.setCellValue(cell, 2) value_2 = self.minimax_alpha_beta_DLS(child, depth - 1, True, first_move, start_time, alpha, beta) child = grid.clone() child.setCellValue(cell, 4) value_4 = self.minimax_alpha_beta_DLS(child, depth - 1, True, first_move, start_time, alpha, beta) min_value = min(min_value, value_2, value_4) beta = min(beta, min_value[0]) if beta <= alpha: #print "Alpha cuf off!" break #cut of branch return min_value
def alpha_beta_tt(k, w, b, depth, alpha, beta, color, max_depth, timeout_event): if timeout_event.isSet(): return None, None # Terminal cases if np.any(k * BOARD_ESCAPES): return +3.4028235e+38 / (1 + max_depth - depth), None if not np.any(k): return -3.4028235e+38 / (1 + max_depth - depth), None if pawn_count(b) == 0: return +3.4028235e+30 / (1 + max_depth - depth), None if pawn_count(w) == 0 and np.any(k * BOARD_ESCAPES): return -3.4028235e+30 / (1 + max_depth - depth), None # Transposition table lookup best_move = None tt_entry = tt_lookup(k, w, b, tt_ab) if tt_entry is not None and tt_entry.get('depth', float('-inf')) >= depth: lowerbound = tt_entry.get('lowerbound', float('-inf')) upperbound = tt_entry.get('upperbound', float('+inf')) best_move = tt_best_moves.get(zhash(k, w, b), None) if lowerbound >= beta: return lowerbound, best_move if upperbound <= alpha: return upperbound, best_move alpha = max(alpha, lowerbound) beta = min(beta, upperbound) alpha_orig = alpha beta_orig = beta # Max depth reached (leaf node) if depth == 0: return heuristic(k, w, b, depth, max_depth, tt_ab), best_move # Move generation and ordering ordered_moves = generate_ordered_moves(k, w, b, color, depth, max_depth) best_move = None if color == 'w': # MAXNODE best_value = float('-inf') for origin, destination, _ in ordered_moves: advance_state(k, w, b, origin, destination) captures = get_capture_victims(k, w, b, color, destination) apply_captures(k, w, b, captures) value, _ = alpha_beta_tt(k, w, b, depth - 1, alpha, beta, 'b', max_depth, timeout_event) revert_state(k, w, b, origin, destination) revert_captures(k, w, b, captures) if timeout_event.isSet(): return None, None if value > best_value: best_value = value best_move = (origin, destination) if best_value > alpha: alpha = best_value if alpha > beta: break else: # MINNODE best_value = float('+inf') for origin, destination, _ in ordered_moves: advance_state(k, w, b, origin, destination) captures = get_capture_victims(k, w, b, color, destination) apply_captures(k, w, b, captures) value, _ = alpha_beta_tt(k, w, b, depth - 1, alpha, beta, 'w', max_depth, timeout_event) revert_state(k, w, b, origin, destination) revert_captures(k, w, b, captures) if timeout_event.isSet(): return None, None if value < best_value: best_value = value best_move = (origin, destination) if best_value < beta: beta = best_value if alpha > beta: break # Transposition table storing tt_entry_data = Dict() if best_value <= alpha_orig: tt_entry_data['upperbound'] = best_value tt_entry_data['lowerbound'] = float('-inf') elif alpha_orig < best_value < beta_orig: tt_entry_data['upperbound'] = best_value tt_entry_data['lowerbound'] = best_value else: tt_entry_data['upperbound'] = float('+inf') tt_entry_data['lowerbound'] = best_value tt_entry_data['depth'] = depth tt_best_moves[zhash(k, w, b)] = best_move tt_set(k, w, b, tt_entry_data, tt_ab) return best_value, best_move
def alphabeta(board, depth, player, alpha, beta): value = None move = None #best possible value for max player a = alpha #best possible value for min player b = beta possible_moves = get_all_possibilities(board, player) # check whether game has ended, player out of moves if len(possible_moves) > 0: # check whether given depth is achieved if depth > 0: # maximizing player if player == constants.MAX_PLAYER: # assign worst value for max value = float('-inf') # recursion for possible moves for p in possible_moves: new_value, new_move = alphabeta(p, depth - 1, constants.MIN_PLAYER, a, b) #if better move found assign it if new_value > value: value = new_value move = copy.deepcopy(p) # max player found greater value than beta # min player will not choose it anyway # stop searching - break loop if new_value >= b: break # assign better alfa for next interations if new_value > a: a = new_value else: #minimizing player #assign worst value for min value = float('inf') # recursion for possible moves for p in possible_moves: new_value, new_move = alphabeta(p, depth - 1, constants.MAX_PLAYER, a, b) #if better move found assign it if new_value < value: value = new_value move = copy.deepcopy(p) # min player found smaller value than alfa # max player will not choose it anyway # stop searching - break loop if new_value <= a: break #assign better beta for next interations if new_value < b: b = new_value else: # leaves, assign value based on heuristic value = heuristic(board) move = copy.deepcopy(board) else: #end of the game if player == constants.MAX_PLAYER: value = -10000 move = copy.deepcopy(board) else: value = 10000 move = copy.deepcopy(board) return value, move
def calculate_cost(self, problem): self.cost = heuristic(self.data, problem)