1from deap_er import creator
2from deap_er import tools
3from deap_er import base
4import random
5import numpy
6import array
7
8
9random.seed(1234) # disables randomization
10
11IND_SIZE = 30
12MIN_VALUE = 4
13MAX_VALUE = 5
14MIN_STRATEGY = 0.5
15MAX_STRATEGY = 3
16
17
18def gen_evo_strat(icls, scls):
19 ind = icls(random.uniform(MIN_VALUE, MAX_VALUE) for _ in range(IND_SIZE))
20 ind.strategy = scls(random.uniform(MIN_STRATEGY, MAX_STRATEGY) for _ in range(IND_SIZE))
21 return ind
22
23
24def check_strategy(strat):
25 def wrapper(func):
26 def wrapped(*args, **kwargs):
27 children = func(*args, **kwargs)
28 for child in children:
29 for i, s in enumerate(child.strategy):
30 if s < strat:
31 child.strategy[i] = strat
32 return children
33 return wrapped
34 return wrapper
35
36
37def setup():
38 creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
39 creator.create("Individual", array.array, typecode="d", fitness=creator.FitnessMin, strategy=None)
40 creator.create("Strategy", array.array, typecode="d")
41
42 toolbox = base.Toolbox()
43 toolbox.register("individual", gen_evo_strat, creator.Individual, creator.Strategy)
44 toolbox.register("population", tools.init_repeat, list, toolbox.individual)
45 toolbox.register("mate", tools.cx_es_blend, alpha=0.1)
46 toolbox.register("mutate", tools.mut_es_log_normal, learn_rate=1.0, mut_prob=0.03)
47 toolbox.register("select", tools.sel_tournament, contestants=3)
48 toolbox.register("evaluate", tools.bm_sphere)
49 toolbox.decorate("mate", check_strategy(MIN_STRATEGY))
50 toolbox.decorate("mutate", check_strategy(MIN_STRATEGY))
51
52 stats = tools.Statistics(lambda ind: ind.fitness.values)
53 stats.register("avg", numpy.mean)
54 stats.register("std", numpy.std)
55 stats.register("min", numpy.min)
56 stats.register("max", numpy.max)
57
58 return toolbox, stats
59
60
61def print_results(best_ind):
62 if not best_ind.fitness.values < (0.5,):
63 raise RuntimeError('Evolution failed to converge.')
64 print(f'\nEvolution converged correctly.')
65
66
67def main():
68 toolbox, stats = setup()
69 pop = toolbox.population(size=100)
70 hof = tools.HallOfFame(1)
71 args = dict(
72 toolbox=toolbox,
73 population=pop,
74 generations=500,
75 offsprings=100,
76 survivors=10,
77 cx_prob=0.6,
78 mut_prob=0.3,
79 hof=hof,
80 stats=stats,
81 verbose=True # prints stats
82 )
83 tools.ea_mu_comma_lambda(**args)
84 print_results(hof[0])
85
86
87if __name__ == "__main__":
88 main()