Esempio n. 1
0
    def Ant(self):
        a = ant.Ant(self)
        self.ants.append(a)
        a.id = "ant" + str(AntFarm.ANT_ID)
        AntFarm.ANT_ID += 1

        return a
Esempio n. 2
0
    def get_best_path(self, num_ants=2, num_steps=3):
        NUM_CITIES = len(self.cities)
        NUM_ANTS = num_ants
        NUM_STEPS = num_steps
        self.calc_attraction()
        ants = []

        for i in xrange(0, NUM_ANTS):
            ants.append(ant.Ant(i, self))

        for step in xrange(0, NUM_STEPS):
            print "Step: ", step + 1, " of ", NUM_STEPS
            path_lens = []
            paths = []
            argu = self
            procs = []

            q = Queue()

            for a in ants:
                p = Process(target=self.mp_tour, args=(
                    a,
                    q,
                ))
                procs.append(p)
                p.start()

            for p in procs:
                p.join()

            ants = []
            while q.empty() == False:
                ants.append(q.get())

            for a in ants:
                #print a.index
                path_len = a.calc_path_length()
                path_lens.append(path_len)
                paths.append(a.path)
                self.update_pheromone(a)
                self.update_routing_table(a)

            best_path_len = min(path_lens)
            best_path = paths[path_lens.index(best_path_len)]

            print "step best path: ", best_path_len, " step: ", step + 1

            self.shortest_paths.append(best_path)
            self.shortest_paths_lens.append(best_path_len)

        output_index = self.shortest_paths_lens.index(
            min(self.shortest_paths_lens))
        output_path = self.shortest_paths[output_index]
        self.shortest_path_len = self.shortest_paths_lens[output_index]
        self.shortest_paths = []
        self.shortest_paths_lens = []

        return output_path
    def __init__(self):
        # 实例化
        self.map = mp.MapInit()
        self.ant = at.Ant()

        self.path = self.map.load_csv()
        self.pheromone_ini = 8
        self.alpha = 0.5
        self.beta = 3
Esempio n. 4
0
    def get_best_path(self, num_ants=2, num_steps=3):
        ants = []
        self.calc_attraction()
        shuffle(self.cities)

        for i in range(0, num_ants):
            ants.append(ant.Ant(i, self))

        for step in range(0, num_steps):
            print("Step: {} of {}".format(step + 1, num_steps))
            path_lens = []
            paths = []
            procs = []

            q = Queue()

            for a in ants:
                p = Process(target=self.mp_tour, args=(
                    a,
                    q,
                ))
                procs.append(p)
                p.start()

            for p in procs:
                p.join()

            ants = []
            while q.empty() == False:
                ants.append(q.get())

            for a in ants:
                path_len = a.calc_path_length()
                path_lens.append(path_len)
                paths.append(a.path)
                self.update_pheromone(a)
                self.update_routing_table(a)

            best_path_len = min(path_lens)
            best_path = paths[path_lens.index(best_path_len)]

            print("Step best path: {} Step: {}".format(best_path_len,
                                                       step + 1))

            self.shortest_paths.append(best_path)
            self.shortest_paths_lens.append(best_path_len)

        output_index = self.shortest_paths_lens.index(
            min(self.shortest_paths_lens))
        output_path = self.shortest_paths[output_index]
        self.shortest_path_len = self.shortest_paths_lens[output_index]
        self.shortest_paths = []
        self.shortest_paths_lens = []

        return output_path
Esempio n. 5
0
def startup():

	mapgen()		

	for i in range(9):

		antList.append(ant.Ant((random.randint(0, 49), 23), 0))

		for j in range(2):
			
			foodList.append(food.Food(random.randint(0,49), array))		
