Last active
August 29, 2015 13:57
-
-
Save macrintr/9877164 to your computer and use it in GitHub Desktop.
Updating from_string method in DEAP gp.py PrimitiveTree class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
File name: gp_from_string_fix.py | |
Author: Thomas Macrina | |
Date created: 03/21/2014 | |
Python Version: 2.7 | |
Overwriting the from_string() method within DEAP's gp.py | |
to properly function with a strongly-typed primitive set. | |
line 30 corresponds to line 100 in gp.py v1.0.0 | |
""" | |
import random | |
import sys | |
import re | |
from collections import defaultdict, deque | |
from functools import partial,wraps | |
from inspect import isclass | |
from operator import eq, lt | |
from deap.gp import PrimitiveTree, Primitive, Terminal | |
# Define the name of type for any types. | |
__type__ = object | |
###################################### | |
# GP Data structure # | |
###################################### | |
def from_string(string, pset): | |
"""Try to convert a string expression into a PrimitiveTree given a | |
PrimitiveSet *pset*. The primitive set needs to contain every primitive | |
present in the expression. | |
:param string: String representation of a Python expression. | |
:param pset: Primitive set from which primitives are selected. | |
:returns: PrimitiveTree populated with the deserialized primitives. | |
""" | |
tokens = re.split("[ \t\n\r\f\v(),]", string) | |
expr = [] | |
ret_types = deque() | |
for token in tokens: | |
if token == '': | |
continue | |
if len(ret_types) != 0: | |
# type_ = ret_types.popleft() | |
type_ = ret_types.pop() # no need to work from left to right | |
else: | |
type_ = None | |
if token in pset.mapping: | |
primitive = pset.mapping[token] | |
if len(ret_types) != 0 and primitive.ret != type_: | |
raise TypeError("Primitive {} return type {} does not " | |
"match the expected one: {}." | |
.format(primitive, primitive.ret, type_)) | |
expr.append(primitive) | |
if isinstance(primitive, Primitive): | |
# ret_types.extendleft(primitive.args) | |
ret_types.extend(reversed(primitive.args)) # give me that array in reverse | |
else: | |
try: | |
token = eval(token) | |
except NameError: | |
raise TypeError("Unable to evaluate terminal: {}.".format(token)) | |
if type_ is None: | |
type_ = type(token) | |
# if type(token) != type_: | |
if not issubclass(type_, type(token)): # allow for terminals that subclass built-in types | |
raise TypeError("Terminal {} type {} does not " | |
"match the expected one: {}." | |
.format(token, type(token), type_)) | |
expr.append(Terminal(token, False, type_)) | |
return PrimitiveTree(expr) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment