Example #1
1
File: cq.py Project: erikvdp/Thesis
def pitch_filter_bank(ratios_pitches=None, fs=16000, Q=25.0, max_loss_pass=1.0, min_attenuation_stop=50.0):
    """
    lowest pitch: 20.6 Hz = pitch 16, the lowest pitch above the low threshold of hearing
    highest pitch: 7458.6 Hz = pitch 118, the highest pitch below half of the sampling frequency (fs = 16000Hz)
    Note that 119 is technically below the nyquist frequency (~7900Hz), but the right stopband frequency wouldn't be.
    
    fs: sampling frequency of the input in Hz
    Q: Q factor = frequency / bandwidth, used to determine passband and stopband frequencies of the elliptic filters
    max_loss_pass: maximal loss in passband in dB
    min_attenuation_stop: minimal attenuation in stopband in dB
    """
    if ratios_pitches is None:
        ratios_pitches = RATIOS_PITCHES_DEFAULT
        # structure: tuples of sampling frequency ratios and sets of pitches

    filters = {} # dictionary indexed by sampling frequency ratio. Each item is again a dictionary indexed by pitch, giving a filter coefficient tuple.
    
    for ratio, pitches in ratios_pitches:
        filters[ratio] = {}
        current_fs = float(fs / ratio) # input sampling frequency for the current set of pitches
        nyquist_freq = current_fs / 2
        for pitch in pitches:
            freq = pitch2freq(pitch)
            w = freq / nyquist_freq # omega = normalised frequency
            w_pass = (w * (1 - 1 / (2*Q)), w * (1 + 1 / (2*Q)))
            w_stop = (w * (1 - 1 / Q), w * (1 + 1 / Q))
            n, w_natural = sig.ellipord(w_pass, w_stop, max_loss_pass, min_attenuation_stop)
            coeff_b, coeff_a = sig.ellip(n, max_loss_pass, min_attenuation_stop, w_natural, btype='bandpass') # get filter coefficients
            # note that scipy's ellip differs from matlab's in that it will always generate a lowpass filter by default.
            # btype='bandpass' needs to be passed explicitly!
            filters[ratio][pitch] = (coeff_b, coeff_a)
    
    return filters
Example #2
0
def filter(sig, order=5, low=50, high=200, plot=False, typ='lowpass'):
    # Filter out-of-band noise by bandpass filter
    # bandpass_out = signal.filtfilt(b11, a11, y)
    # Coherent demodulation, multiplied by coherent carrier in phase with the same frequency
    # coherent_demod = bandpass_out * (coherent_carrier * 2)
    if typ == 'lowpass':
        [b, a] = signal.ellip(order,
                              0.5,
                              60, (high * 2 / Fs),
                              btype='lowpass',
                              analog=False,
                              output='ba')
    elif typ == 'highpass':
        [b, a] = signal.ellip(order,
                              0.5,
                              60, (low * 2 / Fs),
                              btype='highpass',
                              analog=False,
                              output='ba')
    else:
        [b, a] = signal.ellip(order,
                              0.5,
                              60, [low * 2 / Fs, high * 2 / Fs],
                              btype='bandpass',
                              analog=False,
                              output='ba')
    result = signal.filtfilt(b, a, sig)
    if plot == True:
        plt.plot(result)
    return result
Example #3
0
def eliptic(n=5, rp=1, rs=10, wn=3911.5, btype='lowpass'):
    """ normal eliptic designer

    Args:
        n (int, optional): order_of_the_filter. Defaults to 5.
        rp (int, optional): The maximum ripple allowed below unity gain in the passband. Defaults to 1.
        rs (int, optional): The minimum attenuation required in the stop band. Defaults to 10.
        wn (float, optional): critical frequencies. Defaults to 3911.5.
        btype (str, optional): {‘lowpass’, ‘highpass’, ‘bandpass’, ‘bandstop’}. Defaults to 'low'.
    Returns:
        sympy functions: Numerator, denominator        
    """
    Numerator, denominator = signal.ellip(n, rp, rs, wn, btype, analog=True)

    denominator_ = sum(co * s**i for i, co in enumerate(reversed(denominator)))
    Numerator_ = sum(co * s**i for i, co in enumerate(reversed(Numerator)))
    print("transfer function :")
    display(Numerator_ / denominator_)
    Zeros, poles, system_gain = signal.ellip(n,
                                             rp,
                                             rs,
                                             wn,
                                             'low',
                                             analog=True,
                                             output='zpk')
    print("\n Zeros :", Zeros, "\n", "Poles :", poles, "\n", "Gain :",
          system_gain)

    wz, mag, phase = signal.bode((Numerator, denominator))
    fig = plt.figure(figsize=(12, 6))
    ax = fig.add_subplot(121)
    ax.semilogx(wz, mag)  # Bode magnitude plot
    plt.xscale('log')
    plt.title('Elliptic filter frequency response rs=' + str(rs) + " rp=" +
              str(rp))
    plt.xlabel('Frequency [radians / second]')
    plt.ylabel('Magnitude [dB]')
    plt.margins(0, 0.1)
    plt.grid(which='both', axis='both')
    plt.axvline(wn, color='red')  # cutoff frequency
    plt.axhline(-1 * rs, color='red')  # rs
    plt.axhline(-1 * rp, color='red')  # rp

    ax2 = fig.add_subplot(122)
    ax2.semilogx(wz, phase)  # Bode phase plot
    plt.xscale('log')
    plt.title('Elliptic filter frequency response rs=' + str(rs) + " rp=" +
              str(rp))
    plt.xlabel('Frequency [radians / second]')
    plt.ylabel('Phase radians')
    plt.margins(0, 0.1)
    plt.grid(which='both', axis='both')
    plt.axvline(wn, color='red')  # cutoff frequency
    plt.show(block=False)
    return Numerator_, denominator_
Example #4
0
 def __init__(self, timestep):
     self.sampling_rate = int(1. / timestep)
     self.timestep = timestep
     self.c_detect = ellip(
         2, .1, 40, (2 * timestep * DETECT_LOW, 2 * timestep * DETECT_HIGH),
         'bandpass')
     self.c_extract = ellip(
         2, .1, 40,
         (2 * timestep * EXTRACT_LOW, 2 * timestep * EXTRACT_HIGH),
         'bandpass')
     self.c_notch = ellip(2, .5, 20,
                          (2 * timestep * 1999, 2 * timestep * 2001),
                          'bandstop')
Example #5
0
    def __amp_detect(self, x):
        
        ref = np.floor(self.min_ref_per*self.sr/1000.0)
        
        # HIGH-PASS FILTER OF THE DATA
        (b,a) = signal.ellip(2, 0.1, 40, [self.fmin_detect*2.0/self.sr,self.fmax_detect*2.0/self.sr], btype='bandpass', analog=0, output='ba')
        xf_detect = signal.filtfilt(b, a, x)
        (b,a) = signal.ellip(2, 0.1, 40, [self.fmin_sort*2.0/self.sr,self.fmax_sort*2.0/self.sr], btype='bandpass', analog=0, output='ba')
        xf = signal.filtfilt(b, a, x)
        
        
        noise_std_detect = scipy.median(np.abs(xf_detect))/0.6745;
        noise_std_sorted = scipy.median(np.abs(xf))/0.6745;
       
        thr = self.stdmin * noise_std_detect        #thr for detection is based on detected settings.
        thrmax = self.stdmax * noise_std_sorted     #thrmax for artifact removal is based on sorted settings.
        
        # LOCATE SPIKE TIMES
        nspk = 0;
        xaux = np.argwhere(xf_detect[self.w_pre+1:len(xf_detect)-self.w_post-1-1] > thr) + self.w_pre + 1
        xaux = np.resize(xaux,len(xaux))
        xaux0 = 0;
        index = []
        for i in range(len(xaux)):
            if xaux[i] >= (xaux0 + ref):
            # after find a peak it begin search after ref over the last xaux
                iaux = xf[xaux[i]:xaux[i]+np.floor(ref/2.0)].argmax(0)    # introduces alignment
                nspk = nspk + 1
                index.append(iaux + xaux[i])
                xaux0 = index[nspk-1];
        
        # SPIKE STORING (with or without interpolation)
        ls = self.w_pre + self.w_post
        spikes = np.zeros([nspk,ls+4])
        xf = np.concatenate((xf,np.zeros(self.w_post)),axis=0)
        
        for i in range(nspk):                          # Eliminates artifacts
            if np.max( np.abs( xf[index[i]-self.w_pre:index[i]+self.w_post] )) < thrmax :
                spikes[i,:] = xf[index[i]-self.w_pre-1:index[i]+self.w_post+3]
     
        aux = np.argwhere(spikes[:,self.w_pre] == 0)       #erases indexes that were artifacts
        if len(aux) != 0:
            aux = aux.reshape((1,len(aux)))[0]
            spikes = np.delete(spikes, aux, axis = 0)
            index = np.delete(index,aux)
 
        if self.interpolation == 'y':
            # Does interpolation
            spikes = self.__int_spikes(spikes)

        return spikes, thr, index
Example #6
0
def filter_emg(data: np.array, fs: int, Rs: int, notch: bool):

    N, fn = signal.ellipord([46.0, 54.0], [47.0, 53], .01, Rs, fs=fs)
    be, ae = signal.ellip(N, .01, Rs, fn, fs=fs, btype='bandstop')
    N, fn = signal.ellipord([96, 104.0], [97, 103], .01, Rs, fs=fs)
    be_100, ae_100 = signal.ellip(N, .01, Rs, fn, fs=fs, btype='bandstop')
    N, fn = signal.cheb2ord(15, 10, .0086, 55, fs=500)
    bb, ab = signal.cheby2(N, 50, fn, 'high', fs=fs)
    signal_filtered = signal.lfilter(
        be_100, ae_100, signal.lfilter(be, ae, signal.lfilter(bb, ab, data)))
    #     signal_filtered = data
    signal_filtered_zero_ph = signal.filtfilt(
        be_100, ae_100, signal.filtfilt(be, ae, signal.filtfilt(bb, ab, data)))
    return signal_filtered, signal_filtered_zero_ph
Example #7
0
 def __init__(self, timestep):
     self.sampling_rate = int(1. / timestep)
     self.timestep = timestep
     self.c_detect = ellip(2, .1, 40,
                           (2 * timestep * DETECT_LOW,
                            2 * timestep * DETECT_HIGH),
                           'bandpass')
     self.c_extract = ellip(2, .1, 40,
                            (2 * timestep * EXTRACT_LOW,
                             2 * timestep * EXTRACT_HIGH),
                            'bandpass')
     self.c_notch = ellip(2, .5, 20,
                          (2 * timestep * 1999, 2 * timestep * 2001),
                          'bandstop')
Example #8
0
 def __init__(self,
              order=4,
              passband_ripple=1,
              stopband_rejection=50,
              q_factor=25,
              fmin=27.5,
              fmax=4200.,
              fref=A4):
     from scipy.signal import ellip
     self.order = order
     self.passband_ripple = passband_ripple
     self.stopband_rejection = stopband_rejection
     self.q_factor = q_factor
     self.fref = fref
     self.center_frequencies = semitone_frequencies(fmin, fmax, fref=fref)
     # use different sample rates for the individual bands
     self.band_sample_rates = np.ones_like(self.center_frequencies) * 4410
     self.band_sample_rates[self.center_frequencies > 2000] = 22050
     self.band_sample_rates[self.center_frequencies < 250] = 882
     self.filters = []
     for freq, sample_rate in zip(self.center_frequencies,
                                  self.band_sample_rates):
         freqs = [(freq - freq / q_factor / 2.) * 2. / sample_rate,
                  (freq + freq / q_factor / 2.) * 2. / sample_rate]
         self.filters.append(
             ellip(order,
                   passband_ripple,
                   stopband_rejection,
                   freqs,
                   btype='bandpass'))
Example #9
0
	def bp_filt(self, df):
		'''bandpass filter'''
		cutfreq = np.array([self.up_Fcut, self.low_Fcut])
		b, a = signal.ellip(4, 0.1, 40, 
							cutfreq*2/self.dataset.Fs, btype='bandpass')
		output = self.filtfilt_df(df, a, b)
		return output
Example #10
0
 def signal_bypass(self, cutoff, order, a_pass, rp, rs, btype='high'):
     nyq = 0.5 * self.fs
     normal_cutoff = cutoff / nyq
     if self.band_type == 'cheby1':
         b, a = signal.cheby1(order,
                              a_pass,
                              normal_cutoff,
                              btype=btype,
                              analog=False)
     elif self.band_type == 'cheby2':
         b, a = signal.cheby2(order,
                              a_pass,
                              normal_cutoff,
                              btype=btype,
                              analog=False)
     elif self.band_type == 'ellip':
         b, a = signal.ellip(order,
                             rp,
                             rs,
                             normal_cutoff,
                             btype=btype,
                             analog=False)
     elif self.band_type == 'bessel':
         b, a = signal.bessel(order,
                              normal_cutoff,
                              btype=btype,
                              analog=False)
     else:
         b, a = signal.butter(order,
                              normal_cutoff,
                              btype=btype,
                              analog=False)
     return b, a
Example #11
0
 def make_filter(self):
     b, a = ellip(self.order,
                  self.attentuation,
                  [2 * self.fc1 / self.fe, 2 * self.fc2 / self.fe],
                  output="ba",
                  btype="bandpass")
     return b, a
Example #12
0
def ex_24():
    [b_butter, a_butter] = butter(N, Wc, analog=True)
    H = control.tf(b_butter, a_butter)
    plot_zpk_from_H(H, title='Zeros-poles plot for Butterworth filter')

    [b_ch1, a_ch1] = cheby1(N, Ap, Wp, analog=True)
    H = control.tf(b_ch1, a_ch1)
    plot_zpk_from_H(H, title='Zeros-poles plot for Chebyshev-I filter')

    [b_ch2, a_ch2] = cheby2(N, As, Ws, analog=True)
    H = control.tf(b_ch2, a_ch2)
    plot_zpk_from_H(H, title='Zeros-poles plot for Chebyshev-II filter')

    [b_elip, a_elip] = ellip(N, Ap, As, Wp, analog=True)
    H = control.tf(b_elip, a_elip)
    plot_zpk_from_H(H, title='Zeros-poles plot for elliptical filter')

    plt.figure()
    w_butter, h_butter = freqs(b_butter, a_butter)
    w_ch1, h_ch1 = freqs(b_ch1, a_ch1)
    w_ch2, h_ch2 = freqs(b_ch2, a_ch2)
    w_elip, h_elip = freqs(b_elip, a_elip)
    plt.plot(w_butter, abs(h_butter), label="Butterworth")
    plt.plot(w_ch1, abs(h_ch1), label="Chebyshev-I")
    plt.plot(w_ch2, abs(h_ch2), label="Chebyshev-II")
    plt.plot(w_elip, abs(h_elip), label="Elliptic")
    plt.xlabel('Frequency [radians / second]')
    plt.ylabel('Amplitude')

    plt.show()
Example #13
0
def get_filter(spec, filter_type='but', method='zoh'):
    
    if filter_type.lower() in ('butterworth'):
        N, Wn = signal.buttord(2*np.pi*spec['fp'], 2*np.pi*spec['fs'], spec['Amax'], spec['Amin'], analog=True)
        z, p, k = signal.butter(N, Wn, output='zpk', btype='low', analog=True)
    elif filter_type.lower() in ('cauer' + 'elliptic'):
        N, Wn = signal.ellipord(2*np.pi*fp, 2*np.pi*spec['fs'], spec['Amax'], spec['Amin'], analog=True)
        z, p, k = signal.ellip(N, spec['Amax'], spec['Amin'], Wn, output='zpk', btype='low', analog=True)

    def matched_method(z, p, k, dt):
        zd = np.exp(z*dt)
        pd = np.exp(p*dt)
        kd = k * np.abs(np.prod(1-pd)/np.prod(1-zd) * np.prod(z)/np.prod(p))
        return zd, pd, kd, dt

    if method == 'matched':
        zd, pd, kd, dt = matched_method(z, p, k, spec['dt'])
        kd *= 1 - (1 - 10 ** (-spec['Amax']/20))/2
    else:
        zd, pd, kd, dt = signal.cont2discrete((z,p,k), spec['dt'], method=method)

    analog_system = (z,p,k)
    discrete_system = (zd,pd,kd)

    return analog_system, discrete_system
Example #14
0
 def BPmin(self, fil_dict):
     """Elliptic BP filter, minimum order"""
     self.get_params(fil_dict)
     self.N, self.F_PBC = ellipord([self.F_PB, self.F_PB2],
         [self.F_SB, self.F_SB2], self.A_PB, self.A_SB, analog = self.analog)
     self.save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                     btype='bandpass', analog = self.analog, output = frmt))
Example #15
0
def ellip_filter(array, fs, fc, order=3, method='pad'):
    # fs - частота обработки, fc - частота среза (угловая частота)
    # w - скаляр критической частоты, order - порядок фильтра
    w = fc / (fs / 2)  # После перехода на другой тип фильтра не используется
    b, a = signal.ellip(fc / 5, 0.01, fs, 0.125)
    output = signal.filtfilt(b, a, array, method=method)
    return output
Example #16
0
def channel(x, fc, s, T):
    """
    Simule un canal de transmission en renvoyant le signal y = x*g + b en sortie du canal,
    où g est le réponse impulsionnelle d'un filtre passe-bas, b un bruit blanc gaussien et * représente la convolution.
    
    Entrées :
    x (array)   : signal émis
    fc (scalar) : fréquence de coupure du filtre g
    s (scalar)  : écart-type du bruit b
    T (scalar)  : durée d'un bit
    
    Sortie :
    y (array) : signal transmis via le canal
    """

    fe = 100 / T

    # Filtre passe-bas (seulement si canal non idéal)
    if fc < fe / 2:
        num, den = signal.ellip(8, 1, 80, fc * 2 / fe)
        x = signal.lfilter(num, den, x)

    # Bruit
    b = rnd.normal(0, s, x.shape)

    return x + b
def filt(data,
         cutoff,
         fs=1.,
         order=1,
         rp=10.,
         rs=10.,
         kind='butter',
         btype='low',
         ftype='filtfilt',
         axis=0,
         analog=False):
    """
    Apply a digital filter.
    :param data:
    :param cutoff:
    :param fs:
    :param order:
    :param rp:
    :param rs:
    :param kind:
    :param btype:
    :param ftype:
    :param axis:
    :param analog:
    :return:
    """
    nyquistFreqInRads = (2 * pi * fs) / 2
    crit = 2 * pi * cutoff / nyquistFreqInRads
    if kind == 'butter':
        b, a = signal.butter(order, crit, btype=btype, analog=analog)
    elif kind == 'bessel':
        b, a = signal.bessel(order, Wn=crit, btype=btype, analog=analog)
    elif kind == 'cheby1':
        b, a = signal.cheby1(order, rp=rp, Wn=crit, btype=btype, analog=analog)
    elif kind == 'cheby2':
        b, a = signal.cheby2(order, rs=rs, Wn=crit, btype=btype, analog=analog)
    elif kind == 'ellip':
        b, a = signal.ellip(order,
                            rp=rp,
                            rs=rs,
                            Wn=crit,
                            btype=btype,
                            analog=analog)
    else:
        raise ValueError('Invalid filter type specified: {}'.format(kind))

    if ftype == 'filtfilt':
        y = signal.filtfilt(b, a, data, axis=axis)
    elif ftype == 'lfilt':
        y = signal.lfilter(b, a, data, axis=axis)
    else:
        raise ValueError('Invalid filter type specified: {}'.format(btype))

    # If data is dataframe, restore the original column and index info
    if isinstance(data, pd.DataFrame):
        y = pd.DataFrame(y, index=data.index, columns=data.columns)
    elif isinstance(data, pd.Series):
        y = pd.Series(y, index=data.index, name=data.name)

    return y
Example #18
0
def compute_envelope(coch_sig, erbn_cf, fs):
    """Obtain signal envelope.

    Envelope computed using full-wave rectification and low-pass filter

    Args:
        coch_sig (ndarray): input signal
        erbn_cf (ndarray): ERB centre frequencies
        fs (int): sampling frequency

    Returns:
        ndarray: signal envelope

    """

    envelope = np.zeros(coch_sig.shape)
    n_chans = coch_sig.shape[0]
    for ixch in np.arange(0, n_chans):
        # Extract envelope; channel envelope lpf is NOT fixed for all channels,
        # tracks slightly above ERBn
        # Don't need to worry about phase since using bidirectional filters
        # Put limit on bandwidth for very high freq channels, (30/40) == -3dB at fc,
        fc_envlp = (30 / 40) * min(100, erbn_cf[ixch])

        # Reduced rate of cut(4-pole), but improved time response of filter.
        chan_lpfB, chan_lpfA = signal.ellip(2, 0.25, 35, fc_envlp / (fs / 2))

        # Full-wave rectify (take absolute values of raw signal coch_sig) and
        # low-pass to get envelope
        padlen = 3 * (max(len(chan_lpfA), len(chan_lpfB))) - 1
        envelope[ixch, :] = signal.filtfilt(chan_lpfB,
                                            chan_lpfA,
                                            np.abs(coch_sig[ixch, :]),
                                            padlen=padlen)
    return envelope
Example #19
0
File: Linx.py Project: Bruyant/Linx
    def data_hpass(self, x, Wp, srate):
        ''' High-pass filter '''
        Wp = float(Wp*2/srate)
        Ws = Wp*float(self.lineEdit_19.text())
        Rp = float(self.lineEdit_17.text())
        Rs = float(self.lineEdit_18.text())

        tempstring = self.lineEdit_16.text()
        if tempstring == 'auto':
            if self.comboBox_2.currentIndex() == 0:
                (norder, Wn) = buttord(Wp, Ws, Rp, Rs)
            elif self.comboBox_2.currentIndex() == 1:
                (norder, Wn) = ellipord(Wp, Ws, Rp, Rs)
            else:
                (norder, Wn) = cheb1ord(Wp, Ws, Rp, Rs)
        else:
            norder = float(tempstring)
            Wn = Wp

        if self.comboBox_2.currentIndex() == 0:
            (b, a)  =  butter(norder, Wn, btype = 'high')
        elif self.comboBox_2.currentIndex() == 1:
            (b, a)  =  ellip(norder, Rp, Rs, Wn)
        else:
            (b, a)  =  cheby1(norder, Rp, Wn)


        y  =  filtfilt(b, a, x)

        return(y)
Example #20
0
def filter(ephys,
           freq_range,
           filt_order=2,
           ripple=0.2,
           attenuation=40,
           filt_type='bandpass',
           fs=30e3):
    ## ephys = samples x trials or channels

    # notch:
    #notch = 60
    #notch_bw = 100 # notch filter q factor
    #notch_f = notch/(fs/2)
    #notch_q = notch_f/(notch_bw/(fs/2))
    # ??

    # design Elliptic filter:

    [b, a] = signal.ellip(filt_order,
                          ripple,
                          attenuation, [x / (fs / 2) for x in freq_range],
                          btype=filt_type)

    filtered_trace = signal.filtfilt(b, a, ephys, axis=0)
    return filtered_trace
Example #21
0
def ellip_filter(data_sig, ripple_p, ripple_s, cutoff):
    nyq = fs * 0.5
    cutoff_low = cutoff / nyq

    [b, a] = signal.ellip(7, ripple_p, ripple_s, cutoff_low, 'low')
    y = signal.lfilter(b, a, data_sig)
    return y
Example #22
0
def get_filter(spec, filter_type='but', method='zoh'):

    wp = 2*np.pi*spec['fp']
    ws = 2*np.pi*spec['fs']

    if method == 'bilinear':
        wp = 2/spec['dt'] * np.arctan(wp * spec['dt']/2)
        ws = 2/spec['dt'] * np.arctan(ws * spec['dt']/2)
    
    if filter_type.lower() in ('butterworth'):
        N, Wn = signal.buttord(wp, ws, spec['Amax'], spec['Amin'], analog=True)
        z, p, k = signal.butter(N, Wn, output='zpk', btype='low', analog=True)
    elif filter_type.lower() in ('cauer' + 'elliptic'):
        N, Wn = signal.ellipord(wp, ws, spec['Amax'], spec['Amin'], analog=True)
        z, p, k = signal.ellip(N, spec['Amax'], spec['Amin'], Wn, output='zpk', btype='low', analog=True)

    if method == 'matched':
        zd, pd, kd, dt = matched_method(z, p, k, spec['dt'])
        kd *= 1 - (1 - 10 ** (-spec['Amax']/20))/2
    else:
        zd, pd, kd, dt = signal.cont2discrete((z,p,k), spec['dt'], method=method)

    analog_system = (z,p,k)
    discrete_system = (zd,pd,kd)

    return analog_system, discrete_system
Example #23
0
def ellip_bp(atten, ripple, lo=0, hi=0, hp_width=0, lp_width=0, Fs=2.0):
    if hp_width == 0 and lo > 0:
        hp_width = 0.1 * (hi - lo)
        if lo - hp_width <= 0:
            # set hp_width to halfway between 0 and lo
            hp_width = 0.5 * lo
            print('bad HP stopband, adjusting to {0:.1f}'.format(hp_width))
    if lp_width == 0 and hi > 0:
        lp_width = 0.1 * (hi - lo)
        if hi + lp_width >= Fs / 2:
            # make lp_width to halfway between hi and Nyquist
            lp_width = 0.5 * (Fs / 2 - hi)
            print('bad LP stopband, adjusting to {0:.1f}'.format(lp_width))
    if lo > 0 and hi > 0:
        # bandpass design
        wp = np.array([lo, hi]) * 2 / Fs
        ws = np.array([lo - hp_width, hi + lp_width]) * 2 / Fs
        btype = 'bandpass'
    elif lo > 0:
        # highpass design
        wp = 2 * lo / Fs
        ws = 2 * (lo - hp_width) / Fs
        btype = 'highpass'
    elif hi > 0:
        # lowpass design
        wp = 2 * hi / Fs
        ws = 2 * (hi + lp_width) / Fs
        btype = 'lowpass'

    order, wn = signal.ellipord(wp, ws, ripple, atten)
    return signal.ellip(order, ripple, atten, wn, btype=btype)
Example #24
0
 def _sos(self, sfreq):
     nyq = sfreq / 2.
     low_stop, low_pass, high_pass, high_stop, gpass, gstop = self.args
     order, wn = signal.ellipord((low_pass / nyq, high_pass / nyq),
                                 (low_stop / nyq, high_stop / nyq), gpass,
                                 gstop)
     return signal.ellip(order, gpass, gstop, wn, 'bandpass', output='sos')
Example #25
0
 def LPmin(self, fil_dict):
     """Elliptic LP filter, minimum order"""
     self.get_params(fil_dict)
     self.N, self.F_PBC = ellipord(self.F_PB,self.F_SB, self.A_PB,self.A_SB,
                                                       analog = self.analog)
     self.save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                         btype='low', analog = self.analog, output = frmt))
Example #26
0
    def __init__(self, n, rp, rs, Wn, etype='low', name='Elliptic'):
        """
		Create an elliptic filter
		Use the same argument as scipy.signal elliptic filter

		n: (int)The order of the filter.
		rp: (float) The maximum ripple allowed below unity gain in the passband. Specified in decibels, as a positive number.
		rs: (float) The minimum attenuation required in the stop band. Specified in decibels, as a positive number.
		Wn : (array_like) A scalar or length-2 sequence giving the critical frequencies. For elliptic filters, this is the point in the transition band at which the gain first drops below -rp. For digital filters, Wn is normalized from 0 to 1, where 1 is the Nyquist frequency, pi radians/sample. (Wn is thus in half-cycles / sample.) For analog filters, Wn is an angular frequency (e.g. rad/s).

		btype: (string) {‘lowpass’, ‘highpass’, ‘bandpass’, ‘bandstop’}: the type of filter. Default is ‘lowpass’.

		see `https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.signal.ellip.html`

		Returns a Elliptic object (Filter)
		"""

        self.n = n
        self.rp = rp
        self.rs = rs
        self.Wn = Wn
        self.etype = etype

        # call the parent class constructor
        num, den = ellip(n, rp, rs, Wn, etype)
        super(Elliptic, self).__init__(num=num,
                                       den=den,
                                       stable=True,
                                       name=name)
Example #27
0
def bandstop(lowcut, highcut, fs, order=5, ftype='butter', analog=False):
    nyq = 0.5 * fs
    if analog == True:
        wsL = lowcut
        wsH = highcut
    else:
        wsL = lowcut / nyq
        wsH = highcut / nyq
    if ftype == 'butter':
        b, a = signal.butter(order, [wsL, wsH],
                             btype='bandstop',
                             analog=analog)
    elif ftype == 'cheby1':
        b, a = signal.cheby1(order,
                             20, [wsL, wsH],
                             btype='bandstop',
                             analog=analog)
    elif ftype == 'cheby2':
        b, a = signal.cheby2(order,
                             20, [wsL, wsH],
                             btype='bandstop',
                             analog=analog)
    elif ftype == 'ellip':
        b, a = signal.ellip(order,
                            .01,
                            20, [wsL, wsH],
                            btype='bandstop',
                            analog=analog)
    return b, a
Example #28
0
    def _get_filter_coeffs(self, output='sos', analog=False):
        from scipy import signal

        # Compute the filter params
        N, Wn = signal.ellipord(
            wp=self._f_pass,
            ws=self._f_stop,
            gpass=self._max_suppression_pass,
            gstop=self._min_suppression_stop,
            analog=False,
            fs=self._f_sample
        )
        if analog:
            fs = None
        else:
            fs = self._f_sample

        coeffs = signal.ellip(
            N,
            rp=self._max_suppression_pass,
            rs=self._min_suppression_stop,
            Wn=Wn,
            btype=self._kind,
            analog=analog,
            output=output,
            fs=fs
        )

        return coeffs
    def _sos(self, sfreq):
        nyq = sfreq / 2.
        low_stop, low_pass, high_pass, high_stop, gpass, gstop = self.args
        if high_stop is None:
            assert low_stop is not None
            assert high_pass is None
        else:
            high_stop /= nyq
            high_pass /= nyq

        if low_stop is None:
            assert low_pass is None
        else:
            low_pass /= nyq
            low_stop /= nyq

        if low_stop is None:
            btype = 'lowpass'
            wp, ws = high_pass, high_stop
        elif high_stop is None:
            btype = 'highpass'
            wp, ws = low_pass, low_stop
        else:
            btype = 'bandpass'
            wp, ws = (low_pass, high_pass), (low_stop, high_stop)
        order, wn = signal.ellipord(wp, ws, gpass, gstop)
        return signal.ellip(order, gpass, gstop, wn, btype, output='sos')
Example #30
0
 def HPman(self, fil_dict):
     """Elliptic HP filter, manual order"""
     self._get_params(fil_dict)
     if not self._test_N():
         return -1  
     self._save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PB,
                     btype='highpass', analog=self.analog, output=self.FRMT))
Example #31
0
def main():
    """Meant to emulate how pyfda will pass parameters to filters"""

    # fs = 1000.
    # f1 = 45.
    # f2 = 95.
    # b = signal.firwin(3,[f1/fs*2,f2/fs*2])    #3 taps
    #b, a = signal.iirfilter(3, [0.4, 0.7], rs=60, btype='band', ftype='cheby2')
    # print(len(b))
    # print(len(a))
    # print(b)
    # print(a)

    #print(max([max(b),max(a)]))
    #convert floating point to fixed point

    sos = signal.ellip(3, 0.009, 80, 0.05, output='sos')
    x = signal.unit_impulse(10)
    y_sos = signal.sosfilt(sos, x)
    print(sos)

    #print(y_sos)

    B1 = 12  # Number of bits
    L1 = 2**(B1 - 1)  # Round towards zero to avoid overflow

    sos_sc = sos * (2**(B1 - 1))
    sos_sc_int = sos_sc.astype(int)

    print(sos_sc_int)

    y1 = fixp_sine(sos_sc_int, B1, L1)
    # #print(y1/2**B1)
    y2 = floatp_sine(sos, B1, L1)
Example #32
0
def bandpass_filter(data,
                    lowcut,
                    highcut,
                    sample_rate,
                    order,
                    filter='butter'):
    '''
    Returns bandpass filtered data between the frequency ranges specified in the input.

    Args:
        data (numpy.ndarray): array of samples.
        lowcut (float): lower cutoff frequency (Hz).
        highcut (float): lower cutoff frequency (Hz).
        sample_rate (float): sampling rate (Hz).
        order (int): order of the bandpass filter.

    Returns:
        (numpy.ndarray): bandpass filtered data.
    '''

    nyq = 0.5 * sample_rate
    low = lowcut / nyq
    high = highcut / nyq

    if filter == 'chebyshe':
        b, a = cheby1(order, 0.3, [low, high], btype='band')
    elif filter == 'elliptic':
        b, a = ellip(order, 0.3, 1, [low, high], btype='band')
    else:
        b, a = butter(order, [low, high], btype='band')

    y = filtfilt(b, a, data)
    return y
Example #33
0
def testOsc(Osc, oversample: int):
    print(f"Processing: {oversample}x {Osc.__name__}")

    gain = 0.25
    samplerate = 48000
    lowpass = signal.ellip(12,
                           0.01,
                           100,
                           0.4,
                           "low",
                           output="sos",
                           fs=oversample)
    # plotSos(lowpass)

    osc = Osc(samplerate, oversample)

    sig = np.empty(8 * oversample * samplerate)
    switched = np.empty_like(sig)  # debug

    note = np.linspace(0, 128, len(sig) // 2)
    note = np.hstack((note, np.flip(note)))
    for i in range(len(sig)):
        sig[i], switched[i] = osc.process(note[i])
    sig = gain * signal.sosfilt(lowpass, sig)[::oversample]
    switched = signal.sosfilt(lowpass, switched)[::oversample]  # debug

    Path("snd").mkdir(parents=True, exist_ok=True)

    name = f"{Osc.__name__}_x{oversample}_switch"
    soundfile.write(f"snd/{name}.wav", sig, samplerate, subtype="FLOAT")

    plotSpectrogram(sig, switched, samplerate, name)  # debug

    gc.collect()  # Maybe goes out of memory with 32bit CPython.
Example #34
0
 def HPman(self, fil_dict):
     """Elliptic HP filter, manual order"""
     self._get_params(fil_dict)
     if not self._test_N():
         return -1
     self._save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PB,
                     btype='highpass', analog=self.analog, output=self.FRMT))
Example #35
0
    def _sos(self, sfreq):
        nyq = sfreq / 2.
        low_stop, low_pass, high_pass, high_stop, gpass, gstop = self.args
        if high_stop is None:
            assert low_stop is not None
            assert high_pass is None
        else:
            high_stop /= nyq
            high_pass /= nyq

        if low_stop is None:
            assert low_pass is None
        else:
            low_pass /= nyq
            low_stop /= nyq

        if low_stop is None:
            btype = 'lowpass'
            wp, ws = high_pass, high_stop
        elif high_stop is None:
            btype = 'highpass'
            wp, ws = low_pass, low_stop
        else:
            btype = 'bandpass'
            wp, ws = (low_pass, high_pass), (low_stop, high_stop)
        order, wn = signal.ellipord(wp, ws, gpass, gstop)
        return signal.ellip(order, gpass, gstop, wn, btype, output='sos')
Example #36
0
 def design_filter(self, fs):
     if np.isinf(self.LPFcutoff):
         N, Ws = ellipord(self.HPFcutoff * 1e3 / fs * 2,
                          max(5 * 1e3 / fs * 2,
                              (self.HPFcutoff - 5) * 1e3 / fs * 2),
                          self.Rp,
                          self.Rs)
         b, a = ellip(N, self.Rp, self.Rs, Ws, 'high')
     else:
         N, Ws = ellipord([self.HPFcutoff * 1e3 / fs * 2, self.LPFcutoff * 1e3 / fs * 2],
                          [max(5*1e3/fs*2,(self.HPFcutoff-5)*1e3/fs*2),
                           min((fs/2-5e3)/fs*2,(self.LPFcutoff+5)*1e3/fs*2)],
                          self.Rp,
                          self.Rs)
         b, a = ellip(N, self.Rp, self.Rs, Ws)
     return b, a
Example #37
0
def lowpass(sig, cutoff, filter_=('cheby1', 8), sr=44100):
    """Lowpasses input signal based on a cutoff frequency
    
    Arguments:
        sig {numpy 1d array} -- input signal
        cutoff {int} -- cutoff frequency
    
    Keyword Arguments:
        sr {int} -- sampling rate of the input signal (default: {44100})
        filter_type {str} -- type of filter, only butter and cheby1 are implemented (default: {'butter'})
    
    Returns:
        numpy 1d array -- lowpassed signal
    """
    nyq = sr / 2
    cutoff /= nyq

    if filter_[0] == 'butter':
        B, A = signal.butter(filter_[1], cutoff)
    elif filter_[0] == 'cheby1':
        B, A = signal.cheby1(filter_[1], 0.05, cutoff)
    elif filter_[0] == 'bessel':
        B, A = signal.bessel(filter_[1], cutoff, norm='mag')
    elif filter_[0] == 'ellip':
        B, A = signal.ellip(filter_[1], 0.05, 20, cutoff)

    sig_lp = signal.filtfilt(B, A, sig)
    return sig_lp.astype(np.float32)
