NeuroCAPs
NeuroCAPs: A Python Package for Performing Co-Activation Patterns Analyses on Resting-State and Task-Based fMRI Data - Published in JOSS (2025)
Science Score: 93.0%
This score indicates how likely this project is to be science-related based on various indicators:
-
○CITATION.cff file
-
✓codemeta.json file
Found codemeta.json file -
✓.zenodo.json file
Found .zenodo.json file -
✓DOI references
Found 17 DOI reference(s) in README and JOSS metadata -
✓Academic publication links
Links to: joss.theoj.org -
○Academic email domains
-
○Institutional organization owner
-
✓JOSS paper metadata
Published in Journal of Open Source Software
Keywords
Scientific Fields
Repository
A Python package for performing Co-Activation Patterns (CAPs) analyses on resting-state and task-based fMRI data.
Basic Info
- Host: GitHub
- Owner: donishadsmith
- License: mit
- Language: Python
- Default Branch: main
- Homepage: https://neurocaps.readthedocs.io
- Size: 473 MB
Statistics
- Stars: 8
- Watchers: 1
- Forks: 2
- Open Issues: 2
- Releases: 191
Topics
Metadata Files
README.md
NeuroCAPs: Neuroimaging Co-Activation Patterns
NeuroCAPs (Neuroimaging Co-Activation Patterns) is a Python package for performing Co-Activation Patterns (CAPs) analyses on resting-state or task-based fMRI data. CAPs identifies recurring brain states by applying k-means clustering on BOLD timeseries data [^1].
Installation
Requires Python 3.9-3.12.
Standard Installation
bash
pip install neurocaps
Windows Users: Enable long paths and use:
bash
pip install neurocaps[windows]
Development Version
```bash git clone --depth 1 https://github.com/donishadsmith/neurocaps/ cd neurocaps pip install -e .
For windows
pip install -e .[windows]
Clone with submodules to include test data ~140 MB
git submodule update --init ```
Docker
A Docker image is available with demos and headless VTK display configured:
```bash
Pull image
docker pull donishadsmith/neurocaps && docker tag donishadsmith/neurocaps neurocaps
Run interactive bash
docker run -it neurocaps
Run Jupyter Notebook
docker run -it -p 9999:9999 neurocaps notebook ```
Features
NeuroCAPs is built around two main classes (TimeseriesExtractor and CAP) and includes several
features to perform the complete CAPs workflow from postprocessing to visualizations.
Notable features includes:
| Component | Key Features |
| -------- | ------------|
| Timeseries Extraction (TimeseriesExtractor) |
- supports Schaefer, AAL, and deterministic custom parcellations
- performs nuisance regression and motion scrubbing
- reports quality control based on framewise displacement
Important: Optimized for BIDS-compliant data preprocessed with fMRIPrep and assumes data is BIDs compliant. Refer to NeuroCAPs' BIDS Structure and Entities Documentation for additional information.
CAP) | - performs k-means clustering
- finds the optimal number of clusters (silhouette, elbow, variance ratio, Davies-Bouldin)
- computes temporal dynamic metrics (temporal fraction, persistence, counts, transition frequency and probabilities) [^2] [^3]
- converts CAPs to NIfTI images
- creates visualizations (heatmaps, outer products, surface plots, correlation matrices, cosine similarity radar plots [^4] [^5]).
- plots transition matrices
- merges timeseries data across tasks or sessions [^6]
- generates and fetches custom parcellation approaches
Full details for every function and parameter are available in the API Documentation.
Quick Start
The following code demonstrates basic usage of NeuroCAPs (with simulated data) to perform CAPs analysis. A version of this example using real data from OpenNeuro is available on the readthedocs. Additional tutorials and interactive demonstrations are also available.
- Extract timeseries data ```python import numpy as np from neurocaps.extraction import TimeseriesExtractor from neurocaps.utils import simulatebidsdataset
Set seed
np.random.seed(0)
Generate a BIDS directory with fMRIPrep derivatives
bidsroot = simulatebidsdataset(nsubs=3, nruns=1, nvolumes=100, task_name="rest")
Using Schaefer, one of the default parcellation approaches
parcelapproach = {"Schaefer": {"nrois": 100, "yeo_networks": 7}}
List of fMRIPrep-derived confounds for nuisance regression
acompcornames = [f"acompcor0{i}" for i in range(5)] confoundnames = ["cosine", "trans", "rot*", *acompcornames]
Initialize extractor with signal cleaning parameters
extractor = TimeseriesExtractor( space="MNI152NLin2009cAsym", parcelapproach=parcelapproach, confoundnames=confoundnames, standardize=False, # Run discarded if more than 30% of volumes exceed FD threshold fdthreshold={"threshold": 0.90, "outlierpercentage": 0.30}, )
Extract preprocessed BOLD data
extractor.getbold(bidsdir=bidsroot, task="rest", tr=2, ncores=1, verbose=False)
Check QC information
qcdf = extractor.reportqc()
print(qc_df)
```

- Use k-means clustering to identify the optimal number of CAPs from the data using a heuristic ```python from neurocaps.analysis import CAP from neurocaps.utils import PlotDefaults
Initialize CAP class
capanalysis = CAP(parcelapproach=extractor.parcel_approach, groups=None)
plotkwargs = {**PlotDefaults.getcaps(), "figsize": (4, 3), "step": 2}
Find optimal CAPs (2-20) using silhouette method; results are stored
capanalysis.getcaps( subjecttimeseries=extractor.subjecttimeseries, nclusters=range(2, 21), standardize=True, clusterselectionmethod="silhouette", maxiter=500, ninit=10, showfigs=True, **plotkwargs, ) ``` <img src="paper/silhouetteplot.png" alt="Silhouette Score Plot." style="width:46%; height:auto;">
- Compute temporal dynamic metrics for downstream statistical analyses
python # Calculate temporal fraction of each CAP metric_dict = cap_analysis.calculate_metrics( extractor.subject_timeseries, metrics=["temporal_fraction"] ) print(metric_dict["temporal_fraction"])

Note that CAP-1 is the dominant brain state across subjects (highest frequency).
- Visualize CAPs ```python # Create surface and radar plots for each CAP surface_kwargs = {**PlotDefaults.caps2surf(), "layout": "row", "size": (500, 100)}
radarkwargs = {**PlotDefaults.caps2radar(), "height": 400, "width": 485} radarkwargs["radialaxis"] = {"range": [0, 0.4], "tickvals": [0.1, "", "", 0.4]} radar_kwargs["legend"] = {"yanchor": "top", "y": 0.75, "x": 1.15}
capanalysis.caps2surf(**surfacekwargs).caps2radar(**radarkwargs) ``` <img src="paper/cap1_surface.png" alt="CAP-1 Surface Image." style="width:46%; height:auto;">



Radar plots show network alignment (measured by cosine similarity): "High Amplitude" represents alignment to activations (> 0), "Low Amplitude" represents alignment to deactivations (< 0).
Each CAP can be characterized using either maximum alignment (CAP-1: Vis+/SomMot-; CAP-2: SomMot+/Vis-) or predominant alignment ("High Amplitude" − "Low Amplitude"; CAP-1: SalVentAttn+/SomMot-; CAP-2: SomMot+/SalVentAttn-).
```python import pandas as pd
for capname in capanalysis.caps["All Subjects"]: df = pd.DataFrame(capanalysis.cosinesimilarity["All Subjects"][capname]) df["Net"] = df["High Amplitude"] - df["Low Amplitude"] df["Regions"] = capanalysis.cosinesimilarity["All Subjects"]["Regions"] print(f"{capname}:", "\n", df, "\n") ``` CAP-1:

CAP-2:

