Ejemplo n.º 1
0
    def test_compare(self):
        # compare to OCTAVE output
        taps = firls(9, [0, 0.5, 0.55, 1], [1, 1, 0, 0], [1, 2])
        # >> taps = firls(8, [0 0.5 0.55 1], [1 1 0 0], [1, 2]);
        known_taps = [-6.26930101730182e-04, -1.03354450635036e-01,
                      -9.81576747564301e-03, 3.17271686090449e-01,
                      5.11409425599933e-01, 3.17271686090449e-01,
                      -9.81576747564301e-03, -1.03354450635036e-01,
                      -6.26930101730182e-04]
        assert_allclose(taps, known_taps)

        # compare to MATLAB output
        taps = firls(11, [0, 0.5, 0.5, 1], [1, 1, 0, 0], [1, 2])
        # >> taps = firls(10, [0 0.5 0.5 1], [1 1 0 0], [1, 2]);
        known_taps = [
            0.058545300496815, -0.014233383714318, -0.104688258464392,
            0.012403323025279, 0.317930861136062, 0.488047220029700,
            0.317930861136062, 0.012403323025279, -0.104688258464392,
            -0.014233383714318, 0.058545300496815]
        assert_allclose(taps, known_taps)

        # With linear changes:
        taps = firls(7, (0, 1, 2, 3, 4, 5), [1, 0, 0, 1, 1, 0], fs=20)
        # >> taps = firls(6, [0, 0.1, 0.2, 0.3, 0.4, 0.5], [1, 0, 0, 1, 1, 0])
        known_taps = [
            1.156090832768218, -4.1385894727395849, 7.5288619164321826,
            -8.5530572592947856, 7.5288619164321826, -4.1385894727395849,
            1.156090832768218]
        assert_allclose(taps, known_taps)

        taps = firls(7, (0, 1, 2, 3, 4, 5), [1, 0, 0, 1, 1, 0], nyq=10)
        assert_allclose(taps, known_taps)
Ejemplo n.º 2
0
    def test_compare(self):
        # compare to OCTAVE output
        taps = firls(9, [0, 0.5, 0.55, 1], [1, 1, 0, 0], [1, 2])
        # >> taps = firls(8, [0 0.5 0.55 1], [1 1 0 0], [1, 2]);
        known_taps = [-6.26930101730182e-04, -1.03354450635036e-01,
                      -9.81576747564301e-03, 3.17271686090449e-01,
                      5.11409425599933e-01, 3.17271686090449e-01,
                      -9.81576747564301e-03, -1.03354450635036e-01,
                      -6.26930101730182e-04]
        assert_allclose(taps, known_taps)

        # compare to MATLAB output
        taps = firls(11, [0, 0.5, 0.5, 1], [1, 1, 0, 0], [1, 2])
        # >> taps = firls(10, [0 0.5 0.5 1], [1 1 0 0], [1, 2]);
        known_taps = [
            0.058545300496815, -0.014233383714318, -0.104688258464392,
            0.012403323025279, 0.317930861136062, 0.488047220029700,
            0.317930861136062, 0.012403323025279, -0.104688258464392,
            -0.014233383714318, 0.058545300496815]
        assert_allclose(taps, known_taps)

        # With linear changes:
        taps = firls(7, (0, 1, 2, 3, 4, 5), [1, 0, 0, 1, 1, 0], nyq=10)
        # >> taps = firls(6, [0, 0.1, 0.2, 0.3, 0.4, 0.5], [1, 0, 0, 1, 1, 0])
        known_taps = [
            1.156090832768218, -4.1385894727395849, 7.5288619164321826,
            -8.5530572592947856, 7.5288619164321826, -4.1385894727395849,
            1.156090832768218]
        assert_allclose(taps, known_taps)
Ejemplo n.º 3
0
def preProcessing(X0, Fs, fil_type):
    X1 = signal.detrend(X0, axis=0, type='constant')
    if fil_type in ['ppg']:
        b = signal.firls(
            65, [0, 0.3 * 2 / Fs, 0.4 * 2 / Fs, 5 * 2 / Fs, 5.5 * 2 / Fs, 1],
            [0, 0, 1, 1, 0, 0], [100 * 0.02, 0.02, 0.02])
    else:
        b = signal.firls(129, [0, 0.3 * 2 / Fs, 0.4 * 2 / Fs, 1], [0, 0, 1, 1],
                         [100 * 0.02, 0.02])
    X2 = np.zeros((np.shape(X1)[0] - len(b) + 1, np.shape(X1)[1]))
    for i in range(np.shape(X1)[1]):
        X2[:, i] = signal.convolve(X1[:, i], b, mode='valid')
    return X2
