tvboptim 0.2.8__tar.gz → 0.2.10__tar.gz

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 (88) hide show
  1. {tvboptim-0.2.8/src/tvboptim.egg-info → tvboptim-0.2.10}/PKG-INFO +2 -1
  2. {tvboptim-0.2.8 → tvboptim-0.2.10}/pyproject.toml +3 -1
  3. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/external_input/base.py +69 -0
  4. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/external_input/data.py +19 -0
  5. tvboptim-0.2.10/src/tvboptim/experimental/network_dynamics/result.py +397 -0
  6. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/solve.py +224 -41
  7. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/solvers/native.py +39 -0
  8. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/observations/tvb_monitors/__init__.py +3 -1
  9. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/observations/tvb_monitors/bold.py +195 -23
  10. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/types/parameter.py +5 -1
  11. {tvboptim-0.2.8 → tvboptim-0.2.10/src/tvboptim.egg-info}/PKG-INFO +2 -1
  12. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim.egg-info/requires.txt +1 -0
  13. tvboptim-0.2.8/src/tvboptim/experimental/network_dynamics/result.py +0 -178
  14. {tvboptim-0.2.8 → tvboptim-0.2.10}/LICENSE +0 -0
  15. {tvboptim-0.2.8 → tvboptim-0.2.10}/README.md +0 -0
  16. {tvboptim-0.2.8 → tvboptim-0.2.10}/setup.cfg +0 -0
  17. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/__init__.py +0 -0
  18. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/data/__init__.py +0 -0
  19. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/data/connectivity/dTOR/data.npz +0 -0
  20. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/data/connectivity/dk_average/data.npz +0 -0
  21. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/data/functional/dk_average/data.npz +0 -0
  22. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/data/loaders.py +0 -0
  23. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/data/plotting/dk_average/aparc+aseg-mni_09c.nii.gz +0 -0
  24. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/data/plotting/dk_average/fs_default.txt +0 -0
  25. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/data/plotting/dk_average/fs_default_freesurfer_idx.csv +0 -0
  26. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/execution.py +0 -0
  27. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/__init__.py +0 -0
  28. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/__init__.py +0 -0
  29. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/analysis/__init__.py +0 -0
  30. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/analysis/lyapunov.py +0 -0
  31. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/core/__init__.py +0 -0
  32. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/core/bunch.py +0 -0
  33. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/core/network.py +0 -0
  34. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/coupling/__init__.py +0 -0
  35. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/coupling/base.py +0 -0
  36. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/coupling/linear.py +0 -0
  37. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/coupling/subspace.py +0 -0
  38. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/coupling/tvb.py +0 -0
  39. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/dynamics/__init__.py +0 -0
  40. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/dynamics/base.py +0 -0
  41. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/dynamics/lorenz.py +0 -0
  42. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py +0 -0
  43. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/coombes_byrne.py +0 -0
  44. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/epileptor.py +0 -0
  45. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/generic_2d_oscillator.py +0 -0
  46. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/jansen_rit.py +0 -0
  47. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/kuramoto.py +0 -0
  48. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/larter_breakspear.py +0 -0
  49. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/linear.py +0 -0
  50. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/montbrio_pazo_roxin.py +0 -0
  51. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/sup_hopf.py +0 -0
  52. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wilson_cowan.py +0 -0
  53. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang.py +0 -0
  54. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang_exc_inh.py +0 -0
  55. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/external_input/__init__.py +0 -0
  56. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/external_input/parametric.py +0 -0
  57. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/graph/__init__.py +0 -0
  58. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/graph/base.py +0 -0
  59. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/graph/sparse.py +0 -0
  60. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/graph/utils.py +0 -0
  61. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/noise/__init__.py +0 -0
  62. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/noise/base.py +0 -0
  63. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/noise/gaussian.py +0 -0
  64. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/solvers/__init__.py +0 -0
  65. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/solvers/base.py +0 -0
  66. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/solvers/diffrax.py +0 -0
  67. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/utils/__init__.py +0 -0
  68. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/utils/history.py +0 -0
  69. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/experimental/network_dynamics/utils/printer.py +0 -0
  70. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/observations/__init__.py +0 -0
  71. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/observations/observation.py +0 -0
  72. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/observations/tvb_monitors/downsampling.py +0 -0
  73. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/optim/__init__.py +0 -0
  74. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/optim/callbacks.py +0 -0
  75. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/optim/optax.py +0 -0
  76. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/tvbo/__init__.py +0 -0
  77. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/tvbo/prepare_experiment.py +0 -0
  78. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/types/__init__.py +0 -0
  79. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/types/spaces.py +0 -0
  80. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/types/stateutils.py +0 -0
  81. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/utils/__init__.py +0 -0
  82. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/utils/caching.py +0 -0
  83. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim/utils/utils.py +0 -0
  84. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim.egg-info/SOURCES.txt +0 -0
  85. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim.egg-info/dependency_links.txt +0 -0
  86. {tvboptim-0.2.8 → tvboptim-0.2.10}/src/tvboptim.egg-info/top_level.txt +0 -0
  87. {tvboptim-0.2.8 → tvboptim-0.2.10}/tests/test_execution.py +0 -0
  88. {tvboptim-0.2.8 → tvboptim-0.2.10}/tests/test_optax_optimizer_toy.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tvboptim
