BrainStat : A toolbox for statistical analysis of neuroimaging data¶
Welcome to BrainStat’s documentation!
BrainStat is a toolbox for the statistical analysis and context decoding of neuroimaging data. It implements both univariate and multivariate linear models and interfaces with the Allen Human Brain Atlas and Nimare databases. BrainStat flexibly handles common surface, volume, and parcel level data formats, and provides a series of interactive visualization functions. The toolbox has been implemented in both python and matlab, the two most widely adopted programming languages in the neuroimaging and neuroinformatics communities. It is openly available, and documented here.

Developers¶
Reinder Vos de Wael - MICA Lab, Montreal Neurological Institute
Şeyma Bayrak - Max Planck Institute for Human Cognitive and Brain Sciences
Oualid Benkarim - MICA Lab, Montreal Neurological Institute
Sara Lariviere - MICA Lab, Montreal Neurological Institute
Raul Cruces - MICA Lab, Montreal Neurological Institute
Peer Herholz - Montreal Neurological Institute
Seok-Jun Hong - Sungkyunkwan University
Sofie Valk - Max Planck Institute for Human Cognitive and Brain Sciences
Boris Bernhardt - Montreal Neurological Institute
License¶
The BrainStat source code is available under the BSD (3-Clause) license.
Support¶
If you have problems installing the software or questions about usage and documentation, or something else related to BrainStat, you can post to the Issues section of our repository.
Installation Guide¶
BrainStat is available in Python and MATLAB.
Python installation¶
BrainStat is compatible with Python 3.6-3.8. Compatibility with 3.9 is in the works.
BrainStat can be installed using pip
(NOTE: This doesn’t work yet!):
pip install brainstat
Alternatively, you can install the package from Github as follows:
git clone https://github.com/MICA-LAB/BrainStat.git
cd BrainStat
python setup.py install
MATLAB installation¶
This toolbox has been tested with MATLAB versions R2019b and newer.
To install the MATLAB toolbox simply download and unzip the GitHub toolbox and run the following in MATLAB:
addpath(genpath('/path/to/BrainSpace/matlab/'))
If you want to load BrainStat every time you start MATLAB, type edit
startup
and append the above line to the end of this file.
If you wish to open gifti files you will also need to install the gifti library.
Python Index¶
Tutorials¶
Note
Click here to download the full example code
Tutorial 01: Linear Models¶
In this tutorial you will set up your first linear model with BrainStat. First lets load some example data to play around with. We’ll load age, IQ, and left hemispheric cortical thickness for a few subjects.
import numpy as np
import nibabel as nib
import os
import brainstat
from brainstat.tutorial.utils import fetch_tutorial_data
from brainstat.context.utils import read_surface_gz
from nilearn.datasets import fetch_surf_fsaverage
brainstat_dir = os.path.dirname(brainstat.__file__)
data_dir = os.path.join(brainstat_dir, "tutorial")
n = 20
tutorial_data = fetch_tutorial_data(n_subjects=n, data_dir=data_dir)
age = tutorial_data["demographics"]["AGE"].to_numpy()
iq = tutorial_data["demographics"]["IQ"].to_numpy()
# Reshape the thickness files such that left and right hemispheres are in the same row.
files = np.reshape(np.array(tutorial_data["image_files"]), (-1, 2))
# We'll use only the left hemisphere in this tutorial.
thickness = np.zeros((n, 10242))
for i in range(n):
thickness[i, :] = np.squeeze(nib.load(files[i, 0]).get_fdata())
mask = np.all(thickness != 0, axis=0)
pial_left = read_surface_gz(fetch_surf_fsaverage()["pial_left"])
Dataset created in /home/docs/checkouts/readthedocs.org/user_builds/brainstat/checkouts/latest/brainstat/tutorial/brainstat_tutorial
Downloading data from https://box.bic.mni.mcgill.ca/s/wMPF2vj7EoYWELV/download ...
...done. (1 seconds, 0 min)
Downloading data from https://box.bic.mni.mcgill.ca/s/wMPF2vj7EoYWELV/download ...
Downloaded 2015232 of 19209132 bytes (10.5%, 8.7s remaining)
Downloaded 13959168 of 19209132 bytes (72.7%, 0.8s remaining) ...done. (3 seconds, 0 min)
Extracting data from /home/docs/checkouts/readthedocs.org/user_builds/brainstat/checkouts/latest/brainstat/tutorial/brainstat_tutorial/3c1b224c1c95382411fd038ef5a44916/brainstat_tutorial.zip..... done.
Next, we can create a BrainStat linear model by declaring these variables as terms. The term class requires two things: 1) an array or scalar, and 2) a variable name for each column. Lastly, we can create the model by simply adding the terms together.
from brainstat.stats.terms import Term
term_intercept = Term(1, names="intercept")
term_age = Term(age, "age")
term_iq = Term(iq, "iq")
model = term_intercept + term_age + term_iq
We can also add interaction effects to the model by multiplying terms.
model_interaction = term_intercept + term_age + term_iq + term_age * term_iq
Now, lets imagine we have some cortical marker (e.g. cortical thickness) for each subject and we want to evaluate whether this marker changes with age whilst correcting for effects of sex and age-sex interactions.
from brainstat.stats.SLM import SLM
slm = SLM(model_interaction, -age, surf=pial_left, correction="rft", mask=mask)
slm.fit(thickness)
print(slm.t.shape) # These are the t-values of the model.
print(slm.P["pval"]["P"]) # These are the random field theory derived p-values.
(1, 10242)
[1. 1. 1. ... 1. 1. 1.]
By default BrainStat uses a two-tailed test. If you want to get a one-tailed test, simply specify it in the SLM model as follows:
slm_two_tails = SLM(
model_interaction, -age, surf=pial_left, correction="rft", two_tailed=False
)
slm_two_tails.fit(thickness)
/home/docs/checkouts/readthedocs.org/user_builds/brainstat/checkouts/latest/brainstat/stats/_linear_model.py:423: RuntimeWarning: invalid value encountered in divide
u = Y[i, :, j] / normr
Now, imagine that instead of using a fixed effects model, you would prefer a mixed effects model wherein handedness is a random variable. This is simple to set up. All you need to do is initialize the handedness term with the Random class instead, all other code remains identical.
from brainstat.stats.terms import Random
random_handedness = Random(tutorial_data["demographics"]["HAND"], name_ran="Handedness")
random_identity = Random(1, name_ran="identity")
model_random = (
term_intercept
+ term_age
+ term_iq
+ term_age * term_iq
+ random_handedness
+ random_identity
)
slm_random = SLM(model_random, -age, surf=pial_left, correction="fdr", mask=mask)
slm_random.fit(thickness)
That concludes the basic usage of the BrainStat for statistical models.
Total running time of the script: ( 0 minutes 8.400 seconds)
Neuroimaging statistics toolbox. |
MATLAB Index¶
volume_viewer¶
Synopsis¶
Plots data in a volume (source code).
Usage¶
obj = volume_viewer(structural,overlay,varargin);
structural: volume of a structural image.
overlay: (Optional argument) an overlay to plot over the image volume, must have identical dimensions.
varargin: Name-Value Pairs (see below).
obj: an object used for the manipulation of the volume viewer.
Description¶
BrainStat’s volume viewer allows for the viewing of statistcal maps in volume space. The volume viewer allows for scrolling and clicking through the volume. Note that slice orientation is currently hardcoded and cannot be modified.
Name-Value Pairs¶
remove_zero: Does not display zeros in the overlay (default: true).
threshold_lower: Does not display values of the overlay below the minimum of the colorbar (default: false).
threshold_upper: Does not display values of the overlay above the maximum of the colorbar (default: false).
Object Properties¶
slices: Contains the curently displayed slices.
threshold_lower: See name-value pair with identical name.
threshold_upper: See name-value pair with identical name.
remove_zero: See name-value pair with identical name.
image: Contains the input image (not modifiable).
overlay: Contains the input overlay (not modifiable).
handles Contains handles to the graphics objects (not modifiable).
Object Methods¶
obj.colorlimits(limits,image): Sets the color limits of the structural (image=”image”) or overlay (image=”overlay”) to limits.
obj.colormap(cmap,image): Sets the color map of the structural (image=”image”) or overlay (image=”overlay”) to cmap.
Funding¶
Our research is kindly supported by:
Canadian Institutes of Health Research (CIHR)
National Science and Engineering Research Council of Canada (NSERC)
Azrieli Center for Autism Research
The Montreal Neurological Institute]
Canada Research Chairs Program
BrainCanada
SickKids Foundation
Helmholtz Foundation
We also like to thank these funders for training/salary support
Savoy Foundation for Epilepsy (to RvdW)
Healthy Brain and Healthy Lives (to OB)
Fonds de la Recherche du Quebec - Sante (to BB)
Credits¶
Some references that are incorporated into BrainStat
SurfStat references¶
Worsley KJ et al. (2009) A Matlab toolbox for the statistical analysis of univariate and multivariate surface and volumetric data using linear mixed effects models and random field theory. NeuroImage, Volume 47, Supplement 1, July 2009, Pages S39-S41. https://doi.org/10.1016/S1053-8119(09)70882-1
Chung MK et al. (2010) General Multivariate Linear Modeling of Surface Shapes Using SurfStat Neuroimage. 53(2):491-505. doi: 10.1016/j.neuroimage.2010.06.032
Random field theory references¶
Adler RJ and Taylor JE (2007). Random fields and geometry. Springer. Hagler DJ Saygin AP and Sereno MI (2006). Smoothing and cluster thresholding for cortical surface-based group analysis of fMRI data. NeuroImage, 33:1093-1103.
Hayasaka S, Phan KL, Liberzon I, Worsley KJ and Nichols TE (2004). Non-Stationary cluster size inference with random field and permutation methods. NeuroImage, 22:676-687.
Taylor JE and Adler RJ (2003), Euler characteristics for Gaussian fields on manifolds. Annals of Probability, 31:533-563.
Taylor JE and Worsley KJ (2007). Detecting sparse signal in random fields, with an application to brain mapping. Journal of the American Statistical Association, 102:913-928.
Worsley KJ, Andermann M, Koulis T, MacDonald D, and Evans AC (1999). Detecting changes in non-isotropic images. Human Brain Mapping, 8:98-101.