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.

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.3.tar.gz (12.1 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.3-py3-none-any.whl (12.7 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: niitools-0.0.3.tar.gz
  • Upload date:
  • Size: 12.1 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.3.tar.gz
Algorithm Hash digest
SHA256 b78ce34ad3ec040326dd2e6df794a7ce4ac21fb7540538f3e1c80ed172ab546d
MD5 baec6825c70e4cf100cee5211e2a75ad
BLAKE2b-256 67ba8082672a91a3cfe8878f837418e26da05fd23d2f6b1cb192e9d4ac9c9e8c

See more details on using hashes here.

Provenance

The following attestation bundles were made for niitools-0.0.3.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.3-py3-none-any.whl.

File metadata

  • Download URL: niitools-0.0.3-py3-none-any.whl
  • Upload date:
  • Size: 12.7 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.3-py3-none-any.whl
Algorithm Hash digest
SHA256 20febcfcb6d04b850035da15604e9589f93ac4f9055cac1e06f0f08723a89afd
MD5 360dad8393a81964970b473945d19cc8
BLAKE2b-256 d8d6f6f88c44da0c200af7ad106e94825ebbbe53aaaa21c20520d80f03fd77df

See more details on using hashes here.

Provenance

The following attestation bundles were made for niitools-0.0.3-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