Skip to main content

PhysioEx Logo

PhysioEx

PhysioEx (Physiological Signal Explainer) is a Python library for explainable sleep staging with deep learning.

PyPI Version Python Version Tests Docs License: MIT

Overview

PhysioEx provides a standard, reproducible way to train and evaluate state-of-the-art sleep-staging models, so that the effort can go into understanding what the models learn rather than into re-implementing them.

  • Data. Fifteen sleep datasets are read directly from the raw recordings; preprocessing runs lazily, per channel, and is cached on disk.
  • Models. Classic sleep-staging architectures, cardiorespiratory models and pretrained foundation encoders share one interface; published weights are loaded with load_from_pretrained.
  • Training. A PyTorch training and evaluation loop, also available from the command line (train, finetune, test_model).
  • Foundation encoders. Embedding extraction and linear probing on top of pretrained EEG and biosignal backbones.
  • Explainability. Gradient-based attribution (Saliency, Input×Gradient, Integrated and Expected Gradients, and their DFT/STFT variants), concept and prototype methods, and Layer-wise Relevance Propagation for CNN, recurrent and transformer models, with conservation diagnostics.

The full documentation is at https://guidogagl.github.io/physioex/.

Installation

Install the latest release from PyPI (Python 3.11 or later):

pip install physioex

Optional extras add dependencies that only some features need:

Extra Enables
foundation the REVE encoder (transformers)
datasets the HomePAP EDF fallback reader (mne)
tracking TensorBoard and Weights & Biases logging
explain Layer-wise Relevance Propagation (zennit)
gpu-monitor GPU monitoring during training (nvitop)
pip install "physioex[explain]"

To install from source, which includes changes not yet released on PyPI:

git clone https://github.com/guidogagl/physioex.git
cd physioex
pip install -e .

CPU-only installs and torchvision. The explain extra depends on zennit, which requires torchvision. If torch comes from the PyTorch CPU index, install torchvision from the same index before the extra; otherwise pip installs a CUDA build that fails at import with operator torchvision::nms does not exist:

pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
pip install "physioex[explain]"

Quickstart

Set PHYSIOEX_DATA to the directory that holds your datasets.

Train a model

import os
os.environ["PHYSIOEX_DATA"] = "/path/to/datasets"

from physioex.data.datasets import get_dataset, available_datasets
from physioex.models.tinysleepnet import TinySleepNet
from physioex.train.trainer import Trainer

print(available_datasets())  # -> ['alzheimers', 'ccshs', 'cfs', 'chat', 'dcsm', ...]

dataset = get_dataset("hmc")(
    channels=["EEG", "EOG", "EMG"],
    pipelines="time_domain",   # preset preprocessing pipeline
    sequence_length=21,
)

model = TinySleepNet(in_chan=3, n_classes=5)
model = Trainer.train(model=model, dataset=dataset, max_epochs=20)

The same dataset specification drives the command-line tools; see the CLI page in the documentation.

Load a pretrained model or extract embeddings

from physioex.models import load_from_pretrained, extract_embeddings, linear_probe
from physioex.models import CBraModEncoder

model = load_from_pretrained("protosleepnet-gagliardi")  # list_pretrained() lists all names
encoder = CBraModEncoder()
ds = encoder.get_dataset("hmc")                          # matched preprocessing
emb = extract_embeddings(encoder, ds)
scores = linear_probe(emb)

Stage whole nights from cardiorespiratory signals

With sequence_length=0, one dataset item is one whole night.

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("wav2sleep", verbose=True)
data = get_dataset("mesa")(
    channels=["ECG", "PPG", "ABD", "THX"],
    pipelines="wav2sleep",        # the authors' preprocessing
    sequence_length=0,
    label_transform="aasm4",      # W, Light, Deep, REM
    trim_excess_wake=False,
)
test = data.get_splits(split="wav2sleep")[2]
for subject, signals, labels, metadata in rep.iter_nights(data, test[:1]):
    stages = model.predict_night(signals)

Models

All models live in physioex.models.

Classic sleep-staging architectures

Trained from scratch on epoch sequences.

Model Class Input
Chambon et al. 2018 Chambon2018Net raw signals
TinySleepNet TinySleepNet raw signals
Tsinalis et al. 2016 TsinalisCNN raw signals
SeqSleepNet SeqSleepNet time-frequency images
L-SeqSleepNet LSeqSleepNet time-frequency images, long sequences
SleepTransformer SleepTransformer time-frequency images
CoRe-Sleep CoReSleep multimodal
ProtoSleepNet ProtoSleepNet prototype-based, interpretable by design

Cardiorespiratory models

