def generate_random_exptree(self, depth): tree = ExpTree() d = 0 while (d < depth): # Make SHALLOW copy of leaves array: to_expand = [] for leaf in tree.leaves: to_expand.append(leaf) for leaf in to_expand: # Apply +c or *c possibly: r = random.random() if r < self.p_addc: tree.apply_plus_c(leaf) elif r < 2 * self.p_addc: tree.apply_times_c(leaf) # Otherwise, choose a unary or binary op: else: op = random.choice(self.all_ops); if op in ops.unary_ops: tree.apply_unary_op(leaf, op) else: tree.apply_binary_op(leaf, op) d += 1 return tree
def example_tree(): tree = ExpTree() leaf = tree.leaves[0] print("initial tree: " + str(tree)) leaf = tree.apply_times_c(leaf) print("expanded with apply_times_c(): " + str(tree)) leaf = tree.apply_plus_c(leaf) print("expanded with apply_plus_c(): " + str(tree)) left_leaf, right_leaf = tree.apply_binary_op(leaf, ops.mul) print("expanded with apply_binary_op(mul): " + str(tree)) tree.apply_unary_op(left_leaf, ops.sin) print("expanded left leaf with apply_unary_op(sin): " + str(tree)) tree.apply_unary_op(right_leaf, ops.log) print("expanded right leaf with apply_unary_op(log): " + str(tree)) expr = tree.to_expr() print("tree as sympy expression: " + str(expr)) print("number of leaves: " + str(len(tree.leaves))) print("constants: " + str(tree.constants))