mne.SourceEstimate¶

class mne.SourceEstimate(data, vertices=None, tmin=None, tstep=None, subject=None, verbose=None)[source]

Container for surface source estimates.

Parameters
dataarray of shape (n_dipoles, n_times) | tuple, shape (2,)

The data in source space. The data can either be a single array or a tuple with two arrays: “kernel” shape (n_vertices, n_sensors) and “sens_data” shape (n_sensors, n_times). In this case, the source space data corresponds to “numpy.dot(kernel, sens_data)”.

verticeslist of shape (2,)

Vertex numbers corresponding to the data.

tminscalar

Time point of the first sample in data.

tstepscalar

Time step between successive samples in data.

subject

The subject name. While not necessary, it is safer to set the subject parameter to avoid analysis errors.

verbose

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

VectorSourceEstimate

A container for vector source estimates.

VolSourceEstimate

A container for volume source estimates.

MixedSourceEstimate

A container for mixed surface + volume source estimates.

Attributes
subject

The subject name.

timesarray of shape (n_times,)

A timestamp for each sample.

verticeslist of shape (2,)

The indices of the dipoles in the left and right source space.

dataarray of shape (n_dipoles, n_times)

Numpy array of source estimate data.

shapetuple

Shape of the data.

Methods

 __add__(self, a) Add source estimates. __div__(self, a) Divide source estimates. __hash__(self, /) Return hash(self). __mul__(self, a) Multiply source estimates. __neg__(self) Negate the source estimate. __sub__(self, a) Subtract source estimates. bin(self, width[, tstart, tstop, func]) Return a source estimate object with data summarized over time bins. center_of_mass(self[, subject, hemi, …]) Compute the center of mass of activity. copy(self) Return copy of source estimate instance. crop(self[, tmin, tmax, include_tmax]) Restrict SourceEstimate to a time interval. expand(self, vertices) Expand SourceEstimate to include more vertices. extract_label_time_course(self, labels, src) Extract label time courses for lists of labels. get_peak(self[, hemi, tmin, tmax, mode, …]) Get location and latency of peak amplitude. in_label(self, label) Get a source estimate object restricted to a label. mean(self) Make a summary stc file with mean over time points. plot(self[, subject, surface, hemi, …]) Plot SourceEstimate with PySurfer. resample(self, sfreq[, npad, window, …]) Resample data. save(self, fname[, ftype, verbose]) Save the source estimates to a file. sqrt(self) Take the square root. sum(self) Make a summary stc file with sum over time points. time_as_index(self, times[, use_rounding]) Convert time to indices. to_data_frame(self[, picks, index, …]) Export data in tabular structure as a pandas DataFrame. to_original_src(self, src_orig[, …]) Get a source estimate from morphed source to the original subject. transform(self, func[, idx, tmin, tmax, copy]) Apply linear transform. transform_data(self, func[, idx, tmin_idx, …]) Get data after a linear (time) transform has been applied.
__add__(self, a)[source]

__div__(self, a)[source]

Divide source estimates.

__hash__(self, /)

Return hash(self).

__mul__(self, a)[source]

Multiply source estimates.

__neg__(self)[source]

Negate the source estimate.

__sub__(self, a)[source]

Subtract source estimates.

bin(self, width, tstart=None, tstop=None, func=<function mean at 0x7f4a9fae6050>)[source]

Return a source estimate object with data summarized over time bins.

Time bins of width seconds. This method is intended for visualization only. No filter is applied to the data before binning, making the method inappropriate as a tool for downsampling data.

Parameters
widthscalar

Width of the individual bins in seconds.

tstart

Time point where the first bin starts. The default is the first time point of the stc.

tstop

Last possible time point contained in a bin (if the last bin would be shorter than width it is dropped). The default is the last time point of the stc.

funccallable()

Function that is applied to summarize the data. Needs to accept a numpy.array as first input and an axis keyword argument.

Returns
stc

The binned source estimate.

center_of_mass(self, subject=None, hemi=None, restrict_vertices=False, subjects_dir=None, surf='sphere')[source]

Compute the center of mass of activity.

This function computes the spatial center of mass on the surface as well as the temporal center of mass as in [Rf9d93a5fe24c-1].

Note

All activity must occur in a single hemisphere, otherwise an error is raised. The “mass” of each point in space for computing the spatial center of mass is computed by summing across time, and vice-versa for each point in time in computing the temporal center of mass. This is useful for quantifying spatio-temporal cluster locations, especially when combined with mne.vertex_to_mni().

Parameters
subject

The subject the stc is defined for.

hemi

Calculate the center of mass for the left (0) or right (1) hemisphere. If None, one of the hemispheres must be all zeroes, and the center of mass will be calculated for the other hemisphere (useful for getting COM for clusters).

restrict_verticesbool | array of int | instance of SourceSpaces

If True, returned vertex will be one from stc. Otherwise, it could be any vertex from surf. If an array of int, the returned vertex will come from that array. If instance of SourceSpaces (as of 0.13), the returned vertex will be from the given source space. For most accuruate estimates, do not restrict vertices.

subjects_dir

Path to the SUBJECTS_DIR. If None, the path is obtained by using the environment variable SUBJECTS_DIR.

surfstr

The surface to use for Euclidean distance center of mass finding. The default here is “sphere”, which finds the center of mass on the spherical surface to help avoid potential issues with cortical folding.

Returns
vertexint

Vertex of the spatial center of mass for the inferred hemisphere, with each vertex weighted by the sum of the stc across time. For a boolean stc, then, this would be weighted purely by the duration each vertex was active.

hemiint

Hemisphere the vertex was taken from.

tfloat

Time of the temporal center of mass (weighted by the sum across source vertices).

References

Rf9d93a5fe24c-1

Larson and Lee, “The cortical dynamics underlying effective switching of auditory spatial attention”, NeuroImage 2012.

Examples using center_of_mass:

copy(self)[source]

Return copy of source estimate instance.

Examples using copy:

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

Restrict SourceEstimate to a time interval.

Parameters
tmin

The first time point in seconds. If None the first present is used.

tmax

The last time point in seconds. If None the last present is used.

include_tmaxbool

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

New in version 0.19.

Examples using crop:

property data

Numpy array of source estimate data.

expand(self, vertices)[source]

Expand SourceEstimate to include more vertices.

This will add rows to stc.data (zero-filled) and modify stc.vertices to include all vertices in stc.vertices and the input vertices.

Parameters
vertices

New vertices to add. Can also contain old values.

Returns
stc

The modified stc (note: method operates inplace).

extract_label_time_course(self, labels, src, mode='mean_flip', allow_empty=False, verbose=None)[source]

Extract label time courses for lists of labels.

This function will extract one time course for each label. The way the time courses are extracted depends on the mode parameter.

Parameters
labels

The labels for which to extract the time courses.

srclist

Source spaces for left and right hemisphere.

modestr

Extraction mode, see explanation below.

allow_emptybool

Instead of emitting an error, return all-zero time course for labels that do not have any vertices in the source estimate.

verbose

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

Returns
label_tcarray, shape=(n_labels, n_times)

Extracted time course for each label.

extract_label_time_course

extract time courses for multiple STCs

Notes

Valid values for mode are:

• ‘mean’

Average within each label.

• ‘mean_flip’

Average within each label with sign flip depending on source orientation.

• ‘pca_flip’

Apply an SVD to the time courses within each label and use the scaled and sign-flipped first right-singular vector as the label time course. The scaling is performed such that the power of the label time course is the same as the average per-vertex time course power within the label. The sign of the resulting time course is adjusted by multiplying it with “sign(dot(u, flip))” where u is the first left-singular vector, and flip is a sing-flip vector based on the vertex normals. This procedure assures that the phase does not randomly change by 180 degrees from one stc to the next.

• ‘max’

Max value within each label.

Examples using extract_label_time_course:

get_peak(self, hemi=None, tmin=None, tmax=None, mode='abs', vert_as_index=False, time_as_index=False)[source]

Get location and latency of peak amplitude.

Parameters
hemi{‘lh’, ‘rh’, None}

The hemi to be considered. If None, the entire source space is considered.

tmin

The minimum point in time to be considered for peak getting.

tmax

The maximum point in time to be considered for peak getting.

mode{‘pos’, ‘neg’, ‘abs’}

How to deal with the sign of the data. If ‘pos’ only positive values will be considered. If ‘neg’ only negative values will be considered. If ‘abs’ absolute values will be considered. Defaults to ‘abs’.

vert_as_indexbool

whether to return the vertex index instead of of its ID. Defaults to False.

time_as_indexbool

Whether to return the time index instead of the latency. Defaults to False.

Returns
posint

The vertex exhibiting the maximum response, either ID or index.

latency

The time point of the maximum response, either latency in seconds or index.

Examples using get_peak:

in_label(self, label)[source]

Get a source estimate object restricted to a label.

SourceEstimate contains the time course of activation of all sources inside the label.

Parameters
label

The label (as created for example by mne.read_label). If the label does not match any sources in the SourceEstimate, a ValueError is raised.

Returns
stc

The source estimate restricted to the given label.

Examples using in_label:

property lh_data

Left hemisphere data.

property lh_vertno

Left hemisphere vertno.

mean(self)[source]

Make a summary stc file with mean over time points.

Returns
stc

The modified stc.