Whole-night staging from ECG, PPG and respiratory effort. The architectures are re-implemented in PhysioEx; the published weights are downloaded from the original sources, and each model has a matching preprocessing preset.

Model Class Input load_from_pretrained name Weights License
wav2sleep Wav2Sleep any subset of ECG, PPG, ABD, THX (or EOG) wav2sleep, wav2sleep-eog authors (Hugging Face) MIT
Jones et al. 2024 JonesECGNet ECG, age, sex, start time jones-ecg and six variants authors (GitHub) AGPL-3.0
SleepPPG-Net SleepPPGNet PPG sleepppgnet-replica third-party replica non-commercial

examples/pretrained/<model>/verify.py compares each model with its paper on the published test splits. The public wav2sleep checkpoint is a later version than the paper's model (about 1 % lower, as confirmed by the authors), so its results are reported next to the paper's numbers rather than matched.

Foundation encoders

Pretrained backbones behind a uniform encode: (B, L, C, T) -> (B, L, D) interface, for embedding extraction and linear probing.

Encoder Class
CBraMod CBraModEncoder
BENDR BENDREncoder
LaBraM LaBraMEncoder
BIOT BIOTEncoder
SleepFM SleepFMEncoder
TF-C TFCEncoder
REVE REVEEncoder
S-JEPA SJEEncoder
NeuroLM NeuroLMEncoder

Datasets

Datasets are resolved by name with get_dataset(name); available_datasets() lists them. PhysioEx reads the original recordings, which you obtain from the source below. Descriptions of each dataset are in the Data page of the documentation.

Name Dataset Source Size
sleepedf Sleep-EDF Expanded PhysioNet 197 recordings
hmc Haaglanden Medisch Centrum PhysioNet 151 recordings
dcsm Danish Center for Sleep Medicine ERDA 255 recordings
shhs Sleep Heart Health Study NSRR 5,793 participants at visit 1
mesa Multi-Ethnic Study of Atherosclerosis NSRR 2,237 participants
mros Osteoporotic Fractures in Men Study NSRR 2,911 recordings
wsc Wisconsin Sleep Cohort NSRR 1,500 participants at baseline, several visits
stages Stanford Technology Analytics and Genomics in Sleep NSRR 1,914 recordings, 13 sites
ccshs Cleveland Children's Sleep and Health Study NSRR 515 children
cfs Cleveland Family Study NSRR visit-5 recordings
chat Childhood Adenotonsillectomy Trial NSRR baseline and follow-up recordings
hpap HomePAP NSRR three subsets (lab-full, lab-split, home)
mass Montreal Archive of Sleep Studies CEAMS 200 recordings
alzheimers Alzheimer's disease dataset UZ Leuven 69 participants
parkinsons Parkinson's disease dataset UZ Leuven 87 participants, up to 157 recordings

Citation

If you use PhysioEx, please cite:

@article{10.1088/1361-6579/adaf73,
  author  = {Gagliardi, Guido and Alfeo, Luca and Cimino, Mario G C A and Valenza, Gaetano and De Vos, Maarten},
  title   = {PhysioEx, a new Python library for explainable sleep staging through deep learning},
  journal = {Physiological Measurement},
  url     = {http://iopscience.iop.org/article/10.1088/1361-6579/adaf73},
  year    = {2025},
}

License

PhysioEx is released under the MIT License. Pretrained weights from third parties keep their own licenses, listed in the model tables above and printed when they are loaded.

Metadata

Release files for physioex 2.0.7

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for physioex 2.0.7
File Size Uploaded Provenance Actions
physioex-2.0.7.tar.gz 13.9 MB Without provenance Details for physioex-2.0.7.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for physioex 2.0.7
File Interpreter ABI Platform Actions
physioex-2.0.7-py3-none-any.whl Python 3 none any Details for physioex-2.0.7-py3-none-any.whl

Total release size: 14.3 MB

Release files / physioex-2.0.7.tar.gz

Download URL physioex-2.0.7.tar.gz
Size 13.9 MB
Tags Source
SHA-256 checksum
How to use checksums
7b51e59ed62e76112a58cba756f349c79706a879e8f7c5870879f53a07d75f97
BLAKE2b-256 checksum
How to use checksums
9c9297e7dcdd0c4a91a336b30981460df1c1aa5adc7f86482ed7b57681eed416
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.16

Release files / physioex-2.0.7-py3-none-any.whl

Download URL physioex-2.0.7-py3-none-any.whl
Size 442.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1a356dc90de40b6f3694290ca62d383dc97b89c0e0229d1e907784e9eb87e672
BLAKE2b-256 checksum
How to use checksums
eec3a7bd1cc852e74b6462ad156498bbc9877bfaa539ac4876ac841113e46f65
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.16

Security for physioex 2.0.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page