Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions changelog.d/filter-gain-frequency.rst
Original file line number Diff line number Diff line change
@@ -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.
16 changes: 6 additions & 10 deletions src/wfdb/processing/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand Down
29 changes: 29 additions & 0 deletions tests/test_filter_gain.py
Original file line number Diff line number Diff line change
@@ -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
Loading