Metadata-Version: 2.4
Name: T1Prep
Version: 0.3.8
Summary: T1 PREProcessing Pipeline (aka PyCAT)
Author-email: Christian Gaser <christian.gaser@uni-jena.de>
License: Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Homepage, https://github.com/ChristianGaser/T1Prep
Project-URL: Repository, https://github.com/ChristianGaser/T1Prep
Project-URL: Bug Tracker, https://github.com/ChristianGaser/T1Prep/issues
Project-URL: Changelog, https://github.com/ChristianGaser/T1Prep/releases
Classifier: Development Status :: 4 - Beta
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Classifier: License :: OSI Approved :: Apache Software License
Requires-Python: <3.13,>=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cat-surf>=1.0.8
Requires-Dist: nibabel>=3.2
Requires-Dist: numpy>=1.20
Requires-Dist: scipy>=1.10.1
Requires-Dist: torch>=1.11.0
Requires-Dist: deepmriprep>=0.3.0
Requires-Dist: deepbet>=1.0.2
Requires-Dist: torchreg>=0.1.3
Requires-Dist: spline-resize>=0.1.1
Requires-Dist: SplineSmooth3D>=0.1.1
Requires-Dist: nxbc>=0.2.0
Requires-Dist: requests
Requires-Dist: flask>=2.3
Requires-Dist: apscheduler>=3.10
Requires-Dist: h5py>=3.0
Requires-Dist: sentry-sdk
Provides-Extra: gui
Requires-Dist: PySide6>=6.5; extra == "gui"
Requires-Dist: vtk>=9.0.0; extra == "gui"
Dynamic: license-file

