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/_lazy.py ADDED
@@ -0,0 +1,437 @@
1
+ """Import optional dependencies, installing them on demand.
2
+
3
+ The pip specs installed are read back from the installed package metadata, so
4
+ the extras declared in ``pyproject.toml`` are the single source of truth.
5
+ """
6
+
7
+ import importlib
8
+ import importlib.metadata
9
+ import importlib.util
10
+ import os
11
+ import platform
12
+ import re
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ import tempfile
17
+ from collections.abc import Callable, Sequence
18
+ from inspect import getmodulename
19
+ from types import ModuleType
20
+
21
+ from packaging.requirements import Requirement
22
+ from packaging.specifiers import SpecifierSet
23
+ from packaging.utils import canonicalize_name
24
+ from packaging.version import InvalidVersion, Version
25
+
26
+ ENV_VAR = "HTFA_AUTO_INSTALL"
27
+ TORCH_INDEX = "https://download.pytorch.org/whl/"
28
+ # Highest-first; verified 2026-10-23 to carry torch 2.14 wheels.
29
+ CUDA_WHEEL_TAGS = {(13, 2): "cu132", (13, 0): "cu130", (12, 6): "cu126"}
30
+
31
+ _override: bool | None = None
32
+
33
+
34
+ def set_autoinstall(enabled: bool) -> None:
35
+ """Turn on-demand installation of optional dependencies on or off.
36
+
37
+ By default a missing optional dependency (for example matplotlib for plots
38
+ or pillow for 2D images) is installed with pip the first time it is needed.
39
+ The ``HTFA_AUTO_INSTALL`` environment variable (``0``, ``false`` or ``no``
40
+ turns it off) sets the default; this function overrides the variable for the
41
+ current process.
42
+
43
+ Parameters
44
+ ----------
45
+ enabled : bool
46
+ ``True`` allows installation; ``False`` makes a missing dependency raise
47
+ ``ImportError`` with the ``pip install`` command to run.
48
+
49
+ Examples
50
+ --------
51
+ >>> import htfa
52
+ >>> htfa.set_autoinstall(False)
53
+ >>> from htfa._lazy import autoinstall_enabled
54
+ >>> autoinstall_enabled()
55
+ False
56
+ >>> htfa.set_autoinstall(True)
57
+ """
58
+ global _override
59
+ _override = bool(enabled)
60
+
61
+
62
+ def autoinstall_enabled() -> bool:
63
+ """Whether missing optional dependencies may be pip-installed."""
64
+ if _override is not None:
65
+ return _override
66
+ return os.environ.get(ENV_VAR, "1").strip().lower() not in ("0", "false", "no")
67
+
68
+
69
+ def _find_spec(module: str) -> bool:
70
+ try:
71
+ return importlib.util.find_spec(module) is not None
72
+ except (ImportError, ValueError):
73
+ return False
74
+
75
+
76
+ def extra_requirements(extra: str) -> list[str]:
77
+ """Requirement specs that htfa's metadata declares for ``extra``."""
78
+ found = []
79
+ for line in importlib.metadata.requires("htfa") or []:
80
+ req = Requirement(line)
81
+ if req.marker is None:
82
+ continue
83
+ if req.marker.evaluate({"extra": extra}) and not req.marker.evaluate(
84
+ {"extra": ""}
85
+ ):
86
+ req.marker = None
87
+ found.append(str(req))
88
+ if not found:
89
+ raise ValueError(f"htfa declares no requirements for extra {extra!r}")
90
+ return found
91
+
92
+
93
+ def _manual(extra: str) -> str:
94
+ return f'pip install "htfa[{extra}]"'
95
+
96
+
97
+ _DISTRIBUTIONS = {"PIL": "pillow", "sklearn": "scikit-learn"}
98
+
99
+
100
+ def declared_requirement(module: str) -> str:
101
+ """Requirement spec htfa's metadata declares for the library ``module``.
102
+
103
+ The version constraints of every extra that lists the library are combined.
104
+ """
105
+ top = module.split(".")[0]
106
+ name = canonicalize_name(_DISTRIBUTIONS.get(top, top))
107
+ found = None
108
+ spec = SpecifierSet()
109
+ for line in importlib.metadata.requires("htfa") or []:
110
+ req = Requirement(line)
111
+ if canonicalize_name(req.name) == name:
112
+ found = req.name
113
+ spec &= req.specifier
114
+ if found is None:
115
+ raise ImportError(
116
+ f"{module} is not installed, and htfa does not declare it in any extra, "
117
+ "so it is not installed automatically; install it yourself, or pass "
118
+ "the htfa extra that provides it"
119
+ )
120
+ return f"{found}{spec}"
121
+
122
+
123
+ def _succeeds(cmd: list[str], cwd: str) -> bool:
124
+ try:
125
+ run = subprocess.run(cmd, capture_output=True, check=False, cwd=cwd)
126
+ except OSError:
127
+ return False
128
+ return run.returncode == 0
129
+
130
+
131
+ def _installer(cwd: str) -> list[str]:
132
+ """Command prefix that installs packages into this interpreter's environment.
133
+
134
+ pip if it works; else uv (a bare ``uv venv`` has no pip); else pip
135
+ bootstrapped with ensurepip. ``cwd`` is the private directory they run in.
136
+ pip runs without ``-q``: its output is captured, and only a failed run's is
137
+ shown, which then includes the constraint that blocked the resolution.
138
+ """
139
+ # -I keeps a planted pip.py off sys.path; pip still reads the user's and
140
+ # the global pip.conf (a corporate index keeps working), never the cwd.
141
+ pip = [sys.executable, "-I", "-m", "pip"]
142
+ if _succeeds([*pip, "--version"], cwd):
143
+ return [*pip, "install"]
144
+ uv = _find_executable("uv")
145
+ if uv is not None:
146
+ print(f"htfa: pip is not available; installing with {uv}", file=sys.stderr)
147
+ # uv reads uv.toml / pyproject.toml [tool.uv] from the cwd and every
148
+ # parent, which could redirect the index; --no-config ignores them. It
149
+ # also ignores the user's own uv.toml (UV_* environment variables, such
150
+ # as UV_INDEX_URL, still apply).
151
+ return [uv, "--no-config", "pip", "install", "-q", "--python", sys.executable]
152
+ print(
153
+ "htfa: pip is not available; bootstrapping it with ensurepip", file=sys.stderr
154
+ )
155
+ if _succeeds([sys.executable, "-I", "-m", "ensurepip"], cwd) and _succeeds(
156
+ [*pip, "--version"], cwd
157
+ ):
158
+ return [*pip, "install"]
159
+ raise ImportError(
160
+ f"no installer works for {sys.executable}: pip is missing, uv is not on "
161
+ "PATH and ensurepip failed. Install pip (`apt-get install python3-pip` "
162
+ "on Debian/Ubuntu, or `python -m ensurepip`) or uv, then rerun"
163
+ )
164
+
165
+
166
+ class _RestartRequired(ImportError):
167
+ """The install needs another version of a package this process has loaded."""
168
+
169
+
170
+ def imported_distributions() -> dict[str, str]:
171
+ """Installed version of each distribution that provides a loaded module.
172
+
173
+ Keys are canonical distribution names; a top-level name in ``sys.modules``
174
+ is mapped to its distributions with ``packages_distributions`` and, as
175
+ Python 3.11+ does, the top-level entries of each distribution's file list.
176
+ A version that is not PEP 440 cannot be written as a pin and is left out.
177
+ """
178
+ providers = {
179
+ module: set(dists)
180
+ for module, dists in importlib.metadata.packages_distributions().items()
181
+ }
182
+ # Python 3.10's packages_distributions reads only top_level.txt, which
183
+ # wheels not built by setuptools (numpy, packaging) do not have.
184
+ for dist in importlib.metadata.distributions():
185
+ name = dist.metadata["Name"]
186
+ for path in dist.files or ():
187
+ top = path.parts[0] if len(path.parts) > 1 else getmodulename(path.name)
188
+ if name and top and "." not in top: # skips *.dist-info and ../bin
189
+ providers.setdefault(top, set()).add(name)
190
+ names = {
191
+ canonicalize_name(dist)
192
+ for module in list(sys.modules)
193
+ if "." not in module
194
+ for dist in providers.get(module, ())
195
+ }
196
+ pins: dict[str, str] = {}
197
+ for name in sorted(names):
198
+ try:
199
+ version = importlib.metadata.version(name)
200
+ Version(version)
201
+ except (importlib.metadata.PackageNotFoundError, InvalidVersion):
202
+ continue
203
+ pins[name] = version
204
+ return pins
205
+
206
+
207
+ def _restart(changed: list[str], manual: str) -> _RestartRequired:
208
+ return _RestartRequired(
209
+ f"the automatic install would replace {', '.join(changed)}, already "
210
+ "imported in this Python process, and a loaded package cannot be replaced "
211
+ "safely. Restart the process (in Jupyter or Colab: restart the kernel or "
212
+ f"runtime), then run `{manual}` before importing anything else."
213
+ )
214
+
215
+
216
+ def _pip_install(args: list[str], manual: str) -> None:
217
+ """Install ``args`` without changing any distribution that is loaded.
218
+
219
+ Every distribution with an imported module is pinned to its installed
220
+ version through a constraints file, so the installer either leaves them
221
+ alone or fails before changing anything; a failure that names a pin raises
222
+ ``_RestartRequired``.
223
+ """
224
+ pins = imported_distributions()
225
+ # A fresh private directory as cwd: nothing in the shared temp dir is read.
226
+ work = tempfile.mkdtemp(prefix="htfa-install-")
227
+ try:
228
+ constraints = os.path.join(work, "constraints.txt")
229
+ with open(constraints, "w", encoding="utf-8") as f:
230
+ f.writelines(f"{name}=={version}\n" for name, version in pins.items())
231
+ cmd = [*_installer(work), "-c", constraints, *args]
232
+ run = subprocess.run(
233
+ cmd, cwd=work, capture_output=True, text=True, errors="replace"
234
+ )
235
+ finally:
236
+ shutil.rmtree(work, ignore_errors=True)
237
+ importlib.invalidate_caches()
238
+ if run.returncode != 0:
239
+ output = run.stdout + run.stderr
240
+ print(output, end="", file=sys.stderr)
241
+ # pip and uv both quote the constraint that blocks the resolution.
242
+ blocked = [
243
+ f"{name} {version}"
244
+ for name, version in pins.items()
245
+ if re.search(
246
+ rf"(?<![\w.-]){re.escape(name)}=={re.escape(version)}(?![\w.+-])",
247
+ output,
248
+ re.IGNORECASE,
249
+ )
250
+ ]
251
+ if blocked:
252
+ raise _restart(blocked, manual)
253
+ raise subprocess.CalledProcessError(run.returncode, cmd, run.stdout, run.stderr)
254
+
255
+
256
+ def _import(
257
+ module: str, requirements: Callable[[], list[str]], manual: str, need: str
258
+ ) -> ModuleType:
259
+ try:
260
+ return importlib.import_module(module)
261
+ except ImportError as first:
262
+ if not autoinstall_enabled():
263
+ raise ImportError(
264
+ f"{module} is not installed{need}. Install it with `{manual}` "
265
+ "(automatic installation is off)."
266
+ ) from first
267
+ try:
268
+ reqs = requirements()
269
+ print(f"htfa: installing {', '.join(reqs)}{need}...", file=sys.stderr)
270
+ _pip_install(reqs, manual)
271
+ return importlib.import_module(module)
272
+ except _RestartRequired:
273
+ raise
274
+ except (subprocess.CalledProcessError, ImportError, ValueError) as second:
275
+ raise ImportError(
276
+ f"{module} is not installed{need}, and installing it automatically "
277
+ f"failed ({type(second).__name__}: {second}). "
278
+ f"Install it with `{manual}`."
279
+ ) from second
280
+
281
+
282
+ def lazy_import(module: str, extra: str, purpose: str | None = None) -> ModuleType:
283
+ """Import ``module``, installing the htfa ``extra`` that provides it if missing."""
284
+ need = f" (needed for {purpose})" if purpose else ""
285
+ return _import(module, lambda: extra_requirements(extra), _manual(extra), need)
286
+
287
+
288
+ def require(module: str, extra: str | None = None) -> ModuleType:
289
+ """Import a third-party library, installing it on first use.
290
+
291
+ Installation follows the same rules as htfa's own optional dependencies (see
292
+ :func:`set_autoinstall`): it uses the version constraints declared in htfa's
293
+ package metadata, and is off when ``HTFA_AUTO_INSTALL=0``. Only libraries
294
+ that htfa declares are installed.
295
+
296
+ Parameters
297
+ ----------
298
+ module : str
299
+ Name to import, for example ``"hypertools"`` or ``"matplotlib.pyplot"``.
300
+ extra : str, optional
301
+ The htfa extra to install if ``module`` is missing, for example
302
+ ``"tutorials"`` (hypertools, sentence-transformers). By default only the
303
+ library itself is installed, with the constraints that htfa's extras
304
+ declare for it. torch is always installed as for ``backend='torch'``
305
+ (a build matching the CUDA driver).
306
+
307
+ Returns
308
+ -------
309
+ module
310
+ The imported module.
311
+
312
+ Raises
313
+ ------
314
+ ValueError
315
+ If ``module`` is not an absolute module name.
316
+ ImportError
317
+ If the module is missing and cannot be installed: installation is off,
318
+ htfa does not declare it, or the installer failed. The message names the
319
+ command to run.
320
+
321
+ Examples
322
+ --------
323
+ >>> import htfa
324
+ >>> np = htfa.require("numpy")
325
+ >>> np.__name__
326
+ 'numpy'
327
+ """
328
+ if not module or module.startswith("."):
329
+ raise ValueError(f"require needs an absolute module name, got {module!r}")
330
+ if module.split(".")[0] == "torch":
331
+ ensure_torch() # picks the wheel index that matches the CUDA driver
332
+ return importlib.import_module(module)
333
+ if extra is not None:
334
+ return lazy_import(module, extra)
335
+ try:
336
+ return importlib.import_module(module)
337
+ except ImportError:
338
+ pass
339
+ spec = declared_requirement(module)
340
+ return _import(module, lambda: [spec], f'pip install "{spec}"', "")
341
+
342
+
343
+ def torch_index_url(nvidia_smi_output: str | None, system: str) -> str | None:
344
+ """PyTorch wheel index suited to the NVIDIA driver, or None for PyPI default."""
345
+ if system == "Darwin" or not nvidia_smi_output:
346
+ return None
347
+ match = re.search(r"CUDA Version:\s*(\d+)\.(\d+)", nvidia_smi_output)
348
+ if match is None:
349
+ return None
350
+ driver = (int(match.group(1)), int(match.group(2)))
351
+ for version in sorted(CUDA_WHEEL_TAGS, reverse=True):
352
+ if version <= driver:
353
+ return TORCH_INDEX + CUDA_WHEEL_TAGS[version]
354
+ return TORCH_INDEX + "cpu"
355
+
356
+
357
+ def _under(path: str, root: str) -> bool:
358
+ try:
359
+ return os.path.commonpath([path, root]) == root
360
+ except ValueError: # different drives
361
+ return False
362
+
363
+
364
+ def _find_executable(name: str, candidates: Sequence[str] = ()) -> str | None:
365
+ """Locate ``name`` on PATH, or else at ``candidates``, never in the cwd."""
366
+ cwd = os.path.realpath(os.getcwd())
367
+ exts = [""]
368
+ if sys.platform == "win32":
369
+ exts = os.environ.get("PATHEXT", ".COM;.EXE;.BAT;.CMD").split(";")
370
+ for d in os.environ.get("PATH", "").split(os.pathsep):
371
+ if not d or not os.path.isabs(d) or _under(os.path.realpath(d), cwd):
372
+ continue
373
+ for ext in exts:
374
+ path = os.path.join(d, name + ext)
375
+ if os.path.isfile(path) and os.access(path, os.X_OK):
376
+ real = os.path.realpath(path)
377
+ if os.path.isabs(real) and not _under(real, cwd):
378
+ return path
379
+ return next((c for c in candidates if os.path.isfile(c)), None)
380
+
381
+
382
+ def _find_nvidia_smi() -> str | None:
383
+ """Locate nvidia-smi without ever consulting the current directory."""
384
+ candidates = ["/usr/bin/nvidia-smi"]
385
+ root = os.environ.get("SystemRoot")
386
+ if root:
387
+ candidates.append(os.path.join(root, "System32", "nvidia-smi.exe"))
388
+ files = os.environ.get("ProgramFiles")
389
+ if files:
390
+ candidates.append(
391
+ os.path.join(files, "NVIDIA Corporation", "NVSMI", "nvidia-smi.exe")
392
+ )
393
+ return _find_executable("nvidia-smi", candidates)
394
+
395
+
396
+ def ensure_torch() -> ModuleType:
397
+ """Return the torch module, installing a suitable build first if needed."""
398
+ if _find_spec("torch"):
399
+ return importlib.import_module("torch")
400
+ manual = _manual("gpu")
401
+ if not autoinstall_enabled():
402
+ raise ImportError(
403
+ f"torch is not installed. Install it with `{manual}` "
404
+ "(automatic installation is off)."
405
+ )
406
+ output = None
407
+ exe = _find_nvidia_smi()
408
+ if exe:
409
+ try:
410
+ run = subprocess.run(
411
+ [exe], capture_output=True, text=True, check=False, timeout=10
412
+ )
413
+ output = run.stdout if run.returncode == 0 else None
414
+ except (subprocess.TimeoutExpired, OSError):
415
+ output = None
416
+ url = torch_index_url(output, platform.system())
417
+ if url is not None and url.endswith("/cpu"):
418
+ print(
419
+ "htfa: CUDA driver is older than the oldest supported wheels (12.6); "
420
+ "installing CPU-only torch.",
421
+ file=sys.stderr,
422
+ )
423
+ print(
424
+ "htfa: installing torch (GPU backend; this can be a large download)...",
425
+ file=sys.stderr,
426
+ )
427
+ args = ["torch>=2.2"] + (["--index-url", url] if url else [])
428
+ try:
429
+ _pip_install(args, manual)
430
+ return importlib.import_module("torch")
431
+ except _RestartRequired:
432
+ raise
433
+ except (subprocess.CalledProcessError, ImportError) as err:
434
+ raise ImportError(
435
+ f"torch could not be installed automatically ({type(err).__name__}). "
436
+ f"Install it with `{manual}`."
437
+ ) from err
htfa/_matching.py ADDED
@@ -0,0 +1,71 @@
1
+ """Hungarian matching of factors by their centers."""
2
+
3
+ import numpy as np
4
+ from numpy.typing import NDArray
5
+ from scipy.optimize import linear_sum_assignment
6
+ from scipy.spatial.distance import cdist
7
+
8
+ Array = NDArray[np.float64]
9
+
10
+
11
+ def match_factors(true_centers: Array, est_centers: Array) -> NDArray[np.intp]:
12
+ """Match estimated factors to true ones with the Hungarian algorithm.
13
+
14
+ Parameters
15
+ ----------
16
+ true_centers : ndarray, shape (K, D)
17
+ Ground-truth centers.
18
+ est_centers : ndarray, shape (K, D)
19
+ Estimated centers, in arbitrary order.
20
+
21
+ Returns
22
+ -------
23
+ perm : ndarray of int, shape (K,)
24
+ Permutation such that ``est_centers[perm][k]`` corresponds to
25
+ ``true_centers[k]`` (minimum total squared Euclidean distance).
26
+
27
+ Examples
28
+ --------
29
+ >>> import numpy as np
30
+ >>> from htfa.synthetic import match_factors
31
+ >>> true = np.array([[0.0, 0.0], [5.0, 5.0]])
32
+ >>> est = np.array([[5.1, 4.9], [0.1, -0.1]])
33
+ >>> match_factors(true, est)
34
+ array([1, 0])
35
+ """
36
+ cost = cdist(true_centers, est_centers, metric="sqeuclidean")
37
+ rows, cols = linear_sum_assignment(cost)
38
+ perm = np.empty(len(rows), dtype=np.intp)
39
+ perm[rows] = cols
40
+ return perm
41
+
42
+
43
+ def match_components(template_centers: Array, est_centers: Array) -> NDArray[np.intp]:
44
+ """Match each factor's components to a template's, by their centers.
45
+
46
+ Parameters
47
+ ----------
48
+ template_centers, est_centers : ndarray, shape (K, M, D)
49
+ Component centers of K factors with M components each, the factors
50
+ already matched (`match_factors`).
51
+
52
+ Returns
53
+ -------
54
+ perm : ndarray of int, shape (K, M)
55
+ ``est_centers[k, perm[k]]`` corresponds to ``template_centers[k]``
56
+ (Hungarian, per factor).
57
+
58
+ Examples
59
+ --------
60
+ >>> import numpy as np
61
+ >>> from htfa._matching import match_components
62
+ >>> t = np.array([[[0.0, 0.0], [5.0, 5.0]]])
63
+ >>> match_components(t, t[:, ::-1])
64
+ array([[1, 0]])
65
+ """
66
+ return np.stack(
67
+ [
68
+ match_factors(t, e)
69
+ for t, e in zip(template_centers, est_centers, strict=True)
70
+ ]
71
+ )
htfa/_spatial.py ADDED
@@ -0,0 +1,145 @@
1
+ """Shared component geometry for network plots (one edge anchor per component)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from dataclasses import dataclass
7
+ from typing import Any
8
+
9
+ import nibabel as nib
10
+ import numpy as np
11
+
12
+ from ._kernels import Kernel
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class ComponentNodes:
17
+ """Flattened components in factor-major order, retaining their factor IDs."""
18
+
19
+ kernel: str
20
+ centers: np.ndarray
21
+ widths: np.ndarray
22
+ mixing: np.ndarray
23
+ parents: np.ndarray
24
+
25
+ @classmethod
26
+ def from_shape(cls, shape: tuple) -> ComponentNodes:
27
+ name, centers, widths, mixing = shape
28
+ centers, widths, mixing = (
29
+ np.asarray(v, dtype=float) for v in (centers, widths, mixing)
30
+ )
31
+ if (
32
+ centers.ndim != 3
33
+ or widths.shape != centers.shape[:2]
34
+ or mixing.shape != widths.shape
35
+ ):
36
+ raise ValueError(
37
+ "component centers, widths and mixing weights have incompatible shapes"
38
+ )
39
+ if (
40
+ not all(np.all(np.isfinite(v)) for v in (centers, widths, mixing))
41
+ or np.any(widths <= 0)
42
+ or np.any(mixing <= 0)
43
+ ):
44
+ raise ValueError(
45
+ "components must be finite with positive widths and mixing weights"
46
+ )
47
+ Kernel(name, centers.shape[1])
48
+ return cls(
49
+ name,
50
+ centers.reshape(-1, centers.shape[-1]),
51
+ widths.ravel(),
52
+ mixing.ravel(),
53
+ np.repeat(np.arange(len(centers)), centers.shape[1]),
54
+ )
55
+
56
+ def connectivity(self, values: Any) -> np.ndarray:
57
+ """Repeat each factor edge unchanged; omit edges within the same factor."""
58
+ a = np.asarray(values, dtype=float)
59
+ K = int(self.parents.max()) + 1
60
+ if a.ndim not in (2, 3) or a.shape[-2:] != (K, K):
61
+ raise ValueError(f"connectivity must end in ({K}, {K}), got {a.shape}")
62
+ out = a[..., self.parents[:, None], self.parents[None, :]].copy()
63
+ out[..., self.parents[:, None] == self.parents[None, :]] = 0
64
+ return out
65
+
66
+ def values(self, coords: np.ndarray, index: int) -> np.ndarray:
67
+ """Signed, mixing-weighted component profile at world coordinates."""
68
+ z = np.sum((coords - self.centers[index]) ** 2, axis=1) / self.widths[index]
69
+ return self.mixing[index] * Kernel(self.kernel).profile(z, coords.shape[1])
70
+
71
+ def images(self, mask: Any) -> Iterator[tuple[int, Any]]:
72
+ """Signed component images on the mask's native grid (zero outside).
73
+
74
+ Coordinate masks must be an axis-aligned regular lattice. NIfTI masks
75
+ retain their affine, including rotations and anisotropic voxel sizes.
76
+ Each image is made separately, avoiding a V-by-K-by-M allocation.
77
+ """
78
+ coords, indices, shape, affine = _grid(mask)
79
+ for i in range(len(self.centers)):
80
+ data = np.zeros(shape)
81
+ data[tuple(indices.T)] = self.values(coords, i)
82
+ yield i, nib.Nifti1Image(data, affine)
83
+
84
+
85
+ def component_mode(mode: str, has_shape: bool) -> bool:
86
+ if mode not in ("auto", "components", "summary"):
87
+ raise ValueError("node_mode must be 'auto', 'components' or 'summary'")
88
+ return mode == "components" or (mode == "auto" and has_shape)
89
+
90
+
91
+ def check_level(level: float) -> float:
92
+ if not np.isfinite(level) or not 0 < level < 1:
93
+ raise ValueError(
94
+ "lobe_level must be a finite fraction strictly between 0 and 1"
95
+ )
96
+ return float(level)
97
+
98
+
99
+ def _grid(mask: Any) -> tuple[np.ndarray, np.ndarray, tuple, np.ndarray]:
100
+ if isinstance(mask, tuple) or (
101
+ hasattr(mask, "affine") and hasattr(mask, "dataobj")
102
+ ):
103
+ volume, affine = (
104
+ mask if isinstance(mask, tuple) else (mask.dataobj, mask.affine)
105
+ )
106
+ volume, affine = np.asarray(volume), np.asarray(affine, dtype=float)
107
+ if (
108
+ volume.ndim != 3
109
+ or affine.shape != (4, 4)
110
+ or not np.all(np.isfinite(affine))
111
+ ):
112
+ raise ValueError("component lobes need a 3D mask and finite 4x4 affine")
113
+ indices = np.argwhere(np.isfinite(volume) & (volume != 0))
114
+ shape = volume.shape
115
+ coords = nib.affines.apply_affine(affine, indices)
116
+ else:
117
+ from .brainnet import _grid_spacing
118
+
119
+ coords = np.asarray(mask, dtype=float)
120
+ if (
121
+ coords.ndim != 2
122
+ or coords.shape[1] != 3
123
+ or len(coords) < 2
124
+ or not np.all(np.isfinite(coords))
125
+ ):
126
+ raise ValueError("component lobes need finite (V, 3) mask coordinates")
127
+ spacing = _grid_spacing(coords)
128
+ origin = coords.min(axis=0)
129
+ index = (coords - origin) / spacing
130
+ if not np.allclose(index, np.round(index), atol=1e-4, rtol=0):
131
+ raise ValueError(
132
+ "component mask coordinates must form a regular grid; "
133
+ "pass a NIfTI mask to preserve a rotated affine"
134
+ )
135
+ indices = np.round(index).astype(int)
136
+ shape = tuple(indices.max(axis=0) + 1)
137
+ affine = np.diag([*spacing, 1.0])
138
+ affine[:3, 3] = origin
139
+ if not len(indices):
140
+ raise ValueError("mask has no voxels")
141
+ if np.prod(shape) > 16_000_000:
142
+ raise ValueError(
143
+ "component mask bounding grid exceeds 16 million voxels; use a coarser mask"
144
+ )
145
+ return coords, indices, shape, affine
htfa/_validation.py ADDED
@@ -0,0 +1,13 @@
1
+ """Shared validation for real-valued numerical inputs."""
2
+
3
+ from typing import Any
4
+
5
+ import numpy as np
6
+ from numpy.typing import NDArray
7
+
8
+
9
+ def real_array(values: Any, name: str) -> NDArray[np.float64]:
10
+ """Convert to float64 without discarding an imaginary component."""
11
+ if np.iscomplexobj(values):
12
+ raise ValueError(f"{name} must be real-valued")
13
+ return np.asarray(values, dtype=np.float64)