SpectralPipeο
Tip
π‘ Usage Examples - See the notebook for usage examples and code snippets: Spectral analyses
- class sleepeegpy.pipeline.SpectralPipe(*, prec_pipe=None, path_to_eeg=NOTHING, output_dir=NOTHING, path_to_hypno=None, hypno_freq=NOTHING, hypno=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 (
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 (
str
|None
) β 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 in Matplotlib. Defaults to βSpectral_rβ.overlap (
bool
) β Whether to plot hypnogram over the spectrogram or on top of it. Defaults to False.reject_by_annotation (
None
|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: