1
# This file is part of EAP.
3
# EAP is free software: you can redistribute it and/or modify
4
# it under the terms of the GNU Lesser General Public License as
5
# published by the Free Software Foundation, either version 3 of
6
# the License, or (at your option) any later version.
8
# EAP is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU Lesser General Public License for more details.
13
# You should have received a copy of the GNU Lesser General Public
14
# License along with EAP. If not, see <http://www.gnu.org/licenses/>.
21
from deap import benchmarks
22
from deap import creator
23
from deap import tools
28
creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
29
creator.create("Individual", array.array, typecode='d', fitness=creator.FitnessMin)
31
def mutDE(y, a, b, c, f):
33
for i in range(len(y)):
34
y[i] = a[i] + f*(b[i]-c[i])
37
def cxBinomial(x, y, cr):
39
index = random.randrange(size)
41
if i == index or random.random() < cr:
45
def cxExponential(x, y, cr):
47
index = random.randrange(size)
48
# Loop on the indices index -> end, then on 0 -> index
49
for i in range(index, size) + range(0, index):
51
if random.random() < cr:
55
toolbox = base.Toolbox()
56
toolbox.register("attr_float", random.uniform, -3, 3)
57
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, NDIM)
58
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
59
toolbox.register("mutate", mutDE, f=0.8)
60
toolbox.register("mate", cxExponential, cr=0.8)
61
toolbox.register("select", tools.selRandom, k=3)
62
toolbox.register("evaluate", benchmarks.griewank)
65
# Differential evolution parameters
69
pop = toolbox.population(n=MU);
70
hof = tools.HallOfFame(1)
71
stats = tools.Statistics(lambda ind: ind.fitness.values)
72
stats.register("Avg", tools.mean)
73
stats.register("Std", tools.std)
74
stats.register("Min", min)
75
stats.register("Max", max)
77
# Evaluate the individuals
78
fitnesses = toolbox.map(toolbox.evaluate, pop)
79
for ind, fit in zip(pop, fitnesses):
80
ind.fitness.values = fit
85
# We must clone everything to ensure independance
86
a, b, c = [toolbox.clone(ind) for ind in toolbox.select(pop)]
87
x = toolbox.clone(agent)
88
y = toolbox.clone(agent)
89
y = toolbox.mutate(y, a, b, c)
90
z = toolbox.mate(x, y)
94
fitnesses = toolbox.map(toolbox.evaluate, children)
95
for ind, fit, i in zip(children, fitnesses, range(len(fitnesses))):
96
ind.fitness.values = fit
97
if ind.fitness > pop[i].fitness:
103
print "-- Generation %i --" % g
106
print "Best individual is ", hof[0]
107
print "with fitness", hof[0].fitness.values[0]
109
if __name__ == "__main__":