yasa.sw_detect

yasa.sw_detect(data, sf=None, ch_names=None, hypno=None, include=2, 3, freq_sw=0.3, 1.5, dur_neg=0.3, 1.5, dur_pos=0.1, 1, amp_neg=40, 200, amp_pos=10, 150, amp_ptp=75, 350, coupling=False, coupling_params={'freq_sp': 12, 16, 'p': 0.05, 'time': 1}, remove_outliers=False, verbose=False)[source]

Slow-waves detection.

Parameters
dataarray_like

Single or multi-channel data. Unit must be uV and shape (n_samples) or (n_chan, n_samples). Can also be a mne.io.BaseRaw, in which case data, sf, and ch_names will be automatically extracted, and data will also be automatically converted from Volts (MNE) to micro-Volts (YASA).

sffloat

Sampling frequency of the data in Hz. Can be omitted if data is a mne.io.BaseRaw.

Tip

If the detection is taking too long, make sure to downsample your data to 100 Hz (or 128 Hz). For more details, please refer to mne.filter.resample().

ch_nameslist of str

Channel names. Can be omitted if data is a mne.io.BaseRaw.

hypnoarray_like

Sleep stage (hypnogram). If the hypnogram is loaded, the detection will only be applied to the value defined in include (default = N2 + N3 sleep).

The hypnogram must have the same number of samples as data. To upsample your hypnogram, please refer to yasa.hypno_upsample_to_data().

Note

The default hypnogram format in YASA is a 1D integer vector where:

  • -2 = Unscored

  • -1 = Artefact / Movement

  • 0 = Wake

  • 1 = N1 sleep

  • 2 = N2 sleep

  • 3 = N3 sleep

  • 4 = REM sleep

includetuple, list or int

Values in hypno that will be included in the mask. The default is (2, 3), meaning that the detection is applied on N2 and N3 sleep. This has no effect when hypno is None.

freq_swtuple or list

Slow wave frequency range. Default is 0.3 to 1.5 Hz. Please note that YASA uses a FIR filter (implemented in MNE) with a 0.2 Hz transition band, which means that the -6 dB points are located at 0.2 and 1.6 Hz.

dur_negtuple or list

The minimum and maximum duration of the negative deflection of the slow wave. Default is 0.3 to 1.5 second.

dur_postuple or list

The minimum and maximum duration of the positive deflection of the slow wave. Default is 0.1 to 1 second.

amp_negtuple or list

Absolute minimum and maximum negative trough amplitude of the slow-wave. Default is 40 uV to 200 uV. Can also be in unit of standard deviations if the data has been previously z-scored. If you do not want to specify any negative amplitude thresholds, use amp_neg=(None, None).

amp_postuple or list

Absolute minimum and maximum positive peak amplitude of the slow-wave. Default is 10 uV to 150 uV. Can also be in unit of standard deviations if the data has been previously z-scored. If you do not want to specify any positive amplitude thresholds, use amp_pos=(None, None).

amp_ptptuple or list

Minimum and maximum peak-to-peak amplitude of the slow-wave. Default is 75 uV to 350 uV. Can also be in unit of standard deviations if the data has been previously z-scored. Use np.inf to set no upper amplitude threshold (e.g. amp_ptp=(75, np.inf)).

couplingboolean

If True, YASA will also calculate the phase-amplitude coupling between the slow-waves phase and the spindles-related sigma band amplitude. Specifically, the following columns will be added to the output dataframe:

  1. 'SigmaPeak': The location (in seconds) of the maximum sigma peak amplitude within a 2-seconds epoch centered around the negative peak (through) of the current slow-wave.

  2. PhaseAtSigmaPeak: the phase of the bandpas-filtered slow-wave signal (in radians) at 'SigmaPeak'.

    Importantly, since PhaseAtSigmaPeak is expressed in radians, one should use circular statistics to calculate the mean direction and vector length:

    import pingouin as pg
    mean_direction = pg.circ_mean(sw['PhaseAtSigmaPeak'])
    vector_length = pg.circ_r(sw['PhaseAtSigmaPeak'])
    
  3. ndPAC: the normalized Mean Vector Length (also called the normalized direct PAC, or ndPAC) within a 2-sec epoch centered around the negative peak of the slow-wave.

The lower and upper frequencies for the slow-waves and spindles-related sigma signals are defined in freq_sw and coupling_params['freq_sp'], respectively. For more details, please refer to the Jupyter notebook

Note that setting coupling=True may increase computation time.

New in version 0.2.0.

coupling_paramsdict

Parameters for the phase-amplitude coupling.

  • freq_sp is a tuple or list that defines the spindles-related frequency of interest. The default is 12 to 16 Hz, with a wide transition bandwidth of 1.5 Hz.

  • time is an int or a float that defines the time around the negative peak of each detected slow-waves, in seconds. For example, a value of 1 means that the coupling will be calculated for each slow-waves using a 2-seconds epoch centered around the negative peak of the slow-waves (i.e. 1 second on each side).

  • p is a parameter passed to the tensorpac.methods.norm_direct_pac`() function. It represents the p-value to use for thresholding of unreliable coupling values. Sub-threshold PAC values will be set to 0. To disable this behavior (no masking), use p=1 or p=None.

New in version 0.6.0.

remove_outliersboolean

If True, YASA will automatically detect and remove outliers slow-waves using sklearn.ensemble.IsolationForest. The outliers detection is performed on the frequency, amplitude and duration parameters of the detected slow-waves. YASA uses a random seed (42) to ensure reproducible results. Note that this step will only be applied if there are more than 50 detected slow-waves in the first place. Default to False.

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

New in version 0.2.0.

Returns
swyasa.SWResults

To get the full detection dataframe, use:

>>> sw = sw_detect(...)
>>> sw.summary()

This will give a pandas.DataFrame where each row is a detected slow-wave and each column is a parameter (= property). To get the average SW parameters per channel and sleep stage:

>>> sw.summary(grp_chan=True, grp_stage=True)

Notes

The parameters that are calculated for each slow-wave are:

  • 'Start': Start time of each detected slow-wave, in seconds from the beginning of data.

  • 'NegPeak': Location of the negative peak (in seconds)

  • 'MidCrossing': Location of the negative-to-positive zero-crossing (in seconds)

  • 'Pospeak': Location of the positive peak (in seconds)

  • 'End': End time(in seconds)

  • 'Duration': Duration (in seconds)

  • 'ValNegPeak': Amplitude of the negative peak (in uV, calculated on the freq_sw bandpass-filtered signal)

  • 'ValPosPeak': Amplitude of the positive peak (in uV, calculated on the freq_sw bandpass-filtered signal)

  • 'PTP': Peak-to-peak amplitude (= ValPosPeak - ValNegPeak, calculated on the freq_sw bandpass-filtered signal)

  • 'Slope': Slope between NegPeak and MidCrossing (in uV/sec, calculated on the freq_sw bandpass-filtered signal)

  • 'Frequency': Frequency of the slow-wave (= 1 / Duration)

  • 'SigmaPeak': Location of the sigma peak amplitude within a 2-sec epoch centered around the negative peak of the slow-wave. This is only calculated when coupling=True.

  • 'PhaseAtSigmaPeak': SW phase at max sigma amplitude within a 2-sec epoch centered around the negative peak of the slow-wave. This is only calculated when coupling=True

  • 'ndPAC': Normalized direct PAC within a 2-sec epoch centered around the negative peak of the slow-wave. This is only calculated when coupling=True

  • 'Stage': Sleep stage (only if hypno was provided)

slow-wave

For better results, apply this detection only on artefact-free NREM sleep.

References

The slow-waves detection algorithm is based on:

Examples

For an example of how to run the detection, please refer to the tutorial: https://github.com/raphaelvallat/yasa/blob/master/notebooks/05_sw_detection.ipynb