Inspiration

A night in a sleep lab (polysomnography) is the reference for measuring sleep, but in the US it costs about $3,000 on average (Sleep Foundation), and one New York pediatric sleep center quotes waits of 2 to 4 months (ColumbiaDoctors). Meanwhile, far simpler recordings of the heart exist: a Holter monitor or an ECG chest strap records every heartbeat through the night, and heart rate and its variability change with sleep stage and with breathing pauses. We wanted to know, with numbers, how much of a sleep report the time between heartbeats can recover, and how wrong it can be. Somnibeat is meant for researchers and clinicians who already have overnight ECG or RR data and want a quick, transparent first look, and for students of sleep physiology; it is not for self-diagnosis or a replacement for a sleep study.

What it does

Somnibeat turns one night of heartbeat intervals (RR intervals from an ECG) into a sleep report: total sleep time, sleep efficiency, wake bouts, minutes with suspected sleep apnea, and a wake/sleep chart (3- and 4-stage charts are labeled experimental). Every number is shown next to its measured error on recordings the model never saw, and next to a trivial baseline.

  • Live demo, nothing to install: https://handue.github.io/somnibeat/ . Open a sample night or drop your own CSV (time_s, rr_ms). Everything runs in the browser; the file is never sent to a server.
  • Raw ECG? scripts/ecg_to_rr.py converts an EDF/WFDB recording (or an RR export) into that CSV with the same R-peak detector the evaluation used.
  • Code and full write-up: https://github.com/handue/somnibeat (README, docs/WRITEUP.md).

Research prototype, not a diagnostic tool.

How we built it

  1. Data. Five public PhysioNet databases with ECG and expert sleep scoring: CAP Sleep Database (106 records) and MIT-BIH Polysomnographic (18 records) for sleep staging, Apnea-ECG for apnea minutes (MIT-BIH event-derived apnea labels were used only to select the apnea model), UCDDB (25 nights) and the HMC Sleep Staging database (151 recordings) for testing only. Data-check scripts verified sampling rates, channels, epoch alignment and label definitions from the files before any modeling (587 checks for v1, 872 for the v2 training data and 24 for HMC before any prediction; all pass after the documented fixes).
  2. ECG to heartbeats. Our own Pan-Tompkins-style R-peak detector finds 99.93% of annotated beats in the 18 MIT-BIH Polysomnographic records (99.78% positive predictive value). Implausible intervals are flagged, never interpolated.
  3. Features. For every 30-second epoch: heart-rate variability in the time and frequency domain (RMSSD, SDNN, Lomb-Scargle band powers), DFA alpha1, longer 5-10 minute context and cyclic variation of heart rate, normalized within each night.
  4. Models. Gradient boosting with balanced class weights, followed by a hidden Markov model (Viterbi) that turns per-epoch probabilities into a plausible night. Apnea minutes use a gradient boosting + logistic regression ensemble. No deep learning: small, explainable models that run in a browser in seconds.
  5. Same code in the browser. Feature extraction, tree inference, smoothing and the report are reimplemented in JavaScript; parity tests check them against the Python reference.

Evaluation

What we measured. Total sleep time error (minutes), sleep efficiency error (percentage points), wake-bout count error, apnea-minute error (minutes), and epoch-by-epoch agreement with expert scoring (Cohen's kappa), each with a record-level bootstrap 95% CI and Bland-Altman limits of agreement.

How. Model choices were made on training data only, by cross-dataset validation (train on CAP, test on MIT-BIH, and the reverse), under a protocol written before the experiments. The final model was frozen (git tag v2-frozen) and then run once on HMC, a hospital dataset never used before. It is compared with our first model (v1) and with a trivial baseline ("asleep from lights-off") on the same epochs.

Results on HMC (146 nights, primary analysis):

  • Total sleep time error: 46.1 (95% CI 39.5 to 52.8) min, versus 79.4 min for the trivial baseline; bias -6.0 min.
  • Sleep efficiency error: 10.2 (95% CI 8.8 to 11.6) points (baseline 17.4).
  • Wake-bout error: 7.6 (95% CI 6.6 to 8.7) (baseline 11.2).
  • Sleep/wake kappa: 0.43 (95% CI 0.39 to 0.46) (v1: 0.39). 3-stage kappa 0.42 (v1 0.36) and 4-stage kappa 0.38 (v1 0.31), both with separated confidence intervals; the sleep/wake gain has overlapping intervals.
  • Apnea (UCDDB, second look): apnea-minute error 66.9 (95% CI 45.7 to 90.6) min (v1 78.2; "no apnea" baseline 111.2).

What it means. Across a group of nights, total sleep time and sleep efficiency are close to the sleep lab (bias -6.0 min and -1.5 points) and much better than the trivial baseline, but wake bouts are systematically undercounted (bias -7.2). v2 agrees with experts epoch by epoch better than v1 for 3 and 4 stages (separated intervals); its sleep/wake gain is not conclusive on its own. For a single night, the total sleep time can still be off by about two hours (95% limits of agreement -127 to 115 min), and v2 did not improve night-level totals over v1 (total sleep time error 46.1 min for v2 vs 45.0 min for v1). It is not suitable for diagnosing an individual, and we make no accuracy claim for people with arrhythmias or for devices we did not test.

Reproducibility. make reproduce downloads the raw data (SHA-256 verified) and rebuilds the results, web files and documents. A clean clone rebuilt the result, web and document files listed in docs/reproduction_check.md byte for byte (after the last fix there, only the final selection step and the steps after it were rerun). The seed and model hyperparameters are in config/; the v2 selection rules are fixed in the scripts and docs/v2_protocol.md, and the frozen v2 specification is in results/v2/v2_final_spec.json.

Who benefits, and who could be harmed

  • Benefits: researchers and clinicians with existing overnight ECG or Holter data get a documented, reproducible sleep estimate with its expected error, without a PSG; students get a transparent example of what heart rhythm can and cannot say about sleep. Nothing is uploaded, which removes a privacy barrier.
  • False reassurance: v2 misses many apnea minutes (sensitivity 0.41) and tends to underestimate them (bias -23.8 min, 95% CI -59.1 to 8.7, UCDDB second look), so someone with apnea could be falsely reassured and skip a sleep study. Every screen says it is not a diagnostic tool.
  • Hidden fragmentation: v2 undercounts wake bouts (bias -7.2 on HMC), so a fragmented night can look smooth.
  • Needless worry: noisy recordings or arrhythmias (atrial fibrillation, ectopic beats, pacemakers, beta-blockers) can produce false wake or apnea minutes. Low-quality stretches are flagged, but arrhythmias are not detected.
  • Unequal accuracy: all test data are clinical referrals; children are absent or cannot be identified (HMC reports only a mean age), ethnicity is not reported, and we did not report errors by sex or age, so errors for under-represented groups are unknown.

Limitations

  • Tested on hospital ECG only; no validation on home wearables (chest straps, watches, rings), so we make no accuracy claim for them.
  • Test populations are clinical (UCDDB: one hospital, 25 nights, mostly men; HMC: one hospital). Training data are mostly patients; MIT-BIH is all male.
  • UCDDB was used for v1 and again as a second look for v2, so its v2 numbers are weaker evidence than HMC.
  • 3- and 4-stage agreement is far below agreement between human scorers; those charts are experimental.
  • Apnea labels are defined differently in the training and test databases, so apnea errors mix model error with label mismatch.
  • 5 HMC recordings in which fewer than half of the epochs had usable RR coverage (two with almost no usable ECG) were excluded by a rule fixed before prediction; on all 151 recordings, total sleep time error is 52.5 min and sleep/wake kappa 0.40.

Challenges we ran into

  • Our first model looked better in development than on new data. Internal cross-validation mixed the training databases and overstated transfer. For v2 we switched to cross-dataset validation, froze the model with a git tag, and only then touched the new test set.
  • Data surprises: an undocumented stage code, a recording whose hypnogram starts 48 minutes before its ECG file (excluded, because the alignment could not be verified), recordings with flat ECG, and different apnea-label definitions between databases. Each was found by explicit checks and documented rather than silently fixed.
  • Exact browser parity: reimplementing every feature and the tree and HMM inference in JavaScript so that the browser and Python agree, with tests.
  • Byte-for-byte reproducibility: wall-clock times, timestamps and machine-specific details had to be removed from result files before a clean clone matched.

Accomplishments that we're proud of

  • A real held-out test. The model was frozen with a git tag and then run once on 146 hospital nights it had never seen, against a trivial baseline and our first model.
  • Measurable gains where they count for staging. 3-stage kappa rose from 0.36 to 0.42 and 4-stage kappa from 0.31 to 0.38, with non-overlapping confidence intervals.
  • One command rebuilds the evidence. A fresh clone ran make reproduce from the raw PhysioNet downloads and rebuilt the result, web and document files listed in docs/reproduction_check.md byte for byte.
  • The browser runs exactly the evaluated model. Feature extraction, tree and HMM inference were ported to JavaScript and checked against Python by parity tests, so the demo runs without a server or installation and the file stays on the device.
  • Every number is traceable. The README, write-up and this page are generated from the results JSON; no result is typed by hand.

What we learned

Better epoch-level agreement did not automatically give better night-level totals. A trivial baseline and a held-out test set are what make a number mean something. Writing the evaluation protocol before the experiments kept us honest, including when the results were not what we hoped.

What's next for Somnibeat

What we would do with another month:

  1. Validate on a public dataset with simultaneous PSG and a wearable, and report the accuracy drop before any claim about home use.
  2. Report errors by sex, age and apnea severity, pre-registered.
  3. Select and calibrate on night-level error, and fix the wake-bout undercount.
  4. Derive apnea labels the same way in every database and add ECG-derived respiration features.
  5. Detect atrial fibrillation and frequent ectopy and flag those nights instead of reporting confidently.
  6. Show a per-night uncertainty interval (for example conformal prediction) instead of only population-level error.

Attribution

Data: UCDDB (doi:10.13026/C26C7D), CAP Sleep Database (Terzano et al., Sleep Med 2001), MIT-BIH Polysomnographic Database (Ichimaru and Moody 1999; doi:10.13026/C23K5S) and Apnea-ECG (Penzel et al., Computers in Cardiology 2000), under the Open Data Commons Attribution License v1.0, and the HMC Sleep Staging database (Alvarez-Estevez and Rijsman, v1.1, doi:10.13026/t79q-fr32; PLoS ONE 2021), under CC BY 4.0. PhysioNet: Pollard et al., Nature Health 2026. Libraries: NumPy, SciPy, pandas, scikit-learn, wfdb, pyEDFlib, Matplotlib and pytest. Demo video: Playwright (screen capture), Kokoro-82M (narration), Parakeet TDT 0.6B v2 (narration check), FFmpeg (editing). Full list with licenses: SOURCES.md.

AI tools: Claude Code (Anthropic, model Claude Opus 5.5) wrote most of the code, the documentation and the demo-video tooling, and ran the code reviews, under the author's direction. The author set the problem, datasets, evaluation protocol and decision gates, and reviewed the results. No generative model runs in the demo itself. Details: README, "AI tools used".

Built With

Share this project:

Updates

Submission history