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', verbose=None)[source]

Abstract base class for Epochs-type classes.

This class provides basic functionality and should never be instantiated directly. See Epochs below for an explanation of the parameters.

Parameters
infodict

A copy of the info dict from the raw object.

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)

See Epochs docstring.

event_idint | list of int | dict | None

See Epochs docstring.

tminfloat

See Epochs docstring.

tmaxfloat

See Epochs docstring.

baselineNone | tuple of length 2

See Epochs docstring.

rawRaw object

An instance of Raw.

picksstr | list | slice | None

See Epochs docstring.

rejectdict | None

See Epochs docstring.

flatdict | None

See Epochs docstring.

decimint

See Epochs docstring.

reject_tminscalar | None

See Epochs docstring.

reject_tmaxscalar | None

See Epochs docstring.

detrendint | None

See Epochs docstring.

projbool | ‘delayed’

See Epochs docstring.

on_missingstr

See Epochs docstring.

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.

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

See mne.Epochs docstring.

New in version 0.16.

event_repeatedstr

See mne.Epochs docstring.

New in version 0.19.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only.

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

__hash__()

Hash the object.

__iter__()

Facilitate iteration over epochs.

__len__()

Return the number of epochs.

add_channels(add_list[, force_update_info])

Append new channels to the instance.

add_proj(projs[, remove_existing, verbose])

Add SSP projection vectors.

anonymize([daysback, keep_his, verbose])

Anonymize measurement information in place.

apply_baseline([baseline, verbose])

Baseline correct epochs.

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

Compute analytic signal or envelope for a subset of channels.

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

Compute an average over epochs.

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 epochs.

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)

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.

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

Filter a subset of channels.

get_channel_types([picks, unique, only_data_chs])

Get a list of channel type for each channel.

get_data([picks, item])

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

Pick a subset of channels.

pick_channels(ch_names[, ordered])

Pick some channels.

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

Pick some channels by type and names.

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, cmap, sensors, …])

Plot SSP vector.

plot_psd([fmin, fmax, tmin, tmax, proj, …])

Plot the power spectral density across channels.

plot_psd_topomap([bands, vmin, vmax, tmin, …])

Plot the topomap of the power spectral density across epochs.

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)

Rename channels.

reorder_channels(ch_names)

Reorder channels.

resample(sfreq[, npad, window, n_jobs, pad, …])

Resample data.

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_channel_types(mapping[, verbose])

Define the sensor type 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 sensor configuration and head digitization.

shift_time(tshift[, relative])

Shift time scale in epoched or evoked data.

standard_error([picks])

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.

__contains__(ch_type)[source]

Check channel type membership.

Parameters
ch_typestr

Channel type to check for. Can be e.g. ‘meg’, ‘eeg’, ‘stim’, etc.

Returns
inbool

Whether or not the instance contains the given channel type.

Examples

Channel type membership can be tested as:

>>> 'meg' in inst  
True
>>> 'seeg' in inst  
False
__getitem__(item)[source]

Return an Epochs object with a copied subset of epochs.

Parameters
itemslice, array_like, str, or list

See below for use cases.

Returns
epochsinstance of Epochs

See below for use cases.

Notes

Epochs can be accessed as epochs[...] in several ways:

  1. epochs[idx]: Return Epochs object with a subset of epochs (supports single index and python-style slicing).

  2. epochs['name']: Return Epochs object with a copy of the subset of epochs corresponding to an experimental condition as specified by ‘name’.

    If conditions are tagged by names separated by ‘/’ (e.g. ‘audio/left’, ‘audio/right’), and ‘name’ is not in itself an event key, this selects every event whose condition contains the ‘name’ tag (e.g., ‘left’ matches ‘audio/left’ and ‘visual/left’; but not ‘audio_left’). Note that tags selection is insensitive to order: tags like ‘auditory/left’ and ‘left/auditory’ will be treated the same way when accessed.

  3. epochs[['name_1', 'name_2', ... ]]: Return Epochs object with a copy of the subset of epochs corresponding to multiple experimental conditions as specified by 'name_1', 'name_2', ... .

    If conditions are separated by ‘/’, selects every item containing every list tag (e.g. [‘audio’, ‘left’] selects ‘audio/left’ and ‘audio/center/left’, but not ‘audio/right’).

  4. epochs['pandas query']: Return Epochs object with a copy of the subset of epochs (and matching metadata) that match pandas query called with self.metadata.eval, e.g.:

    epochs["col_a > 2 and col_b == 'foo'"]
    

    This is only called if Pandas is installed and self.metadata is a pandas.DataFrame.

    New in version 0.16.

__hash__()[source]

Hash the object.

Returns
hashint

The hash

__iter__()[source]

Facilitate iteration over epochs.

This method resets the object iteration state to the first epoch.

Notes

This enables the use of this Python pattern:

>>> for epoch in epochs:  
>>>     print(epoch)  

Where epoch is given by successive outputs of mne.Epochs.next().

__len__()[source]

Return the number of epochs.

Returns
n_epochsint

The number of remaining epochs.

Notes

This function only works if bad epochs have been dropped.

Examples

This can be used as:

>>> epochs.drop_bad()  
>>> len(epochs)  
43
>>> len(epochs.events)  
43
add_channels(add_list, force_update_info=False)[source]

Append new channels to the instance.

Parameters
add_listlist

A list of objects to append to self. Must contain all the same type as the current object.

force_update_infobool

If True, force the info for objects to be appended to match the values in self. This should generally only be used when adding stim channels for which important metadata won’t be overwritten.

New in version 0.12.

Returns
instinstance of Raw, Epochs, or Evoked

The modified instance.

See also

drop_channels

Notes

If self is a Raw instance that has been preloaded into a numpy.memmap instance, the memmap will be resized.

add_proj(projs, remove_existing=False, verbose=None)[source]

Add SSP projection vectors.

Parameters
projslist

List with projection vectors.

remove_existingbool

Remove the projection vectors currently in the file.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Returns
selfinstance of Raw | Epochs | Evoked

The data container.

Examples using add_proj:

anonymize(daysback=None, keep_his=False, verbose=None)[source]

Anonymize measurement information in place.

Parameters
daysbackint | None

Number of days to subtract from all dates. If None (default), the acquisition date, info['meas_date'], will be set to January 1ˢᵗ, 2000. This parameter is ignored if info['meas_date'] is None (i.e., no acquisition date has been set).

keep_hisbool

If True, his_id of subject_info will not be overwritten. Defaults to False.

Warning

This could mean that info is not fully anonymized. Use with caution.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only.

Returns
instinstance of Raw | Epochs | Evoked

The modified instance.

Notes

Removes potentially identifying information if it exists in info. Specifically for each of the following we use:

  • meas_date, file_id, meas_id

    A default value, or as specified by daysback.

  • subject_info

    Default values, except for ‘birthday’ which is adjusted to maintain the subject age.

  • experimenter, proj_name, description

    Default strings.

  • utc_offset

    None.

  • proj_id

    Zeros.

  • proc_history

    Dates use the meas_date logic, and experimenter a default string.

  • helium_info, device_info

    Dates use the meas_date logic, meta info uses defaults.

If info['meas_date'] is None, it will remain None during processing the above fields.

Operates in place.

New in version 0.13.0.

apply_baseline(baseline=(None, 0), *, verbose=None)[source]

Baseline correct epochs.

Parameters
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.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Returns
epochsinstance of Epochs

The baseline-corrected Epochs object.

Notes

Baseline correction can be done multiple times, but can never be reverted once the data has been loaded.

New in version 0.10.0.

Examples using apply_baseline:

apply_hilbert(picks=None, envelope=False, n_jobs=1, n_fft='auto', verbose=None)[source]

Compute analytic signal or envelope for a subset of channels.

Parameters
picksstr | list | 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 data channels(excluding reference MEG channels).

envelopebool

Compute the envelope signal of each channel. Default False. See Notes.

n_jobsint

The number of jobs to run in parallel (default 1). Requires the joblib package.

n_fftint | None | str

Points to use in the FFT for Hilbert transformation. The signal will be padded with zeros before computing Hilbert, then cut back to original length. If None, n == self.n_times. If ‘auto’, the next highest fast FFT length will be use.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Returns
selfinstance of Raw, Epochs, or Evoked

The raw object with transformed data.

Notes

Parameters

If envelope=False, the analytic signal for the channels defined in picks is computed and the data of the Raw object is converted to a complex representation (the analytic signal is complex valued).

If envelope=True, the absolute value of the analytic signal for the channels defined in picks is computed, resulting in the envelope signal.

If envelope=False, more memory is required since the original raw data as well as the analytic signal have temporarily to be stored in memory. If n_jobs > 1, more memory is required as len(picks) * n_times additional time points need to be temporaily stored in memory.

Also note that the n_fft parameter will allow you to pad the signal with zeros before performing the Hilbert transform. This padding is cut off, but it may result in a slightly different result (particularly around the edges). Use at your own risk.

Analytic signal