Ejemplo n.º 4
0
def return_bandPassedSignal(sample: object,
                            f1L: object,
                            f1H: object,
                            f2L: object,
                            f2H: object,
                            Fs: object = 25) -> object:
    """
    Return bandpass filtered signal with two set of cutoffs

    :rtype: object
    :param sample:
    :param f1L:
    :param f1H:
    :param f2L:
    :param f2H:
    :param Fs:
    :return:
    """
    f = 2 / Fs
    delp = 0.02
    dels1 = 0.02
    dels2 = 0.02
    F = [0, f1L * f, f1H * f, f2L * f, f2H * f, 1]
    A = [0, 0, 1, 1, 0, 0]
    w = [500 / dels1, 1 / delp, 500 / dels2]
    fl = 257
    b = signal.firls(fl, F, A, w)
    sample = np.convolve(sample, b, 'same')
    return sample
Ejemplo n.º 5
0
    def FilterAllHighPass(self,
                          filter_stop_freq=0.1,
                          filter_pass_freq=0.2,
                          filter_order=1001,
                          ArchiveOld=False):
        """Replace Pixels with Pixels spectrally filtered with a scipy.signal high pass filter of order filter_order.
        The transition goes from filter_stop_freq to filter_pass_freq
        """
        if self.Pixels == []:
            return None  # no pixels, nothing to do
        if self.wavelength == []:  # required to find Nyquist frequency
            return None
        if ArchiveOld:
            self.PixelsArchive.append(self.Pixels)
        # Compute the filter once (and then apply it for each spectrum)
        # Find Nyquist frequency from wavelength (assume things are evenly spaced)
        nyquist_rate = 1.0 / (2.0 * (self.wavelength[1] - self.wavelength[0]))
        print(nyquist_rate)
        desired = (0, 0, 1, 1)
        bands = (0, filter_stop_freq, filter_pass_freq, nyquist_rate)
        filter_coefs = ss.firls(filter_order, bands, desired, nyq=nyquist_rate)

        # Apply filtering to spectra belonging to each pixel
        PixelsC = np.zeros(self.Pixels.shape, self.Pixels.dtype)
        # NN = 0
        for ii in range(self.Pixels.shape[0]):
            for jj in range(self.Pixels.shape[1]):
                PixelsC[ii, jj, :] = ss.filtfilt(filter_coefs, [1],
                                                 self.Pixels[ii, jj, :])
                # NN += 1
        # print(NN)
        self.Pixels = PixelsC
        return self.Pixels.shape[0] * self.Pixels.shape[
            1]  # Number of spectra filtered
Ejemplo n.º 6
0
def dz_ramp_beta(n, ratio, tb, d1, d2):
    r"""Creates a sloped beta filter for designing sloped profiles
    """
    ftw = dinf(d1, d2) / tb  # fractional transition width
    shift = n / 4

    f = np.array([
        0, shift - (1 + ftw) * tb / 2, shift - (1 - ftw) * tb / 2, shift +
        (1 - ftw) * tb / 2, shift + (1 + ftw) * tb / 2, n / 2
    ]) / (n / 2)  # edges, normalized to Nyquist

    # left amplitude is derived from the fact that the slope we want is
    # (ratio - 1)/tb, but we specify the amplitudes at the more closely spaced
    # edges which are (1 - ftw) * tb apart
    m = np.array([0, 0, (1 - ftw) * (ratio - 1) + 1, 1, 0, 0])  # amp @ edges

    w = np.array([d1 / d2, 1, d1 / d2])  # band error weights

    # design the filter, firls requires odd numtaps, so design 1 extra & trim
    b = signal.firls(n + 1, f, m, w)
    b = b[0:n]
    # hilbert transformation to suppress negative passband, and demod to DC
    b = signal.hilbert(b)
    b = b * np.exp(-1j * 2 * np.pi / n * shift * np.linspace(0, n - 1, n)) / 2
    b = b * np.exp(-1j * np.pi / n * shift)

    # return a normalized version in order to get 1 at DC
    return np.expand_dims(b / np.sum(b), 0)
