# Nilearn

> Nilearn

- Skill: `hughyau/nilearn` (Agent Skill, multi-file: 394 files)
- Install (CLI): `npx skillmds@latest add hughyau/nilearn`
- Raw SKILL.md: https://api.skillmd.com/api/skills/hughyau/nilearn/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: HughYau (https://skillmd.com/u/hughyau)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/hughyau/nilearn

---


# Nilearn

Nilearn provides neuroimaging-focused building blocks on top of NumPy/scikit-learn for image processing, statistical modeling, decoding, and connectivity workflows.

## Version

<!-- built against: nilearn==0+unknown -->
Built against: `nilearn==0+unknown`
Python: `3.13`
> Source checkout uses dynamic versioning; see `assets/version.txt` for commit and environment details.

## Scope

This skill intentionally focuses on high-usage workflows across `datasets`, `image`, `maskers`, `glm`, `decoding`, `connectome`, `plotting`, `surface`, and `interfaces`.

Out of scope in this skill: private `_utils`, low-level test helpers, and exhaustive coverage of every plotting backend edge case.

Coverage profile: `hybrid` (workflow references + dictionary lookup assets).

## Environment Gate

Install policy and environment decision are recorded in `assets/version.txt`.
Current build used `install_permission: no`, so runtime claims are tagged where relevant.

## Installation

```bash
# requires explicit install permission
pip install nilearn

# optional plotting stack for visualization-heavy workflows
pip install "nilearn[plotting]"
```

---

## Datasets and Atlases

```python
# tested against nilearn==0+unknown
try:
    from nilearn import datasets
    template = datasets.load_mni152_template()
    print(template.shape)
except Exception as e:
    print(f"[UNVERIFIED: install denied in selected environment] {type(e).__name__}: {e}")
```

See `references/datasets-and-atlases.md` for fetchers, template loaders, and version-specific dataset deprecations.

---

## Image Manipulation

```python
# tested against nilearn==0+unknown
try:
    import numpy as np
    import nibabel as nib
    from nilearn.image import math_img

    img = nib.Nifti1Image(np.ones((4, 4, 4), dtype=float), np.eye(4))
    doubled = math_img("img * 2", img=img)
    print(doubled.shape)
except Exception as e:
    print(f"[UNVERIFIED: install denied in selected environment] {type(e).__name__}: {e}")
```

See `references/image-manipulation.md` for `smooth_img`, `math_img`, and `resample_to_img` usage and caveats.

---

## Maskers and Signals

```python
# tested against nilearn==0+unknown
try:
    from nilearn.maskers import NiftiMasker
    masker = NiftiMasker(standardize=True, detrend=True)
    print(type(masker).__name__)
except Exception as e:
    print(f"[UNVERIFIED: install denied in selected environment] {type(e).__name__}: {e}")
```

See `references/maskers-and-signals.md` for `NiftiMasker`/`NiftiLabelsMasker` signatures and migration notes.

---

## GLM Modeling

```python
# tested against nilearn==0+unknown
try:
    from nilearn.glm.first_level import FirstLevelModel
    model = FirstLevelModel(t_r=2.0, noise_model="ar1")
    print(type(model).__name__)
except Exception as e:
    print(f"[UNVERIFIED: install denied in selected environment] {type(e).__name__}: {e}")
```

See `references/glm-modeling.md` for `FirstLevelModel`, `SecondLevelModel`, and `threshold_stats_img` behavior.

---

## Decoding and Connectivity

```python
# tested against nilearn==0+unknown
try:
    from nilearn.decoding import Decoder
    from nilearn.connectome import ConnectivityMeasure

    print(Decoder.__name__, ConnectivityMeasure.__name__)
except Exception as e:
    print(f"[UNVERIFIED: install denied in selected environment] {type(e).__name__}: {e}")
```

See `references/decoding-and-connectivity.md` for `Decoder`, `SearchLight`, and `ConnectivityMeasure` parameter patterns.

---

## Plotting and Visualization

```python
# tested against nilearn==0+unknown
try:
    # REQUIRES: pip install "nilearn[plotting]"
    from nilearn.plotting import plot_stat_map, view_img
    print(plot_stat_map.__name__, view_img.__name__)
except Exception as e:
    print(f"[UNVERIFIED: install denied in selected environment] {type(e).__name__}: {e}")
```

See `references/plotting-and-visualization.md` for `plot_img`, `plot_stat_map`, `view_img`, and surface plotting viewers.

---

## Surface Workflows

```python
# tested against nilearn==0+unknown
try:
    from nilearn.surface import vol_to_surf, SurfaceImage
    print(vol_to_surf.__name__, SurfaceImage.__name__)
except Exception as e:
    print(f"[UNVERIFIED: install denied in selected environment] {type(e).__name__}: {e}")
```

See `references/surface-workflows.md` for `vol_to_surf`, mesh/data loaders, and `SurfaceImage` patterns.

---

## Interfaces (BIDS/fMRIPrep)

```python
# tested against nilearn==0+unknown
try:
    from nilearn.interfaces.bids import get_bids_files
    from nilearn.interfaces.fmriprep import load_confounds
    print(get_bids_files.__name__, load_confounds.__name__)
except Exception as e:
    print(f"[UNVERIFIED: install denied in selected environment] {type(e).__name__}: {e}")
```

See `references/interfaces-bids-and-fmriprep.md` for BIDS queries, confounds loading, and `first_level_from_bids` usage.

---

## Verification (Medium+)

```bash
PYTHONPATH="H:\Agent\OpenSciHub\nilearn" python "H:\Agent\OpenSciHub\.opencode\skills\opensci-skill\scripts\verify-snippets.py" --root "H:\Agent\OpenSciHub\.opencode\skills\nilearn" --fail-fast
```

## Dictionary Assets (Hybrid)

Use dictionary assets before source traversal for symbol-level lookup:

1. Query `assets/symbol-index.jsonl` for exact symbol names.
2. Open the matching module card in `assets/symbol-cards/`.
3. Follow `source` anchors in the card only when implementation details are needed.

Primary dictionary entrypoint: `assets/symbol-index.md`.

## Quick Reference

| Function / Class | Purpose |
|-----------------|---------|
| `datasets.load_mni152_template()` | Load canonical skull-stripped MNI template image. |
| `datasets.fetch_atlas_schaefer_2018()` | Download Schaefer atlas files and labels bundle. |
| `image.math_img()` | Apply NumPy expressions directly to image data. |
| `maskers.NiftiMasker` | Fit/apply voxel masks and clean extracted time series. |
| `glm.first_level.FirstLevelModel` | Build subject-level fMRI GLM from events/designs. |
| `decoding.Decoder` | Cross-validated decoding wrapper over Niimg inputs. |
| `connectome.ConnectivityMeasure` | Estimate covariance/correlation/tangent connectomes. |
| `plotting.plot_stat_map()` | Plot thresholded statistical maps on anatomy. |
| `surface.vol_to_surf()` | Project volumetric data onto cortical surfaces. |
| `interfaces.fmriprep.load_confounds()` | Build denoising regressors from fMRIPrep outputs. |

---

## Module Map

| Submodule | Contents | Notes |
|-----------|----------|-------|
| `nilearn.datasets` | built-in samples + remote fetchers | Large public surface |
| `nilearn.image` | math, smoothing, resampling, concat | Core image transforms |
| `nilearn.maskers` | signal extraction transformers | Main user preprocessing entry |
| `nilearn.glm` | first/second-level stats models | Large API with many defaults |
| `nilearn.decoding` | decoders, searchlight, space-net | ML workflows |
| `nilearn.connectome` | connectivity estimators | feature-level connectomes |
| `nilearn.plotting` | static and interactive viewers | Often requires plotting extras |
| `nilearn.surface` | mesh I/O and volume-to-surface projection | Surface-specific data model |
| `nilearn.interfaces` | BIDS and fMRIPrep integration utilities | Pipeline orchestration helpers |

Import style: explicit `__all__` submodule list in `nilearn.__init__` (no top-level star re-export of function symbols).

See `assets/module-map.md` for full inventory and `[LARGE]` module flags.

---

## References

- `references/datasets-and-atlases.md` - template loading, atlas fetchers, and dataset deprecation path.
- `references/image-manipulation.md` - image-level transforms (`smooth_img`, `math_img`, `resample_to_img`).
- `references/maskers-and-signals.md` - masker constructors and signal extraction controls.
- `references/glm-modeling.md` - first/second-level GLM and thresholding function contract.
- `references/decoding-and-connectivity.md` - decoding wrappers and connectivity estimator patterns.
- `references/plotting-and-visualization.md` - stat-map, surface plots, and interactive viewers.
- `references/surface-workflows.md` - surface mesh/data loading and volume projection workflows.
- `references/interfaces-bids-and-fmriprep.md` - BIDS querying, confounds interfaces, and BIDS-to-GLM bootstrapping.
- `assets/symbol-index.md` - dictionary-style module index for broad API lookup.
- `assets/symbol-index.jsonl` - machine-readable symbol registry.
- `assets/symbol-cards/` - per-module symbol cards with signatures and source anchors.

