yasa.Hypnogram

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

Experimental class for manipulating hypnogram in YASA (dev).

Starting with v0.7, YASA will take a more object-oriented approach to hypnograms. That is, hypnograms are now stored as a class (aka object), which comes with its own attributes and functions. Furthermore, YASA does not allow integer values to define the stages anymore. Instead, users must pass an array of strings with the actual stage names (e.g. [“WAKE”, “WAKE”, “N1”, …, “REM”, “REM”]).

New in version 0.7.0.

Parameters
valuesarray_like

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

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

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

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

  • 5-stages (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 to full spelling and uppercase (e.g. “w” -> “WAKE”).

n_stagesint

Whether values comes from a 2, 3, 4 or 5-stages hypnogram. Default is 5 stages, 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 at https://pandas.pydata.org/docs/user_guide/timeseries.html#timeseries-offset-aliases

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

startstr or datetime

An optional string indicating the starting datetime of the hypnogram (e.g. “2022-12-15 22:30:00”). If start is specified and valid, the index of the hypnogram will be a pandas.DatetimeIndex. Otherwise it will be a pandas.RangeIndex, indicating the epoch number.

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”.

Examples

Create a 2-stages hypnogram

>>> 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 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.

We can access the actual values, which are stored as a pandas.Series, with:

>>> 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, object): ['WAKE', 'SLEEP', 'ART', 'UNS']
>>> # Number of epochs in the hypnogram
>>> hyp.n_epochs
12
>>> # Total duration of the hypnogram, in minutes (12 epochs * 30 seconds = 6 minutes)
>>> hyp.duration
6.0
>>> # Default mapping from strings to integers. Can be changed with `hyp.mapping = {}`
>>> hyp.mapping
{'WAKE': 0, 'SLEEP': 1, 'ART': -1, 'UNS': -2}
>>> # Get the hypnogram Series integer values
>>> hyp.as_int()
Epoch
0     0
1     0
2     0
3     1
4     1
5     1
6     1
7     1
8     0
9     1
10    1
11    1
Name: Stage, dtype: int16
>>> # Calculate the summary sleep statistics
>>> hyp.sleep_statistics()
{'TIB': 6.0,
 'SPT': 4.5,
 'WASO': 0.5,
 'TST': 4.0,
 'SE': 66.6667,
 'SME': 88.8889,
 'SFI': 7.5,
 'SOL': 1.5,
 'SOL_5min': nan,
 'WAKE': 2.0}
>>> # Get the state-transition matrix
>>> counts, probs = hyp.transition_matrix()
>>> counts
To Stage    WAKE  SLEEP
From Stage
WAKE           2      2
SLEEP          1      6

All these methods and properties are also valid with a 5-stages hypnogram. In the example below, we use the yasa.simulate_hypnogram() to generate a plausible 5-stages hypnogram with a 30-seconds resolution. A random seed is specified to ensure that we get reproducible results. Lastly, we set an actual start time to the hypnogram. As a result, the index of the resulting hypnogram is a pandas.DatetimeIndex.

>>> from yasa import simulate_hypnogram
>>> hyp = simulate_hypnogram(
...     tib=500, n_stages=5, start="2022-12-15 22:30:00", scorer="S1", seed=42)
>>> hyp
<Hypnogram | 1000 epochs x 30s (500.00 minutes), 5 stages, scored by S1>
 - 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
Time
2022-12-15 22:30:00    WAKE
2022-12-15 22:30:30    WAKE
2022-12-15 22:31:00    WAKE
2022-12-15 22:31:30    WAKE
2022-12-15 22:32:00    WAKE
                    ...
2022-12-16 06:47:30      N2
2022-12-16 06:48:00      N2
2022-12-16 06:48:30      N2
2022-12-16 06:49:00      N2
2022-12-16 06:49:30      N2
Freq: 30S, Name: S1, Length: 1000, dtype: category
Categories (7, object): ['WAKE', 'N1', 'N2', 'N3', 'REM', 'ART', 'UNS']

The summary sleep statistics will include more items with a 5-stages hypnogram than a 2-stages hypnogram, i.e. the amount and percentage of each sleep stage, the REM latency, etc.

>>> hyp.sleep_statistics()
{'TIB': 500.0,
 'SPT': 497.5,
 'WASO': 79.5,
 'TST': 418.0,
 'SE': 83.6,
 'SME': 84.0201,
 'SFI': 0.7177,
 'SOL': 2.5,
 'SOL_5min': 2.5,
 'Lat_REM': 67.0,
 'WAKE': 82.0,
 'N1': 69.0,
 'N2': 247.0,
 'N3': 64.5,
 'REM': 37.5,
 '%N1': 16.5072,
 '%N2': 59.0909,
 '%N3': 15.4306,
 '%REM': 8.9713}
__init__(values, n_stages=5, *, freq='30s', start=None, scorer=None)[source]

Methods

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

as_annotations()

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.

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.

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 an hypnogram.

transition_matrix()

Create a state-transition matrix from an hypnogram.

upsample(new_freq, **kwargs)

Upsample hypnogram to a higher frequency.

upsample_to_data(data[, sf, verbose])

Upsample an 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.

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 stages in the 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.

as_annotations()[source]

Return a pandas DataFrame summarizing epoch-level information.

Column order and names are compliant with BIDS events files and MNE events/annotations dataframes.

Returns
annotationspandas.DataFrame

A dataframe containing epoch onset, duration, stage, etc.

Examples

>>> from yasa import Hypnogram
>>> hyp = Hypnogram(["W", "W", "LIGHT", "LIGHT", "DEEP", "REM", "WAKE"], n_stages=4)
>>> hyp.as_annotations()
       onset  duration  value description
epoch
0        0.0      30.0      0        WAKE
1       30.0      30.0      0        WAKE
2       60.0      30.0      2       LIGHT
3       90.0      30.0      2       LIGHT
4      120.0      30.0      3        DEEP
5      150.0      30.0      4         REM
6      180.0      30.0      0        WAKE
as_int()[source]

Return hypnogram values as integers.

The default mapping from string to integer is:

  • 2 stages: {“WAKE”: 0, “SLEEP”: 1, “ART”: -1, “UNS”: -2}

  • 3 stages: {“WAKE”: 0, “NREM”: 2, “REM”: 4, “ART”: -1, “UNS”: -2}

  • 4 stages: {“WAKE”: 0, “LIGHT”: 2, “DEEP”: 3, “REM”: 4, “ART”: -1, “UNS”: -2}

  • 5 stages: {“WAKE”: 0, “N1”: 1, “N2”: 2, “N3”: 3, “REM”: 4, “ART”: -1, “UNS”: -2}

Users can define a custom mapping:

>>> hyp.mapping = {"WAKE": 0, "NREM": 1, "REM": 2}

Examples

Convert a 2-stages hypnogram to a pandas.Series of integers

>>> from yasa import Hypnogram
>>> hyp = Hypnogram(["W", "W", "S", "S", "W", "S"], n_stages=2)
>>> hyp.as_int()
Epoch
0    0
1    0
2    1
3    1
4    0
5    1
Name: Stage, dtype: int16

Same with a 4-stages hypnogram

>>> from yasa import Hypnogram
>>> hyp = Hypnogram(["W", "W", "LIGHT", "LIGHT", "DEEP", "REM", "WAKE"], n_stages=4)
>>> hyp.as_int()
Epoch
0    0
1    0
2    2
3    2
4    3
5    4
6    0
Name: Stage, dtype: int16
consolidate_stages(new_n_stages)[source]

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

For example, a standard 5-stage hypnogram (W, N1, N2, N3, REM) could be consolidated to a hypnogram more common with actigraphy (e.g. 2-stages: [Wake, Sleep] or 4-stages: [W, Light, Deep, REM]).

Parameters
selfyasa.Hypnogram

Hypnogram, assumed to be already cropped to time in bed (TIB, also referred to as Total Recording Time, i.e. “lights out” to “lights on”).

new_n_stagesint

