mne.io.RawFIF

class mne.io.RawFIF(fnames, allow_maxshield=False, preload=False, proj=False, compensation=None, add_eeg_ref=True, verbose=None)

Raw data

Parameters:

fnames : list, or string

A list of the raw files to treat as a Raw instance, or a single raw file. For files that have automatically been split, only the name of the first file has to be specified. Filenames should end with raw.fif, raw.fif.gz, raw_sss.fif, raw_sss.fif.gz, raw_tsss.fif or raw_tsss.fif.gz.

allow_maxshield : bool, (default False)

allow_maxshield if True, allow loading of data that has been processed with Maxshield. Maxshield-processed data should generally not be loaded directly, but should be processed using SSS first.

preload : bool 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).

proj : bool

Apply the signal space projection (SSP) operators present in the file to the data. Note: Once the projectors have been applied, they can no longer be removed. It is usually not recommended to apply the projectors at this point as they are applied automatically later on (e.g. when computing inverse solutions).

compensation : None | int

If None the compensation in the data is not modified. If set to n, e.g. 3, apply gradient compensation of grade n as for CTF systems.

add_eeg_ref : bool

If True, add average EEG reference projector (if it’s not already present).

verbose : bool, str, int, or None

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

Attributes:

info : dict

Measurement info.

ch_names : list of string

List of channels’ names.

n_times : int

Total number of time points in the raw file.

preload : bool

Indicates whether raw data are in memory.

verbose : bool, str, int, or None

See above.

Methods

add_channels(add_list[, copy]) Append new channels to the instance.
add_eeg_average_proj() Add an average EEG reference projector if one does not exist
add_events(events[, stim_channel]) Add events to stim channel
add_proj(projs[, remove_existing]) Add SSP projection vectors
anonymize() Anonymize data
append(raws[, preload]) Concatenate raw instances as if they were continuous
apply_function(fun, picks, dtype, n_jobs, ...) Apply a function to a subset of channels.
apply_hilbert(picks[, envelope, n_jobs, ...]) Compute analytic signal or envelope for a subset of channels.
apply_proj() Apply the signal space projection (SSP) operators to the data.
close() Clean up the object.
copy() Return copy of Raw instance
crop([tmin, tmax, copy]) Crop raw data file.
del_proj(idx) Remove SSP projection vector
drop_channels(ch_names[, copy]) Drop some channels
estimate_rank([tstart, tstop, tol, ...]) Estimate rank of the raw data
filter(l_freq, h_freq[, picks, ...]) Filter a subset of channels.
fix_mag_coil_types() Fix Elekta magnetometer coil types
index_as_time(index[, use_first_samp]) Convert indices to time
interpolate_bads([reset_bads, mode]) Interpolate bad MEG and EEG channels.
load_bad_channels([bad_file, force]) Mark channels as bad from a text file, in the style
load_data([verbose]) Load raw data
notch_filter(freqs[, picks, filter_length, ...]) Notch filter a subset of channels.
pick_channels(ch_names[, copy]) Pick some channels
pick_types([meg, eeg, stim, eog, ecg, emg, ...]) Pick some channels by type and names
plot([events, duration, start, n_channels, ...]) Plot raw data
plot_projs_topomap([ch_type, layout, axes]) Plot SSP vector
plot_psd([tmin, tmax, fmin, fmax, proj, ...]) Plot the power spectral density across channels
plot_psd_topo([tmin, tmax, fmin, fmax, ...]) Function for plotting channel wise frequency spectra as topography.
rename_channels(mapping) Rename channels.
resample(sfreq[, npad, window, stim_picks, ...]) Resample data channels.
save(fname[, picks, tmin, tmax, ...]) Save raw data to file
set_channel_types(mapping) Define the sensor type of channels.
set_montage(montage) Set EEG sensor configuration
time_as_index(times[, use_first_samp, ...]) Convert time to indices
to_data_frame([picks, index, scale_time, ...]) Export data in tabular structure as a pandas DataFrame.
__init__(fnames, allow_maxshield=False, preload=False, proj=False, compensation=None, add_eeg_ref=True, verbose=None)
add_channels(add_list, copy=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

Whether to return a new instance or modify in place

Returns:

out : MNE object of type(self)

An object with new channels appended (will be the same object if copy==False)

add_eeg_average_proj()

Add an average EEG reference projector if one does not exist

add_events(events, stim_channel=None)

Add events to stim channel

Parameters:

events : ndarray, 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_channel : str | 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’.

Notes

Data must be preloaded in order to add events.

add_proj(projs, remove_existing=False)

Add SSP projection vectors

Parameters:

projs : list

List with projection vectors.

remove_existing : bool

Remove the projection vectors currently in the file.

Returns:

self : instance of Raw | Epochs | Evoked

The data container.

anonymize()

Anonymize data

This function will remove info[‘subject_info’] if it exists.

Returns:

raw : instance of Raw

The raw object. Operates in place.

append(raws, preload=None)

Concatenate raw instances as if they were continuous

Parameters:

raws : list, or Raw instance

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

preload : bool, 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.

apply_function(fun, picks, dtype, n_jobs, *args, **kwargs)

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 be constructed using preload=True (or string).

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:

fun : function

A function to be applied to the channels. The first argument of fun has to be a timeseries (numpy.ndarray). The function must return an numpy.ndarray with the same size as the input.

picks : array-like of int | None

Indices of channels to apply the function to. If None, all M-EEG channels are used.

dtype : numpy.dtype

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

n_jobs: int :

Number of jobs to run in parallel.

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

apply_hilbert(picks, envelope=False, n_jobs=1, n_fft=None, verbose=None)

Compute analytic signal or envelope for a subset of channels.

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.

Note: DO NOT use envelope=True if you intend to compute an inverse
solution from the raw data. If you want to compute the envelope in source space, use envelope=False and compute the envelope after the inverse solution has been obtained.
Note: 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.
Note: If n_jobs > 1 and envelope=True, more memory is required as
“len(picks) * n_times” additional time points need to be temporaily stored in memory.
Parameters:

picks : array-like of int

Indices of channels to apply the function to.

envelope : bool (default: False)

Compute the envelope signal of each channel.

n_jobs: int :

Number of jobs to run in parallel.

n_fft : int > self.n_times | None

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.

verbose : bool, str, int, or None

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

Notes

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.

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.

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
ch_names

Channel names

close()

Clean up the object.

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

copy()

Return copy of Raw instance

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

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. And data are modified in-place when called with copy=False.

Parameters:

tmin : float

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

tmax : float | None

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

copy : bool

If False Raw is cropped in place.

Returns:

raw : instance of Raw

The cropped raw object.

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_channels(ch_names, copy=False)

Drop some channels

Parameters:

ch_names : list

The list of channels to remove.

copy : bool

If True, returns new instance. Else, modifies in place. Defaults to False.

See also

pick_channels

Notes

New in version 0.9.0.

estimate_rank(tstart=0.0, tstop=30.0, tol=0.0001, return_singular=False, picks=None, scalings='norm')

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:

tstart : float

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

tstop : float | None

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

tol : float

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_singular : bool

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

picks : array_like of int, shape (n_selected_channels,)

The channels to be considered for rank estimation. If None (default) meg and eeg channels are included.

scalings : dict | ‘norm’

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. Defaults to ‘norm’.

Returns:

rank : int

Estimated rank of the data.

s : array

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.

filter(l_freq, h_freq, picks=None, filter_length='10s', l_trans_bandwidth=0.5, h_trans_bandwidth=0.5, n_jobs=1, method='fft', iir_params=None, verbose=None)

Filter a subset of channels.

Applies a zero-phase low-pass, high-pass, band-pass, or band-stop filter to the channels selected by “picks”. The data of the Raw object is modified inplace.

The Raw object has to be constructed using preload=True (or string).

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

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

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

Parameters:

l_freq : float | None

Low cut-off frequency in Hz. If None the data are only low-passed.

h_freq : float | None

High cut-off frequency in Hz. If None the data are only high-passed.

picks : array-like of int | None

Indices of channels to filter. If None only the data (MEG/EEG) channels will be filtered.

filter_length : str (Default: ‘10s’) | int | None

Length of the filter to use. If None or “len(x) < filter_length”, the filter length used is len(x). Otherwise, if int, overlap-add filtering with a filter of the specified length in samples) is used (faster for long signals). If str, a human-readable time in units of “s” or “ms” (e.g., “10s” or “5500ms”) will be converted to the shortest power-of-two length at least that duration. Not used for ‘iir’ filters.

l_trans_bandwidth : float

Width of the transition band at the low cut-off frequency in Hz (high pass or cutoff 1 in bandpass). Not used if ‘order’ is specified in iir_params.

