mne.viz.Brain¶
-
class
mne.viz.
Brain
(subject_id, hemi, surf, title=None, cortex='classic', alpha=1.0, size=800, background='black', foreground=None, figure=None, subjects_dir=None, views='auto', offset=True, show_toolbar=False, offscreen=False, interaction='trackball', units='mm', view_layout='vertical', show=True)[source]¶ Class for visualizing a brain.
Warning
The API for this class is not currently complete. We suggest using
mne.viz.plot_source_estimates()
with the PyVista backend enabled to obtain aBrain
instance.- Parameters
- subject_id
str
Subject name in Freesurfer subjects dir.
- hemi
str
Hemisphere id (ie ‘lh’, ‘rh’, ‘both’, or ‘split’). In the case of ‘both’, both hemispheres are shown in the same window. In the case of ‘split’ hemispheres are displayed side-by-side in different viewing panes.
- surf
str
FreeSurfer surface mesh name (ie ‘white’, ‘inflated’, etc.).
- title
str
Title for the window.
- cortex
str
orNone
Specifies how the cortical surface is rendered. The name of one of the preset cortex styles can be:
'classic'
(default),'high_contrast'
,'low_contrast'
, or'bone'
or a valid color name. Setting this toNone
is equivalent to(0.5, 0.5, 0.5)
.- alpha
float
in [0, 1] Alpha level to control opacity of the cortical surface.
- size
int
| array_like, shape (2,) The size of the window, in pixels. can be one number to specify a square window, or a length-2 sequence to specify (width, height).
- background
tuple
(int
,int
,int
) The color definition of the background: (red, green, blue).
- foregroundmatplotlib color
Color of the foreground (will be used for colorbars and text). None (default) will use black or white depending on the value of
background
.- figure
list
ofFigure
|None
|int
If None (default), a new window will be created with the appropriate views. For single view plots, the figure can be specified as int to retrieve the corresponding Mayavi window.
- subjects_dir
str
|None
If not None, this directory will be used as the subjects directory instead of the value set using the SUBJECTS_DIR environment variable.
- views
list
|str
The views to use.
- offsetbool
If True, aligs origin with medial wall. Useful for viewing inflated surface where hemispheres typically overlap (Default: True).
- show_toolbarbool
If True, toolbars will be shown for each view.
- offscreenbool
If True, rendering will be done offscreen (not shown). Useful mostly for generating images or screenshots, but can be buggy. Use at your own risk.
- interaction
str
Can be “trackball” (default) or “terrain”, i.e. a turntable-style camera.
- units
str
Can be ‘m’ or ‘mm’ (default).
- view_layout
str
Can be “vertical” (default) or “horizontal”. When using “horizontal” mode, the PyVista backend must be used and hemi cannot be “split”.
- showbool
Display the window as soon as it is ready. Defaults to True.
- subject_id
Notes
This table shows the capabilities of each Brain backend (”✓” for full support, and “-” for partial support):
3D function:
surfer.Brain
mne.viz.Brain
add_annotation
✓
✓
add_data
✓
✓
add_foci
✓
✓
add_label
✓
✓
add_text
✓
✓
close
✓
✓
data
✓
✓
foci
✓
labels
✓
✓
remove_foci
✓
remove_labels
✓
✓
remove_annotations
✓
scale_data_colormap
✓
save_image
✓
✓
save_movie
✓
✓
screenshot
✓
✓
show_view
✓
✓
TimeViewer
✓
✓
enable_depth_peeling
✓
get_picked_points
✓
add_data(volume)
✓
view_layout
✓
flatmaps
✓
vertex picking
✓
label picking
✓
- Attributes
Methods
__hash__
()Hash the object.
add_annotation
(annot[, borders, alpha, …])Add an annotation file.
add_data
(array[, fmin, fmid, fmax, thresh, …])Display data from a numpy array on the surface or volume.
add_foci
(coords[, coords_as_verts, …])Add spherical foci, possibly mapping to displayed surf.
add_label
(label[, color, alpha, …])Add an ROI label to the image.
add_text
(x, y, text[, name, color, opacity, …])Add a text to the visualization.
Detect automatically fitting scaling parameters.
Clear the picking glyphs.
close
()Close all figures and cleanup data structure.
Enable depth peeling.
Ensure that widgets respect the windows size.
Return the vertices of the picked points.
help
()Display the help window.
plot_time_course
(hemi, vertex_id, color)Plot the vertex time course.
Add the time line to the MPL widget.
Remove all annotations from the image.
Remove all the ROI labels from the image.
reset
()Reset view and time step.
Reset the camera.
Restore original scaling parameters.
save_image
(filename[, mode])Save view from all panels to disk.
save_movie
(filename[, time_dilation, tmin, …])Save a movie (for data with a time axis).
screenshot
([mode, time_viewer])Generate a screenshot of current view.
set_data_smoothing
(n_steps)Set the number of smoothing steps.
set_playback_speed
(speed)Set the time playback speed.
set_time
(time)Set the time to display (in seconds).
set_time_interpolation
(interpolation)Set the interpolation mode.
set_time_point
(time_idx)Set the time point shown (can be a float to interpolate).
setup_time_viewer
([time_viewer, show_traces])Configure the time viewer parameters.
show
()Display the window.
show_view
([view, roll, distance, row, col, hemi])Orient camera to display view.
toggle_interface
([value])Toggle the interface.
toggle_playback
([value])Toggle time playback.
update_lut
([fmin, fmid, fmax, alpha])Update color map.
-
add_annotation
(annot, borders=True, alpha=1, hemi=None, remove_existing=True, color=None, **kwargs)[source]¶ Add an annotation file.
- Parameters
- annot
str
|tuple
Either path to annotation file or annotation name. Alternatively, the annotation can be specified as a
(labels, ctab)
tuple per hemisphere, i.e.annot=(labels, ctab)
for a single hemisphere orannot=((lh_labels, lh_ctab), (rh_labels, rh_ctab))
for both hemispheres.labels
andctab
should be arrays as returned bynibabel.freesurfer.io.read_annot()
.- bordersbool |
int
Show only label borders. If int, specify the number of steps (away from the true border) along the cortical mesh to include as part of the border definition.
- alpha
float
in [0, 1] Alpha level to control opacity.
- hemi
str
|None
If None, it is assumed to belong to the hemipshere being shown. If two hemispheres are being shown, data must exist for both hemispheres.
- remove_existingbool
If True (default), remove old annotations.
- colormatplotlib-style color
code
If used, show all annotations in the same (specified) color. Probably useful only when showing annotation borders.
- **kwargs
dict
These are passed to the underlying
mayavi.mlab.pipeline.surface
call.
- annot
Examples using
add_annotation
:
-
add_data
(array, fmin=None, fmid=None, fmax=None, thresh=None, center=None, transparent=False, colormap='auto', alpha=1, vertices=None, smoothing_steps=None, time=None, time_label='auto', colorbar=True, hemi=None, remove_existing=None, time_label_size=None, initial_time=None, scale_factor=None, vector_alpha=None, clim=None, src=None, volume_options=0.4, colorbar_kwargs=None, verbose=None)[source]¶ Display data from a numpy array on the surface or volume.
This provides a similar interface to
surfer.Brain.add_overlay()
, but it displays it with a single colormap. It offers more flexibility over the colormap, and provides a way to display four-dimensional data (i.e., a timecourse) or five-dimensional data (i.e., a vector-valued timecourse).Note
fmin
sets the low end of the colormap, and is separate from thresh (this is a different convention fromsurfer.Brain.add_overlay()
).- Parameters
- array
numpy
array
, shape (n_vertices[, 3][, n_times]) Data array. For the data to be understood as vector-valued (3 values per vertex corresponding to X/Y/Z surface RAS), then
array
must be have all 3 dimensions. If vectors with no time dimension are desired, consider using a singleton (e.g.,np.newaxis
) to create a “time” dimension and passtime_label=None
(vector values are not supported).- fmin
float
Minimum value in colormap (uses real fmin if None).
- fmid
float
Intermediate value in colormap (fmid between fmin and fmax if None).
- fmax
float
Maximum value in colormap (uses real max if None).
- thresh
None
orfloat
Not supported yet. If not None, values below thresh will not be visible.
- center
float
orNone
If not None, center of a divergent colormap, changes the meaning of fmin, fmax and fmid.
- transparentbool |
None
If True: use a linear transparency between fmin and fmid and make values below fmin fully transparent (symmetrically for divergent colormaps). None will choose automatically based on colormap type.
- colormap
str
,list
of color, orarray
Name of matplotlib colormap to use, a list of matplotlib colors, or a custom look up table (an n x 4 array coded with RBGA values between 0 and 255), the default “auto” chooses a default divergent colormap, if “center” is given (currently “icefire”), otherwise a default sequential colormap (currently “rocket”).
- alpha
float
in [0, 1] Alpha level to control opacity of the overlay.
- vertices
numpy
array
Vertices for which the data is defined (needed if
len(data) < nvtx
).- smoothing_steps
int
orNone
Number of smoothing steps (smoothing is used if len(data) < nvtx) The value ‘nearest’ can be used too. None (default) will use as many as necessary to fill the surface.
- time
numpy
array
Time points in the data array (if data is 2D or 3D).
- time_label
str
|callable()
|None
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
'auto'
, which will usetime=%0.2f ms
if there is more than one time point.- colorbarbool
Whether to add a colorbar to the figure. Can also be a tuple to give the (row, col) index of where to put the colorbar.
- hemi
str
|None
If None, it is assumed to belong to the hemisphere being shown. If two hemispheres are being shown, an error will be thrown.
- remove_existingbool
Not supported yet. Remove surface added by previous “add_data” call. Useful for conserving memory when displaying different data in a loop.
- time_label_size
int
Font size of the time label (default 14).
- initial_time
float
|None
Time initially shown in the plot.
None
to use the first time sample (default).- scale_factor
float
|None
(default) The scale factor to use when displaying glyphs for vector-valued data.
- vector_alpha
float
|None
Alpha level to control opacity of the arrows. Only used for vector-valued data. If None (default),
alpha
is used.- clim
dict
Original clim arguments.
- srcinstance of
SourceSpaces
|None
The source space corresponding to the source estimate. Only necessary if the STC is a volume or mixed source estimate.
- volume_options
float
|dict
|None
Options for volumetric source estimate plotting, with key/value pairs:
'resolution'
float | NoneResolution (in mm) of volume rendering. Smaller (e.g., 1.) looks better at the cost of speed. None (default) uses the volume source space resolution, which is often something like 7 or 5 mm, without resampling.
'blending'
strCan be “mip” (default) for maximum intensity projection or “composite” for composite blending using alpha values.
'alpha'
float | NoneAlpha for the volumetric rendering. Defaults are 0.4 for vector source estimates and 1.0 for scalar source estimates.
'surface_alpha'
float | NoneAlpha for the surface enclosing the volume(s). None (default) will use half the volume alpha. Set to zero to avoid plotting the surface.
'silhouette_alpha'
float | NoneAlpha for a silhouette along the outside of the volume. None (default) will use
0.25 * surface_alpha
.
'silhouette_linewidth'
floatThe line width to use for the silhouette. Default is 2.
A float input (default 1.) or None will be used for the
'resolution'
entry.- colorbar_kwargs
dict
|None
Options to pass to
pyvista.BasePlotter.add_scalar_bar()
(e.g.,dict(title_font_size=10)
).- verbosebool,
str
,int
, orNone
If not None, override default verbose level (see
mne.verbose()
and Logging documentation for more). If used, it should be passed as a keyword-argument only.
- array
Notes
If the data is defined for a subset of vertices (specified by the “vertices” parameter), a smoothing method is used to interpolate the data onto the high resolution surface. If the data is defined for subsampled version of the surface, smoothing_steps can be set to None, in which case only as many smoothing steps are applied until the whole surface is filled with non-zeros.
Due to a Mayavi (or VTK) alpha rendering bug,
vector_alpha
is clamped to be strictly < 1.
-
add_foci
(coords, coords_as_verts=False, map_surface=None, scale_factor=1, color='white', alpha=1, name=None, hemi=None, resolution=50)[source]¶ Add spherical foci, possibly mapping to displayed surf.
The foci spheres can be displayed at the coordinates given, or mapped through a surface geometry. In other words, coordinates from a volume-based analysis in MNI space can be displayed on an inflated average surface by finding the closest vertex on the white surface and mapping to that vertex on the inflated mesh.
- Parameters
- coords
ndarray
, shape (n_coords, 3) Coordinates in stereotaxic space (default) or array of vertex ids (with
coord_as_verts=True
).- coords_as_vertsbool
Whether the coords parameter should be interpreted as vertex ids.
- map_surface
None
Surface to map coordinates through, or None to use raw coords.
- scale_factor
float
Controls the size of the foci spheres (relative to 1cm).
- colormatplotlib color
code
HTML name, RBG tuple, or hex code.
- alpha
float
in [0, 1] Opacity of focus gylphs.
- name
str
Internal name to use.
- hemi
str
|None
If None, it is assumed to belong to the hemipshere being shown. If two hemispheres are being shown, an error will be thrown.
- resolution
int
The resolution of the spheres.
- coords
Examples using
add_foci
:
-
add_label
(label, color=None, alpha=1, scalar_thresh=None, borders=False, hemi=None, subdir=None, reset_camera=True)[source]¶ Add an ROI label to the image.
- Parameters
- label
str
| instance ofLabel
Label filepath or name. Can also be an instance of an object with attributes “hemi”, “vertices”, “name”, and optionally “color” and “values” (if scalar_thresh is not None).
- colormatplotlib-style color |
None
Anything matplotlib accepts: string, RGB, hex, etc. (default “crimson”).
- alpha
float
in [0, 1] Alpha level to control opacity.
- scalar_thresh
None
|float
Threshold the label ids using this value in the label file’s scalar field (i.e. label only vertices with scalar >= thresh).
- bordersbool |
int
Show only label borders. If int, specify the number of steps (away from the true border) along the cortical mesh to include as part of the border definition.
- hemi
str
|None
If None, it is assumed to belong to the hemipshere being shown.
- subdir
None
|str
If a label is specified as name, subdir can be used to indicate that the label file is in a sub-directory of the subject’s label directory rather than in the label directory itself (e.g. for
$SUBJECTS_DIR/$SUBJECT/label/aparc/lh.cuneus.label
brain.add_label('cuneus', subdir='aparc')
).- reset_camerabool
If True, reset the camera view after adding the label. Defaults to True.
- label
Notes
To remove previously added labels, run Brain.remove_labels().
Examples using
add_label
:
-
add_text
(x, y, text, name=None, color=None, opacity=1.0, row=- 1, col=- 1, font_size=None, justification=None)[source]¶ Add a text to the visualization.
- Parameters
- x
float
X coordinate.
- y
float
Y coordinate.
- text
str
Text to add.
- name
str
Name of the text (text label can be updated using update_text()).
- color
tuple
Color of the text. Default is the foreground color set during initialization (default is black or white depending on the background color).
- opacity
float
Opacity of the text (default 1.0).
- row
int
Row index of which brain to use.
- col
int
Column index of which brain to use.
- font_size
float
|None
The font size to use.
- justification
str
|None
The text justification.
- x
Examples using
add_text
:
-
property
data
¶ Data used by time viewer and color bar widgets.
-
property
interaction
¶ The interaction style.
-
save_image
(filename, mode='rgb')[source]¶ Save view from all panels to disk.
Examples using
save_image
:
-
save_movie
(filename, time_dilation=4.0, tmin=None, tmax=None, framerate=24, interpolation=None, codec=None, bitrate=None, callback=None, time_viewer=False, **kwargs)[source]¶ Save a movie (for data with a time axis).
The movie is created through the
imageio
module. The format is determined by the extension, and additional options can be specified through keyword arguments that depend on the format. For available formats and corresponding parameters see the imageio documentation: http://imageio.readthedocs.io/en/latest/formats.html#multiple-imagesWarning
This method assumes that time is specified in seconds when adding data. If time is specified in milliseconds this will result in movies 1000 times longer than expected.
- Parameters
- filename
str
Path at which to save the movie. The extension determines the format (e.g.,
'*.mov'
,'*.gif'
, …; see theimageio
documentation for available formats).- time_dilation
float
Factor by which to stretch time (default 4). For example, an epoch from -100 to 600 ms lasts 700 ms. With
time_dilation=4
this would result in a 2.8 s long movie.- tmin
float
First time point to include (default: all data).
- tmax
float
Last time point to include (default: all data).
- framerate
float
Framerate of the movie (frames per second, default 24).
- interpolation
str
|None
Interpolation method (
scipy.interpolate.interp1d
parameter). Must be one of ‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, or ‘cubic’. If None, it uses the currentbrain.interpolation
, which defaults to'nearest'
. Defaults to None.- codec
str
|None
The codec to use.
- bitrate
float
|None
The bitrate to use.
- callback
callable()
|None
A function to call on each iteration. Useful for status message updates. It will be passed keyword arguments
frame
andn_frames
.- time_viewerbool
If True, include time viewer traces. Only used if
time_viewer=True
andseparate_canvas=False
.- **kwargs
dict
Specify additional options for
imageio
.
- filename
- Returns
- dialogobject
The opened dialog is returned for testing purpose only.
-
screenshot
(mode='rgb', time_viewer=False)[source]¶ Generate a screenshot of current view.
- Parameters
- Returns
- screenshot
array
Image pixel values.
- screenshot
Examples using
screenshot
:
-
set_data_smoothing
(n_steps)[source]¶ Set the number of smoothing steps.
- Parameters
- n_steps
int
Number of smoothing steps.
- n_steps
-
set_playback_speed
(speed)[source]¶ Set the time playback speed.
- Parameters
- speed
float
The speed of the playback.
- speed
-
set_time
(time)[source]¶ Set the time to display (in seconds).
- Parameters
- time
float
The time to show, in seconds.
- time
-
set_time_interpolation
(interpolation)[source]¶ Set the interpolation mode.
- Parameters
- interpolation
str
|None
Interpolation method (
scipy.interpolate.interp1d
parameter). Must be one of ‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, or ‘cubic’.
- interpolation
-
setup_time_viewer
(time_viewer=True, show_traces=True)[source]¶ Configure the time viewer parameters.
-
show_view
(view=None, roll=None, distance=None, row=0, col=0, hemi=None)[source]¶ Orient camera to display view.
- Parameters
Examples using
show_view
:
-
property
time_interpolation
¶ The interpolation mode.