This document will give you a brief tour of the capabilities of the IPython notebook.
You can view its contents by scrolling around, or execute each cell by typing Shift-Enter
.
The rest of the notebooks in this directory illustrate various other aspects and capabilities of the IPython notebook; some of them may require additional libraries to be executed.
NOTE: This notebook must be run from its own directory, so you must cd
to this directory and then start the notebook, but do not use the --notebook-dir
option to run it from another location.
The first thing you need to know is that you are still controlling the same old IPython you're used to, so things like shell aliases and magic commands still work:
pwd
u'/home/fperez/ipython/tutorial/notebooks'
ls
animation.m4v P10 Basic Interface.ipynb argv.py P15 Parallel Magics.ipynb cat.py* P20 Multiplexing.ipynb Cell Magics.ipynb P21 LoadBalancing.ipynb Display control.ipynb P30 Working with MPI.ipynb figs/ P99 Summary.ipynb foo.py PX01 Example - Remote Iteration.ipynb lnum.py* python-logo.svg myscript.py PZ Performance.ipynb nb@ soln/ nbtour.ipynb text_analysis.py* P01 Overview and Architecture.ipynb
message = 'The IPython notebook is great!'
# note: the echo command does not run on Windows, it's a unix command.
!echo $message
The IPython notebook is great!
IPython adds an 'inline' matplotlib backend, which embeds any matplotlib figures into the notebook.
%pylab inline
Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline]. For more information, type 'help(pylab)'.
x = linspace(0, 3*pi, 500)
plot(x, sin(x**2))
title('A simple chirp');
You can paste blocks of input with prompt markers, such as those from the official Python tutorial
>>> the_world_is_flat = 1
>>> if the_world_is_flat:
... print "Be careful not to fall off!"
Be careful not to fall off!
Errors are shown in informative ways:
%run non_existent_file
ERROR: File `u'non_existent_file.py'` not found.
x = 1
y = 4
z = y/(1-x)
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-8-dc39888fd1d2> in <module>() 1 x = 1 2 y = 4 ----> 3 z = y/(1-x) ZeroDivisionError: integer division or modulo by zero
When IPython needs to display additional information (such as providing details on an object via x?
it will automatically invoke a pager at the bottom of the screen:
magic
If you execute the next cell, you will see the output arriving as it is generated, not all at the end.
import time, sys
for i in range(8):
print i,
time.sleep(0.5)
0 1 2 3 4 5 6 7
We call the low-level system libc.time routine with the wrong argument via ctypes to segfault the Python interpreter:
import sys
from ctypes import CDLL
# This will crash a Linux or Mac system; equivalent calls can be made on Windows
dll = 'dylib' if sys.platform == 'darwin' else 'so.6'
libc = CDLL("libc.%s" % dll)
libc.time(-1) # BOOM!!
You can italicize, boldface
and embed code meant for illustration instead of execution in Python:
def f(x):
"""a docstring"""
return x**2
or other languages:
if (i=0; i<n; i++) {
printf("hello %d\n", i);
x += 4;
}
Courtesy of MathJax, you can include mathematical expressions both inline: $e^{i\pi} + 1 = 0$ and displayed:
$$e^x=\sum_{i=0}^\infty \frac{1}{i!}x^i$$from IPython.display import Image
Image(filename='figs/logo.png')
An image can also be displayed from raw data or a url
Image(url='http://python.org/images/python-logo.gif')
SVG images are also supported out of the box (since modern browsers do a good job of rendering them):
from IPython.display import SVG
SVG(filename='figs/python-logo.svg')
And more exotic objects can also be displayed, as long as their representation supports the IPython display protocol.
For example, videos hosted externally on YouTube are easy to load (and writing a similar wrapper for other hosted content is trivial):
from IPython.display import YouTubeVideo
# a talk about IPython at Sage Days at U. Washington, Seattle.
# Video credit: William Stein.
YouTubeVideo('1j_HxD4iLn8')
Using the nascent video capabilities of modern browsers, you may also be able to display local videos. At the moment this doesn't work very well in all browsers, so it may or may not work for you; we will continue testing this and looking for ways to make it more robust.
The following cell loads a local file called animation.m4v
, encodes the raw video as base64 for http
transport, and uses the HTML5 video tag to load it. On Chrome 15 it works correctly, displaying a control
bar at the bottom with a play/pause button and a location slider.
from IPython.display import HTML
video = open("figs/animation.m4v", "rb").read()
video_encoded = video.encode("base64")
video_tag = '<video controls alt="test" src="data:video/x-m4v;base64,{0}">'.format(video_encoded)
HTML(data=video_tag)
The above examples embed images and video from the notebook filesystem in the output
areas of code cells. It is also possible to request these files directly in markdown cells
if they reside in the notebook directory via relative urls prefixed with files/
:
files/[subdirectory/]<filename>
For example, in the example notebook folder, we have the Python logo, addressed as:
<img src="files/figs/python-logo.svg" />
and a video with the HTML5 video tag:
<video controls src="files/figs/animation.m4v" />
These do not embed the data into the notebook file, and require that the files exist when you are viewing the notebook.
Note that this means that the IPython notebook server also acts as a generic file server for files inside the same tree as your notebooks. Access is not granted outside the notebook folder so you have strict control over what files are visible, but for this reason it is highly recommended that you do not run the notebook server with a notebook directory at a high level in your filesystem (e.g. your home directory).
When you run the notebook in a password-protected manner, local file access is restricted to authenticated users unless read-only views are active.
You can even embed an entire page from another site in an iframe; for example this is today's Wikipedia page for mobile users:
HTML('<iframe src=http://en.mobile.wikipedia.org/?useformat=mobile width=700 height=350>')
.py
in the dashboard%load
with any local or remote url: the Matplotlib Gallery!In this notebook we've kept the output saved so you can see the result, but you should run the next cell yourself (with an active internet connection).
Let's make sure we have pylab again, in case we have restarted the kernel due to the crash demo above
%pylab inline
Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline]. For more information, type 'help(pylab)'.
%load http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/integral_demo.py
And we also support the display of mathematical expressions typeset in LaTeX, which is rendered in the browser thanks to the MathJax library.
Note that this is different from the above examples. Above we were typing mathematical expressions
in Markdown cells (along with normal text) and letting the browser render them; now we are displaying
the output of a Python computation as a LaTeX expression wrapped by the Math()
object so the browser
renders it. The Math
object will add the needed LaTeX delimiters ($$
) if they are not provided:
from IPython.display import Math
Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')
With the Latex
class, you have to include the delimiters yourself. This allows you to use other LaTeX modes such as eqnarray
:
from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{eqnarray}""")
Using these tools, we can integrate with the SymPy package to perform symbolic manipulations, and combined with numpy and matplotlib, also displays numerical visualizations of symbolically constructed expressions.
We first load sympy printing and plotting support, as well as all of sympy:
%load_ext sympyprinting
%pylab inline
from __future__ import division
import sympy as sym
from sympy import *
x, y, z = symbols("x y z")
k, m, n = symbols("k m n", integer=True)
f, g, h = map(Function, 'fgh')
Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline]. For more information, type 'help(pylab)'.
Rational(3,2)*pi + exp(I*x) / (x**2 + y)
exp(I*x).subs(x,pi).evalf()
exp(pi * sqrt(163)).evalf(50)
eq = ((x+y)**2 * (x+1))
eq
expand(eq)
a = 1/x + (x*sin(x) - 1)/x
a
simplify(a)
limit((sin(x)-x)/x**3, x, 0)
(1/cos(x)).series(x, 0, 6)
diff(cos(x**2)**2 / (1+x), x)
integrate(x**2 * cos(x), (x, 0, pi/2))
eqn = Eq(Derivative(f(x),x,x) + 9*f(x), 1)
display(eqn)
dsolve(eqn, f(x))
We will define a function to compute the Taylor series expansions of a symbolically defined expression at various orders and visualize all the approximations together with the original function
def plot_taylor_approximations(func, x0=None, orders=(2, 4), xrange=(0,1), yrange=None, npts=200):
"""Plot the Taylor series approximations to a function at various orders.
Parameters
----------
func : a sympy function
x0 : float
Origin of the Taylor series expansion. If not given, x0=xrange[0].
orders : list
List of integers with the orders of Taylor series to show. Default is (2, 4).
xrange : 2-tuple or array.
Either an (xmin, xmax) tuple indicating the x range for the plot (default is (0, 1)),
or the actual array of values to use.
yrange : 2-tuple
(ymin, ymax) tuple indicating the y range for the plot. If not given,
the full range of values will be automatically used.
npts : int
Number of points to sample the x range with. Default is 200.
"""
if not callable(func):
raise ValueError('func must be callable')
if isinstance(xrange, (list, tuple)):
x = np.linspace(float(xrange[0]), float(xrange[1]), npts)
else:
x = xrange
if x0 is None: x0 = x[0]
xs = sym.Symbol('x')
# Make a numpy-callable form of the original function for plotting
fx = func(xs)
f = sym.lambdify(xs, fx, modules=['numpy'])
# We could use latex(fx) instead of str(), but matploblib gets confused
# with some of the (valid) latex constructs sympy emits. So we play it safe.
plot(x, f(x), label=str(fx), lw=2)
# Build the Taylor approximations, plotting as we go
apps = {}
for order in orders:
app = fx.series(xs, x0, n=order).removeO()
apps[order] = app
# Must be careful here: if the approximation is a constant, we can't
# blindly use lambdify as it won't do the right thing. In that case,
# evaluate the number as a float and fill the y array with that value.
if isinstance(app, sym.numbers.Number):
y = np.zeros_like(x)
y.fill(app.evalf())
else:
fa = sym.lambdify(xs, app, modules=['numpy'])
y = fa(x)
tex = sym.latex(app).replace('$', '')
plot(x, y, label=r'$n=%s:\, %s$' % (order, tex) )
# Plot refinements
if yrange is not None:
plt.ylim(*yrange)
grid()
legend(loc='best').get_frame().set_alpha(0.8)
With this function defined, we can now use it for any sympy function or expression
plot_taylor_approximations(sin, 0, [2, 4, 6], (0, 2*pi), (-2,2))
plot_taylor_approximations(cos, 0, [2, 4, 6], (0, 2*pi), (-2,2))
Remember that a Taylor series is useless beyond its convergence radius, as can be nicely illustrated by
a simple function that has singularities on the real axis. Use the plot_taylor_approximations
function to show how badly various orders (say $n= 2, 4, 6$) converge for $f(x) = \frac{1}{\cos(x)}$.