Skip to content

Instantly share code, notes, and snippets.

@akiross
Last active August 29, 2015 14:17
Show Gist options
  • Save akiross/692c00c8f6c8ff6092dc to your computer and use it in GitHub Desktop.
Save akiross/692c00c8f6c8ff6092dc to your computer and use it in GitHub Desktop.
def generate_rec(pset, min_, max_, condition, type_=None):
'''This is a recursive generation function for STGP, which will
try to generate trees without giving errors for missing primitives.
Basically, if a primitive fails, it removes it from the
list of primitives and try again.'''
height = random.randint(min_, max_)
def _rec_gen(type_, depth, is_term):
if is_term:
try:
return [random.choice(pset.terminals[type_])]
except IndexError:
raise IndexError("Can't find a terminal of type {}".format(type_))
else:
# Build a set of functionals for this type
funcs = list(pset.primitives[type_])
# Decide once if children will be term (FIXME same value for all the children)
is_next_term = condition(height, depth)
while len(funcs):
try:
# Pick a random functional
func = random.choice(funcs)
except IndexError:
raise IndexError("Can't find a functional of type {}".format(type_))
try:
# Build a list for the functional and its children trees
res = [func]
for arg in reversed(func.args):
res.extend(_rec_gen(arg, depth + 1, is_next_term))
return res
except IndexError:
# Remove the functional from the set and try again
funcs.remove(func)
raise IndexError("Can't find a functional of type {}".format(type_))
return _rec_gen(type_, 0, condition(height, 0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment