tvboptim 0.2.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.
Files changed (70) hide show
  1. tvboptim/__init__.py +9 -0
  2. tvboptim/data/__init__.py +12 -0
  3. tvboptim/data/loaders.py +99 -0
  4. tvboptim/execution.py +268 -0
  5. tvboptim/experimental/__init__.py +15 -0
  6. tvboptim/experimental/network_dynamics/__init__.py +28 -0
  7. tvboptim/experimental/network_dynamics/core/__init__.py +6 -0
  8. tvboptim/experimental/network_dynamics/core/bunch.py +67 -0
  9. tvboptim/experimental/network_dynamics/core/network.py +686 -0
  10. tvboptim/experimental/network_dynamics/coupling/__init__.py +22 -0
  11. tvboptim/experimental/network_dynamics/coupling/base.py +1005 -0
  12. tvboptim/experimental/network_dynamics/coupling/linear.py +466 -0
  13. tvboptim/experimental/network_dynamics/coupling/subspace.py +509 -0
  14. tvboptim/experimental/network_dynamics/coupling/tvb.py +202 -0
  15. tvboptim/experimental/network_dynamics/dynamics/__init__.py +7 -0
  16. tvboptim/experimental/network_dynamics/dynamics/base.py +541 -0
  17. tvboptim/experimental/network_dynamics/dynamics/lorenz.py +207 -0
  18. tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py +29 -0
  19. tvboptim/experimental/network_dynamics/dynamics/tvb/coombes_byrne.py +154 -0
  20. tvboptim/experimental/network_dynamics/dynamics/tvb/epileptor.py +200 -0
  21. tvboptim/experimental/network_dynamics/dynamics/tvb/generic_2d_oscillator.py +149 -0
  22. tvboptim/experimental/network_dynamics/dynamics/tvb/jansen_rit.py +158 -0
  23. tvboptim/experimental/network_dynamics/dynamics/tvb/kuramoto.py +120 -0
  24. tvboptim/experimental/network_dynamics/dynamics/tvb/larter_breakspear.py +221 -0
  25. tvboptim/experimental/network_dynamics/dynamics/tvb/linear.py +111 -0
  26. tvboptim/experimental/network_dynamics/dynamics/tvb/montbrio_pazo_roxin.py +137 -0
  27. tvboptim/experimental/network_dynamics/dynamics/tvb/sup_hopf.py +131 -0
  28. tvboptim/experimental/network_dynamics/dynamics/tvb/wilson_cowan.py +210 -0
  29. tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang.py +124 -0
  30. tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang_exc_inh.py +177 -0
  31. tvboptim/experimental/network_dynamics/external_input/__init__.py +20 -0
  32. tvboptim/experimental/network_dynamics/external_input/base.py +152 -0
  33. tvboptim/experimental/network_dynamics/external_input/data.py +203 -0
  34. tvboptim/experimental/network_dynamics/external_input/parametric.py +270 -0
  35. tvboptim/experimental/network_dynamics/graph/__init__.py +14 -0
  36. tvboptim/experimental/network_dynamics/graph/base.py +706 -0
  37. tvboptim/experimental/network_dynamics/graph/sparse.py +885 -0
  38. tvboptim/experimental/network_dynamics/graph/utils.py +0 -0
  39. tvboptim/experimental/network_dynamics/noise/__init__.py +6 -0
  40. tvboptim/experimental/network_dynamics/noise/base.py +162 -0
  41. tvboptim/experimental/network_dynamics/noise/gaussian.py +71 -0
  42. tvboptim/experimental/network_dynamics/result.py +78 -0
  43. tvboptim/experimental/network_dynamics/solve.py +721 -0
  44. tvboptim/experimental/network_dynamics/solvers/__init__.py +15 -0
  45. tvboptim/experimental/network_dynamics/solvers/base.py +46 -0
  46. tvboptim/experimental/network_dynamics/solvers/diffrax.py +63 -0
  47. tvboptim/experimental/network_dynamics/solvers/native.py +308 -0
  48. tvboptim/experimental/network_dynamics/utils/__init__.py +3 -0
  49. tvboptim/experimental/network_dynamics/utils/printer.py +555 -0
  50. tvboptim/model.py +111 -0
  51. tvboptim/observations/__init__.py +3 -0
  52. tvboptim/observations/observation.py +32 -0
  53. tvboptim/observations/tvb_monitors/__init__.py +11 -0
  54. tvboptim/observations/tvb_monitors/bold.py +290 -0
  55. tvboptim/observations/tvb_monitors/downsampling.py +185 -0
  56. tvboptim/optim/__init__.py +4 -0
  57. tvboptim/optim/callbacks.py +333 -0
  58. tvboptim/optim/optax.py +379 -0
  59. tvboptim/types/__init__.py +35 -0
  60. tvboptim/types/parameter.py +769 -0
  61. tvboptim/types/spaces.py +943 -0
  62. tvboptim/types/stateutils.py +109 -0
  63. tvboptim/utils/__init__.py +16 -0
  64. tvboptim/utils/caching.py +82 -0
  65. tvboptim/utils/utils.py +265 -0
  66. tvboptim-0.2.0.dist-info/METADATA +157 -0
  67. tvboptim-0.2.0.dist-info/RECORD +70 -0
  68. tvboptim-0.2.0.dist-info/WHEEL +5 -0
  69. tvboptim-0.2.0.dist-info/licenses/LICENSE +278 -0
  70. tvboptim-0.2.0.dist-info/top_level.txt +1 -0
