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 1185ae2..a6f4ee9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -68,6 +68,32 @@ - `Calories.hourlyRollup` — hourly sums of covered minutes with per-hour coverage; an hour with no covered minute is null, not zero. +### 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 (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 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, +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 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..5ab2202 100644 --- a/lib/src/onehz/clinical/hrv_time.dart +++ b/lib/src/onehz/clinical/hrv_time.dart @@ -148,12 +148,22 @@ 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; } +/// 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) { @@ -625,6 +635,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 +680,32 @@ 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)); } final acf1 = nnDiffAcf1(runs); - final refused = _jitterRefused(acf1, runs); + var refused = _jitterRefused(acf1, runs); + // 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 = []; + 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]); + } + if (run.isNotEmpty) whole.add(run); + refused = _wholeStreamRefused(whole, whole); + } if (rmssds.isEmpty && !refused) { return const Metric.absent( tier: Tier.high, @@ -681,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, @@ -725,6 +759,17 @@ Metric nocturnalRmssd( /// 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 /// carry. Present only when the headline is. class SessionRmssd { @@ -889,6 +934,11 @@ Metric sleepSessionRmssdDetail( final rmssds = []; final runs = >[]; // pooled jitter floor — see [nocturnalRmssd] final perWindow = >>[]; + // 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; @@ -939,6 +989,13 @@ Metric sleepSessionRmssdDetail( } runs.addAll(diffRuns); perWindow.add(diffRuns); + 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)); } @@ -958,7 +1015,20 @@ Metric sleepSessionRmssdDetail( // are noise, the honest output is no headline, not a plausible one — the // readiness composite already treats a null HRV driver as absent. final acf1 = nnDiffAcf1(runs); - final refused = _jitterRefused(acf1, runs); + var refused = _jitterRefused(acf1, runs); + // 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 + 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)); + } if (rmssds.isEmpty && !refused) { return Metric.absent( tier: Tier.high, @@ -966,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, @@ -1024,9 +1096,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..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', @@ -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..5232fdf 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,11 @@ 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 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: 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..46132d9 --- /dev/null +++ b/test/onehz/low_hr_rmssd_gate_test.dart @@ -0,0 +1,125 @@ +// The jitter gate at low resting heart rate. +// +// Breathing at f cycles/beat puts the lag-1 ACF of the successive differences +// 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'; + +import '../../tool/rmssd_gate_corpus.dart'; + +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); + final t0 = n.ts.first; + return nocturnalRmssd(c.nn, [for (final t in c.nnTimesMs) t + t0]); +} + +void main() { + 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 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('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]) { + for (final (ect, miss) in artifacts) { + for (final drop in [0.0, 0.05]) { + 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: 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 clear the floor outright', () { + for (final hr in [60.0, 75.0]) { + 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]}')); +}