Ejemplo n.º 7
0
    def test_firls(self):
        N = 11  # number of taps in the filter
        a = 0.1  # width of the transition band

        # design a halfband symmetric low-pass filter
        h = firls(11, [0, a, 0.5-a, 0.5], [1, 1, 0, 0], nyq=0.5)

        # make sure the filter has correct # of taps
        assert_equal(len(h), N)

        # make sure it is symmetric
        midx = (N-1) // 2
        assert_array_almost_equal(h[:midx], h[:-midx-1:-1])

        # make sure the center tap is 0.5
        assert_almost_equal(h[midx], 0.5)

        # For halfband symmetric, odd coefficients (except the center)
        # should be zero (really small)
        hodd = np.hstack((h[1:midx:2], h[-midx+1::2]))
        assert_array_almost_equal(hodd, 0)

        # now check the frequency response
        w, H = freqz(h, 1)
        f = w/2/np.pi
        Hmag = np.abs(H)

        # check that the pass band is close to unity
        idx = np.logical_and(f > 0, f < a)
        assert_array_almost_equal(Hmag[idx], 1, decimal=3)

        # check that the stop band is close to zero
        idx = np.logical_and(f > 0.5-a, f < 0.5)
        assert_array_almost_equal(Hmag[idx], 0, decimal=3)
Ejemplo n.º 8
0
def desired_bandpass():

    ripple_low = 0.02
    ripple_medium = 0.05
    ripple_high = 0.01
    # Normalized frequencies vector
    F = [0, 0.3, 0.4, 0.7, 0.8, 1]
    # Desired amplitudes of each point listed in 'F'
    Amp = [0, 0, 1, 1, 0, 0]
    # Weights vector
    W = [1 / ripple_low, 1 / ripple_medium, 1 / ripple_high]

    h = firls(M + 1, F, Amp, W)
    A_w = get_amplitude_func(h, 1)

    plt.figure()
    plt.plot(h)
    plt.title("h[n] is GLP filter of type I.")
    plt.grid()
    plt.legend()

    w = np.linspace(-2 * math.pi, 2 * math.pi, 4096)
    A = []
    for i in w:
        A.append(A_w(i))
    w /= math.pi

    plt.figure()
    plt.plot(w, A)
    plot_plus("A(w)")
Ejemplo n.º 9
0
def calc_spectrum(files, silences, fs=44100, plot=False):
    window = 4096
    sentenceLen = []
    sentenceFFT = []

    print("Calculating LTASS...")
    for ind, sentenceList in enumerate(files):
        for ind2, file in enumerate(sentenceList):
            x, fs, _ = sndio.read(file)
            f, t, Zxx = sgnl.stft(x,
                                  window=np.ones(window),
                                  nperseg=window,
                                  noverlap=0)
            sil = silences[ind * 10 + ind2]
            sTemp = np.zeros((sil.shape[0], t.size), dtype=bool)
            for ind3, s in enumerate(sil):
                sTemp[ind3, :] = np.logical_and(t > s[0], t < s[1])
            invalidFFT = np.any(sTemp, axis=0)
            sentenceFFT.append(np.abs(Zxx[:, ~np.any(sTemp, axis=0)]))
            sentenceLen.append(x.size)
    sentenceLen = np.array([sentenceLen]).T
    sentenceLen = sentenceLen / sentenceLen.max()
    sentenceFFT = [x * sentenceLen[i] for i, x in enumerate(sentenceFFT)]
    sentenceFFT = np.concatenate([x.T for x in sentenceFFT])

    grandAvgFFT = np.mean(sentenceFFT, axis=0)
    grandAvgFFT = grandAvgFFT / grandAvgFFT.max()
    print("Fitting filter to LTASS...")
    b = sgnl.firls(2049, np.linspace(0, 1, 2049)[1:], grandAvgFFT[1:])
    if plot:
        plt.semilogy(np.abs(sgnl.freqz(b)[1]))
        plt.plot(np.linspace(0, 512, 2049), grandAvgFFT)
        plt.show()
    return b
Ejemplo n.º 10
0
    def design(self, params):
        coeffs = signal.firls(**params)

        den = np.zeros_like(coeffs)
        den[0] = 1

        return coeffs, den
Ejemplo n.º 11
0
 def getfilts(self, rawdat, fstop=600, fpass=700):
     fnyq = self.fs / 2.
     desired = (0, 0, 1, 1)
     bands = (0, fstop, fpass, fnyq)  # see SciPy documentation
     filtcoefs = sig.firls(1001, bands, desired, nyq=fnyq)
     filtdat = sig.filtfilt(filtcoefs, [1], rawdat, axis=-1)
     return filtdat
