Fourier decompositionΒΆ

This example uses the show(), morph(), translate() and hide() animations to animate plot plot objects to show how we can reconstruct a signal with a Fourier Transform.

import diplotocus as dpl
import numpy as np

#We create our timeline and define a global easing
tl = dpl.Timeline(xlim=(-5,5),ylim=(-0.25,1.5),easing=dpl.easeInCubic())

#We create the signal we want to Fourier decompose
x = np.linspace(-5,5,100)
y = np.exp(-x**2)

#Plot the real signal
tl.ax.plot(x, y, c='k', ls='--', alpha=0.5)

#Get its Fourier power spectrum
freq = np.fft.fftfreq(len(x),x[1]-x[0])
sp = np.fft.fft(y)

#Add a plot object for our reconstructed signal
p_total = dpl.plot(x,np.zeros_like(x),c='green',lw=3)
p_total.plot(duration=30)

#We create a list to store all the plotObjects we will animate
plot_objects = [p_total]

#Loop over the first 8 frequencies
for i in range(8):
    amp = np.abs(sp[i])/len(x)
    phase = np.angle(sp[i])
    if i > 0:
        amp *= 2#We need to double the amplitude of doubled modes

    x0 = np.linspace(-5,5,500,endpoint=False)
    y0 = 0.25*np.cos(x0*2*np.pi*freq[i]) + 1.25
    y1 = amp*np.cos((x0-x[0])*2*np.pi*freq[i] + phase) + 1.25

    #We first create a cosine wave of the current frequency
    p = dpl.plot(x0,y0)

    #We delay each mode so they appear sequentially
    base_delay = 50*i
    #We fade the plot in
    p.show(duration=10,delay=base_delay)
    #Morph it into the right cosine wave given the power spectrum
    p.morph(new_x=x0,new_y=y1,duration=20,delay=base_delay + 10)
    #Move it down
    p.translate(start_pos=(0,0),end_pos=(0,-1.25),duration=20,delay=base_delay + 30)
    #Hide it
    p.hide(duration=10,delay=base_delay + 40)
    plot_objects.append(p)

    #We compute the reconstructed signal from modes <= i
    sp_total = np.where(np.abs(freq) > freq[i],0,sp)
    y_total = np.fft.ifft(sp_total,n=len(x))
    #We update our reconstructed signal
    p_total.morph(new_x=x,new_y=y_total,duration=20,delay=base_delay + 30)

tl.animate(plot_objects)
tl.save_video('../../_static/examples/fourier.mp4')