htfa 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.
- htfa/__init__.py +39 -0
- htfa/_download.py +34 -0
- htfa/_engines.py +562 -0
- htfa/_kernels.py +1532 -0
- htfa/_lazy.py +437 -0
- htfa/_matching.py +71 -0
- htfa/_spatial.py +145 -0
- htfa/_validation.py +13 -0
- htfa/brainnet.py +2257 -0
- htfa/connectivity.py +137 -0
- htfa/datasets.py +457 -0
- htfa/fit.py +115 -0
- htfa/groups.py +677 -0
- htfa/htfa.py +1158 -0
- htfa/io.py +444 -0
- htfa/results.py +1265 -0
- htfa/stats.py +149 -0
- htfa/synthetic.py +453 -0
- htfa/tfa.py +1149 -0
- htfa/timecourse.py +254 -0
- htfa-0.1.0.dist-info/METADATA +234 -0
- htfa-0.1.0.dist-info/RECORD +25 -0
- htfa-0.1.0.dist-info/WHEEL +5 -0
- htfa-0.1.0.dist-info/licenses/LICENSE +20 -0
- htfa-0.1.0.dist-info/top_level.txt +1 -0
htfa/brainnet.py
ADDED
|
@@ -0,0 +1,2257 @@
|
|
|
1
|
+
"""BrainNet Viewer-style network plots and animations.
|
|
2
|
+
|
|
3
|
+
For single Gaussian factors, the default view draws gray spheres inside a
|
|
4
|
+
translucent brain surface. Other kernels and mixtures use their component
|
|
5
|
+
spatial lobes by default. Supplied edge values, such as factor correlations,
|
|
6
|
+
are drawn as tubes when their absolute weight exceeds a threshold (red for
|
|
7
|
+
positive weights, blue for negative ones). The drawing rules follow BrainNet Viewer 1.43
|
|
8
|
+
(Xia, Wang & He, 2013, PLoS ONE 8: e68910; https://www.nitrc.org/projects/bnv/)
|
|
9
|
+
with a white background, mesh color 0.95 gray at opacity 0.2, node radii scaled linearly
|
|
10
|
+
onto 2-7 mm, edge diameter ``|E|`` mm at opacity 0.7, and an orthographic left
|
|
11
|
+
lateral view.
|
|
12
|
+
|
|
13
|
+
Rendering uses pyvista off screen; the ``brain3d`` extra is installed on first
|
|
14
|
+
use. On Linux without a display (Colab, containers), VTK's EGL offscreen
|
|
15
|
+
window (or else OSMesa) is selected automatically. The brain surfaces are
|
|
16
|
+
BrainNet Viewer's own ``.nv`` meshes. BrainNet Viewer is distributed under the
|
|
17
|
+
GNU GPL, so htfa does not ship them: they are
|
|
18
|
+
downloaded from NITRC on first use, checked against SHA-256 checksums, and
|
|
19
|
+
cached (see `mesh_cache_dir`).
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
# Adapted from ContextLab/directed-forgetting-network-dynamics, commit 31a2b66
|
|
23
|
+
# (code/dfnet/render.py and code/dfnet/brainnet_io.py), MIT License,
|
|
24
|
+
# Copyright (c) 2019 Contextual Dynamics Laboratory.
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import math
|
|
29
|
+
import os
|
|
30
|
+
import shutil
|
|
31
|
+
import subprocess
|
|
32
|
+
import sys
|
|
33
|
+
import tempfile
|
|
34
|
+
import time
|
|
35
|
+
import urllib.error
|
|
36
|
+
import urllib.request
|
|
37
|
+
import zipfile
|
|
38
|
+
from collections.abc import Callable, Iterable, Iterator, Sequence
|
|
39
|
+
from pathlib import Path
|
|
40
|
+
from typing import Any
|
|
41
|
+
|
|
42
|
+
import numpy as np
|
|
43
|
+
from scipy.spatial import cKDTree
|
|
44
|
+
|
|
45
|
+
from ._download import DATA_DIR_ENV as DATA_DIR_ENV
|
|
46
|
+
from ._download import data_dir
|
|
47
|
+
from ._download import sha256 as _sha256
|
|
48
|
+
from ._kernels import LAPLACE_EPS, Kernel
|
|
49
|
+
from ._lazy import lazy_import
|
|
50
|
+
from ._spatial import ComponentNodes, check_level, component_mode
|
|
51
|
+
|
|
52
|
+
Array = np.ndarray
|
|
53
|
+
|
|
54
|
+
__all__ = [
|
|
55
|
+
"MESHES",
|
|
56
|
+
"animate_network",
|
|
57
|
+
"annotate_pair",
|
|
58
|
+
"config_style",
|
|
59
|
+
"effective_nodes",
|
|
60
|
+
"fetch_mesh",
|
|
61
|
+
"image_diff",
|
|
62
|
+
"load_mesh",
|
|
63
|
+
"mesh_cache_dir",
|
|
64
|
+
"mni_mask",
|
|
65
|
+
"montage",
|
|
66
|
+
"node_radius",
|
|
67
|
+
"plot_network",
|
|
68
|
+
"read_brainnet_config",
|
|
69
|
+
"read_edge",
|
|
70
|
+
"read_node",
|
|
71
|
+
"read_nv",
|
|
72
|
+
"write_animation",
|
|
73
|
+
"write_edge",
|
|
74
|
+
"write_node",
|
|
75
|
+
"write_nv",
|
|
76
|
+
]
|
|
77
|
+
|
|
78
|
+
# BrainNet Viewer 1.43 (2013-12-27), the release the 2014 movies were made with.
|
|
79
|
+
MESH_ARCHIVE_URL = (
|
|
80
|
+
"https://www.nitrc.org/frs/download.php/6140/BrainNetViewer_20131227.zip"
|
|
81
|
+
)
|
|
82
|
+
MESH_ARCHIVE_SHA256 = "246b10c872966734e2c00b45d6ceee21bf37a02798ee1ba804e6329b0074dd5a"
|
|
83
|
+
_MESH_DIR_IN_ARCHIVE = "BrainNetViewer/Data/SurfTemplate/"
|
|
84
|
+
#: Mesh name -> (file in BrainNet Viewer 1.43's Data/SurfTemplate, SHA-256).
|
|
85
|
+
MESHES = {
|
|
86
|
+
"ch2": (
|
|
87
|
+
"BrainMesh_Ch2withCerebellum.nv",
|
|
88
|
+
"a6bdca96dcb1195829567c1b29d250cae50146c3cd2e7f24b384d3dfdd7d122b",
|
|
89
|
+
),
|
|
90
|
+
"icbm152": (
|
|
91
|
+
"BrainMesh_ICBM152.nv",
|
|
92
|
+
"d68a41d966a36de91b7ae766d2b7aa5c71120de6c11fa68ea04f8a9c0406bea7",
|
|
93
|
+
),
|
|
94
|
+
"icbm152_smoothed": (
|
|
95
|
+
"BrainMesh_ICBM152_smoothed.nv",
|
|
96
|
+
"e2ee8c7e91f42b16e19b84228e8bb43c70389911c567fc4d5a9da03288b614ae",
|
|
97
|
+
),
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
SIZE = (1600, 1000)
|
|
101
|
+
# Left lateral framing fitted to the 2014 frames (1600 x 1000): image column
|
|
102
|
+
# = 740.27 - 5.5288 * y and row = 513.15 - 5.5288 * z, in MNI mm.
|
|
103
|
+
_PX_PER_MM = 5.5288
|
|
104
|
+
_FOCAL = np.array(
|
|
105
|
+
[0.0, -(SIZE[0] / 2 - 740.27) / _PX_PER_MM, (513.15 - SIZE[1] / 2) / _PX_PER_MM]
|
|
106
|
+
)
|
|
107
|
+
_PARALLEL_SCALE = SIZE[1] / 2 / _PX_PER_MM
|
|
108
|
+
# Dorsal/ventral views: centered on the Ch2 mesh's y range (-104.4 to 72.7 mm),
|
|
109
|
+
# with 5% more room so the 177 mm long brain fits the image height.
|
|
110
|
+
_FOCAL_AXIAL = np.array([0.0, -15.85, _FOCAL[2]])
|
|
111
|
+
# view -> (direction from the focal point to the camera, camera up vector)
|
|
112
|
+
VIEWS = {
|
|
113
|
+
"left": ((-1.0, 0.0, 0.0), (0.0, 0.0, 1.0)),
|
|
114
|
+
"lateral": ((-1.0, 0.0, 0.0), (0.0, 0.0, 1.0)),
|
|
115
|
+
"right": ((1.0, 0.0, 0.0), (0.0, 0.0, 1.0)),
|
|
116
|
+
"dorsal": ((0.0, 0.0, 1.0), (0.0, 1.0, 0.0)),
|
|
117
|
+
"ventral": ((0.0, 0.0, -1.0), (0.0, 1.0, 0.0)),
|
|
118
|
+
"anterior": ((0.0, 1.0, 0.0), (0.0, 0.0, 1.0)),
|
|
119
|
+
"posterior": ((0.0, -1.0, 0.0), (0.0, 0.0, 1.0)),
|
|
120
|
+
}
|
|
121
|
+
EDGE_OPACITY = 0.7
|
|
122
|
+
_DULL = {"ambient": 0.3, "diffuse": 0.8, "specular": 0.0} # MATLAB `material dull`
|
|
123
|
+
_SUPERSAMPLE = 2
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _pil() -> Any:
|
|
127
|
+
return lazy_import("PIL.Image", "brain3d", "network plots")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# --------------------------------------------------------------------- file io
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def read_node(path: str | os.PathLike) -> tuple[Array, Array, Array, list[str]]:
|
|
134
|
+
"""Read a BrainNet ``.node`` file.
|
|
135
|
+
|
|
136
|
+
Returns
|
|
137
|
+
-------
|
|
138
|
+
centers : ndarray, shape (K, 3)
|
|
139
|
+
colors, sizes : ndarray, shape (K,)
|
|
140
|
+
labels : list of str
|
|
141
|
+
``"-"`` where the file has no label.
|
|
142
|
+
"""
|
|
143
|
+
rows = [
|
|
144
|
+
line.split()
|
|
145
|
+
for line in Path(path).read_text().splitlines()
|
|
146
|
+
if line.strip() and not line.lstrip().startswith(("#", "%"))
|
|
147
|
+
]
|
|
148
|
+
if not rows or any(len(r) < 5 for r in rows):
|
|
149
|
+
raise ValueError(f"{path}: a .node row needs x y z color size [label]")
|
|
150
|
+
num = np.array([r[:5] for r in rows], dtype=np.float64)
|
|
151
|
+
labels = [" ".join(r[5:]) if len(r) > 5 else "-" for r in rows]
|
|
152
|
+
return num[:, :3], num[:, 3], num[:, 4], labels
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def write_node(
|
|
156
|
+
path: str | os.PathLike,
|
|
157
|
+
centers: Array,
|
|
158
|
+
sizes: Array | None = None,
|
|
159
|
+
colors: Array | None = None,
|
|
160
|
+
labels: Sequence[str] | None = None,
|
|
161
|
+
) -> Path:
|
|
162
|
+
"""Write a BrainNet ``.node`` file (tab separated, two decimals)."""
|
|
163
|
+
centers = _centers(centers)
|
|
164
|
+
K = len(centers)
|
|
165
|
+
sizes = np.ones(K) if sizes is None else _per_node(sizes, K, "sizes")
|
|
166
|
+
colors = np.ones(K) if colors is None else _per_node(colors, K, "colors")
|
|
167
|
+
labels = ["-"] * K if labels is None else [str(s) for s in labels]
|
|
168
|
+
if len(labels) != K:
|
|
169
|
+
raise ValueError(f"labels has {len(labels)} entries for {K} nodes")
|
|
170
|
+
lines = [
|
|
171
|
+
f"{x:.2f}\t{y:.2f}\t{z:.2f}\t{c:.2f}\t{s:.2f}\t{lab}\n"
|
|
172
|
+
for (x, y, z), c, s, lab in zip(centers, colors, sizes, labels, strict=True)
|
|
173
|
+
]
|
|
174
|
+
Path(path).write_text("".join(lines))
|
|
175
|
+
return Path(path)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def read_edge(path: str | os.PathLike) -> Array:
|
|
179
|
+
"""Read a BrainNet ``.edge`` file (whitespace-separated square matrix)."""
|
|
180
|
+
E = np.loadtxt(path, ndmin=2)
|
|
181
|
+
if E.shape[0] != E.shape[1]:
|
|
182
|
+
raise ValueError(f"{path}: edge matrix is {E.shape}, not square")
|
|
183
|
+
return E
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def write_edge(path: str | os.PathLike, connectivity: Array) -> Path:
|
|
187
|
+
"""Write a BrainNet ``.edge`` file (tab separated, two decimals)."""
|
|
188
|
+
E = np.asarray(connectivity, dtype=np.float64)
|
|
189
|
+
if E.ndim != 2 or E.shape[0] != E.shape[1]:
|
|
190
|
+
raise ValueError(f"connectivity must be (K, K), got {E.shape}")
|
|
191
|
+
np.savetxt(path, E, fmt="%0.2f", delimiter="\t")
|
|
192
|
+
return Path(path)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def read_nv(path: str | os.PathLike) -> tuple[Array, Array]:
|
|
196
|
+
"""Read a BrainNet ``.nv`` mesh.
|
|
197
|
+
|
|
198
|
+
The format is the vertex count, one ``x y z`` row per vertex, the face
|
|
199
|
+
count and one row of three 1-based vertex indices per face.
|
|
200
|
+
|
|
201
|
+
Returns
|
|
202
|
+
-------
|
|
203
|
+
vertices : ndarray, shape (V, 3)
|
|
204
|
+
faces : ndarray of int, shape (F, 3), 0-based
|
|
205
|
+
"""
|
|
206
|
+
tokens = [
|
|
207
|
+
line.split()
|
|
208
|
+
for line in Path(path).read_text().splitlines()
|
|
209
|
+
if line.strip() and not line.lstrip().startswith(("#", "%"))
|
|
210
|
+
]
|
|
211
|
+
nv = int(tokens[0][0])
|
|
212
|
+
vertices = np.array(tokens[1 : 1 + nv], dtype=np.float64)
|
|
213
|
+
nf = int(tokens[1 + nv][0])
|
|
214
|
+
faces = np.array(tokens[2 + nv : 2 + nv + nf], dtype=np.int64) - 1
|
|
215
|
+
if vertices.shape != (nv, 3) or faces.shape != (nf, 3):
|
|
216
|
+
raise ValueError(f"{path}: malformed .nv file")
|
|
217
|
+
if np.any(faces < 0) or np.any(faces >= nv):
|
|
218
|
+
raise ValueError(f"{path}: face indices out of range")
|
|
219
|
+
return vertices, faces
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def write_nv(path: str | os.PathLike, vertices: Array, faces: Array) -> Path:
|
|
223
|
+
"""Write a BrainNet ``.nv`` mesh (``faces`` 0-based, written 1-based)."""
|
|
224
|
+
vertices = np.asarray(vertices, dtype=np.float64)
|
|
225
|
+
faces = np.asarray(faces, dtype=np.int64)
|
|
226
|
+
if vertices.ndim != 2 or vertices.shape[1] != 3:
|
|
227
|
+
raise ValueError(f"vertices must be (V, 3), got {vertices.shape}")
|
|
228
|
+
if faces.ndim != 2 or faces.shape[1] != 3:
|
|
229
|
+
raise ValueError(f"faces must be (F, 3), got {faces.shape}")
|
|
230
|
+
with open(path, "w") as f:
|
|
231
|
+
f.write(f"{len(vertices)}\n")
|
|
232
|
+
np.savetxt(f, vertices, fmt="%.6f")
|
|
233
|
+
f.write(f"{len(faces)}\n")
|
|
234
|
+
np.savetxt(f, faces + 1, fmt="%d")
|
|
235
|
+
return Path(path)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def read_brainnet_config(path: str | os.PathLike) -> dict[str, Any]:
|
|
239
|
+
"""Read a BrainNet Viewer option file (``.mat`` holding struct ``EC``).
|
|
240
|
+
|
|
241
|
+
Returns the struct as nested dicts (``cfg["edg"]["draw_threshold"]``, ...).
|
|
242
|
+
"""
|
|
243
|
+
import scipy.io
|
|
244
|
+
|
|
245
|
+
m = scipy.io.loadmat(str(path), squeeze_me=True, struct_as_record=False)
|
|
246
|
+
if "EC" not in m:
|
|
247
|
+
raise ValueError(f"{path} has no BrainNet option struct 'EC'")
|
|
248
|
+
|
|
249
|
+
def todict(x: Any) -> Any:
|
|
250
|
+
if isinstance(x, scipy.io.matlab.mat_struct):
|
|
251
|
+
return {k: todict(getattr(x, k)) for k in x._fieldnames}
|
|
252
|
+
return x
|
|
253
|
+
|
|
254
|
+
return dict(todict(m["EC"]))
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def config_style(cfg: dict[str, Any]) -> dict[str, Any]:
|
|
258
|
+
"""`plot_network` style keywords from a BrainNet option struct.
|
|
259
|
+
|
|
260
|
+
Uses the background color, mesh color and opacity, the first node color,
|
|
261
|
+
the edge draw threshold, and the first / last edge colormap rows as the
|
|
262
|
+
positive / negative edge colors (BrainNet's two-color edge mode). The view
|
|
263
|
+
is always left lateral: BrainNet 1.43 uses ``view(-90, 0)`` for
|
|
264
|
+
``view_direction`` 1, whatever ``view_az`` holds.
|
|
265
|
+
"""
|
|
266
|
+
edge_cm = np.atleast_2d(np.asarray(cfg["edg"]["CM"], dtype=np.float64))
|
|
267
|
+
node_cm = np.atleast_2d(np.asarray(cfg["nod"]["CM"], dtype=np.float64))
|
|
268
|
+
|
|
269
|
+
def rgb(x: Any) -> tuple[float, ...]:
|
|
270
|
+
return tuple(float(v) for v in np.ravel(x))
|
|
271
|
+
|
|
272
|
+
return {
|
|
273
|
+
"background": rgb(cfg["bak"]["color"]),
|
|
274
|
+
"mesh_color": rgb(cfg["msh"]["color"]),
|
|
275
|
+
"mesh_opacity": float(cfg["msh"]["alpha"]),
|
|
276
|
+
"node_color": rgb(node_cm[0]),
|
|
277
|
+
"threshold": float(cfg["edg"]["draw_threshold"]),
|
|
278
|
+
"positive_color": rgb(edge_cm[0]),
|
|
279
|
+
"negative_color": rgb(edge_cm[-1]),
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
# ---------------------------------------------------------------------- meshes
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def mesh_cache_dir() -> Path:
|
|
287
|
+
"""Folder holding downloaded meshes.
|
|
288
|
+
|
|
289
|
+
``$HTFA_DATA_DIR/brainnet`` if that variable is set, otherwise
|
|
290
|
+
``%LOCALAPPDATA%\\htfa\\brainnet`` on Windows and
|
|
291
|
+
``${XDG_CACHE_HOME:-~/.cache}/htfa/brainnet`` elsewhere.
|
|
292
|
+
"""
|
|
293
|
+
return data_dir() / "brainnet"
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
_ZIP_MAGIC = b"PK\x03\x04"
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _fetch_archive(
|
|
300
|
+
dest: Path, folder: Path, attempts: int = 3, url: str = MESH_ARCHIVE_URL
|
|
301
|
+
) -> None:
|
|
302
|
+
"""Download the zip archive at ``url`` to ``dest``.
|
|
303
|
+
|
|
304
|
+
NITRC sometimes answers with an HTML error page (status 200) instead of
|
|
305
|
+
the archive; a response that does not start with the zip signature is
|
|
306
|
+
retried. The SHA-256 check in `_download_meshes` guards the content.
|
|
307
|
+
"""
|
|
308
|
+
from . import __version__
|
|
309
|
+
|
|
310
|
+
request = urllib.request.Request(
|
|
311
|
+
url,
|
|
312
|
+
headers={
|
|
313
|
+
"User-Agent": f"htfa/{__version__} (+https://github.com/ContextLab/htfa)"
|
|
314
|
+
},
|
|
315
|
+
)
|
|
316
|
+
err: Exception | None = None
|
|
317
|
+
for attempt in range(attempts):
|
|
318
|
+
if attempt:
|
|
319
|
+
time.sleep(2.0 * attempt)
|
|
320
|
+
try:
|
|
321
|
+
with urllib.request.urlopen(request, timeout=60) as response:
|
|
322
|
+
head = response.read(len(_ZIP_MAGIC))
|
|
323
|
+
if head != _ZIP_MAGIC:
|
|
324
|
+
kind = response.headers.get("Content-Type", "")
|
|
325
|
+
raise urllib.error.URLError(
|
|
326
|
+
f"{response.url} returned {kind!r} content that is not a "
|
|
327
|
+
"zip archive"
|
|
328
|
+
)
|
|
329
|
+
with open(dest, "wb") as out:
|
|
330
|
+
out.write(head)
|
|
331
|
+
shutil.copyfileobj(response, out)
|
|
332
|
+
return
|
|
333
|
+
except (urllib.error.URLError, OSError) as e:
|
|
334
|
+
err = e
|
|
335
|
+
raise ConnectionError(
|
|
336
|
+
f"could not download the BrainNet Viewer meshes from {url} "
|
|
337
|
+
f"({err}). Download that file by hand and put the .nv files from "
|
|
338
|
+
f"{_MESH_DIR_IN_ARCHIVE} in {folder}, or pass mesh= a path to a .nv file."
|
|
339
|
+
) from err
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _download_meshes(folder: Path) -> None:
|
|
343
|
+
"""Download BrainNet Viewer 1.43 and extract the meshes in `MESHES`."""
|
|
344
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
345
|
+
print(
|
|
346
|
+
f"htfa: downloading BrainNet Viewer 1.43 (21 MB) from {MESH_ARCHIVE_URL} "
|
|
347
|
+
"for its brain surface meshes (BrainNet Viewer is GPL-licensed; "
|
|
348
|
+
"Xia et al., 2013, PLoS ONE 8: e68910)...",
|
|
349
|
+
file=sys.stderr,
|
|
350
|
+
)
|
|
351
|
+
fd, tmp_name = tempfile.mkstemp(suffix=".zip", dir=folder)
|
|
352
|
+
os.close(fd)
|
|
353
|
+
tmp = Path(tmp_name)
|
|
354
|
+
try:
|
|
355
|
+
_fetch_archive(tmp, folder)
|
|
356
|
+
got = _sha256(tmp)
|
|
357
|
+
if got != MESH_ARCHIVE_SHA256:
|
|
358
|
+
raise ValueError(
|
|
359
|
+
f"{MESH_ARCHIVE_URL} has SHA-256 {got}, expected "
|
|
360
|
+
f"{MESH_ARCHIVE_SHA256}; the download is corrupt or the file changed"
|
|
361
|
+
)
|
|
362
|
+
_extract_meshes(tmp, folder)
|
|
363
|
+
finally:
|
|
364
|
+
tmp.unlink(missing_ok=True)
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _extract_meshes(archive_path: Path, folder: Path) -> None:
|
|
368
|
+
"""Extract the meshes in `MESHES` from the BrainNet Viewer zip into ``folder``.
|
|
369
|
+
|
|
370
|
+
Each file is written to ``<name>.part`` and renamed when complete; a
|
|
371
|
+
``.part`` left by a failure is removed.
|
|
372
|
+
"""
|
|
373
|
+
with zipfile.ZipFile(archive_path) as archive:
|
|
374
|
+
for filename, _ in MESHES.values():
|
|
375
|
+
part = folder / (filename + ".part")
|
|
376
|
+
try:
|
|
377
|
+
with (
|
|
378
|
+
archive.open(_MESH_DIR_IN_ARCHIVE + filename) as src,
|
|
379
|
+
open(part, "wb") as dst,
|
|
380
|
+
):
|
|
381
|
+
shutil.copyfileobj(src, dst)
|
|
382
|
+
os.replace(part, folder / filename)
|
|
383
|
+
finally:
|
|
384
|
+
part.unlink(missing_ok=True)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def fetch_mesh(name: str = "ch2") -> Path:
|
|
388
|
+
"""Path to a BrainNet Viewer mesh, downloading it on first use.
|
|
389
|
+
|
|
390
|
+
Parameters
|
|
391
|
+
----------
|
|
392
|
+
name : {"ch2", "icbm152", "icbm152_smoothed"}
|
|
393
|
+
``"ch2"`` is ``BrainMesh_Ch2withCerebellum.nv`` and includes the
|
|
394
|
+
cerebellum; the ICBM152 meshes have no cerebellum.
|
|
395
|
+
|
|
396
|
+
Raises
|
|
397
|
+
------
|
|
398
|
+
ConnectionError
|
|
399
|
+
If the mesh is not cached and cannot be downloaded.
|
|
400
|
+
ValueError
|
|
401
|
+
If a downloaded file does not match its SHA-256 checksum.
|
|
402
|
+
"""
|
|
403
|
+
if name not in MESHES:
|
|
404
|
+
raise ValueError(f"unknown mesh {name!r}; choose from {sorted(MESHES)}")
|
|
405
|
+
filename, sha = MESHES[name]
|
|
406
|
+
path = mesh_cache_dir() / filename
|
|
407
|
+
if path.exists() and _sha256(path) == sha:
|
|
408
|
+
return path
|
|
409
|
+
_download_meshes(path.parent)
|
|
410
|
+
got = _sha256(path)
|
|
411
|
+
if got != sha:
|
|
412
|
+
raise ValueError(f"{path} has SHA-256 {got}, expected {sha}")
|
|
413
|
+
return path
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def load_mesh(mesh: Any) -> tuple[Array, Array] | None:
|
|
417
|
+
"""Resolve ``mesh`` to ``(vertices, faces)``.
|
|
418
|
+
|
|
419
|
+
``mesh`` is a name in `MESHES`, a path to a ``.nv`` file, a
|
|
420
|
+
``(vertices, faces)`` pair (faces 0-based), or ``None`` (no surface).
|
|
421
|
+
"""
|
|
422
|
+
if mesh is None:
|
|
423
|
+
return None
|
|
424
|
+
if isinstance(mesh, str) and mesh in MESHES:
|
|
425
|
+
return read_nv(fetch_mesh(mesh))
|
|
426
|
+
if isinstance(mesh, (str, os.PathLike)):
|
|
427
|
+
if not Path(mesh).is_file():
|
|
428
|
+
raise ValueError(
|
|
429
|
+
f"mesh {mesh!r} is neither a file nor one of {sorted(MESHES)}"
|
|
430
|
+
)
|
|
431
|
+
return read_nv(mesh)
|
|
432
|
+
vertices, faces = mesh
|
|
433
|
+
return np.asarray(vertices, dtype=np.float64), np.asarray(faces, dtype=np.int64)
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
# ------------------------------------------------------------------- rendering
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def node_radius(
|
|
440
|
+
sizes: Any,
|
|
441
|
+
lo: float = 2.0,
|
|
442
|
+
hi: float = 7.0,
|
|
443
|
+
*,
|
|
444
|
+
k: float | None = None,
|
|
445
|
+
b: float | None = None,
|
|
446
|
+
clip: tuple[float, float] | None = None,
|
|
447
|
+
) -> Array:
|
|
448
|
+
"""Sphere radii in mm from node sizes, BrainNet Viewer's ``k * size + b``.
|
|
449
|
+
|
|
450
|
+
By default ``k`` and ``b`` map the smallest size to ``lo`` and the
|
|
451
|
+
largest to ``hi`` (BrainNet "size by value": 2-7 mm). All-equal sizes
|
|
452
|
+
give 4 mm, as in BrainNet Viewer.
|
|
453
|
+
|
|
454
|
+
Parameters
|
|
455
|
+
----------
|
|
456
|
+
sizes : array of shape (K,)
|
|
457
|
+
lo, hi : float
|
|
458
|
+
Radii of the smallest and largest size, ``lo < hi``.
|
|
459
|
+
k, b : float, optional
|
|
460
|
+
A fixed mapping ``k * size + b`` instead (both needed), e.g. the
|
|
461
|
+
``nod.k`` / ``nod.b`` stored in a BrainNet option file, so that radii
|
|
462
|
+
are comparable across plots.
|
|
463
|
+
clip : (float, float), optional
|
|
464
|
+
Clip the radii to this range afterwards.
|
|
465
|
+
|
|
466
|
+
Returns
|
|
467
|
+
-------
|
|
468
|
+
ndarray, shape (K,)
|
|
469
|
+
|
|
470
|
+
Examples
|
|
471
|
+
--------
|
|
472
|
+
>>> from htfa.brainnet import node_radius
|
|
473
|
+
>>> node_radius([1.0, 2.0, 3.0]).tolist()
|
|
474
|
+
[2.0, 4.5, 7.0]
|
|
475
|
+
>>> node_radius([1.0, 2.0, 3.0], k=3.0, b=0.0, clip=(0.0, 7.0)).tolist()
|
|
476
|
+
[3.0, 6.0, 7.0]
|
|
477
|
+
"""
|
|
478
|
+
s = np.asarray(sizes, dtype=np.float64)
|
|
479
|
+
if (k is None) != (b is None):
|
|
480
|
+
raise ValueError("give both k and b, or neither")
|
|
481
|
+
if not lo < hi:
|
|
482
|
+
raise ValueError(f"need lo < hi, got lo={lo}, hi={hi}")
|
|
483
|
+
if clip is not None and not clip[0] <= clip[1]:
|
|
484
|
+
raise ValueError(f"clip must be (min, max) with min <= max, got {clip}")
|
|
485
|
+
if k is not None and b is not None:
|
|
486
|
+
r = k * s + b
|
|
487
|
+
elif s.max() == s.min():
|
|
488
|
+
r = np.full_like(s, 4.0)
|
|
489
|
+
else:
|
|
490
|
+
slope = (hi - lo) / (s.max() - s.min())
|
|
491
|
+
r = slope * s + (hi - slope * s.max())
|
|
492
|
+
return r if clip is None else np.clip(r, clip[0], clip[1])
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def _centers(centers: Any) -> Array:
|
|
496
|
+
c = np.asarray(centers, dtype=np.float64)
|
|
497
|
+
if c.ndim != 2 or c.shape[1] != 3:
|
|
498
|
+
raise ValueError(f"node centers must be (K, 3) MNI coordinates, got {c.shape}")
|
|
499
|
+
return c
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def _per_node(values: Any, K: int, what: str) -> Array:
|
|
503
|
+
v = np.asarray(values, dtype=np.float64).ravel()
|
|
504
|
+
if v.shape != (K,):
|
|
505
|
+
raise ValueError(f"{what} has {v.size} entries for {K} nodes")
|
|
506
|
+
return v
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def _nodes(nodes: Any, sizes: Any, subject: Any) -> tuple[Array, Array]:
|
|
510
|
+
"""Centers and sizes from an HTFAResults, a fitted TFA/HTFA, or an array."""
|
|
511
|
+
centers, widths = _fit_nodes(nodes, subject)
|
|
512
|
+
K = len(centers)
|
|
513
|
+
if sizes is not None:
|
|
514
|
+
return centers, _per_node(sizes, K, "sizes")
|
|
515
|
+
return centers, np.ones(K) if widths is None else widths
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def _fit_nodes(nodes: Any, subject: Any) -> tuple[Array, Array | None]:
|
|
519
|
+
"""Centers and widths (``None`` for an array) of ``nodes``."""
|
|
520
|
+
from .htfa import HTFA
|
|
521
|
+
from .results import HTFAResults
|
|
522
|
+
from .tfa import TFA
|
|
523
|
+
|
|
524
|
+
if isinstance(nodes, HTFAResults):
|
|
525
|
+
if subject == "global" and nodes.global_centers is None:
|
|
526
|
+
raise ValueError("a TFA fit has no global template; pass subject=0")
|
|
527
|
+
centers, widths = nodes._fitted_nodes(subject)
|
|
528
|
+
elif isinstance(nodes, HTFA):
|
|
529
|
+
if subject == "global":
|
|
530
|
+
centers, widths = nodes.global_centers_, nodes.global_widths_
|
|
531
|
+
else:
|
|
532
|
+
centers, widths = nodes.centers_[subject], nodes.widths_[subject]
|
|
533
|
+
elif isinstance(nodes, TFA):
|
|
534
|
+
centers, widths = nodes.centers_, nodes.widths_
|
|
535
|
+
else:
|
|
536
|
+
centers, widths = nodes, None
|
|
537
|
+
centers = _centers(centers)
|
|
538
|
+
return centers, None if widths is None else _per_node(
|
|
539
|
+
widths, len(centers), "widths"
|
|
540
|
+
)
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def _fit_shape(nodes: Any, subject: Any) -> tuple[str, Array, Array, Array] | None:
|
|
544
|
+
"""Kernel name and component centers, widths and mixing weights of a fit
|
|
545
|
+
whose factors are not single RBFs (None for those and for arrays)."""
|
|
546
|
+
from .htfa import HTFA
|
|
547
|
+
from .results import HTFAResults
|
|
548
|
+
from .tfa import TFA
|
|
549
|
+
|
|
550
|
+
if isinstance(nodes, HTFAResults):
|
|
551
|
+
return nodes._shape(subject)
|
|
552
|
+
if not isinstance(nodes, (HTFA, TFA)):
|
|
553
|
+
return None
|
|
554
|
+
kernel = Kernel(getattr(nodes, "kernel", "rbf"), getattr(nodes, "n_components", 1))
|
|
555
|
+
if kernel.plain_rbf:
|
|
556
|
+
return None
|
|
557
|
+
if isinstance(nodes, TFA):
|
|
558
|
+
parts = (nodes.component_centers_, nodes.component_widths_)
|
|
559
|
+
return (kernel.name, *parts, nodes.mixing_weights_)
|
|
560
|
+
if subject == "global":
|
|
561
|
+
return (
|
|
562
|
+
kernel.name,
|
|
563
|
+
nodes.global_component_centers_,
|
|
564
|
+
nodes.global_component_widths_,
|
|
565
|
+
nodes.global_mixing_weights_,
|
|
566
|
+
)
|
|
567
|
+
return (
|
|
568
|
+
kernel.name,
|
|
569
|
+
nodes.component_centers_[subject],
|
|
570
|
+
nodes.component_widths_[subject],
|
|
571
|
+
nodes.mixing_weights_[subject],
|
|
572
|
+
)
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
# ------------------------------------------------------------- effective nodes
|
|
576
|
+
|
|
577
|
+
_TAIL_SIGMAS = 5.0 # RBF weights beyond 5 sigma (exp(-12.5)) are left out
|
|
578
|
+
_TAIL_LOG = _TAIL_SIGMAS**2 / 2 # the other kernels: profile values below exp(-12.5)
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def _reach(kernel: str, w: float, D: int) -> float:
|
|
582
|
+
"""Radius beyond which a component of width ``w`` is left out: its profile
|
|
583
|
+
is below ``exp(-12.5)`` there (``'mexican_hat'``: the positive lobe,
|
|
584
|
+
``r < sqrt(D w / 2)``)."""
|
|
585
|
+
if kernel == "rbf":
|
|
586
|
+
return math.sqrt(_TAIL_LOG * w)
|
|
587
|
+
if kernel == "laplace":
|
|
588
|
+
return math.sqrt(w * ((_TAIL_LOG + LAPLACE_EPS) ** 2 - LAPLACE_EPS**2))
|
|
589
|
+
return math.sqrt(D * w / 2)
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
_UNIT_MASS: dict[tuple[str, int], float] = {}
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def _unit_mass(kernel: str, D: int) -> float:
|
|
596
|
+
"""Integral over R^D of a width-1 component's profile (``'mexican_hat'``:
|
|
597
|
+
of its positive lobe); ``pi**(D / 2)`` for the RBF."""
|
|
598
|
+
if (kernel, D) not in _UNIT_MASS:
|
|
599
|
+
from scipy.integrate import quad
|
|
600
|
+
|
|
601
|
+
profile = Kernel(kernel).profile
|
|
602
|
+
upper = math.sqrt(D / 2) if kernel == "mexican_hat" else np.inf
|
|
603
|
+
radial = quad(
|
|
604
|
+
lambda t: float(profile(np.array(t * t), D)) * t ** (D - 1), 0, upper
|
|
605
|
+
)
|
|
606
|
+
sphere = 2 * math.pi ** (D / 2) / math.gamma(D / 2)
|
|
607
|
+
_UNIT_MASS[kernel, D] = sphere * radial[0]
|
|
608
|
+
return _UNIT_MASS[kernel, D]
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
_TIE_TOL = 1e-3 # distances within 1e-3 voxel count as tied
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def mni_mask() -> Array:
|
|
615
|
+
"""Voxel centers (V, 3) of nilearn's 2 mm MNI152 brain mask, in MNI mm.
|
|
616
|
+
|
|
617
|
+
The default mask for snapping bare node centers (`effective_nodes`,
|
|
618
|
+
`plot_network`): the BrainNet meshes are in MNI space. Needs nilearn (the
|
|
619
|
+
``nilearn`` extra); the mask ships with nilearn, so nothing is downloaded.
|
|
620
|
+
|
|
621
|
+
Raises
|
|
622
|
+
------
|
|
623
|
+
ImportError
|
|
624
|
+
If nilearn is missing and cannot be installed; pass ``mask=`` or
|
|
625
|
+
``snap=False`` instead.
|
|
626
|
+
|
|
627
|
+
Examples
|
|
628
|
+
--------
|
|
629
|
+
>>> from htfa.brainnet import effective_nodes, mni_mask
|
|
630
|
+
>>> mask = mni_mask()
|
|
631
|
+
>>> mask.shape[1]
|
|
632
|
+
3
|
|
633
|
+
>>> c, _, info = effective_nodes([[0.0, 95.0, 0.0]], None, mask) # frontal pole
|
|
634
|
+
>>> bool(info["snapped"][0]), bool(c[0, 1] < 75)
|
|
635
|
+
(True, True)
|
|
636
|
+
"""
|
|
637
|
+
return _mni_mask().copy()
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
_MNI_CACHE: list[Array] = []
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def _mni_mask() -> Array:
|
|
644
|
+
if not _MNI_CACHE:
|
|
645
|
+
try:
|
|
646
|
+
datasets = lazy_import("nilearn.datasets", "nilearn", "the MNI brain mask")
|
|
647
|
+
except ImportError as err:
|
|
648
|
+
raise ImportError(
|
|
649
|
+
f"{err}\nSnapping nodes into the brain needs a mask: the default "
|
|
650
|
+
"for bare MNI centers is nilearn's MNI152 brain mask. Pass mask= "
|
|
651
|
+
"(voxel coordinates or a NIfTI mask) or snap=False."
|
|
652
|
+
) from err
|
|
653
|
+
img = datasets.load_mni152_brain_mask(resolution=2)
|
|
654
|
+
_MNI_CACHE.append(_mask_coords(img)[0])
|
|
655
|
+
return _MNI_CACHE[0]
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def _mask_coords(mask: Any, dim: int | None = None) -> tuple[Array, Array, float]:
|
|
659
|
+
"""Voxel centers, per-axis voxel spacing and voxel volume of a mask.
|
|
660
|
+
|
|
661
|
+
``mask`` is a (V, D) coordinate array, a NIfTI-like image (nonzero
|
|
662
|
+
voxels), or a ``(volume, affine)`` pair. For an image the spacing along
|
|
663
|
+
each world axis is the extent of one voxel along it and the volume is
|
|
664
|
+
``|det(affine[:3, :3])|``. For coordinates the spacing along an axis is
|
|
665
|
+
the median gap between neighboring voxels on the same grid line, and the
|
|
666
|
+
volume is the product of the spacings; voxels off the grid of the first
|
|
667
|
+
voxel (e.g. a union of subjects' differently aligned grids) are moved to
|
|
668
|
+
the nearest point of that grid, so that every region is counted once.
|
|
669
|
+
``dim``, if given, is the number of dimensions the mask must have.
|
|
670
|
+
"""
|
|
671
|
+
if isinstance(mask, tuple) or (
|
|
672
|
+
hasattr(mask, "affine") and hasattr(mask, "dataobj")
|
|
673
|
+
):
|
|
674
|
+
volume, affine = (
|
|
675
|
+
mask if isinstance(mask, tuple) else (mask.dataobj, mask.affine)
|
|
676
|
+
)
|
|
677
|
+
out = _volume_coords(np.asarray(volume), np.asarray(affine, dtype=float))
|
|
678
|
+
_check_dim(out[0], dim)
|
|
679
|
+
return out
|
|
680
|
+
coords = np.asarray(mask, dtype=np.float64)
|
|
681
|
+
if coords.ndim != 2:
|
|
682
|
+
raise ValueError(f"mask coordinates must be (V, D), got {coords.shape}")
|
|
683
|
+
_check_dim(coords, dim)
|
|
684
|
+
if len(coords) == 0:
|
|
685
|
+
raise ValueError("mask has no voxels")
|
|
686
|
+
if len(coords) == 1:
|
|
687
|
+
raise ValueError("mask coordinates need at least 2 voxels to set the spacing")
|
|
688
|
+
spacing = _grid_spacing(coords)
|
|
689
|
+
if not np.all(spacing > 0):
|
|
690
|
+
raise ValueError("mask voxels coincide: cannot tell the voxel spacing")
|
|
691
|
+
idx = (coords - coords[0]) / spacing
|
|
692
|
+
if np.abs(idx - np.round(idx)).max() > 1e-3:
|
|
693
|
+
grid = np.unique(np.floor(idx + 0.5), axis=0)
|
|
694
|
+
coords = coords[0] + grid * spacing
|
|
695
|
+
return coords, spacing, float(np.prod(spacing))
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def _check_dim(coords: Array, dim: int | None) -> None:
|
|
699
|
+
if dim is not None and coords.shape[1] != dim:
|
|
700
|
+
raise ValueError(
|
|
701
|
+
f"mask has {coords.shape[1]} dimensions but centers have {dim}"
|
|
702
|
+
)
|
|
703
|
+
|
|
704
|
+
|
|
705
|
+
def _grid_spacing(coords: Array) -> Array:
|
|
706
|
+
"""Per-axis median gap between neighboring voxels on one grid line."""
|
|
707
|
+
q = np.round(coords, 3)
|
|
708
|
+
spacing = np.empty(q.shape[1])
|
|
709
|
+
for a in range(q.shape[1]):
|
|
710
|
+
other = np.delete(q, a, axis=1)
|
|
711
|
+
order = np.lexsort((q[:, a], *other.T[::-1]))
|
|
712
|
+
same = np.all(other[order][1:] == other[order][:-1], axis=1)
|
|
713
|
+
gaps = np.diff(q[order, a])[same]
|
|
714
|
+
gaps = gaps[gaps > 1e-6]
|
|
715
|
+
if len(gaps):
|
|
716
|
+
spacing[a] = np.median(gaps)
|
|
717
|
+
else: # no two voxels share a line along this axis
|
|
718
|
+
spacing[a] = np.median(cKDTree(coords).query(coords, k=2)[0][:, 1])
|
|
719
|
+
return spacing
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
def _volume_coords(volume: Array, affine: Array) -> tuple[Array, Array, float]:
|
|
723
|
+
ijk = np.argwhere(volume.astype(bool))
|
|
724
|
+
if not len(ijk):
|
|
725
|
+
raise ValueError("mask has no voxels")
|
|
726
|
+
A = affine[:3, :3]
|
|
727
|
+
coords = ijk @ A.T + affine[:3, 3]
|
|
728
|
+
return coords, np.abs(A).sum(axis=1), float(abs(np.linalg.det(A)))
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
def _lowest_tied(tree: Any, points: Array, tol: float, p: float) -> tuple[Array, Array]:
|
|
732
|
+
"""Nearest voxel of each point, the lowest voxel index among near-ties.
|
|
733
|
+
|
|
734
|
+
Distances within ``tol`` of the nearest count as tied. Returns the voxel
|
|
735
|
+
indices and whether another voxel was tied.
|
|
736
|
+
"""
|
|
737
|
+
k = min(8, tree.n)
|
|
738
|
+
d, i = tree.query(points, k=k, p=p)
|
|
739
|
+
d, i = d.reshape(len(points), k), i.reshape(len(points), k)
|
|
740
|
+
tied = d <= d[:, :1] + tol
|
|
741
|
+
best = np.where(tied, i, tree.n).min(axis=1)
|
|
742
|
+
return best, tied.sum(axis=1) > 1
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
def effective_nodes(
|
|
746
|
+
centers: Any,
|
|
747
|
+
widths: Any,
|
|
748
|
+
mask: Any,
|
|
749
|
+
kernel: str = "rbf",
|
|
750
|
+
mixing_weights: Any = None,
|
|
751
|
+
) -> tuple[Array, Array, dict[str, Array]]:
|
|
752
|
+
"""In-mask ("effective") centers and widths of RBF nodes, for display.
|
|
753
|
+
|
|
754
|
+
A fitted center may lie outside the brain: an RBF there still reaches into
|
|
755
|
+
it, and is how a fit explains a blurry cortical activation. A plot should
|
|
756
|
+
not draw a node where no brain is, so the built-in plots show each node as
|
|
757
|
+
the part of its RBF that lies inside the mask, ``F(v) = exp(-||r_v - c||^2
|
|
758
|
+
/ lambda)`` over the mask voxels ``r_v``:
|
|
759
|
+
|
|
760
|
+
- center: the F-weighted centroid of the mask voxels. Interior nodes keep
|
|
761
|
+
their center; nodes near the edge move inward. If the centroid falls
|
|
762
|
+
outside the mask (a concave mask: not within half a voxel of a mask
|
|
763
|
+
voxel), it is snapped to the first mask voxel on the segment from the
|
|
764
|
+
centroid to the original center, or, if that segment never enters the
|
|
765
|
+
mask, to the mask voxel nearest the centroid.
|
|
766
|
+
- width: ``lambda_eff = 2 * sigma_eff**2``, where ``sigma_eff**2`` is the
|
|
767
|
+
F-weighted per-axis variance about the centroid, averaged over axes.
|
|
768
|
+
An RBF has per-axis variance ``lambda / 2``, so interior nodes keep
|
|
769
|
+
``lambda`` (to within 0.2% on 2 mm and 4 mm grids for
|
|
770
|
+
``20 <= lambda <= 400`` mm^2).
|
|
771
|
+
|
|
772
|
+
The fit is not changed. Ties between equally near voxels (e.g. a node on
|
|
773
|
+
the midline between the hemispheres) go to the lowest voxel index and
|
|
774
|
+
are flagged ``ambiguous``.
|
|
775
|
+
|
|
776
|
+
Other kernels and mixtures (``kernel``, component ``centers`` (K, M, D))
|
|
777
|
+
use their own profile ``F`` in place of the RBF's, summed over the
|
|
778
|
+
components with the mixing weights: for ``'mexican_hat'`` its positive
|
|
779
|
+
part ``max(F, 0)`` (the centre, not the negative surround, is the node).
|
|
780
|
+
``lambda_eff = 2 sigma_eff**2`` is then the width of the RBF with the
|
|
781
|
+
same spread: an interior node has ``lambda_eff = 6.02 w`` (D = 2) or
|
|
782
|
+
``8.01 w`` (D = 3) for ``'laplace'`` (``2 (D + 1) w`` without the
|
|
783
|
+
rounding at its center), and ``0.282 w`` or ``0.351 w`` for
|
|
784
|
+
``'mexican_hat'`` (by numerical integration). The mass fraction divides by
|
|
785
|
+
the summed masses of the components (positive lobes), each fully inside;
|
|
786
|
+
voxels where every component is below ``exp(-12.5)`` are left out, and a
|
|
787
|
+
node with no voxel left (far outside the mask) is treated as a point.
|
|
788
|
+
|
|
789
|
+
Parameters
|
|
790
|
+
----------
|
|
791
|
+
centers : array of shape (K, D) or (K, M, D)
|
|
792
|
+
Node centers, or component centers of nodes with M components.
|
|
793
|
+
widths : array of shape (K,) or (K, M), or None
|
|
794
|
+
RBF widths ``lambda`` (the BrainIAK convention ``2 * sigma**2``), or
|
|
795
|
+
the components' widths. ``None`` treats the nodes as points: a
|
|
796
|
+
center within half a voxel of the mask stays, any other goes to the
|
|
797
|
+
nearest mask voxel, and the widths and masses are NaN.
|
|
798
|
+
mask : array of shape (V, D), NIfTI image or (volume, affine)
|
|
799
|
+
The in-brain voxels: voxel centers on a regular grid (its spacing
|
|
800
|
+
may differ per axis; a union of differently aligned grids is moved
|
|
801
|
+
onto the grid of the first voxel), or a mask image whose nonzero
|
|
802
|
+
voxels count. "Within half a voxel" is per axis. `mni_mask` gives
|
|
803
|
+
the MNI152 brain.
|
|
804
|
+
|
|
805
|
+
Returns
|
|
806
|
+
-------
|
|
807
|
+
centers_eff : ndarray, shape (K, D)
|
|
808
|
+
widths_eff : ndarray, shape (K,)
|
|
809
|
+
``lambda_eff``.
|
|
810
|
+
info : dict of ndarray, shape (K,)
|
|
811
|
+
``distance`` (from the original center, in coordinate units),
|
|
812
|
+
``snapped`` (the centroid fell outside the mask), ``ambiguous``
|
|
813
|
+
(tied nearest voxels), ``mass_fraction`` (in-mask RBF mass over the
|
|
814
|
+
mass of an RBF fully inside, ``(pi * lambda)**(D / 2)`` divided by
|
|
815
|
+
the voxel volume), ``sigma`` (``sigma_eff``) and ``width_ratio``
|
|
816
|
+
(``lambda_eff / lambda``; with components, ``lambda`` is their
|
|
817
|
+
mixing-weighted mean width).
|
|
818
|
+
kernel : {'rbf', 'laplace', 'mexican_hat'}, default='rbf'
|
|
819
|
+
Shape of the nodes (see `htfa.TFA`).
|
|
820
|
+
mixing_weights : array of shape (K, M), optional
|
|
821
|
+
Mixing weights of component centers (default: equal).
|
|
822
|
+
|
|
823
|
+
Examples
|
|
824
|
+
--------
|
|
825
|
+
>>> import numpy as np
|
|
826
|
+
>>> from htfa.brainnet import effective_nodes
|
|
827
|
+
>>> ax = np.arange(-20.0, 21.0, 2.0)
|
|
828
|
+
>>> grid = np.stack(np.meshgrid(ax, ax, ax, indexing="ij"), -1).reshape(-1, 3)
|
|
829
|
+
>>> ball = grid[np.linalg.norm(grid, axis=1) <= 20]
|
|
830
|
+
>>> c, w, info = effective_nodes([[0.0, 0.0, 30.0]], [50.0], ball)
|
|
831
|
+
>>> bool(np.linalg.norm(c[0]) < 20), bool(info["snapped"][0])
|
|
832
|
+
(True, False)
|
|
833
|
+
"""
|
|
834
|
+
c = np.asarray(centers, dtype=np.float64)
|
|
835
|
+
if c.ndim not in (2, 3):
|
|
836
|
+
raise ValueError(f"centers must be (K, D) or (K, M, D), got {c.shape}")
|
|
837
|
+
shape = Kernel(kernel, 1 if c.ndim == 2 else c.shape[1])
|
|
838
|
+
if c.ndim == 2 and mixing_weights is not None:
|
|
839
|
+
raise ValueError("mixing_weights need component centers (K, M, D)")
|
|
840
|
+
comps = None
|
|
841
|
+
if c.ndim == 3:
|
|
842
|
+
if widths is None:
|
|
843
|
+
raise ValueError("component centers (K, M, D) need their widths")
|
|
844
|
+
Kc, M, _ = c.shape
|
|
845
|
+
wc = np.asarray(widths, dtype=np.float64).reshape(Kc, M)
|
|
846
|
+
if mixing_weights is None:
|
|
847
|
+
pi = np.full((Kc, M), 1.0 / M)
|
|
848
|
+
else:
|
|
849
|
+
pi = np.asarray(mixing_weights, dtype=np.float64).reshape(Kc, M)
|
|
850
|
+
comps = (c, wc, pi)
|
|
851
|
+
c = np.einsum("km,kmd->kd", pi, c)
|
|
852
|
+
widths = np.sum(pi * wc, axis=1)
|
|
853
|
+
if not np.all(wc > 0):
|
|
854
|
+
raise ValueError("widths must be positive")
|
|
855
|
+
K, D = c.shape
|
|
856
|
+
coords, spacing, voxel_volume = _mask_coords(mask, D)
|
|
857
|
+
w = None if widths is None else _per_node(widths, K, "widths")
|
|
858
|
+
if w is not None and not np.all(w > 0):
|
|
859
|
+
raise ValueError("widths must be positive")
|
|
860
|
+
if comps is None and w is not None:
|
|
861
|
+
comps = (c[:, None], w[:, None], np.ones((K, 1)))
|
|
862
|
+
tree = cKDTree(coords)
|
|
863
|
+
grid = cKDTree(coords / spacing) # voxel units: "inside" is <= 0.5 per axis
|
|
864
|
+
half = 0.5 * (1 + 1e-9)
|
|
865
|
+
out = c.copy()
|
|
866
|
+
sigma = np.full(K, np.nan)
|
|
867
|
+
mass = np.full(K, np.nan)
|
|
868
|
+
snapped = np.zeros(K, dtype=bool)
|
|
869
|
+
ambiguous = np.zeros(K, dtype=bool)
|
|
870
|
+
if comps is not None and not shape.plain_rbf:
|
|
871
|
+
for k in range(K):
|
|
872
|
+
ck, wk, pk = comps[0][k], comps[1][k], comps[2][k]
|
|
873
|
+
dm = tree.query(ck)[0]
|
|
874
|
+
idx = sorted(
|
|
875
|
+
set().union(
|
|
876
|
+
*(
|
|
877
|
+
tree.query_ball_point(ck[m], dm[m] + _reach(kernel, wk[m], D))
|
|
878
|
+
for m in range(len(wk))
|
|
879
|
+
)
|
|
880
|
+
)
|
|
881
|
+
)
|
|
882
|
+
r = coords[idx]
|
|
883
|
+
f = np.zeros(len(r))
|
|
884
|
+
for m in range(len(wk)):
|
|
885
|
+
z = np.sum((r - ck[m]) ** 2, axis=1) / wk[m]
|
|
886
|
+
f += pk[m] * shape.profile(z, D)
|
|
887
|
+
if kernel == "mexican_hat":
|
|
888
|
+
f = np.maximum(f, 0.0)
|
|
889
|
+
total = f.sum()
|
|
890
|
+
if not total > 0:
|
|
891
|
+
continue # nothing of the node inside: a point
|
|
892
|
+
m_k = f @ r / total
|
|
893
|
+
sigma[k] = np.sqrt(f @ np.sum((r - m_k) ** 2, axis=1) / total / D)
|
|
894
|
+
full = _unit_mass(kernel, D) * np.sum(pk * wk ** (D / 2))
|
|
895
|
+
mass[k] = total * voxel_volume / full
|
|
896
|
+
out[k] = m_k
|
|
897
|
+
elif w is not None:
|
|
898
|
+
dmin = tree.query(c)[0]
|
|
899
|
+
for k in range(K):
|
|
900
|
+
s = np.sqrt(w[k] / 2)
|
|
901
|
+
idx = tree.query_ball_point(c[k], dmin[k] + _TAIL_SIGMAS * s)
|
|
902
|
+
r = coords[idx]
|
|
903
|
+
d2 = np.sum((r - c[k]) ** 2, axis=1)
|
|
904
|
+
f = np.exp(-(d2 - dmin[k] ** 2) / w[k]) # scaled by exp(dmin^2 / w)
|
|
905
|
+
total = f.sum()
|
|
906
|
+
m = f @ r / total
|
|
907
|
+
sigma[k] = np.sqrt(f @ np.sum((r - m) ** 2, axis=1) / total / D)
|
|
908
|
+
mass[k] = (
|
|
909
|
+
total
|
|
910
|
+
* np.exp(-(dmin[k] ** 2) / w[k])
|
|
911
|
+
* voxel_volume
|
|
912
|
+
/ (np.pi * w[k]) ** (D / 2)
|
|
913
|
+
)
|
|
914
|
+
out[k] = m
|
|
915
|
+
inside = grid.query(out / spacing, p=np.inf)[0] <= half
|
|
916
|
+
for k in np.flatnonzero(~inside).tolist():
|
|
917
|
+
snapped[k] = True
|
|
918
|
+
hit = _first_hit(grid, out[k] / spacing, c[k] / spacing)
|
|
919
|
+
if hit is not None:
|
|
920
|
+
i, tie = _lowest_tied(grid, hit[None], _TIE_TOL, np.inf)
|
|
921
|
+
else:
|
|
922
|
+
i, tie = _lowest_tied(tree, out[k : k + 1], _TIE_TOL * spacing.min(), 2.0)
|
|
923
|
+
out[k], ambiguous[k] = coords[i[0]], tie[0]
|
|
924
|
+
widths_eff = 2 * sigma**2
|
|
925
|
+
info = {
|
|
926
|
+
"distance": np.linalg.norm(out - c, axis=1),
|
|
927
|
+
"snapped": snapped,
|
|
928
|
+
"ambiguous": ambiguous,
|
|
929
|
+
"mass_fraction": mass,
|
|
930
|
+
"sigma": sigma,
|
|
931
|
+
"width_ratio": widths_eff / w if w is not None else np.full(K, np.nan),
|
|
932
|
+
}
|
|
933
|
+
return out, widths_eff, info
|
|
934
|
+
|
|
935
|
+
|
|
936
|
+
def _first_hit(grid: Any, start: Array, stop: Array) -> Array | None:
|
|
937
|
+
"""First point within half a voxel of the mask on the segment start-stop.
|
|
938
|
+
|
|
939
|
+
Both ends are in voxel units (coordinates / spacing). The walk takes
|
|
940
|
+
quarter-voxel steps, in chunks so that it stops at the first hit, and
|
|
941
|
+
ends where the segment leaves the mask's bounding box.
|
|
942
|
+
"""
|
|
943
|
+
pts = grid.data
|
|
944
|
+
lo, hi = pts.min(axis=0) - 0.5, pts.max(axis=0) + 0.5
|
|
945
|
+
d = stop - start
|
|
946
|
+
t_end = 1.0
|
|
947
|
+
for a in np.flatnonzero(d):
|
|
948
|
+
t_a = ((hi[a] if d[a] > 0 else lo[a]) - start[a]) / d[a]
|
|
949
|
+
t_end = min(t_end, max(t_a, 0.0))
|
|
950
|
+
n = max(1, int(np.ceil(t_end * np.linalg.norm(d) / 0.25)))
|
|
951
|
+
t = np.linspace(0.0, t_end, n + 1)
|
|
952
|
+
for chunk in np.array_split(t, max(1, len(t) // 256)):
|
|
953
|
+
seg = start + chunk[:, None] * d
|
|
954
|
+
hit = np.flatnonzero(grid.query(seg, p=np.inf)[0] <= 0.5 * (1 + 1e-9))
|
|
955
|
+
if len(hit):
|
|
956
|
+
return np.asarray(seg[hit[0]])
|
|
957
|
+
return None
|
|
958
|
+
|
|
959
|
+
|
|
960
|
+
def _default_mask(nodes: Any, subject: Any) -> Any:
|
|
961
|
+
"""The fit's own voxels for an HTFAResults, else the MNI152 brain."""
|
|
962
|
+
from .results import HTFAResults
|
|
963
|
+
|
|
964
|
+
if isinstance(nodes, HTFAResults):
|
|
965
|
+
return nodes._lobe_mask(subject)
|
|
966
|
+
return _mni_mask()
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
def _display_nodes(
|
|
970
|
+
nodes: Any,
|
|
971
|
+
sizes: Any,
|
|
972
|
+
widths: Any,
|
|
973
|
+
subject: Any,
|
|
974
|
+
snap: bool,
|
|
975
|
+
mask: Any,
|
|
976
|
+
scale_by_mass: bool = False,
|
|
977
|
+
fade_by_mass: bool | float = False,
|
|
978
|
+
) -> tuple[Array, Array, Array | None]:
|
|
979
|
+
"""Centers, sizes and per-node opacities (or None) the plots draw."""
|
|
980
|
+
centers, fit_widths = _fit_nodes(nodes, subject)
|
|
981
|
+
K = len(centers)
|
|
982
|
+
w = fit_widths if widths is None else _per_node(widths, K, "widths")
|
|
983
|
+
floor = None
|
|
984
|
+
if fade_by_mass is not False:
|
|
985
|
+
floor = 0.15 if fade_by_mass is True else float(fade_by_mass)
|
|
986
|
+
if not 0 <= floor < 1:
|
|
987
|
+
raise ValueError(
|
|
988
|
+
f"fade_by_mass must be True or an opacity floor in [0, 1), "
|
|
989
|
+
f"got {fade_by_mass!r}"
|
|
990
|
+
)
|
|
991
|
+
if not snap:
|
|
992
|
+
if scale_by_mass or floor is not None:
|
|
993
|
+
raise ValueError("scale_by_mass and fade_by_mass need snap=True")
|
|
994
|
+
return (*_nodes(nodes, w if sizes is None else sizes, subject), None)
|
|
995
|
+
if w is None and (scale_by_mass or floor is not None):
|
|
996
|
+
raise ValueError("scale_by_mass and fade_by_mass need node widths (widths=)")
|
|
997
|
+
if mask is None:
|
|
998
|
+
mask = _default_mask(nodes, subject)
|
|
999
|
+
shape = _fit_shape(nodes, subject) if widths is None else None
|
|
1000
|
+
if shape is None:
|
|
1001
|
+
centers, w_eff, info = effective_nodes(centers, w, mask)
|
|
1002
|
+
else:
|
|
1003
|
+
name, comp_c, comp_w, pi = shape
|
|
1004
|
+
centers, w_eff, info = effective_nodes(comp_c, comp_w, mask, name, pi)
|
|
1005
|
+
if sizes is not None:
|
|
1006
|
+
node_sizes = _per_node(sizes, K, "sizes")
|
|
1007
|
+
else:
|
|
1008
|
+
node_sizes = np.ones(K) if w is None else w_eff
|
|
1009
|
+
if scale_by_mass:
|
|
1010
|
+
node_sizes = node_sizes * info["mass_fraction"]
|
|
1011
|
+
opacity = None
|
|
1012
|
+
if floor is not None:
|
|
1013
|
+
opacity = floor + (1 - floor) * np.clip(info["mass_fraction"], 0, 1)
|
|
1014
|
+
return centers, node_sizes, opacity
|
|
1015
|
+
|
|
1016
|
+
|
|
1017
|
+
def _edge_list(E: Array, threshold: float) -> tuple[Array, Array, Array]:
|
|
1018
|
+
i, j = np.triu_indices(len(E), 1)
|
|
1019
|
+
w = E[i, j]
|
|
1020
|
+
keep = np.abs(w) > threshold
|
|
1021
|
+
return i[keep], j[keep], w[keep]
|
|
1022
|
+
|
|
1023
|
+
|
|
1024
|
+
def _tubes(
|
|
1025
|
+
centers: Array, radii: Array, i: Array, j: Array, widths: Array, sides: int = 20
|
|
1026
|
+
) -> Any:
|
|
1027
|
+
"""Open cylinders from the surface of sphere i to that of sphere j."""
|
|
1028
|
+
pv = lazy_import("pyvista", "brain3d", "network plots")
|
|
1029
|
+
p, q = centers[i], centers[j]
|
|
1030
|
+
u = (q - p) / np.linalg.norm(q - p, axis=1, keepdims=True)
|
|
1031
|
+
a = p + u * radii[i, None]
|
|
1032
|
+
b = q - u * radii[j, None]
|
|
1033
|
+
ref = np.where(np.abs(u[:, [2]]) < 0.9, [[0.0, 0.0, 1.0]], [[1.0, 0.0, 0.0]])
|
|
1034
|
+
e1 = np.cross(u, ref)
|
|
1035
|
+
e1 /= np.linalg.norm(e1, axis=1, keepdims=True)
|
|
1036
|
+
e2 = np.cross(u, e1)
|
|
1037
|
+
th = np.linspace(0, 2 * np.pi, sides, endpoint=False)
|
|
1038
|
+
ring = (
|
|
1039
|
+
np.cos(th)[None, :, None] * e1[:, None]
|
|
1040
|
+
+ np.sin(th)[None, :, None] * e2[:, None]
|
|
1041
|
+
)
|
|
1042
|
+
ring = ring * widths[:, None, None]
|
|
1043
|
+
pts = np.concatenate([a[:, None] + ring, b[:, None] + ring], axis=1)
|
|
1044
|
+
n = len(i)
|
|
1045
|
+
base = (np.arange(n) * 2 * sides)[:, None]
|
|
1046
|
+
k = np.arange(sides)[None]
|
|
1047
|
+
k1 = (k + 1) % sides
|
|
1048
|
+
quads = np.stack(
|
|
1049
|
+
[
|
|
1050
|
+
np.full((n, sides), 4),
|
|
1051
|
+
base + k,
|
|
1052
|
+
base + k1,
|
|
1053
|
+
base + sides + k1,
|
|
1054
|
+
base + sides + k,
|
|
1055
|
+
],
|
|
1056
|
+
axis=-1,
|
|
1057
|
+
)
|
|
1058
|
+
return pv.PolyData(pts.reshape(-1, 3), quads.reshape(-1))
|
|
1059
|
+
|
|
1060
|
+
|
|
1061
|
+
# VTK's offscreen OpenGL windows for Linux without a display, in order of
|
|
1062
|
+
# preference: EGL (libEGL with Mesa's llvmpipe or a GPU driver; preinstalled on
|
|
1063
|
+
# Colab), then OSMesa.
|
|
1064
|
+
HEADLESS_WINDOWS = ("vtkEGLRenderWindow", "vtkOSOpenGLRenderWindow")
|
|
1065
|
+
_GL_PROBE = """
|
|
1066
|
+
import sys
|
|
1067
|
+
sys.path[:] = sys.argv[1:]
|
|
1068
|
+
import vtkmodules.vtkRenderingOpenGL2
|
|
1069
|
+
from vtkmodules.vtkRenderingCore import vtkRenderer, vtkRenderWindow
|
|
1070
|
+
w = vtkRenderWindow()
|
|
1071
|
+
w.SetOffScreenRendering(1)
|
|
1072
|
+
w.SetSize(8, 8)
|
|
1073
|
+
w.AddRenderer(vtkRenderer())
|
|
1074
|
+
w.Render()
|
|
1075
|
+
print(w.GetClassName())
|
|
1076
|
+
"""
|
|
1077
|
+
_auto_window: str | None = None # the window _headless_window selected
|
|
1078
|
+
_no_window = False # no offscreen window worked (cleared when DISPLAY appears)
|
|
1079
|
+
|
|
1080
|
+
|
|
1081
|
+
def _gl_window_works(window: str) -> bool:
|
|
1082
|
+
"""Whether VTK renders with the OpenGL window class ``window``.
|
|
1083
|
+
|
|
1084
|
+
Probed in a subprocess, because VTK crashes the process when the library
|
|
1085
|
+
behind a window class is missing. The subprocess gets this process's
|
|
1086
|
+
``sys.path`` (so it finds the same VTK) and runs in a fresh private
|
|
1087
|
+
directory.
|
|
1088
|
+
"""
|
|
1089
|
+
env = dict(os.environ, VTK_DEFAULT_OPENGL_WINDOW=window)
|
|
1090
|
+
path = [os.path.abspath(p) if p else os.getcwd() for p in sys.path]
|
|
1091
|
+
work = tempfile.mkdtemp(prefix="htfa-glprobe-")
|
|
1092
|
+
try:
|
|
1093
|
+
run = subprocess.run(
|
|
1094
|
+
[sys.executable, "-c", _GL_PROBE, *path],
|
|
1095
|
+
capture_output=True,
|
|
1096
|
+
text=True,
|
|
1097
|
+
env=env,
|
|
1098
|
+
timeout=120,
|
|
1099
|
+
cwd=work,
|
|
1100
|
+
)
|
|
1101
|
+
except (subprocess.TimeoutExpired, OSError):
|
|
1102
|
+
return False
|
|
1103
|
+
finally:
|
|
1104
|
+
shutil.rmtree(work, ignore_errors=True)
|
|
1105
|
+
return run.returncode == 0 and run.stdout.split()[-1:] == [window]
|
|
1106
|
+
|
|
1107
|
+
|
|
1108
|
+
def _headless_window() -> str | None:
|
|
1109
|
+
"""Select VTK's offscreen window on Linux without a display.
|
|
1110
|
+
|
|
1111
|
+
Returns the window class in use (setting ``VTK_DEFAULT_OPENGL_WINDOW`` if it
|
|
1112
|
+
was unset), or ``None`` when a display (or another OS) needs no change.
|
|
1113
|
+
The choice is re-checked on every call: once ``DISPLAY`` is set (for
|
|
1114
|
+
example by starting Xvfb), a window selected here is dropped again.
|
|
1115
|
+
"""
|
|
1116
|
+
global _auto_window, _no_window
|
|
1117
|
+
if not sys.platform.startswith("linux"):
|
|
1118
|
+
return None
|
|
1119
|
+
if os.environ.get("DISPLAY"):
|
|
1120
|
+
if _auto_window and os.environ.get("VTK_DEFAULT_OPENGL_WINDOW") == _auto_window:
|
|
1121
|
+
del os.environ["VTK_DEFAULT_OPENGL_WINDOW"]
|
|
1122
|
+
_auto_window, _no_window = None, False
|
|
1123
|
+
return None
|
|
1124
|
+
chosen = os.environ.get("VTK_DEFAULT_OPENGL_WINDOW")
|
|
1125
|
+
if chosen:
|
|
1126
|
+
return chosen
|
|
1127
|
+
if not _no_window:
|
|
1128
|
+
for window in HEADLESS_WINDOWS:
|
|
1129
|
+
if _gl_window_works(window):
|
|
1130
|
+
os.environ["VTK_DEFAULT_OPENGL_WINDOW"] = window
|
|
1131
|
+
_auto_window = window
|
|
1132
|
+
return window
|
|
1133
|
+
_no_window = True
|
|
1134
|
+
raise RuntimeError(
|
|
1135
|
+
"No display (DISPLAY is unset) and no offscreen OpenGL library: VTK needs "
|
|
1136
|
+
"Mesa's EGL or OSMesa to render without one. Install EGL with "
|
|
1137
|
+
"`apt-get install libegl1 libegl-mesa0` (Debian/Ubuntu; Colab has it) and "
|
|
1138
|
+
"restart Python, or set DISPLAY to a running X server such as Xvfb."
|
|
1139
|
+
)
|
|
1140
|
+
|
|
1141
|
+
|
|
1142
|
+
def _component_surfaces(components: ComponentNodes, mask: Any, level: float) -> list:
|
|
1143
|
+
"""Isosurfaces of each signed component; coordinates remain in world space."""
|
|
1144
|
+
pv = lazy_import("pyvista", "brain3d", "component lobes")
|
|
1145
|
+
level = check_level(level)
|
|
1146
|
+
surfaces = []
|
|
1147
|
+
for i, img in components.images(mask):
|
|
1148
|
+
data = np.asarray(img.dataobj)
|
|
1149
|
+
peak = float(components.mixing[i])
|
|
1150
|
+
if float(np.max(np.abs(data))) < level * peak:
|
|
1151
|
+
continue
|
|
1152
|
+
data = np.pad(data, 1)
|
|
1153
|
+
grid = pv.ImageData(dimensions=data.shape, origin=(-1, -1, -1))
|
|
1154
|
+
grid.point_data["profile"] = data.ravel(order="F")
|
|
1155
|
+
for sign in (1, -1):
|
|
1156
|
+
if float(np.max(sign * data)) < level * peak:
|
|
1157
|
+
continue
|
|
1158
|
+
surface = grid.contour([sign * level * peak], scalars="profile")
|
|
1159
|
+
if surface.n_points:
|
|
1160
|
+
surface = surface.transform(img.affine, inplace=False)
|
|
1161
|
+
surfaces.append((i, sign, surface))
|
|
1162
|
+
return surfaces
|
|
1163
|
+
|
|
1164
|
+
|
|
1165
|
+
def _network_geometry(
|
|
1166
|
+
nodes: Any,
|
|
1167
|
+
sizes: Any,
|
|
1168
|
+
widths: Any,
|
|
1169
|
+
subject: Any,
|
|
1170
|
+
snap: bool,
|
|
1171
|
+
mask: Any,
|
|
1172
|
+
scale_by_mass: bool,
|
|
1173
|
+
fade_by_mass: bool | float,
|
|
1174
|
+
node_mode: str,
|
|
1175
|
+
lobe_level: float,
|
|
1176
|
+
) -> tuple:
|
|
1177
|
+
"""Common static/movie geometry, with factor IDs for expanding edges."""
|
|
1178
|
+
shape = _fit_shape(nodes, subject)
|
|
1179
|
+
if not component_mode(node_mode, shape is not None):
|
|
1180
|
+
return (
|
|
1181
|
+
*_display_nodes(
|
|
1182
|
+
nodes, sizes, widths, subject, snap, mask, scale_by_mass, fade_by_mass
|
|
1183
|
+
),
|
|
1184
|
+
None,
|
|
1185
|
+
None,
|
|
1186
|
+
)
|
|
1187
|
+
if shape is None:
|
|
1188
|
+
centers, fit_widths = _fit_nodes(nodes, subject)
|
|
1189
|
+
w = fit_widths if widths is None else _per_node(widths, len(centers), "widths")
|
|
1190
|
+
if w is None:
|
|
1191
|
+
raise ValueError("component lobes need a fitted model or widths")
|
|
1192
|
+
shape = ("rbf", centers[:, None], w[:, None], np.ones((len(centers), 1)))
|
|
1193
|
+
elif widths is not None:
|
|
1194
|
+
raise ValueError(
|
|
1195
|
+
"widths cannot override fitted component shapes; use node_mode='summary'"
|
|
1196
|
+
)
|
|
1197
|
+
if sizes is not None or scale_by_mass or fade_by_mass:
|
|
1198
|
+
raise ValueError(
|
|
1199
|
+
"sizes and mass scaling apply to node_mode='summary'; "
|
|
1200
|
+
"component lobes use fitted geometry"
|
|
1201
|
+
)
|
|
1202
|
+
components = ComponentNodes.from_shape(shape)
|
|
1203
|
+
if mask is None:
|
|
1204
|
+
mask = _default_mask(nodes, subject)
|
|
1205
|
+
centers = components.centers
|
|
1206
|
+
if snap:
|
|
1207
|
+
centers, _, _ = effective_nodes(
|
|
1208
|
+
centers, components.widths, mask, components.kernel
|
|
1209
|
+
)
|
|
1210
|
+
surfaces = _component_surfaces(components, mask, lobe_level)
|
|
1211
|
+
return centers, components.widths, None, components, surfaces
|
|
1212
|
+
|
|
1213
|
+
|
|
1214
|
+
class _Scene:
|
|
1215
|
+
"""Off-screen plotter holding mesh and nodes; edges change per frame."""
|
|
1216
|
+
|
|
1217
|
+
def __init__(
|
|
1218
|
+
self,
|
|
1219
|
+
centers: Array,
|
|
1220
|
+
sizes: Array,
|
|
1221
|
+
mesh: tuple[Array, Array] | None,
|
|
1222
|
+
view: str,
|
|
1223
|
+
size: tuple[int, int],
|
|
1224
|
+
node_color: Any,
|
|
1225
|
+
mesh_color: Any,
|
|
1226
|
+
mesh_opacity: float,
|
|
1227
|
+
background: Any,
|
|
1228
|
+
node_opacity: Array | None = None,
|
|
1229
|
+
radius_range: tuple[float, float] = (2.0, 7.0),
|
|
1230
|
+
radius_kb: tuple[float, float] | None = None,
|
|
1231
|
+
radius_clip: tuple[float, float] | None = None,
|
|
1232
|
+
component_surfaces: list | None = None,
|
|
1233
|
+
component_weights: Array | None = None,
|
|
1234
|
+
lobe_negative_color: Any = "teal",
|
|
1235
|
+
) -> None:
|
|
1236
|
+
pv = lazy_import("pyvista", "brain3d", "network plots")
|
|
1237
|
+
if view not in VIEWS:
|
|
1238
|
+
raise ValueError(f"unknown view {view!r}; choose from {sorted(VIEWS)}")
|
|
1239
|
+
self.centers = centers
|
|
1240
|
+
k, b = (None, None) if radius_kb is None else radius_kb
|
|
1241
|
+
self.radii = node_radius(
|
|
1242
|
+
sizes, radius_range[0], radius_range[1], k=k, b=b, clip=radius_clip
|
|
1243
|
+
)
|
|
1244
|
+
if not np.all(self.radii > 0):
|
|
1245
|
+
raise ValueError(
|
|
1246
|
+
f"node radii must be positive, got min {self.radii.min():.3g} mm; "
|
|
1247
|
+
"set radius_clip"
|
|
1248
|
+
)
|
|
1249
|
+
self.component_surfaces = component_surfaces
|
|
1250
|
+
self.component_weights = component_weights
|
|
1251
|
+
self.lobe_negative_color = lobe_negative_color
|
|
1252
|
+
if component_surfaces is not None:
|
|
1253
|
+
# Edges originate at each component anchor; no artificial sphere radius.
|
|
1254
|
+
self.radii = np.zeros(len(centers))
|
|
1255
|
+
self.node_opacity = node_opacity
|
|
1256
|
+
self.size = (int(size[0]), int(size[1]))
|
|
1257
|
+
self.view_dir, self.view_up = (np.asarray(v, float) for v in VIEWS[view])
|
|
1258
|
+
self.verts = None if mesh is None else np.asarray(mesh[0], float)
|
|
1259
|
+
s = _SUPERSAMPLE
|
|
1260
|
+
_headless_window()
|
|
1261
|
+
pl = pv.Plotter(
|
|
1262
|
+
off_screen=True,
|
|
1263
|
+
window_size=[self.size[0] * s, self.size[1] * s],
|
|
1264
|
+
lighting="none",
|
|
1265
|
+
)
|
|
1266
|
+
# Depth peeling (needed for the translucent mesh and edges) draws no
|
|
1267
|
+
# translucent geometry into a multisampled framebuffer on Mesa
|
|
1268
|
+
# (llvmpipe, Linux CI). The 2x supersampling above anti-aliases.
|
|
1269
|
+
pl.render_window.SetMultiSamples(0)
|
|
1270
|
+
try:
|
|
1271
|
+
self._build(
|
|
1272
|
+
pv, pl, mesh, view, node_color, mesh_color, mesh_opacity, background
|
|
1273
|
+
)
|
|
1274
|
+
except BaseException:
|
|
1275
|
+
pl.close()
|
|
1276
|
+
raise
|
|
1277
|
+
self.pl = pl
|
|
1278
|
+
self._edges: Any = None
|
|
1279
|
+
|
|
1280
|
+
def _build(
|
|
1281
|
+
self,
|
|
1282
|
+
pv: Any,
|
|
1283
|
+
pl: Any,
|
|
1284
|
+
mesh: tuple[Array, Array] | None,
|
|
1285
|
+
view: str,
|
|
1286
|
+
node_color: Any,
|
|
1287
|
+
mesh_color: Any,
|
|
1288
|
+
mesh_opacity: float,
|
|
1289
|
+
background: Any,
|
|
1290
|
+
) -> None:
|
|
1291
|
+
"""Add the background, mesh, nodes, camera and light to ``pl``."""
|
|
1292
|
+
centers = self.centers
|
|
1293
|
+
pl.set_background(background)
|
|
1294
|
+
if mesh is not None:
|
|
1295
|
+
verts, faces = mesh
|
|
1296
|
+
cells = np.c_[np.full(len(faces), 3), faces].ravel()
|
|
1297
|
+
brain = pv.PolyData(verts, cells).compute_normals()
|
|
1298
|
+
pl.add_mesh(
|
|
1299
|
+
brain,
|
|
1300
|
+
color=mesh_color,
|
|
1301
|
+
opacity=float(mesh_opacity),
|
|
1302
|
+
smooth_shading=True,
|
|
1303
|
+
**_DULL,
|
|
1304
|
+
)
|
|
1305
|
+
if self.component_surfaces is not None:
|
|
1306
|
+
points = []
|
|
1307
|
+
for i, sign, surface in self.component_surfaces:
|
|
1308
|
+
alpha = (
|
|
1309
|
+
1.0 if self.component_weights is None else self.component_weights[i]
|
|
1310
|
+
)
|
|
1311
|
+
pl.add_mesh(
|
|
1312
|
+
surface,
|
|
1313
|
+
color=node_color if sign > 0 else self.lobe_negative_color,
|
|
1314
|
+
opacity=(0.2 + 0.6 * float(alpha)) * (0.35 if sign < 0 else 1.0),
|
|
1315
|
+
smooth_shading=True,
|
|
1316
|
+
show_scalar_bar=False,
|
|
1317
|
+
**_DULL,
|
|
1318
|
+
)
|
|
1319
|
+
points.append(np.asarray(surface.points))
|
|
1320
|
+
if points:
|
|
1321
|
+
geometry = np.vstack(points)
|
|
1322
|
+
self.verts = (
|
|
1323
|
+
geometry
|
|
1324
|
+
if self.verts is None
|
|
1325
|
+
else np.vstack([self.verts, geometry])
|
|
1326
|
+
)
|
|
1327
|
+
else:
|
|
1328
|
+
spheres = [
|
|
1329
|
+
pv.Sphere(radius=r, center=c, theta_resolution=40, phi_resolution=40)
|
|
1330
|
+
for c, r in zip(centers, self.radii, strict=True)
|
|
1331
|
+
]
|
|
1332
|
+
if self.node_opacity is None:
|
|
1333
|
+
pl.add_mesh(
|
|
1334
|
+
pv.merge(spheres), color=node_color, smooth_shading=True, **_DULL
|
|
1335
|
+
)
|
|
1336
|
+
else:
|
|
1337
|
+
for sphere, alpha in zip(spheres, self.node_opacity, strict=True):
|
|
1338
|
+
pl.add_mesh(
|
|
1339
|
+
sphere,
|
|
1340
|
+
color=node_color,
|
|
1341
|
+
opacity=float(alpha),
|
|
1342
|
+
smooth_shading=True,
|
|
1343
|
+
**_DULL,
|
|
1344
|
+
)
|
|
1345
|
+
pl.enable_depth_peeling(number_of_peels=8)
|
|
1346
|
+
pl.enable_parallel_projection()
|
|
1347
|
+
direction, up = VIEWS[view]
|
|
1348
|
+
axial = view in ("dorsal", "ventral")
|
|
1349
|
+
focal = _FOCAL_AXIAL if axial else _FOCAL
|
|
1350
|
+
pl.camera.focal_point = focal
|
|
1351
|
+
pl.camera.position = focal + 500.0 * np.asarray(direction)
|
|
1352
|
+
pl.camera.up = up
|
|
1353
|
+
pl.camera.parallel_scale = _PARALLEL_SCALE * (1.05 if axial else 1.0)
|
|
1354
|
+
pl.camera.clipping_range = (1, 1000)
|
|
1355
|
+
# MATLAB camlight('right'): 30 degrees right of and above the camera.
|
|
1356
|
+
el = az = np.deg2rad(30)
|
|
1357
|
+
pl.add_light(
|
|
1358
|
+
pv.Light(
|
|
1359
|
+
light_type="camera light",
|
|
1360
|
+
position=(np.sin(az) * np.cos(el), np.sin(el), np.cos(az) * np.cos(el)),
|
|
1361
|
+
focal_point=(0, 0, 0),
|
|
1362
|
+
intensity=1.0,
|
|
1363
|
+
positional=False,
|
|
1364
|
+
)
|
|
1365
|
+
)
|
|
1366
|
+
|
|
1367
|
+
def set_edges(
|
|
1368
|
+
self,
|
|
1369
|
+
E: Array,
|
|
1370
|
+
threshold: float,
|
|
1371
|
+
edge_style: str,
|
|
1372
|
+
positive_color: Any,
|
|
1373
|
+
negative_color: Any,
|
|
1374
|
+
) -> None:
|
|
1375
|
+
if self._edges is not None:
|
|
1376
|
+
self.pl.remove_actor(self._edges)
|
|
1377
|
+
self._edges = None
|
|
1378
|
+
i, j, w = _edge_list(E, threshold)
|
|
1379
|
+
if not len(i):
|
|
1380
|
+
return
|
|
1381
|
+
pos = np.asarray(_rgb(positive_color))
|
|
1382
|
+
neg = np.asarray(_rgb(negative_color))
|
|
1383
|
+
rgb = np.where((w > 0)[:, None], pos, neg)
|
|
1384
|
+
if edge_style == "intensity":
|
|
1385
|
+
radius, opacity = 0.5 * np.abs(w), EDGE_OPACITY
|
|
1386
|
+
else:
|
|
1387
|
+
radius, opacity = np.full(len(w), 0.25), 1.0
|
|
1388
|
+
tubes = _tubes(self.centers, self.radii, i, j, radius)
|
|
1389
|
+
per_edge = tubes.n_cells // len(i)
|
|
1390
|
+
tubes.cell_data["rgb"] = np.round(
|
|
1391
|
+
np.repeat(rgb, per_edge, axis=0) * 255
|
|
1392
|
+
).astype(np.uint8)
|
|
1393
|
+
self._edges = self.pl.add_mesh(
|
|
1394
|
+
tubes,
|
|
1395
|
+
scalars="rgb",
|
|
1396
|
+
rgb=True,
|
|
1397
|
+
opacity=opacity,
|
|
1398
|
+
smooth_shading=False,
|
|
1399
|
+
show_scalar_bar=False,
|
|
1400
|
+
**_DULL,
|
|
1401
|
+
)
|
|
1402
|
+
|
|
1403
|
+
def fit_spin(self, rotations: Array) -> tuple[Array, float]:
|
|
1404
|
+
"""Rotation center and parallel scale for a spinning camera.
|
|
1405
|
+
|
|
1406
|
+
The center is the middle of the mesh's bounding box (of the node
|
|
1407
|
+
spheres' without a mesh). The scale is 5% more than the smallest one
|
|
1408
|
+
that keeps the mesh and the nodes inside the image for every brain
|
|
1409
|
+
rotation in ``rotations`` (shape (n, 3, 3)).
|
|
1410
|
+
"""
|
|
1411
|
+
if self.verts is None:
|
|
1412
|
+
lo = (self.centers - self.radii[:, None]).min(axis=0)
|
|
1413
|
+
hi = (self.centers + self.radii[:, None]).max(axis=0)
|
|
1414
|
+
else:
|
|
1415
|
+
lo, hi = self.verts.min(axis=0), self.verts.max(axis=0)
|
|
1416
|
+
center = (lo + hi) / 2
|
|
1417
|
+
w, h = self.size
|
|
1418
|
+
right = np.cross(self.view_dir, self.view_up)
|
|
1419
|
+
nodes = self.centers - center
|
|
1420
|
+
scale = 0.0
|
|
1421
|
+
for start in range(0, len(rotations), 16):
|
|
1422
|
+
R = rotations[start : start + 16]
|
|
1423
|
+
# image axes in brain coordinates: R^T up and R^T right
|
|
1424
|
+
axes = np.einsum("nji,aj->ain", R, np.stack([self.view_up, right]))
|
|
1425
|
+
ext = (np.abs(nodes @ axes) + self.radii[:, None]).max(axis=1)
|
|
1426
|
+
if self.verts is not None:
|
|
1427
|
+
ext = np.maximum(ext, np.abs((self.verts - center) @ axes).max(axis=1))
|
|
1428
|
+
scale = max(scale, float(np.max(np.maximum(ext[0], ext[1] * h / w))))
|
|
1429
|
+
return center, 1.05 * scale
|
|
1430
|
+
|
|
1431
|
+
def orbit(self, R: Array, center: Array, scale: float) -> None:
|
|
1432
|
+
"""Place the camera so the brain looks rotated by ``R`` about ``center``."""
|
|
1433
|
+
# Camera outside the sphere (radius r about center) that holds the
|
|
1434
|
+
# mesh and the nodes; the clipping range spans that sphere.
|
|
1435
|
+
r = 1.05 * self._reach(center) + 1.0
|
|
1436
|
+
cam = self.pl.camera
|
|
1437
|
+
cam.focal_point = center
|
|
1438
|
+
cam.position = center + 2.0 * r * (R.T @ self.view_dir)
|
|
1439
|
+
cam.up = R.T @ self.view_up
|
|
1440
|
+
cam.parallel_scale = scale
|
|
1441
|
+
cam.clipping_range = (r, 3.0 * r)
|
|
1442
|
+
|
|
1443
|
+
def _reach(self, center: Array) -> float:
|
|
1444
|
+
"""Largest distance (mm) from ``center`` to the mesh or a node surface."""
|
|
1445
|
+
d = np.linalg.norm(self.centers - center, axis=1) + self.radii
|
|
1446
|
+
reach = float(d.max()) if d.size else 0.0
|
|
1447
|
+
if self.verts is not None:
|
|
1448
|
+
reach = max(reach, float(np.linalg.norm(self.verts - center, axis=1).max()))
|
|
1449
|
+
return reach
|
|
1450
|
+
|
|
1451
|
+
def image(self) -> Any:
|
|
1452
|
+
Image = _pil()
|
|
1453
|
+
self.pl.render()
|
|
1454
|
+
shot = self.pl.screenshot(None, return_img=True)[..., :3]
|
|
1455
|
+
return Image.fromarray(np.ascontiguousarray(shot)).resize(self.size, Image.BOX)
|
|
1456
|
+
|
|
1457
|
+
def close(self) -> None:
|
|
1458
|
+
self.pl.close()
|
|
1459
|
+
|
|
1460
|
+
|
|
1461
|
+
def _rgb(color: Any) -> tuple[float, float, float]:
|
|
1462
|
+
pv = lazy_import("pyvista", "brain3d", "network plots")
|
|
1463
|
+
r, g, b = pv.Color(color).float_rgb
|
|
1464
|
+
return float(r), float(g), float(b)
|
|
1465
|
+
|
|
1466
|
+
|
|
1467
|
+
def _connectivity(connectivity: Any, K: int, ndim: int) -> Array:
|
|
1468
|
+
E = np.asarray(connectivity, dtype=np.float64)
|
|
1469
|
+
if E.ndim != ndim or E.shape[-2:] != (K, K):
|
|
1470
|
+
want = "(K, K)" if ndim == 2 else "(T, K, K) (or (K, K) with duration)"
|
|
1471
|
+
raise ValueError(f"connectivity must be {want} with K={K}, got {E.shape}")
|
|
1472
|
+
if not np.all(np.isfinite(E)):
|
|
1473
|
+
raise ValueError("connectivity contains NaN or inf")
|
|
1474
|
+
return E
|
|
1475
|
+
|
|
1476
|
+
|
|
1477
|
+
MATLAB_JPEG_QUALITY = 75 # MATLAB's default JPEG export quality (2014 frames)
|
|
1478
|
+
|
|
1479
|
+
|
|
1480
|
+
def _is_jpeg(path: Path) -> bool:
|
|
1481
|
+
return path.suffix.lower() in (".jpg", ".jpeg")
|
|
1482
|
+
|
|
1483
|
+
|
|
1484
|
+
def _jpeg(img: Any, quality: int) -> Any:
|
|
1485
|
+
"""``img`` after a JPEG round trip with 4:2:0 chroma, as MATLAB writes."""
|
|
1486
|
+
import io
|
|
1487
|
+
|
|
1488
|
+
Image = _pil()
|
|
1489
|
+
buf = io.BytesIO()
|
|
1490
|
+
img.save(buf, format="JPEG", quality=int(quality), subsampling=2)
|
|
1491
|
+
buf.seek(0)
|
|
1492
|
+
with Image.open(buf) as im:
|
|
1493
|
+
return im.convert("RGB")
|
|
1494
|
+
|
|
1495
|
+
|
|
1496
|
+
def _save(img: Any, path: Path, jpeg_quality: int | None) -> None:
|
|
1497
|
+
if _is_jpeg(path):
|
|
1498
|
+
quality = MATLAB_JPEG_QUALITY if jpeg_quality is None else jpeg_quality
|
|
1499
|
+
img.save(path, quality=int(quality), subsampling=2)
|
|
1500
|
+
else:
|
|
1501
|
+
img.save(path)
|
|
1502
|
+
|
|
1503
|
+
|
|
1504
|
+
def _style(kwargs: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
1505
|
+
"""Split keyword arguments into scene and edge options, with defaults."""
|
|
1506
|
+
scene = {
|
|
1507
|
+
"view": kwargs.pop("view", "lateral"),
|
|
1508
|
+
"size": kwargs.pop("size", SIZE),
|
|
1509
|
+
"node_color": kwargs.pop("node_color", (0.502, 0.502, 0.502)),
|
|
1510
|
+
"mesh_color": kwargs.pop("mesh_color", (0.95, 0.95, 0.95)),
|
|
1511
|
+
"mesh_opacity": kwargs.pop("mesh_opacity", 0.2),
|
|
1512
|
+
"background": kwargs.pop("background", "white"),
|
|
1513
|
+
"radius_range": tuple(kwargs.pop("radius_range", (2.0, 7.0))),
|
|
1514
|
+
"radius_kb": kwargs.pop("radius_kb", None),
|
|
1515
|
+
"radius_clip": kwargs.pop("radius_clip", None),
|
|
1516
|
+
}
|
|
1517
|
+
edges = {
|
|
1518
|
+
"threshold": float(kwargs.pop("threshold", 0.25)),
|
|
1519
|
+
"edge_style": kwargs.pop("edge_style", "intensity"),
|
|
1520
|
+
"positive_color": kwargs.pop("positive_color", "red"),
|
|
1521
|
+
"negative_color": kwargs.pop("negative_color", "blue"),
|
|
1522
|
+
}
|
|
1523
|
+
if kwargs:
|
|
1524
|
+
raise TypeError(f"unexpected keyword arguments: {sorted(kwargs)}")
|
|
1525
|
+
if edges["edge_style"] not in ("intensity", "flat"):
|
|
1526
|
+
raise ValueError(
|
|
1527
|
+
f"edge_style must be 'intensity' or 'flat', got {edges['edge_style']!r}"
|
|
1528
|
+
)
|
|
1529
|
+
return scene, edges
|
|
1530
|
+
|
|
1531
|
+
|
|
1532
|
+
def plot_network(
|
|
1533
|
+
nodes: Any,
|
|
1534
|
+
connectivity: Any = None,
|
|
1535
|
+
*,
|
|
1536
|
+
sizes: Any = None,
|
|
1537
|
+
widths: Any = None,
|
|
1538
|
+
subject: Any = "global",
|
|
1539
|
+
mesh: Any = "ch2",
|
|
1540
|
+
snap: bool = True,
|
|
1541
|
+
mask: Any = None,
|
|
1542
|
+
scale_by_mass: bool = False,
|
|
1543
|
+
fade_by_mass: bool | float = False,
|
|
1544
|
+
node_mode: str = "auto",
|
|
1545
|
+
lobe_level: float = 0.05,
|
|
1546
|
+
lobe_negative_color: Any = "teal",
|
|
1547
|
+
out: str | os.PathLike | None = None,
|
|
1548
|
+
jpeg_quality: int | None = None,
|
|
1549
|
+
**style: Any,
|
|
1550
|
+
) -> Any:
|
|
1551
|
+
"""Render nodes and thresholded edges BrainNet Viewer-style.
|
|
1552
|
+
|
|
1553
|
+
Parameters
|
|
1554
|
+
----------
|
|
1555
|
+
nodes : HTFAResults, TFA, HTFA or array of shape (K, 3)
|
|
1556
|
+
Node centers in MNI mm. For a fit, the centers of ``subject`` are
|
|
1557
|
+
used and its widths set the node sizes.
|
|
1558
|
+
connectivity : array of shape (K, K), optional
|
|
1559
|
+
Edge weights (upper triangle used). ``None`` draws nodes only.
|
|
1560
|
+
sizes : array of shape (K,), optional
|
|
1561
|
+
Node sizes; mapped linearly onto 2-7 mm radii (`node_radius`; see the
|
|
1562
|
+
``radius_*`` style options).
|
|
1563
|
+
Defaults to the (effective, with ``snap``) widths, or equal sizes
|
|
1564
|
+
(4 mm) when no widths are known.
|
|
1565
|
+
widths : array of shape (K,), optional
|
|
1566
|
+
RBF widths of array ``nodes`` (a fit's own widths are used
|
|
1567
|
+
otherwise).
|
|
1568
|
+
subject : "global" or int
|
|
1569
|
+
Which centers to use when ``nodes`` is a fit.
|
|
1570
|
+
mesh : str, path, (vertices, faces) or None
|
|
1571
|
+
Brain surface; see `load_mesh`. Default ``"ch2"``.
|
|
1572
|
+
snap : bool
|
|
1573
|
+
Draw each node as its in-brain part (`effective_nodes`): the
|
|
1574
|
+
RBF-weighted centroid of the mask voxels, with width
|
|
1575
|
+
``lambda_eff``. Default ``True``; ``False`` draws the fitted centers
|
|
1576
|
+
and widths as they are. The fit itself is never changed, and
|
|
1577
|
+
`effective_nodes` (or `htfa.HTFAResults.display_nodes`) returns the
|
|
1578
|
+
drawn values. Nodes without widths (a bare array without ``widths``)
|
|
1579
|
+
are points: they stay if inside the mask and otherwise move to the
|
|
1580
|
+
nearest mask voxel.
|
|
1581
|
+
mask : array of shape (V, 3), NIfTI image or (volume, affine), optional
|
|
1582
|
+
The in-brain voxels for ``snap``. Default: for an HTFAResults, the
|
|
1583
|
+
subject's voxel coordinates (all subjects' for ``"global"``);
|
|
1584
|
+
otherwise nilearn's 2 mm MNI152 brain mask (`mni_mask`), because the
|
|
1585
|
+
BrainNet meshes are in MNI space. Raises ``ImportError`` if that needs
|
|
1586
|
+
nilearn and nilearn cannot be installed.
|
|
1587
|
+
scale_by_mass : bool
|
|
1588
|
+
Multiply the node sizes by the in-mask RBF mass fraction before they
|
|
1589
|
+
are mapped to radii (needs widths and ``snap``).
|
|
1590
|
+
fade_by_mass : bool or float
|
|
1591
|
+
Node opacity ``floor + (1 - floor) * mass_fraction`` with floor 0.15
|
|
1592
|
+
(``True``) or the given floor, so nodes mostly outside the brain stay
|
|
1593
|
+
faintly visible (needs widths and ``snap``).
|
|
1594
|
+
node_mode : {'auto', 'components', 'summary'}
|
|
1595
|
+
``'auto'`` draws non-RBF kernels and mixtures as spatial component
|
|
1596
|
+
lobes; single RBFs retain the sphere view. ``'components'`` always
|
|
1597
|
+
draws lobes. Every component is an edge anchor: each factor edge is
|
|
1598
|
+
repeated, unchanged, between all pairs of its components and those
|
|
1599
|
+
of the other factor. No within-factor edges are added. ``'summary'``
|
|
1600
|
+
draws one sphere per factor at its effective centroid.
|
|
1601
|
+
lobe_level : float
|
|
1602
|
+
Isosurface level as a fraction of the component's unmasked peak
|
|
1603
|
+
(default 0.05); both positive and negative surfaces are drawn where
|
|
1604
|
+
they intersect ``mask``. Lobes use fitted spatial dimensions, not
|
|
1605
|
+
the ``radius_*`` scaling of summary spheres. Mixing weights control
|
|
1606
|
+
opacity (0.2 + 0.6 times the weight; negative shells use 35% of
|
|
1607
|
+
that opacity so the positive core remains visible), never the edge value.
|
|
1608
|
+
``snap``
|
|
1609
|
+
changes edge anchors only; it does not move the component field.
|
|
1610
|
+
lobe_negative_color : color
|
|
1611
|
+
Color of negative component surfaces (default teal); positive
|
|
1612
|
+
surfaces use ``node_color``. This sign is spatial loading, distinct
|
|
1613
|
+
from positive/negative connectivity colors.
|
|
1614
|
+
out : path, optional
|
|
1615
|
+
Save the image there: PNG, or JPEG for a ``.jpg``/``.jpeg`` suffix
|
|
1616
|
+
(quality ``jpeg_quality``, default 75, 4:2:0 chroma, like MATLAB's
|
|
1617
|
+
export).
|
|
1618
|
+
jpeg_quality : int, optional
|
|
1619
|
+
If given, the image is JPEG-compressed at this quality before it is
|
|
1620
|
+
returned or saved. JPEG at 75 makes thin edges paler.
|
|
1621
|
+
**style
|
|
1622
|
+
``threshold`` (0.25; edges with ``|E| > threshold`` are drawn),
|
|
1623
|
+
``view`` (``"lateral"`` = ``"left"``, ``"right"``, ``"dorsal"``,
|
|
1624
|
+
``"ventral"``, ``"anterior"``, ``"posterior"``), ``size``
|
|
1625
|
+
((1600, 1000) pixels), ``edge_style`` (``"intensity"``: diameter
|
|
1626
|
+
``|E|`` mm at opacity 0.7; ``"flat"``: 0.5 mm, opaque),
|
|
1627
|
+
``positive_color`` ("red"), ``negative_color`` ("blue"),
|
|
1628
|
+
``node_color`` (0.502 gray), ``mesh_color`` (0.95 gray),
|
|
1629
|
+
``mesh_opacity`` (0.2), ``background`` ("white"),
|
|
1630
|
+
``radius_range`` ((2, 7) mm: radii of the smallest and largest
|
|
1631
|
+
size), ``radius_kb`` (a fixed ``(k, b)``: radius ``k * size + b``
|
|
1632
|
+
mm, comparable across plots), ``radius_clip`` (``(min, max)`` mm
|
|
1633
|
+
applied to the radii); see `node_radius`. See also
|
|
1634
|
+
`config_style`.
|
|
1635
|
+
|
|
1636
|
+
Returns
|
|
1637
|
+
-------
|
|
1638
|
+
PIL.Image.Image
|
|
1639
|
+
The RGB image.
|
|
1640
|
+
"""
|
|
1641
|
+
scene_opts, edge_opts = _style(dict(style))
|
|
1642
|
+
centers, node_sizes, opacity, components, surfaces = _network_geometry(
|
|
1643
|
+
nodes,
|
|
1644
|
+
sizes,
|
|
1645
|
+
widths,
|
|
1646
|
+
subject,
|
|
1647
|
+
snap,
|
|
1648
|
+
mask,
|
|
1649
|
+
scale_by_mass,
|
|
1650
|
+
fade_by_mass,
|
|
1651
|
+
node_mode,
|
|
1652
|
+
lobe_level,
|
|
1653
|
+
)
|
|
1654
|
+
if components is not None and connectivity is not None:
|
|
1655
|
+
connectivity = components.connectivity(connectivity)
|
|
1656
|
+
E = None
|
|
1657
|
+
if connectivity is not None:
|
|
1658
|
+
E = _connectivity(connectivity, len(centers), 2)
|
|
1659
|
+
scene = _Scene(
|
|
1660
|
+
centers,
|
|
1661
|
+
node_sizes,
|
|
1662
|
+
load_mesh(mesh),
|
|
1663
|
+
**scene_opts,
|
|
1664
|
+
node_opacity=opacity,
|
|
1665
|
+
component_surfaces=surfaces,
|
|
1666
|
+
component_weights=None if components is None else components.mixing,
|
|
1667
|
+
lobe_negative_color=lobe_negative_color,
|
|
1668
|
+
)
|
|
1669
|
+
try:
|
|
1670
|
+
if E is not None:
|
|
1671
|
+
scene.set_edges(E, **edge_opts)
|
|
1672
|
+
img = scene.image()
|
|
1673
|
+
finally:
|
|
1674
|
+
scene.close()
|
|
1675
|
+
if jpeg_quality is not None:
|
|
1676
|
+
img = _jpeg(img, jpeg_quality)
|
|
1677
|
+
if out is not None:
|
|
1678
|
+
_save(img, Path(out), jpeg_quality)
|
|
1679
|
+
return img
|
|
1680
|
+
|
|
1681
|
+
|
|
1682
|
+
def _check_fps(fps: float) -> None:
|
|
1683
|
+
if not (math.isfinite(float(fps)) and float(fps) > 0):
|
|
1684
|
+
raise ValueError(f"fps must be a positive, finite number, got {fps!r}")
|
|
1685
|
+
|
|
1686
|
+
|
|
1687
|
+
def _movie_length(
|
|
1688
|
+
duration: float | None, n_frames: int | None, fps: float
|
|
1689
|
+
) -> int | None:
|
|
1690
|
+
"""Number of movie frames set by ``duration`` or ``n_frames`` (else None)."""
|
|
1691
|
+
_check_fps(fps)
|
|
1692
|
+
if duration is not None and n_frames is not None:
|
|
1693
|
+
raise ValueError("give duration or n_frames, not both")
|
|
1694
|
+
if duration is not None:
|
|
1695
|
+
if not (math.isfinite(float(duration)) and float(duration) > 0):
|
|
1696
|
+
raise ValueError(
|
|
1697
|
+
f"duration must be a positive, finite number of seconds, "
|
|
1698
|
+
f"got {duration!r}"
|
|
1699
|
+
)
|
|
1700
|
+
n = round(float(duration) * fps)
|
|
1701
|
+
if n < 1:
|
|
1702
|
+
raise ValueError(f"duration {duration} s at {fps} fps gives no frames")
|
|
1703
|
+
return n
|
|
1704
|
+
if n_frames is not None and (int(n_frames) != n_frames or n_frames < 1):
|
|
1705
|
+
raise ValueError(f"n_frames must be a positive integer, got {n_frames!r}")
|
|
1706
|
+
return None if n_frames is None else int(n_frames)
|
|
1707
|
+
|
|
1708
|
+
|
|
1709
|
+
def _spin_rotations(spin: Any, n: int) -> Array:
|
|
1710
|
+
"""Brain rotation of each of ``n`` frames, shape (n, 3, 3).
|
|
1711
|
+
|
|
1712
|
+
Frame k turns the brain by ``spin * k / n`` full turns about the x, then
|
|
1713
|
+
the y, then the z axis (right-hand rule).
|
|
1714
|
+
"""
|
|
1715
|
+
turns = np.asarray(spin, dtype=np.float64)
|
|
1716
|
+
if turns.shape != (3,) or not np.all(np.isfinite(turns)):
|
|
1717
|
+
raise ValueError(
|
|
1718
|
+
f"spin must be three finite numbers of turns (x, y, z), got {spin!r}"
|
|
1719
|
+
)
|
|
1720
|
+
c, s = (f(2 * np.pi * np.outer(np.arange(n) / n, turns)) for f in (np.cos, np.sin))
|
|
1721
|
+
one = np.ones(n)
|
|
1722
|
+
|
|
1723
|
+
def rot(a: int, b: int, axis: int) -> Array:
|
|
1724
|
+
R = np.zeros((n, 3, 3))
|
|
1725
|
+
R[:, axis, axis] = one
|
|
1726
|
+
R[:, a, a] = R[:, b, b] = c[:, axis]
|
|
1727
|
+
R[:, a, b], R[:, b, a] = -s[:, axis], s[:, axis]
|
|
1728
|
+
return R
|
|
1729
|
+
|
|
1730
|
+
return rot(0, 1, 2) @ rot(2, 0, 1) @ rot(1, 2, 0)
|
|
1731
|
+
|
|
1732
|
+
|
|
1733
|
+
def _nearest(t: float, T: int) -> int:
|
|
1734
|
+
"""Index of the window nearest to time ``t`` (halves round up)."""
|
|
1735
|
+
return min(int(np.floor(t + 0.5)), T - 1)
|
|
1736
|
+
|
|
1737
|
+
|
|
1738
|
+
def _at_time(E: Array, t: float, interpolation: str) -> Array:
|
|
1739
|
+
"""Connectivity at fractional window index ``t``."""
|
|
1740
|
+
if interpolation == "nearest":
|
|
1741
|
+
return E[_nearest(t, len(E))]
|
|
1742
|
+
lo = min(int(np.floor(t)), len(E) - 1)
|
|
1743
|
+
frac = t - lo
|
|
1744
|
+
if frac == 0:
|
|
1745
|
+
return E[lo]
|
|
1746
|
+
return (1 - frac) * E[lo] + frac * E[lo + 1]
|
|
1747
|
+
|
|
1748
|
+
|
|
1749
|
+
def animate_network(
|
|
1750
|
+
nodes: Any,
|
|
1751
|
+
connectivity: Any,
|
|
1752
|
+
out: str | os.PathLike,
|
|
1753
|
+
*,
|
|
1754
|
+
fps: float = 10,
|
|
1755
|
+
duration: float | None = None,
|
|
1756
|
+
n_frames: int | None = None,
|
|
1757
|
+
interpolation: str = "linear",
|
|
1758
|
+
spin: Sequence[float] | None = None,
|
|
1759
|
+
sizes: Any = None,
|
|
1760
|
+
widths: Any = None,
|
|
1761
|
+
subject: Any = "global",
|
|
1762
|
+
mesh: Any = "ch2",
|
|
1763
|
+
snap: bool = True,
|
|
1764
|
+
mask: Any = None,
|
|
1765
|
+
scale_by_mass: bool = False,
|
|
1766
|
+
fade_by_mass: bool | float = False,
|
|
1767
|
+
node_mode: str = "auto",
|
|
1768
|
+
lobe_level: float = 0.05,
|
|
1769
|
+
lobe_negative_color: Any = "teal",
|
|
1770
|
+
captions: Sequence[str] | Callable[[float], str] | None = None,
|
|
1771
|
+
frames_dir: str | os.PathLike | None = None,
|
|
1772
|
+
jpeg_quality: int | None = None,
|
|
1773
|
+
**style: Any,
|
|
1774
|
+
) -> Path:
|
|
1775
|
+
"""Render a ``(T, K, K)`` connectivity series as an mp4 or GIF.
|
|
1776
|
+
|
|
1777
|
+
By default the movie has one frame per connectivity window, and the
|
|
1778
|
+
camera, mesh, nodes and threshold stay fixed. ``duration`` (or
|
|
1779
|
+
``n_frames``) sets the number of frames instead, interpolating between
|
|
1780
|
+
windows, and ``spin`` turns the brain.
|
|
1781
|
+
|
|
1782
|
+
Parameters
|
|
1783
|
+
----------
|
|
1784
|
+
nodes, sizes, widths, subject, mesh, snap, mask, scale_by_mass, fade_by_mass
|
|
1785
|
+
As in `plot_network` (``snap`` is on by default).
|
|
1786
|
+
node_mode, lobe_level, lobe_negative_color
|
|
1787
|
+
As in `plot_network`; the same component geometry and repeated edges
|
|
1788
|
+
are used in every frame.
|
|
1789
|
+
**style
|
|
1790
|
+
As in `plot_network`.
|
|
1791
|
+
connectivity : array of shape (T, K, K), or (K, K) with duration
|
|
1792
|
+
One edge matrix per window. A single ``(K, K)`` matrix needs
|
|
1793
|
+
``duration`` or ``n_frames`` and gives fixed edges (for a spin).
|
|
1794
|
+
out : path
|
|
1795
|
+
``.mp4`` (H.264 via imageio-ffmpeg) or ``.gif``. An mp4 is encoded
|
|
1796
|
+
while frames render, holding one frame in memory at a time. A GIF
|
|
1797
|
+
needs all frames for its shared palette, about 4.8 MB per
|
|
1798
|
+
1600 x 1000 frame (see `write_animation`).
|
|
1799
|
+
fps : float
|
|
1800
|
+
Frame rate of the movie, in frames per second (default 10).
|
|
1801
|
+
duration : float, optional
|
|
1802
|
+
Length of the movie in seconds: it gets ``round(duration * fps)``
|
|
1803
|
+
frames whatever T is, so the windows play in slow motion or fast
|
|
1804
|
+
forward. Movie frame ``i`` of ``n`` shows window time
|
|
1805
|
+
``t = i * (T - 1) / (n - 1)`` (all of the windows, first to last).
|
|
1806
|
+
n_frames : int, optional
|
|
1807
|
+
The number of movie frames, instead of ``duration``.
|
|
1808
|
+
interpolation : {"linear", "nearest"}
|
|
1809
|
+
How a fractional ``t`` is drawn: ``"linear"`` (default) mixes the
|
|
1810
|
+
two neighbouring windows, ``(1 - f) * E[floor(t)] + f * E[floor(t)
|
|
1811
|
+
+ 1]`` with ``f = t - floor(t)``, so edges fade in and out
|
|
1812
|
+
smoothly as their weights cross ``threshold``; ``"nearest"`` shows
|
|
1813
|
+
the nearest window (halves round up).
|
|
1814
|
+
spin : (x, y, z) turns, optional
|
|
1815
|
+
Number of full turns of the brain about the MNI x, y and z axes over
|
|
1816
|
+
the whole movie, through the center of the mesh's bounding box (of
|
|
1817
|
+
the nodes without a mesh). Fractions are allowed. Movie frame ``k``
|
|
1818
|
+
of ``n`` turns the brain by ``spin * k / n`` turns, about x first,
|
|
1819
|
+
then y, then z (right-hand rule: ``(0, 0, 0.25)`` brings the front
|
|
1820
|
+
of the brain towards the camera in the left lateral view). The turn
|
|
1821
|
+
is made by orbiting the camera (with its light) around the brain,
|
|
1822
|
+
with the parallel projection kept and the zoom fixed at the largest
|
|
1823
|
+
one that keeps the brain and nodes inside every frame. With a whole
|
|
1824
|
+
number of turns the movie loops seamlessly: frame ``n`` would be
|
|
1825
|
+
frame 0 again. ``None`` (default) keeps the fixed camera of
|
|
1826
|
+
``view``; any spin, even ``(0, 0, 0)``, uses the centered, fitted
|
|
1827
|
+
zoom.
|
|
1828
|
+
captions : sequence of T str, or callable, optional
|
|
1829
|
+
Text shown in a white band above each frame (not over the brain).
|
|
1830
|
+
A sequence gives the caption of each window (a movie frame takes
|
|
1831
|
+
that of the nearest window); a callable is called with each frame's
|
|
1832
|
+
window time ``t`` (a float) and returns its caption.
|
|
1833
|
+
frames_dir : path, optional
|
|
1834
|
+
Also save each frame there as ``1.png``, ``2.png``, ... (``.jpg``
|
|
1835
|
+
with ``jpeg_quality``).
|
|
1836
|
+
jpeg_quality : int, optional
|
|
1837
|
+
JPEG-compress each frame at this quality before it goes into the
|
|
1838
|
+
movie. Lower quality values increase compression artifacts.
|
|
1839
|
+
|
|
1840
|
+
Returns
|
|
1841
|
+
-------
|
|
1842
|
+
pathlib.Path
|
|
1843
|
+
``out``.
|
|
1844
|
+
|
|
1845
|
+
Examples
|
|
1846
|
+
--------
|
|
1847
|
+
Suppose ``centers`` contains K node locations in MNI anatomical reference
|
|
1848
|
+
coordinates, ``E`` contains 30 corresponding K-by-K connectivity matrices,
|
|
1849
|
+
and ``C`` is a single static connectivity matrix. The following examples
|
|
1850
|
+
illustrate animation settings independently of the experiment that supplied
|
|
1851
|
+
those connections.
|
|
1852
|
+
|
|
1853
|
+
A 6 s animation of the 30 windows at 15 frames per second (90 frames,
|
|
1854
|
+
interpolated across the window sequence), turning once about the vertical
|
|
1855
|
+
axis:
|
|
1856
|
+
|
|
1857
|
+
>>> animate_network(centers, E, "net.mp4", fps=15, duration=6,
|
|
1858
|
+
... spin=(0, 0, 1)) # doctest: +SKIP
|
|
1859
|
+
|
|
1860
|
+
A 4 s spin of one static network:
|
|
1861
|
+
|
|
1862
|
+
>>> animate_network(centers, C, "spin.gif", fps=12, duration=4,
|
|
1863
|
+
... spin=(0, 0, 1), size=(480, 300)) # doctest: +SKIP
|
|
1864
|
+
"""
|
|
1865
|
+
scene_opts, edge_opts = _style(dict(style))
|
|
1866
|
+
if interpolation not in ("linear", "nearest"):
|
|
1867
|
+
raise ValueError(
|
|
1868
|
+
f"interpolation must be 'linear' or 'nearest', got {interpolation!r}"
|
|
1869
|
+
)
|
|
1870
|
+
n = _movie_length(duration, n_frames, fps)
|
|
1871
|
+
out = Path(out)
|
|
1872
|
+
if out.suffix.lower() not in (".mp4", ".gif"):
|
|
1873
|
+
raise ValueError(f"out must end in .mp4 or .gif, got {out.name!r}")
|
|
1874
|
+
centers, node_sizes, opacity, components, surfaces = _network_geometry(
|
|
1875
|
+
nodes,
|
|
1876
|
+
sizes,
|
|
1877
|
+
widths,
|
|
1878
|
+
subject,
|
|
1879
|
+
snap,
|
|
1880
|
+
mask,
|
|
1881
|
+
scale_by_mass,
|
|
1882
|
+
fade_by_mass,
|
|
1883
|
+
node_mode,
|
|
1884
|
+
lobe_level,
|
|
1885
|
+
)
|
|
1886
|
+
if components is not None and connectivity is not None:
|
|
1887
|
+
connectivity = components.connectivity(connectivity)
|
|
1888
|
+
K = len(centers)
|
|
1889
|
+
if n is not None and np.ndim(connectivity) == 2:
|
|
1890
|
+
E = _connectivity(connectivity, K, 2)[None]
|
|
1891
|
+
else:
|
|
1892
|
+
E = _connectivity(connectivity, K, 3)
|
|
1893
|
+
T = len(E)
|
|
1894
|
+
if callable(captions):
|
|
1895
|
+
caption: Callable[[float], str] | None = captions
|
|
1896
|
+
elif captions is not None:
|
|
1897
|
+
if len(captions) != T:
|
|
1898
|
+
raise ValueError(f"{len(captions)} captions for {T} frames")
|
|
1899
|
+
seq = list(captions)
|
|
1900
|
+
|
|
1901
|
+
def caption(t: float) -> str:
|
|
1902
|
+
return seq[_nearest(t, T)]
|
|
1903
|
+
|
|
1904
|
+
else:
|
|
1905
|
+
caption = None
|
|
1906
|
+
times = np.arange(T, dtype=np.float64) if n is None else np.linspace(0, T - 1, n)
|
|
1907
|
+
rotations = None if spin is None else _spin_rotations(spin, len(times))
|
|
1908
|
+
folder = None if frames_dir is None else Path(frames_dir)
|
|
1909
|
+
if folder is not None:
|
|
1910
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
1911
|
+
scene = _Scene(
|
|
1912
|
+
centers,
|
|
1913
|
+
node_sizes,
|
|
1914
|
+
load_mesh(mesh),
|
|
1915
|
+
**scene_opts,
|
|
1916
|
+
node_opacity=opacity,
|
|
1917
|
+
component_surfaces=surfaces,
|
|
1918
|
+
component_weights=None if components is None else components.mixing,
|
|
1919
|
+
lobe_negative_color=lobe_negative_color,
|
|
1920
|
+
)
|
|
1921
|
+
|
|
1922
|
+
def frames() -> Iterator[Any]:
|
|
1923
|
+
if rotations is not None:
|
|
1924
|
+
center, scale = scene.fit_spin(rotations)
|
|
1925
|
+
for k, t in enumerate(times):
|
|
1926
|
+
if rotations is not None:
|
|
1927
|
+
scene.orbit(rotations[k], center, scale)
|
|
1928
|
+
scene.set_edges(_at_time(E, float(t), interpolation), **edge_opts)
|
|
1929
|
+
img = scene.image()
|
|
1930
|
+
if caption is not None:
|
|
1931
|
+
img = _with_header(img, [caption(float(t))])
|
|
1932
|
+
if jpeg_quality is not None:
|
|
1933
|
+
img = _jpeg(img, jpeg_quality)
|
|
1934
|
+
if folder is not None:
|
|
1935
|
+
ext = ".png" if jpeg_quality is None else ".jpg"
|
|
1936
|
+
_save(img, folder / f"{k + 1}{ext}", jpeg_quality)
|
|
1937
|
+
yield img
|
|
1938
|
+
|
|
1939
|
+
try:
|
|
1940
|
+
return write_animation(frames(), out, fps=fps)
|
|
1941
|
+
finally:
|
|
1942
|
+
scene.close()
|
|
1943
|
+
|
|
1944
|
+
|
|
1945
|
+
# ------------------------------------------------------------------ animations
|
|
1946
|
+
|
|
1947
|
+
|
|
1948
|
+
def write_animation(
|
|
1949
|
+
images: Iterable[Any], out: str | os.PathLike, fps: float = 10
|
|
1950
|
+
) -> Path:
|
|
1951
|
+
"""Write PIL images as an mp4 (H.264, yuv420p) or looping GIF, by suffix.
|
|
1952
|
+
|
|
1953
|
+
``images`` may be any iterable, such as a generator. An mp4 is written
|
|
1954
|
+
frame by frame as the iterable yields, so only one frame is held in
|
|
1955
|
+
memory at a time.
|
|
1956
|
+
|
|
1957
|
+
GIFs use one palette for all frames (white, white-to-red and white-to-blue
|
|
1958
|
+
ramps, plus median-cut colors of all frames), without dithering, so colors
|
|
1959
|
+
do not flicker between frames. Choosing that palette needs every frame,
|
|
1960
|
+
so a GIF holds all frames in memory: about 4.8 MB per 1600 x 1000 frame
|
|
1961
|
+
(300 frames: about 1.4 GB). Use mp4 for long movies. Pillow stores
|
|
1962
|
+
identical consecutive GIF frames once, with their durations added, so
|
|
1963
|
+
such a GIF has fewer frames but the same running time.
|
|
1964
|
+
"""
|
|
1965
|
+
_check_fps(fps)
|
|
1966
|
+
out = Path(out)
|
|
1967
|
+
suffix = out.suffix.lower()
|
|
1968
|
+
if suffix not in (".mp4", ".gif"):
|
|
1969
|
+
raise ValueError(f"out must end in .mp4 or .gif, got {out.name!r}")
|
|
1970
|
+
if suffix == ".gif":
|
|
1971
|
+
frames = [im.convert("RGB") for im in images]
|
|
1972
|
+
if not frames:
|
|
1973
|
+
raise ValueError("no frames to write")
|
|
1974
|
+
if len({f.size for f in frames}) != 1:
|
|
1975
|
+
raise ValueError("all frames must have the same size")
|
|
1976
|
+
_write_gif(frames, out, fps)
|
|
1977
|
+
return out
|
|
1978
|
+
iio = lazy_import("imageio.v2", "brain3d", "mp4 export")
|
|
1979
|
+
lazy_import("imageio_ffmpeg", "brain3d", "mp4 export")
|
|
1980
|
+
size = None
|
|
1981
|
+
with iio.get_writer(
|
|
1982
|
+
out,
|
|
1983
|
+
fps=fps,
|
|
1984
|
+
codec="libx264",
|
|
1985
|
+
quality=8,
|
|
1986
|
+
macro_block_size=2,
|
|
1987
|
+
pixelformat="yuv420p",
|
|
1988
|
+
) as writer:
|
|
1989
|
+
for im in images:
|
|
1990
|
+
frame = im.convert("RGB")
|
|
1991
|
+
if size is None:
|
|
1992
|
+
size = frame.size
|
|
1993
|
+
elif frame.size != size:
|
|
1994
|
+
raise ValueError("all frames must have the same size")
|
|
1995
|
+
w, h = size
|
|
1996
|
+
writer.append_data(np.asarray(frame.crop((0, 0, w - w % 2, h - h % 2))))
|
|
1997
|
+
if size is None:
|
|
1998
|
+
out.unlink(missing_ok=True)
|
|
1999
|
+
raise ValueError("no frames to write")
|
|
2000
|
+
return out
|
|
2001
|
+
|
|
2002
|
+
|
|
2003
|
+
def _write_gif(frames: list[Any], out: Path, fps: float) -> None:
|
|
2004
|
+
Image = _pil()
|
|
2005
|
+
w, h = frames[0].size
|
|
2006
|
+
tw, th = max(1, w // 2), max(1, h // 2)
|
|
2007
|
+
mosaic = Image.new("RGB", (tw, th * len(frames)))
|
|
2008
|
+
for k, f in enumerate(frames):
|
|
2009
|
+
mosaic.paste(f.resize((tw, th), Image.BOX), (0, k * th))
|
|
2010
|
+
t = np.linspace(0, 1, 16)[:, None]
|
|
2011
|
+
ramps = np.vstack(
|
|
2012
|
+
[[255.0, 255.0, 255.0]]
|
|
2013
|
+
+ [255 * (1 - t) + np.array(c) * t for c in ([255, 0, 0], [0, 0, 255])]
|
|
2014
|
+
)
|
|
2015
|
+
n_free = 255 - len(ramps) # index 255 is reserved for transparency
|
|
2016
|
+
rest = np.asarray(
|
|
2017
|
+
mosaic.quantize(colors=n_free, method=Image.Quantize.MEDIANCUT).getpalette()[
|
|
2018
|
+
: 3 * n_free
|
|
2019
|
+
]
|
|
2020
|
+
).reshape(-1, 3)
|
|
2021
|
+
palette = np.vstack([np.round(ramps), rest]).astype(np.int64)
|
|
2022
|
+
transparent = len(palette)
|
|
2023
|
+
flat_palette = np.vstack([palette, [[255, 0, 255]]]).ravel().tolist()
|
|
2024
|
+
tree = cKDTree(palette)
|
|
2025
|
+
indexed = []
|
|
2026
|
+
for f in frames:
|
|
2027
|
+
a = np.asarray(f).reshape(-1, 3).astype(np.int64)
|
|
2028
|
+
packed = (a[:, 0] << 16) | (a[:, 1] << 8) | a[:, 2]
|
|
2029
|
+
uniq, inv = np.unique(packed, return_inverse=True)
|
|
2030
|
+
cols = np.c_[uniq >> 16, (uniq >> 8) & 255, uniq & 255]
|
|
2031
|
+
idx = tree.query(cols)[1].astype(np.uint8)
|
|
2032
|
+
indexed.append(idx[inv.ravel()].reshape(h, w))
|
|
2033
|
+
pages = []
|
|
2034
|
+
for k, a in enumerate(indexed):
|
|
2035
|
+
b = a.copy()
|
|
2036
|
+
if k:
|
|
2037
|
+
b[a == indexed[k - 1]] = transparent
|
|
2038
|
+
page = Image.fromarray(b, "P")
|
|
2039
|
+
page.putpalette(flat_palette)
|
|
2040
|
+
pages.append(page)
|
|
2041
|
+
pages[0].save(
|
|
2042
|
+
out,
|
|
2043
|
+
save_all=True,
|
|
2044
|
+
append_images=pages[1:],
|
|
2045
|
+
duration=int(round(1000 / fps)),
|
|
2046
|
+
loop=0,
|
|
2047
|
+
transparency=transparent,
|
|
2048
|
+
disposal=1,
|
|
2049
|
+
optimize=False,
|
|
2050
|
+
)
|
|
2051
|
+
|
|
2052
|
+
|
|
2053
|
+
# --------------------------------------------------------------------- panels
|
|
2054
|
+
|
|
2055
|
+
|
|
2056
|
+
def image_diff(a: Any, b: Any, size: tuple[int, int] = (400, 250)) -> float:
|
|
2057
|
+
"""Mean absolute RGB difference (0-255) of two images resized to ``size``.
|
|
2058
|
+
|
|
2059
|
+
``a`` and ``b`` are paths or PIL images.
|
|
2060
|
+
"""
|
|
2061
|
+
Image = _pil()
|
|
2062
|
+
|
|
2063
|
+
def arr(x: Any) -> Array:
|
|
2064
|
+
im = Image.open(x) if isinstance(x, (str, os.PathLike)) else x
|
|
2065
|
+
return np.asarray(
|
|
2066
|
+
im.convert("RGB").resize(size, Image.BILINEAR), dtype=np.float64
|
|
2067
|
+
)
|
|
2068
|
+
|
|
2069
|
+
return float(np.abs(arr(a) - arr(b)).mean())
|
|
2070
|
+
|
|
2071
|
+
|
|
2072
|
+
def _open(x: Any) -> Any:
|
|
2073
|
+
Image = _pil()
|
|
2074
|
+
if isinstance(x, (str, os.PathLike)):
|
|
2075
|
+
with Image.open(x) as im:
|
|
2076
|
+
return im.convert("RGB")
|
|
2077
|
+
return x.convert("RGB")
|
|
2078
|
+
|
|
2079
|
+
|
|
2080
|
+
def _content_box(images: Sequence[Any], margin: int = 10) -> tuple[int, int, int, int]:
|
|
2081
|
+
"""Smallest box holding every non-white pixel of all images, plus a margin."""
|
|
2082
|
+
w, h = images[0].size
|
|
2083
|
+
mask = np.zeros((h, w), dtype=bool)
|
|
2084
|
+
for im in images:
|
|
2085
|
+
if im.size != (w, h):
|
|
2086
|
+
raise ValueError("all images must have the same size")
|
|
2087
|
+
mask |= np.asarray(im).min(axis=2) < 250
|
|
2088
|
+
if not mask.any():
|
|
2089
|
+
return 0, 0, w, h
|
|
2090
|
+
rows, cols = np.flatnonzero(mask.any(axis=1)), np.flatnonzero(mask.any(axis=0))
|
|
2091
|
+
return (
|
|
2092
|
+
max(0, int(cols[0]) - margin),
|
|
2093
|
+
max(0, int(rows[0]) - margin),
|
|
2094
|
+
min(w, int(cols[-1]) + 1 + margin),
|
|
2095
|
+
min(h, int(rows[-1]) + 1 + margin),
|
|
2096
|
+
)
|
|
2097
|
+
|
|
2098
|
+
|
|
2099
|
+
def _font(size: int) -> Any:
|
|
2100
|
+
font = lazy_import("PIL.ImageFont", "brain3d", "annotations")
|
|
2101
|
+
return font.load_default(size=size)
|
|
2102
|
+
|
|
2103
|
+
|
|
2104
|
+
def _center_text(
|
|
2105
|
+
draw: Any, xc: float, y: float, text: str, font: Any, fill: Any
|
|
2106
|
+
) -> None:
|
|
2107
|
+
draw.text(
|
|
2108
|
+
(xc - draw.textlength(text, font=font) / 2, y), text, font=font, fill=fill
|
|
2109
|
+
)
|
|
2110
|
+
|
|
2111
|
+
|
|
2112
|
+
def _with_header(img: Any, lines: Sequence[str], fontsize: int | None = None) -> Any:
|
|
2113
|
+
"""``img`` under a white band holding centered text lines."""
|
|
2114
|
+
Image = _pil()
|
|
2115
|
+
draw_mod = lazy_import("PIL.ImageDraw", "brain3d", "annotations")
|
|
2116
|
+
w, h = img.size
|
|
2117
|
+
size = fontsize or max(16, w // 32)
|
|
2118
|
+
font = _font(size)
|
|
2119
|
+
head = int(size * (0.5 + 1.3 * len(lines)))
|
|
2120
|
+
canvas = Image.new("RGB", (w, head + h), "white")
|
|
2121
|
+
canvas.paste(img, (0, head))
|
|
2122
|
+
d = draw_mod.Draw(canvas)
|
|
2123
|
+
for k, line in enumerate(lines):
|
|
2124
|
+
_center_text(d, w / 2, size * (0.25 + 1.3 * k), line, font, (0, 0, 0))
|
|
2125
|
+
return canvas
|
|
2126
|
+
|
|
2127
|
+
|
|
2128
|
+
def annotate_pair(
|
|
2129
|
+
left: Any,
|
|
2130
|
+
right: Any,
|
|
2131
|
+
titles: tuple[str, str],
|
|
2132
|
+
caption: str | None = None,
|
|
2133
|
+
width: int = 1200,
|
|
2134
|
+
crop: tuple[int, int, int, int] | None = None,
|
|
2135
|
+
) -> Any:
|
|
2136
|
+
"""Two frames side by side under a header band with titles and a caption.
|
|
2137
|
+
|
|
2138
|
+
Parameters
|
|
2139
|
+
----------
|
|
2140
|
+
left, right : path or PIL image
|
|
2141
|
+
Frames of equal size.
|
|
2142
|
+
titles : (str, str)
|
|
2143
|
+
Panel titles; a ``"\\n"`` starts a smaller subtitle line.
|
|
2144
|
+
caption : str, optional
|
|
2145
|
+
A line centered under the titles (e.g. a time counter).
|
|
2146
|
+
width : int
|
|
2147
|
+
Output width in pixels.
|
|
2148
|
+
crop : (left, top, right, bottom), optional
|
|
2149
|
+
Region of each frame to show. Default: the box around all non-white
|
|
2150
|
+
pixels of both frames.
|
|
2151
|
+
|
|
2152
|
+
Returns
|
|
2153
|
+
-------
|
|
2154
|
+
PIL.Image.Image
|
|
2155
|
+
Text sits only in the header band, never over the brain.
|
|
2156
|
+
"""
|
|
2157
|
+
Image = _pil()
|
|
2158
|
+
draw_mod = lazy_import("PIL.ImageDraw", "brain3d", "annotations")
|
|
2159
|
+
ims = [_open(left), _open(right)]
|
|
2160
|
+
box = crop or _content_box(ims)
|
|
2161
|
+
pane_w = width // 2
|
|
2162
|
+
pane_h = round(pane_w * (box[3] - box[1]) / (box[2] - box[0]))
|
|
2163
|
+
tsize = max(16, width // 32)
|
|
2164
|
+
ssize = int(tsize * 0.8)
|
|
2165
|
+
n_sub = max(len(t.split("\n")) for t in titles) - 1
|
|
2166
|
+
head = int(
|
|
2167
|
+
tsize * 1.5
|
|
2168
|
+
+ n_sub * ssize * 1.3
|
|
2169
|
+
+ (ssize * 1.6 if caption else 0)
|
|
2170
|
+
+ tsize * 0.4
|
|
2171
|
+
)
|
|
2172
|
+
ft, fs = _font(tsize), _font(ssize)
|
|
2173
|
+
canvas = Image.new("RGB", (width, head + pane_h), "white")
|
|
2174
|
+
d = draw_mod.Draw(canvas)
|
|
2175
|
+
for k, (im, title) in enumerate(zip(ims, titles, strict=True)):
|
|
2176
|
+
canvas.paste(
|
|
2177
|
+
im.crop(box).resize((pane_w, pane_h), Image.LANCZOS), (k * pane_w, head)
|
|
2178
|
+
)
|
|
2179
|
+
lines = title.split("\n")
|
|
2180
|
+
xc = k * pane_w + pane_w / 2
|
|
2181
|
+
_center_text(d, xc, int(tsize * 0.3), lines[0], ft, (0, 0, 0))
|
|
2182
|
+
for m, line in enumerate(lines[1:]):
|
|
2183
|
+
_center_text(
|
|
2184
|
+
d, xc, int(tsize * 1.5 + m * ssize * 1.3), line, fs, (60, 60, 60)
|
|
2185
|
+
)
|
|
2186
|
+
if caption:
|
|
2187
|
+
_center_text(
|
|
2188
|
+
d, width / 2, int(tsize * 1.6 + n_sub * ssize * 1.3), caption, fs, (0, 0, 0)
|
|
2189
|
+
)
|
|
2190
|
+
d.line([(pane_w, head), (pane_w, head + pane_h)], fill=(200, 200, 200), width=2)
|
|
2191
|
+
return canvas
|
|
2192
|
+
|
|
2193
|
+
|
|
2194
|
+
def montage(
|
|
2195
|
+
images: Sequence[Sequence[Any]],
|
|
2196
|
+
row_labels: Sequence[str],
|
|
2197
|
+
col_labels: Sequence[str],
|
|
2198
|
+
title: str | None = None,
|
|
2199
|
+
cell_width: int = 330,
|
|
2200
|
+
crop: tuple[int, int, int, int] | None = None,
|
|
2201
|
+
out: str | os.PathLike | None = None,
|
|
2202
|
+
) -> Any:
|
|
2203
|
+
"""Grid of frames with row labels on the left and column labels on top.
|
|
2204
|
+
|
|
2205
|
+
Parameters
|
|
2206
|
+
----------
|
|
2207
|
+
images : rows of paths or PIL images, all the same size
|
|
2208
|
+
row_labels, col_labels : sequences of str
|
|
2209
|
+
One per row / column; ``"\\n"`` splits a row label into lines.
|
|
2210
|
+
title : str, optional
|
|
2211
|
+
Line above the column labels.
|
|
2212
|
+
cell_width : int
|
|
2213
|
+
Width of each cell in pixels.
|
|
2214
|
+
crop : (left, top, right, bottom), optional
|
|
2215
|
+
Region of each frame to show; default the box around all non-white
|
|
2216
|
+
pixels of all frames.
|
|
2217
|
+
out : path, optional
|
|
2218
|
+
Save the montage there.
|
|
2219
|
+
|
|
2220
|
+
Returns
|
|
2221
|
+
-------
|
|
2222
|
+
PIL.Image.Image
|
|
2223
|
+
"""
|
|
2224
|
+
Image = _pil()
|
|
2225
|
+
draw_mod = lazy_import("PIL.ImageDraw", "brain3d", "annotations")
|
|
2226
|
+
grid = [[_open(x) for x in row] for row in images]
|
|
2227
|
+
if len(grid) != len(row_labels) or any(len(r) != len(col_labels) for r in grid):
|
|
2228
|
+
raise ValueError("images must be len(row_labels) rows of len(col_labels)")
|
|
2229
|
+
box = crop or _content_box([im for row in grid for im in row])
|
|
2230
|
+
cell_h = round(cell_width * (box[3] - box[1]) / (box[2] - box[0]))
|
|
2231
|
+
tsize, lsize = 40, 34
|
|
2232
|
+
ft, fl = _font(tsize), _font(lsize)
|
|
2233
|
+
label_w = (
|
|
2234
|
+
14
|
|
2235
|
+
+ int(max(fl.getlength(line) for lab in row_labels for line in lab.split("\n")))
|
|
2236
|
+
+ 20
|
|
2237
|
+
)
|
|
2238
|
+
head = int(tsize * 1.8) + (int(tsize * 1.6) if title else 0)
|
|
2239
|
+
W, H = label_w + cell_width * len(col_labels), head + cell_h * len(grid)
|
|
2240
|
+
canvas = Image.new("RGB", (W, H), "white")
|
|
2241
|
+
d = draw_mod.Draw(canvas)
|
|
2242
|
+
if title:
|
|
2243
|
+
_center_text(d, W / 2, int(tsize * 0.3), title, ft, (0, 0, 0))
|
|
2244
|
+
for c, lab in enumerate(col_labels):
|
|
2245
|
+
xc = label_w + c * cell_width + cell_width / 2
|
|
2246
|
+
_center_text(d, xc, head - int(tsize * 1.5), lab, ft, (0, 0, 0))
|
|
2247
|
+
for r, (row, lab) in enumerate(zip(grid, row_labels, strict=True)):
|
|
2248
|
+
for c, im in enumerate(row):
|
|
2249
|
+
cell = im.crop(box).resize((cell_width, cell_h), Image.LANCZOS)
|
|
2250
|
+
canvas.paste(cell, (label_w + c * cell_width, head + r * cell_h))
|
|
2251
|
+
lines = lab.split("\n")
|
|
2252
|
+
yc = head + r * cell_h + cell_h / 2 - len(lines) * lsize * 0.6
|
|
2253
|
+
for k, line in enumerate(lines):
|
|
2254
|
+
d.text((14, yc + k * lsize * 1.2), line, font=fl, fill=(0, 0, 0))
|
|
2255
|
+
if out is not None:
|
|
2256
|
+
canvas.save(out)
|
|
2257
|
+
return canvas
|