mne.io.Raw#
- class mne.io.Raw(fname, allow_maxshield=False, preload=False, on_split_missing='raise', verbose=None)[source]#
Raw data in FIF format.
- Parameters:
- fname
str| file-like The raw filename to load. For files that have automatically been split, the split part will be automatically loaded. Filenames not ending with
raw.fif,raw_sss.fif,raw_tsss.fif,_meg.fif,_eeg.fif, or_ieeg.fif(with or without an optional additional.gzextension) will generate a warning. If a file-like object is provided, preloading must be used.Changed in version 0.18: Support for file-like objects.
- allow_maxshield
bool|str(defaultFalse) 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.
- preload
boolorstr(defaultFalse) 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).
- on_split_missing
str Can be
'raise'(default) to raise an error,'warn'to emit a warning, or'ignore'to ignore when split file is missing.New in version 0.22.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- fname
- Attributes:
- info
mne.Info The
mne.Infoobject with information about the sensors and methods of measurement.ch_nameslistofstrChannel names.
n_timesintNumber of time points.
timesndarrayTime points.
- preload
bool Indicates whether raw data are in memory.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- info
Methods
__contains__(ch_type)Check channel type membership.
__getitem__(item)Get raw data and times.
__len__()Return the number of time points.
add_channels(add_list[, force_update_info])Append new channels to the instance.
add_events(events[, stim_channel, replace])Add events to stim channel.
add_proj(projs[, remove_existing, verbose])Add SSP projection vectors.
add_reference_channels(ref_channels)Add reference channels to data that consists of all zeros.
anonymize([daysback, keep_his, verbose])Anonymize measurement information in place.
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_gradient_compensation(grade[, verbose])Apply CTF gradient compensation.
apply_hilbert([picks, envelope, n_jobs, ...])Compute analytic signal or envelope for a subset of channels.
apply_proj([verbose])Apply the signal space projection (SSP) operators to the data.
close()Clean up the object.
compute_psd([method, fmin, fmax, tmin, ...])Perform spectral analysis on sensor data.
copy()Return copy of Raw instance.
crop([tmin, tmax, include_tmax, verbose])Crop raw data file.
crop_by_annotations([annotations, verbose])Get crops of raw data file for selected annotations.
decimate(decim[, offset, verbose])Decimate the time-series data.
del_proj([idx])Remove SSP projection vector.
describe([data_frame])Describe channels (name, type, descriptive statistics).
drop_channels(ch_names[, on_missing])Drop channel(s).
export(fname[, fmt, physical_range, ...])Export Raw to external formats.
filter(l_freq, h_freq[, picks, ...])Filter a subset of channels.
Fix Elekta magnetometer coil types.
get_channel_types([picks, unique, only_data_chs])Get a list of channel type for each channel.
get_data([picks, start, stop, ...])Get data in the given range.
Get a DigMontage from instance.
interpolate_bads([reset_bads, mode, origin, ...])Interpolate bad MEG and EEG channels.
load_bad_channels([bad_file, force, verbose])Mark channels as bad from a text file.
load_data([verbose])Load raw data.
notch_filter(freqs[, picks, filter_length, ...])Notch filter a subset of channels.
pick(picks[, exclude, verbose])Pick a subset of channels.
pick_channels(ch_names[, ordered, verbose])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, sensors, ...])Plot SSP vector.
plot_psd([fmin, fmax, tmin, tmax, picks, ...])Warning
LEGACY: New code should use .compute_psd().plot().
plot_psd_topo([tmin, tmax, fmin, fmax, ...])Warning
LEGACY: New code should use .compute_psd().plot_topo().
plot_psd_topomap([bands, tmin, tmax, ...])Warning
LEGACY: New code should use .compute_psd().plot_topomap().
plot_sensors([kind, ch_type, title, ...])Plot sensor positions.
rename_channels(mapping[, allow_duplicates, ...])Rename channels.
reorder_channels(ch_names)Reorder channels.
resample(sfreq[, npad, window, stim_picks, ...])Resample all channels.
save(fname[, picks, tmin, tmax, ...])Save raw data to file.
savgol_filter(h_freq[, verbose])Filter the data using Savitzky-Golay polynomial method.
set_annotations(annotations[, emit_warning, ...])Setter for annotations.
set_channel_types(mapping[, verbose])Define the sensor type of channels.
set_eeg_reference([ref_channels, ...])Specify which reference to use for EEG data.
set_meas_date(meas_date)Set the measurement start date.
set_montage(montage[, match_case, ...])Set EEG/sEEG/ECoG/DBS/fNIRS channel positions and digitization points.
shift_time(tshift[, relative])Shift time scale in epoched or evoked data.
time_as_index(times[, use_rounding, origin])Convert time to indices.
to_data_frame([picks, index, scalings, ...])Export data in tabular structure as a pandas DataFrame.
- __contains__(ch_type)[source]#
Check channel type membership.
- Parameters:
- ch_type
str Channel type to check for. Can be e.g. ‘meg’, ‘eeg’, ‘stim’, etc.
- ch_type
- Returns:
- in
bool Whether or not the instance contains the given channel type.
- in
Examples
Channel type membership can be tested as:
>>> 'meg' in inst True >>> 'seeg' in inst False
- __getitem__(item)[source]#
Get raw data and times.
- Parameters:
- item
tupleor array_like See below for use cases.
- item
- Returns:
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]]
- __len__()[source]#
Return the number of time points.
- Returns:
- len
int The number of time points.
- len
Examples
This can be used as:
>>> len(raw) 1000
- property acqparser#
The AcqParserFIF for the measurement info.
See also
- add_channels(add_list, force_update_info=False)[source]#
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.
- force_update_info
bool If True, force the info for objects to be appended to match the values in
self. This should generally only be used when adding stim channels for which important metadata won’t be overwritten.New in version 0.12.
- add_list
- Returns:
See also
Notes
If
selfis a Raw instance that has been preloaded into anumpy.memmapinstance, the memmap will be resized.Examples using
add_channels:
- add_events(events, stim_channel=None, replace=False)[source]#
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’.
- replace
bool If True the old events on the stim channel are removed before adding the new ones.
- events
Notes
Data must be preloaded in order to add events.
Examples using
add_events:
- add_proj(projs, remove_existing=False, verbose=None)[source]#
Add SSP projection vectors.
- Parameters:
- projs
list List with projection vectors.
- remove_existing
bool Remove the projection vectors currently in the file.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- projs
- Returns:
Examples using
add_proj:
- add_reference_channels(ref_channels)[source]#
Add reference channels to data that consists of all zeros.
Adds reference channels to data that were not included during recording. This is useful when you need to re-reference your data to different channels. These added channels will consist of all zeros.
- Parameters:
- Returns:
- property annotations#
Annotationsfor marking segments of data.
- anonymize(daysback=None, keep_his=False, verbose=None)[source]#
Anonymize measurement information in place.
- Parameters:
- daysback
int|None Number of days to subtract from all dates. If
None(default), the acquisition date,info['meas_date'], will be set toJanuary 1ˢᵗ, 2000. This parameter is ignored ifinfo['meas_date']isNone(i.e., no acquisition date has been set).- keep_his
bool If
True,his_idofsubject_infowill not be overwritten. Defaults toFalse.Warning
This could mean that
infois not fully anonymized. Use with caution.- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- daysback
- Returns:
Notes
Removes potentially identifying information if it exists in
info. Specifically for each of the following we use:- meas_date, file_id, meas_id
A default value, or as specified by
daysback.
- subject_info
Default values, except for ‘birthday’ which is adjusted to maintain the subject age.
- experimenter, proj_name, description
Default strings.
- utc_offset
None.
- proj_id
Zeros.
- proc_history
Dates use the
meas_datelogic, and experimenter a default string.
- helium_info, device_info
Dates use the
meas_datelogic, meta info uses defaults.
If
info['meas_date']isNone, it will remainNoneduring processing the above fields.Operates in place.
New in version 0.13.0.
- append(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:
- raws
list, orRawinstance List of Raw instances to concatenate to the current instance (in order), or a single raw instance to concatenate.
- preload
bool,str, orNone(defaultNone) 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 instances passed in.
- raws
Examples using
append:
- apply_function(fun, picks=None, dtype=None, n_jobs=None, channel_wise=True, verbose=None, **kwargs)[source]#
Apply a function to a subset of channels.
The function
funis applied to the channels defined inpicks. The raw object’s data is modified in-place. If the function returns a different data type (e.g.numpy.complex128) it must be specified using thedtypeparameter, which causes the data type of all the data to change (even if the function is only applied to channels inpicks). The object has to have the data loaded e.g. withpreload=Trueorself.load_data().Note
If
n_jobs> 1, more memory is required aslen(picks) * n_timesadditional time points need to be temporarily 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
callable() 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,)ifchannel_wise=Trueand(len(picks), n_times)otherwise. The function must return anndarrayshaped like its input.- picks
str| array_like |slice|None Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g.,
['meg', 'eeg']) will pick channels of those types, channel name strings (e.g.,['MEG0111', 'MEG2623']will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick all data channels (excluding reference MEG channels). Note that channels ininfo['bads']will be included if their names or indices are explicitly provided.- dtype
numpy.dtype Data type to use after applying the function. If None (default) the data type is not modified.
- n_jobs
int|None The number of jobs to run in parallel. If
-1, it is set to the number of CPU cores. Requires thejoblibpackage.None(default) is a marker for ‘unset’ that will be interpreted asn_jobs=1(sequential execution) unless the call is performed under ajoblib.parallel_backend()context manager that sets another value forn_jobs. Ignored ifchannel_wise=Falseas the workload is split across channels.- channel_wise
bool Whether to apply the function to each channel individually. If
False, the function will be applied to all channels at once. DefaultTrue.New in version 0.18.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.- **kwargs
dict Additional keyword arguments to pass to
fun.
- fun
- Returns:
- selfinstance of
Raw The raw object with transformed data.
- selfinstance of
Examples using
apply_function:
- apply_gradient_compensation(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:
- grade
int CTF gradient compensation level.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- grade
- Returns:
- rawinstance of
Raw The modified Raw instance. Works in-place.
- rawinstance of
- apply_hilbert(picks=None, envelope=False, n_jobs=None, n_fft='auto', *, verbose=None)[source]#
Compute analytic signal or envelope for a subset of channels.
- Parameters:
- picks
str| array_like |slice|None Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g.,
['meg', 'eeg']) will pick channels of those types, channel name strings (e.g.,['MEG0111', 'MEG2623']will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick all data channels (excluding reference MEG channels). Note that channels ininfo['bads']will be included if their names or indices are explicitly provided.- envelope
bool Compute the envelope signal of each channel. Default False. See Notes.
- n_jobs
int|None The number of jobs to run in parallel. If
-1, it is set to the number of CPU cores. Requires thejoblibpackage.None(default) is a marker for ‘unset’ that will be interpreted asn_jobs=1(sequential execution) unless the call is performed under ajoblib.parallel_backend()context manager that sets another value forn_jobs.- n_fft
int|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.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- picks
- Returns:
Notes
Parameters
If
envelope=False, the analytic signal for the channels defined inpicksis 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 inpicksis 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_timesadditional time points need to be temporarily stored in memory.Also note that the
n_fftparameter will allow you to pad the signal with zeros before performing the Hilbert transform. This padding is cut off, but it may result in a slightly different result (particularly around the edges). Use at your own risk.Analytic signal
The analytic signal “x_a(t)” of “x(t)” is:
x_a = F^{-1}(F(x) 2U) = x + i y
where “F” is the Fourier transform, “U” the unit step function, and “y” the Hilbert transform of “x”. One usage of the analytic signal is the computation of the envelope signal, which is given by “e(t) = abs(x_a(t))”. Due to the linearity of Hilbert transform and the MNE inverse solution, the enevlope in source space can be obtained by computing the analytic signal in sensor space, applying the MNE inverse, and computing the envelope in source space.
Examples using
apply_hilbert:
- apply_proj(verbose=None)[source]#
Apply the signal space projection (SSP) operators to the data.
- Parameters:
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- verbose
- Returns:
Notes
Once the projectors have been applied, they can no longer be removed. It is usually not recommended to apply the projectors at too early stages, as they are applied automatically later on (e.g. when computing inverse solutions). Hint: using the copy method individual projection vectors can be tested without affecting the original data. With evoked data, consider the following example:
projs_a = mne.read_proj('proj_a.fif') projs_b = mne.read_proj('proj_b.fif') # add the first, copy, apply and see ... evoked.add_proj(a).copy().apply_proj().plot() # add the second, copy, apply and see ... evoked.add_proj(b).copy().apply_proj().plot() # drop the first and see again evoked.copy().del_proj(0).apply_proj().plot() evoked.apply_proj() # finally keep both
Examples using
apply_proj:
- property ch_names#
Channel names.
- close()[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.
- compute_psd(method='welch', fmin=0, fmax=inf, tmin=None, tmax=None, picks=None, proj=False, reject_by_annotation=True, *, n_jobs=1, verbose=None, **method_kw)[source]#
Perform spectral analysis on sensor data.
- Parameters:
- method
'welch'|'multitaper' Spectral estimation method.
'welch'uses Welch’s method[1],'multitaper'uses DPSS tapers[2]. Default is'welch'.- fmin, fmax
float The lower- and upper-bound on frequencies of interest. Default is
fmin=0, fmax=np.inf(spans all frequencies present in the data).- tmin, tmax
float|None First and last times to include, in seconds.
Noneuses the first or last time present in the data. Default istmin=None, tmax=None(all times).- picks
str| array_like |slice|None Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g.,
['meg', 'eeg']) will pick channels of those types, channel name strings (e.g.,['MEG0111', 'MEG2623']will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick good data channels (excluding reference MEG channels). Note that channels ininfo['bads']will be included if their names or indices are explicitly provided.- proj
bool Whether to apply SSP projection vectors before spectral estimation. Default is
False.- reject_by_annotation
bool Whether to omit bad spans of data before spectral estimation. If
True, spans with annotations whose description begins withbadwill be omitted.- n_jobs
int|None The number of jobs to run in parallel. If
-1, it is set to the number of CPU cores. Requires thejoblibpackage.None(default) is a marker for ‘unset’ that will be interpreted asn_jobs=1(sequential execution) unless the call is performed under ajoblib.parallel_backend()context manager that sets another value forn_jobs.- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.- **method_kw
Additional keyword arguments passed to the spectral estimation function (e.g.,
n_fft, n_overlap, n_per_seg, average, windowfor Welch method, orbandwidth, adaptive, low_bias, normalizationfor multitaper method). Seepsd_array_welch()andpsd_array_multitaper()for details.
- method
- Returns:
- spectruminstance of
Spectrum The spectral representation of the data.
- spectruminstance of
Notes
New in version 1.2.
References
Examples using
compute_psd:
The Spectrum and EpochsSpectrum classes: frequency-domain data
The Spectrum and EpochsSpectrum classes: frequency-domain data
- copy()[source]#
Return copy of Raw instance.
- Returns:
- instinstance of
Raw A copy of the instance.
- instinstance of
Examples using
copy:
Signal-space separation (SSS) and Maxwell filtering
Signal-space separation (SSS) and Maxwell filtering
Plot sensor denoising using oversampled temporal projection
Plot sensor denoising using oversampled temporal projection
- crop(tmin=0.0, tmax=None, include_tmax=True, *, verbose=None)[source]#
Crop raw data file.
Limit the data from the raw file to go between specific times. Note that the new
tminis assumed to bet=0for all subsequently called functions (e.g.,time_as_index(), orEpochs). 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:
- tmin
float Start time of the raw data to use in seconds (must be >= 0).
- tmax
float End time of the raw data to use in seconds (cannot exceed data duration).
- include_tmax
bool If True (default), include tmax. If False, exclude tmax (similar to how Python indexing typically works).
New in version 0.19.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- tmin
- Returns:
- rawinstance of
Raw The cropped raw object, modified in-place.
- rawinstance of
Examples using
crop:
Signal-space separation (SSS) and Maxwell filtering
Signal-space separation (SSS) and Maxwell filtering
Plot sensor denoising using oversampled temporal projection
Plot sensor denoising using oversampled temporal projection
- crop_by_annotations(annotations=None, *, verbose=None)[source]#
Get crops of raw data file for selected annotations.
- Parameters:
- annotationsinstance of
Annotations|None The annotations to use for cropping the raw file. If None, the annotations from the instance are used.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- annotationsinstance of
- Returns:
- raws
list The cropped raw objects.
- raws
- decimate(decim, offset=0, verbose=None)[source]#
Decimate the time-series data.
- Parameters:
- decim
int Factor by which to subsample the data.
Warning
Low-pass filtering is not performed, this simply selects every Nth sample (where N is the value passed to
decim), i.e., it compresses the signal (see Notes). If the data are not properly filtered, aliasing artifacts may occur.- offset
int Apply an offset to where the decimation starts relative to the sample corresponding to t=0. The offset is in samples at the current sampling rate.
New in version 0.12.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- decim
- Returns:
- instMNE-object
The decimated object.
See also
Notes
For historical reasons,
decim/ “decimation” refers to simply subselecting samples from a given signal. This contrasts with the broader signal processing literature, where decimation is defined as (quoting [3], p. 172; which cites [4]):“… a general system for downsampling by a factor of M is the one shown in Figure 4.23. Such a system is called a decimator, and downsampling by lowpass filtering followed by compression [i.e, subselecting samples] has been termed decimation (Crochiere and Rabiner, 1983).”
Hence “decimation” in MNE is what is considered “compression” in the signal processing community.
Decimation can be done multiple times. For example,
inst.decimate(2).decimate(2)will be the same asinst.decimate(4).If
decimis 1, this method does not copy the underlying data.New in version 0.10.0.
References
- del_proj(idx='all')[source]#
Remove SSP projection vector.
Note
The projection vector can only be removed if it is inactive (has not been applied to the data).
- Parameters:
- Returns:
Examples using
del_proj:
- describe(data_frame=False)[source]#
Describe channels (name, type, descriptive statistics).
- Parameters:
- data_frame
bool If True, return results in a pandas.DataFrame. If False, only print results. Columns ‘ch’, ‘type’, and ‘unit’ indicate channel index, channel type, and unit of the remaining five columns. These columns are ‘min’ (minimum), ‘Q1’ (first quartile or 25% percentile), ‘median’, ‘Q3’ (third quartile or 75% percentile), and ‘max’ (maximum).
- data_frame
- Returns:
- result
None|pandas.DataFrame If data_frame=False, returns None. If data_frame=True, returns results in a pandas.DataFrame (requires pandas).
- result
- drop_channels(ch_names, on_missing='raise')[source]#
Drop channel(s).
- Parameters:
- ch_namesiterable or
str Iterable (e.g. list) of channel name(s) or channel name to remove.
- on_missing‘raise’ | ‘warn’ | ‘ignore’
Can be
'raise'(default) to raise an error,'warn'to emit a warning, or'ignore'to ignore when entries in ch_names are not present in the raw instance.New in version 0.23.0.
- ch_namesiterable or
- Returns:
See also
Notes
New in version 0.9.0.
Examples using
drop_channels:
- export(fname, fmt='auto', physical_range='auto', add_ch_type=False, *, overwrite=False, verbose=None)[source]#
Export Raw to external formats.
- Supported formats:
BrainVision (
.vhdr,.vmrk,.eeg, uses pybv)EEGLAB (
.set, useseeglabio)EDF (
.edf, uses EDFlib-Python)
Warning
Since we are exporting to external formats, there’s no guarantee that all the info will be preserved in the external format. See Notes for details.
- Parameters:
- fname
str Name of the output file.
- fmt‘auto’ | ‘brainvision’ | ‘edf’ | ‘eeglab’
Format of the export. Defaults to
'auto', which will infer the format from the filename extension. See supported formats above for more information.- physical_range
str|tuple The physical range of the data. If ‘auto’ (default), then it will infer the physical min and max from the data itself, taking the minimum and maximum values per channel type. If it is a 2-tuple of minimum and maximum limit, then those physical ranges will be used. Only used for exporting EDF files.
- add_ch_type
bool Whether to incorporate the channel type into the signal label (e.g. whether to store channel “Fz” as “EEG Fz”). Only used for EDF format. Default is
False.- overwrite
bool If True (default False), overwrite the destination file if it exists.
New in version 0.24.1.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- fname
Notes
New in version 0.24.
Export to external format may not preserve all the information from the instance. To save in native MNE format (
.fif) without information loss, usemne.io.Raw.save()instead. Export does not apply projector(s). Unapplied projector(s) will be lost. Consider applying projector(s) before exporting withmne.io.Raw.apply_proj().For EEGLAB exports, channel locations are expanded to full EEGLAB format. For more details see
eeglabio.utils.cart_to_eeglab().For EDF exports, only channels measured in Volts are allowed; in MNE-Python this means channel types ‘eeg’, ‘ecog’, ‘seeg’, ‘emg’, ‘eog’, ‘ecg’, ‘dbs’, ‘bio’, and ‘misc’. ‘stim’ channels are dropped. Although this function supports storing channel types in the signal label (e.g.
EEG FzorMISC E), other software may not support this (optional) feature of the EDF standard.If
add_ch_typeis True, then channel types are written based on what they are currently set in MNE-Python. One should double check that all their channels are set correctly. You can callraw.set_channel_typesto set channel types.In addition, EDF does not support storing a montage. You will need to store the montage separately and call
raw.set_montage().
- property filenames#
The filenames used.
- filter(l_freq, h_freq, picks=None, filter_length='auto', l_trans_bandwidth='auto', h_trans_bandwidth='auto', n_jobs=None, 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_freq
float|None For FIR filters, the lower pass-band edge; for IIR filters, the lower cutoff frequency. If None the data are only low-passed.
- h_freq
float|None For FIR filters, the upper pass-band edge; for IIR filters, the upper cutoff frequency. If None the data are only high-passed.
- picks
str| array_like |slice|None Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g.,
['meg', 'eeg']) will pick channels of those types, channel name strings (e.g.,['MEG0111', 'MEG2623']will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick all data channels. Note that channels ininfo['bads']will be included if their names or indices are explicitly provided.- filter_length
str|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 forphase="zero-double".int: Specified length in samples. For fir_design=”firwin”, this should not be used.
- l_trans_bandwidth
float|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_bandwidth
float|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_jobs
int|str Number of jobs to run in parallel. Can be ‘cuda’ if
cupyis installed properly and method=’fir’.- method
str ‘fir’ 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. If iir_params is None and method=”iir”, 4th order Butterworth will be used. For more information, see
mne.filter.construct_iir_filter().- phase
str Phase of the filter, only used if
method='fir'. Symmetric linear-phase FIR filters are constructed, and ifphase='zero'(default), the delay of this filter is compensated for, making it non-causal. Ifphase='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_window
str The window to use in FIR design, can be “hamming” (default), “hann” (default in 0.13), or “blackman”.
New in version 0.15.
- fir_design
str Can be “firwin” (default) to use
scipy.signal.firwin(), or “firwin2” to usescipy.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_annotation
str|listofstr 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 bymne.concatenate_raws()ormne.io.Raw.append(), or separated during acquisition. To disable, provide an empty list. Only used ifinstis raw.New in version 0.16..
- pad
str The type of padding to use. Supports all
numpy.pad()modeoptions. 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'.- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- l_freq
- Returns:
See also
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=Trueorself.load_data().l_freqandh_freqare the frequencies below which and above which, respectively, to filter out of the data. Thus the uses are:l_freq < h_freq: band-pass filterl_freq > h_freq: band-stop filterl_freq is not None and h_freq is None: high-pass filterl_freq is None and h_freq is not None: low-pass filter
self.info['lowpass']andself.info['highpass']are only updated with picks=None.Note
If n_jobs > 1, more memory is required as
len(picks) * n_timesadditional time points need to be temporarily 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:
Spatiotemporal permutation F-test on full sensor data
Spatiotemporal permutation F-test on full sensor data
Plot sensor denoising using oversampled temporal projection
Plot sensor denoising using oversampled temporal projection
How to convert 3D electrode positions to a 2D image
How to convert 3D electrode positions to a 2D image
Decoding sensor space data with generalization across time and conditions
Decoding sensor space data with generalization across time and conditions
Analysis of evoked response using ICA and PCA reduction techniques
Analysis of evoked response using ICA and PCA reduction techniques
- property first_samp#
The first data sample.
See first_samp.
- property first_time#
The first time point (including first_samp but not meas_date).
- fix_mag_coil_types()[source]#
Fix Elekta magnetometer coil types.
- Returns:
- rawinstance of
Raw The raw object. Operates in place.
- rawinstance of
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_channel_types(picks=None, unique=False, only_data_chs=False)[source]#
Get a list of channel type for each channel.
- Parameters:
- picks
str| array_like |slice|None Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g.,
['meg', 'eeg']) will pick channels of those types, channel name strings (e.g.,['MEG0111', 'MEG2623']will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick all channels. Note that channels ininfo['bads']will be included if their names or indices are explicitly provided.- unique
bool Whether to return only unique channel types. Default is
False.- only_data_chs
bool Whether to ignore non-data channels. Default is
False.
- picks
- Returns:
- channel_types
list The channel types.
- channel_types
Examples using
get_channel_types:
- get_data(picks=None, start=0, stop=None, reject_by_annotation=None, return_times=False, units=None, *, tmin=None, tmax=None, verbose=None)[source]#
Get data in the given range.
- Parameters:
- picks
str| array_like |slice|None Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g.,
['meg', 'eeg']) will pick channels of those types, channel name strings (e.g.,['MEG0111', 'MEG2623']will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick all channels. Note that channels ininfo['bads']will be included if their names or indices are explicitly provided.- start
int The first sample to include. Defaults to 0.
- stop
int|None End sample (first not to include). If None (default), the end of the data is used.
- reject_by_annotation
None| ‘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_times
bool Whether to return times as well. Defaults to False.
- units
str|dict|None Specify the unit(s) that the data should be returned in. If
None(default), the data is returned in the channel-type-specific default units, which are SI units (see Internal representation (units) and data channels). If a string, must be a sub-multiple of SI units that will be used to scale the data from all channels of the type associated with that unit. This only works if the data contains one channel type that has a unit (unitless channel types are left unchanged). For example if there are only EEG and STIM channels,units='uV'will scale EEG channels to micro-Volts while STIM channels will be unchanged. Finally, if a dictionary is provided, keys must be channel types, and values must be units to scale the data of that channel type to. For exampledict(grad='fT/cm', mag='fT')will scale the corresponding types accordingly, but all other channel types will remain in their channel-type-specific default unit.- tmin
int|float|None Start time of data to get in seconds. The
tminparameter is ignored if thestartparameter is bigger than 0.New in version 0.24.0.
- tmax
int|float|None End time of data to get in seconds. The
tmaxparameter is ignored if thestopparameter is defined.New in version 0.24.0.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- picks
- Returns:
Notes
New in version 0.14.0.
Examples using
get_data:
- get_montage()[source]#
Get a DigMontage from instance.
- Returns:
- montage
None|str|DigMontage A montage containing channel positions. If a string or
DigMontageis specified, the existing channel information will be updated with the channel positions from the montage. Valid strings are the names of the built-in montages that ship with MNE-Python; you can list those viamne.channels.get_builtin_montages(). IfNone(default), the channel positions will be removed from theInfo.
- montage
Examples using
get_montage:
How to convert 3D electrode positions to a 2D image
How to convert 3D electrode positions to a 2D image
- interpolate_bads(reset_bads=True, mode='accurate', origin='auto', method=None, exclude=(), verbose=None)[source]#
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 channels using the minimum-norm method.- originarray_like, shape (3,) |
str Origin of the sphere in the head coordinate frame and in meters. Can be
'auto'(default), which means a head-digitization-based origin fit.New in version 0.17.
- method
dict Method to use for each channel type. Currently only the key “eeg” has multiple options:
"spline"(default)Use spherical spline interpolation.
"MNE"Use minimum-norm projection to a sphere and back. This is the method used for MEG channels.
The value for “meg” is “MNE”, and the value for “fnirs” is “nearest”. The default (None) is thus an alias for:
method=dict(meg="MNE", eeg="spline", fnirs="nearest")
New in version 0.21.
- exclude
list|tuple The channels to exclude from interpolation. If excluded a bad channel will stay in bads.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- reset_bads
- Returns:
Notes
New in version 0.9.0.
- property last_samp#
The last data sample.
- load_bad_channels(bad_file=None, force=False, verbose=None)[source]#
Mark channels as bad from a text file.
This function operates mostly in the style of the C function
mne_mark_bad_channels. Each line in the text file will be interpreted as a name of a bad channel.- Parameters:
- bad_filepath-like |
None File name of the text file containing bad channels. If
None(default), bad channels are cleared, but this is more easily done directly withraw.info['bads'] = [].- force
bool Whether or not to force bad channel marking (of those that exist) if channels are not found, instead of raising an error. Defaults to
False.- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- bad_filepath-like |
- load_data(verbose=None)[source]#
Load raw data.
- Parameters:
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- verbose
- Returns:
- rawinstance of
Raw The raw object with data.
- rawinstance of
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.
Examples using
load_data:
How to convert 3D electrode positions to a 2D image
How to convert 3D electrode positions to a 2D image
Compute evoked ERS source power using DICS, LCMV beamformer, and dSPM
Compute evoked ERS source power using DICS, LCMV beamformer, and dSPM
- property n_times#
Number of time points.
- notch_filter(freqs, picks=None, filter_length='auto', notch_widths=None, trans_bandwidth=1.0, n_jobs=None, 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:
- freqs
float|arrayoffloat|None Specific frequencies to filter out from data, e.g.,
np.arange(60, 241, 60)in the US ornp.arange(50, 251, 50)in Europe.Nonecan only be used with the mode'spectrum_fit', where an F test is used to find sinusoidal components.- picks
str| array_like |slice|None Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g.,
['meg', 'eeg']) will pick channels of those types, channel name strings (e.g.,['MEG0111', 'MEG2623']will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick all data channels. Note that channels ininfo['bads']will be included if their names or indices are explicitly provided.- filter_length
str|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 forphase="zero-double".int: Specified length in samples. For fir_design=”firwin”, this should not be used.
When
method=='spectrum_fit', this sets the effective window duration over which fits are computed. Seemne.filter.create_filter()for options. Longer window lengths will give more stable frequency estimates, but require (potentially much) more processing and are not able to adapt as well to non-stationarities.The default in 0.21 is None, but this will change to
'10s'in 0.22.- notch_widths
float|arrayoffloat|None Width of each stop band (centred at each freq in freqs) in Hz. If None,
freqs / 200is used.- trans_bandwidth
float Width of the transition band in Hz. Only used for
method='fir'.- n_jobs
int|str Number of jobs to run in parallel. Can be ‘cuda’ if
cupyis installed properly and method=’fir’.- method
str ‘fir’ 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. If iir_params is None and method=”iir”, 4th order Butterworth will be used. For more information, see
mne.filter.construct_iir_filter().- 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'andfreqs=None. Note that this will be Bonferroni corrected for the number of frequencies, so large p-values may be justified.- phase
str Phase of the filter, only used if
method='fir'. Symmetric linear-phase FIR filters are constructed, and ifphase='zero'(default), the delay of this filter is compensated for, making it non-causal. Ifphase='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_window
str The window to use in FIR design, can be “hamming” (default), “hann” (default in 0.13), or “blackman”.
New in version 0.15.
- fir_design
str Can be “firwin” (default) to use
scipy.signal.firwin(), or “firwin2” to usescipy.signal.firwin2(). “firwin” uses a time-domain design technique that generally gives improved attenuation using fewer samples than “firwin2”.New in version 0.15.
- pad
str The type of padding to use. Supports all
numpy.pad()modeoptions. 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.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- freqs
- Returns:
- rawinstance of
Raw The raw instance with filtered data.
- rawinstance of
See also
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=Trueorself.load_data().Note
If n_jobs > 1, more memory is required as
len(picks) * n_timesadditional time points need to be temporarily stored in memory.For details, see
mne.filter.notch_filter().Examples using
notch_filter:
- pick(picks, exclude=(), *, verbose=None)[source]#
Pick a subset of channels.
- Parameters:
- picks
str| array_like |slice|None Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g.,
['meg', 'eeg']) will pick channels of those types, channel name strings (e.g.,['MEG0111', 'MEG2623']will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick all channels. Note that channels ininfo['bads']will be included if their names or indices are explicitly provided.- exclude
list|str Set of channels to exclude, only used when picking based on types (e.g., exclude=”bads” when picks=”meg”).
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.New in version 0.24.0.
- picks
- Returns:
Examples using
pick:
Signal-space separation (SSS) and Maxwell filtering
Signal-space separation (SSS) and Maxwell filtering
- pick_channels(ch_names, ordered=False, *, verbose=None)[source]#
Pick some channels.
- Parameters:
- ch_names
list The list of channels to select.
- ordered
bool If True (default False), ensure that the order of the channels in the modified instance matches the order of
ch_names.New in version 0.20.0.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.New in version 1.1.
- ch_names
- Returns:
See also
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_channelsto set channel order if necessary.New in version 0.9.0.
Examples using
pick_channels:
How to convert 3D electrode positions to a 2D image
How to convert 3D electrode positions to a 2D image
- pick_types(meg=False, eeg=False, stim=False, eog=False, ecg=False, emg=False, ref_meg='auto', *, misc=False, resp=False, chpi=False, exci=False, ias=False, syst=False, seeg=False, dipole=False, gof=False, bio=False, ecog=False, fnirs=False, csd=False, dbs=False, temperature=False, gsr=False, include=(), exclude='bads', selection=None, verbose=None)[source]#
Pick some channels by type and names.
- Parameters:
- meg
bool|str If True include MEG channels. If string it can be ‘mag’, ‘grad’, ‘planar1’ or ‘planar2’ to select only magnetometers, all gradiometers, or a specific type of gradiometer.
- 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’, reference channels are included if compensations are present and
megis not False. Can also be the string options for themegparameter.- misc
bool If True include miscellaneous analog channels.
- resp
bool If
Trueinclude respiratory channels.- 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.
- dipole
bool Dipole time course channels.
- gof
bool Dipole goodness of fit channels.
- bio
bool Bio channels.
- ecog
bool Electrocorticography channels.
- fnirs
bool|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).
- csd
bool EEG-CSD channels.
- dbs
bool Deep brain stimulation channels.
- temperature
bool Temperature channels.
- gsr
bool Galvanic skin response channels.
- include
listofstr List of additional channels to include. If empty do not include any.
- exclude
listofstr|str List of channels to exclude. If ‘bads’ (default), exclude channels in
info['bads'].- selection
listofstr Restrict sensor channels (MEG, EEG, etc.) to this list of channel names.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- meg
- Returns:
See also
Notes
New in version 0.9.0.
Examples using
pick_types:
EEG source localization given electrode locations on an MRI
EEG source localization given electrode locations on an MRI
Transform EEG data using current source density (CSD)
Transform EEG data using current source density (CSD)
Computing source timecourses with an XFit-like multi-dipole model
Computing source timecourses with an XFit-like multi-dipole model
- plot(events=None, duration=10.0, start=0.0, n_channels=20, bgcolor='w', color=None, bad_color='lightgray', 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=1.5, show_first_samp=False, proj=True, group_by='type', butterfly=False, decim='auto', noise_cov=None, event_id=None, show_scrollbars=True, show_scalebars=True, time_format='float', precompute=None, use_opengl=None, *, theme=None, overview_mode=None, verbose=None)[source]#
Plot raw data.
- Parameters:
- events
array|None Events to show with vertical bars.
- duration
float Time window (s) to plot. The lesser of this value and the duration of the raw file will be used.
- start
float 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_channels
int Number of channels to plot at once. Defaults to 20. The lesser of
n_channelsandlen(raw.ch_names)will be shown. Has no effect iforderis ‘position’, ‘selection’ or ‘butterfly’.- bgcolorcolor 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='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|None Color(s) to use for events. To show all events in the same color, pass any matplotlib-compatible color. To color events differently, pass a
dictthat maps event names or integer event numbers to colors (must include entries for all events, or include a “fallback” entry with key-1). IfNone, colors are chosen from the current Matplotlib color cycle. Defaults to'cyan'.- scalings‘auto’ |
dict|None Scaling factors for the traces. If a dictionary where any value is
'auto', the scaling factor is set to match the 99.5th percentile of the respective data. If'auto', all scalings (for all channel types) are set to'auto'. If any values are'auto'and the data is not preloaded, a subset up to 100 MB will be loaded. IfNone, 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)
Note
A particular scaling value
scorresponds to half of the visualized signal range around zero (i.e. from0to+sor from0to-s). For example, the default scaling of20e-6(20µV) for EEG signals means that the visualized range will be 40 µV (20 µV in the positive direction and 20 µV in the negative direction).- remove_dc
bool If True remove DC component when plotting data.
- order
arrayofint|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_byis'position'or'selection', theorderparameter is used only for selecting the channels to be plotted.- 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 figure if True.
- block
bool 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. (Only Qt) If you run from a script, this needs to be
Trueor a Qt-eventloop needs to be started somewhere else in the script (e.g. if you want to implement the browser inside another Qt-Application).- highpass
float|None Highpass to apply when displaying data.
- lowpass
float|None Lowpass to apply when displaying data. If highpass > lowpass, a bandstop rather than bandpass filter will be applied.
- filtorder
int 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 twicefiltorder). 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=0to use FIR filtering.- clipping
str|float|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. If float, clipping occurs for values beyond the
clippingmultiple of their dedicated range, soclipping=1.is an alias forclipping='transparent'.Changed in version 0.21: Support for float, and default changed from None to 1.5.
- show_first_samp
bool If True, show time axis relative to the
raw.first_samp.- proj
bool 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; useraw.apply_proj()to modify the data stored in the Raw object.- group_by
str 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 a lasso selector on the topomap. In butterfly mode,'type'and'original'group the channels by type, whereas'selection'and'position'use regional grouping.'type'and'original'modes are ignored whenorderis notNone. Defaults to'type'.- butterfly
bool Whether to start in butterfly mode. Defaults to False.
- decim
int| ‘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 alsomne.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 usingmne.Evoked.plot_white().New in version 0.16.0.
- event_id
dict|None Event IDs used to show at event markers (default None shows the event numbers).
New in version 0.16.0.
- show_scrollbars
bool 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.
- show_scalebars
bool Whether to show scale bars when the plot is initialized. Can be toggled after initialization by pressing s while the plot window is focused. Default is
True.New in version 0.20.0.
- time_format‘float’ | ‘clock’
Style of time labels on the horizontal axis. If
'float', labels will be number of seconds from the start of the recording. If'clock', labels will show “clock time” (hours/minutes/seconds) inferred fromraw.info['meas_date']. Default is'float'.New in version 0.24.
- precompute
bool|str Whether to load all data (not just the visible portion) into RAM and apply preprocessing (e.g., projectors) to the full data array in a separate processor thread, instead of window-by-window during scrolling. The default None uses the
MNE_BROWSER_PRECOMPUTEvariable, which defaults to'auto'.'auto'compares available RAM space to the expected size of the precomputed data, and precomputes only if enough RAM is available. This is only used with the Qt backend.New in version 0.24.
Changed in version 1.0: Support for the MNE_BROWSER_PRECOMPUTE config variable.
- use_opengl
bool|None Whether to use OpenGL when rendering the plot (requires
pyopengl). May increase performance, but effect is dependent on system CPU and graphics hardware. Only works if using the Qt backend. Default is None, which will use False unless the user configuration variableMNE_BROWSER_USE_OPENGLis set to'true', seemne.set_config().New in version 0.24.
- theme
str| path-like Can be “auto”, “light”, or “dark” or a path-like to a custom stylesheet. For Dark-Mode and automatic Dark-Mode-Detection,
qdarkstyleand darkdetect, respectively, are required. If None (default), the config option MNE_BROWSER_THEME will be used, defaulting to “auto” if it’s not found. Only supported by the'qt'backend.New in version 1.0.
- overview_mode
str|None Can be “channels”, “empty”, or “hidden” to set the overview bar mode for the
'qt'backend. If None (default), the config optionMNE_BROWSER_OVERVIEW_MODEwill be used, defaulting to “channels” if it’s not found.New in version 1.1.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- events
- Returns:
- fig
matplotlib.figure.Figure| mne_qt_browser.figure.MNEQtBrowser Browser instance.
- fig
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% ofduration. 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, and scrollbars can be hidden/shown by pressing ‘z’. Right-click a channel label to view its location. 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’sraw.info['bads']entry.If projectors are present, a button labelled “Prj” 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 whenremove_dcis set toTrue. This flag can be toggled by pressing ‘d’.MNE-Python provides two different backends for browsing plots (i.e.,
raw.plot(),epochs.plot(), andica.plot_sources()). One is based onmatplotlib, and the other is based on PyQtGraph. You can set the backend temporarily with the context managermne.viz.use_browser_backend(), you can set it for the duration of a Python session usingmne.viz.set_browser_backend(), and you can set the default for your computer viamne.set_config('MNE_BROWSER_BACKEND', 'matplotlib')(or'qt').Note
For the PyQtGraph backend to run in IPython with
block=Falseyou must run the magic command%gui qt5first.Note
To report issues with the PyQtGraph backend, please use the issues of
mne-qt-browser.Examples using
plot:
Transform EEG data using current source density (CSD)
Transform EEG data using current source density (CSD)
Plot sensor denoising using oversampled temporal projection
Plot sensor denoising using oversampled temporal projection
- plot_projs_topomap(ch_type=None, *, sensors=True, show_names=False, contours=6, outlines='head', sphere=None, image_interp='cubic', extrapolate='auto', border='mean', res=64, size=1, cmap=None, vlim=(None, None), cnorm=None, colorbar=False, cbar_fmt='%3.1f', units=None, axes=None, show=True)[source]#
Plot SSP vector.
- Parameters:
- ch_type‘mag’ | ‘grad’ | ‘planar1’ | ‘planar2’ | ‘eeg’ |
None|list The channel type to plot. For
'grad', the gradiometers are collected in pairs and the RMS for each pair is plotted. IfNoneit will return all channel types present.. If a list of ch_types is provided, it will return multiple figures. Defaults toNone.- sensors
bool|str Whether to add markers for sensor locations. If
str, should be a valid matplotlib format string (e.g.,'r+'for red plusses, see the Notes section ofplot()). IfTrue(the default), black circles will be used.- show_names
bool|callable() If
True, show channel names next to each sensor marker. If callable, channel names will be formatted using the callable; e.g., to delete the prefix ‘MEG ‘ from all channel names, pass the functionlambda x: x.replace('MEG ', ''). Ifmaskis notNone, only non-masked sensor names will be shown.New in version 1.2.
- contours
int| array_like The number of contour lines to draw. If
0, no contours will be drawn. If a positive integer, that number of contour levels are chosen using the matplotlib tick locator (may sometimes be inaccurate, use array for accuracy). If array-like, the array values are used as the contour levels. The values should be in µV for EEG, fT for magnetometers and fT/m for gradiometers. Ifcolorbar=True, the colorbar will have ticks corresponding to the contour levels. Default is6.- outlines‘head’ |
dict|None The outlines to be drawn. If ‘head’, the default head scheme will be drawn. If dict, each key refers to a tuple of x and y positions, the values in ‘mask_pos’ will serve as image mask. Alternatively, a matplotlib patch object can be passed for advanced masking options, either directly or as a function that returns patches (required for multi-axis plots). If None, nothing will be drawn. Defaults to ‘head’.
- sphere
float| array_like | instance ofConductorModel|None| ‘auto’ | ‘eeglab’ The sphere parameters to use for the head outline. Can be array-like of shape (4,) to give the X/Y/Z origin and radius in meters, or a single float to give just the radius (origin assumed 0, 0, 0). Can also be an instance of a spherical
ConductorModelto use the origin and radius from that object. If'auto'the sphere is fit to digitization points. If'eeglab'the head circle is defined by EEG electrodes'Fpz','Oz','T7', and'T8'(if'Fpz'is not present, it will be approximated from the coordinates of'Oz').None(the default) is equivalent to'auto'when enough extra digitization points are available, and (0, 0, 0, 0.095) otherwise.New in version 0.20.
Changed in version 1.1: Added
'eeglab'option.- image_interp
str The image interpolation to be used. Options are
'cubic'(default) to usescipy.interpolate.CloughTocher2DInterpolator,'nearest'to usescipy.spatial.Voronoior'linear'to usescipy.interpolate.LinearNDInterpolator.- extrapolate
str Options:
'box'Extrapolate to four points placed to form a square encompassing all data points, where each side of the square is three times the range of the data in the respective dimension.
'local'(default for MEG sensors)Extrapolate only to nearby points (approximately to points closer than median inter-electrode distance). This will also set the mask to be polygonal based on the convex hull of the sensors.
'head'(default for non-MEG sensors)Extrapolate out to the edges of the clipping circle. This will be on the head circle when the sensors are contained within the head circle, but it can extend beyond the head when sensors are plotted outside the head circle.
Changed in version 0.21:
The default was changed to
'local'for MEG sensors.'local'was changed to use a convex hull mask'head'was changed to extrapolate out to the clipping circle.
New in version 0.20.
- border
float| ‘mean’ Value to extrapolate to on the topomap borders. If
'mean'(default), then each extrapolated point has the average value of its neighbours.New in version 0.20.
- res
int The resolution of the topomap image (number of pixels along each side).
- size
float Side length of each subplot in inches. Only applies when plotting multiple topomaps at a time.
- cmapmatplotlib colormap | (colormap,
bool) | ‘interactive’ |None Colormap to use. If
tuple, the first value indicates the colormap to use and the second value is a boolean defining interactivity. In interactive mode the colors are adjustable by clicking and dragging the colorbar with left and right mouse button. Left mouse button moves the scale up and down and right mouse button adjusts the range. Hitting space bar resets the range. Up and down arrows can be used to change the colormap. IfNone,'Reds'is used for data that is either all-positive or all-negative, and'RdBu_r'is used otherwise.'interactive'is equivalent to(None, True). Defaults toNone.Warning
Interactive mode works smoothly only for a small amount of topomaps. Interactive mode is disabled by default for more than 2 topomaps.
- vlim
tupleof length 2 | ‘joint’ Colormap limits to use. If a
tupleof floats, specifies the lower and upper bounds of the colormap (in that order); providingNonefor either entry will set the corresponding boundary at the min/max of the data (separately for each projector). Elements of thetuplemay also be callable functions which take in aNumPy arrayand return a scalar. Ifvlim='joint', will compute the colormap limits jointly across all projectors of the same channel type, using the min/max of the data for that channel type. If vlim is'joint',infomust not beNone. Defaults to(None, None).- cnorm
matplotlib.colors.Normalize|None How to normalize the colormap. If
None, standard linear normalization is performed. If notNone,vminandvmaxwill be ignored. See Matplotlib docs for more details on colormap normalization, and the ERDs example for an example of its use.New in version 1.2.
- colorbar
bool Plot a colorbar in the rightmost column of the figure.
- cbar_fmt
str Formatting string for colorbar tick labels. See Format Specification Mini-Language for details.
New in version 1.2.
- units
str|None The units to use for the colorbar label. Ignored if
colorbar=False. IfNonethe label will be “AU” indicating arbitrary units. Default isNone.New in version 1.2.
- axesinstance of
Axes|listofAxes|None The axes to plot to. If
None, a newFigurewill be created with the correct number of axes. IfAxesare provided (either as a single instance or alistof axes), the number of axes provided must match the number of projectors.Default isNone.- show
bool Show the figure if
True.
- ch_type‘mag’ | ‘grad’ | ‘planar1’ | ‘planar2’ | ‘eeg’ |
- Returns:
- figinstance of
Figure Figure distributing one image per channel across sensor topography.
- figinstance of
Examples using
plot_projs_topomap:
- plot_psd(fmin=0, fmax=inf, tmin=None, tmax=None, picks=None, proj=False, reject_by_annotation=True, *, method='auto', average=False, dB=True, estimate='auto', xscale='linear', area_mode='std', area_alpha=0.33, color='black', line_alpha=None, spatial_colors=True, sphere=None, exclude='bads', ax=None, show=True, n_jobs=1, verbose=None, **method_kw)[source]#
Warning
LEGACY: New code should use .compute_psd().plot().
Plot power or amplitude spectra.
Separate plots are drawn for each channel type. 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 (⋮). If
average=False, the plot will be interactive, and click-dragging on the spectrum will generate a scalp topography plot for the chosen frequency range in a new figure.- Parameters:
- fmin, fmax
float The lower- and upper-bound on frequencies of interest. Default is
fmin=0, fmax=np.inf(spans all frequencies present in the data).- tmin, tmax
float|None First and last times to include, in seconds.
Noneuses the first or last time present in the data. Default istmin=None, tmax=None(all times).- picks
str| array_like |slice|None Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g.,
['meg', 'eeg']) will pick channels of those types, channel name strings (e.g.,['MEG0111', 'MEG2623']will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick good data channels (excluding reference MEG channels). Note that channels ininfo['bads']will be included if their names or indices are explicitly provided.- proj
bool Whether to apply SSP projection vectors before spectral estimation. Default is
False.- reject_by_annotation
bool Whether to omit bad spans of data before spectral estimation. If
True, spans with annotations whose description begins withbadwill be omitted.- method
'welch'|'multitaper'|'auto' Spectral estimation method.
'welch'uses Welch’s method[1],'multitaper'uses DPSS tapers[2].'auto'(default) uses Welch’s method for continuous data and multitaper forEpochsorEvokeddata.- average
bool 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.
- dB
bool Plot Power Spectral Density (PSD), in units (amplitude**2/Hz (dB)) if
dB=True, andestimate='power'orestimate='auto'. Plot PSD in units (amplitude**2/Hz) ifdB=Falseand,estimate='power'. Plot Amplitude Spectral Density (ASD), in units (amplitude/sqrt(Hz)), ifdB=Falseandestimate='amplitude'orestimate='auto'. Plot ASD, in units (amplitude/sqrt(Hz) (dB)), ifdB=Trueandestimate='amplitude'.- estimate
str, {‘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.
- xscale‘linear’ | ‘log’
Scale of the frequency axis. Default is
'linear'.- area_mode
str|None Mode for plotting area. If ‘std’, the mean +/- 1 STD (across channels) will be plotted. If ‘range’, the min and max (across channels) will be plotted. Bad channels will be excluded from these calculations. If None, no area will be plotted. If average=False, no area is plotted.
- area_alpha
float Alpha for the area.
- color
str|tuple A matplotlib-compatible color to use. Has no effect when spatial_colors=True.
- line_alpha
float|None Alpha for the PSD line. Can be None (default) to use 1.0 when
average=Trueand 0.1 whenaverage=False.- spatial_colors
bool Whether to color spectrum lines by channel location. Ignored if
average=True.- sphere
float| array_like | instance ofConductorModel|None| ‘auto’ | ‘eeglab’ The sphere parameters to use for the head outline. Can be array-like of shape (4,) to give the X/Y/Z origin and radius in meters, or a single float to give just the radius (origin assumed 0, 0, 0). Can also be an instance of a spherical
ConductorModelto use the origin and radius from that object. If'auto'the sphere is fit to digitization points. If'eeglab'the head circle is defined by EEG electrodes'Fpz','Oz','T7', and'T8'(if'Fpz'is not present, it will be approximated from the coordinates of'Oz').None(the default) is equivalent to'auto'when enough extra digitization points are available, and (0, 0, 0, 0.095) otherwise.New in version 0.20.
Changed in version 1.1: Added
'eeglab'option.New in version 0.22.0.
- exclude
listofstr| ‘bads’ Channels names to exclude from being shown. If ‘bads’, the bad channels are excluded. Pass an empty list to plot all channels (including channels marked “bad”, if any).
New in version 0.24.0.
- axinstance of
Axes|listofAxes|None The axes to plot to. If
None, a newFigurewill be created with the correct number of axes. IfAxesare provided (either as a single instance or alistof axes), the number of axes provided must match the number of channel types present in the object..Default isNone.- show
bool Show the figure if
True.- n_jobs
int|None The number of jobs to run in parallel. If
-1, it is set to the number of CPU cores. Requires thejoblibpackage.None(default) is a marker for ‘unset’ that will be interpreted asn_jobs=1(sequential execution) unless the call is performed under ajoblib.parallel_backend()context manager that sets another value forn_jobs.- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.- **method_kw
Additional keyword arguments passed to the spectral estimation function (e.g.,
n_fft, n_overlap, n_per_seg, average, windowfor Welch method, orbandwidth, adaptive, low_bias, normalizationfor multitaper method). Seepsd_array_welch()andpsd_array_multitaper()for details.
- fmin, fmax
- Returns:
- figinstance of
Figure Figure with frequency spectra of the data channels.
- figinstance of
Notes
This method exists to support legacy code; for new code the preferred idiom is
inst.compute_psd().plot()(whereinstis an instance ofRaw,Epochs, orEvoked).Examples using
plot_psd:
Transform EEG data using current source density (CSD)
Transform EEG data using current source density (CSD)
- plot_psd_topo(tmin=None, tmax=None, fmin=0, fmax=100, proj=False, *, method='auto', dB=True, layout=None, color='w', fig_facecolor='k', axis_facecolor='k', axes=None, block=False, show=True, n_jobs=None, verbose=None, **method_kw)[source]#
Warning
LEGACY: New code should use .compute_psd().plot_topo().
Plot power spectral density, separately for each channel.
- Parameters:
- tmin, tmax
float|None First and last times to include, in seconds.
Noneuses the first or last time present in the data. Default istmin=None, tmax=None(all times).- fmin, fmax
float The lower- and upper-bound on frequencies of interest. Default is
fmin=0, fmax=100.- proj
bool Whether to apply SSP projection vectors before spectral estimation. Default is
False.- method
'welch'|'multitaper'|'auto' Spectral estimation method.
'welch'uses Welch’s method[1],'multitaper'uses DPSS tapers[2].'auto'(default) uses Welch’s method for continuous data and multitaper forEpochsorEvokeddata.- dB
bool Whether to plot on a decibel-like scale. If
True, plots 10 × log₁₀(spectral power). Ignored ifnormalize=True.- layoutinstance of
Layout|None Layout instance specifying sensor positions (does not need to be specified for Neuromag data). If
None(default), the 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.
- axesinstance of
Axes|listofAxes|None The axes to plot to. If
None, a newFigurewill be created with the correct number of axes. IfAxesare provided (either as a single instance or alistof axes), the number of axes provided must be length 1 (for efficiency, subplots for each channel are simulated within a singleAxesobject).Default isNone.- block
bool Whether to halt program execution until the figure is closed. May not work on all systems / platforms. Defaults to
False.- show
bool Show the figure if
True.- n_jobs
int|None The number of jobs to run in parallel. If
-1, it is set to the number of CPU cores. Requires thejoblibpackage.None(default) is a marker for ‘unset’ that will be interpreted asn_jobs=1(sequential execution) unless the call is performed under ajoblib.parallel_backend()context manager that sets another value forn_jobs.- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.- **method_kw
Additional keyword arguments passed to the spectral estimation function (e.g.,
n_fft, n_overlap, n_per_seg, average, windowfor Welch method, orbandwidth, adaptive, low_bias, normalizationfor multitaper method). Seepsd_array_welch()andpsd_array_multitaper()for details. Defaults todict(n_fft=2048).
- tmin, tmax
- Returns:
- figinstance of
matplotlib.figure.Figure Figure distributing one image per channel across sensor topography.
- figinstance of
- plot_psd_topomap(bands=None, tmin=None, tmax=None, ch_type=None, *, proj=False, method='auto', normalize=False, agg_fun=None, dB=False, sensors=True, show_names=False, mask=None, mask_params=None, contours=0, outlines='head', sphere=None, image_interp='cubic', extrapolate='auto', border='mean', res=64, size=1, cmap=None, vlim=(None, None), cnorm=None, colorbar=True, cbar_fmt='auto', units=None, axes=None, show=True, n_jobs=None, verbose=None, **method_kw)[source]#
Warning
LEGACY: New code should use .compute_psd().plot_topomap().
Plot scalp topography of PSD for chosen frequency bands.
- Parameters:
- bands
None|dict|listoftuple The frequencies or frequency ranges to plot. If a
dict, keys will be used as subplot titles and values should be either a single frequency (e.g.,{'presentation rate': 6.5}) or a length-two sequence of lower and upper frequency band edges (e.g.,{'theta': (4, 8)}). If a single frequency is provided, the plot will show the frequency bin that is closest to the requested value. IfNone(the default), expands to:bands = {'Delta (0-4 Hz)': (0, 4), 'Theta (4-8 Hz)': (4, 8), 'Alpha (8-12 Hz)': (8, 12), 'Beta (12-30 Hz)': (12, 30), 'Gamma (30-45 Hz)': (30, 45)}
Note
For backwards compatibility,
tuplesof length 2 or 3 are also accepted, where the last element of the tuple is the subplot title and the other entries are frequency values (a single value or band edges). New code should usedictorNone.Changed in version 1.2: Allow passing a dict and discourage passing tuples.
- tmin, tmax
float|None First and last times to include, in seconds.
Noneuses the first or last time present in the data. Default istmin=None, tmax=None(all times).- ch_type‘mag’ | ‘grad’ | ‘planar1’ | ‘planar2’ | ‘eeg’ |
None The channel type to plot. For
'grad', the gradiometers are collected in pairs and the mean for each pair is plotted. IfNonethe first available channel type from order shown above is used. Defaults toNone.- proj
bool Whether to apply SSP projection vectors before spectral estimation. Default is
False.- method
'welch'|'multitaper'|'auto' Spectral estimation method.
'welch'uses Welch’s method[1],'multitaper'uses DPSS tapers[2].'auto'(default) uses Welch’s method for continuous data and multitaper forEpochsorEvokeddata.- normalize
bool If True, each band will be divided by the total power. Defaults to False.
- agg_fun
callable() The function used to aggregate over frequencies. Defaults to
numpy.sum()ifnormalize=True, elsenumpy.mean().- dB
bool Whether to plot on a decibel-like scale. If
True, plots 10 × log₁₀(spectral power) following the application ofagg_fun. Ignored ifnormalize=True.- sensors
bool|str Whether to add markers for sensor locations. If
str, should be a valid matplotlib format string (e.g.,'r+'for red plusses, see the Notes section ofplot()). IfTrue(the default), black circles will be used.- show_names
bool|callable() If
True, show channel names next to each sensor marker. If callable, channel names will be formatted using the callable; e.g., to delete the prefix ‘MEG ‘ from all channel names, pass the functionlambda x: x.replace('MEG ', ''). Ifmaskis notNone, only non-masked sensor names will be shown.- mask
ndarrayofbool, shape (n_channels, n_times) |None Array indicating channel-time combinations to highlight with a distinct plotting style (useful for, e.g. marking which channels at which times a statistical test of the data reaches significance). Array elements set to
Truewill be plotted with the parameters given inmask_params. Defaults toNone, equivalent to an array of allFalseelements.- mask_params
dict|None Additional plotting parameters for plotting significant sensors. Default (None) equals:
dict(marker='o', markerfacecolor='w', markeredgecolor='k', linewidth=0, markersize=4)
- contours
int| array_like The number of contour lines to draw. If
0, no contours will be drawn. If a positive integer, that number of contour levels are chosen using the matplotlib tick locator (may sometimes be inaccurate, use array for accuracy). If array-like, the array values are used as the contour levels. The values should be in µV for EEG, fT for magnetometers and fT/m for gradiometers. Ifcolorbar=True, the colorbar will have ticks corresponding to the contour levels. Default is6.- outlines‘head’ |
dict|None The outlines to be drawn. If ‘head’, the default head scheme will be drawn. If dict, each key refers to a tuple of x and y positions, the values in ‘mask_pos’ will serve as image mask. Alternatively, a matplotlib patch object can be passed for advanced masking options, either directly or as a function that returns patches (required for multi-axis plots). If None, nothing will be drawn. Defaults to ‘head’.
- sphere
float| array_like | instance ofConductorModel|None| ‘auto’ | ‘eeglab’ The sphere parameters to use for the head outline. Can be array-like of shape (4,) to give the X/Y/Z origin and radius in meters, or a single float to give just the radius (origin assumed 0, 0, 0). Can also be an instance of a spherical
ConductorModelto use the origin and radius from that object. If'auto'the sphere is fit to digitization points. If'eeglab'the head circle is defined by EEG electrodes'Fpz','Oz','T7', and'T8'(if'Fpz'is not present, it will be approximated from the coordinates of'Oz').None(the default) is equivalent to'auto'when enough extra digitization points are available, and (0, 0, 0, 0.095) otherwise.New in version 0.20.
Changed in version 1.1: Added
'eeglab'option.- image_interp
str The image interpolation to be used. Options are
'cubic'(default) to usescipy.interpolate.CloughTocher2DInterpolator,'nearest'to usescipy.spatial.Voronoior'linear'to usescipy.interpolate.LinearNDInterpolator.- extrapolate
str Options:
'box'Extrapolate to four points placed to form a square encompassing all data points, where each side of the square is three times the range of the data in the respective dimension.
'local'(default for MEG sensors)Extrapolate only to nearby points (approximately to points closer than median inter-electrode distance). This will also set the mask to be polygonal based on the convex hull of the sensors.
'head'(default for non-MEG sensors)Extrapolate out to the edges of the clipping circle. This will be on the head circle when the sensors are contained within the head circle, but it can extend beyond the head when sensors are plotted outside the head circle.
Changed in version 0.21:
The default was changed to
'local'for MEG sensors.'local'was changed to use a convex hull mask'head'was changed to extrapolate out to the clipping circle.
- border
float| ‘mean’ Value to extrapolate to on the topomap borders. If
'mean'(default), then each extrapolated point has the average value of its neighbours.New in version 0.20.
- res
int The resolution of the topomap image (number of pixels along each side).
- size
float Side length of each subplot in inches.
- cmapmatplotlib colormap | (colormap,
bool) | ‘interactive’ |None Colormap to use. If
tuple, the first value indicates the colormap to use and the second value is a boolean defining interactivity. In interactive mode the colors are adjustable by clicking and dragging the colorbar with left and right mouse button. Left mouse button moves the scale up and down and right mouse button adjusts the range. Hitting space bar resets the range. Up and down arrows can be used to change the colormap. IfNone,'Reds'is used for data that is either all-positive or all-negative, and'RdBu_r'is used otherwise.'interactive'is equivalent to(None, True). Defaults toNone.Warning
Interactive mode works smoothly only for a small amount of topomaps. Interactive mode is disabled by default for more than 2 topomaps.
- vlim
tupleof length 2 | ‘joint’ Colormap limits to use. If a
tupleof floats, specifies the lower and upper bounds of the colormap (in that order); providingNonefor either entry will set the corresponding boundary at the min/max of the data (separately for each topomap). Elements of thetuplemay also be callable functions which take in aNumPy arrayand return a scalar. Ifvlim='joint', will compute the colormap limits jointly across all topomaps of the same channel type, using the min/max of the data for that channel type. Defaults to(None, None).- cnorm
matplotlib.colors.Normalize|None How to normalize the colormap. If
None, standard linear normalization is performed. If notNone,vminandvmaxwill be ignored. See Matplotlib docs for more details on colormap normalization, and the ERDs example for an example of its use.New in version 1.2.
- colorbar
bool Plot a colorbar in the rightmost column of the figure.
- cbar_fmt
str Formatting string for colorbar tick labels. See Format Specification Mini-Language for details. If
'auto', is equivalent to ‘%0.3f’ ifdB=Falseand ‘%0.1f’ ifdB=True. Defaults to'auto'.- units
str|None The units to use for the colorbar label. Ignored if
colorbar=False. IfNonethe label will be “AU” indicating arbitrary units. Default isNone.- axesinstance of
Axes|listofAxes|None The axes to plot to. If
None, a newFigurewill be created with the correct number of axes. IfAxesare provided (either as a single instance or alistof axes), the number of axes provided must match the length ofbands.Default isNone.- show
bool Show the figure if
True.- n_jobs
int|None The number of jobs to run in parallel. If
-1, it is set to the number of CPU cores. Requires thejoblibpackage.None(default) is a marker for ‘unset’ that will be interpreted asn_jobs=1(sequential execution) unless the call is performed under ajoblib.parallel_backend()context manager that sets another value forn_jobs.- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.- **method_kw
Additional keyword arguments passed to the spectral estimation function (e.g.,
n_fft, n_overlap, n_per_seg, average, windowfor Welch method, orbandwidth, adaptive, low_bias, normalizationfor multitaper method). Seepsd_array_welch()andpsd_array_multitaper()for details.
- bands
- Returns:
- figinstance of
Figure Figure showing one scalp topography per frequency band.
- figinstance of
- plot_sensors(kind='topomap', ch_type=None, title=None, show_names=False, ch_groups=None, to_sphere=True, axes=None, block=False, show=True, sphere=None, verbose=None)[source]#
Plot sensor positions.
- Parameters:
- kind
str 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_type
None|str The channel type to plot. Available options ‘mag’, ‘grad’, ‘eeg’, ‘seeg’, ‘dbs’, ‘ecog’, ‘all’. If
'all', all the available mag, grad, eeg, seeg, dbs, and ecog channels are plotted. If None (default), then channels are chosen in the order given above.- title
str|None Title for the figure. If None (default), equals to
'Sensor positions (%s)' % ch_type.- show_names
bool|arrayofstr Whether to display all channel names. If an array, only the channel names in the array are shown. Defaults to False.
- ch_groups‘position’ |
arrayof 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
orderkwarg ofmne.viz.plot_raw(). If array, the channels are divided by picks given in the array.New in version 0.13.0.
- to_sphere
bool 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 ofAxes3D|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.
- block
bool Whether to halt program execution until the figure is closed. Defaults to False.
New in version 0.13.0.
- show
bool Show figure if True. Defaults to True.
- sphere
float| array_like | instance ofConductorModel|None| ‘auto’ | ‘eeglab’ The sphere parameters to use for the head outline. Can be array-like of shape (4,) to give the X/Y/Z origin and radius in meters, or a single float to give just the radius (origin assumed 0, 0, 0). Can also be an instance of a spherical
ConductorModelto use the origin and radius from that object. If'auto'the sphere is fit to digitization points. If'eeglab'the head circle is defined by EEG electrodes'Fpz','Oz','T7', and'T8'(if'Fpz'is not present, it will be approximated from the coordinates of'Oz').None(the default) is equivalent to'auto'when enough extra digitization points are available, and (0, 0, 0, 0.095) otherwise.New in version 0.20.
Changed in version 1.1: Added
'eeglab'option.- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- kind
- Returns:
See also
Notes
This function plots the sensor locations from the info structure using matplotlib. For drawing the sensors using PyVista see
mne.viz.plot_alignment().New in version 0.12.0.
Examples using
plot_sensors:
EEG source localization given electrode locations on an MRI
EEG source localization given electrode locations on an MRI
- property proj#
Whether or not projections are active.
- rename_channels(mapping, allow_duplicates=False, verbose=None)[source]#
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.
Changed in version 0.10.0: Support for a callable function.
- allow_duplicates
bool If True (default False), allow duplicates, which will automatically be renamed with
-Nat the end.New in version 0.22.0.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- mapping
- Returns:
Notes
New in version 0.9.0.
Examples using
rename_channels:
- reorder_channels(ch_names)[source]#
Reorder channels.
- Parameters:
- ch_names
list The desired channel order.
- ch_names
- Returns:
See also
Notes
Channel names must be unique. Channels that are not in
ch_namesare dropped.New in version 0.16.0.
- resample(sfreq, npad='auto', window='boxcar', stim_picks=None, n_jobs=None, events=None, pad='reflect_limited', verbose=None)[source]#
Resample all channels.
If appropriate, an anti-aliasing filter is applied before resampling. See Resampling and decimating data for more information.
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:
- sfreq
float New sample rate to use.
- npad
int|str Amount to pad the start and end of the data. Can also be “auto” to use a padding that will result in a power-of-two size (can be much faster).
- window
str|tuple Frequency-domain window to use in resampling. See
scipy.signal.resample().- stim_picks
listofint|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_jobs
int|str Number of jobs to run in parallel. Can be ‘cuda’ if
cupyis 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.
- pad
str The type of padding to use. Supports all
numpy.pad()modeoptions. 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. The default is'reflect_limited'.New in version 0.15.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- sfreq
- Returns:
See also
Notes
For some data, it may be more accurate to use
npad=0to reduce artifacts. This is dataset dependent – check your data!For optimum performance and to make use of
n_jobs > 1, the raw object has to have the data loaded e.g. withpreload=Trueorself.load_data(), but this increases memory requirements. The resulting raw object will have the data loaded into memory.Examples using
resample:
- save(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:
- fname
str File name of the new dataset. This has to be a new filename unless data have been preloaded. Filenames should end with
raw.fif(common raw data),raw_sss.fif(Maxwell-filtered continuous data),raw_tsss.fif(temporally signal-space-separated data),_meg.fif(common MEG data),_eeg.fif(common EEG data), or_ieeg.fif(common intracranial EEG data). You may also append an additional.gzsuffix to enable gzip compression.- picks
str| array_like |slice|None Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g.,
['meg', 'eeg']) will pick channels of those types, channel name strings (e.g.,['MEG0111', 'MEG2623']will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick all channels. Note that channels ininfo['bads']will be included if their names or indices are explicitly provided.- tmin
float Start time of the raw data to use in seconds (must be >= 0).
- tmax
float End time of the raw data to use in seconds (cannot exceed data duration).
- buffer_size_sec
float|None Size of data chunks in seconds. If None (default), 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 ifprojis 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.
- overwrite
bool If True (default False), overwrite the destination file if it exists. To overwrite original file (the same one that was loaded), data must be preloaded upon reading.
- split_size
str|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’
When splitting files, append a filename partition with the appropriate naming schema: for
'neuromag', a split filefname.fifwill be namedfname.fif,fname-1.fif,fname-2.fifetc.; while for'bids', it will be namedfname_split-01.fif,fname_split-02.fif, etc.New in version 0.17.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- fname
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.
Samples annotated
BAD_ACQ_SKIPare not stored in order to optimize memory. Whatever values, they will be loaded as 0s when reading file.
- savgol_filter(h_freq, verbose=None)[source]#
Filter the data using Savitzky-Golay polynomial method.
- Parameters:
- h_freq
float Approximate high cut-off frequency in Hz. Note that this is not an exact cutoff, since Savitzky-Golay filtering [5] 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.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- h_freq
- Returns:
See also
Notes
For Savitzky-Golay low-pass approximation, see:
New in version 0.9.0.
References
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(annotations, emit_warning=True, on_missing='raise', *, verbose=None)[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_warning
bool Whether to emit warnings when cropping or omitting annotations. The default is True.
- on_missing‘raise’ | ‘warn’ | ‘ignore’
Can be
'raise'(default) to raise an error,'warn'to emit a warning, or'ignore'to ignore when entries in ch_names are not present in the raw instance.New in version 0.23.0.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- annotationsinstance of
- Returns:
- selfinstance of
Raw The raw object with annotations.
- selfinstance of
Examples using
set_annotations:
- set_channel_types(mapping, verbose=None)[source]#
Define the sensor type of channels.
- Parameters:
- mapping
dict A dictionary mapping a channel to a sensor type (str), e.g.,
{'EEG061': 'eog'}.- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- mapping
- Returns:
Notes
The following sensor types are accepted:
ecg, eeg, emg, eog, exci, ias, misc, resp, seeg, dbs, stim, syst, ecog, hbo, hbr, fnirs_cw_amplitude, fnirs_fd_ac_amplitude, fnirs_fd_phase, fnirs_od, temperature, gsr
New in version 0.9.0.
Examples using
set_channel_types:
- set_eeg_reference(ref_channels='average', projection=False, ch_type='auto', forward=None, *, joint=False, verbose=None)[source]#
Specify which reference to use for EEG data.
Use this function to explicitly specify the desired reference for EEG. This can be either an existing electrode or a new virtual channel. This function will re-reference the data according to the desired reference.
- Parameters:
- ref_channels
listofstr|str Can be:
The name(s) of the channel(s) used to construct the reference.
'average'to apply an average reference (default)'REST'to use the Reference Electrode Standardization Technique infinity reference [6].An empty list, in which case MNE will not attempt any re-referencing of the data
- projection
bool If
ref_channels='average'this argument specifies if the average reference should be computed as a projection (True) or not (False; default). Ifprojection=True, the average reference is added as a projection and is not applied to the data (it can be applied afterwards with theapply_projmethod). Ifprojection=False, the average reference is directly applied to the data. Ifref_channelsis not'average',projectionmust be set toFalse(the default in this case).- ch_type
listofstr|str The name of the channel type to apply the reference to. Valid channel types are
'auto','eeg','ecog','seeg','dbs'. If'auto', the first channel type of eeg, ecog, seeg or dbs that is found (in that order) will be selected.New in version 0.19.
Changed in version 1.2:
list-of-stris now supported withprojection=True.- forwardinstance of
Forward|None Forward solution to use. Only used with
ref_channels='REST'.New in version 0.21.
- joint
bool How to handle list-of-str
ch_type. If False (default), one projector is created per channel type. If True, one projector is created across all channel types. This is only used whenprojection=True.New in version 1.2.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- ref_channels
- Returns:
See also
mne.set_bipolar_referenceConvenience function for creating bipolar references.
Notes
Some common referencing schemes and the corresponding value for the
ref_channelsparameter:- 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 ininfo['bads'].
- A single electrode:
Set
ref_channelsto a list containing the name of the channel that will act as the new reference, for exampleref_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_channelsto 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, setref_channels=['M1', 'M2'].
- REST
The given EEG electrodes are referenced to a point at infinity using the lead fields in
forward, which helps standardize the signals.
If a reference is requested that is not the average reference, this function removes any pre-existing average reference projections.
During source localization, the EEG signal should have an average reference.
In order to apply a reference, the data must be preloaded. This is not necessary if
ref_channels='average'andprojection=True.For an average or REST reference, bad EEG channels are automatically excluded if they are properly set in
info['bads'].
New in version 0.9.0.
References
Examples using
set_eeg_reference:
EEG source localization given electrode locations on an MRI
EEG source localization given electrode locations on an MRI
Transform EEG data using current source density (CSD)
Transform EEG data using current source density (CSD)
- set_meas_date(meas_date)[source]#
Set the measurement start date.
- Parameters:
- meas_date
datetime|float|tuple|None The new measurement date. If datetime object, it must be timezone-aware and in UTC. A tuple of (seconds, microseconds) or float (alias for
(meas_date, 0)) can also be passed and a datetime object will be automatically created. If None, will remove the time reference.
- meas_date
- Returns:
See also
Notes
If you want to remove all time references in the file, call
mne.io.anonymize_info(inst.info)after callinginst.set_meas_date(None).New in version 0.20.
- set_montage(montage, match_case=True, match_alias=False, on_missing='raise', verbose=None)[source]#
Set EEG/sEEG/ECoG/DBS/fNIRS channel positions and digitization points.
- Parameters:
- montage
None|str|DigMontage A montage containing channel positions. If a string or
DigMontageis specified, the existing channel information will be updated with the channel positions from the montage. Valid strings are the names of the built-in montages that ship with MNE-Python; you can list those viamne.channels.get_builtin_montages(). IfNone(default), the channel positions will be removed from theInfo.- match_case
bool If True (default), channel name matching will be case sensitive.
New in version 0.20.
- match_alias
bool|dict Whether to use a lookup table to match unrecognized channel location names to their known aliases. If True, uses the mapping in
mne.io.constants.CHANNEL_LOC_ALIASES. If adictis passed, it will be used instead, and should map from non-standard channel names to names in the specifiedmontage. Default isFalse.New in version 0.23.
- on_missing‘raise’ | ‘warn’ | ‘ignore’
Can be
'raise'(default) to raise an error,'warn'to emit a warning, or'ignore'to ignore when channels have missing coordinates.New in version 0.20.1.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- montage
- Returns:
See also
Notes
Warning
Only EEG/sEEG/ECoG/DBS/fNIRS channels can have their positions set using a montage. Other channel types (e.g., MEG channels) should have their positions defined properly using their data reading functions.
Examples using
set_montage:
EEG source localization given electrode locations on an MRI
EEG source localization given electrode locations on an MRI
- shift_time(tshift, relative=True)[source]#
Shift time scale in epoched or evoked data.
- Parameters:
- tshift
float The (absolute or relative) time shift in seconds. If
relativeis True, positive tshift increases the time value associated with each sample, while negative tshift decreases it.- relative
bool If True, increase or decrease time values by
tshiftseconds. Otherwise, shift the time values such that the time of the first sample equalstshift.
- tshift
- Returns:
- epochsMNE-object
The modified instance.
Notes
This method allows you to shift the time values associated with each data sample by an arbitrary amount. It does not resample the signal or change the data values in any way.
- time_as_index(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_rounding
bool If True, use rounding (instead of truncation) when converting times to indices. This can help avoid non-unique indices.
- origin
datetime|float|int|None Time reference for times. If None,
timesare assumed to be relative to first_samp.New in version 0.17.0.
- timeslist-like |
- Returns:
- index
ndarray Indices relative to first_samp corresponding to the times supplied.
- index
Examples using
time_as_index:
- property times#
Time points.
- property tmax#
Last time point.
- property tmin#
First time point.
- to_data_frame(picks=None, index=None, scalings=None, copy=True, start=None, stop=None, long_format=False, time_format=None, *, verbose=None)[source]#
Export data in tabular structure as a pandas DataFrame.
Channels are converted to columns in the DataFrame. By default, an additional column “time” is added, unless
indexis notNone(in which case time values form the DataFrame’s index).- Parameters:
- picks
str| array_like |slice|None Channels to include. Slices and lists of integers will be interpreted as channel indices. In lists, channel type strings (e.g.,
['meg', 'eeg']) will pick channels of those types, channel name strings (e.g.,['MEG0111', 'MEG2623']will pick the given channels. Can also be the string values “all” to pick all channels, or “data” to pick data channels. None (default) will pick all channels. Note that channels ininfo['bads']will be included if their names or indices are explicitly provided.- index‘time’ |
None Kind of index to use for the DataFrame. If
None, a sequential integer index (pandas.RangeIndex) will be used. If'time', apandas.Index,pandas.DatetimeIndex, orpandas.TimedeltaIndexwill be used (depending on the value oftime_format). Defaults toNone.- scalings
dict|None Scaling factor applied to the channels picked. If
None, defaults todict(eeg=1e6, mag=1e15, grad=1e13)— i.e., converts EEG to µV, magnetometers to fT, and gradiometers to fT/cm.- copy
bool If
True, data will be copied. Otherwise data may be modified in place. Defaults toTrue.- start
int|None Starting sample index for creating the DataFrame from a temporal span of the Raw object.
None(the default) uses the first sample.- stop
int|None Ending sample index for creating the DataFrame from a temporal span of the Raw object.
None(the default) uses the last sample.- long_format
bool If True, the DataFrame is returned in long format where each row is one observation of the signal at a unique combination of time point and channel. For convenience, a
ch_typecolumn is added to facilitate subsetting the resulting DataFrame. Defaults toFalse.- time_format
str|None Desired time format. If
None, no conversion is applied, and time values remain as float values in seconds. If'ms', time values will be rounded to the nearest millisecond and converted to integers. If'timedelta', time values will be converted topandas.Timedeltavalues. If'datetime', time values will be converted topandas.Timestampvalues, relative toraw.info['meas_date']and offset byraw.first_samp. Default isNone.New in version 0.20.
- verbose
bool|str|int|None Control verbosity of the logging output. If
None, use the default verbosity level. See the logging documentation andmne.verbose()for details. Should only be passed as a keyword argument.
- picks
- Returns:
- dfinstance of
pandas.DataFrame A dataframe suitable for usage with other statistical/plotting/analysis packages.
- dfinstance of
Examples using
to_data_frame:
Examples using mne.io.Raw#
Working with CTF data: the Brainstorm auditory dataset
Signal-space separation (SSS) and Maxwell filtering
The Spectrum and EpochsSpectrum classes: frequency-domain data
EEG source localization given electrode locations on an MRI
Non-parametric 1 sample cluster statistic on single trial power
Non-parametric between conditions cluster statistic on single trial power
Mass-univariate twoway repeated measures ANOVA on single trial power
Spatiotemporal permutation F-test on full sensor data
Permutation t-test on source data with spatio-temporal clustering
Repeated measures ANOVA on source data with spatio-temporal clustering
Cortical Signal Suppression (CSS) for removal of cortical signals
Define target events based on time lag, plot evoked response
Transform EEG data using current source density (CSD)
Plot sensor denoising using oversampled temporal projection
How to convert 3D electrode positions to a 2D image
Compute Power Spectral Density of inverse solution from single epochs
Compute power and phase lock in label of the source space
Compute source power spectral density (PSD) in a label
Compute induced power in the source space with dSPM
Permutation F-test on sensor data with 1D cluster level
Decoding sensor space data with generalization across time and conditions
Analysis of evoked response using ICA and PCA reduction techniques
Compute MNE-dSPM inverse solution on single epochs
Compute source level time-frequency timecourses using a DICS beamformer
Compute evoked ERS source power using DICS, LCMV beamformer, and dSPM
Computing source timecourses with an XFit-like multi-dipole model