Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions ALGORITHMS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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.
Expand Down
26 changes: 26 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
88 changes: 80 additions & 8 deletions lib/src/onehz/clinical/hrv_time.dart
Original file line number Diff line number Diff line change
Expand Up @@ -148,12 +148,22 @@ bool _onCoarseLattice(List<List<double>> 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<List<double>> runs,
{int minSegments = 20}) {
{int minSegments = 20, List<List<double>>? 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<List<double>> strictRuns, List<List<double>> 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<List<double>> runs) {
Expand Down Expand Up @@ -625,6 +635,7 @@ Metric<double> nocturnalRmssd(
// calmest-looking windows while the night pooled to −0.43/−0.51.
final runs = <List<double>>[];
final perWindow = <List<List<double>>>[];
final keptIdx = <int>[]; // beats of the windows that contributed, in order
final meanRr = <double>[];
final indices = buckets.keys.toList()..sort();
for (final idx in indices) {
Expand Down Expand Up @@ -669,19 +680,42 @@ Metric<double> 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 = <List<double>>[];
var run = <double>[];
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 = <double>[];
continue;
}
run.add(nnMs[i] - nnMs[p]);
}
if (run.isNotEmpty) whole.add(run);
refused = _wholeStreamRefused(whole, whole);
}
if (rmssds.isEmpty && !refused) {
return const Metric<double>.absent(
tier: Tier.high,
inputs_used: inputs,
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<double>.absent(
tier: Tier.high,
Expand Down Expand Up @@ -725,6 +759,17 @@ Metric<double> 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<double>` cannot
/// carry. Present only when the headline is.
class SessionRmssd {
Expand Down Expand Up @@ -889,6 +934,11 @@ Metric<SessionRmssd> sleepSessionRmssdDetail(
final rmssds = <double>[];
final runs = <List<double>>[]; // pooled jitter floor — see [nocturnalRmssd]
final perWindow = <List<List<double>>>[];
// 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 = <List<double>>[], keptTs = <List<double>>[];
int? lastKept;
final meanRr = <double>[];
var overCountedWindows = 0;
var thinWindows = 0;
Expand Down Expand Up @@ -939,6 +989,13 @@ Metric<SessionRmssd> sleepSessionRmssdDetail(
}
runs.addAll(diffRuns);
perWindow.add(diffRuns);
if (lastKept == null || idx != lastKept + 1) {
keptRr.add(<double>[]);
keptTs.add(<double>[]);
}
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));
}
Expand All @@ -958,15 +1015,30 @@ Metric<SessionRmssd> 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<List<double>> 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<SessionRmssd>.absent(
tier: Tier.high,
inputs_used: inputs,
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<SessionRmssd>.absent(
tier: Tier.high,
Expand Down Expand Up @@ -1024,9 +1096,9 @@ Metric<SessionRmssd> 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<List<double>> _cleanWindowRuns(List<double> rr, List<double> ts) {
List<List<double>> _cleanWindowRuns(List<double> rr, List<double> 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 = <double>[];
Expand Down
4 changes: 2 additions & 2 deletions lib/src/onehz/registry/group_registry.dart
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ const GroupRegistry kAnalyticsGroupRegistry = GroupRegistry(1, <GroupDecl>[
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',
Expand Down Expand Up @@ -190,7 +190,7 @@ const GroupRegistry kAnalyticsGroupRegistry = GroupRegistry(1, <GroupDecl>[
GroupDecl(
id: 'hrv.freq',
kind: GroupKind.algorithm,
counter: 2,
counter: 3, // 3: low-HR RMSSD gate reads an unbroken stream (abstention)
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
members: ['hrvFreq'],
api: [
'nightHrvShape',
Expand Down
7 changes: 5 additions & 2 deletions test/algo_version_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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});
});
}
125 changes: 125 additions & 0 deletions test/onehz/low_hr_rmssd_gate_test.dart
Original file line number Diff line number Diff line change
@@ -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<SessionRmssd> _session(({List<double> rr, List<double> ts}) n) =>
sleepSessionRmssdDetail(n.rr, n.ts,
startSec: gateStartSec, endSec: gateStartSec + gateDurSec);

Metric<double> _nocturnal(({List<double> rr, List<double> 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 = <String, ({double hr, double p, double drop, int seed})>{
'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 = <String, (({List<double> rr, List<double> 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));
});
}
});
}
Loading