def perform(self): whole_path = [] pheromone_map = PheromoneMap(n_rows=self.map_size[0], n_cols=self.map_size[1]) colony = Colony(pos=self.agent_pos, pheromone_map=pheromone_map, size=self.colony_size) path, n_iter, satisfies_accuracy = colony.find_target( self.load_pos, proximity_to_standard=self.proximity_to_standard, iter_max=self.iter_max) whole_path = path if path is None or not satisfies_accuracy: return None pheromone_map = PheromoneMap(n_rows=self.map_size[0], n_cols=self.map_size[1]) colony = Colony(pos=self.load_pos, pheromone_map=pheromone_map, size=self.colony_size) path, n_iter, satisfies_accuracy = colony.find_target( self.destination_pos, proximity_to_standard=self.proximity_to_standard, iter_max=self.iter_max) if path is None or not satisfies_accuracy: return None whole_path += path return whole_path
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 __init__(self, nodes, alpha, beta, decay, q): # Make a list of nodes as variables which are JSONifiable nodes_var = [] for node in nodes: nodes_var.append(vars(node)) self.nodes = nodes_var self.alpha = alpha self.beta = beta self.decay = decay self.q = q self.min_pheromone = 0.01 self.local_deposit = 0.1 self.distances = [] self.pheromones = [] colony = Colony() self.ants = colony.ants self.shortest_path = colony.shortest_path self.min_distance = colony.min_distance # Initialise the distances between nodes and pheromone trails for i in range(len(nodes)): distances = [] pheromones = [] for j in range(len(nodes)): distances.append(0 if i == j else nodes[i].distance(nodes[j])) pheromones.append(self.min_pheromone) self.distances.append(distances) self.pheromones.append(pheromones)
def load_config(filename: Path) -> (dict, Colony): """Loads the configuration file with cell table data.""" with open(filename) as fd: # load yaml config yaml_text = '' while True: line = fd.readline() # check for unexpected EOF if not line: raise CellAnnealerError('Invalid config: missing cell table') # check for document divider if RE_DIV.match(line): break yaml_text += line config = yaml.load(yaml_text) # check for necessary configuration values if 'timestep' not in config: raise CellAnnealerError( 'Invalid config: missing timestep (example: \'timestep: 1\')') if 'delimiter' not in config: raise CellAnnealerError( 'Invalid config: missing delimiter (example: \'delimiter: " "\')' ) if 'cellType' not in config: raise CellAnnealerError( 'Invalid config: missing cell type (example: \'cellType: bacilli\'' ) # determine the cell type if config['cellType'] == 'bacilli': cell_type = Bacilli else: raise CellAnnealerError('Invalid config: unrecognized cell type') # confirm that the config file has the necessary info cell_type.check_config(config) # load the cell table cell_colony = Colony() reader = csv.DictReader(fd, delimiter=config['delimiter'], skipinitialspace=True) for row in reader: cell = cell_type(**row) node = LineageNode(cell) cell_colony.roots.append(node) return config, cell_colony
def __init__(self, iterations: int, totalAnts: int, alpha: float, beta: float, rho: float, Q: int, scheme: int): """ :param iterations :param totalAnts :param colony """ self.iterations = iterations self.totalAnts = totalAnts self.colony = Colony(alpha, beta, rho, Q, scheme)
def __init__(self, width, height, n_colonies, n_ants, n_obstacles, decay=0.2, sigma=0.1, moore=False, birth=True, death=True): """ :param width: int, width of the system :param height: int, height of the system :param n_colonies: int, number of colonies :param n_ants: int, number of ants per colony :param decay: float, the rate in which the pheromone decays :param sigma: float, sigma of the Gaussian convolution :param moore: boolean, True/False whether Moore/vonNeumann is used """ super().__init__() # Agent variables self.birth = birth self.death = death self.pheromone_level = 1 # Environment variables self.width = width self.height = height self.grid = MultiGrid(width, height, False) self.moore = moore self.sigma = sigma self.decay = decay # Environment attributes self.schedule = RandomActivation(self) self.colonies = [Colony(self, i, (width // 2, height // 2), n_ants, birth=self.birth, death=self.death) for i in range(n_colonies)] self.pheromones = np.zeros((width, height), dtype=np.float) self.pheromone_updates = [] self.food = FoodGrid(self) self.food.add_food() self.obstacles = [] for _ in range(n_obstacles): self.obstacles.append(Obstacle(self)) # Metric + data collection self.min_distance = distance.cityblock(self.colonies[0].pos, self.food.get_food_pos()) self.datacollector = DataCollector( model_reporters={"Minimum path length": metrics.min_path_length, "Mean minimum path length": metrics.mean_min_path_length}, agent_reporters={"Agent minimum path length": lambda x: min(x.path_lengths), "Encounters": Ant.count_encounters}) # Animation attributes self.pheromone_im = None self.ax = None
def __init__(self, surface, grid_size): self.is_running = True self.grid_size = grid_size self.cells = [] self.food_items = [] self.dimens = surface.get_size() self.init_cells() self.food_count = 3 self.init_food() self.colony = Colony(self)
def aco(self, gens, current_gen, client): """ Returns the generation reached and the shortest path found by the aco algorithm along with its distance """ # The time at the start of the algorithm time_start = time.time() # Initalise the colony and its parameters self.colony = Colony() self.colony.ants = self.ants self.colony.shortest_path = self.shortest_path self.colony.min_distance = self.min_distance # Initialise an array to be append with nodes shortest_path = [] # Do generations from the current generation to the generation number needed for i in range(current_gen, gens): # The current time time_now = time.time() time_elapsed = time_now-time_start # If exectutiion time has reached 25 seconds, return result if (time_elapsed) > 25: break # Ants within colony perform their tours self.colony.perform_tours(self) # Get the shortest tour found by the ants shortest_path = self.colony.shortest_path # Global update of pheromones self.update_pheromones(self.colony) # Generation successful, thus increase the generation reached gen_reached = i+1 # Update Instance parameters to be returned to client self.shortest_path = shortest_path self.min_distance = self.colony.min_distance msg = "Generation " + str(i) + " distance " + str(round(self.colony.min_distance, 3)) + " path " + str(shortest_path) # Emit a message using SocketIO for a dynamic console socketio.emit('my event', msg, room=client) socketio.sleep(0.00000000001) return gen_reached, shortest_path, self.colony.min_distance
def aco(args): print(args) g = None if len(args) >= 6: # init opt params r = 0 ne = 0 alp = 1 bet = 1 hybrid = False r = 0 di = 0.5 lw = 0.1 h_ls = False h_abhc = False while args: arg = args.pop() if arg[0] == '--alg': alg = arg[1] elif arg[0] == '--test': g = read_graph(str(arg[1])) elif arg[0] == '--nants': nants = int(arg[1]) elif arg[0] == '--evaprate': evaprate = float(arg[1]) elif arg[0] == '--maxit': maxit = int(arg[1]) elif arg[0] == '--randinit': randinit = int(arg[1]) elif arg[0] == '--nelit': ne = int(arg[1]) elif arg[0] == '--divint': di = float(arg[1]) elif arg[0] == '--locweight': lw = float(arg[1]) elif arg[0] == '--alph': alp = float(arg[1]) elif arg[0] == '--beta': bet = float(arg[1]) elif arg[0] == '--rank': r = int(arg[1]) elif arg[0] == '--hls': h_ls = True elif arg[0] == '--habhc': h_abhc = True else: exit( "Incorrect number of arguments.\nplease specify the required parameters:\n* --alg type of ACO algorithm: (antsys, elitist, rank, antcolsys);\n* --test test filename;\n* --nants no. of ants;\n* --evaprate evaporation rate;\n* --maxit max no. of iterations;\n* --randinit initialization position of ants: (1 - randomized/ 0 - start at node 0, assuming there is such node);\n\nand the optional parameters:\n+ --nelit natural int no. of elitist ants (required when alg=elitist);\n+ --rank natural int no. of ranked ants (required when alg=rank);\n+ --divint float from 0 to 1, controls the diversification/intensification of pheromones, smaller vals. intensify (required when alg=antcolsys);\n+ --locweight float (usually 0.1), controls amount of preservation of previous pheromones in the local update (required when alg=antcolsys);\n+ --alph alpha exp of pherormone, used to calculate probability of picking edge;\n+ --beta beta exp of visibility, used to calculate probability of picking edge;" ) if g: if randinit == 0 and not g.has_node(0): exit("Graph must contain node 0, to initialize ants at 0.") if h_ls or h_abhc: c = HybridColony(alg, nants, g, maxit, evaprate, randinit, nelit=ne, alph=alp, beta=bet, rank=r, ls=h_ls, abhc=h_abhc) else: c = Colony(alg, nants, g, maxit, evaprate, randinit, nelit=ne, divint=di, locweight=lw, alph=alp, beta=bet, rank=r) else: print('Graph not existing')
median.append(float(partial_statics_dict[s]['median'])) std.append(float(partial_statics_dict[s]['std'])) line = str(alpha) + '\t' + str(beta) + '\t' + str(r) + '\t' + \ str(np.median(median)) + '\t' + str(np.std(std)) + '\n' file.write(line) try: file = str(sys.argv[1]) alpha = int(sys.argv[2]) beta = int(sys.argv[3]) r = float(sys.argv[4]) except: print('Erro nos argumentos') sys.exit(1) partial_statics_dict = dict() n, dist_tsp = read_file_dist(file) sol = read_file_solution(file) tsp = TSP(n, dist_tsp, sol) col = Colony(tsp, alpha, beta, r) statitics, best = col.init() calculate_statitics(partial_statics_dict, statitics) generate_table(partial_statics_dict, alpha, beta, r, file) # print(statitics) # print(partial_statics_dict) plot_best(best, alpha, beta, r, file) #plot_mean(statitics, alpha, beta, r, file)
def main(args): # Parameters initial_seed = 123456 # Used to generate the set of seeds for repetitions n_repetitions = 30 n_iterations = args.iterations initial_pheromone = 0.5 t_min = 0.001 # Min pheromone level t_max = 0.999 # Max pheromone level rho = args.rho # Pheromone decay rate alpha = args.alpha beta = args.beta # Initializations random_seeds = utils.generate_seeds(initial_seed, n_repetitions) n, p, nodes = utils.read_data(args.dataset) world = World(n, p, nodes) n_ants = (n - p) if args.ants is None else args.ants colony = Colony(n_ants) ni = aco.information_heuristic(world) # Information Heuristic dataset_name = args.dataset.split('/')[-1].split('.')[0] output = np.zeros((n_repetitions, n_iterations, 3)) output_dir = "../results/{}it{}rho{}alpha{}beta{}ants{}/".format( dataset_name, n_iterations, rho, alpha, beta, n_ants) # Main loop for repetition in range(n_repetitions): np.random.seed(random_seeds[repetition]) # Reset things for new repetition g_best = Solution(distance=np.inf) world.reset_pheromones(initial_pheromone) print("Repetition {}\n".format(repetition)) for iteration in tqdm(range(n_iterations)): for ant in colony.ants: ant.build_solution(world, ni, alpha, beta) l_best, l_worst = aco.evaluate_solutions(world, colony) world.update_pheromones(rho, g_best, l_best, l_worst) # Check algorithm stagnation if aco.is_stagnated(world, t_min, t_max): world.reset_pheromones(initial_pheromone) # Update global solution if l_best.distance < g_best.distance: g_best = l_best # Reset for next iteration colony.reset_solutions() # Store output data output[repetition][iteration][0] = g_best.distance output[repetition][iteration][1] = l_best.distance output[repetition][iteration][2] = l_worst.distance print("\nBest solution\n" "-------------\n" "Distance: {}\n" "Medians: {}\n".format(g_best.distance, g_best.medians)) utils.write_data(output_dir, output)
from colony import Colony from plot import plot from mlpplot import plot_mpl from tqdm import tqdm c1 = Colony() for i in tqdm(range(1, 5000)): if i % 2500 == 0: c1.kill_ants_single_on_command() c1.random_interaction() c1.add_new_ants() c1.kill_ants() c1.write_to_file() print(c1.index) plot_mpl() c2 = Colony() for i in tqdm(range(1, 5000)): if i % 2500 == 0: c2.kill_ants_single_on_command() c2.add_new_ants() c2.kill_ants() c2.write_to_file() print(c2.index) plot_mpl()
@author: thinkpad """ from grid import Grid from colony import Colony from application import Application #import multiprocessing # Creating the grid grid_map = Grid() # Loading the grid from the file map.txt grid_map.load_grid("map.txt") # Create the Colony moving in grid_map ants_colony = Colony(grid_map) # Start the interface app = Application(grid_map) # Start adding walls, if necessary #app.begin_draw(grid_map) # Uncomment if you want to kepe the modified grid # grid_map.save_grid("map2.txt") # Start the colony #multiprocessing.Process(target=app.start_app,args=[]).start() # The core print("Starting the work") while True:
if __name__ == '__main__': try: x = int(sys.argv[1]) y = int(sys.argv[2]) except: x = X y = Y mode = 'interactive' #mode = 'dump' mode = 'autoplay' # create a colony chicken_col = Colony(width=X, height=Y, init_pop=INIT_POP, seed=0) # plotting object visualizer = StepVisulizer(chicken_col, multiplier=45) cycle_counter = -1 single_frame = visualizer.plot_step(cycle=cycle_counter) # returns an np.array if mode == "interactive": k = ord('n') while k==ord('n'): cycle_counter += 1 chicken_col.progress_a_step() single_frame = visualizer.plot_step(cycle=cycle_counter) cv2.imshow(WINDOW_NAME, single_frame) k = cv2.waitKey(0)
import sys import pygame import utils from colony import Colony from graph import g_graph pygame.init() pygame.display.set_caption('Missile Schematization') screen = pygame.display.set_mode([1000, 650]) screen.fill(utils.get_color('WHITE')) empty = pygame.Surface((1000, 650)) empty.fill(utils.get_color('WHITE')) colony = Colony() # draw map # graph.draw(screen) # pygame.display.flip() ants = pygame.sprite.Group() ants.add(colony.ants) clock = pygame.time.Clock() while True: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): sys.exit()
from pheromone_map import PheromoneMap from colony import Colony from window import Window if __name__ == '__main__': pheromone_map = PheromoneMap(n_rows=40, n_cols=40) colony = Colony(pos=(0, 0), pheromone_map=pheromone_map) path, n_iter, satisfies_accuracy = colony.find_target( (20, 20), proximity_to_standard=0.6) window = Window(greed_size=(40, 40)) window.draw_pheromone_map(pheromone_map) window.run()
from colony import Colony from pheromone_map import PheromoneMap from window import Window import time if __name__ == '__main__': pheromone_map = PheromoneMap(n_rows=40, n_cols=40) colony = Colony(pos=(0, 0), pheromone_map=pheromone_map, size=1) start = time.time() path, n_iter, satisfies_accuracy = colony.find_target((20, 20), proximity_to_standard=0.6) end = time.time() time_diff = end - start print(time_diff) window = Window(greed_size=(40, 40)) window.visualize_path_search(colony_pos=(0, 0), target_pos=(20, 20), path=path) window.run()