text
stringlengths
1
93.6k
# Initialize coefficients matrix
sos = [[[]] for i in range(len(freq))]
# Generate coefficients for each frequency band
for idx, (lower, upper) in enumerate(zip(freq_d, freq_u)):
# Downsampling to improve filter coefficients
fsd = fs / factor[idx] # New sampling rate
# Butterworth Filter with SOS coefficients
sos[idx] = signal.butter(
N=order,
Wn=np.array([lower, upper]) / (fsd / 2),
btype='bandpass',
analog=False,
output='sos')
if show:
_showfilter(sos, freq, freq_u, freq_d, fs, factor)
return sos
def _showfilter(sos, freq, freq_u, freq_d, fs, factor):
wn = 8192
w = np.zeros([wn, len(freq)])
h = np.zeros([wn, len(freq)], dtype=np.complex_)
for idx in range(len(freq)):
fsd = fs / factor[idx] # New sampling rate
w[:, idx], h[:, idx] = signal.sosfreqz(
sos[idx],
worN=wn,
whole=False,
fs=fsd)
fig, ax = plt.subplots()
ax.semilogx(w, 20 * np.log10(abs(h) + np.finfo(float).eps), 'b')
ax.grid(which='major')
ax.grid(which='minor', linestyle=':')
ax.set_xlabel(r'Frequency [Hz]')
ax.set_ylabel('Amplitude [dB]')
ax.set_title('Second-Order Sections - Butterworth Filter')
plt.xlim(freq_d[0] * 0.8, freq_u[-1] * 1.2)
plt.ylim(-4, 1)
ax.set_xticks([16, 31.5, 63, 125, 250, 500, 1000, 2000, 4000, 8000, 16000])
ax.set_xticklabels(['16', '31.5', '63', '125', '250', '500',
'1k', '2k', '4k', '8k', '16k'])
plt.show()
def _genfreqs(limits, fraction, fs):
# Generate frequencies
freq, freq_d, freq_u = getansifrequencies(fraction, limits)
# Remove outer frequency to prevent filter error (fs/2 < freq)
freq, freq_d, freq_u = _deleteouters(freq, freq_d, freq_u, fs)
return freq, freq_d, freq_u
def normalizedfreq(fraction):
"""
Normalized frequencies for one-octave and third-octave band. [IEC
61260-1-2014]
:param fraction: Octave type, for one octave fraction=1,
for third-octave fraction=3
:type fraction: int
:returns: frequencies array
:rtype: list
"""
predefined = {1: _oneoctave(),
3: _thirdoctave(),
}
return predefined[fraction]
def _thirdoctave():
# IEC 61260 - 1 - 2014 (added 12.5, 16, 20 Hz)
return [12.5, 16, 20, 25, 31.5, 40, 50, 63, 80, 100, 125, 160, 200, 250,
315, 400, 500, 630, 800, 1000, 1250, 1600, 2000, 2500, 3150, 4000,
5000, 6300, 8000, 10000, 12500, 16000, 20000]
def _oneoctave():
# IEC 61260 - 1 - 2014 (added 16 Hz)
return [16, 31.5, 63, 125, 250, 500, 1000, 2000, 4000, 8000, 16000]
def _deleteouters(freq, freq_d, freq_u, fs):
idx = np.asarray(np.where(np.array(freq_u) > fs / 2))
if any(idx[0]):
_printwarn('Low sampling rate, frequencies above fs/2 will be removed')
freq = np.delete(freq, idx).tolist()
freq_d = np.delete(freq_d, idx).tolist()
freq_u = np.delete(freq_u, idx).tolist()
return freq, freq_d, freq_u
def getansifrequencies(fraction, limits=None):
""" ANSI s1.11-2004 && IEC 61260-1-2014
Array of frequencies and its edges according to the ANSI and IEC standard.