Esempio n. 6
0
def restart():

	print("restarted")

	mapgen()

	#new units

	for i in range(2):

		antList.append(ant.Ant((random.randint(0, 49), 23), 0))

	#mutated units

	for i in range(5):

		am = ant.Ant((random.randint(0, 49), 23), 0)

		am.neuralNet = winner.neuralNet.makeMutant(1)
	
		antList.append(am)

	#original unit

	for i in range(2):

		ao = ant.Ant((random.randint(0, 49), 23), 0)
		
		ao.neuralNet = winner.neuralNet.makeCopy()

		antList.append(ao)

	foodList.clear()

	for i in range(18):

		foodList.append(food.Food(random.randint(0,49), array))
Esempio n. 7
0
def algorithm():
    vertices = {i for i in range(0, 12)}
    edges = [(0, 10), (0, 2), (1, 2), (1, 7), (1, 10), (2, 9), (3, 4), (3, 6),
             (3, 11), (4, 8), (4, 10), (5, 8), (5, 10), (6, 10), (6, 11),
             (7, 9), (7, 11), (0, 5)]
    w = world.World(vertices, edges, 0.1)
    iterations = 200
    number_of_ants = 50
    goals = [(i, j) for i in range(0, 12) for j in range(i + 1, 12)]
    solutions = {}
    for goal in goals:
        global_best_solution = None
        ants = []

        for _ in range(0, number_of_ants):
            ants.append(ant.Ant(w, goal[0], goal[1]))

        for _ in range(0, iterations):
            for a in ants:
                # print(a.find_solution())
                a.find_solution()
            local_best_ant = ant.find_best_ant(ants)
            if local_best_ant is not None:
                if global_best_solution is None:
                    global_best_solution = local_best_ant.solution
                elif len(local_best_ant.solution) < len(global_best_solution):
                    global_best_solution = local_best_ant.solution

            w.update_pheromone()
            for a in ants:
                a.update_path()
                a.reset()
            # pprint(w.edges)
            # print(f"best solution {global_best_solution}")
        w.reset_edges()
        solutions[goal] = global_best_solution
        print(f"{goal} - {global_best_solution}")
    pprint(solutions)
Esempio n. 8
0
                          [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1],
                          [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1]]

# For trails:
trail_value = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
# List with chances of each choice
chance_list = []
probability_list = []
city_list = []
not_visited_cities = [1, 2, 3, 4, 5, 6, 7]
testing_coordinates = [[100, 100], [50, 200], [400, 50], [150, 500],
                       [500, 150], [500, 400], [600, 300], [400, 400]]
ant = ant.Ant(0, 0)
current_city = 0
shortest_path = 1000
which_iteration = 0
trail_checker = 0

# Creates cities according to testing_coordinates list


def show_pheromones():
    for element in pheromone_value_matrix:
        print(element)


def city_maker():
    city_list.clear()
Esempio n. 9
0
import time

size = int(input("How large a grid do you want? : "))

print("Do you want to step through the positions, or just see a specific position?")
step_through = int(input("Type 1 to step, or 0 to jump to a point: "))

if step_through == 0:
    steps = int(input("How many steps? : "))
    i = 0
else:
    print("Press enter repeatedly to continue, or type 'q' to exit")
    steps = -1
    i = 0

traveler = ant.Ant()
plot = grid.Grid(size)

done = False
while not done:
    x = traveler.get_x()
    y = traveler.get_y()
    #print(x, y, traveler.get_direction())

    if plot.get_color(x, y) is 0:
        traveler.right()
    else:
        traveler.left()

    plot.change_color(x, y)
Esempio n. 10
0
def spawnAnt(color, x, y):
    ant.Ant(color, x, y)
