The fMRI Pre-Processing Pipeline is a lightweight, end-to-end workflow built around fMRIPrep. FMRIPrep handles motion/distortion correction, anatomical/functional alignment to standard spaces, surface mapping, confound modeling, and we added connectivity analysis, with clear QC visualizations considering QC on the number of volumes (Adjustable), FD, high-motion ratio; QC with visual connectivity matrices; and tabular outputs for downstream ML/AI.
- Python ≥ 3.8
- Singularity/Apptainer for containerized execution
- Python packages:
numpy,pandas,nilearn,nibabel,tqdm - fMRIPrep Singularity image:
fmriprep_latest.sif(auto-downloaded) - FreeSurfer license: Valid license file
- (Optional) GPU support with CUDA drivers
- (Optional) conda for environment management
Example Environment Setup
conda create -y -n fmri python=3.10
conda activate fmri
pip install numpy pandas nilearn nibabel tqdm
All paths and behavior are controlled by config.py (shared by all scripts). The pipeline is config-driven with minimal CLI flags for convenience.
Key Configuration Items:
Paths:
INPUT_DIR: BIDS input directoryOUTPUT_DIR: fMRIPrep outputsWORK_DIR: Temporary working directoryLOG_DIR: Pipeline logs
Hardware:
USE_GPU: Enable/disable GPU accelerationGPUS: List of available GPU IDsMAX_PARALLEL: Maximum parallel subjectsMEMORY_MB,NPROCS,OMP_NTHREADS: Resource allocation
fMRIPrep:
OUTPUT_SPACES: Target output spacesFS_NO_RECONALL: Skip FreeSurfer reconstructionLONGITUDINAL: Enable longitudinal processing
Connectivity:
GENERATE_CONNECTIVITY: Enable connectivity matrix generationDEFAULT_ATLASES: Brain atlases for parcellationDEFAULT_CONFOUNDS: Confound regressorsCONNECTIVITY_OUTPUT_DIR: Output directory for matrices
fMRIPrep Output Structure Configuration:
HANDLE_SESSIONS: Handle session-based fMRIPrep output structure (default:True)SESSION_PREFIX: Session directory prefix (default:"ses-")REQUIRED_BOLD_SUFFIX: Required BOLD file suffix (default:_desc-preproc_bold.nii.gz)REQUIRED_CONFOUNDS_SUFFIX: Required confounds suffix (default:_desc-confounds_timeseries.tsv)
File Selection Strategy:
USE_LARGEST_FILE: Use the file with the most time points if multiple are available (default:True)MIN_TIME_POINTS: Minimum required time points for valid data (default:50)
QC thresholds:
MIN_VOLUMES_PASS: 180 (minimum valid volumes for PASS)MIN_VOLUMES_FAIL: 120 (below this = FAIL)FD_PASS_THRESHOLD: 0.3 mm (mean FD)FD_WARN_THRESHOLD: 0.5 mm (mean FD)HIGH_MOTION_PASS_RATIO: 20% (% frames with FD > 0.5 mm)HIGH_MOTION_WARN_RATIO: 30% (% frames with FD > 0.5 mm)
1) Setup & Prerequisites Check, launcher.sh --check
Verifies all required components are available:
- Singularity image
- FreeSurfer license
- Input directory structure
- BIDS filter file
./launcher.sh --check
2) Subject Discovery, subject_manager.py
Discovers available subjects in BIDS directory and creates processing queue.
Inputs: BIDS directory structure (sub-*/)
Outputs: Subject list file (remaining_subjects_array.txt)
python subject_manager.py --action discover --output subjects.txt
python subject_manager.py --action add --subjects sub-01 sub-02
python subject_manager.py --action remove --subjects sub-01
3) fMRI Preprocessing, pipeline_runner.py
Includes automatic connectivity generation and visualization.
Processing Steps:
- BIDS validation and input parsing
- Anatomical preprocessing (skull stripping, registration)
- Functional preprocessing (motion correction, distortion correction)
- Surface generation and volume-to-surface mapping
- Confound estimation and timeseries extraction
- Output space transformation and resampling
- Automatic connectivity matrix generation (if GENERATE_CONNECTIVITY = True)
- Automatic visualization generation
Outputs (per subject in OUTPUT_DIR):
*_desc-preproc_bold.nii.gz: Preprocessed BOLD timeseries*_desc-confounds_timeseries.tsv: Confound regressors*_space-MNI152NLin2009cAsym_desc-preproc_T1w.nii.gz: Anatomical in MNI space- HTML reports with quality metrics
- Connectivity matrices and visualizations (automatic)
Execution Modes:
Single Subject:
python pipeline_runner.py --mode single --subject ON00400 --cpu-only
Parallel Processing:
python pipeline_runner.py --mode parallel --subjects ON00400 ON01016 --cpu-only
Watch Mode (Queue Processing):
python pipeline_runner.py --mode watch
Status Check:
python pipeline_runner.py --mode status
Note: All modes automatically include connectivity generation and visualization unless disabled with --no-connectivity flag.
4) Connectivity Matrix Generation + Visualization, connectivity_matrix.py
Automatically runs after successful fMRIPrep completion (if GENERATE_CONNECTIVITY = True).
Processing Steps:
- Load preprocessed fMRI data and confounds
- Apply brain atlas parcellation (AAL, Harvard-Oxford, Schaefer, etc.)
- Extract regional timeseries with confound regression
- Compute connectivity matrices (correlation, partial correlation, tangent, covariance)
- Generate automatic visualizations (connectivity heatmaps + distribution plots + statistics)
- Save matrices, timeseries, and visualizations
Outputs (per subject in CONNECTIVITY_OUTPUT_DIR):
sub-*_*_timeseries.csv: Regional timeseriessub-*_*_*_connectivity.csv: Connectivity matricessub-*_*_*_visualization.png: Connectivity heatmaps with statistics
Available Atlases: aal, harvard_oxford, schaefer-100, schaefer-400, difumo-256, difumo-1024
python connectivity_matrix.py --subjects sub-01 sub-02 --atlases aal schaefer-100
# OR use standalone runner:
python run_connectivity.py --all-completed --atlases aal harvard_oxford
Note: When using pipeline_runner.py, connectivity generation (including visualization) happens automatically after each subject completes fMRIPrep successfully.
5) Quality Control, fmri_qc.py
Processing Steps:
- Find all subjects with fMRIPrep outputs
- Locate best confounds file per subject/session (≥50 volumes)
- Extract motion parameters (
framewise_displacement) - Compute QC metrics: Mean FD, Max FD, High-Motion Ratio, Volumes
- Apply thresholds to assign PASS / REVIEW / FAIL
- Generate subject-level and group-level QC HTML reports
- Link QC results with connectivity matrices and fMRIPrep HTML reports
Outputs (per subject in qc_reports/subjects):
sub-*_ses-*_qc.html: Detailed subject/session QC report
Outputs (group level in qc_reports/):
fmri_qc_summary.html: Interactive QC summary dashboardfmri_qc_data.csv: Tabular QC data (metrics + status)
QC Thresholds:
- PASS: Mean FD ≤ 0.3 mm, High-Motion Ratio ≤ 20%, Volumes ≥ 180
- REVIEW: Mean FD 0.3–0.5 mm OR High-Motion Ratio ≤ 30% OR Volumes 120–179
- FAIL: Mean FD ≥ 0.5 mm OR High-Motion Ratio > 30% OR Volumes < 120
# Run QC for all subjects
python fmri_qc.py --all
# Run QC for specific subjects
python fmri_qc.py --subjects 001 002
# Export group-level QC summary
python fmri_qc.py --all --export-summary
Pipeline Integration Features
- Unified Workflow: Single command runs fMRIPrep → Connectivity → Visualization automatically
- Smart Processing: Only generates connectivity for successfully completed fMRIPrep subjects
- Automatic Visualization: Every connectivity matrix includes heatmap + statistics plots
- Resource Optimization: Connectivity generation uses the same resource allocation as fMRIPrep
- Error Resilience: Pipeline continues if connectivity generation fails for individual subjects
- Duplicate Prevention: Skips connectivity generation if matrices already exist
- Configuration Control: Enable/disable via GENERATE_CONNECTIVITY in config.py
# 1) Setup environment
conda create -y -n fmri python=3.10
conda activate fmri
pip install numpy pandas nilearn nibabel tqdm
# 2) Configure pipeline
# Edit config.py with your paths and settings
# 3) Check prerequisites
./launcher.sh --check
# 4) Discover subjects
python subject_manager.py --action discover
# 5) Single subject test (includes fMRIPrep + Connectivity + Visualization)
python pipeline_runner.py --mode single --subject ON00400 --cpu-only
# 6) Parallel processing (includes automatic connectivity + visualization)
python pipeline_runner.py --mode parallel --subjects ON00400 ON01016
# 7) Alternative: Standalone connectivity generation
python run_connectivity.py --all-completed
# 8) Run QC (Quality Control)
python fmri_qc.py --all
# 9) Monitor status
python pipeline_runner.py --mode status
Note: Steps 5-6 automatically include connectivity matrix generation and visualization. No separate connectivity command needed!
High-Performance Single Subject
# config.py
MAX_PARALLEL = 1
MEMORY_MB = 100000 # 100GB
NPROCS = 24
OMP_NTHREADS = 8
Balanced Parallel Processing
# config.py
MAX_PARALLEL = 2
MEMORY_MB = 50000 # 50GB per subject
NPROCS = 12
OMP_NTHREADS = 6
CPU-Only Processing
# config.py
USE_GPU = False
MAX_PARALLEL = 4
MEMORY_MB = 32000 # 32GB per subject
NPROCS = 8
OMP_NTHREADS = 4
OUTPUT_DIR/
├── sub-*/
│ ├── anat/
│ │ ├── *_space-MNI152NLin2009cAsym_desc-preproc_T1w.nii.gz
│ │ └── *_desc-brain_mask.nii.gz
│ ├── func/
│ │ ├── *_desc-preproc_bold.nii.gz
│ │ ├── *_desc-confounds_timeseries.tsv
│ │ └── *_desc-carpetplot_bold.svg
│ └── figures/
│ └── *.svg # fMRIPrep figures
├── sub-*.html # fMRIPrep per-subject HTML report
├── logs/
│ ├── sub-*.log
│ ├── sub-*.error
│ └── watcher.log
├── connectivity_matrices/
│ └── sub-*/
│ ├── *_timeseries.csv
│ ├── *_*_connectivity.csv
│ └── *_*_visualization.png
└── qc_reports/ # QC script
├── fmri_qc_summary.html
└── subjects/
└── sub-*_ses-*_qc.html
Pipeline Runner
# Core processing (includes automatic connectivity + visualization)
python pipeline_runner.py --mode {single|parallel|watch|status}
python pipeline_runner.py --mode single --subject SUB_ID [--cpu-only] [--no-connectivity]
python pipeline_runner.py --mode parallel --subjects SUB1 SUB2 [--cpu-only]
# Options
--cpu-only # Force CPU-only processing
--no-connectivity # Skip connectivity matrix generation and visualization
--check # Check prerequisites only
Subject Manager
# Subject management
python subject_manager.py --action {discover|add|remove|list}
python subject_manager.py --action discover [--output FILE]
python subject_manager.py --action add --subjects SUB1 SUB2
python subject_manager.py --action remove --subjects SUB1
Connectivity Generation
# Connectivity matrices + automatic visualization
python connectivity_matrix.py --subjects SUB1 SUB2 --atlases aal schaefer-100
python run_connectivity.py --all-completed --atlases aal harvard_oxford
python run_connectivity.py --subjects SUB1 SUB2 --corr-kinds full-corr partial-corr
# All commands automatically generate both CSV matrices AND PNG visualizations
Launcher (Alternative Interface)
# Bash interface (includes automatic connectivity + visualization)
./launcher.sh --mode {watch|parallel|status|single}
./launcher.sh --mode single --subject SUB_ID [--cpu-only]
./launcher.sh --check
Common Issues
Exit code 126: Permission issues with Singularity
chmod +x /path/to/fmriprep_latest.sif
Exit code 2: Subject not found in BIDS directory
ls /path/to/bids/directory/sub-*
python subject_manager.py --action list
FreeSurfer license error: Invalid or missing license
# Check license file exists and is valid
cat /path/to/license.txt
Out of memory: Reduce resource allocation
# config.py
MEMORY_MB = 32000 # Reduce from higher values
NPROCS = 8 # Reduce parallel processes
GPU not found: Force CPU-only processing
python pipeline_runner.py --mode single --subject SUB_ID --cpu-only
Log Analysis
# Check pipeline status
python pipeline_runner.py --mode status
# View subject logs
tail -f /path/to/logs/sub-SUB_ID.log
cat /path/to/logs/sub-SUB_ID.error
# Monitor system resources
top -u $USER
nvidia-smi # For GPU usage
fMRI QC Manual Review Summary
Overall QC Review
All subjects and sessions are reviewed and classified as PASS, REVIEW, or FAIL based on motion (framewise displacement, FD) and scan length. PASS indicates high-quality data, REVIEW marks usable but moderate-quality data, and FAIL means the data are not usable. The thresholds for these categories (volumes, FD cutoffs, motion ratio) are fully configurable in the QC settings.

Per-Subject QC Reports
Each subject has its own HTML report showing QC status, task and scan details, number of volumes, and motion metrics such as mean and maximum FD. The report also links to the subject’s fMRIPrep output for visual inspection. If connectivity analysis is included, the report provides the connectivity matrix, visualizations, and ROI time series.

fMRIPrep HTML Report Manual Review Guidelines
For detailed quality assessment, review the fMRIPrep HTML reports. Key areas to check:
1. Brain Mask & Segmentation
- Red line: Should outline the brain (not skull/dura)
- Blue line: Should separate white and grey matter
- Check: No brain tissue cutoff
A sample of Brain Mask & Segmentation
2. Spatial Normalization
- Ventricles: Should be aligned between subject and template
- White/grey matter boundaries: Should match
- Check: No stretching or distortion
A sample of Spatial Normalization
3. Fieldmap Correction
- Before/after: Compare images before and after correction
- Frontal area: Check distortion correction
- Check: Normal brain shape after correction
A sample of Fieldmap Correction
4. Functional-Anatomical Alignment
- Red line: Should align with grey/white matter boundary
- Fixed/Moving: No distortion between images
- Check: Proper surface registration
A sample of Functional-Anatomical Alignment
- fMRIPrep: Esteban, O., Markiewicz, C. J., Blair, R. W., et al. (2019). fMRIPrep: a robust preprocessing pipeline for functional MRI. Nature Methods, 16(1), 111-116.
- Nilearn: Abraham, A., Pedregosa, F., Eickenberg, M., et al. (2014). Machine learning for neuroimaging with scikit-learn. Frontiers in Neuroinformatics, 8, 14.
- BIDS: Gorgolewski, K. J., Auer, T., Calhoun, V. D., et al. (2016). The brain imaging data structure, a format for organizing and describing outputs of neuroimaging experiments. Scientific Data, 3, 160044.
- QC / Motion Quality Metrics: Power, J. D., Barnes, K. A., Snyder, A. Z., Schlaggar, B. L., & Petersen, S. E. (2012). Spurious but systematic correlations in functional connectivity MRI networks arise from subject motion. NeuroImage, 59(3), 2142–2154.
We have checked all the items in the code above and reported them in the QC results. However, after preprocessing with fMRIPrep, all outputs must still be carefully reviewed. Always check the fMRIPrep log for the message “fMRIPrep finished successfully!”. Confirm that each scan has an acceptable number of volumes, review the generated QC reports and images, and visually inspect the final outputs for additional verification.
Data with excessive motion or insufficient volumes should be excluded. Typical thresholds include minimum volume counts, mean FD limits, and motion ratios. These thresholds are defined in the QC configuration and can be adjusted depending on dataset requirements. All steps have been carefully performed, and the codes have been made publicly available for transparency and reproducibility.
- Author: Mohammad H. Abbasi (
This email address is being protected from spambots. You need JavaScript enabled to view it. ) - Stanford University, STAI Lab (https://stai.stanford.edu)
- Created: 2025 | Version: 1.0.0 | Last update: September 16, 2025
Acknowledgements
Thanks to the fMRIPrep team, Nilearn contributors, and the broader neuroimaging community
for developing the foundational tools that made this pipeline possible.
Special appreciation to the Stanford Translational AI Lab (STAI Lab) for extending the QC, connectivity,
and pipeline management components.
Sincere thanks to Favour Nerrise and Karan Singh for their valuable feedback, collaboration,
and continuous contributions to improving the pipeline.
If you use this pipeline in your research, please cite it as follows:
Abbasi, M.H., & Adeli, E. (2025). fMRI Processing Pipeline: A lightweight, end-to-end framework for BIDS-compatible fMRI preprocessing and quality control.
Stanford Translational AI Lab, Stanford University. Zenodo.
https://doi.org/10.5281/zenodo.17516604
@software{abbasi2025fmri,
author = {Mohammad Hassan Abbasi and Ehsan Adeli},
title = {f{MRI} {P}rocessing {P}ipeline: A lightweight, end-to-end framework for {BIDS}-compatible f{MRI} preprocessing and quality control},
year = {2025},
institution = {Stanford Translational AI Lab, Stanford University},
publisher = {Zenodo},
doi = {10.5281/zenodo.17516368},
url = {https://doi.org/10.5281/zenodo.17516604},
note = {Zenodo, doi: 10.5281/zenodo.17516604},
}


GitHub
Wiki