tvboptim 0.2.5__tar.gz → 0.2.6__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.6}/PKG-INFO +1 -1
  2. {tvboptim-0.2.5 → tvboptim-0.2.6}/pyproject.toml +1 -1
  3. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/execution.py +49 -5
  4. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/analysis/lyapunov.py +3 -2
  5. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/types/spaces.py +217 -29
  6. {tvboptim-0.2.5 → tvboptim-0.2.6/src/tvboptim.egg-info}/PKG-INFO +1 -1
  7. {tvboptim-0.2.5 → tvboptim-0.2.6}/tests/test_execution.py +119 -0
  8. {tvboptim-0.2.5 → tvboptim-0.2.6}/LICENSE +0 -0
  9. {tvboptim-0.2.5 → tvboptim-0.2.6}/README.md +0 -0
  10. {tvboptim-0.2.5 → tvboptim-0.2.6}/setup.cfg +0 -0
  11. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/__init__.py +0 -0
  12. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/data/__init__.py +0 -0
  13. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/data/connectivity/dTOR/data.npz +0 -0
  14. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/data/connectivity/dk_average/data.npz +0 -0
  15. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/data/functional/dk_average/data.npz +0 -0
  16. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/data/loaders.py +0 -0
  17. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/data/plotting/dk_average/aparc+aseg-mni_09c.nii.gz +0 -0
  18. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/data/plotting/dk_average/fs_default.txt +0 -0
  19. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/data/plotting/dk_average/fs_default_freesurfer_idx.csv +0 -0
  20. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/__init__.py +0 -0
  21. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/__init__.py +0 -0
  22. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/analysis/__init__.py +0 -0
  23. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/core/__init__.py +0 -0
  24. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/core/bunch.py +0 -0
  25. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/core/network.py +0 -0
  26. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/coupling/__init__.py +0 -0
  27. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/coupling/base.py +0 -0
  28. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/coupling/linear.py +0 -0
  29. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/coupling/subspace.py +0 -0
  30. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/coupling/tvb.py +0 -0
  31. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/dynamics/__init__.py +0 -0
  32. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/dynamics/base.py +0 -0
  33. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/dynamics/lorenz.py +0 -0
  34. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py +0 -0
  35. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/coombes_byrne.py +0 -0
  36. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/epileptor.py +0 -0
  37. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/generic_2d_oscillator.py +0 -0
  38. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/jansen_rit.py +0 -0
  39. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/kuramoto.py +0 -0
  40. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/larter_breakspear.py +0 -0
  41. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/linear.py +0 -0
  42. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/montbrio_pazo_roxin.py +0 -0
  43. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/sup_hopf.py +0 -0
  44. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wilson_cowan.py +0 -0
  45. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang.py +0 -0
  46. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang_exc_inh.py +0 -0
  47. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/external_input/__init__.py +0 -0
  48. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/external_input/base.py +0 -0
  49. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/external_input/data.py +0 -0
  50. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/external_input/parametric.py +0 -0
  51. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/graph/__init__.py +0 -0
  52. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/graph/base.py +0 -0
  53. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/graph/sparse.py +0 -0
  54. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/graph/utils.py +0 -0
  55. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/noise/__init__.py +0 -0
  56. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/noise/base.py +0 -0
  57. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/noise/gaussian.py +0 -0
  58. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/result.py +0 -0
  59. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/solve.py +0 -0
  60. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/solvers/__init__.py +0 -0
  61. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/solvers/base.py +0 -0
  62. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/solvers/diffrax.py +0 -0
  63. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/solvers/native.py +0 -0
  64. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/utils/__init__.py +0 -0
  65. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/utils/history.py +0 -0
  66. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/experimental/network_dynamics/utils/printer.py +0 -0
  67. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/observations/__init__.py +0 -0
  68. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/observations/observation.py +0 -0
  69. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/observations/tvb_monitors/__init__.py +0 -0
  70. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/observations/tvb_monitors/bold.py +0 -0
  71. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/observations/tvb_monitors/downsampling.py +0 -0
  72. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/optim/__init__.py +0 -0
  73. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/optim/callbacks.py +0 -0
  74. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/optim/optax.py +0 -0
  75. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/tvbo/__init__.py +0 -0
  76. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/tvbo/prepare_experiment.py +0 -0
  77. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/types/__init__.py +0 -0
  78. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/types/parameter.py +0 -0
  79. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/types/stateutils.py +0 -0
  80. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/utils/__init__.py +0 -0
  81. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/utils/caching.py +0 -0
  82. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim/utils/utils.py +0 -0
  83. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim.egg-info/SOURCES.txt +0 -0
  84. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim.egg-info/dependency_links.txt +0 -0
  85. {tvboptim-0.2.5 → tvboptim-0.2.6}/src/tvboptim.egg-info/requires.txt +0 -0
  86. {tvboptim-0.2.5 → tvboptim-0.2.6}/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.6
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.6"
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,46 @@ class Result(ABC):
16
19
  Result type to provide unified indexing
