Computing a connectome with sparse inverse covariance¶

This example constructs a functional connectome using the sparse inverse covariance.

Note that the inverse covariance (or precision) contains values that can be linked to negated partial correlations, so we negated it for display.

dataset

This example uses the MSDL atlas to extract time series from the development fMRI dataset with the NiftiMapsMasker.

As the MSDL atlas comes with (x, y, z) MNI coordinates for the different regions, we can visualize the matrix as a graph of interaction in a brain. To avoid having too dense a graph, we represent only the 20% edges with the highest values.

Retrieve the atlas and the data¶

from nilearn.datasets import fetch_atlas_msdl, fetch_development_fmri

atlas = fetch_atlas_msdl()
[fetch_atlas_msdl] Dataset directory found: /home/runner/work/nilearn/nilearn/nilearn_data/msdl_atlas
print(atlas.description.content)

# Loading atlas image and labels
atlas_filename = atlas.maps
labels = atlas.labels
{'labels': {'type': list[str], 'desc': 'List of the names of the regions. There are 39 labels such that ``data.labels[i]`` corresponds to map ``i``.'}, 'maps': {'type': <class 'str'>, 'desc': 'Full path to nifti file containing the :term:`Probabilistic atlas` image (shape is equal to ``(40, 48, 35, 39)``).'}, 'networks': {'type': list[str], 'desc': 'List containing the names of the networks. There are 39 network names such that ``data.networks[i]`` is the network name of region ``i``.'}, 'region_coords': {'type': list[list[float]], 'desc': 'Length-3 :obj:`tuple` ``data.region_coords[i]`` contains the coordinates ``(x, y, z)`` of region ``i`` in :term:`MNI` space.'}, 'atlas_type': {'type': <class 'str'>, 'desc': '\n        Type of atlas.\n        See :term:`Probabilistic atlas` and :term:`Deterministic atlas`.'}, 'template': {'type': <class 'str'>, 'desc': 'The standardized space of analysis in which the data is provided.'}}

Loading the functional datasets

data = fetch_development_fmri(n_subjects=1)
[fetch_development_fmri] Dataset directory found: /home/runner/work/nilearn/nilearn/nilearn_data/development_fmri

print basic information on the dataset

print(f"First subject functional nifti images (4D) are at: {data.func[0]}")
First subject functional nifti images (4D) are at: /home/runner/work/nilearn/nilearn/nilearn_data/development_fmri/sub-pixar123_task-pixar_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz

Extract time series¶

from nilearn.maskers import NiftiMapsMasker

masker = NiftiMapsMasker(
    maps_img=atlas_filename,
    standardize_confounds=True,
    standardize="zscore_sample",
    memory="nilearn_cache",
    memory_level=1,
    verbose=1,
)

time_series = masker.fit_transform(data.func[0], confounds=data.confounds)
[NiftiMapsMasker.wrapped] Loading data from sub-pixar123_task-...
[NiftiMapsMasker.wrapped] Loading regions from .../msdl_rois.nii
[NiftiMapsMasker.wrapped] Resampling regions
[NiftiMapsMasker.wrapped] Finished fit
________________________________________________________________________________
[Memory] Calling nilearn.maskers.base_masker.filter_and_extract...
filter_and_extract('/home/runner/work/nilearn/nilearn/nilearn_data/development_fmri/sub-pixar123_task-pixar_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz',
<nilearn.maskers.nifti_maps_masker._ExtractionFunctor object at 0x72034607efd0>, { 'allow_overlap': True,
  'clean_args': None,
  'clean_kwargs': {},
  'cmap': 'CMRmap_r',
  'detrend': False,
  'dtype': None,
  'high_pass': None,
  'high_variance_confounds': False,
  'low_pass': None,
  'maps_img': '/home/runner/work/nilearn/nilearn/nilearn_data/msdl_atlas/MSDL_rois/msdl_rois.nii',
  'mask_img': None,
  'reports': True,
  'smoothing_fwhm': None,
  'standardize': 'zscore_sample',
  'standardize_confounds': True,
  't_r': None,
  'target_affine': None,
  'target_shape': None}, confounds=[ '/home/runner/work/nilearn/nilearn/nilearn_data/development_fmri/sub-pixar123_task-pixar_desc-reducedConfounds_regressors.tsv'], sample_mask=None, memory=Memory(location=nilearn_cache/joblib), memory_level=1, verbose=1, sklearn_output_config=None)
[NiftiMapsMasker.wrapped] Loading data from sub-pixar123_task-...
[NiftiMapsMasker.wrapped] Extracting region signals
[NiftiMapsMasker.wrapped] Cleaning extracted signals
_______________________________________________filter_and_extract - 0.9s, 0.0min

Compute the sparse inverse covariance¶

from sklearn.covariance import GraphicalLassoCV

estimator = GraphicalLassoCV(verbose=True)
estimator.fit(time_series)
[Parallel(n_jobs=1)]: Done   5 out of   5 | elapsed:    0.7s finished
[GraphicalLassoCV] Done refinement  1 out of 4:   0s
[Parallel(n_jobs=1)]: Done   5 out of   5 | elapsed:    0.9s finished
[GraphicalLassoCV] Done refinement  2 out of 4:   1s
[Parallel(n_jobs=1)]: Done   5 out of   5 | elapsed:    0.9s finished
[GraphicalLassoCV] Done refinement  3 out of 4:   2s
[Parallel(n_jobs=1)]: Done   5 out of   5 | elapsed:    0.8s finished
[GraphicalLassoCV] Done refinement  4 out of 4:   3s
GraphicalLassoCV(verbose=True)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.


Visualization: covariance¶

The covariance can be found at estimator.covariance_. We plot it along with its connectome graph.

from nilearn.plotting import (
    plot_connectome,
    plot_matrix,
    show,
    view_connectome,
)

plot_matrix(
    estimator.covariance_,
    labels=labels,
    figure=(9, 7),
    vmax=1,
    vmin=-1,
    title="Covariance",
)

coords = atlas.region_coords

plot_connectome(
    estimator.covariance_, coords, title="Covariance", edge_threshold="80%"
)

show()
  • Covariance
  • plot inverse covariance connectome

Visualization: sparse inverse covariance¶

We negate the precision to get partial correlations.

plot_matrix(
    -estimator.precision_,
    labels=labels,
    figure=(9, 7),
    vmax=1,
    vmin=-1,
    title="Sparse inverse covariance",
)

plot_connectome(
    -estimator.precision_,
    coords,
    title="Sparse inverse covariance",
    edge_threshold="80%",
)

show()
  • Sparse inverse covariance
  • plot inverse covariance connectome

3D visualization in a web browser¶

An alternative to plot_connectome is to use view_connectome that gives more interactive visualizations in a web browser. See 3D Plots of connectomes for more details.

view = view_connectome(-estimator.precision_, coords, edge_threshold="80%")

# In a notebook, if ``view`` is the output of a cell, it will
# be displayed below the cell
view


# uncomment this to open the plot in a web browser:
# view.open_in_browser()

Total running time of the script: (0 minutes 12.378 seconds)

Estimated memory usage: 1004 MB

Gallery generated by Sphinx-Gallery