JonesECGNet (Jones, Itti & Sheth, 2024)#
An ECG-only sleep staging network: a convolutional front-end turns each 30-s epoch of single-lead ECG at 256 Hz into features, dense residual blocks add age, sex and the time since midnight, and a temporal convolutional network classifies the whole night into the five AASM stages.
Paper: Expert-level sleep staging using an electrocardiography-only feed-forward neural network, Computers in Biology and Medicine (2024), doi:10.1016/j.compbiomed.2024.108545.
Authors’ code and weights:
adammj/ecg-sleep-staging(GitHub), AGPL-3.0.physioex class:
physioex.models.jones_ecg:JonesECGNet, written from the paper and the checkpoint layout (no code copied from the AGPL repository).
Quick start#
from physioex.data.datasets import get_dataset
from physioex.models import load_from_pretrained
from physioex.train import replication as rep
model = load_from_pretrained("jones-ecg", verbose=True) # = "jones-ecg-primary"
data = get_dataset("mesa")(
channels=["ECG"],
pipelines="jones_ecg", # port of the authors' MATLAB preprocessing
sequence_length=0, # one item = one whole night
trim_excess_wake=False, # 5 AASM classes, no label transform
)
test = data.get_splits(split="wav2sleep-census")[2]
for subject, signals, labels, metadata in rep.iter_nights(data, test[:1]):
# metadata: {"age": years, "sex": "M"/"F", "recording_start": datetime.time}
stages = model.predict_night(signals, metadata) # (n_epochs,) in 0..4
When age, sex or the recording start are missing, predict_night fills the
corresponding inputs as the variant does for inputs it was not trained with
(standard-normal noise) and logs a warning once.
Inputs and preprocessing#
The jones_ecg preset applies JonesECGPreprocess to the ECG channel: removal
of loose-lead clipping, a zero-phase Chebyshev II high-pass (0.5 Hz), a notch
at the mains frequency plus an iterative search for further narrow-band noise,
resampling to 256 Hz, R-peak detection with the authors’ templates
(archetypes.mat, downloaded on first use) and scaling by twice the 90th
percentile of the R-wave amplitude, clipped to [-1, 1]. The module docstring
lists where the port deviates from the MATLAB code. NSRR readers provide the
subject metadata through subject_metadata(subject_id).
Seven checkpoints are available, all with the same hyper-parameters:
name |
metadata used |
temporal network |
|---|---|---|
|
age, sex, start time |
symmetric |
|
age, sex, start time |
causal |
|
start time |
symmetric |
|
age, sex |
symmetric |
|
none |
symmetric |
|
age, sex, cyclic start time |
symmetric |
|
age, sex, cyclic start time |
causal |
Replication#
examples/pretrained/jones-ecg/verify.py evaluates a variant on the
census-balanced held-out set (get_splits(split="wav2sleep-census")) with the
paper’s metric, the median of the per-recording kappas, and prints next to it
the authors’ own per-recording kappas on exactly the same recordings. Results
of the primary model:
dataset |
paper |
physioex |
status |
|---|---|---|---|
WSC |
0.6141 |
0.6141 |
PASS |
MESA |
0.6750 |
0.6714 |
PASS |
CCSHS |
0.8136 |
0.8034 |
outside tolerance |
On CCSHS (60 nights) the median per-recording difference from the authors’ kappas is -0.001, but single recordings differ by up to 0.13: the preprocessing port is not bit-exact. CFS and CHAT, and the census rows that need them, are skipped when their data are not available.
Training#
physioex does not ship a training script for this model. The authors’ recipe
is summarised in examples/pretrained/jones-ecg/TRAINING.md.
API#
- class physioex.models.jones_ecg.JonesECGNet(variant='primary', n_classes=5)[source]
Bases:
ModuleECG-only sleep staging network of Jones, Itti & Sheth (2024).
- Parameters:
Forward input:
x: (B, L, 1, 7680) or (B, L, 7680) float32 ECG, 256 Hz, in [-1, 1].additional: (B, L, 4) auxiliary features; ifNoneit is built withbuild_additional(), filling the columns the variant was not trained with by standard-normal noise.padding_mask: (B, L) or (B, L, 1) bool/float, 1 = real epoch; default all ones.
Forward returns (B, L, n_classes) log-probabilities over [W, N1, N2, N3, REM].
- static build_additional(n_epochs, variant, age=None, sex=None, midnight_offset=None, generator=None)[source]
Build the (n_epochs, 4) auxiliary-feature matrix for one night.
Columns: [sex (0=F, 1=M), age/100, night_e (−1→1 across the night), midnight_e]. For cyclic variants the last two columns are replaced by (cos t_e, sin t_e) with
t_e = 2π(e/2880 + midnight_offset mod 1). Columns the variant was not trained with (seeVARIANTS) are filled with standard-normal noise drawn fromgenerator: one draw per epoch per column, except demographics which are drawn once per night (size 2) and repeated over the epochs.
- forward(x, additional=None, padding_mask=None)[source]
Run per-epoch inference; returns (B, L, n_classes) log-probabilities.
- classmethod from_original(checkpoint_path, variant)[source]
Load one of the authors’ released checkpoints.
The checkpoints are plain dicts with a
model_state_dictentry whose keys this re-implementation reproduces exactly, so the load is strict and needs no remapping.- Parameters:
- Returns:
The model in
eval()mode.- Return type:
- static midnight_offset(start)[source]
Signed offset in days of
startfrom the nearest midnight.Positive when the start is in the (next) morning, negative in the (previous) evening: 01:30 → +1.5/24, 23:00 → -1/24.
- predict_night(signals, metadata=None)[source]
Classify one whole night, already preprocessed by the
jones_ecgpreset.- Parameters:
signals (dict[str, np.ndarray]) – Mapping of signal name to a
(L, 7680)float array of one night (256 Hz, 30-s epochs, in [-1, 1]); the night’s"ECG"channel is required. Unlike the fixed-grid models, JonesECGNet accepts any number of epochs, so the night is not padded or truncated here.metadata (dict | None) – optional dict with
"age"(years),"sex"("M"/"F") and"recording_start"(datetime.time). The auxiliary features are built withbuild_additional()for the model’s variant; a missing value that the variant was not trained with (seeVARIANTS) is filled with the variant’s noise fallback, with one warning per missing key.
- Returns:
int64 class indices of shape
(L,)in AASM 5-class order [W, N1, N2, N3, REM]. Runs undertorch.no_grad()in eval mode, batch of one, on the model’s current device.- Return type:
np.ndarray
- class physioex.data.steps.JonesECGPreprocess(line_freq=60.0, remove_clips=True, find_noise=True, archetypes_path=None)[source]
Bases:
PreprocessingStepFull Jones et al. (2024) ECG preprocessing in a single step.
Turn one raw single-lead ECG channel (whole night, any fs) into the network input of
physioex.models.jones_ecg.JonesECGNet: 256 Hz, scaled by the per-night R-wave normalization factor and clipped to[-1, 1].Order of operations (MATLAB stage 2 -> stage 3 -> stage 5 scaling):
remove_large_clips— loose-lead clipping mask removal;zero-phase Chebyshev-II high-pass (0.5 / 0.25 Hz, 0.1 / 60 dB);
line-noise notch at
line_freq(with the aliasing rules) plus up to 10 iterative extra-noise notches (iffind_noise);resample to 256 Hz with
resample_poly(p/q fromFraction(256/fs).limit_denominator());R-wave detection (local variation + template; archetypes when available) and normalization factor = 2 x P90 of per-beat
max |x|;divide by the factor, clip to
[-1, 1].
Parameters#
- line_freqfloat
Mains frequency to notch (60.0 in the authors’ US data, 50.0 in EU data).
- remove_clipsbool
Apply the loose-lead clip-mask removal.
- find_noisebool
Run the iterative extra-noise notch search.
- archetypes_pathstr, optional
Path to
archetypes.mat.None(default) downloads it from the authors’ repository on first use. Deliberately excluded fromspec()— a path must not change the cache hash.
Degenerate inputs (all zeros, fully clipped, no beats found) return zeros of the correct length with a warning instead of raising.
- compile(fs_in, header=None)[source]
Precompute any expensive state and return a callable specialized for fs_in.
headeris an optional per-channel metadata dict (physical dimension, physical min/max, …) forwarded to steps that declare they need it (needs_headerattribute, e.g.PhysicalScale). Steps that ignore it simply do not read it; the signature default keeps every existingcompile(fs)call site working.- Parameters:
- Return type: