yasa.Hypnogram#

class yasa.Hypnogram(values, n_stages=5, *, freq='30s', start=None, tz=None, scorer=None, proba=None)[source]#

Standard class for representing and analyzing a sleep hypnogram.

A Hypnogram is a sequence of sleep stage labels sampled at a fixed epoch duration (default 30 seconds). Three assumptions underpin every method in the class:

  1. Uniform epoch duration. Every epoch has the same length, set once via freq. Variable-length epochs are not supported.

  2. Contiguous recording. Epochs are assumed to be consecutive with no temporal gaps.

  3. Closed stage vocabulary. Valid stage labels are fixed by n_stages at construction and cannot be customised. Supported sets are: 2-stage (Wake/Sleep), 3-stage (Wake/NREM/REM), 4-stage (Wake/Light/Deep/REM), and 5-stage (Wake/N1/N2/N3/REM). Artefact (ART) and Unscored (UNS) are always part of the vocabulary regardless of n_stages.

Stages are stored as strings ("WAKE", "N2", "REM", …) rather than integers, reducing the risk of misinterpretation. The object also carries its own metadata: epoch duration, an optional start datetime with timezone, and an optional scorer name.

To create a Hypnogram from a legacy integer array, use from_integers.

To save a Hypnogram to disk and reload it with all metadata intact, use to_json and from_json.

For a step-by-step introduction covering all features, see the Working with Hypnograms tutorial.

Added in version 0.7.0.

Main methods

Method

Description

as_int

Return hypnogram values as a Series of integers.

as_events

Return a BIDS-compatible events DataFrame (onset, duration, stage).

get_mask

Return a boolean array marking epochs that match one or more stage labels.

to_dict / to_json

Serialize the hypnogram and all metadata to a dictionary or JSON file.

crop

Slice the hypnogram by epoch index or absolute timestamp.

pad

Extend the hypnogram before and/or after with a chosen fill stage.

upsample

Resample the hypnogram to a finer epoch resolution.

consolidate_stages

Merge stages to a coarser hypnogram (e.g. 5-stage to 2-stage).

upsample_to_data

Align and upsample the hypnogram to match an EEG recording sample-by-sample.

sleep_statistics

Compute standard AASM sleep statistics (TIB, TST, SE, WASO, stage durations, …).

transition_matrix

Compute the stage-transition count matrix and probability matrix.

find_periods

Detect consecutive runs of a single stage exceeding a minimum duration.

evaluate

Compare two hypnograms epoch-by-epoch (kappa, F1, MCC, …).

plot_hypnogram

Plot the hypnogram as a standard hypnogram figure.

plot_hypnodensity

Plot per-epoch stage probabilities as a stacked area chart (requires proba).

simulate_similar

Simulate a new hypnogram with the same transition probabilities as this one.

The full list of methods and attributes is available at the bottom of this page.

Parameters:
valuesarray_like

A vector of stage values, represented as strings. See some examples below:

  • 2-stage hypnogram (Wake/Sleep): ["W", "S", "S", "W", "S"]

  • 3-stage (Wake/NREM/REM): pd.Series(["WAKE", "NREM", "NREM", "REM", "REM"])

  • 4-stage (Wake/Light/Deep/REM): np.array(["Wake", "Light", "Deep", "Deep"])

  • 5-stage (default): ["N1", "N1", "N2", "N3", "N2", "REM", "W"]

Artefacts (“Art”) and unscored (“Uns”) epochs are always allowed regardless of the number of stages in the hypnogram.

Note

Abbreviated or full spellings for the stages are allowed, as well as lower/upper/mixed case. Internally, YASA will convert the stages to full spelling and uppercase (e.g. “w” -> “WAKE”).

n_stagesint

Whether values comes from a 2, 3, 4 or 5-stage hypnogram. Default is 5-stage, meaning that the following sleep stages are allowed: N1, N2, N3, REM, WAKE.

freqstr

A pandas frequency string indicating the frequency resolution of the hypnogram. Default is “30s” meaning that each value in the hypnogram represents a 30-seconds epoch. Examples: “1min”, “10s”, “15min”. A full list of accepted values can be found in the pandas offset aliases documentation.

freq will be passed to the pandas.date_range function to create the time index of the hypnogram.

startstr, datetime.datetime, or pandas.Timestamp, optional

Start datetime of the hypnogram (e.g. "2022-12-15 22:30:00"). When provided, the hypnogram index becomes a pandas.DatetimeIndex, otherwise it is a pandas.RangeIndex of epoch numbers. Accepts timezone-naive strings / datetimes as well as tz-aware datetime or Timestamp objects.

tzstr or datetime.timezone, optional

Timezone of the hypnogram start time, e.g. "Europe/Paris" or "America/New_York". Only used when start is timezone-naive. A full list of valid timezone strings is available via import zoneinfo; zoneinfo.available_timezones().

scorerstr

