Metadata-Version: 2.4
Name: niitools
Version: 0.0.3
Summary: My humble package for NeuroImaging Informatics tools
Author: diogohs
License: MIT License
        
        Copyright (c) 2026 Diogo Shiraishi
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/diogohs/niitools
Project-URL: Repository, https://github.com/diogohs/niitools
Project-URL: Issues, https://github.com/diogohs/niitools/issues
Project-URL: Bug Tracker, https://github.com/diogohs/niitools/issues
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: loguru>=0.7.3
Requires-Dist: openpyxl>=3.1.5
Requires-Dist: pandas>=2.0.3
Dynamic: license-file

# niitools

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

[![Python Version](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Overview

**niitools** is a Python package designed to streamline the extraction and aggregation of neuroimaging statistics from [FastSurfer](https://github.com/Deep-MI/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)

```bash
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

```bash
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:

```bash
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:**
```bash
niitools fastsurfer -i /mri_data/fastsurfer_results -o /mri_data/statistics
```

### Python Library Usage

Import and use **niitools** in your Python scripts:

```python
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

```python
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

```python
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](https://github.com/diogohs/niitools/issues)
- Submit pull requests for improvements
- Suggest new features or analysis modules

---

## 📄 License

This project is licensed under the MIT License — see the [LICENSE](LICENSE) file for details.
