def _signal_template(self,
signal_period,
frequency_sampling,
frequency_cut,
mean,
std,
filter_std=25,
filter_window_size=500,
seed=None,
n: int=1000):
randgen = np.random.RandomState(seed=seed)
noisy = randgen.normal(mean, std, size=self._size)
high_band_filter = firwin(filter_window_size, frequency_cut,
nyq=frequency_sampling,
window=('gaussian', filter_std))
filtered_noisy = convolve(noisy, high_band_filter, mode='same')
return filtered_noisy
python类firwin()的实例源码
def pb2bb(x, fs, fc, fd=None, flen=127, cutoff=None):
"""Convert passband signal to baseband.
The baseband conversion uses a low-pass filter after downconversion, with a
default cutoff frequency of `0.6*fd`, if `fd` is specified, or `1.1*fc` if `fd`
is not specified. Alternatively, the user may specify the cutoff frequency
explicitly.
For communication applications, one may wish to use :func:`arlpy.comms.downconvert` instead,
as that function supports matched filtering with a pulse shape rather than a generic
low-pass filter.
:param x: passband signal
:param fs: sampling rate of passband signal in Hz
:param fc: carrier frequency in passband in Hz
:param fd: sampling rate of baseband signal in Hz (``None`` => same as `fs`)
:param flen: number of taps in the low-pass FIR filter
:param cutoff: cutoff frequency in Hz (``None`` means auto-select)
:returns: complex baseband signal, sampled at `fd`
"""
if cutoff is None:
cutoff = 0.6*fd if fd is not None else 1.1*fc
y = x * _np.sqrt(2)*_np.exp(2j*_np.pi*fc*time(x,fs))
hb = _sig.firwin(flen, cutoff=cutoff, nyq=fs/2.0)
y = _sig.filtfilt(hb, 1, y)
if fd is not None and fd != fs:
y = _sig.resample_poly(y, 2*fd, fs)[::2]
return y
def design(self, fs, fc, bandwidth, ripple_db=60.0):
"""
Designs a FIR filter that is a low-pass filter.
fs : sampling frequency (Hz)
fc : cut-off frequency (Hz)
bandwidth : transition bandwidth (Hz)s
"""
# Compute the order and Kaiser parameter for the FIR filter.
N, beta = signal.kaiserord(ripple_db, bandwidth / fs * 2)
# Use firwin with a Kaiser window to create a lowpass FIR filter.
fir = signal.firwin(N, fc / fs * 2, window=('kaiser', beta))
# the filter must be symmetric, in order to be zero-phase
assert np.all(np.abs(fir - fir[::-1]) < 1e-15)
self.fir = fir / np.sum(fir)
self.fs = fs
return self
def apply(self, data):
nyq = self.f / 2.0
cutoff = min(self.f, nyq-1)
h = signal.firwin(numtaps=101, cutoff=cutoff, nyq=nyq)
# data[i][ch][dim0]
for i in range(len(data)):
data_point = data[i]
for j in range(len(data_point)):
data_point[j] = signal.lfilter(h, 1.0, data_point[j])
return data
def polyphase_lowpass(arr, downsample=2, n_taps=50, filter_pad=1.1):
filt = firwin(downsample * n_taps, 1 / (downsample * filter_pad))
filtered = polyphase_single_filter(arr, downsample, filt)
return filtered
def polyphase_lowpass(arr, downsample=2, n_taps=50, filter_pad=1.1):
filt = firwin(downsample * n_taps, 1 / (downsample * filter_pad))
filtered = polyphase_single_filter(arr, downsample, filt)
return filtered
def _high_frequency_completion(self, x, transformed):
"""
Please see Sect. 3.2 and 3.3 in the following paper to know why we complete the
unvoiced synthesized voice of the original voice into high frequency range
of F0 transformed voice.
- K. Kobayashi et al., "F0 transformation techniques for statistical voice
conversion with direct waveform modification with spectral differential,"
Proc. IEEE SLT 2016, pp. 693-700. 2016.
"""
# construct feature extractor and synthesis
feat = FeatureExtractor(fs=self.fs)
f0, spc, ap = feat.analyze(x)
uf0 = np.zeros(len(f0))
# synthesis
synth = Synthesizer(fs=self.fs)
unvoice_anasyn = synth.synthesis_spc(uf0, spc, ap)
# HPF for synthesized speech
fil = firwin(255, self.f0rate, pass_zero=False)
HPFed_unvoice_anasyn = lfilter(fil, 1, unvoice_anasyn)
if len(HPFed_unvoice_anasyn) > len(transformed):
return transformed + HPFed_unvoice_anasyn[:len(transformed)]
else:
transformed[:len(HPFed_unvoice_anasyn)] += HPFed_unvoice_anasyn
return transformed
def low_cut_filter(x, fs, cutoff=70):
"""Low cut filter
Parameters
---------
x : array, shape(`samples`)
Waveform sequence
fs: array, int
Sampling frequency
cutoff : float, optional
Cutoff frequency of low cut filter
Default set to 70 [Hz]
Returns
---------
lcf_x : array, shape(`samples`)
Low cut filtered waveform sequence
"""
nyquist = fs // 2
norm_cutoff = cutoff / nyquist
# low cut filter
fil = firwin(255, norm_cutoff, pass_zero=False)
lcf_x = lfilter(fil, 1, x)
return lcf_x
def _design(self):
# Compute the order and Kaiser parameter for the FIR filter.
N, beta = signal.kaiserord(self.ripple_db,
self.bandwidth / self.fs * 2)
# Use firwin with a Kaiser window to create a lowpass FIR filter.
fir = signal.firwin(N, self.fc / self.fs * 2, window=('kaiser', beta))
# the filter must be symmetric, in order to be zero-phase
assert np.all(np.abs(fir - fir[::-1]) < 1e-15)
self.fir = fir / np.sum(fir)
return self
def bandpass_filter(data, lowcut=None, highcut=None, *, numtaps=None,
fs=None):
"""Band filter data using a zero phase FIR filter (filtfilt).
Parameters
----------
data : AnalogSignalArray, ndarray, or list
lowcut : float, optional (default 1 Hz)
Lower cut-off frequency
highcut : float, optional (default 600 Hz)
Upper cut-off frequency
numtaps : int, optional (default 25)
Number of filter taps
fs : float, optional if AnalogSignalArray is passed
Sampling frequency (Hz)
Returns
-------
filtered : same type as data
"""
if numtaps is None:
numtaps = 25
if lowcut is None:
lowcut = 1
if highcut is None:
highcut = 600
if isinstance(data, (np.ndarray, list)):
if fs is None:
raise ValueError("sampling frequency must be specified!")
# Generate filter for detection
b = firwin(numtaps=numtaps,
cutoff=[lowcut/(fs/2), highcut/(fs/2)],
pass_zero=False)
# Filter raw data to get ripple data
ripple_data = filtfilt(b, 1, data)
return ripple_data
elif isinstance(data, AnalogSignalArray):
if fs is None:
fs = data.fs
warnings.warn("no sampling frequency provided,"
" using fs={} Hz from AnalogSignalArray".format(fs))
# Generate filter for detection
b = firwin(numtaps=numtaps,
cutoff=[lowcut/(fs/2), highcut/(fs/2)],
pass_zero=False)
# Filter raw data to get ripple data
ripple_data = filtfilt(b,1,data.ydata)
# Return a copy of the AnalogSignalArray with the filtered data
filtered_analogsignalarray = data.copy()
filtered_analogsignalarray._ydata = ripple_data
return filtered_analogsignalarray
else:
raise TypeError(
"Unknown data type {} to filter.".format(str(type(data))))
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