Skip to content

sleep_statistics

The sleep statistics of a scored hypnogram.

One implementation of the thirteen statistics that :class:~yousleep_common.models.biomarkers.Biomarkers describes, so that every figure computed from a hypnogram (a report, or a model's validation against an expert) is the same number for the same scoring. Each field's description on Biomarkers states its definition; this module computes exactly that.

A hypnogram is given as parallel arrays: each interval's start and end in milliseconds, and its :class:StageCode. Intervals may have any length and may leave gaps; a gap, like an interval of no stage, counts toward time in bed and nothing else. Choosing which intervals belong to the night (lights off to lights on, say) is the caller's: pass the intervals inside it and the time in bed it spans.

This module needs numpy: install the sleep-statistics extra (pip install "yousleep-common[sleep-statistics]").

StageCode

Bases: IntEnum

A scored interval's stage, as the statistics read it.

Any other integer is no stage: an unscored interval, a label in no group (the generic "Sleep stage N", "Sleep stage ?") or movement time. It counts toward time in bed and nothing else. The order follows depth for wake to N3, with REM apart.

sleep_statistics(start_ms, end_ms, stage, *, time_in_bed_ms=None, soremp_threshold_min=DEFAULT_SOREMP_THRESHOLD_MIN)

Compute the thirteen sleep statistics of one hypnogram.

Durations are summed in whole milliseconds and divided once, so the result does not depend on the order the intervals were added up in.

Parameters:

Name Type Description Default
start_ms ArrayLike

Each interval's start, in milliseconds, in time order.

required
end_ms ArrayLike

Each interval's end, in milliseconds.

required
stage ArrayLike

Each interval's :class:StageCode; any other integer is no stage.

required
time_in_bed_ms tuple[int, int] | None

The (start, end) of time in bed, in milliseconds, when the night is a window of the recording. None spans the first interval's start to the last one's end.

None
soremp_threshold_min float

Minutes from sleep onset within which the first REM counts as a sleep-onset REM period (inclusive).

DEFAULT_SOREMP_THRESHOLD_MIN

Returns:

Type Description
Biomarkers

The statistics. One a night does not define (WASO without sleep, REM

Biomarkers

latency without REM) is None, never 0.

Raises:

Type Description
ValueError

If there are no intervals, the arrays differ in length, or time in bed is not longer than zero.

TypeError

If the times or the codes are not integers.

stage_codes(labels)

Return each staging label's code, through its stage group.

Parameters:

Name Type Description Default
labels Iterable[EventLabel]

Staging event labels, in order.

required

Returns:

Type Description
NDArray[int8]

One code per label: its group's :class:StageCode, or UNSCORED for

NDArray[int8]

a label in no group.