i want to model an equation as a tree in python. for example:
x = exp(((-0.5)*((f/sqrt(d))**2)))
how do i do this? i want to be able to switch tree branches, delete parts of the tree etc, and then convert it back into a new equation in text form.
can you give me example code/ Libraries that can do this?
cheers edit 1:
I have come this far now:
import compiler
import pprint
import parser
import ast
class Py2Neko(ast.NodeTransformer):
def generic_visit(self, node):
print type(node).__name__
ast.NodeVisitor.generic_visit(self, node)
def visit_Name(self, node):
print 'Name :', node.id
def visit_Num(self, node):
print 'Num :', node.__dict__['n']
def visit_Str(self, node):
print "Str :", node.s
def visit_Print(self, node):
print "Print :"
ast.NodeVisitor.generic_visit(self, node)
def visit_Assign(self, node):
print "Assign :"
ast.NodeVisitor.generic_visit(self, node)
def visit_Expr(self, node):
print "Expr :"
ast.NodeVisitor.generic_visit(self, node)
if __name__ == '__main__':
node = ast.parse("res= exp(((-0.5*one)*((delta_w*one/delta*one)**2)))")
# print ast.dump(node)
v = Py2Neko()
v.visit(node)
Now it prints all nodes of the tree. However i want to be able to switch branches, delete branches, insert branches and change operators/operands. I need this because i want to be able to mutate the tree randomly.