tvboptim 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. tvboptim/__init__.py +9 -0
  2. tvboptim/data/__init__.py +12 -0
  3. tvboptim/data/loaders.py +99 -0
  4. tvboptim/execution.py +268 -0
  5. tvboptim/experimental/__init__.py +15 -0
  6. tvboptim/experimental/network_dynamics/__init__.py +28 -0
  7. tvboptim/experimental/network_dynamics/core/__init__.py +6 -0
  8. tvboptim/experimental/network_dynamics/core/bunch.py +67 -0
  9. tvboptim/experimental/network_dynamics/core/network.py +686 -0
  10. tvboptim/experimental/network_dynamics/coupling/__init__.py +22 -0
  11. tvboptim/experimental/network_dynamics/coupling/base.py +1005 -0
  12. tvboptim/experimental/network_dynamics/coupling/linear.py +466 -0
  13. tvboptim/experimental/network_dynamics/coupling/subspace.py +509 -0
  14. tvboptim/experimental/network_dynamics/coupling/tvb.py +202 -0
  15. tvboptim/experimental/network_dynamics/dynamics/__init__.py +7 -0
  16. tvboptim/experimental/network_dynamics/dynamics/base.py +541 -0
  17. tvboptim/experimental/network_dynamics/dynamics/lorenz.py +207 -0
  18. tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py +29 -0
  19. tvboptim/experimental/network_dynamics/dynamics/tvb/coombes_byrne.py +154 -0
  20. tvboptim/experimental/network_dynamics/dynamics/tvb/epileptor.py +200 -0
  21. tvboptim/experimental/network_dynamics/dynamics/tvb/generic_2d_oscillator.py +149 -0
  22. tvboptim/experimental/network_dynamics/dynamics/tvb/jansen_rit.py +158 -0
  23. tvboptim/experimental/network_dynamics/dynamics/tvb/kuramoto.py +120 -0
  24. tvboptim/experimental/network_dynamics/dynamics/tvb/larter_breakspear.py +221 -0
  25. tvboptim/experimental/network_dynamics/dynamics/tvb/linear.py +111 -0
  26. tvboptim/experimental/network_dynamics/dynamics/tvb/montbrio_pazo_roxin.py +137 -0
  27. tvboptim/experimental/network_dynamics/dynamics/tvb/sup_hopf.py +131 -0
  28. tvboptim/experimental/network_dynamics/dynamics/tvb/wilson_cowan.py +210 -0
  29. tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang.py +124 -0
  30. tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang_exc_inh.py +177 -0
  31. tvboptim/experimental/network_dynamics/external_input/__init__.py +20 -0
  32. tvboptim/experimental/network_dynamics/external_input/base.py +152 -0
  33. tvboptim/experimental/network_dynamics/external_input/data.py +203 -0
  34. tvboptim/experimental/network_dynamics/external_input/parametric.py +270 -0
  35. tvboptim/experimental/network_dynamics/graph/__init__.py +14 -0
  36. tvboptim/experimental/network_dynamics/graph/base.py +706 -0
  37. tvboptim/experimental/network_dynamics/graph/sparse.py +885 -0
  38. tvboptim/experimental/network_dynamics/graph/utils.py +0 -0
  39. tvboptim/experimental/network_dynamics/noise/__init__.py +6 -0
  40. tvboptim/experimental/network_dynamics/noise/base.py +162 -0
  41. tvboptim/experimental/network_dynamics/noise/gaussian.py +71 -0
  42. tvboptim/experimental/network_dynamics/result.py +78 -0
  43. tvboptim/experimental/network_dynamics/solve.py +721 -0
  44. tvboptim/experimental/network_dynamics/solvers/__init__.py +15 -0
  45. tvboptim/experimental/network_dynamics/solvers/base.py +46 -0
  46. tvboptim/experimental/network_dynamics/solvers/diffrax.py +63 -0
  47. tvboptim/experimental/network_dynamics/solvers/native.py +308 -0
  48. tvboptim/experimental/network_dynamics/utils/__init__.py +3 -0
  49. tvboptim/experimental/network_dynamics/utils/printer.py +555 -0
  50. tvboptim/model.py +111 -0
  51. tvboptim/observations/__init__.py +3 -0
  52. tvboptim/observations/observation.py +32 -0
  53. tvboptim/observations/tvb_monitors/__init__.py +11 -0
  54. tvboptim/observations/tvb_monitors/bold.py +290 -0
  55. tvboptim/observations/tvb_monitors/downsampling.py +185 -0
  56. tvboptim/optim/__init__.py +4 -0
  57. tvboptim/optim/callbacks.py +333 -0
  58. tvboptim/optim/optax.py +379 -0
  59. tvboptim/types/__init__.py +35 -0
  60. tvboptim/types/parameter.py +769 -0
  61. tvboptim/types/spaces.py +943 -0
  62. tvboptim/types/stateutils.py +109 -0
  63. tvboptim/utils/__init__.py +16 -0
  64. tvboptim/utils/caching.py +82 -0
  65. tvboptim/utils/utils.py +265 -0
  66. tvboptim-0.2.0.dist-info/METADATA +157 -0
  67. tvboptim-0.2.0.dist-info/RECORD +70 -0
  68. tvboptim-0.2.0.dist-info/WHEEL +5 -0
  69. tvboptim-0.2.0.dist-info/licenses/LICENSE +278 -0
  70. tvboptim-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,124 @@
