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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
| import numpy as np import matplotlib.pyplot as plt import random from deap import creator, tools, base
creator.create('FitnessMin', base.Fitness, weights=(-1.0, 1.0)) creator.create('Individual', list, fitness=creator.FitnessMin)
gen_size = 54 toolbox = base.Toolbox() toolbox.register('Sequence', np.random.permutation, gen_size) toolbox.register('Individual', tools.initIterate, creator.Individual, toolbox.Sequence)
toolbox.register('Population', tools.initRepeat, list, toolbox.Individual)
nodeDict = {} with open("node.txt", 'r') as f: tmp = f.readlines() for t in tmp: t = t.split() nodeDict[t[0]] = list(map(int, t[1:]))
nodeLine = {} with open("line.txt", 'r') as f: tmp = f.readlines() for t in tmp: t = t.split() nodeLine[t[0]] = list(map(int, t[1:]))
edgeTime = {} with open("time.txt", 'r') as f: tmp = f.readlines() for t in tmp: t = t.split() edgeTime[t[0]+t[1]] = float(t[2]) edgeTime[t[1]+t[0]] = float(t[2])
edgeCost = {} with open("dis.txt", 'r') as f: tmp = f.readlines() for t in tmp: t = t.split() edgeCost[t[0]+t[1]] = float(t[2]) edgeCost[t[1]+t[0]] = float(t[2])
T = 5
def dfs(ind, source, target): path = [] visited = [] stack = [source] lens = [] while stack: cur = stack[-1] if cur not in visited: path.append(cur) visited.append(cur) allow = np.array(nodeDict[str(cur)]) priority_ls = np.asarray(ind)[np.asarray(allow)-1] index = np.argsort(priority_ls) stack.extend(allow[index]) lens.append(len(allow[index])) if target in stack: path.append(target) break else: stack.pop() lens[-1] -= 1 if lens[-1] == 0: lens.pop() path.pop() return path
def eval(ind): path = dfs(ind, source, target) time = TIME(path) cost = COST(path) return (time), (cost)
def TIME(path): time = edgeTime[str(path[0])+str(path[1])] if len(path) > 2: pre = set(nodeLine[str(path[0])]) & set( nodeLine[str(path[1])]) & set(nodeLine[str(path[2])]) time += edgeTime[str(path[1])+str(path[2])] for i in range(2, len(path)-1): time += edgeTime[str(path[i])+str(path[i+1])] now = set(nodeLine[str(path[i])]) & set(nodeLine[str(path[i+1])]) if not pre & now: pre = now time += T return time
def COST(path): dis = 0 for i in range(len(path)-1): dis += edgeCost[str(path[i])+str(path[i+1])] price = [2, 3, 4, 5, 6, 7] rank = [6, 11, 17, 24, 32] rank.append(dis) rank.sort() cost = price[rank.index(dis)] return cost
for source in [54]: for target in range(53, 54): if target == source: continue toolbox.register('evaluate', eval) toolbox.register('select', tools.selTournament, tournsize=2) toolbox.register('mate', tools.cxOrdered) toolbox.register('mutate', tools.mutShuffleIndexes, indpb=0.5) stats = tools.Statistics(key=lambda ind: ind.fitness.values) stats.register('avg', np.mean) stats.register('std', np.std) stats.register('min', np.min) stats.register('max', np.max) logbook = tools.Logbook() logbook.header = 'gen', 'avg', 'std', 'min', 'max'
pop_size = 100 N_GEN = 20 CXPB = 0.8 MUTPB = 0.2
pop = toolbox.Population(n=pop_size) invalid_ind = [ind for ind in pop if not ind.fitness.valid] fitnesses = list(map(toolbox.evaluate, invalid_ind)) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit record = stats.compile(pop) logbook.record(gen=0, **record) for gen in range(1+N_GEN): selectTour = toolbox.select(pop, pop_size) selectInd = list(map(toolbox.clone, selectTour)) for child1, child2 in zip(selectInd[::2], selectInd[1::2]): if random.random() < CXPB: toolbox.mate(child1, child2) del child1.fitness.values del child2.fitness.values for ind in selectInd: if random.random() < MUTPB: toolbox.mutate(ind) del ind.fitness.values invalid_ind = [ind for ind in selectInd if not ind.fitness.valid] fitnesses = list(map(toolbox.evaluate, invalid_ind)) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit combinedPop = pop + selectInd pop = tools.selBest(combinedPop, pop_size) record = stats.compile(pop) logbook.record(gen=gen, **record) print(logbook) bestInd = tools.selBest(pop, 1)[0] bestFit = bestInd.fitness.values print(f'{source} to {target}') print('最短耗时为:', bestFit[0]) print('对应费用为:', bestFit[1]) print('对应路径为:', dfs(bestInd, source, target))
min = logbook.select('min') avg = logbook.select('avg') gen = logbook.select('gen') plt.plot(gen, min, 'b-', label='MIN_FITNESS') plt.plot(gen, avg, 'r-', label='AVG_FITNESS') plt.xlabel('gen') plt.ylabel('fitness') plt.legend(loc='best') plt.tight_layout() plt.show()
|