def checkState(self, currentState, move): #Clone state modifiedState = currentState.fastclone() ants = modifiedState.inventories[self.playerId].ants if move.moveType == MOVE_ANT: #Get ant and update location startingCoord = move.coordList[0] for candidateAnt in ants: if candidateAnt.coords == startingCoord: ant = candidateAnt ant.coords = move.coordList[-1] #Allow worker ants to pick up and drop off food if ant.type == WORKER: constr = getConstrAt(modifiedState, ant.coords) #Let ant perform actions based on the construction that it's on if constr is not None: if constr.type == FOOD: ant.carrying = True elif ((constr.type == ANTHILL) or (constr.type == TUNNEL)) and ant.carrying: modifiedState.inventories[self.playerId].foodCount += 1 ant.carrying = False #Resolve attacks opponentId = (modifiedState.whoseTurn + 1) % 2 range = UNIT_STATS[ant.type][RANGE] #Find an enemy ant that is within range of the current ant for enemyAnt in modifiedState.inventories[opponentId].ants: #Check if the attack is valid diffX = abs(ant.coords[0] - enemyAnt.coords[0]) diffY = abs(ant.coords[1] - enemyAnt.coords[1]) #if attacking ant is within range of enemy ant, attack if range ** 2 >= diffX ** 2 + diffY ** 2: enemyAnt.health -= 1 if enemyAnt.health == 0: modifiedState.inventories[opponentId].ants.remove(enemyAnt) break #If move type is build, then get what to build elif move.moveType == BUILD: coord = move.coordList[0] currentPlayerInv = modifiedState.inventories[self.playerId] #subtract the cost of the item from the player's food count if move.buildType == TUNNEL: currentPlayerInv.foodCount -= CONSTR_STATS[move.buildType][BUILD_COST] currentPlayerInv.constrs.append(Building(coord, TUNNEL, modifiedState.whoseTurn)) else: currentPlayerInv.foodCount -= UNIT_STATS[move.buildType][COST] ant = Ant(coord, move.buildType, modifiedState.whoseTurn) currentPlayerInv.ants.append(ant) ant.hasMoved = True return modifiedState
def getMeetingAnts(self, ants): self._meetingAnts = [] for ant in [ant for ant in ants if ant.direction != self.direction]: if ant.direction == "N": antMeeting = Ant.caseWN(self, ant) if ant.direction == "S": antMeeting = Ant.caseWS(self, ant) if ant.direction == "E": antMeeting = Ant.caseWE(self, ant) if antMeeting.doTheyMeet: self._meetingAnts.append(AntsPairs(self, ant, antMeeting.distance)) return self._meetingAnts
def Sim(Iteration,origin,destination,richness,G,X,rate): currentIteration=1 while currentIteration<= Iteration: print "Iteration "+str(currentIteration)+" is running" a=Ant(origin,destination,richness) while (a.get_reached()!=1): a.update_location(G) #if a.get_current_location()==destination: # print 1 print 'Iteration '+str(currentIteration)+": Destination reached!" a.update_density(G,rate) #print 'In iteration' +str(currentIteration)+", ant takes: " + a. X.update(G,currentIteration) currentIteration=currentIteration+1 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) return G
def processMove(self, currentState, move): # create a bare-bones copy of the state to modify copyOfState = currentState.fastclone() # get references to the player inventories playerInv = copyOfState.inventories[copyOfState.whoseTurn] enemyInv = copyOfState.inventories[(copyOfState.whoseTurn + 1) % 2] if move.moveType == BUILD: # BUILD MOVE if move.buildType < 0: # building a construction playerInv.foodCount -= CONSTR_STATS[move.buildType][BUILD_COST] playerInv.constrs.append( Construction(move.coordList[0], move.buildType)) else: # building an ant playerInv.foodCount -= UNIT_STATS[move.buildType][COST] playerInv.ants.append( Ant(move.coordList[0], move.buildType, copyOfState.whoseTurn)) elif move.moveType == MOVE_ANT: # MOVE AN ANT # get a reference to the ant ant = getAntAt(copyOfState, move.coordList[0]) # update the ant's location after the move ant.coords = move.coordList[-1] ant.hasMoved = True # get a reference to a potential construction at the destination coords constr = getConstrAt(copyOfState, move.coordList[-1]) # check to see if the ant is on a food or tunnel or hill and act accordingly if constr: # we only care about workers if ant.type == WORKER: # if destination is food and ant can carry, pick up food if constr.type == FOOD: if not ant.carrying: ant.carrying = True # if destination is dropoff structure and and is carrying, drop off food elif constr.type == TUNNEL or constr.type == ANTHILL: if ant.carrying: ant.carrying = False playerInv.foodCount += 1 # get a list of the coordinates of the enemy's ants enemyAntCoords = [enemyAnt.coords for enemyAnt in enemyInv.ants] # contains the coordinates of ants that the 'moving' ant can attack validAttacks = [] # go through the list of enemy ant locations and check if # we can attack that spot, and if so add it to a list of # valid attacks (one of which will be chosen at random) for coord in enemyAntCoords: if UNIT_STATS[ant.type][RANGE]**2 >= abs( ant.coords[0] - coord[0])**2 + abs(ant.coords[1] - coord[1])**2: validAttacks.append(coord) # if we can attack, pick a random attack and do it if validAttacks: enemyAnt = getAntAt(copyOfState, random.choice(validAttacks)) attackStrength = UNIT_STATS[ant.type][ATTACK] if enemyAnt.health <= attackStrength: # just to be safe, set the health to 0 enemyAnt.health = 0 # remove the enemy ant from their inventory enemyInv.ants.remove(enemyAnt) else: # lower the enemy ant's health because they were attacked enemyAnt.health -= attackStrength # return the modified copy of the original state return copyOfState
pygame.display.set_caption("Ants!") # Font for rendering text font = pygame.font.SysFont("consolas", 10) # Create the map of tiles tileMap = TileMap() # Store all ants, living or dead, here. ants = [] paused = False # Create the user-requested number of ants. for i in range(0, numAnts): ant = Ant(tileMap.tiles) # Train the ant! AntBootCamp.train(ant) ants.append(ant) while True: # Count the number of living or dead ants alive = 0 dead = 0 for ant in ants: if ant.alive == False: dead += 1 else: alive += 1 # Show the number of living ants in the window caption pygame.display.set_caption(
def __init__(self, base): Ant.__init__(self, base) self.next_cell_for_patrol = self.base.API.get_coord_by_obj(self)
def main_ACO(ft, dimensions, bounds, dim_prec, stop_prec, a, c, w, ant_count, fitness, timeout): ants = Ant.init_colony(ant_count) best_fit_per_gen = 0 grid = Grid(dimensions, bounds, dim_prec) precs = [10e-2, 10e-3, 10e-4, 10e-5, 10e-6, 10e-7, 10e-8, 10e-9] precs_len = len(precs) curr_prec_i = 0 iters = [0] * precs_len best_ants = [] best_ant = Ant() best_ant.value = 100 # time_start = time.process_time() duration = 1 # res = {} # plt_value = [0] * (timeout + 1) # plt_iter = [i for i in range(timeout + 1)] best_fit = 0 best_value = 0 while (best_ant.value > -1 + precs[-1]) and (duration < timeout): # for ant in ants: ant.res = {} j = 0 for dim in grid.dimensions: j += 1 probs = [] total = 0 for r in range(dim_prec): prob = Ant.calc_prob(dim["pheromones"][r], a, c) probs.append(prob) total += prob r = rnd.random() for rng in range(grid.prec): prob = (probs[rng] / total if total != 0 else 0) if r <= prob: range_start = dim["from_bound"] + rng * dim["step"] ant.res["d{}".format( j)] = range_start + rnd.random() * dim["step"] break else: r -= prob ant.value = ft(list(ant.res.values())) ant.fit = fitness(ant.value) best_ant = max(ants, key=lambda p: p.fit) if best_ant.fit > best_fit: best_fit = best_ant.fit best_value = best_ant.value best_ants.append(best_ant.copy()) best_fit_per_gen = best_ant.fit grid.weather_pheromone(w) grid.leave_pheromone(ants) Ant.clear_colony(ants) # duration = time.process_time() - time_start # plt_value[duration] = best_ant.value while curr_prec_i < precs_len and best_ant.value < -1 + precs[ curr_prec_i]: # iters[curr_prec_i] = duration curr_prec_i += 1 if curr_prec_i == precs_len: break duration += 1 best_ant = max(best_ants, key=lambda p: p.fit) best_ant.value = ft(list(best_ant.res.values())) res = { "params": best_ant.res, "value": best_ant.fit, "fvalue": best_ant.value, "iters": iters # "time": time.process_time() - time_start } # plt_value[0] = plt_value[1] # # for value in plt_value: # # value *= 1000 # # plt.set_ylabel("value") # # plt.set_xlabel("iteration") # plt.plot(plt_iter, plt_value, c="blue") # plt.plot([0, timeout - 1], [0, 0], "--", c="red") # plt.show() return res
def create_single_job(self): self.create_jobs(1) x = self.jobs[0][0] + 80 y = self.jobs[0][1] + 80 ant = Ant(x, y, self) self.ants.append(ant)
def __generateAnts(self): ants = [] for i in range(0, self.__numberOfAnts): ants.append( Ant(randint(0, self.__network['noNodes'] - 1), self.__network)) return ants
def AddAnt(self, Ip: string): if not (self.FindAnt(Ip)): NewAnt = Ant(0, Ip) NewAnt.SetParameters(self.Alpha, self.Beta, self.Evaporation) self.Ants.append(NewAnt) self.DrawEdges(NewAnt)
raise ValueError("Width and height have to be evenly divisible by size") # Creating the sreen and its frame screen = pygame.display.set_mode([width, height]) pygame.display.set_caption("Langton's Ant") clock = pygame.time.Clock() done = False squares = [] # Calculating numbers of squares horizontally and vertically nx = width // size ny = height // size ant = Ant(nx,ny) # Filling the squares list with Square objects for i in range(0, width, size): line = [] for j in range(0, height, size): line.append(Square(i,j)) squares.append(line) # Function that draws squares on the screen def show(squares): global size for i in squares: for j in i: color = BLACK if j.state else WHITE pygame.draw.rect(screen, color, [j.x,j.y,size,size])
def __init__(self, f): self.graph = Graph(f) self.ants = [Ant(self.graph) for x in range(NUMBER_OF_ANTS)]
screen = pygame.display.set_mode(size) pygame.display.set_caption("Ants!") # Font for rendering text font = pygame.font.SysFont("consolas", 10) # Create the map of tiles tileMap = TileMap() # Store all ants, living or dead, here. ants = [] # Create the user-requested number of ants. for i in range(0, numAnts): ants.append(Ant(tileMap.tiles)) while True: alive = 0 dead = 0 for ant in ants: if ant.state == 3: dead += 1 else: alive += 1 # Show the number of living ants in the window caption pygame.display.set_caption( str(len(ants)) + " Ants! " + str(alive) + " alive " + str(dead) + " dead ") # Clear the screen to black
def initialize(self): self.__ants = [] for _ in range(self.__probParams["noAnts"]): self.__ants.append(Ant(self.__params))
def __initializeAnts(self): self.__ants = [] for _ in range(self.__parameters['numberOfAnts']): self.__ants.append(Ant(self.__parameters))
def __init__(self, _config, _nodes_list): AntAlgorithm.__init__(self, _config, _nodes_list) self.history_best = Ant(self.nodes_list[0]) # TODO how to make arbitrary big max value? self.history_best.result_value = 100000
def _individual(self, length): individual = self.__permutations[np.random.randint(0, length)] return Ant(self, individual)
def __init__(self, xpos, ypos, tiles, sprite): Ant.__init__(self, xpos, ypos, tiles, sprite) self.speed = 7
def __init__(self, x, y): Ant.__init__(self, x, y , "S")
return '\n'.join([ ' '.join([ '-' if not self.blocks[i][j] else str(self.blocks[i][j]) for i in range(self.blocks.shape[0]) ]) for j in range(self.blocks.shape[1]) ]) def add(self, agent): self.blocks[agent.x, agent.y] = agent def remove(self, agent): self.blocks[agent.x, agent.y] = None def get_all_agents(self): agents = [] for i in range(self.blocks.shape[0]): for j in range(self.blocks.shape[1]): if self.blocks[i][j] is not None: agents.append(self.blocks[i][j]) return agents if __name__ == '__main__': maze = Maze(20, 20) print(maze.__class__.__name__) a = Ant(2, 2) maze.blocks[0][0] = a print(maze) # print(np.where(maze.blocks == a)) # print(maze.blocks[np.where(maze.blocks == a)])
#print(dataM[1]) phiM1=createPheromoneMatix(size=len(distM),distance=1888) feasLocIN1=len(distM)*[0] phiM2=createPheromoneMatix(size=len(distM),distance=1888) feasLocIN2=len(distM)*[0] #nnSearch(0,distM,dataM) #print(dataM[1]) vehicleNumber=60 ant0=Ant(vehicleCount=vehicleNumber,dataM=dataM) bestSolution=ant0.calculate(dataM,distM,phiM1,feasLocIN1,1) #getting ready phi matrix file TF_Path=path.relpath('Output/Phi.txt') tf=open(TF_Path,'w') tf.write('phi matrix:\n\n') #phi m write iteration=0 while iteration <200: #print('iteration number',antCount
def __init__(self, base): Ant.__init__(self, base) self.food_time = 0
maxSteps = int(parsedIn[0]) if maxSteps == -1: print("Input the positive amount of steps to traverse") continue else: totalInput.append(inp) break elif inp[0] != '#': # # comments will be skipped over # parsedIn = inp #seperates input into 3 parts, symbol, direction to go, what symbol to change dnaDict[parsedIn[0]] = ( parsedIn[1].upper(), parsedIn[2] ) #WAdd(parsedIn[0],(parsedIn[1], parsedIn[2])) if firstLine: defaultSym = parsedIn[0] firstLine = False totalInput.append(inp) except EOFError: exit() ant = Ant(dnaDict, defaultSym) #print(ant.plane) currentStep = 0 currentPos = (0, 0) while currentStep < maxSteps: currentPos = ant.move(currentPos) currentStep += 1 for inp in totalInput: print(inp) print("# {0} {1}\n".format(currentPos[0], currentPos[1]))
from Maze import Maze from Ant import Ant from Bug import Bug import numpy as np from Viewer import draw import cv2 if __name__ == '__main__': np.random.seed(60 ) maze = Maze(10, 10) maze.reset() for _ in range(50): ant = Ant(np.random.randint(10), np.random.randint(10)) maze.add(ant) for _ in range(5): bug = Bug(np.random.randint(10), np.random.randint(10)) maze.add(bug) for step in range(100): print('step: ', step) all_agents = maze.get_all_agents() for agent in all_agents: obs = agent.get_obs(maze) action = agent.step(maze, obs) print(maze) all_agents = maze.get_all_agents() print('%d ants, %d bugs' % (sum([agent.__class__.__name__ == 'Ant' for agent in all_agents]), sum([agent.__class__.__name__ == 'Bug' for agent in all_agents]))) img = draw(maze)
def antPopulate(self): for i in range(self.N): AntObject = Ant(i, self.N) self.Ants.append(AntObject)
def getNextState(currentState, move): """ Version of genNextState with food carrying bug fixed. Description: Creates a copy of the given state and modifies the inventories in it to reflect what they would look like after a given move. For efficiency, only the inventories are modified and the board is set to None. The original (given) state is not modified. Parameters: currentState - A clone of the current state (GameState) move - The move that the agent would take (Move) Return: A clone of what the state would look like if the move was made """ # variables I will need myGameState = currentState.fastclone() myInv = utils.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 = utils.getAntAt(myGameState, myTunnel.coords) if ant is not None: opponentsAnts = myGameState.inventories[not me].ants if ant in opponentsAnts: myTunnel.captureHealth -= 1 if utils.getAntAt(myGameState, myAntHill.coords) is not None: ant = utils.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 = [c.WORKER, c.DRONE, c.SOLDIER, c.R_SOLDIER] if move.moveType == c.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 == c.WORKER: myInv.foodCount -= 1 elif move.buildType == c.DRONE or move.buildType == c.R_SOLDIER: myInv.foodCount -= 2 elif move.buildType == c.SOLDIER: myInv.foodCount -= 3 # If a building is built update list of buildings and the update food # count if move.moveType == c.BUILD: if move.buildType == c.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 == c.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 = utils.getConstrList(myGameState, None, (c.FOOD, )) for food in foods: if food.coords == ant.coords: ant.carrying = True # If my ant is close to an enemy ant attack it if ant.type == c.WORKER: continue adjacentTiles = utils.listAdjacent(ant.coords) for adj in adjacentTiles: # If ant is adjacent my ant if utils.getAntAt(myGameState, adj) is not None: closeAnt = utils.getAntAt(myGameState, adj) if closeAnt.player != me: # if the ant is not me closeAnt.health = closeAnt.health - \ UNIT_STATS[ant.type][c.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 test_direction_getter(): ant = Ant((30, 20), "N") assert ant.direction == "N" assert ant.direction != "South"
if __name__ == "__main__": args = io.get_args() distance_matrix, num_cities = io.get_matrix(args) #default parameters = {"INITIAL_PHEROMONE": 10**(-16), "MAX_ITR": 50, "NUM_CITIES": num_cities, "NUM_ANTS": num_cities * 2, "ALPHA": 1, "BETA": 5, "P": 0.5, "Q": 100} ants = [Ant() for _ in range(0, parameters['NUM_ANTS'])] graph = Graph(parameters) graph.create_graph(distance_matrix, parameters['INITIAL_PHEROMONE']) for itr in tqdm(range(0, parameters['MAX_ITR']), position=0, leave=True): graph.insert_ants(ants) graph.build_routes() graph.update_pheromone() graph.calculate_log() if itr < parameters['MAX_ITR']-1: graph.clear_routes() print(graph.get_parameters()) print("\nBest Solution: ", graph.best_global) pc.plot_graphics(graph, parameters)
def test_position_getter(): ant = Ant((30, 20), "N") assert ant.position_x == 30 assert ant.position_y == 20 assert ant.position_x != "N"
def __init__(self, x, y): Ant.__init__(self, x, y , "W")
def initialisation(self): #self.__ants = [Ant(self.__problParams["noNodes"]) for _ in range(0, self.__params["noAnts"])] noAnts = round(self.__problParams["noNodes"] * self.__params["antFactor"]) self.__ants = [Ant(self.__problParams["noNodes"]) for _ in range(0, noAnts)] for ant in self.__ants: ant.visit(randint(0, self.__problParams["noNodes"] - 1))
self.reachState = reachState self.stateEval = stateEval #UNIT TEST #Prepare a demo board to build gameState p1Inventory = Inventory(PLAYER_ONE, [], [], 0) p2Inventory = Inventory(PLAYER_TWO, [], [], 0) neutralInventory = Inventory(NEUTRAL, [], [], 0) board = [[Location((col, row)) for row in xrange(0,BOARD_LENGTH)] for col in xrange(0,BOARD_LENGTH)] sampAnt = Ant((0,0), WORKER, PLAYER_ONE) enemyAnt = Ant((3,4), WORKER, PLAYER_TWO) enemyQueen = Ant((6,4), QUEEN, PLAYER_TWO) playerOneQueen = Ant((7,5), QUEEN, PLAYER_ONE) #Food ant that's already carrying something foodAnt = Ant((4,4), WORKER, PLAYER_ONE) foodAnt.carrying = True sampAnthill = Building((1,2), ANTHILL, PLAYER_ONE) sampTunnel = Building((3,2), TUNNEL, PLAYER_ONE) playerOneTunnel = Building((8,8), TUNNEL, PLAYER_ONE) sampFoodOne = Building((5,2), FOOD, PLAYER_ONE) sampFoodTwo = Building((7,2), FOOD, PLAYER_ONE) p1Inventory.ants.append(playerOneQueen) p1Inventory.constrs.append(playerOneTunnel) p1Inventory.constrs.append(sampFoodOne) p1Inventory.constrs.append(sampFoodTwo) p1Inventory.constrs.append(sampAnthill) p1Inventory.ants.append(sampAnt) p1Inventory.ants.append(foodAnt) p2Inventory.ants.append(enemyAnt) p2Inventory.ants.append(enemyQueen)
def make_ant(self, id, job, beta): a = Ant(id, job, beta) self.ant_list.append(a) return self.ant_list
def setAntCount(self, ant_count): self.ants = [ Ant.Ant(i, self.environment, self.environment.nests[0]) for i in range(0, ant_count) ]
def initialisation(self): self.__population = [] for _ in range(self.__params['colSize']): a = Ant(self.__params) self.__population.append(a)
#print(dataM[1]) phiM1=createPheromoneMatix(size=len(distM),distance=1888) feasLocIN1=len(distM)*[0] phiM2=createPheromoneMatix(size=len(distM),distance=1888) feasLocIN2=len(distM)*[0] #nnSearch(0,distM,dataM) #print(dataM[1]) vehicleNumber=60 ant0=Ant(vehicleCount=vehicleNumber,depo=0) bestSolution=ant0.calculate(dataM,distM,phiM1,feasLocIN1,2) iteration=0 while iteration <300: #print('iteration number',antCount) ant1=Ant(vehicleCount=vehicleNumber-1,depo=0) solution1=ant1.calculate(dataM,distM,phiM1,feasLocIN1,2) if solution1['visitedCount']==101: vehicleNumber-=1 phiM2=createPheromoneMatix(size=len(distM),distance=1888) feasLocIN2=len(distM)*[0]
def init(self): cities = [i for i in range(1, self.__numberOfNodes + 1)] random.shuffle(cities) self.__ants = [Ant(i) for i in cities]