mne.SourceEstimate

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

Container for surface source estimates

Parameters:

data : array of shape (n_dipoles, n_times) | 2-tuple (kernel, sens_data)

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

vertices : list of two arrays

Vertex numbers corresponding to the data.

tmin : scalar

Time point of the first sample in data.

tstep : scalar

Time step between successive samples in data.

subject : str | None

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

verbose : bool, str, int, or None

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

Attributes:

subject : str | None

The subject name.

times : array of shape (n_times,)

The time vector.

vertices : list of two arrays of shape (n_dipoles,)

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

data : array of shape (n_dipoles, n_times)

The data in source space.

shape : tuple

The shape of the data. A tuple of int (n_dipoles, n_times).

Methods

bin(width[, tstart, tstop, func]) Returns a SourceEstimate object with data summarized over time bins
center_of_mass([subject, hemi, ...]) Return the vertex on a given surface that is at the center of mass of the activity in stc.
copy() Return copy of SourceEstimate instance
crop([tmin, tmax]) Restrict SourceEstimate to a time interval
expand(vertices) Expand SourceEstimate to include more vertices
extract_label_time_course(labels, src[, ...]) Extract label time courses for lists of labels
get_peak([hemi, tmin, tmax, mode, ...]) Get location and latency of peak amplitude
in_label(label) Returns a SourceEstimate object restricted to a label
mean() Make a summary stc file with mean power between tmin and tmax.
morph(subject_to[, grade, smooth, ...]) Morph a source estimate from one subject to another
morph_precomputed(subject_to, vertices_to, ...) Morph source estimate between subjects using a precomputed matrix
plot([subject, surface, hemi, colormap, ...]) Plot SourceEstimates with PySurfer
resample(sfreq[, npad, window, n_jobs, verbose]) Resample data
save(fname[, ftype, verbose]) Save the source estimates to a file
sqrt() Take the square root
to_data_frame([picks, index, scale_time, ...]) Export data in tabular structure as a pandas DataFrame.
to_original_src(src_orig[, subject_orig, ...]) Return a SourceEstimate from morphed source to the original subject
transform(func[, idx, tmin, tmax, copy]) Apply linear transform
transform_data(func[, idx, tmin_idx, tmax_idx]) Get data after a linear (time) transform has been applied
__init__(data, vertices=None, tmin=None, tstep=None, subject=None, verbose=None)
bin(width, tstart=None, tstop=None, func=<function mean>)

Returns a SourceEstimate 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:

width : scalar

Width of the individual bins in seconds.

tstart : scalar | None

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

tstop : scalar | None

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.

func : callable

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

Returns:

stc : instance of SourceEstimate

The binned SourceEstimate.

center_of_mass(subject=None, hemi=None, restrict_vertices=False, subjects_dir=None)

Return the vertex on a given surface that is at the center of mass of the activity in stc. Note that all activity must occur in a single hemisphere, otherwise an error is returned. 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 the function mne.source_space.vertex_to_mni().

Parameters:

subject : string | None

The subject the stc is defined for.

hemi : int, or None

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_vertices : bool, or array of int

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. For most accuruate estimates, do not restrict vertices.

subjects_dir : str, or None

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

Returns:

vertex : int

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.

hemi : int

Hemisphere the vertex was taken from.

t : float

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

References: :

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

copy()

Return copy of SourceEstimate instance

crop(tmin=None, tmax=None)

Restrict SourceEstimate to a time interval

Parameters:

tmin : float | None

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

tmax : float | None

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

data

Numpy array of source estimate data

expand(vertices)

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 : list of array

New vertices to add. Can also contain old values.

Returns:

stc : instance of SourceEstimate

The modified stc (note: method operates inplace).

extract_label_time_course(labels, src, mode='mean_flip', allow_empty=False, verbose=None)

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.

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

labels : Label | list of Label

The labels for which to extract the time courses.

src : list

Source spaces for left and right hemisphere.

mode : str

Extraction mode, see explanation above.

allow_empty : bool

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

verbose : bool, str, int, or None

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

Returns:

label_tc : array, shape=(len(labels), n_times)

Extracted time course for each label.

See also

extract_label_time_course
extract time courses for multiple STCs
get_peak(hemi=None, tmin=None, tmax=None, mode='abs', vert_as_index=False, time_as_index=False)

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 : float | None

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

tmax : float | None

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

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

time_as_index : bool

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

Returns:

pos : int

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

latency : float | int

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

in_label(label)

Returns a SourceEstimate object restricted to a label

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

Parameters:

label : Label | BiHemiLabel

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.

mean()

Make a summary stc file with mean power between tmin and tmax.

Returns:

stc : instance of SourceEstimate

The modified stc (method operates inplace).

morph(subject_to, grade=5, smooth=None, subjects_dir=None, buffer_size=64, n_jobs=1, subject_from=None, sparse=False, verbose=None)

Morph a source estimate from one subject to another

Parameters:

subject_to : string

Name of the subject on which to morph as named in the SUBJECTS_DIR

grade : int, list (of two arrays), or None

Resolution of the icosahedral mesh (typically 5). If None, all vertices will be used (potentially filling the surface). If a list, then values will be morphed to the set of vertices specified in in grade[0] and grade[1]. Note that specifying the vertices (e.g., grade=[np.arange(10242), np.arange(10242)] for fsaverage on a standard grade 5 source space) can be substantially faster than computing vertex locations. Note that if subject=’fsaverage’ and ‘grade=5’, this set of vertices will automatically be used (instead of computed) for speed, since this is a common morph. NOTE : If sparse=True, grade has to be set to None.

smooth : int or None

Number of iterations for the smoothing of the surface data. If None, smooth is automatically defined to fill the surface with non-zero values.

subjects_dir : string, or None

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

buffer_size : int

Morph data in chunks of buffer_size time instants. Saves memory when morphing long time intervals.

n_jobs : int

Number of jobs to run in parallel.

subject_from : string

Name of the original subject as named in the SUBJECTS_DIR. If None, self.subject will be used.

sparse : bool

Morph as a sparse source estimate. If True the only parameters used are subject_to and subject_from, and grade has to be None.

verbose : bool, str, int, or None

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

Returns:

stc_to : SourceEstimate

Source estimate for the destination subject.

morph_precomputed(subject_to, vertices_to, morph_mat, subject_from=None)

Morph source estimate between subjects using a precomputed matrix

Parameters:

subject_to : string

Name of the subject on which to morph as named in the SUBJECTS_DIR.

vertices_to : list of array of int

The vertices on the destination subject’s brain.

morph_mat : sparse matrix

The morphing matrix, usually from compute_morph_matrix.

subject_from : string | None

Name of the original subject as named in the SUBJECTS_DIR. If None, self.subject will be used.

Returns:

stc_to : SourceEstimate

Source estimate for the destination subject.

plot(subject=None, surface='inflated', hemi='lh', colormap='auto', time_label='time=%0.2f ms', smoothing_steps=10, transparent=None, alpha=1.0, time_viewer=False, config_opts=None, subjects_dir=None, figure=None, views='lat', colorbar=True, clim='auto')

Plot SourceEstimates with PySurfer

Note: PySurfer currently needs the SUBJECTS_DIR environment variable, which will automatically be set by this function. Plotting multiple SourceEstimates with different values for subjects_dir will cause PySurfer to use the wrong FreeSurfer surfaces when using methods of the returned Brain object. It is therefore recommended to set the SUBJECTS_DIR environment variable or always use the same value for subjects_dir (within the same Python session).

Parameters:

subject : str | None

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.

surface : str

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

hemi : str, ‘lh’ | ‘rh’ | ‘split’ | ‘both’

The hemisphere to display.

colormap : str | 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. If ‘auto’, either ‘hot’ or ‘mne’ will be chosen based on whether ‘lims’ or ‘pos_lims’ are specified in clim.

time_label : str

How to print info about the time instant visualized.

smoothing_steps : int

The amount of smoothing.

transparent : bool | None

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

alpha : float

Alpha value to apply globally to the overlay.

time_viewer : bool

Display time viewer GUI.

config_opts : dict

Keyword arguments for Brain initialization. See pysurfer.viz.Brain.

subjects_dir : str

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

figure : instance of mayavi.core.scene.Scene | None

If None, the last figure will be cleaned and a new figure will be created.

views : str | list

View to use. See surfer.Brain().

colorbar : bool

If True, display colorbar on scene.

clim : str | dict

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

kind : str

Flag to specify type of limits. ‘value’ or ‘percent’.

lims : list | np.ndarray | tuple of float, 3 elements

Note: Only use this if ‘colormap’ is not ‘mne’. Left, middle, and right bound for colormap.

pos_lims : list | np.ndarray | tuple of float, 3 elements

Note: Only use this if ‘colormap’ is ‘mne’. Left, middle, and right bound for colormap. Positive values will be mirrored directly across zero during colormap construction to obtain negative control points.

Returns:

brain : Brain

A instance of surfer.viz.Brain from PySurfer.

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

Resample data

Parameters:

sfreq : float

New sample rate to use.

npad : int

Amount to pad the start and end of the data.

window : string or tuple

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

n_jobs : int

Number of jobs to run in parallel.

verbose : bool, str, int, or None

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

save(fname, ftype='stc', verbose=None)

Save the source estimates to a file

Parameters:

fname : string

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.

ftype : string

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

verbose : bool, str, int, or None

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

shape

Shape of the data

sqrt()

Take the square root

Returns:

stc : instance of SourceEstimate

A copy of the SourceEstimate with sqrt(data).

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

Export data in tabular structure as a pandas DataFrame.

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

Parameters:

picks : array-like of int | None

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

index : tuple of str | None

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

scale_time : float

Scaling to be applied to time units.

scalings : dict | None

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

copy : bool

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

start : int | None

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

stop : int | None

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

Returns:

df : instance of pandas.core.DataFrame

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

to_original_src(src_orig, subject_orig=None, subjects_dir=None, verbose=None)

Return a SourceEstimate from morphed source to the original subject

Parameters:

src_orig : instance of SourceSpaces

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

subject_orig : str | None

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 : string, or None

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

verbose : bool, str, int, or None

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

Notes

New in version 0.10.0.

transform(func, idx=None, tmin=None, tmax=None, copy=False)

Apply linear transform

The transform is applied to each source time course independently.

Parameters:

func : callable

The transform to be applied, including parameters (see, e.g., mne.fixes.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. 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 (see below) 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.

idx : array | None

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

tmin : float | int | None

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

tmax : float | int | None

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

copy : bool

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

Returns:

stcs : instance of SourceEstimate | list

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

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 “lcmv_epochs” do this automatically (if possible).

transform_data(func, idx=None, tmin_idx=None, tmax_idx=None)

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

The transorm is applied to each source time course independently.

Parameters:

func : callable

The transform to be applied, including parameters (see, e.g., mne.fixes.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 : array | None

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

tmin_idx : int | None

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

tmax_idx : int | None

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_t : ndarray

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 “lcmv_epochs” do this automatically (if possible).