tvboptim 0.2.5__tar.gz → 0.2.7__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.5/src/tvboptim.egg-info → tvboptim-0.2.7}/PKG-INFO +1 -1
- {tvboptim-0.2.5 → tvboptim-0.2.7}/pyproject.toml +1 -1
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/execution.py +52 -5
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/analysis/lyapunov.py +19 -17
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/core/bunch.py +13 -7
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/solve.py +23 -8
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/solvers/native.py +2 -2
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/types/spaces.py +224 -29
- {tvboptim-0.2.5 → tvboptim-0.2.7/src/tvboptim.egg-info}/PKG-INFO +1 -1
- {tvboptim-0.2.5 → tvboptim-0.2.7}/tests/test_execution.py +119 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/LICENSE +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/README.md +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/setup.cfg +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/data/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/data/connectivity/dTOR/data.npz +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/data/connectivity/dk_average/data.npz +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/data/functional/dk_average/data.npz +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/data/loaders.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/data/plotting/dk_average/aparc+aseg-mni_09c.nii.gz +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/data/plotting/dk_average/fs_default.txt +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/data/plotting/dk_average/fs_default_freesurfer_idx.csv +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/analysis/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/core/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/core/network.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/coupling/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/coupling/base.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/coupling/linear.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/coupling/subspace.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/coupling/tvb.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/base.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/lorenz.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/coombes_byrne.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/epileptor.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/generic_2d_oscillator.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/jansen_rit.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/kuramoto.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/larter_breakspear.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/linear.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/montbrio_pazo_roxin.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/sup_hopf.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wilson_cowan.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang_exc_inh.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/external_input/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/external_input/base.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/external_input/data.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/external_input/parametric.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/graph/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/graph/base.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/graph/sparse.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/graph/utils.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/noise/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/noise/base.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/noise/gaussian.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/result.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/solvers/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/solvers/base.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/solvers/diffrax.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/utils/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/utils/history.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/utils/printer.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/observations/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/observations/observation.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/observations/tvb_monitors/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/observations/tvb_monitors/bold.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/observations/tvb_monitors/downsampling.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/optim/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/optim/callbacks.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/optim/optax.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/tvbo/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/tvbo/prepare_experiment.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/types/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/types/parameter.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/types/stateutils.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/utils/__init__.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/utils/caching.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/utils/utils.py +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim.egg-info/SOURCES.txt +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim.egg-info/dependency_links.txt +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim.egg-info/requires.txt +0 -0
- {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim.egg-info/top_level.txt +0 -0
|
@@ -2,8 +2,11 @@ from abc import ABC
|
|
|
2
2
|
|
|
3
3
|
import jax
|
|
4
4
|
import jax.numpy as jnp
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
5
7
|
from tqdm import tqdm
|
|
6
8
|
|
|
9
|
+
from tvboptim.types.spaces import _keypath_to_name
|
|
7
10
|
from tvboptim.types.stateutils import combine_state
|
|
8
11
|
|
|
9
12
|
|
|
@@ -16,7 +19,24 @@ class Result(ABC):
|
|
|
16
19
|
Result type to provide unified indexing
|
|
17
20
|
"""
|
|
18
21
|
|
|
19
|
-
|
|
22
|
+
space = None
|
|
23
|
+
|
|
24
|
+
def _result_col_names(self, param_cols) -> list:
|
|
25
|
+
"""Derive result column names from the first result, handling collisions."""
|
|
26
|
+
sample = self[0]
|
|
27
|
+
paths_and_leaves, _ = jax.tree_util.tree_flatten_with_path(sample)
|
|
28
|
+
col_names = [_keypath_to_name(p) for p, _ in paths_and_leaves]
|
|
29
|
+
for i, name in enumerate(col_names):
|
|
30
|
+
if name in param_cols:
|
|
31
|
+
col_names[i] = f"result.{name}"
|
|
32
|
+
return col_names
|
|
33
|
+
|
|
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)
|
|
39
|
+
return df
|
|
20
40
|
|
|
21
41
|
|
|
22
42
|
class SequentialExecution(Execution):
|
|
@@ -95,12 +115,13 @@ class SequentialExecution(Execution):
|
|
|
95
115
|
jax.block_until_ready(self.model(state, *self.args, **self.kwargs))
|
|
96
116
|
)
|
|
97
117
|
# results.append(jax.block_until_ready(self.model(state, *self.args, **self.kwargs)))
|
|
98
|
-
return SequentialResult(results)
|
|
118
|
+
return SequentialResult(results, space=self.statespace)
|
|
99
119
|
|
|
100
120
|
|
|
101
121
|
class SequentialResult(Result):
|
|
102
|
-
def __init__(self, results):
|
|
122
|
+
def __init__(self, results, space=None):
|
|
103
123
|
self.results = results
|
|
124
|
+
self.space = space
|
|
104
125
|
|
|
105
126
|
def __iter__(self):
|
|
106
127
|
return iter(self.results)
|
|
@@ -111,6 +132,15 @@ class SequentialResult(Result):
|
|
|
111
132
|
def __len__(self):
|
|
112
133
|
return len(self.results)
|
|
113
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
|
+
|
|
114
144
|
|
|
115
145
|
class ParallelExecution(Execution):
|
|
116
146
|
"""
|
|
@@ -215,13 +245,16 @@ class ParallelExecution(Execution):
|
|
|
215
245
|
res = jax.block_until_ready(
|
|
216
246
|
jax.pmap(self.map_model, in_axes=0)(self.diff_state)
|
|
217
247
|
)
|
|
218
|
-
return ParallelResult(
|
|
248
|
+
return ParallelResult(
|
|
249
|
+
res, self.space.N, self.n_vmap, self.n_pmap, space=self.space
|
|
250
|
+
)
|
|
219
251
|
|
|
220
252
|
|
|
221
253
|
class ParallelResult(Result):
|
|
222
|
-
def __init__(self, results, N, n_vmap, n_pmap):
|
|
254
|
+
def __init__(self, results, N, n_vmap, n_pmap, space=None):
|
|
223
255
|
self.results = results
|
|
224
256
|
self.N = N
|
|
257
|
+
self.space = space
|
|
225
258
|
self.n_vmap = n_vmap
|
|
226
259
|
self.n_pmap = n_pmap
|
|
227
260
|
|
|
@@ -266,3 +299,17 @@ class ParallelResult(Result):
|
|
|
266
299
|
return leaf[pmap_idx, second_dim_idx]
|
|
267
300
|
|
|
268
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.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/analysis/lyapunov.py
RENAMED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import jax
|
|
2
2
|
import jax.numpy as jnp
|
|
3
|
-
|
|
4
|
-
from ..core.bunch import Bunch
|
|
3
|
+
|
|
5
4
|
from .. import prepare
|
|
5
|
+
from ..core.bunch import Bunch
|
|
6
|
+
from ..solvers import Heun
|
|
6
7
|
|
|
7
8
|
|
|
8
9
|
def lyapunov(network, solver=None, t=1000.0, n=10, d0=1e-9, dt=0.1, t0=0.0):
|
|
@@ -42,13 +43,13 @@ def lyapunov(network, solver=None, t=1000.0, n=10, d0=1e-9, dt=0.1, t0=0.0):
|
|
|
42
43
|
|
|
43
44
|
def _lyapunov(solve_fn, config, t, n=10, d0=1e-9):
|
|
44
45
|
"""Low-level MLE estimation using a pre-built solve_fn / config."""
|
|
45
|
-
u_init = config.initial_state.dynamics
|
|
46
|
+
u_init = config.initial_state.dynamics # [n_states, n_nodes]
|
|
46
47
|
D = u_init.size
|
|
47
48
|
u2_init = u_init + d0 / jnp.sqrt(D)
|
|
48
49
|
|
|
49
50
|
def _solve_from(u):
|
|
50
|
-
new_is = Bunch({**config.initial_state,
|
|
51
|
-
new_cfg = Bunch({**config,
|
|
51
|
+
new_is = Bunch({**config.initial_state, "dynamics": u})
|
|
52
|
+
new_cfg = Bunch({**config, "initial_state": new_is})
|
|
52
53
|
return solve_fn(new_cfg).ys[-1]
|
|
53
54
|
|
|
54
55
|
@jax.jit
|
|
@@ -70,8 +71,9 @@ def _lyapunov(solve_fn, config, t, n=10, d0=1e-9):
|
|
|
70
71
|
return float(log_sum / (n * t))
|
|
71
72
|
|
|
72
73
|
|
|
73
|
-
def lyapunov_spectrum(
|
|
74
|
-
|
|
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
|
+
):
|
|
75
77
|
"""
|
|
76
78
|
Estimate the Lyapunov spectrum of a network.
|
|
77
79
|
|
|
@@ -116,8 +118,8 @@ def _lyapunov_spectrum_sim(solve_fn, config, t, n=10, k=None, d0=1e-9):
|
|
|
116
118
|
|
|
117
119
|
def _solve_flat(u_flat):
|
|
118
120
|
u = u_flat.reshape(shape)
|
|
119
|
-
new_is = Bunch({**config.initial_state,
|
|
120
|
-
new_cfg = Bunch({**config,
|
|
121
|
+
new_is = Bunch({**config.initial_state, "dynamics": u})
|
|
122
|
+
new_cfg = Bunch({**config, "initial_state": new_is})
|
|
121
123
|
return solve_fn(new_cfg).ys[-1].flatten()
|
|
122
124
|
|
|
123
125
|
@jax.jit
|
|
@@ -125,10 +127,10 @@ def _lyapunov_spectrum_sim(solve_fn, config, t, n=10, k=None, d0=1e-9):
|
|
|
125
127
|
def _step(carry, _):
|
|
126
128
|
u_flat, Q, log_sum = carry
|
|
127
129
|
new_u = _solve_flat(u_flat)
|
|
128
|
-
perturbed = u_flat + d0 * Q.T
|
|
129
|
-
new_perturbed = jax.vmap(_solve_flat)(perturbed)
|
|
130
|
-
delta = (new_perturbed - new_u) / d0
|
|
131
|
-
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]
|
|
132
134
|
log_sum = log_sum + jnp.log(jnp.abs(jnp.diag(R)))
|
|
133
135
|
return (new_u, Q_new, log_sum), None
|
|
134
136
|
|
|
@@ -151,8 +153,8 @@ def _lyapunov_spectrum_jvp(solve_fn, config, t, n=10, k=None):
|
|
|
151
153
|
|
|
152
154
|
def _solve_flat(u_flat):
|
|
153
155
|
u = u_flat.reshape(shape)
|
|
154
|
-
new_is = Bunch({**config.initial_state,
|
|
155
|
-
new_cfg = Bunch({**config,
|
|
156
|
+
new_is = Bunch({**config.initial_state, "dynamics": u})
|
|
157
|
+
new_cfg = Bunch({**config, "initial_state": new_is})
|
|
156
158
|
return solve_fn(new_cfg).ys[-1].flatten()
|
|
157
159
|
|
|
158
160
|
@jax.jit
|
|
@@ -160,8 +162,8 @@ def _lyapunov_spectrum_jvp(solve_fn, config, t, n=10, k=None):
|
|
|
160
162
|
def _step(carry, _):
|
|
161
163
|
u_flat, Q, log_sum = carry
|
|
162
164
|
new_u, jvp_fn = jax.linearize(_solve_flat, u_flat)
|
|
163
|
-
tangents = jax.vmap(jvp_fn)(Q.T)
|
|
164
|
-
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]
|
|
165
167
|
log_sum = log_sum + jnp.log(jnp.abs(jnp.diag(R)))
|
|
166
168
|
return (new_u, Q_new, log_sum), None
|
|
167
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
|
+
)
|
|
@@ -340,7 +340,9 @@ def prepare(
|
|
|
340
340
|
|
|
341
341
|
n_nodes = network.graph.n_nodes
|
|
342
342
|
|
|
343
|
-
def compute_all_couplings(
|
|
343
|
+
def compute_all_couplings(
|
|
344
|
+
t, network_state, coupling_state_dict, config, coupling_data_dict
|
|
345
|
+
):
|
|
344
346
|
"""Pre-compiled closure for coupling computation.
|
|
345
347
|
|
|
346
348
|
Avoids method calls and dict iterations in scan loop.
|
|
@@ -361,7 +363,12 @@ def prepare(
|
|
|
361
363
|
data = coupling_data_dict[name]
|
|
362
364
|
state_data = coupling_state_dict[name]
|
|
363
365
|
coupling_inputs[name] = coupling.compute(
|
|
364
|
-
t,
|
|
366
|
+
t,
|
|
367
|
+
network_state,
|
|
368
|
+
data,
|
|
369
|
+
state_data,
|
|
370
|
+
config.coupling[name],
|
|
371
|
+
config.graph,
|
|
365
372
|
)
|
|
366
373
|
|
|
367
374
|
return coupling_inputs
|
|
@@ -375,7 +382,9 @@ def prepare(
|
|
|
375
382
|
for name in network.coupling.keys()
|
|
376
383
|
]
|
|
377
384
|
|
|
378
|
-
def update_all_coupling_states(
|
|
385
|
+
def update_all_coupling_states(
|
|
386
|
+
coupling_state_dict, new_network_state, coupling_data_dict
|
|
387
|
+
):
|
|
379
388
|
"""Pre-compiled closure for coupling state updates.
|
|
380
389
|
|
|
381
390
|
Avoids method calls and dict iterations in scan loop.
|
|
@@ -924,7 +933,12 @@ def prepare(
|
|
|
924
933
|
data = coupling_data_dict[name]
|
|
925
934
|
empty_state = Bunch()
|
|
926
935
|
coupling_inputs[name] = coupling.compute(
|
|
927
|
-
t,
|
|
936
|
+
t,
|
|
937
|
+
network_state,
|
|
938
|
+
data,
|
|
939
|
+
empty_state,
|
|
940
|
+
config.coupling[name],
|
|
941
|
+
config.graph,
|
|
928
942
|
)
|
|
929
943
|
|
|
930
944
|
return coupling_inputs
|
|
@@ -1069,7 +1083,9 @@ def prepare(
|
|
|
1069
1083
|
external_inputs = compute_all_externals(t, y, config)
|
|
1070
1084
|
|
|
1071
1085
|
# Call dynamics
|
|
1072
|
-
result = dynamics_fn(
|
|
1086
|
+
result = dynamics_fn(
|
|
1087
|
+
t, y, config.dynamics, coupling_inputs, external_inputs
|
|
1088
|
+
)
|
|
1073
1089
|
|
|
1074
1090
|
# Extract derivatives (discard auxiliaries if present)
|
|
1075
1091
|
if isinstance(result, tuple):
|
|
@@ -1279,9 +1295,7 @@ def prepare(
|
|
|
1279
1295
|
)
|
|
1280
1296
|
else:
|
|
1281
1297
|
ext_inputs = zero_external
|
|
1282
|
-
return dynamics_fn(
|
|
1283
|
-
t_inner, s, params, zero_coupling, ext_inputs
|
|
1284
|
-
)
|
|
1298
|
+
return dynamics_fn(t_inner, s, params, zero_coupling, ext_inputs)
|
|
1285
1299
|
|
|
1286
1300
|
# Noise
|
|
1287
1301
|
if has_noise:
|
|
@@ -1486,6 +1500,7 @@ def prepare(
|
|
|
1486
1500
|
drift_term = diffrax.ODETerm(vector_field)
|
|
1487
1501
|
|
|
1488
1502
|
if has_noise:
|
|
1503
|
+
|
|
1489
1504
|
def diffusion_vector_field(t, y, args):
|
|
1490
1505
|
return compute_diffusion_matrix(t, y, config.noise)
|
|
1491
1506
|
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/solvers/native.py
RENAMED
|
@@ -267,9 +267,9 @@ class BoundedSolver(NativeSolver):
|
|
|
267
267
|
high: float | jnp.ndarray = jnp.inf,
|
|
268
268
|
):
|
|
269
269
|
self.base_solver = base_solver
|
|
270
|
-
low
|
|
270
|
+
low = jnp.asarray(low)
|
|
271
271
|
high = jnp.asarray(high)
|
|
272
|
-
self.low
|
|
272
|
+
self.low = low[:, None] if low.ndim == 1 else low
|
|
273
273
|
self.high = high[:, None] if high.ndim == 1 else high
|
|
274
274
|
|
|
275
275
|
def step(
|
|
@@ -40,9 +40,36 @@ import equinox as eqx
|
|
|
40
40
|
import jax
|
|
41
41
|
import jax.numpy as jnp
|
|
42
42
|
import numpy as np
|
|
43
|
+
import pandas as pd
|
|
43
44
|
|
|
44
45
|
from tvboptim.utils import safe_reshape
|
|
45
46
|
|
|
47
|
+
|
|
48
|
+
def _keypath_to_name(keypath):
|
|
49
|
+
"""Convert a JAX KeyPath to a readable dot-separated column name.
|
|
50
|
+
|
|
51
|
+
Examples
|
|
52
|
+
--------
|
|
53
|
+
>>> # DictKey / GetAttrKey use dot notation
|
|
54
|
+
>>> # (DictKey('model'), DictKey('G')) → 'model.G'
|
|
55
|
+
>>> # SequenceKey uses bracket notation
|
|
56
|
+
>>> # (DictKey('results'), SequenceKey(0)) → 'results[0]'
|
|
57
|
+
>>> # (SequenceKey(0), DictKey('amplitude')) → '[0].amplitude'
|
|
58
|
+
"""
|
|
59
|
+
parts = []
|
|
60
|
+
for key in keypath:
|
|
61
|
+
if hasattr(key, "key"): # DictKey
|
|
62
|
+
parts.append(f".{key.key}")
|
|
63
|
+
elif hasattr(key, "idx"): # SequenceKey
|
|
64
|
+
parts.append(f"[{key.idx}]")
|
|
65
|
+
elif hasattr(key, "name"): # GetAttrKey (namedtuple)
|
|
66
|
+
parts.append(f".{key.name}")
|
|
67
|
+
else:
|
|
68
|
+
parts.append(f".{key}")
|
|
69
|
+
name = "".join(parts).lstrip(".")
|
|
70
|
+
return name if name else "value"
|
|
71
|
+
|
|
72
|
+
|
|
46
73
|
try:
|
|
47
74
|
import numpyro.distributions # noqa: F401
|
|
48
75
|
|
|
@@ -94,9 +121,17 @@ class AbstractAxis(ABC):
|
|
|
94
121
|
>>> print(f"Normal samples: {values}")
|
|
95
122
|
"""
|
|
96
123
|
|
|
97
|
-
def __init__(self):
|
|
98
|
-
"""Initialize axis.
|
|
99
|
-
|
|
124
|
+
def __init__(self, group=None):
|
|
125
|
+
"""Initialize axis.
|
|
126
|
+
|
|
127
|
+
Parameters
|
|
128
|
+
----------
|
|
129
|
+
group : hashable, optional
|
|
130
|
+
Group label. Axes sharing the same group are zipped together
|
|
131
|
+
into a single composite axis before the Space's combination
|
|
132
|
+
mode is applied. Default is None (ungrouped).
|
|
133
|
+
"""
|
|
134
|
+
self.group = group
|
|
100
135
|
|
|
101
136
|
@abstractmethod
|
|
102
137
|
def generate_values(self, key: Optional[jax.random.PRNGKey] = None) -> jnp.ndarray:
|
|
@@ -160,7 +195,12 @@ class GridAxis(AbstractAxis):
|
|
|
160
195
|
"""
|
|
161
196
|
|
|
162
197
|
def __init__(
|
|
163
|
-
self,
|
|
198
|
+
self,
|
|
199
|
+
low: float,
|
|
200
|
+
high: float,
|
|
201
|
+
n: int,
|
|
202
|
+
shape: Optional[Tuple[int, ...]] = None,
|
|
203
|
+
group=None,
|
|
164
204
|
):
|
|
165
205
|
"""Initialize grid axis.
|
|
166
206
|
|
|
@@ -175,8 +215,10 @@ class GridAxis(AbstractAxis):
|
|
|
175
215
|
shape : Tuple[int, ...], optional
|
|
176
216
|
Shape of generated values. If specified, values are broadcast to this shape.
|
|
177
217
|
Default is None.
|
|
218
|
+
group : hashable, optional
|
|
219
|
+
Group label for axis grouping. See AbstractAxis. Default is None.
|
|
178
220
|
"""
|
|
179
|
-
super().__init__()
|
|
221
|
+
super().__init__(group=group)
|
|
180
222
|
self.low = low
|
|
181
223
|
self.high = high
|
|
182
224
|
self.n = n
|
|
@@ -253,7 +295,12 @@ class LogGridAxis(AbstractAxis):
|
|
|
253
295
|
"""
|
|
254
296
|
|
|
255
297
|
def __init__(
|
|
256
|
-
self,
|
|
298
|
+
self,
|
|
299
|
+
low: float,
|
|
300
|
+
high: float,
|
|
301
|
+
n: int,
|
|
302
|
+
shape: Optional[Tuple[int, ...]] = None,
|
|
303
|
+
group=None,
|
|
257
304
|
):
|
|
258
305
|
"""Initialize log grid axis.
|
|
259
306
|
|
|
@@ -268,8 +315,10 @@ class LogGridAxis(AbstractAxis):
|
|
|
268
315
|
shape : Tuple[int, ...], optional
|
|
269
316
|
Shape of generated values. If specified, values are broadcast to this shape.
|
|
270
317
|
Default is None.
|
|
318
|
+
group : hashable, optional
|
|
319
|
+
Group label for axis grouping. See AbstractAxis. Default is None.
|
|
271
320
|
"""
|
|
272
|
-
super().__init__()
|
|
321
|
+
super().__init__(group=group)
|
|
273
322
|
self.low = low
|
|
274
323
|
self.high = high
|
|
275
324
|
self.n = n
|
|
@@ -350,7 +399,12 @@ class UniformAxis(AbstractAxis):
|
|
|
350
399
|
"""
|
|
351
400
|
|
|
352
401
|
def __init__(
|
|
353
|
-
self,
|
|
402
|
+
self,
|
|
403
|
+
low: float,
|
|
404
|
+
high: float,
|
|
405
|
+
n: int,
|
|
406
|
+
shape: Optional[Tuple[int, ...]] = None,
|
|
407
|
+
group=None,
|
|
354
408
|
):
|
|
355
409
|
"""Initialize uniform axis.
|
|
356
410
|
|
|
@@ -365,8 +419,10 @@ class UniformAxis(AbstractAxis):
|
|
|
365
419
|
shape : Tuple[int, ...], optional
|
|
366
420
|
Shape of generated values. If specified, values are broadcast to this shape.
|
|
367
421
|
Default is None.
|
|
422
|
+
group : hashable, optional
|
|
423
|
+
Group label for axis grouping. See AbstractAxis. Default is None.
|
|
368
424
|
"""
|
|
369
|
-
super().__init__()
|
|
425
|
+
super().__init__(group=group)
|
|
370
426
|
self.low = low
|
|
371
427
|
self.high = high
|
|
372
428
|
self.n = n
|
|
@@ -445,15 +501,17 @@ class DataAxis(AbstractAxis):
|
|
|
445
501
|
>>> print(data_jax.size) # 5
|
|
446
502
|
"""
|
|
447
503
|
|
|
448
|
-
def __init__(self, values: Union[List, jnp.ndarray]):
|
|
504
|
+
def __init__(self, values: Union[List, jnp.ndarray], group=None):
|
|
449
505
|
"""Initialize data axis.
|
|
450
506
|
|
|
451
507
|
Parameters
|
|
452
508
|
----------
|
|
453
509
|
values : array-like
|
|
454
510
|
Predefined values to sample from.
|
|
511
|
+
group : hashable, optional
|
|
512
|
+
Group label for axis grouping. See AbstractAxis. Default is None.
|
|
455
513
|
"""
|
|
456
|
-
super().__init__()
|
|
514
|
+
super().__init__(group=group)
|
|
457
515
|
self.values = jnp.asarray(values)
|
|
458
516
|
|
|
459
517
|
if self.values.size == 0:
|
|
@@ -546,6 +604,7 @@ class NumPyroAxis(AbstractAxis):
|
|
|
546
604
|
n: int,
|
|
547
605
|
sample_shape: Optional[Tuple[int, ...]] = None,
|
|
548
606
|
broadcast_mode: bool = False,
|
|
607
|
+
group=None,
|
|
549
608
|
):
|
|
550
609
|
"""Initialize NumPyro distribution axis.
|
|
551
610
|
|
|
@@ -560,8 +619,10 @@ class NumPyroAxis(AbstractAxis):
|
|
|
560
619
|
broadcast_mode : bool, optional
|
|
561
620
|
If True, sample once per axis point then broadcast to sample_shape.
|
|
562
621
|
If False, sample independently for each element. Default is False.
|
|
622
|
+
group : hashable, optional
|
|
623
|
+
Group label for axis grouping. See AbstractAxis. Default is None.
|
|
563
624
|
"""
|
|
564
|
-
super().__init__()
|
|
625
|
+
super().__init__(group=group)
|
|
565
626
|
|
|
566
627
|
if not NUMPYRO_AVAILABLE:
|
|
567
628
|
raise ImportError(
|
|
@@ -735,6 +796,38 @@ class Space:
|
|
|
735
796
|
# Calculate total combinations
|
|
736
797
|
self._N = self._calculate_total_size()
|
|
737
798
|
|
|
799
|
+
def _get_effective_sizes(self, axes):
|
|
800
|
+
"""Compute effective axis sizes accounting for groups.
|
|
801
|
+
|
|
802
|
+
Axes sharing a group label are zipped together into a single
|
|
803
|
+
composite axis. Returns one effective size per group plus one
|
|
804
|
+
per ungrouped axis.
|
|
805
|
+
"""
|
|
806
|
+
from collections import OrderedDict
|
|
807
|
+
|
|
808
|
+
groups = OrderedDict() # group_label -> list of sizes
|
|
809
|
+
ungrouped_sizes = []
|
|
810
|
+
|
|
811
|
+
for axis in axes:
|
|
812
|
+
if axis.group is not None:
|
|
813
|
+
groups.setdefault(axis.group, []).append(axis.size)
|
|
814
|
+
else:
|
|
815
|
+
ungrouped_sizes.append(axis.size)
|
|
816
|
+
|
|
817
|
+
effective_sizes = []
|
|
818
|
+
for group_label, sizes in groups.items():
|
|
819
|
+
min_s = min(sizes)
|
|
820
|
+
max_s = max(sizes)
|
|
821
|
+
if min_s != max_s:
|
|
822
|
+
print(
|
|
823
|
+
f"WARNING: Axes in group '{group_label}' have different sizes "
|
|
824
|
+
f"{sizes}. Using minimum size {min_s}."
|
|
825
|
+
)
|
|
826
|
+
effective_sizes.append(min_s)
|
|
827
|
+
|
|
828
|
+
effective_sizes.extend(ungrouped_sizes)
|
|
829
|
+
return effective_sizes
|
|
830
|
+
|
|
738
831
|
def _calculate_total_size(self) -> int:
|
|
739
832
|
"""Calculate total number of parameter combinations."""
|
|
740
833
|
axes = jax.tree.leaves(
|
|
@@ -744,20 +837,20 @@ class Space:
|
|
|
744
837
|
if not axes:
|
|
745
838
|
return 1
|
|
746
839
|
|
|
747
|
-
|
|
840
|
+
effective_sizes = self._get_effective_sizes(axes)
|
|
748
841
|
|
|
749
842
|
if self.mode == "product":
|
|
750
|
-
return int(np.prod(
|
|
843
|
+
return int(np.prod(effective_sizes))
|
|
751
844
|
elif self.mode == "zip":
|
|
752
|
-
min_size = min(
|
|
753
|
-
max_size = max(
|
|
845
|
+
min_size = min(effective_sizes)
|
|
846
|
+
max_size = max(effective_sizes)
|
|
754
847
|
|
|
755
|
-
# Warn if axes have different sizes in zip mode
|
|
756
848
|
if min_size != max_size:
|
|
757
|
-
lost_combinations = sum(size - min_size for size in
|
|
849
|
+
lost_combinations = sum(size - min_size for size in effective_sizes)
|
|
758
850
|
print(
|
|
759
|
-
f"WARNING: In zip mode, axes have different sizes
|
|
760
|
-
f"Using minimum size {min_size},
|
|
851
|
+
f"WARNING: In zip mode, effective axes have different sizes "
|
|
852
|
+
f"{effective_sizes}. Using minimum size {min_size}, "
|
|
853
|
+
f"losing {lost_combinations} combinations."
|
|
761
854
|
)
|
|
762
855
|
|
|
763
856
|
return min_size
|
|
@@ -812,15 +905,74 @@ class Space:
|
|
|
812
905
|
if not axis_values_list:
|
|
813
906
|
return [], axis_tree_def
|
|
814
907
|
|
|
908
|
+
# Get axes in same flat order to read group labels
|
|
909
|
+
axes_flat = jax.tree.leaves(
|
|
910
|
+
self.axis_state, is_leaf=lambda x: isinstance(x, AbstractAxis)
|
|
911
|
+
)
|
|
912
|
+
|
|
913
|
+
# Check if any groups exist — fast path if not
|
|
914
|
+
has_groups = any(a.group is not None for a in axes_flat)
|
|
915
|
+
|
|
916
|
+
if not has_groups:
|
|
917
|
+
# Original ungrouped logic
|
|
918
|
+
if self.mode == "product":
|
|
919
|
+
meshgrid_arrays = jnp.meshgrid(*axis_values_list, indexing="ij")
|
|
920
|
+
flattened_arrays = [arr.flatten() for arr in meshgrid_arrays]
|
|
921
|
+
elif self.mode == "zip":
|
|
922
|
+
flattened_arrays = axis_values_list
|
|
923
|
+
return flattened_arrays, axis_tree_def
|
|
924
|
+
|
|
925
|
+
# --- Grouped logic ---
|
|
926
|
+
from collections import OrderedDict
|
|
927
|
+
|
|
928
|
+
# Partition axes into groups and ungrouped
|
|
929
|
+
group_map = OrderedDict() # group_label -> [(flat_idx, values), ...]
|
|
930
|
+
ungrouped = [] # [(flat_idx, values), ...]
|
|
931
|
+
|
|
932
|
+
for i, (axis, values) in enumerate(zip(axes_flat, axis_values_list)):
|
|
933
|
+
if axis.group is not None:
|
|
934
|
+
group_map.setdefault(axis.group, []).append((i, values))
|
|
935
|
+
else:
|
|
936
|
+
ungrouped.append((i, values))
|
|
937
|
+
|
|
938
|
+
# Build effective axes: one representative per group + one per ungrouped
|
|
939
|
+
effective_values = []
|
|
940
|
+
# Each entry: ('group', [(orig_idx, truncated_values), ...])
|
|
941
|
+
# or ('single', orig_idx)
|
|
942
|
+
effective_meta = []
|
|
943
|
+
|
|
944
|
+
for group_label, members in group_map.items():
|
|
945
|
+
sizes = [v.shape[0] for _, v in members]
|
|
946
|
+
eff_size = min(sizes)
|
|
947
|
+
truncated = [(idx, v[:eff_size]) for idx, v in members]
|
|
948
|
+
# Use index array as representative for meshgrid
|
|
949
|
+
effective_values.append(jnp.arange(eff_size))
|
|
950
|
+
effective_meta.append(("group", truncated))
|
|
951
|
+
|
|
952
|
+
for idx, values in ungrouped:
|
|
953
|
+
effective_values.append(values)
|
|
954
|
+
effective_meta.append(("single", idx))
|
|
955
|
+
|
|
956
|
+
# Apply combination mode on effective axes
|
|
815
957
|
if self.mode == "product":
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
flattened_arrays = [arr.flatten() for arr in meshgrid_arrays]
|
|
958
|
+
meshgrid_arrays = jnp.meshgrid(*effective_values, indexing="ij")
|
|
959
|
+
flat_effective = [arr.flatten() for arr in meshgrid_arrays]
|
|
819
960
|
elif self.mode == "zip":
|
|
820
|
-
|
|
821
|
-
|
|
961
|
+
flat_effective = effective_values
|
|
962
|
+
|
|
963
|
+
# Expand back to original flat ordering
|
|
964
|
+
result = [None] * len(axis_values_list)
|
|
965
|
+
|
|
966
|
+
for eff_idx, (meta, combined) in enumerate(zip(effective_meta, flat_effective)):
|
|
967
|
+
kind, payload = meta
|
|
968
|
+
if kind == "group":
|
|
969
|
+
index_array = combined.astype(jnp.int32)
|
|
970
|
+
for orig_idx, truncated_values in payload:
|
|
971
|
+
result[orig_idx] = truncated_values[index_array]
|
|
972
|
+
else: # 'single'
|
|
973
|
+
result[payload] = combined
|
|
822
974
|
|
|
823
|
-
return
|
|
975
|
+
return result, axis_tree_def
|
|
824
976
|
|
|
825
977
|
def _get_combination_at_index(self, index: int) -> Dict[str, Any]:
|
|
826
978
|
"""Get a single combination by indexing into flattened arrays."""
|
|
@@ -931,8 +1083,14 @@ class Space:
|
|
|
931
1083
|
f"Slice {index} results in empty parameter space with no combinations"
|
|
932
1084
|
)
|
|
933
1085
|
|
|
934
|
-
# Create new axis state with DataAxis instances
|
|
935
|
-
|
|
1086
|
+
# Create new axis state with DataAxis instances, preserving groups
|
|
1087
|
+
axes_flat = jax.tree.leaves(
|
|
1088
|
+
self.axis_state, is_leaf=lambda x: isinstance(x, AbstractAxis)
|
|
1089
|
+
)
|
|
1090
|
+
data_axes = [
|
|
1091
|
+
DataAxis(values, group=axis.group)
|
|
1092
|
+
for values, axis in zip(sliced_arrays, axes_flat)
|
|
1093
|
+
]
|
|
936
1094
|
new_axis_state = jax.tree.unflatten(axis_tree_def, data_axes)
|
|
937
1095
|
|
|
938
1096
|
# Create new Space in zip mode
|
|
@@ -1038,8 +1196,45 @@ class Space:
|
|
|
1038
1196
|
else:
|
|
1039
1197
|
return batched_axis_tree, self.static_state
|
|
1040
1198
|
|
|
1199
|
+
def to_dataframe(self) -> pd.DataFrame:
|
|
1200
|
+
"""Convert parameter space to a pandas DataFrame.
|
|
1201
|
+
|
|
1202
|
+
Each row is one parameter combination. Column names are derived
|
|
1203
|
+
from the pytree key paths (e.g. ``'coupling.G'``, ``'noise.sigma'``).
|
|
1204
|
+
Scalar leaves become scalar cells; array leaves become object cells
|
|
1205
|
+
containing numpy arrays.
|
|
1206
|
+
|
|
1207
|
+
Returns
|
|
1208
|
+
-------
|
|
1209
|
+
pd.DataFrame
|
|
1210
|
+
DataFrame with one row per combination and one column per leaf.
|
|
1211
|
+
"""
|
|
1212
|
+
# Derive column names from axis positions in axis_state only,
|
|
1213
|
+
# not from the full combined state (which includes all equinox module
|
|
1214
|
+
# leaves and would produce numeric/garbage column names).
|
|
1215
|
+
paths_and_leaves, _ = jax.tree_util.tree_flatten_with_path(
|
|
1216
|
+
self.axis_state, is_leaf=lambda x: isinstance(x, AbstractAxis)
|
|
1217
|
+
)
|
|
1218
|
+
axis_paths = [
|
|
1219
|
+
p for p, leaf in paths_and_leaves if isinstance(leaf, AbstractAxis)
|
|
1220
|
+
]
|
|
1221
|
+
col_names = [_keypath_to_name(p) for p in axis_paths]
|
|
1222
|
+
|
|
1223
|
+
flattened_arrays, _ = self._generate_all_combinations()
|
|
1224
|
+
|
|
1225
|
+
columns = {}
|
|
1226
|
+
for name, arr in zip(col_names, flattened_arrays):
|
|
1227
|
+
arr_np = np.asarray(arr)
|
|
1228
|
+
# tolist() converts 0-dim slices to plain Python scalars (hashable),
|
|
1229
|
+
# needed for pandas pivot/groupby. Multi-dim axes stay as arrays.
|
|
1230
|
+
columns[name] = arr_np.tolist() if arr_np.ndim == 1 else list(arr_np)
|
|
1231
|
+
|
|
1232
|
+
return pd.DataFrame(columns)
|
|
1233
|
+
|
|
1041
1234
|
def __repr__(self):
|
|
1042
1235
|
axes = jax.tree.leaves(
|
|
1043
1236
|
self.axis_state, is_leaf=lambda x: isinstance(x, AbstractAxis)
|
|
1044
1237
|
)
|
|
1045
|
-
|
|
1238
|
+
groups = {a.group for a in axes if a.group is not None}
|
|
1239
|
+
group_info = f", groups={len(groups)}" if groups else ""
|
|
1240
|
+
return f"Space(N={self.N}, mode='{self.mode}', axes={len(axes)}{group_info})"
|
|
@@ -185,5 +185,124 @@ class TestExecution(unittest.TestCase):
|
|
|
185
185
|
)
|
|
186
186
|
|
|
187
187
|
|
|
188
|
+
class TestResultToDataFrame(unittest.TestCase):
|
|
189
|
+
"""Test Result.to_dataframe() functionality."""
|
|
190
|
+
|
|
191
|
+
def setUp(self):
|
|
192
|
+
self.state = {
|
|
193
|
+
"a": DataAxis(jnp.linspace(1.0, 5.0, 5)),
|
|
194
|
+
"b": DataAxis(jnp.linspace(10.0, 50.0, 5)),
|
|
195
|
+
}
|
|
196
|
+
self.space = Space(self.state)
|
|
197
|
+
|
|
198
|
+
def test_sequential_result_has_space(self):
|
|
199
|
+
"""SequentialResult stores space reference."""
|
|
200
|
+
|
|
201
|
+
def f(state):
|
|
202
|
+
return {"sum": state["a"] + state["b"]}
|
|
203
|
+
|
|
204
|
+
result = SequentialExecution(f, self.space).run()
|
|
205
|
+
self.assertIs(result.space, self.space)
|
|
206
|
+
|
|
207
|
+
def test_sequential_dict_result_columns(self):
|
|
208
|
+
"""Dict results produce named columns."""
|
|
209
|
+
|
|
210
|
+
def f(state):
|
|
211
|
+
return {"sum": state["a"] + state["b"], "product": state["a"] * state["b"]}
|
|
212
|
+
|
|
213
|
+
result = SequentialExecution(f, self.space).run()
|
|
214
|
+
df = result.to_dataframe()
|
|
215
|
+
|
|
216
|
+
self.assertEqual(len(df), 5)
|
|
217
|
+
# Param columns
|
|
218
|
+
self.assertIn("a", df.columns)
|
|
219
|
+
self.assertIn("b", df.columns)
|
|
220
|
+
# Result columns
|
|
221
|
+
self.assertIn("sum", df.columns)
|
|
222
|
+
self.assertIn("product", df.columns)
|
|
223
|
+
|
|
224
|
+
def test_sequential_list_result_columns(self):
|
|
225
|
+
"""List results produce bracketed column names."""
|
|
226
|
+
|
|
227
|
+
def f(state):
|
|
228
|
+
return [state["a"], state["b"]]
|
|
229
|
+
|
|
230
|
+
result = SequentialExecution(f, self.space).run()
|
|
231
|
+
df = result.to_dataframe()
|
|
232
|
+
|
|
233
|
+
self.assertIn("[0]", df.columns)
|
|
234
|
+
self.assertIn("[1]", df.columns)
|
|
235
|
+
|
|
236
|
+
def test_sequential_single_array_result(self):
|
|
237
|
+
"""Single array result produces 'value' column."""
|
|
238
|
+
|
|
239
|
+
def f(state):
|
|
240
|
+
return state["a"] + state["b"]
|
|
241
|
+
|
|
242
|
+
result = SequentialExecution(f, self.space).run()
|
|
243
|
+
df = result.to_dataframe()
|
|
244
|
+
|
|
245
|
+
self.assertIn("value", df.columns)
|
|
246
|
+
|
|
247
|
+
def test_name_collision_prefixed(self):
|
|
248
|
+
"""Result column colliding with param name gets 'result.' prefix."""
|
|
249
|
+
|
|
250
|
+
def f(state):
|
|
251
|
+
return {"a": state["a"] * 2} # 'a' collides with param 'a'
|
|
252
|
+
|
|
253
|
+
result = SequentialExecution(f, self.space).run()
|
|
254
|
+
df = result.to_dataframe()
|
|
255
|
+
|
|
256
|
+
self.assertIn("a", df.columns) # param
|
|
257
|
+
self.assertIn("result.a", df.columns) # result, prefixed
|
|
258
|
+
|
|
259
|
+
def test_parallel_result_has_space(self):
|
|
260
|
+
"""ParallelResult stores space reference."""
|
|
261
|
+
|
|
262
|
+
def f(state):
|
|
263
|
+
return {"sum": state["a"] + state["b"]}
|
|
264
|
+
|
|
265
|
+
result = ParallelExecution(f, self.space, n_pmap=1).run()
|
|
266
|
+
self.assertIs(result.space, self.space)
|
|
267
|
+
|
|
268
|
+
def test_parallel_result_to_dataframe(self):
|
|
269
|
+
"""ParallelResult.to_dataframe works like sequential."""
|
|
270
|
+
|
|
271
|
+
def f(state):
|
|
272
|
+
return {"sum": state["a"] + state["b"]}
|
|
273
|
+
|
|
274
|
+
result = ParallelExecution(f, self.space, n_pmap=1).run()
|
|
275
|
+
df = result.to_dataframe()
|
|
276
|
+
|
|
277
|
+
self.assertEqual(len(df), 5)
|
|
278
|
+
self.assertIn("a", df.columns)
|
|
279
|
+
self.assertIn("sum", df.columns)
|
|
280
|
+
|
|
281
|
+
def test_array_result_in_cell(self):
|
|
282
|
+
"""Non-scalar results stored as array objects in cells."""
|
|
283
|
+
import numpy as np
|
|
284
|
+
|
|
285
|
+
def f(state):
|
|
286
|
+
return {"timeseries": jnp.ones(10) * state["a"]}
|
|
287
|
+
|
|
288
|
+
result = SequentialExecution(f, self.space).run()
|
|
289
|
+
df = result.to_dataframe()
|
|
290
|
+
|
|
291
|
+
self.assertIn("timeseries", df.columns)
|
|
292
|
+
self.assertEqual(np.asarray(df["timeseries"].iloc[0]).shape, (10,))
|
|
293
|
+
|
|
294
|
+
def test_nested_dict_result(self):
|
|
295
|
+
"""Nested dict results produce dot-separated names."""
|
|
296
|
+
|
|
297
|
+
def f(state):
|
|
298
|
+
return {"metrics": {"mean": state["a"], "std": state["b"]}}
|
|
299
|
+
|
|
300
|
+
result = SequentialExecution(f, self.space).run()
|
|
301
|
+
df = result.to_dataframe()
|
|
302
|
+
|
|
303
|
+
self.assertIn("metrics.mean", df.columns)
|
|
304
|
+
self.assertIn("metrics.std", df.columns)
|
|
305
|
+
|
|
306
|
+
|
|
188
307
|
if __name__ == "__main__":
|
|
189
308
|
unittest.main()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/data/plotting/dk_average/aparc+aseg-mni_09c.nii.gz
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/analysis/__init__.py
RENAMED
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/core/__init__.py
RENAMED
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/core/network.py
RENAMED
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/coupling/__init__.py
RENAMED
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/coupling/base.py
RENAMED
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/coupling/linear.py
RENAMED
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/coupling/subspace.py
RENAMED
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/coupling/tvb.py
RENAMED
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/__init__.py
RENAMED
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/base.py
RENAMED
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/lorenz.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/linear.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/external_input/base.py
RENAMED
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/external_input/data.py
RENAMED
|
File without changes
|
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/graph/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/graph/sparse.py
RENAMED
|
File without changes
|
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/noise/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/noise/gaussian.py
RENAMED
|
File without changes
|
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/solvers/__init__.py
RENAMED
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/solvers/base.py
RENAMED
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/solvers/diffrax.py
RENAMED
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/utils/__init__.py
RENAMED
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/utils/history.py
RENAMED
|
File without changes
|
{tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/utils/printer.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|