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

jones-ecg-primary (jones-ecg)

age, sex, start time

symmetric

jones-ecg-realtime

age, sex, start time

causal

jones-ecg-no-demographics

start time

symmetric

jones-ecg-no-time

age, sex

symmetric

jones-ecg-only-ecg

none

symmetric

jones-ecg-cyclic

age, sex, cyclic start time

symmetric

jones-ecg-cyclic-realtime

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: Module

ECG-only sleep staging network of Jones, Itti & Sheth (2024).

Parameters:
  • variant (str) – one of VARIANTS (default "primary").

  • n_classes (int) – number of sleep classes (5: W, N1, N2, N3, REM).

Forward input:

  • x: (B, L, 1, 7680) or (B, L, 7680) float32 ECG, 256 Hz, in [-1, 1].

  • additional: (B, L, 4) auxiliary features; if None it is built with build_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 (see VARIANTS) are filled with standard-normal noise drawn from generator: one draw per epoch per column, except demographics which are drawn once per night (size 2) and repeated over the epochs.

Raises:

ValueError – if age, sex or midnight_offset is missing for a variant that was trained with it.

Parameters:
Return type:

Tensor

forward(x, additional=None, padding_mask=None)[source]

Run per-epoch inference; returns (B, L, n_classes) log-probabilities.

Parameters:
Return type:

Tensor

classmethod from_original(checkpoint_path, variant)[source]

Load one of the authors’ released checkpoints.

The checkpoints are plain dicts with a model_state_dict entry whose keys this re-implementation reproduces exactly, so the load is strict and needs no remapping.

Parameters:
  • checkpoint_path (str | Path) – path to the .pt checkpoint (e.g. downloaded from adammj/ecg-sleep-staging).

  • variant (str) – variant name (used to build the matching architecture).

Returns:

The model in eval() mode.

Return type:

JonesECGNet

static midnight_offset(start)[source]

Signed offset in days of start from 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.

Parameters:

start (time | datetime)

Return type:

float

predict_night(signals, metadata=None)[source]

Classify one whole night, already preprocessed by the jones_ecg preset.

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 with build_additional() for the model’s variant; a missing value that the variant was not trained with (see VARIANTS) 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 under torch.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: PreprocessingStep

Full 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):

  1. remove_large_clips — loose-lead clipping mask removal;

  2. zero-phase Chebyshev-II high-pass (0.5 / 0.25 Hz, 0.1 / 60 dB);

  3. line-noise notch at line_freq (with the aliasing rules) plus up to 10 iterative extra-noise notches (if find_noise);

  4. resample to 256 Hz with resample_poly (p/q from Fraction(256/fs).limit_denominator());

  5. R-wave detection (local variation + template; archetypes when available) and normalization factor = 2 x P90 of per-beat max |x|;

  6. 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 from spec() — 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.

header is an optional per-channel metadata dict (physical dimension, physical min/max, …) forwarded to steps that declare they need it (needs_header attribute, e.g. PhysicalScale). Steps that ignore it simply do not read it; the signature default keeps every existing compile(fs) call site working.

Parameters:
Return type:

CompiledStep

spec()[source]

Return canonical, hashable text repr.

Format: ClassName(key1=val1,key2=val2,…) with sorted keys, floats normalized via f’{float(v):.10g}’.

Return type:

str

Parameters:
  • line_freq (float)

  • remove_clips (bool)

  • find_noise (bool)

  • archetypes_path (Optional[str])