NetNeuroTools Guide
Purpose
This skill encodes the complete API and recommended workflows for netneurotools, a Python toolbox for network neuroscience developed by the Network Neuroscience Lab (netneurolab). It covers dataset fetching, brain connectivity metrics, network randomization and null models, community detection, spatial autocorrelation statistics, parcellation interface utilities, and cortical/subcortical surface visualization.
When to Use This Skill
Activate when the user:
- Works with brain connectivity matrices (structural or functional)
- Needs network communication metrics (shortest path, navigation, communicability, search information, diffusion efficiency)
- Wants to generate null/surrogate networks preserving degree, strength, or distance distributions
- Performs community detection or consensus clustering on brain networks
- Computes spatial autocorrelation (Moran's I, Geary's C, Lee's L) on parcellated brain data
- Fetches standard neuroimaging templates (fsaverage, fsLR, CIVET, Conte69) or atlases (Schaefer, Cammoun, Pauli)
- Needs to convert between vertex-level and parcel-level brain data
- Visualizes data on cortical surfaces using PyVista or PySurfer
- Mentions netneurotools, netneurolab, or any function from this toolbox
- Performs structure-function coupling, assortativity analysis, or dominance analysis
- Simulates atrophy spreading on brain networks (SIR model)
Reference Files (Progressive Disclosure)
| Topic |
File |
When to Read |
| Datasets |
references/datasets.md |
User fetches templates, atlases, or project datasets |
| Network Metrics |
references/metrics.md |
User computes communication, assortativity, spreading, or statistical network metrics |
| Networks |
references/networks.md |
User builds consensus connectivity, randomizes networks, or thresholds graphs |
| Statistics |
references/stats.md |
User runs permutation tests, correlations, residualization, or dominance analysis |
| Spatial & Modularity |
references/spatial-modularity.md |
User computes spatial autocorrelation or performs community detection |
| Interface & Plotting |
references/interface-plotting.md |
User converts parcels/vertices, handles CIFTI/GIFTI files, or plots on cortical surfaces |
Installation
pip install netneurotools
# For PyVista surface plotting (recommended)
pip install netneurotools[pyvista]
# For PySurfer surface plotting (legacy)
pip install netneurotools[pysurfer]
# For numba acceleration
pip install netneurotools[numba]
Core dependencies: numpy>=1.16, scipy>=1.4.0, scikit-learn, matplotlib, nibabel>=3.0.0, nilearn, bctpy, tqdm, neuromaps
Overview Pipeline
1. Fetch data --> netneurotools.datasets (templates, atlases, connectomes)
2. Build networks --> netneurotools.networks (consensus, thresholding)
3. Analyze metrics --> netneurotools.metrics (communication, assortativity)
4. Null models --> netneurotools.networks (randomization, surrogates)
5. Statistics --> netneurotools.stats (permutation tests, dominance)
6. Spatial stats --> netneurotools.spatial (Moran's I, Geary's C, Lee's L)
7. Modularity --> netneurotools.modularity (consensus clustering)
8. Visualize --> netneurotools.plotting (cortical surfaces, heatmaps)
Quick Start
Fetch Atlas and Template
from netneurotools.datasets import fetch_schaefer2018, fetch_fsaverage_curated
# Fetch Schaefer 400-parcel atlas in fsaverage space
parc = fetch_schaefer2018('fsaverage')['400Parcels7Networks']
# parc is a SURFACE namedtuple with fields .L and .R
# Fetch curated fsaverage surfaces
surfaces = fetch_fsaverage_curated('fsaverage5')
# surfaces has keys: 'white', 'pial', 'inflated', 'sphere', 'medial', 'sulc', 'vaavg'
# Each value is a SURFACE namedtuple with fields .L and .R
Consensus Functional Connectivity
from netneurotools.networks import func_consensus
import numpy as np
# data: (N_nodes, T_timepoints, S_subjects) array
consensus = func_consensus(data, n_boot=1000, ci=95, seed=42)
Community Detection
from netneurotools.modularity import consensus_modularity
import numpy as np
# adjacency: (N, N) non-negative connectivity matrix
consensus, Q_all, zrand_all = consensus_modularity(
adjacency, gamma=1.5, repeats=100, seed=1234
)
Generate Distance-Preserving Surrogates
from netneurotools.networks import match_length_degree_distribution
newB, newW, nr = match_length_degree_distribution(
W, D, nbins=10, nswap=1000, seed=42
)
Permutation Test for Correlation
from netneurotools.stats import permtest_pearsonr, make_correlated_xy
x, y = make_correlated_xy(corr=0.3, size=100, seed=42)
r, p = permtest_pearsonr(x, y, n_perm=5000, seed=42)
Spatial Autocorrelation
from netneurotools.spatial import morans_i
I = morans_i(annotation_vector, spatial_weight_matrix)
Plot on Cortical Surface (PyVista)
from netneurotools.plotting import pv_plot_surface
import numpy as np
data_L = np.random.random((10242,))
data_R = np.random.random((10242,))
pl = pv_plot_surface(
(data_L, data_R),
template="fsaverage5",
surf="inflated",
cmap="viridis",
lighting_style="plastic",
jupyter_backend="static",
)
Plot Parcellated Data (Shortcut)
from netneurotools.plotting import pv_plot_parcellated_data
import numpy as np
data = np.random.rand(400)
pl = pv_plot_parcellated_data(data, 'schaefer400x7', template='fsaverage')
Key Data Structures
| Structure |
Description |
Fields |
SURFACE |
namedtuple for hemisphere file pairs |
.L, .R (left/right hemisphere paths) |
sklearn.utils.Bunch |
Dict-like object returned by fetch functions |
Varies per function |
FREESURFER_IGNORE |
Labels to ignore in FreeSurfer parcellations |
["unknown", "corpuscallosum", "Background+FreeSurfer_Defined_Medial_Wall"] |
PARCIGNORE |
Labels to ignore in parcellation operations |
["unknown", "corpuscallosum", "Background+FreeSurfer_Defined_Medial_Wall", "???", "Unknown", "Medial_wall", "Medial wall", "medial_wall"] |
Core Modules Quick Reference
| Module |
Key Functions |
Purpose |
datasets |
fetch_fsaverage, fetch_schaefer2018, fetch_cammoun2012, fetch_conte69, fetch_famous_gmat |
Fetch templates, atlases, connectomes |
metrics |
distance_wei_floyd, navigation_wu, communicability_wei, search_information, mean_first_passage_time, assortativity_und, simulate_atrophy |
Network communication and properties |
networks |
func_consensus, struct_consensus, match_length_degree_distribution, strength_preserving_rand_sa |
Build consensus, generate null models |
stats |
permtest_pearsonr, efficient_pearsonr, residualize, get_dominance_stats |
Statistical testing and regression |
spatial |
morans_i, gearys_c, lees_l, local_morans_i, local_gearys_c, local_lees_l |
Spatial autocorrelation |
modularity |
consensus_modularity, find_consensus, zrand, get_modularity |
Community detection and evaluation |
interface |
vertices_to_parcels, parcels_to_vertices, load_surf_parc_file, deconstruct_cifti |
Format conversion |
plotting |
pv_plot_surface, pv_plot_parcellated_data, pv_plot_subcortex, plot_mod_heatmap |
Visualization |
Common Pitfalls
SURFACE fields are .L and .R, not .lh and .rh. Use surface.L and surface.R to access hemisphere paths.
Weight-to-distance conversion must be done before calling distance_wei_floyd or search_information. Common transform: D = -np.log(W / (np.max(W) + 1)).
Minimum permutation p-value is 1 / (n_perm + 1). With n_perm=1000, the smallest p-value is ~0.001.
consensus_modularity requires non-negative input. Louvain cannot handle negative weights. Set negatives to zero: A[A < 0] = 0.
struct_consensus hemiid encoding: 0 = right hemisphere, 1 = left hemisphere.
pv_plot_surface data format: When hemi='both', vertex_data can be a tuple (left, right) or a single concatenated array. Data length must match template vertex count.
Data directory: All fetch functions default to ~/nnt-data. Override with data_dir= parameter or set NNT_DATA environment variable.
match_length_degree_distribution recommended nswap: Use nswap = nnodes * 20 for adequate randomization.
strength_preserving_rand_sa frac parameter must be between 0 and 1. It controls temperature decrease per annealing stage.
parcels_to_vertices and vertices_to_parcels support .annot, .gii, and .dlabel.nii parcellation files. For .dlabel.nii, pass a single file path; for .annot or .gii, pass a tuple of (left, right) paths.
Numba acceleration is available for spatial stats, weighted correlation, and some metrics. Install numba for significant speedups on large datasets.
Headless rendering with PyVista: set os.environ["VTK_DEFAULT_OPENGL_WINDOW"] = "vtkOSOpenGLRenderWindow" before importing pyvista.
1---2name: netneurotools-guide3description: Domain-validated guidance for network neuroscience analysis using netneurotools: datasets, brain network metrics, connectivity consensus, modularity, spatial statistics, null models, and cortical surface visualization. Use this skill whenever the user works with brain connectivity matrices, connectomes, graph theory on brain networks, parcellated brain data (Schaefer, Cammoun, Desikan-Killiany), cortical surface templates (fsaverage, fsLR, CIVET, Conte69), network communication metrics, null model generation, spatial autocorrelation on brain maps, community detection in connectomes, or surface-based visualization with PyVista/PySurfer. Also trigger when the user mentions netneurotools, netneurolab, structure-function coupling, network neuroscience, brain graph analysis, or needs to fetch neuroimaging atlases and templates.4---56# NetNeuroTools Guide78## Purpose910This skill encodes the complete API and recommended workflows for **netneurotools**, a Python toolbox for network neuroscience developed by the Network Neuroscience Lab (netneurolab). It covers dataset fetching, brain connectivity metrics, network randomization and null models, community detection, spatial autocorrelation statistics, parcellation interface utilities, and cortical/subcortical surface visualization.1112## When to Use This Skill1314Activate when the user:15- Works with brain connectivity matrices (structural or functional)16- Needs network communication metrics (shortest path, navigation, communicability, search information, diffusion efficiency)17- Wants to generate null/surrogate networks preserving degree, strength, or distance distributions18- Performs community detection or consensus clustering on brain networks19- Computes spatial autocorrelation (Moran's I, Geary's C, Lee's L) on parcellated brain data20- Fetches standard neuroimaging templates (fsaverage, fsLR, CIVET, Conte69) or atlases (Schaefer, Cammoun, Pauli)21- Needs to convert between vertex-level and parcel-level brain data22- Visualizes data on cortical surfaces using PyVista or PySurfer23- Mentions netneurotools, netneurolab, or any function from this toolbox24- Performs structure-function coupling, assortativity analysis, or dominance analysis25- Simulates atrophy spreading on brain networks (SIR model)2627## Reference Files (Progressive Disclosure)2829| Topic | File | When to Read |30|-------|------|--------------|31| Datasets | `references/datasets.md` | User fetches templates, atlases, or project datasets |32| Network Metrics | `references/metrics.md` | User computes communication, assortativity, spreading, or statistical network metrics |33| Networks | `references/networks.md` | User builds consensus connectivity, randomizes networks, or thresholds graphs |34| Statistics | `references/stats.md` | User runs permutation tests, correlations, residualization, or dominance analysis |35| Spatial & Modularity | `references/spatial-modularity.md` | User computes spatial autocorrelation or performs community detection |36| Interface & Plotting | `references/interface-plotting.md` | User converts parcels/vertices, handles CIFTI/GIFTI files, or plots on cortical surfaces |3738## Installation3940```bash41pip install netneurotools4243# For PyVista surface plotting (recommended)44pip install netneurotools[pyvista]4546# For PySurfer surface plotting (legacy)47pip install netneurotools[pysurfer]4849# For numba acceleration50pip install netneurotools[numba]51```5253**Core dependencies:** numpy>=1.16, scipy>=1.4.0, scikit-learn, matplotlib, nibabel>=3.0.0, nilearn, bctpy, tqdm, neuromaps5455## Overview Pipeline5657```581. Fetch data --> netneurotools.datasets (templates, atlases, connectomes)592. Build networks --> netneurotools.networks (consensus, thresholding)603. Analyze metrics --> netneurotools.metrics (communication, assortativity)614. Null models --> netneurotools.networks (randomization, surrogates)625. Statistics --> netneurotools.stats (permutation tests, dominance)636. Spatial stats --> netneurotools.spatial (Moran's I, Geary's C, Lee's L)647. Modularity --> netneurotools.modularity (consensus clustering)658. Visualize --> netneurotools.plotting (cortical surfaces, heatmaps)66```6768## Quick Start6970### Fetch Atlas and Template7172```python73from netneurotools.datasets import fetch_schaefer2018, fetch_fsaverage_curated7475# Fetch Schaefer 400-parcel atlas in fsaverage space76parc = fetch_schaefer2018('fsaverage')['400Parcels7Networks']77# parc is a SURFACE namedtuple with fields .L and .R7879# Fetch curated fsaverage surfaces80surfaces = fetch_fsaverage_curated('fsaverage5')81# surfaces has keys: 'white', 'pial', 'inflated', 'sphere', 'medial', 'sulc', 'vaavg'82# Each value is a SURFACE namedtuple with fields .L and .R83```8485### Consensus Functional Connectivity8687```python88from netneurotools.networks import func_consensus89import numpy as np9091# data: (N_nodes, T_timepoints, S_subjects) array92consensus = func_consensus(data, n_boot=1000, ci=95, seed=42)93```9495### Community Detection9697```python98from netneurotools.modularity import consensus_modularity99import numpy as np100101# adjacency: (N, N) non-negative connectivity matrix102consensus, Q_all, zrand_all = consensus_modularity(103 adjacency, gamma=1.5, repeats=100, seed=1234104)105```106107### Generate Distance-Preserving Surrogates108109```python110from netneurotools.networks import match_length_degree_distribution111112newB, newW, nr = match_length_degree_distribution(113 W, D, nbins=10, nswap=1000, seed=42114)115```116117### Permutation Test for Correlation118119```python120from netneurotools.stats import permtest_pearsonr, make_correlated_xy121122x, y = make_correlated_xy(corr=0.3, size=100, seed=42)123r, p = permtest_pearsonr(x, y, n_perm=5000, seed=42)124```125126### Spatial Autocorrelation127128```python129from netneurotools.spatial import morans_i130131I = morans_i(annotation_vector, spatial_weight_matrix)132```133134### Plot on Cortical Surface (PyVista)135136```python137from netneurotools.plotting import pv_plot_surface138import numpy as np139140data_L = np.random.random((10242,))141data_R = np.random.random((10242,))142pl = pv_plot_surface(143 (data_L, data_R),144 template="fsaverage5",145 surf="inflated",146 cmap="viridis",147 lighting_style="plastic",148 jupyter_backend="static",149)150```151152### Plot Parcellated Data (Shortcut)153154```python155from netneurotools.plotting import pv_plot_parcellated_data156import numpy as np157158data = np.random.rand(400)159pl = pv_plot_parcellated_data(data, 'schaefer400x7', template='fsaverage')160```161162## Key Data Structures163164| Structure | Description | Fields |165|-----------|-------------|--------|166| `SURFACE` | namedtuple for hemisphere file pairs | `.L`, `.R` (left/right hemisphere paths) |167| `sklearn.utils.Bunch` | Dict-like object returned by fetch functions | Varies per function |168| `FREESURFER_IGNORE` | Labels to ignore in FreeSurfer parcellations | `["unknown", "corpuscallosum", "Background+FreeSurfer_Defined_Medial_Wall"]` |169| `PARCIGNORE` | Labels to ignore in parcellation operations | `["unknown", "corpuscallosum", "Background+FreeSurfer_Defined_Medial_Wall", "???", "Unknown", "Medial_wall", "Medial wall", "medial_wall"]` |170171## Core Modules Quick Reference172173| Module | Key Functions | Purpose |174|--------|--------------|---------|175| `datasets` | `fetch_fsaverage`, `fetch_schaefer2018`, `fetch_cammoun2012`, `fetch_conte69`, `fetch_famous_gmat` | Fetch templates, atlases, connectomes |176| `metrics` | `distance_wei_floyd`, `navigation_wu`, `communicability_wei`, `search_information`, `mean_first_passage_time`, `assortativity_und`, `simulate_atrophy` | Network communication and properties |177| `networks` | `func_consensus`, `struct_consensus`, `match_length_degree_distribution`, `strength_preserving_rand_sa` | Build consensus, generate null models |178| `stats` | `permtest_pearsonr`, `efficient_pearsonr`, `residualize`, `get_dominance_stats` | Statistical testing and regression |179| `spatial` | `morans_i`, `gearys_c`, `lees_l`, `local_morans_i`, `local_gearys_c`, `local_lees_l` | Spatial autocorrelation |180| `modularity` | `consensus_modularity`, `find_consensus`, `zrand`, `get_modularity` | Community detection and evaluation |181| `interface` | `vertices_to_parcels`, `parcels_to_vertices`, `load_surf_parc_file`, `deconstruct_cifti` | Format conversion |182| `plotting` | `pv_plot_surface`, `pv_plot_parcellated_data`, `pv_plot_subcortex`, `plot_mod_heatmap` | Visualization |183184## Common Pitfalls1851861. **SURFACE fields are `.L` and `.R`**, not `.lh` and `.rh`. Use `surface.L` and `surface.R` to access hemisphere paths.1871882. **Weight-to-distance conversion** must be done before calling `distance_wei_floyd` or `search_information`. Common transform: `D = -np.log(W / (np.max(W) + 1))`.1891903. **Minimum permutation p-value** is `1 / (n_perm + 1)`. With `n_perm=1000`, the smallest p-value is ~0.001.1911924. **`consensus_modularity` requires non-negative input.** Louvain cannot handle negative weights. Set negatives to zero: `A[A < 0] = 0`.1931945. **`struct_consensus` hemiid encoding**: 0 = right hemisphere, 1 = left hemisphere.1951966. **`pv_plot_surface` data format**: When `hemi='both'`, `vertex_data` can be a tuple `(left, right)` or a single concatenated array. Data length must match template vertex count.1971987. **Data directory**: All fetch functions default to `~/nnt-data`. Override with `data_dir=` parameter or set `NNT_DATA` environment variable.1992008. **`match_length_degree_distribution` recommended nswap**: Use `nswap = nnodes * 20` for adequate randomization.2012029. **`strength_preserving_rand_sa` frac parameter** must be between 0 and 1. It controls temperature decrease per annealing stage.20320410. **`parcels_to_vertices` and `vertices_to_parcels`** support `.annot`, `.gii`, and `.dlabel.nii` parcellation files. For `.dlabel.nii`, pass a single file path; for `.annot` or `.gii`, pass a tuple of `(left, right)` paths.20520611. **Numba acceleration** is available for spatial stats, weighted correlation, and some metrics. Install numba for significant speedups on large datasets.20720812. **Headless rendering** with PyVista: set `os.environ["VTK_DEFAULT_OPENGL_WINDOW"] = "vtkOSOpenGLRenderWindow"` before importing pyvista.