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,769 @@
1
+ """
2
+ New minimal Parameter implementation for TVBOptim refactoring.
3
+
4
+ This module implements a simplified Parameter class that:
5
+ - Removes redundant fields (name, doc, free/grad)
6
+ - Provides native JAX integration via __jax_array__
7
+ - Implements full arithmetic operations
8
+ - Supports specialized subclasses (BoundedParameter)
9
+ """
10
+
11
+ from typing import Any, Tuple, Union
12
+
13
+ import jax
14
+ import jax.numpy as jnp
15
+ import numpy as np
16
+ from jax.tree_util import register_pytree_node_class
17
+
18
+
19
+ @register_pytree_node_class
20
+ class Parameter:
21
+ """
22
+ A minimal JAX-native parameter with full arithmetic support.
23
+
24
+ If placed at a position in the state tree, that position will take part in optimizations and will be differentiated. A state can be split into parameters and static parts by partition_state and combined by combine_state.
25
+
26
+ Parameters
27
+ ----------
28
+ value : Union[float, int, jnp.ndarray]
29
+ The parameter value. Will be converted to JAX array.
30
+
31
+ Examples
32
+ --------
33
+ >>> p1 = Parameter(1.0)
34
+ >>> p2 = Parameter(jnp.array([1, 2, 3]))
35
+ >>> result = p1 + p2 # Works with JAX arithmetic
36
+ >>> grad_fn = jax.grad(lambda p: jnp.sum(p**2))
37
+ >>> gradients = grad_fn(p1) # Seamless gradients
38
+ """
39
+
40
+ def __init__(self, value: Union[float, int, jnp.ndarray]) -> None:
41
+ self.value = jnp.asarray(value)
42
+
43
+ def __repr__(self) -> str:
44
+ # return f"Parameter({self.__jax_array__()})"
45
+ return f"Parameter({self.value})"
46
+
47
+ def __str__(self) -> str:
48
+ return self.__repr__()
49
+
50
+ def __format__(self, format_spec: str) -> str:
51
+ """Support f-string formatting by delegating to the underlying value."""
52
+ return format(float(self.__jax_array__()), format_spec)
53
+
54
+ # JAX Integration
55
+ def __jax_array__(self) -> jnp.ndarray:
56
+ """JAX array protocol - makes Parameter behave like native JAX array."""
57
+ return self.value
58
+
59
+ def __array__(self) -> jnp.ndarray:
60
+ """NumPy array protocol compatibility."""
61
+ # return self.value # Return JAX array directly instead of converting to numpy
62
+ return np.array(
63
+ self.__jax_array__()
64
+ ) # Return JAX array directly instead of converting to numpy
65
+
66
+ # Properties
67
+ @property
68
+ def shape(self) -> Tuple[int, ...]:
69
+ """Shape of the parameter value."""
70
+ return self.value.shape
71
+
72
+ @shape.setter
73
+ def shape(self, shape: Tuple[int, ...]) -> None:
74
+ """
75
+ Broadcasts the value to the desired shape if possible.
76
+
77
+ Useful to turn a global parameter local.
78
+
79
+ Args:
80
+ shape: Desired shape for the parameter
81
+
82
+ Raises:
83
+ ValueError: If the parameter shape cannot be broadcasted
84
+ """
85
+ if self.shape == shape:
86
+ pass
87
+ else:
88
+ try:
89
+ self.value = jnp.broadcast_to(self.value, shape)
90
+ except ValueError:
91
+ raise ValueError(
92
+ f"Parameter shape {shape} does not match value shape {self.shape} and can not be broadcasted automatically."
93
+ )
94
+
95
+ @property
96
+ def dtype(self) -> jnp.dtype:
97
+ """Data type of the parameter value."""
98
+ return self.value.dtype
99
+
100
+ @property
101
+ def ndim(self) -> int:
102
+ """Number of dimensions."""
103
+ return self.value.ndim
104
+
105
+ @property
106
+ def size(self) -> int:
107
+ """Total number of elements."""
108
+ return self.value.size
109
+
110
+ # Arithmetic Operations - Return JAX arrays for seamless integration
111
+ def __add__(self, other) -> jnp.ndarray:
112
+ """Addition: param + other"""
113
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
114
+ return self.__jax_array__() + other_val
115
+
116
+ def __radd__(self, other) -> jnp.ndarray:
117
+ """Reverse addition: other + param"""
118
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
119
+ return other_val + self.__jax_array__()
120
+
121
+ def __sub__(self, other) -> jnp.ndarray:
122
+ """Subtraction: param - other"""
123
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
124
+ return self.__jax_array__() - other_val
125
+
126
+ def __rsub__(self, other) -> jnp.ndarray:
127
+ """Reverse subtraction: other - param"""
128
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
129
+ return other_val - self.__jax_array__()
130
+
131
+ def __mul__(self, other) -> jnp.ndarray:
132
+ """Multiplication: param * other"""
133
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
134
+ return self.__jax_array__() * other_val
135
+
136
+ def __rmul__(self, other) -> jnp.ndarray:
137
+ """Reverse multiplication: other * param"""
138
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
139
+ return other_val * self.__jax_array__()
140
+
141
+ def __truediv__(self, other) -> jnp.ndarray:
142
+ """Division: param / other"""
143
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
144
+ return self.__jax_array__() / other_val
145
+
146
+ def __rtruediv__(self, other) -> jnp.ndarray:
147
+ """Reverse division: other / param"""
148
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
149
+ return other_val / self.__jax_array__()
150
+
151
+ def __floordiv__(self, other) -> jnp.ndarray:
152
+ """Floor division: param // other"""
153
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
154
+ return self.__jax_array__() // other_val
155
+
156
+ def __rfloordiv__(self, other) -> jnp.ndarray:
157
+ """Reverse floor division: other // param"""
158
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
159
+ return other_val // self.__jax_array__()
160
+
161
+ def __mod__(self, other) -> jnp.ndarray:
162
+ """Modulo: param % other"""
163
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
164
+ return self.__jax_array__() % other_val
165
+
166
+ def __rmod__(self, other) -> jnp.ndarray:
167
+ """Reverse modulo: other % param"""
168
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
169
+ return other_val % self.__jax_array__()
170
+
171
+ def __pow__(self, other) -> jnp.ndarray:
172
+ """Power: param ** other"""
173
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
174
+ return self.__jax_array__() ** other_val
175
+
176
+ def __rpow__(self, other) -> jnp.ndarray:
177
+ """Reverse power: other ** param"""
178
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
179
+ return other_val ** self.__jax_array__()
180
+
181
+ # Unary Operations
182
+ def __neg__(self) -> jnp.ndarray:
183
+ """Negation: -param"""
184
+ return -self.__jax_array__()
185
+
186
+ def __pos__(self) -> jnp.ndarray:
187
+ """Positive: +param"""
188
+ return +self.__jax_array__()
189
+
190
+ def __abs__(self) -> jnp.ndarray:
191
+ """Absolute value: abs(param)"""
192
+ return jnp.abs(self.__jax_array__())
193
+
194
+ # Comparison Operations
195
+ def __eq__(self, other) -> jnp.ndarray:
196
+ """Equality: param == other"""
197
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
198
+ return self.__jax_array__() == other_val
199
+
200
+ def __ne__(self, other) -> jnp.ndarray:
201
+ """Inequality: param != other"""
202
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
203
+ return self.__jax_array__() != other_val
204
+
205
+ def __lt__(self, other) -> jnp.ndarray:
206
+ """Less than: param < other"""
207
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
208
+ return self.__jax_array__() < other_val
209
+
210
+ def __le__(self, other) -> jnp.ndarray:
211
+ """Less than or equal: param <= other"""
212
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
213
+ return self.__jax_array__() <= other_val
214
+
215
+ def __gt__(self, other) -> jnp.ndarray:
216
+ """Greater than: param > other"""
217
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
218
+ return self.__jax_array__() > other_val
219
+
220
+ def __ge__(self, other) -> jnp.ndarray:
221
+ """Greater than or equal: param >= other"""
222
+ other_val = other.__jax_array__() if hasattr(other, "__jax_array__") else other
223
+ return self.__jax_array__() >= other_val
224
+
225
+ # Indexing
226
+ def __getitem__(self, key) -> jnp.ndarray:
227
+ """Indexing: param[key]"""
228
+ return self.__jax_array__()[key]
229
+
230
+ # PyTree Implementation
231
+ def tree_flatten(self) -> Tuple[Tuple[jnp.ndarray], None]:
232
+ """Flatten for JAX pytree registration."""
233
+ children = (self.value,)
234
+ aux_data = None
235
+ return children, aux_data
236
+
237
+ @classmethod
238
+ def tree_unflatten(
239
+ cls, aux_data: None, children: Tuple[jnp.ndarray]
240
+ ) -> "Parameter":
241
+ """Unflatten for JAX pytree registration."""
242
+ instance = cls.__new__(cls)
243
+ instance.value = children[0] # Normalized values (ones)
244
+ return instance
245
+
246
+
247
+ @register_pytree_node_class
248
+ class NormalizedParameter(Parameter):
249
+ """
250
+ Parameter that stores normalized values (ones) internally but presents
251
+ scaled values (scale * ones) to the outside world.
252
+
253
+ This enables optimization with normalized coordinates where gradients
254
+ have consistent magnitudes across different parameter scales, while
255
+ still returning properly scaled values for computation.
256
+
257
+ Parameters
258
+ ----------
259
+ value : Union[float, int, jnp.ndarray]
260
+ The original parameter value used to compute the static scale.
261
+
262
+ Examples
263
+ --------
264
+ >>> param = NormalizedParameter(jnp.array([2.0, 4.0, 6.0]))
265
+ >>> param.value # Internal normalized storage (ones)
266
+ Array([1., 1., 1.], dtype=float32)
267
+ >>> param.__jax_array__() # External scaled values (scale * ones)
268
+ Array([2., 4., 6.], dtype=float32)
269
+ >>> param.scale # Static scale factor
270
+ Array([2., 4., 6.], dtype=float32)
271
+ """
272
+
273
+ def __init__(self, value: Union[float, int, jnp.ndarray]) -> None:
274
+ # Store original value as static scale
275
+ original_value = jnp.asarray(value)
276
+ self.scale = original_value
277
+
278
+ # Store normalized values (ones) internally
279
+ normalized_value = jnp.ones_like(original_value)
280
+
281
+ # Initialize parent with normalized value
282
+ super().__init__(normalized_value)
283
+
284
+ def __repr__(self) -> str:
285
+ return f"NormalizedParameter(scale={self.scale}, normalized={self.value}, value ={self.__jax_array__()})"
286
+
287
+ def __jax_array__(self) -> jnp.ndarray:
288
+ """Return scaled values: scale * normalized_ones."""
289
+ return self.scale * self.value # scale * ones = original values
290
+
291
+ def tree_flatten(self) -> Tuple[Tuple[jnp.ndarray], jnp.ndarray]:
292
+ """Flatten for JAX pytree registration."""
293
+ children = (self.value,) # Only normalized ones are differentiable
294
+ aux_data = self.scale # Scale is static (not differentiable)
295
+ return children, aux_data
296
+
297
+ @classmethod
298
+ def tree_unflatten(
299
+ cls, aux_data: jnp.ndarray, children: Tuple[jnp.ndarray]
300
+ ) -> "NormalizedParameter":
301
+ """Unflatten for JAX pytree registration."""
302
+ # Reconstruct from normalized values and static scale
303
+ instance = cls.__new__(cls)
304
+ instance.value = children[0] # Normalized values (ones)
305
+ instance.scale = aux_data # Static scale factor
306
+ return instance
307
+
308
+
309
+ @register_pytree_node_class
310
+ class TransformedParameter(Parameter):
311
+ """
312
+ Parameter with custom forward and reverse transformations.
313
+
314
+ This enables arbitrary parameter transformations by applying:
315
+ - inverse transform: constrained → unconstrained (at initialization)
316
+ - forward transform: unconstrained → constrained (when used as array)
317
+
318
+ The parameter is stored internally in unconstrained space for smooth
319
+ optimization, but presents constrained values when used.
320
+
321
+ Parameters
322
+ ----------
323
+ value : Union[float, int, jnp.ndarray]
324
+ The initial constrained parameter value.
325
+ forward_transform : callable
326
+ Function to transform from unconstrained to constrained space.
327
+ Applied every time the parameter is used as a JAX array.
328
+ inverse_transform : callable
329
+ Function to transform from constrained to unconstrained space.
330
+ Applied once at initialization.
331
+
332
+ Examples
333
+ --------
334
+ >>> # Log-normal parameter
335
+ >>> forward = lambda x: jnp.exp(x) # unconstrained → constrained
336
+ >>> inverse = lambda x: jnp.log(x) # constrained → unconstrained
337
+ >>> param = TransformedParameter(2.0, forward, inverse)
338
+ >>> param.__jax_array__() # Returns exp(log(2.0)) = 2.0
339
+
340
+ >>> # Sigmoid bounded parameter
341
+ >>> forward = lambda x: jax.nn.sigmoid(x) # unconstrained → constrained
342
+ >>> inverse = lambda x: jnp.log(x / (1 - x)) # constrained → unconstrained
343
+ >>> param = TransformedParameter(0.7, forward, inverse)
344
+ """
345
+
346
+ def __init__(
347
+ self,
348
+ value: Union[float, int, jnp.ndarray],
349
+ forward_transform: callable,
350
+ inverse_transform: callable,
351
+ ) -> None:
352
+ # Apply inverse transform to store in unconstrained space
353
+ unconstrained_value = inverse_transform(jnp.asarray(value))
354
+ super().__init__(unconstrained_value)
355
+ self.forward_transform = forward_transform
356
+ self.inverse_transform = inverse_transform
357
+
358
+ def __repr__(self) -> str:
359
+ return f"TransformedParameter(original={self.__jax_array__()}, transformed={self.value})"
360
+
361
+ def __jax_array__(self) -> jnp.ndarray:
362
+ """Return transformed value in constrained space."""
363
+ return self.forward_transform(self.value)
364
+
365
+ def tree_flatten(self) -> Tuple[Tuple[jnp.ndarray], Tuple[callable, callable]]:
366
+ """Flatten for JAX pytree registration."""
367
+ children = (self.value,) # Only unconstrained values are differentiable
368
+ aux_data = (self.forward_transform, self.inverse_transform)
369
+ return children, aux_data
370
+
371
+ @classmethod
372
+ def tree_unflatten(
373
+ cls, aux_data: Tuple[callable, callable], children: Tuple[jnp.ndarray]
374
+ ) -> "TransformedParameter":
375
+ """Unflatten for JAX pytree registration."""
376
+ forward_transform, inverse_transform = aux_data
377
+ instance = cls.__new__(cls)
378
+ instance.value = children[0] # Unconstrained values
379
+ instance.forward_transform = forward_transform
380
+ instance.inverse_transform = inverse_transform
381
+ return instance
382
+
383
+
384
+ @register_pytree_node_class
385
+ class SigmoidBoundedParameter(TransformedParameter):
386
+ """
387
+ Parameter with sigmoid-based bounds enforcement.
388
+
389
+ Uses sigmoid transformation to map from unconstrained real space to
390
+ bounded interval [low, high]. This provides smooth gradients and
391
+ avoids the gradient issues of hard clipping.
392
+
393
+ Parameters
394
+ ----------
395
+ value : Union[float, int, jnp.ndarray]
396
+ The initial parameter value (will be clipped to bounds).
397
+ low : float
398
+ Lower bound for the parameter value.
399
+ high : float
400
+ Upper bound for the parameter value.
401
+
402
+ Examples
403
+ --------
404
+ >>> param = SigmoidBoundedParameter(0.7, low=0.0, high=1.0)
405
+ >>> param.__jax_array__() # Returns value in [0, 1]
406
+ >>> # Gradients flow smoothly through sigmoid transformation
407
+ """
408
+
409
+ def __init__(
410
+ self, value: Union[float, int, jnp.ndarray], low: float, high: float
411
+ ) -> None:
412
+ if low >= high:
413
+ raise ValueError(f"Invalid bounds: low ({low}) must be < high ({high})")
414
+
415
+ self.low = low
416
+ self.high = high
417
+
418
+ # Clip initial value to bounds
419
+ clipped_value = jnp.clip(jnp.asarray(value), low, high)
420
+
421
+ def forward_transform(x):
422
+ """Map from unconstrained space to [low, high] using sigmoid."""
423
+ return low + (high - low) * jax.nn.sigmoid(x)
424
+
425
+ def inverse_transform(x):
426
+ """Map from [low, high] to unconstrained space using logit."""
427
+ # Normalize to [0, 1]
428
+ normalized = (x - low) / (high - low)
429
+ # Clamp to avoid numerical issues with log(0) or log(inf)
430
+ normalized = jnp.clip(normalized, 1e-7, 1 - 1e-7)
431
+ # Apply logit
432
+ return jnp.log(normalized / (1 - normalized))
433
+
434
+ super().__init__(clipped_value, forward_transform, inverse_transform)
435
+
436
+ def __repr__(self) -> str:
437
+ return f"SigmoidBoundedParameter({self.__jax_array__()}, low={self.low}, high={self.high})"
438
+
439
+ def tree_flatten(
440
+ self,
441
+ ) -> Tuple[Tuple[jnp.ndarray], Tuple[float, float, callable, callable]]:
442
+ """Flatten for JAX pytree registration."""
443
+ children = (self.value,)
444
+ aux_data = (self.low, self.high, self.forward_transform, self.inverse_transform)
445
+ return children, aux_data
446
+
447
+ @classmethod
448
+ def tree_unflatten(
449
+ cls,
450
+ aux_data: Tuple[float, float, callable, callable],
451
+ children: Tuple[jnp.ndarray],
452
+ ) -> "SigmoidBoundedParameter":
453
+ """Unflatten for JAX pytree registration."""
454
+ low, high, forward_transform, inverse_transform = aux_data
455
+ instance = cls.__new__(cls)
456
+ instance.value = children[0]
457
+ instance.low = low
458
+ instance.high = high
459
+ instance.forward_transform = forward_transform
460
+ instance.inverse_transform = inverse_transform
461
+ return instance
462
+
463
+
464
+ @register_pytree_node_class
465
+ class LogPositiveParameter(TransformedParameter):
466
+ """
467
+ Parameter constrained to be positive using log transformation.
468
+
469
+ Maps from unconstrained real space to (lower, ∞) using log transformation.
470
+ This provides smooth gradients and is ideal for scale parameters like
471
+ conductances, time constants, etc.
472
+
473
+ Parameters
474
+ ----------
475
+ value : Union[float, int, jnp.ndarray]
476
+ The initial parameter value (must be > lower).
477
+ lower : float, optional
478
+ Lower bound for the parameter value. Default is 0.0.
479
+
480
+ Examples
481
+ --------
482
+ >>> param = LogPositiveParameter(2.0) # Always positive
483
+ >>> param = LogPositiveParameter(5.0, lower=1.0) # Always > 1.0
484
+ """
485
+
486
+ def __init__(
487
+ self, value: Union[float, int, jnp.ndarray], lower: float = 0.0
488
+ ) -> None:
489
+ value_array = jnp.asarray(value)
490
+ if jnp.any(value_array <= lower):
491
+ raise ValueError(f"Initial value must be > {lower}, got {value}")
492
+
493
+ self.lower = lower
494
+
495
+ def forward_transform(x):
496
+ """Map from unconstrained space to (lower, ∞) using exp."""
497
+ return lower + jnp.exp(x)
498
+
499
+ def inverse_transform(x):
500
+ """Map from (lower, ∞) to unconstrained space using log."""
501
+ return jnp.log(x - lower)
502
+
503
+ super().__init__(value, forward_transform, inverse_transform)
504
+
505
+ def __repr__(self) -> str:
506
+ return f"LogPositiveParameter({self.__jax_array__()}, lower={self.lower})"
507
+
508
+ def tree_flatten(
509
+ self,
510
+ ) -> Tuple[Tuple[jnp.ndarray], Tuple[float, callable, callable]]:
511
+ """Flatten for JAX pytree registration."""
512
+ children = (self.value,)
513
+ aux_data = (self.lower, self.forward_transform, self.inverse_transform)
514
+ return children, aux_data
515
+
516
+ @classmethod
517
+ def tree_unflatten(
518
+ cls, aux_data: Tuple[float, callable, callable], children: Tuple[jnp.ndarray]
519
+ ) -> "LogPositiveParameter":
520
+ """Unflatten for JAX pytree registration."""
521
+ lower, forward_transform, inverse_transform = aux_data
522
+ instance = cls.__new__(cls)
523
+ instance.value = children[0]
524
+ instance.lower = lower
525
+ instance.forward_transform = forward_transform
526
+ instance.inverse_transform = inverse_transform
527
+ return instance
528
+
529
+
530
+ @register_pytree_node_class
531
+ class LogNegativeParameter(TransformedParameter):
532
+ """
533
+ Parameter constrained to be negative using log transformation.
534
+
535
+ Maps from unconstrained real space to (-∞, upper) using negative log transformation.
536
+ Useful for parameters that must remain below a certain threshold.
537
+
538
+ Parameters
539
+ ----------
540
+ value : Union[float, int, jnp.ndarray]
541
+ The initial parameter value (must be < upper).
542
+ upper : float, optional
543
+ Upper bound for the parameter value. Default is 0.0.
544
+
545
+ Examples
546
+ --------
547
+ >>> param = LogNegativeParameter(-2.0) # Always negative
548
+ >>> param = LogNegativeParameter(-1.0, upper=5.0) # Always < 5.0
549
+ """
550
+
551
+ def __init__(
552
+ self, value: Union[float, int, jnp.ndarray], upper: float = 0.0
553
+ ) -> None:
554
+ value_array = jnp.asarray(value)
555
+ if jnp.any(value_array >= upper):
556
+ raise ValueError(f"Initial value must be < {upper}, got {value}")
557
+
558
+ self.upper = upper
559
+
560
+ def forward_transform(x):
561
+ """Map from unconstrained space to (-∞, upper) using -exp."""
562
+ return upper - jnp.exp(x)
563
+
564
+ def inverse_transform(x):
565
+ """Map from (-∞, upper) to unconstrained space using log."""
566
+ return jnp.log(upper - x)
567
+
568
+ super().__init__(value, forward_transform, inverse_transform)
569
+
570
+ def __repr__(self) -> str:
571
+ return f"LogNegativeParameter({self.__jax_array__()}, upper={self.upper})"
572
+
573
+ def tree_flatten(
574
+ self,
575
+ ) -> Tuple[Tuple[jnp.ndarray], Tuple[float, callable, callable]]:
576
+ """Flatten for JAX pytree registration."""
577
+ children = (self.value,)
578
+ aux_data = (self.upper, self.forward_transform, self.inverse_transform)
579
+ return children, aux_data
580
+
581
+ @classmethod
582
+ def tree_unflatten(
583
+ cls, aux_data: Tuple[float, callable, callable], children: Tuple[jnp.ndarray]
584
+ ) -> "LogNegativeParameter":
585
+ """Unflatten for JAX pytree registration."""
586
+ upper, forward_transform, inverse_transform = aux_data
587
+ instance = cls.__new__(cls)
588
+ instance.value = children[0]
589
+ instance.upper = upper
590
+ instance.forward_transform = forward_transform
591
+ instance.inverse_transform = inverse_transform
592
+ return instance
593
+
594
+
595
+ @register_pytree_node_class
596
+ class MaskedParameter(TransformedParameter):
597
+ """
598
+ Parameter that keeps masked entries fixed at their initial values.
599
+
600
+ This allows selective optimization where only certain entries in an array
601
+ are subject to optimization while others remain frozen. Useful for maintaining
602
+ structural constraints like sparsity patterns, symmetries, or fixed values.
603
+
604
+ Parameters
605
+ ----------
606
+ value : Union[float, int, jnp.ndarray]
607
+ The initial parameter values.
608
+ mask : jnp.ndarray
609
+ Boolean mask where True indicates optimizable entries and False indicates
610
+ frozen entries that maintain their initial values.
611
+
612
+ Examples
613
+ --------
614
+ >>> # Keep zero entries frozen, optimize non-zero entries
615
+ >>> value = jnp.array([1.0, 0.0, 3.0, 0.0, 5.0])
616
+ >>> mask = value != 0.0 # True for non-zero, False for zero
617
+ >>> param = MaskedParameter(value, mask)
618
+ >>> # Only positions [0, 2, 4] will be optimized
619
+
620
+ >>> # Upper triangular matrix optimization
621
+ >>> matrix = jnp.array([[1, 2], [0, 3]])
622
+ >>> mask = jnp.triu(jnp.ones_like(matrix)).astype(bool)
623
+ >>> param = MaskedParameter(matrix, mask)
624
+ """
625
+
626
+ def __init__(
627
+ self, value: Union[float, int, jnp.ndarray], mask: jnp.ndarray
628
+ ) -> None:
629
+ value_array = jnp.asarray(value)
630
+ self.mask = jnp.asarray(mask, dtype=bool)
631
+
632
+ # Ensure mask and value have compatible shapes
633
+ if self.mask.shape != value_array.shape:
634
+ raise ValueError(
635
+ f"Mask shape {self.mask.shape} must match value shape {value_array.shape}"
636
+ )
637
+
638
+ # Store frozen values (entries where mask is False)
639
+ self.frozen_values = jnp.where(self.mask, 0.0, value_array)
640
+
641
+ def forward_transform(x):
642
+ """Apply mask: use optimized values where mask=True, frozen values where mask=False."""
643
+ return jnp.where(self.mask, x, self.frozen_values)
644
+
645
+ def inverse_transform(x):
646
+ """Extract optimizable values: set frozen entries to 0 in unconstrained space."""
647
+ return jnp.where(self.mask, x, 0.0)
648
+
649
+ super().__init__(value, forward_transform, inverse_transform)
650
+
651
+ def __repr__(self) -> str:
652
+ n_optimizable = jnp.sum(self.mask)
653
+ n_frozen = jnp.sum(~self.mask)
654
+ return f"MaskedParameter(shape={self.mask.shape}, optimizable={n_optimizable}, frozen={n_frozen})"
655
+
656
+ def tree_flatten(
657
+ self,
658
+ ) -> Tuple[Tuple[jnp.ndarray], Tuple[jnp.ndarray, jnp.ndarray, callable, callable]]:
659
+ """Flatten for JAX pytree registration."""
660
+ children = (self.value,)
661
+ aux_data = (
662
+ self.mask,
663
+ self.frozen_values,
664
+ self.forward_transform,
665
+ self.inverse_transform,
666
+ )
667
+ return children, aux_data
668
+
669
+ @classmethod
670
+ def tree_unflatten(
671
+ cls,
672
+ aux_data: Tuple[jnp.ndarray, jnp.ndarray, callable, callable],
673
+ children: Tuple[jnp.ndarray],
674
+ ) -> "MaskedParameter":
675
+ """Unflatten for JAX pytree registration."""
676
+ mask, frozen_values, forward_transform, inverse_transform = aux_data
677
+ instance = cls.__new__(cls)
678
+ instance.value = children[0]
679
+ instance.mask = mask
680
+ instance.frozen_values = frozen_values
681
+ instance.forward_transform = forward_transform
682
+ instance.inverse_transform = inverse_transform
683
+ return instance
684
+
685
+
686
+ @register_pytree_node_class
687
+ class BoundedParameter(Parameter):
688
+ """
689
+ Parameter with automatic bounds enforcement.
690
+
691
+ The bounds are applied transparently whenever the parameter is used
692
+ as a JAX array, ensuring constraints are always satisfied.
693
+
694
+ Parameters
695
+ ----------
696
+ value : Union[float, int, jnp.ndarray]
697
+ The parameter value. Will be converted to JAX array.
698
+ low : float
699
+ Lower bound for the parameter value.
700
+ high : float
701
+ Upper bound for the parameter value.
702
+
703
+ Examples
704
+ --------
705
+ >>> param = BoundedParameter(1.5, low=0.0, high=1.0)
706
+ >>> result = param + 0.1 # Automatically clips to [0, 1]
707
+ >>> print(result) # 1.1
708
+ """
709
+
710
+ def __init__(
711
+ self, value: Union[float, int, jnp.ndarray], low: float, high: float
712
+ ) -> None:
713
+ super().__init__(value)
714
+ self.low = low
715
+ self.high = high
716
+
717
+ if low >= high:
718
+ raise ValueError(f"Invalid bounds: low ({low}) must be < high ({high})")
719
+
720
+ def __repr__(self) -> str:
721
+ return f"BoundedParameter({self.value}, low={self.low}, high={self.high})"
722
+ # return f"BoundedParameter({self.__jax_array__()}, low={self.low}, high={self.high})"
723
+
724
+ def __jax_array__(self) -> jnp.ndarray:
725
+ """Return clipped value respecting bounds."""
726
+ return jnp.clip(self.value, self.low, self.high)
727
+
728
+ def tree_flatten(self) -> Tuple[Tuple[jnp.ndarray], Tuple[float, float]]:
729
+ """Flatten for JAX pytree registration."""
730
+ children = (self.value,)
731
+ aux_data = (self.low, self.high)
732
+ return children, aux_data
733
+
734
+ @classmethod
735
+ def tree_unflatten(
736
+ cls, aux_data: Tuple[float, float], children: Tuple[jnp.ndarray]
737
+ ) -> "BoundedParameter":
738
+ """Unflatten for JAX pytree registration."""
739
+ low, high = aux_data
740
+ return cls(children[0], low, high)
741
+
742
+
743
+ # Utility functions for working with parameters
744
+ def is_parameter(obj: Any) -> bool:
745
+ """Check if object is a Parameter instance."""
746
+ return isinstance(obj, Parameter)
747
+
748
+
749
+ def extract_values(tree: Any) -> Any:
750
+ """
751
+ Extract parameter values from a pytree, leaving other types unchanged.
752
+
753
+ This replaces the old collect_parameters() function.
754
+
755
+ Parameters
756
+ ----------
757
+ tree : Any
758
+ PyTree potentially containing Parameter objects
759
+
760
+ Returns
761
+ -------
762
+ Any
763
+ PyTree with Parameter objects replaced by their values
764
+ """
765
+ return jax.tree.map(
766
+ lambda x: x.__jax_array__() if is_parameter(x) else x,
767
+ tree,
768
+ is_leaf=is_parameter,
769
+ )