{ "cells": [ {"cell_type":"markdown","source":"

Advanced Expression Manipulation

","metadata":{"internals":{"slide_type":"subslide","slide_helper":"subslide_end"},"slideshow":{"slide_type":"slide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"

In this section, we discuss some ways that we can perform advanced manipulation of expressions.

","metadata":{}}, {"cell_type":"markdown","source":"

Understanding Expression Trees

","metadata":{"internals":{"slide_type":"subslide","slide_helper":"subslide_end"},"slideshow":{"slide_type":"slide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"

Quick Tip

","metadata":{}}, {"cell_type":"markdown","source":"

To play with the srepr form of expressions in the SymPy Live shell, change the output format to Repr in the settings.

","metadata":{}}, {"cell_type":"markdown","source":"

Before we can do this, we need to understand how expressions are represented in SymPy. A mathematical expression is represented as a tree. Let us take the expression 2^x + xy, i.e., 2**x + x*y. We can see what this expression looks like internally by using srepr

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> from sympy import *\n >>> x, y, z = symbols('x y z')\n\n >>> expr = 2**x + x*y\n >>> srepr(expr)\n \"Add(Pow(Integer(2), Symbol('x')), Mul(Symbol('x'), Symbol('y')))\""],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"","metadata":{}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["Add(Pow(Integer(2), Symbol('x')), Mul(Symbol('x'), Symbol('y')))"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["using SymPy\nx, y, z = symbols(\"x y z\")\n\nexpr = 2^x + x*y\nsrepr(expr)"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

The easiest way to tear this apart is to look at a diagrm of the expression tree. Here is a diagram.

","metadata":{}}, {"cell_type":"markdown","source":"

Note

This comes from dotprint(2**x + x*y, labelfunc=srepr). But we don't render digraph objects here

\n
","metadata":{}}, {"cell_type":"markdown","source":"

First, let's look at the leaves of this tree. Symbols are instances of the class Symbol. While we have been doing

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> x = symbols('x')"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}x\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["x = symbols(\"x\")"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

we could have also done

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> x = Symbol('x')"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"","metadata":{}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}x\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["x = sympy.Symbol(\"x\")"],"metadata":{},"execution_count":1}, {"outputs":[{"output_type":"execute_result","data":{"text/plain":["(x,)"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["@vars x"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

Either way, we get a Symbol with the name \"x\" [#symbols-fn]_. For the number in the expression, 2, we got Integer(2). Integer is the SymPy class for integers. It is similar to the Python built-in type int, except that Integer plays nicely with other SymPy types.

","metadata":{}}, {"cell_type":"markdown","source":"

When we write 2**x, this creates a Pow object. Pow is short for \"power\".

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> srepr(2**x)\n \"Pow(Integer(2), Symbol('x'))\""],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"","metadata":{}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["Pow(Integer(2), Symbol('x'))"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["srepr(2^x)"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

We could have created the same object by calling Pow(2, x)

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> Pow(2, x)\n 2**x"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"","metadata":{}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}2^{x}\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["sympy.Pow(2, x)"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

Note that in the srepr output, we see Integer(2), the SymPy version of integers, even though technically, we input 2, a Python int. In general, whenever you combine a SymPy object with a non-SymPy object via some function or operation, the non-SymPy object will be converted into a SymPy object. The function that does this is sympify [#sympify-fn]_.

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> type(2)\n <... 'int'>\n >>> type(sympify(2))\n "],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/plain":["Int64"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["typeof(2)"],"metadata":{},"execution_count":1}, {"outputs":[{"output_type":"execute_result","data":{"text/plain":["SymPy.Sym"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["typeof(sympify(2))"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

We have seen that 2**x is represented as Pow(2, x). What about x*y? As we might expect, this is the multiplication of x and y. The SymPy class for multiplication is Mul.

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> srepr(x*y)\n \"Mul(Symbol('x'), Symbol('y'))\""],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["Mul(Symbol('x'), Symbol('y'))"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["srepr(x*y)"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

Thus, we could have created the same object by writing Mul(x, y).

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> Mul(x, y)\n x*y"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"","metadata":{}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}x y\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["sympy.Mul(x, y)"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

Now we get to our final expression, 2**x + x*y. This is the addition of our last two objects, Pow(2, x), and Mul(x, y). The SymPy class for addition is Add, so, as you might expect, to create this object, we use Add(Pow(2, x), Mul(x, y)).

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> Add(Pow(2, x), Mul(x, y))\n 2**x + x*y"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"","metadata":{}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}2^{x} + x y\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["import_from(sympy, (:Add, :Mul, :Pow), typ=:Any)\nAdd(Pow(2, x), Mul(x, y))"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

SymPy expression trees can have many branches, and can be quite deep or quite broad. Here is a more complicated example

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> expr = sin(x*y)/2 - x**2 + 1/y\n >>> srepr(expr)\n \"Add(Mul(Integer(-1), Pow(Symbol('x'), Integer(2))), Mul(Rational(1, 2),\n sin(Mul(Symbol('x'), Symbol('y')))), Pow(Symbol('y'), Integer(-1)))\""],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["Add(Mul(Integer(-1), Pow(Symbol('x'), Integer(2))), Mul(Rational(1, 2), sin(Mul(Symbol('x'), Symbol('y')))), Pow(Symbol('y'), Integer(-1)))"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["expr = sin(x*y)/2 - x^2 + 1/y\nsrepr(expr)"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

Here is a diagram

","metadata":{}}, {"cell_type":"markdown","source":"

Note

produced with dotprint(sin(x*y)/2 - x**2 + 1/y, labelfunc=srepr), but not rendered here

\n
","metadata":{}}, {"cell_type":"markdown","source":"

This expression reveals some interesting things about SymPy expression trees. Let's go through them one by one.

","metadata":{}}, {"cell_type":"markdown","source":"

Let's first look at the term x**2. As we expected, we see Pow(x, 2). One level up, we see we have Mul(-1, Pow(x, 2)). There is no subtraction class in SymPy. x - y is represented as x + -y, or, more completely, x + -1*y, i.e., Add(x, Mul(-1, y)).

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> srepr(x - y)\n \"Add(Symbol('x'), Mul(Integer(-1), Symbol('y')))\""],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["Add(Symbol('x'), Mul(Integer(-1), Symbol('y')))"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["srepr(x - y)"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

Next, look at 1/y. We might expect to see something like Div(1, y), but similar to subtraction, there is no class in SymPy for division. Rather, division is represented by a power of -1. Hence, we have Pow(y, -1). What if we had divided something other than 1 by y, like x/y? Let's see.

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> expr = x/y\n >>> srepr(expr)\n \"Mul(Symbol('x'), Pow(Symbol('y'), Integer(-1)))\""],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["Mul(Symbol('x'), Pow(Symbol('y'), Integer(-1)))"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["expr = x/y\nsrepr(expr)"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

We see that x/y is represented as x*y**-1, i.e., Mul(x, Pow(y, -1)).

","metadata":{}}, {"cell_type":"markdown","source":"

Finally, let's look at the sin(x*y)/2 term. Following the pattern of the previous example, we might expect to see Mul(sin(x*y), Pow(Integer(2), -1)). But instead, we have Mul(Rational(1, 2), sin(x*y)). Rational numbers are always combined into a single term in a multiplication, so that when we divide by 2, it is represented as multiplying by 1/2.

","metadata":{}}, {"cell_type":"markdown","source":"

Finally, one last note. You may have noticed that the order we entered our expression and the order that it came out from srepr or in the graph were different. You may have also noticed this phenomenon earlier in the tutorial. For example

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> 1 + x\n x + 1"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}x + 1\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["1 + x"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

This because in SymPy, the arguments of the commutative operations Add and Mul are stored in an arbitrary (but consistent!) order, which is independent of the order inputted (if you're worried about noncommutative multiplication, don't be. In SymPy, you can create noncommutative Symbols using Symbol('A', commutative=False), and the order of multiplication for noncommutative Symbols is kept the same as the input). Furthermore, as we shall see in the next section, the printing order and the order in which things are stored internally need not be the same either.

","metadata":{}}, {"cell_type":"markdown","source":"

Quick Tip

","metadata":{}}, {"cell_type":"markdown","source":"

The way an expression is represented internally and the way it is printed are often not the same.

","metadata":{}}, {"cell_type":"markdown","source":"

In general, an important thing to keep in mind when working with SymPy expression trees is this: the internal representation of an expression and the way it is printed need not be the same. The same is true for the input form. If some expression manipulation algorithm is not working in the way you expected it to, chances are, the internal representation of the object is different from what you thought it was.

","metadata":{}}, {"cell_type":"markdown","source":"

Recursing through an Expression Tree

","metadata":{"internals":{"slide_type":"subslide","slide_helper":"subslide_end"},"slideshow":{"slide_type":"slide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"

Now that you know how expression trees work in SymPy, let's look at how to dig our way through an expression tree. Every object in SymPy has two very important attributes, func, and args.

","metadata":{}}, {"cell_type":"markdown","source":"

func

","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"

func is the head of the object. For example, (x*y).func is Mul. Usually it is the same as the class of the object (though there are exceptions to this rule).

","metadata":{}}, {"cell_type":"markdown","source":"

Two notes about func. First, the class of an object need not be the same as the one used to create it. For example

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> expr = Add(x, x)\n >>> expr.func\n "],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/plain":["PyObject "]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["expr = Add(x, x)\nexpr.func"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
    \n
  • The output isn't as desired, as PyObjects don't show nicely here. We can ask for the name, which does display as desired:

    \n
  • \n
","metadata":{}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["Mul"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["expr.func.__name__"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
    \n
  • In SymPy the func and args properties are exported as functions in the module SymPy.Introspection.

    \n
  • \n
","metadata":{}}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

We created Add(x, x), so we might expect expr.func to be Add, but instead we got Mul. Why is that? Let's take a closer look at expr.

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> expr\n 2*x"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}2 x\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["expr"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

Add(x, x), i.e., x + x, was automatically converted into Mul(2, x), i.e., 2*x, which is a Mul. SymPy classes make heavy use of the __new__ class constructor, which, unlike __init__, allows a different class to be returned from the constructor.

","metadata":{}}, {"cell_type":"markdown","source":"

Second, some classes are special-cased, usually for efficiency reasons [#singleton-fn]_.

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> Integer(2).func\n \n >>> Integer(0).func\n \n >>> Integer(-1).func\n "],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["Integer"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["sympy.Integer(2).func.__name__"],"metadata":{},"execution_count":1}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["Zero"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["sympy.Integer(0).func.__name__"],"metadata":{},"execution_count":1}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["NegativeOne"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["sympy.Integer(-1).func.__name__"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

For the most part, these issues will not bother us. The special classes Zero, One, NegativeOne, and so on are subclasses of Integer, so as long as you use isinstance, it will not be an issue.

","metadata":{}}, {"cell_type":"markdown","source":"

args

","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"

args are the top-level arguments of the object. (x*y).args would be (x, y). Let's look at some examples

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> expr = 3*y**2*x\n >>> expr.func\n \n >>> expr.args\n (3, x, y**2)"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"
    \n
  • The args property can be accessed exactly as func

    \n
  • \n
","metadata":{}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["Mul"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["expr = 3*y^2*x\nexpr.func.__name__"],"metadata":{},"execution_count":1}, {"outputs":[{"output_type":"execute_result","data":{"text/plain":["(3, x, y^2)"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["expr.args"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

From this, we can see that expr == Mul(3, y**2, x). In fact, we can see that we can completely reconstruct expr from its func and its args.

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> expr.func(*expr.args)\n 3*x*y**2\n >>> expr == expr.func(*expr.args)\n True"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}3 x y^{2}\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["expr.func(expr.args...)"],"metadata":{},"execution_count":1}, {"outputs":[{"output_type":"execute_result","data":{"text/plain":["true"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["expr == expr.func(expr.args...)"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

Note that although we entered 3*y**2*x, the args are (3, x, y**2). In a Mul, the Rational coefficient will come first in the args, but other than that, the order of everything else follows no special pattern. To be sure, though, there is an order.

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> expr = y**2*3*x\n >>> expr.args\n (3, x, y**2)"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/plain":["(3, x, y^2)"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["expr = y^2*3*x\nexpr.args"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

Mul's args are sorted, so that the same Mul will have the same args. But the sorting is based on some criteria designed to make the sorting unique and efficient that has no mathematical significance.

","metadata":{}}, {"cell_type":"markdown","source":"

The srepr form of our expr is Mul(3, x, Pow(y, 2)). What if we want to get at the args of Pow(y, 2). Notice that the y**2 is in the third slot of expr.args, i.e., expr.args[2].

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> expr.args[2]\n y**2"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}x\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["expr.args[2]"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

So to get the args of this, we call expr.args[2].args.

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> expr.args[2].args\n (y, 2)"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"
    \n
  • Python uses 0-based indexing, so we bump the index by 1

    \n
  • \n
","metadata":{}}, {"outputs":[{"output_type":"execute_result","data":{"text/plain":["(y, 2)"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["expr.args[3].args"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

Now what if we try to go deeper. What are the args of y. Or 2. Let's see.

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> y.args\n ()\n >>> Integer(2).args\n ()"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/plain":["()"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["y.args"],"metadata":{},"execution_count":1}, {"outputs":[{"output_type":"execute_result","data":{"text/plain":["()"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["sympy.Integer(2).args"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

They both have empty args. In SymPy, empty args signal that we have hit a leaf of the expression tree.

","metadata":{}}, {"cell_type":"markdown","source":"

So there are two possibilities for a SymPy expression. Either it has empty args, in which case it is a leaf node in any expression tree, or it has args, in which case, it is a branch node of any expression tree. When it has args, it can be completely rebuilt from its func and its args. This is expressed in the key invariant.

","metadata":{}}, {"cell_type":"markdown","source":"

Key Invariant

","metadata":{}}, {"cell_type":"markdown","source":"

Every well-formed SymPy expression must either have empty args or satisfy expr == expr.func(expr.args...).

","metadata":{}}, {"cell_type":"markdown","source":"

(Recall that in Python if a is a tuple, then f(*a) means to call f with arguments from the elements of a, e.g., f(*(1, 2, 3)) is the same as f(1, 2, 3).)

","metadata":{}}, {"cell_type":"markdown","source":"

This key invariant allows us to write simple algorithms that walk expression trees, change them, and rebuild them into new expressions.

","metadata":{}}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"
    \n
  • Splatting replaces the *a term above, or f(a...).

    \n
  • \n
","metadata":{}}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

Walking the Tree

","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"

With this knowledge, let's look at how we can recurse through an expression tree. The nested nature of args is a perfect fit for recursive functions. The base case will be empty args. Let's write a simple function that goes through an expression and prints all the args at each level.

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> def pre(expr):\n ... print(expr)\n ... for arg in expr.args:\n ... pre(arg)"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/plain":["pre (generic function with 1 method)"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["function pre(expr)\n @show expr\n for arg in expr.args\n \tpre(arg)\n\tend\nend"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

See how nice it is that () signals leaves in the expression tree. We don't even have to write a base case for our recursion; it is handled automatically by the for loop.

","metadata":{}}, {"cell_type":"markdown","source":"

Let's test our function.

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> expr = x*y + 1\n >>> pre(expr)\n x*y + 1\n 1\n x*y\n x\n y"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"
    \n
  • @show does not work in these notes; this would need copy-and-pasting to be verified

    \n
  • \n
","metadata":{}}, {"outputs":[],"cell_type":"code","source":["expr = x*y + 1\npre(expr)"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

Can you guess why we called our function pre? We just wrote a pre-order traversal function for our expression tree. See if you can write a post-order traversal function.

","metadata":{}}, {"cell_type":"markdown","source":"

Such traversals are so common in SymPy that the generator functions preorder_traversal and postorder_traversal are provided to make such traversals easy. We could have also written our algorithm as

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> for arg in preorder_traversal(expr):\n ... print(arg)\n x*y + 1\n 1\n x*y\n x\n y"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"
    \n
  • The preorder_traversal function is not a function, so needs to be qualified:

    \n
  • \n
","metadata":{}}, {"outputs":[],"cell_type":"code","source":["for arg in sympy.preorder_traversal(expr)\n @show arg\nend"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

Prevent expression evaluation

","metadata":{"internals":{"slide_type":"subslide","slide_helper":"subslide_end"},"slideshow":{"slide_type":"slide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"

There are generally two ways to prevent the evaluation, either pass an evaluate=False parameter while constructing the expression, or create an evaluation stopper by wrapping the expression with UnevaluatedExpr.

","metadata":{}}, {"cell_type":"markdown","source":"

For example:

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> from sympy import Add\n >>> from sympy.abc import x, y, z\n >>> x + x\n 2*x\n >>> Add(x, x)\n 2*x\n >>> Add(x, x, evaluate=False)\n x + x"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}2 x\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["@vars x y z\nx + x"],"metadata":{},"execution_count":1}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}2 x\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["Add(x, x)"],"metadata":{},"execution_count":1}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}x + x\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["Add(x, x, evaluate=False)"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

If you don't remember the class corresponding to the expression you want to build (operator overloading usually assumes evaluate=True), just use sympify and pass a string:

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> from sympy import sympify\n >>> sympify(\"x + x\", evaluate=False)\n x + x"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}2 x\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["sympify(\"x + x\", evaluate=false)\n x + x"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

Note that evaluate=False won't prevent future evaluation in later usages of the expression:

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> expr = Add(x, x, evaluate=False)\n >>> expr\n x + x\n >>> expr + x\n 3*x"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}x + x\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["expr = Add(x, x, evaluate=false)\nexpr"],"metadata":{},"execution_count":1}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}3 x\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["expr + x"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

That's why the class UnevaluatedExpr comes handy. UnevaluatedExpr is a method provided by SymPy which lets the user keep an expression unevaluated. By unevaluated it is meant that the value inside of it will not interact with the expressions outside of it to give simplified outputs. For example:

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> from sympy import UnevaluatedExpr\n >>> expr = x + UnevaluatedExpr(x)\n >>> expr\n x + x\n >>> x + expr\n 2*x + x"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}x + x\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["import_from(sympy, (:UnevaluatedExpr,))\nexpr = x + UnevaluatedExpr(x)\nexpr"],"metadata":{},"execution_count":1}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}2 x + x\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["x + expr"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

The x remaining alone is the x wrapped by UnevaluatedExpr. To release it:

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> (x + expr).doit()\n 3*x"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}3 x\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["(x + expr).doit()"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

Other examples:

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> from sympy import *\n >>> from sympy.abc import x, y, z\n >>> uexpr = UnevaluatedExpr(S.One*5/7)*UnevaluatedExpr(S.One*3/4)\n >>> uexpr\n (5/7)*(3/4)\n >>> x*UnevaluatedExpr(1/x)\n x*1/x"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}\\frac{5}{7} \\frac{3}{4}\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["@vars x y z\nconst S = sympy.S\nuexpr = UnevaluatedExpr(S.One * 5/7) * UnevaluatedExpr(S.One * 3/4)\nuexpr"],"metadata":{},"execution_count":1}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}x \\frac{1}{x}\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["x * UnevaluatedExpr(1/x)"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

A point to be noted is that UnevaluatedExpr cannot prevent the evaluation of an expression which is given as argument. For example:

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> expr1 = UnevaluatedExpr(x + x)\n >>> expr1\n 2*x\n >>> expr2 = sympify('x + x', evaluate=False)\n >>> expr2\n x + x"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}2 x\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["expr1 = UnevaluatedExpr(x + x)\nexpr1"],"metadata":{},"execution_count":1}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}x + x\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["expr2 = sympify(\"x + x\", evaluate=False)\nexpr2"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

Remember that expr2 will be evaluated if included into another expression. Combine both of the methods to prevent both inside and outside evaluations:

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> UnevaluatedExpr(sympify(\"x + x\", evaluate=False)) + y\n y + x + x"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\begin{equation*}y + x + x\\end{equation*}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["UnevaluatedExpr(sympify(\"x + x\", evaluate=False)) + y"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

UnevalutedExpr is supported by SymPy printers and can be used to print the result in different output forms. For example

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> from sympy import latex\n >>> uexpr = UnevaluatedExpr(S.One*5/7)*UnevaluatedExpr(S.One*3/4)\n >>> print(latex(uexpr))\n \\frac{5}{7} \\frac{3}{4}"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"cell_type":"markdown","source":"
    \n
  • The printing support is through show, but we can use SymPy's:

    \n
  • \n
","metadata":{}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\frac{5}{7} \\frac{3}{4}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["uexpr = UnevaluatedExpr(S.One*5/7)*UnevaluatedExpr(S.One*3/4)\nsympy.latex(uexpr)"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

In order to release the expression and get the evaluated LaTeX form, just use .doit():

","metadata":{}}, {"outputs":[],"cell_type":"code","source":[" >>> print(latex(uexpr.doit()))\n \\frac{15}{28}"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
In Julia:
","metadata":{"internals":{"slide_type":"subslide"},"slideshow":{"slide_type":"subslide"},"slide_helper":"slide_end"}}, {"outputs":[{"output_type":"execute_result","data":{"text/latex":["\\frac{15}{28}"]},"metadata":{},"execution_count":1}],"cell_type":"code","source":["sympy.latex(uexpr.doit())"],"metadata":{},"execution_count":1}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

Footnotes

","metadata":{}}, {"cell_type":"markdown","source":"
    \n
  • [#symbols-fn] We have been using symbols instead of Symbol because it automatically splits apart strings into multiple Symbol\\ s. symbols('x y z') returns a tuple of three Symbol\\ s. Symbol('x y z') returns a single Symbol called x y z.

    \n
  • \n
  • [#sympify-fn] Technically, it is an internal function called _sympify, which differs from sympify in that it does not convert strings. x + '2' is not allowed.

    \n
  • \n
  • [#singleton-fn] Classes like One and Zero are singletonized, meaning that only one object is ever created, no matter how many times the class is called. This is done for space efficiency, as these classes are very common. For example, Zero might occur very often in a sparse matrix represented densely. As we have seen, NegativeOne occurs any time we have -x or 1/x. It is also done for speed efficiency because singletonized objects can be compared by is. The unique objects for each singletonized class can be accessed from the S object.

    \n
  • \n
","metadata":{}}, {"cell_type":"markdown","source":"
","metadata":{}}, {"cell_type":"markdown","source":"

return to index

","metadata":{}} ], "metadata": { "language_info": { "file_extension": ".jl", "mimetype": "application/julia", "name": "julia", "version": "0.6" }, "kernelspec": { "display_name": "Julia 1.0.0", "language": "julia", "name": "julia-1.0" } }, "nbformat": 4, "nbformat_minor": 2 }