-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcorrection.py
More file actions
2775 lines (2487 loc) · 112 KB
/
correction.py
File metadata and controls
2775 lines (2487 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
correction.py — Pass 3 cardiac-cycle correction and state-timeline generation.
Entry point: run_pass3_correction().
Structure
---------
Module-level helpers (formerly closures inside _refine_and_correct_peaks)
Boundary geometry (_resolve_boundary_overlap, _paint_state_boundaries,
_build_reasoning_payload)
S2-events rebuild (_rebuild_s2_events)
Main entry point (run_pass3_correction)
"""
import logging
import math
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
from scipy.signal import find_peaks
from classifier import PeakClassifier
from confidence_engine import calculate_bpm_intervals
from hrv import _median_mad_keep_mask_time_window, filter_interval_durations_by_limits
# ─────────────────────────────────────────────────────────────────────────────
# State encoding constants (shared with pipeline / plotting)
# ─────────────────────────────────────────────────────────────────────────────
STATE_S1 = 0
STATE_SYSTOLE = 1
STATE_S2 = 2
STATE_DIASTOLE = 3
# Samples inside HF-noise windows when pass3_enable_noise_repair clears untrusted labels.
STATE_UNKNOWN = 4
STATE_LABELS_ENCODING: Dict[str, int] = {
"S1": STATE_S1,
"systole": STATE_SYSTOLE,
"S2": STATE_S2,
"diastole": STATE_DIASTOLE,
"unknown": STATE_UNKNOWN,
}
# ─────────────────────────────────────────────────────────────────────────────
# Pass 3: large-gap peak recovery (debug/visualization)
# ─────────────────────────────────────────────────────────────────────────────
def _detect_sensitive_peaks_in_large_gap_windows(
audio_envelope: np.ndarray,
sample_rate: int,
gap_windows_samples: List[Dict[str, Any]],
params: Dict,
*,
prominence_quantile: Optional[float] = None,
height_scale_override: Optional[float] = None,
dynamic_noise_floor_series: Optional[pd.Series] = None,
) -> np.ndarray:
"""
Rerun a more sensitive peak detector inside Pass 3 "large gap" windows.
The recovered peaks are stored in analysis_data for plotting/debug and are also
consumed by _pass3_snap_rebuilt_states_to_recovered_peaks to shift synthetic S1/S2
boundaries onto real acoustic events after the gap fill is complete.
"""
if sample_rate <= 0:
return np.asarray([], dtype=np.int64)
env = np.asarray(audio_envelope, dtype=np.float64)
n = int(len(env))
if n <= 0:
return np.asarray([], dtype=np.int64)
if not gap_windows_samples or not isinstance(gap_windows_samples, list):
return np.asarray([], dtype=np.int64)
min_peak_dist_samples = int(float(params.get("min_peak_distance_sec", 0.18)) * float(sample_rate))
min_peak_dist_samples = max(1, int(min_peak_dist_samples))
if prominence_quantile is None:
q = float(params.get("pass3_gap_recovery_peak_prominence_quantile", 0.50))
else:
q = float(prominence_quantile)
q = float(np.clip(q, 0.0, 1.0))
if height_scale_override is None:
height_scale = float(params.get("pass3_gap_recovery_height_scale", 0.85))
else:
height_scale = float(height_scale_override)
height_scale = float(np.clip(height_scale, 0.0, 1.0))
nf = None
if dynamic_noise_floor_series is not None and isinstance(dynamic_noise_floor_series, pd.Series):
try:
nf_arr = dynamic_noise_floor_series.to_numpy(dtype=np.float64, copy=False)
if len(nf_arr) == n:
nf = nf_arr
except Exception:
nf = None
out: List[int] = []
for w in gap_windows_samples:
if not isinstance(w, dict):
continue
try:
lo = int(w.get("start_sample", -1))
hi = int(w.get("end_sample", -1))
except Exception:
continue
lo = int(max(0, min(lo, n)))
hi = int(max(0, min(hi, n)))
if hi <= lo + 3:
continue
seg = env[lo:hi]
if seg.size < 4:
continue
try:
prom_thresh = float(np.quantile(seg, q))
except Exception:
prom_thresh = 0.0
if not np.isfinite(prom_thresh) or prom_thresh < 0:
prom_thresh = 0.0
height = None
if nf is not None:
ht = nf[lo:hi] * height_scale
height = ht
try:
pk, _ = find_peaks(
seg,
height=height,
prominence=prom_thresh,
distance=min_peak_dist_samples,
)
except Exception:
continue
if pk is None or len(pk) == 0:
continue
out.extend((lo + np.asarray(pk, dtype=np.int64)).tolist())
if not out:
return np.asarray([], dtype=np.int64)
# Unique + sorted
out_arr = np.asarray(sorted(set(int(x) for x in out if 0 <= int(x) < n)), dtype=np.int64)
return out_arr
def _pass3_snap_rebuilt_states_to_recovered_peaks(
state_labels: np.ndarray,
state_boundaries: List[Tuple],
recovered_peaks_insensitive: np.ndarray,
recovered_peaks_sensitive: np.ndarray,
audio_envelope: np.ndarray,
sample_rate: int,
snap_window_samples: int,
) -> Tuple[np.ndarray, List[Tuple]]:
"""
Post-processing: after the gap fill is complete, shift rebuilt S1 and S2 segment
boundaries to align with acoustically recovered peaks where available.
"Fill first, then shift": the existing rebuild produced a valid non-overlapping
partition; this function makes small position adjustments on top of it. The
neighboring systole or diastole segment absorbs the shift on each side, so the
partition stays contiguous and non-overlapping by construction.
Snapping is S1-first and cycle-aware:
Pass 1 — all rebuilt S1 segments snap first (forward order), reserving peaks.
Pass 2 — rebuilt S2 segments snap to remaining unresolved peaks only, and are
also blocked from using any peak within snap_window_samples of the next
rebuilt S1 center (first right of refusal), preventing S2 from stealing
peaks that should anchor S1s.
Each recovered peak is assigned to at most one segment (tracked via used_peaks).
State segments represent durations [start, end). The center of an S1 or S2 segment
is only used here to locate a nearby recovered peak and compute the shift delta.
For start_after_s1 gaps, the first rebuilt segment is systole (not S1), so the kept
real S1 anchor before the gap is never touched by this function.
"""
if (
(recovered_peaks_insensitive is None or len(recovered_peaks_insensitive) == 0)
and (recovered_peaks_sensitive is None or len(recovered_peaks_sensitive) == 0)
):
return state_labels, state_boundaries
# NOTE: don't use `arr or []` with numpy arrays (ambiguous truth value).
rec_ins = np.asarray(
recovered_peaks_insensitive if recovered_peaks_insensitive is not None else [],
dtype=np.int64,
)
rec_sens = np.asarray(
recovered_peaks_sensitive if recovered_peaks_sensitive is not None else [],
dtype=np.int64,
)
n = int(len(state_labels))
env = np.asarray(audio_envelope, dtype=np.float64)
sw = int(snap_window_samples)
used_peaks: set = set()
def _snap(expected: int, exclude_near: Optional[int] = None, *, allow_sensitive: bool = False) -> Optional[int]:
# Due to how gap detection works, there shouldn't be any already-known raw peaks
# inside the gap; recovered peaks are the only candidate source here.
# Scoring: closest in time; tie-break by higher envelope amplitude.
# Recovered peaks are generated with find_peaks(distance=...) so adjacent
# candidates shouldn't appear — the tie-break is just a safety net.
lo = expected - sw
hi = expected + sw
base = rec_ins
if allow_sensitive and rec_sens.size:
# S2 can use leftover insensitive peaks plus any additional sensitive peaks.
base = np.unique(np.concatenate([rec_ins, rec_sens]))
mask = (base >= lo) & (base <= hi)
cands = base[mask]
# Exclude peaks already consumed by a prior snap.
cands = cands[np.array([int(c) not in used_peaks for c in cands], dtype=bool)]
# Exclude peaks near the next S1 center (first right of refusal for S2 snapping).
if exclude_near is not None:
cands = cands[np.abs(cands - exclude_near) > sw]
if len(cands) == 0:
return None
dists = np.abs(cands - expected)
min_d = int(np.min(dists))
closest = cands[dists == min_d]
if len(closest) == 1:
return int(closest[0])
amps = env[np.clip(closest, 0, n - 1)]
return int(closest[np.argmax(amps)])
def _apply_shift(i: int, snapped: int) -> bool:
"""Shift segment i to be centered on snapped. Updates segs in place. Returns True if applied."""
a0, a1 = int(segs[i][0]), int(segs[i][1])
width = a1 - a0
if width <= 0:
return False
center = (a0 + a1) // 2
delta = snapped - center
if delta == 0:
return False
new_a0 = a0 + delta
new_a1 = a1 + delta # = new_a0 + width (segment width is preserved)
# Lower bound: can't start before the previous segment ends.
prev_end = int(segs[i - 1][1]) if i > 0 else a0
new_a0 = max(prev_end, new_a0)
new_a1 = new_a0 + width # re-derive after clamping start
# Upper bound: the next segment must keep at least 1 sample (systole / diastole).
next_end = int(segs[i + 1][1]) if i + 1 < ns else a1
if new_a1 >= next_end:
# Not enough room after the shift; keep synthetic placement.
return False
if new_a1 <= new_a0:
return False
segs[i][0] = new_a0
segs[i][1] = new_a1
name = segs[i][2]
new_meta = dict(segs[i][3])
new_meta["s1" if name == "S1" else "s2"] = snapped
new_meta["snapped"] = True
try:
if isinstance(new_meta.get("reasoning"), dict):
r = dict(new_meta["reasoning"])
notes = r.get("notes")
if not isinstance(notes, list):
notes = []
notes = list(notes)
notes.append("Shifted to recovered peak at gap.")
r["notes"] = notes
new_meta["reasoning"] = r
except Exception:
pass
segs[i][3] = new_meta
# Adjacent segments absorb the shift on each side.
if i > 0:
segs[i - 1][1] = new_a0
if i + 1 < ns:
segs[i + 1][0] = new_a1
return True
# Work on a mutable copy (list-of-lists) sorted by start.
segs = [list(s) for s in sorted(state_boundaries, key=lambda t: int(t[0]))]
ns = len(segs)
changed = False
def _is_rebuilt(i: int) -> bool:
m = segs[i][3]
return isinstance(m, dict) and m.get("rebuild_source") in ("gap_insert", "noise_repair")
# --- Pass 1: Snap all rebuilt S1 segments first ---
# S1 is the primary cardiac anchor; it gets first pick of recovered peaks.
for i in range(ns):
if segs[i][2] != "S1" or not _is_rebuilt(i):
continue
center = (int(segs[i][0]) + int(segs[i][1])) // 2
snapped = _snap(center, allow_sensitive=False)
if snapped is None:
continue
if _apply_shift(i, snapped):
used_peaks.add(snapped)
changed = True
# --- Pass 2: Snap rebuilt S2 segments using only remaining peaks ---
# Build rebuilt S1 centers (post-Pass-1 positions) for first-right-of-refusal:
# any peak within snap_window_samples of a future S1 center is off-limits for S2.
rebuilt_s1_centers = [
(int(segs[i][0]) + int(segs[i][1])) // 2
for i in range(ns)
if segs[i][2] == "S1" and _is_rebuilt(i)
]
for i in range(ns):
if segs[i][2] != "S2" or not _is_rebuilt(i):
continue
center = (int(segs[i][0]) + int(segs[i][1])) // 2
next_s1_center = next((c for c in rebuilt_s1_centers if c > center), None)
snapped = _snap(center, exclude_near=next_s1_center, allow_sensitive=True)
if snapped is None:
continue
if _apply_shift(i, snapped):
used_peaks.add(snapped)
changed = True
if not changed:
return state_labels, state_boundaries
new_boundaries = [tuple(s) for s in segs]
# Repaint state_labels from the updated boundary list.
_state_code = {
"S1": STATE_S1, "systole": STATE_SYSTOLE, "S2": STATE_S2, "diastole": STATE_DIASTOLE,
}
for _a0, _a1, _name, _ in new_boundaries:
code = _state_code.get(_name)
if code is None:
continue
lo = int(max(0, min(int(_a0), n)))
hi = int(max(0, min(int(_a1), n)))
if hi > lo:
state_labels[lo:hi] = code
return state_labels, new_boundaries
# ─────────────────────────────────────────────────────────────────────────────
# Module-level helpers (formerly closures inside _refine_and_correct_peaks)
# ─────────────────────────────────────────────────────────────────────────────
def _bpm_at_time(
t_sec: float,
lt_source: Any,
fallback_bpm: float,
) -> float:
"""
Interpolate BPM at time t_sec from a raster-backed source.
Accepts:
- (times, bpm) tuple/list of arrays
- dict with {"times": ..., "bpm": ...}
- pd.Series indexed by time (legacy; allowed for now)
"""
if lt_source is None:
return fallback_bpm
try:
times = None
values = None
if isinstance(lt_source, (tuple, list)) and len(lt_source) == 2:
times, values = lt_source
elif isinstance(lt_source, dict):
times = lt_source.get("times")
values = lt_source.get("bpm")
elif isinstance(lt_source, pd.Series):
if getattr(lt_source, "empty", True):
return fallback_bpm
times = lt_source.index.values
values = lt_source.values
else:
return fallback_bpm
times = np.asarray(times, dtype=np.float64)
values = np.asarray(values, dtype=np.float64)
if len(times) < 2 or len(times) != len(values):
return fallback_bpm
bpm = float(np.interp(float(t_sec), times, values, left=float(values[0]), right=float(values[-1])))
if not np.isfinite(bpm) or bpm <= 0:
return fallback_bpm
return bpm
except Exception:
return fallback_bpm
def _find_transient_bounds(
peak_idx: int,
half_window: int,
min_half: int,
max_half: int,
n_samples: int,
audio_envelope: np.ndarray,
edge_alpha: float,
edge_n_exp: float,
) -> Tuple[int, int]:
"""
Return (start, end) as a [start, end) sample slice for the transient at peak_idx.
Walks outward through a super-Gaussian-weighted envelope until the weighted value
drops to edge_alpha * peak_weighted_value. half_window is a hard cap; min/max_half
clamp the result to physiology bounds. Falls back to fixed half_window on error.
"""
try:
left = max(0, peak_idx - half_window)
right = min(n_samples - 1, peak_idx + half_window)
n_win = right - left + 1
sigma = max(1.0, n_win / 4.0)
dist = np.abs(np.arange(left, right + 1, dtype=np.float64) - peak_idx)
weights = np.exp(-((dist / sigma) ** edge_n_exp))
weighted_env = weights * audio_envelope[left: right + 1]
center_offset = peak_idx - left
peak_val = float(weighted_env[center_offset])
if peak_val <= 0.0:
raise ValueError("zero peak")
thresh = edge_alpha * peak_val
start = left
for k in range(center_offset - 1, -1, -1):
if weighted_env[k] <= thresh:
start = left + k + 1
break
end = right
for k in range(center_offset + 1, len(weighted_env)):
if weighted_env[k] <= thresh:
end = left + k - 1
break
start = max(start, peak_idx - max_half)
end = min(end, peak_idx + max_half)
start = min(start, peak_idx - min_half)
end = max(end, peak_idx + min_half)
start = max(0, start)
end = min(n_samples - 1, end)
return int(start), int(end + 1)
except Exception:
return max(0, peak_idx - half_window), min(n_samples, peak_idx + half_window + 1)
def _fmt_corr_note(c: Dict[str, Any], sample_rate: float) -> str:
"""Return a warning line describing the direct correction applied."""
ctype = c.get("type", "")
if ctype == "resnap_s2":
new_sys = round((c.get("new_s2", 0) - c.get("s1", 0)) / sample_rate * 1000)
return f"\u26a0 Systole out of range \u2014 S2 repositioned, systole now {new_sys}ms"
if ctype == "insert_s1":
return f"\u26a0 RR gap too long \u2014 missing beat inserted at {c.get('t_expected_sec', 0):.2f}s"
if ctype == "remove_false_s1":
return (
f"\u26a0 Both systole+diastole too short \u2014 false beat at "
f"{c.get('removed_s1', 0) / sample_rate:.2f}s removed"
)
if ctype == "flip_demote_s1":
old_t = c.get("old_s1_next", 0) / sample_rate
new_t = c.get("new_s1_next", 0) / sample_rate
return (
f"\u26a0 Diastole too short \u2014 beat at {old_t:.2f}s re-labeled as S2, "
f"new S1 at {new_t:.2f}s"
)
if ctype in ("sensitive_peak", "spectral_s2"):
new_sys = round(c.get("new_systole_sec", 0) * 1000)
method = "sensitive peak detection" if ctype == "sensitive_peak" else "spectral fingerprint"
return f"\u26a0 Systole too long \u2014 faint S2 found via {method}, systole now {new_sys}ms"
return f"\u26a0 Correction applied ({ctype})"
def _fmt_cascade_note(src: Dict[str, Any], sample_rate: float) -> str:
"""Return an info line describing an upstream correction that shifted this segment."""
ctype = src.get("type", "")
src_t = src.get("s1", src.get("s1_prev", 0)) / sample_rate
label = {
"resnap_s2": "S2 resnap",
"insert_s1": "beat insertion",
"remove_false_s1": "false beat removal",
"flip_demote_s1": "S1/S2 flip correction",
"sensitive_peak": "faint-S2 detection",
"spectral_s2": "spectral S2 detection",
}.get(ctype, ctype)
return f"\u2139 Shifted by {label} at {src_t:.2f}s; duration still within expected range"
# ─────────────────────────────────────────────────────────────────────────────
# Boundary geometry helpers
# ─────────────────────────────────────────────────────────────────────────────
def _resolve_boundary_overlap(
s1_start: int, s1_end: int,
s2_start: int, s2_end: int,
s1_next: int,
) -> Tuple[int, int, int, int]:
"""Resolve S1/S2 window overlaps and clip S2 end to the next cycle boundary."""
if s2_start < s1_end:
mid = (s1_end + s2_start) // 2
s1_end = max(s1_start + 1, min(s1_end, mid))
s2_start = max(s2_start, s1_end)
if s2_end >= s1_next:
s2_end = min(s2_end, s1_next)
return s1_start, s1_end, s2_start, s2_end
def _paint_state_boundaries(
s1: int,
s2: int,
s1_next: int,
s1_half: int,
s2_half: int,
n_samples: int,
audio_envelope: Optional[np.ndarray] = None,
edge_alpha: float = 0.03,
edge_n_exp: float = 4.0,
min_s1_half: int = 1,
max_s1_half: int = 50,
min_s2_half: int = 1,
max_s2_half: int = 50,
use_transient_detection: bool = False,
) -> Tuple[int, int, int, int]:
"""
Compute (s1_start, s1_end, s2_start, s2_end) for one cardiac cycle.
use_transient_detection=True (final timeline): envelope-based edge detection via
_find_transient_bounds; requires audio_envelope.
use_transient_detection=False (before-correction snapshot): fixed ±half-window.
"""
if use_transient_detection and audio_envelope is not None:
s1_start, s1_end = _find_transient_bounds(
s1, s1_half, min_s1_half, max_s1_half, n_samples, audio_envelope, edge_alpha, edge_n_exp,
)
s2_start, s2_end = _find_transient_bounds(
s2, s2_half, min_s2_half, max_s2_half, n_samples, audio_envelope, edge_alpha, edge_n_exp,
)
else:
s1_start = max(0, s1 - s1_half)
s1_end = min(n_samples, s1 + s1_half + 1)
s2_start = max(0, s2 - s2_half)
s2_end = min(n_samples, s2 + s2_half + 1)
s1_start, s1_end, s2_start, s2_end = _resolve_boundary_overlap(
s1_start, s1_end, s2_start, s2_end, s1_next,
)
return s1_start, s1_end, s2_start, s2_end
def _hover_audio_time_mmssmmm(sample_idx: int, sample_rate: float) -> str:
"""Wall-clock style time from start of audio: M:SS.mmm (minutes may exceed two digits)."""
sr = float(max(sample_rate, 1e-9))
t = float(sample_idx) / sr
m = int(t // 60)
s = t - 60.0 * m
return f"{m}:{s:06.3f}"
def _envelope_align_duration_note(phase: str, before_ms: int, after_ms: int) -> str:
"""Hover line: fixed ±window duration vs envelope-aligned duration (Pass 3 final paint)."""
label = {"S1": "S1", "S2": "S2", "systole": "Systole", "diastole": "Diastole"}.get(phase, phase)
if before_ms == after_ms:
return (
f"\u2139 {label}: duration unchanged at {after_ms}ms "
f"(envelope bounds matched the fixed \u00b1window span)."
)
return (
f"\u2139 {label}: duration altered to align with envelope bounds "
f"(from {before_ms}ms to {after_ms}ms)."
)
def _s2_index_hover_note(
s1: int,
s2: int,
s1_next: int,
s1_s2_pairs: Optional[List[Tuple[int, int]]],
ivs: Dict,
sample_rate: float,
) -> str:
"""Short S2 peak-time line for hover (Pass 2 pair vs BPM nominal)."""
pair_map = {int(a): int(b) for a, b in (s1_s2_pairs or [])}
s2_p2 = pair_map.get(int(s1))
in_w = s2_p2 is not None and s1 < int(s2_p2) < s1_next
s1_s2_nom = float(ivs.get("s1_s2_nominal", 0.30))
sr = float(sample_rate)
s2i = int(s2)
t_here = _hover_audio_time_mmssmmm(s2i, sr)
if in_w and s2i == int(s2_p2):
return f"\u2139 S2: location unchanged at {t_here}."
if in_w:
t_from = _hover_audio_time_mmssmmm(int(s2_p2), sr)
t_to = _hover_audio_time_mmssmmm(s2i, sr)
return f"\u2139 S2: location altered from {t_from} to {t_to}."
return (
f"\u2139 S2: at {t_here} from BPM nominal s1_s2 ({s1_s2_nom:.3f}s); no Pass 2 pair in this RR window."
)
def _build_reasoning_payload(
s1: int,
s1_start: int,
s1_end: int,
s2: int,
s2_start: int,
s2_end: int,
s1_next: int,
ivs: Dict,
direct_corrections: List[Dict],
cascade_src: Optional[Dict],
before_s2: Optional[int],
before_s1nxt: Optional[int],
sample_rate: float,
shift_thresh_samp: int,
*,
hover_debug_geometry: bool = False,
hover_s1_s2_pairs: Optional[List[Tuple[int, int]]] = None,
hover_s1_half: int = 0,
hover_s2_half: int = 0,
hover_n_samples: int = 0,
) -> Dict[str, Any]:
"""Build expected/measured ms + warning notes per state for the HTML overlay (cardiac strip hover)."""
_exp_s1_ms = round(ivs.get("s1_nominal", 0.040) * 1000)
_exp_sys_ms = round(ivs.get("s1_s2_nominal", 0.300) * 1000)
_exp_s2_ms = round(ivs.get("s2_nominal", 0.030) * 1000)
_exp_dia_ms = round(ivs.get("s2_s1_nominal", 0.400) * 1000)
_meas_s1_ms = round((s1_end - s1_start) / sample_rate * 1000) if s1_end > s1_start else 0
_meas_sys_ms = round((s2_start - s1_end) / sample_rate * 1000) if s2_start > s1_end else 0
_meas_s2_ms = round((s2_end - s2_start) / sample_rate * 1000) if s2_end > s2_start else 0
_meas_dia_ms = round((s1_next - s2_end) / sample_rate * 1000) if s1_next > s2_end else 0
_s1_notes = [_fmt_corr_note(c, sample_rate) for c in direct_corrections
if c.get("type") == "remove_false_s1"]
_sys_notes = [_fmt_corr_note(c, sample_rate) for c in direct_corrections
if c.get("type") in ("resnap_s2", "flip_demote_s1", "sensitive_peak", "spectral_s2")]
_s2_notes = [_fmt_corr_note(c, sample_rate) for c in direct_corrections
if c.get("type") in ("resnap_s2", "flip_demote_s1", "sensitive_peak", "spectral_s2")]
_dia_notes = [_fmt_corr_note(c, sample_rate) for c in direct_corrections
if c.get("type") in ("insert_s1", "flip_demote_s1")]
if cascade_src:
if not _sys_notes and before_s2 is not None and abs(before_s2 - s2) > shift_thresh_samp:
_sys_notes.append(_fmt_cascade_note(cascade_src, sample_rate))
if not _dia_notes and before_s1nxt is not None and abs(before_s1nxt - s1_next) > shift_thresh_samp:
_dia_notes.append(_fmt_cascade_note(cascade_src, sample_rate))
if not _s2_notes and before_s2 is not None and abs(before_s2 - s2) > shift_thresh_samp:
_s2_notes.append(_fmt_cascade_note(cascade_src, sample_rate))
if hover_debug_geometry:
if hover_n_samples > 0 and hover_s1_half >= 1 and hover_s2_half >= 1:
fs1s, fs1e, fs2s, fs2e = _paint_state_boundaries(
s1, s2, s1_next, hover_s1_half, hover_s2_half, hover_n_samples,
use_transient_detection=False,
)
bf_s1 = round((fs1e - fs1s) / sample_rate * 1000) if fs1e > fs1s else 0
bf_s2 = round((fs2e - fs2s) / sample_rate * 1000) if fs2e > fs2s else 0
bf_sys = round((fs2s - fs1e) / sample_rate * 1000) if fs2s > fs1e else 0
bf_dia = round((s1_next - fs2e) / sample_rate * 1000) if s1_next > fs2e else 0
_s1_notes = [_envelope_align_duration_note("S1", bf_s1, _meas_s1_ms)] + _s1_notes
_sys_notes = [_envelope_align_duration_note("systole", bf_sys, _meas_sys_ms)] + _sys_notes
_s2_notes = (
[_envelope_align_duration_note("S2", bf_s2, _meas_s2_ms)]
+ [_s2_index_hover_note(s1, s2, s1_next, hover_s1_s2_pairs, ivs, sample_rate)]
+ _s2_notes
)
_dia_notes = [_envelope_align_duration_note("diastole", bf_dia, _meas_dia_ms)] + _dia_notes
else:
_s1_notes = [
f"\u2139 S1: duration {_meas_s1_ms}ms (envelope-aligned; fixed-window baseline unavailable).",
] + _s1_notes
_sys_notes = [
f"\u2139 Systole: duration {_meas_sys_ms}ms (gap after envelope paint).",
] + _sys_notes
_s2_notes = (
[f"\u2139 S2: duration {_meas_s2_ms}ms (envelope-aligned; fixed-window baseline unavailable)."]
+ [_s2_index_hover_note(s1, s2, s1_next, hover_s1_s2_pairs, ivs, sample_rate)]
+ _s2_notes
)
_dia_notes = [
f"\u2139 Diastole: duration {_meas_dia_ms}ms (gap after envelope paint).",
] + _dia_notes
return {
"S1": {"expected_ms": _exp_s1_ms, "measured_ms": _meas_s1_ms, "notes": _s1_notes},
"systole": {"expected_ms": _exp_sys_ms, "measured_ms": _meas_sys_ms, "notes": _sys_notes},
"S2": {"expected_ms": _exp_s2_ms, "measured_ms": _meas_s2_ms, "notes": _s2_notes},
"diastole": {"expected_ms": _exp_dia_ms, "measured_ms": _meas_dia_ms, "notes": _dia_notes},
}
# ─────────────────────────────────────────────────────────────────────────────
# S2-events rebuild helper
# ─────────────────────────────────────────────────────────────────────────────
def _rebuild_s2_events(
s1_list: List[int],
lt_series: Optional[pd.Series],
fallback_bpm: float,
sample_rate: int,
params: Dict,
seed_s2_events: Optional[List[int]] = None,
) -> List[int]:
"""One S2 index per RR interval: Pass 2 seed when valid, else BPM nominal clamp."""
seed = seed_s2_events
s2_events: List[int] = []
for j in range(len(s1_list) - 1):
a = int(s1_list[j])
b = int(s1_list[j + 1])
if b <= a:
s2_events.append(int(a))
continue
if seed is not None and j < len(seed):
sj = int(seed[j])
if a < sj < b:
s2_events.append(int(max(a + 1, min(sj, b - 1))))
continue
t_a = a / float(sample_rate)
bpm_a = _bpm_at_time(t_a, lt_series, fallback_bpm)
ivs_a = calculate_bpm_intervals(bpm_a, params)
s1_s2_nominal_a = float(ivs_a.get("s1_s2_nominal", 0.30))
s2_pred_a = int(round(a + s1_s2_nominal_a * sample_rate))
s2_events.append(int(max(a + 1, min(s2_pred_a, b - 1))))
return s2_events
def _noise_sample_intervals(
noise_event_segments: Optional[List[Dict[str, Any]]],
sample_rate: int,
n_samples: int,
) -> List[Tuple[int, int]]:
"""Convert noise_event_segments (seconds) to half-open sample intervals [lo, hi)."""
out: List[Tuple[int, int]] = []
if not noise_event_segments or sample_rate <= 0 or n_samples <= 0:
return out
for seg in noise_event_segments:
if not isinstance(seg, dict):
continue
try:
t0 = float(seg.get("start", float("nan")))
t1 = float(seg.get("end", float("nan")))
except (TypeError, ValueError):
continue
if not (math.isfinite(t0) and math.isfinite(t1)) or t1 <= t0:
continue
lo = int(math.floor(t0 * sample_rate))
hi = int(math.ceil(t1 * sample_rate))
lo = max(0, lo)
hi = min(n_samples, max(lo + 1, hi))
out.append((lo, hi))
return out
def _merge_sorted_intervals(ivs: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
if not ivs:
return []
s = sorted(ivs, key=lambda t: (t[0], t[1]))
out: List[Tuple[int, int]] = [s[0]]
for a, b in s[1:]:
la, lb = out[-1]
if a <= lb:
out[-1] = (la, max(lb, b))
else:
out.append((a, b))
return out
def _half_open_intervals_intersect(a0: int, a1: int, b0: int, b1: int) -> bool:
"""True iff [a0, a1) and [b0, b1) overlap (half-open)."""
return int(b0) < int(a1) and int(b1) > int(a0)
def _span_intersects_merged_noise(
lo: int, hi: int, merged: List[Tuple[int, int]], n_samples: int,
) -> bool:
"""True if [lo, hi) overlaps any merged HF-noise interval."""
for nlo, nhi in merged:
nlo = max(0, int(nlo))
nhi = min(n_samples, int(nhi))
if nhi <= nlo:
continue
if _half_open_intervals_intersect(lo, hi, nlo, nhi):
return True
return False
def _build_lt_bpm_series_from_clean_rr(
s1_peaks: np.ndarray,
noise_ivs: List[Tuple[int, int]],
sample_rate: int,
n_samples: int,
params: Optional[Dict] = None,
) -> Optional[pd.Series]:
"""
Build a time-indexed BPM series from S1→S1 intervals that do NOT intersect HF-noise.
Each retained interval contributes one (t_mid, bpm) point:
t_mid = midpoint time of the RR interval, bpm = 60 / RR_sec.
Applies the same light cleaning used for measured systole/diastole curves:
- local MAD outlier removal in a rolling time window
- small Gaussian-weighted rolling mean smoothing
Returns None if there are not enough clean intervals to interpolate (need >=2).
"""
if sample_rate <= 0:
return None
peaks = np.asarray(s1_peaks, dtype=np.int64)
if len(peaks) < 2:
return None
merged = _merge_sorted_intervals(noise_ivs or [])
if merged and int(merged[0][0]) == 0:
# Mirror _pass3_clear_states_in_hf_noise: ignore the first noise span at file start.
merged = merged[1:]
t_list: List[float] = []
bpm_list: List[float] = []
sr = float(sample_rate)
for i in range(len(peaks) - 1):
a = int(peaks[i])
b = int(peaks[i + 1])
if b <= a:
continue
if merged and _span_intersects_merged_noise(a, b, merged, n_samples):
continue
rr_sec = (b - a) / sr
if not np.isfinite(rr_sec) or rr_sec <= 0:
continue
bpm = 60.0 / rr_sec
if not np.isfinite(bpm) or bpm <= 0:
continue
t_mid = 0.5 * (a + b) / sr
t_list.append(float(t_mid))
bpm_list.append(float(bpm))
if len(t_list) < 2:
return None
t = np.asarray(t_list, dtype=np.float64)
y = np.asarray(bpm_list, dtype=np.float64)
order = np.argsort(t)
t = t[order]
y = y[order]
# Reuse the measured-phase cleaner (MAD + light Gaussian smoothing).
# We pass noise_ivs=None because RR intervals were already excluded by intersection tests.
t2, y2 = _pass3_clean_duration_series(t, y, noise_ivs=None, sample_rate=sample_rate, params=(params or {}))
if len(t2) < 2:
return None
return pd.Series(y2, index=t2, dtype=float)
def _dense_bpm_raster_from_series(
lt_series: Optional[pd.Series],
n_samples: int,
sample_rate: int,
fallback_bpm: float,
dt_sec: float = 0.05,
) -> Tuple[np.ndarray, np.ndarray]:
"""
Build a dense BPM raster (times, bpm_values) sampled every dt_sec across the file.
This makes the BPM prior explicit and continuous-in-time for later consumers.
Values are obtained by linear interpolation of lt_series with constant edge extrapolation.
"""
sr = float(sample_rate)
if sr <= 0 or n_samples <= 0:
return np.asarray([], dtype=np.float64), np.asarray([], dtype=np.float64)
dur_sec = float(n_samples) / sr
if not np.isfinite(dur_sec) or dur_sec <= 0:
return np.asarray([], dtype=np.float64), np.asarray([], dtype=np.float64)
dt = float(dt_sec)
if not np.isfinite(dt) or dt <= 0:
dt = 0.05
t_grid = np.arange(0.0, dur_sec + 1e-12, dt, dtype=np.float64)
if lt_series is None or getattr(lt_series, "empty", True):
return t_grid, np.full_like(t_grid, float(fallback_bpm), dtype=np.float64)
try:
times = np.asarray(lt_series.index.values, dtype=np.float64)
values = np.asarray(lt_series.values, dtype=np.float64)
if len(times) < 2 or len(times) != len(values):
return t_grid, np.full_like(t_grid, float(fallback_bpm), dtype=np.float64)
bpm_grid = np.interp(t_grid, times, values, left=float(values[0]), right=float(values[-1])).astype(np.float64)
bpm_grid[~np.isfinite(bpm_grid)] = float(fallback_bpm)
bpm_grid[bpm_grid <= 0] = float(fallback_bpm)
return t_grid, bpm_grid
except Exception:
return t_grid, np.full_like(t_grid, float(fallback_bpm), dtype=np.float64)
def _dense_raster_from_points(
t_points: np.ndarray,
y_points: np.ndarray,
n_samples: int,
sample_rate: int,
*,
dt_sec: float = 0.05,
) -> Tuple[np.ndarray, np.ndarray]:
"""
Build a dense raster (times, values) sampled every dt_sec across the file from sparse points.
Uses linear interpolation with constant edge extrapolation (np.interp).
Returns empty arrays when there are not enough points to interpolate (need >=2).
"""
sr = float(sample_rate)
if sr <= 0 or n_samples <= 0:
return np.asarray([], dtype=np.float64), np.asarray([], dtype=np.float64)
dur_sec = float(n_samples) / sr
if not np.isfinite(dur_sec) or dur_sec <= 0:
return np.asarray([], dtype=np.float64), np.asarray([], dtype=np.float64)
dt = float(dt_sec)
if not np.isfinite(dt) or dt <= 0:
dt = 0.05
t_points = np.asarray(t_points, dtype=np.float64)
y_points = np.asarray(y_points, dtype=np.float64)
if len(t_points) < 2 or len(t_points) != len(y_points):
return np.asarray([], dtype=np.float64), np.asarray([], dtype=np.float64)
t_grid = np.arange(0.0, dur_sec + 1e-12, dt, dtype=np.float64)
order = np.argsort(t_points)
t_points = t_points[order]
y_points = y_points[order]
y_grid = np.interp(t_grid, t_points, y_points, left=float(y_points[0]), right=float(y_points[-1])).astype(np.float64)
return t_grid, y_grid
def _pass3_clear_states_in_hf_noise(
state_labels: np.ndarray,
state_boundaries: List[Tuple],
noise_ivs: List[Tuple[int, int]],
n_samples: int,
s1_peaks: np.ndarray,
) -> Tuple[np.ndarray, List[Tuple]]:
"""
HF noise repair (merged preprocessing windows):
- If the **S1** phase of a beat intersects noise, clear dense labels from painted S1 start
through the next S1 peak and drop all four boundary segments for that beat.
- If **diastole** intersects noise **and S1 does not**, clear only **after** that beat's
own S1 phase through the next S1 peak ``[s1_end, s1_next)``, keep the **S1** segment,
and drop systole / S2 / diastole segments for that beat only (anchor = this beat's S1).
The **first merged** HF-noise interval **starting at sample 0** is ignored for this
repair only: clearing there would remove early S1 runs and Pass 3 state-timeline BPM would
have no points for the start of the file. Later noise windows still trigger clearing.
"""
merged = _merge_sorted_intervals(noise_ivs)
if not merged:
return state_labels, state_boundaries
if int(merged[0][0]) == 0:
merged = merged[1:]
if not merged:
return state_labels, state_boundaries
peaks = np.asarray(s1_peaks, dtype=np.int64)
n_cyc = max(0, len(peaks) - 1)
# One pass over boundaries: O(n) maps for cycle lookups (avoids re-scanning per beat).
s1_span: Dict[int, Tuple[int, int]] = {}
dia_span: Dict[int, Tuple[int, int]] = {}
for seg in state_boundaries:
st = seg[2]
if st not in ("S1", "diastole"):
continue
bm = seg[3] if isinstance(seg[3], dict) else {}
pk = bm.get("s1")
if pk is None:
continue
pk_i = int(pk)
a0 = max(0, min(int(seg[0]), n_samples))
a1 = max(0, min(int(seg[1]), n_samples))
if a1 <= a0:
continue
if st == "S1":
s1_span[pk_i] = (a0, a1)
else:
dia_span[pk_i] = (a0, a1)
s1_touch: set = set()
dia_touch: set = set()
for i in range(n_cyc):
pk = int(peaks[i])
s1_next = int(peaks[i + 1])
if s1_next <= pk:
continue
se = s1_span.get(pk)
if se is None:
continue
s0, e0 = se
if _span_intersects_merged_noise(s0, e0, merged, n_samples):
s1_touch.add(pk)
de = dia_span.get(pk)