Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

AFNI Preprocessing & Group Analysis

Run this notebook

Author: Monika Doerig

Date: May 1 2025

License:

MIT License

Note: If this notebook uses neuroimaging tools from Neurocontainers, those tools retain their original licenses. Please see Neurodesk citation guidelines for details.

Citation:

Tools included in this workflow

AFNI

Workflows this work is based on

Educational resources

Andy’s Brain Book:

Dataset

Flanker Dataset from OpenNeuro:

  • Kelly AMC and Uddin LQ and Biswal BB and Castellanos FX and Milham MP (2018). Flanker task (event-related). OpenNeuro Dataset ds000102. [Dataset] doi: null

  • Kelly AM, Uddin LQ, Biswal BB, Castellanos FX, Milham MP. Competition between functional brain networks mediates behavioral variability. Neuroimage. 2008 Jan 1;39(1):527-37. doi: Kelly et al. (2008). Epub 2007 Aug 23. PMID: 17919929.

  • Mennes, M., Kelly, C., Zuo, X.N., Di Martino, A., Biswal, B.B., Castellanos, F.X., Milham, M.P. (2010). Inter-individual differences in resting-state functional connectivity predict task-induced BOLD activity. Neuroimage, 50(4):1690-701. doi: Mennes et al. (2010). Epub 2010 Jan 15. Erratum in: Neuroimage. 2011 Mar 1;55(1):434

  • Mennes, M., Zuo, X.N., Kelly, C., Di Martino, A., Zang, Y.F., Biswal, B., Castellanos, F.X., Milham, M.P. (2011). Linking inter-individual differences in neural activation and behavior to intrinsic brain dynamics. Neuroimage, 54(4):2950-9. doi: Mennes et al. (2011)ed in your example

Load packages

['afni/25.2.03']

Import Python Modules

1. Download Data

action summary:
  get (notneeded: 3)

The data is structured in BIDS format:

Fetching long content....

Creating Timing Files

Condition-specific timing files are generated using the same approach described in the Preprocessing and GLM notebook. In brief:

  • Onset times and durations are extracted from each subject’s events.tsv file.

  • Trials are categorized into congruent and incongruent conditions.

  • The make_Timings.sh script (from Andy’s AFNI_Scripts repository) is used to convert this event information into AFNI-compatible .1D timing files.

  • For each subject, two timing files are created (one per condition), spanning both runs, and saved in the subject’s func/ directory.

These .1D timing files will then be used in the first-level GLM to model condition-specific brain responses.

Running the Timing File Script

After placing the make_Timings.sh script into the ds000102/ directory, we can execute it from within the notebook:

Check the output:

0 10 40 76 102 150 164 174 208 220 232 260 
0 54 64 76 88 130 144 154 196 246 274 

2. Running Preprocessing and First-Level Analysis for All Subjects

All of the preprocessing and regression steps for subject sub-08 were introduced and explained in the example notebooks Preprocessing with AFNI and AFNI Preprocessing and GLM, both of which are highly inspired by Andy’s Brain Book’s tutorial.
These notebooks demonstrate how to use afni_proc.py to generate an automated pipeline and interpret each preprocessing and regression block.

Preprocessing and GLM Workflow:

➡️ setup ➡️ tcat ➡️ tshift ➡️ align ➡️ tlrc ➡️ volreg ➡️ blur ➡️ mask ➡️ scale ➡️ regress ➡️ 🧠

✅ Outputs: fitted time series, residuals, tSNR maps, beta weights, and statistical maps from the GLM.

To replicate the preprocessing and GLM steps used for sub-08 across multiple participants, we loop over all 3 subjects (sub-01 to sub-03) and generate an individualized AFNI pipeline for each one using afni_proc.py. This automated approach performs several key operations:

  • Loads each subject’s anatomical image and both functional runs.

  • Specifies the full processing pipeline: slice timing correction, alignment, linear registration to MNI space, motion correction, blurring, masking, scaling, and regression modeling.

  • Models two stimulus conditions (congruent and incongruent) using a gamma basis function (GAM).

  • Specifies two general linear tests (GLTs): incongruent − congruent and congruent − incongruent.

  • Censors time points with excessive motion (> 0.3 mm) and outlier volumes (> 5% of voxels), and estimates spatial smoothness for later use in group analysis.

  • Uses separate motion parameter regressors per run and saves the full fitted timeseries.

  • Runs 3dREMLfit for improved autocorrelation modeling.

