mne.realtime.RtEpochs

class mne.realtime.RtEpochs(client, event_id, tmin, tmax, stim_channel='STI 014', sleep_time=0.1, baseline=(None, 0), picks=None, name='Unknown', reject=None, flat=None, proj=True, decim=1, reject_tmin=None, reject_tmax=None, detrend=None, add_eeg_ref=True, isi_max=2.0, find_events=None, verbose=None)

Realtime Epochs

Can receive epochs in real time from an RtClient.

For example, to get some epochs from a running mne_rt_server on ‘localhost’, you could use:

client = mne.realtime.RtClient('localhost')
event_id, tmin, tmax = 1, -0.2, 0.5

epochs = mne.realtime.RtEpochs(client, event_id, tmin, tmax)
epochs.start()  # start the measurement and start receiving epochs

evoked_1 = epochs.average()  # computed over all epochs
evoked_2 = epochs[-5:].average()  # computed over the last 5 epochs
Parameters:

client : instance of mne.realtime.RtClient

The realtime client.

event_id : int | list of int

The id of the event to consider. If int, only events with the ID specified by event_id are considered. Multiple event ID’s can be specified using a list.

tmin : float

Start time before event.

tmax : float

End time after event.

stim_channel : string or list of string

Name of the stim channel or all the stim channels affected by the trigger.

sleep_time : float

Time in seconds to wait between checking for new epochs when epochs are requested and the receive queue is empty.

baseline : None (default) or tuple of length 2

The time interval to apply baseline correction. If None do not apply it. If baseline is (a, b) the interval is between “a (s)” and “b (s)”. If a is None the beginning of the data is used and if b is None then b is set to the end of the interval. If baseline is equal to (None, None) all the time interval is used.

picks : array-like of int | None (default)

Indices of channels to include (if None, all channels are used).

name : string

Comment that describes the Evoked data created.

reject : dict | 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. Example:

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

flat : dict | 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.

proj : bool, optional

Apply SSP projection vectors

decim : int

Factor by which to downsample the data from the raw file upon import. Warning: This simply selects every nth sample, data is not filtered here. If data is not properly filtered, aliasing artifacts may occur.

reject_tmin : scalar | None

Start of the time window used to reject epochs (with the default None, the window will start with tmin).

reject_tmax : scalar | None

End of the time window used to reject epochs (with the default None, the window will end with tmax).

detrend : int | 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).

add_eeg_ref : bool

If True, an EEG average reference will be added (unless one already exists).

isi_max : float

The maximmum time in seconds between epochs. If no epoch arrives in the next isi_max seconds the RtEpochs stops.

find_events : dict

The arguments to the real-time find_events method as a dictionary. If find_events is None, then default values are used. Valid keys are ‘output’ | ‘consecutive’ | ‘min_duration’ | ‘mask’. Example (also default values):

find_events = dict(output='onset', consecutive='increasing',
                   min_duration=0, mask=0)

See mne.find_events for detailed explanation of these options.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose). Defaults to client.verbose.

Attributes:

info : dict

Measurement info.

event_id : dict

Names of of conditions corresponding to event_ids.

ch_names : list of string

List of channels’ names.

events : array, shape (n_events, 3)

The events associated with the epochs currently in the queue.

verbose : bool, str, int, or None

See above.

Methods

add_channels(add_list[, copy, force_update_info]) Append new channels to the instance.
add_eeg_average_proj() Add an average EEG reference projector if one does not exist
add_proj(projs[, remove_existing, verbose]) Add SSP projection vectors
apply_baseline(baseline[, copy, verbose]) Baseline correct epochs
apply_proj() Apply the signal space projection (SSP) operators to the data.
average([picks]) Compute average of epochs
copy() Return copy of Epochs instance
crop([tmin, tmax, copy]) Crops a time interval from epochs object.
decimate(decim[, copy, offset]) 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_bad_epochs(*args, **kwargs)

Warning

DEPRECATED: drop_bad_epochs method has been renamed drop_bad. drop_bad_epochs method will be removed in 0.13

drop_channels(ch_names[, copy]) Drop some channels
drop_epochs(*args, **kwargs)

Warning

DEPRECATED: drop_epochs method has been renamed drop. drop_epochs method will be removed in 0.13

drop_log_stats([ignore]) Compute the channel stats based on a drop_log from Epochs.
equalize_event_counts(event_ids[, method, copy]) Equalize the number of trials in each condition
get_data() Get all epochs as a 3D array
interpolate_bads([reset_bads, mode]) Interpolate bad MEG and EEG channels.
iter_evoked() Iterate over epochs as a sequence of Evoked objects
load_data() Load the data if not already preloaded
next([return_event_id]) To make iteration over epochs easy.
pick_channels(ch_names[, copy]) Pick some channels
pick_types([meg, eeg, stim, eog, ecg, emg, ...]) Pick some channels by type and names
plot([picks, scalings, show, block, ...]) 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, layout, axes]) Plot SSP vector
plot_psd([fmin, fmax, proj, bandwidth, ...]) Plot the power spectral density across epochs
plot_psd_topomap([bands, vmin, vmax, proj, ...]) Plot the topomap of the power spectral density across epochs
plot_sensors([kind, ch_type, title, ...]) Plot sensors positions.
plot_topo_image([layout, sigma, vmin, vmax, ...]) Plot Event Related Potential / Fields image on topographies
rename_channels(mapping) Rename channels.
resample(sfreq[, npad, window, n_jobs, ...]) Resample preloaded data
save(fname[, split_size]) Save epochs in a fif file
savgol_filter(h_freq[, copy]) Filter the data using Savitzky-Golay polynomial method
set_channel_types(mapping) Define the sensor type of channels.
set_montage(montage[, verbose]) Set EEG sensor configuration
standard_error([picks]) Compute standard error over epochs
start() Start receiving epochs
stop([stop_receive_thread, stop_measurement]) Stop receiving 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, scale_time, ...]) Export data in tabular structure as a pandas DataFrame.
__init__(client, event_id, tmin, tmax, stim_channel='STI 014', sleep_time=0.1, baseline=(None, 0), picks=None, name='Unknown', reject=None, flat=None, proj=True, decim=1, reject_tmin=None, reject_tmax=None, detrend=None, add_eeg_ref=True, isi_max=2.0, find_events=None, verbose=None)
add_channels(add_list, copy=None, force_update_info=False)

Append new channels to the instance.

Parameters:

add_list : list

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

copy : bool

This parameter has been deprecated and will be removed in 0.13. Use inst.copy() instead. Whether to return a new instance or modify in place.

force_update_info : bool

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:

inst : instance of Raw, Epochs, or Evoked

The modified instance.

add_eeg_average_proj()

Add an average EEG reference projector if one does not exist

add_proj(projs, remove_existing=False, verbose=None)

Add SSP projection vectors

Parameters:

projs : list

List with projection vectors.

remove_existing : bool

Remove the projection vectors currently in the file.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose).

Returns:

self : instance of Raw | Epochs | Evoked

The data container.

apply_baseline(baseline, copy=None, verbose=None)

Baseline correct epochs

Parameters:

baseline : tuple of length 2

The time interval to apply baseline correction. (a, b) is the interval is between “a (s)” and “b (s)”. If a is None the beginning of the data is used and if b is None then b is set to the end of the interval. If baseline is equal to (None, None) all the time interval is used.

copy : bool

This parameter has been deprecated and will be removed in 0.13. Use inst.copy() instead. Whether to return a new instance or modify in place.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose).

Returns:

epochs : instance of Epochs

The baseline-corrected Epochs object.

Notes

Baseline correction can be done multiple times.

New in version 0.10.0.

apply_proj()

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

Returns:

self : instance 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
average(picks=None)

Compute average of epochs

Parameters:

picks : array-like of int | None

If None only MEG, EEG, SEEG, and ECoG channels are kept otherwise the channels indices in picks are kept.

Returns:

evoked : instance 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.

ch_names

Channel names

copy()

Return copy of Epochs instance

crop(tmin=None, tmax=None, copy=None)

Crops a time interval from epochs object.

Parameters:

tmin : float | None

Start time of selection in seconds.

tmax : float | None

End time of selection in seconds.

copy : bool

This parameter has been deprecated and will be removed in 0.13. Use inst.copy() instead. Whether to return a new instance or modify in place.

Returns:

epochs : instance of Epochs

The cropped epochs.

Notes

Unlike Python slices, MNE time intervals include both their end points; crop(tmin, tmax) returns the interval tmin <= t <= tmax.

decimate(decim, copy=None, offset=0)

Decimate the epochs

Parameters:

decim : int

The amount to decimate data.

copy : bool

