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
Hypnogramis a sequence of sleep stage labels sampled at a fixed epoch duration (default 30 seconds). Three assumptions underpin every method in the class:Uniform epoch duration. Every epoch has the same length, set once via
freq. Variable-length epochs are not supported.Contiguous recording. Epochs are assumed to be consecutive with no temporal gaps.
Closed stage vocabulary. Valid stage labels are fixed by
n_stagesat 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 ofn_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
Hypnogramfrom a legacy integer array, usefrom_integers.To save a
Hypnogramto disk and reload it with all metadata intact, useto_jsonandfrom_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
Return hypnogram values as a
Seriesof integers.Return a BIDS-compatible events
DataFrame(onset, duration, stage).Return a boolean array marking epochs that match one or more stage labels.
Serialize the hypnogram and all metadata to a dictionary or JSON file.
Slice the hypnogram by epoch index or absolute timestamp.
Extend the hypnogram before and/or after with a chosen fill stage.
Resample the hypnogram to a finer epoch resolution.
Merge stages to a coarser hypnogram (e.g. 5-stage to 2-stage).
Align and upsample the hypnogram to match an EEG recording sample-by-sample.
Compute standard AASM sleep statistics (TIB, TST, SE, WASO, stage durations, …).
Compute the stage-transition count matrix and probability matrix.
Detect consecutive runs of a single stage exceeding a minimum duration.
Compare two hypnograms epoch-by-epoch (kappa, F1, MCC, …).
Plot the hypnogram as a standard hypnogram figure.
Plot per-epoch stage probabilities as a stacked area chart (requires
proba).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
valuescomes 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.
freqwill be passed to thepandas.date_rangefunction to create the time index of the hypnogram.- startstr,
datetime.datetime, orpandas.Timestamp, optional Start datetime of the hypnogram (e.g.
"2022-12-15 22:30:00"). When provided, the hypnogram index becomes apandas.DatetimeIndex, otherwise it is apandas.RangeIndexof epoch numbers. Accepts timezone-naive strings / datetimes as well as tz-awaredatetimeorTimestampobjects.- tzstr or
datetime.timezone, optional Timezone of the hypnogram
starttime, e.g."Europe/Paris"or"America/New_York". Only used whenstartis timezone-naive. A full list of valid timezone strings is available viaimport 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”.- proba
pandas.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, ...])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
Hypnogramfrom a dictionary produced byto_dict.from_integers(values[, mapping, n_stages, ...])Create a
Hypnogramfrom an integer-encoded hypnogram array.from_json(fname)from_profusion(fname, *[, start, tz, scorer])Create a
Hypnogramfrom 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.
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.
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
Total duration of the hypnogram, expressed in minutes.
End date/time of the hypnogram (exclusive: start of the epoch after the last one).
The frequency resolution of the hypnogram.
The hypnogram values, stored in a
pandas.Series.The allowed stage labels.
A dictionary with the mapping from string to integer values.
A dictionary with the mapping from integer to string values.
The number of epochs in the hypnogram.
The number of allowed sleep stages in the hypnogram (2, 3, 4, or 5).
If specified, a
pandas.DataFramewith the probability of each sleep stage for each epoch in hypnogram.The sampling frequency (Hz) of the hypnogram.
The scorer name.
The start date/time of the hypnogram.
A
pandas.TimedeltaIndexvector with the accumulated time difference of each epoch compared to the first epoch.