Surface NMR processing and inversion GUI
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

smooth.py 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import numpy
  2. def smooth(x,window_len=11,window='hanning'):
  3. """smooth the data using a window with requested size.
  4. This method is based on the convolution of a scaled window with the signal.
  5. The signal is prepared by introducing reflected copies of the signal
  6. (with the window size) in both ends so that transient parts are minimized
  7. in the begining and end part of the output signal.
  8. input:
  9. x: the input signal
  10. window_len: the dimension of the smoothing window; should be an odd integer
  11. window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
  12. flat window will produce a moving average smoothing.
  13. output:
  14. the smoothed signal
  15. example:
  16. t=linspace(-2,2,0.1)
  17. x=sin(t)+randn(len(t))*0.1
  18. y=smooth(x)
  19. see also:
  20. numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve
  21. scipy.signal.lfilter
  22. TODO: the window parameter could be the window itself if an array instead of a string
  23. """
  24. if x.ndim != 1:
  25. raise ValueError("smooth only accepts 1 dimension arrays.")
  26. if x.size < window_len:
  27. raise ValueError("Input vector needs to be bigger than window size.")
  28. if window_len<3:
  29. return x
  30. if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
  31. raise ValueError("Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'")
  32. s=numpy.r_[2*x[0]-x[window_len:1:-1],x,2*x[-1]-x[-1:-window_len:-1]]
  33. #print(len(s))
  34. if window == 'flat': #moving average
  35. w=ones(window_len,'d')
  36. else:
  37. w=eval('numpy.'+window+'(window_len)')
  38. y=numpy.convolve(w/w.sum(),s,mode='same')
  39. return y[window_len-1:-window_len+1]
  40. from numpy import *
  41. from pylab import *
  42. def smooth_demo():
  43. t=linspace(-4,4,100)
  44. x=sin(t)
  45. xn=x+randn(len(t))*0.1
  46. y=smooth(x)
  47. ws=31
  48. subplot(211)
  49. plot(ones(ws))
  50. windows=['flat', 'hanning', 'hamming', 'bartlett', 'blackman']
  51. hold(True)
  52. for w in windows[1:]:
  53. eval('plot('+w+'(ws) )')
  54. axis([0,30,0,1.1])
  55. legend(windows)
  56. title("The smoothing windows")
  57. subplot(212)
  58. plot(x)
  59. plot(xn)
  60. for w in windows:
  61. plot(smooth(xn,10,w))
  62. l=['original signal', 'signal with noise']
  63. l.extend(windows)
  64. legend(l)
  65. title("Smoothing a noisy signal")
  66. show()
  67. if __name__=='__main__':
  68. smooth_demo()