GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — noop-analytics-engine/ios/StrandAnalytics/SleepStager.swift at main · Newbbsss/noop-analytics-engine Expand file tree/ Copy pathSleepStager.swiftMore file actions 2051 lines (1862 loc) · 115 KB / Copy pathSleepStager.swiftFile metadata and controls2051 lines (1862 loc) · 115 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 import Foundation import WhoopProtocol // SleepStager.swift — sleep/wake detection + APPROXIMATE 4-class staging. // // Ported from server/ingest/app/analysis/sleep.py and sleep_features.py. // // HONEST HEDGING: these stages are APPROXIMATIONS, not PSG-validated, not medical // advice. The EEG-free 4-class ceiling is ~65–73% epoch agreement (Walch 2019). // Light/deep separation is the weakest link — deep-minute estimates are the least // reliable output. // // Pipeline (30 s epochs): // Stage 0 gravity-stillness sleep/wake spine → in-bed sessions. Cole–Kripke // (te Lindert 30 s) computed as a citable cross-check; HR confirms runs. // Stage 1 per-epoch cardiorespiratory features over a rolling 5-min window // (mean HR, DoG-HR variability, RMSSD/SDNN from RR, resp rate + RRV). // Stage 2 transparent percentile-band classifier → {wake, light, deep, rem}. // Stage 3 median smoothing + physiology re-imposition (no early REM, deep in // the first third of the night). // // NOTE: the Python source computes RMSSD/SDNN/HF/LF/LFHF via neurokit2 per epoch. // On-device we have no neurokit2/scipy, so frequency-domain features (HF, LF/HF) // are omitted and the parasympathetic-tone signal is RMSSD only. Respiration rate // + RRV are derived from the raw 1 Hz resp channel with a simple peak detector // (the Python source explicitly derives these "robustly ourselves" too, so this // path is a faithful port rather than an approximation). The classifier seam, // percentile bands, smoothing, and physiology rules are reproduced exactly. // MARK: - Public output shapes /// A contiguous sleep-stage segment. Times are wall-clock unix seconds. public struct StageSegment: Equatable, Sendable, Codable { public var start: Int public var end: Int public var stage: String // "wake" | "light" | "deep" | "rem" public init(start: Int, end: Int, stage: String) { self.start = start; self.end = end; self.stage = stage } } /// A detected sleep session (in-bed span) with APPROXIMATE staging. public struct SleepSession: Equatable, Sendable { public let start: Int public let end: Int /// asleep / in-bed in [0, 1] (AASM TST/TIB; asleep = in-bed − wake). public let efficiency: Double public let stages: [StageSegment] /// Lowest 5-min rolling-mean HR during the session (bpm), or nil. public let restingHR: Int? /// Mean RMSSD over 5-min windows across the session (ms), or nil. public let avgHRV: Double? public init(start: Int, end: Int, efficiency: Double, stages: [StageSegment], restingHR: Int?, avgHRV: Double?) { self.start = start; self.end = end; self.efficiency = efficiency self.stages = stages; self.restingHR = restingHR; self.avgHRV = avgHRV } } public enum SleepStager { // MARK: - Stage 0 constants (sleep.py) /// Per-sample gravity change (g) at/below which a sample is "still". public static let gravityStillThresholdG: Double = 0.01 /// Rolling stillness window (minutes). public static let stillWindowMin: Int = 15 /// Fraction of still samples to call the window-center "sleep". public static let stillFraction: Double = 0.70 /// Data gap (minutes) that always breaks a run. public static let maxGapMin: Int = 20 /// Runs shorter than this (minutes) are absorbed into neighbours. public static let mergeMin: Int = 15 /// A sleep run must exceed this (minutes) to count as a session. public static let minSleepMin: Int = 60 /// Assumed sample interval (seconds) when not inferable. public static let defaultIntervalS: Double = 60.0 // MARK: - Daytime false-sleep guard (#90) // A long, still, sedentary daytime stretch (reading, a desk, a sofa) is gravity- // indistinguishable from a real nap, so the gravity spine alone misclassifies it as // sleep. The fix is NOT to drop daytime sleep — real naps are legitimate sessions — // but to hold a window whose CENTER falls in the local daytime band to a stricter bar: // it must be long enough to be a real nap AND show a genuine cardiac dip (a sedentary // stretch keeps a near-baseline HR). Overnight windows are UNCHANGED. /// Local hour (inclusive) at which the stricter daytime bar begins. public static let daytimeBandStartHour: Int = 11 /// Local hour (exclusive) at which the stricter daytime bar ends. A window whose center /// is in [start, end) local hours is "daytime"; everything else is "overnight". public static let daytimeBandEndHour: Int = 20 /// A still sleep run that resumes within this gap of an overnight sleep chain is the /// night's TAIL — a late wake past the daytime-band start, or a brief morning stir then /// back to sleep — not an isolated daytime nap, so it skips the daytime guard. Without /// this, a real sleep that ran past ~11:00 local had its tail rejected as a "nap" and the /// displayed wake time was truncated to late morning (late sleepers / shift workers). // Reimplemented from @vulnix0x4's PR #353. public static let nightContinuationGapMin: Int = 90 /// A daytime window must run at least this long (minutes) to count — short still /// daytime stretches are the dominant false-positive and are rejected outright. public static let daytimeMinSleepMin: Int = 90 /// A daytime window's resting HR (lowest 5-min rolling mean) must be at or below /// baseline × this to confirm a real cardiac dip. Stricter than the overnight 1.05: /// a true nap dips BELOW the waking-day median, sedentary stillness does not. public static let daytimeRestingHRMult: Double = 0.95 // MARK: - H4 physiological in-bed span cap (#547 / #531 / #509 / tail) /// Maximum plausible in-bed span (seconds) for a SINGLE assembled main-sleep run. No real single night /// runs longer than this: a 12 h+ "sleep" is a bad-clock artefact (a stale/duplicated timestamp range, /// or a strap that banked one frozen still stretch under a wrong clock) reading as one enormous still /// block — which then reports a 12 h sleep and poisons Rest / the debt ledger / the headline. 16 h is /// well above any genuine night (incl. recovery/illness sleeps and late weekend lie-ins) yet below the /// clock-artefact range. A run whose span exceeds this is DROPPED (not silently truncated to 16 h, which /// would fabricate a wake time): an over-long block is not trustworthy enough to assert a span for at /// all. (#547 / #531 / #509 tail) public static let maxMainSleepSpanS: Int = 16 * 60 * 60 // MARK: - H7 morning-stillness nap suppression (#531) // After a real overnight wake the wrist is often still (sitting with coffee, back in bed scrolling, a // sofa) for a stretch that the gravity spine reads as a fresh "nap" — #531's 9 am phantom nap right after // the night ended. It is NOT a night-tail continuation (that is handled by `nightContinuationGapMin` and // exempted), and it can clear the ordinary daytime guard (it is long + the post-wake HR is still low), so // it slipped through. H7 holds a daytime block that BEGINS within `morningStillnessWindowMin` of the // just-detected overnight wake to a STRONGER bar than an ordinary daytime nap: it must show a genuine // SUSTAINED re-onset — a real second sleep dips clearly below the day median, not merely near it. /// A daytime block whose onset falls within this many minutes AFTER an overnight chain's wake is treated /// as suspected morning residual stillness and held to the stronger re-onset bar below. ~3 h covers the /// post-wake window where residual stillness masquerades as a nap; a genuine afternoon nap (hours later) /// is past it and faces only the ordinary daytime guard. (#531) public static let morningStillnessWindowMin: Int = 180 /// The stronger resting-HR bar (× day baseline) a suspected-morning-stillness block must clear to be kept /// as a real re-onset. Stricter than the ordinary daytime `daytimeRestingHRMult` (0.95): residual waking /// stillness keeps a near-waking HR, so only a block that dips clearly (a true second sleep) survives. public static let morningReonsetRestingHRMult: Double = 0.90 /// The persisted v18 BAND sleep_state value that means "asleep" (Interpreter's `(sb>>4)&3`: 0 wake / /// 1 still / 2 asleep / 3 up). The strap's OWN scored band state — an independent anchor we CONSUME to /// confirm a borderline morning re-onset (H7) without re-deriving anything. (#531 / H8 consume) public static let bandStateAsleep: Int = 2 /// Fraction of a suspected-morning-stillness block's epochs whose persisted band sleep_state must read /// "asleep" (`bandStateAsleep`) for the strap's OWN signal to CONFIRM a genuine re-onset and KEEP the /// block even when its HR dip is borderline. A real second sleep the strap itself scored asleep is a /// strong, honest anchor; a residual-stillness false nap reads "still"/"up", not "asleep". ≥0.6 keeps /// this conservative. (H8 consume) public static let morningReonsetBandAsleepFrac: Double = 0.6 /// Soft-snap bed/wake to longest band-asleep stretch (Fable Sleep #27/#28). Slack ±90 min. public static let bandBoundSlackSec: Int = 90 * 60 public static let bandBoundMinAsleepSec: Int = 90 * 60 public static let bandBoundSampleGapSec: Int = 5 * 60 /// Seconds in a calendar day (for local-hour-of-day arithmetic). static let secondsPerDay: Int = 86_400 /// Floor on the rolling-window size in samples. public static let minWindowSamples: Int = 3 /// A run is HR-confirmed only if mean HR ≤ baseline × this. public static let hrSleepBaselineMult: Double = 1.05 /// Skip HR refinement (trust gravity) when fewer than this many HR samples. public static let hrRefineMinSamples: Int = 30 /// Consecutive sleep epochs required to declare onset (parity with Android SleepStager = 5). public static let onsetPersistEpochs: Int = 5 // MARK: - Off-wrist backstop (#500) // A wrist-OFF stretch reads as perfectly still gravity with no contrary motion, so the // gravity spine classifies it as sleep — and because the off-wrist epochs carry zero/missing // HR the daytime guard treats them as "missing data" and lets them through (a daytime desk-off // strap logged a phantom sleep). The backstop measures OFF-WRIST COVERAGE: while the strap is // worn it emits ~1 Hz HR, so a long CONTIGUOUS gap in the HR samples spanning part of a candidate // sleep run is a strong off-wrist proxy that works even when explicit WRIST_OFF events are absent; // explicit WRIST_OFF→WRIST_ON intervals (when the store surfaces them) sharpen it. A run is dropped // only when that coverage reaches maxOffWristSleepFraction of its duration (the FRACTIONAL rule from // j0b-dev's #504), so a real night that over-extends into a SHORT off-wrist tail survives. This is // independent of the daytime band — off-wrist time is off-wrist day or night, and a night-tail // continuation does NOT exempt it. /// A contiguous HR-sample gap of at least this many minutes contributes to a candidate run's /// off-wrist coverage. Sized at maxGapMin so a real worn night (dense ~1 Hz HR, or PPG-derived HR /// on a 5/MG) contributes ~no gap, but a wrist-off stretch (HR flatlines to no samples) contributes /// its whole span. The edges of the run count too: a run that begins/ends far from its nearest HR /// sample is partially uncovered. public static let offWristHRGapMin: Int = 20 /// FRACTIONAL off-wrist rejection (#500), design credited to j0b-dev's #504 analysis. A candidate /// sleep run is dropped ONLY when its off-wrist coverage — the UNION of its long HR-gap spans and /// any WRIST_OFF→WRIST_ON intervals overlapping it — is at least this fraction of its duration. The /// earlier guard dropped the WHOLE run on ANY contiguous HR gap or ANY single WRIST_OFF blip, which /// nuked a real night that over-extended into a SHORT off-wrist morning tail (strap removed shortly /// after waking) or that contained one stray WRIST_OFF event. 0.5 keeps such a night (<50% off-wrist) /// while still dropping an all-day desk strap (≈100% gap) or a session genuinely spent off-wrist. public static let maxOffWristSleepFraction: Double = 0.5 /// Minimum average HR-stream density for the off-wrist HR-gap proxy to be trusted (#507). The proxy /// reads a >`offWristHRGapMin`-minute hole in HR as "off the wrist" — valid only when HR is otherwise /// dense (live 5/MG, or a worn night with continuous HR), so a real gap is anomalous. A WHOOP 4.0's /// SYNCED night is reconstructed mostly from MOTION with sparse, derived HR, whose natural gaps would /// otherwise read as off-wrist and wrongly DROP a real night. So if the HR stream averages fewer than /// one sample per this many seconds, we don't assert off-wrist from gaps at all (WRIST_OFF events /// still apply). Self-consistent: a night sparse enough to be >50% gap-covered is, by definition, /// below this density, so it is spared. Measured over the whole stream, so an off-wrist HOLE inside an /// otherwise dense, worn day (#500) is still caught. static let hrDenseSpacingS: Int = 600 // one HR sample per 10 minutes, averaged over the stream // MARK: - Sparse-gravity robustness (#308) // On an un-unlocked WHOOP 5.0 the strap backfills mostly v18/v26 records where gravity is // sparse/clumped (~25% coverage), so the gravity-only Stage-0 spine fragments the night at // every >maxGapMin gravity gap and detectSleep drops every <minSleepMin fragment — collapsing // a ~6 h night to ~1 h. The fix derives the in-bed spine from a sustained low-HR stretch and // uses gravity stillness only to REFINE it, but is GATED ENTIRELY behind a "gravity is sparse" // condition so dense WHOOP-4.0 nights stay BYTE-IDENTICAL (a 4.0 regression is unacceptable). /// Gravity is "sparse" when its timespan covers less than this fraction of the HR-sample /// timespan. A dense 4.0 night has gravity spanning the whole HR window (≈1.0) and never /// trips this; a 5.0 backfill clumps gravity into a fraction of the night. public static let sparseGravitySpanFrac: Double = 0.5 /// When sparse, HR drives the in-bed spine: an HR sample is "sleep-band" when its bpm ≤ /// baseline × this. Reuses the overnight HR-confirmation multiplier so the band is the same /// one detectSleep already trusts to confirm a run. public static let hrSleepBandMult: Double = hrSleepBaselineMult /// When sparse, two adjacent sleep runs separated ONLY by a gravity gap up to this many /// minutes are merged if the intervening HR stays in the sleep band — so a real night is not /// shredded into sub-minSleepMin fragments by gravity dropouts. Sized at the daytime-nap /// floor (a real continuous night never has a true >90 min wake bridge mid-sleep). public static let sparseBridgeGapMin: Int = 90 // MARK: - Stage 1–3 constants (sleep_features.py) public static let epochS: Double = 30.0 public static let featureWindowS: Double = 5 * 60.0 public static let ckCountDivisor: Double = 100.0 public static let ckCountClip: Double = 300.0 public static let moveDeltaThresholdG: Double = 0.01 public static let hrDogSigma1S: Double = 120.0 public static let hrDogSigma2S: Double = 600.0 public static let stageHRLowPct: Double = 25.0 public static let stageHRHighPct: Double = 70.0 public static let stageHRVHighPct: Double = 70.0 public static let stageHRVarHighPct: Double = 65.0 public static let stageRRVHighPct: Double = 65.0 public static let stageRRVLowPct: Double = 50.0 public static let stageWakeMoveFrac: Double = 0.15 public static let stageStillMoveFrac: Double = 0.10 /// Fraction of sleep-period epochs that must carry a MISSING per-epoch RMSSD (sparse R-R) for the /// session's cardiac signal to count as PPG-DERIVED / sparse-cardiac. On a WHOOP 5/MG the PPG-derived /// HR feeds a noisier per-epoch HR-variance, which inflates `hrVar` on otherwise still, low-HR sleep /// epochs and was tripping the Stage-2 WAKE rule (which keys on the `hrvarHigh` percentile) — so a /// whole night over-reported WAKE. We already trust `!rmssd.isFinite` as a PPG/sparse tell for the /// pro-deep RMSSD handling (#127/#129); at this share across the night it also down-weights the /// HR-variance half of the WAKE rule. ~50% keeps a real worn 4.0 night (dense R-R) on the strict /// path and only relaxes nights whose cardiac signal is genuinely sparse/derived. (#705) public static let cardiacSparseEpochFrac: Double = 0.5 public static let smoothEpochs: Int = 5 public static let noREMAfterOnsetMin: Double = 15.0 public static let deepFirstFraction: Double = 1.0 / 3.0 /// Fragment-merge threshold (#274). A staged run shorter than this is "noise": the /// WHOOP 5/MG banks sparse motion, so the stager emits lots of sub-minute stage flecks /// and the hypnogram reads choppier than WHOOP's. mergeFragments (a DISPLAY/scoring /// smoothing applied AFTER staging, never to the underlying detection) absorbs runs /// below this into their neighbours. 3 min is conservative — long enough to clear the /// fleck noise, short enough to leave a genuine stage transition (a real deep or REM /// block runs many minutes) untouched. public static let fragmentMergeMin: Double = 3.0 /// fragmentMergeMin expressed in 30 s epochs (6). A run with < this many epochs merges. public static let fragmentMergeEpochs: Int = Int((fragmentMergeMin * 60.0 / epochS).rounded()) /// te Lindert 30 s Cole–Kripke weights [A₋₄..A₊₂]. SI = 0.001·Σ wᵢ·Aᵢ; sleep iff SI<1. public static let ckWeights: [Double] = [106.0, 54.0, 58.0, 76.0, 230.0, 74.0, 67.0] public static let ckScale: Double = 0.001 public static let ckBack: Int = 4 public static let ckFwd: Int = 2 // MARK: - Gravity deltas /// Per-record movement proxy = L2 magnitude of the gravity change vs the /// previous record. First record → 0. (No dropout sentinel needed: GravitySample /// always carries finite x/y/z.) static func gravityDeltas(_ grav: [GravitySample]) -> [Double] { var deltas: [Double] = [] deltas.reserveCapacity(grav.count) var prev: GravitySample? = nil for (i, r) in grav.enumerated() { if i == 0 { deltas.append(0.0) } else if let p = prev { let dx = p.x - r.x, dy = p.y - r.y, dz = p.z - r.z deltas.append((dx * dx + dy * dy + dz * dz).squareRoot()) } else { deltas.append(0.0) } prev = r } return deltas } /// Median spacing between consecutive timestamps, restricted to (0, 300 s). static func medianIntervalS(_ times: [Int]) -> Double { guard times.count >= 2 else { return defaultIntervalS } var gaps: [Double] = [] for i in 0..<(times.count - 1) { let g = Double(times[i + 1] - times[i]) if g > 0 && g < 300 { gaps.append(g) } } guard !gaps.isEmpty else { return defaultIntervalS } gaps.sort() return max(gaps[gaps.count / 2], 1.0) } static func windowSize(_ times: [Int]) -> Int { let interval = medianIntervalS(times) return max(minWindowSamples, Int(Double(stillWindowMin * 60) / interval)) } // MARK: - Sparse-gravity gate (#308) /// Largest spacing between consecutive timestamps (seconds), NO upper cap; 0 for <2 samples. /// Used to detect clumped/sparse gravity where the dropouts themselves are the signal: a few /// long dropouts in otherwise-dense (clumped) motion keep the MEDIAN gap small but still break /// runs, so the largest gap — not the median — is the right signal (#28). static func largestGapS(_ times: [Int]) -> Double { guard times.count >= 2 else { return 0 } var mx = 0.0 for i in 0..<(times.count - 1) { let g = Double(times[i + 1] - times[i]) if g > mx { mx = g } } return mx } /// True when gravity is too sparse for the gravity-only spine to be trusted across gaps: /// the gravity timespan covers < sparseGravitySpanFrac of the HR-sample timespan, OR the /// LARGEST gravity inter-sample gap exceeds maxGapMin. The largest-gap test (not just the /// median) catches CLUMPED motion — dense bursts split by a few long dropouts, the typical /// WHOOP 4.0 backfill (#28) — whose median gap stays small yet which still hides run-breaking /// gaps. Requires a real HR span to compare against — with no/degenerate HR the dense path is /// kept (false), so a 4.0 with absent HR is never reclassified as sparse. static func isGravitySparse(_ grav: [GravitySample], hr: [HRSample]) -> Bool { if grav.count < 2 || hr.count < 2 { return false } let hrSpan = Double(hr[hr.count - 1].ts - hr[0].ts) if hrSpan <= 0 { return false } let gravSpan = Double(grav[grav.count - 1].ts - grav[0].ts) if gravSpan < sparseGravitySpanFrac * hrSpan { return true } // #28: clumped 4.0 motion keeps a SMALL median gap yet still contains >maxGapMin dropouts // the gravity-only spine shreds the night on. The largest gap catches what a median would // miss (largest ≥ median, so this subsumes the old median check). Flagging sparse only // ENABLES buildRuns' HR-vouched bridge — a real wake (HR above the sleep band) still breaks. return largestGapS(grav.map { $0.ts }) > Double(maxGapMin * 60) } /// True when HR stays in the sleep band (≤ baseline × hrSleepBandMult) across (a, b], used to /// decide whether a pure gravity gap is a real wake or just a dropout. With no baseline or no /// HR in the interval, the answer is false (cannot vouch for the gap → treat as a real break). static func hrSleepBandAcross(_ a: Int, _ b: Int, hr: [HRSample], baseline: Double?) -> Bool { guard let baseline = baseline else { return false } let seg = hr.filter { $0.ts > a && $0.ts <= b } if seg.isEmpty { return false } let meanHR = Double(seg.reduce(0) { $0 + $1.bpm }) / Double(seg.count) return meanHR <= baseline * hrSleepBandMult } /// Per-record sleep flags from a rolling fraction of "still" samples. static func classifyStill(_ grav: [GravitySample], _ deltas: [Double]) -> [Bool] { let n = grav.count if n < 2 { return [Bool](repeating: false, count: n) } let half = windowSize(grav.map { $0.ts }) / 2 // stillPrefix[i] = # still samples among deltas[0..<i]: O(1) window counts → an O(n) scan, not // O(n×window). The old nested loop burned minutes of CPU per analysis tick (and on Android, on // the main thread, froze the app into ANRs after a few nights of 1 Hz history). Identical output. var stillPrefix = [Int](repeating: 0, count: n + 1) for i in 0..<n { stillPrefix[i + 1] = stillPrefix[i] + (deltas[i] < gravityStillThresholdG ? 1 : 0) } var flags: [Bool] = [] flags.reserveCapacity(n) for i in 0..<n { let lo = max(0, i - half) let hi = min(n, i + half + 1) let stillCount = stillPrefix[hi] - stillPrefix[lo] flags.append(Double(stillCount) / Double(hi - lo) >= stillFraction) } return flags } struct Period { var stage: String; var start: Int; var end: Int } /// Collapse per-record flags into contiguous runs, breaking on class change /// or a gap > maxGapMin minutes. /// /// When `sparse` (gravity is too clumped to bridge gaps — #308), a PURE gravity data-gap /// (no contrary motion) does NOT close a SLEEP run while HR stays in the sleep band across /// the gap: the strap simply banked no motion there, not a wake. A class change always still /// closes the run, and the dense path (`sparse == false`) is byte-identical to the original. static func buildRuns(_ grav: [GravitySample], _ flags: [Bool], sparse: Bool = false, hr: [HRSample] = [], baseline: Double? = nil) -> [Period] { let n = grav.count if n == 0 { return [] } let times = grav.map { $0.ts } let maxGapS = maxGapMin * 60 var periods: [Period] = [] var runStart = 0 for i in 1...n { let atEnd = (i == n) let close: Bool if atEnd { close = true } else { let classChanged = flags[i] != flags[runStart] var gapExceeded = (times[i] - times[i - 1]) > maxGapS // Sparse override: a pure gravity gap (no class change) does not break a sleep // run when HR stays in the sleep band across it — the gap is a dropout, not a wake. if sparse && gapExceeded && !classChanged && flags[runStart] && hrSleepBandAcross(times[i - 1], times[i], hr: hr, baseline: baseline) { gapExceeded = false } close = classChanged || gapExceeded } if close { periods.append(Period(stage: flags[runStart] ? "sleep" : "active", start: times[runStart], end: times[i - 1])) runStart = i } } return periods } /// Absorb runs shorter than mergeMin minutes into their neighbours. static func mergePeriods(_ periods: [Period], mergeMinutes: Int = mergeMin) -> [Period] { if periods.isEmpty { return [] } var pending = periods let thresholdS = mergeMinutes * 60 var merged: [Period] = [] var i = 0 while i < pending.count { let current = pending[i] let tooShort = (current.end - current.start) < thresholdS if !tooShort { merged.append(current); i += 1; continue } let hasPrev = i > 0 && !merged.isEmpty let hasNext = i + 1 < pending.count let bridgesSame = hasPrev && hasNext && pending[i - 1].stage == pending[i + 1].stage if bridgesSame { let prev = merged.removeLast() merged.append(Period(stage: prev.stage, start: prev.start, end: pending[i + 1].end)) i += 2 } else if hasNext { pending[i + 1] = Period(stage: pending[i + 1].stage, start: current.start, end: pending[i + 1].end) i += 1 } else if hasPrev { let prev = merged.removeLast() merged.append(Period(stage: prev.stage, start: prev.start, end: current.end)) i += 1 } else { i += 1 } } return merged } /// Sparse-gravity bridge (#308): merge two adjacent SLEEP runs separated ONLY by a gap up to /// sparseBridgeGapMin minutes when the intervening HR stays in the sleep band — so a real night /// fragmented by gravity dropouts is re-stitched into one continuous in-bed span BEFORE the /// minSleepMin gate drops the pieces. Active runs and over-threshold gaps are left untouched; /// the span between two bridged sleep runs (an "active"/gap run, if present) is absorbed. /// A no-op when `sparse == false`, so the dense 4.0 path is unchanged. static func bridgeSparseSleep(_ periods: [Period], sparse: Bool, hr: [HRSample], baseline: Double?) -> [Period] { if !sparse || periods.isEmpty { return periods } let bridgeGapS = sparseBridgeGapMin * 60 var out: [Period] = [] for p in periods { if let last = out.last, last.stage == "sleep", p.stage == "sleep" { let gap = p.start - last.end if gap >= 0 && gap <= bridgeGapS && hrSleepBandAcross(last.end, p.start, hr: hr, baseline: baseline) { out[out.count - 1] = Period(stage: "sleep", start: last.start, end: p.end) continue } } out.append(p) } return out } // MARK: - HR refinement static func rowsBetween<T>(_ rows: [T], start: Int, end: Int, ts: (T) -> Int) -> [T] { rows.filter { ts($0) >= start && ts($0) <= end } } /// Day HR baseline = median bpm over all HR samples; nil if none. static func hrBaseline(_ hr: [HRSample]) -> Double? { let vals = hr.map { Double($0.bpm) } guard !vals.isEmpty else { return nil } return HRVAnalyzer.median(vals) } static func confirmSleepWithHR(_ p: Period, hr: [HRSample], baseline: Double?) -> Bool { guard let baseline = baseline else { return true } let seg = rowsBetween(hr, start: p.start, end: p.end) { $0.ts } if seg.count < hrRefineMinSamples { return true } let meanHR = Double(seg.reduce(0) { $0 + $1.bpm }) / Double(seg.count) return meanHR <= baseline * hrSleepBaselineMult } /// True when the run's CENTER, shifted to LOCAL time by tzOffsetSeconds, lands in the /// daytime band [daytimeBandStartHour, daytimeBandEndHour). The center (not the edges) /// is used so a window straddling a band edge is classified once, by where it mostly is. /// `((x % d) + d) % d` is a floored modulo so a negative local-shifted time still maps /// into [0, secondsPerDay). static func isDaytimeCenter(_ p: Period, tzOffsetSeconds: Int) -> Bool { // Int overflow-safe: starts/ends are unix seconds; midpoint via average of the two. let center = p.start + (p.end - p.start) / 2 let local = center + tzOffsetSeconds let secOfDay = ((local % secondsPerDay) + secondsPerDay) % secondsPerDay let hour = secOfDay / 3_600 return hour >= daytimeBandStartHour && hour < daytimeBandEndHour } /// True when a run's ONSET (start), in LOCAL time, falls OUTSIDE the daytime band — i.e. /// the sleep began at night, not during the day. Anchors a continuous-sleep chain: only a /// chain that began overnight may carry its tail past the daytime-band start (a late wake). static func isOvernightOnset(_ start: Int, tzOffsetSeconds: Int) -> Bool { let local = start + tzOffsetSeconds let secOfDay = ((local % secondsPerDay) + secondsPerDay) % secondsPerDay let hour = secOfDay / 3_600 return !(hour >= daytimeBandStartHour && hour < daytimeBandEndHour) } /// Stricter bar for a daytime-centered window (#90). A real daytime nap clears it; a /// long sedentary still stretch (the false-positive this guards) does not, because it /// is either too short or never shows a genuine cardiac dip below the day median. /// Overnight windows never reach here. Returns true = keep, false = reject. /// /// `restingHR` is the window's own lowest 5-min rolling-mean HR (the sleep-depth proxy /// detectSleep already computes); `baseline` is the day's median HR. With no usable HR /// evidence (nil baseline OR nil restingHR) a daytime stretch cannot be confirmed as a /// real nap, so it is rejected — sedentary daytime stillness without a measured HR dip /// is far more likely than an unmonitored nap, and this path can never touch the night. static func passesDaytimeGuard(_ p: Period, restingHR: Int?, baseline: Double?) -> Bool { let daytimeMinSleepS = daytimeMinSleepMin * 60 if (p.end - p.start) < daytimeMinSleepS { return false } guard let baseline = baseline, let resting = restingHR else { return false } return Double(resting) <= baseline * daytimeRestingHRMult } /// H7 morning-stillness nap suppression (#531). Returns true = KEEP, false = REJECT, for a daytime block /// `p` that begins shortly after a real overnight wake. `morningWakeEnd` is the end of the just-detected /// OVERNIGHT chain (nil when the prior chain was not overnight, or there was none) — when `p.start` is /// within `morningStillnessWindowMin` of it, the block is suspected morning residual stillness and must /// clear the ORDINARY daytime guard AND show a SUSTAINED re-onset: its resting HR must dip below the /// stronger `morningReonsetRestingHRMult × baseline` bar (a true second sleep, not near-waking stillness). /// Outside the morning window this is a no-op (returns the plain daytime-guard result), so a genuine /// afternoon nap is unaffected. (#531) static func passesMorningStillnessGuard(_ p: Period, restingHR: Int?, baseline: Double?, morningWakeEnd: Int?, bandSleepState: [(ts: Int, state: Int)] = []) -> Bool { // Only a daytime block beginning within the post-wake window of an overnight chain is suspected. guard let wakeEnd = morningWakeEnd, p.start >= wakeEnd, (p.start - wakeEnd) <= morningStillnessWindowMin * 60 else { return passesDaytimeGuard(p, restingHR: restingHR, baseline: baseline) } // Suspected morning stillness needs at least the ordinary daytime guard (long enough + a real dip). if !passesDaytimeGuard(p, restingHR: restingHR, baseline: baseline) { return false } // CONSUME the strap's OWN banked band sleep_state (#531 / H8): if the strap itself scored this block // predominantly "asleep", that is a strong independent re-onset anchor — KEEP it even on a borderline // HR dip. This only ever RESCUES a block the strap says was real sleep; it never fabricates one. if bandStateConfirmsAsleep(p, bandSleepState: bandSleepState) { return true } // Otherwise require the clearly-deeper cardiac dip of a true second sleep. guard let baseline = baseline, let resting = restingHR else { return false } return Double(resting) <= baseline * morningReonsetRestingHRMult } /// CONSUME-side helper (#531 / H8): true when the strap's OWN persisted v18 band sleep_state over the /// block `[p.start, p.end]` reads predominantly "asleep" (`bandStateAsleep`), at/above /// `morningReonsetBandAsleepFrac` of the in-block samples — an independent confirmation of a real /// re-onset. Empty/absent band state → false (no anchor → fall back to the HR bar); we never invent a /// "asleep" reading the strap did not bank. Pure + deterministic. (#531 / H8 consume) static func bandStateConfirmsAsleep(_ p: Period, bandSleepState: [(ts: Int, state: Int)]) -> Bool { let inBlock = bandSleepState.filter { $0.ts >= p.start && $0.ts <= p.end } guard !inBlock.isEmpty else { return false } let asleep = inBlock.reduce(0) { $0 + ($1.state == bandStateAsleep ? 1 : 0) } return Double(asleep) / Double(inBlock.count) >= morningReonsetBandAsleepFrac } /// Off-wrist HR-gap spans (#500). The contiguous HR-coverage gaps of at least `offWristHRGapMin` /// minutes WITHIN [p.start, p.end], as concrete `[start, end)` sub-intervals — a strong wrist-OFF /// proxy. Worn, the strap streams ~1 Hz HR (or PPG-derived HR on a 5/MG), so a real night yields no /// long gap; an off-wrist stretch flatlines to no HR samples and yields a span. The leading edge /// (`p.start` → first in-run sample) and trailing edge (last in-run sample → `p.end`) count too, /// and a run with NO in-run HR at all is one full-period gap. With NO HR data at all (no stream) /// this returns [] (the gravity-only path is left to the existing guards — we can't assert /// off-wrist without HR). These spans are UNIONed with the WRIST_OFF intervals by `offWristFraction`. static func offWristHRGapSpans(_ p: Period, hr: [HRSample]) -> [(start: Int, end: Int)] { if hr.isEmpty || p.end <= p.start { return [] } // Density gate (#507): only trust the HR-gap off-wrist proxy when the HR STREAM is dense enough // that a long gap is anomalous. A WHOOP 4.0 synced night is motion-reconstructed with sparse HR, // so its natural gaps must NOT read as off-wrist (that wrongly dropped a real night). Judge over // the whole stream so an off-wrist HOLE inside an otherwise dense, worn day (#500) is still caught. let sortedAll = hr.sorted { $0.ts < $1.ts } let streamSpan = sortedAll[sortedAll.count - 1].ts - sortedAll[0].ts if streamSpan >= hrDenseSpacingS && hr.count < streamSpan / hrDenseSpacingS { return [] } let gapS = offWristHRGapMin * 60 let seg = hr.filter { $0.ts >= p.start && $0.ts <= p.end }.sorted { $0.ts < $1.ts } // No HR anywhere inside a run long enough to matter → the whole period is one gap. if seg.isEmpty { return (p.end - p.start) >= gapS ? [(start: p.start, end: p.end)] : [] } var spans: [(start: Int, end: Int)] = [] // Leading edge: run start to first sample. if seg[0].ts - p.start >= gapS { spans.append((start: p.start, end: seg[0].ts)) } // Interior: any gap between consecutive in-run samples. for i in 1..<seg.count where seg[i].ts - seg[i - 1].ts >= gapS { spans.append((start: seg[i - 1].ts, end: seg[i].ts)) } // Trailing edge: last sample to run end. if p.end - seg[seg.count - 1].ts >= gapS { spans.append((start: seg[seg.count - 1].ts, end: p.end)) } return spans } /// Fractional off-wrist coverage of a candidate run [p.start, p.end] in [0, 1] (#500). /// Design credited to j0b-dev's #504 analysis: instead of a binary drop on ANY HR gap or ANY single /// WRIST_OFF blip, we measure how much of the run is off-wrist and let the caller drop it only past /// `maxOffWristSleepFraction`. Coverage = (length of the UNION of) the HR-gap spans (`offWristHRGapSpans`) /// AND the supplied WRIST_OFF→WRIST_ON `wristOff` intervals, clipped to the run, divided by duration. /// Unioning avoids double-counting overlapping gap+event time. A real night with a small (<50%) /// off-wrist tail scores low and is kept; an all-day desk strap (HR-gap ≈100%, no events needed) or a /// session genuinely spent off the wrist scores high and is dropped. static func offWristFraction(_ p: Period, hr: [HRSample], wristOff: [(start: Int, end: Int)]) -> Double { let dur = p.end - p.start if dur <= 0 { return 0 } // Collect every off-wrist span, clipped to the run: HR-gap proxy spans + explicit wrist-off events. var spans = offWristHRGapSpans(p, hr: hr) for w in wristOff { let s = max(w.start, p.start), e = min(w.end, p.end) if e > s { spans.append((start: s, end: e)) } } if spans.isEmpty { return 0 } // Union the spans so overlapping gap+event time is counted once, then sum the covered length. spans.sort { $0.start < $1.start } var covered = 0, curStart = spans[0].start, curEnd = spans[0].end for sp in spans.dropFirst() { if sp.start <= curEnd { curEnd = max(curEnd, sp.end) // overlapping/adjacent → extend } else { covered += curEnd - curStart // disjoint → bank the run curStart = sp.start; curEnd = sp.end } } covered += curEnd - curStart return Double(covered) / Double(dur) } // MARK: - detectSleep (public) /// Detect sleep sessions from biometric streams. Empty/absent gravity → []. /// Gravity-only input degrades gracefully (HR/RR/resp refinements skipped). /// /// `tzOffsetSeconds` is the wall-clock UTC offset (TimeZone.current.secondsFromGMT) /// used ONLY to place each window's center on a LOCAL clock for the daytime /// false-sleep guard (#90). It defaults to 0 so the pure function and its tests stay /// UTC; the live call site (IntelligenceEngine) passes the device's real offset. /// `wristOff` is an optional list of off-wrist `[start, end)` intervals (unix seconds), paired from /// the strap's WRIST_OFF/WRIST_ON events by `AnalyticsEngine.offWristIntervals`. When the call site /// has them (IntelligenceEngine reads `store.events`), they sharpen the always-on HR-gap off-wrist /// backstop: a candidate run is dropped when its off-wrist coverage (HR-gap spans UNION these /// intervals) reaches `maxOffWristSleepFraction` of its duration — the FRACTIONAL rule from #504, so /// a real night with a short off-wrist tail survives (#500). Defaults to empty (HR-gap proxy only), /// so the pure function and its tests stay event-free. /// `bandSleepState` is the strap's OWN persisted v18 BAND sleep_state per timestamp (Interpreter's /// `(sb>>4)&3`: 0 wake / 1 still / 2 asleep / 3 up), used ONLY to CONSUME-confirm a borderline H7 morning /// re-onset (#531): a daytime block the strap itself scored predominantly "asleep" is KEPT even on a /// borderline HR dip. Default empty keeps pure-function callers/tests free of it; IntelligenceEngine /// passes the night window's persisted band state. It can only RESCUE a real-sleep block, never fabricate. /// `useSleepStagerV2` (V7 / #690): when true, each accepted night is staged by the experimental /// cardiorespiratory recipe `SleepStagerV2.stageSession` instead of V1's `stageSession`. DETECTION is /// unchanged (same accepted windows); only the per-epoch hypnogram differs. Default false keeps V1 the /// byte-identical default (the frozen-golden tests stay green). The live call site threads /// `PuffinExperiment.experimentalSleepV2Enabled` so the Settings toggle now affects normal detected /// nights, not just the self-heal restage path. public static func detectSleep(hr: [HRSample] = [], rr: [RRInterval] = [], resp: [RespSample] = [], gravity: [GravitySample], tzOffsetSeconds: Int = 0, wristOff: [(start: Int, end: Int)] = [], bandSleepState: [(ts: Int, state: Int)] = [], useSleepStagerV2: Bool = false, traceSink: ((String) -> Void)? = nil) -> [SleepSession] { // Sleep & Rest test mode only: when a trace is requested we MUST run the live ladder, not a // memoized result, so each gate verdict is emitted for THIS night. The trace is side-effect- // only and never changes the sessions, so a traced and an untraced call return the identical // array. With no sink (the default, every existing call site) the path below is byte-identical // to before: same memo key, same compute. if let traceSink { return detectSleepUncached(hr: hr, rr: rr, resp: resp, gravity: gravity, tzOffsetSeconds: tzOffsetSeconds, wristOff: wristOff, bandSleepState: bandSleepState, useSleepStagerV2: useSleepStagerV2, traceSink: traceSink) } // v7.0.2 perf (#707): the single heaviest analytics call — it sorts the dense full-day gravity // stream (~tens of thousands of samples for a worn day), builds the gravity-delta/still spine, and // stages every accepted run. The post-sync scoring loop calls it once PER DAY across the window, and // a re-run with the SAME raw (an idempotent re-pass, or a later sync that didn't touch this day's // streams) re-does all of it for an identical `[SleepSession]`. Memoize on a FULL key: every input // that steers detection or staging — the four streams, the tz offset (daytime-guard + onset band), // the off-wrist intervals (#500 backstop), the persisted band state (#531 H8), and the V2 toggle (an // edit to any re-keys to a fresh compute). Result-only + bounded; the raw arrays are never retained. let key = DetectKey( grav: StreamFingerprint.of(gravity, ts: { $0.ts }, quant: { Int(($0.x + $0.y + $0.z) * 1024) }), hr: StreamFingerprint.of(hr, ts: { $0.ts }, quant: { Int($0.bpm) }), rr: StreamFingerprint.of(rr, ts: { $0.ts }, quant: { Int($0.rrMs) }), resp: StreamFingerprint.of(resp, ts: { $0.ts }, quant: { $0.raw }), tz: tzOffsetSeconds, wristOff: StreamFingerprint.of(wristOff, ts: { $0.start }, quant: { $0.end }), band: StreamFingerprint.of(bandSleepState, ts: { $0.ts }, quant: { $0.state }), v2: useSleepStagerV2) return detectSleepCache.value(key) { detectSleepUncached(hr: hr, rr: rr, resp: resp, gravity: gravity, tzOffsetSeconds: tzOffsetSeconds, wristOff: wristOff, bandSleepState: bandSleepState, useSleepStagerV2: useSleepStagerV2, traceSink: nil) } } private struct DetectKey: Hashable { let grav: StreamFingerprint; let hr: StreamFingerprint let rr: StreamFingerprint; let resp: StreamFingerprint let tz: Int let wristOff: StreamFingerprint; let band: StreamFingerprint let v2: Bool } /// ≈ the number of distinct days in a scoring window; FIFO-evicted, holds only small session arrays. private static let detectSleepCache = AnalyticsMemoCache<DetectKey, [SleepSession]>(capacity: 40) /// The unchanged detection+staging pipeline; split out verbatim so the public entry memoizes in front. private static func detectSleepUncached(hr: [HRSample], rr: [RRInterval], resp: [RespSample], gravity: [GravitySample], tzOffsetSeconds: Int, wristOff: [(start: Int, end: Int)], bandSleepState: [(ts: Int, state: Int)], useSleepStagerV2: Bool, traceSink: ((String) -> Void)? = nil) -> [SleepSession] { let grav = gravity.sorted { $0.ts < $1.ts } if grav.count < 2 { return [] } let hrS = hr.sorted { $0.ts < $1.ts } let rrS = rr.sorted { $0.ts < $1.ts } let respS = resp.sorted { $0.ts < $1.ts } let baseline = hrBaseline(hrS) // Sparse-gravity gate (#308): an un-unlocked WHOOP 5.0 backfills mostly v18/v26 records // where gravity is clumped (~25% coverage), so the gravity-only spine fragments the night. // ONLY when sparse do the three robustness branches engage; a dense 4.0 night is `false` // here and follows the exact original path (byte-identical). let sparse = isGravitySparse(grav, hr: hrS) let deltas = gravityDeltas(grav) let flags = classifyStill(grav, deltas) var runs = buildRuns(grav, flags, sparse: sparse, hr: hrS, baseline: baseline) runs = mergePeriods(runs) // Re-stitch sleep runs fragmented by pure gravity dropouts (sparse only) before minSleepMin. let runsBeforeBridge = traceSink == nil ? 0 : runs.filter { $0.stage == "sleep" }.count runs = bridgeSparseSleep(runs, sparse: sparse, hr: hrS, baseline: baseline) // Sleep & Rest test mode (E3): record the sparse-gravity bridge result, so a sparse 5.0 night // rescued from fragmentation is visible. Only emitted when gravity is sparse (the only case the // bridge can act) and only when tracing. Side-effect-only. if let traceSink, sparse { let runsAfterBridge = runs.filter { $0.stage == "sleep" }.count traceSink(GateTrace.runLine(index: -1, startTs: 0, endTs: 0, verdict: runsAfterBridge < runsBeforeBridge ? .kept : .dropped, gate: "sparseBridge", detail: "sparse=true gapMin=\(sparseBridgeGapMin) runsBefore=\(runsBeforeBridge) runsAfter=\(runsAfterBridge)")) } let minSleepS = minSleepMin * 60 var sessions: [SleepSession] = [] // Continuous-sleep chain tracking so a real overnight sleep that runs PAST the daytime-band // start (a late wake, or a brief morning stir then back to sleep that leaves the tail as its // own daytime-centered run) is NOT mistaken for an isolated daytime nap and rejected — which // truncated the displayed wake time to ~late morning. A daytime run skips the nap guard ONLY // when it directly continues (≤ nightContinuationGap) a chain that BEGAN overnight; isolated // daytime stillness (hours after waking) still faces the full guard. // Reimplemented from @vulnix0x4's PR #353. let continuationGapS = nightContinuationGapMin * 60 var chainPrevEnd: Int? = nil // end of the last accepted sleep run var chainFromOvernight = false // did the current contiguous chain begin overnight? // Sleep & Rest test mode (E2): each candidate sleep run emits ONE verdict line naming the gate // that kept or dropped it. The decisions below are byte-identical to the untraced path; the // `traceSink?(...)` calls are the only addition and never alter `sessions`. `runIndex` counts // only sleep-stage runs so the trace numbers match the candidate ordinal. var runIndex = -1 for p in runs { if p.stage != "sleep" { continue } runIndex += 1 let spanMin = (p.end - p.start) / 60 if (p.end - p.start) <= minSleepS { traceSink?(GateTrace.runLine(index: runIndex, startTs: p.start, endTs: p.end, verdict: .dropped, gate: "minSleepMin", detail: "spanMin=\(spanMin) minSleepMin=\(minSleepMin)")) continue } // H4 physiological in-bed span cap (#547/#531/#509 tail): a single assembled main-sleep run // longer than ~16 h is a bad-clock artefact (a frozen still stretch banked under a stale/wrong // clock), not a real night. Drop it rather than report (or truncate to) a 12 h+ "sleep" — an // over-long block can't be trusted to assert a span at all, and truncating would fabricate a // wake time. Checked before staging so the artefact never reaches the aggregate. if (p.end - p.start) > maxMainSleepSpanS { traceSink?(GateTrace.runLine(index: runIndex, startTs: p.start, endTs: p.end, verdict: .dropped, gate: "maxMainSleepSpanS", detail: "spanMin=\(spanMin) maxMainSleepSpanMin=\(maxMainSleepSpanS / 60)")) continue } if !confirmSleepWithHR(p, hr: hrS, baseline: baseline) { traceSink?(GateTrace.runLine(index: runIndex, startTs: p.start, endTs: p.end, verdict: .dropped, gate: "hrConfirm", detail: "hrSleepBaselineMult=\(hrSleepBaselineMult) baseline=\(baseline.map { Int($0) } ?? -1)")) continue } // Off-wrist backstop (#500), FRACTIONAL rule (design credited to j0b-dev's #504 analysis): // a wrist-OFF stretch is still gravity with no HR, so it slips past both the gravity spine // and the daytime guard's "missing data" path. Measure off-wrist COVERAGE — the union of the // run's long HR-coverage gaps (the must-have proxy) and any WRIST_OFF→WRIST_ON intervals // overlapping it — and drop the run only when that reaches maxOffWristSleepFraction of its // duration. This no longer nukes a real night that over-extends into a SHORT (<50%) off-wrist // morning tail, or that holds a single stray WRIST_OFF blip, while an all-day desk strap // (≈100% gap) is still dropped. Checked BEFORE the night-tail exemption: off-wrist time is // off-wrist day or night and must NOT ride a continuation chain. It does NOT re-anchor the // chain (the run is simply skipped). let offFrac = offWristFraction(p, hr: hrS, wristOff: wristOff) if offFrac >= maxOffWristSleepFraction { traceSink?(GateTrace.runLine(index: runIndex, startTs: p.start, endTs: p.end, verdict: .dropped, gate: "offWrist", detail: "offWristFrac=\(round2(offFrac)) max=\(maxOffWristSleepFraction)")) continue } // Daytime false-sleep guard (#90): a window centered in the local daytime band // must clear a stricter bar (≥daytimeMinSleepMin AND a real resting-HR dip). // Overnight windows skip this entirely. restingHR is computed here (reused below). let resting = sessionRestingHR(start: p.start, end: p.end, hr: hrS) let continuesChain = chainPrevEnd.map { p.start - $0 <= continuationGapS } ?? false let isNightTail = continuesChain && chainFromOvernight // the night's tail, not a nap // H7 (#531): when the prior accepted chain BEGAN overnight, its wake (`chainPrevEnd`) anchors the // morning-stillness window. A daytime block beginning within it that is NOT a night-tail must // clear the STRONGER re-onset bar — killing the 9 am phantom nap of residual post-wake stillness // while keeping a genuine second sleep. Outside the window the guard is the ordinary daytime bar. let morningWakeEnd = chainFromOvernight ? chainPrevEnd : nil let isDaytime = isDaytimeCenter(p, tzOffsetSeconds: tzOffsetSeconds) // Evaluate the morning-stillness guard ONLY when the run is daytime-centered, preserving the // original short-circuit (overnight runs never call it). The boolean used to `continue` below // is identical to the original combined condition. let passesMorning = isDaytime ? passesMorningStillnessGuard(p, restingHR: resting, baseline: baseline, morningWakeEnd: morningWakeEnd, bandSleepState: bandSleepState) : true if isDaytime, !passesMorning, !isNightTail { let gateName = (morningWakeEnd != nil) ? "morningStillness" : "daytimeGuard" traceSink?(GateTrace.runLine(index: runIndex, startTs: p.start, endTs: p.end, verdict: .dropped, gate: gateName, detail: "daytime=true restingHR=\(resting ?? -1) baseline=\(baseline.map { Int($0) } ?? -1) nightTail=false")) continue } // Fable Sleep #27/#28: soft-snap bed/wake to longest band-asleep stretch when present. let (bed, wake) = refineBoundsFromBandState(start: p.start, end: p.end, bandSleepState: bandSleepState) let stages = useSleepStagerV2 ? SleepStagerV2.stageSession(start: bed, end: wake, grav: grav, hr: hrS, rr: rrS, resp: respS) : stageSession(start: bed, end: wake, grav: grav, hr: hrS, rr: rrS, resp: respS) let eff = efficiency(start: bed, end: wake, stages: stages) let avgHrv = sessionAvgHRV(start: bed, end: wake, rr: rrS) let restingFinal = (bed != p.start || wake != p.end) ? sessionRestingHR(start: bed, end: wake, hr: hrS) : resting sessions.append(SleepSession(start: bed, end: wake, efficiency: eff, stages: stages, restingHR: restingFinal, avgHRV: avgHrv)) traceSink?(GateTrace.runLine(index: runIndex, startTs: bed, endTs: wake, verdict: .kept, gate: "accepted", detail: "spanMin=\((wake - bed) / 60) eff=\(round2(eff)) restingHR=\(restingFinal ?? -1) daytime=\(isDaytime)")) // A run that does NOT continue the chain re-anchors it on this run's onset. if !continuesChain { chainFromOvernight = isOvernightOnset(bed, tzOffsetSeconds: tzOffsetSeconds) } chainPrevEnd = wake } sessions.sort { $0.start < $1.start } return sessions } /// Soft-align gravity bed/wake to the longest contiguous band-asleep stretch overlapping the /// candidate window (Fable Sleep #27/#28). Returns the original bounds when band is sparse or /// the stretch is too short / too far from the gravity window. Never invents a night. public static func refineBoundsFromBandState( start: Int, end: Int, bandSleepState: [(ts: Int, state: Int)], slackSec: Int = bandBoundSlackSec, minAsleepSec: Int = bandBoundMinAsleepSec, gapSec: Int = bandBoundSampleGapSec ) -> (Int, Int) { guard !bandSleepState.isEmpty, end > start else { return (start, end) } let lo = start - slackSec let hi = end + slackSec let asleep = bandSleepState .filter { $0.state == bandStateAsleep && $0.ts >= lo && $0.ts <= hi } .map(\.ts) .sorted() guard asleep.count >= 3 else { return (start, end) } var bestA = asleep[0], bestB = asleep[0] var runA = asleep[0], runB = asleep[0] for i in 1..<asleep.count { let t = asleep[i] if t - runB <= gapSec { runB = t } else { if runB - runA > bestB - bestA { bestA = runA; bestB = runB } runA = t; runB = t } } if runB - runA > bestB - bestA { bestA = runA; bestB = runB } let span = bestB - bestA guard span >= minAsleepSec else { return (start, end) } guard bestB >= start, bestA <= end else { return (start, end) } guard abs(bestA - start) <= slackSec, abs(bestB - end) <= slackSec else { return (start, end) } let gravSpan = end - start guard span >= gravSpan / 2 else { return (start, end) } let newStart = min(max(bestA, lo), hi) let newEnd = min(max(bestB + 60, lo), hi) guard newEnd - newStart >= minAsleepSec else { return (start, end) } return (newStart, newEnd) } /// asleep / in-bed in [0, 1]; asleep = in-bed − wake. static func efficiency(start: Int, end: Int, stages: [StageSegment]) -> Double { let inBed = Double(end - start) if inBed <= 0 { return 0 } let wake = stages.filter { $0.stage == "wake" }.reduce(0.0) { $0 + Double($1.end - $1.start) } let asleep = max(0.0, inBed - wake) return min(1.0, asleep / inBed) } // MARK: - Stage 1–3: staging over a 30 s epoch grid /// First persistent-sleep epoch (onset) and last sleep epoch (final wake). static func onsetAndFinalWake(_ ckFlags: [Bool]) -> (Int, Int) { let n = ckFlags.count if n == 0 { return (0, 0) } var onset: Int? = nil var run = 0 for (i, s) in ckFlags.enumerated() { run = s ? run + 1 : 0 if run >= onsetPersistEpochs { onset = i - onsetPersistEpochs + 1; break } } var final: Int? = nil for i in stride(from: n - 1, through: 0, by: -1) where ckFlags[i] { final = i; break } let o = onset ?? 0 var f = final ?? (n - 1) if f < o { f = n - 1 } return (o, f) } /// Build a 30 s hypnogram for [start, end] and return StageSegments. /// Stage a FORCED window from raw streams (no boundary detection): the same per-epoch classifier /// the detection path uses, run over exactly `[start, end]`. The sleep-edit path calls this to /// re-derive real stages for a hand-corrected window — so extending a boundary recovers genuine /// stages from the sensor data instead of a fabricated "awake" block. (#318) public static func stageSession(start: Int, end: Int, grav: [GravitySample], hr: [HRSample], rr: [RRInterval], resp: [RespSample]) -> [StageSegment] { // v7.0.2 perf (#707): stage each window AT MOST ONCE per (window, input-fingerprint). Both // `detectSleep` (per accepted run) and the sleep-edit restage call this with byte-identical streams // across post-sync passes / `body` re-evaluations; each call builds a fresh 30 s epoch grid + // per-epoch feature arrays before collapsing to a few `StageSegment`s. The key folds in the window // (an edit re-keys) and a strided fingerprint of every stream the V1 recipe READS (grav/hr/rr/resp — // resp IS consumed here via the epoch grid, unlike V2). Result-only, bounded, no raw arrays retained. let key = V1StageKey( start: start, end: end, grav: StreamFingerprint.of(grav, ts: { $0.ts }, quant: { Int(($0.x + $0.y + $0.z) * 1024) }), hr: StreamFingerprint.of(hr, ts: { $0.ts }, quant: { Int($0.bpm) }), rr: StreamFingerprint.of(rr, ts: { $0.ts }, quant: { Int($0.rrMs) }), resp: StreamFingerprint.of(resp, ts: { $0.ts }, quant: { $0.raw })) return stageSessionCache.value(key) { stageSessionUncached(start: start, end: end, grav: grav, hr: hr, rr: rr, resp: resp) } } private struct V1StageKey: Hashable { let start: Int; let end: Int let grav: StreamFingerprint; let hr: StreamFingerprint let rr: StreamFingerprint; let resp: StreamFingerprint } private static let stageSessionCache = AnalyticsMemoCache<V1StageKey, [StageSegment]>(capacity: 32) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |