
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "auto_examples/plot_alignment_methods_benchmark.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_alignment_methods_benchmark.py>`
        to download the full example code.

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

.. _sphx_glr_auto_examples_plot_alignment_methods_benchmark.py:


Alignment methods benchmark (template-based ROI case)
=====================================================
In this tutorial, we compare various methods of alignment on a group-based alignment
problem for Individual Brain Charting subjects. For each subject, we have a lot
of functional information in the form of several task-based
contrast per subject. We will just work here on a ROI.

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 19-35

Retrieve the data
------------------
In this example we use the IBC dataset, which include a large number of
different contrasts maps for 12 subjects.

The contrasts come from tasks in the Archi and HCP fMRI batteries, designed
to probe a range of cognitive functions, including:

* Motor control: finger, foot, and tongue movements
* Social cognition: interpreting short films and stories
* Spatial orientation: judging orientation and hand-side
* Numerical reasoning: reading and listening to math problems
* Emotion processing: judging facial expressions
* Reward processing: responding to gains and losses
* Working memory: maintaining sequences of faces and objects
* Object categorization: matching and comparing visual stimuli

.. GENERATED FROM PYTHON SOURCE LINES 35-46

.. code-block:: Python


    # We download the images for subjects sub-01 and sub-02.
    # ``files`` is the list of paths for each subjects.
    # ``df`` is a dataframe with metadata about each of them.
    # ``mask`` is the common mask for IBC subjects.

    from fmralign.fetch_example_data import fetch_ibc_subjects_contrasts

    sub_ids = ["sub-01", "sub-02", "sub-04"]
    files, df, mask = fetch_ibc_subjects_contrasts(sub_ids)





.. 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 47-50

Extract a mask for the visual cortex from Yeo Atlas
---------------------------------------------------
First, we fetch and plot the complete atlas

.. GENERATED FROM PYTHON SOURCE LINES 50-73

.. code-block:: Python


    from nilearn import datasets, plotting
    from nilearn.image import concat_imgs, load_img, new_img_like, resample_to_img

    atlas_yeo_2011 = datasets.fetch_atlas_yeo_2011()
    atlas = load_img(atlas_yeo_2011.thick_7)

    # Select visual cortex, create a mask and resample it to the right resolution

    mask_visual = new_img_like(atlas, atlas.get_fdata() == 1)
    resampled_mask_visual = resample_to_img(
        mask_visual, mask, interpolation="nearest"
    )

    # Plot the mask we will use
    plotting.plot_roi(
        resampled_mask_visual,
        title="Visual regions mask extracted from atlas",
        cut_coords=(8, -80, 9),
        colorbar=False,
        cmap="Paired",
    )




