How to use python classes in GP module?

89 views
Skip to first unread message

Sergey Sosnin

unread,
Oct 2, 2014, 11:12:18 AM10/2/14
to deap-...@googlegroups.com
Hi everyone,

The question is how to correctly works with custom types in GP module?
I have the code below:

pset = gp.PrimitiveSet("main", 0)
pset.addPrimitive(split,2,name="split")
pset.addEphemeralConstant("atom",lambda : random.choice(atom_set))
pset.addEphemeralConstant("nums",lambda : random.randint(0,4))

random.choice(atom_set) returns string.
But if I try to use a custom class, I face an error.

pset = gp.PrimitiveSet("main", 0)
pset.addPrimitive(split,2,name="split")
pset.addEphemeralConstant("atom",lambda : Atom(random.choice(atom_set)))
pset.addEphemeralConstant("nums",lambda : random.randint(0,4))

split(split(split(<__main__.Atom instance at 0x000000000DAF86C8>, 1)....

SyntaxError: invalid syntax
It seems as all arguments of functions were converted to strings. How to avoid that? How to use types in GP  module?

Félix-Antoine Fortin

unread,
Oct 10, 2014, 9:51:17 AM10/10/14
to deap
Hi Sergey,

Our in-house expert in GP is currently fiddling with the problem, we will try to find a solution soon.

The problem is the following. In order to compile the PrimitiveTree in executable Python code, we first convert the tree in a string of code. This string is then passed to the Python compiler which returns an executable function. However, in order to do the conversion, we suppose that every object has a string representation that can be used to recreate the object.

The problem can be circumvent with Terminals by specifying a name (http://deap.readthedocs.org/en/master/api/gp.html#deap.gp.PrimitiveSet.addTerminal). However the name logic has yet been extended to Ephemeral Constant, since until today with have always dealt with Ephemeral Constant that can be recreated using their string representation.

Until we find a general solution, the problem could be avoided if you can define a __repr__ function for the Atom type that would return the appropriate Python code to reconstruct the object, for example "Atom('Fe')".

Hope this helps,
Félix-Antoine

Félix-Antoine Fortin

--
You received this message because you are subscribed to the Google Groups "deap-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to deap-users+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages