This lecture by Aron Ahmadia and David Ketcheson is licensed under a Creative Commons Attribution 4.0 International License. All code examples are also licensed under the MIT license.
from IPython.core.display import HTML
css_file = './example.css'
HTML(open(css_file, "r").read())
This is a brief introduction to exploring numerical methods using IPython Notebook Widgets, aimed at lecturers who wish to incorporate it in their teaching, written in an IPython Notebook. This presentation adapts material from the IPython official documentation.
%matplotlib inline
from math import pi
from IPython.display import display, HTML
from IPython.html import widgets
from IPython.html.widgets import interact, interactive
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def show_args(**kwargs):
s = '<h3>Arguments:</h3><table>\n'
for k,v in kwargs.items():
s += '<tr><td>{0}</td><td>{1}</td></tr>\n'.format(k,v)
s += '</table>'
display(HTML(s))
i = interact(show_args,
Temp=(0,10),
Current=(0.,10.,0.01),
z=True,
Text=u'Type here!',
Algorithm=['This','That','Other'],
a=widgets.FloatSliderWidget(min=-10.0, max=10.0, step=0.1, value=5.0, description="Float (a)")
)
a | 5.0 |
Temp | 5 |
Algorithm | This |
Text | Type here! |
Current | 4.99 |
z | True |
def plot_sine(n):
x = np.arange(0, 2*pi, 0.01);
y = np.sin(n*x)
fig = plt.figure(figsize = (8, 6));
ax = fig.add_subplot(1,1,1);
ax.plot(x, y, 'g', linewidth=4);
interact(plot_sine, n=(1, 5, 1));
def solve_lorenz(N=10, angle=0.0, max_time=4.0, sigma=10.0, beta=8./3, rho=28.0):
fig = plt.figure(figsize = (4, 3));
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, angle=(0.,360.), N=(0,50), sigma=(0.0,50.0), rho=(0.0,50.0))
display(w)
t, x_t = w.result
xyz_avg = x_t.mean(axis=1)
plt.hist(xyz_avg[:,0])
plt.title('Average $x(t)$')
<matplotlib.text.Text at 0x105346110>