/
main.py
181 lines (129 loc) · 5.68 KB
/
main.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
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
from character import heroes, villains, shared_comics, VillainTeam, HeroTeam
import multiprocessing
import array
import random
import sys
from deap import algorithms
from deap import base
from deap import creator
from deap import tools
cache_teams = {}
def convertChromosomeToHeroTeam(chromosome):
heroIds = tuple(set(chromosome))
if heroIds not in cache_teams:
cache_teams[heroIds] = HeroTeam(heroIds)
return cache_teams[heroIds]
# This function is the evaluation function, we want
def fitness(chsTeam):
team = convertChromosomeToHeroTeam(chsTeam)
score = team.getCollaboration(oppositeTeam=villain_team)
numBeats = team.numBeats(villain_team)
score += 1000 * numBeats
if team.getCost() <= BUDGET :
score *= 10
return max(0,score),
def cxTeam(ind1, ind2):
size = min(len(ind1), len(ind2))
numSwitches = random.randint(1, size-1)
for i in xrange(numSwitches):
cxpoint1 = random.randint(0, size - 1)
cxpoint2 = random.randint(0, size - 1)
ind1[cxpoint1], ind2[cxpoint1] = ind2[cxpoint2], ind1[cxpoint2]
return ind1, ind2
def mutTeam(ind):
size = len(ind)
for i in xrange(size):
if random.random() < 1.0 / size:
ind[i] = random.choice(heroes.keys())
return ind,
def selectTeams(individuals, k):
return tools.selTournament(individuals, int(0.95*len(individuals)), tournsize=4) + \
tools.selWorst(individuals, int(0.05*len(individuals)))
def printBestTeamStats(bestTeam):
print 'Team Size:', bestTeam.size(), ' Villain Team Size:', villain_team.size()
print 'BeatsTeam?',bestTeam.beatsTeam(villain_team), 'UnderBudget?',bestTeam.getCost() <= BUDGET
print 'Power Grids:', bestTeam.getPowerGrid(), villain_team.getPowerGrid()
print 'Collaboration:', bestTeam.getCollaboration(oppositeTeam=villain_team, pprint=True)
print 'Cost:', bestTeam.getCost(), ' BUDGET:', BUDGET
print bestTeam, ' vs ', villain_team
if __name__ == '__main__':
if len(sys.argv) > 1:
entryFile = sys.argv[1]
else:
entryFile = 'Villan Teams/V12_763.txt'
with open(entryFile, 'r') as f:
villains_team_ids= [int(x) for x in f.read().split(' ')]
villain_team = VillainTeam(villains_team_ids)
BUDGET = villain_team.calculateBudget()
IND_SIZE = villain_team.size()
CXPB, MUTPB, NGEN, NPOP, MAXGENNOCHANGE = 0.7, 0.2, 1000, 500, 100
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", array.array, typecode='i', fitness=creator.FitnessMax)
toolbox = base.Toolbox()
toolbox.register("indices", random.sample, heroes.keys(), IND_SIZE)
toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.indices)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("mate", cxTeam)
toolbox.register("mutate", mutTeam)
#toolbox.register("select", selectTeams)
toolbox.register("select", tools.selTournament, tournsize=4)
toolbox.register("evaluate", fitness)
pop = toolbox.population(n=NPOP)
hof = tools.HallOfFame(2)
pool = multiprocessing.Pool(IND_SIZE)
print("Start of evolution")
# Evaluate the entire population
fitnesses = list(pool.map(toolbox.evaluate, pop))
for ind, fit in zip(pop, fitnesses):
ind.fitness.values = fit
print(" Evaluated %i individuals" % len(pop))
hof.update(pop)
best_collab = 0
best_ever = convertChromosomeToHeroTeam(hof[0])
best_not_change = 0
# Begin the evolution
for g in range(NGEN):
# Select the next generation individuals
offspring = toolbox.select(pop, len(pop))
# Clone the selected individuals
offspring = list(pool.map(toolbox.clone, offspring))
# Apply crossover and mutation on the offspring
for child1, child2 in zip(offspring[::2], offspring[1::2]):
if random.random() < CXPB:
toolbox.mate(child1, child2)
del child1.fitness.values,
del child2.fitness.values
for mutant in offspring:
if random.random() < MUTPB:
toolbox.mutate(mutant)
del mutant.fitness.values
# Evaluate the individuals with an invalid fitness
invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
fitnesses = pool.map(toolbox.evaluate, invalid_ind)
for ind, fit in zip(invalid_ind, fitnesses):
ind.fitness.values = fit
#print(" Evaluated %i individuals" % len(invalid_ind))
# The population is entirely replaced by the offspring
pop[:] = offspring
# Gather all the fitnesses in one list and print the stats
fits = [ind.fitness.values[0] for ind in pop]
hof.update(pop)
best_ind = hof[0]#tools.selBest(pop, 1)[0]
bestTeam = convertChromosomeToHeroTeam(best_ind)
collab = bestTeam.getCollaboration(oppositeTeam=villain_team)
cost = bestTeam.getCost()
beats = bestTeam.beatsTeam(villain_team)
if beats and cost < BUDGET and collab > best_collab:
best_ever = bestTeam
best_not_change = 0
best_collab = collab
else:
best_not_change +=1
if best_not_change > MAXGENNOCHANGE:
break
if g%10 == 0:
print "-- Generation %i (%s)-- MAX:%i" % (g, len(pop), collab)
print("-- End of (successful) evolution --")
#best_ind = tools.selBest(pop, 1)[0]
#print("Best individual is %s, %s" % (best_ind, best_ind.fitness.values))
printBestTeamStats(best_ever)