pytfce 0.1.0__py3-none-any.whl

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/__init__.py 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
+ ]
pytfce/config.py ADDED
@@ -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
+ }
pytfce/core/etfce.py ADDED
@@ -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
+ }
pytfce/core/grf.py ADDED
@@ -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