biosigpy 0.3.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- biosigpy/__init__.py +43 -0
- biosigpy/_version.py +3 -0
- biosigpy/ecg/__init__.py +18 -0
- biosigpy/ecg/baselineremove.py +164 -0
- biosigpy/ecg/pantompkins.py +160 -0
- biosigpy/ecg/sloperange.py +192 -0
- biosigpy/hrv/__init__.py +28 -0
- biosigpy/hrv/_fillgaps_debug.py +204 -0
- biosigpy/hrv/fdmetrics.py +301 -0
- biosigpy/hrv/fillgaps.py +403 -0
- biosigpy/hrv/ipfm.py +196 -0
- biosigpy/hrv/osp.py +261 -0
- biosigpy/hrv/removefp.py +65 -0
- biosigpy/hrv/tdmetrics.py +114 -0
- biosigpy/tools/__init__.py +15 -0
- biosigpy/tools/_nan_processing.py +133 -0
- biosigpy/tools/_validation.py +61 -0
- biosigpy/tools/lpd_filter.py +220 -0
- biosigpy/tools/medfilt_threshold.py +94 -0
- biosigpy/tools/nan_filter.py +67 -0
- biosigpy/tools/nan_filtfilt.py +89 -0
- biosigpy/tools/snap_to_peak.py +118 -0
- biosigpy-0.3.1.dist-info/METADATA +59 -0
- biosigpy-0.3.1.dist-info/RECORD +27 -0
- biosigpy-0.3.1.dist-info/WHEEL +5 -0
- biosigpy-0.3.1.dist-info/licenses/LICENSE +674 -0
- biosigpy-0.3.1.dist-info/top_level.txt +1 -0
biosigpy/__init__.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Python implementations of Biosiglib biomedical signal algorithms."""
|
|
2
|
+
|
|
3
|
+
from biosigpy._version import __version__
|
|
4
|
+
from biosigpy.ecg.baselineremove import (
|
|
5
|
+
BaselineRemoveResult,
|
|
6
|
+
BaselineRemoveWarning,
|
|
7
|
+
baselineremove,
|
|
8
|
+
)
|
|
9
|
+
from biosigpy.ecg.pantompkins import pantompkins
|
|
10
|
+
from biosigpy.ecg.sloperange import SlopeRangeResult, sloperange
|
|
11
|
+
from biosigpy.hrv.fillgaps import FillGapsResult, fillgaps
|
|
12
|
+
from biosigpy.hrv.fdmetrics import (
|
|
13
|
+
FdMetricsResult,
|
|
14
|
+
FdMetricsWarning,
|
|
15
|
+
SeparatedFdMetricsResult,
|
|
16
|
+
fdmetrics,
|
|
17
|
+
)
|
|
18
|
+
from biosigpy.hrv.ipfm import IpfmResult, ipfm
|
|
19
|
+
from biosigpy.hrv.osp import OspResult, osp
|
|
20
|
+
from biosigpy.hrv.removefp import removefp
|
|
21
|
+
from biosigpy.hrv.tdmetrics import tdmetrics
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"BaselineRemoveResult",
|
|
25
|
+
"BaselineRemoveWarning",
|
|
26
|
+
"FillGapsResult",
|
|
27
|
+
"FdMetricsResult",
|
|
28
|
+
"FdMetricsWarning",
|
|
29
|
+
"IpfmResult",
|
|
30
|
+
"OspResult",
|
|
31
|
+
"SeparatedFdMetricsResult",
|
|
32
|
+
"SlopeRangeResult",
|
|
33
|
+
"__version__",
|
|
34
|
+
"baselineremove",
|
|
35
|
+
"fdmetrics",
|
|
36
|
+
"fillgaps",
|
|
37
|
+
"ipfm",
|
|
38
|
+
"osp",
|
|
39
|
+
"pantompkins",
|
|
40
|
+
"removefp",
|
|
41
|
+
"sloperange",
|
|
42
|
+
"tdmetrics",
|
|
43
|
+
]
|
biosigpy/_version.py
ADDED
biosigpy/ecg/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Electrocardiogram signal-processing algorithms."""
|
|
2
|
+
|
|
3
|
+
from biosigpy.ecg.baselineremove import (
|
|
4
|
+
BaselineRemoveResult,
|
|
5
|
+
BaselineRemoveWarning,
|
|
6
|
+
baselineremove,
|
|
7
|
+
)
|
|
8
|
+
from biosigpy.ecg.pantompkins import pantompkins
|
|
9
|
+
from biosigpy.ecg.sloperange import SlopeRangeResult, sloperange
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"BaselineRemoveResult",
|
|
13
|
+
"BaselineRemoveWarning",
|
|
14
|
+
"SlopeRangeResult",
|
|
15
|
+
"baselineremove",
|
|
16
|
+
"pantompkins",
|
|
17
|
+
"sloperange",
|
|
18
|
+
]
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""ECG baseline removal from fiducial isoelectric samples."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import warnings
|
|
6
|
+
from typing import NamedTuple
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from numpy.typing import ArrayLike
|
|
10
|
+
from scipy.interpolate import CubicSpline
|
|
11
|
+
|
|
12
|
+
from biosigpy.tools._validation import as_integer_scalar, as_real_vector
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"BaselineRemoveResult",
|
|
17
|
+
"BaselineRemoveWarning",
|
|
18
|
+
"baselineremove",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class BaselineRemoveResult(NamedTuple):
|
|
23
|
+
"""Named, unpackable result of :func:`baselineremove`."""
|
|
24
|
+
|
|
25
|
+
ecg_detrended: np.ndarray
|
|
26
|
+
baseline: np.ndarray
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class BaselineRemoveWarning(UserWarning):
|
|
30
|
+
"""Structured Biosiglib diagnostic emitted by :func:`baselineremove`."""
|
|
31
|
+
|
|
32
|
+
def __init__(self) -> None:
|
|
33
|
+
self.warning_id = "no_valid_fiducial_positions"
|
|
34
|
+
self.affected_ids = ("fiducial_positions",)
|
|
35
|
+
super().__init__(
|
|
36
|
+
"no_valid_fiducial_positions; "
|
|
37
|
+
"affected_ids: fiducial_positions"
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def baselineremove(
|
|
42
|
+
ecg: ArrayLike,
|
|
43
|
+
fiducial_positions: ArrayLike,
|
|
44
|
+
offset: int,
|
|
45
|
+
window_size: int = 5,
|
|
46
|
+
) -> BaselineRemoveResult:
|
|
47
|
+
"""Remove an ECG baseline estimated at supplied fiducial positions.
|
|
48
|
+
|
|
49
|
+
Parameters
|
|
50
|
+
----------
|
|
51
|
+
ecg : array_like
|
|
52
|
+
Non-empty one-dimensional finite real ECG signal.
|
|
53
|
+
fiducial_positions : array_like
|
|
54
|
+
Non-empty positive finite positions on the canonical one-based sample
|
|
55
|
+
grid. Fractional, unordered, and repeated positions are accepted.
|
|
56
|
+
offset : int
|
|
57
|
+
Nonnegative sample offset subtracted before position rounding.
|
|
58
|
+
window_size : int, default=5
|
|
59
|
+
Positive nominal averaging-window size. Even values produce a
|
|
60
|
+
symmetric effective span of ``window_size + 1`` samples away from
|
|
61
|
+
signal boundaries.
|
|
62
|
+
|
|
63
|
+
Returns
|
|
64
|
+
-------
|
|
65
|
+
BaselineRemoveResult
|
|
66
|
+
Named result containing the detrended ECG and estimated baseline as
|
|
67
|
+
one-dimensional arrays aligned with ``ecg``.
|
|
68
|
+
|
|
69
|
+
Warns
|
|
70
|
+
-----
|
|
71
|
+
BaselineRemoveWarning
|
|
72
|
+
If no adjusted fiducial position lies inside the signal. The original
|
|
73
|
+
ECG and an all-zero baseline are returned.
|
|
74
|
+
|
|
75
|
+
Raises
|
|
76
|
+
------
|
|
77
|
+
TypeError
|
|
78
|
+
If a vector is non-numeric or complex, or a scalar is not an integer.
|
|
79
|
+
ValueError
|
|
80
|
+
If a vector is empty, has an invalid shape or nonfinite values, a
|
|
81
|
+
scalar is outside its allowed range, or exactly one valid fiducial
|
|
82
|
+
position remains.
|
|
83
|
+
|
|
84
|
+
Notes
|
|
85
|
+
-----
|
|
86
|
+
Positions are rounded half away from zero after subtracting ``offset``.
|
|
87
|
+
Two valid positions define a line, three define a quadratic, and four or
|
|
88
|
+
more define a cubic not-a-knot spline. The end pieces extrapolate over ECG
|
|
89
|
+
samples outside the first and last valid positions.
|
|
90
|
+
|
|
91
|
+
Examples
|
|
92
|
+
--------
|
|
93
|
+
>>> result = baselineremove([2, 4, 8, 16, 32], [1, 5], 0, 2)
|
|
94
|
+
>>> result.baseline
|
|
95
|
+
array([ 3. , 8.25, 13.5 , 18.75, 24. ])
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
signal = as_real_vector(ecg, name="ecg")
|
|
99
|
+
if signal.size == 0:
|
|
100
|
+
raise ValueError("ecg must not be empty")
|
|
101
|
+
if not np.all(np.isfinite(signal)):
|
|
102
|
+
raise ValueError("ecg must contain only finite values")
|
|
103
|
+
|
|
104
|
+
positions = as_real_vector(
|
|
105
|
+
fiducial_positions, name="fiducial_positions"
|
|
106
|
+
)
|
|
107
|
+
if positions.size == 0:
|
|
108
|
+
raise ValueError("fiducial_positions must not be empty")
|
|
109
|
+
if not np.all(np.isfinite(positions)):
|
|
110
|
+
raise ValueError(
|
|
111
|
+
"fiducial_positions must contain only finite values"
|
|
112
|
+
)
|
|
113
|
+
if np.any(positions <= 0.0):
|
|
114
|
+
raise ValueError("fiducial_positions must be positive")
|
|
115
|
+
|
|
116
|
+
offset_value = as_integer_scalar(offset, name="offset")
|
|
117
|
+
if offset_value < 0:
|
|
118
|
+
raise ValueError("offset must be nonnegative")
|
|
119
|
+
window_value = as_integer_scalar(window_size, name="window_size")
|
|
120
|
+
if window_value <= 0:
|
|
121
|
+
raise ValueError("window_size must be positive")
|
|
122
|
+
|
|
123
|
+
adjusted_positions = _round_half_away_from_zero(
|
|
124
|
+
positions - offset_value
|
|
125
|
+
)
|
|
126
|
+
valid_positions = np.unique(
|
|
127
|
+
adjusted_positions[
|
|
128
|
+
(adjusted_positions >= 1) &
|
|
129
|
+
(adjusted_positions <= signal.size)
|
|
130
|
+
]
|
|
131
|
+
).astype(np.intp)
|
|
132
|
+
|
|
133
|
+
if valid_positions.size == 0:
|
|
134
|
+
warnings.warn(BaselineRemoveWarning(), stacklevel=2)
|
|
135
|
+
return BaselineRemoveResult(signal.copy(), np.zeros_like(signal))
|
|
136
|
+
if valid_positions.size == 1:
|
|
137
|
+
raise ValueError("at least two valid fiducial positions are required")
|
|
138
|
+
|
|
139
|
+
radius = window_value // 2
|
|
140
|
+
fiducial_levels = np.asarray(
|
|
141
|
+
[
|
|
142
|
+
np.mean(
|
|
143
|
+
signal[
|
|
144
|
+
max(0, int(position) - 1 - radius):
|
|
145
|
+
min(signal.size, int(position) + radius)
|
|
146
|
+
]
|
|
147
|
+
)
|
|
148
|
+
for position in valid_positions
|
|
149
|
+
],
|
|
150
|
+
dtype=np.float64,
|
|
151
|
+
)
|
|
152
|
+
spline = CubicSpline(
|
|
153
|
+
valid_positions.astype(np.float64),
|
|
154
|
+
fiducial_levels,
|
|
155
|
+
bc_type="not-a-knot",
|
|
156
|
+
extrapolate=True,
|
|
157
|
+
)
|
|
158
|
+
sample_grid = np.arange(1, signal.size + 1, dtype=np.float64)
|
|
159
|
+
baseline = np.asarray(spline(sample_grid), dtype=np.float64)
|
|
160
|
+
return BaselineRemoveResult(signal - baseline, baseline)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _round_half_away_from_zero(values: np.ndarray) -> np.ndarray:
|
|
164
|
+
return np.copysign(np.floor(np.abs(values) + 0.5), values)
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Pan-Tompkins-style ECG R-wave detection."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from numpy.typing import ArrayLike
|
|
5
|
+
from scipy import signal
|
|
6
|
+
|
|
7
|
+
from biosigpy.tools._validation import as_positive_real_scalar, as_real_vector
|
|
8
|
+
from biosigpy.tools.lpd_filter import lpd_filter
|
|
9
|
+
from biosigpy.tools.nan_filter import nan_filter
|
|
10
|
+
from biosigpy.tools.nan_filtfilt import nan_filtfilt
|
|
11
|
+
from biosigpy.tools.snap_to_peak import snap_to_peak
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def pantompkins(
|
|
15
|
+
ecg: ArrayLike,
|
|
16
|
+
sampling_frequency: float,
|
|
17
|
+
*,
|
|
18
|
+
bandpass_frequency: ArrayLike = (5.0, 12.0),
|
|
19
|
+
integration_window_size: float = 0.15,
|
|
20
|
+
minimum_peak_distance: float = 0.5,
|
|
21
|
+
snap_to_peak_window_size: float = 20.0,
|
|
22
|
+
) -> dict[str, np.ndarray]:
|
|
23
|
+
"""Detect ECG R waves with the Biosiglib Pan-Tompkins workflow.
|
|
24
|
+
|
|
25
|
+
Parameters
|
|
26
|
+
----------
|
|
27
|
+
ecg : array_like
|
|
28
|
+
One-dimensional real numeric ECG signal with at least two samples.
|
|
29
|
+
Infinite values are invalid.
|
|
30
|
+
sampling_frequency : float
|
|
31
|
+
Positive sampling frequency in Hz.
|
|
32
|
+
bandpass_frequency : array_like, optional
|
|
33
|
+
Two-element bandpass frequency vector in Hz. Values must be positive,
|
|
34
|
+
strictly increasing, and inside the Nyquist range.
|
|
35
|
+
integration_window_size : float, optional
|
|
36
|
+
Moving-integration window length in seconds.
|
|
37
|
+
minimum_peak_distance : float, optional
|
|
38
|
+
Minimum distance between envelope peaks in seconds.
|
|
39
|
+
snap_to_peak_window_size : float, optional
|
|
40
|
+
Search radius in samples used when refining detections to local ECG
|
|
41
|
+
maxima.
|
|
42
|
+
|
|
43
|
+
Returns
|
|
44
|
+
-------
|
|
45
|
+
dict[str, numpy.ndarray]
|
|
46
|
+
Dictionary with ``r_wave_times`` in seconds, ``ecg_filtered``,
|
|
47
|
+
``decg_squared``, and ``decg_envelope``.
|
|
48
|
+
|
|
49
|
+
Raises
|
|
50
|
+
------
|
|
51
|
+
TypeError
|
|
52
|
+
If numeric inputs are not real numeric data.
|
|
53
|
+
ValueError
|
|
54
|
+
If inputs are outside the accepted shape, range, or positivity
|
|
55
|
+
constraints.
|
|
56
|
+
|
|
57
|
+
Notes
|
|
58
|
+
-----
|
|
59
|
+
This function follows the Biosiglib ``ecg.pantompkins`` specification. It
|
|
60
|
+
returns R-wave times and intermediate processing signals. Bandpass and
|
|
61
|
+
derivative filtering use the NaN-aware public filtering tools with
|
|
62
|
+
``max_gap=0``. Peak refinement uses
|
|
63
|
+
:func:`biosigpy.tools.snap_to_peak.snap_to_peak`, and derivative filter
|
|
64
|
+
design uses :func:`biosigpy.tools.lpd_filter.lpd_filter`.
|
|
65
|
+
|
|
66
|
+
Examples
|
|
67
|
+
--------
|
|
68
|
+
>>> import numpy as np
|
|
69
|
+
>>> from biosigpy.ecg import pantompkins
|
|
70
|
+
>>> fs = 256.0
|
|
71
|
+
>>> time = np.arange(0.0, 2.0, 1.0 / fs)
|
|
72
|
+
>>> ecg = np.sin(2.0 * np.pi * 1.2 * time)
|
|
73
|
+
>>> outputs = pantompkins(ecg, fs)
|
|
74
|
+
>>> "r_wave_times" in outputs
|
|
75
|
+
True
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
ecg_vector = _ecg_vector(ecg)
|
|
79
|
+
fs = as_positive_real_scalar(sampling_frequency, name="sampling_frequency")
|
|
80
|
+
bandpass = _bandpass_pair(bandpass_frequency, fs)
|
|
81
|
+
window_seconds = as_positive_real_scalar(
|
|
82
|
+
integration_window_size, name="integration_window_size"
|
|
83
|
+
)
|
|
84
|
+
peak_distance_seconds = as_positive_real_scalar(
|
|
85
|
+
minimum_peak_distance, name="minimum_peak_distance"
|
|
86
|
+
)
|
|
87
|
+
snap_to_peak_window_size = as_positive_real_scalar(
|
|
88
|
+
snap_to_peak_window_size, name="snap_to_peak_window_size"
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
b_bandpass, a_bandpass = signal.butter(
|
|
92
|
+
4, bandpass, btype="bandpass", fs=fs
|
|
93
|
+
)
|
|
94
|
+
ecg_filtered = nan_filtfilt(
|
|
95
|
+
b_bandpass,
|
|
96
|
+
a_bandpass,
|
|
97
|
+
ecg_vector,
|
|
98
|
+
max_gap=0,
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
derivative_filter, _ = lpd_filter(fs, bandpass[1], order=4)
|
|
102
|
+
decg = nan_filter(
|
|
103
|
+
derivative_filter,
|
|
104
|
+
[1.0],
|
|
105
|
+
ecg_filtered,
|
|
106
|
+
max_gap=0,
|
|
107
|
+
)
|
|
108
|
+
decg_squared = decg**2
|
|
109
|
+
|
|
110
|
+
window_samples = int(np.floor(fs * window_seconds + 0.5))
|
|
111
|
+
if window_samples < 1:
|
|
112
|
+
raise ValueError("integration_window_size is shorter than one sample")
|
|
113
|
+
integration_kernel = np.ones(window_samples, dtype=np.float64) / window_samples
|
|
114
|
+
decg_envelope = np.convolve(decg_squared, integration_kernel, mode="same")
|
|
115
|
+
|
|
116
|
+
minimum_distance_samples = int(np.floor(fs * peak_distance_seconds + 0.5))
|
|
117
|
+
peak_indices, _ = signal.find_peaks(
|
|
118
|
+
decg_envelope, distance=max(1, minimum_distance_samples)
|
|
119
|
+
)
|
|
120
|
+
peak_indices = np.unique(np.sort(peak_indices))
|
|
121
|
+
filter_edge_margin = 3 * max(b_bandpass.size, a_bandpass.size)
|
|
122
|
+
peak_indices = snap_to_peak(
|
|
123
|
+
ecg_vector, peak_indices.astype(np.float64) + 1.0, snap_to_peak_window_size
|
|
124
|
+
)
|
|
125
|
+
peak_indices = peak_indices[np.isfinite(peak_indices)] - 1.0
|
|
126
|
+
peak_indices = peak_indices[peak_indices >= filter_edge_margin]
|
|
127
|
+
|
|
128
|
+
return {
|
|
129
|
+
"r_wave_times": peak_indices.astype(np.float64) / fs,
|
|
130
|
+
"ecg_filtered": np.asarray(ecg_filtered, dtype=np.float64),
|
|
131
|
+
"decg_squared": np.asarray(decg_squared, dtype=np.float64),
|
|
132
|
+
"decg_envelope": np.asarray(decg_envelope, dtype=np.float64),
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _ecg_vector(ecg: ArrayLike) -> np.ndarray:
|
|
137
|
+
ecg = as_real_vector(ecg, name="ecg")
|
|
138
|
+
if ecg.size < 2:
|
|
139
|
+
raise ValueError("ecg must contain at least two samples")
|
|
140
|
+
if np.any(np.isinf(ecg)):
|
|
141
|
+
raise ValueError("ecg must not contain infinite values")
|
|
142
|
+
return ecg
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _bandpass_pair(value: ArrayLike, sampling_frequency: float) -> np.ndarray:
|
|
146
|
+
array = np.asarray(value)
|
|
147
|
+
if array.shape != (2,) or not np.issubdtype(array.dtype, np.number):
|
|
148
|
+
raise ValueError("bandpass_frequency must contain two numeric values")
|
|
149
|
+
if np.issubdtype(array.dtype, np.complexfloating):
|
|
150
|
+
raise TypeError("bandpass_frequency must be real")
|
|
151
|
+
|
|
152
|
+
bandpass = np.asarray(array, dtype=np.float64)
|
|
153
|
+
if (
|
|
154
|
+
not np.all(np.isfinite(bandpass))
|
|
155
|
+
or np.any(bandpass <= 0)
|
|
156
|
+
or bandpass[0] >= bandpass[1]
|
|
157
|
+
or bandpass[1] >= sampling_frequency / 2.0
|
|
158
|
+
):
|
|
159
|
+
raise ValueError("bandpass_frequency must lie inside the Nyquist range")
|
|
160
|
+
return bandpass
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Slope-range ECG-derived respiration."""
|
|
2
|
+
|
|
3
|
+
from typing import NamedTuple
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from numpy.typing import ArrayLike
|
|
7
|
+
|
|
8
|
+
from biosigpy.tools._validation import as_positive_real_scalar, as_real_vector
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
__all__ = ["SlopeRangeResult", "sloperange"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SlopeRangeResult(NamedTuple):
|
|
15
|
+
"""Named, unpackable result of :func:`sloperange`.
|
|
16
|
+
|
|
17
|
+
Attributes
|
|
18
|
+
----------
|
|
19
|
+
edr : numpy.ndarray
|
|
20
|
+
ECG-derived respiration amplitudes aligned with R-wave times, in the
|
|
21
|
+
same arbitrary amplitude unit as ``decg``.
|
|
22
|
+
upslopes : numpy.ndarray
|
|
23
|
+
Signal-aligned derivative ECG values inside complete upslope windows,
|
|
24
|
+
with ``NaN`` elsewhere.
|
|
25
|
+
downslopes : numpy.ndarray
|
|
26
|
+
Signal-aligned derivative ECG values inside complete downslope
|
|
27
|
+
windows, with ``NaN`` elsewhere.
|
|
28
|
+
upslope_max_positions : numpy.ndarray
|
|
29
|
+
Zero-based positions of selected upslope maxima aligned with R-wave
|
|
30
|
+
times, in samples, with ``NaN`` for incomplete beats.
|
|
31
|
+
downslope_min_positions : numpy.ndarray
|
|
32
|
+
Zero-based positions of selected downslope minima aligned with R-wave
|
|
33
|
+
times, in samples, with ``NaN`` for incomplete beats.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
edr: np.ndarray
|
|
37
|
+
upslopes: np.ndarray
|
|
38
|
+
downslopes: np.ndarray
|
|
39
|
+
upslope_max_positions: np.ndarray
|
|
40
|
+
downslope_min_positions: np.ndarray
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def sloperange(
|
|
44
|
+
decg: ArrayLike,
|
|
45
|
+
r_wave_times: ArrayLike,
|
|
46
|
+
sampling_frequency: float,
|
|
47
|
+
) -> SlopeRangeResult:
|
|
48
|
+
"""Estimate respiration from derivative ECG morphology around R waves.
|
|
49
|
+
|
|
50
|
+
Parameters
|
|
51
|
+
----------
|
|
52
|
+
decg : array_like
|
|
53
|
+
One-dimensional derivative ECG signal with at least two finite real
|
|
54
|
+
samples.
|
|
55
|
+
r_wave_times : array_like
|
|
56
|
+
Finite R-wave occurrence times in seconds. Values must form a
|
|
57
|
+
non-empty, strictly increasing one-dimensional sequence and map inside
|
|
58
|
+
the derivative ECG sample grid.
|
|
59
|
+
sampling_frequency : float
|
|
60
|
+
Positive finite sampling frequency in Hz.
|
|
61
|
+
|
|
62
|
+
Returns
|
|
63
|
+
-------
|
|
64
|
+
SlopeRangeResult
|
|
65
|
+
Named result containing five one-dimensional arrays. ``edr`` and the
|
|
66
|
+
two position arrays are aligned with ``r_wave_times``; ``upslopes`` and
|
|
67
|
+
``downslopes`` are aligned with ``decg``. The result can also be
|
|
68
|
+
unpacked in that field order.
|
|
69
|
+
|
|
70
|
+
Raises
|
|
71
|
+
------
|
|
72
|
+
TypeError
|
|
73
|
+
If an input expected to be numeric contains non-numeric or complex
|
|
74
|
+
data.
|
|
75
|
+
ValueError
|
|
76
|
+
If an input has an invalid shape, length, finite-value constraint,
|
|
77
|
+
order, sample-grid mapping, or sampling frequency.
|
|
78
|
+
|
|
79
|
+
Notes
|
|
80
|
+
-----
|
|
81
|
+
Extrema positions use the zero-based Python and canonical Biosiglib sample
|
|
82
|
+
grid. Beats contribute to both diagnostic slope vectors only when both
|
|
83
|
+
analysis windows are complete. The earliest sample is selected when an
|
|
84
|
+
extreme value is tied.
|
|
85
|
+
|
|
86
|
+
Examples
|
|
87
|
+
--------
|
|
88
|
+
>>> import numpy as np
|
|
89
|
+
>>> from biosigpy.ecg import sloperange
|
|
90
|
+
>>> decg = np.zeros(40)
|
|
91
|
+
>>> decg[[9, 10]] = 3.0
|
|
92
|
+
>>> decg[[13, 14]] = -2.0
|
|
93
|
+
>>> result = sloperange(decg, [0.1], 100.0)
|
|
94
|
+
>>> result.edr
|
|
95
|
+
array([5.])
|
|
96
|
+
>>> result.upslope_max_positions
|
|
97
|
+
array([9.])
|
|
98
|
+
>>> edr, upslopes, downslopes, upmaxpos, downminpos = result
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
derivative_ecg = as_real_vector(decg, name="decg")
|
|
102
|
+
if derivative_ecg.size < 2:
|
|
103
|
+
raise ValueError("decg must contain at least two samples")
|
|
104
|
+
if not np.all(np.isfinite(derivative_ecg)):
|
|
105
|
+
raise ValueError("decg must contain only finite values")
|
|
106
|
+
|
|
107
|
+
times = as_real_vector(r_wave_times, name="r_wave_times")
|
|
108
|
+
if times.size == 0:
|
|
109
|
+
raise ValueError("r_wave_times must not be empty")
|
|
110
|
+
if not np.all(np.isfinite(times)):
|
|
111
|
+
raise ValueError("r_wave_times must contain only finite values")
|
|
112
|
+
if np.any(np.diff(times) <= 0.0):
|
|
113
|
+
raise ValueError("r_wave_times must be strictly increasing")
|
|
114
|
+
|
|
115
|
+
fs = as_positive_real_scalar(
|
|
116
|
+
sampling_frequency, name="sampling_frequency"
|
|
117
|
+
)
|
|
118
|
+
with np.errstate(over="ignore", invalid="ignore"):
|
|
119
|
+
sample_positions = times * fs
|
|
120
|
+
if not np.all(np.isfinite(sample_positions)):
|
|
121
|
+
raise ValueError("r_wave_times cannot be mapped to the sample grid")
|
|
122
|
+
|
|
123
|
+
rounded_positions = _round_half_away_from_zero(sample_positions)
|
|
124
|
+
if np.any(rounded_positions < 0) or np.any(
|
|
125
|
+
rounded_positions >= derivative_ecg.size
|
|
126
|
+
):
|
|
127
|
+
raise ValueError("r_wave_times must map inside the decg sample grid")
|
|
128
|
+
r_wave_samples = rounded_positions.astype(np.intp)
|
|
129
|
+
|
|
130
|
+
short_window = int(np.floor(fs * 0.015 + 0.5))
|
|
131
|
+
long_window = int(np.floor(fs * 0.05 + 0.5))
|
|
132
|
+
edr = np.full(times.shape, np.nan, dtype=np.float64)
|
|
133
|
+
upslopes = np.full(derivative_ecg.shape, np.nan, dtype=np.float64)
|
|
134
|
+
downslopes = np.full(derivative_ecg.shape, np.nan, dtype=np.float64)
|
|
135
|
+
upslope_max_positions = np.full(
|
|
136
|
+
times.shape, np.nan, dtype=np.float64
|
|
137
|
+
)
|
|
138
|
+
downslope_min_positions = np.full(
|
|
139
|
+
times.shape, np.nan, dtype=np.float64
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
for beat_index, sample in enumerate(r_wave_samples):
|
|
143
|
+
sample = int(sample)
|
|
144
|
+
upslope_start = sample - long_window + 1
|
|
145
|
+
upslope_stop = sample + short_window + 1
|
|
146
|
+
downslope_start = sample - short_window
|
|
147
|
+
downslope_stop = sample + long_window
|
|
148
|
+
|
|
149
|
+
windows_are_empty = (
|
|
150
|
+
upslope_start >= upslope_stop
|
|
151
|
+
or downslope_start >= downslope_stop
|
|
152
|
+
)
|
|
153
|
+
windows_cross_boundary = (
|
|
154
|
+
upslope_start < 0
|
|
155
|
+
or downslope_start < 0
|
|
156
|
+
or upslope_stop > derivative_ecg.size
|
|
157
|
+
or downslope_stop > derivative_ecg.size
|
|
158
|
+
)
|
|
159
|
+
if windows_are_empty or windows_cross_boundary:
|
|
160
|
+
continue
|
|
161
|
+
|
|
162
|
+
upslope_segment = derivative_ecg[upslope_start:upslope_stop]
|
|
163
|
+
downslope_segment = derivative_ecg[
|
|
164
|
+
downslope_start:downslope_stop
|
|
165
|
+
]
|
|
166
|
+
upslope_max_position = upslope_start + int(
|
|
167
|
+
np.argmax(upslope_segment)
|
|
168
|
+
)
|
|
169
|
+
downslope_min_position = downslope_start + int(
|
|
170
|
+
np.argmin(downslope_segment)
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
upslopes[upslope_start:upslope_stop] = upslope_segment
|
|
174
|
+
downslopes[downslope_start:downslope_stop] = downslope_segment
|
|
175
|
+
upslope_max_positions[beat_index] = upslope_max_position
|
|
176
|
+
downslope_min_positions[beat_index] = downslope_min_position
|
|
177
|
+
edr[beat_index] = (
|
|
178
|
+
derivative_ecg[upslope_max_position]
|
|
179
|
+
- derivative_ecg[downslope_min_position]
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
return SlopeRangeResult(
|
|
183
|
+
edr=edr,
|
|
184
|
+
upslopes=upslopes,
|
|
185
|
+
downslopes=downslopes,
|
|
186
|
+
upslope_max_positions=upslope_max_positions,
|
|
187
|
+
downslope_min_positions=downslope_min_positions,
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _round_half_away_from_zero(values: np.ndarray) -> np.ndarray:
|
|
192
|
+
return np.copysign(np.floor(np.abs(values) + 0.5), values)
|
biosigpy/hrv/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Heart-rate and pulse-variability algorithms."""
|
|
2
|
+
|
|
3
|
+
from biosigpy.hrv.fillgaps import FillGapsResult, fillgaps
|
|
4
|
+
from biosigpy.hrv.fdmetrics import (
|
|
5
|
+
FdMetricsResult,
|
|
6
|
+
FdMetricsWarning,
|
|
7
|
+
SeparatedFdMetricsResult,
|
|
8
|
+
fdmetrics,
|
|
9
|
+
)
|
|
10
|
+
from biosigpy.hrv.ipfm import IpfmResult, ipfm
|
|
11
|
+
from biosigpy.hrv.osp import OspResult, osp
|
|
12
|
+
from biosigpy.hrv.removefp import removefp
|
|
13
|
+
from biosigpy.hrv.tdmetrics import tdmetrics
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"FillGapsResult",
|
|
17
|
+
"FdMetricsResult",
|
|
18
|
+
"FdMetricsWarning",
|
|
19
|
+
"IpfmResult",
|
|
20
|
+
"OspResult",
|
|
21
|
+
"SeparatedFdMetricsResult",
|
|
22
|
+
"fdmetrics",
|
|
23
|
+
"fillgaps",
|
|
24
|
+
"ipfm",
|
|
25
|
+
"osp",
|
|
26
|
+
"removefp",
|
|
27
|
+
"tdmetrics",
|
|
28
|
+
]
|