barakuda_filters.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # A collection of filters for low-pass filtering ans spectral-analysis stuff...
  2. # Laurent Brodeau, Jan. 2015
  3. import numpy as nmp
  4. from scipy.interpolate import UnivariateSpline
  5. from scipy.signal import wiener, filtfilt, butter, gaussian, freqz
  6. from scipy.ndimage import filters
  7. #import scipy.optimize as op
  8. # For spectral analysis:
  9. #from scipy.fftpack import fft
  10. def ssqe(sm, s, npts):
  11. return nmp.sqrt(nmp.sum(nmp.power(s-sm,2)))/npts
  12. def testGauss(x, y):
  13. b = gaussian(39, 10)
  14. #ga = filtfilt(b/b.sum(), [1.0], y)
  15. ga = filters.convolve1d(y, b/b.sum())
  16. return ga
  17. def testButterworth(nyf, x, y):
  18. b, a = butter(4, 1.5/nyf)
  19. fl = filtfilt(b, a, y)
  20. return fl
  21. def testWiener(x, y):
  22. #wi = wiener(y, mysize=29, noise=0.5)
  23. wi = wiener(y, mysize=29)
  24. return wi
  25. def testSpline(x, y, rS):
  26. sp = UnivariateSpline(x, y, k=4, s=rS)
  27. return sp(x)
  28. #def plotPowerSpectrum(y, w):
  29. # ft = nmp.fft.rfft(y)
  30. # ps = nmp.real(ft*nmp.conj(ft))*nmp.square(dt)
  31. def Amp_Spctrm(vy, rdt=1., lwin=False):
  32. # L. Brodeau, 2015
  33. # Computes a Single-Sided Amplitude Spectrum of vy(t)
  34. #
  35. # In general, you should apply a window function to your time domain data
  36. # before calculating the FFT, to reduce spectral leakage. The Hann window is
  37. # almost never a bad choice. You can also use the rfft function to skip the
  38. # -FSample/2, 0 part of the output.
  39. # Depending on the implementation, your FFT routine might output yout =
  40. # yin/N, or yout = yin/sqrt(N), or if you applied a window, you have to
  41. # replace N with a coefficient that depends on the chosen window.
  42. N = len(vy) # length of the signal
  43. if lwin:
  44. sY = 2.*nmp.fft.rfft(vy*nmp.hanning(N))/(float(N)/2.) # fft computing and normalization (Fast Fourier Transform)
  45. else:
  46. sY = nmp.fft.rfft(vy)/(float(N)/2.) # fft computing and normalization (Fast Fourier Transform)
  47. sY = nmp.abs(sY[:N/2]) # Taking real part, and symetric around 0, only keep half!
  48. vfreq = nmp.fft.fftfreq(N, d=rdt) # in hours, or d=1.0/24 in days
  49. vfreq = vfreq[:N/2]
  50. # The inverse Fourier Transform would be: numpy.fft.ifft
  51. return vfreq, sY
  52. def Pow_Spctrm(vy, rdt=1., lwin=False):
  53. [ vfreq, spY ] = Amp_Spctrm(vy, lwin=lwin, rdt=rdt)
  54. spY = spY*spY
  55. return vfreq, spY