本文整理汇总了Python中scipy.signal.butter方法的典型用法代码示例。如果您正苦于以下问题:Python signal.butter方法的具体用法?Python signal.butter怎么用?Python signal.butter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.signal
的用法示例。
在下文中一共展示了signal.butter方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: butter_lowpass
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import butter [as 别名]
def butter_lowpass(cutoff, fs, order=5):
"""
Design lowpass filter.
Args:
- cutoff (float) : the 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 = cutoff / nyq
b, a = butter(order, low, btype='low', analog=False)
# returns the filter coefficients: numerator and denominator
return b, a
示例2: butter_highpass
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import butter [as 别名]
def butter_highpass(cutoff, fs, order=5):
"""
Design a highpass filter.
Args:
- cutoff (float) : the 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
high = cutoff / nyq
b, a = butter(order, high, btype='high', analog=False)
# returns the filter coefficients: numerator and denominator
return b, a
示例3: butter_bandpass
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import butter [as 别名]
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
示例4: compressor
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import butter [as 别名]
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
示例5: butter_highpass
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import butter [as 别名]
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.
示例6: test_zi_pseudobroadcast
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import butter [as 别名]
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))
示例7: __init__
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import butter [as 别名]
def __init__(self, recording, freq_min=300, freq_max=6000, freq_wid=1000, filter_type='fft', order=3,
chunk_size=30000, cache_chunks=False):
assert HAVE_BFR, "To use the BandpassFilterRecording, install scipy: \n\n pip install scipy\n\n"
self._freq_min = freq_min
self._freq_max = freq_max
self._freq_wid = freq_wid
self._type = filter_type
self._order = order
self._chunk_size = chunk_size
if self._type == 'butter':
fn = recording.get_sampling_frequency() / 2.
band = np.array([self._freq_min, self._freq_max]) / fn
self._b, self._a = ss.butter(self._order, band, btype='bandpass')
if not np.all(np.abs(np.roots(self._a)) < 1):
raise ValueError('Filter is not stable')
FilterRecording.__init__(self, recording=recording, chunk_size=chunk_size, cache_chunks=cache_chunks)
self.copy_channel_properties(recording)
self.is_filtered = True
self._kwargs = {'recording': recording.make_serialized_dict(), 'freq_min': freq_min, 'freq_max': freq_max,
'freq_wid': freq_wid, 'filter_type': filter_type, 'order': order,
'chunk_size': chunk_size, 'cache_chunks': cache_chunks}
示例8: _do_filter
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import butter [as 别名]
def _do_filter(self, chunk):
sampling_frequency = self._recording.get_sampling_frequency()
M = chunk.shape[0]
chunk2 = chunk
# Do the actual filtering with a DFT with real input
if self._type == 'fft':
chunk_fft = np.fft.rfft(chunk2)
kernel = _create_filter_kernel(
chunk2.shape[1],
sampling_frequency,
self._freq_min, self._freq_max, self._freq_wid
)
kernel = kernel[0:chunk_fft.shape[1]] # because this is the DFT of real data
chunk_fft = chunk_fft * np.tile(kernel, (M, 1))
chunk_filtered = np.fft.irfft(chunk_fft)
elif self._type == 'butter':
chunk_filtered = ss.filtfilt(self._b, self._a, chunk2, axis=1)
return chunk_filtered
示例9: bandpass_filter
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import butter [as 别名]
def bandpass_filter(data, low, high, fs, order=5):
"""
Does a bandpass filter over the given data.
: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).
"""
if not scipy_imported:
raise NotImplementedError("This function is unusable without Scipy")
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
示例10: lowpass_filter
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import butter [as 别名]
def lowpass_filter(data, cutoff, fs, order=5):
"""
Does a lowpass filter over the given data.
:param data: The data (numpy array) to be filtered.
:param cutoff: 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).
"""
if not scipy_imported:
raise NotImplementedError("This function is unusable without Scipy")
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = signal.butter(order, normal_cutoff, btype='low', analog=False)
y = signal.lfilter(b, a, data)
return y
示例11: digital_down_conversion
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import butter [as 别名]
def digital_down_conversion(self, I, Q, freqs=None):
"""
performs a digital down conversion to get rid of the carrier frequency.
Useful for timetrace readout, when only envelope is needed.
:param I:
:param Q:
:param freqs:
:return:
"""
if freqs is None:
freqs = np.array(self._tone_freq) - self._LO
samplerate = self.get_adc_clock()
sig_amp = np.zeros((len(freqs), len(I)))
sig_pha = np.zeros((len(freqs), len(I)))
t = np.linspace(0, float(len(I)) / samplerate, len(I))
for i, f in enumerate(freqs):
cut_off_freq = self.cut_off_freq_ratio * np.abs(f) / (samplerate / 2)
b, a = signal.butter(self.lowpass_order, cut_off_freq, 'low') # design the filter
signal_down = (I+1j*Q)*np.exp(1j*2*np.pi*f*t)
signal_down_lp = scipy.signal.lfilter(b, a, signal_down)
sig_amp[i, :] = np.abs(signal_down_lp)
sig_pha[i, :] = np.angle(signal_down_lp)
return sig_amp.T, sig_pha.T # transform because readout expects the data this way
# +++++ DAC (AWG) settings ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
示例12: add_disturbance
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import butter [as 别名]
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
示例13: _butter_bandpass_filter
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import butter [as 别名]
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)
示例14: demodulate
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import butter [as 别名]
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
示例15: upscale_log
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import butter [as 别名]
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