CoCalc Shared Files2013-11-02-103244.ipynb
Author: william cotter
Views : 241
Description: Jupyter notebook 2013-11-02-103244.ipynb
In [4]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import Image
from qutip import *


--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-4-7f2844c0124a> in <module>() 3 import numpy as np 4 from IPython.display import Image ----> 5 from qutip import * 6 7 ImportError: No module named qutip 
In [2]:
2070010039

In [3]:
%load_ext octavemagic
%octave
x=21070010039
tic()
y=floor(2*x^.5)
parfor i = 2:y
c(:,i) = abs(sin((x+i)*pi/i));

end

parfor n=2:y

if (c(:,n))<1e-6
n,"nonprime"
toc()
exit
endif
end
x,"prime"
toc()

 File "<ipython-input-3-607f96c0d7cd>", line 6 parfor i = 2:y , ^ SyntaxError: invalid syntax 
In [2]:
%julia
a=2
a

ERROR: Line magic function %julia not found.
2
In [ ]:


In [ ]:

x = %octave [1 6 8 9 88 56 , 1 7 3 3 4 6];
x

In [1]:
4

4
In [4]:
%load_ext octavemagic

%octave(x=99

y=int(2*x^.5)
parfor i=2:y
c(:,i) = abs(sin((x+i)*pi/i));

end

parfor n=2:y

if (c(:,n))<1e-6
n,"nonprime"

exit
endif
end
x,"prime"


 File "<ipython-input-4-f1cf958213e2>", line 6 parfor i=2:y ^ SyntaxError: invalid syntax 
In [4]:
%octave -s 600,200 -f png

subplot(121);
[x, y] = meshgrid(0:0.1:3);
r = sin(x - 0.5).^2 + cos(y - 0.5).^2;
surf(x, y, r);

subplot(122);
sombrero()

 File "<ipython-input-4-c0c475d2b10b>", line 4 [x, y] = meshgrid(0:0.1:3); ^ SyntaxError: invalid syntax 
In [7]:
%octave
tic()
x = -2:0.01:2;
y = -2:0.01:2;
[xx,yy] = meshgrid(x,y);
z = sin(xx.^2-yy.^2);
toc()


 File "<ipython-input-6-d771a77862ed>", line 3 x = -2:0.01:2; ^ SyntaxError: invalid syntax 
In [ ]:
oct2py

In [2]:


x=99
tic()
y=floor(2*x^.5)
parfor i=2:y
c(:,i) = abs(sin((x+i)*pi/i));

end

parfor n=2:y

if (c(:,n))<1e-6
n,"nonprime"
toc()
exit
endif
end
x,"prime"
toc()

 File "<ipython-input-2-6dee538ee987>", line 6 parfor i=2:y ^ SyntaxError: invalid syntax 
In [8]:
%octave
x=99
tic()
y=floor(2*x^.5)
parfor i = 2:y
c(:,i) = abs(sin((x+i)*pi/i));

end

parfor n=2:y

if (c(:,n))<1e-6
n,"nonprime"
toc()
exit
endif
end
x,"prime"
toc()

 File "<ipython-input-8-12720de76be8>", line 5 parfor i = 2:y ^ SyntaxError: invalid syntax 
In [1]:
%load_ext octavemagic
%octave
octave(2+4)


--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-1-b5400d308764> in <module>() ----> 1 get_ipython().magic(u'load_ext octavemagic') 2 get_ipython().magic(u'octave') 3 octave(2+4) /projects/sage/sage-6.10/local/lib/python2.7/site-packages/IPython/core/interactiveshell.py in magic(self, arg_s) 2334 magic_name, _, magic_arg_s = arg_s.partition(' ') 2335 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) -> 2336 return self.run_line_magic(magic_name, magic_arg_s) 2337 2338 #------------------------------------------------------------------------- /projects/sage/sage-6.10/local/lib/python2.7/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line) 2255 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals 2256 with self.builtin_trap: -> 2257 result = fn(*args,**kwargs) 2258 return result 2259 <decorator-gen-64> in load_ext(self, module_str) /projects/sage/sage-6.10/local/lib/python2.7/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k) 191 # but it's overkill for just that one bit of state. 192 def magic_deco(arg): --> 193 call = lambda f, *a, **k: f(*a, **k) 194 195 if callable(arg): /projects/sage/sage-6.10/local/lib/python2.7/site-packages/IPython/core/magics/extension.py in load_ext(self, module_str) 64 if not module_str: 65 raise UsageError('Missing module name.') ---> 66 res = self.shell.extension_manager.load_extension(module_str) 67 68 if res == 'already loaded': /projects/sage/sage-6.10/local/lib/python2.7/site-packages/IPython/core/extensions.py in load_extension(self, module_str) 87 if module_str not in sys.modules: 88 with prepended_to_syspath(self.ipython_extension_dir): ---> 89 __import__(module_str) 90 mod = sys.modules[module_str] 91 if self._call_load_ipython_extension(mod): ImportError: No module named octavemagic 
In [11]:
%load_ext octavemagic
%octave
f =sin(x)*x


--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-11-ed68f79a1d1b> in <module>() 1 get_ipython().magic(u'load_ext octavemagic') 2 get_ipython().magic(u'octave') ----> 3 f =sin(x)*x NameError: name 'x' is not defined 
In [2]:
from matplotlib.widgets import Cursor
import pylab

fig = pylab.figure(figsize=(8,6))
ax = fig.add_axes([0.075, 0.25, 0.9, 0.725], axisbg='#FFFFCC')

x,y = (x+y)/y
ax.plot(x,y,'o')
ax.set_xlim(2,23)
ax.set_ylim(2,10)

# set useblit = True on gtkagg for enhanced performance
cursor = Cursor(ax, useblit=True, color='red', linewidth=2 )

pylab.show()

--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-2-412e68b352ae> in <module>() 5 ax = fig.add_axes([0.075, 0.25, 0.9, 0.725], axisbg='#FFFFCC') 6 ----> 7 x,y = (x+y)/y 8 ax.plot(x,y,'o') 9 ax.set_xlim(2,23) NameError: name 'x' is not defined 
In [3]:

pylab
x= randn(10000000)
y=randn(10000000)+6
hist(x, 100)+hist(y,100)

--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-3-cf1295bf88b8> in <module>() 1 2 pylab ----> 3 x= randn(10000000) 4 y=randn(10000000)+6 5 hist(x, 100)+hist(y,100) NameError: name 'randn' is not defined 
In [1]:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def data_gen():
t = data_gen.t
cnt = 0
while cnt < 1000:
cnt+=1
t += 0.05
yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)
data_gen.t = 0

fig, ax = plt.subplots()
line, = ax.plot([], [], lw=2)
ax.set_ylim(-1.1, 1.1)
ax.set_xlim(0, 5)
ax.grid()
xdata, ydata = [], []
def run(data):
# update the data
t,y = data
xdata.append(t)
ydata.append(y)
xmin, xmax = ax.get_xlim()

if t >= xmax:
ax.set_xlim(xmin, 2*xmax)
ax.figure.canvas.draw()
line.set_data(xdata, ydata)

return line,

ani = animation.FuncAnimation(fig, run, data_gen, blit=True, interval=10,
repeat=False)
plt.show()

In [4]:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

majorLocator   = MultipleLocator(20)
majorFormatter = FormatStrFormatter('%d')
minorLocator   = MultipleLocator(5)

t = np.arange(0.0, 100.0, 0.1)
s = np.sin(0.1*np.pi*t)*np.exp(-t*0.03)

fig, ax = plt.subplots()
plt.plot(t,s)

ax.xaxis.set_major_locator(majorLocator)
ax.xaxis.set_major_formatter(majorFormatter)

#for the minor ticks, use no labels; default NullFormatter
ax.xaxis.set_minor_locator(minorLocator)

plt.show()

In [6]:
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np

plt.ion()

fig = plt.figure()
X, Y, Z = axes3d.get_test_data(0.1)
ax.plot_wireframe(X, Y, Z, rstride=5, cstride=5)

for angle in range(0, 720):
ax.view_init(20, angle)
plt.draw()

In [1]:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,

# animation function.  This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()

