示例#1
0
    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)
示例#2
0
class MyBot:
    def __init__(self):
        """Add our log filter so that botversion and turn number are output correctly"""
        log_filter = LogFilter()
        getLogger().addFilter(log_filter)

    # do_setup is run once at the start of the game
    # after the bot has received the game settings
    # the ants class is created and setup by the Ants.run method
    def do_setup(self, ants):
        self.initialized = False

    # do turn is run once per turn
    # the ants class has the game state and is updated by the Ants.run method
    # it also has several helper methods to use
    def do_turn(self, ants):
        global turn_number
        if not self.initialized:
            self.colony = Colony(ants)
            self.initialized = True
        else:
            self.colony.move(ants)
        turn_number = turn_number + 1

        """    
示例#3
0
def colony():
    colony = Colony()
    colony.describe()
    return render_template('index.html',
                           title = 'diaspora',
                           colony = colony.description,
                           attributes = colony.attributes)    
示例#4
0
    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)
示例#5
0
    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
示例#6
0
    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)
示例#7
0
def api():
    if request.method == 'GET':                
        if not request.query_string:
            howMany = 0
        else:
            howMany = int(request.query_string)
        if howMany <= 500:            
            colonies = []
            for i in range(0, howMany):
                colony = Colony()
                colony.describe()
                colonies.append(colony.serialize())        
            to_dump = {'colonies' : colonies}    
            return jsonify(to_dump)
        else:
            return "Too many colonies requested (500 max)."
示例#8
0
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)
示例#10
0
    def do_turn(self, ants):
        global turn_number
        if not self.initialized:
            self.colony = Colony(ants)
            self.initialized = True
        else:
            self.colony.move(ants)
        turn_number = turn_number + 1

        """    
示例#11
0
文件: model.py 项目: Fije/MC-ACO
    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
示例#12
0
    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
示例#13
0
文件: simulation.py 项目: Kimbsy/Ants
  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()

    # Initializa the cells
    self.init_cells()

    # Set the number of Food objects availble
    self.food_count = 1

    # Initialise Food objects
    self.init_food()

    # Initialize the colony
    self.colony = Colony(self)
示例#14
0
文件: aco.py 项目: dcguim/hot
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')
示例#15
0
        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)
示例#16
0
class Arena(arcade.Window):
    def __init__(self, width, height, title, generation_callback=None):
        super().__init__(width, height, title)

        self.wall_list = arcade.SpriteList(is_static=True,
                                           use_spatial_hash=True)
        self.food_list = arcade.SpriteList(is_static=True,
                                           use_spatial_hash=True)
        self.ant_list = arcade.SpriteList(use_spatial_hash=False)
        self.physics_engine = None
        if settings.MAX_FPS:
            self.set_update_rate(1 / settings.MAX_FPS)
        self.actual_fps = settings.MAX_FPS  # Initializse to something

        self.generation = 0
        self.generation_callback = generation_callback  # For testing purposes

    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 create_base(self):
        x = settings.SCREEN_WIDTH / 2
        for y in range(0, round(20 * settings.SCALE),
                       settings.WALL_THICKNESS()):
            block = arcade.SpriteSolidColor(
                settings.WALL_THICKNESS(),
                settings.WALL_THICKNESS(),
                settings.BASE_COLOR,
            )
            block.center_x = x - 8 * settings.SCALE
            block.center_y = y
            self.wall_list.append(block)
            block = arcade.SpriteSolidColor(
                settings.WALL_THICKNESS(),
                settings.WALL_THICKNESS(),
                settings.BASE_COLOR,
            )
            block.center_x = x + 8 * settings.SCALE
            block.center_y = y
            self.wall_list.append(block)

    def create_wall(self):
        def block_at(x, y):
            block = arcade.SpriteSolidColor(
                settings.WALL_THICKNESS(),
                settings.WALL_THICKNESS(),
                settings.WALL_COLOR,
            )
            block.center_x = x
            block.center_y = y
            wally.append(block)

        while True:
            wally = []
            length = random.randint(settings.WALL_MIN(), settings.WALL_MAX())
            if random.random() < 0.5:
                # Horizontal
                start_x = random.randint(0, settings.SCREEN_WIDTH - length)
                y = random.randint(0, settings.SCREEN_HEIGHT)
                for x in range(start_x, start_x + length,
                               settings.WALL_THICKNESS()):
                    block_at(x, y)
            else:
                # Vertical
                start_y = random.randint(0, settings.SCREEN_HEIGHT - length)
                x = random.randint(0, settings.SCREEN_WIDTH)
                for y in range(start_y, start_y + length,
                               settings.WALL_THICKNESS()):
                    block_at(x, y)
            for block in wally:
                if arcade.check_for_collision_with_list(block, self.wall_list):
                    break  # Oops, break it off, try a new wall
            else:
                for block in wally:
                    self.wall_list.append(block)
                return

    def create_food_blob(self, size=10, start_coo=None):
        scale = settings.SCALE * 3
        if start_coo:
            start_x, start_y = start_coo
        else:
            start_x = random.randint(0, settings.SCREEN_WIDTH - size * scale)
            start_y = random.randint(0, settings.SCREEN_HEIGHT - size * scale)

        for x in range(start_x, start_x + size * scale, scale):
            for y in range(start_y, start_y + size * scale, scale):
                block = arcade.SpriteSolidColor(scale, scale,
                                                settings.FOOD_COLOR)
                block.center_x = x
                block.center_y = y
                if not arcade.check_for_collision_with_list(
                        block, self.wall_list):
                    self.food_list.append(block)

    def on_draw(self):
        # This command has to happen before we start drawing
        arcade.start_render()

        # Draw all the sprites.
        self.wall_list.draw()
        self.food_list.draw()
        for ant in self.ant_list:
            ant.draw()
            # ant.draw_hit_box((255,0,0))

    # def on_key_press(self, key, modifiers):
    #     """Called whenever a key is pressed. """
    #
    #     if key == arcade.key.UP:
    #         self.player_sprite.change_y = MOVEMENT_SPEED
    #     elif key == arcade.key.DOWN:
    #         self.player_sprite.change_y = -MOVEMENT_SPEED
    #     elif key == arcade.key.LEFT:
    #         self.player_sprite.change_x = -MOVEMENT_SPEED
    #     elif key == arcade.key.RIGHT:
    #         self.player_sprite.change_x = MOVEMENT_SPEED
    #
    # def on_key_release(self, key, modifiers):
    #     """Called when the user releases a key. """
    #
    #     if key == arcade.key.UP or key == arcade.key.DOWN:
    #         self.player_sprite.change_y = 0
    #     elif key == arcade.key.LEFT or key == arcade.key.RIGHT:
    #         self.player_sprite.change_x = 0

    def on_update(self, delta_time):
        self.colony.tick()
        self.actual_fps = (99 * self.actual_fps + 1 / delta_time) / 100
        food_per_100_turns = self.colony.food_per_turn() * 100
        self.set_caption(
            f"{settings.SCREEN_TITLE} - {self.actual_fps:0.0f} fps, {food_per_100_turns:0.0f} food per 100 turns - {self.generation}"
        )
        arcade.start_render()
        for ant in self.ant_list:
            ant.move()
        self.generation += 1  #!! Dubbel naast colony.tick()
        if self.generation_callback:
            self.generation_callback(self.generation, self)
示例#17
0
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)
示例#18
0
@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:
示例#19
0
文件: simulation.py 项目: Kimbsy/Ants
class Simulation:
  """Main simulation class"""

  # Constuctor
  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()

    # Initializa the cells
    self.init_cells()

    # Set the number of Food objects availble
    self.food_count = 1

    # Initialise Food objects
    self.init_food()

    # Initialize the colony
    self.colony = Colony(self)

  # Stop the app
  def stop(self):
    self.is_running = False

  # Create 2D list of Cell objects
  def init_cells(self):
    # Create grid_size * grid_size array of Cells
    for i in range(0, self.grid_size):
      cell_row = []
      for j in range(0, self.grid_size):
        # Pass in dimensions of surface and grid_size so Cell can decide its own size
        cell = Cell(i, j, self.dimens, self.grid_size)

        # Add it to the sim's cells list
        cell_row.append(cell)
      self.cells.append(cell_row)

  # Populate food_items list
  def init_food(self):
    for i in range(0, self.food_count):
      self.add_food()

  # Update the simulation
  def update(self):
    # Update the cells
    for cell_row in self.cells:
      for cell in cell_row:
        cell.update()

    # Update the colony
    self.colony.update(self.dimens)

    # Update food items
    for food in self.food_items:
      food.update()

  # Add food to list
  def add_food(self):
    food = Food(self)
    self.food_items.append(food)

  # Remove food from list
  def kill_food(self, food):
    self.food_items.remove(food)

  # Get the cell at the given position
  def get_cell_at(self, pos):
    # Get position ad dimensions
    width = self.dimens[0]
    height = self.dimens[1]
    x = pos[0]
    y = pos[1]

    # Calculate grid coordinates
    grid_x = int(((x / width) * self.grid_size))
    grid_y = int(((y / height) * self.grid_size))

    # Get Cell at coordinates
    cell = self.cells[grid_x][grid_y]
    return cell

  # Get the eight cells surrounding a position
  def get_surrounding_cells(self, pos):
    cells = []

    cell = self.get_cell_at(pos)

    # Calculate the indices of the rows surrounding the cell
    left_index = (cell.grid_i - 1) % self.grid_size
    right_index = (cell.grid_i + 1) % self.grid_size
    top_index = (cell.grid_j - 1) % self.grid_size
    bottom_index = (cell.grid_j + 1) % self.grid_size

    cells.append(self.cells[left_index][top_index])
    cells.append(self.cells[cell.grid_i][top_index])
    cells.append(self.cells[right_index][top_index])
    cells.append(self.cells[right_index][cell.grid_j])
    cells.append(self.cells[right_index][bottom_index])
    cells.append(self.cells[cell.grid_i][bottom_index])
    cells.append(self.cells[left_index][bottom_index])
    cells.append(self.cells[left_index][cell.grid_j])

    return cells

  # Reset the pheremone levels in the cell at a position
  def reset_cell(self, pos):
    # Find the cell to update
    cell = self.get_cell_at(pos)
    cell.set_pheremone_level(255)

  # Draw things to surface
  def render(self, surface):
    # Draw cells
    for cell_row in self.cells:
      for cell in cell_row:
        cell.render(surface)

    # Draw Food
    for food in self.food_items:
      food.render(surface)

    # Draw colony
    self.colony.render(surface)
