mne.io.Raw

class mne.io.Raw(fname, allow_maxshield=False, preload=False, verbose=None)[source]

Raw data in FIF format.

Parameters
fnamestr | file-like

The raw filename to load. For files that have automatically been split, the split part will be automatically loaded. Filenames should end with raw.fif, raw.fif.gz, raw_sss.fif, raw_sss.fif.gz, raw_tsss.fif, raw_tsss.fif.gz, or _meg.fif. If a file-like object is provided, preloading must be used.

Changed in version 0.18: Support for file-like objects.

allow_maxshieldbool | str (default False)

If True, allow loading of data that has been recorded with internal active compensation (MaxShield). Data recorded with MaxShield should generally not be loaded directly, but should first be processed using SSS/tSSS to remove the compensation signals that may also affect brain activity. Can also be “yes” to load without eliciting a warning.

preloadbool or str (default False)

Preload data into memory for data manipulation and faster indexing. If True, the data will be preloaded into memory (fast, requires large amount of memory). If preload is a string, preload is the file name of a memory-mapped file which is used to store the data on the hard drive (slower, requires less memory).

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more).

Attributes
infodict

Measurement info.

ch_nameslist of str

Channel names.

n_timesint

Number of time points.

timesndarray

Time points.

preloadbool

Indicates whether raw data are in memory.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more).

Methods

__contains__(self, ch_type)

Check channel type membership.

__getitem__(self, item)

Get raw data and times.

__hash__(self)

Hash the object.

__len__(self)

Return the number of time points.

add_channels(self, add_list[, force_update_info])

Append new channels to the instance.

add_events(self, events[, stim_channel, replace])

Add events to stim channel.

add_proj(self, projs[, remove_existing, verbose])

Add SSP projection vectors.

anonymize(self)

Anonymize measurement information in place.

append(self, raws[, preload])

Concatenate raw instances as if they were continuous.

apply_function(self, fun[, picks, dtype, …])

Apply a function to a subset of channels.

apply_gradient_compensation(self, grade[, …])

Apply CTF gradient compensation.

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

Compute analytic signal or envelope for a subset of channels.

apply_proj(self)

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

close(self)

Clean up the object.

copy(self)

Return copy of Raw instance.

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

Crop raw data file.

del_proj(self[, idx])

Remove SSP projection vector.

drop_channels(self, ch_names)

Drop channel(s).

estimate_rank(self[, tstart, tstop, tol, …])

Warning

DEPRECATED: raw.estimate_rank is deprecated and will be removed in 0.19, use mne.compute_rank instead.

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

Filter a subset of channels.

fix_mag_coil_types(self)

Fix Elekta magnetometer coil types.

get_data(self[, picks, start, stop, …])

Get data in the given range.

interpolate_bads(self[, reset_bads, mode, …])

Interpolate bad MEG and EEG channels.

load_bad_channels(self[, bad_file, force])

Mark channels as bad from a text file.

load_data(self[, verbose])

Load raw data.

notch_filter(self, freqs[, picks, …])

Notch filter a subset of channels.

pick(self, picks[, exclude])

Pick a subset of channels.

pick_channels(self, ch_names)

Pick some channels.

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

Pick some channels by type and names.

plot(self[, events, duration, start, …])

Plot raw data.

plot_projs_topomap(self[, ch_type, layout, axes])

Plot SSP vector.

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

Plot the power spectral density across channels.

plot_psd_topo(self[, tmin, tmax, fmin, …])

Plot channel-wise frequency spectra as topography.

plot_sensors(self[, kind, ch_type, title, …])

Plot sensor positions.

rename_channels(self, mapping)

Rename channels.

reorder_channels(self, ch_names)

Reorder channels.

resample(self, sfreq[, npad, window, …])

Resample all channels.

save(self, fname[, picks, tmin, tmax, …])

Save raw data to file.

savgol_filter(self, h_freq[, verbose])

Filter the data using Savitzky-Golay polynomial method.

set_annotations(self, annotations[, …])

Setter for annotations.

set_channel_types(self, mapping)

Define the sensor type of channels.

