Literature DB >> 34434837

'SleepCycles' package for R - A free software tool for the detection of sleep cycles from sleep staging.

Christine Blume1, Christian Cajochen2.   

Abstract

The detection of NREM-REM sleep cycles in human sleep data (i.e., polysomnographically assessed sleep stages) enables fine-grained analyses of ultradian variations in sleep microstructure (e.g., sleep spindles, and arousals), or other amplitude- and frequency-specific electroencephalographic features during sleep. While many laboratories have software that is used internally, reproducibility requires the availability of open-source software. Therefore, we here introduce the 'SleepCycles' package for R, an open-source software package that identifies sleep cycles and their respective (non-) rapid eye movement ([N]REM) periods from sleep staging data. Additionally, each (N)REM period is subdivided into parts of equal duration (percentiles), which may be useful for further fine-grained analyses. The detection criteria used in the package are, with some adaptations, largely based on criteria originally proposed by Feinberg and Floyd (1979). The latest version of the package can be downloaded from the Comprehensive R Archives Network (CRAN).•The package 'SleepCycles' for R allows to identify sleep cycles and their respective NREM and REM periods from sleep staging results.•Besides the cycle detection, NREM and REM periods are also split into parts of equal duration (percentiles) thereby allowing for a better temporal resolution across the night and comparisons of sleep cycles with different durations amongst different night recordings.
© 2021 The Authors.

Entities:  

Keywords:  Circadian rhythm; R; Sleep; Sleep cycles; Sleep staging

Year:  2021        PMID: 34434837      PMCID: PMC8374325          DOI: 10.1016/j.mex.2021.101318

Source DB:  PubMed          Journal:  MethodsX        ISSN: 2215-0161


American Association of Sleep Medicine Comprehensive R Archives Network Electroencephalogram Electrooculogram Electromyogram Non-rapid eye movement Non-rapid eye movement (sleep) period Polysomnography Name of the software in which the package was written Rapid eye movement Rapid eye movement (sleep) period Rechtschaffen & Kales Specifications Table

Method details

Introduction

In human sleep research, sleep medicine, and chronobiology, the ‘gold standard’ of sleep assessment is the so-called polysomnography (PSG). This method needs to include measurements of brain activity (electroencephalogram; EEG), muscle tone (electromyogram; EMG), and eye movements (electrooculogram; EOG) to allow for subsequent sleep staging, i.e. the assignment of sleep stages to 30 second epochs of signal (cf. [1]). The first formal approach to categorising different sleep stages in human adults based on the signal patterns in the PSG traces back to A. Rechtschaffen and A. Kales (R&K criteria) [21]. According to these criteria, six different sleep stages are distinguished: wake, non-rapid eye movement (NREM) sleep stages S1-S4 (representing a continuum of increasing sleep depth), and rapid eye movement (REM) sleep (cf. Table 1). Since 2007, the R&K criteria have largely been replaced by the rules of the American Academy of Sleep Medicine (AASM; [1]). Besides smaller changes in terminology, that is, NREM sleep stages are denoted by a capital ‘N’ rather than ‘S’, the major difference that is relevant in the context of the software package described here is that deep sleep stages S3 and S4, which differ in the proportion of slow waves, were combined into stage N3. Thus, according to the AASM criteria, there are only five sleep stages (cf. Table 1; note that the ‘SleepCycles’ package can still handle results from sleep staging according to R&K criteria, see below).
Table 1

Sleep stages in humans according to Rechtschaffen and Kales (R&K) criteria and the criteria of the American Association of Sleep Medicine (AASM).

Rechtschaffen and Kales [21]AmericanAcademy of Sleep Medicine [1]
WakeW (0)W (0)
Non-rapid eye movement (NREM) sleep stagesS1 (1)N1 (1)
S2 (2)N2 (2)
S3 (3)N3 (3)
S4 (4)
Rapid-eye movement (REM) sleepREM (5)REM (5)

The numbers in brackets denote the numeric value that sleep stages are commonly assigned and which the ‘SleepCycles’ package requires as an input (for details see below).

Sleep stages in humans according to Rechtschaffen and Kales (R&K) criteria and the criteria of the American Association of Sleep Medicine (AASM). The numbers in brackets denote the numeric value that sleep stages are commonly assigned and which the ‘SleepCycles’ package requires as an input (for details see below). Over the course of a sleep episode, NREM and REM sleep periods alternate in a cyclic fashion (cf. Fig. 1), a pattern that has first been described as early as in the 1950s [2,3,9]. Somewhat later, Feinberg and Floyd [12] were the first to propose formal criteria to describe these NREM-REM cycles and their criteria have since been adopted and applied by many researchers. In healthy individuals, a sleep episode begins with N1 sleep, which is followed by N2 and N3 sleep, and finally REM. Following REM, the next sequence of N1, N2, N3, and REM sleep, that is, the next cycle, begins. Deviations from this cyclic pattern can have diagnostic relevance for certain sleep disorders such as narcolepsy, which is characterised by a tendency to start sleep with a REM episode [15].
Fig. 1

Examples of sleep cycles detected with the ‘SleepCycles’ package. Above the hypnogram, i.e. the succession of sleep stages, the NREM and REM periods of each cycle have been marked. Each NREM cycle usually comprises first a NREM (darker colours) and then a REM (yellow) period. (A) Regular night with NREM onset, no NREM period exceeds 120 min in duration. (B) The first detected sleep cycle comprised more than 240 epochs (i.e., 120 min) excluding wakefulness. Thus, the NREM period was split into two, where the first N3 epoch following a lightening of sleep (i.e., at least 12 min of any other stage than N3) marks the onset of the second period.

Examples of sleep cycles detected with the ‘SleepCycles’ package. Above the hypnogram, i.e. the succession of sleep stages, the NREM and REM periods of each cycle have been marked. Each NREM cycle usually comprises first a NREM (darker colours) and then a REM (yellow) period. (A) Regular night with NREM onset, no NREM period exceeds 120 min in duration. (B) The first detected sleep cycle comprised more than 240 epochs (i.e., 120 min) excluding wakefulness. Thus, the NREM period was split into two, where the first N3 epoch following a lightening of sleep (i.e., at least 12 min of any other stage than N3) marks the onset of the second period. Usually, during an 8-hour sleep period, we experience four to five such NREM-REM sleep cycles each lasting about 90–120 min [6,18]. Especially in adolescents and young adults, the first REM period is however sometimes skipped (first described by [2,3]) and only a ‘lightening of sleep’, that is, a period of wake, N1 and/or N2, can be observed [13,17]. Importantly, throughout the night, the relative proportions of each sleep stage per cycle change. While healthy individuals have relatively large amounts of N3 sleep during the earlier sleep cycles, its proportion decreases or it disappears altogether as the night progresses (cf. Fig. 1). This decrease in the amount of deep N3 sleep is paralleled by an increase in the amount of REM sleep with most REM sleep occurring in the final third of the night (cf. Fig. 1). The variations also reflect changes in homoeostatic sleep drive and the circadian drive for wakefulness [5,10,11]. For many sleep studies it is of interest to take sleep cycles into account as this allows to investigate the effects of certain interventions across physiologically and phenomenologically meaningful ‘chunks’ (e.g., effects of pre-sleep artificial light exposure on delta power in NREM periods across the night: [7]) or ultradian variations in sleep microstructure (e.g., sleep spindles: [8]; or arousals: [22]). However, the detection of sleep cycles is not trivial, partly because criteria such as those originally proposed by Feinberg and Floyd [12], which the ‘SleepCycles’ package is largely based on, were initially not developed for a translation into code and are therefore sometimes underspecified. Moreover, the non-availability of (open source) software suggests that most solutions presumably stay inside laboratories, which hinders reproducibility. The ‘SleepCycles’ package for R provides a solution, which is easy to apply to any sleep staging results even for users, who are only little familiar with coding in R. The most recent version of the package can always be downloaded from the Comprehensive R Archives Network (CRAN) and is, just as R itself, open source. As the package will be updated from time to time, e.g. to ensure compatibility with other packages, we do not provide a zip file of the package along with this publication. Users are advised to regularly check CRAN for package updates.

Method description

Rules for detection

The ‘SleepCycles’ detection algorithm is largely based on the criteria originally proposed by Feinberg and Floyd [12] with some adaptations. Table 2 provides an overview of the differences between the original criteria and the ones implemented in the package. More precisely, NREM periods (NREMPs) are defined as periods that start with N1 (default option) or N2 at the beginning of the night. Following a REM period (REMP), wakefulness can also mark the beginning of a new NREMP. At this point, the settings represent an adaptation of the original criteria, where S2 instead of N1 marked the beginning of any NREMP. Regarding the first NREMP, we felt that starting with N1 better corresponds to the AASM criteria, which define sleep onset as any other sleep stage than wake [1]. Moreover, we feel that the first NREMP starting with N1 rather than N2 could increase the comparability of NREMPs across the night, but this choice is up to the user. Last, during the night, the adapted criteria are associated with a smoothing, which previously was presumably done manually to prevent wake and N1/S1 from being added to a preceding REMP and/or breaks between consecutive (N)REMPs. NREMPs have a minimal duration of 15 min, which can include wakefulness and up to <5 min of REM sleep (except for the first REMP where no minimum duration criterion is applied). Thus, any REM sleep following the first NREMP automatically marks the beginning of the first REMP.
Table 2

Criteria for the detection of sleep cycles and differences between criteria originally proposed by [12] and criteria used in the ‘SleepCycles’ package.

CriterionFeinberg and Floyd [12]‘SleepCycles’ package
Start of NREMPsS2First sleep episode starts with N1 (default) or N2; following a REM period, it can also start with wake
Minimum duration of NREMPs15 min (including wake before final awakening)
Maximum duration of NREMPs120 min (excluding wake)
Splitting of NREMPs if duration exceeds 120 min (excl. wake)Split at first N3 epoch following a period of 12 min with any other sleep stage than N31
Duration of REMPsFirst REMP: no minimum duration; subsequent REMPs: minimum 5 minutes2
Completeness of a (N)REMP(N)REMP is followed by at least 5 min of (N)REM3

(N)REMP = (non-)rapid eye movement period; S1 = stage 1 sleep according to R&K [21] criteria; N1/N3 = NREM sleep stage 1/3 according to the criteria of the American Association of Sleep Medicine (AASM, 2007). 1Note that the code suggests potential splitting points that fulfil this criterion and in case there are several, users are asked to select one, provide a different point, or indicate that they do not want to split the NREMP (see below and Fig. 2). 2Note that, if there is an ‘obvious’ REMP, e.g. a sequence of REM epochs with a duration of for instance 4 or 4.5 min separating two longer periods without REM, that is NREMPs, which therefore does not meet the duration criterion, the minimum duration can be decreased using the ‘REMP_length’ criterion following careful consideration. 3By default, incomplete (N)REMPs at the end of the night are not removed, can be changes in the ‘rm_incomplete_periods’ argument.

Criteria for the detection of sleep cycles and differences between criteria originally proposed by [12] and criteria used in the ‘SleepCycles’ package. (N)REMP = (non-)rapid eye movement period; S1 = stage 1 sleep according to R&K [21] criteria; N1/N3 = NREM sleep stage 1/3 according to the criteria of the American Association of Sleep Medicine (AASM, 2007). 1Note that the code suggests potential splitting points that fulfil this criterion and in case there are several, users are asked to select one, provide a different point, or indicate that they do not want to split the NREMP (see below and Fig. 2). 2Note that, if there is an ‘obvious’ REMP, e.g. a sequence of REM epochs with a duration of for instance 4 or 4.5 min separating two longer periods without REM, that is NREMPs, which therefore does not meet the duration criterion, the minimum duration can be decreased using the ‘REMP_length’ criterion following careful consideration. 3By default, incomplete (N)REMPs at the end of the night are not removed, can be changes in the ‘rm_incomplete_periods’ argument.
Fig. 2

Interactive splitting dialogue in case of a NREMP exceeding 120 min. The code suggests potential splitting points, which in this case is epoch 152. Specifically, epoch 152 is the first N3 epoch following a lightening of sleep, i.e. a period of any stage other than N3 for a minimum of 12 min. The dialogue in R's console additionally informs the user about how long the resulting NREMPs would be.

While there is no minimum duration criterion for the first REMP, any other REMP must be at least 5 min long. It can include wake or, theoretically, also short segments of NREM sleep and only ends when the criteria for a next NREMP are met. Especially in younger people or after benzodiazepine intake, the first NREMP can sometimes exceed 120 min in duration (excl. wake). This is because the first REM is skipped, and only a ‘lightening of sleep’ without the presence of REM sleep is observed [4,13,17]. In this case, the ‘SleepCycle’ algorithm suggests splitting this NREMP into two parts. Specifically, the new cycle should then start with the first N3 epoch following an episode(>12 min; [13,16,17,22]) with any other stage than N3, i.e. a lightening of sleep [13,17]. The code generates suggestions where splitting could take place according to these criteria and informs the user about the duration of the two NREMPs that would result from the splitting (cf. Fig. 2). Additionally, the potential splitting points are visualised on top of a hypnogram to allow for a better-informed decision. The user can then interactively choose where to split the NREMP. However, the code also offers the possibility to provide a numeric value for an epoch at which to split or users can decide to not split at all. In case the splitting criterion is not fulfilled despite a NREMP exceeding 120 min, users are notified that the NREMP cannot be split. Interactive splitting dialogue in case of a NREMP exceeding 120 min. The code suggests potential splitting points, which in this case is epoch 152. Specifically, epoch 152 is the first N3 epoch following a lightening of sleep, i.e. a period of any stage other than N3 for a minimum of 12 min. The dialogue in R's console additionally informs the user about how long the resulting NREMPs would be. Any combination of a NREMP and the following REMP represents one NREM cycle, except for the case when a NREMP is split. In this case, the first of the two resulting NREMPs represents a sleep cycle (without REM). In laboratory situations, participants are often woken up in the mornings, which may result in ‘incomplete’ sleep periods. In line with [12], a REM or NREM sleep period at the end of the night is only considered complete if it is followed by at least five minutes of NREM or REM sleep before awakening, respectively. By default, the code does not remove incomplete sleep periods at the end, but the rm_incomplete_period argument can be used to do so.

Package functions

The main function is the ‘SleepCycles’ function, which loops through all files in the directory p. It accepts the arguments listed in Table 3. The other functions that come with the package are auxiliary functions and should not be changed, wherefore they are not readily visible to the users.
Table 3

Arguments for the ‘SleepCycles’ function.

ArgumentDefault valueInput
pCharacter string specifying the directory with the staging result files
sleepstart“N1”Character string specifying which sleep stage to start the first NREMP with. Can be “N1” (default) or “N2”
filesNANumeric vector indicating the files to process, e.g., c(2:5)
filetype“txt”“txt” or “vmrk”
treat_as_WNAAny numeric value to be treated as stage ‘Wake’
treat_as_N3NAAny numeric value to be treated as stage ‘N3’
rm_incomplete_periodFALSELogical value; specifies whether an incomplete period at the end should be removed. Default: FALSE.
plotTRUELogical value; specifies whether the results of the analysis should be plotted and the plot saved at the end. Default: TRUE.
REMP_length10Numeric value specifying the minimum length of any REM period following the first. Default: 10. Should only be changed after careful consideration.

W = wake; REMP = REM period, NA = not available.

Arguments for the ‘SleepCycles’ function. W = wake; REMP = REM period, NA = not available.

Data requirements

The only requirement is that the input file(s) contain a numeric vector representing the sleep stages (i.e., 0, 1, 2, 3, and 5 according to AASM rules) that have been assigned to each 30 second epoch of a night. Multiple nights of the same or several individuals must be stored in different files and the function will loop through these. The package can also handle staging according to R&K criteria; however, users will then have to specify that the numeric value ‘4′ should be treated as N3 in the treat_as_N3 argument. Please note that at the time of writing this manuscript, the package cannot sleep staging data based on 20 second epochs. The package can also treat one other numeric value as ‘Wake’ using the treat_as_W argument, for instance sometimes epochs during which participants move are assigned a different numeric value. In case not all values present in the staging data have been specified, users will receive the error message ‘Please check your file. The vector with the staging seems to contain other numbers than the sleep stages or the numbers you want to treat as a sleep stage’. The code can handle text files (ending ‘.txt’) or BrainVision analyzer 2 marker files (ending ‘.vmrk’). The file type can be specified in the filetype argument (“txt” or “vmrk”, default is “txt”). Any further data columns besides the one containing the sleep staging, e.g. sampling points, will simply be copied to the output file and otherwise be ignored by the code. When reading in text files, users will be prompted to specify whether their data contains column names in the first row, i.e. a header, as well as the column separator (can be comma, semicolon, or tabulator). Please note that staging criteria have originally been developed for adult PSG recordings, although there is a paediatric extension for AASM criteria [20]. Regarding sleep cycles, previous research by [17] suggested that from 2 years of age onwards, the average sleep cycle length remains stable until the age of 19. From this perspective, it seems plausible that the package can also be applied to data from children, although perhaps with some caution. Likewise, while the code should theoretically be able to handle changes in sleep across the lifespan such as decreased amounts of N3 and REM sleep, increased amounts of N1 and N2, and increased sleep fragmentation [19], the performance of the detection may change. The same holds true for patients suffering from sleep fragmentation due to for example sleep-disordered breathing [14]. We therefore recommend to always review the detection results using the hypnograms with the detection results plotted on top (cf. Fig. 1).

Output

The detection algorithm compiles and saves a separate text (cf. Fig. 3) file for each input file. It contains a ‘SleepStages’ column with the staging data the detection is based on, a ‘SleepCycle’ column with a numeric value specifying the NREM cycle (i.e., NREM and REM period), a ‘N_REM’ column, where ‘0′ denotes a NREM period and ‘1′ denotes REM period, as well as a column named ‘percentile’.
Fig. 3

Output file. The resulting text file contains the sleep staging data and gives the sleep cycle an epoch belongs to. Further, it contains information about whether an epoch belongs to a REM or NREM period (cf. ‘N_REM’ column) and which percentile of a (N)REMP it pertains to.

Output file. The resulting text file contains the sleep staging data and gives the sleep cycle an epoch belongs to. Further, it contains information about whether an epoch belongs to a REM or NREM period (cf. ‘N_REM’ column) and which percentile of a (N)REMP it pertains to. This latter column contains information about the percentile of a NREMP or REMP each epoch belongs to. If a (N)REMP comprises less than 10 epochs, they are all assigned the number ‘1′. In case the length of a period is not divisible by 10 (e.g., 203 epochs), one epoch is added to percentiles in a randomised fashion to reach the correct length of a period (here: 7 percentiles of 20 epochs, 3 of 21 epochs). All data available in the input file are also included in the output file for text files. For ‘vmrk’ files, the original ‘description’ column is renamed to ‘SleepStages’ and the ‘Channel’ and ‘Length’ columns are omitted as well as the first line, which includes information on the sampling rate.

