def run(): """==================== test some things ==================""" D = AntDomain([1000, 1000], pitch=1) D.set_gaussian(sigma=25) P = MapPlot(D.Map.X, D.Map.Y, 'blue') A = Ant(start_pos=[500, 500], limits=[1000, 1000], speed=10, angle=360 * np.random.rand()) i = 0 for loc in 300 + np.random.rand(100, 2) * 600: i += 1 tic = time.time() D.local_add_pheromone(loc=loc, Q=1e3) D.update_pheromone() # P.draw_contour(D.Map.map) if i % 5 == 0 or i == 1: P.draw_contour(D.Map.map) A.random_step(sigma=10) P.draw_scatter(A.pos.x, A.pos.y, color='k') print("Iteration {i} in {s:.4f} msec".format(i=i, s=(time.time() - tic) * 1e3)) P.hold_until_close()
def epoch(self, pheromoneMatrix): population = [] for i in range(self.__noAnts): ant = Ant(self.__problem) population.append(ant) for i in range(self.__problem.getNumberOfTasks() - 1): for ant in population: ant.update(pheromoneMatrix, self.__alpha, self.__beta, self.__q0) t = [1.0 / population[i].fitness() for i in range(len(population))] for i in range(self.__problem.getNumberOfComputers()): for j in range(self.__problem.getNumberOfTasks()): pheromoneMatrix[i][j] = (1 - self.__rho) * pheromoneMatrix[i][j] for i in range(len(population)): for j in range(len(population[i].getPath()) - 1): x = population[i].getPath()[j] y = population[i].getPath()[j + 1] pheromoneMatrix[x][y] = pheromoneMatrix[x][y] + t[i] fitness = [[population[i].fitness(), i] for i in range(len(population))] fitness = min(fitness) return population[fitness[1]]
def spawnMouseAnts(): global spawnAnts global pos if(spawnAnts): spawnedAnt = Ant() spawnedAnt.setPos(pos[0], pos[1], map) antList.append(spawnedAnt)
def create_children(breeders, env, number_of_child, ants_energy, food_value): # creates children using genes from to selected ants nextColony = [] breeders_indexes = np.arange(len(breeders)) breeders_indexes_shuffled = np.arange(len(breeders)) np.random.shuffle(breeders_indexes_shuffled) for i in range(len(breeders) / 2): # first round of childrean, each pair of randomly selected parents create one of them # each parent can be selected only once first_parent_id = breeders_indexes_shuffled[i] second_parent_id = breeders_indexes_shuffled[ len(breeders_indexes_shuffled) - i - 1] brain = select_genes(breeders[first_parent_id], breeders[second_parent_id]) nextColony.append( Ant(env, energy=ants_energy, food_value=food_value, genetic_inh=brain, child=1)) for j in range(number_of_child - (len(breeders) / 2)): # if we need more children, we are going to use again some of the old parents random_parent = random.choice(breeders_indexes) brain = select_genes(breeders[random_parent], breeders[len(breeders) - random_parent - 1]) nextColony.append( Ant(env, energy=ants_energy, food_value=food_value, genetic_inh=brain, child=1)) return nextColony
def step(self): if not self.ant.settled: try: self.ant.move() except Error as e: raise e else: if self.ant.y > self.maxHeight: self.maxHeight = self.ant.y if self.checkBridge(): return False self.addJoints(self.ant) self.antId = self.antId + 1 self.numAnts += 1 if G.DeterministicAnts: self.ant = Pyramid(self.antId) self.oldy = self.y self.y = self.ant.y if self.y != self.oldy: Physics.resetPhysics() Physics.checkPhysics() else: self.ant = Ant(self.antId) Physics.resetPhysics() Physics.checkPhysics() self.updateShaking() return True
def f(ant: Ant, pheromones: dict) -> Ant: neighbors = ant.get_neighbors() transition_arr = [(ant.solution_path[-1], i) for i in neighbors] for index in range(len(transition_arr)): i, j = transition_arr[index] if i > j: transition_arr[index] = (j, i) next_neighbor = None distances = np.array(list(map(ant.get_distance, transition_arr))) heuristic = distances**-beta if np.random.uniform() < q0: max_pheromone = 0 next_neighbor = np.argmax( np.array([pheromones[coord] for coord in transition_arr]) * heuristic) else: taos = np.array([pheromones[coord] for coord in transition_arr]) probabilities = ((taos ** alpha)*heuristic) / \ ((taos ** alpha)*heuristic).sum() next_neighbor = np.random.choice(len(transition_arr), p=probabilities) ant.add_node(transition_arr[next_neighbor]) return ant
def __init__(self, size=[1000, 1000], pitch=1, n_ants=5): """ ================== Do a simulation of an Ant ================== """ self.size = size self.pitch = pitch self.Dom = AntDomain(size, pitch, food={ 'location': [850, 500], 'radius': 50 }, nest={ 'location': [150, 500], 'radius': 50 }) self.Dom.set_gaussian(sigma=10) self.Ant = Ant( limits=size, start_pos=[700, 500], speed=5, ) self.Ants = [ Ant(limits=size, start_pos=1000 * np.random.rand(1, 2)[0], angle=360 * np.random.rand(), speed=2, v_max=5, ant_id=i) for i in range(n_ants) ] self.Plot = MapPlot(self.Dom.Map.X, self.Dom.Map.Y)
class Sim(object): def __init__(self): G.state = np.zeros((G.numBlocksX, G.numBlocksY), dtype=np.int) G.weight = np.ones((G.numBlocksX, G.numBlocksY)) self.antId = 0 if G.DeterministicAnts: self.ant = Pyramid(self.antId) self.y = self.ant.y self.oldy = self.y else: self.ant = Ant(self.antId) self.numAnts = 1 self.maxHeight = 0 G.jointData = np.zeros((G.numBlocksX * G.numBlocksY * 3)) G.numJoints = 0 G.jointRef = {} def step(self): if not self.ant.settled: try: self.ant.move() except Error as e: raise e else: if self.ant.y > self.maxHeight: self.maxHeight = self.ant.y if self.checkBridge(): return False self.addJoints(self.ant) self.antId = self.antId + 1 self.numAnts += 1 if G.DeterministicAnts: self.ant = Pyramid(self.antId) self.oldy = self.y self.y = self.ant.y if self.y != self.oldy: Physics.resetPhysics() Physics.checkPhysics() else: self.ant = Ant(self.antId) Physics.resetPhysics() Physics.checkPhysics() self.updateShaking() return True def addJoints(self, ant): for adjacent in getAdjacent(ant.pos): if G.state[adjacent]: Joint(ant.pos, adjacent, -1) # attach anchor joints if ant.y == 0: Joint(ant.pos, (ant.x, ant.y - 1), -1) Joint(ant.pos, (ant.x - 1, ant.y - 1), -1) Joint(ant.pos, (ant.x + 1, ant.y - 1), -1) def getForces(self, (x, y)): return [f.force() for f in G.jointRef[(x, y)]]
def create_generation(ant: Ant, board: np.ndarray): print("creating generation") coords = ant.get_coords() board_value = board[coords[1], coords[0]] cell_type = ant.evolve(board_value) return {"ant": ant, "new_value": cell_type, "coords": coords}
def run(self): ''' Function to run the rank based Ant Colony Optimization algorithm ''' best_ant = Ant(0, 0, []) for i in range(self._n_iterations): colony = [] for j in range(self._n_ants): ant = Ant(0, self._distances.shape[0], copy.deepcopy(self._vehicles)) for x in range(len(ant.vehicles)): ant.vehicles[x].put_node_path(0, self._occupancies, self._distances, self._times) ant.build_path(self._distances, self._times, self._occupancies, self._pheromone, self._alpha, self._beta) ant.calculate_distance(self._distances) ant.objectve_function(self._distance_cost) colony.append(ant) n_bests_ants = self.find_n_bests_ants(colony) if n_bests_ants[0].of_value < best_ant.of_value: best_ant = n_bests_ants[0] self.update_pheromone(best_ant, n_bests_ants) #print("Iteration: %d Best OF: %f" %(i + 1, best_ant.of_value)) return best_ant
def pheromone_update(self, ant: Ant): """ Pheromone update method to be potentially used after each batch of ants :param self: Reference to the graph :param ant: The ant during the update """ # Update the pheromone levels for each edge the ant took value = self.get_path_value(ant.get_tour()) for n1, n2 in ant.get_tour(): self.edges[n1, n2]['pheromone'] = (1 - self.global_evaporation_rate) * self.edges[n1, n2]['pheromone'] + \ self.global_evaporation_rate * value
def init_tiles_ants(self): self.screen_size = self.screen.get_size()[0] self.tile_size = self.screen_size // cfg.N_TILES if isinstance(self.init_tiles, str) and self.init_tiles == 'random': self.tiles = np.random.randint(0, 2, (cfg.N_TILES, cfg.N_TILES)) elif self.init_tiles is not None: self.tiles = self.init_tiles else: self.tiles = np.zeros((cfg.N_TILES, cfg.N_TILES)) self.ant = Ant(self.ant_init_pos, self.ant_init_direction) self.total_step = 0
def __init__(self, data, alpha=0.2, label=None, mask=None, option=None): self.mask = mask self.option = option self.al = alpha self.nest_counter = 1 if label is None: self.ants = set([Ant(datum) for datum in data.tolist()]) else: self.ants = set([ Ant(datum, true_label=label[i]) for i, datum in enumerate(data.tolist()) ])
def make_ants(G, pos, num_steps, anthill_data): ants = [] for ant_num in range(1, int(anthill_data['ants']) + 1): ant = Ant(ant_num) ant.set_node_path(anthill_data) ant.set_location(pos, anthill_data) ant.set_journey(pos, num_steps, anthill_data) ant.color = ant_colors[ant_num % 11] ants.append(ant) return (ants)
class LangtonsAnt: def __init__( self, initial_state: List[List[bool]], start_position: List[int] ) -> None: self._grid = Grid(initial_state) self._ant = Ant(start_position[0], start_position[1]) def next(self) -> bool: current_ant_position_x, current_ant_position_y = self._ant.position if self._grid.get_color(current_ant_position_x, current_ant_position_y): self._grid.change_color(current_ant_position_x, current_ant_position_y) self._ant.turn(TurnDirection.RIGHT) self._ant.move() else: self._grid.change_color(current_ant_position_x, current_ant_position_y) self._ant.turn(TurnDirection.LEFT) self._ant.move() return self.validate_move() @property def state(self): return self._grid.state @property def ant_position(self): return self._ant.position def validate_move(self) -> bool: current_ant_position_x, current_ant_position_y = self._ant.position return self._grid.validate_point(current_ant_position_x, current_ant_position_y) def validate(self) -> bool: return self._grid.validate()
def populate_world(self): first_ant = Ant(world=self, n_nodes=self.n_nodes, alpha=self.alpha, beta=self.beta) ant = first_ant for i in range(self.n_ants - 1): ant.next = Ant(world=self, n_nodes=self.n_nodes, alpha=self.alpha, beta=self.beta) ant = ant.next self.first_ant = first_ant
def __init__(self, parameters, instance): self.instance = instance self.ants = [Ant(instance) for i in range(parameters.n_ants)] self.best_so_far_ant = Ant(instance) self.restart_best_ant = Ant(instance) self.prob_of_selection = [0 for i in range(parameters.nn_ants + 1)] # Ensure that we do not run over the last element in the random wheel. self.prob_of_selection[parameters.nn_ants] = math.inf self.pheromone = [[None for i in range(instance.n)] for i in range(instance.n)] self.total = [[None for i in range(instance.n)] for i in range(instance.n)] self.nn_tour = None self.compute_nn_tour()
def put_ants(self): points = range(1,self.points+1) position = 0 for tower in self.__towers: ant = Ant() ant.position = position ant.set_coverage(copy(points)) ant.possible_towers = copy(self.__towers) ant.route = [] ant.set_actual_tower(tower) self.__ants.append(ant) position += 1
def update(self, data): map(lambda tile, pheromones: tile.update(**pheromones), self.tiles, data['board']) for tile in self.tiles: rect, color = tile.render() pygame.draw.rect(self.screen, color, rect) for ant_repr in data['ants']: if ant_repr['id'] in self.ants: ant = self.ants[ant_repr['id']] ant.position = ant_repr['position'] else: ant = Ant(**ant_repr) self.ants[ant_repr['id']] = ant pos = map(lambda coord: coord * TILE_SIZE + TILE_SIZE / 2, ant.position) ant_color = YELLOW if ant.carries_food else GREEN pygame.draw.circle(self.screen, ant_color, pos, TILE_SIZE / 5) # Place colony pygame.draw.rect(self.screen, GREEN, self.colony) # Place food food_pos = self.food['position'] pile = [[ food_pos[0] * TILE_SIZE + TILE_SIZE / 2, food_pos[1] * TILE_SIZE ], [food_pos[0] * TILE_SIZE, (food_pos[1] + 1) * TILE_SIZE], [(food_pos[0] + 1) * TILE_SIZE, (food_pos[1] + 1) * TILE_SIZE]] pygame.draw.polygon(self.screen, YELLOW, pile) pygame.display.flip()
def __init__(self): self.area = Area() self.ant_num = 20 self.ant_list = [] self.add_number = 0 for i in range(self.ant_num): self.ant_list.append(Ant(self.area.area))
def Start_find_food(self): # while True: ant_x_list = [] ant_y_list = [] dispatch = False mydispatch = False direction = 0 if self.add_number > 0: self.ant_list.append(Ant(self.area.area)) self.add_number = self.add_number - 1 self.ant_num = self.ant_num + 1 for i in range(self.ant_num): dispatch = self.ant_list[i].walking() if len(self.ant_list[i].previous_location_list) > 2000: self.ant_list[i].previous_location_lis = [] if dispatch == True: mydispatch = True ant_x_list.append(self.ant_list[i].location[0]) ant_y_list.append(self.ant_list[i].location[1]) # if self.ant_list[i].direction_x==self.ant_list[i].driection_y and self.ant_list[i].direction_x: # direction=direction+1 # print(direction) pass print(len(self.ant_list[19].previous_location_list)) if mydispatch == True: if self.ant_num < 50: self.add_number = 5 return ant_x_list, ant_y_list
def reconnaissance(self, iterations=1): maze = self.maze if self.do_reconnaissance < 1: return maze print 'performing reconnaissance with %d ants for %d steps in %d iterations' % ( self.ant_count, self.do_reconnaissance, iterations) disabled = set() start_time = time.time() for iteration in range(iterations): ants = [] for i in range(self.ant_count): ants.append(Ant(maze, maze.start)) results = self.pool.map_async( ant_loop_apply, itertools.izip(ants, [self.do_reconnaissance] * self.ant_count)).get(999999) for ant in results: for disable in ant.disable_positions: maze.disable_at(disable) disabled.add(disable) print 'Reconnaissance done, %d cells disabled in %0.2fs' % ( len(disabled), time.time() - start_time) return maze
def ant_colony_opt(matrix, n_ants=10, max_iterations=23000): best_pheromone_matrix = np.ones(shape=(9, 9, 9)) / 9 ants = [Ant(matrix.copy(), best_pheromone_matrix) for _ in range(n_ants)] print(ants[0].fitness()) best_fitness = float('inf') best_ant = None history = [] for _ in tqdm(range(max_iterations)): for i, ant in enumerate(ants): ant.solve_sudoku(epsilon_greedy=0.05) fitness = ant.fitness() if fitness < best_fitness: best_ant = copy.deepcopy(ant) best_fitness = fitness tqdm.write(str(best_fitness)) for i in range(9): for j in range(9): best_pheromone_matrix[i][j][best_ant.current_solution[i, j] - 1] += 0.0005 best_pheromone_matrix[i][j] /= np.sum( best_pheromone_matrix[i][j]) history.append(best_fitness) if best_fitness == 0: # We found the solution, just stop break return best_ant.current_solution, history
def __init__(self, graph, num_ants, alpha=1.0, beta=5.0, iterations=10, evaporation=0.5): self.graph = graph self.locationsLength = len(graph.locations) self.num_ants = num_ants self.alpha = alpha # importância do feromônio self.beta = beta # importância da informação heurística self.iterations = iterations # quantidade de iterações self.evaporation = evaporation # taxa de evaporação self.ants = [] # lista de ants locations = self.graph.getLocationsList() # cria as ants colocando cada uma em uma location diferente for _ in range(self.num_ants): location_ant = random.choice(locations) locations.remove(location_ant) self.ants.append(Ant(location=location_ant)) if not locations: locations = [ location for location in range(1, self.locationsLength + 1) ] # reestrutura location como set locations = self.graph.locations for key_edge in self.graph.edges: # pheromone = 1.0 / (self.locationsLength * cost) self.graph.setPheromoneEdge(key_edge[0], key_edge[1], 0.1)
def thread_body(queue): pixels = NeoPixel(DATA_PIN, N_PIXELS, brightness=BRIGHTNESS, auto_write=False) updates = {'RAINBOW': Rainbow(pixels), 'ANT': Ant(pixels), 'OCD': Ocd(pixels), 'FLASH': Flash(pixels), 'IMPLODE': Implode(pixels), 'ERROR': Error(pixels), 'QUIT': Quit(pixels)} assert set(updates.keys()) == MODES mode = "OCD" while True: try: new_mode = queue.get_nowait() assert new_mode in MODES, "unknown mode %s" % mode if new_mode != mode: updates[new_mode].setup() mode = new_mode except: pass sleep = updates[mode].exec_update() if mode == "QUIT": break time.sleep(sleep)
def perform_tours(self, instance): """ Initialises ants within colony and makes the ants perform their tours around the tsp instance """ # Create n ants with each one starting on a random node where n is the amount of nodes node_range = len(instance.nodes) - 1 self.ants = [ Ant(instance, random.randint(0, node_range)) for _ in range(node_range) ] # Make each ant perform a tour around the instance for ant in self.ants: ant.perform_tour(instance) # Update pheromones locally self.local_update_pheromones(instance, ant.nodes_traversed()) distance = ant.get_distance(instance) # Initialise the minimum distance as infinity if None if not (self.min_distance): self.min_distance = float('inf') # Update the colonys minimum distance and shortest path if the ant has found a shorter distance if self.min_distance > distance: self.min_distance = distance self.shortest_path = ant.path[:]
def ant_algorithm(self): for i in range(self.max_iter): ants = list(Ant(self.graph) for j in range(self.ants_num)) for k in range(self.ants_num): while not len(ants[k].att_to_visit) == 0: next_index = self.select_next_attraction(ants[k]) if not ants[k].check_condition(next_index): next_index = self.select_next_attraction(ants[k]) if not ants[k].check_condition(next_index): next_index = 0 ants[k].visit_attraction(next_index) ants[k].visit_attraction(0) paths_distance = np.array( [ant.total_travel_distance for ant in ants]) best_index = np.argmin(paths_distance) if self.best_path is None or paths_distance[ best_index] < self.best_path_distance: self.best_path = ants[int(best_index)].travel_path self.best_path_distance = paths_distance[best_index] self.best_vehicle_num = self.best_path.count(0) - 1 self.graph.update_pheromones(self.best_path, self.best_path_distance) print('Iteration ' + str(i)) print('Best path distance is ' + str(round(self.best_path_distance, 3)) + ', number of vehicle is ' + str(self.best_vehicle_num))
def create_ants(self): self.reset() ants = [] for i in range(0, self.num_ants): ant = Ant(i, random.randint(0, self.graph.num_nodes - 1), self) ants.append(ant) return ants
def create_new_ant(): sensing_area = random.randint(1, 10) p_repeat = random.random() p_target = random.random() p_pheromone = random.random() new_ant = Ant(sensing_area, p_repeat, p_target, p_pheromone, get_id = get_ant_id) return new_ant
def setup(self): if settings.DRAW_BASE: self.create_base() for _ in range(settings.NUM_WALLS): self.create_wall() for _ in range(settings.NUM_FOOD_BLOBS): self.create_food_blob(settings.FOOD_BLOB_SIZE) self.colony = Colony() for _ in range(settings.NUM_ANTS): ant = Ant(settings.SCREEN_WIDTH / 2, 0, self, self.colony, scale=settings.SCALE) self.ant_list.append(ant) arcade.set_background_color(settings.FIELD_COLOR) if self.generation_callback: self.generation_callback(self.generation, self)
def main(commands: dict, ordered_colours: list): """ The main function responsible for running and simulating the ant's movements """ ant = Ant(commands, ordered_colours) board = Board(ant) run = True clock = pygame.time.Clock() rows, cols = ROWS, COLS while run: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() board.draw_board(rows, cols, WIN) board.draw_ant(rows, WIN) board.update_ant_dir() board.update_ant_pos() if board.check_edge(): rows, cols = (rows * 3), (cols * 3) board.increase_board() pygame.display.update()
def test_completable_path(): num_nodes = 8 delta_mat = [[0,1,1,1,1,1,1,1],[1,0,1,1,1,1,1,1],[1,1,0,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,1,0,1,1,1],[1,1,1,1,1,0,1,1],[1,1,1,1,1,1,0,1],[1,1,1,1,1,1,1,0]] num_ants = 1 num_iterations = 10 colors1 = "RRRRBBBB" graph1 = AntGraph(num_nodes,delta_mat,colors1) colony1 = AntColony(graph1,num_ants,num_iterations) ant1 = Ant(1, 1, colony1) print "testing reds_left initialization: " + str(ant1.reds_left) #Visited: 1,2,3 ant1.currNode = 3 ant1.last_3_colors = ("R","R","R") self.reds_left = 1
def new_ant(self): """ Creates new ant and adds it to the Node's ant list. Parameters: None Returns: None """ ant = Ant(self.num, random.randint(0, self.net_size - 2)) if ant.dest >= self.num: ant.dest += 1 ant.prev = self.num self.ants.append(ant)
def spawnBlueAnts(): global spawnBlueAnts global pos if(spawnBAnts): spawnedBlueAnt = Ant() spawnedBlueAnt.setPos(pos[0], pos[1], map) spawnedBlueAnt.setFaction("blue") spawnedBlueAnt.setColor() antList.append(spawnedBlueAnt)
def spawnGreenAnts(): global spawnGreenAnts global pos if(spawnGAnts): spawnedGreenAnt = Ant() spawnedGreenAnt.setPos(pos[0], pos[1], map) spawnedGreenAnt.setFaction("green") spawnedGreenAnt.setColor() antList.append(spawnedGreenAnt)
def spawnRedAnts(): global spawnRedAnts global pos if(spawnRAnts): spawnedRedAnt = Ant() spawnedRedAnt.setPos(pos[0], pos[1], map) spawnedRedAnt.setFaction("red") spawnedRedAnt.setColor() antList.append(spawnedRedAnt)
def test_valid_color(): num_nodes = 6 delta_mat = [[0,1,1,1,1,1],[1,0,1,1,1,1],[1,1,0,1,1,1],[1,1,1,0,1,1],[1,1,1,1,0,1],[1,1,1,1,1,0]] num_ants = 1 num_iterations = 10 colors1 = "RRRRRR" colors2 = "RRRBBB" colors3 = "BBBBBB" graph1 = AntGraph(num_nodes,delta_mat,colors1) colony1 = AntColony(graph1,num_ants,num_iterations) ant1 = Ant(1, 1, colony1) ant1.last_3_colors = ("R","R","R") print "False: " + str(ant1.valid_color(1)) ant1.last_3_colors = ("B","B","B") print "True: " + str(ant1.valid_color(1)) ant1.last_3_colors = ("R","R","B") print "True: " + str(ant1.valid_color(1)) graph2 = AntGraph(num_nodes,delta_mat,colors2) colony2 = AntColony(graph2,num_ants,num_iterations) ant2 = Ant(1, 1, colony2) ant2.last_3_colors = ("R","R","R") print "True: " + str(ant2.valid_color(3)) print "False: " + str(ant2.valid_color(1)) graph3 = AntGraph(num_nodes,delta_mat,colors3) colony3 = AntColony(graph3,num_ants,num_iterations) ant3 = Ant(1, 1, colony3) ant3.last_3_colors = ("R","R","R") print "True: " + str(ant3.valid_color(1)) ant3.last_3_colors = ("B","B","B") print "False: " + str(ant3.valid_color(1)) ant3.last_3_colors = ("B","R","B") print "True: " + str(ant3.valid_color(1))
def updatePhermone(): if randint(0, 10) >= 0: count = 0 for i in antGrid.storedInformation: sPhermoneLevel = antGrid.storedInformation[count][1] if sPhermoneLevel > 5: antGrid.storedInformation[count][1] = sPhermoneLevel - 1 count += 1 backlog = len(antGrid.storedIndex) if backlog > 40000: antGrid.storedIndex.pop(0) antGrid.storedInformation.pop(0) ant = Ant(DEFAULT_COORDINATES) antGrid = Grid(ant.GRID_WIDTH, ant.GRID_HEIGHT) screen = pygame.display.set_mode((ant.GRID_WIDTH, ant.GRID_HEIGHT)) running = True herd = [Ant(DEFAULT_COORDINATES) for i in range(0, NUMBER_ANTS)] iterations = 1 # for debugging purposes while running: displayAnts() updatePhermone() for ant in herd:
def spawn_worker(cont): own = cont.owner worker = Ant(bge.logic.getCurrentScene().addObject("Ant")) worker.worldPosition.xy = own.worldPosition.xy bge.logic.sendMessage("GUI") worker.target = own.worldPosition + Vector((0, -3, 0))
def __init__(self, position): Ant.__init__(self, position) self.path = [] self.index = 0 self.target = None
def spawn_test_ants(): redLocation = [100, 100] greenLocation = [120, 120] redAnt = Ant() redAnt.setFaction("red") redAnt.setColor() redAnt.health = 25 redAnt.setPos(redLocation[0], redLocation[1], map) antList.append(redAnt) greenAnt = Ant() greenAnt.setFaction("green") greenAnt.setColor() greenAnt.health = 100 greenAnt.setPos(greenLocation[0], greenLocation[1], map) antList.append(greenAnt)
def __init__(self, position): Ant.__init__(self, position) self.path = [] self.index = 0
def gwas(start_snp, end_snp, individuals, ants_number, update_times, factor, threshold): """ individuals: sum of cases and control. factor: 0<factor<1 user-adjustable distribution.if factor is near 1,snps with high scores are only slightly more likely to be selected. threshold <-> P-Value: 26.12<->0.001;20.09<->0.01;15.51<->.0.05 """ snps_number = end_snp - start_snp + 1 dict_pair = Prepare.dict_pair(start_snp, end_snp) print('dict_pair done') n = 0 for order in range(1, 101): dict_prob = Prepare.dict_prob1(start_snp, end_snp + 1) print('dict_prob done') label, data_set = Prepare.data_matrix(order, individuals, snps_number) dict_weka = Prepare.load_weka_ranking(order) snps_sequence = Prepare.snps_sequence1(start_snp, end_snp) snps_scores = [0] * snps_number # Rank dict on weight,return a list of tuples list_weka = sorted(dict_weka.items(), key=lambda weka: weka[1], reverse=True) rank = Prepare.scaling_rank(factor, snps_number) for snp_weight_tuple, new_weight in zip(list_weka, rank): # allocate scaling rank weight to corresponding snp snps_scores[snp_weight_tuple[0] - start_snp] = new_weight selected_pairs = {} for x in range(update_times): list_k1_threshold = [] # 存储chi2_statistics > 阈值的pair在dict_prob[first_snp]中的索引位置 list_k2_threshold = [] # 存储chi2_statistics > 阈值的pair在dict_prob[second_snp]中的索引位置 list_chi2_statistics = [] # 存储chi2_statistics > 阈值的pair的卡方值,在update的时候使用 list_k1 = [] # 存储chi2_statistics < 阈值的pair在dict_prob[first_snp]中的索引位置 list_k2 = [] # 存储chi2_statistics < 阈值的pair在dict_prob[second_snp]中的索引位置 list_first_snp_threshold = [] # 存储chi2_statistics > 阈值的first_snp list_second_snp_threshold = [] # 存储chi2_statistics > 阈值的second_snp list_first_snp = [] # 存储chi2_statistics < 阈值的first_snp list_second_snp = [] # 存储chi2_statistics < 阈值的second_snp for y in range(ants_number): first_snp = Ant.ant_first_snp(snps_sequence, snps_scores) second_snp = Ant.ant_second_snp(first_snp, dict_pair, dict_prob) # print(first_snp, second_snp) if second_snp > first_snp: k1 = second_snp - start_snp - 1 k2 = first_snp - start_snp else: k1 = second_snp - start_snp k2 = first_snp - start_snp - 1 case_row, control_row = ChiSquareTest.chi2_table(data_set, label, first_snp, second_snp, individuals) sum_colum, A2_NcNr, chi2_statistics = ChiSquareTest.chi2_test(case_row, control_row, individuals) if chi2_statistics > threshold: list_k1_threshold.append(k1) list_k2_threshold.append(k2) list_chi2_statistics.append(chi2_statistics) list_first_snp_threshold.append(first_snp) list_second_snp_threshold.append(second_snp) else: list_k1.append(k1) list_k2.append(k2) list_first_snp.append(first_snp) list_second_snp.append(second_snp) # 更新条件概率和snps_scores. # 除以 10 的目的是将卡方值转换到和weight同样的量级.snps_score_original[x]引入expert information for m, i, j in zip(list_first_snp_threshold, list_k1_threshold, list_chi2_statistics): dict_prob[m][i] += (int(j) / 10) for m, i, j in zip(list_second_snp_threshold, list_k2_threshold, list_chi2_statistics): dict_prob[m][i] += (int(j) / 10) for m, i in zip(list_first_snp, list_k1): dict_prob[m][i] = 0 for m, i in zip(list_second_snp, list_k2): dict_prob[m][i] = 0 for first, second, i in zip(list_first_snp_threshold, list_second_snp_threshold, list_k1_threshold): selected_pairs[(first, second)] = dict_prob[first][i] print(selected_pairs) result = sorted(selected_pairs.items(), key=lambda x: x[1], reverse=True) for x in result[0:20]: if x[0] == (999, 988) or x[0] == (998, 999): n += 1 break f = open('result_conProb-H0.1-{ants}_{updates}-fac={factor}.txt'.format( ants=ants_number, updates=update_times, factor=factor), 'a') f.writelines('\n') f.writelines(str(x[0]) + '\t' + str(x[1]) + '\n' for x in result[0:20]) f.writelines('----------------------------------') f.close() f = open('result_conProb-H0.1-{ants}_{updates}-fac={factor}.txt'.format( ants=ants_number, updates=update_times, factor=factor), 'a') f.writelines('\nThe pow of this ACO algorithm is ' + str(n) + '%') f.close()
def __checkPoint__(self, point): fake_ant = Ant('fake') fake_ant.picture = self.picture fake_ant.point = point return not self.__isAntIntersectAnything(fake_ant)
def __init__(self, position): Ant.__init__(self, position)
def step(self, start_node_name): ant = Ant(self.graph, start_node_name) distance = ant.run() if distance < self.best_distance: ant.pheromonize() self.best_distance = distance