tvboptim 0.2.7__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.7/src/tvboptim.egg-info → tvboptim-0.2.9}/PKG-INFO +3 -3
- {tvboptim-0.2.7 → tvboptim-0.2.9}/pyproject.toml +3 -3
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/core/network.py +40 -16
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/base.py +24 -0
- tvboptim-0.2.9/src/tvboptim/experimental/network_dynamics/result.py +397 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/solve.py +522 -530
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/solvers/native.py +39 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/observations/tvb_monitors/__init__.py +11 -2
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/observations/tvb_monitors/bold.py +237 -13
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/observations/tvb_monitors/downsampling.py +13 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/optim/optax.py +105 -37
- {tvboptim-0.2.7 → tvboptim-0.2.9/src/tvboptim.egg-info}/PKG-INFO +3 -3
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim.egg-info/SOURCES.txt +2 -1
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim.egg-info/requires.txt +2 -2
- tvboptim-0.2.9/tests/test_optax_optimizer_toy.py +170 -0
- tvboptim-0.2.7/src/tvboptim/experimental/network_dynamics/result.py +0 -127
- {tvboptim-0.2.7 → tvboptim-0.2.9}/LICENSE +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/README.md +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/setup.cfg +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/data/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/data/connectivity/dTOR/data.npz +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/data/connectivity/dk_average/data.npz +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/data/functional/dk_average/data.npz +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/data/loaders.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/data/plotting/dk_average/aparc+aseg-mni_09c.nii.gz +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/data/plotting/dk_average/fs_default.txt +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/data/plotting/dk_average/fs_default_freesurfer_idx.csv +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/execution.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/analysis/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/analysis/lyapunov.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/core/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/core/bunch.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/coupling/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/coupling/base.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/coupling/linear.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/coupling/subspace.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/coupling/tvb.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/lorenz.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/coombes_byrne.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/epileptor.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/generic_2d_oscillator.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/jansen_rit.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/kuramoto.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/larter_breakspear.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/linear.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/montbrio_pazo_roxin.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/sup_hopf.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wilson_cowan.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang_exc_inh.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/external_input/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/external_input/base.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/external_input/data.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/external_input/parametric.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/graph/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/graph/base.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/graph/sparse.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/graph/utils.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/noise/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/noise/base.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/noise/gaussian.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/solvers/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/solvers/base.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/solvers/diffrax.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/utils/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/utils/history.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/utils/printer.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/observations/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/observations/observation.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/optim/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/optim/callbacks.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/tvbo/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/tvbo/prepare_experiment.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/types/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/types/parameter.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/types/spaces.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/types/stateutils.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/utils/__init__.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/utils/caching.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/utils/utils.py +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim.egg-info/dependency_links.txt +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim.egg-info/top_level.txt +0 -0
- {tvboptim-0.2.7 → tvboptim-0.2.9}/tests/test_execution.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tvboptim
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.9
|
|
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
|
|
@@ -23,11 +23,11 @@ Requires-Dist: optimistix
|
|
|
23
23
|
Requires-Dist: matplotlib
|
|
24
24
|
Requires-Dist: numpy
|
|
25
25
|
Requires-Dist: pandas
|
|
26
|
-
Requires-Dist: jax<0.
|
|
26
|
+
Requires-Dist: jax<0.10
|
|
27
27
|
Requires-Dist: equinox
|
|
28
28
|
Requires-Dist: dill
|
|
29
29
|
Requires-Dist: tqdm
|
|
30
|
-
Requires-Dist: numpyro>=0.
|
|
30
|
+
Requires-Dist: numpyro>=0.20.1
|
|
31
31
|
Requires-Dist: diffrax
|
|
32
32
|
Requires-Dist: plum-dispatch
|
|
33
33
|
Provides-Extra: dev
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "tvboptim"
|
|
7
|
-
version = "0.2.
|
|
7
|
+
version = "0.2.9"
|
|
8
8
|
description = "Optimization tools for The Virtual Brain"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
authors = [
|
|
@@ -30,11 +30,11 @@ dependencies = [
|
|
|
30
30
|
"matplotlib",
|
|
31
31
|
"numpy",
|
|
32
32
|
"pandas",
|
|
33
|
-
"jax<0.
|
|
33
|
+
"jax<0.10", # numpyro<=0.20.1 imports jax.extend.core.primitives.xla_pmap_p, removed in jax 0.10. Drop cap once numpyro releases a fix.
|
|
34
34
|
"equinox",
|
|
35
35
|
"dill",
|
|
36
36
|
"tqdm",
|
|
37
|
-
"numpyro>=0.
|
|
37
|
+
"numpyro>=0.20.1",
|
|
38
38
|
"diffrax",
|
|
39
39
|
"plum-dispatch",
|
|
40
40
|
]
|
{tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/core/network.py
RENAMED
|
@@ -244,37 +244,39 @@ class Network:
|
|
|
244
244
|
def update_history(self, solution: Optional[NativeSolution]) -> None:
|
|
245
245
|
"""Update internal history from a simulation result.
|
|
246
246
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
247
|
+
Slices ``solution.ys`` down to the integrated state variables (by name,
|
|
248
|
+
using ``solution.variable_names``) so delay lookups and ``initial_state``
|
|
249
|
+
see ``[n_time, len(STATE_NAMES), n_nodes]`` regardless of the dynamics'
|
|
250
|
+
VARIABLES_OF_INTEREST. Also warns if time coverage < max_delay.
|
|
251
251
|
|
|
252
252
|
Args:
|
|
253
|
-
solution:
|
|
253
|
+
solution: Solution from a previous simulation, or None to clear history.
|
|
254
|
+
Must carry ``variable_names`` — all solve() paths populate this.
|
|
254
255
|
|
|
255
256
|
Raises:
|
|
256
|
-
ValueError: If solution shape
|
|
257
|
+
ValueError: If the solution shape is not 3D, lacks ``variable_names``,
|
|
258
|
+
is missing any entry of ``dynamics.STATE_NAMES``, or has an
|
|
259
|
+
n_nodes mismatch with the graph.
|
|
257
260
|
"""
|
|
258
261
|
if solution is None:
|
|
259
262
|
self._history = None
|
|
260
263
|
return
|
|
261
264
|
|
|
262
|
-
# Validate shape
|
|
263
265
|
if solution.ys.ndim != 3:
|
|
264
266
|
raise ValueError(
|
|
265
|
-
f"History must be 3D [n_time,
|
|
267
|
+
f"History must be 3D [n_time, n_variables, n_nodes], "
|
|
266
268
|
f"got shape {solution.ys.shape}"
|
|
267
269
|
)
|
|
268
270
|
|
|
269
|
-
|
|
271
|
+
state_names = tuple(self.dynamics.STATE_NAMES)
|
|
270
272
|
n_nodes = self.graph.n_nodes
|
|
271
|
-
_,
|
|
273
|
+
_, hist_vars, hist_nodes = solution.ys.shape
|
|
274
|
+
variable_names = solution.variable_names
|
|
272
275
|
|
|
273
|
-
|
|
274
|
-
if hist_states != n_states:
|
|
276
|
+
if variable_names is None:
|
|
275
277
|
raise ValueError(
|
|
276
|
-
|
|
277
|
-
|
|
278
|
+
"Cannot update history: solution.variable_names is None. "
|
|
279
|
+
"Construct the solution via solve() or pass variable_names explicitly."
|
|
278
280
|
)
|
|
279
281
|
|
|
280
282
|
if hist_nodes != n_nodes:
|
|
@@ -282,7 +284,21 @@ class Network:
|
|
|
282
284
|
f"History has {hist_nodes} nodes but network has {n_nodes} nodes"
|
|
283
285
|
)
|
|
284
286
|
|
|
285
|
-
|
|
287
|
+
if hist_vars != len(variable_names):
|
|
288
|
+
raise ValueError(
|
|
289
|
+
f"History axis 1 has {hist_vars} entries but variable_names "
|
|
290
|
+
f"has {len(variable_names)}: {variable_names}"
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
missing = [name for name in state_names if name not in variable_names]
|
|
294
|
+
if missing:
|
|
295
|
+
raise ValueError(
|
|
296
|
+
f"Cannot update history: solution is missing state variables "
|
|
297
|
+
f"{missing}. Recorded variables: {variable_names}. "
|
|
298
|
+
f"Include all STATE_NAMES {state_names} in the dynamics' "
|
|
299
|
+
f"VARIABLES_OF_INTEREST before running the simulation."
|
|
300
|
+
)
|
|
301
|
+
|
|
286
302
|
if self.max_delay > 0.0:
|
|
287
303
|
time_coverage = solution.ts[-1] - solution.ts[0]
|
|
288
304
|
if time_coverage < self.max_delay:
|
|
@@ -292,7 +308,15 @@ class Network:
|
|
|
292
308
|
UserWarning,
|
|
293
309
|
)
|
|
294
310
|
|
|
295
|
-
|
|
311
|
+
state_cols = [variable_names.index(name) for name in state_names]
|
|
312
|
+
sliced_ys = solution.ys[:, jnp.array(state_cols, dtype=int), :]
|
|
313
|
+
|
|
314
|
+
self._history = NativeSolution(
|
|
315
|
+
ts=solution.ts,
|
|
316
|
+
ys=sliced_ys,
|
|
317
|
+
dt=getattr(solution, "dt", None),
|
|
318
|
+
variable_names=state_names,
|
|
319
|
+
)
|
|
296
320
|
|
|
297
321
|
def prepare(self, dt: float, t0: float, t1: float) -> tuple[Bunch, Bunch]:
|
|
298
322
|
"""Prepare all couplings for simulation.
|
{tvboptim-0.2.7 → tvboptim-0.2.9}/src/tvboptim/experimental/network_dynamics/dynamics/base.py
RENAMED
|
@@ -178,6 +178,30 @@ class AbstractDynamics(ABC):
|
|
|
178
178
|
else:
|
|
179
179
|
return jnp.broadcast_to(initial[:, None], (self.N_STATES, n_nodes))
|
|
180
180
|
|
|
181
|
+
def set_variables_of_interest(
|
|
182
|
+
self, variables_of_interest: Tuple[Union[str, int], ...]
|
|
183
|
+
) -> None:
|
|
184
|
+
"""Update which variables are recorded in the trajectory output.
|
|
185
|
+
|
|
186
|
+
Validates the new selection against STATE_NAMES + AUXILIARY_NAMES and
|
|
187
|
+
assigns it. Any previously prepared model captured the old selection
|
|
188
|
+
and must be rebuilt by calling ``prepare()`` again.
|
|
189
|
+
|
|
190
|
+
Args:
|
|
191
|
+
variables_of_interest: Tuple of variable names or indices to record.
|
|
192
|
+
Empty tuple means "record all state variables" (default behavior).
|
|
193
|
+
|
|
194
|
+
Raises:
|
|
195
|
+
ValueError: If any entry is not a valid name or in-range index.
|
|
196
|
+
"""
|
|
197
|
+
previous = self.VARIABLES_OF_INTEREST
|
|
198
|
+
self.VARIABLES_OF_INTEREST = tuple(variables_of_interest)
|
|
199
|
+
try:
|
|
200
|
+
self.get_variables_of_interest_indices()
|
|
201
|
+
except ValueError as e:
|
|
202
|
+
self.VARIABLES_OF_INTEREST = previous
|
|
203
|
+
raise ValueError(f"Invalid VARIABLES_OF_INTEREST: {e}")
|
|
204
|
+
|
|
181
205
|
def get_variables_of_interest_indices(self) -> Tuple[int, ...]:
|
|
182
206
|
"""Get indices of variables to record.
|
|
183
207
|
|
|
@@ -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)
|