tvboptim 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. tvboptim/__init__.py +9 -0
  2. tvboptim/data/__init__.py +12 -0
  3. tvboptim/data/loaders.py +99 -0
  4. tvboptim/execution.py +268 -0
  5. tvboptim/experimental/__init__.py +15 -0
  6. tvboptim/experimental/network_dynamics/__init__.py +28 -0
  7. tvboptim/experimental/network_dynamics/core/__init__.py +6 -0
  8. tvboptim/experimental/network_dynamics/core/bunch.py +67 -0
  9. tvboptim/experimental/network_dynamics/core/network.py +686 -0
  10. tvboptim/experimental/network_dynamics/coupling/__init__.py +22 -0
  11. tvboptim/experimental/network_dynamics/coupling/base.py +1005 -0
  12. tvboptim/experimental/network_dynamics/coupling/linear.py +466 -0
  13. tvboptim/experimental/network_dynamics/coupling/subspace.py +509 -0
  14. tvboptim/experimental/network_dynamics/coupling/tvb.py +202 -0
  15. tvboptim/experimental/network_dynamics/dynamics/__init__.py +7 -0
  16. tvboptim/experimental/network_dynamics/dynamics/base.py +541 -0
  17. tvboptim/experimental/network_dynamics/dynamics/lorenz.py +207 -0
  18. tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py +29 -0
  19. tvboptim/experimental/network_dynamics/dynamics/tvb/coombes_byrne.py +154 -0
  20. tvboptim/experimental/network_dynamics/dynamics/tvb/epileptor.py +200 -0
  21. tvboptim/experimental/network_dynamics/dynamics/tvb/generic_2d_oscillator.py +149 -0
  22. tvboptim/experimental/network_dynamics/dynamics/tvb/jansen_rit.py +158 -0
  23. tvboptim/experimental/network_dynamics/dynamics/tvb/kuramoto.py +120 -0
  24. tvboptim/experimental/network_dynamics/dynamics/tvb/larter_breakspear.py +221 -0
  25. tvboptim/experimental/network_dynamics/dynamics/tvb/linear.py +111 -0
  26. tvboptim/experimental/network_dynamics/dynamics/tvb/montbrio_pazo_roxin.py +137 -0
  27. tvboptim/experimental/network_dynamics/dynamics/tvb/sup_hopf.py +131 -0
  28. tvboptim/experimental/network_dynamics/dynamics/tvb/wilson_cowan.py +210 -0
  29. tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang.py +124 -0
  30. tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang_exc_inh.py +177 -0
  31. tvboptim/experimental/network_dynamics/external_input/__init__.py +20 -0
  32. tvboptim/experimental/network_dynamics/external_input/base.py +152 -0
  33. tvboptim/experimental/network_dynamics/external_input/data.py +203 -0
  34. tvboptim/experimental/network_dynamics/external_input/parametric.py +270 -0
  35. tvboptim/experimental/network_dynamics/graph/__init__.py +14 -0
  36. tvboptim/experimental/network_dynamics/graph/base.py +706 -0
  37. tvboptim/experimental/network_dynamics/graph/sparse.py +885 -0
  38. tvboptim/experimental/network_dynamics/graph/utils.py +0 -0
  39. tvboptim/experimental/network_dynamics/noise/__init__.py +6 -0
  40. tvboptim/experimental/network_dynamics/noise/base.py +162 -0
  41. tvboptim/experimental/network_dynamics/noise/gaussian.py +71 -0
  42. tvboptim/experimental/network_dynamics/result.py +78 -0
  43. tvboptim/experimental/network_dynamics/solve.py +721 -0
  44. tvboptim/experimental/network_dynamics/solvers/__init__.py +15 -0
  45. tvboptim/experimental/network_dynamics/solvers/base.py +46 -0
  46. tvboptim/experimental/network_dynamics/solvers/diffrax.py +63 -0
  47. tvboptim/experimental/network_dynamics/solvers/native.py +308 -0
  48. tvboptim/experimental/network_dynamics/utils/__init__.py +3 -0
  49. tvboptim/experimental/network_dynamics/utils/printer.py +555 -0
  50. tvboptim/model.py +111 -0
  51. tvboptim/observations/__init__.py +3 -0
  52. tvboptim/observations/observation.py +32 -0
  53. tvboptim/observations/tvb_monitors/__init__.py +11 -0
  54. tvboptim/observations/tvb_monitors/bold.py +290 -0
  55. tvboptim/observations/tvb_monitors/downsampling.py +185 -0
  56. tvboptim/optim/__init__.py +4 -0
  57. tvboptim/optim/callbacks.py +333 -0
  58. tvboptim/optim/optax.py +379 -0
  59. tvboptim/types/__init__.py +35 -0
  60. tvboptim/types/parameter.py +769 -0
  61. tvboptim/types/spaces.py +943 -0
  62. tvboptim/types/stateutils.py +109 -0
  63. tvboptim/utils/__init__.py +16 -0
  64. tvboptim/utils/caching.py +82 -0
  65. tvboptim/utils/utils.py +265 -0
  66. tvboptim-0.2.0.dist-info/METADATA +157 -0
  67. tvboptim-0.2.0.dist-info/RECORD +70 -0
  68. tvboptim-0.2.0.dist-info/WHEEL +5 -0
  69. tvboptim-0.2.0.dist-info/licenses/LICENSE +278 -0
  70. tvboptim-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,943 @@