This parameter has been deprecated and will be removed in 0.13. Use inst.copy() instead. Whether to return a new instance or modify in place.

offset : int

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.

Returns:

epochs : instance of Epochs

The decimated Epochs object.

Notes

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

New in version 0.10.0.

del_proj(idx)

Remove SSP projection vector

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

idx : int

Index of the projector to remove.

Returns:

self : instance of Raw | Epochs | Evoked

drop(indices, reason='USER', verbose=None)

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:

indices : array of ints or bools

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

reason : str

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

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose). Defaults to self.verbose.

Returns:

epochs : instance of Epochs

The epochs with indices dropped. Operates in-place.

drop_bad(reject='existing', flat='existing', verbose=None)

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:

reject : dict | 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.

flat : dict | 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.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose). Defaults to self.verbose.

Returns:

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

drop_bad_epochs(*args, **kwargs)

Warning

DEPRECATED: drop_bad_epochs method has been renamed drop_bad. drop_bad_epochs method will be removed in 0.13

Drop bad epochs without retaining the epochs data

drop_channels(ch_names, copy=None)

Drop some channels

Parameters:

ch_names : list

The list of channels to remove.

copy : bool

This parameter has been deprecated and will be removed in 0.13. Use inst.copy() instead. Whether to return a new instance or modify in place.

Returns:

inst : instance of Raw, Epochs, or Evoked

The modified instance.

See also

pick_channels

Notes

New in version 0.9.0.

drop_epochs(*args, **kwargs)

Warning

DEPRECATED: drop_epochs method has been renamed drop. drop_epochs method will be removed in 0.13

Drop epochs based on indices or boolean mask

drop_log_stats(ignore=('IGNORED', ))

Compute the channel stats based on a drop_log from Epochs.

Parameters:

ignore : list

The drop reasons to ignore.

Returns:

perc : float

Total percentage of epochs dropped.

See also

plot_drop_log

equalize_event_counts(event_ids, method='mintime', copy=None)

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_ids : list

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.

method : str

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

copy : bool

This parameter has been deprecated and will be removed in 0.13. Use inst.copy() instead. Whether to return a new instance or modify in place.

Returns:

epochs : instance of Epochs

The modified Epochs instance.

indices : array 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’.

events

The events associated with the epochs currently in the queue.

get_data()

Get all epochs as a 3D array

Returns:

data : array of shape (n_epochs, n_channels, n_times)

A copy of the epochs data.

interpolate_bads(reset_bads=True, mode='accurate')

Interpolate bad MEG and EEG channels.

Operates in place.

Parameters:

reset_bads : bool

If True, remove the bads from info.

mode : str

Either ‘accurate’ or ‘fast’, determines the quality of the Legendre polynomial expansion used for interpolation of MEG channels.

Returns:

inst : instance of Raw, Epochs, or Evoked

The modified instance.

Notes

New in version 0.9.0.

iter_evoked()

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

load_data()

Load the data if not already preloaded

Returns:

epochs : instance of Epochs

The epochs object.

Notes

This function operates in-place.

New in version 0.10.0.

next(return_event_id=False)

To make iteration over epochs easy.

Parameters:

return_event_id : bool

If True, return both an epoch and and event_id.

Returns:

epoch : instance of Epochs

The epoch.

event_id : int

The event id. Only returned if return_event_id is True.

pick_channels(ch_names, copy=None)

Pick some channels

Parameters:

ch_names : list

The list of channels to select.

copy : bool

This parameter has been deprecated and will be removed in 0.13. Use inst.copy() instead. Whether to return a new instance or modify in place.

Returns:

inst : instance of Raw, Epochs, or Evoked

The modified instance.

See also

drop_channels

Notes

New in version 0.9.0.

pick_types(meg=True, 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, bio=False, ecog=False, include=[], exclude='bads', selection=None, copy=None)

Pick some channels by type and names

Parameters:

meg : bool | str

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

eeg : bool

If True include EEG channels.

stim : bool

If True include stimulus channels.

eog : bool

If True include EOG channels.

ecg : bool

If True include ECG channels.

emg : bool

If True include EMG channels.

ref_meg: bool | str :

If True include CTF / 4D reference channels. If ‘auto’, the reference channels are only included if compensations are present.

misc : bool

If True include miscellaneous analog channels.

resp : bool

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

chpi : bool

If True include continuous HPI coil channels.

exci : bool

