Skip to content

Instantly share code, notes, and snippets.

@amarvutha
Created April 3, 2014 18:51
Show Gist options
  • Save amarvutha/9960514 to your computer and use it in GitHub Desktop.
Save amarvutha/9960514 to your computer and use it in GitHub Desktop.
Animated reconstruction of a random ellipse from fourier coefficients
# Fourier reconstruction of random ellipse
# Amar Vutha
# 2014-04-03
import pylab as plt
import numpy as np
from numpy import pi
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Generate random ellipse
t = np.arange(0,2*pi,1e-4)
r = np.zeros(len(t))
a,b = np.random.random(), np.random.random()
theta = t.copy()
r = a*b/np.sqrt( ( a*np.sin(theta) )**2 + ( b*np.cos(theta) )**2 )
fig = plt.figure()
ax = plt.subplot(111,polar=True)
ax.set_rlim(0,1)
ax.plot(theta,r,'r--',lw=3,alpha=0.5)
line, = ax.plot(theta,r,lw=2)
linebg, = ax.plot(theta,np.ones(len(theta)),'g--',lw=3,alpha=0.2)
### Fourier transform #####
phi = t.copy()
Nmax = 20
A,B = [],[]
dp = phi[1] - phi[0]
A_DC = np.sum(r) * dp/(2*pi)
A,B = np.zeros( (Nmax) ), np.zeros( (Nmax) )
for n in range(1,Nmax):
A[n] = np.sum(r*np.cos(n*phi)) * dp/pi
B[n] = np.sum(r*np.sin(n*phi)) * dp/pi
### Reconstruction ######
def reconstruct(M):
R = A_DC
for m in range(1,M):
R += A[m]* np.cos(m*phi) + B[m]* np.sin(m*phi)
return R
def animate(i):
line.set_ydata(reconstruct(i)) # update the data
linebg.set_ydata(np.cos(i*theta)) # shows the shape corresponding to the fourier coefficient
return (line,) + (linebg,)
#Init only required for blitting to give a clean slate.
def init():
line.set_ydata(np.ma.array(phi, mask=True))
linebg.set_ydata(np.ma.array(phi, mask=True))
return (line,) + (linebg,)
ani = animation.FuncAnimation(fig, animate, np.arange(1, Nmax), init_func=init,
interval=500, blit=True)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment