Skip to main content

My humble package for NeuroImaging Informatics tools

Project description

niitools

NeuroImaging Informatics Tools — Extract and aggregate brain segmentation statistics from FastSurfer outputs

Python Version License: MIT

Overview

niitools is a Python package designed to streamline the extraction and aggregation of neuroimaging statistics from FastSurfer brain segmentation outputs. It processes multiple subjects at scale and generates publication-ready CSV and Excel reports for four key neuroimaging metrics:

  • Cortical Thickness — Average thickness across cortical regions (left & right hemispheres)
  • Subcortical Segmentation — Volumes of subcortical structures (Aseg)
  • Brain Stem Analysis — Volumetric measurements of brain stem components
  • Cerebellar Segmentation — Cerebellar structure volumes via CerebNet

Perfect for neuroimaging research pipelines, clinical studies, and batch processing of brain MRI analysis outputs.


✨ Features

  • 🚀 Batch Processing — Process hundreds of subjects in a single command
  • 📊 Multi-Format Output — Generate both CSV and Excel files with automatic formatting
  • 🧠 Four Analysis Modules — Comprehensive coverage of cortical, subcortical, brainstem, and cerebellar metrics
  • 🔄 Flexible API — Use as a command-line tool or import as a Python library
  • 📝 Logging Support — Detailed logging with loguru for debugging and audit trails
  • Validation — Automatic validation of FastSurfer output directory structure

📦 Installation

From Source (Recommended for Development)

git clone https://github.com/diogohs/niitools.git
cd niitools
pip install -e .

This installs the package in editable mode and registers the niitools command-line tool.

From PyPI

pip install niitools

Requirements

  • Python: 3.8 or higher
  • Dependencies:
    • pandas>=2.0.3 — Data manipulation and analysis
    • openpyxl>=3.1.5 — Excel file generation
    • loguru>=0.7.3 — Advanced logging

🚀 Quick Start

Command-Line Usage

Extract FastSurfer statistics from all subjects in a directory:

niitools fastsurfer -i ./data/input -o ./data/output

Arguments:

  • -i, --input (required) — Path to directory containing FastSurfer output directories
  • -o, --output (required) — Path to output directory for CSV and Excel files

Example:

niitools fastsurfer -i /mri_data/fastsurfer_results -o /mri_data/statistics

Python Library Usage

Import and use niitools in your Python scripts:

from pathlib import Path
from niitools.fastsurfer import run_fastsurfer

# Define input and output paths
input_dir = Path("./data/input")
output_dir = Path("./data/output")

# Run the analysis
run_fastsurfer(input_dir, output_dir)

The function will:

  1. Scan the input directory for valid FastSurfer output structures
  2. Extract statistics from each subject
  3. Aggregate results across all subjects
  4. Generate both CSV and Excel output files

📋 Output Files

The analysis generates 8 output files (4 metrics × 2 formats):

Files Generated

Metric CSV File Excel File
Cortical Thickness (Left) FastSurfer_Cortical_Thickness_left.csv FastSurfer_Cortical_Thickness_left.xlsx
Cortical Thickness (Right) FastSurfer_Cortical_Thickness_right.csv FastSurfer_Cortical_Thickness_right.xlsx
Subcortical (Aseg) FastSurfer_Aseg.csv FastSurfer_Aseg.xlsx
Brain Stem FastSurfer_BrainStem.csv FastSurfer_BrainStem.xlsx
Cerebellar (CerebNet) FastSurfer_CerebNet.csv FastSurfer_CerebNet.xlsx

Output Structure

Each output file contains:

  • Subject Column — Subject identifier in the first column
  • Region Columns — One column per brain region with extracted metrics
  • One Row per Subject — Aggregated statistics for each subject

🏗️ Project Structure

niitools/
├── niitools/
│   ├── __init__.py              # Package initialization
│   ├── __main__.py              # CLI entry point
│   ├── validate.py              # Validation utilities
│   ├── utils.py                 # Helper functions
│   └── fastsurfer/
│       ├── __init__.py          # Module exports
│       ├── _executor.py         # Main execution logic
│       ├── aseg.py              # Subcortical segmentation parsing
│       ├── brainstem.py         # Brain stem parsing
│       ├── cerebnet.py          # Cerebellar segmentation parsing
│       └── cortical.py          # Cortical thickness parsing
├── tests/
│   ├── __init__.py
│   └── test_converter.py        # Unit tests
├── notebooks/                   # Jupyter notebooks with examples
├── data/
│   ├── input/                   # FastSurfer outputs (input)
│   └── output/                  # Generated statistics (output)
├── pyproject.toml               # Project configuration
├── README.md                    # This file
└── LICENSE                      # MIT License