Desired number of sleep stages. Must be lower than the current number of stages.

  • 5 stages - Wake, N1, N2, N3, REM

  • 4 stages - Wake, Light, Deep, REM

  • 3 stages - Wake, NREM, REM

  • 2 stages - Wake, Sleep

Note

Unscored and Artefact are always allowed.

Returns
hypyasa.Hypnogram

The consolidated Hypnogram object. This function returns a copy, i.e. the original hypnogram is not modified in place.

Examples

>>> from yasa import Hypnogram
>>> hyp = Hypnogram(["W", "W", "N1", "N2", "N2", "N2", "N2", "W"], n_stages=5)
>>> hyp_2s = hyp.consolidate_stages(2)
>>> print(hyp_2s)
Epoch
0     WAKE
1     WAKE
2    SLEEP
3    SLEEP
4    SLEEP
5    SLEEP
6    SLEEP
7     WAKE
Name: Stage, dtype: category
Categories (4, object): ['WAKE', 'SLEEP', 'ART', 'UNS']
copy()[source]

Return a new copy of the current Hypnogram.

evaluate(obs_hyp)[source]

Evaluate agreement between two hypnograms of the same sleep session.

For example, the reference hypnogram (i.e., self) might be a manually-scored hypnogram and the reference hypnogram (i.e., ref_hyp) might be a hypnogram from actigraphy, a wearable device, or an automated scorer (e.g., yasa.SleepStaging.predict()).

Parameters
selfyasa.Hypnogram

Reference or ground-truth hypnogram.

obs_hypyasa.Hypnogram

The observed or to-be-evaluated hypnogram.

Returns
ebeyasa.EpochByEpochAgreement

See EpochByEpochAgreement documentation for more detail.

Examples

>>> from yasa import simulate_hypnogram
>>> hyp_a = simulate_hypnogram(tib=90, scorer="AASM", seed=8)
>>> hyp_b = hyp_a.simulate_similar(scorer="YASA", seed=9)
>>> ebe = hyp_a.evaluate(hyp_b)
>>> ebe.get_agreement().round(3)
accuracy        0.550
balanced_acc    0.355
kappa           0.227
mcc             0.231
precision       0.515
recall          0.550
fbeta           0.524
Name: agreement, dtype: float64
find_periods(threshold='5min', equal_length=False)[source]

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

Parameters
selfyasa.Hypnogram

Hypnogram, assumed to be already cropped to time in bed (TIB, also referred to as Total Recording Time, i.e. “lights out” to “lights on”).

thresholdstr

This function will only keep periods that exceed a certain duration (default ‘5min’), e.g. ‘5min’, ‘15min’, ’30sec’, ‘1hour’. To disable thresholding, use ‘0sec’.

equal_lengthbool

If True, the periods will all have the exact duration defined in threshold. That is, periods that are longer than the duration threshold will be divided into sub-periods of exactly the length of threshold.

Returns
periodspandas.DataFrame

Output dataframe

  • values : The value in hypno of the current period

  • start : The index of the start of the period in hypno

  • length : The duration of the period, in number of epochs

Examples

Let’s assume that we have an hypnogram where sleep = 1 and wake = 0, with one value per minute.

>>> from yasa import Hypnogram
>>> val = 11 * ["W"] + 3 * ["S"] + 2 * ["W"] + 9 * ["S"] + ["W", "W"]
>>> hyp = Hypnogram(val, n_stages=2, freq="1min")
>>> hyp.find_periods(threshold="0min")
  values  start  length
0   WAKE      0      11
1  SLEEP     11       3
2   WAKE     14       2
3  SLEEP     16       9
4   WAKE     25       2

This gives us the start and duration of each sequence of consecutive values in the hypnogram. For example, the first row tells us that there is a sequence of 11 consecutive WAKE starting at the first index of hypno.

Now, we may want to keep only periods that are longer than a specific threshold, for example 5 minutes:

>>> hyp.find_periods(threshold="5min")
  values  start  length
0   WAKE      0      11
1  SLEEP     16       9

Only the two sequences that are longer than 5 minutes (11 minutes and 9 minutes respectively) are kept. Feel free to play around with different values of threshold!

This function is not limited to binary arrays, e.g. a 5-stages hypnogram at 30-sec resolution:

>>> from yasa import simulate_hypnogram
>>> hyp = simulate_hypnogram(tib=30, seed=42)
>>> hyp.find_periods(threshold="2min")
  values  start  length
0   WAKE      0       5
1     N1      5       6
2     N2     11      49

Lastly, using equal_length=True will further divide the periods into segments of the same duration, i.e. the duration defined in threshold:

>>> hyp.find_periods(threshold="5min", equal_length=True)
  values  start  length
0     N2     11      10
1     N2     21      10
2     N2     31      10
3     N2     41      10

Here, the 24.5 minutes of consecutive N2 sleep (= 49 epochs) are divided into 4 periods of exactly 5 minute each. The remaining 4.5 minutes at the end of the hypnogram are removed because it is less than 5 minutes. In other words, the remainder of the division of a given segment by the desired duration is discarded.

plot_hypnogram(**kwargs)[source]

Plot the hypnogram.

Parameters
**kwargsdict

Optional keyword arguments passed to yasa.plot_hypnogram().

Returns
axmatplotlib.axes.Axes

Matplotlib Axes

Examples

>>> from yasa import simulate_hypnogram
>>> ax = simulate_hypnogram(tib=480, seed=88).plot_hypnogram(highlight="REM")
../_images/yasa-Hypnogram-1.png
simulate_similar(**kwargs)[source]

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

Parameters
selfyasa.Hypnogram

Hypnogram, assumed to be already cropped to time in bed (TIB).

**kwargsdict

Optional keyword arguments passed to yasa.simulate_hypnogram().

Returns
hypyasa.Hypnogram

A simulated hypnogram.

Examples

>>> import pandas as pd
>>> from yasa import Hypnogram
>>> hyp = Hypnogram(
...     ["W", "S", "W"], n_stages=2, freq="2min", scorer="Human").upsample("30s")
>>> shyp = hyp.simulate_similar(scorer="Simulated", seed=6)
>>> df = pd.concat([hyp.hypno, shyp.hypno], axis=1)
>>> print(df)
       Human Simulated
Epoch
0       WAKE      WAKE
1       WAKE      WAKE
2       WAKE      WAKE
3       WAKE      WAKE
4      SLEEP     SLEEP
5      SLEEP     SLEEP
6      SLEEP     SLEEP
7      SLEEP     SLEEP
8       WAKE     SLEEP
9       WAKE     SLEEP
10      WAKE     SLEEP
11      WAKE      WAKE
sleep_statistics()[source]

Compute standard sleep statistics from an hypnogram.

This function supports a 2, 3, 4 or 5-stages hypnogram.

Parameters
selfyasa.Hypnogram

Hypnogram, assumed to be already cropped to time in bed (TIB, also referred to as Total Recording Time, i.e. “lights out” to “lights on”).

Returns
statsdict

Summary sleep statistics.

Notes

All values except SE, SME, SFI and the percentage of each stage are expressed in minutes. YASA follows the AASM guidelines to calculate these parameters:

  • Time in Bed (TIB): total duration of the hypnogram.

  • Sleep Period Time (SPT): duration from first to last period of sleep.

  • Wake After Sleep Onset (WASO): duration of wake periods within SPT.

  • Total Sleep Time (TST): total sleep duration in SPT.

  • Sleep Onset Latency (SOL): Latency to first epoch of any sleep.

  • SOL 5min: Latency to 5 minutes of persistent sleep (any stage).

  • REM latency: latency to first REM sleep.

  • Sleep Efficiency (SE): TST / TIB * 100 (%).

  • Sleep Maintenance Efficiency (SME): TST / SPT * 100 (%).

  • Sleep Fragmentation Index: number of transitions from sleep to wake / hours of TST

  • Sleep stages amount and proportion of TST

Warning

Artefact and Unscored epochs are excluded from the calculation of the total sleep time (TST). TST is calculated as the sum of all REM and NREM sleep in SPT.

Warning

The definition of REM latency in the AASM scoring manual differs from the REM latency reported here. The former uses the time from first epoch of sleep, while YASA uses the time from the beginning of the recording. The AASM definition of the REM latency can be found with SOL - Lat_REM.

References

  • Iber (2007). The AASM manual for the scoring of sleep and associated events: rules, terminology and technical specifications. American Academy of Sleep Medicine.

  • Silber et al. (2007). The visual scoring of sleep in adults. Journal of Clinical Sleep Medicine, 3(2), 121-131.

Examples

Sleep statistics for a 2-stage hypnogram with a resolution of 15-seconds

>>> from yasa import Hypnogram
>>> # Generate a fake hypnogram, where "S" = Sleep, "W" = Wake
>>> values = 10 * ["W"] + 40 * ["S"] + 5 * ["W"] + 40 * ["S"] + 9 * ["W"]
>>> hyp = Hypnogram(values, freq="15s", n_stages=2)
>>> hyp.sleep_statistics()
{'TIB': 26.0,
'SPT': 21.25,
'WASO': 1.25,
'TST': 20.0,
'SE': 76.9231,
'SME': 94.1176,
'SFI': 1.5,
'SOL': 2.5,
'SOL_5min': 2.5,
'WAKE': 6.0}

Sleep statistics for a 5-stages hypnogram

>>> from yasa import simulate_hypnogram
>>> # Generate a 8 hr (= 480 minutes) 5-stages hypnogram with a 30-seconds resolution
>>> hyp = simulate_hypnogram(tib=480, seed=42)
>>> hyp.sleep_statistics()
{'TIB': 480.0,
'SPT': 477.5,
'WASO': 79.5,
'TST': 398.0,
'SE': 82.9167,
'SME': 83.3508,
'SFI': 0.7538,
'SOL': 2.5,
'SOL_5min': 2.5,
'Lat_REM': 67.0,
'WAKE': 82.0,
'N1': 67.0,
'N2': 240.5,
'N3': 53.0,
'REM': 37.5,
'%N1': 16.8342,
'%N2': 60.4271,
'%N3': 13.3166,
'%REM': 9.4221}
transition_matrix()[source]

Create a state-transition matrix from an hypnogram.

Parameters
selfyasa.Hypnogram

Hypnogram, assumed to be already cropped to time in bed (TIB, also referred to as Total Recording Time, i.e. “lights out” to “lights on”). For best results, the hypnogram should not contain any artefact or unscored epochs.

Returns
countspandas.DataFrame

Counts transition matrix (number of transitions from stage A to stage B). The pre-transition states are the rows and the post-transition states are the columns.

probspandas.DataFrame

Conditional probability transition matrix, i.e. given that current state is A, what is the probability that the next state is B. probs is a right stochastic matrix, i.e. each row sums to 1.

Examples

>>> from yasa import Hypnogram, simulate_hypnogram
>>> # Generate a 8 hr (= 480 minutes) 5-stages hypnogram with a 30-seconds resolution
>>> hyp = simulate_hypnogram(tib=480, seed=42)
>>> counts, probs = hyp.transition_matrix()
>>> counts
To Stage    WAKE  N1   N2  N3  REM
From Stage
WAKE         153  11    0   0    0
N1             6  99   29   0    0
N2             3  16  447  10    5
N3             1   3    4  96    1
REM            0   5    1   0   69
>>> probs.round(3)
To Stage     WAKE     N1     N2     N3   REM
From Stage
WAKE        0.933  0.067  0.000  0.000  0.00
N1          0.045  0.739  0.216  0.000  0.00
N2          0.006  0.033  0.929  0.021  0.01
N3          0.010  0.029  0.038  0.914  0.01
REM         0.000  0.067  0.013  0.000  0.92
upsample(new_freq, **kwargs)[source]

Upsample hypnogram to a higher frequency.

Parameters
selfyasa.Hypnogram

Hypnogram, assumed to be already cropped to time in bed (TIB, also referred to as Total Recording Time, i.e. “lights out” to “lights on”). For best results, the hypnogram should not contain any artefact or unscored epochs.