3
- Version: 0.2.8
3
+ Version: 0.2.10
4
4
  Summary: Optimization tools for The Virtual Brain
5
5
  Author-email: Marius Pille <marius.pille@bih-charite.de>
6
6
  License-Expression: EUPL-1.2
@@ -43,6 +43,7 @@ Requires-Dist: tvb-library; extra == "docs"
43
43
  Requires-Dist: jupyter-cache>=1.0.1; extra == "docs"
44
44
  Requires-Dist: nibabel; extra == "docs"
45
45
  Requires-Dist: nilearn; extra == "docs"
46
+ Requires-Dist: pymoo; extra == "docs"
46
47
  Requires-Dist: griffe<2.0.0; extra == "docs"
47
48
  Dynamic: license-file
48
49
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "tvboptim"
7
- version = "0.2.8"
7
+ version = "0.2.10"
8
8
  description = "Optimization tools for The Virtual Brain"
9
9
  readme = "README.md"
10
10
  authors = [
@@ -76,6 +76,7 @@ docs = [
76
76
  "jupyter-cache>=1.0.1",
77
77
  "nibabel",
78
78
  "nilearn",
79
+ "pymoo",
79
80
  "griffe<2.0.0"
80
81
  ]
81
82
 
@@ -95,6 +96,7 @@ docs = [
95
96
  "jupyter-cache>=1.0.1",
96
97
  "nibabel",
97
98
  "nilearn",
99
+ "pymoo",
98
100
  "griffe<2.0.0"
99
101
  ]
100
102
 
@@ -150,3 +150,72 @@ class AbstractExternalInput(ABC):
150
150
  """String representation of external input."""
151
151
  param_str = ", ".join(f"{k}={v}" for k, v in self.params.items())
152
152
  return f"{self.__class__.__name__}({param_str})"
153
+
154
+ def _plot_prepare(self, n_nodes: int, dt: float) -> Tuple[Bunch, Bunch]:
155
+ """Lightweight prepare for the plot path (no network required).
156
+
157
+ Subclasses that need precomputed data (e.g. interpolators) override this.
158
+ Default returns empty Bunches, which works for all stateless parametric
159
+ inputs.
160
+ """
161
+ return Bunch(), Bunch()
162
+
163
+ def plot(
164
+ self,
165
+ t0: float = 0.0,
166
+ t1: float = 1.0,
167
+ *,
168
+ dt: float = None,
169
+ n_nodes: int = 1,
170
+ ax=None,
171
+ ):
172
+ """Plot the input signal over [t0, t1] for quick inspection.
173
+
174
+ Calls ``compute`` directly with a zero state and empty input_data /
175
+ input_state (or whatever ``_plot_prepare`` returns). State-dependent or
176
+ stateful inputs will therefore show open-loop behavior only.
177
+
178
+ Args:
179
+ t0, t1: Time interval to plot.
180
+ dt: Sampling step. Defaults to (t1 - t0) / 500.
181
+ n_nodes: Number of nodes to render (lets spatial patterns show up).
182
+ ax: Matplotlib axis (or array of axes for multi-dim outputs). Created
183
+ if None.
184
+
185
+ Returns:
186
+ The matplotlib axis (or array of axes) used for plotting.
187
+ """
188
+ import matplotlib.pyplot as plt
189
+
190
+ if dt is None:
191
+ dt = (t1 - t0) / 500.0
192
+
193
+ input_data, input_state = self._plot_prepare(n_nodes, dt)
194
+ state = jnp.zeros((1, n_nodes))
195
+
196
+ ts = jnp.arange(t0, t1, dt)
197
+ signals = jnp.stack(
198
+ [
199
+ self.compute(float(t), state, input_data, input_state, self.params)
200
+ for t in ts
201
+ ]
202
+ ) # [T, N_OUTPUT_DIMS, n_nodes]
203
+
204
+ n_dims = signals.shape[1]
205
+ if ax is None:
206
+ fig, ax = plt.subplots(n_dims, 1, sharex=True, squeeze=False)
207
+ ax = ax[:, 0]
208
+ else:
209
+ ax = ax if hasattr(ax, "__len__") else [ax]
210
+
211
+ show_legend = n_nodes <= 8
212
+ for d in range(n_dims):
213
+ for i in range(n_nodes):
214
+ ax[d].plot(ts, signals[:, d, i], label=f"node {i}" if show_legend else None)
215
+ ax[d].set_ylabel(f"input[{d}]" if n_dims > 1 else "input")
216
+ if show_legend and n_nodes > 1:
217
+ ax[d].legend(loc="best", fontsize="small")
218
+ ax[-1].set_xlabel("time")
219
+ ax[0].set_title(repr(self))
220
+
221
+ return ax if n_dims > 1 else ax[0]
@@ -187,6 +187,25 @@ class DataInput(AbstractExternalInput):
187
187
  # [n_times, n_dims, n_nodes] → [n_dims, n_nodes]
188
188
  return interpolated
189
189
 
190
+ def _plot_prepare(self, n_nodes, dt):
191
+ """Build interpolator for the plot path without a network."""
192
+ times = self.params.times
193
+ data = self.params.data
194
+ interp_type = self.params.interpolation_type
195
+
196
+ if interp_type == "linear":
197
+ interpolator = diffrax.LinearInterpolation(ts=times, ys=data)
198
+ else:
199
+ coeffs = diffrax.backward_hermite_coefficients(ts=times, ys=data)
200
+ interpolator = diffrax.CubicInterpolation(ts=times, coeffs=coeffs)
201
+
202
+ input_data = Bunch(
203
+ interpolator=interpolator,
204
+ n_nodes=n_nodes,
205
+ data_shape=tuple(data.shape),
206
+ )
207
+ return input_data, Bunch()
208
+
190
209
  def update_state(
191
210
  self, input_data: Bunch, input_state: Bunch, new_state: jnp.ndarray
192
211
  ) -> Bunch:
@@ -0,0 +1,397 @@
1
+ """Result types for Network Dynamics native solvers.
2
+
3
+ This module provides Diffrax-like solution objects for native Network Dynamics solvers,
4
+ ensuring consistent API across solver types.
5
+ """
6
+
7
+ import warnings
8
+ from typing import Optional, Sequence, Tuple, Union
9
+
10
+ import jax.numpy as jnp
11
+ from jax import tree_util
12
+
13
+
14
+ @tree_util.register_pytree_with_keys_class
15
+ class NativeSolution:
16
+ """Solution object for Network Dynamics native solvers.
17
+
18
+ Provides the same interface as Diffrax solutions (.ys, .ts) while being
19
+ a proper JAX PyTree for compatibility with JAX transformations.
20
+
21
+ Attributes:
22
+ ts: Time points, shape [n_time]
23
+ ys: Trajectory data, shape [n_time, n_variables, n_nodes]
24
+ dt: Time step (optional), stored as static auxiliary data
25
+ variable_names: Names of the variables along axis 1 of ys, in order.
26
+ Contains state variables and/or auxiliary variables, depending on
27
+ the dynamics' VARIABLES_OF_INTEREST. None if unknown.
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ ts: jnp.ndarray,
33
+ ys: jnp.ndarray,
34
+ dt: float = None,
35
+ variable_names: Optional[Tuple[str, ...]] = None,
36
+ ):
37
+ """Initialize native solution.
38
+
39
+ Args:
40
+ ts: Time points, shape [n_time]
41
+ ys: Trajectory array, shape [n_time, n_variables, n_nodes]
42
+ dt: Time step (optional), stored as static auxiliary data for JIT compatibility
43
+ variable_names: Names of the variables along axis 1 of ys, in order.
44
+ """
45
+ self.ts = ts
46
+ self.ys = ys
47
+ self.dt = dt
48
+ self.variable_names = (
49
+ tuple(variable_names) if variable_names is not None else None
50
+ )
51
+
52
+ @property
53
+ def time(self):
54
+ return self.ts
55
+
56
+ @property
57
+ def data(self):
58
+ return self.ys
59
+
60
+ def tree_flatten(self):
61
+ """JAX PyTree flatten for transformations."""
62
+ children = (self.ts, self.ys)
63
+ aux_data = {"dt": self.dt, "variable_names": self.variable_names}
64
+ return children, aux_data
65
+
66
+ def tree_flatten_with_keys(self):
67
+ """JAX PyTree flatten with named keys (so paths render as ``.ts``/``.ys``)."""
68
+ children = (
69
+ (tree_util.GetAttrKey("ts"), self.ts),
70
+ (tree_util.GetAttrKey("ys"), self.ys),
71
+ )
72
+ aux_data = {"dt": self.dt, "variable_names": self.variable_names}
73
+ return children, aux_data
74
+
75
+ @classmethod
76
+ def tree_unflatten(cls, aux_data, children):
77
+ """JAX PyTree unflatten for transformations."""
78
+ ts, ys = children
79
+ dt = aux_data.get("dt") if aux_data else None
80
+ variable_names = aux_data.get("variable_names") if aux_data else None
81
+ return cls(ts, ys, dt=dt, variable_names=variable_names)
82
+
83
+ def __repr__(self):
84
+ """String representation."""
85
+ return (
86
+ f"NativeSolution(shape={self.ys.shape}, "
87
+ f"t=[{self.ts[0]:.2f}, {self.ts[-1]:.2f}], "
88
+ f"variable_names={self.variable_names})"
89
+ )
90
+
91
+ def _resolve_variables(
92
+ self,
93
+ variables: Optional[Sequence[Union[str, int]]],
94
+ ) -> Tuple[list, list]:
95
+ """Normalize variable selection to (indices, labels)."""
96
+ n_vars = self.ys.shape[1]
97
+ if variables is None:
98
+ idx = list(range(n_vars))
99
+ else:
100
+ idx = []
101
+ for v in variables:
102
+ if isinstance(v, str):
103
+ if self.variable_names is None:
104
+ raise ValueError(
105
+ "Cannot select variables by name: variable_names "
106
+ "is not set on this solution. Pass integer indices."
107
+ )
108
+ if v not in self.variable_names:
109
+ raise ValueError(
110
+ f"Variable {v!r} not in variable_names="
111
+ f"{self.variable_names}."
112
+ )
113
+ idx.append(self.variable_names.index(v))
114
+ else:
115
+ vi = int(v)
116
+ if not -n_vars <= vi < n_vars:
117
+ raise IndexError(
118
+ f"Variable index {vi} out of bounds for n_variables={n_vars}."
119
+ )
120
+ idx.append(vi % n_vars)
121
+
122
+ labels = [
123
+ self.variable_names[i] if self.variable_names is not None else f"var[{i}]"
124
+ for i in idx
125
+ ]
126
+ return idx, labels
127
+
128
+ def _resolve_nodes(
129
+ self,
130
+ nodes: Optional[Union[int, Sequence[int]]],
131
+ n_nodes: int,
132
+ max_nodes: int,
133
+ ) -> list:
134
+ """Normalize node selection to a list of indices."""
135
+ if nodes is None:
136
+ if n_nodes > max_nodes:
137
+ warnings.warn(
138
+ f"Solution has {n_nodes} nodes; plotting first {max_nodes}. "
139
+ f"Pass nodes=[...] or max_nodes=N to override.",
140
+ stacklevel=3,
141
+ )
142
+ return list(range(max_nodes))
143
+ return list(range(n_nodes))
144
+ if isinstance(nodes, int):
145
+ return list(range(min(nodes, n_nodes)))
146
+ idx = [int(n) for n in nodes]
147
+ for ni in idx:
148
+ if not -n_nodes <= ni < n_nodes:
149
+ raise IndexError(
150
+ f"Node index {ni} out of bounds for n_nodes={n_nodes}."
151
+ )
152
+ return [ni % n_nodes for ni in idx]
153
+
154
+ def _resolve_t_mask(
155
+ self,
156
+ t_range: Optional[Tuple[Optional[float], Optional[float]]],
157
+ default_window: Optional[float],
158
+ ) -> jnp.ndarray:
159
+ """Build a boolean time mask with soft clipping."""
160
+ ts = self.ts
161
+ t_min, t_max = float(ts[0]), float(ts[-1])
162
+ user_supplied = t_range is not None
163
+
164
+ if t_range is None:
165
+ t0 = t_min
166
+ t1 = t_max if default_window is None else min(t_min + default_window, t_max)
167
+ else:
168
+ req_t0, req_t1 = t_range
169
+ t0 = t_min if req_t0 is None else float(req_t0)
170
+ t1 = t_max if req_t1 is None else float(req_t1)
171
+
172
+ clipped_t0 = max(t0, t_min)
173
+ clipped_t1 = min(t1, t_max)
174
+
175
+ if clipped_t0 >= clipped_t1:
176
+ raise ValueError(
177
+ f"Requested t_range=({t0}, {t1}) has no overlap with "
178
+ f"available range [{t_min}, {t_max}]."
179
+ )
180
+
181
+ if user_supplied and (clipped_t0 != t0 or clipped_t1 != t1):
182
+ requested_span = t1 - t0
183
+ actual_span = clipped_t1 - clipped_t0
184
+ if actual_span < 0.9 * requested_span:
185
+ warnings.warn(
186
+ f"Requested t_range=({t0}, {t1}) only partially overlaps "
187
+ f"available [{t_min}, {t_max}]; plotting "
188
+ f"[{clipped_t0}, {clipped_t1}].",
189
+ stacklevel=3,
190
+ )
191
+
192
+ return (ts >= clipped_t0) & (ts <= clipped_t1)
193
+
194
+ @staticmethod
195
+ def _prepare_axes(ax, n_vars, figsize, dpi):
196
+ """Set up or validate axes for n_vars subplots."""
197
+ import matplotlib.pyplot as plt
198
+
199
+ if ax is None:
200
+ if figsize is None:
201
+ figsize = (10, max(2.0, 2.0 * n_vars))
202
+ fig, axes = plt.subplots(
203
+ n_vars, 1, figsize=figsize, dpi=dpi, sharex=True, squeeze=False
204
+ )
205
+ return fig, list(axes[:, 0])
206
+
207
+ # Single Axes
208
+ if hasattr(ax, "plot"):
209
+ if n_vars != 1:
210
+ raise ValueError(
211
+ f"Got a single Axes but {n_vars} variables to plot; "
212
+ f"pass a sequence of {n_vars} Axes."
213
+ )
214
+ return ax.figure, [ax]
215
+
216
+ # Sequence of Axes
217
+ axes_list = list(ax)
218
+ if len(axes_list) != n_vars:
219
+ raise ValueError(
220
+ f"Got {len(axes_list)} Axes but {n_vars} variables to plot."
221
+ )
222
+ return axes_list[0].figure, axes_list
223
+
224
+ def plot(
225
+ self,
226
+ variables: Optional[Sequence[Union[str, int]]] = None,
227
+ nodes: Optional[Union[int, Sequence[int]]] = None,
228
+ t_range: Optional[Tuple[Optional[float], Optional[float]]] = None,
229
+ max_nodes: int = 10,
230
+ default_window: Optional[float] = 10_000.0,
231
+ ax=None,
232
+ figsize: Optional[Tuple[float, float]] = None,
233
+ dpi: float = 150,
234
+ **plot_kwargs,
235
+ ):
236
+ """Quick-look plot of the solution trajectory.
237
+
238
+ One subplot per selected variable, with selected nodes overlaid as lines.
239
+ Intended for first-pass inspection, not publication.
240
+
241
+ Args:
242
+ variables: Variables to plot. Names (requires ``variable_names``)
243
+ or integer indices, mixable. ``None`` plots all variables.
244
+ nodes: Node selection. ``None`` plots all nodes up to ``max_nodes``;
245
+ ``int N`` plots the first ``N``; a sequence selects explicitly.
246
+ t_range: ``(t_start, t_end)`` time window. Either bound may be
247
+ ``None`` for open-ended. Soft-clipped to available data with a
248
+ warning if the overlap is partial.
249
+ max_nodes: Cap when ``nodes=None`` to avoid plotting hundreds of
250
+ lines. Emits a warning when the cap kicks in.
251
+ default_window: When ``t_range`` is None, plot the first
252
+ ``default_window`` time units (default 10_000, matching ms).
253
+ Set to ``None`` to plot the full range.
254
+ ax: Existing Axes (single, when one variable) or sequence of Axes
255
+ (one per variable). ``None`` creates a new figure.
256
+ figsize: Figure size when creating a new figure.
257
+ dpi: Figure DPI when creating a new figure (ignored if ``ax`` is
258
+ supplied). Default 150.
259
+ **plot_kwargs: Forwarded to ``ax.plot`` (e.g. ``color``, ``lw``).
260
+
261
+ Returns:
262
+ ``(fig, axes)`` where ``axes`` is a list with one Axes per variable.
263
+ """
264
+ var_idx, var_labels = self._resolve_variables(variables)
265
+ node_idx = self._resolve_nodes(nodes, self.ys.shape[2], max_nodes)
266
+ t_mask = self._resolve_t_mask(t_range, default_window)
267
+
268
+ ts_sel = self.ts[t_mask]
269
+ ys_sel = self.ys[t_mask][:, var_idx, :][:, :, node_idx]
270
+
271
+ fig, axes = self._prepare_axes(ax, len(var_idx), figsize, dpi)
272
+
273
+ plot_kwargs.setdefault("alpha", 0.7 if len(node_idx) > 3 else 1.0)
274
+ show_legend = len(node_idx) <= 8
275
+
276
+ for k, label in enumerate(var_labels):
277
+ a = axes[k]
278
+ for j, ni in enumerate(node_idx):
279
+ a.plot(
280
+ ts_sel,
281
+ ys_sel[:, k, j],
282
+ label=f"node {ni}" if show_legend else None,
283
+ **plot_kwargs,
284
+ )
285
+ a.set_ylabel(label)
286
+ a.set_title(label)
287
+ a.grid(True, alpha=0.3)
288
+ if show_legend:
289
+ a.legend(fontsize="small", loc="best")
290
+
291
+ axes[-1].set_xlabel("time")
292
+ fig.tight_layout()
293
+ return fig, axes
294
+
295
+
296
+ @tree_util.register_pytree_with_keys_class
297
+ class DiffraxSolution(NativeSolution):
298
+ """Solution wrapper for Diffrax solvers, compatible with NativeSolution interface.
299
+
300
+ Wraps a diffrax Solution object and exposes the NativeSolution interface
301
+ (.ts, .ys, .dt), while preserving access to the full diffrax solution via
302
+ ``_solution`` (use this to reach ``.stats``, ``.result``, etc.).
303
+
304
+ Note: the Diffrax prepare path does not apply ``VARIABLES_OF_INTEREST``
305
+ filtering and discards auxiliaries, so ``ys`` always has shape
306
+ ``[n_time, N_STATES, n_nodes]`` and ``variable_names`` always equals
307
+ ``STATE_NAMES``. Use a native solver if you need VOI filtering or
308
+ auxiliary outputs.
309
+
310
+ Attributes:
311
+ _solution: The underlying diffrax Solution object
312
+ dt: Effective save time step inferred from saveat.ts at prepare time,
313
+ or None if saveat was not ts-based. Only meaningful for uniformly
314
+ spaced ``SaveAt(ts=...)``.
315
+ variable_names: Names of the variables along axis 1 of ys, in order.
316
+ """
317
+
318
+ def __init__(
319
+ self,
320
+ solution,
321
+ dt=None,
322
+ variable_names: Optional[Tuple[str, ...]] = None,
323
+ ):
324
+ self._solution = solution
325
+ self.dt = dt
326
+ self.variable_names = (
327
+ tuple(variable_names) if variable_names is not None else None
328
+ )
329
+
330
+ @property
331
+ def ts(self):
332
+ return self._solution.ts
333
+
334
+ @property
335
+ def ys(self):
336
+ return self._solution.ys
337
+
338
+ @property
339
+ def stats(self):
340
+ return self._solution.stats
341
+
342
+ @property
343
+ def result(self):
344
+ return self._solution.result
345
+
346
+ def tree_flatten(self):
347
+ children = (self._solution,)
348
+ aux_data = {"dt": self.dt, "variable_names": self.variable_names}
349
+ return children, aux_data
350
+
351
+ def tree_flatten_with_keys(self):
352
+ children = ((tree_util.GetAttrKey("solution"), self._solution),)
353
+ aux_data = {"dt": self.dt, "variable_names": self.variable_names}
354
+ return children, aux_data
355
+
356
+ @classmethod
357
+ def tree_unflatten(cls, aux_data, children):
358
+ return cls(
359
+ children[0],
360
+ dt=aux_data.get("dt"),
361
+ variable_names=aux_data.get("variable_names"),
362
+ )
363
+
364
+ def __repr__(self):
365
+ return (
366
+ f"DiffraxSolution(shape={self.ys.shape}, "
367
+ f"t=[{self.ts[0]:.2f}, {self.ts[-1]:.2f}], dt={self.dt}, "
368
+ f"variable_names={self.variable_names})"
369
+ )
370
+
371
+
372
+ def wrap_native_result(
373
+ trajectory: jnp.ndarray,
374
+ t0: float,
375
+ t1: float,
376
+ dt: float,
377
+ variable_names: Optional[Tuple[str, ...]] = None,
378
+ ) -> NativeSolution:
379
+ """Wrap native solver trajectory in solution object.
380
+
381
+ Args:
382
+ trajectory: Trajectory array from native solver, shape [n_time, n_variables, n_nodes]
383
+ t0: Start time
384
+ t1: End time
385
+ dt: Time step
386
+ variable_names: Names of the variables along axis 1 of trajectory, in order.
387
+
388
+ Returns:
389
+ NativeSolution with .ys, .ts, and .variable_names attributes like Diffrax
390
+ """
391
+ n_steps = trajectory.shape[0]
392
+ # Native solvers scan over time_steps = arange(t0, t1, dt) and emit the
393
+ # post-step state on each iteration. Trajectory[i] is therefore the state
394
+ # at time t0 + (i + 1) * dt, so the save grid runs (t0, t1] with the
395
+ # endpoint t1 included and the initial state t0 excluded.
396
+ ts = t0 + (jnp.arange(n_steps) + 1) * dt
397
+ return NativeSolution(ts=ts, ys=trajectory, dt=dt, variable_names=variable_names)