📚 Advanced Usage

Processing with Custom Logging

from pathlib import Path
from loguru import logger
from niitools.fastsurfer import run_fastsurfer

# Configure logging
logger.add("niitools_processing.log", level="DEBUG")

# Run with logging enabled
run_fastsurfer(Path("./input"), Path("./output"))

Validating FastSurfer Directories

from pathlib import Path
from niitools.validate import is_fastsurfer_output

subject_dir = Path("./data/SUBJECT_001")
if is_fastsurfer_output(subject_dir):
    print("Valid FastSurfer output structure!")
else:
    print("Missing required subdirectories")

⚙️ FastSurfer Output Requirements

niitools expects standard FastSurfer output directories with the following structure:

SUBJECT_ID/
├── label/          # Brain region labels
├── mri/            # MRI volumes and brain stem outputs
├── scripts/        # FastSurfer processing scripts
├── stats/          # Statistical output files
└── surf/           # Surface files

Ensure your FastSurfer output contains these required files:

  • stats/aseg.stats — Subcortical segmentation statistics
  • stats/cerebellum.CerebNet.stats — Cerebellar segmentation
  • stats/lh.aparc.DKTatlas.mapped.stats — Left hemisphere cortical thickness
  • stats/rh.aparc.DKTatlas.mapped.stats — Right hemisphere cortical thickness
  • mri/brainstemSsLabels.volumes.txt — Brain stem volumes

🐛 Troubleshooting

No subjects found

⚠️  No valid FastSurfer output directories found in {input_dir}

Solution: Verify that input directories contain the required FastSurfer subdirectories (label, mri, scripts, stats, surf).

Missing statistics files

⚠️  Missing required statistics file

Solution: Ensure FastSurfer processing completed successfully and generated all required output files.

Python version incompatibility

ERROR: This package requires Python 3.8 or higher

Solution: Upgrade Python: python --version should return 3.8+


🤝 Contributing

Contributions are welcome! Please feel free to:

  • Report bugs via GitHub Issues
  • Submit pull requests for improvements
  • Suggest new features or analysis modules

📄 License

This project is licensed under the MIT License — see the LICENSE file for details.


Develop

uv pip install -e .
niitools fastsurfer -i data\input -o data\output

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

niitools-0.0.6.tar.gz (12.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

niitools-0.0.6-py3-none-any.whl (13.6 kB view details)

Uploaded Python 3

File details

Details for the file niitools-0.0.6.tar.gz.

File metadata

  • Download URL: niitools-0.0.6.tar.gz
  • Upload date:
  • Size: 12.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for niitools-0.0.6.tar.gz
Algorithm Hash digest
SHA256 015f515f4aa476a28940d2e2e898c415c8b636ca7d363950ec78f9d1240321e5
MD5 44edd24e9868855cb1462322853ce5f7
BLAKE2b-256 03d48ec01818275288b3cbd0e321d262286e5112c0cbc578144b0f6727953c24

See more details on using hashes here.

Provenance

The following attestation bundles were made for niitools-0.0.6.tar.gz:

Publisher: python-publish.yml on diogohs/niitools

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file niitools-0.0.6-py3-none-any.whl.

File metadata

  • Download URL: niitools-0.0.6-py3-none-any.whl
  • Upload date:
  • Size: 13.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for niitools-0.0.6-py3-none-any.whl
Algorithm Hash digest
SHA256 5dc7c06c6b81e12c32e91c9eb25f4548e30054ff03689d6361df761937c68412
MD5 591284b976fb9b4dc2235b1f55967465
BLAKE2b-256 a42716256f1571764f1344bc30ab7b286fb42ff5488ea6fd8739d41f016d8007

See more details on using hashes here.

Provenance

The following attestation bundles were made for niitools-0.0.6-py3-none-any.whl:

Publisher: python-publish.yml on diogohs/niitools

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page