set_eeg_reference(self[, ref_channels, …])

Specify which reference to use for EEG data.

set_montage(self, montage[, set_dig, …])

Set EEG sensor configuration and head digitization.

time_as_index(self, times[, use_rounding, …])

Convert time to indices.

to_data_frame(self[, picks, index, …])

Export data in tabular structure as a pandas DataFrame.

__contains__(self, 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__(self, item)[source]

Get raw data and times.

Parameters
itemtuple or array_like

See below for use cases.

Returns
datandarray, shape (n_channels, n_times)

The raw data.

timesndarray, shape (n_times,)

The times associated with the data.

Examples

Generally raw data is accessed as:

>>> data, times = raw[picks, time_slice]  

To get all data, you can thus do either of:

>>> data, times = raw[:]  

Which will be equivalent to:

>>> data, times = raw[:, :]  

To get only the good MEG data from 10-20 seconds, you could do:

>>> picks = mne.pick_types(raw.info, meg=True, exclude='bads')  
>>> t_idx = raw.time_as_index([10., 20.])  
>>> data, times = raw[picks, t_idx[0]:t_idx[1]]  
__hash__(self)[source]

Hash the object.

Returns
hashint

The hash

__len__(self)[source]

Return the number of time points.

Returns
lenint

The number of time points.

Examples

This can be used as:

>>> len(raw)  
1000
property acqparser

The AcqParserFIF for the measurement info.

See also

mne.AcqParserFIF
add_channels(self, 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_events(self, events, stim_channel=None, replace=False)[source]

Add events to stim channel.

Parameters
eventsndarray, shape (n_events, 3)

Events to add. The first column specifies the sample number of each event, the second column is ignored, and the third column provides the event value. If events already exist in the Raw instance at the given sample numbers, the event values will be added together.

stim_channelstr | None

Name of the stim channel to add to. If None, the config variable ‘MNE_STIM_CHANNEL’ is used. If this is not found, it will default to ‘STI 014’.

replacebool

If True the old events on the stim channel are removed before adding the new ones.

Notes

Data must be preloaded in order to add events.

Examples using add_events:

add_proj(self, 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). Defaults to self.verbose.

Returns
selfinstance of Raw | Epochs | Evoked

The data container.

Examples using add_proj:

property annotations

Annotations for marking segments of data.

anonymize(self)[source]

Anonymize measurement information in place.

Reset ‘subject_info’, ‘meas_date’, ‘file_id’, and ‘meas_id’ keys if they exist in info.

Returns
infoinstance of Info

Measurement information for the dataset.

Notes

Operates in place.

New in version 0.13.0.

append(self, raws, preload=None)[source]

Concatenate raw instances as if they were continuous.

Note

Boundaries of the raw files are annotated bad. If you wish to use the data as continuous recording, you can remove the boundary annotations after concatenation (see mne.Annotations.delete()).

Parameters
rawslist, or Raw instance

list of Raw instances to concatenate to the current instance (in order), or a single raw instance to concatenate.

preloadbool, str, or None (default None)

Preload data into memory for data manipulation and faster indexing. If True, the data will be preloaded into memory (fast, requires large amount of memory). If preload is a string, preload is the file name of a memory-mapped file which is used to store the data on the hard drive (slower, requires less memory). If preload is None, preload=True or False is inferred using the preload status of the raw files passed in.

Examples using append:

apply_function(self, fun, picks=None, dtype=None, n_jobs=1, channel_wise=True, *args, **kwargs)[source]

Apply a function to a subset of channels.

The function “fun” is applied to the channels defined in “picks”. The data of the Raw object is modified inplace. If the function returns a different data type (e.g. numpy.complex) it must be specified using the dtype parameter, which causes the data type used for representing the raw data to change.

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

Note

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

Note

If the data type changes (dtype != None), more memory is required since the original and the converted data needs to be stored in memory.

Parameters
funcallable()

A function to be applied to the channels. The first argument of fun has to be a timeseries (numpy.ndarray). The function must operate on an array of shape (n_times,) if channel_wise=True and (len(picks), n_times) otherwise. The function must return an ndarray shaped like its input.

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

dtypenumpy.dtype (default: None)

Data type to use for raw data after applying the function. If None the data type is not modified.

n_jobs: int (default: 1)

Number of jobs to run in parallel. Ignored if channel_wise is False.

channel_wise: bool (default: True)

Whether to apply the function to each channel individually. If False, the function will be applied to all channels at once.

New in version 0.18.

*args :

Additional positional arguments to pass to fun (first pos. argument of fun is the timeseries of a channel).

**kwargs :

Keyword arguments to pass to fun. Note that if “verbose” is passed as a member of kwargs, it will be consumed and will override the default mne-python verbose level (see mne.verbose() and Logging documentation for more).

Returns
selfinstance of Raw

The raw object with transformed data.

Examples using apply_function:

apply_gradient_compensation(self, grade, verbose=None)[source]

Apply CTF gradient compensation.

Warning

The compensation matrices are stored with single precision, so repeatedly switching between different of compensation (e.g., 0->1->3->2) can increase numerical noise, especially if data are saved to disk in between changing grades. It is thus best to only use a single gradient compensation level in final analyses.

Parameters
gradeint

CTF gradient compensation level.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). Defaults to self.verbose.

Returns
rawinstance of Raw

The modified Raw instance. Works in-place.

Examples using apply_gradient_compensation:

apply_hilbert(self, 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 (default: False)

Compute the envelope signal of each channel. See Notes.

n_jobs: int

Number of jobs to run in parallel.

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). 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(self)[source]

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

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
property ch_names

Channel names.

close(self)[source]

Clean up the object.

Does nothing for objects that close their file descriptors. Things like RawFIF will override this method.

property compensation_grade

The current gradient compensation grade.

copy(self)[source]

Return copy of Raw instance.

Examples using copy:

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

Crop raw data file.

Limit the data from the raw file to go between specific times. Note that the new tmin is assumed to be t=0 for all subsequently called functions (e.g., time_as_index, or Epochs). New first_samp and last_samp are set accordingly.

Thus function operates in-place on the instance. Use mne.io.Raw.copy() if operation on a copy is desired.

Parameters
tminfloat

New start time in seconds (must be >= 0).

tmaxfloat | None

New end time in seconds of the data (cannot exceed data duration).

include_tmaxbool

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

New in version 0.19.

Returns
rawinstance of Raw

The cropped raw object, modified in-place.

Examples using crop:

del_proj(self, 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

Examples using del_proj:

drop_channels(self, 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:

estimate_rank(self, tstart=0.0, tstop=30.0, tol=0.0001, return_singular=False, picks=None, scalings='norm', verbose=None)[source]

Warning

DEPRECATED: raw.estimate_rank is deprecated and will be removed in 0.19, use mne.compute_rank instead.

Estimate rank of the raw data.

This function is meant to provide a reasonable estimate of the rank. The true rank of the data depends on many factors, so use at your own risk.

Parameters
tstartfloat

Start time to use for rank estimation. Default is 0.0.

tstopfloat | None

End time to use for rank estimation. Default is 30.0. If None, the end time of the raw file is used.

tolfloat

Tolerance for singular values to consider non-zero in calculating the rank. The singular values are calculated in this method such that independent data are expected to have singular value around one.

return_singularbool

If True, also return the singular values that were used to determine the rank.

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 | ‘norm’ | None

To achieve reliable rank estimation on multiple sensors, sensors have to be rescaled. This parameter controls the rescaling. If dict, it will update the following dict of defaults:

dict(mag=1e11, grad=1e9, eeg=1e5)

If ‘norm’ data will be scaled by internally computed channel-wise norms. None will perform no scaling. Defaults to ‘norm’.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more).

Returns
rankint

Estimated rank of the data.

sarray

If return_singular is True, the singular values that were thresholded to determine the rank are also returned.

Notes

If data are not pre-loaded, the appropriate data will be loaded by this function (can be memory intensive).

Projectors are not taken into account unless they have been applied to the data using apply_proj(), since it is not always possible to tell whether or not projectors have been applied previously.

Bad channels will be excluded from calculations.

property filenames

The filenames used.

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

Filter a subset of channels.

Parameters
l_freqfloat | None

For FIR filters, the lower pass-band edge; for IIR filters, the upper 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 low-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). 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:

property first_samp

The first data sample.

fix_mag_coil_types(self)[source]

Fix Elekta magnetometer coil types.

Returns
rawinstance of Raw

The raw object. Operates in place.

Notes

This function changes magnetometer coil types 3022 (T1: SQ20483N) and 3023 (T2: SQ20483-A) to 3024 (T3: SQ20950N) in the channel definition records in the info structure.

Neuromag Vectorview systems can contain magnetometers with two different coil sizes (3022 and 3023 vs. 3024). The systems incorporating coils of type 3024 were introduced last and are used at the majority of MEG sites. At some sites with 3024 magnetometers, the data files have still defined the magnetometers to be of type 3022 to ensure compatibility with older versions of Neuromag software. In the MNE software as well as in the present version of Neuromag software coil type 3024 is fully supported. Therefore, it is now safe to upgrade the data files to use the true coil type.

Note

The effect of the difference between the coil sizes on the current estimates computed by the MNE software is very small. Therefore the use of mne_fix_mag_coil_types is not mandatory.

get_data(self, picks=None, start=0, stop=None, reject_by_annotation=None, return_times=False, verbose=None)[source]

Get data in the given range.

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.

startint

The first sample to include. Defaults to 0.

stopint | None

End sample (first not to include). If None (default), the end of the data is used.

reject_by_annotationNone | ‘omit’ | ‘NaN’

Whether to reject by annotation. If None (default), no rejection is done. If ‘omit’, segments annotated with description starting with ‘bad’ are omitted. If ‘NaN’, the bad samples are filled with NaNs.

return_timesbool

Whether to return times as well. Defaults to False.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). Defaults to self.verbose.

Returns
datandarray, shape (n_channels, n_times)

Copy of the data in the given range.

timesndarray, shape (n_times,)

Times associated with the data samples. Only returned if return_times=True.

Notes

New in version 0.14.0.

Examples using get_data:

interpolate_bads(self, reset_bads=True, mode='accurate', origin=(0.0, 0.0, 0.04), 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 MEG channels.

originarray_like, shape (3,) | str

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

New in version 0.17.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). Defaults to self.verbose.

Returns
instinstance of Raw, Epochs, or Evoked

The modified instance.

Notes

New in version 0.9.0.

property last_samp

The last data sample.

load_bad_channels(self, bad_file=None, force=False)[source]

Mark channels as bad from a text file.

This function operates mostly in the style of the C function mne_mark_bad_channels.

Parameters
bad_filestr

File name of the text file containing bad channels If bad_file = None, bad channels are cleared, but this is more easily done directly as raw.info[‘bads’] = [].

forcebool

Whether or not to force bad channel marking (of those that exist) if channels are not found, instead of raising an error.

load_data(self, verbose=None)[source]

Load raw data.

Parameters
verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). Defaults to self.verbose.

Returns
rawinstance of Raw

The raw object with data.

Notes

This function will load raw data if it was not already preloaded. If data were already preloaded, it will do nothing.