1
+ """Clean axis and space system for TVBOptim.
2
+
3
+ This module implements a simple, composable parameter space system for systematic
4
+ exploration of brain simulation parameters.
5
+
6
+ The system consists of:
7
+
8
+ - **AbstractAxis**: Base class for sampling strategies (grid, uniform, data)
9
+ - **Space**: Composes axes into parameter combinations with product/zip modes
10
+ - **Centralized key management**: Single random key for all stochastic operations
11
+ - **JAX-native integration**: Full support for vmap/pmap parallel execution
12
+
13
+ Axes generate raw JAX arrays only. Parameter creation is handled separately by user code.
14
+
15
+ Examples
16
+ --------
17
+ >>> from tvboptim.types.spaces import Space, GridAxis, UniformAxis, NumPyroAxis
18
+ >>> import numpyro.distributions as dist
19
+ >>> import copy
20
+ >>>
21
+ >>> # Create exploration state with axes
22
+ >>> exploration_state = copy.deepcopy(state)
23
+ >>> exploration_state.parameters.coupling.a = GridAxis(0.0, 1.0, 10)
24
+ >>> exploration_state.parameters.model.J_N = UniformAxis(0.0, 1.0, 5)
25
+ >>> exploration_state.parameters.noise.sigma = NumPyroAxis(dist.LogNormal(0.0, 1.0), 8)
26
+ >>>
27
+ >>> # Create space for parameter exploration
28
+ >>> space = Space(exploration_state, mode='product')
29
+ >>> print(f"Total combinations: {space.N}")
30
+ >>>
31
+ >>> # Access individual combinations
32
+ >>> first_combination = space[0]
33
+ >>> subset = space[10:20]
34
+ """
35
+
36
+ from abc import ABC, abstractmethod
37
+ from typing import Any, Dict, List, Optional, Tuple, Union
38
+
39
+ import equinox as eqx
40
+ import jax
41
+ import jax.numpy as jnp
42
+ import numpy as np
43
+
44
+ from tvboptim.utils import safe_reshape
45
+
46
+ try:
47
+ import numpyro.distributions # noqa: F401
48
+
49
+ NUMPYRO_AVAILABLE = True
50
+ except ImportError:
51
+ NUMPYRO_AVAILABLE = False
52
+
53
+ # =============================================================================
54
+ # Abstract Base Classes
55
+ # =============================================================================
56
+
57
+
58
+ class AbstractAxis(ABC):
59
+ """Abstract base class for all parameter sampling axes.
60
+
61
+ An axis defines how to sample values along one dimension of parameter space.
62
+ Axes generate raw JAX arrays only - no parameter creation is performed.
63
+
64
+ Notes
65
+ -----
66
+ All concrete axis implementations must provide:
67
+
68
+ - `generate_values()` method to produce sample values
69
+ - `size` property returning the number of values generated
70
+
71
+ Examples
72
+ --------
73
+ >>> from tvboptim.types.spaces import GridAxis, UniformAxis, NumPyroAxis
74
+ >>> import numpyro.distributions as dist
75
+ >>>
76
+ >>> # Grid sampling from 0 to 1 with 5 points
77
+ >>> grid_axis = GridAxis(0.0, 1.0, 5)
78
+ >>> values = grid_axis.generate_values()
79
+ >>> print(f"Grid values: {values}")
80
+ >>>
81
+ >>> # Random uniform sampling
82
+ >>> uniform_axis = UniformAxis(0.0, 1.0, 3)
83
+ >>> values = uniform_axis.generate_values(jax.random.key(42))
84
+ >>> print(f"Random values: {values}")
85
+ >>>
86
+ >>> # NumPyro distribution sampling
87
+ >>> normal_axis = NumPyroAxis(dist.Normal(0.0, 1.0), 4)
88
+ >>> values = normal_axis.generate_values(jax.random.key(42))
89
+ >>> print(f"Normal samples: {values}")
90
+ """
91
+
92
+ def __init__(self):
93
+ """Initialize axis."""
94
+ pass
95
+
96
+ @abstractmethod
97
+ def generate_values(self, key: Optional[jax.random.PRNGKey] = None) -> jnp.ndarray:
98
+ """Generate all values for this axis.
99
+
100
+ Parameters
101
+ ----------
102
+ key : jax.random.PRNGKey, optional
103
+ Random key for stochastic sampling. Ignored by deterministic axes.
104
+
105
+ Returns
106
+ -------
107
+ jnp.ndarray
108
+ Generated values as raw JAX arrays.
109
+ """
110
+ pass
111
+
112
+ @property
113
+ @abstractmethod
114
+ def size(self) -> int:
115
+ """Number of values this axis generates.
116
+
117
+ Returns
118
+ -------
119
+ int
120
+ Total number of sample points along this axis.
121
+ """
122
+ pass
123
+
124
+
125
+ # =============================================================================
126
+ # Concrete Axis Implementations
127
+ # =============================================================================
128
+
129
+
130
+ class GridAxis(AbstractAxis):
131
+ """Axis for systematic grid sampling over parameter bounds.
132
+
133
+ Generates linearly spaced values between low and high bounds using
134
+ deterministic grid sampling.
135
+
136
+ Parameters
137
+ ----------
138
+ low : float
139
+ Lower bound for sampling.
140
+ high : float
141
+ Upper bound for sampling.
142
+ n : int
143
+ Number of grid points to generate.
144
+
145
+ Raises
146
+ ------
147
+ ValueError
148
+ If n <= 0 or low >= high.
149
+
150
+ Examples
151
+ --------
152
+ >>> grid = GridAxis(0.0, 1.0, 5)
153
+ >>> values = grid.generate_values()
154
+ >>> print(values) # [0.0, 0.25, 0.5, 0.75, 1.0]
155
+ """
156
+
157
+ def __init__(
158
+ self, low: float, high: float, n: int, shape: Optional[Tuple[int, ...]] = None
159
+ ):
160
+ """Initialize grid axis.
161
+
162
+ Parameters
163
+ ----------
164
+ low : float
165
+ Lower bound for sampling.
166
+ high : float
167
+ Upper bound for sampling.
168
+ n : int
169
+ Number of grid points to generate.
170
+ shape : Tuple[int, ...], optional
171
+ Shape of generated values. If specified, values are broadcast to this shape.
172
+ Default is None.
173
+ """
174
+ super().__init__()
175
+ self.low = low
176
+ self.high = high
177
+ self.n = n
178
+ self.shape = shape
179
+
180
+ if n <= 0:
181
+ raise ValueError(f"Grid size must be positive, got {n}")
182
+ if low >= high:
183
+ raise ValueError(f"Low bound ({low}) must be less than high bound ({high})")
184
+
185
+ def generate_values(self, key: Optional[jax.random.PRNGKey] = None) -> jnp.ndarray:
186
+ """Generate linearly spaced grid values.
187
+
188
+ Parameters
189
+ ----------
190
+ key : jax.random.PRNGKey, optional
191
+ Random key. Ignored for deterministic grid sampling.
192
+
193
+ Returns
194
+ -------
195
+ jnp.ndarray
196
+ Array of linearly spaced values from low to high. If shape is specified,
197
+ values are broadcast to shape (n,) + shape with identical values across
198
+ additional dimensions.
199
+ """
200
+ values = jnp.linspace(self.low, self.high, self.n)
201
+ if self.shape:
202
+ # Broadcast to (n,) + shape - all values in additional dims are identical
203
+ values = values.reshape(self.n, *([1] * len(self.shape)))
204
+ values = jnp.broadcast_to(values, (self.n,) + self.shape)
205
+ return values
206
+
207
+ @property
208
+ def size(self) -> int:
209
+ """Number of grid points.
210
+
211
+ Returns
212
+ -------
213
+ int
214
+ Number of grid points (n).
215
+ """
216
+ return self.n
217
+
218
+ def __repr__(self):
219
+ return f"GridAxis(low={self.low}, high={self.high}, n={self.n})"
220
+
221
+
222
+ class UniformAxis(AbstractAxis):
223
+ """Axis for uniform random sampling over parameter bounds.
224
+
225
+ Generates random values uniformly distributed between low and high bounds
226
+ using stochastic sampling.
227
+
228
+ Parameters
229
+ ----------
230
+ low : float
231
+ Lower bound for sampling.
232
+ high : float
233
+ Upper bound for sampling.
234
+ n : int
235
+ Number of random samples to generate.
236
+
237
+ Raises
238
+ ------
239
+ ValueError
240
+ If n <= 0 or low >= high.
241
+
242
+ Examples
243
+ --------
244
+ >>> import jax
245
+ >>> uniform = UniformAxis(0.0, 1.0, 3)
246
+ >>> values = uniform.generate_values(jax.random.key(42))
247
+ >>> print(values) # Random values between 0 and 1
248
+ """
249
+
250
+ def __init__(
251
+ self, low: float, high: float, n: int, shape: Optional[Tuple[int, ...]] = None
252
+ ):
253
+ """Initialize uniform axis.
254
+
255
+ Parameters
256
+ ----------
257
+ low : float
258
+ Lower bound for sampling.
259
+ high : float
260
+ Upper bound for sampling.
261
+ n : int
262
+ Number of random samples to generate.
263
+ shape : Tuple[int, ...], optional
264
+ Shape of generated values. If specified, values are broadcast to this shape.
265
+ Default is None.
266
+ """
267
+ super().__init__()
268
+ self.low = low
269
+ self.high = high
270
+ self.n = n
271
+ self.shape = shape
272
+
273
+ if n <= 0:
274
+ raise ValueError(f"Sample size must be positive, got {n}")
275
+ if low >= high:
276
+ raise ValueError(f"Low bound ({low}) must be less than high bound ({high})")
277
+
278
+ def generate_values(self, key: Optional[jax.random.PRNGKey] = None) -> jnp.ndarray:
279
+ """Generate uniformly distributed random values.
280
+
281
+ Parameters
282
+ ----------
283
+ key : jax.random.PRNGKey, optional
284
+ Random key for sampling. If None, uses default key(0).
285
+
286
+ Returns
287
+ -------
288
+ jnp.ndarray
289
+ Array of uniformly distributed random values. If shape is specified,
290
+ values are broadcast to shape (n,) + shape with identical values across
291
+ additional dimensions.
292
+ """
293
+ if key is None:
294
+ key = jax.random.key(0)
295
+
296
+ values = jax.random.uniform(key, (self.n,), minval=self.low, maxval=self.high)
297
+ if self.shape:
298
+ # Broadcast to (n,) + shape - all values in additional dims are identical
299
+ values = values.reshape(self.n, *([1] * len(self.shape)))
300
+ values = jnp.broadcast_to(values, (self.n,) + self.shape)
301
+ return values
302
+
303
+ @property
304
+ def size(self) -> int:
305
+ """Number of random samples.
306
+
307
+ Returns
308
+ -------
309
+ int
310
+ Number of samples (n).
311
+ """
312
+ return self.n
313
+
314
+ def __repr__(self):
315
+ return f"UniformAxis(low={self.low}, high={self.high}, n={self.n})"
316
+
317
+
318
+ class DataAxis(AbstractAxis):
319
+ """Axis for sampling from predefined data values.
320
+
321
+ Uses a fixed set of values provided by the user. This axis type is
322
+ deterministic and always returns the same predefined values. The first dimension of the data will always be used as axis dimension.
323
+
324
+ Parameters
325
+ ----------
326
+ values : array-like
327
+ Predefined values to sample from.
328
+
329
+ Raises
330
+ ------
331
+ ValueError
332
+ If values array is empty.
333
+
334
+ Examples
335
+ --------
336
+ >>> import jax.numpy as jnp
337
+ >>> data = DataAxis([1.0, 2.5, 3.7, 4.2])
338
+ >>> values = data.generate_values()
339
+ >>> print(values) # [1.0, 2.5, 3.7, 4.2]
340
+ >>>
341
+ >>> # Can also use JAX arrays
342
+ >>> data_jax = DataAxis(jnp.linspace(0, 1, 5))
343
+ >>> print(data_jax.size) # 5
344
+ """
345
+
346
+ def __init__(self, values: Union[List, jnp.ndarray]):
347
+ """Initialize data axis.
348
+
349
+ Parameters
350
+ ----------
351
+ values : array-like
352
+ Predefined values to sample from.
353
+ """
354
+ super().__init__()
355
+ self.values = jnp.asarray(values)
356
+
357
+ if self.values.size == 0:
358
+ raise ValueError("Data axis requires at least one value")
359
+
360
+ def generate_values(self, key: Optional[jax.random.PRNGKey] = None) -> jnp.ndarray:
361
+ """Return the predefined data values.
362
+
363
+ Parameters
364
+ ----------
365
+ key : jax.random.PRNGKey, optional
366
+ Random key. Ignored for deterministic data sampling.
367
+
368
+ Returns
369
+ -------
370
+ jnp.ndarray
371
+ The predefined data values.
372
+ """
373
+ return self.values
374
+
375
+ @property
376
+ def size(self) -> int:
377
+ """Number of predefined values.
378
+
379
+ Returns
380
+ -------
381
+ int
382
+ Length of the values array.
383
+ """
384
+ return len(self.values)
385
+
386
+ def __repr__(self):
387
+ return f"DataAxis(values={self.values})"
388
+
389
+
390
+ class NumPyroAxis(AbstractAxis):
391
+ """Axis for sampling from NumPyro probability distributions.
392
+
393
+ Samples values from any NumPyro distribution with support for both
394
+ independent sampling (each element different) and broadcast sampling
395
+ (same sample broadcast to shape).
396
+
397
+ Parameters
398
+ ----------
399
+ distribution : numpyro.distributions.Distribution
400
+ NumPyro distribution to sample from.
401
+ n : int
402
+ Number of samples along the axis dimension.
403
+ sample_shape : Tuple[int, ...], optional
404
+ Additional shape dimensions for each sample. Default is None.
405
+ broadcast_mode : bool, optional
406
+ Sampling strategy:
407
+ - False (default): Sample independently for each element in sample_shape
408
+ - True: Sample once per axis point, then broadcast to sample_shape
409
+
410
+ Raises
411
+ ------
412
+ ImportError
413
+ If NumPyro is not installed.
414
+ ValueError
415
+ If n <= 0 or distribution is not a valid NumPyro distribution.
416
+ TypeError
417
+ If distribution is not a NumPyro distribution instance.
418
+
419
+ Examples
420
+ --------
421
+ >>> import numpyro.distributions as dist
422
+ >>>
423
+ >>> # Independent sampling: each element different
424
+ >>> normal_axis = NumPyroAxis(dist.Normal(0.0, 1.0), n=5,
425
+ ... sample_shape=(3, 4), broadcast_mode=False)
426
+ >>> values = normal_axis.generate_values(jax.random.key(42))
427
+ >>> print(values.shape) # (5, 3, 4) with 60 different samples
428
+ >>>
429
+ >>> # Broadcast sampling: same sample per axis point
430
+ >>> beta_axis = NumPyroAxis(dist.Beta(2.0, 5.0), n=3,
431
+ ... sample_shape=(2, 2), broadcast_mode=True)
432
+ >>> values = beta_axis.generate_values(jax.random.key(42))
433
+ >>> print(values.shape) # (3, 2, 2) with 3 unique samples broadcast
434
+ >>>
435
+ >>> # Simple 1D sampling
436
+ >>> uniform_axis = NumPyroAxis(dist.Uniform(0.0, 1.0), n=10)
437
+ >>> values = uniform_axis.generate_values(jax.random.key(42))
438
+ >>> print(values.shape) # (10,)
439
+ """
440
+
441
+ def __init__(
442
+ self,
443
+ distribution,
444
+ n: int,
445
+ sample_shape: Optional[Tuple[int, ...]] = None,
446
+ broadcast_mode: bool = False,
447
+ ):
448
+ """Initialize NumPyro distribution axis.
449
+
450
+ Parameters
451
+ ----------
452
+ distribution : numpyro.distributions.Distribution
453
+ NumPyro distribution to sample from.
454
+ n : int
455
+ Number of samples along the axis dimension.
456
+ sample_shape : Tuple[int, ...], optional
457
+ Additional shape dimensions for each sample. Default is None.
458
+ broadcast_mode : bool, optional
459
+ If True, sample once per axis point then broadcast to sample_shape.
460
+ If False, sample independently for each element. Default is False.
461
+ """
462
+ super().__init__()
463
+
464
+ if not NUMPYRO_AVAILABLE:
465
+ raise ImportError(
466
+ "NumPyro is required for NumPyroAxis. Install with: pip install numpyro"
467
+ )
468
+
469
+ # Check if distribution is a NumPyro distribution
470
+ if not hasattr(distribution, "sample") or not hasattr(
471
+ distribution, "batch_shape"
472
+ ):
473
+ raise TypeError("distribution must be a NumPyro distribution instance")
474
+
475
+ if n <= 0:
476
+ raise ValueError(f"Sample size must be positive, got {n}")
477
+
478
+ self.distribution = distribution
479
+ self.n = n
480
+ self.sample_shape = sample_shape if sample_shape is not None else ()
481
+ self.broadcast_mode = broadcast_mode
482
+
483
+ def generate_values(self, key: Optional[jax.random.PRNGKey] = None) -> jnp.ndarray:
484
+ """Generate values by sampling from the NumPyro distribution.
485
+
486
+ Parameters
487
+ ----------
488
+ key : jax.random.PRNGKey, optional
489
+ Random key for sampling. If None, uses default key(0).
490
+
491
+ Returns
492
+ -------
493
+ jnp.ndarray
494
+ Sampled values with shape (n,) + sample_shape. Sampling strategy
495
+ depends on broadcast_mode:
496
+ - broadcast_mode=False: Each element independently sampled
497
+ - broadcast_mode=True: Each axis sample broadcast to sample_shape
498
+ """
499
+ if key is None:
500
+ key = jax.random.key(0)
501
+
502
+ if self.broadcast_mode and self.sample_shape:
503
+ # Sample once per axis point, then broadcast
504
+ samples = self.distribution.sample(key, sample_shape=(self.n,))
505
+
506
+ # Add singleton dimensions and broadcast
507
+ for _ in range(len(self.sample_shape)):
508
+ samples = samples[..., None]
509
+ samples = jnp.broadcast_to(samples, (self.n,) + self.sample_shape)
510
+
511
+ else:
512
+ # Sample independently for all elements
513
+ full_sample_shape = (self.n,) + self.sample_shape
514
+ samples = self.distribution.sample(key, sample_shape=full_sample_shape)
515
+
516
+ return samples
517
+
518
+ @property
519
+ def size(self) -> int:
520
+ """Number of samples along the axis dimension.
521
+
522
+ Returns
523
+ -------
524
+ int
525
+ Number of axis samples (n).
526
+ """
527
+ return self.n
528
+
529
+ def __repr__(self):
530
+ return (
531
+ f"NumPyroAxis(distribution={self.distribution}, n={self.n}, "
532
+ f"sample_shape={self.sample_shape}, broadcast_mode={self.broadcast_mode})"
533
+ )
534
+
535
+
536
+ # =============================================================================
537
+ # Space Class for Composing Axes
538
+ # =============================================================================
539
+
540
+
541
+ class Space:
542
+ """Composable parameter space built from multiple axes.
543
+
544
+ Space discovers AbstractAxis instances in a parameter state tree and
545
+ composes them to create parameter combinations. Supports both product
546
+ (Cartesian product) and zip (parallel) combination modes.
547
+
548
+ The Space class provides efficient parameter exploration by:
549
+
550
+ - **Automatic axis discovery**: Finds AbstractAxis instances in state trees
551
+ - **Flexible combination modes**: Product mode for full grid search, zip mode for parallel sampling
552
+ - **Efficient iteration**: Pre-generates combinations for fast access
553
+ - **Slicing support**: Create subspaces with `space[start:end]` syntax
554
+
555
+ Parameters
556
+ ----------
557
+ state : dict
558
+ State tree containing AbstractAxis instances and fixed values.
559
+ mode : str, optional
560
+ Combination mode: 'product' for Cartesian product, 'zip' for parallel.
561
+ Default is 'zip'.
562
+ key : jax.random.PRNGKey, optional
563
+ Random key for stochastic axes. Default creates new key.
564
+
565
+ Raises
566
+ ------
567
+ ValueError
568
+ If mode is not 'product' or 'zip', or if no AbstractAxis instances found.
569
+
570
+ Examples
571
+ --------
572
+ >>> import jax.numpy as jnp
573
+ >>> import copy
574
+ >>> from tvboptim.types.spaces import Space, GridAxis, UniformAxis
575
+ >>>
576
+ >>> # Create exploration state
577
+ >>> exploration_state = copy.deepcopy(base_state)
578
+ >>> exploration_state.parameters.coupling.a = GridAxis(0.0, 1.0, 5)
579
+ >>> exploration_state.parameters.model.J_N = UniformAxis(0.0, 1.0, 3)
580
+ >>>
581
+ >>> # Product mode: 5 × 3 = 15 combinations
582
+ >>> space = Space(exploration_state, mode='product')
583
+ >>> print(f"Total combinations: {space.N}")
584
+ >>>
585
+ >>> # Access individual combinations
586
+ >>> first_state = space[0]
587
+ >>> print(first_state.parameters.coupling.a)
588
+ >>>
589
+ >>> # Create subspace
590
+ >>> subset = space[2:8]
591
+ >>> print(f"Subset size: {len(subset)}")
592
+ >>>
593
+ >>> # Parallel execution
594
+ >>> batched_states = space.collect(n_vmap=4, n_pmap=2)
595
+ """
596
+
597
+ def __init__(
598
+ self,
599
+ state: Dict[str, Any],
600
+ mode: str = "zip",
601
+ key: Optional[jax.random.PRNGKey] = None,
602
+ ):
603
+ """Initialize space from state tree.
604
+
605
+ Parameters
606
+ ----------
607
+ state : dict
608
+ State tree containing AbstractAxis instances and fixed values.
609
+ mode : str, optional
610
+ Combination mode: 'product' for Cartesian product, 'zip' for parallel.
611
+ Default is 'zip'.
612
+ key : jax.random.PRNGKey, optional
613
+ Random key for stochastic axes. Default creates new key.
614
+ """
615
+ self.state = state
616
+ self.mode = mode
617
+ self.key = key if key is not None else jax.random.key(0)
618
+
619
+ if mode not in ["product", "zip"]:
620
+ raise ValueError(f"Mode must be 'product' or 'zip', got {mode}")
621
+
622
+ # Use equinox.partition to separate axes from static values
623
+ self.axis_state, self.static_state = eqx.partition(
624
+ state, lambda x: isinstance(x, AbstractAxis)
625
+ )
626
+ axes = jax.tree.leaves(
627
+ self.axis_state, is_leaf=lambda x: isinstance(x, AbstractAxis)
628
+ )
629
+ if not axes:
630
+ # No axes found, raise error
631
+ raise ValueError("Space must contain at least one AbstractAxis instance")
632
+
633
+ # Calculate total combinations
634
+ self._N = self._calculate_total_size()
635
+
636
+ def _calculate_total_size(self) -> int:
637
+ """Calculate total number of parameter combinations."""
638
+ axes = jax.tree.leaves(
639
+ self.axis_state, is_leaf=lambda x: isinstance(x, AbstractAxis)
640
+ )
641
+
642
+ if not axes:
643
+ return 1
644
+
645
+ axis_sizes = [axis.size for axis in axes]
646
+
647
+ if self.mode == "product":
648
+ return int(np.prod(axis_sizes))
649
+ elif self.mode == "zip":
650
+ min_size = min(axis_sizes)
651
+ max_size = max(axis_sizes)
652
+
653
+ # Warn if axes have different sizes in zip mode
654
+ if min_size != max_size:
655
+ lost_combinations = sum(size - min_size for size in axis_sizes)
656
+ print(
657
+ f"WARNING: In zip mode, axes have different sizes {axis_sizes}. "
658
+ f"Using minimum size {min_size}, losing {lost_combinations} combinations."
659
+ )
660
+
661
+ return min_size
662
+
663
+ def _generate_axis_values(self) -> Dict[str, Any]:
664
+ """Generate values for all axes using jax.tree.map."""
665
+ # Pre-generate sub-keys for all axes to avoid correlations
666
+ axes = jax.tree.leaves(
667
+ self.axis_state, is_leaf=lambda x: isinstance(x, AbstractAxis)
668
+ )
669
+ keys = jax.random.split(self.key, len(axes) + 1)[1:] # Skip first key
670
+
671
+ # Create iterator for keys
672
+ key_iter = iter(keys)
673
+
674
+ def generate_values(axis):
675
+ if isinstance(axis, AbstractAxis):
676
+ # Always pass a key, even if not needed (to avoid correlations)
677
+ axis_key = next(key_iter)
678
+ return axis.generate_values(axis_key)
679
+ return axis # Not an axis, return as-is
680
+
681
+ return jax.tree.map(
682
+ generate_values,
683
+ self.axis_state,
684
+ is_leaf=lambda x: isinstance(x, AbstractAxis),
685
+ )
686
+
687
+ @property
688
+ def N(self) -> int:
689
+ """Total number of parameter combinations."""
690
+ return self._N
691
+
692
+ def _generate_all_combinations(self) -> Tuple[List[jnp.ndarray], Any]:
693
+ """
694
+ Generate all parameter combinations as flattened arrays.
695
+
696
+ Returns
697
+ -------
698
+ tuple
699
+ (flattened_arrays, tree_def) where flattened_arrays contains
700
+ all parameter combinations and tree_def allows reconstruction.
701
+ """
702
+ # Generate values for all axes
703
+ axis_values_tree = self._generate_axis_values()
704
+
705
+ # Flatten to get list of arrays
706
+ axis_values_list, axis_tree_def = jax.tree.flatten(
707
+ axis_values_tree, is_leaf=lambda x: isinstance(x, jnp.ndarray)
708
+ )
709
+
710
+ if not axis_values_list:
711
+ return [], axis_tree_def
712
+
713
+ if self.mode == "product":
714
+ # Create meshgrid for Cartesian product and flatten each
715
+ meshgrid_arrays = jnp.meshgrid(*axis_values_list, indexing="ij")
716
+ flattened_arrays = [arr.flatten() for arr in meshgrid_arrays]
717
+ elif self.mode == "zip":
718
+ # In zip mode, arrays are already aligned
719
+ flattened_arrays = axis_values_list
720
+
721
+ return flattened_arrays, axis_tree_def
722
+
723
+ def _get_combination_at_index(self, index: int) -> Dict[str, Any]:
724
+ """Get a single combination by indexing into flattened arrays."""
725
+ flattened_arrays, axis_tree_def = self._generate_all_combinations()
726
+
727
+ if not flattened_arrays:
728
+ return self.static_state
729
+
730
+ # Index into each flattened array to get values for this combination
731
+ indexed_values = [arr[index] for arr in flattened_arrays]
732
+
733
+ # Reconstruct axis tree with indexed values
734
+ axis_values_tree = jax.tree.unflatten(axis_tree_def, indexed_values)
735
+
736
+ # Replace axes with their values using tree_map
737
+ def replace_axis_with_value(axis, value):
738
+ if isinstance(axis, AbstractAxis):
739
+ return value
740
+ return axis
741
+
742
+ processed_axis_tree = jax.tree.map(
743
+ replace_axis_with_value,
744
+ self.axis_state,
745
+ axis_values_tree,
746
+ is_leaf=lambda x: isinstance(x, AbstractAxis),
747
+ )
748
+
749
+ return eqx.combine(processed_axis_tree, self.static_state)
750
+
751
+ # Iterator protocol for sequential execution
752
+ def __iter__(self):
753
+ """Initialize iterator with pre-generated combinations."""
754
+ # Generate all combinations once and store
755
+ self.flattened_arrays, self.axis_tree_def = self._generate_all_combinations()
756
+ self.i = 0
757
+ return self
758
+
759
+ def __next__(self):
760
+ """Get next parameter state using pre-generated arrays."""
761
+ if self.i < self.N:
762
+ if not self.flattened_arrays:
763
+ # No axes case
764
+ state = self.static_state
765
+ else:
766
+ # Index directly into pre-generated arrays
767
+ indexed_values = [arr[self.i] for arr in self.flattened_arrays]
768
+ axis_values_tree = jax.tree.unflatten(
769
+ self.axis_tree_def, indexed_values
770
+ )
771
+
772
+ # Replace axes with values
773
+ def replace_axis_with_value(axis, value):
774
+ if isinstance(axis, AbstractAxis):
775
+ return value
776
+ return axis
777
+
778
+ processed_axis_tree = jax.tree.map(
779
+ replace_axis_with_value,
780
+ self.axis_state,
781
+ axis_values_tree,
782
+ is_leaf=lambda x: isinstance(x, AbstractAxis),
783
+ )
784
+
785
+ state = eqx.combine(processed_axis_tree, self.static_state)
786
+
787
+ self.i += 1
788
+ return state
789
+ raise StopIteration
790
+
791
+ def __getitem__(self, index: Union[int, slice]) -> Union[Dict[str, Any], "Space"]:
792
+ """
793
+ Get specific parameter combination(s).
794
+
795
+ Parameters
796
+ ----------
797
+ index : int or slice
798
+ Index or slice for combinations.
799
+
800
+ Returns
801
+ -------
802
+ dict or Space
803
+ Single state (int index) or new Space with DataAxis instances (slice).
804
+ """
805
+ if isinstance(index, int):
806
+ # Single index: return state dict
807
+ if index < 0:
808
+ index += self.N
809
+ if index < 0 or index >= self.N:
810
+ raise IndexError(
811
+ f"Index {index} out of range for {self.N} combinations"
812
+ )
813
+ return self._get_combination_at_index(index)
814
+
815
+ elif isinstance(index, slice):
816
+ # Slice: return new Space with DataAxis instances
817
+ flattened_arrays, axis_tree_def = self._generate_all_combinations()
818
+
819
+ if not flattened_arrays:
820
+ # No axes, return space with only static state
821
+ return Space(self.static_state, mode="zip", key=self.key)
822
+
823
+ # Slice each array according to the index
824
+ sliced_arrays = [arr[index] for arr in flattened_arrays]
825
+
826
+ # Check if slice results in empty arrays
827
+ if any(arr.size == 0 for arr in sliced_arrays):
828
+ raise ValueError(
829
+ f"Slice {index} results in empty parameter space with no combinations"
830
+ )
831
+
832
+ # Create new axis state with DataAxis instances
833
+ data_axes = [DataAxis(values) for values in sliced_arrays]
834
+ new_axis_state = jax.tree.unflatten(axis_tree_def, data_axes)
835
+
836
+ # Create new Space in zip mode
837
+ return Space(
838
+ eqx.combine(new_axis_state, self.static_state), mode="zip", key=self.key
839
+ )
840
+
841
+ else:
842
+ raise TypeError(f"Index must be int or slice, got {type(index)}")
843
+
844
+ def __len__(self) -> int:
845
+ """Number of parameter combinations."""
846
+ return self.N
847
+
848
+ def collect(
849
+ self,
850
+ n_vmap: int = None,
851
+ n_pmap: int = None,
852
+ fill_value: float = jnp.nan,
853
+ combine: bool = True,
854
+ ) -> Dict[str, Any]:
855
+ """Generate batched states for parallel execution.
856
+
857
+ Creates parameter combinations organized for efficient JAX parallel execution
858
+ using vmap and pmap. This method is essential for high-performance parameter
859
+ exploration on modern accelerators.
860
+
861
+ Parameters
862
+ ----------
863
+ n_vmap : int, optional
864
+ Number of states to vectorize over using vmap. If None, defaults to 1.
865
+ n_pmap : int, optional
866
+ Number of devices for parallel mapping with pmap. If None, defaults to 1.
867
+ fill_value : float, optional
868
+ Value used for padding when reshaping to target dimensions.
869
+ Default is jnp.nan.
870
+ combine : bool, optional
871
+ Whether to combine the static state with the parameter combinations
872
+ into a complete state. If False, returns (axis_tree, static_state) tuple.
873
+ Default is True.
874
+
875
+ Returns
876
+ -------
877
+ dict or tuple
878
+ If combine=True: State tree with batched parameter combinations shaped
879
+ for parallel execution with dimensions (n_pmap, n_vmap, n_map).
880
+ If combine=False: Tuple of (batched_axis_tree, static_state).
881
+
882
+ Warnings
883
+ --------
884
+ If the total requested size (n_pmap * n_vmap * n_map) exceeds the number
885
+ of combinations N, padding with fill_value will be used.
886
+
887
+ Examples
888
+ --------
889
+ >>> # Create space with 100 combinations
890
+ >>> space = Space(exploration_state, mode='product')
891
+ >>>
892
+ >>> # Batch for parallel execution: 2 devices, 8 vectors each
893
+ >>> batched_states = space.collect(n_vmap=8, n_pmap=2)
894
+ >>> print(batched_states.shape) # (2, 8, n_map)
895
+ >>>
896
+ >>> # Use with JAX transformations
897
+ >>> results = jax.pmap(jax.vmap(simulation_fn))(batched_states)
898
+ """
899
+ # Calculate batch dimensions
900
+ shape = tuple()
901
+ if n_vmap is None:
902
+ n_vmap = 1
903
+ else:
904
+ shape = (n_vmap,) + shape
905
+ if n_pmap is None:
906
+ n_pmap = 1
907
+ else:
908
+ shape = (n_pmap,) + shape
909
+ n_map = int(jnp.ceil(self.N / (n_vmap * n_pmap)))
910
+ shape = shape + (n_map,)
911
+
912
+ # If n_pmap * n_vmap * n_map > N, warn that fill value is used
913
+ if n_pmap * n_vmap * n_map > self.N:
914
+ print(
915
+ f"WARNING: Total requested size {n_pmap * n_vmap * n_map} exceeds N = {self.N}. Using fill value: {fill_value}"
916
+ )
917
+
918
+ # Generate all combinations as flattened arrays
919
+ array_list, axis_tree_def = self._generate_all_combinations()
920
+
921
+ if not array_list:
922
+ # No axes, just return static state with proper batching
923
+ return self.static_state
924
+
925
+ # Reshape first dimension of each flattened array to batch dimensions
926
+ batched_arrays = [
927
+ safe_reshape(arr, shape + arr.shape[1:], fill_value) for arr in array_list
928
+ ]
929
+
930
+ # Reconstruct the axis tree with batched arrays
931
+ batched_axis_tree = jax.tree.unflatten(axis_tree_def, batched_arrays)
932
+
933
+ if combine:
934
+ # Combine with static state
935
+ return eqx.combine(batched_axis_tree, self.static_state)
936
+ else:
937
+ return batched_axis_tree, self.static_state
938
+
939
+ def __repr__(self):
940
+ axes = jax.tree.leaves(
941
+ self.axis_state, is_leaf=lambda x: isinstance(x, AbstractAxis)
942
+ )
943
+ return f"Space(N={self.N}, mode='{self.mode}', axes={len(axes)})"