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.
Files changed (86) hide show
  1. {tvboptim-0.2.5/src/tvboptim.egg-info → tvboptim-0.2.7}/PKG-INFO +1 -1
  2. {tvboptim-0.2.5 → tvboptim-0.2.7}/pyproject.toml +1 -1
  3. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/execution.py +52 -5
  4. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/analysis/lyapunov.py +19 -17
  5. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/core/bunch.py +13 -7
  6. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/solve.py +23 -8
  7. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/solvers/native.py +2 -2
  8. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/types/spaces.py +224 -29
  9. {tvboptim-0.2.5 → tvboptim-0.2.7/src/tvboptim.egg-info}/PKG-INFO +1 -1
  10. {tvboptim-0.2.5 → tvboptim-0.2.7}/tests/test_execution.py +119 -0
  11. {tvboptim-0.2.5 → tvboptim-0.2.7}/LICENSE +0 -0
  12. {tvboptim-0.2.5 → tvboptim-0.2.7}/README.md +0 -0
  13. {tvboptim-0.2.5 → tvboptim-0.2.7}/setup.cfg +0 -0
  14. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/__init__.py +0 -0
  15. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/data/__init__.py +0 -0
  16. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/data/connectivity/dTOR/data.npz +0 -0
  17. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/data/connectivity/dk_average/data.npz +0 -0
  18. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/data/functional/dk_average/data.npz +0 -0
  19. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/data/loaders.py +0 -0
  20. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/data/plotting/dk_average/aparc+aseg-mni_09c.nii.gz +0 -0
  21. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/data/plotting/dk_average/fs_default.txt +0 -0
  22. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/data/plotting/dk_average/fs_default_freesurfer_idx.csv +0 -0
  23. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/__init__.py +0 -0
  24. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/__init__.py +0 -0
  25. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/analysis/__init__.py +0 -0
  26. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/core/__init__.py +0 -0
  27. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/core/network.py +0 -0
  28. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/coupling/__init__.py +0 -0
  29. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/coupling/base.py +0 -0
  30. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/coupling/linear.py +0 -0
  31. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/coupling/subspace.py +0 -0
  32. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/coupling/tvb.py +0 -0
  33. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/__init__.py +0 -0
  34. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/base.py +0 -0
  35. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/lorenz.py +0 -0
  36. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py +0 -0
  37. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/coombes_byrne.py +0 -0
  38. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/epileptor.py +0 -0
  39. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/generic_2d_oscillator.py +0 -0
  40. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/jansen_rit.py +0 -0
  41. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/kuramoto.py +0 -0
  42. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/larter_breakspear.py +0 -0
  43. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/linear.py +0 -0
  44. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/montbrio_pazo_roxin.py +0 -0
  45. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/sup_hopf.py +0 -0
  46. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wilson_cowan.py +0 -0
  47. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang.py +0 -0
  48. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang_exc_inh.py +0 -0
  49. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/external_input/__init__.py +0 -0
  50. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/external_input/base.py +0 -0
  51. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/external_input/data.py +0 -0
  52. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/external_input/parametric.py +0 -0
  53. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/graph/__init__.py +0 -0
  54. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/graph/base.py +0 -0
  55. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/graph/sparse.py +0 -0
  56. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/graph/utils.py +0 -0
  57. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/noise/__init__.py +0 -0
  58. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/noise/base.py +0 -0
  59. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/noise/gaussian.py +0 -0
  60. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/result.py +0 -0
  61. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/solvers/__init__.py +0 -0
  62. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/solvers/base.py +0 -0
  63. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/solvers/diffrax.py +0 -0
  64. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/utils/__init__.py +0 -0
  65. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/utils/history.py +0 -0
  66. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/experimental/network_dynamics/utils/printer.py +0 -0
  67. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/observations/__init__.py +0 -0
  68. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/observations/observation.py +0 -0
  69. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/observations/tvb_monitors/__init__.py +0 -0
  70. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/observations/tvb_monitors/bold.py +0 -0
  71. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/observations/tvb_monitors/downsampling.py +0 -0
  72. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/optim/__init__.py +0 -0
  73. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/optim/callbacks.py +0 -0
  74. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/optim/optax.py +0 -0
  75. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/tvbo/__init__.py +0 -0
  76. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/tvbo/prepare_experiment.py +0 -0
  77. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/types/__init__.py +0 -0
  78. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/types/parameter.py +0 -0
  79. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/types/stateutils.py +0 -0
  80. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/utils/__init__.py +0 -0
  81. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/utils/caching.py +0 -0
  82. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim/utils/utils.py +0 -0
  83. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim.egg-info/SOURCES.txt +0 -0
  84. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim.egg-info/dependency_links.txt +0 -0
  85. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim.egg-info/requires.txt +0 -0
  86. {tvboptim-0.2.5 → tvboptim-0.2.7}/src/tvboptim.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tvboptim