[![Python 3.9 | 3.10 | 3.11 | 3.12](https://img.shields.io/badge/Python-3.9%20|%203.10%20|%203.11%20|%203.12-3776AB?logo=python&logoColor=white)](https://www.python.org/downloads/)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg?logo=apache&logoColor=white)](LICENSE)
[![Release](https://img.shields.io/github/v/release/ChristianGaser/T1Prep?display_name=tag&include_prereleases)](https://github.com/ChristianGaser/T1Prep/releases)
<!--
[![Tag](https://img.shields.io/github/v/tag/ChristianGaser/T1Prep?sort=semver)](https://github.com/ChristianGaser/T1Prep/tags)
-->
> [!WARNING]
> This project is **still in development** and might contain bugs. **If you experience any issues, please [let me know](https://github.com/ChristianGaser/T1Prep/issues)!**

<img src="T1Prep_logo.svg" alt="T1Prep logo" width="340"> 

# T1Prep: T1 PREProcessing Pipeline (aka PyCAT) 

## Table of Contents

- [Requirements](#requirements)
- [Main Differences to CAT12](#main-differences-to-cat12)
- [Installation](#installation)
- [Quick Install (Recommended)](#quick-install-recommended)
- [Windows Installation via WSL](#windows-installation-via-wsl-recommended)
- [Manual Installation](#manual-installation)
- [Web UI (Flask)](#web-ui-flask)
- [Docker](#docker)
- [Output Folder Structure and Naming Conventions](#output-folder-structure-and-naming-conventions)
- [Usage](#usage)
- [Helper Scripts](#helper-scripts)
- [Python API](#python-api)
- [Options](#options)
- [Output folders structure](#output-folders-structure)
- [Naming behaviour](#naming-behaviour)
- [Examples](#examples)
- [Longitudinal realignment (experimental)](#longitudinal-realignment-experimental)
- [Input](#input)
- [Support](#support)
- [License](#license)

---

T1Prep is a pipeline that preprocesses T1-weighted MRI data and supports segmentation and cortical surface reconstruction. It provides a complete set of tools for efficiently processing structural MRI scans.

T1Prep partially integrates [DeepMriPrep](https://github.com/wwu-mmll/deepmriprep), which uses deep learning (DL) techniques to mimic CAT12's functionality for processing structural MRIs. For details, see:
Lukas Fisch et al., "deepmriprep: Voxel-based Morphometry (VBM) Preprocessing via Deep Neural Networks," available on arXiv at https://doi.org/10.48550/arXiv.2408.10656.

An alternative approach uses DeepMriPrep for bias field correction, lesion detection, and also serves as an initial estimate for the subsequent AMAP segmentation from CAT12. 

Cortical surface reconstruction and thickness estimation use the algorithms from [CAT-Surface](https://github.com/ChristianGaser/CAT-Surface) (a core component of the [CAT12 toolbox](https://github.com/ChristianGaser/cat12)) via the [`cat-surf`](https://pypi.org/project/cat-surf/) Python package, which provides pure Python bindings to the CAT-Surface C library — no platform-specific compiled binaries are required.

It is designed for both single-subject and batch processing, with optional parallelization and flexible output naming conventions. The naming patterns are compatible with both 
CAT12 folder structures and the BIDS derivatives standard.

## Requirements
 [Python 3.9-3.12](https://www.python.org/downloads/) is required, and all necessary libraries are automatically installed the first time T1Prep is run or is called with the flag "--install".

## Main Differences to CAT12
- Implemented entirely in Python, eliminating the need for a Matlab license or platform-specific compiled binaries.
- Newly developed pipeline to estimate cortical surface and thickness.
- Skull-stripping, segmentation and non-linear spatial registration uses DeepMriPrep
- Does not yet support longitudinal pipelines.
- No quality assessment implemented yet.
- Only T1 MRI data supported.

## Installation

### Quick Install (Recommended)
Install T1Prep directly with a single command:
```bash
curl -fsSL https://raw.githubusercontent.com/ChristianGaser/T1Prep/refs/heads/main/scripts/install.sh | bash
```

The installer will interactively prompt you to:
1. **Select a version**: Latest release, development (main branch), or choose from available releases
2. **Choose installation directory**: Current folder, temporary folder, or custom path

#### Non-Interactive Installation
Use environment variables to skip the interactive prompts:
```bash
# Install latest release to current directory
T1PREP_VERSION=latest T1PREP_INSTALL_DIR="$PWD/T1Prep" \
  curl -fsSL https://raw.githubusercontent.com/ChristianGaser/T1Prep/refs/heads/main/scripts/install.sh | bash

# Install specific version to custom directory
T1PREP_VERSION=v1.0.0 T1PREP_INSTALL_DIR=/opt/T1Prep \
  curl -fsSL https://raw.githubusercontent.com/ChristianGaser/T1Prep/refs/heads/main/scripts/install.sh | bash
```

| Environment Variable | Description |
|---------------------|-------------|
| `T1PREP_VERSION` | Release tag (e.g., `v1.0.0`) or `latest` |
| `T1PREP_INSTALL_DIR` | Absolute path for installation |

### Windows Installation via WSL (Recommended)

T1Prep requires a Linux environment to run. On Windows, we recommend using **Windows Subsystem for Linux (WSL)**, which provides a complete Linux environment with full compatibility.

#### WSL Requirements

| Windows Version | WSL Support |
|-----------------|-------------|
| Windows 11 (all versions) | WSL 2 ✓ |
| Windows 10 version 2004+ (Build 19041+) | WSL 2 ✓ |
| Windows 10 version 1903-1909 | WSL 2 (with manual kernel update) |
| Windows 10 version 1607-1903 | WSL 1 only |
| Windows Server 2019+ | WSL ✓ |

#### Installing WSL and T1Prep

1. **Install WSL** (run PowerShell as Administrator):
   ```powershell
   wsl --install
   ```
   This installs WSL 2 with Ubuntu by default. Restart your computer when prompted.

2. **Open Ubuntu** from the Start menu and complete the initial setup (create username/password).

3. **Install T1Prep** inside WSL (Ubuntu terminal):
   ```bash
   curl -fsSL https://raw.githubusercontent.com/ChristianGaser/T1Prep/main/scripts/install.sh | bash
   ```

4. **Access Windows files** from WSL at `/mnt/c/` (C: drive), `/mnt/d/` (D: drive), etc.:
   ```bash
   # Process a file from your Windows Documents folder
   T1Prep --out-dir /mnt/c/Users/YourName/T1Prep_output /mnt/c/Users/YourName/Documents/scan.nii.gz
   ```

#### Alternative: Docker on Windows

If you prefer not to install WSL directly, you can use Docker Desktop for Windows (which uses WSL 2 internally):

```powershell
docker run --rm -it -v C:\path\to\data:/data t1prep:latest --out-dir /data/out /data/file.nii.gz
```

See the [Docker](#docker) section for build instructions.

### Manual Installation
Download T1Prep_$version.zip from Github and unzip:
```bash
  unzip T1Prep_$version.zip -d your_installation_folder
```
Install required Python packages (check that the correct Python version 3.9-3.12
is being used):
```bash
./scripts/T1Prep --python python3.12 --install
```
Alternatively, install the dependencies manually:
```bash
python3.12 -m pip install -r requirements.txt
```

## Web UI (Flask)

A minimal browser-based UI is available for local use. It uploads selected NIfTI
files, lets you configure General and Save options, and can schedule jobs to
start at a specific time.

```bash
./scripts/T1Prep_ui
```

By default the Web UI runs on port 5050. To use a different port:

```bash
./scripts/T1Prep_ui 5500
```

When started, the UI will try to open an app-style window (Chrome if available,
otherwise your default browser). You can also open the URL manually in any
browser.

Then open http://127.0.0.1:5050 (or the port you selected) in your browser.

To prevent auto-opening a browser window:

```bash
./scripts/T1Prep_ui --no-browser
```

Uploaded files are stored under `webui_uploads/` and per-job logs under
`webui_jobs/`.

## Docker

A Dockerfile is provided to build an image with all required dependencies.

### Build

**Default (release ZIP):**
```bash
docker build -t t1prep:latest .
```

**Latest GitHub source (e.g., main):**

```bash
docker build \
  --build-arg T1PREP_SOURCE=git \
  --build-arg T1PREP_REF=main \
  -t t1prep:git-main .
```

**Specific release:**

```bash
docker build \
  --build-arg T1PREP_VERSION=v0.2.0-beta \
  -t t1prep:release .
```

### Run

Mount your data directory into the container (replace /path/to/data with your folder):

```bash
docker run --rm -it \
  -v /path/to/data:/data \
  t1prep:latest \
  --out-dir /data/out /data/file.nii.gz
```
Append `--gpus all` to `docker run` to enable GPU acceleration when available.

### Memory & performance

Make sure that the container has at least 16-24 GB of RAM available. If you are using Docker Desktop/WSL2, increase the VM memory in the settings. If you receive an error message stating that there is no space left on the device: /tmp/, you can try the following:
If you obtain an error that no space is left on device: /tmp/ you can try that:
```bash
docker run --rm -it \
  --tmpfs /tmp:rw,exec,nosuid,nodev,size=16g \
  -v /path/to/data:/data \
  t1prep:latest \
  --out-dir /data/out /data/file.nii.gz
```

## Output Folder Structure and Naming Conventions

T1Prep automatically determines output locations based on the input data structure:

1. **BIDS datasets**  
   If the input NIfTI is located in an `anat` folder:

`<dataset-root>/derivatives/T1Prep-v<version>/<sub-XXX>/<ses-YYY>/anat/`
   
- Subject (`sub-XXX`) and session (`ses-YYY`) are extracted from the path.
- If `--out-dir <DIR>` is specified, the BIDS substructure will still be created inside `<DIR>`.

2. **Non-BIDS datasets**  
Results are written to **CAT12-style subfolders** (`mri/`, `surf/`, etc.) in:
   
`<input-folder>/<subfolder>/`

or in `<DIR>` if `--out-dir <DIR>` is specified.

3. **Naming Conventions**  
- **Default (CAT12)**: Uses classic names like `mri/brainmask.nii` and `surf/lh.thickness`.
- **With `--bids`**: Uses BIDS derivatives naming, e.g.:
  ```
  sub-01_ses-1_space-T1w_desc-brain_mask.nii.gz
  sub-01_ses-1_hemi-L_thickness.shape.gii
  ```
- All filename mappings for both modes are defined in `Names.tsv` and can be customized.   
   
## Usage
```bash
./scripts/T1Prep [options] file1.nii.[.gz] file2.nii[.gz] ...
```

## Helper Scripts

In addition to `./scripts/T1Prep`, the following wrappers provide convenient
entry points for Web UI and CAT-Surface post-processing.

### `./scripts/T1Prep_ui`

Launches the Flask Web UI (same tool described in the [Web UI (Flask)](#web-ui-flask) section).

```bash
./scripts/T1Prep_ui
./scripts/T1Prep_ui 5500
./scripts/T1Prep_ui --no-browser
```

- Default port: `5050`
- Optional positional port argument (e.g., `5500`)
- `--no-browser` disables auto-launching a browser/app window

### `./scripts/CAT_SurfResampleMulti_ui`

Resamples LH/RH surface values to target spheres and writes a combined output
per LH input using `CAT_SurfResampleMulti`.

```bash
./scripts/CAT_SurfResampleMulti_ui [options] lh.thickness.subject.gii
```

Common options:
- `--out <DIR>` output directory
- `--res <STR>` output surface resolution (`32k` or `4k`)
- `--fwhm <FLOAT>` smoothing FWHM
- `--trg-sphere <FILE>` target LH sphere
- `--mask <FILE>` target LH mask
- `--jobs <N>` parallel worker count

Input expectations:
- Supports `lh.*` naming and auto-derives RH counterparts
- BIDS-style `*_left*` naming is currently not implemented

### `./scripts/CAT_SurfParameters_ui`

Computes surface parameters from mesh files using CAT-Surface binaries
(`CAT_SurfCurvature`, `CAT_SurfFractalDimension`, `CAT_SurfArea`,
`CAT_SurfRatio`, `CAT_SurfSulcusDepth`) bundled in `src/t1prep/bin/`.

```bash
./scripts/CAT_SurfParameters_ui [options] lh.central.gii
```

Common options:
- `-gy`, `-mc`, `-gc`, `-cv`, `-si`, `-sh`, `-fi`, `-area`, `-fd`, `-sr`, `-sra`
- `-depth`, `-sqrt-depth`, `-min-curv`, `-max-curv`, `-dp`
- `-gifti` write GIfTI output
- `-noclobber` do not overwrite existing files
- `--jobs <N>` / `--no-parallel` parallel control

Input expectations:
- Accepts `.obj` and `.gii`
- For `lh.*` files, matching `rh.*` is processed automatically when available

### `./scripts/CAT_Surf2ROIMulti_ui`

Extracts ROI-wise values from surface value files using `CAT_Surf2ROIMulti`.
For each LH input, RH files are derived automatically.

```bash
./scripts/CAT_Surf2ROIMulti_ui [options] lh.thickness.subject.gii
```

Common options:
- `--out <DIR>` output directory
- `--res <STR>` surface/atlas resolution (default `32k`)
- `--trg-sphere <FILE>` target LH sphere
- `--annot <NAMES>` one or multiple atlas names
- `--jobs <N>` / `--no-parallel` parallel control

Atlas names for `--annot` are resolved as:
- `src/t1prep/data/atlases_surfaces_<res>/lh.<name>.annot`
- `src/t1prep/data/atlases_surfaces_<res>/rh.<name>.annot`

Multi-atlas examples:

```bash
./scripts/CAT_Surf2ROIMulti_ui --annot "'aparc_DK40.freesurfer' 'aparc_a2009s.freesurfer'" lh.thickness.subject.gii
./scripts/CAT_Surf2ROIMulti_ui --annot "aparc_DK40.freesurfer,aparc_a2009s.freesurfer" lh.thickness.subject.gii
```

## Python API
You can also call the full pipeline from Python without shelling out manually:

```python
from t1prep import run_t1prep

# Single file, BIDS naming
run_t1prep("/data/sub-01/ses-1/anat/sub-01_ses-1_T1w.nii.gz", bids=True)

# Multiple files with options and logging
run_t1prep([
  "/data/T1/sub-01.nii.gz",
  "/data/T1/sub-02.nii.gz",
], out_dir="/results", atlas=["neuromorphometrics", "suit"], multi=-1,
   wp=True, p=True, csf=True, lesions=True, gz=True, stream_output=True,
   log_file="/results/T1Prep_run.log")
```

## Options
Simply call T1Prep to see available options
```bash
./scripts/T1Prep
```

Skull-stripping modes:
- `--skullstrip-only`: run skull-stripping only and exit after writing a skull-stripped image and brain mask.
- `--no-skullstrip` / `--skip-skullstrip`: skip skull-stripping (assumes input is already skull-stripped).

Longitudinal / advanced flags:
- `--initial-surf <FILE>`: use an initial surface estimate for longitudinal processing.
- `--long-data <PATH>`: process the volume at `<PATH>` while keeping output naming/folders based on the provided input file.
- `--no-atlas`: disable atlas labeling (overrides any defaults file atlas selection).

Robustness:
- `--no-retry`: disable automatic retry of failed processing steps. By default, if
  segmentation or surface estimation fails for a subject it is retried once before being
  reported as an error.

## Output folders structure
Output folder structure depends on the input dataset type:
* BIDS datasets (if the upper-level folder of the input files is 'anat'):
    Results are placed in a BIDS-compatible derivatives folder:
    inside &lt;DIR&gt;
    Subject ('sub-XXX') and session ('ses-YYY') are auto-detected.
* Non-BIDS datasets:
    Results are placed in subfolders similar to CAT12 output
    (e.g., 'mri/', 'surf/', 'report/', 'label') inside the specified 
    output directory.

If '--bids' is set, the BIDS derivatives substructure will always be used
inside &lt;DIR&gt;.

## Naming behaviour
* CAT12 style (default): Uses legacy folder and file names
  (e.g., 'mri/mwp1sub-01.nii', 'surf/lh.thickness.sub-01').
* BIDS style: Uses standardized derivatives names, including 
  subject/session identifiers, modality, and processing steps.

The complete mapping between internal outputs and both naming conventions
is stored in 'Names.tsv' and can be customized.

Examples:
Input: /data/study/sub-01/ses-1/anat/sub-01_ses-1_T1w.nii.gz
Default output (no --out-dir):
    /data/study/derivatives/T1Prep-v${version}/sub-01/ses-1/anat/
With --out-dir /results:
    /results/derivatives/T1Prep-v${version}/sub-01/ses-1/anat/

Input: /data/T1_images/subject01.nii.gz
Default output (no --out-dir):
    /data/T1_images/mri/
With --out-dir /results:
    /results/mri/

## Examples
```bash
  ./scripts/T1Prep --out-dir test_folder sTRIO*.nii
```
Process all files matching the pattern 'sTRIO*.nii'. Generate segmentation 
and surface maps, saving the results in the 'test_folder' directory.

```bash
  ./scripts/T1Prep --no-surf sTRIO*.nii
```
Process all files matching the pattern 'sTRIO*.nii', but skip surface 
creation. Only segmentation maps are generated and saved in the same 
directory as the input files.

```bash
  ./scripts/T1Prep --python python3.9 --no-overwrite "surf/lh.thickness." sTRIO*.nii
```
Process all files matching the pattern `'sTRIO*.nii'` and use python3.9. 
Skip processing for files where 'surf/lh.thickness.*' already exists, and 
save new results in the same directory as the input files.

```bash
  ./scripts/T1Prep --lesion --no-sphere sTRIO*.nii
```
Process all files matching the pattern `'sTRIO*.nii'`. Skip processing of 
spherical registration, but additionally save lesion map (named p7sTRIO*.nii) 
in native space.

```bash
  ./scripts/T1Prep --amap sTRIO*.nii
```
Process all files matching the pattern `'sTRIO*.nii'` and enable AMAP segmentation.
  
```bash
  ./scripts/T1Prep --multi 8 --p --csf sTRIO*.nii
```

```bash
  ./scripts/T1Prep --skullstrip-only --out-dir test_folder sTRIO*.nii
```
Only run skull-stripping and write the skull-stripped image and brain mask.

```bash
  ./scripts/T1Prep --skip-skullstrip --out-dir test_folder sTRIO*_brain.nii
```
Skip skull-stripping for already skull-stripped inputs.
Process all files matching the pattern 'sTRIO*.nii'. Additionally save 
segmentations in native space, including CSF segmentation. The processing 
pipeline involves two stages of parallelization:

1. Segmentation (Python-based): Runs best with about 16-24GB of memory per 
   process. The number of processes is automatically estimated based on 
   available memory to optimize resource usage.

2. Surface Extraction: This stage does not require significant memory and is
   fully distributed across all available processorsor limited to the 
   defined number of processes using the "--multi" flag.

If "--multi" is set to a specific number (e.g., 8), the system still 
estimates memory-based constraints for segmentation parallelization. However,
the specified number of processes (e.g., 8) will be used for surface 
extraction, ensuring efficient parallelization across the two stages. The 
default setting is -1, which automatically estimates the number of
available processors.

## Longitudinal realignment (experimental)

For rigid realignment of a series of NIfTI volumes, use the realignment helper:

```bash
./scripts/realign_longitudinal.sh --help
```

New tuning flags in the Python realigner:
- `--max-fwhm-mm <FLOAT>`: maximum smoothing (FWHM, mm) for coarse alignment.
- `--no-intensity-scale`: disable SPM-like global intensity scaling.
- `--overlap-penalty-weight <FLOAT>`: penalize samples that fall outside the moving FOV.
- `--sample-strategy {grid,gradient}`: choose deterministic grid or edge-biased gradient sampling.
- `--grad-quantile <FLOAT>`: threshold for selecting high-gradient samples.


## Input
T1-weighted MRI images in NIfTI format (extension nii/nii.gz).

## Support
For issues and inquiries, contact [me](mailto:christian.gaser@uni-jena.de).

## License
T1Prep is distributed under the terms of the [Apache License](https://www.apache.org/licenses/LICENSE-2.0) 
as published by the Apache Software Foundation.