--------------------------------------------------------------------------- IOError Traceback (most recent call last) <ipython-input-1-0e958eaac575> in <module>() 29 # your system: for more information, see 30 # http://matplotlib.sourceforge.net/api/animation_api.html ---> 31 anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264']) 32 33 plt.show() /projects/sage/sage-6.10/local/lib/python2.7/site-packages/matplotlib-1.5.0-py2.7-linux-x86_64.egg/matplotlib/animation.py in save(self, filename, writer, fps, dpi, codec, bitrate, extra_args, metadata, extra_anim, savefig_kwargs) 778 # TODO: Need to see if turning off blit is really necessary 779 anim._draw_next_frame(d, blit=False) --> 780 writer.grab_frame(**savefig_kwargs) 781 782 # Reconnect signal for first draw if necessary /projects/sage/sage-6.10/local/lib/python2.7/site-packages/matplotlib-1.5.0-py2.7-linux-x86_64.egg/matplotlib/animation.py in grab_frame(self, **savefig_kwargs) 223 # frame format and dpi. 224 self.fig.savefig(self._frame_sink(), format=self.frame_format, --> 225 dpi=self.dpi, **savefig_kwargs) 226 except RuntimeError: 227 out, err = self._proc.communicate() /projects/sage/sage-6.10/local/lib/python2.7/site-packages/matplotlib-1.5.0-py2.7-linux-x86_64.egg/matplotlib/figure.py in savefig(self, *args, **kwargs) 1537 self.set_frameon(frameon) 1538 -> 1539 self.canvas.print_figure(*args, **kwargs) 1540 1541 if frameon: /projects/sage/sage-6.10/local/lib/python2.7/site-packages/matplotlib-1.5.0-py2.7-linux-x86_64.egg/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs) 2228 orientation=orientation, 2229 bbox_inches_restore=_bbox_inches_restore, -> 2230 **kwargs) 2231 finally: 2232 if bbox_inches and restore_bbox: /projects/sage/sage-6.10/local/lib/python2.7/site-packages/matplotlib-1.5.0-py2.7-linux-x86_64.egg/matplotlib/backends/backend_agg.py in print_raw(self, filename_or_obj, *args, **kwargs) 517 close = False 518 try: --> 519 fileobj.write(renderer._renderer.buffer_rgba()) 520 finally: 521 if close: IOError: [Errno 32] Broken pipe 
In [2]:
from numpy import sin, cos
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import matplotlib.animation as animation

class DoublePendulum:
"""Double Pendulum Class

init_state is [theta1, omega1, theta2, omega2] in degrees,
where theta1, omega1 is the angular position and velocity of the first
pendulum arm, and theta2, omega2 is that of the second pendulum arm
"""
def __init__(self,
init_state = [120, 0, -20, 0],
L1=1.0,  # length of pendulum 1 in m
L2=1.0,  # length of pendulum 2 in m
M1=1.0,  # mass of pendulum 1 in kg
M2=1.0,  # mass of pendulum 2 in kg
G=9.8,  # acceleration due to gravity, in m/s^2
origin=(0, 0)):
self.init_state = np.asarray(init_state, dtype='float')
self.params = (L1, L2, M1, M2, G)
self.origin = origin
self.time_elapsed = 0

self.state = self.init_state * np.pi / 180.

def position(self):
"""compute the current x,y positions of the pendulum arms"""
(L1, L2, M1, M2, G) = self.params

x = np.cumsum([self.origin[0],
L1 * sin(self.state[0]),
L2 * sin(self.state[2])])
y = np.cumsum([self.origin[1],
-L1 * cos(self.state[0]),
-L2 * cos(self.state[2])])
return (x, y)

def energy(self):
"""compute the energy of the current state"""
(L1, L2, M1, M2, G) = self.params

x = np.cumsum([L1 * sin(self.state[0]),
L2 * sin(self.state[2])])
y = np.cumsum([-L1 * cos(self.state[0]),
-L2 * cos(self.state[2])])
vx = np.cumsum([L1 * self.state[1] * cos(self.state[0]),
L2 * self.state[3] * cos(self.state[2])])
vy = np.cumsum([L1 * self.state[1] * sin(self.state[0]),
L2 * self.state[3] * sin(self.state[2])])

U = G * (M1 * y[0] + M2 * y[1])
K = 0.5 * (M1 * np.dot(vx, vx) + M2 * np.dot(vy, vy))

return U + K

def dstate_dt(self, state, t):
"""compute the derivative of the given state"""
(M1, M2, L1, L2, G) = self.params

dydx = np.zeros_like(state)
dydx[0] = state[1]
dydx[2] = state[3]

cos_delta = cos(state[2] - state[0])
sin_delta = sin(state[2] - state[0])

den1 = (M1 + M2) * L1 - M2 * L1 * cos_delta * cos_delta
dydx[1] = (M2 * L1 * state[1] * state[1] * sin_delta * cos_delta
+ M2 * G * sin(state[2]) * cos_delta
+ M2 * L2 * state[3] * state[3] * sin_delta
- (M1 + M2) * G * sin(state[0])) / den1

den2 = (L2 / L1) * den1
dydx[3] = (-M2 * L2 * state[3] * state[3] * sin_delta * cos_delta
+ (M1 + M2) * G * sin(state[0]) * cos_delta
- (M1 + M2) * L1 * state[1] * state[1] * sin_delta
- (M1 + M2) * G * sin(state[2])) / den2

return dydx

def step(self, dt):
"""execute one time step of length dt and update state"""
self.state = integrate.odeint(self.dstate_dt, self.state, [0, dt])[1]
self.time_elapsed += dt

#------------------------------------------------------------
# set up initial state and global variables
pendulum = DoublePendulum([180., 0.0, -20., 0.0])
dt = 1./30 # 30 fps

#------------------------------------------------------------
# set up figure and animation
fig = plt.figure()
xlim=(-2, 2), ylim=(-2, 2))
ax.grid()

line, = ax.plot([], [], 'o-', lw=2)
time_text = ax.text(0.02, 0.95, '', transform=ax.transAxes)
energy_text = ax.text(0.02, 0.90, '', transform=ax.transAxes)

def init():
"""initialize animation"""
line.set_data([], [])
time_text.set_text('')
energy_text.set_text('')
return line, time_text, energy_text

def animate(i):
"""perform animation step"""
global pendulum, dt
pendulum.step(dt)

line.set_data(*pendulum.position())
time_text.set_text('time = %.1f' % pendulum.time_elapsed)
energy_text.set_text('energy = %.3f J' % pendulum.energy())
return line, time_text, energy_text

# choose the interval based on dt and the time to animate one step
from time import time
t0 = time()
animate(0)
t1 = time()
interval = 1000 * dt - (t1 - t0)

ani = animation.FuncAnimation(fig, animate, frames=300,
interval=interval, blit=False, init_func=init)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# http://matplotlib.sourceforge.net/api/animation_api.html
ani.save('double_pendulum.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()

In [4]:
import numpy as np
from scipy.spatial.distance import pdist, squareform

import matplotlib.pyplot as plt
import scipy.integrate as integrate
import matplotlib.animation as animation

class ParticleBox:
"""Orbits class

init_state is an [N x 4] array, where N is the number of particles:
[[x1, y1, vx1, vy1],
[x2, y2, vx2, vy2],
...               ]

bounds is the size of the box: [xmin, xmax, ymin, ymax]
"""
def __init__(self,
init_state = [[1, 0, 0, -1],
[-0.5, 0.5, 0.5, 0.5],
[-0.5, -0.5, -0.5, 0.5]],
bounds = [-2, 2, -2, 2],
size = 0.04,
M = 0.05,
G = 9.8):
self.init_state = np.asarray(init_state, dtype=float)
self.M = M * np.ones(self.init_state.shape[0])
self.size = size
self.state = self.init_state.copy()
self.time_elapsed = 0
self.bounds = bounds
self.G = G

def step(self, dt):
"""step once by dt seconds"""
self.time_elapsed += dt

# update positions
self.state[:, :2] += dt * self.state[:, 2:]

# find pairs of particles undergoing a collision
D = squareform(pdist(self.state[:, :2]))
ind1, ind2 = np.where(D < 2 * self.size)
unique = (ind1 < ind2)
ind1 = ind1[unique]
ind2 = ind2[unique]

# update velocities of colliding pairs
for i1, i2 in zip(ind1, ind2):
# mass
m1 = self.M[i1]
m2 = self.M[i2]

# location vector
r1 = self.state[i1, :2]
r2 = self.state[i2, :2]

# velocity vector
v1 = self.state[i1, 2:]
v2 = self.state[i2, 2:]

# relative location & velocity vectors
r_rel = r1 - r2
v_rel = v1 - v2

# momentum vector of the center of mass
v_cm = (m1 * v1 + m2 * v2) / (m1 + m2)

# collisions of spheres reflect v_rel over r_rel
rr_rel = np.dot(r_rel, r_rel)
vr_rel = np.dot(v_rel, r_rel)
v_rel = 2 * r_rel * vr_rel / rr_rel - v_rel

# assign new velocities
self.state[i1, 2:] = v_cm + v_rel * m2 / (m1 + m2)
self.state[i2, 2:] = v_cm - v_rel * m1 / (m1 + m2)

# check for crossing boundary
crossed_x1 = (self.state[:, 0] < self.bounds[0] + self.size)
crossed_x2 = (self.state[:, 0] > self.bounds[1] - self.size)
crossed_y1 = (self.state[:, 1] < self.bounds[2] + self.size)
crossed_y2 = (self.state[:, 1] > self.bounds[3] - self.size)

self.state[crossed_x1, 0] = self.bounds[0] + self.size
self.state[crossed_x2, 0] = self.bounds[1] - self.size

self.state[crossed_y1, 1] = self.bounds[2] + self.size
self.state[crossed_y2, 1] = self.bounds[3] - self.size

self.state[crossed_x1 | crossed_x2, 2] *= -1
self.state[crossed_y1 | crossed_y2, 3] *= -1

self.state[:, 3] -= self.M * self.G * dt

#------------------------------------------------------------
# set up initial state
np.random.seed(0)
init_state = -0.5 + np.random.random((50, 4))
init_state[:, :2] *= 3.9

box = ParticleBox(init_state, size=0.04)
dt = 1. / 30 # 30fps

#------------------------------------------------------------
# set up figure and animation
fig = plt.figure()
xlim=(-3.2, 3.2), ylim=(-2.4, 2.4))

# particles holds the locations of the particles
particles, = ax.plot([], [], 'bo', ms=6)

# rect is the box edge
rect = plt.Rectangle(box.bounds[::2],
box.bounds[1] - box.bounds[0],
box.bounds[3] - box.bounds[2],
ec='none', lw=2, fc='none')

def init():
"""initialize animation"""
global box, rect
particles.set_data([], [])
rect.set_edgecolor('none')
return particles, rect

def animate(i):
"""perform animation step"""
global box, rect, dt, ax, fig
box.step(dt)

ms = int(fig.dpi * 2 * box.size * fig.get_figwidth()
/ np.diff(ax.get_xbound())[0])

# update pieces of the animation
rect.set_edgecolor('k')
particles.set_data(box.state[:, 0], box.state[:, 1])
particles.set_markersize(ms)
return particles, rect

ani = animation.FuncAnimation(fig, animate, frames=600,
interval=10, blit=True, init_func=init)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# http://matplotlib.sourceforge.net/api/animation_api.html
#ani.save('particle_box.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()

In [3]:
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation

def Gen_RandLine(length, dims=2) :
"""
Create a line using a random walk algorithm

length is the number of points for the line.
dims is the number of dimensions the line has.
"""
lineData = np.empty((dims, length))
lineData[:, 0] = np.random.rand(dims)
for index in range(1, length) :
# scaling the random numbers by 0.1 so
# movement is small compared to position.
# subtraction by 0.5 is to change the range to [-0.5, 0.5]
# to allow a line to move backwards.
step = ((np.random.rand(dims) - 0.5) * 0.1)
lineData[:, index] = lineData[:, index-1] + step

return lineData

def update_lines(num, dataLines, lines) :
for line, data in zip(lines, dataLines) :
# NOTE: there is no .set_data() for 3 dim data...
line.set_data(data[0:2, :num])
line.set_3d_properties(data[2,:num])
return lines

# Attaching 3D axis to the figure
fig = plt.figure()
ax = p3.Axes3D(fig)

# Fifty lines of random 3-D lines
data = [Gen_RandLine(25, 3) for index in range(50)]

# Creating fifty line objects.
# NOTE: Can't pass empty arrays into 3d version of plot()
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data]

# Setting the axes properties
ax.set_xlim3d([0.0, 1.0])
ax.set_xlabel('X')

ax.set_ylim3d([0.0, 1.0])
ax.set_ylabel('Y')

ax.set_zlim3d([0.0, 1.0])
ax.set_zlabel('Z')

ax.set_title('3D Test')

# Creating the Animation object
line_ani = animation.FuncAnimation(fig, update_lines, 25, fargs=(data, lines),
interval=50, blit=False)

plt.show()

In [5]:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def update_line(num, data, line):
line.set_data(data[...,:num])
return line,

fig1 = plt.figure()

data = np.random.rand(2, 25)
l, = plt.plot([], [], 'r-')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l),
interval=50, blit=True)
#line_ani.save('lines.mp4')

fig2 = plt.figure()

x = np.arange(-9, 10)
y = np.arange(-9, 10).reshape(-1, 1)
base = np.hypot(x, y)
ims = []
ims.append((plt.pcolor(x, y, base + add, norm=plt.Normalize(0, 30)),))

im_ani = animation.ArtistAnimation(fig2, ims, interval=50, repeat_delay=3000,
blit=True)

plt.show()

In [ ]:
import pylab
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

x = np.arange(0, 2*np.pi, 0.01)        # x-array
line, = ax.plot(x, np.sin(x))

def animate(i):
line.set_ydata(np.sin(x+i/10.0))  # update the data
return line,

#Init only required for blitting to give a clean slate.
def init():
return line,

ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,
interval=25, blit=True)
plt.show()

In [9]:
import numpy as np
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
import matplotlib.animation as animation

class Scope:
def __init__(self, ax, maxt=2, dt=0.02):
self.ax = ax
self.dt = dt
self.maxt = maxt
self.tdata = [0]
self.ydata = [0]
self.line = Line2D(self.tdata, self.ydata)
self.ax.set_ylim(-.1, 1.1)
self.ax.set_xlim(0, self.maxt)

def update(self, y):
lastt = self.tdata[-1]
if lastt > self.tdata[0] + self.maxt: # reset the arrays
self.tdata = [self.tdata[-1]]
self.ydata = [self.ydata[-1]]
self.ax.set_xlim(self.tdata[0], self.tdata[0] + self.maxt)
self.ax.figure.canvas.draw()

t = self.tdata[-1] + self.dt
self.tdata.append(t)
self.ydata.append(y)
self.line.set_data(self.tdata, self.ydata)
return self.line,

def emitter(p=0.03):
'return a random value with probability p, else 0'
while True:
v = np.random.rand(1)
if v > p:
yield 0.
else:
yield np.random.rand(1)

fig, ax = plt.subplots()
scope = Scope(ax)

# pass a generator in "emitter" to produce data for the update func
ani = animation.FuncAnimation(fig, scope.update, emitter, interval=10,
blit=True)

plt.show()


In [5]:
%pylab inline
from clawpack import pyclaw
from clawpack import riemann
#from matplotlib import animation
#import matplotlib.pyplot as plt
from clawpack.visclaw.JSAnimation import IPython_display
import numpy as np
claw = pyclaw.Controller()
claw.tfinal = 1.0

claw.keep_copy = True       # Keep solution data in memory for plotting
claw.output_format = None   # Don't write solution data to file
claw.num_output_times = 50
riemann
riemann_solver = riemann.acoustics_1D
claw.solver = pyclaw.ClawSolver1D(riemann_solver)
claw.solver.all_bcs = pyclaw.BC.periodic
domain = pyclaw.Domain( (0.,), (1.,), (100,))
claw.solution = pyclaw.Solution(claw.solver.num_eqn,domain)
x=domain.grid.x.centers
bet=100; gam=5; x0=0.75
claw.solution.q[0,:] = np.exp(-bet * (x-x0)**2) * np.cos(gam * (x - x0))
claw.solution.q[1,:] = 0.

plt.plot(x, claw.solution.q[0,:],'-o')
riemann_solver.cparam
import numpy as np

density = 1.0
bulk_modulus = 1.0
impedance = np.sqrt(density*bulk_modulus)
sound_speed = np.sqrt(density/bulk_modulus)

claw.solution.state.problem_data = {
'rho' : density,
'bulk': bulk_modulus,
'zz'  : np.sqrt(density*bulk_modulus),
'cc'  : np.sqrt(bulk_modulus/density)
}
status = claw.run()
pressure = claw.frames[50].q[0,:]
plt.plot(x,pressure,'-o')

fig = plt.figure()
ax = plt.axes(xlim=(0, 1), ylim=(-0.2, 1.2))

frame = claw.frames[0]
pressure = frame.q[0,:]
line, = ax.plot([], [], lw=2)

def fplot(frame_number):
frame = claw.frames[frame_number]
pressure = frame.q[0,:]
line.set_data(x,pressure)
return line,

animation.FuncAnimation(fig, fplot, frames=len(claw.frames), interval=30)