Ejemplo n.º 12
0
def filtr_HR(X0, Fs=25, filt=True):
    nyq = Fs / 2
    flag = False

    if len(X0.shape) == 1:
        X0 = X0.reshape(-1, 1)
        flag = True
    X1 = np.copy(X0)  #sig.detrend(X0,type='constant',axis=0); # Subtract mean
    if filt:
        # filter design used from Ju's code with slight changes for python syntax
        b = sig.firls(219,
                      np.array([0, 0.5, 1, nyq]),
                      np.array([1, 1, 0, 0]),
                      np.array([1, 1]),
                      nyq=nyq)
        X = np.zeros(X1.shape)
        for i in range(X1.shape[1]):
            #X[:,i] = sig.convolve(X1[:,i],b,mode='same'); # filtering using convolution, mode='same' returns the centered signal without any delay
            X[:, i] = sig.filtfilt(b, [1], X1[:, i])
    else:
        X = X1

    if flag:
        X = X.reshape(-1)
    #X=sig.detrend(X,type='constant',axis=0); # subtracted mean again to center around x=0 just in case things changed during filtering
    return X
def preProcessing(data, Fs=25, fil_type='ppg'):
    '''
    Inputs
    data: a numpy array of shape n*10 .. the columns are timestamp,ppg red, ppg infrared,
    ppg green, acl x,y,z, gyro x,y,z
    Fs: sampling rate
    fil_type: ppg or ecg
    Output X2: preprocessed signal data
    preprocessing the data by filtering
    '''
    if data.shape[0] < 165:
        return np.zeros((0, data.shape[1]))

    X0 = data[:, 1:4]
    X1 = signal.detrend(X0, axis=0, type='constant')
    # if fil_type in ['ppg']:
    b = signal.firls(65,
                     np.array([0, 0.3, 0.4, 2, 2.5, Fs / 2]),
                     np.array([0, 0, 1, 1, 0, 0]),
                     np.array([100 * 0.02, 0.02, 0.02]),
                     fs=Fs)
    X2 = np.zeros((np.shape(X1)[0] - len(b) + 1, data.shape[1]))
    for i in range(X2.shape[1]):
        if i in [1, 2, 3]:
            X2[:, i] = signal.convolve(X1[:, i - 1], b, mode='valid')
        else:
            X2[:, i] = data[64:, i]

    return X2
Ejemplo n.º 14
0
    def test_firls(self):
        N = 11  # number of taps in the filter
        a = 0.1  # width of the transition band

        # design a halfband symmetric low-pass filter
        h = firls(11, [0, a, 0.5-a, 0.5], [1, 1, 0, 0], fs=1.0)

        # make sure the filter has correct # of taps
        assert_equal(len(h), N)

        # make sure it is symmetric
        midx = (N-1) // 2
        assert_array_almost_equal(h[:midx], h[:-midx-1:-1])

        # make sure the center tap is 0.5
        assert_almost_equal(h[midx], 0.5)

        # For halfband symmetric, odd coefficients (except the center)
        # should be zero (really small)
        hodd = np.hstack((h[1:midx:2], h[-midx+1::2]))
        assert_array_almost_equal(hodd, 0)

        # now check the frequency response
        w, H = freqz(h, 1)
        f = w/2/np.pi
        Hmag = np.abs(H)

        # check that the pass band is close to unity
        idx = np.logical_and(f > 0, f < a)
        assert_array_almost_equal(Hmag[idx], 1, decimal=3)

        # check that the stop band is close to zero
        idx = np.logical_and(f > 0.5-a, f < 0.5)
        assert_array_almost_equal(Hmag[idx], 0, decimal=3)
Ejemplo n.º 15
0
def JP_dzls(nf, tb, d1, d2):
    '''
    Designs a least squares filter.

    Parameters
    ----------
    nf : int
        Filter length
    tb : float
        Time-bandwidth
    d1 : float
        Pass band ripple
    d2 : float
        Stop band ripple

    Returns
    -------
    h : numpy.ndarray
        Least squares filter
    '''
    di = JP_dinf(d1, d2)
    w = di / tb
    f = np.asarray([0, (1 - w) * (tb / 2),
                    (1 + w) * (tb / 2), nf / 2]) / (nf / 2)
    m = np.asarray([1, 1, 0, 0])
    w = np.asarray([1, d1 / d2])

    h = firls(nf - 1, f, m, w)

    h = resample(h, nf)

    return h
