physioex.train.replication#

Library support for replicating published cardiorespiratory results.

The three integrated cardiorespiratory sleep-staging networks (Wav2Sleep, SleepPPG-Net and the ECG-only network of Jones et al.) report their headline numbers as Cohen’s kappa computed in two different ways:

  • pooled — one confusion matrix over every scored epoch of every recording (Wav2Sleep’s kappa_T, Jones’ overall_kappa);

  • median record — one kappa per recording, then the median across recordings (SleepPPG-Net, Jones’ headline number).

This module provides the plumbing to recompute those numbers on whole nights and check them against the values printed in the papers:

No GPU or data access happens at import time.

Module Attributes

SPLIT_VISITS

Visits that the published test splits draw from, per dataset registry name.

Functions

align(pred, labels)

Cut prediction and labels to their common length.

check(results, targets)

Compare measured results against the paper's claimed values.

evaluate(y_true_records, y_pred_records, ...)

Compute the kappa metrics of one evaluation run.

format_table(rows)

Render comparison rows as a fixed-width text table.

has_scoring_issues(dataset, subject_id)

True when the night has no N1, N3 or REM epoch in its raw AASM labels.

iter_nights(dataset, subject_ids)

Yield one entry per whole night of the given subjects.

load_paper_metrics(path)

Read the paper's claimed results from a JSON file.

replication_kwargs(dataset_name)

Constructor keyword sets that together cover a dataset's split nights.

Classes

PaperTarget(dataset, condition, value[, ...])

One number to replicate from a paper.

class physioex.train.replication.PaperTarget(dataset, condition, value, metric='pooled_kappa', tolerance=0.05, assert_=True, requires=<factory>, note='')[source]#

Bases: object

One number to replicate from a paper.

Parameters:
dataset#

dataset name (e.g. "shhs").

Type:

str

condition#

the split/condition the paper reports (e.g. "test").

Type:

str

value#

the published value.

Type:

float

metric#

"pooled_kappa" or "median_record_kappa".

Type:

str

tolerance#

accepted absolute deviation |ours - paper|.

Type:

float

assert_#

True = the target must PASS (FAIL otherwise); False = the number is only reported (REPORT).

Type:

bool

requires#

dataset names whose results must all be present for the target to be evaluated (default [dataset]).

Type:

List[str]

note#

free text shown in the table for context.

Type:

str

physioex.train.replication.SPLIT_VISITS: dict[str, tuple[int, ...]] = {'mros': (1, 2), 'shhs': (1, 2), 'wsc': (1, 2, 3, 4)}#

Visits that the published test splits draw from, per dataset registry name. The readers load one visit per instance (visit= argument), so a replication builds one instance per visit and pools the nights.

physioex.train.replication.align(pred, labels)[source]#

Cut prediction and labels to their common length.

Whole-night models with a fixed input grid (Wav2Sleep, SleepPPG-Net: 1200 epochs) produce predictions for padded epochs when the night is shorter than the grid, and the authors’ inference drops the tail labels of nights longer than the grid. Both effects leave pred and labels at different lengths; cutting both to min(len) recovers the epochs that are scored and predicted alike.

Parameters:
  • pred (ndarray) – prediction array, (L_p,) class indices (any length).

  • labels (ndarray) – label array, (L_l,) class indices.

Returns:

(pred_aligned, labels_aligned, n_dropped) where the first two have shape (min(L_p, L_l),) and n_dropped is the number of labelled epochs that were dropped (max(0, L_l - min(L_p, L_l))) so callers can report it.

Return type:

tuple[ndarray, ndarray, int]

physioex.train.replication.check(results, targets)[source]#

Compare measured results against the paper’s claimed values.

Parameters:
Returns:

One dict per target with keys dataset, condition, metric, paper, ours, delta, tolerance, status (plus note). status is "SKIP" when any dataset in the target’s requires has no results, "PASS"/"FAIL" when assert_ is true and |delta| <= tolerance (or not), and "REPORT" when assert_ is false. ours/delta are None for SKIP rows.

Return type:

List[Dict[str, Any]]

physioex.train.replication.evaluate(y_true_records, y_pred_records, n_classes)[source]#

Compute the kappa metrics of one evaluation run.

Wraps physioex.train.metrics.pooled_kappa(), physioex.train.metrics.median_record_kappa() and physioex.train.metrics.per_record_kappa() (epochs with an unscored true label are ignored there).

Parameters:
  • y_true_records (Sequence[ndarray]) – one label array (class indices, -1 unscored) per recording.

  • y_pred_records (Sequence[ndarray]) – one prediction array per recording, same order.

  • n_classes (int) – number of classes (4 for Wav2Sleep/SleepPPG-Net, 5 for Jones).

Returns:

dict with "pooled_kappa", "median_record_kappa", "per_record_kappa" (list), "n_records" and "n_epochs" (total scored epochs across recordings).

Return type:

Dict[str, Any]

physioex.train.replication.format_table(rows)[source]#

Render comparison rows as a fixed-width text table.

Parameters:

rows (Sequence[dict]) – the dicts returned by check() (any subset of their keys is used, in the canonical column order).

Returns:

The table as a string (no trailing newline).

Return type:

str

physioex.train.replication.has_scoring_issues(dataset, subject_id)[source]#

True when the night has no N1, N3 or REM epoch in its raw AASM labels.

wav2sleep’s ingestion marks such nights as .issues (recordings scored sleep/wake only, with N2 as the sole sleep class) and its per-dataset test evaluation leaves them out (exclude_issues=True). The check reads the labels before any label_transform, since aasm4 merges N1 into Light.

Parameters:
Return type:

bool

physioex.train.replication.iter_nights(dataset, subject_ids)[source]#

Yield one entry per whole night of the given subjects.

The dataset must be built in whole-night mode (sequence_length <= 0); in that mode item index i is exactly subject i (see BasePhysioDataset._get_recording_item).

Parameters:
  • dataset (BasePhysioDataset) – a BasePhysioDataset instance (whole-night mode).

  • subject_ids (Sequence[str]) – subject ids to iterate over, in any order.

Yields:

Tuples (subject_id, signals, labels, metadata) where

  • signals maps the requested channel name (channel_info[key] ["request"], e.g. "ECG"; the item key such as "ECG_0" when no request is recorded) to a (L, T_e) float32 array of the (preprocessed) whole-night signal. Channels the subject lacks (available=False, zero-filled by the dataset) are left out;

  • labels is the (L,) int64 label array in the dataset’s label transform (e.g. aasm4: W=0, Light=1, Deep=2, REM=3; -1 unscored), aligned with the signals;

  • metadata is the return value of dataset.subject_metadata(subject_id) when the dataset provides that method, else {}.

Return type:

Iterator[tuple[str, dict[str, np.ndarray], np.ndarray, dict]]

physioex.train.replication.load_paper_metrics(path)[source]#

Read the paper’s claimed results from a JSON file.

The file has the top-level keys "model", "source", "metric", "tolerance" and "targets" (a list of objects with keys dataset, condition, value and optional metric, tolerance, assert (bool, default true), requires, note). A target’s optional metric/tolerance/assert override the top-level ones.

Parameters:

path (str | Path) – path to the JSON file.

Returns:

(header, targets) where header is the top-level dict without "targets" and targets the list of PaperTarget.

Return type:

tuple[dict, list[PaperTarget]]

physioex.train.replication.replication_kwargs(dataset_name)[source]#

Constructor keyword sets that together cover a dataset’s split nights.

One dict per visit for multi-visit datasets (see SPLIT_VISITS), else a single dict. CCSHS also gets exclude_subjects=[]: its default exclusion list (recordings whose XML disagrees with the NSRR summary CSV) is a physioex choice the published evaluations did not make.

Parameters:

dataset_name (str)

Return type:

list[dict]