Python scipy.signal.butter() Examples
The following are 30
code examples of scipy.signal.butter().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
scipy.signal
, or try the search function
.
Example #1
Source File: filters.py From pydiogment with BSD 3-Clause "New" or "Revised" License | 7 votes |
def butter_bandpass(low_cut, high_cut, fs, order=5): """ Design band pass filter. Args: - low_cut (float) : the low cutoff frequency of the filter. - high_cut (float) : the high cutoff frequency of the filter. - fs (float) : the sampling rate. - order (int) : order of the filter, by default defined to 5. """ # calculate the Nyquist frequency nyq = 0.5 * fs # design filter low = low_cut / nyq high = high_cut / nyq b, a = butter(order, [low, high], btype='band') # returns the filter coefficients: numerator and denominator return b, a
Example #2
Source File: audio.py From signaltrain with GNU General Public License v3.0 | 6 votes |
def compressor(x, thresh=-24, ratio=2, attackrel=0.045, sr=44100.0, dtype=np.float32): """ simple compressor effect, code thanks to Eric Tarr @hackaudio Inputs: x: the input waveform thresh: threshold in dB ratio: compression ratio attackrel: attack & release time in seconds sr: sample rate """ attack = attackrel * sr # convert to samples fc = 1.0/float(attack) # this is like 1/attack time b, a = scipy_signal.butter(1, fc, analog=False, output='ba') zi = scipy_signal.lfilter_zi(b, a) dB = 20. * np.log10(np.abs(x) + 1e-6) in_env, _ = scipy_signal.lfilter(b, a, dB, zi=zi*dB[0]) # input envelope calculation out_env = np.copy(in_env) # output envelope i = np.where(in_env > thresh) # compress where input env exceeds thresh out_env[i] = thresh + (in_env[i]-thresh)/ratio gain = np.power(10.0,(out_env-in_env)/20) y = x * gain return y
Example #3
Source File: test_signaltools.py From GraphicDesignPatternByPython with MIT License | 6 votes |
def test_zi_pseudobroadcast(self): x = self.generate((4, 5, 20)) b,a = signal.butter(8, 0.2, output='ba') b = self.convert_dtype(b) a = self.convert_dtype(a) zi_size = b.shape[0] - 1 # lfilter requires x.ndim == zi.ndim exactly. However, zi can have # length 1 dimensions. zi_full = self.convert_dtype(np.ones((4, 5, zi_size))) zi_sing = self.convert_dtype(np.ones((1, 1, zi_size))) y_full, zf_full = lfilter(b, a, x, zi=zi_full) y_sing, zf_sing = lfilter(b, a, x, zi=zi_sing) assert_array_almost_equal(y_sing, y_full) assert_array_almost_equal(zf_full, zf_sing) # lfilter does not prepend ones assert_raises(ValueError, lfilter, b, a, x, -1, np.ones(zi_size))
Example #4
Source File: grasp.py From kaggle_grasp_and_lift_eeg_detection with BSD 2-Clause "Simplified" License | 6 votes |
def butter_highpass(highcut, fs, order): nyq = 0.5 * fs high = highcut / nyq b, a = butter(order, high, btype="highpass") return b, a # Sources for Batch Iterators # # These classes load training and test data and perform some basic preprocessing on it. # They are then passed to factory functions that create the net. There they are used # as data sources for the batch iterators that feed data to the net. # All classes band pass or low pass filter their data based on min / max freq using # a causal filter (lfilter) when the data is first loaded. # * TrainSource loads a several series of EEG data and events, splices them together into # one long stream, then normalizes the EEG data to zero mean and unit standard deviation. # * TestSource is like TrainSource except that it uses the mean and standard deviation # computed for the associated training source to normalize the EEG data. # * SubmitSource is like TestSource except that it does not load and event data.
Example #5
Source File: filtering.py From heartrate_analysis_python with GNU General Public License v3.0 | 6 votes |
def butter_bandpass(lowcut, highcut, sample_rate, order=2): '''standard bandpass filter. Function that defines standard Butterworth bandpass filter. Filters out frequencies outside the frequency range defined by [lowcut, highcut]. Parameters ---------- lowcut : int or float Lower frequency bound of the filter in Hz highcut : int or float Upper frequency bound of the filter in Hz sample_rate : int or float sample rate of the supplied signal order : int filter order, defines the strength of the roll-off around the cutoff frequency. Typically orders above 6 are not used frequently. default : 2 Returns ------- out : tuple numerator and denominator (b, a) polynomials of the defined Butterworth IIR filter. Examples -------- we can specify lowcut, highcut and sample_rate as ints or floats. >>> b, a = butter_bandpass(lowcut = 1, highcut = 6, sample_rate = 100, order = 2) >>> b, a = butter_bandpass(lowcut = 0.4, highcut = 3.7, sample_rate = 72.6, order = 2) ''' nyq = 0.5 * sample_rate low = lowcut / nyq high = highcut / nyq b, a = butter(order, [low, high], btype='band') return b, a
Example #6
Source File: EEGsynth.py From eegsynth with GNU General Public License v3.0 | 5 votes |
def butter_highpass(highcut, fs, order=9): nyq = 0.5 * fs high = highcut / nyq b, a = butter(order, high, btype='highpass') return b, a ####################################################################
Example #7
Source File: Filtering.py From incubator-sdap-nexus with Apache License 2.0 | 5 votes |
def applyLowPassFilter(y, lowcut=12.0, order=9.0): if len(y) - 12 <= lowcut: lowcut = 3 nyq = 0.5 * len(y) low = lowcut / nyq # high = highcut / nyq b, a = butter(order, low) m = min([len(y), len(a), len(b)]) padlen = 30 if m >= 30 else m fl = filtfilt(b, a, y, padlen=padlen) return fl
Example #8
Source File: base.py From phy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def add_default_filter(self, sample_rate): b, a = butter(3, 150.0 / sample_rate * 2.0, 'high') @self.add_filter def high_pass(arr, axis=0): arr = lfilter(b, a, arr, axis=axis) arr = np.flip(arr, axis=axis) arr = lfilter(b, a, arr, axis=axis) arr = np.flip(arr, axis=axis) return arr self.set('high_pass')
Example #9
Source File: raw_data_filter.py From phy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def attach_to_controller(self, controller): b, a = butter(3, 150.0 / controller.model.sample_rate * 2.0, 'high') @controller.raw_data_filter.add_filter def high_pass(arr, axis=0): return filtfilt(b, a, arr, axis=axis)
Example #10
Source File: __init__.py From srep with GNU General Public License v3.0 | 5 votes |
def butter_bandpass_filter(data, lowcut, highcut, fs, order): from scipy.signal import butter, lfilter nyq = 0.5 * fs low = lowcut / nyq high = highcut / nyq b, a = butter(order, [low, high], btype='bandpass') y = lfilter(b, a, data) return y
Example #11
Source File: utils.py From PyFNND with GNU General Public License v3.0 | 5 votes |
def detrend(x, dt=0.02, stop_hz=0.01, order=5): orig_shape = x.shape x = np.atleast_2d(x) nyquist = 0.5 / dt stop = stop_hz / nyquist b, a = signal.butter(order, Wn=stop, btype='lowpass') y = signal.filtfilt(b, a, x, axis=1) return (x - y).reshape(orig_shape)
Example #12
Source File: stats.py From nltools with MIT License | 5 votes |
def _butter_bandpass_filter(data, low_cut, high_cut, fs, axis = 0, order=5): '''Apply a bandpass butterworth filter with zero-phase filtering Args: data: (np.array) low_cut: (float) lower bound cutoff for high pass filter high_cut: (float) upper bound cutoff for low pass filter fs: (float) sampling frequency in Hz axis: (int) axis to perform filtering. order: (int) filter order for butterworth bandpass Returns: bandpass filtered data. ''' nyq = 0.5 * fs b, a = butter(order, [low_cut/nyq, high_cut/nyq], btype='band') return filtfilt(b, a, data, axis=axis)
Example #13
Source File: MorseDecoder.py From LSTM_morse with MIT License | 5 votes |
def demodulate(x, Fs, freq): """return decimated and demodulated audio signal envelope at a known CW frequency """ t = np.arange(len(x))/ float(Fs) mixed = x*((1 + np.sin(2*np.pi*freq*t))/2 ) #calculate envelope and low pass filter this demodulated signal #filter bandwidth impacts decoding accuracy significantly #for high SNR signals 40 Hz is better, for low SNR 20Hz is better # 25Hz is a compromise - could this be made an adaptive value? low_cutoff = 25. # 25 Hz cut-off for lowpass wn = low_cutoff/ (Fs/2.) b, a = butter(3, wn) # 3rd order butterworth filter z = filtfilt(b, a, abs(mixed)) decimate = int(Fs/64) # 8000 Hz / 64 = 125 Hz => 8 msec / sample Ts = 1000.*decimate/float(Fs) o = z[0::decimate]/max(z) return o
Example #14
Source File: log_tools.py From pyGeoPressure with MIT License | 5 votes |
def upscale_log(log, freq=20): """ downscale a well log with a lowpass butterworth filter """ depth = np.array(log.depth) data = np.array(log.data) mask = np.isfinite(data) func = interp1d(depth[mask], data[mask]) interp_data = func(depth[log.start_idx: log.stop_idx]) nyq = 10000 / 2 dw = freq / nyq b, a = butter(4, dw, btype='low', analog=False) filtered = filtfilt(b, a, interp_data, method='gust') downscale_data = np.array(data) downscale_data[log.start_idx: log.stop_idx] = filtered log_downscale = Log() log_downscale.name = log.name + "_downscale_" + str(freq) log_downscale.units = log.units log_downscale.descr = log.descr log_downscale.depth = log.depth log_downscale.data = downscale_data return log_downscale
Example #15
Source File: plotCSVfile.py From GAN-MRI with GNU General Public License v3.0 | 5 votes |
def butter_lowpass(cutoff, fs, order=5): nyq = 0.5 * fs normal_cutoff = cutoff / nyq b, a = butter(order, normal_cutoff, btype='low', analog=False) return b, a
Example #16
Source File: DataserToSpectogram.py From CNNs-on-CHB-MIT with GNU General Public License v3.0 | 5 votes |
def butter_highpass_filter(data, cutoff, fs, order=5): nyq = 0.5 * fs normal_cutoff = cutoff / nyq b, a = butter(order, normal_cutoff, btype='high', analog=False) y = lfilter(b, a, data) return y #Creazione del puntatore al file del paziente con indice uguale a index
Example #17
Source File: filter.py From klusta with BSD 3-Clause "New" or "Revised" License | 5 votes |
def bandpass_filter(rate=None, low=None, high=None, order=None): """Butterworth bandpass filter.""" assert low < high assert order >= 1 return signal.butter(order, (low / (rate / 2.), high / (rate / 2.)), 'pass')
Example #18
Source File: EEGsynth.py From eegsynth with GNU General Public License v3.0 | 5 votes |
def butter_lowpass(lowcut, fs, order=9): nyq = 0.5 * fs low = lowcut / nyq b, a = butter(order, low, btype='lowpass') return b, a ####################################################################
Example #19
Source File: XerawdpImitation.py From pax with BSD 3-Clause "New" or "Revised" License | 5 votes |
def butter_bandpass(lowcut, highcut, fs, order=5): nyq = 0.5 * fs low = lowcut / nyq high = highcut / nyq b, a = butter(order, [low, high], btype='band') return b, a
Example #20
Source File: audiosegment.py From Speech_emotion_recognition_BLSTM with MIT License | 5 votes |
def _bandpass_filter(self, data, low, high, fs, order=5): """ :param data: The data (numpy array) to be filtered. :param low: The low cutoff in Hz. :param high: The high cutoff in Hz. :param fs: The sample rate (in Hz) of the data. :param order: The order of the filter. The higher the order, the tighter the roll-off. :returns: Filtered data (numpy array). """ nyq = 0.5 * fs low = low / nyq high = high / nyq b, a = signal.butter(order, [low, high], btype='band') y = signal.lfilter(b, a, data) return y
Example #21
Source File: worker.py From PDR-with-Map-Matching with MIT License | 5 votes |
def Init(self): self.log_filename = 'log\\log_worker.txt' self.sensor_data_process = [] self.sampling_rate = 400 self.delta_time = 1.0 / self.sampling_rate self.beta = 0.1 self.epsilon = 0.001 self.gravity = 9.7 self.magic_number_scale = 5.1 self.scale = self.gravity * self.magic_number_scale self.magic_number_scale_single_integration = 2.8 self.scale_single_integration = self.gravity * self.magic_number_scale_single_integration LP_Cutoff = 2.0 self.LP_b, self.LP_a = signal.butter(2, 2.0 * LP_Cutoff * self.delta_time, 'low') PLP_Cutoff = 0.05 self.PLP_b, self.PLP_a = signal.butter(1, 2.0 * PLP_Cutoff * self.delta_time, 'low') self.min_length_for_process = 400 self.reserve_data_length = 200 self.walking = False self.step_number = 0 self.map_matching = MapMatching() return
Example #22
Source File: Sensor.py From Deep-Spying with Apache License 2.0 | 5 votes |
def apply_butterworth_filter(self, data, frequency, type, order=6): CUTOFF_FREQUENCY = 0.5 critical = 0.5 * frequency normal_cutoff = CUTOFF_FREQUENCY / critical b, a = signal.butter(order, normal_cutoff, btype=type, analog=False) result = signal.lfilter(b, a, data) return result
Example #23
Source File: representations.py From CorpusTools with BSD 3-Clause "New" or "Revised" License | 5 votes |
def to_envelopes(path,num_bands,freq_lims,downsample=True): """Generate amplitude envelopes from a full path to a .wav, following Lewandowski (2012). Parameters ---------- filename : str Full path to .wav file to process. num_bands : int Number of frequency bands to use. freq_lims : tuple Minimum and maximum frequencies in Hertz to use. downsample : bool If true, envelopes will be downsampled to 120 Hz Returns ------- 2D array Amplitude envelopes over time """ sr, proc = preproc(path,alpha=0.97) #proc = proc / 32768 #hack!! for 16-bit pcm proc = proc/sqrt(mean(proc**2))*0.03; bandLo = [ freq_lims[0]*exp(log(freq_lims[1]/freq_lims[0])/num_bands)**x for x in range(num_bands)] bandHi = [ freq_lims[0]*exp(log(freq_lims[1]/freq_lims[0])/num_bands)**(x+1) for x in range(num_bands)] envelopes = [] for i in range(num_bands): b, a = butter(2,(bandLo[i]/(sr/2),bandHi[i]/(sr/2)), btype = 'bandpass') env = filtfilt(b,a,proc) env = abs(hilbert(env)) if downsample: env = resample(env,int(ceil(len(env)/int(ceil(sr/120))))) #env = decimate(env,int(ceil(sr/120))) envelopes.append(env) return array(envelopes).T
Example #24
Source File: filtering.py From heartrate_analysis_python with GNU General Public License v3.0 | 5 votes |
def butter_highpass(cutoff, sample_rate, order=2): '''standard highpass filter. Function that defines standard Butterworth highpass filter Parameters ---------- cutoff : int or float frequency in Hz that acts as cutoff for filter. All frequencies below cutoff are filtered out. sample_rate : int or float sample rate of the supplied signal order : int filter order, defines the strength of the roll-off around the cutoff frequency. Typically orders above 6 are not used frequently. default : 2 Returns ------- out : tuple numerator and denominator (b, a) polynomials of the defined Butterworth IIR filter. Examples -------- we can specify the cutoff and sample_rate as ints or floats. >>> b, a = butter_highpass(cutoff = 2, sample_rate = 100, order = 2) >>> b, a = butter_highpass(cutoff = 4.5, sample_rate = 12.5, order = 5) ''' nyq = 0.5 * sample_rate normal_cutoff = cutoff / nyq b, a = butter(order, normal_cutoff, btype='high', analog=False) return b, a
Example #25
Source File: filtering.py From heartrate_analysis_python with GNU General Public License v3.0 | 5 votes |
def butter_lowpass(cutoff, sample_rate, order=2): '''standard lowpass filter. Function that defines standard Butterworth lowpass filter Parameters ---------- cutoff : int or float frequency in Hz that acts as cutoff for filter. All frequencies above cutoff are filtered out. sample_rate : int or float sample rate of the supplied signal order : int filter order, defines the strength of the roll-off around the cutoff frequency. Typically orders above 6 are not used frequently. default: 2 Returns ------- out : tuple numerator and denominator (b, a) polynomials of the defined Butterworth IIR filter. Examples -------- >>> b, a = butter_lowpass(cutoff = 2, sample_rate = 100, order = 2) >>> b, a = butter_lowpass(cutoff = 4.5, sample_rate = 12.5, order = 5) ''' nyq = 0.5 * sample_rate normal_cutoff = cutoff / nyq b, a = butter(order, normal_cutoff, btype='low', analog=False) return b, a
Example #26
Source File: signal_filtering.py From HAR-stacked-residual-bidir-LSTMs with Apache License 2.0 | 5 votes |
def butter_lowpass(cutoff, nyq_freq, order=4): # Build the filter normal_cutoff = float(cutoff) / nyq_freq b, a = signal.butter(order, normal_cutoff, btype='lowpass') return b, a
Example #27
Source File: prep_vctk.py From audio-super-res with MIT License | 5 votes |
def butter_bandpass(lowcut, highcut, fs, order=5): nyq = 0.5 * fs low = lowcut / nyq high = highcut / nyq b, a = butter(order, [low, high], btype='band') return b, a
Example #28
Source File: vehicle.py From omg-tools with GNU Lesser General Public License v3.0 | 5 votes |
def add_disturbance(self, input): if self.options['input_disturbance'] is not None: fc = self.options['input_disturbance']['fc'] stdev = self.options['input_disturbance']['stdev'] if 'mean' in self.options['input_disturbance']: mean = self.options['input_disturbance']['mean'] else: mean = np.zeros(stdev.shape) n_sign = input.shape[0] n_samp = input.shape[1] disturbance = np.zeros((n_sign, n_samp)) filt = butter(3, fc, 'low') for k in range(n_sign): disturbance[k, :] = filtfilt(filt[0], filt[1], normal(mean[k], stdev[k], n_samp)) return input + disturbance else: return input
Example #29
Source File: main_KF.py From Deep_Visual_Inertial_Odometry with MIT License | 5 votes |
def filtfilt(data): y = np.zeros_like(data) b, a = signal.butter(8, 0.1) for i in range(0, 3): y[:, i] = signal.filtfilt(b, a, data[:, i], padlen=100) return y
Example #30
Source File: sigsys.py From scikit-dsp-comm with BSD 2-Clause "Simplified" License | 5 votes |
def deci24(x): """ Decimate by L = 24 using Butterworth filters. The decimation is done using two three stages. Downsample sample by L = 2 and lowpass filter, downsample by 3 and lowpass filter, then downsample by L = 4 and lowpass filter. In all cases the lowpass filter is a 10th-order Butterworth lowpass. Parameters ---------- x : ndarray of the input signal Returns ------- y : ndarray of the output signal Notes ----- The cutoff frequency of the lowpass filters is 1/2, 1/3, and 1/4 to track the upsampling by 2, 3, and 4 respectively. Examples -------- >>> y = deci24(x) """ # Stage 1: M = 2 b2,a2 = signal.butter(10,1/2.) y1 = signal.lfilter(b2,a2,x) y1 = downsample(y1,2) # Stage 2: M = 3 b3,a3 = signal.butter(10,1/3.) y2 = signal.lfilter(b3,a3,y1) y2 = downsample(y2,3) # Stage 3: L = 4 b4,a4 = signal.butter(10,1/4.) y3 = signal.lfilter(b4,a4,y2) y3 = downsample(y3,4) return y3