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,32 @@
|
|
|
1
|
+
import jax.numpy as jnp
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def compute_fc(timeseries, s_var=0, mode=0, skip_t=0):
|
|
5
|
+
"""Compute functional connectivity matrix from timeseries data.
|
|
6
|
+
|
|
7
|
+
Args:
|
|
8
|
+
timeseries: Timeseries data with .data attribute
|
|
9
|
+
s_var: State variable index (default: 0)
|
|
10
|
+
mode: Mode index for 4D data (default: 0)
|
|
11
|
+
skip_t: Number of initial timepoints to skip (default: 0)
|
|
12
|
+
|
|
13
|
+
Returns:
|
|
14
|
+
Functional connectivity matrix with diagonal set to 0
|
|
15
|
+
"""
|
|
16
|
+
if hasattr(timeseries, "data"):
|
|
17
|
+
timeseries = timeseries.data
|
|
18
|
+
if timeseries.ndim < 4:
|
|
19
|
+
_fc = jnp.corrcoef(timeseries[skip_t:, s_var, :], rowvar=False)
|
|
20
|
+
else:
|
|
21
|
+
_fc = jnp.corrcoef(timeseries[skip_t:, s_var, :, mode], rowvar=False)
|
|
22
|
+
# diag elements 0
|
|
23
|
+
return _fc.at[jnp.diag_indices(_fc.shape[0])].set(0)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def fc_corr(fc1, fc2):
|
|
27
|
+
return jnp.corrcoef(fc1.flatten(), fc2.flatten())[0, 1]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def rmse(matrix1, matrix2, axis=None):
|
|
31
|
+
rmse_value = jnp.sqrt(jnp.square(matrix1 - matrix2).mean(axis=axis))
|
|
32
|
+
return rmse_value
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
from .bold import Bold, HRFKernel, LotkaVolterraHRFKernel
|
|
2
|
+
from .downsampling import AbstractMonitor, SubSampling, TemporalAverage
|
|
3
|
+
|
|
4
|
+
__all__ = [
|
|
5
|
+
"AbstractMonitor",
|
|
6
|
+
"SubSampling",
|
|
7
|
+
"TemporalAverage",
|
|
8
|
+
"Bold",
|
|
9
|
+
"LotkaVolterraHRFKernel",
|
|
10
|
+
"HRFKernel",
|
|
11
|
+
]
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import math
|
|
2
|
+
|
|
3
|
+
import equinox as eqx
|
|
4
|
+
import jax
|
|
5
|
+
import jax.numpy as jnp
|
|
6
|
+
import jax.scipy as jsp
|
|
7
|
+
import matplotlib.pyplot as plt
|
|
8
|
+
|
|
9
|
+
from tvboptim.experimental.network_dynamics.result import NativeSolution
|
|
10
|
+
|
|
11
|
+
from .downsampling import AbstractMonitor, TemporalAverage
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class HRFKernel(eqx.Module):
|
|
15
|
+
"""Base class for hemodynamic response function kernels.
|
|
16
|
+
|
|
17
|
+
A kernel is a function of time that defines the hemodynamic response.
|
|
18
|
+
Subclasses must implement the kernel computation and specify its duration.
|
|
19
|
+
|
|
20
|
+
Attributes:
|
|
21
|
+
duration: Duration of kernel support in milliseconds
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
duration: float
|
|
25
|
+
|
|
26
|
+
def __call__(self, t: jax.Array, downsample_dt: float) -> jax.Array:
|
|
27
|
+
"""Compute kernel values at time points.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
t: Time points at which to evaluate the kernel
|
|
31
|
+
downsample_dt: Time step of downsampled signal (for internal use)
|
|
32
|
+
|
|
33
|
+
Returns:
|
|
34
|
+
Kernel values at the specified time points
|
|
35
|
+
"""
|
|
36
|
+
raise NotImplementedError
|
|
37
|
+
|
|
38
|
+
def plot(self, dt=1.0, ax=None):
|
|
39
|
+
"""Plot the kernel function over its duration.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
dt: Time step in milliseconds (default: 1.0 ms)
|
|
43
|
+
ax: Matplotlib axis to plot on (default: None, creates new figure)
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
Matplotlib axis object
|
|
47
|
+
"""
|
|
48
|
+
if ax is None:
|
|
49
|
+
_, ax = plt.subplots(figsize=(10, 4))
|
|
50
|
+
|
|
51
|
+
# Compute number of samples from duration and dt
|
|
52
|
+
n_samples = int(jnp.ceil(self.duration / dt))
|
|
53
|
+
|
|
54
|
+
# Evaluate kernel over its duration
|
|
55
|
+
t = jnp.linspace(0.0, self.duration, n_samples)
|
|
56
|
+
kernel_values = self(t, dt)
|
|
57
|
+
|
|
58
|
+
# Plot
|
|
59
|
+
ax.plot(t, kernel_values)
|
|
60
|
+
ax.set_xlabel("Time (ms)")
|
|
61
|
+
ax.set_ylabel("Kernel value")
|
|
62
|
+
ax.set_title(f"{self.__class__.__name__}")
|
|
63
|
+
ax.grid(True, alpha=0.3)
|
|
64
|
+
|
|
65
|
+
return ax
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class LotkaVolterraHRFKernel(HRFKernel):
|
|
69
|
+
"""Canonical hemodynamic response function based on Lotka-Volterra dynamics.
|
|
70
|
+
|
|
71
|
+
This implements the oscillatory HRF kernel used in standard BOLD signal modeling.
|
|
72
|
+
|
|
73
|
+
Attributes:
|
|
74
|
+
tau_s: Signal decay time constant in seconds (default: 0.8 s)
|
|
75
|
+
tau_f: Feedback time constant in seconds (default: 0.4 s)
|
|
76
|
+
scaling: Kernel amplitude scaling factor (default: 1/3)
|
|
77
|
+
duration: Kernel support duration in ms (default: 20,000 ms = 20 s)
|
|
78
|
+
|
|
79
|
+
Note:
|
|
80
|
+
The tau parameters are in seconds (not ms) to match the standard HRF formulation.
|
|
81
|
+
Time input to __call__ is expected in milliseconds and converted internally.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
tau_s: float = 0.8 # seconds
|
|
85
|
+
tau_f: float = 0.4 # seconds
|
|
86
|
+
scaling: float = 1.0 / 3.0
|
|
87
|
+
duration: float = 20_000.0 # ms (20 seconds)
|
|
88
|
+
|
|
89
|
+
def __init__(self, tau_s=0.8, tau_f=0.4, scaling=1.0 / 3.0, duration=20_000.0):
|
|
90
|
+
"""Initialize Lotka-Volterra HRF kernel.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
tau_s: Signal decay time constant in seconds (default: 0.8 s)
|
|
94
|
+
tau_f: Feedback time constant in seconds (default: 0.4 s)
|
|
95
|
+
scaling: Kernel amplitude scaling factor (default: 1/3)
|
|
96
|
+
duration: Kernel support duration in ms (default: 20,000 ms)
|
|
97
|
+
"""
|
|
98
|
+
self.tau_s = tau_s
|
|
99
|
+
self.tau_f = tau_f
|
|
100
|
+
self.scaling = scaling
|
|
101
|
+
self.duration = duration
|
|
102
|
+
|
|
103
|
+
def __call__(self, t: jax.Array, downsample_dt: float) -> jax.Array:
|
|
104
|
+
"""Compute Lotka-Volterra HRF kernel.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
t: Time points in milliseconds at which to evaluate the kernel
|
|
108
|
+
downsample_dt: Not used for this kernel
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
HRF kernel values
|
|
112
|
+
"""
|
|
113
|
+
# Convert time from ms to seconds for the HRF formula
|
|
114
|
+
t_seconds = t / 1000.0
|
|
115
|
+
|
|
116
|
+
omega = jnp.sqrt(1.0 / self.tau_f - 1.0 / (4.0 * self.tau_s**2))
|
|
117
|
+
return (
|
|
118
|
+
self.scaling
|
|
119
|
+
* jnp.exp(-0.5 * (t_seconds / self.tau_s))
|
|
120
|
+
* jnp.sin(omega * t_seconds)
|
|
121
|
+
/ omega
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class Bold(AbstractMonitor):
|
|
126
|
+
"""BOLD signal monitor using hemodynamic response function convolution.
|
|
127
|
+
|
|
128
|
+
This monitor simulates the Blood Oxygen Level Dependent (BOLD) signal by:
|
|
129
|
+
1. Downsampling the neural activity
|
|
130
|
+
2. Convolving with a hemodynamic response function kernel
|
|
131
|
+
3. Downsampling to the final BOLD sampling period
|
|
132
|
+
"""
|
|
133
|
+
|
|
134
|
+
# BOLD model parameters
|
|
135
|
+
k_1: float = 5.6 # Signal scaling factor
|
|
136
|
+
V_0: float = 0.02 # Resting blood volume fraction
|
|
137
|
+
|
|
138
|
+
# Sampling parameters
|
|
139
|
+
period: float = 1000.0 # ms, final BOLD sampling period
|
|
140
|
+
downsample_period: float = 4.0 # ms, intermediate downsampling period
|
|
141
|
+
|
|
142
|
+
# Processing configuration
|
|
143
|
+
kernel: HRFKernel = eqx.field(static=True)
|
|
144
|
+
downsample: eqx.Module = eqx.field(static=True)
|
|
145
|
+
convolution_mode: str = eqx.field(static=True)
|
|
146
|
+
|
|
147
|
+
# History buffer for continuous monitoring
|
|
148
|
+
history: jax.Array = None
|
|
149
|
+
|
|
150
|
+
def __init__(
|
|
151
|
+
self,
|
|
152
|
+
k_1=5.6,
|
|
153
|
+
V_0=0.02,
|
|
154
|
+
period=1000.0,
|
|
155
|
+
downsample_period=4.0,
|
|
156
|
+
kernel=None,
|
|
157
|
+
downsample=None,
|
|
158
|
+
voi=None,
|
|
159
|
+
convolution_mode="valid",
|
|
160
|
+
history=None,
|
|
161
|
+
):
|
|
162
|
+
"""Initialize BOLD monitor.
|
|
163
|
+
|
|
164
|
+
Args:
|
|
165
|
+
k_1: Signal scaling factor (default: 5.6)
|
|
166
|
+
V_0: Resting blood volume fraction (default: 0.02)
|
|
167
|
+
period: Final BOLD sampling period in ms (default: 1000.0)
|
|
168
|
+
downsample_period: Intermediate downsampling period in ms (default: 4.0)
|
|
169
|
+
kernel: HRF kernel to use (default: LotkaVolterraHRFKernel())
|
|
170
|
+
downsample: Downsampling strategy (default: TemporalAverage with voi)
|
|
171
|
+
voi: Variable of interest index for downsampling
|
|
172
|
+
convolution_mode: Convolution mode - 'valid', 'same', or 'full' (default: 'valid')
|
|
173
|
+
history: Prior data for warm start. Can be None (zeros), jax.Array, or NativeSolution
|
|
174
|
+
"""
|
|
175
|
+
# Normalize voi using base class method
|
|
176
|
+
self.voi = self._normalize_voi(voi)
|
|
177
|
+
|
|
178
|
+
self.k_1 = k_1
|
|
179
|
+
self.V_0 = V_0
|
|
180
|
+
self.period = period
|
|
181
|
+
self.downsample_period = downsample_period
|
|
182
|
+
self.convolution_mode = convolution_mode
|
|
183
|
+
|
|
184
|
+
# Set up kernel
|
|
185
|
+
if kernel is None:
|
|
186
|
+
self.kernel = LotkaVolterraHRFKernel()
|
|
187
|
+
else:
|
|
188
|
+
self.kernel = kernel
|
|
189
|
+
|
|
190
|
+
# Set up downsampling
|
|
191
|
+
if downsample is None:
|
|
192
|
+
# Pass the already normalized voi to the downsampler
|
|
193
|
+
self.downsample = TemporalAverage(voi=self.voi, period=downsample_period)
|
|
194
|
+
else:
|
|
195
|
+
self.downsample = downsample
|
|
196
|
+
|
|
197
|
+
# Process history buffer
|
|
198
|
+
self.history = self._process_history(history)
|
|
199
|
+
|
|
200
|
+
def _process_history(self, history):
|
|
201
|
+
"""Process history input into standardized buffer.
|
|
202
|
+
|
|
203
|
+
Args:
|
|
204
|
+
history: None (default to zeros), jax.Array, or Solution object (Native or Diffrax)
|
|
205
|
+
|
|
206
|
+
Returns:
|
|
207
|
+
Processed history array or None
|
|
208
|
+
"""
|
|
209
|
+
if history is None:
|
|
210
|
+
return None
|
|
211
|
+
elif hasattr(history, "ys") and hasattr(history, "ts"):
|
|
212
|
+
# Duck typing: any solution-like object with .ys and .ts attributes
|
|
213
|
+
# Works with both NativeSolution and Diffrax solutions
|
|
214
|
+
# Extract the required history length based on kernel duration
|
|
215
|
+
# Use Python int() and math.ceil() to keep concrete during JIT
|
|
216
|
+
n_samples = int(math.ceil(self.kernel.duration / self.downsample_period))
|
|
217
|
+
# Downsample the history first
|
|
218
|
+
downsampled_history = self.downsample(history)
|
|
219
|
+
# Take the last n_samples
|
|
220
|
+
return downsampled_history.ys[-n_samples:]
|
|
221
|
+
else:
|
|
222
|
+
# Assume it's already a jax.Array
|
|
223
|
+
return history
|
|
224
|
+
|
|
225
|
+
def __call__(self, sol, t_offset=0.0):
|
|
226
|
+
"""Apply BOLD monitor to simulation results.
|
|
227
|
+
|
|
228
|
+
Args:
|
|
229
|
+
sol: Simulation solution with .ys, .ts, and .dt attributes
|
|
230
|
+
Works with NativeSolution (requires dt as auxiliary data)
|
|
231
|
+
t_offset: Time offset to add to output timestamps (default: 0.0)
|
|
232
|
+
|
|
233
|
+
Returns:
|
|
234
|
+
NativeSolution with BOLD signal timeseries
|
|
235
|
+
"""
|
|
236
|
+
ts = sol.ts
|
|
237
|
+
dt = sol.dt # Use dt from auxiliary data
|
|
238
|
+
|
|
239
|
+
# --- Downsample neural activity ---
|
|
240
|
+
downsampled = self.downsample(sol)
|
|
241
|
+
ys_downsampled = downsampled.ys
|
|
242
|
+
|
|
243
|
+
# --- Create HRF kernel ---
|
|
244
|
+
# Compute kernel sample points using Python int() and math.ceil()
|
|
245
|
+
kernel_samples = int(math.ceil(self.kernel.duration / self.downsample_period))
|
|
246
|
+
kernel_time = jnp.linspace(0.0, self.kernel.duration, kernel_samples)
|
|
247
|
+
hrf = self.kernel(kernel_time, self.downsample_period)
|
|
248
|
+
|
|
249
|
+
# --- Prepare signal with history buffer ---
|
|
250
|
+
if self.history is None:
|
|
251
|
+
# Prepend zeros for warm-up
|
|
252
|
+
ys_with_history = jnp.vstack(
|
|
253
|
+
[jnp.zeros((kernel_samples, *ys_downsampled.shape[1:])), ys_downsampled]
|
|
254
|
+
)
|
|
255
|
+
else:
|
|
256
|
+
# Use provided history
|
|
257
|
+
ys_with_history = jnp.vstack([self.history, ys_downsampled])
|
|
258
|
+
|
|
259
|
+
# --- Convolution with HRF ---
|
|
260
|
+
def convolve_single(x):
|
|
261
|
+
return jsp.signal.fftconvolve(x, hrf, mode=self.convolution_mode)
|
|
262
|
+
|
|
263
|
+
# Vectorized convolution over nodes and state variables
|
|
264
|
+
bold = jax.vmap(
|
|
265
|
+
lambda y: jax.vmap(convolve_single, in_axes=1, out_axes=1)(y),
|
|
266
|
+
in_axes=1,
|
|
267
|
+
out_axes=1,
|
|
268
|
+
)(ys_with_history)
|
|
269
|
+
|
|
270
|
+
# Apply BOLD scaling
|
|
271
|
+
bold = self.k_1 * self.V_0 * (bold - 1.0)
|
|
272
|
+
|
|
273
|
+
# --- Final downsampling to BOLD sampling period ---
|
|
274
|
+
# Compute index step for final sampling using Python int() and round()
|
|
275
|
+
final_samples_per_period = self.period / self.downsample_period
|
|
276
|
+
final_idx_step = int(round(final_samples_per_period))
|
|
277
|
+
|
|
278
|
+
# Sample at the specified period
|
|
279
|
+
bold_indices = jnp.arange(0, bold.shape[0], final_idx_step)
|
|
280
|
+
bold_signal = bold[bold_indices, ...]
|
|
281
|
+
|
|
282
|
+
# Create time points for BOLD signal using Python int() and round()
|
|
283
|
+
bold_time = ts[:: int(round(self.period / dt))] + t_offset
|
|
284
|
+
|
|
285
|
+
# Ensure time and signal arrays match in length
|
|
286
|
+
min_len = min(len(bold_time), len(bold_signal))
|
|
287
|
+
bold_time = bold_time[:min_len]
|
|
288
|
+
bold_signal = bold_signal[:min_len]
|
|
289
|
+
|
|
290
|
+
return NativeSolution(ts=bold_time, ys=bold_signal, dt=self.period)
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Downsampling strategies for neural activity timeseries.
|
|
2
|
+
|
|
3
|
+
This module provides different methods for reducing the temporal resolution
|
|
4
|
+
of simulation outputs, commonly used before BOLD signal computation.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import equinox as eqx
|
|
8
|
+
import jax
|
|
9
|
+
import jax.numpy as jnp
|
|
10
|
+
|
|
11
|
+
from tvboptim.experimental.network_dynamics.result import NativeSolution
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class AbstractMonitor(eqx.Module):
|
|
15
|
+
"""Base class for monitoring and downsampling strategies.
|
|
16
|
+
|
|
17
|
+
Provides common functionality for handling variable of interest (voi)
|
|
18
|
+
parameter normalization to ensure dimensions are preserved.
|
|
19
|
+
|
|
20
|
+
Attributes:
|
|
21
|
+
voi: Variable of interest (state variable index) to extract.
|
|
22
|
+
Normalized to preserve dimensions.
|
|
23
|
+
period: Sampling/averaging period in milliseconds
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
voi: object = eqx.field(static=True)
|
|
27
|
+
period: float = eqx.field(static=True)
|
|
28
|
+
|
|
29
|
+
@staticmethod
|
|
30
|
+
def _normalize_voi(voi):
|
|
31
|
+
"""Normalize voi to preserve dimensions.
|
|
32
|
+
|
|
33
|
+
Converts integers and single-index slices to dimension-preserving slices.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
voi: Variable of interest specification. Can be:
|
|
37
|
+
- None: uses all variables (jnp.s_[:])
|
|
38
|
+
- int: single index (converted to slice)
|
|
39
|
+
- slice: slice object (normalized if single-index)
|
|
40
|
+
- other: passed through as-is
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
Normalized voi that preserves dimensions
|
|
44
|
+
"""
|
|
45
|
+
if voi is None:
|
|
46
|
+
return jnp.s_[:]
|
|
47
|
+
elif isinstance(voi, int):
|
|
48
|
+
return jnp.s_[voi : voi + 1] # Preserves dimension
|
|
49
|
+
elif isinstance(voi, slice):
|
|
50
|
+
# Check if it's a single-index slice like jnp.s_[0]
|
|
51
|
+
# These have start, stop, step where stop is None and step is None
|
|
52
|
+
if voi.stop is None and voi.step is None and isinstance(voi.start, int):
|
|
53
|
+
# Convert to dimension-preserving slice
|
|
54
|
+
return jnp.s_[voi.start : voi.start + 1]
|
|
55
|
+
else:
|
|
56
|
+
return voi
|
|
57
|
+
else:
|
|
58
|
+
# Assume it's already in the correct format
|
|
59
|
+
return voi
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class SubSampling(AbstractMonitor):
|
|
63
|
+
"""Downsample timeseries by selecting every nth sample.
|
|
64
|
+
|
|
65
|
+
This is a simple point-wise downsampling strategy that picks samples
|
|
66
|
+
at regular intervals without any averaging.
|
|
67
|
+
|
|
68
|
+
Attributes:
|
|
69
|
+
voi: Variable of interest (state variable index) to extract.
|
|
70
|
+
If None, uses all variables.
|
|
71
|
+
period: Sampling period in milliseconds (default: 4.0)
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
period: float = eqx.field(static=True)
|
|
75
|
+
|
|
76
|
+
def __init__(self, voi=None, period=4.0):
|
|
77
|
+
"""Initialize SubSampling.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
voi: Variable of interest index. If None, extracts all state variables.
|
|
81
|
+
If integer, the dimension is preserved using slice notation.
|
|
82
|
+
period: Sampling period in milliseconds (default: 4.0)
|
|
83
|
+
"""
|
|
84
|
+
self.voi = self._normalize_voi(voi)
|
|
85
|
+
self.period = period
|
|
86
|
+
|
|
87
|
+
def __call__(self, sol, t_offset=0.0):
|
|
88
|
+
"""Downsample the solution by selecting every nth sample.
|
|
89
|
+
|
|
90
|
+
Args:
|
|
91
|
+
sol: Simulation solution with .ys, .ts, and .dt attributes
|
|
92
|
+
Works with NativeSolution (requires dt as auxiliary data)
|
|
93
|
+
t_offset: Time offset to add to output timestamps (default: 0.0)
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
NativeSolution with downsampled timeseries
|
|
97
|
+
"""
|
|
98
|
+
ts, ys = sol.ts, sol.ys
|
|
99
|
+
# Use sol.dt from auxiliary data and convert with Python int()
|
|
100
|
+
# This keeps sample_step concrete during JIT compilation
|
|
101
|
+
sample_step = int(round(self.period / sol.dt))
|
|
102
|
+
# Select indices at regular intervals
|
|
103
|
+
sample_indices = jnp.arange(sample_step - 1, ts.shape[0], sample_step)
|
|
104
|
+
return NativeSolution(
|
|
105
|
+
ts=ts[sample_indices] + t_offset,
|
|
106
|
+
ys=ys[sample_indices, self.voi, ...],
|
|
107
|
+
dt=self.period,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class TemporalAverage(AbstractMonitor):
|
|
112
|
+
"""Downsample timeseries by averaging over temporal windows.
|
|
113
|
+
|
|
114
|
+
This downsampling strategy computes the mean over non-overlapping
|
|
115
|
+
temporal windows, providing smoother output than simple subsampling.
|
|
116
|
+
The output timestamps are centered within each averaging window.
|
|
117
|
+
|
|
118
|
+
Attributes:
|
|
119
|
+
voi: Variable of interest (state variable index) to extract.
|
|
120
|
+
If None, uses all variables.
|
|
121
|
+
period: Averaging window size in milliseconds (default: 4.0)
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
# period: float = 4.0
|
|
125
|
+
period: float = eqx.field(static=True)
|
|
126
|
+
|
|
127
|
+
def __init__(self, voi=None, period=4.0):
|
|
128
|
+
"""Initialize TemporalAverage.
|
|
129
|
+
|
|
130
|
+
Args:
|
|
131
|
+
voi: Variable of interest index. If None, extracts all state variables.
|
|
132
|
+
If integer, the dimension is preserved using slice notation.
|
|
133
|
+
period: Averaging window size in milliseconds (default: 4.0)
|
|
134
|
+
"""
|
|
135
|
+
self.voi = self._normalize_voi(voi)
|
|
136
|
+
self.period = period
|
|
137
|
+
|
|
138
|
+
def __call__(self, sol):
|
|
139
|
+
"""Downsample by averaging over temporal windows.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
sol: Simulation solution with .ys, .ts, and .dt attributes
|
|
143
|
+
Works with NativeSolution (requires dt as auxiliary data)
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
NativeSolution with temporally averaged timeseries
|
|
147
|
+
"""
|
|
148
|
+
ts, ys = sol.ts, sol.ys
|
|
149
|
+
|
|
150
|
+
# Apply voi slicing first
|
|
151
|
+
ys_sliced = ys[:, self.voi, ...]
|
|
152
|
+
|
|
153
|
+
# Number of samples per averaging window
|
|
154
|
+
# Use sol.dt from auxiliary data and convert with Python int()
|
|
155
|
+
samples_per_window = int(round(self.period / sol.dt))
|
|
156
|
+
|
|
157
|
+
# Map time points to sample indices
|
|
158
|
+
time_indices = (ts[::samples_per_window] / sol.dt).astype(int)
|
|
159
|
+
|
|
160
|
+
def average_window(start_idx):
|
|
161
|
+
"""Compute average over a temporal window."""
|
|
162
|
+
# Define slice starting point for all dimensions
|
|
163
|
+
start_indices = (start_idx,) + (0,) * (ys_sliced.ndim - 1)
|
|
164
|
+
# Define slice size based on the sliced array shape
|
|
165
|
+
slice_sizes = (samples_per_window,) + ys_sliced.shape[1:]
|
|
166
|
+
|
|
167
|
+
# Extract window and compute mean over time axis
|
|
168
|
+
return jnp.mean(
|
|
169
|
+
jax.lax.dynamic_slice(ys_sliced, start_indices, slice_sizes),
|
|
170
|
+
axis=0,
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
# Vectorized averaging over all windows
|
|
174
|
+
averaged_trace = jax.vmap(average_window)(time_indices)
|
|
175
|
+
|
|
176
|
+
# Create time indices centered in each window
|
|
177
|
+
# Offset by half window to center timestamps
|
|
178
|
+
center_offset = (samples_per_window - 2) // 2
|
|
179
|
+
centered_indices = jnp.arange(center_offset, ts.shape[0], samples_per_window)
|
|
180
|
+
|
|
181
|
+
return NativeSolution(
|
|
182
|
+
ts=ts[centered_indices],
|
|
183
|
+
ys=averaged_trace[: centered_indices.shape[0], ...],
|
|
184
|
+
dt=self.period,
|
|
185
|
+
)
|