# zoom in to the waveform
samples=range(len(signal))t=librosa.samples_to_time(samples,sr=sr)plt.figure(figsize=(10,5))plt.plot(t[10000:10400],signal[10000:10400])plt.xlabel("Time (s)")plt.ylabel("Amplitude")plt.show()
# compare signal and sinusoids
f=523phase=0phase2=0.55sin=0.1*np.sin(2*np.pi*(f*t-phase))sin2=0.1*np.sin(2*np.pi*(f*t-phase2))plt.figure(figsize=(10,5))plt.plot(t[10000:10400],signal[10000:10400])plt.plot(t[10000:10400],sin[10000:10400],color="r")plt.plot(t[10000:10400],sin2[10000:10400],color="y")plt.fill_between(t[10000:10400],sin2[10000:10400]*signal[10000:10400])plt.xlabel("Time (s)")plt.ylabel("Amplitude")plt.show()
Fourier transform: Step by step
Choose a frequency -> Optimise phase -> Calculate magnitude
defcreate_signal(freq,time):sin=np.sin(2*np.pi*(freq*time))sin2=np.sin(2*np.pi*(2*freq*time))sin3=np.sin(2*np.pi*(3*freq*time))returnsin+sin2+sin3defcalculate_centre_of_gravity(mult_signal):x_centre=np.mean([x.realforxinmult_signal])y_centre=np.mean([x.imagforxinmult_signal])returnx_centre,y_centredefcalculate_sum(mult_signal):x_sum=np.sum([x.realforxinmult_signal])y_sum=np.sum([x.imagforxinmult_signal])returnx_sum,y_sumdefcreate_pure_tone(freq,time):angle=-2*np.pi*freq*timereturnnp.cos(angle)+1j*np.sin(angle)defplot_fourier_transform(pure_tone_freq,signal_freq,time,plot_centre_of_gravity=False,plot_sum=False):# create sinusoid and signal
pure_tone=create_pure_tone(pure_tone_freq,time)signal=create_signal(signal_freq,time)# multiply pure tone and signal
mult_signal=pure_tone*signalX=[x.realforxinmult_signal]Y=[x.imagforxinmult_signal]plt.figure(figsize=(8,5))plt.plot(X,Y,'o')# calculate and plot centre of gravity
ifplot_centre_of_gravity:centre_of_gravity=calculate_centre_of_gravity(mult_signal)plt.plot([centre_of_gravity[0]],[centre_of_gravity[1]],marker='o',markersize=10,color="red")# calculate and plot sum
ifplot_sum:integral=calculate_sum(mult_signal)plt.plot([integral[0]],[integral[1]],marker='o',markersize=10,color="green")# set origin axes
ax=plt.gca()ax.grid(True)ax.spines['left'].set_position('zero')ax.spines['right'].set_color('none')ax.spines['bottom'].set_position('zero')ax.spines['top'].set_color('none')ifnotplot_sum:plt.xlim(-3,3)plt.ylim(-3,3)plt.show()defplot_signal(signal,time):plt.figure(figsize=(8,5))plt.plot(signal,time)plt.xlabel("Time")plt.ylabel("Intensity")plt.show()
Comments powered by Disqus.