Preprocessing¶
The preprocessing pipeline converts raw imaging data into simulation-ready head meshes. This is a one-time setup per subject — once complete, you can run unlimited simulations without repeating these steps.
graph LR
A[DICOM] -->|dcm2niix| B[NIfTI]
B -->|CHARM| C[Head Mesh]
C -->|subject_atlas| D[Atlas Parcellations]
B -->|recon-all| E[FreeSurfer Surfaces]
C -->|tissue analysis| F[Tissue Report]
style C fill:#2d5a27,stroke:#4a8,color:#fff
Full Pipeline¶
Run all preprocessing steps with a single call:
from tit.pre import run_pipeline
exit_code = run_pipeline(
project_dir="/data/my_project",
subject_ids=["001", "002"],
convert_dicom=True,
run_recon=True,
parallel_recon=True,
parallel_cores=4,
create_m2m=True,
run_tissue_analysis=True,
run_qsiprep=False,
run_qsirecon=False,
extract_dti=False,
run_subcortical_segmentations=False,
)
Selective Steps
Each boolean flag controls a specific step. Set only the ones you need — for example, if FreeSurfer recon-all is already done, set run_recon=False and create_m2m=True to run only CHARM (which also runs subject_atlas automatically).
Individual Steps¶
Each preprocessing step can be called independently for finer control:
from tit.pre import (
run_dicom_to_nifti,
run_recon_all,
run_charm,
run_tissue_analysis,
run_subcortical_segmentations,
run_qsiprep,
run_qsirecon,
extract_dti_tensor,
discover_subjects,
check_m2m_exists,
)
# Discover subjects from sourcedata/
subjects = discover_subjects("/data/my_project")
# Check if head mesh already exists
if not check_m2m_exists("/data/my_project", "001"):
run_charm("/data/my_project", "001", logger=my_logger)
Step Details¶
| Step | Function | What It Does |
|---|---|---|
| DICOM to NIfTI | run_dicom_to_nifti() |
Converts DICOM files to NIfTI format using dcm2niix |
| CHARM head mesh | run_charm() |
Creates SimNIBS-compatible head mesh from T1/T2 images |
| Subject atlas | run_subject_atlas() |
Creates atlas-based parcellations (a2009s, DK40, HCP_MMP1); runs automatically after CHARM in the pipeline |
| FreeSurfer recon-all | run_recon_all() |
Full cortical reconstruction and subcortical segmentation (takes 6-12 hours per subject) |
| Tissue analysis | run_tissue_analysis() |
Analyzes tissue thickness and volume (bone, CSF, skin) from the head mesh |
| Subcortical segmentation | run_subcortical_segmentations() |
Runs thalamic nuclei and hippocampal subfield segmentations standalone (also runs automatically at the end of run_recon_all) |
Compute Time
FreeSurfer recon-all is the most time-consuming step (6-12 hours per subject). Use parallel_recon=True with parallel_cores to process multiple subjects simultaneously.
DTI / Diffusion Pipeline¶
For anisotropic conductivity simulations, TI-Toolbox supports diffusion processing via QSIPrep/QSIRecon Docker containers:
from tit.pre import run_qsiprep, run_qsirecon, extract_dti_tensor
import logging
logger = logging.getLogger("my_pipeline")
# Run QSIPrep DWI preprocessing
run_qsiprep("/data/my_project", "001", logger=logger)
# Run QSIRecon reconstruction
run_qsirecon("/data/my_project", "001", logger=logger)
# Extract DTI tensor for SimNIBS anisotropic conductivity
extract_dti_tensor("/data/my_project", "001", logger=logger)
These steps can also be included in the full pipeline by setting run_qsiprep=True, run_qsirecon=True, and extract_dti=True. Optional configuration dicts (qsiprep_config, qsi_recon_config) control parameters such as output resolution, recon specs, and atlases.
BIDS Directory Structure¶
After preprocessing, your project follows this layout:
project_root/
├── sourcedata/ # Raw DICOM
├── sub-001/
│ └── anat/ # NIfTI files (T1w, T2w)
└── derivatives/
├── SimNIBS/sub-001/
│ └── m2m_001/ # Head mesh (simulation-ready)
│ └── segmentation/ # Atlas parcellations
├── freesurfer/sub-001/ # recon-all outputs
├── qsiprep/sub-001/ # QSIPrep DWI outputs (if run)
└── qsirecon/sub-001/ # QSIRecon tensor outputs (if run)
API Reference¶
tit.pre.structural.run_pipeline ¶
run_pipeline(project_dir: str, subject_ids: Iterable[str], *, convert_dicom: bool = False, run_recon: bool = False, parallel_recon: bool = False, parallel_cores: int | None = None, create_m2m: bool = False, run_tissue_analysis: bool = False, run_qsiprep: bool = False, run_qsirecon: bool = False, qsiprep_config: dict | None = None, qsi_recon_config: dict | None = None, extract_dti: bool = False, run_subcortical_segmentations: bool = False, debug: bool = False, stop_event: object | None = None, logger_callback: Callable | None = None, runner: CommandRunner | None = None) -> int
Run the preprocessing pipeline for one or more subjects.
Parameters¶
project_dir : str
BIDS project root.
subject_ids : iterable of str
Subject identifiers without the sub- prefix.
convert_dicom : bool, optional
Run DICOM to NIfTI conversion.
run_recon : bool, optional
Run FreeSurfer recon-all.
parallel_recon : bool, optional
Run recon-all in parallel across subjects.
parallel_cores : int, optional
Max parallel subjects for recon-all.
create_m2m : bool, optional
Run SimNIBS charm (also runs subject_atlas for .annot files).
run_tissue_analysis : bool, optional
Run tissue analysis pipeline.
run_qsiprep : bool, optional
Run QSIPrep DWI preprocessing via Docker.
run_qsirecon : bool, optional
Run QSIRecon reconstruction via Docker.
qsi_recon_specs : iterable of str, optional
QSIRecon reconstruction specs to run. Default: ['dipy_dki'].
extract_dti : bool, optional
Extract DTI tensor for SimNIBS anisotropic conductivity.
run_subcortical_segmentations : bool, optional
Run thalamic nuclei and hippocampal subfield segmentations (standalone).
debug : bool, optional
Enable verbose logging.
stop_event : object, optional
Event used to cancel running steps.
logger_callback : callable, optional
Callback used by GUI to capture log lines.
runner : CommandRunner, optional
Subprocess runner used to stream output.
Returns¶
int 0 on success, 1 on failure.
Source code in tit/pre/structural.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 | |
tit.pre.utils.discover_subjects ¶
Return sorted, deduplicated subject IDs found in a BIDS project tree.
Discovery order: 1. sourcedata/sub-/T1w/ or T2w/ — any subdir, NIfTI (.nii/.nii.gz), or .tgz 2. sourcedata/sub-/.tgz (compressed bundles at top level) 3. sub-/anat/T1w.nii[.gz] or T2w.nii[.gz] at project root
Source code in tit/pre/utils.py
tit.pre.utils.check_m2m_exists ¶
Return True if the SimNIBS m2m directory for subject_id already exists.
Path:
Source code in tit/pre/utils.py
tit.pre.dicom2nifti.run_dicom_to_nifti ¶
run_dicom_to_nifti(project_dir: str, subject_id: str, *, logger, runner: CommandRunner | None = None) -> None
Convert DICOMs to BIDS-compliant NIfTI for a subject.
Parameters¶
project_dir : str BIDS project root directory. subject_id : str Subject identifier without the 'sub-' prefix. logger : logging.Logger Logger for progress and command output. runner : CommandRunner, optional Subprocess runner for streaming output.
Source code in tit/pre/dicom2nifti.py
tit.pre.recon_all.run_recon_all ¶
run_recon_all(project_dir: str, subject_id: str, *, logger, parallel: bool = False, runner: CommandRunner | None = None) -> None
Run FreeSurfer recon-all for a subject.
Parameters¶
project_dir : str
BIDS project root.
subject_id : str
Subject identifier without the sub- prefix.
logger : logging.Logger
Logger used for progress and command output.
parallel : bool, optional
Use FreeSurfer OpenMP parallelization.
runner : CommandRunner, optional
Subprocess runner used to stream output.
Source code in tit/pre/recon_all.py
tit.pre.recon_all.run_subcortical_segmentations ¶
run_subcortical_segmentations(project_dir: str, subject_id: str, *, logger, runner: CommandRunner | None = None) -> None
Run thalamic nuclei and hippocampal subfield segmentations standalone.
Resolves the FreeSurfer subjects directory from the project layout and delegates to the internal segmentation runner. Intended for cases where recon-all has already completed and only the subcortical step needs to be (re-)run.
Parameters¶
project_dir : str
BIDS project root.
subject_id : str
Subject identifier without the sub- prefix.
logger : logging.Logger
Logger for progress output.
runner : CommandRunner, optional
Subprocess runner for streaming output.
Source code in tit/pre/recon_all.py
tit.pre.charm.run_charm ¶
run_charm(project_dir: str, subject_id: str, *, logger, runner: CommandRunner | None = None) -> None
Run SimNIBS charm for a subject.
Parameters¶
project_dir : str
BIDS project root.
subject_id : str
Subject identifier without the sub- prefix.
logger : logging.Logger
Logger used for progress and command output.
runner : CommandRunner, optional
Subprocess runner used to stream output.
Source code in tit/pre/charm.py
tit.pre.charm.run_subject_atlas ¶
run_subject_atlas(project_dir: str, subject_id: str, *, logger, runner: CommandRunner | None = None) -> None
Run subject_atlas to create .annot files for a subject.
This should be called after charm completes successfully. Generates all three atlases: a2009s, DK40, and HCP_MMP1.
Parameters¶
project_dir : str
BIDS project root.
subject_id : str
Subject identifier without the sub- prefix.
logger : logging.Logger
Logger used for progress and command output.
runner : CommandRunner, optional
Subprocess runner used to stream output.
Source code in tit/pre/charm.py
tit.pre.tissue_analyzer.run_tissue_analysis ¶
run_tissue_analysis(project_dir: str, subject_id: str, *, tissues: Iterable[str] = DEFAULT_TISSUES, logger: Logger, runner: CommandRunner | None = None) -> dict
Run tissue analysis for a subject.
Parameters¶
project_dir : str BIDS project root. subject_id : str Subject identifier without the 'sub-' prefix. tissues : iterable of str Tissue types to analyze (default: bone, csf, skin). logger : logging.Logger Logger for progress output. runner : CommandRunner, optional Not used, kept for API compatibility.
Returns¶
dict Analysis results for each tissue type.
Source code in tit/pre/tissue_analyzer.py
tit.pre.qsi.qsiprep.run_qsiprep ¶
run_qsiprep(project_dir: str, subject_id: str, *, logger: Logger, output_resolution: float = QSI_DEFAULT_OUTPUT_RESOLUTION, cpus: int | None = None, memory_gb: int | None = None, omp_threads: int = QSI_DEFAULT_OMP_THREADS, image_tag: str = QSI_DEFAULT_IMAGE_TAG, skip_bids_validation: bool = True, denoise_method: str = 'dwidenoise', unringing_method: str = 'mrdegibbs', runner: CommandRunner | None = None) -> None
Run QSIPrep preprocessing for a subject's DWI data.
This function spawns a QSIPrep Docker container as a sibling to the current SimNIBS container using Docker-out-of-Docker (DooD).
Parameters¶
project_dir : str Path to the BIDS project root directory. subject_id : str Subject identifier (without 'sub-' prefix). logger : logging.Logger Logger for status messages. output_resolution : float, optional Target output resolution in mm. Default: 2.0. cpus : int, optional Number of CPUs to allocate. Default: 8. memory_gb : int, optional Memory limit in GB. Default: 32. omp_threads : int, optional Number of OpenMP threads. Default: 1. image_tag : str, optional QSIPrep Docker image tag. Default: '1.1.1'. skip_bids_validation : bool, optional Skip BIDS validation. Default: True. denoise_method : str, optional Denoising method. Default: 'dwidenoise'. unringing_method : str, optional Unringing method. Default: 'mrdegibbs'. runner : CommandRunner | None, optional Command runner for subprocess execution.
Raises¶
PreprocessError If QSIPrep fails or prerequisites are not met.
Source code in tit/pre/qsi/qsiprep.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | |
tit.pre.qsi.qsirecon.run_qsirecon ¶
run_qsirecon(project_dir: str, subject_id: str, *, logger: Logger, recon_specs: list[str] | None = None, atlases: list[str] | None = None, use_gpu: bool = False, cpus: int | None = None, memory_gb: int | None = None, omp_threads: int = QSI_DEFAULT_OMP_THREADS, image_tag: str = QSI_DEFAULT_IMAGE_TAG, skip_odf_reports: bool = True, runner: CommandRunner | None = None) -> None
Run QSIRecon reconstruction for a subject's preprocessed DWI data.
This function spawns QSIRecon Docker containers as siblings to the current SimNIBS container using Docker-out-of-Docker (DooD).
QSIRecon requires QSIPrep output as input. Multiple reconstruction specs can be run sequentially.
Parameters¶
project_dir : str Path to the BIDS project root directory. subject_id : str Subject identifier (without 'sub-' prefix). logger : logging.Logger Logger for status messages. recon_specs : list[str] | None, optional List of reconstruction specifications to run. Default: ['mrtrix_multishell_msmt_ACT-fast']. Available specs: mrtrix_multishell_msmt_ACT-fast, multishell_scalarfest, dipy_dki, dipy_mapmri, amico_noddi, pyafq_tractometry, etc. atlases : list[str] | None, optional List of atlases for connectivity analysis. Default: ['Schaefer100', 'AAL116']. use_gpu : bool, optional Enable GPU acceleration. Default: False. cpus : int, optional Number of CPUs to allocate. Default: 8. memory_gb : int, optional Memory limit in GB. Default: 32. omp_threads : int, optional Number of OpenMP threads. Default: 1. image_tag : str, optional QSIRecon Docker image tag. Default: '1.1.1'. skip_odf_reports : bool, optional Skip ODF report generation. Default: True. runner : CommandRunner | None, optional Command runner for subprocess execution.
Raises¶
PreprocessError If QSIRecon fails or prerequisites are not met.
Source code in tit/pre/qsi/qsirecon.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | |
tit.pre.qsi.dti_extractor.extract_dti_tensor ¶
extract_dti_tensor(project_dir: str, subject_id: str, *, logger: Logger, source: str = 'qsirecon', skip_registration: bool = False) -> Path
Extract DTI tensor from QSIRecon output for SimNIBS.
This function finds the DTI tensor in QSIRecon outputs, converts it to SimNIBS format, and saves it to the m2m directory.
Parameters¶
project_dir : str Path to the BIDS project root directory. subject_id : str Subject identifier (without 'sub-' prefix). logger : logging.Logger Logger for status messages. source : str, optional Source of DTI tensor. Currently only 'qsirecon' is supported. Default: 'qsirecon'. skip_registration : bool, optional If True, skip registration to SimNIBS T1 space. Use this if the tensor is already in the correct space. Default: False.
Returns¶
Path Path to the extracted DTI tensor file in m2m directory.
Raises¶
PreprocessError If tensor extraction fails.
Source code in tit/pre/qsi/dti_extractor.py
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 | |