h_trans_bandwidth : float

Width of the transition band at the high cut-off frequency in Hz (low pass or cutoff 2 in bandpass). Not used if ‘order’ is specified in iir_params.

n_jobs : int | str

Number of jobs to run in parallel. Can be ‘cuda’ if scikits.cuda is installed properly, CUDA is initialized, and method=’fft’.

method : str

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

iir_params : dict | None

Dictionary of parameters to use for IIR filtering. See mne.filter.construct_iir_filter for details. If iir_params is None and method=”iir”, 4th order Butterworth will be used.

verbose : bool, str, int, or None

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

fix_mag_coil_types()

Fix Elekta magnetometer coil types

Returns:

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

index_as_time(index, use_first_samp=False)

Convert indices to time

Parameters:

index : list-like | int

List of ints or int representing points in time.

use_first_samp : boolean

If True, the time returned is relative to the session onset, else relative to the recording onset.

Returns:

times : ndarray

Times corresponding to the index supplied.

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:

self : mne.io.Raw, mne.Epochs or mne.Evoked

The interpolated data.

Notes

New in version 0.9.0.

load_bad_channels(bad_file=None, force=False)

Mark channels as bad from a text file, in the style (mostly) of the C function mne_mark_bad_channels

Parameters:

bad_file : string

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’] = [].

force : boolean

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

load_data(verbose=None)

Load raw data

Parameters:

verbose : bool, str, int, or None

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

Returns:

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

n_times

Number of time points

notch_filter(freqs, picks=None, filter_length='10s', notch_widths=None, trans_bandwidth=1.0, n_jobs=1, method='fft', iir_params=None, mt_bandwidth=None, p_value=0.05, verbose=None)

Notch filter a subset of channels.

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

The Raw object has to be constructed using preload=True (or string).

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

freqs : float | 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.

picks : array-like of int | None

Indices of channels to filter. If None only the data (MEG/EEG) channels will be filtered.

filter_length : str (Default: ‘10s’) | int | None

Length of the filter to use. If None or “len(x) < filter_length”, the filter length used is len(x). Otherwise, if int, overlap-add filtering with a filter of the specified length in samples) is used (faster for long signals). If str, a human-readable time in units of “s” or “ms” (e.g., “10s” or “5500ms”) will be converted to the shortest power-of-two length at least that duration. Not used for ‘iir’ filters.

notch_widths : float | array of float | None

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

trans_bandwidth : float

Width of the transition band in Hz.

n_jobs : int | str

Number of jobs to run in parallel. Can be ‘cuda’ if scikits.cuda is installed properly, CUDA is initialized, and method=’fft’.

method : str

‘fft’ will use overlap-add FIR filtering, ‘iir’ will use IIR forward-backward filtering (via filtfilt). ‘spectrum_fit’ will use multi-taper estimation of sinusoidal components.

iir_params : dict | None

Dictionary of parameters to use for IIR filtering. See mne.filter.construct_iir_filter for details. If iir_params is None and method=”iir”, 4th order Butterworth will be used.

mt_bandwidth : float | None

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

p_value : float

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.

verbose : bool, str, int, or None

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

Notes

For details, see mne.filter.notch_filter.

pick_channels(ch_names, copy=False)

Pick some channels

Parameters:

ch_names : list

The list of channels to select.

copy : bool

If True, returns new instance. Else, modifies in place. Defaults to False.

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, include=[], exclude='bads', selection=None, copy=False)

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.

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

If True, returns new instance. Else, modifies in place. Defaults to False.

Notes

New in version 0.9.0.

plot(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='type', show_options=False, title=None, show=True, block=False, highpass=None, lowpass=None, filtorder=4, clipping=None)

Plot raw data

Parameters:

events : array | None

Events to show with vertical bars.

duration : float

Time window (sec) to plot in a given time.

start : float

Initial time to show (can be changed dynamically once plotted).

n_channels : int

Number of channels to plot at once. Defaults to 20.

bgcolor : color object

Color of the background.

color : dict | color object | None

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

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

bad_color : color object

Color to make bad channels.

event_color : color object

Color to use for events.

scalings : dict | None

Scale factors for the traces. 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)

remove_dc : bool

If True remove DC component when plotting data.

order : ‘type’ | ‘original’ | array

Order in which to plot data. ‘type’ groups by channel type, ‘original’ plots in the order of ch_names, array gives the indices to use in plotting.

