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,686 @@
1
+ """Unified network class for coupling system.
2
+
3
+ This module implements a single Network class that handles all equation types
4
+ (ODE/DDE/SDE/SDDE) through composition rather than inheritance.
5
+ """
6
+
7
+ import warnings
8
+ from typing import TYPE_CHECKING, Dict, List, Optional, Union
9
+
10
+ import jax.numpy as jnp
11
+
12
+ from ..coupling.base import AbstractCoupling
13
+ from ..dynamics.base import AbstractDynamics
14
+ from ..graph.base import AbstractGraph
15
+ from ..noise.base import AbstractNoise
16
+ from ..result import NativeSolution
17
+ from .bunch import Bunch
18
+
19
+ if TYPE_CHECKING:
20
+ from ..external_input.base import AbstractExternalInput
21
+
22
+
23
+ class Network:
24
+ """Unified network class for all equation types (ODE/DDE/SDE/SDDE).
25
+
26
+ Network behavior is determined by composition:
27
+ - Coupling type: InstantaneousCoupling (ODE/SDE) vs DelayedCoupling (DDE/SDDE)
28
+ - Noise presence: None (deterministic) vs AbstractNoise (stochastic)
29
+
30
+ Supports multiple named coupling inputs and external inputs that are automatically
31
+ mapped to dynamics model's COUPLING_INPUTS and EXTERNAL_INPUTS specifications.
32
+
33
+ Args:
34
+ dynamics: Dynamics model (must be AbstractDynamics)
35
+ coupling: Single coupling, dict {name: coupling}, or list [coupling1, ...]
36
+ graph: Network connectivity (AbstractGraph or DelayGraph)
37
+ noise: Optional noise model for stochastic systems
38
+ history: Optional history for warm-starting simulations
39
+ external_input: Optional external inputs (single, dict, or list)
40
+
41
+ Example:
42
+ # Single coupling (ODE)
43
+ network = Network(Lorenz(), LinearCoupling(...), graph)
44
+
45
+ # Multiple couplings (dict)
46
+ network = Network(
47
+ FlexibleLorenz(),
48
+ {'structural': LinearCoupling(...), 'modulatory': SigmoidCoupling(...)},
49
+ graph
50
+ )
51
+
52
+ # Multiple couplings (list - auto-mapped to COUPLING_INPUTS order)
53
+ network = Network(
54
+ FlexibleLorenz(),
55
+ [LinearCoupling(...), SigmoidCoupling(...)],
56
+ graph
57
+ )
58
+
59
+ # With noise (SDE)
60
+ network = Network(Lorenz(), LinearCoupling(...), graph, noise=AdditiveNoise(...))
61
+
62
+ # With delays (DDE)
63
+ network = Network(Lorenz(), DelayedLinearCoupling(...), delay_graph)
64
+
65
+ # With external input
66
+ network = Network(
67
+ WongWang(),
68
+ LinearCoupling(...),
69
+ graph,
70
+ external_input={'I_ext': DataInput(...)}
71
+ )
72
+ """
73
+
74
+ def __init__(
75
+ self,
76
+ dynamics: AbstractDynamics,
77
+ coupling: Union[
78
+ AbstractCoupling, Dict[str, AbstractCoupling], List[AbstractCoupling]
79
+ ],
80
+ graph: AbstractGraph,
81
+ noise: Optional[AbstractNoise] = None,
82
+ history: Optional[NativeSolution] = None,
83
+ external_input: Optional[
84
+ Union[
85
+ "AbstractExternalInput",
86
+ Dict[str, "AbstractExternalInput"],
87
+ List["AbstractExternalInput"],
88
+ ]
89
+ ] = None,
90
+ ):
91
+ """Initialize unified network with validation."""
92
+ self.dynamics = dynamics
93
+ self.graph = graph
94
+ self.noise = noise
95
+
96
+ # Normalize coupling input to dict format with validation
97
+ self.couplings = self._normalize_couplings(coupling, dynamics)
98
+
99
+ # Normalize external input to dict format with validation
100
+
101
+ self.externals = self._normalize_external_inputs(external_input or {}, dynamics)
102
+
103
+ # Extract max_delay from graph (0.0 for non-DelayGraph)
104
+ self.max_delay = getattr(graph, "max_delay", 0.0)
105
+
106
+ # Resolve noise state indices if noise provided
107
+ if self.noise is not None:
108
+ self.noise._state_indices = self.noise._resolve_state_indices(dynamics)
109
+
110
+ # Initialize history (validates if provided)
111
+ self._history = None
112
+ if history is not None:
113
+ self.update_history(history)
114
+
115
+ def _normalize_couplings(
116
+ self,
117
+ coupling_input: Union[
118
+ AbstractCoupling, Dict[str, AbstractCoupling], List[AbstractCoupling]
119
+ ],
120
+ dynamics: AbstractDynamics,
121
+ ) -> Dict[str, AbstractCoupling]:
122
+ """Convert coupling input to dict format with validation.
123
+
124
+ Args:
125
+ coupling_input: Single coupling, dict, or list
126
+ dynamics: Dynamics model for COUPLING_INPUTS validation
127
+
128
+ Returns:
129
+ Dict mapping coupling names to coupling objects
130
+
131
+ Raises:
132
+ ValueError: If coupling specification doesn't match dynamics COUPLING_INPUTS
133
+ """
134
+ # Case 1: Dict - validate names match COUPLING_INPUTS
135
+ if isinstance(coupling_input, dict):
136
+ # Check for unknown coupling names
137
+ unknown = set(coupling_input.keys()) - set(dynamics.COUPLING_INPUTS.keys())
138
+ if unknown:
139
+ raise ValueError(
140
+ f"Unknown coupling names: {unknown}. "
141
+ f"Dynamics {dynamics.__class__.__name__} expects: "
142
+ f"{list(dynamics.COUPLING_INPUTS.keys())}"
143
+ )
144
+ return coupling_input
145
+
146
+ # Case 2: List - map to COUPLING_INPUTS order
147
+ elif isinstance(coupling_input, list):
148
+ if len(coupling_input) != len(dynamics.COUPLING_INPUTS):
149
+ raise ValueError(
150
+ f"Got {len(coupling_input)} couplings but dynamics "
151
+ f"{dynamics.__class__.__name__} expects {len(dynamics.COUPLING_INPUTS)}: "
152
+ f"{list(dynamics.COUPLING_INPUTS.keys())}"
153
+ )
154
+ return {
155
+ name: coup
156
+ for name, coup in zip(dynamics.COUPLING_INPUTS.keys(), coupling_input)
157
+ }
158
+
159
+ # Case 3: Single coupling
160
+ else:
161
+ if len(dynamics.COUPLING_INPUTS) == 0:
162
+ raise ValueError(
163
+ f"Dynamics {dynamics.__class__.__name__} has no COUPLING_INPUTS. "
164
+ f"Cannot add coupling."
165
+ )
166
+ elif len(dynamics.COUPLING_INPUTS) == 1:
167
+ # Use the only coupling name
168
+ name = list(dynamics.COUPLING_INPUTS.keys())[0]
169
+ return {name: coupling_input}
170
+ else:
171
+ # Multiple coupling inputs - need clarification
172
+ raise ValueError(
173
+ f"Dynamics {dynamics.__class__.__name__} expects multiple coupling inputs: "
174
+ f"{list(dynamics.COUPLING_INPUTS.keys())}. "
175
+ f"Please provide dict {{name: coupling}} or list [coupling1, coupling2, ...]"
176
+ )
177
+
178
+ def _normalize_external_inputs(
179
+ self,
180
+ external_input: Union[
181
+ "AbstractExternalInput",
182
+ Dict[str, "AbstractExternalInput"],
183
+ List["AbstractExternalInput"],
184
+ ],
185
+ dynamics: AbstractDynamics,
186
+ ) -> Dict[str, "AbstractExternalInput"]:
187
+ """Convert external input to dict format with validation.
188
+
189
+ Args:
190
+ external_input: Single input, dict, or list
191
+ dynamics: Dynamics model for EXTERNAL_INPUTS validation
192
+
193
+ Returns:
194
+ Dict mapping input names to input objects
195
+
196
+ Raises:
197
+ ValueError: If input specification doesn't match dynamics EXTERNAL_INPUTS
198
+ """
199
+
200
+ # Case 1: Dict - validate names match EXTERNAL_INPUTS
201
+ if isinstance(external_input, dict):
202
+ # Check for unknown input names
203
+ unknown = set(external_input.keys()) - set(dynamics.EXTERNAL_INPUTS.keys())
204
+ if unknown:
205
+ raise ValueError(
206
+ f"Unknown external input names: {unknown}. "
207
+ f"Dynamics {dynamics.__class__.__name__} expects: "
208
+ f"{list(dynamics.EXTERNAL_INPUTS.keys())}"
209
+ )
210
+ return external_input
211
+
212
+ # Case 2: List - map to EXTERNAL_INPUTS order
213
+ elif isinstance(external_input, list):
214
+ if len(external_input) != len(dynamics.EXTERNAL_INPUTS):
215
+ raise ValueError(
216
+ f"Got {len(external_input)} external inputs but dynamics "
217
+ f"{dynamics.__class__.__name__} expects {len(dynamics.EXTERNAL_INPUTS)}: "
218
+ f"{list(dynamics.EXTERNAL_INPUTS.keys())}"
219
+ )
220
+ return {
221
+ name: inp
222
+ for name, inp in zip(dynamics.EXTERNAL_INPUTS.keys(), external_input)
223
+ }
224
+
225
+ # Case 3: Single external input
226
+ else:
227
+ if len(dynamics.EXTERNAL_INPUTS) == 0:
228
+ raise ValueError(
229
+ f"Dynamics {dynamics.__class__.__name__} has no EXTERNAL_INPUTS. "
230
+ f"Cannot add external input."
231
+ )
232
+ elif len(dynamics.EXTERNAL_INPUTS) == 1:
233
+ # Use the only input name
234
+ name = list(dynamics.EXTERNAL_INPUTS.keys())[0]
235
+ return {name: external_input}
236
+ else:
237
+ # Multiple external inputs - need clarification
238
+ raise ValueError(
239
+ f"Dynamics {dynamics.__class__.__name__} expects multiple external inputs: "
240
+ f"{list(dynamics.EXTERNAL_INPUTS.keys())}. "
241
+ f"Please provide dict {{name: input}} or list [input1, input2, ...]"
242
+ )
243
+
244
+ def update_history(self, solution: Optional[NativeSolution]) -> None:
245
+ """Update internal history from a simulation result.
246
+
247
+ Validates that the solution matches network configuration:
248
+ - n_states must match dynamics.STATE_VARIABLES
249
+ - n_nodes must match graph.n_nodes
250
+ - Warns if time coverage < max_delay (will be padded in get_history)
251
+
252
+ Args:
253
+ solution: NativeSolution from a previous simulation, or None to clear history
254
+
255
+ Raises:
256
+ ValueError: If solution shape doesn't match network configuration
257
+ """
258
+ if solution is None:
259
+ self._history = None
260
+ return
261
+
262
+ # Validate shape
263
+ if solution.ys.ndim != 3:
264
+ raise ValueError(
265
+ f"History must be 3D [n_time, n_states, n_nodes], "
266
+ f"got shape {solution.ys.shape}"
267
+ )
268
+
269
+ n_states = len(self.dynamics.STATE_NAMES)
270
+ n_nodes = self.graph.n_nodes
271
+ _, hist_states, hist_nodes = solution.ys.shape
272
+
273
+ # Error on state/node mismatch
274
+ if hist_states != n_states:
275
+ raise ValueError(
276
+ f"History has {hist_states} states but network expects {n_states} "
277
+ f"(STATE_NAMES: {self.dynamics.STATE_NAMES})"
278
+ )
279
+
280
+ if hist_nodes != n_nodes:
281
+ raise ValueError(
282
+ f"History has {hist_nodes} nodes but network has {n_nodes} nodes"
283
+ )
284
+
285
+ # Warn if insufficient time coverage
286
+ if self.max_delay > 0.0:
287
+ time_coverage = solution.ts[-1] - solution.ts[0]
288
+ if time_coverage < self.max_delay:
289
+ warnings.warn(
290
+ f"History covers {time_coverage:.3f}s but network needs "
291
+ f"{self.max_delay:.3f}s for delays. History will be padded.",
292
+ UserWarning,
293
+ )
294
+
295
+ self._history = solution
296
+
297
+ def prepare(self, dt: float) -> tuple[Bunch, Bunch]:
298
+ """Prepare all couplings for simulation.
299
+
300
+ Calls prepare() on each coupling to get coupling_data and coupling_state.
301
+
302
+ Args:
303
+ dt: Integration timestep
304
+
305
+ Returns:
306
+ coupling_data_dict: Bunch {name: coupling_data_bunch}
307
+ Precomputed data for each coupling (stored outside scan carry)
308
+ coupling_state_dict: Bunch {name: coupling_state_bunch}
309
+ Internal state for each coupling (stored in scan carry)
310
+ """
311
+ coupling_data_dict = Bunch()
312
+ coupling_state_dict = Bunch()
313
+
314
+ for name, coupling in self.couplings.items():
315
+ data, state = coupling.prepare(self, dt)
316
+ coupling_data_dict[name] = data
317
+ coupling_state_dict[name] = state
318
+
319
+ return coupling_data_dict, coupling_state_dict
320
+
321
+ def prepare_external(self, dt: float) -> tuple[Bunch, Bunch]:
322
+ """Prepare all external inputs for simulation.
323
+
324
+ Calls prepare() on each external input to get external_data and external_state.
325
+
326
+ Args:
327
+ dt: Integration timestep
328
+
329
+ Returns:
330
+ external_data_dict: Bunch {name: external_data_bunch}
331
+ Precomputed data for each external input (stored outside scan carry)
332
+ external_state_dict: Bunch {name: external_state_bunch}
333
+ Internal state for each external input (stored in scan carry)
334
+ """
335
+ external_data_dict = Bunch()
336
+ external_state_dict = Bunch()
337
+
338
+ for name, external in self.externals.items():
339
+ data, state = external.prepare(self, dt)
340
+ external_data_dict[name] = data
341
+ external_state_dict[name] = state
342
+
343
+ return external_data_dict, external_state_dict
344
+
345
+ def compute_coupling_inputs(
346
+ self,
347
+ t: float,
348
+ state: jnp.ndarray,
349
+ coupling_data_dict: Bunch,
350
+ coupling_state_dict: Bunch,
351
+ ) -> Bunch:
352
+ """Compute all coupling inputs and return as Bunch.
353
+
354
+ Args:
355
+ t: Current time
356
+ state: Current network state [n_states, n_nodes]
357
+ coupling_data_dict: Precomputed coupling data from prepare()
358
+ coupling_state_dict: Current coupling internal states
359
+
360
+ Returns:
361
+ coupling_inputs: Bunch {name: array[n_dims, n_nodes]}
362
+ Named coupling inputs ready for dynamics.dynamics()
363
+ Missing couplings automatically filled with zeros
364
+ """
365
+ coupling_inputs = Bunch()
366
+
367
+ for name, n_dims in self.dynamics.COUPLING_INPUTS.items():
368
+ if name not in self.couplings:
369
+ # Missing coupling - use zeros
370
+ coupling_inputs[name] = jnp.zeros((n_dims, self.graph.n_nodes))
371
+ else:
372
+ # Compute coupling
373
+ coupling = self.couplings[name]
374
+ data = coupling_data_dict[name]
375
+ state_data = coupling_state_dict[name]
376
+ coupling_inputs[name] = coupling.compute(
377
+ t, state, data, state_data, coupling.params, self.graph
378
+ )
379
+
380
+ return coupling_inputs
381
+
382
+ def compute_external_inputs(
383
+ self,
384
+ t: float,
385
+ state: jnp.ndarray,
386
+ external_data_dict: Bunch,
387
+ external_state_dict: Bunch,
388
+ ) -> Bunch:
389
+ """Compute all external inputs and return as Bunch.
390
+
391
+ Args:
392
+ t: Current time
393
+ state: Current network state [n_states, n_nodes]
394
+ external_data_dict: Precomputed external data from prepare_external()
395
+ external_state_dict: Current external internal states
396
+
397
+ Returns:
398
+ external_inputs: Bunch {name: array[n_dims, n_nodes]}
399
+ Named external inputs ready for dynamics.dynamics()
400
+ Missing inputs automatically filled with zeros
401
+ """
402
+ external_inputs = Bunch()
403
+
404
+ for name, n_dims in self.dynamics.EXTERNAL_INPUTS.items():
405
+ if name not in self.externals:
406
+ # Missing external input - use zeros
407
+ external_inputs[name] = jnp.zeros((n_dims, self.graph.n_nodes))
408
+ else:
409
+ # Compute external input
410
+ external = self.externals[name]
411
+ data = external_data_dict[name]
412
+ state_data = external_state_dict[name]
413
+ external_inputs[name] = external.compute(
414
+ t, state, data, state_data, external.params
415
+ )
416
+
417
+ return external_inputs
418
+
419
+ def update_coupling_states(
420
+ self,
421
+ coupling_data_dict: Bunch,
422
+ coupling_state_dict: Bunch,
423
+ new_state: jnp.ndarray,
424
+ ) -> Bunch:
425
+ """Update all coupling internal states after integration step.
426
+
427
+ Args:
428
+ coupling_data_dict: Precomputed coupling data from prepare()
429
+ coupling_state_dict: Current coupling internal states
430
+ new_state: New network state after integration [n_states, n_nodes]
431
+
432
+ Returns:
433
+ new_coupling_state_dict: Bunch {name: updated_coupling_state_bunch}
434
+ """
435
+ new_states = Bunch()
436
+
437
+ for name, coupling in self.couplings.items():
438
+ new_states[name] = coupling.update_state(
439
+ coupling_data_dict[name],
440
+ coupling_state_dict[name],
441
+ new_state,
442
+ )
443
+
444
+ return new_states
445
+
446
+ def update_external_states(
447
+ self,
448
+ external_data_dict: Bunch,
449
+ external_state_dict: Bunch,
450
+ new_state: jnp.ndarray,
451
+ ) -> Bunch:
452
+ """Update all external input internal states after integration step.
453
+
454
+ Args:
455
+ external_data_dict: Precomputed external data from prepare_external()
456
+ external_state_dict: Current external internal states
457
+ new_state: New network state after integration [n_states, n_nodes]
458
+
459
+ Returns:
460
+ new_external_state_dict: Bunch {name: updated_external_state_bunch}
461
+ """
462
+ new_states = Bunch()
463
+
464
+ for name, external in self.externals.items():
465
+ new_states[name] = external.update_state(
466
+ external_data_dict[name],
467
+ external_state_dict[name],
468
+ new_state,
469
+ )
470
+
471
+ return new_states
472
+
473
+ @property
474
+ def params(self) -> Bunch:
475
+ """Aggregate parameters from all network components.
476
+
477
+ Returns:
478
+ Bunch with flattened structure:
479
+ dynamics: Dynamics parameters
480
+ coupling.{name}: Parameters for each coupling
481
+ noise: Noise parameters (if noise present)
482
+ """
483
+ p = Bunch()
484
+ p.dynamics = self.dynamics.params
485
+
486
+ # Couplings as nested dict
487
+ p.coupling = Bunch()
488
+ for name, coupling in self.couplings.items():
489
+ p.coupling[name] = coupling.params
490
+
491
+ # External inputs as nested dict
492
+ p.external = Bunch()
493
+ for name, external in self.externals.items():
494
+ p.external[name] = external.params
495
+
496
+ # Noise (optional)
497
+ if self.noise is not None:
498
+ p.noise = self.noise.params
499
+
500
+ return p
501
+
502
+ @property
503
+ def initial_state(self) -> jnp.ndarray:
504
+ """Initial state for all nodes.
505
+
506
+ If history is set, returns the last state from the history.
507
+ Otherwise, returns the dynamics' INITIAL_STATE broadcasted to all nodes.
508
+
509
+ Returns:
510
+ Initial state array [n_states, n_nodes]
511
+ """
512
+ if self._history is not None:
513
+ # Use the last state from history
514
+ return self._history.ys[-1] # [n_states, n_nodes]
515
+ else:
516
+ # Use default initial state from dynamics
517
+ ic = jnp.array(self.dynamics.INITIAL_STATE)
518
+ return jnp.broadcast_to(ic[:, None], (ic.shape[0], self.graph.n_nodes))
519
+
520
+ def _get_initial_history(self, dt: float) -> Optional[jnp.ndarray]:
521
+ """Get history buffer based on initial state for delayed coupling networks.
522
+
523
+ Args:
524
+ dt: Integration timestep
525
+
526
+ Returns:
527
+ None if no delays (max_delay == 0.0)
528
+ Otherwise history buffer [n_steps, n_states, n_nodes]
529
+ where n_steps = ceil(max_delay / dt)
530
+ """
531
+ if self.max_delay == 0.0:
532
+ return None
533
+
534
+ n_steps = int(jnp.ceil(self.max_delay / dt))
535
+ return jnp.broadcast_to(
536
+ self.initial_state[None, :, :],
537
+ (n_steps, self.initial_state.shape[0], self.initial_state.shape[1]),
538
+ )
539
+
540
+ def _extract_history_window(self, dt: float) -> jnp.ndarray:
541
+ """Extract history window from stored solution.
542
+
543
+ Extracts the last max_delay seconds from self._history:
544
+ - Interpolates if dt doesn't match the history's dt
545
+ - Pads with first timestep if history is too short
546
+
547
+ Args:
548
+ dt: Integration timestep for the new simulation
549
+
550
+ Returns:
551
+ History buffer [n_steps, n_states, n_nodes]
552
+ where n_steps = ceil(max_delay / dt)
553
+ """
554
+ # Calculate required number of steps
555
+ n_steps_needed = int(jnp.ceil(self.max_delay / dt))
556
+
557
+ # Get history data
558
+ hist_ts = self._history.ts
559
+ hist_ys = self._history.ys # [n_time, n_states, n_nodes]
560
+
561
+ # Calculate history dt (assume uniform spacing)
562
+ hist_dt = hist_ts[1] - hist_ts[0] if len(hist_ts) > 1 else dt
563
+
564
+ # Check if we need interpolation (allow small numerical tolerance)
565
+ needs_interpolation = jnp.abs(hist_dt - dt) > 1e-9
566
+
567
+ # Calculate time coverage and check if we need padding
568
+ time_coverage = hist_ts[-1] - hist_ts[0]
569
+ needs_padding = time_coverage < self.max_delay
570
+
571
+ if needs_padding:
572
+ # Pad at the beginning with the first timestep
573
+ n_steps_available = len(hist_ts)
574
+ n_steps_to_pad = n_steps_needed - n_steps_available
575
+
576
+ if n_steps_to_pad > 0:
577
+ # Repeat first timestep
578
+ first_state = hist_ys[0:1, :, :] # [1, n_states, n_nodes]
579
+ padding = jnp.tile(first_state, (n_steps_to_pad, 1, 1))
580
+
581
+ if needs_interpolation:
582
+ # Interpolate available data, then pad
583
+ interpolated = self._interpolate_history(
584
+ hist_ts, hist_ys, n_steps_needed - n_steps_to_pad
585
+ )
586
+ return jnp.concatenate([padding, interpolated], axis=0)
587
+ else:
588
+ # Just pad and concatenate
589
+ return jnp.concatenate([padding, hist_ys], axis=0)
590
+ else:
591
+ # We have enough data but warned in update_history
592
+ # Extract what we need
593
+ if needs_interpolation:
594
+ return self._interpolate_history(hist_ts, hist_ys, n_steps_needed)
595
+ else:
596
+ return hist_ys[-n_steps_needed:]
597
+ else:
598
+ # Sufficient time coverage - extract last max_delay seconds
599
+ if needs_interpolation:
600
+ # Find the time window we need
601
+ t_start = hist_ts[-1] - self.max_delay
602
+ start_idx = jnp.searchsorted(hist_ts, t_start)
603
+
604
+ # Extract and interpolate
605
+ window_ts = hist_ts[start_idx:]
606
+ window_ys = hist_ys[start_idx:]
607
+
608
+ return self._interpolate_history(window_ts, window_ys, n_steps_needed)
609
+ else:
610
+ # No interpolation needed, just extract
611
+ return hist_ys[-n_steps_needed:]
612
+
613
+ def _interpolate_history(
614
+ self, old_ts: jnp.ndarray, old_ys: jnp.ndarray, n_steps: int
615
+ ) -> jnp.ndarray:
616
+ """Interpolate history to match target dt.
617
+
618
+ Args:
619
+ old_ts: Original time points [n_time_old]
620
+ old_ys: Original trajectory [n_time_old, n_states, n_nodes]
621
+ n_steps: Number of steps needed in output
622
+
623
+ Returns:
624
+ Interpolated history [n_steps, n_states, n_nodes]
625
+ """
626
+ # Create new time grid
627
+ new_ts = jnp.linspace(old_ts[0], old_ts[-1], n_steps)
628
+
629
+ # Reshape for vectorized interpolation: [n_time, n_states * n_nodes]
630
+ n_time_old, n_states, n_nodes = old_ys.shape
631
+ old_ys_flat = old_ys.reshape(n_time_old, -1) # [n_time_old, n_states*n_nodes]
632
+
633
+ # Interpolate each (state, node) combination
634
+ # jnp.interp works on 1D, so we vmap over the second dimension
635
+ def interp_1d(y_values):
636
+ return jnp.interp(new_ts, old_ts, y_values)
637
+
638
+ # Vectorize over all state-node combinations
639
+ from jax import vmap
640
+
641
+ new_ys_flat = vmap(interp_1d, in_axes=1, out_axes=1)(old_ys_flat)
642
+
643
+ # Reshape back to [n_steps, n_states, n_nodes]
644
+ return new_ys_flat.reshape(n_steps, n_states, n_nodes)
645
+
646
+ def get_history(self, dt: float) -> Optional[jnp.ndarray]:
647
+ """Get history buffer for delayed coupling networks.
648
+
649
+ If no custom history is set, returns initial state-based history.
650
+ If custom history is set, extracts appropriate window from stored solution.
651
+
652
+ Args:
653
+ dt: Integration timestep
654
+
655
+ Returns:
656
+ None if no delays (max_delay == 0.0)
657
+ Otherwise history buffer [n_steps, n_states, n_nodes]
658
+ where n_steps = ceil(max_delay / dt)
659
+ """
660
+ if self.max_delay == 0.0:
661
+ return None
662
+
663
+ if self._history is None:
664
+ return self._get_initial_history(dt)
665
+ else:
666
+ return self._extract_history_window(dt)
667
+
668
+ def __repr__(self) -> str:
669
+ """Human-readable representation of network configuration."""
670
+ parts = [
671
+ "Network(",
672
+ f" dynamics={self.dynamics.__class__.__name__}",
673
+ f" nodes={self.graph.n_nodes}",
674
+ f" couplings={list(self.couplings.keys())}",
675
+ ]
676
+
677
+ if self.externals:
678
+ parts.append(f" externals={list(self.externals.keys())}")
679
+
680
+ if self.max_delay > 0:
681
+ parts.append(f" max_delay={self.max_delay:.3f}")
682
+
683
+ if self.noise is not None:
684
+ parts.append(f" noise={self.noise.__class__.__name__}")
685
+
686
+ return "\n".join(parts) + "\n)"
@@ -0,0 +1,22 @@
1
+ """Coupling functions for network interactions."""
2
+
3
+ from .base import AbstractCoupling
4
+ from .linear import (
5
+ DelayedDifferenceCoupling,
6
+ DelayedLinearCoupling,
7
+ DifferenceCoupling,
8
+ FastLinearCoupling,
9
+ LinearCoupling,
10
+ )
11
+ from .tvb import DelayedSigmoidalJansenRit, SigmoidalJansenRit
12
+
13
+ __all__ = [
14
+ "AbstractCoupling",
15
+ "LinearCoupling",
16
+ "DifferenceCoupling",
17
+ "SigmoidalJansenRit",
18
+ "DelayedSigmoidalJansenRit",
19
+ "DelayedLinearCoupling",
20
+ "DelayedDifferenceCoupling",
21
+ "FastLinearCoupling",
22
+ ]