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,706 @@
1
+ """Abstract base class for network topology representations."""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import Optional, Sequence
5
+
6
+ import jax
7
+ import jax.numpy as jnp
8
+ from jax.tree_util import register_pytree_node_class
9
+
10
+
11
+ class AbstractGraph(ABC):
12
+ """Abstract base class for network topology representations.
13
+
14
+ Defines the interface for network topology that can be used with dynamics.
15
+ All graph types (dense, sparse, multilayer, etc.) should inherit from this class.
16
+
17
+ Note: Subclasses should store immutable properties (n_nodes, sparsity, symmetric)
18
+ as private fields computed during initialization to avoid issues during pytree
19
+ transformations where weights might not be available.
20
+ """
21
+
22
+ @property
23
+ @abstractmethod
24
+ def n_nodes(self) -> int:
25
+ """Number of nodes in the network.
26
+
27
+ This should return a stored value (_n_nodes), not computed from weights.
28
+ """
29
+ pass
30
+
31
+ @property
32
+ @abstractmethod
33
+ def region_labels(self) -> Sequence[str]:
34
+ """Labels for each node/region in the network.
35
+
36
+ This should return a stored sequence of labels (_region_labels).
37
+ If not provided during initialization, defaults to ['Region_0', 'Region_1', ...].
38
+ """
39
+ pass
40
+
41
+ @property
42
+ @abstractmethod
43
+ def weights(self) -> jnp.ndarray:
44
+ """Weight matrix [n_nodes, n_nodes].
45
+
46
+ Returns the connectivity matrix that can be used directly with
47
+ JAX operations like jnp.matmul() or @. Works for both dense
48
+ and sparse representations.
49
+ """
50
+ pass
51
+
52
+ @abstractmethod
53
+ def verify(self, verbose: bool = True) -> bool:
54
+ """Verify graph structure and properties.
55
+
56
+ Args:
57
+ verbose: Whether to print verification details
58
+
59
+ Returns:
60
+ True if verification passes, False otherwise
61
+ """
62
+ pass
63
+
64
+ @property
65
+ @abstractmethod
66
+ def symmetric(self) -> bool:
67
+ """Check if the graph is symmetric (undirected).
68
+
69
+ This should return a stored value (_symmetric), not computed from weights.
70
+ """
71
+ pass
72
+
73
+ @property
74
+ @abstractmethod
75
+ def sparsity(self) -> float:
76
+ """Calculate the sparsity of the graph (fraction of non-zero connections).
77
+
78
+ This should return a stored value (_sparsity), not computed from weights.
79
+ """
80
+ pass
81
+
82
+ def __repr__(self) -> str:
83
+ """String representation of the graph."""
84
+ return (
85
+ f"{self.__class__.__name__}("
86
+ f"n_nodes={self.n_nodes}, "
87
+ f"sparsity={self.sparsity:.3f}, "
88
+ f"symmetric={self.symmetric})"
89
+ )
90
+
91
+
92
+ @register_pytree_node_class
93
+ class DenseGraph(AbstractGraph):
94
+ """Dense graph representation.
95
+
96
+ Standard dense matrix representation of network topology.
97
+ Suitable for most brain networks which are typically 50-90% dense.
98
+
99
+ Args:
100
+ weights: Weight matrix [n_nodes, n_nodes]
101
+ region_labels: Optional sequence of region labels (list, tuple, or array). If None, defaults to ['Region_0', 'Region_1', ...]
102
+ symmetric: Whether to treat as symmetric (None = auto-detect)
103
+ """
104
+
105
+ def __init__(
106
+ self,
107
+ weights: jnp.ndarray,
108
+ region_labels: Optional[Sequence[str]] = None,
109
+ symmetric: Optional[bool] = None,
110
+ ):
111
+ # Convert to JAX array if needed
112
+ self._weights = jnp.asarray(weights)
113
+
114
+ # Validate basic shape requirements
115
+ if self._weights.ndim != 2:
116
+ raise ValueError(f"Weight matrix must be 2D, got {self._weights.ndim}D")
117
+
118
+ if self._weights.shape[0] != self._weights.shape[1]:
119
+ raise ValueError(
120
+ f"Weight matrix must be square, got shape {self._weights.shape}"
121
+ )
122
+
123
+ # Store n_nodes to avoid accessing weights.shape during pytree transformations
124
+ self._n_nodes = self._weights.shape[0]
125
+
126
+ # Store region labels (auto-generate if not provided)
127
+ if region_labels is None:
128
+ self._region_labels = [f"Region_{i}" for i in range(self._n_nodes)]
129
+ else:
130
+ if len(region_labels) != self._n_nodes:
131
+ raise ValueError(
132
+ f"Number of region labels ({len(region_labels)}) must match "
133
+ f"number of nodes ({self._n_nodes})"
134
+ )
135
+ self._region_labels = list(region_labels) # Ensure it's a list
136
+
137
+ # Compute and store symmetric property
138
+ if symmetric is None:
139
+ # Auto-detect symmetry
140
+ self._symmetric = bool(jnp.allclose(self._weights, self._weights.T))
141
+ else:
142
+ self._symmetric = symmetric
143
+
144
+ # Compute and store sparsity
145
+ if self._n_nodes <= 1:
146
+ self._sparsity = 0.0
147
+ else:
148
+ total_possible = self._n_nodes * (self._n_nodes - 1) # Exclude diagonal
149
+ non_zero = jnp.count_nonzero(
150
+ self._weights - jnp.diag(jnp.diag(self._weights))
151
+ )
152
+ self._sparsity = float(non_zero) / total_possible
153
+
154
+ # Run verification
155
+ if not self.verify(verbose=False):
156
+ raise ValueError("Graph verification failed")
157
+
158
+ @property
159
+ def weights(self) -> jnp.ndarray:
160
+ """Weight matrix [n_nodes, n_nodes]."""
161
+ return self._weights
162
+
163
+ @property
164
+ def n_nodes(self) -> int:
165
+ """Number of nodes in the network."""
166
+ return self._n_nodes
167
+
168
+ @property
169
+ def region_labels(self) -> Sequence[str]:
170
+ """Labels for each node/region in the network."""
171
+ return self._region_labels
172
+
173
+ @property
174
+ def symmetric(self) -> bool:
175
+ """Check if the graph is symmetric (undirected)."""
176
+ return self._symmetric
177
+
178
+ @property
179
+ def sparsity(self) -> float:
180
+ """Calculate the sparsity of the graph (fraction of non-zero connections)."""
181
+ return self._sparsity
182
+
183
+ def verify(self, verbose: bool = True) -> bool:
184
+ """Verify graph structure and properties.
185
+
186
+ Checks:
187
+ - Finite values in weight matrix
188
+ - Consistent shape
189
+ - Symmetric flag consistency (if provided)
190
+
191
+ Args:
192
+ verbose: Whether to print verification details
193
+
194
+ Returns:
195
+ True if verification passes, False otherwise
196
+ """
197
+ try:
198
+ if verbose:
199
+ print(f"Verifying {self.__class__.__name__}:")
200
+ print(f" Shape: {self.weights.shape}")
201
+ print(f" Nodes: {self.n_nodes}")
202
+ print(f" Sparsity: {self.sparsity:.3f}")
203
+
204
+ # Check for finite values
205
+ if not jnp.all(jnp.isfinite(self.weights)):
206
+ if verbose:
207
+ print(" L ERROR: Weight matrix contains non-finite values")
208
+ return False
209
+
210
+ # Verify symmetric flag consistency with actual weights
211
+ actual_symmetric = bool(jnp.allclose(self.weights, self.weights.T))
212
+ if self._symmetric != actual_symmetric:
213
+ if verbose:
214
+ print(
215
+ f" L ERROR: Stored symmetric flag ({self._symmetric}) doesn't match actual symmetry ({actual_symmetric})"
216
+ )
217
+ return False
218
+
219
+ if verbose:
220
+ print(f" Symmetric: {self.symmetric}")
221
+ print("  Verification passed!")
222
+
223
+ return True
224
+
225
+ except Exception as e:
226
+ if verbose:
227
+ print(f" L ERROR: {e}")
228
+ return False
229
+
230
+ @classmethod
231
+ def random(
232
+ cls,
233
+ n_nodes: int,
234
+ sparsity: float = 0.7,
235
+ symmetric: bool = True,
236
+ weight_dist: str = "lognormal",
237
+ allow_self_loops: bool = False,
238
+ key: Optional[jax.random.PRNGKey] = None,
239
+ ) -> "DenseGraph":
240
+ """Create a random graph with brain-like connectivity.
241
+
242
+ Args:
243
+ n_nodes: Number of nodes in the network
244
+ sparsity: Fraction of connections present (0.7 = 70% dense)
245
+ symmetric: Whether to create undirected (symmetric) connectivity
246
+ weight_dist: Weight distribution ('lognormal', 'uniform', or 'binary')
247
+ allow_self_loops: Whether to allow self-connections (diagonal)
248
+ key: JAX random key (if None, creates one with seed 0)
249
+
250
+ Returns:
251
+ DenseGraph with random connectivity
252
+
253
+ Example:
254
+ >>> import jax
255
+ >>> key = jax.random.key(42)
256
+ >>> graph = DenseGraph.random(n_nodes=10, sparsity=0.5, key=key)
257
+ """
258
+ if key is None:
259
+ key = jax.random.key(0)
260
+
261
+ # Split keys for connectivity and weights
262
+ key_conn, key_weights = jax.random.split(key)
263
+
264
+ # Generate connectivity mask (Erdős-Rényi)
265
+ conn_prob = jax.random.uniform(key_conn, shape=(n_nodes, n_nodes))
266
+ mask = conn_prob < sparsity
267
+
268
+ # Remove self-loops if needed
269
+ if not allow_self_loops:
270
+ mask = mask.at[jnp.arange(n_nodes), jnp.arange(n_nodes)].set(False)
271
+
272
+ # Make symmetric if needed
273
+ if symmetric:
274
+ # Use upper triangle and mirror
275
+ mask = jnp.triu(mask, k=1)
276
+ mask = mask | mask.T
277
+
278
+ # Generate weights based on distribution
279
+ if weight_dist == "lognormal":
280
+ # Log-normal: mean=0, std=1 in log-space
281
+ weights = jax.random.lognormal(key_weights, shape=(n_nodes, n_nodes))
282
+ elif weight_dist == "uniform":
283
+ weights = jax.random.uniform(key_weights, shape=(n_nodes, n_nodes))
284
+ elif weight_dist == "binary":
285
+ weights = jnp.ones((n_nodes, n_nodes))
286
+ else:
287
+ raise ValueError(
288
+ f"Unknown weight_dist: {weight_dist}. Use 'lognormal', 'uniform', or 'binary'"
289
+ )
290
+
291
+ # Make weights symmetric if needed
292
+ if symmetric:
293
+ weights = jnp.triu(weights, k=1)
294
+ weights = weights + weights.T
295
+
296
+ # Apply mask
297
+ weights = jnp.where(mask, weights, 0.0)
298
+
299
+ return cls(weights, symmetric=symmetric if symmetric else None)
300
+
301
+ def tree_flatten(self):
302
+ """Flatten Graph for JAX PyTree."""
303
+ children = (self._weights,) # Array data
304
+ aux_data = (
305
+ self._n_nodes,
306
+ self._symmetric,
307
+ self._sparsity,
308
+ self._region_labels,
309
+ ) # Static metadata
310
+ return children, aux_data
311
+
312
+ @classmethod
313
+ def tree_unflatten(cls, aux_data, children):
314
+ """Reconstruct Graph from PyTree data."""
315
+ obj = object.__new__(cls)
316
+ obj._weights = children[0]
317
+ obj._n_nodes = aux_data[0]
318
+ obj._symmetric = aux_data[1]
319
+ obj._sparsity = aux_data[2]
320
+ obj._region_labels = aux_data[3]
321
+ return obj
322
+
323
+ def plot(self, log_scale_weights: bool = False, figsize: tuple = (12, 5)):
324
+ """Plot connectivity matrix and weight distribution.
325
+
326
+ Args:
327
+ log_scale_weights: If True, log-transform weights before plotting (helps reveal structure)
328
+ figsize: Figure size (width, height)
329
+
330
+ Returns:
331
+ fig, axes: Matplotlib figure and axes
332
+ """
333
+ try:
334
+ import matplotlib.pyplot as plt
335
+ except ImportError:
336
+ raise ImportError(
337
+ "matplotlib is required for plotting. Install with: pip install matplotlib"
338
+ )
339
+
340
+ # Prepare weights for plotting
341
+ weights_plot = jnp.array(self.weights)
342
+ if log_scale_weights:
343
+ # Log transform, handling zeros
344
+ weights_plot = jnp.where(
345
+ weights_plot > 0, jnp.log10(weights_plot + 1e-10), 0.0
346
+ )
347
+ weight_label = "log10(Weight)"
348
+ else:
349
+ weight_label = "Weight"
350
+
351
+ # Create figure
352
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize)
353
+
354
+ # Plot connectivity matrix
355
+ im1 = ax1.imshow(weights_plot, cmap="cividis", aspect="auto")
356
+ ax1.set_title("Connectivity Matrix")
357
+ ax1.set_xlabel("Target Node")
358
+ ax1.set_ylabel("Source Node")
359
+ plt.colorbar(im1, ax=ax1, label=weight_label)
360
+
361
+ # Plot weight distribution
362
+ weights_nonzero = self.weights[self.weights > 0]
363
+ if len(weights_nonzero) > 0:
364
+ if log_scale_weights:
365
+ weights_nonzero = jnp.log10(weights_nonzero + 1e-10)
366
+ ax2.hist(weights_nonzero, bins=50, edgecolor="black", alpha=0.7)
367
+ ax2.set_xlabel(weight_label)
368
+ ax2.set_ylabel("Count")
369
+ ax2.set_title("Weight Distribution")
370
+ ax2.set_yscale("log")
371
+ else:
372
+ ax2.text(
373
+ 0.5,
374
+ 0.5,
375
+ "No connections",
376
+ ha="center",
377
+ va="center",
378
+ transform=ax2.transAxes,
379
+ )
380
+ ax2.set_title("Weight Distribution")
381
+
382
+ # Main title with graph properties
383
+ fig.suptitle(
384
+ f"{self.__class__.__name__}: {self.n_nodes} nodes, sparsity={self.sparsity:.3f}, symmetric={self.symmetric}",
385
+ fontsize=12,
386
+ y=1.02,
387
+ )
388
+
389
+ plt.tight_layout()
390
+ return fig, (ax1, ax2)
391
+
392
+
393
+ @register_pytree_node_class
394
+ class DenseDelayGraph(DenseGraph):
395
+ """Dense graph with transmission delays.
396
+
397
+ Extends DenseGraph with a delay matrix for modeling transmission delays
398
+ between network nodes. Used for delay differential equations (DDEs).
399
+
400
+ Args:
401
+ weights: Weight matrix [n_nodes, n_nodes]
402
+ delays: Delay matrix [n_nodes, n_nodes] in same units as integration time
403
+ region_labels: Optional sequence of region labels (list, tuple, or array). If None, defaults to ['Region_0', 'Region_1', ...]
404
+ symmetric: Whether to treat as symmetric (None = auto-detect)
405
+ """
406
+
407
+ def __init__(
408
+ self,
409
+ weights: jnp.ndarray,
410
+ delays: jnp.ndarray,
411
+ region_labels: Optional[Sequence[str]] = None,
412
+ symmetric: Optional[bool] = None,
413
+ ):
414
+ # Process delays first (needed for verify method)
415
+ self._delays = jnp.asarray(delays)
416
+
417
+ # Validate delay matrix shape before calling parent
418
+ weights_array = jnp.asarray(weights)
419
+ if self._delays.shape != weights_array.shape:
420
+ raise ValueError(
421
+ f"Delay matrix shape {self._delays.shape} must match weight matrix shape {weights_array.shape}"
422
+ )
423
+
424
+ # Compute and store max_delay to avoid accessing delays during pytree transformations
425
+ self._max_delay = float(jnp.max(self._delays))
426
+
427
+ # Initialize parent Graph (pass region_labels)
428
+ super().__init__(weights, region_labels=region_labels, symmetric=symmetric)
429
+
430
+ # Run additional verification
431
+ if not self.verify(verbose=False):
432
+ raise ValueError("DelayGraph verification failed")
433
+
434
+ @property
435
+ def delays(self) -> jnp.ndarray:
436
+ """Delay matrix [n_nodes, n_nodes]."""
437
+ return self._delays
438
+
439
+ @property
440
+ def max_delay(self) -> float:
441
+ """Maximum delay in the network."""
442
+ return self._max_delay
443
+
444
+ def verify(self, verbose: bool = True) -> bool:
445
+ """Verify delay graph structure.
446
+
447
+ Additional checks beyond Graph.verify():
448
+ - Non-negative delays
449
+ - Finite delay values
450
+ - Delay matrix shape consistency
451
+ """
452
+ # First run parent verification
453
+ if not super().verify(verbose):
454
+ return False
455
+
456
+ try:
457
+ if verbose:
458
+ print(f" Delays shape: {self.delays.shape}")
459
+ print(f" Max delay: {self.max_delay}")
460
+
461
+ # Check for non-negative delays
462
+ if jnp.any(self.delays < 0):
463
+ if verbose:
464
+ print(" L ERROR: Delay matrix contains negative values")
465
+ return False
466
+
467
+ # Check for finite delays
468
+ if not jnp.all(jnp.isfinite(self.delays)):
469
+ if verbose:
470
+ print(" L ERROR: Delay matrix contains non-finite values")
471
+ return False
472
+
473
+ if verbose:
474
+ print("  DelayGraph verification passed!")
475
+
476
+ return True
477
+
478
+ except Exception as e:
479
+ if verbose:
480
+ print(f" L ERROR: {e}")
481
+ return False
482
+
483
+ def __repr__(self) -> str:
484
+ """String representation of the delay graph."""
485
+ return (
486
+ f"{self.__class__.__name__}("
487
+ f"n_nodes={self.n_nodes}, "
488
+ f"sparsity={self.sparsity:.3f}, "
489
+ f"symmetric={self.symmetric}, "
490
+ f"max_delay={self.max_delay:.3f})"
491
+ )
492
+
493
+ @classmethod
494
+ def random(
495
+ cls,
496
+ n_nodes: int,
497
+ sparsity: float = 0.7,
498
+ symmetric: bool = True,
499
+ weight_dist: str = "lognormal",
500
+ max_delay: float = 50.0,
501
+ delay_dist: str = "uniform",
502
+ allow_self_loops: bool = False,
503
+ key: Optional[jax.random.PRNGKey] = None,
504
+ ) -> "DenseDelayGraph":
505
+ """Create a random delay graph with brain-like connectivity.
506
+
507
+ Args:
508
+ n_nodes: Number of nodes in the network
509
+ sparsity: Fraction of connections present (0.7 = 70% dense)
510
+ symmetric: Whether to create undirected (symmetric) connectivity
511
+ weight_dist: Weight distribution ('lognormal', 'uniform', or 'binary')
512
+ max_delay: Maximum transmission delay
513
+ delay_dist: Delay distribution ('uniform' or 'constant')
514
+ allow_self_loops: Whether to allow self-connections (diagonal)
515
+ key: JAX random key (if None, creates one with seed 0)
516
+
517
+ Returns:
518
+ DenseDelayGraph with random connectivity and delays
519
+
520
+ Example:
521
+ >>> import jax
522
+ >>> key = jax.random.key(42)
523
+ >>> graph = DenseDelayGraph.random(n_nodes=10, max_delay=20.0, key=key)
524
+ """
525
+ if key is None:
526
+ key = jax.random.key(0)
527
+
528
+ # Split keys for weights and delays
529
+ key_weights, key_delays = jax.random.split(key)
530
+
531
+ # Generate connectivity mask and weights using parent method
532
+ key_conn, key_w = jax.random.split(key_weights)
533
+ conn_prob = jax.random.uniform(key_conn, shape=(n_nodes, n_nodes))
534
+ mask = conn_prob < sparsity
535
+
536
+ # Remove self-loops if needed
537
+ if not allow_self_loops:
538
+ mask = mask.at[jnp.arange(n_nodes), jnp.arange(n_nodes)].set(False)
539
+
540
+ # Make symmetric if needed
541
+ if symmetric:
542
+ mask = jnp.triu(mask, k=1)
543
+ mask = mask | mask.T
544
+
545
+ # Generate weights
546
+ if weight_dist == "lognormal":
547
+ weights = jax.random.lognormal(key_w, shape=(n_nodes, n_nodes))
548
+ elif weight_dist == "uniform":
549
+ weights = jax.random.uniform(key_w, shape=(n_nodes, n_nodes))
550
+ elif weight_dist == "binary":
551
+ weights = jnp.ones((n_nodes, n_nodes))
552
+ else:
553
+ raise ValueError(f"Unknown weight_dist: {weight_dist}")
554
+
555
+ # Make weights symmetric if needed
556
+ if symmetric:
557
+ weights = jnp.triu(weights, k=1)
558
+ weights = weights + weights.T
559
+
560
+ weights = jnp.where(mask, weights, 0.0)
561
+
562
+ # Generate delays with same sparsity pattern
563
+ if delay_dist == "uniform":
564
+ delays = jax.random.uniform(
565
+ key_delays, shape=(n_nodes, n_nodes), minval=0.0, maxval=max_delay
566
+ )
567
+ elif delay_dist == "constant":
568
+ delays = jnp.full((n_nodes, n_nodes), max_delay)
569
+ else:
570
+ raise ValueError(
571
+ f"Unknown delay_dist: {delay_dist}. Use 'uniform' or 'constant'"
572
+ )
573
+
574
+ # Make delays symmetric if needed
575
+ if symmetric:
576
+ delays = jnp.triu(delays, k=1)
577
+ delays = delays + delays.T
578
+
579
+ # Apply same mask to delays
580
+ delays = jnp.where(mask, delays, 0.0)
581
+
582
+ return cls(weights, delays, symmetric=symmetric if symmetric else None)
583
+
584
+ def plot(self, log_scale_weights: bool = False, figsize: tuple = (12, 10)):
585
+ """Plot connectivity matrix, delays, and their distributions.
586
+
587
+ Args:
588
+ log_scale_weights: If True, log-transform weights before plotting (helps reveal structure)
589
+ figsize: Figure size (width, height)
590
+
591
+ Returns:
592
+ fig, axes: Matplotlib figure and axes (2x2 grid)
593
+ """
594
+ try:
595
+ import matplotlib.pyplot as plt
596
+ except ImportError:
597
+ raise ImportError(
598
+ "matplotlib is required for plotting. Install with: pip install matplotlib"
599
+ )
600
+
601
+ # Prepare weights for plotting
602
+ weights_plot = jnp.array(self.weights)
603
+ if log_scale_weights:
604
+ weights_plot = jnp.where(
605
+ weights_plot > 0, jnp.log10(weights_plot + 1e-10), 0.0
606
+ )
607
+ weight_label = "log10(Weight)"
608
+ else:
609
+ weight_label = "Weight"
610
+
611
+ # Create figure
612
+ fig, axes = plt.subplots(2, 2, figsize=figsize)
613
+
614
+ # Plot connectivity matrix
615
+ im1 = axes[0, 0].imshow(weights_plot, cmap="cividis", aspect="auto")
616
+ axes[0, 0].set_title("Connectivity Matrix")
617
+ axes[0, 0].set_xlabel("Target Node")
618
+ axes[0, 0].set_ylabel("Source Node")
619
+ plt.colorbar(im1, ax=axes[0, 0], label=weight_label)
620
+
621
+ # Plot weight distribution
622
+ weights_nonzero = self.weights[self.weights > 0]
623
+ if len(weights_nonzero) > 0:
624
+ if log_scale_weights:
625
+ weights_nonzero = jnp.log10(weights_nonzero + 1e-10)
626
+ axes[0, 1].hist(weights_nonzero, bins=50, edgecolor="black", alpha=0.7)
627
+ axes[0, 1].set_xlabel(weight_label)
628
+ axes[0, 1].set_ylabel("Count")
629
+ axes[0, 1].set_title("Weight Distribution")
630
+ axes[0, 1].set_yscale("log")
631
+ else:
632
+ axes[0, 1].text(
633
+ 0.5,
634
+ 0.5,
635
+ "No connections",
636
+ ha="center",
637
+ va="center",
638
+ transform=axes[0, 1].transAxes,
639
+ )
640
+ axes[0, 1].set_title("Weight Distribution")
641
+
642
+ # Plot delay matrix
643
+ im2 = axes[1, 0].imshow(self.delays, cmap="cividis_r", aspect="auto")
644
+ axes[1, 0].set_title("Transmission Delays")
645
+ axes[1, 0].set_xlabel("Target Node")
646
+ axes[1, 0].set_ylabel("Source Node")
647
+ plt.colorbar(im2, ax=axes[1, 0], label="Delay")
648
+
649
+ # Plot delay distribution
650
+ delays_nonzero = self.delays[self.delays > 0]
651
+ if len(delays_nonzero) > 0:
652
+ axes[1, 1].hist(delays_nonzero, bins=50, edgecolor="black", alpha=0.7)
653
+ axes[1, 1].set_xlabel("Delay")
654
+ axes[1, 1].set_ylabel("Count")
655
+ axes[1, 1].set_title("Delay Distribution")
656
+ axes[1, 1].set_yscale("log")
657
+ else:
658
+ axes[1, 1].text(
659
+ 0.5,
660
+ 0.5,
661
+ "No delays",
662
+ ha="center",
663
+ va="center",
664
+ transform=axes[1, 1].transAxes,
665
+ )
666
+ axes[1, 1].set_title("Delay Distribution")
667
+
668
+ # Main title with graph properties
669
+ fig.suptitle(
670
+ f"{self.__class__.__name__}: {self.n_nodes} nodes, sparsity={self.sparsity:.3f}, symmetric={self.symmetric}, max_delay={self.max_delay:.2f}",
671
+ fontsize=12,
672
+ y=0.995,
673
+ )
674
+
675
+ plt.tight_layout()
676
+ return fig, axes
677
+
678
+ def tree_flatten(self):
679
+ """Flatten DenseDelayGraph for JAX PyTree."""
680
+ children = (self._weights, self._delays) # Array data
681
+ aux_data = (
682
+ self._n_nodes,
683
+ self._symmetric,
684
+ self._sparsity,
685
+ self._max_delay,
686
+ self._region_labels,
687
+ ) # Static metadata
688
+ return children, aux_data
689
+
690
+ @classmethod
691
+ def tree_unflatten(cls, aux_data, children):
692
+ """Reconstruct DenseDelayGraph from PyTree data."""
693
+ obj = object.__new__(cls)
694
+ obj._weights = children[0]
695
+ obj._delays = children[1]
696
+ obj._n_nodes = aux_data[0]
697
+ obj._symmetric = aux_data[1]
698
+ obj._sparsity = aux_data[2]
699
+ obj._max_delay = aux_data[3]
700
+ obj._region_labels = aux_data[4]
701
+ return obj
702
+
703
+
704
+ # Backward compatibility aliases
705
+ Graph = DenseGraph
706
+ DelayGraph = DenseDelayGraph