pytfce 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pytfce-0.1.0/LICENSE +21 -0
- pytfce-0.1.0/PKG-INFO +129 -0
- pytfce-0.1.0/README.md +94 -0
- pytfce-0.1.0/pyproject.toml +45 -0
- pytfce-0.1.0/setup.cfg +4 -0
- pytfce-0.1.0/src/pytfce/__init__.py +20 -0
- pytfce-0.1.0/src/pytfce/config.py +54 -0
- pytfce-0.1.0/src/pytfce/core/__init__.py +12 -0
- pytfce-0.1.0/src/pytfce/core/etfce.py +182 -0
- pytfce-0.1.0/src/pytfce/core/grf.py +109 -0
- pytfce-0.1.0/src/pytfce/core/ptfce_baseline.py +579 -0
- pytfce-0.1.0/src/pytfce/core/ptfce_etfce.py +235 -0
- pytfce-0.1.0/src/pytfce/core/ptfce_exact.py +253 -0
- pytfce-0.1.0/src/pytfce/core/smoothness.py +187 -0
- pytfce-0.1.0/src/pytfce/core/tfce.py +52 -0
- pytfce-0.1.0/src/pytfce/utils/__init__.py +1 -0
- pytfce-0.1.0/src/pytfce/utils/metrics.py +40 -0
- pytfce-0.1.0/src/pytfce/utils/phantoms.py +195 -0
- pytfce-0.1.0/src/pytfce/utils/plotting.py +406 -0
- pytfce-0.1.0/src/pytfce/utils/tui.py +171 -0
- pytfce-0.1.0/src/pytfce.egg-info/PKG-INFO +129 -0
- pytfce-0.1.0/src/pytfce.egg-info/SOURCES.txt +27 -0
- pytfce-0.1.0/src/pytfce.egg-info/dependency_links.txt +1 -0
- pytfce-0.1.0/src/pytfce.egg-info/requires.txt +16 -0
- pytfce-0.1.0/src/pytfce.egg-info/top_level.txt +1 -0
- pytfce-0.1.0/tests/test_grf.py +145 -0
- pytfce-0.1.0/tests/test_ptfce.py +121 -0
- pytfce-0.1.0/tests/test_smoothness.py +106 -0
- pytfce-0.1.0/tests/test_tfce.py +61 -0
pytfce-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Don Yin, Hao Chen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
pytfce-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pytfce
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Fast probabilistic Threshold-Free Cluster Enhancement in Python
|
|
5
|
+
Author-email: Don Yin <dy323@cam.ac.uk>, Hao Chen <hc666@cam.ac.uk>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Don-Yin/pytfce
|
|
8
|
+
Project-URL: Repository, https://github.com/Don-Yin/pytfce
|
|
9
|
+
Project-URL: Issues, https://github.com/Don-Yin/pytfce/issues
|
|
10
|
+
Keywords: neuroimaging,TFCE,pTFCE,VBM,statistics,GRF
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: numpy
|
|
23
|
+
Requires-Dist: scipy
|
|
24
|
+
Requires-Dist: connected-components-3d
|
|
25
|
+
Provides-Extra: plotting
|
|
26
|
+
Requires-Dist: matplotlib; extra == "plotting"
|
|
27
|
+
Provides-Extra: tui
|
|
28
|
+
Requires-Dist: rich; extra == "tui"
|
|
29
|
+
Provides-Extra: all
|
|
30
|
+
Requires-Dist: matplotlib; extra == "all"
|
|
31
|
+
Requires-Dist: rich; extra == "all"
|
|
32
|
+
Provides-Extra: test
|
|
33
|
+
Requires-Dist: pytest; extra == "test"
|
|
34
|
+
Dynamic: license-file
|
|
35
|
+
|
|
36
|
+
# pytfce
|
|
37
|
+
|
|
38
|
+
Fast probabilistic Threshold-Free Cluster Enhancement in Python.
|
|
39
|
+
|
|
40
|
+
## Overview
|
|
41
|
+
|
|
42
|
+
`pytfce` is a pure-Python package for probabilistic TFCE (pTFCE), providing analytical inference on neuroimaging statistical maps without permutation testing. It implements a baseline pTFCE faithful to the original R package (Spisák et al. 2019) and a novel hybrid eTFCE–GRF that combines union-find cluster retrieval with analytical GRF p-values. On real brain data (~2M voxels), `pytfce` is 73× faster than the R pTFCE package while producing concordant results.
|
|
43
|
+
|
|
44
|
+
## Installation
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
# from PyPI (not yet published)
|
|
48
|
+
pip install pytfce
|
|
49
|
+
|
|
50
|
+
# development install
|
|
51
|
+
git clone https://github.com/your-org/pytfce.git
|
|
52
|
+
cd pytfce
|
|
53
|
+
pip install -e .
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
**Dependencies:** NumPy, SciPy, connected-components-3d (installed automatically).
|
|
57
|
+
|
|
58
|
+
## Quick start
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
import nibabel as nib
|
|
62
|
+
from pytfce import ptfce_baseline, ptfce_exact
|
|
63
|
+
|
|
64
|
+
img = nib.load("zstat1.nii.gz")
|
|
65
|
+
Z = img.get_fdata()
|
|
66
|
+
mask = Z != 0 # or load a proper brain mask
|
|
67
|
+
|
|
68
|
+
# --- baseline pTFCE (fast, matches R pTFCE) ---
|
|
69
|
+
result = ptfce_baseline(Z, mask)
|
|
70
|
+
|
|
71
|
+
# --- hybrid eTFCE–GRF (exact cluster retrieval) ---
|
|
72
|
+
result = ptfce_exact(Z, mask)
|
|
73
|
+
|
|
74
|
+
# result keys:
|
|
75
|
+
# result["p"] — enhanced p-values (3-D array)
|
|
76
|
+
# result["logp"] — −log10(p) for visualization
|
|
77
|
+
# result["Z_enhanced"] — enhanced Z-scores
|
|
78
|
+
# result["smoothness"] — estimated smoothness dict
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Variants
|
|
82
|
+
|
|
83
|
+
| Variant | Method | Speed (2M vox) | Best for |
|
|
84
|
+
|---------|--------|---------------:|----------|
|
|
85
|
+
| `ptfce_baseline` | pTFCE (threshold grid + CCL) | ~5 s | Standard use, small–medium volumes |
|
|
86
|
+
| `ptfce_exact` | eTFCE–GRF (union-find + GRF) | ~84 s | Large volumes, finer threshold grids |
|
|
87
|
+
|
|
88
|
+
Both variants use identical GRF p-values and aggregation. The baseline sweeps a threshold grid with connected-component labelling at each level; the hybrid uses a single union-find sweep, eliminating discretisation error at the cost of higher constant overhead.
|
|
89
|
+
|
|
90
|
+
## Validation
|
|
91
|
+
|
|
92
|
+
**Spatial detection** — Phantom study (64³ volume, 80 subjects, 3 embedded blobs). All pTFCE variants achieve Dice = 1.0:
|
|
93
|
+
|
|
94
|
+

|
|
95
|
+
|
|
96
|
+
**Runtime** — Log-scale comparison across five methods (emulated phantom). Py pTFCE runs in 0.34 s vs 21.7 s for R pTFCE (64× speedup):
|
|
97
|
+
|
|
98
|
+

|
|
99
|
+
|
|
100
|
+
## API reference
|
|
101
|
+
|
|
102
|
+
| Function | Description |
|
|
103
|
+
|----------|-------------|
|
|
104
|
+
| `ptfce_baseline(Z, mask, ...)` | Baseline pTFCE with LUT-accelerated GRF p-values |
|
|
105
|
+
| `ptfce_exact(Z, mask, ...)` | Hybrid eTFCE–GRF via union-find + analytical GRF |
|
|
106
|
+
| `estimate_smoothness(Z, mask)` | Estimate image smoothness (FWHM) from a Z-score map |
|
|
107
|
+
| `estimate_smoothness_from_residuals(Y, X, mask)` | Estimate smoothness from GLM residuals |
|
|
108
|
+
| `fwer_z_threshold(n_resels, alpha)` | GRF Euler-characteristic FWER Z-threshold |
|
|
109
|
+
| `pvox_clust(V, Rd, c, h)` | P(Z ≥ h \| cluster_size = c) via GRF Bayes' rule |
|
|
110
|
+
| `aggregate_logpvals_vec(s, delta)` | Vectorised Q-function for log-probability aggregation |
|
|
111
|
+
|
|
112
|
+
## Citation
|
|
113
|
+
|
|
114
|
+
If you use `pytfce` in your research, please cite:
|
|
115
|
+
|
|
116
|
+
```bibtex
|
|
117
|
+
@article{pytfce2026,
|
|
118
|
+
author = {Yin, Don and Chen, Hao},
|
|
119
|
+
title = {pytfce: {Fast} probabilistic {Threshold-Free Cluster Enhancement}
|
|
120
|
+
in {Python}},
|
|
121
|
+
journal = {Journal of Open Source Software},
|
|
122
|
+
year = {2026},
|
|
123
|
+
doi = {10.21105/joss.XXXXX}
|
|
124
|
+
}
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## License
|
|
128
|
+
|
|
129
|
+
MIT
|
pytfce-0.1.0/README.md
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# pytfce
|
|
2
|
+
|
|
3
|
+
Fast probabilistic Threshold-Free Cluster Enhancement in Python.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
`pytfce` is a pure-Python package for probabilistic TFCE (pTFCE), providing analytical inference on neuroimaging statistical maps without permutation testing. It implements a baseline pTFCE faithful to the original R package (Spisák et al. 2019) and a novel hybrid eTFCE–GRF that combines union-find cluster retrieval with analytical GRF p-values. On real brain data (~2M voxels), `pytfce` is 73× faster than the R pTFCE package while producing concordant results.
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
# from PyPI (not yet published)
|
|
13
|
+
pip install pytfce
|
|
14
|
+
|
|
15
|
+
# development install
|
|
16
|
+
git clone https://github.com/your-org/pytfce.git
|
|
17
|
+
cd pytfce
|
|
18
|
+
pip install -e .
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
**Dependencies:** NumPy, SciPy, connected-components-3d (installed automatically).
|
|
22
|
+
|
|
23
|
+
## Quick start
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
import nibabel as nib
|
|
27
|
+
from pytfce import ptfce_baseline, ptfce_exact
|
|
28
|
+
|
|
29
|
+
img = nib.load("zstat1.nii.gz")
|
|
30
|
+
Z = img.get_fdata()
|
|
31
|
+
mask = Z != 0 # or load a proper brain mask
|
|
32
|
+
|
|
33
|
+
# --- baseline pTFCE (fast, matches R pTFCE) ---
|
|
34
|
+
result = ptfce_baseline(Z, mask)
|
|
35
|
+
|
|
36
|
+
# --- hybrid eTFCE–GRF (exact cluster retrieval) ---
|
|
37
|
+
result = ptfce_exact(Z, mask)
|
|
38
|
+
|
|
39
|
+
# result keys:
|
|
40
|
+
# result["p"] — enhanced p-values (3-D array)
|
|
41
|
+
# result["logp"] — −log10(p) for visualization
|
|
42
|
+
# result["Z_enhanced"] — enhanced Z-scores
|
|
43
|
+
# result["smoothness"] — estimated smoothness dict
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Variants
|
|
47
|
+
|
|
48
|
+
| Variant | Method | Speed (2M vox) | Best for |
|
|
49
|
+
|---------|--------|---------------:|----------|
|
|
50
|
+
| `ptfce_baseline` | pTFCE (threshold grid + CCL) | ~5 s | Standard use, small–medium volumes |
|
|
51
|
+
| `ptfce_exact` | eTFCE–GRF (union-find + GRF) | ~84 s | Large volumes, finer threshold grids |
|
|
52
|
+
|
|
53
|
+
Both variants use identical GRF p-values and aggregation. The baseline sweeps a threshold grid with connected-component labelling at each level; the hybrid uses a single union-find sweep, eliminating discretisation error at the cost of higher constant overhead.
|
|
54
|
+
|
|
55
|
+
## Validation
|
|
56
|
+
|
|
57
|
+
**Spatial detection** — Phantom study (64³ volume, 80 subjects, 3 embedded blobs). All pTFCE variants achieve Dice = 1.0:
|
|
58
|
+
|
|
59
|
+

|
|
60
|
+
|
|
61
|
+
**Runtime** — Log-scale comparison across five methods (emulated phantom). Py pTFCE runs in 0.34 s vs 21.7 s for R pTFCE (64× speedup):
|
|
62
|
+
|
|
63
|
+

|
|
64
|
+
|
|
65
|
+
## API reference
|
|
66
|
+
|
|
67
|
+
| Function | Description |
|
|
68
|
+
|----------|-------------|
|
|
69
|
+
| `ptfce_baseline(Z, mask, ...)` | Baseline pTFCE with LUT-accelerated GRF p-values |
|
|
70
|
+
| `ptfce_exact(Z, mask, ...)` | Hybrid eTFCE–GRF via union-find + analytical GRF |
|
|
71
|
+
| `estimate_smoothness(Z, mask)` | Estimate image smoothness (FWHM) from a Z-score map |
|
|
72
|
+
| `estimate_smoothness_from_residuals(Y, X, mask)` | Estimate smoothness from GLM residuals |
|
|
73
|
+
| `fwer_z_threshold(n_resels, alpha)` | GRF Euler-characteristic FWER Z-threshold |
|
|
74
|
+
| `pvox_clust(V, Rd, c, h)` | P(Z ≥ h \| cluster_size = c) via GRF Bayes' rule |
|
|
75
|
+
| `aggregate_logpvals_vec(s, delta)` | Vectorised Q-function for log-probability aggregation |
|
|
76
|
+
|
|
77
|
+
## Citation
|
|
78
|
+
|
|
79
|
+
If you use `pytfce` in your research, please cite:
|
|
80
|
+
|
|
81
|
+
```bibtex
|
|
82
|
+
@article{pytfce2026,
|
|
83
|
+
author = {Yin, Don and Chen, Hao},
|
|
84
|
+
title = {pytfce: {Fast} probabilistic {Threshold-Free Cluster Enhancement}
|
|
85
|
+
in {Python}},
|
|
86
|
+
journal = {Journal of Open Source Software},
|
|
87
|
+
year = {2026},
|
|
88
|
+
doi = {10.21105/joss.XXXXX}
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## License
|
|
93
|
+
|
|
94
|
+
MIT
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=64", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pytfce"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Fast probabilistic Threshold-Free Cluster Enhancement in Python"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = {text = "MIT"}
|
|
12
|
+
authors = [
|
|
13
|
+
{name = "Don Yin", email = "dy323@cam.ac.uk"},
|
|
14
|
+
{name = "Hao Chen", email = "hc666@cam.ac.uk"},
|
|
15
|
+
]
|
|
16
|
+
keywords = ["neuroimaging", "TFCE", "pTFCE", "VBM", "statistics", "GRF"]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Development Status :: 4 - Beta",
|
|
19
|
+
"Intended Audience :: Science/Research",
|
|
20
|
+
"License :: OSI Approved :: MIT License",
|
|
21
|
+
"Programming Language :: Python :: 3",
|
|
22
|
+
"Programming Language :: Python :: 3.10",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Topic :: Scientific/Engineering :: Medical Science Apps.",
|
|
26
|
+
]
|
|
27
|
+
dependencies = [
|
|
28
|
+
"numpy",
|
|
29
|
+
"scipy",
|
|
30
|
+
"connected-components-3d",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[project.optional-dependencies]
|
|
34
|
+
plotting = ["matplotlib"]
|
|
35
|
+
tui = ["rich"]
|
|
36
|
+
all = ["matplotlib", "rich"]
|
|
37
|
+
test = ["pytest"]
|
|
38
|
+
|
|
39
|
+
[project.urls]
|
|
40
|
+
Homepage = "https://github.com/Don-Yin/pytfce"
|
|
41
|
+
Repository = "https://github.com/Don-Yin/pytfce"
|
|
42
|
+
Issues = "https://github.com/Don-Yin/pytfce/issues"
|
|
43
|
+
|
|
44
|
+
[tool.setuptools.packages.find]
|
|
45
|
+
where = ["src"]
|
pytfce-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""pTFCE: probabilistic Threshold-Free Cluster Enhancement.
|
|
2
|
+
|
|
3
|
+
Pure-Python reimplementation of pTFCE (Spisák et al. 2019),
|
|
4
|
+
with the hybrid eTFCE–GRF variant (union-find + analytical GRF p-values).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from pytfce.core.ptfce_baseline import ptfce as ptfce_baseline
|
|
8
|
+
from pytfce.core.ptfce_exact import ptfce_exact
|
|
9
|
+
from pytfce.core.smoothness import estimate_smoothness, estimate_smoothness_from_residuals, fwer_z_threshold
|
|
10
|
+
from pytfce.core.grf import pvox_clust, aggregate_logpvals_vec
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"ptfce_baseline",
|
|
14
|
+
"ptfce_exact",
|
|
15
|
+
"estimate_smoothness",
|
|
16
|
+
"estimate_smoothness_from_residuals",
|
|
17
|
+
"fwer_z_threshold",
|
|
18
|
+
"pvox_clust",
|
|
19
|
+
"aggregate_logpvals_vec",
|
|
20
|
+
]
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Experiment configuration — single source of truth for all parameters.
|
|
2
|
+
|
|
3
|
+
Import this module from any experiment script to get consistent settings.
|
|
4
|
+
Edit here to change conditions globally.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
# ── phantom generation ─────────────────────────────────────────────
|
|
10
|
+
N_SUBJECTS = 80
|
|
11
|
+
SMOOTH_SIGMA = 1.5
|
|
12
|
+
SEED = 42
|
|
13
|
+
SHAPE_DEFAULT = (64, 64, 64)
|
|
14
|
+
|
|
15
|
+
# ── volume-size scaling ablation ───────────────────────────────────
|
|
16
|
+
VOLUME_SIZES = {
|
|
17
|
+
"small": (32, 32, 32),
|
|
18
|
+
"medium": (48, 48, 48),
|
|
19
|
+
"default": (64, 64, 64),
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
# ── signal amplitude ablation ──────────────────────────────────────
|
|
23
|
+
AMPLITUDES = {
|
|
24
|
+
"weak": 0.3,
|
|
25
|
+
"medium": 0.5,
|
|
26
|
+
"strong": 0.8,
|
|
27
|
+
"very_strong": 1.2,
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
# ── signal shape ablation ──────────────────────────────────────────
|
|
31
|
+
# (imported at runtime to avoid circular deps)
|
|
32
|
+
SHAPE_BLOBS = {
|
|
33
|
+
"small": [{"c": (32, 32, 32), "r": (4, 4, 4)}],
|
|
34
|
+
"large": [{"c": (32, 32, 32), "r": (8, 8, 8)}],
|
|
35
|
+
"elongated": [{"c": (32, 32, 32), "r": (3, 3, 12)}],
|
|
36
|
+
"multi": [{"c": (22, 32, 32), "r": (5, 5, 5)},
|
|
37
|
+
{"c": (42, 32, 32), "r": (3, 3, 3)},
|
|
38
|
+
{"c": (32, 22, 32), "r": (4, 4, 4)}],
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
# ── pTFCE core ─────────────────────────────────────────────────────
|
|
42
|
+
NH = 100
|
|
43
|
+
Z_EST_THR = 1.3
|
|
44
|
+
CONNECTIVITY = 6
|
|
45
|
+
LUT_DENSITY = 60
|
|
46
|
+
|
|
47
|
+
# ── TFCE permutation benchmarks ───────────────────────────────────
|
|
48
|
+
TFCE_PERM_COUNTS = [200, 500, 1000]
|
|
49
|
+
|
|
50
|
+
# ── parameter optimization ─────────────────────────────────────────
|
|
51
|
+
OPT_LR = 0.01
|
|
52
|
+
OPT_STEPS = 30
|
|
53
|
+
OPT_NH = 50
|
|
54
|
+
OPT_DIFFUSION_STEPS = 10
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Core pTFCE algorithms and GRF computations."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _empty_result(Z: np.ndarray) -> dict:
|
|
7
|
+
"""Fallback result when there are no supra-threshold voxels."""
|
|
8
|
+
return {
|
|
9
|
+
"p": np.ones_like(Z), "logp": np.zeros_like(Z),
|
|
10
|
+
"Z_enhanced": np.zeros_like(Z), "smoothness": {},
|
|
11
|
+
"fwer_z_thresh": np.inf, "diagnostics": {},
|
|
12
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""Pure eTFCE: exact TFCE scores via union-find cluster retrieval.
|
|
2
|
+
|
|
3
|
+
Reimplements the score computation from:
|
|
4
|
+
Chen, X., Weeda, W., Nichols, T.E., & Goeman, J.J. (2026).
|
|
5
|
+
eTFCE: Exact Threshold-Free Cluster Enhancement via Fast Cluster Retrieval.
|
|
6
|
+
arXiv:2603.03004.
|
|
7
|
+
|
|
8
|
+
Produces TFCE scores (not p-values). Inference still requires permutation
|
|
9
|
+
testing. The advantage over standard discretized TFCE is:
|
|
10
|
+
(1) Exact integration (no dh discretization error)
|
|
11
|
+
(2) Single sweep replaces Nh separate CCL passes
|
|
12
|
+
|
|
13
|
+
This implementation uses a dense equi-spaced Z-grid with union-find
|
|
14
|
+
cluster retrieval. The grid can be made arbitrarily fine at minimal
|
|
15
|
+
cost because union-find avoids repeated CCL.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import time
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def etfce(
|
|
26
|
+
stat_map: np.ndarray,
|
|
27
|
+
mask: np.ndarray | None = None,
|
|
28
|
+
E: float = 0.5,
|
|
29
|
+
H: float = 2.0,
|
|
30
|
+
dh: float = 0.01,
|
|
31
|
+
verbose: bool = True,
|
|
32
|
+
progress_queue=None,
|
|
33
|
+
) -> dict:
|
|
34
|
+
"""Compute TFCE scores using union-find cluster retrieval.
|
|
35
|
+
|
|
36
|
+
Parameters
|
|
37
|
+
----------
|
|
38
|
+
stat_map : 3D array
|
|
39
|
+
Z-statistic map (only positive values are enhanced).
|
|
40
|
+
mask : 3D bool array, optional
|
|
41
|
+
Brain mask. If None, uses stat_map > 0.
|
|
42
|
+
E, H : float
|
|
43
|
+
TFCE extent and height exponents (default 0.5, 2.0).
|
|
44
|
+
dh : float
|
|
45
|
+
Threshold step size in Z-space (default 0.01, 10x finer than FSL).
|
|
46
|
+
"""
|
|
47
|
+
stat_map = np.asarray(stat_map, dtype=np.float64)
|
|
48
|
+
if mask is None:
|
|
49
|
+
mask = stat_map > 0
|
|
50
|
+
else:
|
|
51
|
+
mask = np.asarray(mask, dtype=bool)
|
|
52
|
+
|
|
53
|
+
safe = np.where(np.isfinite(stat_map) & mask, stat_map, 0.0)
|
|
54
|
+
safe = np.clip(safe, 0, None)
|
|
55
|
+
z_max = float(safe.max())
|
|
56
|
+
|
|
57
|
+
if z_max <= 0:
|
|
58
|
+
return {"tfce": np.zeros_like(safe), "diagnostics": {}}
|
|
59
|
+
|
|
60
|
+
t0 = time.perf_counter()
|
|
61
|
+
|
|
62
|
+
flat = safe.ravel()
|
|
63
|
+
pos_mask = flat > 0
|
|
64
|
+
pos_indices = np.flatnonzero(pos_mask)
|
|
65
|
+
pos_values = flat[pos_indices]
|
|
66
|
+
N = len(pos_indices)
|
|
67
|
+
|
|
68
|
+
order = np.argsort(-pos_values)
|
|
69
|
+
sorted_flat = pos_indices[order]
|
|
70
|
+
sorted_vals = pos_values[order]
|
|
71
|
+
|
|
72
|
+
flat_to_rank = np.full(flat.shape[0], -1, dtype=np.intp)
|
|
73
|
+
flat_to_rank[sorted_flat] = np.arange(N)
|
|
74
|
+
|
|
75
|
+
parent = np.arange(N, dtype=np.intp)
|
|
76
|
+
uf_rank = np.zeros(N, dtype=np.intp)
|
|
77
|
+
uf_size = np.ones(N, dtype=np.intp)
|
|
78
|
+
active = np.zeros(N, dtype=bool)
|
|
79
|
+
|
|
80
|
+
sx, sy, sz = stat_map.shape
|
|
81
|
+
offsets_3d = np.array([
|
|
82
|
+
[1, 0, 0], [-1, 0, 0],
|
|
83
|
+
[0, 1, 0], [0, -1, 0],
|
|
84
|
+
[0, 0, 1], [0, 0, -1],
|
|
85
|
+
], dtype=np.intp)
|
|
86
|
+
|
|
87
|
+
def find(a: int) -> int:
|
|
88
|
+
root = a
|
|
89
|
+
while parent[root] != root:
|
|
90
|
+
root = parent[root]
|
|
91
|
+
while parent[a] != root:
|
|
92
|
+
parent[a], a = root, parent[a]
|
|
93
|
+
return root
|
|
94
|
+
|
|
95
|
+
def union(a: int, b: int):
|
|
96
|
+
ra, rb = find(a), find(b)
|
|
97
|
+
if ra == rb:
|
|
98
|
+
return
|
|
99
|
+
if uf_rank[ra] < uf_rank[rb]:
|
|
100
|
+
parent[ra] = rb
|
|
101
|
+
uf_size[rb] += uf_size[ra]
|
|
102
|
+
elif uf_rank[ra] > uf_rank[rb]:
|
|
103
|
+
parent[rb] = ra
|
|
104
|
+
uf_size[ra] += uf_size[rb]
|
|
105
|
+
else:
|
|
106
|
+
parent[rb] = ra
|
|
107
|
+
uf_size[ra] += uf_size[rb]
|
|
108
|
+
uf_rank[ra] += 1
|
|
109
|
+
|
|
110
|
+
h_grid = np.arange(dh, z_max + dh, dh)[::-1]
|
|
111
|
+
Nh = len(h_grid)
|
|
112
|
+
|
|
113
|
+
if verbose and progress_queue is None:
|
|
114
|
+
print(f" [eTFCE] z_max={z_max:.1f}, Nh={Nh}, dh={dh}, "
|
|
115
|
+
f"N_pos={N}, E={E}, H={H}")
|
|
116
|
+
|
|
117
|
+
cursor = 0
|
|
118
|
+
accumulator = np.zeros(N, dtype=np.float64)
|
|
119
|
+
|
|
120
|
+
for step, h in enumerate(h_grid):
|
|
121
|
+
if progress_queue and step % max(1, Nh // 20) == 0:
|
|
122
|
+
progress_queue.put({"name": "eTFCE",
|
|
123
|
+
"current": step, "total": Nh,
|
|
124
|
+
"phase": "sweep"})
|
|
125
|
+
|
|
126
|
+
while cursor < N and sorted_vals[cursor] >= h:
|
|
127
|
+
i = cursor
|
|
128
|
+
active[i] = True
|
|
129
|
+
fi = int(sorted_flat[i])
|
|
130
|
+
xi = fi // (sy * sz)
|
|
131
|
+
yi = (fi % (sy * sz)) // sz
|
|
132
|
+
zi = fi % sz
|
|
133
|
+
|
|
134
|
+
for d in range(6):
|
|
135
|
+
nx = xi + int(offsets_3d[d, 0])
|
|
136
|
+
ny = yi + int(offsets_3d[d, 1])
|
|
137
|
+
nz = zi + int(offsets_3d[d, 2])
|
|
138
|
+
if 0 <= nx < sx and 0 <= ny < sy and 0 <= nz < sz:
|
|
139
|
+
nf = nx * sy * sz + ny * sz + nz
|
|
140
|
+
ni = flat_to_rank[nf]
|
|
141
|
+
if ni >= 0 and active[ni]:
|
|
142
|
+
union(i, ni)
|
|
143
|
+
cursor += 1
|
|
144
|
+
|
|
145
|
+
if cursor == 0:
|
|
146
|
+
continue
|
|
147
|
+
|
|
148
|
+
active_idx = np.arange(cursor)
|
|
149
|
+
roots = parent[active_idx].copy()
|
|
150
|
+
for _ in range(5):
|
|
151
|
+
new_roots = parent[roots]
|
|
152
|
+
if np.array_equal(new_roots, roots):
|
|
153
|
+
break
|
|
154
|
+
roots = new_roots
|
|
155
|
+
parent[active_idx] = roots
|
|
156
|
+
|
|
157
|
+
sizes = uf_size[roots]
|
|
158
|
+
accumulator[:cursor] += (sizes.astype(np.float64) ** E) * (h ** H) * dh
|
|
159
|
+
|
|
160
|
+
tfce_out = np.zeros(flat.shape[0], dtype=np.float64)
|
|
161
|
+
for i in range(N):
|
|
162
|
+
tfce_out[sorted_flat[i]] = accumulator[i]
|
|
163
|
+
tfce_out = tfce_out.reshape(stat_map.shape)
|
|
164
|
+
|
|
165
|
+
t_total = time.perf_counter() - t0
|
|
166
|
+
|
|
167
|
+
if progress_queue:
|
|
168
|
+
progress_queue.put({"name": "eTFCE",
|
|
169
|
+
"current": Nh, "total": Nh, "phase": "done"})
|
|
170
|
+
|
|
171
|
+
if verbose and progress_queue is None:
|
|
172
|
+
print(f" [eTFCE] done in {t_total:.2f}s")
|
|
173
|
+
|
|
174
|
+
return {
|
|
175
|
+
"tfce": tfce_out,
|
|
176
|
+
"diagnostics": {
|
|
177
|
+
"total_time": round(t_total, 4),
|
|
178
|
+
"n_thresholds": Nh,
|
|
179
|
+
"dh": dh,
|
|
180
|
+
"n_positive_voxels": N,
|
|
181
|
+
},
|
|
182
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Gaussian Random Field helpers for pTFCE.
|
|
2
|
+
|
|
3
|
+
Expected cluster size, cluster-size PDF, and Bayesian posterior P(h|c).
|
|
4
|
+
Ported from the R pTFCE package (github.com/spisakt/pTFCE) and FSL.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
from scipy import special, stats
|
|
13
|
+
from scipy.integrate import quad
|
|
14
|
+
|
|
15
|
+
_GAMMA_2_5 = float(special.gamma(2.5))
|
|
16
|
+
_LOG_2PI = math.log(2.0 * math.pi)
|
|
17
|
+
_INV_SQRT_2PI = 1.0 / math.sqrt(2.0 * math.pi)
|
|
18
|
+
_INV_SQRT_2 = 1.0 / math.sqrt(2.0)
|
|
19
|
+
_UPPER_Z = 37.06503921751289 # = min(38.0, norm.isf(1e-300)), precomputed
|
|
20
|
+
_SF_UPPER = 1e-300 # norm.sf(_UPPER_Z) ≈ 1e-300
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def expected_cluster_size(h: np.ndarray, V: int, Rd: float) -> np.ndarray:
|
|
24
|
+
"""Expected cluster size at Z-threshold *h* (GRF, FSL port).
|
|
25
|
+
|
|
26
|
+
Parameters
|
|
27
|
+
----------
|
|
28
|
+
h : array-like
|
|
29
|
+
Z-score thresholds.
|
|
30
|
+
V : int
|
|
31
|
+
Number of masked voxels.
|
|
32
|
+
Rd : float
|
|
33
|
+
RESEL count (dLh * V).
|
|
34
|
+
"""
|
|
35
|
+
h = np.asarray(h, dtype=np.float64)
|
|
36
|
+
log_num = np.log(V) + stats.norm.logsf(h)
|
|
37
|
+
log_den = np.full_like(h, -np.inf)
|
|
38
|
+
valid = h >= 1.1
|
|
39
|
+
h2 = h[valid] ** 2
|
|
40
|
+
log_den[valid] = np.log(Rd) + np.log(h2 - 1) - h2 / 2.0 - 2.0 * _LOG_2PI
|
|
41
|
+
log_ec = log_num.copy()
|
|
42
|
+
log_ec[valid] = log_num[valid] - log_den[valid]
|
|
43
|
+
return np.exp(log_ec).clip(min=1.0)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _expected_cluster_size_scalar(h: float, log_V: float, log_Rd: float) -> float:
|
|
47
|
+
"""Scalar fast-path for expected_cluster_size (avoids array alloc)."""
|
|
48
|
+
log_sf = math.log(0.5 * math.erfc(h * _INV_SQRT_2) + 1e-300)
|
|
49
|
+
log_num = log_V + log_sf
|
|
50
|
+
if h >= 1.1:
|
|
51
|
+
h2 = h * h
|
|
52
|
+
log_den = log_Rd + math.log(h2 - 1.0) - h2 * 0.5 - 2.0 * _LOG_2PI
|
|
53
|
+
log_ec = log_num - log_den
|
|
54
|
+
else:
|
|
55
|
+
log_ec = log_num
|
|
56
|
+
ec = math.exp(log_ec)
|
|
57
|
+
return ec if ec > 1.0 else 1.0
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def cluster_pdf(c: float, lam: float) -> float:
|
|
61
|
+
"""PDF of cluster size *c* given rate parameter *lam* (D=3)."""
|
|
62
|
+
if c <= 0:
|
|
63
|
+
return 0.0
|
|
64
|
+
return (2.0 * lam / (3.0 * c ** (1.0 / 3.0))) * np.exp(-lam * c ** (2.0 / 3.0))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def pvox_clust(V: int, Rd: float, c: float, h: float,
|
|
68
|
+
z_est_thr: float = 1.3) -> float:
|
|
69
|
+
"""P(Z >= h | cluster_size = c) via Bayes' rule with GRF likelihood.
|
|
70
|
+
|
|
71
|
+
Uses numerical integration (scipy.integrate.quad).
|
|
72
|
+
"""
|
|
73
|
+
if c <= 0 or not math.isfinite(h):
|
|
74
|
+
return 1.0
|
|
75
|
+
|
|
76
|
+
log_V = math.log(V)
|
|
77
|
+
log_Rd = math.log(Rd)
|
|
78
|
+
c_13 = c ** (1.0 / 3.0)
|
|
79
|
+
c_23 = c ** (2.0 / 3.0)
|
|
80
|
+
|
|
81
|
+
def integrand(xi: float) -> float:
|
|
82
|
+
ec = _expected_cluster_size_scalar(xi, log_V, log_Rd)
|
|
83
|
+
lam = (ec / _GAMMA_2_5) ** (-2.0 / 3.0)
|
|
84
|
+
cpdf = (2.0 * lam / (3.0 * c_13)) * math.exp(-lam * c_23)
|
|
85
|
+
phi = _INV_SQRT_2PI * math.exp(-0.5 * xi * xi)
|
|
86
|
+
return cpdf * phi
|
|
87
|
+
|
|
88
|
+
upper = _UPPER_Z
|
|
89
|
+
numerator, _ = quad(integrand, h, upper, limit=200)
|
|
90
|
+
denominator, _ = quad(integrand, z_est_thr, upper, limit=200)
|
|
91
|
+
|
|
92
|
+
if denominator < 1e-300:
|
|
93
|
+
return 0.5 * math.erfc(h * _INV_SQRT_2)
|
|
94
|
+
return float(max(min(numerator / denominator, 1.0), _SF_UPPER))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def aggregate_logpvals(s: float, delta: float) -> float:
|
|
98
|
+
"""Q-function: equidistant incremental log-probability aggregation."""
|
|
99
|
+
if s <= 0:
|
|
100
|
+
return 0.0
|
|
101
|
+
return 0.5 * (math.sqrt(delta * (8.0 * s + delta)) - delta)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def aggregate_logpvals_vec(s: np.ndarray, delta: float) -> np.ndarray:
|
|
105
|
+
"""Vectorised Q-function over an array of accumulated -logp sums."""
|
|
106
|
+
out = np.zeros_like(s)
|
|
107
|
+
pos = s > 0
|
|
108
|
+
out[pos] = 0.5 * (np.sqrt(delta * (8.0 * s[pos] + delta)) - delta)
|
|
109
|
+
return out
|