Esempio n. 11
0
def AOC_path (nest, food, DecTable, no_of_colonies,no_of_ants=5) :
    """
    This function return the best (maximum proability) ant path connecting the nest with food.
    """
    #go = time.time()
    no_of_critical_ants = 0
    cost_goal_generation = 0.3
    
    
    for generation in range(no_of_colonies) :
        #print('colony',no_of_colonies)
        #progressBar(value = generation, endvalue=no_of_colonies)
        #sys.stdout.write("done: " % generation / no_of_colonies * 100.)
        #sys.stdout.flush()
        if no_of_critical_ants < 30 :
            cost_goal_generation -= 0.001 
        else : cost_goal_generation += 0.001

 
        ant_colony = []
        no_of_critical_ants = 0
        
        
        for m in range(no_of_ants) :
            #print('ant',m)
            ant = ANT.Ant(birth_coordinates=nest)
           
            ant_colony.append(ant) 

            while (ant.location != food) :

                loc = ant.location
                state_transition_probas = []

                neigbours = ANT.GetNeighbours(point=loc)


                for n in neigbours :
                    state_transition_probas.append(DecTable.p_ij(location=loc,destination=n,track=ant.track))
                
                next_state = GRID.GetNextState(state_transition_probas=state_transition_probas,neigbours=neigbours)
                ant.AddMove(nextpoint=next_state)
                #print(loc,next_state)
                
                colormap_value = 1./ DecTable.eta_ij[loc,next_state]
                ant.AddCost(value=colormap_value)

                if colormap_value >= cost_goal_generation :
                    ant.critical_steps += 1

                if ant.critical_steps > 1 :
                    #print 'dead'
                    no_of_critical_ants += 1
                    break



                # if level reached of the food one, go up or down
                if (ant.location[0] == food[0]) :
                    #print('level reached')
                    #print('food',food)
                    while ( loc[1] != food[1] and loc[1] > 1 and loc[1] < 88) :
                        loc = ant.location

                        #walk up
                        if loc[1] < food[1] :
                            next_state = (loc[0],loc[1]+1)
                        else :
                            next_state = (loc[0],loc[1]-1)
                        
                        #print(next_state)
                        ant.AddMove(nextpoint=next_state)
                        #print 1./DecTable.eta_ij[loc,next_state]
                        colormap_value = 1./ DecTable.eta_ij[loc,next_state]
                        ant.AddCost(value=colormap_value)

                        #print colormap_value

                        if colormap_value >= cost_goal_generation :
                            ant.critical_steps += 1

                        if ant.critical_steps > 1 :
                            #print 'dead'
                            no_of_critical_ants += 1
                            break
                    else :
                        break
                    break


        #print('ok')
        DecTable.UpdatePheromone(colony=ant_colony)
        #print('ok')

        """
        for n in ANT.GetNeighbours((108,45)) :
            print n
            print DecTable.p_ij(location=(108,45), destination=n)
        """

        #print ('reduced goal', cost_goal_generation)
        #print( 'no_of_critical_ants', no_of_critical_ants)

        """
        if generation%100 == 0 :
            print (generation)

            plt.figure(figsize=(11,11))
            pl.FlooadPlot(pic=gt_map,flood_level=0.3)

            cost_in_generation = []
            for a in ant_colony :
                track_length = 1.*len(a.track)
                pl.PlotTrack(track=a.track)
                #plt.pause(0.05)
                if a.critical_steps < 2 :
                    #print 'hi'
                    cost_in_generation.append(a.cost / track_length)
                else :   
                    cost_in_generation.append(1.)
                #print TrackCost(ant=a,cost_map=astar_landscape)
            print ('minimal track', np.argmin(cost_in_generation))
            print ('cost', ant_colony[np.argmin(cost_in_generation)].cost)
            print ('cost per unit length', ant_colony[np.argmin(cost_in_generation)].cost / len(ant_colony[np.argmin(cost_in_generation)].track))
            print ('amount of critical steps', ant_colony[np.argmin(cost_in_generation)].critical_steps)


            pl.HighlightTrack(ant_colony[np.argmin(cost_in_generation)].track)
            plt.show()
        """
    stop = time.time()

    #print ('total time: ', stop-go)
    return GetMaxProbaPath(start=nest,goal=food,decisionTable=DecTable)
Esempio n. 12
0
    def run(self):
        pygame.display.set_caption("Ant Simulator")
        # saving cords every ... secs
        pygame.time.set_timer(pygame.USEREVENT, 3000)
        # initialize food
        nest = Object(self.width / 2 - 5, self.height / 2 - 5, 10, 10,
                      (55, 55, 55))
        foods = []
        ants = []

        foods.append(Object(500, 200, 50, 50, (0, 255, 0)))
        foods.append(Object(100, 350, 50, 100, (0, 255, 0)))
        back_ants = []

        run = True
        while run:
            self.screen.fill((0, 0, 0))
            self.clock.tick(self.fps)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        run = False
                if event.type == pygame.USEREVENT and not self.foundFood:
                    for ant in ants:
                        ant.saveCoordinates()

            # create ants one time
            while not self.ant_stop:
                for i in range(1500):
                    ants.append(
                        ant_file.Ant(self.width / 2, self.height / 2, 1,
                                     random.randrange(3, 12)))
                self.ant_stop = True

            # draw things
            for ant in ants:
                ant.update(self.screen, self.width, self.height)

            for food in foods:
                food.update(self.screen)
            self.nest.update(self.screen)

            # food collison
            for ant in ants:
                if not ant.back:
                    for food in foods:
                        if ant.x >= food.x and ant.x <= food.x + food.width:
                            if ant.y >= food.y and ant.y <= food.y + food.height:
                                # save cords for one last time
                                ant.saveCoordinates()
                                back_ants.append(ant)
                                self.foundFood = True

            # move ant back to nest
            if self.foundFood:
                for ant in back_ants:
                    #}ant.color = (127, 30, 212)
                    ant.moveBack(nest, self.fps)
                    #ant.drawPath(self.screen)

            pygame.display.flip()
Esempio n. 13
0
    # S - source node
    # D - destination node
    S, D = map(int, raw_input().split())

    for i in xrange(E):
        # a - node
        # b - node
        # d - weight
        a, b, weight = map(int, raw_input().split())
        graph.add(a, b, weight)

    for node in graph.nodes:
        node.initPheromoneTable()

    # Debug output - init pheromone table
    for node in graph.nodes:
        print "\nId: " + str(node.id + 1)
        print "Links: "

        for entry in node.pheromoneTable:
            print "\tId: " + str(entry.link[0].id + 1) + " - " + str(
                entry.probability) + '%'

    # Generate ants
    for i in xrange(globals.ANT_COUNT):
        a = ant.Ant('ant_' + str(i) + '@127.0.0.1', globals.PASSWORD, i, graph,
                    globals.AntDirection.FORWARD_ANT, S - 1, D - 1)

        a.start()
        time.sleep(globals.TICK_PERIOD)
Esempio n. 14
0
 def __init__(self, numberOfAnts, size):
     self.ants = [ant.Ant(i + 1, size) for i in range(numberOfAnts)]
     self.size = size
     self.board = [[0 for x in range(size[0])] for y in range(size[1])]
Esempio n. 15
0
import pygame
import ant as antClass
from time import time as epoh

pygame.init()

size = [300, 300]
screen = pygame.display.set_mode(size)
pygame.display.set_caption('')

clock = pygame.time.Clock()
fps = 40

ants = []
for i in range(50):
    ants += [(antClass.Ant(i + 125, size[1] - 12))]
    ants += [(antClass.Ant(i + 125, size[1] - 10))]
    ants += [(antClass.Ant(i + 125, size[1] - 8))]
    screen.set_at((i + 125, size[1] - 8), [255, 0, 0])

time = int(epoh())
frames = 0

fireplace = pygame.image.load('fireplace.png')
fireplace = pygame.transform.scale(fireplace, (300, 350))
screen.blit(fireplace, (0, 0))

mona_lisa = pygame.image.load('mona_lisa.jpg')
mona_lisa = pygame.transform.scale(mona_lisa, (50, 70))
screen.blit(mona_lisa, (210, 33))
Esempio n. 16
0
 def test_no_deps(self):
     a = ant.Ant()
     self.assertEquals(a._dependencies(), [])