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,1005 @@
1
+ """New coupling system with self-contained state management.
2
+
3
+ This module implements the coupling architecture with:
4
+ - prepare(), compute(), update_state() interface
5
+ - Bunch-based coupling_data and coupling_state
6
+ - Support for multi-coupling networks
7
+ """
8
+
9
+ from abc import ABC, abstractmethod
10
+ from typing import Optional, Tuple
11
+
12
+ import jax.numpy as jnp
13
+
14
+ from ..core.bunch import Bunch
15
+ from ..graph.base import AbstractGraph
16
+
17
+ # ============================================================================
18
+ # Helper Functions
19
+ # ============================================================================
20
+
21
+
22
+ def _get_n_states(state_idx) -> int:
23
+ """Get number of states from index array or scalar."""
24
+ if hasattr(state_idx, "__len__"):
25
+ return len(state_idx)
26
+ elif state_idx is not None:
27
+ return 1
28
+ else:
29
+ return 0
30
+
31
+
32
+ def _ensure_dense(arr):
33
+ """Convert sparse array to dense if needed."""
34
+ return arr.todense() if hasattr(arr, "todense") else arr
35
+
36
+
37
+ def _prepare_bcoo_indices(
38
+ graph, incoming_idx
39
+ ) -> Tuple[Optional[jnp.ndarray], Optional[tuple], bool]:
40
+ """Prepare BCOO sparse indices for 3D tensor [n_incoming, n_nodes, n_nodes].
41
+
42
+ Args:
43
+ graph: Graph instance (checked for sparsity)
44
+ incoming_idx: Incoming state indices
45
+
46
+ Returns:
47
+ Tuple of (bcoo_indices, bcoo_shape, use_sparse_incoming):
48
+ - bcoo_indices: [n_batch*nnz, 3] indices for BCOO construction
49
+ - bcoo_shape: (n_incoming, n_nodes, n_nodes) shape tuple
50
+ - use_sparse_incoming: bool flag whether to use sparse optimization
51
+ """
52
+ from ..graph.sparse import SparseDelayGraph, SparseGraph
53
+
54
+ if not isinstance(graph, (SparseGraph, SparseDelayGraph)):
55
+ return None, None, False
56
+
57
+ n_incoming = _get_n_states(incoming_idx)
58
+
59
+ # Only use sparse incoming if we actually have incoming states
60
+ if n_incoming == 0:
61
+ return None, None, False
62
+
63
+ nnz = graph.nnz
64
+ n_nodes = graph.n_nodes
65
+
66
+ # Build 3D indices [n_batch*nnz, 3] for BCOO [n_incoming, n_nodes, n_nodes]
67
+ batch_indices = jnp.repeat(jnp.arange(n_incoming), nnz)
68
+ spatial_indices = jnp.tile(graph.weights.indices, (n_incoming, 1))
69
+ bcoo_indices = jnp.column_stack([batch_indices, spatial_indices])
70
+
71
+ bcoo_shape = (n_incoming, n_nodes, n_nodes)
72
+
73
+ return bcoo_indices, bcoo_shape, True
74
+
75
+
76
+ def _sparse_weighted_sum(pre_states, graph, is_bcoo: bool = False):
77
+ """Perform sparse weighted sum: sum over edges of (pre_states * weights).
78
+
79
+ Handles both BCOO sparse pre_states and dense pre_states with sparse graph.
80
+
81
+ Args:
82
+ pre_states: Either BCOO [n_output, n_nodes, n_nodes] or dense array
83
+ graph: Sparse graph with weights
84
+ is_bcoo: True if pre_states is BCOO, False if dense
85
+
86
+ Returns:
87
+ Dense array [n_output, n_nodes] after weighted sum
88
+ """
89
+ import jax.experimental.sparse as jsparse
90
+
91
+ indices = graph.weights.indices # [nnz, 2]
92
+ n_output = pre_states.shape[0]
93
+ nnz = graph.nnz
94
+
95
+ if is_bcoo or hasattr(pre_states, "todense"):
96
+ # BCOO path: pre_states.data is flat [n_output * nnz]
97
+ # Reshape pre data: [n_output * nnz] -> [n_output, nnz]
98
+ pre_data_batched = pre_states.data.reshape(n_output, nnz)
99
+
100
+ # Element-wise multiply: [n_output, nnz] * [nnz] -> [n_output, nnz]
101
+ weighted_data = pre_data_batched * graph.weights.data[None, :]
102
+
103
+ # Sum over edges for each output dimension
104
+ summed_list = []
105
+ for i in range(n_output):
106
+ weighted_bcoo_i = jsparse.BCOO(
107
+ (weighted_data[i], indices), shape=(graph.n_nodes, graph.n_nodes)
108
+ )
109
+ summed_i = jsparse.bcoo_reduce_sum(weighted_bcoo_i, axes=(1,))
110
+ summed_list.append(_ensure_dense(summed_i))
111
+
112
+ return jnp.stack(summed_list, axis=0)
113
+ else:
114
+ # Dense pre_states path: extract values at sparse locations
115
+ summed_list = []
116
+ for i in range(n_output):
117
+ # Extract values at sparse edges only
118
+ pre_values = pre_states[i, indices[:, 0], indices[:, 1]] # [nnz]
119
+
120
+ # Element-wise multiply: pre.data * weights.data
121
+ weighted_values = pre_values * graph.weights.data # [nnz]
122
+
123
+ # Reconstruct BCOO and sum over source nodes (axis=1)
124
+ pre_bcoo = jsparse.BCOO(
125
+ (weighted_values, indices), shape=graph.weights.shape
126
+ )
127
+ summed_i_sparse = jsparse.bcoo_reduce_sum(pre_bcoo, axes=(1,))
128
+ summed_list.append(_ensure_dense(summed_i_sparse))
129
+
130
+ return jnp.stack(summed_list, axis=0)
131
+
132
+
133
+ # ============================================================================
134
+ # Coupling Classes
135
+ # ============================================================================
136
+
137
+
138
+ class AbstractCoupling(ABC):
139
+ """Ultra-minimal interface for completely custom coupling implementations.
140
+
141
+ Use this base class only when you need full control over coupling computation
142
+ and the standard matrix multiplication patterns don't apply.
143
+
144
+ Attributes:
145
+ N_OUTPUT_STATES: Number of output states after coupling
146
+ DEFAULT_PARAMS: Default coupling parameters as a Bunch
147
+ """
148
+
149
+ N_OUTPUT_STATES: int = 0
150
+ DEFAULT_PARAMS: Bunch = Bunch()
151
+
152
+ def __init__(self, incoming_states=None, local_states=None, **kwargs):
153
+ """Initialize coupling with state names and parameter overrides.
154
+
155
+ Args:
156
+ incoming_states: State names from connected nodes (str, tuple, or list)
157
+ Optional - what states to collect from incoming connections
158
+ local_states: State names from current node (str, tuple, or list)
159
+ Optional - what states to use from local node
160
+ **kwargs: Parameter overrides for DEFAULT_PARAMS
161
+
162
+ Raises:
163
+ ValueError: If neither incoming_states nor local_states is provided,
164
+ or if unknown parameters given
165
+ """
166
+ # At least one state source must be specified
167
+ if incoming_states is None and local_states is None:
168
+ raise ValueError(
169
+ f"{self.__class__.__name__} requires at least one of 'incoming_states' "
170
+ f"or 'local_states'. A coupling must couple something!"
171
+ )
172
+
173
+ # Store state names as instance attributes
174
+ self.INCOMING_STATE_NAMES = (
175
+ incoming_states if incoming_states is not None else []
176
+ )
177
+ self.LOCAL_STATE_NAMES = local_states if local_states is not None else []
178
+
179
+ # Create instance parameters by copying defaults and updating with kwargs
180
+ self.params = self.DEFAULT_PARAMS.copy() if self.DEFAULT_PARAMS else Bunch()
181
+ for key, value in kwargs.items():
182
+ if key not in self.DEFAULT_PARAMS:
183
+ raise ValueError(
184
+ f"Unknown parameter '{key}' for {self.__class__.__name__}. "
185
+ f"Available parameters: {list(self.DEFAULT_PARAMS.keys())}"
186
+ )
187
+ self.params[key] = value
188
+
189
+ @abstractmethod
190
+ def prepare(self, network, dt: float) -> Tuple[Bunch, Bunch]:
191
+ """Prepare coupling for simulation.
192
+
193
+ Handles all setup logic that was previously in solve.py:
194
+ - State index computation
195
+ - History buffer initialization (for delays)
196
+ - Parameter validation
197
+
198
+ Args:
199
+ network: Network instance with graph, dynamics, initial_state
200
+ dt: Integration timestep
201
+
202
+ Returns:
203
+ Tuple of (coupling_data, coupling_state):
204
+
205
+ coupling_data: Bunch
206
+ Static precomputed data (stored outside scan carry):
207
+ - incoming_indices: State indices to read from
208
+ - local_indices: Local state indices
209
+ - delay_indices: Delay step indices (for delayed coupling)
210
+ - Other static precomputed data
211
+ NOTE: Does NOT contain weights/delays - access via graph parameter
212
+
213
+ coupling_state: Bunch
214
+ Mutable internal state (stored in scan carry):
215
+ - history: Circular buffer for delays (if applicable)
216
+ - [empty Bunch() for instantaneous coupling]
217
+ """
218
+ pass
219
+
220
+ @abstractmethod
221
+ def compute(
222
+ self,
223
+ t: float,
224
+ state: jnp.ndarray,
225
+ coupling_data: Bunch,
226
+ coupling_state: Bunch,
227
+ params: Bunch,
228
+ graph: AbstractGraph,
229
+ ) -> jnp.ndarray:
230
+ """Compute coupling input during simulation.
231
+
232
+ Replaces the coupling_fun built by networks. Handles all coupling
233
+ computation including delays, matrix multiplication, pre/post transforms.
234
+
235
+ Args:
236
+ t: Current simulation time
237
+ state: Current network state [n_states, n_nodes]
238
+ coupling_data: Precomputed static data (indices, etc.)
239
+ coupling_state: Mutable internal state (history buffers, etc.)
240
+ params: Coupling parameters (G, a, b, etc.)
241
+ graph: Network graph for accessing weights/delays
242
+
243
+ Returns:
244
+ Coupling input [n_coupling_inputs, n_nodes]
245
+ """
246
+ pass
247
+
248
+ @abstractmethod
249
+ def update_state(
250
+ self, coupling_data: Bunch, coupling_state: Bunch, new_state: jnp.ndarray
251
+ ) -> Bunch:
252
+ """Update coupling internal state after integration step.
253
+
254
+ Handles state-dependent updates like history buffer management.
255
+
256
+ Args:
257
+ coupling_data: Precomputed arrays (for reference)
258
+ coupling_state: Current internal state
259
+ new_state: New network state after integration [n_states, n_nodes]
260
+
261
+ Returns:
262
+ Updated coupling_state as Bunch
263
+ """
264
+ pass
265
+
266
+
267
+ class InstantaneousCoupling(AbstractCoupling):
268
+ """Base class for coupling without delays (ODE/SDE systems).
269
+
270
+ Handles standard weight matrix multiplication pattern:
271
+ 1. Extract incoming and local states
272
+ 2. Apply pre() transformation
273
+ 3. Matrix multiplication with connectivity weights
274
+ 4. Apply post() transformation
275
+
276
+ Users typically only need to override pre() and/or post() methods.
277
+ """
278
+
279
+ def get_mode(self, incoming_idx, local_idx, n_nodes=2) -> str:
280
+ """Detect coupling mode by calling pre() with dummy data.
281
+
282
+ This allows us to optimize sparse graphs by knowing ahead of time
283
+ whether the coupling uses vectorized or per-edge mode.
284
+
285
+ Args:
286
+ incoming_idx: Indices for incoming states (for sizing dummy data)
287
+ local_idx: Indices for local states (for sizing dummy data)
288
+
289
+ Returns:
290
+ 'vectorized' if pre() reduces dimensionality (2D output)
291
+ 'per_edge' if pre() preserves per-edge structure (3D output)
292
+ """
293
+ # Create dummy data with correct shapes based on actual state selection
294
+ n_incoming = len(incoming_idx) if hasattr(incoming_idx, "__len__") else 1
295
+ n_local = len(local_idx) if hasattr(local_idx, "__len__") else 1
296
+
297
+ # Dummy per-edge tensor: [n_incoming, n_nodes, n_nodes] with n_nodes=2
298
+ dummy_incoming = jnp.zeros((n_incoming, n_nodes, n_nodes))
299
+ dummy_local = jnp.zeros((n_local, n_nodes))
300
+
301
+ # Call pre() to check output shape
302
+ result = self.pre(dummy_incoming, dummy_local, self.params)
303
+
304
+ return "vectorized" if result.ndim == 2 else "per_edge"
305
+
306
+ def prepare(self, network, dt: float) -> Tuple[Bunch, Bunch]:
307
+ """Standard preparation for instantaneous coupling.
308
+
309
+ Args:
310
+ network: Network instance with graph, dynamics, initial_state
311
+ dt: Integration timestep (not used for instantaneous coupling)
312
+
313
+ Returns:
314
+ coupling_data: Bunch with incoming_indices, local_indices, state_indices, mode
315
+ coupling_state: Empty Bunch (no internal state)
316
+ """
317
+ graph = network.graph
318
+ dynamics = network.dynamics
319
+
320
+ # Resolve state indices
321
+ incoming_idx = dynamics.name_to_index(self.INCOMING_STATE_NAMES)
322
+ local_idx = dynamics.name_to_index(self.LOCAL_STATE_NAMES)
323
+
324
+ # Detect mode for optimization (used to decide sparse strategy)
325
+ mode = self.get_mode(incoming_idx, local_idx, n_nodes=graph.n_nodes)
326
+
327
+ # Create state_indices for per-edge coupling support (from v1 system)
328
+ # This allows incoming_states[:, state_indices] to expand to per-edge format
329
+ n_nodes = graph.n_nodes
330
+ state_indices = jnp.arange(n_nodes) * jnp.ones((n_nodes, n_nodes)).astype(int)
331
+
332
+ # Store mode as boolean flags (JAX-traceable) instead of string
333
+ is_per_edge = mode == "per_edge"
334
+
335
+ # Precompute BCOO indices for sparse incoming states optimization
336
+ bcoo_indices, bcoo_shape, use_sparse_incoming = _prepare_bcoo_indices(
337
+ graph, incoming_idx
338
+ )
339
+
340
+ coupling_data = Bunch(
341
+ incoming_indices=incoming_idx,
342
+ local_indices=local_idx,
343
+ state_indices=state_indices,
344
+ is_per_edge=is_per_edge,
345
+ bcoo_indices=bcoo_indices,
346
+ bcoo_shape=bcoo_shape,
347
+ use_sparse_incoming=use_sparse_incoming,
348
+ )
349
+ coupling_state = Bunch() # Empty for instantaneous coupling
350
+
351
+ return coupling_data, coupling_state
352
+
353
+ def compute(
354
+ self,
355
+ t: float,
356
+ state: jnp.ndarray,
357
+ coupling_data: Bunch,
358
+ coupling_state: Bunch,
359
+ params: Bunch,
360
+ graph: AbstractGraph,
361
+ ) -> jnp.ndarray:
362
+ """Coupling computation with automatic vectorized vs per-edge dispatch.
363
+
364
+ Supports two modes based on pre() output shape:
365
+ 1. Vectorized (2D): pre() returns [n_states, n_nodes] → use matmul
366
+ 2. Per-edge (3D): pre() returns [n_states, n_nodes, n_nodes] → element-wise multiply + sum
367
+
368
+ Both modes support dense and sparse graphs automatically.
369
+ For sparse graphs, per-edge expansion is kept sparse to save memory.
370
+
371
+ Args:
372
+ t: Current simulation time
373
+ state: Current network state [n_states, n_nodes]
374
+ coupling_data: Bunch with incoming_indices, local_indices, state_indices
375
+ coupling_state: Empty Bunch (not used)
376
+ params: Coupling parameters
377
+ graph: Network graph for accessing weights (dense or sparse)
378
+
379
+ Returns:
380
+ Coupling input [n_coupling_inputs, n_nodes]
381
+ """
382
+ from ..graph.sparse import SparseGraph
383
+
384
+ # Extract states
385
+ local_states = state[coupling_data.local_indices]
386
+ incoming_states = state[coupling_data.incoming_indices]
387
+
388
+ # Build incoming_states_edge and compute coupling based on graph type
389
+ if coupling_data.use_sparse_incoming:
390
+ # SPARSE INCOMING: Build 3D BCOO to avoid dense materialization
391
+ summed = self._compute_sparse_incoming(
392
+ incoming_states, local_states, params, graph, coupling_data
393
+ )
394
+
395
+ elif isinstance(graph, SparseGraph) and coupling_data.is_per_edge:
396
+ # SPARSE FALLBACK: Dense incoming with sparse graph
397
+ incoming_states_edge = incoming_states[:, coupling_data.state_indices]
398
+ pre_states = self.pre(incoming_states_edge, local_states, params)
399
+ summed = _sparse_weighted_sum(pre_states, graph, is_bcoo=False)
400
+
401
+ else:
402
+ # DENSE or VECTORIZED
403
+ incoming_states_edge = incoming_states[:, coupling_data.state_indices]
404
+ pre_states = self.pre(incoming_states_edge, local_states, params)
405
+
406
+ if pre_states.ndim == 2:
407
+ # Vectorized mode: matmul
408
+ summed = pre_states @ graph.weights
409
+ elif pre_states.ndim == 3:
410
+ # Per-edge mode: element-wise multiply + sum
411
+ summed = jnp.sum(pre_states * graph.weights, axis=2)
412
+ else:
413
+ raise ValueError(
414
+ f"pre() returned unexpected shape: {pre_states.shape}. "
415
+ f"Expected 2D or 3D."
416
+ )
417
+
418
+ # Apply post-transform
419
+ return self.post(summed, local_states, params)
420
+
421
+ def _compute_sparse_incoming(
422
+ self, incoming_states, local_states, params, graph, coupling_data
423
+ ):
424
+ """Compute coupling with sparse incoming states (BCOO optimization)."""
425
+ import jax.experimental.sparse as jsparse
426
+
427
+ indices = graph.weights.indices
428
+ n_incoming = incoming_states.shape[0]
429
+
430
+ # Extract values at source nodes for each incoming state
431
+ incoming_data_list = []
432
+ for i in range(n_incoming):
433
+ values_at_sources = incoming_states[i, indices[:, 1]]
434
+ incoming_data_list.append(values_at_sources)
435
+
436
+ incoming_data_flat = jnp.concatenate(incoming_data_list)
437
+
438
+ # Create 3D BCOO [n_incoming, n_nodes, n_nodes]
439
+ incoming_states_edge = jsparse.BCOO(
440
+ (incoming_data_flat, coupling_data.bcoo_indices),
441
+ shape=coupling_data.bcoo_shape,
442
+ )
443
+
444
+ # Apply sparse pre-transform
445
+ pre_states = self._sparse_pre(incoming_states_edge, local_states, params)
446
+
447
+ # Perform sparse weighted sum
448
+ return _sparse_weighted_sum(pre_states, graph, is_bcoo=True)
449
+
450
+ def update_state(
451
+ self, coupling_data: Bunch, coupling_state: Bunch, new_state: jnp.ndarray
452
+ ) -> Bunch:
453
+ """No mutable state to update for instantaneous coupling.
454
+
455
+ Args:
456
+ coupling_data: Not used
457
+ coupling_state: Empty Bunch
458
+ new_state: Not used
459
+
460
+ Returns:
461
+ Unchanged coupling_state (empty Bunch)
462
+ """
463
+ return coupling_state
464
+
465
+ def describe(self) -> dict:
466
+ """Generate human-readable description of coupling for printing.
467
+
468
+ Uses introspection of pre() and post() methods to infer mathematical form.
469
+ Subclasses can override to provide custom descriptions.
470
+
471
+ Returns:
472
+ Dictionary with 'network_form', 'pre_form', 'post_form' keys
473
+ """
474
+ # Get incoming/local state descriptions (no subscripts here)
475
+ incoming = self._format_state_list(self.INCOMING_STATE_NAMES)
476
+ local = self._format_state_list(self.LOCAL_STATE_NAMES)
477
+
478
+ # Check if pre() and post() are customized
479
+ pre_form = self._infer_pre_form(incoming, local)
480
+ post_form = self._infer_post_form()
481
+
482
+ # Determine which states are used in the network form
483
+ # FastLinearCoupling uses local states (vectorized mode)
484
+
485
+ # Get subscripted version for network form
486
+ state_with_subscript = self._format_state_list(
487
+ self.INCOMING_STATE_NAMES if incoming else self.LOCAL_STATE_NAMES,
488
+ with_subscript=True,
489
+ )
490
+
491
+ # Build network form with pre/post embedded
492
+ # Use post_form directly if available (already has actual values substituted)
493
+ base_sum = f"Σⱼ wᵢⱼ * {state_with_subscript}"
494
+
495
+ if pre_form and post_form:
496
+ # Substitute base into post_form
497
+ network_form = post_form.replace(
498
+ "(...)", f"Σⱼ wᵢⱼ * pre({state_with_subscript})"
499
+ )
500
+ elif pre_form:
501
+ network_form = f"Σⱼ wᵢⱼ * pre({state_with_subscript})"
502
+ elif post_form:
503
+ # Substitute the sum into post form
504
+ network_form = post_form.replace("(...)", base_sum)
505
+ else:
506
+ network_form = base_sum
507
+
508
+ return {
509
+ "network_form": network_form,
510
+ "pre_form": pre_form if pre_form else None,
511
+ "post_form": post_form if post_form else None,
512
+ }
513
+
514
+ def _format_state_list(self, states, with_subscript: bool = False) -> str:
515
+ """Format state names for display.
516
+
517
+ Args:
518
+ states: State names (str, list, or tuple)
519
+ with_subscript: If True, add subscript ⱼ to each state
520
+
521
+ Returns:
522
+ Formatted string like 'S', 'Sⱼ', '(y1ⱼ, y2ⱼ)', etc.
523
+ """
524
+ if isinstance(states, str):
525
+ return states + "ⱼ" if with_subscript else states
526
+ elif isinstance(states, (list, tuple)):
527
+ if len(states) == 0:
528
+ return ""
529
+ elif len(states) == 1:
530
+ state = states[0]
531
+ return state + "ⱼ" if with_subscript else state
532
+ else:
533
+ # Multiple states: format as (state1ⱼ, state2ⱼ)
534
+ if with_subscript:
535
+ formatted = [s + "ⱼ" for s in states]
536
+ else:
537
+ formatted = states
538
+ return f"({', '.join(formatted)})"
539
+ return str(states)
540
+
541
+ def _infer_pre_form(self, incoming: str, local: str) -> str:
542
+ """Infer pre() transformation form by introspecting the method.
543
+
544
+ Returns empty string if pre() is the default identity.
545
+ """
546
+ import inspect
547
+
548
+ try:
549
+ pre_source = inspect.getsource(self.pre)
550
+ # Check if it's the default identity (returns incoming_states unchanged)
551
+ if "return incoming_states" in pre_source and pre_source.count("\n") <= 5:
552
+ return "" # Default identity, don't show
553
+ except (AttributeError, OSError, TypeError):
554
+ pass
555
+
556
+ # Check if there are meaningful parameters used in pre
557
+ # For now, return empty - subclasses will override if needed
558
+ return ""
559
+
560
+ def _infer_post_form(self) -> str:
561
+ """Infer post() transformation form by introspecting the method.
562
+
563
+ Returns the post transformation with actual parameter values.
564
+ """
565
+ import inspect
566
+
567
+ try:
568
+ post_source = inspect.getsource(self.post)
569
+
570
+ # Try to extract the return expression
571
+ lines = post_source.strip().split("\n")
572
+ for line in lines:
573
+ if "return" in line:
574
+ # Extract expression after return
575
+ expr = line.split("return", 1)[1].strip()
576
+
577
+ # Substitute parameter values
578
+ for key, value in self.params.items():
579
+ # Replace params.key with actual value
580
+ expr = expr.replace(f"params.{key}", str(value))
581
+
582
+ # Clean up common patterns
583
+ expr = expr.replace("summed_inputs", "(...)")
584
+ expr = expr.replace("local_states", "local")
585
+
586
+ return expr
587
+ except (AttributeError, OSError, TypeError, KeyError):
588
+ pass
589
+
590
+ # Fallback: check for common parameter patterns
591
+ if "G" in self.params:
592
+ return "G * (...)"
593
+
594
+ return ""
595
+
596
+ def pre(
597
+ self, incoming_states: jnp.ndarray, local_states: jnp.ndarray, params: Bunch
598
+ ) -> jnp.ndarray:
599
+ """Transform states before matrix multiplication. Default: identity (per-edge).
600
+
601
+ Args:
602
+ incoming_states: States from connected nodes in per-edge format
603
+ Shape: [n_incoming, n_nodes_target, n_nodes_source]
604
+ where [:, j, k] is state from source node k to target node j
605
+ local_states: States from current node [n_local, n_nodes]
606
+ params: Coupling parameters
607
+
608
+ Returns:
609
+ Transformed states - shape determines coupling mode:
610
+ - [n_states, n_nodes]: Vectorized mode (uses matmul)
611
+ - [n_states, n_nodes, n_nodes]: Per-edge mode (uses element-wise multiply + sum)
612
+
613
+ Default returns incoming_states unchanged (3D) → per-edge mode
614
+ This matches v1 behavior where default pre() is identity.
615
+ """
616
+ # Default: return incoming_states unchanged (identity)
617
+ # This gives [n_incoming, n_nodes, n_nodes] shape → per-edge mode (like v1)
618
+ return incoming_states
619
+
620
+ def _sparse_pre(self, incoming_states, local_states: jnp.ndarray, params: Bunch):
621
+ """Sparse version of pre() using sparsify decorator.
622
+
623
+ Default implementation wraps self.pre() with sparsify.
624
+ Subclasses can override this for custom sparse implementations.
625
+
626
+ Args:
627
+ incoming_states: BCOO tensor [n_incoming, n_nodes, n_nodes]
628
+ local_states: Dense tensor [n_local, n_nodes]
629
+ params: Coupling parameters
630
+
631
+ Returns:
632
+ BCOO tensor [n_output, n_nodes, n_nodes]
633
+ """
634
+ import jax.experimental.sparse as jsparse
635
+
636
+ return jsparse.sparsify(self.pre)(incoming_states, local_states, params)
637
+
638
+ @abstractmethod
639
+ def post(
640
+ self, summed_inputs: jnp.ndarray, local_states: jnp.ndarray, params: Bunch
641
+ ) -> jnp.ndarray:
642
+ """Transform coupling after summation. Must be implemented by subclasses.
643
+
644
+ Args:
645
+ summed_inputs: Summed coupling inputs [n_coupling_inputs, n_nodes]
646
+ local_states: States from current node [n_local, n_nodes]
647
+ params: Coupling parameters
648
+
649
+ Returns:
650
+ Final coupling input [n_coupling_inputs, n_nodes]
651
+ """
652
+ pass
653
+
654
+
655
+ class DelayedCoupling(AbstractCoupling):
656
+ """Base class for coupling with transmission delays (DDE/SDDE systems).
657
+
658
+ Handles delayed coupling pattern:
659
+ 1. Extract delayed states from history buffer
660
+ 2. Apply pre() transformation
661
+ 3. Matrix multiplication with connectivity weights
662
+ 4. Apply post() transformation
663
+ 5. Update history buffer
664
+
665
+ Users typically only need to override pre() and/or post() methods.
666
+ """
667
+
668
+ def prepare(self, network, dt: float) -> Tuple[Bunch, Bunch]:
669
+ """Standard preparation for delayed coupling.
670
+
671
+ Args:
672
+ network: Network instance with graph, dynamics, initial_state
673
+ dt: Integration timestep
674
+
675
+ Returns:
676
+ coupling_data: Bunch with indices, delay_indices, state_indices
677
+ coupling_state: Bunch with history buffer
678
+ """
679
+ graph = network.graph
680
+ dynamics = network.dynamics
681
+
682
+ # Resolve state indices
683
+ incoming_idx = dynamics.name_to_index(self.INCOMING_STATE_NAMES)
684
+ local_idx = dynamics.name_to_index(self.LOCAL_STATE_NAMES)
685
+
686
+ # Setup delay indexing (static)
687
+ delays_dense = _ensure_dense(graph.delays)
688
+ delay_indices = jnp.round(delays_dense / dt).astype(jnp.int32)
689
+ state_indices = jnp.arange(graph.n_nodes)
690
+
691
+ # Precompute BCOO indices for sparse incoming states optimization
692
+ bcoo_indices, bcoo_shape, use_sparse_incoming = _prepare_bcoo_indices(
693
+ graph, incoming_idx
694
+ )
695
+
696
+ coupling_data = Bunch(
697
+ incoming_indices=incoming_idx,
698
+ local_indices=local_idx,
699
+ delay_indices=delay_indices,
700
+ state_indices=state_indices,
701
+ bcoo_indices=bcoo_indices,
702
+ bcoo_shape=bcoo_shape,
703
+ use_sparse_incoming=use_sparse_incoming,
704
+ )
705
+
706
+ # Initialize history buffer using network's get_history
707
+ # This matches v1's network.get_history(dt=dt) behavior
708
+ history_full = network.get_history(dt) # [max_delay_steps+1, n_states, n_nodes]
709
+
710
+ # Extract only incoming states for history buffer
711
+ history = history_full[
712
+ :, incoming_idx, :
713
+ ] # [max_delay_steps+1, n_incoming, n_nodes]
714
+
715
+ coupling_state = Bunch(history=history)
716
+
717
+ return coupling_data, coupling_state
718
+
719
+ def compute(
720
+ self,
721
+ t: float,
722
+ state: jnp.ndarray,
723
+ coupling_data: Bunch,
724
+ coupling_state: Bunch,
725
+ params: Bunch,
726
+ graph: AbstractGraph,
727
+ ) -> jnp.ndarray:
728
+ """Delayed coupling computation with sparse graph support.
729
+
730
+ Delays are always per-edge (heterogeneous delays per connection).
731
+ Exploits same sparsity pattern for weights and delays when using sparse graphs.
732
+
733
+ Args:
734
+ t: Current simulation time
735
+ state: Current network state [n_states, n_nodes]
736
+ coupling_data: Bunch with indices, delay_indices
737
+ coupling_state: Bunch with history buffer
738
+ params: Coupling parameters
739
+ graph: Network graph for accessing weights (dense or sparse)
740
+
741
+ Returns:
742
+ Coupling input [n_coupling_inputs, n_nodes]
743
+ """
744
+ from ..graph.sparse import SparseDelayGraph
745
+
746
+ # Extract delayed states from history using indices from coupling_data
747
+ # delayed_states[i, j, k] = history[delay[j,k], i, k]
748
+ # i.e., state i from node k delayed by delay[j,k] going to node j
749
+ delayed_states = jnp.transpose(
750
+ coupling_state.history[
751
+ coupling_data.delay_indices, :, coupling_data.state_indices
752
+ ],
753
+ (
754
+ 2,
755
+ 0,
756
+ 1,
757
+ ), # Reorder to [n_incoming, n_nodes_target, n_nodes_source] - matches v1
758
+ )
759
+
760
+ # Extract local states
761
+ local_states = state[coupling_data.local_indices]
762
+
763
+ # Compute coupling based on graph type
764
+ if coupling_data.use_sparse_incoming:
765
+ # SPARSE DELAYED INCOMING: Build 3D BCOO
766
+ summed = self._compute_sparse_delayed(
767
+ delayed_states, local_states, params, graph, coupling_data
768
+ )
769
+
770
+ elif isinstance(graph, SparseDelayGraph):
771
+ # SPARSE FALLBACK: Dense delayed states with sparse graph
772
+ pre_states = self.pre(delayed_states, local_states, params)
773
+ summed = _sparse_weighted_sum(pre_states, graph, is_bcoo=False)
774
+
775
+ else:
776
+ # DENSE DELAYED PATH
777
+ pre_states = self.pre(delayed_states, local_states, params)
778
+ summed = jnp.sum(pre_states * graph.weights, axis=2)
779
+
780
+ # Apply post-transform
781
+ return self.post(summed, local_states, params)
782
+
783
+ def _compute_sparse_delayed(
784
+ self, delayed_states, local_states, params, graph, coupling_data
785
+ ):
786
+ """Compute delayed coupling with sparse delayed states (BCOO optimization)."""
787
+ import jax.experimental.sparse as jsparse
788
+
789
+ indices = graph.weights.indices
790
+ n_incoming = coupling_data.bcoo_shape[0]
791
+
792
+ # Extract delayed values at edges for each incoming state
793
+ delayed_data_list = []
794
+ for i in range(n_incoming):
795
+ # Get delayed state from source_k to target_j for each edge
796
+ values_at_edges = delayed_states[i, indices[:, 0], indices[:, 1]]
797
+ delayed_data_list.append(values_at_edges)
798
+
799
+ delayed_data_flat = jnp.concatenate(delayed_data_list)
800
+
801
+ # Create 3D BCOO [n_incoming, n_nodes, n_nodes]
802
+ delayed_states_sparse = jsparse.BCOO(
803
+ (delayed_data_flat, coupling_data.bcoo_indices),
804
+ shape=coupling_data.bcoo_shape,
805
+ )
806
+
807
+ # Apply sparse pre-transform
808
+ pre_states = self._sparse_pre(delayed_states_sparse, local_states, params)
809
+
810
+ # Perform sparse weighted sum
811
+ return _sparse_weighted_sum(pre_states, graph, is_bcoo=True)
812
+
813
+ def update_state(
814
+ self, coupling_data: Bunch, coupling_state: Bunch, new_state: jnp.ndarray
815
+ ) -> Bunch:
816
+ """Update history buffer for delayed coupling.
817
+
818
+ Args:
819
+ coupling_data: Bunch with incoming_indices (for extracting states)
820
+ coupling_state: Bunch with current history buffer
821
+ new_state: New network state after integration [n_states, n_nodes]
822
+
823
+ Returns:
824
+ New Bunch with updated history buffer
825
+ """
826
+ # Update history buffer (circular) - only mutable operation
827
+ new_history = jnp.roll(coupling_state.history, -1, axis=0)
828
+ new_incoming_states = new_state[coupling_data.incoming_indices]
829
+ new_history = new_history.at[0].set(new_incoming_states)
830
+
831
+ return Bunch(history=new_history)
832
+
833
+ def describe(self) -> dict:
834
+ """Generate human-readable description of delayed coupling for printing.
835
+
836
+ Uses introspection of pre() and post() methods to infer mathematical form.
837
+ Subclasses can override to provide custom descriptions.
838
+
839
+ Returns:
840
+ Dictionary with 'network_form', 'pre_form', 'post_form' keys
841
+ """
842
+ # Get incoming/local state descriptions (no subscripts here)
843
+ incoming = self._format_state_list(self.INCOMING_STATE_NAMES)
844
+ local = self._format_state_list(self.LOCAL_STATE_NAMES)
845
+
846
+ # Check if pre() and post() are customized
847
+ pre_form = self._infer_pre_form(incoming, local)
848
+ post_form = self._infer_post_form()
849
+
850
+ # Get subscripted version for network form
851
+ incoming_with_subscript = self._format_state_list(
852
+ self.INCOMING_STATE_NAMES, with_subscript=True
853
+ )
854
+
855
+ # Build network form with pre/post embedded and delays
856
+ if pre_form and post_form:
857
+ network_form = f"post(Σⱼ wᵢⱼ * pre({incoming_with_subscript}(t - τᵢⱼ)))"
858
+ elif pre_form:
859
+ network_form = f"Σⱼ wᵢⱼ * pre({incoming_with_subscript}(t - τᵢⱼ))"
860
+ elif post_form:
861
+ network_form = f"post(Σⱼ wᵢⱼ * {incoming_with_subscript}(t - τᵢⱼ))"
862
+ else:
863
+ network_form = f"Σⱼ wᵢⱼ * {incoming_with_subscript}(t - τᵢⱼ)"
864
+
865
+ return {
866
+ "network_form": network_form,
867
+ "pre_form": pre_form,
868
+ "post_form": post_form,
869
+ }
870
+
871
+ def _format_state_list(self, states, with_subscript: bool = False) -> str:
872
+ """Format state names for display.
873
+
874
+ Args:
875
+ states: State names (str, list, or tuple)
876
+ with_subscript: If True, add subscript ⱼ to each state
877
+
878
+ Returns:
879
+ Formatted string like 'S', 'Sⱼ', '(y1ⱼ, y2ⱼ)', etc.
880
+ """
881
+ if isinstance(states, str):
882
+ return states + "ⱼ" if with_subscript else states
883
+ elif isinstance(states, (list, tuple)):
884
+ if len(states) == 0:
885
+ return ""
886
+ elif len(states) == 1:
887
+ state = states[0]
888
+ return state + "ⱼ" if with_subscript else state
889
+ else:
890
+ # Multiple states: format as (state1ⱼ, state2ⱼ)
891
+ if with_subscript:
892
+ formatted = [s + "ⱼ" for s in states]
893
+ else:
894
+ formatted = states
895
+ return f"({', '.join(formatted)})"
896
+ return str(states)
897
+
898
+ def _infer_pre_form(self, incoming: str, local: str) -> str:
899
+ """Infer pre() transformation form by introspecting the method.
900
+
901
+ Returns empty string if pre() is the default identity.
902
+ """
903
+ import inspect
904
+
905
+ try:
906
+ pre_source = inspect.getsource(self.pre)
907
+ # Check if it's the default identity (returns delayed_states unchanged)
908
+ if "return delayed_states" in pre_source and pre_source.count("\n") <= 5:
909
+ return "" # Default identity, don't show
910
+ except (AttributeError, OSError, TypeError):
911
+ pass
912
+
913
+ # Check if there are meaningful parameters used in pre
914
+ # For now, return empty - subclasses will override if needed
915
+ return ""
916
+
917
+ def _infer_post_form(self) -> str:
918
+ """Infer post() transformation form by introspecting the method.
919
+
920
+ Returns the post transformation with actual parameter values.
921
+ """
922
+ import inspect
923
+
924
+ try:
925
+ post_source = inspect.getsource(self.post)
926
+
927
+ # Try to extract the return expression
928
+ lines = post_source.strip().split("\n")
929
+ for line in lines:
930
+ if "return" in line:
931
+ # Extract expression after return
932
+ expr = line.split("return", 1)[1].strip()
933
+
934
+ # Substitute parameter values
935
+ for key, value in self.params.items():
936
+ # Replace params.key with actual value
937
+ expr = expr.replace(f"params.{key}", str(value))
938
+
939
+ # Clean up common patterns
940
+ expr = expr.replace("summed_inputs", "(...)")
941
+ expr = expr.replace("local_states", "local")
942
+
943
+ return expr
944
+ except (AttributeError, OSError, TypeError, KeyError):
945
+ pass
946
+
947
+ # Fallback: check for common parameter patterns
948
+ if "G" in self.params:
949
+ return "G * (...)"
950
+
951
+ return ""
952
+
953
+ def pre(
954
+ self, delayed_states: jnp.ndarray, local_states: jnp.ndarray, params: Bunch
955
+ ) -> jnp.ndarray:
956
+ """Transform delayed states before matrix multiplication. Default: identity.
957
+
958
+ Args:
959
+ delayed_states: Delayed states from history in per-edge format
960
+ Shape: [n_incoming, n_nodes_target, n_nodes_source]
961
+ where [:, j, k] is state from source node k to target node j,
962
+ delayed by delay[j, k]
963
+ local_states: States from current node [n_local, n_nodes]
964
+ params: Coupling parameters
965
+
966
+ Returns:
967
+ Transformed states [n_incoming, n_nodes_target, n_nodes_source]
968
+ Note: Delays are always per-edge (3D), unlike instantaneous coupling
969
+ which supports both vectorized (2D) and per-edge (3D) modes.
970
+ """
971
+ return delayed_states
972
+
973
+ def _sparse_pre(self, delayed_states, local_states: jnp.ndarray, params: Bunch):
974
+ """Sparse version of pre() using sparsify decorator.
975
+
976
+ Default implementation wraps self.pre() with sparsify.
977
+ Subclasses can override this for custom sparse implementations.
978
+
979
+ Args:
980
+ delayed_states: BCOO tensor [n_incoming, n_nodes, n_nodes]
981
+ local_states: Dense tensor [n_local, n_nodes]
982
+ params: Coupling parameters
983
+
984
+ Returns:
985
+ BCOO tensor [n_output, n_nodes, n_nodes]
986
+ """
987
+ import jax.experimental.sparse as jsparse
988
+
989
+ return jsparse.sparsify(self.pre)(delayed_states, local_states, params)
990
+
991
+ @abstractmethod
992
+ def post(
993
+ self, summed_inputs: jnp.ndarray, local_states: jnp.ndarray, params: Bunch
994
+ ) -> jnp.ndarray:
995
+ """Transform coupling after summation. Must be implemented by subclasses.
996
+
997
+ Args:
998
+ summed_inputs: Summed coupling inputs [n_coupling_inputs, n_nodes]
999
+ local_states: States from current node [n_local, n_nodes]
1000
+ params: Coupling parameters
1001
+
1002
+ Returns:
1003
+ Final coupling input [n_coupling_inputs, n_nodes]
1004
+ """
1005
+ pass