|
| 1 | +/** |
| 2 | + * Temporal Smoothing for Sleep Stage Classification |
| 3 | + * |
| 4 | + * Implements a Hidden Markov Model (HMM) Forward Algorithm to prevent |
| 5 | + * rapid state switching ("jitter") in sleep stage classification. |
| 6 | + * |
| 7 | + * Key features: |
| 8 | + * 1. HMM Forward Algorithm - Uses transition matrix to smooth predictions |
| 9 | + * 2. Minimum Dwell Time - Prevents transitions within N seconds of last change |
| 10 | + * 3. Hysteresis - Requires higher confidence to exit a state than to enter |
| 11 | + * 4. Exponential smoothing of raw probabilities before HMM |
| 12 | + * |
| 13 | + * Based on sleep staging literature: |
| 14 | + * - Radha et al. 2019: Temporal context is critical for sleep staging |
| 15 | + * - Standard polysomnography uses 30-second epochs with transition rules |
| 16 | + */ |
| 17 | + |
| 18 | +import type { SleepStage3, Stage3Probabilities } from './remOptimizedClassifier'; |
| 19 | + |
| 20 | +// ============================================================================ |
| 21 | +// Configuration Constants |
| 22 | +// ============================================================================ |
| 23 | + |
| 24 | +/** Minimum time (ms) to stay in a state before allowing transition */ |
| 25 | +const MIN_DWELL_TIME_MS = 60000; // 60 seconds - prevents rapid flickering |
| 26 | + |
| 27 | +/** Minimum time in REM before allowing exit (REM cycles are typically 10-20 min) */ |
| 28 | +const MIN_REM_DWELL_TIME_MS = 120000; // 2 minutes |
| 29 | + |
| 30 | +/** Exponential smoothing factor for raw probabilities (0-1, higher = more smoothing) */ |
| 31 | +const PROBABILITY_SMOOTHING_ALPHA = 0.3; |
| 32 | + |
| 33 | +/** Confidence threshold multiplier for exiting current state (hysteresis) */ |
| 34 | +const EXIT_THRESHOLD_MULTIPLIER = 1.3; |
| 35 | + |
| 36 | +/** Minimum probability difference required to change states */ |
| 37 | +const MIN_PROBABILITY_DELTA = 0.15; |
| 38 | + |
| 39 | +// ============================================================================ |
| 40 | +// Types |
| 41 | +// ============================================================================ |
| 42 | + |
| 43 | +interface SmootherState { |
| 44 | + beliefState: Stage3Probabilities; |
| 45 | + currentStage: SleepStage3; |
| 46 | + stageEntryTime: number; |
| 47 | + smoothedProbabilities: Stage3Probabilities; |
| 48 | + transitionCount: number; |
| 49 | + lastTransitionTime: number; |
| 50 | +} |
| 51 | + |
| 52 | +export interface SmoothingResult { |
| 53 | + stage: SleepStage3; |
| 54 | + probabilities: Stage3Probabilities; |
| 55 | + confidence: number; |
| 56 | + wasSmoothed: boolean; |
| 57 | + dwellTimeMs: number; |
| 58 | + transitionBlocked: boolean; |
| 59 | + blockReason: string | null; |
| 60 | +} |
| 61 | + |
| 62 | +// ============================================================================ |
| 63 | +// Module State |
| 64 | +// ============================================================================ |
| 65 | + |
| 66 | +let state: SmootherState = { |
| 67 | + beliefState: { awake: 0.5, nrem: 0.4, rem: 0.1 }, |
| 68 | + currentStage: 'awake', |
| 69 | + stageEntryTime: Date.now(), |
| 70 | + smoothedProbabilities: { awake: 0.5, nrem: 0.4, rem: 0.1 }, |
| 71 | + transitionCount: 0, |
| 72 | + lastTransitionTime: Date.now(), |
| 73 | +}; |
| 74 | + |
| 75 | +// ============================================================================ |
| 76 | +// Public API |
| 77 | +// ============================================================================ |
| 78 | + |
| 79 | +/** |
| 80 | + * Reset the temporal smoother state. Call when starting a new sleep session. |
| 81 | + */ |
| 82 | +export function resetTemporalSmoother(): void { |
| 83 | + const now = Date.now(); |
| 84 | + state = { |
| 85 | + beliefState: { awake: 0.5, nrem: 0.4, rem: 0.1 }, |
| 86 | + currentStage: 'awake', |
| 87 | + stageEntryTime: now, |
| 88 | + smoothedProbabilities: { awake: 0.5, nrem: 0.4, rem: 0.1 }, |
| 89 | + transitionCount: 0, |
| 90 | + lastTransitionTime: now, |
| 91 | + }; |
| 92 | +} |
| 93 | + |
| 94 | +/** |
| 95 | + * Get current smoother state for debugging/display. |
| 96 | + */ |
| 97 | +export function getSmootherState(): Readonly<SmootherState> { |
| 98 | + return { ...state }; |
| 99 | +} |
| 100 | + |
| 101 | +/** |
| 102 | + * Apply temporal smoothing to sleep stage probabilities using HMM Forward Algorithm. |
| 103 | + * |
| 104 | + * @param rawProbabilities - Point-in-time probabilities from classifier |
| 105 | + * @param transitionMatrix - T[from][to] transition probabilities |
| 106 | + * @param minutesSinceSleepStart - Time context for REM likelihood |
| 107 | + * @returns Smoothed classification result |
| 108 | + */ |
| 109 | +export function smoothSleepStage( |
| 110 | + rawProbabilities: Stage3Probabilities, |
| 111 | + transitionMatrix: Record<SleepStage3, Record<SleepStage3, number>>, |
| 112 | + minutesSinceSleepStart: number |
| 113 | +): SmoothingResult { |
| 114 | + const now = Date.now(); |
| 115 | + const stages: SleepStage3[] = ['awake', 'nrem', 'rem']; |
| 116 | + |
| 117 | + const smoothedRaw = applyExponentialSmoothing(rawProbabilities, state.smoothedProbabilities); |
| 118 | + state.smoothedProbabilities = smoothedRaw; |
| 119 | + |
| 120 | + const hmmProbabilities = applyHMMForward(smoothedRaw, transitionMatrix); |
| 121 | + state.beliefState = hmmProbabilities; |
| 122 | + |
| 123 | + let candidateStage: SleepStage3 = 'nrem'; |
| 124 | + let maxProb = 0; |
| 125 | + for (const stage of stages) { |
| 126 | + if (hmmProbabilities[stage] > maxProb) { |
| 127 | + maxProb = hmmProbabilities[stage]; |
| 128 | + candidateStage = stage; |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + const dwellTimeMs = now - state.stageEntryTime; |
| 133 | + let transitionBlocked = false; |
| 134 | + let blockReason: string | null = null; |
| 135 | + let finalStage = candidateStage; |
| 136 | + |
| 137 | + if (candidateStage !== state.currentStage) { |
| 138 | + const minDwell = state.currentStage === 'rem' ? MIN_REM_DWELL_TIME_MS : MIN_DWELL_TIME_MS; |
| 139 | + |
| 140 | + if (dwellTimeMs < minDwell) { |
| 141 | + transitionBlocked = true; |
| 142 | + blockReason = `Dwell time ${Math.round(dwellTimeMs / 1000)}s < min ${Math.round(minDwell / 1000)}s`; |
| 143 | + finalStage = state.currentStage; |
| 144 | + } |
| 145 | + |
| 146 | + if (!transitionBlocked) { |
| 147 | + const currentProb = hmmProbabilities[state.currentStage]; |
| 148 | + const candidateProb = hmmProbabilities[candidateStage]; |
| 149 | + const requiredDelta = MIN_PROBABILITY_DELTA * EXIT_THRESHOLD_MULTIPLIER; |
| 150 | + |
| 151 | + if (candidateProb - currentProb < requiredDelta) { |
| 152 | + transitionBlocked = true; |
| 153 | + blockReason = `Probability delta ${(candidateProb - currentProb).toFixed(3)} < required ${requiredDelta.toFixed(3)}`; |
| 154 | + finalStage = state.currentStage; |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + if (!transitionBlocked && candidateStage === 'rem' && minutesSinceSleepStart < 60) { |
| 159 | + transitionBlocked = true; |
| 160 | + blockReason = `REM blocked: only ${minutesSinceSleepStart.toFixed(0)} min into sleep (need 60+)`; |
| 161 | + finalStage = state.currentStage; |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + const wasSmoothed = finalStage !== candidateStage; |
| 166 | + if (finalStage !== state.currentStage) { |
| 167 | + state.currentStage = finalStage; |
| 168 | + state.stageEntryTime = now; |
| 169 | + state.transitionCount++; |
| 170 | + state.lastTransitionTime = now; |
| 171 | + } |
| 172 | + |
| 173 | + const sortedProbs = Object.values(hmmProbabilities).sort((a, b) => b - a); |
| 174 | + const confidence = sortedProbs[0] - sortedProbs[1] + 0.3; |
| 175 | + |
| 176 | + return { |
| 177 | + stage: finalStage, |
| 178 | + probabilities: hmmProbabilities, |
| 179 | + confidence: Math.min(1, Math.max(0, confidence)), |
| 180 | + wasSmoothed, |
| 181 | + dwellTimeMs, |
| 182 | + transitionBlocked, |
| 183 | + blockReason, |
| 184 | + }; |
| 185 | +} |
| 186 | + |
| 187 | +// ============================================================================ |
| 188 | +// Internal Functions |
| 189 | +// ============================================================================ |
| 190 | + |
| 191 | +/** |
| 192 | + * Apply exponential moving average smoothing to probabilities. |
| 193 | + */ |
| 194 | +function applyExponentialSmoothing( |
| 195 | + current: Stage3Probabilities, |
| 196 | + previous: Stage3Probabilities |
| 197 | +): Stage3Probabilities { |
| 198 | + const alpha = PROBABILITY_SMOOTHING_ALPHA; |
| 199 | + return { |
| 200 | + awake: alpha * current.awake + (1 - alpha) * previous.awake, |
| 201 | + nrem: alpha * current.nrem + (1 - alpha) * previous.nrem, |
| 202 | + rem: alpha * current.rem + (1 - alpha) * previous.rem, |
| 203 | + }; |
| 204 | +} |
| 205 | + |
| 206 | +/** |
| 207 | + * Apply HMM Forward Algorithm update. |
| 208 | + * |
| 209 | + * For each state s_t: |
| 210 | + * P(s_t | observations) ∝ P(observation | s_t) × Σ[P(s_t | s_{t-1}) × P(s_{t-1})] |
| 211 | + * |
| 212 | + * Where: |
| 213 | + * - P(observation | s_t) = rawProbabilities (emission/likelihood from sensors) |
| 214 | + * - P(s_t | s_{t-1}) = transitionMatrix (learned from historical data) |
| 215 | + * - P(s_{t-1}) = beliefState (our current belief) |
| 216 | + */ |
| 217 | +function applyHMMForward( |
| 218 | + likelihoods: Stage3Probabilities, |
| 219 | + transitionMatrix: Record<SleepStage3, Record<SleepStage3, number>> |
| 220 | +): Stage3Probabilities { |
| 221 | + const stages: SleepStage3[] = ['awake', 'nrem', 'rem']; |
| 222 | + const nextBelief: Stage3Probabilities = { awake: 0, nrem: 0, rem: 0 }; |
| 223 | + |
| 224 | + for (const toStage of stages) { |
| 225 | + let prediction = 0; |
| 226 | + for (const fromStage of stages) { |
| 227 | + prediction += state.beliefState[fromStage] * transitionMatrix[fromStage][toStage]; |
| 228 | + } |
| 229 | + nextBelief[toStage] = prediction * likelihoods[toStage]; |
| 230 | + } |
| 231 | + |
| 232 | + const sum = nextBelief.awake + nextBelief.nrem + nextBelief.rem; |
| 233 | + if (sum > 0) { |
| 234 | + nextBelief.awake /= sum; |
| 235 | + nextBelief.nrem /= sum; |
| 236 | + nextBelief.rem /= sum; |
| 237 | + } else { |
| 238 | + return { awake: 0.33, nrem: 0.34, rem: 0.33 }; |
| 239 | + } |
| 240 | + |
| 241 | + return nextBelief; |
| 242 | +} |
| 243 | + |
| 244 | +// ============================================================================ |
| 245 | +// Diagnostic Functions |
| 246 | +// ============================================================================ |
| 247 | + |
| 248 | +/** |
| 249 | + * Get diagnostic information about the smoother for debugging. |
| 250 | + */ |
| 251 | +export function getSmootherDiagnostics(): { |
| 252 | + currentStage: SleepStage3; |
| 253 | + beliefState: Stage3Probabilities; |
| 254 | + dwellTimeSeconds: number; |
| 255 | + transitionCount: number; |
| 256 | + timeSinceLastTransitionSeconds: number; |
| 257 | +} { |
| 258 | + const now = Date.now(); |
| 259 | + return { |
| 260 | + currentStage: state.currentStage, |
| 261 | + beliefState: { ...state.beliefState }, |
| 262 | + dwellTimeSeconds: Math.round((now - state.stageEntryTime) / 1000), |
| 263 | + transitionCount: state.transitionCount, |
| 264 | + timeSinceLastTransitionSeconds: Math.round((now - state.lastTransitionTime) / 1000), |
| 265 | + }; |
| 266 | +} |
0 commit comments