Flux excitation channel used to be a stimulus channel.

ias : bool

Internal Active Shielding data (maybe on Triux only).

syst : bool

System status channel information (on Triux systems only).

seeg : bool

Stereotactic EEG channels.

bio : bool

Bio channels.

ecog : bool

Electrocorticography channels.

include : list of string

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

exclude : list of string | str

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

selection : list of string

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

copy : bool

This parameter has been deprecated and will be removed in 0.13. Use inst.copy() instead. Whether to return a new instance or modify in place.

Returns:

inst : instance of Raw, Epochs, or Evoked

The modified instance.

Notes

New in version 0.9.0.

plot(picks=None, scalings=None, show=True, block=False, n_epochs=20, n_channels=20, title=None)

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:

picks : array-like of int | None

Channels to be included. If None only good data channels are used. Defaults to None

scalings : dict | 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)

show : bool

Whether to show the figure or not.

block : bool

Whether to halt program execution until the figure is closed. Useful for rejecting bad trials on the fly by clicking on a sub plot.

n_epochs : int

The number of epochs per view.

n_channels : int

The number of channels per view on mne_browse_epochs. If trellis is True, this parameter has no effect. Defaults to 20.

title : str | None

The title of the window. If None, epochs name will be displayed. If trellis is True, this parameter has no effect. Defaults to None.

Returns:

fig : Instance 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. Butterfly plot can be toggled with b key. Right mouse click adds a vertical line to the plot.

New in version 0.10.0.

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)

Show the channel stats based on a drop_log from Epochs

Parameters:

threshold : float

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

n_max_plot : int

Maximum number of channels to show stats for.

subject : str

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

color : tuple | str

Color to use for the bars.

width : float

Width of the bars.

ignore : list

The drop reasons to ignore.

show : bool

Show figure if True.

Returns:

perc : float

Total percentage of epochs dropped.

fig : Instance of matplotlib.figure.Figure

The figure.

plot_image(picks=None, sigma=0.0, vmin=None, vmax=None, colorbar=True, order=None, show=True, units=None, scalings=None, cmap='RdBu_r', fig=None, overlay_times=None)

Plot Event Related Potential / Fields image

Parameters:

picks : int | array-like of int | None

The indices of the channels to consider. If None, the first five good channels are plotted.

sigma : float

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

vmin : float

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

vmax : float

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

colorbar : bool

Display or not a colorbar.

order : None | 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).

show : bool

Show figure if True.

units : dict | None

The units of the channel types used for axes lables. If None, defaults to units=dict(eeg=’uV’, grad=’fT/cm’, mag=’fT’).

scalings : dict | 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).

cmap : matplotlib colormap

Colormap.

fig : matplotlib figure | None

Figure instance to draw the image to. Figure must contain two axes for drawing the single trials and evoked responses. If None a new figure is created. Defaults to None.

overlay_times : array-like, shape (n_epochs,) | None

If not None the parameter is interpreted as time instants in seconds and is added to the image. It is typically useful to display reaction times. Note that it is defined with respect to the order of epochs such that overlay_times[0] corresponds to epochs[0].

Returns:

figs : list of matplotlib figures

One figure per channel displayed.

plot_projs_topomap(ch_type=None, layout=None, axes=None)

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.

layout : None | Layout | List of Layouts

Layout instance specifying sensor positions (does not need to be specified for Neuromag data). If possible, the correct layout file is inferred from the data; if no appropriate layout file was found, the layout is automatically generated from the sensor locations. Or a list of Layout if projections are from different sensor types.

axes : instance 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.

Returns:

fig : instance of matplotlib figure

Figure distributing one image per channel across sensor topography.

plot_psd(fmin=0, fmax=inf, proj=False, bandwidth=None, adaptive=False, low_bias=True, normalization='length', picks=None, ax=None, color='black', area_mode='std', area_alpha=0.33, dB=True, n_jobs=1, verbose=None, show=True)

Plot the power spectral density across epochs

Parameters:

fmin : float

Start frequency to consider.

fmax : float

End frequency to consider.

proj : bool

Apply projection.

bandwidth : float

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

adaptive : bool

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

low_bias : bool

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

normalization : str

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

picks : array-like of int | None

List of channels to use.

ax : instance of matplotlib Axes | None

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

color : str | tuple

A matplotlib-compatible color to use.

area_mode : str | 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.

area_alpha : float

