.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/07_advanced/plot_bids_analysis.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code or to run this example in your browser via Binder .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_07_advanced_plot_bids_analysis.py: BIDS dataset first and second level analysis ============================================ Full step-by-step example of fitting a :term:`GLM` to perform a first and second level analysis in a :term:`BIDS` dataset and visualizing the results. Details about the :term:`BIDS` standard can be consulted at `https://bids.neuroimaging.io/ `_. More specifically: 1. Download an :term:`fMRI` :term:`BIDS` dataset with two language conditions to contrast. 2. Extract first level model objects automatically from the :term:`BIDS` dataset. 3. Fit a second level model on the fitted first level models. Notice that in this case the preprocessed :term:`bold` images were already normalized to the same :term:`MNI` space. .. GENERATED FROM PYTHON SOURCE LINES 21-24 .. code-block:: Python from nilearn import plotting .. GENERATED FROM PYTHON SOURCE LINES 25-33 Fetch example :term:`BIDS` dataset ---------------------------------- We download a simplified :term:`BIDS` dataset made available for illustrative purposes. It contains only the necessary information to run a statistical analysis using Nilearn. The raw data subject folders only contain bold.json and events.tsv files, while the derivatives folder includes the preprocessed files preproc.nii and the confounds.tsv files. .. GENERATED FROM PYTHON SOURCE LINES 33-37 .. code-block:: Python from nilearn.datasets import fetch_language_localizer_demo_dataset data = fetch_language_localizer_demo_dataset(legacy_output=False) .. GENERATED FROM PYTHON SOURCE LINES 38-39 Here is the location of the dataset on disk. .. GENERATED FROM PYTHON SOURCE LINES 39-41 .. code-block:: Python print(data.data_dir) .. rst-class:: sphx-glr-script-out .. code-block:: none /home/himanshu/nilearn_data/fMRI-language-localizer-demo-dataset .. GENERATED FROM PYTHON SOURCE LINES 42-53 Obtain automatically FirstLevelModel objects and fit arguments -------------------------------------------------------------- From the dataset directory we automatically obtain the FirstLevelModel objects with their subject_id filled from the :term:`BIDS` dataset. Moreover, we obtain for each model a dictionary with run_imgs, events and confounder regressors since in this case a confounds.tsv file is available in the :term:`BIDS` dataset. To get the first level models we only have to specify the dataset directory and the task_label as specified in the file names. .. GENERATED FROM PYTHON SOURCE LINES 53-65 .. code-block:: Python from nilearn.glm.first_level import first_level_from_bids task_label = "languagelocalizer" ( models, models_run_imgs, models_events, models_confounds, ) = first_level_from_bids( data.data_dir, task_label, img_filters=[("desc", "preproc")], n_jobs=2 ) .. rst-class:: sphx-glr-script-out .. code-block:: none /home/himanshu/Desktop/nilearn_work/nilearn/nilearn/glm/first_level/first_level.py:1374: UserWarning: 'StartTime' not found in file /home/himanshu/nilearn_data/fMRI-language-localizer-demo-dataset/derivatives/sub-01/func/sub-01_task-languagelocalizer_desc-preproc_bold.json. StartTime = infer_slice_timing_start_time_from_dataset( .. GENERATED FROM PYTHON SOURCE LINES 66-70 Quick sanity check on fit arguments ----------------------------------- Additional checks or information extraction from pre-processed data can be made here. .. GENERATED FROM PYTHON SOURCE LINES 72-73 We just expect one run_img per subject. .. GENERATED FROM PYTHON SOURCE LINES 73-77 .. code-block:: Python from pathlib import Path print([Path(run).name for run in models_run_imgs[0]]) .. rst-class:: sphx-glr-script-out .. code-block:: none ['sub-01_task-languagelocalizer_desc-preproc_bold.nii.gz'] .. GENERATED FROM PYTHON SOURCE LINES 78-81 The only confounds stored are regressors obtained from motion correction. As we can verify from the column headers of the confounds table corresponding to the only run_img present. .. GENERATED FROM PYTHON SOURCE LINES 81-83 .. code-block:: Python print(models_confounds[0][0].columns) .. rst-class:: sphx-glr-script-out .. code-block:: none Index(['RotX', 'RotY', 'RotZ', 'X', 'Y', 'Z'], dtype='object') .. GENERATED FROM PYTHON SOURCE LINES 84-87 During this acquisition the subject read blocks of sentences and consonant strings. So these are our only two conditions in events. We verify there are 12 blocks for each condition. .. GENERATED FROM PYTHON SOURCE LINES 87-89 .. code-block:: Python print(models_events[0][0]["trial_type"].value_counts()) .. rst-class:: sphx-glr-script-out .. code-block:: none trial_type language 12 string 12 Name: count, dtype: int64 .. GENERATED FROM PYTHON SOURCE LINES 90-97 First level model estimation ---------------------------- Now we simply fit each first level model and plot for each subject the :term:`contrast` that reveals the language network (language - string). Notice that we can define a :term:`contrast` using the names of the conditions specified in the events dataframe. Sum, subtraction and scalar multiplication are allowed. .. GENERATED FROM PYTHON SOURCE LINES 99-100 Set the threshold as the z-variate with an uncorrected p-value of 0.001. .. GENERATED FROM PYTHON SOURCE LINES 100-104 .. code-block:: Python from scipy.stats import norm p001_unc = norm.isf(0.001) .. GENERATED FROM PYTHON SOURCE LINES 105-106 Prepare figure for concurrent plot of individual maps. .. GENERATED FROM PYTHON SOURCE LINES 106-127 .. code-block:: Python import matplotlib.pyplot as plt fig, axes = plt.subplots(nrows=2, ncols=5, figsize=(8, 4.5)) model_and_args = zip(models, models_run_imgs, models_events, models_confounds) for midx, (model, imgs, events, confounds) in enumerate(model_and_args): # fit the GLM model.fit(imgs, events, confounds) # compute the contrast of interest zmap = model.compute_contrast("language-string") plotting.plot_glass_brain( zmap, colorbar=False, threshold=p001_unc, title=f"sub-{model.subject_label}", axes=axes[int(midx / 5), int(midx % 5)], plot_abs=False, display_mode="x", ) fig.suptitle("subjects z_map language network (unc p<0.001)") plotting.show() .. image-sg:: /auto_examples/07_advanced/images/sphx_glr_plot_bids_analysis_001.png :alt: subjects z_map language network (unc p<0.001) :srcset: /auto_examples/07_advanced/images/sphx_glr_plot_bids_analysis_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 128-134 Second level model estimation ----------------------------- We just have to provide the list of fitted FirstLevelModel objects to the SecondLevelModel object for estimation. We can do this because all subjects share a similar design matrix (same variables reflected in column names). .. GENERATED FROM PYTHON SOURCE LINES 134-138 .. code-block:: Python from nilearn.glm.second_level import SecondLevelModel second_level_input = models .. GENERATED FROM PYTHON SOURCE LINES 139-140 Note that we apply a smoothing of 8mm. .. GENERATED FROM PYTHON SOURCE LINES 140-143 .. code-block:: Python second_level_model = SecondLevelModel(smoothing_fwhm=8.0, n_jobs=2) second_level_model = second_level_model.fit(second_level_input) .. GENERATED FROM PYTHON SOURCE LINES 144-148 Computing contrasts at the second level is as simple as at the first level. Since we are not providing confounders we are performing a one-sample test at the second level with the images determined by the specified first level contrast. .. GENERATED FROM PYTHON SOURCE LINES 148-152 .. code-block:: Python zmap = second_level_model.compute_contrast( first_level_contrast="language-string" ) .. GENERATED FROM PYTHON SOURCE LINES 153-155 The group level :term:`contrast` reveals a left lateralized fronto-temporal language network. .. GENERATED FROM PYTHON SOURCE LINES 155-165 .. code-block:: Python plotting.plot_glass_brain( zmap, colorbar=True, threshold=p001_unc, title="Group language network (unc p<0.001)", plot_abs=False, display_mode="x", figure=plt.figure(figsize=(5, 4)), ) plotting.show() .. image-sg:: /auto_examples/07_advanced/images/sphx_glr_plot_bids_analysis_002.png :alt: plot bids analysis :srcset: /auto_examples/07_advanced/images/sphx_glr_plot_bids_analysis_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-timing **Total running time of the script:** (1 minutes 2.618 seconds) **Estimated memory usage:** 1078 MB .. _sphx_glr_download_auto_examples_07_advanced_plot_bids_analysis.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/nilearn/nilearn/0.10.4?urlpath=lab/tree/notebooks/auto_examples/07_advanced/plot_bids_analysis.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_bids_analysis.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_bids_analysis.py ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_