diff --git a/lib/compute/derivation_engine.dart b/lib/compute/derivation_engine.dart index 36c3c9435..6cec51410 100644 --- a/lib/compute/derivation_engine.dart +++ b/lib/compute/derivation_engine.dart @@ -3105,10 +3105,29 @@ class CompactResult { int get freedBytes => beforeBytes > afterBytes ? beforeBytes - afterBytes : 0; } +/// The experimental HMM sleep staging switch (Settings), default off. +const kSleepHmmStagesPref = 'sleep_hmm_stages'; + class DerivationEngine { DerivationEngine({this.log, this.background = false, this.offloadActive}); final void Function(String)? log; + /// EXPERIMENTAL, default off: re-stage the sleep window with the HMM + /// classifier inside [deriveDayBundle]. Read from the pref on every pass so + /// the foreground engine and every headless one agree, and a toggle takes + /// effect without a relaunch. Any failure reads as off. + static Future _hmmStagesOn() async { + try { + // reload(): a headless isolate caches its instance, so without it a + // toggle made in the app is not seen until that isolate restarts. + final prefs = await SharedPreferences.getInstance(); + await prefs.reload(); + return prefs.getBool(kSleepHmmStagesPref) ?? false; + } catch (_) { + return false; + } + } + /// True while a band offload is draining. The scheduler never STARTS a /// derive during one, but one can start mid-pass; the raw prune checks this /// before archiving each substrate bucket and stops for the pass, so a drain @@ -3380,6 +3399,7 @@ class DerivationEngine { ..sort(); final head = [ 'v${debugFingerprintAlgoVersion ?? kAlgoVersion}', + if (await _hmmStagesOn()) 'hmm', dataNowSec, // The edges a day is aged against (band and wearable; see // [_agingEdgeFor]), from the pass's own memo. @@ -3888,6 +3908,7 @@ class DerivationEngine { if (days.isEmpty) return 0; if (_running) return 0; _running = true; + lastRunFailedDays = 0; final startedAt = DateTime.now().millisecondsSinceEpoch; _diag ..['running'] = true @@ -3979,6 +4000,7 @@ class DerivationEngine { // every day under the current timezone, so it clears the travel hold too. // A partial selection deliberately does not: those days say nothing about // the ones still held. + lastRunFailedDays = failures; if (force && failures == 0) { final rawDays = (await LocalDb.decodedRecTsMaxByDay()).keys.toSet(); if (rawDays.isNotEmpty && rawDays.difference(days).isEmpty) { @@ -3999,6 +4021,7 @@ class DerivationEngine { return done; } catch (e, st) { _log('derive selected ERROR: $e\n$st'); + lastRunFailedDays = days.length; return 0; } finally { await _runStorageHousekeeping(); @@ -5955,6 +5978,7 @@ class DerivationEngine { // guess — sleep-onset latency only means what people think it means on a // forced window. sleepSource: day.sleepSource, + useHmmStages: await _hmmStagesOn(), ); final withHistory = _attachHistory(input, history); diff --git a/lib/compute/onehz_pipeline.dart b/lib/compute/onehz_pipeline.dart index 9f188d117..989a0ae93 100644 --- a/lib/compute/onehz_pipeline.dart +++ b/lib/compute/onehz_pipeline.dart @@ -1,3 +1,4 @@ +import 'sleep_pipeline_hmm.dart'; // onehz_pipeline.dart — the PURE, isolate-safe per-day analytics pipeline (V2). // // `deriveDayBundle` is a top-level function with NO DB / IO / Flutter binding @@ -415,6 +416,13 @@ class DayBundleInput { /// meaningful on a FORCED window — see `sol_sec` below. final String sleepSource; + /// EXPERIMENTAL, default OFF (PR #628 review): when true, the per-second + /// stage labels are re-derived by the HMM/Viterbi classifier + /// (`sleep_pipeline_hmm.dart`) from the sleep-window HR/RR substrate instead + /// of using the coordinator-supplied [hypnoStages]. Off by default so the + /// shipped heuristic stays the source of truth until the HMM is validated. + final bool useHmmStages; + const DayBundleInput({ required this.date, required this.dayTsSec, @@ -446,6 +454,7 @@ class DayBundleInput { this.deviceFamily, this.sleepSource = 'auto', this.stepSpans = const [], + this.useHmmStages = false, }); Map toJson() => { @@ -479,6 +488,7 @@ class DayBundleInput { 'day_flags': dayFlags, 'device_family': deviceFamily, 'sleep_source': sleepSource, + 'use_hmm_stages': useHmmStages, }; static DayBundleInput fromJson(Map m) { @@ -532,12 +542,103 @@ class DayBundleInput { dayFlags: strs('day_flags'), deviceFamily: m['device_family'] as String?, sleepSource: m['sleep_source'] as String? ?? 'auto', + useHmmStages: m['use_hmm_stages'] as bool? ?? false, stepSpans: [ for (final r in (m['step_spans'] as List? ?? const [])) [for (final v in (r as List)) (v as num).toInt()], ], ); } + + /// Copy with replaced per-second stage labels — the experimental HMM + /// re-staging path in [deriveDayBundle]. Every figure [sleepJson] derives + /// from the labels is recomputed from [stages] by `segmentSleep`'s own + /// definitions (counts over OBSERVED seconds only, WASO between the first + /// and last sleep second, efficiency over observed in-bed time), so a night + /// never mixes the HMM's stage totals with the original stager's + /// efficiency. Figures `segmentSleep` derives that edge does not recompute + /// here are dropped rather than left describing the old labels. Null when + /// the labels hold no sleep at all: the caller keeps the original night. + DayBundleInput? withHypnoStages(List stages) { + var light = 0, deep = 0, rem = 0, wake = 0, unobserved = 0; + var firstSleep = -1, lastSleep = -1; + for (var i = 0; i < stages.length; i++) { + switch (stages[i]) { + case 'light' || 'nrem': + light++; + case 'deep': + deep++; + case 'rem': + rem++; + case 'wake': + wake++; + default: + unobserved++; + continue; + } + if (stages[i] != 'wake') { + if (firstSleep < 0) firstSleep = i; + lastSleep = i; + } + } + final nrem = light + deep; + final tst = nrem + rem; + if (tst == 0) return null; + var waso = 0; + for (var i = firstSleep; i <= lastSleep; i++) { + if (stages[i] == 'wake') waso++; + } + final observedSec = stages.length - unobserved; + final json = {...sleepJson} + ..remove('sustained_awakenings') + ..remove('longest_sleep_run_sec') + ..remove('light_range_sec') + ..remove('deep_range_sec') + ..remove('rem_range_sec'); + json + ..['tst_sec'] = tst + ..['waso_sec'] = waso + ..['nrem_sec'] = nrem + ..['light_sec'] = light + ..['deep_sec'] = deep + ..['rem_sec'] = rem + ..['wake_sec'] = wake + ..['efficiency_pct'] = observedSec > 0 ? 100.0 * tst / observedSec : null + ..['stager_source'] = 'hmm'; + return DayBundleInput( + date: date, + dayTsSec: dayTsSec, + dayHr: dayHr, + dayRrTsMs: dayRrTsMs, + dayRrMs: dayRrMs, + sleepTsSec: sleepTsSec, + sleepHr: sleepHr, + sleepRrTsMs: sleepRrTsMs, + sleepRrMs: sleepRrMs, + sleepSkinTemp: sleepSkinTemp, + sleepJson: json, + hypnoStages: stages, + sleepOnsetSec: sleepOnsetSec, + sleepOffsetSec: sleepOffsetSec, + tonightSleepOnsetSec: tonightSleepOnsetSec, + profile: profile, + lnRmssdHistory: lnRmssdHistory, + lnRmssdDates: lnRmssdDates, + rhrHistory: rhrHistory, + respHistory: respHistory, + rmssdHistory: rmssdHistory, + skinTempAdcHistory: skinTempAdcHistory, + quietHrrHistory: quietHrrHistory, + readinessZHistory: readinessZHistory, + observedHrCeilingBpm: observedHrCeilingBpm, + dayConfidence: dayConfidence, + dayFlags: dayFlags, + stepSpans: stepSpans, + deviceFamily: deviceFamily, + sleepSource: sleepSource, + useHmmStages: useHmmStages, + ); + } } /// THE ISOLATE ENTRY POINT. @@ -546,7 +647,19 @@ class DayBundleInput { /// full derived bundle). Call directly + synchronously in tests, or via /// `Isolate.run(() => deriveDayBundle(input))` in production. Map deriveDayBundle(Map inputJson) { - final d = DayBundleInput.fromJson(inputJson); + var d = DayBundleInput.fromJson(inputJson); + + // EXPERIMENTAL HMM re-staging (default OFF — PR #628 review): when the + // input opts in, per-second labels are re-derived from the sleep-window + // HR/RR substrate by the Viterbi classifier. It abstains — the shipped + // labels stay — for the whole night when there is no baseline, and for + // each 30 s epoch it has no heart rate or RMSSD for; a second the band did + // not watch stays unobserved. The night's accounting is then recomputed + // from the final labels and the night is tagged `stager_source: hmm`. + if (d.useHmmStages && d.hypnoStages.isNotEmpty) { + final restaged = _hmmRestage(d); + if (restaged != null) d = d.withHypnoStages(restaged) ?? d; + } // ── HR over the DAY (for the curve, strain zones, dip day-side) ─────────── final dayHr = [for (final h in d.dayHr) h.toDouble()]; @@ -1393,6 +1506,9 @@ Map deriveDayBundle(Map inputJson) { // Why this night produced nothing, when the segmenter knows. Null on a // normal night; never render a bare dash for an absence that carries one. 'absence_reason': absenceReason, + // Present only when the experimental re-staging labelled this night (PR + // #628), so a night of the shipped stager is stored exactly as before. + if (d.sleepJson['stager_source'] == 'hmm') 'stager_source': 'hmm', // Seconds the band's own last SLEEP cut off the end of the auto window; null = rule did not apply. Provenance, never a metric. 'band_offset_trim_sec': bandOffsetTrimSec, 'stager': _envelope( @@ -2346,3 +2462,187 @@ int? _medianGapSec(List tsSec, {int minGapSec = 1}) { ]..sort(); return gaps.isEmpty ? null : gaps[gaps.length ~/ 2]; } + +/// Longest gap between two consecutive beats that still counts as one run of +/// beats; a successive difference is never taken across a longer one. +const double _rrRunBreakMs = 3000; + +/// Per-second RMSSD over the sleep window: for each second in [tsSec], the +/// RMSSD of cleaned NN intervals whose beat-end falls within the trailing +/// [windowSec] seconds. Seconds with no beat coverage get 0.0 (the HMM +/// treats that as an unusable observation, never as a measurement). +List _rmssdPerSecond( + List nn, + List nnTimesMs, + List tsSec, { + required int windowSec, +}) { + final out = List.filled(tsSec.length, 0.0); + if (nn.isEmpty || nnTimesMs.isEmpty || tsSec.isEmpty) return out; + var lo = 0; + var hi = 0; + for (var i = 0; i < tsSec.length; i++) { + final secMs = tsSec[i] * 1000.0; + while (lo < nn.length && nnTimesMs[lo] < secMs - windowSec * 1000) { + lo++; + } + while (hi < nn.length && nnTimesMs[hi] <= secMs) { + hi++; + } + if (hi - lo < 2) continue; + var sumSq = 0.0; + var diffs = 0; + for (var k = lo + 1; k < hi; k++) { + // Two beats seconds apart across a recording gap are not neighbours: + // their difference is not a beat-to-beat change. + if (nnTimesMs[k] - nnTimesMs[k - 1] > _rrRunBreakMs) continue; + final d = nn[k] - nn[k - 1]; + sumSq += d * d; + diffs++; + } + if (diffs == 0) continue; + out[i] = math.sqrt(sumSq / diffs); + } + return out; +} + +/// EXPERIMENTAL HMM/Viterbi re-staging (gated by [DayBundleInput.useHmmStages]). +/// +/// Returns the night's per-second labels, index-aligned with +/// [DayBundleInput.hypnoStages] (second `i` is `sleepOnsetSec + i`), or null +/// when the decoder abstains on the whole night — no HR or RMSSD baseline in +/// the first 120 minutes, or under 30 usable seconds — so the caller keeps the +/// shipped labels. +/// +/// Observations are placed BY CLOCK SECOND over the window: the substrate is +/// sparse (a row only where the band recorded) while the labels are dense, so +/// pairing them by row index would let a gap cost no time and shift every +/// later label. Within the night the decoder abstains per 30 s epoch: an +/// epoch with no plausible heart rate or no RMSSD keeps its shipped label, +/// and an unobserved second stays unobserved. +List? _hmmRestage(DayBundleInput d) { + final n = d.hypnoStages.length; + final t0 = d.sleepOnsetSec; + final hrAt = List.filled(n, 0.0); + for (var i = 0; i < d.sleepTsSec.length && i < d.sleepHr.length; i++) { + final k = d.sleepTsSec[i] - t0; + if (k >= 0 && k < n) hrAt[k] = d.sleepHr[i].toDouble(); + } + final corrected = correctRr(d.sleepRrMs, rrTsMs: d.sleepRrTsMs); + // nnTimesMs is relative to the start of the first input beat; put it back + // on the epoch so it lines up with the window's clock. + final rrEpoch0 = d.sleepRrTsMs.isEmpty || d.sleepRrMs.isEmpty + ? 0.0 + : d.sleepRrTsMs.first.toDouble() - d.sleepRrMs.first; + final nnTimes = [for (final t in corrected.nnTimesMs) t + rrEpoch0]; + final rmssdAt = _rmssdPerSecond( + corrected.nn, + nnTimes, + [for (var i = 0; i < n; i++) t0 + i], + windowSec: 60, + ); + final labels = _classifySleepStagesHMM([ + for (var i = 0; i < n; i++) + { + 'ts': t0 + i, + 'hr': d.hypnoStages[i] == 'unobserved' ? 0.0 : hrAt[i], + 'rmssd': d.hypnoStages[i] == 'unobserved' ? 0.0 : rmssdAt[i], + }, + ]); + if (labels == null) return null; + final merged = [ + for (var i = 0; i < n; i++) + d.hypnoStages[i] == 'unobserved' + ? 'unobserved' + : (labels[i] ?? d.hypnoStages[i]), + ]; + // The decoder never goes from REM straight to deep between its own labels, + // so any REM -> deep boundary left here involves a shipped label standing in + // for an epoch it abstained on. REM passes through light. + var prev = ''; + for (var i = 0; i < n; i++) { + if (merged[i] == 'unobserved') continue; + if (merged[i] == 'deep' && prev == 'rem') { + merged[i] = 'light'; + } + prev = merged[i]; + } + return merged; +} + +/// The Viterbi decode over 30 s epochs of [epochData] (per-second records +/// with `ts`, `hr`, `rmssd`). Null when the whole night abstains (see +/// [_hmmRestage]); otherwise one label per record, null where its epoch had +/// no usable heart rate or RMSSD. +List? _classifySleepStagesHMM(List> epochData) { + if (epochData.isEmpty) return null; + final analyzer = SleepStageAnalyzer(); + // Baseline from the first 120 minutes BY ELAPSED TIME, not the first 240 + // rows — per-second rows at 1 Hz would otherwise cover only ~4 minutes. + final t0 = (epochData.first['ts'] as num?)?.toDouble() ?? 0.0; + final first120m = epochData + .where((e) => ((e['ts'] as num?)?.toDouble() ?? 0.0) - t0 <= 120 * 60) + .toList(); + analyzer.computeBaseline(first120m); + // No baseline (RR that only starts after the first 120 minutes, say) makes + // every emission neutral, and wake's self-transition then labels a measured + // night as wake. Keep the shipped labels instead. + if (analyzer.hrMinNight == null || analyzer.rmssdMeanNight == null) { + return null; + } + final usable = epochData.where((e) { + final hr = (e['hr'] as num?)?.toDouble() ?? 0.0; + final rmssd = (e['rmssd'] as num?)?.toDouble() ?? 0.0; + return hr > 30.0 && hr < 200.0 && rmssd > 0.0 && rmssd < 500.0; + }).length; + if (usable < 30) return null; + // The transition table is per 30 s scoring epoch (AASM epoch length), so + // decode 30 s epochs, not 1 Hz rows: per row, wake's 0.90 self-transition + // would mean a ~10 s mean dwell. Each epoch averages its plausible HR and + // RMSSD; an epoch with none gets 0 (the neutral emission), and its label is + // not used. + final epochOf = [ + for (final e in epochData) + ((((e['ts'] as num?)?.toDouble() ?? t0) - t0) ~/ 30).toInt(), + ]; + final epochs = >[]; + final idx = {}; + for (var i = 0; i < epochData.length; i++) { + final k = idx.putIfAbsent(epochOf[i], () { + epochs.add({'hr': 0.0, 'rmssd': 0.0, 'nh': 0, 'nr': 0}); + return epochs.length - 1; + }); + final hr = (epochData[i]['hr'] as num?)?.toDouble() ?? 0.0; + final rmssd = (epochData[i]['rmssd'] as num?)?.toDouble() ?? 0.0; + final ep = epochs[k]; + if (hr > 30.0 && hr < 200.0) { + ep['hr'] = (ep['hr'] as double) + hr; + ep['nh'] = (ep['nh'] as int) + 1; + } + if (rmssd > 0.0 && rmssd < 500.0) { + ep['rmssd'] = (ep['rmssd'] as double) + rmssd; + ep['nr'] = (ep['nr'] as int) + 1; + } + } + for (final ep in epochs) { + final nh = ep['nh'] as int, nr = ep['nr'] as int; + ep['hr'] = nh == 0 ? 0.0 : (ep['hr'] as double) / nh; + ep['rmssd'] = nr == 0 ? 0.0 : (ep['rmssd'] as double) / nr; + } + final states = analyzer.viterbiDecode(epochs); + if (states.length != epochs.length) return null; + String label(SleepState s) => switch (s) { + SleepState.wake => 'wake', + SleepState.nremLight => 'light', + SleepState.nremDeep => 'deep', + SleepState.rem => 'rem', + }; + return [ + for (var i = 0; i < epochData.length; i++) + if (epochs[idx[epochOf[i]]!] case final ep + when (ep['nh'] as int) > 0 && (ep['nr'] as int) > 0) + label(states[idx[epochOf[i]]!]) + else + null, + ]; +} diff --git a/lib/compute/sleep_pipeline_hmm.dart b/lib/compute/sleep_pipeline_hmm.dart new file mode 100644 index 000000000..c09826f8d --- /dev/null +++ b/lib/compute/sleep_pipeline_hmm.dart @@ -0,0 +1,190 @@ +// DISCLAIMER: EXPERIMENTAL RESEARCH FEATURE ONLY. +// +// This classifier is NOT a medical device, NOT a validated sleep staging tool, +// and NOT a substitute for clinical polysomnography (PSG). +// +// The sleep staging methodology used here is for informational and research +// purposes only. It is based on autonomic signatures derived from wrist-worn +// PPG sensors and accelerometry. These signatures are estimates and not +// clinically diagnostic. +// +// IF YOU ARE EXPERIENCING SLEEP PROBLEMS (e.g. apnea, chronic insomnia, +// excessive daytime fatigue), please consult a physician or a qualified +// sleep specialist. Do NOT rely on these analytics for medical decisions. + +import 'dart:math'; + +enum SleepState { wake, nremLight, nremDeep, rem } + +// The transition table and the emission sigmoid centres/scales below are +// hand-set ESTIMATES (per 30 s epoch), not fitted to or validated against PSG. +class HMMConfig { + static const states = [ + SleepState.wake, + SleepState.nremLight, + SleepState.nremDeep, + SleepState.rem + ]; + + static final Map> transitionLogProb = { + SleepState.wake: { + SleepState.wake: log(0.90), + SleepState.nremLight: log(0.09), + SleepState.nremDeep: log(0.005), + SleepState.rem: log(0.005) + }, + SleepState.nremLight: { + SleepState.wake: log(0.05), + SleepState.nremLight: log(0.80), + SleepState.nremDeep: log(0.10), + SleepState.rem: log(0.05) + }, + SleepState.nremDeep: { + SleepState.wake: log(0.02), + SleepState.nremLight: log(0.15), + SleepState.nremDeep: log(0.80), + SleepState.rem: log(0.03) + }, + SleepState.rem: { + SleepState.wake: log(0.05), + SleepState.nremLight: log(0.10), + // INTENTIONAL HARD FORBID: REM never goes straight to deep (it passes + // through light). log(0) is -infinity; the decoder only ever ADDS it to + // finite emissions and compares, so it rules the move out without ever + // producing NaN. + SleepState.nremDeep: double.negativeInfinity, + SleepState.rem: log(0.85) + }, + }; +} + +class SleepStageAnalyzer { + double? hrMinNight; + double? rmssdMeanNight; + + // The same plausibility window decides which samples form the baseline and + // which observations get scored. A value outside it (a 250 bpm spike, a NaN + // from a dropped beat) is a measurement fault, not physiology, and scoring it + // would push the decoder towards wake. + static bool _plausibleHr(double? h) => h != null && h.isFinite && h > 30.0 && h < 200.0; + static bool _plausibleRmssd(double? r) => r != null && r.isFinite && r > 0.0 && r < 500.0; + + void computeBaseline(List> first120minData) { + if (first120minData.isEmpty) return; + final hrs = first120minData + .map((d) => (d['hr'] as num?)?.toDouble()) + .where(_plausibleHr) + .cast() + .toList(); + final rmssds = first120minData + .map((d) => (d['rmssd'] as num?)?.toDouble()) + .where(_plausibleRmssd) + .cast() + .toList(); + + if (hrs.isNotEmpty) { + hrs.sort(); + hrMinNight = hrs[(hrs.length * 0.1).floor()]; + } + if (rmssds.isNotEmpty) rmssdMeanNight = rmssds.reduce((a, b) => a + b) / rmssds.length; + } + + double _getEmissionLogProb(SleepState state, double hr, double rmssd, {bool isContactLost = false}) { + if (isContactLost || + !_plausibleHr(hr) || + !_plausibleRmssd(rmssd) || + hrMinNight == null || + rmssdMeanNight == null) { + return log(0.25); + } + + final hrNorm = hr / hrMinNight!; + final rmssdNorm = rmssd / rmssdMeanNight!; + + double sigmoid(double x, double center, double scale) => 1.0 / (1.0 + exp(-(x - center) / scale)); + + double prob; + switch (state) { + case SleepState.wake: + prob = sigmoid(hrNorm, 1.2, 0.05) * (1.0 - sigmoid(rmssdNorm, 0.8, 0.05)); + break; + case SleepState.nremDeep: + prob = (1.0 - sigmoid(hrNorm, 1.0, 0.05)) * sigmoid(rmssdNorm, 1.1, 0.05); + break; + case SleepState.rem: + prob = sigmoid(hrNorm, 1.05, 0.05) * sigmoid(rmssdNorm, 1.0, 0.05); + break; + case SleepState.nremLight: + prob = 0.4; + break; + } + return log(max(0.01, prob)); + } + + List viterbiDecode(List> nightData) { + if (nightData.isEmpty) return []; + + final T = nightData.length; + final states = HMMConfig.states; + final N = states.length; + + final viterbi = List.generate(T, (_) => List.filled(N, double.negativeInfinity)); + final backpointer = List.generate(T, (_) => List.filled(N, 0)); + + for (var i = 0; i < N; i++) { + final state = states[i]; + final hr = (nightData[0]['hr'] as num?)?.toDouble() ?? 0.0; + final rmssd = (nightData[0]['rmssd'] as num?)?.toDouble() ?? 0.0; + final initProb = (state == SleepState.wake || state == SleepState.nremLight) ? log(0.5) : double.negativeInfinity; + viterbi[0][i] = initProb + + _getEmissionLogProb(state, hr, rmssd, + isContactLost: nightData[0]['isContactLost'] == true); + } + + for (var t = 1; t < T; t++) { + final hr = (nightData[t]['hr'] as num?)?.toDouble() ?? 0.0; + final rmssd = (nightData[t]['rmssd'] as num?)?.toDouble() ?? 0.0; + final contactLost = nightData[t]['isContactLost'] == true; + for (var j = 0; j < N; j++) { + final nextState = states[j]; + final emission = + _getEmissionLogProb(nextState, hr, rmssd, isContactLost: contactLost); + var maxLogProb = double.negativeInfinity; + var bestPrevState = 0; + for (var i = 0; i < N; i++) { + final prevState = states[i]; + final trans = HMMConfig.transitionLogProb[prevState]![nextState]!; + final logProb = viterbi[t - 1][i] + trans + emission; + if (logProb > maxLogProb) { + maxLogProb = logProb; + bestPrevState = i; + } + } + viterbi[t][j] = maxLogProb; + backpointer[t][j] = bestPrevState; + } + } + + var bestLastState = 0; + var maxFinalProb = double.negativeInfinity; + for (var i = 0; i < N; i++) { + if (viterbi[T - 1][i] > maxFinalProb) { + maxFinalProb = viterbi[T - 1][i]; + bestLastState = i; + } + } + // Wake and light are always reachable with finite emissions, so a path + // always exists; if one ever does not (or a score is NaN), decode + // nothing and let the caller keep the shipped labels. + if (!maxFinalProb.isFinite) return []; + + final result = List.filled(T, SleepState.nremLight); + var currentStateIndex = bestLastState; + result[T - 1] = states[currentStateIndex]; + for (var t = T - 1; t > 0; t--) { + currentStateIndex = backpointer[t][currentStateIndex]; + result[t - 1] = states[currentStateIndex]; + } + return result; + } +} diff --git a/lib/data/backup_extras.dart b/lib/data/backup_extras.dart index a7c240ac2..0355ecde4 100644 --- a/lib/data/backup_extras.dart +++ b/lib/data/backup_extras.dart @@ -164,6 +164,7 @@ const Map kPrefTypes = { 'rough_night.ask': 'string', 'rough_night.dismissed': 'string', 'share.map_tiles': 'bool', + 'sleep_hmm_stages': 'bool', 'theme_choice': 'string', 'ui.shell_tab': 'int', 'ui.shell_tab.v2': 'int', diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index d07a1e55c..75805955a 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -3735,7 +3735,11 @@ "welcomeSettingsSkipped": "{n, plural, =1{1 Einstellung in der Sicherung war nicht lesbar und wurde übersprungen} other{{n} Einstellungen in der Sicherung waren nicht lesbar und wurden übersprungen}}", "@welcomeSettingsSkipped": { "description": "Import report: settings rows in the backup that could not be read", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "welcomeSettingsSkippedBody": "Dafür bleiben die Werte dieses Telefons.", "welcomeCoachChatGptReentry": "Deine ChatGPT-Anmeldung bleibt im sicheren Speicher und wurde nicht gesichert. Melde dich in den KI-Einstellungen erneut an, um den Coach auf diesem Telefon zu nutzen.", @@ -3743,7 +3747,11 @@ "welcomeSettingsRestored": "{n} Einstellungen wiederhergestellt", "@welcomeSettingsRestored": { "description": "Import report: number of restored app preferences", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "strengthCustomWeight": "Benutzerdefiniertes Gewicht", "strengthEnterValue": "Wert eingeben", @@ -3813,5 +3821,13 @@ "dayStrainWornAsOf": "Getragen, Stand {time}", "bandStatusFirmwareLockedTitle": "Die Firmware des Bands hält wahrscheinlich seine Daten zurück", "bandStatusFirmwareLockedReason": "Dieses Band läuft mit WHOOP-Firmware 50.43. Sie kann sich verbinden und der App antworten, aber keine Aufzeichnungen und keine Live-Herzfrequenz senden, solange kein von WHOOP signiertes Mitgliedschafts-Token auf dem Band ist. Das ist ein möglicher Grund, warum keine Daten ankommen. OpenStrap kann dieses Token nicht ausstellen. Alles, was hier schon gespeichert ist, bleibt erhalten.", - "bandStatusFirmwareLockedFix": "Liegt es an der Firmware, lässt sich das in der App nicht ändern, und der Hinweis verschwindet, sobald das Band wieder Aufzeichnungen sendet" + "bandStatusFirmwareLockedFix": "Liegt es an der Firmware, lässt sich das in der App nicht ändern, und der Hinweis verschwindet, sobald das Band wieder Aufzeichnungen sendet", + "settingsSleepHmmRowTitle": "Experimentelles Schlaf-Staging (HMM)", + "@settingsSleepHmmRowTitle": { + "description": "Title of the experimental HMM sleep staging toggle in Settings." + }, + "settingsSleepHmmRowSub": "Forschungsalgorithmus, kein Medizinprodukt. Standard aus.", + "@settingsSleepHmmRowSub": { + "description": "Subtitle of the experimental HMM sleep staging toggle in Settings." + } } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 56d019152..5329d10e0 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1086,151 +1086,151 @@ }, "flashWarning": "Installing an image you supply yourself can permanently damage your strap, void its warranty and stop it working. It cannot be undone from this app. OpenStrap does not provide, review or endorse any image, and OpenStrap and its contributors accept no responsibility or liability for any loss or damage. You do this entirely at your own risk.", "@flashWarning": { - "description": "Install-an-image screen (WHOOP 5): Warning" + "description": "Install-an-image screen (WHOOP 5): Warning" }, "flashAccept": "I understand and accept the risk", "@flashAccept": { - "description": "Install-an-image screen (WHOOP 5): Accept" + "description": "Install-an-image screen (WHOOP 5): Accept" }, "flashFileInfo": "{name}\n{bytes} bytes\nsha256 {sha}", "@flashFileInfo": { - "description": "Install-an-image screen (WHOOP 5): FileInfo", - "placeholders": { - "name": { - "type": "String" - }, - "bytes": { - "type": "int" - }, - "sha": { - "type": "String" - } + "description": "Install-an-image screen (WHOOP 5): FileInfo", + "placeholders": { + "name": { + "type": "String" + }, + "bytes": { + "type": "int" + }, + "sha": { + "type": "String" } + } }, "flashChoose": "Choose image file", "@flashChoose": { - "description": "Install-an-image screen (WHOOP 5): Choose" + "description": "Install-an-image screen (WHOOP 5): Choose" }, "flashChooseAnother": "Choose another", "@flashChooseAnother": { - "description": "Install-an-image screen (WHOOP 5): ChooseAnother" + "description": "Install-an-image screen (WHOOP 5): ChooseAnother" }, "flashSend": "Send to strap", "@flashSend": { - "description": "Install-an-image screen (WHOOP 5): Send" + "description": "Install-an-image screen (WHOOP 5): Send" }, "flashStop": "Stop", "@flashStop": { - "description": "Install-an-image screen (WHOOP 5): Stop" + "description": "Install-an-image screen (WHOOP 5): Stop" }, "flashProgress": "{done} of {total} blocks sent. Keep the app open and the strap close.", "@flashProgress": { - "description": "Install-an-image screen (WHOOP 5): Progress", - "placeholders": { - "done": { - "type": "int" - }, - "total": { - "type": "int" - } + "description": "Install-an-image screen (WHOOP 5): Progress", + "placeholders": { + "done": { + "type": "int" + }, + "total": { + "type": "int" } + } }, "flashCommitting": "Sending the commit…", "@flashCommitting": { - "description": "Install-an-image screen (WHOOP 5): Committing" + "description": "Install-an-image screen (WHOOP 5): Committing" }, "flashCommitted": "The strap accepted the image. That does not confirm it is running. Check the strap's firmware version after it restarts.", "@flashCommitted": { - "description": "Install-an-image screen (WHOOP 5): Committed" + "description": "Install-an-image screen (WHOOP 5): Committed" }, "flashCommitUnknown": "The commit was sent but the strap did not answer. It may or may not have been applied. Do not try again. Check the strap's firmware version after it restarts.", "@flashCommitUnknown": { - "description": "Install-an-image screen (WHOOP 5): CommitUnknown" + "description": "Install-an-image screen (WHOOP 5): CommitUnknown" }, "flashBlockNoImage": "Choose an image file first.", "@flashBlockNoImage": { - "description": "Install-an-image screen (WHOOP 5): BlockNoImage" + "description": "Install-an-image screen (WHOOP 5): BlockNoImage" }, "flashBlockTooLarge": "That file is too large for an image.", "@flashBlockTooLarge": { - "description": "Install-an-image screen (WHOOP 5): BlockTooLarge" + "description": "Install-an-image screen (WHOOP 5): BlockTooLarge" }, "flashBlockNoLink": "Connect a WHOOP 5 and wait for any sync to finish.", "@flashBlockNoLink": { - "description": "Install-an-image screen (WHOOP 5): BlockNoLink" + "description": "Install-an-image screen (WHOOP 5): BlockNoLink" }, "flashBlockBatteryUnknown": "Battery level unknown. Wait for it to be read.", "@flashBlockBatteryUnknown": { - "description": "Install-an-image screen (WHOOP 5): BlockBatteryUnknown" + "description": "Install-an-image screen (WHOOP 5): BlockBatteryUnknown" }, "flashBlockBatteryLow": "Battery is {pct}%. Charge to at least {min}% first.", "@flashBlockBatteryLow": { - "description": "Install-an-image screen (WHOOP 5): BlockBatteryLow", - "placeholders": { - "pct": { - "type": "int" - }, - "min": { - "type": "int" - } + "description": "Install-an-image screen (WHOOP 5): BlockBatteryLow", + "placeholders": { + "pct": { + "type": "int" + }, + "min": { + "type": "int" } + } }, "flashFailTakeover": "Could not take over the connection.", "@flashFailTakeover": { - "description": "Install-an-image screen (WHOOP 5): FailTakeover" + "description": "Install-an-image screen (WHOOP 5): FailTakeover" }, "flashFailStart": "The strap did not accept the start of the update.", "@flashFailStart": { - "description": "Install-an-image screen (WHOOP 5): FailStart" + "description": "Install-an-image screen (WHOOP 5): FailStart" }, "flashFailData": "The strap rejected data at byte {offset}. Nothing was committed.", "@flashFailData": { - "description": "Install-an-image screen (WHOOP 5): FailData", - "placeholders": { - "offset": { - "type": "int" - } + "description": "Install-an-image screen (WHOOP 5): FailData", + "placeholders": { + "offset": { + "type": "int" } + } }, "flashFailVerify": "The strap did not verify the image. Nothing was committed.", "@flashFailVerify": { - "description": "Install-an-image screen (WHOOP 5): FailVerify" + "description": "Install-an-image screen (WHOOP 5): FailVerify" }, "flashFailCancelled": "Cancelled. Nothing was committed.", "@flashFailCancelled": { - "description": "Install-an-image screen (WHOOP 5): FailCancelled" + "description": "Install-an-image screen (WHOOP 5): FailCancelled" }, "flashFailCommitRejected": "The strap did not accept the commit.", "@flashFailCommitRejected": { - "description": "Install-an-image screen (WHOOP 5): FailCommitRejected" + "description": "Install-an-image screen (WHOOP 5): FailCommitRejected" }, "flashPickUnreadable": "That file could not be read.", "@flashPickUnreadable": { - "description": "Install-an-image screen (WHOOP 5): PickUnreadable" + "description": "Install-an-image screen (WHOOP 5): PickUnreadable" }, "flashConfirmTitle": "Install this image?", "@flashConfirmTitle": { - "description": "Install-an-image screen (WHOOP 5): ConfirmTitle" + "description": "Install-an-image screen (WHOOP 5): ConfirmTitle" }, "flashConfirmBody": "The strap has the file and verified it. Nothing is installed until you press Sure, and that cannot be undone.\n\n{name}\nsha256 {sha}", "@flashConfirmBody": { - "description": "Install-an-image screen (WHOOP 5): ConfirmBody", - "placeholders": { - "name": { - "type": "String" - }, - "sha": { - "type": "String" - } + "description": "Install-an-image screen (WHOOP 5): ConfirmBody", + "placeholders": { + "name": { + "type": "String" + }, + "sha": { + "type": "String" } + } }, "flashConfirmSure": "Sure", "@flashConfirmSure": { - "description": "Install-an-image screen (WHOOP 5): ConfirmSure" + "description": "Install-an-image screen (WHOOP 5): ConfirmSure" }, "flashConfirmCancel": "Cancel", "@flashConfirmCancel": { - "description": "Install-an-image screen (WHOOP 5): ConfirmCancel" + "description": "Install-an-image screen (WHOOP 5): ConfirmCancel" }, "flashAcknowledge": "I checked the firmware version. Allow another install.", "@flashAcknowledge": { @@ -17181,7 +17181,11 @@ "welcomeSettingsSkipped": "{n, plural, =1{1 setting in the backup could not be read and was skipped} other{{n} settings in the backup could not be read and were skipped}}", "@welcomeSettingsSkipped": { "description": "Import report: settings rows in the backup that could not be read", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "welcomeSettingsSkippedBody": "Those keep this phone's values.", "welcomeCoachChatGptReentry": "Your ChatGPT sign-in stays in secure storage and was not backed up. Sign in again in AI settings to use the coach on this phone.", @@ -17189,32 +17193,60 @@ "welcomeSettingsRestored": "{n} settings restored", "@welcomeSettingsRestored": { "description": "Import report: number of restored app preferences", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "strengthCustomWeight": "Custom weight", - "@strengthCustomWeight": {"description": "Strength set editor copy."}, + "@strengthCustomWeight": { + "description": "Strength set editor copy." + }, "strengthEnterValue": "Enter a value", - "@strengthEnterValue": {"description": "Strength set editor copy."}, + "@strengthEnterValue": { + "description": "Strength set editor copy." + }, "strengthInvalidNumber": "Invalid number", - "@strengthInvalidNumber": {"description": "Strength set editor copy."}, + "@strengthInvalidNumber": { + "description": "Strength set editor copy." + }, "strengthLoadRangeKg": "Must be 0–500 kg", - "@strengthLoadRangeKg": {"description": "Strength set editor copy."}, + "@strengthLoadRangeKg": { + "description": "Strength set editor copy." + }, "strengthLoadRangeLb": "Must be 0–1100 lb", - "@strengthLoadRangeLb": {"description": "Strength set editor copy."}, + "@strengthLoadRangeLb": { + "description": "Strength set editor copy." + }, "strengthRepsRange": "Must be 1–200 reps", - "@strengthRepsRange": {"description": "Strength set editor copy."}, + "@strengthRepsRange": { + "description": "Strength set editor copy." + }, "strengthEditSet": "Edit set", - "@strengthEditSet": {"description": "Strength set editor copy."}, + "@strengthEditSet": { + "description": "Strength set editor copy." + }, "strengthDeleteSet": "Delete set", - "@strengthDeleteSet": {"description": "Strength set editor copy."}, + "@strengthDeleteSet": { + "description": "Strength set editor copy." + }, "strengthDeleteSetConfirm": "Delete this set?", - "@strengthDeleteSetConfirm": {"description": "Strength set editor copy."}, + "@strengthDeleteSetConfirm": { + "description": "Strength set editor copy." + }, "strengthBodyweight": "Bodyweight", - "@strengthBodyweight": {"description": "Strength set editor copy."}, + "@strengthBodyweight": { + "description": "Strength set editor copy." + }, "strengthDelete": "Delete", - "@strengthDelete": {"description": "Strength set editor copy."}, + "@strengthDelete": { + "description": "Strength set editor copy." + }, "strengthSaveFailed": "Failed to save changes", - "@strengthSaveFailed": {"description": "Strength set editor copy."}, + "@strengthSaveFailed": { + "description": "Strength set editor copy." + }, "bandStatusFirmwareLockedTitle": "The band’s firmware is probably holding back its data", "@bandStatusFirmwareLockedTitle": { "description": "BandStatus card title: band firmware 50.43 withholds all data until a WHOOP membership token is on it" @@ -17255,5 +17287,13 @@ "type": "String" } } + }, + "settingsSleepHmmRowTitle": "Experimental sleep staging (HMM)", + "@settingsSleepHmmRowTitle": { + "description": "Title of the experimental HMM sleep staging toggle in Settings." + }, + "settingsSleepHmmRowSub": "Research algorithm, not a medical device. Off by default.", + "@settingsSleepHmmRowSub": { + "description": "Subtitle of the experimental HMM sleep staging toggle in Settings." } } diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 6b38b34b3..d199e9be5 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -3033,7 +3033,11 @@ "welcomeSettingsSkipped": "{n, plural, =1{1 ajuste de la copia no se pudo leer y se omitió} other{{n} ajustes de la copia no se pudieron leer y se omitieron}}", "@welcomeSettingsSkipped": { "description": "Import report: settings rows in the backup that could not be read", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "welcomeSettingsSkippedBody": "Esos conservan los valores de este teléfono.", "welcomeCoachChatGptReentry": "Tu sesión de ChatGPT permanece en el almacenamiento seguro y no se incluyó en la copia. Vuelve a iniciar sesión en los ajustes de IA para usar el asistente en este teléfono.", @@ -3041,7 +3045,11 @@ "welcomeSettingsRestored": "{n} ajustes restaurados", "@welcomeSettingsRestored": { "description": "Import report: number of restored app preferences", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "strengthCustomWeight": "Peso personalizado", "strengthEnterValue": "Introduce un valor", @@ -3514,6 +3522,14 @@ "bandStatusFirmwareLockedTitle": "Probablemente el firmware de la banda está reteniendo sus datos", "bandStatusFirmwareLockedReason": "Esta banda usa el firmware 50.43 de WHOOP, que puede conectarse y responder a la app sin enviar registros ni frecuencia cardíaca en vivo hasta que haya en ella un token de membresía firmado por WHOOP. Es una posible razón de que no lleguen datos. OpenStrap no puede emitir ese token. Todo lo que ya está guardado aquí está a salvo.", "bandStatusFirmwareLockedFix": "Si es el firmware, la app no puede cambiarlo y el aviso desaparece cuando la banda vuelva a enviar registros", + "settingsSleepHmmRowTitle": "Clasificación del sueño experimental (HMM)", + "@settingsSleepHmmRowTitle": { + "description": "Title of the experimental HMM sleep staging toggle in Settings." + }, + "settingsSleepHmmRowSub": "Algoritmo de investigación, no un dispositivo médico. Desactivado por defecto.", + "@settingsSleepHmmRowSub": { + "description": "Subtitle of the experimental HMM sleep staging toggle in Settings." + }, "supplementSmartWindowMinutes": "{m} min antes de la hora de despertar", "supplementGoalValue": "Objetivo {target}", "supplementOfCountUnit": "de {n} {unit}", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 9bb79a39c..37586894a 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -3004,7 +3004,11 @@ "welcomeSettingsSkipped": "{n, plural, =1{1 réglage de la sauvegarde était illisible et a été ignoré} other{{n} réglages de la sauvegarde étaient illisibles et ont été ignorés}}", "@welcomeSettingsSkipped": { "description": "Import report: settings rows in the backup that could not be read", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "welcomeSettingsSkippedBody": "Ils gardent les valeurs de ce téléphone.", "welcomeCoachChatGptReentry": "Votre connexion à ChatGPT reste dans le stockage sécurisé et n’a pas été sauvegardée. Connectez-vous à nouveau dans les réglages de l’IA pour utiliser le coach sur ce téléphone.", @@ -3012,7 +3016,11 @@ "welcomeSettingsRestored": "{n} réglages restaurés", "@welcomeSettingsRestored": { "description": "Import report: number of restored app preferences", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "strengthCustomWeight": "Poids personnalisé", "strengthEnterValue": "Saisissez une valeur", @@ -3514,6 +3522,14 @@ "bandStatusFirmwareLockedTitle": "Le firmware du bracelet retient probablement ses données", "bandStatusFirmwareLockedReason": "Ce bracelet utilise le firmware WHOOP 50.43, qui peut se connecter et répondre à l’application sans envoyer ni enregistrements ni fréquence cardiaque en direct tant qu’un jeton d’abonnement signé par WHOOP n’est pas présent sur le bracelet. C’est une raison possible pour laquelle aucune donnée n’arrive. OpenStrap ne peut pas émettre ce jeton. Tout ce qui est déjà enregistré ici est en sécurité.", "bandStatusFirmwareLockedFix": "Si c’est le firmware, l’application n’y peut rien et ce message disparaît dès que le bracelet renvoie des enregistrements", + "settingsSleepHmmRowTitle": "Stadification du sommeil expérimentale (HMM)", + "@settingsSleepHmmRowTitle": { + "description": "Title of the experimental HMM sleep staging toggle in Settings." + }, + "settingsSleepHmmRowSub": "Algorithme de recherche, pas un dispositif médical. Désactivé par défaut.", + "@settingsSleepHmmRowSub": { + "description": "Subtitle of the experimental HMM sleep staging toggle in Settings." + }, "supplementSmartWindowMinutes": "{m} min avant l’heure de réveil", "supplementGoalValue": "Objectif {target}", "supplementOfCountUnit": "sur {n} {unit}", diff --git a/lib/l10n/app_hi.arb b/lib/l10n/app_hi.arb index 47a98ef60..2586934aa 100644 --- a/lib/l10n/app_hi.arb +++ b/lib/l10n/app_hi.arb @@ -3004,7 +3004,11 @@ "welcomeSettingsSkipped": "{n, plural, =1{बैकअप की 1 सेटिंग पढ़ी नहीं जा सकी और छोड़ दी गई} other{बैकअप की {n} सेटिंग्स पढ़ी नहीं जा सकीं और छोड़ दी गईं}}", "@welcomeSettingsSkipped": { "description": "Import report: settings rows in the backup that could not be read", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "welcomeSettingsSkippedBody": "उनके लिए इस फ़ोन के मान बने रहेंगे।", "welcomeCoachChatGptReentry": "आपका ChatGPT साइन-इन सुरक्षित स्टोरेज में रहता है और बैकअप में शामिल नहीं किया गया। इस फ़ोन पर कोच इस्तेमाल करने के लिए AI सेटिंग में फिर से साइन इन करें।", @@ -3012,7 +3016,11 @@ "welcomeSettingsRestored": "{n} सेटिंग बहाल हुईं", "@welcomeSettingsRestored": { "description": "Import report: number of restored app preferences", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "strengthCustomWeight": "कस्टम वज़न", "strengthEnterValue": "एक मान दर्ज करें", @@ -3514,6 +3522,14 @@ "bandStatusFirmwareLockedTitle": "बैंड का फ़र्मवेयर शायद उसका डेटा रोक रहा है", "bandStatusFirmwareLockedReason": "यह बैंड WHOOP फ़र्मवेयर 50.43 पर चल रहा है, जो कनेक्ट होकर ऐप को जवाब दे सकता है, लेकिन जब तक बैंड पर WHOOP द्वारा साइन किया गया सदस्यता टोकन न हो, तब तक हो सकता है कि कोई रिकॉर्डिंग या लाइव हृदय गति न भेजे। डेटा न आने का एक संभावित कारण यह हो सकता है। OpenStrap वह टोकन जारी नहीं कर सकता। यहाँ पहले से सहेजा गया सब कुछ सुरक्षित है।", "bandStatusFirmwareLockedFix": "अगर वजह फ़र्मवेयर है, तो ऐप इसे बदल नहीं सकता और बैंड के फिर से रिकॉर्डिंग भेजते ही यह संदेश हट जाएगा", + "settingsSleepHmmRowTitle": "प्रायोगिक नींद चरण विश्लेषण (HMM)", + "@settingsSleepHmmRowTitle": { + "description": "Title of the experimental HMM sleep staging toggle in Settings." + }, + "settingsSleepHmmRowSub": "यह एक शोध एल्गोरिदम है, चिकित्सा उपकरण नहीं। यह डिफ़ॉल्ट रूप से बंद है।", + "@settingsSleepHmmRowSub": { + "description": "Subtitle of the experimental HMM sleep staging toggle in Settings." + }, "supplementSmartWindowMinutes": "जागने के समय से {m} मिनट पहले", "supplementGoalValue": "लक्ष्य {target}", "supplementOfCountUnit": "{n} {unit} में से", diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 1ae074694..874429c5a 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -8094,7 +8094,11 @@ "welcomeSettingsSkipped": "{n, plural, one{{n} настройку из резервной копии не удалось прочитать, она пропущена} few{{n} настройки из резервной копии не удалось прочитать, они пропущены} many{{n} настроек из резервной копии не удалось прочитать, они пропущены} other{{n} настройки из резервной копии не удалось прочитать, они пропущены}}", "@welcomeSettingsSkipped": { "description": "Import report: settings rows in the backup that could not be read", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "welcomeSettingsSkippedBody": "Для них остаются значения этого телефона.", "welcomeCoachChatGptReentry": "Данные входа в ChatGPT остаются в защищённом хранилище и не включены в резервную копию. Войдите снова в настройках ИИ, чтобы пользоваться тренером на этом телефоне.", @@ -8102,7 +8106,11 @@ "welcomeSettingsRestored": "Восстановлено настроек: {n}", "@welcomeSettingsRestored": { "description": "Import report: number of restored app preferences", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "strengthCustomWeight": "Свой вес", "strengthEnterValue": "Введите значение", @@ -8336,5 +8344,13 @@ "type": "String" } } + }, + "settingsSleepHmmRowTitle": "Экспериментальное определение стадий сна (HMM)", + "@settingsSleepHmmRowTitle": { + "description": "Title of the experimental HMM sleep staging toggle in Settings." + }, + "settingsSleepHmmRowSub": "Исследовательский алгоритм, не медицинское устройство. Выключено по умолчанию.", + "@settingsSleepHmmRowSub": { + "description": "Subtitle of the experimental HMM sleep staging toggle in Settings." } } diff --git a/lib/l10n/app_th.arb b/lib/l10n/app_th.arb index c6937dc3a..13db46918 100644 --- a/lib/l10n/app_th.arb +++ b/lib/l10n/app_th.arb @@ -16475,7 +16475,11 @@ "welcomeSettingsSkipped": "{n, plural, other{อ่านการตั้งค่า {n} รายการในข้อมูลสำรองไม่ได้และข้ามไป}}", "@welcomeSettingsSkipped": { "description": "Import report: settings rows in the backup that could not be read", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "welcomeSettingsSkippedBody": "รายการเหล่านั้นใช้ค่าของโทรศัพท์เครื่องนี้ต่อ", "welcomeCoachChatGptReentry": "ข้อมูลการลงชื่อเข้าใช้ ChatGPT ยังอยู่ในพื้นที่จัดเก็บที่ปลอดภัยและไม่ได้รวมอยู่ในข้อมูลสำรอง โปรดลงชื่อเข้าใช้อีกครั้งในการตั้งค่า AI เพื่อใช้โค้ชบนโทรศัพท์เครื่องนี้", @@ -16483,7 +16487,11 @@ "welcomeSettingsRestored": "กู้คืนการตั้งค่าแล้ว {n} รายการ", "@welcomeSettingsRestored": { "description": "Import report: number of restored app preferences", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "strengthCustomWeight": "น้ำหนักที่กำหนดเอง", "strengthEnterValue": "ป้อนค่า", @@ -16960,5 +16968,13 @@ "pairReplaceMyBand": "เปลี่ยนสายรัดของฉัน", "dayStepsWhoop4NoCounter": "WHOOP 4.0 ไม่มีตัวนับก้าวในตัว จึงนับก้าวได้เฉพาะตอนที่แอปนี้กำลังรับข้อมูลสดจากสายรัดเท่านั้น", "healthWearNotUpdatedSince": "ไม่ได้อัปเดตตั้งแต่ {time}", - "dayStrainWornAsOf": "สวมใส่ ข้อมูล ณ {time}" + "dayStrainWornAsOf": "สวมใส่ ข้อมูล ณ {time}", + "settingsSleepHmmRowTitle": "การแบ่งระยะการนอนแบบทดลอง (HMM)", + "@settingsSleepHmmRowTitle": { + "description": "Title of the experimental HMM sleep staging toggle in Settings." + }, + "settingsSleepHmmRowSub": "อัลกอริทึมเพื่อการวิจัย ไม่ใช่อุปกรณ์การแพทย์ ปิดไว้โดยค่าเริ่มต้น", + "@settingsSleepHmmRowSub": { + "description": "Subtitle of the experimental HMM sleep staging toggle in Settings." + } } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 7c26f10a7..79e4df6dc 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -3004,7 +3004,11 @@ "welcomeSettingsSkipped": "{n, plural, other{备份中有 {n} 项设置无法读取,已跳过}}", "@welcomeSettingsSkipped": { "description": "Import report: settings rows in the backup that could not be read", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "welcomeSettingsSkippedBody": "这些设置保留本机的值。", "welcomeCoachChatGptReentry": "你的 ChatGPT 登录信息保留在安全存储中,未包含在备份内。请在 AI 设置中重新登录,以便在此手机上使用教练。", @@ -3012,7 +3016,11 @@ "welcomeSettingsRestored": "已恢复 {n} 项设置", "@welcomeSettingsRestored": { "description": "Import report: number of restored app preferences", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "strengthCustomWeight": "自定义重量", "strengthEnterValue": "输入数值", @@ -3514,6 +3522,14 @@ "bandStatusFirmwareLockedTitle": "手环固件可能正在扣留它的数据", "bandStatusFirmwareLockedReason": "这个手环运行的是 WHOOP 固件 50.43:它可以连接并响应应用,但在手环上没有 WHOOP 签名的会员令牌之前,可能不会发送任何记录或实时心率。这可能是收不到数据的原因之一。OpenStrap 无法签发这个令牌。已保存在这里的所有数据都是安全的。", "bandStatusFirmwareLockedFix": "如果是固件的原因,应用无法更改,手环重新发送记录后此提示会自动消失", + "settingsSleepHmmRowTitle": "实验性睡眠分期 (HMM)", + "@settingsSleepHmmRowTitle": { + "description": "Title of the experimental HMM sleep staging toggle in Settings." + }, + "settingsSleepHmmRowSub": "研究算法,非医疗设备。默认关闭。", + "@settingsSleepHmmRowSub": { + "description": "Subtitle of the experimental HMM sleep staging toggle in Settings." + }, "supplementSmartWindowMinutes": "起床时间前 {m} 分钟", "supplementGoalValue": "目标 {target}", "supplementOfCountUnit": "共 {n} {unit}", diff --git a/lib/state/app_state.dart b/lib/state/app_state.dart index 79d9fb62a..75516226c 100644 --- a/lib/state/app_state.dart +++ b/lib/state/app_state.dart @@ -572,6 +572,7 @@ class AppState extends ChangeNotifier { // truth for every network call — announcements, OTA, telemetry, import). healthSyncEnabled = prefs.getBool(_kHealthSync) ?? false; phoneStepsEnabled = prefs.getBool(_kPhoneSteps) ?? false; + sleepHmmStagesEnabled = prefs.getBool(kSleepHmmStagesPref) ?? false; // Pull early without delaying launch. syncPhoneSteps queues a fresh light // derive AFTER the sensor rows land, including when an earlier band pass // already finished. The screen must not wait for another BLE drain. @@ -831,6 +832,41 @@ class AppState extends ChangeNotifier { // switch from callers that never see this class. static const String _kHealthSync = kHealthSyncPref; + /// EXPERIMENTAL, default off: the derivation engine re-stages the sleep + /// window with the HMM classifier (it reads the pref itself on every pass). + bool sleepHmmStagesEnabled = false; + + /// Toggle the experimental HMM sleep staging. The field moves only once the + /// pref write is accepted, since the engine reads the pref: a failed write + /// leaves the switch showing what the engine will actually use. Then every + /// day still on disk is re-derived, so the switch shows up on recent nights + /// rather than only on the next one. + Future setSleepHmmStages(bool on) async { + bool saved; + try { + final prefs = await SharedPreferences.getInstance(); + saved = await prefs.setBool(kSleepHmmStagesPref, on); + } catch (e) { + _log('[settings] sleep HMM switch not saved: $e'); + saved = false; + } + if (!saved) return false; + sleepHmmStagesEnabled = on; + notifyListeners(); + // run(force: true) skips finalized nights; rederiveDays does not. + unawaited(() async { + try { + if (!await rederiveDays(await substrateDays())) { + _log('[settings] sleep HMM re-derive failed; finalized nights keep ' + 'their old stager until Re-analyze data'); + } + } catch (e) { + _log('[settings] sleep HMM re-derive failed: $e'); + } + }()); + return true; + } + /// "Apple Health" (iOS) or "Health Connect" (Android). String get healthStoreName => HealthExporter.storeName; bool get healthIsApple => HealthExporter.isApple; @@ -1552,6 +1588,7 @@ class AppState extends ChangeNotifier { telemetryConsent = false; healthShareConsent = false; consentChosen = false; + sleepHmmStagesEnabled = false; TelemetryService.instance.applyConsent(false); HealthUploader.instance.deviceId = null; // maybeUpload bails without one deviceId = ''; @@ -2754,8 +2791,10 @@ class AppState extends ChangeNotifier { /// Force-derive [days] (a wearable was enabled, disabled or switched), then /// refresh. Waits out a pass already running rather than dropping the ask. - Future rederiveDays(Set days) async { - if (days.isEmpty) return; + /// False when the pass threw or any day failed (logged), so a caller that + /// owes the user more than a log line can tell. + Future rederiveDays(Set days) async { + if (days.isEmpty) return true; while (_derive.running) { await Future.delayed(const Duration(milliseconds: 250)); } @@ -2764,10 +2803,15 @@ class AppState extends ChangeNotifier { // between, so this call cannot hit runDays' "already running" return. try { await _derive.runDays(_profile, days, force: true); + // runDays swallows a failing day and counts it instead. Read the count + // before any further await: another pass resets it as it starts. + final failedDays = _derive.lastRunFailedDays; await LocalDb.refreshComputeFreshness(); bumpInsights(); + return failedDays == 0; } catch (e) { _log('[derive] wearable re-derive failed: $e'); + return false; } } diff --git a/lib/ui2/profile/settings.dart b/lib/ui2/profile/settings.dart index 81f088ecf..13e3e5b32 100644 --- a/lib/ui2/profile/settings.dart +++ b/lib/ui2/profile/settings.dart @@ -215,6 +215,7 @@ class _MoreSettingsState extends State onRequestBackgroundExempt: app.requestIgnoreBatteryOptimizations, onOpenOemAutostart: app.openOemAutostartSettings, phoneSteps: app.phoneStepsEnabled, + sleepHmm: app.sleepHmmStagesEnabled, telemetry: app.telemetryConsent, barcodeLookup: _barcode, // Shown when the build has the feature OR when this install already @@ -253,6 +254,8 @@ class _MoreSettingsState extends State onTogglePhoneSteps: () => app.phoneStepsEnabled ? app.disablePhoneSteps() : app.requestPhoneSteps(), + onToggleSleepHmm: () => + app.setSleepHmmStages(!app.sleepHmmStagesEnabled), onToggleTelemetry: () => app.setTelemetryConsent(!app.telemetryConsent), onToggleBarcodeLookup: () => _toggleBarcode(c), onToggleHealthShare: () => _toggleHealthShare(c, app), @@ -573,6 +576,9 @@ class MoreSettingsView extends StatelessWidget { final ClockFormat clockFormat; final bool phoneSteps, telemetry, barcodeLookup, cycleTracking; + /// EXPERIMENTAL HMM sleep staging (PR #628 review) — off by default. + final bool sleepHmm; + /// The live-workout HR-zone-crossing haptic. Off by default; [zoneAlertZone] /// (1..5) is only meaningful — and only drawn — while this is on. final bool zoneAlertEnabled; @@ -634,6 +640,7 @@ class MoreSettingsView extends StatelessWidget { onCycleAppearance, onCycleClockFormat, onTogglePhoneSteps, + onToggleSleepHmm, onToggleTelemetry, onToggleBarcodeLookup, onToggleCycleTracking, @@ -656,6 +663,7 @@ class MoreSettingsView extends StatelessWidget { this.onRequestBackgroundExempt, this.onOpenOemAutostart, this.phoneSteps = false, + this.sleepHmm = false, this.healthSync = false, this.healthState = HealthLinkState.unknown, this.healthStore = 'Apple Health', @@ -684,6 +692,7 @@ class MoreSettingsView extends StatelessWidget { this.onCycleAppearance, this.onCycleClockFormat, this.onTogglePhoneSteps, + this.onToggleSleepHmm, this.onToggleTelemetry, this.onToggleBarcodeLookup, this.onToggleCycleTracking, @@ -787,6 +796,15 @@ class MoreSettingsView extends StatelessWidget { 'What may interrupt you, quiet hours, and off ' 'switches for all of them', onTap: onNotifications), + SetRow(LucideIcons.moonStar, C.indigo, + l?.settingsSleepHmmRowTitle ?? + 'Experimental sleep staging (HMM)', + sub: l?.settingsSleepHmmRowSub ?? + 'Research algorithm, not a medical device. Off by ' + 'default; applies from the next sync', + value: sleepHmm ? on : off, + chevron: false, + onTap: onToggleSleepHmm), SetRow(LucideIcons.ruler, C.blue, l?.settingsUnitsRowTitle ?? 'Units', value: units, onTap: onCycleUnits), diff --git a/test/backup/settings_audit_guard_test.dart b/test/backup/settings_audit_guard_test.dart index 30ccf40b6..fb59ed372 100644 --- a/test/backup/settings_audit_guard_test.dart +++ b/test/backup/settings_audit_guard_test.dart @@ -35,6 +35,7 @@ const _mustTravel = { 'notif_relay_enabled', 'notif_relay_packages', 'ui.shell_tab.v2', 'ui.recap_range', 'ui.workouts_range', 'ui.wearable_show_estimates', 'ui.wearable_side_by_side', + 'sleep_hmm_stages', 'rough_night.ask', 'rough_night.dismissed', // Existing history/dedupe state travels to avoid repeated alerts/imports. 'ai.journal_done_day', 'last_recovery_notif_day', 'last_stepgoal_day', @@ -115,6 +116,7 @@ const _indirectKeys = >{ 'health_import_profile_at', 'health_import_workouts_at'], 'lib/notify/notification_prefs.dart:_kBatteryPct': ['notif_battery_pct'], 'lib/state/app_state.dart:_kHealthSync': ['health_sync'], + 'lib/state/app_state.dart:kSleepHmmStagesPref': ['sleep_hmm_stages'], 'lib/sync/paired_device.dart:_kWornOn': ['paired_worn_on'], 'lib/sync/paired_device.dart:key': [ 'paired_remote_id', 'paired_serial', 'paired_generation'], diff --git a/test/sleep_cycle_continuity_test.dart b/test/sleep_cycle_continuity_test.dart new file mode 100644 index 000000000..5c591238a --- /dev/null +++ b/test/sleep_cycle_continuity_test.dart @@ -0,0 +1,329 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/compute/onehz_pipeline.dart'; +import 'package:openstrap_edge/compute/sleep_pipeline_hmm.dart'; +import 'package:openstrap_edge/state/app_state.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +// ignore: depend_on_referenced_packages +import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + hmmPipelineMain(); + reviewFixesMain(); + test('Arousals do not trigger a full cycle reset and maintain stage continuity', () { + final analyzer = SleepStageAnalyzer(); + + // Baseline erzeugen (HR ~ 60, RMSSD ~ 40) + final baseline = List.generate(240, (i) => {'hr': 60.0, 'rmssd': 40.0}); + analyzer.computeBaseline(baseline); + + // Testsequenz: Deep Sleep -> Kurzes Arousal (Wake) -> Deep Sleep + final nightData = >[]; + + // Block 1: Stable Deep Sleep + nightData.addAll(List.generate(20, (i) => {'hr': 55.0, 'rmssd': 50.0})); + + // Block 2: Short Arousal (1 Epoche) + nightData.add({'hr': 80.0, 'rmssd': 20.0}); + + // Block 3: Return to Deep Sleep + nightData.addAll(List.generate(20, (i) => {'hr': 55.0, 'rmssd': 50.0})); + + final states = analyzer.viterbiDecode(nightData); + + // Erwartung: Nach dem Arousal kehrt das System direkt wieder zu NREM Deep zurück, + // ohne stundenlang in NREM Light "festzustecken". + expect(states[19], SleepState.nremDeep); + expect(states[21], SleepState.nremDeep); + }); + + group('observations the decoder cannot trust', () { + SleepStageAnalyzer baselined() { + final a = SleepStageAnalyzer(); + a.computeBaseline(List.generate(240, (_) => {'hr': 60.0, 'rmssd': 40.0})); + return a; + } + + List> deepAround(List> middle) => [ + ...List.generate(20, (_) => {'hr': 55.0, 'rmssd': 50.0}), + ...middle, + ...List.generate(20, (_) => {'hr': 55.0, 'rmssd': 50.0}), + ]; + + test('a contact-lost stretch is bridged, not scored as wake', () { + final night = deepAround(List.generate( + 10, (_) => {'hr': 95.0, 'rmssd': 12.0, 'isContactLost': true})); + final states = baselined().viterbiDecode(night); + for (var t = 20; t < 30; t++) { + expect(states[t], SleepState.nremDeep, reason: 'epoch $t'); + } + }); + + test('implausible and non-finite HR get the neutral emission', () { + for (final bad in [250.0, double.nan, double.infinity]) { + final night = deepAround( + List.generate(10, (_) => {'hr': bad, 'rmssd': 12.0})); + final states = baselined().viterbiDecode(night); + for (var t = 20; t < 30; t++) { + expect(states[t], SleepState.nremDeep, reason: 'hr=$bad epoch $t'); + } + } + }); + + test('the same values without the flag still read as wake', () { + final night = deepAround( + List.generate(10, (_) => {'hr': 95.0, 'rmssd': 12.0})); + final states = baselined().viterbiDecode(night); + expect(states[25], SleepState.wake); + }); + + test('baseline skips missing and non-finite values instead of throwing', () { + final a = SleepStageAnalyzer(); + a.computeBaseline([ + {'hr': null, 'rmssd': 40.0}, + {'rmssd': 40.0}, + {'hr': double.nan, 'rmssd': double.nan}, + ...List.generate(20, (_) => {'hr': 60.0, 'rmssd': 40.0}), + ]); + expect(a.hrMinNight, 60.0); + expect(a.rmssdMeanNight, 40.0); + }); + }); +} + +/// The opt-in path through [deriveDayBundle]: a quiet first half and an +/// aroused second half must re-stage (the decoder actually ran on epoch-aligned +/// beats), and a second the band did not watch stays unobserved. +void hmmPipelineMain() { + test('opt-in HMM re-stages a measured night and keeps unobserved seconds', () { + const t0 = 1780000000; + const n = 4 * 3600; + final tsSec = [for (var s = 0; s < n; s++) t0 + s]; + final hr = [for (var s = 0; s < n; s++) s < n ~/ 2 ? 55 : 80]; + final rrTs = [], rrMs = []; + var t = t0 * 1000.0; + var i = 0; + while (t < (t0 + n) * 1000.0) { + final aroused = t >= (t0 + n ~/ 2) * 1000.0; + final rr = aroused + ? 750.0 + 2.0 * ((i % 3) - 1) + : 1090.0 + 40.0 * ((i % 5) - 2); + t += rr; + rrTs.add(t); + rrMs.add(rr); + i++; + } + final stages = List.filled(n, 'light'); + for (var s = 100; s < 160; s++) { + stages[s] = 'unobserved'; + } + Map run(bool hmm) => deriveDayBundle(DayBundleInput( + date: '2026-06-01', + dayTsSec: tsSec, + dayHr: hr, + sleepTsSec: tsSec, + sleepHr: hr, + sleepRrTsMs: rrTs, + sleepRrMs: rrMs, + sleepSkinTemp: List.filled(n, 0), + sleepJson: const {}, + hypnoStages: stages, + sleepOnsetSec: t0, + sleepOffsetSec: t0 + n, + profile: const {'age': 30, 'sex': 'm', 'weight': 75, 'height': 178}, + useHmmStages: hmm, + ).toJson()); + List seq(Map b) => [ + for (final s in ((b['series'] as Map)['hypnogram'] as List).cast()) + s['stage'] as String, + ]; + expect(seq(run(false)).toSet(), {'light', 'unobserved'}); + final on = seq(run(true)); + expect(on, contains('unobserved')); + expect(on.toSet().difference({'light', 'unobserved'}), isNotEmpty); + }); +} + +/// A 4 h night: a quiet first half and an aroused second half, beats for the +/// whole night unless [rrFromSec] starts them later, and substrate rows +/// missing over [gap] (seconds into the night) when given. +const _t0 = 1780000000; +const _n = 4 * 3600; + +DayBundleInput _night({ + int rrFromSec = 0, + (int, int)? gap, + Map sleepJson = const {}, + List? stages, + bool hmm = true, +}) { + bool missing(int s) => gap != null && s >= gap.$1 && s < gap.$2; + final tsSec = [ + for (var s = 0; s < _n; s++) + if (!missing(s)) _t0 + s + ]; + final hr = [for (final t in tsSec) t - _t0 < _n ~/ 2 ? 55 : 80]; + final rrTs = [], rrMs = []; + var t = (_t0 + rrFromSec) * 1000.0; + var i = 0; + while (t < (_t0 + _n) * 1000.0) { + final aroused = t >= (_t0 + _n ~/ 2) * 1000.0; + final rr = aroused + ? 750.0 + 2.0 * ((i % 3) - 1) + : 1090.0 + 40.0 * ((i % 5) - 2); + t += rr; + if (!missing(t ~/ 1000 - _t0)) { + rrTs.add(t); + rrMs.add(rr); + } + i++; + } + return DayBundleInput( + date: '2026-06-01', + dayTsSec: tsSec, + dayHr: hr, + sleepTsSec: tsSec, + sleepHr: hr, + sleepRrTsMs: rrTs, + sleepRrMs: rrMs, + sleepSkinTemp: List.filled(tsSec.length, 0), + sleepJson: sleepJson, + hypnoStages: stages ?? List.filled(_n, 'light'), + sleepOnsetSec: _t0, + sleepOffsetSec: _t0 + _n, + profile: const {'age': 30, 'sex': 'm', 'weight': 75, 'height': 178}, + useHmmStages: hmm, + ); +} + +/// The stored per-second labels, expanded back from the hypnogram segments. +List _labels(Map bundle) { + final out = List.filled(_n, '?'); + for (final seg + in ((bundle['series'] as Map)['hypnogram'] as List).cast()) { + for (var t = seg['start'] as int; t < (seg['end'] as int); t++) { + out[t - _t0] = seg['stage'] as String; + } + } + return out; +} + +class _RefusingStore extends SharedPreferencesStorePlatform { + @override + Future clear() async => false; + @override + Future> getAll() async => {}; + @override + Future remove(String key) async => false; + @override + Future setValue(String valueType, String key, Object value) async => + false; +} + +void reviewFixesMain() { + group('PR #628 review', () { + test('no RMSSD baseline in the first 120 min keeps the shipped labels', () { + // Beats only from minute 150: the baseline window holds none, so every + // emission would be neutral and the decoder would read wake. + final b = deriveDayBundle(_night(rrFromSec: 150 * 60).toJson()); + expect(_labels(b).toSet(), {'light'}); + expect((b['sleep'] as Map).containsKey('stager_source'), isFalse); + }); + + test('a gap in the substrate is placed by clock, and its epochs abstain', + () { + // 20 minutes with no rows inside the quiet half. Paired by row index the + // lengths no longer matched and the night was silently never re-staged. + final b = deriveDayBundle(_night(gap: (1800, 3000)).toJson()); + final l = _labels(b); + expect(l.toSet().difference({'light'}), isNotEmpty, + reason: 'a sparse night is re-staged'); + // No heart rate, no beats: those epochs keep the shipped label. + for (var s = 1830; s < 2970; s++) { + expect(l[s], 'light', reason: 'second $s has no observation'); + } + // And the aroused half is still where the clock says it is. + expect(l.sublist(_n ~/ 2 + 600).where((x) => x == 'wake').length, + greaterThan((_n ~/ 2 - 600) * 0.8)); + expect(l.sublist(600, 1800).where((x) => x == 'wake'), isEmpty); + }); + + test('the night\'s accounting comes from the new labels, tagged hmm', () { + final stages = List.filled(_n, 'light'); + for (var s = 100; s < 160; s++) { + stages[s] = 'unobserved'; + } + final b = deriveDayBundle(_night( + stages: stages, + sleepJson: const { + 'window': {'onset_ms': 0}, + 'tst_sec': _n - 60, + 'waso_sec': 0, + 'in_bed_sec': _n, + 'unobserved_sec': 60, + 'efficiency_pct': 100.0, + 'nrem_sec': _n - 60, + 'light_sec': _n - 60, + 'deep_sec': 0, + 'rem_sec': 0, + 'wake_sec': 0, + 'confidence': 0.8, + }, + ).toJson()); + final sleep = b['sleep'] as Map; + expect(sleep['stager_source'], 'hmm'); + final acc = (sleep['accounting'] as Map)['value'] as Map; + final l = _labels(b); + int count(Set s) => l.where(s.contains).length; + final tst = count({'light', 'deep', 'rem'}); + expect(acc['tst_sec'], tst); + expect(acc['wake_sec'], count({'wake'})); + expect(acc['light_sec'] + acc['deep_sec'] + acc['rem_sec'], tst); + expect(acc['efficiency_pct'], closeTo(100.0 * tst / (_n - 60), 1e-9), + reason: 'not the original stager\'s 100 %'); + expect(acc['efficiency_pct'], lessThan(100.0)); + }); + + test('switch off: the bundle is exactly what it was', () { + final b = deriveDayBundle(_night(hmm: false).toJson()); + expect(_labels(b).toSet(), {'light'}); + expect((b['sleep'] as Map).containsKey('stager_source'), isFalse); + }); + + test('no decode ever yields NaN or an infinite score', () { + final a = SleepStageAnalyzer() + ..computeBaseline([ + for (var i = 0; i < 50; i++) {'hr': 60.0, 'rmssd': 40.0} + ]); + // REM straight into a deep-looking stretch: the forbidden move. + final states = a.viterbiDecode([ + for (var i = 0; i < 20; i++) {'hr': 66.0, 'rmssd': 44.0}, + for (var i = 0; i < 20; i++) {'hr': 50.0, 'rmssd': 60.0}, + for (var i = 0; i < 5; i++) {'hr': double.nan, 'rmssd': double.infinity}, + ]); + expect(states, hasLength(45)); + for (var t = 1; t < states.length; t++) { + expect( + states[t - 1] == SleepState.rem && states[t] == SleepState.nremDeep, + isFalse, + reason: 'epoch $t'); + } + }); + + test('a refused pref write leaves the switch showing what the engine reads', + () async { + SharedPreferences.setMockInitialValues({}); + final real = SharedPreferencesStorePlatform.instance; + SharedPreferencesStorePlatform.instance = _RefusingStore(); + SharedPreferences.resetStatic(); + addTearDown(() { + SharedPreferencesStorePlatform.instance = real; + SharedPreferences.resetStatic(); + }); + final app = AppState.forTesting(); + addTearDown(app.dispose); + expect(await app.setSleepHmmStages(true), isFalse); + expect(app.sleepHmmStagesEnabled, isFalse); + }); + }); +} diff --git a/test/ui2_gallery_test.dart b/test/ui2_gallery_test.dart index d9682ff2f..ede12b97f 100644 --- a/test/ui2_gallery_test.dart +++ b/test/ui2_gallery_test.dart @@ -56,6 +56,8 @@ void main() { devMode: true, onGallery: () => opened = true, ))); + await tester.scrollUntilVisible(find.text('Developer'), 300, + scrollable: find.byType(Scrollable).first); expect(find.text('Developer'), findsOneWidget); await tester.ensureVisible(find.text('Component gallery')); await tester.pumpAndSettle();