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,320 @@
1
+ # examples/nest_like/brette_et_al_2007.py
2
+ # Copyright 2026 BrainX Ecosystem Limited. Apache 2.0.
3
+ """Brette et al. 2007 (Vogels-Abbott) COBA + CUBA benchmarks — NEST-style port.
4
+
5
+ Port of NEST's ``brette_et_al_2007/{coba,cuba}.py`` onto brainpy.state's explicit
6
+ ``Simulator`` API. Both are the Vogels & Abbott (2005) [1]_ sparse self-sustained
7
+ excitatory/inhibitory network — the FACETS simulator-review benchmarks [2]_:
8
+
9
+ * **COBA** (benchmark 1): conductance-based ``iaf_cond_exp``. Excitatory input is
10
+ routed to ``g_ex`` (``receptor_type=1``) and inhibitory input to ``g_in``
11
+ (``receptor_type=2``); inhibition arises from the reversal potential ``E_in``,
12
+ so the inhibitory weight is a **positive** conductance magnitude.
13
+ * **CUBA** (benchmark 2): current-based ``iaf_psc_exp``. The neuron splits
14
+ excitatory/inhibitory postsynaptic currents by weight **sign** internally, so
15
+ the inhibitory weight is **negative** and no receptor routing is needed.
16
+
17
+ Both share one architecture: ``NE=3200`` excitatory + ``NI=800`` inhibitory neurons,
18
+ connection probability ``epsilon=0.02`` (``fixed_indegree`` of ``CE=64`` excitatory
19
+ and ``CI=16`` inhibitory inputs onto every neuron), and a brief 50 ms Poisson **kick**
20
+ (300 Hz to the first 50 excitatory neurons) that ignites activity which then
21
+ self-sustains in an asynchronous-irregular state. The spike output of ``Nrec=500``
22
+ neurons per population is recorded; the reported observable is the mean per-neuron
23
+ population firing rate.
24
+
25
+ The Hodgkin-Huxley variant of this benchmark (NEST ``hh_coba.py``) already ships as
26
+ ``examples/brainpy_like/106_COBA_HH_2007.py``.
27
+
28
+ Run: python examples/nest_like/brette_et_al_2007.py
29
+
30
+ References
31
+ ----------
32
+ .. [1] Vogels TP, Abbott LF. 2005. Signal propagation and logic gating in networks
33
+ of integrate-and-fire neurons. J Neurosci. 25(46):10786-10795.
34
+ .. [2] Brette R, Rudolph M, Carnevale T, et al. 2007. Simulation of networks of
35
+ spiking neurons: a review of tools and strategies. J Comput Neurosci.
36
+ 23(3):349-398.
37
+ """
38
+ import jax
39
+ import brainstate
40
+ jax.config.update('jax_enable_x64', True)
41
+ brainstate.environ.set(precision=64)
42
+
43
+ import numpy as np
44
+ import brainunit as u
45
+ import braintools
46
+
47
+ from brainpy.state import (
48
+ Simulator, fixed_indegree, one_to_one,
49
+ iaf_cond_exp, iaf_psc_exp, poisson_generator, spike_recorder,
50
+ )
51
+
52
+ # --- Shared Vogels-Abbott architecture -------------------------------------------
53
+ NE, NI = 3200, 800 # excitatory / inhibitory population sizes
54
+ EPSILON = 0.02 # connection probability -> fixed in-degrees
55
+ NSTIM = 50 # # excitatory neurons receiving the ignition kick
56
+ NREC = 500 # # neurons per population recorded for the rate
57
+ DELAY = 0.1 # synaptic delay [ms]
58
+ DT = 0.1 # integration step [ms]
59
+ KICK_RATE = 300.0 # ignition Poisson rate [spikes/s]
60
+ KICK_START, KICK_STOP = 1.0, 51.0 # ignition window [ms]
61
+
62
+ # --- COBA (benchmark 1: iaf_cond_exp, conductance-based) -------------------------
63
+ COBA_PARAMS = dict(E_L=-60.0, V_th=-50.0, V_reset=-60.0, t_ref=5.0, E_ex=0.0,
64
+ E_in=-80.0, C_m=200.0, g_L=10.0, tau_syn_ex=5.0, tau_syn_in=10.0)
65
+ COBA_W_E = 6.0 # excitatory weight [nS] -> receptor 1 (g_ex)
66
+ COBA_W_I = 67.0 # inhibitory weight [nS] -> receptor 2 (g_in), positive magnitude
67
+ COBA_SIMTIME = 1000.0 # [ms]
68
+
69
+ # --- CUBA (benchmark 2: iaf_psc_exp, current-based) ------------------------------
70
+ CUBA_PARAMS = dict(E_L=-49.0, V_th=-50.0, V_reset=-60.0, C_m=200.0, tau_m=20.0,
71
+ tau_syn_ex=5.0, tau_syn_in=10.0, t_ref=5.0)
72
+ CUBA_VINIT = -49.0 # initial membrane potential [mV]
73
+ CUBA_W_E = 16.2 # excitatory PSC amplitude [pA] (positive, sign-routed)
74
+ CUBA_W_I = -139.5 # inhibitory PSC amplitude [pA] (negative, sign-routed)
75
+ CUBA_SIMTIME = 10000.0 # [ms] (10x longer than COBA: low load needs a longer window)
76
+
77
+
78
+ def connection_counts(ne=NE, ni=NI, epsilon=EPSILON):
79
+ """Fixed in-degrees ``(CE, CI)`` for the Vogels-Abbott network.
80
+
81
+ Parameters
82
+ ----------
83
+ ne, ni : int, optional
84
+ Excitatory / inhibitory population sizes.
85
+ epsilon : float, optional
86
+ Connection probability; the in-degree is ``int(N * epsilon)``.
87
+
88
+ Returns
89
+ -------
90
+ tuple of int
91
+ ``(CE, CI)`` — excitatory and inhibitory inputs onto every neuron.
92
+
93
+ Examples
94
+ --------
95
+ .. code-block:: python
96
+
97
+ >>> from examples.nest_like.brette_et_al_2007 import connection_counts
98
+ >>> connection_counts(3200, 800, 0.02)
99
+ (64, 16)
100
+ """
101
+ return int(ne * epsilon), int(ni * epsilon)
102
+
103
+
104
+ def population_rate(raster, n_rec, simtime_ms):
105
+ """Mean per-neuron firing rate [spikes/s] from a spike-count raster.
106
+
107
+ Matches NEST's benchmark formula ``n_spikes / (n_rec * simtime) * 1000``.
108
+
109
+ Parameters
110
+ ----------
111
+ raster : ArrayLike
112
+ ``(T, N)`` per-step spike-count matrix (as returned by ``result.spikes``).
113
+ n_rec : int
114
+ Number of neurons the rate is averaged over.
115
+ simtime_ms : float
116
+ Duration of the spike count window [ms].
117
+
118
+ Returns
119
+ -------
120
+ float
121
+ Mean firing rate [spikes/s].
122
+
123
+ Examples
124
+ --------
125
+ .. code-block:: python
126
+
127
+ >>> import numpy as np
128
+ >>> from examples.nest_like.brette_et_al_2007 import population_rate
129
+ >>> raster = np.zeros((1000, 2)); raster[::100] = 1 # 10 spikes/neuron in 100 ms
130
+ >>> population_rate(raster, 2, 100.0)
131
+ 100.0
132
+ """
133
+ return float(np.asarray(raster).sum()) / (n_rec * simtime_ms) * 1000.0
134
+
135
+
136
+ def build_coba(seed, *, ne=NE, ni=NI, dt=DT, comm='sparse'):
137
+ """Build the conductance-based (COBA) Vogels-Abbott network.
138
+
139
+ Parameters
140
+ ----------
141
+ seed : int
142
+ Seed for the kick generator and the four connectivity draws (offset per block).
143
+ ne, ni : int, optional
144
+ Excitatory / inhibitory population sizes.
145
+ dt : float, optional
146
+ Integration step [ms].
147
+ comm : str, optional
148
+ Connectivity backend, ``'sparse'`` (CSR) or ``'dense'``. Default ``'sparse'``.
149
+
150
+ Returns
151
+ -------
152
+ tuple
153
+ ``(sim, esr, isr)`` — the configured ``Simulator`` and the excitatory /
154
+ inhibitory ``spike_recorder`` handles.
155
+ """
156
+ ce, ci = connection_counts(ne, ni)
157
+ params = dict(
158
+ E_L=COBA_PARAMS['E_L'] * u.mV, V_th=COBA_PARAMS['V_th'] * u.mV,
159
+ V_reset=COBA_PARAMS['V_reset'] * u.mV, t_ref=COBA_PARAMS['t_ref'] * u.ms,
160
+ E_ex=COBA_PARAMS['E_ex'] * u.mV, E_in=COBA_PARAMS['E_in'] * u.mV,
161
+ C_m=COBA_PARAMS['C_m'] * u.pF, g_L=COBA_PARAMS['g_L'] * u.nS,
162
+ tau_syn_ex=COBA_PARAMS['tau_syn_ex'] * u.ms, tau_syn_in=COBA_PARAMS['tau_syn_in'] * u.ms,
163
+ V_initializer=braintools.init.Constant(COBA_PARAMS['E_L'] * u.mV))
164
+
165
+ sim = Simulator(dt=dt * u.ms)
166
+ e = sim.create(iaf_cond_exp, ne, params=params)
167
+ i = sim.create(iaf_cond_exp, ni, params=params)
168
+ kick = sim.create(poisson_generator, NSTIM, rate=KICK_RATE * u.Hz,
169
+ start=KICK_START * u.ms, stop=KICK_STOP * u.ms, rng_seed=seed)
170
+ esr = sim.create(spike_recorder)
171
+ isr = sim.create(spike_recorder)
172
+
173
+ # Recurrent: every neuron gets CE excitatory (receptor 1 -> g_ex) and CI
174
+ # inhibitory (receptor 2 -> g_in) inputs; inhibitory weight is a positive nS.
175
+ sim.connect(e, e + i, weight=COBA_W_E * u.nS, delay=DELAY * u.ms,
176
+ rule=fixed_indegree(ce), comm=comm, receptor_type=1,
177
+ allow_multapses=True, seed=10 * seed + 1)
178
+ sim.connect(i, e + i, weight=COBA_W_I * u.nS, delay=DELAY * u.ms,
179
+ rule=fixed_indegree(ci), comm=comm, receptor_type=2,
180
+ allow_multapses=True, seed=10 * seed + 2)
181
+ # Ignition kick: independent 300 Hz trains -> first NSTIM excitatory neurons.
182
+ sim.connect(kick, e[:NSTIM], weight=COBA_W_E * u.nS, delay=DELAY * u.ms,
183
+ rule=one_to_one, receptor_type=1)
184
+ sim.connect(e[:NREC], esr)
185
+ sim.connect(i[:NREC], isr)
186
+ return sim, esr, isr
187
+
188
+
189
+ def build_cuba(seed, *, ne=NE, ni=NI, dt=DT, comm='sparse'):
190
+ """Build the current-based (CUBA) Vogels-Abbott network.
191
+
192
+ Same architecture as :func:`build_coba` but with ``iaf_psc_exp`` neurons; the
193
+ neuron routes excitatory/inhibitory PSCs by weight **sign**, so the inhibitory
194
+ weight is negative and no receptor routing is used.
195
+
196
+ Parameters
197
+ ----------
198
+ seed : int
199
+ Seed for the kick generator and connectivity draws.
200
+ ne, ni : int, optional
201
+ Population sizes.
202
+ dt : float, optional
203
+ Integration step [ms].
204
+ comm : str, optional
205
+ Connectivity backend. Default ``'sparse'``.
206
+
207
+ Returns
208
+ -------
209
+ tuple
210
+ ``(sim, esr, isr)``.
211
+ """
212
+ ce, ci = connection_counts(ne, ni)
213
+ params = dict(
214
+ E_L=CUBA_PARAMS['E_L'] * u.mV, V_th=CUBA_PARAMS['V_th'] * u.mV,
215
+ V_reset=CUBA_PARAMS['V_reset'] * u.mV, C_m=CUBA_PARAMS['C_m'] * u.pF,
216
+ tau_m=CUBA_PARAMS['tau_m'] * u.ms, tau_syn_ex=CUBA_PARAMS['tau_syn_ex'] * u.ms,
217
+ tau_syn_in=CUBA_PARAMS['tau_syn_in'] * u.ms, t_ref=CUBA_PARAMS['t_ref'] * u.ms,
218
+ V_initializer=braintools.init.Constant(CUBA_VINIT * u.mV))
219
+
220
+ sim = Simulator(dt=dt * u.ms)
221
+ e = sim.create(iaf_psc_exp, ne, params=params)
222
+ i = sim.create(iaf_psc_exp, ni, params=params)
223
+ kick = sim.create(poisson_generator, NSTIM, rate=KICK_RATE * u.Hz,
224
+ start=KICK_START * u.ms, stop=KICK_STOP * u.ms, rng_seed=seed)
225
+ esr = sim.create(spike_recorder)
226
+ isr = sim.create(spike_recorder)
227
+
228
+ # Recurrent: excitatory weight positive, inhibitory weight negative (sign-routed).
229
+ sim.connect(e, e + i, weight=CUBA_W_E * u.pA, delay=DELAY * u.ms,
230
+ rule=fixed_indegree(ce), comm=comm, allow_multapses=True, seed=10 * seed + 1)
231
+ sim.connect(i, e + i, weight=CUBA_W_I * u.pA, delay=DELAY * u.ms,
232
+ rule=fixed_indegree(ci), comm=comm, allow_multapses=True, seed=10 * seed + 2)
233
+ sim.connect(kick, e[:NSTIM], weight=CUBA_W_E * u.pA, delay=DELAY * u.ms,
234
+ rule=one_to_one)
235
+ sim.connect(e[:NREC], esr)
236
+ sim.connect(i[:NREC], isr)
237
+ return sim, esr, isr
238
+
239
+
240
+ def _rates(res, esr, isr, simtime, n_rec=NREC):
241
+ """Full-window and second-half (self-sustained) E/I rates from the recorders."""
242
+ e_raster = np.asarray(res.spikes(esr.segments[0].population)) # (T, n_rec)
243
+ i_raster = np.asarray(res.spikes(isr.segments[0].population))
244
+ half = e_raster.shape[0] // 2
245
+ return dict(
246
+ e_rate=population_rate(e_raster, n_rec, simtime),
247
+ i_rate=population_rate(i_raster, n_rec, simtime),
248
+ e_rate_late=population_rate(e_raster[half:], n_rec, simtime / 2.0),
249
+ i_rate_late=population_rate(i_raster[half:], n_rec, simtime / 2.0),
250
+ )
251
+
252
+
253
+ def simulate_coba(seed, *, simtime=COBA_SIMTIME, ne=NE, ni=NI, dt=DT, comm='sparse'):
254
+ """Build, run, and measure the COBA network for one seed.
255
+
256
+ Parameters
257
+ ----------
258
+ seed : int
259
+ Network seed.
260
+ simtime : float, optional
261
+ Simulated duration [ms].
262
+ ne, ni : int, optional
263
+ Population sizes.
264
+ dt : float, optional
265
+ Integration step [ms].
266
+ comm : str, optional
267
+ Connectivity backend.
268
+
269
+ Returns
270
+ -------
271
+ dict
272
+ ``e_rate``/``i_rate`` (full-window, NEST formula) and ``e_rate_late``/
273
+ ``i_rate_late`` (second-half, evidence of self-sustained activity) [spikes/s].
274
+ """
275
+ sim, esr, isr = build_coba(seed, ne=ne, ni=ni, dt=dt, comm=comm)
276
+ res = sim.simulate(simtime * u.ms)
277
+ return _rates(res, esr, isr, simtime)
278
+
279
+
280
+ def simulate_cuba(seed, *, simtime=CUBA_SIMTIME, ne=NE, ni=NI, dt=DT, comm='sparse'):
281
+ """Build, run, and measure the CUBA network for one seed.
282
+
283
+ Parameters
284
+ ----------
285
+ seed : int
286
+ Network seed.
287
+ simtime : float, optional
288
+ Simulated duration [ms].
289
+ ne, ni : int, optional
290
+ Population sizes.
291
+ dt : float, optional
292
+ Integration step [ms].
293
+ comm : str, optional
294
+ Connectivity backend.
295
+
296
+ Returns
297
+ -------
298
+ dict
299
+ ``e_rate``/``i_rate`` and ``e_rate_late``/``i_rate_late`` [spikes/s].
300
+ """
301
+ sim, esr, isr = build_cuba(seed, ne=ne, ni=ni, dt=dt, comm=comm)
302
+ res = sim.simulate(simtime * u.ms)
303
+ return _rates(res, esr, isr, simtime)
304
+
305
+
306
+ def main():
307
+ print("Brette et al. 2007 (Vogels-Abbott) self-sustained E/I network — "
308
+ f"NE={NE}, NI={NI}, CE/CI={connection_counts()}.")
309
+ print(f" COBA (iaf_cond_exp, conductance) simtime={COBA_SIMTIME} ms ...")
310
+ coba = simulate_coba(seed=1)
311
+ print(f" E rate {coba['e_rate']:.2f} Hz | I rate {coba['i_rate']:.2f} Hz "
312
+ f"(2nd-half E {coba['e_rate_late']:.2f} Hz -> self-sustained)")
313
+ print(f" CUBA (iaf_psc_exp, current) simtime={CUBA_SIMTIME} ms ...")
314
+ cuba = simulate_cuba(seed=1)
315
+ print(f" E rate {cuba['e_rate']:.2f} Hz | I rate {cuba['i_rate']:.2f} Hz "
316
+ f"(2nd-half E {cuba['e_rate_late']:.2f} Hz -> self-sustained)")
317
+
318
+
319
+ if __name__ == "__main__":
320
+ main()
@@ -0,0 +1,108 @@
1
+ # examples/nest_like/brunel_alpha.py
2
+ # Copyright 2026 BrainX Ecosystem Limited. Apache 2.0.
3
+ """Brunel (2000) random balanced network with alpha synapses — NEST-style port.
4
+
5
+ Port of NEST's ``brunel_alpha_nest.py`` onto brainpy.state's explicit Simulator
6
+ API, driving the real ``iaf_psc_alpha`` / ``poisson_generator`` / ``spike_recorder``
7
+ models. Default ``order=400`` keeps the dense event projection memory-light; pass
8
+ a larger ``order`` once the sparse comm (EventFixedNumConn) lands.
9
+
10
+ Run: python examples/nest_like/brunel_alpha.py
11
+ """
12
+ import jax
13
+ import brainstate
14
+ jax.config.update('jax_enable_x64', True)
15
+ brainstate.environ.set(precision=64)
16
+
17
+ import numpy as np
18
+ import scipy.special as sp
19
+ import brainunit as u
20
+ import braintools
21
+
22
+ from brainpy.state import (
23
+ Simulator, fixed_indegree, all_to_all,
24
+ iaf_psc_alpha, poisson_generator, spike_recorder,
25
+ )
26
+
27
+
28
+ def LambertWm1(x):
29
+ return sp.lambertw(x, k=-1 if x < 0 else 0).real
30
+
31
+
32
+ def ComputePSPnorm(tauMem, CMem, tauSyn):
33
+ a = tauMem / tauSyn
34
+ b = 1.0 / tauSyn - 1.0 / tauMem
35
+ t_max = 1.0 / b * (-LambertWm1(-np.exp(-1.0 / a) / a) - 1.0 / a)
36
+ return (np.exp(1.0) / (tauSyn * CMem * b)
37
+ * ((np.exp(-t_max / tauMem) - np.exp(-t_max / tauSyn)) / b
38
+ - t_max * np.exp(-t_max / tauSyn)))
39
+
40
+
41
+ def build(order=2500, simtime=1000.0, comm='sparse'):
42
+ dt, delay = 0.1, 1.5
43
+ g, eta, epsilon = 5.0, 2.0, 0.1
44
+ NE, NI = 4 * order, 1 * order
45
+ CE, CI = int(epsilon * NE), int(epsilon * NI)
46
+ N_rec = 50
47
+ tauSyn, tauMem, CMem, theta, tref = 0.5, 20.0, 250.0, 20.0, 2.0
48
+
49
+ J = 0.1
50
+ J_unit = ComputePSPnorm(tauMem, CMem, tauSyn)
51
+ J_ex = J / J_unit
52
+ J_in = -g * J_ex
53
+ nu_th = (theta * CMem) / (J_ex * CE * np.exp(1) * tauMem * tauSyn)
54
+ p_rate = 1000.0 * (eta * nu_th) * CE
55
+
56
+ npar = dict(C_m=CMem * u.pF, tau_m=tauMem * u.ms, tau_syn_ex=tauSyn * u.ms,
57
+ tau_syn_in=tauSyn * u.ms, t_ref=tref * u.ms, E_L=0. * u.mV,
58
+ V_reset=0. * u.mV, V_th=theta * u.mV,
59
+ V_initializer=braintools.init.Constant(0. * u.mV))
60
+
61
+ sim = Simulator(dt=dt * u.ms)
62
+ ne = sim.create(iaf_psc_alpha, NE, params=npar)
63
+ ni = sim.create(iaf_psc_alpha, NI, params=npar)
64
+ noise = sim.create(poisson_generator, rate=p_rate * u.Hz)
65
+ esr = sim.create(spike_recorder)
66
+ isr = sim.create(spike_recorder)
67
+
68
+ sim.connect(noise, ne, weight=J_ex * u.pA, delay=delay * u.ms, rule=all_to_all)
69
+ sim.connect(noise, ni, weight=J_ex * u.pA, delay=delay * u.ms, rule=all_to_all)
70
+ sim.connect(ne, ne + ni, weight=J_ex * u.pA, delay=delay * u.ms,
71
+ rule=fixed_indegree(CE), comm=comm, allow_multapses=True, seed=1)
72
+ sim.connect(ni, ne + ni, weight=J_in * u.pA, delay=delay * u.ms,
73
+ rule=fixed_indegree(CI), comm=comm, allow_multapses=True, seed=2)
74
+ sim.connect(ne[:N_rec], esr)
75
+ sim.connect(ni[:N_rec], isr)
76
+ return sim, esr, isr, N_rec, simtime
77
+
78
+
79
+ def main():
80
+ order = 2500
81
+ print(f"Brunel network: order={order} -> {4 * order} exc + {order} inh neurons, "
82
+ f"sparse comm.")
83
+ print(" Building (fixed-indegree sampling is O(N); ~1-2 min at this size)...")
84
+ sim, esr, isr, N_rec, simtime = build(order=order)
85
+ res = sim.simulate(simtime * u.ms)
86
+ erate = res.rate(esr.segments[0].population)
87
+ irate = res.rate(isr.segments[0].population)
88
+ print("Brunel network (brainpy.state, alpha synapses)")
89
+ print(f" Excitatory rate : {erate:.2f} spks/s")
90
+ print(f" Inhibitory rate : {irate:.2f} spks/s")
91
+
92
+ try:
93
+ import matplotlib.pyplot as plt
94
+ spk = np.asarray(res.spikes(esr.segments[0].population)) # (T, N_rec)
95
+ ts, ids = np.nonzero(spk > 0)
96
+ plt.figure(figsize=(8, 4))
97
+ plt.scatter(ts * 0.1, ids, s=1.0, color="k")
98
+ plt.xlabel("time (ms)"); plt.ylabel("exc neuron")
99
+ plt.title("Brunel network — excitatory raster")
100
+ plt.tight_layout()
101
+ plt.savefig("examples/nest_like/brunel_alpha_raster.png", dpi=100)
102
+ print(" wrote examples/nest_like/brunel_alpha_raster.png")
103
+ except ImportError:
104
+ print(" (matplotlib not installed; skipping raster)")
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()
@@ -0,0 +1,93 @@
1
+ # examples/nest_like/brunel_delta.py
2
+ # Copyright 2026 BrainX Ecosystem Limited. Apache 2.0.
3
+ """Brunel (2000) random balanced network with delta synapses — NEST-style port.
4
+
5
+ Port of NEST's ``brunel_delta_nest.py`` onto brainpy.state's explicit Simulator
6
+ API, driving the real ``iaf_psc_delta`` / ``poisson_generator`` / ``spike_recorder``
7
+ models. Unlike the alpha variant, delta synapses deliver an instantaneous
8
+ membrane-voltage jump, so connection weights are voltages (mV) and ``J_ex = J``
9
+ directly — there is no ComputePSPnorm current-to-voltage rescaling.
10
+
11
+ Run: python examples/nest_like/brunel_delta.py
12
+ """
13
+ import jax
14
+ import brainstate
15
+ jax.config.update('jax_enable_x64', True)
16
+ brainstate.environ.set(precision=64)
17
+
18
+ import numpy as np
19
+ import brainunit as u
20
+ import braintools
21
+
22
+ from brainpy.state import (
23
+ Simulator, fixed_indegree, all_to_all,
24
+ iaf_psc_delta, poisson_generator, spike_recorder,
25
+ )
26
+
27
+
28
+ def build(order=2500, simtime=1000.0, comm='sparse'):
29
+ dt, delay = 0.1, 1.5
30
+ g, eta, epsilon = 5.0, 2.0, 0.1
31
+ NE, NI = 4 * order, 1 * order
32
+ CE, CI = int(epsilon * NE), int(epsilon * NI)
33
+ N_rec = 50
34
+ tauMem, CMem, theta, tref = 20.0, 1.0, 20.0, 2.0
35
+
36
+ J = 0.1 # mV, postsynaptic amplitude (delta jump)
37
+ J_ex = J
38
+ J_in = -g * J_ex
39
+ nu_th = theta / (J * CE * tauMem)
40
+ p_rate = 1000.0 * (eta * nu_th) * CE
41
+
42
+ npar = dict(C_m=CMem * u.pF, tau_m=tauMem * u.ms, t_ref=tref * u.ms,
43
+ E_L=0. * u.mV, V_reset=0. * u.mV, V_th=theta * u.mV,
44
+ V_initializer=braintools.init.Constant(0. * u.mV))
45
+
46
+ sim = Simulator(dt=dt * u.ms)
47
+ ne = sim.create(iaf_psc_delta, NE, params=npar)
48
+ ni = sim.create(iaf_psc_delta, NI, params=npar)
49
+ noise = sim.create(poisson_generator, rate=p_rate * u.Hz)
50
+ esr = sim.create(spike_recorder)
51
+ isr = sim.create(spike_recorder)
52
+
53
+ sim.connect(noise, ne, weight=J_ex * u.mV, delay=delay * u.ms, rule=all_to_all)
54
+ sim.connect(noise, ni, weight=J_ex * u.mV, delay=delay * u.ms, rule=all_to_all)
55
+ sim.connect(ne, ne + ni, weight=J_ex * u.mV, delay=delay * u.ms,
56
+ rule=fixed_indegree(CE), comm=comm, allow_multapses=True, seed=1)
57
+ sim.connect(ni, ne + ni, weight=J_in * u.mV, delay=delay * u.ms,
58
+ rule=fixed_indegree(CI), comm=comm, allow_multapses=True, seed=2)
59
+ sim.connect(ne[:N_rec], esr)
60
+ sim.connect(ni[:N_rec], isr)
61
+ return sim, esr, isr, N_rec, simtime
62
+
63
+
64
+ def main():
65
+ order = 2500
66
+ print(f"Brunel network: order={order} -> {4 * order} exc + {order} inh neurons, "
67
+ f"delta synapses, sparse comm.")
68
+ print(" Building (fixed-indegree sampling is O(N); ~1-2 min at this size)...")
69
+ sim, esr, isr, N_rec, simtime = build(order=order)
70
+ res = sim.simulate(simtime * u.ms)
71
+ erate = res.rate(esr.segments[0].population)
72
+ irate = res.rate(isr.segments[0].population)
73
+ print("Brunel network (brainpy.state, delta synapses)")
74
+ print(f" Excitatory rate : {erate:.2f} spks/s")
75
+ print(f" Inhibitory rate : {irate:.2f} spks/s")
76
+
77
+ try:
78
+ import matplotlib.pyplot as plt
79
+ spk = np.asarray(res.spikes(esr.segments[0].population)) # (T, N_rec)
80
+ ts, ids = np.nonzero(spk > 0)
81
+ plt.figure(figsize=(8, 4))
82
+ plt.scatter(ts * 0.1, ids, s=1.0, color="k")
83
+ plt.xlabel("time (ms)"); plt.ylabel("exc neuron")
84
+ plt.title("Brunel network — excitatory raster (delta synapses)")
85
+ plt.tight_layout()
86
+ plt.savefig("examples/nest_like/brunel_delta_raster.png", dpi=100)
87
+ print(" wrote examples/nest_like/brunel_delta_raster.png")
88
+ except ImportError:
89
+ print(" (matplotlib not installed; skipping raster)")
90
+
91
+
92
+ if __name__ == "__main__":
93
+ main()
@@ -0,0 +1,171 @@
1
+ # examples/nest_like/clopath_synapse_spike_pairing.py
2
+ # Copyright 2026 BrainX Ecosystem Limited. Apache 2.0.
3
+ """Clopath voltage-based STDP spike-pairing -- NEST-style port.
4
+
5
+ Port of NEST's ``clopath_synapse_spike_pairing.py``. A presynaptic spike train is
6
+ paired with a postsynaptic train (driven by an 80 mV ``spike_generator`` clamp)
7
+ across pairing frequencies 10-50 Hz, in both post-before-pre (depression-leaning)
8
+ and pre-before-post (potentiation) orderings, onto an ``aeif_psc_delta_clopath``
9
+ neuron through a single ``clopath_synapse`` edge. The stored weight after the
10
+ protocol is read with ``res.weight_trace`` and the *normalised weight change* is
11
+ plotted against pairing frequency (the upstream figure).
12
+
13
+ ``aeif_psc_delta_clopath`` is a **delta** neuron, so the bare ``clopath_synapse``
14
+ weight is in **mV** (not pA). The protocol, parameters, and frozen 5 % parity band
15
+ are the cluster-07 ones (LTD near-exact, LTP within 5 %). The presynaptic train
16
+ relays through a ``spike_generator`` directly into the plastic edge (in NEST a
17
+ ``parrot_neuron`` relays it, since a device cannot drive a plastic synapse).
18
+
19
+ Run: python examples/nest_like/clopath_synapse_spike_pairing.py
20
+ """
21
+ import jax
22
+ import brainstate
23
+ jax.config.update('jax_enable_x64', True)
24
+ brainstate.environ.set(precision=64)
25
+
26
+ import numpy as np
27
+ import brainunit as u
28
+ import braintools
29
+
30
+ from brainpy.state import (Simulator, spike_generator, clopath_synapse,
31
+ static_synapse, aeif_psc_delta_clopath)
32
+
33
+ # -- canonical cluster-07 spike-pairing protocol (NEST pynest example) ------------
34
+ DT = 0.1 # ms, resolution
35
+ RELAY_D = 0.1 # spike_generator -> driver delay (ms) == one step
36
+ INIT_W = 0.5 # initial Clopath weight (mV; aeif_psc_delta_clopath is a delta model)
37
+ DRIVE_W = 80.0 # post driver weight (mV voltage jump -> forces the V_clamp spike)
38
+ DELAY_UBARS = 0.1 # ms; aligned to the substrate's one-step read lag
39
+
40
+ #: Pairing frequencies (Hz) of the five trains in each ordering (upstream).
41
+ RHO = np.array([10.0, 20.0, 30.0, 40.0, 50.0])
42
+
43
+ # Canonical pre/post spike trains: first five = post-before-pre (depression-leaning),
44
+ # last five = pre-before-post (potentiation), at 10/20/30/40/50 Hz pairing rates.
45
+ SPIKE_TIMES_PRE = [
46
+ [20.0, 120.0, 220.0, 320.0, 420.0],
47
+ [20.0, 70.0, 120.0, 170.0, 220.0],
48
+ [20.0, 53.3, 86.7, 120.0, 153.3],
49
+ [20.0, 45.0, 70.0, 95.0, 120.0],
50
+ [20.0, 40.0, 60.0, 80.0, 100.0],
51
+ [120.0, 220.0, 320.0, 420.0, 520.0, 620.0],
52
+ [70.0, 120.0, 170.0, 220.0, 270.0, 320.0],
53
+ [53.3, 86.6, 120.0, 153.3, 186.6, 220.0],
54
+ [45.0, 70.0, 95.0, 120.0, 145.0, 170.0],
55
+ [40.0, 60.0, 80.0, 100.0, 120.0, 140.0],
56
+ ]
57
+ SPIKE_TIMES_POST = [
58
+ [10.0, 110.0, 210.0, 310.0, 410.0],
59
+ [10.0, 60.0, 110.0, 160.0, 210.0],
60
+ [10.0, 43.3, 76.7, 110.0, 143.3],
61
+ [10.0, 35.0, 60.0, 85.0, 110.0],
62
+ [10.0, 30.0, 50.0, 70.0, 90.0],
63
+ [130.0, 230.0, 330.0, 430.0, 530.0, 630.0],
64
+ [80.0, 130.0, 180.0, 230.0, 280.0, 330.0],
65
+ [63.3, 96.6, 130.0, 163.3, 196.6, 230.0],
66
+ [55.0, 80.0, 105.0, 130.0, 155.0, 180.0],
67
+ [50.0, 70.0, 90.0, 110.0, 130.0, 150.0],
68
+ ]
69
+ #: Index range of the pure depression-leaning (post-before-pre) trains.
70
+ LTD_TRAINS = range(0, 5)
71
+ #: Index range of the potentiation (pre-before-post) trains.
72
+ LTP_TRAINS = range(5, 10)
73
+
74
+
75
+ def clopath_neuron(sim, n=1):
76
+ """Create ``n`` ``aeif_psc_delta_clopath`` neurons with the canonical parameters."""
77
+ return sim.create(
78
+ aeif_psc_delta_clopath, n,
79
+ E_L=-70.6 * u.mV, V_peak=33.0 * u.mV, C_m=281.0 * u.pF, theta_minus=-70.6 * u.mV,
80
+ theta_plus=-45.3 * u.mV, A_LTD=14.0e-5, A_LTP=8.0e-5, tau_u_bar_minus=10.0 * u.ms,
81
+ tau_u_bar_plus=7.0 * u.ms, delay_u_bars=DELAY_UBARS * u.ms, a=4.0 * u.nS,
82
+ b=0.0805 * u.pA, V_reset=-49.6 * u.mV, V_clamp=33.0 * u.mV, t_clamp=2.0 * u.ms,
83
+ t_ref=0.0 * u.ms, I_e=0.0 * u.pA,
84
+ V_initializer=braintools.init.Constant(-70.6 * u.mV))
85
+
86
+
87
+ def pairing_weight(s_pre, s_post):
88
+ """Final ``clopath_synapse`` weight (mV) after the canonical pairing protocol.
89
+
90
+ Builds a single ``clopath_synapse`` edge onto an ``aeif_psc_delta_clopath`` post,
91
+ clamps the post with an 80 mV ``spike_generator`` at the postsynaptic times, and
92
+ reads the final stored weight with ``res.weight_trace``.
93
+ """
94
+ sim = Simulator(dt=DT * u.ms)
95
+ post = clopath_neuron(sim)
96
+ sg_pre = sim.create(spike_generator, spike_times=np.asarray(s_pre) * u.ms)
97
+ sg_post = sim.create(spike_generator, spike_times=np.asarray(s_post) * u.ms)
98
+ sim.connect(sg_post, post, synapse=static_synapse(weight=DRIVE_W * u.mV),
99
+ delay=RELAY_D * u.ms)
100
+ proj = sim.connect(sg_pre, post, synapse=clopath_synapse(weight=INIT_W * u.mV),
101
+ delay=RELAY_D * u.ms)
102
+ sim.record_weight(proj)
103
+ res = sim.simulate((10.0 + max(s_pre[-1], s_post[-1])) * u.ms)
104
+ return float(u.get_mantissa(res.weight_trace(proj))[-1, 0])
105
+
106
+
107
+ def normalized_weight_change(weights, init_w=INIT_W):
108
+ """Normalise a final weight to the upstream's percent-of-baseline scale.
109
+
110
+ The NEST example reports ``100 * 15 * (w - init) / init + 100`` so the
111
+ no-change baseline maps to ``100 %``.
112
+
113
+ Parameters
114
+ ----------
115
+ weights : array_like
116
+ Final Clopath weights (mV).
117
+ init_w : float, optional
118
+ Initial weight (mV). Default :data:`INIT_W` (``0.5``).
119
+
120
+ Returns
121
+ -------
122
+ numpy.ndarray
123
+ Normalised weight change in percent.
124
+ """
125
+ return 100.0 * 15.0 * (np.asarray(weights) - init_w) / init_w + 100.0
126
+
127
+
128
+ def run():
129
+ """Run the 10 canonical pairing trains on the ``Simulator`` API.
130
+
131
+ Returns
132
+ -------
133
+ rho : numpy.ndarray
134
+ Pairing frequencies (Hz), :data:`RHO`.
135
+ post_pre : numpy.ndarray
136
+ Normalised weight change for the post-before-pre trains (:data:`LTD_TRAINS`).
137
+ pre_post : numpy.ndarray
138
+ Normalised weight change for the pre-before-post trains (:data:`LTP_TRAINS`).
139
+ weights : numpy.ndarray
140
+ Raw final Clopath weights (mV) for all 10 trains, in train-index order.
141
+ """
142
+ brainstate.environ.set(dt=DT * u.ms)
143
+ weights = np.array([pairing_weight(sp, sq)
144
+ for sp, sq in zip(SPIKE_TIMES_PRE, SPIKE_TIMES_POST)])
145
+ post_pre = normalized_weight_change(weights[list(LTD_TRAINS)])
146
+ pre_post = normalized_weight_change(weights[list(LTP_TRAINS)])
147
+ return RHO, post_pre, pre_post, weights
148
+
149
+
150
+ def main():
151
+ rho, post_pre, pre_post, weights = run()
152
+ print("Clopath spike-pairing (brainpy.state, aeif_psc_delta_clopath, w in mV)")
153
+ for r, a, b in zip(rho, post_pre, pre_post):
154
+ print(f" {r:4.0f} Hz: post-pre {a:7.2f} % pre-post {b:7.2f} %")
155
+
156
+ try:
157
+ import matplotlib.pyplot as plt
158
+ plt.figure(figsize=(6, 4))
159
+ plt.plot(rho, post_pre, "g.-", label="post-before-pre")
160
+ plt.plot(rho, pre_post, "b.-", label="pre-before-post")
161
+ plt.xlabel("rho (Hz)"); plt.ylabel("normalized weight change (%)")
162
+ plt.title("Clopath synapse -- spike pairing")
163
+ plt.legend(); plt.tight_layout()
164
+ plt.savefig("examples/nest_like/clopath_synapse_spike_pairing.png", dpi=100)
165
+ print(" wrote examples/nest_like/clopath_synapse_spike_pairing.png")
166
+ except ImportError:
167
+ print(" (matplotlib not installed; skipping plot)")
168
+
169
+
170
+ if __name__ == "__main__":
171
+ main()