diff --git a/lib/compute/derivation_engine.dart b/lib/compute/derivation_engine.dart index 36c3c9435..76f175f0d 100644 --- a/lib/compute/derivation_engine.dart +++ b/lib/compute/derivation_engine.dart @@ -3105,10 +3105,27 @@ 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 { + return (await SharedPreferences.getInstance()) + .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 +3397,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. @@ -5955,6 +5973,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..7fa41bdfe 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,72 @@ 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 — used by the experimental + /// HMM re-staging path in [deriveDayBundle]. The stage-second totals in + /// [sleepJson] are recomputed from [stages] so the stored hypnogram and the + /// displayed totals always describe the same night. + DayBundleInput withHypnoStages(List stages) { + var light = 0, deep = 0, rem = 0, wake = 0; + for (final s in stages) { + switch (s) { + case 'light': light++; + case 'deep': deep++; + case 'rem': rem++; + case 'wake': wake++; + } + } + final nrem = light + deep; + final tst = nrem + rem; + final json = {...sleepJson}; + if (json.containsKey('tst_sec')) json['tst_sec'] = tst; + if (json.containsKey('waso_sec')) json['waso_sec'] = wake; + if (json.containsKey('nrem_sec')) json['nrem_sec'] = nrem; + if (json.containsKey('light_sec')) json['light_sec'] = light; + if (json.containsKey('deep_sec')) json['deep_sec'] = deep; + if (json.containsKey('rem_sec')) json['rem_sec'] = rem; + if (json.containsKey('wake_sec')) json['wake_sec'] = wake; + 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 +616,54 @@ 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 instead of the coordinator's + // heuristic labels. RR intervals are windowed into per-second RMSSD via + // the same cleaned-NN helpers the pipeline itself uses; the decode is only + // applied when it covers the full window and has usable observations, + // otherwise the shipped labels stay. + if (d.useHmmStages && + d.hypnoStages.isNotEmpty && + d.sleepTsSec.isNotEmpty && + d.sleepTsSec.length == d.hypnoStages.length) { + 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 sleepTsSec. + 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]; + // Per-second RMSSD: 60 s trailing window of cleaned NN intervals, + // stamped at the window's last beat second. Missing coverage -> 0 + // (scored as neutral/unusable by the classifier). + final rmssdPerSec = _rmssdPerSecond( + corrected.nn, + nnTimes, + d.sleepTsSec, + windowSec: 60, + ); + final epochs = >[ + for (var i = 0; i < d.sleepTsSec.length; i++) + { + 'ts': d.sleepTsSec[i], + 'hr': i < d.sleepHr.length ? d.sleepHr[i] : 0, + 'rmssd': rmssdPerSec[i], + 'motion_artifact': false, + }, + ]; + final hmmStages = _classifySleepStagesHMM(epochs); + if (hmmStages != null && hmmStages.length == d.hypnoStages.length) { + // A second the band did not watch stays unobserved; the decoder only + // relabels seconds that were actually measured. + d = d.withHypnoStages([ + for (var i = 0; i < hmmStages.length; i++) + d.hypnoStages[i] == 'unobserved' ? 'unobserved' : hmmStages[i], + ]); + } + } // ── HR over the DAY (for the curve, strain zones, dip day-side) ─────────── final dayHr = [for (final h in d.dayHr) h.toDouble()]; @@ -2346,3 +2463,103 @@ int? _medianGapSec(List tsSec, {int minGapSec = 1}) { ]..sort(); return gaps.isEmpty ? null : gaps[gaps.length ~/ 2]; } + +/// 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; + final window = nn.sublist(lo, hi); + var sumSq = 0.0; + for (var k = 1; k < window.length; k++) { + final d = window[k] - window[k - 1]; + sumSq += d * d; + } + out[i] = math.sqrt(sumSq / (window.length - 1)); + } + return out; +} + +/// EXPERIMENTAL HMM/Viterbi re-staging (gated by [DayBundleInput.useHmmStages]). +/// +/// [epochData] is per-second sleep-window records with `ts` (epoch sec), `hr`, +/// and `rmssd` (already windowed/cleaned, see [deriveDayBundle]). Returns +/// per-second stage labels, or null when the night has too few usable +/// observations to stage honestly — the caller then keeps the supplied labels. +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); + // An unmeasured night must not decode as wake: with no usable observation + // every state ties and wake's self-transition wins. Bail out instead. + 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). + 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); + 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++) label(states[idx[epochOf[i]]!])]; +} diff --git a/lib/compute/sleep_pipeline_hmm.dart b/lib/compute/sleep_pipeline_hmm.dart new file mode 100644 index 000000000..c7f526fca --- /dev/null +++ b/lib/compute/sleep_pipeline_hmm.dart @@ -0,0 +1,182 @@ +// 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), + SleepState.nremDeep: log(0.00), + 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; + } + } + + 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 ebea56d52..39ca3b7a8 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -3710,7 +3710,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.", @@ -3718,7 +3722,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", @@ -3788,5 +3796,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; gilt ab dem nächsten Sync", + "@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 d667ff68e..b826d3468 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -998,151 +998,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": { @@ -17081,7 +17081,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.", @@ -17089,32 +17093,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" @@ -17155,5 +17187,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; applies from the next sync", + "@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 add8dee42..1af2569e8 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -3008,7 +3008,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.", @@ -3016,7 +3020,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", @@ -3488,5 +3496,13 @@ "dayStrainWornAsOf": "Llevada, a las {time}", "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" + "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; se aplica desde la próxima sincronización", + "@settingsSleepHmmRowSub": { + "description": "Subtitle of the experimental HMM sleep staging toggle in Settings." + } } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 64765d824..d4bf8035e 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -2979,7 +2979,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.", @@ -2987,7 +2991,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", @@ -3488,5 +3496,13 @@ "dayStrainWornAsOf": "Porté, à {time}", "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" + "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 ; s'applique dès la prochaine synchronisation", + "@settingsSleepHmmRowSub": { + "description": "Subtitle of the experimental HMM sleep staging toggle in Settings." + } } diff --git a/lib/l10n/app_hi.arb b/lib/l10n/app_hi.arb index 2017e0d3b..532bccfc4 100644 --- a/lib/l10n/app_hi.arb +++ b/lib/l10n/app_hi.arb @@ -2979,7 +2979,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 सेटिंग में फिर से साइन इन करें।", @@ -2987,7 +2991,11 @@ "welcomeSettingsRestored": "{n} सेटिंग बहाल हुईं", "@welcomeSettingsRestored": { "description": "Import report: number of restored app preferences", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "strengthCustomWeight": "कस्टम वज़न", "strengthEnterValue": "एक मान दर्ज करें", @@ -3488,5 +3496,13 @@ "dayStrainWornAsOf": "पहना, {time} तक का आंकड़ा", "bandStatusFirmwareLockedTitle": "बैंड का फ़र्मवेयर शायद उसका डेटा रोक रहा है", "bandStatusFirmwareLockedReason": "यह बैंड WHOOP फ़र्मवेयर 50.43 पर चल रहा है, जो कनेक्ट होकर ऐप को जवाब दे सकता है, लेकिन जब तक बैंड पर WHOOP द्वारा साइन किया गया सदस्यता टोकन न हो, तब तक हो सकता है कि कोई रिकॉर्डिंग या लाइव हृदय गति न भेजे। डेटा न आने का एक संभावित कारण यह हो सकता है। OpenStrap वह टोकन जारी नहीं कर सकता। यहाँ पहले से सहेजा गया सब कुछ सुरक्षित है।", - "bandStatusFirmwareLockedFix": "अगर वजह फ़र्मवेयर है, तो ऐप इसे बदल नहीं सकता और बैंड के फिर से रिकॉर्डिंग भेजते ही यह संदेश हट जाएगा" + "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." + } } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 59d75705d..b27c502e2 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -8069,7 +8069,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 остаются в защищённом хранилище и не включены в резервную копию. Войдите снова в настройках ИИ, чтобы пользоваться тренером на этом телефоне.", @@ -8077,7 +8081,11 @@ "welcomeSettingsRestored": "Восстановлено настроек: {n}", "@welcomeSettingsRestored": { "description": "Import report: number of restored app preferences", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "strengthCustomWeight": "Свой вес", "strengthEnterValue": "Введите значение", @@ -8311,5 +8319,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 a083fd8b7..5288b363a 100644 --- a/lib/l10n/app_th.arb +++ b/lib/l10n/app_th.arb @@ -16450,7 +16450,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 เพื่อใช้โค้ชบนโทรศัพท์เครื่องนี้", @@ -16458,7 +16462,11 @@ "welcomeSettingsRestored": "กู้คืนการตั้งค่าแล้ว {n} รายการ", "@welcomeSettingsRestored": { "description": "Import report: number of restored app preferences", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "strengthCustomWeight": "น้ำหนักที่กำหนดเอง", "strengthEnterValue": "ป้อนค่า", @@ -16935,5 +16943,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 84749ffb7..a7c6aa47a 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -2979,7 +2979,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 设置中重新登录,以便在此手机上使用教练。", @@ -2987,7 +2991,11 @@ "welcomeSettingsRestored": "已恢复 {n} 项设置", "@welcomeSettingsRestored": { "description": "Import report: number of restored app preferences", - "placeholders": {"n": {"type": "int"}} + "placeholders": { + "n": { + "type": "int" + } + } }, "strengthCustomWeight": "自定义重量", "strengthEnterValue": "输入数值", @@ -3488,5 +3496,13 @@ "dayStrainWornAsOf": "佩戴(截至 {time} 的数据)", "bandStatusFirmwareLockedTitle": "手环固件可能正在扣留它的数据", "bandStatusFirmwareLockedReason": "这个手环运行的是 WHOOP 固件 50.43:它可以连接并响应应用,但在手环上没有 WHOOP 签名的会员令牌之前,可能不会发送任何记录或实时心率。这可能是收不到数据的原因之一。OpenStrap 无法签发这个令牌。已保存在这里的所有数据都是安全的。", - "bandStatusFirmwareLockedFix": "如果是固件的原因,应用无法更改,手环重新发送记录后此提示会自动消失" + "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." + } } diff --git a/lib/state/app_state.dart b/lib/state/app_state.dart index 79d9fb62a..33e2fed6d 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,18 @@ 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; applies from the next derive. + Future setSleepHmmStages(bool on) async { + sleepHmmStagesEnabled = on; + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool(kSleepHmmStagesPref, on); + notifyListeners(); + } + /// "Apple Health" (iOS) or "Health Connect" (Android). String get healthStoreName => HealthExporter.storeName; bool get healthIsApple => HealthExporter.isApple; @@ -1552,6 +1565,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 = ''; 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..f715bed6e --- /dev/null +++ b/test/sleep_cycle_continuity_test.dart @@ -0,0 +1,139 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/compute/onehz_pipeline.dart'; +import 'package:openstrap_edge/compute/sleep_pipeline_hmm.dart'; + +void main() { + hmmPipelineMain(); + 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); + }); +} 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();