### Install BrainSpace from GitHub Source: https://github.com/mica-mni/brainspace/blob/master/docs/pages/install.rst Install BrainSpace directly from its GitHub repository. This method involves cloning the repository and running the setup script. ```bash git clone https://github.com/MICA-MNI/BrainSpace.git cd BrainSpace python setup.py install ``` -------------------------------- ### Install BrainSpace using pip Source: https://github.com/mica-mni/brainspace/blob/master/docs/pages/install.rst Use this command to install the BrainSpace package via pip. Ensure you have Python 3.5+ installed. ```bash pip install brainspace ``` -------------------------------- ### GradientMaps with Joint Alignment Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/index_intro.rst Initializes and fits a GradientMaps object using the 'joint' alignment method. This example shows the disparity before and after alignment when using the 'joint' approach. ```python gm3 = GradientMaps(n_gradients=2, approach='le', kernel='normalized_angle', alignment='joint') gm3.fit([x1, x2]) # the disparity between the gradients np.sum(np.square(gm3.gradients_[0] - gm3.gradients_[1])) # with 'manifold', the embedding and alignment are performed simultaneously np.sum(np.square(gm3.aligned_[0] - gm3.aligned_[1])) ``` -------------------------------- ### Retrieving Cell Types in BSPolyData Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/vtk_wrap.rst Demonstrates how to get the cell types present in a BSPolyData object and verify them against VTK constants. ```python output2.cell_types vtk.VTK_TRIANGLE == 5 ``` -------------------------------- ### Fetch Preprocessed Timeseries Data Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/auto_examples/plot_tutorial0.ipynb Fetches preprocessed timeseries data for use in gradient analysis. This is a convenient way to get sample data. ```python from brainspace.datasets import fetch_timeseries_preprocessing timeseries = fetch_timeseries_preprocessing() ``` -------------------------------- ### Load Conte69 Surfaces (Python) Source: https://github.com/mica-mni/brainspace/blob/master/docs/pages/getting_started.rst Loads the default conte69 surface data for both left and right hemispheres. Use this to get started with surface-based analysis. ```python from brainspace.datasets import load_conte69 # Load left and right hemispheres surf_lh, surf_rh = load_conte69() surf_lh.n_points 32492 surf_rh.n_points 32492 ``` -------------------------------- ### Wrap VTK object and access properties Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/vtk_wrap.rst Demonstrates wrapping a VTK object and using getVTK to retrieve properties. Also shows how to set new values using setVTK. ```python import vtk # Let's create a sphere with VTK s = vtk.vtkSphere() # And check the default values s.GetRadius() s.GetCenter() # We are going to wrap the sphere from brainspace.vtk_interface import wrap_vtk ws = wrap_vtk(s) # ws is an instance of BSVTKObjectWrapper # and holds a reference to the VTK sphere ws.VTKObject # Now we can invoke getter methods as follows: ws.getVTK('radius', center=None) # and set different values ws.setVTK(radius=2, center=(1.5, 1.5, 1.5)) # To check that everything works as expected s.GetRadius() s.GetCenter() # these methods can be invoked on the wrapper, which forwards # them to the VTK object ws.GetRadius() ``` -------------------------------- ### Build VTK Pipeline Serially Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/vtk_wrap.rst Demonstrates constructing a VTK pipeline by connecting filters sequentially using `wrap_vtk` for cleaner syntax compared to manual `SetInputConnection` calls. ```python import vtk from brainspace.vtk_interface import wrap_vtk point_source = wrap_vtk(vtk.vtkPointSource, numberOfPoints=25) delauny = wrap_vtk(vtk.vtkDelaunay2D, tolerance=0.01) smooth_filter = wrap_vtk(vtk.vtkWindowedSincPolyDataFilter, numberOfIterations=20, featureEdgeSmoothing=True, nonManifoldSmoothing=True) normals_filter = wrap_vtk(vtk.vtkPolyDataNormals, splitting=False, consistency=True, autoOrientNormals=True, computePointNormals=True) output1 = normals_filter.execute(smooth_filter, delauny, point_source) output1.GetNumberOfPoints() ``` -------------------------------- ### Setting up a BrainSpace Plotter Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/vtk_wrap.rst Illustrates the initialization of a BrainSpace Plotter with specified dimensions and rendering options. Other arguments are forwarded to the underlying VTK render window. ```python from brainspace.mesh import mesh_io as mio from brainspace.plotting.base import Plotter ipth = 'path_to_surface' surf = mio.read_surface(ipth, return_data=True) yeo7_colors = np.array([[0, 0, 0, 255], [0, 118, 14, 255], [230, 148, 34, 255], [205, 62, 78, 255], [120, 18, 134, 255], [220, 248, 164, 255], [70, 130, 180, 255], [196, 58, 250, 255]], dtype=np.uint8) p = Plotter(n_rows=2, n_cols=2, try_qt=False, size=(400, 400)) ren1 = p.AddRenderer(row=0, col=None, background=(1,1,1)) ac1 = ren1.AddActor() ``` -------------------------------- ### Wrap VTK Actor and Instantiate Wrapper Directly Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/vtk_wrap.rst Shows how to wrap a VTK actor and how to directly instantiate its corresponding BrainSpace wrapper class. Arguments can be passed during direct instantiation. ```python import vtk from brainspace.vtk_interface import wrap_vtk wa = wrap_vtk(vtk.vtkActor()) wa ``` ```python from brainspace.vtk_interface.wrappers import BSActor wa2 = BSActor() wa2 ``` ```python wa3 = BSActor(mapper=wm) wa3.mapper.VTKObject is wm.VTKObject wa3.mapper.VTKObject is m ``` -------------------------------- ### Wrap VTK object with initial values Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/vtk_wrap.rst Illustrates using wrap_vtk to simultaneously wrap a VTK object and set its initial properties. ```python ws2 = wrap_vtk(vtk.vtkSphere(), radius=10, center=(5, 5, 0)) ws2.getVTK('radius', 'center') ws2.VTKObject.GetRadius() ws2.VTKObject.GetCenter() ``` -------------------------------- ### Load Sample Data Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/auto_examples/plot_tutorial1.ipynb Loads mean connectivity matrix, parcellation labels, and cortical surfaces. Requires `brainspace.datasets`. ```python from brainspace.datasets import load_group_fc, load_parcellation, load_conte69 # First load mean connectivity matrix and Schaefer parcellation conn_matrix = load_group_fc('schaefer', scale=400) labeling = load_parcellation('schaefer', scale=400, join=True) # and load the conte69 surfaces surf_lh, surf_rh = load_conte69() ``` -------------------------------- ### Plot Original and Rotated T1w/T2w Data Source: https://github.com/mica-mni/brainspace/blob/master/docs/pages/matlab_doc/examples/tutorial_3_null_models.rst Visualizes the original T1w/T2w data on hemisphere surfaces and plots a few examples of the rotated versions to illustrate the effect of spin permutations. ```matlab % Plot original data h1 = plot_hemispheres([t1wt2w_lh;t1wt2w_rh],{surf_lh,surf_rh}); ``` ```matlab % Plot a few of the rotations h2 = plot_hemispheres(t1wt2w_rotated(:,1:3),{surf_lh,surf_rh}); ``` -------------------------------- ### Call VTK state methods via wrapper Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/vtk_wrap.rst Shows how VTK state methods, like SetColorModeToDefault, can be invoked through the wrapper interface. ```python # Let's create a mapper m = vtk.vtkPolyDataMapper() # This class has several state methods to set the color mode [m for m in dir(m) if m.startswith('SetColorModeTo')] ``` -------------------------------- ### Load Data for Gradient Significance Testing Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/auto_examples/plot_tutorial3.rst Loads surface data, spheres, marker data (t1w/t2w intensity, cortical thickness), and a template functional gradient. This is the initial setup for assessing gradient significance. ```default import numpy as np from brainspace.datasets import load_gradient, load_marker, load_conte69 # load the conte69 hemisphere surfaces and spheres surf_lh, surf_rh = load_conte69() sphere_lh, sphere_rh = load_conte69(as_sphere=True) # Load the data t1wt2w_lh, t1wt2w_rh = load_marker('t1wt2w') t1wt2w = np.concatenate([t1wt2w_lh, t1wt2w_rh]) thickness_lh, thickness_rh = load_marker('thickness') thickness = np.concatenate([thickness_lh, thickness_rh]) # Template functional gradient embedding = load_gradient('fc', idx=0, join=True) ``` -------------------------------- ### VTK Rendering Wrappers Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/api_doc/brainspace.vtk_interface.rst Wrappers for VTK rendering components. ```APIDOC ## Rendering Wrappers ### Description Wrappers for VTK rendering components, including renderers, render windows, and interactor styles. ### Classes - **BSRenderer**: Wrapper for VTK renderers. - **BSRenderWindow**: Wrapper for VTK render windows. - **BSRenderWindowInteractor**: Wrapper for render window interactor. - **BSGenericRenderWindowInteractor**: Generic interactor for render windows. - **BSInteractorStyle**: Base class for interactor styles. - **BSInteractorStyleJoystickCamera**: Joystick-style camera interactor. - **BSInteractorStyleJoystickActor**: Joystick-style actor interactor. - **BSInteractorStyleTerrain**: Terrain interaction style. - **BSInteractorStyleRubberBandZoom**: Rubber band zoom interactor style. - **BSInteractorStyleTrackballActor**: Trackball actor interactor style. - **BSInteractorStyleTrackballCamera**: Trackball camera interactor style. - **BSInteractorStyleImage**: Image interaction style. - **BSInteractorStyleRubberBandPick**: Rubber band pick interactor style. - **BSInteractorStyleSwitchBase**: Base class for interactor style switching. - **BSInteractorStyleSwitch**: Interactor style switching. - **BSCamera**: Wrapper for VTK cameras. ``` -------------------------------- ### Inspect VTK mapping for attribute access Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/vtk_wrap.rst Demonstrates how to inspect the vtk_map dictionary within BSVTKObjectWrapper to understand available attribute mappings for VTK methods. ```python ws.vtk_map.keys() # for getter methods ws.vtk_map['get'] # To access the reference count, for example, these are the same ws.referencecount ws.ReferenceCount ``` -------------------------------- ### Wrap VTK Object and Modify Properties Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/vtk_wrap.rst Demonstrates wrapping a VTK object and using the wrapper to set properties. The wrapper provides attribute-like access for VTK methods. ```python from vtk.vtkCommonCore import vtkPolyDataMapper from brainspace.vtk_interface import wrap_vtk m = vtkPolyDataMapper() wm = wrap_vtk(m) wm.colorModeToMapScalars = None wm.GetColorModeAsString() ``` ```python wm.colorMode = 'DirectScalars' wm.GetColorModeAsString() ``` ```python m2 = wrap_vtk(vtkPolyDataMapper(), colorMode='mapScalars', scalarVisibility=False) m2.getVTK('colorModeAsString', 'scalarVisibility') ``` -------------------------------- ### VTK Algorithm Wrappers Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/api_doc/brainspace.vtk_interface.rst Wrappers for VTK algorithms and filters. ```APIDOC ## Algorithm Wrappers ### Description Wrappers for VTK algorithms, including general algorithms and specific filters for image writing and window capture. ### Classes - **BSAlgorithm**: Base wrapper for VTK algorithms. - **BSPolyDataAlgorithm**: Wrapper for algorithms that operate on polygonal data. - **BSWindowToImageFilter**: Wrapper for capturing window content as an image. - **BSImageWriter**: Base class for image writers. - **BSBMPWriter**: Writer for BMP image format. - **BSJPEGWriter**: Writer for JPEG image format. - **BSPNGWriter**: Writer for PNG image format. - **BSPostScriptWriter**: Writer for PostScript files. - **BSTIFFWriter**: Writer for TIFF image format. ``` -------------------------------- ### GradientMaps Initialization Source: https://github.com/mica-mni/brainspace/blob/master/docs/pages/matlab_doc/main_functionality/gradientmaps.rst Initializes a GradientMaps object. Various name-value pairs can be provided to configure the kernel, approach, alignment, random state, number of components, and verbosity. ```APIDOC ## GradientMaps Initialization ### Description Initializes a GradientMaps object with optional configuration parameters. ### Usage ```matlab gm = GradientMaps(varargin_1); ``` ### Parameters #### Name-Value Pairs - **kernel**: Specifies the kernel to use. Options include 'none', 'pearson', 'spearman', 'gaussian', 'cosine similarity', 'normalized angle', or a function handle. - **approach**: Specifies the dimensionality reduction approach. Options include 'principal component analysis', 'laplacian eigenmap', 'diffusion embedding', or a function handle. - **alignment**: Specifies the alignment method. Options include 'none', 'procrustes analysis', or 'joint alignment', or a function handle. - **random_state**: Sets the random seed for reproducibility. Accepts any input for MATLAB's `rng` function or `nan` for the current state. - **n_components**: The number of components to compute (default: 10). - **verbose**: Boolean to control display of non-warning/error messages (default: false). ### Example ```matlab gm = GradientMaps('kernel','g','approach','pca','alignment','','random_state',10,'verbose',true); ``` ``` -------------------------------- ### Fit Gradient Maps and Visualize Source: https://github.com/mica-mni/brainspace/blob/master/docs/pages/matlab_doc/examples/tutorial_2_gradient_customization.rst Fit gradient maps using a specified kernel and sparsity. Visualize the first two eigenvectors of the computed gradients. ```matlab gm = GradientMaps('kernel','na'); gm = gm.fit(fused_matrix, 'Sparsity', 0); h = plot_hemispheres(gm.gradients{1}(:,1:2), ... {surf_lh,surf_rh}, ... 'parcellation', labeling, ... 'labeltext',{'eigenvector1','eigenvector2'}); ``` -------------------------------- ### VTK Property Wrappers Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/api_doc/brainspace.vtk_interface.rst Wrappers for VTK property objects. ```APIDOC ## Property Wrappers ### Description Wrappers for VTK property objects, controlling the appearance of actors. ### Classes - **BSProperty**: Base wrapper for VTK properties. - **BSProperty2D**: Wrapper for 2D properties. - **BSTextProperty**: Wrapper for text properties. ``` -------------------------------- ### Initialize Sampled Surrogate Maps Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/auto_examples/plot_tutorial3.ipynb Initializes the SampledSurrogateMaps object for generating surrogate datasets. This is recommended for large datasets to manage computational and memory resources. ```python from brainspace.null_models import SampledSurrogateMaps n_surrogate_datasets = 1000 ``` -------------------------------- ### Initialize GradientMaps Object Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/index_intro.rst Initializes the GradientMaps class with specified parameters for gradient computation and alignment. The affinity matrix is built using 'normalized_angle', gradients are found using 'le' (Laplacian eigenmaps), and alignment is done via 'procrustes'. ```python from brainspace.gradient import GradientMaps # We build the affinity matrix using 'normalized_angle', # use Laplacian eigenmaps (i.e., 'le') to find the gradients # and align gradients using procrustes gm = GradientMaps(n_gradients=2, approach='le', kernel='normalized_angle', alignment='procrustes') ``` -------------------------------- ### Initialize and Fit Spin Permutations Model Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/auto_examples/plot_tutorial3.ipynb Initializes the SpinPermutations model with a specified number of repetitions and fits it to the spherical data. This prepares the model for generating rotated data. ```python from brainspace.null_models import SpinPermutations from brainspace.plotting import plot_hemispheres # Let's create some rotations n_rand = 1000 sp = SpinPermutations(n_rep=n_rand, random_state=0) sp.fit(sphere_lh, points_rh=sphere_rh) t1wt2w_rotated = np.hstack(sp.randomize(t1wt2w_lh, t1wt2w_rh)) thickness_rotated = np.hstack(sp.randomize(thickness_lh, thickness_rh)) ``` -------------------------------- ### VTK Lookup Table Wrappers Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/api_doc/brainspace.vtk_interface.rst Wrappers for VTK lookup table objects used for color mapping. ```APIDOC ## Lookup Table Wrappers ### Description Wrappers for VTK lookup table objects, used to map scalar values to colors. ### Classes - **BSScalarsToColors**: Maps scalars to colors. - **BSLookupTable**: Base lookup table wrapper. - **BSLookupTableWithEnabling**: Lookup table with enabling functionality. - **BSWindowLevelLookupTable**: Lookup table for window/level adjustments. - **BSColorTransferFunction**: Transfer function for color mapping. - **BSDiscretizableColorTransferFunction**: Discretizable color transfer function. ``` -------------------------------- ### Load Sample Data for Gradient Maps Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/auto_examples/plot_tutorial2.ipynb Loads functional connectivity data and parcellation labels, along with surface data, required for gradient analysis. ```python from brainspace.datasets import load_group_fc, load_parcellation, load_conte69 # First load mean connectivity matrix and Schaefer parcellation conn_matrix = load_group_fc('schaefer', scale=400) labeling = load_parcellation('schaefer', scale=400, join=True) mask = labeling != 0 # and load the conte69 hemisphere surfaces surf_lh, surf_rh = load_conte69() ``` -------------------------------- ### Custom Multi-Panel Surface Visualization with plot_surf Source: https://context7.com/mica-mni/brainspace/llms.txt Enables detailed control over surface visualization layouts, views, color maps, and shared color ranges for complex arrangements. Requires surface data and a layout definition. ```python import numpy as np from brainspace.datasets import load_conte69, load_gradient from brainspace.plotting import plot_surf surf_lh, surf_rh = load_conte69() fc_g1_lh, fc_g1_rh = load_gradient('fc', idx=0) surf_lh.append_array(fc_g1_lh, name='fc_grad1', at='p') surf_rh.append_array(fc_g1_rh, name='fc_grad1', at='p') surfs = {'lh': surf_lh, 'rh': surf_rh} layout = [['lh', 'rh'], ['lh', 'rh']] plot_surf( surfs, layout, array_name='fc_grad1', view=[['lateral', 'lateral'], ['medial', 'medial']], color_bar='bottom', share='row', cmap='viridis', label_text={'top': ['Left', 'Right']}, size=(800, 600), zoom=1.4, screenshot=True, filename='custom_layout.png' ) ``` -------------------------------- ### Initialize GradientMaps Object Source: https://github.com/mica-mni/brainspace/blob/master/docs/pages/matlab_doc/main_functionality/gradientmaps.rst Initialize a GradientMaps object with default settings or custom parameters. Name-value pairs can be provided to configure the kernel, approach, alignment, random state, number of components, and verbosity. ```matlab gm = GradientMaps(); ``` ```matlab gm = GradientMaps('kernel','g','approach','pca','alignment','','random_state',10,'verbose',true); ``` -------------------------------- ### Generate Surrogate Datasets with SampledSurrogateMaps Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/auto_examples/plot_tutorial3.rst Generates surrogate datasets using the SampledSurrogateMaps class, which is more computationally efficient for large datasets. It requires fitting the model with the geodesic distance and sorted indices, then randomizing the original data. ```python from brainspace.null_models import SampledSurrogateMaps n_surrogate_datasets = 1000 # Note: number samples must be greater than number neighbors num_samples = 100 num_neighbors = 50 ssm = SampledSurrogateMaps(ns=num_samples, knn=num_neighbors, random_state=0) ssm.fit(gd, idx_sorted) t1wt2w_surrogates = ssm.randomize(t1wt2w_tl, n_rep=n_surrogate_datasets) curv_surrogates = ssm.randomize(curv_tl, n_rep=n_surrogate_datasets) ``` -------------------------------- ### Generate Surrogate Maps Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/auto_examples/plot_tutorial3.ipynb Initializes and fits a SampledSurrogateMaps object to generate surrogate datasets for observed data. Ensure the number of samples is greater than the number of neighbors. ```python num_samples = 100 num_neighbors = 50 ssm = SampledSurrogateMaps(ns=num_samples, knn=num_neighbors, random_state=0) ssm.fit(gd, idx_sorted) t1wt2w_surrogates = ssm.randomize(t1wt2w_tl, n_rep=n_surrogate_datasets) curv_surrogates = ssm.randomize(curv_tl, n_rep=n_surrogate_datasets) ``` -------------------------------- ### VTK Mapper Wrappers Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/api_doc/brainspace.vtk_interface.rst Wrappers for VTK mapper objects used in rendering. ```APIDOC ## Mapper Wrappers ### Description Wrappers for VTK mapper objects, which are responsible for mapping data to graphics primitives. ### Classes - **BSDataSetMapper**: Mapper for general datasets. - **BSPolyDataMapper**: Mapper for polygonal data. - **BSLabeledContourMapper**: Mapper for labeled contours. - **BSLabeledDataMapper**: Mapper for labeled data. - **BSLabelPlacementMapper**: Mapper for placing labels. - **BSPolyDataMapper2D**: 2D mapper for polygonal data. - **BSTextMapper2D**: 2D mapper for text. ``` -------------------------------- ### Compare Different Kernels for Gradient Computation Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/auto_examples/plot_tutorial2.rst Compares gradient computation using 'pearson', 'spearman', and 'normalized_angle' kernels. The resulting gradients are mapped to labels for visualization. ```python import numpy as np from brainspace.gradient import GradientMaps from brainspace.plotting import plot_hemispheres from brainspace.utils.parcellation import map_to_labels kernels = ['pearson', 'spearman', 'normalized_angle'] gradients_kernel = [None] * len(kernels) for i, k in enumerate(kernels): gm = GradientMaps(kernel=k, approach='dm', random_state=0) gm.fit(conn_matrix) gradients_kernel[i] = map_to_labels(gm.gradients_[:, i], labeling, mask=mask, fill=np.nan) label_text = ['Pearson', 'Spearman', 'Normalized\nAngle'] plot_hemispheres(surf_lh, surf_rh, array_name=gradients_kernel, size=(1200, 600), cmap='viridis_r', color_bar=True, label_text=label_text, zoom=1.45) ``` -------------------------------- ### Basic Wrapping Functions Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/api_doc/brainspace.vtk_interface.rst Functions for wrapping and identifying VTK objects within BrainSpace. ```APIDOC ## Basic Wrapping ### Description Provides functions to wrap and identify VTK objects, along with a base class for BrainSpace VTK object wrappers. ### Functions - **wrap_vtk(obj)**: Wraps a VTK object. - **is_vtk(obj)**: Checks if an object is a VTK object. - **is_wrapper(obj)**: Checks if an object is a BrainSpace VTK wrapper. ### Classes - **BSVTKObjectWrapper**: Base class for BrainSpace VTK object wrappers. ``` -------------------------------- ### VTK Miscellanea Wrappers Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/api_doc/brainspace.vtk_interface.rst Miscellaneous VTK wrappers provided by BrainSpace. ```APIDOC ## Miscellanea Wrappers ### Description Miscellaneous wrappers for VTK objects, including collections and cell arrays. ### Classes - **BSCellArray**: Wrapper for cell arrays. - **BSGL2PSExporter**: Exporter for GL2PS format. - **BSCollection**: Base class for VTK collections. - **BSPropCollection**: Collection of VTK properties. - **BSActor2DCollection**: Collection of 2D actors. - **BSActorCollection**: Collection of VTK actors. - **BSProp3DCollection**: Collection of 3D properties. - **BSMapperCollection**: Collection of VTK mappers. - **BSRendererCollection**: Collection of VTK renderers. - **BSPolyDataCollection**: Collection of polygonal data. - **BSTextPropertyCollection**: Collection of text properties. - **BSCoordinate**: Wrapper for VTK coordinates. ``` -------------------------------- ### Access VTK properties as attributes Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/vtk_wrap.rst Shows how VTK setters and getters can be accessed as attributes on the wrapper object, simplifying interaction. ```python # we can access to the radius and center ws.radius ws.center # and even set new values ws.radius = 8 ws.center = (10, 10, 10) # check that everything's ok s.GetRadius() s.GetCenter() ``` -------------------------------- ### Compare Gradient Alignment Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/index_intro.rst Illustrates the effect of alignment by comparing the disparity (sum of squared differences) between original and aligned gradients of two datasets. Lower disparity indicates better alignment. ```python import numpy as np # Disparity between the original gradients np.sum(np.square(gm.gradients_[0] - gm.gradients_[1])) # disparity is decreased after alignment np.sum(np.square(gm.aligned_[0] - gm.aligned_[1])) ``` -------------------------------- ### Variogram Object Creation and Fitting Source: https://github.com/mica-mni/brainspace/blob/master/docs/pages/matlab_doc/main_functionality/variogram.rst This snippet demonstrates how to create a variogram object and use its fit method to generate surrogate datasets. ```APIDOC ## variogram ### Description Generates null model data correcting for spatial autocorrelation. ### Usage ```matlab obj = variogram(D,varargin); surrogates = obj.fit(x,n); ``` ### Parameters #### Input Arguments - **D** (symmetric distance matrix) - A symmetric distance matrix. - **varargin** - See name-value pairs below. #### Output Arguments - **obj** (variogram object) - The variogram object. - **surrogates** (surrogate datasets) - Surrogate datasets. ### Name-Value Pairs - **deltas** (proportion, default: 0.1:0.1:0.9) - Proportion of neighbours to include for smoothing. - **kernel** (string or function handle, default: 'exp') - Kernel with which to smooth permuted maps. Valid options are 'gaussian', 'exp', 'invdist', 'uniform', and a function handle. - **pv** (percentile, default: 25) - Percentile of pairwise distance distribution at which to truncate during variogram fitting. - **nh** (integer, default: 25) - Number of uniformly spaced distances at which to compute variograms. - **resample** (boolean, default: false) - Resample surrogate maps' values from target brain map. - **b** (numeric, default: three times the spacing between variogram x-coordinates) - Gaussian kernel bandwidth for variogram smoothing. - **random_state** (any valid input for rng()) - Seed for random number generator. Set to nan for no random initialization. - **ns** (integer, default: inf) - Number of samples to use when subsampling the brainmap. - **knn** (integer, default: 1000) - Number of nearest neighbours to use when smoothing the map. Must be smaller than ns. - **num_workers** (integer, default: 0) - Number of workers in the parallel pool. Requires the parallel processing toolbox. Set to 0 for no parallelization. ### Description Implementation of the variogram matching procedure as presented by (Burt et al., 2020). This class generates surrogate data by permuting the input data, smoothing it with different kernels, and determining which smoothed permuted map best fits the variogram of the empirical data. ``` -------------------------------- ### Construct Gradients Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/auto_examples/plot_tutorial1.ipynb Initializes and fits the GradientMaps model to the connectivity matrix to compute gradients. Requires `brainspace.gradient`. ```python from brainspace.gradient import GradientMaps # Ask for 10 gradients (default) gm = GradientMaps(n_components=10, random_state=0) gm.fit(conn_matrix) ``` -------------------------------- ### Load and Plot fsaverage5 Surfaces Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/auto_examples/plot_tutorial0.ipynb Loads the fsaverage5 surface data and plots the left and right hemispheres with gradient information. Ensure 'grad' is defined before running. ```python surf_lh, surf_rh = load_fsa5() plot_hemispheres(surf_lh, surf_rh, array_name=grad, size=(1200, 400), cmap='viridis_r', color_bar=True, label_text=['Grad1', 'Grad2'], zoom=1.5) ``` -------------------------------- ### Plot First Gradient (Python) Source: https://github.com/mica-mni/brainspace/blob/master/docs/pages/getting_started.rst Maps the first computed gradient to the original surface labeling and plots it on the cortical hemispheres. Requires numpy and mapping utilities. ```python import numpy as np from brainspace.utils.parcellation import map_to_labels # map to original size grad = map_to_labels(gm.gradients_[:, 0], labeling, mask=labeling != 0, fill=np.nan) # Plot first gradient on the cortical surface. plot_hemispheres(surf_lh, surf_rh, array_name=grad, size=(800, 200)) ``` -------------------------------- ### VTK Data Object Wrappers Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/api_doc/brainspace.vtk_interface.rst Wrappers for various VTK data object types. ```APIDOC ## Data Object Wrappers ### Description Wrappers for common VTK data object types, providing a consistent interface for BrainSpace. ### Classes - **BSDataObject**: Base wrapper for VTK data objects. - **BSTable**: Wrapper for VTK table data. - **BSCompositeDataSet**: Wrapper for composite datasets. - **BSDataSet**: Wrapper for VTK datasets. - **BSPointSet**: Wrapper for point sets. - **BSPolyData**: Wrapper for polygonal data. - **BSUnstructuredGrid**: Wrapper for unstructured grids. ``` -------------------------------- ### Wrap VTK Objects with wrap_vtk Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/vtk_wrap.rst Demonstrates wrapping VTK objects using the wrap_vtk function. This is useful for applying VTK filters and processing data within BrainSpace. ```python from brainspace.vtk_interface import wrap_vtk import vtk # Create a source and a filter point_source = vtk.vtkPointSource() point_source.SetNumberOfPoints(50) point_source.Update() delauny = wrap_vtk(vtk.vtkDelaunay2D) # Create a smoothing filter smooth_filter = wrap_vtk(vtk.vtkWindowedSincPolyDataFilter, numberOfIterations=20, featureEdgeSmoothing=True, nonManifoldSmoothing=True) # Compute normals normals_filter = wrap_vtk(vtk.vtkPolyDataNormals, splitting=False, consistency=True, autoOrientNormals=True, computePointNormals=True) # Execute and get the output output2 = serial_connect(point_source, delauny, smooth_filter, normals_filter, as_data=True) output2 ``` -------------------------------- ### Compute and Plot Gradients with Different Kernels Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/auto_examples/plot_tutorial2.ipynb Computes and visualizes the first gradient using Pearson, Spearman, and Normalized Angle kernels. Requires BrainSpace and NumPy. ```python import numpy as np from brainspace.gradient import GradientMaps from brainspace.plotting import plot_hemispheres from brainspace.utils.parcellation import map_to_labels kernels = ['pearson', 'spearman', 'normalized_angle'] gradients_kernel = [None] * len(kernels) for i, k in enumerate(kernels): gm = GradientMaps(kernel=k, approach='dm', random_state=0) gm.fit(conn_matrix) gradients_kernel[i] = map_to_labels(gm.gradients_[:, 0], labeling, mask=mask, fill=np.nan) label_text = ['Pearson', 'Spearman', 'Normalized\nAngle'] plot_hemispheres(surf_lh, surf_rh, array_name=gradients_kernel, size=(1200, 600), cmap='viridis_r', color_bar=True, label_text=label_text, zoom=1.45) ``` -------------------------------- ### VTK Actor Wrappers Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/api_doc/brainspace.vtk_interface.rst Wrappers for VTK actor objects used in scene rendering. ```APIDOC ## Actor Wrappers ### Description Wrappers for VTK actor objects, which represent objects in a 3D scene. ### Classes - **BSActor2D**: Wrapper for 2D actors. - **BSScalarBarActor**: Actor for displaying a scalar bar. - **BSTexturedActor2D**: Wrapper for 2D actors with textures. - **BSTextActor**: Wrapper for text actors. - **BSActor**: Base wrapper for VTK actors. ``` -------------------------------- ### Pipeline Functionality Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/api_doc/brainspace.vtk_interface.rst Functions for managing and connecting VTK pipeline objects. ```APIDOC ## Pipeline Functionality ### Description Functions to manage the VTK pipeline, including connecting objects, retrieving outputs, and converting data. ### Functions - **serial_connect(producer, consumer)**: Connects a producer to a consumer in the serial pipeline. - **get_output(obj)**: Retrieves the output of a VTK algorithm. - **to_data(obj)**: Converts a VTK object to a BrainSpace data format. - **connect(producer, consumer)**: Connects two VTK objects in a pipeline. ``` -------------------------------- ### Multi-Subject Gradient Alignment with GradientMaps Source: https://context7.com/mica-mni/brainspace/llms.txt Demonstrates aligning gradients from multiple subjects using either joint embedding or Procrustes analysis. It also shows how to align a single new subject's gradients to a pre-computed reference. ```python from brainspace.datasets import load_group_fc from brainspace.gradient import GradientMaps # Simulate two subject connectivity matrices conn_group = load_group_fc('schaefer', scale=200) # (200, 200) conn_holdout = load_group_fc('schaefer', scale=200, group='holdout') # Joint alignment: embed both subjects simultaneously gm_joint = GradientMaps(n_components=5, approach='dm', alignment='joint', random_state=0) gm_joint.fit([conn_group, conn_holdout]) print("Aligned (joint) gradients:", [a.shape for a in gm_joint.aligned_]) # [(200, 5), (200, 5)] # Procrustes alignment: align individual embeddings iteratively gm_proc = GradientMaps(n_components=5, approach='le', alignment='procrustes', random_state=0) gm_proc.fit([conn_group, conn_holdout], n_iter=10) print("Aligned (procrustes) gradients:", [a.shape for a in gm_proc.aligned_]) # [(200, 5), (200, 5)] # Align a single new subject to a pre-computed reference reference = gm_proc.aligned_[0] gm_new = GradientMaps(n_components=5, approach='le', alignment='procrustes', random_state=0) gm_new.fit(conn_group, reference=reference) print("Single-subject aligned gradient:", gm_new.aligned_.shape) # (200, 5) ``` -------------------------------- ### read_surface / write_surface / convert_surface Source: https://context7.com/mica-mni/brainspace/llms.txt Provides unified I/O for cortical surface formats, returning BSPolyData objects that wrap VTK polydata with a Pythonic interface. ```APIDOC ## Surface Mesh I/O ### Description Unified I/O for cortical surface formats, returning `BSPolyData` objects. ### Functions - `read_surface(filepath)`: Reads a surface mesh from a file. - `write_surface(surface, filepath, oformat)`: Writes a surface mesh to a file. - `convert_surface(input_path, output_path, otype)`: Converts a surface mesh from one format to another. ### Parameters - `filepath` (str): Path to the surface file. - `surface` (`BSPolyData`): The surface object to write. - `oformat` (str): The output format for writing (e.g., 'ascii', 'vtp'). - `input_path` (str): Path to the input surface file for conversion. - `output_path` (str): Path for the converted output surface file. - `otype` (str): The output type for conversion (e.g., 'vtk'). ### Usage ```python from brainspace.mesh.mesh_io import read_surface, write_surface, convert_surface # Read surface surf_gii = read_surface('/path/to/lh.pial.gii') # Access mesh data # surf_gii.n_points # surf_gii.n_cells # surf_gii.point_data.keys() # Write surface write_surface(surf_gii, '/path/to/output.vtp') # Convert surface convert_surface('/path/to/lh.pial', '/path/to/lh.gii') ``` ``` -------------------------------- ### Accessing Point Data in BSPolyData Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/vtk_wrap.rst Shows how to access point data arrays, such as normals, from a BSPolyData object using dictionary-like access or a dedicated method. ```python output2.PointData.keys() output2.point_keys output2.PointData['Normals'].shape output2.get_array(name='Normals', at='point').shape output2.get_array(name='Normals') ``` -------------------------------- ### VTK Decorators Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/api_doc/brainspace.vtk_interface.rst Decorators for managing input and output wrapping of VTK objects in functions. ```APIDOC ## Decorators ### Description Decorators to automatically wrap and unwrap VTK objects passed as arguments or returned from functions. ### Decorators - **wrap_input(func)**: Wraps input arguments of a function. - **wrap_output(func)**: Wraps the output of a function. - **unwrap_input(func)**: Unwraps input arguments of a function. - **unwrap_output(func)**: Unwraps the output of a function. - **append_vtk(func)**: Appends VTK functionality to a function. ``` -------------------------------- ### Loading and Visualizing Multi-modal Data Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/auto_examples/plot_tutorial2.ipynb Loads functional connectivity (FC) and microstructural profile covariance (MPC) data, then visualizes features from a seed region. Requires 'load_group_fc', 'load_group_mpc', 'load_parcellation', 'map_to_labels', and 'plot_hemispheres'. ```python from brainspace.datasets import load_group_fc # First load mean connectivity matrix and parcellation fc = load_group_fc('vosdewael', scale=200) mpc = load_group_mpc('vosdewael', scale=200) labeling = load_parcellation('vosdewael', scale=200, join=True) mask = labeling != 0 seeds = [None] * 2 seeds[0] = map_to_labels(fc[0], labeling, mask=mask, fill=np.nan) seeds[1] = map_to_labels(mpc[0], labeling, mask=mask, fill=np.nan) # visualise the features from a seed region (seed 0) plot_hemispheres(surf_lh, surf_rh, array_name=seeds, label_text=['FC', 'MPC'], size=(1200, 400), color_bar=True, cmap='viridis', zoom=1.45) ``` -------------------------------- ### Loading and Visualizing Multimodal Data Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/auto_examples/plot_tutorial2.rst Loads functional connectivity (FC) and microstructural profile covariance (MPC) data, then visualizes features from a seed region. Requires surf_lh, surf_rh, labeling, and mask. ```python from brainspace.datasets import load_group_mpc # First load mean connectivity matrix and parcellation fc = load_group_fc('vosdewael', scale=200) mpc = load_group_mpc('vosdewael', scale=200) labeling = load_parcellation('vosdewael', scale=200, join=True) mask = labeling != 0 seeds = [None] * 2 seeds[0] = map_to_labels(fc[0], labeling, mask=mask, fill=np.nan) seeds[1] = map_to_labels(mpc[0], labeling, mask=mask, fill=np.nan) # visualise the features from a seed region (seed 0) plot_hemispheres(surf_lh, surf_rh, array_name=seeds, label_text=['FC', 'MPC'], size=(1200, 400), color_bar=True, cmap='viridis', zoom=1.45) ``` -------------------------------- ### Load Built-in Datasets Source: https://context7.com/mica-mni/brainspace/llms.txt Loads pre-computed group-averaged connectivity matrices, parcellations, masks, and surface meshes. Supports various scales and cohorts. ```python from brainspace.datasets import ( load_group_fc, load_group_mpc, load_parcellation, load_mask, load_conte69, load_fsa5, load_marker, load_gradient ) # Group-averaged FC matrix — main or holdout cohort fc_main = load_group_fc('schaefer', scale=400, group='main') # (400, 400) fc_holdout = load_group_fc('vosdewael', scale=200, group='holdout') # (200, 200) # Group-averaged MPC matrix (fusion tutorial data) mpc = load_group_mpc('vosdewael', scale=200) # (200, 200) # Parcellation labels — separate hemispheres or joined lab_lh, lab_rh = load_parcellation('schaefer', scale=200) # each: (32492,) lab_all = load_parcellation('schaefer', scale=200, join=True) # (64984,) # Cortical masks (midline exclusion) mask_lh, mask_rh = load_mask('midline') # boolean arrays (32492,) # Conte69 32k pial surfaces and spheres surf_lh, surf_rh = load_conte69() sphere_lh, sphere_rh = load_conte69(as_sphere=True) fsa5_lh, fsa5_rh = load_fsa5() # Pre-computed cortical markers and FC/MPC gradients thick_lh, thick_rh = load_marker('thickness') # cortical thickness t1t2_lh, t1t2_rh = load_marker('t1wt2w') # T1w/T2w myelin proxy fc_grad1_lh, fc_grad1_rh = load_gradient('fc', idx=0) # 1st FC gradient mpc_grad1_lh, _ = load_gradient('mpc', idx=0) # 1st MPC gradient print("FC matrix:", fc_main.shape) print("Conte69 LH vertices:", surf_lh.n_points) ``` -------------------------------- ### read_surface Function Source: https://github.com/mica-mni/brainspace/blob/master/docs/pages/matlab_doc/main_functionality/read_surface.rst Reads surfaces from disk. Accepted formats include gifti, freesurfer, .mat, and .obj files. For .mat files, it expects variables like 'vertices' and 'faces' or 'coord' and 'tri'. ```APIDOC ## read_surface ### Description Reads surfaces from the disk. Accepted formats are gifti files (provided the gifti library is installed), freesurfer files, .mat files and .obj files. When provided with a .mat file, the file must contain variables corresponding to a MATLAB surface i.e. 'vertices' and 'faces' or a SurfStat surface i.e. 'coord and 'tri'. 'vertices' is an n-by-3 list of vertex coordinates, 'faces' is an m-by-3 matrix of triangles, 'coord', is a 3-by-n list of vertex coordinates, and 'tri' is identical to faces in the MATLAB format. ### Usage ```matlab surf_out = read_surface(file); ``` ### Parameters #### Path Parameters - **file** (string) - Description: File to read from. ### Returns #### surf_out - (struct) - Output surface. ``` -------------------------------- ### Load Surfaces Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/api_doc/brainspace.datasets.rst Functions for loading surface data. ```APIDOC ## load_conte69 ### Description Loads the Conte69 surface data. ### Method `load_conte69()` ### Parameters None ### Response Returns the loaded surface data. ``` -------------------------------- ### Load BrainSpace Datasets Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/auto_examples/plot_tutorial3.ipynb Loads surface data, markers (t1wt2w, thickness), and a template functional gradient using brainspace.datasets. Requires `numpy`. ```python import numpy as np from brainspace.datasets import load_gradient, load_marker, load_conte69 # load the conte69 hemisphere surfaces and spheres surf_lh, surf_rh = load_conte69() sphere_lh, sphere_rh = load_conte69(as_sphere=True) # Load the data t1wt2w_lh, t1wt2w_rh = load_marker('t1wt2w') t1wt2w = np.concatenate([t1wt2w_lh, t1wt2w_rh]) thickness_lh, thickness_rh = load_marker('thickness') thickness = np.concatenate([thickness_lh, thickness_rh]) # Template functional gradient embedding = load_gradient('fc', idx=0, join=True) ``` -------------------------------- ### Fit Gradient Maps with Alignment Source: https://github.com/mica-mni/brainspace/blob/master/docs/python_doc/auto_examples/plot_tutorial2.ipynb Fits GradientMaps using Procrustes and joint alignment techniques on two different functional connectivity datasets. Requires BrainSpace. ```python conn_matrix2 = load_group_fc('schaefer', scale=400, group='holdout') gp = GradientMaps(kernel='normalized_angle', alignment='procrustes') gj = GradientMaps(kernel='normalized_angle', alignment='joint') gp.fit([conn_matrix, conn_matrix2]) gj.fit([conn_matrix, conn_matrix2]) ``` -------------------------------- ### Read/Write Surface Meshes Source: https://context7.com/mica-mni/brainspace/llms.txt Unified I/O for cortical surface formats (GIFTI, FreeSurfer, VTK). Returns BSPolyData objects with Pythonic interface. Supports format conversion. ```python from brainspace.mesh.mesh_io import read_surface, write_surface, convert_surface # Read various formats (auto-detects type from extension) surf_gii = read_surface('/path/to/lh.pial.gii') # GIFTI surf_fs = read_surface('/path/to/lh.pial') # FreeSurfer binary surf_gz = read_surface('/path/to/lh.white.gii.gz') # gzip-compressed surf_vtk = read_surface('/path/to/surface.vtk') # VTK legacy # Access mesh data print("Number of points:", surf_gii.n_points) print("Number of cells: ", surf_gii.n_cells) print("Point data arrays:", surf_gii.point_data.keys()) # Write to a different format write_surface(surf_gii, '/path/to/output.vtp') # VTK XML write_surface(surf_gii, '/path/to/output.asc', oformat='ascii') # FreeSurfer ASCII # One-step format conversion convert_surface('/path/to/lh.pial', '/path/to/lh.gii') convert_surface('/path/to/lh.pial.gii', '/path/to/lh.vtk', otype='vtk') ```