Skip to content

Instantly share code, notes, and snippets.

@schlamar
Last active December 16, 2015 15:49
Show Gist options
  • Save schlamar/5458717 to your computer and use it in GitHub Desktop.
Save schlamar/5458717 to your computer and use it in GitHub Desktop.
Deap function composition as alternative to eval lamba expression in lambdify.
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