示例#20
0

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)
示例#21
0
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()
示例#22
0
class Instance(object):
    """
    Instance class representing the TSP Instance
    """
    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 get_path_distance(self, path):
        """
        Returns the total total distance of a path taken
        """
        length = len(path)
        distance = 0
        for i in range(length):
            distance += self.distances[path[i]][path[(i + 1) % length]]
        return distance

    def update_pheromones(self, colony):
        """
        Updates pheromones between nodes globally, a way of letting ants know on future
        generations about the strongest paths to take.
        """

        # Decay all pheromone trails
        for i in range(len(self.nodes)):
            for j in range(len(self.nodes)):
                self.pheromones[i][j] *=(1- self.decay)

        # Add to edge pheromones if edge was part of successful tour
        for ant in colony.ants:
            distance = self.get_path_distance(ant.path)
            if distance <= colony.min_distance:
                for i, j in ant.nodes_traversed():
                    self.pheromones[i][j] += self.q / distance

        # Keep pheromone trails greater than or equal to 0.01, so nodes do not become
        # completely unviable choices.
        for i in range(len(self.nodes)):
            for j in range(len(self.nodes)):
                self.pheromones[i][j] = max(self.pheromones[i][j], self.min_pheromone)



    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
示例#23
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 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()
示例#25
0
class Simulation:
    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 stop(self):
        self.is_running = False

    def init_cells(self):
        for i in range(0, self.grid_size):
            cell_row = []
            for j in range(0, self.grid_size):
                cell = Cell(i, j, self.dimens, self.grid_size)

                cell_row.append(cell)
            self.cells.append(cell_row)

    def init_food(self):
        for i in range(0, self.food_count):
            self.add_food()

    def update(self):
        for cell_row in self.cells:
            for cell in cell_row:
                cell.update()

        self.colony.update(self.dimens)

        for food in self.food_items:
            food.update()

    def add_food(self):
        food = Food(self)
        self.food_items.append(food)

    def kill_food(self, food):
        self.food_items.remove(food)

    def get_cell_at(self, pos):
        width = self.dimens[0]
        height = self.dimens[1]
        x = pos[0]
        y = pos[1]

        grid_x = int(((x / width) * self.grid_size))
        grid_y = int(((y / height) * self.grid_size))

        cell = self.cells[grid_x][grid_y]
        return cell

    def get_surrounding_cells(self, pos):
        cells = []

        cell = self.get_cell_at(pos)

        left_index = (cell.grid_i - 1) % self.grid_size
        right_index = (cell.grid_i + 1) % self.grid_size
        top_index = (cell.grid_j - 1) % self.grid_size
        bottom_index = (cell.grid_j + 1) % self.grid_size

        cells.append(self.cells[left_index][top_index])
        cells.append(self.cells[cell.grid_i][top_index])
        cells.append(self.cells[right_index][top_index])
        cells.append(self.cells[right_index][cell.grid_j])
        cells.append(self.cells[right_index][bottom_index])
        cells.append(self.cells[cell.grid_i][bottom_index])
        cells.append(self.cells[left_index][bottom_index])
        cells.append(self.cells[left_index][cell.grid_j])

        return cells

    def reset_cell(self, pos):
        cell = self.get_cell_at(pos)
        cell.set_pheromone_level(255)

    def render(self, surface):
        for cell_row in self.cells:
            for cell in cell_row:
                cell.render(surface)

        for food in self.food_items:
            food.render(surface)

        self.colony.render(surface)