%load_ext load_style
%load_style talk.css
from version 2.0
, IPython includes an architecture for interactive widgets that tie together Python code running in the kernel and JavaScript/HTML/CSS running in the browser. These widgets enable users to explore their code and data interactively.
from IPython.html.widgets import interactive, interact, fixed
from IPython.html import widgets
def f(x):
print(x)
interact(f, x=10);
decorator
syntax¶from datetime import datetime
@interact(x=10)
def f(x):
print(x)
interact(f, x=True);
interact(f, x='Hi there!');
interact(f, x=widgets.IntSliderWidget(min=-20,max=40,step=2,value=10));
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
@interact(degree=2)
def f(degree):
x = np.linspace(0,1,100)
f, ax = plt.subplots(figsize=(10,5))
plt.plot(x, x**degree)
plt.show()
from IPython.display import display
from sympy import Symbol, Eq, factor, init_printing
init_printing(use_latex='mathjax')
x = Symbol('x')
def factorit(n):
display(Eq(x**n-1, factor(x**n-1)))
factorit(12)
interact(factorit, n=(2,40));
The Lorenz system is a system of ordinary differential equations (the Lorenz equations) first studied by Edward Lorenz. It is notable for having chaotic solutions for certain parameter values and initial conditions. In particular, the Lorenz attractor is a set of chaotic solutions of the Lorenz system which, when plotted, resemble a butterfly or figure eight.
The system is described by:
$$ \begin{align} \frac{\mathrm{d}x}{\mathrm{d}t} &= \sigma (y - x), \\ \frac{\mathrm{d}y}{\mathrm{d}t} &= x (\rho - z) - y, \\ \frac{\mathrm{d}z}{\mathrm{d}t} &= x y - \beta z. \end{align} $$$x$, $y$, and $z$ make up the system state, $t$ is time, and $\sigma$, $\rho$, $\beta$ are the system parameters
The small animation below shows a sample solution for when when ρ = 28, σ = 10, and β = 8/3 (Values used by Lorenz)
The IPython widget infrastructure is a convenient way to visualise what happens to the solutions as we vary the parameters
from IPython.display import clear_output, display, HTML
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
We define a function that can integrate the system of 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).
def solve_lorenz(N=10, angle=0.0, max_time=10.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 Lorentz system."""
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
t, x_t = solve_lorenz(angle=0, N=10)
w = interactive(solve_lorenz, N=(0,50), max_time=(0,30), angle=(0.,360.), sigma=(0.0,50.0), rho=(0.0,50.0), beta=(0,30) )
display(w)
import pandas as pd
xdf = pd.DataFrame({'A':np.random.randn(5), 'B':np.random.randn(5)})
xdf.plot()
def plot_df(label):
xdf[label].plot()
w = interactive(plot_df, label=['A','B'])
display(w)
!ipython nbconvert IPython_widgets.ipynb --to html