From a0fb1224ba216c4ce3624d8a75aa94cfe1d4e8e0 Mon Sep 17 00:00:00 2001 From: Boyonabike Date: Wed, 2 Dec 2026 16:25:31 +0000 Subject: [PATCH 1/4] rmssd gate: let the breathing exemption see a low-heart-rate night At a resting HR in the low 40s, ordinary breathing puts the lag-1 ACF of successive differences near cos 2*pi*f (about -0.37 to -0.45), past the -0.35 jitter floor. The spectral exemption exists for that night but needs 20 unbroken 64-beat segments, and the strict 20% ectopic filter, strap dropouts and 5-min window edges leave a WHOOP 4 night with 3-17. sleepSessionRmssdDetail judges the floor on its contributing windows as one stream (still the strict 20% filter) and lets the exemption read that stream through a 30% filter for length. ACF1 stays strict so admitted ectopic pairs cannot lift white noise over the floor. nocturnalRmssd reads its contributing windows as one stream for the exemption too. Published values and thresholds are unchanged; only which nights abstain changes. hrv.freq moves to counter 3. --- CHANGELOG.md | 25 ++++ lib/src/onehz/clinical/hrv_time.dart | 73 ++++++++-- lib/src/onehz/registry/group_registry.dart | 2 +- test/algo_version_test.dart | 6 +- test/onehz/low_hr_rmssd_gate_test.dart | 156 +++++++++++++++++++++ 5 files changed, 245 insertions(+), 17 deletions(-) create mode 100644 test/onehz/low_hr_rmssd_gate_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 1185ae2..39fefc3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -68,6 +68,31 @@ - `Calories.hourlyRollup` — hourly sums of covered minutes with per-hour coverage; an hour with no covered minute is null, not zero. +### Let the breathing exemption see a low-heart-rate night + +Breathing at f cycles/beat puts the lag-1 ACF of successive differences near +cos 2πf, so at a resting HR in the low 40s ordinary breathing reads −0.37 to +−0.45, past the −0.35 jitter floor. The spectral exemption exists for that +night but needs 20 unbroken 64-beat segments, and on a WHOOP 4 night the +strict 20% ectopic filter, strap dropouts and the 5-min window edges cut the +stream into runs of 5–10 beats (3–17 segments). Measured on six real nights at +HR 43–46: all six were refused; each now publishes 108–131 ms against a Garmin +reading of 116–130 ms for the same nights. + +`sleepSessionRmssdDetail` now judges the jitter floor on the contributing +windows read as one stream, still through the strict 20% filter, and the +spectral exemption reads that stream through a 30% filter +(`kGateEctopicThreshold`) for its length. Each window's own clearance check +uses the 30% stream for its spectrum as well. ACF1 stays on the strict stream +on purpose: an ectopic pair the 30% filter admits lifts ACF1 over the floor +and would pass white noise outright. `nocturnalRmssd` reads its contributing +windows as one stream for the exemption too. The published RMSSD values and +every threshold (floor, noise-share ceiling, 20 segments, 20% value filter) +are unchanged; only which nights abstain changes. On 144 synthetic nights at +55–75 bpm every value is identical, and white-noise nights with up to 3% +ectopic pairs and 2% missed beats are still refused at 42, 55 and 75 bpm. +`hrv.freq` moves to counter 3. + ### Review input and gap validity HRV time, nocturnal and session RMSSD abstain on non-finite NN intervals before diff --git a/lib/src/onehz/clinical/hrv_time.dart b/lib/src/onehz/clinical/hrv_time.dart index b98f6cf..bcdfa75 100644 --- a/lib/src/onehz/clinical/hrv_time.dart +++ b/lib/src/onehz/clinical/hrv_time.dart @@ -148,17 +148,18 @@ bool _onCoarseLattice(List> diffRuns, double msd) => /// The one RMSSD jitter verdict every path shares: ACF1 below the floor AND /// the spectrum does not show a respiratory line on a low white floor. bool _jitterRefused(double? acf1, List> runs, - {int minSegments = 20}) { + {int minSegments = 20, List>? shareRuns}) { if (acf1 == null || acf1 >= kNnDiffAcf1Floor) return false; - final share = nnDiffNoiseShare(runs, minSegments: minSegments); + final share = nnDiffNoiseShare(shareRuns ?? runs, minSegments: minSegments); return share == null || share >= kNnDiffNoiseShareCeiling; } /// One 5-min window judged on its own: a measured ACF1 at or above the floor, /// or its own spectral line (4 segments is what a window at HR ~40 holds). -bool _windowClears(List> runs) { +bool _windowClears(List> runs, [List>? shareRuns]) { final a = nnDiffAcf1(runs); - return a != null && !_jitterRefused(a, runs, minSegments: 4); + return a != null && + !_jitterRefused(a, runs, minSegments: 4, shareRuns: shareRuns); } /// The window RMSSDs a headline may use. A night that cleared the floor @@ -168,11 +169,11 @@ bool _windowClears(List> runs) { /// loud breathing windows carry the pooled share. There every window has to /// clear the gate itself. List _clearedWindows(double? nightAcf1, List rmssds, - List>> winRuns) { + List>> winRuns, [List>>? winShareRuns]) { if (nightAcf1 == null || nightAcf1 >= kNnDiffAcf1Floor) return rmssds; return [ for (var i = 0; i < rmssds.length; i++) - if (_windowClears(winRuns[i])) rmssds[i] + if (_windowClears(winRuns[i], winShareRuns?[i])) rmssds[i] ]; } @@ -236,8 +237,10 @@ List? _steadyBreathingWindows( bool refused, List rmssds, List>> winRuns, - List meanRrMs) { - final kept = refused ? const [] : _clearedWindows(acf1, rmssds, winRuns); + List meanRrMs, [List>>? winShareRuns]) { + final kept = refused + ? const [] + : _clearedWindows(acf1, rmssds, winRuns, winShareRuns); if (kept.isNotEmpty) return (rmssds: kept, byBreathing: false, note: ''); if (acf1 == null || acf1 >= kNnDiffAcf1Floor) return null; final idx = _steadyBreathingWindows(winRuns, meanRrMs); @@ -625,6 +628,7 @@ Metric nocturnalRmssd( // calmest-looking windows while the night pooled to −0.43/−0.51. final runs = >[]; final perWindow = >>[]; + final keptIdx = []; // beats of the windows that contributed, in order final meanRr = []; final indices = buckets.keys.toList()..sort(); for (final idx in indices) { @@ -669,11 +673,28 @@ Metric nocturnalRmssd( if (nd < minBeatsPerWindow) continue; runs.addAll(winRuns); perWindow.add(winRuns); + keptIdx.addAll(seg); meanRr.add(mean([for (final i in seg) nnMs[i]])!); rmssds.add(math.sqrt(ssd / nd)); } + // The spectral exemption reads the contributing windows as one stream, not + // re-cut at every 5-min edge (see [sleepSessionRmssdDetail]); ACF1 stays on + // the per-window runs. Same seam rule, so a skipped window's hole still + // breaks the run. + final shareRuns = >[]; + var sRun = []; + for (var k = 1; k < keptIdx.length; k++) { + final i = keptIdx[k], p = keptIdx[k - 1]; + if (nnTimesMs[i] - nnTimesMs[p] > nnMs[i] + 0.5) { + if (sRun.isNotEmpty) shareRuns.add(sRun); + sRun = []; + continue; + } + sRun.add(nnMs[i] - nnMs[p]); + } + if (sRun.isNotEmpty) shareRuns.add(sRun); final acf1 = nnDiffAcf1(runs); - final refused = _jitterRefused(acf1, runs); + final refused = _jitterRefused(acf1, runs, shareRuns: shareRuns); if (rmssds.isEmpty && !refused) { return const Metric.absent( tier: Tier.high, @@ -724,6 +745,7 @@ Metric nocturnalRmssd( /// A floor, not a weight: weighting by n would weight by HEART RATE, letting /// high-HR, low-RMSSD REM/arousal windows pull the mean down. const int kMinDiffsPerRmssdWindow = 20; +const double kGateEctopicThreshold = 0.30; /// The nightly headline RMSSD plus the diagnostics a `Metric` cannot /// carry. Present only when the headline is. @@ -889,6 +911,8 @@ Metric sleepSessionRmssdDetail( final rmssds = []; final runs = >[]; // pooled jitter floor — see [nocturnalRmssd] final perWindow = >>[]; + final perWindowShare = >>[]; + final keptRr = [], keptTs = []; // windows that contributed final meanRr = []; var overCountedWindows = 0; var thinWindows = 0; @@ -937,8 +961,15 @@ Metric sleepSessionRmssdDetail( thinWindows++; continue; } - runs.addAll(diffRuns); + final gateRuns = [ + for (final r in _cleanWindowRuns(buckets[idx]!, bucketsTs[idx]!, + threshold: kGateEctopicThreshold)) + if (r.length >= 2) [for (var i = 1; i < r.length; i++) r[i] - r[i - 1]] + ]; perWindow.add(diffRuns); + perWindowShare.add(gateRuns); + keptRr.addAll(winRr); + keptTs.addAll(winTs); meanRr.add(mean([for (final r in rrRuns) ...r])!); rmssds.add(math.sqrt(ssd / nd)); } @@ -957,8 +988,21 @@ Metric sleepSessionRmssdDetail( // THE HEADLINE nightly RMSSD (→ ln_rmssd → readiness). When the differences // are noise, the honest output is no headline, not a plausible one — the // readiness composite already treats a null HRV driver as absent. + // Gate evidence over the contributing windows as one stream, not re-cut at + // every 5-min edge: a seam the heart did not make costs the Welch test a + // 64-beat segment. A dropped window leaves a time gap, which the cleaner's + // seam check breaks the run on, so its beats never reach the verdict. + // ACF1 stays on the strict (20%) stream: an ectopic pair the lenient + // cleaner admits lifts ACF1 over the floor and would pass noise outright. + // Only the spectral exemption reads the lenient stream, for its length. + List> diffsOf(double thr) => [ + for (final r in _cleanWindowRuns(keptRr, keptTs, threshold: thr)) + if (r.length >= 2) [for (var i = 1; i < r.length; i++) r[i] - r[i - 1]] + ]; + runs.addAll(diffsOf(0.20)); + final shareRuns = diffsOf(kGateEctopicThreshold); final acf1 = nnDiffAcf1(runs); - final refused = _jitterRefused(acf1, runs); + final refused = _jitterRefused(acf1, runs, shareRuns: shareRuns); if (rmssds.isEmpty && !refused) { return Metric.absent( tier: Tier.high, @@ -966,7 +1010,8 @@ Metric sleepSessionRmssdDetail( note: 'no valid 5-min windows for sleep-session RMSSD$dropped', ); } - final kept = _keptWindows(acf1, refused, rmssds, perWindow, meanRr); + final kept = + _keptWindows(acf1, refused, rmssds, perWindow, meanRr, perWindowShare); if (kept == null) { return Metric.absent( tier: Tier.high, @@ -1024,9 +1069,9 @@ Metric sleepSessionRmssdDetail( /// all — the tolerance is `nn[i] + 1000.0`, not `nocturnalRmssd`'s `+ 0.5` /// (which assumes sub-second beat times), so quantization alone never trips /// it while an actual multi-second-or-longer dropout still does. -List> _cleanWindowRuns(List rr, List ts) { +List> _cleanWindowRuns(List rr, List ts, + {double threshold = 0.20}) { const radius = 2; - const threshold = 0.20; // Range filter first, keeping each survivor's position in [rr] — BOTH filters // break a run, so neither one's compaction can manufacture a difference. final nn = []; diff --git a/lib/src/onehz/registry/group_registry.dart b/lib/src/onehz/registry/group_registry.dart index 52887ea..a24b1da 100644 --- a/lib/src/onehz/registry/group_registry.dart +++ b/lib/src/onehz/registry/group_registry.dart @@ -190,7 +190,7 @@ const GroupRegistry kAnalyticsGroupRegistry = GroupRegistry(1, [ GroupDecl( id: 'hrv.freq', kind: GroupKind.algorithm, - counter: 2, + counter: 3, // 3: low-HR RMSSD gate reads an unbroken stream (abstention) members: ['hrvFreq'], api: [ 'nightHrvShape', diff --git a/test/algo_version_test.dart b/test/algo_version_test.dart index 1e7d53b..455e1b0 100644 --- a/test/algo_version_test.dart +++ b/test/algo_version_test.dart @@ -4,7 +4,7 @@ import 'package:openstrap_analytics/onehz.dart'; import 'package:test/test.dart'; void main() { - test('PR output changes move their owning groups to counter 2', () { + test('PR output changes move their owning groups past counter 1', () { const changed = { 'found.core', // Lomb-Scargle first-sample origin. 'found.rr_correction', // Artifact-run cap, already bumped. @@ -14,8 +14,10 @@ void main() { 'night.rhythm', // Cosinor/circadian and gap-aware irregular screening. 'activity.load', // TRIMP, CTL/ATL and time-in-zone aggregation. }; + // Moved again since: hrv.freq to 3 (low-HR RMSSD gate abstention). + const since = {'hrv.freq': 3}; expect({for (final g in kAnalyticsGroupRegistry.groups) if (g.counter != 1) g.id: g.counter}, - {for (final id in changed) id: 2}); + {for (final id in changed) id: since[id] ?? 2}); }); } diff --git a/test/onehz/low_hr_rmssd_gate_test.dart b/test/onehz/low_hr_rmssd_gate_test.dart new file mode 100644 index 0000000..1c29b76 --- /dev/null +++ b/test/onehz/low_hr_rmssd_gate_test.dart @@ -0,0 +1,156 @@ +// The jitter gate at low resting heart rate. +// +// Breathing at f cycles/beat puts the lag-1 ACF of the successive differences +// at about cos 2πf. At 46 bpm and 15 breaths/min, f ≈ 0.33 and ACF1 ≈ −0.45: +// past kNnDiffAcf1Floor with no jitter at all. The spectral exemption exists for +// that night, but it needs 20 unbroken 64-beat segments, and a strap that drops +// ~5% of beats, read through the strict ectopic filter and re-cut at every 5-min +// window edge, never hands it 20. These nights pin that the exemption can now +// see a real breathing night, and that the longer stream it reads does not let +// a noise night through, with or without stray beats in it. +import 'dart:math' as math; + +import 'package:openstrap_analytics/onehz.dart'; +import 'package:test/test.dart'; + +double _gauss(math.Random r) => + math.sqrt(-2 * math.log(r.nextDouble() + 1e-12)) * + math.cos(2 * math.pi * r.nextDouble()); + +const _startSec = 1796100000; +const _durSec = 7 * 3600; + +/// A 7 h night. [rsaMs] is the breathing swing (0 = none), [noiseMs] white +/// jitter on every beat, [drop] the share of beats the strap never delivers. +/// [ectopic] beats become a 0.7×/1.3× premature + compensatory pair, [missed] +/// beats merge into the next (a missed detection). +({List rr, List ts}) _night({ + required double hr, + required int seed, + double breathsPerMin = 15, + double rsaMs = 0, + double noiseMs = 5, + bool lfWander = true, + double drop = 0, + double ectopic = 0, + double missed = 0, +}) { + final r = math.Random(seed); + final rr = [], ts = []; + final meanRr = 60000 / hr; + var t = _startSec * 1000.0, phase = 0.0, br = breathsPerMin, amp = rsaMs; + var lf = 0.0; + double? pending; + while (t < (_startSec + _durSec) * 1000.0) { + final p0 = phase; + phase += 2 * math.pi * (br / 60) * (meanRr / 1000); + if ((phase / (2 * math.pi)).floor() != (p0 / (2 * math.pi)).floor()) { + br = (breathsPerMin + _gauss(r) * 2).clamp(6, 24).toDouble(); + amp = rsaMs * (1 + _gauss(r) * .25); + } + if (lfWander) lf = lf * 0.97 + _gauss(r) * 8; + var v = meanRr + amp * math.sin(phase) + lf + _gauss(r) * noiseMs; + if (pending != null) { + v += pending; + pending = null; + } + final u = r.nextDouble(); + final beats = []; + if (u < ectopic) { + beats.addAll([v * 0.7, v * 1.3]); + } else if (u < ectopic + missed) { + pending = v; + continue; + } else { + beats.add(v); + } + for (final b in beats) { + t += b; + if (r.nextDouble() >= drop) { + rr.add(b); + ts.add(t); + } + } + } + return (rr: rr, ts: ts); +} + +Metric _nocturnal(({List rr, List ts}) n) { + final c = correctRr(n.rr, rrTsMs: n.ts); + final t0 = n.ts.first; + return nocturnalRmssd(c.nn, [for (final t in c.nnTimesMs) t + t0]); +} + +void main() { + group('sleep-session RMSSD at low resting HR', () { + // 46 bpm, 15 breaths/min (f ≈ 0.33, ACF1 ≈ −0.45), 3% of beats dropped. + // Fixed fixtures: main refuses all three, so they pin the longer gate + // stream. Seed 0 of the same setting is refused by both (a dropout run + // leaves it under 20 segments) and is not pinned. Synthetic beats rarely + // trip the strict ectopic filter, which is what fragmented the real + // WHOOP 4 nights this was found on, so these understate the effect there. + for (final seed in [1, 2, 3]) { + test('46 bpm, 15 breaths/min, 3% dropped beats publishes (seed $seed)', + () { + final n = _night( + hr: 46, seed: seed, breathsPerMin: 15, rsaMs: 130, drop: 0.03); + final m = sleepSessionRmssdDetail(n.rr, n.ts, + startSec: _startSec, endSec: _startSec + _durSec); + expect(m.present, isTrue, reason: m.note); + // Through the breathing line, not by ACF1 clearing the floor. + expect(m.value!.diffAcf1!, lessThan(kNnDiffAcf1Floor)); + // A 130 ms swing at f ≈ 0.33: RMSSD ≈ 130·√2·sin(πf) ≈ 159 ms. + expect(m.value!.rmssd, inInclusiveRange(130, 180)); + }); + } + }); + + group('the longer stream still refuses noise', () { + final cases = { + 'clean': (ect: 0, miss: 0), + '1% ectopic pairs + 1% missed': (ect: 0.01, miss: 0.01), + '3% ectopic pairs + 2% missed': (ect: 0.03, miss: 0.02), + }; + for (final hr in [42.0, 55.0, 75.0]) { + for (final noise in [20.0, 60.0]) { + cases.forEach((label, art) { + for (final drop in [0.0, 0.05]) { + test('white ${noise.toInt()} ms at ${hr.toInt()} bpm, $label, ' + 'drop $drop', () { + final n = _night( + hr: hr, + seed: 0, + noiseMs: noise, + lfWander: false, + drop: drop, + ectopic: art.ect, + missed: art.miss); + final m = sleepSessionWindowedRmssd(n.rr, n.ts, + startSec: _startSec, endSec: _startSec + _durSec); + expect(m.present, isFalse, + reason: 'published ${m.value} from white noise'); + final nr = _nocturnal(n); + expect(nr.present, isFalse, + reason: 'nocturnalRmssd published ${nr.value} from white noise'); + }); + } + }); + } + } + }); + + group('typical heart rates are untouched', () { + // Nights that cleared the floor before any of this pass straight through + // and publish from the strict stream, as they always did. + for (final hr in [60.0, 75.0]) { + test('$hr bpm, 1% ectopic + 1% missed, 5% dropped', () { + final n = _night( + hr: hr, seed: 1, rsaMs: 40, drop: 0.05, ectopic: 0.01, missed: 0.01); + final m = sleepSessionRmssdDetail(n.rr, n.ts, + startSec: _startSec, endSec: _startSec + _durSec); + expect(m.present, isTrue, reason: m.note); + expect(m.value!.diffAcf1!, greaterThanOrEqualTo(kNnDiffAcf1Floor)); + }); + } + }); +} From 315e53ed1e9996a5ef2e6d629890f3c1b2b5d821 Mon Sep 17 00:00:00 2001 From: Boyonabike Date: Wed, 2 Dec 2026 16:48:02 +0000 Subject: [PATCH 2/4] rmssd gate: make the low-HR change a second look after a refusal The first version re-judged every night on the whole-night stream and let each window's clearance read the 30 % stream. Against main that changed the headline of 25 of 41 low-HR synthetic nights main already published (by -3.7..+3.8 ms) and, with misplaced beats, refused a night main published. Now the existing per-window verdict runs unchanged, and only a night it refuses is judged again on its contributing windows as one stream (ACF1 on the strict 20 % stream, noise share on the 30 % one). By construction no published value changes; only some refused nights publish. The six real nights keep the same values (108-131 ms). kGateEctopicThreshold is documented as an ESTIMATE next to the code and in ALGORITHMS.md, with Hirsch & Bishop 1981 added to the references. tool/rmssd_gate_corpus.dart reproduces the synthetic evidence (332 seeded nights; diff its output on main and on this branch), and the tests use its generator, including a misplaced-beat night that imitates what fragmented the real nights. Nights main publishes are pinned to main's values. --- ALGORITHMS.md | 5 +- CHANGELOG.md | 44 +++--- lib/src/onehz/clinical/hrv_time.dart | 100 ++++++------- test/onehz/low_hr_rmssd_gate_test.dart | 189 +++++++++++-------------- tool/rmssd_gate_corpus.dart | 167 ++++++++++++++++++++++ 5 files changed, 323 insertions(+), 182 deletions(-) create mode 100644 tool/rmssd_gate_corpus.dart diff --git a/ALGORITHMS.md b/ALGORITHMS.md index 7de6b20..baebea3 100644 --- a/ALGORITHMS.md +++ b/ALGORITHMS.md @@ -56,8 +56,8 @@ Grouped by family (subdirectory under `lib/src/onehz/`). File paths are relative | Function | File | Method | Citation | |---|---|---|---| | `hrvTime` | `clinical/hrv_time.dart` | RMSSD/SDNN/pNNx | Task Force 1996 | -| `nocturnalRmssd` | `clinical/hrv_time.dart` | median-of-5-min-window nightly RMSSD | — | -| `sleepSessionWindowedRmssd` / `sleepSessionRmssdDetail` | `clinical/hrv_time.dart` | mean-of-5-min-window RMSSD; windows need ≥ 20 clean successive differences (ultra-short RMSSD literature); Malik 20 % ectopic rejection | Malik et al.; Munoz et al. 2015; Baek et al. 2015 | +| `nocturnalRmssd` | `clinical/hrv_time.dart` | median-of-5-min-window nightly RMSSD; the jitter gate's spectral exemption reads the contributing windows as one stream | — | +| `sleepSessionWindowedRmssd` / `sleepSessionRmssdDetail` | `clinical/hrv_time.dart` | mean-of-5-min-window RMSSD; windows need ≥ 20 clean successive differences (ultra-short RMSSD literature); Malik 20 % ectopic rejection; the jitter gate's ACF1 reads the contributing windows as one 20 % stream and its spectral exemption the same stream through a 30 % filter (`kGateEctopicThreshold`, ESTIMATE: an engineering choice so the exemption can reach a low-HR night) | Malik et al.; Munoz et al. 2015; Baek et al. 2015; Hirsch & Bishop 1981 | | `rrCoverage` | `clinical/hrv_time.dart` | Σ plausible RR ÷ wall-clock span; > 1.10 means duplicated or interleaved beats, and `hrvTime` / `nocturnalRmssd` / `nightHrvShape` / the sleep-session headline refuse RMSSD; the headline also drops any 5-min window holding more beat-time than its length | — (integrity check; contiguous runs measure 0.963–1.001) | | `hrvFreq` | `clinical/hrv_freq.dart` | LF/HF via Lomb-Scargle periodogram on native (unevenly-sampled) beat times | Laguna, Moody & Mark 1998; Bigger 1992 | | `decelerationCapacity` / `accelerationCapacity` | `clinical/prsa.dart` | Phase-rectified signal averaging (DC/AC) | Bauer et al. 2006 | @@ -205,6 +205,7 @@ Malik et al. References added for the methods above: +- Hirsch, J. A., Bishop, B. (1981). Respiratory sinus arrhythmia in humans: how breathing pattern modulates heart rate. American Journal of Physiology 241(4):H620-H629. - Welford, B. P. (1962). Note on a method for calculating corrected sums of squares and products. Technometrics 4(3):419-420. - Chan, T. F., Golub, G. H., LeVeque, R. J. (1983). Algorithms for computing the sample variance: analysis and recommendations. The American Statistician 37(3):242-247. - Hyndman, R. J., Fan, Y. (1996). Sample quantiles in statistical packages. The American Statistician 50(4):361-365. diff --git a/CHANGELOG.md b/CHANGELOG.md index 39fefc3..5354c97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -68,30 +68,30 @@ - `Calories.hourlyRollup` — hourly sums of covered minutes with per-hour coverage; an hour with no covered minute is null, not zero. -### Let the breathing exemption see a low-heart-rate night +### Give a refused low-heart-rate night a second look Breathing at f cycles/beat puts the lag-1 ACF of successive differences near -cos 2πf, so at a resting HR in the low 40s ordinary breathing reads −0.37 to -−0.45, past the −0.35 jitter floor. The spectral exemption exists for that -night but needs 20 unbroken 64-beat segments, and on a WHOOP 4 night the -strict 20% ectopic filter, strap dropouts and the 5-min window edges cut the -stream into runs of 5–10 beats (3–17 segments). Measured on six real nights at -HR 43–46: all six were refused; each now publishes 108–131 ms against a Garmin -reading of 116–130 ms for the same nights. - -`sleepSessionRmssdDetail` now judges the jitter floor on the contributing -windows read as one stream, still through the strict 20% filter, and the -spectral exemption reads that stream through a 30% filter -(`kGateEctopicThreshold`) for its length. Each window's own clearance check -uses the 30% stream for its spectrum as well. ACF1 stays on the strict stream -on purpose: an ectopic pair the 30% filter admits lifts ACF1 over the floor -and would pass white noise outright. `nocturnalRmssd` reads its contributing -windows as one stream for the exemption too. The published RMSSD values and -every threshold (floor, noise-share ceiling, 20 segments, 20% value filter) -are unchanged; only which nights abstain changes. On 144 synthetic nights at -55–75 bpm every value is identical, and white-noise nights with up to 3% -ectopic pairs and 2% missed beats are still refused at 42, 55 and 75 bpm. -`hrv.freq` moves to counter 3. +cos 2πf (Hirsch & Bishop 1981 for the respiratory sinus arrhythmia behind +it), so at a resting HR in the low 40s ordinary breathing reads past the +−0.35 jitter floor. The spectral exemption exists for that night but needs 20 +unbroken 64-beat segments, and on a WHOOP 4 night the strict 20 % ectopic +filter, strap dropouts and the 5-min window edges cut the stream into runs +with a median of 6–11 beats (3–14 segments). On six real nights at HR 43–47 +every headline was refused; each now publishes 108–131 ms, against Garmin +readings of 116–130 ms for the same nights. + +When the existing verdict refuses, `sleepSessionRmssdDetail` and +`nocturnalRmssd` now judge the contributing windows again as one stream. ACF1 +is taken on the strict 20 % stream; only the session headline's noise share +reads a 30 % stream (`kGateEctopicThreshold`, ESTIMATE: an engineering choice, +not a published value), because a 30 % ACF1 lets an ectopic pair lift white +noise over the floor. The second look never runs for a night the existing +verdict passes, so no published value changes: only some refused nights +publish. RMSSD values and every threshold are unchanged. `tool/rmssd_gate_corpus.dart` +reproduces the synthetic evidence: against main, 332 nights (typical HR, +white noise with ectopic and missed beats, low HR, misplaced beats) show no +night lost and no value changed, 3 headlines and 1 `nocturnalRmssd` gained, +and all 108 noise nights still refused. `hrv.freq` moves to counter 3. ### Review input and gap validity diff --git a/lib/src/onehz/clinical/hrv_time.dart b/lib/src/onehz/clinical/hrv_time.dart index bcdfa75..411f035 100644 --- a/lib/src/onehz/clinical/hrv_time.dart +++ b/lib/src/onehz/clinical/hrv_time.dart @@ -154,12 +154,21 @@ bool _jitterRefused(double? acf1, List> runs, return share == null || share >= kNnDiffNoiseShareCeiling; } +/// A second look for a night the per-window verdict refused: the same +/// contributing beats read as ONE stream, not re-cut at every 5-min edge, so +/// the spectral exemption can find its 20 segments on a low-HR night (see +/// [kGateEctopicThreshold]). ACF1 is judged on [strictRuns]; only the noise +/// share reads [shareRuns]. Called only when the first verdict refused, so a +/// night that publishes today publishes the same value. +bool _wholeStreamRefused( + List> strictRuns, List> shareRuns) => + _jitterRefused(nnDiffAcf1(strictRuns), strictRuns, shareRuns: shareRuns); + /// One 5-min window judged on its own: a measured ACF1 at or above the floor, /// or its own spectral line (4 segments is what a window at HR ~40 holds). -bool _windowClears(List> runs, [List>? shareRuns]) { +bool _windowClears(List> runs) { final a = nnDiffAcf1(runs); - return a != null && - !_jitterRefused(a, runs, minSegments: 4, shareRuns: shareRuns); + return a != null && !_jitterRefused(a, runs, minSegments: 4); } /// The window RMSSDs a headline may use. A night that cleared the floor @@ -169,11 +178,11 @@ bool _windowClears(List> runs, [List>? shareRuns]) { /// loud breathing windows carry the pooled share. There every window has to /// clear the gate itself. List _clearedWindows(double? nightAcf1, List rmssds, - List>> winRuns, [List>>? winShareRuns]) { + List>> winRuns) { if (nightAcf1 == null || nightAcf1 >= kNnDiffAcf1Floor) return rmssds; return [ for (var i = 0; i < rmssds.length; i++) - if (_windowClears(winRuns[i], winShareRuns?[i])) rmssds[i] + if (_windowClears(winRuns[i])) rmssds[i] ]; } @@ -237,10 +246,8 @@ List? _steadyBreathingWindows( bool refused, List rmssds, List>> winRuns, - List meanRrMs, [List>>? winShareRuns]) { - final kept = refused - ? const [] - : _clearedWindows(acf1, rmssds, winRuns, winShareRuns); + List meanRrMs) { + final kept = refused ? const [] : _clearedWindows(acf1, rmssds, winRuns); if (kept.isNotEmpty) return (rmssds: kept, byBreathing: false, note: ''); if (acf1 == null || acf1 >= kNnDiffAcf1Floor) return null; final idx = _steadyBreathingWindows(winRuns, meanRrMs); @@ -677,24 +684,24 @@ Metric nocturnalRmssd( meanRr.add(mean([for (final i in seg) nnMs[i]])!); rmssds.add(math.sqrt(ssd / nd)); } - // The spectral exemption reads the contributing windows as one stream, not - // re-cut at every 5-min edge (see [sleepSessionRmssdDetail]); ACF1 stays on - // the per-window runs. Same seam rule, so a skipped window's hole still - // breaks the run. - final shareRuns = >[]; - var sRun = []; - for (var k = 1; k < keptIdx.length; k++) { - final i = keptIdx[k], p = keptIdx[k - 1]; - if (nnTimesMs[i] - nnTimesMs[p] > nnMs[i] + 0.5) { - if (sRun.isNotEmpty) shareRuns.add(sRun); - sRun = []; - continue; + final acf1 = nnDiffAcf1(runs); + var refused = _jitterRefused(acf1, runs); + if (refused) { + // The NN here is already corrected upstream; same seam rule as above. + final whole = >[]; + var run = []; + for (var k = 1; k < keptIdx.length; k++) { + final i = keptIdx[k], p = keptIdx[k - 1]; + if (nnTimesMs[i] - nnTimesMs[p] > nnMs[i] + 0.5) { + if (run.isNotEmpty) whole.add(run); + run = []; + continue; + } + run.add(nnMs[i] - nnMs[p]); } - sRun.add(nnMs[i] - nnMs[p]); + if (run.isNotEmpty) whole.add(run); + refused = _wholeStreamRefused(whole, whole); } - if (sRun.isNotEmpty) shareRuns.add(sRun); - final acf1 = nnDiffAcf1(runs); - final refused = _jitterRefused(acf1, runs, shareRuns: shareRuns); if (rmssds.isEmpty && !refused) { return const Metric.absent( tier: Tier.high, @@ -745,6 +752,16 @@ Metric nocturnalRmssd( /// A floor, not a weight: weighting by n would weight by HEART RATE, letting /// high-HR, low-RMSSD REM/arousal windows pull the mean down. const int kMinDiffsPerRmssdWindow = 20; + +/// Ectopic threshold for the stream the second look's spectral exemption reads +/// (never the RMSSD values, which keep Malik's 20 %, and never ACF1). ESTIMATE: +/// an engineering choice, not a published value. At a resting HR in the low +/// 40s, respiratory sinus arrhythmia (Hirsch & Bishop 1981) is large next to +/// the RR interval and the 20 % rule cuts the stream at beats a breath +/// produced: on six WHOOP 4 nights at HR 43–47 it rejected 1,067–2,867 beats a +/// night and left the exemption 3–14 of the 20 segments it needs; 30 % left +/// 21–46. ACF1 stays on the 20 % stream because an ectopic pair this admits +/// lifts ACF1 over the floor and would pass white noise. const double kGateEctopicThreshold = 0.30; /// The nightly headline RMSSD plus the diagnostics a `Metric` cannot @@ -911,7 +928,6 @@ Metric sleepSessionRmssdDetail( final rmssds = []; final runs = >[]; // pooled jitter floor — see [nocturnalRmssd] final perWindow = >>[]; - final perWindowShare = >>[]; final keptRr = [], keptTs = []; // windows that contributed final meanRr = []; var overCountedWindows = 0; @@ -961,13 +977,8 @@ Metric sleepSessionRmssdDetail( thinWindows++; continue; } - final gateRuns = [ - for (final r in _cleanWindowRuns(buckets[idx]!, bucketsTs[idx]!, - threshold: kGateEctopicThreshold)) - if (r.length >= 2) [for (var i = 1; i < r.length; i++) r[i] - r[i - 1]] - ]; + runs.addAll(diffRuns); perWindow.add(diffRuns); - perWindowShare.add(gateRuns); keptRr.addAll(winRr); keptTs.addAll(winTs); meanRr.add(mean([for (final r in rrRuns) ...r])!); @@ -988,21 +999,15 @@ Metric sleepSessionRmssdDetail( // THE HEADLINE nightly RMSSD (→ ln_rmssd → readiness). When the differences // are noise, the honest output is no headline, not a plausible one — the // readiness composite already treats a null HRV driver as absent. - // Gate evidence over the contributing windows as one stream, not re-cut at - // every 5-min edge: a seam the heart did not make costs the Welch test a - // 64-beat segment. A dropped window leaves a time gap, which the cleaner's - // seam check breaks the run on, so its beats never reach the verdict. - // ACF1 stays on the strict (20%) stream: an ectopic pair the lenient - // cleaner admits lifts ACF1 over the floor and would pass noise outright. - // Only the spectral exemption reads the lenient stream, for its length. - List> diffsOf(double thr) => [ - for (final r in _cleanWindowRuns(keptRr, keptTs, threshold: thr)) - if (r.length >= 2) [for (var i = 1; i < r.length; i++) r[i] - r[i - 1]] - ]; - runs.addAll(diffsOf(0.20)); - final shareRuns = diffsOf(kGateEctopicThreshold); final acf1 = nnDiffAcf1(runs); - final refused = _jitterRefused(acf1, runs, shareRuns: shareRuns); + var refused = _jitterRefused(acf1, runs); + if (refused) { + List> diffsOf(double threshold) => [ + for (final r in _cleanWindowRuns(keptRr, keptTs, threshold: threshold)) + if (r.length >= 2) [for (var i = 1; i < r.length; i++) r[i] - r[i - 1]] + ]; + refused = _wholeStreamRefused(diffsOf(0.20), diffsOf(kGateEctopicThreshold)); + } if (rmssds.isEmpty && !refused) { return Metric.absent( tier: Tier.high, @@ -1010,8 +1015,7 @@ Metric sleepSessionRmssdDetail( note: 'no valid 5-min windows for sleep-session RMSSD$dropped', ); } - final kept = - _keptWindows(acf1, refused, rmssds, perWindow, meanRr, perWindowShare); + final kept = _keptWindows(acf1, refused, rmssds, perWindow, meanRr); if (kept == null) { return Metric.absent( tier: Tier.high, diff --git a/test/onehz/low_hr_rmssd_gate_test.dart b/test/onehz/low_hr_rmssd_gate_test.dart index 1c29b76..46132d9 100644 --- a/test/onehz/low_hr_rmssd_gate_test.dart +++ b/test/onehz/low_hr_rmssd_gate_test.dart @@ -1,79 +1,23 @@ // The jitter gate at low resting heart rate. // // Breathing at f cycles/beat puts the lag-1 ACF of the successive differences -// at about cos 2πf. At 46 bpm and 15 breaths/min, f ≈ 0.33 and ACF1 ≈ −0.45: -// past kNnDiffAcf1Floor with no jitter at all. The spectral exemption exists for -// that night, but it needs 20 unbroken 64-beat segments, and a strap that drops -// ~5% of beats, read through the strict ectopic filter and re-cut at every 5-min -// window edge, never hands it 20. These nights pin that the exemption can now -// see a real breathing night, and that the longer stream it reads does not let -// a noise night through, with or without stray beats in it. -import 'dart:math' as math; - +// near cos 2πf: at ~14–15 breaths/min and 42–46 bpm, f ≈ 0.31–0.36 and ACF1 is +// past kNnDiffAcf1Floor with no jitter at all. The spectral exemption exists +// for that night but needs 20 unbroken 64-beat segments; beats an optical +// sensor places 15–28 % early or late trip the 20 % ectopic filter, and with +// dropouts and the 5-min window edges the stream never holds 20. A refused +// night now gets a second look at its contributing beats as one stream. +// +// The nights come from tool/rmssd_gate_corpus.dart (seeded). The pinned +// values were produced by main at b92686a. import 'package:openstrap_analytics/onehz.dart'; import 'package:test/test.dart'; -double _gauss(math.Random r) => - math.sqrt(-2 * math.log(r.nextDouble() + 1e-12)) * - math.cos(2 * math.pi * r.nextDouble()); +import '../../tool/rmssd_gate_corpus.dart'; -const _startSec = 1796100000; -const _durSec = 7 * 3600; - -/// A 7 h night. [rsaMs] is the breathing swing (0 = none), [noiseMs] white -/// jitter on every beat, [drop] the share of beats the strap never delivers. -/// [ectopic] beats become a 0.7×/1.3× premature + compensatory pair, [missed] -/// beats merge into the next (a missed detection). -({List rr, List ts}) _night({ - required double hr, - required int seed, - double breathsPerMin = 15, - double rsaMs = 0, - double noiseMs = 5, - bool lfWander = true, - double drop = 0, - double ectopic = 0, - double missed = 0, -}) { - final r = math.Random(seed); - final rr = [], ts = []; - final meanRr = 60000 / hr; - var t = _startSec * 1000.0, phase = 0.0, br = breathsPerMin, amp = rsaMs; - var lf = 0.0; - double? pending; - while (t < (_startSec + _durSec) * 1000.0) { - final p0 = phase; - phase += 2 * math.pi * (br / 60) * (meanRr / 1000); - if ((phase / (2 * math.pi)).floor() != (p0 / (2 * math.pi)).floor()) { - br = (breathsPerMin + _gauss(r) * 2).clamp(6, 24).toDouble(); - amp = rsaMs * (1 + _gauss(r) * .25); - } - if (lfWander) lf = lf * 0.97 + _gauss(r) * 8; - var v = meanRr + amp * math.sin(phase) + lf + _gauss(r) * noiseMs; - if (pending != null) { - v += pending; - pending = null; - } - final u = r.nextDouble(); - final beats = []; - if (u < ectopic) { - beats.addAll([v * 0.7, v * 1.3]); - } else if (u < ectopic + missed) { - pending = v; - continue; - } else { - beats.add(v); - } - for (final b in beats) { - t += b; - if (r.nextDouble() >= drop) { - rr.add(b); - ts.add(t); - } - } - } - return (rr: rr, ts: ts); -} +Metric _session(({List rr, List ts}) n) => + sleepSessionRmssdDetail(n.rr, n.ts, + startSec: gateStartSec, endSec: gateStartSec + gateDurSec); Metric _nocturnal(({List rr, List ts}) n) { final c = correctRr(n.rr, rrTsMs: n.ts); @@ -82,72 +26,97 @@ Metric _nocturnal(({List rr, List ts}) n) { } void main() { - group('sleep-session RMSSD at low resting HR', () { - // 46 bpm, 15 breaths/min (f ≈ 0.33, ACF1 ≈ −0.45), 3% of beats dropped. - // Fixed fixtures: main refuses all three, so they pin the longer gate - // stream. Seed 0 of the same setting is refused by both (a dropout run - // leaves it under 20 segments) and is not pinned. Synthetic beats rarely - // trip the strict ectopic filter, which is what fragmented the real - // WHOOP 4 nights this was found on, so these understate the effect there. - for (final seed in [1, 2, 3]) { - test('46 bpm, 15 breaths/min, 3% dropped beats publishes (seed $seed)', - () { - final n = _night( - hr: 46, seed: seed, breathsPerMin: 15, rsaMs: 130, drop: 0.03); - final m = sleepSessionRmssdDetail(n.rr, n.ts, - startSec: _startSec, endSec: _startSec + _durSec); + group('a refused low-HR night gets a second look', () { + // main refuses all of these. + final cases = { + '44 bpm, 4 % misplaced, 3 % dropped (seed 1)': + (hr: 44, p: 0.04, drop: 0.03, seed: 1), + '44 bpm, 4 % misplaced, 3 % dropped (seed 2)': + (hr: 44, p: 0.04, drop: 0.03, seed: 2), + '46 bpm, 8 % misplaced, 1 % dropped (seed 3)': + (hr: 46, p: 0.08, drop: 0.01, seed: 3), + }; + cases.forEach((label, c) { + test('session headline publishes: $label', () { + final m = _session(gateNight( + hr: c.hr, seed: c.seed, rsaMs: 110, drop: c.drop, misplaced: c.p)); expect(m.present, isTrue, reason: m.note); // Through the breathing line, not by ACF1 clearing the floor. expect(m.value!.diffAcf1!, lessThan(kNnDiffAcf1Floor)); - // A 130 ms swing at f ≈ 0.33: RMSSD ≈ 130·√2·sin(πf) ≈ 159 ms. - expect(m.value!.rmssd, inInclusiveRange(130, 180)); + // A 110 ms swing at f ≈ 0.33: RMSSD ≈ 110·√2·sin(πf) ≈ 135 ms. + expect(m.value!.rmssd, inInclusiveRange(115, 150)); }); - } + }); + + test('nocturnalRmssd publishes: 44 bpm, 4 % misplaced, 3 % dropped (seed 0)', + () { + final m = _nocturnal(gateNight( + hr: 44, seed: 0, rsaMs: 110, drop: 0.03, misplaced: 0.04)); + expect(m.present, isTrue, reason: m.note); + }); }); - group('the longer stream still refuses noise', () { - final cases = { - 'clean': (ect: 0, miss: 0), - '1% ectopic pairs + 1% missed': (ect: 0.01, miss: 0.01), - '3% ectopic pairs + 2% missed': (ect: 0.03, miss: 0.02), + group('a night main already publishes keeps its value', () { + // The second look runs only after a refusal, so a night that cleared the + // gate before is untouched, including one that cleared it through the + // spectral exemption. + final pinned = rr, List ts}), double, double)>{ + '44 bpm, 4 % misplaced, 1 % dropped (seed 0)': ( + gateNight(hr: 44, seed: 0, rsaMs: 110, drop: 0.01, misplaced: 0.04), + 130.6, 150.5), + '44 bpm, 4 % misplaced, 1 % dropped (seed 2)': ( + gateNight(hr: 44, seed: 2, rsaMs: 110, drop: 0.01, misplaced: 0.04), + 129.2, 149.1), + '46 bpm, 15 breaths/min, 1 % dropped (seed 0)': ( + gateNight(hr: 46, seed: 0, breathsPerMin: 15, rsaMs: 130, drop: 0.01), + 152.6, 158.2), }; + pinned.forEach((label, p) { + test(label, () { + final (night, session, nocturnal) = p; + final s = _session(night); + expect(s.present, isTrue, reason: s.note); + expect(s.value!.diffAcf1!, lessThan(kNnDiffAcf1Floor)); + expect(s.value!.rmssd, closeTo(session, 0.05)); + expect(_nocturnal(night).value, closeTo(nocturnal, 0.05)); + }); + }); + }); + + group('the second look still refuses noise', () { + const artifacts = [(0.0, 0.0), (0.01, 0.01), (0.03, 0.02)]; for (final hr in [42.0, 55.0, 75.0]) { for (final noise in [20.0, 60.0]) { - cases.forEach((label, art) { + for (final (ect, miss) in artifacts) { for (final drop in [0.0, 0.05]) { - test('white ${noise.toInt()} ms at ${hr.toInt()} bpm, $label, ' - 'drop $drop', () { - final n = _night( + test('white ${noise.toInt()} ms at ${hr.toInt()} bpm, ' + 'ectopic $ect + missed $miss, drop $drop', () { + final n = gateNight( hr: hr, seed: 0, noiseMs: noise, lfWander: false, drop: drop, - ectopic: art.ect, - missed: art.miss); - final m = sleepSessionWindowedRmssd(n.rr, n.ts, - startSec: _startSec, endSec: _startSec + _durSec); - expect(m.present, isFalse, - reason: 'published ${m.value} from white noise'); + ectopic: ect, + missed: miss); + final s = _session(n); + expect(s.present, isFalse, + reason: 'published ${s.value?.rmssd} from white noise'); final nr = _nocturnal(n); expect(nr.present, isFalse, reason: 'nocturnalRmssd published ${nr.value} from white noise'); }); } - }); + } } } }); - group('typical heart rates are untouched', () { - // Nights that cleared the floor before any of this pass straight through - // and publish from the strict stream, as they always did. + group('typical heart rates clear the floor outright', () { for (final hr in [60.0, 75.0]) { - test('$hr bpm, 1% ectopic + 1% missed, 5% dropped', () { - final n = _night( - hr: hr, seed: 1, rsaMs: 40, drop: 0.05, ectopic: 0.01, missed: 0.01); - final m = sleepSessionRmssdDetail(n.rr, n.ts, - startSec: _startSec, endSec: _startSec + _durSec); + test('$hr bpm, 1 % ectopic + 1 % missed, 5 % dropped', () { + final m = _session(gateNight( + hr: hr, seed: 1, rsaMs: 40, drop: 0.05, ectopic: 0.01, missed: 0.01)); expect(m.present, isTrue, reason: m.note); expect(m.value!.diffAcf1!, greaterThanOrEqualTo(kNnDiffAcf1Floor)); }); diff --git a/tool/rmssd_gate_corpus.dart b/tool/rmssd_gate_corpus.dart new file mode 100644 index 0000000..695c250 --- /dev/null +++ b/tool/rmssd_gate_corpus.dart @@ -0,0 +1,167 @@ +// Measurement tool, not a test: the synthetic corpora behind the low-HR RMSSD +// gate change. Seeded, no I/O except print. Run it on main and on the branch +// and diff the output: +// +// dart run tool/rmssd_gate_corpus.dart > /tmp/gate_branch.txt +// git stash / switch to main, run again > /tmp/gate_main.txt +// diff /tmp/gate_main.txt /tmp/gate_branch.txt +// +// One line per night: corpus, parameters, then the sleep-session headline +// (`sleepSessionWindowedRmssd`) and `nocturnalRmssd` (on `correctRr` output), +// each as a value in ms or ABSENT. A summary per corpus closes the output. +// +// typical : HR 55/60/65/75, RSA 25/50 ms, 0/5 % dropped beats, no / 1+1 % / +// 3+2 % ectopic pairs + missed beats, 3 seeds (144 nights) +// noise : white RR jitter 20/60 ms with no breathing or slow wander, HR +// 42/55/75, the same dropout and artifact grid, 3 seeds (108 nights) +// lowhr : HR 42/46, 14/15 breaths/min, RSA 130 ms, 1/2/3 % dropped, 4 seeds +// misplaced: HR 44/46, 14 breaths/min, RSA 110 ms, 4/8 % of beats detected +// 15–28 % early or late, 1/3 % dropped, 4 seeds +// +// Clean synthetic beats rarely trip the strict 20 % ectopic filter, which is +// what fragmented the real WHOOP 4 nights this was found on; `misplaced` +// imitates that, `lowhr` does not. +import 'dart:math' as math; + +import 'package:openstrap_analytics/onehz.dart'; + +double _gauss(math.Random r) => + math.sqrt(-2 * math.log(r.nextDouble() + 1e-12)) * + math.cos(2 * math.pi * r.nextDouble()); + +const gateStartSec = 1796100000; +const gateDurSec = 7 * 3600; + +({List rr, List ts}) gateNight({ + required double hr, + required int seed, + double breathsPerMin = 14, + double rsaMs = 0, + double noiseMs = 5, + bool lfWander = true, + double drop = 0, + double ectopic = 0, + double missed = 0, + double misplaced = 0, +}) { + final r = math.Random(seed); + final rr = [], ts = []; + final meanRr = 60000 / hr; + var t = gateStartSec * 1000.0, phase = 0.0, br = breathsPerMin, amp = rsaMs; + var lf = 0.0; + double? pending; + var carry = 0.0; + while (t < (gateStartSec + gateDurSec) * 1000.0) { + final p0 = phase; + phase += 2 * math.pi * (br / 60) * (meanRr / 1000); + if ((phase / (2 * math.pi)).floor() != (p0 / (2 * math.pi)).floor()) { + br = (breathsPerMin + _gauss(r) * 2).clamp(6, 24).toDouble(); + amp = rsaMs * (1 + _gauss(r) * .25); + } + if (lfWander) lf = lf * 0.97 + _gauss(r) * 8; + var v = meanRr + amp * math.sin(phase) + lf + _gauss(r) * noiseMs; + if (pending != null) { + v += pending; + pending = null; + } + // A beat detected 15–28 % of the interval early or late; the next + // interval absorbs the shift, as optical beat detection does. + v -= carry; + carry = 0; + if (misplaced > 0 && r.nextDouble() < misplaced) { + carry = (0.15 + 0.13 * r.nextDouble()) * v * (r.nextBool() ? 1 : -1); + v += carry; + } + final u = r.nextDouble(); + final beats = []; + if (u < ectopic) { + beats.addAll([v * 0.7, v * 1.3]); + } else if (u < ectopic + missed) { + pending = v; + continue; + } else { + beats.add(v); + } + for (final b in beats) { + t += b; + if (r.nextDouble() >= drop) { + rr.add(b); + ts.add(t); + } + } + } + return (rr: rr, ts: ts); +} + +String _fmt(Metric m) => + m.present ? m.value!.toStringAsFixed(1) : 'ABSENT'; + +void main() { + final summary = >{}; // corpus -> [nights, session, nocturnal] + void night(String corpus, String label, ({List rr, List ts}) n) { + final s = sleepSessionWindowedRmssd(n.rr, n.ts, + startSec: gateStartSec, endSec: gateStartSec + gateDurSec); + final c = correctRr(n.rr, rrTsMs: n.ts); + final t0 = n.ts.first; + final noc = nocturnalRmssd(c.nn, [for (final t in c.nnTimesMs) t + t0]); + print('$corpus $label session=${_fmt(s)} nocturnal=${_fmt(noc)}'); + final tally = summary.putIfAbsent(corpus, () => [0, 0, 0]); + tally[0]++; + if (s.present) tally[1]++; + if (noc.present) tally[2]++; + } + + const artifacts = [(0.0, 0.0), (0.01, 0.01), (0.03, 0.02)]; + for (final hr in [55.0, 60.0, 65.0, 75.0]) { + for (final rsa in [25.0, 50.0]) { + for (final drop in [0.0, 0.05]) { + for (final (ect, miss) in artifacts) { + for (var seed = 0; seed < 3; seed++) { + night('typical', + 'hr=$hr rsa=$rsa drop=$drop ect=$ect miss=$miss seed=$seed', + gateNight(hr: hr, seed: seed, rsaMs: rsa, drop: drop, + ectopic: ect, missed: miss)); + } + } + } + } + } + for (final hr in [42.0, 55.0, 75.0]) { + for (final noise in [20.0, 60.0]) { + for (final drop in [0.0, 0.05]) { + for (final (ect, miss) in artifacts) { + for (var seed = 0; seed < 3; seed++) { + night('noise', + 'hr=$hr white=$noise drop=$drop ect=$ect miss=$miss seed=$seed', + gateNight(hr: hr, seed: seed, noiseMs: noise, lfWander: false, + drop: drop, ectopic: ect, missed: miss)); + } + } + } + } + } + for (final hr in [42.0, 46.0]) { + for (final br in [14.0, 15.0]) { + for (final drop in [0.01, 0.02, 0.03]) { + for (var seed = 0; seed < 4; seed++) { + night('lowhr', 'hr=$hr br=$br drop=$drop seed=$seed', + gateNight(hr: hr, seed: seed, breathsPerMin: br, rsaMs: 130, + drop: drop)); + } + } + } + } + for (final hr in [44.0, 46.0]) { + for (final p in [0.04, 0.08]) { + for (final drop in [0.01, 0.03]) { + for (var seed = 0; seed < 4; seed++) { + night('misplaced', 'hr=$hr misplaced=$p drop=$drop seed=$seed', + gateNight(hr: hr, seed: seed, rsaMs: 110, drop: drop, + misplaced: p)); + } + } + } + } + summary.forEach((corpus, t) => print( + '# $corpus: ${t[0]} nights, session published ${t[1]}, nocturnal published ${t[2]}')); +} From 5e09654354a09b2832d71005b92636813dcaf6cb Mon Sep 17 00:00:00 2001 From: Boyonabike Date: Wed, 2 Dec 2026 21:17:59 +0000 Subject: [PATCH 3/4] rmssd gate: bump sleep.stage too; don't clean across a dropped window AdvancedSleepStager._sessionAvgHRV reads sleepSessionWindowedRmssd, so the second look changes the stager's avgHrv. sleep.stage does not list hrv.freq in its deps, so the hrv.freq bump never reached it: sleep.stage moves to 3. The session second look concatenated every contributing window before the radius-2 median cleaner, so beats either side of a dropped window were each other's neighbours. The stream is now kept as one segment per run of adjacent contributing windows and each segment is cleaned on its own; it is still one stream within a run, so the 5-min edges are not re-cut. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++- lib/src/onehz/clinical/hrv_time.dart | 21 ++++++++++++++++----- lib/src/onehz/registry/group_registry.dart | 2 +- test/algo_version_test.dart | 5 +++-- 4 files changed, 22 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5354c97..b8f3733 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -91,7 +91,8 @@ publish. RMSSD values and every threshold are unchanged. `tool/rmssd_gate_corpus reproduces the synthetic evidence: against main, 332 nights (typical HR, white noise with ectopic and missed beats, low HR, misplaced beats) show no night lost and no value changed, 3 headlines and 1 `nocturnalRmssd` gained, -and all 108 noise nights still refused. `hrv.freq` moves to counter 3. +and all 108 noise nights still refused. `hrv.freq` moves to counter 3, and +`sleep.stage` with it: the stager's session average HRV reads the same gate. ### Review input and gap validity diff --git a/lib/src/onehz/clinical/hrv_time.dart b/lib/src/onehz/clinical/hrv_time.dart index 411f035..6a6800c 100644 --- a/lib/src/onehz/clinical/hrv_time.dart +++ b/lib/src/onehz/clinical/hrv_time.dart @@ -928,7 +928,11 @@ Metric sleepSessionRmssdDetail( final rmssds = []; final runs = >[]; // pooled jitter floor — see [nocturnalRmssd] final perWindow = >>[]; - final keptRr = [], keptTs = []; // windows that contributed + // Beats of the windows that contributed, one segment per run of ADJACENT + // contributing windows: a dropped window between two leaves a gap the + // cleaner's median neighbourhood must not reach across. + final keptRr = >[], keptTs = >[]; + int? lastKept; final meanRr = []; var overCountedWindows = 0; var thinWindows = 0; @@ -979,8 +983,13 @@ Metric sleepSessionRmssdDetail( } runs.addAll(diffRuns); perWindow.add(diffRuns); - keptRr.addAll(winRr); - keptTs.addAll(winTs); + if (lastKept == null || idx != lastKept + 1) { + keptRr.add([]); + keptTs.add([]); + } + keptRr.last.addAll(winRr); + keptTs.last.addAll(winTs); + lastKept = idx; meanRr.add(mean([for (final r in rrRuns) ...r])!); rmssds.add(math.sqrt(ssd / nd)); } @@ -1003,8 +1012,10 @@ Metric sleepSessionRmssdDetail( var refused = _jitterRefused(acf1, runs); if (refused) { List> diffsOf(double threshold) => [ - for (final r in _cleanWindowRuns(keptRr, keptTs, threshold: threshold)) - if (r.length >= 2) [for (var i = 1; i < r.length; i++) r[i] - r[i - 1]] + for (var g = 0; g < keptRr.length; g++) + for (final r + in _cleanWindowRuns(keptRr[g], keptTs[g], threshold: threshold)) + if (r.length >= 2) [for (var i = 1; i < r.length; i++) r[i] - r[i - 1]] ]; refused = _wholeStreamRefused(diffsOf(0.20), diffsOf(kGateEctopicThreshold)); } diff --git a/lib/src/onehz/registry/group_registry.dart b/lib/src/onehz/registry/group_registry.dart index a24b1da..7f84e4c 100644 --- a/lib/src/onehz/registry/group_registry.dart +++ b/lib/src/onehz/registry/group_registry.dart @@ -137,7 +137,7 @@ const GroupRegistry kAnalyticsGroupRegistry = GroupRegistry(1, [ GroupDecl( id: 'sleep.stage', kind: GroupKind.algorithm, - counter: 2, + counter: 3, // 3: session avgHrv follows the low-HR RMSSD gate's second look members: ['segmentSleep', 'stageMinuteRanges', 'cardioStager'], api: [ 'resetCardioObservations', diff --git a/test/algo_version_test.dart b/test/algo_version_test.dart index 455e1b0..5232fdf 100644 --- a/test/algo_version_test.dart +++ b/test/algo_version_test.dart @@ -14,8 +14,9 @@ void main() { 'night.rhythm', // Cosinor/circadian and gap-aware irregular screening. 'activity.load', // TRIMP, CTL/ATL and time-in-zone aggregation. }; - // Moved again since: hrv.freq to 3 (low-HR RMSSD gate abstention). - const since = {'hrv.freq': 3}; + // Moved again since: hrv.freq and sleep.stage to 3 (low-HR RMSSD gate + // abstention; sleep.stage's session avgHrv reads the same gate). + const since = {'hrv.freq': 3, 'sleep.stage': 3}; expect({for (final g in kAnalyticsGroupRegistry.groups) if (g.counter != 1) g.id: g.counter}, {for (final id in changed) id: since[id] ?? 2}); From a39d6a7b3bc47e5681e85164611861fe317bf30f Mon Sep 17 00:00:00 2001 From: Boyonabike Date: Wed, 2 Dec 2026 21:40:37 +0000 Subject: [PATCH 4/4] rmssd gate: second look only for a night main's path leaves blank A refused night can still publish on main through the steady-breathing fallback. The second look ran for every refused night, so such a night could pass it and publish from _clearedWindows instead: a different window set and confidence, against "no published value changes". The second look now runs only when main's _keptWindows returns nothing, and main's result is reused otherwise. tool/rmssd_gate_corpus.dart output is identical to the previous head; against main it still only turns ABSENT into values (3 headlines, 1 nocturnal). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +++--- lib/src/onehz/clinical/hrv_time.dart | 20 ++++++++++++++++---- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b8f3733..a6f4ee9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -85,9 +85,9 @@ When the existing verdict refuses, `sleepSessionRmssdDetail` and is taken on the strict 20 % stream; only the session headline's noise share reads a 30 % stream (`kGateEctopicThreshold`, ESTIMATE: an engineering choice, not a published value), because a 30 % ACF1 lets an ectopic pair lift white -noise over the floor. The second look never runs for a night the existing -verdict passes, so no published value changes: only some refused nights -publish. RMSSD values and every threshold are unchanged. `tool/rmssd_gate_corpus.dart` +noise over the floor. The second look runs only for a night the existing +path leaves blank (refused, and no steady-breathing fallback), so no published +value changes: only some blank nights publish. RMSSD values and every threshold are unchanged. `tool/rmssd_gate_corpus.dart` reproduces the synthetic evidence: against main, 332 nights (typical HR, white noise with ectopic and missed beats, low HR, misplaced beats) show no night lost and no value changed, 3 headlines and 1 `nocturnalRmssd` gained, diff --git a/lib/src/onehz/clinical/hrv_time.dart b/lib/src/onehz/clinical/hrv_time.dart index 6a6800c..5ab2202 100644 --- a/lib/src/onehz/clinical/hrv_time.dart +++ b/lib/src/onehz/clinical/hrv_time.dart @@ -686,7 +686,11 @@ Metric nocturnalRmssd( } final acf1 = nnDiffAcf1(runs); var refused = _jitterRefused(acf1, runs); - if (refused) { + // A refused night main's path still publishes (steady breathing) keeps that + // value and window set: the second look is only for a night it leaves blank. + final mainKept = + refused ? _keptWindows(acf1, true, rmssds, perWindow, meanRr) : null; + if (refused && mainKept == null) { // The NN here is already corrected upstream; same seam rule as above. final whole = >[]; var run = []; @@ -709,7 +713,9 @@ Metric nocturnalRmssd( note: 'no usable 5-min windows for nocturnal RMSSD', ); } - final kept = _keptWindows(acf1, refused, rmssds, perWindow, meanRr); + // Still refused here means mainKept was computed, and was null. + final kept = mainKept ?? + (refused ? null : _keptWindows(acf1, false, rmssds, perWindow, meanRr)); if (kept == null) { return Metric.absent( tier: Tier.high, @@ -1010,7 +1016,11 @@ Metric sleepSessionRmssdDetail( // readiness composite already treats a null HRV driver as absent. final acf1 = nnDiffAcf1(runs); var refused = _jitterRefused(acf1, runs); - if (refused) { + // A refused night main's path still publishes (steady breathing) keeps that + // value and window set: the second look is only for a night it leaves blank. + final mainKept = + refused ? _keptWindows(acf1, true, rmssds, perWindow, meanRr) : null; + if (refused && mainKept == null) { List> diffsOf(double threshold) => [ for (var g = 0; g < keptRr.length; g++) for (final r @@ -1026,7 +1036,9 @@ Metric sleepSessionRmssdDetail( note: 'no valid 5-min windows for sleep-session RMSSD$dropped', ); } - final kept = _keptWindows(acf1, refused, rmssds, perWindow, meanRr); + // Still refused here means mainKept was computed, and was null. + final kept = mainKept ?? + (refused ? null : _keptWindows(acf1, false, rmssds, perWindow, meanRr)); if (kept == null) { return Metric.absent( tier: Tier.high,