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/>.
23
from eap import creator
24
from eap import toolbox
26
from eap import algorithms
27
from eap import halloffame
29
# Define new functions
30
def safeDiv(left, right):
33
except ZeroDivisionError:
36
pset = gp.PrimitiveSet("MAIN", 1)
37
pset.addPrimitive(operator.add, 2)
38
pset.addPrimitive(operator.sub, 2)
39
pset.addPrimitive(operator.mul, 2)
40
pset.addPrimitive(safeDiv, 2)
41
pset.addPrimitive(operator.neg, 1)
42
pset.addPrimitive(math.cos, 1)
43
pset.addPrimitive(math.sin, 1)
44
pset.addEphemeralConstant(lambda: random.randint(-1,1))
45
pset.renameArguments({"ARG0" : "x"})
47
creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
48
creator.create("Individual", gp.PrimitiveTree, fitness=creator.FitnessMin, pset=pset)
50
tools = toolbox.Toolbox()
51
tools.register("expr", gp.generateRamped, pset=pset, min_=1, max_=2)
52
tools.register("individual", creator.Individual, content_init=tools.expr)
54
tools.register("population", list, content_init=tools.individual, size_init=100)
55
tools.register("lambdify", gp.lambdify, pset=pset)
57
def evalSymbReg(individual):
58
# Transform the tree expression in a callable function
59
func = tools.lambdify(expr=individual)
60
# Evaluate the sum of squared difference between the expression
61
# and the real function : x**4 + x**3 + x**2 + x
62
values = (x/10. for x in xrange(-10,10))
63
diff_func = lambda x: (func(x)-(x**4 + x**3 + x**2 + x))**2
64
diff = sum(map(diff_func, values))
67
tools.register("evaluate", evalSymbReg)
68
tools.register("select", toolbox.selTournament, tournsize=3)
69
tools.register("mate", toolbox.cxTreeUniformOnePoint)
70
tools.register("expr_mut", gp.generateFull, min_=0, max_=2)
71
tools.register('mutate', toolbox.mutTreeUniform, expr=tools.expr_mut)
73
if __name__ == "__main__":
76
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
78
pop = tools.population()
79
hof = halloffame.HallOfFame(1)
81
algorithms.eaSimple(tools, pop, 0.5, 0.1, 40, halloffame=hof)
82
logging.info("Best individual is %s, %s", gp.evaluate(hof[0]), hof[0].fitness)