Processing is executed in parallel using a process pool, with up to 3 subjects processed simultaneously. Each subject’s script is saved and executed in a controlled logging environment, which captures terminal output into a log file for transparency and troubleshooting.

This block ensures consistent preprocessing and first-level GLM estimation across all subjects in the dataset.

⏳ Note: This next step will take a while to run (approximately 1 to 3 hours depending on computing resources).
CPUs available: 32
Parallel subjects: 3
Jobs per subject: 10
Loading...

Summary of results:
sub-02 skipped (already processed)
sub-01 skipped (already processed)
sub-03 skipped (already processed)

3. Group - Analysis

After estimating the first-level general linear model (GLM) for each subject, we will perform a group-level analysis to assess whether the Incongruent - Congruent contrast showed a consistent effect across subjects.

Creating a Group Mask

First, we’ll create a group-level mask by combining each subject’s individual mask using a logical intersection. This ensures that only voxels present in all subjects’ data are included in the group analysis:

++ processing 3 input dataset(s), NN=2...
++ padding all datasets by 0 (for dilations)
++ have 3 volumes of input to combine
++ frac 1 over 3 volumes gives min count 3
++ voxel limits: 0 clipped, 71053 survived, 240243 were zero
++ writing result group_mask...
** ERROR: output dataset name 'group_mask' conflicts with existing file
** ERROR: dataset NOT written to disk!

3.1 Group-Level Analysis with 3dttest++

AFNI’s 3dttest++ performs a voxelwise one-sample t-test across subjects. This tests whether the average contrast estimate (e.g., Incongruent - Congruent) is significantly different from zero at each voxel.oxelwise t-scoresariability.

Identifying Contrast Sub-Brick

Before running the group-level test, we must determine which sub-brick contains the desired contrast. We use 3dinfo to inspect the subject-level stats+tlrc dataset and find the index of the contrast sub-brick corresponding to incongruent minus congruent (e.g., sub-brick #7, depending on how GLTs were defined in afni_proc.py):

++ 3dinfo: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]

Dataset File:    stats.sub-01+tlrc
Identifier Code: XYZ_Y9xxyZs1gXQn8ZFQ1SMccg  Creation Date: Thu Apr  9 08:40:46 2026
Template Space:  MNI_2009c_asym
Dataset Type:    Func-Bucket (-fbuc)
Byte Order:      LSB_FIRST [this CPU native = LSB_FIRST]
Storage Mode:    BRIK
Storage Space:   16,187,392 (16 million) bytes
Geometry String: "MATRIX(-3,0,0,94.5,0,-3,0,130.5,0,0,3,-76.5):64,76,64"
Data Axes Tilt:  Plumb
Data Axes Orientation:
  first  (x) = Left-to-Right
  second (y) = Posterior-to-Anterior
  third  (z) = Inferior-to-Superior   [-orient LPI]
R-to-L extent:   -94.500 [R] -to-    94.500 [L] -step-     3.000 mm [ 64 voxels]
A-to-P extent:   -94.500 [A] -to-   130.500 [P] -step-     3.000 mm [ 76 voxels]
I-to-S extent:   -76.500 [I] -to-   112.500 [S] -step-     3.000 mm [ 64 voxels]
Number of values stored at each pixel = 13
  -- At sub-brick #0 'Full_Fstat' datum type is float:            0 to       57.6257
     statcode = fift;  statpar = 2 266
  -- At sub-brick #1 'congruent#0_Coef' datum type is float:     -32.8176 to       17.2739
  -- At sub-brick #2 'congruent#0_Tstat' datum type is float:     -7.21763 to       6.16751
     statcode = fitt;  statpar = 266
  -- At sub-brick #3 'congruent_Fstat' datum type is float:            0 to       52.0941
     statcode = fift;  statpar = 1 266
  -- At sub-brick #4 'incongruent#0_Coef' datum type is float:     -28.5104 to       15.6762
  -- At sub-brick #5 'incongruent#0_Tstat' datum type is float:     -5.63953 to       10.3149
     statcode = fitt;  statpar = 266
  -- At sub-brick #6 'incongruent_Fstat' datum type is float:            0 to       106.398
     statcode = fift;  statpar = 1 266
  -- At sub-brick #7 'incongruent-congruent_GLT#0_Coef' datum type is float:     -22.0622 to       17.8422
  -- At sub-brick #8 'incongruent-congruent_GLT#0_Tstat' datum type is float:     -4.78922 to       6.65772
     statcode = fitt;  statpar = 266
  -- At sub-brick #9 'incongruent-congruent_GLT_Fstat' datum type is float:            0 to       44.3253
     statcode = fift;  statpar = 1 266
  -- At sub-brick #10 'congruent-incongruent_GLT#0_Coef' datum type is float:     -17.8422 to       22.0622
  -- At sub-brick #11 'congruent-incongruent_GLT#0_Tstat' datum type is float:     -6.65772 to       4.78922
     statcode = fitt;  statpar = 266
  -- At sub-brick #12 'congruent-incongruent_GLT_Fstat' datum type is float:            0 to       44.3253
     statcode = fift;  statpar = 1 266

