Python numpy.blackman() Examples
The following are 30
code examples of numpy.blackman().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example #1
Source File: audio_tools.py From tools with BSD 3-Clause "New" or "Revised" License | 8 votes |
def run_mgc_example(): import matplotlib.pyplot as plt fs, x = wavfile.read("test16k.wav") pos = 3000 fftlen = 1024 win = np.blackman(fftlen) / np.sqrt(np.sum(np.blackman(fftlen) ** 2)) xw = x[pos:pos + fftlen] * win sp = 20 * np.log10(np.abs(np.fft.rfft(xw))) mgc_order = 20 mgc_alpha = 0.41 mgc_gamma = -0.35 mgc_arr = win2mgc(xw, order=mgc_order, alpha=mgc_alpha, gamma=mgc_gamma, verbose=True) xwsp = 20 * np.log10(np.abs(np.fft.rfft(xw))) sp = mgc2sp(mgc_arr, mgc_alpha, mgc_gamma, fftlen) plt.plot(xwsp) plt.plot(20. / np.log(10) * np.real(sp), "r") plt.xlim(1, len(xwsp)) plt.show()
Example #2
Source File: audio_tools.py From representation_mixing with BSD 3-Clause "New" or "Revised" License | 6 votes |
def run_mgc_example(): import matplotlib.pyplot as plt fs, x = wavfile.read("test16k.wav") pos = 3000 fftlen = 1024 win = np.blackman(fftlen) / np.sqrt(np.sum(np.blackman(fftlen) ** 2)) xw = x[pos:pos + fftlen] * win sp = 20 * np.log10(np.abs(np.fft.rfft(xw))) mgc_order = 20 mgc_alpha = 0.41 mgc_gamma = -0.35 mgc_arr = win2mgc(xw, order=mgc_order, alpha=mgc_alpha, gamma=mgc_gamma, verbose=True) xwsp = 20 * np.log10(np.abs(np.fft.rfft(xw))) sp = mgc2sp(mgc_arr, mgc_alpha, mgc_gamma, fftlen) plt.plot(xwsp) plt.plot(20. / np.log(10) * np.real(sp), "r") plt.xlim(1, len(xwsp)) plt.show()
Example #3
Source File: MorseDecoder.py From LSTM_morse with MIT License | 6 votes |
def find_peak(fname): """Find the signal frequency and maximum value""" #print("find_peak",fname) Fs, x = wavfile.read(fname) f,s = periodogram(x, Fs,'blackman',8192,'linear', False, scaling='spectrum') threshold = max(s)*0.8 # only 0.4 ... 1.0 of max value freq peaks included maxtab, mintab = peakdet(abs(s[0:int(len(s)/2-1)]), threshold,f[0:int(len(f)/2-1)] ) try: val = maxtab[0,0] except: print("Error: {}".format(maxtab)) val = 600. return val # Fs should be 8000 Hz # with decimation down to 125 Hz we get 8 msec / sample # with WPM equals to 20 => Tdit = 1200/WPM = 60 msec (time of 'dit') # 4 seconds equals 256 samples ~ 66.67 Tdits # word 'PARIS' is 50 Tdits
Example #4
Source File: display.py From OpenNFB with GNU General Public License v3.0 | 6 votes |
def init(self, lo=0, hi=125, bins=256, yrange=750, ratio=False): self.widget = pg.PlotWidget() self.widget.setLabel('bottom', 'Frequency', units='Hz') self.bars = pg.BarGraphItem() self.win = np.hanning(bins) self.win = np.blackman(bins) #self.win = np.ones(bins) self.lo, self.hi = lo, hi self.ratio = ratio FS = self.input.sample_rate self.gr_block.set_history(bins) #num_bars = int(round((self.bins - 1) * (self.hi - self.lo) / FS)) # This is total bullshit: num_bars = len(np.zeros(bins)[lo: hi]) x = np.linspace(self.lo, self.hi, num_bars) self.bars = pg.BarGraphItem(x=x, height=range(num_bars), width=1.0) self.bars.setOpts(brushes=[pg.hsvColor(float(x) / num_bars) for x in range(num_bars)]) self.widget.addItem(self.bars) # TODO: Better autoranging features #self.plot.enableAutoRange('xy', False) self.widget.setYRange(0, yrange) self.widget.enableAutoRange('y', 0.95) self.buffer = np.zeros(bins) self.timer = pg.QtCore.QTimer() self.timer.timeout.connect(self.updateGUI) self.timer.start(10)
Example #5
Source File: iqplot.py From iqtool with The Unlicense | 6 votes |
def plotSpectrogram(data, fftWindow, fftSize, Fs): if fftSize == None: N = len(data) else: N = fftSize if Fs == None: Fs = 2 if fftWindow == "rectangular": plt.specgram(data, NFFT=N, Fs=Fs, window=lambda data: data*np.ones(len(data)), noverlap=int(N/10)) elif fftWindow == "bartlett": plt.specgram(data, NFFT=N, Fs=Fs, window=lambda data: data*np.bartlett(len(data)), noverlap=int(N/10)) elif args.fftWindow == "blackman": plt.specgram(data, NFFT=N, Fs=Fs, window=lambda data: data*np.blackman(len(data)), noverlap=int(N/10)) elif fftWindow == "hamming": plt.specgram(data, NFFT=N, Fs=Fs, window=lambda data: data*np.hamming(len(data)), noverlap=int(N/10)) elif fftWindow == "hanning": plt.specgram(data, NFFT=N, Fs=Fs, window=lambda data: data*np.hanning(len(data)), noverlap=int(N/10)) plt.show()
Example #6
Source File: Filter.py From urh with GNU General Public License v3.0 | 6 votes |
def design_windowed_sinc_lpf(fc, bw): N = Filter.get_filter_length_from_bandwidth(bw) # Compute sinc filter impulse response h = np.sinc(2 * fc * (np.arange(N) - (N - 1) / 2.)) # We use blackman window function w = np.blackman(N) # Multiply sinc filter with window function h = h * w # Normalize to get unity gain h_unity = h / np.sum(h) return h_unity
Example #7
Source File: probe1d.py From us-rawdata-sda with MIT License | 6 votes |
def impulse_response(self, sampling_frequency): dt = 1 / sampling_frequency if self.impulse_window in ['hanning', 'blackman']: t_start = 0 t_stop = int(self.impulse_cycles / self.center_frequency * sampling_frequency) * dt # int() applies floor t_num = int(self.impulse_cycles / self.center_frequency * sampling_frequency) + 1 # int() applies floor t = np.linspace(t_start, t_stop, t_num) impulse = np.sin(2 * np.pi * self.center_frequency * t) if self.impulse_window == 'hanning': win = np.hanning(impulse.shape[0]) elif self.impulse_window == 'blackman': win = np.blackman(impulse.shape[0]) else: raise NotImplementedError('Window type {} not implemented'.format(self.impulse_window)) return impulse * win elif self.impulse_window == 'gauss': # Compute cutoff time for when the pulse amplitude falls below `tpr` (in dB) which is set at -100dB tpr = -60 t_cutoff = scipy.signal.gausspulse('cutoff', fc=int(self.center_frequency), bw=self.bandwidth, tpr=tpr) t = np.arange(-t_cutoff, t_cutoff, dt) return scipy.signal.gausspulse(t, fc=self.center_frequency, bw=self.bandwidth, tpr=tpr) else: raise NotImplementedError('Window type {} not implemented'.format(self.impulse_window))
Example #8
Source File: seismic.py From seisplot with Apache License 2.0 | 6 votes |
def spectrum(signal, fs, taper=True): if taper: windowed = signal * np.blackman(len(signal)) else: windowed = signal a = abs(np.fft.rfft(windowed)) f = np.fft.rfftfreq(len(signal), 1/fs) db = 20 * np.log10(a) sig = db - np.amax(db) + 20 indices = ((sig[1:] >= 0) & (sig[:-1] < 0)).nonzero() crossings = [z - sig[z] / (sig[z+1] - sig[z]) for z in indices] mi, ma = np.amin(crossings), np.amax(crossings) x = np.arange(0, len(f)) # for back-interpolation f_min = np.interp(mi, x, f) f_max = np.interp(ma, x, f) return f, a, f_min, f_max
Example #9
Source File: net34.py From kaggle_grasp_and_lift_eeg_detection with BSD 2-Clause "Simplified" License | 6 votes |
def transform(self, X_indices, y_indices): X_indices, y_indices = super(IndexBatchIterator, self).transform(X_indices, y_indices) [count] = X_indices.shape # Use preallocated space X = self.Xbuf[:count] Y = self.Ybuf[:count] window = np.blackman(SAMPLE_SIZE//DOWNSAMPLE)[None,:] for i, ndx in enumerate(X_indices): if ndx == -1: ndx = np.random.randint(len(self.source.events)) augmented = self.augmented[:,ndx:ndx+SAMPLE_SIZE] X[i] = augmented[:,::-1][:,::DOWNSAMPLE] if y_indices is not None: Y[i] = self.source.events[ndx] Y = None if (y_indices is None) else Y return X, Y
Example #10
Source File: audio.py From representation_mixing with BSD 3-Clause "New" or "Revised" License | 6 votes |
def run_mgc_example(): import matplotlib.pyplot as plt fs, x = wavfile.read("test16k.wav") pos = 3000 fftlen = 1024 win = np.blackman(fftlen) / np.sqrt(np.sum(np.blackman(fftlen) ** 2)) xw = x[pos:pos + fftlen] * win sp = 20 * np.log10(np.abs(np.fft.rfft(xw))) mgc_order = 20 mgc_alpha = 0.41 mgc_gamma = -0.35 mgc_arr = win2mgc(xw, order=mgc_order, alpha=mgc_alpha, gamma=mgc_gamma, verbose=True) xwsp = 20 * np.log10(np.abs(np.fft.rfft(xw))) sp = mgc2sp(mgc_arr, mgc_alpha, mgc_gamma, fftlen) plt.plot(xwsp) plt.plot(20. / np.log(10) * np.real(sp), "r") plt.xlim(1, len(xwsp)) plt.show()
Example #11
Source File: preprocess.py From pactools with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _plot_multiple_spectrum(signals, fs, labels, colors): """ plot the signals spectrum """ s = Spectrum(block_length=min(2048, signals[0].size), fs=fs, wfunc=np.blackman) for sig in signals: s.periodogram(sig, hold=True) s.plot(labels=labels, colors=colors, fscale='lin')
Example #12
Source File: fir.py From pactools with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _design(self): """Designs the FIR filter""" # the length of the filter order = self._get_order() half_order = (order - 1) // 2 w = np.blackman(order) t = np.linspace(-half_order, half_order, order) phase = (2.0 * np.pi * self.fc / self.fs) * t car = np.cos(phase) fir = w * car # the filter must be symmetric, in order to be zero-phase assert np.all(np.abs(fir - fir[::-1]) < 1e-15) # remove the constant component by forcing fir.sum() = 0 if self.zero_mean: fir -= fir.sum() / order gain = np.sum(fir * car) self.fir = fir * (1.0 / gain) # add the imaginary part to have a complex wavelet if self.extract_complex: car_imag = np.sin(phase) fir_imag = w * car_imag self.fir_imag = fir_imag * (1.0 / gain) return self
Example #13
Source File: test_simplification.py From coffeegrindsize with MIT License | 5 votes |
def test_fft_peaks(): fig, ax = plt.subplots() t = np.arange(65536) p1 = ax.plot(abs(np.fft.fft(np.sin(2*np.pi*.01*t)*np.blackman(len(t))))) path = p1[0].get_path() transform = p1[0].get_transform() path = transform.transform_path(path) simplified = path.cleaned(simplify=True) assert simplified.vertices.size == 36
Example #14
Source File: test_simplification.py From twitter-stock-recommendation with MIT License | 5 votes |
def test_fft_peaks(): fig, ax = plt.subplots() t = np.arange(65536) p1 = ax.plot(abs(np.fft.fft(np.sin(2*np.pi*.01*t)*np.blackman(len(t))))) path = p1[0].get_path() transform = p1[0].get_transform() path = transform.transform_path(path) simplified = path.cleaned(simplify=True) assert simplified.vertices.size == 36
Example #15
Source File: MorseDecoder.py From LSTM_morse with MIT License | 5 votes |
def get_specgram(signal, rate): arr2D, freqs, bins = specgram( signal, window=np.blackman(nfft), Fs=rate, NFFT=nfft, noverlap=overlap, pad_to=32 * nfft, ) return arr2D, freqs, bins
Example #16
Source File: process.py From sound_field_analysis-py with MIT License | 5 votes |
def iFFT(Y, output_length=None, window=False): """ Inverse real-valued Fourier Transform Parameters ---------- Y : array_like Frequency domain data [Nsignals x Nbins] output_length : int, optional Length of returned time-domain signal (Default: 2 x len(Y) + 1) window : boolean, optional Window applied to the resulting time-domain signal Returns ------- y : array_like Reconstructed time-domain signal """ Y = _np.atleast_2d(Y) y = _np.fft.irfft(Y, n=output_length) if window: no_of_samples = y.shape[-1] if window == 'hann': window_array = _np.hanning(no_of_samples) elif window == 'hamming': window_array = _np.hamming(no_of_samples) elif window == 'blackman': window_array = _np.blackman(no_of_samples) elif window == 'kaiser': window_array = _np.kaiser(no_of_samples, 3) else: raise ValueError('Selected window must be one of hann, hamming, blackman or kaiser') y *= window_array return y # noinspection PyUnusedLocal
Example #17
Source File: speechprocessing.py From TSNetVocoder with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self, sf=16000, fl=400, fs=80, fftl=512, mfbsize=80): self.sf = sf self.fl = fl self.fs = fs self.fftl = fftl self.mfbsize = mfbsize winpower = numpy.sqrt(numpy.sum(numpy.square(numpy.blackman(self.fl).astype(numpy.float32)))) self.window = numpy.blackman(self.fl).astype(numpy.float32) / winpower self.melfb = self._melfbank()
Example #18
Source File: synth_data.py From ConvNetQuake with MIT License | 5 votes |
def get_normalized_templates(template_streams): templates = [] for ts in template_streams: t = data_conversion.stream2array(ts) t = t.astype(np.float32) t -= np.mean(t, axis=1, keepdims=True) template_max = np.amax(np.abs(t)) t /= template_max t *= np.blackman(ts[0].stats.npts) templates.append(t) return templates
Example #19
Source File: callback.py From alphacsc with BSD 3-Clause "New" or "Revised" License | 5 votes |
def kde_sklearn(x, x_grid, bandwidth): """Kernel Density Estimation with Scikit-learn""" n_samples, = x.shape if n_samples == 0: return np.zeros_like(x_grid) window = np.blackman(bandwidth) * bandwidth return np.convolve(x, window, 'same')
Example #20
Source File: plot_output.py From alphacsc with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _plot_activation(z_k, info, ax, color, n_times_atom, t_min=0, plot="density"): sfreq = int(info.get('sfreq', 1)) z_k = z_k.mean(axis=0) # Average over the epochs t = np.arange(len(z_k)) / sfreq + t_min if plot == "density": blob = np.blackman(n_times_atom) # bandwidth of n_times_atom z_k_smooth = np.convolve(z_k, blob, mode='same') ax.fill_between(t, z_k_smooth, color=color, alpha=.5) elif plot == "logratio": eps = 1e-4 baseline = z_k[:sfreq] # Take the first second a a baseline mean_baseline = max(baseline.mean(), eps) patch = np.ones(sfreq) energy = np.maximum(np.convolve(z_k, patch, mode='same'), eps) logratio = np.log10(energy / mean_baseline) # logratio /= np.std(logratio[:sfreq]) ax.plot(t[sfreq // 2:-sfreq // 2], logratio[sfreq // 2:-sfreq // 2]) elif plot == "whiskers": # Take 1s at the beginning of the epochs as a baseline # Take 1s starting from stim as evoked # Take 1s starting 1s after the stim as induced baseline = z_k[:sfreq] evoked = z_k[(0 < t) * (t < 1)] induced = z_k[(1 < t) * (t < 2)] ax.boxplot([baseline, evoked, induced], sym='', labels=["baseline", "evoked", "induced"]) # raise NotImplementedError("Not yet!") else: raise NotImplementedError("No plot '{}' for activations".format(plot))
Example #21
Source File: waterfall.py From OpenNFB with GNU General Public License v3.0 | 5 votes |
def init(self): self.canvas = Canvas() self.widget = self.canvas.native self.gr_block.set_history(bins) self.win = np.blackman(bins)
Example #22
Source File: gnuradio_protocol.py From OpenNFB with GNU General Public License v3.0 | 5 votes |
def init(self, lo=0, hi=125, bins=256, yrange=750, ratio=False): self.widget = pg.PlotWidget() self.widget.setLabel('bottom', 'Frequency', units='Hz') self.bars = pg.BarGraphItem() self.win = np.hanning(bins) self.win = np.blackman(bins) #self.win = np.ones(bins) self.lo, self.hi = lo, hi self.ratio = ratio FS = self.input.sample_rate self.gr_block.set_history(bins) #num_bars = int(round((self.bins - 1) * (self.hi - self.lo) / FS)) # This is total bullshit: num_bars = len(np.zeros(bins)[lo: hi]) x = np.linspace(self.lo, self.hi, num_bars) self.bars = pg.BarGraphItem(x=x, height=range(num_bars), width=1.0) self.bars.setOpts(brushes=[pg.hsvColor(float(x) / num_bars) for x in range(num_bars)]) self.widget.addItem(self.bars) # TODO: Better autoranging features #self.plot.enableAutoRange('xy', False) self.widget.setYRange(0, yrange) self.widget.enableAutoRange('y', 0.95) self.buffer = np.zeros(bins) self.timer = QtCore.QTimer() self.timer.timeout.connect(self.updateGUI) self.timer.start(10)
Example #23
Source File: iqplot.py From iqtool with The Unlicense | 5 votes |
def plotPSD(data,fftWindow, Fs): assert fftWindow in ['rectangular', 'bartlett', 'blackman', 'hamming', 'hanning'] N = len(data) #Generate the selected window if fftWindow == "rectangular": window = np.ones(N) elif fftWindow == "bartlett": window = np.bartlett(N) elif args.fftWindow == "blackman": window = np.blackman(N) elif fftWindow == "hamming": window = np.hamming(N) elif fftWindow == "hanning": window = np.hanning(N) dft = np.fft.fft(data*window) if Fs == None: #If the sample rate is known then plot PSD as #Power/Freq in (dB/Hz) plt.psd(data*window, NFFT=N) else: #If sample rate is not known then plot PSD as #Power/Freq as (dB/rad/sample) plt.psd(data*window, NFFT=N, Fs=Fs) plt.show()
Example #24
Source File: window.py From cupy with MIT License | 5 votes |
def blackman(M): """Returns the Blackman window. The Blackman window is defined as .. math:: w(n) = 0.42 - 0.5 \\cos\\left(\\frac{2\\pi{n}}{M-1}\\right) + 0.08 \\cos\\left(\\frac{4\\pi{n}}{M-1}\\right) \\qquad 0 \\leq n \\leq M-1 Args: M (:class:`~int`): Number of points in the output window. If zero or less, an empty array is returned. Returns: ~cupy.ndarray: Output ndarray. .. seealso:: :func:`numpy.blackman` """ if M == 1: return cupy.ones(1, dtype=cupy.float64) if M <= 0: return cupy.array([]) alpha = numpy.pi * 2 / (M - 1) out = cupy.empty(M, dtype=cupy.float64) return _blackman_kernel(alpha, out)
Example #25
Source File: test_simplification.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_fft_peaks(): fig, ax = plt.subplots() t = np.arange(65536) p1 = ax.plot(abs(np.fft.fft(np.sin(2*np.pi*.01*t)*np.blackman(len(t))))) path = p1[0].get_path() transform = p1[0].get_transform() path = transform.transform_path(path) simplified = path.cleaned(simplify=True) assert simplified.vertices.size == 36
Example #26
Source File: speechprocessing.py From project-CURRENNT-scripts with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self, sf=16000, fl=400, fs=80, fftl=1024, mfbsize=80): self.sf = sf self.fl = fl self.fs = fs self.fftl = fftl self.mfbsize = mfbsize winpower = np.sqrt(np.sum(np.square(np.blackman(self.fl).astype(np.float32)))) self.window = np.blackman(self.fl).astype(np.float32) / winpower self.melfb = self._melfbank()
Example #27
Source File: basenji_data_hic_read.py From basenji with Apache License 2.0 | 5 votes |
def smooth(y, box_pts, window='flat'): # https://scipy-cookbook.readthedocs.io/items/SignalSmooth.html if window is 'flat': box = np.ones(box_pts) elif window is 'blackman': box = np.blackman(box_pts) else: raise ValueError('unknown window') box /= np.sum(box) y_smooth = astroconv.convolve(y, box, boundary='extend') # also: None, fill, wrap, extend return y_smooth
Example #28
Source File: texttiling.py From razzy-spinner with GNU General Public License v3.0 | 4 votes |
def smooth(x,window_len=11,window='flat'): """smooth the data using a window with requested size. This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the beginning and end part of the output signal. :param x: the input signal :param window_len: the dimension of the smoothing window; should be an odd integer :param window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman' flat window will produce a moving average smoothing. :return: the smoothed signal example:: t=linspace(-2,2,0.1) x=sin(t)+randn(len(t))*0.1 y=smooth(x) :see also: numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve, scipy.signal.lfilter TODO: the window parameter could be the window itself if an array instead of a string """ if x.ndim != 1: raise ValueError("smooth only accepts 1 dimension arrays.") if x.size < window_len: raise ValueError("Input vector needs to be bigger than window size.") if window_len < 3: return x if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']: raise ValueError("Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'") s=numpy.r_[2*x[0]-x[window_len:1:-1],x,2*x[-1]-x[-1:-window_len:-1]] #print(len(s)) if window == 'flat': #moving average w = numpy.ones(window_len,'d') else: w = eval('numpy.' + window + '(window_len)') y = numpy.convolve(w/w.sum(), s, mode='same') return y[window_len-1:-window_len+1]
Example #29
Source File: texttiling.py From luscan-devel with GNU General Public License v2.0 | 4 votes |
def smooth(x,window_len=11,window='flat'): """smooth the data using a window with requested size. This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the beginning and end part of the output signal. :param x: the input signal :param window_len: the dimension of the smoothing window; should be an odd integer :param window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman' flat window will produce a moving average smoothing. :return: the smoothed signal example:: t=linspace(-2,2,0.1) x=sin(t)+randn(len(t))*0.1 y=smooth(x) :see also: numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve, scipy.signal.lfilter TODO: the window parameter could be the window itself if an array instead of a string """ if x.ndim != 1: raise ValueError, "smooth only accepts 1 dimension arrays." if x.size < window_len: raise ValueError, "Input vector needs to be bigger than window size." if window_len<3: return x if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']: raise ValueError, "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'" s=numpy.r_[2*x[0]-x[window_len:1:-1],x,2*x[-1]-x[-1:-window_len:-1]] #print(len(s)) if window == 'flat': #moving average w=numpy.ones(window_len,'d') else: w=eval('numpy.'+window+'(window_len)') y=numpy.convolve(w/w.sum(),s,mode='same') return y[window_len-1:-window_len+1]
Example #30
Source File: texttiling.py From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International | 4 votes |
def smooth(x, window_len=11, window='flat'): """smooth the data using a window with requested size. This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the beginning and end part of the output signal. :param x: the input signal :param window_len: the dimension of the smoothing window; should be an odd integer :param window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman' flat window will produce a moving average smoothing. :return: the smoothed signal example:: t=linspace(-2,2,0.1) x=sin(t)+randn(len(t))*0.1 y=smooth(x) :see also: numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve, scipy.signal.lfilter TODO: the window parameter could be the window itself if an array instead of a string """ if x.ndim != 1: raise ValueError("smooth only accepts 1 dimension arrays.") if x.size < window_len: raise ValueError("Input vector needs to be bigger than window size.") if window_len < 3: return x if window not in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']: raise ValueError( "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'" ) s = numpy.r_[2 * x[0] - x[window_len:1:-1], x, 2 * x[-1] - x[-1:-window_len:-1]] # print(len(s)) if window == 'flat': # moving average w = numpy.ones(window_len, 'd') else: w = eval('numpy.' + window + '(window_len)') y = numpy.convolve(w / w.sum(), s, mode='same') return y[window_len - 1 : -window_len + 1]