Statistics¶
The statistics module performs cluster-based permutation testing on MNI-space NIfTI volumes produced by the simulation pipeline. It supports two analysis types: group comparison (responders vs non-responders) and correlation (voxelwise correlation with a continuous outcome measure, ACES-style).
graph LR
NIFTI([MNI NIfTI Volumes]) --> TEST[Voxelwise Test]
CSV([Subject CSV]) --> TEST
TEST --> PERM[Permutation Engine]
PERM --> REPORT([Summary Report])
PERM --> PLOTS([Null Distribution Plots])
PERM --> MAPS([NIfTI Output Maps])
style NIFTI fill:#1a3a5c,stroke:#48a,color:#fff
style CSV fill:#1a3a5c,stroke:#48a,color:#fff
style TEST fill:#2d5a27,stroke:#4a8,color:#fff
style PERM fill:#2d5a27,stroke:#4a8,color:#fff
style REPORT fill:#1a5c4a,stroke:#4a8,color:#fff
style PLOTS fill:#1a5c4a,stroke:#4a8,color:#fff
style MAPS fill:#1a5c4a,stroke:#4a8,color:#fff
Group Comparison¶
Compare two groups (e.g., responders vs non-responders) using cluster-based permutation testing with voxelwise t-tests. Supports both unpaired (independent samples) and paired designs.
from tit.stats import GroupComparisonConfig, run_group_comparison
# Load subjects from CSV (columns: subject_id, simulation_name, response)
subjects = GroupComparisonConfig.load_subjects("/data/my_project/subjects.csv")
config = GroupComparisonConfig(
analysis_name="responder_comparison",
subjects=subjects,
test_type=GroupComparisonConfig.TestType.UNPAIRED,
alternative=GroupComparisonConfig.Alternative.TWO_SIDED,
n_permutations=5000,
alpha=0.05,
cluster_threshold=0.05,
cluster_stat=GroupComparisonConfig.ClusterStat.MASS,
tissue_type=GroupComparisonConfig.TissueType.GREY,
group1_name="Responders",
group2_name="Non-Responders",
)
result = run_group_comparison(config)
print(f"Significant clusters: {result.n_significant_clusters}")
print(f"Significant voxels: {result.n_significant_voxels}")
print(f"Analysis time: {result.analysis_time:.1f}s")
print(f"Output directory: {result.output_dir}")
Correlation¶
Test for voxelwise correlation between electric field magnitude and a continuous outcome measure (e.g., clinical effect size). Supports Pearson and Spearman correlation with optional subject-level weights.
from tit.stats import CorrelationConfig, run_correlation
# Load subjects from CSV (columns: subject_id, simulation_name, effect_size; optional: weight)
subjects = CorrelationConfig.load_subjects("/data/my_project/correlation_subjects.csv")
config = CorrelationConfig(
analysis_name="efield_outcome_correlation",
subjects=subjects,
correlation_type=CorrelationConfig.CorrelationType.PEARSON,
n_permutations=5000,
alpha=0.05,
cluster_threshold=0.05,
cluster_stat=CorrelationConfig.ClusterStat.MASS,
tissue_type=CorrelationConfig.TissueType.GREY,
use_weights=True,
effect_metric="Clinical Improvement",
)
result = run_correlation(config)
print(f"Significant clusters: {result.n_significant_clusters}")
print(f"Significant voxels: {result.n_significant_voxels}")
Configuration¶
Subject Definitions¶
Both analysis types use a nested Subject dataclass to define per-subject metadata. Subjects are typically loaded from CSV files via the load_subjects class method.
CSV columns: subject_id, simulation_name, response (0 or 1).
| Field | Type | Description |
|---|---|---|
subject_id |
str |
Subject identifier (e.g., "001") |
simulation_name |
str |
Name of the simulation to load |
response |
int |
Group assignment: 1 = group 1, 0 = group 2 |
CSV columns: subject_id, simulation_name, effect_size; optional: weight.
| Field | Type | Default | Description |
|---|---|---|---|
subject_id |
str |
Subject identifier | |
simulation_name |
str |
Name of the simulation to load | |
effect_size |
float |
Continuous outcome measure | |
weight |
float |
1.0 |
Subject-level weight |
Enums¶
| Enum | Values | Used By |
|---|---|---|
GroupComparisonConfig.TestType |
UNPAIRED, PAIRED |
Group comparison only |
GroupComparisonConfig.Alternative |
TWO_SIDED, GREATER, LESS |
Group comparison only |
CorrelationConfig.CorrelationType |
PEARSON, SPEARMAN |
Correlation only |
ClusterStat |
MASS, SIZE |
Both (nested as GroupComparisonConfig.ClusterStat / CorrelationConfig.ClusterStat) |
TissueType |
GREY, WHITE, ALL |
Both (nested as GroupComparisonConfig.TissueType / CorrelationConfig.TissueType) |
Statistical Parameters¶
These parameters are shared by both GroupComparisonConfig and CorrelationConfig:
| Parameter | Type | Default | Description |
|---|---|---|---|
analysis_name |
str |
Name for this analysis run | |
subjects |
list[Subject] |
List of subject definitions | |
cluster_threshold |
float |
0.05 |
Uncorrected p-value threshold for cluster formation |
cluster_stat |
ClusterStat |
MASS |
Cluster statistic: "mass" (sum of t-values) or "size" (voxel count) |
n_permutations |
int |
1000 |
Number of permutations for null distribution |
alpha |
float |
0.05 |
Family-wise error rate for cluster significance |
n_jobs |
int |
-1 |
Number of parallel jobs (-1 = all CPUs) |
tissue_type |
TissueType |
GREY |
Tissue mask: "grey", "white", or "all" |
nifti_file_pattern |
str \| None |
None |
Custom NIfTI filename pattern (auto-resolved from tissue_type if None) |
atlas_files |
list[str] |
[] |
Atlas filenames for overlap analysis |
NIfTI File Patterns¶
The tissue_type field determines which NIfTI files are loaded from each subject's simulation output:
| TissueType | Resolved Pattern |
|---|---|
GREY |
grey_{simulation_name}_TI_MNI_MNI_TI_max.nii.gz |
WHITE |
white_{simulation_name}_TI_MNI_MNI_TI_max.nii.gz |
ALL |
{simulation_name}_TI_MNI_MNI_TI_max.nii.gz |
Set nifti_file_pattern to override the auto-resolved pattern.
Output¶
Results are saved to derivatives/ti-toolbox/stats/<analysis_type>/<analysis_name>/ within the project directory. Both analysis types produce the following:
| File | Description |
|---|---|
significant_voxels_mask.nii.gz |
Binary mask of significant voxels |
pvalues_map.nii.gz |
Negative log10 p-value map |
permutation_null_distribution.pdf |
Null distribution with observed clusters |
cluster_size_mass_correlation.pdf |
Cluster size vs mass scatter plot |
analysis_summary.txt |
Text summary of results |
permutation_details.txt |
Per-permutation log |
*_analysis_*.log |
Timestamped run log |
Group comparison additionally produces:
| File | Description |
|---|---|
average_responders.nii.gz |
Mean field map for group 1 |
average_non_responders.nii.gz |
Mean field map for group 2 |
difference_map.nii.gz |
Group 1 minus group 2 difference map |
Correlation additionally produces:
| File | Description |
|---|---|
correlation_map.nii.gz |
Full voxelwise correlation map |
correlation_map_thresholded.nii.gz |
Correlation map masked to significant voxels |
t_statistics_map.nii.gz |
Voxelwise t-statistic map |
average_efield.nii.gz |
Mean electric field across all subjects |
Result Dataclasses¶
GroupComparisonResult¶
| Field | Type | Description |
|---|---|---|
success |
bool |
Whether the analysis completed |
output_dir |
str |
Path to the output directory |
n_responders |
int |
Number of group 1 subjects |
n_non_responders |
int |
Number of group 2 subjects |
n_significant_voxels |
int |
Count of significant voxels |
n_significant_clusters |
int |
Count of significant clusters |
cluster_threshold |
float |
Cluster statistic threshold from null distribution |
analysis_time |
float |
Total runtime in seconds |
clusters |
list |
Cluster details (size, MNI center) |
log_file |
str |
Path to the analysis log |
CorrelationResult¶
| Field | Type | Description |
|---|---|---|
success |
bool |
Whether the analysis completed |
output_dir |
str |
Path to the output directory |
n_subjects |
int |
Number of subjects |
n_significant_voxels |
int |
Count of significant voxels |
n_significant_clusters |
int |
Count of significant clusters |
cluster_threshold |
float |
Cluster statistic threshold from null distribution |
analysis_time |
float |
Total runtime in seconds |
clusters |
list |
Cluster details (size, MNI center, mean/peak r) |
log_file |
str |
Path to the analysis log |
API Reference¶
tit.stats.config.GroupComparisonConfig
dataclass
¶
GroupComparisonConfig(analysis_name: str, subjects: list[Subject], test_type: TestType = UNPAIRED, alternative: Alternative = TWO_SIDED, cluster_threshold: float = 0.05, cluster_stat: ClusterStat = MASS, n_permutations: int = 1000, alpha: float = 0.05, n_jobs: int = -1, tissue_type: TissueType = GREY, nifti_file_pattern: str | None = None, group1_name: str = 'Responders', group2_name: str = 'Non-Responders', value_metric: str = 'Current Intensity', atlas_files: list[str] = list())
Configuration for cluster-based permutation testing between two groups.
Compares voxelwise field intensities between responders and non-responders using a t-test with cluster-based permutation correction for multiple comparisons.
Attributes¶
analysis_name : str
Human-readable name for this analysis run.
subjects : list of Subject
Subject entries, each labelled as responder (1) or non-responder (0).
test_type : TestType
Whether to use an unpaired or paired t-test.
alternative : Alternative
Sidedness of the test hypothesis.
cluster_threshold : float
Uncorrected p-value threshold for forming clusters.
cluster_stat : ClusterStat
Cluster-level statistic used for permutation testing
("mass" or "size").
n_permutations : int
Number of permutations for the null distribution.
alpha : float
Family-wise error rate for significance.
n_jobs : int
Number of parallel workers (-1 for all CPUs).
tissue_type : TissueType
Which tissue compartment to analyze.
nifti_file_pattern : str or None
Filename pattern for subject NIfTI files. If None, derived
automatically from tissue_type.
group1_name : str
Display label for the responder group.
group2_name : str
Display label for the non-responder group.
value_metric : str
Label for the field value axis in plots.
atlas_files : list of str
Atlas filenames for overlap analysis (looked up in the bundled
atlas directory).
See Also¶
GroupComparisonResult : Result container returned by the analysis. run_group_comparison : Orchestration function that consumes this config.
Subject
dataclass
¶
A single subject in a group comparison analysis.
Attributes¶
subject_id : str
Subject identifier (without sub- prefix).
simulation_name : str
Name of the simulation to load for this subject.
response : int
Group label -- 1 for responder, 0 for non-responder.
load_subjects
classmethod
¶
Load group comparison subjects from a CSV file.
Expected columns: subject_id, simulation_name, response
(0 or 1). The sub- prefix is stripped from subject IDs
automatically.
Parameters¶
csv_path : str Path to a CSV file with the required columns.
Returns¶
list of Subject Subject instances parsed from the CSV rows.
Raises¶
ValueError If required columns are missing from the CSV.
Source code in tit/stats/config.py
tit.stats.config.GroupComparisonResult
dataclass
¶
GroupComparisonResult(success: bool, output_dir: str, n_responders: int, n_non_responders: int, n_significant_voxels: int, n_significant_clusters: int, cluster_threshold: float, analysis_time: float, clusters: list, log_file: str)
Result of a group comparison permutation test.
Attributes¶
success : bool Whether the analysis completed without error. output_dir : str Absolute path to the directory containing all outputs (NIfTI maps, plots, summary text, log). n_responders : int Number of responder subjects included. n_non_responders : int Number of non-responder subjects included. n_significant_voxels : int Total voxels surviving cluster-corrected threshold. n_significant_clusters : int Number of spatially contiguous clusters that survived permutation correction. cluster_threshold : float Cluster-level statistic threshold derived from the permutation null distribution at the requested alpha. analysis_time : float Wall-clock duration of the full analysis in seconds. clusters : list of dict One entry per significant cluster, containing size, mass, peak coordinates, and atlas overlap info. log_file : str Absolute path to the analysis log file.
See Also¶
GroupComparisonConfig : Configuration that produced this result. run_group_comparison : Function that returns this result.
tit.stats.config.CorrelationConfig
dataclass
¶
CorrelationConfig(analysis_name: str, subjects: list[Subject], correlation_type: CorrelationType = PEARSON, cluster_threshold: float = 0.05, cluster_stat: ClusterStat = MASS, n_permutations: int = 1000, alpha: float = 0.05, n_jobs: int = -1, use_weights: bool = True, tissue_type: TissueType = GREY, nifti_file_pattern: str | None = None, effect_metric: str = 'Effect Size', field_metric: str = 'Electric Field Magnitude', atlas_files: list[str] = list())
Configuration for correlation-based cluster permutation testing.
Tests voxelwise correlation between brain field intensities and a continuous behavioral or clinical measure (effect size) across subjects, with cluster-based permutation correction for multiple comparisons.
Attributes¶
analysis_name : str
Human-readable name for this analysis run.
subjects : list of Subject
Subject entries with associated effect sizes.
correlation_type : CorrelationType
Pearson or Spearman rank correlation.
cluster_threshold : float
Uncorrected p-value threshold for forming clusters.
cluster_stat : ClusterStat
Cluster-level statistic used for permutation testing
("mass" or "size").
n_permutations : int
Number of permutations for the null distribution.
alpha : float
Family-wise error rate for significance.
n_jobs : int
Number of parallel workers (-1 for all CPUs).
use_weights : bool
Whether to apply per-subject weights during correlation.
tissue_type : TissueType
Which tissue compartment to analyze.
nifti_file_pattern : str or None
Filename pattern for subject NIfTI files. If None, derived
automatically from tissue_type.
effect_metric : str
Label for the behavioral/clinical variable in plots.
field_metric : str
Label for the field intensity axis in plots.
atlas_files : list of str
Atlas filenames for overlap analysis (looked up in the bundled
atlas directory).
See Also¶
CorrelationResult : Result container returned by the analysis. run_correlation : Orchestration function that consumes this config.
Subject
dataclass
¶
A single subject in a correlation analysis.
Attributes¶
subject_id : str
Subject identifier (without sub- prefix).
simulation_name : str
Name of the simulation to load for this subject.
effect_size : float
Continuous behavioral or clinical measure to correlate with
field intensity.
weight : float
Per-subject weight (default 1.0).
load_subjects
classmethod
¶
Load correlation subjects from a CSV file.
Expected columns: subject_id, simulation_name,
effect_size. Optional column: weight. Rows with NaN
subject_id or effect_size are silently skipped. The sub-
prefix is stripped from subject IDs automatically.
Parameters¶
csv_path : str Path to a CSV file with the required columns.
Returns¶
list of Subject Subject instances parsed from valid CSV rows.
Raises¶
ValueError If required columns are missing or no valid subjects are found.
Source code in tit/stats/config.py
tit.stats.config.CorrelationResult
dataclass
¶
CorrelationResult(success: bool, output_dir: str, n_subjects: int, n_significant_voxels: int, n_significant_clusters: int, cluster_threshold: float, analysis_time: float, clusters: list, log_file: str)
Result of a correlation-based cluster permutation test.
Attributes¶
success : bool Whether the analysis completed without error. output_dir : str Absolute path to the directory containing all outputs (NIfTI maps, plots, summary text, log). n_subjects : int Number of subjects included in the analysis. n_significant_voxels : int Total voxels surviving cluster-corrected threshold. n_significant_clusters : int Number of spatially contiguous clusters that survived permutation correction. cluster_threshold : float Cluster-level statistic threshold derived from the permutation null distribution at the requested alpha. analysis_time : float Wall-clock duration of the full analysis in seconds. clusters : list of dict One entry per significant cluster, containing size, mass, peak coordinates, mean/peak correlation coefficients, and atlas overlap info. log_file : str Absolute path to the analysis log file.
See Also¶
CorrelationConfig : Configuration that produced this result. run_correlation : Function that returns this result.
tit.stats.permutation.run_group_comparison ¶
run_group_comparison(config: GroupComparisonConfig, callback_handler=None, stop_callback=None) -> GroupComparisonResult
Run cluster-based permutation testing for group comparison.
Loads responder and non-responder NIfTI volumes, performs voxelwise t-tests, applies cluster-based permutation correction, generates diagnostic plots, and saves all outputs to the BIDS derivatives tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
GroupComparisonConfig
|
Fully specified group comparison configuration. |
required |
callback_handler
|
Optional |
None
|
|
stop_callback
|
Optional callable that returns |
None
|
Returns:
| Type | Description |
|---|---|
GroupComparisonResult
|
A |
GroupComparisonResult
|
including paths to all generated output files. |
Raises:
| Type | Description |
|---|---|
KeyboardInterrupt
|
If |
Source code in tit/stats/permutation.py
tit.stats.permutation.run_correlation ¶
run_correlation(config: CorrelationConfig, callback_handler=None, stop_callback=None) -> CorrelationResult
Run cluster-based permutation testing for correlation (ACES-style).
Loads subject NIfTI volumes and effect sizes, computes voxelwise correlation, applies cluster-based permutation correction, generates diagnostic plots, and saves all outputs to the BIDS derivatives tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
CorrelationConfig
|
Fully specified correlation configuration. |
required |
callback_handler
|
Optional |
None
|
|
stop_callback
|
Optional callable that returns |
None
|
Returns:
| Type | Description |
|---|---|
CorrelationResult
|
A |
CorrelationResult
|
paths to all generated output files. |
Raises:
| Type | Description |
|---|---|
KeyboardInterrupt
|
If |
Source code in tit/stats/permutation.py
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 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 | |
tit.stats.engine.PermutationEngine ¶
PermutationEngine(*, cluster_threshold: float = 0.05, n_permutations: int = 1000, alpha: float = 0.05, cluster_stat: str = 'mass', alternative: str = 'two-sided', n_jobs: int = -1, log: Logger | None = None)
Master class for cluster-based permutation testing.
Stores all control parameters as self.* so methods only need data arrays.
Source code in tit/stats/engine.py
correct_groups ¶
correct_groups(responders, non_responders, *, p_values, t_statistics, valid_mask, test_type: str = 'unpaired', perm_log_file: str | None = None, subject_ids_resp: list | None = None, subject_ids_non_resp: list | None = None) -> tuple
Cluster-based permutation correction for group comparison.
Returns (sig_mask, threshold, sig_clusters, null_dist, observed_clusters,
correlation_data).
Source code in tit/stats/engine.py
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 | |
correct_correlation ¶
correct_correlation(subject_data, effect_sizes, *, r_values, t_statistics, p_values, valid_mask, correlation_type: str = 'pearson', weights=None, perm_log_file: str | None = None, subject_ids: list | None = None) -> tuple
Cluster-based permutation correction for correlation analysis.
Returns (sig_mask, threshold, sig_clusters, null_dist, observed_clusters,
correlation_data).
Source code in tit/stats/engine.py
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 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 | |
tit.stats.engine.cluster_analysis ¶
Connected-component analysis with MNI coordinate mapping.
Returns a list of cluster dicts sorted by size (descending).
Source code in tit/stats/engine.py
tit.stats.nifti.load_subject_nifti_ti_toolbox ¶
load_subject_nifti_ti_toolbox(subject_id: str, simulation_name: str, nifti_file_pattern: str = 'grey_{simulation_name}_TI_MNI_MNI_TI_max.nii.gz', dtype=float32) -> tuple[ndarray, Nifti1Image, str]
Load a single subject's NIfTI file from TI-Toolbox BIDS structure.
Parameters¶
subject_id : str
Subject identifier (e.g. '070').
simulation_name : str
Simulation folder name (e.g. 'ICP_RHIPPO').
nifti_file_pattern : str, optional
Filename pattern with {subject_id} / {simulation_name}
placeholders.
dtype : numpy dtype, optional
Data type for the returned array. Default is np.float32.
Returns¶
data : numpy.ndarray 3-D array of voxel values. img : nibabel.Nifti1Image The loaded NIfTI image (useful for affine / header). filepath : str Absolute path of the loaded file.
Raises¶
FileNotFoundError If the resolved NIfTI path does not exist.
Source code in tit/stats/nifti.py
tit.stats.nifti.load_group_data_ti_toolbox ¶
load_group_data_ti_toolbox(subject_configs: list[dict], nifti_file_pattern: str = 'grey_{simulation_name}_TI_MNI_MNI_TI_max.nii.gz', dtype=float32) -> tuple[ndarray, Nifti1Image, list[str]]
Load and stack multiple subjects into a 4-D array.
Parameters¶
subject_configs : list of dict
Each dict must contain 'subject_id' and 'simulation_name'
keys (e.g. {'subject_id': '070', 'simulation_name': 'ICP_RHIPPO'}).
nifti_file_pattern : str, optional
Filename pattern forwarded to :func:load_subject_nifti_ti_toolbox.
dtype : numpy dtype, optional
Data type for the returned arrays. Default is np.float32.
Returns¶
data_4d : numpy.ndarray
Shape (X, Y, Z, n_subjects).
template_img : nibabel.Nifti1Image
Image from the first subject (affine / header reference).
subject_ids : list of str
Subject identifiers in the same order as the last axis of
data_4d.
Raises¶
ValueError If no subjects could be loaded.