----- HISTORY -----
[ubuntu@6c8ba8253917: Thu Apr  9 08:40:46 2026] {AFNI_25.2.03:linux_ubuntu_24_64} 3dDeconvolve -input pb04.sub-01.r01.scale+tlrc.HEAD pb04.sub-01.r02.scale+tlrc.HEAD -censor censor_sub-01_combined_2.1D -ortvec mot_demean.r01.1D mot_demean_r01 -ortvec mot_demean.r02.1D mot_demean_r02 -polort 2 -num_stimts 2 -stim_times 1 stimuli/congruent.1D GAM -stim_label 1 congruent -stim_times 2 stimuli/incongruent.1D GAM -stim_label 2 incongruent -jobs 10 -gltsym 'SYM: incongruent -congruent' -glt_label 1 incongruent-congruent -gltsym 'SYM: congruent -incongruent' -glt_label 2 congruent-incongruent -fout -tout -x1D X.xmat.1D -xjpeg X.jpg -x1D_uncensored X.nocensor.xmat.1D -errts errts.sub-01 -bucket stats.sub-01
[ubuntu@6c8ba8253917: Thu Apr  9 08:40:46 2026] Output prefix: stats.sub-01

This command lists all sub-bricks with their labels, allowing us to find the relevant contrast parameter estimate:

-- At sub-brick #7 'incongruent-congruent_GLT#0_Coef' datum type is float:     -22.0622 to       17.8422

Sub-bricks labeled with “Coef” represent contrast (beta) estimates, while “Tstat” or “Fstat” indicate test statistics. For group analysis, we will extract the Coef sub-brick (here: index [7]).

We then automate the 3dttest++ execution with the following steps:

  • Set the base directory containing all subjects’ AFNI result folders.

  • Locate sub-brick [**7] for each subject (the contrast of interest).

  • Verify dataset existence to avoid processing missing subjects.

  • Construct the 3dttest++ command with:

    • An output prefix for group results,

    • A group brain mask to constrain the analysis,

    • A label for the subject set (Inc-Con),

    • Subpaired with their corresponding contrast sub-brick pathssti**mates.

  • Run the command using subprocess.run() to capture and log output.

The resulting dataset (Flanker_Inc-Con_ttest+tlrc) contains:

  • Effect size map: average contrast values across subjects

  • T-statistic map: voxelwise t-values representing statistical significance

Running 3dttest++...


Command: 3dttest++ -prefix /home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/group_results/Flanker-Inc-Con_ttest -mask /home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/group_mask+tlrc -setA Inc-Con sub-01 /home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/sub-01.results/stats.sub-01+tlrc[7] sub-02 /home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/sub-02.results/stats.sub-02+tlrc[7] sub-03 /home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/sub-03.results/stats.sub-03+tlrc[7]

++ 3dttest++: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]
++ Authored by: Zhark++
++ 71053 voxels in -mask dataset
++ option -setA :: processing as LONG form (label label dset label dset ...)
++ have 3 volumes corresponding to option '-setA'
++ loading -setA datasets
++ t-testing:0123456789.0123456789.0123456789.0123456789.0123456789.!
++ ---------- End of analyses -- freeing workspaces ----------
++ Creating FDR curves in output dataset
*+ WARNING: Smallest FDR q [1 Inc-Con_Tstat] = 0.6916 ==> few true single voxel detections
 + Added 1 FDR curve to dataset
** ERROR: output dataset name 'Flanker-Inc-Con_ttest' conflicts with existing file
** ERROR: dataset NOT written to disk!
++ ----- 3dttest++ says so long, farewell, and happy trails to you :) -----

This code snippet automates running AFNI’s 3dttest++ for a group analysis of the Incongruent - Congruent contrast:

  • Set the base directory where all subjects’ AFNI results are stored.

  • Find all subject result folders matching the pattern sub-*.results.

  • Build a list of dataset paths pointing to the 7th sub-brick [7] (the contrast of interest) in each subject’s stats dataset, verifying file existence and alerting if missing.

  • Construct the 3dttest++ command with:

    • Output prefix for group results,

    • Group mask to restrict the test to voxels common across subjects,

    • Label for the group set (Inc-Con),

    • Subject IDs paired with their corresponding contrast sub-brick paths.

  • Run the command as a subprocess, capturing and printing AFNI’s output and errors for review.

The resulting output (Flanker_Inc-Con_ttest+tlrc) contains:

  • Effect size map: average contrast across subjects

  • T-statistic map: voxelwise t-sores

3.2 Performing Group Analysis with 3dMEMA

To account for both the variability within subjects (parameter estimate differences) and the variability across subjects (contrast estimate precision), we will also perform a group-level analysis using AFNI’s 3dMEMA.

Unlike a simple t-test, 3dMEMA leverages each subject’s contrast estimate and corresponding t-statistic (or standard error), providing a more accurate mixed-effects model.

The steps we will take are:

  • Build a set list containing each subject’s ID along with the paths to their contrast estimate (_REML+tlrc[7]) and t-statistic (_REML+tlrc[8]) sub-bricks.

  • Verify that both files exist for each subject to avoid missing data errors.

  • Construct the 3dMEMA command with an output prefix, the group mask, and the full subject set list.

  • Run the command as a subprocess, capturing output for review.

This process will produce a group-level statistical map that balances effect size and reliability, offering a robust inference about the Incongruent - Congruent contrast across subjects.

Running 3dMEMA...

Command: 3dMEMA -prefix /home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/group_results/Flanker_Inc-Con_MEMA -mask /home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/group_mask+tlrc -set IncCon sub-01 /home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/sub-01.results/stats.sub-01_REML+tlrc[7] /home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/sub-01.results/stats.sub-01_REML+tlrc[8] sub-02 /home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/sub-02.results/stats.sub-02_REML+tlrc[7] /home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/sub-02.results/stats.sub-02_REML+tlrc[8] sub-03 /home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/sub-03.results/stats.sub-03_REML+tlrc[7] /home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/sub-03.results/stats.sub-03_REML+tlrc[8] 



** Error: 
   File /home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/group_results/Flanker_Inc-Con_MEMAexists! Try a different name.


3.3 Visualizing Group-Level Results

Now that we have completed both group analyses — one with 3dttest++ and one with 3dMEMA — let’s visualize the resulting voxelwise t-statistic maps.

Steps:

  1. Convert AFNI datasets to NIfTI format using 3dcopy, to ensure compatibility with Python neuroimaging tools like nilearn.

  1. Extract the t-statistic sub-brick (sub-brick index [1]) using 3dTcat. This gives us:

    • Inc-Con_Tstat from the 3dttest++ result

    • IncCon_Tstat from the 3dMEMA result

  1. Load the statistical maps into Python using nilearn.image.load_img().

  1. Plot using transparent thresholding via nilearn.plotting.plot_stat_map() with transparency_range=[1, 3.3]. Rather than hard thresholding, this approach fades out low t-values and makes voxels above T > 3.3 (≈ p < 0.001) fully opaque, giving a more complete and informative view of the data.

Note on Multiple Comparison Correction:
Cluster-size correction using 3dClustSim requires stable estimates of spatial smoothness, which generally requires at least 14 subjects.
Since our analysis includes only 3 subjects, we do not apply 3dClustSim or other parametric corrections.
This approach is intended for exploratory visualization only and should not be used for formal statistical inference.

This allows us to visually inspect and compare the sensitivity and spatial extent of effects revealed by the simple one-sample t-test (3dttest++) and the mixed-effects model (3dMEMA) for the Incongruent - Congruent contrast.

++ 3dcopy: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]
** ERROR: output dataset name 'Flanker-Inc-Con_ttest.nii.gz' conflicts with existing file
** ERROR: dataset NOT written to disk!
++ 3dcopy: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]
** ERROR: output dataset name 'Flanker_Inc-Con_MEMA.nii.gz' conflicts with existing file
** ERROR: dataset NOT written to disk!
++ 3dinfo: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]

Dataset File:    /home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/group_results/Flanker-Inc-Con_ttest.nii.gz
Identifier Code: XYZ_6Wu73ZNXHIX5JfN_Fpi3ZA  Creation Date: Thu Apr  9 09:52:04 2026
Template Space:  MNI_2009c_asym
Dataset Type:    Anat Bucket (-abuc)
Byte Order:      LSB_FIRST {assumed} [this CPU native = LSB_FIRST]
Storage Mode:    NIFTI
Storage Space:   2,490,368 (2.5 million) bytes
Geometry String: "MATRIX(-3,0,0,94.5,0,-3,0,130.5,0,0,3,-76.5):64,76,64"
Data Axes Tilt:  Plumb
Data Axes Orientation:
  first  (x) = Left-to-Right
  second (y) = Posterior-to-Anterior
  third  (z) = Inferior-to-Superior   [-orient LPI]
R-to-L extent:   -94.500 [R] -to-    94.500 [L] -step-     3.000 mm [ 64 voxels]
A-to-P extent:   -94.500 [A] -to-   130.500 [P] -step-     3.000 mm [ 76 voxels]
I-to-S extent:   -76.500 [I] -to-   112.500 [S] -step-     3.000 mm [ 64 voxels]
Number of values stored at each pixel = 2
  -- At sub-brick #0 'Inc-Con_mean' datum type is float:     -2.33243 to       4.29261
  -- At sub-brick #1 'Inc-Con_Tstat' datum type is float:     -51.0612 to            99
     statcode = fitt;  statpar = 2

----- HISTORY -----
[ubuntu@6c8ba8253917: Thu Apr  9 09:50:10 2026] {AFNI_25.2.03:linux_ubuntu_24_64} 3dttest++ -prefix /home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/group_results/Flanker-Inc-Con_ttest -mask /home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/group_mask+tlrc -setA Inc-Con sub-01 '/home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/sub-01.results/stats.sub-01+tlrc[7]' sub-02 '/home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/sub-02.results/stats.sub-02+tlrc[7]' sub-03 '/home/jovyan/workspace/books/examples/functional_imaging/afni_pro_glm/sub-03.results/stats.sub-03+tlrc[7]'
[ubuntu@6c8ba8253917: Thu Apr  9 09:52:03 2026] {AFNI_25.2.03:linux_ubuntu_24_64} 3dcopy ./afni_pro_glm/group_results/Flanker-Inc-Con_ttest+tlrc ./afni_pro_glm/group_results/Flanker-Inc-Con_ttest.nii.gz

++ 3dTcat: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]
** ERROR: output dataset name 'Flanker-Inc-Con_ttest_Tstat.nii.gz' conflicts with existing file
** ERROR: dataset NOT written to disk!
++ elapsed time = 0.2 s
++ 3dTcat: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]
** ERROR: output dataset name 'Flanker_Inc-Con_MEMA_Tstat.nii.gz' conflicts with existing file
** ERROR: dataset NOT written to disk!
++ elapsed time = 0.2 s
<Figure size 730x350 with 5 Axes>
<Figure size 730x350 with 5 Axes>

4. ROI Analysis

4.1 ROI Analysis: Atlas-Based MidACC Mask

To investigate group-level effects within a specific anatomical region, we use an atlas-based Region of Interest (ROI) mask focusing on the mid anterior cingulate cortex (midACC).

1. Identify Available Atlases:

We begin by confirming the available atlases using:

!whereami -show_atlas_code

