brainx-skill 1.0.8 → 1.0.10
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.
- package/README.md +1 -6
- package/manifest.json +3 -2
- package/package.json +2 -1
- package/skills/braincell/SKILL.md +1 -1
- package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +107 -44
- package/skills/braincell/references/channel-library.md +0 -85
- package/skills/braincell/references/ion-library.md +0 -67
- package/skills/braincell/references/multicompartment/filter-function-library.md +0 -8
- package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +204 -65
- package/skills/brainmass/SKILL.md +290 -0
- package/skills/brainmass/references/batch-transform-acceleration.md +136 -0
- package/skills/brainmass/references/brainstate/parameter-constraints-regularization.md +214 -0
- package/skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
- package/skills/brainmass/references/braintools/cogtask.md +190 -0
- package/skills/brainmass/references/braintools/data-preprocessing.md +83 -0
- package/skills/brainmass/references/braintools/metric.md +157 -0
- package/skills/brainmass/references/braintools/optimizer.md +187 -0
- package/skills/brainmass/references/braintools/parameter-initializer.md +187 -0
- package/skills/brainmass/references/braintools/surrogate.md +151 -0
- package/skills/brainmass/references/coupling-network-api.md +148 -0
- package/skills/brainmass/references/datasets-api.md +72 -0
- package/skills/brainmass/references/fitting-with-objectives-api.md +146 -0
- package/skills/brainmass/references/forward-observation-api.md +131 -0
- package/skills/brainmass/references/horn-task-training.md +199 -0
- package/skills/brainmass/references/modellibrary.md +104 -0
- package/skills/brainmass/references/noiseprocesses.md +121 -0
- package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +130 -0
- package/skills/brainmass/references/scripts/eeg-fitting-with-gradients.py +230 -0
- package/skills/brainmass/references/scripts/gradient-free-fitting.py +106 -0
- package/skills/brainmass/references/scripts/hopf-bifurcation-single-node.py +78 -0
- package/skills/brainmass/references/scripts/horn-cognitive-task-training.py +211 -0
- package/skills/brainmass/references/scripts/jansen-rit-eeg-proxy.py +76 -0
- package/skills/brainmass/references/scripts/kuramoto-synchronization.py +81 -0
- package/skills/brainmass/references/scripts/linear-baseline-node.py +81 -0
- package/skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +249 -0
- package/skills/brainmass/references/scripts/seizure-epileptor-case-study.py +126 -0
- package/skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +86 -0
- package/skills/brainmass/references/scripts/wong-wang-decision-making.py +167 -0
- package/skills/brainmass/references/scripts/wong-wang-dmf-resting-state.py +72 -0
- package/skills/brainmass/references/visualization-analysis-api.md +130 -0
- package/skills/brainpy-state/SKILL.md +1 -1
- package/skills/brainx-general-guard/SKILL.md +52 -118
- package/skills/brainx-install/SKILL.md +7 -4
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +0 -303
- package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +0 -62
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"""Reference script mirrored from:
|
|
2
|
+
https://brainx.chaobrain.com/brainmass/gallery/case_studies/horn_cognitive_task.html
|
|
3
|
+
|
|
4
|
+
Converted from the official notebook at upstream commit
|
|
5
|
+
293eaeb8948474c645208b68c531b7cb5482d4fb. Notebook outputs are omitted and
|
|
6
|
+
``%matplotlib inline`` remains commented; code and Markdown cells are preserved.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
# %% tags=["remove-cell"]
|
|
10
|
+
# Hidden setup cell (imports, deterministic seed, global dt).
|
|
11
|
+
# %matplotlib inline
|
|
12
|
+
import brainmass
|
|
13
|
+
import brainstate
|
|
14
|
+
import braintools
|
|
15
|
+
import brainunit as u
|
|
16
|
+
import jax
|
|
17
|
+
import jax.numpy as jnp
|
|
18
|
+
import numpy as np
|
|
19
|
+
import matplotlib.pyplot as plt
|
|
20
|
+
|
|
21
|
+
brainstate.random.seed(0)
|
|
22
|
+
brainstate.environ.set(dt=1.0 * u.ms)
|
|
23
|
+
|
|
24
|
+
# %% [markdown]
|
|
25
|
+
# # Training a HORN Network on a Cognitive Task
|
|
26
|
+
#
|
|
27
|
+
# The previous case studies *fit* a few biophysical parameters. This one **trains** an entire
|
|
28
|
+
# recurrent network — every weight — to *perform a task*, the data-driven showcase of a
|
|
29
|
+
# differentiable brain model. Because brainmass networks are end-to-end differentiable, the same
|
|
30
|
+
# backpropagation that fit one parameter scales to training a recurrent network with
|
|
31
|
+
# gradient descent.
|
|
32
|
+
#
|
|
33
|
+
# We train a {class}`~brainmass.HORNSeqNetwork` — a recurrent network of coupled **harmonic
|
|
34
|
+
# oscillators** (a Harmonic Oscillator Recurrent Network) — on the bundled **delayed
|
|
35
|
+
# match-to-sample** task. The network sees a cue symbol, must hold it across a delay, then sees a
|
|
36
|
+
# probe and decides whether they **match**. Solving it requires genuine working memory in the
|
|
37
|
+
# recurrent dynamics.
|
|
38
|
+
#
|
|
39
|
+
# **Source:** consolidates the HORN cognitive-task training scripts onto the bundled
|
|
40
|
+
# {func}`brainmass.datasets.delayed_match_task` — fully self-contained, no downloads.
|
|
41
|
+
#
|
|
42
|
+
# :::{note}
|
|
43
|
+
# {class}`~brainmass.Fitter` targets *parameter fitting* against a single fixed target. **Task
|
|
44
|
+
# training** — minibatched `(inputs, targets)` over epochs with a held-out metric — is a different
|
|
45
|
+
# loop, so we drive a {mod}`braintools.optim` optimizer directly. A future `Trainer` would wrap
|
|
46
|
+
# this loop.
|
|
47
|
+
# :::
|
|
48
|
+
|
|
49
|
+
# %% [markdown]
|
|
50
|
+
# ## 1. The task
|
|
51
|
+
#
|
|
52
|
+
# {func}`brainmass.datasets.delayed_match_task` synthesises the dataset. Each trial is a sequence:
|
|
53
|
+
# a one-hot **cue** symbol at the first step, blank steps (the delay), then a one-hot **probe** at
|
|
54
|
+
# the last step. The binary target is `1` if probe matches cue, else `0`. We use a 2-symbol
|
|
55
|
+
# alphabet and 8-step sequences, and hold out a test split.
|
|
56
|
+
|
|
57
|
+
# %%
|
|
58
|
+
inputs_np, targets_np = brainmass.datasets.delayed_match_task(
|
|
59
|
+
n_samples=320, seq_len=8, n_symbols=2, seed=0,
|
|
60
|
+
)
|
|
61
|
+
print("inputs :", inputs_np.shape, "(n_samples, seq_len, n_symbols)")
|
|
62
|
+
print("targets:", targets_np.shape, " class balance =", f"{targets_np.mean():.2f}")
|
|
63
|
+
|
|
64
|
+
inputs = jnp.asarray(inputs_np, dtype=jnp.float32)
|
|
65
|
+
targets = jnp.asarray(targets_np, dtype=jnp.int32)
|
|
66
|
+
n_train = 256
|
|
67
|
+
X_train, y_train = inputs[:n_train], targets[:n_train]
|
|
68
|
+
X_test, y_test = inputs[n_train:], targets[n_train:]
|
|
69
|
+
n_symbols = inputs.shape[2]
|
|
70
|
+
|
|
71
|
+
fig, axes = plt.subplots(1, 2, figsize=(9, 3))
|
|
72
|
+
for ax, idx, name in [(axes[0], int(np.argmax(targets_np == 1)), 'match'),
|
|
73
|
+
(axes[1], int(np.argmax(targets_np == 0)), 'non-match')]:
|
|
74
|
+
ax.imshow(inputs_np[idx].T, aspect='auto', cmap='Greys', interpolation='nearest')
|
|
75
|
+
ax.set_title(f'{name} (target={int(targets_np[idx])})')
|
|
76
|
+
ax.set_xlabel('time step'); ax.set_ylabel('symbol'); ax.set_yticks(range(n_symbols))
|
|
77
|
+
plt.tight_layout()
|
|
78
|
+
plt.show()
|
|
79
|
+
|
|
80
|
+
# %% [markdown]
|
|
81
|
+
# ## 2. The HORN classifier
|
|
82
|
+
#
|
|
83
|
+
# A {class}`~brainmass.HORNSeqNetwork` maps an input *sequence* `(T, n_input)` to one output vector
|
|
84
|
+
# by running its oscillator dynamics over the sequence and reading out the final state. We give it
|
|
85
|
+
# two output units (match / non-match logits) and raise the oscillator excitability `alpha` above
|
|
86
|
+
# its default so it responds strongly enough to learn quickly.
|
|
87
|
+
#
|
|
88
|
+
# The network writes its hidden states **in place**, and `init_state` allocates them *unbatched*.
|
|
89
|
+
# To process a mini-batch we reset the hidden states to the batch shape before each forward pass
|
|
90
|
+
# and feed the sequence as `(T, batch, n_input)` (time leading).
|
|
91
|
+
|
|
92
|
+
# %%
|
|
93
|
+
net = brainmass.HORNSeqNetwork(
|
|
94
|
+
n_input=n_symbols,
|
|
95
|
+
n_hidden=64,
|
|
96
|
+
n_output=2,
|
|
97
|
+
alpha=0.2, # excitability (raised from the 0.04 default)
|
|
98
|
+
omega=2 * np.pi / 28,
|
|
99
|
+
)
|
|
100
|
+
brainstate.nn.init_all_states(net)
|
|
101
|
+
|
|
102
|
+
def reset_hidden(batch_size):
|
|
103
|
+
# HORN allocates hidden states unbatched; broadcast them to the batch shape.
|
|
104
|
+
for layer in net.layers:
|
|
105
|
+
shape = (batch_size,) + tuple(layer.horn.in_size)
|
|
106
|
+
layer.horn.x.value = jnp.zeros(shape)
|
|
107
|
+
layer.horn.y.value = jnp.zeros(shape)
|
|
108
|
+
|
|
109
|
+
def logits(batch_inputs): # (B, T, n_symbols) -> (B, 2)
|
|
110
|
+
reset_hidden(batch_inputs.shape[0])
|
|
111
|
+
seq = jnp.transpose(batch_inputs, (1, 0, 2)) # (T, B, n_symbols): time leads
|
|
112
|
+
return net(seq)
|
|
113
|
+
|
|
114
|
+
weights = net.states(brainstate.ParamState)
|
|
115
|
+
print("trainable weight tensors:", len(weights))
|
|
116
|
+
|
|
117
|
+
# %% [markdown]
|
|
118
|
+
# ## 3. The training loop
|
|
119
|
+
#
|
|
120
|
+
# The loss is softmax cross-entropy between the logits and the binary target, with accuracy tracked
|
|
121
|
+
# alongside. We register the trainable weights with Adam and, each step, take the gradient of the
|
|
122
|
+
# loss through the **whole recurrent rollout** ({func}`brainstate.transform.grad`) and apply it —
|
|
123
|
+
# the canonical brainmass training primitive, jitted for speed. The only new ingredients beyond the
|
|
124
|
+
# fitting case study are **minibatching** and the **epoch loop**.
|
|
125
|
+
|
|
126
|
+
# %%
|
|
127
|
+
optimizer = braintools.optim.Adam(lr=3e-2)
|
|
128
|
+
optimizer.register_trainable_weights(weights)
|
|
129
|
+
|
|
130
|
+
def loss_and_acc(batch_inputs, batch_targets):
|
|
131
|
+
lg = logits(batch_inputs)
|
|
132
|
+
logp = jax.nn.log_softmax(lg, axis=-1)
|
|
133
|
+
ce = -jnp.mean(logp[jnp.arange(batch_targets.shape[0]), batch_targets])
|
|
134
|
+
acc = jnp.mean(jnp.argmax(lg, axis=-1) == batch_targets)
|
|
135
|
+
return ce, acc
|
|
136
|
+
|
|
137
|
+
@brainstate.transform.jit
|
|
138
|
+
def train_step(batch_inputs, batch_targets):
|
|
139
|
+
grad_fn = brainstate.transform.grad(
|
|
140
|
+
lambda: loss_and_acc(batch_inputs, batch_targets),
|
|
141
|
+
weights, has_aux=True, return_value=True,
|
|
142
|
+
)
|
|
143
|
+
grads, loss, acc = grad_fn()
|
|
144
|
+
optimizer.step(grads)
|
|
145
|
+
return loss, acc
|
|
146
|
+
|
|
147
|
+
@brainstate.transform.jit
|
|
148
|
+
def evaluate(batch_inputs, batch_targets):
|
|
149
|
+
return loss_and_acc(batch_inputs, batch_targets)
|
|
150
|
+
|
|
151
|
+
n_epochs, batch_size = 20, 32
|
|
152
|
+
history = {'epoch': [], 'train_loss': [], 'train_acc': [], 'test_acc': []}
|
|
153
|
+
for epoch in range(n_epochs):
|
|
154
|
+
perm = np.random.RandomState(epoch).permutation(n_train)
|
|
155
|
+
losses, accs = [], []
|
|
156
|
+
for start in range(0, n_train, batch_size):
|
|
157
|
+
idx = perm[start:start + batch_size]
|
|
158
|
+
if len(idx) < batch_size:
|
|
159
|
+
continue
|
|
160
|
+
loss, acc = train_step(X_train[idx], y_train[idx])
|
|
161
|
+
losses.append(float(loss)); accs.append(float(acc))
|
|
162
|
+
_, test_acc = evaluate(X_test, y_test)
|
|
163
|
+
history['epoch'].append(epoch)
|
|
164
|
+
history['train_loss'].append(float(np.mean(losses)))
|
|
165
|
+
history['train_acc'].append(float(np.mean(accs)))
|
|
166
|
+
history['test_acc'].append(float(test_acc))
|
|
167
|
+
if epoch % 4 == 0 or epoch == n_epochs - 1:
|
|
168
|
+
print(f"epoch {epoch:2d}: train_loss={np.mean(losses):.4f} "
|
|
169
|
+
f"train_acc={np.mean(accs):.3f} test_acc={float(test_acc):.3f}")
|
|
170
|
+
|
|
171
|
+
# %% [markdown]
|
|
172
|
+
# ## 4. Results
|
|
173
|
+
#
|
|
174
|
+
# The network starts at chance (~50%, a binary task) and — as gradient descent shapes its
|
|
175
|
+
# recurrent weights to hold the cue across the delay — climbs toward perfect accuracy on both the
|
|
176
|
+
# training and the held-out test set.
|
|
177
|
+
|
|
178
|
+
# %%
|
|
179
|
+
final_train = history['train_acc'][-1]
|
|
180
|
+
final_test = history['test_acc'][-1]
|
|
181
|
+
print(f"final train accuracy: {final_train:.1%}")
|
|
182
|
+
print(f"final test accuracy: {final_test:.1%}")
|
|
183
|
+
|
|
184
|
+
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4))
|
|
185
|
+
ax1.plot(history['epoch'], history['train_loss'], marker='.')
|
|
186
|
+
ax1.set_xlabel('epoch'); ax1.set_ylabel('cross-entropy loss')
|
|
187
|
+
ax1.set_title('Training loss'); ax1.grid(alpha=0.3)
|
|
188
|
+
ax2.plot(history['epoch'], history['train_acc'], marker='.', label='train')
|
|
189
|
+
ax2.plot(history['epoch'], history['test_acc'], marker='.', label='test')
|
|
190
|
+
ax2.axhline(0.5, color='grey', ls='--', lw=1, label='chance')
|
|
191
|
+
ax2.set_xlabel('epoch'); ax2.set_ylabel('accuracy')
|
|
192
|
+
ax2.set_ylim(0.4, 1.02); ax2.set_title('Accuracy'); ax2.legend(); ax2.grid(alpha=0.3)
|
|
193
|
+
plt.tight_layout()
|
|
194
|
+
plt.show()
|
|
195
|
+
|
|
196
|
+
# %% [markdown]
|
|
197
|
+
# ## Summary
|
|
198
|
+
#
|
|
199
|
+
# We trained a recurrent harmonic-oscillator network to perform a working-memory task:
|
|
200
|
+
#
|
|
201
|
+
# - the bundled {func}`~brainmass.datasets.delayed_match_task` provides minibatchable
|
|
202
|
+
# `(inputs, targets)` — **no external download**,
|
|
203
|
+
# - a {class}`~brainmass.HORNSeqNetwork` reads a sequence to a decision, with hidden states reset to
|
|
204
|
+
# the batch shape each forward pass,
|
|
205
|
+
# - gradient descent through the full recurrent rollout (jitted `brainstate.transform.grad` +
|
|
206
|
+
# `braintools.optim.Adam`) drives accuracy from chance to near-perfect on a held-out split.
|
|
207
|
+
#
|
|
208
|
+
# This is the differentiable-brain showcase: the *same* autodiff that fits a single coupling
|
|
209
|
+
# strength trains an entire network end to end. The one piece {class}`~brainmass.Fitter` does not
|
|
210
|
+
# yet own — minibatched task training with a held-out metric — is the loop a future `Trainer` would
|
|
211
|
+
# wrap.
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Reference script mirrored from:
|
|
2
|
+
https://brainx.chaobrain.com/brainmass/gallery/model_zoo/jansen_rit.html
|
|
3
|
+
|
|
4
|
+
Converted from the official notebook at upstream commit
|
|
5
|
+
293eaeb8948474c645208b68c531b7cb5482d4fb. Notebook outputs are omitted and
|
|
6
|
+
``%matplotlib inline`` remains commented; code and Markdown cells are preserved.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
# %% tags=["remove-cell"]
|
|
10
|
+
# %matplotlib inline
|
|
11
|
+
import brainmass
|
|
12
|
+
import brainstate
|
|
13
|
+
import brainunit as u
|
|
14
|
+
import jax.numpy as jnp
|
|
15
|
+
import numpy as np
|
|
16
|
+
import matplotlib.pyplot as plt
|
|
17
|
+
brainstate.random.seed(0)
|
|
18
|
+
brainstate.environ.set(dt=0.1 * u.ms)
|
|
19
|
+
|
|
20
|
+
# %% [markdown]
|
|
21
|
+
# # Jansen-Rit Model
|
|
22
|
+
#
|
|
23
|
+
# The **Jansen-Rit model** simulates EEG-like activity from a cortical column built from three interacting populations — pyramidal cells, excitatory interneurons, and inhibitory interneurons. Each population is a second-order linear filter (post-synaptic potential) followed by a sigmoidal firing-rate nonlinearity. For a range of external input rates the column produces alpha-band (~10 Hz) oscillations, making it a standard generative model of scalp EEG.
|
|
24
|
+
#
|
|
25
|
+
# **Reference:** Jansen & Rit (1995), *Electroencephalogram and visual evoked potential generation in a mathematical model of coupled cortical columns*, Biological Cybernetics 73(4):357-366.
|
|
26
|
+
|
|
27
|
+
# %% [markdown]
|
|
28
|
+
# ## Build the model
|
|
29
|
+
|
|
30
|
+
# %%
|
|
31
|
+
node = brainmass.JansenRitStep(in_size=1)
|
|
32
|
+
node
|
|
33
|
+
|
|
34
|
+
# %% [markdown]
|
|
35
|
+
# ## Run a simulation
|
|
36
|
+
#
|
|
37
|
+
# The model is driven by an external pyramidal input rate `E_inp`. The EEG proxy is the pyramidal membrane potential `M`.
|
|
38
|
+
|
|
39
|
+
# %%
|
|
40
|
+
sim = brainmass.Simulator(node, dt=0.1 * u.ms)
|
|
41
|
+
res = sim.run(2000. * u.ms,
|
|
42
|
+
inputs=lambda i, t: (0. * u.mV, 220. * u.Hz, 0. * u.mV),
|
|
43
|
+
monitors=['M'], transient=500. * u.ms)
|
|
44
|
+
res['M'].shape
|
|
45
|
+
|
|
46
|
+
# %% [markdown]
|
|
47
|
+
# ## Visualize
|
|
48
|
+
#
|
|
49
|
+
# The pyramidal potential `M` oscillates in the alpha band — the Jansen-Rit EEG proxy.
|
|
50
|
+
|
|
51
|
+
# %%
|
|
52
|
+
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
|
|
53
|
+
brainmass.viz.plot_timeseries(res['M'], ts=res['ts'], ax=axes[0])
|
|
54
|
+
axes[0].set_title('Jansen-Rit EEG proxy (M)')
|
|
55
|
+
brainmass.viz.plot_power_spectrum(res['M'][:, 0], dt=0.1 * u.ms, ax=axes[1])
|
|
56
|
+
axes[1].set_title('Power spectrum'); axes[1].set_xlim(0, 40)
|
|
57
|
+
plt.tight_layout()
|
|
58
|
+
plt.show()
|
|
59
|
+
|
|
60
|
+
# %% [markdown]
|
|
61
|
+
# ## Try it: vary the external input rate `p`
|
|
62
|
+
#
|
|
63
|
+
# The mean input rate to the pyramidal population sets the regime; in the classic band (~120-320 Hz) the column produces alpha-like rhythms, and outside it the dynamics change qualitatively.
|
|
64
|
+
|
|
65
|
+
# %%
|
|
66
|
+
fig, ax = plt.subplots(figsize=(8, 4))
|
|
67
|
+
for p in [120., 220., 320.]:
|
|
68
|
+
m = brainmass.JansenRitStep(in_size=1)
|
|
69
|
+
r = brainmass.Simulator(m, dt=0.1 * u.ms).run(
|
|
70
|
+
1500. * u.ms,
|
|
71
|
+
inputs=lambda i, t, pp=p: (0. * u.mV, pp * u.Hz, 0. * u.mV),
|
|
72
|
+
monitors=['M'], transient=500. * u.ms)
|
|
73
|
+
ax.plot(u.get_magnitude(r['ts']), u.get_magnitude(r['M'])[:, 0], label=f'p = {p:.0f} Hz')
|
|
74
|
+
ax.set_xlabel('time (ms)'); ax.set_ylabel('M (mV)'); ax.legend()
|
|
75
|
+
ax.set_title('Input-rate sweep')
|
|
76
|
+
plt.show()
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Reference script mirrored from:
|
|
2
|
+
https://brainx.chaobrain.com/brainmass/gallery/model_zoo/kuramoto.html
|
|
3
|
+
|
|
4
|
+
Converted from the official notebook at upstream commit
|
|
5
|
+
293eaeb8948474c645208b68c531b7cb5482d4fb. Notebook outputs are omitted and
|
|
6
|
+
``%matplotlib inline`` remains commented; code and Markdown cells are preserved.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
# %% tags=["remove-cell"]
|
|
10
|
+
# %matplotlib inline
|
|
11
|
+
import brainmass
|
|
12
|
+
import brainstate
|
|
13
|
+
import brainunit as u
|
|
14
|
+
import jax.numpy as jnp
|
|
15
|
+
import numpy as np
|
|
16
|
+
import matplotlib.pyplot as plt
|
|
17
|
+
brainstate.random.seed(0)
|
|
18
|
+
brainstate.environ.set(dt=0.1 * u.ms)
|
|
19
|
+
|
|
20
|
+
# %% [markdown]
|
|
21
|
+
# # Kuramoto Phase Oscillators
|
|
22
|
+
#
|
|
23
|
+
# The **Kuramoto model** is the canonical model of synchronization in a population of coupled phase oscillators. Each oscillator $i$ has a natural frequency $\omega_i$ and is pulled toward its neighbours' phases:
|
|
24
|
+
#
|
|
25
|
+
# $$\dot\theta_i = \omega_i + \frac{K}{N}\sum_j W_{ij}\sin(\theta_j - \theta_i).$$
|
|
26
|
+
#
|
|
27
|
+
# Below a critical coupling $K_c$ the oscillators drift incoherently; above it they synchronize. Global coherence is measured by the Kuramoto order parameter $R = |\frac{1}{N}\sum_j e^{i\theta_j}|$, which rises from ~0 (incoherent) to ~1 (fully synchronized).
|
|
28
|
+
#
|
|
29
|
+
# **Reference:** Kuramoto (1975), *Self-entrainment of a population of coupled nonlinear oscillators*, in International Symposium on Mathematical Problems in Theoretical Physics.
|
|
30
|
+
|
|
31
|
+
# %% [markdown]
|
|
32
|
+
# ## Build the model
|
|
33
|
+
#
|
|
34
|
+
# We build a population of `N = 50` all-to-all coupled oscillators with heterogeneous natural frequencies.
|
|
35
|
+
|
|
36
|
+
# %%
|
|
37
|
+
N = 50
|
|
38
|
+
omega = np.asarray(brainstate.random.normal(1.0, 0.3, N))
|
|
39
|
+
node = brainmass.KuramotoNetwork(in_size=N, omega=omega, K=2.0,
|
|
40
|
+
conn=np.ones((N, N)))
|
|
41
|
+
node
|
|
42
|
+
|
|
43
|
+
# %% [markdown]
|
|
44
|
+
# ## Run a simulation
|
|
45
|
+
|
|
46
|
+
# %%
|
|
47
|
+
sim = brainmass.Simulator(node, dt=0.1 * u.ms)
|
|
48
|
+
res = sim.run(150. * u.ms, monitors=['theta'])
|
|
49
|
+
theta = u.get_magnitude(res['theta'])
|
|
50
|
+
R = np.abs(np.mean(np.exp(1j * theta), axis=1))
|
|
51
|
+
R[0], R[-1]
|
|
52
|
+
|
|
53
|
+
# %% [markdown]
|
|
54
|
+
# ## Visualize
|
|
55
|
+
#
|
|
56
|
+
# Left: the order parameter `R` climbing toward synchronization. Right: individual phases (mod $2\pi$) bunching together over time.
|
|
57
|
+
|
|
58
|
+
# %%
|
|
59
|
+
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
|
|
60
|
+
axes[0].plot(u.get_magnitude(res['ts']), R)
|
|
61
|
+
axes[0].set_xlabel('time (ms)'); axes[0].set_ylabel('order parameter R')
|
|
62
|
+
axes[0].set_ylim(0, 1); axes[0].set_title('Synchronization (K = 2.0)')
|
|
63
|
+
axes[1].plot(u.get_magnitude(res['ts']), np.mod(theta[:, ::5], 2 * np.pi),
|
|
64
|
+
lw=0.6, alpha=0.7)
|
|
65
|
+
axes[1].set_xlabel('time (ms)'); axes[1].set_ylabel('phase (rad)')
|
|
66
|
+
axes[1].set_title('Individual phases')
|
|
67
|
+
plt.tight_layout()
|
|
68
|
+
plt.show()
|
|
69
|
+
|
|
70
|
+
# %% [markdown]
|
|
71
|
+
# ## Try it: vary the coupling strength `K`
|
|
72
|
+
#
|
|
73
|
+
# Sweep `K` across the synchronization transition: weak coupling stays incoherent (`R` low), strong coupling locks the population (`R` -> 1).
|
|
74
|
+
|
|
75
|
+
# %%
|
|
76
|
+
for K in [0.0, 1.0, 3.0]:
|
|
77
|
+
m = brainmass.KuramotoNetwork(in_size=N, omega=omega, K=K, conn=np.ones((N, N)))
|
|
78
|
+
r = brainmass.Simulator(m, dt=0.1 * u.ms).run(200. * u.ms, monitors=['theta'])
|
|
79
|
+
th = u.get_magnitude(r['theta'])
|
|
80
|
+
R_final = float(np.abs(np.mean(np.exp(1j * th[-50:]), axis=1)).mean())
|
|
81
|
+
print(f'K = {K:.1f} -> steady order parameter R = {R_final:.3f}')
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Reference script mirrored from:
|
|
2
|
+
https://brainx.chaobrain.com/brainmass/gallery/model_zoo/linear.html
|
|
3
|
+
|
|
4
|
+
Converted from the official notebook at upstream commit
|
|
5
|
+
293eaeb8948474c645208b68c531b7cb5482d4fb. Notebook outputs are omitted and
|
|
6
|
+
``%matplotlib inline`` remains commented; code and Markdown cells are preserved.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
# %% tags=["remove-cell"]
|
|
10
|
+
# %matplotlib inline
|
|
11
|
+
import brainmass
|
|
12
|
+
import brainstate
|
|
13
|
+
import brainunit as u
|
|
14
|
+
import jax.numpy as jnp
|
|
15
|
+
import numpy as np
|
|
16
|
+
import matplotlib.pyplot as plt
|
|
17
|
+
brainstate.random.seed(0)
|
|
18
|
+
brainstate.environ.set(dt=0.1 * u.ms)
|
|
19
|
+
|
|
20
|
+
# %% [markdown]
|
|
21
|
+
# # Linear Node
|
|
22
|
+
#
|
|
23
|
+
# The **Linear node** is the simplest possible region model — a single damped linear state variable,
|
|
24
|
+
#
|
|
25
|
+
# $$\dot x = \gamma\,x + \text{coupling},$$
|
|
26
|
+
#
|
|
27
|
+
# with $\gamma < 0$ for a stable node. On its own it is a leaky integrator that decays to zero (or to a forced steady state $-c/\gamma$ under a constant drive $c$). It is TVB's `Linear` model and serves as a baseline / sanity-check node for coupling and integration tests — analytically tractable because exponential-Euler is *exact* for linear systems. (Distinct from the two-population `ThresholdLinearStep`.)
|
|
28
|
+
#
|
|
29
|
+
# **Reference:** Sanz-Leon, Knock, Spiegler & Jirsa (2015), *Mathematical framework for large-scale brain network modeling in The Virtual Brain*, NeuroImage 111:385-430.
|
|
30
|
+
|
|
31
|
+
# %% [markdown]
|
|
32
|
+
# ## Build the model
|
|
33
|
+
|
|
34
|
+
# %%
|
|
35
|
+
node = brainmass.LinearStep(in_size=1, gamma=-10.0)
|
|
36
|
+
node
|
|
37
|
+
|
|
38
|
+
# %% [markdown]
|
|
39
|
+
# ## Run a simulation
|
|
40
|
+
#
|
|
41
|
+
# We kick the node away from rest and watch it decay. The exponential-Euler step is exact for this linear ODE, so the trajectory matches the closed form $x(t) = x_0 e^{\gamma t}$.
|
|
42
|
+
|
|
43
|
+
# %%
|
|
44
|
+
brainstate.nn.init_all_states(node)
|
|
45
|
+
node.x.value = node.x.value + 1.0 # kick to x = 1
|
|
46
|
+
res = brainmass.Simulator(node, dt=0.1 * u.ms).run(
|
|
47
|
+
50. * u.ms, monitors=['x'], init_states=False)
|
|
48
|
+
res['x'].shape
|
|
49
|
+
|
|
50
|
+
# %% [markdown]
|
|
51
|
+
# ## Visualize
|
|
52
|
+
#
|
|
53
|
+
# The simulated decay (dots) lies on the analytic exponential (line).
|
|
54
|
+
|
|
55
|
+
# %%
|
|
56
|
+
ts = u.get_magnitude(res['ts'])
|
|
57
|
+
x = u.get_magnitude(res['x'])[:, 0]
|
|
58
|
+
fig, ax = plt.subplots(figsize=(8, 4))
|
|
59
|
+
ax.plot(ts, x, 'o', ms=3, label='simulated')
|
|
60
|
+
ax.plot(ts, np.exp(-10.0 * ts / 1000.0), '-', label=r'analytic $e^{\gamma t}$')
|
|
61
|
+
ax.set_xlabel('time (ms)'); ax.set_ylabel('x'); ax.legend()
|
|
62
|
+
ax.set_title('Linear node: exp-Euler is exact')
|
|
63
|
+
plt.show()
|
|
64
|
+
|
|
65
|
+
# %% [markdown]
|
|
66
|
+
# ## Try it: vary the decay rate `gamma`
|
|
67
|
+
#
|
|
68
|
+
# More negative `gamma` means faster decay (shorter time constant $\tau = -1/\gamma$). With a constant drive the node would instead settle at $-c/\gamma$.
|
|
69
|
+
|
|
70
|
+
# %%
|
|
71
|
+
fig, ax = plt.subplots(figsize=(8, 4))
|
|
72
|
+
for gamma in [-5.0, -10.0, -20.0]:
|
|
73
|
+
m = brainmass.LinearStep(in_size=1, gamma=gamma)
|
|
74
|
+
brainstate.nn.init_all_states(m)
|
|
75
|
+
m.x.value = m.x.value + 1.0
|
|
76
|
+
r = brainmass.Simulator(m, dt=0.1 * u.ms).run(
|
|
77
|
+
50. * u.ms, monitors=['x'], init_states=False)
|
|
78
|
+
ax.plot(u.get_magnitude(r['ts']), u.get_magnitude(r['x'])[:, 0], label=f'gamma = {gamma}')
|
|
79
|
+
ax.set_xlabel('time (ms)'); ax.set_ylabel('x'); ax.legend()
|
|
80
|
+
ax.set_title('Decay-rate sweep')
|
|
81
|
+
plt.show()
|