New in version 0.10.0.

property n_times

Number of time points.

notch_filter(self, freqs, picks=None, filter_length='auto', notch_widths=None, trans_bandwidth=1.0, n_jobs=1, method='fir', iir_params=None, mt_bandwidth=None, p_value=0.05, phase='zero', fir_window='hamming', fir_design='firwin', pad='reflect_limited', verbose=None)[source]

Notch filter a subset of channels.

Parameters
freqsfloat | array of float | None

Specific frequencies to filter out from data, e.g., np.arange(60, 241, 60) in the US or np.arange(50, 251, 50) in Europe. None can only be used with the mode ‘spectrum_fit’, where an F test is used to find sinusoidal components.

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.

notch_widthsfloat | array of float | None

Width of each stop band (centred at each freq in freqs) in Hz. If None, freqs / 200 is used.

trans_bandwidthfloat

Width of the transition band in Hz. 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().

mt_bandwidthfloat | None

The bandwidth of the multitaper windowing function in Hz. Only used in ‘spectrum_fit’ mode.

p_valuefloat

p-value to use in F-test thresholding to determine significant sinusoidal components to remove when method=’spectrum_fit’ and freqs=None. Note that this will be Bonferroni corrected for the number of frequencies, so large p-values may be justified.

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.

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

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). Defaults to self.verbose.

