-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplotting.py
More file actions
2002 lines (1860 loc) · 89.6 KB
/
plotting.py
File metadata and controls
2002 lines (1860 loc) · 89.6 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
import os
import logging
import time
import urllib.parse
import re
from time_utils import seconds_to_datetime
import csv
import shutil
import json
import tempfile
from typing import Dict, Optional, List, Any, Tuple
from peak_utils import PeakType, _get_peak_type_from_debug, format_debug_entry, get_peak_prominence_details
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from config import DEFAULT_OUTPUT_OPTIONS, output_stem_from_path, strip_output_filename_emojis
from confidence_engine import calculate_bpm_intervals
from hrv import compute_systole_interval_curve
import librosa
import librosa.display
import matplotlib
matplotlib.use("Agg") # Use non-interactive backend for spectrogram generation
import matplotlib.pyplot as plt
def _elapsed_seconds_to_plot_datetimes(seconds: np.ndarray) -> pd.DatetimeIndex:
"""
Vectorized equivalent of
pd.to_datetime([seconds_to_datetime(float(t)) for t in seconds]).
Same local-epoch convention as time_utils.seconds_to_datetime (for Plotly x).
"""
arr = np.asarray(seconds, dtype=np.float64).reshape(-1)
if arr.size == 0:
return pd.DatetimeIndex([], dtype="datetime64[ns]")
base = pd.Timestamp(seconds_to_datetime(0.0))
return base + pd.to_timedelta(arr, unit="s")
def prewarm_kaleido_png_export() -> None:
"""
Start Kaleido's persistent sync server (Kaleido >= 1.1) so Chromium stays
alive across multiple fig.write_image() calls. Plotly routes write_image to
kaleido.calc_fig_sync, which uses the global server when it is running.
Safe to call multiple times. No-op if Kaleido is missing or too old.
Kaleido registers its own atexit handler to stop the server on shutdown.
"""
try:
logging.debug("Kaleido: prewarm_kaleido_png_export()")
import kaleido # noqa: PLC0415
if not hasattr(kaleido, "start_sync_server"):
logging.debug("Kaleido: start_sync_server missing (install kaleido>=1.1 for persistent export)")
return
# Align with plotly.io.defaults so the server loads the same plotly.js /
# MathJax as Plotly would pass via kopts on one-shot exports (kopts are
# ignored per call while the server is running).
kw = {"silence_warnings": True}
try:
import plotly.io as pio # noqa: PLC0415
d = pio.defaults
if getattr(d, "plotlyjs", None):
kw["plotlyjs"] = d.plotlyjs
if getattr(d, "mathjax", None):
kw["mathjax"] = d.mathjax
except Exception:
pass
try:
from kaleido import _sync_server as _kaleido_sync # noqa: PLC0415
_kaleido_was_running = _kaleido_sync.GlobalKaleidoServer().is_running()
except Exception:
_kaleido_was_running = False
kaleido.start_sync_server(**kw)
if _kaleido_was_running:
logging.debug("Kaleido: sync server already running (batch — reuse persistent Chromium)")
else:
logging.debug("Kaleido: start_sync_server() started (persistent Chromium for PNG export)")
except Exception:
logging.debug(
"Kaleido: prewarm failed (one-shot export per write_image)",
exc_info=True,
)
def _compute_systolic_interval_data(
analysis_data: Dict,
pass_metrics: Dict,
sample_rate: int,
params: Dict,
) -> Tuple[List[float], List[float], List[float], List[float]]:
"""
Compute measured systole intervals from labeled pairs and BPM-expected systolic curve.
Returns (observed_times, observed_intervals, expected_times, expected_intervals).
"""
# Measured systole intervals from labeled pairs
pairs = analysis_data.get("s1_s2_pairs") or []
observed_times: List[float] = []
observed_intervals: List[float] = []
for s1_idx, s2_idx in pairs:
t = (s1_idx + s2_idx) / 2.0 / sample_rate
interval = (s2_idx - s1_idx) / sample_rate
observed_times.append(t)
observed_intervals.append(interval)
# BPM-expected systolic curve from pass metrics
smoothed_bpm = pass_metrics.get("smoothed_bpm")
bpm_times = pass_metrics.get("bpm_times")
expected_times: List[float] = []
expected_intervals: List[float] = []
if smoothed_bpm is not None and bpm_times is not None and len(bpm_times) == len(smoothed_bpm):
for t, bpm in zip(np.asarray(bpm_times, dtype=float), np.asarray(smoothed_bpm, dtype=float)):
intervals = calculate_bpm_intervals(float(bpm), params)
expected_times.append(float(t))
expected_intervals.append(intervals["s1_s2_nominal"])
return observed_times, observed_intervals, expected_times, expected_intervals
def _compute_measured_systole_from_state_boundaries(
analysis_data: Dict,
sample_rate: int,
*,
prefer: str = "after",
) -> Tuple[List[float], List[float]]:
"""
Compute measured systole durations from Pass 3 dense state boundaries.
Returns (times, durations) in seconds, where time is the segment midpoint.
"""
if prefer == "before":
boundaries = analysis_data.get("pass3_state_boundaries_before") or []
else:
boundaries = analysis_data.get("pass3_state_boundaries") or []
if not boundaries:
boundaries = analysis_data.get("pass3_state_boundaries_before") or []
measured_times: List[float] = []
measured_durations: List[float] = []
for s0, s1, state_name, _meta in (boundaries or []):
try:
if str(state_name).lower() != "systole":
continue
s0i = int(s0)
s1i = int(s1)
if s1i <= s0i:
continue
t_mid = (s0i + s1i) / 2.0 / float(sample_rate)
dur = (s1i - s0i) / float(sample_rate)
if not np.isfinite(t_mid) or not np.isfinite(dur):
continue
measured_times.append(float(t_mid))
measured_durations.append(float(dur))
except Exception:
continue
return measured_times, measured_durations
def _compute_measured_diastole_from_state_boundaries(
analysis_data: Dict,
sample_rate: int,
*,
prefer: str = "after",
) -> Tuple[List[float], List[float]]:
"""
Compute measured diastole durations from Pass 3 dense state boundaries.
Returns (times, durations) in seconds, where time is the segment midpoint.
"""
if prefer == "before":
boundaries = analysis_data.get("pass3_state_boundaries_before") or []
else:
boundaries = analysis_data.get("pass3_state_boundaries") or []
if not boundaries:
boundaries = analysis_data.get("pass3_state_boundaries_before") or []
measured_times: List[float] = []
measured_durations: List[float] = []
for s0, s1, state_name, _meta in (boundaries or []):
try:
if str(state_name).lower() != "diastole":
continue
s0i = int(s0)
s1i = int(s1)
if s1i <= s0i:
continue
t_mid = (s0i + s1i) / 2.0 / float(sample_rate)
dur = (s1i - s0i) / float(sample_rate)
if not np.isfinite(t_mid) or not np.isfinite(dur):
continue
measured_times.append(float(t_mid))
measured_durations.append(float(dur))
except Exception:
continue
return measured_times, measured_durations
def _compute_expected_diastole_from_bpm(
pass_metrics: Dict,
params: Dict,
) -> Tuple[List[float], List[float]]:
"""
Compute expected diastole (S2→next S1) from BPM over time.
Returns (times, durations) in seconds.
"""
smoothed_bpm = pass_metrics.get("smoothed_bpm")
bpm_times = pass_metrics.get("bpm_times")
expected_times: List[float] = []
expected_durations: List[float] = []
if smoothed_bpm is not None and bpm_times is not None and len(bpm_times) == len(smoothed_bpm):
for t, bpm in zip(np.asarray(bpm_times, dtype=float), np.asarray(smoothed_bpm, dtype=float)):
intervals = calculate_bpm_intervals(float(bpm), params)
expected_times.append(float(t))
expected_durations.append(float(intervals["s2_s1_nominal"]))
return expected_times, expected_durations
def _compute_systolic_shift(
obs_t: List[float],
obs_iv: List[float],
exp_t: List[float],
exp_iv: List[float],
peak_bpm_time_sec: Optional[float],
) -> Optional[float]:
"""
Compute shift to align expected systole curve to measured data.
If peak_bpm_time_sec: use exertion only (t < peak). Else: average across all time.
Returns shift (measured_avg - expected_avg) or None if insufficient data.
"""
if not obs_t or not obs_iv or not exp_t or not exp_iv or len(exp_t) < 2:
return None
obs_t_arr = np.array(obs_t, dtype=float)
obs_iv_arr = np.array(obs_iv, dtype=float)
exp_t_arr = np.array(exp_t, dtype=float)
exp_iv_arr = np.array(exp_iv, dtype=float)
if peak_bpm_time_sec is not None:
mask = obs_t_arr < peak_bpm_time_sec
else:
mask = np.ones(len(obs_t_arr), dtype=bool)
if not np.any(mask):
return None
measured_avg = float(np.mean(obs_iv_arr[mask]))
expected_at_measured = np.interp(obs_t_arr[mask], exp_t_arr, exp_iv_arr)
expected_avg = float(np.mean(expected_at_measured))
return measured_avg - expected_avg
class Plotter:
"""Handles the creation and generation of the final analysis plot."""
def __init__(
self,
file_name: str,
params: Dict,
sample_rate: int,
output_directory: str,
source_audio_path: Optional[str] = None,
):
self.file_name = file_name
self.output_stem = output_stem_from_path(file_name)
self.params = params
self.sample_rate = sample_rate
self.output_directory = output_directory
self.audio_source_path = source_audio_path or file_name
self.fig = make_subplots(specs=[[{"secondary_y": True}]])
self.audio_duration_sec = None # Will be set during plot_and_save
# Optional spectrogram image filenames (saved in output dir); filtered generated on demand.
self.spectrogram_original_filename: Optional[str] = None
self.bpm_axis_center: float = float(params.get("default_bpm_axis_center", 125))
self.bpm_axis_span: float = float(params.get("bpm_axis_span", 150))
def _generate_spectrogram_image(self, audio_path: str, output_path: str) -> Optional[str]:
"""
Generate a spectrogram image from the audio file and save as PNG to output_path.
Returns the basename of the saved file (for use in HTML/config), or None on failure.
"""
try:
# Load audio at a reasonable sample rate for spectrogram
audio_data, sr = librosa.load(audio_path, sr=22050, mono=True)
if audio_data is None or len(audio_data) == 0:
logging.warning("Could not load audio for spectrogram generation")
return None
# Compute mel spectrogram for better visual representation
n_fft = 2048
hop_length = 128
n_mels = 256 # Slightly smaller for reasonable file size
# Generate mel spectrogram
S = librosa.feature.melspectrogram(
y=audio_data, sr=sr, n_fft=n_fft, hop_length=hop_length, n_mels=n_mels
)
# Convert to dB scale
S_dB = librosa.power_to_db(S, ref=np.max)
# Calculate figure dimensions based on audio duration; cap width to limit file size
duration = len(audio_data) / sr
fig_width = min(max(20, duration / 10), 80)
fig_height = 6
# Create figure with transparent background
fig, ax = plt.subplots(figsize=(fig_width, fig_height))
fig.patch.set_alpha(0)
ax.patch.set_alpha(0)
# Display spectrogram with a colormap that works well as background
librosa.display.specshow(
S_dB,
sr=sr,
hop_length=hop_length,
x_axis="time",
y_axis="mel",
ax=ax,
cmap="magma",
)
# Remove axes, labels, and all decorations for clean overlay
ax.axis("off")
ax.set_xlabel("")
ax.set_ylabel("")
ax.set_title("")
# Remove all margins
plt.tight_layout(pad=0)
plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
# Save to file as PNG with transparency (dpi 72 for smaller file size)
fig.savefig(
output_path,
format="png",
transparent=True,
dpi=72,
bbox_inches="tight",
pad_inches=0,
)
plt.close(fig)
basename = os.path.basename(output_path)
logging.info(f"Generated spectrogram image for background overlay: {basename}")
return basename
except Exception as e:
logging.warning(f"Failed to generate spectrogram image: {e}")
return None
def plot_and_save(
self,
audio_envelope: np.ndarray,
all_raw_peaks: np.ndarray,
analysis_data: Dict,
pass_metrics: Dict,
output_options: Optional[Dict] = None,
output_suffix: Optional[str] = None,
filename_suffix: Optional[str] = None,
pass1_bpm_series: Optional[pd.Series] = None,
pass1_bpm_times: Optional[np.ndarray] = None,
):
"""Generates and saves the main analysis plot by calling helper methods.
pass_metrics: BPM/HRV/slope metrics for the pass being plotted (pass 2, pass 3, etc.).
output_suffix: pass id for trace labels and systolic logic ('_pass2', '_pass3').
filename_suffix: if set, used for HTML/PNG/CSV file names; if None, uses output_suffix or '_bpm_plot'.
"""
self.fig = make_subplots(specs=[[{"secondary_y": True}]])
self.time_axis_sec = np.arange(len(audio_envelope)) / self.sample_rate
self.audio_duration_sec = self.time_axis_sec[-1] if len(self.time_axis_sec) > 0 else 0
self._has_systolic_traces = False
# Optional pass 3 dense state timeline (S1/systole/S2/diastole) for HTML overlay.
self._pass3_state_boundaries = analysis_data.get("pass3_state_boundaries") or []
self._pass3_state_boundaries_before = analysis_data.get("pass3_state_boundaries_before") or []
self._pass3_state_labels_encoding = analysis_data.get("pass3_state_labels_encoding") or {}
self._noise_event_segments = analysis_data.get("noise_event_segments") or []
self._pass3_noise_unreliable_windows_samples = analysis_data.get("pass3_noise_unreliable_windows_samples") or []
self._pass3_large_gap_windows_samples = analysis_data.get("pass3_large_gap_windows_samples") or []
self._pass3_gap_quiet_windows_samples = analysis_data.get("pass3_gap_quiet_windows_samples") or []
self._pass3_large_gap_recovered_peaks_insensitive = analysis_data.get("pass3_large_gap_recovered_peaks_insensitive") or []
self._pass3_large_gap_recovered_peaks_sensitive = analysis_data.get("pass3_large_gap_recovered_peaks_sensitive") or []
# Long-plot optimization: optionally skip heavy debug traces for very long recordings.
optimize_long_plots = bool(self.params.get("optimize_long_plots", False))
long_threshold_sec = float(self.params.get("long_plot_duration_threshold_sec", 600.0))
# Only skip details if the recording is longer than the threshold; shorter files always show full detail.
self.skip_detailed_debug_traces = optimize_long_plots and self.audio_duration_sec > long_threshold_sec
self._add_line_traces(audio_envelope, analysis_data, all_raw_peaks)
self._add_trough_markers(audio_envelope, analysis_data)
self._add_peak_traces(
all_raw_peaks,
analysis_data.get("peak_classifications", {}),
audio_envelope,
analysis_data.get("trough_indices"),
)
self._add_pass3_large_gap_recovered_peak_markers(audio_envelope)
self._add_bpm_hrv_traces(
pass_metrics.get("smoothed_bpm"),
analysis_data,
pass_metrics.get("windowed_hrv_df"),
output_suffix=output_suffix,
pass1_bpm_series=pass1_bpm_series,
pass1_bpm_times=pass1_bpm_times,
instant_bpm=pass_metrics.get("instant_bpm"),
bpm_times=pass_metrics.get("bpm_times"),
instant_bpm_raw=pass_metrics.get("instant_bpm_raw"),
bpm_times_raw=pass_metrics.get("bpm_times_raw"),
)
self._add_systolic_interval_traces(
analysis_data, pass_metrics, output_suffix,
)
self._add_slope_traces(
pass_metrics.get("major_inclines"),
pass_metrics.get("major_declines"),
pass_metrics.get("peak_recovery_stats"),
pass_metrics.get("peak_exertion_stats"),
)
self._add_annotations_and_summary(
pass_metrics.get("bpm_times"),
pass_metrics.get("smoothed_bpm"),
pass_metrics.get("hrv_summary"),
pass_metrics.get("hrr_stats"),
pass_metrics.get("peak_recovery_stats"),
)
self._prepare_bpm_axis_center(pass_metrics)
self._configure_layout()
base_name = self.output_stem
file_suffix = (
filename_suffix
if filename_suffix is not None
else (output_suffix if output_suffix is not None else "_bpm_plot")
)
output_html_path = os.path.join(self.output_directory, f"{base_name}{file_suffix}.html")
output_png_path = os.path.join(self.output_directory, f"{base_name}{file_suffix}.png")
plot_title = f"Heartbeat Analysis - {os.path.basename(self.file_name)}"
plot_config = {
"scrollZoom": True,
"toImageButtonOptions": {"filename": plot_title, "format": "png", "scale": 2},
"showTips": False,
}
html_requested = True if output_options is None else output_options.get("html", True)
png_requested = False if output_options is None else output_options.get("png", False)
if html_requested:
# Determine whether spectrogram generation is enabled (can be disabled via GUI/output options).
self.spectrogram_enabled = True
if output_options is not None:
self.spectrogram_enabled = output_options.get("spectrogram", True)
# Generate spectrogram image for optional background overlay (original audio only).
# Filtered spectrograms are generated later in _generate_custom_html if needed.
if self.spectrogram_enabled:
try:
spec_path = os.path.join(self.output_directory, f"{base_name}_spectrogram.png")
self.spectrogram_original_filename = self._generate_spectrogram_image(
self.audio_source_path or self.file_name, spec_path
)
except Exception as e:
logging.warning(f"Failed to generate original spectrogram: {e}")
else:
logging.info("Skipping original spectrogram generation as requested (spectrogram output disabled).")
# Generate the base Plotly HTML
plotly_html = self.fig.to_html(config=plot_config, full_html=False, include_plotlyjs='cdn')
# If CDN is unavailable, fall back to a local plotly.min.js beside the HTML (if present).
plotly_html = re.sub(
r'<script\s+src="(https://cdn\.plot\.ly/plotly[^"]+)"\s*></script>',
r'<script src="\1" onerror="this.onerror=null;this.src=\'plotly.min.js\';"></script>',
plotly_html,
count=1,
)
# Generate custom HTML with audio player and playhead
custom_html = self._generate_custom_html(
plotly_html, plot_title, base_name, output_options=output_options
)
with open(output_html_path, 'w', encoding='utf-8') as f:
f.write(custom_html)
logging.info(f"Interactive plot with audio player saved to {output_html_path}")
else:
logging.info("Skipping HTML plot generation as requested.")
if png_requested:
# Use a large default canvas so the graph itself is comfortably sized in the PNG.
opts = output_options or {}
png_scale = int(opts.get("png_scale", 2) or 2)
png_width = int(opts.get("png_width") or 2100)
png_height = int(opts.get("png_height") or 1200)
write_kwargs = {
"format": "png",
"scale": png_scale,
"width": png_width,
"height": png_height,
}
try:
self.fig.write_image(output_png_path, **write_kwargs)
logging.info(f"Plot PNG exported via Kaleido to {output_png_path}")
except Exception as e:
logging.warning(f"Failed to export Plot PNG (requires kaleido): {e}")
if output_options is None or output_options.get("csv", True):
smoothed_bpm = pass_metrics.get("smoothed_bpm")
bpm_times = pass_metrics.get("bpm_times")
if smoothed_bpm is not None and bpm_times is not None and len(bpm_times) == len(smoothed_bpm) and len(bpm_times) > 0:
csv_path = os.path.join(self.output_directory, f"{base_name}{file_suffix}.csv")
csv_bpm_header = (
"BPM (Pass 2)"
if output_suffix == "_pass2"
else "BPM (Pass 3)"
if output_suffix == "_pass3"
else "Average BPM"
)
try:
with open(csv_path, "w", newline="", encoding="utf-8") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["Time (s)", csv_bpm_header])
for t, bpm in zip(np.asarray(bpm_times, dtype=float), np.asarray(smoothed_bpm, dtype=float)):
if not np.isnan(bpm):
writer.writerow([f"{t:.3f}", f"{bpm:.3f}"])
logging.info(f"BPM plot data saved to {csv_path}")
except Exception as e:
logging.error(f"Failed to write BPM plot CSV: {e}")
else:
logging.info("Skipping CSV generation as requested.")
return self.fig
def plot_pass1_save(
self,
audio_envelope: np.ndarray,
anchor_beats: np.ndarray,
output_options: Optional[Dict] = None,
output_html_path: Optional[str] = None,
pass1_analysis_data: Optional[Dict] = None,
pass1_bpm_data: Optional[Dict] = None,
):
"""
Builds and saves the pass 1 plot: envelope, anchor beats, BPM scatter + curve (canonical, same as algorithm), and BPM Trend (Belief).
pass1_bpm_data: dict from compute_pass1_bpm_curve: raw_scatter_* (instant BPM), scatter_* (outlier-filtered), curve_* (Gaussian smoothing on filtered).
"""
self.time_axis_sec = np.arange(len(audio_envelope), dtype=float) / self.sample_rate
self.audio_duration_sec = float(self.time_axis_sec[-1]) if len(self.time_axis_sec) > 0 else 0.0
base_name = self.output_stem
if output_html_path is None:
output_html_path = os.path.join(self.output_directory, f"{base_name}_pass1.html")
html_requested = True if output_options is None else output_options.get("html", True)
if not html_requested:
logging.info("Skipping pass 1 HTML as requested.")
return
self.spectrogram_enabled = False
fig = make_subplots(specs=[[{"secondary_y": True}]])
factor = self.params.get("plot_downsample_factor", 5)
n = len(audio_envelope)
if factor > 1 and n >= factor:
plot_secs = np.arange(0, n, factor, dtype=np.float64) / self.sample_rate
plot_envelope = audio_envelope[::factor]
else:
plot_secs = np.arange(n, dtype=np.float64) / self.sample_rate
plot_envelope = audio_envelope
plot_time = _elapsed_seconds_to_plot_datetimes(plot_secs)
use_nr_main = (pass1_analysis_data or {}).get("noise_removed_envelope") is not None
main_env_name = "Noise Removed Envelope" if use_nr_main else "Bandpass Envelope"
fig.add_trace(
go.Scatter(x=plot_time, y=plot_envelope, name=main_env_name, line=dict(color="#47a5c4")),
secondary_y=False,
)
bp_pass1 = (pass1_analysis_data or {}).get("bandpass_envelope")
if (
use_nr_main
and bp_pass1 is not None
and isinstance(bp_pass1, np.ndarray)
and len(bp_pass1) == n
):
plot_bp = bp_pass1[::factor] if factor > 1 and n >= factor else bp_pass1
fig.add_trace(
go.Scatter(
x=plot_time,
y=plot_bp,
name="Bandpass Envelope",
line=dict(color="#3498db", width=1.25, dash="dot"),
visible="legendonly",
hovertemplate="Bandpass Envelope: %{y:.4f}<extra></extra>",
),
secondary_y=False,
)
inv_env = (pass1_analysis_data or {}).get("inverse_band_envelope")
if inv_env is not None and isinstance(inv_env, np.ndarray) and len(inv_env) == n:
plot_inv = inv_env[::factor] if factor > 1 and n >= factor else inv_env
fig.add_trace(
go.Scatter(
x=plot_time,
y=plot_inv,
name="Noise Envelope",
line=dict(color="#b85c9e", width=1.25),
visible="legendonly",
hovertemplate="Noise Envelope: %{y:.4f}<extra></extra>",
),
secondary_y=False,
)
nr_env = (pass1_analysis_data or {}).get("noise_removed_envelope")
if (
not use_nr_main
and nr_env is not None
and isinstance(nr_env, np.ndarray)
and len(nr_env) == n
):
plot_nr = nr_env[::factor] if factor > 1 and n >= factor else nr_env
fig.add_trace(
go.Scatter(
x=plot_time,
y=plot_nr,
name="Noise Removed Envelope",
line=dict(color="#e67e22", width=1.25),
visible="legendonly",
hovertemplate="Noise Removed Envelope: %{y:.4f}<extra></extra>",
),
secondary_y=False,
)
if len(anchor_beats) > 0:
in_bounds = (anchor_beats >= 0) & (anchor_beats < len(audio_envelope))
ab = anchor_beats[in_bounds]
if len(ab) > 0:
anchor_times_sec = ab.astype(np.float64) / self.sample_rate
anchor_times_dt = _elapsed_seconds_to_plot_datetimes(anchor_times_sec)
y_at_beats = np.asarray(audio_envelope)[ab]
fig.add_trace(
go.Scatter(
x=anchor_times_dt,
y=y_at_beats,
name="Anchor beats",
mode="markers",
marker=dict(symbol="diamond", size=8, color="orange"),
),
secondary_y=False,
)
# Pass 1 instant BPM: raw 60/RR, then local median±MAD in time window, then global median±MAD (pass1_bpm_global_outlier_mad_k; <=0 skips)
if pass1_bpm_data and "raw_scatter_times" in pass1_bpm_data and "raw_scatter_bpm" in pass1_bpm_data:
rt = pass1_bpm_data["raw_scatter_times"]
rb = pass1_bpm_data["raw_scatter_bpm"]
if len(rt) > 0 and len(rt) == len(rb):
raw_dt = _elapsed_seconds_to_plot_datetimes(np.asarray(rt, dtype=np.float64))
fig.add_trace(
go.Scatter(
x=raw_dt,
y=rb,
name="Instant BPM (Pass 1)",
mode="markers",
marker=dict(size=6, color="#e74c3c", symbol="circle"),
visible="legendonly",
),
secondary_y=True,
)
self.bpm_axis_center = float(np.median(rb))
if pass1_bpm_data and "scatter_times" in pass1_bpm_data and "scatter_bpm" in pass1_bpm_data:
st = pass1_bpm_data["scatter_times"]
sb = pass1_bpm_data["scatter_bpm"]
if len(st) > 0 and len(st) == len(sb):
scatter_dt = _elapsed_seconds_to_plot_datetimes(np.asarray(st, dtype=np.float64))
fig.add_trace(
go.Scatter(
x=scatter_dt,
y=sb,
name="Instant BPM (Pass 1) outliers removed",
mode="markers",
marker=dict(size=6, color="#9b59b6", symbol="circle-open"),
),
secondary_y=True,
)
self.bpm_axis_center = float(np.median(sb))
if pass1_bpm_data and "curve_times" in pass1_bpm_data and "curve_bpm" in pass1_bpm_data:
ct = pass1_bpm_data["curve_times"]
cb = pass1_bpm_data["curve_bpm"]
if len(ct) > 0 and len(ct) == len(cb):
curve_dt = _elapsed_seconds_to_plot_datetimes(np.asarray(ct, dtype=np.float64))
fig.add_trace(
go.Scatter(
x=curve_dt,
y=cb,
name="BPM (pass 1)",
mode="lines",
line=dict(color="orange", width=2),
),
secondary_y=True,
)
has_pass1_bpm_markers = pass1_bpm_data and (
("raw_scatter_bpm" in pass1_bpm_data and len(pass1_bpm_data["raw_scatter_bpm"]) > 0)
or ("scatter_bpm" in pass1_bpm_data and len(pass1_bpm_data["scatter_bpm"]) > 0)
)
if not has_pass1_bpm_markers:
self.bpm_axis_center = float(self.params.get("default_bpm_axis_center", self.bpm_axis_center))
# BPM Trend (Belief) (canonical: dense raster at STANDARD_DT_SEC).
if pass1_analysis_data and "pass2_lt_bpm_times" in pass1_analysis_data and "pass2_lt_bpm" in pass1_analysis_data:
lt_times = np.asarray(pass1_analysis_data["pass2_lt_bpm_times"], dtype=np.float64)
lt_vals = np.asarray(pass1_analysis_data["pass2_lt_bpm"], dtype=np.float64)
if len(lt_times) >= 2 and len(lt_times) == len(lt_vals):
lt_times_dt = _elapsed_seconds_to_plot_datetimes(lt_times)
fig.add_trace(
go.Scatter(
x=lt_times_dt,
y=lt_vals,
name="BPM Trend (Belief)",
mode="lines",
line=dict(color="orange", width=2),
visible="legendonly",
),
secondary_y=True,
)
self.fig = fig
self._configure_layout()
plot_title = f"Pass 1 - {os.path.basename(self.file_name)}"
plot_config = {
"scrollZoom": True,
"toImageButtonOptions": {"filename": plot_title, "format": "png", "scale": 2},
"showTips": False,
}
plotly_html = self.fig.to_html(config=plot_config, full_html=False, include_plotlyjs="cdn")
# If CDN is unavailable, fall back to a local plotly.min.js beside the HTML (if present).
plotly_html = re.sub(
r'<script\s+src="(https://cdn\.plot\.ly/plotly[^"]+)"\s*></script>',
r'<script src="\1" onerror="this.onerror=null;this.src=\'plotly.min.js\';"></script>',
plotly_html,
count=1,
)
self._noise_event_segments = (pass1_analysis_data or {}).get("noise_event_segments") or []
self._pass3_state_boundaries = []
self._pass3_state_boundaries_before = []
custom_html = self._generate_custom_html(
plotly_html, plot_title, base_name, output_options=output_options
)
with open(output_html_path, "w", encoding="utf-8") as f:
f.write(custom_html)
logging.info(f"Preliminary pass plot saved to {output_html_path}")
self.fig = make_subplots(specs=[[{"secondary_y": True}]])
def _prepare_bpm_axis_center(self, pass_metrics: Dict):
"""Use detected BPM stats to keep the BPM axis centered without altering the per-file zoom."""
hrv_summary = pass_metrics.get("hrv_summary") or {}
avg_bpm = hrv_summary.get("avg_bpm")
smoothed_bpm = pass_metrics.get("smoothed_bpm")
if avg_bpm is None and smoothed_bpm is not None and len(smoothed_bpm) > 0:
avg_bpm = float(np.nanmean(np.asarray(smoothed_bpm, dtype=float)))
if avg_bpm is None:
avg_bpm = float(self.params.get("default_bpm_axis_center", self.bpm_axis_center))
self.bpm_axis_center = float(avg_bpm)
def _configure_layout(self):
"""Sets up the plot layout, titles, and axes with custom x-axis tick labels."""
self.fig.update_layout(
template="plotly_dark",
dragmode="pan",
legend=dict(orientation="h", yanchor="bottom", y=1, xanchor="right", x=1),
margin=dict(t=90, b=30, l=40, r=00), # borders/margins
hovermode="x unified",
autosize=True,
uirevision="layout-stable",
)
duration_sec = float(self.time_axis_sec[-1])
tick_interval_sec = 30
tick_positions_sec = np.arange(0, duration_sec + 1e-6, tick_interval_sec, dtype=float)
if tick_positions_sec.size > 0 and tick_positions_sec[-1] < duration_sec:
tick_positions_sec = np.append(tick_positions_sec, duration_sec)
tickvals = _elapsed_seconds_to_plot_datetimes(tick_positions_sec)
ticktext = [f"{int(s // 60):02d}:{int(s % 60):02d} ({s:.2f})" for s in tick_positions_sec]
self.fig.update_xaxes(
title_text="Time",
tickvals=tickvals,
ticktext=ticktext,
hoverformat="%M:%S.%L",
automargin=False,
title_standoff=4,
domain=[0, 0.95],
)
# Use the audio envelope trace, if present, to scale the amplitude axis.
robust_upper_limit = 1
if self.fig.data:
envelope_values = None
for trace in self.fig.data:
tname = getattr(trace, "name", "")
if tname in ("Bandpass Envelope", "Noise Removed Envelope") and hasattr(trace, "y"):
try:
envelope_values = np.asarray(trace.y, dtype=float)
except Exception:
envelope_values = None
break
if envelope_values is not None and envelope_values.size > 0:
robust_upper_limit = float(np.quantile(envelope_values, 0.95))
amplitude_scale = self.params.get("plot_amplitude_scale_factor", 60.0)
self.fig.update_yaxes(
title_text="Signal Amplitude",
secondary_y=False,
range=[0, robust_upper_limit * amplitude_scale],
showgrid=False,
automargin=False,
title_standoff=4,
)
half_span = self.bpm_axis_span / 2.0
min_bpm = max(self.bpm_axis_center - half_span, 5)
max_bpm = self.bpm_axis_center + half_span
self.fig.update_yaxes(
title_text="BPM / HRV",
secondary_y=True,
range=[min_bpm, max_bpm],
autorange=False,
automargin=False,
title_standoff=0,
)
if getattr(self, "_has_systolic_traces", False):
self.fig.update_layout(
yaxis3=dict(
title="Phase Interval (s)",
overlaying="y",
anchor="free",
side="right",
position=0.97,
range=[0.1, 0.45],
showgrid=False,
automargin=False,
title_standoff=0,
),
)
def _add_line_traces(
self,
audio_envelope: np.ndarray,
analysis_data: Dict,
all_raw_peaks: Optional[np.ndarray] = None,
):
"""Adds audio envelope and noise floor traces. Downsampling (plot_downsample_factor) applies only here
to these large arrays; contractility, BPM, HRV and markers are never downsampled.
Note: Do not use dashed lines (dash=...) for line traces--they cause noticeable lag in the plot."""
if getattr(self, "skip_detailed_debug_traces", False):
logging.info("Skipping audio envelope and noise floor traces for long file (optimization enabled).")
return
plot_envelope = audio_envelope
plot_noise_floor = analysis_data.get("dynamic_noise_floor_series")
# Downsample only envelope and noise floor for performance; other traces (contractility, BPM, HRV) use full data
factor = self.params.get("plot_downsample_factor", 5)
n = len(audio_envelope)
if factor > 1 and n >= factor:
logging.info(f"Downsampling envelope and noise floor by factor {factor} for plotting.")
plot_secs = np.arange(0, n, factor, dtype=np.float64) / self.sample_rate
plot_time_axis_dt = _elapsed_seconds_to_plot_datetimes(plot_secs)
plot_envelope = audio_envelope[::factor]
if plot_noise_floor is not None and not plot_noise_floor.empty:
plot_noise_floor = plot_noise_floor.iloc[::factor]
else:
plot_secs = np.arange(n, dtype=np.float64) / self.sample_rate
plot_time_axis_dt = _elapsed_seconds_to_plot_datetimes(plot_secs)
use_nr_main = analysis_data.get("noise_removed_envelope") is not None
main_env_name = "Noise Removed Envelope" if use_nr_main else "Bandpass Envelope"
self.fig.add_trace(
go.Scatter(x=plot_time_axis_dt, y=plot_envelope, name=main_env_name, line=dict(color="#47a5c4")),
secondary_y=False,
)
bp_adata = analysis_data.get("bandpass_envelope")
if (
use_nr_main
and bp_adata is not None
and isinstance(bp_adata, np.ndarray)
and len(bp_adata) == n
):
plot_bp = bp_adata[::factor] if factor > 1 and n >= factor else bp_adata
self.fig.add_trace(
go.Scatter(
x=plot_time_axis_dt,
y=plot_bp,
name="Bandpass Envelope",
line=dict(color="#3498db", width=1.25, dash="dot"),
visible="legendonly",
hovertemplate="Bandpass Envelope: %{y:.4f}<extra></extra>",
),
secondary_y=False,
)
if (
plot_noise_floor is not None
and not plot_noise_floor.empty
and len(plot_noise_floor) >= len(plot_time_axis_dt)
):
self.fig.add_trace(
go.Scatter(
x=plot_time_axis_dt,
y=plot_noise_floor.values,
name="Dynamic Noise Floor",
line=dict(color="green", width=1.5),
hovertemplate="Noise Floor: %{y:.4f}<extra></extra>",
visible="legendonly",
),
secondary_y=False,
)
inv_env = analysis_data.get("inverse_band_envelope")
if inv_env is not None and isinstance(inv_env, np.ndarray) and len(inv_env) == n:
plot_inv = inv_env[::factor] if factor > 1 and n >= factor else inv_env
self.fig.add_trace(
go.Scatter(
x=plot_time_axis_dt,
y=plot_inv,
name="Noise Envelope",
line=dict(color="#b85c9e", width=1.25),
visible="legendonly",
hovertemplate="Noise Envelope: %{y:.4f}<extra></extra>",
),
secondary_y=False,
)
nr_env = analysis_data.get("noise_removed_envelope")
if (
not use_nr_main
and nr_env is not None
and isinstance(nr_env, np.ndarray)
and len(nr_env) == n
):
plot_nr = nr_env[::factor] if factor > 1 and n >= factor else nr_env
self.fig.add_trace(
go.Scatter(
x=plot_time_axis_dt,
y=plot_nr,
name="Noise Removed Envelope",
line=dict(color="#e67e22", width=1.25),
visible="legendonly",
hovertemplate="Noise Removed Envelope: %{y:.4f}<extra></extra>",
),
secondary_y=False,
)
def _add_trough_markers(self, audio_envelope: np.ndarray, analysis_data: Dict):
"""Adds trough markers to the plot using original full-resolution data for accuracy."""
if getattr(self, "skip_detailed_debug_traces", False):
logging.info("Skipping trough markers for long file (optimization enabled).")
return
trough_indices = analysis_data.get("trough_indices")
if trough_indices is not None and trough_indices.size > 0:
trough_times_dt = _elapsed_seconds_to_plot_datetimes(
np.asarray(trough_indices, dtype=np.float64) / self.sample_rate
)
self.fig.add_trace(
go.Scatter(
x=trough_times_dt,
y=audio_envelope[trough_indices],
mode="markers",
name="Troughs",
marker=dict(color="green", symbol="circle-open", size=6),
visible="legendonly",
),
secondary_y=False,
)
def _add_peak_marker_trace(
self, indices, customdata, name, color, symbol, size, audio_envelope, hovertemplate
):
"""Add a single Scatter trace for peak markers (S1, S2, or Noise)."""
times_dt = _elapsed_seconds_to_plot_datetimes(
np.asarray(indices, dtype=np.float64) / self.sample_rate
)
self.fig.add_trace(
go.Scatter(
x=times_dt,
y=audio_envelope[indices],
mode="markers",
name=name,
marker=dict(color=color, symbol=symbol, size=size),
customdata=customdata,
hovertemplate=hovertemplate,
),
secondary_y=False,
)
def _add_peak_traces(self, all_raw_peaks, debug_info, audio_envelope, trough_indices=None):
"""Adds S1, S2, and Noise peak markers to the plot with detailed hover info."""
if getattr(self, "skip_detailed_debug_traces", False):
logging.info("Skipping S1/S2/Noise peak markers for long file (optimization enabled).")