<jupyter_start><jupyter_text>Sympy - Symbolic algebra in Python <NAME> (<EMAIL>) - minor edits to perform plotting using the Bokeh package. 2015-05-17<NAME> (<EMAIL>) http://dml.riken.jp/~rob/The latest version of the original [IPython notebook](http://ipython.org/notebook.html) lecture is available at [http://github.com/jrjohansson/scientific-python-lectures](http://github.com/jrjohansson/scientific-python-lectures).The other notebooks in this lecture series are indexed at [http://jrjohansson.github.com](http://jrjohansson.github.com).<jupyter_code>from bokeh.plotting import output_notebook
output_notebook()
from bokeh.plotting import figure, show<jupyter_output><empty_output><jupyter_text>Introduction There are two notable Computer Algebra Systems (CAS) for Python:* [SymPy](http://sympy.org/en/index.html) - A python module that can be used in any Python program, or in an IPython session, that provides powerful CAS features. * [Sage](http://www.sagemath.org/) - Sage is a full-featured and very powerful CAS enviroment that aims to provide an open source system that competes with Mathematica and Maple. Sage is not a regular Python module, but rather a CAS environment that uses Python as its programming language.Sage is in some aspects more powerful than SymPy, but both offer very comprehensive CAS functionality. The advantage of SymPy is that it is a regular Python module and integrates well with the IPython notebook. In this lecture we will therefore look at how to use SymPy with IPython notebooks. If you are interested in an open source CAS environment I also recommend to read more about Sage.To get started using SymPy in a Python program or notebook, import the module `sympy`:<jupyter_code>from sympy import *<jupyter_output><empty_output><jupyter_text>To get nice-looking $\LaTeX$ formatted output run:<jupyter_code>init_printing()

# or with older versions of sympy/ipython, load the IPython extension
#%load_ext sympy.interactive.ipythonprinting
# or
#%load_ext sympyprinting<jupyter_output><empty_output><jupyter_text>Symbolic variables In SymPy we need to create symbols for the variables we want to work with. We can create a new symbol using the `Symbol` class:<jupyter_code>x = Symbol('x')
(pi + x)**2
# alternative way of defining symbols
a, b, c = symbols("a, b, c")
type(a)<jupyter_output><empty_output><jupyter_text>We can add assumptions to symbols when we create them:<jupyter_code>x = Symbol('x', real=True)
x.is_imaginary
x = Symbol('x', positive=True)
x > 0<jupyter_output><empty_output><jupyter_text>Complex numbers The imaginary unit is denoted `I` in Sympy.<jupyter_code>1+1*I
I**2
(x * I + 1)**2<jupyter_output><empty_output><jupyter_text>Rational numbers There are three different numerical types in SymPy: `Real`, `Rational`, `Integer`:<jupyter_code>r1 = Rational(4,5)
r2 = Rational(5,4)
r1
r1+r2
r1/r2<jupyter_output><empty_output><jupyter_text>Numerical evaluation SymPy uses a library for arbitrary precision as numerical backend, and has predefined SymPy expressions for a number of mathematical constants, such as: `pi`, `e`, `oo` for infinity.To evaluate an expression numerically we can use the `evalf` function (or `N`). It takes an argument `n` which specifies the number of significant digits.<jupyter_code>pi.evalf(n=50)
y = (x + pi)**2
N(y, 5) # same as evalf<jupyter_output><empty_output><jupyter_text>When we numerically evaluate algebraic expressions we often want to substitute a symbol with a numerical value. In SymPy we do that using the `subs` function:<jupyter_code>y.subs(x, 1.5)
N(y.subs(x, 1.5))<jupyter_output><empty_output><jupyter_text>The `subs` function can of course also be used to substitute Symbols and expressions:<jupyter_code>y.subs(x, a+pi)<jupyter_output><empty_output><jupyter_text>We can also combine numerical evolution of expressions with NumPy arrays:<jupyter_code>import numpy
x_vec = numpy.arange(0, 10, 0.1)
y_vec = numpy.array([N(((x + pi)**2).subs(x, xx)) for xx in x_vec], dtype=float)
#TODO: note, weird issue with "Float" object (vs numpy float type) serialization to JSON
N(y, 5)
title = N(y, 5).__str__()
p = figure(title=title, x_axis_label='x', y_axis_label='y')
p.line(x_vec, y_vec)
show(p)<jupyter_output><empty_output><jupyter_text>However, this kind of numerical evolution can be very slow, and there is a much more efficient way to do it: Use the function `lambdify` to "compile" a Sympy expression into a function that is much more efficient to evaluate numerically:<jupyter_code>f = lambdify([x], (x + pi)**2, 'numpy')  # the first argument is a list of variables that
                                         # f will be a function of: in this case only x -> f(x)
y_vec = f(x_vec)  # now we can directly pass a numpy array and f(x) is efficiently evaluated
# Note: this does not have the same "Float" object problem as above.<jupyter_output><empty_output><jupyter_text>The speedup when using "lambdified" functions instead of direct numerical evaluation can be significant, often several orders of magnitude. Even in this simple example we get a significant speed up:<jupyter_code>%%timeit

y_vec = numpy.array([N(((x + pi)**2).subs(x, xx)) for xx in x_vec])
%%timeit

y_vec = f(x_vec)<jupyter_output>The slowest run took 13.65 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 2.48 µs per loop<jupyter_text>Algebraic manipulations One of the main uses of an CAS is to perform algebraic manipulations of expressions. For example, we might want to expand a product, factor an expression, or simply an expression. The functions for doing these basic operations in SymPy are demonstrated in this section.  Expand and factor The first steps in an algebraic manipulation<jupyter_code>(x+1)*(x+2)*(x+3)
expand((x+1)*(x+2)*(x+3))<jupyter_output><empty_output><jupyter_text>This is "reversible" with the `factor` command. The `expand` function takes a number of keywords arguments which we can tell the functions what kind of expansions we want to have performed. For example, to expand trigonometric expressions, use the `trig=True` keyword argument:<jupyter_code>sin(a+b)
expand(sin(a+b), trig=True)<jupyter_output><empty_output><jupyter_text>See `help(expand)` for a detailed explanation of the various types of expansions the `expand` functions can perform. The opposite of product expansion is of course factoring. The factor an expression in SymPy use the `factor` function:<jupyter_code>factor(x**3 + 6 * x**2 + 11*x + 6)<jupyter_output><empty_output><jupyter_text>Simplify The `simplify` tries to simplify an expression into a nice looking expression, using various techniques. More specific alternatives to the `simplify` functions also exists: `trigsimp`, `powsimp`, `logcombine`, etc. The basic usages of these functions are as follows:<jupyter_code># simplify expands a product
simplify((x+1)*(x+2)*(x+3))
# simplify uses trigonometric identities
simplify(sin(a)**2 + cos(a)**2)
simplify(cos(x)/sin(x))<jupyter_output><empty_output><jupyter_text>apart and together To manipulate symbolic expressions of fractions, we can use the `apart` and `together` functions:<jupyter_code>f1 = 1/((a+1)*(a+2))
f1
apart(f1)
f2 = 1/(a+2) + 1/(a+3)
f2
together(f2)<jupyter_output><empty_output><jupyter_text>Simplify usually combines fractions but does not factor:<jupyter_code>simplify(f2)<jupyter_output><empty_output><jupyter_text>Calculus In addition to algebraic manipulations, the other main use of CAS is to do calculus, like derivatives and integrals of algebraic expressions.  Differentiation Differentiation is usually simple. Use the `diff` function. The first argument is the expression to take the derivative of, and the second argument is the symbol by which to take the derivative:<jupyter_code>y
y**2
diff(y**2, x)<jupyter_output><empty_output><jupyter_text>For higher order derivatives we can do:<jupyter_code>diff(y**2, x, x)
diff(y**2, x, 2) # same as above<jupyter_output><empty_output><jupyter_text>To calculate the derivative of a multivariate expression, we can do:<jupyter_code>x, y, z = symbols("x,y,z")
f = sin(x*y) + cos(y*z)<jupyter_output><empty_output><jupyter_text>$\frac{d^3f}{dxdy^2}$<jupyter_code>diff(f, x, 1, y, 2)<jupyter_output><empty_output><jupyter_text>Integration Integration is done in a similar fashion:<jupyter_code>f
integrate(f, x)<jupyter_output><empty_output><jupyter_text>By providing limits for the integration variable we can evaluate definite integrals:<jupyter_code>integrate(f, (x, -1, 1))<jupyter_output><empty_output><jupyter_text>and also improper integrals<jupyter_code>integrate(exp(-x**2), (x, -oo, oo))<jupyter_output><empty_output><jupyter_text>Remember, `oo` is the SymPy notation for inifinity.  Sums and products We can evaluate sums and products using the functions: 'Sum'<jupyter_code>n = Symbol("n")
Sum(1/n**2, (n, 1, 10))
Sum(1/n**2, (n,1, 10)).evalf()
Sum(1/n**2, (n, 1, oo)).evalf()<jupyter_output><empty_output><jupyter_text>Products work much the same way:<jupyter_code>Product(n, (n, 1, 10)) # 10!<jupyter_output><empty_output><jupyter_text>Limits Limits can be evaluated using the `limit` function. For example,<jupyter_code>limit(sin(x)/x, x, 0)<jupyter_output><empty_output><jupyter_text>We can use 'limit' to check the result of derivation using the `diff` function:<jupyter_code>f
diff(f, x)<jupyter_output><empty_output><jupyter_text>$\displaystyle \frac{\mathrm{d}f(x,y)}{\mathrm{d}x} = \frac{f(x+h,y)-f(x,y)}{h}$<jupyter_code>h = Symbol("h")
limit((f.subs(x, x+h) - f)/h, h, 0)<jupyter_output><empty_output><jupyter_text>OK! We can change the direction from which we approach the limiting point using the `dir` keywork argument:<jupyter_code>limit(1/x, x, 0, dir="+")
limit(1/x, x, 0, dir="-")<jupyter_output><empty_output><jupyter_text>Series Series expansion is also one of the most useful features of a CAS. In SymPy we can perform a series expansion of an expression using the `series` function:<jupyter_code>series(exp(x), x)<jupyter_output><empty_output><jupyter_text>By default it expands the expression around $x=0$, but we can expand around any value of $x$ by explicitly include a value in the function call:<jupyter_code>series(exp(x), x, 1)<jupyter_output><empty_output><jupyter_text>And we can explicitly define to which order the series expansion should be carried out:<jupyter_code>series(exp(x), x, 1, 10)<jupyter_output><empty_output><jupyter_text>The series expansion includes the order of the approximation, which is very useful for keeping track of the order of validity when we do calculations with series expansions of different order:<jupyter_code>s1 = cos(x).series(x, 0, 5)
s1
s2 = sin(x).series(x, 0, 2)
s2
expand(s1 * s2)<jupyter_output><empty_output><jupyter_text>If we want to get rid of the order information we can use the `removeO` method:<jupyter_code>expand(s1.removeO() * s2.removeO())<jupyter_output><empty_output><jupyter_text>But note that this is not the correct expansion of $\cos(x)\sin(x)$ to $5$th order:<jupyter_code>(cos(x)*sin(x)).series(x, 0, 6)<jupyter_output><empty_output><jupyter_text>Linear algebra  Matrices Matrices are defined using the `Matrix` class:<jupyter_code>m11, m12, m21, m22 = symbols("m11, m12, m21, m22")
b1, b2 = symbols("b1, b2")
A = Matrix([[m11, m12],[m21, m22]])
A
b = Matrix([[b1], [b2]])
b<jupyter_output><empty_output><jupyter_text>With `Matrix` class instances we can do the usual matrix algebra operations:<jupyter_code>A**2
A * b<jupyter_output><empty_output><jupyter_text>And calculate determinants and inverses, and the like:<jupyter_code>A.det()
A.inv()<jupyter_output><empty_output><jupyter_text>Solving equations For solving equations and systems of equations we can use the `solve` function:<jupyter_code>solve(x**2 - 1, x)
solve(x**4 - x**2 - 1, x)<jupyter_output><empty_output><jupyter_text>System of equations:<jupyter_code>solve([x + y - 1, x - y - 1], [x,y])<jupyter_output><empty_output><jupyter_text>In terms of other symbolic expressions:<jupyter_code>solve([x + y - a, x - y - c], [x,y])<jupyter_output><empty_output><jupyter_text>Quantum mechanics: noncommuting variables How about non-commuting symbols? In quantum mechanics we need to work with noncommuting operators, and SymPy has a nice support for noncommuting symbols and even a subpackage for quantum mechanics related calculations!<jupyter_code>from sympy.physics.quantum import *<jupyter_output><empty_output><jupyter_text>States We can define symbol states, kets and bras:<jupyter_code>Ket('psi')
Bra('psi')
u = Ket('0')
d = Ket('1')

a, b = symbols('alpha beta', complex=True)
phi = a * u + sqrt(1-abs(a)**2) * d; phi
Dagger(phi)
Dagger(phi) * d<jupyter_output><empty_output><jupyter_text>Use `qapply` to distribute a mutiplication:<jupyter_code>qapply(Dagger(phi) * d)
qapply(Dagger(phi) * u)<jupyter_output><empty_output><jupyter_text>Operators<jupyter_code>A = Operator('A')
B = Operator('B')<jupyter_output><empty_output><jupyter_text>Check if they are commuting!<jupyter_code>A * B == B * A
expand((A+B)**3)
c = Commutator(A,B)
c<jupyter_output><empty_output><jupyter_text>We can use the `doit` method to evaluate the commutator:<jupyter_code>c.doit()<jupyter_output><empty_output><jupyter_text>We can mix quantum operators with C-numbers:<jupyter_code>c = Commutator(a * A, b * B)
c<jupyter_output><empty_output><jupyter_text>To expand the commutator, use the `expand` method with the `commutator=True` keyword argument:<jupyter_code>c = Commutator(A+B, A*B)
c.expand(commutator=True)
Dagger(Commutator(A, B))
ac = AntiCommutator(A,B)
ac.doit()<jupyter_output><empty_output><jupyter_text>Example: Quadrature commutator Let's look at the commutator of the electromagnetic field quadatures $x$ and $p$. We can write the quadrature operators in terms of the creation and annihilation operators as:$\displaystyle x = (a + a^\dagger)/\sqrt{2}$$\displaystyle p = -i(a - a^\dagger)/\sqrt{2}$<jupyter_code>X = (A + Dagger(A))/sqrt(2)
X
P = -I * (A - Dagger(A))/sqrt(2)
P<jupyter_output><empty_output><jupyter_text>Let's expand the commutator $[x,p]$<jupyter_code>Commutator(X, P).expand(commutator=True).expand(commutator=True)<jupyter_output><empty_output><jupyter_text>Here we see directly that the well known commutation relation for the quadratures$[x,p]=i$is a directly related to$[A, A^\dagger]=1$ (which SymPy does not know about, and does not simplify). For more details on the quantum module in SymPy, see:* http://docs.sympy.org/0.7.2/modules/physics/quantum/index.html* http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/master/docs/examples/notebooks/sympy_quantum_computing.ipynb  Further reading * http://sympy.org/en/index.html - The SymPy projects web page.* https://github.com/sympy/sympy - The source code of SymPy.* http://live.sympy.org - Online version of SymPy for testing and demonstrations.  Versions<jupyter_code># must have version_information.py file in local dir or appropriate PATH
%reload_ext version_information 

%version_information numpy, sympy, bokeh<jupyter_output><empty_output>