diff --git a/lib/src/onehz/sleep/hr_fallback.dart b/lib/src/onehz/sleep/hr_fallback.dart index 15ebbab..21e7bb8 100644 --- a/lib/src/onehz/sleep/hr_fallback.dart +++ b/lib/src/onehz/sleep/hr_fallback.dart @@ -102,13 +102,17 @@ HrLedWindow? hrLedSleepWindow( continue; } var j = i; + var hole = false; while (j < n) { // A HOLE IN THE RECORD ends the run. Two "low" samples three hours apart // are two observations, not a three-hour low-HR stretch — and the run's // duration below is WALL CLOCK, so without this the proposed window (the // one the user is shown and asked to confirm) was inflated by hours of // data we never had. - if (j > i && tsSec[j] - tsSec[j - 1] > maxSampleGapSec) break; + if (j > i && tsSec[j] - tsSec[j - 1] > maxSampleGapSec) { + hole = true; + break; + } if (low(j)) { j++; continue; @@ -134,7 +138,9 @@ HrLedWindow? hrLedSleepWindow( } final dur = tsSec[(j - 1).clamp(0, n - 1)] - tsSec[i]; runs.add((start: i, end: j, dur: dur)); - i = j + 1; + // After a hole j is the first sample of the next stretch, still a candidate + // run start; every other break stops on a non-low j. + i = hole ? j : j + 1; } // 5. Defer a dip still going at the cut, and every dip chained to it the diff --git a/test/onehz/hr_fallback_test.dart b/test/onehz/hr_fallback_test.dart index 4694d73..7be09c0 100644 --- a/test/onehz/hr_fallback_test.dart +++ b/test/onehz/hr_fallback_test.dart @@ -90,5 +90,26 @@ void main() { expect(w!.offsetSec, lessThanOrEqualTo(t0 + 3 * 3600 + 300), reason: 'pre-fix: t0+12000, the end of the awake stretch'); }); + + test('a run starting right after a recording hole keeps its first sample', () { + final hr = []; + final ts = []; + const t0 = 1700000000; + var t = t0; + void seg(int secs, double bpm) { + for (var i = 0; i < secs; i++) { + hr.add(bpm); + ts.add(t++); + } + } + seg(3 * 3600, 50); + t += 6 * 60; + final afterHole = t; + seg(4 * 3600, 50); + final w = hrLedSleepWindow(hr, ts, + hrBaseline: List.filled(120, 75)); + expect(w, isNotNull); + expect(w!.onsetSec, afterHole); + }); }); }