From b8e23f422a085b45cbce1ef3314623d54e5660ff Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Sun, 22 Nov 2026 21:23:06 -0500 Subject: [PATCH 1/2] Compute the GQRS filters for the whole signal at once GQRS called qf() once per sample, and qf() called sm(), each doing a few dozen operations on NumPy scalars. After the first few samples, both are running sums of integers: sm() adds and subtracts four samples to the previous smoothed value, and qf() adds a combination of smoothed values to the previous filter output. On the first call where the running sums have started, compute the outputs of qf() for every remaining call with cumulative sums, giving the same integers. Each call then only stores the next output in the buffer. The rest of the state that qf() and sm() update (the smoothed value buffer, v1, smt, sample_valid, SIG_SMOOTH and SIG_QRS) is set when the last output is used, or if the calls stop following on from each other, in which case qf() takes over. Signals that are not integers, and outputs that would overflow, are left to qf() as before. The main loop also reads the filter output buffer directly instead of through qfv_at(). On MIT-BIH record 100, gqrs_detect takes 0.36 s instead of 1.4 s. --- changelog.d/gqrs-speed.rst | 2 + src/wfdb/processing/qrs.py | 152 ++++++++++++++++++++++++++++++++++++- tests/test_processing.py | 66 ++++++++++++++++ 3 files changed, 217 insertions(+), 3 deletions(-) create mode 100644 changelog.d/gqrs-speed.rst diff --git a/changelog.d/gqrs-speed.rst b/changelog.d/gqrs-speed.rst new file mode 100644 index 00000000..de8e6de4 --- /dev/null +++ b/changelog.d/gqrs-speed.rst @@ -0,0 +1,2 @@ +**Speed up gqrs_detect** + ``gqrs_detect`` now computes its smoothing and QRS matched filters for the whole signal with NumPy, instead of one sample at a time in Python, and is about 4 times faster (0.36 seconds instead of 1.4 for the 30-minute MIT-BIH record 100). The detected QRS locations are unchanged. diff --git a/src/wfdb/processing/qrs.py b/src/wfdb/processing/qrs.py index 38c7f255..8b28a180 100644 --- a/src/wfdb/processing/qrs.py +++ b/src/wfdb/processing/qrs.py @@ -1003,6 +1003,8 @@ def detect(self, x, conf, adc_zero): self.qfv = np.zeros((self.c._BUFLN), dtype="int64") self.smv = np.zeros((self.c._BUFLN), dtype="int64") self.v1 = 0 + # Filter outputs computed ahead by _qf_ahead, if any + self._ahead = None t0 = 0 self.tf = len(x) - 1 @@ -1228,6 +1230,9 @@ def qf(self): N/A """ + if self._qf_ahead(): + return + # Do this first, to ensure that all of the other smoothed values # needed below are in the buffer dv2 = self.sm(self.t + self.c.dt4) @@ -1245,6 +1250,144 @@ def qf(self): self.qfv_put(self.t, v0 * v0) self.SIG_QRS.append(v0**2) + def _qf_ahead(self): + """Evaluate qf() from filter outputs computed for the rest of the signal. + + After the first few samples, sm() and qf() are running sums that + qf() advances by one sample per call, which is slow in Python. On + the first call in that state, this computes their outputs for all + of the remaining calls with NumPy, giving the same integers. Each + call then stores the next output in the buffer, as qf() would. The + rest of the state that qf() updates is set when the last output is + used, since only qf() and sm() read it. + + Returns + ------- + bool + Whether qf() was evaluated. If not, qf() is evaluated as usual. + + """ + ahead = self._ahead + if ahead is None: + ahead = self._compute_ahead() + if ahead is None: + # The running sums have not started yet + return False + self._ahead = ahead + if not ahead: + return False + + k = self.t - ahead["t0"] + if k != ahead["used"]: + # The calls did not follow on from each other, so go back to + # qf() from here on, with the state it expects + self._finish_ahead(ahead) + return False + self.qfv[self.t & ahead["mask"]] = ahead["qfv_list"][k] + ahead["used"] = k + 1 + if k == ahead["last"]: + self._finish_ahead(ahead) + return True + + def _compute_ahead(self): + """Compute the outputs of qf() for every remaining call. + + Returns + ------- + dict, bool or None + The outputs and the information needed to use them, None if + the running sums have not started yet, or False if the outputs + cannot be computed this way (for example, for a signal that is + not made of integers). + + """ + c = self.c + t0 = self.t + smt = c.smt + if smt <= int(c.smt0): + return None + smdt = int(c.smdt) + x = np.asarray(self.x) + # A float signal is rounded at every step of sm(), so it cannot be + # summed ahead. Unsigned 64-bit integers do not mix with int64. + if not (x.dtype.kind == "i" or (x.dtype.kind == "u" and x.dtype.itemsize < 8)): + return False + tf = len(x) - 1 + # qf() is called once per sample until sm() reads past the end of + # the signal, after the call at t_last + t_last = tf - 3 * c.dt + 2 + if smt != t0 + c.dt4 - 1 or t_last < t0: + return False + + # Smoothed values, for samples t0 - dt4 to t_last + dt4. Those up to + # smt are already in the buffer. Later ones are the running sum in + # sm(), with samples before the start or after the end taken from + # the first or last sample, as in at(). + lo = t0 - c.dt4 + hi = t_last + c.dt4 + mask = c._BUFLN - 1 + known = self.smv[np.arange(lo, smt + 1) & mask] + s = np.arange(smt + 1, hi + 1) + x = x.astype(np.int64) + + def at(t): + return x[np.clip(t, 0, tf)] + + step = at(s + smdt) + at(s + smdt - 1) - at(s - smdt) - at(s - smdt - 1) + new = self.smv[smt & mask] + np.cumsum(step) + smv = np.concatenate([known, new]) + + t = np.arange(t0, t_last + 1) - lo + + def diff(d): + return smv[t + d] - smv[t - d] + + dv1 = diff(c.dt) + dv = (((dv1 << 1) - diff(c.dt2)) << 1) + dv1 - diff(c.dt3) + dv = (dv << 1) + diff(c.dt4) + v1 = self.v1 + np.cumsum(dv) + v0 = np.trunc(v1 / c.v1norm).astype(np.int64) + # qf() stores v0 * v0 in an int64 buffer, which raises an + # OverflowError if it is too large. Leave that to qf(). + if np.any(np.abs(v0) > 3037000499): + return False + qfv = (v0 * v0).tolist() + + return { + "t0": t0, + "last": len(qfv) - 1, + "used": 0, + "mask": mask, + "lo": lo, + "smv": smv, + "new": new, + "v1": v1, + "qfv_list": qfv, + } + + def _finish_ahead(self, ahead): + """Stop using the outputs computed ahead, leaving the state as qf() would. + + The state is set as after the last output that was used: the + smoothed values go into the buffer, and the outputs into SIG_SMOOTH + and SIG_QRS. + + """ + used = ahead["used"] + c = self.c + c.smt = ahead["t0"] + c.dt4 - 1 + used + self.v1 = ahead["v1"][used - 1] + # sm() last reads the sample at smt - smdt - 1, which is past the + # end of the signal after the last output + if used - 1 == ahead["last"]: + self.sample_valid = False + start = max(ahead["lo"], c.smt - c._BUFLN + 1) + i = np.arange(start, c.smt + 1) + self.smv[i & ahead["mask"]] = ahead["smv"][i - ahead["lo"]] + self.SIG_SMOOTH.extend(ahead["new"][:used].tolist()) + self.SIG_QRS.extend(ahead["qfv_list"][:used]) + self._ahead = False + def gqrs(self, from_sample, to_sample): """The GQRS algorithm. @@ -1402,6 +1545,8 @@ def find_missing(r, p): r = None next_minute = 0 minutes = 0 + qfv = self.qfv + mask = self.c._BUFLN - 1 while self.t <= to_sample + self.c.sps: if self.countdown < 0: if self.sample_valid: @@ -1414,9 +1559,10 @@ def find_missing(r, p): if self.countdown < 0: break - q0 = self.qfv_at(self.t) - q1 = self.qfv_at(self.t - 1) - q2 = self.qfv_at(self.t - 2) + # The same as qfv_at(), without the cost of a method call + q0 = qfv[self.t & mask] + q1 = qfv[(self.t - 1) & mask] + q2 = qfv[(self.t - 2) & mask] # state == RUNNING only if q1 > self.c.pthr and q2 < q1 and q1 >= q0 and self.t > self.c.dt4: add_peak(self.t - 1, q1, 0) diff --git a/tests/test_processing.py b/tests/test_processing.py index 21e5f876..50932fa6 100644 --- a/tests/test_processing.py +++ b/tests/test_processing.py @@ -172,6 +172,72 @@ def test_gqrs(self): assert np.array_equal(peaks, expected_peaks) + @staticmethod + def _run_gqrs(x, fs, adc_gain, adc_zero): + """Run GQRS, and return its annotations and final state.""" + conf = processing.qrs.GQRS.Conf(fs=fs, adc_gain=adc_gain) + gqrs = processing.qrs.GQRS() + annotations = gqrs.detect(x=x, conf=conf, adc_zero=adc_zero) + return ( + [(a.time, a.type, a.subtype, a.num) for a in annotations], + vars(conf), + gqrs.smv.tolist(), + gqrs.qfv.tolist(), + int(gqrs.v1), + gqrs.SIG_SMOOTH, + gqrs.SIG_QRS, + ) + + @pytest.mark.parametrize( + ("record_name", "channel", "fs"), + [("100", 0, None), ("100", 1, None), ("12726", 0, None), ("100", 0, 60)], + ) + def test_gqrs_filters_computed_ahead(self, monkeypatch, record_name, channel, fs): + """Computing the filters ahead gives the same result as qf() and sm().""" + record = wfdb.rdrecord( + f"sample-data/{record_name}", + channels=[channel], + sampto=100000, + physical=False, + ) + x = record.d_signal[:, 0] + if fs is not None: + # A low sampling frequency, where the filters are shortest + x = x[:: round(record.fs / fs)] + else: + fs = record.fs + args = (x, fs, record.adc_gain[0], record.adc_zero[0]) + computed = [] + compute = processing.qrs.GQRS._compute_ahead + + def record_computed(self): + result = compute(self) + computed.append(result) + return result + + with monkeypatch.context() as m: + m.setattr(processing.qrs.GQRS, "_compute_ahead", record_computed) + ahead = self._run_gqrs(*args) + # The filters were computed ahead, once the running sums started + assert any(isinstance(result, dict) for result in computed) + + with monkeypatch.context() as m: + m.setattr(processing.qrs.GQRS, "_compute_ahead", lambda self: False) + expected = self._run_gqrs(*args) + assert ahead == expected + assert len(ahead[0]) > 10 + + # Stop using the filters computed ahead partway through + use = processing.qrs.GQRS._qf_ahead + + def stop_early(self): + if self._ahead and self._ahead["used"] == 5000: + self._finish_ahead(self._ahead) + return use(self) + + monkeypatch.setattr(processing.qrs.GQRS, "_qf_ahead", stop_early) + assert self._run_gqrs(*args) == expected + def test_correct_peaks(self): sig, fields = wfdb.rdsamp("sample-data/100") ann = wfdb.rdann("sample-data/100", "atr") From a3b37df35841a9e08e204675dc684aed321fc5b9 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Sun, 22 Nov 2026 23:23:15 -0500 Subject: [PATCH 2/2] Compute the GQRS filters ahead in chunks _compute_ahead computed the filter outputs for the whole rest of the signal at once, and kept several full-length arrays until the last output was used. For 2 million samples, this raised the peak memory use of GQRS from 168 MB to 328 MB. Compute the outputs for 32,768 calls at a time instead. At the end of each chunk, the state is set as qf() would leave it, and the next chunk continues from there. Only the samples that sm() reads for the chunk are converted to int64, and the input is converted to an array once. For 2 million samples, the peak memory use is now 187 MB (168 MB on main), and detection still takes 0.9 s (4.2 s on main). --- src/wfdb/processing/qrs.py | 47 +++++++++++++++++++++++++------------- tests/test_processing.py | 46 +++++++++++++++++++++++++++++++++---- 2 files changed, 73 insertions(+), 20 deletions(-) diff --git a/src/wfdb/processing/qrs.py b/src/wfdb/processing/qrs.py index 8b28a180..4e5b08b9 100644 --- a/src/wfdb/processing/qrs.py +++ b/src/wfdb/processing/qrs.py @@ -1005,6 +1005,7 @@ def detect(self, x, conf, adc_zero): self.v1 = 0 # Filter outputs computed ahead by _qf_ahead, if any self._ahead = None + self._x_array = None t0 = 0 self.tf = len(x) - 1 @@ -1251,15 +1252,16 @@ def qf(self): self.SIG_QRS.append(v0**2) def _qf_ahead(self): - """Evaluate qf() from filter outputs computed for the rest of the signal. + """Evaluate qf() from filter outputs computed ahead. After the first few samples, sm() and qf() are running sums that qf() advances by one sample per call, which is slow in Python. On - the first call in that state, this computes their outputs for all - of the remaining calls with NumPy, giving the same integers. Each - call then stores the next output in the buffer, as qf() would. The - rest of the state that qf() updates is set when the last output is - used, since only qf() and sm() read it. + the first call in that state, this computes their outputs for the + next `_AHEAD_CHUNK_SIZE` calls with NumPy, giving the same integers, + and then the next chunk when those have been used. Each call stores + the next output in the buffer, as qf() would. The rest of the state + that qf() updates is set at the end of each chunk, since only qf() + and sm() read it. Returns ------- @@ -1282,15 +1284,22 @@ def _qf_ahead(self): # The calls did not follow on from each other, so go back to # qf() from here on, with the state it expects self._finish_ahead(ahead) + self._ahead = False return False self.qfv[self.t & ahead["mask"]] = ahead["qfv_list"][k] ahead["used"] = k + 1 if k == ahead["last"]: self._finish_ahead(ahead) + # Compute the next chunk on the next call, unless this was the + # last call + self._ahead = False if ahead["final"] else None return True + # The number of qf() outputs that _qf_ahead computes at a time + _AHEAD_CHUNK_SIZE = 32768 + def _compute_ahead(self): - """Compute the outputs of qf() for every remaining call. + """Compute the outputs of qf() for the next chunk of calls. Returns ------- @@ -1307,7 +1316,9 @@ def _compute_ahead(self): if smt <= int(c.smt0): return None smdt = int(c.smdt) - x = np.asarray(self.x) + if self._x_array is None: + self._x_array = np.asarray(self.x) + x = self._x_array # A float signal is rounded at every step of sm(), so it cannot be # summed ahead. Unsigned 64-bit integers do not mix with int64. if not (x.dtype.kind == "i" or (x.dtype.kind == "u" and x.dtype.itemsize < 8)): @@ -1318,26 +1329,30 @@ def _compute_ahead(self): t_last = tf - 3 * c.dt + 2 if smt != t0 + c.dt4 - 1 or t_last < t0: return False + t_stop = min(t_last, t0 + self._AHEAD_CHUNK_SIZE - 1) - # Smoothed values, for samples t0 - dt4 to t_last + dt4. Those up to + # Smoothed values, for samples t0 - dt4 to t_stop + dt4. Those up to # smt are already in the buffer. Later ones are the running sum in # sm(), with samples before the start or after the end taken from # the first or last sample, as in at(). lo = t0 - c.dt4 - hi = t_last + c.dt4 + hi = t_stop + c.dt4 mask = c._BUFLN - 1 known = self.smv[np.arange(lo, smt + 1) & mask] s = np.arange(smt + 1, hi + 1) - x = x.astype(np.int64) + # The samples that sm() reads for this chunk + x_lo = min(max(smt - smdt, 0), tf) + x_hi = min(max(hi + smdt, 0), tf) + x = x[x_lo : x_hi + 1].astype(np.int64) def at(t): - return x[np.clip(t, 0, tf)] + return x[np.clip(t, 0, tf) - x_lo] step = at(s + smdt) + at(s + smdt - 1) - at(s - smdt) - at(s - smdt - 1) new = self.smv[smt & mask] + np.cumsum(step) smv = np.concatenate([known, new]) - t = np.arange(t0, t_last + 1) - lo + t = np.arange(t0, t_stop + 1) - lo def diff(d): return smv[t + d] - smv[t - d] @@ -1356,6 +1371,7 @@ def diff(d): return { "t0": t0, "last": len(qfv) - 1, + "final": t_stop == t_last, "used": 0, "mask": mask, "lo": lo, @@ -1366,7 +1382,7 @@ def diff(d): } def _finish_ahead(self, ahead): - """Stop using the outputs computed ahead, leaving the state as qf() would. + """Set the state as qf() would after the outputs computed ahead. The state is set as after the last output that was used: the smoothed values go into the buffer, and the outputs into SIG_SMOOTH @@ -1379,14 +1395,13 @@ def _finish_ahead(self, ahead): self.v1 = ahead["v1"][used - 1] # sm() last reads the sample at smt - smdt - 1, which is past the # end of the signal after the last output - if used - 1 == ahead["last"]: + if ahead["final"] and used - 1 == ahead["last"]: self.sample_valid = False start = max(ahead["lo"], c.smt - c._BUFLN + 1) i = np.arange(start, c.smt + 1) self.smv[i & ahead["mask"]] = ahead["smv"][i - ahead["lo"]] self.SIG_SMOOTH.extend(ahead["new"][:used].tolist()) self.SIG_QRS.extend(ahead["qfv_list"][:used]) - self._ahead = False def gqrs(self, from_sample, to_sample): """The GQRS algorithm. diff --git a/tests/test_processing.py b/tests/test_processing.py index 50932fa6..4708ac51 100644 --- a/tests/test_processing.py +++ b/tests/test_processing.py @@ -1,4 +1,5 @@ import math +import tracemalloc from unittest import mock import numpy as np @@ -189,15 +190,28 @@ def _run_gqrs(x, fs, adc_gain, adc_zero): ) @pytest.mark.parametrize( - ("record_name", "channel", "fs"), - [("100", 0, None), ("100", 1, None), ("12726", 0, None), ("100", 0, 60)], + ("record_name", "channel", "fs", "sampto", "chunk_size"), + [ + ("100", 0, None, 100000, None), + ("100", 1, None, 100000, None), + ("12726", 0, None, 100000, None), + ("100", 0, 60, 100000, None), + # Chunks that end at many different points in the signal + ("100", 0, None, 100000, 1000), + ("100", 0, None, 5000, 7), + ("100", 0, None, 5000, 1), + ], ) - def test_gqrs_filters_computed_ahead(self, monkeypatch, record_name, channel, fs): + def test_gqrs_filters_computed_ahead( + self, monkeypatch, record_name, channel, fs, sampto, chunk_size + ): """Computing the filters ahead gives the same result as qf() and sm().""" + if chunk_size is not None: + monkeypatch.setattr(processing.qrs.GQRS, "_AHEAD_CHUNK_SIZE", chunk_size) record = wfdb.rdrecord( f"sample-data/{record_name}", channels=[channel], - sampto=100000, + sampto=sampto, physical=False, ) x = record.d_signal[:, 0] @@ -233,11 +247,35 @@ def record_computed(self): def stop_early(self): if self._ahead and self._ahead["used"] == 5000: self._finish_ahead(self._ahead) + self._ahead = False return use(self) monkeypatch.setattr(processing.qrs.GQRS, "_qf_ahead", stop_early) assert self._run_gqrs(*args) == expected + def test_gqrs_filters_computed_ahead_memory(self, monkeypatch): + """The filters for a long signal are computed in chunks of bounded size.""" + peaks = [] + compute = processing.qrs.GQRS._compute_ahead + + def measure(self): + tracemalloc.start() + try: + result = compute(self) + peaks.append(tracemalloc.get_traced_memory()[1]) + finally: + tracemalloc.stop() + return result + + monkeypatch.setattr(processing.qrs.GQRS, "_compute_ahead", measure) + x = np.zeros(1_000_000, dtype=np.int16) + processing.gqrs_detect(d_sig=x, fs=360, adc_gain=200, adc_zero=0) + + # Computing the whole signal at once used about 85 bytes per sample + chunk_size = processing.qrs.GQRS._AHEAD_CHUNK_SIZE + assert len(peaks) > len(x) // chunk_size + assert max(peaks) < 8 * 2**20 + def test_correct_peaks(self): sig, fields = wfdb.rdsamp("sample-data/100") ann = wfdb.rdann("sample-data/100", "atr")