
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "auto_examples/plot_group_alignment.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_auto_examples_plot_group_alignment.py>`
        to download the full example code.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_auto_examples_plot_group_alignment.py:


Template-based prediction.
==========================

In this tutorial, we show how to improve inter-subject similarity using a template
computed across multiple source subjects. For this purpose, we leverage GroupAlignment
to create a template, using Procrustes alignment. Leveraging the learned template,
we align the target subject using shared information.
We then compare the voxelwise similarity between the
target subject and the template to the similarity between the target subject and
the anatomical Euclidean average of the source subjects.

We mostly rely on Python common packages and on nilearn to handle
functional data in a clean fashion.


To run this example, you must launch IPython via ``ipython
--matplotlib`` in a terminal, or use ``jupyter-notebook``.

.. GENERATED FROM PYTHON SOURCE LINES 23-33

Retrieve the data
-----------------
In this example we use the IBC dataset, which includes a large number of
different contrasts maps for 12 subjects.
We download the images for subjects sub-01, sub-02, sub-04, sub-05, sub-06
and sub-07 (or retrieve them if they were already downloaded).
imgs is the list of paths to available statistical images for each subjects.
df is a dataframe with metadata about each of them.
mask is a binary image used to extract grey matter regions.


.. GENERATED FROM PYTHON SOURCE LINES 33-39

.. code-block:: Python


    from fmralign.fetch_example_data import fetch_ibc_subjects_contrasts

    subjects = ["sub-01", "sub-02", "sub-04", "sub-05", "sub-06", "sub-07"]
    imgs, df, mask_img = fetch_ibc_subjects_contrasts(subjects)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    [get_dataset_dir] Dataset found in /Users/emdupre/nilearn_data/ibc




.. GENERATED FROM PYTHON SOURCE LINES 40-46

Define a masker
-----------------
We define a nilearn masker that will be used to handle relevant data.
For more information, consult Nilearn's documentation on
:external+nilearn:ref:`masker objects <masker_objects>`.


.. GENERATED FROM PYTHON SOURCE LINES 46-51

.. code-block:: Python


    from nilearn.maskers import NiftiMasker

    masker = NiftiMasker(mask_img=mask_img).fit()








.. GENERATED FROM PYTHON SOURCE LINES 52-58

Prepare the data
----------------
For each subject, we will use two series of contrasts acquired during
two independent sessions with a different phase encoding:
Antero-posterior(AP) or Postero-anterior(PA).


.. GENERATED FROM PYTHON SOURCE LINES 58-74

.. code-block:: Python



    # To infer a template for subjects sub-01 to sub-06 for both AP and PA data,
    # we make a list of 4D niimgs from our list of list of files containing 3D images

    from nilearn.image import concat_imgs

    template_train = []
    for i in range(5):
        template_train.append(concat_imgs(imgs[i]))

    # sub-07 (that is 5th in the list) will be our left-out subject.
    # We make a single 4D Niimg from our list of 3D filenames.

    left_out_subject = concat_imgs(imgs[5])








.. GENERATED FROM PYTHON SOURCE LINES 75-79

Compute a baseline (average of subjects)
----------------------------------------
We create an image with as many contrasts as any subject representing for
each contrast the average of all train subjects maps.

.. GENERATED FROM PYTHON SOURCE LINES 79-85

.. code-block:: Python


    import numpy as np

    masked_imgs = [masker.transform(img) for img in template_train]
    euclidean_avg = np.mean(masked_imgs, axis=0)








.. GENERATED FROM PYTHON SOURCE LINES 86-96

Create a template from the training subjects.
---------------------------------------------
We define an estimator using :class:`~fmralign.alignment.group_alignment.GroupAlignment`:
  * We align the whole brain through multiple local alignments.
  * These alignments are calculated on a parcellation of the brain in 150 pieces,
    this parcellation creates group of functionally similar voxels.
  * The template is created iteratively, aligning all subjects data into a
    common space, from which the template is inferred and aligning again to this
    new template space.


.. GENERATED FROM PYTHON SOURCE LINES 96-111

