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,721 @@
1
+ """Solving system for network architecture.
2
+
3
+ This module provides the prepare-solve pattern for Network with multi-coupling
4
+ support. The prepare() function sets up the integration with all coupling state
5
+ management, and returns a pure function for execution.
6
+ """
7
+
8
+ from typing import Callable, Tuple
9
+
10
+ import diffrax
11
+ import jax
12
+ import jax.numpy as jnp
13
+ from plum import dispatch
14
+
15
+ from .core.bunch import Bunch
16
+ from .core.network import Network
17
+ from .result import wrap_native_result
18
+ from .solvers.diffrax import DiffraxSolver
19
+ from .solvers.native import NativeSolver
20
+
21
+
22
+ def solve(
23
+ network: Network,
24
+ solver: NativeSolver,
25
+ t0: float = 0.0,
26
+ t1: float = 100.0,
27
+ dt: float = 0.1,
28
+ ):
29
+ """Main entry point for network simulation.
30
+
31
+ Args:
32
+ network: Network instance with multi-coupling support
33
+ solver: NativeSolver instance (Euler, Heun, etc.)
34
+ t0: Start time
35
+ t1: End time
36
+ dt: Time step
37
+
38
+ Returns:
39
+ Simulation results wrapped in result object
40
+
41
+ Example:
42
+ >>> from network_dynamics import Network, solve
43
+ >>> from network_dynamics.solvers import Euler
44
+ >>> from network_dynamics.dynamics import Lorenz
45
+ >>> from network_dynamics.coupling import LinearCoupling
46
+ >>> from network_dynamics.graph import Graph
47
+ >>>
48
+ >>> dynamics = Lorenz()
49
+ >>> coupling = LinearCoupling(incoming_states='x', G=1.0)
50
+ >>> graph = Graph(weights)
51
+ >>> network = Network(dynamics, coupling, graph)
52
+ >>>
53
+ >>> result = solve(network, Euler(), t0=0, t1=10, dt=0.01)
54
+ """
55
+ solve_fn, params = prepare(network, solver, t0=t0, t1=t1, dt=dt)
56
+ return solve_fn(params)
57
+
58
+
59
+ @dispatch
60
+ def prepare(
61
+ network: Network,
62
+ solver: NativeSolver,
63
+ t0: float = 0.0,
64
+ t1: float = 1.0,
65
+ dt: float = 0.1,
66
+ ) -> Tuple[Callable, Bunch]:
67
+ """Prepare network for native solver integration.
68
+
69
+ This function:
70
+ 1. Prepares all couplings (creates history buffers if needed)
71
+ 2. Builds config structure with params, graph, initial_state, _internal
72
+ 3. Pre-generates noise samples if stochastic
73
+ 4. Pre-compiles coupling computation and state update closures
74
+ 5. Returns pure function for integration
75
+
76
+ Args:
77
+ network: Network with multi-coupling
78
+ solver: NativeSolver (Euler, Heun, etc.)
79
+ t0: Start time
80
+ t1: End time
81
+ dt: Time step
82
+
83
+ Returns:
84
+ Tuple of (solve_function, config)
85
+ - solve_function: Pure function that takes config and returns results
86
+ - config: Bunch with flattened params, graph, initial_state, _internal
87
+ """
88
+ # Prepare all couplings (creates history buffers, computes indices, etc.)
89
+ coupling_data_dict, coupling_state_dict_init = network.prepare(dt)
90
+
91
+ # Prepare all external inputs
92
+ external_data_dict, external_state_dict_init = network.prepare_external(dt)
93
+
94
+ # Time array
95
+ time_steps = jnp.arange(t0, t1, dt)
96
+
97
+ # Build new config structure
98
+ config = Bunch(
99
+ # Parameters (flattened - no params. prefix)
100
+ dynamics=network.dynamics.params,
101
+ coupling=Bunch(),
102
+ external=Bunch(),
103
+ # Graph (PyTree object)
104
+ graph=network.graph,
105
+ # Initial state
106
+ initial_state=Bunch(
107
+ dynamics=network.initial_state,
108
+ coupling=coupling_state_dict_init,
109
+ external=external_state_dict_init,
110
+ ),
111
+ # Internal (static precomputed data)
112
+ _internal=Bunch(
113
+ coupling=coupling_data_dict,
114
+ external=external_data_dict,
115
+ time=Bunch(t0=t0, t1=t1, dt=dt),
116
+ ),
117
+ )
118
+
119
+ # Add coupling params
120
+ for name, coupling in network.couplings.items():
121
+ config.coupling[name] = coupling.params
122
+
123
+ # Add external input params
124
+ for name, external in network.externals.items():
125
+ config.external[name] = external.params
126
+
127
+ # Add noise params and samples if stochastic
128
+ if network.noise is not None:
129
+ config.noise = network.noise.params
130
+ n_steps = len(time_steps)
131
+ n_nodes = network.graph.n_nodes
132
+ n_noise_states = len(network.noise._state_indices)
133
+ noise_shape = (n_steps, n_noise_states, n_nodes)
134
+ config._internal.noise_samples = network.noise.generate_noise_samples(
135
+ noise_shape
136
+ )
137
+
138
+ # =========================================================================
139
+ # PRE-COMPILE COUPLING COMPUTATION CLOSURE
140
+ # =========================================================================
141
+ # Build a list of (name, coupling, data) tuples to avoid dict iteration in scan
142
+ coupling_list = []
143
+ coupling_names_ordered = []
144
+ for name in network.dynamics.COUPLING_INPUTS.keys():
145
+ coupling_names_ordered.append(name)
146
+ if name in network.couplings:
147
+ coupling = network.couplings[name]
148
+ data = coupling_data_dict[name]
149
+ coupling_list.append((name, coupling, data))
150
+ else:
151
+ coupling_list.append((name, None, None))
152
+
153
+ n_nodes = network.graph.n_nodes
154
+ graph = network.graph # Capture graph for closure
155
+
156
+ def compute_all_couplings(t, network_state, coupling_state_dict, config):
157
+ """Pre-compiled closure for coupling computation.
158
+
159
+ Avoids method calls and dict iterations in scan loop.
160
+
161
+ Args:
162
+ config: Config containing coupling parameters to use
163
+ """
164
+ coupling_inputs = Bunch()
165
+
166
+ for name, coupling, data in coupling_list:
167
+ if coupling is None:
168
+ # Missing coupling - use zeros
169
+ n_dims = network.dynamics.COUPLING_INPUTS[name]
170
+ coupling_inputs[name] = jnp.zeros((n_dims, n_nodes))
171
+ else:
172
+ # Compute coupling using pre-fetched data and graph
173
+ state_data = coupling_state_dict[name]
174
+ coupling_inputs[name] = coupling.compute(
175
+ t, network_state, data, state_data, config.coupling[name], graph
176
+ )
177
+
178
+ return coupling_inputs
179
+
180
+ # =========================================================================
181
+ # PRE-COMPILE COUPLING STATE UPDATE CLOSURE
182
+ # =========================================================================
183
+ # Build list of couplings that need state updates (avoid dict iteration)
184
+ update_list = [
185
+ (name, network.couplings[name], coupling_data_dict[name])
186
+ for name in network.couplings.keys()
187
+ ]
188
+
189
+ def update_all_coupling_states(coupling_state_dict, new_network_state):
190
+ """Pre-compiled closure for coupling state updates.
191
+
192
+ Avoids method calls and dict iterations in scan loop.
193
+ """
194
+ new_states = Bunch()
195
+
196
+ for name, coupling, data in update_list:
197
+ new_states[name] = coupling.update_state(
198
+ data,
199
+ coupling_state_dict[name],
200
+ new_network_state,
201
+ )
202
+
203
+ return new_states
204
+
205
+ # =========================================================================
206
+ # PRE-COMPILE EXTERNAL INPUT COMPUTATION CLOSURE
207
+ # =========================================================================
208
+ # Build a list of (name, external, data) tuples to avoid dict iteration in scan
209
+ external_list = []
210
+ for name in network.dynamics.EXTERNAL_INPUTS.keys():
211
+ if name in network.externals:
212
+ external_obj = network.externals[name]
213
+ data = external_data_dict[name]
214
+ external_list.append((name, external_obj, data))
215
+ else:
216
+ external_list.append((name, None, None))
217
+
218
+ def compute_all_externals(t, network_state, external_state_dict, config):
219
+ """Pre-compiled closure for external input computation.
220
+
221
+ Avoids method calls and dict iterations in scan loop.
222
+
223
+ Args:
224
+ config: Config containing external input parameters to use
225
+ """
226
+ external_inputs = Bunch()
227
+
228
+ for name, external_obj, data in external_list:
229
+ if external_obj is None:
230
+ # Missing external input - use zeros
231
+ n_dims = network.dynamics.EXTERNAL_INPUTS[name]
232
+ external_inputs[name] = jnp.zeros((n_dims, n_nodes))
233
+ else:
234
+ # Compute external input using pre-fetched data
235
+ state_data = external_state_dict[name]
236
+ external_inputs[name] = external_obj.compute(
237
+ t, network_state, data, state_data, config.external[name]
238
+ )
239
+
240
+ return external_inputs
241
+
242
+ # =========================================================================
243
+ # PRE-COMPILE EXTERNAL STATE UPDATE CLOSURE
244
+ # =========================================================================
245
+ # Build list of external inputs that need state updates (avoid dict iteration)
246
+ external_update_list = [
247
+ (name, network.externals[name], external_data_dict[name])
248
+ for name in network.externals.keys()
249
+ ]
250
+
251
+ def update_all_external_states(external_state_dict, new_network_state):
252
+ """Pre-compiled closure for external state updates.
253
+
254
+ Avoids method calls and dict iterations in scan loop.
255
+ """
256
+ new_states = Bunch()
257
+
258
+ for name, external_obj, data in external_update_list:
259
+ new_states[name] = external_obj.update_state(
260
+ data,
261
+ external_state_dict[name],
262
+ new_network_state,
263
+ )
264
+
265
+ return new_states
266
+
267
+ # =========================================================================
268
+ # PRE-COMPILE DYNAMICS + COUPLING COMPUTATION
269
+ # =========================================================================
270
+ # Store dynamics function reference to avoid attribute lookup
271
+ dynamics_fn = network.dynamics.dynamics
272
+
273
+ # Pre-allocate solver step function reference
274
+ solver_step = solver.step
275
+
276
+ # =========================================================================
277
+ # VARIABLES OF INTEREST - Determine what to record
278
+ # =========================================================================
279
+ voi_indices = network.dynamics.get_variables_of_interest_indices()
280
+ n_states = network.dynamics.N_STATES
281
+
282
+ # Split VOI indices into state and auxiliary indices
283
+ state_voi_indices = jnp.array([i for i in voi_indices if i < n_states], dtype=int)
284
+ aux_voi_indices = jnp.array(
285
+ [i - n_states for i in voi_indices if i >= n_states], dtype=int
286
+ )
287
+
288
+ # Flag: do we need to record any auxiliaries?
289
+ record_auxiliaries = len(aux_voi_indices) > 0
290
+
291
+ def _f(config):
292
+ """Pure integration function."""
293
+ state0 = config.initial_state
294
+
295
+ def op(state, inputs):
296
+ """Single integration step.
297
+
298
+ Args:
299
+ state: Bunch(dynamics=network_state, coupling=coupling_state_dict, external=external_state_dict)
300
+ inputs: (t, step_idx) for SDE or just t for ODE
301
+
302
+ Returns:
303
+ (next_state, output) tuple for scan
304
+ """
305
+ # Unpack inputs
306
+ if network.noise is not None:
307
+ t = inputs[0]
308
+ step_idx = jnp.int32(inputs[1])
309
+ else:
310
+ t = inputs
311
+ step_idx = None
312
+
313
+ # Inline dynamics wrapper to avoid extra function creation
314
+ # Note: This is still inside op, but it's the minimal unavoidable closure
315
+ def wrapped_dynamics(t_inner, network_state, params_dynamics):
316
+ # Compute all coupling inputs using pre-compiled closure
317
+ coupling_inputs = compute_all_couplings(
318
+ t_inner, network_state, state.coupling, config
319
+ )
320
+ # Compute all external inputs using pre-compiled closure
321
+ external_inputs = compute_all_externals(
322
+ t_inner, network_state, state.external, config
323
+ )
324
+ # Call dynamics with coupling and external inputs
325
+ # Returns (derivatives, auxiliaries) or just derivatives
326
+ return dynamics_fn(
327
+ t_inner,
328
+ network_state,
329
+ params_dynamics,
330
+ coupling_inputs,
331
+ external_inputs,
332
+ )
333
+
334
+ # Prepare noise sample if stochastic
335
+ noise_sample = jnp.zeros_like(state.dynamics)
336
+ if network.noise is not None:
337
+ # Get pre-generated noise for this timestep
338
+ noise = config._internal.noise_samples[step_idx]
339
+
340
+ # Compute diffusion coefficient
341
+ diffusion = network.noise.diffusion(t, state.dynamics, config.noise)
342
+
343
+ # Scale noise: g(t,x) * sqrt(dt) * dW
344
+ # The sqrt(dt) factor is essential for SDEs - Brownian increments scale with sqrt(dt)
345
+ scaled_noise = diffusion * jnp.sqrt(dt) * noise
346
+
347
+ # Insert into correct state indices
348
+ noise_sample = noise_sample.at[network.noise._state_indices].set(
349
+ scaled_noise
350
+ )
351
+
352
+ # Solver integration step using pre-compiled function references
353
+ # Returns (next_state, auxiliaries)
354
+ next_dynamics_state, auxiliaries = solver_step(
355
+ wrapped_dynamics, t, state.dynamics, dt, config.dynamics, noise_sample
356
+ )
357
+
358
+ # Use pre-compiled closure for coupling state updates
359
+ next_coupling_state_dict = update_all_coupling_states(
360
+ state.coupling, next_dynamics_state
361
+ )
362
+
363
+ # Use pre-compiled closure for external state updates
364
+ next_external_state_dict = update_all_external_states(
365
+ state.external, next_dynamics_state
366
+ )
367
+
368
+ # Build next state Bunch
369
+ next_state = Bunch(
370
+ dynamics=next_dynamics_state,
371
+ coupling=next_coupling_state_dict,
372
+ external=next_external_state_dict,
373
+ )
374
+
375
+ # Apply VARIABLES_OF_INTEREST filtering to build output
376
+ # Collect selected state variables
377
+ if len(state_voi_indices) > 0:
378
+ selected_states = next_dynamics_state[state_voi_indices]
379
+ else:
380
+ selected_states = jnp.array([]).reshape(0, next_dynamics_state.shape[1])
381
+
382
+ # Collect selected auxiliary variables if needed
383
+ if record_auxiliaries and auxiliaries.size > 0:
384
+ selected_aux = auxiliaries[aux_voi_indices]
385
+ # Concatenate states and auxiliaries
386
+ output = jnp.concatenate([selected_states, selected_aux], axis=0)
387
+ else:
388
+ output = selected_states
389
+
390
+ # Return (carry, output)
391
+ return next_state, output
392
+
393
+ # Prepare scan inputs
394
+ if network.noise is None:
395
+ # ODE/DDE: just time
396
+ scan_inputs = time_steps
397
+ else:
398
+ # SDE/SDDE: time + step index for noise lookup
399
+ scan_inputs = jnp.stack([time_steps, jnp.arange(len(time_steps))], axis=1)
400
+
401
+ # Run integration
402
+ _, res = jax.lax.scan(op, state0, scan_inputs)
403
+
404
+ # Wrap result for consistency
405
+ return wrap_native_result(res, t0, t1, dt)
406
+
407
+ return _f, config
408
+
409
+
410
+ @dispatch
411
+ def prepare(
412
+ network: Network,
413
+ solver: DiffraxSolver,
414
+ t0: float = 0.0,
415
+ t1: float = 1.0,
416
+ dt: float = 0.1,
417
+ ) -> Tuple[Callable, Bunch]:
418
+ """Prepare network for Diffrax solver integration.
419
+
420
+ Note: Diffrax solvers only support STATELESS couplings and external inputs.
421
+ Stateful couplings (e.g., delayed coupling with history buffers) cannot be
422
+ used with Diffrax solvers because Diffrax controls the integration loop internally.
423
+
424
+ Args:
425
+ network: Network instance
426
+ solver: DiffraxSolver instance
427
+ t0: Start time
428
+ t1: End time
429
+ dt: Initial time step (used as dt0 for Diffrax)
430
+
431
+ Returns:
432
+ Tuple of (solve_function, config)
433
+ - solve_function: Pure function that takes config and returns Diffrax solution
434
+ - config: Bunch with parameters and precomputed data
435
+
436
+ Raises:
437
+ ValueError: If network contains stateful couplings or noise
438
+ """
439
+ # =========================================================================
440
+ # VALIDATION: Check for unsupported features
441
+ # =========================================================================
442
+
443
+ # Check for delayed coupling (stateful)
444
+ if network.max_delay > 0.0:
445
+ raise ValueError(
446
+ f"Diffrax solver does not support delayed coupling (max_delay={network.max_delay}). "
447
+ "Delayed couplings require stateful history buffers that cannot be maintained "
448
+ "with Diffrax's internal integration loop. Use NativeSolver instead."
449
+ )
450
+
451
+ # Note on solver compatibility with SDEs:
452
+ # We let Diffrax handle any incompatibility errors rather than checking solver types here.
453
+ # Diffrax will raise appropriate errors if a solver doesn't support SDEs.
454
+
455
+ # Warn about potential stateful couplings
456
+ # Note: We can't easily detect if update_state() is non-trivial without running it,
457
+ # but delayed coupling is the main stateful case, which we've already checked above.
458
+
459
+ # =========================================================================
460
+ # PREPARE COUPLING AND EXTERNAL INPUT DATA
461
+ # =========================================================================
462
+
463
+ # Prepare all couplings (get read-only data, ignore state since we can't maintain it)
464
+ coupling_data_dict, _ = network.prepare(dt)
465
+
466
+ # Prepare all external inputs (get read-only data, ignore state)
467
+ external_data_dict, _ = network.prepare_external(dt)
468
+
469
+ # Build config structure
470
+ config = Bunch(
471
+ # Parameters
472
+ dynamics=network.dynamics.params,
473
+ coupling=Bunch(),
474
+ external=Bunch(),
475
+ # Graph
476
+ graph=network.graph,
477
+ # Initial state [n_states, n_nodes]
478
+ initial_state=network.initial_state,
479
+ # Internal data
480
+ _internal=Bunch(
481
+ coupling=coupling_data_dict,
482
+ external=external_data_dict,
483
+ time=Bunch(t0=t0, t1=t1, dt=dt),
484
+ ),
485
+ )
486
+
487
+ # Add coupling params
488
+ for name, coupling in network.couplings.items():
489
+ config.coupling[name] = coupling.params
490
+
491
+ # Add external input params
492
+ for name, external in network.externals.items():
493
+ config.external[name] = external.params
494
+
495
+ # Add noise params if present
496
+ if network.noise is not None:
497
+ config.noise = network.noise.params
498
+
499
+ # =========================================================================
500
+ # PRE-COMPILE COUPLING COMPUTATION CLOSURE
501
+ # =========================================================================
502
+
503
+ # Build coupling list for fast iteration (avoid dict lookups in vector field)
504
+ coupling_list = []
505
+ for name in network.dynamics.COUPLING_INPUTS.keys():
506
+ if name in network.couplings:
507
+ coupling = network.couplings[name]
508
+ data = coupling_data_dict[name]
509
+ coupling_list.append((name, coupling, data))
510
+ else:
511
+ coupling_list.append((name, None, None))
512
+
513
+ n_nodes = network.graph.n_nodes
514
+ graph = network.graph
515
+
516
+ def compute_all_couplings(t, network_state, config):
517
+ """Compute all coupling inputs (stateless - no coupling state).
518
+
519
+ Args:
520
+ config: Config containing coupling parameters to use
521
+ """
522
+ coupling_inputs = Bunch()
523
+
524
+ for name, coupling, data in coupling_list:
525
+ if coupling is None:
526
+ # Missing coupling - use zeros
527
+ n_dims = network.dynamics.COUPLING_INPUTS[name]
528
+ coupling_inputs[name] = jnp.zeros((n_dims, n_nodes))
529
+ else:
530
+ # Compute coupling (stateless - pass empty state)
531
+ # For stateless couplings, coupling_state should be ignored
532
+ empty_state = Bunch()
533
+ coupling_inputs[name] = coupling.compute(
534
+ t, network_state, data, empty_state, config.coupling[name], graph
535
+ )
536
+
537
+ return coupling_inputs
538
+
539
+ # =========================================================================
540
+ # PRE-COMPILE EXTERNAL INPUT COMPUTATION CLOSURE
541
+ # =========================================================================
542
+
543
+ # Build external input list
544
+ external_list = []
545
+ for name in network.dynamics.EXTERNAL_INPUTS.keys():
546
+ if name in network.externals:
547
+ external_obj = network.externals[name]
548
+ data = external_data_dict[name]
549
+ external_list.append((name, external_obj, data))
550
+ else:
551
+ external_list.append((name, None, None))
552
+
553
+ def compute_all_externals(t, network_state, config):
554
+ """Compute all external inputs (stateless).
555
+
556
+ Args:
557
+ config: Config containing external input parameters to use
558
+ """
559
+ external_inputs = Bunch()
560
+
561
+ for name, external_obj, data in external_list:
562
+ if external_obj is None:
563
+ # Missing external input - use zeros
564
+ n_dims = network.dynamics.EXTERNAL_INPUTS[name]
565
+ external_inputs[name] = jnp.zeros((n_dims, n_nodes))
566
+ else:
567
+ # Compute external input (stateless - pass empty state)
568
+ empty_state = Bunch()
569
+ external_inputs[name] = external_obj.compute(
570
+ t, network_state, data, empty_state, config.external[name]
571
+ )
572
+
573
+ return external_inputs
574
+
575
+ # =========================================================================
576
+ # CREATE DIFFRAX ODETerm WRAPPER (Drift)
577
+ # =========================================================================
578
+
579
+ dynamics_fn = network.dynamics.dynamics
580
+ n_states = network.dynamics.N_STATES
581
+
582
+ def vector_field(t, y, args):
583
+ """Diffrax-compatible vector field: f(t, y, args) -> dy/dt.
584
+
585
+ Args:
586
+ t: Current time
587
+ y: Network state [n_states, n_nodes]
588
+ args: Not used (params are in closure)
589
+
590
+ Returns:
591
+ derivatives: [n_states, n_nodes]
592
+ """
593
+ # Compute coupling inputs
594
+ coupling_inputs = compute_all_couplings(t, y, config)
595
+
596
+ # Compute external inputs
597
+ external_inputs = compute_all_externals(t, y, config)
598
+
599
+ # Call dynamics
600
+ result = dynamics_fn(t, y, config.dynamics, coupling_inputs, external_inputs)
601
+
602
+ # Extract derivatives (discard auxiliaries if present)
603
+ if isinstance(result, tuple):
604
+ derivatives, _ = result
605
+ else:
606
+ derivatives = result
607
+
608
+ return derivatives
609
+
610
+ # =========================================================================
611
+ # CREATE DIFFRAX ControlTerm WRAPPER (Diffusion) if noise present
612
+ # =========================================================================
613
+
614
+ diffusion_term = None
615
+ if network.noise is not None:
616
+ # Get noise configuration
617
+ noise_state_indices = network.noise._state_indices
618
+ n_noise_states = len(noise_state_indices)
619
+
620
+ def diffusion_vector_field(t, y, args):
621
+ """Diffusion coefficient g(t, y) for ControlTerm.
622
+
623
+ Args:
624
+ t: Current time
625
+ y: Network state [n_states, n_nodes]
626
+ args: Not used (params are in closure)
627
+
628
+ Returns:
629
+ Diffusion matrix [n_states, n_nodes, n_brownian]
630
+ where n_brownian = n_noise_states * n_nodes
631
+ """
632
+ # Compute diffusion coefficients using noise model
633
+ g_raw = network.noise.diffusion(t, y, config.noise)
634
+
635
+ # Handle different return types from diffusion():
636
+ # - Scalar (e.g., AdditiveNoise with constant sigma)
637
+ # - Array [n_noise_states, n_nodes] (e.g., MultiplicativeNoise)
638
+
639
+ # Ensure g has shape [n_noise_states, n_nodes]
640
+ if jnp.ndim(g_raw) == 0:
641
+ # Scalar - broadcast to all noise states and nodes
642
+ g = jnp.full((n_noise_states, n_nodes), g_raw)
643
+ elif jnp.ndim(g_raw) == 1:
644
+ # 1D array - could be per-state or per-node, assume broadcasting needed
645
+ g = jnp.broadcast_to(g_raw[..., None], (n_noise_states, n_nodes))
646
+ else:
647
+ # Already [n_noise_states, n_nodes]
648
+ g = g_raw
649
+
650
+ # Build full diffusion matrix that maps Brownian motion to state space
651
+ # Shape: [n_states, n_nodes, n_brownian]
652
+ # where n_brownian = n_noise_states * n_nodes
653
+ n_brownian = n_noise_states * n_nodes
654
+
655
+ # Initialize with zeros
656
+ diffusion_matrix = jnp.zeros((n_states, n_nodes, n_brownian))
657
+
658
+ # Fill in the diagonal blocks for states that receive noise
659
+ for i, state_idx in enumerate(noise_state_indices):
660
+ for j in range(n_nodes):
661
+ # This Brownian dimension corresponds to state_idx, node j
662
+ brownian_idx = i * n_nodes + j
663
+ # Set the diffusion coefficient
664
+ diffusion_matrix = diffusion_matrix.at[
665
+ state_idx, j, brownian_idx
666
+ ].set(g[i, j])
667
+
668
+ return diffusion_matrix
669
+
670
+ # Create Brownian motion
671
+ n_brownian = n_noise_states * n_nodes
672
+ brownian_motion = diffrax.VirtualBrownianTree(
673
+ t0=t0,
674
+ t1=t1,
675
+ tol=dt * 0.01, # Brownian tree tolerance (finer than dt)
676
+ shape=(n_brownian,),
677
+ key=network.noise.key,
678
+ )
679
+
680
+ # Create diffusion term
681
+ diffusion_term = diffrax.ControlTerm(diffusion_vector_field, brownian_motion)
682
+
683
+ # =========================================================================
684
+ # CREATE SOLVE FUNCTION
685
+ # =========================================================================
686
+
687
+ def _f(config):
688
+ """Pure integration function using Diffrax."""
689
+ # Create drift term (deterministic dynamics)
690
+ drift_term = diffrax.ODETerm(vector_field)
691
+
692
+ # Combine terms
693
+ if diffusion_term is not None:
694
+ # SDE: combine drift and diffusion
695
+ terms = diffrax.MultiTerm(drift_term, diffusion_term)
696
+ else:
697
+ # ODE: just drift
698
+ terms = drift_term
699
+
700
+ # Solve using diffrax with 2D state [n_states, n_nodes]
701
+ solution = diffrax.diffeqsolve(
702
+ terms,
703
+ solver.solver,
704
+ t0=t0,
705
+ t1=t1,
706
+ dt0=dt,
707
+ y0=config.initial_state,
708
+ saveat=solver.saveat,
709
+ stepsize_controller=solver.stepsize_controller,
710
+ max_steps=solver.max_steps,
711
+ **solver.diffrax_kwargs,
712
+ )
713
+
714
+ # NOTE: Diffrax may pad solution arrays with inf when max_steps is specified.
715
+ # Users should filter finite values in post-processing if needed:
716
+ # finite_mask = jnp.isfinite(solution.ts)
717
+ # solution_filtered = solution.ts[finite_mask], solution.ys[finite_mask]
718
+
719
+ return solution
720
+
721
+ return _f, config