1#    This file is part of DEAP.
2#
3#    DEAP 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.
7#
8#    DEAP 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.
12#
13#    You should have received a copy of the GNU Lesser General Public
14#    License along with DEAP. If not, see <http://www.gnu.org/licenses/>.
15
16import array
17import random
18
19import numpy
20
21from deap import algorithms
22from deap import base
23from deap import creator
24from deap import tools
25
26creator.create("FitnessMax", base.Fitness, weights=(1.0,))
27creator.create("Individual", array.array, typecode='b', fitness=creator.FitnessMax)
28
29toolbox = base.Toolbox()
30
31# Attribute generator
32toolbox.register("attr_bool", random.randint, 0, 1)
33
34# Structure initializers
35toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, 100)
36toolbox.register("population", tools.initRepeat, list, toolbox.individual)
37
38def evalOneMax(individual):
39    return sum(individual),
40
41toolbox.register("evaluate", evalOneMax)
42toolbox.register("mate", tools.cxTwoPoint)
43toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
44toolbox.register("select", tools.selTournament, tournsize=3)
45
46def main():
47    random.seed(64)
48
49    pop = toolbox.population(n=300)
50    hof = tools.HallOfFame(1)
51    stats = tools.Statistics(lambda ind: ind.fitness.values)
52    stats.register("avg", numpy.mean)
53    stats.register("std", numpy.std)
54    stats.register("min", numpy.min)
55    stats.register("max", numpy.max)
56
57    pop, log = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=40,
58                                   stats=stats, halloffame=hof, verbose=True)
59
60    return pop, log, hof
61
62if __name__ == "__main__":
63    main()
64