.. image-sg:: /auto_examples/images/sphx_glr_plot_alignment_methods_benchmark_001.png
   :alt: plot alignment methods benchmark
   :srcset: /auto_examples/images/sphx_glr_plot_alignment_methods_benchmark_001.png
   :class: sphx-glr-single-img


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

 .. code-block:: none

    /Users/emdupre/Desktop/fmralign/examples/plot_alignment_methods_benchmark.py:54: DeprecationWarning: From release >=0.13.0, instead of returning several atlas image accessible via different keys, this fetcher will return the atlas as a dictionary with a single atlas image, accessible through a 'maps' key. To suppress this warning, Please use the parameters 'n_networks' and 'thickness' to specify the exact atlas image you want.
      atlas_yeo_2011 = datasets.fetch_atlas_yeo_2011()
    [fetch_atlas_yeo_2011] Dataset found in /Users/emdupre/nilearn_data/yeo_2011
    /Users/emdupre/Desktop/fmralign/examples/plot_alignment_methods_benchmark.py:60: FutureWarning: 'force_resample' will be set to 'True' by default in Nilearn 0.13.0.
    Use 'force_resample=True' to suppress this warning.
      resampled_mask_visual = resample_to_img(
    /Users/emdupre/Desktop/fmralign/examples/plot_alignment_methods_benchmark.py:60: FutureWarning: From release 0.13.0 onwards, this function will, by default, copy the header of the input image to the output. Currently, the header is reset to the default Nifti1Header. To suppress this warning and use the new behavior, set `copy_header=True`.
      resampled_mask_visual = resample_to_img(

    <nilearn.plotting.displays._slicers.OrthoSlicer object at 0x321635ee0>



.. GENERATED FROM PYTHON SOURCE LINES 74-80

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 80-85

.. code-block:: Python


    from nilearn.maskers import NiftiMasker

    roi_masker = NiftiMasker(mask_img=resampled_mask_visual).fit()








.. GENERATED FROM PYTHON SOURCE LINES 86-94

Prepare the data
----------------
For each subject, for each task and conditions, our dataset contains two
independent acquisitions, similar except for one acquisition parameter, the
encoding phase used that was either Antero-Posterior (AP) or
Postero-Anterior (PA). Although this induces small differences
in the final data, we will take  advantage of these pseudo-duplicates
to define training and test samples.

.. GENERATED FROM PYTHON SOURCE LINES 94-122

.. code-block:: Python


    # The training set:
    # * source_train: AP acquisitions from source subjects (sub-01, sub-02).
    # * target_train: AP acquisitions from the target subject (sub-04).
    #

    source_subjects = [sub for sub in sub_ids if sub != "sub-04"]
    source_train_imgs = [
        concat_imgs(df[(df.subject == sub) & (df.acquisition == "ap")].path.values)
        for sub in source_subjects
    ]
    target_train_img = concat_imgs(
        df[(df.subject == "sub-04") & (df.acquisition == "ap")].path.values
    )

    # The testing set:
    # * source_test: PA acquisitions from source subjects (sub-01, sub-02).
    # * target test: PA acquisitions from the target subject (sub-04).
    #

    source_test_imgs = [
        concat_imgs(df[(df.subject == sub) & (df.acquisition == "pa")].path.values)
        for sub in source_subjects
    ]
    target_test_img = concat_imgs(
        df[(df.subject == "sub-04") & (df.acquisition == "pa")].path.values
    )








.. GENERATED FROM PYTHON SOURCE LINES 123-129

Choose the number of regions for local alignment
------------------------------------------------
First, as we will proceed to local alignment we choose a suitable number of
regions so that each of them is approximately 100 voxels wide. Then our
estimator will first make a functional clustering of voxels based on train
data to divide them into meaningful regions.

.. GENERATED FROM PYTHON SOURCE LINES 129-137

.. code-block:: Python


    import numpy as np

    n_voxels = roi_masker.mask_img_.get_fdata().sum()
    print(f"The chosen region of interest contains {n_voxels} voxels")
    n_pieces = int(np.round(n_voxels / 100))
    print(f"We will cluster them in {n_pieces} regions")





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

 .. code-block:: none

    The chosen region of interest contains 6631.0 voxels
    We will cluster them in 66 regions




.. GENERATED FROM PYTHON SOURCE LINES 138-144

Extract the parcels labels
--------------------------
We will use intra-parcel alignments, fmralign provides a simple utility
to extract the labels of associated to each voxel:
:func:`~fmralign.embeddings.parcellation.get_labels`.
We then organize the data in dictionaries of pairs of subjects names and data.

.. GENERATED FROM PYTHON SOURCE LINES 144-163

.. code-block:: Python


    from fmralign.embeddings.parcellation import get_labels

    labels = get_labels(source_train_imgs, roi_masker, n_pieces)
    dict_source_train = dict(
        zip(
            source_subjects,
            [roi_masker.transform(img) for img in source_train_imgs],
        )
    )
    dict_source_test = dict(
        zip(
            source_subjects,
            [roi_masker.transform(img) for img in source_test_imgs],
        )
    )
    target_train = roi_masker.transform(target_train_img)
    target_test = roi_masker.transform(target_test_img)





.. 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 11 > 1. Completing it to avoid stopping the tree early.
      connectivity, n_connected_components = _fix_connectivity(




.. GENERATED FROM PYTHON SOURCE LINES 164-180

Define the estimators, fit them and do a prediction
---------------------------------------------------
On each region, we search for a transformation :math:`R` that is either:

  *  orthogonal, using :class:`~fmralign.methods.Procrustes`
     s.t. :math:`||sc RX - Y ||^2` is minimized, where :math:`sc` is a scaling factor
  *  the :class:`~fmralign.methods.OptimalTransport` plan,
     which yields the minimal transport cost while respecting the mass conservation constraints.
     Calculated with entropic regularization.
  *  the deterministic shared response model (:class:`~fmralign.methods.DetSRM`),
     which computes a shared response space from different subjects,
     and then projects individual subject data into it.

Then for each method we define the estimator, fit it, predict the new image and plot
its correlation with the real signal. We use the identity (euclidean averaging)
as the baseline.

.. GENERATED FROM PYTHON SOURCE LINES 180-208

.. code-block:: Python


    from fmralign import GroupAlignment
    from fmralign.metrics import score_voxelwise

    methods = ["identity", "procrustes", "ot", "SRM"]

    # Prepare to store the results
    titles, aligned_scores = [], []

    for i, method in enumerate(methods):
        # Fit the group estimator on the training data
        group_estimator = GroupAlignment(method=method, labels=labels).fit(
            dict_source_train
        )
        # Compute a mapping between the template and the new subject
        # using `target_train` and make a prediction using the left-out-data
        target_pred = group_estimator.predict_subject(
            dict_source_test, target_train
        )

        # Derive correlation between prediction, test
        method_error = score_voxelwise(target_test, target_pred, loss="corr")

        # Store the results for plotting later
        aligned_score_img = roi_masker.inverse_transform(method_error)
        titles.append(f"Correlation of prediction after {method} alignment")
        aligned_scores.append(aligned_score_img)





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

 .. code-block:: none

    /Users/emdupre/Desktop/fmralign/fmralign/metrics.py:55: ConstantInputWarning: An input array is constant; the correlation coefficient is not defined.
      pearsonr(X_gt[:, vox], X_pred[:, vox])[
    /opt/miniconda3/envs/fmralign/lib/python3.12/site-packages/ot/bregman/_sinkhorn.py:1331: UserWarning: Sinkhorn did not converge. You might want to increase the number of iterations `numItermax` or the regularization parameter `reg`.
      warnings.warn(




.. GENERATED FROM PYTHON SOURCE LINES 209-211

Plot the results
----------------

.. GENERATED FROM PYTHON SOURCE LINES 211-228

.. code-block:: Python

    import matplotlib.pyplot as plt

    fig, axes = plt.subplots(4, 1, figsize=(8, 12))

    for i, (score, title) in enumerate(zip(aligned_scores, titles)):
        plotting.plot_stat_map(
            score,
            display_mode="z",
            cut_coords=[-15, -5],
            vmax=1,
            title=title,
            axes=axes[i],
            colorbar=True,
        )

    plt.show()




.. image-sg:: /auto_examples/images/sphx_glr_plot_alignment_methods_benchmark_002.png
   :alt: plot alignment methods benchmark
   :srcset: /auto_examples/images/sphx_glr_plot_alignment_methods_benchmark_002.png
   :class: sphx-glr-single-img


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

 .. code-block:: none

    /Users/emdupre/Desktop/fmralign/examples/plot_alignment_methods_benchmark.py:216: UserWarning: Non-finite values detected. These values will be replaced with zeros.
      plotting.plot_stat_map(




.. GENERATED FROM PYTHON SOURCE LINES 229-237

Summary:
--------
We compared :class:`~fmralign.alignment.group_alignment.GroupAlignment` methods
(i.e., :class:`~fmralign.methods.OptimalTransport`,
:class:`~fmralign.methods.Procrustes`)
with :class:`~fmralign.methods.DetSRM` alignment on visual cortex activity.
You can see that :class:`~fmralign.methods.DetSRM` introduces more
smoothness in the transformation, resulting in slightly higher correlation values.


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

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


.. _sphx_glr_download_auto_examples_plot_alignment_methods_benchmark.py:

.. only:: html

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

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

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

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

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

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

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


.. only:: html

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

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