plot(self, subject=None, surface='inflated', hemi='lh', colormap='auto', time_label='auto', smoothing_steps=10, transparent=True, alpha=1.0, time_viewer=False, subjects_dir=None, figure=None, views='lat', colorbar=True, clim='auto', cortex='classic', size=800, background='black', foreground='white', initial_time=None, time_unit='s', backend='auto', spacing='oct6', title=None, verbose=None)[source]

Plot SourceEstimate with PySurfer.

By default this function uses mayavi.mlab to plot the source estimates. If Mayavi is not installed, the plotting is done with matplotlib.pyplot (much slower, decimated source space by default).

Parameters
subject

The subject name corresponding to FreeSurfer environment variable SUBJECT. If None stc.subject will be used. If that is None, the environment will be used.

surfacestr

The type of surface (inflated, white etc.).

hemistr, ‘lh’ | ‘rh’ | ‘split’ | ‘both’

The hemisphere to display.

colormapstr | np.ndarray of float, shape(n_colors, 3 | 4)

Name of colormap to use or a custom look up table. If array, must be (n x 3) or (n x 4) array for with RGB or RGBA values between 0 and 255. The default (‘auto’) uses ‘hot’ for one-sided data and ‘mne’ for two-sided data.

time_label

Format of the time label (a format string, a function that maps floating point time values to strings, or None for no label). The default is time=%0.2f ms.

smoothing_stepsint

The amount of smoothing

transparent

If True, use a linear transparency between fmin and fmid. None will choose automatically based on colormap type.

alphafloat

Alpha value to apply globally to the overlay. Has no effect with mpl backend.

time_viewerbool

Display time viewer GUI.

subjects_dirstr

The path to the freesurfer subjects reconstructions. It corresponds to Freesurfer environment variable SUBJECTS_DIR.

figureinstance of mayavi.core.api.Scene | instance of matplotlib.figure.Figure | list | int | None

If None, a new figure will be created. If multiple views or a split view is requested, this must be a list of the appropriate length. If int is provided it will be used to identify the Mayavi figure by it’s id or create a new figure with the given id. If an instance of matplotlib figure, mpl backend is used for plotting.

views

View to use. See surfer.Brain. Supported views: [‘lat’, ‘med’, ‘ros’, ‘cau’, ‘dor’ ‘ven’, ‘fro’, ‘par’]. Using multiple views is not supported for mpl backend.

colorbarbool

If True, display colorbar on scene.

clim

Colorbar properties specification. If ‘auto’, set clim automatically based on data percentiles. If dict, should contain:

kind‘value’ | ‘percent’

Flag to specify type of limits.

limslist | np.ndarray | tuple of float, 3 elements

Lower, middle, and upper bounds for colormap.

pos_limslist | np.ndarray | tuple of float, 3 elements

Lower, middle, and upper bound for colormap. Positive values will be mirrored directly across zero during colormap construction to obtain negative control points.

Note

Only one of lims or pos_lims should be provided. Only sequential colormaps should be used with lims, and only divergent colormaps should be used with pos_lims.

cortex

Specifies how binarized curvature values are rendered. Either the name of a preset PySurfer cortex colorscheme (one of ‘classic’, ‘bone’, ‘low_contrast’, or ‘high_contrast’), or the name of mayavi colormap, or a tuple with values (colormap, min, max, reverse) to fully specify the curvature colors. Has no effect with mpl backend.

size

The size of the window, in pixels. can be one number to specify a square window, or the (width, height) of a rectangular window. Has no effect with mpl backend.

backgroundmatplotlib color

Color of the background of the display window.

foregroundmatplotlib color

Color of the foreground of the display window. Has no effect with mpl backend.

initial_time

The time to display on the plot initially. None to display the first time sample (default).

time_unit‘s’ | ‘ms’

Whether time is represented in seconds (“s”, default) or milliseconds (“ms”).

backend‘auto’ | ‘mayavi’ | ‘matplotlib’

Which backend to use. If 'auto' (default), tries to plot with mayavi, but resorts to matplotlib if mayavi is not available.

New in version 0.15.0.

spacingstr

The spacing to use for the source space. Can be 'ico#' for a recursively subdivided icosahedron, 'oct#' for a recursively subdivided octahedron, or 'all' for all points. In general, you can speed up the plotting by selecting a sparser source space. Has no effect with mayavi backend. Defaults to ‘oct6’.

New in version 0.15.0.

title

Title for the figure. If None, the subject name will be used.

New in version 0.17.0.

verbose

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

Returns
figure

An instance of surfer.Brain from PySurfer or matplotlib figure.

Examples using plot:

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

Resample data.

Parameters
sfreqfloat

New sample rate to use.

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

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

n_jobsint

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

verbose

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

Notes

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

Note that the sample rate of the original data is inferred from tstep.

Examples using resample:

property rh_data

Right hemisphere data.

property rh_vertno

Right hemisphere vertno.

save(self, fname, ftype='stc', verbose=None)[source]

Save the source estimates to a file.

Parameters
fnamestr

The stem of the file name. The file names used for surface source spaces are obtained by adding “-lh.stc” and “-rh.stc” (or “-lh.w” and “-rh.w”) to the stem provided, for the left and the right hemisphere, respectively.

ftypestr

File format to use. Allowed values are “stc” (default), “w”, and “h5”. The “w” format only supports a single time point.

verbose

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

Examples using save:

property sfreq

Sample rate of the data.

property shape

Shape of the data.

sqrt(self)[source]

Take the square root.

Returns
stcinstance of SourceEstimate

A copy of the SourceEstimate with sqrt(data).

sum(self)[source]

Make a summary stc file with sum over time points.

Returns
stc

The modified stc.

Examples using sum:

time_as_index(self, times, use_rounding=False)[source]

Convert time to indices.

Parameters
timeslist-like | float | int

List of numbers or a number representing points in time.

use_roundingbool

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

Returns
indexndarray

Indices corresponding to the times supplied.

Examples using time_as_index:

property times

A timestamp for each sample.

property tmin

The first timestamp.

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

Export data in tabular structure as a pandas DataFrame.

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

Parameters
picks

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.

index

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

scaling_timefloat

Scaling to be applied to time units.

scalings

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

copybool

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

start

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

stop

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

long_formatbool

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

Returns
dfinstance of pandas.DataFrame

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

to_original_src(self, src_orig, subject_orig=None, subjects_dir=None, verbose=None)[source]

Get a source estimate from morphed source to the original subject.

Parameters
src_originstance of SourceSpaces

The original source spaces that were morphed to the current subject.

subject_orig

The original subject. For most source spaces this shouldn’t need to be provided, since it is stored in the source space itself.

subjects_dir

Path to SUBJECTS_DIR if it is not set in the environment.

verbose

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

Returns
stc

The transformed source estimate.

Notes

New in version 0.10.0.

Examples using to_original_src:

transform(self, func, idx=None, tmin=None, tmax=None, copy=False)[source]

Apply linear transform.

The transform is applied to each source time course independently.

Parameters
funccallable()

The transform to be applied, including parameters (see, e.g., functools.partial()). The first parameter of the function is the input data. The first two dimensions of the transformed data should be (i) vertices and (ii) time. See Notes for details.

idx

Indices of source time courses for which to compute transform. If None, all time courses are used.

tmin

First time point to include (ms). If None, self.tmin is used.

tmax

Last time point to include (ms). If None, self.tmax is used.

copybool

If True, return a new instance of SourceEstimate instead of modifying the input inplace.

Returns
stcs

The transformed stc or, in the case of transforms which yield N-dimensional output (where N > 2), a list of stcs. For a list, copy must be True.

Notes

Transforms which yield 3D output (e.g. time-frequency transforms) are valid, so long as the first two dimensions are vertices and time. In this case, the copy parameter must be True and a list of SourceEstimates, rather than a single instance of SourceEstimate, will be returned, one for each index of the 3rd dimension of the transformed data. In the case of transforms yielding 2D output (e.g. filtering), the user has the option of modifying the input inplace (copy = False) or returning a new instance of SourceEstimate (copy = True) with the transformed data.

Applying transforms can be significantly faster if the SourceEstimate object was created using “(kernel, sens_data)”, for the “data” parameter as the transform is applied in sensor space. Inverse methods, e.g., “apply_inverse_epochs”, or “apply_lcmv_epochs” do this automatically (if possible).

transform_data(self, func, idx=None, tmin_idx=None, tmax_idx=None)[source]

Get data after a linear (time) transform has been applied.

The transform is applied to each source time course independently.

Parameters
funccallable()

The transform to be applied, including parameters (see, e.g., functools.partial()). The first parameter of the function is the input data. The first return value is the transformed data, remaining outputs are ignored. The first dimension of the transformed data has to be the same as the first dimension of the input data.

idx

Indicices of source time courses for which to compute transform. If None, all time courses are used.

tmin_idx

Index of first time point to include. If None, the index of the first time point is used.

tmax_idx

Index of the first time point not to include. If None, time points up to (and including) the last time point are included.

Returns
data_tndarray

The transformed data.

Notes

Applying transforms can be significantly faster if the SourceEstimate object was created using “(kernel, sens_data)”, for the “data” parameter as the transform is applied in sensor space. Inverse methods, e.g., “apply_inverse_epochs”, or “apply_lcmv_epochs” do this automatically (if possible).

property tstep

The change in time between two consecutive samples (1 / sfreq).