def search(self, curState, world, heuristic ): ''' Does A* search ''' global nodesExpanded global nodesGenerated closedList = {} Q = [] startNode = StateNode( curState, 0, 0 ) closedList[startNode.uniqueString(world)] = 1 #Q.appendleft( startNode ) heapq.heappush(Q,(startNode.f,startNode)) while True: if len(Q) == 0: return None node = heapq.heappop(Q)[1] #print("popping node") #print( node.f ) #print( node.state.toString() ) if node.isClean(): return node.state GlobalVars.nodesExpanded = GlobalVars.nodesExpanded + 1 for child in node.expand(world, heuristic): #print( child.f ) #print( child.uniqueString(world) ) #print( child.state.toString() ) s = child.uniqueString(world) GlobalVars.nodesGenerated = GlobalVars.nodesGenerated + 1 if s not in closedList or child.f+1 < closedList[s]: #print("pushing node") #print( child.f )child.f+1 #print( child.state.toString() ) closedList[s] = child.f+1 heapq.heappush(Q,(child.f,child))
def do_tabu_search(dataset, k, r_ratio, max_iter, tabu_tenure): current_node = StateNode(dataset, k) tabu_moves = np.zeros((current_node.k, 2 * current_node.d)) best_state = current_node for iter in range(max_iter): positive_i = np.where(tabu_moves > 0) tabu_moves[positive_i] -= 1 neighbours = current_node.get_children() neighbours_pq = [] for neighbour in neighbours: heappush(neighbours_pq, neighbour) best_candidate = None while best_candidate is None: if len(neighbours_pq) == 0: return best_state neighbour = heappop(neighbours_pq) if not is_tabu(tabu_moves, neighbour): best_candidate = neighbour elif neighbour < best_state: # aspiration by default best_candidate = neighbour best_state = best_candidate current_node = best_candidate reverse_index = best_candidate.direction_moved + ( 1 - 2 * (best_candidate.direction_moved % 2)) tabu_moves[best_candidate.center_moved, reverse_index] = tabu_tenure #print(str(iter) + '. ' + str(current_node.get_score())) return best_state
def getMove(self, currentState): me = currentState.whoseTurn if self.playerIndex == None: self.playerIndex = me foods = getConstrList(currentState, None, (FOOD, )) # Find Food and Tunnel of agent if self.myTunnel is None: self.myTunnel = getConstrList(currentState, me, (TUNNEL, ))[0] if self.myFood == None: closest = 1000 for food in foods: dist = approxDist(self.myTunnel.coords, food.coords) if (dist < closest): self.myFood = food closest = dist # Start of the recursive method self.searchTree.top = StateNode(currentState, None, None, None, 0) self.searchTree.top.subNodes = self.RecursiveFindMove(currentState, 0) # Find best move bestScore = -100 bestNode = self.searchTree.top for node in self.searchTree.top.subNodes: if node.move is not None: if node.score > bestScore: bestNode = node bestScore = node.score return bestNode.move
def RecursiveFindMove(self, GameState, currentDepth): if currentDepth <= self.searchTree.depthLimit: nodes = [] states = [] # List of next states being generated by each move node = StateNode(GameState, None, 0, None, currentDepth, None, None) moves = listAllLegalMoves( GameState) # List of all legal moves from that state for move in moves: states.append(getNextState(GameState, move)) if len(states) < 10: x = len(states) else: x = 10 for i in range(0, x): newNode = StateNode(states[i], GameState, 0, moves[i], currentDepth, node, None) newNode.score = self.calculateStateScore(states[i]) nodesToCalculate = self.RecursiveFindMove( states[i], currentDepth + 1) if nodesToCalculate is not None: newNode.subNodes = nodesToCalculate node.score = self.BestNodeInList(nodesToCalculate) nodes.append(newNode) return nodes else: return None
def do_simulated_annealing(dataset, k, r_ratio, alpha, t_start, t_iter): t = t_start node = StateNode(dataset, k) while(t > 0.1): for i in range(t_iter): current_score = node.get_score() neighbours = node.get_children() random.shuffle(neighbours) print(str(t) + ", " + str(current_score)) for candidate in neighbours: delta = candidate.get_score() - current_score if accept_move(t, delta): node = candidate break t = alpha * t return node
def search(self, curState, world ): ''' Does uniform cost search ''' closedList = {} Q = [] startNode = StateNode( curState, 0, 0 ) closedList[startNode.uniqueString(world)] = 1 #Q.appendleft( startNode ) heapq.heappush(Q,(startNode.f,startNode)) while True: if len(Q) == 0: return None node = heapq.heappop(Q)[1] if node.isClean(): return node.state GlobalVars.nodesExpanded = GlobalVars.nodesExpanded + 1 for child in node.expand(world): GlobalVars.nodesGenerated = GlobalVars.nodesGenerated + 1 if child.uniqueString(world) not in closedList: closedList[child.uniqueString(world)] = 1 heapq.heappush(Q,(child.f,child))
def do_ACO(dataset, k, r_ratio, num_ants, num_steps_max, evap_rate, t_init, delta_p_base): node = StateNode(dataset, k, r_ratio=r_ratio) T_shape = [int(1 / r_ratio) for i in range(node.d)] pheromone_matrix = np.full(tuple(T_shape), t_init) ants = [Ant(StateNode(dataset, k, r_ratio=r_ratio), r_ratio) for i in range(num_ants)] # ants = [Ant(node, r_ratio) for i in range(num_ants)] best_state = node print('Starting ACO:') print('Params: num_ants:{}, num_steps_max: {}, evap_rate: {}, t_init: {}, Q: {}' .format(str(num_ants), str(num_steps_max), str(evap_rate), str(t_init), str(delta_p_base))) print('Initial Score: ' ) print('============') for index, ant in enumerate(ants): ant.forwards(pheromone_matrix, num_steps_max) pheromone_matrix = ant.backwards(pheromone_matrix, delta_p_base) pheromone_matrix = evaporate(pheromone_matrix, evap_rate) if ant.get_best().get_score() < best_state.get_score(): best_state = ant.get_best() print(str(index) + '. personal best: ' + str(round(ant.get_best().get_score())) + 'global best: ' + str(round(best_state.get_score()))) return best_state
def search(self, curState, world, maxDepth=-1): ''' Iterative version of depth first search. This currently has some bugs and is not fit for use! It does not return an optimal solution when used with iterative deepening. The recrusive version works, though. ''' closedList = {} queue = [] startNode = StateNode( curState, 0, 0 ) closedList[startNode.uniqueString(world)] = 1 queue.append( startNode ) depth = 0 if maxDepth == -1: maxDepth = 1000000 #return self.do_search(queue,closedList,world,depth,maxDepth) while True: if queue == []: return None node = queue.pop() #if node.uniqueString(world) in closedList: #print( node.state.printString(world) ) if node.isClean(): return node.state if depth < maxDepth: GlobalVars.nodesExpanded = GlobalVars.nodesExpanded + 1 for child in node.expand( world ): GlobalVars.nodesGenerated = GlobalVars.nodesGenerated + 1 if child.uniqueString(world) not in closedList: closedList[child.uniqueString(world)] = 1 queue.append( child ) depth = depth + 1 else: depth = depth - 1 #print(len(closedList)) del closedList[node.uniqueString(world)]
def maxNodes(self, currentState): bestNode = StateNode(currentState, None, None, None, None) return bestNode
queenThr3 = AIPlayer.myQueenThreat(AIPlayer, state3) if queenThr1 == -1.25: print("myQueenThreat Unit Test: True") else: print("myQueenThreat Unit Test: False") if queenThr2 == -1.25: print("myQueenThreat Unit Test: True") else: print("myQueenThreat Unit Test: False") if queenThr3 == -1: print("myQueenThreat Unit Test: True") else: print("myQueenThreat Unit Test: False") # Test Best Node in List node1 = StateNode(state1, None, 5, None, 0, None, None) node2 = StateNode(state1, None, 1, None, 0, None, None) node3 = StateNode(state1, None, -3, None, 0, None, None) node4 = StateNode(state1, None, None, None, 0, None, None) nodes = {node1, node2, node3, node4} sum = AIPlayer.BestNodeInList(AIPlayer, nodes) if sum == 5: print("BestNodeInList Unit Test: True") else: print("BestNodeInList Unit Test: False") # Test method workerAnts worker1 = AIPlayer.workerAnts(AIPlayer, state1) worker2 = AIPlayer.workerAnts(AIPlayer, state1) worker3 = AIPlayer.workerAnts(AIPlayer, state1) print("\n\nCould not find way to add food to board for testing \n"
from StateNode import StateNode from heapq import heappush, heappop import numpy as np from timeit import default_timer as timer import csv dataset = np.loadtxt('../data/iris.txt') outfile = open('../out/iris_k4.csv', 'w') writer = csv.writer(outfile, lineterminator='\n') for i in range(100): initial_node = StateNode(dataset, k=3) # Algorithm parameters r_ratio = 0.01 max_iter = 10000 # Uniform cost graph search pqueue = [] heappush(pqueue, initial_node) i = 0 start = timer() prev_score = initial_node.get_score() while i < max_iter: expand_node = heappop(pqueue) current_score = expand_node.get_score() if prev_score <= current_score and i > 0: end = timer() print(str([current_score, end - start, i])) writer.writerow([current_score, end - start, i]) break