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,541 @@
1
+ """Abstract base class for neural dynamics models with multi-coupling support.
2
+
3
+ This version extends the original AbstractDynamics with support for multiple
4
+ named coupling inputs, enabling more flexible network architectures.
5
+ """
6
+
7
+ from abc import ABC, abstractmethod
8
+ from typing import Optional, Tuple, Union
9
+
10
+ import jax.numpy as jnp
11
+ from diffrax import Dopri5, ODETerm, SaveAt, diffeqsolve
12
+
13
+ from ..core.bunch import Bunch
14
+
15
+
16
+ class AbstractDynamics(ABC):
17
+ """Abstract base class for neural dynamics models with multi-coupling support.
18
+
19
+ This base class extends the original AbstractDynamics with the ability to declare
20
+ and receive multiple named coupling inputs via Bunch objects, enabling flexible
21
+ network architectures with different coupling mechanisms.
22
+
23
+ Attributes
24
+ ----------
25
+ STATE_NAMES : tuple of str
26
+ Names of integrated state variables
27
+ INITIAL_STATE : tuple of float
28
+ Default initial values for integrated states
29
+ AUXILIARY_NAMES : tuple of str
30
+ Names of auxiliary (non-integrated) variables
31
+ DEFAULT_PARAMS : Bunch
32
+ Default parameter values as Bunch object
33
+ COUPLING_INPUTS : dict
34
+ Dictionary of expected coupling inputs ``{name: n_dims}``
35
+ EXTERNAL_INPUTS : dict
36
+ Dictionary of external input specifications ``{name: n_dims}``
37
+ VARIABLES_OF_INTEREST : tuple
38
+ Variables to record (empty tuple = record all state variables)
39
+ """
40
+
41
+ # Integrated state variables (required)
42
+ STATE_NAMES: Tuple[str, ...] = ()
43
+ INITIAL_STATE: Tuple[float, ...] = ()
44
+
45
+ # Auxiliary variables (optional)
46
+ AUXILIARY_NAMES: Tuple[str, ...] = ()
47
+
48
+ # Parameters
49
+ DEFAULT_PARAMS: Bunch = Bunch()
50
+
51
+ # NEW: Multi-coupling support
52
+ COUPLING_INPUTS: dict = {} # e.g., {'structural': 1, 'modulatory': 1}
53
+
54
+ # External inputs (independent of network coupling)
55
+ EXTERNAL_INPUTS: dict = {} # e.g., {'stimulus': 1, 'perturbation': 2}
56
+
57
+ # Recording configuration
58
+ VARIABLES_OF_INTEREST: Tuple[Union[str, int], ...] = () # Empty = record all
59
+
60
+ def __init__(self, **kwargs):
61
+ """Initialize dynamics with optional parameter and configuration overrides.
62
+
63
+ Parameters
64
+ ----------
65
+ **kwargs : dict
66
+ Parameter overrides for DEFAULT_PARAMS or configuration options such as
67
+ VARIABLES_OF_INTEREST or INITIAL_STATE
68
+ """
69
+ # Handle special configuration parameters
70
+ if "VARIABLES_OF_INTEREST" in kwargs:
71
+ self.VARIABLES_OF_INTEREST = kwargs.pop("VARIABLES_OF_INTEREST")
72
+ # Validate variables of interest
73
+ try:
74
+ self.get_variables_of_interest_indices()
75
+ except ValueError as e:
76
+ raise ValueError(f"Invalid VARIABLES_OF_INTEREST: {e}")
77
+
78
+ # Handle INITIAL_STATE override
79
+ if "INITIAL_STATE" in kwargs:
80
+ initial_state = kwargs.pop("INITIAL_STATE")
81
+ # Convert to tuple if needed
82
+ if isinstance(initial_state, (int, float)):
83
+ initial_state = (initial_state,)
84
+ elif not isinstance(initial_state, tuple):
85
+ initial_state = tuple(initial_state)
86
+
87
+ # Validate length matches STATE_NAMES
88
+ if len(initial_state) != len(self.STATE_NAMES):
89
+ raise ValueError(
90
+ f"INITIAL_STATE length ({len(initial_state)}) must match "
91
+ f"STATE_NAMES length ({len(self.STATE_NAMES)})"
92
+ )
93
+ self.INITIAL_STATE = initial_state
94
+
95
+ # Create instance parameters by copying defaults and updating with kwargs
96
+ self.params = self.DEFAULT_PARAMS.copy()
97
+ for key, value in kwargs.items():
98
+ if key not in self.DEFAULT_PARAMS:
99
+ raise ValueError(
100
+ f"Unknown parameter '{key}' for {self.__class__.__name__}. "
101
+ f"Available parameters: {list(self.DEFAULT_PARAMS.keys())}"
102
+ )
103
+ self.params[key] = value
104
+
105
+ def __init_subclass__(cls, **kwargs):
106
+ """Validate class attributes when subclassing."""
107
+ super().__init_subclass__(**kwargs)
108
+
109
+ # Skip validation for AbstractDynamics itself
110
+ if cls.__name__ == "AbstractDynamics":
111
+ return
112
+
113
+ # Inherit attributes from parent if not explicitly defined
114
+ if hasattr(cls, "__bases__") and len(cls.__bases__) > 0:
115
+ parent = cls.__bases__[0]
116
+ if issubclass(parent, AbstractDynamics) and parent != AbstractDynamics:
117
+ # Inherit attributes that weren't redefined
118
+ if not cls.STATE_NAMES:
119
+ cls.STATE_NAMES = parent.STATE_NAMES
120
+ if not cls.INITIAL_STATE:
121
+ cls.INITIAL_STATE = parent.INITIAL_STATE
122
+ if not cls.AUXILIARY_NAMES and hasattr(parent, "AUXILIARY_NAMES"):
123
+ cls.AUXILIARY_NAMES = parent.AUXILIARY_NAMES
124
+ if not cls.COUPLING_INPUTS and hasattr(parent, "COUPLING_INPUTS"):
125
+ cls.COUPLING_INPUTS = parent.COUPLING_INPUTS
126
+ if not cls.VARIABLES_OF_INTEREST and hasattr(
127
+ parent, "VARIABLES_OF_INTEREST"
128
+ ):
129
+ cls.VARIABLES_OF_INTEREST = parent.VARIABLES_OF_INTEREST
130
+
131
+ # Merge DEFAULT_PARAMS
132
+ if hasattr(parent, "DEFAULT_PARAMS"):
133
+ merged_params = parent.DEFAULT_PARAMS.copy()
134
+ merged_params.update(cls.DEFAULT_PARAMS)
135
+ cls.DEFAULT_PARAMS = merged_params
136
+
137
+ # Validate consistency of attributes
138
+ if len(cls.STATE_NAMES) != len(cls.INITIAL_STATE):
139
+ raise ValueError(f"{cls.__name__}: len(STATE_NAMES) != len(INITIAL_STATE)")
140
+
141
+ @property
142
+ def all_variable_names(self) -> Tuple[str, ...]:
143
+ """All variable names (integrated + auxiliary)."""
144
+ return self.STATE_NAMES + self.AUXILIARY_NAMES
145
+
146
+ @property
147
+ def N_STATES(self) -> int:
148
+ """Total number of variables (integrated + auxiliary)."""
149
+ return len(self.STATE_NAMES)
150
+
151
+ @property
152
+ def N_AUXILIARIES(self) -> int:
153
+ """Total number of variables (integrated + auxiliary)."""
154
+ return len(self.AUXILIARY_NAMES)
155
+
156
+ @property
157
+ def n_variables(self) -> int:
158
+ """Total number of variables (integrated + auxiliary)."""
159
+ return self.N_STATES + self.N_AUXILIARIES
160
+
161
+ @property
162
+ def has_auxiliaries(self) -> bool:
163
+ """Whether this dynamics has auxiliary variables."""
164
+ return self.N_AUXILIARIES > 0
165
+
166
+ def get_default_initial_state(self, n_nodes: int = 1) -> jnp.ndarray:
167
+ """Get default initial state array.
168
+
169
+ Args:
170
+ n_nodes: Number of network nodes
171
+
172
+ Returns:
173
+ Initial state array of shape [N_STATES, n_nodes]
174
+ """
175
+ initial = jnp.array(self.INITIAL_STATE)
176
+ if n_nodes == 1:
177
+ return initial[:, None]
178
+ else:
179
+ return jnp.broadcast_to(initial[:, None], (self.N_STATES, n_nodes))
180
+
181
+ def get_variables_of_interest_indices(self) -> Tuple[int, ...]:
182
+ """Get indices of variables to record.
183
+
184
+ Returns:
185
+ Tuple of indices into all_variable_names. If VARIABLES_OF_INTEREST is empty,
186
+ returns only state variable indices (default behavior).
187
+ """
188
+ if not self.VARIABLES_OF_INTEREST:
189
+ # Default: record only state variables (not auxiliaries)
190
+ return tuple(range(self.N_STATES))
191
+
192
+ indices = []
193
+ for var in self.VARIABLES_OF_INTEREST:
194
+ if isinstance(var, int):
195
+ if 0 <= var < self.n_variables:
196
+ indices.append(var)
197
+ else:
198
+ raise ValueError(
199
+ f"Variable index {var} out of range [0, {self.n_variables})"
200
+ )
201
+ elif isinstance(var, str):
202
+ if var in self.all_variable_names:
203
+ indices.append(self.all_variable_names.index(var))
204
+ else:
205
+ raise ValueError(
206
+ f"Variable name '{var}' not found in {self.all_variable_names}"
207
+ )
208
+ else:
209
+ raise ValueError(
210
+ f"Variable of interest must be int or str, got {type(var)}"
211
+ )
212
+
213
+ return tuple(indices)
214
+
215
+ def name_to_index(self, names: Union[str, Tuple[str, ...], list]) -> jnp.ndarray:
216
+ """Convert state names to indices.
217
+
218
+ Args:
219
+ names: Single state name, tuple/list of state names, or empty list
220
+
221
+ Returns:
222
+ Array of indices corresponding to the state names
223
+
224
+ Examples:
225
+ For Lorenz with STATE_NAMES = ("x", "y", "z"):
226
+ name_to_index("x") -> jnp.array([0])
227
+ name_to_index(["y", "x"]) -> jnp.array([1, 0])
228
+ name_to_index(("z", "y")) -> jnp.array([2, 1])
229
+ name_to_index([]) -> jnp.array([], dtype=int)
230
+ """
231
+ if isinstance(names, str):
232
+ # Single name
233
+ if names not in self.STATE_NAMES:
234
+ raise ValueError(
235
+ f"State name '{names}' not found in {self.STATE_NAMES}"
236
+ )
237
+ return jnp.array([self.STATE_NAMES.index(names)], dtype=int)
238
+
239
+ elif isinstance(names, (list, tuple)):
240
+ # Multiple names (including empty)
241
+ if len(names) == 0:
242
+ return jnp.array([], dtype=int)
243
+
244
+ indices = []
245
+ for name in names:
246
+ if not isinstance(name, str):
247
+ raise ValueError(
248
+ f"All names must be strings, got {type(name)} for '{name}'"
249
+ )
250
+ if name not in self.STATE_NAMES:
251
+ raise ValueError(
252
+ f"State name '{name}' not found in {self.STATE_NAMES}"
253
+ )
254
+ indices.append(self.STATE_NAMES.index(name))
255
+ return jnp.array(indices, dtype=int)
256
+
257
+ else:
258
+ raise ValueError(f"names must be str, list, or tuple, got {type(names)}")
259
+
260
+ @abstractmethod
261
+ def dynamics(
262
+ self,
263
+ t: float,
264
+ state: jnp.ndarray,
265
+ params: Bunch,
266
+ coupling: Bunch,
267
+ external: Bunch,
268
+ ) -> Union[jnp.ndarray, Tuple[jnp.ndarray, jnp.ndarray]]:
269
+ """Compute state derivatives and auxiliary variables.
270
+
271
+ Parameters
272
+ ----------
273
+ t : float
274
+ Current time
275
+ state : jnp.ndarray
276
+ Current state with shape ``[N_STATES, n_nodes]``
277
+ params : Bunch
278
+ Model parameters as Bunch object (supports broadcasting)
279
+ coupling : Bunch
280
+ Named coupling inputs accessed as attributes (e.g., ``coupling.structural``,
281
+ ``coupling.modulatory``). Missing couplings are automatically filled with zeros.
282
+ external : Bunch
283
+ Named external inputs accessed as attributes (e.g., ``external.stimulus``,
284
+ ``external.perturbation``). Missing inputs are automatically filled with zeros.
285
+
286
+ Returns
287
+ -------
288
+ derivatives : jnp.ndarray or tuple
289
+ If ``N_AUXILIARIES == 0``: Returns derivatives array with shape ``[N_STATES, n_nodes]``
290
+
291
+ If ``N_AUXILIARIES > 0``: Returns tuple ``(derivatives, auxiliaries)`` where:
292
+
293
+ - derivatives has shape ``[N_STATES, n_nodes]``
294
+ - auxiliaries has shape ``[N_AUXILIARIES, n_nodes]``
295
+
296
+ Notes
297
+ -----
298
+ - If COUPLING_INPUTS is empty, the model has no coupling
299
+ - Coupling arrays have shape ``[n_dims, n_nodes]`` where n_dims is declared in COUPLING_INPUTS
300
+ - If EXTERNAL_INPUTS is empty, the model has no external inputs
301
+ - External input arrays have shape ``[n_dims, n_nodes]`` where n_dims is declared in EXTERNAL_INPUTS
302
+ """
303
+ pass
304
+
305
+ def verify(self, n_nodes: int = 1, verbose: bool = True) -> bool:
306
+ """Verify that dynamics implementation is correct.
307
+
308
+ Tests the dynamics function with default initial state and parameters
309
+ at t=0 with zero coupling to ensure it runs without errors and returns
310
+ the expected output format.
311
+
312
+ Args:
313
+ n_nodes: Number of nodes to test with
314
+ verbose: Whether to print verification details
315
+
316
+ Returns:
317
+ True if verification passes, False otherwise
318
+ """
319
+ try:
320
+ # Get test inputs
321
+ state = self.get_default_initial_state(n_nodes)
322
+ params = self.params
323
+
324
+ # Create coupling Bunch with zeros for all declared inputs
325
+ coupling = Bunch()
326
+ for name, n_dims in self.COUPLING_INPUTS.items():
327
+ coupling[name] = jnp.zeros((n_dims, n_nodes))
328
+
329
+ # Create external Bunch with zeros for all declared inputs
330
+ external = Bunch()
331
+ for name, n_dims in self.EXTERNAL_INPUTS.items():
332
+ external[name] = jnp.zeros((n_dims, n_nodes))
333
+
334
+ if verbose:
335
+ print(f"Verifying {self.__class__.__name__}:")
336
+ print(f" State shape: {state.shape}")
337
+ print(f" Coupling inputs: {list(self.COUPLING_INPUTS.keys())}")
338
+ print(f" External inputs: {list(self.EXTERNAL_INPUTS.keys())}")
339
+ print(f" Expected auxiliaries: {self.N_AUXILIARIES}")
340
+
341
+ # Call dynamics
342
+ result = self.dynamics(0.0, state, params, coupling, external)
343
+
344
+ # Check return format
345
+ if self.N_AUXILIARIES == 0:
346
+ # Should return just derivatives
347
+ if isinstance(result, tuple):
348
+ if verbose:
349
+ print(" ❌ ERROR: Expected single array but got tuple")
350
+ return False
351
+ derivatives = result
352
+ if derivatives.shape != (self.N_STATES, n_nodes):
353
+ if verbose:
354
+ print(
355
+ f" ❌ ERROR: Expected derivatives shape {(self.N_STATES, n_nodes)}, got {derivatives.shape}"
356
+ )
357
+ return False
358
+ else:
359
+ # Should return (derivatives, auxiliaries)
360
+ if not isinstance(result, tuple) or len(result) != 2:
361
+ if verbose:
362
+ print(
363
+ " ❌ ERROR: Expected tuple of (derivatives, auxiliaries)"
364
+ )
365
+ return False
366
+ derivatives, auxiliaries = result
367
+ if derivatives.shape != (self.N_STATES, n_nodes):
368
+ if verbose:
369
+ print(
370
+ f" ❌ ERROR: Expected derivatives shape {(self.N_STATES, n_nodes)}, got {derivatives.shape}"
371
+ )
372
+ return False
373
+ if auxiliaries.shape != (self.N_AUXILIARIES, n_nodes):
374
+ if verbose:
375
+ print(
376
+ f" ❌ ERROR: Expected auxiliaries shape {(self.N_AUXILIARIES, n_nodes)}, got {auxiliaries.shape}"
377
+ )
378
+ return False
379
+
380
+ if verbose:
381
+ print(" ✅ Verification passed!")
382
+ return True
383
+
384
+ except Exception as e:
385
+ if verbose:
386
+ print(f" ❌ ERROR: {e}")
387
+ return False
388
+
389
+ def simulate(
390
+ self,
391
+ t0: float = 0.0,
392
+ t1: float = 10.0,
393
+ dt: float = 0.01,
394
+ n_nodes: int = 1,
395
+ params: Optional[Bunch] = None,
396
+ initial_state: Optional[jnp.ndarray] = None,
397
+ solver=None,
398
+ **solver_kwargs,
399
+ ) -> Tuple[jnp.ndarray, jnp.ndarray]:
400
+ """Simulate dynamics using Diffrax.
401
+
402
+ Args:
403
+ t0: Start time
404
+ t1: End time
405
+ dt: Time step for output
406
+ n_nodes: Number of nodes to simulate
407
+ params: Parameters (default: self.params)
408
+ initial_state: Initial state (default: from get_default_initial_state)
409
+ solver: Diffrax solver (default: Dopri5)
410
+ **solver_kwargs: Additional solver arguments
411
+
412
+ Returns:
413
+ times: [n_timesteps] - Time points
414
+ trajectory: [n_timesteps, n_states, n_nodes] - State trajectory
415
+ """
416
+ if params is None:
417
+ params = self.params
418
+
419
+ if initial_state is None:
420
+ initial_state = self.get_default_initial_state(n_nodes)
421
+
422
+ if solver is None:
423
+ solver = Dopri5()
424
+
425
+ # Create zero coupling Bunch for all declared coupling inputs
426
+ coupling_zeros = Bunch()
427
+ for name, n_dims in self.COUPLING_INPUTS.items():
428
+ coupling_zeros[name] = jnp.zeros((n_dims, n_nodes))
429
+
430
+ # Create zero external Bunch for all declared external inputs
431
+ external_zeros = Bunch()
432
+ for name, n_dims in self.EXTERNAL_INPUTS.items():
433
+ external_zeros[name] = jnp.zeros((n_dims, n_nodes))
434
+
435
+ def ode_func(t, y, args):
436
+ """ODE function for Diffrax - returns only derivatives."""
437
+ result = self.dynamics(t, y, params, coupling_zeros, external_zeros)
438
+ # Extract only derivatives if auxiliaries are returned
439
+ if isinstance(result, tuple):
440
+ return result[0] # derivatives only
441
+ return result
442
+
443
+ # Set up time points - ensure we don't exceed t1
444
+ times = jnp.arange(
445
+ t0, t1 + dt / 2, dt
446
+ ) # Add dt/2 to handle floating point precision
447
+ save_at = SaveAt(ts=times)
448
+
449
+ # Solve ODE
450
+ term = ODETerm(ode_func)
451
+ solution = diffeqsolve(
452
+ terms=term,
453
+ solver=solver,
454
+ t0=t0,
455
+ t1=t1,
456
+ dt0=dt,
457
+ y0=initial_state,
458
+ saveat=save_at,
459
+ **solver_kwargs,
460
+ )
461
+
462
+ return times, solution.ys # shape: [n_timesteps, n_states, n_nodes]
463
+
464
+ def plot(
465
+ self,
466
+ t0: float = 0.0,
467
+ t1: float = 10.0,
468
+ dt: float = 0.01,
469
+ n_nodes: int = 1,
470
+ figsize: Tuple[int, int] = (10, 6),
471
+ **simulate_kwargs,
472
+ ) -> None:
473
+ """Plot dynamics timeseries for state variables.
474
+
475
+ Note: Currently only plots state variables (not auxiliaries) as auxiliaries
476
+ are not computed during simulation.
477
+
478
+ Args:
479
+ t0: Start time
480
+ t1: End time
481
+ dt: Time step
482
+ n_nodes: Number of nodes to simulate
483
+ figsize: Figure size (width, height)
484
+ **simulate_kwargs: Additional arguments for simulate()
485
+ """
486
+ try:
487
+ import matplotlib.pyplot as plt
488
+ except ImportError:
489
+ raise ImportError(
490
+ "matplotlib is required for plotting. Install with: pip install matplotlib"
491
+ )
492
+
493
+ # Simulate dynamics
494
+ times, trajectory = self.simulate(
495
+ t0=t0, t1=t1, dt=dt, n_nodes=n_nodes, **simulate_kwargs
496
+ )
497
+
498
+ # Plot only state variables (trajectory only contains states)
499
+ # Create plot
500
+ fig, axes = plt.subplots(self.N_STATES, 1, figsize=figsize, sharex=True)
501
+ if self.N_STATES == 1:
502
+ axes = [axes] # Make iterable for single plot
503
+
504
+ for state_idx, state_name in enumerate(self.STATE_NAMES):
505
+ ax = axes[state_idx]
506
+
507
+ # Plot each node
508
+ for node in range(n_nodes):
509
+ label = f"Node {node}" if n_nodes > 1 else None
510
+ ax.plot(times, trajectory[:, state_idx, node], label=label)
511
+
512
+ ax.set_ylabel(state_name)
513
+ ax.grid(True, alpha=0.3)
514
+
515
+ if n_nodes > 1:
516
+ ax.legend()
517
+
518
+ axes[-1].set_xlabel("Time")
519
+ plt.suptitle(f"{self.__class__.__name__} Dynamics")
520
+ plt.tight_layout()
521
+ plt.show()
522
+
523
+ def __repr__(self) -> str:
524
+ """String representation of dynamics."""
525
+ coupling_str = (
526
+ f", coupling_inputs={list(self.COUPLING_INPUTS.keys())}"
527
+ if self.COUPLING_INPUTS
528
+ else ""
529
+ )
530
+ external_str = (
531
+ f", external_inputs={list(self.EXTERNAL_INPUTS.keys())}"
532
+ if self.EXTERNAL_INPUTS
533
+ else ""
534
+ )
535
+ return (
536
+ f"{self.__class__.__name__}("
537
+ f"states={self.N_STATES}, "
538
+ f"auxiliaries={self.N_AUXILIARIES}"
539
+ f"{coupling_str}"
540
+ f"{external_str})"
541
+ )