Returns
rawinstance of Raw

The raw instance with filtered data.

Notes

Applies a zero-phase notch filter to the channels selected by “picks”. By default the data of the Raw object is modified inplace.

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

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 details, see mne.filter.notch_filter().

Examples using notch_filter:

pick(self, 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.

Examples using pick:

pick_channels(self, ch_names)[source]

Pick some channels.

Parameters
ch_nameslist

The list of channels to select.

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(self, 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, dipole=False, gof=False, bio=False, ecog=False, fnirs=False, include=(), exclude='bads', selection=None, verbose=None)[source]

Pick some channels by type and names.

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

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_meg: bool | str

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

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

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). 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(self, events=None, duration=10.0, start=0.0, n_channels=20, bgcolor='w', color=None, bad_color=(0.8, 0.8, 0.8), event_color='cyan', scalings=None, remove_dc=True, order=None, show_options=False, title=None, show=True, block=False, highpass=None, lowpass=None, filtorder=4, clipping=None, show_first_samp=False, proj=True, group_by='type', butterfly=False, decim='auto', noise_cov=None, event_id=None, show_scrollbars=True, verbose=None)[source]

Plot raw data.

Parameters
eventsarray | None

Events to show with vertical bars.

durationfloat

Time window (s) to plot. The lesser of this value and the duration of the raw file will be used.

startfloat

Initial time to show (can be changed dynamically once plotted). If show_first_samp is True, then it is taken relative to raw.first_samp.

n_channelsint

Number of channels to plot at once. Defaults to 20. The lesser of n_channels and len(raw.ch_names) will be shown. Has no effect if order is ‘position’, ‘selection’ or ‘butterfly’.

bgcolorcolor object

Color of the background.

colordict | color object | None

Color for the data traces. If None, defaults to:

dict(mag='darkblue', grad='b', eeg='k', eog='k', ecg='m',
     emg='k', ref_meg='steelblue', misc='k', stim='k',
     resp='k', chpi='k')
bad_colorcolor object

Color to make bad channels.

event_colorcolor object | dict

Color to use for events. Can also be a dict with {event_number: color} pairings. Use event_number==-1 for any event numbers in the events list that are not in the dictionary.

scalingsdict | 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 times 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=1e2)
remove_dcbool

If True remove DC component when plotting data.

orderarray of int | None

Order in which to plot data. If the array is shorter than the number of channels, only the given channels are plotted. If None (default), all channels are plotted. If group_by is 'position' or 'selection', the order parameter is used only for selecting the channels to be plotted.

show_optionsbool

If True, a dialog for options related to projection is shown.

titlestr | None

The title of the window. If None, and either the filename of the raw object or ‘<unknown>’ will be displayed as title.

showbool

Show figure if True.

blockbool

Whether to halt program execution until the figure is closed. Useful for setting bad channels on the fly by clicking on a line. May not work on all systems / platforms.

highpassfloat | None

Highpass to apply when displaying data.

lowpassfloat | None

Lowpass to apply when displaying data. If highpass > lowpass, a bandstop rather than bandpass filter will be applied.

filtorderint

Filtering order. 0 will use FIR filtering with MNE defaults. Other values will construct an IIR filter of the given order and apply it with filtfilt() (making the effective order twice filtorder). Filtering may produce some edge artifacts (at the left and right edges) of the signals during display.

Changed in version 0.18: Support for filtorder=0 to use FIR filtering.

clippingstr | None

If None, channels are allowed to exceed their designated bounds in the plot. If “clamp”, then values are clamped to the appropriate range for display, creating step-like artifacts. If “transparent”, then excessive values are not shown, creating gaps in the traces.

