yasa.SpindlesResults

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

Output class for spindles detection.

Attributes
_eventspandas.DataFrame

Output detection dataframe

_dataarray_like

Original EEG data of shape (n_chan, n_samples).

_data_filtarray_like

Sigma-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]

Methods

__init__(events, data, sf, ch_names, hypno, ...)

compare_channels([score, max_distance_sec])

Compare detected spindles across channels.

compare_detection(other[, max_distance_sec, ...])

Compare the detected spindles against either another YASA detection or against custom annotations (e.g.

get_coincidence_matrix([scaled])

Return the (scaled) coincidence matrix.

get_mask()

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 or filtered data of each detected event after centering to a specific timepoint.

plot_average([center, hue, time_before, ...])

Plot the average spindle.

plot_detection()

Plot an overlay of the detected spindles on the EEG signal.

summary([grp_chan, grp_stage, mask, ...])

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

compare_channels(score='f1', max_distance_sec=0)[source]

Compare detected spindles 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 spindles, 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 spindles 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 spindles 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 spindles 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 spindles, 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.

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?

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 spindles 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 spindle 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 spindle 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()  # Unscaled 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='Peak', time_before=1, time_after=1, filt=(None, None), mask=None, as_dataframe=True)[source]

Return the raw or filtered 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 center peak of the spindles.

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.

maskarray_like or None

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

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='Peak', hue='Channel', time_before=1, time_after=1, filt=(None, None), mask=None, figsize=(6, 4.5), **kwargs)[source]

Plot the average spindle.

Parameters
centerstr

Landmark of the event to synchronize the timing on. Default is to use the most prominent peak of the spindle.

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=(12, 16) will apply a 12 to 16 Hz bandpass filter, and filt=(None, 40) will apply a 40 Hz lowpass filter. Filtering is done using the default parameters in the mne.filter.filter_data() function.

maskarray_like or None

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

maskarray_like or None

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

aggfuncstr or function

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

sortbool

If True, sort group keys when grouping.