diff --git a/changelog.d/filter-gain-frequency.rst b/changelog.d/filter-gain-frequency.rst new file mode 100644 index 00000000..df4094a3 --- /dev/null +++ b/changelog.d/filter-gain-frequency.rst @@ -0,0 +1,4 @@ +**Evaluate filter gain at the requested frequency** + ``processing.get_filter_gain`` no longer rounds up to a fixed frequency grid. + This also fixes an ``IndexError`` at the Nyquist frequency and frequencies + just below it. diff --git a/src/wfdb/processing/basic.py b/src/wfdb/processing/basic.py index 4902bbc5..878d2c30 100644 --- a/src/wfdb/processing/basic.py +++ b/src/wfdb/processing/basic.py @@ -245,9 +245,10 @@ def get_filter_gain(b, a, f_gain, fs): List of linear filter b coefficients. a : list List of linear filter a coefficients. - f_gain : int, float, optional - The frequency at which to calculate the gain. - fs : int, float, optional + f_gain : int, float + The frequency at which to calculate the gain, in the same units as + `fs`. Evaluated at this frequency, including the Nyquist frequency. + fs : int, float The sampling frequency of the system. Returns @@ -256,14 +257,9 @@ def get_filter_gain(b, a, f_gain, fs): The passband gain at the desired frequency. """ - # Save the passband gain - w, h = signal.freqz(b, a) w_gain = f_gain * 2 * np.pi / fs - - ind = np.where(w >= w_gain)[0][0] - gain = abs(h[ind]) - - return gain + _, h = signal.freqz(b, a, worN=[w_gain]) + return abs(h[0]) def normalize(X): diff --git a/tests/test_filter_gain.py b/tests/test_filter_gain.py new file mode 100644 index 00000000..4c6f059a --- /dev/null +++ b/tests/test_filter_gain.py @@ -0,0 +1,29 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose + +from wfdb import processing + + +@pytest.mark.parametrize("fs", [250, 1000]) +@pytest.mark.parametrize("fraction", [0, 0.1234, 0.4999, 0.5]) +@pytest.mark.parametrize( + "b,a,expected", + [ + ([1], [1], lambda w: 1), + ([0.5, 0.5], [1], lambda w: abs(np.cos(w / 2))), + ([1, -1], [1], lambda w: 2 * abs(np.sin(w / 2))), + ([1], [1, -0.5], lambda w: 1 / np.sqrt(1.25 - np.cos(w))), + ], +) +def test_filter_gain_at_requested_frequency(fs, fraction, b, a, expected): + """Measure analytic FIR/IIR responses via the public processing API.""" + frequency = fraction * fs + omega = 2 * np.pi * fraction + original_b, original_a = b.copy(), a.copy() + + gain = processing.get_filter_gain(b, a, frequency, fs) + + assert_allclose(gain, expected(omega), rtol=1e-12, atol=1e-14) + assert b == original_b + assert a == original_a