Alpha for the area.

dB : bool

If True, transform data to decibels.

n_jobs : int

Number of jobs to run in parallel.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose).

show : bool

Show figure if True.

Returns:

fig : instance of matplotlib figure

Figure distributing one image per channel across sensor topography.

plot_psd_topomap(bands=None, vmin=None, vmax=None, proj=False, bandwidth=None, adaptive=False, low_bias=True, normalization='length', ch_type=None, layout=None, cmap='RdBu_r', agg_fun=None, dB=True, n_jobs=1, normalize=False, cbar_fmt='%0.3f', outlines='head', show=True, verbose=None)

Plot the topomap of the power spectral density across epochs

Parameters:

bands : list of tuple | None

The lower and upper frequency and the name for that band. If None, (default) expands to:

bands = [(0, 4, ‘Delta’), (4, 8, ‘Theta’), (8, 12, ‘Alpha’),

(12, 30, ‘Beta’), (30, 45, ‘Gamma’)]

vmin : float | callable | None

The value specifying the lower bound of the color range. If None, and vmax is None, -vmax is used. Else np.min(data). If callable, the output equals vmin(data).

vmax : float | callable | None

The value specifying the upper bound of the color range. If None, the maximum absolute value is used. If callable, the output equals vmax(data). Defaults to None.

proj : bool

Apply projection.

bandwidth : float

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

adaptive : bool

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

low_bias : bool

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

normalization : str

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 : {None, ‘mag’, ‘grad’, ‘planar1’, ‘planar2’, ‘eeg’}

The channel type to plot. For ‘grad’, the gradiometers are collected in pairs and the RMS for each pair is plotted. If None, defaults to ‘mag’ if MEG data are present and to ‘eeg’ if only EEG data are present.

layout : None | Layout

Layout instance specifying sensor positions (does not need to be specified for Neuromag data). If possible, the correct layout file is inferred from the data; if no appropriate layout file was found, the layout is automatically generated from the sensor locations.

cmap : matplotlib colormap

Colormap. For magnetometers and eeg defaults to ‘RdBu_r’, else ‘Reds’.

agg_fun : callable

The function used to aggregate over frequencies. Defaults to np.sum. if normalize is True, else np.mean.

dB : bool

If True, transform data to decibels (with 10 * np.log10(data)) following the application of agg_fun. Only valid if normalize is False.

n_jobs : int

Number of jobs to run in parallel.

normalize : bool

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

cbar_fmt : str

The colorbar format. Defaults to ‘%0.3f’.

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, and the ‘autoshrink’ (bool) field will trigger automated shrinking of the positions due to points outside the outline. 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’.

show : bool

Show figure if True.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose).

Returns:

fig : instance of matplotlib figure

Figure distributing one image per channel across sensor topography.

plot_sensors(kind='topomap', ch_type=None, title=None, show_names=False, show=True)

Plot sensors positions.

Parameters:

kind : str

Whether to plot the sensors as 3d or as topomap. Available options ‘topomap’, ‘3d’. Defaults to ‘topomap’.

ch_type : ‘mag’ | ‘grad’ | ‘eeg’ | ‘seeg’ | ‘ecog’ | None

The channel type to plot. If None, then channels are chosen in the order given above.

title : str | None

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

show_names : bool

Whether to display all channel names. Defaults to False.

show : bool

Show figure if True. Defaults to True.

Returns:

fig : instance of matplotlib figure

Figure containing the sensor topography.

Notes

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

New in version 0.12.0.

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

Plot Event Related Potential / Fields image on topographies

Parameters:

layout: instance of Layout :

System specific sensor positions.

sigma : float

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

vmin : float

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

vmax : float

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

colorbar : bool

Display or not a colorbar.

order : None | 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)).

cmap : instance of matplotlib.pyplot.colormap

Colors to be mapped to the values.

layout_scale: float :

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

title : str

Title of the figure.

scalings : dict | None

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

border : str

matplotlib borders style to be used for each sensor plot.

fig_facecolor : str | obj

The figure face color. Defaults to black.

font_color : str | obj

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

show : bool

Show figure if True.

Returns:

fig : instance of matplotlib figure

Figure distributing one image per channel across sensor topography.

rename_channels(mapping)

Rename channels.

Parameters:

mapping : dict | 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 (new in version 0.10.0).

Notes

New in version 0.9.0.

