htfa 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.
- htfa-0.1.0/LICENSE +20 -0
- htfa-0.1.0/PKG-INFO +234 -0
- htfa-0.1.0/README.md +156 -0
- htfa-0.1.0/htfa/__init__.py +39 -0
- htfa-0.1.0/htfa/_download.py +34 -0
- htfa-0.1.0/htfa/_engines.py +562 -0
- htfa-0.1.0/htfa/_kernels.py +1532 -0
- htfa-0.1.0/htfa/_lazy.py +437 -0
- htfa-0.1.0/htfa/_matching.py +71 -0
- htfa-0.1.0/htfa/_spatial.py +145 -0
- htfa-0.1.0/htfa/_validation.py +13 -0
- htfa-0.1.0/htfa/brainnet.py +2257 -0
- htfa-0.1.0/htfa/connectivity.py +137 -0
- htfa-0.1.0/htfa/datasets.py +457 -0
- htfa-0.1.0/htfa/fit.py +115 -0
- htfa-0.1.0/htfa/groups.py +677 -0
- htfa-0.1.0/htfa/htfa.py +1158 -0
- htfa-0.1.0/htfa/io.py +444 -0
- htfa-0.1.0/htfa/results.py +1265 -0
- htfa-0.1.0/htfa/stats.py +149 -0
- htfa-0.1.0/htfa/synthetic.py +453 -0
- htfa-0.1.0/htfa/tfa.py +1149 -0
- htfa-0.1.0/htfa/timecourse.py +254 -0
- htfa-0.1.0/htfa.egg-info/PKG-INFO +234 -0
- htfa-0.1.0/htfa.egg-info/SOURCES.txt +60 -0
- htfa-0.1.0/htfa.egg-info/dependency_links.txt +1 -0
- htfa-0.1.0/htfa.egg-info/requires.txt +63 -0
- htfa-0.1.0/htfa.egg-info/top_level.txt +1 -0
- htfa-0.1.0/pyproject.toml +105 -0
- htfa-0.1.0/setup.cfg +4 -0
- htfa-0.1.0/tests/test_brainiak_crosscheck.py +250 -0
- htfa-0.1.0/tests/test_brainnet.py +1669 -0
- htfa-0.1.0/tests/test_component_plots.py +250 -0
- htfa-0.1.0/tests/test_connectivity.py +49 -0
- htfa-0.1.0/tests/test_datasets.py +267 -0
- htfa-0.1.0/tests/test_docs.py +44 -0
- htfa-0.1.0/tests/test_engines.py +232 -0
- htfa-0.1.0/tests/test_equivalence.py +547 -0
- htfa-0.1.0/tests/test_fast_mode.py +596 -0
- htfa-0.1.0/tests/test_fit.py +105 -0
- htfa-0.1.0/tests/test_fit_equivalence.py +149 -0
- htfa-0.1.0/tests/test_folder_hierarchy.py +201 -0
- htfa-0.1.0/tests/test_gpu_accuracy.py +96 -0
- htfa-0.1.0/tests/test_groups.py +544 -0
- htfa-0.1.0/tests/test_headless.py +185 -0
- htfa-0.1.0/tests/test_htfa.py +626 -0
- htfa-0.1.0/tests/test_io.py +341 -0
- htfa-0.1.0/tests/test_kernel_shapes.py +345 -0
- htfa-0.1.0/tests/test_kernels.py +1248 -0
- htfa-0.1.0/tests/test_lazy.py +497 -0
- htfa-0.1.0/tests/test_lm_scaling.py +116 -0
- htfa-0.1.0/tests/test_multi_gpu.py +242 -0
- htfa-0.1.0/tests/test_package.py +10 -0
- htfa-0.1.0/tests/test_release_plot_ticks.py +85 -0
- htfa-0.1.0/tests/test_release_redteam.py +323 -0
- htfa-0.1.0/tests/test_results.py +349 -0
- htfa-0.1.0/tests/test_shape_equivalence.py +282 -0
- htfa-0.1.0/tests/test_shape_fits.py +423 -0
- htfa-0.1.0/tests/test_stats.py +111 -0
- htfa-0.1.0/tests/test_synthetic.py +154 -0
- htfa-0.1.0/tests/test_tfa.py +917 -0
- htfa-0.1.0/tests/test_timecourse.py +122 -0
htfa-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
Copyright (c) 2022 Contextual Dynamics Lab
|
|
3
|
+
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
in the Software without restriction, including without limitation the rights
|
|
7
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
furnished to do so, subject to the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
17
|
+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
|
18
|
+
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
19
|
+
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
|
|
20
|
+
OR OTHER DEALINGS IN THE SOFTWARE.
|
htfa-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: htfa
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Hierarchical Topographic Factor Analysis
|
|
5
|
+
Author-email: Contextual Dynamics Lab <contextualdynamics@gmail.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/ContextLab/htfa
|
|
8
|
+
Project-URL: Repository, https://github.com/ContextLab/htfa
|
|
9
|
+
Keywords: neuroimaging,factor-analysis,dimensionality-reduction,neuroscience,fmri,brain-networks
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: numpy>=1.24
|
|
25
|
+
Requires-Dist: scipy>=1.10
|
|
26
|
+
Requires-Dist: scikit-learn>=1.3
|
|
27
|
+
Requires-Dist: nibabel>=5
|
|
28
|
+
Requires-Dist: joblib>=1.3
|
|
29
|
+
Requires-Dist: threadpoolctl>=3
|
|
30
|
+
Requires-Dist: packaging>=21
|
|
31
|
+
Requires-Dist: torch>=2.2; sys_platform == "darwin" and platform_machine == "arm64"
|
|
32
|
+
Provides-Extra: plot
|
|
33
|
+
Requires-Dist: matplotlib>=3.7; extra == "plot"
|
|
34
|
+
Requires-Dist: nilearn>=0.10.1; extra == "plot"
|
|
35
|
+
Provides-Extra: images
|
|
36
|
+
Requires-Dist: pillow>=10; extra == "images"
|
|
37
|
+
Requires-Dist: tifffile>=2023.1; extra == "images"
|
|
38
|
+
Provides-Extra: nilearn
|
|
39
|
+
Requires-Dist: nilearn>=0.10.1; extra == "nilearn"
|
|
40
|
+
Provides-Extra: tutorials
|
|
41
|
+
Requires-Dist: hypertools>=1.1; extra == "tutorials"
|
|
42
|
+
Requires-Dist: sentence-transformers>=3; extra == "tutorials"
|
|
43
|
+
Provides-Extra: gpu
|
|
44
|
+
Requires-Dist: torch>=2.2; extra == "gpu"
|
|
45
|
+
Provides-Extra: brain3d
|
|
46
|
+
Requires-Dist: pyvista>=0.43; extra == "brain3d"
|
|
47
|
+
Requires-Dist: imageio>=2.31; extra == "brain3d"
|
|
48
|
+
Requires-Dist: imageio-ffmpeg>=0.4.9; extra == "brain3d"
|
|
49
|
+
Requires-Dist: pillow>=10.1; extra == "brain3d"
|
|
50
|
+
Provides-Extra: dev
|
|
51
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
52
|
+
Requires-Dist: pytest-cov>=5; extra == "dev"
|
|
53
|
+
Requires-Dist: sympy>=1.12; extra == "dev"
|
|
54
|
+
Requires-Dist: ruff>=0.5; extra == "dev"
|
|
55
|
+
Requires-Dist: mypy>=1.10; extra == "dev"
|
|
56
|
+
Requires-Dist: build>=1; extra == "dev"
|
|
57
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
58
|
+
Requires-Dist: nilearn>=0.10.1; extra == "dev"
|
|
59
|
+
Requires-Dist: matplotlib>=3.7; extra == "dev"
|
|
60
|
+
Requires-Dist: pillow>=10.1; extra == "dev"
|
|
61
|
+
Requires-Dist: tifffile>=2023.1; extra == "dev"
|
|
62
|
+
Requires-Dist: pyvista>=0.43; extra == "dev"
|
|
63
|
+
Requires-Dist: imageio>=2.31; extra == "dev"
|
|
64
|
+
Requires-Dist: imageio-ffmpeg>=0.4.9; extra == "dev"
|
|
65
|
+
Provides-Extra: docs
|
|
66
|
+
Requires-Dist: sphinx>=7; extra == "docs"
|
|
67
|
+
Requires-Dist: furo; extra == "docs"
|
|
68
|
+
Requires-Dist: numpydoc; extra == "docs"
|
|
69
|
+
Requires-Dist: sphinx-gallery; extra == "docs"
|
|
70
|
+
Requires-Dist: nbsphinx; extra == "docs"
|
|
71
|
+
Requires-Dist: ipykernel; extra == "docs"
|
|
72
|
+
Requires-Dist: nbconvert; extra == "docs"
|
|
73
|
+
Requires-Dist: matplotlib>=3.7; extra == "docs"
|
|
74
|
+
Requires-Dist: nilearn>=0.10.1; extra == "docs"
|
|
75
|
+
Requires-Dist: pillow>=10; extra == "docs"
|
|
76
|
+
Requires-Dist: tifffile>=2023.1; extra == "docs"
|
|
77
|
+
Dynamic: license-file
|
|
78
|
+
|
|
79
|
+
# htfa
|
|
80
|
+
|
|
81
|
+
<picture>
|
|
82
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ContextLab/htfa/main/docs/_static/cover_dark.png">
|
|
83
|
+
<img alt="HTFA factor network: 50 template factors drawn as spheres inside a translucent brain, with the strongest inter-subject correlations as edges" src="https://raw.githubusercontent.com/ContextLab/htfa/main/docs/_static/cover_light.png" width="100%">
|
|
84
|
+
</picture>
|
|
85
|
+
|
|
86
|
+
<sub>Illustrative movie-viewing analysis: an HTFA template (K = 50) fitted to 12 adults watching Pixar's <i>Partly Cloudy</i>, from Nilearn's <code>development_fmri</code> dataset, viewed from the left, above and right. Inter-subject functional correlation (ISFC) measures correlations between participants' factor time courses at matching moments of the film. Edges show the strongest 5% of factor pairs (|ISFC| ≥ 0.137; red positive, blue negative). Node size represents factor width; node colour identifies communities in the positive-ISFC graph. See the <a href="https://htfa.readthedocs.io/en/latest/tutorials/10_dynamic_isfc_animation.html">ISFC tutorial</a> for the analysis workflow.</sub>
|
|
87
|
+
|
|
88
|
+
[](https://pypi.org/project/htfa/)
|
|
89
|
+
[](https://github.com/ContextLab/htfa/actions/workflows/tests.yml)
|
|
90
|
+
[](https://htfa.readthedocs.io/en/latest/?badge=latest)
|
|
91
|
+
[](https://github.com/ContextLab/htfa/blob/main/LICENSE)
|
|
92
|
+
|
|
93
|
+
## Overview
|
|
94
|
+
|
|
95
|
+
Topographic factor analysis (TFA) models a data matrix `X` (voxels by time points) as `X ≈ F W + noise`. Each of the `K` factors is a spatial kernel, or a mixture of kernels, with fitted centers and widths in coordinate space. `W` holds the factors' weights over time [1]. Hierarchical TFA (HTFA) fits TFA to several subjects at once, with a global template that the per-subject factors are tied to [2, 3, 4].
|
|
96
|
+
|
|
97
|
+
The examples use simulated data, movie-viewing fMRI, a word-viewing experiment, and ordinary 2D images to illustrate different parts of the API. TFA and HTFA do not require a particular task: the inputs are observations at spatial coordinates. HTFA fits can have different time-series lengths across subjects; analyses that correlate subjects at matching time points, such as ISFC, additionally require aligned samples.
|
|
98
|
+
|
|
99
|
+
htfa is a standalone Python implementation of these algorithms. Its numerical validation includes comparisons with [BrainIAK](https://brainiak.org); BrainIAK is not a runtime dependency.
|
|
100
|
+
|
|
101
|
+
- No MPI or local compilation is needed when installing the prebuilt dependency wheels for a supported platform.
|
|
102
|
+
- Analytic Jacobian for the center/width least-squares problem (`htfa/_kernels.py`).
|
|
103
|
+
- A NumPy engine and a torch engine (CUDA, Apple Metal, CPU), chosen with the estimators' `backend` argument; `auto` uses a GPU only for large problems when torch is already installed. HTFA distributes independent subjects across visible CUDA GPUs; `gpu_devices` selects a subset.
|
|
104
|
+
- Two solver modes: `mode='fast'` (the default) and `mode='exact'` (the reference for numerical equivalence and BrainIAK checks). The modes optimize the same objective but can reach different local minima; see [Performance](https://htfa.readthedocs.io/en/latest/performance.html) and [Validation](https://htfa.readthedocs.io/en/latest/validation.html).
|
|
105
|
+
- Factor shapes: Gaussian (`kernel='rbf'`, the default), `'laplace'` and `'mexican_hat'`, and mixtures of several components per factor (`n_components`).
|
|
106
|
+
- Nested subject groups with group-level templates and permutation comparisons.
|
|
107
|
+
- Reconstruction R² and nominal conditional Gaussian AIC, AICc and BIC (`htfa.stats`).
|
|
108
|
+
- Inputs: NIfTI files and folders, nilearn/nibabel objects, numpy arrays and 2D images.
|
|
109
|
+
- Synthetic data with ground truth (`htfa.synthetic`), factor-level connectivity, a results object, and BrainNet Viewer-style 3D network plots (`htfa.brainnet`).
|
|
110
|
+
|
|
111
|
+
## Quick tour
|
|
112
|
+
|
|
113
|
+
The [quick-start guide](https://htfa.readthedocs.io/en/latest/quickstart.html) walks through fitting, inspecting, and plotting a model, then loading your own images.
|
|
114
|
+
|
|
115
|
+
Generate synthetic data for three subjects with known factor parameters, fit HTFA, and compare the recovered centers with the truth:
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
import htfa
|
|
119
|
+
from htfa.synthetic import match_factors
|
|
120
|
+
|
|
121
|
+
Xs, Rs, truth = htfa.make_htfa_data(
|
|
122
|
+
n_subjects=3, grid_shape=(12, 12, 12), n_samples=60, K=5, random_state=0
|
|
123
|
+
)
|
|
124
|
+
res = htfa.fit(
|
|
125
|
+
Xs, K=5, coords=Rs, standardize=False, max_global_iter=30, random_state=0
|
|
126
|
+
)
|
|
127
|
+
print(res.global_centers.shape) # template centers
|
|
128
|
+
print(res.weights[0].shape) # factor time courses of the first subject
|
|
129
|
+
print(res.connectivity(0).shape) # factor connectivity of the first subject
|
|
130
|
+
perm = match_factors(truth["centers"][0], res.centers[0])
|
|
131
|
+
print(abs(res.centers[0][perm] - truth["centers"][0]).max())
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Output:
|
|
135
|
+
|
|
136
|
+
```
|
|
137
|
+
(5, 3)
|
|
138
|
+
(5, 60)
|
|
139
|
+
(5, 5)
|
|
140
|
+
0.01688680355447225
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
For real data, pass a folder with one `.nii` / `.nii.gz` file per subject:
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
res = htfa.fit("path/to/folder", K=50, random_state=0)
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
Nested folders supply group names and hierarchical templates from their paths.
|
|
150
|
+
Use `groups=False` to ignore folder-derived grouping, or pass explicit `groups`
|
|
151
|
+
to define the experimental hierarchy yourself. Each file remains one subject;
|
|
152
|
+
repeated runs from one person are not independent subjects.
|
|
153
|
+
|
|
154
|
+
The inputs `htfa.fit` accepts, its parameters and the results object are described in the [documentation](https://htfa.readthedocs.io/en/latest/) and in [docs/API.md](https://github.com/ContextLab/htfa/blob/main/docs/API.md).
|
|
155
|
+
|
|
156
|
+
## Installation
|
|
157
|
+
|
|
158
|
+
Install the [PyPI release](https://pypi.org/project/htfa/):
|
|
159
|
+
|
|
160
|
+
```bash
|
|
161
|
+
pip install htfa
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
For development, using [uv](https://docs.astral.sh/uv/):
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
git clone https://github.com/ContextLab/htfa.git
|
|
168
|
+
cd htfa
|
|
169
|
+
make install
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
`make install` creates `.venv` (Python 3.12) and installs the package with the `dev` and `docs` extras. The package requires Python 3.10 or newer. On Apple Silicon Macs, torch is a core dependency.
|
|
173
|
+
|
|
174
|
+
### Optional extras
|
|
175
|
+
|
|
176
|
+
| Extra | Contents |
|
|
177
|
+
|-|-|
|
|
178
|
+
| `plot` | matplotlib, nilearn |
|
|
179
|
+
| `images` | pillow, tifffile |
|
|
180
|
+
| `nilearn` | nilearn |
|
|
181
|
+
| `gpu` | torch |
|
|
182
|
+
| `brain3d` | pyvista, imageio, imageio-ffmpeg, pillow (BrainNet Viewer-style network plots and animations, `htfa.brainnet`) |
|
|
183
|
+
| `tutorials` | hypertools, sentence-transformers (only to re-execute the word-decoding tutorial) |
|
|
184
|
+
| `dev` | test, lint, type-checking and packaging tools, plus plotting and image dependencies |
|
|
185
|
+
| `docs` | sphinx, furo, numpydoc, sphinx-gallery, nbsphinx, and others |
|
|
186
|
+
|
|
187
|
+
Optional dependencies are installed with pip the first time they are needed, using the versions declared for the extra. To turn this off, set the environment variable `HTFA_AUTO_INSTALL=0` or call:
|
|
188
|
+
|
|
189
|
+
```python
|
|
190
|
+
import htfa
|
|
191
|
+
|
|
192
|
+
htfa.set_autoinstall(False)
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
## Documentation
|
|
196
|
+
|
|
197
|
+
The Sphinx site is built from `docs/` with `make docs` (output in `docs/_build/html`). Its pages:
|
|
198
|
+
|
|
199
|
+
- [Installation](https://htfa.readthedocs.io/en/latest/installation.html)
|
|
200
|
+
- [Inputs](https://htfa.readthedocs.io/en/latest/inputs.html)
|
|
201
|
+
- [Optional dependencies](https://htfa.readthedocs.io/en/latest/optional_dependencies.html)
|
|
202
|
+
- [Tutorials](https://htfa.readthedocs.io/en/latest/tutorials.html)
|
|
203
|
+
- [Example gallery](https://htfa.readthedocs.io/en/latest/auto_examples/index.html)
|
|
204
|
+
- [API reference](https://htfa.readthedocs.io/en/latest/api.html)
|
|
205
|
+
|
|
206
|
+
## Testing
|
|
207
|
+
|
|
208
|
+
```bash
|
|
209
|
+
make test
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
By default, tests marked `brainiak` or `network` are deselected. Markers:
|
|
213
|
+
|
|
214
|
+
- `brainiak`: compares against the reference BrainIAK implementation (requires brainiak)
|
|
215
|
+
- `network`: requires network access (downloads data)
|
|
216
|
+
- `gpu`: requires a GPU backend (torch with CUDA or MPS)
|
|
217
|
+
- `slow`: long-running test
|
|
218
|
+
|
|
219
|
+
For example, `.venv/bin/pytest -m brainiak` runs the BrainIAK comparison tests.
|
|
220
|
+
|
|
221
|
+
## Citing
|
|
222
|
+
|
|
223
|
+
1. J. R. Manning, R. Ranganath, K. A. Norman, and D. M. Blei (2014). Topographic factor analysis: a Bayesian model for inferring brain networks from neural data. *PLoS ONE* 9(5). [doi:10.1371/journal.pone.0094914](https://doi.org/10.1371/journal.pone.0094914)
|
|
224
|
+
2. J. R. Manning, R. Ranganath, W. Keung, N. B. Turk-Browne, J. D. Cohen, K. A. Norman, and D. M. Blei (2014). Hierarchical topographic factor analysis. *2014 International Workshop on Pattern Recognition in Neuroimaging (PRNI)*. [doi:10.1109/PRNI.2014.6858530](https://doi.org/10.1109/prni.2014.6858530)
|
|
225
|
+
3. J. R. Manning, X. Zhu, T. L. Willke, R. Ranganath, K. Stachenfeld, U. Hasson, D. M. Blei, and K. A. Norman (2018). A probabilistic approach to discovering dynamic full-brain functional connectivity patterns. *NeuroImage*. [doi:10.1016/j.neuroimage.2018.01.071](https://doi.org/10.1016/j.neuroimage.2018.01.071)
|
|
226
|
+
4. M. J. Anderson, M. Capotă, J. S. Turek, X. Zhu, T. L. Willke, Y. Wang, P.-H. Chen, J. R. Manning, P. J. Ramadge, and K. A. Norman (2016). Enabling factor analysis on thousand-subject neuroimaging datasets. *IEEE International Conference on Big Data*. [doi:10.1109/BigData.2016.7840719](https://doi.org/10.1109/BigData.2016.7840719)
|
|
227
|
+
|
|
228
|
+
## Contributing
|
|
229
|
+
|
|
230
|
+
See [CONTRIBUTING.md](https://github.com/ContextLab/htfa/blob/main/CONTRIBUTING.md).
|
|
231
|
+
|
|
232
|
+
## License
|
|
233
|
+
|
|
234
|
+
MIT; see [LICENSE](https://github.com/ContextLab/htfa/blob/main/LICENSE). `htfa/brainnet.py` and `htfa/timecourse.py` adapt code from ContextLab/directed-forgetting-network-dynamics (commit 31a2b66; MIT License, Copyright (c) 2019 Contextual Dynamics Laboratory). The BrainNet Viewer brain meshes used by `htfa.brainnet` are not included; they are downloaded from NITRC on first use (BrainNet Viewer is distributed under the GNU GPL).
|
htfa-0.1.0/README.md
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
# htfa
|
|
2
|
+
|
|
3
|
+
<picture>
|
|
4
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ContextLab/htfa/main/docs/_static/cover_dark.png">
|
|
5
|
+
<img alt="HTFA factor network: 50 template factors drawn as spheres inside a translucent brain, with the strongest inter-subject correlations as edges" src="https://raw.githubusercontent.com/ContextLab/htfa/main/docs/_static/cover_light.png" width="100%">
|
|
6
|
+
</picture>
|
|
7
|
+
|
|
8
|
+
<sub>Illustrative movie-viewing analysis: an HTFA template (K = 50) fitted to 12 adults watching Pixar's <i>Partly Cloudy</i>, from Nilearn's <code>development_fmri</code> dataset, viewed from the left, above and right. Inter-subject functional correlation (ISFC) measures correlations between participants' factor time courses at matching moments of the film. Edges show the strongest 5% of factor pairs (|ISFC| ≥ 0.137; red positive, blue negative). Node size represents factor width; node colour identifies communities in the positive-ISFC graph. See the <a href="https://htfa.readthedocs.io/en/latest/tutorials/10_dynamic_isfc_animation.html">ISFC tutorial</a> for the analysis workflow.</sub>
|
|
9
|
+
|
|
10
|
+
[](https://pypi.org/project/htfa/)
|
|
11
|
+
[](https://github.com/ContextLab/htfa/actions/workflows/tests.yml)
|
|
12
|
+
[](https://htfa.readthedocs.io/en/latest/?badge=latest)
|
|
13
|
+
[](https://github.com/ContextLab/htfa/blob/main/LICENSE)
|
|
14
|
+
|
|
15
|
+
## Overview
|
|
16
|
+
|
|
17
|
+
Topographic factor analysis (TFA) models a data matrix `X` (voxels by time points) as `X ≈ F W + noise`. Each of the `K` factors is a spatial kernel, or a mixture of kernels, with fitted centers and widths in coordinate space. `W` holds the factors' weights over time [1]. Hierarchical TFA (HTFA) fits TFA to several subjects at once, with a global template that the per-subject factors are tied to [2, 3, 4].
|
|
18
|
+
|
|
19
|
+
The examples use simulated data, movie-viewing fMRI, a word-viewing experiment, and ordinary 2D images to illustrate different parts of the API. TFA and HTFA do not require a particular task: the inputs are observations at spatial coordinates. HTFA fits can have different time-series lengths across subjects; analyses that correlate subjects at matching time points, such as ISFC, additionally require aligned samples.
|
|
20
|
+
|
|
21
|
+
htfa is a standalone Python implementation of these algorithms. Its numerical validation includes comparisons with [BrainIAK](https://brainiak.org); BrainIAK is not a runtime dependency.
|
|
22
|
+
|
|
23
|
+
- No MPI or local compilation is needed when installing the prebuilt dependency wheels for a supported platform.
|
|
24
|
+
- Analytic Jacobian for the center/width least-squares problem (`htfa/_kernels.py`).
|
|
25
|
+
- A NumPy engine and a torch engine (CUDA, Apple Metal, CPU), chosen with the estimators' `backend` argument; `auto` uses a GPU only for large problems when torch is already installed. HTFA distributes independent subjects across visible CUDA GPUs; `gpu_devices` selects a subset.
|
|
26
|
+
- Two solver modes: `mode='fast'` (the default) and `mode='exact'` (the reference for numerical equivalence and BrainIAK checks). The modes optimize the same objective but can reach different local minima; see [Performance](https://htfa.readthedocs.io/en/latest/performance.html) and [Validation](https://htfa.readthedocs.io/en/latest/validation.html).
|
|
27
|
+
- Factor shapes: Gaussian (`kernel='rbf'`, the default), `'laplace'` and `'mexican_hat'`, and mixtures of several components per factor (`n_components`).
|
|
28
|
+
- Nested subject groups with group-level templates and permutation comparisons.
|
|
29
|
+
- Reconstruction R² and nominal conditional Gaussian AIC, AICc and BIC (`htfa.stats`).
|
|
30
|
+
- Inputs: NIfTI files and folders, nilearn/nibabel objects, numpy arrays and 2D images.
|
|
31
|
+
- Synthetic data with ground truth (`htfa.synthetic`), factor-level connectivity, a results object, and BrainNet Viewer-style 3D network plots (`htfa.brainnet`).
|
|
32
|
+
|
|
33
|
+
## Quick tour
|
|
34
|
+
|
|
35
|
+
The [quick-start guide](https://htfa.readthedocs.io/en/latest/quickstart.html) walks through fitting, inspecting, and plotting a model, then loading your own images.
|
|
36
|
+
|
|
37
|
+
Generate synthetic data for three subjects with known factor parameters, fit HTFA, and compare the recovered centers with the truth:
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import htfa
|
|
41
|
+
from htfa.synthetic import match_factors
|
|
42
|
+
|
|
43
|
+
Xs, Rs, truth = htfa.make_htfa_data(
|
|
44
|
+
n_subjects=3, grid_shape=(12, 12, 12), n_samples=60, K=5, random_state=0
|
|
45
|
+
)
|
|
46
|
+
res = htfa.fit(
|
|
47
|
+
Xs, K=5, coords=Rs, standardize=False, max_global_iter=30, random_state=0
|
|
48
|
+
)
|
|
49
|
+
print(res.global_centers.shape) # template centers
|
|
50
|
+
print(res.weights[0].shape) # factor time courses of the first subject
|
|
51
|
+
print(res.connectivity(0).shape) # factor connectivity of the first subject
|
|
52
|
+
perm = match_factors(truth["centers"][0], res.centers[0])
|
|
53
|
+
print(abs(res.centers[0][perm] - truth["centers"][0]).max())
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Output:
|
|
57
|
+
|
|
58
|
+
```
|
|
59
|
+
(5, 3)
|
|
60
|
+
(5, 60)
|
|
61
|
+
(5, 5)
|
|
62
|
+
0.01688680355447225
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
For real data, pass a folder with one `.nii` / `.nii.gz` file per subject:
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
res = htfa.fit("path/to/folder", K=50, random_state=0)
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Nested folders supply group names and hierarchical templates from their paths.
|
|
72
|
+
Use `groups=False` to ignore folder-derived grouping, or pass explicit `groups`
|
|
73
|
+
to define the experimental hierarchy yourself. Each file remains one subject;
|
|
74
|
+
repeated runs from one person are not independent subjects.
|
|
75
|
+
|
|
76
|
+
The inputs `htfa.fit` accepts, its parameters and the results object are described in the [documentation](https://htfa.readthedocs.io/en/latest/) and in [docs/API.md](https://github.com/ContextLab/htfa/blob/main/docs/API.md).
|
|
77
|
+
|
|
78
|
+
## Installation
|
|
79
|
+
|
|
80
|
+
Install the [PyPI release](https://pypi.org/project/htfa/):
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
pip install htfa
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
For development, using [uv](https://docs.astral.sh/uv/):
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
git clone https://github.com/ContextLab/htfa.git
|
|
90
|
+
cd htfa
|
|
91
|
+
make install
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
`make install` creates `.venv` (Python 3.12) and installs the package with the `dev` and `docs` extras. The package requires Python 3.10 or newer. On Apple Silicon Macs, torch is a core dependency.
|
|
95
|
+
|
|
96
|
+
### Optional extras
|
|
97
|
+
|
|
98
|
+
| Extra | Contents |
|
|
99
|
+
|-|-|
|
|
100
|
+
| `plot` | matplotlib, nilearn |
|
|
101
|
+
| `images` | pillow, tifffile |
|
|
102
|
+
| `nilearn` | nilearn |
|
|
103
|
+
| `gpu` | torch |
|
|
104
|
+
| `brain3d` | pyvista, imageio, imageio-ffmpeg, pillow (BrainNet Viewer-style network plots and animations, `htfa.brainnet`) |
|
|
105
|
+
| `tutorials` | hypertools, sentence-transformers (only to re-execute the word-decoding tutorial) |
|
|
106
|
+
| `dev` | test, lint, type-checking and packaging tools, plus plotting and image dependencies |
|
|
107
|
+
| `docs` | sphinx, furo, numpydoc, sphinx-gallery, nbsphinx, and others |
|
|
108
|
+
|
|
109
|
+
Optional dependencies are installed with pip the first time they are needed, using the versions declared for the extra. To turn this off, set the environment variable `HTFA_AUTO_INSTALL=0` or call:
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
import htfa
|
|
113
|
+
|
|
114
|
+
htfa.set_autoinstall(False)
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## Documentation
|
|
118
|
+
|
|
119
|
+
The Sphinx site is built from `docs/` with `make docs` (output in `docs/_build/html`). Its pages:
|
|
120
|
+
|
|
121
|
+
- [Installation](https://htfa.readthedocs.io/en/latest/installation.html)
|
|
122
|
+
- [Inputs](https://htfa.readthedocs.io/en/latest/inputs.html)
|
|
123
|
+
- [Optional dependencies](https://htfa.readthedocs.io/en/latest/optional_dependencies.html)
|
|
124
|
+
- [Tutorials](https://htfa.readthedocs.io/en/latest/tutorials.html)
|
|
125
|
+
- [Example gallery](https://htfa.readthedocs.io/en/latest/auto_examples/index.html)
|
|
126
|
+
- [API reference](https://htfa.readthedocs.io/en/latest/api.html)
|
|
127
|
+
|
|
128
|
+
## Testing
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
make test
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
By default, tests marked `brainiak` or `network` are deselected. Markers:
|
|
135
|
+
|
|
136
|
+
- `brainiak`: compares against the reference BrainIAK implementation (requires brainiak)
|
|
137
|
+
- `network`: requires network access (downloads data)
|
|
138
|
+
- `gpu`: requires a GPU backend (torch with CUDA or MPS)
|
|
139
|
+
- `slow`: long-running test
|
|
140
|
+
|
|
141
|
+
For example, `.venv/bin/pytest -m brainiak` runs the BrainIAK comparison tests.
|
|
142
|
+
|
|
143
|
+
## Citing
|
|
144
|
+
|
|
145
|
+
1. J. R. Manning, R. Ranganath, K. A. Norman, and D. M. Blei (2014). Topographic factor analysis: a Bayesian model for inferring brain networks from neural data. *PLoS ONE* 9(5). [doi:10.1371/journal.pone.0094914](https://doi.org/10.1371/journal.pone.0094914)
|
|
146
|
+
2. J. R. Manning, R. Ranganath, W. Keung, N. B. Turk-Browne, J. D. Cohen, K. A. Norman, and D. M. Blei (2014). Hierarchical topographic factor analysis. *2014 International Workshop on Pattern Recognition in Neuroimaging (PRNI)*. [doi:10.1109/PRNI.2014.6858530](https://doi.org/10.1109/prni.2014.6858530)
|
|
147
|
+
3. J. R. Manning, X. Zhu, T. L. Willke, R. Ranganath, K. Stachenfeld, U. Hasson, D. M. Blei, and K. A. Norman (2018). A probabilistic approach to discovering dynamic full-brain functional connectivity patterns. *NeuroImage*. [doi:10.1016/j.neuroimage.2018.01.071](https://doi.org/10.1016/j.neuroimage.2018.01.071)
|
|
148
|
+
4. M. J. Anderson, M. Capotă, J. S. Turek, X. Zhu, T. L. Willke, Y. Wang, P.-H. Chen, J. R. Manning, P. J. Ramadge, and K. A. Norman (2016). Enabling factor analysis on thousand-subject neuroimaging datasets. *IEEE International Conference on Big Data*. [doi:10.1109/BigData.2016.7840719](https://doi.org/10.1109/BigData.2016.7840719)
|
|
149
|
+
|
|
150
|
+
## Contributing
|
|
151
|
+
|
|
152
|
+
See [CONTRIBUTING.md](https://github.com/ContextLab/htfa/blob/main/CONTRIBUTING.md).
|
|
153
|
+
|
|
154
|
+
## License
|
|
155
|
+
|
|
156
|
+
MIT; see [LICENSE](https://github.com/ContextLab/htfa/blob/main/LICENSE). `htfa/brainnet.py` and `htfa/timecourse.py` adapt code from ContextLab/directed-forgetting-network-dynamics (commit 31a2b66; MIT License, Copyright (c) 2019 Contextual Dynamics Laboratory). The BrainNet Viewer brain meshes used by `htfa.brainnet` are not included; they are downloaded from NITRC on first use (BrainNet Viewer is distributed under the GNU GPL).
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Hierarchical Topographic Factor Analysis."""
|
|
2
|
+
|
|
3
|
+
from . import datasets as datasets
|
|
4
|
+
from . import stats as stats
|
|
5
|
+
from ._lazy import require, set_autoinstall
|
|
6
|
+
from .brainnet import animate_network, plot_network
|
|
7
|
+
from .connectivity import dynamic_connectivity, isfc, static_connectivity
|
|
8
|
+
from .fit import fit
|
|
9
|
+
from .groups import group_permutation_test
|
|
10
|
+
from .htfa import HTFA
|
|
11
|
+
from .io import Subject, load
|
|
12
|
+
from .results import HTFAResults
|
|
13
|
+
from .synthetic import make_group_data, make_htfa_data, make_tfa_data
|
|
14
|
+
from .tfa import TFA
|
|
15
|
+
from .timecourse import plot_timecourse
|
|
16
|
+
|
|
17
|
+
__version__ = "0.1.0"
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"HTFA",
|
|
21
|
+
"HTFAResults",
|
|
22
|
+
"Subject",
|
|
23
|
+
"TFA",
|
|
24
|
+
"animate_network",
|
|
25
|
+
"dynamic_connectivity",
|
|
26
|
+
"fit",
|
|
27
|
+
"group_permutation_test",
|
|
28
|
+
"isfc",
|
|
29
|
+
"load",
|
|
30
|
+
"make_group_data",
|
|
31
|
+
"make_htfa_data",
|
|
32
|
+
"make_tfa_data",
|
|
33
|
+
"plot_network",
|
|
34
|
+
"plot_timecourse",
|
|
35
|
+
"require",
|
|
36
|
+
"set_autoinstall",
|
|
37
|
+
"static_connectivity",
|
|
38
|
+
"stats",
|
|
39
|
+
]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Where htfa caches downloaded files, and their checksums."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
DATA_DIR_ENV = "HTFA_DATA_DIR"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def data_dir() -> Path:
|
|
14
|
+
"""Root folder for files htfa downloads.
|
|
15
|
+
|
|
16
|
+
``$HTFA_DATA_DIR`` if that variable is set, otherwise ``%LOCALAPPDATA%\\htfa``
|
|
17
|
+
on Windows and ``${XDG_CACHE_HOME:-~/.cache}/htfa`` elsewhere.
|
|
18
|
+
"""
|
|
19
|
+
root = os.environ.get(DATA_DIR_ENV)
|
|
20
|
+
if root:
|
|
21
|
+
return Path(root).expanduser()
|
|
22
|
+
if sys.platform == "win32" and os.environ.get("LOCALAPPDATA"):
|
|
23
|
+
return Path(os.environ["LOCALAPPDATA"]) / "htfa"
|
|
24
|
+
base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
|
|
25
|
+
return Path(base).expanduser() / "htfa"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def sha256(path: Path) -> str:
|
|
29
|
+
"""Hex SHA-256 digest of the file at ``path``."""
|
|
30
|
+
h = hashlib.sha256()
|
|
31
|
+
with open(path, "rb") as f:
|
|
32
|
+
for block in iter(lambda: f.read(1 << 20), b""):
|
|
33
|
+
h.update(block)
|
|
34
|
+
return h.hexdigest()
|