Python numpy.blackman() Examples

The following are 30 code examples for showing how to use numpy.blackman(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: tools   Author: kastnerkyle   File: audio_tools.py    License: BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
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
Project: kaggle_grasp_and_lift_eeg_detection   Author: bitsofbits   File: net34.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 3
Project: seisplot   Author: agile-geoscience   File: seismic.py    License: Apache License 2.0 6 votes vote down vote up
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 4
Project: us-rawdata-sda   Author: dperdios   File: probe1d.py    License: MIT License 6 votes vote down vote up
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 5
Project: iqtool   Author: jgibbard   File: iqplot.py    License: The Unlicense 6 votes vote down vote up
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
Project: LSTM_morse   Author: ag1le   File: MorseDecoder.py    License: MIT License 6 votes vote down vote up
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 7
Project: urh   Author: jopohl   File: Filter.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 8
Project: representation_mixing   Author: kastnerkyle   File: audio.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 9
Project: representation_mixing   Author: kastnerkyle   File: audio_tools.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 10
Project: basenji   Author: calico   File: basenji_data_hic_read.py    License: Apache License 2.0 5 votes vote down vote up
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 11
Project: project-CURRENNT-scripts   Author: nii-yamagishilab   File: speechprocessing.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 12
Project: python3_ios   Author: holzschu   File: test_simplification.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 13
Project: cupy   Author: cupy   File: window.py    License: MIT License 5 votes vote down vote up
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 14
Project: iqtool   Author: jgibbard   File: iqplot.py    License: The Unlicense 5 votes vote down vote up
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 15
Project: OpenNFB   Author: strfry   File: gnuradio_protocol.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 16
Project: OpenNFB   Author: strfry   File: display.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 17
Project: OpenNFB   Author: strfry   File: waterfall.py    License: GNU General Public License v3.0 5 votes vote down vote up
def init(self):
        self.canvas = Canvas()
        self.widget = self.canvas.native

        self.gr_block.set_history(bins)
        self.win = np.blackman(bins) 
Example 18
Project: sound_field_analysis-py   Author: AppliedAcousticsChalmers   File: process.py    License: MIT License 5 votes vote down vote up
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 19
Project: alphacsc   Author: alphacsc   File: plot_output.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 20
Project: alphacsc   Author: alphacsc   File: callback.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 21
Project: ConvNetQuake   Author: tperol   File: synth_data.py    License: MIT License 5 votes vote down vote up
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 22
Project: TSNetVocoder   Author: nii-yamagishilab   File: speechprocessing.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 23
Project: LSTM_morse   Author: ag1le   File: MorseDecoder.py    License: MIT License 5 votes vote down vote up
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 24
Project: coffeegrindsize   Author: jgagneastro   File: test_simplification.py    License: MIT License 5 votes vote down vote up
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 25
Project: pactools   Author: pactools   File: preprocess.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 26
Project: pactools   Author: pactools   File: fir.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 27
Project: twitter-stock-recommendation   Author: alvarobartt   File: test_simplification.py    License: MIT License 5 votes vote down vote up
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 28
Project: razzy-spinner   Author: rafasashi   File: texttiling.py    License: GNU General Public License v3.0 4 votes vote down vote up
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
Project: nanovna-saver   Author: NanoVNA-Saver   File: TDR.py    License: GNU General Public License v3.0 4 votes vote down vote up
def updateTDR(self):
        c = 299792458
        # TODO: Let the user select whether to use high or low resolution TDR?
        FFT_POINTS = 2**14

        if len(self.app.data) < 2:
            return

        if self.tdr_velocity_dropdown.currentData() == -1:
            self.tdr_velocity_input.setDisabled(False)
        else:
            self.tdr_velocity_input.setDisabled(True)
            self.tdr_velocity_input.setText(str(self.tdr_velocity_dropdown.currentData()))

        try:
            v = float(self.tdr_velocity_input.text())
        except ValueError:
            return

        step_size = self.app.data[1].freq - self.app.data[0].freq
        if step_size == 0:
            self.tdr_result_label.setText("")
            logger.info("Cannot compute cable length at 0 span")
            return

        s11 = []
        for d in self.app.data:
            s11.append(np.complex(d.re, d.im))

        window = np.blackman(len(self.app.data))

        windowed_s11 = window * s11
        self.td = np.abs(np.fft.ifft(windowed_s11, FFT_POINTS))
        step = np.ones(FFT_POINTS)
        self.step_response = signal.convolve(self.td, step)

        self.step_response_Z = 50 * (1 + self.step_response) / (1 - self.step_response)

        time_axis = np.linspace(0, 1/step_size, FFT_POINTS)
        self.distance_axis = time_axis * v * c
        # peak = np.max(td)
        #  We should check that this is an actual *peak*, and not just a vague maximum
        index_peak = np.argmax(self.td)

        cable_len = round(self.distance_axis[index_peak]/2, 3)
        feet = math.floor(cable_len / 0.3048)
        inches = round(((cable_len / 0.3048) - feet)*12, 1)

        self.tdr_result_label.setText(f"{cable_len}m ({feet}ft {inches}in)")
        self.app.tdr_result_label.setText(str(cable_len) + " m")
        self.updated.emit() 
Example 30
Project: luscan-devel   Author: blackye   File: texttiling.py    License: GNU General Public License v2.0 4 votes vote down vote up
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]