resample(sfreq, npad=None, window='boxcar', n_jobs=1, copy=None, verbose=None)

Resample preloaded data

Parameters:

sfreq : float

New sample rate to use

npad : int | 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).

window : string or tuple

Window to use in resampling. See scipy.signal.resample.

n_jobs : int

Number of jobs to run in parallel.

copy : bool

This parameter has been deprecated and will be removed in 0.13. Use inst.copy() instead. Whether to return a new instance or modify in place.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose). Defaults to self.verbose.

Returns:

epochs : instance of Epochs

The resampled epochs object.

Notes

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

save(fname, split_size='2GB')

Save epochs in a fif file

Parameters:

fname : str

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

split_size : string | 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.

Notes

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

savgol_filter(h_freq, copy=False)

Filter the data using Savitzky-Golay polynomial method

Parameters:

h_freq : float

Approximate high cut-off frequency in Hz. Note that this is not an exact cutoff, since Savitzky-Golay filtering [R26] 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.

copy : bool

If True, a copy of the object, filtered, is returned. If False (default), it operates on the object in place.

Returns:

inst : instance 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

[R26](1, 2) Savitzky, A., Golay, M.J.E. (1964). “Smoothing and Differentiation of Data by Simplified Least Squares Procedures”. Analytical Chemistry 36 (8): 1627-39.

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)

Define the sensor type of channels.

Note: The following sensor types are accepted:
ecg, eeg, emg, eog, exci, ias, misc, resp, seeg, stim, syst, ecog
Parameters:

mapping : dict

a dictionary mapping a channel to a sensor type (str) {‘EEG061’: ‘eog’}.

Notes

New in version 0.9.0.

set_montage(montage, verbose=None)

Set EEG sensor configuration

Parameters:

montage : instance of Montage or DigMontage

The montage to use.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose).

Notes

Operates in place.

New in version 0.9.0.

standard_error(picks=None)

Compute standard error over epochs

Parameters:

picks : array-like of int | None

If None only MEG, EEG, SEEG, and ECoG channels are kept otherwise the channels indices in picks are kept.

Returns:

evoked : instance of Evoked

The standard error over epochs.

start()

Start receiving epochs

The measurement will be started if it has not already been started.

stop(stop_receive_thread=False, stop_measurement=False)

Stop receiving epochs

Parameters:

stop_receive_thread : bool

Stop the receive thread. Note: Other RtEpochs instances will also stop receiving epochs when the receive thread is stopped. The receive thread will always be stopped if stop_measurement is True.

stop_measurement : bool

Also stop the measurement. Note: Other clients attached to the server will also stop receiving data.

subtract_evoked(evoked=None)

Subtract an evoked response from each epoch

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

Parameters:

evoked : instance of Evoked | None

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

Returns:

self : instance 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)

Convert time to indices

Parameters:

times : list-like | float | int

List of numbers or a number representing points in time.

use_rounding : boolean

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

Returns:

index : ndarray

Indices corresponding to the times supplied.

to_data_frame(picks=None, index=None, scale_time=1000.0, scalings=None, copy=True, start=None, stop=None)

Export data in tabular structure as a pandas DataFrame.

Columns and indices will depend on the object being converted. Generally this will include as much relevant information as possible for the data type being converted. This makes it easy to convert data for use in packages that utilize dataframes, such as statsmodels or seaborn.

Parameters:

picks : array-like of int | None

If None only MEG and EEG channels are kept otherwise the channels indices in picks are kept.

index : tuple of str | None

Column to be used as index for the data. Valid string options are ‘epoch’, ‘time’ and ‘condition’. If None, all three info columns will be included in the table as categorial data.

scale_time : float

Scaling to be applied to time units.

scalings : dict | None

Scaling to be applied to the channels picked. If None, defaults to scalings=dict(eeg=1e6, grad=1e13, mag=1e15, misc=1.0).

copy : bool

If true, data will be copied. Else data may be modified in place.

start : int | None

If it is a Raw object, this defines a starting index for creating the dataframe from a slice. The times will be interpolated from the index and the sampling rate of the signal.

stop : int | None

If it is a Raw object, this defines a stop index for creating the dataframe from a slice. The times will be interpolated from the index and the sampling rate of the signal.

Returns:

df : instance of pandas.core.DataFrame

A dataframe suitable for usage with other statistical/plotting/analysis packages. Column/Index values will depend on the object type being converted, but should be human-readable.