aind-dynamic-foraging-basic-analysis 0.4.1__py3-none-any.whl → 0.4.2__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.
- aind_dynamic_foraging_basic_analysis/__init__.py +1 -1
- aind_dynamic_foraging_basic_analysis/metrics/snr_envelope_rr.py +929 -0
- aind_dynamic_foraging_basic_analysis/plot/plot_foraging_session_plotly.py +10 -5
- {aind_dynamic_foraging_basic_analysis-0.4.1.dist-info → aind_dynamic_foraging_basic_analysis-0.4.2.dist-info}/METADATA +1 -1
- {aind_dynamic_foraging_basic_analysis-0.4.1.dist-info → aind_dynamic_foraging_basic_analysis-0.4.2.dist-info}/RECORD +8 -7
- {aind_dynamic_foraging_basic_analysis-0.4.1.dist-info → aind_dynamic_foraging_basic_analysis-0.4.2.dist-info}/WHEEL +0 -0
- {aind_dynamic_foraging_basic_analysis-0.4.1.dist-info → aind_dynamic_foraging_basic_analysis-0.4.2.dist-info}/licenses/LICENSE +0 -0
- {aind_dynamic_foraging_basic_analysis-0.4.1.dist-info → aind_dynamic_foraging_basic_analysis-0.4.2.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,929 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Envelope + rise-rate (Env+RR) signal-to-noise estimator for 1D
|
|
3
|
+
fluorescence (dF/F) traces.
|
|
4
|
+
|
|
5
|
+
:class:`EnvelopeRRSNR` estimates SNR by:
|
|
6
|
+
|
|
7
|
+
1. Tracking a **tonic baseline** beneath the trace (``tonic_method``:
|
|
8
|
+
``'arpls'`` (default, adaptive asymmetric least squares), ``'als'``
|
|
9
|
+
(fixed-asymmetry ALS), or ``'envelope'`` (valley/local-minima
|
|
10
|
+
tracking)).
|
|
11
|
+
2. Subtracting it to get a **phasic residual**.
|
|
12
|
+
3. Estimating the noise floor from that residual (``noise_method``:
|
|
13
|
+
``'aind_mad'`` (default), ``'folded_iqr'``, or ``'mad_iqr_avg'``).
|
|
14
|
+
4. Detecting phasic peaks above ``peak_threshold_sd`` and refining them
|
|
15
|
+
with a rise-rate gate that rejects slow drifts.
|
|
16
|
+
5. Reporting **total SNR** as ``snr_tonic + snr_phasic``: ``snr_tonic``
|
|
17
|
+
is the tonic baseline's own peak-to-peak range divided by the noise
|
|
18
|
+
floor, and ``snr_phasic`` is a suprathreshold peak-amplitude
|
|
19
|
+
statistic divided by the noise floor, optionally bias-corrected
|
|
20
|
+
(``bias_correction``; fit against ``snr_phasic`` specifically, see
|
|
21
|
+
``EnvelopeRRResult``).
|
|
22
|
+
|
|
23
|
+
Class API
|
|
24
|
+
---------
|
|
25
|
+
Construct once, call :meth:`~EnvelopeRRSNR.fit` per trace for the full
|
|
26
|
+
result (``snr_`` (total), ``snr_tonic_``, ``snr_phasic_``, ``noise_``,
|
|
27
|
+
``peaks_``, ``tonic_``, ``residual_``, ...), :meth:`~EnvelopeRRSNR.estimate`
|
|
28
|
+
for a one-shot ``(snr, noise, peaks)`` tuple (``snr`` is the total;
|
|
29
|
+
drop-in compatible with a plain ``estimate_snr(trace, fps)`` function),
|
|
30
|
+
:meth:`~EnvelopeRRSNR.estimate_components` for the one-shot
|
|
31
|
+
``(snr_total, snr_tonic, snr_phasic)`` breakdown, or
|
|
32
|
+
:meth:`~EnvelopeRRSNR.decompose` for just ``(tonic, phasic)``.
|
|
33
|
+
|
|
34
|
+
Notes
|
|
35
|
+
-----
|
|
36
|
+
- Feed a dF/F preprocessed trace (peak height is interpreted from zero).
|
|
37
|
+
- Default ``fps`` is 20 Hz; NaNs are filled with the trace median.
|
|
38
|
+
- Needs only numpy/scipy -- no other dependencies for any ``noise_method``.
|
|
39
|
+
|
|
40
|
+
Example
|
|
41
|
+
-------
|
|
42
|
+
>>> import numpy as np
|
|
43
|
+
>>> from snr_envelope_rr import EnvelopeRRSNR
|
|
44
|
+
>>> rng = np.random.default_rng(0)
|
|
45
|
+
>>> t = np.arange(1200) / 20.0
|
|
46
|
+
>>> y = 0.05 * np.sin(2 * np.pi * t / 40.0) + 0.01 * rng.standard_normal(1200)
|
|
47
|
+
>>> result = EnvelopeRRSNR(fps=20.0).fit(y)
|
|
48
|
+
>>> isinstance(result.snr, float) and isinstance(result.noise, float)
|
|
49
|
+
True
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
from __future__ import annotations
|
|
53
|
+
|
|
54
|
+
import warnings
|
|
55
|
+
from dataclasses import dataclass, field
|
|
56
|
+
from typing import Dict, Optional, Tuple, Union
|
|
57
|
+
|
|
58
|
+
import numpy as np
|
|
59
|
+
from numpy.typing import NDArray
|
|
60
|
+
from scipy import interpolate, ndimage, signal, stats
|
|
61
|
+
|
|
62
|
+
__all__ = ["EnvelopeRRSNR", "EnvelopeRRResult"]
|
|
63
|
+
|
|
64
|
+
# Tuned defaults at the reference frame rate below. peak_threshold_sd is a
|
|
65
|
+
# sigma multiplier (unitless, does not scale with fps). The other three are
|
|
66
|
+
# window sizes in *samples*; scale_window() rescales them to preserve their
|
|
67
|
+
# real-world duration at a different fps.
|
|
68
|
+
_REFERENCE_FPS = 20.0
|
|
69
|
+
_TUNED_DEFAULTS = {
|
|
70
|
+
# Grid search (tonic_method='arpls', the default) found
|
|
71
|
+
# peak_threshold_sd=2.0 optimal for noise_method='aind_mad'
|
|
72
|
+
# (score=0.762; arpls_lam=1e7, arpls_n_iter=15, rise_window=5).
|
|
73
|
+
"peak_threshold_sd": 2.0,
|
|
74
|
+
# lower_min_distance/lower_smooth_window only apply if
|
|
75
|
+
# tonic_method='envelope' is explicitly chosen (default is 'arpls',
|
|
76
|
+
# which uses arpls_lam/arpls_n_iter/arpls_ratio instead).
|
|
77
|
+
"lower_min_distance": 20, # 1.00 s at 20 fps
|
|
78
|
+
"lower_smooth_window": 31, # 1.55 s at 20 fps
|
|
79
|
+
"rise_window": 5, # 0.25 s at 20 fps
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
# Linear bias correction fit against ground-truth SNR for the tuned
|
|
83
|
+
# defaults above (noise_method='aind_mad', peak_threshold_sd=2.0,
|
|
84
|
+
# tonic_method='arpls'): snr_corrected = (snr_raw - intercept) / slope.
|
|
85
|
+
# R^2=0.9462. Auto-applied as the constructor's default bias_correction
|
|
86
|
+
# only when the effective config matches these defaults exactly (see
|
|
87
|
+
# __init__); pass bias_correction=None to disable, or refit via
|
|
88
|
+
# fit_bias_correction_from_benchmark for a different configuration.
|
|
89
|
+
_TUNED_BIAS_CORRECTION: Tuple[float, float] = (1.8494, -0.5508)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class _UnsetType:
|
|
93
|
+
"""Sentinel distinguishing "bias_correction not specified" (auto-
|
|
94
|
+
resolve) from an explicit ``bias_correction=None`` (disable)."""
|
|
95
|
+
|
|
96
|
+
def __repr__(self) -> str:
|
|
97
|
+
"""Return a short, unambiguous marker for debugging/repr output."""
|
|
98
|
+
return "<unset>"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
_UNSET = _UnsetType()
|
|
102
|
+
|
|
103
|
+
# Noise-floor estimator for sigma_fit. 'aind_mad' (default): median-
|
|
104
|
+
# filtered residual + twice-trimmed scaled MAD (see _mad_noise_std;
|
|
105
|
+
# reproduces aind-ophys-utils' noise_std(method='mad') exactly, cloned
|
|
106
|
+
# locally so this module has no dependency on that package). 'folded_iqr':
|
|
107
|
+
# folds the residual around its own half-sample mode, scales the IQR.
|
|
108
|
+
# 'mad_iqr_avg': mean of the two.
|
|
109
|
+
# 'mad' is a deprecated alias for 'aind_mad' (DeprecationWarning).
|
|
110
|
+
_VALID_NOISE_METHODS = ("aind_mad", "folded_iqr", "mad_iqr_avg")
|
|
111
|
+
_DEFAULT_NOISE_METHOD = "aind_mad"
|
|
112
|
+
_DEPRECATED_NOISE_METHOD_ALIASES = {"mad": "aind_mad"}
|
|
113
|
+
|
|
114
|
+
# Remaining envelope-decomposition parameters; overridable via `config`.
|
|
115
|
+
_DEFAULT_CONFIG: Dict = {
|
|
116
|
+
"interp_kind": "pchip", # 'pchip' or 'linear' envelope interpolation
|
|
117
|
+
# 'arpls' (default): envelope's local-minima tonic tracking collapses
|
|
118
|
+
# at higher SNR (large transients distort where minima land); arPLS
|
|
119
|
+
# held up across the full SNR range tested. _TUNED_BIAS_CORRECTION
|
|
120
|
+
# is fit against this default -- switching tonic_method disables it
|
|
121
|
+
# automatically (see bias_correction's resolution in __init__).
|
|
122
|
+
"tonic_method": "arpls", # 'envelope' (valley-tracked), 'als', or 'arpls'
|
|
123
|
+
"als_lam": 1e7, # ALS smoothness (only if tonic_method='als')
|
|
124
|
+
"als_p": 0.01, # ALS asymmetry, rides under peaks
|
|
125
|
+
"als_n_iter": 10,
|
|
126
|
+
"arpls_lam": 1e7, # arPLS smoothness (only if tonic_method='arpls')
|
|
127
|
+
"arpls_n_iter": 15,
|
|
128
|
+
"arpls_ratio": 1e-6,
|
|
129
|
+
"midpoint_window": 101, # smoothing window for the midpoint reference curve
|
|
130
|
+
"midpoint_polyorder": 1,
|
|
131
|
+
"lower_order": 2, # local-minimum order for valley detection
|
|
132
|
+
"upper_min_distance": 3, # min spacing enforced by find_peaks on the residual
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# ======================================================================
|
|
137
|
+
# Private helpers
|
|
138
|
+
# ======================================================================
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _half_sample_mode(x: NDArray[np.floating]) -> float:
|
|
142
|
+
"""Robust mode estimator (half-sample mode; Bickel & Fruhwirth-
|
|
143
|
+
Schnatter 2006). Recursively narrows to the shortest contiguous half
|
|
144
|
+
of the sorted data until <=3 points remain, then returns their
|
|
145
|
+
center. No external dependency; O(n log n).
|
|
146
|
+
"""
|
|
147
|
+
data = np.sort(np.asarray(x, dtype=np.float64))
|
|
148
|
+
while len(data) > 3:
|
|
149
|
+
n = len(data)
|
|
150
|
+
half_n = (n + 1) // 2
|
|
151
|
+
widths = data[half_n - 1:] - data[:n - half_n + 1]
|
|
152
|
+
i = int(np.argmin(widths))
|
|
153
|
+
data = data[i:i + half_n]
|
|
154
|
+
if len(data) == 1:
|
|
155
|
+
return float(data[0])
|
|
156
|
+
if len(data) == 2:
|
|
157
|
+
return float(np.mean(data))
|
|
158
|
+
d1, d2 = data[1] - data[0], data[2] - data[1]
|
|
159
|
+
if d1 < d2:
|
|
160
|
+
return float(np.mean(data[:2]))
|
|
161
|
+
elif d2 < d1:
|
|
162
|
+
return float(np.mean(data[1:]))
|
|
163
|
+
else:
|
|
164
|
+
return float(data[1])
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _folded_iqr_noise_std(residual: NDArray[np.floating]) -> float:
|
|
168
|
+
"""Robust noise sigma via folded (one-sided) IQR, mode-anchored.
|
|
169
|
+
|
|
170
|
+
Reflects the below-mode half of the residual around its own
|
|
171
|
+
half-sample mode (:func:`_half_sample_mode`) and scales the IQR by
|
|
172
|
+
1.349. Only ever looks at the below-mode half, so it never sees
|
|
173
|
+
above-mode phasic transients -- unlike a two-sided estimator (e.g.
|
|
174
|
+
:func:`_mad_noise_std`).
|
|
175
|
+
"""
|
|
176
|
+
residual = np.asarray(residual, dtype=np.float64)
|
|
177
|
+
anchor = _half_sample_mode(residual)
|
|
178
|
+
below = residual[residual < anchor]
|
|
179
|
+
if len(below) >= 20:
|
|
180
|
+
reflected = anchor - below
|
|
181
|
+
q75r, q25r = float(np.percentile(reflected, 75)), float(np.percentile(reflected, 25))
|
|
182
|
+
return (q75r - q25r) / 1.349
|
|
183
|
+
return float(np.std(residual[residual <= np.median(residual)]))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _robust_std(x: NDArray[np.floating]) -> float:
|
|
187
|
+
"""Scaled median absolute deviation, assuming near-Gaussian noise.
|
|
188
|
+
|
|
189
|
+
Local clone of aind-ophys-utils' ``robust_std`` (1D, no-NaN case) --
|
|
190
|
+
see :func:`_mad_noise_std`.
|
|
191
|
+
"""
|
|
192
|
+
if x.size == 0:
|
|
193
|
+
return float("nan")
|
|
194
|
+
med = float(np.median(x))
|
|
195
|
+
return 1.4826 * float(np.median(np.abs(x - med)))
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _mad_noise_std(residual: NDArray[np.floating], filter_length: int = 31) -> float:
|
|
199
|
+
"""Robust noise sigma via a median-filtered residual + twice-trimmed
|
|
200
|
+
scaled MAD.
|
|
201
|
+
|
|
202
|
+
Local, dependency-free clone of aind-ophys-utils'
|
|
203
|
+
``noise_std(x, method='mad')`` (the 1D, ``skipna=False`` case, which
|
|
204
|
+
is all this module needs) -- reproduces it exactly (validated
|
|
205
|
+
against the original numerically) without requiring that package,
|
|
206
|
+
which pulls in pytorch even for this method (a module-level default
|
|
207
|
+
argument elsewhere in that package evaluates ``torch.cuda.is_available()``
|
|
208
|
+
at import time).
|
|
209
|
+
|
|
210
|
+
Median-filters the residual to remove any remaining slow baseline,
|
|
211
|
+
takes what's left, trims positive-peak outliers, then trims any
|
|
212
|
+
remaining outliers on either side, and returns the scaled MAD of
|
|
213
|
+
that twice-trimmed remainder.
|
|
214
|
+
"""
|
|
215
|
+
residual = np.asarray(residual, dtype=np.float64)
|
|
216
|
+
if np.any(np.isnan(residual)):
|
|
217
|
+
return float("nan")
|
|
218
|
+
baseline = ndimage.percentile_filter(residual, 50, size=filter_length, mode="reflect")
|
|
219
|
+
noise = residual - baseline
|
|
220
|
+
if noise.size == 0:
|
|
221
|
+
return float("nan")
|
|
222
|
+
filtered_0 = noise[noise < 1.5 * np.abs(noise.min())]
|
|
223
|
+
rstd = _robust_std(filtered_0)
|
|
224
|
+
filtered_1 = filtered_0[np.abs(filtered_0) < 2.5 * rstd]
|
|
225
|
+
return _robust_std(filtered_1)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _moving_average(
|
|
229
|
+
x: NDArray[np.floating], window: int, polyorder: int = 1
|
|
230
|
+
) -> NDArray[np.floating]:
|
|
231
|
+
"""Savitzky-Golay smoothed reference curve, used as the midpoint."""
|
|
232
|
+
window = window if window % 2 == 1 else window + 1
|
|
233
|
+
window = min(window, len(x) if len(x) % 2 == 1 else len(x) - 1)
|
|
234
|
+
return signal.savgol_filter(x, window_length=window, polyorder=polyorder)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _interpolate_envelope(idx_anchored, val_anchored, n, interp_kind: str = "pchip"):
|
|
238
|
+
"""Interpolate anchor points (e.g. tonic valleys) to a full-length curve."""
|
|
239
|
+
query = np.arange(n)
|
|
240
|
+
if interp_kind == "linear":
|
|
241
|
+
return np.interp(query, idx_anchored, val_anchored)
|
|
242
|
+
elif interp_kind == "pchip":
|
|
243
|
+
return interpolate.PchipInterpolator(idx_anchored, val_anchored, extrapolate=True)(query)
|
|
244
|
+
else:
|
|
245
|
+
raise ValueError(f"Unknown interp_kind: {interp_kind!r}. Use 'linear' or 'pchip'.")
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _lower_envelope(x, midpoint, smooth_window, order, min_distance, interp_kind="pchip"):
|
|
249
|
+
"""Valley-tracked tonic (slow baseline) envelope beneath ``x``."""
|
|
250
|
+
if smooth_window % 2 == 0:
|
|
251
|
+
smooth_window += 1
|
|
252
|
+
x_smooth = signal.savgol_filter(x, window_length=smooth_window, polyorder=3)
|
|
253
|
+
|
|
254
|
+
minima_idx = signal.argrelmin(x_smooth, order=order)[0]
|
|
255
|
+
if len(minima_idx) > 0:
|
|
256
|
+
minima_idx = minima_idx[x[minima_idx] < midpoint[minima_idx]]
|
|
257
|
+
|
|
258
|
+
if len(minima_idx) > 1:
|
|
259
|
+
filtered = [minima_idx[0]]
|
|
260
|
+
for idx in minima_idx[1:]:
|
|
261
|
+
if idx - filtered[-1] >= min_distance:
|
|
262
|
+
filtered.append(idx)
|
|
263
|
+
minima_idx = np.array(filtered)
|
|
264
|
+
|
|
265
|
+
if len(minima_idx) < 2:
|
|
266
|
+
return np.full_like(x, np.min(x), dtype=float), minima_idx
|
|
267
|
+
|
|
268
|
+
idx_anchored = np.concatenate([[0], minima_idx, [len(x) - 1]])
|
|
269
|
+
val_anchored = x[idx_anchored]
|
|
270
|
+
return _interpolate_envelope(idx_anchored, val_anchored, len(x), interp_kind), minima_idx
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _als_baseline(y, lam: float = 1e7, p: float = 0.01, n_iter: int = 10):
|
|
274
|
+
"""Asymmetric Least Squares (ALS) smooth curve, ridden under peaks
|
|
275
|
+
when ``p`` is small (``tonic_method='als'``).
|
|
276
|
+
|
|
277
|
+
Has a sharp trade-off in its single fixed ``p``: small p (~0.01)
|
|
278
|
+
resists large transients but is biased at low SNR; larger p
|
|
279
|
+
(~0.2-0.3) is good at low SNR but collapses at high SNR. See
|
|
280
|
+
``tonic_method='arpls'`` (:func:`_arpls_baseline`), which adapts the
|
|
281
|
+
asymmetry per trace instead of fixing it in advance.
|
|
282
|
+
"""
|
|
283
|
+
from scipy import sparse
|
|
284
|
+
from scipy.sparse.linalg import spsolve
|
|
285
|
+
|
|
286
|
+
L = len(y)
|
|
287
|
+
D = sparse.diags([1, -2, 1], [0, -1, -2], shape=(L, L - 2), dtype=float)
|
|
288
|
+
D = lam * D.dot(D.transpose())
|
|
289
|
+
w = np.ones(L)
|
|
290
|
+
z = y.copy()
|
|
291
|
+
for _ in range(n_iter):
|
|
292
|
+
W = sparse.spdiags(w, 0, L, L)
|
|
293
|
+
z = spsolve((W + D).tocsc(), w * y)
|
|
294
|
+
w = p * (y > z) + (1 - p) * (y < z)
|
|
295
|
+
return z
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _arpls_baseline(y, lam: float = 1e7, n_iter: int = 15, ratio: float = 1e-6):
|
|
299
|
+
"""Asymmetrically Reweighted Penalized Least Squares (arPLS) smooth
|
|
300
|
+
curve (Baek et al. 2015; ``tonic_method='arpls'``).
|
|
301
|
+
|
|
302
|
+
Like :func:`_als_baseline`, but the asymmetry weights are re-derived
|
|
303
|
+
from the current residual's own below-baseline noise statistics at
|
|
304
|
+
every iteration (same one-sided logic as
|
|
305
|
+
:func:`_folded_iqr_noise_std`) instead of one fixed `p` chosen in
|
|
306
|
+
advance -- resolving ALS's low/high-SNR trade-off in testing.
|
|
307
|
+
Iterates until the relative weight change drops below `ratio` or
|
|
308
|
+
`n_iter` is reached.
|
|
309
|
+
"""
|
|
310
|
+
from scipy import sparse
|
|
311
|
+
from scipy.sparse.linalg import spsolve
|
|
312
|
+
|
|
313
|
+
L = len(y)
|
|
314
|
+
D = sparse.diags([1, -2, 1], [0, -1, -2], shape=(L, L - 2), dtype=float)
|
|
315
|
+
D = lam * D.dot(D.transpose())
|
|
316
|
+
w = np.ones(L)
|
|
317
|
+
z = y.copy()
|
|
318
|
+
for _ in range(n_iter):
|
|
319
|
+
W = sparse.spdiags(w, 0, L, L)
|
|
320
|
+
z = spsolve((W + D).tocsc(), w * y)
|
|
321
|
+
d = y - z
|
|
322
|
+
d_neg = d[d < 0]
|
|
323
|
+
m = float(np.mean(d_neg)) if len(d_neg) else 0.0
|
|
324
|
+
s = float(np.std(d_neg)) if len(d_neg) else 1e-12
|
|
325
|
+
s = s if s > 1e-12 else 1e-12
|
|
326
|
+
w_new = 1.0 / (1.0 + np.exp(np.clip(2 * (d - (2 * s - m)) / s, -500, 500)))
|
|
327
|
+
if np.linalg.norm(w - w_new) / (np.linalg.norm(w) + 1e-12) < ratio:
|
|
328
|
+
w = w_new
|
|
329
|
+
break
|
|
330
|
+
w = w_new
|
|
331
|
+
return z
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _detect_peaks_rise_rate(residual, candidates, sigma, rise_window: int = 3):
|
|
335
|
+
"""Reject candidate peaks whose approach isn't fast enough to be a
|
|
336
|
+
real transient onset (vs. a slow drift crossing threshold)."""
|
|
337
|
+
if len(candidates) < 5:
|
|
338
|
+
return candidates
|
|
339
|
+
|
|
340
|
+
slopes = []
|
|
341
|
+
for idx in candidates:
|
|
342
|
+
lo = max(0, idx - rise_window)
|
|
343
|
+
window = residual[lo:idx]
|
|
344
|
+
if len(window) >= 2:
|
|
345
|
+
slopes.append(float(np.mean(np.diff(window))))
|
|
346
|
+
else:
|
|
347
|
+
slopes.append(0.0)
|
|
348
|
+
slopes = np.array(slopes)
|
|
349
|
+
|
|
350
|
+
lower = slopes[slopes <= np.median(slopes)]
|
|
351
|
+
if len(lower) >= 5:
|
|
352
|
+
_, sigma_slope = stats.norm.fit(lower)
|
|
353
|
+
slope_thresh = max(sigma_slope * 3.0, sigma * 0.1)
|
|
354
|
+
else:
|
|
355
|
+
slope_thresh = np.percentile(slopes, 50)
|
|
356
|
+
|
|
357
|
+
return candidates[slopes > slope_thresh]
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _decompose_envelope_rr(x: NDArray[np.floating], config: Dict) -> Dict:
|
|
361
|
+
"""Tonic/phasic decomposition + rise-rate gated peak detection."""
|
|
362
|
+
cfg = config
|
|
363
|
+
|
|
364
|
+
midpoint = _moving_average(
|
|
365
|
+
x,
|
|
366
|
+
window=cfg["midpoint_window"],
|
|
367
|
+
polyorder=cfg["midpoint_polyorder"],
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
tonic_method = cfg.get("tonic_method", "envelope")
|
|
371
|
+
if tonic_method == "als":
|
|
372
|
+
tonic = _als_baseline(
|
|
373
|
+
x,
|
|
374
|
+
lam=cfg.get("als_lam", 1e7),
|
|
375
|
+
p=cfg.get("als_p", 0.01),
|
|
376
|
+
n_iter=cfg.get("als_n_iter", 10),
|
|
377
|
+
)
|
|
378
|
+
tonic_minima = np.array([], dtype=int)
|
|
379
|
+
elif tonic_method == "arpls":
|
|
380
|
+
tonic = _arpls_baseline(
|
|
381
|
+
x,
|
|
382
|
+
lam=cfg.get("arpls_lam", 1e7),
|
|
383
|
+
n_iter=cfg.get("arpls_n_iter", 15),
|
|
384
|
+
ratio=cfg.get("arpls_ratio", 1e-6),
|
|
385
|
+
)
|
|
386
|
+
tonic_minima = np.array([], dtype=int)
|
|
387
|
+
elif tonic_method == "envelope":
|
|
388
|
+
tonic, tonic_minima = _lower_envelope(
|
|
389
|
+
x,
|
|
390
|
+
midpoint,
|
|
391
|
+
cfg["lower_smooth_window"],
|
|
392
|
+
cfg["lower_order"],
|
|
393
|
+
cfg["lower_min_distance"],
|
|
394
|
+
interp_kind=cfg["interp_kind"],
|
|
395
|
+
)
|
|
396
|
+
else:
|
|
397
|
+
raise ValueError(
|
|
398
|
+
f"tonic_method must be 'envelope', 'als', or 'arpls'; got {tonic_method!r}."
|
|
399
|
+
)
|
|
400
|
+
|
|
401
|
+
residual = x - tonic
|
|
402
|
+
|
|
403
|
+
noise_method = cfg.get("noise_method", _DEFAULT_NOISE_METHOD)
|
|
404
|
+
if noise_method in _DEPRECATED_NOISE_METHOD_ALIASES:
|
|
405
|
+
noise_method = _DEPRECATED_NOISE_METHOD_ALIASES[noise_method]
|
|
406
|
+
|
|
407
|
+
if noise_method == "folded_iqr":
|
|
408
|
+
sigma_iqr = _folded_iqr_noise_std(residual)
|
|
409
|
+
elif noise_method == "aind_mad":
|
|
410
|
+
sigma_iqr = _mad_noise_std(residual)
|
|
411
|
+
elif noise_method == "mad_iqr_avg":
|
|
412
|
+
sigma_iqr = 0.5 * (_folded_iqr_noise_std(residual) + _mad_noise_std(residual))
|
|
413
|
+
else:
|
|
414
|
+
raise ValueError(
|
|
415
|
+
f"noise_method must be one of {_VALID_NOISE_METHODS}; "
|
|
416
|
+
f"got {noise_method!r}."
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
if len(tonic_minima) >= 5:
|
|
420
|
+
n = len(residual)
|
|
421
|
+
mid_idx = ((tonic_minima[:-1] + tonic_minima[1:]) // 2).astype(int)
|
|
422
|
+
mid_idx = mid_idx[(mid_idx >= 0) & (mid_idx < n)]
|
|
423
|
+
sigma_minima = float(np.std(residual[mid_idx])) if len(mid_idx) >= 5 else sigma_iqr
|
|
424
|
+
else:
|
|
425
|
+
sigma_minima = sigma_iqr
|
|
426
|
+
|
|
427
|
+
sigma_fit = sigma_iqr
|
|
428
|
+
thresh = cfg["peak_threshold_sd"] * sigma_fit
|
|
429
|
+
|
|
430
|
+
raw_peaks, _ = signal.find_peaks(
|
|
431
|
+
residual,
|
|
432
|
+
height=thresh,
|
|
433
|
+
distance=cfg.get("upper_min_distance", 3),
|
|
434
|
+
)
|
|
435
|
+
event_maxima = _detect_peaks_rise_rate(
|
|
436
|
+
residual,
|
|
437
|
+
raw_peaks,
|
|
438
|
+
sigma_fit,
|
|
439
|
+
rise_window=cfg.get("rise_window", 3),
|
|
440
|
+
)
|
|
441
|
+
event_maxima = np.asarray(event_maxima, dtype=int)
|
|
442
|
+
event_maxima = event_maxima[(event_maxima >= 0) & (event_maxima < len(residual))]
|
|
443
|
+
peak_amps = residual[event_maxima] if len(event_maxima) > 0 else np.array([])
|
|
444
|
+
|
|
445
|
+
if len(peak_amps) > 0:
|
|
446
|
+
phasic_p95 = float(np.percentile(peak_amps, 95))
|
|
447
|
+
phasic_median = float(np.median(peak_amps))
|
|
448
|
+
phasic_sd = float(np.std(peak_amps))
|
|
449
|
+
else:
|
|
450
|
+
phasic_p95 = phasic_median = phasic_sd = 0.0
|
|
451
|
+
|
|
452
|
+
return {
|
|
453
|
+
"tonic": tonic,
|
|
454
|
+
"tonic_minima": tonic_minima,
|
|
455
|
+
"event_maxima": event_maxima,
|
|
456
|
+
"midpoint": midpoint,
|
|
457
|
+
"residual": residual,
|
|
458
|
+
"peak_amps": peak_amps,
|
|
459
|
+
"noise_sigma": float(sigma_fit),
|
|
460
|
+
"noise_sigma_iqr": float(sigma_iqr),
|
|
461
|
+
"noise_sigma_minima": float(sigma_minima),
|
|
462
|
+
"peak_threshold": float(thresh),
|
|
463
|
+
"detection_method": "rise_rate",
|
|
464
|
+
"tonic_method": tonic_method,
|
|
465
|
+
"tonic_range": float(np.ptp(tonic)),
|
|
466
|
+
"phasic_p95": phasic_p95,
|
|
467
|
+
"phasic_median": phasic_median,
|
|
468
|
+
"phasic_amplitude": phasic_sd,
|
|
469
|
+
"phasic_snr_p95": float(phasic_p95 / sigma_fit) if sigma_fit > 0 else float("nan"),
|
|
470
|
+
"phasic_snr_median": float(phasic_median / sigma_fit) if sigma_fit > 0 else float("nan"),
|
|
471
|
+
"phasic_snr_sd": float(phasic_sd / sigma_fit) if sigma_fit > 0 else float("nan"),
|
|
472
|
+
"tonic_snr_sd": float(np.ptp(tonic) / sigma_fit) if sigma_fit > 0 else float("nan"),
|
|
473
|
+
"config": cfg,
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
@dataclass
|
|
478
|
+
class EnvelopeRRResult:
|
|
479
|
+
"""Fitted result of :meth:`EnvelopeRRSNR.fit`.
|
|
480
|
+
|
|
481
|
+
Attributes
|
|
482
|
+
----------
|
|
483
|
+
snr : float
|
|
484
|
+
**Total** SNR: ``snr_tonic + snr_phasic``, before bias
|
|
485
|
+
correction. (Changed from phasic-only in earlier versions of
|
|
486
|
+
this class -- see ``snr_phasic`` for that quantity on its own.)
|
|
487
|
+
snr_tonic : float
|
|
488
|
+
Tonic-baseline SNR: the tonic's own peak-to-peak range divided
|
|
489
|
+
by the noise floor. How much the slow baseline itself varies
|
|
490
|
+
relative to the noise, independent of any phasic events.
|
|
491
|
+
snr_phasic : float
|
|
492
|
+
Phasic SNR: ``signal / noise``, using ``signal_statistic`` on
|
|
493
|
+
the suprathreshold phasic peak amplitudes. This is what ``snr``
|
|
494
|
+
meant in earlier versions of this class, and is the quantity
|
|
495
|
+
``bias_correction`` was actually fit against (see
|
|
496
|
+
``snr_phasic_corrected``).
|
|
497
|
+
snr_phasic_corrected : float or None
|
|
498
|
+
``snr_phasic`` after applying ``bias_correction`` (``None`` if
|
|
499
|
+
none configured, or if no phasic peaks were detected).
|
|
500
|
+
snr_corrected : float or None
|
|
501
|
+
**Total**, bias-corrected: ``snr_tonic + snr_phasic_corrected``
|
|
502
|
+
(``None`` if ``bias_correction`` isn't configured). Since
|
|
503
|
+
``bias_correction`` was fit only against ``snr_phasic`` (see
|
|
504
|
+
above), this is a derived combination, not itself a directly
|
|
505
|
+
validated correction of the total -- treat it as an estimate
|
|
506
|
+
built from one validated piece and one uncorrected piece.
|
|
507
|
+
noise : float
|
|
508
|
+
Estimated noise floor of the tonic-subtracted residual, via
|
|
509
|
+
``config['noise_method']``.
|
|
510
|
+
peaks : numpy.ndarray
|
|
511
|
+
Indices of detected phasic event peaks (rise-rate gated).
|
|
512
|
+
tonic : numpy.ndarray
|
|
513
|
+
Fitted tonic (slow baseline), same length as the input trace.
|
|
514
|
+
residual : numpy.ndarray
|
|
515
|
+
Tonic-subtracted residual (``trace - tonic``).
|
|
516
|
+
signal : float
|
|
517
|
+
Suprathreshold peak-amplitude statistic used as
|
|
518
|
+
``snr_phasic``'s numerator (median or 95th percentile, per
|
|
519
|
+
``signal_statistic``).
|
|
520
|
+
config : dict
|
|
521
|
+
The resolved configuration used for this fit.
|
|
522
|
+
"""
|
|
523
|
+
|
|
524
|
+
snr: float
|
|
525
|
+
snr_tonic: float
|
|
526
|
+
snr_phasic: float
|
|
527
|
+
noise: float
|
|
528
|
+
peaks: NDArray[np.intp]
|
|
529
|
+
tonic: NDArray[np.floating]
|
|
530
|
+
residual: NDArray[np.floating]
|
|
531
|
+
signal: float
|
|
532
|
+
config: Dict = field(repr=False)
|
|
533
|
+
snr_corrected: Optional[float] = None
|
|
534
|
+
snr_phasic_corrected: Optional[float] = None
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
class EnvelopeRRSNR:
|
|
538
|
+
"""Envelope + rise-rate SNR estimator for 1D fluorescence traces.
|
|
539
|
+
|
|
540
|
+
Parameters
|
|
541
|
+
----------
|
|
542
|
+
fps : float, optional
|
|
543
|
+
Sampling frequency (frames per second), by default ``20.0``.
|
|
544
|
+
peak_threshold_sd : float, optional
|
|
545
|
+
Detection threshold for candidate phasic peaks, in units of the
|
|
546
|
+
estimated noise sigma (unitless; does not scale with ``fps``).
|
|
547
|
+
Defaults to ``2.0``, grid-search-optimal for
|
|
548
|
+
``noise_method='aind_mad'`` with ``tonic_method='arpls'``
|
|
549
|
+
(score=0.762). ``folded_iqr`` also optimizes at ``2.0``;
|
|
550
|
+
``mad_iqr_avg`` optimizes at ``2.5`` -- don't assume one
|
|
551
|
+
``noise_method``'s tuned threshold transfers to another.
|
|
552
|
+
signal_statistic : {'median', 'p95'}, optional
|
|
553
|
+
Statistic of the suprathreshold peak amplitudes used as the SNR
|
|
554
|
+
numerator, by default ``'median'``.
|
|
555
|
+
noise_method : {'aind_mad', 'folded_iqr', 'mad_iqr_avg'}, optional
|
|
556
|
+
Noise-floor estimator on the tonic-subtracted residual, by
|
|
557
|
+
default ``'aind_mad'``.
|
|
558
|
+
|
|
559
|
+
- ``'aind_mad'``: local clone of aind-ophys-utils'
|
|
560
|
+
``noise_std(method='mad')`` (see :func:`_mad_noise_std`) --
|
|
561
|
+
reproduces it exactly without depending on that package.
|
|
562
|
+
- ``'folded_iqr'``: folds the below-mode half of the residual
|
|
563
|
+
(mode via :func:`_half_sample_mode`) and scales the IQR.
|
|
564
|
+
- ``'mad_iqr_avg'``: mean of the two above.
|
|
565
|
+
|
|
566
|
+
``'mad'`` is a deprecated alias for ``'aind_mad'`` (raises
|
|
567
|
+
``DeprecationWarning``).
|
|
568
|
+
bias_correction : tuple of (slope, intercept), or None, optional
|
|
569
|
+
If given, ``snr_phasic_corrected = (snr_phasic - intercept) /
|
|
570
|
+
slope`` is computed on every fit -- this was fit against
|
|
571
|
+
``snr_phasic`` specifically (the only quantity ever validated
|
|
572
|
+
against ground truth), not the total ``snr``; ``snr_corrected``
|
|
573
|
+
(the corrected total) is then ``snr_tonic + snr_phasic_corrected``,
|
|
574
|
+
a derived combination rather than an independently-validated
|
|
575
|
+
correction. Defaults to a tuned fit
|
|
576
|
+
(``slope=1.8494, intercept=-0.5508, R^2=0.9462``), but only
|
|
577
|
+
auto-applies when ``noise_method``, ``peak_threshold_sd``, and
|
|
578
|
+
``tonic_method`` all still match the defaults it was fit
|
|
579
|
+
against (``'aind_mad'``, ``2.0``, ``'arpls'``); change any of
|
|
580
|
+
those and this silently resolves to ``None`` instead of
|
|
581
|
+
misapplying a correction fit for a different configuration.
|
|
582
|
+
Pass ``bias_correction=None`` explicitly to disable it even
|
|
583
|
+
with the tuned defaults. Fit your own via
|
|
584
|
+
:meth:`fit_bias_correction_from_benchmark` or
|
|
585
|
+
``numpy.polyfit(true_snr, snr_est, 1)`` for other
|
|
586
|
+
configurations -- each sits at its own scale.
|
|
587
|
+
config : dict, optional
|
|
588
|
+
Overrides merged on top of the fps-scaled tuned defaults
|
|
589
|
+
(``lower_min_distance``, ``lower_smooth_window``,
|
|
590
|
+
``rise_window``) and this module's fixed defaults -- see
|
|
591
|
+
``_DEFAULT_CONFIG``. Notably ``config={'tonic_method': 'als'}``
|
|
592
|
+
or ``'envelope'`` to change the tonic tracker (default
|
|
593
|
+
``'arpls'`` -- see :func:`_arpls_baseline`), or
|
|
594
|
+
``config={'noise_method': ...}``, which takes precedence over
|
|
595
|
+
the ``noise_method`` argument.
|
|
596
|
+
|
|
597
|
+
Notes
|
|
598
|
+
-----
|
|
599
|
+
- Noise is estimated from the tonic-subtracted residual, not the
|
|
600
|
+
raw derivative, so it's robust to slow drift and phasic events.
|
|
601
|
+
- If fewer than one phasic peak is found, ``snr_phasic`` is ``NaN``
|
|
602
|
+
(and so is the total ``snr``, via propagation) and a
|
|
603
|
+
``RuntimeWarning`` is issued; ``snr_tonic`` is still computed.
|
|
604
|
+
- **Window defaults scale with fps.** ``lower_min_distance``,
|
|
605
|
+
``lower_smooth_window``, and ``rise_window`` are tuned at 20 fps
|
|
606
|
+
and rescaled by :meth:`scale_window` to preserve real-world
|
|
607
|
+
duration at other rates (``lower_smooth_window`` forced odd).
|
|
608
|
+
Pass an explicit value in ``config`` to opt out.
|
|
609
|
+
"""
|
|
610
|
+
|
|
611
|
+
def __init__(
|
|
612
|
+
self,
|
|
613
|
+
fps: float = 20.0,
|
|
614
|
+
peak_threshold_sd: float = _TUNED_DEFAULTS["peak_threshold_sd"],
|
|
615
|
+
signal_statistic: str = "median",
|
|
616
|
+
noise_method: str = _DEFAULT_NOISE_METHOD,
|
|
617
|
+
bias_correction: Union[Tuple[float, float], None, "_UnsetType"] = _UNSET,
|
|
618
|
+
config: Optional[Dict] = None,
|
|
619
|
+
) -> None:
|
|
620
|
+
"""Construct an estimator; see the class docstring for parameter details."""
|
|
621
|
+
if signal_statistic not in ("median", "p95"):
|
|
622
|
+
raise ValueError(
|
|
623
|
+
f"signal_statistic must be 'median' or 'p95', got {signal_statistic!r}."
|
|
624
|
+
)
|
|
625
|
+
# config={'noise_method': ...} takes precedence over the argument.
|
|
626
|
+
effective_noise_method = (config or {}).get("noise_method", noise_method)
|
|
627
|
+
if effective_noise_method in _DEPRECATED_NOISE_METHOD_ALIASES:
|
|
628
|
+
new_name = _DEPRECATED_NOISE_METHOD_ALIASES[effective_noise_method]
|
|
629
|
+
effective_noise_method = new_name
|
|
630
|
+
if effective_noise_method not in _VALID_NOISE_METHODS:
|
|
631
|
+
raise ValueError(
|
|
632
|
+
f"noise_method must be one of {_VALID_NOISE_METHODS} "
|
|
633
|
+
f"(or the deprecated alias 'mad' for 'aind_mad'), "
|
|
634
|
+
f"got {effective_noise_method!r}."
|
|
635
|
+
)
|
|
636
|
+
|
|
637
|
+
# Same precedence, for the other two settings _TUNED_BIAS_CORRECTION
|
|
638
|
+
# was fit against -- needed to decide if it's safe to auto-apply.
|
|
639
|
+
effective_peak_threshold_sd = (config or {}).get("peak_threshold_sd", peak_threshold_sd)
|
|
640
|
+
effective_tonic_method = (config or {}).get("tonic_method", _DEFAULT_CONFIG["tonic_method"])
|
|
641
|
+
|
|
642
|
+
if bias_correction is _UNSET:
|
|
643
|
+
# Auto-apply the tuned correction only if noise_method,
|
|
644
|
+
# peak_threshold_sd, and tonic_method all match what it was
|
|
645
|
+
# fit against -- otherwise it'd silently misapply a
|
|
646
|
+
# correction fit for a different configuration.
|
|
647
|
+
matches_tuned_config = (
|
|
648
|
+
effective_noise_method == _DEFAULT_NOISE_METHOD
|
|
649
|
+
and effective_peak_threshold_sd == _TUNED_DEFAULTS["peak_threshold_sd"]
|
|
650
|
+
and effective_tonic_method == _DEFAULT_CONFIG["tonic_method"]
|
|
651
|
+
)
|
|
652
|
+
bias_correction = _TUNED_BIAS_CORRECTION if matches_tuned_config else None
|
|
653
|
+
|
|
654
|
+
self.fps = fps
|
|
655
|
+
self.peak_threshold_sd = effective_peak_threshold_sd
|
|
656
|
+
self.signal_statistic = signal_statistic
|
|
657
|
+
self.noise_method = effective_noise_method
|
|
658
|
+
self.bias_correction = bias_correction
|
|
659
|
+
|
|
660
|
+
scaled_defaults = {
|
|
661
|
+
"lower_min_distance": self.scale_window(_TUNED_DEFAULTS["lower_min_distance"], fps),
|
|
662
|
+
"lower_smooth_window": self.scale_window(
|
|
663
|
+
_TUNED_DEFAULTS["lower_smooth_window"], fps, make_odd=True
|
|
664
|
+
),
|
|
665
|
+
"rise_window": self.scale_window(_TUNED_DEFAULTS["rise_window"], fps),
|
|
666
|
+
}
|
|
667
|
+
self.config = {
|
|
668
|
+
**_DEFAULT_CONFIG,
|
|
669
|
+
"fps": fps,
|
|
670
|
+
"peak_threshold_sd": peak_threshold_sd,
|
|
671
|
+
**scaled_defaults,
|
|
672
|
+
**(config or {}),
|
|
673
|
+
# Set last (resolved, canonical name) so a raw alias in
|
|
674
|
+
# `config` can't override it back to the deprecated spelling.
|
|
675
|
+
"noise_method": effective_noise_method,
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
# populated by fit()
|
|
679
|
+
self.result_: Optional[EnvelopeRRResult] = None
|
|
680
|
+
|
|
681
|
+
@staticmethod
|
|
682
|
+
def scale_window(
|
|
683
|
+
base_samples: int,
|
|
684
|
+
fps: float,
|
|
685
|
+
reference_fps: float = _REFERENCE_FPS,
|
|
686
|
+
make_odd: bool = False,
|
|
687
|
+
) -> int:
|
|
688
|
+
"""Rescale a sample-count window to a new fps, preserving duration.
|
|
689
|
+
|
|
690
|
+
Returns ``round(base_samples * fps / reference_fps)``, floored
|
|
691
|
+
at 1. If ``make_odd``, increments by 1 if the result is even
|
|
692
|
+
(required by e.g. Savitzky-Golay windows).
|
|
693
|
+
|
|
694
|
+
Example
|
|
695
|
+
-------
|
|
696
|
+
>>> EnvelopeRRSNR.scale_window(20, fps=40.0)
|
|
697
|
+
40
|
|
698
|
+
"""
|
|
699
|
+
n = int(round(base_samples * fps / reference_fps))
|
|
700
|
+
n = max(1, n)
|
|
701
|
+
if make_odd and n % 2 == 0:
|
|
702
|
+
n += 1
|
|
703
|
+
return n
|
|
704
|
+
|
|
705
|
+
# ------------------------------------------------------------------
|
|
706
|
+
# Core API
|
|
707
|
+
# ------------------------------------------------------------------
|
|
708
|
+
|
|
709
|
+
def fit(self, trace: NDArray[np.floating]) -> EnvelopeRRResult:
|
|
710
|
+
"""Decompose ``trace`` and estimate its SNR.
|
|
711
|
+
|
|
712
|
+
NaNs in ``trace`` are replaced with its median first. Returns
|
|
713
|
+
an :class:`EnvelopeRRResult`, also stored on ``self.result_``
|
|
714
|
+
for the convenience properties (``self.snr_``, etc.).
|
|
715
|
+
"""
|
|
716
|
+
trace = np.nan_to_num(trace, nan=float(np.nanmedian(trace)))
|
|
717
|
+
|
|
718
|
+
with warnings.catch_warnings():
|
|
719
|
+
warnings.simplefilter("ignore")
|
|
720
|
+
raw = _decompose_envelope_rr(trace, self.config)
|
|
721
|
+
|
|
722
|
+
snr_key = "phasic_snr_p95" if self.signal_statistic == "p95" else "phasic_snr_median"
|
|
723
|
+
sig_key = "phasic_p95" if self.signal_statistic == "p95" else "phasic_median"
|
|
724
|
+
|
|
725
|
+
peaks = np.asarray(raw["event_maxima"], dtype=int)
|
|
726
|
+
snr_phasic = float(raw[snr_key])
|
|
727
|
+
snr_tonic = float(raw["tonic_snr_sd"])
|
|
728
|
+
noise = float(raw["noise_sigma"])
|
|
729
|
+
signal = float(raw[sig_key])
|
|
730
|
+
|
|
731
|
+
if len(peaks) == 0:
|
|
732
|
+
warnings.warn(
|
|
733
|
+
"No phasic peaks detected above threshold. Returning NaN for snr_phasic.",
|
|
734
|
+
RuntimeWarning,
|
|
735
|
+
stacklevel=2,
|
|
736
|
+
)
|
|
737
|
+
snr_phasic = float("nan")
|
|
738
|
+
|
|
739
|
+
snr_total = snr_tonic + snr_phasic # NaN-propagates if snr_phasic is NaN
|
|
740
|
+
|
|
741
|
+
snr_phasic_corrected = None
|
|
742
|
+
snr_corrected = None
|
|
743
|
+
if self.bias_correction is not None and not np.isnan(snr_phasic):
|
|
744
|
+
# bias_correction was fit against snr_phasic specifically (the
|
|
745
|
+
# only quantity ever validated against ground truth) -- see
|
|
746
|
+
# EnvelopeRRResult's docstring for why snr_corrected (a total)
|
|
747
|
+
# is therefore a derived combination, not itself validated.
|
|
748
|
+
slope, intercept = self.bias_correction
|
|
749
|
+
snr_phasic_corrected = float((snr_phasic - intercept) / slope)
|
|
750
|
+
snr_corrected = snr_tonic + snr_phasic_corrected
|
|
751
|
+
|
|
752
|
+
self.result_ = EnvelopeRRResult(
|
|
753
|
+
snr=snr_total,
|
|
754
|
+
snr_tonic=snr_tonic,
|
|
755
|
+
snr_phasic=snr_phasic,
|
|
756
|
+
snr_corrected=snr_corrected,
|
|
757
|
+
snr_phasic_corrected=snr_phasic_corrected,
|
|
758
|
+
noise=noise,
|
|
759
|
+
peaks=peaks,
|
|
760
|
+
tonic=raw["tonic"],
|
|
761
|
+
residual=raw["residual"],
|
|
762
|
+
signal=signal,
|
|
763
|
+
config=raw["config"],
|
|
764
|
+
)
|
|
765
|
+
return self.result_
|
|
766
|
+
|
|
767
|
+
def estimate(
|
|
768
|
+
self, trace: NDArray[np.floating], apply_correction: bool = False
|
|
769
|
+
) -> Tuple[float, float, NDArray[np.intp]]:
|
|
770
|
+
"""One-shot functional interface: ``fit`` and return a 3-tuple.
|
|
771
|
+
|
|
772
|
+
Returns ``(snr, noise, peaks)``, the same shape as a plain
|
|
773
|
+
derivative-based ``estimate_snr(trace, fps)`` function, for
|
|
774
|
+
drop-in comparison. ``snr`` is the **total**
|
|
775
|
+
(``snr_tonic + snr_phasic``). Use :meth:`estimate_components`
|
|
776
|
+
for the tonic/phasic breakdown without giving up this shape.
|
|
777
|
+
|
|
778
|
+
Returns the raw (uncorrected) total by default even if
|
|
779
|
+
``bias_correction`` is configured; pass ``apply_correction=True``
|
|
780
|
+
to get ``snr_corrected`` instead. Use ``.fit(trace)`` directly
|
|
781
|
+
for repeated calls to avoid recomputing.
|
|
782
|
+
"""
|
|
783
|
+
result = self.fit(trace)
|
|
784
|
+
if apply_correction and result.snr_corrected is not None:
|
|
785
|
+
snr = result.snr_corrected
|
|
786
|
+
else:
|
|
787
|
+
snr = result.snr
|
|
788
|
+
return snr, result.noise, result.peaks
|
|
789
|
+
|
|
790
|
+
def estimate_components(
|
|
791
|
+
self, trace: NDArray[np.floating], apply_correction: bool = False
|
|
792
|
+
) -> Tuple[float, float, float]:
|
|
793
|
+
"""One-shot SNR breakdown: ``fit`` and return
|
|
794
|
+
``(snr_total, snr_tonic, snr_phasic)``.
|
|
795
|
+
|
|
796
|
+
Companion to :meth:`estimate`, which only returns the total (to
|
|
797
|
+
keep that method's 3-tuple shape drop-in compatible with a
|
|
798
|
+
plain ``estimate_snr(trace, fps)`` function). ``snr_total``
|
|
799
|
+
here always equals :meth:`estimate`'s first element under the
|
|
800
|
+
same ``apply_correction`` setting.
|
|
801
|
+
|
|
802
|
+
Returns raw (uncorrected) values by default; pass
|
|
803
|
+
``apply_correction=True`` to get ``snr_corrected`` and
|
|
804
|
+
``snr_phasic_corrected`` for the 1st/3rd elements (``snr_tonic``
|
|
805
|
+
has no correction to apply, so it's unaffected either way).
|
|
806
|
+
"""
|
|
807
|
+
result = self.fit(trace)
|
|
808
|
+
if apply_correction and result.snr_corrected is not None:
|
|
809
|
+
return result.snr_corrected, result.snr_tonic, result.snr_phasic_corrected
|
|
810
|
+
return result.snr, result.snr_tonic, result.snr_phasic
|
|
811
|
+
|
|
812
|
+
def decompose(
|
|
813
|
+
self, trace: Optional[NDArray[np.floating]] = None
|
|
814
|
+
) -> Tuple[NDArray[np.floating], NDArray[np.floating]]:
|
|
815
|
+
"""Return the (tonic, phasic) decomposition of a trace.
|
|
816
|
+
|
|
817
|
+
Convenience wrapper around :meth:`fit`. "Phasic" is the tonic-
|
|
818
|
+
subtracted residual (``trace - tonic``, same as
|
|
819
|
+
``EnvelopeRRResult.residual``). If ``trace`` is omitted, returns
|
|
820
|
+
the decomposition from the most recent :meth:`fit`/
|
|
821
|
+
:meth:`estimate` call (raises if not yet fit).
|
|
822
|
+
|
|
823
|
+
Example
|
|
824
|
+
-------
|
|
825
|
+
>>> import numpy as np
|
|
826
|
+
>>> y = 0.01 * np.random.default_rng(0).standard_normal(1200)
|
|
827
|
+
>>> tonic, phasic = EnvelopeRRSNR(fps=20.0).decompose(y)
|
|
828
|
+
>>> np.allclose(phasic, y - tonic)
|
|
829
|
+
True
|
|
830
|
+
"""
|
|
831
|
+
if trace is not None:
|
|
832
|
+
result = self.fit(trace)
|
|
833
|
+
else:
|
|
834
|
+
self._check_fitted()
|
|
835
|
+
result = self.result_
|
|
836
|
+
return result.tonic, result.residual
|
|
837
|
+
|
|
838
|
+
# ------------------------------------------------------------------
|
|
839
|
+
# Convenience read-only views onto the last fit
|
|
840
|
+
# ------------------------------------------------------------------
|
|
841
|
+
|
|
842
|
+
@property
|
|
843
|
+
def snr_(self) -> float:
|
|
844
|
+
"""Total SNR (``snr_tonic_ + snr_phasic_``) from the most recent
|
|
845
|
+
:meth:`fit` call (raw, uncorrected)."""
|
|
846
|
+
self._check_fitted()
|
|
847
|
+
return self.result_.snr
|
|
848
|
+
|
|
849
|
+
@property
|
|
850
|
+
def snr_corrected_(self) -> Optional[float]:
|
|
851
|
+
"""Bias-corrected total SNR from the most recent :meth:`fit` call."""
|
|
852
|
+
self._check_fitted()
|
|
853
|
+
return self.result_.snr_corrected
|
|
854
|
+
|
|
855
|
+
@property
|
|
856
|
+
def snr_tonic_(self) -> float:
|
|
857
|
+
"""Tonic-baseline SNR from the most recent :meth:`fit` call."""
|
|
858
|
+
self._check_fitted()
|
|
859
|
+
return self.result_.snr_tonic
|
|
860
|
+
|
|
861
|
+
@property
|
|
862
|
+
def snr_phasic_(self) -> float:
|
|
863
|
+
"""Phasic SNR from the most recent :meth:`fit` call (raw, uncorrected)."""
|
|
864
|
+
self._check_fitted()
|
|
865
|
+
return self.result_.snr_phasic
|
|
866
|
+
|
|
867
|
+
@property
|
|
868
|
+
def noise_(self) -> float:
|
|
869
|
+
"""Noise floor from the most recent :meth:`fit` call."""
|
|
870
|
+
self._check_fitted()
|
|
871
|
+
return self.result_.noise
|
|
872
|
+
|
|
873
|
+
@property
|
|
874
|
+
def peaks_(self) -> NDArray[np.intp]:
|
|
875
|
+
"""Detected phasic peak indices from the most recent :meth:`fit` call."""
|
|
876
|
+
self._check_fitted()
|
|
877
|
+
return self.result_.peaks
|
|
878
|
+
|
|
879
|
+
@property
|
|
880
|
+
def tonic_(self) -> NDArray[np.floating]:
|
|
881
|
+
"""Fitted tonic envelope from the most recent :meth:`fit` call."""
|
|
882
|
+
self._check_fitted()
|
|
883
|
+
return self.result_.tonic
|
|
884
|
+
|
|
885
|
+
@property
|
|
886
|
+
def residual_(self) -> NDArray[np.floating]:
|
|
887
|
+
"""Tonic-subtracted residual from the most recent :meth:`fit` call."""
|
|
888
|
+
self._check_fitted()
|
|
889
|
+
return self.result_.residual
|
|
890
|
+
|
|
891
|
+
def _check_fitted(self) -> None:
|
|
892
|
+
"""Raise RuntimeError if fit()/estimate()/decompose() hasn't been called yet."""
|
|
893
|
+
if self.result_ is None:
|
|
894
|
+
raise RuntimeError(
|
|
895
|
+
"This EnvelopeRRSNR instance has not been fit yet. "
|
|
896
|
+
"Call `.fit(trace)`, `.estimate(trace)`, or `.decompose(trace)` first."
|
|
897
|
+
)
|
|
898
|
+
|
|
899
|
+
# ------------------------------------------------------------------
|
|
900
|
+
# Bias-correction helper
|
|
901
|
+
# ------------------------------------------------------------------
|
|
902
|
+
|
|
903
|
+
@staticmethod
|
|
904
|
+
def fit_bias_correction_from_benchmark(
|
|
905
|
+
true_snr: NDArray[np.floating], snr_est: NDArray[np.floating]
|
|
906
|
+
) -> Tuple[float, float]:
|
|
907
|
+
"""Fit a linear bias correction from benchmark ground truth.
|
|
908
|
+
|
|
909
|
+
Convenience wrapper around ``numpy.polyfit`` for correcting a
|
|
910
|
+
consistent linear bias found by sweeping known SNR levels. Fit
|
|
911
|
+
this against ``snr_phasic`` (not the total ``snr``), separately
|
|
912
|
+
per configuration (``noise_method``, ``peak_threshold_sd``,
|
|
913
|
+
``tonic_method``) -- each sits at its own scale. Returns
|
|
914
|
+
``(slope, intercept)``; pass directly as
|
|
915
|
+
``bias_correction=(slope, intercept)`` to the constructor.
|
|
916
|
+
|
|
917
|
+
Example
|
|
918
|
+
-------
|
|
919
|
+
>>> import numpy as np
|
|
920
|
+
>>> true_snr = np.array([5.0, 10.0, 20.0, 40.0])
|
|
921
|
+
>>> snr_est = 0.9 * true_snr + 1.5 # simulated linear bias
|
|
922
|
+
>>> slope, intercept = EnvelopeRRSNR.fit_bias_correction_from_benchmark(
|
|
923
|
+
... true_snr, snr_est)
|
|
924
|
+
"""
|
|
925
|
+
true_snr = np.asarray(true_snr, dtype=float)
|
|
926
|
+
snr_est = np.asarray(snr_est, dtype=float)
|
|
927
|
+
ok = np.isfinite(true_snr) & np.isfinite(snr_est)
|
|
928
|
+
slope, intercept = np.polyfit(true_snr[ok], snr_est[ok], 1)
|
|
929
|
+
return float(slope), float(intercept)
|
|
@@ -617,8 +617,13 @@ def plot_session_in_time_nwb_plotly( # noqa: C901 pragma: no cover
|
|
|
617
617
|
df_fip = pd.concat(fip_acc, ignore_index=True) if fip_acc else None
|
|
618
618
|
|
|
619
619
|
return plot_session_in_time_plotly(
|
|
620
|
-
df_events,
|
|
621
|
-
|
|
620
|
+
df_events,
|
|
621
|
+
df_trials,
|
|
622
|
+
df_fip,
|
|
623
|
+
fip=fip,
|
|
624
|
+
adjust_time=adjust_time,
|
|
625
|
+
title=title,
|
|
626
|
+
smooth_factor=smooth_factor,
|
|
622
627
|
)
|
|
623
628
|
|
|
624
629
|
|
|
@@ -811,17 +816,17 @@ def plot_session_in_time_plotly( # noqa: C901 pragma: no cover
|
|
|
811
816
|
moving_average(~np.isnan(choice), smooth_factor) + 1e-6
|
|
812
817
|
)
|
|
813
818
|
sm[sm > 100] = np.nan
|
|
814
|
-
xsm = gc[off_s:
|
|
819
|
+
xsm = gc[off_s:off_s + len(sm)]
|
|
815
820
|
choice_x += [*xsm, None]
|
|
816
821
|
choice_y += [*_to_curve(sm[: len(xsm)]), None]
|
|
817
822
|
lt = np.concatenate([_ev("left_lick_time"), _ev("right_lick_time")])
|
|
818
823
|
if len(lt):
|
|
819
|
-
counts = np.bincount(_trial_of(lt), minlength=n_tr + 1)[1:
|
|
824
|
+
counts = np.bincount(_trial_of(lt), minlength=n_tr + 1)[1:n_tr + 1]
|
|
820
825
|
sm = moving_average(counts.astype(float), smooth_factor)
|
|
821
826
|
top = np.nanmax(sm) if len(sm) else 0
|
|
822
827
|
if top > 0:
|
|
823
828
|
sm = sm / top
|
|
824
|
-
xsm = gc[off_s:
|
|
829
|
+
xsm = gc[off_s:off_s + len(sm)]
|
|
825
830
|
lick_x += [*xsm, None]
|
|
826
831
|
lick_y += [*_to_curve(sm[: len(xsm)]), None]
|
|
827
832
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
aind_dynamic_foraging_basic_analysis/__init__.py,sha256=
|
|
1
|
+
aind_dynamic_foraging_basic_analysis/__init__.py,sha256=pO-o8--kyozQbswBSFFd7wNFGe1NLO-Afwy_zecsGbo,410
|
|
2
2
|
aind_dynamic_foraging_basic_analysis/data_model/foraging_session.py,sha256=7PFHfEIXP3QcjFS9Fk88S7PzBBYnUYw81WBjjEu_UKo,3536
|
|
3
3
|
aind_dynamic_foraging_basic_analysis/licks/annotation.py,sha256=04NKOxqGS1B06WDPH_9Pu1rgyDq1LwvXbc0YDLIx6Io,13305
|
|
4
4
|
aind_dynamic_foraging_basic_analysis/licks/lick_analysis.py,sha256=WqaDbAinxmkRpGez92kBoc4YpyuLbDBNEOfq06bbXhY,20333
|
|
@@ -6,15 +6,16 @@ aind_dynamic_foraging_basic_analysis/licks/plot_interlick_interval.py,sha256=fld
|
|
|
6
6
|
aind_dynamic_foraging_basic_analysis/metrics/event_rate.py,sha256=8X7hx_4thFLa61k90W4--cBr3-4L89T5YXggSHa9FXM,3520
|
|
7
7
|
aind_dynamic_foraging_basic_analysis/metrics/foraging_efficiency.py,sha256=9IhMqQo_aU_RFsDu8D2P3-Qu3J72bo7sASC3dkUQ2YE,8634
|
|
8
8
|
aind_dynamic_foraging_basic_analysis/metrics/session_metrics.py,sha256=3oWHVbGRsOBVtlNoBJcd6_HcK178i9rkmvy8eALpzKo,6113
|
|
9
|
+
aind_dynamic_foraging_basic_analysis/metrics/snr_envelope_rr.py,sha256=Egxarot52mRb4hPh_uJj44h4Y1ADyPE_IOuKiWm7gV4,38655
|
|
9
10
|
aind_dynamic_foraging_basic_analysis/metrics/snr_kurtosis.py,sha256=F7SJ2zwleMPdmRu5RD9T0YEY482i5D90x1PZjujoD5U,5073
|
|
10
11
|
aind_dynamic_foraging_basic_analysis/metrics/trial_metrics.py,sha256=OxJvxz1XssEFJ5Nrnlqqgx9UsftbzTDonFIE65azLKM,13220
|
|
11
12
|
aind_dynamic_foraging_basic_analysis/plot/plot_fip.py,sha256=Lkw9YafpB6Kv3-pnZ663mc83o16tYNnekRqhb4TD2Ss,26962
|
|
12
13
|
aind_dynamic_foraging_basic_analysis/plot/plot_foraging_session.py,sha256=06OEfIZTtE6zEH1iQLTrzadwxGB5rntlSyh8KPhFfEs,16914
|
|
13
|
-
aind_dynamic_foraging_basic_analysis/plot/plot_foraging_session_plotly.py,sha256=
|
|
14
|
+
aind_dynamic_foraging_basic_analysis/plot/plot_foraging_session_plotly.py,sha256=5KQnDbBXCpUUMz4iYPV56ihpTgxXz-EnawWGeVD69ek,39213
|
|
14
15
|
aind_dynamic_foraging_basic_analysis/plot/plot_session_scroller.py,sha256=_3vYP7zBkiq9psR1ph_cuNhOzvV3emdco2wnmO5ud5A,18255
|
|
15
16
|
aind_dynamic_foraging_basic_analysis/plot/style.py,sha256=9OE22zVQR39FBt4mfdRFA43YbqXwhQF71VBSiFP65Qk,2649
|
|
16
|
-
aind_dynamic_foraging_basic_analysis-0.4.
|
|
17
|
-
aind_dynamic_foraging_basic_analysis-0.4.
|
|
18
|
-
aind_dynamic_foraging_basic_analysis-0.4.
|
|
19
|
-
aind_dynamic_foraging_basic_analysis-0.4.
|
|
20
|
-
aind_dynamic_foraging_basic_analysis-0.4.
|
|
17
|
+
aind_dynamic_foraging_basic_analysis-0.4.2.dist-info/licenses/LICENSE,sha256=U0Y7B3gZJHXpjJVLgTQjM8e_c8w4JJpLgGhIdsoFR1Y,1092
|
|
18
|
+
aind_dynamic_foraging_basic_analysis-0.4.2.dist-info/METADATA,sha256=W3wxomeIAdKH5S2AyaJQZqKwvtCVmijWoCh_62ETnf4,9876
|
|
19
|
+
aind_dynamic_foraging_basic_analysis-0.4.2.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
20
|
+
aind_dynamic_foraging_basic_analysis-0.4.2.dist-info/top_level.txt,sha256=gc5fvvd3cR7uvCHkTaSx-TcC4JmKMt9dBYMPncEO8VY,37
|
|
21
|
+
aind_dynamic_foraging_basic_analysis-0.4.2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|