show_first_sampbool

If True, show time axis relative to the raw.first_samp.

projbool

Whether to apply projectors prior to plotting (default is True). Individual projectors can be enabled/disabled interactively (see Notes). This argument only affects the plot; use raw.apply_proj() to modify the data stored in the Raw object.

group_bystr

How to group channels. 'type' groups by channel type, 'original' plots in the order of ch_names, 'selection' uses Elekta’s channel groupings (only works for Neuromag data), 'position' groups the channels by the positions of the sensors. 'selection' and 'position' modes allow custom selections by using lasso selector on the topomap. Pressing ctrl key while selecting allows appending to the current selection. Channels marked as bad appear with red edges on the topomap. 'type' and 'original' groups the channels by type in butterfly mode whereas 'selection' and 'position' use regional grouping. 'type' and 'original' modes are overridden with order keyword.

butterflybool

Whether to start in butterfly mode. 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 least three times larger than min(info['lowpass'], lowpass) (e.g., a 40 Hz lowpass will result in at least a 120 Hz displayed sample rate).

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.

event_iddict | None

Event IDs used to show at event markers (default None shows theh event numbers).

New in version 0.16.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.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more).

Returns
figinstance of matplotlib.figure.Figure

Raw traces.

Notes

The arrow keys (up/down/left/right) can typically be used to navigate between channels and time ranges, but this depends on the backend matplotlib is configured to use (e.g., mpl.use(‘TkAgg’) should work). The left/right arrows will scroll by 25% of duration, whereas shift+left/shift+right will scroll by 100% of duration. The scaling can be adjusted with - and + (or =) keys. The viewport dimensions can be adjusted with page up/page down and home/end keys. Full screen mode can be toggled with the F11 key. To mark or un-mark a channel as bad, click on a channel label or a channel trace. The changes will be reflected immediately in the raw object’s raw.info['bads'] entry.

If projectors are present, a button labelled “Proj” in the lower right corner of the plot window opens a secondary control window, which allows enabling/disabling specific projectors individually. This provides a means of interactively observing how each projector would affect the raw data if it were applied.

Annotation mode is toggled by pressing ‘a’, butterfly mode by pressing ‘b’, and whitening mode (when noise_cov is not None) by pressing ‘w’. By default, the channel means are removed when remove_dc is set to True. This flag can be toggled by pressing ‘d’.

Examples using plot:

plot_projs_topomap(self, ch_type=None, layout=None, axes=None)[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.

layoutNone | Layout | list of 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. Or a list of Layout if projections are from different sensor types.

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.

Returns
figinstance of Figure

Figure distributing one image per channel across sensor topography.

Examples using plot_projs_topomap:

plot_psd(self, fmin=0, fmax=inf, tmin=None, tmax=None, proj=False, n_fft=None, n_overlap=0, reject_by_annotation=True, 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, 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.

n_fftint | None

Number of points to use in Welch FFT calculations. Default is None, which uses the minimum of 2048 and the number of time points.

n_overlapint

The number of points of overlap between blocks. The default value is 0 (no overlap).

reject_by_annotationbool

Whether to omit bad segments from the data while computing the PSD. If True, annotated segments with a description that starts with ‘bad’ are omitted. Has no effect if inst is an Epochs or Evoked object. Defaults to True.

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.xscale=xscale,

spatial_colorsbool

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

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more).

Returns
figinstance of Figure

Figure with frequency spectra of the data channels.

Examples using plot_psd:

plot_psd_topo(self, tmin=0.0, tmax=None, fmin=0, fmax=100, proj=False, n_fft=2048, n_overlap=0, layout=None, color='w', fig_facecolor='k', axis_facecolor='k', dB=True, show=True, block=False, n_jobs=1, axes=None, verbose=None)[source]

Plot channel-wise frequency spectra as topography.

Parameters
tminfloat

Start time for calculations. Defaults to zero.

tmaxfloat | None

End time for calculations. If None (default), the end of data is used.

fminfloat

Start frequency to consider. Defaults to zero.

fmaxfloat

End frequency to consider. Defaults to 100.

projbool

Apply projection. Defaults to False.

n_fftint

Number of points to use in Welch FFT calculations. Defaults to 2048.

n_overlapint

The number of points of overlap between blocks. Defaults to 0 (no overlap).

layoutinstance of Layout | None

Layout instance specifying sensor positions (does not need to be specified for Neuromag data). If None (default), the correct layout is inferred from the data.

colorstr | tuple

A matplotlib-compatible color to use for the curves. Defaults to white.

fig_facecolorstr | tuple

A matplotlib-compatible color to use for the figure background. Defaults to black.

axis_facecolorstr | tuple

A matplotlib-compatible color to use for the axis background. Defaults to black.

dBbool

If True, transform data to decibels. Defaults to True.

showbool

Show figure if True. Defaults to True.

blockbool

Whether to halt program execution until the figure is closed. May not work on all systems / platforms. Defaults to False.

n_jobsint

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

axesinstance of matplotlib Axes | None

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

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more).

