Intro to sympy:

  • variables
  • differentiation
  • integration
  • evaluation of symbolic expressions
In [2]:
import sympy as sym
sym.init_printing() # for LaTeX formatted output

import numpy as np

import matplotlib as mpl
import matplotlib.pyplot as plt
In [3]:
# Following is an Ipython magic command that puts figures in the  notebook.
%matplotlib notebook

# M.L. modification of matplotlib defaults
# Changes can also be put in matplotlibrc file, 
# or effected using mpl.rcParams[]
mpl.style.use('classic')
plt.rc('figure', figsize = (6, 4.5))        # Reduces overall size of figures
plt.rc('axes', labelsize=16, titlesize=14)
plt.rc('figure', autolayout = True)         # Adjusts supblot parameters for new size

NOTES

  • Sympy functions, and variables, and even floats aren't the same as numpy/scipy/python analogues. For example

    • sym.exp != sp.exp
  • Sympy has some math functions included, but not full numpy/scipy, as demonstrated in the following cells.

  • Symbols that are going to used as symbolic variable must be declared as such. This is different than in Mathematica.

  • One consequence is that sympy symbolic expressions must be turned into scipy/numpy/python expressions if they are to be evaluated for plotting or numerical results. This is done with the lambdify command.

  • In fall 2019 we're using sympy< 1.4. Documentation and tutorial can be found at http://docs.sympy.org/latest/

  • ML's conclusion as of 9/17/16: Don't mix sympy and scipy/numpy. Do symbolic work with sympy, and then switch by "lambdifying" symbolic exressions, turning them into python functions.

  • sympy does have it's own plotting capabilities for symbolic expressions (matplotlib is a back-end). ML hasn't explored this very deeply; so far just using matplotlib on "lambdified" expressions.

Symbolic variables

Given the way I imported things, the following cell doesn't work.

In [4]:
exp(3.)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-9fe1318e8774> in <module>
----> 1 exp(3.)

NameError: name 'exp' is not defined

This does work.

In [5]:
sym.exp(3.)
Out[5]:
$\displaystyle 20.0855369231877$

And, as in Mathematica, the output of the following cell will be symbolic.

In [6]:
sym.exp(3)
Out[6]:
$\displaystyle e^{3}$

The analogue of Mathematica's Exp[3]//N, or N[Exp[3]], is

In [7]:
sym.exp(3).evalf()  
Out[7]:
$\displaystyle 20.0855369231877$

The analogue of Mathematica's "slash-dot using" syntax Exp[x]/.x->3 is

In [8]:
sym.exp(x).subs({x:3})
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-8-50af8329c15d> in <module>
----> 1 sym.exp(x).subs({x:3})

NameError: name 'x' is not defined

Oops! This is an example of not having declared x to be a symbolic variable. Let's try again.

In sympy, variables that are going to be used as algebraic symbols must be declared as such. Here's an example of a simple declaration:

In [9]:
x = sym.symbols('x')
sym.exp(x).subs({x:3.})
Out[9]:
$\displaystyle 20.0855369231877$
In [10]:
type(x)
Out[10]:
sympy.core.symbol.Symbol

You can control, to some degree, assumptions about the symbolic variables. (As of sympy 1.0, this is still a work in progress for sophisticated assumptions.)

In [11]:
y = sym.symbols('y',negative=True)
(4 - y).is_positive
Out[11]:
True

The variable name used in python code, and the output representation do not have be the same. Here's a built-in example:

In [12]:
sym.pi, sym.E
Out[12]:
$\displaystyle \left( \pi, \ e\right)$
In [13]:
sym.pi.evalf(), sym.E.evalf()
Out[13]:
$\displaystyle \left( 3.14159265358979, \ 2.71828182845905\right)$

Sympy knows how to convert some standard variables to LaTeX output:

In [14]:
Sigma = sym.symbols('Sigma')
Sigma
Out[14]:
$\displaystyle \Sigma$

But you can be more creative:

In [15]:
sigma, sigma_p = sym.symbols('Sigma, \Sigma^{\prime}')
sigma, sigma_p
Out[15]:
$\displaystyle \left( \Sigma, \ \Sigma^{\prime}\right)$

There are other shorter ways to declare symbolic variables, but you lose some of the flexibility demonstrated above. You can import directly from a set of common symbols in the following way:

  • from sympy.abc import w

Integration

Now let's evaluate the following integral:

