0

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.

tarrasch
  • 2,630
  • 8
  • 37
  • 61

3 Answers3

1

Operators and functions are parent nodes, and operands are the leaves.

x = exp(((-0.5)*((f/sqrt(d))**2)))

Start with a top-down approach: [ operator { operand1, operand2 }]

[ = { x, exp(((-0.5)*((f/sqrt(d))**2))) }]

followed by:

[ = { x, [ * { exp(((-0.5), ((f/sqrt(d))**2))) }] }]

then:

[ = { x, [ * { [ exp { -0.5 }],  [ ** { f/sqrt(d)), 2 }] }] }]

You get the idea.

This link might be your answer.

Community
  • 1
  • 1
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • the link was pretty good. it brought me to ast.nodevisitor. If you can tell me how i can swap two branches of the tree or insert/delete branches, then thats an answer. – tarrasch Jun 16 '11 at 11:20
  • Standard operations on any tree data structures. I'd recommend reading about trees. – duffymo Jun 16 '11 at 13:37
  • i will just ask another answer, since the question has deviated. – tarrasch Jun 17 '11 at 08:41
0

PyParsing should be able to help you. (I'm assuming your equation might not necessarily be using the Python syntax itself, strictly speaking.)

Bruno
  • 119,590
  • 31
  • 270
  • 376
0

What you want is to build and work with parse trees. Aside from the built-in parsing, if your equations go outside python's native syntax, take a look at this overview, which may be dated. Lots of options there.

Pontus Gagge
  • 17,166
  • 1
  • 38
  • 51