/
main.py
234 lines (171 loc) · 6.73 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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import random
from deap import base
from deap import creator
from deap import tools
from math import sin
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
toolbox = base.Toolbox()
# Attribute generator
toolbox.register("attr", random.randint, -5, 10)
# Structure initializers
toolbox.register("individual", tools.initRepeat, creator.Individual,
toolbox.attr, 3)
# define the population to be a list of individuals
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
def feasible(individual):
"""Feasibility function for the individual. Returns True if feasible False
otherwise."""
if -3 < individual[0] < 9 and individual[1] > 0 and individual[2] != 0:
return True
return False
#PenAdapt = 3
# fitness function
#def evalFct(individual):
"""Evaluation function for the individual."""
#x1 = individual[0]
#x2 = individual[1]
#x3 = individual[2]
#if feasible(individual):
# return (x1 - 25)**2 * sin(x2) * (x3/3),
#else:
# return ((x1 - 25)**2 * sin(x2) * (x3/3))/PenAdapt,
# ----------
# Operator registration
# ----------
# register the goal / fitness function
#toolbox.register("evaluate", evalFct)
# register the crossover operator
toolbox.register("mate", tools.cxTwoPoint)
# register a mutation operator with a probability to
# flip each attribute/gene of 0.05
toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
# operator for selecting individuals for breeding the next
# generation: each individual of the current generation
# is replaced by the 'fittest' (best) of three individuals
# drawn randomly from the current generation.
toolbox.register("select", tools.selTournament, tournsize=3)
# ----------
def main(CrossoverP, MutationP, PenAdapt):
random.seed(64)
# create an initial population of 300 individuals (where
# each individual is a list of integers)
pop = toolbox.population(n=10)
# CXPB is the probability with which two individuals
# are crossed
#
# MUTPB is the probability for mutating an individual
CXPB = CrossoverP
MUTPB = MutationP
def evalFct(individual, adaptiveP):
"""Evaluation function for the individual."""
x1 = individual[0]
x2 = individual[1]
x3 = individual[2]
if feasible(individual):
return (x1 - 25) ** 2 * sin(x2) * (x3 / 3),
else:
#
return ((x1 - 25) ** 2 * sin(x2) * (x3 / 3)) / adaptiveP,
toolbox.register("evaluate", evalFct, adaptiveP = PenAdapt)
print("Start of evolution")
# Evaluate the entire population ---WIP---
fitnesses = list(map(toolbox.evaluate, pop))
for ind, fit in zip(pop, fitnesses):
ind.fitness.values = fit
#print(ind.fitness.values)
print(" Evaluated %i individuals" % len(pop))
# Extracting all the fitnesses of
fits = [ind.fitness.values[0] for ind in pop]
# Variable keeping track of the number of generations
g = 0
comptDim = 0
comptAug = 0
comptDiv = 0
# Begin the evolution
while g < 100:
# A new generation
g = g + 1
print("-- Generation %i --" % g)
#print(pop)
i = 0
for inf in pop:
if feasible(inf) is False:
#print(inf)
i = i+1
print(" incompatibles: %s" % i)
# Select the next generation individuals
offspring = toolbox.select(pop, len(pop))
# Clone the selected individuals
offspring = list(map(toolbox.clone, offspring))
# Apply crossover and mutation on the offspring
for child1, child2 in zip(offspring[::2], offspring[1::2]):
# cross two individuals with probability CXPB
if random.random() < CXPB:
toolbox.mate(child1, child2)
# fitness values of the children
# must be recalculated later
del child1.fitness.values
del child2.fitness.values
for mutant in offspring:
# mutate an individual with probability MUTPB
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 = 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]
length = len(pop)
mean = sum(fits) / length
#sum2 = sum(x * x for x in fits)
#std = abs(sum2 / length - mean ** 2) ** 0.5
i = 0
BestOne = tools.selBest(pop, 5)
print(" Min %s" % min(fits))
print(" Max %s" % max(fits))
print(" Avg %s" % mean)
#print(" Std %s" % std)
print(" Best 3 solutions %s" % BestOne)
# si les 3 best sont faisables
if all(feasible(i) for i in BestOne):
PenAdapt = PenAdapt/12
print(" Pénalité diminuée ! %s" % PenAdapt)
comptDim = comptDim + 1
# si les 3 best sont infaisables
elif not any(feasible(i) for i in BestOne):
PenAdapt = PenAdapt * 2
print(" Pénalité augmentée! %s" % PenAdapt)
comptAug = comptAug + 1
# si il y a de la diversité
else:
print(" Aucun changement de pénalité ! %s" % PenAdapt)
comptDiv = comptDiv + 1
# fitness function avec pénalité adaptative
def adaptiveEval(individual, adaptiveP):
x1 = individual[0]
x2 = individual[1]
x3 = individual[2]
if feasible(individual):
return (x1 - 25) ** 2 * sin(x2) * (x3 / 3),
else:
#
return ((x1 - 25) ** 2 * sin(x2) * (x3 / 3)) / adaptiveP,
toolbox.register("evaluate", adaptiveEval, adaptiveP = PenAdapt)
print("-- End of evolution --")
best_ind = tools.selBest(pop, 1)[0]
worst_ind = tools.selWorst(pop, 1)[0]
print(" Pénalité augmentée %s fois" % comptAug)
print(" Pénalité diminuée %s fois" % comptDim)
print(" Pénalité non changée %s fois" % comptDiv)
print(" Pénalité %s" % PenAdapt)
print("Best individual is %s, %s" % (best_ind, best_ind.fitness.values))
print("Worst individual is %s, %s" % (worst_ind, worst_ind.fitness.values))
if __name__ == "__main__":
main(0.5, 0.1, 9)