new_freqstr

Frequency is defined with a pandas frequency string, e.g. “10s” or “1min”.

Returns
hypyasa.Hypnogram

The upsampled Hypnogram object. This function returns a copy, i.e. the original hypnogram is not modified in place.

Examples

Create a 30-sec hypnogram

>>> from yasa import Hypnogram
>>> hyp = Hypnogram(["W", "W", "S", "S", "W"], n_stages=2, start="2022-12-23 23:00")
>>> hyp.hypno
Time
2022-12-23 23:00:00     WAKE
2022-12-23 23:00:30     WAKE
2022-12-23 23:01:00    SLEEP
2022-12-23 23:01:30    SLEEP
2022-12-23 23:02:00     WAKE
Freq: 30S, Name: Stage, dtype: category
Categories (4, object): ['WAKE', 'SLEEP', 'ART', 'UNS']

Upsample to a 15-seconds resolution

>>> hyp_up = hyp.upsample("15s")
>>> hyp_up.hypno
Time
2022-12-23 23:00:00     WAKE
2022-12-23 23:00:15     WAKE
2022-12-23 23:00:30     WAKE
2022-12-23 23:00:45     WAKE
2022-12-23 23:01:00    SLEEP
2022-12-23 23:01:15    SLEEP
2022-12-23 23:01:30    SLEEP
2022-12-23 23:01:45    SLEEP
2022-12-23 23:02:00     WAKE
2022-12-23 23:02:15     WAKE
Freq: 15S, Name: Stage, dtype: category
Categories (4, object): ['WAKE', 'SLEEP', 'ART', 'UNS']
upsample_to_data(data, sf=None, verbose=True)[source]

Upsample an 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.

Parameters
selfyasa.Hypnogram

Hypnogram, assumed to be already cropped to time in bed (TIB, also referred to as Total Recording Time, i.e. “lights out” to “lights on”). For best results, the hypnogram should not contain any artefact or unscored epochs.

dataarray_like or mne.io.BaseRaw

1D or 2D EEG data. Can also be a mne.io.BaseRaw, in which case data and sf_data will be automatically extracted.

sf_datafloat

The sampling frequency of data, in Hz (e.g. 100 Hz, 256 Hz, …). Can be omitted if data is a mne.io.BaseRaw.

verbosebool or str

Verbose level. Default (False) will only print warning and error messages. The logging levels are ‘debug’, ‘info’, ‘warning’, ‘error’, and ‘critical’. For most users the choice is between ‘info’ (or verbose=True) and warning (verbose=False).

Returns
hypnoarray_like

The hypnogram values, upsampled to sf_data and cropped/padded to max(data.shape). For compatibility with most YASA functions, the returned hypnogram is an array with integer values, and not a yasa.Hypnogram object.

Warns
UserWarning

If the upsampled hypno is shorter / longer than max(data.shape) and therefore needs to be padded/cropped respectively. This output can be disabled by passing verbose='ERROR'.

property duration

Total duration of the hypnogram, expressed in minutes. AKA Time in Bed.

property freq

The frequency resolution of the hypnogram. Default is ’30s’

property hypno

The hypnogram values, stored in a pandas.Series. To reduce memory usage, the stages are stored as categories (pandas.Categorical). hypno inherits all the methods of a standard pandas.Series, e.g. .describe(), .unique(), .to_csv(), and more.

Note

print(Hypnogram) is a shortcut to print(Hypnogram.hypno).

property labels

The allowed stage labels.

property mapping

A dictionary with the mapping from string to integer values.

property mapping_int

A dictionary with the mapping from integer to string values.

property n_epochs

The number of epochs in the hypnogram.

property n_stages

The number of allowed stages in the hypnogram. This is not the number of unique stages in the current hypnogram. This does not include Artefact and Unscored which are always allowed.

property sampling_frequency

The sampling frequency (Hz) of the hypnogram.

property scorer

The scorer name.

property start

The start date/time of the hypnogram. Default is None.

property timedelta

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