def runTest(Inventory): import Ant import Construction ant1 = Ant.Ant((2,3), Ant.QUEEN, 1) ant2 = Ant.Ant((4,5), Ant.WORKER, 1) construction1 = Construction.Construction((3,4), Construction.TUNNEL) construction2 = Construction.Construction((1,2), Construction.ANTHILL) testInventory = Inventory.Inventory(1,[ant1, ant2], [construction1, construction2], 3) testQueen = testInventory.getQueen() if testQueen == None: raise Exception("getQueen method is not returning existing Queen Ant") testAntHill = testInventory.getAnthill() if testAntHill == None: raise Exception("getAnthill method is not returning existing Ant Hill") testInventoryClone = testInventory.clone() if testInventoryClone == testInventory: raise Exception("The cloned inventory is equal to the original") if testInventoryClone.player != testInventory.player: raise Exception("The cloned inventory does not have the same player as the original Inventory") if testInventoryClone.ants != testInventory.ants: raise Exception("The cloned inventory does not have the same set of ants as the original Inventory") if testInventoryClone.constructions != testInventory.constructions: raise Exception("The cloned inventory does not have the same set of constructions as the original Inventory") if testInventoryClone.foodCount != testInventory.foodCount: raise Exception("The cloned inventory does not have the same number of food pieces as the original Inventory") testInventoryClone.foodCount = 5 if testInventoryClone.foodCount == testInventory.foodCount: raise Exception("The changed cloned inventory food count is the same as the original")
def solve_problem(self): print("\nSTARTING ITERATIONS\n") # print("Number of iterations: "+ str(self.number_iterations)) for it in range(self.number_iterations): print("Current iteration: " + str(it)) ant = Ant(self.number_jobs,self.number_machines,self.graph,self.pheromone_trails,self.best_seq) # Only one ant per iteration ant.build_sequence() self.ant_results.append(ant.z_graph) # Save result to plot self.ant_results_ls.append(ant.z_ls_graph) self.update_best_solution(ant) self.update_trail_intensities(ant) #print(self.pheromone_trails) # Job-index-based swap scheme self.before_swap_seq, self.before_swap_z = self.best_seq,self.z_best self.best_seq,self.z_best = job_index_based_swap_scheme(self.before_swap_seq,self.before_swap_z,self.graph,self.number_machines) self.show_solution() self.show_graphics()
def getNextState(self, currentState, move): returnState = currentState.fastclone() #check move type if move.moveType == MOVE_ANT: startCoord = move.coordList[0] endCoord = move.coordList[-1] #take ant from start coord antToMove = getAntAt(returnState, startCoord) #if the ant is null, return if antToMove is None: return returnState #change ant's coords and hasMoved status antToMove.coords = (endCoord[0], endCoord[1]) antToMove.hasMoved = True elif move.moveType == BUILD: coord = move.coordList[0] currentPlayerInv = returnState.inventories[returnState.whoseTurn] #subtract the cost of the item from the player's food count if move.buildType == TUNNEL: currentPlayerInv.foodCount -= CONSTR_STATS[move.buildType][BUILD_COST] tunnel = Building(coord, TUNNEL, returnState.whoseTurn) returnState.inventories[returnState.whoseTurn].constrs.append(tunnel) else: currentPlayerInv.foodCount -= UNIT_STATS[move.buildType][COST] ant = Ant(coord, move.buildType, returnState.whoseTurn) ant.hasMoved = True returnState.inventories[returnState.whoseTurn].ants.append(ant) elif move.moveType == END: #take care of end of turn business for ants and contructions for ant in returnState.inventories[returnState.whoseTurn].ants: constrUnderAnt = getConstrAt(returnState, ant.coords) if constrUnderAnt is not None: #if constr is enemy's and ant hasn't moved, affect capture health of buildings if type(constrUnderAnt) is Building and not ant.hasMoved and not constrUnderAnt.player == returnState.whoseTurn: constrUnderAnt.captureHealth -= 1 if constrUnderAnt.captureHealth == 0 and constrUnderAnt.type != ANTHILL: constrUnderAnt.player = returnState.whoseTurn constrUnderAnt.captureHealth = CONSTR_STATS[constrUnderAnt.type][CAP_HEALTH] #have all worker ants on food sources gather food elif constrUnderAnt.type == FOOD and ant.type == WORKER: ant.carrying = True #deposit carried food (only workers carry) elif (constrUnderAnt.type == ANTHILL or constrUnderAnt.type == TUNNEL) and ant.carrying: returnState.inventories[returnState.whoseTurn].foodCount += 1 ant.carrying = False #reset hasMoved on all ants of player ant.hasMoved = False returnState.whoseTurn = (returnState.whoseTurn + 1)% 2 return returnState
def prediction(self, prevState, currentState, move): if move.moveType == MOVE_ANT: initCoord = move.coordList[0] finalCoord = move.coordList[-1] inventories = currentState.inventories[self.playerId] myAnts = inventories.ants index = 0 for ant in currentState.inventories[self.playerId].ants: if ant.coords == initCoord: ant.coords = finalCoord ant.hasMoved = True index +=1 return self.pointValue(prevState, currentState) elif move.moveType == BUILD: coord = move.coordList[0] currentPlayerInv = currentState.inventories[currentState.whoseTurn] tunnel = currentPlayerInv.getAnthill() tunnelCoords = tunnel.coords if move.buildType == TUNNEL: currentPlayerInv.foodCount -= CONSTR_STATS[move.buildType][BUILD_COST] tunnel = Building(coord, TUNNEL, currentState.whoseTurn) currentPlayerInv.constrs.append(tunnel) else: currentPlayerInv.foodCount -= UNIT_STATS[move.buildType][COST] ant = Ant(coord, move.buildType, currentState.whoseTurn) ant.hasMoved = True currentState.inventories[self.playerId].ants.append(ant) currentState.inventories[currentState.whoseTurn].ants.append(ant) return self.pointValue(prevState, currentState)
def test( ): a = Ant.Ant( 0, x = 200, y = 100 ) b = Ant.Ant( 0, x = 100, y = 200 ) while True: a.angle = 0 b.angle = PI / 3.0 show_img( grid_ ) draw_ant( a, grid_ ) draw_ant( b, grid_ ) show_img( grid_ )
def expandNode(self, currentState, move): gameState = currentState.fastclone() # ourInventory = gameState.inventories[self.playerId] ourId = gameState.whoseTurn ourInventory = gameState.inventories[gameState.whoseTurn] if (move.moveType == MOVE_ANT): antToMove = None for ant in ourInventory.ants: if ant.coords == move.coordList[0]: antToMove = ant if antToMove is not None: antToMove.coords = move.coordList[-1] antToMove.hasMoved = True # check if other ants near by for attack opponentId = self.getOpponentId(gameState.whoseTurn) enemyInv = gameState.inventories[opponentId] ## Checks if can attack. self.attackSequence(enemyInv, antToMove) elif (move.moveType == BUILD): # just worried about building Ants and Tunnel if (move.buildType == WORKER): # add ant ourInventory.ants.append(Ant(move.coordList[-1], WORKER, ourId)) # subtract food ourInventory.foodCount -= 1 elif (move.buildType == DRONE): ourInventory.ants.append(Ant(move.coordList[-1], DRONE, ourId)) ourInventory.foodCount -= 1 elif (move.buildType == SOLDIER): ourInventory.ants.append( Ant(move.coordList[-1], SOLDIER, ourId)) ourInventory.foodCount -= 2 elif (move.buildType == R_SOLDIER): ourInventory.ants.append( Ant(move.coordList[-1], R_SOLDIER, ourId)) ourInventory.foodCount -= 2 elif (move.buildType == TUNNEL): ourInventory.constrs.append( Building(move.coordList[-1], TUNNEL, ourId)) ourInventory.foodCount -= 3 else: self.pickUpFood(gameState, ourInventory) self.dropOffFood(gameState, ourInventory) return gameState return gameState
def initAnts(self): ratio = self.population_size / self.node_count if (ratio < 1): set_selected_nodes = sample(list(range(self.node_count)), self.population_size) for node in set_selected_nodes: self.population.append(Ant(node)) else: if (ratio != int(ratio)): exit( 'If the population is bigger than the number of nodes, the population size must be divisible by the number of nodes.' ) for j in range(int(ratio)): for i in range(self.node_count): self.population.append(Ant(i))
def do_turn(self, ants): ants.orders.clear() ants.destinations.clear() # update ant list - my ants should be updated to reflect # where they were ordered to go last turn. # so any ants not in the ant_list are new. if len(ants.my_ants()) != len(self.ant_list): expected_locs = [] for ant in self.ant_list: expected_locs.append(ant.loc) for loc in ants.my_ants(): if loc not in expected_locs: self.ant_list.append(Ant(ants, loc)) # likewise, any dead ants should be removed. for loc in ants.dead_list: for ant in self.ant_list: if loc == ant.loc: self.ant_list.remove(loc) sys.stderr.write('ants: ' + str(len(self.ant_list)) + '\n') # connect previously invisible ants.nodes to the graph # and remove ants.nodes that have all neighbors mapped from unfinished for node in ants.unfinished_nodes[:]: if ants.visible(node.loc): finished = True for neighbor_loc in ants.neighbors(node.loc): if ants.visible(neighbor_loc): neighbor_node = ants.nodes[neighbor_loc] if not node in ants.graph.keys(): ants.graph[node] = set([neighbor_node]) else: ants.graph[node].add(neighbor_node) else: finished = False if finished: ants.unfinished_nodes.remove(node) # add all ants.destinations for food_loc in ants.food(): ants.destinations.add(food_loc) for hill_loc, hill_owner in ants.enemy_hills(): ants.destinations.add(hill_loc) for unseen_loc in self.unseen: ants.destinations.add(unseen_loc) ant_dist = [] for dest in ants.destinations: for ant in self.ant_list: dist = ants.distance(ant.loc, dest) ant_dist.append((dist, ant, dest)) ant_dist.sort() for dist, ant, dest in ant_dist: ant.do_move_location(dest) # move all ants to their next locitions for ant in self.ant_list: ant.moveToNext()
def doBuild(self, nextState, move): coord = move.coordList[0] currentPlayerInv = nextState.inventories[nextState.whoseTurn] #subtract the cost of the item from the player's food count if move.buildType == TUNNEL: currentPlayerInv.foodCount -= CONSTR_STATS[move.buildType][BUILD_COST] tunnel = Building(coord, TUNNEL, nextState.whoseTurn) nextState.board[coord[0]][coord[1]].constr = tunnel else: currentPlayerInv.foodCount -= UNIT_STATS[move.buildType][COST] ant = Ant(coord, move.buildType, nextState.whoseTurn) ant.hasMoved = True nextState.board[coord[0]][coord[1]].ant = ant nextState.inventories[nextState.whoseTurn].ants.append(ant)
def initialiseAntPopulation(self,numAnts): """ Initialise population with the GBO ant variant """ AntColony = [] for i in range(numAnts): AntColony.append(Ant.Ant_GBO(self.Lg)) return np.array(AntColony)
def genState(self, currentState, moveAction): simpleState = currentState.fastclone() opponentId = 0 if self.playerId == 0: opponentId = 1 if moveAction.moveType == MOVE_ANT: #move the ant. movingAnt = getAntAt(simpleState, moveAction.coordList[0]) if movingAnt == None: return None movingAnt.coords = moveAction.coordList[len(moveAction.coordList) - 1] #assume we attack an ant nearby # (in the case of multiple targets this may be inaccurate) for coord in listAdjacent(movingAnt.coords): ant = getAntAt(simpleState, coord) if ant != None and ant.player != self.playerId: ant.health -= UNIT_STATS[movingAnt.type][ATTACK] #an ant has died if ant.health <= 0: simpleState.inventories[opponentId].ants.remove(ant) break #worker ants pick up food if they end turn on a food foods = getConstrList(simpleState, None, [(FOOD)]) for food in foods: if movingAnt.type == WORKER and food.coords == movingAnt.coords: movingAnt.carrying = True #worker ants drop food if they end turn on the goals goals = getConstrList(simpleState, None, types=(ANTHILL, TUNNEL)) for goal in goals: if movingAnt.type == WORKER and goal.coords == movingAnt.coords and movingAnt.carrying: movingAnt.carrying = False simpleState.inventories[self.playerId].foodCount += 1 elif moveAction.moveType == BUILD: # decrease the food amount for the player simpleState.inventories[self.playerId].foodCount -= UNIT_STATS[ moveAction.buildType][COST] if simpleState.inventories[self.playerId].foodCount < 0: return None #add the appropriate ant to the player's inventory newAnt = Ant(moveAction.coordList[0], moveAction.buildType, self.playerId) simpleState.inventories[self.playerId].ants.append(newAnt) # elif moveAction.moveType == END: # we made no change return simpleState
def create_ants(self, testAnts, loc,myHive, myEnv, job): color = myHive.get_color() #print color for i in n.arange(n.alen(testAnts)): #print loc testAnts[i] = a.ANT(loc[0],loc[1],0,0, self.canvas.create_rectangle(loc[0]*self.size_ratio ,loc[1] *self.size_ratio + self.size_ratio,(loc[0]*self.size_ratio),loc[1]*self.size_ratio, outline = color), myHive, myEnv, job) myEnv.set_number_ants_in_desert(1);
def setUp(self): board = [[Location((col, row)) for row in xrange(0, BOARD_LENGTH)] for col in xrange(0, BOARD_LENGTH)] #Initialize all the ants p1Queen = Ant((1, 0), QUEEN, PLAYER_ONE) p2Queen = Ant((1, 8), QUEEN, PLAYER_TWO) p1Worker1 = Ant((0, 3), WORKER, PLAYER_ONE) p2Worker1 = Ant((4, 6), WORKER, PLAYER_TWO) p1Worker2 = Ant((6, 2), WORKER, PLAYER_ONE) p1Worker2.carrying = True p2Worker2 = Ant((6, 7), WORKER, PLAYER_TWO) p1Drone1 = Ant((4, 5), DRONE, PLAYER_ONE) p1Drone2 = Ant((2, 3), DRONE, PLAYER_ONE) p1Ants = [p1Queen, p1Worker1, p1Worker2, p1Drone1, p1Drone2] p2Ants = [p2Queen, p2Worker1, p2Worker2] #Initialize all the constructions p1Anthill = Building((1, 1), ANTHILL, PLAYER_ONE) p2Anthill = Building((1, 8), ANTHILL, PLAYER_TWO) p1Tunnel = Building((6, 2), TUNNEL, PLAYER_ONE) p2Tunnel = Building((7, 8), TUNNEL, PLAYER_TWO) allFood = [Construction((0, 3), FOOD), Construction((5, 2), FOOD), Construction((2, 8), FOOD), Construction((6, 7), FOOD)] #Populate the players' inventories self.p1Inventory = Inventory(PLAYER_ONE, p1Ants, [p1Anthill, p1Tunnel], 2) self.p2Inventory = Inventory(PLAYER_TWO, p2Ants, [p2Anthill, p2Tunnel], 2) nInventory = Inventory(NEUTRAL, [], allFood, 0) #Put the ants on the board for ant in p1Ants: board[ant.coords[0]][ant.coords[1]].ant = ant for ant in p2Ants: board[ant.coords[0]][ant.coords[1]].ant = ant #Put the constructs on the board for construct in self.p1Inventory.constrs: board[construct.coords[0]][construct.coords[1]].constr = construct for construct in self.p2Inventory.constrs: board[construct.coords[0]][construct.coords[1]].constr = construct #Put the food on the board for food in allFood: board[food.coords[0]][food.coords[1]].constr = food self.state = GameState(board, [self.p1Inventory, self.p2Inventory, nInventory], PLAY_PHASE, PLAYER_ONE)
def _initialize_ants(dataset, num_ants, num_clusters, beta, prob_cutoff, pheromones): ''' Initialize the population of ants. ''' ants = [] for i in range(num_ants): ant = Ant.ant(dataset, num_clusters, beta, prob_cutoff, pheromones) ants.append(ant) return ants
def populate(self): for i in range(self.population): found_unused_cell = False while not found_unused_cell: x, y = random.randint(0, self.world_size - 1), random.randint( 0, self.world_size - 1) if self.map[y][x] is None: found_unused_cell = True self.map[y][x] = Ant(pos=(x, y), world=self, ant_type=WORKER_ANT, change_factor=self.change_factor)
def addAnt(self): colony = self.getTile(self.colony) newAnt = None if not colony.getAnt(): newAnt = Ant.Ant(self.colony, self.antNumber) self.antNumber = self.antNumber + 1 self.newAntCount = self.newAntCount - 1 self.ants.append(newAnt) colony.setAnt(newAnt) return newAnt
def runTest(Location): import Ant import Construction ant1 = Ant.Ant((2, 3), Ant.QUEEN, 1) ant2 = Ant.Ant((5, 6), Ant.WORKER, 1) construction1 = Construction.Construction((3, 4), Construction.TUNNEL) testLocation = Location.Location((2, 3)) testLocation2 = Location.Location((4, 5)) testLocation.ant = ant1 testLocation.constr = construction1 if (testLocation.ant == None): raise Exception( "Ant is not found at a location where there should be an Ant") if (testLocation.constr == None): raise Exception( "Construction is not found at a location where they should be a Construction" ) if (testLocation2.ant != None): raise Exception("Ant is found at a location where there is no Ant") if (testLocation2.constr != None): raise Exception( "Construction is found at a location where there is not Construction" ) locationClone = testLocation.clone() if locationClone == testLocation: raise Exception("The cloned location is equal to the original") if locationClone.ant != testLocation.ant: raise Exception( "The cloned location does not have the same ant object as the original location" ) if locationClone.constr != testLocation.constr: raise Exception( "The cloned location does not have the same construction as the original location" ) locationClone.ant = ant2 if locationClone.ant == testLocation.ant: raise Exception( "The ant on the cloned location has been changed but is not recognized as different from the original location" )
def main(fname1, fname2): data = [] ant = [] # データの読み込み O_data = pd.read_csv(fname1) code_data = pd.read_csv(fname2) V_data = O_data.values V_code_data = code_data.values # np.random.shuffle(V_data) #ランダムに並び替え T_data = V_data.tolist() T_code_data = V_code_data.tolist() # データを0~1に標準化 vmin = float(V_data.min()) vmax = float(V_data.max()) V_data = (V_data - vmin) / (vmax - vmin) data = V_data.tolist() # 標準化されたデータのリスト X = [] # ant.append(Ant.Ant([],0,0)) #root 根 サポート役 for i in range(len(T_code_data)): # アリ(データ)の初期化 ant.append(Ant.d_Ant(data[i], i, 0, int(T_code_data[i][0]))) X.append(T_data[i]) # cluster_Ant用 # 木の構築 count1 = 0 # 繰り返しの上限 count2 = 0 # 接続済みアリのカウント while count1 < 1000 and count2 < len(data) - 1: count2 = 0 for ai in ant[1:]: # 0番目はサポート if ai.conect == False: a_pos = ant[ai.a_pos] build_organize(a_pos, ai, ant) else: count2 = count2 + 1 count1 = count1 + 1 # ----サポート(root)の子の中で一番類似するデータ---- tmp = 0 for i in ant[0].children: if Sim(ant[0], ant[i]) > tmp: tmp = Sim(ant[0], ant[i]) ant[0].set_plus(i) # --------------------------------------------------- ant[0].set_parent(0) X = np.array(X) return ant, X, count1 - 1
def prediction(self, currentState, move): # get a fastclone of the state currentState = currentState.fastclone() # for movement moves evaluate the ants' movements if move.moveType == MOVE_ANT: startCoord = move.coordList[0] endCoord = move.coordList[-1] #take ant from start coord antToMove = getAntAt(currentState, startCoord) #change ant's coords and hasMoved status antToMove.coords = (endCoord[0], endCoord[1]) antToMove.hasMoved = True # for build moves, determine what was built, then add that to the appropriate list elif move.moveType == BUILD: coord = move.coordList[0] currentPlayerInv = currentState.inventories[currentState.whoseTurn] if move.buildType == TUNNEL: #subtract the cost of the item from the player's food count currentPlayerInv.foodCount -= CONSTR_STATS[move.buildType][BUILD_COST] # add the tunnel to our list of constructions tunnel = Building(coord, TUNNEL, currentState.whoseTurn) currentPlayerInv.constrs += tunnel else: #subtract the cost of the item from the player's food count currentPlayerInv.foodCount -= UNIT_STATS[move.buildType][COST] # add the ant to our list of ants ant = Ant(coord, move.buildType, currentState.whoseTurn) ant.hasMoved = True currentState.inventories[currentState.whoseTurn].ants.append(ant) return currentState
def __init__(self, num_ant=10, w_heuristic=2, w_pheromone_vapor=0.1, q0=0.9, p=0.1, max_gen=2500, city_name=""): self.m = num_ant # 蚂蚁数目 self.b = w_heuristic # 启发式信息权重 self.a = w_pheromone_vapor # 信息素挥发因子 self.t0 = 0.0 # 初始信息素 self.q0 = q0 # 伪随机因子 self.p = p # 信息素局部挥发因子 self.gen = max_gen # 最大进化代数 self.ant = np.zeros(self.m, dtype=Ant) # 蚁群 self.best = Ant() # 历史最优蚂蚁 self.city = City(city_name) # 城市对象 self.dis_matrix = self.city.get_dis_matrix() # 距离矩阵 self.num_city = self.city.num_city # 城市数量 self.pheromone_matrix = np.zeros((self.num_city, self.num_city), dtype=float) # 信息素矩阵
def unitTest1(): board = [[Location((col, row)) for row in range(0, BOARD_LENGTH)] for col in range(0, BOARD_LENGTH)] p1Inventory = Inventory(PLAYER_ONE, [], [], 10) p2Inventory = Inventory(PLAYER_TWO, [], [], 0) neutralInventory = Inventory(NEUTRAL, [], [], 0) state = GameState(board, [p1Inventory, p2Inventory, neutralInventory], MENU_PHASE, PLAYER_ONE) #Add an ant to move ant = Ant((0, 0), WORKER, 0) board[0][0].ant = ant p1Inventory.ants.append(ant) player = AIPlayer(0) newState = player.hypotheticalMove( state, Move(MOVE_ANT, ((0, 0), (0, 1), (0, 2)), None)) if tuple(newState.inventories[0].ants[0].coords) != (0, 2): print "didn't move ant" return False #test adding a building newState = player.hypotheticalMove(state, Move(BUILD, ((3, 3), ), TUNNEL)) if len(newState.inventories[0].constrs) == 0: print "didn't create construction" return False if newState.inventories[0].constrs[0].type != TUNNEL: print "created wrong type of construction" return False if tuple(newState.inventories[0].constrs[0].coords) != (3, 3): print "created construction at wrong place" return False if newState.inventories[0].foodCount != 7: print "didn't subtract food cost" return False return True
def start(scene, city): global cities, numberOfCities resultFile = open("results", "w") cities = city numberOfCities = len(cities) tau0 = 1 / (len(cities) * nearestNeighbor(list(cities), resultFile) ) # copying cities list and send nn algorithm # tau0 = (n * Cnn )^-1 # create Ants for i in range(0, numberOfAnts): ants.append(Ant(i)) systemStart(scene, iteration, cities, ants, pheromoneMatrix, numberOfCities, numberOfAnts, beta, q0, rho, ksi, tau0, resultFile)
def iteration(self): antSet = [Ant(self.n, self.lst) for i in range(self.noAnts)] for i in range(self.n * self.n): for x in antSet: x.addMove(self.q0, self.trace, self.alpha, self.beta) dTrace = [ 1.0 / intermediate_fitness(antSet[i].path, antSet[i]) for i in range(len(antSet)) ] for i in range(self.n * self.n): for j in range(self.n * self.n): self.trace[i][j] = (1 - self.rho) * self.trace[i][j] for i in range(len(antSet)): for j in range(len(antSet[i].path) - 1): x = int(antSet[i].pheromones[j]) y = int(antSet[i].pheromones[j + 1]) self.trace[x][y] = self.trace[x][y] + dTrace[i] f = [[intermediate_fitness(antSet[i].path, antSet[i]), i] for i in range(len(antSet))] f = min(f) return antSet[f[1]].path
def loadingFile(): """ load the file with the last saved data, makes a split method that puts you located in the file lists the position as 0 and 1 at position 1 are all values suggar, poison, wine Clod and the size of the matrix, equals the globals variables to change the value of the same """ global wineCount global poisonCount global sugarCount global nameAntFile global sizeMatrixGlobals global antInstance file = open("Settings.txt", "r") dataLines = file.readlines() for line in dataLines: info = line.split(",") if info[0] == "wineClod": wineCount = int(info[1]) if info[0] == "poisonClod": poisonCount = int(info[1]) if info[0] == "sugarClod": sugarCount = int(info[1]) if info[0] == "sizeMatrix": sizeMatrixGlobals = int(info[1]) if info[0] == "nameAnt": nameAntFile = info[1] antInstance = Ant(info[1]) file.close()
def init(self): # 初始化所有蚂蚁 for i in range(self.m): self.ant[i] = Ant() self.ant[i].path.resize(self.num_city) # 信息素初始化 (贪婪选择一条道路) seq = np.zeros(self.num_city, dtype=int) flag = np.zeros(self.num_city, dtype=int) seq[0] = np.random.randint(self.num_city) flag[seq[0]] = 1 # 创建下一个城市的信息数组 next_city = np.zeros(shape=self.num_city, dtype=NextCityInit) for i in range(self.num_city): next_city[i] = NextCityInit() # 贪婪选择 s = 0.0 for i in range(self.num_city - 1): for j in range(self.num_city): next_city[j].dis = self.dis_matrix[seq[i]][j] next_city[j].id = j next_city.sort() for j in range(1, self.num_city): if flag[next_city[j].id] == 0: seq[i + 1] = next_city[j].id s = s + next_city[j].dis flag[next_city[j].id] = 1 break s = s + self.dis_matrix[0][seq[self.num_city - 1]] # 计算信息素 self.t0 = 1.0 / (self.num_city * s) for i in range(self.num_city): for j in range(self.num_city): self.pheromone_matrix[i][j] = self.t0
x = 300 colony_ = (x,x) source_ = map(lambda a: a - x, grid_.shape) pp1_ = [ colony_, (200,200), (300,150), (500,100), (800, 200), (850,400), source_ ] pp2_ = [ colony_, (400,400), (550,800), source_ ] pp3_ = [ colony_, (400,800), (800,800), source_ ] p1_ = spline_fit( pp1_ ) p2_ = spline_fit( pp2_ ) p3_ = spline_fit( pp3_ ) paths_ = [ p1_, p2_, p3_ ] # Initially all ants are colony ants_ = [ Ant.Ant(i, x=colony_[0], y=colony_[1]) for i in range( 10000 ) ] def show_img( img ): cv2.imshow( "grid", img ) cv2.waitKey( 10 ) def show_path( path, img, weight = 1 ): cv2.polylines( img, [path], False, weight, 1) def updateAnts( ): global ants_ # Scan in neighbouring direction and select the best direction to [ a.scanAndMove( ) for a in ants_ ] def show_ants( length = 5 ): global grid_
def hypotheticalMove(self, state, move): newState = state.fastclone() if move.moveType == END: newState.whoseTurn = 1 - state.whoseTurn return newState elif move.moveType == MOVE_ANT: ant = getAntAt(newState, move.coordList[0]) ant.coords = move.coordList[-1] #check if ant is depositing food if ant.carrying: if tuple(ant.coords) in self.buildingCoords[self.playerId]: ant.carrying = False newState.inventories[self.playerId].foodCount += 1 #check if ant is picking up food if not ant.carrying: if tuple(ant.coords) in self.foodCoords: ant.carrying = True #check if ant can attack targets = [] #coordinates of attackable ants range = UNIT_STATS[ant.type][RANGE] for ant in newState.inventories[1 - self.playerId].ants: dist = math.sqrt((ant.coords[0] - ant.coords[0])**2 + (ant.coords[1] - ant.coords[1])**2) if dist <= range: #target is in range and may be attacked targets.append(ant.coords) if targets: #Attack the ant chosen by the AI target = self.getAttack(newState, ant, targets) targetAnt = getAntAt(newState, target) targetAnt.health -= UNIT_STATS[ant.type][ATTACK] if targetAnt.health <= 0: #Remove the dead ant newState.inventories[1 - self.playerId].ants.remove(targetAnt) ant.hasMoved = True else: #Move type BUILD if move.buildType in (WORKER, DRONE, SOLDIER, R_SOLDIER): #Build ant on hill ant = Ant(move.coordList[0], move.buildType, self.playerId) newState.inventories[self.playerId].ants.append(ant) newState.inventories[self.playerId].foodCount -= UNIT_STATS[ move.buildType][COST] else: #build new building building = Building(move.coordList[0], move.buildType, self.playerId) newState.inventories[self.playerId].constrs.append(building) newState.inventories[self.playerId].foodCount -= CONSTR_STATS[ move.buildType][BUILD_COST] return newState
def getNextState(currentState, move): # variables I will need myGameState = currentState.fastclone() myInv = getCurrPlayerInventory(myGameState) me = myGameState.whoseTurn myAnts = myInv.ants # If enemy ant is on my anthill or tunnel update capture health myTunnels = myInv.getTunnels() myAntHill = myInv.getAnthill() for myTunnel in myTunnels: ant = getAntAt(myGameState, myTunnel.coords) if ant is not None: opponentsAnts = myGameState.inventories[not me].ants if ant in opponentsAnts: myTunnel.captureHealth -= 1 if getAntAt(myGameState, myAntHill.coords) is not None: ant = getAntAt(myGameState, myAntHill.coords) opponentsAnts = myGameState.inventories[not me].ants if ant in opponentsAnts: myAntHill.captureHealth -= 1 # If an ant is built update list of ants antTypes = [WORKER, DRONE, SOLDIER, R_SOLDIER] if move.moveType == BUILD: if move.buildType in antTypes: ant = Ant(myInv.getAnthill().coords, move.buildType, me) myInv.ants.append(ant) # Update food count depending on ant built if move.buildType == WORKER: myInv.foodCount -= 1 elif move.buildType == DRONE or move.buildType == R_SOLDIER: myInv.foodCount -= 2 elif move.buildType == SOLDIER: myInv.foodCount -= 3 # If a building is built update list of buildings and the update food count if move.moveType == BUILD: if move.buildType == TUNNEL: building = Construction(move.coordList[0], move.buildType) myInv.constrs.append(building) myInv.foodCount -= 3 # If an ant is moved update their coordinates and has moved if move.moveType == MOVE_ANT: newCoord = move.coordList[len(move.coordList) - 1] startingCoord = move.coordList[0] for ant in myAnts: if ant.coords == startingCoord: ant.coords = newCoord ant.hasMoved = False # If an ant is carrying food and ends on the anthill or tunnel drop the food if ant.carrying and ant.coords == myInv.getAnthill().coords: myInv.foodCount += 1 ant.carrying = False for tunnels in myTunnels: if ant.carrying and (ant.coords == tunnels.coords): myInv.foodCount += 1 ant.carrying = False # If an ant doesn't have food and ends on the food grab food if not ant.carrying: foods = getConstrList(myGameState, None, (FOOD, )) for food in foods: if food.coords == ant.coords: ant.carrying = True # If my ant is close to an enemy ant attack it adjacentTiles = listAdjacent(ant.coords) for adj in adjacentTiles: if getAntAt(myGameState, adj) is not None: # If ant is adjacent my ant closeAnt = getAntAt(myGameState, adj) if closeAnt.player != me: # if the ant is not me closeAnt.health = closeAnt.health - UNIT_STATS[ ant.type][ATTACK] # attack # If an enemy is attacked and looses all its health remove it from the other players # inventory if closeAnt.health <= 0: enemyAnts = myGameState.inventories[ not me].ants for enemy in enemyAnts: if closeAnt.coords == enemy.coords: myGameState.inventories[ not me].ants.remove(enemy) # If attacked an ant already don't attack any more break return myGameState
def putTheirInventory(inventory): inventory.constrs.append(Construction((0, 7), ANTHILL)) inventory.constrs.append(Construction((1, 7), TUNNEL)) queen = Ant((0, 7), QUEEN, PLAYER_TWO) queen.health = 1 inventory.ants.append(queen) # Queen
def putOurInventory(inventory): inventory.constrs.append(Construction((0,3), ANTHILL)) inventory.constrs.append(Construction((1,3), TUNNEL)) inventory.ants.append(Ant((0,3), QUEEN, PLAYER_ONE)) # Queen inventory.ants.append(Ant((0,6), DRONE, PLAYER_ONE)) # Queen
def getNextState(currentState, move): # variables I will need myGameState = currentState.fastclone() myInv = getCurrPlayerInventory(myGameState) me = myGameState.whoseTurn myAnts = myInv.ants myTunnels = myInv.getTunnels() myAntHill = myInv.getAnthill() # If enemy ant is on my anthill or tunnel update capture health ant = getAntAt(myGameState, myAntHill.coords) if ant is not None: if ant.player != me: myAntHill.captureHealth -= 1 # If an ant is built update list of ants antTypes = [WORKER, DRONE, SOLDIER, R_SOLDIER] if move.moveType == BUILD: if move.buildType in antTypes: ant = Ant(myInv.getAnthill().coords, move.buildType, me) myInv.ants.append(ant) # Update food count depending on ant built myInv.foodCount -= UNIT_STATS[move.buildType][COST] # ants are no longer allowed to build tunnels, so this is an error elif move.buildType == TUNNEL: print("Attempted tunnel build in getNextState()") return currentState # If an ant is moved update their coordinates and has moved elif move.moveType == MOVE_ANT: newCoord = move.coordList[-1] startingCoord = move.coordList[0] for ant in myAnts: if ant.coords == startingCoord: ant.coords = newCoord # TODO: should this be set true? Design decision ant.hasMoved = False # If an ant is carrying food and ends on the anthill or tunnel drop the food if ant.carrying and ant.coords == myInv.getAnthill().coords: myInv.foodCount += 1 ant.carrying = False for tunnels in myTunnels: if ant.carrying and (ant.coords == tunnels.coords): myInv.foodCount += 1 ant.carrying = False # If an ant doesn't have food and ends on the food grab food if not ant.carrying and ant.type == WORKER: foods = getConstrList(myGameState, 2, [FOOD]) for food in foods: if food.coords == ant.coords: ant.carrying = True # If my ant is close to an enemy ant attack it attackable = listAttackable(ant.coords, UNIT_STATS[ant.type][RANGE]) for coord in attackable: foundAnt = getAntAt(myGameState, coord) if foundAnt is not None: # If ant is adjacent my ant if foundAnt.player != me: # if the ant is not me foundAnt.health = foundAnt.health - UNIT_STATS[ ant.type][ATTACK] # attack # If an enemy is attacked and looses all its health remove it from the other players # inventory if foundAnt.health <= 0: myGameState.inventories[1 - me].ants.remove( foundAnt) # If attacked an ant already don't attack any more break return myGameState
def main(neuralNetwork): ########## global GEN_NUM, food_storage food_storage = [] for i in range(100): food_storage.append((random.randrange(0, GRID_WIDTH), random.randrange(0, GRID_HEIGHT))) ants = {} GEN_NUM += 1 # nets = [] # ge = [] ge = {} nets = {} ant_id = 0 for net in neuralNetwork: nets[ant_id] = net ants[ant_id] = Ant(10, 10) ge[ant_id] = 0 ant_id += 1 ########## QUIT = False while QUIT == False: if gui: clock.tick(FPS) rem_ants = set() for ant_id, ant in ants.items(): brainInput = ant.createVision() brainInput = brainInput.reshape(brainInput.shape[0], 1) brainOutput = nets[ant_id].forward_propagation(brainInput) performance, isIn = ant.move(brainOutput) if isIn ==False: rem_ants.add(ant_id) ge[ant_id] += performance else: ge[ant_id] += performance if ant.num_moves > ant.allowed_moves: rem_ants.add(ant_id) if gui: for event in pygame.event.get(): if event.type == pygame.QUIT: QUIT = True pygame.quit() quit() # elif event.type == pygame.KEYDOWN: # if event.key == pygame.K_LEFT: # output[2] = 1 # elif event.key == pygame.K_UP: # output[3] = 1 # elif event.key == pygame.K_RIGHT: # output[4] = 1 # elif event.key == pygame.K_DOWN: # output[0] = 1 # for ant in ants: # valid = ant.move(output) # if not valid: # rem_ants.add(ant) for ant_id in rem_ants: ants.pop(ant_id) if len(ants) == 0: QUIT = True if gui: WIN.fill((255, 255, 255)) for ant_id, ant in ants.items(): ant.draw(WIN, ANT_IMAGE) # ant.move(np.random.rand(5)) pygame.display.update() return ge
def initialiseAntPopulation(self, numAnts): AntColony = [] for i in range(numAnts): AntColony.append(Ant.Ant_BBO(self.Lg)) return np.array(AntColony)
def addAnt(self): self.ants.append(a.Ant(self.frame, self.width, self.height, self.x, self.y, self.land[self.startx][self.starty]))
continue return round(eval, 8) ## # UNIT TESTING SECTION ## aiPlayer = AIPlayer(PLAYER_ONE) ### Test 1 ### # Build a Drone # build a test board antCarrying = Ant((3, 3), WORKER, PLAYER_ONE) antCarrying.carrying = True inventory1 = Inventory(PLAYER_ONE, [ Ant((4, 2), WORKER, PLAYER_ONE), antCarrying, Ant((7, 0), SOLDIER, PLAYER_ONE), Ant((0, 0), QUEEN, PLAYER_ONE) ], [ Building((2, 2), ANTHILL, PLAYER_ONE), Building((3, 4), TUNNEL, PLAYER_ONE) ], 1) inventory2 = Inventory(PLAYER_TWO, [ Ant((0, 9), SOLDIER, PLAYER_TWO), Ant((1, 9), WORKER, PLAYER_TWO),
# This agent doens't learn # def registerWin(self, hasWon): #method templaste, not implemented pass # UNIT TEST # Here we test the methods we wrote for Homework 2 # First we check our getValue function, this function evaluates a state # Case 1 (simple) # Check state with AI has only queen as ant and 0 food, with the enemy having a worker ant # The AI has lost, so function should return -1 basicState = GameState(0, 0, 0, 0).getBasicState() randomAnt = Ant((0, 1), WORKER, 1) basicState.inventories[1].ants.append(randomAnt) AIplayer = AIPlayer(1) value = AIplayer.getValue(basicState) rightValue = -1 if not math.isclose(value, rightValue): print("Error, the getValue function gives the value ", value, \ "instead of the value ", rightValue, ".") # Case 2 (complex) # Check state with queen, one soldier ant and 5 food for the AI # versus queen and one ant and one food for the opponent randomSoldierAnt = Ant((0, 1), R_SOLDIER, 1) basicState.inventories[0].ants.append(randomSoldierAnt) basicState.inventories[0].foodCount = 5 enemyWorkerAnt = Ant((0, 2), WORKER, 1) basicState.inventories[1].ants.append(enemyWorkerAnt)
def spline_fit( path ): nPoints = 4 * int( Ant.distance( path[0], path[-1] )) tck, u = scipy.interpolate.splprep( zip(*path), s=0.0 ) xi, yi = scipy.interpolate.splev( np.linspace(0,1,nPoints), tck ) pts = np.array( zip( xi, yi ), np.int32 ) return pts
def nextState(self, currentState, currMove): #make a clone of the current State nState = currentState.fastclone() #Get my inventory myInv = None oInv = None for inv in nState.inventories: if inv.player == nState.whoseTurn: myInv = inv else: oInv = inv #Apply Our Move #If we have a MOVE_ANT moveType if currMove.moveType == MOVE_ANT: startCoord = currMove.coordList[0] endCoord = currMove.coordList[-1] #take ant from start coord antToMove = getAntAt(nState, (startCoord[0], startCoord[1])) #change ant's coords antToMove.coords = (endCoord[0], endCoord[1]) #assign ant to antToMove in inventory for ant in myInv.ants: if ant.coords == antToMove.coords: ant = antToMove ant.hasMoved = True #find ants within attack range potentialTargets = [] for ant in oInv.ants: if self.distance(myAnt.coords,ant.coords)<= UNIT_STATS[myAnt.type][RANGE]: potentialTargets.append(ant.coords) #if there are ants within attack range, uses get attack to find a victim if potentialTargets != []: victim = self.getAttack(nState, antToMove, potentialTargets) #decrements the victim's health loseHealth = UNIT_STATS[antToMove.type][ATTACK] for ant in oInv.ants: if ant.coords == victim: ant.health -= loseHealth #removes the ant if its health is 0 if getAntAt(nState, (victim[0],victim[1])).ant.health <= 0: deadAnt = getAntAt(newState, (victim[0],victim[1])).ant oInv.ants.remove(deadAnt) #change ant carrying to true if it grabs food antConstr = getConstrAt(nState, antToMove.coords) if antConstr == FOOD and antToMove.type == WORKER: antToMove.carrying = true #add 1 to total food if ant carrying goes to anthill or tunnel if antToMove.carrying and (antConstr == TUNNEL or antConstr == ANTHILL): currentPlayerInv.foodCount += 1 antToMove.carrying = false #If we have a BUILD moveType elif currMove.moveType == BUILD: coord = currMove.coordList[0] currentPlayerInv = nState.inventories[nState.whoseTurn] #subtract the cost of the item from the player's food count if currMove.buildType == TUNNEL: currentPlayerInv.foodCount -= CONSTR_STATS[currMove.buildType][BUILD_COST] tunnel = Building(coord, TUNNEL, nState.whoseTurn) nState.board[coord[0]][coord[1]].constr = tunnel else: currentPlayerInv.foodCount -= UNIT_STATS[currMove.buildType][COST] ant = Ant(coord, currMove.buildType, nState.whoseTurn) ant.hasMoved = True nState.inventories[nState.whoseTurn].ants.append(ant) elif currMove.moveType == END: return nState return nState