Ejemplo n.º 16
0
    def bandlmt_wnoise(npoints=1000,
                       mu=10,
                       arvmean=1,
                       time=100,
                       freqsupport=(0, 1.5, 1.7, 3, 3.2, 4.5, 4.7, 5),
                       ampsupport=(0.9, 1, 0.2, 0.2, 1, 0.9, 0, 0),
                       numtabs=201,
                       seed=None):
        if seed is None:
            seed = np.random.randint(0, int(1e6))
            print('Randomly chosen seed is {}.'.format(seed))
        if freqsupport[-1] > npoints / time / 2:
            raise FilterBandwidthExceedsSamplingBandwidthError

        np.random.seed(seed)

        freqsupport = list(freqsupport)
        fs = npoints / time
        freqsupport[-1] = fs / 2

        t = np.linspace(time / npoints, time, npoints)
        n = np.random.randn(npoints + numtabs)

        coeffs = scisig.firls(numtabs, freqsupport, ampsupport, nyq=fs / 2)
        zi = scisig.lfilter_zi(b=coeffs, a=1)
        z, _ = scisig.lfilter(b=coeffs, a=1, x=n, zi=zi * n[0])
        z = z[numtabs:]

        sig = Signal(t, z)
        sig *= 1 / np.mean(abs(sig.vals)) * arvmean
        sig += mu

        return sig
Ejemplo n.º 17
0
 def test_rank_deficient(self):
     # solve() runs but warns (only sometimes, so here we don't use match)
     x = firls(21, [0, 0.1, 0.9, 1], [1, 1, 0, 0])
     w, h = freqz(x, fs=2.)
     assert_allclose(np.abs(h[:2]), 1., atol=1e-5)
     assert_allclose(np.abs(h[-2:]), 0., atol=1e-6)
     # switch to pinvh (tolerances could be higher with longer
     # filters, but using shorter ones is faster computationally and
     # the idea is the same)
     x = firls(101, [0, 0.01, 0.99, 1], [1, 1, 0, 0])
     w, h = freqz(x, fs=2.)
     mask = w < 0.01
     assert mask.sum() > 3
     assert_allclose(np.abs(h[mask]), 1., atol=1e-4)
     mask = w > 0.99
     assert mask.sum() > 3
     assert_allclose(np.abs(h[mask]), 0., atol=1e-4)
Ejemplo n.º 18
0
def detlpf(Fs, Flo, in_i, in_q):
    b = scpsig.firls(
        501, [0.0, (0.5 * Flo) / (Fs / 2), (Flo) / (Fs / 2), 1.0],
        [10**(0 / 20), 10**(0 / 20), 10**(-60 / 20), 10**(-60 / 20)], [1, 1])
    a = 1
    out_i = scpsig.lfilter(b, a, in_i)
    out_q = scpsig.lfilter(b, a, in_q)
    return [out_i, out_q]
Ejemplo n.º 19
0
 def test_rank_deficient(self):
     # solve() runs but warns (only sometimes, so here we don't use match)
     x = firls(21, [0, 0.1, 0.9, 1], [1, 1, 0, 0])
     w, h = freqz(x, fs=2.)
     assert_allclose(np.abs(h[:2]), 1., atol=1e-5)
     assert_allclose(np.abs(h[-2:]), 0., atol=1e-6)
     # switch to pinvh (tolerances could be higher with longer
     # filters, but using shorter ones is faster computationally and
     # the idea is the same)
     x = firls(101, [0, 0.01, 0.99, 1], [1, 1, 0, 0])
     w, h = freqz(x, fs=2.)
     mask = w < 0.01
     assert mask.sum() > 3
     assert_allclose(np.abs(h[mask]), 1., atol=1e-4)
     mask = w > 0.99
     assert mask.sum() > 3
     assert_allclose(np.abs(h[mask]), 0., atol=1e-4)
Ejemplo n.º 20
0
def highpass_filter(fs = 2000000, flt_stopfreq = 300, flt_passfreq = 600, flt_order = 1):
  # High-pass filter
  nyquist_rate = fs / 2.0
  desired = (0, 0, 1, 1)
  bands = (0, flt_stopfreq, flt_passfreq, nyquist_rate)
  flt_coefs = signal.firls(flt_order, bands, desired, nyq=nyquist_rate)
  freq, response = signal.freqz(flt_coefs)
  #print flt_coefs[300:700]
  return freq, response