The analytic signal “x_a(t)” of “x(t)” is:

x_a = F^{-1}(F(x) 2U) = x + i y

where “F” is the Fourier transform, “U” the unit step function, and “y” the Hilbert transform of “x”. One usage of the analytic signal is the computation of the envelope signal, which is given by “e(t) = abs(x_a(t))”. Due to the linearity of Hilbert transform and the MNE inverse solution, the enevlope in source space can be obtained by computing the analytic signal in sensor space, applying the MNE inverse, and computing the envelope in source space.

Examples using apply_hilbert:

apply_proj(verbose=None)[source]

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

Parameters
verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Returns
selfinstance of Raw | Epochs | Evoked

The instance.

Notes

Once the projectors have been applied, they can no longer be removed. It is usually not recommended to apply the projectors at too early stages, as they are applied automatically later on (e.g. when computing inverse solutions). Hint: using the copy method individual projection vectors can be tested without affecting the original data. With evoked data, consider the following example:

projs_a = mne.read_proj('proj_a.fif')
projs_b = mne.read_proj('proj_b.fif')
# add the first, copy, apply and see ...
evoked.add_proj(a).copy().apply_proj().plot()
# add the second, copy, apply and see ...
evoked.add_proj(b).copy().apply_proj().plot()
# drop the first and see again
evoked.copy().del_proj(0).apply_proj().plot()
evoked.apply_proj()  # finally keep both

Examples using apply_proj:

as_type(ch_type='grad', mode='fast')[source]

Compute virtual epochs using interpolated fields.

Warning

Using virtual epochs to compute inverse can yield unexpected results. The virtual channels have '_v' appended at the end of the names to emphasize that the data contained in them are interpolated.

Parameters
ch_typestr

The destination channel type. It can be ‘mag’ or ‘grad’.

modestr

Either 'accurate' or 'fast', determines the quality of the Legendre polynomial expansion used. 'fast' should be sufficient for most applications.

Returns
epochsinstance of mne.EpochsArray

The transformed epochs object containing only virtual channels.

Notes

This method returns a copy and does not modify the data it operates on. It also returns an EpochsArray instance.

New in version 0.20.0.

average(picks=None, method='mean')[source]

Compute an average over epochs.

Parameters
picksstr | list | 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 data channels.

methodstr | callable()

How to combine the data. If “mean”/”median”, the mean/median are returned. Otherwise, must be a callable which, when passed an array of shape (n_epochs, n_channels, n_time) returns an array of shape (n_channels, n_time). Note that due to file type limitations, the kind for all these will be “average”.

Returns
evokedinstance of Evoked | dict of Evoked

The averaged epochs.

Notes

Computes an average of all epochs in the instance, even if they correspond to different conditions. To average by condition, do epochs[condition].average() for each condition separately.

When picks is None and epochs contain only ICA channels, no channels are selected, resulting in an error. This is because ICA channels are not considered data channels (they are of misc type) and only data channels are selected when picks is None.

The method parameter allows e.g. robust averaging. For example, one could do:

>>> from scipy.stats import trim_mean  
>>> trim = lambda x: trim_mean(x, 0.1, axis=0)  
>>> epochs.average(method=trim)  

This would compute the trimmed mean.

Examples using average:

property ch_names

Channel names.

property compensation_grade

The current gradient compensation grade.

copy()[source]

Return copy of Epochs instance.

Returns
epochsinstance of Epochs

A copy of the object.

Examples using copy:

crop(tmin=None, tmax=None, include_tmax=True, verbose=None)[source]

Crop a time interval from the epochs.

Parameters
tminfloat | None

Start time of selection in seconds.

tmaxfloat | None

End time of selection in seconds.

include_tmaxbool

If True (default), include tmax. If False, exclude tmax (similar to how Python indexing typically works).

New in version 0.19.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Returns
epochsinstance of Epochs

The cropped epochs object, modified in-place.

Notes

Unlike Python slices, MNE time intervals by default include both their end points; crop(tmin, tmax) returns the interval tmin <= t <= tmax. Pass include_tmax=False to specify the half-open interval tmin <= t < tmax instead.

decimate(decim, offset=0, verbose=None)[source]

Decimate the epochs.

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.

offsetint

Apply an offset to where the decimation starts relative to the sample corresponding to t=0. The offset is in samples at the current sampling rate.

New in version 0.12.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Returns
epochsinstance of Epochs

The decimated Epochs object.

Notes

For historical reasons, decim / “decimation” refers to simply subselecting samples from a given signal. This contrasts with the broader signal processing literature, where decimation is defined as (quoting 1, p. 172; which cites 2):

“… a general system for downsampling by a factor of M is the one shown in Figure 4.23. Such a system is called a decimator, and downsampling by lowpass filtering followed by compression [i.e, subselecting samples] has been termed decimation (Crochiere and Rabiner, 1983).”

Hence “decimation” in MNE is what is considered “compression” in the signal processing community.

Decimation can be done multiple times. For example, inst.decimate(2).decimate(2) will be the same as inst.decimate(4).

If decim is 1, this method does not copy the underlying data.

New in version 0.10.0.

References

1

Alan V. Oppenheim, Ronald W. Schafer, and John R. Buck. Discrete-Time Signal Processing. Prentice Hall, Upper Saddle River, NJ, 2 edition edition, January 1999. ISBN 978-0-13-754920-7.

2

Ronald E. Crochiere and Lawrence R. Rabiner. Multirate Digital Signal Processing. Pearson, Englewood Cliffs, NJ, 1 edition edition, December 1983. ISBN 978-0-13-605162-6.

del_proj(idx='all')[source]

Remove SSP projection vector.

Note

The projection vector can only be removed if it is inactive (has not been applied to the data).

Parameters
idxint | list of int | str

Index of the projector to remove. Can also be “all” (default) to remove all projectors.

Returns
selfinstance of Raw | Epochs | Evoked

The instance.

drop(indices, reason='USER', verbose=None)[source]

Drop epochs based on indices or boolean mask.

Note

The indices refer to the current set of undropped epochs rather than the complete set of dropped and undropped epochs. They are therefore not necessarily consistent with any external indices (e.g., behavioral logs). To drop epochs based on external criteria, do not use the preload=True flag when constructing an Epochs object, and call this method before calling the mne.Epochs.drop_bad() or mne.Epochs.load_data() methods.

Parameters
indicesarray of int or bool

Set epochs to remove by specifying indices to remove or a boolean mask to apply (where True values get removed). Events are correspondingly modified.

reasonstr

Reason for dropping the epochs (‘ECG’, ‘timeout’, ‘blink’ etc). Default: ‘USER’.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Returns
epochsinstance of Epochs

The epochs with indices dropped. Operates in-place.

drop_bad(reject='existing', flat='existing', verbose=None)[source]

Drop bad epochs without retaining the epochs data.

Should be used before slicing operations.

Warning

This operation is slow since all epochs have to be read from disk. To avoid reading epochs from disk multiple times, use mne.Epochs.load_data().

Parameters
rejectdict | str | None

Rejection parameters based on peak-to-peak amplitude. Valid keys are ‘grad’ | ‘mag’ | ‘eeg’ | ‘eog’ | ‘ecg’. If reject is None then no rejection is done. If ‘existing’, then the rejection parameters set at instantiation are used.

flatdict | str | None

Rejection parameters based on flatness of signal. Valid keys are ‘grad’ | ‘mag’ | ‘eeg’ | ‘eog’ | ‘ecg’, and values are floats that set the minimum acceptable peak-to-peak amplitude. If flat is None then no rejection is done. If ‘existing’, then the flat parameters set at instantiation are used.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Returns
epochsinstance of Epochs

The epochs with bad epochs dropped. Operates in-place.

Notes

Dropping bad epochs can be done multiple times with different reject and flat parameters. However, once an epoch is dropped, it is dropped forever, so if more lenient thresholds may subsequently be applied, epochs.copy should be used.

Examples using drop_bad:

drop_channels(ch_names)[source]

Drop channel(s).

Parameters
ch_namesiterable or str

Iterable (e.g. list) of channel name(s) or channel name to remove.

Returns
instinstance of Raw, Epochs, or Evoked

The modified instance.

Notes

New in version 0.9.0.

Examples using drop_channels:

drop_log_stats(ignore=('IGNORED'))[source]

Compute the channel stats based on a drop_log from Epochs.

Parameters
ignorelist

The drop reasons to ignore.

Returns
percfloat

Total percentage of epochs dropped.

See also

plot_drop_log
equalize_event_counts(event_ids, method='mintime')[source]

Equalize the number of trials in each condition.

It tries to make the remaining epochs occurring as close as possible in time. This method works based on the idea that if there happened to be some time-varying (like on the scale of minutes) noise characteristics during a recording, they could be compensated for (to some extent) in the equalization process. This method thus seeks to reduce any of those effects by minimizing the differences in the times of the events in the two sets of epochs. For example, if one had event times [1, 2, 3, 4, 120, 121] and the other one had [3.5, 4.5, 120.5, 121.5], it would remove events at times [1, 2] in the first epochs and not [20, 21].

