Ask Your Question
1

Tree representing an expression

asked 2021-07-29 05:06:43 +0100

Apprentice gravatar image

updated 2024-02-21 11:24:50 +0100

FrédéricC gravatar image

Is there a way to see the tree representing an expression in Sage? Just like Mathematica does with:

TreeForm[Sqrt[x^2+y^2+z^2] + x/y]]

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
1

answered 2021-07-30 09:33:00 +0100

slelievre gravatar image

updated 2021-07-30 10:53:43 +0100

Sage does not provide a built-in function for that.

However, such a function is given in the answer to this Sage question:

Refreshing the code from that answer for Python 3:

class ExpressionGraph():
    def __init__(self, expr):
        self.G = Graph()
        self.i = 0
        self.expr = expr
        self.root = None
        self.graph_expr(self.expr)
    def plot(self, *args, **kwds):
        # print "root is {0}".format(self.root)
        return self.G.plot(*args, layout='tree', tree_root=self.root, **kwds)
    def graph_expr(self, expr):
        try:
            operator = expr.operator()
        except AttributeError:  # e.g. if expr is an integer
            operator = None
        if operator is None:
            name = "[{0}] {1}".format(self.i, expr)
            # print(self.i)
            # print("(leaf) {0}".format(expr))
            self.i += 1
            self.G.add_vertex(name)
            return name
        else:
            name = "[{0}] {1}".format(self.i, expr.operator().__name__)
            # print(self.i)
            # print("(node) {0}; {1}".format(expr, expr.operator().__name__))
            if self.i == 0:
                self.root = name
                # print("  ** root is '{0}' **".format(self.root))
            self.i += 1
            new_nodes = []
            for opnd in expr.operands():
                new_nodes += [self.graph_expr(opnd)]
            self.G.add_vertex(name)
            self.G.add_edges([(name, node) for node in new_nodes])
            return name

Using it:

sage: x, y, z = SR.var('x, y, z')
sage: f = sqrt(x^2+y^2+z^2) + x/y
sage: E = ExpressionGraph(f)
sage: E.plot()

Expression tree plotted with Sage

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2021-07-29 05:06:43 +0100

Seen: 272 times

Last updated: Jul 30 '21