yasa.Hypnogram.find_periods#

Hypnogram.find_periods(threshold='5min', equal_length=False)[source]#

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

Parameters:
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 with one row per period and the following columns:

  • values (str): The stage label of the current period.

  • start (int): The index of the first epoch of the period in the hypnogram.

  • length (int): The duration of the period in number of epochs.

Examples

Let’s assume that we have a 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-stage 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.