Agent skill

Nilearn

by cosanlab in cosanlab/nltools

Comprehensive nilearn (neuroimaging) API reference and best practices.

MITAuto-check passedData & Analytics

Install Nilearn

skills CLI
$ npx skills add cosanlab/nltools --skill nilearn -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install cosanlab/nltools nilearn --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/cosanlab/nltools.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.claude/skills/nilearn .claude/skills/nilearn && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
nilearn
GitHub stars
131
Token cost
~3.3k tokens
SKILL.md length
732 words
Files
18 (incl. references)
Skills in repo
3
Repo updated
First seen
Licence
MIT

At a glance

Comprehensive nilearn (neuroimaging) API reference and best practices.

  • Works in 4 steps: fMRIPrep → first-level GLM → Functional connectivity (multi-subject) → Decoding / MVPA → …
  • Debugging code that uses nilearn for fMRI analysis
  • SKILL.md covers When to use this skill, How this skill is organized, Mental model and Picker: which submodule for…, plus 4 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Nilearn is an agent skill from cosanlab/nltools. Comprehensive nilearn (neuroimaging) API reference and best practices. Use when writing, reviewing, or debugging code that uses nilearn for fMRI analysis, GLM modeling, brain plotting, masking, decoding, connectivity, or surface analysis. Per-submodule references live under references/ — load the relevant file (e.g. references/glm.md) for full inventories, signatures, and patterns.

Its SKILL.md is about 3.3k tokens, which your agent loads only when the skill is triggered. The skill folder holds 18 other files, including reference files (for example `references/connectome.md`, `references/datasets.md` and `references/decoding.md`).

It sits in Data & Analytics, covering Data visualization. It works with Python. The repository describes itself as: Python toolbox for analyzing imaging data. The licence is MIT.

When your agent uses it

  • Debugging code that uses nilearn for fMRI analysis
  • Surface analysis

Example prompts

  • “/nilearn”

Requirements

  • Python 3

Workflow steps

4 steps, taken from the step headings in SKILL.md.

  1. fMRIPrep → first-level GLM
  2. Functional connectivity (multi-subject)
  3. Decoding / MVPA
  4. Surface analysis (modern API)

What it can do on your machine

Read from SKILL.md and the folder at commit cbc9551. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are python).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Nilearn loads about 3.3k tokens when it runs, and up to ~35k if it reads all its reference files. Until then it costs about 99 tokens; SKILL.md has 732 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~99
When it runs · the whole SKILL.md, loaded when a task matches
~3.3k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~35k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from cosanlab/nltools at commit cbc9551, republished under its MIT licence (© cosanlab). 732 words, ~3,323 tokens.

Download SKILL.mdSave it as .claude/skills/nilearn/SKILL.md (or your agent's skills folder). This skill also uses 17 other files; get the full folder from GitHub.
name
nilearn
description
Comprehensive nilearn (neuroimaging) API reference and best practices. Use when writing, reviewing, or debugging code that uses nilearn for fMRI analysis, GLM modeling, brain plotting, masking, decoding, connectivity, or surface analysis. Per-submodule references live under `references/` — load the relevant file (e.g. `references/glm.md`) for full inventories, signatures, and patterns.

Nilearn

Statistical and machine-learning tools for neuroimaging. Every masker and model class follows scikit-learn's fit / transform / predict / fit_transform API.

When to use this skill

  • Writing, reviewing, or debugging any code that imports nilearn.
  • Picking the right masker, atlas, GLM noise model, or decoder.
  • Building a first-level or second-level GLM, connectivity pipeline, MVPA decoder, or surface workflow.
  • Visualizing brain data (slices, glass brain, surface, interactive HTML).

How this skill is organized

SKILL.md (this file) is a lean overview, picker tables, common workflows, and cross-cutting gotchas. For full per-submodule API surface — every public class, every function, full constructor signatures, post-fit attributes — load the relevant file from references/.

SubmoduleReferenceCovers
nilearn.connectomereferences/connectome.mdConnectivityMeasure, sparse covariance, vec/matrix utils
nilearn.datasetsreferences/datasets.mdAll fetch_atlas_*, fetch_* example data, load_mni152_*, load_fsaverage
nilearn.decodingreferences/decoding.mdDecoder, FREM*, SpaceNet*, SearchLight
nilearn.decompositionreferences/decomposition.mdCanICA, DictLearning
nilearn.exceptionsreferences/exceptions.mdMaskWarning, DimensionError, MeshDimensionError, etc.
nilearn.glmreferences/glm.mdFirstLevelModel, SecondLevelModel, design matrices, contrasts, thresholding
nilearn.imagereferences/image.mdload_img, resample_*, smooth_img, math_img, clean_img, etc.
nilearn.interfacesreferences/interfaces.mdfmriprep load_confounds, BIDS helpers, FSL helpers
nilearn.maskersreferences/maskers.mdNiftiMasker, NiftiLabelsMasker, NiftiMapsMasker, NiftiSpheresMasker, all Multi* and Surface* variants
nilearn.maskingreferences/masking.mdcompute_*_mask, apply_mask, unmask, intersect_masks
nilearn.mass_univariatereferences/mass_univariate.mdpermuted_ols (TFCE / cluster-mass / cluster-size)
nilearn.plottingreferences/plotting.mdAll plot_*, view_*, find_*, slicer/projector classes
nilearn.regionsreferences/regions.mdRegionExtractor, Parcellations, connected_regions, signal/img helpers
nilearn.reportingreferences/reporting.mdget_clusters_table, HTMLReport, model.generate_report()
nilearn.signalreferences/signal.mdclean, butterworth, high_variance_confounds
nilearn.surfacereferences/surface.mdSurfaceImage, PolyMesh, vol_to_surf
nilearn.utilsreferences/utils.mdEstimator/function introspection helpers

Mental model

raw NIfTI ──┐
            │  masker (extract signals)        masker.transform(img) → (T × features)
atlas ──────┘
                 │
                 ▼
       sklearn-style model (fit / predict / score)
                 │
                 ▼
       img back out via masker.inverse_transform(weights) → Niimg

Three things to choose every time:

  1. Masker — what region (whole brain, atlas, spheres, surface)? See references/maskers.md.
  2. Cleaning params — standardize, detrend, high_pass, low_pass, t_r, confounds, sample_mask. Order is always: detrend → filter → confound removal → standardize.
  3. Model — GLM (glm.FirstLevelModel), MVPA (decoding.Decoder), connectivity (connectome.ConnectivityMeasure), parcellation (regions.Parcellations), or decomposition (decomposition.CanICA / DictLearning).

Picker: which submodule for which task?

TaskSubmodule(s)
Run a task-fMRI GLMglm + interfaces.fmriprep (confounds) + maskers (optional)
Group-level analysisglm.second_level + mass_univariate (permutation)
Multiple-comparison correctionglm.threshold_stats_img, mass_univariate.permuted_ols (TFCE)
Functional connectivitymaskers (extract ROI signals) → connectome.ConnectivityMeasure
MVPA / decodingdecoding.Decoder (or FREM*, SpaceNet*, SearchLight)
ICA / dictionary learningdecomposition.CanICA / DictLearning
Data-driven parcellationregions.Parcellations
Brain visualization (volume)plotting.plot_stat_map, plot_glass_brain, view_img
Brain visualization (surface)plotting.plot_img_on_surf, view_img_on_surf
Project volume → surfacesurface.vol_to_surf or SurfaceImage.from_volume
Get an atlas / templatedatasets.fetch_atlas_* / datasets.load_mni152_*
Image arithmetic / resample / smoothimage.math_img, resample_img, smooth_img
Build a maskmasking.compute_brain_mask, compute_epi_mask
Load fMRIPrep confoundsinterfaces.fmriprep.load_confounds

Picker: which masker?

MaskerInputUse case
NiftiMasker3D/4D NIfTIWhole-brain voxel-level (decoding, searchlight, RSA)
NiftiLabelsMasker3D integer atlasROI-based with discrete parcellation
NiftiMapsMasker4D probabilistic mapsICA components, soft/probabilistic atlases
NiftiSpheresMaskerMNI coordinatesSeed-based connectivity, literature ROIs
MultiNiftiMasker (and MultiLabels/MultiMaps/MultiSpheres)Multiple subjectsSame as above, parallel across subjects
SurfaceMaskerSurfaceImageSurface-based vertex-level
SurfaceLabelsMaskerSurface parcellationSurface ROI extraction
SurfaceMapsMaskerSurface probability mapsSurface probabilistic atlas extraction

Full constructor signatures, post-fit attributes, and clean_args/mask_args semantics: references/maskers.md.

Common workflows

Show full SKILL.md (293 more words)Show less
1. fMRIPrep → first-level GLM
python
from nilearn.interfaces.fmriprep import load_confounds
from nilearn.glm.first_level import FirstLevelModel
from nilearn.glm import threshold_stats_img

confounds, sample_mask = load_confounds(
    fmri_img, strategy=('motion', 'high_pass', 'wm_csf', 'scrub'),
    motion='full', scrub=5,
)

flm = FirstLevelModel(t_r=2.0, hrf_model='glover', noise_model='ar1',
                      smoothing_fwhm=6, high_pass=0.01, mask_img=mask)
flm.fit(fmri_img, events=events_df, confounds=confounds, sample_masks=sample_mask)

z_map = flm.compute_contrast('active - rest', output_type='z_score')
thresholded, thresh = threshold_stats_img(
    z_map, alpha=0.05, height_control='fdr', cluster_threshold=10,
)

Details: references/glm.md, references/interfaces.md.

2. Functional connectivity (multi-subject)
python
from nilearn.maskers import NiftiLabelsMasker
from nilearn.connectome import ConnectivityMeasure
from nilearn.datasets import fetch_atlas_schaefer_2018

atlas = fetch_atlas_schaefer_2018(n_rois=200)
masker = NiftiLabelsMasker(labels_img=atlas.maps, labels=atlas.labels,
                           standardize='zscore_sample', memory='nilearn_cache')

all_ts = [masker.fit_transform(img, confounds=conf) for img, conf in zip(imgs, confs)]

conn = ConnectivityMeasure(kind='tangent', vectorize=True)
features = conn.fit_transform(all_ts)  # (n_subjects, n_features) — ready for sklearn

Details: references/connectome.md, references/maskers.md.

3. Decoding / MVPA
python
from nilearn.decoding import Decoder

decoder = Decoder(
    estimator='svc', mask=mask_img, cv=5,
    screening_percentile=5, scoring='accuracy',
    smoothing_fwhm=4, standardize=True,
)
decoder.fit(fmri_imgs, y=labels)
print(decoder.cv_scores_)
weight_img = decoder.coef_img_['face']

Details: references/decoding.md.

4. Surface analysis (modern API)
python
from nilearn.surface import SurfaceImage
from nilearn.datasets import load_fsaverage
from nilearn.maskers import SurfaceMasker, SurfaceLabelsMasker

fsaverage5 = load_fsaverage('fsaverage5')                          # PolyMesh
surf_img   = SurfaceImage.from_volume(mesh=fsaverage5, volume_img=fmri_4d)

masker  = SurfaceMasker()
signals = masker.fit_transform(surf_img)

Details: references/surface.md, references/maskers.md.

Cross-cutting gotchas

These apply across submodules. Per-submodule gotchas live in each references/<sub>.md.

  1. standardize=True ≠ 'zscore_sample'. True maps to 'zscore' (divides by N). Use 'zscore_sample' (divides by N−1) for most analyses.

  2. Events DataFrame column names are strict: onset (sec), duration (sec), trial_type (str). Optional: modulation. Other column names are silently ignored.

  3. threshold_stats_img returns a tuple (thresholded_img, threshold_value) — always unpack.

  4. load_confounds returns a tuple (confounds_df, sample_mask). Pass sample_mask to flm.fit(sample_masks=...).

  5. fetch_* vs load_*. fetch_* downloads from the internet on first call (cached at ~/nilearn_data, override with data_dir=). load_* loads bundled data instantly — no network.

  6. Surface API: old vs new. fetch_surf_fsaverage() returns the old dict format. load_fsaverage() returns the new PolyMesh. Use the new API; only the new API works with SurfaceImage/SurfaceMasker.

  7. make_glm_report is deprecated. Use model.generate_report(contrasts=...) instead.

  8. get_data(img) returns a copy. For read-only access, use img.get_fdata() (nibabel) directly.

  9. n_jobs=-1 caution. Can hang or OOM on large images. Start with n_jobs=1, increase carefully.

  10. Default cmaps changed in v0.13: 'RdBu_r' for diverging stat maps, 'gray' for anat, 'inferno' for sequential.

  11. Resampling interpolation depends on image type. Use 'nearest' for discrete label/ROI images, 'continuous' (default) for stat maps and continuous data.

  12. Processing order in signal.clean and maskers: detrend → filter → remove confounds → standardize. Filters are applied to confounds too.

  13. clean_img vs signal.clean. clean_img takes 4D NIfTI; signal.clean takes 2D (timepoints, features) arrays. Maskers use signal.clean internally.

  14. Memory/caching. All maskers and models accept memory= for joblib caching. Use it for any expensive op:

    python
    masker = NiftiMasker(memory='nilearn_cache', memory_level=1)
  15. force_resample default changed. In v0.13+, image.resample_img defaults to force_resample=True.

Quick imports cheat-sheet

python
# Maskers
from nilearn.maskers import (
    NiftiMasker, NiftiLabelsMasker, NiftiMapsMasker, NiftiSpheresMasker,
    MultiNiftiMasker, SurfaceMasker, SurfaceLabelsMasker, SurfaceMapsMasker,
)

# GLM
from nilearn.glm.first_level import FirstLevelModel, make_first_level_design_matrix, first_level_from_bids
from nilearn.glm.second_level import SecondLevelModel, non_parametric_inference
from nilearn.glm import threshold_stats_img, fdr_threshold, expression_to_contrast_vector

# Image / signal / masking
from nilearn import image
from nilearn.signal import clean, butterworth, high_variance_confounds
from nilearn import masking

# Connectivity / decoding / decomposition
from nilearn.connectome import ConnectivityMeasure, sym_matrix_to_vec, vec_to_sym_matrix
from nilearn.decoding import Decoder, DecoderRegressor, SearchLight, FREMClassifier, SpaceNetClassifier
from nilearn.decomposition import CanICA, DictLearning

# Regions / surface
from nilearn.regions import RegionExtractor, Parcellations, connected_regions
from nilearn.surface import SurfaceImage, PolyMesh, vol_to_surf

# Plotting
from nilearn import plotting
from nilearn.plotting import plot_stat_map, plot_glass_brain, plot_img_on_surf, view_img

# Datasets / interfaces / mass-univariate / reporting
from nilearn.datasets import (
    load_mni152_template, load_mni152_brain_mask, load_fsaverage,
    fetch_atlas_schaefer_2018, fetch_atlas_harvard_oxford, fetch_atlas_difumo,
    fetch_haxby, fetch_adhd, fetch_development_fmri,
)
from nilearn.interfaces.fmriprep import load_confounds, load_confounds_strategy
from nilearn.interfaces.bids import get_bids_files, parse_bids_filename
from nilearn.mass_univariate import permuted_ols
from nilearn.reporting import get_clusters_table

© cosanlab, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 17 other files (references) in .claude/skills/nilearn of cosanlab/nltools.

  • SKILL.md
  • references/connectome.md
  • references/datasets.md
  • references/decoding.md
  • references/decomposition.md
  • references/exceptions.md
  • references/glm.md
  • references/image.md
  • references/interfaces.md
  • references/maskers.md
  • references/masking.md
  • references/mass_univariate.md
  • references/plotting.md
  • references/regions.md
  • references/reporting.md
  • references/signal.md
  • references/surface.md
  • references/utils.md

Open the folder on GitHubat commit cbc9551

Compare with similar skills

Nilearn next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Nilearn compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Nilearn this skillcosanlab/nltools131—~3.3kAutomated safety check: PassMIT
Academic Figurejoshua-zyy/academic-paper-writer115—~816Automated safety check: PassMIT
Scientific Schematicsjimmc414/Kosmos595—~16kAutomated safety check: NotesNone
Microsim Generatordmccreary/ibook-skills105—~11kAutomated safety check: PassNone
Release Evidence WorkflowAli-Marandi/ClimateDataAnalyzer107—~1.6kAutomated safety check: PassMIT
Scientific Figure MakingChenLiu-1996/figures4papers8.3k—~557Automated safety check: PassCustom licence

Similar skills

  • Academic Figure

    joshua-zyy/academic-paper-writer

    Create, revise, or audit academic data/result figures for CS/AI/ML papers.

    115 GitHub stars~816 tokensUpdated 4 days ago
    Data & AnalyticsAuto-check passed
  • Scientific Schematics

    jimmc414/Kosmos

    Create publication-quality scientific diagrams, flowcharts, and schematics using Python (graphviz, matplotlib, schemdraw, networkx).

    595 GitHub stars~16k tokensUpdated today
    Data & AnalyticsAuto-check: notes
  • Microsim Generator

    dmccreary/ibook-skills

    Creates interactive educational MicroSims, routing to the best-matched generator - p5.js, Chart.js, Plotly, Mermaid, vis-network, timelines, maps, Venn, causal-loop/feedback-loop diagrams (CLD)…

    105 GitHub stars~11k tokensUpdated today
    Data & AnalyticsAuto-check passed
  • Release Evidence Workflow

    Ali-Marandi/ClimateDataAnalyzer

    Build an auditable release-evidence workflow for a desktop or packaged application.

    107 GitHub stars~1.6k tokensUpdated 1 mo ago
    Data & AnalyticsAuto-check passed
  • Scientific Figure Making

    ChenLiu-1996/figures4papers

    Covers publication-ready matplotlib figures for academic papers, slides, and reports—bars, trends, scatter, heatmaps, and multi-panel layouts—with this…

    8.3k GitHub stars~557 tokensUpdated 3 days ago
    Data & AnalyticsAuto-check passed
  • Plot From Image

    Trae1ounG/paper-plot-skills

    Reproduce any academic paper figure from an uploaded image using accumulated style experience.

    869 GitHub starsUsed in 1 repo~868 tokens
    Data & AnalyticsAuto-check passed

More from cosanlab/nltools

  • Marimo Pair

    cosanlab/nltools

    Work inside a running marimo notebook's kernel — execute code, create cells, and build a notebook as an artifact.

    131 GitHub starsUsed in 1 repo~3k tokens
    Auto-check passed
  • Marimo Notebook

    cosanlab/nltools

    Write a marimo notebook in a Python file in the right format.

    131 GitHub starsUsed in 4 repos~2.1k tokens
    Auto-check passed

Works with

Questions about Nilearn

What does Nilearn do?

Comprehensive nilearn (neuroimaging) API reference and best practices. Nilearn is an agent skill from cosanlab/nltools. Comprehensive nilearn (neuroimaging) API reference and best practices.

When should I use Nilearn?

Nilearn fits situations like: debugging code that uses nilearn for fMRI analysis; surface analysis.

How do I install Nilearn in Claude Code?

Run `npx skills add cosanlab/nltools --skill nilearn -a claude-code`. Or copy the skill folder (.claude/skills/nilearn in cosanlab/nltools) into .claude/skills/nilearn in your project. Claude Code loads it when a task matches its description.

How do I install Nilearn in Codex?

Run `npx skills add cosanlab/nltools --skill nilearn -a codex`. Or copy the skill folder (.claude/skills/nilearn in cosanlab/nltools) into .agents/skills/nilearn in your project. Codex loads it when a task matches its description.

Can I use Nilearn in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add cosanlab/nltools --skill nilearn -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/nilearn, .gemini/skills/nilearn, .github/skills/nilearn and .opencode/skills/nilearn in your project.

What does Nilearn need to run?

SKILL.md names no scripts, command-line tools or credentials: Nilearn is instructions for the agent only. Our summary lists: Python 3.

Does Nilearn access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Nilearn safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Nilearn use?

Nilearn is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Nilearn use?

About 3.3k tokens (SKILL.md is roughly 13k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 32k tokens, read only when the agent opens those files.

What are the alternatives to Nilearn?

Skills that share tags, products or a category with Nilearn: Academic Figure (joshua-zyy/academic-paper-writer, 115 stars), Scientific Schematics (jimmc414/Kosmos, 595 stars), Microsim Generator (dmccreary/ibook-skills, 105 stars) and Release Evidence Workflow (Ali-Marandi/ClimateDataAnalyzer, 107 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Nilearn?

cosanlab (a GitHub organization) maintains it in cosanlab/nltools, which has 131 GitHub stars. The repository holds 3 skills in this directory. The repository was last updated on October 8, 2026.

Source: cosanlab/nltools on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.