Ejemplo n.º 1
0
    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)
Ejemplo n.º 2
0
    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):
            print("Iteration: %d Best OF: %f" % (i, best_ant.of()))
            colony = []
            for j in range(self.n_ants):
                ant = Ant(np.random.randint(self.distances.shape[0]),
                          self.distances.shape[0])
                ant.build_path(self.distances, 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() < best_ant.of():
                best_ant = n_bests_ants[0]

            self.update_pheromone(best_ant, n_bests_ants)
        print(self.pheromone)
        return best_ant
Ejemplo n.º 3
0
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
Ejemplo n.º 4
0
    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
Ejemplo n.º 5
0
def part2(instructions):
    ship = Ant(0, 0, 90)
    waypoint = Ant(10, 1)
    for ins in instructions:
        i, value = ins[0], int(ins[1:])
        if i == "F":
            x, y = waypoint.pos()
            ship.x += value * x
            ship.y += value * y
        elif i == "N":
            waypoint.north(value)
        elif i == "S":
            waypoint.south(value)
        elif i == "E":
            waypoint.east(value)
        elif i == "W":
            waypoint.west(value)
        elif i in "LR":
            dist = waypoint.dist()
            angle = waypoint.angle()
            waypoint.x = 0
            waypoint.y = 0
            if i == "L":
                waypoint.heading = angle + value
            else:
                waypoint.heading = angle - value
            waypoint.forward(dist)
    return manhattan_distance((0, 0), ship.pos())
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))
Ejemplo n.º 7
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())
         ])
Ejemplo n.º 8
0
    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
Ejemplo n.º 9
0
    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()
Ejemplo n.º 10
0
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 __init__(self,
                 emptyNodes,
                 foodSources,
                 antHills,
                 pheromoneStrength=1,
                 baseEdgeWeight=1,
                 pheromoneDecayRate=0.01):
        super(FoodTravelGraph, self).__init__()
        self.ants = []
        self.frames = []
        self.baseEdgeWeight = baseEdgeWeight
        self.emptyNodes = emptyNodes
        self.foodSources = foodSources
        self.antHills = antHills
        self.pheromoneStrength = pheromoneStrength
        self.baseEdgeWeight = baseEdgeWeight
        self.pheromoneDecayRate = pheromoneDecayRate

        for node in emptyNodes:
            self.add_node(node, pos=emptyNodes[node], isFood=False)

        for node in foodSources:
            self.add_node(node, pos=foodSources[node], isFood=True)

        for node in antHills:
            self.add_node(node,
                          pos=antHills[node]["pos"],
                          ants=antHills[node]["ants"],
                          isFood=False)
            for ant in range(antHills[node]["ants"]):
                self.ants.append(
                    Ant(home=node,
                        pos=node,
                        pheromoneStrength=pheromoneStrength))
                # create ant

        for hill in antHills:
            for node in emptyNodes:
                # add edge between this ant hill and this empty node
                self.add_edge(hill,
                              node,
                              pheromones=0,
                              length=dist(antHills[hill]["pos"],
                                          emptyNodes[node]))

                # add edges between this empty node and all food nodes
                for food in foodSources:
                    self.add_edge(node,
                                  food,
                                  pheromones=0,
                                  length=dist(foodSources[food],
                                              emptyNodes[node]))

                # add edges between this empty node and all other empty nodes
                for node2 in emptyNodes:
                    self.add_edge(node,
                                  node2,
                                  pheromones=0,
                                  length=dist(emptyNodes[node2],
                                              emptyNodes[node]))
Ejemplo n.º 12
0
 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))
Ejemplo n.º 13
0
def test_ant_do_turn():
    ant = Ant(1, 1)
    assert ant.orientation == Orientation.UP
    ant.turn(TurnDirection.LEFT)
    assert ant.orientation == Orientation.LEFT
    ant.turn(TurnDirection.LEFT)
    assert ant.orientation == Orientation.DOWN
Ejemplo n.º 14
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)
    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)
Ejemplo n.º 16
0
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
Ejemplo n.º 17
0
 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()
Ejemplo n.º 18
0
 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
Ejemplo n.º 19
0
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()
Ejemplo n.º 20
0
    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[:]
Ejemplo n.º 21
0
    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
Ejemplo n.º 22
0
    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 search(self, n):
        """Includes row construction and pheromone update of all ants in a single search
        iteration."""
        points_i = [random.randint(0, len(self.points) - 1) for _ in range(n)]
        ants = []

        for i in points_i:
            config = self.config['ant']
            ant = Ant(self.points, i, self.orig_kd_tree, self.points_orig_i, config)
            ants.append(ant)

        for ant in ants:        
            ant.construct_solution(self.kd_tree, self.pheromone_matrix,
                    self.min_max_dist, self.min_max_angle)
            mm_dist = self.update_min_max(ant.candidate_dists, self.min_max_dist, self.n)
            mm_angle = self.update_min_max(ant.candidate_angles, self.min_max_angle, self.n)
            if mm_dist: self.min_max_dist = mm_dist 
            if mm_angle: self.min_max_angle = mm_angle 
            self.n += 1

        for key, pher_value in self.pheromone_matrix.items():
            self.pheromone_matrix[key] = min(self.MIN_PHER, self.EVAP_RATE * pher_value)

        for ant in ants:
            ant.pheromone_update(self.pheromone_matrix, min_periods=1, center=True,
                                 window=self.WINDOW, win_type=self.WIN_TYPE)

        return ants
Ejemplo n.º 24
0
 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
Ejemplo n.º 25
0
    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
Ejemplo n.º 26
0
 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)
Ejemplo n.º 27
0
    def __init__(self):
        with open('meetlog.csv', 'w+') as x:
            pass
        with open('creation.csv', 'w+') as f:
            pass
        with open('changelog.csv', 'w+') as f:
            pass
        with open('ant_data.csv', 'w+') as f:
            pass
        self.index = {
            "worker": 0,
            "harvester": 0,
            "soldier": 0,
            "caretaker": 0
        }

        self.array = []

        for i in range(100):
            types = ['worker', 'harvester', 'soldier', 'caretaker']
            choice_of_ant = random.randint(0, 3)
            newAnt = Ant(types[choice_of_ant])
            with open('creation.csv', 'a') as f:
                f.write(f'{newAnt.role} \n')
            self.array.append(newAnt)
            self.index[newAnt.role] += 1

        print(self.index)
Ejemplo n.º 28
0
    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))
Ejemplo n.º 29
0
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
Ejemplo n.º 30
0
def reset():
    global grid, ant
    grid.delete()
    del grid
    del ant

    grid = Grid([5, 5], rules, batch, window, scale=25)
    ant = Ant(2, 2, grid)