Parameters
event_idslist

The event types to equalize. Each entry in the list can either be a str (single event) or a list of str. In the case where one of the entries is a list of str, event_ids in that list will be grouped together before equalizing trial counts across conditions. In the case where partial matching is used (using ‘/’ in event_ids), event_ids will be matched according to the provided tags, that is, processing works as if the event_ids matched by the provided tags had been supplied instead. The event_ids must identify nonoverlapping subsets of the epochs.

methodstr

If ‘truncate’, events will be truncated from the end of each event list. If ‘mintime’, timing differences between each event list will be minimized.

Returns
epochsinstance of Epochs

The modified Epochs instance.

indicesarray of int

Indices from the original events list that were dropped.

Notes

For example (if epochs.event_id was {‘Left’: 1, ‘Right’: 2, ‘Nonspatial’:3}:

epochs.equalize_event_counts([[‘Left’, ‘Right’], ‘Nonspatial’])

would equalize the number of trials in the ‘Nonspatial’ condition with the total number of trials in the ‘Left’ and ‘Right’ conditions.

If multiple indices are provided (e.g. ‘Left’ and ‘Right’ in the example above), it is not guaranteed that after equalization, the conditions will contribute evenly. E.g., it is possible to end up with 70 ‘Nonspatial’ trials, 69 ‘Left’ and 1 ‘Right’.

Examples using equalize_event_counts:

property filename

The filename.

filter(l_freq, h_freq, picks=None, filter_length='auto', l_trans_bandwidth='auto', h_trans_bandwidth='auto', n_jobs=1, method='fir', iir_params=None, phase='zero', fir_window='hamming', fir_design='firwin', skip_by_annotation=('edge', 'bad_acq_skip'), pad='edge', verbose=None)[source]

Filter a subset of channels.

Parameters
l_freqfloat | None

For FIR filters, the lower pass-band edge; for IIR filters, the lower cutoff frequency. If None the data are only low-passed.

h_freqfloat | None

For FIR filters, the upper pass-band edge; for IIR filters, the upper cutoff frequency. If None the data are only high-passed.

picksstr | list | 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 data channels.

filter_lengthstr | int

Length of the FIR filter to use (if applicable):

  • ‘auto’ (default): The filter length is chosen based on the size of the transition regions (6.6 times the reciprocal of the shortest transition band for fir_window=’hamming’ and fir_design=”firwin2”, and half that for “firwin”).

  • str: A human-readable time in units of “s” or “ms” (e.g., “10s” or “5500ms”) will be converted to that number of samples if phase="zero", or the shortest power-of-two length at least that duration for phase="zero-double".

  • int: Specified length in samples. For fir_design=”firwin”, this should not be used.

l_trans_bandwidthfloat | str

Width of the transition band at the low cut-off frequency in Hz (high pass or cutoff 1 in bandpass). Can be “auto” (default) to use a multiple of l_freq:

min(max(l_freq * 0.25, 2), l_freq)

Only used for method='fir'.

h_trans_bandwidthfloat | str

Width of the transition band at the high cut-off frequency in Hz (low pass or cutoff 2 in bandpass). Can be “auto” (default in 0.14) to use a multiple of h_freq:

min(max(h_freq * 0.25, 2.), info['sfreq'] / 2. - h_freq)

Only used for method='fir'.

n_jobsint | str

Number of jobs to run in parallel. Can be ‘cuda’ if cupy is installed properly and method=’fir’.

methodstr

‘fir’ will use overlap-add FIR filtering, ‘iir’ will use IIR forward-backward filtering (via filtfilt).

iir_paramsdict | None

Dictionary of parameters to use for IIR filtering. If iir_params is None and method=”iir”, 4th order Butterworth will be used. For more information, see mne.filter.construct_iir_filter().

phasestr

Phase of the filter, only used if method='fir'. Symmetric linear-phase FIR filters are constructed, and if phase='zero' (default), the delay of this filter is compensated for, making it non-causal. If phase=='zero-double', then this filter is applied twice, once forward, and once backward (also making it non-causal). If ‘minimum’, then a minimum-phase filter will be constricted and applied, which is causal but has weaker stop-band suppression.

New in version 0.13.

fir_windowstr

The window to use in FIR design, can be “hamming” (default), “hann” (default in 0.13), or “blackman”.

New in version 0.15.

fir_designstr

Can be “firwin” (default) to use scipy.signal.firwin(), or “firwin2” to use scipy.signal.firwin2(). “firwin” uses a time-domain design technique that generally gives improved attenuation using fewer samples than “firwin2”.

New in version 0.15.

skip_by_annotationstr | list of str

If a string (or list of str), any annotation segment that begins with the given string will not be included in filtering, and segments on either side of the given excluded annotated segment will be filtered separately (i.e., as independent signals). The default (('edge', 'bad_acq_skip') will separately filter any segments that were concatenated by mne.concatenate_raws() or mne.io.Raw.append(), or separated during acquisition. To disable, provide an empty list. Only used if inst is raw.

New in version 0.16..

padstr

The type of padding to use. Supports all numpy.pad() mode options. Can also be “reflect_limited”, which pads with a reflected version of each vector mirrored on the first and last values of the vector, followed by zeros. Only used for method='fir'.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Returns
instinstance of Epochs, Evoked, or Raw

The filtered data.

Notes

Applies a zero-phase low-pass, high-pass, band-pass, or band-stop filter to the channels selected by picks. The data are modified inplace.

The object has to have the data loaded e.g. with preload=True or self.load_data().

l_freq and h_freq are the frequencies below which and above which, respectively, to filter out of the data. Thus the uses are:

  • l_freq < h_freq: band-pass filter

  • l_freq > h_freq: band-stop filter

  • l_freq is not None and h_freq is None: high-pass filter

  • l_freq is None and h_freq is not None: low-pass filter

self.info['lowpass'] and self.info['highpass'] are only updated with picks=None.

Note

If n_jobs > 1, more memory is required as len(picks) * n_times additional time points need to be temporaily stored in memory.

For more information, see the tutorials Background information on filtering and Filtering and resampling data and mne.filter.create_filter().

New in version 0.15.

Examples using filter:

get_channel_types(picks=None, unique=False, only_data_chs=False)[source]

Get a list of channel type for each channel.

Parameters
picksstr | list | 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.

uniquebool

Whether to return only unique channel types. Default is False.

only_data_chsbool

Whether to ignore non-data channels. Default is False.

Returns
channel_typeslist

The channel types.

Examples using get_channel_types:

get_data(picks=None, item=None)[source]

Get all epochs as a 3D array.

Parameters
picksstr | list | 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.

itemslice | array_like | str | list | None

The items to get. See mne.Epochs.__getitem__() for a description of valid options. This can be substantially faster for obtaining an ndarray than __getitem__() for repeated access on large Epochs objects. None (default) is an alias for slice(None).

New in version 0.20.

Returns
dataarray of shape (n_epochs, n_channels, n_times)

A view on epochs data.

Examples using get_data:

get_montage()[source]

Get a DigMontage from instance.

Returns
montageNone | str | DigMontage

A montage containing channel positions. If str or DigMontage is specified, the channel info will be updated with the channel positions. Default is None. See also the documentation of mne.channels.DigMontage for more information.

interpolate_bads(reset_bads=True, mode='accurate', origin='auto', method=None, verbose=None)[source]

Interpolate bad MEG and EEG channels.

Operates in place.

Parameters
reset_badsbool

If True, remove the bads from info.

modestr

Either 'accurate' or 'fast', determines the quality of the Legendre polynomial expansion used for interpolation of channels using the minimum-norm method.

originarray_like, shape (3,) | str

Origin of the sphere in the head coordinate frame and in meters. Can be 'auto' (default), which means a head-digitization-based origin fit.

New in version 0.17.

methoddict

Method to use for each channel type. Currently only the key “eeg” has multiple options:

  • "spline" (default)

    Use spherical spline interpolation.

  • "MNE"

    Use minimum-norm projection to a sphere and back. This is the method used for MEG channels.

The value for “meg” is “MNE”, and the value for “fnirs” is “nearest”. The default (None) is thus an alias for:

method=dict(meg="MNE", eeg="spline", fnirs="nearest")

New in version 0.21.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Returns
instinstance of Raw, Epochs, or Evoked

The modified instance.

Notes

New in version 0.9.0.

Examples using interpolate_bads:

iter_evoked(copy=False)[source]

Iterate over epochs as a sequence of Evoked objects.

The Evoked objects yielded will each contain a single epoch (i.e., no averaging is performed).

This method resets the object iteration state to the first epoch.

Parameters
copybool

If False copies of data and measurement info will be omitted to save time.

load_data()[source]

Load the data if not already preloaded.

Returns
epochsinstance of Epochs

The epochs object.

Notes

This function operates in-place.

New in version 0.10.0.

Examples using load_data:

property metadata

Get the metadata.

next(return_event_id=False)[source]

Iterate over epoch data.

Parameters
return_event_idbool

If True, return both the epoch data and an event_id.

Returns
epocharray of shape (n_channels, n_times)

The epoch data.

event_idint

The event id. Only returned if return_event_id is True.

pick(picks, exclude=())[source]

Pick a subset of channels.

Parameters
picksstr | list | 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.

excludelist | str

Set of channels to exclude, only used when picking based on types (e.g., exclude=”bads” when picks=”meg”).

Returns
instinstance of Raw, Epochs, or Evoked

The modified instance.

pick_channels(ch_names, ordered=False)[source]

Pick some channels.

Parameters
ch_nameslist

The list of channels to select.

orderedbool

If True (default False), ensure that the order of the channels in the modified instance matches the order of ch_names.

New in version 0.20.0.

Returns
instinstance of Raw, Epochs, or Evoked

The modified instance.

Notes

The channel names given are assumed to be a set, i.e. the order does not matter. The original order of the channels is preserved. You can use reorder_channels to set channel order if necessary.

New in version 0.9.0.

Examples using pick_channels:

pick_types(meg=None, eeg=False, stim=False, eog=False, ecg=False, emg=False, ref_meg='auto', misc=False, resp=False, chpi=False, exci=False, ias=False, syst=False, seeg=False, dipole=False, gof=False, bio=False, ecog=False, fnirs=False, csd=False, include=(), exclude='bads', selection=None, verbose=None)[source]

Pick some channels by type and names.

Parameters
megbool | str

If True include MEG channels. If string it can be ‘mag’, ‘grad’, ‘planar1’ or ‘planar2’ to select only magnetometers, all gradiometers, or a specific type of gradiometer.

eegbool

If True include EEG channels.

stimbool

If True include stimulus channels.

eogbool

If True include EOG channels.

ecgbool

If True include ECG channels.

emgbool

If True include EMG channels.

ref_megbool | str

If True include CTF / 4D reference channels. If ‘auto’, reference channels are included if compensations are present and meg is not False. Can also be the string options for the meg parameter.

miscbool

If True include miscellaneous analog channels.

respbool

If True include response-trigger channel. For some MEG systems this is separate from the stim channel.

chpibool

If True include continuous HPI coil channels.

excibool

Flux excitation channel used to be a stimulus channel.

iasbool

Internal Active Shielding data (maybe on Triux only).

systbool

System status channel information (on Triux systems only).

seegbool

Stereotactic EEG channels.

dipolebool

Dipole time course channels.

gofbool

Dipole goodness of fit channels.

biobool

Bio channels.

ecogbool

Electrocorticography channels.

fnirsbool | str

Functional near-infrared spectroscopy channels. If True include all fNIRS channels. If False (default) include none. If string it can be ‘hbo’ (to include channels measuring oxyhemoglobin) or ‘hbr’ (to include channels measuring deoxyhemoglobin).

csdbool

EEG-CSD channels.

includelist of str

List of additional channels to include. If empty do not include any.

excludelist of str | str

List of channels to exclude. If ‘bads’ (default), exclude channels in info['bads'].

selectionlist of str

Restrict sensor channels (MEG, EEG) to this list of channel names.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Returns
instinstance of Raw, Epochs, or Evoked

The modified instance.

See also

pick_channels

Notes

New in version 0.9.0.

Examples using pick_types:

plot(picks=None, scalings=None, n_epochs=20, n_channels=20, title=None, events=None, event_colors=None, order=None, show=True, block=False, decim='auto', noise_cov=None, butterfly=False, show_scrollbars=True, epoch_colors=None, event_id=None)[source]

Visualize epochs.

Bad epochs can be marked with a left click on top of the epoch. Bad channels can be selected by clicking the channel name on the left side of the main axes. Calling this function drops all the selected bad epochs as well as bad epochs marked beforehand with rejection parameters.

Parameters
picksstr | list | 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 good data channels.

scalingsdict | ‘auto’ | None

Scaling factors for the traces. If any fields in scalings are ‘auto’, the scaling factor is set to match the 99.5th percentile of a subset of the corresponding data. If scalings == ‘auto’, all scalings fields are set to ‘auto’. If any fields are ‘auto’ and data is not preloaded, a subset of epochs up to 100mb will be loaded. If None, defaults to:

dict(mag=1e-12, grad=4e-11, eeg=20e-6, eog=150e-6, ecg=5e-4,
     emg=1e-3, ref_meg=1e-12, misc=1e-3, stim=1, resp=1, chpi=1e-4,
     whitened=10.)
n_epochsint

The number of epochs per view. Defaults to 20.

n_channelsint

The number of channels per view. Defaults to 20.

titlestr | None

The title of the window. If None, epochs name will be displayed. Defaults to None.

eventsNone, array, shape (n_events, 3)

Events to show with vertical bars. If events are provided, the epoch numbers are not shown to prevent overlap. You can toggle epoch numbering through options (press ‘o’ key). You can use plot_events as a legend for the colors. By default, the coloring scheme is the same.

Warning

If the epochs have been resampled, the events no longer align with the data.

New in version 0.14.0.

event_colorsNone, dict

Dictionary of event_id value and its associated color. If None, colors are automatically drawn from a default list (cycled through if number of events longer than list of default colors). Uses the same coloring scheme as plot_events.

New in version 0.14.0.

orderarray of str | None

Order in which to plot channel types.

New in version 0.18.0.

showbool

Show figure if True. Defaults to True.

blockbool

Whether to halt program execution until the figure is closed. Useful for rejecting bad trials on the fly by clicking on an epoch. Defaults to False.

decimint | ‘auto’

Amount to decimate the data during display for speed purposes. You should only decimate if the data are sufficiently low-passed, otherwise aliasing can occur. The ‘auto’ mode (default) uses the decimation that results in a sampling rate at least three times larger than info['lowpass'] (e.g., a 40 Hz lowpass will result in at least a 120 Hz displayed sample rate).

New in version 0.15.0.

noise_covinstance of Covariance | str | None

Noise covariance used to whiten the data while plotting. Whitened data channels are scaled by scalings['whitened'], and their channel names are shown in italic. Can be a string to load a covariance from disk. See also mne.Evoked.plot_white() for additional inspection of noise covariance properties when whitening evoked data. For data processed with SSS, the effective dependence between magnetometers and gradiometers may introduce differences in scaling, consider using mne.Evoked.plot_white().

New in version 0.16.0.

butterflybool

Whether to directly call the butterfly view.

New in version 0.18.0.

show_scrollbarsbool

Whether to show scrollbars when the plot is initialized. Can be toggled after initialization by pressing z (“zen mode”) while the plot window is focused. Default is True.

New in version 0.19.0.

epoch_colorslist of (n_epochs) list (of n_channels) | None

Colors to use for individual epochs. If None, use default colors.

event_iddict | None

Dictionary of event labels (e.g. ‘aud_l’) as keys and associated event integers as values. Useful when events contains event numbers not present in epochs.event_id (e.g., because of event subselection). Values in event_id will take precedence over those in epochs.event_id when there are overlapping keys.

New in version 0.20.

Returns
figinstance of matplotlib.figure.Figure

The figure.

Notes

The arrow keys (up/down/left/right) can be used to navigate between channels and epochs and the scaling can be adjusted with - and + (or =) keys, but this depends on the backend matplotlib is configured to use (e.g., mpl.use(TkAgg) should work). Full screen mode can be toggled with f11 key. The amount of epochs and channels per view can be adjusted with home/end and page down/page up keys. These can also be set through options dialog by pressing o key. h key plots a histogram of peak-to-peak values along with the used rejection thresholds. Butterfly plot can be toggled with b key. Right mouse click adds a vertical line to the plot. Click ‘help’ button at bottom left corner of the plotter to view all the options.

New in version 0.10.0.

Examples using plot:

plot_drop_log(threshold=0, n_max_plot=20, subject='Unknown', color=(0.9, 0.9, 0.9), width=0.8, ignore=('IGNORED'), show=True)[source]

Show the channel stats based on a drop_log from Epochs.

Parameters
thresholdfloat

The percentage threshold to use to decide whether or not to plot. Default is zero (always plot).

n_max_plotint

Maximum number of channels to show stats for.

subjectstr

The subject name to use in the title of the plot.

colortuple | str

Color to use for the bars.

widthfloat

Width of the bars.

ignorelist

The drop reasons to ignore.

showbool

Show figure if True.

Returns
figinstance of matplotlib.figure.Figure

The figure.

Examples using plot_drop_log:

plot_image(picks=None, sigma=0.0, vmin=None, vmax=None, colorbar=True, order=None, show=True, units=None, scalings=None, cmap=None, fig=None, axes=None, overlay_times=None, combine=None, group_by=None, evoked=True, ts_args=None, title=None, clear=False)[source]

Plot Event Related Potential / Fields image.

Parameters
picksstr | list | 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 good data channels. picks interacts with group_by and combine to determine the number of figures generated; see Notes.

sigmafloat

The standard deviation of a Gaussian smoothing window applied along the epochs axis of the image. If 0, no smoothing is applied. Defaults to 0.

vminNone | float | callable()

The min value in the image (and the ER[P/F]). The unit is µV for EEG channels, fT for magnetometers and fT/cm for gradiometers. If vmin is None and multiple plots are returned, the limit is equalized within channel types. Hint: to specify the lower limit of the data, use vmin=lambda data: data.min().

vmaxNone | float | callable()

The max value in the image (and the ER[P/F]). The unit is µV for EEG channels, fT for magnetometers and fT/cm for gradiometers. If vmin is None and multiple plots are returned, the limit is equalized within channel types.

colorbarbool

Display or not a colorbar.

orderNone | array of int | callable()

If not None, order is used to reorder the epochs along the y-axis of the image. If it is an array of int, its length should match the number of good epochs. If it is a callable it should accept two positional parameters (times and data, where data.shape == (len(good_epochs), len(times))) and return an array of indices that will sort data along its first axis.

showbool

Show figure if True.

unitsdict | None

The units of the channel types used for axes labels. If None, defaults to units=dict(eeg='µV', grad='fT/cm', mag='fT').

scalingsdict | None

The scalings of the channel types to be applied for plotting. If None, defaults to scalings=dict(eeg=1e6, grad=1e13, mag=1e15, eog=1e6).

cmapNone | colormap | (colormap, bool) | ‘interactive’

Colormap. If tuple, the first value indicates the colormap to use and the second value is a boolean defining interactivity. In interactive mode the colors are adjustable by clicking and dragging the colorbar with left and right mouse button. Left mouse button moves the scale up and down and right mouse button adjusts the range. Hitting space bar resets the scale. Up and down arrows can be used to change the colormap. If ‘interactive’, translates to (‘RdBu_r’, True). If None, “RdBu_r” is used, unless the data is all positive, in which case “Reds” is used.

figFigure | None

Figure instance to draw the image to. Figure must contain the correct number of axes for drawing the epochs image, the evoked response, and a colorbar (depending on values of evoked and colorbar). If None a new figure is created. Defaults to None.

axeslist of Axes | dict of list of Axes | None

List of Axes objects in which to draw the image, evoked response, and colorbar (in that order). Length of list must be 1, 2, or 3 (depending on values of colorbar and evoked parameters). If a dict, each entry must be a list of Axes objects with the same constraints as above. If both axes and group_by are dicts, their keys must match. Providing non-None values for both fig and axes results in an error. Defaults to None.

overlay_timesarray_like, shape (n_epochs,) | None

Times (in seconds) at which to draw a line on the corresponding row of the image (e.g., a reaction time associated with each epoch). Note that overlay_times should be ordered to correspond with the Epochs object (i.e., overlay_times[0] corresponds to epochs[0], etc).

combineNone | str | callable()

How to combine information across channels. If a str, must be one of ‘mean’, ‘median’, ‘std’ (standard deviation) or ‘gfp’ (global field power). If callable, the callable must accept one positional input (data of shape (n_epochs, n_channels, n_times)) and return an array of shape (n_epochs, n_times). For example:

combine = lambda data: np.median(data, axis=1)

If combine is None, channels are combined by computing GFP, unless group_by is also None and picks is a list of specific channels (not channel types), in which case no combining is performed and each channel gets its own figure. See Notes for further details. Defaults to None.

group_byNone | dict

Specifies which channels are aggregated into a single figure, with aggregation method determined by the combine parameter. If not None, one Figure is made per dict entry; the dict key will be used as the figure title and the dict values must be lists of picks (either channel names or integer indices of epochs.ch_names). For example:

group_by=dict(Left_ROI=[1, 2, 3, 4], Right_ROI=[5, 6, 7, 8])

Note that within a dict entry all channels must have the same type. group_by interacts with picks and combine to determine the number of figures generated; see Notes. Defaults to None.

evokedbool

Draw the ER[P/F] below the image or not.

ts_argsNone | dict

Arguments passed to a call to plot_compare_evokeds to style the evoked plot below the image. Defaults to an empty dictionary, meaning plot_compare_evokeds will be called with default parameters.

titleNone | str

If str, will be plotted as figure title. Otherwise, the title will indicate channel(s) or channel type being plotted. Defaults to None.

clearbool

Whether to clear the axes before plotting (if fig or axes are provided). Defaults to False.

Returns
figslist of Figure

One figure per channel, channel type, or group, depending on values of picks, group_by, and combine. See Notes.

Notes

You can control how channels are aggregated into one figure or plotted in separate figures through a combination of the picks, group_by, and combine parameters. If group_by is a dict, the result is one Figure per dictionary key (for any valid values of picks and combine). If group_by is None, the number and content of the figures generated depends on the values of picks and combine, as summarized in this table:

group_by

picks

combine

result

dict

None, int, list of int, ch_name, list of ch_names, ch_type, list of ch_types

None, string, or callable

1 figure per dict key

None

None, ch_type, list of ch_types

None, string, or callable

1 figure per ch_type

int, ch_name, list of int, list of ch_names

None

1 figure per pick

string or callable

1 figure

Examples using plot_image:

plot_projs_topomap(ch_type=None, cmap=None, sensors=True, colorbar=False, res=64, size=1, show=True, outlines='head', contours=6, image_interp='bilinear', axes=None, vlim=(None, None), sphere=None, extrapolate='auto', border='mean')[source]

Plot SSP vector.

Parameters
ch_type‘mag’ | ‘grad’ | ‘planar1’ | ‘planar2’ | ‘eeg’ | None | list

The channel type to plot. For ‘grad’, the gradiometers are collec- ted in pairs and the RMS for each pair is plotted. If None (default), it will return all channel types present. If a list of ch_types is provided, it will return multiple figures.

cmapmatplotlib colormap | (colormap, bool) | ‘interactive’ | None

Colormap to use. If tuple, the first value indicates the colormap to use and the second value is a boolean defining interactivity. In interactive mode (only works if colorbar=True) the colors are adjustable by clicking and dragging the colorbar with left and right mouse button. Left mouse button moves the scale up and down and right mouse button adjusts the range. Hitting space bar resets the range. Up and down arrows can be used to change the colormap. If None (default), ‘Reds’ is used for all positive data, otherwise defaults to ‘RdBu_r’. If ‘interactive’, translates to (None, True).

sensorsbool | str

Add markers for sensor locations to the plot. Accepts matplotlib plot format string (e.g., ‘r+’ for red plusses). If True, a circle will be used (via .add_artist). Defaults to True.

colorbarbool

Plot a colorbar.

resint

The resolution of the topomap image (n pixels along each side).

sizescalar

Side length of the topomaps in inches (only applies when plotting multiple topomaps at a time).

showbool

Show figure if True.

outlines‘head’ | ‘skirt’ | dict | None

The outlines to be drawn. If ‘head’, the default head scheme will be drawn. If ‘skirt’ the head scheme will be drawn, but sensors are allowed to be plotted outside of the head circle. If dict, each key refers to a tuple of x and y positions, the values in ‘mask_pos’ will serve as image mask. Alternatively, a matplotlib patch object can be passed for advanced masking options, either directly or as a function that returns patches (required for multi-axis plots). If None, nothing will be drawn. Defaults to ‘head’.

contoursint | array of float

The number of contour lines to draw. If 0, no contours will be drawn. When an integer, matplotlib ticker locator is used to find suitable values for the contour thresholds (may sometimes be inaccurate, use array for accuracy). If an array, the values represent the levels for the contours. Defaults to 6.

image_interpstr

The image interpolation to be used. All matplotlib options are accepted.

axesinstance of Axes | list | None

The axes to plot to. If list, the list must be a list of Axes of the same length as the number of projectors. If instance of Axes, there must be only one projector. Defaults to None.

vlimtuple of length 2 | ‘joint’

Colormap limits to use. If tuple, specifies the lower and upper bounds of the colormap (in that order); providing None for either of these will set the corresponding boundary at the min/max of the data (separately for each projector). The keyword value 'joint' will compute the colormap limits jointly across all provided projectors of the same channel type, using the min/max of the projector data. If vlim is 'joint', info must not be None. Defaults to (None, None).

spherefloat | array_like | str | None

The sphere parameters to use for the cartoon head. Can be array-like of shape (4,) to give the X/Y/Z origin and radius in meters, or a single float to give the radius (origin assumed 0, 0, 0). Can also be a spherical ConductorModel, which will use the origin and radius. Can be “auto” to use a digitization-based fit. Can also be None (default) to use ‘auto’ when enough extra digitization points are available, and 0.095 otherwise. Currently the head radius does not affect plotting.

New in version 0.20.

extrapolatestr

Options:

  • 'box'

    Extrapolate to four points placed to form a square encompassing all data points, where each side of the square is three times the range of the data in the respective dimension.

  • 'local' (default)

    Extrapolate only to nearby points (approximately to points closer than median inter-electrode distance). This will also set the mask to be polygonal based on the convex hull of the sensors.

  • 'head'

    Extrapolate out to the edges of the clipping circle. This will be on the head circle when the sensors are contained within the head circle, but it can extend beyond the head when sensors are plotted outside the head circle.

    Changed in version 0.21:
  • The default was changed to 'local'

  • 'local' was changed to use a convex hull mask

  • 'head' was changed to extrapolate out to the clipping circle.

New in version 0.20.

borderfloat | ‘mean’

Value to extrapolate to on the topomap borders. If 'mean' (default), then each extrapolated point has the average value of its neighbours.

New in version 0.20.

Returns
figinstance of Figure

Figure distributing one image per channel across sensor topography.

Examples using plot_projs_topomap:

plot_psd(fmin=0, fmax=inf, tmin=None, tmax=None, proj=False, bandwidth=None, adaptive=False, low_bias=True, normalization='length', picks=None, ax=None, color='black', xscale='linear', area_mode='std', area_alpha=0.33, dB=True, estimate='auto', show=True, n_jobs=1, average=False, line_alpha=None, spatial_colors=True, sphere=None, verbose=None)[source]

Plot the power spectral density across channels.

Different channel types are drawn in sub-plots. When the data have been processed with a bandpass, lowpass or highpass filter, dashed lines indicate the boundaries of the filter (–). The line noise frequency is also indicated with a dashed line (-.).

Parameters
fminfloat

Start frequency to consider.

fmaxfloat

End frequency to consider.

tminfloat | None

Start time to consider.

tmaxfloat | None

End time to consider.

projbool

Apply projection.

bandwidthfloat

The bandwidth of the multi taper windowing function in Hz. The default value is a window half-bandwidth of 4.

adaptivebool

Use adaptive weights to combine the tapered spectra into PSD (slow, use n_jobs >> 1 to speed up computation).

low_biasbool

Only use tapers with more than 90% spectral concentration within bandwidth.

normalizationstr

Either “full” or “length” (default). If “full”, the PSD will be normalized by the sampling rate as well as the length of the signal (as in nitime).

picksstr | list | 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 good data channels Cannot be None if ax is supplied.If both picks and ax are None separate subplots will be created for each standard channel type (mag, grad, and eeg).

axinstance of Axes | None

Axes to plot into. If None, axes will be created.

colorstr | tuple

A matplotlib-compatible color to use. Has no effect when spatial_colors=True.

xscalestr

Can be ‘linear’ (default) or ‘log’.

area_modestr | None

Mode for plotting area. If ‘std’, the mean +/- 1 STD (across channels) will be plotted. If ‘range’, the min and max (across channels) will be plotted. Bad channels will be excluded from these calculations. If None, no area will be plotted. If average=False, no area is plotted.

area_alphafloat

Alpha for the area.

dBbool

Plot Power Spectral Density (PSD), in units (amplitude**2/Hz (dB)) if dB=True, and estimate='power' or estimate='auto'. Plot PSD in units (amplitude**2/Hz) if dB=False and, estimate='power'. Plot Amplitude Spectral Density (ASD), in units (amplitude/sqrt(Hz)), if dB=False and estimate='amplitude' or estimate='auto'. Plot ASD, in units (amplitude/sqrt(Hz) (db)), if dB=True and estimate='amplitude'.

estimatestr, {‘auto’, ‘power’, ‘amplitude’}

Can be “power” for power spectral density (PSD), “amplitude” for amplitude spectrum density (ASD), or “auto” (default), which uses “power” when dB is True and “amplitude” otherwise.

showbool

Show figure if True.

n_jobsint

The number of jobs to run in parallel (default 1). Requires the joblib package.

averagebool

If False, the PSDs of all channels is displayed. No averaging is done and parameters area_mode and area_alpha are ignored. When False, it is possible to paint an area (hold left mouse button and drag) to plot a topomap.

line_alphafloat | None

Alpha for the PSD line. Can be None (default) to use 1.0 when average=True and 0.1 when average=False.

spatial_colorsbool

Whether to use spatial colors. Only used when average=False.

spherefloat | array_like | str | None

The sphere parameters to use for the cartoon head. Can be array-like of shape (4,) to give the X/Y/Z origin and radius in meters, or a single float to give the radius (origin assumed 0, 0, 0). Can also be a spherical ConductorModel, which will use the origin and radius. Can be “auto” to use a digitization-based fit. Can also be None (default) to use ‘auto’ when enough extra digitization points are available, and 0.095 otherwise. Currently the head radius does not affect plotting.

New in version 0.20.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only.

Returns
figinstance of Figure

Figure with frequency spectra of the data channels.

Examples using plot_psd:

plot_psd_topomap(bands=None, vmin=None, vmax=None, tmin=None, tmax=None, proj=False, bandwidth=None, adaptive=False, low_bias=True, normalization='length', ch_type=None, cmap=None, agg_fun=None, dB=True, n_jobs=1, normalize=False, cbar_fmt='auto', outlines='head', axes=None, show=True, sphere=None, vlim=(None, None), verbose=None)[source]

Plot the topomap of the power spectral density across epochs.

Parameters
bandslist of tuple | None

The frequencies or frequency ranges to plot. Length-2 tuples specify a single frequency and a subplot title (e.g., (6.5, 'presentation rate')); length-3 tuples specify lower and upper band edges and a subplot title. If None (the default), expands to:

bands = [(0, 4, 'Delta'), (4, 8, 'Theta'), (8, 12, 'Alpha'),
         (12, 30, 'Beta'), (30, 45, 'Gamma')]

In bands where a single frequency is provided, the topomap will reflect the single frequency bin that is closest to the provided value.

vminNone

Deprecated; use vlim instead.

vmaxNone

Deprecated; use vlim instead.

tminfloat | None

Start time to consider.

tmaxfloat | None

End time to consider.

projbool

Apply projection.

bandwidthfloat

The bandwidth of the multi taper windowing function in Hz. The default value is a window half-bandwidth of 4 Hz.

adaptivebool

Use adaptive weights to combine the tapered spectra into PSD (slow, use n_jobs >> 1 to speed up computation).

low_biasbool

Only use tapers with more than 90% spectral concentration within bandwidth.

normalizationstr

Either “full” or “length” (default). If “full”, the PSD will be normalized by the sampling rate as well as the length of the signal (as in nitime).

ch_type‘mag’ | ‘grad’ | ‘planar1’ | ‘planar2’ | ‘eeg’ | None

The channel type to plot. For ‘grad’, the gradiometers are collected in pairs and the mean for each pair is plotted. If None, then first available channel type from order given above is used. Defaults to None.

cmapmatplotlib colormap | (colormap, bool) | ‘interactive’ | None

Colormap to use. If tuple, the first value indicates the colormap to use and the second value is a boolean defining interactivity. In interactive mode the colors are adjustable by clicking and dragging the colorbar with left and right mouse button. Left mouse button moves the scale up and down and right mouse button adjusts the range. Hitting space bar resets the range. Up and down arrows can be used to change the colormap. If None, 'Reds' is used for data that is either all-positive or all-negative, and 'RdBu_r' is used otherwise. 'interactive' is equivalent to (None, True). Defaults to None.

agg_funcallable()

The function used to aggregate over frequencies. Defaults to numpy.sum() if normalize=True, else numpy.mean().

dBbool

If True, transform data to decibels (with 10 * np.log10(data)) following the application of agg_fun. Ignored if normalize=True.

n_jobsint

The number of jobs to run in parallel (default 1). Requires the joblib package.

normalizebool

If True, each band will be divided by the total power. Defaults to False.

cbar_fmtstr

Format string for the colorbar tick labels. If 'auto', is equivalent to ‘%0.3f’ if dB=False and ‘%0.1f’ if dB=True. Defaults to 'auto'.

outlines‘head’ | ‘skirt’ | dict | None

The outlines to be drawn. If ‘head’, the default head scheme will be drawn. If ‘skirt’ the head scheme will be drawn, but sensors are allowed to be plotted outside of the head circle. If dict, each key refers to a tuple of x and y positions, the values in ‘mask_pos’ will serve as image mask. Alternatively, a matplotlib patch object can be passed for advanced masking options, either directly or as a function that returns patches (required for multi-axis plots). If None, nothing will be drawn. Defaults to ‘head’.

axeslist of Axes | None

List of axes to plot consecutive topographies to. If None the axes will be created automatically. Defaults to None.

showbool

Show figure if True.

spherefloat | array_like | str | None

The sphere parameters to use for the cartoon head. Can be array-like of shape (4,) to give the X/Y/Z origin and radius in meters, or a single float to give the radius (origin assumed 0, 0, 0). Can also be a spherical ConductorModel, which will use the origin and radius. Can be “auto” to use a digitization-based fit. Can also be None (default) to use ‘auto’ when enough extra digitization points are available, and 0.095 otherwise. Currently the head radius does not affect plotting.

New in version 0.20.

vlimtuple of length 2 | ‘joint’

Colormap limits to use. If a tuple of floats, specifies the lower and upper bounds of the colormap (in that order); providing None for either entry will set the corresponding boundary at the min/max of the data (separately for each topomap). Elements of the tuple may also be callable functions which take in a NumPy array and return a scalar. If vlim='joint', will compute the colormap limits jointly across all topomaps of the same channel type, using the min/max of the data. Defaults to (None, None).

New in version 0.21.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only.

Returns
figinstance of Figure

Figure distributing one image per channel across sensor topography.

Examples using plot_psd_topomap:

plot_sensors(kind='topomap', ch_type=None, title=None, show_names=False, ch_groups=None, to_sphere=True, axes=None, block=False, show=True, sphere=None, verbose=None)[source]

Plot sensor positions.

Parameters
kindstr

Whether to plot the sensors as 3d, topomap or as an interactive sensor selection dialog. Available options ‘topomap’, ‘3d’, ‘select’. If ‘select’, a set of channels can be selected interactively by using lasso selector or clicking while holding control key. The selected channels are returned along with the figure instance. Defaults to ‘topomap’.

ch_typeNone | str

The channel type to plot. Available options ‘mag’, ‘grad’, ‘eeg’, ‘seeg’, ‘ecog’, ‘all’. If 'all', all the available mag, grad, eeg, seeg and ecog channels are plotted. If None (default), then channels are chosen in the order given above.

titlestr | None

Title for the figure. If None (default), equals to 'Sensor positions (%s)' % ch_type.

show_namesbool | array of str

Whether to display all channel names. If an array, only the channel names in the array are shown. Defaults to False.

ch_groups‘position’ | array of shape (n_ch_groups, n_picks) | None

Channel groups for coloring the sensors. If None (default), default coloring scheme is used. If ‘position’, the sensors are divided into 8 regions. See order kwarg of mne.viz.plot_raw(). If array, the channels are divided by picks given in the array.

New in version 0.13.0.

to_spherebool

Whether to project the 3d locations to a sphere. When False, the sensor array appears similar as to looking downwards straight above the subject’s head. Has no effect when kind=’3d’. Defaults to True.

New in version 0.14.0.

axesinstance of Axes | instance of Axes3D | None

Axes to draw the sensors to. If kind='3d', axes must be an instance of Axes3D. If None (default), a new axes will be created.

New in version 0.13.0.

blockbool

Whether to halt program execution until the figure is closed. Defaults to False.

New in version 0.13.0.

showbool

Show figure if True. Defaults to True.

spherefloat | array_like | str | None

The sphere parameters to use for the cartoon head. Can be array-like of shape (4,) to give the X/Y/Z origin and radius in meters, or a single float to give the radius (origin assumed 0, 0, 0). Can also be a spherical ConductorModel, which will use the origin and radius. Can be “auto” to use a digitization-based fit. Can also be None (default) to use ‘auto’ when enough extra digitization points are available, and 0.095 otherwise. Currently the head radius does not affect plotting.

New in version 0.20.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Returns
figinstance of Figure

Figure containing the sensor topography.

selectionlist

A list of selected channels. Only returned if kind=='select'.

Notes

This function plots the sensor locations from the info structure using matplotlib. For drawing the sensors using mayavi see mne.viz.plot_alignment().

New in version 0.12.0.

Examples using plot_sensors:

plot_topo_image(layout=None, sigma=0.0, vmin=None, vmax=None, colorbar=None, order=None, cmap='RdBu_r', layout_scale=0.95, title=None, scalings=None, border='none', fig_facecolor='k', fig_background=None, font_color='w', show=True)[source]

Plot Event Related Potential / Fields image on topographies.

Parameters
layoutinstance of Layout

System specific sensor positions.

sigmafloat

The standard deviation of the Gaussian smoothing to apply along the epoch axis to apply in the image. If 0., no smoothing is applied.

vminfloat

The min value in the image. The unit is µV for EEG channels, fT for magnetometers and fT/cm for gradiometers.

vmaxfloat

The max value in the image. The unit is µV for EEG channels, fT for magnetometers and fT/cm for gradiometers.

colorbarbool | None

Whether to display a colorbar or not. If None a colorbar will be shown only if all channels are of the same type. Defaults to None.

orderNone | array of int | callable()

If not None, order is used to reorder the epochs on the y-axis of the image. If it’s an array of int it should be of length the number of good epochs. If it’s a callable the arguments passed are the times vector and the data as 2d array (data.shape[1] == len(times)).

cmapcolormap

Colors to be mapped to the values.

layout_scalefloat

Scaling factor for adjusting the relative size of the layout on the canvas.

titlestr

Title of the figure.

scalingsdict | None

The scalings of the channel types to be applied for plotting. If None, defaults to dict(eeg=1e6, grad=1e13, mag=1e15).

borderstr

Matplotlib borders style to be used for each sensor plot.

fig_facecolorcolor

The figure face color. Defaults to black.

fig_backgroundNone | array

A background image for the figure. This must be a valid input to matplotlib.pyplot.imshow(). Defaults to None.

font_colorcolor

The color of tick labels in the colorbar. Defaults to white.

showbool

Whether to show the figure. Defaults to True.

Returns
figinstance of matplotlib.figure.Figure

Figure distributing one image per channel across sensor topography.

Notes

In an interactive Python session, this plot will be interactive; clicking on a channel image will pop open a larger view of the image; this image will always have a colorbar even when the topo plot does not (because it shows multiple sensor types).

property proj

Whether or not projections are active.

rename_channels(mapping)[source]

Rename channels.

Parameters
mappingdict | callable()

A dictionary mapping the old channel to a new channel name e.g. {‘EEG061’ : ‘EEG161’}. Can also be a callable function that takes and returns a string.

Changed in version 0.10.0: Support for a callable function.

Returns
instinstance of Raw | Epochs | Evoked

The instance (modified in place).

Changed in version 0.20: Return the instance.

Notes

New in version 0.9.0.

Examples using rename_channels:

reorder_channels(ch_names)[source]

Reorder channels.

Parameters
ch_nameslist

The desired channel order.

Returns
instinstance of Raw, Epochs, or Evoked

The modified instance.

Notes

Channel names must be unique. Channels that are not in ch_names are dropped.

New in version 0.16.0.

resample(sfreq, npad='auto', window='boxcar', n_jobs=1, pad='edge', verbose=None)[source]

Resample data.

Note

Data must be loaded.

Parameters
sfreqfloat

New sample rate to use.

npadint | str

Amount to pad the start and end of the data. Can also be “auto” to use a padding that will result in a power-of-two size (can be much faster).

windowstr | tuple

Frequency-domain window to use in resampling. See scipy.signal.resample().

n_jobsint | str

Number of jobs to run in parallel. Can be ‘cuda’ if cupy is installed properly.

padstr

The type of padding to use. Supports all numpy.pad() mode options. Can also be “reflect_limited”, which pads with a reflected version of each vector mirrored on the first and last values of the vector, followed by zeros. Only used for method='fir'. The default is 'edge', which pads with the edge values of each vector.

New in version 0.15.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Returns
instinstance of Epochs or Evoked

The resampled object.

Notes

For some data, it may be more accurate to use npad=0 to reduce artifacts. This is dataset dependent – check your data!

Examples using resample:

save(fname, split_size='2GB', fmt='single', overwrite=False, verbose=True)[source]

Save epochs in a fif file.

Parameters
fnamestr

The name of the file, which should end with -epo.fif or -epo.fif.gz.

split_sizestr | int

Large raw files are automatically split into multiple pieces. This parameter specifies the maximum size of each piece. If the parameter is an integer, it specifies the size in Bytes. It is also possible to pass a human-readable string, e.g., 100MB. Note: Due to FIFF file limitations, the maximum split size is 2GB.

New in version 0.10.0.

fmtstr

Format to save data. Valid options are ‘double’ or ‘single’ for 64- or 32-bit float, or for 128- or 64-bit complex numbers respectively. Note: Data are processed with double precision. Choosing single-precision, the saved data will slightly differ due to the reduction in precision.

New in version 0.17.

overwritebool

If True, the destination file (if it exists) will be overwritten. If False (default), an error will be raised if the file exists. To overwrite original file (the same one that was loaded), data must be preloaded upon reading. This defaults to True in 0.18 but will change to False in 0.19.

New in version 0.18.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Notes

Bad epochs will be dropped before saving the epochs to disk.

Examples using save:

savgol_filter(h_freq, verbose=None)[source]

Filter the data using Savitzky-Golay polynomial method.

Parameters
h_freqfloat

Approximate high cut-off frequency in Hz. Note that this is not an exact cutoff, since Savitzky-Golay filtering 3 is done using polynomial fits instead of FIR/IIR filtering. This parameter is thus used to determine the length of the window over which a 5th-order polynomial smoothing is used.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Returns
instinstance of Epochs or Evoked

The object with the filtering applied.

Notes

For Savitzky-Golay low-pass approximation, see:

New in version 0.9.0.

References

3

Abraham Savitzky and Marcel J. E. Golay. Smoothing and differentiation of data by simplified least squares procedures. Analytical Chemistry, 36(8):1627–1639, 1964. doi:10.1021/ac60214a047.

Examples

>>> import mne
>>> from os import path as op
>>> evoked_fname = op.join(mne.datasets.sample.data_path(), 'MEG', 'sample', 'sample_audvis-ave.fif')  
>>> evoked = mne.read_evokeds(evoked_fname, baseline=(None, 0))[0]  
>>> evoked.savgol_filter(10.)  # low-pass at around 10 Hz 
>>> evoked.plot()  
set_channel_types(mapping, verbose=None)[source]

Define the sensor type of channels.

Parameters
mappingdict

A dictionary mapping a channel to a sensor type (str), e.g., {'EEG061': 'eog'}.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Returns
instinstance of Raw | Epochs | Evoked

The instance (modified in place).

Changed in version 0.20: Return the instance.

Notes

The following sensor types are accepted:

ecg, eeg, emg, eog, exci, ias, misc, resp, seeg, stim, syst, ecog, hbo, hbr, fnirs_cw_amplitude, fnirs_od

New in version 0.9.0.

Examples using set_channel_types:

set_eeg_reference(ref_channels='average', projection=False, ch_type='auto', forward=None, verbose=None)[source]

Specify which reference to use for EEG data.

Use this function to explicitly specify the desired reference for EEG. This can be either an existing electrode or a new virtual channel. This function will re-reference the data according to the desired reference.

Parameters
ref_channelslist of str | str

Can be:

  • The name(s) of the channel(s) used to construct the reference.

  • 'average' to apply an average reference (default)

  • 'REST' to use the Reference Electrode Standardization Technique infinity reference 4.

  • An empty list, in which case MNE will not attempt any re-referencing of the data

projectionbool

If ref_channels='average' this argument specifies if the average reference should be computed as a projection (True) or not (False; default). If projection=True, the average reference is added as a projection and is not applied to the data (it can be applied afterwards with the apply_proj method). If projection=False, the average reference is directly applied to the data. If ref_channels is not 'average', projection must be set to False (the default in this case).

ch_type‘auto’ | ‘eeg’ | ‘ecog’ | ‘seeg’

The name of the channel type to apply the reference to. If ‘auto’, the first channel type of eeg, ecog or seeg that is found (in that order) will be selected.

New in version 0.19.

forwardinstance of Forward | None

Forward solution to use. Only used with ref_channels='REST'.

New in version 0.21.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Returns
instinstance of Raw | Epochs | Evoked

Data with EEG channels re-referenced. If ref_channels='average' and projection=True a projection will be added instead of directly re-referencing the data.

See also

mne.set_bipolar_reference

Convenience function for creating bipolar references.

Notes

Some common referencing schemes and the corresponding value for the ref_channels parameter:

  • Average reference:

    A new virtual reference electrode is created by averaging the current EEG signal by setting ref_channels='average'. Bad EEG channels are automatically excluded if they are properly set in info['bads'].

  • A single electrode:

    Set ref_channels to a list containing the name of the channel that will act as the new reference, for example ref_channels=['Cz'].

  • The mean of multiple electrodes:

    A new virtual reference electrode is created by computing the average of the current EEG signal recorded from two or more selected channels. Set ref_channels to a list of channel names, indicating which channels to use. For example, to apply an average mastoid reference, when using the 10-20 naming scheme, set ref_channels=['M1', 'M2'].

  • REST

    The given EEG electrodes are referenced to a point at infinity using the lead fields in forward, which helps standardize the signals.

  1. If a reference is requested that is not the average reference, this function removes any pre-existing average reference projections.

  2. During source localization, the EEG signal should have an average reference.

  3. In order to apply a reference, the data must be preloaded. This is not necessary if ref_channels='average' and projection=True.

  4. For an average or REST reference, bad EEG channels are automatically excluded if they are properly set in info['bads'].

New in version 0.9.0.

References

4

D. Yao. A method to standardize a reference of scalp EEG recordings to a point at infinity. Physiological Measurement, 22(4):693–711, November 2001. doi:10.1088/0967-3334/22/4/305.

set_meas_date(meas_date)[source]

Set the measurement start date.

Parameters
meas_datedatetime | float | tuple | None

The new measurement date. If datetime object, it must be timezone-aware and in UTC. A tuple of (seconds, microseconds) or float (alias for (meas_date, 0)) can also be passed and a datetime object will be automatically created. If None, will remove the time reference.

Returns
instinstance of Raw | Epochs | Evoked

The modified raw instance. Operates in place.

Notes

If you want to remove all time references in the file, call mne.io.anonymize_info(inst.info) after calling inst.set_meas_date(None).

New in version 0.20.

set_montage(montage, match_case=True, on_missing='raise', verbose=None)[source]

Set EEG sensor configuration and head digitization.

Parameters
montageNone | str | DigMontage

A montage containing channel positions. If str or DigMontage is specified, the channel info will be updated with the channel positions. Default is None. See also the documentation of mne.channels.DigMontage for more information.

match_casebool

If True (default), channel name matching will be case sensitive.

New in version 0.20.

on_missingstr

Can be 'raise' (default) to raise an error, 'warn' to emit a warning, or 'ignore' to ignore when channels have missing coordinates.

New in version 0.20.1.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). If used, it should be passed as a keyword-argument only. Defaults to self.verbose.

Returns
instinstance of Raw | Epochs | Evoked

The instance.

Notes

Operates in place.

shift_time(tshift, relative=True)[source]

Shift time scale in epoched or evoked data.

Parameters
tshiftfloat

The (absolute or relative) time shift in seconds. If relative is True, positive tshift increases the time value associated with each sample, while negative tshift decreases it.

relativebool

If True, increase or decrease time values by tshift seconds. Otherwise, shift the time values such that the time of the first sample equals tshift.

Returns
epochsinstance of Epochs

The modified Epochs instance.

Notes

This method allows you to shift the time values associated with each data sample by an arbitrary amount. It does not resample the signal or change the data values in any way.

standard_error(picks=None)[source]

Compute standard error over epochs.

Parameters
picksstr | list | 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 data channels.

Returns
evokedinstance of Evoked

The standard error over epochs.

subtract_evoked(evoked=None)[source]

Subtract an evoked response from each epoch.

Can be used to exclude the evoked response when analyzing induced activity, see e.g. [1].

Parameters
evokedinstance of Evoked | None

The evoked response to subtract. If None, the evoked response is computed from Epochs itself.

Returns
selfinstance of Epochs

The modified instance (instance is also modified inplace).

References

1

David et al. “Mechanisms of evoked and induced responses in MEG/EEG”, NeuroImage, vol. 31, no. 4, pp. 1580-1591, July 2006.

time_as_index(times, use_rounding=False)[source]

Convert time to indices.

Parameters
timeslist-like | float | int

List of numbers or a number representing points in time.

use_roundingbool

If True, use rounding (instead of truncation) when converting times to indices. This can help avoid non-unique indices.

Returns
indexndarray

Indices corresponding to the times supplied.

property times

Time vector in seconds.

property tmax

Last time point.

property tmin

First time point.

to_data_frame(picks=None, index=None, scalings=None, copy=True, long_format=False, time_format='ms')[source]

Export data in tabular structure as a pandas DataFrame.

Channels are converted to columns in the DataFrame. By default, additional columns “time”, “epoch” (epoch number), and “condition” (epoch event description) are added, unless index is not None (in which case the columns specified in index will be used to form the DataFrame’s index instead).

Parameters
picksstr | list | 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.

indexstr | list of str | None

Kind of index to use for the DataFrame. If None, a sequential integer index (pandas.RangeIndex) will be used. If 'time', a pandas.Float64Index, pandas.Int64Index, or pandas.TimedeltaIndex will be used (depending on the value of time_format). If a list of two or more string values, a pandas.MultiIndex will be created. Valid string values are ‘time’, ‘epoch’, and ‘condition’. Defaults to None.

scalingsdict | None

Scaling factor applied to the channels picked. If None, defaults to dict(eeg=1e6, mag=1e15, grad=1e13) — i.e., converts EEG to µV, magnetometers to fT, and gradiometers to fT/cm.

copybool

If True, data will be copied. Otherwise data may be modified in place. Defaults to True.

long_formatbool

If True, the DataFrame is returned in long format where each row is one observation of the signal at a unique combination of time point, channel, epoch number, and condition. For convenience, a ch_type column is added to facilitate subsetting the resulting DataFrame. Defaults to False.

time_formatstr | None

Desired time format. If None, no conversion is applied, and time values remain as float values in seconds. If 'ms', time values will be rounded to the nearest millisecond and converted to integers. If 'timedelta', time values will be converted to pandas.Timedelta values. Defaults to 'ms'.

New in version 0.20.

Returns
dfinstance of pandas.DataFrame

A dataframe suitable for usage with other statistical/plotting/analysis packages.

Examples using to_data_frame:

Examples using mne.BaseEpochs