tvboptim 0.2.9__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. {tvboptim-0.2.9/src/tvboptim.egg-info → tvboptim-0.3.0}/PKG-INFO +3 -2
  2. {tvboptim-0.2.9 → tvboptim-0.3.0}/README.md +1 -1
  3. {tvboptim-0.2.9 → tvboptim-0.3.0}/pyproject.toml +3 -1
  4. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/__init__.py +2 -2
  5. tvboptim-0.3.0/src/tvboptim/analysis/__init__.py +17 -0
  6. tvboptim-0.3.0/src/tvboptim/analysis/identifiability.py +530 -0
  7. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/data/__init__.py +6 -1
  8. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/data/functional/dk_average/data.npz +0 -0
  9. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/data/loaders.py +54 -0
  10. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/external_input/base.py +69 -0
  11. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/external_input/data.py +19 -0
  12. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/solve.py +70 -27
  13. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/solvers/__init__.py +2 -2
  14. tvboptim-0.3.0/src/tvboptim/experimental/network_dynamics/solvers/base.py +12 -0
  15. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/solvers/native.py +39 -8
  16. tvboptim-0.3.0/src/tvboptim/observations/__init__.py +19 -0
  17. tvboptim-0.3.0/src/tvboptim/observations/observation.py +136 -0
  18. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/observations/tvb_monitors/__init__.py +6 -1
  19. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/observations/tvb_monitors/bold.py +195 -23
  20. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/types/parameter.py +5 -1
  21. {tvboptim-0.2.9 → tvboptim-0.3.0/src/tvboptim.egg-info}/PKG-INFO +3 -2
  22. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim.egg-info/SOURCES.txt +3 -0
  23. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim.egg-info/requires.txt +1 -0
  24. tvboptim-0.3.0/tests/test_identifiability.py +359 -0
  25. tvboptim-0.2.9/src/tvboptim/experimental/network_dynamics/solvers/base.py +0 -46
  26. tvboptim-0.2.9/src/tvboptim/observations/__init__.py +0 -3
  27. tvboptim-0.2.9/src/tvboptim/observations/observation.py +0 -34
  28. {tvboptim-0.2.9 → tvboptim-0.3.0}/LICENSE +0 -0
  29. {tvboptim-0.2.9 → tvboptim-0.3.0}/setup.cfg +0 -0
  30. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/data/connectivity/dTOR/data.npz +0 -0
  31. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/data/connectivity/dk_average/data.npz +0 -0
  32. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/data/plotting/dk_average/aparc+aseg-mni_09c.nii.gz +0 -0
  33. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/data/plotting/dk_average/fs_default.txt +0 -0
  34. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/data/plotting/dk_average/fs_default_freesurfer_idx.csv +0 -0
  35. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/execution.py +0 -0
  36. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/__init__.py +0 -0
  37. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/__init__.py +0 -0
  38. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/analysis/__init__.py +0 -0
  39. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/analysis/lyapunov.py +0 -0
  40. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/core/__init__.py +0 -0
  41. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/core/bunch.py +0 -0
  42. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/core/network.py +0 -0
  43. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/coupling/__init__.py +0 -0
  44. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/coupling/base.py +0 -0
  45. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/coupling/linear.py +0 -0
  46. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/coupling/subspace.py +0 -0
  47. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/coupling/tvb.py +0 -0
  48. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/dynamics/__init__.py +0 -0
  49. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/dynamics/base.py +0 -0
  50. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/dynamics/lorenz.py +0 -0
  51. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py +0 -0
  52. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/coombes_byrne.py +0 -0
  53. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/epileptor.py +0 -0
  54. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/generic_2d_oscillator.py +0 -0
  55. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/jansen_rit.py +0 -0
  56. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/kuramoto.py +0 -0
  57. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/larter_breakspear.py +0 -0
  58. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/linear.py +0 -0
  59. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/montbrio_pazo_roxin.py +0 -0
  60. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/sup_hopf.py +0 -0
  61. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wilson_cowan.py +0 -0
  62. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang.py +0 -0
  63. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang_exc_inh.py +0 -0
  64. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/external_input/__init__.py +0 -0
  65. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/external_input/parametric.py +0 -0
  66. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/graph/__init__.py +0 -0
  67. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/graph/base.py +0 -0
  68. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/graph/sparse.py +0 -0
  69. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/graph/utils.py +0 -0
  70. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/noise/__init__.py +0 -0
  71. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/noise/base.py +0 -0
  72. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/noise/gaussian.py +0 -0
  73. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/result.py +0 -0
  74. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/solvers/diffrax.py +0 -0
  75. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/utils/__init__.py +0 -0
  76. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/utils/history.py +0 -0
  77. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/experimental/network_dynamics/utils/printer.py +0 -0
  78. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/observations/tvb_monitors/downsampling.py +0 -0
  79. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/optim/__init__.py +0 -0
  80. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/optim/callbacks.py +0 -0
  81. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/optim/optax.py +0 -0
  82. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/tvbo/__init__.py +0 -0
  83. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/tvbo/prepare_experiment.py +0 -0
  84. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/types/__init__.py +0 -0
  85. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/types/spaces.py +0 -0
  86. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/types/stateutils.py +0 -0
  87. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/utils/__init__.py +0 -0
  88. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/utils/caching.py +0 -0
  89. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim/utils/utils.py +0 -0
  90. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim.egg-info/dependency_links.txt +0 -0
  91. {tvboptim-0.2.9 → tvboptim-0.3.0}/src/tvboptim.egg-info/top_level.txt +0 -0
  92. {tvboptim-0.2.9 → tvboptim-0.3.0}/tests/test_execution.py +0 -0
  93. {tvboptim-0.2.9 → tvboptim-0.3.0}/tests/test_optax_optimizer_toy.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tvboptim