.. code-block:: Python


    from fmralign import GroupAlignment
    from fmralign.embeddings.parcellation import get_labels

    # Use only the first image to speed up the computation of the labels
    labels = get_labels(imgs[0], n_pieces=150, masker=masker)

    # We create a dictionary with the subject names as keys and the subjects data as values
    dict_alignment = dict(zip(subjects, masked_imgs))

    # We use Procrustes/scaled orthogonal alignment method
    template_estim = GroupAlignment(method="procrustes", labels=labels)
    template_estim.fit(X=dict_alignment, y="template")
    procrustes_template = template_estim.template





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    /Users/emdupre/Desktop/fmralign/fmralign/embeddings/parcellation.py:82: UserWarning: Overriding provided-default estimator parameters with provided masker parameters :
    Parameter mask_strategy :
        Masker parameter background - overriding estimator parameter epi
    Parameter smoothing_fwhm :
        Masker parameter None - overriding estimator parameter 4.0

      parcellation.fit(images_to_parcel)
    [Parcellations.fit] Resampling mask
    /opt/miniconda3/envs/fmralign/lib/python3.12/site-packages/sklearn/cluster/_agglomerative.py:325: UserWarning: the number of connected components of the connectivity matrix is 35 > 1. Completing it to avoid stopping the tree early.
      connectivity, n_connected_components = _fix_connectivity(
    /Users/emdupre/Desktop/fmralign/fmralign/alignment/utils.py:208: UserWarning: 
     Some parcels are more than 1000 voxels wide it can slow down alignment,especially optimal_transport :
     parcel 11 : 1026 voxels
     parcel 37 : 1370 voxels
     parcel 42 : 2251 voxels
      warnings.warn(warning)




.. GENERATED FROM PYTHON SOURCE LINES 112-117

Predict new data for left-out subject
-------------------------------------
We predict the contrasts of the left-out subject using the template we just
created. This method takes the left-out subject as input, computes a pairwise
alignment with the template and returns the aligned data.

.. GENERATED FROM PYTHON SOURCE LINES 117-127

.. code-block:: Python


    from fmralign import PairwiseAlignment

    left_out_data = masker.transform(left_out_subject)
    pairwise_estim = PairwiseAlignment(method="procrustes", labels=labels).fit(
        left_out_data, procrustes_template
    )

    predictions_from_template = pairwise_estim.transform(left_out_data)








.. GENERATED FROM PYTHON SOURCE LINES 128-134

Score the baseline and the prediction
-------------------------------------
We use a utility scoring function to measure the voxelwise correlation
between the images. That is, for each voxel, we measure the correlation between
its profile of activation without and with alignment, to see if template-based
alignment was able to improve inter-subject similarity.

.. GENERATED FROM PYTHON SOURCE LINES 134-142

.. code-block:: Python


    from fmralign.metrics import score_voxelwise

    average_score = score_voxelwise(left_out_data, euclidean_avg, loss="corr")
    template_score = score_voxelwise(
        predictions_from_template, procrustes_template, loss="corr"
    )








.. GENERATED FROM PYTHON SOURCE LINES 143-147

Plotting the measures
---------------------
Finally we plot both scores


.. GENERATED FROM PYTHON SOURCE LINES 147-161

.. code-block:: Python


    from nilearn import plotting

    average_score_img = masker.inverse_transform(average_score)
    template_score_img = masker.inverse_transform(template_score)
    baseline_display = plotting.plot_stat_map(
        average_score_img, display_mode="z", vmax=1, cut_coords=[-15, -5]
    )
    baseline_display.title("Left-out subject correlation with group average")
    display = plotting.plot_stat_map(
        template_score_img, display_mode="z", cut_coords=[-15, -5], vmax=1
    )
    display.title("Aligned subject correlation with Procrustes template")




.. rst-class:: sphx-glr-horizontal


    *

      .. image-sg:: /auto_examples/images/sphx_glr_plot_group_alignment_001.png
         :alt: plot group alignment
         :srcset: /auto_examples/images/sphx_glr_plot_group_alignment_001.png
         :class: sphx-glr-multi-img

    *

      .. image-sg:: /auto_examples/images/sphx_glr_plot_group_alignment_002.png
         :alt: plot group alignment
         :srcset: /auto_examples/images/sphx_glr_plot_group_alignment_002.png
         :class: sphx-glr-multi-img





.. GENERATED FROM PYTHON SOURCE LINES 162-164

We observe that creating a template and aligning a new subject to it yields
better inter-subject similarity than regular euclidean averaging.


.. rst-class:: sphx-glr-timing

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


.. _sphx_glr_download_auto_examples_plot_group_alignment.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: plot_group_alignment.ipynb <plot_group_alignment.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: plot_group_alignment.py <plot_group_alignment.py>`

    .. container:: sphx-glr-download sphx-glr-download-zip

      :download:`Download zipped: plot_group_alignment.zip <plot_group_alignment.zip>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