Example #38
0
        def test_sosfilt_gpu(
            self,
            rand_2d_data_gen,
            gpubenchmark,
            num_signals,
            num_samps,
            order,
            dtype,
        ):

            cpu_sos = signal.ellip(order, 0.009, 80, 0.05, output="sos")
            cpu_sos = np.array(cpu_sos, dtype=dtype)
            gpu_sos = cp.asarray(cpu_sos)
            cpu_sig = np.random.rand(num_signals, num_samps)
            cpu_sig = np.array(cpu_sig, dtype=dtype)
            gpu_sig = cp.asarray(cpu_sig)

            output = gpubenchmark(
                self.gpu_version,
                gpu_sos,
                gpu_sig,
            )

            key = self.cpu_version(cpu_sos, cpu_sig)
            assert array_equal(cp.asnumpy(output), key)
Example #39
0
    def draw_cpu_image(self, data_path, fitting):
        """
        cpu图像
        """
        # 清除原图像
        self.cpu_subplot.cla()
        # 设置cpu坐标轴属性
        self.cpu_subplot.set_title("CPU INFO")
        self.cpu_subplot.set_xlabel("Time")
        self.cpu_subplot.set_ylabel("Use Rate")
        self.cpu_subplot.grid()

        data_dict = self.load_data(data_path)

        # 从数据中获取cpu个数
        cpu_count = 0
        for i in data_dict.keys():
            if (str(i).startswith("cpu")):
                cpu_count += 1

        mean_cpu = 0
        max_cpu = 0
        min_cpu = 100

        for i in range(cpu_count):
            x_list = ast.literal_eval(data_dict["cpu-" + str(i)][0])
            # for debug
            # x_list = [item * self.interval for item in x_list]

            y_list = ast.literal_eval(data_dict["cpu-" + str(i)][1])

            # min, max, mean
            mean_cpu += np.mean(y_list)
            if (max(y_list) > max_cpu):
                max_cpu = max(y_list)
            if (min(y_list) < min_cpu):
                min_cpu = min(y_list)
            # if fitting:
            #     # 对cpu的数据进行3次多项式拟合,去掉其中不合理的峰值
            #     x_list_new, y_list_new = self.data_fitting(x_list, y_list)
            # else:
            #     # 不拟合
            #     x_list_new = x_list
            #     y_list_new = y_list

            # 创建fillter
            b, a = signal.ellip(4, 0.01, 120, 0.125)
            fgust = signal.filtfilt(b, a, y_list, method="gust")
            self.cpu_subplot.plot(x_list, fgust, label='cpu-' + str(i))
        self.logger.info("min cpu = {}%".format(min_cpu))
        self.logger.info("max cpu = {}%".format(max_cpu))
        self.logger.info("total mean cpu = {}%".format(mean_cpu / cpu_count))
        # 坐标自动调整
        self.cpu_subplot.set_xlim(0, x_list[len(x_list) - 1])
        # 设置成110,当cpu为100% 的时候显示好看点
        self.cpu_subplot.set_ylim(0, 110)
        # 设置图例位置,loc可以为[upper, lower, left, right, center]
        # self.cpu_subplot.legend(loc='right', shadow=True) # 去掉, 因为当cpu为64个的时候, 长度超过图表限制了
        self.logger.info("finished draw cpu image")
Example #40
0
 def BSman(self, fil_dict):
     """Elliptic BS filter, manual order"""
     self._get_params(fil_dict)
     if not self._test_N():
         return -1
     self._save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, 
         [self.F_PB,self.F_PB2], btype='bandstop', analog=self.analog, 
                                                             output=self.FRMT))
Example #41
0
    def demodulate(self, waves, plot=False):
        [b11, a11] = signal.ellip(5,
                                  0.5,
                                  60, [2000 * 2 / 80000, 6000 * 2 / 80000],
                                  btype='bandpass',
                                  analog=False,
                                  output='ba')
        [b12, a12] = signal.ellip(5,
                                  0.5,
                                  60, (2000 * 2 / 80000),
                                  btype='lowpass',
                                  analog=False,
                                  output='ba')
        output = []

        for ind, wave in enumerate(waves):
            bandpass_out = signal.filtfilt(b11, a11, wave)
            coherent_demod = bandpass_out * (self.carrier * 2)
            lowpass_out = signal.filtfilt(b12, a12, coherent_demod)
            if plot:
                subplots_adjust(left=0.125,
                                right=0.9,
                                bottom=0.1,
                                top=0.9,
                                wspace=0.2,
                                hspace=1)
                plt.subplot(len(waves), 1, ind + 1)
                plt.plot(lowpass_out)
                plt.title("after applying low pass filter {}/{}".format(
                    ind + 1, len(waves)))

            # detection_bpsk = np.zeros(len(self.t), dtype=np.float32)
            flag = [0 for i in range(self.tot_bits)]

            for i in range(self.tot_bits):
                tempF = 0
                for j in range(self.bit_length):
                    tempF = tempF + lowpass_out[i * self.bit_length + j]
                    if tempF > 0:
                        flag[i] = 1
                    else:
                        flag[i] = 0
            output.append(flag)
        if plot:
            plt.show()
        return output
Example #42
0
    def __init__(self, type, fc, gain = 0, Q = 1, enabled = True):
        self._enabled = enabled
        self._type = type
        self._fc = fc
        self._g = gain
        self._Q = Q

        if type == FilterType.HPBrickwall:
            z, p, k = scsig.ellip(12, 0.01, 80, fc, 'high', output='zpk')
            self._sos = zpk2sos(z, p, k)[0]
        elif type == FilterType.LPBrickwall:
            z, p, k = scsig.ellip(12, 0.01, 80, fc, 'low', output='zpk')
            self._sos = zpk2sos(z, p, k)[0]
        elif type == FilterType.HPButter:
            z, p, k = scsig.butter(2 ** Q, fc, btype = 'high', output='zpk')
            self._sos = zpk2sos(z, p, k)[0]
        elif type == FilterType.LPButter:
            z, p, k = scsig.butter(2 ** Q, fc, output='zpk')
            self._sos = zpk2sos(z, p, k)[0]
        elif type == FilterType.LShelving or type == FilterType.HShelving:
            A = 10 ** (gain / 20)
            wc = np.pi * fc
            wS = np.sin(wc)
            wC = np.cos(wc)
            alpha = wS / (2 * Q)
            beta = A ** 0.5 / Q
            c = 1
            if type == FilterType.LShelving:
                c = -1

            b0 = A * (A + 1 + c * (A - 1) * wC + beta * wS)
            b1 = - c * 2 * A * (A - 1 + c * (A + 1) * wC)
            b2 = A * (A + 1 + c * (A - 1) * wC - beta * wS)
            a0 = (A + 1 - c * (A - 1) * wC + beta * wS)
            a1 = c * 2 * (A - 1 - c * (A + 1) * wC)
            a2 = (A + 1 - c * (A - 1) * wC - beta * wS)
            self._sos = np.array([[ b0, b1, b2, a0, a1, a2 ]])
        elif type == FilterType.Peak:
            self.g = gain
            wc = np.pi * fc
            b, a = scsig.bilinear([1, 10 ** (gain / 20) * wc / Q, wc ** 2],
                [1, wc / Q, wc ** 2])
            self._sos = np.append(b, a).reshape(1, 6)

        self._ord = self._sos.shape[0] * 2
        self.icReset()
