Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down
3 changes: 3 additions & 0 deletions docs/_quarto.yml
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ quartodoc:
- tvb.WongWangExcInh
- tvb.WilsonCowan
- tvb.MontbrioPazoRoxin
- tvb.ReducedSetFitzHughNagumo
- tvb.CoombesByrne2D
- tvb.LarterBreakspear
- tvb.Epileptor
Expand All @@ -217,6 +218,8 @@ quartodoc:
- LinearCoupling
- FastLinearCoupling
- DelayedLinearCoupling
- SumLinearCoupling
- DelayedSumLinearCoupling
- DifferenceCoupling
- DelayedDifferenceCoupling
- SigmoidalJansenRit
Expand Down
3 changes: 3 additions & 0 deletions docs/_sidebar.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
24 changes: 24 additions & 0 deletions docs/basics/parameters_and_optimization.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions docs/network_dynamics/coupling.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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.
61 changes: 61 additions & 0 deletions docs/network_dynamics/dynamics.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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.

Expand All @@ -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

Expand Down
13 changes: 8 additions & 5 deletions src/tvboptim/experimental/network_dynamics/core/heterogeneous.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down
33 changes: 32 additions & 1 deletion src/tvboptim/experimental/network_dynamics/core/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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).

Expand Down Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Coupling functions for network interactions."""

from .base import (
PER_SOURCE,
AbstractCoupling,
BufferStrategy,
DelayedCoupling,
Expand All @@ -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",
Expand All @@ -27,6 +31,8 @@
"SigmoidalJansenRit",
"DelayedSigmoidalJansenRit",
"DelayedLinearCoupling",
"SumLinearCoupling",
"DelayedSumLinearCoupling",
"DelayedDifferenceCoupling",
"FastLinearCoupling",
"SubspaceCoupling",
Expand Down
Loading
Loading