mne.BaseEpochs#

class mne.BaseEpochs(info, data, events, event_id=None, tmin=-0.2, tmax=0.5, baseline=(None, 0), raw=None, picks=None, reject=None, flat=None, decim=1, reject_tmin=None, reject_tmax=None, detrend=None, proj=True, on_missing='raise', preload_at_end=False, selection=None, drop_log=None, filename=None, metadata=None, event_repeated='error', *, raw_sfreq=None, annotations=None, verbose=None)[source]#

Abstract base class for Epochs-type classes.

Note

This class should not be instantiated directly via mne.BaseEpochs(...). Instead, use one of the functions listed in the See Also section below.

Parameters:
infomne.Info

The mne.Info object with information about the sensors and methods of measurement.

datandarray | None

If None, data will be read from the Raw object. If ndarray, must be of shape (n_epochs, n_channels, n_times).

eventsarray of int, shape (n_events, 3)

The array of events. The first column contains the event time in samples, with first_samp included. The third column contains the event id. If some events don’t match the events of interest as specified by event_id, they will be marked as IGNORED in the drop log.

event_idint | list of int | dict | str | list of str | None

The id of the events to consider. If dict, the keys can later be used to access associated events. Example: dict(auditory=1, visual=3). If int, a dict will be created with the id as string. If a list of int, all events with the IDs specified in the list are used. If a str or list of str, events must be None to use annotations and then the IDs must be the name(s) of the annotations to use. If None, all events will be used and a dict is created with string integer names corresponding to the event id integers.

tmin, tmaxfloat

Start and end time of the epochs in seconds, relative to the time-locked event. The closest or matching samples corresponding to the start and end time are included. Defaults to -0.2 and 0.5, respectively.

baselineNone | tuple of length 2

The time interval to consider as “baseline” when applying baseline correction. If None, do not apply baseline correction. If a tuple (a, b), the interval is between a and b (in seconds), including the endpoints. If a is None, the beginning of the data is used; and if b is None, it is set to the end of the interval. If (None, None), the entire time interval is used.

Note

The baseline (a, b) includes both endpoints, i.e. all timepoints t such that a <= t <= b.

Correction is applied to each epoch and channel individually in the following way:

  1. Calculate the mean signal of the baseline period.

  2. Subtract this mean from the entire epoch.

Defaults to (None, 0), i.e. beginning of the the data until time point zero.

rawRaw object

An instance of Raw.

picksstr | array_like | slice | None

Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g., ['meg', 'eeg']) will pick channels of those types, channel name strings (e.g., ['MEG0111', 'MEG2623'] will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick all channels. Note that channels in info['bads'] will be included if their names or indices are explicitly provided.

rejectdict | None

Reject epochs based on maximum peak-to-peak signal amplitude (PTP), i.e. the absolute difference between the lowest and the highest signal value. In each individual epoch, the PTP is calculated for every channel. If the PTP of any one channel exceeds the rejection threshold, the respective epoch will be dropped.

The dictionary keys correspond to the different channel types; valid keys can be any channel type present in the object.

Example:

reject = dict(grad=4000e-13,  # unit: T / m (gradiometers)
              mag=4e-12,      # unit: T (magnetometers)
              eeg=40e-6,      # unit: V (EEG channels)
              eog=250e-6      # unit: V (EOG channels)
              )

Note

Since rejection is based on a signal difference calculated for each channel separately, applying baseline correction does not affect the rejection procedure, as the difference will be preserved.

Note

To constrain the time period used for estimation of signal quality, pass the reject_tmin and reject_tmax parameters.

If reject is None (default), no rejection is performed.

flatdict | None

Reject epochs based on minimum peak-to-peak signal amplitude (PTP). Valid keys can be any channel type present in the object. The values are floats that set the minimum acceptable PTP. If the PTP is smaller than this threshold, the epoch will be dropped. If None then no rejection is performed based on flatness of the signal.

Note

To constrain the time period used for estimation of signal quality, pass the reject_tmin and reject_tmax parameters.

decimint

Factor by which to subsample the data.

Warning

Low-pass filtering is not performed, this simply selects every Nth sample (where N is the value passed to decim), i.e., it compresses the signal (see Notes). If the data are not properly filtered, aliasing artifacts may occur.

reject_tmin, reject_tmaxfloat | None

Start and end of the time window used to reject epochs based on peak-to-peak (PTP) amplitudes as specified via reject and flat. The default None corresponds to the first and last time points of the epochs, respectively.

Note

This parameter controls the time period used in conjunction with both, reject and flat.

detrendint | None

If 0 or 1, the data channels (MEG and EEG) will be detrended when loaded. 0 is a constant (DC) detrend, 1 is a linear detrend. None is no detrending. Note that detrending is performed before baseline correction. If no DC offset is preferred (zeroth order detrending), either turn off baseline correction, as this may introduce a DC shift, or set baseline correction to use the entire time interval (will yield equivalent results but be slower).

projbool | ‘delayed’

Apply SSP projection vectors. If proj is ‘delayed’ and reject is not None the single epochs will be projected before the rejection decision, but used in unprojected state if they are kept. This way deciding which projection vectors are good can be postponed to the evoked stage without resulting in lower epoch counts and without producing results different from early SSP application given comparable parameters. Note that in this case baselining, detrending and temporal decimation will be postponed. If proj is False no projections will be applied which is the recommended value if SSPs are not used for cleaning the data.

on_missing‘raise’ | ‘warn’ | ‘ignore’

What to do if one or several event ids are not found in the recording. Valid keys are ‘raise’ | ‘warn’ | ‘ignore’ Default is 'raise'. If 'warn', it will proceed but warn; if 'ignore', it will proceed silently.

Note

If none of the event ids are found in the data, an error will be automatically generated irrespective of this parameter.

preload_at_endbool

Load all epochs from disk when creating the object or wait before accessing each epoch (more memory efficient but can be slower).

selectioniterable | None

Iterable of indices of selected epochs. If None, will be automatically generated, corresponding to all non-zero events.

New in v0.16.

drop_logtuple | None

Tuple of tuple of strings indicating which epochs have been marked to be ignored.

filenamestr | None

The filename (if the epochs are read from disk).

metadatainstance of pandas.DataFrame | None

A pandas.DataFrame specifying metadata about each epoch. If given, len(metadata) must equal len(events). The DataFrame may only contain values of type (str | int | float | bool). If metadata is given, then pandas-style queries may be used to select subsets of data, see mne.Epochs.__getitem__(). When a subset of the epochs is created in this (or any other supported) manner, the metadata object is subsetted accordingly, and the row indices will be modified to match epochs.selection.

New in v0.16.

event_repeatedstr

How to handle duplicates in events[:, 0]. Can be 'error' (default), to raise an error, ‘drop’ to only retain the row occurring first in the events, or 'merge' to combine the coinciding events (=duplicates) into a new event (see Notes for details).

New in v0.19.

raw_sfreqfloat

The original Raw object sampling rate. If None, then it is set to info['sfreq'].

annotationsinstance of mne.Annotations | None

Annotations to set.

verbosebool | str | int | None

Control verbosity of the logging output. If None, use the default verbosity level. See the logging documentation and mne.verbose() for details. Should only be passed as a keyword argument.

Notes

The BaseEpochs class is public to allow for stable type-checking in user code (i.e., isinstance(my_epochs, BaseEpochs)) but should not be used as a constructor for Epochs objects (use instead mne.Epochs).

Attributes:
annotations
ch_names

Channel names.

compensation_grade

The current gradient compensation grade.

filename

The filename.

metadata

Get the metadata.

proj

Whether or not projections are active.

times

Time vector in seconds.

tmax

Last time point.

tmin

First time point.

Methods

__contains__(ch_type)

Check channel type membership.

__getitem__(item)

Return an Epochs object with a copied subset of epochs.

__iter__()

Facilitate iteration over epochs.

__len__()

Return the number of epochs.

add_annotations_to_metadata([overwrite])

Add raw annotations into the Epochs metadata data frame.

add_channels(add_list[, force_update_info])

Append new channels to the instance.

add_proj(projs[, remove_existing, verbose])

Add SSP projection vectors.

add_reference_channels(ref_channels)

Add reference channels to data that consists of all zeros.

anonymize([daysback, keep_his, verbose])

Anonymize measurement information in place.

apply_baseline([baseline, verbose])

Baseline correct epochs.

apply_function(fun[, picks, dtype, n_jobs, ...])

Apply a function to a subset of channels.

apply_hilbert([picks, envelope, n_jobs, ...])

Compute analytic signal or envelope for a subset of channels/vertices.

apply_proj([verbose])

Apply the signal space projection (SSP) operators to the data.

as_type([ch_type, mode])

Compute virtual epochs using interpolated fields.

average([picks, method, by_event_type])

Compute an average over epochs.

compute_psd([method, fmin, fmax, tmin, ...])

Perform spectral analysis on sensor data.

copy()

Return copy of Epochs instance.

crop([tmin, tmax, include_tmax, verbose])

Crop a time interval from the epochs.

decimate(decim[, offset, verbose])

Decimate the time-series data.

del_proj([idx])

Remove SSP projection vector.

drop(indices[, reason, verbose])

Drop epochs based on indices or boolean mask.

drop_bad([reject, flat, verbose])

Drop bad epochs without retaining the epochs data.

drop_channels(ch_names[, on_missing])

Drop channel(s).

drop_log_stats([ignore])

Compute the channel stats based on a drop_log from Epochs.

equalize_event_counts([event_ids, method])

Equalize the number of trials in each condition.

export(fname[, fmt, overwrite, verbose])

Export Epochs to external formats.

filter(l_freq, h_freq[, picks, ...])

Filter a subset of channels/vertices.

get_annotations_per_epoch()

Get a list of annotations that occur during each epoch.

get_channel_types([picks, unique, only_data_chs])

Get a list of channel type for each channel.

get_data([picks, item, units, tmin, tmax, ...])

Get all epochs as a 3D array.

get_montage()

Get a DigMontage from instance.

interpolate_bads([reset_bads, mode, origin, ...])

Interpolate bad MEG and EEG channels.

iter_evoked([copy])

Iterate over epochs as a sequence of Evoked objects.

load_data()

Load the data if not already preloaded.

next([return_event_id])

Iterate over epoch data.

pick(picks[, exclude, verbose])

Pick a subset of channels.

pick_channels(ch_names[, ordered, verbose])

Warning

LEGACY: New code should use inst.pick(...).

pick_types([meg, eeg, stim, eog, ecg, emg, ...])

Warning

LEGACY: New code should use inst.pick(...).

plot([picks, scalings, n_epochs, ...])

Visualize epochs.

plot_drop_log([threshold, n_max_plot, ...])

Show the channel stats based on a drop_log from Epochs.

plot_image([picks, sigma, vmin, vmax, ...])

Plot Event Related Potential / Fields image.

plot_projs_topomap([ch_type, sensors, ...])

Plot SSP vector.

plot_psd([fmin, fmax, tmin, tmax, picks, ...])

Plot power or amplitude spectra.

plot_psd_topo([tmin, tmax, fmin, fmax, ...])

Warning

LEGACY: New code should use .compute_psd().plot_topo().

plot_psd_topomap([bands, tmin, tmax, ...])

Warning

LEGACY: New code should use .compute_psd().plot_topomap().

plot_sensors([kind, ch_type, title, ...])

Plot sensor positions.

plot_topo_image([layout, sigma, vmin, vmax, ...])

Plot Event Related Potential / Fields image on topographies.

rename_channels(mapping[, allow_duplicates, ...])

Rename channels.

reorder_channels(ch_names)

Reorder channels.

resample(sfreq, *[, npad, window, n_jobs, ...])

Resample data.

reset_drop_log_selection()

Reset the drop_log and selection entries.

save(fname[, split_size, fmt, overwrite, ...])

Save epochs in a fif file.

savgol_filter(h_freq[, verbose])

Filter the data using Savitzky-Golay polynomial method.

set_annotations(annotations[, on_missing, ...])

Setter for Epoch annotations from Raw.

set_channel_types(mapping, *[, ...])

Specify the sensor types of channels.

set_eeg_reference([ref_channels, ...])

Specify which reference to use for EEG data.

set_meas_date(meas_date)

Set the measurement start date.

set_montage(montage[, match_case, ...])

Set EEG/sEEG/ECoG/DBS/fNIRS channel positions and digitization points.

shift_time(tshift[, relative])

Shift time scale in epoched or evoked data.

standard_error([picks, by_event_type])

Compute standard error over epochs.

subtract_evoked([evoked])

Subtract an evoked response from each epoch.

time_as_index(times[, use_rounding])

Convert time to indices.

to_data_frame([picks, index, scalings, ...])

Export data in tabular structure as a pandas DataFrame.