aind-dynamic-foraging-basic-analysis 0.4.2__py3-none-any.whl → 0.4.3__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 +623 -62
- {aind_dynamic_foraging_basic_analysis-0.4.2.dist-info → aind_dynamic_foraging_basic_analysis-0.4.3.dist-info}/METADATA +1 -1
- {aind_dynamic_foraging_basic_analysis-0.4.2.dist-info → aind_dynamic_foraging_basic_analysis-0.4.3.dist-info}/RECORD +7 -7
- {aind_dynamic_foraging_basic_analysis-0.4.2.dist-info → aind_dynamic_foraging_basic_analysis-0.4.3.dist-info}/WHEEL +0 -0
- {aind_dynamic_foraging_basic_analysis-0.4.2.dist-info → aind_dynamic_foraging_basic_analysis-0.4.3.dist-info}/licenses/LICENSE +0 -0
- {aind_dynamic_foraging_basic_analysis-0.4.2.dist-info → aind_dynamic_foraging_basic_analysis-0.4.3.dist-info}/top_level.txt +0 -0
|
@@ -37,27 +37,43 @@ Notes
|
|
|
37
37
|
- Default ``fps`` is 20 Hz; NaNs are filled with the trace median.
|
|
38
38
|
- Needs only numpy/scipy -- no other dependencies for any ``noise_method``.
|
|
39
39
|
|
|
40
|
-
Example
|
|
40
|
+
Example: random noise with sinusoidal tonic baseline (SNR ~ 10)
|
|
41
|
+
and no real phasic transients (SNR ~ 0)
|
|
41
42
|
-------
|
|
43
|
+
|
|
42
44
|
>>> import numpy as np
|
|
43
45
|
>>> from snr_envelope_rr import EnvelopeRRSNR
|
|
44
|
-
>>> rng = np.random.default_rng(
|
|
46
|
+
>>> rng = np.random.default_rng(2)
|
|
45
47
|
>>> t = np.arange(1200) / 20.0
|
|
46
|
-
>>>
|
|
47
|
-
>>>
|
|
48
|
-
>>>
|
|
48
|
+
>>> noise_floor = 0.01
|
|
49
|
+
>>> tonic_amp = 5 * noise_floor # 10 * noise floor
|
|
50
|
+
>>> y = tonic_amp * np.sin(2 * np.pi * t / 40.0) + noise_floor * rng.standard_normal(1200)
|
|
51
|
+
>>> estimator = EnvelopeRRSNR(fps=20.0)
|
|
52
|
+
>>> result = estimator.fit(y)
|
|
53
|
+
>>> snr, noise, peaks = estimator.estimate(y) # one-shot form
|
|
54
|
+
>>> print(f"total SNR: {snr}")
|
|
55
|
+
total SNR: 12.965802243331636
|
|
56
|
+
>>> print(f"noise estimate (true=0.01): {noise}")
|
|
57
|
+
noise estimate (true=0.01): 0.009333765351685406
|
|
58
|
+
>>> print(f"detected peaks: {peaks}")
|
|
59
|
+
detected peaks: [ 56 105 291 348 604 724]
|
|
60
|
+
>>> print(f"tonic SNR (true=10.0): {result.snr_tonic:.2f}")
|
|
61
|
+
tonic SNR (true=10.0): 10.17
|
|
62
|
+
>>> print(f"phasic SNR (true=0.0): {result.snr_phasic:.2f}")
|
|
63
|
+
phasic SNR (true=0.0): 2.80
|
|
49
64
|
True
|
|
65
|
+
|
|
50
66
|
"""
|
|
51
67
|
|
|
52
68
|
from __future__ import annotations
|
|
53
69
|
|
|
54
70
|
import warnings
|
|
55
|
-
from dataclasses import dataclass, field
|
|
71
|
+
from dataclasses import dataclass, field, replace
|
|
56
72
|
from typing import Dict, Optional, Tuple, Union
|
|
57
73
|
|
|
58
74
|
import numpy as np
|
|
59
75
|
from numpy.typing import NDArray
|
|
60
|
-
from scipy import interpolate, ndimage, signal
|
|
76
|
+
from scipy import interpolate, ndimage, signal
|
|
61
77
|
|
|
62
78
|
__all__ = ["EnvelopeRRSNR", "EnvelopeRRResult"]
|
|
63
79
|
|
|
@@ -88,6 +104,12 @@ _TUNED_DEFAULTS = {
|
|
|
88
104
|
# fit_bias_correction_from_benchmark for a different configuration.
|
|
89
105
|
_TUNED_BIAS_CORRECTION: Tuple[float, float] = (1.8494, -0.5508)
|
|
90
106
|
|
|
107
|
+
# Only used if tonic_range_method='robust' -- samples at the reference
|
|
108
|
+
# fps above (~5.0s); not tuned/validated like _TUNED_DEFAULTS, just a
|
|
109
|
+
# reasonable starting point (see _robust_tonic_range's docstring). Scaled
|
|
110
|
+
# to the instance's actual fps in __init__, same as _TUNED_DEFAULTS.
|
|
111
|
+
_DEFAULT_TONIC_ROBUST_MIN_DISTANCE = 100
|
|
112
|
+
|
|
91
113
|
|
|
92
114
|
class _UnsetType:
|
|
93
115
|
"""Sentinel distinguishing "bias_correction not specified" (auto-
|
|
@@ -211,6 +233,14 @@ def _mad_noise_std(residual: NDArray[np.floating], filter_length: int = 31) -> f
|
|
|
211
233
|
takes what's left, trims positive-peak outliers, then trims any
|
|
212
234
|
remaining outliers on either side, and returns the scaled MAD of
|
|
213
235
|
that twice-trimmed remainder.
|
|
236
|
+
|
|
237
|
+
Falls back to a less-trimmed robust std (rather than NaN) if a
|
|
238
|
+
trimming step empties out completely -- this happens on short or
|
|
239
|
+
heavily-anomalous windows (e.g. one chunk of a chunked/windowed
|
|
240
|
+
estimate landing squarely on a large artifact) where the first
|
|
241
|
+
trim's own scale estimate collapses to 0. Silently returning NaN
|
|
242
|
+
there would poison any downstream aggregation across windows
|
|
243
|
+
(``np.median`` propagates a single NaN to the whole result).
|
|
214
244
|
"""
|
|
215
245
|
residual = np.asarray(residual, dtype=np.float64)
|
|
216
246
|
if np.any(np.isnan(residual)):
|
|
@@ -221,8 +251,14 @@ def _mad_noise_std(residual: NDArray[np.floating], filter_length: int = 31) -> f
|
|
|
221
251
|
return float("nan")
|
|
222
252
|
filtered_0 = noise[noise < 1.5 * np.abs(noise.min())]
|
|
223
253
|
rstd = _robust_std(filtered_0)
|
|
224
|
-
filtered_1 = filtered_0[np.abs(filtered_0) < 2.5 * rstd]
|
|
225
|
-
|
|
254
|
+
filtered_1 = filtered_0[np.abs(filtered_0) < 2.5 * rstd] if rstd > 0 else np.array([])
|
|
255
|
+
if filtered_1.size > 0:
|
|
256
|
+
result = _robust_std(filtered_1)
|
|
257
|
+
if result > 0:
|
|
258
|
+
return result
|
|
259
|
+
if rstd > 0:
|
|
260
|
+
return rstd
|
|
261
|
+
return _robust_std(noise)
|
|
226
262
|
|
|
227
263
|
|
|
228
264
|
def _moving_average(
|
|
@@ -333,7 +369,24 @@ def _arpls_baseline(y, lam: float = 1e7, n_iter: int = 15, ratio: float = 1e-6):
|
|
|
333
369
|
|
|
334
370
|
def _detect_peaks_rise_rate(residual, candidates, sigma, rise_window: int = 3):
|
|
335
371
|
"""Reject candidate peaks whose approach isn't fast enough to be a
|
|
336
|
-
real transient onset (vs. a slow drift crossing threshold).
|
|
372
|
+
real transient onset (vs. a slow drift crossing threshold).
|
|
373
|
+
|
|
374
|
+
Calibrates its slope threshold from a robust (MAD-based) scale
|
|
375
|
+
estimate of the below-median ("noise-like") candidate slopes, not
|
|
376
|
+
an ordinary standard deviation (``scipy.stats.norm.fit``, what this
|
|
377
|
+
used before). Ordinary std is itself not robust: a single moderate
|
|
378
|
+
anomaly elsewhere in the trace can spawn a few large-magnitude
|
|
379
|
+
candidate slopes from its own decay tail, and even just one or two
|
|
380
|
+
of those landing in the "below-median" bucket can inflate an
|
|
381
|
+
ordinary std by 2x+ -- which pushes slope_thresh above genuine
|
|
382
|
+
events' own slopes and silently suppresses their detection
|
|
383
|
+
(measured: one moderate, localized anomaly cut detected event count
|
|
384
|
+
from 73 to 19 out of ~80 genuine events, purely through this
|
|
385
|
+
threshold-calibration side effect, though the anomaly itself was
|
|
386
|
+
nowhere near most of the suppressed events). The MAD-based estimate
|
|
387
|
+
used here left detection completely unchanged (73 to 73) on that
|
|
388
|
+
same case.
|
|
389
|
+
"""
|
|
337
390
|
if len(candidates) < 5:
|
|
338
391
|
return candidates
|
|
339
392
|
|
|
@@ -349,7 +402,7 @@ def _detect_peaks_rise_rate(residual, candidates, sigma, rise_window: int = 3):
|
|
|
349
402
|
|
|
350
403
|
lower = slopes[slopes <= np.median(slopes)]
|
|
351
404
|
if len(lower) >= 5:
|
|
352
|
-
|
|
405
|
+
sigma_slope = 1.4826 * np.median(np.abs(lower - np.median(lower)))
|
|
353
406
|
slope_thresh = max(sigma_slope * 3.0, sigma * 0.1)
|
|
354
407
|
else:
|
|
355
408
|
slope_thresh = np.percentile(slopes, 50)
|
|
@@ -357,79 +410,288 @@ def _detect_peaks_rise_rate(residual, candidates, sigma, rise_window: int = 3):
|
|
|
357
410
|
return candidates[slopes > slope_thresh]
|
|
358
411
|
|
|
359
412
|
|
|
360
|
-
def
|
|
361
|
-
|
|
362
|
-
|
|
413
|
+
def _despike_interpolate(
|
|
414
|
+
x: NDArray[np.floating], window: int, k: float
|
|
415
|
+
) -> Tuple[NDArray[np.floating], NDArray[np.bool_], float]:
|
|
416
|
+
"""Flag samples far from a local (rolling-median) baseline and
|
|
417
|
+
replace them via linear interpolation from the nearest un-flagged
|
|
418
|
+
samples on either side -- run *before* tonic fitting, not as a
|
|
419
|
+
replacement for it.
|
|
420
|
+
|
|
421
|
+
Why this and not a fixed-ceiling clip: clipping a decaying artifact
|
|
422
|
+
to a hard ceiling turns it into a flat plateau, which a smoothness-
|
|
423
|
+
penalized fit (arPLS/ALS) can end up tracking *more* readily than
|
|
424
|
+
the original decay, since a sustained flat elevation looks more
|
|
425
|
+
like genuine slow drift than a decaying transient does -- clipping
|
|
426
|
+
can make tonic contamination worse, not better (measured directly:
|
|
427
|
+
a naive global clip at 50x a robust noise estimate roughly
|
|
428
|
+
tripled downstream tonic contamination in one test case). Removing
|
|
429
|
+
the flagged span and interpolating over it avoids introducing that
|
|
430
|
+
new, more-trackable shape.
|
|
363
431
|
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
432
|
+
Parameters
|
|
433
|
+
----------
|
|
434
|
+
x : ndarray
|
|
435
|
+
window : int
|
|
436
|
+
Rolling-median window (samples) for the local baseline and
|
|
437
|
+
local MAD estimate.
|
|
438
|
+
k : float
|
|
439
|
+
Flag samples where ``|x - rolling_median| > k * local_MAD``.
|
|
440
|
+
|
|
441
|
+
Returns
|
|
442
|
+
-------
|
|
443
|
+
x_clean : ndarray
|
|
444
|
+
Copy of ``x`` with flagged samples replaced.
|
|
445
|
+
flagged : ndarray of bool
|
|
446
|
+
local_noise_est : float
|
|
447
|
+
Median of the local MAD estimate across the trace (diagnostic).
|
|
448
|
+
"""
|
|
449
|
+
rolling_med = ndimage.median_filter(x, size=window, mode="reflect")
|
|
450
|
+
dev = x - rolling_med
|
|
451
|
+
local_mad = 1.4826 * ndimage.median_filter(np.abs(dev), size=window, mode="reflect")
|
|
452
|
+
local_mad = np.maximum(local_mad, 1e-12)
|
|
453
|
+
flagged = np.abs(dev) > k * local_mad
|
|
454
|
+
|
|
455
|
+
x_clean = x.copy()
|
|
456
|
+
if flagged.any() and not flagged.all():
|
|
457
|
+
idx = np.arange(len(x))
|
|
458
|
+
x_clean[flagged] = np.interp(idx[flagged], idx[~flagged], x[~flagged])
|
|
459
|
+
|
|
460
|
+
return x_clean, flagged, float(np.median(local_mad))
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _robust_tonic_range(tonic: NDArray[np.floating], min_distance: int) -> Tuple[float, int]:
|
|
464
|
+
"""Median peak-to-valley swing amplitude of the tonic curve --
|
|
465
|
+
mirrors how phasic amplitude is estimated (detect individual
|
|
466
|
+
events, take the median across them) instead of ``ptp(tonic)``'s
|
|
467
|
+
single global max-minus-min.
|
|
468
|
+
|
|
469
|
+
Detects local maxima and minima in ``tonic``
|
|
470
|
+
(``scipy.signal.argrelextrema``, ``order=min_distance`` -- the
|
|
471
|
+
number of samples on each side a point must exceed to count as a
|
|
472
|
+
local extremum), takes the absolute difference between each pair of
|
|
473
|
+
temporally-adjacent extrema (each one a single peak-to-valley or
|
|
474
|
+
valley-to-peak "swing"), and returns the median swing amplitude.
|
|
475
|
+
|
|
476
|
+
A one-off contaminated region typically produces only one or two
|
|
477
|
+
anomalous swings among many genuine ones, so the median has a real
|
|
478
|
+
breakdown point -- unlike ``ptp(tonic)``, which *is* the
|
|
479
|
+
contaminated region's own extreme value whenever that region
|
|
480
|
+
happens to contain the global max or min. Unlike a chunked/windowed
|
|
481
|
+
estimate (:meth:`EnvelopeRRSNR.fit_chunked`), this doesn't impose an
|
|
482
|
+
arbitrary fixed-duration window that can slice a genuine slow cycle
|
|
483
|
+
in half and underestimate it by construction -- it finds extrema
|
|
484
|
+
wherever the curve's own structure actually puts them, the same
|
|
485
|
+
principle ``find_peaks`` already uses for phasic events.
|
|
486
|
+
|
|
487
|
+
The trade-off: robustness here scales with how many genuine swings
|
|
488
|
+
get detected, same as phasic's median scales with how many genuine
|
|
489
|
+
events get detected. A short recording relative to the tonic's own
|
|
490
|
+
drift period (few genuine cycles) gives the median little to work
|
|
491
|
+
with, same limitation phasic would have with only a handful of true
|
|
492
|
+
transients.
|
|
493
|
+
|
|
494
|
+
Parameters
|
|
495
|
+
----------
|
|
496
|
+
tonic : ndarray
|
|
497
|
+
Fitted tonic curve.
|
|
498
|
+
min_distance : int
|
|
499
|
+
Minimum spacing (samples) between detected extrema -- should be
|
|
500
|
+
well below the tonic's own characteristic drift period, but
|
|
501
|
+
well above any remaining fast wiggle in the fitted curve.
|
|
502
|
+
|
|
503
|
+
Returns
|
|
504
|
+
-------
|
|
505
|
+
tonic_range : float
|
|
506
|
+
Median swing amplitude, or ``ptp(tonic)`` if fewer than 2
|
|
507
|
+
extrema are detected (not enough structure for a meaningful
|
|
508
|
+
median -- e.g. a very short trace or an almost perfectly flat
|
|
509
|
+
tonic).
|
|
510
|
+
n_swings : int
|
|
511
|
+
Number of swings the median was computed over (0 if it fell
|
|
512
|
+
back to ``ptp``).
|
|
513
|
+
"""
|
|
514
|
+
peaks = signal.argrelextrema(tonic, np.greater, order=min_distance)[0]
|
|
515
|
+
valleys = signal.argrelextrema(tonic, np.less, order=min_distance)[0]
|
|
516
|
+
extrema_idx = np.sort(np.concatenate([peaks, valleys]))
|
|
517
|
+
if len(extrema_idx) < 2:
|
|
518
|
+
return float(np.ptp(tonic)), 0
|
|
519
|
+
swings = np.abs(np.diff(tonic[extrema_idx]))
|
|
520
|
+
return float(np.median(swings)), len(swings)
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def _apply_pre_despike(
|
|
524
|
+
x: NDArray[np.floating], cfg: Dict
|
|
525
|
+
) -> Tuple[NDArray[np.floating], int, float]:
|
|
526
|
+
"""Optionally despike ``x`` before it's used for tonic fitting.
|
|
527
|
+
|
|
528
|
+
Off by default (``cfg['pre_despike_window']`` is ``None``),
|
|
529
|
+
preserving prior behavior exactly unless opted in. Scoped to
|
|
530
|
+
protecting the tonic fit only -- callers should run residual/peak
|
|
531
|
+
detection on the ORIGINAL ``x``, not this function's output, so a
|
|
532
|
+
genuine large artifact still surfaces as an inspectable outlier
|
|
533
|
+
rather than silently vanishing. Even with despiking on, a large
|
|
534
|
+
enough outlier relative to the true tonic's own dynamic range can
|
|
535
|
+
still leak through a smoothness-penalized fit;
|
|
536
|
+
``n_extreme_samples``/``frac_extreme_samples`` are diagnostics for
|
|
537
|
+
exactly that residual risk, not a guarantee despiking fully
|
|
538
|
+
removed it.
|
|
539
|
+
|
|
540
|
+
Returns
|
|
541
|
+
-------
|
|
542
|
+
x_for_tonic : ndarray
|
|
543
|
+
``x`` unchanged if pre-despiking is off, else the despiked copy.
|
|
544
|
+
n_extreme_samples : int
|
|
545
|
+
frac_extreme_samples : float
|
|
546
|
+
"""
|
|
547
|
+
pre_despike_window = cfg.get("pre_despike_window", None)
|
|
548
|
+
if pre_despike_window is None:
|
|
549
|
+
return x, 0, 0.0
|
|
550
|
+
x_for_tonic, flagged, _local_noise = _despike_interpolate(
|
|
551
|
+
x, window=pre_despike_window, k=cfg.get("pre_despike_k", 5.0)
|
|
368
552
|
)
|
|
553
|
+
n_extreme_samples = int(np.sum(flagged))
|
|
554
|
+
frac_extreme_samples = float(n_extreme_samples / len(x))
|
|
555
|
+
return x_for_tonic, n_extreme_samples, frac_extreme_samples
|
|
369
556
|
|
|
370
|
-
|
|
557
|
+
|
|
558
|
+
def _fit_tonic_curve(
|
|
559
|
+
x_for_tonic: NDArray[np.floating],
|
|
560
|
+
midpoint: NDArray[np.floating],
|
|
561
|
+
tonic_method: str,
|
|
562
|
+
cfg: Dict,
|
|
563
|
+
) -> Tuple[NDArray[np.floating], NDArray[np.intp]]:
|
|
564
|
+
"""Fit the tonic (slow baseline) curve with the requested tracker.
|
|
565
|
+
|
|
566
|
+
Parameters
|
|
567
|
+
----------
|
|
568
|
+
x_for_tonic : ndarray
|
|
569
|
+
Trace to fit (already despiked if pre-despiking was applied).
|
|
570
|
+
midpoint : ndarray
|
|
571
|
+
Smoothed reference curve; only used by ``tonic_method='envelope'``.
|
|
572
|
+
tonic_method : {'als', 'arpls', 'envelope'}
|
|
573
|
+
cfg : dict
|
|
574
|
+
Method-specific tuning knobs (``als_lam``/``als_p``/``als_n_iter``,
|
|
575
|
+
``arpls_lam``/``arpls_n_iter``/``arpls_ratio``, or
|
|
576
|
+
``lower_smooth_window``/``lower_order``/``lower_min_distance``/
|
|
577
|
+
``interp_kind``).
|
|
578
|
+
|
|
579
|
+
Returns
|
|
580
|
+
-------
|
|
581
|
+
tonic : ndarray
|
|
582
|
+
tonic_minima : ndarray of int
|
|
583
|
+
Valley indices tracked by the envelope method; empty for
|
|
584
|
+
``'als'``/``'arpls'`` (they have no discrete "minima" concept).
|
|
585
|
+
|
|
586
|
+
Raises
|
|
587
|
+
------
|
|
588
|
+
ValueError
|
|
589
|
+
If ``tonic_method`` isn't one of the three supported values.
|
|
590
|
+
"""
|
|
371
591
|
if tonic_method == "als":
|
|
372
592
|
tonic = _als_baseline(
|
|
373
|
-
|
|
593
|
+
x_for_tonic,
|
|
374
594
|
lam=cfg.get("als_lam", 1e7),
|
|
375
595
|
p=cfg.get("als_p", 0.01),
|
|
376
596
|
n_iter=cfg.get("als_n_iter", 10),
|
|
377
597
|
)
|
|
378
|
-
|
|
598
|
+
return tonic, np.array([], dtype=int)
|
|
379
599
|
elif tonic_method == "arpls":
|
|
380
600
|
tonic = _arpls_baseline(
|
|
381
|
-
|
|
601
|
+
x_for_tonic,
|
|
382
602
|
lam=cfg.get("arpls_lam", 1e7),
|
|
383
603
|
n_iter=cfg.get("arpls_n_iter", 15),
|
|
384
604
|
ratio=cfg.get("arpls_ratio", 1e-6),
|
|
385
605
|
)
|
|
386
|
-
|
|
606
|
+
return tonic, np.array([], dtype=int)
|
|
387
607
|
elif tonic_method == "envelope":
|
|
388
|
-
|
|
389
|
-
|
|
608
|
+
return _lower_envelope(
|
|
609
|
+
x_for_tonic,
|
|
390
610
|
midpoint,
|
|
391
611
|
cfg["lower_smooth_window"],
|
|
392
612
|
cfg["lower_order"],
|
|
393
613
|
cfg["lower_min_distance"],
|
|
394
614
|
interp_kind=cfg["interp_kind"],
|
|
395
615
|
)
|
|
396
|
-
|
|
397
|
-
raise ValueError(
|
|
398
|
-
f"tonic_method must be 'envelope', 'als', or 'arpls'; got {tonic_method!r}."
|
|
399
|
-
)
|
|
616
|
+
raise ValueError(f"tonic_method must be 'envelope', 'als', or 'arpls'; got {tonic_method!r}.")
|
|
400
617
|
|
|
401
|
-
residual = x - tonic
|
|
402
618
|
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
619
|
+
def _resolve_noise_method(noise_method: str) -> str:
|
|
620
|
+
"""Resolve a deprecated ``noise_method`` alias (e.g. ``'mad'``) to
|
|
621
|
+
its canonical name (``'aind_mad'``); returns unrecognized names
|
|
622
|
+
unchanged so the caller's own validation can reject them."""
|
|
623
|
+
return _DEPRECATED_NOISE_METHOD_ALIASES.get(noise_method, noise_method)
|
|
406
624
|
|
|
625
|
+
|
|
626
|
+
def _estimate_residual_noise(residual: NDArray[np.floating], noise_method: str) -> float:
|
|
627
|
+
"""Dispatch to the requested noise-floor estimator on the tonic-
|
|
628
|
+
subtracted residual.
|
|
629
|
+
|
|
630
|
+
Parameters
|
|
631
|
+
----------
|
|
632
|
+
residual : ndarray
|
|
633
|
+
noise_method : {'aind_mad', 'folded_iqr', 'mad_iqr_avg'}
|
|
634
|
+
Deprecated aliases (e.g. ``'mad'``) are resolved first via
|
|
635
|
+
:func:`_resolve_noise_method`.
|
|
636
|
+
|
|
637
|
+
Returns
|
|
638
|
+
-------
|
|
639
|
+
float
|
|
640
|
+
|
|
641
|
+
Raises
|
|
642
|
+
------
|
|
643
|
+
ValueError
|
|
644
|
+
If ``noise_method`` (after alias resolution) isn't one of the
|
|
645
|
+
three supported values.
|
|
646
|
+
"""
|
|
647
|
+
noise_method = _resolve_noise_method(noise_method)
|
|
407
648
|
if noise_method == "folded_iqr":
|
|
408
|
-
|
|
649
|
+
return _folded_iqr_noise_std(residual)
|
|
409
650
|
elif noise_method == "aind_mad":
|
|
410
|
-
|
|
651
|
+
return _mad_noise_std(residual)
|
|
411
652
|
elif noise_method == "mad_iqr_avg":
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
653
|
+
return 0.5 * (_folded_iqr_noise_std(residual) + _mad_noise_std(residual))
|
|
654
|
+
raise ValueError(f"noise_method must be one of {_VALID_NOISE_METHODS}; got {noise_method!r}.")
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
def _estimate_sigma_minima(
|
|
658
|
+
residual: NDArray[np.floating],
|
|
659
|
+
tonic_minima: NDArray[np.intp],
|
|
660
|
+
fallback_sigma: float,
|
|
661
|
+
) -> float:
|
|
662
|
+
"""Noise estimate from the residual at valley-to-valley midpoints --
|
|
663
|
+
only meaningful for ``tonic_method='envelope'``, which tracks an
|
|
664
|
+
explicit list of minima. Falls back to ``fallback_sigma`` if there
|
|
665
|
+
aren't enough minima (or valid midpoints) for a stable estimate.
|
|
666
|
+
"""
|
|
667
|
+
if len(tonic_minima) < 5:
|
|
668
|
+
return fallback_sigma
|
|
669
|
+
n = len(residual)
|
|
670
|
+
mid_idx = ((tonic_minima[:-1] + tonic_minima[1:]) // 2).astype(int)
|
|
671
|
+
mid_idx = mid_idx[(mid_idx >= 0) & (mid_idx < n)]
|
|
672
|
+
if len(mid_idx) < 5:
|
|
673
|
+
return fallback_sigma
|
|
674
|
+
return float(np.std(residual[mid_idx]))
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
def _detect_phasic_events(
|
|
678
|
+
residual: NDArray[np.floating], sigma_fit: float, cfg: Dict
|
|
679
|
+
) -> Tuple[NDArray[np.intp], float, NDArray[np.floating]]:
|
|
680
|
+
"""Detect suprathreshold phasic peaks and gate them by rise rate
|
|
681
|
+
(see :func:`_detect_peaks_rise_rate`).
|
|
682
|
+
|
|
683
|
+
Returns
|
|
684
|
+
-------
|
|
685
|
+
event_maxima : ndarray of int
|
|
686
|
+
threshold : float
|
|
687
|
+
``peak_threshold_sd * sigma_fit`` -- the height cutoff used.
|
|
688
|
+
peak_amps : ndarray
|
|
689
|
+
``residual[event_maxima]``; empty if no events were detected.
|
|
690
|
+
"""
|
|
691
|
+
threshold = cfg["peak_threshold_sd"] * sigma_fit
|
|
430
692
|
raw_peaks, _ = signal.find_peaks(
|
|
431
693
|
residual,
|
|
432
|
-
height=
|
|
694
|
+
height=threshold,
|
|
433
695
|
distance=cfg.get("upper_min_distance", 3),
|
|
434
696
|
)
|
|
435
697
|
event_maxima = _detect_peaks_rise_rate(
|
|
@@ -441,13 +703,119 @@ def _decompose_envelope_rr(x: NDArray[np.floating], config: Dict) -> Dict:
|
|
|
441
703
|
event_maxima = np.asarray(event_maxima, dtype=int)
|
|
442
704
|
event_maxima = event_maxima[(event_maxima >= 0) & (event_maxima < len(residual))]
|
|
443
705
|
peak_amps = residual[event_maxima] if len(event_maxima) > 0 else np.array([])
|
|
706
|
+
return event_maxima, threshold, peak_amps
|
|
444
707
|
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
708
|
+
|
|
709
|
+
def _summarize_phasic_amplitudes(
|
|
710
|
+
peak_amps: NDArray[np.floating],
|
|
711
|
+
) -> Tuple[float, float, float]:
|
|
712
|
+
"""95th percentile / median / std of detected peak amplitudes; all
|
|
713
|
+
zero if no events were detected.
|
|
714
|
+
|
|
715
|
+
Returns
|
|
716
|
+
-------
|
|
717
|
+
(phasic_p95, phasic_median, phasic_sd)
|
|
718
|
+
"""
|
|
719
|
+
if len(peak_amps) == 0:
|
|
720
|
+
return 0.0, 0.0, 0.0
|
|
721
|
+
return (
|
|
722
|
+
float(np.percentile(peak_amps, 95)),
|
|
723
|
+
float(np.median(peak_amps)),
|
|
724
|
+
float(np.std(peak_amps)),
|
|
725
|
+
)
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
def _compute_tonic_range(
|
|
729
|
+
tonic: NDArray[np.floating], tonic_range_method: str, cfg: Dict
|
|
730
|
+
) -> Tuple[float, int]:
|
|
731
|
+
"""Dispatch to the requested tonic-amplitude summary statistic.
|
|
732
|
+
|
|
733
|
+
``ptp(tonic)`` (``max - min``) has a breakdown point of exactly one
|
|
734
|
+
sample -- a single large excursion the tonic fit only partially
|
|
735
|
+
absorbs (e.g. from a sustained artifact arPLS's reweighting doesn't
|
|
736
|
+
fully reject) inflates it directly, with nothing to average it out.
|
|
737
|
+
``'percentile'`` trims ``tonic_range_trim_pct`` from each tail
|
|
738
|
+
before taking the range, at the cost of also clipping any genuine
|
|
739
|
+
tonic dynamic range that happens to live in that trimmed fraction --
|
|
740
|
+
choose ``tonic_range_trim_pct`` to comfortably exceed the fraction
|
|
741
|
+
of the trace you expect a real artifact to occupy (e.g. a 5s glitch
|
|
742
|
+
in a 150s trace is ~3.3% one-sided; ``trim_pct=5`` gives a 5%
|
|
743
|
+
one-sided margin above that). ``'robust'`` (the default) instead
|
|
744
|
+
takes the median peak-to-valley swing amplitude across detected
|
|
745
|
+
local extrema in the tonic curve (see :func:`_robust_tonic_range`),
|
|
746
|
+
mirroring how phasic amplitude is estimated (detect individual
|
|
747
|
+
events, take the median across them) rather than reading off a
|
|
748
|
+
single global extreme value.
|
|
749
|
+
|
|
750
|
+
Returns
|
|
751
|
+
-------
|
|
752
|
+
tonic_range : float
|
|
753
|
+
n_tonic_swings : int
|
|
754
|
+
Only nonzero for ``tonic_range_method='robust'``.
|
|
755
|
+
|
|
756
|
+
Raises
|
|
757
|
+
------
|
|
758
|
+
ValueError
|
|
759
|
+
If ``tonic_range_method`` isn't one of the three supported
|
|
760
|
+
values.
|
|
761
|
+
"""
|
|
762
|
+
if tonic_range_method == "ptp":
|
|
763
|
+
return float(np.ptp(tonic)), 0
|
|
764
|
+
elif tonic_range_method == "percentile":
|
|
765
|
+
trim_pct = cfg.get("tonic_range_trim_pct", 5.0)
|
|
766
|
+
tonic_range = float(np.percentile(tonic, 100 - trim_pct) - np.percentile(tonic, trim_pct))
|
|
767
|
+
return tonic_range, 0
|
|
768
|
+
elif tonic_range_method == "robust":
|
|
769
|
+
min_distance = cfg.get("tonic_robust_min_distance", _DEFAULT_TONIC_ROBUST_MIN_DISTANCE)
|
|
770
|
+
return _robust_tonic_range(tonic, min_distance)
|
|
771
|
+
raise ValueError(
|
|
772
|
+
f"tonic_range_method must be 'ptp', 'percentile', or 'robust'; "
|
|
773
|
+
f"got {tonic_range_method!r}."
|
|
774
|
+
)
|
|
775
|
+
|
|
776
|
+
|
|
777
|
+
def _decompose_envelope_rr(x: NDArray[np.floating], config: Dict) -> Dict:
|
|
778
|
+
"""Tonic/phasic decomposition + rise-rate gated peak detection.
|
|
779
|
+
|
|
780
|
+
A thin orchestrator: optional pre-despiking
|
|
781
|
+
(:func:`_apply_pre_despike`) -> tonic fit (:func:`_fit_tonic_curve`)
|
|
782
|
+
-> noise-floor estimate (:func:`_estimate_residual_noise`,
|
|
783
|
+
:func:`_estimate_sigma_minima`) -> phasic peak detection
|
|
784
|
+
(:func:`_detect_phasic_events`, :func:`_summarize_phasic_amplitudes`)
|
|
785
|
+
-> tonic-amplitude summary statistic (:func:`_compute_tonic_range`).
|
|
786
|
+
See each helper's own docstring for the mechanism and trade-offs of
|
|
787
|
+
the strategy it dispatches between; this function itself makes no
|
|
788
|
+
strategy decisions of its own.
|
|
789
|
+
"""
|
|
790
|
+
cfg = config
|
|
791
|
+
|
|
792
|
+
x_for_tonic, n_extreme_samples, frac_extreme_samples = _apply_pre_despike(x, cfg)
|
|
793
|
+
|
|
794
|
+
midpoint = _moving_average(
|
|
795
|
+
x_for_tonic,
|
|
796
|
+
window=cfg["midpoint_window"],
|
|
797
|
+
polyorder=cfg["midpoint_polyorder"],
|
|
798
|
+
)
|
|
799
|
+
|
|
800
|
+
tonic_method = cfg.get("tonic_method", "envelope")
|
|
801
|
+
tonic, tonic_minima = _fit_tonic_curve(x_for_tonic, midpoint, tonic_method, cfg)
|
|
802
|
+
|
|
803
|
+
# residual/peak-detection intentionally use the ORIGINAL x, not
|
|
804
|
+
# x_for_tonic -- despiking is scoped to protecting the tonic fit; a
|
|
805
|
+
# genuine large artifact should still surface in the residual/phasic
|
|
806
|
+
# stats as an inspectable outlier rather than being silently erased.
|
|
807
|
+
residual = x - tonic
|
|
808
|
+
|
|
809
|
+
noise_method = cfg.get("noise_method", _DEFAULT_NOISE_METHOD)
|
|
810
|
+
sigma_iqr = _estimate_residual_noise(residual, noise_method)
|
|
811
|
+
sigma_minima = _estimate_sigma_minima(residual, tonic_minima, sigma_iqr)
|
|
812
|
+
sigma_fit = sigma_iqr
|
|
813
|
+
|
|
814
|
+
event_maxima, thresh, peak_amps = _detect_phasic_events(residual, sigma_fit, cfg)
|
|
815
|
+
phasic_p95, phasic_median, phasic_sd = _summarize_phasic_amplitudes(peak_amps)
|
|
816
|
+
|
|
817
|
+
tonic_range_method = cfg.get("tonic_range_method", "robust")
|
|
818
|
+
tonic_range, n_tonic_swings = _compute_tonic_range(tonic, tonic_range_method, cfg)
|
|
451
819
|
|
|
452
820
|
return {
|
|
453
821
|
"tonic": tonic,
|
|
@@ -462,14 +830,17 @@ def _decompose_envelope_rr(x: NDArray[np.floating], config: Dict) -> Dict:
|
|
|
462
830
|
"peak_threshold": float(thresh),
|
|
463
831
|
"detection_method": "rise_rate",
|
|
464
832
|
"tonic_method": tonic_method,
|
|
465
|
-
"tonic_range":
|
|
833
|
+
"tonic_range": tonic_range,
|
|
466
834
|
"phasic_p95": phasic_p95,
|
|
467
835
|
"phasic_median": phasic_median,
|
|
468
836
|
"phasic_amplitude": phasic_sd,
|
|
469
837
|
"phasic_snr_p95": float(phasic_p95 / sigma_fit) if sigma_fit > 0 else float("nan"),
|
|
470
838
|
"phasic_snr_median": float(phasic_median / sigma_fit) if sigma_fit > 0 else float("nan"),
|
|
471
839
|
"phasic_snr_sd": float(phasic_sd / sigma_fit) if sigma_fit > 0 else float("nan"),
|
|
472
|
-
"tonic_snr_sd": float(
|
|
840
|
+
"tonic_snr_sd": float(tonic_range / sigma_fit) if sigma_fit > 0 else float("nan"),
|
|
841
|
+
"n_extreme_samples": n_extreme_samples,
|
|
842
|
+
"n_tonic_swings": n_tonic_swings,
|
|
843
|
+
"frac_extreme_samples": frac_extreme_samples,
|
|
473
844
|
"config": cfg,
|
|
474
845
|
}
|
|
475
846
|
|
|
@@ -519,6 +890,30 @@ class EnvelopeRRResult:
|
|
|
519
890
|
``signal_statistic``).
|
|
520
891
|
config : dict
|
|
521
892
|
The resolved configuration used for this fit.
|
|
893
|
+
n_extreme_samples : int
|
|
894
|
+
Count of samples flagged and interpolated over by pre-despiking
|
|
895
|
+
before the tonic fit (0 if ``pre_despike_window`` wasn't set in
|
|
896
|
+
``config``). A nonzero count doesn't mean the tonic fit is now
|
|
897
|
+
clean -- see the module docstring's note on ``tonic_range`` and
|
|
898
|
+
despiking's actual, partial effectiveness against large,
|
|
899
|
+
sustained artifacts.
|
|
900
|
+
frac_extreme_samples : float
|
|
901
|
+
``n_extreme_samples / len(trace)``.
|
|
902
|
+
n_chunks : int or None
|
|
903
|
+
Number of chunks actually used to compute ``snr_tonic``, if
|
|
904
|
+
this result came from :meth:`EnvelopeRRSNR.fit_chunked` rather
|
|
905
|
+
than :meth:`EnvelopeRRSNR.fit`. ``None`` after a plain ``fit``.
|
|
906
|
+
chunk_duration_s : float or None
|
|
907
|
+
Chunk length (seconds) used by :meth:`fit_chunked`, if
|
|
908
|
+
applicable.
|
|
909
|
+
per_chunk_tonic_snr : list of float or None
|
|
910
|
+
Each chunk's own ``snr_tonic`` before aggregation, if this
|
|
911
|
+
result came from :meth:`fit_chunked`.
|
|
912
|
+
n_tonic_swings : int
|
|
913
|
+
Number of peak-to-valley swings the median was computed over,
|
|
914
|
+
if ``config['tonic_range_method'] == 'robust'`` (0 otherwise,
|
|
915
|
+
including the fallback-to-``ptp`` case when fewer than 2
|
|
916
|
+
extrema were detected -- see :func:`_robust_tonic_range`).
|
|
522
917
|
"""
|
|
523
918
|
|
|
524
919
|
snr: float
|
|
@@ -532,6 +927,12 @@ class EnvelopeRRResult:
|
|
|
532
927
|
config: Dict = field(repr=False)
|
|
533
928
|
snr_corrected: Optional[float] = None
|
|
534
929
|
snr_phasic_corrected: Optional[float] = None
|
|
930
|
+
n_extreme_samples: int = 0
|
|
931
|
+
frac_extreme_samples: float = 0.0
|
|
932
|
+
n_chunks: Optional[int] = None
|
|
933
|
+
chunk_duration_s: Optional[float] = None
|
|
934
|
+
per_chunk_tonic_snr: Optional[list] = None
|
|
935
|
+
n_tonic_swings: int = 0
|
|
535
936
|
|
|
536
937
|
|
|
537
938
|
class EnvelopeRRSNR:
|
|
@@ -594,6 +995,23 @@ class EnvelopeRRSNR:
|
|
|
594
995
|
``config={'noise_method': ...}``, which takes precedence over
|
|
595
996
|
the ``noise_method`` argument.
|
|
596
997
|
|
|
998
|
+
``tonic_range_method`` (default ``'robust'``) controls how
|
|
999
|
+
``snr_tonic`` is computed from the fitted tonic curve:
|
|
1000
|
+
``'robust'`` -- median peak-to-valley swing amplitude across
|
|
1001
|
+
detected local extrema, mirroring how ``snr_phasic`` is
|
|
1002
|
+
estimated (detect individual events, take the median across
|
|
1003
|
+
them), spacing controlled by ``tonic_robust_min_distance``
|
|
1004
|
+
(default 100 samples at 20fps, fps-scaled) -- or ``'ptp'``
|
|
1005
|
+
(``max(tonic) - min(tonic)``, the previous default; a fragile,
|
|
1006
|
+
single-sample-breakdown-point statistic -- kept for backward
|
|
1007
|
+
compatibility, and still useful as a plain, unadorned baseline
|
|
1008
|
+
to compare against), or ``'percentile'`` (trims
|
|
1009
|
+
``tonic_range_trim_pct`` from each tail before taking the
|
|
1010
|
+
range). See :func:`_robust_tonic_range` for the full mechanism
|
|
1011
|
+
and its own trade-off (robustness scales with how many genuine
|
|
1012
|
+
tonic swings actually get detected, same as ``snr_phasic``'s
|
|
1013
|
+
robustness scales with detected event count).
|
|
1014
|
+
|
|
597
1015
|
Notes
|
|
598
1016
|
-----
|
|
599
1017
|
- Noise is estimated from the tonic-subtracted residual, not the
|
|
@@ -663,6 +1081,7 @@ class EnvelopeRRSNR:
|
|
|
663
1081
|
_TUNED_DEFAULTS["lower_smooth_window"], fps, make_odd=True
|
|
664
1082
|
),
|
|
665
1083
|
"rise_window": self.scale_window(_TUNED_DEFAULTS["rise_window"], fps),
|
|
1084
|
+
"tonic_robust_min_distance": self.scale_window(_DEFAULT_TONIC_ROBUST_MIN_DISTANCE, fps),
|
|
666
1085
|
}
|
|
667
1086
|
self.config = {
|
|
668
1087
|
**_DEFAULT_CONFIG,
|
|
@@ -761,9 +1180,151 @@ class EnvelopeRRSNR:
|
|
|
761
1180
|
residual=raw["residual"],
|
|
762
1181
|
signal=signal,
|
|
763
1182
|
config=raw["config"],
|
|
1183
|
+
n_extreme_samples=raw["n_extreme_samples"],
|
|
1184
|
+
frac_extreme_samples=raw["frac_extreme_samples"],
|
|
1185
|
+
n_tonic_swings=raw["n_tonic_swings"],
|
|
764
1186
|
)
|
|
765
1187
|
return self.result_
|
|
766
1188
|
|
|
1189
|
+
def fit_chunked(
|
|
1190
|
+
self,
|
|
1191
|
+
trace: NDArray[np.floating],
|
|
1192
|
+
chunk_duration_s: Optional[float] = None,
|
|
1193
|
+
min_chunk_duration_s: float = 30.0,
|
|
1194
|
+
chunk_fraction: float = 0.20,
|
|
1195
|
+
aggregate: str = "median",
|
|
1196
|
+
) -> EnvelopeRRResult:
|
|
1197
|
+
"""Like :meth:`fit`, but computes ``snr_tonic`` from a chunked,
|
|
1198
|
+
per-window median instead of the single global fit's
|
|
1199
|
+
``ptp(tonic)``.
|
|
1200
|
+
|
|
1201
|
+
Why: ``ptp(tonic)`` has a breakdown point of exactly one sample
|
|
1202
|
+
-- a single large excursion the tonic fit only partially
|
|
1203
|
+
absorbs (e.g. a sustained artifact arPLS's reweighting doesn't
|
|
1204
|
+
fully reject) inflates it directly, with nothing to average it
|
|
1205
|
+
out. Splitting the trace into independent chunks and fitting
|
|
1206
|
+
each one separately means a one-off artifact can only poison
|
|
1207
|
+
the (hopefully minority of) chunks it actually overlaps; the
|
|
1208
|
+
median across chunks then has a real breakdown point, rather
|
|
1209
|
+
than relying on one global fit's shape being trustworthy in
|
|
1210
|
+
the first place. Measured on synthetic one-off sustained
|
|
1211
|
+
artifacts: brings tonic_snr inflation from ~6x (a flat true
|
|
1212
|
+
baseline, 5000x-noise_sigma artifact) down to ~1.04x, versus
|
|
1213
|
+
~15-20% reductions from pre-despiking or percentile-trimmed
|
|
1214
|
+
``tonic_range`` alone -- this changes the failure mode instead
|
|
1215
|
+
of just softening it.
|
|
1216
|
+
|
|
1217
|
+
The trade-off: a chunk shorter than the recording's own genuine
|
|
1218
|
+
tonic drift period will only see a fraction of that drift,
|
|
1219
|
+
biasing ``snr_tonic`` down even on a clean trace (measured:
|
|
1220
|
+
~3x underestimate using 15s chunks against a 120s-period
|
|
1221
|
+
drift). Default chunk sizing (``chunk_duration_s=None``)
|
|
1222
|
+
balances this with ``max(min_chunk_duration_s, chunk_fraction *
|
|
1223
|
+
recording_duration)`` -- a fixed floor for short recordings,
|
|
1224
|
+
scaling up for longer ones so chunk size tracks a long
|
|
1225
|
+
recording's own timescale rather than staying fixed at the
|
|
1226
|
+
floor. Pass ``chunk_duration_s`` explicitly to match your own
|
|
1227
|
+
recordings' known drift timescale instead of relying on this
|
|
1228
|
+
heuristic -- it's a reasonable default, not a substitute for
|
|
1229
|
+
knowing your own data.
|
|
1230
|
+
|
|
1231
|
+
Everything else (phasic peak detection, noise floor, residual,
|
|
1232
|
+
the returned ``tonic`` curve) is unchanged from :meth:`fit` --
|
|
1233
|
+
only ``snr_tonic`` (and the ``snr``/``snr_corrected`` totals
|
|
1234
|
+
derived from it) differ. New fields not populated by a plain
|
|
1235
|
+
:meth:`fit` call: ``n_chunks``, ``chunk_duration_s``,
|
|
1236
|
+
``per_chunk_tonic_snr``.
|
|
1237
|
+
|
|
1238
|
+
Parameters
|
|
1239
|
+
----------
|
|
1240
|
+
trace : ndarray
|
|
1241
|
+
chunk_duration_s : float, optional
|
|
1242
|
+
Chunk length in seconds. If None (default), uses
|
|
1243
|
+
``max(min_chunk_duration_s, chunk_fraction * len(trace)/fps)``.
|
|
1244
|
+
min_chunk_duration_s : float
|
|
1245
|
+
Floor on the default chunk duration (seconds). Ignored if
|
|
1246
|
+
``chunk_duration_s`` is given explicitly.
|
|
1247
|
+
chunk_fraction : float
|
|
1248
|
+
Fraction of the recording's total duration used for the
|
|
1249
|
+
default chunk duration, before the floor is applied.
|
|
1250
|
+
Ignored if ``chunk_duration_s`` is given explicitly.
|
|
1251
|
+
aggregate : {'median', 'mean'}
|
|
1252
|
+
How to combine per-chunk ``snr_tonic`` values. ``'median'``
|
|
1253
|
+
(default) is what gives this its outlier robustness;
|
|
1254
|
+
``'mean'`` has no breakdown point and defeats the purpose --
|
|
1255
|
+
provided mainly for comparison/diagnostics.
|
|
1256
|
+
|
|
1257
|
+
Returns
|
|
1258
|
+
-------
|
|
1259
|
+
EnvelopeRRResult
|
|
1260
|
+
Same structure as :meth:`fit`'s return value, with
|
|
1261
|
+
``snr_tonic``/``snr``/``snr_corrected`` computed from the
|
|
1262
|
+
chunked-median tonic estimate, plus ``n_chunks``,
|
|
1263
|
+
``chunk_duration_s``, ``per_chunk_tonic_snr``. Also stored
|
|
1264
|
+
on ``self.result_``.
|
|
1265
|
+
"""
|
|
1266
|
+
trace = np.nan_to_num(trace, nan=float(np.nanmedian(trace)))
|
|
1267
|
+
|
|
1268
|
+
# Global fit first: phasic peaks/signal/noise/residual/the
|
|
1269
|
+
# returned tonic curve all come from here, unchanged from a
|
|
1270
|
+
# plain fit() -- only snr_tonic (and totals derived from it)
|
|
1271
|
+
# get overridden below.
|
|
1272
|
+
result = self.fit(trace)
|
|
1273
|
+
|
|
1274
|
+
n = len(trace)
|
|
1275
|
+
if chunk_duration_s is None:
|
|
1276
|
+
chunk_duration_s = max(min_chunk_duration_s, chunk_fraction * (n / self.fps))
|
|
1277
|
+
chunk_len = max(1, int(round(chunk_duration_s * self.fps)))
|
|
1278
|
+
n_chunks_requested = max(1, n // chunk_len)
|
|
1279
|
+
chunks = np.array_split(trace, n_chunks_requested)
|
|
1280
|
+
|
|
1281
|
+
min_samples = max(50, int(self.config.get("midpoint_window", 101)))
|
|
1282
|
+
per_chunk_tonic_snr = []
|
|
1283
|
+
for c in chunks:
|
|
1284
|
+
if len(c) < min_samples:
|
|
1285
|
+
continue
|
|
1286
|
+
with warnings.catch_warnings():
|
|
1287
|
+
warnings.simplefilter("ignore")
|
|
1288
|
+
r = _decompose_envelope_rr(c, self.config)
|
|
1289
|
+
per_chunk_tonic_snr.append(float(r["tonic_snr_sd"]))
|
|
1290
|
+
|
|
1291
|
+
if aggregate == "median":
|
|
1292
|
+
agg_fn = np.nanmedian
|
|
1293
|
+
elif aggregate == "mean":
|
|
1294
|
+
agg_fn = np.nanmean
|
|
1295
|
+
else:
|
|
1296
|
+
raise ValueError(f"aggregate must be 'median' or 'mean'; got {aggregate!r}.")
|
|
1297
|
+
|
|
1298
|
+
if per_chunk_tonic_snr:
|
|
1299
|
+
snr_tonic_chunked = float(agg_fn(per_chunk_tonic_snr))
|
|
1300
|
+
else:
|
|
1301
|
+
warnings.warn(
|
|
1302
|
+
"No chunk was long enough to fit (trace too short for "
|
|
1303
|
+
"chunk_duration_s/min_chunk_duration_s) -- falling back "
|
|
1304
|
+
"to the global (non-chunked) snr_tonic.",
|
|
1305
|
+
RuntimeWarning,
|
|
1306
|
+
stacklevel=2,
|
|
1307
|
+
)
|
|
1308
|
+
snr_tonic_chunked = result.snr_tonic
|
|
1309
|
+
|
|
1310
|
+
snr_total_chunked = snr_tonic_chunked + result.snr_phasic # NaN-propagates
|
|
1311
|
+
|
|
1312
|
+
snr_corrected_chunked = None
|
|
1313
|
+
if self.bias_correction is not None and result.snr_phasic_corrected is not None:
|
|
1314
|
+
snr_corrected_chunked = snr_tonic_chunked + result.snr_phasic_corrected
|
|
1315
|
+
|
|
1316
|
+
chunked_result = replace(
|
|
1317
|
+
result,
|
|
1318
|
+
snr=snr_total_chunked,
|
|
1319
|
+
snr_tonic=snr_tonic_chunked,
|
|
1320
|
+
snr_corrected=snr_corrected_chunked,
|
|
1321
|
+
n_chunks=len(per_chunk_tonic_snr),
|
|
1322
|
+
chunk_duration_s=float(chunk_duration_s),
|
|
1323
|
+
per_chunk_tonic_snr=per_chunk_tonic_snr,
|
|
1324
|
+
)
|
|
1325
|
+
self.result_ = chunked_result
|
|
1326
|
+
return chunked_result
|
|
1327
|
+
|
|
767
1328
|
def estimate(
|
|
768
1329
|
self, trace: NDArray[np.floating], apply_correction: bool = False
|
|
769
1330
|
) -> Tuple[float, float, NDArray[np.intp]]:
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
aind_dynamic_foraging_basic_analysis/__init__.py,sha256=
|
|
1
|
+
aind_dynamic_foraging_basic_analysis/__init__.py,sha256=yFwtNyfxrbBfjwuan3c0LIXYDVCbS-93Y17Hg5aH8H0,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,7 +6,7 @@ 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=
|
|
9
|
+
aind_dynamic_foraging_basic_analysis/metrics/snr_envelope_rr.py,sha256=hE0YEmcKj182F8HVFlPw669IIZLpyBGw5NLEoDHTVWo,63827
|
|
10
10
|
aind_dynamic_foraging_basic_analysis/metrics/snr_kurtosis.py,sha256=F7SJ2zwleMPdmRu5RD9T0YEY482i5D90x1PZjujoD5U,5073
|
|
11
11
|
aind_dynamic_foraging_basic_analysis/metrics/trial_metrics.py,sha256=OxJvxz1XssEFJ5Nrnlqqgx9UsftbzTDonFIE65azLKM,13220
|
|
12
12
|
aind_dynamic_foraging_basic_analysis/plot/plot_fip.py,sha256=Lkw9YafpB6Kv3-pnZ663mc83o16tYNnekRqhb4TD2Ss,26962
|
|
@@ -14,8 +14,8 @@ aind_dynamic_foraging_basic_analysis/plot/plot_foraging_session.py,sha256=06OEfI
|
|
|
14
14
|
aind_dynamic_foraging_basic_analysis/plot/plot_foraging_session_plotly.py,sha256=5KQnDbBXCpUUMz4iYPV56ihpTgxXz-EnawWGeVD69ek,39213
|
|
15
15
|
aind_dynamic_foraging_basic_analysis/plot/plot_session_scroller.py,sha256=_3vYP7zBkiq9psR1ph_cuNhOzvV3emdco2wnmO5ud5A,18255
|
|
16
16
|
aind_dynamic_foraging_basic_analysis/plot/style.py,sha256=9OE22zVQR39FBt4mfdRFA43YbqXwhQF71VBSiFP65Qk,2649
|
|
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.
|
|
21
|
-
aind_dynamic_foraging_basic_analysis-0.4.
|
|
17
|
+
aind_dynamic_foraging_basic_analysis-0.4.3.dist-info/licenses/LICENSE,sha256=U0Y7B3gZJHXpjJVLgTQjM8e_c8w4JJpLgGhIdsoFR1Y,1092
|
|
18
|
+
aind_dynamic_foraging_basic_analysis-0.4.3.dist-info/METADATA,sha256=I1SEwHBOlKjhq3Ajg39PCPyl_q4WgpD_exHQfpaczpM,9876
|
|
19
|
+
aind_dynamic_foraging_basic_analysis-0.4.3.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
20
|
+
aind_dynamic_foraging_basic_analysis-0.4.3.dist-info/top_level.txt,sha256=gc5fvvd3cR7uvCHkTaSx-TcC4JmKMt9dBYMPncEO8VY,37
|
|
21
|
+
aind_dynamic_foraging_basic_analysis-0.4.3.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|