$$ \int\left[\sin(x y) + \cos(y z)\right]\, dx $$
In [16]:
x,y,z = sym.symbols('x,y,z')
In [17]:
f = sym.sin(x*y) + sym.cos(y*z)  # scipy trig functions won't work!
In [18]:
sym.integrate(f,x)
Out[18]:
$\displaystyle x \cos{\left(y z \right)} + \begin{cases} - \frac{\cos{\left(x y \right)}}{y} & \text{for}\: y \neq 0 \\0 & \text{otherwise} \end{cases}$

Now let's make it a definite integral:

$$ \int_{-1}^1\left[\sin(x y) + \cos(y z)\right]\, dx $$
In [19]:
sym.integrate(f,(x,-1,1))
Out[19]:
$\displaystyle 2 \cos{\left(y z \right)}$

And now a 2-d integral with infinity as a limit:

$$ \int_{-\infty}^\infty\int_{-\infty}^\infty e^{-x^2-y^2}\, dxdy $$
In [20]:
sym.integrate(sym.exp(-x**2 - y**2), \
              (x, -sym.oo, sym.oo), (y, -sym.oo, sym.oo))
Out[20]:
$\displaystyle \pi$

Differentiation

In [21]:
x,y,z = sym.symbols('x,y,z')
In [22]:
g = sym.cos(x)**2
In [23]:
sym.diff(g,x)     # First derivative (or sym.diff(g,x,1))
Out[23]:
$\displaystyle - 2 \sin{\left(x \right)} \cos{\left(x \right)}$
In [24]:
sym.diff(g,x,2)   # Higher order derivative (or sym.diff(g,x,x))
Out[24]:
$\displaystyle 2 \left(\sin^{2}{\left(x \right)} - \cos^{2}{\left(x \right)}\right)$

Evaluate $$\frac{\partial^3}{\partial^2x\partial y} e^{xyz}$$

In [25]:
h = sym.exp(x*y*z)
sym.diff(h,x,x,y)
Out[25]:
$\displaystyle y z^{2} \left(x y z + 2\right) e^{x y z}$
In [26]:
def m(x):
    return 3*x**4
In [27]:
sym.diff(m(x),x)
Out[27]:
$\displaystyle 12 x^{3}$

Evaluating sympy expressions numerically

In [28]:
x,y,z = sym.symbols('x,y,z')

Evaluation at a single point

In [29]:
a = 12*x**3
In [30]:
a.subs(x,2)  # or a.sub({x:2}). In general, the argument is a dictionary
Out[30]:
$\displaystyle 96$
In [31]:
b = a*sym.exp(y)
b
Out[31]:
$\displaystyle 12 x^{3} e^{y}$
In [32]:
b.subs(x,2)
Out[32]:
$\displaystyle 96 e^{y}$
In [33]:
b.subs({x:2,y:sym.log(1/2)})
Out[33]:
$\displaystyle 48.0$

Turn sympy expression into a python function for subsequent use

In [34]:
f = sym.lambdify(x,a)         # Creates a python function f(x)
g = sym.lambdify((x,y),b)     # Creates a python function g(x,y)
In [38]:
xx = np.linspace(-4,4,161) # xx so that it doesn't collide with symbolic x
y = f(xx)
z = g(xx,np.log(1/2))
plt.figure()
plt.plot(xx,y, label='$y$')
plt.plot(xx,z, label='$z$')
plt.xlabel('$x$')
plt.legend();

Version Information

version_information is from J.R. Johansson (jrjohansson at gmail.com)
See Introduction to scientific computing with Python:
http://nbviewer.jupyter.org/github/jrjohansson/scientific-python-lectures/blob/master/Lecture-0-Scientific-Computing-with-Python.ipynb
for more information and instructions for package installation.

If version_information has been installed system wide (as it has been on linuxremotes), continue with next cell as written. If not, comment out top line in next cell and uncomment the second line.

In [35]:
%load_ext version_information

#%install_ext http://raw.github.com/jrjohansson/version_information/master/version_information.py
Loading extensions from ~/.ipython/extensions is deprecated. We recommend managing extensions like any other Python packages, in site-packages.
In [36]:
version_information numpy, sympy, matplotlib
Out[36]:
SoftwareVersion
Python3.7.3 64bit [GCC 7.3.0]
IPython7.5.0
OSLinux 3.10.0 862.14.4.el7.x86_64 x86_64 with redhat 7.5 Maipo
numpy1.16.3
sympy1.4
matplotlib3.0.3
Tue Oct 08 13:19:30 2019 EDT
In [ ]: