# yasa.SWResults¶

class yasa.SWResults(events, data, sf, ch_names, hypno, data_filt)[source]

Output class for slow-waves detection.

Attributes
_eventspandas.DataFrame

Output detection dataframe

_dataarray_like

EEG data of shape (n_chan, n_samples).

_data_filtarray_like

Slow-wave filtered EEG data of shape (n_chan, n_samples).

_sffloat

Sampling frequency of data.

_ch_nameslist

Channel names.

_hypnoarray_like or None

Sleep staging vector.

__init__(events, data, sf, ch_names, hypno, data_filt)[source]

Initialize self. See help(type(self)) for accurate signature.

Methods

 __init__(events, data, sf, ch_names, hypno, …) Initialize self. compare_channels([score, max_distance_sec]) Compare detected slow-waves across channels. compare_detection(other[, max_distance_sec, …]) Compare the detected slow-waves against either another YASA detection or against custom annotations (e.g. find_cooccurring_spindles(spindles[, lookaround]) Given a spindles detection summary dataframe, find slow-waves that co-occur with sleep spindles. get_coincidence_matrix([scaled]) Return the (scaled) coincidence matrix. Return a boolean array indicating for each sample in data if this sample is part of a detected event (True) or not (False). get_sync_events([center, time_before, …]) Return the raw data of each detected event after centering to a specific timepoint. plot_average([center, hue, time_before, …]) Plot the average slow-wave. Plot an overlay of the detected slow-waves on the EEG signal. summary([grp_chan, grp_stage, mask, …]) Return a summary of the SW detection, optionally grouped across channels and/or stage.
compare_channels(score='f1', max_distance_sec=0)[source]

Compare detected slow-waves across channels.

This is a wrapper around the yasa.compare_detection() function. Please refer to the documentation of this function for more details.

Parameters
scorestr

The performance metric to compute. Accepted values are “precision”, “recall” (aka sensitivity) and “f1” (default). The F1-score is the harmonic mean of precision and recall, and is usually the preferred metric to evaluate the agreement between two channels. All three metrics are bounded by 0 and 1, where 1 indicates perfect agreement.

max_distance_secfloat

The maximum distance between slow-waves, in seconds, to consider as the same event.

Warning

To reduce computation cost, YASA rounds the start time of each spindle to the nearest decisecond (= 100 ms). This means that the lowest possible resolution is 100 ms, regardless of the sampling frequency of the data. Two slow-waves starting at 500 ms and 540 ms on their respective channels will therefore always be considered the same event, even when max_distance_sec=0.

Returns
scorespandas.DataFrame

A Pandas DataFrame with the output scores, of shape (n_chan, n_chan).

Notes

Some use cases of this function:

1. What proportion of slow-waves detected in one channel are also detected on another channel (if using score="recall").

2. What is the overall agreement in the detected events between channels?

3. Is the agreement better in channels that are close to one another?

compare_detection(other, max_distance_sec=0, other_is_groundtruth=True)[source]

Compare the detected slow-waves against either another YASA detection or against custom annotations (e.g. ground-truth human scoring).

This function is a wrapper around the yasa.compare_detection() function. Please refer to the documentation of this function for more details.

Parameters
otherdataframe or detection results

This can be either a) the output of another YASA detection, for example if you want to test the impact of tweaking some parameters on the detected events or b) a pandas DataFrame with custom annotations, obtained by another detection method outside of YASA, or with manual labelling. If b), the dataframe must contain the “Start” and “Channel” columns, with the start of each event in seconds from the beginning of the recording and the channel name, respectively. The channel names should match the output of the summary() method.

max_distance_secfloat

The maximum distance between slow-waves, in seconds, to consider as the same event.

Warning

To reduce computation cost, YASA rounds the start time of each slow-wave to the nearest decisecond (= 100 ms). This means that the lowest possible resolution is 100 ms, regardless of the sampling frequency of the data.

other_is_groundtruthbool

If True (default), other will be considered as the ground-truth scoring. If False, the current detection will be considered as the ground-truth, and the precision and recall scores will be inverted. This parameter has no effect on the F1-score.

Note

when other is the ground-truth (default), the recall score is the fraction of events in other that were succesfully detected by the current detection, and the precision score is the proportion of detected events by the current detection that are also present in other.

Returns
scorespandas.DataFrame

A Pandas DataFrame with the channel names as index, and the following columns

• precision: Precision score, aka positive predictive value

• recall: Recall score, aka sensitivity

• f1: F1-score

• n_self: Number of detected events in self (current method).

• n_other: Number of detected events in other.

Notes

Some use cases of this function:

1. How well does YASA events detection perform against ground-truth human annotations?

2. If I change the threshold(s) of the events detection, do the detected events match those obtained with the default parameters?

3. Which detection thresholds give the highest agreement with the ground-truth scoring?

find_cooccurring_spindles(spindles, lookaround=1.2)[source]

Given a spindles detection summary dataframe, find slow-waves that co-occur with sleep spindles.

New in version 0.6.0.

Parameters
spindlespandas.DataFrame

Output dataframe of yasa.SpindlesResults.summary().

lookaroundfloat

Lookaround window, in seconds. The default is +/- 1.2 seconds around the negative peak of the slow-wave, as in [1]. This means that YASA will look for a spindle in a 2.4 seconds window centered around the downstate of the slow-wave.

Returns
_eventspandas.DataFrame

The slow-wave detection is modified IN-PLACE (see Notes). To see the updated dataframe, call the yasa.SWResults.summary() method.

Notes

From [1]:

“SO–spindle co-occurrence was first determined by the number of spindle centers occurring within a ±1.2-sec window around the downstate peak of a SO, expressed as the ratio of all detected SO events in an individual channel.”

This function adds three columns to the output detection dataframe:

• CooccurringSpindle: a boolean column (True / False) that indicates whether the given slow-wave co-occur with a sleep spindle.

• CooccurringSpindlePeak: the timestamp of the peak of the co-occurring, in seconds from beginning of recording. Values are set to np.nan when no co-occurring spindles were found.

• DistanceSpindleToSW: The distance in seconds from the center peak of the spindles and the negative peak of the slow-waves. Negative values indicate that the spindles occured before the negative peak of the slow-waves. Values are set to np.nan when no co-occurring spindles were found.

References

1(1,2)

Kurz, E. M., Conzelmann, A., Barth, G. M., Renner, T. J., Zinke, K., & Born, J. (2021). How do children with autism spectrum disorder form gist memory during sleep? A study of slow oscillation–spindle coupling. Sleep, 44(6), zsaa290.

get_coincidence_matrix(scaled=True)[source]

Return the (scaled) coincidence matrix.

Parameters
scaledbool

If True (default), the coincidence matrix is scaled (see Notes).

Returns
coincidencepd.DataFrame

A symmetric matrix with the (scaled) coincidence values.

Notes

Do slow-waves occur at the same time? One way to measure this is to calculate the coincidence matrix, which gives, for each pair of channel, the number of samples that were marked as a slow-waves in both channels. The output is a symmetric matrix, in which the diagonal is simply the number of data points that were marked as a slow-waves in the channel.

The coincidence matrix can be scaled (default) by dividing the output by the product of the sum of each individual binary mask, as shown in the example below. It can then be used to define functional networks or quickly find outlier channels.

References

Examples

Calculate the coincidence of two binary mask:

>>> import numpy as np
>>> x = np.array([0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1])
>>> y = np.array([0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1])
>>> x * y
array([0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1])

>>> (x * y).sum()  # Coincidence
3

>>> (x * y).sum() / (x.sum() * y.sum())  # Scaled coincidence
0.12

get_mask()[source]

Return a boolean array indicating for each sample in data if this sample is part of a detected event (True) or not (False).

get_sync_events(center='NegPeak', time_before=0.4, time_after=0.8, filt=None, None, mask=None, as_dataframe=True)[source]

Return the raw data of each detected event after centering to a specific timepoint.

Parameters
centerstr

Landmark of the event to synchronize the timing on. Default is to use the negative peak of the slow-wave.

time_beforefloat

Time (in seconds) before center.

time_afterfloat

Time (in seconds) after center.

filttuple

Optional filtering to apply to data. For instance, filt=(1, 30) will apply a 1 to 30 Hz bandpass filter, and filt=(None, 40) will apply a 40 Hz lowpass filter. Filtering is done using default parameters in the mne.filter.filter_data() function.

Custom boolean mask. Only the detected events for which mask is True will be included. Default is None, i.e. no masking (all events are included).

as_dataframeboolean

If True (default), returns a long-format pandas dataframe. If False, returns a list of numpy arrays. Each element of the list a unique channel, and the shape of the numpy arrays within the list is (n_events, n_times).

Returns
df_syncpandas.DataFrame or list

Ouput long-format dataframe (if as_dataframe=True):

'Event' : Event number
'Time' : Timing of the events (in seconds)
'Amplitude' : Raw or filtered data for event
'Channel' : Channel
'IdxChannel' : Index of channel in data
'Stage': Sleep stage in which the events occured (if available)

plot_average(center='NegPeak', hue='Channel', time_before=0.4, time_after=0.8, filt=None, None, mask=None, figsize=6, 4.5, **kwargs)[source]

Plot the average slow-wave.

Parameters
centerstr

Landmark of the event to synchronize the timing on. The default is to use the negative peak of the slow-wave.

huestr

Grouping variable that will produce lines with different colors. Can be either ‘Channel’ or ‘Stage’.

time_beforefloat

Time (in seconds) before center.

time_afterfloat

Time (in seconds) after center.

filttuple

Optional filtering to apply to data. For instance, filt=(1, 30) will apply a 1 to 30 Hz bandpass filter, and filt=(None, 40) will apply a 40 Hz lowpass filter. Filtering is done using default parameters in the mne.filter.filter_data() function.

Custom boolean mask. Only the detected events for which mask is True will be plotted. Default is None, i.e. no masking (all events are included).

figsizetuple

Figure size in inches.

**kwargsdict

Optional argument that are passed to seaborn.lineplot().

plot_detection()[source]

Plot an overlay of the detected slow-waves on the EEG signal.

This only works in Jupyter and it requires the ipywidgets (https://ipywidgets.readthedocs.io/en/latest/) package.

To activate the interactive mode, make sure to run:

>>> %matplotlib widget


New in version 0.4.0.

summary(grp_chan=False, grp_stage=False, mask=None, aggfunc='mean', sort=True)[source]

Return a summary of the SW detection, optionally grouped across channels and/or stage.

Parameters
grp_chanbool

If True, group by channel (for multi-channels detection only).

grp_stagebool

If True, group by sleep stage (provided that an hypnogram was used).

Averaging function (e.g. 'mean' or 'median').