3
- Version: 0.2.5
3
+ Version: 0.2.7
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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "tvboptim"
7
- version = "0.2.5"
7
+ version = "0.2.7"
8
8
  description = "Optimization tools for The Virtual Brain"
9
9
  readme = "README.md"
10
10
  authors = [
@@ -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
- pass
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(res, self.space.N, self.n_vmap, self.n_pmap)
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)
@@ -1,8 +1,9 @@
1
1
  import jax
2
2
  import jax.numpy as jnp
3
- from ..solvers import Heun
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 # [n_states, n_nodes]
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, 'dynamics': u})
51
- new_cfg = Bunch({**config, 'initial_state': new_is})
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(network, solver=None, t=1000.0, n=10, k=None,
74
- dt=0.1, t0=0.0, mode="jvp", d0=1e-9):
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, 'dynamics': u})
120
- new_cfg = Bunch({**config, 'initial_state': new_is})
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 # [k, D]
129
- new_perturbed = jax.vmap(_solve_flat)(perturbed) # [k, D]
130
- delta = (new_perturbed - new_u) / d0 # [k, D]
131
- Q_new, R = jnp.linalg.qr(delta.T) # [D, k], [k, k]
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, 'dynamics': u})
155
- new_cfg = Bunch({**config, 'initial_state': new_is})
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) # [k, D]
164
- Q_new, R = jnp.linalg.qr(tangents.T) # [D, k], [k, k]
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
- def _bunch_tree_flatten(bunch: Bunch) -> Tuple[Tuple[Any, ...], Tuple[str, ...]]:
55
- """Flatten Bunch into values and keys for JAX PyTree."""
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
- values = tuple(bunch[key] for key in keys)
58
- return values, keys
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
- # Register the PyTree
67
- jax.tree_util.register_pytree_node(Bunch, _bunch_tree_flatten, _bunch_tree_unflatten)
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(t, network_state, coupling_state_dict, config, coupling_data_dict):
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, network_state, data, state_data, config.coupling[name], config.graph
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(coupling_state_dict, new_network_state, coupling_data_dict):
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, network_state, data, empty_state, config.coupling[name], config.graph
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(t, y, config.dynamics, coupling_inputs, external_inputs)
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
 
@@ -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 = jnp.asarray(low)
270
+ low = jnp.asarray(low)
271
271
  high = jnp.asarray(high)
272
- self.low = low[:, None] if low.ndim == 1 else 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
- pass
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, low: float, high: float, n: int, shape: Optional[Tuple[int, ...]] = None
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, low: float, high: float, n: int, shape: Optional[Tuple[int, ...]] = None
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, low: float, high: float, n: int, shape: Optional[Tuple[int, ...]] = None
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
- axis_sizes = [axis.size for axis in axes]
840
+ effective_sizes = self._get_effective_sizes(axes)
748
841
 
749
842
  if self.mode == "product":
750
- return int(np.prod(axis_sizes))
843
+ return int(np.prod(effective_sizes))
751
844
  elif self.mode == "zip":
752
- min_size = min(axis_sizes)
753
- max_size = max(axis_sizes)
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 axis_sizes)
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 {axis_sizes}. "
760
- f"Using minimum size {min_size}, losing {lost_combinations} combinations."
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
- # Create meshgrid for Cartesian product and flatten each
817
- meshgrid_arrays = jnp.meshgrid(*axis_values_list, indexing="ij")
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
- # In zip mode, arrays are already aligned
821
- flattened_arrays = axis_values_list
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 flattened_arrays, axis_tree_def
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
- data_axes = [DataAxis(values) for values in sliced_arrays]
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
- return f"Space(N={self.N}, mode='{self.mode}', axes={len(axes)})"
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})"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tvboptim
3
- Version: 0.2.5
3
+ Version: 0.2.7
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
@@ -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