Example #43
0
 def BPmin(self, fil_dict):
     """Elliptic BP filter, minimum order"""
     self._get_params(fil_dict)
     self.N, self.F_PBC = ellipord([self.F_PB, self.F_PB2],
         [self.F_SB, self.F_SB2], self.A_PB, self.A_SB, analog=self.analog)
     if not self._test_N():
         return -1
     self._save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                     btype='bandpass', analog=self.analog, output=self.FRMT))
Example #44
0
    def HPmin(self, fil_dict):
        """Elliptic HP filter, minimum order"""
        self._get_params(fil_dict)
        self.N, self.F_PBC = ellipord(self.F_PB,self.F_SB, self.A_PB,self.A_SB,
                                                          analog=self.analog)
#       force even N
        if (self.N%2)== 1:
            self.N += 1
        self._save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                        btype='highpass', analog=self.analog, output=self.FRMT))
Example #45
0
    def _design(self):
        if not self.stopband_attenuation:
            self.stopband_attenuation = self.filter_parameters['stopband_attenuation']

        if not self.ripple:
            self.ripple = self.filter_parameters['ripple']

        if self.already_normalized_Wn:
            self.Z, self.P, self.K = signal.ellip(self.N, self.ripple,
                                                  self.stopband_attenuation,
                                                  self.Wn,
                                                  self.filter_kind,
                                                  analog=False, output='zpk')
        else:
            self.Z, self.P, self.K = signal.ellip(self.N, self.ripple,
                                                  self.stopband_attenuation,
                                                  self.normalize_Wn(),
                                                  self.filter_kind, analog=False,
                                                  output='zpk')
Example #46
0
 def BPmin(self, fil_dict):
     """Elliptic BP filter, minimum order"""
     self._get_params(fil_dict)
     self.N, self.F_PBC = ellipord([self.F_PB, self.F_PB2],
         [self.F_SB, self.F_SB2], self.A_PB, self.A_SB, analog=self.analog)
     #logger.warning(" "+str(self.F_PBC) + " " + str(self.N))
     if (self.N%2)== 1:
         self.N += 1
     #logger.warning("-"+str(self.F_PBC) + " " + str(self.A_SB))
     self._save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                     btype='bandpass', analog=self.analog, output=self.FRMT))
Example #47
0
    def LPmin(self, fil_dict):
        """Elliptic LP filter, minimum order"""
        self._get_params(fil_dict)
        self.N, self.F_PBC = ellipord(self.F_PB,self.F_SB, self.A_PB,self.A_SB,
                                                          analog=self.analog)
#       force even N
        if (self.N%2)== 1:
            self.N += 1
        #logger.warning("and "+str(self.F_PBC) + " " + str(self.N))
        self._save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                            btype='low', analog=self.analog, output=self.FRMT))
Example #48
0
def _get_elliptic_filter(passband, fs, order = 5, rp = 1, rs = 15):
    """
    Return an n-th order elliptic passband filter (default 5th)
    The resulting passband filter will be of order 2 * order
    Frequencies will be normalized with Fs / 2
    By default, the remaining parameters assume following values:
    rp = 1 (maximum passband ripple allowed in db)
    rs = 15 (minimum stopband attenuation required in db)
    """
    band = passband[2:4] / (fs / 2)
    return ellip(N = order, rp = rp, rs = rs, Wn = band, btype='pass')
Example #49
0
    def BSmin(self, fil_dict):
        """Elliptic BP filter, minimum order"""
        self._get_params(fil_dict)
        self.N, self.F_PBC = ellipord([self.F_PB, self.F_PB2],
                                [self.F_SB, self.F_SB2], self.A_PB,self.A_SB,
                                                        analog=self.analog)
#       force even N
        if (self.N%2)== 1:
            self.N += 1
        self._save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PBC,
                        btype='bandstop', analog=self.analog, output=self.FRMT))
Example #50
0
def elliptical_filter(): #Design an elliptical filter with some predefined parameters

	N = 8 #order
	rp = 1 #max ripple below unity in passband [dB]
	rs = 10 #max attenuation in the stop band [dB]

	wn = 0.5 #frequency in the transition band when gain drops below rp (for ellip)
	type = 'low' #filter type

	b, a = signal.ellip(N,rp,rs,wn,'low',analog=False)
	w, h = signal.freqs(b, a)
	return (b,a,w,h)
Example #51
0
File: Linx.py Project: Bruyant/Linx
    def data_lpass(self, x, Wp, srate):
        ''' Low-pass filter using various filter type '''
        tempstring = self.lineEdit_16.text()
        
        if tempstring == 'auto':
            Wp = float(Wp*2/srate)
            Ws = Wp*float(self.lineEdit_19.text())
            Rp = float(self.lineEdit_17.text())
            Rs = float(self.lineEdit_18.text())
            
            if self.comboBox_2.currentIndex() == 0:
                (norder, Wn) = buttord(Wp, Ws, Rp, Rs)
            elif self.comboBox_2.currentIndex() == 1:
                (norder, Wn) = ellipord(Wp, Ws, Rp, Rs)
            else:
                (norder, Wn) = cheb1ord(Wp, Ws, Rp, Rs)

        else:
            norder = float(tempstring)
            Wp = float(Wp*2/srate)
            Ws = Wp*2
            self.lineEdit_19.setText(str(Ws/Wp))
            Rp = 3
            self.lineEdit_17.setText(str(Rp))
            Rs = 0.3*norder*20
            self.lineEdit_18.setText(str(Rs))
            
            if self.comboBox_2.currentIndex() == 0:
                (norder, Wn) = buttord(Wp, Ws, Rp, Rs)
            elif self.comboBox_2.currentIndex() == 1:
                (norder, Wn) = ellipord(Wp, Ws, Rp, Rs)
            else:
                (norder, Wn) = cheb1ord(Wp, Ws, Rp, Rs)
            
        if self.comboBox_2.currentIndex() == 0:
            (b, a)  =  butter(norder, Wn)
        elif self.comboBox_2.currentIndex() == 1:
            (b, a)  =  ellip(norder, Rp, Rs, Wn)
        else:
            (b, a)  =  cheby1(norder, Rp, Wn)
            
        
        y  =  filtfilt(b, a, x)
        
        return(y)
Example #52
0
def iir_basic(a):
  
        filt_type = a["Response Type"]
        
        print('filt_type', filt_type)
        design_method = a["Design_Methode"]
        if design_method == 'Elliptic':
            ftype = 'ellip'
        elif design_method == 'Chebychev 1':
            ftype = 'cheby1'
        elif design_method == 'Chebychev 2':
            ftype = 'cheby2'
        elif design_method == 'Butterworth':
            ftype = 'butter'
#        else: raise_exception
            
        print('design_method', design_method)
        N = a['Order']
        print('order',N)
        fs = a["Fs"]
        F_pass = 2 * a["Fpass"]/fs
#        F_stop = 2 * a[3][2][2]/fs
        F_stop = 0.8
        print('fs','fpass','fstop',fs, F_pass, F_stop)
        A_pass = a["Apass"]
        A_stop = a["Astop"]
#        A_stop = a[4][2][2]
        print('A_pass', 'A_stop', A_pass, A_stop)
