tvboptim 0.2.6__tar.gz → 0.2.8__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.
- {tvboptim-0.2.6/src/tvboptim.egg-info → tvboptim-0.2.8}/PKG-INFO +3 -3
- {tvboptim-0.2.6 → tvboptim-0.2.8}/pyproject.toml +3 -3
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/execution.py +36 -33
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/analysis/lyapunov.py +16 -15
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/core/bunch.py +13 -7
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/core/network.py +40 -16
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/dynamics/base.py +24 -0
- tvboptim-0.2.8/src/tvboptim/experimental/network_dynamics/result.py +178 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/solve.py +328 -504
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/solvers/native.py +2 -2
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/observations/tvb_monitors/__init__.py +11 -2
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/observations/tvb_monitors/bold.py +237 -13
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/observations/tvb_monitors/downsampling.py +13 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/optim/optax.py +105 -37
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/types/spaces.py +22 -15
- {tvboptim-0.2.6 → tvboptim-0.2.8/src/tvboptim.egg-info}/PKG-INFO +3 -3
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim.egg-info/SOURCES.txt +2 -1
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim.egg-info/requires.txt +2 -2
- tvboptim-0.2.8/tests/test_optax_optimizer_toy.py +170 -0
- tvboptim-0.2.6/src/tvboptim/experimental/network_dynamics/result.py +0 -127
- {tvboptim-0.2.6 → tvboptim-0.2.8}/LICENSE +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/README.md +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/setup.cfg +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/data/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/data/connectivity/dTOR/data.npz +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/data/connectivity/dk_average/data.npz +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/data/functional/dk_average/data.npz +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/data/loaders.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/data/plotting/dk_average/aparc+aseg-mni_09c.nii.gz +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/data/plotting/dk_average/fs_default.txt +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/data/plotting/dk_average/fs_default_freesurfer_idx.csv +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/analysis/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/core/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/coupling/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/coupling/base.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/coupling/linear.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/coupling/subspace.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/coupling/tvb.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/dynamics/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/dynamics/lorenz.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/coombes_byrne.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/epileptor.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/generic_2d_oscillator.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/jansen_rit.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/kuramoto.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/larter_breakspear.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/linear.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/montbrio_pazo_roxin.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/sup_hopf.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wilson_cowan.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang_exc_inh.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/external_input/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/external_input/base.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/external_input/data.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/external_input/parametric.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/graph/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/graph/base.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/graph/sparse.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/graph/utils.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/noise/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/noise/base.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/noise/gaussian.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/solvers/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/solvers/base.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/solvers/diffrax.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/utils/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/utils/history.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/utils/printer.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/observations/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/observations/observation.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/optim/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/optim/callbacks.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/tvbo/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/tvbo/prepare_experiment.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/types/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/types/parameter.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/types/stateutils.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/utils/__init__.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/utils/caching.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/utils/utils.py +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim.egg-info/dependency_links.txt +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim.egg-info/top_level.txt +0 -0
- {tvboptim-0.2.6 → tvboptim-0.2.8}/tests/test_execution.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tvboptim
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.8
|
|
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
|
|
@@ -23,11 +23,11 @@ Requires-Dist: optimistix
|
|
|
23
23
|
Requires-Dist: matplotlib
|
|
24
24
|
Requires-Dist: numpy
|
|
25
25
|
Requires-Dist: pandas
|
|
26
|
-
Requires-Dist: jax<0.
|
|
26
|
+
Requires-Dist: jax<0.10
|
|
27
27
|
Requires-Dist: equinox
|
|
28
28
|
Requires-Dist: dill
|
|
29
29
|
Requires-Dist: tqdm
|
|
30
|
-
Requires-Dist: numpyro>=0.
|
|
30
|
+
Requires-Dist: numpyro>=0.20.1
|
|
31
31
|
Requires-Dist: diffrax
|
|
32
32
|
Requires-Dist: plum-dispatch
|
|
33
33
|
Provides-Extra: dev
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "tvboptim"
|
|
7
|
-
version = "0.2.
|
|
7
|
+
version = "0.2.8"
|
|
8
8
|
description = "Optimization tools for The Virtual Brain"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
authors = [
|
|
@@ -30,11 +30,11 @@ dependencies = [
|
|
|
30
30
|
"matplotlib",
|
|
31
31
|
"numpy",
|
|
32
32
|
"pandas",
|
|
33
|
-
"jax<0.
|
|
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.
|
|
34
34
|
"equinox",
|
|
35
35
|
"dill",
|
|
36
36
|
"tqdm",
|
|
37
|
-
"numpyro>=0.
|
|
37
|
+
"numpyro>=0.20.1",
|
|
38
38
|
"diffrax",
|
|
39
39
|
"plum-dispatch",
|
|
40
40
|
]
|
|
@@ -21,43 +21,21 @@ class Result(ABC):
|
|
|
21
21
|
|
|
22
22
|
space = None
|
|
23
23
|
|
|
24
|
-
def
|
|
25
|
-
"""
|
|
26
|
-
|
|
27
|
-
Each row corresponds to one parameter combination. If a space
|
|
28
|
-
reference is stored, parameter columns are included. Result
|
|
29
|
-
column names are derived from the pytree key paths of the
|
|
30
|
-
result structure.
|
|
31
|
-
|
|
32
|
-
Returns
|
|
33
|
-
-------
|
|
34
|
-
pd.DataFrame
|
|
35
|
-
"""
|
|
36
|
-
# Parameter columns
|
|
37
|
-
if self.space is not None:
|
|
38
|
-
df = self.space.to_dataframe()
|
|
39
|
-
else:
|
|
40
|
-
df = pd.DataFrame()
|
|
41
|
-
|
|
42
|
-
# Result columns
|
|
24
|
+
def _result_col_names(self, param_cols) -> list:
|
|
25
|
+
"""Derive result column names from the first result, handling collisions."""
|
|
43
26
|
sample = self[0]
|
|
44
|
-
paths_and_leaves,
|
|
27
|
+
paths_and_leaves, _ = jax.tree_util.tree_flatten_with_path(sample)
|
|
45
28
|
col_names = [_keypath_to_name(p) for p, _ in paths_and_leaves]
|
|
46
|
-
|
|
47
|
-
# Handle name collisions with param columns
|
|
48
29
|
for i, name in enumerate(col_names):
|
|
49
|
-
if name in
|
|
30
|
+
if name in param_cols:
|
|
50
31
|
col_names[i] = f"result.{name}"
|
|
32
|
+
return col_names
|
|
51
33
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
for name, values in result_data.items():
|
|
59
|
-
df[name] = values
|
|
60
|
-
|
|
34
|
+
@staticmethod
|
|
35
|
+
def _assign_leaves(df, col_names, leaves):
|
|
36
|
+
"""Assign (N, ...) numpy leaves to DataFrame columns."""
|
|
37
|
+
for name, leaf in zip(col_names, leaves):
|
|
38
|
+
df[name] = leaf if leaf.ndim == 1 else list(leaf)
|
|
61
39
|
return df
|
|
62
40
|
|
|
63
41
|
|
|
@@ -154,6 +132,15 @@ class SequentialResult(Result):
|
|
|
154
132
|
def __len__(self):
|
|
155
133
|
return len(self.results)
|
|
156
134
|
|
|
135
|
+
def to_dataframe(self) -> pd.DataFrame:
|
|
136
|
+
df = self.space.to_dataframe() if self.space is not None else pd.DataFrame()
|
|
137
|
+
col_names = self._result_col_names(df.columns)
|
|
138
|
+
|
|
139
|
+
# Stack N individual results into a single pytree of (N, ...) arrays
|
|
140
|
+
stacked = jax.tree.map(lambda *xs: np.stack(xs), *self.results)
|
|
141
|
+
leaves = jax.tree.leaves(stacked)
|
|
142
|
+
return self._assign_leaves(df, col_names, leaves)
|
|
143
|
+
|
|
157
144
|
|
|
158
145
|
class ParallelExecution(Execution):
|
|
159
146
|
"""
|
|
@@ -258,7 +245,9 @@ class ParallelExecution(Execution):
|
|
|
258
245
|
res = jax.block_until_ready(
|
|
259
246
|
jax.pmap(self.map_model, in_axes=0)(self.diff_state)
|
|
260
247
|
)
|
|
261
|
-
return ParallelResult(
|
|
248
|
+
return ParallelResult(
|
|
249
|
+
res, self.space.N, self.n_vmap, self.n_pmap, space=self.space
|
|
250
|
+
)
|
|
262
251
|
|
|
263
252
|
|
|
264
253
|
class ParallelResult(Result):
|
|
@@ -310,3 +299,17 @@ class ParallelResult(Result):
|
|
|
310
299
|
return leaf[pmap_idx, second_dim_idx]
|
|
311
300
|
|
|
312
301
|
return jax.tree.map(extract_at_indices, self.results)
|
|
302
|
+
|
|
303
|
+
def to_dataframe(self) -> pd.DataFrame:
|
|
304
|
+
df = self.space.to_dataframe() if self.space is not None else pd.DataFrame()
|
|
305
|
+
col_names = self._result_col_names(df.columns)
|
|
306
|
+
|
|
307
|
+
def unbatch(leaf):
|
|
308
|
+
if self.n_pmap is not None:
|
|
309
|
+
# (n_pmap, n_map, ...) → (n_pmap * n_map, ...)
|
|
310
|
+
leaf = leaf.reshape((-1,) + leaf.shape[2:])
|
|
311
|
+
# trim padding to N
|
|
312
|
+
return np.asarray(leaf[: self.N])
|
|
313
|
+
|
|
314
|
+
leaves = jax.tree.leaves(jax.tree.map(unbatch, self.results))
|
|
315
|
+
return self._assign_leaves(df, col_names, leaves)
|
{tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/analysis/lyapunov.py
RENAMED
|
@@ -43,13 +43,13 @@ def lyapunov(network, solver=None, t=1000.0, n=10, d0=1e-9, dt=0.1, t0=0.0):
|
|
|
43
43
|
|
|
44
44
|
def _lyapunov(solve_fn, config, t, n=10, d0=1e-9):
|
|
45
45
|
"""Low-level MLE estimation using a pre-built solve_fn / config."""
|
|
46
|
-
u_init = config.initial_state.dynamics
|
|
46
|
+
u_init = config.initial_state.dynamics # [n_states, n_nodes]
|
|
47
47
|
D = u_init.size
|
|
48
48
|
u2_init = u_init + d0 / jnp.sqrt(D)
|
|
49
49
|
|
|
50
50
|
def _solve_from(u):
|
|
51
|
-
new_is = Bunch({**config.initial_state,
|
|
52
|
-
new_cfg = Bunch({**config,
|
|
51
|
+
new_is = Bunch({**config.initial_state, "dynamics": u})
|
|
52
|
+
new_cfg = Bunch({**config, "initial_state": new_is})
|
|
53
53
|
return solve_fn(new_cfg).ys[-1]
|
|
54
54
|
|
|
55
55
|
@jax.jit
|
|
@@ -71,8 +71,9 @@ def _lyapunov(solve_fn, config, t, n=10, d0=1e-9):
|
|
|
71
71
|
return float(log_sum / (n * t))
|
|
72
72
|
|
|
73
73
|
|
|
74
|
-
def lyapunov_spectrum(
|
|
75
|
-
|
|
74
|
+
def lyapunov_spectrum(
|
|
75
|
+
network, solver=None, t=1000.0, n=10, k=None, dt=0.1, t0=0.0, mode="jvp", d0=1e-9
|
|
76
|
+
):
|
|
76
77
|
"""
|
|
77
78
|
Estimate the Lyapunov spectrum of a network.
|
|
78
79
|
|
|
@@ -117,8 +118,8 @@ def _lyapunov_spectrum_sim(solve_fn, config, t, n=10, k=None, d0=1e-9):
|
|
|
117
118
|
|
|
118
119
|
def _solve_flat(u_flat):
|
|
119
120
|
u = u_flat.reshape(shape)
|
|
120
|
-
new_is = Bunch({**config.initial_state,
|
|
121
|
-
new_cfg = Bunch({**config,
|
|
121
|
+
new_is = Bunch({**config.initial_state, "dynamics": u})
|
|
122
|
+
new_cfg = Bunch({**config, "initial_state": new_is})
|
|
122
123
|
return solve_fn(new_cfg).ys[-1].flatten()
|
|
123
124
|
|
|
124
125
|
@jax.jit
|
|
@@ -126,10 +127,10 @@ def _lyapunov_spectrum_sim(solve_fn, config, t, n=10, k=None, d0=1e-9):
|
|
|
126
127
|
def _step(carry, _):
|
|
127
128
|
u_flat, Q, log_sum = carry
|
|
128
129
|
new_u = _solve_flat(u_flat)
|
|
129
|
-
perturbed = u_flat + d0 * Q.T
|
|
130
|
-
new_perturbed = jax.vmap(_solve_flat)(perturbed)
|
|
131
|
-
delta = (new_perturbed - new_u) / d0
|
|
132
|
-
Q_new, R = jnp.linalg.qr(delta.T)
|
|
130
|
+
perturbed = u_flat + d0 * Q.T # [k, D]
|
|
131
|
+
new_perturbed = jax.vmap(_solve_flat)(perturbed) # [k, D]
|
|
132
|
+
delta = (new_perturbed - new_u) / d0 # [k, D]
|
|
133
|
+
Q_new, R = jnp.linalg.qr(delta.T) # [D, k], [k, k]
|
|
133
134
|
log_sum = log_sum + jnp.log(jnp.abs(jnp.diag(R)))
|
|
134
135
|
return (new_u, Q_new, log_sum), None
|
|
135
136
|
|
|
@@ -152,8 +153,8 @@ def _lyapunov_spectrum_jvp(solve_fn, config, t, n=10, k=None):
|
|
|
152
153
|
|
|
153
154
|
def _solve_flat(u_flat):
|
|
154
155
|
u = u_flat.reshape(shape)
|
|
155
|
-
new_is = Bunch({**config.initial_state,
|
|
156
|
-
new_cfg = Bunch({**config,
|
|
156
|
+
new_is = Bunch({**config.initial_state, "dynamics": u})
|
|
157
|
+
new_cfg = Bunch({**config, "initial_state": new_is})
|
|
157
158
|
return solve_fn(new_cfg).ys[-1].flatten()
|
|
158
159
|
|
|
159
160
|
@jax.jit
|
|
@@ -161,8 +162,8 @@ def _lyapunov_spectrum_jvp(solve_fn, config, t, n=10, k=None):
|
|
|
161
162
|
def _step(carry, _):
|
|
162
163
|
u_flat, Q, log_sum = carry
|
|
163
164
|
new_u, jvp_fn = jax.linearize(_solve_flat, u_flat)
|
|
164
|
-
tangents = jax.vmap(jvp_fn)(Q.T)
|
|
165
|
-
Q_new, R = jnp.linalg.qr(tangents.T)
|
|
165
|
+
tangents = jax.vmap(jvp_fn)(Q.T) # [k, D]
|
|
166
|
+
Q_new, R = jnp.linalg.qr(tangents.T) # [D, k], [k, k]
|
|
166
167
|
log_sum = log_sum + jnp.log(jnp.abs(jnp.diag(R)))
|
|
167
168
|
return (new_u, Q_new, log_sum), None
|
|
168
169
|
|
|
@@ -50,12 +50,16 @@ class Bunch(dict):
|
|
|
50
50
|
return Bunch(super().copy())
|
|
51
51
|
|
|
52
52
|
|
|
53
|
-
# Register Bunch as a JAX PyTree
|
|
54
|
-
|
|
55
|
-
|
|
53
|
+
# Register Bunch as a JAX PyTree with named keys so that
|
|
54
|
+
# jax.tree_util.tree_flatten_with_path produces DictKey paths instead of
|
|
55
|
+
# FlattenedIndexKey positional indices.
|
|
56
|
+
def _bunch_tree_flatten_with_keys(
|
|
57
|
+
bunch: Bunch,
|
|
58
|
+
) -> Tuple[Tuple[Any, ...], Tuple[str, ...]]:
|
|
59
|
+
"""Flatten Bunch into (key, value) pairs and aux keys for JAX PyTree."""
|
|
56
60
|
keys = tuple(sorted(bunch.keys())) # Sort for deterministic order
|
|
57
|
-
|
|
58
|
-
return
|
|
61
|
+
children_with_keys = [(jax.tree_util.DictKey(k), bunch[k]) for k in keys]
|
|
62
|
+
return children_with_keys, keys
|
|
59
63
|
|
|
60
64
|
|
|
61
65
|
def _bunch_tree_unflatten(keys: Tuple[str, ...], values: Tuple[Any, ...]) -> Bunch:
|
|
@@ -63,5 +67,7 @@ def _bunch_tree_unflatten(keys: Tuple[str, ...], values: Tuple[Any, ...]) -> Bun
|
|
|
63
67
|
return Bunch(zip(keys, values))
|
|
64
68
|
|
|
65
69
|
|
|
66
|
-
#
|
|
67
|
-
jax.tree_util.
|
|
70
|
+
# register_pytree_with_keys provides both regular and key-aware flattening
|
|
71
|
+
jax.tree_util.register_pytree_with_keys(
|
|
72
|
+
Bunch, _bunch_tree_flatten_with_keys, _bunch_tree_unflatten
|
|
73
|
+
)
|
{tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/core/network.py
RENAMED
|
@@ -244,37 +244,39 @@ class Network:
|
|
|
244
244
|
def update_history(self, solution: Optional[NativeSolution]) -> None:
|
|
245
245
|
"""Update internal history from a simulation result.
|
|
246
246
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
247
|
+
Slices ``solution.ys`` down to the integrated state variables (by name,
|
|
248
|
+
using ``solution.variable_names``) so delay lookups and ``initial_state``
|
|
249
|
+
see ``[n_time, len(STATE_NAMES), n_nodes]`` regardless of the dynamics'
|
|
250
|
+
VARIABLES_OF_INTEREST. Also warns if time coverage < max_delay.
|
|
251
251
|
|
|
252
252
|
Args:
|
|
253
|
-
solution:
|
|
253
|
+
solution: Solution from a previous simulation, or None to clear history.
|
|
254
|
+
Must carry ``variable_names`` — all solve() paths populate this.
|
|
254
255
|
|
|
255
256
|
Raises:
|
|
256
|
-
ValueError: If solution shape
|
|
257
|
+
ValueError: If the solution shape is not 3D, lacks ``variable_names``,
|
|
258
|
+
is missing any entry of ``dynamics.STATE_NAMES``, or has an
|
|
259
|
+
n_nodes mismatch with the graph.
|
|
257
260
|
"""
|
|
258
261
|
if solution is None:
|
|
259
262
|
self._history = None
|
|
260
263
|
return
|
|
261
264
|
|
|
262
|
-
# Validate shape
|
|
263
265
|
if solution.ys.ndim != 3:
|
|
264
266
|
raise ValueError(
|
|
265
|
-
f"History must be 3D [n_time,
|
|
267
|
+
f"History must be 3D [n_time, n_variables, n_nodes], "
|
|
266
268
|
f"got shape {solution.ys.shape}"
|
|
267
269
|
)
|
|
268
270
|
|
|
269
|
-
|
|
271
|
+
state_names = tuple(self.dynamics.STATE_NAMES)
|
|
270
272
|
n_nodes = self.graph.n_nodes
|
|
271
|
-
_,
|
|
273
|
+
_, hist_vars, hist_nodes = solution.ys.shape
|
|
274
|
+
variable_names = solution.variable_names
|
|
272
275
|
|
|
273
|
-
|
|
274
|
-
if hist_states != n_states:
|
|
276
|
+
if variable_names is None:
|
|
275
277
|
raise ValueError(
|
|
276
|
-
|
|
277
|
-
|
|
278
|
+
"Cannot update history: solution.variable_names is None. "
|
|
279
|
+
"Construct the solution via solve() or pass variable_names explicitly."
|
|
278
280
|
)
|
|
279
281
|
|
|
280
282
|
if hist_nodes != n_nodes:
|
|
@@ -282,7 +284,21 @@ class Network:
|
|
|
282
284
|
f"History has {hist_nodes} nodes but network has {n_nodes} nodes"
|
|
283
285
|
)
|
|
284
286
|
|
|
285
|
-
|
|
287
|
+
if hist_vars != len(variable_names):
|
|
288
|
+
raise ValueError(
|
|
289
|
+
f"History axis 1 has {hist_vars} entries but variable_names "
|
|
290
|
+
f"has {len(variable_names)}: {variable_names}"
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
missing = [name for name in state_names if name not in variable_names]
|
|
294
|
+
if missing:
|
|
295
|
+
raise ValueError(
|
|
296
|
+
f"Cannot update history: solution is missing state variables "
|
|
297
|
+
f"{missing}. Recorded variables: {variable_names}. "
|
|
298
|
+
f"Include all STATE_NAMES {state_names} in the dynamics' "
|
|
299
|
+
f"VARIABLES_OF_INTEREST before running the simulation."
|
|
300
|
+
)
|
|
301
|
+
|
|
286
302
|
if self.max_delay > 0.0:
|
|
287
303
|
time_coverage = solution.ts[-1] - solution.ts[0]
|
|
288
304
|
if time_coverage < self.max_delay:
|
|
@@ -292,7 +308,15 @@ class Network:
|
|
|
292
308
|
UserWarning,
|
|
293
309
|
)
|
|
294
310
|
|
|
295
|
-
|
|
311
|
+
state_cols = [variable_names.index(name) for name in state_names]
|
|
312
|
+
sliced_ys = solution.ys[:, jnp.array(state_cols, dtype=int), :]
|
|
313
|
+
|
|
314
|
+
self._history = NativeSolution(
|
|
315
|
+
ts=solution.ts,
|
|
316
|
+
ys=sliced_ys,
|
|
317
|
+
dt=getattr(solution, "dt", None),
|
|
318
|
+
variable_names=state_names,
|
|
319
|
+
)
|
|
296
320
|
|
|
297
321
|
def prepare(self, dt: float, t0: float, t1: float) -> tuple[Bunch, Bunch]:
|
|
298
322
|
"""Prepare all couplings for simulation.
|
{tvboptim-0.2.6 → tvboptim-0.2.8}/src/tvboptim/experimental/network_dynamics/dynamics/base.py
RENAMED
|
@@ -178,6 +178,30 @@ class AbstractDynamics(ABC):
|
|
|
178
178
|
else:
|
|
179
179
|
return jnp.broadcast_to(initial[:, None], (self.N_STATES, n_nodes))
|
|
180
180
|
|
|
181
|
+
def set_variables_of_interest(
|
|
182
|
+
self, variables_of_interest: Tuple[Union[str, int], ...]
|
|
183
|
+
) -> None:
|
|
184
|
+
"""Update which variables are recorded in the trajectory output.
|
|
185
|
+
|
|
186
|
+
Validates the new selection against STATE_NAMES + AUXILIARY_NAMES and
|
|
187
|
+
assigns it. Any previously prepared model captured the old selection
|
|
188
|
+
and must be rebuilt by calling ``prepare()`` again.
|
|
189
|
+
|
|
190
|
+
Args:
|
|
191
|
+
variables_of_interest: Tuple of variable names or indices to record.
|
|
192
|
+
Empty tuple means "record all state variables" (default behavior).
|
|
193
|
+
|
|
194
|
+
Raises:
|
|
195
|
+
ValueError: If any entry is not a valid name or in-range index.
|
|
196
|
+
"""
|
|
197
|
+
previous = self.VARIABLES_OF_INTEREST
|
|
198
|
+
self.VARIABLES_OF_INTEREST = tuple(variables_of_interest)
|
|
199
|
+
try:
|
|
200
|
+
self.get_variables_of_interest_indices()
|
|
201
|
+
except ValueError as e:
|
|
202
|
+
self.VARIABLES_OF_INTEREST = previous
|
|
203
|
+
raise ValueError(f"Invalid VARIABLES_OF_INTEREST: {e}")
|
|
204
|
+
|
|
181
205
|
def get_variables_of_interest_indices(self) -> Tuple[int, ...]:
|
|
182
206
|
"""Get indices of variables to record.
|
|
183
207
|
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""Result types for Network Dynamics native solvers.
|
|
2
|
+
|
|
3
|
+
This module provides Diffrax-like solution objects for native Network Dynamics solvers,
|
|
4
|
+
ensuring consistent API across solver types.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Optional, Tuple
|
|
8
|
+
|
|
9
|
+
import jax.numpy as jnp
|
|
10
|
+
from jax import tree_util
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@tree_util.register_pytree_node_class
|
|
14
|
+
class NativeSolution:
|
|
15
|
+
"""Solution object for Network Dynamics native solvers.
|
|
16
|
+
|
|
17
|
+
Provides the same interface as Diffrax solutions (.ys, .ts) while being
|
|
18
|
+
a proper JAX PyTree for compatibility with JAX transformations.
|
|
19
|
+
|
|
20
|
+
Attributes:
|
|
21
|
+
ts: Time points, shape [n_time]
|
|
22
|
+
ys: Trajectory data, shape [n_time, n_variables, n_nodes]
|
|
23
|
+
dt: Time step (optional), stored as static auxiliary data
|
|
24
|
+
variable_names: Names of the variables along axis 1 of ys, in order.
|
|
25
|
+
Contains state variables and/or auxiliary variables, depending on
|
|
26
|
+
the dynamics' VARIABLES_OF_INTEREST. None if unknown.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
ts: jnp.ndarray,
|
|
32
|
+
ys: jnp.ndarray,
|
|
33
|
+
dt: float = None,
|
|
34
|
+
variable_names: Optional[Tuple[str, ...]] = None,
|
|
35
|
+
):
|
|
36
|
+
"""Initialize native solution.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
ts: Time points, shape [n_time]
|
|
40
|
+
ys: Trajectory array, shape [n_time, n_variables, n_nodes]
|
|
41
|
+
dt: Time step (optional), stored as static auxiliary data for JIT compatibility
|
|
42
|
+
variable_names: Names of the variables along axis 1 of ys, in order.
|
|
43
|
+
"""
|
|
44
|
+
self.ts = ts
|
|
45
|
+
self.ys = ys
|
|
46
|
+
self.dt = dt
|
|
47
|
+
self.variable_names = (
|
|
48
|
+
tuple(variable_names) if variable_names is not None else None
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def time(self):
|
|
53
|
+
return self.ts
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def data(self):
|
|
57
|
+
return self.ys
|
|
58
|
+
|
|
59
|
+
def tree_flatten(self):
|
|
60
|
+
"""JAX PyTree flatten for transformations."""
|
|
61
|
+
children = (self.ts, self.ys)
|
|
62
|
+
aux_data = {"dt": self.dt, "variable_names": self.variable_names}
|
|
63
|
+
return children, aux_data
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def tree_unflatten(cls, aux_data, children):
|
|
67
|
+
"""JAX PyTree unflatten for transformations."""
|
|
68
|
+
ts, ys = children
|
|
69
|
+
dt = aux_data.get("dt") if aux_data else None
|
|
70
|
+
variable_names = aux_data.get("variable_names") if aux_data else None
|
|
71
|
+
return cls(ts, ys, dt=dt, variable_names=variable_names)
|
|
72
|
+
|
|
73
|
+
def __repr__(self):
|
|
74
|
+
"""String representation."""
|
|
75
|
+
return (
|
|
76
|
+
f"NativeSolution(shape={self.ys.shape}, "
|
|
77
|
+
f"t=[{self.ts[0]:.2f}, {self.ts[-1]:.2f}], "
|
|
78
|
+
f"variable_names={self.variable_names})"
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@tree_util.register_pytree_node_class
|
|
83
|
+
class DiffraxSolution(NativeSolution):
|
|
84
|
+
"""Solution wrapper for Diffrax solvers, compatible with NativeSolution interface.
|
|
85
|
+
|
|
86
|
+
Wraps a diffrax Solution object and exposes the NativeSolution interface
|
|
87
|
+
(.ts, .ys, .dt), while preserving access to the full diffrax solution via
|
|
88
|
+
``_solution`` (use this to reach ``.stats``, ``.result``, etc.).
|
|
89
|
+
|
|
90
|
+
Note: the Diffrax prepare path does not apply ``VARIABLES_OF_INTEREST``
|
|
91
|
+
filtering and discards auxiliaries, so ``ys`` always has shape
|
|
92
|
+
``[n_time, N_STATES, n_nodes]`` and ``variable_names`` always equals
|
|
93
|
+
``STATE_NAMES``. Use a native solver if you need VOI filtering or
|
|
94
|
+
auxiliary outputs.
|
|
95
|
+
|
|
96
|
+
Attributes:
|
|
97
|
+
_solution: The underlying diffrax Solution object
|
|
98
|
+
dt: Effective save time step inferred from saveat.ts at prepare time,
|
|
99
|
+
or None if saveat was not ts-based. Only meaningful for uniformly
|
|
100
|
+
spaced ``SaveAt(ts=...)``.
|
|
101
|
+
variable_names: Names of the variables along axis 1 of ys, in order.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
def __init__(
|
|
105
|
+
self,
|
|
106
|
+
solution,
|
|
107
|
+
dt=None,
|
|
108
|
+
variable_names: Optional[Tuple[str, ...]] = None,
|
|
109
|
+
):
|
|
110
|
+
self._solution = solution
|
|
111
|
+
self.dt = dt
|
|
112
|
+
self.variable_names = (
|
|
113
|
+
tuple(variable_names) if variable_names is not None else None
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def ts(self):
|
|
118
|
+
return self._solution.ts
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def ys(self):
|
|
122
|
+
return self._solution.ys
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def stats(self):
|
|
126
|
+
return self._solution.stats
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def result(self):
|
|
130
|
+
return self._solution.result
|
|
131
|
+
|
|
132
|
+
def tree_flatten(self):
|
|
133
|
+
children = (self._solution,)
|
|
134
|
+
aux_data = {"dt": self.dt, "variable_names": self.variable_names}
|
|
135
|
+
return children, aux_data
|
|
136
|
+
|
|
137
|
+
@classmethod
|
|
138
|
+
def tree_unflatten(cls, aux_data, children):
|
|
139
|
+
return cls(
|
|
140
|
+
children[0],
|
|
141
|
+
dt=aux_data.get("dt"),
|
|
142
|
+
variable_names=aux_data.get("variable_names"),
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
def __repr__(self):
|
|
146
|
+
return (
|
|
147
|
+
f"DiffraxSolution(shape={self.ys.shape}, "
|
|
148
|
+
f"t=[{self.ts[0]:.2f}, {self.ts[-1]:.2f}], dt={self.dt}, "
|
|
149
|
+
f"variable_names={self.variable_names})"
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def wrap_native_result(
|
|
154
|
+
trajectory: jnp.ndarray,
|
|
155
|
+
t0: float,
|
|
156
|
+
t1: float,
|
|
157
|
+
dt: float,
|
|
158
|
+
variable_names: Optional[Tuple[str, ...]] = None,
|
|
159
|
+
) -> NativeSolution:
|
|
160
|
+
"""Wrap native solver trajectory in solution object.
|
|
161
|
+
|
|
162
|
+
Args:
|
|
163
|
+
trajectory: Trajectory array from native solver, shape [n_time, n_variables, n_nodes]
|
|
164
|
+
t0: Start time
|
|
165
|
+
t1: End time
|
|
166
|
+
dt: Time step
|
|
167
|
+
variable_names: Names of the variables along axis 1 of trajectory, in order.
|
|
168
|
+
|
|
169
|
+
Returns:
|
|
170
|
+
NativeSolution with .ys, .ts, and .variable_names attributes like Diffrax
|
|
171
|
+
"""
|
|
172
|
+
n_steps = trajectory.shape[0]
|
|
173
|
+
# Native solvers scan over time_steps = arange(t0, t1, dt) and emit the
|
|
174
|
+
# post-step state on each iteration. Trajectory[i] is therefore the state
|
|
175
|
+
# at time t0 + (i + 1) * dt, so the save grid runs (t0, t1] with the
|
|
176
|
+
# endpoint t1 included and the initial state t0 excluded.
|
|
177
|
+
ts = t0 + (jnp.arange(n_steps) + 1) * dt
|
|
178
|
+
return NativeSolution(ts=ts, ys=trajectory, dt=dt, variable_names=variable_names)
|