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,885 @@
1
+ """Sparse graph implementations using JAX BCOO format.
2
+
3
+ This module provides sparse alternatives to dense graphs for memory efficiency
4
+ with large, sparse connectivity matrices.
5
+ """
6
+
7
+ from typing import Optional, Sequence, Tuple, Union
8
+
9
+ import jax
10
+ import jax.numpy as jnp
11
+ from jax.experimental.sparse import BCOO
12
+ from jax.tree_util import register_pytree_node_class
13
+
14
+ from .base import AbstractGraph
15
+
16
+
17
+ @register_pytree_node_class
18
+ class SparseGraph(AbstractGraph):
19
+ """Sparse graph representation using JAX BCOO format.
20
+
21
+ Stores only non-zero weights for memory efficiency. Suitable for large
22
+ networks with sparse connectivity (e.g., < 30% density).
23
+
24
+ Args:
25
+ weights: Sparse weight matrix (BCOO) or dense array (will be sparsified)
26
+ region_labels: Optional sequence of region labels (list, tuple, or array). If None, defaults to ['Region_0', 'Region_1', ...]
27
+ threshold: Values with absolute value below this are treated as zero
28
+
29
+ Example:
30
+ >>> # From dense
31
+ >>> dense_weights = jnp.array([[0, 0.5, 0], [0.3, 0, 0], [0, 0.2, 0]])
32
+ >>> graph = SparseGraph(dense_weights)
33
+ >>>
34
+ >>> # From COO format
35
+ >>> data = jnp.array([0.5, 0.3, 0.2])
36
+ >>> row = jnp.array([0, 1, 2])
37
+ >>> col = jnp.array([1, 0, 1])
38
+ >>> graph = SparseGraph.from_coo(data, row, col, shape=(3, 3))
39
+ >>>
40
+ >>> # From dense graph
41
+ >>> from network_dynamics.graph.base import DenseGraph
42
+ >>> dense_graph = DenseGraph(dense_weights)
43
+ >>> sparse_graph = SparseGraph.from_dense(dense_graph, threshold=1e-10)
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ weights: Union[BCOO, jnp.ndarray],
49
+ region_labels: Optional[Sequence[str]] = None,
50
+ threshold: float = 0.0,
51
+ ):
52
+ """Initialize sparse graph from BCOO or dense array."""
53
+ if isinstance(weights, BCOO):
54
+ self._weights = weights
55
+ else:
56
+ # Convert dense to sparse
57
+ weights_arr = jnp.asarray(weights)
58
+ # Apply threshold
59
+ if threshold > 0.0:
60
+ weights_arr = jnp.where(
61
+ jnp.abs(weights_arr) > threshold, weights_arr, 0.0
62
+ )
63
+ self._weights = BCOO.fromdense(weights_arr)
64
+
65
+ # Validate shape
66
+ if self._weights.ndim != 2:
67
+ raise ValueError(f"Weight matrix must be 2D, got {self._weights.ndim}D")
68
+
69
+ if self._weights.shape[0] != self._weights.shape[1]:
70
+ raise ValueError(
71
+ f"Weight matrix must be square, got shape {self._weights.shape}"
72
+ )
73
+
74
+ self._n_nodes = self._weights.shape[0]
75
+
76
+ # Store region labels (auto-generate if not provided)
77
+ if region_labels is None:
78
+ self._region_labels = [f"Region_{i}" for i in range(self._n_nodes)]
79
+ else:
80
+ if len(region_labels) != self._n_nodes:
81
+ raise ValueError(
82
+ f"Number of region labels ({len(region_labels)}) must match "
83
+ f"number of nodes ({self._n_nodes})"
84
+ )
85
+ self._region_labels = list(region_labels)
86
+
87
+ @classmethod
88
+ def from_dense(cls, graph: "AbstractGraph", threshold: float = 1e-10):
89
+ """Convert dense graph to sparse.
90
+
91
+ Args:
92
+ graph: Dense graph to convert
93
+ threshold: Set values with |weight| < threshold to zero
94
+
95
+ Returns:
96
+ SparseGraph with same connectivity (zeroed below threshold)
97
+ """
98
+ weights = graph.weights
99
+ # Apply threshold
100
+ weights_masked = jnp.where(jnp.abs(weights) > threshold, weights, 0.0)
101
+ # Convert to sparse (threshold already applied, so pass 0.0)
102
+ return cls(weights_masked, threshold=0.0)
103
+
104
+ @classmethod
105
+ def from_coo(
106
+ cls,
107
+ data: jnp.ndarray,
108
+ row: jnp.ndarray,
109
+ col: jnp.ndarray,
110
+ shape: Tuple[int, int],
111
+ ):
112
+ """Create sparse graph from COO format.
113
+
114
+ Args:
115
+ data: Non-zero weight values [nnz]
116
+ row: Row indices [nnz]
117
+ col: Column indices [nnz]
118
+ shape: Matrix shape (n_nodes, n_nodes)
119
+
120
+ Returns:
121
+ SparseGraph with specified connectivity
122
+
123
+ Example:
124
+ >>> # Triangle graph: 0->1, 1->2, 2->0
125
+ >>> data = jnp.array([0.5, 0.3, 0.2])
126
+ >>> row = jnp.array([0, 1, 2])
127
+ >>> col = jnp.array([1, 2, 0])
128
+ >>> graph = SparseGraph.from_coo(data, row, col, shape=(3, 3))
129
+ """
130
+ indices = jnp.stack([row, col], axis=1)
131
+ weights_sparse = BCOO((data, indices), shape=shape)
132
+ return cls(weights_sparse, threshold=0.0)
133
+
134
+ @property
135
+ def n_nodes(self) -> int:
136
+ """Number of nodes in the network."""
137
+ return self._n_nodes
138
+
139
+ @property
140
+ def region_labels(self) -> Sequence[str]:
141
+ """Labels for each node/region in the network."""
142
+ return self._region_labels
143
+
144
+ @property
145
+ def weights(self) -> BCOO:
146
+ """Sparse weight matrix in BCOO format."""
147
+ return self._weights
148
+
149
+ @property
150
+ def nnz(self) -> int:
151
+ """Number of non-zero elements in weight matrix."""
152
+ return self._weights.nse
153
+
154
+ @property
155
+ def sparsity(self) -> float:
156
+ """Fraction of non-zero connections (excluding diagonal)."""
157
+ total_possible = self._n_nodes * (self._n_nodes - 1)
158
+ if total_possible == 0:
159
+ return 0.0
160
+
161
+ # Count off-diagonal non-zeros
162
+ row_idx = self._weights.indices[:, 0]
163
+ col_idx = self._weights.indices[:, 1]
164
+ off_diag_nnz = jnp.sum(row_idx != col_idx)
165
+
166
+ return float(off_diag_nnz) / total_possible
167
+
168
+ @property
169
+ def symmetric(self) -> bool:
170
+ """Check if the graph is symmetric (undirected).
171
+
172
+ Note: This converts to dense for comparison. For large sparse graphs,
173
+ this can be memory intensive. Use sparingly.
174
+ """
175
+ dense = self._weights.todense()
176
+ return bool(jnp.allclose(dense, dense.T))
177
+
178
+ def todense(self) -> jnp.ndarray:
179
+ """Convert sparse graph to dense array.
180
+
181
+ Warning: This creates a full n_nodes x n_nodes array. Use sparingly
182
+ for large sparse graphs.
183
+
184
+ Returns:
185
+ Dense weight matrix [n_nodes, n_nodes]
186
+ """
187
+ return self._weights.todense()
188
+
189
+ def verify(self, verbose: bool = True) -> bool:
190
+ """Verify graph structure and properties.
191
+
192
+ Args:
193
+ verbose: Whether to print verification details
194
+
195
+ Returns:
196
+ True if verification passes, False otherwise
197
+ """
198
+ # Check for NaN/Inf in sparse data
199
+ if jnp.any(jnp.isnan(self._weights.data)):
200
+ if verbose:
201
+ print("ERROR: NaN values in sparse weights")
202
+ return False
203
+
204
+ if jnp.any(jnp.isinf(self._weights.data)):
205
+ if verbose:
206
+ print("ERROR: Inf values in sparse weights")
207
+ return False
208
+
209
+ if verbose:
210
+ density_pct = self.sparsity * 100
211
+ print("SparseGraph verification passed:")
212
+ print(f" Nodes: {self._n_nodes}")
213
+ print(f" Non-zeros: {self.nnz}")
214
+ print(f" Density: {density_pct:.3f}%")
215
+ print(f" Symmetric: {self.symmetric}")
216
+
217
+ return True
218
+
219
+ @classmethod
220
+ def random(
221
+ cls,
222
+ n_nodes: int,
223
+ sparsity: float = 0.7,
224
+ symmetric: bool = True,
225
+ weight_dist: str = "lognormal",
226
+ allow_self_loops: bool = False,
227
+ key: Optional[jax.random.PRNGKey] = None,
228
+ ) -> "SparseGraph":
229
+ """Create a random sparse graph with brain-like connectivity.
230
+
231
+ Args:
232
+ n_nodes: Number of nodes in the network
233
+ sparsity: Fraction of connections present (0.7 = 70% dense)
234
+ symmetric: Whether to create undirected (symmetric) connectivity
235
+ weight_dist: Weight distribution ('lognormal', 'uniform', or 'binary')
236
+ allow_self_loops: Whether to allow self-connections (diagonal)
237
+ key: JAX random key (if None, creates one with seed 0)
238
+
239
+ Returns:
240
+ SparseGraph with random connectivity
241
+
242
+ Example:
243
+ >>> import jax
244
+ >>> key = jax.random.key(42)
245
+ >>> graph = SparseGraph.random(n_nodes=100, sparsity=0.3, key=key)
246
+ """
247
+ if key is None:
248
+ key = jax.random.key(0)
249
+
250
+ # Split keys for edge sampling and weights
251
+ key_edges, key_weights = jax.random.split(key)
252
+
253
+ # Calculate expected number of edges
254
+ max_edges = (
255
+ n_nodes * (n_nodes - 1) if not allow_self_loops else n_nodes * n_nodes
256
+ )
257
+ if symmetric:
258
+ max_edges = max_edges // 2 # Only upper triangle
259
+
260
+ n_edges = int(sparsity * max_edges)
261
+
262
+ if symmetric:
263
+ # Sample edges from upper triangle only
264
+ key_row, key_col = jax.random.split(key_edges)
265
+
266
+ # Sample random upper triangular edges
267
+ row = jax.random.randint(key_row, (n_edges,), 0, n_nodes)
268
+ col = jax.random.randint(key_col, (n_edges,), 0, n_nodes)
269
+
270
+ # Ensure upper triangle (swap if needed) and no self-loops if required
271
+ needs_swap = row > col
272
+ row, col = jnp.where(needs_swap, col, row), jnp.where(needs_swap, row, col)
273
+
274
+ if not allow_self_loops:
275
+ # Filter out diagonal entries
276
+ valid = row != col
277
+ row, col = row[valid], col[valid]
278
+ # Resample to get back to desired edge count (approximate)
279
+ actual_n = len(row)
280
+ if actual_n < n_edges:
281
+ # Add more edges to compensate
282
+ key_extra = jax.random.fold_in(key_edges, 1)
283
+ extra_needed = n_edges - actual_n
284
+ key_row2, key_col2 = jax.random.split(key_extra)
285
+ extra_row = jax.random.randint(
286
+ key_row2, (extra_needed,), 0, n_nodes
287
+ )
288
+ extra_col = jax.random.randint(
289
+ key_col2, (extra_needed,), 0, n_nodes
290
+ )
291
+ needs_swap2 = extra_row >= extra_col
292
+ extra_row = jnp.where(needs_swap2, extra_row + 1, extra_row)
293
+ extra_row = jnp.clip(extra_row, 0, n_nodes - 1)
294
+ row = jnp.concatenate([row, extra_row])
295
+ col = jnp.concatenate([col, extra_col])
296
+
297
+ # Generate weights for upper triangle edges
298
+ if weight_dist == "lognormal":
299
+ edge_weights = jax.random.lognormal(key_weights, shape=(len(row),))
300
+ elif weight_dist == "uniform":
301
+ edge_weights = jax.random.uniform(key_weights, shape=(len(row),))
302
+ elif weight_dist == "binary":
303
+ edge_weights = jnp.ones(len(row))
304
+ else:
305
+ raise ValueError(f"Unknown weight_dist: {weight_dist}")
306
+
307
+ # Create symmetric edges by duplicating (i,j) -> (j,i)
308
+ row_sym = jnp.concatenate([row, col])
309
+ col_sym = jnp.concatenate([col, row])
310
+ weights_sym = jnp.concatenate([edge_weights, edge_weights])
311
+
312
+ # Create sparse matrix from COO
313
+ indices = jnp.stack([row_sym, col_sym], axis=1)
314
+ weights_bcoo = BCOO((weights_sym, indices), shape=(n_nodes, n_nodes))
315
+
316
+ else:
317
+ # Non-symmetric: sample random edges
318
+ key_row, key_col = jax.random.split(key_edges)
319
+ row = jax.random.randint(key_row, (n_edges,), 0, n_nodes)
320
+ col = jax.random.randint(key_col, (n_edges,), 0, n_nodes)
321
+
322
+ if not allow_self_loops:
323
+ # Filter and resample diagonal entries
324
+ valid = row != col
325
+ row, col = row[valid], col[valid]
326
+
327
+ # Generate weights
328
+ if weight_dist == "lognormal":
329
+ edge_weights = jax.random.lognormal(key_weights, shape=(len(row),))
330
+ elif weight_dist == "uniform":
331
+ edge_weights = jax.random.uniform(key_weights, shape=(len(row),))
332
+ elif weight_dist == "binary":
333
+ edge_weights = jnp.ones(len(row))
334
+ else:
335
+ raise ValueError(f"Unknown weight_dist: {weight_dist}")
336
+
337
+ # Create sparse matrix from COO
338
+ indices = jnp.stack([row, col], axis=1)
339
+ weights_bcoo = BCOO((edge_weights, indices), shape=(n_nodes, n_nodes))
340
+
341
+ return cls(weights_bcoo, threshold=0.0)
342
+
343
+ def plot(self, log_scale_weights: bool = False, figsize: tuple = (12, 5)):
344
+ """Plot sparse connectivity matrix and weight distribution.
345
+
346
+ Args:
347
+ log_scale_weights: If True, log-transform weights before plotting (helps reveal structure)
348
+ figsize: Figure size (width, height)
349
+
350
+ Returns:
351
+ fig, axes: Matplotlib figure and axes
352
+
353
+ Note:
354
+ Converts sparse matrix to dense for visualization. Zeros are shown as white (background).
355
+ """
356
+ try:
357
+ import matplotlib.pyplot as plt
358
+ except ImportError:
359
+ raise ImportError(
360
+ "matplotlib is required for plotting. Install with: pip install matplotlib"
361
+ )
362
+
363
+ # Convert to dense for plotting
364
+ weights_dense = self.todense()
365
+
366
+ # Prepare weights for plotting
367
+ if log_scale_weights:
368
+ weights_plot = jnp.where(
369
+ weights_dense > 0, jnp.log10(weights_dense + 1e-10), jnp.nan
370
+ )
371
+ weight_label = "log10(Weight)"
372
+ else:
373
+ weights_plot = jnp.where(weights_dense > 0, weights_dense, jnp.nan)
374
+ weight_label = "Weight"
375
+
376
+ # Create figure
377
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize)
378
+
379
+ # Create custom colormap with white for NaN (zeros)
380
+ cmap = plt.cm.cividis.copy()
381
+ cmap.set_bad("white")
382
+
383
+ # Plot connectivity matrix
384
+ im1 = ax1.imshow(weights_plot, cmap=cmap, aspect="auto")
385
+ ax1.set_title("Connectivity Matrix")
386
+ ax1.set_xlabel("Target Node")
387
+ ax1.set_ylabel("Source Node")
388
+ plt.colorbar(im1, ax=ax1, label=weight_label)
389
+
390
+ # Plot weight distribution
391
+ weights_nonzero = weights_dense[weights_dense > 0]
392
+ if len(weights_nonzero) > 0:
393
+ if log_scale_weights:
394
+ weights_nonzero = jnp.log10(weights_nonzero + 1e-10)
395
+ ax2.hist(weights_nonzero, bins=50, edgecolor="black", alpha=0.7)
396
+ ax2.set_xlabel(weight_label)
397
+ ax2.set_ylabel("Count")
398
+ ax2.set_title("Weight Distribution")
399
+ ax2.set_yscale("log")
400
+ else:
401
+ ax2.text(
402
+ 0.5,
403
+ 0.5,
404
+ "No connections",
405
+ ha="center",
406
+ va="center",
407
+ transform=ax2.transAxes,
408
+ )
409
+ ax2.set_title("Weight Distribution")
410
+
411
+ # Main title with graph properties
412
+ fig.suptitle(
413
+ f"{self.__class__.__name__}: {self.n_nodes} nodes, nnz={self.nnz}, sparsity={self.sparsity:.3f}, symmetric={self.symmetric}",
414
+ fontsize=12,
415
+ y=1.02,
416
+ )
417
+
418
+ plt.tight_layout()
419
+ return fig, (ax1, ax2)
420
+
421
+ def tree_flatten(self):
422
+ """Flatten for JAX PyTree."""
423
+ children = (self._weights,)
424
+ aux_data = (self._n_nodes, self._region_labels)
425
+ return children, aux_data
426
+
427
+ @classmethod
428
+ def tree_unflatten(cls, aux_data, children):
429
+ """Unflatten from JAX PyTree."""
430
+ obj = object.__new__(cls)
431
+ obj._weights = children[0]
432
+ obj._n_nodes = aux_data[0]
433
+ obj._region_labels = aux_data[1]
434
+ return obj
435
+
436
+ def __repr__(self) -> str:
437
+ """String representation of sparse graph."""
438
+ return (
439
+ f"SparseGraph("
440
+ f"n_nodes={self._n_nodes}, "
441
+ f"nnz={self.nnz}, "
442
+ f"sparsity={self.sparsity:.3f}, "
443
+ f"symmetric={self.symmetric})"
444
+ )
445
+
446
+
447
+ @register_pytree_node_class
448
+ class SparseDelayGraph(SparseGraph):
449
+ """Sparse graph with transmission delays.
450
+
451
+ Both weights and delays are stored as sparse BCOO matrices with the same
452
+ sparsity pattern. Where weight is zero (no connection), delay is undefined.
453
+
454
+ Args:
455
+ weights: Sparse weights (BCOO) or dense array
456
+ delays: Sparse delays (BCOO) or dense array (same pattern as weights)
457
+ region_labels: Optional sequence of region labels (list, tuple, or array). If None, defaults to ['Region_0', 'Region_1', ...]
458
+ threshold: Sparsity threshold for weights
459
+
460
+ Example:
461
+ >>> # From dense
462
+ >>> weights = jnp.array([[0, 0.5, 0], [0.3, 0, 0], [0, 0.2, 0]])
463
+ >>> delays = jnp.array([[0, 10.0, 0], [5.0, 0, 0], [0, 15.0, 0]])
464
+ >>> graph = SparseDelayGraph(weights, delays)
465
+ >>>
466
+ >>> # From dense delay graph
467
+ >>> from network_dynamics.graph.base import DenseDelayGraph
468
+ >>> dense_graph = DenseDelayGraph(weights, delays)
469
+ >>> sparse_graph = SparseDelayGraph.from_dense(dense_graph, threshold=1e-10)
470
+ """
471
+
472
+ def __init__(
473
+ self,
474
+ weights: Union[BCOO, jnp.ndarray],
475
+ delays: Union[BCOO, jnp.ndarray],
476
+ region_labels: Optional[Sequence[str]] = None,
477
+ threshold: float = 0.0,
478
+ ):
479
+ """Initialize sparse delay graph."""
480
+ # Initialize weights via parent
481
+ super().__init__(weights, region_labels=region_labels, threshold=threshold)
482
+
483
+ # Handle delays
484
+ if isinstance(delays, BCOO):
485
+ self._delays = delays
486
+ else:
487
+ # Convert delays to sparse with same pattern as weights
488
+ delays_arr = jnp.asarray(delays)
489
+
490
+ # Get weight pattern (where weights are non-zero)
491
+ weights_dense = self._weights.todense()
492
+ weights_mask = jnp.abs(weights_dense) > 0.0
493
+
494
+ # Apply mask to delays (delays only where weights exist)
495
+ delays_masked = jnp.where(weights_mask, delays_arr, 0.0)
496
+ self._delays = BCOO.fromdense(delays_masked)
497
+
498
+ # Verify same shape
499
+ if self._delays.shape != self._weights.shape:
500
+ raise ValueError(
501
+ f"Delays shape {self._delays.shape} doesn't match "
502
+ f"weights shape {self._weights.shape}"
503
+ )
504
+
505
+ # Ideally same sparsity pattern, but we'll allow some flexibility
506
+ if self._delays.nse != self._weights.nse:
507
+ print(
508
+ f"Warning: delays ({self._delays.nse} nnz) and "
509
+ f"weights ({self._weights.nse} nnz) have different sparsity patterns. "
510
+ f"This may indicate an issue."
511
+ )
512
+
513
+ # Compute max delay from sparse data (keep as array for JAX tracing)
514
+ self._max_delay = (
515
+ jnp.max(self._delays.data) if self._delays.nse > 0 else jnp.array(0.0)
516
+ )
517
+
518
+ @classmethod
519
+ def from_dense(cls, graph: "AbstractGraph", threshold: float = 1e-10):
520
+ """Convert dense delay graph to sparse.
521
+
522
+ Applies the same sparsity pattern to both weights and delays.
523
+
524
+ Args:
525
+ graph: Dense delay graph to convert
526
+ threshold: Values with |weight| < threshold treated as zero
527
+
528
+ Returns:
529
+ SparseDelayGraph with same connectivity pattern for weights and delays
530
+ """
531
+ if not hasattr(graph, "delays"):
532
+ raise ValueError(
533
+ "Graph must have delays attribute to convert to SparseDelayGraph"
534
+ )
535
+
536
+ weights = graph.weights
537
+ delays = graph.delays
538
+
539
+ # Apply threshold to weights to get mask
540
+ weights_mask = jnp.abs(weights) > threshold
541
+
542
+ # Apply mask to both weights and delays
543
+ weights_masked = jnp.where(weights_mask, weights, 0.0)
544
+ delays_masked = jnp.where(weights_mask, delays, 0.0)
545
+
546
+ return cls(weights_masked, delays_masked, threshold=0.0)
547
+
548
+ @property
549
+ def delays(self) -> BCOO:
550
+ """Sparse delay matrix in BCOO format (same pattern as weights)."""
551
+ return self._delays
552
+
553
+ @property
554
+ def max_delay(self) -> float:
555
+ """Maximum delay across all connections."""
556
+ return self._max_delay
557
+
558
+ def verify(self, verbose: bool = True) -> bool:
559
+ """Verify graph structure and delays.
560
+
561
+ Args:
562
+ verbose: Whether to print verification details
563
+
564
+ Returns:
565
+ True if verification passes, False otherwise
566
+ """
567
+ # Check weights via parent
568
+ if not super().verify(verbose=False):
569
+ return False
570
+
571
+ # Check delays for NaN/Inf
572
+ if jnp.any(jnp.isnan(self._delays.data)):
573
+ if verbose:
574
+ print("ERROR: NaN values in sparse delays")
575
+ return False
576
+
577
+ if jnp.any(jnp.isinf(self._delays.data)):
578
+ if verbose:
579
+ print("ERROR: Inf values in sparse delays")
580
+ return False
581
+
582
+ # Check for negative delays
583
+ if jnp.any(self._delays.data < 0):
584
+ if verbose:
585
+ print("ERROR: Negative delays found")
586
+ return False
587
+
588
+ if verbose:
589
+ density_pct = self.sparsity * 100
590
+ print("SparseDelayGraph verification passed:")
591
+ print(f" Nodes: {self._n_nodes}")
592
+ print(f" Non-zeros: {self.nnz}")
593
+ print(f" Density: {density_pct:.3f}%")
594
+ print(f" Max delay: {self._max_delay:.3f}")
595
+ print(f" Symmetric: {self.symmetric}")
596
+
597
+ return True
598
+
599
+ @classmethod
600
+ def random(
601
+ cls,
602
+ n_nodes: int,
603
+ sparsity: float = 0.7,
604
+ symmetric: bool = True,
605
+ weight_dist: str = "lognormal",
606
+ max_delay: float = 50.0,
607
+ delay_dist: str = "uniform",
608
+ allow_self_loops: bool = False,
609
+ key: Optional[jax.random.PRNGKey] = None,
610
+ ) -> "SparseDelayGraph":
611
+ """Create a random sparse delay graph with brain-like connectivity.
612
+
613
+ Args:
614
+ n_nodes: Number of nodes in the network
615
+ sparsity: Fraction of connections present (0.7 = 70% dense)
616
+ symmetric: Whether to create undirected (symmetric) connectivity
617
+ weight_dist: Weight distribution ('lognormal', 'uniform', or 'binary')
618
+ max_delay: Maximum transmission delay
619
+ delay_dist: Delay distribution ('uniform' or 'constant')
620
+ allow_self_loops: Whether to allow self-connections (diagonal)
621
+ key: JAX random key (if None, creates one with seed 0)
622
+
623
+ Returns:
624
+ SparseDelayGraph with random connectivity and delays
625
+
626
+ Example:
627
+ >>> import jax
628
+ >>> key = jax.random.key(42)
629
+ >>> graph = SparseDelayGraph.random(n_nodes=100, sparsity=0.3, max_delay=20.0, key=key)
630
+ """
631
+ if key is None:
632
+ key = jax.random.key(0)
633
+
634
+ # Split keys for edge sampling, weights, and delays
635
+ key_edges, key_weights, key_delays = jax.random.split(key, 3)
636
+
637
+ # Calculate expected number of edges
638
+ max_edges = (
639
+ n_nodes * (n_nodes - 1) if not allow_self_loops else n_nodes * n_nodes
640
+ )
641
+ if symmetric:
642
+ max_edges = max_edges // 2 # Only upper triangle
643
+
644
+ n_edges = int(sparsity * max_edges)
645
+
646
+ if symmetric:
647
+ # Sample edges from upper triangle only
648
+ key_row, key_col = jax.random.split(key_edges)
649
+
650
+ # Sample random upper triangular edges
651
+ row = jax.random.randint(key_row, (n_edges,), 0, n_nodes)
652
+ col = jax.random.randint(key_col, (n_edges,), 0, n_nodes)
653
+
654
+ # Ensure upper triangle (swap if needed) and no self-loops if required
655
+ needs_swap = row > col
656
+ row, col = jnp.where(needs_swap, col, row), jnp.where(needs_swap, row, col)
657
+
658
+ if not allow_self_loops:
659
+ # Filter out diagonal entries
660
+ valid = row != col
661
+ row, col = row[valid], col[valid]
662
+ # Resample to get back to desired edge count (approximate)
663
+ actual_n = len(row)
664
+ if actual_n < n_edges:
665
+ # Add more edges to compensate
666
+ key_extra = jax.random.fold_in(key_edges, 1)
667
+ extra_needed = n_edges - actual_n
668
+ key_row2, key_col2 = jax.random.split(key_extra)
669
+ extra_row = jax.random.randint(
670
+ key_row2, (extra_needed,), 0, n_nodes
671
+ )
672
+ extra_col = jax.random.randint(
673
+ key_col2, (extra_needed,), 0, n_nodes
674
+ )
675
+ needs_swap2 = extra_row >= extra_col
676
+ extra_row = jnp.where(needs_swap2, extra_row + 1, extra_row)
677
+ extra_row = jnp.clip(extra_row, 0, n_nodes - 1)
678
+ row = jnp.concatenate([row, extra_row])
679
+ col = jnp.concatenate([col, extra_col])
680
+
681
+ # Generate weights for upper triangle edges
682
+ if weight_dist == "lognormal":
683
+ edge_weights = jax.random.lognormal(key_weights, shape=(len(row),))
684
+ elif weight_dist == "uniform":
685
+ edge_weights = jax.random.uniform(key_weights, shape=(len(row),))
686
+ elif weight_dist == "binary":
687
+ edge_weights = jnp.ones(len(row))
688
+ else:
689
+ raise ValueError(f"Unknown weight_dist: {weight_dist}")
690
+
691
+ # Generate delays for upper triangle edges
692
+ if delay_dist == "uniform":
693
+ edge_delays = jax.random.uniform(
694
+ key_delays, shape=(len(row),), minval=0.0, maxval=max_delay
695
+ )
696
+ elif delay_dist == "constant":
697
+ edge_delays = jnp.full((len(row),), max_delay)
698
+ else:
699
+ raise ValueError(f"Unknown delay_dist: {delay_dist}")
700
+
701
+ # Create symmetric edges by duplicating (i,j) -> (j,i)
702
+ row_sym = jnp.concatenate([row, col])
703
+ col_sym = jnp.concatenate([col, row])
704
+ weights_sym = jnp.concatenate([edge_weights, edge_weights])
705
+ delays_sym = jnp.concatenate([edge_delays, edge_delays])
706
+
707
+ # Create sparse matrices from COO
708
+ indices = jnp.stack([row_sym, col_sym], axis=1)
709
+ weights_bcoo = BCOO((weights_sym, indices), shape=(n_nodes, n_nodes))
710
+ delays_bcoo = BCOO((delays_sym, indices), shape=(n_nodes, n_nodes))
711
+
712
+ else:
713
+ # Non-symmetric: sample random edges
714
+ key_row, key_col = jax.random.split(key_edges)
715
+ row = jax.random.randint(key_row, (n_edges,), 0, n_nodes)
716
+ col = jax.random.randint(key_col, (n_edges,), 0, n_nodes)
717
+
718
+ if not allow_self_loops:
719
+ # Filter and resample diagonal entries
720
+ valid = row != col
721
+ row, col = row[valid], col[valid]
722
+
723
+ # Generate weights
724
+ if weight_dist == "lognormal":
725
+ edge_weights = jax.random.lognormal(key_weights, shape=(len(row),))
726
+ elif weight_dist == "uniform":
727
+ edge_weights = jax.random.uniform(key_weights, shape=(len(row),))
728
+ elif weight_dist == "binary":
729
+ edge_weights = jnp.ones(len(row))
730
+ else:
731
+ raise ValueError(f"Unknown weight_dist: {weight_dist}")
732
+
733
+ # Generate delays
734
+ if delay_dist == "uniform":
735
+ edge_delays = jax.random.uniform(
736
+ key_delays, shape=(len(row),), minval=0.0, maxval=max_delay
737
+ )
738
+ elif delay_dist == "constant":
739
+ edge_delays = jnp.full((len(row),), max_delay)
740
+ else:
741
+ raise ValueError(f"Unknown delay_dist: {delay_dist}")
742
+
743
+ # Create sparse matrices from COO
744
+ indices = jnp.stack([row, col], axis=1)
745
+ weights_bcoo = BCOO((edge_weights, indices), shape=(n_nodes, n_nodes))
746
+ delays_bcoo = BCOO((edge_delays, indices), shape=(n_nodes, n_nodes))
747
+
748
+ return cls(weights_bcoo, delays_bcoo, threshold=0.0)
749
+
750
+ def plot(self, log_scale_weights: bool = False, figsize: tuple = (12, 10)):
751
+ """Plot sparse connectivity matrix, delays, and their distributions.
752
+
753
+ Args:
754
+ log_scale_weights: If True, log-transform weights before plotting (helps reveal structure)
755
+ figsize: Figure size (width, height)
756
+
757
+ Returns:
758
+ fig, axes: Matplotlib figure and axes (2x2 grid)
759
+
760
+ Note:
761
+ Converts sparse matrices to dense for visualization. Zeros are shown as white (background).
762
+ """
763
+ try:
764
+ import matplotlib.pyplot as plt
765
+ except ImportError:
766
+ raise ImportError(
767
+ "matplotlib is required for plotting. Install with: pip install matplotlib"
768
+ )
769
+
770
+ # Convert to dense for plotting
771
+ weights_dense = self.todense()
772
+ delays_dense = self._delays.todense()
773
+
774
+ # Prepare weights for plotting
775
+ if log_scale_weights:
776
+ weights_plot = jnp.where(
777
+ weights_dense > 0, jnp.log10(weights_dense + 1e-10), jnp.nan
778
+ )
779
+ weight_label = "log10(Weight)"
780
+ else:
781
+ weights_plot = jnp.where(weights_dense > 0, weights_dense, jnp.nan)
782
+ weight_label = "Weight"
783
+
784
+ # Prepare delays for plotting (show as NaN where zero)
785
+ delays_plot = jnp.where(delays_dense > 0, delays_dense, jnp.nan)
786
+
787
+ # Create figure
788
+ fig, axes = plt.subplots(2, 2, figsize=figsize)
789
+
790
+ # Create custom colormap with white for NaN (zeros)
791
+ cmap_weights = plt.cm.cividis.copy()
792
+ cmap_weights.set_bad("white")
793
+ cmap_delays = plt.cm.cividis_r.copy()
794
+ cmap_delays.set_bad("white")
795
+
796
+ # Plot connectivity matrix
797
+ im1 = axes[0, 0].imshow(weights_plot, cmap=cmap_weights, aspect="auto")
798
+ axes[0, 0].set_title("Connectivity Matrix")
799
+ axes[0, 0].set_xlabel("Target Node")
800
+ axes[0, 0].set_ylabel("Source Node")
801
+ plt.colorbar(im1, ax=axes[0, 0], label=weight_label)
802
+
803
+ # Plot weight distribution
804
+ weights_nonzero = weights_dense[weights_dense > 0]
805
+ if len(weights_nonzero) > 0:
806
+ if log_scale_weights:
807
+ weights_nonzero = jnp.log10(weights_nonzero + 1e-10)
808
+ axes[0, 1].hist(weights_nonzero, bins=50, edgecolor="black", alpha=0.7)
809
+ axes[0, 1].set_xlabel(weight_label)
810
+ axes[0, 1].set_ylabel("Count")
811
+ axes[0, 1].set_title("Weight Distribution")
812
+ axes[0, 1].set_yscale("log")
813
+ else:
814
+ axes[0, 1].text(
815
+ 0.5,
816
+ 0.5,
817
+ "No connections",
818
+ ha="center",
819
+ va="center",
820
+ transform=axes[0, 1].transAxes,
821
+ )
822
+ axes[0, 1].set_title("Weight Distribution")
823
+
824
+ # Plot delay matrix
825
+ im2 = axes[1, 0].imshow(delays_plot, cmap=cmap_delays, aspect="auto")
826
+ axes[1, 0].set_title("Transmission Delays")
827
+ axes[1, 0].set_xlabel("Target Node")
828
+ axes[1, 0].set_ylabel("Source Node")
829
+ plt.colorbar(im2, ax=axes[1, 0], label="Delay")
830
+
831
+ # Plot delay distribution
832
+ delays_nonzero = delays_dense[delays_dense > 0]
833
+ if len(delays_nonzero) > 0:
834
+ axes[1, 1].hist(delays_nonzero, bins=50, edgecolor="black", alpha=0.7)
835
+ axes[1, 1].set_xlabel("Delay")
836
+ axes[1, 1].set_ylabel("Count")
837
+ axes[1, 1].set_title("Delay Distribution")
838
+ axes[1, 1].set_yscale("log")
839
+ else:
840
+ axes[1, 1].text(
841
+ 0.5,
842
+ 0.5,
843
+ "No delays",
844
+ ha="center",
845
+ va="center",
846
+ transform=axes[1, 1].transAxes,
847
+ )
848
+ axes[1, 1].set_title("Delay Distribution")
849
+
850
+ # Main title with graph properties
851
+ fig.suptitle(
852
+ f"{self.__class__.__name__}: {self.n_nodes} nodes, nnz={self.nnz}, sparsity={self.sparsity:.3f}, max_delay={self._max_delay:.2f}",
853
+ fontsize=12,
854
+ y=0.995,
855
+ )
856
+
857
+ plt.tight_layout()
858
+ return fig, axes
859
+
860
+ def tree_flatten(self):
861
+ """Flatten for JAX PyTree."""
862
+ children = (self._weights, self._delays)
863
+ aux_data = (self._n_nodes, self._region_labels, self._max_delay)
864
+ return children, aux_data
865
+
866
+ @classmethod
867
+ def tree_unflatten(cls, aux_data, children):
868
+ """Unflatten from JAX PyTree."""
869
+ obj = object.__new__(cls)
870
+ obj._weights = children[0]
871
+ obj._delays = children[1]
872
+ obj._n_nodes = aux_data[0]
873
+ obj._region_labels = aux_data[1]
874
+ obj._max_delay = aux_data[2]
875
+ return obj
876
+
877
+ def __repr__(self) -> str:
878
+ """String representation of sparse delay graph."""
879
+ return (
880
+ f"SparseDelayGraph("
881
+ f"n_nodes={self._n_nodes}, "
882
+ f"nnz={self.nnz}, "
883
+ f"sparsity={self.sparsity:.3f}, "
884
+ f"max_delay={self._max_delay:.3f})"
885
+ )