This lists all atlases bundled with AFNI.

Fetching long content....

2. Generate ROI masks (midACC): Using the FS.afni.MNI2009c_asym atlas — a FreeSurfer-based parcellation in MNI 2009c asymmetric space, matching our preprocessing template — we create separate masks for the left and right midACC using the caudalanteriorcingulate label:

!whereami -mask_atlas_region "FS.afni.MNI2009c_asym::ctx-lh-caudalanteriorcingulate" -prefix ./afni_pro_glm/group_results/midACC_lh_mask
!whereami -mask_atlas_region "FS.afni.MNI2009c_asym::ctx-rh-caudalanteriorcingulate" -prefix ./afni_pro_glm/group_results/midACC_rh_mask
++ Input coordinates orientation set by default rules to RAI
Best match for ctx-lh-caudalanteriorcingulate:
   ctx-lh-caudalanteriorcingulate (code 48 )

** ERROR: output dataset name 'midACC_lh_mask' conflicts with existing file
** ERROR: dataset NOT written to disk!
++ Input coordinates orientation set by default rules to RAI
Best match for ctx-rh-caudalanteriorcingulate:
   ctx-rh-caudalanteriorcingulate (code 83 )

** ERROR: output dataset name 'midACC_rh_mask' conflicts with existing file
** ERROR: dataset NOT written to disk!

We then combine both hemispheres into a single bilateral ROI mask:

++ processing 2 input dataset(s), NN=2...
++ padding all datasets by 0 (for dilations)
++ have 2 volumes of input to combine
++ frac 0 over 2 volumes gives min count 0
++ voxel limits: 0 clipped, 3876 survived, 8526145 were zero
++ writing result midACC_mask...
** ERROR: output dataset name 'midACC_mask' conflicts with existing file
** ERROR: dataset NOT written to disk!

To use the mask with Python tools like nilearn, we also convert it to NIfTI format:

++ 3dAFNItoNIFTI: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]
<nilearn.plotting.displays._slicers.OrthoSlicer at 0x7fd94e97c050>
<Figure size 730x350 with 5 Axes>

3. Resample the Mask to Match Functional Data:

To ensure compatibility with the functional/statistical datasets, we resample the ROI mask to the same voxel resolution as the subject-level stats+tlrc files:

** ERROR: output dataset name 'midACC_rs' conflicts with existing file
** ERROR: dataset NOT written to disk!
failure: cannot write dataset, exiting...

4. Extract Contrast Values from Each Subject:

We extract the contrast estimate for each subject by:

  1. Collecting the congruent and incongruent beta sub-bricks across all subjects:

++ 3dbucket: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]
++ 3dbucket: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]
++ 3dbucket: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]
*+ WARNING: Over-writing dataset ././afni_pro_glm/group_results/Congruent_betas+tlrc.HEAD
++ 3dbucket: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]
*+ WARNING: Over-writing dataset ././afni_pro_glm/group_results/Incongruent_betas+tlrc.HEAD
++ 3dbucket: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]
*+ WARNING: Over-writing dataset ././afni_pro_glm/group_results/Congruent_betas+tlrc.HEAD
++ 3dbucket: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]
*+ WARNING: Over-writing dataset ././afni_pro_glm/group_results/Incongruent_betas+tlrc.HEAD

This will produce 4D images:

  • Congruent_betas+tlrc → all congruent betas across subjects

  • Incongruent_betas+tlrc → all incongruent betas across subjects

  1. Computing the subject-wise contrast (Incongruent – Congruent) using 3dcalc:

++ 3dcalc: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]
++ Authored by: A cast of thousands
** ERROR: output dataset name 'incong_minus_cong' conflicts with existing file
** ERROR: dataset NOT written to disk!
  1. Extracting the mean contrast value within the ROI for each subject using 3dmaskave:

++ 3dmaskave: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]
+++ 147 voxels survive the mask

5. Statistical Testing: Finally, we load the contrast values and run a one-sample t-test to determine whether the average contrast across subjects significantly differs from zero:

Mean contrast: 0.1796
t = 2.2511, p = 0.1532
✅ Interpretation