tvboptim/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """TVBOptim - Optimization tools for The Virtual Brain."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from . import data
6
+ from .model import jaxify
7
+ from .types import parameter, spaces
8
+
9
+ __all__ = ["spaces", "jaxify", "parameter", "data"]
@@ -0,0 +1,12 @@
1
+ """Data loading utilities for tvboptim.
2
+
3
+ This module provides convenient access to built-in connectivity and
4
+ functional connectivity datasets.
5
+ """
6
+
7
+ from .loaders import load_functional_connectivity, load_structural_connectivity
8
+
9
+ __all__ = [
10
+ "load_structural_connectivity",
11
+ "load_functional_connectivity",
12
+ ]
@@ -0,0 +1,99 @@
1
+ """Data loading functions for built-in datasets."""
2
+
3
+ from pathlib import Path
4
+ from typing import List, Tuple
5
+
6
+ import jax.numpy as jnp
7
+ import numpy as np
8
+
9
+ # Get the data directory
10
+ _DATA_DIR = Path(__file__).parent
11
+
12
+
13
+ def load_structural_connectivity(
14
+ name: str = "dk_average",
15
+ ) -> Tuple[jnp.ndarray, jnp.ndarray, List[str]]:
16
+ """
17
+ Load structural connectivity data.
18
+
19
+ Returns raw connectivity weights, tract lengths, and region labels.
20
+ Users can normalize or preprocess as needed.
21
+
22
+ Available datasets:
23
+ - "dk_average": Average structural connectivity from Desikan-Killiany
24
+ parcellation (84 regions)
25
+ - "dTOR": Virtual DBS structural connectivity with Glasser cortical
26
+ parcellation plus distal and striatum regions (370 regions)
27
+
28
+ Args:
29
+ name: Dataset name (default: "dk_average")
30
+
31
+ Returns:
32
+ weights: Connectivity weights [n_nodes, n_nodes]
33
+ lengths: Tract lengths in mm [n_nodes, n_nodes]
34
+ region_labels: List of region acronyms (e.g., ['L.BSTS', 'R.MTG', ...])
35
+
36
+ Examples:
37
+ >>> from tvboptim.data import load_structural_connectivity
38
+ >>> weights, lengths, region_labels = load_structural_connectivity()
39
+ >>> print(weights.shape)
40
+ (84, 84)
41
+ >>> print(len(region_labels))
42
+ 84
43
+ >>> print(region_labels[:3])
44
+ ['L.BSTS', 'L.CACG', 'L.CMFG']
45
+
46
+ >>> # Load dTOR dataset
47
+ >>> weights, lengths, region_labels = load_structural_connectivity("dTOR")
48
+ >>> print(weights.shape)
49
+ (370, 370)
50
+
51
+ >>> # Normalize if needed
52
+ >>> weights_norm = weights / jnp.max(weights)
53
+ """
54
+ data_path = _DATA_DIR / "connectivity" / name / "data.npz"
55
+
56
+ if not data_path.exists():
57
+ raise ValueError(
58
+ f"Dataset '{name}' not found. Available datasets: dk_average, dTOR"
59
+ )
60
+
61
+ data = np.load(data_path, allow_pickle=True)
62
+ weights = jnp.array(data["weights"])
63
+ lengths = jnp.array(data["lengths"])
64
+ region_labels = data["region_labels"].tolist()
65
+
66
+ return weights, lengths, region_labels
67
+
68
+
69
+ def load_functional_connectivity(name: str = "dk_average") -> jnp.ndarray:
70
+ """
71
+ Load functional connectivity data.
72
+
73
+ Returns empirical functional connectivity matrix as JAX array.
74
+
75
+ Available datasets:
76
+ - "dk_average": Average functional connectivity from Desikan-Killiany
77
+ parcellation (84 regions)
78
+
79
+ Args:
80
+ name: Dataset name (default: "dk_average")
81
+
82
+ Returns:
83
+ fc: Functional connectivity matrix [n_nodes, n_nodes]
84
+
85
+ Examples:
86
+ >>> from tvboptim.data import load_functional_connectivity
87
+ >>> fc_target = load_functional_connectivity()
88
+ >>> print(fc_target.shape)
89
+ (84, 84)
90
+ """
91
+ data_path = _DATA_DIR / "functional" / name / "data.npz"
92
+
93
+ if not data_path.exists():
94
+ raise ValueError(f"Dataset '{name}' not found. Available datasets: dk_average")
95
+
96
+ data = np.load(data_path)
97
+ fc = jnp.array(data["fc"])
98
+
99
+ return fc
tvboptim/execution.py ADDED
@@ -0,0 +1,268 @@
1
+ from abc import ABC
2
+
3
+ import jax
4
+ import jax.numpy as jnp
5
+ from tqdm import tqdm
6
+
7
+ from tvboptim.types.stateutils import combine_state
8
+
9
+
10
+ class Execution(ABC):
11
+ pass
12
+
13
+
14
+ class Result(ABC):
15
+ """
16
+ Result type to provide unified indexing
17
+ """
18
+
19
+ pass
20
+
21
+
22
+ class SequentialExecution(Execution):
23
+ """
24
+ Sequential execution of models across parameter spaces with progress tracking.
25
+
26
+ SequentialExecution provides a straightforward approach to executing a model
27
+ function across all parameter combinations in a given state space. Unlike
28
+ ParallelExecution, it processes parameter combinations one at a time, making
29
+ it ideal for debugging, memory-constrained environments, or when parallel
30
+ execution is not feasible or desired.
31
+
32
+ Parameters
33
+ ----------
34
+ model : callable
35
+ Model function to execute. Should accept a state parameter and return
36
+ simulation results. Signature: model(state, *args, **kwargs).
37
+ statespace : AbstractSpace
38
+ Parameter space (DataSpace, UniformSpace, or GridSpace) defining the
39
+ parameter combinations to execute across.
40
+ *args : tuple
41
+ Positional arguments passed directly to the model function.
42
+ **kwargs : dict
43
+ Keyword arguments passed directly to the model function.
44
+
45
+ Examples
46
+ --------
47
+ >>> import jax.numpy as jnp
48
+ >>> from tvboptim.types.spaces import GridSpace
49
+ >>> from tvboptim.types.parameter import Parameter
50
+ >>>
51
+ >>> # Define a simple model
52
+ >>> def simulate(state, noise_level=0.0):
53
+ ... result = state['param1'] * state['param2'] + noise_level
54
+ ... return {'output': result, 'inputs': state}
55
+ >>>
56
+ >>> # Create parameter space
57
+ >>> state = {
58
+ ... 'param1': Parameter("param1", 0.0, low=0.0, high=1.0, free=True),
59
+ ... 'param2': Parameter("param2", 0.0, low=-1.0, high=1.0, free=True)
60
+ ... }
61
+ >>> space = GridSpace(state, n=5) # 25 parameter combinations
62
+ >>>
63
+ >>> # Set up sequential execution
64
+ >>> executor = SequentialExecution(
65
+ ... model=simulate,
66
+ ... statespace=space,
67
+ ... noise_level=0.1 # Keyword argument passed to model
68
+ ... )
69
+ >>>
70
+ >>> # Execute across all parameter combinations
71
+ >>> results = executor.run() # Shows progress bar
72
+ >>>
73
+ >>> # Access results
74
+ >>> first_result = results[0]
75
+ >>> all_results = list(results) # Convert to list
76
+ >>> total_count = len(results)
77
+
78
+ """
79
+
80
+ def __init__(self, model, statespace, collect=True, *args, **kwargs):
81
+ self.model = model
82
+ self.statespace = statespace
83
+ self.args = args
84
+ self.kwargs = kwargs
85
+ # if collect:
86
+ # self.model = lambda state, *args, **kwargs: model(collect_parameters(state), *args, **kwargs)
87
+
88
+ def run(self):
89
+ """
90
+ Execute the model across all parameter combinations in parallel.
91
+ """
92
+ results = []
93
+ for state in tqdm(self.statespace):
94
+ results.append(
95
+ jax.block_until_ready(self.model(state, *self.args, **self.kwargs))
96
+ )
97
+ # results.append(jax.block_until_ready(self.model(state, *self.args, **self.kwargs)))
98
+ return SequentialResult(results)
99
+
100
+
101
+ class SequentialResult(Result):
102
+ def __init__(self, results):
103
+ self.results = results
104
+
105
+ def __iter__(self):
106
+ return iter(self.results)
107
+
108
+ def __getitem__(self, index):
109
+ return self.results[index]
110
+
111
+ def __len__(self):
112
+ return len(self.results)
113
+
114
+
115
+ class ParallelExecution(Execution):
116
+ """
117
+ Efficient parallel execution of models across parameter spaces using JAX.
118
+
119
+ ParallelExecution orchestrates the parallel computation of a model function
120
+ across all parameter combinations in a given state space. It leverages JAX's
121
+ pmap (for multi-device parallelism) and vmap (for vectorization).
122
+
123
+ Parameters
124
+ ----------
125
+ model : callable
126
+ Model function to execute. Should accept a state parameter and return
127
+ simulation results. Signature: model(state, *args, **kwargs).
128
+ space : AbstractSpace
129
+ Parameter space (DataSpace, UniformSpace, or GridSpace) defining the
130
+ parameter combinations to execute across.
131
+ *args : tuple
132
+ Positional arguments passed directly to the model function.
133
+ n_vmap : int, optional
134
+ Number of states to vectorize over using jax.vmap. Controls batch size
135
+ for vectorized execution within each device. Default is 1.
136
+ n_pmap : int, optional
137
+ Number of devices to parallelize over using jax.pmap. Should typically
138
+ match the number of available devices. Default is 1.
139
+ **kwargs : dict
140
+ Keyword arguments passed directly to the model function.
141
+
142
+
143
+ Examples
144
+ --------
145
+ >>> import jax
146
+ >>> import jax.numpy as jnp
147
+ >>> from tvboptim.types.spaces import GridSpace
148
+ >>> from tvboptim.types.parameter import Parameter
149
+ >>>
150
+ >>> # Define a simple model
151
+ >>> def simulate(state):
152
+ ... return state['param1'] * state['param2']
153
+ >>>
154
+ >>> # Create parameter space
155
+ >>> state = {
156
+ ... 'param1': Parameter("param1", 0.0, low=0.0, high=1.0, free=True),
157
+ ... 'param2': Parameter("param2", 0.0, low=-1.0, high=1.0, free=True)
158
+ ... }
159
+ >>> space = GridSpace(state, n=10) # 100 parameter combinations
160
+ >>>
161
+ >>> # Set up parallel execution
162
+ >>> n_devices = jax.device_count()
163
+ >>> executor = ParallelExecution(
164
+ ... model=simulate,
165
+ ... statespace=space,
166
+ ... n_vmap=5, # Vectorize over 5 states per device
167
+ ... n_pmap=n_devices # Use all available devices
168
+ ... )
169
+ >>>
170
+ >>> # Execute across all parameter combinations
171
+ >>> results = executor.run()
172
+ >>>
173
+ >>> # Access individual results
174
+ >>> first_result = results[0]
175
+ >>> all_results = list(results) # Convert to list
176
+ >>> subset_results = results[10:20] # Slice notation
177
+
178
+ Notes
179
+ -----
180
+ For optimal performance:
181
+
182
+ - Set n_pmap to match the number of available devices - on CPU use the pmap trick to force XLA to use N devices:
183
+ os.environ['XLA_FLAGS'] = f'--xla_force_host_platform_device_count={N}'
184
+ - Tune n_vmap based on memory constraints and model complexity
185
+
186
+ The execution uses jax.block_until_ready() to ensure all computation completes
187
+ before returning results, providing accurate timing measurements.
188
+ """
189
+
190
+ def __init__(self, model, space, *args, n_vmap=1, n_pmap=1, **kwargs):
191
+ self.model = model
192
+ self.space = space
193
+ self.n_vmap = n_vmap
194
+ self.n_pmap = n_pmap
195
+ self.args = args
196
+ self.kwargs = kwargs
197
+ diff_state, static_state = space.collect(n_pmap=n_pmap, combine=False)
198
+
199
+ self.diff_state = diff_state
200
+
201
+ # kwargs args probably go directly into model
202
+ def _model(d):
203
+ state = combine_state(d, static_state)
204
+ return model(state, *self.args, **self.kwargs)
205
+
206
+ def map_model(d):
207
+ return jax.lax.map(_model, d, batch_size=n_vmap)
208
+
209
+ self.map_model = map_model
210
+
211
+ def run(self):
212
+ """
213
+ Execute the model across all parameter combinations in parallel.
214
+ """
215
+ res = jax.block_until_ready(
216
+ jax.pmap(self.map_model, in_axes=0)(self.diff_state)
217
+ )
218
+ return ParallelResult(res, self.space.N, self.n_vmap, self.n_pmap)
219
+
220
+
221
+ class ParallelResult(Result):
222
+ def __init__(self, results, N, n_vmap, n_pmap):
223
+ self.results = results
224
+ self.N = N
225
+ self.n_vmap = n_vmap
226
+ self.n_pmap = n_pmap
227
+
228
+ # Calculate second dimension size
229
+ if n_pmap is None:
230
+ self.second_dim_size = max(1, int(jnp.ceil(N / n_vmap)))
231
+ else:
232
+ self.second_dim_size = max(1, int(jnp.ceil(N / n_pmap)))
233
+
234
+ def __len__(self):
235
+ return self.N
236
+
237
+ def __iter__(self):
238
+ for i in range(self.N):
239
+ yield self[i]
240
+
241
+ def __getitem__(self, index):
242
+ if isinstance(index, slice):
243
+ return [self[i] for i in range(*index.indices(self.N))]
244
+
245
+ if index < 0:
246
+ index += self.N
247
+ if index < 0 or index >= self.N:
248
+ raise IndexError(f"Index {index} out of range for length {self.N}")
249
+
250
+ if self.n_pmap is None:
251
+ # No first dimension: results shape is (second_dim_size, ...)
252
+ # Second dimension contains n_vmap * n_map elements
253
+ vmap_idx = index // (self.second_dim_size // self.n_vmap)
254
+ map_idx = index % (self.second_dim_size // self.n_vmap)
255
+ second_dim_idx = vmap_idx * (self.second_dim_size // self.n_vmap) + map_idx
256
+
257
+ def extract_at_indices(leaf):
258
+ return leaf[second_dim_idx]
259
+
260
+ else:
261
+ # First dimension is n_pmap: results shape is (n_pmap, second_dim_size, ...)
262
+ pmap_idx = index // self.second_dim_size
263
+ second_dim_idx = index % self.second_dim_size
264
+
265
+ def extract_at_indices(leaf):
266
+ return leaf[pmap_idx, second_dim_idx]
267
+
268
+ return jax.tree.map(extract_at_indices, self.results)
@@ -0,0 +1,15 @@
1
+ """Experimental modules for TVBOptim.
2
+
3
+ This package contains experimental features and integrations that are under
4
+ active development. APIs may change without notice.
5
+
6
+ Modules:
7
+ network_dynamics: JAX-based brain network modeling framework with support
8
+ for ODEs, DDEs, SDEs, and SDDEs with flexible coupling
9
+ and graph structures.
10
+ """
11
+
12
+ # Import network_dynamics as a submodule
13
+ from . import network_dynamics
14
+
15
+ __all__ = ["network_dynamics"]
@@ -0,0 +1,28 @@
1
+ """Network Dynamics: JAX-based brain network modeling interface.
2
+
3
+ Part of TVBOptim experimental modules.
4
+ """
5
+
6
+ from .core import Bunch, Network
7
+ from .graph import (
8
+ DelayGraph,
9
+ DenseDelayGraph,
10
+ DenseGraph,
11
+ Graph,
12
+ SparseDelayGraph,
13
+ SparseGraph,
14
+ )
15
+ from .solve import prepare, solve
16
+
17
+ __all__ = [
18
+ "Bunch",
19
+ "Graph",
20
+ "DelayGraph",
21
+ "SparseGraph",
22
+ "SparseDelayGraph",
23
+ "DenseGraph",
24
+ "DenseDelayGraph",
25
+ "solve",
26
+ "prepare",
27
+ "Network",
28
+ ]
@@ -0,0 +1,6 @@
1
+ """Core components of Network Dynamics."""
2
+
3
+ from .bunch import Bunch
4
+ from .network import Network
5
+
6
+ __all__ = ["Bunch", "Network"]
@@ -0,0 +1,67 @@
1
+ """Parameter container with attribute access and JAX PyTree support."""
2
+
3
+ from typing import Any, Tuple
4
+
5
+ import jax
6
+
7
+
8
+ class Bunch(dict):
9
+ """Dictionary with attribute access for parameters.
10
+
11
+ A JAX PyTree-compatible parameter container that allows both dict['key']
12
+ and dict.key access patterns. Designed for neural dynamics parameters
13
+ with support for JAX transformations.
14
+
15
+ Examples:
16
+ >>> params = Bunch(a=1.0, b=2.0)
17
+ >>> params.a # attribute access
18
+ 1.0
19
+ >>> params['b'] # dict access
20
+ 2.0
21
+ >>> jax.tree.map(lambda x: x * 2, params) # JAX transformations
22
+ Bunch(a=2.0, b=4.0)
23
+ """
24
+
25
+ def __getattr__(self, key: str) -> Any:
26
+ try:
27
+ return self[key]
28
+ except KeyError:
29
+ raise AttributeError(
30
+ f"'{self.__class__.__name__}' object has no attribute '{key}'"
31
+ )
32
+
33
+ def __setattr__(self, key: str, value: Any) -> None:
34
+ self[key] = value
35
+
36
+ def __delattr__(self, key: str) -> None:
37
+ try:
38
+ del self[key]
39
+ except KeyError:
40
+ raise AttributeError(
41
+ f"'{self.__class__.__name__}' object has no attribute '{key}'"
42
+ )
43
+
44
+ def __repr__(self) -> str:
45
+ items = ", ".join(f"{k}={v!r}" for k, v in self.items())
46
+ return f"{self.__class__.__name__}({items})"
47
+
48
+ def copy(self) -> "Bunch":
49
+ """Create a shallow copy of the Bunch."""
50
+ return Bunch(super().copy())
51
+
52
+
53
+ # Register Bunch as a JAX PyTree
54
+ def _bunch_tree_flatten(bunch: Bunch) -> Tuple[Tuple[Any, ...], Tuple[str, ...]]:
55
+ """Flatten Bunch into values and keys for JAX PyTree."""
56
+ keys = tuple(sorted(bunch.keys())) # Sort for deterministic order
57
+ values = tuple(bunch[key] for key in keys)
58
+ return values, keys
59
+
60
+
61
+ def _bunch_tree_unflatten(keys: Tuple[str, ...], values: Tuple[Any, ...]) -> Bunch:
62
+ """Reconstruct Bunch from keys and values for JAX PyTree."""
63
+ return Bunch(zip(keys, values))
64
+
65
+
66
+ # Register the PyTree
67
+ jax.tree_util.register_pytree_node(Bunch, _bunch_tree_flatten, _bunch_tree_unflatten)