Last active
December 16, 2015 15:49
-
-
Save schlamar/5458717 to your computer and use it in GitHub Desktop.
Deap function composition as alternative to eval lamba expression in lambdify.
This file contains 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
def _lookup(pos): | |
def composition(*args): | |
return args[pos] | |
return composition | |
def _apply(func, *funcs): | |
def composition(*args): | |
return func(*(f(*args) for f in funcs)) | |
return composition | |
def compose(expr, pset): | |
stack = [] | |
for node in expr: | |
stack.append((node, [])) | |
while len(stack[-1][1]) == stack[-1][0].arity: | |
prim, funcs = stack.pop() | |
if isinstance(prim, gp.Terminal): | |
func = _lookup(pset.arguments.index(prim.value)) | |
else: | |
func = _apply(expr.pset.context[prim.name], *funcs) | |
if len(stack) == 0: | |
break | |
stack[-1][1].append(func) | |
return func | |
def composeADF(expr): | |
adfdict = {} | |
func = None | |
for subexpr in reversed(expr): | |
subexpr.pset.context.update(adfdict) | |
func = compose(subexpr, subexpr.pset) | |
adfdict.update({subexpr.pset.__name__: func}) | |
return func |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment