J.R. Johansson (robert@riken.jp) http://dml.riken.jp/~rob/
The latest version of this IPython notebook lecture is available at http://github.com/jrjohansson/scientific-python-lectures.
The other notebooks in this lecture series are indexed at http://jrjohansson.github.com.
In [1]:
%pylab inline
There are two notable Computer Algebra Systems (CAS) for Python:
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
:
In [2]:
from sympy import *
To get nice-looking $\LaTeX$ formatted output run:
In [3]:
init_printing()
# or with older versions of sympy/ipython, load the IPython extension
#%load_ext sympy.interactive.ipythonprinting
# or
#%load_ext sympyprinting
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:
In [4]:
x = Symbol('x')
In [5]:
(pi + x)**2
Out[5]:
In [6]:
# alternative way of defining symbols
a, b, c = symbols("a, b, c")
In [7]:
type(a)
Out[7]:
We can add assumptions to symbols when we create them:
In [8]:
x = Symbol('x', real=True)
In [9]:
x.is_imaginary
Out[9]:
In [10]:
x = Symbol('x', positive=True)
In [11]:
x > 0
Out[11]:
The imaginary unit is denoted I
in Sympy.
In [12]:
1+1*I
Out[12]:
In [13]:
I**2
Out[13]:
In [14]:
(x * I + 1)**2
Out[14]:
There are three different numerical types in SymPy: Real
, Rational
, Integer
:
In [15]:
r1 = Rational(4,5)
r2 = Rational(5,4)
In [16]:
r1
Out[16]:
In [17]:
r1+r2
Out[17]:
In [18]:
r1/r2
Out[18]:
SymPy uses a library for artitrary 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.
In [19]:
pi.evalf(n=50)
Out[19]:
In [20]:
y = (x + pi)**2
In [21]:
N(y, 5) # same as evalf
Out[21]:
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:
In [22]:
y.subs(x, 1.5)
Out[22]:
In [23]:
N(y.subs(x, 1.5))
Out[23]:
The subs
function can of course also be used to substitute Symbols and expressions:
In [24]:
y.subs(x, a+pi)
Out[24]:
We can also combine numerical evolution of expressions with NumPy arrays:
In [25]:
import numpy
In [26]:
x_vec = numpy.arange(0, 10, 0.1)
In [27]:
y_vec = numpy.array([N(((x + pi)**2).subs(x, xx)) for xx in x_vec])
In [28]:
fig, ax = subplots()
ax.plot(x_vec, y_vec);
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:
In [29]:
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)
In [30]:
y_vec = f(x_vec) # now we can directly pass a numpy array and f(x) is efficiently evaluated
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:
In [31]:
%%timeit
y_vec = numpy.array([N(((x + pi)**2).subs(x, xx)) for xx in x_vec])
In [32]:
%%timeit
y_vec = f(x_vec)
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.
The first steps in an algebraic manipulation
In [33]:
(x+1)*(x+2)*(x+3)
Out[33]:
In [34]:
expand((x+1)*(x+2)*(x+3))
Out[34]:
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:
In [35]:
sin(a+b)
Out[35]:
In [36]:
expand(sin(a+b), trig=True)
Out[36]:
See help(expand)
for a detailed explanation of the various types of expansions the expand
functions can perform.
The opposite a product expansion is of course factoring. The factor an expression in SymPy use the factor
function:
In [37]:
factor(x**3 + 6 * x**2 + 11*x + 6)
Out[37]:
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:
In [38]:
# simplify expands a product
simplify((x+1)*(x+2)*(x+3))
Out[38]:
In [39]:
# simplify uses trigonometric identities
simplify(sin(a)**2 + cos(a)**2)
Out[39]:
In [40]:
simplify(cos(x)/sin(x))
Out[40]:
To manipulate symbolic expressions of fractions, we can use the apart
and together
functions:
In [41]:
f1 = 1/((a+1)*(a+2))
In [42]:
f1
Out[42]:
In [43]:
apart(f1)
Out[43]:
In [44]:
f2 = 1/(a+2) + 1/(a+3)
In [45]:
f2
Out[45]:
In [46]:
together(f2)
Out[46]:
Simplify usually combines fractions but does not factor:
In [47]:
simplify(f2)
Out[47]:
In addition to algebraic manipulations, the other main use of CAS is to do calculus, like derivatives and integrals of algebraic expressions.
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:
In [48]:
y
Out[48]:
In [49]:
diff(y**2, x)
Out[49]:
For higher order derivatives we can do:
In [50]:
diff(y**2, x, x)
Out[50]:
In [51]:
diff(y**2, x, 2) # same as above
Out[51]:
To calculate the derivative of a multivariate expression, we can do:
In [52]:
x, y, z = symbols("x,y,z")
In [53]:
f = sin(x*y) + cos(y*z)
$\frac{d^3f}{dxdy^2}$
In [54]:
diff(f, x, 1, y, 2)
Out[54]:
Integration is done in a similar fashion:
In [55]:
f
Out[55]:
In [56]:
integrate(f, x)
Out[56]:
By providing limits for the integration variable we can evaluate definite integrals:
In [57]:
integrate(f, (x, -1, 1))
Out[57]:
and also improper integrals
In [58]:
integrate(exp(-x**2), (x, -oo, oo))
Out[58]:
Remember, oo
is the SymPy notation for inifinity.
We can evaluate sums and products using the functions: 'Sum'
In [59]:
n = Symbol("n")
In [60]:
Sum(1/n**2, (n, 1, 10))
Out[60]:
In [61]:
Sum(1/n**2, (n,1, 10)).evalf()
Out[61]:
In [62]:
Sum(1/n**2, (n, 1, oo)).evalf()
Out[62]:
Products work much the same way:
In [63]:
Product(n, (n, 1, 10)) # 10!
Out[63]:
Limits can be evaluated using the limit
function. For example,
In [64]:
limit(sin(x)/x, x, 0)
Out[64]:
We can use 'limit' to check the result of derivation using the diff
function:
In [65]:
f
Out[65]:
In [66]:
diff(f, x)
Out[66]:
$\displaystyle \frac{\mathrm{d}f(x,y)}{\mathrm{d}x} = \frac{f(x+h,y)-f(x,y)}{h}$
In [67]:
h = Symbol("h")
In [68]:
limit((f.subs(x, x+h) - f)/h, h, 0)
Out[68]:
OK!
We can change the direction from which we approach the limiting point using the dir
keywork argument:
In [69]:
limit(1/x, x, 0, dir="+")
Out[69]:
In [70]:
limit(1/x, x, 0, dir="-")
Out[70]:
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:
In [71]:
series(exp(x), x)
Out[71]:
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:
In [72]:
series(exp(x), x, 1)
Out[72]:
And we can explicitly define to which order the series expansion should be carried out:
In [73]:
series(exp(x), x, 1, 10)
Out[73]:
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:
In [74]:
s1 = cos(x).series(x, 0, 5)
s1
Out[74]:
In [75]:
s2 = sin(x).series(x, 0, 2)
s2
Out[75]:
In [76]:
expand(s1 * s2)
Out[76]:
If we want to get rid of the order information we can use the removeO
method:
In [77]:
expand(s1.removeO() * s2.removeO())
Out[77]:
But note that this is not the correct expansion of $\cos(x)\sin(x)$ to $5$th order:
In [78]:
(cos(x)*sin(x)).series(x, 0, 6)
Out[78]:
Matrices are defined using the Matrix
class:
In [79]:
m11, m12, m21, m22 = symbols("m11, m12, m21, m22")
b1, b2 = symbols("b1, b2")
In [80]:
A = Matrix([[m11, m12],[m21, m22]])
A
Out[80]:
In [81]:
b = Matrix([[b1], [b2]])
b
Out[81]:
With Matrix
class instances we can do the usual matrix algebra operations:
In [82]:
A**2
Out[82]:
In [83]:
A * b
Out[83]:
And calculate determinants and inverses, and the like:
In [84]:
A.det()
Out[84]:
In [85]:
A.inv()
Out[85]:
For solving equations and systems of equations we can use the solve
function:
In [86]:
solve(x**2 - 1, x)
Out[86]:
In [87]:
solve(x**4 - x**2 - 1, x)
Out[87]:
System of equations:
In [88]:
solve([x + y - 1, x - y - 1], [x,y])
Out[88]:
In terms of other symbolic expressions:
In [89]:
solve([x + y - a, x - y - c], [x,y])
Out[89]:
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!
In [5]:
from sympy.physics.quantum import *
We can define symbol states, kets and bras:
In [91]:
Ket('psi')
Out[91]:
In [92]:
Bra('psi')
Out[92]:
In [93]:
u = Ket('0')
d = Ket('1')
a, b = symbols('alpha beta', complex=True)
In [94]:
phi = a * u + sqrt(1-abs(a)**2) * d; phi
Out[94]:
In [95]:
Dagger(phi)
Out[95]:
In [96]:
Dagger(phi) * d
Out[96]:
Use qapply
to distribute a mutiplication:
In [97]:
qapply(Dagger(phi) * d)
Out[97]:
In [98]:
qapply(Dagger(phi) * u)
Out[98]:
In [6]:
A = Operator('A')
B = Operator('B')
Check if they are commuting!
In [100]:
A * B == B * A
Out[100]:
In [101]:
expand((A+B)**3)
Out[101]:
In [102]:
c = Commutator(A,B)
c
Out[102]:
We can use the doit
method to evaluate the commutator:
In [103]:
c.doit()
Out[103]:
We can mix quantum operators with C-numbers:
In [104]:
c = Commutator(a * A, b * B)
c
Out[104]:
To expand the commutator, use the expand
method with the commutator=True
keyword argument:
In [105]:
c = Commutator(A+B, A*B)
c.expand(commutator=True)
Out[105]:
In [106]:
Dagger(Commutator(A, B))
Out[106]:
In [107]:
ac = AntiCommutator(A,B)
In [108]:
ac.doit()
Out[108]:
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}$
In [109]:
X = (A + Dagger(A))/sqrt(2)
X
Out[109]:
In [110]:
P = -I * (A - Dagger(A))/sqrt(2)
P
Out[110]:
Let's expand the commutator $[x,p]$
In [111]:
Commutator(X, P).expand(commutator=True).expand(commutator=True)
Out[111]:
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:
In [7]:
%reload_ext version_information
%version_information numpy, sympy
Out[7]: