Ejemplo n.º 1
0
        def ant_colony(self,row_number):
            ant=AntColony()
            points= self.combine_all_category_plus_store_code_position_similarity(row_number)[0]
            pheromone=self.combine_all_category_plus_store_code_position_similarity(row_number)[1]
            x= ant.repeated_ant_colony(number_of_repeat=10,points=points,points_pheromone=pheromone)

            return x
Ejemplo n.º 2
0
    def calcFitnesses(self):
        '''
        calculate fitness of every chromosome
        '''
        costs = []
        routes = []

        for c in range(self.n_chromosomes):
            cost = 0
            truck_routes = []
            for t in range(self.n_trucks):
                if (len(self.truck_loads[c][t]) > 0):
                    if (len(self.truck_loads[c][t]) <= 9):
                        truck_distance, path = self.brute_force_solution(
                            self.truck_loads[c][t])
                    else:
                        truck_distance_mat = self.submat(
                            self.truck_loads[c][t])
                        ac = AntColony(distances=truck_distance_mat,
                                       n_ants=20,
                                       n_best=10,
                                       n_iterations=100,
                                       decay=0.95,
                                       alpha=1,
                                       beta=4)
                        path, truck_distance = ac.run()
                    cost += (truck_distance * self.transportation_costs[t])
                    truck_routes.append(path)
                else:
                    truck_routes.append(())
            costs.append(cost)
            routes.append(truck_routes)
        self.costs = np.array(costs)
        self.fitnesses = (self.fitness_counter - self.costs) + 1
        self.routes = routes
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.º 4
0
def run_aco(filename, map_param, num_ants, maxiter, alpha, beta,
            evaporation_coeficient):
    if map_param is 1:
        small_world = le_coordenadas_tsp("test_cases/berlin52.tsp")
        small_world_solution = read_solution()
        dicio = dicio_cidades(small_world)
    elif map_param is 2:
        medium_world = le_coordenadas_tsp("test_cases/kroA100.tsp")
        medium_world_solution = read_solution()
        dicio = dicio_cidades(medium_world)
    elif map_param is 3:
        large_world = le_coordenadas_tsp("test_cases/ch150.tsp")
        large_world_solution = read_solution()
        dicio = dicio_cidades(large_world)

    sol = [
        0, 21, 48, 31, 17, 30, 20, 16, 2, 44, 18, 40, 7, 8, 9, 42, 32, 50, 10,
        51, 13, 12, 46, 25, 26, 27, 11, 24, 3, 47, 23, 5, 4, 14, 37, 39, 36,
        38, 35, 34, 33, 43, 45, 15, 28, 49, 19, 22, 29, 41, 6, 1
    ]
    f = eval_solution(distance, dicio)
    print(f(sol, dicio))

    colony = AntColony(
        dicio,
        distance,
        ant_count=num_ants,
        alpha=alpha,
        beta=beta,
        pheromone_evaporation_coefficient=evaporation_coeficient,
        time_budget=maxiter)
    colony.mainloop()

    data = {
        "best_individuals": colony.best_individuals,
        "fitness_averages": colony.fitness_averages,
        "generation_calculation_times": colony.generation_calculation_times,
        "population_initialization_time":
        colony.population_initialization_time,
        "population_size": num_ants,
        "iterations": maxiter,
        "alpha": alpha,
        "beta": beta,
        "evaporation_coeficient": evaporation_coeficient
    }
    print(" ------------------ Converting ---------------------")
    converter = CsvConverter(filename, data)
    converter.aco_to_csv()
    print(" ------------------ Ending ACO ---------------------")
Ejemplo n.º 5
0
    def calcFitnessesOffspring(self):
        '''
        calculate fitness of every chromosome
        '''
        costs = []
        routes = []

        for c in range(np.shape(self.offspring)[2]):
            cost = 0
            truck_routes = []
            for t in range(self.n_trucks):
                if (len(self.offspring_loads[c][t]) > 0):
                    truck_distance_mat = self.submat(
                        self.offspring_loads[c][t])
                    if (len(self.offspring_loads[c][t]) > 3):
                        ac = AntColony(distances=truck_distance_mat,
                                       n_ants=20,
                                       n_best=10,
                                       n_iterations=10,
                                       decay=0.95,
                                       alpha=1,
                                       beta=4)
                        path, truck_distance = ac.run()
                    else:
                        truck_distance = sum([
                            truck_distance_mat[i, (i + 1) %
                                               len(truck_distance_mat)]
                            for i in range(len(truck_distance_mat))
                        ])
                        path = [(i, (i + 1) % len(truck_distance_mat))
                                for i in range(len(truck_distance_mat))]
                    cost += (truck_distance * self.transportation_costs[t])
                    truck_routes.append(path)
                else:
                    truck_routes.append(())
            costs.append(cost)
            routes.append(truck_routes)
        self.offspring_costs = np.array(costs)
        self.offspring_fitnesses = (self.fitness_counter - self.costs) + 1
        self.routes = routes
Ejemplo n.º 6
0
    def __calculate(self):
        """Private method. Computes an optimal path using ant colonization."""
        # All values taken from paper
        self.num_ants = 10
        self.num_iterations = 50  
        self.num_repetitions = 2 

        try:
            self.graph = AntGraph(self.num_nodes, self.distances,self.colors) # construct the graph
            self.best_path_cost = sys.maxint # initialize cost to infinity
            for i in range(0, self.num_repetitions): # run multiple repetitions. Run multiple repetitions because each iteration is random.
                self.graph.reset_tau()  # reset trail level
                ant_colony = AntColony(self.graph, self.num_ants, self.num_iterations) # construct ant colony
                ant_colony.start()
                if ant_colony.best_path_cost < self.best_path_cost: # if we found a better path, take that path
                    self.best_path_vec = ant_colony.best_path_vec
                    self.best_path_cost = ant_colony.best_path_cost
            self.best_path_colors = [self.graph.get_color(node) for node in self.best_path_vec]

        except Exception, e:
            print "exception: " + str(e)
            traceback.print_exc()
Ejemplo n.º 7
0
def main():
    json_data = json.loads(str(request.data, encoding='utf-8'))
    adjList = json_data["adj"]
    ant_count = int(json_data["ant_count"])
    iterations = int(json_data["iterations"])
    alpha = float(json_data["alpha"])
    beta = float(json_data["beta"])
    rho = float(json_data["rho"])
    Q = int(json_data["Q"])

    for i in range(len(adjList[0])):
        for j in range(len(adjList[0])):
            if adjList[i][j] is None:
                adjList[i][j] = math.inf

    # print(adjList)
    ac = AntColony(ant_count, iterations, alpha, beta, rho, Q)
    graph = Graph(adjList, len(adjList[0]))
    path, cost = ac.solve(graph)
    data = {"cost": cost, "path": path}
    # print(type(data),type(json.dumps(data)))

    return json.dumps(data)
Ejemplo n.º 8
0
    def acoga(root, IT_WITHOUT_G_BETTER=It_Without_G_Better):
        t1 = time()
        best_states = AntColony.ant_colony(root, IT_WITHOUT_G_BETTER)
        t2 = time()
        print('Ant Colony time:', t2 - t1)
        print('Current best:', best_states[0].heuristic)

        best_states = [GeneticState(state.state) for state in best_states]

        t1 = time()
        ret = GeneticAlgorithm.genetic_algorithm(best_states, IT_WITHOUT_G_BETTER)
        t2 = time()
        print('Genetic Algorithm time:', t2 - t1)
        return ret
def test_completable_path():
	num_nodes = 8
	delta_mat = [[0,1,1,1,1,1,1,1],[1,0,1,1,1,1,1,1],[1,1,0,1,1,1,1,1],[1,1,1,0,1,1,1,1],[1,1,1,1,0,1,1,1],[1,1,1,1,1,0,1,1],[1,1,1,1,1,1,0,1],[1,1,1,1,1,1,1,0]]
	num_ants = 1
	num_iterations = 10
	colors1 = "RRRRBBBB"

	graph1 = AntGraph(num_nodes,delta_mat,colors1)
	colony1 = AntColony(graph1,num_ants,num_iterations)

	
	ant1 = Ant(1, 1, colony1)

	print "testing reds_left initialization: " + str(ant1.reds_left)

	#Visited: 1,2,3
	ant1.currNode = 3 
	ant1.last_3_colors = ("R","R","R")
	self.reds_left = 1
Ejemplo n.º 10
0
# Made by - Pratik Luitel , Anish Dulal, Stuti Kafle
# available at - https://github.com/pratikluitel/ACOVisualization
# make a venv and install dependencies in requirements.txt before you proceed

import numpy as np

from ant_colony import AntColony

# making a random large city with 100 streets

large_distances = np.random.randint(1, 10, size=(100, 100))
large_distances = (large_distances + large_distances.T).astype('float64')
np.fill_diagonal(large_distances, float('inf'))

large_ant_colony = AntColony(large_distances, 10, 5, 50, 0.15, alpha=1, beta=1)
print(large_ant_colony.run())
Ejemplo n.º 11
0
import numpy as np

from ant_colony import AntColony

distances = np.array([[np.inf, 2, 2, 5, 7], [2, np.inf, 4, 8, 2],
                      [2, 4, np.inf, 1, 3], [5, 8, 1, np.inf, 2],
                      [7, 2, 3, 2, np.inf]])

ant_colony = AntColony(distances, 1, 1, 100, 0.95, alpha=1, beta=1)
shortest_path = ant_colony.run()
print("shorted_path: {}".format(shortest_path))
@author: Srijan
"""

import numpy as np
import pandas as pd
import warnings
from ant_colony import AntColony
warnings.filterwarnings('ignore')

tdata = pd.read_csv("train_new.csv")
y = tdata['mdd']
x = tdata.iloc[1:66, 1:66]
x = np.array(x)
#x=np.transpose(x)

ant_colony = AntColony(x, 50, 10, 100, 0.95, alpha=10, beta=5)
shortest_path = ant_colony.run()
s_path = shortest_path[0]
weight = shortest_path[1]

path = []

l = len(s_path)
l -= 2
print('Shortest Path: ', end='\t')
for i in range(l):
    if (i != l):
        print(s_path[i][1], end=' -> ')
        path.append('C' + str(s_path[i][1]))
print(s_path[l][1])
path.append('C' + str(s_path[l][1]))
Ejemplo n.º 13
0
# Made by - Pratik Luitel , Anish Dulal, Stuti Kafles
# available at - https://github.com/pratikluitel/ACOVisualization
# make a venv and install dependencies in requirements.txt before you proceed

import numpy as np

from ant_colony import AntColony

# making a city with 5 streets

small_distances = np.array([[np.inf, 2, 2, 5, 7, 4], [2, np.inf, 4, 8, 2, 3],
                            [2, 4, np.inf, 1, 3, 6], [5, 8, 1, np.inf, 2, 8],
                            [7, 2, 3, 2, np.inf, 1], [4, 3, 6, 8, 1, np.inf]])

small_ant_colony = AntColony(small_distances,
                             5,
                             2,
                             10,
                             0.95,
                             alpha=1,
                             beta=1,
                             graph=False)
small_ant_colony.run()
Ejemplo n.º 14
0
Archivo: main.py Proyecto: 2easy/ctsp
g_sol = greedy.solve()
print("GREEDY SOLUTION:\t\t\t"+str(g_sol)+" ---> " + str(greedy.cost))

# example usage of SimpleTabooSearch find solution at once
sts = SimpleTabooSearch(dists1)
sts_sol = sts.solve()
print("SIMPLE TABOO SEARCH SOLUTION:\t\t"+ str(sts_sol)+ " ---> "+ str(sts.cost))

san = SimulatedAnnealing(dists1,g_sol)
san_sol = san.solve()
print("GREEDY - SIMULATED ANNEALING SOLUTION:\t\t"+ str(san_sol)+ " ---> "+ str(san.cost))

san2 = SimulatedAnnealing(dists1,sts_sol)
san_sol2 = san2.solve()
print("SIMPLE TABOO - SIMULATED ANNEALING SOLUTION:\t\t"+ str(san_sol2)+ " ---> "+ str(san2.cost))

aco = AntColony(dists1,g_sol)
aco_sol = aco.solve()
print("ANT COLONY SOLUTION:\t\t"+ str(aco_sol)+ " ---> "+ str(aco.cost))
# example usage of SimpleTabooSearch step by step with access to intermediate values
#sts1 = SimpleTabooSearch(dists1)
#while sts1.step():
#    #print(str(sts1.i)+" step --best-->\t"+str(sts1.best))
#    print(str(sts1.i)+" step --current-->\t"+str(sts1.current))
#sts1_sol = sts1.solution
#print("SIMPLE TABOO SEARCH STEPbySTEP SOLUTION:\t\t"+ str(sts1_sol)+ " ---> "+ str(sts1.cost))

# example usage of Simulated Annealing find solution at once
#sa_sol = simulated_annealing.solve(dists1)
#print("SIMULATED ANNEALING SOLUTION:\t\t"+ str(sa_sol)+ " ---> "+ str(compute_cost(sa_sol, dists1)))
Ejemplo n.º 15
0
'''
Ant Colony Optimization 
stolen from: 
https://raw.githubusercontent.com/Akavall/AntColonyOptimization/master/ant_colony.py

'''
n_ants = 100
n_best = 25
n_iterations = 300
decay = 0.1

distCopy = distances.copy()
np.fill_diagonal(distCopy,np.inf)

colony = AntColony(distCopy, n_ants, n_best, n_iterations, decay, alpha=1.0, beta=1.5,coords=coords)

shortes_path = colony.run()


# only city indices
route = [s[1]-1 for s in shortes_path[0][:-1]]

# demands sorted by traveling route
demandRoute = demands[route]

# genetic algorithm
gA = GenAlgo(coords, demands, route, demandRoute, distances[1:,1:], depotDistances, vehicleCapacities, vehicleCosts)

routes = []
demandRoutes = []
        num_ants = 20
        num_iterations = 12
        num_repetitions = 1 # TODO: Increase number of repetitions?
    else:
        num_ants = 28 
        num_iterations = 30 # TODO: INCREASE THIS?
        num_repetitions = 3 # TODO: INCREASE THIS?

    try:
        graph = AntGraph(num_nodes, distances,colors) # construct the graph
                #EDIT
        best_path_vec = None 
        best_path_cost = sys.maxint # initialize cost to infinity
        for i in range(0, num_repetitions): # run multiple repetitions. Run multiple repetitions because each iteration is random.
            graph.reset_tau()  # reset trail level
            ant_colony = AntColony(graph, num_ants, num_iterations) # construct ant colony
            ant_colony.start()
            if ant_colony.best_path_cost < best_path_cost: # if we found a better path, take that path
                best_path_vec = ant_colony.best_path_vec
                best_path_cost = ant_colony.best_path_cost
        best_path_colors = [graph.get_color(node) for node in best_path_vec]


        print "\n------------------------------------------------------------"
        print "                     Results                                "
        print "------------------------------------------------------------"
        print "\nBest path = %s" % (best_path_vec,)
        print "\nBest path cost = %s\n" % (best_path_cost,)
        print "\nBest path colors = %s\n" % (best_path_colors,)
        print "\nBest Path, cost improvement", localSearch(graph,best_path_vec)        #Run local search on output of ant colonization 
        M = RandomStartLocalSearch(graph)                                           #Run random graph generator + Local Search
Ejemplo n.º 17
0
from ant_colony import AntColony

test_nodes = {
    0: (0, 7),
    1: (3, 9),
    2: (12, 4),
    3: (14, 11),
    4: (8, 11),
    5: (15, 6),
    6: (6, 15),
    7: (15, 9),
    8: (12, 10),
    9: (10, 7)
}


def distance(start, end):
    x_distance = abs(start[0] - end[0])
    y_distance = abs(start[1] - end[1])

    import math
    return math.sqrt(pow(x_distance, 2) + pow(y_distance, 2))


colony = AntColony(test_nodes, distance)

answer = colony.mainloop()
print(answer)
Ejemplo n.º 18
0
import numpy as np
from ant_colony import AntColony


#  формирование графа
graph = []
first_row = list(map(float, input().split()))
n = len(first_row)
graph.append(first_row)
for i in range(n - 1):
    row = list(map(float, input().split()))
    graph.append(row)

graph = np.array(graph)
for i in range(n):
    graph[i][i] = np.inf
	
# запуск муравьиного алгоритма
ant_colony = AntColony(graph, 20, 200, 0.9, alpha=2, beta=1)
shortest_path = ant_colony.main_func()

print(int(shortest_path[1]))  #  вывод длины наименьшего пути, найденного муравьями (shortest_path[0] - путь, shortest_path[1] - его длина)
Ejemplo n.º 19
0
from MapFileLoader import MapFileLoader
import time
import numpy as np
import sys
import argparse

if __name__ == '__main__':
    ants = 100
    iterations = 1
    p = 0.5
    Q = 2
    map_path = "map3.txt"
    mapfileloader = MapFileLoader(map_path)
    # Get the map
    Map = Map(mapfileloader)
    Colony = AntColony(Map, ants, iterations, p, Q)

    graph = MazeGraphSolver(mapfileloader)
    starttime = time.time()
    acopath = Colony.calculate_path()
    print(format(f"it took ACO {time.time()-starttime} sec to find a path"))
    starttime = time.time()
    print(acopath)

    optimalpath = graph.GetPath()
    print(
        format(
            f"it took Optimal graph find {time.time() - starttime} sec to find a path"
        ))

    SD = SolutionDrawing(Map.initial_node, Map.final_node, Map.occupancy_map)
        num_repetitions = 1  # TODO: Increase number of repetitions?
    else:
        num_ants = 28
        num_iterations = 30  # TODO: INCREASE THIS?
        num_repetitions = 3  # TODO: INCREASE THIS?

    try:
        graph = AntGraph(num_nodes, distances, colors)  # construct the graph
        #EDIT
        best_path_vec = None
        best_path_cost = sys.maxint  # initialize cost to infinity
        for i in range(
                0, num_repetitions
        ):  # run multiple repetitions. Run multiple repetitions because each iteration is random.
            graph.reset_tau()  # reset trail level
            ant_colony = AntColony(graph, num_ants,
                                   num_iterations)  # construct ant colony
            ant_colony.start()
            if ant_colony.best_path_cost < best_path_cost:  # if we found a better path, take that path
                best_path_vec = ant_colony.best_path_vec
                best_path_cost = ant_colony.best_path_cost
        best_path_colors = [graph.get_color(node) for node in best_path_vec]

        print "\n------------------------------------------------------------"
        print "                     Results                                "
        print "------------------------------------------------------------"
        print "\nBest path = %s" % (best_path_vec, )
        print "\nBest path cost = %s\n" % (best_path_cost, )
        print "\nBest path colors = %s\n" % (best_path_colors, )
        print "\nBest Path, cost improvement", localSearch(
            graph,
            best_path_vec)  #Run local search on output of ant colonization