def bandpassfilter(x,fs):
    """
    
    :param x: a list of samples 
    :param fs: sampling frequency
    :return: filtered list
    """
    x = signal.detrend(x)
    b = signal.firls(129,[0,0.6*2/fs,0.7*2/fs,3*2/fs,3.5*2/fs,1],[0,0,1,1,0,0],[100*0.02,0.02,0.02])
    return signal.convolve(x,b,'valid')
Ejemplo n.º 22
0
 def init_preliminary_filter(self, order=None, freq_stop=40, freq_pass=70):
     # calculate filter coefficients for preliminary hp filter
     if order is None:
         # order = int(np.round(300/16000*self.Fs))
         order = int(np.ceil(300 / 16000 * self.Fs) // 2 * 2 + 1)
     logging.info("Preliminary high-pass filter order set to %d" % order)
     self.hpfilt_b = sig.firls(
         order, [0, freq_stop, freq_pass, self.Fs / 2], [0, 0, 1, 1], [1, 1], fs=self.Fs
     )
     return len(self.hpfilt_b)
Ejemplo n.º 23
0
    def fit(self, *args, **kwargs):
        super().fit(*args, **kwargs)

        freqs = librosa.core.fft_frequencies(sr=2, n_fft=self.num_fft)
        self.firs = {
            device: signal.firls(self.num_taps,
                                 _bands(freqs),
                                 _bands(coefficients),
                                 fs=2)
            for device, coefficients in self.coefficients.items()
        }
Ejemplo n.º 24
0
 def init_preliminary_filter(self, order=None, freq_stop=40, freq_pass=70):
     # calculate filter coefficients for preliminary hp filter
     if order is None:
         order = int(np.round(300/16000*self.Fs))
     logging.info('Preliminary high-pass filter order set to %d'%order)
     self.hpfilt_b = sig.firls(order,
                               [0, freq_stop, freq_pass, self.Fs/2],
                               [0, 0, 1, 1],
                               [1, 1],
                               fs=self.Fs)
     return len(self.hpfilt_b)
Ejemplo n.º 25
0
def firlsDesign(L, w0, rippleDb=-30):
    "Like `remezDesign` but uses `scipy.signal.firls` instead of Remez."
    ntaps, _ = signal.kaiserord(rippleDb,
                                (2 * np.pi - 2 * w0) / (L * 2 * np.pi))
    # firls requires odd numtaps
    if ntaps % 2 == 0:
        ntaps += 1
    b, g = remezBands(L, w0)
    # the `vstack` stuff below: repeat each element of `g` twice, so `[1 0 0]`
    # becomes `[1 1, 0 0, 0 0]`.
    return signal.firls(ntaps, b, np.vstack([g, g]).T.ravel(), nyq=0.5)
Ejemplo n.º 26
0
def detect_env(x):
    '''
    Detect envelope of signal
    Group delay = 49
    '''
    fbe = [0, 0.05, 0.1, 1]
    damps = [1, 1, 0, 0]
    b = signal.firls(99, fbe, damps)
    gd = 49  # Can be computed using signal.group_delay

    envx = (np.pi / 2) * signal.lfilter(b, 1, np.abs(x))
    return envx, gd
Ejemplo n.º 27
0
    def highpass_filter(self, raw, fs):

        nyquist_rate = fs / 2.
        desired = (0, 0, 1, 1)
        bands = (0, self.stop_freq_Hz, self.pass_freq_Hz, nyquist_rate)
        filter_coefs = signal.firls(self.filter_order,
                                    bands,
                                    desired,
                                    nyq=nyquist_rate)

        filtered_raw = signal.filtfilt(filter_coefs, [1], raw)
        return filtered_raw
Ejemplo n.º 28
0
def lowpass(my_signal,
            sampl_freq,
            passband_frac=0.5,
            stopband_frac=0.75,
            filter_order=21):
    nyquist_rate = sampl_freq / 2.
    desired = (1, 1, 0, 0)
    bands = (0, passband_frac * nyquist_rate, stopband_frac * nyquist_rate,
             nyquist_rate)
    filter_coefs = signal.firls(filter_order, bands, desired, nyq=nyquist_rate)
    filtered = signal.filtfilt(filter_coefs, [1], my_signal)
    return filtered
Ejemplo n.º 29
0
def filtr(X0,Fs,filt=False):
    nyq=Fs/2
    X1 = sig.detrend(X0,type='constant',axis=0); # Subtract mean
    if filt:
        # filter design used from Ju's code with slight changes for python syntax
        b = sig.firls(129,np.array([0,0.6,0.7,3,3.5,nyq]),np.array([0,0,1,1,0,0]),np.array([100*0.02,0.02,0.02]),nyq=nyq);
        X=np.zeros(X1.shape)
        for i in range(X1.shape[1]):
            X[:,i] = sig.convolve(X1[:,i],b,mode='same'); # filtering using convolution, mode='same' returns the 'centered signal without any delay
    else:
        X=X1
    X=sig.detrend(X,type='constant',axis=0); # subtracted mean again to center around x=0 just in case things changed during filtering
    return X
def CreateNote(string, Delay):
    Numerator = signal.firls(43, [0, 1 / Delay, 2 / Delay, 1], [0, 0, 1, 1])
    list = zerolistmaker(int(Delay))
    list = [1] + list + [-0.5, -0.5]
    Denominator = np.array(list)

    zi = np.random.rand(max(len(Denominator), len(Numerator)) - 1, 1)

    note, z0 = lfilter(Numerator, Denominator, input, axis=-2, zi=zi)
    note = note - np.mean(note)
    note = note / max(abs(note))
    sd.play(note, FS)
    sd.wait()
Ejemplo n.º 31
0
def highpass_filter(y, sr):
    filter_stop_freq = 70  # Hz
    filter_pass_freq = 100  # Hz
    filter_order = 1001

    # High-pass filter
    nyquist_rate = sr / 2.
    desired = (0, 0, 1, 1)
    bands = (0, filter_stop_freq, filter_pass_freq, nyquist_rate)
    filter_coefs = signal.firls(filter_order, bands, desired, nyq=nyquist_rate)

    # Apply high-pass filter
    filtered_audio = signal.filtfilt(filter_coefs, [1], y)
    return filtered_audio
Ejemplo n.º 32
0
def firls(n: int, f, a, w=None) -> Tuple:
    """
    FIR filter design using least-squares error minimization.

    Calculate the filter coefficients for the linear-phase finite
    impulse response (FIR) filter which has the best approximation
    to the desired frequency response described by `f` and
    `a` in the least squares sense (i.e., the integral of the
    weighted mean-squared error within the specified bands is
    minimized).

    Parameters
    ----------
    n : int
        Filter order, specified as a real positive scalar. `n` must be even.
        
    f : array_like
        A monotonic nondecreasing sequence containing the band edges in
        Hz. All elements must be non-negative and less than or equal to
        1.
        
    a : array_like
        A sequence the same size as `f` containing the desired gain
        at the start and end point of each band.
        
    w : array_like, optional
        A relative weighting to give to each band region when solving
        the least squares problem. `w` has to be half the size of
        `f`.

    Returns
    -------
    system :a tuple of array_like describing the system.
            The following gives the number of elements in the tuple and
            the interpretation:
                
                * (num, den)
    """

    if n % 2 == 1:
        n += 1
        #print('Warning: The filter order you inserted is even.')
        #print('         The filter order changed to {}.'.format(n))

    n += 1
    num = signal.firls(n, f, a, weight=w)
    den = 1

    return num, den
Ejemplo n.º 33
0
def compute_moving_window_int(sample: np.ndarray,
							  fs: float,
							  blackmanWinlen: int,
							  filter_length: int = 257,
							  delta: float = .02) -> np.ndarray:
	"""
	:param sample: ecg sample array
	:param fs: sampling frequency
	:param blackmanWinlen: length of the blackman window on which to compute the moving window integration
	:param filter_length: length of the FIR bandpass filter on which filtering is done on ecg sample array
	:param delta: to compute the weights of each band in FIR filter
	:return: the Moving window integration of the sample array
	"""
	# I believe these constants can be kept in a file
	try:
		# filter edges
		filter_edges = [0, 4.5 * 2 / fs, 5 * 2 / fs, 20 * 2 / fs, 20.5 * 2 / fs, 1]
		# gains at filter band edges
		gains = [0, 0, 1, 1, 0, 0]
		# weights
		weights = [500 / delta, 1 / delta, 500 / delta]
		# length of the FIR filter

		# FIR filter coefficients for bandpass filtering
		filter_coeff = signal.firls(filter_length, filter_edges, gains, weights)

		# bandpass filtered signal
		bandpass_signal = signal.convolve(sample, filter_coeff, 'same')
		bandpass_signal /= np.percentile(bandpass_signal, 90)

		# derivative array
		derivative_array = (np.array([-1.0, -2.0, 0, 2.0, 1.0])) * (1 / 8)
		# derivative signal (differentiation of the bandpass)
		derivative_signal = signal.convolve(bandpass_signal, derivative_array, 'same')
		derivative_signal /= np.percentile(derivative_signal, 90)

		# squared derivative signal
		derivative_squared_signal = derivative_signal ** 2
		derivative_squared_signal /= np.percentile(derivative_squared_signal, 90)

		# blackman window
		blackman_window = np.blackman(blackmanWinlen)
		# moving window Integration of squared derivative signal
		mov_win_int_signal = signal.convolve(derivative_squared_signal, blackman_window, 'same')
		mov_win_int_signal /= np.percentile(mov_win_int_signal, 90)

		return mov_win_int_signal
	except:
		return np.array([])
Ejemplo n.º 34
0
def _highpass_filter(y, sr):
    filter_stop_freq = 50  # Hz
    filter_pass_freq = 200  # Hz
    filter_order = 1001

    # High-pass filter
    nyquist_rate = sr / 2.
    desired = (0, 0, 1, 1)
    bands = (0, filter_stop_freq, filter_pass_freq, nyquist_rate)
    filter_coefs = signal.firls(filter_order, bands, desired, nyq=nyquist_rate)

    # Apply high-pass filter
    filtered_audio = signal.filtfilt(filter_coefs, [1], y)
    yt = np.ascontiguousarray(filtered_audio)
    return yt
Ejemplo n.º 35
0
    def __init__(
            self, name, passband_end_frequency, stopband_start_frequency,
            filter_length, input_sample_rate):
        
        fs = input_sample_rate

        # Design filter.
        f_pass = passband_end_frequency
        f_stop = stopband_start_frequency
        bands = np.array([0, f_pass, f_stop, fs / 2])
#         desired = np.array([1, 0])
#         coefficients = signal.remez(filter_length, bands, desired, fs=fs)
        desired = np.array([1, 1, 0, 0])
        coefficients = signal.firls(filter_length, bands, desired, fs=fs)

        super().__init__(name, coefficients, input_sample_rate)
def _firls(numtaps, bands, desired):
    
    """
    Designs an FIR filter that is optimum in a least squares sense.
    
    This function is like `scipy.signal.firls` except that `numtaps`
    can be even as well as odd and band weighting is not supported.
    """
    
    # TODO: Add support for band weighting and then submit a pull
    # request to improve `scipy.signal.firls`.
    
    numtaps = int(numtaps)
    if numtaps % 2 == 1:
        return signal.firls(numtaps, bands, desired)
    else:
        return _firls_even(numtaps, bands, desired)
Ejemplo n.º 37
0
 def time_firls(self, n, edges):
     signal.firls(n, (0,) + edges + (1,), [1, 1, 0, 0])
Ejemplo n.º 38
0
					self.values, self.uncertainty = \
						MC(self.values, self.uncertainty, b, a, filter_uncertainty, runs=MonteCarloRuns)
			else:
				if not isinstance(MonteCarloRuns, int):
					MonteCarloRuns = 10000
				self.values, self.uncertainty = \
					MC(self.values, self.uncertainty, b, a, filter_uncertainty, runs=MonteCarloRuns)
		else:	# IIR-type filter
			if not isinstance(MonteCarloRuns, int):
				MonteCarloRuns = 10000
				self.values, self.uncertainty = \
					MC(self.values, self.uncertainty, b, a, filter_uncertainty, runs=MonteCarloRuns)




if __name__=="__main__":
	N = 1024
	Ts = 0.01
	time = np.arange(0, N*Ts, Ts)
	x = rect(time, Ts*N//4, Ts*N//4*3)
	ux= 0.02
	signal = Signal(time, x, Ts = Ts, uncertainty = ux)
	b  = dsp.firls(15, [0, 0.2*signal.Fs/2, 0.25*signal.Fs/2, signal.Fs/2 ], [1, 1, 0, 0], nyq=signal.Fs/2)
	Ub = np.diag(b*1e-1)
	signal.apply_filter(b, filter_uncertainty=Ub)
	signal.plot_uncertainty()
	bl, al = dsp.bessel(4, 0.2)
	Ul = np.diag(np.r_[al[1:]*1e-3, bl*1e-2]**2)
	signal.apply_filter(bl, al, filter_uncertainty = Ul)
	signal.plot_uncertainty(fignr = 3)