本文整理汇总了Python中scipy.signal.firwin2函数的典型用法代码示例。如果您正苦于以下问题:Python firwin2函数的具体用法?Python firwin2怎么用?Python firwin2使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了firwin2函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: filter_VE
def filter_VE(data):
f=np.linspace(0,1,50000)
a = np.ones(50000)
#Switching power supply frequency (~290 KHz)
a[2850:2950] =0
#1.49 MHz
a[14850:14950]=0
#AM 1.37 MHz
a[13650:13750] = 0
#80 m Ham band (3.97 MHz)
a[39650:39750] = 0
#80 m Ham band (4 MHz)
a[39950:40050]= 0
a[-1]=0
b=sigs.firwin2(3000,f,a)
[h, fpoints] = sigs.freqz(b, 1, 50000,10E6)
#Run the FIR filter
vec = sigs.lfilter(b,1,data)
return vec
示例2: lab6_ex2
def lab6_ex2():
# set parameters of system
fn = 1.0
nt = 50 #number of taps
freq = array([0,0.1,0.2,0.5,1.0]) #frequency sampling points
gain = array([1.0,1.0,0.01,0.001,0])
b = firwin2(nt,freq,gain,nyq=fn) #calc FIR coefficients with given frequency response
a = array([1.0,0]) #(no feedback (FIR), poles at origin reduced to 1 for simplification)
# calc frequency response of filter and plot
w,h = freqz(b,a)
plot(w/pi, 20*log10(abs(h)),'b-')
title('FIR of given frequency response')
xlabel('normalized frequency (1 = fn)')
ylabel('magnitude (dB scale)')
grid()
show()
print('\nResponses in dB scale (all frequencies are relative to fn):\nf = 0, gain = 0 dB\nf = 0.1, gain = -1.05 dB\nf = 0.2, gain = -18.25 dB\nf = 0.5, gain = -56.4 dB\nf = 1.0, gain =~ -92 dB (filter tries to approach -inf and goes off the scale around f = 0.999)')
print('\nThe filter has 49 zeros (the same as number of taps - 1)')
print('The filter should also have 49 poles (all at the origin) so that it is causal. However, in this implementation (firwin2) there are no poles (except those added by the user)')
# calc and show zeros and poles on zplane
z,p,k = tf2zpk(b,a)
zplane(z,p)
title('zplane of FIR of given frequency response (50 taps)')
show()
print('\nFrom the zplane diagram, we can see pairs of conjugate pairs of zeros that follow along the unit circle. For each pair of conjugate pairs, one conjugate pair is inside of the unit circle and one is on the outside. As the frequency increases to fn, each pair of zeros generally gets closer and closer to the unit circle, thus attenuating the signal even further, up to a gain of 0 @ f = fn)')
示例3: fir2FiltAlt
def fir2FiltAlt(f1, f2, f3, f4, filterType, snd, fs, filterOrder):
fs = float(fs)
f1 = (f1 * 2) / fs
f2 = (f2 * 2) / fs
f3 = (f3 * 2) / fs
f4 = (f4 * 2) / fs
n = filterOrder
if filterType == 'lowpass':
f = [0, f3, f4, 1]
m = [1, 1, 0.00003, 0]
elif filterType == 'highpass':
f = [0, f1, f2, 0.999999, 1] #high pass
m = [0, 0.00003, 1, 1, 0]
elif filterType == 'bandpass':
f = [0, f1, f2, ((f2+f3)/2), f3, f4, 1]
m = [0, 0.00003, 1, 1, 1, 0.00003, 0]
elif filterType == 'bandstop':
f = [0, f1, f2, ((f2+f3)/2), f3, f4, 0.999999, 1] #band stop
m = [1, 1, 0.00003, 0, 0.00003, 1, 1, 0]
b = firwin2 (n,f,m);
x = copy.copy(snd)
x = convolve(snd, b, 1)
#x[:, 1] = convolve(snd[:,1], b, 1)
return x
示例4: get_channelizer_taps
def get_channelizer_taps(M, n_taps=100):
taps = signal.firwin2(100, [0, 1.0/M, 1.0/M+0.05, 1], [1, 1, 0, 0])
# Divide by integral of absolute values to prevent the possibility
# of overflow.
chantaps = [taps[i::M] for i in range(M)]
scaledtaps, tapscalefactor = scale_taps(chantaps)
return scaledtaps, tapscalefactor
示例5: test04
def test04(self):
"""Test firwin2 when window=None."""
ntaps = 5
# Ideal lowpass: gain is 1 on [0,0.5], and 0 on [0.5, 1.0]
freq = [0.0, 0.5, 0.5, 1.0]
gain = [1.0, 1.0, 0.0, 0.0]
taps = firwin2(ntaps, freq, gain, window=None, nfreqs=8193)
alpha = 0.5 * (ntaps - 1)
m = np.arange(0, ntaps) - alpha
h = 0.5 * sinc(0.5 * m)
assert_array_almost_equal(h, taps)
示例6: test05
def test05(self):
"""Test firwin2 for calculating Type IV filters"""
ntaps = 1500
freq = [0.0, 1.0]
gain = [0.0, 1.0]
taps = firwin2(ntaps, freq, gain, window=None, antisymmetric=True)
assert_array_almost_equal(taps[: ntaps // 2], -taps[ntaps // 2:][::-1])
freqs, response = freqz(taps, worN=2048)
assert_array_almost_equal(abs(response), freqs / np.pi, decimal=4)
示例7: test03
def test03(self):
width = 0.02
ntaps, beta = kaiserord(120, width)
# ntaps must be odd for positive gain at Nyquist.
ntaps = int(ntaps) | 1
freq = [0.0, 0.4, 0.4, 0.5, 0.5, 1.0]
gain = [1.0, 1.0, 0.0, 0.0, 1.0, 1.0]
taps = firwin2(ntaps, freq, gain, window=("kaiser", beta))
freq_samples = np.array([0.0, 0.4 - width, 0.4 + width, 0.45, 0.5 - width, 0.5 + width, 0.75, 1.0])
freqs, response = freqz(taps, worN=np.pi * freq_samples)
assert_array_almost_equal(np.abs(response), [1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0], decimal=5)
示例8: firf
def firf(x, f_range, fs = 1000, w = 7, tw = .15):
"""
Filter signal with an FIR filter
x : array-like, 1d
Time series to filter
f_range : (low, high), Hz
Cutoff frequencies of bandpass filter
fs : float, Hz
Sampling rate
w : float
Length of the filter in terms of the number of cycles of the oscillation
whose frequency is the center of the bandpass filter
tw : float
Transition width of the filter in normalized frequency space
Returns
-------
x_filt : array-like, 1d
Filtered time series
"""
if w <= 0:
raise ValueError('Number of cycles in a filter must be a positive number.')
if np.logical_or(tw < 0, tw > 1):
raise ValueError('Transition width must be between 0 and 1.')
nyq = fs/2
if np.any(np.array(f_range) > nyq):
raise ValueError('Filter frequencies must be below nyquist rate.')
if np.any(np.array(f_range) < 0):
raise ValueError('Filter frequencies must be positive.')
cf = np.mean(f_range)
Ntaps = np.floor(w * fs / cf)
if len(x) < Ntaps:
raise RuntimeError('Length of filter is loger than data. Provide more data or a shorter filter.')
# Characterize desired filter
f = [0, (1-tw)*f_range[0]/nyq, f_range[0]/nyq, f_range[1]/nyq, (1+tw)*f_range[1]/nyq, 1]
m = [0,0,1,1,0,0]
if any(np.diff(f)<0):
raise RuntimeError('Invalid FIR filter parameters. Please decrease the transition width parameter.')
# Perform filtering
taps = firwin2(Ntaps, f, m)
x_filt = filtfilt(taps,[1],x)
if any(np.isnan(x_filt)):
raise RuntimeError('Filtered signal contains nans. Adjust filter parameters.')
return x_filt
示例9: test02
def test02(self):
width = 0.04
beta = 12.0
# ntaps must be odd for positive gain at Nyquist.
ntaps = 401
# An ideal highpass filter.
freq = [0.0, 0.5, 0.5, 1.0]
gain = [0.0, 0.0, 1.0, 1.0]
taps = firwin2(ntaps, freq, gain, window=("kaiser", beta))
freq_samples = np.array([0.0, 0.25, 0.5 - width, 0.5 + width, 0.75, 1.0])
freqs, response = freqz(taps, worN=np.pi * freq_samples)
assert_array_almost_equal(np.abs(response), [0.0, 0.0, 0.0, 1.0, 1.0, 1.0], decimal=5)
示例10: test01
def test01(self):
width = 0.04
beta = 12.0
ntaps = 400
# Filter is 1 from w=0 to w=0.5, then decreases linearly from 1 to 0 as w
# increases from w=0.5 to w=1 (w=1 is the Nyquist frequency).
freq = [0.0, 0.5, 1.0]
gain = [1.0, 1.0, 0.0]
taps = firwin2(ntaps, freq, gain, window=("kaiser", beta))
freq_samples = np.array([0.0, 0.25, 0.5 - width / 2, 0.5 + width / 2, 0.75, 1.0 - width / 2])
freqs, response = freqz(taps, worN=np.pi * freq_samples)
assert_array_almost_equal(np.abs(response), [1.0, 1.0, 1.0, 1.0 - width, 0.5, width], decimal=5)
示例11: test06
def test06(self):
"""Test firwin2 for calculating Type III filters"""
ntaps = 1501
freq = [0.0, 0.5, 0.55, 1.0]
gain = [0.0, 0.5, 0.0, 0.0]
taps = firwin2(ntaps, freq, gain, window=None, antisymmetric=True)
assert_equal(taps[ntaps // 2], 0.0)
assert_array_almost_equal(taps[: ntaps // 2], -taps[ntaps // 2 + 1:][::-1])
freqs, response1 = freqz(taps, worN=2048)
response2 = np.interp(freqs / np.pi, freq, gain)
assert_array_almost_equal(abs(response1), response2, decimal=3)
示例12: design_filter
def design_filter(filter_type, f_p, f_w, filter_dur, window):
if filter_type == 'highpass':
f_s = f_p - f_w
freq = [0., f_s, f_p, sfreq / 2.]
gain = [0., 0., 1., 1.]
else:
f_s = f_p + f_w
freq = [0., f_p, f_s, sfreq / 2.]
gain = [1., 1., 0., 0.]
n = int(sfreq * filter_dur)
n += ~(n % 2) # Type II filter can't have 0 attenuation at nyq
h = signal.firwin2(n, freq, gain, nyq=sfreq / 2., window=window)
return h
示例13: lock2
def lock2(f0, fp, fc, fs, coeff_ratio=8.0, coeffs=None,
window='blackman', print_response=True):
"""Create a gentle fir filter. Pass frequencies below fp, cutoff frequencies
above fc, and gradually taper to 0 in between."""
# Convert to digital frequencies, normalizing f_nyq to 1,
# as requested by scipy.signal.firwin2
nyq = fs / 2
fp = fp / nyq
fc = fc / nyq
if coeffs is None:
coeffs = int(round(coeff_ratio / fc, 0))
# Force number of tukey coefficients odd
alpha = (1-fp*1.0/fc)
n = int(round(1000. / alpha) // 2)
N = n * 2 + 1
f = np.linspace(0, fc, n+1)
fm = np.zeros(n + 2)
mm = np.zeros(n + 2)
fm[:-1] = f
# Append fm = nyquist frequency by hand; needed by firwin2
fm[-1] = 1.
m = signal.tukey(N, alpha=alpha)
# Only take the falling part of the tukey window,
# not the part equal to zero
mm[:-1] = m[n:]
# Use approx. 8x more frequencies than total coefficients we need
nfreqs = 2**(int(round(np.log2(coeffs)))+3)+1
b = signal.firwin2(coeffs, fm, mm,
nfreqs=nfreqs,
window=window)
# Force filter gain to 1 at DC; corrects for small rounding errors
b = b / np.sum(b)
w, rep = signal.freqz(b, worN=np.pi*np.array([0., fp/2, fp, fc, 2*fc,
0.5*f0/nyq, f0/nyq, 1.]))
if print_response:
print("Response:")
_print_magnitude_data(w, rep, fs)
return b
示例14: computefir
def computefir(fc, L: int, ofn, fs: int, method: str):
"""
bandpass FIR design
https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.firwin.html
http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.remez.html
L: number of taps
output:
b: FIR filter coefficients
"""
assert len(fc) == 2, 'specify lower and upper bandpass filter corner frequencies in Hz.'
if method == 'remez':
b = signal.remez(numtaps=L,
bands=[0, 0.9*fc[0], fc[0], fc[1], 1.1*fc[1], 0.5*fs],
desired=[0, 1, 0],
Hz=fs)
elif method == 'firwin':
b = signal.firwin(L, [fc[0], fc[1]],
window='blackman',
pass_zero=False, nyq=fs//2)
elif method == 'firwin2':
b = signal.firwin2(L, [0, fc[0], fc[1], fs//2], [0, 1, 1, 0],
window='blackman',
nyq=fs//2,
# antisymmetric=True,
)
else:
raise ValueError(f'unknown filter design method {method}')
if ofn:
ofn = Path(ofn).expanduser()
print(f'writing {ofn}')
# FIXME make binary
with ofn.open('w') as h:
h.write(f'{b.size}\n') # first line is number of coefficients
b.tofile(h, sep=" ") # second line is space-delimited coefficents
return b
示例15: _matched_filters
def _matched_filters(ks, x_m, N_pts, dec=16, window='hann', n_pts_eval_fir=48000):
ks = ks / dec
N = N_pts // dec
k = np.linspace(0, ks/2, n_pts_eval_fir)
resp_ac = _j1filt(k * 2 * np.pi * x_m)
fir_ac_dec = signal.firwin2(N, k, resp_ac, nyq=k[-1], window=window)
fir_dc_dec = signal.firwin(N, jn_zeros(0, 1)[0] / (2*np.pi*x_m),
nyq=k[-1], window=window)
# Manually force gain to 1 at DC; firwin2 rounding errors probable cause of
# minor losses (< 1 percent)
fir_ac_dec = fir_ac_dec / np.sum(fir_ac_dec)
fir_dc_dec = fir_dc_dec / np.sum(fir_dc_dec)
fir_ac = np.fft.irfft(np.fft.rfft(fir_ac_dec), fir_ac_dec.size * dec)
fir_dc = np.fft.irfft(np.fft.rfft(fir_dc_dec), fir_dc_dec.size * dec)
return fir_ac, fir_dc