Populating the interactive namespace from numpy and matplotlib 2019-08-08 15:40:25,317 INFO CLAW: Solution 0 computed for time t=0.000000 2019-08-08 15:40:25,320 INFO CLAW: Solution 1 computed for time t=0.020000 2019-08-08 15:40:25,323 INFO CLAW: Solution 2 computed for time t=0.040000 2019-08-08 15:40:25,326 INFO CLAW: Solution 3 computed for time t=0.060000 2019-08-08 15:40:25,329 INFO CLAW: Solution 4 computed for time t=0.080000 2019-08-08 15:40:25,331 INFO CLAW: Solution 5 computed for time t=0.100000 2019-08-08 15:40:25,334 INFO CLAW: Solution 6 computed for time t=0.120000 2019-08-08 15:40:25,337 INFO CLAW: Solution 7 computed for time t=0.140000 2019-08-08 15:40:25,339 INFO CLAW: Solution 8 computed for time t=0.160000 2019-08-08 15:40:25,342 INFO CLAW: Solution 9 computed for time t=0.180000 2019-08-08 15:40:25,344 INFO CLAW: Solution 10 computed for time t=0.200000 2019-08-08 15:40:25,347 INFO CLAW: Solution 11 computed for time t=0.220000 2019-08-08 15:40:25,350 INFO CLAW: Solution 12 computed for time t=0.240000 2019-08-08 15:40:25,360 INFO CLAW: Solution 13 computed for time t=0.260000 2019-08-08 15:40:25,363 INFO CLAW: Solution 14 computed for time t=0.280000 2019-08-08 15:40:25,366 INFO CLAW: Solution 15 computed for time t=0.300000 2019-08-08 15:40:25,420 INFO CLAW: Solution 16 computed for time t=0.320000 2019-08-08 15:40:25,429 INFO CLAW: Solution 17 computed for time t=0.340000 2019-08-08 15:40:25,432 INFO CLAW: Solution 18 computed for time t=0.360000 2019-08-08 15:40:25,435 INFO CLAW: Solution 19 computed for time t=0.380000 2019-08-08 15:40:25,439 INFO CLAW: Solution 20 computed for time t=0.400000 2019-08-08 15:40:25,442 INFO CLAW: Solution 21 computed for time t=0.420000 2019-08-08 15:40:25,445 INFO CLAW: Solution 22 computed for time t=0.440000 2019-08-08 15:40:25,448 INFO CLAW: Solution 23 computed for time t=0.460000 2019-08-08 15:40:25,452 INFO CLAW: Solution 24 computed for time t=0.480000 2019-08-08 15:40:25,455 INFO CLAW: Solution 25 computed for time t=0.500000 2019-08-08 15:40:25,457 INFO CLAW: Solution 26 computed for time t=0.520000 2019-08-08 15:40:25,460 INFO CLAW: Solution 27 computed for time t=0.540000 2019-08-08 15:40:25,464 INFO CLAW: Solution 28 computed for time t=0.560000 2019-08-08 15:40:25,467 INFO CLAW: Solution 29 computed for time t=0.580000 2019-08-08 15:40:25,470 INFO CLAW: Solution 30 computed for time t=0.600000 2019-08-08 15:40:25,517 INFO CLAW: Solution 31 computed for time t=0.620000 2019-08-08 15:40:25,520 INFO CLAW: Solution 32 computed for time t=0.640000 2019-08-08 15:40:25,524 INFO CLAW: Solution 33 computed for time t=0.660000 2019-08-08 15:40:25,528 INFO CLAW: Solution 34 computed for time t=0.680000 2019-08-08 15:40:25,532 INFO CLAW: Solution 35 computed for time t=0.700000 2019-08-08 15:40:25,536 INFO CLAW: Solution 36 computed for time t=0.720000 2019-08-08 15:40:25,540 INFO CLAW: Solution 37 computed for time t=0.740000 2019-08-08 15:40:25,543 INFO CLAW: Solution 38 computed for time t=0.760000 2019-08-08 15:40:25,546 INFO CLAW: Solution 39 computed for time t=0.780000 2019-08-08 15:40:25,549 INFO CLAW: Solution 40 computed for time t=0.800000 2019-08-08 15:40:25,552 INFO CLAW: Solution 41 computed for time t=0.820000 2019-08-08 15:40:25,556 INFO CLAW: Solution 42 computed for time t=0.840000 2019-08-08 15:40:25,621 INFO CLAW: Solution 43 computed for time t=0.860000 2019-08-08 15:40:25,625 INFO CLAW: Solution 44 computed for time t=0.880000 2019-08-08 15:40:25,628 INFO CLAW: Solution 45 computed for time t=0.900000 2019-08-08 15:40:25,632 INFO CLAW: Solution 46 computed for time t=0.920000 2019-08-08 15:40:25,635 INFO CLAW: Solution 47 computed for time t=0.940000 2019-08-08 15:40:25,654 INFO CLAW: Solution 48 computed for time t=0.960000 2019-08-08 15:40:25,658 INFO CLAW: Solution 49 computed for time t=0.980000 2019-08-08 15:40:25,662 INFO CLAW: Solution 50 computed for time t=1.000000
WARNING: 1 intermediate output message was discarded.
WARNING: 1 intermediate output message was discarded.
In [12]:
python make_animation.py


 File "<ipython-input-12-e68de4b2a7db>", line 1 python make_animation.py ^ SyntaxError: invalid syntax 
In [15]:
animation_example.ipynb


--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-15-b9fb7d3dcca5> in <module>() ----> 1 animation_example.ipynb NameError: name 'animation_example' is not defined 
In [30]:
%pylab inline

import matplotlib.pyplot as plt
import matplotlib.animation as manimation
from clawpack import pyclaw
from clawpack import riemann
from JSAnimation import IPython_display
from matplotlib import animation
#matplotlib.use("Agg")
# create a simple animation
fig = plt.figure()
ax = plt.axes(xlim=(0, 10), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

x = np.linspace(0, 10, 1000)

def init():
line.set_data([], [])
return line,

def animate(i):
line.set_data(x, np.cos(i * 0.02 * np.pi) * np.sin(x - i * 0.02 * np.pi))
return line,

animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=20, blit=True)


--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-30-8b0ca269f505> in <module>() 5 from clawpack import pyclaw 6 from clawpack import riemann ----> 7 from JSAnimation import IPython_display 8 from matplotlib import animation 9 #matplotlib.use("Agg") ImportError: No module named JSAnimation 
Populating the interactive namespace from numpy and matplotlib
In [ ]:
%pylab inline
from __future__ import  division
from matplotlib.patches import FancyArrow
import mpl_toolkits.mplot3d.art3d as art3d
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.gridspec as gridspec

def dftmatrix(Nfft=32,N=None):
'construct DFT matrix'
k= np.arange(Nfft)
if N is None: N = Nfft
n = arange(N)
U = matrix(exp(1j* 2*pi/Nfft *k*n[:,None])) # use numpy broadcasting to create matrix
return U/sqrt(Nfft)

Nfft=16
v = ones((16,1))
U = dftmatrix(Nfft=Nfft,N=16)

# ---
# hardcoded constants to format complicated figure

gs = gridspec.GridSpec(8,12)
gs.update( wspace=1, left=0.01)

fig =figure(figsize=(10,5))
ax0 = subplot(gs[:,:3])

ax0.set_aspect(1)
a=2*pi/Nfft*arange(Nfft)

colors = ['k','b','r','m','g','Brown','DarkBlue','Tomato','Violet', 'Tan','Salmon','Pink',
for j,i in enumerate(a):

ax0.text(1,0.1,'0',fontsize=16)
ax0.text(0.1,1,r'$\frac{\pi}{2}$',fontsize=22)
ax0.text(-1,0.1,r'$\pi$',fontsize=18)
ax0.text(0.1,-1.2,r'$\frac{3\pi}{2}$',fontsize=22)
ax0.axis(array([-1,1,-1,1])*1.45)
ax0.set_xlabel('Real')
ax0.set_ylabel('Imaginary')

# plots in the middle column
for i in range(8):
ax=subplot(gs[i,4:8])
ax.set_xticks([]);  ax.set_yticks([])
ax.set_ylabel(r'$\Omega_{%d}=%d\times\frac{2\pi}{16}$'%(i,i),fontsize=16,
rotation='horizontal')
ax.plot(U.real[:,i],'-o',color=colors[i])
ax.plot(U.imag[:,i],'--o',color=colors[i],alpha=0.2)
ax.axis(ymax=4/Nfft*1.1,ymin=-4/Nfft*1.1)
ax.set_xticks(arange(16))
ax.set_xlabel('n')

# plots in the far right column
for i in range(8):
ax=subplot(gs[i,8:])
ax.set_xticks([]);  ax.set_yticks([])
ax.set_ylabel(r'$\Omega_{%d}=%d\times\frac{2\pi}{16}$'%(i+8,i+8),fontsize=16,
rotation='horizontal')
ax.plot(U.real[:,i+8],'-o',color=colors[i+8])
ax.plot(U.imag[:,i+8],'--o',color=colors[i+8],alpha=0.2)
ax.axis(ymax=4/Nfft*1.1,ymin=-4/Nfft*1.1)
ax.yaxis.set_label_position('right')
ax.set_xticks(arange(16))
ax.set_xlabel('n')

In [ ]:
U = dftmatrix(64,16)
x = ones((16,1))
X = U.H*x

fig,ax=subplots()
fig.set_size_inches((8,4))

ax.set_aspect(0.8)
ax.grid()
ax.stem(arange(0,16)*2*pi/16.,abs(dftmatrix(16).H*x),
markerfmt='gs', basefmt='g-',linefmt='g-',
ax.set_ylabel(r'$|X(\Omega)|$',fontsize=18)
ax.set_xticks([0, pi/2., pi, 3*pi/2,2*pi])
ax.axis([-.1, 2*pi,-.1,4.1])
ax.legend(loc=0)
ax.set_xticklabels(['0',r'$\frac{\pi}{2}$', r'$\pi$',r'$\frac{3\pi}{2}$', r'$2\pi$'],
fontsize=18);

In [9]:
matplotlib.use("Agg")
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as manimation
matplotlib.use("Agg")
FFMpegWriter = manimation.writers['ffmpeg']
comment='Movie support!')

fig = plt.figure()
l, = plt.plot([], [], 'k-o')

plt.xlim(-5, 5)
plt.ylim(-5, 5)

x0,y0 = 0, 0

with writer.saving(fig, "writer_test.mp4", 100):
for i in range(100):
x0 += 0.1 * np.random.randn()
y0 += 0.1 * np.random.randn()
l.set_data(x0, y0)
writer.grab_frame()

/projects/sage/sage-6.10/local/lib/python2.7/site-packages/matplotlib-1.5.0-py2.7-linux-x86_64.egg/matplotlib/__init__.py:1350: UserWarning: This call to matplotlib.use() has no effect because the backend has already been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot, or matplotlib.backends is imported for the first time. warnings.warn(_use_error_msg)
In [6]:
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as manimation

FFMpegWriter = manimation.writers['ffmpeg']
comment='Movie support!')

