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,249 @@
1
+ """Reference script mirrored from:
2
+ https://brainx.chaobrain.com/brainmass/gallery/case_studies/resting_state_meg.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=0.1 * u.ms)
23
+
24
+ # %% [markdown]
25
+ # # Resting-State MEG: A Whole-Brain Modeling Pipeline
26
+ #
27
+ # This case study walks through the classic **resting-state** workflow: take a structural
28
+ # connectome, simulate a whole-brain neural-mass network on it, project the regional activity
29
+ # through a forward model to a sensor-space MEG signal, and finally validate the model by
30
+ # comparing its **functional connectivity** (FC) against an empirical target.
31
+ #
32
+ # ```
33
+ # structural connectome → whole-brain Network → forward model → functional connectivity
34
+ # (anatomy) (dynamics) (MEG sensors) (validation target)
35
+ # ```
36
+ #
37
+ # In a real study the connectome and the empirical MEG would come from imaging data (e.g. an HCP
38
+ # diffusion-MRI tractography matrix and a parcellated MEG recording). To keep this notebook
39
+ # **fully self-contained and executable with no downloads**, we drive the entire pipeline with
40
+ # the bundled {func}`brainmass.datasets.load_dataset` connectome and a *synthetic* empirical
41
+ # target. The prose flags exactly where your own data would plug in.
42
+ #
43
+ # **Source:** modernized from the resting-state MEG example shipped with brainmass; the
44
+ # hand-rolled simulation loop is replaced by the high-level {class}`~brainmass.Network` /
45
+ # {class}`~brainmass.Simulator` API.
46
+
47
+ # %% [markdown]
48
+ # ## 1. The structural connectome
49
+ #
50
+ # {func}`brainmass.datasets.load_dataset('example_connectome') <brainmass.datasets.load_dataset>`
51
+ # returns an 8-region {class}`~brainmass.datasets.Connectome`: a symmetric, zero-diagonal weight
52
+ # matrix in `[0, 1]`, a unit-aware (`mm`) inter-region distance matrix, and region labels. The
53
+ # distances set the **conduction delays** (`delay = distance / speed`).
54
+ #
55
+ # :::{note}
56
+ # **Plugging in real data.** Replace this block with your own subject connectome: an `(N, N)`
57
+ # weight matrix from tractography and an `(N, N)` Euclidean (or fiber-length) distance matrix in
58
+ # `mm`. Everything downstream is `N`-agnostic.
59
+ # :::
60
+
61
+ # %%
62
+ conn = brainmass.datasets.load_dataset('example_connectome')
63
+ W = conn.weights # (8, 8) structural connectivity, [0, 1]
64
+ D = conn.distances # (8, 8) distances, unit-aware (mm)
65
+ labels = list(conn.labels) # ['R0', ..., 'R7']
66
+ N = W.shape[0]
67
+ print(f"{N} regions:", labels)
68
+ print("weights :", W.shape, "range", f"[{W.min():.2f}, {W.max():.2f}]")
69
+ print("distances:", D.shape, "unit", D.unit)
70
+
71
+ fig, axes = plt.subplots(1, 2, figsize=(10, 4))
72
+ brainmass.viz.plot_connectivity(W, labels=labels, ax=axes[0])
73
+ axes[0].set_title('Structural connectivity (weights)')
74
+ brainmass.viz.plot_connectivity(u.get_magnitude(D), labels=labels, ax=axes[1])
75
+ axes[1].set_title('Inter-region distance (mm)')
76
+ plt.tight_layout()
77
+ plt.show()
78
+
79
+ # %% [markdown]
80
+ # ## 2. The whole-brain network
81
+ #
82
+ # We place a {class}`~brainmass.WilsonCowanStep` excitatory/inhibitory node at every region and
83
+ # wire them with **diffusive** coupling on the excitatory rate `rE`, with conduction delays from
84
+ # `distance / speed`. Per-region {class}`~brainmass.OUProcess` noise on `rE` keeps the resting
85
+ # state from collapsing to a single fixed point (so the FC is non-degenerate). This single
86
+ # {class}`~brainmass.Network` object replaces the connectome wiring that used to be copy-pasted by
87
+ # hand across every example.
88
+ #
89
+ # :::{note}
90
+ # A delay-coupled `Network` sizes its delay buffers from the global `dt` **at construction time**,
91
+ # so `brainstate.environ.set(dt=...)` is called once in the setup cell before we build it.
92
+ # :::
93
+
94
+ # %%
95
+ node = brainmass.WilsonCowanStep(
96
+ N,
97
+ noise_E=brainmass.OUProcess(N, sigma=0.01, tau=20.0 * u.ms),
98
+ noise_I=brainmass.OUProcess(N, sigma=0.01, tau=20.0 * u.ms),
99
+ )
100
+ net = brainmass.Network(
101
+ node,
102
+ conn=W,
103
+ distance=D,
104
+ speed=10.0 * u.mm / u.ms, # axonal conduction speed
105
+ coupling='diffusive',
106
+ coupled_var='rE',
107
+ k=1.5, # global coupling strength (TVB's G)
108
+ )
109
+ print("network:", net.n_node, "regions, coupling =", type(net.coupling).__name__)
110
+
111
+ # %% [markdown]
112
+ # ## 3. Simulate resting-state activity
113
+ #
114
+ # {class}`~brainmass.Simulator` runs the whole network with one call. We discard an initial
115
+ # transient and record the excitatory rate of every region.
116
+
117
+ # %%
118
+ sim = brainmass.Simulator(net, dt=0.1 * u.ms)
119
+ res = sim.run(
120
+ 4000.0 * u.ms,
121
+ monitors=lambda m: m.node.rE.value, # (T, N) excitatory rates
122
+ transient=300.0 * u.ms,
123
+ )
124
+ activity = res['output'] # (T, N)
125
+ print("activity:", activity.shape)
126
+
127
+ fig, ax = plt.subplots(figsize=(9, 4))
128
+ brainmass.viz.plot_timeseries(activity[:, :4], ts=res['ts'], labels=labels[:4], ax=ax)
129
+ ax.set_title('Simulated resting-state activity (first 4 regions)')
130
+ plt.tight_layout()
131
+ plt.show()
132
+
133
+ # %% [markdown]
134
+ # ## 4. Forward model: regions → MEG sensors
135
+ #
136
+ # Neural activity is observed at the scalp, not in the cortex. A **lead field** `L` linearly maps
137
+ # the `N` regional source amplitudes to `M` sensor measurements: `y = scale · source · L`. Here we
138
+ # use {class}`~brainmass.MEGLeadFieldModel` with a synthetic geometric lead field (a real study
139
+ # supplies a head-model lead field, e.g. from MNE/Brainstorm). We treat the excitatory rate as the
140
+ # dipole source amplitude.
141
+ #
142
+ # :::{note}
143
+ # **Plugging in real data.** Replace `L` with your forward operator of shape `(N_regions,
144
+ # N_sensors)` carrying units `sensor_unit / (nA·m)`. The lead field is the only geometry-specific
145
+ # ingredient.
146
+ # :::
147
+
148
+ # %%
149
+ M = 16 # number of MEG sensors
150
+ # Synthetic geometric lead field: each region projects to sensors with a smooth,
151
+ # distance-like falloff. A real lead field comes from a head model.
152
+ rng = np.random.default_rng(1)
153
+ L_raw = np.abs(rng.standard_normal((N, M))) + 0.1
154
+ L_raw = L_raw / L_raw.sum(axis=0, keepdims=True) # column-normalize
155
+ L = jnp.asarray(L_raw) * (u.tesla / (u.nA * u.meter))
156
+
157
+ # Base LeadFieldModel with an explicit mV-source -> dipole scale, so an mV source
158
+ # yields a correct tesla MEG output.
159
+ meg = brainmass.LeadFieldModel(
160
+ in_size=(N,), out_size=(M,), L=L,
161
+ sensor_unit=u.tesla,
162
+ scale=u.nA * u.meter / u.mV,
163
+ )
164
+ # Treat the (dimensionless) excitatory rate as an mV-scale dipole source amplitude.
165
+ sources = jnp.asarray(u.get_magnitude(activity)) * u.mV # (T, N)
166
+ sensor_meg = meg.update(sources) # (T, M), unit: tesla
167
+ print("sensor MEG:", sensor_meg.shape, "unit", u.get_unit(sensor_meg))
168
+
169
+ fig, ax = plt.subplots(figsize=(9, 4))
170
+ brainmass.viz.plot_timeseries(u.get_magnitude(sensor_meg)[:, :4], ts=res['ts'], ax=ax)
171
+ ax.set_title('Simulated MEG sensor traces (first 4 sensors)')
172
+ plt.tight_layout()
173
+ plt.show()
174
+
175
+ # %% [markdown]
176
+ # ## 5. Validate the functional connectivity
177
+ #
178
+ # The standard resting-state validation asks two questions of the simulated **functional
179
+ # connectivity** (FC) — the region-by-region correlation of the activity:
180
+ #
181
+ # 1. **Does FC reflect the anatomy?** A good whole-brain model produces an FC that is shaped by the
182
+ # structural connectome. We measure this as the correlation between the off-diagonal FC and the
183
+ # structural weights — the canonical *structure-function* coupling.
184
+ # 2. **Does FC match a target recording?** We build a synthetic "empirical" target by running the
185
+ # same model with a different noise realization (standing in for real data with the same
186
+ # parcellation) and score the match with {func}`brainmass.objectives.fc_corr`.
187
+ #
188
+ # :::{note}
189
+ # **Plugging in real data.** Replace `target_activity` with your parcellated empirical recording of
190
+ # shape `(T, N)`; the FC and both scores are computed identically. With short stochastic recordings,
191
+ # FC correlations of a few tenths are realistic — structure-function coupling is the more robust
192
+ # validation.
193
+ # :::
194
+
195
+ # %%
196
+ # --- Synthetic "empirical" target (stands in for a real MEG recording) ---
197
+ brainstate.random.seed(123)
198
+ target_node = brainmass.WilsonCowanStep(
199
+ N,
200
+ noise_E=brainmass.OUProcess(N, sigma=0.01, tau=20.0 * u.ms),
201
+ noise_I=brainmass.OUProcess(N, sigma=0.01, tau=20.0 * u.ms),
202
+ )
203
+ target_net = brainmass.Network(
204
+ target_node, conn=W, distance=D, speed=10.0 * u.mm / u.ms,
205
+ coupling='diffusive', coupled_var='rE', k=1.5,
206
+ )
207
+ target_res = brainmass.Simulator(target_net, dt=0.1 * u.ms).run(
208
+ 4000.0 * u.ms, monitors=lambda m: m.node.rE.value, transient=300.0 * u.ms)
209
+ target_activity = target_res['output']
210
+
211
+ # --- Functional connectivity: simulated vs target ---
212
+ fc_sim = braintools.metric.functional_connectivity(u.get_magnitude(activity))
213
+ fc_tar = braintools.metric.functional_connectivity(u.get_magnitude(target_activity))
214
+
215
+ # (1) Structure-function coupling: does the simulated FC reflect the connectome?
216
+ triu = np.triu_indices(N, k=1)
217
+ sc_fc_corr = float(np.corrcoef(fc_sim[triu], np.asarray(W)[triu])[0, 1])
218
+ # (2) Simulated vs target FC.
219
+ fc_match = float(brainmass.objectives.fc_corr()(activity, target_activity))
220
+ print(f"structure-function coupling corr(FC, SC): {sc_fc_corr:.3f}")
221
+ print(f"FC correlation (simulated vs target) : {fc_match:.3f}")
222
+
223
+ # %%
224
+ fig, axes = plt.subplots(1, 2, figsize=(10, 4))
225
+ brainmass.viz.plot_functional_connectivity(fc_sim, is_matrix=True, labels=labels, ax=axes[0])
226
+ axes[0].set_title('Simulated FC')
227
+ brainmass.viz.plot_functional_connectivity(fc_tar, is_matrix=True, labels=labels, ax=axes[1])
228
+ axes[1].set_title('Target ("empirical") FC')
229
+ plt.suptitle(f'corr(FC, SC) = {sc_fc_corr:.3f} | FC corr (sim vs target) = {fc_match:.3f}',
230
+ y=1.02)
231
+ plt.tight_layout()
232
+ plt.show()
233
+
234
+ # %% [markdown]
235
+ # ## Summary
236
+ #
237
+ # We ran the complete resting-state pipeline end to end:
238
+ #
239
+ # 1. loaded a **structural connectome** ({func}`~brainmass.datasets.load_dataset`),
240
+ # 2. built a delay-coupled whole-brain {class}`~brainmass.Network` of Wilson-Cowan nodes,
241
+ # 3. simulated it with {class}`~brainmass.Simulator`,
242
+ # 4. projected the activity to **MEG sensors** through a lead-field forward model, and
243
+ # 5. validated the model by **structure-function coupling** and **FC correlation**
244
+ # ({func}`~brainmass.objectives.fc_corr`).
245
+ #
246
+ # To turn this into a real study, swap the three flagged blocks — connectome, lead field, and
247
+ # target activity — for your imaging data; the modeling code is unchanged. The next natural step is
248
+ # to *fit* the coupling strength `k` so the simulated FC best matches the target, which is exactly
249
+ # what {class}`~brainmass.Fitter` does (see the EEG-fitting case study).
@@ -0,0 +1,126 @@
1
+ """Reference script mirrored from:
2
+ https://brainx.chaobrain.com/brainmass/gallery/case_studies/seizure_epileptor.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=0.1 * u.ms)
23
+
24
+ # %% [markdown]
25
+ # # Seizure Dynamics with the Epileptor
26
+ #
27
+ # The **Epileptor** (Jirsa et al., 2014) is the reference whole-brain model of epileptic seizures.
28
+ # It is a six-dimensional system that couples a fast oscillatory subsystem, a slower
29
+ # spike-and-wave subsystem, and — crucially — a **slow permittivity variable** `z` that evolves on
30
+ # a much longer timescale. That slow variable autonomously ramps seizure-like discharges *on* and
31
+ # then *off*, reproducing the stereotyped **onset / offset** structure of a focal seizure without
32
+ # any external trigger.
33
+ #
34
+ # This case study shows:
35
+ #
36
+ # 1. an epileptogenic node generating a full seizure cycle, with the LFP proxy `lfp = x2 − x1` and
37
+ # the hidden slow driver `z` plotted together,
38
+ # 2. how the **epileptogenicity parameter** `x0` separates healthy tissue from a seizure focus, and
39
+ # 3. the bifurcation it controls.
40
+ #
41
+ # **Reference:** Jirsa, Stacey, Quilichini, Ivanov & Bernard (2014), *On the nature of seizure
42
+ # dynamics*, Brain 137(8):2210-2230. The model is fully bundled in
43
+ # {class}`~brainmass.EpileptorStep` — no external data is needed.
44
+
45
+ # %% [markdown]
46
+ # ## 1. An epileptogenic node
47
+ #
48
+ # `x0` sets the node's excitability (epileptogenicity). `x0 = -1.6` puts the node firmly in the
49
+ # **seizing** regime, so it will discharge autonomously. The slow `z` is stiff, so we need a long
50
+ # run (here 3 s at `dt = 0.1 ms`) for a complete onset → ictal → offset cycle to play out.
51
+
52
+ # %%
53
+ node = brainmass.EpileptorStep(in_size=1, x0=-1.6)
54
+ sim = brainmass.Simulator(node, dt=0.1 * u.ms)
55
+ res = sim.run(
56
+ 3000.0 * u.ms,
57
+ monitors={'lfp': lambda m: m.lfp(), 'z': 'z', 'x1': 'x1'},
58
+ )
59
+ print("recorded steps:", res['lfp'].shape[0])
60
+ lfp_mag = u.get_magnitude(res['lfp'])
61
+ print(f"LFP range: [{lfp_mag.min():.2f}, {lfp_mag.max():.2f}] (large excursions = ictal)")
62
+
63
+ # %% [markdown]
64
+ # ## 2. The seizure and its hidden driver
65
+ #
66
+ # Plotting the LFP proxy above the slow variable `z` reveals the mechanism: the LFP is quiescent,
67
+ # then bursts into fast, high-amplitude discharges (the seizure), then returns to baseline. The
68
+ # **timing of onset and offset is set entirely by the slow ramp of `z`** — the variable you cannot
69
+ # see in an EEG but that the model exposes directly.
70
+
71
+ # %%
72
+ fig, axes = plt.subplots(2, 1, figsize=(10, 6), sharex=True)
73
+ brainmass.viz.plot_timeseries(res['lfp'], ts=res['ts'], ax=axes[0])
74
+ axes[0].set_title('Epileptor LFP proxy (lfp = x2 - x1)')
75
+ axes[0].set_ylabel('LFP')
76
+ brainmass.viz.plot_timeseries(res['z'], ts=res['ts'], ax=axes[1])
77
+ axes[1].set_title('Slow permittivity variable z (the seizure driver)')
78
+ axes[1].set_ylabel('z')
79
+ plt.tight_layout()
80
+ plt.show()
81
+
82
+ # %% [markdown]
83
+ # ## 3. Epileptogenicity: healthy vs. seizure focus
84
+ #
85
+ # The same node is **healthy** or a **seizure focus** depending only on `x0`. We sweep it across
86
+ # the boundary (near `x0 ≈ -2.0`) and use the peak of the fast variable `x1` as a simple seizure
87
+ # indicator: a healthy node keeps `x1` negative, a seizing node drives it positive.
88
+
89
+ # %%
90
+ records = {}
91
+ for x0 in [-2.4, -2.0, -1.8, -1.6]:
92
+ m = brainmass.EpileptorStep(in_size=1, x0=x0)
93
+ r = brainmass.Simulator(m, dt=0.1 * u.ms).run(
94
+ 3000.0 * u.ms, monitors={'lfp': lambda mm: mm.lfp(), 'x1': 'x1'})
95
+ x1max = float(np.max(u.get_magnitude(r['x1'])))
96
+ state = 'SEIZING' if x1max > 0 else 'healthy'
97
+ records[x0] = (r, x1max, state)
98
+ print(f"x0 = {x0:+.1f} -> max(x1) = {x1max:+.3f} ({state})")
99
+
100
+ # %%
101
+ fig, axes = plt.subplots(4, 1, figsize=(10, 8), sharex=True)
102
+ for ax, (x0, (r, x1max, state)) in zip(axes, records.items()):
103
+ brainmass.viz.plot_timeseries(r['lfp'], ts=r['ts'], ax=ax)
104
+ ax.set_title(f'x0 = {x0:+.1f} ({state}, max x1 = {x1max:+.2f})')
105
+ ax.set_ylabel('LFP')
106
+ axes[-1].set_xlabel('time (ms)')
107
+ plt.suptitle('Epileptogenicity x0 controls the seizure transition', y=1.0)
108
+ plt.tight_layout()
109
+ plt.show()
110
+
111
+ # %% [markdown]
112
+ # ## Summary
113
+ #
114
+ # The Epileptor reproduces a full seizure from first principles:
115
+ #
116
+ # - the **slow permittivity variable `z`** autonomously times seizure **onset and offset** — the
117
+ # LFP discharges ride on its slow ramp,
118
+ # - the **epileptogenicity parameter `x0`** sets whether a node is healthy or a seizure focus,
119
+ # with a sharp transition near `x0 ≈ -2.0`, and
120
+ # - {class}`~brainmass.EpileptorStep` exposes the `lfp()` observable (`x2 − x1`) that stands in for
121
+ # a recorded local field potential.
122
+ #
123
+ # In a whole-brain study you would place Epileptor nodes on a connectome (via
124
+ # {class}`~brainmass.Network`), make a subset of regions epileptogenic, and study how seizures
125
+ # **recruit** and **propagate** through the network — the same construction as the resting-state
126
+ # case study, with the Epileptor as the node.
@@ -0,0 +1,86 @@
1
+ """Reference script mirrored from:
2
+ https://brainx.chaobrain.com/brainmass/gallery/model_zoo/wilson_cowan.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
+ # # Wilson-Cowan Model
22
+ #
23
+ # The **Wilson-Cowan model** describes the coupled dynamics of an excitatory population rate $r_E$ and an inhibitory population rate $r_I$ through sigmoidal firing-rate functions:
24
+ #
25
+ # $$\tau_E\dot r_E = -r_E + S_E(w_{EE} r_E - w_{EI} r_I + I_E),\qquad \tau_I\dot r_I = -r_I + S_I(w_{IE} r_E - w_{II} r_I + I_I).$$
26
+ #
27
+ # Depending on the synaptic weights and inputs the model exhibits a stable low-activity state, multistability, or sustained oscillations from the excitatory-inhibitory loop. It is the classic two-population mean-field model of cortical dynamics.
28
+ #
29
+ # **Reference:** Wilson & Cowan (1972), *Excitatory and inhibitory interactions in localized populations of model neurons*, Biophysical Journal 12(1):1-24.
30
+
31
+ # %% [markdown]
32
+ # ## Build the model
33
+ #
34
+ # We choose weights and a drive that put the E-I loop into a limit-cycle (oscillatory) regime.
35
+
36
+ # %%
37
+ node = brainmass.WilsonCowanStep(
38
+ in_size=1, tau_E=2.5 * u.ms, tau_I=3.75 * u.ms,
39
+ wEE=16.0, wEI=12.0, wIE=15.0, wII=3.0)
40
+ node
41
+
42
+ # %% [markdown]
43
+ # ## Run a simulation
44
+
45
+ # %%
46
+ sim = brainmass.Simulator(node, dt=0.1 * u.ms)
47
+ res = sim.run(300. * u.ms, inputs=lambda i, t: (1.0, 0.0),
48
+ monitors=['rE', 'rI'], transient=50. * u.ms)
49
+ res['rE'].shape
50
+
51
+ # %% [markdown]
52
+ # ## Visualize
53
+ #
54
+ # E and I rates oscillate out of phase; the phase portrait shows the E-I limit cycle.
55
+
56
+ # %%
57
+ fig, axes = plt.subplots(1, 2, figsize=(10, 4))
58
+ brainmass.viz.plot_timeseries(
59
+ jnp.concatenate([res['rE'], res['rI']], axis=1), ts=res['ts'],
60
+ labels=['rE', 'rI'], ax=axes[0])
61
+ axes[0].set_title('Wilson-Cowan E / I rates')
62
+ brainmass.viz.plot_phase_portrait(res['rE'], res['rI'], ax=axes[1])
63
+ axes[1].set_xlabel('rE'); axes[1].set_ylabel('rI')
64
+ axes[1].set_title('E-I limit cycle')
65
+ plt.tight_layout()
66
+ plt.show()
67
+
68
+ # %% [markdown]
69
+ # ## Try it: vary the excitatory drive
70
+ #
71
+ # The external drive to the E population moves the node between quiescence, oscillation, and high steady activity.
72
+
73
+ # %%
74
+ fig, ax = plt.subplots(figsize=(8, 4))
75
+ for drive in [0.0, 1.0, 2.5]:
76
+ m = brainmass.WilsonCowanStep(
77
+ in_size=1, tau_E=2.5 * u.ms, tau_I=3.75 * u.ms,
78
+ wEE=16.0, wEI=12.0, wIE=15.0, wII=3.0)
79
+ r = brainmass.Simulator(m, dt=0.1 * u.ms).run(
80
+ 300. * u.ms, inputs=lambda i, t, d=drive: (d, 0.0),
81
+ monitors=['rE'], transient=50. * u.ms)
82
+ ax.plot(u.get_magnitude(r['ts']), u.get_magnitude(r['rE'])[:, 0],
83
+ label=f'I_E = {drive}')
84
+ ax.set_xlabel('time (ms)'); ax.set_ylabel('rE'); ax.legend()
85
+ ax.set_title('Excitatory drive sweep')
86
+ plt.show()
@@ -0,0 +1,167 @@
1
+ """Reference script mirrored from:
2
+ https://brainx.chaobrain.com/brainmass/gallery/case_studies/decision_making.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=0.1 * u.ms)
23
+
24
+ # %% [markdown]
25
+ # # Perceptual Decision-Making with Wong-Wang
26
+ #
27
+ # The **Wong-Wang** model (Wong & Wang, 2006) is the canonical reduced circuit for a two-choice
28
+ # perceptual decision. Two populations of neurons — one for each choice — compete through
29
+ # recurrent self-excitation and mutual inhibition. The competition makes the circuit **bistable**:
30
+ # from a symmetric resting state it commits to one of two high-activity attractors. A sensory
31
+ # **evidence** signal (motion `coherence`) biases which attractor wins, and the slow ramp of the
32
+ # synaptic gating variables `S1`/`S2` is the model's signature of **evidence accumulation**.
33
+ #
34
+ # This case study demonstrates:
35
+ #
36
+ # 1. **evidence accumulation** — the gating variables ramping to a decision under noise,
37
+ # 2. **bistability** — symmetric (zero-evidence) trials breaking left or right at random, and
38
+ # 3. a **psychometric** sweep — choice probability vs. evidence strength.
39
+ #
40
+ # **Reference:** Wong & Wang (2006), *A recurrent network mechanism of time integration in
41
+ # perceptual decisions*, J. Neurosci. 26(4):1314-1328. The model is bundled as
42
+ # {class}`~brainmass.WongWangStep` — no external data needed.
43
+ #
44
+ # :::{note}
45
+ # {class}`~brainmass.WongWangStep` is the reduced **two-variable decision** model (states `S1`,
46
+ # `S2`; `update(coherence=...)`), distinct from {class}`~brainmass.WongWangExcInhStep`, the
47
+ # excitatory/inhibitory mean-field model used for resting-state BOLD.
48
+ # :::
49
+
50
+ # %% [markdown]
51
+ # ## 1. A single decision trial
52
+ #
53
+ # We drive the circuit with a constant rightward **coherence** (favoring population 1) and inject
54
+ # small current noise into each population so trials are stochastic. The firing rates `r1`, `r2`
55
+ # start together, then one wins. The whole trial is compiled into a single
56
+ # {func}`brainstate.transform.for_loop` — the brainmass idiom for running a model many steps — so
57
+ # each trial is fast and we can run dozens of them below.
58
+
59
+ # %%
60
+ dt = 0.1 * u.ms
61
+
62
+ def run_trial(coherence, *, duration=1000.0 * u.ms, sigma=0.02 * u.nA, seed=0):
63
+ """Run one Wong-Wang decision trial; return time, rates (r1, r2), gating (S1, S2)."""
64
+ brainstate.random.seed(seed)
65
+ model = brainmass.WongWangStep(
66
+ in_size=1,
67
+ noise_s1=brainmass.GaussianNoise(1, sigma=sigma),
68
+ noise_s2=brainmass.GaussianNoise(1, sigma=sigma),
69
+ )
70
+ brainstate.nn.init_all_states(model)
71
+ n_steps = int(duration / dt)
72
+
73
+ def step(i):
74
+ r1, r2 = model.update(coherence=coherence)
75
+ return (u.get_magnitude(r1[0]), u.get_magnitude(r2[0]),
76
+ model.S1.value[0], model.S2.value[0])
77
+
78
+ with brainstate.environ.context(dt=dt):
79
+ r1s, r2s, s1s, s2s = brainstate.transform.for_loop(step, np.arange(n_steps))
80
+ ts = (np.arange(n_steps) + 1) * u.get_magnitude(dt)
81
+ return ts, np.asarray(r1s), np.asarray(r2s), np.asarray(s1s), np.asarray(s2s)
82
+
83
+ ts, r1, r2, s1, s2 = run_trial(coherence=0.25, seed=1)
84
+ winner = 1 if s1[-1] > s2[-1] else 2
85
+ print(f"coherence = +0.25 (favors pop 1) -> winner: population {winner}")
86
+ print(f"final gating: S1 = {s1[-1]:.3f}, S2 = {s2[-1]:.3f}")
87
+
88
+ # %%
89
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4))
90
+ ax1.plot(ts, r1, label='r1 (pop 1)'); ax1.plot(ts, r2, label='r2 (pop 2)')
91
+ ax1.set_xlabel('time (ms)'); ax1.set_ylabel('firing rate (Hz)')
92
+ ax1.set_title('Firing rates: competition'); ax1.legend(); ax1.grid(alpha=0.3)
93
+ ax2.plot(ts, s1, label='S1'); ax2.plot(ts, s2, label='S2')
94
+ ax2.set_xlabel('time (ms)'); ax2.set_ylabel('synaptic gating')
95
+ ax2.set_title('Evidence accumulation (gating ramps to a decision)')
96
+ ax2.legend(); ax2.grid(alpha=0.3)
97
+ plt.tight_layout()
98
+ plt.show()
99
+
100
+ # %% [markdown]
101
+ # ## 2. Bistability under zero evidence
102
+ #
103
+ # With **no** evidence (`coherence = 0`) the circuit is symmetric, but noise still pushes it into
104
+ # one of the two attractors — and *which* one varies trial to trial. Running several zero-coherence
105
+ # trials with different noise seeds shows the spontaneous left/right split that is the hallmark of
106
+ # a bistable decision circuit.
107
+
108
+ # %%
109
+ fig, ax = plt.subplots(figsize=(9, 4))
110
+ n_trials = 8
111
+ choices = []
112
+ for seed in range(n_trials):
113
+ t, _, _, s1_t, s2_t = run_trial(coherence=0.0, seed=seed)
114
+ choice = 1 if s1_t[-1] > s2_t[-1] else 2
115
+ choices.append(choice)
116
+ color = 'tab:blue' if choice == 1 else 'tab:red'
117
+ ax.plot(t, s1_t - s2_t, color=color, alpha=0.7)
118
+ ax.axhline(0, color='grey', lw=1)
119
+ ax.set_xlabel('time (ms)'); ax.set_ylabel('S1 - S2 (decision variable)')
120
+ ax.set_title(f'Zero-evidence bistability: {choices.count(1)} chose pop 1, '
121
+ f'{choices.count(2)} chose pop 2')
122
+ plt.tight_layout()
123
+ plt.show()
124
+ print("per-trial choices (zero coherence):", choices)
125
+
126
+ # %% [markdown]
127
+ # ## 3. Psychometric curve
128
+ #
129
+ # Sweeping the evidence strength and measuring how often population 1 wins traces a
130
+ # **psychometric curve**: chance (50%) at zero coherence, rising toward certainty as the evidence
131
+ # grows. We average several noisy trials per coherence level.
132
+
133
+ # %%
134
+ coherences = [-0.5, -0.25, -0.1, 0.0, 0.1, 0.25, 0.5]
135
+ n_rep = 12
136
+ p_choose_1 = []
137
+ for c in coherences:
138
+ wins = 0
139
+ for seed in range(n_rep):
140
+ _, _, _, s1_t, s2_t = run_trial(coherence=c, seed=seed, duration=800.0 * u.ms)
141
+ wins += int(s1_t[-1] > s2_t[-1])
142
+ p_choose_1.append(wins / n_rep)
143
+ print(f"coherence = {c:+.2f} -> P(choose pop 1) = {wins / n_rep:.2f}")
144
+
145
+ fig, ax = plt.subplots(figsize=(6.5, 4))
146
+ ax.plot(coherences, p_choose_1, 'o-', color='tab:purple')
147
+ ax.axhline(0.5, color='grey', ls='--', lw=1)
148
+ ax.axvline(0.0, color='grey', ls=':', lw=1)
149
+ ax.set_xlabel('motion coherence'); ax.set_ylabel('P(choose population 1)')
150
+ ax.set_ylim(-0.05, 1.05); ax.set_title('Psychometric curve')
151
+ plt.tight_layout()
152
+ plt.show()
153
+
154
+ # %% [markdown]
155
+ # ## Summary
156
+ #
157
+ # The Wong-Wang circuit reproduces the core phenomena of two-choice perceptual decisions:
158
+ #
159
+ # - **evidence accumulation** — the synaptic gating variables `S1`/`S2` ramp up and one wins,
160
+ # - **bistability** — under zero evidence, noise alone breaks the symmetry left or right, and
161
+ # - a **psychometric curve** — choice probability rises smoothly with evidence strength.
162
+ #
163
+ # {class}`~brainmass.WongWangStep` exposes the rates via `update(coherence=...)` and the gating
164
+ # state via `model.S1` / `model.S2`. A constant scalar drive like `coherence` is passed directly to
165
+ # `update`; the noise injected through `noise_s1`/`noise_s2` is what makes individual trials
166
+ # stochastic. This single-circuit model is the decision-making node you would embed in a larger
167
+ # network to study distributed choice.