prpy 0.2.30__tar.gz → 0.3.2__tar.gz
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.
- {prpy-0.2.30/prpy.egg-info → prpy-0.3.2}/PKG-INFO +2 -2
- {prpy-0.2.30 → prpy-0.3.2}/README.md +1 -1
- prpy-0.3.2/prpy/numpy/__init__.py +29 -0
- prpy-0.3.2/prpy/numpy/core.py +91 -0
- prpy-0.3.2/prpy/numpy/detect.py +267 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/numpy/face.py +22 -11
- prpy-0.3.2/prpy/numpy/filters.py +280 -0
- prpy-0.3.2/prpy/numpy/freq.py +251 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/numpy/image.py +12 -6
- prpy-0.3.2/prpy/numpy/interp.py +297 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/numpy/metric.py +13 -6
- prpy-0.3.2/prpy/numpy/physio.py +802 -0
- prpy-0.3.2/prpy/numpy/rolling.py +124 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/numpy/stride_tricks.py +25 -10
- {prpy-0.2.30 → prpy-0.3.2/prpy.egg-info}/PKG-INFO +2 -2
- {prpy-0.2.30 → prpy-0.3.2}/prpy.egg-info/SOURCES.txt +14 -4
- prpy-0.3.2/tests/conftest.py +230 -0
- prpy-0.3.2/tests/test_numpy_core.py +80 -0
- prpy-0.3.2/tests/test_numpy_detect.py +116 -0
- prpy-0.3.2/tests/test_numpy_filters.py +143 -0
- prpy-0.3.2/tests/test_numpy_freq.py +111 -0
- prpy-0.3.2/tests/test_numpy_interp.py +184 -0
- prpy-0.3.2/tests/test_numpy_physio.py +447 -0
- prpy-0.3.2/tests/test_numpy_rolling.py +86 -0
- {prpy-0.2.30 → prpy-0.3.2}/tests/test_numpy_stride_tricks.py +2 -2
- prpy-0.2.30/prpy/numpy/image_ops.cpython-310-darwin.so +0 -0
- prpy-0.2.30/prpy/numpy/image_ops.cpython-312-darwin.so +0 -0
- prpy-0.2.30/prpy/numpy/signal.py +0 -771
- prpy-0.2.30/prpy/torch/__init__.py +0 -19
- prpy-0.2.30/tests/conftest.py +0 -98
- prpy-0.2.30/tests/test_numpy_signal.py +0 -432
- {prpy-0.2.30 → prpy-0.3.2}/.gitignore +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/LICENSE +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/MANIFEST.in +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/__init__.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/constants.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/ffmpeg/__init__.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/ffmpeg/probe.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/ffmpeg/readwrite.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/ffmpeg/utils.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/helpers.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/numpy/image_ops.c +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/numpy/utils.py +0 -0
- {prpy-0.2.30/prpy/numpy → prpy-0.3.2/prpy/tensorflow}/__init__.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/tensorflow/image.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/tensorflow/loss.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/tensorflow/lr_schedule.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/tensorflow/model_saver.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/tensorflow/nan.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/tensorflow/optimizer.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/tensorflow/signal.py +0 -0
- {prpy-0.2.30/prpy/tensorflow → prpy-0.3.2/prpy/torch}/__init__.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy/torch/model_saver.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy.egg-info/dependency_links.txt +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy.egg-info/requires.txt +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/prpy.egg-info/top_level.txt +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/pyproject.toml +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/setup.cfg +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/setup.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/tests/test_ffmpeg.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/tests/test_numpy_face.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/tests/test_numpy_image.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/tests/test_numpy_metric.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/tests/test_numpy_utils.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/tests/test_tensorflow.py +0 -0
- {prpy-0.2.30 → prpy-0.3.2}/tests/test_torch.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: prpy
|
|
3
|
-
Version: 0.2
|
|
3
|
+
Version: 0.3.2
|
|
4
4
|
Summary: Collection of Python utils for signal, image, and video processing
|
|
5
5
|
Author-email: Philipp Rouast <philipp@rouast.com>
|
|
6
6
|
License: MIT License
|
|
@@ -51,7 +51,7 @@ It contains subpackages for working with `numpy`, `ffmpeg`, `tensorflow`, and `t
|
|
|
51
51
|
|
|
52
52
|
## Installation
|
|
53
53
|
|
|
54
|
-
General prerequisites are `python>=3.
|
|
54
|
+
General prerequisites are `python>=3.9` and `ffmpeg` installed and accessible via the `$PATH` environment variable.
|
|
55
55
|
|
|
56
56
|
- Please note: If using `numpy` or `tensorflow` options, we only support Python `<3.12` because of the dependencies.
|
|
57
57
|
|
|
@@ -9,7 +9,7 @@ It contains subpackages for working with `numpy`, `ffmpeg`, `tensorflow`, and `t
|
|
|
9
9
|
|
|
10
10
|
## Installation
|
|
11
11
|
|
|
12
|
-
General prerequisites are `python>=3.
|
|
12
|
+
General prerequisites are `python>=3.9` and `ffmpeg` installed and accessible via the `$PATH` environment variable.
|
|
13
13
|
|
|
14
14
|
- Please note: If using `numpy` or `tensorflow` options, we only support Python `<3.12` because of the dependencies.
|
|
15
15
|
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Copyright (c) 2025 Philipp Rouast
|
|
2
|
+
#
|
|
3
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
# in the Software without restriction, including without limitation the rights
|
|
6
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
# furnished to do so, subject to the following conditions:
|
|
9
|
+
#
|
|
10
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
# copies or substantial portions of the Software.
|
|
12
|
+
#
|
|
13
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
# SOFTWARE.
|
|
20
|
+
|
|
21
|
+
from .core import *
|
|
22
|
+
from .face import *
|
|
23
|
+
from .filters import *
|
|
24
|
+
from .freq import *
|
|
25
|
+
from .image import *
|
|
26
|
+
from .interp import *
|
|
27
|
+
from .metric import *
|
|
28
|
+
from .stride_tricks import *
|
|
29
|
+
from .utils import *
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# Copyright (c) 2025 Philipp Rouast
|
|
2
|
+
#
|
|
3
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
# in the Software without restriction, including without limitation the rights
|
|
6
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
# furnished to do so, subject to the following conditions:
|
|
9
|
+
#
|
|
10
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
# copies or substantial portions of the Software.
|
|
12
|
+
#
|
|
13
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
# SOFTWARE.
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
from typing import Union
|
|
23
|
+
|
|
24
|
+
def div0(
|
|
25
|
+
a: Union[np.ndarray, float, int],
|
|
26
|
+
b: Union[np.ndarray, float, int],
|
|
27
|
+
fill: Union[float, int] = np.nan
|
|
28
|
+
) -> np.ndarray:
|
|
29
|
+
"""
|
|
30
|
+
Divide after accounting for zeros in divisor, e.g.:
|
|
31
|
+
|
|
32
|
+
- div0( [-1, 0, 1], 0, fill=np.nan) -> [nan nan nan]
|
|
33
|
+
- div0( 1, 0, fill=np.inf ) -> inf
|
|
34
|
+
|
|
35
|
+
Source: https://stackoverflow.com/a/35696047/3595278
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
a: Dividend
|
|
39
|
+
b: Divisor
|
|
40
|
+
fill: Use this value to fill where b == 0.
|
|
41
|
+
Returns:
|
|
42
|
+
c: safe a/b
|
|
43
|
+
"""
|
|
44
|
+
assert isinstance(fill, (int, float))
|
|
45
|
+
with np.errstate(divide='ignore', invalid='ignore'):
|
|
46
|
+
c = np.true_divide(a, b)
|
|
47
|
+
if np.isscalar(c):
|
|
48
|
+
return c if np.isfinite(c) else fill
|
|
49
|
+
else:
|
|
50
|
+
c[~np.isfinite(c)] = fill
|
|
51
|
+
return c
|
|
52
|
+
|
|
53
|
+
def standardize(
|
|
54
|
+
x: np.ndarray,
|
|
55
|
+
axis: Union[int, None] = -1
|
|
56
|
+
) -> np.ndarray:
|
|
57
|
+
"""
|
|
58
|
+
Perform standardization
|
|
59
|
+
|
|
60
|
+
- Note: Returns zero if std == 0
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
x: The input data
|
|
64
|
+
axis: Axis over which to standardize
|
|
65
|
+
Returns:
|
|
66
|
+
x: The standardized data
|
|
67
|
+
"""
|
|
68
|
+
assert axis is None or isinstance(axis, int) or (isinstance(axis, tuple) and all(isinstance(i, int) for i in axis))
|
|
69
|
+
x = np.array(x)
|
|
70
|
+
x -= np.mean(x, axis=axis, keepdims=x.ndim>0)
|
|
71
|
+
std = np.std(x, axis=axis, keepdims=x.ndim>0)
|
|
72
|
+
x = div0(x, std, fill=0)
|
|
73
|
+
return x
|
|
74
|
+
|
|
75
|
+
def normalize(
|
|
76
|
+
x: np.ndarray,
|
|
77
|
+
axis: Union[int, tuple, None] = -1
|
|
78
|
+
) -> np.ndarray:
|
|
79
|
+
"""
|
|
80
|
+
Perform normalization
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
x: The input data
|
|
84
|
+
axis: Axis or axes over which to normalize
|
|
85
|
+
Returns:
|
|
86
|
+
x: The normalized data
|
|
87
|
+
"""
|
|
88
|
+
assert axis is None or isinstance(axis, int) or (isinstance(axis, tuple) and all(isinstance(i, int) for i in axis))
|
|
89
|
+
x = np.array(x)
|
|
90
|
+
x -= np.mean(x, axis=axis, keepdims=x.ndim>0)
|
|
91
|
+
return x
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
# Copyright (c) 2025 Philipp Rouast
|
|
2
|
+
#
|
|
3
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
# in the Software without restriction, including without limitation the rights
|
|
6
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
# furnished to do so, subject to the following conditions:
|
|
9
|
+
#
|
|
10
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
# copies or substantial portions of the Software.
|
|
12
|
+
#
|
|
13
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
# SOFTWARE.
|
|
20
|
+
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
import logging
|
|
23
|
+
import numpy as np
|
|
24
|
+
from scipy import signal
|
|
25
|
+
from typing import Callable, Tuple, Optional, List, Union
|
|
26
|
+
|
|
27
|
+
from prpy.numpy.freq import estimate_freq_periodogram
|
|
28
|
+
from prpy.numpy.interp import interpolate_data_outliers
|
|
29
|
+
from prpy.numpy.rolling import rolling_calc
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class PeakDetectDebug:
|
|
33
|
+
t: np.ndarray
|
|
34
|
+
vals_raw: np.ndarray
|
|
35
|
+
vals_trans: np.ndarray
|
|
36
|
+
freqs: np.ndarray
|
|
37
|
+
det_idxs: np.ndarray
|
|
38
|
+
det_idxs_raw: Optional[np.ndarray]
|
|
39
|
+
det_t_diff: np.ndarray
|
|
40
|
+
det_t_diff_imp: np.ndarray
|
|
41
|
+
min_dist_t: float
|
|
42
|
+
min_width_t: Optional[float]
|
|
43
|
+
period_rel_tol: Tuple[float, float]
|
|
44
|
+
|
|
45
|
+
def detect_valid_peaks(
|
|
46
|
+
vals: np.ndarray,
|
|
47
|
+
*,
|
|
48
|
+
f_s: Optional[float] = None,
|
|
49
|
+
height: float = 0.,
|
|
50
|
+
prominence: Optional[Tuple[float, float]] = None,
|
|
51
|
+
period_rel_tol: Tuple[float, float] = (0.4, 0.8),
|
|
52
|
+
window_size: int,
|
|
53
|
+
overlap: Optional[int] = None,
|
|
54
|
+
min_det_for_valid_seq: int = 1,
|
|
55
|
+
t: Optional[np.ndarray] = None,
|
|
56
|
+
width: Optional[Union[float, Tuple[float, float]]] = None,
|
|
57
|
+
fft_fn: Optional[Callable[[np.ndarray], np.ndarray]] = None,
|
|
58
|
+
f_range: Optional[Tuple[float, float]] = None,
|
|
59
|
+
f_res: Optional[float] = None,
|
|
60
|
+
vals_fn: Optional[Callable[[np.ndarray], np.ndarray]] = None,
|
|
61
|
+
interp_vals_outliers_z: Optional[float] = None,
|
|
62
|
+
interp_freqs_outliers_z: Optional[float] = None,
|
|
63
|
+
refine: Optional[str] = None,
|
|
64
|
+
refine_dist: float = 0.1,
|
|
65
|
+
return_debug: bool = False,
|
|
66
|
+
) -> tuple:
|
|
67
|
+
"""
|
|
68
|
+
Detect sequences of valid peaks in a periodical signal (e.g., ECG)
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
vals: The signal values to search for peaks (n,)
|
|
72
|
+
f_s: Sampling frequency in Hz. Required if `t` not given.
|
|
73
|
+
height: Required height of peaks
|
|
74
|
+
prominence: Required (min, max) prominence of peaks
|
|
75
|
+
period_rel_tol: (shorter, longer)
|
|
76
|
+
- Allowed *relative* deviation of each peak-to-peak interval from the reference interval:
|
|
77
|
+
valid if (1-shorter)·T_ref < T < (1+longer)·T_ref
|
|
78
|
+
window_size: The size of the reference frequency calculation window in number of data points
|
|
79
|
+
overlap: The overlap of consecutive reference frequency calculation windows in number of data points
|
|
80
|
+
min_det_for_valid_seq: Minimum consecutive valid detections to keep a sequence.
|
|
81
|
+
t: The timestamps of the signal values (n,). If omitted, derived from `f_s`.
|
|
82
|
+
width: Required width of peaks in seconds (either scalar as minimum or tuple for (min, max))
|
|
83
|
+
fft_fn: Optional callable to be applied to vals before fft
|
|
84
|
+
f_range: The frequency range to be considered (may be None)
|
|
85
|
+
f_res: The frequency resolution (may be None)
|
|
86
|
+
vals_fn: Optional transform applied before peak detection
|
|
87
|
+
interp_vals_outliers_z, interp_freqs_outliers_z: Z-score thresholds for outlier interpolation.
|
|
88
|
+
refine: Secondary peak-refinement strategy (None, 'raw_peak', 'raw_foot')
|
|
89
|
+
refine_dist: Max admissible shift (seconds) during refinement.
|
|
90
|
+
return_debug: If True, also return a `PeakDetectDebug` object.
|
|
91
|
+
Returns:
|
|
92
|
+
Tuple of
|
|
93
|
+
- valid_det_idxs_list: List of lists of indices representing sequences of valid peaks
|
|
94
|
+
- valid: Boolean array indicating which parts of the signal had valid peak detections (n,)
|
|
95
|
+
- debug: PeakDetectDebug
|
|
96
|
+
"""
|
|
97
|
+
# Basic checks
|
|
98
|
+
if t is None and f_s is None: raise ValueError("Provide either `t` or `f_s`.")
|
|
99
|
+
assert isinstance(vals, np.ndarray)
|
|
100
|
+
size = vals.shape[0]
|
|
101
|
+
if t is None:
|
|
102
|
+
t = np.arange(size) / f_s
|
|
103
|
+
else:
|
|
104
|
+
assert t.shape[0] == size, "`t` must match `vals` length"
|
|
105
|
+
if f_s is None:
|
|
106
|
+
f_s = size / (t[-1] - t[0])
|
|
107
|
+
vals_raw = vals.copy()
|
|
108
|
+
period_rel_tol_shorter, period_rel_tol_longer = period_rel_tol
|
|
109
|
+
# Sliding reference freq
|
|
110
|
+
window_size = min(window_size, size - 1)
|
|
111
|
+
if overlap is None: overlap = window_size // 2
|
|
112
|
+
freqs = rolling_calc(
|
|
113
|
+
x=vals,
|
|
114
|
+
calc_fn=lambda x: estimate_freq_periodogram(
|
|
115
|
+
x=x,
|
|
116
|
+
f_s=f_s,
|
|
117
|
+
f_range=f_range,
|
|
118
|
+
f_res=f_res,
|
|
119
|
+
axis=1
|
|
120
|
+
),
|
|
121
|
+
min_window_size=window_size,
|
|
122
|
+
max_window_size=window_size,
|
|
123
|
+
overlap=overlap,
|
|
124
|
+
transform_fn=fft_fn,
|
|
125
|
+
fill_method='start'
|
|
126
|
+
)
|
|
127
|
+
# Preprocess
|
|
128
|
+
if interp_vals_outliers_z is not None:
|
|
129
|
+
vals = interpolate_data_outliers(vals, z_score=interp_vals_outliers_z)
|
|
130
|
+
if vals_fn is not None:
|
|
131
|
+
vals = vals_fn(vals)
|
|
132
|
+
if interp_freqs_outliers_z is not None:
|
|
133
|
+
freqs = interpolate_data_outliers(freqs, z_score=interp_freqs_outliers_z)
|
|
134
|
+
# Peak detection
|
|
135
|
+
if width is not None:
|
|
136
|
+
width_s = width
|
|
137
|
+
width = width * f_s if isinstance(width, float) else tuple(w * f_s if w is not None else None for w in width)
|
|
138
|
+
else:
|
|
139
|
+
width_s = None
|
|
140
|
+
min_dist_samples = max(1/np.quantile(freqs, 0.9) * f_s * (1 - period_rel_tol_shorter), 0)
|
|
141
|
+
raw_det_idxs, _ = signal.find_peaks(
|
|
142
|
+
vals,
|
|
143
|
+
height=height,
|
|
144
|
+
distance=min_dist_samples,
|
|
145
|
+
width=width,
|
|
146
|
+
prominence=prominence
|
|
147
|
+
)
|
|
148
|
+
if raw_det_idxs.size == 0:
|
|
149
|
+
logging.warning("No peaks found - maybe tweak `vals_fn` or thresholds.")
|
|
150
|
+
return ([], np.zeros(size)) if not return_debug else ([], np.zeros(size), None)
|
|
151
|
+
if raw_det_idxs.size == 1:
|
|
152
|
+
logging.warning("Only a single peak - periodicity checks will pass trivially.")
|
|
153
|
+
valid = np.ones(size)
|
|
154
|
+
return ([raw_det_idxs.tolist()], valid) if not return_debug \
|
|
155
|
+
else ([raw_det_idxs.tolist()], valid, None)
|
|
156
|
+
# Optional refinement
|
|
157
|
+
det_idxs = raw_det_idxs
|
|
158
|
+
if refine is not None:
|
|
159
|
+
window_samples = int(refine_dist * f_s)
|
|
160
|
+
if refine == 'raw_peak':
|
|
161
|
+
det_idxs = _refine_raw_peak(vals=vals_raw,
|
|
162
|
+
det_idxs=raw_det_idxs,
|
|
163
|
+
window_samples=window_samples)
|
|
164
|
+
elif refine == 'raw_foot':
|
|
165
|
+
det_idxs = _refine_raw_foot(vals=vals_raw,
|
|
166
|
+
det_idxs=raw_det_idxs,
|
|
167
|
+
window_samples=window_samples)
|
|
168
|
+
else:
|
|
169
|
+
raise ValueError(f"Unknown refine mode '{refine}'.")
|
|
170
|
+
# Validity test
|
|
171
|
+
det_t_diff = np.diff(t[det_idxs])
|
|
172
|
+
det_t_diff = np.concatenate([[det_t_diff[0]], det_t_diff])
|
|
173
|
+
det_t_diff_imp = 1/freqs[det_idxs]
|
|
174
|
+
# Detections are valid if diffs are close enough to implied diffs
|
|
175
|
+
det_valid = np.logical_and(det_t_diff < det_t_diff_imp * (1 + period_rel_tol_longer),
|
|
176
|
+
det_t_diff > det_t_diff_imp * (1 - period_rel_tol_shorter))
|
|
177
|
+
# Determine sequences of consecutive valid detections
|
|
178
|
+
det_valid_seq_start_idx = np.where(np.logical_and(np.concatenate([[True], np.diff(det_valid)]), det_valid))[0]
|
|
179
|
+
det_valid_seq_end_idx = np.where(np.logical_and(np.concatenate([np.diff(det_valid), [True]]), det_valid))[0]
|
|
180
|
+
valid_det_idxs_list = [det_idxs[start:end+1].tolist() for start, end in zip(det_valid_seq_start_idx, det_valid_seq_end_idx) if end-start >= min_det_for_valid_seq]
|
|
181
|
+
# Determine valid column
|
|
182
|
+
valid_idxs_list = [list(range(det_idxs[start], det_idxs[end])) for start, end in zip(det_valid_seq_start_idx, det_valid_seq_end_idx)]
|
|
183
|
+
valid_idxs = [item for sublist in valid_idxs_list for item in sublist]
|
|
184
|
+
valid = np.zeros(size)
|
|
185
|
+
valid[valid_idxs] = 1
|
|
186
|
+
if not return_debug:
|
|
187
|
+
return valid_det_idxs_list, valid
|
|
188
|
+
debug = PeakDetectDebug(
|
|
189
|
+
t=t,
|
|
190
|
+
vals_raw=vals_raw,
|
|
191
|
+
vals_trans=vals,
|
|
192
|
+
freqs=freqs,
|
|
193
|
+
det_idxs=det_idxs,
|
|
194
|
+
det_idxs_raw=raw_det_idxs,
|
|
195
|
+
det_t_diff=det_t_diff,
|
|
196
|
+
det_t_diff_imp=det_t_diff_imp,
|
|
197
|
+
min_dist_t=min_dist_samples / f_s,
|
|
198
|
+
min_width_t=width_s[0] if isinstance(width_s, tuple) else width_s,
|
|
199
|
+
period_rel_tol=period_rel_tol,
|
|
200
|
+
)
|
|
201
|
+
return valid_det_idxs_list, valid, debug
|
|
202
|
+
|
|
203
|
+
def _refine_raw_peak(
|
|
204
|
+
vals: np.ndarray,
|
|
205
|
+
det_idxs: np.ndarray,
|
|
206
|
+
window_samples: int
|
|
207
|
+
) -> list:
|
|
208
|
+
"""
|
|
209
|
+
Refine peak detections by searching for maximum within local window.
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
vals: Signal values (n,)
|
|
213
|
+
det_idxs: Detected peak indices
|
|
214
|
+
window_samples: Number of samples defining the local search window around each detection
|
|
215
|
+
Returns:
|
|
216
|
+
Lost of lists of refined peak indices
|
|
217
|
+
"""
|
|
218
|
+
half_w = window_samples // 2
|
|
219
|
+
offsets = np.arange(-half_w, half_w)
|
|
220
|
+
|
|
221
|
+
# build a (N, window) index matrix around each detection
|
|
222
|
+
idx_matrix = det_idxs[:, None] + offsets[None, :]
|
|
223
|
+
idx_clipped = np.clip(idx_matrix, 0, vals.shape[0] - 1)
|
|
224
|
+
|
|
225
|
+
# extract and mask out‑of‑bounds
|
|
226
|
+
mask = (idx_matrix < 0) | (idx_matrix >= vals.shape[0])
|
|
227
|
+
windows = vals[idx_clipped]
|
|
228
|
+
windows = np.where(mask, -np.inf, windows)
|
|
229
|
+
|
|
230
|
+
# find local max per row
|
|
231
|
+
local_off = np.argmax(windows, axis=1)
|
|
232
|
+
refined = idx_clipped[np.arange(det_idxs.size), local_off]
|
|
233
|
+
|
|
234
|
+
return refined
|
|
235
|
+
|
|
236
|
+
def _refine_raw_foot(
|
|
237
|
+
vals: np.ndarray,
|
|
238
|
+
det_idxs: np.ndarray,
|
|
239
|
+
window_samples: int
|
|
240
|
+
) -> list:
|
|
241
|
+
"""
|
|
242
|
+
Refine peak detections by searching for minimum within local window.
|
|
243
|
+
|
|
244
|
+
Args:
|
|
245
|
+
vals: Signal values (n,)
|
|
246
|
+
det_idxs: Detected peak indices
|
|
247
|
+
window_samples: Number of samples defining the local search window around each detection
|
|
248
|
+
Returns:
|
|
249
|
+
Lost of lists of refined foot indices
|
|
250
|
+
"""
|
|
251
|
+
half_w = window_samples // 2
|
|
252
|
+
offsets = np.arange(-half_w, half_w)
|
|
253
|
+
|
|
254
|
+
# build a (N, window) index matrix around each detection
|
|
255
|
+
idx_matrix = det_idxs[:, None] + offsets[None, :]
|
|
256
|
+
idx_clipped = np.clip(idx_matrix, 0, vals.shape[0] - 1)
|
|
257
|
+
|
|
258
|
+
# extract and mask out‑of‑bounds
|
|
259
|
+
mask = (idx_matrix < 0) | (idx_matrix >= vals.shape[0])
|
|
260
|
+
windows = vals[idx_clipped]
|
|
261
|
+
windows = np.where(mask, -np.inf, windows)
|
|
262
|
+
|
|
263
|
+
# find local max per row
|
|
264
|
+
local_off = np.argmin(windows, axis=1)
|
|
265
|
+
refined = idx_clipped[np.arange(det_idxs.size), local_off]
|
|
266
|
+
|
|
267
|
+
return refined
|
|
@@ -23,7 +23,8 @@ from prpy.numpy.image import crop_slice_resize
|
|
|
23
23
|
from typing import Union
|
|
24
24
|
|
|
25
25
|
def _force_even_dims(roi: tuple) -> tuple:
|
|
26
|
-
"""
|
|
26
|
+
"""
|
|
27
|
+
Force even dimensions
|
|
27
28
|
|
|
28
29
|
Args:
|
|
29
30
|
roi: The region of interest with potentially uneven dimensions
|
|
@@ -46,7 +47,8 @@ def _get_roi_from_det(
|
|
|
46
47
|
clip_dims: Union[tuple, None] = None,
|
|
47
48
|
force_even_dims: bool = False
|
|
48
49
|
) -> tuple:
|
|
49
|
-
"""
|
|
50
|
+
"""
|
|
51
|
+
Convert face detection to roi by relative add/reduce.
|
|
50
52
|
|
|
51
53
|
Args:
|
|
52
54
|
det: The face detection [0, H/W] in format (x0, y0, x1, y1).
|
|
@@ -83,8 +85,10 @@ def get_face_roi_from_det(
|
|
|
83
85
|
det: tuple,
|
|
84
86
|
force_even_dims: bool = False
|
|
85
87
|
) -> tuple:
|
|
86
|
-
"""
|
|
87
|
-
|
|
88
|
+
"""
|
|
89
|
+
Convert face detection into face roi.
|
|
90
|
+
|
|
91
|
+
- Reduces width to 60% and height to 80%.
|
|
88
92
|
|
|
89
93
|
Args:
|
|
90
94
|
det: The face detection [0, H/W] in form (x0, y0, x1, y1)
|
|
@@ -99,8 +103,10 @@ def get_forehead_roi_from_det(
|
|
|
99
103
|
det: tuple,
|
|
100
104
|
force_even_dims: bool = False
|
|
101
105
|
) -> tuple:
|
|
102
|
-
"""
|
|
103
|
-
|
|
106
|
+
"""
|
|
107
|
+
Convert face detection into forehead roi.
|
|
108
|
+
|
|
109
|
+
- Reduces det to forehead as 35% to 65% of width, and 15% to 25% of height.
|
|
104
110
|
|
|
105
111
|
Args:
|
|
106
112
|
det: The face detection [0, H/W] in form (x0, y0, x1, y1)
|
|
@@ -118,7 +124,8 @@ def get_upper_body_roi_from_det(
|
|
|
118
124
|
v: int = 1,
|
|
119
125
|
force_even_dims: bool = False
|
|
120
126
|
) -> tuple:
|
|
121
|
-
"""
|
|
127
|
+
"""
|
|
128
|
+
Convert face detection into upper body roi and clip to frame constraints.
|
|
122
129
|
|
|
123
130
|
Args:
|
|
124
131
|
det: The face detection [0, H/W] in form (x0, y0, x1, y1)
|
|
@@ -186,7 +193,8 @@ def get_meta_roi_from_det(
|
|
|
186
193
|
clip_dims: tuple,
|
|
187
194
|
force_even_dims: bool = False
|
|
188
195
|
) -> tuple:
|
|
189
|
-
"""
|
|
196
|
+
"""
|
|
197
|
+
Convert face detection into meta roi and clip to frame constraints.
|
|
190
198
|
|
|
191
199
|
Args:
|
|
192
200
|
det: The face detection [0, H/W] in form (x0, y0, x1, y1)
|
|
@@ -205,7 +213,8 @@ def get_roi_from_det(
|
|
|
205
213
|
clip_dims: Union[tuple, None] = None,
|
|
206
214
|
force_even_dims: bool = False
|
|
207
215
|
) -> tuple:
|
|
208
|
-
"""
|
|
216
|
+
"""
|
|
217
|
+
Convert face detection into specified roi.
|
|
209
218
|
|
|
210
219
|
Args:
|
|
211
220
|
det: The face detection [0, H/W] in form (x0, y0, x1, y1)
|
|
@@ -253,8 +262,10 @@ def crop_resize_from_det(
|
|
|
253
262
|
scale_algorithm: str,
|
|
254
263
|
force_even_dims: bool = False
|
|
255
264
|
) -> np.ndarray:
|
|
256
|
-
"""
|
|
257
|
-
|
|
265
|
+
"""
|
|
266
|
+
Crop and resize a video according to a single face detection.
|
|
267
|
+
|
|
268
|
+
- Resize to specified size with specified method.
|
|
258
269
|
|
|
259
270
|
Args:
|
|
260
271
|
video: The video. Shape (n_frames, h, w, c)
|