This provides a simple but interpretable ROI-based statistical test focused on the Incongruent - Congruent contrast in the midACC. This result indicates that:

  • On average, the contrast Incongruent - Congruent is positive within the mid anterior cingulate cortex (midACC) ROI.

  • The difference is not statistically significant at the α = 0.05 level (p = 0.153) with only 3 subjects.

  • The direction of the effect is consistent with the expected result — greater midACC activation during Incongruent compared to Congruent trials.

  • The lack of significance is expected given the very small sample size of 3 subjects — this result is for demonstration purposes only.

4.2 ROI Analysis Using a Spherical Mask

To complement the atlas-based ROI analysis, we can also define a spherical ROI centered on a coordinate of interest. This can be useful for hypothesis-driven analyses targeting specific anatomical or functional peaks.

1. Define the sphere:

  • A 5mm radius sphere is created around the coordinate (0, 20, 44) using AFNI’s 3dUndump.

  • The sphere is aligned to the grid of the functional data via the -master option.

echo "0 20 44" | 3dUndump -orient LPI -srad 5 -master Incongruent_betas+tlrc -prefix ConflictROI+tlrc -xyz -
++ 3dUndump: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]
++ Starting to fill via -xyz coordinates
++ Total number of voxels filled = 19
** ERROR: output dataset name 'ConflictROI' conflicts with existing file
** ERROR: dataset NOT written to disk!
++ Wrote out dataset ././afni_pro_glm/group_results/ConflictROI_AA1+tlrc.BRIK

2. Extract ROI contrast values:

  • The average Incongruent - Congruent contrast value will be computed for each subject using 3dmaskave:

++ 3dmaskave: AFNI version=AFNI_25.2.03 (Jul  4 2025) [64-bit]
+++ 19 voxels survive the mask

3. Statistical test:

  • A one-sample t-test can be performed to determine whether the contrast values within the sphere significantly differ from zero.

Mean contrast: 0.2386
t = 1.8883, p = 0.1996

✅ Interpretation of Sphere ROI Results

  • The mean contrast value for Incongruent-Congruent in the spherical ROI is 0.2386.

  • The one-sample t-test does not shows a significant effect at the α = 0.05 level:
    t(2) = 1.8883, p = 0.1996.

  • The direction of the effect remains consistent with the expected result — greater activation during Incongruent compared to Congruent trials — but the small sample size of 3 subjects is insufficient to reach statistical significance.

  • This result is for demonstration purposes only.

Dependencies in Jupyter/Python

  • Using the package watermark to document system environment and software versions used in this notebook, alongside the Neurodesktop version extracted from the JUPYTER_IMAGE or NEURODESKTOP_VERSION environment variables.

Last updated: 2026-04-09T09:53:23.417874+00:00

Python implementation: CPython
Python version       : 3.13.9
IPython version      : 9.7.0

Compiler    : GCC 14.3.0
OS          : Linux
Release     : 5.15.0-171-generic
Machine     : x86_64
Processor   : x86_64
CPU cores   : 32
Architecture: 64bit

IPython   : 9.7.0
ipyniivue : 2.4.4
matplotlib: 3.10.8
nibabel   : 5.3.3
nilearn   : 0.13.1
numpy     : 2.3.5
scipy     : 1.16.3
tqdm      : 4.67.1

Neurodesktop version: 2025-12-20
References
  1. Kelly, A. M. C., Uddin, L. Q., Biswal, B. B., Castellanos, F. X., & Milham, M. P. (2008). Competition between functional brain networks mediates behavioral variability. NeuroImage, 39(1), 527–537. 10.1016/j.neuroimage.2007.08.008
  2. Mennes, M., Kelly, C., Zuo, X.-N., Di Martino, A., Biswal, B. B., Castellanos, F. X., & Milham, M. P. (2010). Inter-individual differences in resting-state functional connectivity predict task-induced BOLD activity. NeuroImage, 50(4), 1690–1701. 10.1016/j.neuroimage.2010.01.002
  3. Mennes, M., Zuo, X.-N., Kelly, C., Di Martino, A., Zang, Y.-F., Biswal, B., Castellanos, F. X., & Milham, M. P. (2011). Linking inter-individual differences in neural activation and behavior to intrinsic brain dynamics. NeuroImage, 54(4), 2950–2959. 10.1016/j.neuroimage.2010.10.046