#        W = a[5]
#        print('W',W)
        
        if N == 'min':
            b,a = sig.iirdesign(F_pass, F_stop, A_pass, A_stop, analog = False, 
                                ftype = ftype, output = 'ba')            
        else:
            if ftype == 'ellip':
                b,a = sig.ellip(N, A_pass, A_stop, [F_pass, F_stop], btype ='low' )
            elif ftype == 'cheby1':
                b,a = sig.cheby1(N, A_pass, [F_pass, F_stop], btype ='low' )
            elif ftype == 'cheby2':
                b,a = sig.cheby2(N, A_stop, [F_pass, F_stop], btype ='low' )
            elif ftype == 'butter':
                b,a = sig.butter(N, (2 * a["Fc"]/fs), btype ='low' )
        return b, a
Example #53
0
File: plot.py Project: mrow4a/UNI
def elliptic_bandpass(low, high, fs, order):
    nyq = 0.5 * fs
    n_low = low / nyq
    n_high = high / nyq
    b, a = signal.ellip(order,0.2,80, [n_low, n_high], btype='band', analog=False)
    fig2 = plt.figure()
    plt.title('Digital filter frequency response')
    ax1 = fig2.add_subplot(211)
    w, h = signal.freqz(b,a)
    plt.plot(w/(math.pi*2)*fs, abs(h), 'b')
    plt.ylabel('Amplitude', color='b')
    plt.xlabel('Frequency [freq/sample]')
    ax2 = ax1.twinx()
    angles = np.unwrap(np.angle(h))
    plt.plot(w/(math.pi*2)*fs, angles, 'g')
    plt.ylabel('Angle (radians)', color='g')
    plt.grid()
    plt.axis('tight')
    plt.show()
    return b, a
Example #54
0
def demo_data(num_symbols, samples_per_symbol):
    """
    Generate some data for demonstrations.

    `num_symbols` is the number of symbols (i.e. bits) to include
    in the data stream.

    `samples_per_symbol` is the number of samples per symbol.
    (For interesting demonstrations, this number should be at least 20.)

    The total length of the result is `num_symbols` * `samples_per_symbol`.

    Example
    -------
    Import matplotlib and demo_data:

    >>> import matplotlib.pyplot as plt
    >>> from eyediagram.demo_data import demo_data

    Generate and plot some data:

    >>> y = demo_data(16, 25)
    >>> plt.plot(y)

    """
    # A random stream of "symbols" (i.e. bits)
    bits = np.random.randint(0, 2, size=num_symbols)

    # Upsample the bit stream.
    sig = np.repeat(bits, samples_per_symbol)

    # Convert the edges of the symbols to ramps.
    r = min(5, samples_per_symbol // 2)
    sig = np.convolve(sig, [1./r]*r, mode='same')

    # Add some noise and pass the signal through a lowpass filter.
    b, a = ellip(4, 0.087, 30, 0.15)
    y = lfilter(b, a, sig + 0.075*np.random.randn(len(sig)))

    return y
Example #55
0
 def design(self, ripple=None):
     if self.filter_class == 'butterworth':
         self.B, self.A = signal.butter(self.N, self.Wn,
                                        self.filter_type, analog=True,
                                        output='ba')
     elif self.filter_class == 'chebyshev_1':
         if ripple is None or ripple <= 0:
             raise ValueError("Must give a ripple that is > 0")
         self.B, self.A = signal.cheby1(self.N, ripple, self.Wn,
                                        self.filter_type, analog=True,
                                        output='ba')
     elif self.filter_class == 'chebyshev_2':
         self.B, self.A = signal.cheby2(self.N, self.stopband_attenuation, self.Wn,
                                        self.filter_type, analog=True, output='ba')
     elif self.filter_class == 'elliptical':
         self.B, self.A = signal.ellip(self.N, self.passband_attenuation,
                                       self.stopband_attenuation, self.Wn,
                                       self.filter_type, analog=True, output='ba')
     elif self.filter_class == 'bessel':
         self.B, self.A = signal.bessel(self.N, self.Wn, self.filter_type, analog=True)
     else:
         raise NotImplementedError("Computation of {} not implemented yet.".format(self.filter_class))
Example #56
0
def demo_ASK(num_symbols, samples_per_symbol, ask_order=2, rc=True, bandlimit=True, noise=0.0):
    bits = np.float16(np.random.randint(0, ask_order, size=num_symbols))/(ask_order-1)
    sig = np.repeat(bits, samples_per_symbol)
    if rc:
        # raised-cosine filter also known as Hann window (not to be confused with Hanning window!)
        win = hann(samples_per_symbol)
        sig = np.convolve(sig, win/np.sum(win), mode='same')
    # Add noise
    sig += noise*np.random.randn(len(sig))
    if bandlimit:
        # limit bandwidth to Nyquist bandwidth f_cutoff = f_sample/2
        f_cutoff = 2.0/np.float16(samples_per_symbol)
        print f_cutoff
        # we'll use a 4th order Cauer bandpass filter (realistic!)
        (b, a) = ellip(4, 0.05, 40, f_cutoff, 'low') # , analog=True)
        if False:
            (w, h) = freqs(b, a)
            print min(w), min(abs(h))
            plt.plot(w, 20*np.log10(abs(h)))
            plt.show()
        sig = lfilter(b, a, sig)
    
    return sig
Example #57
0
#!/usr/bin/python3

# Calculates the coefficients for an elliptic filter

from scipy import signal
# sampling rate
fs = 1000
# cutoff
f0 = 100
# order
order = 4
# passband ripple
pr = 5
# minimum stopband rejection
sr = 40
sos = signal.ellip(order, pr, sr, f0/fs*2, 'low', output='sos')
for s in sos:
    print("{",end="")
    n = 0
    for c in s:
        print("%.18e" % c,end="")
        n=n+1
        if n<6:
            print(",",end="")
    print("},")
Example #58
0
 def BSman(self, fil_dict):
     """Elliptic BS filter, manual order"""
     self.get_params(fil_dict)
     self.save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, 
         [self.F_PB,self.F_PB2], btype='bandstop', analog = self.analog, 
                                                             output = frmt))
#    bb = [1,0,1,0]
#    bb = [1, -3, 3, -1]
    # Optional: Cascade filter twice by convolving coefficients with themselves
#    bb = np.convolve(bb,bb)
    #bb = [1,2,3,2,1]
#    bb = sig.remez(16, [0, 1/8, 1/4, 0.5],[1,0],[6,1])

    aa = zeros(len(bb)-1)
    aa = np.append(1.,aa) # create same number of poles at origin (FIR)

else: # FILT = 'IIR'
    
    bb, aa = ([1, 1],[1, -1.5, 0.9])
#    bb, aa =[1], [1,0,0.64]
#    bb, aa = [1], [1, -1]
    bb, aa = sig.ellip(4, 0.1, 40, 0.2)
    
    #bb, aa = ([1,0,0,0,-1],[-1,1])
    bb, aa = (0.25*np.convolve([1,0,2,0,1], [1,1]),[1, 0,1])


##############################################################################

[w, H] = sig.freqz(bb, aa, N_FFT, whole) # calculate H(w) along the 
                                        # upper half of unity circle
                                        # w runs from 0 ... pi, length = N_FFT
f = w / (2 * pi) * f_S                  # translate w to absolute frequencies

H_abs = abs(H)
H_max = max(H_abs); H_max_dB = 20*log10(H_max); F_max = f[np.argmax(H_abs)]
Example #60
0
 def HPman(self, fil_dict):
     """Elliptic HP filter, manual order"""
     self.get_params(fil_dict)
     self.save(fil_dict, sig.ellip(self.N, self.A_PB, self.A_SB, self.F_PB,
                     btype='highpass', analog = self.analog, output = frmt))