3
- Version: 0.2.9
3
+ Version: 0.3.0
4
4
  Summary: Optimization tools for The Virtual Brain
5
5
  Author-email: Marius Pille <marius.pille@bih-charite.de>
6
6
  License-Expression: EUPL-1.2
@@ -43,6 +43,7 @@ Requires-Dist: tvb-library; extra == "docs"
43
43
  Requires-Dist: jupyter-cache>=1.0.1; extra == "docs"
44
44
  Requires-Dist: nibabel; extra == "docs"
45
45
  Requires-Dist: nilearn; extra == "docs"
46
+ Requires-Dist: pymoo; extra == "docs"
46
47
  Requires-Dist: griffe<2.0.0; extra == "docs"
47
48
  Dynamic: license-file
48
49
 
@@ -146,4 +147,4 @@ If you use TVB-Optim in your research, please cite:
146
147
  }
147
148
  ```
148
149
 
149
- Copyright © 2025 Charité Universitätsmedizin Berlin
150
+ Copyright © 2026 Charité Universitätsmedizin Berlin
@@ -98,4 +98,4 @@ If you use TVB-Optim in your research, please cite:
98
98
  }
99
99
  ```
100
100
 
101
- Copyright © 2025 Charité Universitätsmedizin Berlin
101
+ Copyright © 2026 Charité Universitätsmedizin Berlin
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "tvboptim"
7
- version = "0.2.9"
7
+ version = "0.3.0"
8
8
  description = "Optimization tools for The Virtual Brain"
9
9
  readme = "README.md"
10
10
  authors = [
@@ -76,6 +76,7 @@ docs = [
76
76
  "jupyter-cache>=1.0.1",
77
77
  "nibabel",
78
78
  "nilearn",
79
+ "pymoo",
79
80
  "griffe<2.0.0"
80
81
  ]
81
82
 
@@ -95,6 +96,7 @@ docs = [
95
96
  "jupyter-cache>=1.0.1",
96
97
  "nibabel",
97
98
  "nilearn",
99
+ "pymoo",
98
100
  "griffe<2.0.0"
99
101
  ]
100
102
 
@@ -7,8 +7,8 @@ try:
7
7
  except Exception:
8
8
  __version__ = "unknown"
9
9
 
10
- from . import data
10
+ from . import analysis, data
11
11
  from .tvbo.prepare_experiment import HAS_TVBO, prepare
12
12
  from .types import parameter, spaces
13
13
 
14
- __all__ = ["spaces", "prepare", "HAS_TVBO", "parameter", "data"]
14
+ __all__ = ["spaces", "prepare", "HAS_TVBO", "parameter", "data", "analysis"]
@@ -0,0 +1,17 @@
1
+ """Analysis tools for tvboptim models and parameter estimates."""
2
+
3
+ from .identifiability import (
4
+ IdentifiabilityResult,
5
+ analyze_identifiability,
6
+ eigendecompose_curvature,
7
+ fisher_information,
8
+ loss_hessian,
9
+ )
10
+
11
+ __all__ = [
12
+ "IdentifiabilityResult",
13
+ "analyze_identifiability",
14
+ "eigendecompose_curvature",
15
+ "fisher_information",
16
+ "loss_hessian",
17
+ ]
@@ -0,0 +1,530 @@
1
+ """Local identifiability analysis for tvboptim parameter estimates.
2
+
3
+ The curvature of the loss around a fitted parameter point tells you which
4
+ parameter combinations the data actually constrains. A near-zero eigenvalue
5
+ of the loss Hessian (equivalently, of the Fisher information) marks a
6
+ *sloppy* direction: a combination of parameters that can be changed without
7
+ moving the loss -- i.e. a practically non-identifiable direction.
8
+
9
+ Two curvature objects are available:
10
+
11
+ * the **Hessian of the scalar loss** (:func:`loss_hessian`) -- needs only
12
+ the loss you already optimize;
13
+ * the **Gauss-Newton Fisher information** ``J^T J / sigma**2``
14
+ (:func:`fisher_information`) -- needs a vector-valued model output (the
15
+ residual / prediction before it is reduced to a scalar). It is always
16
+ positive semi-definite and is the object the Cramer-Rao bound refers to.
17
+
18
+ At a good fit the two nearly coincide. Either way the curvature is taken in
19
+ the same coordinates the optimizer works in -- the flattened ``Parameter``
20
+ leaves of a config -- so transformed parameters (``LogPositiveParameter``,
21
+ ``NormalizedParameter``, ...) are handled automatically: the spectrum comes
22
+ out in their stored (log / normalized) coordinates.
23
+
24
+ References
25
+ ----------
26
+ Gutenkunst et al. 2007, *PLoS Comput Biol* -- "Universally sloppy parameter
27
+ sensitivities in systems biology models" (the eigenspectrum / sloppiness
28
+ framework).
29
+ Raue et al. 2009, *Bioinformatics* -- profile likelihood and practical
30
+ identifiability.
31
+
32
+ Notes
33
+ -----
34
+ The Hessian eigenspectrum is a *local* diagnostic: it describes the basin
35
+ around the supplied point only. It reliably flags flat ridges (practical
36
+ non-identifiability), but it does **not** see disconnected alternative
37
+ optima (multimodality) -- use profile likelihood or posterior sampling for
38
+ that.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import warnings
44
+ from dataclasses import dataclass
45
+ from typing import Literal
46
+
47
+ import jax
48
+ import jax.numpy as jnp
49
+ import numpy as np
50
+ from jax.flatten_util import ravel_pytree
51
+
52
+ from tvboptim.types.parameter import is_parameter
53
+ from tvboptim.types.stateutils import combine_state, partition_state
54
+
55
+ _Kind = Literal["hessian", "fisher"]
56
+
57
+ __all__ = [
58
+ "IdentifiabilityResult",
59
+ "analyze_identifiability",
60
+ "eigendecompose_curvature",
61
+ "fisher_information",
62
+ "loss_hessian",
63
+ ]
64
+
65
+ _KIND_LABELS = {"hessian": "loss Hessian", "fisher": "Fisher information"}
66
+
67
+
68
+ # --------------------------------------------------------------------------
69
+ # Parameter-path labelling
70
+ # --------------------------------------------------------------------------
71
+ def _key_str(key) -> str:
72
+ """Render a single JAX pytree key as a plain string."""
73
+ for attr in ("key", "name", "idx"):
74
+ if hasattr(key, attr):
75
+ return str(getattr(key, attr))
76
+ return str(key)
77
+
78
+
79
+ def _path_str(path) -> str:
80
+ """Join a JAX pytree key path into a dotted string."""
81
+ return ".".join(_key_str(k) for k in path)
82
+
83
+
84
+ def _parameter_labels(diff_state) -> list[str]:
85
+ """One human-readable label per scalar entry of the flattened diff_state.
86
+
87
+ The order matches ``ravel_pytree(diff_state)``: parameters are visited in
88
+ pytree-traversal order, and an array-valued ``Parameter`` of size m
89
+ expands to m consecutive ``name[i]`` labels.
90
+ """
91
+ leaves_with_path, _ = jax.tree_util.tree_flatten_with_path(
92
+ diff_state, is_leaf=is_parameter
93
+ )
94
+ labels: list[str] = []
95
+ for path, param in leaves_with_path:
96
+ base = _path_str(path) or "param"
97
+ if param.size == 1:
98
+ labels.append(base)
99
+ else:
100
+ labels.extend(f"{base}[{i}]" for i in range(param.size))
101
+ return labels
102
+
103
+
104
+ def _flatten_state(state):
105
+ """Partition + ravel the Parameter leaves of a state.
106
+
107
+ Returns the pieces needed to plug callables into a flat-theta interface,
108
+ without committing to which callable will be wrapped. Use this when more
109
+ than one callable (e.g. both ``loss`` and ``model``) needs to share the
110
+ same flatten.
111
+
112
+ Returns
113
+ -------
114
+ theta0 : jnp.ndarray
115
+ The flattened current parameter values.
116
+ unravel : callable
117
+ Inverse of the flattening, reconstructing the diff_state pytree.
118
+ static_state : pytree
119
+ The non-Parameter pieces of ``state``.
120
+ labels : list[str]
121
+ Parameter name per entry of ``theta0``.
122
+ """
123
+ diff_state, static_state = partition_state(state)
124
+ theta0, unravel = ravel_pytree(diff_state)
125
+
126
+ if theta0.size == 0:
127
+ raise ValueError(
128
+ "No Parameter leaves found in `state`. Wrap the quantities you "
129
+ "want analysed in tvboptim.types.Parameter(...) before calling "
130
+ "an identifiability function."
131
+ )
132
+
133
+ labels = _parameter_labels(diff_state)
134
+ if len(labels) != theta0.size:
135
+ # Should not happen; guards against a label/flatten ordering drift.
136
+ raise RuntimeError(
137
+ f"Internal error: {len(labels)} labels for {theta0.size} "
138
+ "parameters. Please report this."
139
+ )
140
+ return theta0, unravel, static_state, labels
141
+
142
+
143
+ def _flatten_problem(fn, state):
144
+ """Convenience: flatten ``state`` and wrap ``fn`` to take a flat theta."""
145
+ theta0, unravel, static_state, labels = _flatten_state(state)
146
+
147
+ def fn_flat(theta):
148
+ return fn(combine_state(unravel(theta), static_state))
149
+
150
+ return fn_flat, theta0, unravel, labels
151
+
152
+
153
+ # --------------------------------------------------------------------------
154
+ # Result container
155
+ # --------------------------------------------------------------------------
156
+ @dataclass(eq=False)
157
+ class IdentifiabilityResult:
158
+ """Eigendecomposition of a loss-curvature matrix at a parameter point.
159
+
160
+ Attributes
161
+ ----------
162
+ eigenvalues : jnp.ndarray
163
+ Eigenvalues in ascending order. Small (near-zero) eigenvalues are
164
+ sloppy / non-identifiable directions; large eigenvalues are stiff /
165
+ well-constrained ones.
166
+ eigenvectors : jnp.ndarray
167
+ Eigenvectors as columns; ``eigenvectors[:, i]`` belongs to
168
+ ``eigenvalues[i]``. Each column is a unit-norm combination of the
169
+ parameters in ``labels``.
170
+ matrix : jnp.ndarray
171
+ The curvature matrix that was decomposed (loss Hessian or Fisher
172
+ information).
173
+ labels : list[str]
174
+ Parameter name per row/column of ``matrix``.
175
+ theta : jnp.ndarray
176
+ The flattened parameter point the curvature was evaluated at.
177
+ gradient_norm : float or None
178
+ L2 norm of the loss gradient at ``theta``. Only meaningful as a
179
+ check that ``theta`` is a genuine optimum.
180
+ kind : {"hessian", "fisher"}
181
+ Which curvature object ``matrix`` is.
182
+ """
183
+
184
+ eigenvalues: jnp.ndarray
185
+ eigenvectors: jnp.ndarray
186
+ matrix: jnp.ndarray
187
+ labels: list
188
+ theta: jnp.ndarray
189
+ gradient_norm: float | None = None
190
+ kind: _Kind = "hessian"
191
+
192
+ @property
193
+ def n_params(self) -> int:
194
+ return len(self.labels)
195
+
196
+ def condition_number(self) -> float:
197
+ """Ratio of largest to smallest |eigenvalue|. Large => ill-posed."""
198
+ a = jnp.abs(self.eigenvalues)
199
+ lo = float(a.min())
200
+ hi = float(a.max())
201
+ return float("inf") if lo == 0.0 else hi / lo
202
+
203
+ def rank(self, rtol: float = 1e-8) -> int:
204
+ """Number of eigenvalues above ``rtol * max|eigenvalue|``.
205
+
206
+ A rank below ``n_params`` means that many parameter combinations are
207
+ practically non-identifiable at this point.
208
+ """
209
+ a = jnp.abs(self.eigenvalues)
210
+ return int(jnp.sum(a > rtol * float(a.max())))
211
+
212
+ def _direction(self, idx: int) -> dict:
213
+ vec = np.asarray(self.eigenvectors[:, idx])
214
+ order = np.argsort(-np.abs(vec))
215
+ return {
216
+ "eigenvalue": float(self.eigenvalues[idx]),
217
+ "loadings": {self.labels[j]: float(vec[j]) for j in order},
218
+ }
219
+
220
+ def sloppy_directions(self, n: int = 3) -> list[dict]:
221
+ """The ``n`` flattest directions (smallest eigenvalues first).
222
+
223
+ Each entry is ``{"eigenvalue": float, "loadings": {label: coeff}}``
224
+ with loadings sorted by descending |coeff|.
225
+ """
226
+ n = min(n, self.n_params)
227
+ return [self._direction(i) for i in range(n)]
228
+
229
+ def stiff_directions(self, n: int = 3) -> list[dict]:
230
+ """The ``n`` stiffest directions (largest eigenvalues first)."""
231
+ n = min(n, self.n_params)
232
+ return [self._direction(self.n_params - 1 - i) for i in range(n)]
233
+
234
+ def summary(self) -> str:
235
+ """Human-readable one-screen report."""
236
+ label = _KIND_LABELS.get(self.kind, self.kind)
237
+ lines = [
238
+ f"Identifiability analysis -- {label} "
239
+ f"({self.n_params} parameters)",
240
+ "-" * 60,
241
+ ]
242
+ if self.gradient_norm is not None:
243
+ lines.append(f"gradient norm at point : {self.gradient_norm:.3e}")
244
+ lines += [
245
+ f"eigenvalue range : {float(self.eigenvalues.min()):.3e}"
246
+ f" ... {float(self.eigenvalues.max()):.3e}",
247
+ f"condition number : {self.condition_number():.3e}",
248
+ f"numerical rank (rtol=1e-8): {self.rank()} / {self.n_params}",
249
+ "",
250
+ "Flattest (least identifiable) direction:",
251
+ ]
252
+ d = self.sloppy_directions(1)[0]
253
+ lines.append(f" eigenvalue = {d['eigenvalue']:.3e}")
254
+ for lab, coeff in list(d["loadings"].items())[:5]:
255
+ lines.append(f" {lab:<28s} {coeff:+.4f}")
256
+ return "\n".join(lines)
257
+
258
+ def plot_spectrum(self, ax=None):
259
+ """Log-scale plot of |eigenvalues|, largest to smallest."""
260
+ import matplotlib.pyplot as plt
261
+
262
+ if ax is None:
263
+ _, ax = plt.subplots(figsize=(6, 4))
264
+ ev = np.sort(np.abs(np.asarray(self.eigenvalues)))[::-1]
265
+ ax.semilogy(np.arange(1, len(ev) + 1), ev, "o-")
266
+ ax.set_xlabel("eigenvalue index (stiff -> sloppy)")
267
+ ax.set_ylabel("|eigenvalue|")
268
+ ax.set_title(f"{_KIND_LABELS.get(self.kind, self.kind)} eigenspectrum")
269
+ ax.grid(True, which="both", alpha=0.3)
270
+ return ax
271
+
272
+ def __repr__(self) -> str:
273
+ return (
274
+ f"IdentifiabilityResult(kind={self.kind!r}, "
275
+ f"n_params={self.n_params}, "
276
+ f"rank={self.rank()}, "
277
+ f"condition_number={self.condition_number():.3e})"
278
+ )
279
+
280
+
281
+ # --------------------------------------------------------------------------
282
+ # Building blocks
283
+ # --------------------------------------------------------------------------
284
+ def _hessian_at(loss_flat, theta0):
285
+ """Symmetric dense Hessian of a flat-theta loss at ``theta0``."""
286
+ H = jax.hessian(loss_flat)(theta0)
287
+ return 0.5 * (H + H.T) # symmetrize against floating-point asymmetry
288
+
289
+
290
+ def _fisher_at(model_flat, theta0, sigma, mode: str = "auto"):
291
+ """Gauss-Newton Fisher information ``J^T J / sigma**2`` at ``theta0``.
292
+
293
+ Internal helper: ``model_flat`` must already take a 1-D theta and return
294
+ a JAX array (any shape). Used by both ``fisher_information`` and the
295
+ Fisher path of ``analyze_identifiability``.
296
+ """
297
+ n_params = theta0.size
298
+ out_shape = jax.eval_shape(model_flat, theta0).shape
299
+ n_obs = int(np.prod(out_shape, dtype=int))
300
+ if n_obs <= 1:
301
+ warnings.warn(
302
+ "`model` returns a scalar (or length-1) output. The Fisher "
303
+ "information will be rank-1 and uninformative -- pass the "
304
+ "vector-valued model output (residuals / predictions before the "
305
+ "reduction to a scalar loss).",
306
+ stacklevel=3,
307
+ )
308
+
309
+ if mode == "auto":
310
+ mode = "fwd" if n_params <= n_obs else "rev"
311
+ if mode == "fwd":
312
+ J = jax.jacfwd(model_flat)(theta0)
313
+ elif mode == "rev":
314
+ J = jax.jacrev(model_flat)(theta0)
315
+ else:
316
+ raise ValueError(f"Unknown mode {mode!r}, expected 'auto', 'fwd', 'rev'.")
317
+ J = jnp.reshape(J, (n_obs, n_params))
318
+
319
+ sig = jnp.asarray(sigma, dtype=J.dtype)
320
+ if sig.ndim == 0:
321
+ Jw = J / sig
322
+ elif sig.shape == (n_obs,):
323
+ Jw = J / sig[:, None]
324
+ else:
325
+ raise ValueError(
326
+ f"sigma must be a scalar or a 1-D array of length n_obs={n_obs} "
327
+ "(the flattened model output, in C-order — flatten yourself if "
328
+ f"`model(state)` is multi-dimensional). Got shape {sig.shape}."
329
+ )
330
+
331
+ return Jw.T @ Jw
332
+
333
+
334
+ def loss_hessian(loss, state, *, check_gradient: bool = True):
335
+ """Dense Hessian of a scalar loss w.r.t. the ``Parameter`` leaves of ``state``.
336
+
337
+ Parameters
338
+ ----------
339
+ loss : callable
340
+ ``loss(state) -> scalar``. Same contract as ``OptaxOptimizer``.
341
+ state : pytree
342
+ A config whose optimizable quantities are wrapped in ``Parameter``.
343
+ Pass the *fitted* config to analyse a found estimate.
344
+ check_gradient : bool, optional
345
+ Also compute the loss-gradient norm at the point (default True). It
346
+ is cheap and lets callers verify the point is a genuine optimum.
347
+
348
+ Returns
349
+ -------
350
+ H : jnp.ndarray
351
+ Symmetric ``(n_params, n_params)`` Hessian.
352
+ theta0 : jnp.ndarray
353
+ Flattened parameter values the Hessian was evaluated at.
354
+ labels : list[str]
355
+ Parameter name per row/column of ``H``.
356
+ grad_norm : float or None
357
+ L2 norm of the gradient at ``theta0`` (None if ``check_gradient`` is
358
+ False).
359
+ """
360
+ loss_flat, theta0, _, labels = _flatten_problem(loss, state)
361
+ H = _hessian_at(loss_flat, theta0)
362
+ grad_norm = None
363
+ if check_gradient:
364
+ grad_norm = float(jnp.linalg.norm(jax.grad(loss_flat)(theta0)))
365
+ return H, theta0, labels, grad_norm
366
+
367
+
368
+ def fisher_information(model, state, *, sigma=1.0, mode: str = "auto"):
369
+ """Gauss-Newton Fisher information ``J^T J / sigma**2`` from a vector model.
370
+
371
+ ``model`` returns the *vector-valued* output -- the residual or the raw
372
+ prediction, before the reduction to a scalar loss. ``J`` is the Jacobian
373
+ of that vector w.r.t. the ``Parameter`` leaves of ``state``; ``J^T J`` is
374
+ identical whether ``model`` returns the residual or the prediction.
375
+
376
+ Unlike the loss Hessian, this object is always positive semi-definite and
377
+ drops the noise-dependent residual-curvature term, so it stays meaningful
378
+ away from a perfect fit. It is the matrix whose inverse is the
379
+ Cramer-Rao lower bound on the parameter covariance.
380
+
381
+ Parameters
382
+ ----------
383
+ model : callable
384
+ ``model(state) -> array``. The pre-reduction model output. May be
385
+ multi-dimensional; it is flattened in C-order internally.
386
+ state : pytree
387
+ Config with optimizable quantities wrapped in ``Parameter``.
388
+ sigma : float or array, optional
389
+ Observation noise scale. Either a scalar, or a 1-D array of length
390
+ ``prod(model(state).shape)`` giving per-observation noise scales for
391
+ the model output flattened in C-order. If your model returns a
392
+ multi-D output, flatten ``sigma`` yourself to match. Default 1.0.
393
+ mode : {"auto", "fwd", "rev"}, optional
394
+ Jacobian mode. ``"auto"`` picks forward-mode when there are at most
395
+ as many parameters as observations, reverse-mode otherwise.
396
+
397
+ Returns
398
+ -------
399
+ FIM : jnp.ndarray
400
+ Symmetric ``(n_params, n_params)`` Fisher information matrix.
401
+ theta0 : jnp.ndarray
402
+ Flattened parameter values the FIM was evaluated at.
403
+ labels : list[str]
404
+ Parameter name per row/column of ``FIM``.
405
+ """
406
+ model_flat, theta0, _, labels = _flatten_problem(model, state)
407
+ FIM = _fisher_at(model_flat, theta0, sigma, mode=mode)
408
+ return FIM, theta0, labels
409
+
410
+
411
+ def eigendecompose_curvature(
412
+ matrix, labels, theta0, *, kind: _Kind, gradient_norm=None
413
+ ) -> IdentifiabilityResult:
414
+ """Eigendecompose a (symmetric) curvature matrix into an IdentifiabilityResult.
415
+
416
+ The matrix is assumed to be a loss Hessian or Fisher information matrix —
417
+ i.e. a *curvature* of a loss / log-likelihood in parameter space. The name
418
+ avoids the word "spectrum" because that overloads with frequency-domain
419
+ spectra in time-series and imaging contexts.
420
+
421
+ ``kind`` is required and not defaulted: passing a Fisher matrix with the
422
+ default ``"hessian"`` (or vice versa) would silently mislabel results
423
+ downstream in ``summary()`` / ``__repr__``.
424
+ """
425
+ if kind not in ("hessian", "fisher"):
426
+ raise ValueError(
427
+ f"`kind` must be 'hessian' or 'fisher', got {kind!r}."
428
+ )
429
+ matrix = jnp.asarray(matrix)
430
+ matrix = 0.5 * (matrix + matrix.T) # symmetrize against floating-point asymmetry
431
+ eigenvalues, eigenvectors = jnp.linalg.eigh(matrix)
432
+ return IdentifiabilityResult(
433
+ eigenvalues=eigenvalues,
434
+ eigenvectors=eigenvectors,
435
+ matrix=matrix,
436
+ labels=list(labels),
437
+ theta=jnp.asarray(theta0),
438
+ gradient_norm=gradient_norm,
439
+ kind=kind,
440
+ )
441
+
442
+
443
+ def analyze_identifiability(
444
+ loss,
445
+ state,
446
+ *,
447
+ model=None,
448
+ sigma=None,
449
+ check_gradient: bool = True,
450
+ warn_gradient_tol: float = 1e-3,
451
+ ) -> IdentifiabilityResult:
452
+ """End-to-end local identifiability analysis from a loss and a config.
453
+
454
+ Computes a curvature matrix at the parameter point encoded in ``state``,
455
+ eigendecomposes it, and returns an :class:`IdentifiabilityResult`.
456
+
457
+ With ``model=None`` (default) the curvature is the **Hessian of the
458
+ scalar loss** -- nothing beyond the loss you already optimize is needed.
459
+ Pass ``model`` to instead use the **Gauss-Newton Fisher information**
460
+ ``J^T J / sigma**2`` of a vector-valued model output; that object is
461
+ always positive semi-definite and is what the Cramer-Rao bound refers
462
+ to. ``loss`` is still used either way for the at-an-optimum check.
463
+
464
+ Parameters
465
+ ----------
466
+ loss : callable
467
+ ``loss(state) -> scalar``. Used for the gradient / optimum check,
468
+ and as the curvature source when ``model`` is None.
469
+ state : pytree
470
+ Fitted config with optimizable quantities wrapped in ``Parameter``.
471
+ model : callable, optional
472
+ ``model(state) -> array``: the pre-reduction model output. If given,
473
+ the Fisher information is used instead of the loss Hessian.
474
+ sigma : float or array, optional
475
+ Observation noise scale for the Fisher information. Only meaningful
476
+ with ``model`` set; passing a value while ``model`` is None emits a
477
+ warning (the loss-Hessian path does not use it). Defaults to 1.0
478
+ internally.
479
+ check_gradient : bool, optional
480
+ Compute the loss-gradient norm at the point (default True).
481
+ warn_gradient_tol : float, optional
482
+ If the gradient norm exceeds this, emit a warning -- the eigenspectrum
483
+ is only an identifiability diagnostic *at an optimum*. Default 1e-3.
484
+
485
+ Returns
486
+ -------
487
+ IdentifiabilityResult
488
+ """
489
+ if sigma is not None and model is None:
490
+ warnings.warn(
491
+ "`sigma` was passed but `model` is None, so the loss-Hessian "
492
+ "path is used and `sigma` is ignored. Pass a vector-valued "
493
+ "`model` to use the Fisher information.",
494
+ stacklevel=2,
495
+ )
496
+ sigma_eff = 1.0 if sigma is None else sigma
497
+
498
+ # Single flatten of state — shared between gradient check, loss-Hessian,
499
+ # and Fisher-information paths.
500
+ theta0, unravel, static_state, labels = _flatten_state(state)
501
+
502
+ def loss_flat(theta):
503
+ return loss(combine_state(unravel(theta), static_state))
504
+
505
+ grad_norm = None
506
+ if check_gradient:
507
+ grad_norm = float(jnp.linalg.norm(jax.grad(loss_flat)(theta0)))
508
+ if grad_norm > warn_gradient_tol:
509
+ warnings.warn(
510
+ f"Gradient norm at the supplied point is {grad_norm:.3e} "
511
+ f"(> {warn_gradient_tol:.0e}). The eigenspectrum is an "
512
+ "identifiability diagnostic only at a genuine optimum; away "
513
+ "from one it mixes curvature with slope. Re-fit, or pass a "
514
+ "larger warn_gradient_tol if this is intentional.",
515
+ stacklevel=2,
516
+ )
517
+
518
+ if model is None:
519
+ H = _hessian_at(loss_flat, theta0)
520
+ return eigendecompose_curvature(
521
+ H, labels, theta0, gradient_norm=grad_norm, kind="hessian"
522
+ )
523
+
524
+ def model_flat(theta):
525
+ return model(combine_state(unravel(theta), static_state))
526
+
527
+ FIM = _fisher_at(model_flat, theta0, sigma_eff)
528
+ return eigendecompose_curvature(
529
+ FIM, labels, theta0, gradient_norm=grad_norm, kind="fisher"
530
+ )
@@ -4,9 +4,14 @@ This module provides convenient access to built-in connectivity and
4
4
  functional connectivity datasets.
5
5
  """
6
6
 
7
- from .loaders import load_functional_connectivity, load_structural_connectivity
7
+ from .loaders import (
8
+ load_fcd_distribution,
9
+ load_functional_connectivity,
10
+ load_structural_connectivity,
11
+ )
8
12
 
9
13
  __all__ = [
10
14
  "load_structural_connectivity",
11
15
  "load_functional_connectivity",
16
+ "load_fcd_distribution",
12
17
  ]
@@ -103,3 +103,57 @@ def load_functional_connectivity(name: str = "dk_average") -> jnp.ndarray:
103
103
  fc = jnp.array(data["fc"])
104
104
 
105
105
  return fc
106
+
107
+
108
+ def load_fcd_distribution(
109
+ name: str = "dk_average",
110
+ ) -> Tuple[jnp.ndarray, jnp.ndarray]:
111
+ """
112
+ Load a typical empirical FCD value distribution.
113
+
114
+ Returns the histogram bin midpoints and a normalised density (integrates
115
+ to 1 over its support). Like the other example datasets shipped with
116
+ tvboptim, this is meant as a *qualitative* reference — a realistic FCD
117
+ shape to test, demo, and explore against — not as a calibrated benchmark.
118
+
119
+ The sliding-window parameters that produced the histogram are not
120
+ recorded. Pick a window/step for your simulated FCD that gives a
121
+ qualitatively comparable shape (Herzog et al. 2024 use a 30-sample
122
+ window with 2-sample step at TR = 1 s, which is a reasonable default).
123
+
124
+ Available datasets:
125
+ - "dk_average": FCD value histogram on Desikan-Killiany BOLD
126
+ (84 regions).
127
+
128
+ Args:
129
+ name: Dataset name (default: "dk_average")
130
+
131
+ Returns:
132
+ midpoints: Bin midpoints [n_bins]
133
+ density: Normalised density evaluated on `midpoints` [n_bins]
134
+
135
+ Examples:
136
+ >>> from tvboptim.data import load_fcd_distribution
137
+ >>> midpoints, density = load_fcd_distribution()
138
+ >>> print(midpoints.shape, density.shape)
139
+ (100,) (100,)
140
+ """
141
+ data_path = _DATA_DIR / "functional" / name / "data.npz"
142
+
143
+ if not data_path.exists():
144
+ raise ValueError(f"Dataset '{name}' not found. Available datasets: dk_average")
145
+
146
+ data = np.load(data_path, allow_pickle=True)
147
+ if "fcd_edges" not in data.files:
148
+ raise ValueError(
149
+ f"Dataset '{name}' has no FCD histogram. "
150
+ "Available datasets with FCD: dk_average"
151
+ )
152
+
153
+ edges = np.asarray(data["fcd_edges"])
154
+ hist = np.asarray(data["fcd_hist"])
155
+ midpoints = (edges[1:] + edges[:-1]) / 2
156
+ bin_width = float(edges[1] - edges[0])
157
+ density = hist / np.sum(hist) / bin_width
158
+
159
+ return jnp.array(midpoints), jnp.array(density)