An optional string indicating the scorer name. If specified, this will be set as the name of the pandas.Series, otherwise the name will be set to “Stage”.

probapandas.DataFrame

An optional dataframe with the probability of each sleep stage for each epoch in hypnogram. Each row must sum to 1. This is automatically included if the hypnogram is created with yasa.SleepStaging.

Examples

Create a 2-stage hypnogram and inspect its contents:

>>> from yasa import Hypnogram
>>> values = ["W", "W", "W", "S", "S", "S", "S", "S", "W", "S", "S", "S"]
>>> hyp = Hypnogram(values, n_stages=2)
>>> hyp
<Hypnogram | 12 epochs x 30s (6.00 minutes), 2 unique stages>
 - Use `.hypno` to get the string values as a pandas.Series
 - Use `.as_int()` to get the integer values as a pandas.Series
 - Use `.plot_hypnogram()` to plot the hypnogram
See the online documentation for more details.
>>> hyp.hypno
Epoch
0      WAKE
1      WAKE
2      WAKE
3     SLEEP
4     SLEEP
5     SLEEP
6     SLEEP
7     SLEEP
8      WAKE
9     SLEEP
10    SLEEP
11    SLEEP
Name: Stage, dtype: category
Categories (4, str): ['WAKE', 'SLEEP', 'ART', 'UNS']
>>> hyp.n_epochs
12
>>> import pandas as pd
>>> pd.Series(hyp.sleep_statistics())
TIB         6.0000
SPT         4.5000
WASO        0.5000
TST         4.0000
SE         66.6667
SME        88.8889
SFI         7.5000
SOL         1.5000
SOL_5min       NaN
WAKE        2.0000
dtype: float64
>>> counts, probs = hyp.transition_matrix()
>>> counts
To Stage    WAKE  SLEEP
From Stage
WAKE           2      2
SLEEP          1      6

For more examples covering 4-stage and 5-stage hypnograms, visualization, slicing, EEG alignment, saving, and scorer comparison, see the Working with Hypnograms tutorial.

Methods

__init__(values[, n_stages, freq, start, ...])

as_events()

Return a pandas DataFrame summarizing epoch-level information.

as_int()

Return hypnogram values as integers.

consolidate_stages(new_n_stages)

Reduce the number of stages in a hypnogram to match actigraphy or wearables.

copy()

Return a new copy of the current Hypnogram.

crop([start, end])

Crop the hypnogram to a range of epochs or absolute timestamps.

evaluate(obs_hyp)

Evaluate agreement between two hypnograms of the same sleep session.

find_periods([threshold, equal_length])

Find sequences of consecutive values exceeding a certain duration in hypnogram.

from_dict(d)

Reconstruct a Hypnogram from a dictionary produced by to_dict.

from_integers(values[, mapping, n_stages, ...])

Create a Hypnogram from an integer-encoded hypnogram array.

from_json(fname)

Load a Hypnogram from a JSON file saved with to_json.

from_profusion(fname, *[, start, tz, scorer])

Create a Hypnogram from a Compumedics Profusion hypnogram (.xml).

get_mask(stages)

Return a boolean NumPy array marking epochs that match the given stages.

pad([before, after, fill_value])

Extend the hypnogram by padding epochs before and/or after.

plot_hypnodensity([palette, ax])

Plot the hypnodensity: per-epoch stage probabilities as a stacked area chart.

plot_hypnogram(**kwargs)

Plot the hypnogram.

simulate_similar(**kwargs)

Simulate a new hypnogram based on properties of the current hypnogram.

sleep_statistics()

Compute standard sleep statistics from a hypnogram.

to_dict()

Return the Hypnogram as a JSON-serializable dictionary.

to_json(fname)

Save the Hypnogram to a JSON file.

transition_matrix()

Create a state-transition matrix from a hypnogram.

upsample(new_freq)

Upsample hypnogram to a higher frequency.

upsample_to_data(data[, sf, ...])

Upsample a hypnogram to a given sampling frequency and fit the resulting hypnogram to corresponding EEG data, such that the hypnogram and EEG data have the exact same number of samples.

Attributes

duration

Total duration of the hypnogram, expressed in minutes.

end

End date/time of the hypnogram (exclusive: start of the epoch after the last one).

freq

The frequency resolution of the hypnogram.

hypno

The hypnogram values, stored in a pandas.Series.

labels

The allowed stage labels.

mapping

A dictionary with the mapping from string to integer values.

mapping_int

A dictionary with the mapping from integer to string values.

n_epochs

The number of epochs in the hypnogram.

n_stages

The number of allowed sleep stages in the hypnogram (2, 3, 4, or 5).

proba

If specified, a pandas.DataFrame with the probability of each sleep stage for each epoch in hypnogram.

sampling_frequency

The sampling frequency (Hz) of the hypnogram.

scorer

The scorer name.

start

The start date/time of the hypnogram.

timedelta

A pandas.TimedeltaIndex vector with the accumulated time difference of each epoch compared to the first epoch.