Note: For information about logging, refer to NeuroCAPs' Logging Guide.
Citing
If you would like to cite NeuroCAPs, you can use:
Smith, D., (2025). NeuroCAPs: A Python Package for Performing Co-Activation Patterns Analyses on Resting-State and Task-Based fMRI Data. Journal of Open Source Software, 10(112), 8196, https://doi.org/10.21105/joss.08196
Reporting Issues
Bug reports, feature requests, and documentation enhancements can be reported using the templates offered when creating a new issue in the issue tracker.
Contributing
Please refer the contributing guidelines on how to contribute to NeuroCAPs.
Acknowledgements
NeuroCAPs relies on several popular data processing, machine learning, neuroimaging, and visualization packages.
Additionally, some foundational concepts in this package take inspiration from features or design patterns implemented in other neuroimaging Python packages, specifically:
- mtorabi59's pydfc, a toolbox that allows comparisons among several popular dynamic functionality methods.
- 62442katieb's IDConn, a pipeline for assessing individual differences in resting-state or task-based functional connectivity.
References
[^1]: Liu, X., Chang, C., & Duyn, J. H. (2013). Decomposition of spontaneous brain activity into distinct fMRI co-activation patterns. Frontiers in Systems Neuroscience, 7. https://doi.org/10.3389/fnsys.2013.00101
[^2]: Liu, X., Zhang, N., Chang, C., & Duyn, J. H. (2018). Co-activation patterns in resting-state fMRI signals. NeuroImage, 180, 485–494. https://doi.org/10.1016/j.neuroimage.2018.01.041
[^3]: Yang, H., Zhang, H., Di, X., Wang, S., Meng, C., Tian, L., & Biswal, B. (2021). Reproducible coactivation patterns of functional brain networks reveal the aberrant dynamic state transition in schizophrenia. NeuroImage, 237, 118193. https://doi.org/10.1016/j.neuroimage.2021.118193
[^4]: Zhang, R., Yan, W., Manza, P., Shokri-Kojori, E., Demiral, S. B., Schwandt, M., Vines, L., Sotelo, D., Tomasi, D., Giddens, N. T., Wang, G., Diazgranados, N., Momenan, R., & Volkow, N. D. (2023). Disrupted brain state dynamics in opioid and alcohol use disorder: attenuation by nicotine use. Neuropsychopharmacology, 49(5), 876–884. https://doi.org/10.1038/s41386-023-01750-w
[^5]: Ingwersen, T., Mayer, C., Petersen, M., Frey, B. M., Fiehler, J., Hanning, U., Kühn, S., Gallinat, J., Twerenbold, R., Gerloff, C., Cheng, B., Thomalla, G., & Schlemm, E. (2024). Functional MRI brain state occupancy in the presence of cerebral small vessel disease — A pre-registered replication analysis of the Hamburg City Health Study. Imaging Neuroscience, 2, 1–17. https://doi.org/10.1162/imaga00122
[^6]: Kupis, L., Romero, C., Dirks, B., Hoang, S., Parladé, M. V., Beaumont, A. L., Cardona, S. M., Alessandri, M., Chang, C., Nomi, J. S., & Uddin, L. Q. (2020). Evoked and intrinsic brain network dynamics in children with autism spectrum disorder. NeuroImage: Clinical, 28, 102396. https://doi.org/10.1016/j.nicl.2020.102396
Owner
- Name: Donisha Smith
- Login: donishadsmith
- Kind: user
- Repositories: 5
- Profile: https://github.com/donishadsmith
Currently, I am a Cognitive Neuroscience PhD student at Florida International University.
JOSS Publication
NeuroCAPs: A Python Package for Performing Co-Activation Patterns Analyses on Resting-State and Task-Based fMRI Data
Authors
Tags
neuroimaging fMRI dynamic functional connectivity co-activation patternsGitHub Events
Total
- Create event: 163
- Issues event: 15
- Release event: 105
- Watch event: 7
- Delete event: 96
- Issue comment event: 49
- Push event: 1,436
- Pull request review event: 1
- Pull request event: 89
- Fork event: 2
Last Year
- Create event: 163
- Issues event: 15
- Release event: 105
- Watch event: 7
- Delete event: 96
- Issue comment event: 49
- Push event: 1,436
- Pull request review event: 1
- Pull request event: 89
- Fork event: 2
Issues and Pull Requests
Last synced: 4 months ago
All Time
- Total issues: 9
- Total pull requests: 48
- Average time to close issues: 16 days
- Average time to close pull requests: 1 day
- Total issue authors: 3
- Total pull request authors: 3
- Average comments per issue: 0.11
- Average comments per pull request: 0.5
- Merged pull requests: 28
- Bot issues: 1
- Bot pull requests: 27
Past Year
- Issues: 9
- Pull requests: 48
- Average time to close issues: 16 days
- Average time to close pull requests: 1 day
- Issue authors: 3
- Pull request authors: 3
- Average comments per issue: 0.11
- Average comments per pull request: 0.5
- Merged pull requests: 28
- Bot issues: 1
- Bot pull requests: 27
Top Authors
Issue Authors
- donishadsmith (7)
- litter-bee (1)
- renovate[bot] (1)
Pull Request Authors
- renovate[bot] (27)
- donishadsmith (20)
- yibeichan (1)
Top Labels
Issue Labels
Pull Request Labels
Packages
- Total packages: 1
-
Total downloads:
- pypi 1,721 last-month
- Total dependent packages: 0
- Total dependent repositories: 0
- Total versions: 212
- Total maintainers: 1
pypi.org: neurocaps
Co-activation Patterns (CAPs) Python package
- Homepage: https://neurocaps.readthedocs.io
- Documentation: https://neurocaps.readthedocs.io/
- License: mit
-
Latest release: 1.0.0
published over 1 year ago
Rankings
Maintainers (1)
Dependencies
- nibabel *
- pybids *
- actions/checkout v3 composite
- actions/setup-python v2 composite
