diff --git a/CHANGELOG.md b/CHANGELOG.md index 9333c58..6a201e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -97,6 +97,18 @@ aims to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - See `docs/basics/agent_skill.qmd` for the supported clients, the scopes, the Python API, and how to place the files by hand. +- **Derived parameters for dynamics.** A model declares `DERIVED_PARAMS` and + implements `derived_params(params)`; the values are computed once per solve + on every solve path and merged into the `params` that `dynamics()` receives, + with gradients flowing to the primary parameters. Derived values never live + in `config.dynamics`. `model.resolve_params(params)` exposes them for + inspection and direct `dynamics()` calls. +- Added `dynamics.tvb.ReducedSetFitzHughNagumo`, a TVB port whose mode + coefficients are derived from `mu` and `sigma`, so the population + heterogeneity can be swept and fitted. +- Added `SumLinearCoupling` and `DelayedSumLinearCoupling`, which sum their + source states before transport into one channel. + ### Changed - Clarified block-size-dependent stochastic noise, executor compilation reuse, @@ -121,9 +133,21 @@ aims to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). depended on the population time constant. At the default `tau = 1.0` this is a no-op, so existing results and TVB parity are unaffected; only runs with `tau != 1` change. +- **Elementwise couplings emit one channel per source state.** `LinearCoupling`, + `DifferenceCoupling`, `KuramotoCoupling`, the sigmoid and tanh couplings and + their delayed variants declare `N_OUTPUT_STATES = PER_SOURCE`, so + `LinearCoupling(source=("r", "V"))` feeds a 2-channel input. Single-source + use is unchanged. Minor breaking change: a subclass of one of these whose + `pre()` combines states must now declare its own `N_OUTPUT_STATES`; the error + says so. ### Fixed +- `Network` now checks each coupling's channel count against the model's + `COUPLING_INPUTS`. Previously a too-narrow coupling was clamped silently, so + e.g. `MontbrioPazoRoxin` with `LinearCoupling(source="r")` received its + r-coupling as V-coupling. Heterogeneous routes check against their readout + width. - BOLD monitors support custom streaming downsamplers with persistent state and live parameters, and arbitrary callable downsamplers post-hoc. - The deprecated `streaming_hrf_bold` reducer now resolves solution-valued warm diff --git a/docs/_quarto.yml b/docs/_quarto.yml index 4377f70..e2198f3 100644 --- a/docs/_quarto.yml +++ b/docs/_quarto.yml @@ -205,6 +205,7 @@ quartodoc: - tvb.WongWangExcInh - tvb.WilsonCowan - tvb.MontbrioPazoRoxin + - tvb.ReducedSetFitzHughNagumo - tvb.CoombesByrne2D - tvb.LarterBreakspear - tvb.Epileptor @@ -217,6 +218,8 @@ quartodoc: - LinearCoupling - FastLinearCoupling - DelayedLinearCoupling + - SumLinearCoupling + - DelayedSumLinearCoupling - DifferenceCoupling - DelayedDifferenceCoupling - SigmoidalJansenRit diff --git a/docs/_sidebar.yml b/docs/_sidebar.yml index 71f5d37..e3f57f0 100644 --- a/docs/_sidebar.yml +++ b/docs/_sidebar.yml @@ -74,6 +74,7 @@ website: - reference/tvb.WongWangExcInh.qmd - reference/tvb.WilsonCowan.qmd - reference/tvb.MontbrioPazoRoxin.qmd + - reference/tvb.ReducedSetFitzHughNagumo.qmd - reference/tvb.CoombesByrne2D.qmd - reference/tvb.LarterBreakspear.qmd - reference/tvb.Epileptor.qmd @@ -83,6 +84,8 @@ website: - reference/LinearCoupling.qmd - reference/FastLinearCoupling.qmd - reference/DelayedLinearCoupling.qmd + - reference/SumLinearCoupling.qmd + - reference/DelayedSumLinearCoupling.qmd - reference/DifferenceCoupling.qmd - reference/DelayedDifferenceCoupling.qmd - reference/SigmoidalJansenRit.qmd diff --git a/docs/basics/parameters_and_optimization.qmd b/docs/basics/parameters_and_optimization.qmd index f2f2bbd..53fe0f8 100644 --- a/docs/basics/parameters_and_optimization.qmd +++ b/docs/basics/parameters_and_optimization.qmd @@ -196,6 +196,30 @@ p_opt, _ = opt.run(p_custom, max_steps=1000) print("Optimized parameter:", p_opt) print("Smaller than 1:", p_opt < 1.0) ``` + +### Fitting a derived quantity + +Sometimes the quantity you want to fit is not the one the model is written in. A model may use a rate `a` while you want to fit the time constant `tau = 1 / a`. Instead of changing the model, wrap `a` in a `TransformedParameter` whose leaf is `tau`. The optimizer updates `tau`, and the model keeps seeing `a`. + +```{python} +# The model uses the rate a, but we want to fit the time constant tau = 1 / a. +a = TransformedParameter( + 0.02, forward_transform=lambda tau: 1.0 / tau, inverse_transform=lambda a: 1.0 / a +) +print("Stored leaf (tau):", a.value) +print("Value the model sees (a):", a.constrained_value) + +# Fit toward a target rate of 0.04, i.e. tau = 25. +def rate_loss(a): + return (a - 0.04) ** 2 + +a_opt, _ = OptaxOptimizer(rate_loss, optax.adam(0.5)).run(a, max_steps=200) +print("Fitted tau:", a_opt.value) +print("Fitted a:", a_opt.constrained_value) +``` + +In a simulation, place it like any other parameter, e.g. `config.dynamics.a = TransformedParameter(...)`. Gradients and optimizer steps then act on `tau`, so choose learning rates in `tau` units. The mapping has to be invertible and depend only on that one parameter. If the derived quantity combines several fitted parameters, express the model in the quantity you want to fit instead. + ## Batched fitting: starts, seeds, and observations `Space` controls **which values vary between fits**. `Parameter` controls **which diff --git a/docs/network_dynamics/coupling.qmd b/docs/network_dynamics/coupling.qmd index bb8274e..6b5a4be 100644 --- a/docs/network_dynamics/coupling.qmd +++ b/docs/network_dynamics/coupling.qmd @@ -197,6 +197,26 @@ def pre(self, incoming_states, local_states, params): This enables synchronization dynamics where coupling strength depends on state mismatch. +## Output Channels + +Each coupling input declares a width in `COUPLING_INPUTS`, and its coupling must produce exactly that many channels. Elementwise couplings (`LinearCoupling`, `DifferenceCoupling`, `KuramotoCoupling` and their delayed variants) declare `N_OUTPUT_STATES = PER_SOURCE`: one channel per source state, in order: + +```python +# MontbrioPazoRoxin declares {"instant": 2, ...}: channel 0 from r, channel 1 from V +LinearCoupling(source=("r", "V"), G=0.5) +``` + +`SumLinearCoupling` and `DelayedSumLinearCoupling` add their source states before transport and produce one channel, for inputs defined on a sum of states: + +```python +# ReducedSetFitzHughNagumo: one input, the coupled sum of the three xi modes +SumLinearCoupling(source=("xi1", "xi2", "xi3"), G=0.5) +``` + +This equals summing the channels of `LinearCoupling` with the same sources, with one transport instead of one per source. + +A custom coupling whose `pre()` combines states sets `N_OUTPUT_STATES` to the number of channels it returns, as `SigmoidalJansenRit` does for `y1 - y2`. `Network` raises when a coupling's channel count differs from the declared input width. + # Node and Edge Message Paths The framework selects the scalable transport representation from the coupling contract: @@ -529,6 +549,7 @@ Coupling enables inter-region communication in brain networks: - **Performance**: Incoming-only transforms use node messages; delays, target-local math, and edge parameters use aligned edge messages (O(E) on sparse graphs) - **Delays**: Computed from tract lengths and conduction speed; managed automatically via history buffers with increased computational cost - **Multiple couplings**: Named dictionary with automatic zero-filling for missing inputs +- **Channels**: One output channel per source state for elementwise couplings, `SumLinearCoupling` to sum states, checked against `COUPLING_INPUTS` - **Custom couplings**: Subclass `InstantaneousCoupling` or `DelayedCoupling` and override `pre()`/`post()` Coupling integrates with [Dynamics](dynamics.qmd) through named inputs and with [Graph](graph.qmd) through connectivity structure. Together they define collective network behavior. diff --git a/docs/network_dynamics/dynamics.qmd b/docs/network_dynamics/dynamics.qmd index 7d03fb0..b50656f 100644 --- a/docs/network_dynamics/dynamics.qmd +++ b/docs/network_dynamics/dynamics.qmd @@ -111,6 +111,8 @@ class MyDynamics(AbstractDynamics): **Parameters** (`DEFAULT_PARAMS`): Model-specific constants that can be overridden at instantiation. +**Derived Parameters** (`DERIVED_PARAMS`): Names of values the model computes from its parameters in `derived_params()`. They are recomputed once per solve, so they always track the live parameters, but they cannot be set or fitted directly. See [Derived Parameters](#derived-parameters). + **Coupling Inputs** (`COUPLING_INPUTS`): Declares which named coupling inputs the model expects and their dimensionality. Missing couplings are automatically filled with zeros. **Variables of Interest** (`VARIABLES_OF_INTEREST`): Controls which variables are saved during simulation: @@ -364,6 +366,63 @@ plt.show() The FitzHugh-Nagumo model exhibits classic excitable dynamics: subthreshold perturbations decay back to rest, while suprathreshold perturbations trigger a large-amplitude "spike" - the computational basis of neural coding. +## Derived Parameters + +Some models use quantities that are functions of their parameters: products of gains and rates, sample points of a distribution, integrals over mode partitions. Declare their names in `DERIVED_PARAMS` and compute them in `derived_params()`. The framework calls the hook once per solve, before the time loop, and merges the result into the `params` that `dynamics()` receives: + +```{python} +class TimescaleFitzHughNagumo(FitzHughNagumo): + """FitzHugh-Nagumo written in terms of a recovery rate.""" + + DERIVED_PARAMS = ("eps", "a_eps") + + def derived_params(self, params): + eps = 1.0 / params.tau + return Bunch(eps=eps, a_eps=params.a * eps) + + def dynamics(self, t, state, params, coupling, external): + V, W = state[0], state[1] + I_mem = V - (V**3 / 3.0) - W + dV_dt = I_mem + params.I + coupling.structural[0] + dW_dt = params.eps * V + params.a_eps - params.b * params.eps * W + return jnp.array([dV_dt, dW_dt]), jnp.array([I_mem]) + +fhn_eps = TimescaleFitzHughNagumo() +fhn_eps.verify(n_nodes=1) +``` + +Users of the model set, sweep and fit the primary parameters (`tau` here) as usual. `config.dynamics` holds only primary values, so the derived ones can never go stale, and gradients flow through the hook to the primary parameters. To inspect derived values, or to call `dynamics()` directly, resolve the parameters first: + +```{python} +resolved = fhn_eps.resolve_params(fhn_eps.params) +print("eps =", resolved.eps, " a_eps =", resolved.a_eps) +``` + +`resolve_params()` returns a new `Bunch` and leaves its input untouched; resolve again after changing a primary value. + +Rules for the hook: + +- Return a `Bunch` with exactly the names in `DERIVED_PARAMS`, and only those. Primary values are merged in by the framework. +- Keep it pure JAX: read from `params`, not `self.params`, and do not mutate anything. Constants fixed in `__init__` may be read from `self`. One derived value may use another through a local variable. +- Shapes are the model's responsibility. The hook sees the parameters as they are (scalar, per node, or per group in a heterogeneous network) and should reject shapes it does not support. + +Setting a derived value, for example `TimescaleFitzHughNagumo(eps=0.1)` or `config.dynamics.eps = 0.1`, raises an error that names the primary parameters to use instead. If a derived quantity should be free, make it a primary parameter in a subclass: + +```{python} +class FreeRateFitzHughNagumo(TimescaleFitzHughNagumo): + DEFAULT_PARAMS = Bunch(eps=0.08) # eps is now primary + DERIVED_PARAMS = ("a_eps",) + + def derived_params(self, params): + return Bunch(a_eps=params.a * params.eps) +``` + +`DERIVED_PARAMS` follows ordinary inheritance: omit it to inherit, define it to replace (`()` removes all derived values). To extend a parent, add to its tuple and merge `super().derived_params(params)` with the new values. If you want to fit a quantity that is an invertible function of a single parameter without changing the model, see [Fitting a derived quantity](../basics/parameters_and_optimization.qmd#fitting-a-derived-quantity). + +`ReducedSetFitzHughNagumo` is a shipped model built this way: its mode coefficients are integrals over the input distribution $\mathcal{N}(\mu, \sigma)$, recomputed from `mu` and `sigma` once per solve, so the population heterogeneity can be swept or fitted by gradient descent. Couple it with `SumLinearCoupling(source=("xi1", "xi2", "xi3"))`. + +Cheap scalar arithmetic like the example above can just as well stay inline in `dynamics()`. The hook pays off for clarity, for parity with models defined that way in TVB, and for expensive derivations (matrices, integrals) under gradients, where computing them once per solve avoids repeating their backward pass at every step. + # Available Dynamics Models TVB-Optim includes several canonical models from computational neuroscience: @@ -377,6 +436,7 @@ TVB-Optim includes several canonical models from computational neuroscience: | `WilsonCowan` | 2 | Neural mass | E/I populations | Population dynamics, pattern formation | | `Epileptor` | 6 | Neural mass | Seizure dynamics | Epilepsy modeling, bifurcations | | `Kuramoto` | 1 | Phase model | Synchronization | Phase coupling, oscillator networks | +| `ReducedSetFitzHughNagumo` | 12 | Mode reduction | Heterogeneous FHN population, derived parameters | Fitting population heterogeneity (`mu`, `sigma`) | See the [API Reference](../reference/index.qmd) for complete parameter descriptions and mathematical details. @@ -387,6 +447,7 @@ Dynamics models define the local temporal evolution at each network node: - **Built-in models** cover common use cases from chaotic systems to biophysical neural masses - **Auxiliary variables** must be explicitly included in `VARIABLES_OF_INTEREST` to be recorded - **Custom dynamics** are straightforward to implement by subclassing `AbstractDynamics` +- **Derived parameters** (`DERIVED_PARAMS` + `derived_params()`) are computed once per solve from the live parameters - **Parameter customization** enables model configuration without modifying source code (e.g., adjusting `I` in FitzHugh-Nagumo to control excitability) - **Standalone methods** (`verify()`, `simulate()`, `plot()`) enable testing before network integration diff --git a/src/tvboptim/experimental/network_dynamics/core/heterogeneous.py b/src/tvboptim/experimental/network_dynamics/core/heterogeneous.py index dc2456e..993f06e 100644 --- a/src/tvboptim/experimental/network_dynamics/core/heterogeneous.py +++ b/src/tvboptim/experimental/network_dynamics/core/heterogeneous.py @@ -385,13 +385,16 @@ def _validate_routes(self): f"on group {group_name!r}; expected " f"{list(dynamics.COUPLING_INPUTS)}" ) - if conversion is None: + # Callable-only sources have unknown width; prepare() checks them. + if conversion is None and known_widths: expected = dynamics.COUPLING_INPUTS[input_name] - if route.coupling.N_OUTPUT_STATES != expected: + produced = route.coupling.n_output_channels( + next(iter(known_widths)) + ) + if produced != expected: raise ValueError( - f"route {route_name!r} outputs " - f"{route.coupling.N_OUTPUT_STATES} channels but " - f"{group_name!r}.{input_name} expects {expected}; " + f"route {route_name!r} outputs {produced} channels " + f"but {group_name!r}.{input_name} expects {expected}; " "provide an explicit conversion" ) diff --git a/src/tvboptim/experimental/network_dynamics/core/network.py b/src/tvboptim/experimental/network_dynamics/core/network.py index 82fa29b..d699686 100644 --- a/src/tvboptim/experimental/network_dynamics/core/network.py +++ b/src/tvboptim/experimental/network_dynamics/core/network.py @@ -9,7 +9,7 @@ import jax.numpy as jnp -from ..coupling.base import AbstractCoupling +from ..coupling.base import PER_SOURCE, AbstractCoupling from ..dynamics.base import AbstractDynamics from ..graph.base import AbstractGraph, delay_steps_bound, effective_max_delay from ..graph.topology import prepare_graph_topology, validate_graph_topology @@ -21,6 +21,36 @@ from ..external_input.base import AbstractExternalInput +def _check_output_channels( + name: str, coupling: AbstractCoupling, dynamics: AbstractDynamics +) -> None: + """Raise if a coupling's channel count differs from the declared input.""" + source = coupling.SOURCE_STATE_NAMES + names = (source,) if isinstance(source, str) else tuple(source) + produced = coupling.n_output_channels(len(names)) + expected = dynamics.COUPLING_INPUTS[name] + if produced == expected: + return + if coupling.N_OUTPUT_STATES is PER_SOURCE: + hint = ( + f"{coupling.__class__.__name__} outputs one channel per source " + f"state; pass {expected} source state(s), or use a coupling that " + "combines states (e.g. SumLinearCoupling). A pre() that combines " + "states must declare N_OUTPUT_STATES." + ) + else: + hint = ( + f"{coupling.__class__.__name__} has a fixed N_OUTPUT_STATES = " + f"{coupling.N_OUTPUT_STATES}." + ) + raise ValueError( + f"Coupling {name!r} ({coupling.__class__.__name__}, source={names}) " + f"outputs {produced} channel(s), but " + f"{dynamics.__class__.__name__}.COUPLING_INPUTS[{name!r}] expects " + f"{expected}. {hint}" + ) + + class Network: """Unified network class for all equation types (ODE/DDE/SDE/SDDE). @@ -106,6 +136,7 @@ def __init__( "in an ordinary Network. Selector-free couplings are only " "valid inside a heterogeneous SignalRoute." ) + _check_output_channels(name, value, dynamics) # Normalize external input to dict format with validation diff --git a/src/tvboptim/experimental/network_dynamics/coupling/__init__.py b/src/tvboptim/experimental/network_dynamics/coupling/__init__.py index 98a26fb..ed17ac4 100644 --- a/src/tvboptim/experimental/network_dynamics/coupling/__init__.py +++ b/src/tvboptim/experimental/network_dynamics/coupling/__init__.py @@ -1,6 +1,7 @@ """Coupling functions for network interactions.""" from .base import ( + PER_SOURCE, AbstractCoupling, BufferStrategy, DelayedCoupling, @@ -10,14 +11,17 @@ from .linear import ( DelayedDifferenceCoupling, DelayedLinearCoupling, + DelayedSumLinearCoupling, DifferenceCoupling, FastLinearCoupling, LinearCoupling, + SumLinearCoupling, ) from .subspace import SubspaceCoupling from .tvb import DelayedSigmoidalJansenRit, SigmoidalJansenRit __all__ = [ + "PER_SOURCE", "AbstractCoupling", "InstantaneousCoupling", "BufferStrategy", @@ -27,6 +31,8 @@ "SigmoidalJansenRit", "DelayedSigmoidalJansenRit", "DelayedLinearCoupling", + "SumLinearCoupling", + "DelayedSumLinearCoupling", "DelayedDifferenceCoupling", "FastLinearCoupling", "SubspaceCoupling", diff --git a/src/tvboptim/experimental/network_dynamics/coupling/base.py b/src/tvboptim/experimental/network_dynamics/coupling/base.py index 8197d13..36fd2e2 100644 --- a/src/tvboptim/experimental/network_dynamics/coupling/base.py +++ b/src/tvboptim/experimental/network_dynamics/coupling/base.py @@ -8,7 +8,7 @@ import warnings from abc import ABC, abstractmethod -from typing import Literal, Optional, Tuple +from typing import Literal, Optional, Tuple, Union import jax import jax.numpy as jnp @@ -18,6 +18,27 @@ BufferStrategy = Literal["roll", "circular", "preallocated"] + +class _PerSource: + """Marker for ``N_OUTPUT_STATES``: one output channel per source state.""" + + __slots__ = () + + def __repr__(self) -> str: + return "PER_SOURCE" + + def __reduce__(self): + return "PER_SOURCE" + + def __copy__(self): + return self + + def __deepcopy__(self, memo): + return self + + +PER_SOURCE = _PerSource() + _PRE_CONTRACT_MIGRATION = ( "pre() must be elementwise over the final message axes: remove explicit " "[:, :, None] / [None, :, :] reshapes and declare PRE_USES_LOCAL or " @@ -51,11 +72,13 @@ class AbstractCoupling(ABC): and the standard matrix multiplication patterns don't apply (e.g., SubspaceCoupling). Attributes: - N_OUTPUT_STATES: Number of output states after coupling + N_OUTPUT_STATES: Number of output channels. ``PER_SOURCE`` (default) + means one channel per source state, as for elementwise couplings; a + coupling whose ``pre()`` combines states declares a fixed int. DEFAULT_PARAMS: Default coupling parameters as a Bunch """ - N_OUTPUT_STATES: int = 0 + N_OUTPUT_STATES: Union[int, _PerSource] = PER_SOURCE DEFAULT_PARAMS: Bunch = Bunch() def __init__( @@ -132,6 +155,17 @@ def _resolve_state_alias(new_value, legacy_value, new_name, legacy_name): ) return legacy_value + def n_output_channels(self, n_source: int) -> int: + """Number of output channels when ``n_source`` states are transported.""" + if self.N_OUTPUT_STATES is PER_SOURCE: + return n_source + return self.N_OUTPUT_STATES + + def _describe_output_channels(self) -> str: + if self.N_OUTPUT_STATES is PER_SOURCE: + return "one channel per source state" + return f"N_OUTPUT_STATES = {self.N_OUTPUT_STATES}" + @property def INCOMING_STATE_NAMES(self): """Deprecated alias for :attr:`SOURCE_STATE_NAMES` (removed in 1.0).""" @@ -405,13 +439,24 @@ def _validate_pre_contract(self, graph, incoming_idx, local_idx, dtype) -> None: f"{_PRE_CONTRACT_MIGRATION}" ) from exc - expected = (self.N_OUTPUT_STATES, *message_shape) - if not hasattr(result, "shape") or tuple(result.shape) != expected: - actual = getattr(result, "shape", type(result).__name__) + n_out = self.n_output_channels(n_incoming) + expected = (n_out, *message_shape) + actual = tuple(getattr(result, "shape", ())) + if actual == expected: + return + name = self.__class__.__name__ + if len(actual) == len(expected) and actual[1:] == tuple(message_shape): raise ValueError( - f"{self.__class__.__name__}.pre() returned shape {actual}; " - f"expected {expected}. {_PRE_CONTRACT_MIGRATION}" + f"{name}.pre() returned {actual[0]} channels for {n_incoming} " + f"source states; expected {n_out} " + f"({self._describe_output_channels()}). Set N_OUTPUT_STATES to " + "the number of channels pre() returns." ) + shown = actual if hasattr(result, "shape") else type(result).__name__ + raise ValueError( + f"{name}.pre() returned shape {shown}; expected {expected}. " + f"{_PRE_CONTRACT_MIGRATION}" + ) def precompute( self, @@ -565,7 +610,7 @@ def pre( params: Coupling parameters Returns: - Transformed messages [N_OUTPUT_STATES, *message_shape]. + Transformed messages [n_output_channels, *message_shape]. """ return incoming_states diff --git a/src/tvboptim/experimental/network_dynamics/coupling/kuramoto.py b/src/tvboptim/experimental/network_dynamics/coupling/kuramoto.py index a1fb0b6..6a4e1f9 100644 --- a/src/tvboptim/experimental/network_dynamics/coupling/kuramoto.py +++ b/src/tvboptim/experimental/network_dynamics/coupling/kuramoto.py @@ -9,7 +9,7 @@ import jax.numpy as jnp from ..core.bunch import Bunch -from .base import DelayedCoupling, InstantaneousCoupling +from .base import PER_SOURCE, DelayedCoupling, InstantaneousCoupling class KuramotoCoupling(InstantaneousCoupling): @@ -24,12 +24,12 @@ class KuramotoCoupling(InstantaneousCoupling): source : str or list of str State name(s) to collect from connected nodes (typically ``'theta'``) local : str or list of str - State name(s) from current node (required for the phase difference) + State name(s) from current node, paired in order with ``source`` Attributes ---------- - N_OUTPUT_STATES : int - Number of output coupling states: ``1`` + N_OUTPUT_STATES : PER_SOURCE + One output channel per source state DEFAULT_PARAMS : Bunch Default parameters: ``G=1.0`` (global coupling strength) @@ -43,7 +43,7 @@ class KuramotoCoupling(InstantaneousCoupling): >>> coupling = KuramotoCoupling(source='theta', local='theta', G=1.0) """ - N_OUTPUT_STATES = 1 + N_OUTPUT_STATES = PER_SOURCE DEFAULT_PARAMS = Bunch(G=1.0) PRE_USES_LOCAL = True @@ -96,12 +96,12 @@ class DelayedKuramotoCoupling(DelayedCoupling): source : str or list of str State name(s) to collect from connected nodes (typically ``'theta'``) local : str or list of str - State name(s) from current node (required for the phase difference) + State name(s) from current node, paired in order with ``source`` Attributes ---------- - N_OUTPUT_STATES : int - Number of output coupling states: ``1`` + N_OUTPUT_STATES : PER_SOURCE + One output channel per source state DEFAULT_PARAMS : Bunch Default parameters: ``G=1.0`` (global coupling strength) @@ -124,7 +124,7 @@ class DelayedKuramotoCoupling(DelayedCoupling): Royal Society A, 377(2153), 20180132. """ - N_OUTPUT_STATES = 1 + N_OUTPUT_STATES = PER_SOURCE DEFAULT_PARAMS = Bunch(G=1.0) PRE_USES_LOCAL = True diff --git a/src/tvboptim/experimental/network_dynamics/coupling/linear.py b/src/tvboptim/experimental/network_dynamics/coupling/linear.py index b148e1f..cc881a5 100644 --- a/src/tvboptim/experimental/network_dynamics/coupling/linear.py +++ b/src/tvboptim/experimental/network_dynamics/coupling/linear.py @@ -11,7 +11,7 @@ import jax.numpy as jnp from ..core.bunch import Bunch -from .base import DelayedCoupling, InstantaneousCoupling +from .base import PER_SOURCE, DelayedCoupling, InstantaneousCoupling class LinearCoupling(InstantaneousCoupling): @@ -34,8 +34,8 @@ class LinearCoupling(InstantaneousCoupling): Attributes ---------- - N_OUTPUT_STATES : int - Number of output coupling states: ``1`` + N_OUTPUT_STATES : PER_SOURCE + One output channel per source state DEFAULT_PARAMS : Bunch Default parameters: ``G=1.0`` (global coupling strength), ``b=0.0`` (offset/bias) @@ -48,7 +48,7 @@ class LinearCoupling(InstantaneousCoupling): >>> coupling = LinearCoupling(source='x', G=0.5, b=0.1) """ - N_OUTPUT_STATES = 1 + N_OUTPUT_STATES = PER_SOURCE DEFAULT_PARAMS = Bunch(G=1.0, b=0.0) # No pre() override: the default identity runs on source-node messages. @@ -75,6 +75,43 @@ def post( return params.G * summed_inputs + params.b +class SumLinearCoupling(LinearCoupling): + """Linear coupling of the sum of several source states. + + Adds the source states of each sending node before transport, giving one + output channel: + + $$c_i = G \\cdot \\sum_{j} w_{ij} \\sum_{s} x_{s,j} + b$$ + + Equivalent to summing the channels of ``LinearCoupling`` with the same + sources, at the cost of a single transport. + + Parameters + ---------- + source : list of str + State names to sum on each sending node (required) + + Attributes + ---------- + N_OUTPUT_STATES : int + Number of output coupling states: ``1`` + DEFAULT_PARAMS : Bunch + Default parameters: ``G=1.0`` (global coupling strength), ``b=0.0`` (offset/bias) + + Examples + -------- + >>> coupling = SumLinearCoupling(source=("xi1", "xi2", "xi3"), G=0.1) + """ + + N_OUTPUT_STATES = 1 + + def pre( + self, incoming_states: jnp.ndarray, local_states: jnp.ndarray, params: Bunch + ) -> jnp.ndarray: + """Sum the source states into one message ``[1, *M]``.""" + return incoming_states.sum(axis=0, keepdims=True) + + class FastLinearCoupling(LinearCoupling): """Deprecated compatibility spelling for :class:`LinearCoupling`. @@ -135,12 +172,12 @@ class DifferenceCoupling(InstantaneousCoupling): source : str or list of str State name(s) to collect from connected nodes (required) local : str or list of str - State name(s) from current node (required for computing differences) + State name(s) from current node, paired in order with ``source`` Attributes ---------- - N_OUTPUT_STATES : int - Number of output coupling states: ``1`` + N_OUTPUT_STATES : PER_SOURCE + One output channel per source state DEFAULT_PARAMS : Bunch Default parameters: ``G=1.0`` (global coupling strength) @@ -150,7 +187,7 @@ class DifferenceCoupling(InstantaneousCoupling): >>> coupling = DifferenceCoupling(source='x', local='x', G=1.0) """ - N_OUTPUT_STATES = 1 + N_OUTPUT_STATES = PER_SOURCE DEFAULT_PARAMS = Bunch(G=1.0) PRE_USES_LOCAL = True @@ -205,8 +242,8 @@ class SigmoidCoupling(InstantaneousCoupling): Attributes ---------- - N_OUTPUT_STATES : int - Number of output coupling states: ``1`` + N_OUTPUT_STATES : PER_SOURCE + One output channel per source state DEFAULT_PARAMS : Bunch Default parameters: ``G=1.0`` (global coupling strength), ``a=1.0`` (input scaling), ``b=0.0`` (offset), ``slope=1.0`` (sigmoid steepness), ``midpoint=0.0`` (sigmoid center) @@ -216,7 +253,7 @@ class SigmoidCoupling(InstantaneousCoupling): >>> coupling = SigmoidCoupling(source='x', G=1.0, slope=2.0, midpoint=0.0) """ - N_OUTPUT_STATES = 1 + N_OUTPUT_STATES = PER_SOURCE DEFAULT_PARAMS = Bunch(G=1.0, a=1.0, b=0.0, slope=1.0, midpoint=0.0) def post( @@ -258,8 +295,8 @@ class TanhCoupling(InstantaneousCoupling): Attributes ---------- - N_OUTPUT_STATES : int - Number of output coupling states: ``1`` + N_OUTPUT_STATES : PER_SOURCE + One output channel per source state DEFAULT_PARAMS : Bunch Default parameters: ``G=0.5`` (global coupling strength), ``scale=2.0`` (scaling before tanh) @@ -268,7 +305,7 @@ class TanhCoupling(InstantaneousCoupling): >>> coupling = TanhCoupling(source='x', G=0.5, scale=2.0) """ - N_OUTPUT_STATES = 1 + N_OUTPUT_STATES = PER_SOURCE DEFAULT_PARAMS = Bunch(G=0.5, scale=2.0) def post( @@ -308,8 +345,8 @@ class DelayedLinearCoupling(DelayedCoupling): Attributes ---------- - N_OUTPUT_STATES : int - Number of output coupling states: ``1`` + N_OUTPUT_STATES : PER_SOURCE + One output channel per source state DEFAULT_PARAMS : Bunch Default parameters: ``G=1.0`` (coupling strength), ``b=0.0`` (offset/bias) @@ -318,7 +355,7 @@ class DelayedLinearCoupling(DelayedCoupling): >>> coupling = DelayedLinearCoupling(source='S', G=1.0) """ - N_OUTPUT_STATES = 1 + N_OUTPUT_STATES = PER_SOURCE DEFAULT_PARAMS = Bunch(G=1.0, b=0.0) def post( @@ -337,6 +374,39 @@ def post( return params.G * summed_inputs + params.b +class DelayedSumLinearCoupling(DelayedLinearCoupling): + """Delayed linear coupling of the sum of several source states. + + Delayed counterpart of ``SumLinearCoupling``: + + $$c_i(t) = G \\cdot \\sum_{j} w_{ij} \\sum_{s} x_{s,j}(t - \\tau_{ij}) + b$$ + + Parameters + ---------- + source : list of str + State names to sum on each sending node (required) + + Attributes + ---------- + N_OUTPUT_STATES : int + Number of output coupling states: ``1`` + DEFAULT_PARAMS : Bunch + Default parameters: ``G=1.0`` (coupling strength), ``b=0.0`` (offset/bias) + + Examples + -------- + >>> coupling = DelayedSumLinearCoupling(source=("xi1", "xi2", "xi3"), G=0.1) + """ + + N_OUTPUT_STATES = 1 + + def pre( + self, delayed_states: jnp.ndarray, local_states: jnp.ndarray, params: Bunch + ) -> jnp.ndarray: + """Sum the delayed source states into one message ``[1, *M]``.""" + return delayed_states.sum(axis=0, keepdims=True) + + class DelayedDifferenceCoupling(DelayedCoupling): """Diffusive coupling with transmission delays. @@ -353,12 +423,12 @@ class DelayedDifferenceCoupling(DelayedCoupling): source : str or list of str State name(s) to collect from connected nodes (required) local : str or list of str - State name(s) from current node (required for computing differences) + State name(s) from current node, paired in order with ``source`` Attributes ---------- - N_OUTPUT_STATES : int - Number of output coupling states: ``1`` + N_OUTPUT_STATES : PER_SOURCE + One output channel per source state DEFAULT_PARAMS : Bunch Default parameters: ``G=1.0`` (global coupling strength) @@ -367,7 +437,7 @@ class DelayedDifferenceCoupling(DelayedCoupling): >>> coupling = DelayedDifferenceCoupling(source='x', local='x', G=1.0) """ - N_OUTPUT_STATES = 1 + N_OUTPUT_STATES = PER_SOURCE DEFAULT_PARAMS = Bunch(G=1.0) PRE_USES_LOCAL = True @@ -420,8 +490,8 @@ class DelayedSigmoidCoupling(DelayedCoupling): Attributes ---------- - N_OUTPUT_STATES : int - Number of output coupling states: ``1`` + N_OUTPUT_STATES : PER_SOURCE + One output channel per source state DEFAULT_PARAMS : Bunch Default parameters: ``G=1.0`` (global coupling strength), ``slope=1.0`` (sigmoid steepness), ``midpoint=0.0`` (sigmoid center) @@ -431,7 +501,7 @@ class DelayedSigmoidCoupling(DelayedCoupling): >>> coupling = DelayedSigmoidCoupling(source='x', G=1.0, slope=1.0, midpoint=0.0) """ - N_OUTPUT_STATES = 1 + N_OUTPUT_STATES = PER_SOURCE DEFAULT_PARAMS = Bunch(G=1.0, slope=1.0, midpoint=0.0) def post( diff --git a/src/tvboptim/experimental/network_dynamics/dynamics/base.py b/src/tvboptim/experimental/network_dynamics/dynamics/base.py index 9b38641..7c377ef 100644 --- a/src/tvboptim/experimental/network_dynamics/dynamics/base.py +++ b/src/tvboptim/experimental/network_dynamics/dynamics/base.py @@ -5,13 +5,17 @@ """ from abc import ABC, abstractmethod -from typing import Optional, Tuple, Union +from typing import Mapping, Optional, Tuple, Union import jax.numpy as jnp from diffrax import Dopri5, ODETerm, SaveAt, diffeqsolve from ..core.bunch import Bunch +_REPARAMETERIZATION_DOCS = ( + "docs/basics/parameters_and_optimization.qmd ('Fitting a derived quantity')" +) + class AbstractDynamics(ABC): """Abstract base class for neural dynamics models with multi-coupling support. @@ -30,6 +34,9 @@ class AbstractDynamics(ABC): Names of auxiliary (non-integrated) variables DEFAULT_PARAMS : Bunch Default parameter values as Bunch object + DERIVED_PARAMS : tuple of str + Names of values computed from the parameters by ``derived_params``. + They are never set, swept or optimized directly. COUPLING_INPUTS : dict Dictionary of expected coupling inputs ``{name: n_dims}`` EXTERNAL_INPUTS : dict @@ -47,6 +54,7 @@ class AbstractDynamics(ABC): # Parameters DEFAULT_PARAMS: Bunch = Bunch() + DERIVED_PARAMS: Tuple[str, ...] = () # NEW: Multi-coupling support COUPLING_INPUTS: dict = {} # e.g., {'structural': 1, 'modulatory': 1} @@ -95,6 +103,12 @@ def __init__(self, **kwargs): # Create instance parameters by copying defaults and updating with kwargs self.params = self.DEFAULT_PARAMS.copy() for key, value in kwargs.items(): + if key in self.DERIVED_PARAMS: + raise ValueError( + f"'{key}' is computed by {self.__class__.__name__}; set its " + f"primary parameters instead. Primary parameters: " + f"{list(self.DEFAULT_PARAMS.keys())}" + ) if key not in self.DEFAULT_PARAMS: raise ValueError( f"Unknown parameter '{key}' for {self.__class__.__name__}. " @@ -138,6 +152,39 @@ def __init_subclass__(cls, **kwargs): if len(cls.STATE_NAMES) != len(cls.INITIAL_STATE): raise ValueError(f"{cls.__name__}: len(STATE_NAMES) != len(INITIAL_STATE)") + # DERIVED_PARAMS uses ordinary attribute inheritance, unlike the + # "empty means inherit" block above: an explicit () must be able to + # replace a parent declaration when a value is promoted to primary. + cls._validate_derived_declaration() + + @classmethod + def _validate_derived_declaration(cls) -> None: + """Check DERIVED_PARAMS format, disjointness and hook presence.""" + names = cls.DERIVED_PARAMS + if not isinstance(names, tuple) or not all(isinstance(n, str) for n in names): + raise TypeError( + f"{cls.__name__}.DERIVED_PARAMS must be a tuple of strings, " + f"e.g. ('gain',); got {names!r}" + ) + duplicates = sorted({n for n in names if names.count(n) > 1}) + if duplicates: + raise ValueError( + f"{cls.__name__}.DERIVED_PARAMS has duplicate names: {duplicates}" + ) + overlap = [n for n in names if n in cls.DEFAULT_PARAMS] + if overlap: + raise ValueError( + f"{cls.__name__}: {overlap} appear in both DEFAULT_PARAMS and " + f"DERIVED_PARAMS. A value is either primary or derived; to make " + f"a derived value free, remove it from DERIVED_PARAMS and from " + f"the derived_params() output." + ) + if names and cls.derived_params is AbstractDynamics.derived_params: + raise TypeError( + f"{cls.__name__} declares DERIVED_PARAMS={names} but does not " + f"implement or inherit derived_params()." + ) + @property def all_variable_names(self) -> Tuple[str, ...]: """All variable names (integrated + auxiliary).""" @@ -281,6 +328,91 @@ def name_to_index(self, names: Union[str, Tuple[str, ...], list]) -> jnp.ndarray else: raise ValueError(f"names must be str, list, or tuple, got {type(names)}") + def derived_params(self, params: Bunch) -> Bunch: + """Compute derived values from the live parameters. + + Override this to return a ``Bunch`` with exactly the names in + ``DERIVED_PARAMS``. Only derived values are returned; the framework + merges them with the primary parameters before calling ``dynamics()``. + + The hook runs inside jit/grad/vmap once per solve, so it must be pure + JAX: read parameters from ``params`` (not ``self.params``) and do not + mutate the input or the instance. Constants fixed at construction time + may be read from ``self``. + + Parameters + ---------- + params : Bunch + Primary parameters, e.g. ``config.dynamics``. + + Returns + ------- + Bunch + Derived values keyed by the names in ``DERIVED_PARAMS``. + """ + return Bunch() + + def resolve_params(self, params: Mapping, location: Optional[str] = None) -> Bunch: + """Return primary and derived parameters as one ``Bunch``. + + This is what ``dynamics()`` receives during a solve. Use it to inspect + derived values or to call ``dynamics()`` directly. Not meant to be + overridden; implement ``derived_params`` instead. + + Parameters + ---------- + params : Bunch + Primary parameters, e.g. ``model.params`` or ``config.dynamics``. + Must not contain derived names. + location : str, optional + Where ``params`` came from (e.g. ``"config.dynamics"``), used in + error messages. + + Returns + ------- + Bunch + A new ``Bunch``; ``params`` is left untouched. For models without + derived parameters, ``params`` is returned unchanged. + + Examples + -------- + >>> resolved = model.resolve_params(config.dynamics) + >>> model.dynamics(t, state, resolved, coupling, external) + """ + if type(self).derived_params is AbstractDynamics.derived_params: + return params + + name = self.__class__.__name__ + where = f" in {location}" if location else "" + derived_names = self.DERIVED_PARAMS + + given = [n for n in derived_names if n in params] + if given: + raise ValueError( + f"{given}{where} are computed by {name}.derived_params() and " + f"cannot be set, swept or optimized directly. Set or fit the " + f"primary parameters instead. To fit a derived quantity, " + f"reparameterize the model; see {_REPARAMETERIZATION_DOCS}." + ) + + derived = self.derived_params(params) + if not isinstance(derived, Bunch): + raise TypeError( + f"{name}.derived_params() must return a Bunch, " + f"got {type(derived).__name__}" + ) + missing = [n for n in derived_names if n not in derived] + extra = [n for n in derived if n not in derived_names] + if missing or extra: + raise ValueError( + f"{name}.derived_params() must return exactly DERIVED_PARAMS=" + f"{derived_names}; missing {missing}, unexpected {extra}" + ) + + resolved = Bunch(params) + resolved.update(derived) + return resolved + @abstractmethod def dynamics( self, @@ -299,7 +431,8 @@ def dynamics( state : jnp.ndarray Current state with shape ``[N_STATES, n_nodes]`` params : Bunch - Model parameters as Bunch object (supports broadcasting) + Model parameters as Bunch object (supports broadcasting). Includes + derived values, see ``resolve_params``. coupling : Bunch Named coupling inputs accessed as attributes (e.g., ``coupling.structural``, ``coupling.modulatory``). Missing couplings are automatically filled with zeros. @@ -343,7 +476,7 @@ def verify(self, n_nodes: int = 1, verbose: bool = True) -> bool: try: # Get test inputs state = self.get_default_initial_state(n_nodes) - params = self.params + params = self.resolve_params(self.params, "model.params") # Create coupling Bunch with zeros for all declared inputs coupling = Bunch() @@ -428,7 +561,7 @@ def simulate( t1: End time dt: Time step for output n_nodes: Number of nodes to simulate - params: Parameters (default: self.params) + params: Primary parameters (default: self.params) initial_state: Initial state (default: from get_default_initial_state) solver: Diffrax solver (default: Dopri5) **solver_kwargs: Additional solver arguments @@ -439,6 +572,7 @@ def simulate( """ if params is None: params = self.params + params = self.resolve_params(params) if initial_state is None: initial_state = self.get_default_initial_state(n_nodes) diff --git a/src/tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py b/src/tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py index 62fff62..549c3b2 100644 --- a/src/tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py +++ b/src/tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py @@ -8,6 +8,7 @@ from .larter_breakspear import LarterBreakspear from .linear import Linear from .montbrio_pazo_roxin import MontbrioPazoRoxin +from .reduced_set import ReducedSetFitzHughNagumo from .sup_hopf import SupHopf from .wilson_cowan import WilsonCowan from .wong_wang import ReducedWongWang @@ -22,6 +23,7 @@ "LarterBreakspear", "Linear", "MontbrioPazoRoxin", + "ReducedSetFitzHughNagumo", "SupHopf", "WilsonCowan", "ReducedWongWang", diff --git a/src/tvboptim/experimental/network_dynamics/dynamics/tvb/reduced_set.py b/src/tvboptim/experimental/network_dynamics/dynamics/tvb/reduced_set.py new file mode 100644 index 0000000..4cd2303 --- /dev/null +++ b/src/tvboptim/experimental/network_dynamics/dynamics/tvb/reduced_set.py @@ -0,0 +1,209 @@ +"""Reduced set of FitzHugh-Nagumo oscillators (Stefanescu & Jirsa 2008).""" + +import jax.numpy as jnp +import numpy as np +from jax.scipy.stats import norm + +from ...core.bunch import Bunch +from ..base import AbstractDynamics + +_N_MODES = 3 +_MODE_STATES = ("xi", "eta", "alpha", "beta") + + +def _mode_indicators(n_samples: int) -> np.ndarray: + """Partition ``n_samples`` sample points into equally sized modes.""" + per_mode = n_samples // _N_MODES + indicators = np.zeros((_N_MODES, n_samples)) + for i in range(_N_MODES): + indicators[i, i * per_mode : (i + 1) * per_mode] = 1.0 + return indicators + + +def _scalar(model: str, name: str, value) -> jnp.ndarray: + value = jnp.asarray(value) + if value.size != 1: + raise ValueError( + f"{model}: '{name}' must be a scalar (the population distribution " + f"is shared by all nodes); got shape {value.shape}" + ) + return value.reshape(()) + + +class ReducedSetFitzHughNagumo(AbstractDynamics): + """Mode decomposition of a heterogeneous population of FitzHugh-Nagumo neurons. + + Each node models a population of excitatory and inhibitory FitzHugh-Nagumo + oscillators whose input currents are normally distributed with mean ``mu`` + and standard deviation ``sigma``. The population is reduced to three modes + per subpopulation [Stefanescu & Jirsa 2008]. Port of TVB's + ``ReducedSetFitzHughNagumo``. + + Notes + ----- + **State equations** for mode $i$ (sums over modes $k$): + + $$ + \\begin{aligned} + \\dot{\\xi}_i &= \\tau\\left(\\xi_i - e_i\\frac{\\xi_i^3}{3} - \\eta_i\\right) + + K_{11}\\left(\\sum_k A_{ki}\\xi_k - \\xi_i\\right) + - K_{12}\\left(\\sum_k B_{ki}\\alpha_k - \\xi_i\\right) + + \\tau\\left(I^E_i + c\\right) \\\\ + \\dot{\\eta}_i &= \\left(\\xi_i - b\\eta_i + m_i\\right) / \\tau \\\\ + \\dot{\\alpha}_i &= \\tau\\left(\\alpha_i - f_i\\frac{\\alpha_i^3}{3} - \\beta_i\\right) + + K_{21}\\left(\\sum_k C_{ki}\\xi_k - \\alpha_i\\right) + + \\tau\\left(I^I_i + c\\right) \\\\ + \\dot{\\beta}_i &= \\left(\\alpha_i - b\\beta_i + n_i\\right) / \\tau + \\end{aligned} + $$ + + where $c$ is the network input to the summed $\\xi$ modes. + + **Derived parameters.** The mode coefficients $A, B, C, e, f, I^E, I^I, + m, n$ are integrals of the mode functions against the input distribution + $\\mathcal{N}(\\mu, \\sigma)$. They are computed from ``mu``, ``sigma`` and + ``a`` once per solve by ``derived_params``, so ``mu`` and ``sigma`` can be + swept or fitted by gradient descent. Inspect them with + ``model.resolve_params(model.params)``. + + **Layout.** TVB's ``(4, nodes, modes)`` state is flattened to 12 states + ordered ``xi1..3, eta1..3, alpha1..3, beta1..3``. Per-mode derived values + have shape ``(3, 1)``; ``Aik``, ``Bik``, ``Cik`` keep TVB's ``(3, 3)`` layout. + + **Coupling.** As in TVB, the network input is the coupled sum of the three + $\\xi$ modes and drives every mode. ``SumLinearCoupling`` sums the modes + before transport: + + ```python + coupling = {"instant": SumLinearCoupling(source=("xi1", "xi2", "xi3"))} + ``` + + ``mu`` and ``sigma`` must be scalars. ``a``, ``b``, ``tau`` and the + ``K`` gains may be per node. + + Parameters + ---------- + nv, nu : int + Number of sample points of the excitatory and inhibitory input + distributions (default 1500). They set array shapes, so they are + constructor arguments rather than parameters, and must be divisible + by 3. + **kwargs + Parameter overrides, see ``DEFAULT_PARAMS``. + """ + + STATE_NAMES = tuple( + f"{name}{i}" for name in _MODE_STATES for i in range(1, _N_MODES + 1) + ) + INITIAL_STATE = (0.0,) * (len(_MODE_STATES) * _N_MODES) + + DEFAULT_PARAMS = Bunch( + tau=3.0, # Time-scale separation + a=0.45, + b=0.9, + K11=0.5, # Internal coupling, excitatory to excitatory + K12=0.15, # Internal coupling, inhibitory to excitatory + K21=0.15, # Internal coupling, excitatory to inhibitory + sigma=0.35, # Standard deviation of the input distribution + mu=0.0, # Mean of the input distribution + ) + + DERIVED_PARAMS = ("Aik", "Bik", "Cik", "e_i", "f_i", "IE_i", "II_i", "m_i", "n_i") + + COUPLING_INPUTS = { + "instant": 1, # Coupled sum of the xi modes + "delayed": 1, + } + + def __init__(self, nv: int = 1500, nu: int = 1500, **kwargs): + for name, n in (("nv", nv), ("nu", nu)): + if not isinstance(n, int) or n <= 0 or n % _N_MODES: + raise ValueError( + f"{self.__class__.__name__}: {name} must be a positive int " + f"divisible by {_N_MODES}, got {n!r}" + ) + super().__init__(**kwargs) + self.nv, self.nu = nv, nu + # Quantile levels and mode partitions depend only on the sample counts. + self._pv = np.arange(1, nv + 1) / (nv + 1) + self._pu = np.arange(1, nu + 1) / (nu + 1) + self._V = _mode_indicators(nv) + self._U = _mode_indicators(nu) + + def derived_params(self, params: Bunch) -> Bunch: + name = self.__class__.__name__ + mu = _scalar(name, "mu", params.mu) + sigma = _scalar(name, "sigma", params.sigma) + trapz = jnp.trapezoid + + Zv = norm.ppf(self._pv, loc=mu, scale=sigma) + Zu = norm.ppf(self._pu, loc=mu, scale=sigma) + V = self._V / jnp.sqrt(trapz(self._V**2, Zv, axis=1))[:, None] + U = self._U / jnp.sqrt(trapz(self._U**2, Zu, axis=1))[:, None] + g1 = norm.pdf(Zv, loc=mu, scale=sigma) + g2 = norm.pdf(Zu, loc=mu, scale=sigma) + + int_V = trapz(V, Zv, axis=1)[:, None] # (modes, 1) + int_U = trapz(U, Zu, axis=1)[:, None] + int_g1V = trapz(g1 * V, Zv, axis=1)[None, :] # (1, modes) + int_g2U = trapz(g2 * U, Zu, axis=1)[None, :] + + return Bunch( + Aik=(int_V @ int_g1V).T, + Bik=int_V @ int_g2U, + Cik=(int_U @ int_g1V).T, + e_i=trapz(V**4, Zv, axis=1)[:, None], + f_i=trapz(U**4, Zu, axis=1)[:, None], + IE_i=trapz(Zv * V, Zv, axis=1)[:, None], + II_i=trapz(Zu * U, Zu, axis=1)[:, None], + m_i=params.a * int_V, + n_i=params.a * int_U, + ) + + def dynamics( + self, + t: float, + state: jnp.ndarray, + params: Bunch, + coupling: Bunch, + external: Bunch, + ) -> jnp.ndarray: + """Compute the reduced FitzHugh-Nagumo dynamics. + + Parameters + ---------- + t : float + Current time (unused for autonomous system) + state : jnp.ndarray + Current state with shape ``[12, n_nodes]`` + params : Bunch + Primary and derived parameters (see ``resolve_params``) + coupling : Bunch + Coupling inputs ``.instant`` and ``.delayed``, each ``[1, n_nodes]`` + (coupled sum of the xi modes) + external : Bunch + External inputs (unused) + + Returns + ------- + jnp.ndarray + State derivatives with shape ``[12, n_nodes]`` + """ + xi, eta, alpha, beta = jnp.split(state, len(_MODE_STATES)) + c = coupling.instant[0] + coupling.delayed[0] + tau = params.tau + + dxi = ( + tau * (xi - params.e_i * xi**3 / 3.0 - eta) + + params.K11 * (params.Aik.T @ xi - xi) + - params.K12 * (params.Bik.T @ alpha - xi) + + tau * (params.IE_i + c) + ) + deta = (xi - params.b * eta + params.m_i) / tau + dalpha = ( + tau * (alpha - params.f_i * alpha**3 / 3.0 - beta) + + params.K21 * (params.Cik.T @ xi - alpha) + + tau * (params.II_i + c) + ) + dbeta = (alpha - params.b * beta + params.n_i) / tau + return jnp.concatenate((dxi, deta, dalpha, dbeta)) diff --git a/src/tvboptim/experimental/network_dynamics/solve.py b/src/tvboptim/experimental/network_dynamics/solve.py index 5515f55..e3119a0 100644 --- a/src/tvboptim/experimental/network_dynamics/solve.py +++ b/src/tvboptim/experimental/network_dynamics/solve.py @@ -293,6 +293,8 @@ def _native_output_sample( """Describe one assembled native output through the real prepared inputs.""" def output(): + resolved_params = dynamics.resolve_params(params, "config.dynamics") + def dynamics_fn(t, state, current_params): return dynamics.dynamics( t, @@ -307,7 +309,7 @@ def dynamics_fn(t, state, current_params): jnp.asarray(t0), initial_state, dt, - params, + resolved_params, jnp.zeros_like(initial_state), ) return _assemble_output( @@ -1325,14 +1327,22 @@ def prepare( source_mask = source_mask.at[nodes].set(1) coupling_data._source_mask = source_mask + n_route_channels = route.coupling.n_output_channels(source_width) target_specs = [] for group_name in sorted(route.target): input_name, conversion = route.target[group_name] nodes = jnp.asarray(network.group_nodes[group_name], dtype=int) n_group_nodes = len(network.group_nodes[group_name]) + n_expected = network.groups[group_name].dynamics.COUPLING_INPUTS[input_name] + if conversion is None and n_route_channels != n_expected: + raise ValueError( + f"route {route_name!r} outputs {n_route_channels} channels " + f"but {group_name!r}.{input_name} expects {n_expected}; " + "provide an explicit conversion" + ) if conversion is not None: signal = jax.ShapeDtypeStruct( - (route.coupling.N_OUTPUT_STATES, n_group_nodes), signal_dtype + (n_route_channels, n_group_nodes), signal_dtype ) try: converted = jax.eval_shape( @@ -1620,8 +1630,15 @@ def _f(config): grouped_state0[topology_anchor_group], ) enriched = precompute_routes(config) + # Resolve derived parameters once per solve; the solver forwards the + # resolved values to every stage. dynamics_params = Bunch( - {name: config.groups[name].dynamics for name in network.group_names} + { + name: network.groups[name].dynamics.resolve_params( + config.groups[name].dynamics, f"config.groups.{name}.dynamics" + ) + for name in network.group_names + } ) streaming = ( @@ -2308,6 +2325,11 @@ def _f(config): # This allows parameter-dependent quantities (e.g. W_eff = W * wLRE) to # be computed with gradient flow while avoiding per-step redundancy. enriched = precompute_all_couplings(config) + # Resolve derived parameters once per solve; the solver forwards the + # resolved values to every stage. + dynamics_params = network.dynamics.resolve_params( + config.dynamics, "config.dynamics" + ) # Noise source. Streaming (per-block fold_in) activates when blocking is # on, the network has noise, and no full tensor is injected: it skips the @@ -2408,7 +2430,7 @@ def wrapped_dynamics(t_inner, network_state, params_dynamics): # Solver integration step using pre-compiled function references # Returns (next_state, auxiliaries) next_dynamics_state, auxiliaries = solver_step( - wrapped_dynamics, t, state.dynamics, dt, config.dynamics, noise_sample + wrapped_dynamics, t, state.dynamics, dt, dynamics_params, noise_sample ) # Use pre-compiled closure for coupling state updates @@ -2756,6 +2778,9 @@ def _f(config): # This allows parameter-dependent quantities (e.g. W_eff = W * wLRE) to # be computed with gradient flow while avoiding per-step redundancy. enriched = precompute_all_couplings(config) + dynamics_params = network.dynamics.resolve_params( + config.dynamics, "config.dynamics" + ) def vector_field(t, y, args): """Diffrax-compatible vector field: f(t, y, args) -> dy/dt.""" @@ -2767,7 +2792,7 @@ def vector_field(t, y, args): # Call dynamics result = dynamics_fn( - t, y, config.dynamics, coupling_inputs, external_inputs + t, y, dynamics_params, coupling_inputs, external_inputs ) # Extract derivatives (discard auxiliaries if present) @@ -3036,6 +3061,9 @@ def probe_external_inputs(_t, _state): def _f(config): """Pure integration function for bare dynamics.""" + # Resolve derived parameters once per solve; the solver forwards the + # resolved values to every stage. + dynamics_params = dynamics.resolve_params(config.dynamics, "config.dynamics") # Noise source. Streaming (per-block fold_in) activates when blocking is # on, the dynamics has noise, and no full tensor is injected; otherwise @@ -3096,7 +3124,7 @@ def wrapped_dynamics(t_inner, s, params): noise_sample = jnp.zeros_like(state) next_state, auxiliaries = solver_step( - wrapped_dynamics, t, state, dt, config.dynamics, noise_sample + wrapped_dynamics, t, state, dt, dynamics_params, noise_sample ) # VOI filtering @@ -3298,13 +3326,14 @@ def compute_all_externals(t, state, config): def _f(config): """Pure integration function using Diffrax for bare dynamics.""" + dynamics_params = dynamics.resolve_params(config.dynamics, "config.dynamics") def vector_field(t, y, args): if has_externals: ext_inputs = compute_all_externals(t, y, config) else: ext_inputs = zero_external - result = dynamics_fn(t, y, config.dynamics, zero_coupling, ext_inputs) + result = dynamics_fn(t, y, dynamics_params, zero_coupling, ext_inputs) if isinstance(result, tuple): derivatives, _ = result else: diff --git a/src/tvboptim/experimental/network_dynamics/utils/printer.py b/src/tvboptim/experimental/network_dynamics/utils/printer.py index 29991d0..1dfb3eb 100644 --- a/src/tvboptim/experimental/network_dynamics/utils/printer.py +++ b/src/tvboptim/experimental/network_dynamics/utils/printer.py @@ -216,6 +216,9 @@ def _format_parameters(self) -> str: param_items.append(f"{key}={value}") lines = ["Parameters", "-" * 50, " " + ", ".join(param_items)] + derived = getattr(self.network.dynamics, "DERIVED_PARAMS", ()) + if derived: + lines.append(f" Derived: {', '.join(derived)}") return "\n".join(lines) @@ -277,6 +280,8 @@ def _format_groups(self) -> str: ) if hasattr(dynamics, "params") and dynamics.params: lines.append(f" Parameters: {self._format_params(dynamics.params)}") + if getattr(dynamics, "DERIVED_PARAMS", ()): + lines.append(f" Derived: {', '.join(dynamics.DERIVED_PARAMS)}") lines.append("") return "\n".join(lines).rstrip() @@ -467,7 +472,13 @@ def format(self) -> str: # Annotate source with coupling descriptions annotated = self._annotate_source(source, coupling_usage) - lines = ["Dynamics Equations", "-" * 50, annotated] + lines = ["Dynamics Equations", "-" * 50] + if getattr(self.dynamics, "DERIVED_PARAMS", ()): + derived = inspect.getsource(self.dynamics.derived_params) + derived = self._remove_docstring(derived) + derived = self._collapse_function_signature(derived) + lines.extend([derived.rstrip(), ""]) + lines.append(annotated) return "\n".join(lines) diff --git a/src/tvboptim/skills/tvboptim/references/custom-dynamics-and-coupling.md b/src/tvboptim/skills/tvboptim/references/custom-dynamics-and-coupling.md index 1c2af59..d2f916e 100644 --- a/src/tvboptim/skills/tvboptim/references/custom-dynamics-and-coupling.md +++ b/src/tvboptim/skills/tvboptim/references/custom-dynamics-and-coupling.md @@ -20,6 +20,7 @@ Declare the interface at class level: - `STATE_NAMES` and equal-length `INITIAL_STATE` for integrated variables; - `DEFAULT_PARAMS` as a `Bunch`; +- optional `DERIVED_PARAMS`, names of values computed from the parameters by `derived_params()`; - optional `AUXILIARY_NAMES` for derived, non-integrated outputs; - `COUPLING_INPUTS = {name: dimension}`; - optional `EXTERNAL_INPUTS = {name: dimension}`; @@ -57,6 +58,8 @@ assert model.verify(n_nodes=2) Declared but unsupplied coupling and external inputs are zero-filled by the solve/network layer. Passing an unknown parameter to the constructor, or an unknown coupling key to `Network`, is an error. Do not hide misspellings with permissive dictionaries. +Use `derived_params(self, params)` for parameter-dependent quantities that `dynamics()` needs, the dynamics counterpart of coupling `precompute`. Return a `Bunch` with exactly the names in `DERIVED_PARAMS`; the solve path calls it once per forward call and merges the result into the `params` that `dynamics()` receives. Read from `params`, not `self.params`. Derived values never live in `config.dynamics` and cannot be set, swept or fitted; fit the primary parameters, or promote a quantity to `DEFAULT_PARAMS` in a subclass when it should be free. Direct calls to `dynamics()` need `model.resolve_params(params)` first. Cheap scalar arithmetic can stay inline in `dynamics()`. `dynamics.tvb.ReducedSetFitzHughNagumo` is a worked example with matrix-valued derived parameters. + Use `model.verify()` as an interface check, then simulate bare dynamics to test numerical behavior without graph complexity: ```python @@ -126,6 +129,8 @@ Test progressively: When the dynamics declares several coupling channels, provide a dictionary keyed by those declarations. It is valid to omit a declared channel only when a zero input is intentional. +A coupling must produce as many channels as its input declares in `COUPLING_INPUTS`. Elementwise couplings (`LinearCoupling`, `DifferenceCoupling`, `KuramotoCoupling` and delayed variants) declare `N_OUTPUT_STATES = PER_SOURCE`, one channel per source state, so a 2-channel input takes `source=("r", "V")`. `SumLinearCoupling` sums its source states into one channel. A custom `pre()` that combines states must declare `N_OUTPUT_STATES`. `Network` rejects mismatches. + ## Avoid common extension errors - Returning Python lists instead of stacked JAX arrays. @@ -133,6 +138,7 @@ When the dynamics declares several coupling channels, provide a dictionary keyed - Declaring auxiliaries but returning the wrong auxiliary count. - Saving an auxiliary without adding it to `VARIABLES_OF_INTEREST`. - Reading a coupling/external name not declared by the class. +- Putting a derived value into `DEFAULT_PARAMS` or `config.dynamics` instead of `DERIVED_PARAMS`, or reading `self.params` inside `derived_params()`. - Selecting `source` when `post` needs `local` state, or vice versa. - Writing the deprecated `incoming_states=`/`local_states=` keywords into new code. - Treating an instantaneous class as delayed because of a dictionary label. diff --git a/src/tvboptim/skills/tvboptim/references/heterogeneous-networks.md b/src/tvboptim/skills/tvboptim/references/heterogeneous-networks.md index 7665855..0413f72 100644 --- a/src/tvboptim/skills/tvboptim/references/heterogeneous-networks.md +++ b/src/tvboptim/skills/tvboptim/references/heterogeneous-networks.md @@ -70,7 +70,7 @@ route = SignalRoute( The route, not the coupling, owns signal selection. Construct the route's coupling **without** `source=` or `local=`; supplying either is an error. - `source` maps a group name to a state name, a tuple of state names, or a `readout(state, params) -> [Q, n_group_nodes]` callable. Every source readout on one route must emit the same channel count `Q`. -- `target` maps a group name to a coupling-input name, or to `(input_name, conversion)` where `conversion(signal, params)` transforms the target-local transported slice. Without a conversion, the coupling's `N_OUTPUT_STATES` must equal the target's declared `COUPLING_INPUTS[input_name]`. +- `target` maps a group name to a coupling-input name, or to `(input_name, conversion)` where `conversion(signal, params)` transforms the target-local transported slice. Without a conversion, the coupling's output channels (one per source channel `Q` for elementwise couplings, otherwise its `N_OUTPUT_STATES`) must equal the target's declared `COUPLING_INPUTS[input_name]`. - `local` supplies target-local readouts and is required exactly when the coupling sets `PRE_USES_LOCAL`, as `DifferenceCoupling` does. Supplying it for a coupling that does not use local signals is an error. - `source_params`, `local_params`, and `target_params` hold per-group readout parameters. They stay separate so a target-only group can carry local-readout parameters and so source and local readouts on one group do not share a namespace. diff --git a/src/tvboptim/types/parameter.py b/src/tvboptim/types/parameter.py index 229a9df..0e266e3 100644 --- a/src/tvboptim/types/parameter.py +++ b/src/tvboptim/types/parameter.py @@ -311,6 +311,9 @@ class TransformedParameter(Parameter): >>> forward = lambda x: jax.nn.sigmoid(x) # unconstrained → constrained >>> inverse = lambda x: jnp.log(x / (1 - x)) # constrained → unconstrained >>> param = TransformedParameter(0.7, forward, inverse) + + >>> # Reparametrization: fit tau = 1 / a while the model sees the rate a + >>> param = TransformedParameter(0.02, lambda tau: 1.0 / tau, lambda a: 1.0 / a) """ def __init__( diff --git a/tests/test_network_dynamics/test_coupling_channels.py b/tests/test_network_dynamics/test_coupling_channels.py new file mode 100644 index 0000000..a7d7827 --- /dev/null +++ b/tests/test_network_dynamics/test_coupling_channels.py @@ -0,0 +1,226 @@ +"""Coupling output channels: one per source state, and checked against inputs.""" + +import copy +import pickle + +import jax.numpy as jnp +import pytest + +from tvboptim.experimental.network_dynamics import ( + Bunch, + HeterogeneousNetwork, + Network, + NodeGroup, + SignalRoute, + prepare, +) +from tvboptim.experimental.network_dynamics.coupling import ( + PER_SOURCE, + DelayedDifferenceCoupling, + DelayedKuramotoCoupling, + DelayedLinearCoupling, + DelayedSumLinearCoupling, + DifferenceCoupling, + KuramotoCoupling, + LinearCoupling, + SumLinearCoupling, +) +from tvboptim.experimental.network_dynamics.coupling.linear import ( + DelayedSigmoidCoupling, + SigmoidCoupling, + TanhCoupling, +) +from tvboptim.experimental.network_dynamics.dynamics.base import AbstractDynamics +from tvboptim.experimental.network_dynamics.graph import DenseDelayGraph, DenseGraph +from tvboptim.experimental.network_dynamics.solvers import Heun + +N_NODES = 4 +WEIGHTS = jnp.array( + [ + [0.0, 0.4, 0.1, 0.0], + [0.3, 0.0, 0.0, 0.5], + [0.2, 0.6, 0.0, 0.1], + [0.0, 0.2, 0.7, 0.0], + ] +) +DELAYS = jnp.array( + [ + [0.0, 0.3, 0.2, 0.0], + [0.3, 0.0, 0.0, 0.4], + [0.2, 0.1, 0.0, 0.3], + [0.0, 0.4, 0.3, 0.0], + ] +) + + +class Pair(AbstractDynamics): + """Two leaky states; channel ``i`` of ``c`` drives state ``i``.""" + + STATE_NAMES = ("x", "y") + INITIAL_STATE = (0.3, -0.2) + DEFAULT_PARAMS = Bunch(k=-0.5) + COUPLING_INPUTS = {"c": 2} + + def dynamics(self, t, state, params, coupling, external): + return params.k * state + jnp.tanh(coupling.c) + + +class PairSplit(Pair): + """``Pair`` with one input per state.""" + + COUPLING_INPUTS = {"cx": 1, "cy": 1} + + def dynamics(self, t, state, params, coupling, external): + c = jnp.concatenate([coupling.cx, coupling.cy]) + return params.k * state + jnp.tanh(c) + + +class PairShared(Pair): + """``Pair`` driven by the sum of both channels.""" + + def dynamics(self, t, state, params, coupling, external): + return params.k * state + jnp.tanh(coupling.c.sum(axis=0, keepdims=True)) + + +class PairSummed(Pair): + """``Pair`` with a single input, the sum over states.""" + + COUPLING_INPUTS = {"c": 1} + + +# (coupling class, uses local states, delayed) +ELEMENTWISE = [ + (LinearCoupling, False, False), + (DifferenceCoupling, True, False), + (SigmoidCoupling, False, False), + (TanhCoupling, False, False), + (KuramotoCoupling, True, False), + (DelayedLinearCoupling, False, True), + (DelayedDifferenceCoupling, True, True), + (DelayedSigmoidCoupling, False, True), + (DelayedKuramotoCoupling, True, True), +] +ELEMENTWISE_IDS = [cls.__name__ for cls, _, _ in ELEMENTWISE] + + +def _graph(delayed): + return DenseDelayGraph(WEIGHTS, DELAYS) if delayed else DenseGraph(WEIGHTS) + + +def _coupling(cls, uses_local, names): + return cls(source=names, local=names) if uses_local else cls(source=names) + + +def _solve(network): + solve_fn, config = prepare(network, Heun(), t1=2.0, dt=0.05) + return solve_fn(config).ys + + +@pytest.mark.parametrize("cls,uses_local,delayed", ELEMENTWISE, ids=ELEMENTWISE_IDS) +def test_multi_source_equals_one_coupling_per_source(cls, uses_local, delayed): + graph = _graph(delayed) + joint = Network(Pair(), {"c": _coupling(cls, uses_local, ("x", "y"))}, graph) + split = Network( + PairSplit(), + { + "cx": _coupling(cls, uses_local, "x"), + "cy": _coupling(cls, uses_local, "y"), + }, + graph, + ) + assert cls.N_OUTPUT_STATES is PER_SOURCE + assert joint.coupling["c"].n_output_channels(2) == 2 + assert jnp.allclose(_solve(joint), _solve(split), atol=1e-6) + + +@pytest.mark.parametrize( + "sum_cls,linear_cls,delayed", + [ + (SumLinearCoupling, LinearCoupling, False), + (DelayedSumLinearCoupling, DelayedLinearCoupling, True), + ], + ids=["instant", "delayed"], +) +def test_sum_linear_equals_summed_linear_channels(sum_cls, linear_cls, delayed): + graph = _graph(delayed) + summed = Network( + PairSummed(), {"c": sum_cls(source=("x", "y"), G=0.8, b=0.1)}, graph + ) + channels = Network( + PairShared(), {"c": linear_cls(source=("x", "y"), G=0.8, b=0.05)}, graph + ) + assert jnp.allclose(_solve(summed), _solve(channels), atol=1e-6) + + +class SumWithoutDeclaration(LinearCoupling): + def pre(self, incoming_states, local_states, params): + return incoming_states.sum(axis=0, keepdims=True) + + +@pytest.mark.parametrize( + "dynamics,coupling,match", + [ + (Pair(), LinearCoupling(source="x"), "outputs 1 channel.*expects 2"), + ( + Pair(), + SumLinearCoupling(source=("x", "y")), + "fixed N_OUTPUT_STATES = 1", + ), + ( + PairSummed(), + LinearCoupling(source=("x", "y")), + "outputs 2 channel.*SumLinearCoupling", + ), + ], + ids=["too-few-sources", "fixed-width", "too-many-sources"], +) +def test_network_rejects_channel_mismatch(dynamics, coupling, match): + with pytest.raises(ValueError, match=match): + Network(dynamics, {"c": coupling}, DenseGraph(WEIGHTS)) + + +def test_combining_pre_must_declare_its_channels(): + network = Network( + Pair(), {"c": SumWithoutDeclaration(source=("x", "y"))}, DenseGraph(WEIGHTS) + ) + with pytest.raises(ValueError, match="returned 1 channels for 2 source states"): + prepare(network, Heun(), t1=0.1, dt=0.05) + + +def _route_network(readout): + return HeterogeneousNetwork( + graph=DenseGraph(WEIGHTS), + groups={"all": NodeGroup(Pair(), jnp.arange(N_NODES))}, + routes={ + "r": SignalRoute( + source={"all": readout}, + coupling=LinearCoupling(), + target={"all": "c"}, + ) + }, + ) + + +def test_route_channels_follow_source_width(): + _solve(_route_network(("x", "y"))) + + +@pytest.mark.parametrize( + "readout,at_prepare", + [("x", False), (lambda state, params: state[0:1], True)], + ids=["names", "callable"], +) +def test_route_rejects_channel_mismatch(readout, at_prepare): + match = "outputs 1 channels but 'all'.c expects 2" + if at_prepare: + network = _route_network(readout) + with pytest.raises(ValueError, match=match): + _solve(network) + else: + with pytest.raises(ValueError, match=match): + _route_network(readout) + + +def test_per_source_marker_survives_copy_and_pickle(): + for clone in (copy.copy, copy.deepcopy, lambda m: pickle.loads(pickle.dumps(m))): + assert clone(PER_SOURCE) is PER_SOURCE diff --git a/tests/test_network_dynamics/test_declared_inputs_influence.py b/tests/test_network_dynamics/test_declared_inputs_influence.py index 465d111..c514f40 100644 --- a/tests/test_network_dynamics/test_declared_inputs_influence.py +++ b/tests/test_network_dynamics/test_declared_inputs_influence.py @@ -74,7 +74,8 @@ def vector_field(*blocks): coupling, external = Bunch(), Bunch() for (kind, name, _), block in zip(channels, blocks): (coupling if kind == "coupling" else external)[name] = block - out = model.dynamics(0.0, state, model.params, coupling, external) + params = model.resolve_params(model.params) + out = model.dynamics(0.0, state, params, coupling, external) return out[0] if isinstance(out, tuple) else out blocks = [jnp.zeros((n_dims, N_NODES)) for _, _, n_dims in channels] diff --git a/tests/test_network_dynamics/test_derived_params.py b/tests/test_network_dynamics/test_derived_params.py new file mode 100644 index 0000000..16835dc --- /dev/null +++ b/tests/test_network_dynamics/test_derived_params.py @@ -0,0 +1,482 @@ +"""Derived parameters: values computed from primary parameters once per solve. + +A model that declares ``DERIVED_PARAMS`` must behave exactly like the same +model computing those values inline in ``dynamics()``, on every dispatch path, +for trajectories and for gradients with respect to the primary parameters. +""" + +import diffrax +import jax +import jax.numpy as jnp +import numpy as np +import pytest + +from tvboptim.execution import ParallelExecution +from tvboptim.experimental.network_dynamics import ( + Bunch, + HeterogeneousNetwork, + Network, + NodeGroup, + prepare, +) +from tvboptim.experimental.network_dynamics.coupling import LinearCoupling +from tvboptim.experimental.network_dynamics.dynamics.base import AbstractDynamics +from tvboptim.experimental.network_dynamics.graph import DenseGraph +from tvboptim.experimental.network_dynamics.solvers import DiffraxSolver, Heun +from tvboptim.observations.tvb_monitors import SubSampling +from tvboptim.types import DataAxis, Space, TransformedParameter + +T1 = 1.0 +DT = 0.1 +N_NODES = 3 +WEIGHTS = jnp.array( + [ + [0.0, 0.4, 0.0, 0.2, 0.0], + [0.3, 0.0, 0.1, 0.0, 0.0], + [0.0, 0.2, 0.0, 0.0, 0.5], + [0.1, 0.0, 0.0, 0.0, 0.3], + [0.0, 0.0, 0.4, 0.2, 0.0], + ] +) + + +def _positive(value): + return TransformedParameter(value, jnp.exp, jnp.log) + + +class InlineLeak(AbstractDynamics): + """Reference: computes everything inside ``dynamics()``.""" + + STATE_NAMES = ("x",) + INITIAL_STATE = (0.5,) + DEFAULT_PARAMS = Bunch(tau=2.0, k=0.7) + COUPLING_INPUTS = {"drive": 1} + + def dynamics(self, t, state, params, coupling, external): + rate = 1.0 / params.tau + gain = jnp.tanh(params.k) * rate + return jnp.stack((-rate * state[0] + gain * coupling.drive[0] + 0.1,)) + + +class DerivedLeak(AbstractDynamics): + """Same model with ``rate`` and ``gain`` declared as derived values.""" + + STATE_NAMES = ("x",) + INITIAL_STATE = (0.5,) + DEFAULT_PARAMS = Bunch(tau=2.0, k=0.7) + DERIVED_PARAMS = ("rate", "gain") + COUPLING_INPUTS = {"drive": 1} + + def derived_params(self, params): + # gain depends on the other derived value through a local variable. + rate = 1.0 / params.tau + return Bunch(rate=rate, gain=jnp.tanh(params.k) * rate) + + def dynamics(self, t, state, params, coupling, external): + return jnp.stack( + (-params.rate * state[0] + params.gain * coupling.drive[0] + 0.1,) + ) + + +def _diffrax(): + return DiffraxSolver( + diffrax.Tsit5(), saveat=diffrax.SaveAt(ts=jnp.arange(0.0, T1, DT)) + ) + + +def _network(model_cls, n_nodes=N_NODES): + return Network( + dynamics=model_cls(tau=jnp.linspace(1.5, 3.0, n_nodes)), + coupling={"drive": LinearCoupling(source="x", G=0.5)}, + graph=DenseGraph(WEIGHTS[:n_nodes, :n_nodes]), + ) + + +def _heterogeneous(model_cls): + # Groups of different sizes with group-local (scalar) primary values. + return HeterogeneousNetwork( + graph=DenseGraph(WEIGHTS), + groups={ + "a": NodeGroup(model_cls(tau=1.5), [0, 2]), + "b": NodeGroup(model_cls(tau=3.0, k=0.2), [1, 3, 4]), + }, + ) + + +def _dynamics_locations(config): + """Primary-parameter Bunches of a config, flat or grouped.""" + if "groups" in config: + return [config.groups[name].dynamics for name in config.groups] + return [config.dynamics] + + +# (label, prepare(model_cls) -> (solve_fn, config)) +PATHS = [ + ( + "bare_native", + lambda cls: prepare(cls(), Heun(), t1=T1, dt=DT, n_nodes=N_NODES), + ), + ( + "bare_native_observe", + lambda cls: prepare( + cls(), + Heun(block_size=2), + t1=T1, + dt=DT, + n_nodes=N_NODES, + observe=SubSampling(period=0.2), + ), + ), + ( + "bare_diffrax", + lambda cls: prepare(cls(), _diffrax(), t1=T1, dt=DT, n_nodes=N_NODES), + ), + ("network_native", lambda cls: prepare(_network(cls), Heun(), t1=T1, dt=DT)), + ( + "network_native_observe", + lambda cls: prepare( + _network(cls), + Heun(block_size=2), + t1=T1, + dt=DT, + observe=SubSampling(period=0.2), + ), + ), + ("network_diffrax", lambda cls: prepare(_network(cls), _diffrax(), t1=T1, dt=DT)), + ( + "heterogeneous_native", + lambda cls: prepare(_heterogeneous(cls), Heun(), t1=T1, dt=DT), + ), +] +PATH_IDS = [label for label, _ in PATHS] + + +def _loss(solve_fn, config, tau_scale): + varied = config.copy() + for params in _dynamics_locations(varied): + params.tau = params.tau * tau_scale + leaves = jax.tree.leaves(solve_fn(varied).ys) + return sum(jnp.square(leaf).sum() for leaf in leaves) + + +@pytest.mark.parametrize("_label,build", PATHS, ids=PATH_IDS) +def test_derived_matches_inline_trajectories_and_gradients(_label, build): + inline_fn, inline_cfg = build(InlineLeak) + derived_fn, derived_cfg = build(DerivedLeak) + + jax.tree.map( + lambda a, b: np.testing.assert_allclose(a, b, rtol=1e-6, atol=1e-6), + inline_fn(inline_cfg).ys, + derived_fn(derived_cfg).ys, + ) + + inline_grad = jax.grad(lambda s: _loss(inline_fn, inline_cfg, s))(1.0) + derived_grad = jax.grad(lambda s: _loss(derived_fn, derived_cfg, s))(1.0) + assert inline_grad != 0.0 + np.testing.assert_allclose(derived_grad, inline_grad, rtol=1e-5) + + +@pytest.mark.parametrize("_label,build", PATHS, ids=PATH_IDS) +def test_config_holds_only_primary_parameters(_label, build): + _, config = build(DerivedLeak) + for params in _dynamics_locations(config): + assert set(params) == set(DerivedLeak.DEFAULT_PARAMS) + + +@pytest.mark.parametrize("_label,build", PATHS, ids=PATH_IDS) +def test_derived_name_in_config_is_rejected_with_location(_label, build): + solve_fn, config = build(DerivedLeak) + _dynamics_locations(config)[0].rate = 0.5 + expected = "config.groups.a.dynamics" if "groups" in config else "config.dynamics" + with pytest.raises(ValueError, match=rf"\['rate'\] in {expected}"): + solve_fn(config) + + +def test_space_sweep_over_primary_updates_derived_values(): + solve_fn, config = prepare(_network(DerivedLeak), Heun(), t1=T1, dt=DT) + inline_fn, inline_cfg = prepare(_network(InlineLeak), Heun(), t1=T1, dt=DT) + taus = jnp.array([1.0, 2.0, 4.0]) + + def final_mean(fn): + return lambda cfg: fn(cfg).ys[-1].mean() + + results = [] + for fn, cfg in ((solve_fn, config), (inline_fn, inline_cfg)): + swept = cfg.copy() + swept.dynamics.tau = DataAxis(taus) + execution = ParallelExecution(final_mean(fn), Space(swept), n_vmap=3, n_pmap=1) + results.append(np.asarray([np.asarray(v) for v in execution.run()])) + + derived, inline = results + np.testing.assert_allclose(derived, inline, rtol=1e-6) + assert len(np.unique(derived)) == len(taus), "derived value went stale" + + +# Model-level API -------------------------------------------------------------- + + +def test_resolve_params_merges_without_mutating_input(): + model = DerivedLeak(tau=4.0) + primary = model.params.copy() + resolved = model.resolve_params(model.params) + + assert dict(model.params) == dict(primary) + assert set(resolved) == {"tau", "k", "rate", "gain"} + np.testing.assert_allclose(resolved.rate, 0.25) + + model.params.tau = 2.0 + np.testing.assert_allclose(model.resolve_params(model.params).rate, 0.5) + + +def test_resolve_params_is_identity_without_derived_values(): + model = InlineLeak() + assert model.resolve_params(model.params) is model.params + + +def test_verify_and_simulate_resolve_derived_values(): + inline, derived = InlineLeak(), DerivedLeak() + assert derived.verify(n_nodes=2, verbose=False) + _, inline_ys = inline.simulate(t1=T1, dt=DT, n_nodes=2) + _, derived_ys = derived.simulate(t1=T1, dt=DT, n_nodes=2) + np.testing.assert_allclose(derived_ys, inline_ys, rtol=1e-6) + + +def test_resolved_values_can_drive_direct_dynamics_calls(): + inline, derived = InlineLeak(), DerivedLeak() + state = jnp.ones((1, 2)) + coupling = Bunch(drive=jnp.full((1, 2), 0.3)) + np.testing.assert_allclose( + derived.dynamics( + 0.0, state, derived.resolve_params(derived.params), coupling, Bunch() + ), + inline.dynamics(0.0, state, inline.params, coupling, Bunch()), + ) + + +def test_identity_derivation_keeps_transformed_parameter_gradients(): + class InlineTau(InlineLeak): + pass + + class IdentityTau(InlineLeak): + DERIVED_PARAMS = ("tau_used",) + + def derived_params(self, params): + return Bunch(tau_used=params.tau) + + def dynamics(self, t, state, params, coupling, external): + return InlineLeak.dynamics( + self, t, state, Bunch(params, tau=params.tau_used), coupling, external + ) + + def grad_for(cls): + solve_fn, config = prepare(cls(), Heun(), t1=T1, dt=DT, n_nodes=2) + + def loss(tau): + varied = config.copy() + varied.dynamics.tau = tau + return jnp.square(solve_fn(varied).ys).sum() + + return jax.grad(loss)(_positive(2.0)).value + + expected = grad_for(InlineTau) + assert expected != 0.0 + np.testing.assert_allclose(grad_for(IdentityTau), expected, rtol=1e-6) + + +# Inheritance ------------------------------------------------------------------ + + +class ScaledGain(DerivedLeak): + """Overrides the formula, keeps the inherited names.""" + + def derived_params(self, params): + rate = 1.0 / params.tau + return Bunch(rate=rate, gain=2.0 * rate) + + +class WithOffset(DerivedLeak): + """Extends the parent declaration via ``super()``.""" + + DERIVED_PARAMS = DerivedLeak.DERIVED_PARAMS + ("double_rate",) + + def derived_params(self, params): + derived = super().derived_params(params) + derived.double_rate = 2.0 * derived.rate + return derived + + +class FreeGain(DerivedLeak): + """Promotes every derived value to a primary parameter.""" + + DEFAULT_PARAMS = Bunch(rate=0.5, gain=0.3) + DERIVED_PARAMS = () + + def derived_params(self, params): + return Bunch() + + +class FreeRate(DerivedLeak): + """Partial promotion: ``rate`` becomes primary, ``gain`` stays derived.""" + + DEFAULT_PARAMS = Bunch(rate=0.5) + DERIVED_PARAMS = ("gain",) + + def derived_params(self, params): + return Bunch(gain=jnp.tanh(params.k) * params.rate) + + +class Unchanged(DerivedLeak): + pass + + +INHERITANCE = [ + (Unchanged, ("rate", "gain"), {"tau", "k"}, {"rate": 0.5}), + (ScaledGain, ("rate", "gain"), {"tau", "k"}, {"gain": 1.0}), + (WithOffset, ("rate", "gain", "double_rate"), {"tau", "k"}, {"double_rate": 1.0}), + (FreeGain, (), {"tau", "k", "rate", "gain"}, {"rate": 0.5, "gain": 0.3}), + (FreeRate, ("gain",), {"tau", "k", "rate"}, {"rate": 0.5}), +] + + +@pytest.mark.parametrize( + "cls,derived_names,primary_names,expected", + INHERITANCE, + ids=[case[0].__name__ for case in INHERITANCE], +) +def test_inheritance_of_derived_declarations( + cls, derived_names, primary_names, expected +): + model = cls() + assert cls.DERIVED_PARAMS == derived_names + assert set(model.params) == primary_names + resolved = model.resolve_params(model.params) + assert set(resolved) == primary_names | set(derived_names) + for name, value in expected.items(): + np.testing.assert_allclose(resolved[name], value) + assert model.verify(verbose=False) + + +# Errors ----------------------------------------------------------------------- + + +def _subclass(body): + namespace = { + "STATE_NAMES": ("x",), + "INITIAL_STATE": (0.0,), + "DEFAULT_PARAMS": Bunch(tau=1.0), + "dynamics": lambda self, t, state, params, coupling, external: state, + **body, + } + return type("Broken", (AbstractDynamics,), namespace) + + +def _hook(result): + return {"derived_params": lambda self, params: result} + + +CLASS_ERRORS = [ + ( + "not_a_tuple", + {"DERIVED_PARAMS": ["rate"], **_hook(Bunch(rate=1.0))}, + TypeError, + "tuple of strings", + ), + ( + "not_strings", + {"DERIVED_PARAMS": (1,), **_hook(Bunch())}, + TypeError, + "tuple of strings", + ), + ( + "duplicates", + {"DERIVED_PARAMS": ("r", "r"), **_hook(Bunch(r=1.0))}, + ValueError, + "duplicate", + ), + ( + "overlaps_primary", + {"DERIVED_PARAMS": ("tau",), **_hook(Bunch(tau=1.0))}, + ValueError, + "either primary or derived", + ), + ( + "missing_hook", + {"DERIVED_PARAMS": ("rate",)}, + TypeError, + "does not implement or inherit", + ), +] + + +@pytest.mark.parametrize( + "_label,body,error,match", CLASS_ERRORS, ids=[c[0] for c in CLASS_ERRORS] +) +def test_invalid_declarations_fail_at_class_creation(_label, body, error, match): + with pytest.raises(error, match=match): + _subclass(body) + + +def test_overlap_after_inheritance_points_to_promotion(): + with pytest.raises(ValueError, match="remove it from DERIVED_PARAMS"): + + class ForgotToRemove(DerivedLeak): + DEFAULT_PARAMS = Bunch(rate=0.5) + + +RESOLUTION_ERRORS = [ + ("plain_dict", {"rate": 1.0}, TypeError, "must return a Bunch"), + ("missing", Bunch(), ValueError, r"missing \['rate'\]"), + ("extra", Bunch(rate=1.0, other=2.0), ValueError, r"unexpected \['other'\]"), +] + + +@pytest.mark.parametrize( + "_label,result,error,match", + RESOLUTION_ERRORS, + ids=[c[0] for c in RESOLUTION_ERRORS], +) +@pytest.mark.parametrize("entry", ["resolve", "simulate"]) +def test_malformed_hook_output_fails_at_resolution(_label, result, error, match, entry): + model = _subclass({"DERIVED_PARAMS": ("rate",), **_hook(result)})() + with pytest.raises(error, match=match): + if entry == "resolve": + model.resolve_params(model.params) + else: + solve_fn, config = prepare(model, Heun(), t1=T1, dt=DT) + solve_fn(config) + + +DERIVED_INPUTS = [ + ("plain_value", 0.5), + ("parameter", _positive(0.5)), +] + + +@pytest.mark.parametrize( + "_label,value", DERIVED_INPUTS, ids=[c[0] for c in DERIVED_INPUTS] +) +def test_derived_name_in_input_is_rejected(_label, value): + model = DerivedLeak() + with pytest.raises(ValueError, match="Fitting a derived quantity"): + model.resolve_params(Bunch(model.params, rate=value)) + + +def test_resolving_twice_is_rejected(): + model = DerivedLeak() + with pytest.raises(ValueError, match="cannot be set, swept or optimized"): + model.resolve_params(model.resolve_params(model.params)) + + +def test_setting_derived_value_in_constructor_is_rejected(): + with pytest.raises(ValueError, match="computed by DerivedLeak; set its primary"): + DerivedLeak(rate=0.5) + + +@pytest.mark.parametrize("build", [_network, _heterogeneous], ids=["flat", "grouped"]) +def test_printer_lists_derived_names(build): + from tvboptim.experimental.network_dynamics.utils.printer import format_network + + text = format_network(build(DerivedLeak)) + assert "Derived: rate, gain" in text + if build is _network: + assert "def derived_params" in text diff --git a/tests/test_network_dynamics/test_instantaneous_message_passing.py b/tests/test_network_dynamics/test_instantaneous_message_passing.py index e45f37e..17276a4 100644 --- a/tests/test_network_dynamics/test_instantaneous_message_passing.py +++ b/tests/test_network_dynamics/test_instantaneous_message_passing.py @@ -32,6 +32,12 @@ def post(self, summed_inputs, local_states, params): return summed_inputs +class ThreeInputLinear(Linear): + """Linear dynamics accepting the three coupling channels.""" + + COUPLING_INPUTS = {"instant": 3} + + WEIGHTS = np.array( [ [0.0, 2.0, 0.0, 0.0], @@ -61,7 +67,7 @@ def _compute(graph): source="x", local="x", ) - network = Network(Linear(), {"instant": coupling}, graph) + network = Network(ThreeInputLinear(), {"instant": coupling}, graph) data, coupling_state = network.prepare(dt=0.1, t0=0.0, t1=0.2) return network.compute_coupling_inputs( 0.0, @@ -138,8 +144,12 @@ def test_q3_weight_and_state_gradients_sparse_match_dense_under_jit(): source="x", local="x", ) - dense_network = Network(Linear(), {"instant": dense_coupling}, dense_graph) - sparse_network = Network(Linear(), {"instant": sparse_coupling}, sparse_graph) + dense_network = Network( + ThreeInputLinear(), {"instant": dense_coupling}, dense_graph + ) + sparse_network = Network( + ThreeInputLinear(), {"instant": sparse_coupling}, sparse_graph + ) dense_data, dense_coupling_state = dense_network.prepare(0.1, 0.0, 0.2) sparse_data, sparse_coupling_state = sparse_network.prepare(0.1, 0.0, 0.2) dense_aux = dense_graph.tree_flatten()[1] diff --git a/tests/test_network_dynamics/test_reduced_set.py b/tests/test_network_dynamics/test_reduced_set.py new file mode 100644 index 0000000..ef97873 --- /dev/null +++ b/tests/test_network_dynamics/test_reduced_set.py @@ -0,0 +1,99 @@ +"""ReducedSetFitzHughNagumo: TVB parity of derived values and gradients.""" + +import jax +import jax.numpy as jnp +import numpy as np +import pytest +from tvb.simulator import models as tvb_models + +from tvboptim.experimental.network_dynamics import Bunch, Network, prepare +from tvboptim.experimental.network_dynamics.coupling import SumLinearCoupling +from tvboptim.experimental.network_dynamics.dynamics.tvb import ( + ReducedSetFitzHughNagumo, +) +from tvboptim.experimental.network_dynamics.graph import DenseGraph +from tvboptim.experimental.network_dynamics.solvers import Heun + +DISTRIBUTIONS = [(0.0, 0.35), (0.2, 0.6), (-0.1, 0.15)] +DIST_IDS = [f"mu={mu}-sigma={sigma}" for mu, sigma in DISTRIBUTIONS] + + +def _tvb(mu, sigma): + model = tvb_models.ReducedSetFitzHughNagumo( + mu=np.array([mu]), sigma=np.array([sigma]) + ) + model.configure() + return model + + +def _flatten(tvb_array): + """TVB ``(4, nodes, modes)`` to tvboptim ``(12, nodes)``.""" + n_vars, n_nodes, n_modes = tvb_array.shape + return tvb_array.transpose(0, 2, 1).reshape(n_vars * n_modes, n_nodes) + + +@pytest.mark.parametrize("mu,sigma", DISTRIBUTIONS, ids=DIST_IDS) +def test_derived_values_match_tvb(mu, sigma): + reference = _tvb(mu, sigma) + model = ReducedSetFitzHughNagumo(mu=mu, sigma=sigma) + derived = model.resolve_params(model.params) + for name in model.DERIVED_PARAMS: + expected = getattr(reference, name) + actual = np.asarray(derived[name]) + if expected.shape == (1, 3): # TVB row vectors are (3, 1) columns here + actual = actual.T + np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-6) + + +@pytest.mark.parametrize("mu,sigma", DISTRIBUTIONS, ids=DIST_IDS) +def test_dynamics_match_tvb_dfun(mu, sigma): + reference = _tvb(mu, sigma) + model = ReducedSetFitzHughNagumo(mu=mu, sigma=sigma) + rng = np.random.default_rng(0) + state = rng.normal(size=(4, 5, 3)) + coupling = 0.1 * rng.normal(size=(2, 5, 3)) + + expected = _flatten(reference.dfun(state, coupling)) + actual = model.dynamics( + 0.0, + jnp.asarray(_flatten(state)), + model.resolve_params(model.params), + Bunch( + instant=jnp.asarray(coupling[0].sum(axis=1))[None], + delayed=jnp.zeros((1, 5)), + ), + Bunch(), + ) + np.testing.assert_allclose(actual, expected, rtol=1e-4, atol=1e-5) + + +@pytest.mark.parametrize("name", ["mu", "sigma"]) +def test_population_parameters_receive_gradients(name): + n_nodes = 4 + network = Network( + dynamics=ReducedSetFitzHughNagumo(nv=300, nu=300), + coupling={"instant": SumLinearCoupling(source=("xi1", "xi2", "xi3"), G=0.05)}, + graph=DenseGraph(jnp.ones((n_nodes, n_nodes)) - jnp.eye(n_nodes)), + ) + solve_fn, config = prepare(network, Heun(), t1=5.0, dt=0.05) + + def loss(value): + varied = config.copy() + varied.dynamics[name] = value + return jnp.square(solve_fn(varied).ys[:, :3]).mean() + + grad = jax.grad(loss)(jnp.asarray(config.dynamics[name])) + assert jnp.isfinite(grad) and grad != 0.0 + + +@pytest.mark.parametrize("name", ["mu", "sigma"]) +def test_node_varying_distribution_is_rejected(name): + model = ReducedSetFitzHughNagumo(**{name: jnp.array([0.3, 0.4])}) + with pytest.raises(ValueError, match=f"'{name}' must be a scalar"): + model.resolve_params(model.params) + + +@pytest.mark.parametrize("kwargs", [{"nv": 1000}, {"nu": 0}, {"nv": 30.0}]) +def test_sample_counts_are_validated(kwargs): + with pytest.raises(ValueError, match="divisible by 3"): + ReducedSetFitzHughNagumo(**kwargs) diff --git a/tests/test_network_dynamics/test_tvb_comparison.py b/tests/test_network_dynamics/test_tvb_comparison.py index 11facfa..b022d47 100644 --- a/tests/test_network_dynamics/test_tvb_comparison.py +++ b/tests/test_network_dynamics/test_tvb_comparison.py @@ -28,7 +28,9 @@ from tvboptim.experimental.network_dynamics import Network, prepare from tvboptim.experimental.network_dynamics.coupling import ( DelayedLinearCoupling, + DelayedSumLinearCoupling, LinearCoupling, + SumLinearCoupling, ) from tvboptim.experimental.network_dynamics.dynamics.tvb import ( CoombesByrne2D, @@ -39,6 +41,7 @@ LarterBreakspear, Linear, MontbrioPazoRoxin, + ReducedSetFitzHughNagumo, ReducedWongWang, SupHopf, WilsonCowan, @@ -49,9 +52,21 @@ from tvboptim.experimental.network_dynamics.result import NativeSolution from tvboptim.experimental.network_dynamics.solvers import Heun + +def _flatten_modes(tvb_array): + """TVB ``[time, svar, node, mode]`` to ``[time, svar * mode, node]``.""" + n_time, n_svar, n_node, n_mode = tvb_array.shape + return tvb_array.transpose(0, 1, 3, 2).reshape(n_time, n_svar * n_mode, n_node) + + # ============================================================================== # MODEL REGISTRY # ============================================================================== +# Optional keys: "n_modes" flattens TVB's mode axis into the state axis +# (state-major, matching e.g. xi1..3, eta1..3); "couplings" overrides the +# (instant, delayed) coupling classes; "dt" overrides DT for stiff models; +# "input" names the dynamics input that receives TVB's long-range coupling +# (default: the coupling config name). MODEL_REGISTRY = { "Linear": { "tvb_class": models.Linear, @@ -98,7 +113,7 @@ "MontbrioPazoRoxin": { "tvb_class": models.MontbrioPazoRoxin, "tvboptim_class": MontbrioPazoRoxin, - "coupling_var": "r", + "coupling_var": ("r", "V"), "state_indices": [0, 1], "tvb_cvar": [0, 1], "params": {}, @@ -123,6 +138,7 @@ "tvb_class": models.WilsonCowan, "tvboptim_class": WilsonCowan, "coupling_var": "E", + "input": "delayed", # "instant" is TVB's local coupling "state_indices": [0, 1], "tvb_cvar": [0, 1], "params": {}, @@ -151,10 +167,21 @@ "tvb_cvar": [0], "params": {}, }, + "ReducedSetFitzHughNagumo": { + "tvb_class": models.ReducedSetFitzHughNagumo, + "tvboptim_class": ReducedSetFitzHughNagumo, + "coupling_var": ("xi1", "xi2", "xi3"), + "couplings": (SumLinearCoupling, DelayedSumLinearCoupling), + "n_modes": 3, + "dt": 0.02, # stiff from TVB's random initial conditions at DT=0.1 + "state_indices": list(range(12)), + "tvb_cvar": [0], + "params": {}, + }, "Epileptor": { "tvb_class": models.Epileptor, "tvboptim_class": Epileptor, - "coupling_var": "x1", + "coupling_var": ("x1", "x2"), "state_indices": [0, 1, 2, 3, 4, 5], "tvb_cvar": [0, 3], "params": {}, @@ -201,6 +228,7 @@ class TestTVBComparison(unittest.TestCase): "JansenRit", "LarterBreakspear", "Epileptor", + "ReducedSetFitzHughNagumo", ] def setUp(self): @@ -249,8 +277,11 @@ def _test_single_configuration(self, model_name, coupling_config): ) # 4. Compare results + tvb_data = tvb_result["data"] + if config.get("n_modes", 1) > 1: + tvb_data = _flatten_modes(tvb_data)[..., None] comparison_metrics = self._compare_results( - tvb_data=tvb_result["data"], + tvb_data=tvb_data, tvboptim_data=tvboptim_result["data"], state_indices=config["state_indices"], ) @@ -264,6 +295,7 @@ def _test_single_configuration(self, model_name, coupling_config): def _run_tvb_simulation(self, config, coupling_config): """Run TVB simulation.""" + dt = config.get("dt", self.DT) # Configure connectivity with speed conn = connectivity.Connectivity( weights=np.array(self.weights), @@ -273,7 +305,7 @@ def _run_tvb_simulation(self, config, coupling_config): speed=np.array([coupling_config["speed"]]), ) conn.configure() - conn.set_idelays(self.DT) + conn.set_idelays(dt) # Create model with all state variables as VOI for complete comparison model_params = config["params"].copy() @@ -289,7 +321,7 @@ def _run_tvb_simulation(self, config, coupling_config): model=tvb_model, connectivity=conn, coupling=coupling.Linear(a=np.array([coupling_config["G"]])), - integrator=integrators.HeunDeterministic(dt=self.DT), + integrator=integrators.HeunDeterministic(dt=dt), monitors=[monitors.Raw()], simulation_length=self.SIMULATION_LENGTH, ).configure() @@ -301,9 +333,11 @@ def _run_tvb_simulation(self, config, coupling_config): ) # Extract ICs for TVB-Optim (already in correct order) - initial_conditions_tvboptim = jnp.array( - initial_conditions[:, :, :, 0], dtype=jnp.float64 - ) + if config.get("n_modes", 1) > 1: + ics = _flatten_modes(initial_conditions) + else: + ics = initial_conditions[:, :, :, 0] + initial_conditions_tvboptim = jnp.array(ics, dtype=jnp.float64) # Set ICs and reconfigure sim.initial_conditions = initial_conditions @@ -323,15 +357,19 @@ def _run_tvboptim_simulation( self, config, coupling_config, tvb_initial_conditions, tvb_conn ): """Run TVB-Optim simulation with matching initial conditions from TVB.""" + dt = config.get("dt", self.DT) # Compute delays speed = coupling_config["speed"] + instant_cls, delayed_cls = config.get( + "couplings", (LinearCoupling, DelayedLinearCoupling) + ) if np.isinf(speed): # Instant coupling - use DenseGraph graph = DenseGraph(self.weights, region_labels=self.region_labels) - coupling_obj = LinearCoupling( + coupling_obj = instant_cls( source=config["coupling_var"], G=coupling_config["G"] ) - coupling_dict = {"instant": coupling_obj} + coupling_dict = {config.get("input", "instant"): coupling_obj} t_offset = 0.0 else: # Delayed coupling - use DenseDelayGraph @@ -339,11 +377,11 @@ def _run_tvboptim_simulation( graph = DenseDelayGraph( self.weights, delays, region_labels=self.region_labels ) - coupling_obj = DelayedLinearCoupling( + coupling_obj = delayed_cls( source=config["coupling_var"], G=coupling_config["G"] ) - coupling_dict = {"delayed": coupling_obj} - t_offset = float(tvb_conn.horizon * self.DT) + coupling_dict = {config.get("input", "delayed"): coupling_obj} + t_offset = float(tvb_conn.horizon * dt) # Create dynamics model_params = config["params"].copy() @@ -361,7 +399,7 @@ def _run_tvboptim_simulation( # Set initial conditions from TVB (already in correct order) t_max = tvb_conn.horizon - ts_tvb = jnp.arange(0.0, t_max * self.DT, self.DT) + ts_tvb = jnp.arange(0.0, t_max * dt, dt) network.update_history( NativeSolution( ts_tvb, @@ -376,7 +414,7 @@ def _run_tvboptim_simulation( Heun(), t0=0.0 + t_offset, t1=self.SIMULATION_LENGTH + t_offset, - dt=self.DT, + dt=dt, ) model_fn = jax.jit(model_fn) result = model_fn(state)