Returns
figinstance of matplotlib.figure.Figure

Figure distributing one image per channel across sensor topography.

Examples using plot_psd_topo:

plot_sensors(self, kind='topomap', ch_type=None, title=None, show_names=False, ch_groups=None, to_sphere=True, axes=None, block=False, show=True)[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.

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:

property proj

Whether or not projections are active.

rename_channels(self, 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 (new in version 0.10.0).

Notes

New in version 0.9.0.

Examples using rename_channels:

reorder_channels(self, 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(self, sfreq, npad='auto', window='boxcar', stim_picks=None, n_jobs=1, events=None, pad='reflect_limited', verbose=None)[source]

Resample all channels.

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

Warning

The intended purpose of this function is primarily to speed up computations (e.g., projection calculation) when precise timing of events is not required, as downsampling raw data effectively jitters trigger timings. It is generally recommended not to epoch downsampled data, but instead epoch and then downsample, as epoching downsampled data jitters triggers. For more, see this illustrative gist.

If resampling the continuous data is desired, it is recommended to construct events using the original data. The event onsets can be jointly resampled with the raw data using the ‘events’ parameter (a resampled copy is returned).

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

stim_pickslist of int | None

Stim channels. These channels are simply subsampled or supersampled (without applying any filtering). This reduces resampling artifacts in stim channels, but may lead to missing triggers. If None, stim channels are automatically chosen using mne.pick_types().

n_jobsint | str

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

events2D array, shape (n_events, 3) | None

An optional event matrix. When specified, the onsets of the events are resampled jointly with the data. NB: The input events are not modified, but a new array is returned with the raw instead.

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

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). Defaults to self.verbose.

Returns
rawinstance of Raw

The resampled version of the raw object.

eventsarray, shape (n_events, 3) | None

If events are jointly resampled, these are returned with the raw.

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(self, fname, picks=None, tmin=0, tmax=None, buffer_size_sec=None, drop_small_buffer=False, proj=False, fmt='single', overwrite=False, split_size='2GB', split_naming='neuromag', verbose=None)[source]

Save raw data to file.

Parameters
fnamestr

File name of the new dataset. This has to be a new filename unless data have been preloaded. Filenames should end with raw.fif, raw.fif.gz, raw_sss.fif, raw_sss.fif.gz, raw_tsss.fif, raw_tsss.fif.gz, or _meg.fif.

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.

tminfloat | None

Time in seconds of first sample to save. If None first sample is used.

tmaxfloat | None

Time in seconds of last sample to save. If None last sample is used.

buffer_size_secfloat | None

Size of data chunks in seconds. If None (default), the buffer size of the original file is used.

drop_small_bufferbool

Drop or not the last buffer. It is required by maxfilter (SSS) that only accepts raw files with buffers of the same size.

projbool

If True the data is saved with the projections applied (active).

Note

If apply_proj() was used to apply the projections, the projectons will be active even if proj is False.

fmt‘single’ | ‘double’ | ‘int’ | ‘short’

Format to use to save raw data. Valid options are ‘double’, ‘single’, ‘int’, and ‘short’ for 64- or 32-bit float, or 32- or 16-bit integers, respectively. It is strongly recommended to use ‘single’, as this is backward-compatible, and is standard for maintaining precision. Note that using ‘short’ or ‘int’ may result in loss of precision, complex data cannot be saved as ‘short’, and neither complex data types nor real data stored as ‘double’ can be loaded with the MNE command-line tools. See raw.orig_format to determine the format the original data were stored in.

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.

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.

split_naming{‘neuromag’ | ‘bids’}

Add the filename partition with the appropriate naming schema.

New in version 0.17.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). Defaults to self.verbose.

Notes

If Raw is a concatenation of several raw files, be warned that only the measurement information from the first raw file is stored. This likely means that certain operations with external tools may not work properly on a saved concatenated file (e.g., probably some or all forms of SSS). It is recommended not to concatenate and then save raw files for this reason.

Examples using save:

savgol_filter(self, 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 [1] 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). 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

1

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_annotations(self, annotations, emit_warning=True)[source]

Setter for annotations.

This setter checks if they are inside the data range.

Parameters
annotationsinstance of mne.Annotations | None

Annotations to set. If None, the annotations is defined but empty.

emit_warningbool

Whether to emit warnings when limiting or omitting annotations.

Returns
selfinstance of Raw

The raw object with annotations.

Examples using set_annotations:

set_channel_types(self, mapping)[source]

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, hbo, hbr

Parameters
mappingdict

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

Notes

New in version 0.9.0.

Examples using set_channel_types:

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

Specify which reference to use for EEG data.

By default, MNE-Python will automatically re-reference the EEG signal to use an average reference (see below). 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 and prevent MNE-Python from automatically adding an average reference projection.

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

No re-referencing:

If the EEG data is already using the proper reference, set ref_channels=[]. This will prevent MNE-Python from automatically adding an average reference projection.

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

Parameters
ref_channelslist of str | str

The name(s) of the channel(s) used to construct the reference. To apply an average reference, specify 'average' here (default). If an empty list is specified, the data is assumed to already have a proper reference and MNE will not attempt any re-referencing of the data. Defaults to an average reference.

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.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). 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

  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 reference, bad EEG channels are automatically excluded if they are properly set in info['bads'].