show_options : bool

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

title : str | None

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

show : bool

Show figures if True

block : bool

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

highpass : float | None

Highpass to apply when displaying data.

lowpass : float | None

Lowpass to apply when displaying data.

filtorder : int

Filtering order. Note that for efficiency and simplicity, filtering during plotting uses forward-backward IIR filtering, so the effective filter order will be twice filtorder. Filtering the lines for display may also produce some edge artifacts (at the left and right edges) of the signals during display. Filtering requires scipy >= 0.10.

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

Returns:

fig : Instance 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 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 to toggled with f11 key. To mark or un-mark a channel as bad, click on the rather flat segments of a channel’s time series. The changes will be reflected immediately in the raw object’s raw.info['bads'] entry.

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(tmin=0.0, tmax=60.0, fmin=0, fmax=inf, proj=False, n_fft=2048, picks=None, ax=None, color='black', area_mode='std', area_alpha=0.33, n_overlap=0, dB=True, show=True, n_jobs=1, verbose=None)

Plot the power spectral density across channels

Parameters:

tmin : float

Start time for calculations.

tmax : float

End time for calculations.

fmin : float

Start frequency to consider.

fmax : float

End frequency to consider.

proj : bool

Apply projection.

n_fft : int

Number of points to use in Welch FFT calculations.

picks : array-like of int | None

List of channels to use. 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).

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

How to plot 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.

n_overlap : int

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

dB : bool

If True, transform data to decibels.

show : bool

Call pyplot.show() at the end.

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

Returns:

fig : instance of matplotlib figure

Figure with frequency spectra of the data channels.

plot_psd_topo(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, n_jobs=1, verbose=None)

Function for plotting channel wise frequency spectra as topography.

Parameters:

tmin : float

Start time for calculations. Defaults to zero.

tmax : float | None

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

fmin : float

Start frequency to consider. Defaults to zero.

fmax : float

End frequency to consider. Defaults to 100.

proj : bool

Apply projection. Defaults to False.

n_fft : int

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

n_overlap : int

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

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

color : str | tuple

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

fig_facecolor : str | tuple

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

axis_facecolor : str | tuple

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

dB : bool

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

show : bool

Show figure if True. Defaults to True.

n_jobs : int

Number of jobs to run in parallel. Defaults to 1.

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.

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=100, window='boxcar', stim_picks=None, n_jobs=1, events=None, copy=False, verbose=None)

Resample data channels.

Resamples all channels.

The Raw object has to be constructed using preload=True (or string).

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. See here for an example:

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.

Parameters:

sfreq : float

New sample rate to use.

npad : int

Amount to pad the start and end of the data.

window : string or tuple

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

stim_picks : array 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(raw.info, meg=False, stim=True, exclude=[]).

n_jobs : int | str

Number of jobs to run in parallel. Can be ‘cuda’ if scikits.cuda is installed properly and CUDA is initialized.

events : 2D array, shape (n_events, 3) | None

An optional event matrix. When specified, the onsets of the events are resampled jointly with the data.

copy : bool

Whether to operate on a copy of the data (True) or modify data in-place (False). Defaults to False.

verbose : bool, str, int, or None

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

Returns:

raw : instance of Raw

The resampled version of the raw 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, picks=None, tmin=0, tmax=None, buffer_size_sec=10, drop_small_buffer=False, proj=False, fmt='single', overwrite=False, split_size='2GB', verbose=None)

Save raw data to file

Parameters:

fname : string

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 or raw_tsss.fif.gz.

picks : array-like of int | None

Indices of channels to include. If None all channels are kept.

tmin : float | None

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

tmax : float | None

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

buffer_size_sec : float | None

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

drop_small_buffer : bool

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

proj : bool

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

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.

overwrite : bool

If True, the destination file (if it exists) will be overwritten. If False (default), an error will be raised if the file exists.

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.

verbose : bool, str, int, or None

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

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

Set EEG sensor configuration

Parameters:montage : instance of Montage or DigMontage

Notes

Operates in place.

New in version 0.9.0.

time_as_index(times, use_first_samp=False, use_rounding=False)

Convert time to indices

Parameters:

times : list-like | float | int

List of numbers or a number representing points in time.

use_first_samp : boolean

If True, time is treated as relative to the session onset, else as relative to the recording onset.

use_rounding : boolean

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

Returns:

index : ndarray

Indices corresponding to the times supplied.

times

Time points

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.