17
20
  """
18
21
 
19
- pass
22
+ space = None
23
+
24
+ def to_dataframe(self) -> pd.DataFrame:
25
+ """Convert results (and parameters) to a pandas DataFrame.
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
43
+ sample = self[0]
44
+ paths_and_leaves, treedef = jax.tree_util.tree_flatten_with_path(sample)
45
+ col_names = [_keypath_to_name(p) for p, _ in paths_and_leaves]
46
+
47
+ # Handle name collisions with param columns
48
+ for i, name in enumerate(col_names):
49
+ if name in df.columns:
50
+ col_names[i] = f"result.{name}"
51
+
52
+ result_data = {name: [] for name in col_names}
53
+ for result in self:
54
+ leaves = jax.tree.leaves(result)
55
+ for name, leaf in zip(col_names, leaves):
56
+ result_data[name].append(np.asarray(leaf))
57
+
58
+ for name, values in result_data.items():
59
+ df[name] = values
60
+
61
+ return df
20
62
 
21
63
 
22
64
  class SequentialExecution(Execution):
@@ -95,12 +137,13 @@ class SequentialExecution(Execution):
95
137
  jax.block_until_ready(self.model(state, *self.args, **self.kwargs))
96
138
  )
97
139
  # results.append(jax.block_until_ready(self.model(state, *self.args, **self.kwargs)))
98
- return SequentialResult(results)
140
+ return SequentialResult(results, space=self.statespace)
99
141
 
100
142
 
101
143
  class SequentialResult(Result):
102
- def __init__(self, results):
144
+ def __init__(self, results, space=None):
103
145
  self.results = results
146
+ self.space = space
104
147
 
105
148
  def __iter__(self):
106
149
  return iter(self.results)
@@ -215,13 +258,14 @@ class ParallelExecution(Execution):
215
258
  res = jax.block_until_ready(
216
259
  jax.pmap(self.map_model, in_axes=0)(self.diff_state)
217
260
  )
218
- return ParallelResult(res, self.space.N, self.n_vmap, self.n_pmap)
261
+ return ParallelResult(res, self.space.N, self.n_vmap, self.n_pmap, space=self.space)
219
262
 
220
263
 
221
264
  class ParallelResult(Result):
222
- def __init__(self, results, N, n_vmap, n_pmap):
265
+ def __init__(self, results, N, n_vmap, n_pmap, space=None):
223
266
  self.results = results
224
267
  self.N = N
268
+ self.space = space
225
269
  self.n_vmap = n_vmap
226
270
  self.n_pmap = n_pmap
227
271
 
@@ -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):
@@ -40,9 +40,35 @@ 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
+
46
72
  try:
47
73
  import numpyro.distributions # noqa: F401
48
74
 
@@ -94,9 +120,17 @@ class AbstractAxis(ABC):
94
120
  >>> print(f"Normal samples: {values}")
95
121
  """
96
122
 
97
- def __init__(self):
98
- """Initialize axis."""
99
- pass
123
+ def __init__(self, group=None):
124
+ """Initialize axis.
125
+
126
+ Parameters
127
+ ----------
128
+ group : hashable, optional
129
+ Group label. Axes sharing the same group are zipped together
130
+ into a single composite axis before the Space's combination
131
+ mode is applied. Default is None (ungrouped).
132
+ """
133
+ self.group = group
100
134
 
101
135
  @abstractmethod
102
136
  def generate_values(self, key: Optional[jax.random.PRNGKey] = None) -> jnp.ndarray:
@@ -160,7 +194,12 @@ class GridAxis(AbstractAxis):
160
194
  """
161
195
 
162
196
  def __init__(
163
- self, low: float, high: float, n: int, shape: Optional[Tuple[int, ...]] = None
197
+ self,
198
+ low: float,
199
+ high: float,
200
+ n: int,
201
+ shape: Optional[Tuple[int, ...]] = None,
202
+ group=None,
164
203
  ):