1
+ """Reduced Wong-Wang neural mass model with multi-coupling support."""
2
+
3
+ from typing import Tuple
4
+
5
+ import jax.numpy as jnp
6
+
7
+ from ...core.bunch import Bunch
8
+ from ..base import AbstractDynamics
9
+
10
+
11
+ class ReducedWongWang(AbstractDynamics):
12
+ """Reduced Wong-Wang neural mass model with multi-coupling support.
13
+
14
+ This implementation accepts two coupling inputs (instantaneous and delayed),
15
+ both of which contribute to the total synaptic input.
16
+
17
+ Notes
18
+ -----
19
+ The model describes the dynamics of a single synaptic gating variable representing
20
+ NMDA receptor activity.
21
+
22
+ **State equation:**
23
+
24
+ $$\\frac{dS}{dt} = -\\frac{S}{\\tau_s} + (1-S) H(x) \\gamma$$
25
+
26
+ **Transfer function:**
27
+
28
+ $$H(x) = \\frac{ax - b}{1 - \\exp(-d(ax - b))}$$
29
+
30
+ **Total input:**
31
+
32
+ $$x = w J_N S + I_o + J_N (c_{\\text{instant}} + c_{\\text{delayed}})$$
33
+
34
+ Attributes
35
+ ----------
36
+ STATE_NAMES : tuple of str
37
+ State variable name: ``("S",)`` (synaptic gating variable)
38
+ INITIAL_STATE : tuple of float
39
+ Default initial condition: ``(0.1,)``
40
+ AUXILIARY_NAMES : tuple of str
41
+ Auxiliary variable: ``("H",)`` (transfer function output)
42
+ COUPLING_INPUTS : dict
43
+ Coupling specification: ``{'instant': 1, 'delayed': 1}``
44
+ DEFAULT_PARAMS : Bunch
45
+ Standard Wong-Wang parameters (a, b, d, gamma, tau_s, w, J_N, I_o)
46
+ """
47
+
48
+ STATE_NAMES = ("S",)
49
+ INITIAL_STATE = (0.1,) # Small initial synaptic activity
50
+
51
+ AUXILIARY_NAMES = ("H",)
52
+
53
+ DEFAULT_PARAMS = Bunch(
54
+ a=0.270, # Input gain parameter [n/C]
55
+ b=0.108, # Input shift parameter [kHz]
56
+ d=154.0, # Parameter for H function [ms]
57
+ gamma=0.641, # Kinetic parameter
58
+ tau_s=100.0, # NMDA decay time constant [ms]
59
+ w=0.6, # Excitatory recurrence
60
+ J_N=0.2609, # Excitatory recurrence
61
+ I_o=0.33, # Effective external input [nA]
62
+ )
63
+
64
+ # Multi-coupling: instantaneous and delayed
65
+ COUPLING_INPUTS = {
66
+ "instant": 1,
67
+ "delayed": 1,
68
+ }
69
+
70
+ def dynamics(
71
+ self,
72
+ t: float,
73
+ state: jnp.ndarray,
74
+ params: Bunch,
75
+ coupling: Bunch,
76
+ external: Bunch,
77
+ ) -> Tuple[jnp.ndarray, jnp.ndarray]:
78
+ """Compute Wong-Wang dynamics with two coupling inputs.
79
+
80
+ Parameters
81
+ ----------
82
+ t : float
83
+ Current time (unused for autonomous system)
84
+ state : jnp.ndarray
85
+ Current state with shape ``[1, n_nodes]`` containing S (synaptic gating variable)
86
+ params : Bunch
87
+ Model parameters: a, b, d, gamma, tau_s, w, J_N, I_o
88
+ coupling : Bunch
89
+ Coupling inputs with attributes ``.instant[1, n_nodes]`` and ``.delayed[1, n_nodes]``
90
+ external : Bunch
91
+ External inputs (currently unused)
92
+
93
+ Returns
94
+ -------
95
+ derivatives : jnp.ndarray
96
+ State derivatives with shape ``[1, n_nodes]`` containing dS/dt
97
+ auxiliaries : jnp.ndarray
98
+ Auxiliary variables with shape ``[1, n_nodes]`` containing H (transfer function)
99
+ """
100
+ # Unpack parameters
101
+ a, b, d = params.a, params.b, params.d
102
+ gamma, tau_s = params.gamma, params.tau_s
103
+ w, J_N, I_o = params.w, params.J_N, params.I_o
104
+
105
+ # Unpack state and coupling
106
+ S = state[0] # Synaptic gating variable
107
+ c_instant = coupling.instant[0]
108
+ c_delayed = coupling.delayed[0]
109
+
110
+ # Total input to population (both couplings add via J_N)
111
+ x = w * J_N * S + I_o + J_N * c_instant + J_N * c_delayed
112
+
113
+ # Transfer function H(x)
114
+ ax_minus_b = a * x - b
115
+ H = ax_minus_b / (1 - jnp.exp(-d * ax_minus_b))
116
+
117
+ # Population dynamics
118
+ dS_dt = -(S / tau_s) + (1 - S) * H * gamma
119
+
120
+ # Package results
121
+ derivatives = jnp.array([dS_dt])
122
+ auxiliaries = jnp.array([H])
123
+
124
+ return derivatives, auxiliaries
@@ -0,0 +1,177 @@
1
+ """Wong-Wang model with separate excitatory and inhibitory populations.
2
+
3
+ Reduced mean-field model with explicit excitatory and inhibitory populations,
4
+ mutually coupled through local connections and long-range network coupling.
5
+
6
+ References:
7
+ - Wong & Wang (2006). A Recurrent Network Mechanism of Time Integration in
8
+ Perceptual Decisions. Journal of Neuroscience, 26(4), 1314-1328.
9
+ - Deco et al. (2014). How Local Excitation-Inhibition Ratio Impacts the
10
+ Whole Brain Dynamics. Journal of Neuroscience, 34(23), 7886-7898.
11
+ """
12
+
13
+ from typing import Tuple
14
+
15
+ import jax.numpy as jnp
16
+
17
+ from ...core.bunch import Bunch
18
+ from ..base import AbstractDynamics
19
+
20
+
21
+ class WongWangExcInh(AbstractDynamics):
22
+ """Wong-Wang neural mass model with excitatory and inhibitory populations.
23
+
24
+ Two-population model representing local excitatory-inhibitory dynamics
25
+ with NMDA-mediated recurrence and long-range coupling.
26
+
27
+ Notes
28
+ -----
29
+ **State equations:**
30
+
31
+ $$
32
+ \\begin{aligned}
33
+ x_e &= w_p J_N S_e - J_i S_i + W_e I_o + c_{\\text{total}} + I_{\\text{ext}} \\\\
34
+ H_e &= \\frac{a_e x_e - b_e}{1 - \\exp(-d_e(a_e x_e - b_e))} \\\\
35
+ \\frac{dS_e}{dt} &= -\\frac{S_e}{\\tau_e} + (1 - S_e) H_e \\gamma_e
36
+ \\end{aligned}
37
+ $$
38
+
39
+ $$
40
+ \\begin{aligned}
41
+ x_i &= J_N S_e - S_i + W_i I_o + \\lambda c_{\\text{total}} \\\\
42
+ H_i &= \\frac{a_i x_i - b_i}{1 - \\exp(-d_i(a_i x_i - b_i))} \\\\
43
+ \\frac{dS_i}{dt} &= -\\frac{S_i}{\\tau_i} + H_i \\gamma_i
44
+ \\end{aligned}
45
+ $$
46
+
47
+ where: $c_{\\text{total}} = G J_N (c_{\\text{delayed}} + c_{\\text{instant}})$
48
+
49
+ Attributes
50
+ ----------
51
+ STATE_NAMES : tuple of str
52
+ State variables: ``('S_e', 'S_i')`` (excitatory and inhibitory synaptic gating)
53
+ INITIAL_STATE : tuple of float
54
+ Default initial conditions: ``(0.001, 0.001)``
55
+ AUXILIARY_NAMES : tuple of str
56
+ Auxiliary variables: ``('H_e', 'H_i')`` (transfer functions)
57
+ COUPLING_INPUTS : dict
58
+ Coupling specification: ``{'instant': 1, 'delayed': 1}``
59
+ DEFAULT_PARAMS : Bunch
60
+ Standard Wong-Wang parameters for excitatory/inhibitory populations
61
+
62
+ References
63
+ ----------
64
+ Wong & Wang (2006). A Recurrent Network Mechanism of Time Integration in
65
+ Perceptual Decisions. Journal of Neuroscience, 26(4), 1314-1328.
66
+ """
67
+
68
+ STATE_NAMES = ("S_e", "S_i")
69
+ INITIAL_STATE = (0.001, 0.001)
70
+
71
+ AUXILIARY_NAMES = ("H_e", "H_i")
72
+
73
+ DEFAULT_PARAMS = Bunch(
74
+ # Excitatory population parameters
75
+ a_e=310.0, # [n/C] Input gain parameter
76
+ b_e=125.0, # [Hz] Input shift parameter
77
+ d_e=0.160, # [s] Input scaling parameter
78
+ gamma_e=0.641 / 1000, # Kinetic parameter
79
+ tau_e=100.0, # [ms] NMDA decay time constant
80
+ w_p=1.4, # Recurrence weight
81
+ W_e=1.0, # External input scaling weight
82
+ # Inhibitory population parameters
83
+ a_i=615.0, # [n/C] Input gain parameter
84
+ b_i=177.0, # [Hz] Input shift parameter
85
+ d_i=0.087, # [s] Input scaling parameter
86
+ gamma_i=1.0 / 1000, # Kinetic parameter
87
+ tau_i=10.0, # [ms] NMDA decay time constant
88
+ W_i=0.7, # External input scaling weight
89
+ # Synaptic weights
90
+ J_N=0.15, # [nA] NMDA current
91
+ J_i=1.0, # Inhibitory synaptic weight
92
+ # External inputs
93
+ I_o=0.382, # Background input current
94
+ I_ext=0.0, # External stimulation current
95
+ # Coupling parameters
96
+ G=2.0, # Global coupling strength
97
+ lamda=0.0, # Lambda: inhibitory coupling weight
98
+ )
99
+
100
+ COUPLING_INPUTS = {
101
+ "instant": 1, # Local/instantaneous coupling
102
+ "delayed": 1, # Long-range delayed coupling
103
+ }
104
+
105
+ def dynamics(
106
+ self,
107
+ t: float,
108
+ state: jnp.ndarray,
109
+ params: Bunch,
110
+ coupling: Bunch,
111
+ external: Bunch,
112
+ ) -> Tuple[jnp.ndarray, jnp.ndarray]:
113
+ """Compute Wong-Wang excitatory-inhibitory dynamics.
114
+
115
+ Parameters
116
+ ----------
117
+ t : float
118
+ Current time (ms)
119
+ state : jnp.ndarray
120
+ Current state with shape ``[2, n_nodes]`` containing ``(S_e, S_i)``
121
+ params : Bunch
122
+ Model parameters
123
+ coupling : Bunch
124
+ Coupling inputs with attributes ``.instant`` and ``.delayed``
125
+ external : Bunch
126
+ External inputs (currently unused)
127
+
128
+ Returns
129
+ -------
130
+ derivatives : jnp.ndarray
131
+ State derivatives with shape ``[2, n_nodes]``
132
+ auxiliaries : jnp.ndarray
133
+ Auxiliary variables with shape ``[2, n_nodes]`` containing ``(H_e, H_i)`` transfer functions
134
+ """
135
+ # Unpack state variables
136
+ S_e = state[0] # Excitatory synaptic gating
137
+ S_i = state[1] # Inhibitory synaptic gating
138
+
139
+ # Unpack coupling
140
+ c_instant = coupling.instant[0] # Local coupling (proportional to S_e)
141
+ c_delayed = coupling.delayed[0] # Long-range coupling
142
+
143
+ # Combined coupling (both instant and delayed)
144
+ coupling_total = params.G * params.J_N * (c_delayed + c_instant)
145
+
146
+ # Excitatory population input
147
+ J_N_S_e = params.J_N * S_e
148
+ x_e = (
149
+ params.w_p * J_N_S_e
150
+ - params.J_i * S_i
151
+ + params.W_e * params.I_o
152
+ + coupling_total
153
+ + params.I_ext
154
+ )
155
+
156
+ # Excitatory transfer function
157
+ x_e_scaled = params.a_e * x_e - params.b_e
158
+ H_e = x_e_scaled / (1.0 - jnp.exp(-params.d_e * x_e_scaled))
159
+
160
+ # Excitatory dynamics
161
+ dS_e_dt = -(S_e / params.tau_e) + (1.0 - S_e) * H_e * params.gamma_e
162
+
163
+ # Inhibitory population input
164
+ x_i = J_N_S_e - S_i + params.W_i * params.I_o + params.lamda * coupling_total
165
+
166
+ # Inhibitory transfer function
167
+ x_i_scaled = params.a_i * x_i - params.b_i
168
+ H_i = x_i_scaled / (1.0 - jnp.exp(-params.d_i * x_i_scaled))
169
+
170
+ # Inhibitory dynamics
171
+ dS_i_dt = -(S_i / params.tau_i) + H_i * params.gamma_i
172
+
173
+ # Package results
174
+ derivatives = jnp.array([dS_e_dt, dS_i_dt])
175
+ auxiliaries = jnp.array([H_e, H_i])
176
+
177
+ return derivatives, auxiliaries
@@ -0,0 +1,20 @@
1
+ """External input system for network dynamics.
2
+
3
+ This module provides external inputs that can drive network dynamics
4
+ independently of coupling. External inputs are time-dependent (and optionally
5
+ state-dependent) signals.
6
+ """
7
+
8
+ from .base import AbstractExternalInput
9
+ from .data import DataInput
10
+ from .parametric import ConstantInput, PulseInput, PulseTrainInput, RampInput, SineInput
11
+
12
+ __all__ = [
13
+ "AbstractExternalInput",
14
+ "SineInput",
15
+ "PulseInput",
16
+ "PulseTrainInput",
17
+ "RampInput",
18
+ "ConstantInput",
19
+ "DataInput",
20
+ ]
@@ -0,0 +1,152 @@
1
+ """Abstract base class for external inputs.
2
+
3
+ This module defines the interface for external inputs that can be added to
4
+ network dynamics simulations. External inputs are time-dependent (and optionally
5
+ state-dependent) signals that influence node dynamics independently of network
6
+ coupling.
7
+
8
+ The interface mirrors the coupling system with prepare/compute/update_state
9
+ pattern, supporting both stateless and stateful inputs.
10
+ """
11
+
12
+ from abc import ABC, abstractmethod
13
+ from typing import Tuple
14
+
15
+ import jax.numpy as jnp
16
+
17
+ from ..core.bunch import Bunch
18
+
19
+
20
+ class AbstractExternalInput(ABC):
21
+ """Abstract base class for external inputs.
22
+
23
+ External inputs are functions of time (and optionally state) that provide
24
+ additional drive to node dynamics, independent of network coupling.
25
+
26
+ Like couplings, external inputs follow a three-stage pattern:
27
+ 1. prepare(): Setup and precomputation before simulation
28
+ 2. compute(): Calculate input at each timestep during simulation
29
+ 3. update_state(): Update internal state after each integration step
30
+
31
+ Class Attributes:
32
+ N_OUTPUT_DIMS: Number of output dimensions
33
+ DEFAULT_PARAMS: Default parameter values as Bunch
34
+
35
+ Instance Attributes:
36
+ params: Instance-specific parameters (copy of DEFAULT_PARAMS + overrides)
37
+ """
38
+
39
+ N_OUTPUT_DIMS: int = 1
40
+ DEFAULT_PARAMS: Bunch = Bunch()
41
+
42
+ def __init__(self, seed=None, **kwargs):
43
+ """Initialize external input with parameter overrides.
44
+
45
+ Args:
46
+ seed: Optional random seed for stateful inputs with randomness
47
+ **kwargs: Parameter overrides for DEFAULT_PARAMS
48
+
49
+ Raises:
50
+ ValueError: If unknown parameters are provided
51
+ """
52
+ # Create instance parameters by copying defaults and updating with kwargs
53
+ self.params = self.DEFAULT_PARAMS.copy() if self.DEFAULT_PARAMS else Bunch()
54
+ for key, value in kwargs.items():
55
+ if key not in self.DEFAULT_PARAMS:
56
+ raise ValueError(
57
+ f"Unknown parameter '{key}' for {self.__class__.__name__}. "
58
+ f"Available parameters: {list(self.DEFAULT_PARAMS.keys())}"
59
+ )
60
+ self.params[key] = value
61
+
62
+ # Store seed for stateful inputs that need randomness
63
+ self.seed = seed
64
+
65
+ @abstractmethod
66
+ def prepare(self, network, dt: float) -> Tuple[Bunch, Bunch]:
67
+ """Prepare input for simulation.
68
+
69
+ Called once before simulation starts. Handles setup logic like:
70
+ - Resolving state indices (for state-dependent inputs)
71
+ - Initializing internal state (for stateful inputs)
72
+ - Precomputing static data
73
+
74
+ Args:
75
+ network: Network instance with graph, dynamics, initial_state
76
+ dt: Integration timestep
77
+
78
+ Returns:
79
+ Tuple of (input_data, input_state):
80
+
81
+ input_data: Bunch
82
+ Static precomputed data (stored outside scan carry):
83
+ - state_indices: Which states to monitor (for state-dependent)
84
+ - dt: Timestep (for stateful updates)
85
+ - Other static precomputed data
86
+
87
+ input_state: Bunch
88
+ Mutable internal state (stored in scan carry):
89
+ - Empty Bunch() for stateless inputs
90
+ - Internal variables for stateful inputs (e.g., adaptation level)
91
+ """
92
+ pass
93
+
94
+ @abstractmethod
95
+ def compute(
96
+ self,
97
+ t: float,
98
+ state: jnp.ndarray,
99
+ input_data: Bunch,
100
+ input_state: Bunch,
101
+ params: Bunch,
102
+ ) -> jnp.ndarray:
103
+ """Compute external input at current time.
104
+
105
+ Called at each timestep during simulation to calculate the input signal.
106
+
107
+ Args:
108
+ t: Current simulation time
109
+ state: Current network state [n_states, n_nodes]
110
+ input_data: Precomputed static data from prepare()
111
+ input_state: Current mutable internal state
112
+ params: Input parameters (supports broadcasting)
113
+
114
+ Returns:
115
+ Input array with flexible shape that will be auto-broadcast:
116
+ - Scalar: Broadcast to [N_OUTPUT_DIMS, n_nodes]
117
+ - [n_nodes]: Reshape to [N_OUTPUT_DIMS, n_nodes]
118
+ - [N_OUTPUT_DIMS, n_nodes]: Use directly
119
+
120
+ Parameters in params can be:
121
+ - Scalars: Same value for all nodes
122
+ - [n_nodes] arrays: Node-specific values (spatial patterns)
123
+ """
124
+ pass
125
+
126
+ @abstractmethod
127
+ def update_state(
128
+ self,
129
+ input_data: Bunch,
130
+ input_state: Bunch,
131
+ new_state: jnp.ndarray,
132
+ ) -> Bunch:
133
+ """Update input internal state after integration step.
134
+
135
+ Called after each integration step. For stateless inputs, this is a no-op
136
+ (just return input_state unchanged). For stateful inputs, this updates
137
+ internal variables based on the new state.
138
+
139
+ Args:
140
+ input_data: Precomputed static data from prepare()
141
+ input_state: Current mutable internal state
142
+ new_state: New network state after integration [n_states, n_nodes]
143
+
144
+ Returns:
145
+ Updated input_state as Bunch
146
+ """
147
+ pass
148
+
149
+ def __repr__(self) -> str:
150
+ """String representation of external input."""
151
+ param_str = ", ".join(f"{k}={v}" for k, v in self.params.items())
152
+ return f"{self.__class__.__name__}({param_str})"
@@ -0,0 +1,203 @@
1
+ """Data-based external inputs using interpolation.
2
+
3
+ This module provides external inputs from time-series data using Diffrax
4
+ interpolation for smooth, resolution-independent stimulus delivery.
5
+ """
6
+
7
+ from typing import Literal
8
+
9
+ import diffrax
10
+ import jax.numpy as jnp
11
+
12
+ from ..core.bunch import Bunch
13
+ from .base import AbstractExternalInput
14
+
15
+
16
+ class DataInput(AbstractExternalInput):
17
+ """External input from interpolated time-series data.
18
+
19
+ Provides stimulus from discrete time-series data using interpolation,
20
+ allowing simulation dt to differ from data sampling rate.
21
+
22
+ Data shapes:
23
+ - Global scalar: data=[n_times] → broadcasts to all nodes
24
+ - Per-node: data=[n_times, n_nodes] → node-specific signals
25
+ - Multi-dimensional: data=[n_times, n_dims, n_nodes] → multiple signals per node
26
+
27
+ Interpolation types:
28
+ - 'linear': Fast piecewise linear interpolation
29
+ - 'cubic': Smooth cubic Hermite spline (backward differences)
30
+
31
+ Args:
32
+ times: Time points [n_times] (must be increasing)
33
+ data: Data values at each time point (see shapes above)
34
+ interpolation: Interpolation method ('linear' or 'cubic')
35
+
36
+ Example:
37
+ >>> # Global stimulus from data
38
+ >>> times = jnp.linspace(0, 10, 100)
39
+ >>> data = jnp.sin(times)
40
+ >>> stimulus = DataInput(times, data, interpolation='cubic')
41
+ >>>
42
+ >>> # Per-node stimulus
43
+ >>> n_nodes = 5
44
+ >>> data = jnp.sin(times[:, None] + jnp.arange(n_nodes)) # [100, 5]
45
+ >>> stimulus = DataInput(times, data)
46
+
47
+ Attributes:
48
+ N_OUTPUT_DIMS: Inferred from data shape (1 for scalar/per-node, n_dims for multi-dim)
49
+ DEFAULT_PARAMS: Contains times, data, interpolation_type for reference
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ times: jnp.ndarray,
55
+ data: jnp.ndarray,
56
+ interpolation: Literal["linear", "cubic"] = "linear",
57
+ **kwargs,
58
+ ):
59
+ """Initialize DataInput with time-series data.
60
+
61
+ Args:
62
+ times: Time points [n_times]
63
+ data: Data values (flexible shape)
64
+ interpolation: 'linear' or 'cubic'
65
+ **kwargs: Additional parameters (unused, for consistency)
66
+ """
67
+ # Validate inputs
68
+ times = jnp.asarray(times)
69
+ data = jnp.asarray(data)
70
+
71
+ if times.ndim != 1:
72
+ raise ValueError(f"times must be 1D array, got shape {times.shape}")
73
+
74
+ if data.shape[0] != times.shape[0]:
75
+ raise ValueError(
76
+ f"First dimension of data {data.shape[0]} must match "
77
+ f"times length {times.shape[0]}"
78
+ )
79
+
80
+ if interpolation not in ("linear", "cubic"):
81
+ raise ValueError(
82
+ f"interpolation must be 'linear' or 'cubic', got {interpolation}"
83
+ )
84
+
85
+ # Determine output dimensionality from data shape
86
+ if data.ndim == 1:
87
+ # [n_times] - global scalar
88
+ n_output_dims = 1
89
+ elif data.ndim == 2:
90
+ # [n_times, n_nodes] - per-node scalar
91
+ n_output_dims = 1
92
+ elif data.ndim == 3:
93
+ # [n_times, n_dims, n_nodes] - multi-dimensional
94
+ n_output_dims = data.shape[1]
95
+ else:
96
+ raise ValueError(
97
+ f"data must have 1, 2, or 3 dimensions, got shape {data.shape}"
98
+ )
99
+
100
+ self.N_OUTPUT_DIMS = n_output_dims
101
+
102
+ # Store data as parameters (for reference, not optimization)
103
+ self.DEFAULT_PARAMS = Bunch(
104
+ times=times,
105
+ data=data,
106
+ interpolation_type=interpolation,
107
+ )
108
+
109
+ # Initialize base class
110
+ super().__init__(**kwargs)
111
+
112
+ def prepare(self, network, dt: float):
113
+ """Prepare interpolation object for simulation.
114
+
115
+ Creates Diffrax interpolation object based on interpolation type.
116
+
117
+ Args:
118
+ network: Network instance (used to get n_nodes)
119
+ dt: Integration time step
120
+
121
+ Returns:
122
+ Tuple of (input_data, input_state)
123
+ - input_data: Bunch with interpolator and metadata
124
+ - input_state: Empty Bunch (stateless)
125
+ """
126
+ times = self.params.times
127
+ data = self.params.data
128
+ interp_type = self.params.interpolation_type
129
+
130
+ # Create interpolation object
131
+ if interp_type == "linear":
132
+ interpolator = diffrax.LinearInterpolation(ts=times, ys=data)
133
+ else: # cubic
134
+ # Compute cubic spline coefficients
135
+ coeffs = diffrax.backward_hermite_coefficients(ts=times, ys=data)
136
+ interpolator = diffrax.CubicInterpolation(ts=times, coeffs=coeffs)
137
+
138
+ # Store interpolator and metadata
139
+ input_data = Bunch(
140
+ interpolator=interpolator,
141
+ n_nodes=network.graph.n_nodes,
142
+ data_shape=tuple(
143
+ data.shape
144
+ ), # Original data shape for broadcasting logic (as tuple)
145
+ )
146
+
147
+ # Stateless - no state to track
148
+ input_state = Bunch()
149
+
150
+ return input_data, input_state
151
+
152
+ def compute(
153
+ self,
154
+ t: float,
155
+ state: jnp.ndarray,
156
+ input_data: Bunch,
157
+ input_state: Bunch,
158
+ params: Bunch,
159
+ ) -> jnp.ndarray:
160
+ """Compute interpolated input at time t.
161
+
162
+ Args:
163
+ t: Current time
164
+ state: Network state [n_state_vars, n_nodes] (unused for stateless input)
165
+ input_data: Bunch with interpolator and metadata
166
+ input_state: Empty Bunch (stateless)
167
+ params: Parameters with times, data, interpolation_type
168
+
169
+ Returns:
170
+ Input array [n_dims, n_nodes] with interpolated values
171
+ """
172
+ interpolator = input_data.interpolator
173
+ n_nodes = input_data.n_nodes
174
+ data_shape = input_data.data_shape
175
+
176
+ # Evaluate interpolation at time t
177
+ interpolated = interpolator.evaluate(t)
178
+
179
+ # Handle broadcasting based on original data shape
180
+ if len(data_shape) == 1:
181
+ # [n_times] → scalar → broadcast to [1, n_nodes]
182
+ return jnp.full((1, n_nodes), interpolated)
183
+ elif len(data_shape) == 2:
184
+ # [n_times, n_nodes] → [n_nodes] → [1, n_nodes]
185
+ return interpolated[None, :]
186
+ else:
187
+ # [n_times, n_dims, n_nodes] → [n_dims, n_nodes]
188
+ return interpolated
189
+
190
+ def update_state(
191
+ self, input_data: Bunch, input_state: Bunch, new_state: jnp.ndarray
192
+ ) -> Bunch:
193
+ """Update input state (no-op for stateless input).
194
+
195
+ Args:
196
+ input_data: Static input data
197
+ input_state: Current state (empty)
198
+ new_state: New network state
199
+
200
+ Returns:
201
+ Unchanged input_state (empty Bunch)
202
+ """
203
+ return input_state