New in version 0.9.0.

Examples using set_eeg_reference:

set_montage(self, montage, set_dig=<object object at 0x7f4a8e2ea1b0>, raise_if_subset=<object object at 0x7f4a8e2ea1b0>, 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.

set_digbool

If True, update the digitization information (info['dig']) in addition to the channel positions (info['chs'][idx]['loc']).

Deprecated. This parameter will be removed in 0.20.

raise_if_subset: bool

If True, ValueError will be raised when montage.ch_names is a subset of info[‘ch_names’]. This parameter was introduced for backward compatibility when set to False.

Defaults to False in 0.19, it will change to default to True in 0.20, and will be removed in 0.21.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() and Logging documentation for more). Defaults to self.verbose.

Notes

Operates in place.

New in version 0.9.0.

Examples using set_montage:

time_as_index(self, times, use_rounding=False, origin=None)[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.

origin: time-like | float | int | None

Time reference for times. If None, times are assumed to be relative to first_samp.

New in version 0.17.0.

Returns
indexndarray

Indices relative to first_samp corresponding to the times supplied.

Examples using time_as_index:

property times

Time points.

to_data_frame(self, picks=None, index=None, scaling_time=1000.0, scalings=None, copy=True, start=None, stop=None, long_format=False)[source]

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

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

scaling_timefloat

Scaling to be applied to time units.

scalingsdict | None

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

copybool

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

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

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

long_formatbool

If True, the dataframe is returned in long format where each row is one observation of the signal at a unique coordinate of channels, time points, epochs and conditions. The number of factors depends on the data container. For convenience, a ch_type column is added when using this option that will facilitate subsetting the resulting dataframe. Defaults to False.

Returns
dfinstance of pandas.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.

Examples using to_data_frame:

Examples using mne.io.Raw