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.
- tvboptim/__init__.py +9 -0
- tvboptim/data/__init__.py +12 -0
- tvboptim/data/loaders.py +99 -0
- tvboptim/execution.py +268 -0
- tvboptim/experimental/__init__.py +15 -0
- tvboptim/experimental/network_dynamics/__init__.py +28 -0
- tvboptim/experimental/network_dynamics/core/__init__.py +6 -0
- tvboptim/experimental/network_dynamics/core/bunch.py +67 -0
- tvboptim/experimental/network_dynamics/core/network.py +686 -0
- tvboptim/experimental/network_dynamics/coupling/__init__.py +22 -0
- tvboptim/experimental/network_dynamics/coupling/base.py +1005 -0
- tvboptim/experimental/network_dynamics/coupling/linear.py +466 -0
- tvboptim/experimental/network_dynamics/coupling/subspace.py +509 -0
- tvboptim/experimental/network_dynamics/coupling/tvb.py +202 -0
- tvboptim/experimental/network_dynamics/dynamics/__init__.py +7 -0
- tvboptim/experimental/network_dynamics/dynamics/base.py +541 -0
- tvboptim/experimental/network_dynamics/dynamics/lorenz.py +207 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py +29 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/coombes_byrne.py +154 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/epileptor.py +200 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/generic_2d_oscillator.py +149 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/jansen_rit.py +158 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/kuramoto.py +120 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/larter_breakspear.py +221 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/linear.py +111 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/montbrio_pazo_roxin.py +137 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/sup_hopf.py +131 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/wilson_cowan.py +210 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang.py +124 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang_exc_inh.py +177 -0
- tvboptim/experimental/network_dynamics/external_input/__init__.py +20 -0
- tvboptim/experimental/network_dynamics/external_input/base.py +152 -0
- tvboptim/experimental/network_dynamics/external_input/data.py +203 -0
- tvboptim/experimental/network_dynamics/external_input/parametric.py +270 -0
- tvboptim/experimental/network_dynamics/graph/__init__.py +14 -0
- tvboptim/experimental/network_dynamics/graph/base.py +706 -0
- tvboptim/experimental/network_dynamics/graph/sparse.py +885 -0
- tvboptim/experimental/network_dynamics/graph/utils.py +0 -0
- tvboptim/experimental/network_dynamics/noise/__init__.py +6 -0
- tvboptim/experimental/network_dynamics/noise/base.py +162 -0
- tvboptim/experimental/network_dynamics/noise/gaussian.py +71 -0
- tvboptim/experimental/network_dynamics/result.py +78 -0
- tvboptim/experimental/network_dynamics/solve.py +721 -0
- tvboptim/experimental/network_dynamics/solvers/__init__.py +15 -0
- tvboptim/experimental/network_dynamics/solvers/base.py +46 -0
- tvboptim/experimental/network_dynamics/solvers/diffrax.py +63 -0
- tvboptim/experimental/network_dynamics/solvers/native.py +308 -0
- tvboptim/experimental/network_dynamics/utils/__init__.py +3 -0
- tvboptim/experimental/network_dynamics/utils/printer.py +555 -0
- tvboptim/model.py +111 -0
- tvboptim/observations/__init__.py +3 -0
- tvboptim/observations/observation.py +32 -0
- tvboptim/observations/tvb_monitors/__init__.py +11 -0
- tvboptim/observations/tvb_monitors/bold.py +290 -0
- tvboptim/observations/tvb_monitors/downsampling.py +185 -0
- tvboptim/optim/__init__.py +4 -0
- tvboptim/optim/callbacks.py +333 -0
- tvboptim/optim/optax.py +379 -0
- tvboptim/types/__init__.py +35 -0
- tvboptim/types/parameter.py +769 -0
- tvboptim/types/spaces.py +943 -0
- tvboptim/types/stateutils.py +109 -0
- tvboptim/utils/__init__.py +16 -0
- tvboptim/utils/caching.py +82 -0
- tvboptim/utils/utils.py +265 -0
- tvboptim-0.2.0.dist-info/METADATA +157 -0
- tvboptim-0.2.0.dist-info/RECORD +70 -0
- tvboptim-0.2.0.dist-info/WHEEL +5 -0
- tvboptim-0.2.0.dist-info/licenses/LICENSE +278 -0
- tvboptim-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
"""Subspace coupling: operates on regional/cluster level.
|
|
2
|
+
|
|
3
|
+
This module implements coupling that aggregates node states to regional states,
|
|
4
|
+
applies coupling at the regional level, then distributes back to nodes.
|
|
5
|
+
|
|
6
|
+
Use cases:
|
|
7
|
+
- Brain networks: 1000s of voxels → 100s of brain regions
|
|
8
|
+
- Multi-scale networks: Fine-grain nodes → coarse-grain clusters
|
|
9
|
+
- Hierarchical coupling: Different coupling strengths at different scales
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from typing import Callable, Optional, Tuple
|
|
13
|
+
|
|
14
|
+
import jax.numpy as jnp
|
|
15
|
+
|
|
16
|
+
from ..core.bunch import Bunch
|
|
17
|
+
from ..graph.base import AbstractGraph
|
|
18
|
+
from .base import AbstractCoupling
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class _RegionalNetworkContext:
|
|
22
|
+
"""Minimal context for regional coupling preparation.
|
|
23
|
+
|
|
24
|
+
This lightweight class provides only the interface needed by coupling.prepare():
|
|
25
|
+
- graph: Regional graph
|
|
26
|
+
- dynamics: Dynamics model (for state name resolution)
|
|
27
|
+
- get_initial_history(): Aggregated regional history
|
|
28
|
+
|
|
29
|
+
This avoids the need to create a full Network instance and deal with
|
|
30
|
+
property overriding issues.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
graph: AbstractGraph,
|
|
36
|
+
dynamics,
|
|
37
|
+
node_network,
|
|
38
|
+
region_one_hot_normalized: jnp.ndarray,
|
|
39
|
+
n_regions: int,
|
|
40
|
+
aggregator: Callable,
|
|
41
|
+
):
|
|
42
|
+
"""Initialize regional network context.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
graph: Regional graph
|
|
46
|
+
dynamics: Dynamics model
|
|
47
|
+
node_network: Node-level network (for history aggregation)
|
|
48
|
+
region_one_hot_normalized: [n_nodes, n_regions] normalized one-hot encoding
|
|
49
|
+
n_regions: Number of regions
|
|
50
|
+
aggregator: Function to aggregate states (typically SubspaceCoupling.aggregate)
|
|
51
|
+
"""
|
|
52
|
+
self.graph = graph
|
|
53
|
+
self.dynamics = dynamics
|
|
54
|
+
self._node_network = node_network
|
|
55
|
+
self._region_one_hot_normalized = region_one_hot_normalized
|
|
56
|
+
self._n_regions = n_regions
|
|
57
|
+
self._aggregator = aggregator
|
|
58
|
+
|
|
59
|
+
def get_initial_history(self, dt: float) -> Optional[jnp.ndarray]:
|
|
60
|
+
"""Return aggregated regional history.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
dt: Integration timestep
|
|
64
|
+
|
|
65
|
+
Returns:
|
|
66
|
+
Regional history [n_steps, n_states, n_regions] or None if no delays
|
|
67
|
+
"""
|
|
68
|
+
# Check if regional graph has delays
|
|
69
|
+
if not hasattr(self.graph, "max_delay") or self.graph.max_delay == 0.0:
|
|
70
|
+
return None
|
|
71
|
+
|
|
72
|
+
# Regional graph has delays, so we need to create history
|
|
73
|
+
# Even if node network has no delays, we need to initialize regional history
|
|
74
|
+
n_steps = int(jnp.ceil(self.graph.max_delay / dt))
|
|
75
|
+
|
|
76
|
+
# Get node-level initial state (not history, just initial state)
|
|
77
|
+
# Aggregate it and broadcast to create regional history
|
|
78
|
+
node_initial_state = self._node_network.initial_state # [n_states, n_nodes]
|
|
79
|
+
|
|
80
|
+
# Create minimal coupling_data for aggregator
|
|
81
|
+
# (contains only the precomputed fields needed for aggregation)
|
|
82
|
+
aggregation_data = Bunch(
|
|
83
|
+
region_one_hot_normalized=self._region_one_hot_normalized
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
regional_initial_state = self._aggregator(node_initial_state, aggregation_data)
|
|
87
|
+
|
|
88
|
+
# Broadcast to create history buffer
|
|
89
|
+
regional_history = jnp.broadcast_to(
|
|
90
|
+
regional_initial_state[None, :, :],
|
|
91
|
+
(n_steps, regional_initial_state.shape[0], self._n_regions),
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
return regional_history
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class SubspaceCoupling(AbstractCoupling):
|
|
98
|
+
"""Coupling that operates on a regional/cluster subspace.
|
|
99
|
+
|
|
100
|
+
Aggregates node states to regional states, applies inner coupling
|
|
101
|
+
on regional graph, then distributes results back to nodes.
|
|
102
|
+
|
|
103
|
+
Notes
|
|
104
|
+
-----
|
|
105
|
+
The coupling operates in three stages:
|
|
106
|
+
|
|
107
|
+
1. **Aggregation**: Node states are aggregated to regional states (default: mean)
|
|
108
|
+
|
|
109
|
+
$$s_r = \\text{aggregate}(\\{s_i : i \\in \\text{region } r\\})$$
|
|
110
|
+
|
|
111
|
+
2. **Regional coupling**: Inner coupling is applied on the regional graph
|
|
112
|
+
|
|
113
|
+
$$c_r = f_{\\text{coupling}}(s, \\text{regional_graph})$$
|
|
114
|
+
|
|
115
|
+
3. **Distribution**: Regional coupling is distributed back to nodes (default: broadcast)
|
|
116
|
+
|
|
117
|
+
$$c_i = \\text{distribute}(c_{\\text{region}[i]})$$
|
|
118
|
+
|
|
119
|
+
Users can customize aggregation/distribution by overriding:
|
|
120
|
+
|
|
121
|
+
- ``aggregate()``: node_state → regional_state (default: mean)
|
|
122
|
+
- ``distribute()``: regional_coupling → node_coupling (default: broadcast)
|
|
123
|
+
|
|
124
|
+
Parameters
|
|
125
|
+
----------
|
|
126
|
+
inner_coupling : AbstractCoupling
|
|
127
|
+
Coupling to apply at regional level (can be any coupling: Linear, Delayed, custom, etc.)
|
|
128
|
+
region_mapping : jnp.ndarray
|
|
129
|
+
Array with shape ``[n_nodes]`` mapping nodes to region IDs (0 to n_regions-1)
|
|
130
|
+
regional_graph : AbstractGraph
|
|
131
|
+
Graph defining region-to-region connectivity (must have n_nodes == n_regions)
|
|
132
|
+
use_sparse : bool, optional
|
|
133
|
+
If True, use BCOO sparse format for aggregation matrix (default: ``True``)
|
|
134
|
+
**kwargs
|
|
135
|
+
Additional parameters stored in ``self.params`` for custom subclasses
|
|
136
|
+
|
|
137
|
+
Attributes
|
|
138
|
+
----------
|
|
139
|
+
inner_coupling : AbstractCoupling
|
|
140
|
+
Coupling to apply at regional level
|
|
141
|
+
region_mapping : jnp.ndarray
|
|
142
|
+
Array mapping nodes to region IDs
|
|
143
|
+
regional_graph : AbstractGraph
|
|
144
|
+
Graph defining region-to-region connectivity
|
|
145
|
+
n_regions : int
|
|
146
|
+
Number of regions (derived from region_mapping)
|
|
147
|
+
N_OUTPUT_STATES : int
|
|
148
|
+
Number of output coupling states (inherited from inner_coupling)
|
|
149
|
+
|
|
150
|
+
Examples
|
|
151
|
+
--------
|
|
152
|
+
>>> # 1000 nodes mapped to 90 brain regions
|
|
153
|
+
>>> region_mapping = jnp.array([...]) # [1000] with values 0-89
|
|
154
|
+
>>> regional_graph = DelayGraph(weights_90x90, delays_90x90)
|
|
155
|
+
>>>
|
|
156
|
+
>>> coupling = SubspaceCoupling(
|
|
157
|
+
... inner_coupling=DelayedLinearCoupling(incoming_states='S', G=0.5),
|
|
158
|
+
... region_mapping=region_mapping,
|
|
159
|
+
... regional_graph=regional_graph
|
|
160
|
+
... )
|
|
161
|
+
>>>
|
|
162
|
+
>>> # Use in network with mixed coupling
|
|
163
|
+
>>> network = Network(
|
|
164
|
+
... dynamics=ReducedWongWang(),
|
|
165
|
+
... coupling={
|
|
166
|
+
... 'instant': LinearCoupling(incoming_states='S', G=0.2),
|
|
167
|
+
... 'delayed': coupling # Regional delayed coupling
|
|
168
|
+
... },
|
|
169
|
+
... graph=node_graph
|
|
170
|
+
... )
|
|
171
|
+
"""
|
|
172
|
+
|
|
173
|
+
def __init__(
|
|
174
|
+
self,
|
|
175
|
+
inner_coupling: AbstractCoupling,
|
|
176
|
+
region_mapping: jnp.ndarray,
|
|
177
|
+
regional_graph: AbstractGraph,
|
|
178
|
+
use_sparse: bool = True,
|
|
179
|
+
**kwargs,
|
|
180
|
+
):
|
|
181
|
+
"""Initialize subspace coupling.
|
|
182
|
+
|
|
183
|
+
Args:
|
|
184
|
+
inner_coupling: Coupling to apply at regional level
|
|
185
|
+
Can be any coupling (Linear, Delayed, custom, etc.)
|
|
186
|
+
region_mapping: [n_nodes] array mapping nodes to region IDs (0 to n_regions-1)
|
|
187
|
+
Example: [0, 0, 1, 1, 2, 2] maps 6 nodes to 3 regions
|
|
188
|
+
regional_graph: Graph defining region-to-region connectivity
|
|
189
|
+
Must have n_nodes == n_regions
|
|
190
|
+
use_sparse: If True, use BCOO sparse format for aggregation matrix
|
|
191
|
+
Can improve memory usage for large networks with many regions
|
|
192
|
+
**kwargs: Additional parameters (stored in self.params for custom subclasses)
|
|
193
|
+
|
|
194
|
+
Raises:
|
|
195
|
+
ValueError: If regional_graph size doesn't match number of regions
|
|
196
|
+
"""
|
|
197
|
+
# Extract state names from inner coupling
|
|
198
|
+
super().__init__(
|
|
199
|
+
incoming_states=inner_coupling.INCOMING_STATE_NAMES,
|
|
200
|
+
local_states=inner_coupling.LOCAL_STATE_NAMES,
|
|
201
|
+
**kwargs,
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
self.inner_coupling = inner_coupling
|
|
205
|
+
self.region_mapping = region_mapping
|
|
206
|
+
self.regional_graph = regional_graph
|
|
207
|
+
self.use_sparse = use_sparse
|
|
208
|
+
self.N_OUTPUT_STATES = inner_coupling.N_OUTPUT_STATES
|
|
209
|
+
|
|
210
|
+
# Validate region_mapping
|
|
211
|
+
self.n_regions = int(jnp.max(region_mapping) + 1)
|
|
212
|
+
if self.regional_graph.n_nodes != self.n_regions:
|
|
213
|
+
raise ValueError(
|
|
214
|
+
f"Regional graph has {self.regional_graph.n_nodes} nodes but "
|
|
215
|
+
f"region_mapping defines {self.n_regions} regions. They must match."
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
def prepare(self, network, dt: float) -> Tuple[Bunch, Bunch]:
|
|
219
|
+
"""Prepare regional structures and inner coupling.
|
|
220
|
+
|
|
221
|
+
Args:
|
|
222
|
+
network: Network instance (node-level)
|
|
223
|
+
dt: Integration timestep
|
|
224
|
+
|
|
225
|
+
Returns:
|
|
226
|
+
coupling_data: Bunch with regional structures and inner_data
|
|
227
|
+
coupling_state: Bunch with inner_state
|
|
228
|
+
|
|
229
|
+
Raises:
|
|
230
|
+
ValueError: If region_mapping size doesn't match network size
|
|
231
|
+
"""
|
|
232
|
+
# Validate region_mapping size matches network
|
|
233
|
+
if len(self.region_mapping) != network.graph.n_nodes:
|
|
234
|
+
raise ValueError(
|
|
235
|
+
f"region_mapping has {len(self.region_mapping)} nodes but "
|
|
236
|
+
f"network has {network.graph.n_nodes} nodes. They must match."
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
# Precompute static data for aggregation/distribution
|
|
240
|
+
n_nodes = network.graph.n_nodes
|
|
241
|
+
|
|
242
|
+
if self.use_sparse:
|
|
243
|
+
# Build sparse BCOO aggregation matrix
|
|
244
|
+
import jax.experimental.sparse as jsparse
|
|
245
|
+
|
|
246
|
+
# Create indices: one entry per node mapping to its region
|
|
247
|
+
# indices[i] = [i, region_mapping[i]]
|
|
248
|
+
indices = jnp.column_stack(
|
|
249
|
+
[jnp.arange(n_nodes), self.region_mapping]
|
|
250
|
+
) # [n_nodes, 2]
|
|
251
|
+
|
|
252
|
+
# Count nodes per region for normalization
|
|
253
|
+
region_counts = jnp.array(
|
|
254
|
+
[jnp.sum(self.region_mapping == r) for r in range(self.n_regions)]
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
# Create normalized values: 1/count[r] for each node in region r
|
|
258
|
+
values = 1.0 / region_counts[self.region_mapping] # [n_nodes]
|
|
259
|
+
|
|
260
|
+
# Create BCOO sparse matrix [n_nodes, n_regions]
|
|
261
|
+
region_one_hot_normalized = jsparse.BCOO(
|
|
262
|
+
(values, indices), shape=(n_nodes, self.n_regions)
|
|
263
|
+
)
|
|
264
|
+
else:
|
|
265
|
+
# Dense version (original)
|
|
266
|
+
region_one_hot = jnp.eye(self.n_regions)[self.region_mapping]
|
|
267
|
+
region_counts = jnp.sum(region_one_hot, axis=0)
|
|
268
|
+
region_one_hot_normalized = region_one_hot / region_counts[None, :]
|
|
269
|
+
|
|
270
|
+
# Create regional context for inner coupling preparation
|
|
271
|
+
regional_context = self._create_regional_context(
|
|
272
|
+
network, region_one_hot_normalized
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
# Prepare inner coupling with regional context
|
|
276
|
+
inner_data, inner_state = self.inner_coupling.prepare(regional_context, dt)
|
|
277
|
+
|
|
278
|
+
coupling_data = Bunch(
|
|
279
|
+
n_regions=self.n_regions,
|
|
280
|
+
region_one_hot_normalized=region_one_hot_normalized, # Normalized for mean aggregation
|
|
281
|
+
region_mapping=self.region_mapping, # For distribute()
|
|
282
|
+
inner_data=inner_data,
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
coupling_state = Bunch(inner_state=inner_state)
|
|
286
|
+
|
|
287
|
+
return coupling_data, coupling_state
|
|
288
|
+
|
|
289
|
+
def _create_regional_context(self, node_network, region_one_hot_normalized):
|
|
290
|
+
"""Create regional context for inner coupling preparation.
|
|
291
|
+
|
|
292
|
+
This creates a lightweight mock that provides only what coupling.prepare()
|
|
293
|
+
needs: graph, dynamics, and get_initial_history().
|
|
294
|
+
|
|
295
|
+
Args:
|
|
296
|
+
node_network: Node-level Network instance
|
|
297
|
+
region_one_hot_normalized: Precomputed normalized one-hot encoding
|
|
298
|
+
|
|
299
|
+
Returns:
|
|
300
|
+
_RegionalNetworkContext instance with regional graph and aggregated history
|
|
301
|
+
"""
|
|
302
|
+
return _RegionalNetworkContext(
|
|
303
|
+
graph=self.regional_graph,
|
|
304
|
+
dynamics=node_network.dynamics,
|
|
305
|
+
node_network=node_network,
|
|
306
|
+
region_one_hot_normalized=region_one_hot_normalized,
|
|
307
|
+
n_regions=self.n_regions,
|
|
308
|
+
aggregator=self.aggregate,
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
def compute(
|
|
312
|
+
self,
|
|
313
|
+
t: float,
|
|
314
|
+
state: jnp.ndarray,
|
|
315
|
+
coupling_data: Bunch,
|
|
316
|
+
coupling_state: Bunch,
|
|
317
|
+
params: Bunch,
|
|
318
|
+
graph: AbstractGraph,
|
|
319
|
+
) -> jnp.ndarray:
|
|
320
|
+
"""Compute subspace coupling: aggregate → couple → distribute.
|
|
321
|
+
|
|
322
|
+
Args:
|
|
323
|
+
t: Current simulation time
|
|
324
|
+
state: Current network state [n_states, n_nodes]
|
|
325
|
+
coupling_data: Precomputed regional structures
|
|
326
|
+
coupling_state: Inner coupling state
|
|
327
|
+
params: Coupling parameters (not used - inner coupling has its own params)
|
|
328
|
+
graph: Node-level graph (not used - regional_graph used instead)
|
|
329
|
+
|
|
330
|
+
Returns:
|
|
331
|
+
Node-level coupling input [n_coupling_inputs, n_nodes]
|
|
332
|
+
"""
|
|
333
|
+
# 1. Aggregate: node states → regional states
|
|
334
|
+
regional_state = self.aggregate(state, coupling_data)
|
|
335
|
+
|
|
336
|
+
# 2. Compute coupling at regional level
|
|
337
|
+
regional_coupling = self.inner_coupling.compute(
|
|
338
|
+
t,
|
|
339
|
+
regional_state,
|
|
340
|
+
coupling_data.inner_data,
|
|
341
|
+
coupling_state.inner_state,
|
|
342
|
+
self.inner_coupling.params, # Use inner coupling's params
|
|
343
|
+
self.regional_graph,
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
# 3. Distribute: regional coupling → node coupling
|
|
347
|
+
node_coupling = self.distribute(regional_coupling, coupling_data)
|
|
348
|
+
|
|
349
|
+
return node_coupling
|
|
350
|
+
|
|
351
|
+
def update_state(
|
|
352
|
+
self, coupling_data: Bunch, coupling_state: Bunch, new_state: jnp.ndarray
|
|
353
|
+
) -> Bunch:
|
|
354
|
+
"""Update inner coupling state (e.g., regional history buffer).
|
|
355
|
+
|
|
356
|
+
Args:
|
|
357
|
+
coupling_data: Precomputed regional structures
|
|
358
|
+
coupling_state: Current inner coupling state
|
|
359
|
+
new_state: New network state [n_states, n_nodes]
|
|
360
|
+
|
|
361
|
+
Returns:
|
|
362
|
+
Updated coupling_state with new inner_state
|
|
363
|
+
"""
|
|
364
|
+
# Aggregate new node state to regional state
|
|
365
|
+
regional_state = self.aggregate(new_state, coupling_data)
|
|
366
|
+
|
|
367
|
+
# Update inner coupling state with regional state
|
|
368
|
+
new_inner_state = self.inner_coupling.update_state(
|
|
369
|
+
coupling_data.inner_data, coupling_state.inner_state, regional_state
|
|
370
|
+
)
|
|
371
|
+
|
|
372
|
+
return Bunch(inner_state=new_inner_state)
|
|
373
|
+
|
|
374
|
+
# ========================================================================
|
|
375
|
+
# Customizable Methods (like pre/post pattern)
|
|
376
|
+
# ========================================================================
|
|
377
|
+
|
|
378
|
+
def aggregate(self, node_state: jnp.ndarray, coupling_data: Bunch) -> jnp.ndarray:
|
|
379
|
+
"""Aggregate node states to regional states. Default: mean.
|
|
380
|
+
|
|
381
|
+
Override this method to customize aggregation strategy.
|
|
382
|
+
|
|
383
|
+
Args:
|
|
384
|
+
node_state: [n_states, n_nodes] node-level states
|
|
385
|
+
coupling_data: Bunch containing precomputed aggregation data
|
|
386
|
+
(region_one_hot_normalized, etc.)
|
|
387
|
+
|
|
388
|
+
Returns:
|
|
389
|
+
regional_state: [n_states, n_regions] region-level states
|
|
390
|
+
|
|
391
|
+
Examples:
|
|
392
|
+
Mean (default): Use normalized region_one_hot_normalized (single matmul)
|
|
393
|
+
Sum: Use unnormalized region_one_hot instead
|
|
394
|
+
Weighted: Add custom aggregation matrix to coupling_data in prepare()
|
|
395
|
+
|
|
396
|
+
Note:
|
|
397
|
+
coupling_data is populated in prepare() and contains all precomputed
|
|
398
|
+
static data needed for aggregation. By default, region_one_hot_normalized
|
|
399
|
+
is pre-divided by region counts, so a single matrix multiply computes the mean.
|
|
400
|
+
Supports both dense and BCOO sparse matrices automatically.
|
|
401
|
+
"""
|
|
402
|
+
# Mean aggregation via single matrix multiply
|
|
403
|
+
# [n_states, n_nodes] @ [n_nodes, n_regions] → [n_states, n_regions]
|
|
404
|
+
# Works for both dense and sparse (BCOO) matrices
|
|
405
|
+
regional_state = node_state @ coupling_data.region_one_hot_normalized
|
|
406
|
+
|
|
407
|
+
return regional_state
|
|
408
|
+
|
|
409
|
+
def distribute(
|
|
410
|
+
self, regional_coupling: jnp.ndarray, coupling_data: Bunch
|
|
411
|
+
) -> jnp.ndarray:
|
|
412
|
+
"""Distribute regional coupling to node-level coupling. Default: broadcast.
|
|
413
|
+
|
|
414
|
+
Override this method to customize distribution strategy.
|
|
415
|
+
|
|
416
|
+
Args:
|
|
417
|
+
regional_coupling: [n_coupling_inputs, n_regions] regional coupling
|
|
418
|
+
coupling_data: Bunch containing precomputed distribution data
|
|
419
|
+
(region_mapping, region_counts, etc.)
|
|
420
|
+
|
|
421
|
+
Returns:
|
|
422
|
+
node_coupling: [n_coupling_inputs, n_nodes] node-level coupling
|
|
423
|
+
|
|
424
|
+
Examples:
|
|
425
|
+
Broadcast (default): All nodes in region get same value
|
|
426
|
+
Scaled: Divide by region_counts from coupling_data
|
|
427
|
+
Weighted: Add custom distribution weights to coupling_data in prepare()
|
|
428
|
+
|
|
429
|
+
Note:
|
|
430
|
+
coupling_data is populated in prepare() and contains all precomputed
|
|
431
|
+
static data needed for distribution. This design allows flexible
|
|
432
|
+
customization without changing the API.
|
|
433
|
+
"""
|
|
434
|
+
# Broadcast: all nodes in region r get regional_coupling[:, r]
|
|
435
|
+
node_coupling = regional_coupling[:, coupling_data.region_mapping]
|
|
436
|
+
|
|
437
|
+
return node_coupling
|
|
438
|
+
|
|
439
|
+
def describe(self) -> dict:
|
|
440
|
+
"""Generate human-readable description of subspace coupling for printing.
|
|
441
|
+
|
|
442
|
+
Delegates to inner coupling and adds regional/subspace information.
|
|
443
|
+
|
|
444
|
+
Returns:
|
|
445
|
+
Dictionary with coupling description including regional structure
|
|
446
|
+
"""
|
|
447
|
+
# Check if inner coupling has describe() method
|
|
448
|
+
if hasattr(self.inner_coupling, "describe"):
|
|
449
|
+
inner_desc = self.inner_coupling.describe()
|
|
450
|
+
else:
|
|
451
|
+
# Fallback for couplings without describe()
|
|
452
|
+
inner_desc = {}
|
|
453
|
+
|
|
454
|
+
# Determine type from inner coupling class
|
|
455
|
+
from .base import DelayedCoupling
|
|
456
|
+
|
|
457
|
+
coupling_type = (
|
|
458
|
+
"delayed"
|
|
459
|
+
if isinstance(self.inner_coupling, DelayedCoupling)
|
|
460
|
+
else "instantaneous"
|
|
461
|
+
)
|
|
462
|
+
|
|
463
|
+
# Build description with subspace-specific information
|
|
464
|
+
desc = {
|
|
465
|
+
"class_name": f"Subspace({self.inner_coupling.__class__.__name__})",
|
|
466
|
+
"type": inner_desc.get("type", coupling_type), # Use inner type or infer
|
|
467
|
+
"incoming_states": inner_desc.get("incoming_states", []),
|
|
468
|
+
"local_states": inner_desc.get("local_states", []),
|
|
469
|
+
"params": inner_desc.get("params", {}),
|
|
470
|
+
"network_form": inner_desc.get("network_form", ""),
|
|
471
|
+
"pre_form": inner_desc.get("pre_form"),
|
|
472
|
+
"post_form": inner_desc.get("post_form"),
|
|
473
|
+
# Subspace-specific fields
|
|
474
|
+
"n_regions": self.n_regions,
|
|
475
|
+
"aggregation": self._get_aggregation_method_name(),
|
|
476
|
+
"distribution": self._get_distribution_method_name(),
|
|
477
|
+
"inner_coupling_name": self.inner_coupling.__class__.__name__,
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
# Modify network_form to indicate regional operation
|
|
481
|
+
if desc["network_form"]:
|
|
482
|
+
# Replace node index j with region index r (Unicode subscripts)
|
|
483
|
+
regional_form = (
|
|
484
|
+
desc["network_form"]
|
|
485
|
+
.replace("ⱼ", "ᵣ")
|
|
486
|
+
.replace("wᵢⱼ", "wᵢᵣ")
|
|
487
|
+
.replace("τᵢⱼ", "τᵢᵣ")
|
|
488
|
+
)
|
|
489
|
+
desc["network_form"] = f"[{self.n_regions} regions] {regional_form}"
|
|
490
|
+
|
|
491
|
+
# Add regional max_delay if applicable
|
|
492
|
+
if desc["type"] == "delayed" and hasattr(self.regional_graph, "max_delay"):
|
|
493
|
+
desc["max_delay"] = self.regional_graph.max_delay
|
|
494
|
+
|
|
495
|
+
return desc
|
|
496
|
+
|
|
497
|
+
def _get_aggregation_method_name(self) -> str:
|
|
498
|
+
"""Get the name of the aggregation method (for printing)."""
|
|
499
|
+
# Check if user overrode aggregate method
|
|
500
|
+
if type(self).aggregate is not SubspaceCoupling.aggregate:
|
|
501
|
+
return "custom"
|
|
502
|
+
return "mean"
|
|
503
|
+
|
|
504
|
+
def _get_distribution_method_name(self) -> str:
|
|
505
|
+
"""Get the name of the distribution method (for printing)."""
|
|
506
|
+
# Check if user overrode distribute method
|
|
507
|
+
if type(self).distribute is not SubspaceCoupling.distribute:
|
|
508
|
+
return "custom"
|
|
509
|
+
return "broadcast"
|