tvboptim 0.3.0__tar.gz → 0.4.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 (99) hide show
  1. {tvboptim-0.3.0/src/tvboptim.egg-info → tvboptim-0.4.0}/PKG-INFO +8 -5
  2. {tvboptim-0.3.0 → tvboptim-0.4.0}/README.md +3 -2
  3. {tvboptim-0.3.0 → tvboptim-0.4.0}/pyproject.toml +13 -3
  4. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/analysis/identifiability.py +2 -5
  5. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/execution.py +6 -3
  6. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/__init__.py +2 -0
  7. tvboptim-0.4.0/src/tvboptim/experimental/network_dynamics/analysis/__init__.py +9 -0
  8. tvboptim-0.4.0/src/tvboptim/experimental/network_dynamics/analysis/adiabatic_scan.py +183 -0
  9. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/analysis/lyapunov.py +18 -4
  10. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/core/bunch.py +12 -2
  11. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/core/network.py +60 -10
  12. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/coupling/__init__.py +3 -0
  13. tvboptim-0.4.0/src/tvboptim/experimental/network_dynamics/coupling/base.py +1319 -0
  14. tvboptim-0.4.0/src/tvboptim/experimental/network_dynamics/coupling/kuramoto.py +159 -0
  15. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/coupling/linear.py +44 -56
  16. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/coupling/subspace.py +60 -15
  17. tvboptim-0.4.0/src/tvboptim/experimental/network_dynamics/coupling/transport.py +65 -0
  18. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/coupling/tvb.py +8 -16
  19. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/external_input/base.py +3 -1
  20. tvboptim-0.4.0/src/tvboptim/experimental/network_dynamics/graph/__init__.py +26 -0
  21. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/graph/base.py +428 -29
  22. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/graph/sparse.py +338 -231
  23. tvboptim-0.4.0/src/tvboptim/experimental/network_dynamics/graph/topology.py +159 -0
  24. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/solve.py +544 -152
  25. tvboptim-0.4.0/src/tvboptim/experimental/network_dynamics/solvers/base.py +31 -0
  26. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/solvers/native.py +106 -34
  27. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/utils/history.py +6 -3
  28. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/observations/__init__.py +2 -0
  29. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/observations/observation.py +51 -0
  30. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/observations/tvb_monitors/__init__.py +5 -0
  31. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/observations/tvb_monitors/bold.py +128 -24
  32. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/optim/callbacks.py +6 -14
  33. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/types/parameter.py +48 -20
  34. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/types/spaces.py +67 -0
  35. tvboptim-0.4.0/src/tvboptim/utils/caching.py +159 -0
  36. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/utils/utils.py +27 -0
  37. {tvboptim-0.3.0 → tvboptim-0.4.0/src/tvboptim.egg-info}/PKG-INFO +8 -5
  38. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim.egg-info/SOURCES.txt +4 -0
  39. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim.egg-info/requires.txt +2 -2
  40. {tvboptim-0.3.0 → tvboptim-0.4.0}/tests/test_identifiability.py +6 -11
  41. tvboptim-0.3.0/src/tvboptim/experimental/network_dynamics/analysis/__init__.py +0 -3
  42. tvboptim-0.3.0/src/tvboptim/experimental/network_dynamics/coupling/base.py +0 -1057
  43. tvboptim-0.3.0/src/tvboptim/experimental/network_dynamics/graph/__init__.py +0 -14
  44. tvboptim-0.3.0/src/tvboptim/experimental/network_dynamics/solvers/base.py +0 -12
  45. tvboptim-0.3.0/src/tvboptim/utils/caching.py +0 -82
  46. {tvboptim-0.3.0 → tvboptim-0.4.0}/LICENSE +0 -0
  47. {tvboptim-0.3.0 → tvboptim-0.4.0}/setup.cfg +0 -0
  48. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/__init__.py +0 -0
  49. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/analysis/__init__.py +0 -0
  50. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/data/__init__.py +0 -0
  51. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/data/connectivity/dTOR/data.npz +0 -0
  52. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/data/connectivity/dk_average/data.npz +0 -0
  53. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/data/functional/dk_average/data.npz +0 -0
  54. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/data/loaders.py +0 -0
  55. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/data/plotting/dk_average/aparc+aseg-mni_09c.nii.gz +0 -0
  56. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/data/plotting/dk_average/fs_default.txt +0 -0
  57. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/data/plotting/dk_average/fs_default_freesurfer_idx.csv +0 -0
  58. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/__init__.py +0 -0
  59. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/core/__init__.py +0 -0
  60. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/dynamics/__init__.py +0 -0
  61. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/dynamics/base.py +0 -0
  62. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/dynamics/lorenz.py +0 -0
  63. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py +0 -0
  64. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/coombes_byrne.py +0 -0
  65. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/epileptor.py +0 -0
  66. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/generic_2d_oscillator.py +0 -0
  67. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/jansen_rit.py +0 -0
  68. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/kuramoto.py +0 -0
  69. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/larter_breakspear.py +0 -0
  70. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/linear.py +0 -0
  71. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/montbrio_pazo_roxin.py +0 -0
  72. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/sup_hopf.py +0 -0
  73. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wilson_cowan.py +0 -0
  74. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang.py +0 -0
  75. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang_exc_inh.py +0 -0
  76. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/external_input/__init__.py +0 -0
  77. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/external_input/data.py +0 -0
  78. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/external_input/parametric.py +0 -0
  79. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/graph/utils.py +0 -0
  80. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/noise/__init__.py +0 -0
  81. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/noise/base.py +0 -0
  82. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/noise/gaussian.py +0 -0
  83. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/result.py +0 -0
  84. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/solvers/__init__.py +0 -0
  85. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/solvers/diffrax.py +0 -0
  86. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/utils/__init__.py +0 -0
  87. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/experimental/network_dynamics/utils/printer.py +0 -0
  88. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/observations/tvb_monitors/downsampling.py +0 -0
  89. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/optim/__init__.py +0 -0
  90. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/optim/optax.py +0 -0
  91. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/tvbo/__init__.py +0 -0
  92. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/tvbo/prepare_experiment.py +0 -0
  93. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/types/__init__.py +0 -0
  94. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/types/stateutils.py +0 -0
  95. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim/utils/__init__.py +0 -0
  96. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim.egg-info/dependency_links.txt +0 -0
  97. {tvboptim-0.3.0 → tvboptim-0.4.0}/src/tvboptim.egg-info/top_level.txt +0 -0
  98. {tvboptim-0.3.0 → tvboptim-0.4.0}/tests/test_execution.py +0 -0
  99. {tvboptim-0.3.0 → tvboptim-0.4.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.3.0
3
+ Version: 0.4.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
@@ -14,6 +14,8 @@ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
14
14
  Classifier: Programming Language :: Python :: 3
15
15
  Classifier: Programming Language :: Python :: 3.11
16
16
  Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
17
19
  Classifier: Operating System :: OS Independent
18
20
  Requires-Python: >=3.11
19
21
  Description-Content-Type: text/markdown
@@ -23,11 +25,11 @@ Requires-Dist: optimistix
23
25
  Requires-Dist: matplotlib
24
26
  Requires-Dist: numpy
25
27
  Requires-Dist: pandas
26
- Requires-Dist: jax<0.10
28
+ Requires-Dist: jax
27
29
  Requires-Dist: equinox
28
30
  Requires-Dist: dill
29
31
  Requires-Dist: tqdm
30
- Requires-Dist: numpyro>=0.20.1
32
+ Requires-Dist: numpyro>=0.21.0
31
33
  Requires-Dist: diffrax
32
34
  Requires-Dist: plum-dispatch
33
35
  Provides-Extra: dev
@@ -53,8 +55,8 @@ Dynamic: license-file
53
55
 
54
56
  # TVB-Optim
55
57
 
58
+ <!-- [![Ruff](https://github.com/virtual-twin/tvboptim/actions/workflows/ruff.yml/badge.svg)](https://github.com/virtual-twin/tvboptim/actions/workflows/ruff.yml) -->
56
59
  [![Tests](https://github.com/virtual-twin/tvboptim/actions/workflows/python-package.yml/badge.svg)](https://github.com/virtual-twin/tvboptim/actions/workflows/python-package.yml)
57
- [![Ruff](https://github.com/virtual-twin/tvboptim/actions/workflows/ruff.yml/badge.svg)](https://github.com/virtual-twin/tvboptim/actions/workflows/ruff.yml)
58
60
  [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
59
61
  [![PyPI version](https://img.shields.io/pypi/v/tvboptim.svg)](https://pypi.org/project/tvboptim/)
60
62
  [![Documentation](https://img.shields.io/badge/docs-online-brightgreen.svg)](https://virtual-twin.github.io/tvboptim)
@@ -93,12 +95,13 @@ from tvboptim.experimental.network_dynamics.graph import DenseDelayGraph
93
95
  from tvboptim.observations.tvb_monitors import Bold
94
96
  from tvboptim.observations import compute_fc, rmse
95
97
  from tvboptim.optim import OptaxOptimizer
98
+ from tvboptim.types import Parameter
96
99
  import optax
97
100
 
98
101
  # Build brain network model
99
102
  network = Network(
100
103
  dynamics=ReducedWongWang(),
101
- coupling={'delayed': LinearCoupling(incoming_states="S", G=0.5)},
104
+ coupling={'delayed': LinearCoupling(incoming_states="S", G=Parameter(0.5))},
102
105
  graph=DenseDelayGraph(weights, delays)
103
106
  )
104
107
 
@@ -4,8 +4,8 @@
4
4
 
5
5
  # TVB-Optim
6
6
 
7
+ <!-- [![Ruff](https://github.com/virtual-twin/tvboptim/actions/workflows/ruff.yml/badge.svg)](https://github.com/virtual-twin/tvboptim/actions/workflows/ruff.yml) -->
7
8
  [![Tests](https://github.com/virtual-twin/tvboptim/actions/workflows/python-package.yml/badge.svg)](https://github.com/virtual-twin/tvboptim/actions/workflows/python-package.yml)
8
- [![Ruff](https://github.com/virtual-twin/tvboptim/actions/workflows/ruff.yml/badge.svg)](https://github.com/virtual-twin/tvboptim/actions/workflows/ruff.yml)
9
9
  [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
10
10
  [![PyPI version](https://img.shields.io/pypi/v/tvboptim.svg)](https://pypi.org/project/tvboptim/)
11
11
  [![Documentation](https://img.shields.io/badge/docs-online-brightgreen.svg)](https://virtual-twin.github.io/tvboptim)
@@ -44,12 +44,13 @@ from tvboptim.experimental.network_dynamics.graph import DenseDelayGraph
44
44
  from tvboptim.observations.tvb_monitors import Bold
45
45
  from tvboptim.observations import compute_fc, rmse
46
46
  from tvboptim.optim import OptaxOptimizer
47
+ from tvboptim.types import Parameter
47
48
  import optax
48
49
 
49
50
  # Build brain network model
50
51
  network = Network(
51
52
  dynamics=ReducedWongWang(),
52
- coupling={'delayed': LinearCoupling(incoming_states="S", G=0.5)},
53
+ coupling={'delayed': LinearCoupling(incoming_states="S", G=Parameter(0.5))},
53
54
  graph=DenseDelayGraph(weights, delays)
54
55
  )
55
56
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "tvboptim"
7
- version = "0.3.0"
7
+ version = "0.4.0"
8
8
  description = "Optimization tools for The Virtual Brain"
9
9
  readme = "README.md"
10
10
  authors = [
@@ -21,6 +21,8 @@ classifiers = [
21
21
  "Programming Language :: Python :: 3",
22
22
  "Programming Language :: Python :: 3.11",
23
23
  "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Programming Language :: Python :: 3.14",
24
26
  "Operating System :: OS Independent",
25
27
  ]
26
28
  requires-python = ">=3.11"
@@ -30,11 +32,11 @@ dependencies = [
30
32
  "matplotlib",
31
33
  "numpy",
32
34
  "pandas",
33
- "jax<0.10", # numpyro<=0.20.1 imports jax.extend.core.primitives.xla_pmap_p, removed in jax 0.10. Drop cap once numpyro releases a fix.
35
+ "jax",
34
36
  "equinox",
35
37
  "dill",
36
38
  "tqdm",
37
- "numpyro>=0.20.1",
39
+ "numpyro>=0.21.0",
38
40
  "diffrax",
39
41
  "plum-dispatch",
40
42
  ]
@@ -100,6 +102,14 @@ docs = [
100
102
  "griffe<2.0.0"
101
103
  ]
102
104
 
105
+ [tool.uv]
106
+ # tvb-library depends on numba without an upper or lower bound, so a fresh
107
+ # resolution can backtrack numba down to 0.53.1 (-> llvmlite 0.36.0), which
108
+ # only builds on Python <3.10 and breaks CI on the >=3.11 matrix. Floor numba
109
+ # at a version that ships wheels for our supported Pythons. Constraints only
110
+ # bound transitively-pulled packages; they do not add a direct dependency.
111
+ constraint-dependencies = ["numba>=0.61", "llvmlite>=0.44"]
112
+
103
113
  [tool.ruff]
104
114
  line-length = 88
105
115
  target-version = "py311"
@@ -235,8 +235,7 @@ class IdentifiabilityResult:
235
235
  """Human-readable one-screen report."""
236
236
  label = _KIND_LABELS.get(self.kind, self.kind)
237
237
  lines = [
238
- f"Identifiability analysis -- {label} "
239
- f"({self.n_params} parameters)",
238
+ f"Identifiability analysis -- {label} ({self.n_params} parameters)",
240
239
  "-" * 60,
241
240
  ]
242
241
  if self.gradient_norm is not None:
@@ -423,9 +422,7 @@ def eigendecompose_curvature(
423
422
  downstream in ``summary()`` / ``__repr__``.
424
423
  """
425
424
  if kind not in ("hessian", "fisher"):
426
- raise ValueError(
427
- f"`kind` must be 'hessian' or 'fisher', got {kind!r}."
428
- )
425
+ raise ValueError(f"`kind` must be 'hessian' or 'fisher', got {kind!r}.")
429
426
  matrix = jnp.asarray(matrix)
430
427
  matrix = 0.5 * (matrix + matrix.T) # symmetrize against floating-point asymmetry
431
428
  eigenvalues, eigenvectors = jnp.linalg.eigh(matrix)
@@ -224,13 +224,16 @@ class ParallelExecution(Execution):
224
224
  self.n_pmap = n_pmap
225
225
  self.args = args
226
226
  self.kwargs = kwargs
227
- diff_state, static_state = space.collect(n_pmap=n_pmap, combine=False)
227
+ diff_state, axis_tree_def, static_state = space._collect_mapping_inputs(
228
+ n_pmap=n_pmap
229
+ )
228
230
 
229
231
  self.diff_state = diff_state
230
232
 
231
233
  # kwargs args probably go directly into model
232
- def _model(d):
233
- state = combine_state(d, static_state)
234
+ def _model(axis_values):
235
+ axis_state = jax.tree.unflatten(axis_tree_def, axis_values)
236
+ state = combine_state(axis_state, static_state)
234
237
  return model(state, *self.args, **self.kwargs)
235
238
 
236
239
  def map_model(d):
@@ -8,6 +8,7 @@ from .graph import (
8
8
  DelayGraph,
9
9
  DenseDelayGraph,
10
10
  DenseGraph,
11
+ DenseLengthGraph,
11
12
  Graph,
12
13
  SparseDelayGraph,
13
14
  SparseGraph,
@@ -22,6 +23,7 @@ __all__ = [
22
23
  "SparseDelayGraph",
23
24
  "DenseGraph",
24
25
  "DenseDelayGraph",
26
+ "DenseLengthGraph",
25
27
  "solve",
26
28
  "prepare",
27
29
  "Network",
@@ -0,0 +1,9 @@
1
+ from .adiabatic_scan import AdiabaticScanResult, adiabatic_scan
2
+ from .lyapunov import lyapunov, lyapunov_spectrum
3
+
4
+ __all__ = [
5
+ "lyapunov",
6
+ "lyapunov_spectrum",
7
+ "adiabatic_scan",
8
+ "AdiabaticScanResult",
9
+ ]
@@ -0,0 +1,183 @@
1
+ """Adiabatic parameter scan: a network bifurcation diagram.
2
+
3
+ Slowly ramp one parameter from ``low`` to ``high`` (and optionally back down to
4
+ catch hysteresis), carrying the settled state forward between steps, and record
5
+ summary statistics of an observed network signal at each value. This traces a
6
+ bifurcation-diagram-like picture of how the network's activity changes with the
7
+ swept parameter.
8
+
9
+ The swept parameter is addressed with a lens ``accessor`` applied through
10
+ ``eqx.tree_at`` (e.g. ``lambda c: c.coupling.instant.G``), so any nested config
11
+ field can be scanned without the function knowing its name.
12
+ """
13
+
14
+ from dataclasses import dataclass
15
+ from typing import Callable, Dict
16
+
17
+ import equinox as eqx
18
+ import jax
19
+ import jax.numpy as jnp
20
+ import numpy as np
21
+
22
+ from .. import prepare
23
+ from ..core.bunch import Bunch
24
+ from ..solvers import Heun
25
+
26
+
27
+ @dataclass
28
+ class AdiabaticScanResult:
29
+ """Result of an :func:`adiabatic_scan`.
30
+
31
+ Attributes
32
+ ----------
33
+ p : jax.Array
34
+ The swept parameter values, in scan order. Length ``2*n`` when
35
+ ``bothways`` (up then down), else ``n``.
36
+ n_up : int
37
+ Number of values in the ascending branch. ``p[:n_up]`` is the up-branch
38
+ and ``p[n_up:]`` the down-branch.
39
+ stats : Bunch of str -> jax.Array
40
+ One array per recorded statistic, stacked along the scan axis and
41
+ reachable by attribute (``stats.mean``) or key (``stats["mean"]``).
42
+ Shape is ``[len(p)]`` for scalar reducers and ``[len(p), ...]`` for
43
+ vector-valued reducers (e.g. ``[len(p), n_nodes]`` for a per-node
44
+ statistic).
45
+ """
46
+
47
+ p: jax.Array
48
+ n_up: int
49
+ stats: Bunch
50
+
51
+
52
+ def _default_observe(result):
53
+ """Observe the first variable across all nodes -> [n_time, n_nodes]."""
54
+ return result.ys[:, 0, :]
55
+
56
+
57
+ def _network_mean(arr):
58
+ """Mean over time per node, then averaged across nodes."""
59
+ return jnp.mean(arr, axis=0).mean()
60
+
61
+
62
+ def _network_min(arr):
63
+ """Mean over time per node, then the minimum across nodes."""
64
+ return jnp.mean(arr, axis=0).min()
65
+
66
+
67
+ def _network_max(arr):
68
+ """Mean over time per node, then the maximum across nodes."""
69
+ return jnp.mean(arr, axis=0).max()
70
+
71
+
72
+ _DEFAULT_STATISTICS = {
73
+ "mean": _network_mean,
74
+ "min": _network_min,
75
+ "max": _network_max,
76
+ }
77
+
78
+
79
+ def adiabatic_scan(
80
+ network,
81
+ solver=None,
82
+ *,
83
+ accessor: Callable,
84
+ low: float,
85
+ high: float,
86
+ n: int,
87
+ t: float = 2000.0,
88
+ skip: float = 1000.0,
89
+ dt: float = 1.0,
90
+ t0: float = 0.0,
91
+ bothways: bool = True,
92
+ observe: Callable = None,
93
+ statistics: Dict[str, Callable] = None,
94
+ ) -> AdiabaticScanResult:
95
+ """Ramp one parameter and record network statistics (bifurcation diagram).
96
+
97
+ Parameters
98
+ ----------
99
+ network : Network
100
+ solver : solver instance, optional (default: Heun())
101
+ accessor : callable
102
+ Lens onto the swept leaf, used as ``eqx.tree_at(accessor, config, value)``.
103
+ Example: ``lambda c: c.coupling.instant.G``.
104
+ low, high : float
105
+ Bounds of the swept parameter.
106
+ n : int
107
+ Number of values per branch.
108
+ t : float
109
+ Simulation duration per step in ms.
110
+ skip : float
111
+ Transient duration in ms discarded before computing statistics.
112
+ dt : float
113
+ Integration timestep in ms.
114
+ t0 : float
115
+ Simulation start time.
116
+ bothways : bool
117
+ If True, scan up then back down to expose hysteresis.
118
+ observe : callable, optional
119
+ ``result -> [n_time, n_nodes]`` signal to summarise. Defaults to the
120
+ first variable across all nodes.
121
+ statistics : dict of str -> callable, optional
122
+ Maps a name to a reducer ``[n_time, n_nodes] -> scalar or array``.
123
+ Vector-valued reducers (e.g. a per-node ``[n_nodes]`` statistic) are
124
+ supported as long as the output shape is the same at every scan point.
125
+ Defaults to mean/min/max of the per-node temporal mean across the
126
+ network.
127
+
128
+ Returns
129
+ -------
130
+ AdiabaticScanResult
131
+
132
+ Notes
133
+ -----
134
+ The settled state is carried forward between steps (the slow, adiabatic
135
+ ramp). For networks with delayed coupling the delay history buffer is not
136
+ carried, so this is only exact for instantaneous (non-delayed) coupling.
137
+ """
138
+ if solver is None:
139
+ solver = Heun()
140
+ if observe is None:
141
+ observe = _default_observe
142
+ if statistics is None:
143
+ statistics = _DEFAULT_STATISTICS
144
+
145
+ solve_fn, config = prepare(network, solver, t0=t0, t1=t0 + t, dt=dt)
146
+
147
+ p_up = jnp.linspace(low, high, n)
148
+ if bothways:
149
+ p = jnp.concatenate([p_up, p_up[::-1]])
150
+ else:
151
+ p = p_up
152
+
153
+ n_states = config.initial_state.dynamics.shape[0]
154
+ init_state = config.initial_state.dynamics
155
+
156
+ # The save grid is deterministic in (t0, t1, dt), so the post-transient
157
+ # window is the same at every step. Resolve it once to static integer
158
+ # indices (a host-side computation) so the scan body has no data-dependent
159
+ # shapes and stays jittable.
160
+ probe_ts = np.asarray(solve_fn(config).ts)
161
+ keep = jnp.asarray(np.flatnonzero(probe_ts > (t0 + skip)))
162
+
163
+ def step(state, value):
164
+ cfg = eqx.tree_at(accessor, config, value)
165
+ cfg = eqx.tree_at(lambda c: c.initial_state.dynamics, cfg, state)
166
+ result = solve_fn(cfg)
167
+
168
+ # statistics over the post-transient window. Reducer outputs stay on the
169
+ # JAX side; lax.scan stacks them along the scan axis, so array-valued
170
+ # reducers like a per-node median ([n_nodes]) are supported.
171
+ arr = observe(result)[keep]
172
+ outs = {name: fn(arr) for name, fn in statistics.items()}
173
+
174
+ # carry the settled state forward (the slow, adiabatic ramp)
175
+ new_state = result.ys[-1][:n_states]
176
+ return new_state, outs
177
+
178
+ # The whole sweep is one jitted scan: a single XLA compilation, the carry
179
+ # expressed natively, and the function is vmap-able over a batch of `p`
180
+ # arrays to explore several ranges in parallel.
181
+ _, stacked = jax.jit(lambda s, ps: jax.lax.scan(step, s, ps))(init_state, p)
182
+
183
+ return AdiabaticScanResult(p=p, n_up=n, stats=Bunch(stacked))
@@ -30,10 +30,15 @@ def lyapunov(network, solver=None, t=1000.0, n=10, d0=1e-9, dt=0.1, t0=0.0):
30
30
 
31
31
  Notes
32
32
  -----
33
- For networks with delayed coupling the delay history is held fixed
34
- across segments (good approximation when t >> max_delay). Run a
35
- warmup via network.update_history(result) before calling this
36
- function to initialise the delay buffer from a settled trajectory.
33
+ For delayed coupling the history buffer is held fixed across segments
34
+ (each rescaling step re-seeds only the point state), so the result is a
35
+ good approximation only when t >> max_delay, not exact. The two-trajectory
36
+ method is the natural route to a delay-correct MLE -- each trajectory
37
+ evolves its own history, so no explicit history-space tangents are needed --
38
+ but that needs carrying the full final state (point + history) across
39
+ segments, or running unsegmented. Run a warmup via
40
+ network.update_history(result) first to initialise the delay buffer from a
41
+ settled trajectory.
37
42
  """
38
43
  if solver is None:
39
44
  solver = Heun()
@@ -95,6 +100,15 @@ def lyapunov_spectrum(
95
100
  Returns
96
101
  -------
97
102
  jnp.ndarray — top k Lyapunov exponents sorted descending (1/ms)
103
+
104
+ Notes
105
+ -----
106
+ Exact for instantaneous (non-delayed) coupling only. Both modes propagate a
107
+ *point* state (perturb/linearize only ``initial_state.dynamics``) and reset
108
+ the delay history buffer each rescaling step, so for delayed coupling the
109
+ history is held fixed across segments: a good approximation only when
110
+ ``t >> max_delay``, not the true DDE spectrum (which would need tangents
111
+ spanning the augmented history-buffer state).
98
112
  """
99
113
  if solver is None:
100
114
  solver = Heun()
@@ -46,8 +46,18 @@ class Bunch(dict):
46
46
  return f"{self.__class__.__name__}({items})"
47
47
 
48
48
  def copy(self) -> "Bunch":
49
- """Create a shallow copy of the Bunch."""
50
- return Bunch(super().copy())
49
+ """Structurally copy this Bunch and any nested PyTree containers.
50
+
51
+ Rebuilds every container (nested Bunch, graph object, ...) so
52
+ mutating the copy -- including plain attribute assignment like
53
+ `cfg.graph.delays = x` -- does not leak back into the original.
54
+ Leaves (arrays, scalars, PRNG keys) are immutable in JAX, so
55
+ sharing them is safe and avoids duplicating large arrays (graph
56
+ weights, history buffers, pre-sampled noise tensors). Same
57
+ operation as solve.py's `_snapshot`, exposed here as `.copy()` so
58
+ it works for ad-hoc config mutation outside prepare().
59
+ """
60
+ return jax.tree.map(lambda x: x, self)
51
61
 
52
62
 
53
63
  # Register Bunch as a JAX PyTree with named keys so that
@@ -11,7 +11,8 @@ import jax.numpy as jnp
11
11
 
12
12
  from ..coupling.base import AbstractCoupling
13
13
  from ..dynamics.base import AbstractDynamics
14
- from ..graph.base import AbstractGraph
14
+ from ..graph.base import AbstractGraph, delay_steps_bound, effective_max_delay
15
+ from ..graph.topology import prepare_graph_topology, validate_graph_topology
15
16
  from ..noise.base import AbstractNoise
16
17
  from ..result import NativeSolution
17
18
  from .bunch import Bunch
@@ -100,8 +101,12 @@ class Network:
100
101
 
101
102
  self.externals = self._normalize_external_inputs(external_input or {}, dynamics)
102
103
 
103
- # Extract max_delay from graph (0.0 for non-DelayGraph)
104
- self.max_delay = getattr(graph, "max_delay", 0.0)
104
+ # Extract max_delay from graph (0.0 for non-DelayGraph). Prefers a
105
+ # declared max_delay_bound over the actual max(delays), matching the
106
+ # coupling's own buffer sizing (coupling/base.py prepare()), so
107
+ # history is padded to the same length delays may be raised to
108
+ # within the bound during a sweep.
109
+ self.max_delay = effective_max_delay(graph)
105
110
 
106
111
  # Resolve noise state indices if noise provided
107
112
  if self.noise is not None:
@@ -318,7 +323,16 @@ class Network:
318
323
  variable_names=state_names,
319
324
  )
320
325
 
321
- def prepare(self, dt: float, t0: float, t1: float) -> tuple[Bunch, Bunch]:
326
+ def prepare(
327
+ self,
328
+ dt: float,
329
+ t0: float,
330
+ t1: float,
331
+ *,
332
+ stage_time_centroid: float = 0.0,
333
+ recompute_coupling_per_stage: bool = False,
334
+ _prepared_topology=None,
335
+ ) -> tuple[Bunch, Bunch]:
322
336
  """Prepare all couplings for simulation.
323
337
 
324
338
  Calls prepare() on each coupling to get coupling_data and coupling_state.
@@ -327,6 +341,20 @@ class Network:
327
341
  dt: Integration timestep
328
342
  t0: Simulation start time
329
343
  t1: Simulation end time
344
+ stage_time_centroid: The solver's ``sum_i b_i * c_i`` (see
345
+ AbstractSolver). DelayedCoupling.precompute() reads it to undo
346
+ the delay bias introduced by freezing the coupling across
347
+ solver stages. The default 0.0 means "step-start evaluation",
348
+ i.e. no shift.
349
+ recompute_coupling_per_stage: The solver's flag of the same name.
350
+ DelayedCoupling.precompute() needs it to decide whether the
351
+ stage-time shift is safe to apply (it is not, on its own, for a
352
+ coupling that also reads a frozen local state).
353
+
354
+ Both are written into every coupling_data *after* coupling.prepare()
355
+ returns, rather than passed down into it, so that couplings overriding
356
+ prepare() with the historical (network, dt, t0, t1) signature keep
357
+ working unchanged.
330
358
 
331
359
  Returns:
332
360
  coupling_data_dict: Bunch {name: coupling_data_bunch}
@@ -336,9 +364,17 @@ class Network:
336
364
  """
337
365
  coupling_data_dict = Bunch()
338
366
  coupling_state_dict = Bunch()
367
+ prepared_topology = (
368
+ prepare_graph_topology(self.graph)
369
+ if _prepared_topology is None
370
+ else _prepared_topology
371
+ )
339
372
 
340
373
  for name, coupling in self.coupling.items():
341
374
  data, state = coupling.prepare(self, dt, t0, t1)
375
+ data._prepared_topology = prepared_topology
376
+ data.stage_time_centroid = stage_time_centroid
377
+ data.recompute_coupling_per_stage = recompute_coupling_per_stage
342
378
  coupling_data_dict[name] = data
343
379
  coupling_state_dict[name] = state
344
380
 
@@ -380,16 +416,27 @@ class Network:
380
416
  Args:
381
417
  t: Current time
382
418
  state: Current network state [n_states, n_nodes]
383
- coupling_data_dict: Precomputed coupling data from prepare()
419
+ coupling_data_dict: Coupling data from prepare()
384
420
  coupling_state_dict: Current coupling internal states
385
421
 
386
422
  Returns:
387
423
  coupling_inputs: Bunch {name: array[n_dims, n_nodes]}
388
424
  Named coupling inputs ready for dynamics.dynamics()
389
425
  Missing couplings automatically filled with zeros
426
+
427
+ Note:
428
+ Runs precompute() per call, as solve.py does once per forward pass.
429
+ compute() must never see raw prepare() output: DelayedCoupling only
430
+ resolves its delay read indices in precompute().
390
431
  """
391
432
  coupling_inputs = Bunch()
392
433
 
434
+ if coupling_data_dict:
435
+ first_data = next(iter(coupling_data_dict.values()))
436
+ state = validate_graph_topology(
437
+ first_data._prepared_topology, self.graph, state
438
+ )
439
+
393
440
  for name, n_dims in self.dynamics.COUPLING_INPUTS.items():
394
441
  if name not in self.coupling:
395
442
  # Missing coupling - use zeros
@@ -397,7 +444,9 @@ class Network:
397
444
  else:
398
445
  # Compute coupling
399
446
  coupling = self.coupling[name]
400
- data = coupling_data_dict[name]
447
+ data = coupling.precompute(
448
+ coupling_data_dict[name], coupling.params, self.graph
449
+ )
401
450
  state_data = coupling_state_dict[name]
402
451
  coupling_inputs[name] = coupling.compute(
403
452
  t, state, data, state_data, coupling.params, self.graph
@@ -552,11 +601,12 @@ class Network:
552
601
  Returns:
553
602
  None if no delays (max_delay == 0.0)
554
603
  Otherwise history buffer [n_steps, n_states, n_nodes]
555
- where n_steps = ceil(max_delay / dt)
604
+ where n_steps = delay_steps_bound(max_delay, dt) + 1
556
605
  """
557
- n_steps = max(
558
- 1, int(jnp.ceil(self.max_delay / dt))
559
- ) # at least 1 step (case: speed = inf)
606
+ # Covering [t0 - max_delay, t0] takes one row per step plus the t0
607
+ # endpoint. Must match extract_history_window() and the read indices
608
+ # DelayedCoupling.prepare() derives from the same bound.
609
+ n_steps = delay_steps_bound(self.max_delay, dt) + 1
560
610
  return jnp.broadcast_to(
561
611
  self.initial_state[None, :, :],
562
612
  (n_steps, self.initial_state.shape[0], self.initial_state.shape[1]),
@@ -6,6 +6,7 @@ from .base import (
6
6
  DelayedCoupling,
7
7
  InstantaneousCoupling,
8
8
  )
9
+ from .kuramoto import DelayedKuramotoCoupling, KuramotoCoupling
9
10
  from .linear import (
10
11
  DelayedDifferenceCoupling,
11
12
  DelayedLinearCoupling,
@@ -29,4 +30,6 @@ __all__ = [
29
30
  "DelayedDifferenceCoupling",
30
31
  "FastLinearCoupling",
31
32
  "SubspaceCoupling",
33
+ "KuramotoCoupling",
34
+ "DelayedKuramotoCoupling",
32
35
  ]