fig = plt.figure()
l, = plt.plot([], [], 'k-o')

plt.xlim(-5, 5)
plt.ylim(-5, 5)

x0,y0 = 0, 0

with writer.saving(fig, "writer_test.mp4", 100):
for i in range(100):
x0 += 0.1 * np.random.randn()
y0 += 0.1 * np.random.randn()
l.set_data(x0, y0)
writer.grab_frame()

/usr/local/lib/python2.7/dist-packages/ipykernel/__main__.py:3: UserWarning: This call to matplotlib.use() has no effect because the backend has already been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot, or matplotlib.backends is imported for the first time. The backend was *originally* set to 'module://ipykernel.pylab.backend_inline' by the following code: File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/usr/local/lib/python2.7/dist-packages/ipykernel/__main__.py", line 3, in <module> app.launch_new_instance() File "/usr/local/lib/python2.7/dist-packages/traitlets/config/application.py", line 658, in launch_instance app.start() File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelapp.py", line 486, in start self.io_loop.start() File "/usr/lib/python2.7/dist-packages/zmq/eventloop/ioloop.py", line 177, in start super(ZMQIOLoop, self).start() File "/usr/lib/python2.7/dist-packages/tornado/ioloop.py", line 888, in start handler_func(fd_obj, events) File "/usr/lib/python2.7/dist-packages/tornado/stack_context.py", line 277, in null_wrapper return fn(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events self._handle_recv() File "/usr/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv self._run_callback(callback, msg) File "/usr/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback callback(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/tornado/stack_context.py", line 277, in null_wrapper return fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 283, in dispatcher return self.dispatch_shell(stream, msg) File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 233, in dispatch_shell handler(stream, idents, msg) File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 399, in execute_request user_expressions, allow_stdin) File "/usr/local/lib/python2.7/dist-packages/ipykernel/ipkernel.py", line 208, in do_execute res = shell.run_cell(code, store_history=store_history, silent=silent) File "/usr/local/lib/python2.7/dist-packages/ipykernel/zmqshell.py", line 537, in run_cell return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2714, in run_cell interactivity=interactivity, compiler=compiler, result=result) File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2818, in run_ast_nodes if self.run_code(code, result): File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2878, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-5-46cdedab5100>", line 1, in <module> get_ipython().magic(u'pylab inline') File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2160, in magic return self.run_line_magic(magic_name, magic_arg_s) File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2081, in run_line_magic result = fn(*args,**kwargs) File "</usr/local/lib/python2.7/dist-packages/decorator.pyc:decorator-gen-106>", line 2, in pylab File "/usr/local/lib/python2.7/dist-packages/IPython/core/magic.py", line 188, in <lambda> call = lambda f, *a, **k: f(*a, **k) File "/usr/local/lib/python2.7/dist-packages/IPython/core/magics/pylab.py", line 156, in pylab gui, backend, clobbered = self.shell.enable_pylab(args.gui, import_all=import_all) File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 3005, in enable_pylab gui, backend = self.enable_matplotlib(gui) File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2966, in enable_matplotlib pt.activate_matplotlib(backend) File "/usr/local/lib/python2.7/dist-packages/IPython/core/pylabtools.py", line 315, in activate_matplotlib matplotlib.pyplot.switch_backend(backend) File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 232, in switch_backend matplotlib.use(newbackend, warn=False, force=True) File "/usr/lib/python2.7/dist-packages/matplotlib/__init__.py", line 1306, in use reload(sys.modules['matplotlib.backends']) File "/usr/lib/python2.7/dist-packages/matplotlib/backends/__init__.py", line 14, in <module> line for line in traceback.format_stack() app.launch_new_instance()
In [10]:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,

# animation function.  This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,

# animation function.  This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,

# animation function.  This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,

# animation function.  This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()

 File "<ipython-input-250-0864ede6667a>", line 33 plt.show()import numpy as np ^ SyntaxError: invalid syntax 
 File "<ipython-input-10-0864ede6667a>", line 33 plt.show()import numpy as np ^ SyntaxError: invalid syntax 
In [7]:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,

# animation function.  This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()

In [11]:
from numpy import sin, cos
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import matplotlib.animation as animation

class DoublePendulum:
"""Double Pendulum Class

init_state is [theta1, omega1, theta2, omega2] in degrees,
where theta1, omega1 is the angular position and velocity of the first
pendulum arm, and theta2, omega2 is that of the second pendulum arm
"""
def __init__(self,
init_state = [120, 0, -20, 0],
L1=1.0,  # length of pendulum 1 in m
L2=1.0,  # length of pendulum 2 in m
M1=1.0,  # mass of pendulum 1 in kg
M2=1.0,  # mass of pendulum 2 in kg
G=9.8,  # acceleration due to gravity, in m/s^2
origin=(0, 0)):
self.init_state = np.asarray(init_state, dtype='float')
self.params = (L1, L2, M1, M2, G)
self.origin = origin
self.time_elapsed = 0

self.state = self.init_state * np.pi / 180.

def position(self):
"""compute the current x,y positions of the pendulum arms"""
(L1, L2, M1, M2, G) = self.params

x = np.cumsum([self.origin[0],
L1 * sin(self.state[0]),
L2 * sin(self.state[2])])
y = np.cumsum([self.origin[1],
-L1 * cos(self.state[0]),
-L2 * cos(self.state[2])])
return (x, y)

def energy(self):
"""compute the energy of the current state"""
(L1, L2, M1, M2, G) = self.params

x = np.cumsum([L1 * sin(self.state[0]),
L2 * sin(self.state[2])])
y = np.cumsum([-L1 * cos(self.state[0]),
-L2 * cos(self.state[2])])
vx = np.cumsum([L1 * self.state[1] * cos(self.state[0]),
L2 * self.state[3] * cos(self.state[2])])
vy = np.cumsum([L1 * self.state[1] * sin(self.state[0]),
L2 * self.state[3] * sin(self.state[2])])

U = G * (M1 * y[0] + M2 * y[1])
K = 0.5 * (M1 * np.dot(vx, vx) + M2 * np.dot(vy, vy))

return U + K

def dstate_dt(self, state, t):
"""compute the derivative of the given state"""
(M1, M2, L1, L2, G) = self.params

dydx = np.zeros_like(state)
dydx[0] = state[1]
dydx[2] = state[3]

cos_delta = cos(state[2] - state[0])
sin_delta = sin(state[2] - state[0])

den1 = (M1 + M2) * L1 - M2 * L1 * cos_delta * cos_delta
dydx[1] = (M2 * L1 * state[1] * state[1] * sin_delta * cos_delta
+ M2 * G * sin(state[2]) * cos_delta
+ M2 * L2 * state[3] * state[3] * sin_delta
- (M1 + M2) * G * sin(state[0])) / den1

den2 = (L2 / L1) * den1
dydx[3] = (-M2 * L2 * state[3] * state[3] * sin_delta * cos_delta
+ (M1 + M2) * G * sin(state[0]) * cos_delta
- (M1 + M2) * L1 * state[1] * state[1] * sin_delta
- (M1 + M2) * G * sin(state[2])) / den2

return dydx

def step(self, dt):
"""execute one time step of length dt and update state"""
self.state = integrate.odeint(self.dstate_dt, self.state, [0, dt])[1]
self.time_elapsed += dt

#------------------------------------------------------------
# set up initial state and global variables
pendulum = DoublePendulum([180., 0.0, -20., 0.0])
dt = 1./30 # 30 fps

#------------------------------------------------------------
# set up figure and animation
fig = plt.figure()
xlim=(-2, 2), ylim=(-2, 2))
ax.grid()

line, = ax.plot([], [], 'o-', lw=2)
time_text = ax.text(0.02, 0.95, '', transform=ax.transAxes)
energy_text = ax.text(0.02, 0.90, '', transform=ax.transAxes)

def init():
"""initialize animation"""
line.set_data([], [])
time_text.set_text('')
energy_text.set_text('')
return line, time_text, energy_text

def animate(i):
"""perform animation step"""
global pendulum, dt
pendulum.step(dt)

line.set_data(*pendulum.position())
time_text.set_text('time = %.1f' % pendulum.time_elapsed)
energy_text.set_text('energy = %.3f J' % pendulum.energy())
return line, time_text, energy_text

# choose the interval based on dt and the time to animate one step
from time import time
t0 = time()
animate(0)
t1 = time()
interval = 1000 * dt - (t1 - t0)

ani = animation.FuncAnimation(fig, animate, frames=300,
interval=interval, blit=True, init_func=init)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# http://matplotlib.sourceforge.net/api/animation_api.html
ani.save('double_pendulum.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()

--------------------------------------------------------------------------- IOError Traceback (most recent call last) <ipython-input-11-b6c57cb0ffc5> in <module>() 135 # your system: for more information, see 136 # http://matplotlib.sourceforge.net/api/animation_api.html --> 137 ani.save('double_pendulum.mp4', fps=30, extra_args=['-vcodec', 'libx264']) 138 139 plt.show() /projects/sage/sage-6.10/local/lib/python2.7/site-packages/matplotlib-1.5.0-py2.7-linux-x86_64.egg/matplotlib/animation.py in save(self, filename, writer, fps, dpi, codec, bitrate, extra_args, metadata, extra_anim, savefig_kwargs) 778 # TODO: Need to see if turning off blit is really necessary 779 anim._draw_next_frame(d, blit=False) --> 780 writer.grab_frame(**savefig_kwargs) 781 782 # Reconnect signal for first draw if necessary /projects/sage/sage-6.10/local/lib/python2.7/site-packages/matplotlib-1.5.0-py2.7-linux-x86_64.egg/matplotlib/animation.py in grab_frame(self, **savefig_kwargs) 223 # frame format and dpi. 224 self.fig.savefig(self._frame_sink(), format=self.frame_format, --> 225 dpi=self.dpi, **savefig_kwargs) 226 except RuntimeError: 227 out, err = self._proc.communicate() /projects/sage/sage-6.10/local/lib/python2.7/site-packages/matplotlib-1.5.0-py2.7-linux-x86_64.egg/matplotlib/figure.py in savefig(self, *args, **kwargs) 1537 self.set_frameon(frameon) 1538 -> 1539 self.canvas.print_figure(*args, **kwargs) 1540 1541 if frameon: /projects/sage/sage-6.10/local/lib/python2.7/site-packages/matplotlib-1.5.0-py2.7-linux-x86_64.egg/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs) 2228 orientation=orientation, 2229 bbox_inches_restore=_bbox_inches_restore, -> 2230 **kwargs) 2231 finally: 2232 if bbox_inches and restore_bbox: /projects/sage/sage-6.10/local/lib/python2.7/site-packages/matplotlib-1.5.0-py2.7-linux-x86_64.egg/matplotlib/backends/backend_agg.py in print_raw(self, filename_or_obj, *args, **kwargs) 517 close = False 518 try: --> 519 fileobj.write(renderer._renderer.buffer_rgba()) 520 finally: 521 if close: IOError: [Errno 32] Broken pipe 
In [40]:
from pylab import *
import os
# set the interactive mode of pylab to ON
ion()
# opens a new figure to plot into
fig_hndl = figure()
# make an empty list into which we'll append
# the filenames of the PNGs that compose each
# frame.
files=[]
# filename for the name of the resulting movie
filename = 'animation'
number_of_frames = 100
for t in range(number_of_frames):
# draw the frame
imshow(rand(100,100))
# form a filename
fname = '_tmp%03d.png'%t
# save the frame
savefig(fname)
# append the filename to the list
files.append(fname)
# call mencoder
os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=10
-ovc lavc -lavcopts vcodec=wmv2 -oac copy
-o " + filename + ".mpg")
# cleanup
for fname in files: os.remove(fname)

 File "<ipython-input-40-cd26f200e280>", line 24 os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=10 ^ SyntaxError: EOL while scanning string literal 
In [12]:
import sys
import os
import glob
from multiprocessing import Pool,cpu_count

from pylab import *
import netCDF4
import datetime as dt
import numpy.ma as ma

from datetime import date, datetime, timedelta
from visvis import movieWrite

from PIL import Image
NUM_PROCESSES = 6
def perdelta(start, end, delta):
curr = start
while curr < end:
yield curr
curr += delta
def plotWave(args):
url = args['url']
box = args['box']
name = args['title']
start = args['date']
vname = args['vname']
imname = 'input_0000'+start.strftime('%Y%m%d%H%M')+'.png'
nc = netCDF4.Dataset(url)
lat = nc.variables['lat'][:]
lon = nc.variables['lon'][:]
time_var = nc.variables['time']
dtime = netCDF4.num2date(time_var[:],time_var.units)
bi=(lon>=box[0])&(lon<=box[2])
bj=(lat>=box[1])&(lat<=box[3])
istart = netCDF4.date2index(start,time_var,select='nearest')
var = nc.variables[vname][istart,bj,bi]
plt.figure(figsize=(8,8))
plt.pcolormesh(lon[bi], lat[bj], hs, vmin=0, vmax=3)
#print imname
plt.title('%s %s' %(name, start.strftime('%Y/%m/%d %H:%M')) )
plt.savefig(imname)
ef gen_dates(nc,vname,past,box,title):
#print url
for result in perdelta(datetime.utcnow() - timedelta(days=past), datetime.utcnow(), timedelta(hours=1)):
#		print "gen_dates:",type(result),result
yield {'url':url, 'vname':vname, 'date':result, 'box':box, 'title':title}
def makeGOMmovie(url,vname,days,box,title=""):
print url
pool = Pool(processes=4)
results = pool.imap_unordered(plotWave, gen_dates(url,vname,days,box,title), 100)
pool.close()
pool.join()
cd /usgs/data2/notebook/frames
url='http://thredds.ucar.edu/thredds/dodsC/grib/NCEP/WW3/Coastal_US_East_Coast/best'
box = [-71.5,39.5,-63.,46.]
days = 1
vname = 'Significant_height_of_combined_wind_waves_and_swell_surface'
title = 'Wave Height in the Gulf of Maine'
makeGOMmovie(url,vname,days,box,title)
IMGS = []
imgs = glob.glob("*.png")
print imgs
for im in imgs:
IMGS.append(Image.open(im))
movieWrite("/var/www/images/latest.gif",IMGS)
from IPython.core.display import HTML
HTML('<img src="http://geoport.whoi.edu/images/latest.gif" />')

 File "<ipython-input-12-722b7c2a9e9a>", line 43 ef gen_dates(nc,vname,past,box,title): ^ SyntaxError: invalid syntax 
In [43]:
from IPython import parallel
rc = parallel.Client()
rc.block=True
rc.ids
myArgs=gen_dates(url, vname,days,box,title="")
view.map(plotWave, myArgs)

--------------------------------------------------------------------------- IOError Traceback (most recent call last) <ipython-input-43-caeef17811a7> in <module>() 1 from IPython import parallel ----> 2 rc = parallel.Client() 3 rc.block=True 4 rc.ids 5 view=rc.load_balanced_view() /usr/local/sage/sage-6.2/local/lib/python2.7/site-packages/IPython/parallel/client/client.py in __init__(self, url_file, profile, profile_dir, ipython_dir, context, debug, sshserver, sshkey, password, paramiko, timeout, cluster_id, **extra_args) 407 ) 408 --> 409 with open(url_file) as f: 410 cfg = json.load(f) 411 IOError: [Errno 2] No such file or directory: u'/projects/d2667bf4-a57b-4454-9956-d8d176cb2d03/.sage/ipython-1.2.1/profile_default/security/ipcontroller-client.json' 
In [1]:
%octave
x=20000000003

tic()
y=floor(x^.5)
parfor i = 2:y
c(:,i) = abs(sin((x+i)*pi/i));

end

parfor n=2:y

if (c(:,n))<1e-6
n,"nonprime"
toc()
exit
endif
end
x,"prime"
toc()


 File "<ipython-input-1-d7a6b27299a3>", line 6 parfor i = 2:y ^ SyntaxError: invalid syntax 
In [13]:
import os
import sys
import random
import string
import warnings
if sys.version_info < (3, 0):
from cStringIO import StringIO as InMemory
else:
from io import BytesIO as InMemory
from matplotlib.animation import writers, FileMovieWriter
from base64 import b64encode

ICON_DIR = os.path.join(os.path.dirname(__file__), 'icons')

class _Icons(object):
"""This class is a container for base64 representations of the icons"""
icons = ['first', 'prev', 'reverse', 'pause', 'play', 'next', 'last']

def __init__(self, icon_dir=ICON_DIR, extension='png'):
self.icon_dir = icon_dir
self.extension = extension
for icon in self.icons:
setattr(self, icon,

return 'data:image/{0};base64,{1}'.format(self.extension,
b64encode(data).decode('ascii'))

JS_INCLUDE = """
<script language="javascript">
/* Define the Animation class */
function Animation(frames, img_id, slider_id, interval, loop_select_id){
this.img_id = img_id;
this.slider_id = slider_id;
this.loop_select_id = loop_select_id;
this.interval = interval;
this.current_frame = 0;
this.direction = 0;
this.timer = null;
this.frames = new Array(frames.length);

for (var i=0; i<frames.length; i++)
{
this.frames[i] = new Image();
this.frames[i].src = frames[i];
}
document.getElementById(this.slider_id).max = this.frames.length - 1;
this.set_frame(this.current_frame);
}

Animation.prototype.get_loop_state = function(){
var button_group = document[this.loop_select_id].state;
for (var i = 0; i < button_group.length; i++) {
var button = button_group[i];
if (button.checked) {
return button.value;
}
}
return undefined;
}

Animation.prototype.set_frame = function(frame){
this.current_frame = frame;
document.getElementById(this.img_id).src = this.frames[this.current_frame].src;
document.getElementById(this.slider_id).value = this.current_frame;
}

Animation.prototype.next_frame = function()
{
this.set_frame(Math.min(this.frames.length - 1, this.current_frame + 1));
}

Animation.prototype.previous_frame = function()
{
this.set_frame(Math.max(0, this.current_frame - 1));
}

Animation.prototype.first_frame = function()
{
this.set_frame(0);
}

Animation.prototype.last_frame = function()
{
this.set_frame(this.frames.length - 1);
}

Animation.prototype.slower = function()
{
this.interval /= 0.7;
if(this.direction > 0){this.play_animation();}
else if(this.direction < 0){this.reverse_animation();}
}

Animation.prototype.faster = function()
{
this.interval *= 0.7;
if(this.direction > 0){this.play_animation();}
else if(this.direction < 0){this.reverse_animation();}
}

Animation.prototype.anim_step_forward = function()
{
this.current_frame += 1;
if(this.current_frame < this.frames.length){
this.set_frame(this.current_frame);
}else{
var loop_state = this.get_loop_state();
if(loop_state == "loop"){
this.first_frame();
}else if(loop_state == "reflect"){
this.last_frame();
this.reverse_animation();
}else{
this.pause_animation();
this.last_frame();
}
}
}

Animation.prototype.anim_step_reverse = function()
{
this.current_frame -= 1;
if(this.current_frame >= 0){
this.set_frame(this.current_frame);
}else{
var loop_state = this.get_loop_state();
if(loop_state == "loop"){
this.last_frame();
}else if(loop_state == "reflect"){
this.first_frame();
this.play_animation();
}else{
this.pause_animation();
this.first_frame();
}
}
}

Animation.prototype.pause_animation = function()
{
this.direction = 0;
if (this.timer){
clearInterval(this.timer);
this.timer = null;
}
}

Animation.prototype.play_animation = function()
{
this.pause_animation();
this.direction = 1;
var t = this;
if (!this.timer) this.timer = setInterval(function(){t.anim_step_forward();}, this.interval);
}

Animation.prototype.reverse_animation = function()
{
this.pause_animation();
this.direction = -1;
var t = this;
if (!this.timer) this.timer = setInterval(function(){t.anim_step_reverse();}, this.interval);
}
</script>
"""

DISPLAY_TEMPLATE = """
<div class="animation" align="center">
<img id="_anim_img{id}">
<br>
<input id="_anim_slider{id}" type="range" style="width:350px" name="points" min="0" max="1" step="1" value="0" onchange="anim{id}.set_frame(parseInt(this.value));"></input>
<br>
<button onclick="anim{id}.slower()">&#8211;</button>
<button onclick="anim{id}.first_frame()"><img class="anim_icon" src="{icons.first}"></button>
<button onclick="anim{id}.previous_frame()"><img class="anim_icon" src="{icons.prev}"></button>
<button onclick="anim{id}.reverse_animation()"><img class="anim_icon" src="{icons.reverse}"></button>
<button onclick="anim{id}.pause_animation()"><img class="anim_icon" src="{icons.pause}"></button>
<button onclick="anim{id}.play_animation()"><img class="anim_icon" src="{icons.play}"></button>
<button onclick="anim{id}.next_frame()"><img class="anim_icon" src="{icons.next}"></button>
<button onclick="anim{id}.last_frame()"><img class="anim_icon" src="{icons.last}"></button>
<button onclick="anim{id}.faster()">+</button>
<form action="#n" name="_anim_loop_select{id}" class="anim_control">
<input type="radio" name="state" value="once" {once_checked}> Once </input>
<input type="radio" name="state" value="loop" {loop_checked}> Loop </input>
<input type="radio" name="state" value="reflect" {reflect_checked}> Reflect </input>
</form>
</div>

<script language="javascript">
/* Instantiate the Animation class. */
/* The IDs given should match those used in the template above. */
(function() {{
var img_id = "_anim_img{id}";
var slider_id = "_anim_slider{id}";
var loop_select_id = "_anim_loop_select{id}";
var frames = new Array({Nframes});
{fill_frames}

/* set a timeout to make sure all the above elements are created before
the object is initialized. */
setTimeout(function() {{
anim{id} = new Animation(frames, img_id, slider_id, {interval}, loop_select_id);
}}, 0);
}})()
</script>
"""

INCLUDED_FRAMES = """
for (var i=0; i<{Nframes}; i++){{
frames[i] = "{frame_dir}/frame" + ("0000000" + i).slice(-7) + ".{frame_format}";
}}
"""

def _included_frames(frame_list, frame_format):
"""frame_list should be a list of filenames"""
return INCLUDED_FRAMES.format(Nframes=len(frame_list),
frame_dir=os.path.dirname(frame_list[0]),
frame_format=frame_format)

def _embedded_frames(frame_list, frame_format):
"""frame_list should be a list of base64-encoded png files"""
template = '  frames[{0}] = "data:image/{1};base64,{2}"\n'
embedded = "\n"
for i, frame_data in enumerate(frame_list):
embedded += template.format(i, frame_format,
frame_data.replace('\n', '\\\n'))
return embedded

@writers.register('html')
class HTMLWriter(FileMovieWriter):
# we start the animation id count at a random number: this way, if two
# animations are meant to be included on one HTML page, there is a
# very small chance of conflict.
rng = random.Random()
exec_key = 'animation.ffmpeg_path'
args_key = 'animation.ffmpeg_args'
supported_formats = ['png', 'jpeg', 'tiff', 'svg']

@classmethod
def new_id(cls):
#return '%16x' % cls.rng.getrandbits(64)
return ''.join(cls.rng.choice(string.ascii_uppercase)
for x in range(16))

def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None,
self.embed_frames = embed_frames
self.default_mode = default_mode.lower()

if self.default_mode not in ['loop', 'once', 'reflect']:
self.default_mode = 'loop'
warnings.warn("unrecognized default_mode: using 'loop'")

self._saved_frames = list()
super(HTMLWriter, self).__init__(fps, codec, bitrate,

def setup(self, fig, outfile, dpi, frame_dir=None):
if os.path.splitext(outfile)[-1] not in ['.html', '.htm']:
raise ValueError("outfile must be *.htm or *.html")

if not self.embed_frames:
if frame_dir is None:
frame_dir = outfile.rstrip('.html') + '_frames'
if not os.path.exists(frame_dir):
os.makedirs(frame_dir)
frame_prefix = os.path.join(frame_dir, 'frame')
else:
frame_prefix = None

super(HTMLWriter, self).setup(fig, outfile, dpi,
frame_prefix, clear_temp=False)

def grab_frame(self, **savefig_kwargs):
if self.embed_frames:
suffix = '.' + self.frame_format
f = InMemory()
self.fig.savefig(f, format=self.frame_format,
dpi=self.dpi, **savefig_kwargs)
f.seek(0)
else:
return super(HTMLWriter, self).grab_frame(**savefig_kwargs)

def _run(self):
# make a ducktyped subprocess standin
# this is called by the MovieWriter base class, but not used here.
class ProcessStandin(object):
returncode = 0
def communicate(self):
return ('', '')
self._proc = ProcessStandin()

# save the frames to an html file
if self.embed_frames:
fill_frames = _embedded_frames(self._saved_frames,
self.frame_format)
else:
# temp names is filled by FileMovieWriter
fill_frames = _included_frames(self._temp_names,
self.frame_format)

mode_dict = dict(once_checked='',
loop_checked='',
reflect_checked='')
mode_dict[self.default_mode + '_checked'] = 'checked'

interval = int(1000. / self.fps)

with open(self.outfile, 'w') as of:
of.write(JS_INCLUDE)
of.write(DISPLAY_TEMPLATE.format(id=self.new_id(),
Nframes=len(self._temp_names),
fill_frames=fill_frames,
interval=interval,
icons=_Icons(),
**mode_dict))

--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-13-6f6e74282130> in <module>() 12 13 ---> 14 ICON_DIR = os.path.join(os.path.dirname(__file__), 'icons') 15 16 NameError: name '__file__' is not defined 
In [1]:
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

from JSAnimation import HTMLWriter

N_trajectories = 20

def lorentz_deriv((x, y, z), t0, sigma=10., beta=8./3, rho=28.0):
"""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_trajectories, 3))

# Solve for the trajectories
t = np.linspace(0, 2, 500)
x_t = np.asarray([integrate.odeint(lorentz_deriv, x0i, t)
for x0i in x0])

# Set up figure & 3D axis for animation
fig = plt.figure(figsize=(4, 3))
ax = fig.add_axes([0, 0, 1, 1], projection='3d')
ax.axis('off')

# choose a different color for each trajectory
colors = plt.cm.jet(np.linspace(0, 1, N_trajectories))

# set up lines and points
lines = sum([ax.plot([], [], [], '-', c=c)
for c in colors], [])
pts = sum([ax.plot([], [], [], 'o', c=c, ms=4)
for c in colors], [])

# prepare the axes limits
ax.set_xlim((-25, 25))
ax.set_ylim((-35, 35))
ax.set_zlim((5, 55))

# set point-of-view: specified by (altitude degrees, azimuth degrees)
ax.view_init(30, 0)

# initialization function: plot the background of each frame
def init():
for line, pt in zip(lines, pts):
line.set_data([], [])
line.set_3d_properties([])

pt.set_data([], [])
pt.set_3d_properties([])
return lines + pts

# animation function.  This will be called sequentially with the frame number
def animate(i):
# we'll step two time-steps per frame.  This leads to nice results.
i = (2 * i) % x_t.shape[1]

for line, pt, xi in zip(lines, pts, x_t):
x, y, z = xi[:i + 1].T
line.set_data(x, y)
line.set_3d_properties(z)

pt.set_data(x[-1:], y[-1:])
pt.set_3d_properties(z[-1:])

ax.view_init(30, 0.3 * i)
fig.canvas.draw()
return lines + pts

# instantiate the animator.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=30, blit=True)

# set embed_frames=False so that frames will be stored individually
anim.save('lorenz_animation.html', writer=HTMLWriter(embed_frames=False))


--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-1-565bfe0254cb> in <module>() 7 from matplotlib import animation 8 ----> 9 from JSAnimation import HTMLWriter 10 11 N_trajectories = 20 ImportError: No module named JSAnimation 
In [16]:
%%cython
def cython_sum ( n ):
from math import sin
return sum ( sin ( i ) for i in xrange (1 , n +1))


warning: .cache/ipython/cython/_cython_magic_cf41ac5c8402992e2cedd6a88163a947.pyx:1:0: Unreachable code Error compiling Cython file: ------------------------------------------------------------ ... def cython_sum ( n ): from math import sin return sum ( sin ( i ) for i in xrange (1 , n +1)) ^ ------------------------------------------------------------ .cache/ipython/cython/_cython_magic_cf41ac5c8402992e2cedd6a88163a947.pyx:3:0: Return not inside a function body Error compiling Cython file: ------------------------------------------------------------ ... def cython_sum ( n ): from math import sin return sum ( sin ( i ) for i in xrange (1 , n +1)) ^ ------------------------------------------------------------ .cache/ipython/cython/_cython_magic_cf41ac5c8402992e2cedd6a88163a947.pyx:3:46: undeclared name not builtin: n Error compiling Cython file: ------------------------------------------------------------ ... def cython_sum ( n ): from math import sin return sum ( sin ( i ) for i in xrange (1 , n +1)) ^ ------------------------------------------------------------ .cache/ipython/cython/_cython_magic_cf41ac5c8402992e2cedd6a88163a947.pyx:3:17: undeclared name not builtin: sin Error compiling Cython file: ------------------------------------------------------------ ... def cython_sum ( n ): from math import sin return sum ( sin ( i ) for i in xrange (1 , n +1)) ^ ------------------------------------------------------------ .cache/ipython/cython/_cython_magic_cf41ac5c8402992e2cedd6a88163a947.pyx:3:11: Compiler crash in OptimizeBuiltinCalls ModuleNode.body = StatListNode(_cython_magic_cf41ac5c8402992e2cedd6a88163a947.pyx:1:0, is_terminator = True) StatListNode.stats[2] = ReturnStatNode(_cython_magic_cf41ac5c8402992e2cedd6a88163a947.pyx:3:0, is_terminator = True) ReturnStatNode.value = SimpleCallNode(_cython_magic_cf41ac5c8402992e2cedd6a88163a947.pyx:3:11, result_is_used = True, use_managed_ref = True) Compiler crash traceback from this point on: File "Visitor.py", line 170, in Cython.Compiler.Visitor.TreeVisitor._visit (Cython/Compiler/Visitor.c:4284) File "Visitor.py", line 488, in Cython.Compiler.Visitor.MethodDispatcherTransform.visit_SimpleCallNode (Cython/Compiler/Visitor.c:9692) AttributeError: 'NoneType' object has no attribute 'is_pyobject'
In [3]:
%load_ext cythonmagic


In [246]:

%%cython
def f(x):
return 2.0*x

ERROR: Cell magic %%cython not found.
In [ ]:
f(26)


In [ ]:
%%cython
from math import sin
def cython_sum(n):
return sum ( sin ( i ) for i in xrange (1 , n +1))


In [ ]:
(cython_sum(100000000000))

In [245]:
%%cython
def prod(*iterable):
p= 1
for n in iterable:
p *= n
return p


ERROR: Cell magic %%cython not found.
In [ ]:
prod(10)

In [ ]:


In [ ]:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

majorLocator   = MultipleLocator(20)
majorFormatter = FormatStrFormatter('%d')
minorLocator   = MultipleLocator(5)

x = 40
t = np.arange(2, 20, .1)
s = np.sin((x+t)*np.pi/t)

fig, ax = plt.subplots()
plt.plot(t,s)

ax.xaxis.set_major_locator(majorLocator)
ax.xaxis.set_major_formatter(majorFormatter)

#for the minor ticks, use no labels; default NullFormatter
ax.xaxis.set_minor_locator(minorLocator)

plt.show()

In [8]:
np.fft.fft(np.exp(2j * np.pi * np.arange(16) / 16))

array([ -8.99620797e-16 -4.40687738e-17j, 1.60000000e+01 -7.25077679e-15j, 6.65262409e-16 +8.32123684e-17j, -2.21867130e-31 -4.74809032e-17j, 5.99180286e-16 -6.54691437e-16j, 3.33066907e-15 +2.29714122e-15j, 6.00227049e-16 +1.10377247e-15j, 5.54667824e-31 +5.32749612e-16j, 2.10602227e-16 +6.69535287e-17j, 0.00000000e+00 +2.07509661e-15j, -1.98288444e-16 +1.61716991e-16j, 2.21867130e-31 +2.92410263e-16j, -4.00020436e-16 +1.12166540e-15j, -3.33066907e-15 +1.40896280e-15j, -5.77342295e-16 -8.58843107e-16j, -5.54667824e-31 -2.87820252e-16j])
In [11]:
 import matplotlib.pyplot as plt
t = np.arange(2,256)
sp = np.fft.fft(np.sin(t+23)*np.pi/t)
freq = np.fft.fftfreq(t.shape[0])
plt.plot(freq, sp.real, freq, sp.imag)

plt.show()

 File "<ipython-input-11-df4cd182b04d>", line 2 t = np.arange(2,256) ^ IndentationError: unexpected indent 
In [9]:
a = FastFourierTransform(16)
for i in range(16): a[i] = (random(),random())
A = plot(a)
B = plot(a, style='polar')
type(A)

type(B)

a = FastFourierTransform(125)
b = FastFourierTransform(125)
for i in range(1, 60): a[i]=1
for i in range(1, 60): b[i]=1
a.forward_transform()
a.inverse_transform()

(a.plot()+b.plot())

--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-9-20c6d8a668c4> in <module>() ----> 1 a = FastFourierTransform(16) 2 for i in range(16): a[i] = (random(),random()) 3 A = plot(a) 4 B = plot(a, style='polar') 5 type(A) NameError: name 'FastFourierTransform' is not defined 
In [8]:
a = FFT(8)
a

--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-8-c5e2a0d2fb58> in <module>() ----> 1 a = FFT(8) 2 a NameError: name 'FFT' is not defined 
In [271]:
import pygsl

--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-271-a7eacf315851> in <module>() ----> 1 import pygsl ImportError: No module named pygsl 
In [7]:
import numpy as np
import pygsl.monte as monte
import pygsl.rng

def g(xx, params):
v = 3*sum(xx)
return v

G = monte.gsl_monte_function(g, None, 3)

xl = np.array([0,0,0])
xu = np.array([1,1,1],dtype=float)

grand = pygsl.rng.mt19937_1999()
calls = int(10**6)

var("x y z")
exact_int = integrate(integrate(integrate(3*(x+y+z), x),y),z)
exact = exact_int.subs(dict(zip([x,y,z], map(float,xu)))) - exact_int.subs(dict(zip([x,y,z], map(float, xl))))

def display_results (title, result, error):
print "%s ==================" %  title
print "result = % .6f" % result
print "sigma  = % .6f" % error
print "exact  = % .6f" % exact
t = (result - exact, np.abs(result - exact) / error)
print "error  = % .6f = %.1g sigma" % t

def run_vegas():
s = monte.vegas(int(3))
s.init()

res, err = s.integrate(G, xl, xu, int(10000), grand)
display_results ("vegas warm-up", res, err)

print "converging..."
while 1:
res, err = s.integrate(G, xl, xu, int(calls/1000), grand)
chisq = s.get_chisq()
print "result = % .6f sigma = % .6f chisq/dof = %.1f" % (res, err, chisq);
display_results("vegas:", res, err)
if (abs(chisq - 1.0) <= 0.5):
break

run_vegas()

--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-7-edca2285ce09> in <module>() 1 import numpy as np ----> 2 import pygsl.monte as monte 3 import pygsl.rng 4 5 def g(xx, params): ImportError: No module named pygsl.monte 
In [7]:
a=2
a

2
In [ ]: