Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
Loading items

Target

Select target project
  • jupyter4jsc/j4j_notebooks
  • kreuzer1/j4j_notebooks
  • goebbert1/j4j_notebooks
3 results
Select Git revision
Loading items
Show changes

Commits on Source 165

65 additional commits have been omitted to prevent performance issues.
Showing
with 129 additions and 10981 deletions
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
\ No newline at end of file
%% Cell type:markdown id: tags:
# Simple Animations Using clear_output
%% Cell type:markdown id: tags:
Sometimes you want to clear the output area in the middle of a calculation. This can be useful for doing simple animations. In terminals, there is the carriage-return (`'\r'`) for overwriting a single line, but the notebook frontend can clear the whole output area, not just a single line.
To clear output in the Notebook you can use the `clear_output()` function. If you are clearing the output every frame of an animation, calling `clear_output()` will create noticeable flickering. You can use `clear_output(wait=True)` to add the *clear_output* call to a queue. When data becomes available to replace the existing output, the *clear_output* will be called immediately before the new data is added. This avoids the flickering by not rendering the cleared output to the screen.
%% Cell type:markdown id: tags:
## Simple example
%% Cell type:markdown id: tags:
Here we show our progress iterating through a list:
%% Cell type:code id: tags:
``` python
import sys
import time
```
%% Cell type:code id: tags:
``` python
from IPython.display import display, clear_output
for i in range(10):
time.sleep(0.25)
clear_output(wait=True)
print(i)
sys.stdout.flush()
```
%% Output
9
%% Cell type:markdown id: tags:
## AsyncResult.wait_interactive
%% Cell type:markdown id: tags:
The AsyncResult object has a special `wait_interactive()` method, which prints its progress interactively,
so you can watch as your parallel computation completes.
**This example assumes you have an IPython cluster running, which you can start from the [cluster panel](/#clusters)**
%% Cell type:code id: tags:
``` python
#from IPython import parallel
#rc = parallel.Client()
#view = rc.load_balanced_view()
#
#amr = view.map_async(time.sleep, [0.5]*100)
#
#amr.wait_interactive()
```
%% Cell type:markdown id: tags:
## Matplotlib example
%% Cell type:markdown id: tags:
You can also use `clear_output()` to clear figures and plots.
%% Cell type:code id: tags:
``` python
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
```
%% Cell type:code id: tags:
``` python
from scipy.special import jn
x = np.linspace(0,5)
f, ax = plt.subplots()
ax.set_title("Bessel functions")
for n in range(1,10):
time.sleep(1)
ax.plot(x, jn(x,n))
clear_output(wait=True)
display(f)
# close the figure at the end, so we don't get a duplicate
# of the last plot
plt.close()
```
%% Output
%% Cell type:code id: tags:
``` python
```
Source diff could not be displayed: it is too large. Options to address this: view the blob.
%% Cell type:markdown id: tags:
# Capturing Output With <tt>%%capture</tt>
%% Cell type:markdown id: tags:
IPython has a [cell magic](Cell Magics.ipynb), `%%capture`, which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable.
%% Cell type:code id: tags:
``` python
from __future__ import print_function
import sys
```
%% Cell type:markdown id: tags:
By default, `%%capture` discards these streams. This is a simple way to suppress unwanted output.
%% Cell type:code id: tags:
``` python
%%capture
print('hi, stdout')
print('hi, stderr', file=sys.stderr)
```
%% Cell type:markdown id: tags:
If you specify a name, then stdout/stderr will be stored in an object in your namespace.
%% Cell type:code id: tags:
``` python
%%capture captured
print('hi, stdout')
print('hi, stderr', file=sys.stderr)
```
%% Cell type:code id: tags:
``` python
captured
```
%% Output
<IPython.utils.capture.CapturedIO at 0x1076c9310>
%% Cell type:markdown id: tags:
Calling the object writes the output to stdout/stderr as appropriate.
%% Cell type:code id: tags:
``` python
captured()
```
%% Output
hi, stdout
hi, stderr
%% Cell type:code id: tags:
``` python
captured.stdout
```
%% Output
'hi, stdout\n'
%% Cell type:code id: tags:
``` python
captured.stderr
```
%% Output
'hi, stderr\n'
%% Cell type:markdown id: tags:
`%%capture` grabs all output types, not just stdout/stderr, so you can do plots and use IPython's display system inside `%%capture`
%% Cell type:code id: tags:
``` python
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
```
%% Cell type:code id: tags:
``` python
%%capture wontshutup
print("setting up X")
x = np.linspace(0,5,1000)
print("step 2: constructing y-data")
y = np.sin(x)
print("step 3: display info about y")
plt.plot(x,y)
print("okay, I'm done now")
```
%% Cell type:code id: tags:
``` python
wontshutup()
```
%% Output
setting up X
step 2: constructing y-data
step 3: display info about y
okay, I'm done now
%% Cell type:markdown id: tags:
And you can selectively disable capturing stdout, stderr or rich display, by passing `--no-stdout`, `--no-stderr` and `--no-display`
%% Cell type:code id: tags:
``` python
%%capture cap --no-stderr
print('hi, stdout')
print("hello, stderr", file=sys.stderr)
```
%% Output
hello, stderr
%% Cell type:code id: tags:
``` python
cap.stdout
```
%% Output
'hi, stdout\n'
%% Cell type:code id: tags:
``` python
cap.stderr
```
%% Output
''
%% Cell type:code id: tags:
``` python
cap.outputs
```
%% Output
[]
%% Cell type:markdown id: tags:
# Custom Display Logic
%% Cell type:markdown id: tags:
## Overview
%% Cell type:markdown id: tags:
As described in the [Rich Output](Rich Output.ipynb) tutorial, the IPython display system can display rich representations of objects in the following formats:
* JavaScript
* HTML
* PNG
* JPEG
* SVG
* LaTeX
* PDF
This Notebook shows how you can add custom display logic to your own classes, so that they can be displayed using these rich representations. There are two ways of accomplishing this:
1. Implementing special display methods such as `_repr_html_` when you define your class.
2. Registering a display function for a particular existing class.
This Notebook describes and illustrates both approaches.
%% Cell type:markdown id: tags:
Import the IPython display functions.
%% Cell type:code id: tags:
``` python
from IPython.display import (
display, display_html, display_png, display_svg
)
```
%% Cell type:markdown id: tags:
Parts of this notebook need the matplotlib inline backend:
%% Cell type:code id: tags:
``` python
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
```
%% Cell type:markdown id: tags:
## Special display methods
%% Cell type:markdown id: tags:
The main idea of the first approach is that you have to implement special display methods when you define your class, one for each representation you want to use. Here is a list of the names of the special methods and the values they must return:
* `_repr_html_`: return raw HTML as a string
* `_repr_json_`: return a JSONable dict
* `_repr_jpeg_`: return raw JPEG data
* `_repr_png_`: return raw PNG data
* `_repr_svg_`: return raw SVG data as a string
* `_repr_latex_`: return LaTeX commands in a string surrounded by "$".
%% Cell type:markdown id: tags:
As an illustration, we build a class that holds data generated by sampling a Gaussian distribution with given mean and standard deviation. Here is the definition of the `Gaussian` class, which has a custom PNG and LaTeX representation.
%% Cell type:code id: tags:
``` python
from IPython.core.pylabtools import print_figure
from IPython.display import Image, SVG, Math
class Gaussian(object):
"""A simple object holding data sampled from a Gaussian distribution.
"""
def __init__(self, mean=0.0, std=1, size=1000):
self.data = np.random.normal(mean, std, size)
self.mean = mean
self.std = std
self.size = size
# For caching plots that may be expensive to compute
self._png_data = None
def _figure_data(self, format):
fig, ax = plt.subplots()
ax.hist(self.data, bins=50)
ax.set_title(self._repr_latex_())
ax.set_xlim(-10.0,10.0)
data = print_figure(fig, format)
# We MUST close the figure, otherwise IPython's display machinery
# will pick it up and send it as output, resulting in a double display
plt.close(fig)
return data
def _repr_png_(self):
if self._png_data is None:
self._png_data = self._figure_data('png')
return self._png_data
def _repr_latex_(self):
return r'$\mathcal{N}(\mu=%.2g, \sigma=%.2g),\ N=%d$' % (self.mean,
self.std, self.size)
```
%% Cell type:markdown id: tags:
Create an instance of the Gaussian distribution and return it to display the default representation:
%% Cell type:code id: tags:
``` python
x = Gaussian(2.0, 1.0)
x
```
%% Output
$\mathcal{N}(\mu=2, \sigma=1),\ N=1000$
<__main__.Gaussian at 0x10665a4e0>
%% Cell type:markdown id: tags:
You can also pass the object to the `display` function to display the default representation:
%% Cell type:code id: tags:
``` python
display(x)
```
%% Output
$\mathcal{N}(\mu=2, \sigma=1),\ N=1000$
%% Cell type:markdown id: tags:
Use `display_png` to view the PNG representation:
%% Cell type:code id: tags:
``` python
display_png(x)
```
%% Output
%% Cell type:markdown id: tags:
<div class="alert alert-success">
It is important to note a subtle different between <code>display</code> and <code>display_png</code>. The former computes <em>all</em> representations of the object, and lets the notebook UI decide which to display. The later only computes the PNG representation.
</div>
%% Cell type:markdown id: tags:
Create a new Gaussian with different parameters:
%% Cell type:code id: tags:
``` python
x2 = Gaussian(0, 2, 2000)
x2
```
%% Output
$\mathcal{N}(\mu=0, \sigma=2),\ N=2000$
<__main__.Gaussian at 0x106ab8c18>
%% Cell type:markdown id: tags:
You can then compare the two Gaussians by displaying their histograms:
%% Cell type:code id: tags:
``` python
display_png(x)
display_png(x2)
```
%% Output
%% Cell type:markdown id: tags:
Note that like `print`, you can call any of the `display` functions multiple times in a cell.
%% Cell type:markdown id: tags:
## Adding IPython display support to existing objects
%% Cell type:markdown id: tags:
When you are directly writing your own classes, you can adapt them for display in IPython by following the above approach. But in practice, you often need to work with existing classes that you can't easily modify. We now illustrate how to add rich output capabilities to existing objects. We will use the NumPy polynomials and change their default representation to be a formatted LaTeX expression.
%% Cell type:markdown id: tags:
First, consider how a NumPy polynomial object renders by default:
%% Cell type:code id: tags:
``` python
p = np.polynomial.Polynomial([1,2,3], [-10, 10])
p
```
%% Output
Polynomial([ 1., 2., 3.], [-10., 10.], [-1, 1])
%% Cell type:markdown id: tags:
Next, define a function that pretty-prints a polynomial as a LaTeX string:
%% Cell type:code id: tags:
``` python
def poly_to_latex(p):
terms = ['%.2g' % p.coef[0]]
if len(p) > 1:
term = 'x'
c = p.coef[1]
if c!=1:
term = ('%.2g ' % c) + term
terms.append(term)
if len(p) > 2:
for i in range(2, len(p)):
term = 'x^%d' % i
c = p.coef[i]
if c!=1:
term = ('%.2g ' % c) + term
terms.append(term)
px = '$P(x)=%s$' % '+'.join(terms)
dom = r', $x \in [%.2g,\ %.2g]$' % tuple(p.domain)
return px+dom
```
%% Cell type:markdown id: tags:
This produces, on our polynomial ``p``, the following:
%% Cell type:code id: tags:
``` python
poly_to_latex(p)
```
%% Output
'$P(x)=1+2 x+3 x^2$, $x \\in [-10,\\ 10]$'
%% Cell type:markdown id: tags:
You can render this string using the `Latex` class:
%% Cell type:code id: tags:
``` python
from IPython.display import Latex
Latex(poly_to_latex(p))
```
%% Output
$P(x)=1+2 x+3 x^2$, $x \in [-10,\ 10]$
<IPython.core.display.Latex object>
%% Cell type:markdown id: tags:
However, you can configure IPython to do this automatically by registering the `Polynomial` class and the `poly_to_latex` function with an IPython display formatter. Let's look at the default formatters provided by IPython:
%% Cell type:code id: tags:
``` python
ip = get_ipython()
for mime, formatter in ip.display_formatter.formatters.items():
print('%24s : %s' % (mime, formatter.__class__.__name__))
```
%% Output
image/png : PNGFormatter
application/pdf : PDFFormatter
text/html : HTMLFormatter
image/jpeg : JPEGFormatter
text/plain : PlainTextFormatter
text/markdown : MarkdownFormatter
application/json : JSONFormatter
application/javascript : JavascriptFormatter
text/latex : LatexFormatter
image/svg+xml : SVGFormatter
%% Cell type:markdown id: tags:
The `formatters` attribute is a dictionary keyed by MIME types. To define a custom LaTeX display function, you want a handle on the `text/latex` formatter:
%% Cell type:code id: tags:
``` python
ip = get_ipython()
latex_f = ip.display_formatter.formatters['text/latex']
```
%% Cell type:markdown id: tags:
The formatter object has a couple of methods for registering custom display functions for existing types.
%% Cell type:code id: tags:
``` python
help(latex_f.for_type)
```
%% Output
Help on method for_type in module IPython.core.formatters:
for_type(typ, func=None) method of IPython.core.formatters.LatexFormatter instance
Add a format function for a given type.
Parameters
-----------
typ : type or '__module__.__name__' string for a type
The class of the object that will be formatted using `func`.
func : callable
A callable for computing the format data.
`func` will be called with the object to be formatted,
and will return the raw data in this formatter's format.
Subclasses may use a different call signature for the
`func` argument.
If `func` is None or not specified, there will be no change,
only returning the current value.
Returns
-------
oldfunc : callable
The currently registered callable.
If you are registering a new formatter,
this will be the previous value (to enable restoring later).
%% Cell type:code id: tags:
``` python
help(latex_f.for_type_by_name)
```
%% Output
Help on method for_type_by_name in module IPython.core.formatters:
for_type_by_name(type_module, type_name, func=None) method of IPython.core.formatters.LatexFormatter instance
Add a format function for a type specified by the full dotted
module and name of the type, rather than the type of the object.
Parameters
----------
type_module : str
The full dotted name of the module the type is defined in, like
``numpy``.
type_name : str
The name of the type (the class name), like ``dtype``
func : callable
A callable for computing the format data.
`func` will be called with the object to be formatted,
and will return the raw data in this formatter's format.
Subclasses may use a different call signature for the
`func` argument.
If `func` is None or unspecified, there will be no change,
only returning the current value.
Returns
-------
oldfunc : callable
The currently registered callable.
If you are registering a new formatter,
this will be the previous value (to enable restoring later).
%% Cell type:markdown id: tags:
In this case, we will use `for_type_by_name` to register `poly_to_latex` as the display function for the `Polynomial` type:
%% Cell type:code id: tags:
``` python
latex_f.for_type_by_name('numpy.polynomial.polynomial',
'Polynomial', poly_to_latex)
```
%% Cell type:markdown id: tags:
Once the custom display function has been registered, all NumPy `Polynomial` instances will be represented by their LaTeX form instead:
%% Cell type:code id: tags:
``` python
p
```
%% Output
$P(x)=1+2 x+3 x^2$, $x \in [-10,\ 10]$
Polynomial([ 1., 2., 3.], [-10., 10.], [-1, 1])
%% Cell type:code id: tags:
``` python
p2 = np.polynomial.Polynomial([-20, 71, -15, 1])
p2
```
%% Output
$P(x)=-20+71 x+-15 x^2+x^3$, $x \in [-1,\ 1]$
Polynomial([-20., 71., -15., 1.], [-1, 1], [-1, 1])
%% Cell type:markdown id: tags:
## More complex display with `_ipython_display_`
%% Cell type:markdown id: tags:
Rich output special methods and functions can only display one object or MIME type at a time. Sometimes this is not enough if you want to display multiple objects or MIME types at once. An example of this would be to use an HTML representation to put some HTML elements in the DOM and then use a JavaScript representation to add events to those elements.
**IPython 2.0** recognizes another display method, `_ipython_display_`, which allows your objects to take complete control of displaying themselves. If this method is defined, IPython will call it, and make no effort to display the object using the above described `_repr_*_` methods for custom display functions. It's a way for you to say "Back off, IPython, I can display this myself." Most importantly, your `_ipython_display_` method can make multiple calls to the top-level `display` functions to accomplish its goals.
Here is an object that uses `display_html` and `display_javascript` to make a plot using the [Flot](http://www.flotcharts.org/) JavaScript plotting library:
%% Cell type:code id: tags:
``` python
import json
import uuid
from IPython.display import display_javascript, display_html, display
class FlotPlot(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.uuid = str(uuid.uuid4())
def _ipython_display_(self):
json_data = json.dumps(list(zip(self.x, self.y)))
display_html('<div id="{}" style="height: 300px; width:80%;"></div>'.format(self.uuid),
raw=True
)
display_javascript("""
require(["//cdnjs.cloudflare.com/ajax/libs/flot/0.8.2/jquery.flot.min.js"], function() {
var line = JSON.parse("%s");
console.log(line);
$.plot("#%s", [line]);
});
""" % (json_data, self.uuid), raw=True)
```
%% Cell type:code id: tags:
``` python
import numpy as np
x = np.linspace(0,10)
y = np.sin(x)
FlotPlot(x, np.sin(x))
```
%% Output
Source diff could not be displayed: it is too large. Options to address this: view the blob.
%% Cell type:markdown id: tags:
# Using `raw_input` and `%debug` in the Notebook
%% Cell type:markdown id: tags:
The Notebook has added support for `raw_input` and `%debug`, as of 1.0.
%% Cell type:code id: tags:
``` python
# Python 3 compat
import sys
if sys.version_info[0] >= 3:
raw_input = input
```
%% Cell type:code id: tags:
``` python
name = 'John' # raw_input("What is your name? ")
name
```
%% Output
What is your name? bla
'bla'
%% Cell type:code id: tags:
``` python
def div(x, y):
return x/y
# div(1,0)
```
%% Output
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-4-a5097cc0c0c5> in <module>()
2 return x/y
3
----> 4 div(1,0)
<ipython-input-4-a5097cc0c0c5> in div(x, y)
1 def div(x, y):
----> 2 return x/y
3
4 div(1,0)
ZeroDivisionError: division by zero
%% Cell type:code id: tags:
``` python
%debug
```
%% Output
> <ipython-input-4-a5097cc0c0c5>(2)div()
 1 def div(x, y):
----> 2  return x/y
 3 

ipdb> x
1
ipdb> y
0
ipdb> bt
<ipython-input-4-a5097cc0c0c5>(4)<module>()
 1 def div(x, y):
 2  return x/y
 3 
----> 4 div(1,0)

> <ipython-input-4-a5097cc0c0c5>(2)div()
 1 def div(x, y):
----> 2  return x/y
 3 
 4 div(1,0)

ipdb> exit
Source diff could not be displayed: it is too large. Options to address this: view the blob.
%% Cell type:markdown id: tags:
# SymPy: Open Source Symbolic Mathematics
This notebook uses the [SymPy](http://sympy.org) package to perform symbolic manipulations,
and combined with numpy and matplotlib, also displays numerical visualizations of symbolically
constructed expressions.
We first load sympy printing extensions, as well as all of sympy:
%% Cell type:code id: tags:
``` python
from IPython.display import display
from sympy.interactive import printing
printing.init_printing(use_latex='mathjax')
import sympy as sym
x, y, z = sym.symbols("x y z")
k, m, n = sym.symbols("k m n", integer=True)
f, g, h = map(sym.Function, 'fgh')
```
%% Cell type:markdown id: tags:
<h2>Elementary operations</h2>
%% Cell type:code id: tags:
``` python
sym.Rational(3,2)*sym.pi + sym.exp(sym.I*x) / (x**2 + y)
```
%% Output
$$\frac{3 \pi}{2} + \frac{e^{i x}}{x^{2} + y}$$
ⅈ⋅x
3⋅π ℯ
─── + ──────
2 2
x + y
%% Cell type:code id: tags:
``` python
sym.exp(sym.I*x).subs(x,sym.pi).evalf()
```
%% Output
$$-1.0$$
-1.00000000000000
%% Cell type:code id: tags:
``` python
e = x + 2*y
```
%% Cell type:code id: tags:
``` python
sym.srepr(e)
```
%% Output
"Add(Symbol('x'), Mul(Integer(2), Symbol('y')))"
%% Cell type:code id: tags:
``` python
sym.exp(sym.pi * sym.sqrt(163)).evalf(50)
```
%% Output
$$262537412640768743.99999999999925007259719818568888$$
262537412640768743.99999999999925007259719818568888
%% Cell type:markdown id: tags:
<h2>Algebra<h2>
%% Cell type:code id: tags:
``` python
eq = ((x+y)**2 * (x+1))
eq
```
%% Output
$$\left(x + 1\right) \left(x + y\right)^{2}$$
2
(x + 1)⋅(x + y)
%% Cell type:code id: tags:
``` python
sym.expand(eq)
```
%% Output
$$x^{3} + 2 x^{2} y + x^{2} + x y^{2} + 2 x y + y^{2}$$
3 2 2 2 2
x + 2⋅x ⋅y + x + x⋅y + 2⋅x⋅y + y
%% Cell type:code id: tags:
``` python
a = 1/x + (x*sym.sin(x) - 1)/x
a
```
%% Output
$$\frac{x \sin{\left (x \right )} - 1}{x} + \frac{1}{x}$$
x⋅sin(x) - 1 1
──────────── + ─
x x
%% Cell type:code id: tags:
``` python
sym.simplify(a)
```
%% Output
$$\sin{\left (x \right )}$$
sin(x)
%% Cell type:code id: tags:
``` python
eq = sym.Eq(x**3 + 2*x**2 + 4*x + 8, 0)
eq
```
%% Output
$$x^{3} + 2 x^{2} + 4 x + 8 = 0$$
3 2
x + 2⋅x + 4⋅x + 8 = 0
%% Cell type:code id: tags:
``` python
sym.solve(eq, x)
```
%% Output
$$\left [ -2, \quad - 2 i, \quad 2 i\right ]$$
[-2, -2⋅ⅈ, 2⋅ⅈ]
%% Cell type:code id: tags:
``` python
a, b = sym.symbols('a b')
sym.Sum(6*n**2 + 2**n, (n, a, b))
```
%% Output
$$\sum_{n=a}^{b} \left(2^{n} + 6 n^{2}\right)$$
b
___
╲ ⎛ n 2⎞
╱ ⎝2 + 6⋅n ⎠
‾‾‾
n = a
%% Cell type:markdown id: tags:
<h2>Calculus</h2>
%% Cell type:code id: tags:
``` python
sym.limit((sym.sin(x)-x)/x**3, x, 0)
```
%% Output
$$- \frac{1}{6}$$
-1/6
%% Cell type:code id: tags:
``` python
(1/sym.cos(x)).series(x, 0, 6)
```
%% Output
$$1 + \frac{x^{2}}{2} + \frac{5 x^{4}}{24} + O\left(x^{6}\right)$$
2 4
x 5⋅x ⎛ 6⎞
1 + ── + ──── + O⎝x ⎠
2 24
%% Cell type:code id: tags:
``` python
sym.diff(sym.cos(x**2)**2 / (1+x), x)
```
%% Output
$$- \frac{4 x \sin{\left (x^{2} \right )} \cos{\left (x^{2} \right )}}{x + 1} - \frac{\cos^{2}{\left (x^{2} \right )}}{\left(x + 1\right)^{2}}$$
⎛ 2⎞ ⎛ 2⎞ 2⎛ 2⎞
4⋅x⋅sin⎝x ⎠⋅cos⎝x ⎠ cos ⎝x ⎠
- ─────────────────── - ────────
x + 1 2
(x + 1)
%% Cell type:code id: tags:
``` python
sym.integrate(x**2 * sym.cos(x), (x, 0, sym.pi/2))
```
%% Output
$$-2 + \frac{\pi^{2}}{4}$$
2
π
-2 + ──
4
%% Cell type:code id: tags:
``` python
eqn = sym.Eq(sym.Derivative(f(x),x,x) + 9*f(x), 1)
display(eqn)
sym.dsolve(eqn, f(x))
```
%% Output
$$9 f{\left (x \right )} + \frac{d^{2}}{d x^{2}} f{\left (x \right )} = 1$$
$$f{\left (x \right )} = C_{1} \sin{\left (3 x \right )} + C_{2} \cos{\left (3 x \right )} + \frac{1}{9}$$
f(x) = C₁⋅sin(3⋅x) + C₂⋅cos(3⋅x) + 1/9
%% Cell type:markdown id: tags:
# Illustrating Taylor series
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
%% Cell type:code id: tags:
``` python
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
```
%% Cell type:code id: tags:
``` python
# You can change the default figure size to be a bit larger if you want,
# uncomment the next line for that:
#plt.rc('figure', figsize=(10, 6))
```
%% Cell type:code id: tags:
``` python
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.
plt.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('$', '')
plt.plot(x, y, label=r'$n=%s:\, %s$' % (order, tex) )
# Plot refinements
if yrange is not None:
plt.ylim(*yrange)
plt.grid()
plt.legend(loc='best').get_frame().set_alpha(0.8)
```
%% Cell type:markdown id: tags:
With this function defined, we can now use it for any sympy function or expression
%% Cell type:code id: tags:
``` python
plot_taylor_approximations(sym.sin, 0, [2, 4, 6], (0, 2*sym.pi), (-2,2))
```
%% Output
%% Cell type:code id: tags:
``` python
plot_taylor_approximations(sym.cos, 0, [2, 4, 6], (0, 2*sym.pi), (-2,2))
```
%% Output
%% Cell type:markdown id: tags:
This shows easily how a Taylor series is useless beyond its convergence radius, illustrated by
a simple function that has singularities on the real axis:
%% Cell type:code id: tags:
``` python
# For an expression made from elementary functions, we must first make it into
# a callable function, the simplest way is to use the Python lambda construct.
plot_taylor_approximations(lambda x: 1/sym.cos(x), 0, [2,4,6], (0, 2*sym.pi), (-5,5))
```
%% Output
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
# Working With External Code
%% Cell type:markdown id: tags:
The IPython Kernel makes it easy to incorporate external code from sources such as the internet or copy/paste.
%% Cell type:markdown id: tags:
## Pasting code into cells
%% Cell type:markdown id: tags:
You can copy and paste code from other sources directly into cells. Pasting code with `>>>` prompts works as expected:
%% Cell type:code id: tags:
``` python
>>> the_world_is_flat = 1
>>> if the_world_is_flat:
... print("Be careful not to fall off!")
```
%% Output
Be careful not to fall off!
%% Cell type:markdown id: tags:
## The %load magic
%% Cell type:markdown id: tags:
The `%load` magic lets you load code from URLs or local files:
%% Cell type:code id: tags:
``` python
%load?
```
%% Cell type:code id: tags:
``` python
%matplotlib inline
```
%% Cell type:code id: tags:
``` python
%load http://matplotlib.org/mpl_examples/showcase/integral_demo.py
```
%% Cell type:code id: tags:
``` python
# %load http://matplotlib.org/mpl_examples/showcase/integral_demo.py
"""
Plot demonstrating the integral as the area under a curve.
Although this is a simple example, it demonstrates some important tweaks:
* A simple line plot with custom color and line width.
* A shaded region created using a Polygon patch.
* A text label with mathtext rendering.
* figtext calls to label the x- and y-axes.
* Use of axis spines to hide the top and right spines.
* Custom tick placement and labels.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
def func(x):
return (x - 3) * (x - 5) * (x - 7) + 85
a, b = 2, 9 # integral limits
x = np.linspace(0, 10)
y = func(x)
fig, ax = plt.subplots()
plt.plot(x, y, 'r', linewidth=2)
plt.ylim(ymin=0)
# Make the shaded region
ix = np.linspace(a, b)
iy = func(ix)
verts = [(a, 0)] + list(zip(ix, iy)) + [(b, 0)]
poly = Polygon(verts, facecolor='0.9', edgecolor='0.5')
ax.add_patch(poly)
plt.text(0.5 * (a + b), 30, r"$\int_a^b f(x)\mathrm{d}x$",
horizontalalignment='center', fontsize=20)
plt.figtext(0.9, 0.05, '$x$')
plt.figtext(0.1, 0.9, '$y$')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
ax.set_xticks((a, b))
ax.set_xticklabels(('$a$', '$b$'))
ax.set_yticks([])
plt.show()
```
%% Output
%% Cell type:markdown id: tags:
# Exploring Beat Frequencies using the `Audio` Object
%% Cell type:markdown id: tags:
This example uses the `Audio` object and Matplotlib to explore the phenomenon of beat frequencies.
%% Cell type:code id: tags:
``` python
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
```
%% Cell type:code id: tags:
``` python
from ipywidgets import interactive
from IPython.display import Audio, display
import numpy as np
```
%% Output
:0: FutureWarning: IPython widgets are experimental and may change in the future.
%% Cell type:code id: tags:
``` python
def beat_freq(f1=220.0, f2=224.0):
max_time = 3
rate = 8000
times = np.linspace(0,max_time,rate*max_time)
signal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)
print(f1, f2, abs(f1-f2))
display(Audio(data=signal, rate=rate))
return signal
```
%% Cell type:code id: tags:
``` python
v = interactive(beat_freq, f1=(200.0,300.0), f2=(200.0,300.0))
display(v)
```
%% Output
220.0 224.0 4.0
%% Cell type:code id: tags:
``` python
v.kwargs
```
%% Output
{'f1': 220.0, 'f2': 224.0}
%% Cell type:code id: tags:
``` python
f1, f2 = v.children
f1.value = 255
f2.value = 260
plt.plot(v.result[0:6000])
```
%% Output
255.0 260.0 5.0
[<matplotlib.lines.Line2D at 0x7fbde2a61860>]
%% Cell type:markdown id: tags:
# Exploring the Lorenz System of Differential Equations
%% Cell type:markdown id: tags:
In this Notebook we explore the Lorenz system of differential equations:
$$
\begin{aligned}
\dot{x} & = \sigma(y-x) \\
\dot{y} & = \rho x - y - xz \\
\dot{z} & = -\beta z + xy
\end{aligned}
$$
This is one of the classic systems in non-linear differential equations. It exhibits a range of different behaviors as the parameters ($\sigma$, $\beta$, $\rho$) are varied.
%% Cell type:markdown id: tags:
## Imports
%% Cell type:markdown id: tags:
First, we import the needed things from IPython, NumPy, Matplotlib and SciPy.
%% Cell type:code id: tags:
``` python
%matplotlib inline
```
%% Cell type:code id: tags:
``` python
from ipywidgets import interact, interactive
from IPython.display import clear_output, display, HTML
```
%% Cell type:code id: tags:
``` python
import numpy as np
from scipy import integrate
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import cnames
from matplotlib import animation
```
%% Cell type:markdown id: tags:
## Computing the trajectories and plotting the result
%% Cell type:markdown id: tags:
We define a function that can integrate the differential equations numerically and then plot the solutions. This function has arguments that control the parameters of the differential equation ($\sigma$, $\beta$, $\rho$), the numerical integration (`N`, `max_time`) and the visualization (`angle`).
%% Cell type:code id: tags:
``` python
def solve_lorenz(N=10, angle=0.0, max_time=4.0, sigma=10.0, beta=8./3, rho=28.0):
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], projection='3d')
ax.axis('off')
# prepare the axes limits
ax.set_xlim((-25, 25))
ax.set_ylim((-35, 35))
ax.set_zlim((5, 55))
def lorenz_deriv(x_y_z, t0, sigma=sigma, beta=beta, rho=rho):
"""Compute the time-derivative of a Lorenz system."""
x, y, z = x_y_z
return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z]
# Choose random starting points, uniformly distributed from -15 to 15
np.random.seed(1)
x0 = -15 + 30 * np.random.random((N, 3))
# Solve for the trajectories
t = np.linspace(0, max_time, int(250*max_time))
x_t = np.asarray([integrate.odeint(lorenz_deriv, x0i, t)
for x0i in x0])
# choose a different color for each trajectory
colors = plt.cm.jet(np.linspace(0, 1, N))
for i in range(N):
x, y, z = x_t[i,:,:].T
lines = ax.plot(x, y, z, '-', c=colors[i])
plt.setp(lines, linewidth=2)
ax.view_init(30, angle)
plt.show()
return t, x_t
```
%% Cell type:markdown id: tags:
Let's call the function once to view the solutions. For this set of parameters, we see the trajectories swirling around two points, called attractors.
%% Cell type:code id: tags:
``` python
t, x_t = solve_lorenz(angle=0, N=10)
```
%% Output
%% Cell type:markdown id: tags:
Using IPython's `interactive` function, we can explore how the trajectories behave as we change the various parameters.
%% Cell type:code id: tags:
``` python
w = interactive(solve_lorenz, angle=(0.,360.), N=(0,50), sigma=(0.0,50.0), rho=(0.0,50.0))
display(w)
```
%% Output
%% Cell type:markdown id: tags:
The object returned by `interactive` is a `Widget` object and it has attributes that contain the current result and arguments:
%% Cell type:code id: tags:
``` python
t, x_t = w.result
```
%% Cell type:code id: tags:
``` python
w.kwargs
```
%% Output
{'N': 10,
'angle': 0.0,
'beta': 2.6666666666666665,
'max_time': 4.0,
'rho': 28.0,
'sigma': 10.0}
%% Cell type:markdown id: tags:
After interacting with the system, we can take the result and perform further computations. In this case, we compute the average positions in $x$, $y$ and $z$.
%% Cell type:code id: tags:
``` python
xyz_avg = x_t.mean(axis=1)
```
%% Cell type:code id: tags:
``` python
xyz_avg.shape
```
%% Output
(10, 3)
%% Cell type:markdown id: tags:
Creating histograms of the average positions (across different trajectories) show that on average the trajectories swirl about the attractors.
%% Cell type:code id: tags:
``` python
plt.hist(xyz_avg[:,0])
plt.title('Average $x(t)$')
```
%% Output
Text(0.5,1,'Average $x(t)$')
%% Cell type:code id: tags:
``` python
plt.hist(xyz_avg[:,1])
plt.title('Average $y(t)$')
```
%% Output
Text(0.5,1,'Average $y(t)$')
%% Cell type:markdown id: tags:
# Widget Events
%% Cell type:markdown id: tags:
## Special events
%% Cell type:code id: tags:
``` python
from __future__ import print_function
```
%% Cell type:markdown id: tags:
The `Button` is not used to represent a data type. Instead the button widget is used to **handle mouse clicks**. The **`on_click` method** of the `Button` can be used to register function to be called when the button is clicked. The doc string of the `on_click` can be seen below.
%% Cell type:code id: tags:
``` python
import ipywidgets as widgets
print(widgets.Button.on_click.__doc__)
```
%% Output
Register a callback to execute when the button is clicked.
The callback will be called with one argument, the clicked button
widget instance.
Parameters
----------
remove: bool (optional)
Set to true to remove the callback from the list of callbacks.
%% Cell type:markdown id: tags:
### Example
%% Cell type:markdown id: tags:
Since button clicks are **stateless**, they are **transmitted from the front-end to the back-end using custom messages**. By using the `on_click` method, a button that prints a message when it has been clicked is shown below.
%% Cell type:code id: tags:
``` python
from IPython.display import display
button = widgets.Button(description="Click Me!")
out_button = widgets.Output()
display(button)
display(out_button)
def on_button_clicked(b):
with out_button:
print("Button clicked.")
button.on_click(on_button_clicked)
```
%% Output
%% Cell type:markdown id: tags:
### on_submit
%% Cell type:markdown id: tags:
The **`Text`** also has a special **`on_submit` event**. The `on_submit` event **fires when the user hits return**.
%% Cell type:code id: tags:
``` python
text = widgets.Text()
out_text = widgets.Output()
display(text)
display(out_text)
def handle_submit(sender):
with out_text:
print(text.value)
text.on_submit(handle_submit)
```
%% Output
%% Cell type:markdown id: tags:
## Traitlet events
%% Cell type:markdown id: tags:
**Widget properties are IPython traitlets** and **traitlets are eventful**. To handle changes, the **`observe` method** of the widget can be used to **register a callback**. The doc string for `observe` can be seen below.
%% Cell type:code id: tags:
``` python
print(widgets.Widget.observe.__doc__)
```
%% Output
Setup a handler to be called when a trait changes.
This is used to setup dynamic notifications of trait changes.
Parameters
----------
handler : callable
A callable that is called when a trait changes. Its
signature should be ``handler(change)``, where ``change`` is a
dictionary. The change dictionary at least holds a 'type' key.
* ``type``: the type of notification.
Other keys may be passed depending on the value of 'type'. In the
case where type is 'change', we also have the following keys:
* ``owner`` : the HasTraits instance
* ``old`` : the old value of the modified trait attribute
* ``new`` : the new value of the modified trait attribute
* ``name`` : the name of the modified trait attribute.
names : list, str, All
If names is All, the handler will apply to all traits. If a list
of str, handler will apply to all names in the list. If a
str, the handler will apply just to that name.
type : str, All (default: 'change')
The type of notification to filter by. If equal to All, then all
notifications are passed to the observe handler.
%% Cell type:markdown id: tags:
### Signature Dictionary
%% Cell type:markdown id: tags:
Mentioned in the doc string, the registered callback's signature should be ``handler(change)``, where ``change`` is a dictionary.
If the type of notification observed is 'change', the keys ``owner``, ``old``, ``new`` and ``name`` are also available.
Using this, an example of how to output an IntSlider's value as it is changed can be seen below.
%% Cell type:code id: tags:
``` python
from ipywidgets import IntSlider, Output
from IPython.display import display
x = IntSlider(description='x')
out_x = Output()
def update_y(change):
with out_x:
print('old:', change['old'], 'new:', change['new'])
x.observe(update_y, 'value')
display(x)
display(out_x)
```
%% Output
%% Cell type:markdown id: tags:
# Linking Widgets
%% Cell type:markdown id: tags:
Often, you may want to simply link widget attributes together. Synchronization of attributes can be done in a simpler way than by using bare traitlets events.
The first method is to use the `link` and `directional_link` functions from the `traitlets` module.
%% Cell type:markdown id: tags:
## Linking traitlets attributes from the server side
%% Cell type:code id: tags:
``` python
import traitlets
```
%% Cell type:code id: tags:
``` python
caption = widgets.Label(value = 'The values of slider1 and slider2 are synchronized')
sliders1, slider2 = widgets.IntSlider(description='Slider 1'), widgets.IntSlider(description='Slider 2')
l = traitlets.link((sliders1, 'value'), (slider2, 'value'))
display(caption, sliders1, slider2)
```
%% Output
%% Cell type:code id: tags:
``` python
caption = widgets.Label(value = 'Changes in source values are reflected in target1 and target2')
source, target1, target2 = widgets.IntSlider(description='Source'),\
widgets.IntSlider(description='Target 1'),\
widgets.IntSlider(description='Target 2')
traitlets.dlink((source, 'value'), (target1, 'value'))
traitlets.dlink((source, 'value'), (target2, 'value'))
display(caption, source, target1, target2)
```
%% Output
%% Cell type:markdown id: tags:
Function `traitlets.link` returns a `Link` object. The link can be broken by calling the `unlink` method.
%% Cell type:code id: tags:
``` python
#l.unlink()
```
%% Cell type:markdown id: tags:
## Linking widgets attributes from the client side
%% Cell type:markdown id: tags:
When synchronizing traitlets attributes, you may experience a lag because of the latency dues to the roundtrip to the server side. You can also directly link widgets attributes, either in a unidirectional or a bidirectional fashion using the link widgets.
%% Cell type:code id: tags:
``` python
caption = widgets.Label(value = 'The values of range1 and range2')
range1, range2 = widgets.IntSlider(description='Range 1'), widgets.IntSlider(description='Range 2')
l = widgets.jslink((range1, 'value'), (range2, 'value'))
display(caption, range1, range2)
```
%% Output
%% Cell type:code id: tags:
``` python
caption = widgets.Label(value = 'Changes in source_range values are reflected in target_range1 and target_range2')
source_range, target_range1, target_range2 = widgets.IntSlider(description='Source range'),\
widgets.IntSlider(description='Target range 1'),\
widgets.IntSlider(description='Target range 2')
widgets.jsdlink((source_range, 'value'), (target_range1, 'value'))
widgets.jsdlink((source_range, 'value'), (target_range2, 'value'))
display(caption, source_range, target_range1, target_range2)
```
%% Output
%% Cell type:markdown id: tags:
Function `widgets.jslink` returns a `Link` widget. The link can be broken by calling the `unlink` method.
%% Cell type:code id: tags:
``` python
#l.unlink()
```
%% Cell type:markdown id: tags:
# Widget List
%% Cell type:markdown id: tags:
## Complete list
%% Cell type:markdown id: tags:
For a complete list of the widgets available to you, you can list the classes in the widget namespace (as seen below). `Widget` and `DOMWidget`, not listed below, are base classes.
Widgets that have a `description` attribute can render Latex equations.
%% Cell type:code id: tags:
``` python
import ipywidgets as widgets
[n for n in dir(widgets) if not n.endswith('Widget') and n[0] == n[0].upper() and not n[0] == '_']
```
%% Output
['Accordion',
'BoundedFloatText',
'BoundedIntText',
'Box',
'Button',
'ButtonStyle',
'CallbackDispatcher',
'Checkbox',
'Color',
'ColorPicker',
'Controller',
'DatePicker',
'Datetime',
'Dropdown',
'FloatProgress',
'FloatRangeSlider',
'FloatSlider',
'FloatText',
'HBox',
'HTML',
'HTMLMath',
'Image',
'IntProgress',
'IntRangeSlider',
'IntSlider',
'IntText',
'Label',
'Layout',
'NumberFormat',
'Output',
'Password',
'Play',
'RadioButtons',
'Select',
'SelectMultiple',
'SelectionRangeSlider',
'SelectionSlider',
'SliderStyle',
'Style',
'Tab',
'Text',
'Textarea',
'ToggleButton',
'ToggleButtons',
'ToggleButtonsStyle',
'VBox',
'Valid']
%% Cell type:markdown id: tags:
## Numeric widgets
%% Cell type:markdown id: tags:
There are 8 widgets distributed with IPython that are designed to display numeric values. Widgets exist for displaying integers and floats, both bounded and unbounded. The integer widgets share a similar naming scheme to their floating point counterparts. By replacing `Float` with `Int` in the widget name, you can find the Integer equivalent.
%% Cell type:markdown id: tags:
### FloatSlider
%% Cell type:code id: tags:
``` python
widgets.FloatSlider(
value=7.5,
min=5.0,
max=10.0,
step=0.1,
description='Test:',
)
```
%% Output
%% Cell type:markdown id: tags:
Sliders can also be **displayed vertically**.
%% Cell type:code id: tags:
``` python
widgets.FloatSlider(
value=7.5,
min=5.0,
max=10.0,
step=0.1,
description='Test',
orientation='vertical',
)
```
%% Output
%% Cell type:markdown id: tags:
### FloatProgress
%% Cell type:code id: tags:
``` python
widgets.FloatProgress(
value=7.5,
min=5.0,
max=10.0,
step=0.1,
description='Loading:',
)
```
%% Output
%% Cell type:markdown id: tags:
### BoundedFloatText
%% Cell type:code id: tags:
``` python
widgets.BoundedFloatText(
value=7.5,
min=5.0,
max=10.0,
description='Text:',
)
```
%% Output
%% Cell type:markdown id: tags:
### FloatText
%% Cell type:code id: tags:
``` python
widgets.FloatText(
value=7.5,
description='Any:',
)
```
%% Output
%% Cell type:markdown id: tags:
## Boolean widgets
%% Cell type:markdown id: tags:
There are two widgets that are designed to display a boolean value.
%% Cell type:markdown id: tags:
### ToggleButton
%% Cell type:code id: tags:
``` python
widgets.ToggleButton(
description='Click me',
value=False,
)
```
%% Output
%% Cell type:markdown id: tags:
### Checkbox
%% Cell type:code id: tags:
``` python
widgets.Checkbox(
description='Check me',
value=True,
)
```
%% Output
%% Cell type:markdown id: tags:
## Selection widgets
%% Cell type:markdown id: tags:
There are four widgets that can be used to display single selection lists, and one that can be used to display multiple selection lists. All inherit from the same base class. You can specify the **enumeration of selectable options by passing a list**. You can **also specify the enumeration as a dictionary**, in which case the **keys will be used as the item displayed** in the list and the corresponding **value will be returned** when an item is selected.
%% Cell type:markdown id: tags:
### Dropdown
%% Cell type:code id: tags:
``` python
from IPython.display import display
w = widgets.Dropdown(
options=['1', '2', '3'],
value='2',
description='Number:',
)
display(w)
```
%% Output
%% Cell type:code id: tags:
``` python
w.value
```
%% Output
'2'
%% Cell type:markdown id: tags:
The following is also valid:
%% Cell type:code id: tags:
``` python
w = widgets.Dropdown(
options={'One': 1, 'Two': 2, 'Three': 3},
value=2,
description='Number:',
)
display(w)
```
%% Output
%% Cell type:code id: tags:
``` python
w.value
```
%% Output
2
%% Cell type:markdown id: tags:
### RadioButtons
%% Cell type:code id: tags:
``` python
widgets.RadioButtons(
description='Pizza topping:',
options=['pepperoni', 'pineapple', 'anchovies'],
)
```
%% Output
%% Cell type:markdown id: tags:
### Select
%% Cell type:code id: tags:
``` python
widgets.Select(
description='OS:',
options=['Linux', 'Windows', 'OSX'],
)
```
%% Output
%% Cell type:markdown id: tags:
### ToggleButtons
%% Cell type:code id: tags:
``` python
widgets.ToggleButtons(
description='Speed:',
options=['Slow', 'Regular', 'Fast'],
)
```
%% Output
%% Cell type:markdown id: tags:
### SelectMultiple
Multiple values can be selected with <kbd>shift</kbd> and <kbd>ctrl</kbd> pressed and mouse clicks or arrow keys.
%% Cell type:code id: tags:
``` python
w = widgets.SelectMultiple(
description="Fruits",
options=['Apples', 'Oranges', 'Pears']
)
display(w)
```
%% Output
%% Cell type:code id: tags:
``` python
w.value
```
%% Output
()
%% Cell type:markdown id: tags:
## String widgets
%% Cell type:markdown id: tags:
There are 4 widgets that can be used to display a string value. Of those, the **`Text` and `Textarea` widgets accept input**. The **`Label` and `HTML` widgets display the string** as either Latex or HTML respectively, but **do not accept input**.
%% Cell type:markdown id: tags:
### Text
%% Cell type:code id: tags:
``` python
widgets.Text(
description='String:',
value='Hello World',
)
```
%% Output
%% Cell type:markdown id: tags:
### Textarea
%% Cell type:code id: tags:
``` python
widgets.Textarea(
description='String:',
value='Hello World',
)
```
%% Output
%% Cell type:markdown id: tags:
### Label
%% Cell type:code id: tags:
``` python
widgets.Label(
value="$$\\frac{n!}{k!(n-k)!} = \\binom{n}{k}$$",
)
```
%% Output
%% Cell type:markdown id: tags:
### HTML
%% Cell type:code id: tags:
``` python
widgets.HTML(
value="Hello <b>World</b>"
)
```
%% Output
%% Cell type:markdown id: tags:
## Button
%% Cell type:code id: tags:
``` python
widgets.Button(description='Click me')
```
%% Output
%% Cell type:code id: tags:
``` python
import ipywidgets as widgets
from IPython.display import display
```
%% Cell type:markdown id: tags:
# Widget Styling
%% Cell type:markdown id: tags:
## The **`layout`** attribute
The `layout` attribute impacts how widgets are laid out. You can get a list of layout properties using the `keys` property.
%% Cell type:code id: tags:
``` python
b = widgets.Button()
b.layout.keys
```
%% Output
['_model_module',
'_model_module_version',
'_model_name',
'_view_count',
'_view_module',
'_view_module_version',
'_view_name',
'align_content',
'align_items',
'align_self',
'border',
'bottom',
'display',
'flex',
'flex_flow',
'height',
'justify_content',
'left',
'margin',
'max_height',
'max_width',
'min_height',
'min_width',
'order',
'overflow',
'overflow_x',
'overflow_y',
'padding',
'right',
'top',
'visibility',
'width']
%% Cell type:markdown id: tags:
The layout property values are mapped to the values of the corresponding CSS properties.For more detail on the possible values, you can refer to the [ipywidgets documentation](http://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Styling.html#The-layout-attribute).
%% Cell type:markdown id: tags:
## The **`style`** attribute
The style attribute is used to expose non-layout related styling attributes of widgets.
Widget styling attributes are specific to each widget type. You can list them for a specific widget using the `keys` property.
%% Cell type:code id: tags:
``` python
b.style.keys
```
%% Output
['_model_module',
'_model_module_version',
'_model_name',
'_view_count',
'_view_module',
'_view_module_version',
'_view_name',
'button_color',
'font_weight']
%% Cell type:markdown id: tags:
### Basic example
%% Cell type:markdown id: tags:
Attributes can be set by defining them as keyword arguments in the widget's constructor or dynamically.
%% Cell type:code id: tags:
``` python
b1_layout = widgets.Layout(width='50%', height='50px', border='solid red')
b1 = widgets.Button(description='50% width, 50px height', layout=b1_layout)
display(b1)
```
%% Output
%% Cell type:code id: tags:
``` python
b1.style.button_color = 'tomato' # colors can be set either by name or color code
# button.style.button_color = '#FFFFFF'
```
%% Cell type:markdown id: tags:
The `layout` and `style` properties can be shared between multiple widgets and assigned directly.
%% Cell type:code id: tags:
``` python
b2 = widgets.Button(layout=b1.layout, style=b1.style)
display(b2)
```
%% Output
%% Cell type:markdown id: tags:
## Predefined styles
Many widgets have predefined styles you can choose from.
%% Cell type:code id: tags:
``` python
display(widgets.Button(description = "Primary", button_style='primary'))
display(widgets.Button(description = "Success", button_style='success'))
display(widgets.Button(description = "Info", button_style='info'))
display(widgets.Button(description = "Warning", button_style='warning'))
display(widgets.Button(description = "Danger", button_style='danger'))
```
%% Output
%% Cell type:markdown id: tags:
## Parent/child relationships
%% Cell type:markdown id: tags:
To display widget A inside widget B, widget A must be a child of widget B. Widgets that can contain other widgets have a **`children` attribute**. This attribute can be **set via a keyword argument** in the widget's constructor **or after construction**. Calling display on an **object with children automatically displays those children**, too.
%% Cell type:code id: tags:
``` python
float_range = widgets.FloatSlider()
string = widgets.Text(value='hi')
container = widgets.Box(children=[float_range, string])
# Or, shorter:
# container = widgets.Box([float_range, string])
container.layout.border = 'dotted red 3px'
display(container) # Displays the `container` and all of it's children.
```
%% Output
%% Cell type:markdown id: tags:
### After the parent is displayed
%% Cell type:markdown id: tags:
Children **can be added to parents** after the parent has been displayed. The **parent is responsible for rendering its children**.
%% Cell type:code id: tags:
``` python
container = widgets.Box()
container.layout.border = 'dotted red 3px'
display(container)
int_range = widgets.IntSlider()
container.children=[int_range]
```
%% Output
%% Cell type:markdown id: tags:
# Alignment
%% Cell type:markdown id: tags:
Most widgets have a **`description` attribute**, which allows a label for the widget to be defined.
The label of the widget **has a fixed minimum width**.
The text of the label is **always right aligned and the widget is left aligned**:
%% Cell type:code id: tags:
``` python
display(widgets.Text(description="a:"))
display(widgets.Text(description="aa:"))
display(widgets.Text(description="aaa:"))
```
%% Output
%% Cell type:markdown id: tags:
If a **description is longer** than the minimum width, the **description is truncated**:
%% Cell type:code id: tags:
``` python
display(widgets.Text(description="a:"))
display(widgets.Text(description="aa:"))
display(widgets.Text(description="aaa:"))
display(widgets.Text(description="aaaaaaaaaaaaaaaaaa:"))
```
%% Output
%% Cell type:markdown id: tags:
To display a long description in its entirety, you can set the
**`style` attribute**. This will however make the **widget itself shorter**.
Alternatively, you can use a `label` widget directly.
%% Cell type:code id: tags:
``` python
display(widgets.Text(description="a:"))
style={'description_width':'initial'}
display(widgets.Text(description="aaaaaaaaaaaaaaaaaa:", style=style))
label=widgets.Label("aaaaaaaaaaaaaaaaaa:")
display(widgets.Box([label, widgets.Text()]))
```
%% Output
%% Cell type:markdown id: tags:
If a `description` is **not set** for the widget, the **label is not displayed**:
%% Cell type:code id: tags:
``` python
display(widgets.Text(description="a:"))
display(widgets.Text(description="aa:"))
display(widgets.Text(description="aaa:"))
display(widgets.Text())
```
%% Output
%% Cell type:markdown id: tags:
## Fancy boxes
%% Cell type:markdown id: tags:
If you need to display a more complicated set of widgets, there are **specialized containers** that you can use. To display **multiple sets of widgets**, you can use an **`Accordion` or a `Tab` in combination with one `Box` per set of widgets** (as seen below). The "pages" of these widgets are their children. To set the titles of the pages, one can **call `set_title`**.
%% Cell type:markdown id: tags:
### Accordion
%% Cell type:code id: tags:
``` python
name1 = widgets.Text(description='Location:')
zip1 = widgets.BoundedIntText(description='Zip:', min=0, max=99999)
page1 = widgets.Box([name1, zip1])
name2 = widgets.Text(description='Location:')
zip2 = widgets.BoundedIntText(description='Zip:', min=0, max=99999)
page2 = widgets.Box([name2, zip2])
accord = widgets.Accordion(children=[page1, page2])
display(accord)
accord.set_title(0, 'From')
accord.set_title(1, 'To')
```
%% Output
%% Cell type:markdown id: tags:
### TabWidget
%% Cell type:code id: tags:
``` python
name = widgets.Text(description='Name:')
color = widgets.Dropdown(description='Color:', options=['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'])
page1 = widgets.Box(children=[name, color])
age = widgets.IntSlider(description='Age:', min=0, max=120, value=50)
gender = widgets.RadioButtons(description='Gender:', options=['male', 'female'])
page2 = widgets.Box([age, gender])
tabs = widgets.Tab([page1, page2])
display(tabs)
tabs.set_title(0, 'Name')
tabs.set_title(1, 'Details')
```
%% Output
%% Cell type:markdown id: tags:
## Flex boxes
%% Cell type:markdown id: tags:
Widgets can be aligned using the `FlexBox`, `HBox`, and `VBox` widgets. `Box` widgets enable the CSS flexbox spec, exposed via the `layout` attribute.
%% Cell type:markdown id: tags:
### Application to widgets
%% Cell type:markdown id: tags:
Widgets display vertically by default:
%% Cell type:code id: tags:
``` python
buttons = [widgets.Button(description=str(i)) for i in range(3)]
display(*buttons)
```
%% Output
%% Cell type:markdown id: tags:
### Using hbox
%% Cell type:markdown id: tags:
To make widgets display horizontally, you need to **child them to a `HBox` widget**.
%% Cell type:code id: tags:
``` python
container = widgets.HBox(buttons)
display(container)
```
%% Output
%% Cell type:markdown id: tags:
You can center the buttons by setting `justify-content` to `center`. Possible other values are `flex-start`, `flex-end`, `space-between` and `space-around`.
%% Cell type:code id: tags:
``` python
container.layout.justify_content = 'center'
```
%% Cell type:code id: tags:
``` python
#container.layout.justify_content = 'flex-start'
#container.layout.justify_content = 'flex-end'
#container.layout.justify_content = 'space-between'
#container.layout.justify_content = 'space-around'
```
%% Cell type:markdown id: tags:
## Visibility
%% Cell type:markdown id: tags:
Sometimes it is necessary to **hide or show widgets** in place, **without having to re-display** the widget.
The `visibilty` property of the `layout` attribute can be used to hide or show **widgets that have already been displayed** (as seen below). The `visibility` property can be:
* `visible` - the widget is displayed
* `hidden` - the widget is hidden, and the empty space where the widget would be is collapsed
%% Cell type:code id: tags:
``` python
w1 = widgets.Label(value="First line")
w2 = widgets.Label(value="Second line")
w3 = widgets.Label(value="Third line")
display(w1, w2, w3)
```
%% Output
%% Cell type:code id: tags:
``` python
w2.layout.visibility = 'hidden'
```
%% Cell type:code id: tags:
``` python
w2.layout.visibility = 'visible'
```
%% Cell type:markdown id: tags:
### Another example
%% Cell type:markdown id: tags:
In the example below, a form is rendered, which conditionally displays widgets depending on the state of other widgets. Try toggling the student checkbox.
%% Cell type:code id: tags:
``` python
form = widgets.VBox()
first = widgets.Text(description="First Name:")
last = widgets.Text(description="Last Name:")
student = widgets.Checkbox(description="Student:", value=False)
school_info = widgets.VBox([widgets.Text(description="School:"),
widgets.IntText(description="Grade:", min=0, max=12)],
layout=widgets.Layout(visibility='hidden'))
pet = widgets.Text(description="Pet's Name:")
form.children = [first, last, student, school_info, pet]
display(form)
def on_student_toggle(change):
if change['new']:
school_info.layout.visibility = 'visible'
else:
school_info.layout.visibility = 'hidden'
student.observe(on_student_toggle, 'value')
```
%% Output
# Code of the IPython Cookbook, Second Edition (2018)
[![Binder](https://mybinder.org/badge.svg)](https://mybinder.org/v2/gh/ipython-books/cookbook-2nd-code/master)
This repository contains the Jupyter notebooks of the 100+ recipes of [*IPython Interactive Computing and Visualization Cookbook, Second Edition (2018)*](https://www.packtpub.com/big-data-and-business-intelligence/ipython-interactive-computing-and-visualization-cookbook-second-e), by [Cyrille Rossant](http://cyrille.rossant.net), *Packt Publishing*.
This repository is read-only: the source files are on the [cookbook-2nd](https://github.com/ipython-books/cookbook-2nd) repository.
## Running the code in the cloud
With [Binder](https://mybinder.org/), you can run most of the Jupyter notebooks directly from your web browser without installing anything. Just click on the `launch binder` button above. A temporary Jupyter Notebook server with all dependencies will be automatically launched in the cloud. It is not persistent: all your changes will be lost after some time.
## Running the code on your computer
1. [**Install** git](https://git-scm.com/downloads).
2. [**Download and install** Anaconda](https://www.anaconda.com/download/): choose the **Python 3.6, 64-bit** version for your operating system (macOS, Linux, or Windows).
3. **Open** a terminal (`cmd` on Windows).
4. **Clone** the repository:
```bash
$ git clone https://github.com/ipython-books/cookbook-2nd-code.git
$ cd cookbook-2nd-code
```
5. **Create** the `cookbook` [conda environment](https://conda.io/docs/user-guide/tasks/manage-environments.html#creating-an-environment-from-an-environment-yml-file):
```bash
conda env create -f environment.yml
```
6. **Activate** the environment:
* On macOS and Linux:
```bash
source activate cookbook
```
* On Windows:
```bash
activate cookbook
```
7. **Launch** the [Jupyter Notebook](http://jupyter.org/install.html):
```bash
$ jupyter notebook
```
%% Cell type:markdown id: tags:
# 1.1. Introducing IPython and the Jupyter Notebook
%% Cell type:code id: tags:
``` python
print("Hello world!")
```
%% Output
Hello world!
%% Cell type:code id: tags:
``` python
2 + 2
```
%% Output
4
%% Cell type:code id: tags:
``` python
_ * 3
```
%% Output
12
%% Cell type:code id: tags:
``` python
!ls
```
%% Output
01_notebook.ipynb __pycache__ papermill_05_config.ipynb
02_pandas.ipynb csvmagic.py papermill_06_kernel.ipynb
03_numpy.ipynb papermill_01_notebook.ipynb plotkernel.py
04_magic.ipynb papermill_02_pandas.ipynb plotter
05_config.ipynb papermill_03_numpy.ipynb random_magics.py
06_kernel.ipynb papermill_04_magic.ipynb test.txt
%% Cell type:code id: tags:
``` python
%lsmagic
```
%% Output
Available line magics:
%alias %alias_magic %autoawait %autocall %automagic %autosave %bookmark %cat %cd %clear %colors %conda %config %connect_info %cp %debug %dhist %dirs %doctest_mode %ed %edit %env %gui %hist %history %killbgscripts %ldir %less %lf %lk %ll %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %lx %macro %magic %man %matplotlib %mkdir %more %mv %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %pip %popd %pprint %precision %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %rep %rerun %reset %reset_selective %rm %rmdir %run %save %sc %set_env %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmode
Available cell magics:
%%! %%HTML %%SVG %%bash %%capture %%debug %%file %%html %%javascript %%js %%latex %%markdown %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script %%sh %%svg %%sx %%system %%time %%timeit %%writefile
Automagic is ON, % prefix IS NOT needed for line magics.
%% Cell type:code id: tags:
``` python
%%writefile test.txt
Hello world!
```
%% Output
Writing /p/home/jusers/goebbert1/jureca/mytest.txt
%% Cell type:code id: tags:
``` python
# Let's check what this file contains.
with open('test.txt', 'r') as f:
print(f.read())
```
%% Output
Hello world!
%% Cell type:code id: tags:
``` python
%run?
```
%% Output
%% Cell type:code id: tags:
``` python
from IPython.display import HTML, SVG, YouTubeVideo
```
%% Cell type:code id: tags:
``` python
HTML('''
<table style="border: 2px solid black;">
''' +
''.join(['<tr>' +
''.join([f'<td>{row},{col}</td>'
for col in range(5)]) +
'</tr>' for row in range(5)]) +
'''
</table>
''')
```
%% Output
<IPython.core.display.HTML object>
%% Cell type:code id: tags:
``` python
SVG('''<svg width="600" height="80">''' +
''.join([f'''<circle
cx="{(30 + 3*i) * (10 - i)}"
cy="30"
r="{3. * float(i)}"
fill="red"
stroke-width="2"
stroke="black">
</circle>''' for i in range(10)]) +
'''</svg>''')
```
%% Output
<IPython.core.display.SVG object>
%% Cell type:code id: tags:
``` python
YouTubeVideo('VQBZ2MqWBZI')
```
%% Output
<IPython.lib.display.YouTubeVideo at 0x7fbab4254a58>
%% Cell type:markdown id: tags:
```json
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello world!\n"
]
}
],
"source": [
"print(\"Hello world!\")"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}
```
%% Cell type:markdown id: tags:
## Cleanup
%% Cell type:code id: tags:
``` python
!rm -f test.txt
```
Source diff could not be displayed: it is too large. Options to address this: view the blob.