-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTSP_paralelo_multiprocessing.py
100 lines (86 loc) · 3.43 KB
/
TSP_paralelo_multiprocessing.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import random
import json
import numpy
import time
import multiprocessing
import matplotlib.pyplot as plt
from deap import algorithms
from deap import base
from deap import creator
from deap import tools
#from scoop import futures
# gr*.json contiene el mapa de distancias entre ciudades en formato JSON
with open("gr17.json", "r") as tsp_data:
tsp = json.load(tsp_data)
# matriz de distancia
distance_map = tsp["DistanceMatrix"]
# número de ciudades que visitar
IND_SIZE = tsp["TourSize"]
# Creamos los objetos para definir el problema y el tipo de individuo
creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
creator.create("Individual", list, fitness=creator.FitnessMin)
toolbox = base.Toolbox()
# Generación de un tour aleatorio
toolbox.register("indices", random.sample, range(IND_SIZE), IND_SIZE)
# Generación de inviduos y población
toolbox.register("individual", tools.initIterate, creator.Individual,
toolbox.indices)
toolbox.register("population", tools.initRepeat, list,
toolbox.individual, 100)
def evalTSP(individual):
""" Función objetivo, calcula la distancia que recorre el viajante"""
# distancia entre el último elemento y el primero
distance = distance_map[individual[-1]][individual[0]]
# distancia entre el resto de ciudades
for gene1, gene2 in zip(individual[0:-1], individual[1:]):
distance += distance_map[gene1][gene2]
time.sleep(0.001) # retraso añadido
return distance,
# registro de operaciones genéticas
toolbox.register("mate", tools.cxOrdered)
toolbox.register("mutate", tools.mutShuffleIndexes, indpb=0.05)
toolbox.register("select", tools.selTournament, tournsize=3)
toolbox.register("evaluate", evalTSP)
def plot_evolucion(log):
gen = log.select("gen")
fit_mins = log.select("min")
fit_maxs = log.select("max")
fit_ave = log.select("avg")
fig, ax1 = plt.subplots()
ax1.plot(gen, fit_mins, "b")
ax1.plot(gen, fit_maxs, "r")
ax1.plot(gen, fit_ave, "--k")
ax1.fill_between(gen, fit_mins, fit_maxs,
where=fit_maxs >= fit_mins,
facecolor="g", alpha=0.2)
ax1.set_xlabel("Generación")
ax1.set_ylabel("Fitness")
ax1.legend(["Min", "Max", "Avg"])
ax1.set_ylim([2000, 6000])
plt.grid(True)
plt.savefig("EvolucionTSP.eps", dpi=300)
def main():
random.seed(100)
CXPB, MUTPB, NGEN = 0.7, 0.3, 120
pop = toolbox.population()
MU, LAMBDA = len(pop), len(pop)
hof = tools.HallOfFame(1)
stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register("avg", numpy.mean)
stats.register("std", numpy.std)
stats.register("min", numpy.min)
stats.register("max", numpy.max)
logbook = tools.Logbook()
pop, logbook = algorithms.eaMuPlusLambda(pop, toolbox, MU,
LAMBDA, CXPB, MUTPB,
NGEN, stats=stats,
halloffame=hof,
verbose=False)
return hof, logbook
if __name__ == "__main__":
t1 = time.time()
pool = multiprocessing.Pool(processes=4)
toolbox.register("map", pool.map)
best, log = main()
t2 = time.time()
print("Tiempo de ejecución %f" %(t2-t1))