Localization

Convert from MNI152 to FSAverage

naplib.localization.mni152_to_fsaverage(coords)[source]

Convert 3D coordinates from MNI152 space to fsaverage space.

Parameters:

coords (np.ndarray (elecs, 3)) -- Coordinates in MNI space

Returns:

new_coords -- Coordinates in fsaverage space

Return type:

np.ndarray (elecs, 3)

Convert from FSAverage to MNI152

naplib.localization.fsaverage_to_mni152(coords)[source]

Convert 3D coordinates from fsaverage space to MNI152 space.

Parameters:

coords (np.ndarray (elecs, 3)) -- Coordinates in fsaverage space

Returns:

new_coords -- Coordinates in MNI152 space

Return type:

np.ndarray (elecs, 3)

Convert from any source space to any target space

naplib.localization.src_to_dst(coords, src_pial, src_sphere, dst_pial, dst_sphere, require_lh_mask=False, threshold=100, distance_report=False, verbose=False)[source]

Convert 3D coordinates from any space to another space. Each subject comes with a bunch of MRI files; In this function these files are used: 1. lh.pial file of the source space ==> SRC_PATH/surf/lh.pial 2. lh.sphere.reg file of the source ==> SRC_PATH/surf/lh.sphere.reg 3. lh.pial file of the destination ==> DST_PATH/surf/lh.pial 4. lh.sphere.reg file of the destination ==> DST_PATH/surf/lh.sphere.reg

fsLR is also supported: files ending with .gii

Provide LH files, the function assumes the RH ones are in the same directory.

NOTE: In case of converting to an atlas space, the files we need are accessible by installing freesurfer: https://surfer.nmr.mgh.harvard.edu/fswiki/DownloadAndInstall Path of different atlas spaces: PATH_freesurfer/8.0.0/subjects/

Parameters:
  • coords (np.ndarray (elecs, 3)) -- Coordinates in source space. Can be in both hemispheres.

  • src_pial (str/dict{'vert_lh', 'vert_rh'}) -- Path to the source pial surface file (e.g., 'lh.pial'). In case of a mat file for pial surfaces, provide a dictionary with keys 'vert_lh' and 'vert_rh' containing the vertices for each hemisphere.

  • src_sphere (str) -- Path to the source sphere file (e.g., 'lh.sphere.reg')

  • dst_pial (str) -- Path to the destination pial surface file (e.g., 'lh.pial')

  • dst_sphere (str) -- Path to the destination sphere file (e.g., 'lh.sphere.reg')

  • require_lh_mask (bool, optional) -- If True, returns a mask indicating which coordinates are in the left hemisphere. Default is False.

  • threshold (float, optional) -- Maximum distance in mm for an electrode to be considered in cortex (not in depth).

  • distance_report (bool, optional) -- If True, returns the distance of each coordinate to the nearest vertex. Default is False.

  • verbose (bool, optional) -- If True, prints additional information about the conversion process. Default is False.

Returns:

  • new_coords (np.ndarray (elecs, 3)) -- Coordinates in target space

  • lh_mask (np.ndarray (elecs,)) -- Mask indicating which coordinates are in the left hemisphere (if require_lh_mask is True)

  • distance (np.ndarray (elecs,) or None) -- Distance of each coordinate to the nearest vertex in the source pial surface (if distance_report is True)

Localization on a Freesurfer Brain

class naplib.localization.Brain(surf_type: str = 'pial', subject: str = 'fsaverage', coordinate_space: str = 'FSAverage', atlas=None, subject_dir=None)[source]

Brain representation containing a left and right hemisphere. Can be used for plotting, distance calculations, etc.

Parameters:
  • surf_type (str, default='pial') -- Cortical surface type, either 'pial' or 'inflated' or another if the corresponding files can be found.

  • subject (str, default='fsaverage') -- Subject to use, must be a directory within subject_dir

  • coordinate_space (str, default='FSAverage') -- Coordinate space of brain vertices. Must be 'FSAverage' or 'MNI152'

  • atlas (str, default=None) -- Atlas for brain parcellation. Defaults to 'Destrieux' for coordinate_space='FSAverage' and 'Desikan-Killiany' for 'MNI152'. Can also be an annotation file name given by {subject_dir}/{subject}/label/?h.{atlas}.annot

  • subject_dir (str/path-like, defaults to SUBJECT_DIR environment variable, or the current directory) -- if that does not exist. Path containing the subject's folder.

Examples

>>> from naplib.localization import Brain
>>> from naplib.visualization import plot_brain_elecs
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> brain = Brain('pial', subject_dir='path/to/freesurfer/subjects/').split_stg().join_ifg()
>>> coords = np.array([[-47.281147  ,  17.026093  , -21.833099  ],
                       [-48.273964  ,  16.155487  , -20.162935  ]])
>>> isleft = np.array([True, True])
>>> annotations = brain.annotate_coords(coords, isleft)
array(['mSTG','mSTG'])
>>> dist_from_HG = brain.distance_from_region(coords, isleft, region='pmHG', metric='surf')
array([52.67211969 50.86446306])
>>> # plot electrodes on brain with matplotlib
>>> fig, axes = plot_brain_elecs(brain, coords, isleft, values=dist_from_HG, hemi='lh', view='lateral')
>>> plt.show()
>>> # plot electrodes on brain in interactive 3D figure
>>> fig, _ = plot_brain_elecs(brain, coords, isleft, values=dist_from_HG, backend='plotly')
>>> fig.write_html("interactive_brain_plot.html") # save as an interactive html figure
>>> fig.show()
load_labels()[source]

Load Destrieux labels of each vertex from annotation files.

simplify_labels()[source]

Simplify Destrieux labels into shortforms.

split_hg(method='midpoint')[source]

Split HG vertices into posteromedial (pmHG) and anterolateral (alHG) halves.

Parameters:
  • method -- How to split the halves. One of 'midpoint', 'endpoint' or 'median'.

  • str -- How to split the halves. One of 'midpoint', 'endpoint' or 'median'.

split_stg(method='tts_plane')[source]

Split STG into middle (mSTG) and posterior (pSTG) halves.

remove_tts(method='split')[source]

Convert TTS labels into either HG or PT ones.

join_ifg()[source]

Join all three subregion of IFG into one.

annotate(verts, is_left, is_surf=None, text=True)[source]

Get labels for vertices of the surface.

Parameters:
  • verts (np.ndarray) -- Array of vertices.

  • isleft (np.ndarray) -- Boolean array whether each vertex belongs to the left hemisphere.

  • distance_cutoff (float, default=10) -- Electrodes further than this distance (in mm) from the cortical surface will be labeled as "Other"

  • is_surf (boolean np.ndarray) -- Array of the same shape as the number of vertices in the surface (e.g. len(self.lh.surf[0])) indicating whether those points should be included as surface options. If an electrode is closest to a point with a False indicator in this array, then it will get None as its label.

  • text (bool, default=True) -- Whether to return labels as string names, or integer labels.

Returns:

labels -- Array of labels, either as strings or ints.

Return type:

np.ndarray

annotate_coords(coords, isleft=None, distance_cutoff=10, is_surf=None, text=True, get_dists=False)[source]

Get labels (like pmHG, IFG, etc) for coordinates. Note, the coordinates should match the surf_type of this brain, otherwise finding nearest surface points to each coordinate in order to label it may be inaccurate.

Parameters:
  • coords (np.ndarray) -- Array of coordinates, shape (num_elecs, 3).

  • isleft (np.ndarray (elecs,), optional) -- If provided, specifies a boolean which is True for each electrode that is in the left hemisphere. If not given, this will be inferred from the first dimension of the coords (negative is left).

  • distance_cutoff (float, default=10) -- Electrodes further than this distance (in mm) from the cortical surface will be labeled as None

  • is_surf (boolean np.ndarray) -- Array of the same shape as the number of vertices in the surface (e.g. len(self.lh.surf[0])) indicating whether those points should be included as surface options. If an electrode is closest to a point with a False indicator in this array, then it will get None as its label.

  • text (bool, default=True) -- Whether to return labels as string names, or integer labels.

  • get_dists (bool, default=False) -- Whether to return distances for each electrode to the nearest vertex.

Returns:

  • labels (np.ndarray) -- Array of labels, either as strings or ints.

  • dists (np.ndarray, optional) -- Array of minimum distances as floats

distance_from_region(coords, isleft=None, region='pmHG', metric='surf')[source]

Get distance from a certain region for each electrode's coordinates. Can compute distance along the cortical surface or as euclidean distance. For proper results, assuming coordinates are in pial space, the brain must also be in pial space.

Parameters:
  • coords (np.ndarray) -- Array of coordinates in pial space for this brain's subject_id, shape (num_elecs, 3).

  • isleft (np.ndarray (elecs,), optional) -- If provided, specifies a boolean which is True for each electrode that is in the left hemisphere. If not given, this will be inferred from the first dimension of the coords (negative is left).

  • region (str, default='pmHG') -- Anatomical label. Must exist in the labels for the brain.

  • metric ({'surf','euclidean'}, default='surf') -- Either surf, for distance along cortical surface, or euclidean, for euclidean distance.

Returns:

distances -- Array of distances, in mm.

Return type:

np.ndarray

paint_overlay(labels, value=1)[source]

Paint brain region(s) specified by label(s).

Parameters:
  • labels (str | list[str]) -- Region or regions to paint an overlay.

  • value (float, default=1) -- Value to paint the region overlay with.

Returns:

self

Return type:

an instance of self

mark_overlay(verts, isleft, value=1, inner_radius=0.8, taper=True)[source]

Fill circle(s) around target(s).

Parameters:
  • verts (np.ndarray) -- Vertices to mark.

  • isleft (np.ndarray of booleans) -- Indicator of same shape as verts for whether they are in the left hemisphere.

  • value (float, default=1) -- Value to mark with.

  • inner_radius (float, default=0.8) -- Radius of circle to mark around each vertex.

  • taper (bool, default=True) -- Whether to taper the circular mark.

Returns:

self

Return type:

instance of self

set_visible(labels, min_alpha=0)[source]

Set certain regions as visible with a float label, and the rest will be invisible.

Parameters:
  • labels (str | list[str]) -- Label(s) to set as visible.

  • min_alpha (float, default=0)

Returns:

self

Return type:

instance of self

reset_overlay_except(labels)[source]

Keep certain regions and the rest as colorless.

Parameters:

labels (str | list[str]) -- Label(s) to set as visible.

Returns:

self

Return type:

instance of self

interpolate_electrodes_onto_brain(coords, values, isleft=None, k=10, max_dist=10, roi='all', reset_overlay_first=True)[source]

Use electrode coordinates to interpolate 1-dimensional values corresponding to each electrode onto the brain's surface.

Parameters:
  • coords (np.ndarray (elecs, 3)) -- 3D coordinates of electrodes

  • values (np.ndarray (elecs,)) -- Value for each electrode

  • isleft (np.ndarray (elecs,), optional) -- If provided, specifies a boolean which is True for each electrode that is in the left hemisphere. If not given, this will be inferred from the first dimension of the coords (negative is left).

  • k (int, default=10) -- Number of nearest neighbors to consider

  • max_dist (float, default=10) -- Maximum distance (in mm) outside of which nearest neighbors will be ignored

  • roi (list of strings, or string in {'all', 'temporal'}, default='all') -- Regions to allow interpolation over. By default, the entire brain surface is allowed. Can also be specified as a list of string labels (drawing from self.lh.label_names)

  • reset_overlay_first (bool, default=True) -- If True (default), reset the overlay before creating a new overlay

Notes

After running this function, you can use the visualization function plot_brain_overlay for a quick matplotlib plot, or you can extract the surface values from the self.lh.overlay and self.rh.overlay attributes, etc, for plotting with another tool like pysurfer or plotly.

parcellate_overlay(merge_func=<function mean>)[source]

Merges brain overlay values within each atlas parcel.

This method applies a merging function to the overlay values within each anatomical parcel defined by an atlas. It is typically used after interpolating electrode data onto the brain surface (e.g., via brain.interpolate_electrodes_onto_brain()) to summarize the data within each parcel.

Parameters:

merge_func (callable, default=numpy.mean) -- The function used to combine the overlay values within each parcel. The function should accept an array-like object of values and return a single value. Common examples include numpy.mean (default), numpy.median, and numpy.max.

Returns:

self -- Returns the instance itself, with the overlay data parcellated.

Return type:

instance of self

Examples using ``Brain ``

Plot Intracranial Electrodes

Plot Intracranial Electrodes