Examples

For examples, please see the package vignette.

Funding

CB is supported by an FWF-funded Erwin-Schroedinger Fellowship (J-4243), a grant from the Freiwillige Akademische Gesellschaft Basel, a grant from the Psychiatric Hospital of the University of Basel, and a grant from the Novartis Foundation for Biological-Medical Research.

Declaration of Competing Interest

The authors declare that they have no known competing financial interests or personal relationships that could have appeared to influence the work reported in this paper.

Specifications Table

Subject AreaNeuroscience
More specific subject areaChronobiology; sleep research
Method nameDetection of sleep cycles
Name and reference of original methodFeinberg, I., & Floyd, T. (1979). Systematic trends across the night in human sleep cycles. Psychophysiology, 16(3), 283–291
Resource availabilityhttps://github.com/ChristineBlume/SleepCycleshttps://cran.r-project.org/web/packages/SleepCycles/index.html
  18 in total

1.  Topographical distribution of spindles: variations between and within nrem sleep cycles.

Authors:  L De Gennaro; M Ferrara; M Bertini
Journal:  Sleep Res Online       Date:  2000

2.  Two types of ocular motility occurring in sleep.

Authors:  E ASERINSKY; N KLEITMAN
Journal:  J Appl Physiol       Date:  1955-07       Impact factor: 3.531

3.  Systematic trends across the night in human sleep cycles.

Authors:  I Feinberg; T C Floyd
Journal:  Psychophysiology       Date:  1979-05       Impact factor: 4.016

4.  Ultradian dynamics of sleep after a single dose of benzodiazepine hypnotics.

Authors:  A A Borbély; P Achermann
Journal:  Eur J Pharmacol       Date:  1991-03-19       Impact factor: 4.432

5.  The two-process model of sleep regulation: a reappraisal.

Authors:  Alexander A Borbély; Serge Daan; Anna Wirz-Justice; Tom Deboer
Journal:  J Sleep Res       Date:  2016-01-14       Impact factor: 3.981

6.  Electroencephalogram power density and slow wave sleep as a function of prior waking and circadian phase.

Authors:  D J Dijk; D P Brunner; D G Beersma; A A Borbély
Journal:  Sleep       Date:  1990-10       Impact factor: 5.849

7.  Characteristics of sleep slow waves in children and adolescents.

Authors:  Salomé Kurth; Oskar G Jenni; Brady A Riedner; Giulio Tononi; Mary A Carskadon; Reto Huber
Journal:  Sleep       Date:  2010-04       Impact factor: 5.849

8.  Persistence of the circadian rhythm of REM sleep: a variety of experimental manipulations of the sleep-wake cycle.

Authors:  S Endo; T Kobayashi; T Yamamoto; H Fukuda; M Sasaki; T Ohta
Journal:  Sleep       Date:  1981-09       Impact factor: 5.849

9.  Acute exposure to evening blue-enriched light impacts on human sleep.

Authors:  Sarah L Chellappa; Roland Steiner; Peter Oelhafen; Dieter Lang; Thomas Götz; Julia Krebs; Christian Cajochen
Journal:  J Sleep Res       Date:  2013-03-20       Impact factor: 3.981

10.  Ultradian modulation of cortical arousals during sleep: effects of age and exposure to nighttime transportation noise.

Authors:  Franziska Rudzik; Laurie Thiesse; Reto Pieren; Harris Héritier; Ikenna C Eze; Maria Foraster; Danielle Vienneau; Mark Brink; Jean Marc Wunderli; Nicole Probst-Hensch; Martin Röösli; Stephany Fulda; Christian Cajochen
Journal:  Sleep       Date:  2020-07-13       Impact factor: 5.849

View more

北京卡尤迪生物科技股份有限公司 © 2022-2023.