SpectralPipe#
- class sleepeegpy.pipeline.SpectralPipe(*, prec_pipe=None, path_to_eeg=_Nothing.NOTHING, output_dir=_Nothing.NOTHING, path_to_hypno=None, hypno_freq=_Nothing.NOTHING, hypno=_Nothing.NOTHING)[source]#
Bases:
BaseHypnoPipe
,SpectrumPlots
The spectral analyses pipeline element.
Contains methods for computing and plotting PSD, spectrogram and topomaps per sleep stage.
Methods:
For each sleep stage creates a
mne.time_frequency.SpectrumArray
object.A wrapper for
mne.io.Raw.interpolate_bads()
Spectral parametrization by FOOOF - fitting oscillations & one over f.
A wrapper for
mne.io.Raw.plot()
.Plots hypnogram and spectrogram.
Plot PSD per sleep stage.
A wrapper for
mne.viz.plot_sensors()
with a legend.Plots topomap for a sleep stage and a frequency band.
Plots topomap collage for multiple sleep stages and bands.
Runs YASA's automatic sleep staging.
Loads spectra stored in hdf5 files.
Saves SleepSpectrum objects to h5 files.
A wrapper for
mne.io.Raw.save()
.A wrapper for
mne.io.Raw.set_eeg_reference()
.A wrapper for
yasa.sleep_statistics()
.Attributes:
An instanse of
mne.io.Raw
ormne.Epochs
.Instances of
fooof.FOOOF
per sleep stage.Calculates percent of data segments annotated as BAD.
A wrapper for
raw.info["sfreq"]
.Path to hypnogram.
Sampling rate of the hypnogram in Hz.
Hypnogram with sampling frequency hypno_freq with int representing sleep stage.
Hypnogram upsampled to the sampling frequency of the raw data.
Preceding pipe that hands over mne_raw object and output_dir.
Can be any eeg file type supported by
mne.io.read_raw()
.Path to the directory where the output will be saved.
Instances of
SleepSpectrum
per sleep stage.-
mne_raw:
Raw
|Epochs
[source]# An instanse of
mne.io.Raw
ormne.Epochs
.
-
fooofs:
dict
[source]# Instances of
fooof.FOOOF
per sleep stage.
- compute_psd(sleep_stages={'N1': 1, 'N2': 2, 'N3': 3, 'REM': 4, 'Wake': 0}, reference=None, fmin=0, fmax=60, picks='eeg', reject_by_annotation=True, save=False, overwrite=False, **psd_kwargs)[source]#
For each sleep stage creates a
mne.time_frequency.SpectrumArray
object.- Parameters:
sleep_stages (
dict
) – Sleep stages mapping in hypnogram. Defaults to {“Wake”: 0, “N1”: 1, “N2”: 2, “N3”: 3, “REM”: 4}.reference (
UnionType
[Iterable
[str
],str
,None
]) – Which eeg reference to compute PSD with. If None, the reference isn’t changed. Defaults to None.fmin (
float
) – Lower frequency bound. Defaults to 0.fmax (
float
) – Upper frequency bound. Defaults to 60.picks (
str
|Iterable
[str
]) – Channels to compute spectra for. Refer tomne.io.Raw.pick()
. Defaults to “eeg”.reject_by_annotation (
bool
) – Whether to not use the annotations for the spectra computation. Defaults to True.save (
bool
) – Whether to save the spectra in .h5 files. Defaults to False.overwrite (
bool
) – Whether to overwrite psd files. Defaults to False.**psd_kwargs – Additional arguments passed to
mne.time_frequency.psd_array_welch()
.
- parametrize(picks, freq_range=None, average_ch=False, **kwargs)[source]#
Spectral parametrization by FOOOF - fitting oscillations & one over f.
- Parameters:
picks – Channels to use in parametrization.
freq_range – Range of frequencies to parametrize. If None, set to bandpass filter boundaries. Defaults to None.
average_ch – Whether to average psds over channels. If False or multiple channels are provided, the FOOOFGroup will be used. Defaults to False.
**kwargs – Arguments passed to
fooof.FOOOF
.
- read_spectra(dirpath=None)[source]#
Loads spectra stored in hdf5 files.
Filenames should end with {sleep_stage}-psd.h5
- Parameters:
dirpath (
Optional
[str
]) – Path to the directory containing hdf5 files. Defaults to None.
- plot_hypnospectrogram(picks=('E101',), win_sec=10, trimperc=2.5, freq_range=(0, 40), cmap='Spectral_r', overlap=False, reject_by_annotation='NaN', save=False, axis=None)[source]#
Plots hypnogram and spectrogram.
Adapted from YASA.
- Parameters:
picks (
str
|Iterable
[str
]) – Channels to compute the spectrogram on. Defaults to (“E101”,).win_sec (
float
) – The length of the sliding window, in seconds, used for multitaper PSD calculation. Defaults to 30.trimperc (
float
) – The amount of data to trim on both ends of the distribution when normalizing the colormap. Defaults to 2.5.freq_range (
tuple
) – Range of x axis on spectrogram plot. Defaults to (0, 40).cmap (
str
) – Matplotlib colormap. Choosing Colormaps. Defaults to “Spectral_r”.overlap (
bool
) – Whether to plot hypnogram over the spectrogram or on top of it. Defaults to False.reject_by_annotation (
Optional
[str
]) – Whether to reject the annotations for the spectrogram computation. Can be ‘NaN’, ‘omit’ or None. Defaults to ‘NaN’.save (
bool
) – Whether to save the figure. Defaults to False.axis (
Axes
) – Instance ofmatplotlib.axes.Axes
. Defaults to None.
- property bad_data_percent[source]#
Calculates percent of data segments annotated as BAD.
- Returns:
percent of bad data spans in raw data
- Return type:
float
- interpolate_bads(**interp_kwargs)[source]#
A wrapper for
mne.io.Raw.interpolate_bads()
- Parameters:
**interp_kwargs – Arguments passed to
mne.io.Raw.interpolate_bads()
.
- plot(save_annotations=False, save_bad_channels=False, overwrite=False, **kwargs)[source]#
A wrapper for
mne.io.Raw.plot()
.- Parameters:
save_annotations (
bool
) – Whether to save annotations as txt. Defaults to False.save_bad_channels (
bool
) – Whether to save bad channels as txt. Defaults to False.overwrite (
bool
) – Whether to overwrite annotations and bad_channels files if exist. Defaults to False.**kwargs – Arguments passed to
mne.io.Raw.plot()
.
- plot_psds(picks, psd_range=(-40, 60), freq_range=(0, 60), dB=True, xscale='linear', axis=None, plot_sensors=False, save=False, legend_args=None, **plot_kwargs)[source]#
Plot PSD per sleep stage.
- Parameters:
picks (
Iterable
[str
] |str
) – Channels to plot PSDs for. Refer tomne.io.Raw.pick()
.psd_range (
tuple
) – Range of y axis on PSD plot. Defaults to (-40, 60).freq_range (
tuple
) – Range of x axis on PSD plot. Defaults to (0, 40).dB – Whether transform PSD to dB. Defaults to True.
xscale (
str
) – Scale of the X axis, check available values atmatplotlib.axes.Axes.set_xscale()
. Defaults to “linear”.axis (
axis
) – Instance ofmatplotlib.axes.Axes
. Defaults to None.plot_sensors (
bool
) – Whether to plot sensor map showing which channels were used for computing PSD. Defaults to False.save (
bool
) – Whether to save the figure. Defaults to False.**plot_kwargs – Arguments passed to the
matplotlib.pyplot.plot()
. Have no effect if axis is provided.Defaults to None.
- plot_sensors(legend=None, legend_args=None, **kwargs)[source]#
A wrapper for
mne.viz.plot_sensors()
with a legend.- Parameters:
legend (
Iterable
[str
]) – ch_groups names to connect to colors. Defaults to None.legend_args (
dict
) – Arguments passed tomatplotlib.axes.Axes.legend()
. Defaults to None.**kwargs – Arguments passed to
mne.viz.plot_sensors()
.
- plot_topomap(stage='REM', band={'Delta': (0, 4)}, dB=False, axis=None, save=False, topomap_args=None, cbar_args=None)[source]#
Plots topomap for a sleep stage and a frequency band.
- Parameters:
stage (
str
) – One of the sleep_stages keys. Defaults to “REM”.band (
dict
) – Name-value pair - with name=arbitrary name and value=(l_freq, h_freq). Defaults to {“Delta”: (0, 4)}.dB (
bool
) – Whether transform PSD to dB. Defaults to False.axis (
axis
) – Instance ofmatplotlib.axes.Axes
. Defaults to None.save (
bool
) – Whether to save the figure. Defaults to False.topomap_args (
dict
) – Arguments passed tomne.viz.plot_topomap()
.Defaults to None.cbar_args (
dict
) – Arguments passed tomatplotlib.pyplot.colorbar()
.Defaults to None.
- plot_topomap_collage(stages_to_plot='all', bands={'Alpha': (8, 12.49), 'Beta': (12.5, 29.99), 'Delta': (0, 3.99), 'Gamma': (30, 60), 'Sigma': (12.5, 15), 'Theta': (4, 7.99)}, dB=False, low_percentile=5, high_percentile=95, fig=None, save=False, topomap_args=None, cbar_args=None)[source]#
Plots topomap collage for multiple sleep stages and bands.
- Parameters:
stages_to_plot (
tuple
) – Tuple of strings representing names from sleep_stages, e.g., (“REM”, “N1”). If set to “all” plots every stage provided in sleep_stages. Defaults to “all”.bands (
dict
) – Dict of name-value pairs - with name=arbitrary name and value=(l_freq, h_freq). Defaults to { “Delta”: (0, 3.99), “Theta”: (4, 7.99), “Alpha”: (8, 12.49), “Sigma”: (12.5, 15), “Beta”: (12.5, 29.99), “Gamma”: (30, 60), }.dB (
bool
) – Whether transform PSD to dB. Defaults to False.sleep_stages – Mapping between sleep stages names and their integer representations. Defaults to {“Wake”: 0, “N1”: 1, “N2”: 2, “N3”: 3, “REM”: 4}.
low_percentile (
float
) – Set min color value by percentile of the band data. Defaults to 5.high_percentile (
float
) – Set max color value by percentile of the band data. Defaults to 95.fig (
figure
) – Instance ofmpl:matplotlib.pyplot.figure
. Defaults to None.save (
bool
) – Whether to save the figure. Defaults to False.topomap_args (
dict
) – Arguments passed tomne.viz.plot_topomap()
. Defaults to None.cbar_args (
dict
) – Arguments passed tomatplotlib.pyplot.colorbar()
. Defaults to None.
- predict_hypno(eeg_name='E183', eog_name='E252', emg_name='E247', ref_name='E26', save=True)[source]#
Runs YASA’s automatic sleep staging.
- Parameters:
eeg_name (
str
) – Preferentially a central electrode. Defaults to “E183”.eog_name (
str
) – Preferentially, the left LOC channel. Defaults to “E252”.emg_name (
str
) – Preferentially a chin electrode. Defaults to “E247”.ref_name (
str
) – Reference channel, preferentially a mastoid. Defaults to “E26”.save (
bool
) – Whether to save the hypnogram to file. Defaults to True.
- save_psds(overwrite)[source]#
Saves SleepSpectrum objects to h5 files.
- Parameters:
overwrite – Whether to overwrite existing spectrum files.
- save_raw(fname, **kwargs)[source]#
A wrapper for
mne.io.Raw.save()
.- Parameters:
fname (
str
) – Filename for the fif file being saved.**kwargs – Arguments passed to
mne.io.Raw.save()
.
- set_eeg_reference(ref_channels='average', projection=False, **kwargs)[source]#
A wrapper for
mne.io.Raw.set_eeg_reference()
.- Parameters:
ref_channels –
ref_channels
. Defaults to ‘average’.projection –
projection
. Defaults to False.**kwargs – Additional arguments passed to
mne.io.Raw.set_eeg_reference()
.
- property sf[source]#
A wrapper for
raw.info["sfreq"]
.- Returns:
sampling frequency
- Return type:
float
- sleep_stats(save=False)[source]#
A wrapper for
yasa.sleep_statistics()
.- Parameters:
save (
bool
) – Whether to save the stats to csv. Defaults to False.
- path_to_hypno: Path#
Path to hypnogram. Must be text file with every row being int representing sleep stage for the epoch.
- hypno_freq: float#
Sampling rate of the hypnogram in Hz.
E.g., 1/30 means 1 sample per 30 secs epoch, 250 means 1 sample per 1/250 sec epoch.
- hypno: np.ndarray#
Hypnogram with sampling frequency hypno_freq with int representing sleep stage.
- hypno_up: np.array#
Hypnogram upsampled to the sampling frequency of the raw data.
- prec_pipe: Type[BasePipeType]#
Preceding pipe that hands over mne_raw object and output_dir.
- path_to_eeg: Path#
Can be any eeg file type supported by
mne.io.read_raw()
.
- output_dir: Path#
Path to the directory where the output will be saved.
- psds: dict#
Instances of
SleepSpectrum
per sleep stage.
-
mne_raw: