tvboptim 0.2.8__tar.gz → 0.2.9__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.
- {tvboptim-0.2.8/src/tvboptim.egg-info → tvboptim-0.2.9}/PKG-INFO +1 -1
- {tvboptim-0.2.8 → tvboptim-0.2.9}/pyproject.toml +1 -1
- tvboptim-0.2.9/src/tvboptim/experimental/network_dynamics/result.py +397 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/solve.py +224 -41
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/solvers/native.py +39 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9/src/tvboptim.egg-info}/PKG-INFO +1 -1
- tvboptim-0.2.8/src/tvboptim/experimental/network_dynamics/result.py +0 -178
- {tvboptim-0.2.8 → tvboptim-0.2.9}/LICENSE +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/README.md +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/setup.cfg +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/data/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/data/connectivity/dTOR/data.npz +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/data/connectivity/dk_average/data.npz +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/data/functional/dk_average/data.npz +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/data/loaders.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/data/plotting/dk_average/aparc+aseg-mni_09c.nii.gz +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/data/plotting/dk_average/fs_default.txt +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/data/plotting/dk_average/fs_default_freesurfer_idx.csv +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/execution.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/analysis/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/analysis/lyapunov.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/core/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/core/bunch.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/core/network.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/coupling/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/coupling/base.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/coupling/linear.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/coupling/subspace.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/coupling/tvb.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/base.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/lorenz.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/coombes_byrne.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/epileptor.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/generic_2d_oscillator.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/jansen_rit.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/kuramoto.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/larter_breakspear.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/linear.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/montbrio_pazo_roxin.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/sup_hopf.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wilson_cowan.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang_exc_inh.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/external_input/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/external_input/base.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/external_input/data.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/external_input/parametric.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/graph/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/graph/base.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/graph/sparse.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/graph/utils.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/noise/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/noise/base.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/noise/gaussian.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/solvers/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/solvers/base.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/solvers/diffrax.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/utils/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/utils/history.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/utils/printer.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/observations/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/observations/observation.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/observations/tvb_monitors/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/observations/tvb_monitors/bold.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/observations/tvb_monitors/downsampling.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/optim/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/optim/callbacks.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/optim/optax.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/tvbo/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/tvbo/prepare_experiment.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/types/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/types/parameter.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/types/spaces.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/types/stateutils.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/utils/__init__.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/utils/caching.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim/utils/utils.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim.egg-info/SOURCES.txt +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim.egg-info/dependency_links.txt +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim.egg-info/requires.txt +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/src/tvboptim.egg-info/top_level.txt +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/tests/test_execution.py +0 -0
- {tvboptim-0.2.8 → tvboptim-0.2.9}/tests/test_optax_optimizer_toy.py +0 -0
|
@@ -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)
|