165
204
  """Initialize grid axis.
166
205
 
@@ -175,8 +214,10 @@ class GridAxis(AbstractAxis):
175
214
  shape : Tuple[int, ...], optional
176
215
  Shape of generated values. If specified, values are broadcast to this shape.
177
216
  Default is None.
217
+ group : hashable, optional
218
+ Group label for axis grouping. See AbstractAxis. Default is None.
178
219
  """
179
- super().__init__()
220
+ super().__init__(group=group)
180
221
  self.low = low
181
222
  self.high = high
182
223
  self.n = n
@@ -253,7 +294,12 @@ class LogGridAxis(AbstractAxis):
253
294
  """
254
295
 
255
296
  def __init__(
256
- self, low: float, high: float, n: int, shape: Optional[Tuple[int, ...]] = None
297
+ self,
298
+ low: float,
299
+ high: float,
300
+ n: int,
301
+ shape: Optional[Tuple[int, ...]] = None,
302
+ group=None,
257
303
  ):
258
304
  """Initialize log grid axis.
259
305
 
@@ -268,8 +314,10 @@ class LogGridAxis(AbstractAxis):
268
314
  shape : Tuple[int, ...], optional
269
315
  Shape of generated values. If specified, values are broadcast to this shape.
270
316
  Default is None.
317
+ group : hashable, optional
318
+ Group label for axis grouping. See AbstractAxis. Default is None.
271
319
  """
272
- super().__init__()
320
+ super().__init__(group=group)
273
321
  self.low = low
274
322
  self.high = high
275
323
  self.n = n
@@ -350,7 +398,12 @@ class UniformAxis(AbstractAxis):
350
398
  """
351
399
 
352
400
  def __init__(
353
- self, low: float, high: float, n: int, shape: Optional[Tuple[int, ...]] = None
401
+ self,
402
+ low: float,
403
+ high: float,
404
+ n: int,
405
+ shape: Optional[Tuple[int, ...]] = None,
406
+ group=None,
354
407
  ):
355
408
  """Initialize uniform axis.
356
409
 
@@ -365,8 +418,10 @@ class UniformAxis(AbstractAxis):
365
418
  shape : Tuple[int, ...], optional
366
419
  Shape of generated values. If specified, values are broadcast to this shape.
367
420
  Default is None.
421
+ group : hashable, optional
422
+ Group label for axis grouping. See AbstractAxis. Default is None.
368
423
  """
369
- super().__init__()
424
+ super().__init__(group=group)
370
425
  self.low = low
371
426
  self.high = high
372
427
  self.n = n
@@ -445,15 +500,17 @@ class DataAxis(AbstractAxis):
445
500
  >>> print(data_jax.size) # 5
446
501
  """
447
502
 
448
- def __init__(self, values: Union[List, jnp.ndarray]):
503
+ def __init__(self, values: Union[List, jnp.ndarray], group=None):
449
504
  """Initialize data axis.
450
505
 
451
506
  Parameters
452
507
  ----------
453
508
  values : array-like
454
509
  Predefined values to sample from.
510
+ group : hashable, optional
511
+ Group label for axis grouping. See AbstractAxis. Default is None.
455
512
  """
456
- super().__init__()
513
+ super().__init__(group=group)
457
514
  self.values = jnp.asarray(values)
458
515
 
459
516
  if self.values.size == 0:
@@ -546,6 +603,7 @@ class NumPyroAxis(AbstractAxis):
546
603
  n: int,
547
604
  sample_shape: Optional[Tuple[int, ...]] = None,
548
605
  broadcast_mode: bool = False,
606
+ group=None,
549
607
  ):
550
608
  """Initialize NumPyro distribution axis.
551
609
 
@@ -560,8 +618,10 @@ class NumPyroAxis(AbstractAxis):
560
618
  broadcast_mode : bool, optional
561
619
  If True, sample once per axis point then broadcast to sample_shape.
562
620
  If False, sample independently for each element. Default is False.
