brainx-skill 1.0.6 → 1.0.9

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 (120) hide show
  1. package/README.md +10 -8
  2. package/adapters/gemini.js +7 -0
  3. package/adapters/opencode.js +7 -0
  4. package/adapters/windsurf.js +7 -0
  5. package/installation/lib/installer.js +4 -1
  6. package/manifest.json +6 -1
  7. package/package.json +8 -2
  8. package/skills/braincell/SKILL.md +182 -0
  9. package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
  10. package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +273 -0
  11. package/skills/braincell/references/channel-library.md +85 -0
  12. package/skills/braincell/references/ion-library.md +87 -0
  13. package/skills/braincell/references/mixions-for-adaptation.md +81 -0
  14. package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
  15. package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
  16. package/skills/braincell/references/multicompartment/filter-function-library.md +154 -0
  17. package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
  18. package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
  19. package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
  20. package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +260 -0
  21. package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
  22. package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
  23. package/skills/braincell/references/scripts/channel_ablation.py +61 -0
  24. package/skills/braincell/references/scripts/fi_curve.py +68 -0
  25. package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
  26. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
  27. package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
  28. package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
  29. package/skills/braincell/references/solver-library-with-effects.md +188 -0
  30. package/skills/brainevent/SKILL.md +268 -0
  31. package/skills/brainevent/references/connectivity-variants.md +312 -0
  32. package/skills/brainevent/references/custom-operators-cpu.md +304 -0
  33. package/skills/brainevent/references/custom-operators-gpu.md +468 -0
  34. package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
  35. package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
  36. package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
  37. package/skills/brainevent/references/sparse-formats.md +182 -0
  38. package/skills/brainevent/references/synaptic-plasticity.md +285 -0
  39. package/skills/brainmass/SKILL.md +290 -0
  40. package/skills/brainmass/references/batch-transform-acceleration.md +136 -0
  41. package/skills/brainmass/references/brainstate/parameter-constraints-regularization.md +214 -0
  42. package/skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
  43. package/skills/brainmass/references/braintools/cogtask.md +190 -0
  44. package/skills/brainmass/references/braintools/data-preprocessing.md +83 -0
  45. package/skills/brainmass/references/braintools/metric.md +157 -0
  46. package/skills/brainmass/references/braintools/optimizer.md +187 -0
  47. package/skills/brainmass/references/braintools/parameter-initializer.md +187 -0
  48. package/skills/brainmass/references/braintools/surrogate.md +151 -0
  49. package/skills/brainmass/references/coupling-network-api.md +148 -0
  50. package/skills/brainmass/references/datasets-api.md +72 -0
  51. package/skills/brainmass/references/fitting-with-objectives-api.md +146 -0
  52. package/skills/brainmass/references/forward-observation-api.md +131 -0
  53. package/skills/brainmass/references/horn-task-training.md +199 -0
  54. package/skills/brainmass/references/modellibrary.md +104 -0
  55. package/skills/brainmass/references/noiseprocesses.md +121 -0
  56. package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +130 -0
  57. package/skills/brainmass/references/scripts/eeg-fitting-with-gradients.py +230 -0
  58. package/skills/brainmass/references/scripts/gradient-free-fitting.py +106 -0
  59. package/skills/brainmass/references/scripts/hopf-bifurcation-single-node.py +78 -0
  60. package/skills/brainmass/references/scripts/horn-cognitive-task-training.py +211 -0
  61. package/skills/brainmass/references/scripts/jansen-rit-eeg-proxy.py +76 -0
  62. package/skills/brainmass/references/scripts/kuramoto-synchronization.py +81 -0
  63. package/skills/brainmass/references/scripts/linear-baseline-node.py +81 -0
  64. package/skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +249 -0
  65. package/skills/brainmass/references/scripts/seizure-epileptor-case-study.py +126 -0
  66. package/skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +86 -0
  67. package/skills/brainmass/references/scripts/wong-wang-decision-making.py +167 -0
  68. package/skills/brainmass/references/scripts/wong-wang-dmf-resting-state.py +72 -0
  69. package/skills/brainmass/references/visualization-analysis-api.md +130 -0
  70. package/skills/brainpy-state/SKILL.md +232 -0
  71. package/skills/brainpy-state/references/array-creation.md +158 -0
  72. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
  73. package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
  74. package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
  75. package/skills/brainpy-state/references/braintools/metric.md +152 -0
  76. package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
  77. package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
  78. package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
  79. package/skills/brainpy-state/references/component-selection.md +273 -0
  80. package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
  81. package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
  82. package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
  83. package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
  84. package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
  85. package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
  86. package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
  87. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
  88. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
  89. package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
  90. package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
  91. package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
  92. package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
  93. package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
  94. package/skills/brainpy-state/references/projection-patterns.md +125 -0
  95. package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
  96. package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
  97. package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
  98. package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
  99. package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
  100. package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
  101. package/skills/brainstate/SKILL.md +1 -1
  102. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +250 -399
  103. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +6 -2
  104. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +16 -2
  105. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +8 -3
  106. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +64 -143
  107. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +13 -1
  108. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +11 -1
  109. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +35 -7
  110. package/skills/brainstate/references/collective_model_operations.md +9 -9
  111. package/skills/brainstate/references/extension_mechanisms.md +12 -1
  112. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -97
  113. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +102 -176
  114. package/skills/brainstate/references/model-interop-and-migration.md +11 -1
  115. package/skills/brainstate/references/size-inference-variations.md +11 -0
  116. package/skills/brainstate/references/state-graph-operations.md +13 -15
  117. package/skills/brainstate/references/state_collections_and_utilities.md +12 -1
  118. package/skills/brainx-general-guard/SKILL.md +68 -0
  119. package/skills/brainstate/references/braintools-optimizer-reference.md +0 -133
  120. package/skills/brainstate/references/libraries/solver-library-with-effects.md +0 -85
@@ -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()