621
+ group : hashable, optional
622
+ Group label for axis grouping. See AbstractAxis. Default is None.
563
623
  """
564
- super().__init__()
624
+ super().__init__(group=group)
565
625
 
566
626
  if not NUMPYRO_AVAILABLE:
567
627
  raise ImportError(
@@ -735,6 +795,38 @@ class Space:
735
795
  # Calculate total combinations
736
796
  self._N = self._calculate_total_size()
737
797
 
798
+ def _get_effective_sizes(self, axes):
799
+ """Compute effective axis sizes accounting for groups.
800
+
801
+ Axes sharing a group label are zipped together into a single
802
+ composite axis. Returns one effective size per group plus one
803
+ per ungrouped axis.
804
+ """
805
+ from collections import OrderedDict
806
+
807
+ groups = OrderedDict() # group_label -> list of sizes
808
+ ungrouped_sizes = []
809
+
810
+ for axis in axes:
811
+ if axis.group is not None:
812
+ groups.setdefault(axis.group, []).append(axis.size)
813
+ else:
814
+ ungrouped_sizes.append(axis.size)
815
+
816
+ effective_sizes = []
817
+ for group_label, sizes in groups.items():
818
+ min_s = min(sizes)
819
+ max_s = max(sizes)
820
+ if min_s != max_s:
821
+ print(
822
+ f"WARNING: Axes in group '{group_label}' have different sizes "
823
+ f"{sizes}. Using minimum size {min_s}."
824
+ )
825
+ effective_sizes.append(min_s)
826
+
827
+ effective_sizes.extend(ungrouped_sizes)
828
+ return effective_sizes
829
+
738
830
  def _calculate_total_size(self) -> int:
739
831
  """Calculate total number of parameter combinations."""
740
832
  axes = jax.tree.leaves(
@@ -744,20 +836,22 @@ class Space:
744
836
  if not axes:
745
837
  return 1
746
838
 
747
- axis_sizes = [axis.size for axis in axes]
839
+ effective_sizes = self._get_effective_sizes(axes)
748
840
 
749
841
  if self.mode == "product":
750
- return int(np.prod(axis_sizes))
842
+ return int(np.prod(effective_sizes))
751
843
  elif self.mode == "zip":
752
- min_size = min(axis_sizes)
753
- max_size = max(axis_sizes)
844
+ min_size = min(effective_sizes)
845
+ max_size = max(effective_sizes)
754
846
 
755
- # Warn if axes have different sizes in zip mode
756
847
  if min_size != max_size:
757
- lost_combinations = sum(size - min_size for size in axis_sizes)
848
+ lost_combinations = sum(
849
+ size - min_size for size in effective_sizes
850
+ )
758
851
  print(
759
- f"WARNING: In zip mode, axes have different sizes {axis_sizes}. "
760
- f"Using minimum size {min_size}, losing {lost_combinations} combinations."
852
+ f"WARNING: In zip mode, effective axes have different sizes "
853
+ f"{effective_sizes}. Using minimum size {min_size}, "
854
+ f"losing {lost_combinations} combinations."
761
855
  )
762
856
 
763
857
  return min_size
@@ -812,15 +906,76 @@ class Space:
812
906
  if not axis_values_list:
813
907
  return [], axis_tree_def
814
908
 
909
+ # Get axes in same flat order to read group labels
910
+ axes_flat = jax.tree.leaves(
911
+ self.axis_state, is_leaf=lambda x: isinstance(x, AbstractAxis)
912
+ )
913
+
914
+ # Check if any groups exist — fast path if not
915
+ has_groups = any(a.group is not None for a in axes_flat)
916
+
917
+ if not has_groups:
918
+ # Original ungrouped logic
919
+ if self.mode == "product":
920
+ meshgrid_arrays = jnp.meshgrid(*axis_values_list, indexing="ij")
921
+ flattened_arrays = [arr.flatten() for arr in meshgrid_arrays]
922
+ elif self.mode == "zip":
923
+ flattened_arrays = axis_values_list
924
+ return flattened_arrays, axis_tree_def
925
+
926
+ # --- Grouped logic ---
927
+ from collections import OrderedDict
928
+
929
+ # Partition axes into groups and ungrouped
930
+ group_map = OrderedDict() # group_label -> [(flat_idx, values), ...]
931
+ ungrouped = [] # [(flat_idx, values), ...]
932
+
933
+ for i, (axis, values) in enumerate(zip(axes_flat, axis_values_list)):
934
+ if axis.group is not None:
935
+ group_map.setdefault(axis.group, []).append((i, values))
936
+ else:
937
+ ungrouped.append((i, values))
938
+
939
+ # Build effective axes: one representative per group + one per ungrouped
940
+ effective_values = []
941
+ # Each entry: ('group', [(orig_idx, truncated_values), ...])
942
+ # or ('single', orig_idx)
943
+ effective_meta = []
944
+
945
+ for group_label, members in group_map.items():
946
+ sizes = [v.shape[0] for _, v in members]
947
+ eff_size = min(sizes)
948
+ truncated = [(idx, v[:eff_size]) for idx, v in members]
949
+ # Use index array as representative for meshgrid
950
+ effective_values.append(jnp.arange(eff_size))
951
+ effective_meta.append(("group", truncated))
952
+
953
+ for idx, values in ungrouped:
954
+ effective_values.append(values)
955
+ effective_meta.append(("single", idx))
956
+
957
+ # Apply combination mode on effective axes
815
958
  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]
959
+ meshgrid_arrays = jnp.meshgrid(*effective_values, indexing="ij")
960
+ flat_effective = [arr.flatten() for arr in meshgrid_arrays]
819
961
  elif self.mode == "zip":
820
- # In zip mode, arrays are already aligned
821
- flattened_arrays = axis_values_list
962
+ flat_effective = effective_values
822
963
 
823
- return flattened_arrays, axis_tree_def
964
+ # Expand back to original flat ordering
965
+ result = [None] * len(axis_values_list)
966
+
967
+ for eff_idx, (meta, combined) in enumerate(
968
+ zip(effective_meta, flat_effective)
969
+ ):
970
+ kind, payload = meta
971
+ if kind == "group":
972
+ index_array = combined.astype(jnp.int32)
973
+ for orig_idx, truncated_values in payload:
974
+ result[orig_idx] = truncated_values[index_array]
975
+ else: # 'single'
976
+ result[payload] = combined
977
+
978
+ return result, axis_tree_def
824
979
 
825
980
  def _get_combination_at_index(self, index: int) -> Dict[str, Any]:
826
981
  """Get a single combination by indexing into flattened arrays."""
@@ -931,8 +1086,14 @@ class Space:
931
1086
  f"Slice {index} results in empty parameter space with no combinations"
932
1087
  )
933
1088
 
934
- # Create new axis state with DataAxis instances
935
- data_axes = [DataAxis(values) for values in sliced_arrays]
1089
+ # Create new axis state with DataAxis instances, preserving groups
1090
+ axes_flat = jax.tree.leaves(
1091
+ self.axis_state, is_leaf=lambda x: isinstance(x, AbstractAxis)
1092
+ )
1093
+ data_axes = [
1094
+ DataAxis(values, group=axis.group)
1095
+ for values, axis in zip(sliced_arrays, axes_flat)
1096
+ ]
936
1097
  new_axis_state = jax.tree.unflatten(axis_tree_def, data_axes)
937
1098
 
938
1099
  # Create new Space in zip mode
@@ -1038,8 +1199,35 @@ class Space:
1038
1199
  else:
1039
1200
  return batched_axis_tree, self.static_state
1040
1201
 
1202
+ def to_dataframe(self) -> pd.DataFrame:
1203
+ """Convert parameter space to a pandas DataFrame.
1204
+
1205
+ Each row is one parameter combination. Column names are derived
1206
+ from the pytree key paths (e.g. ``'coupling.G'``, ``'noise.sigma'``).
1207
+ Scalar leaves become scalar cells; array leaves become object cells
1208
+ containing numpy arrays.
1209
+
1210
+ Returns
1211
+ -------
1212
+ pd.DataFrame
1213
+ DataFrame with one row per combination and one column per leaf.
1214
+ """
1215
+ sample = self[0]
1216
+ paths_and_leaves, treedef = jax.tree_util.tree_flatten_with_path(sample)
1217
+ col_names = [_keypath_to_name(p) for p, _ in paths_and_leaves]
1218
+
1219
+ columns = {name: [] for name in col_names}
1220
+ for params in self:
1221
+ leaves = jax.tree.leaves(params)
1222
+ for name, leaf in zip(col_names, leaves):
1223
+ columns[name].append(np.asarray(leaf))
1224
+
1225
+ return pd.DataFrame(columns)
1226
+
1041
1227
  def __repr__(self):
1042
1228
  axes = jax.tree.leaves(
1043
1229
  self.axis_state, is_leaf=lambda x: isinstance(x, AbstractAxis)
1044
1230
  )
1045
- return f"Space(N={self.N}, mode='{self.mode}', axes={len(axes)})"
1231
+ groups = {a.group for a in axes if a.group is not None}
1232
+ group_info = f", groups={len(groups)}" if groups else ""
1233
+ 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.6
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