brainx-skill 1.0.14 → 1.0.16

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 (171) hide show
  1. package/README.md +17 -1
  2. package/manifest.json +1 -1
  3. package/mcp-servers/codex/skills.json +1 -1
  4. package/package.json +1 -1
  5. package/skills/bio-neuro-lit/SKILL.md +4 -2
  6. package/skills/bio-neuro-lit/references/required-supplements.md +27 -0
  7. package/skills/brainx-acceleration/SKILL.md +30 -437
  8. package/skills/brainx-acceleration/references/audit-and-rewrite-patterns.md +326 -0
  9. package/skills/brainx-general-guard/SKILL.md +24 -8
  10. package/skills/brainx-install/SKILL.md +3 -3
  11. package/skills/brainx-install/references/compatibility-and-release-matching.md +28 -20
  12. package/skills/brainx-install/references/uninstall-and-cleanup.md +11 -4
  13. package/skills/brainx-modeling-loop/SKILL.md +143 -36
  14. package/skills/brainx-modeling-loop/agents/openai.yaml +2 -2
  15. package/skills/brainx-modeling-loop/references/mechanism-comparison.md +62 -0
  16. package/skills/brainx-modeling-loop/references/multiscale-coupling.md +16 -0
  17. package/skills/brainx-modeling-loop/references/paper-reproduction.md +42 -0
  18. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +14 -14
  19. package/skills/brainx-modeling-loop/references/run-experiment.md +1 -1
  20. package/skills/brainx-modeling-loop/references/training-workflow.md +10 -8
  21. package/skills/brainx-visualization/SKILL.md +6 -2
  22. package/skills/brainx-visualization/references/neural-data-visualization.md +1 -1
  23. package/skills/brainx-visualization/references/statistical-and-model-visualization.md +1 -1
  24. package/skills/package-skills/braincell/SKILL.md +23 -14
  25. package/skills/package-skills/braincell/references/braintools/input-current.md +1 -1
  26. package/skills/package-skills/braincell/references/braintools/metric.md +72 -46
  27. package/skills/package-skills/braincell/references/mixions-for-adaptation.md +1 -1
  28. package/skills/package-skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +1 -1
  29. package/skills/package-skills/braincell/references/multicompartment/cv-policy-reference.md +1 -1
  30. package/skills/package-skills/braincell/references/multicompartment/filter-function-library.md +3 -3
  31. package/skills/package-skills/braincell/references/multicompartment/morphology-io-loading-validation.md +1 -1
  32. package/skills/package-skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +31 -43
  33. package/skills/package-skills/braincell/references/multicompartment/network-workflow.md +49 -0
  34. package/skills/package-skills/braincell/references/multicompartment/probe-reference.md +26 -114
  35. package/skills/package-skills/braincell/references/multicompartment/topology-building-and-visualization.md +40 -28
  36. package/skills/package-skills/braincell/references/scripts/cell_multicompartment_reference.py +13 -17
  37. package/skills/package-skills/brainevent/SKILL.md +0 -3
  38. package/skills/package-skills/brainevent/references/synaptic-plasticity.md +1 -1
  39. package/skills/package-skills/brainmass/SKILL.md +5 -3
  40. package/skills/package-skills/brainmass/references/brainstate/parameter-constraints-regularization.md +9 -7
  41. package/skills/package-skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
  42. package/skills/package-skills/brainmass/references/braintools/data-preprocessing.md +15 -7
  43. package/skills/package-skills/brainmass/references/braintools/metric.md +72 -46
  44. package/skills/package-skills/brainmass/references/coupling-network-api.md +3 -1
  45. package/skills/package-skills/brainmass/references/fitting-with-objectives-api.md +6 -6
  46. package/skills/package-skills/brainmass/references/horn-task-training.md +9 -9
  47. package/skills/package-skills/brainmass/references/modellibrary.md +12 -10
  48. package/skills/package-skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +5 -3
  49. package/skills/package-skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +10 -6
  50. package/skills/package-skills/brainmass/references/simulator-input-monitor-api.md +3 -1
  51. package/skills/package-skills/brainmass/references/visualization-analysis-api.md +17 -9
  52. package/skills/package-skills/brainspike/SKILL.md +201 -0
  53. package/skills/package-skills/brainspike/references/braintools/connectivity.md +40 -0
  54. package/skills/package-skills/brainspike/references/braintools/data-preprocessing.md +39 -0
  55. package/skills/package-skills/brainspike/references/braintools/input-current.md +55 -0
  56. package/skills/package-skills/brainspike/references/braintools/metric.md +36 -0
  57. package/skills/package-skills/brainspike/references/braintools/optimizer.md +50 -0
  58. package/skills/package-skills/brainspike/references/braintools/parameter-initializer.md +43 -0
  59. package/skills/package-skills/brainspike/references/braintools/surrogate.md +40 -0
  60. package/skills/package-skills/brainspike/references/migration-boundary.md +38 -0
  61. package/skills/package-skills/brainspike/references/model-and-readout-selection.md +41 -0
  62. package/skills/package-skills/brainspike/references/multirate-coupling.md +31 -0
  63. package/skills/package-skills/brainspike/references/multiscale-composition.md +28 -0
  64. package/skills/package-skills/brainspike/references/native-composition.md +52 -0
  65. package/skills/package-skills/brainspike/references/native-delays.md +34 -0
  66. package/skills/package-skills/brainspike/references/native-projections.md +43 -0
  67. package/skills/package-skills/brainspike/references/native-training.md +36 -0
  68. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/devices.md +33 -33
  69. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/divergence-and-parity.md +15 -15
  70. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/integration-categories.md +1 -1
  71. package/skills/package-skills/brainspike/references/nest-compatible/model-library.md +200 -0
  72. package/skills/package-skills/brainspike/references/nest-compatible/network-building.md +276 -0
  73. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brette_et_al_2007.py +23 -26
  74. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_alpha.py +18 -21
  75. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_delta.py +16 -19
  76. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +11 -12
  77. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +10 -11
  78. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/spatial_gaussex.py +18 -18
  79. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/synapsecollection.py +26 -29
  80. package/skills/package-skills/brainspike/references/nest-compatible/synapse-and-connectivity.md +166 -0
  81. package/skills/package-skills/brainspike/references/nest-delay-boundaries.md +31 -0
  82. package/skills/package-skills/brainspike/references/nonlinear-state-sharing.md +26 -0
  83. package/skills/package-skills/{brainpy-state → brainspike}/references/perturbation-experiment-validity.md +2 -2
  84. package/skills/package-skills/brainspike/references/simulator-training.md +61 -0
  85. package/skills/package-skills/brainspike/references/temporal-task-training.md +36 -0
  86. package/skills/package-skills/brainspike/scripts/advanced_native_patterns.py +76 -0
  87. package/skills/package-skills/brainspike/scripts/delay_workflow.py +44 -0
  88. package/skills/package-skills/brainspike/scripts/delayed_cue_training.py +78 -0
  89. package/skills/package-skills/brainspike/scripts/lif_smoke.py +31 -0
  90. package/skills/package-skills/brainspike/scripts/multiscale_workflow.py +35 -0
  91. package/skills/package-skills/brainspike/scripts/native_ei_network.py +47 -0
  92. package/skills/package-skills/brainspike/scripts/native_workflows.py +77 -0
  93. package/skills/package-skills/brainspike/scripts/nest_boundary_workflows.py +108 -0
  94. package/skills/package-skills/brainspike/scripts/train_native_snn.py +65 -0
  95. package/skills/package-skills/brainspike/scripts/train_nest_simulator.py +69 -0
  96. package/skills/package-skills/brainspike/scripts/train_nest_simulator_two_weights.py +220 -0
  97. package/skills/package-skills/brainstate/SKILL.md +16 -21
  98. package/skills/package-skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +1 -138
  99. package/skills/package-skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +1 -1
  100. package/skills/package-skills/brainstate/references/brainstate/delay-buffers.md +45 -0
  101. package/skills/package-skills/brainstate/references/brainstate/parameter-constraints-regularization.md +9 -7
  102. package/skills/package-skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
  103. package/skills/package-skills/brainstate/references/brainstate/randomness-and-reproducibility.md +6 -4
  104. package/skills/package-skills/brainstate/references/brainstate/transformation-grad-expansion.md +4 -4
  105. package/skills/package-skills/brainstate/references/brainstate/transformation-vmap-expansion.md +1 -1
  106. package/skills/package-skills/brainstate/references/braintools-optimizer-reference.md +16 -0
  107. package/skills/package-skills/brainstate/references/libraries/prebuilt-layer-library.md +1 -1
  108. package/skills/package-skills/brainstate/references/simulation-environment.md +5 -5
  109. package/skills/package-skills/braintrace/SKILL.md +17 -38
  110. package/skills/package-skills/braintrace/references/Drtrl.md +9 -26
  111. package/skills/package-skills/braintrace/references/algorithm selection.md +7 -12
  112. package/skills/package-skills/braintrace/references/batching.md +15 -35
  113. package/skills/package-skills/braintrace/references/compiler_internal.md +1 -1
  114. package/skills/package-skills/braintrace/references/custom algorithms.md +1 -2
  115. package/skills/package-skills/braintrace/references/customizing_primitive_transforms.md +26 -15
  116. package/skills/package-skills/braintrace/references/pp_pprop workflow.md +5 -139
  117. package/skills/package-skills/brainunit/SKILL.md +7 -2
  118. package/skills/package-skills/brainunit/references/array-mechanics/functional-structural-api.md +1 -1
  119. package/skills/package-skills/brainunit/references/math-function-library.md +2 -2
  120. package/skills/package-skills/brainunit/references/typing-and-runtime-validation.md +5 -2
  121. package/skills/package-skills/brainevent/references/scripts/102_EI_net_1996.py +0 -107
  122. package/skills/package-skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +0 -168
  123. package/skills/package-skills/brainevent/references/scripts/coba_ei_teaching.py +0 -356
  124. package/skills/package-skills/brainpy-state/SKILL.md +0 -247
  125. package/skills/package-skills/brainpy-state/references/array-creation.md +0 -158
  126. package/skills/package-skills/brainpy-state/references/brain-dynamics-delay-protocol.md +0 -147
  127. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/analysis.md +0 -150
  128. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/brainpy legacy workflow.md +0 -373
  129. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/built-in dynamic neuron model.md +0 -150
  130. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/connecting neurons.md +0 -175
  131. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/customize neuron and synpase.md +0 -286
  132. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Input generation.md +0 -111
  133. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/More about simulation.md +0 -163
  134. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +0 -113
  135. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +0 -136
  136. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +0 -222
  137. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +0 -123
  138. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/delays.md +0 -107
  139. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +0 -185
  140. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/integrators.md +0 -181
  141. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/route activity through connectivity.md +0 -102
  142. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synaptic projections.md +0 -147
  143. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synpase properties.md +0 -159
  144. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/loss library.md +0 -127
  145. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/optimizers.md +0 -167
  146. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/parameter initializers.md +0 -107
  147. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/prebuilt neural network layers.md +0 -186
  148. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/surrogate gradients.md +0 -104
  149. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainer library.md +0 -89
  150. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md +0 -253
  151. package/skills/package-skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +0 -334
  152. package/skills/package-skills/brainpy-state/references/braintools/connectivity.md +0 -206
  153. package/skills/package-skills/brainpy-state/references/braintools/data-preprocessing.md +0 -79
  154. package/skills/package-skills/brainpy-state/references/braintools/input-current.md +0 -199
  155. package/skills/package-skills/brainpy-state/references/braintools/metric.md +0 -152
  156. package/skills/package-skills/brainpy-state/references/braintools/optimizer.md +0 -179
  157. package/skills/package-skills/brainpy-state/references/braintools/parameter-initializer.md +0 -183
  158. package/skills/package-skills/brainpy-state/references/braintools/surrogate.md +0 -147
  159. package/skills/package-skills/brainpy-state/references/component-selection.md +0 -288
  160. package/skills/package-skills/brainpy-state/references/nest-compatible/model-library.md +0 -200
  161. package/skills/package-skills/brainpy-state/references/nest-compatible/nest-workflow.md +0 -156
  162. package/skills/package-skills/brainpy-state/references/nest-compatible/network-building.md +0 -264
  163. package/skills/package-skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +0 -153
  164. package/skills/package-skills/brainpy-state/references/projection-patterns.md +0 -127
  165. package/skills/package-skills/brainpy-state/references/scripts/103_COBA_2005.py +0 -86
  166. package/skills/package-skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +0 -181
  167. package/skills/package-skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +0 -156
  168. package/skills/package-skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +0 -111
  169. package/skills/package-skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +0 -221
  170. package/skills/package-skills/brainpy-state/references/scripts/sound_localization.py +0 -240
  171. package/skills/package-skills/brainpy-state/references/scripts/training-snn.py +0 -119
@@ -1,6 +1,6 @@
1
1
  # BrainMass model library
2
2
 
3
- Use this reference when selecting a public BrainMass model, comparing dynamical cost, identifying its primary observable, or distinguishing variants with similar names. Return to `skills/package-skills/brainmass/SKILL.md` after selection for the canonical `Simulator` workflow.
3
+ Use this reference when selecting a public BrainMass model, comparing dynamical cost, identifying its primary observable, or distinguishing variants with similar names. Return to `SKILL.md` after selection for the canonical `Simulator` workflow.
4
4
 
5
5
  ## Inspect the public catalogue
6
6
 
@@ -81,7 +81,9 @@ Match the intervention to the model's equations; similarly named inhibitory para
81
81
  | API | Description |
82
82
  |---|---|
83
83
  | `JansenRitStep(Ai=...)` | Use for inhibitory postsynaptic gain in an alpha/EEG cortical column; `Ai` is measured in mV and scales the inhibitory-population filter, so lowering it weakens the inhibitory postsynaptic potential represented in `eeg() = E - I`. |
84
- | `WilsonCowanStep(wEI=...)` | Use for inhibitory feedback onto the excitatory rate population; `wEI` is dimensionless I-to-E coupling and enters the excitatory equation subtractively, so lowering it weakens that coupling. |
84
+ | `WilsonCowanStep(wIE=...)` | Use for inhibitory feedback onto the excitatory population in BrainMass `0.1.1` (BrainX `2026.10.25`). Lower `wIE` to weaken the dimensionless, subtractive I→E coupling. `wEI` controls E→I in this release. |
85
+
86
+ Verify the keyword mapping with unequal cross weights before porting a Wilson–Cowan intervention. Compare both derivatives or a short integration step with the intended equations. The published equations and gallery use the opposite keyword convention.
85
87
 
86
88
  Change only the selected inhibitory parameter in a matched causal comparison. Treat defaults and source-documented estimation ranges as context, not as evidence for a chosen intervention magnitude. Label an unsourced, outcome-tuned, or outside-range value as phenomenological and show nearby sensitivity before claiming a robust regime change.
87
89
 
@@ -167,14 +169,14 @@ Open only the script that matches the selected model or scientific regime.
167
169
 
168
170
  | Script | Open when |
169
171
  |---|---|
170
- | `scripts/hopf-bifurcation-single-node.py` | Demonstrating oscillation onset across the Hopf bifurcation or checking settled amplitude against `sqrt(a)`. |
171
- | `scripts/wilson-cowan-ei-dynamics.py` | Simulating E/I population rates, their phase portrait, or an excitatory-drive sweep. |
172
- | `scripts/jansen-rit-eeg-proxy.py` | Simulating the Jansen-Rit EEG proxy, its spectrum, or an input-rate sweep. |
173
- | `scripts/seizure-epileptor-case-study.py` | Comparing healthy and seizure-like Epileptor regimes across epileptogenicity `x0`. |
174
- | `scripts/wong-wang-decision-making.py` | Running stochastic competing-population decisions or estimating a psychometric curve. |
175
- | `scripts/kuramoto-synchronization.py` | Measuring synchronization through the Kuramoto order parameter while varying coupling strength. |
176
- | `scripts/wong-wang-dmf-resting-state.py` | Inspecting resting excitatory rate and gating in the Wong-Wang excitatory-inhibitory dynamic mean-field model. |
177
- | `scripts/linear-baseline-node.py` | Checking integration against the analytical linear decay before diagnosing a more complex model. |
172
+ | `references/scripts/hopf-bifurcation-single-node.py` | Demonstrating oscillation onset across the Hopf bifurcation or checking settled amplitude against `sqrt(a)`. |
173
+ | `references/scripts/wilson-cowan-ei-dynamics.py` | Simulating E/I population rates, their phase portrait, or an excitatory-drive sweep. |
174
+ | `references/scripts/jansen-rit-eeg-proxy.py` | Simulating the Jansen-Rit EEG proxy, its spectrum, or an input-rate sweep. |
175
+ | `references/scripts/seizure-epileptor-case-study.py` | Comparing healthy and seizure-like Epileptor regimes across epileptogenicity `x0`. |
176
+ | `references/scripts/wong-wang-decision-making.py` | Running stochastic competing-population decisions or estimating a psychometric curve. |
177
+ | `references/scripts/kuramoto-synchronization.py` | Measuring synchronization through the Kuramoto order parameter while varying coupling strength. |
178
+ | `references/scripts/wong-wang-dmf-resting-state.py` | Inspecting resting excitatory rate and gating in the Wong-Wang excitatory-inhibitory dynamic mean-field model. |
179
+ | `references/scripts/linear-baseline-node.py` | Checking integration against the analytical linear decay before diagnosing a more complex model. |
178
180
 
179
181
  ## Common selection failures
180
182
 
@@ -4,6 +4,8 @@ https://brainx.chaobrain.com/brainmass/gallery/case_studies/resting_state_meg.ht
4
4
  Converted from the official notebook at upstream commit
5
5
  293eaeb8948474c645208b68c531b7cb5482d4fb. Notebook outputs are omitted and
6
6
  ``%matplotlib inline`` remains commented; code and Markdown cells are preserved.
7
+
8
+ Requires BrainTools 0.4.0 or newer for functional-connectivity analysis.
7
9
  """
8
10
 
9
11
  # %% tags=["remove-cell"]
@@ -11,7 +13,7 @@ Converted from the official notebook at upstream commit
11
13
  # %matplotlib inline
12
14
  import brainmass
13
15
  import brainstate
14
- import braintools
16
+ from braintools.analysis.population import functional_connectivity
15
17
  import brainunit as u
16
18
  import jax
17
19
  import jax.numpy as jnp
@@ -209,8 +211,8 @@ target_res = brainmass.Simulator(target_net, dt=0.1 * u.ms).run(
209
211
  target_activity = target_res['output']
210
212
 
211
213
  # --- 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
+ fc_sim = functional_connectivity(u.get_magnitude(activity))
215
+ fc_tar = functional_connectivity(u.get_magnitude(target_activity))
214
216
 
215
217
  # (1) Structure-function coupling: does the simulated FC reflect the connectome?
216
218
  triu = np.triu_indices(N, k=1)
@@ -1,9 +1,9 @@
1
- """Reference script mirrored from:
1
+ """Reference script adapted from:
2
2
  https://brainx.chaobrain.com/brainmass/gallery/model_zoo/wilson_cowan.html
3
3
 
4
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.
5
+ 293eaeb8948474c645208b68c531b7cb5482d4fb. The cross-population weights use
6
+ BrainMass 0.1.1 keyword names while preserving the notebook's directional gains.
7
7
  """
8
8
 
9
9
  # %% tags=["remove-cell"]
@@ -22,7 +22,11 @@ brainstate.environ.set(dt=0.1 * u.ms)
22
22
  #
23
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
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).$$
25
+ # $$\tau_E\dot r_E = -r_E + (1-r\,r_E) S_E(w_{EE} r_E - w_{IE} r_I + I_E),$$
26
+ # $$\tau_I\dot r_I = -r_I + (1-r\,r_I) S_I(w_{EI} r_E - w_{II} r_I + I_I).$$
27
+ #
28
+ # In BrainMass 0.1.1, WilsonCowanStep uses source-to-target subscripts.
29
+ # Its refractory coefficient r defaults to 1.
26
30
  #
27
31
  # 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
32
  #
@@ -36,7 +40,7 @@ brainstate.environ.set(dt=0.1 * u.ms)
36
40
  # %%
37
41
  node = brainmass.WilsonCowanStep(
38
42
  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)
43
+ wEE=16.0, wEI=15.0, wIE=12.0, wII=3.0)
40
44
  node
41
45
 
42
46
  # %% [markdown]
@@ -75,7 +79,7 @@ fig, ax = plt.subplots(figsize=(8, 4))
75
79
  for drive in [0.0, 1.0, 2.5]:
76
80
  m = brainmass.WilsonCowanStep(
77
81
  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)
82
+ wEE=16.0, wEI=15.0, wIE=12.0, wII=3.0)
79
83
  r = brainmass.Simulator(m, dt=0.1 * u.ms).run(
80
84
  300. * u.ms, inputs=lambda i, t, d=drive: (d, 0.0),
81
85
  monitors=['rE'], transient=50. * u.ms)
@@ -8,9 +8,11 @@ Use this reference when a BrainMass run needs driven inputs, custom observables,
8
8
 
9
9
  | API | Description |
10
10
  |---|---|
11
- | `brainmass.Simulator(model, dt=...)` | Use to bind a model or `Network` to an integration step for the standard run path. |
11
+ | `brainmass.Simulator(model, dt=...)` | Use to bind any `brainstate.nn.Module` model or `Network` to an integration step for the standard run path. |
12
12
  | `Simulator.run(duration, *, inputs=None, monitors=None, transient=None, sample_every=None, batch_size=None, init_states=True, jit=True)` | Use to execute a duration and return a dict of time-major monitored values plus unit-aware `ts`. It initializes State and JIT-compiles by default. |
13
13
 
14
+ `model` may be any `brainstate.nn.Module`, including a custom aggregate model you define. A model missing from the public catalogue does not justify rebuilding the initializer, time loop, or monitors.
15
+
14
16
  Do not manually derive the number of steps, initialize State, scope `dt`, build a transformed loop, downsample, or reconstruct timestamps when these controls express the run.
15
17
 
16
18
  ## Supply model inputs
@@ -1,6 +1,6 @@
1
1
  # Visualization and analysis
2
2
 
3
- Use this reference when plotting BrainMass results or computing time-series, functional-connectivity, functional-connectivity-dynamics, and spectral summaries. Keep scientific metric computation in Braintools and use `brainmass.viz` as the thin optional plotting layer.
3
+ Use this reference when plotting BrainMass results or computing sample-by-signal Pearson similarity, time-series, functional-connectivity, functional-connectivity-dynamics, and spectral summaries. Keep scientific metric computation in Braintools and use `brainmass.viz` as the thin optional plotting layer.
4
4
 
5
5
  ## Plot results
6
6
 
@@ -18,16 +18,23 @@ Every helper accepts `ax=` and returns the `matplotlib.axes.Axes` it drew on. Pa
18
18
 
19
19
  ## Compute standard summaries
20
20
 
21
+ The FC, FCD, and PSD examples require BrainTools 0.4.0 or newer and use
22
+ `braintools.analysis`.
23
+
21
24
  Strip units explicitly before a metric that operates on scale-free raw arrays. Keep the sampling interval and labels separately.
22
25
 
23
26
  | API | Description |
24
27
  |---|---|
25
- | `braintools.metric.functional_connectivity(signal)` | Compute pairwise correlation across regions from a `(time, regions)` trajectory. |
26
- | `braintools.metric.functional_connectivity_dynamics(signal, window_size, step_size)` | Slide an FC window and correlate windowed FC matrices to return an `(n_window, n_window)` FCD matrix. |
27
- | `braintools.metric.power_spectral_density(signal, dt, nperseg=None, noverlap=None, freq_range=None)` | Use for a one-sided Welch PSD of a `(time,)` or `(time, channels)` signal; pass `dt` as a time `Quantity` or a float in seconds, and it returns frequencies in Hz plus PSD shaped `(frequency,)` or `(frequency, channels)`. |
28
+ | `braintools.analysis.population.functional_connectivity(activities)` | Compute the square pairwise Pearson matrix across columns of a `(time, signals)` array; check axes and undefined values before use. |
29
+ | `braintools.analysis.population.functional_connectivity_dynamics(activities, window_size=30, step_size=5)` | Correlate windowed FC matrices to return an `(n_window, n_window)` FCD matrix; specify the window and step in recorded samples. |
30
+ | `braintools.analysis.spectral.power_spectral_density(lfp, dt, nperseg=None, noverlap=None, freq_range=None)` | Use for a one-sided Welch PSD of a `(time,)` or `(time, channels)` signal; pass `dt` as a time `Quantity` or a float in seconds, and it returns frequencies in Hz plus PSD shaped `(frequency,)` or `(frequency, channels)`. |
28
31
  | `brainmass.objectives.fc_corr()` | Score correlation between prediction and target FC without manually recomputing the comparison logic. |
29
32
  | `brainmass.objectives.fcd_distribution(fcd_matrix, ...)` | Estimate the off-diagonal FCD value distribution used by distributional FCD objectives. |
30
33
 
34
+ For columnwise Pearson similarity over other observations, such as stimulus responses, evaluate this same API before writing a generic correlation implementation. This extends the documented time-series layout algebraically: verify the required centering, precision and reduction axis, and label the result by its actual observable rather than implying temporal or causal connectivity. A host-side data-generation boundary does not by itself exclude an applicable BrainTools metric.
35
+
36
+ Check finite inputs and positive column variances before correlation when undefined Pearson values must remain undefined. In BrainTools 0.4.0, a constant column returned zeros off the diagonal and one on the diagonal in a CPU probe. Reject invalid columns or preserve an explicit validity mask under the scientific missing-value policy. Verify parity on a small witness before substituting the API into a source-defined analysis. See the [official Pearson matrix contract](https://brainx.chaobrain.com/braintools/apis/generated/braintools.analysis.population.functional_connectivity.html) for shapes and NaN handling.
37
+
31
38
  ## Canonical analysis workflow
32
39
 
33
40
  ```python
@@ -70,8 +77,8 @@ result = brainmass.Simulator(network, dt=dt).run(
70
77
  )
71
78
 
72
79
  signal = u.get_magnitude(result["output"])
73
- fc = braintools.metric.functional_connectivity(signal)
74
- fcd = braintools.metric.functional_connectivity_dynamics(
80
+ fc = braintools.analysis.population.functional_connectivity(signal)
81
+ fcd = braintools.analysis.population.functional_connectivity_dynamics(
75
82
  signal,
76
83
  window_size=100,
77
84
  step_size=20,
@@ -104,7 +111,7 @@ Use one channel at a time unless the metric explicitly accepts multichannel inpu
104
111
 
105
112
  ```python
106
113
  record_dt = result["ts"][1] - result["ts"][0]
107
- frequencies, power = braintools.metric.power_spectral_density(
114
+ frequencies, power = braintools.analysis.spectral.power_spectral_density(
108
115
  signal[:, 0],
109
116
  record_dt,
110
117
  )
@@ -126,5 +133,6 @@ Freeze a signal-amplitude or in-band-power floor before inspecting condition out
126
133
 
127
134
  ## Official sources
128
135
 
129
- - `https://brainx.chaobrain.com/brainmass/reference/viz.html`
130
- - `https://brainx.chaobrain.com/brainmass/howto/analyze_results.html`
136
+ - [BrainTools analysis API](https://brainx.chaobrain.com/braintools/apis/analysis.html)
137
+ - [BrainMass visualization API](https://brainx.chaobrain.com/brainmass/reference/viz.html)
138
+ - [BrainMass results analysis guide](https://brainx.chaobrain.com/brainmass/howto/analyze_results.html)
@@ -0,0 +1,201 @@
1
+ ---
2
+ name: brainspike
3
+ description: Use for point-neuron modeling, spiking networks, synapses, plasticity, devices, spatial connectivity, and PyNEST migration. Use as the sole point-neuron skill with BrainCell or BrainMass in multiscale tasks; use public Neuron/Synapse composition for custom dynamics, gradient training, and cross-package coupling.
4
+ ---
5
+
6
+ # BrainSpike
7
+
8
+ ## Purpose and boundary
9
+
10
+ Use this skill for point-neuron networks through either the NEST-compatible `Simulator` or a native graph built from public `brainspike.Neuron` and `Synapse` bases. Use the Simulator for NEST-named models, devices, and the verified continuous-voltage fitting path; use native composition for custom equations, surrogate-gradient recurrent training, and cross-package coupling.
11
+
12
+ The examples target BrainSpikes `0.2.0` (import `brainspike`), bundled with
13
+ BrainX `2026.10.25`. Use the original skill snapshot for experiments frozen
14
+ on the older `brainpy.state` NEST API.
15
+
16
+ Enable 64-bit JAX before creating a `Simulator`, for example
17
+ `jax.config.update("jax_enable_x64", True)` or
18
+ `brainstate.environ.set(precision=64)`. With 32-bit JAX, the default
19
+ `poisson_generator` stop sentinel overflows its int64 comparison and simulation
20
+ fails during tracing. The bundled NEST-compatible scripts set this at import.
21
+
22
+ Canonical path:
23
+
24
+ `create Simulator -> create nodes and devices -> connect sources, populations, and recorders -> simulate -> read SimulationResult`
25
+
26
+ Keep each NEST-compatible graph under its Simulator. For native composition, construct a BrainState Module graph, initialize hidden State, reset independent rollouts, and execute State-aware transforms. Open `references/simulator-training.md` for direct NEST Simulator voltage-objective training, `references/native-composition.md` for custom neurons and synapses, `references/native-training.md` for BPTT or pp-prop, and `references/multiscale-composition.md` for cellular/regional exchange. These public-base workflows do not require the private unified kernel.
27
+
28
+
29
+ ## Underlying mental model
30
+
31
+ For the NEST path, use one explicit `Simulator` instead of PyNEST's global kernel; it owns creation, connectivity, rollout State, recording, and results. Preserve NEST names with BrainUnit quantities, while connection rules select edges, synapse specs define edge behavior, and source/observer roles determine device direction.
32
+
33
+ ### API structure
34
+
35
+ | API family | Use |
36
+ |---|---|
37
+ | `brainspike.Simulator` | Own node creation, connection construction, simulation lifecycle, and result collection. |
38
+ | `brainspike` NEST models | Select NEST-compatible neurons, synapses, plasticity rules, generators, recorders, and detectors by NEST-style name. |
39
+ | `brainspike.Neuron`, `brainspike.Synapse` | Define native dynamics with explicit hidden State and compose them in BrainState Modules. |
40
+ | `brainstate.transform` | Execute and differentiate native Module graphs; the Simulator owns its own rollout. |
41
+ | `brainspike.spatial` | Place populations in 2-D or 3-D space and construct distance-dependent kernels, masks, and connection rules. |
42
+ | `brainunit` | Supply physical time, voltage, current, conductance, capacitance, rate, weight, and delay quantities. |
43
+
44
+ ### Create the simulator and nodes
45
+
46
+ Create every population and device through one `Simulator`; each `create()` call returns a `NodeView` that preserves population identity while supporting concatenation and slicing.
47
+
48
+ | API | Description |
49
+ |---|---|
50
+ | `brainspike.Simulator(dt=...)` | Use to start an independent NEST-compatible network; it owns the timestep, graph, rollout, and results. |
51
+ | `sim.create(model, size=1, *, params=None, positions=None, **kwargs)` | Use for neurons and devices; it instantiates the selected NEST-compatible model and returns a `NodeView`. Pass a large parameter set with `params=dict(...)` or individual parameters as keywords. |
52
+ | `left + right` | Use to concatenate `NodeView` objects while preserving their segment boundaries; the result can be passed to one `connect()` call. |
53
+ | `view[slice]` | Use to select a subset of a single population for connectivity or recording without creating another population. |
54
+
55
+ ```python
56
+ import brainstate
57
+ import brainunit as u
58
+ import brainspike
59
+
60
+ brainstate.environ.set(precision=64)
61
+
62
+ sim = brainspike.Simulator(dt=0.1 * u.ms)
63
+ neurons = sim.create(
64
+ brainspike.iaf_psc_alpha,
65
+ 100,
66
+ params={"I_e": 350.0 * u.pA},
67
+ )
68
+ sample = neurons[:5]
69
+ ```
70
+
71
+ Open `references/braintools/parameter-initializer.md` when choosing initial voltages or weight distributions. Open `references/braintools/input-current.md` when a timed stimulation protocol must enter a neuron or NEST device.
72
+
73
+ Open `references/nest-compatible/model-library.md` when choosing a neuron family or exact NEST-compatible model name. Open `references/nest-compatible/network-building.md` when composing multi-segment `NodeView` objects or spatial placement.
74
+
75
+ ### Connect populations and devices
76
+
77
+ Connect source to target with a connection rule plus a unitful synapse spec, and reverse the call only for analog recorders that observe a population.
78
+
79
+ | API | Description |
80
+ |---|---|
81
+ | `sim.connect(pre, post, *, rule=..., weight=..., delay=..., ...)` | Use to build a projection, attach a source device, or register a recorder tap; it returns projection handles for realized projections and `None` for recorder taps or current injectors. |
82
+ | `brainspike.all_to_all` | Use when every source must connect to every target; this is the default generator fan-out rule. |
83
+ | `brainspike.fixed_indegree(k)` | Use when every target must draw exactly `k` presynaptic edges; set `seed` for reproducible BrainSpike wiring and `comm="sparse"` for large event fan-in. |
84
+ | `synapse=brainspike.<synapse_model>(...)` | Use when the edge is plastic or needs behavior beyond static weight and delay; keep rule parameters on the synapse spec. |
85
+ | `sim.connect(generator, neuron)` | Use for current and spike sources; generators drive their targets. |
86
+ | `sim.connect(neuron, spike_recorder)` | Use to tap emitted spikes. |
87
+ | `sim.connect(multimeter, neuron)` | Use for analog observation; `multimeter` follows NEST's reversed recorder direction. |
88
+
89
+ ```python
90
+ drive = sim.create(brainspike.poisson_generator, rate=8000.0 * u.Hz, rng_seed=0)
91
+ spike_recorder = sim.create(brainspike.spike_recorder)
92
+ meter = sim.create(
93
+ brainspike.multimeter,
94
+ record_from=["V_m"],
95
+ interval=0.1 * u.ms,
96
+ )
97
+
98
+ sim.connect(
99
+ drive,
100
+ neurons,
101
+ rule=brainspike.all_to_all,
102
+ weight=10.0 * u.pA,
103
+ delay=1.0 * u.ms,
104
+ )
105
+ sim.connect(neurons, spike_recorder)
106
+ sim.connect(meter, sample)
107
+ ```
108
+
109
+ Do not interchange default and explicit synapse delay paths; open `references/nest-delay-boundaries.md` for supported array shapes and the release-scoped amplitude counterexample.
110
+
111
+ Open `references/nest-compatible/synapse-and-connectivity.md` when selecting a static, special, STP, STDP, or voltage-based synapse; choosing a rule; or inspecting realized edges. Open `references/nest-compatible/devices.md` when selecting a generator, recorder, detector, or result-readback method.
112
+
113
+ ### Simulate and read results
114
+
115
+ `simulate()` starts from freshly initialized State and returns one in-memory `SimulationResult` whose common time axis indexes spike and analog recordings.
116
+
117
+ | API | Description |
118
+ |---|---|
119
+ | `sim.simulate(duration, *, dt=None)` | Use for an independent run from initialized State and time zero; it returns a `SimulationResult`. |
120
+ | `result.times` | Use for the run's common `(n_steps,)` time axis. |
121
+ | `result.spikes(recorder)` | Use for a spike recorder's `(n_steps, n_recorded)` spike matrix. |
122
+ | `result.rate(recorder)` | Use for the mean firing rate in spikes per second over the recorded neurons. |
123
+ | `result.trace(recorder, recordable)` | Use for a multimeter trace in the model State's natural unit; it raises `KeyError` when the recordable was not registered. |
124
+
125
+ ```python
126
+ result = sim.simulate(100.0 * u.ms)
127
+
128
+ spikes = result.spikes(spike_recorder)
129
+ voltage = result.trace(meter, "V_m")
130
+ rate = result.rate(spike_recorder)
131
+
132
+ assert spikes.shape[0] == result.times.shape[0]
133
+ assert voltage.shape[0] == result.times.shape[0]
134
+ ```
135
+
136
+ Open `references/nest-compatible/network-building.md` when continuing State across windows with `cont()`, resetting persistent rollout State, recording plastic weights, inspecting `SynapseCollection`, or selecting spatial primitives.
137
+
138
+ ## Reference routing
139
+
140
+ Open only the smallest reference that owns the decision.
141
+
142
+ | Reference | Open when |
143
+ |---|---|
144
+ | `references/simulator-training.md` | Differentiating NEST Simulator voltage recordings, fitting connection weights/current, or checking hard-spike and outer-JIT limitations |
145
+ | `references/nonlinear-state-sharing.md` | Sharing nonlinear source traces or rejecting invalid target/heterogeneous aggregation |
146
+ | `references/nest-delay-boundaries.md` | Choosing tested delay-array/spec paths, fractional grid transmission, or checking the explicit-spec amplitude anomaly |
147
+ | `references/multirate-coupling.md` | Exchanging held regional signals and conserved window rates on integer-related fine/coarse clocks |
148
+ | `references/model-and-readout-selection.md` | Choosing physiology, synaptic current/conductance meaning, or instantaneous versus dynamic/windowed readouts |
149
+ | `references/native-projections.md` | Building a complete native E/I conductance network and checking communication/filter/current/target order |
150
+ | `references/native-delays.md` | Adding native transmission history and proving event, conductance, and voltage arrival times |
151
+ | `references/temporal-task-training.md` | Training independent batched cue-delay-report trials with masks or checkpointed BPTT |
152
+ | `references/native-composition.md` | Implementing custom point-neuron or synaptic equations, explicit State placement, or native event communication |
153
+ | `references/native-training.md` | Training a native recurrent spiking graph with BPTT, a trainable readout, or BrainTrace pp-prop |
154
+ | `references/multiscale-composition.md` | Exchanging signals between point neurons, detailed cells, and regional models on an explicit clock |
155
+ | `references/braintools/input-current.md` | Generating unit-aware stimulation or choosing native current arrays versus NEST source devices |
156
+ | `references/braintools/parameter-initializer.md` | Initializing membrane State, physical weights, or dimensionless native-layer parameters reproducibly |
157
+ | `references/braintools/metric.md` | Choosing a voltage, classification, spike-timing, or rate metric and its unit/axis reduction |
158
+ | `references/braintools/optimizer.md` | Selecting the registered parameter collection and native versus Simulator optimizer boundary |
159
+ | `references/braintools/surrogate.md` | Choosing and checking the backward spike derivative in the actual training path |
160
+ | `references/braintools/data-preprocessing.md` | Encoding analog features as time-major spikes or a declared current representation |
161
+ | `references/braintools/connectivity.md` | Generating topology beyond native Simulator rules and preserving edge/weight/delay ordering |
162
+ | `references/perturbation-experiment-validity.md` | Calibrating matched point-neuron interventions or validating baseline activity before scaling a causal experiment |
163
+ | `references/migration-boundary.md` | Replacing BrainPy or BrainPy-State, deciding whether their skills or runtime dependencies can be removed, or checking the tested migration scope |
164
+ | `references/nest-compatible/model-library.md` | Selecting or identifying a NEST-compatible neuron family or exact model name, or locating its neuron API entry |
165
+ | `references/nest-compatible/synapse-and-connectivity.md` | Selecting static or special synapses, STP/STDP rules, connection rules, weight/delay specs, or realized-connectivity inspection |
166
+ | `references/nest-compatible/devices.md` | Selecting generators, recorders, detectors, source semantics, connection direction, or result readback |
167
+ | `references/nest-compatible/network-building.md` | Using `Simulator`, `NodeView`, `SimulationResult`, `SynapseCollection`, projection classes, connection-rule helpers, or spatial networks |
168
+ | `references/nest-compatible/divergence-and-parity.md` | Porting NEST code, locating STDP parameters, explaining a mismatch, choosing trace versus distributional validation, or checking documented parity bands |
169
+ | `references/nest-compatible/integration-categories.md` | Determining how a model family is numerically updated and which validation category to consult next |
170
+
171
+ ## Full workflow scripts
172
+
173
+ Use these standalone scripts when the canonical inline workflow is too small for the task. Plotting examples save PNG files in the current working directory. Keep the scripts separate from the Markdown references so their complete source remains directly runnable.
174
+
175
+ | Script | Open when |
176
+ |---|---|
177
+ | `references/nest-compatible/scripts/brunel_alpha.py` | Building an alpha-synapse Brunel network |
178
+ | `references/nest-compatible/scripts/brunel_delta.py` | Checking delta-synapse voltage-weight semantics in a Brunel network |
179
+ | `references/nest-compatible/scripts/brette_et_al_2007.py` | Reproducing the comparative network workflow from Brette et al. (2007) |
180
+ | `references/nest-compatible/scripts/synapsecollection.py` | Inspecting or manipulating realized synapses through `SynapseCollection` |
181
+ | `references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py` | Evaluating short-term plasticity behavior against the Tsodyks2 protocol |
182
+ | `references/nest-compatible/scripts/clopath_synapse_spike_pairing.py` | Running the Clopath voltage-based plasticity spike-pairing protocol |
183
+ | `references/nest-compatible/scripts/spatial_gaussex.py` | Building spatial connectivity with a Gaussian distance-dependent rule |
184
+
185
+ ## Boundaries and common failures
186
+
187
+ - Keep NEST Simulator execution separate from native Module execution; do not assume the two graphs are interchangeable.
188
+ - Native training and custom dynamics use public BrainSpike bases; do not require private kernel APIs or restore retired BrainPy projections.
189
+
190
+
191
+ ## Official sources
192
+
193
+ - https://brainx.chaobrain.com/brainspike/nest-style/models.html
194
+ - https://brainx.chaobrain.com/brainspike/nest-style/connectivity.html
195
+ - https://brainx.chaobrain.com/brainspike/nest-style/devices.html
196
+ - https://brainx.chaobrain.com/brainspike/nest-style/tutorials/03-connect-network.html
197
+ - https://brainx.chaobrain.com/brainspike/apis/nest-network.html
198
+ - https://brainx.chaobrain.com/brainspike/nest-style/divergences/index.html
199
+ - https://brainx.chaobrain.com/brainspike/nest-style/validation-status.html
200
+ - https://brainx.chaobrain.com/brainspike/nest-style/divergences/stdp.html
201
+ - https://brainx.chaobrain.com/brainspike/nest-style/integration-categories.html
@@ -0,0 +1,40 @@
1
+ # Construct BrainSpike connectivity with Braintools
2
+
3
+ Use a Braintools connector when geometry or topology selects neuron pairs beyond the native Simulator rules. Keep pair selection, edge ordering, physical weights/delays, and event representation as separate decisions.
4
+
5
+ ## Choose the connection owner
6
+
7
+ | API | Use |
8
+ |---|---|
9
+ | `brainspike.fixed_indegree(k)` / `pairwise_bernoulli(p)` | Prefer the Simulator's own rule when it already expresses the required network. |
10
+ | `braintools.conn.ExcitatoryInhibitory(...)` | Use when the topology must preserve declared excitatory/inhibitory source roles and associated signed efficacy. |
11
+ | `braintools.conn.DistanceDependent(...)` | Use when explicit positions determine pair selection; verify its required geometry inputs before constructing a spatial network. |
12
+ | `brainspike.explicit_edges(pre_indices, post_indices)` | Import selected pairs into the NEST Simulator; preserve population-local indices and paired edge order. |
13
+
14
+ ## Generate an explicit paired edge list
15
+
16
+ ```python
17
+ import braintools
18
+ import brainunit as u
19
+
20
+ pattern = braintools.conn.ExcitatoryInhibitory(
21
+ exc_ratio=0.8, exc_prob=0.1, inh_prob=0.2,
22
+ exc_weight=1.0*u.pA, inh_weight=-0.8*u.pA,
23
+ )
24
+ connections = pattern(pre_size=20, post_size=10)
25
+ assert connections.shape == (20, 10)
26
+ assert connections.pre_indices.shape == connections.post_indices.shape
27
+ assert connections.weights.shape[0] == connections.n_connections
28
+ ```
29
+
30
+ Keep `pre_indices[i]`, `post_indices[i]`, `weights[i]`, and any `delays[i]` aligned through filtering, sorting, or compression. Preserve a connector seed through the documented interface when exact graph replay is required. Do not assume BrainState's RNG controls every host-side connector.
31
+
32
+ For a NEST graph, pass matching source/target views and an `explicit_edges` rule to `connect()`. Match the target model's weight unit and verify the required per-edge weight/delay form before passing arbitrary connector arrays: the local experiment establishes distinct delays on separate connections, not all per-edge array representations. A signed current weight does not define an inhibitory conductance model; use its receptor/reversal contract when conductance is represented.
33
+
34
+ For native fixed communication, open `brainevent` → `references/sparse-formats.md` to convert the paired edge list into CSR/CSC while preserving edge-value order. Use `references/native-composition.md` for conductance filtering and target update order. Do not replace the trainable ETP-aware projection with an arbitrary binary event operator and assume the same temporal gradients.
35
+
36
+ Open `references/nest-compatible/network-building.md` for Simulator rule, index, and projection semantics, and `references/braintools/parameter-initializer.md` when existing weights need distance modulation rather than new topology.
37
+
38
+ ## Source
39
+
40
+ [BrainTools connectivity API](https://brainx.chaobrain.com/braintools/apis/conn.html). The connector example targets BrainTools 0.4.0.
@@ -0,0 +1,39 @@
1
+ # Encode inputs for BrainSpike
2
+
3
+ Use a spike encoder when the scientific input representation requires binary events. Keep analog current protocols in `references/braintools/input-current.md`; encoding changes the representation and is not a generic normalization step.
4
+
5
+ ## Choose the representation
6
+
7
+ | API | Use |
8
+ |---|---|
9
+ | `braintools.spike.LatencyEncoder(...)` | Use when feature magnitude should determine first-spike timing; set the physical timestep and represented window. |
10
+ | `braintools.spike.PoissonEncoder(...)` | Use when stochastic rate coding is part of the model; declare normalization, rate scale, RNG ownership, and observation window. |
11
+ | `braintools.spike.StepCurrentEncoder(...)` | Use for an analog current code; do not wrap its output as binary events. |
12
+
13
+ ## Preserve the encoded time axis
14
+
15
+ ```python
16
+ import brainstate
17
+ import braintools
18
+ import brainunit as u
19
+
20
+ values = u.math.asarray([0.02, 0.5, 1.0])
21
+ encoder = braintools.spike.LatencyEncoder(method="linear", normalize=True, tau=4*u.ms)
22
+ with brainstate.environ.context(dt=1*u.ms):
23
+ spikes = encoder(values, n_time=5)
24
+ assert spikes.shape == (5, 3)
25
+ assert u.math.argmax(spikes[:, 2]) < u.math.argmax(spikes[:, 1])
26
+ assert u.math.argmax(spikes[:, 1]) < u.math.argmax(spikes[:, 0])
27
+ ```
28
+
29
+ Match the encoder's feature/neuron axis to the receiving projection and keep trials distinct from encoded time. Fix normalization on training data only; do not re-fit it on validation trials. For stochastic encoders, compare empirical rates across repeated windows rather than expecting exact counts in one short sequence.
30
+
31
+ For native graphs, pass each time slice into the declared input layer through the State-aware sequence driver. A dimensionless spike tensor is not a physical current; use the model's explicit projection and current scale. The bundled `RecurrentSNN` has one external feature, so change its input dimension before supplying this three-feature example.
32
+
33
+ For a NEST graph, open `references/nest-compatible/devices.md` to express the desired spike times or generator rates through device APIs. An encoded tensor is not itself a `NodeView`. Verify the event-time/bin convention and initial-time handling before translating bins into a spike generator.
34
+
35
+ Open `references/braintools/metric.md` when evaluating encoded timing or rate accuracy, and `references/braintools/parameter-initializer.md` when the receiving projection requires deliberate weight scaling.
36
+
37
+ ## Source
38
+
39
+ [BrainTools spike encoders](https://brainx.chaobrain.com/braintools/apis/spike.html). Use the BrainTools 0.4 namespace `braintools.spike` and `n_time=`.
@@ -0,0 +1,55 @@
1
+ # Generate point-neuron input currents
2
+
3
+ Use `braintools.input` to construct a physical stimulation protocol once under the model timestep. The generated array is time-major data; the consuming neuron or device determines how it enters the simulation.
4
+
5
+ ## Choose the input boundary
6
+
7
+ | API | Use |
8
+ |---|---|
9
+ | `braintools.input.Constant([(current, duration), ...])` | Use for baseline, pulse, and recovery sections; calling the protocol returns one physical current sample per step. |
10
+ | `braintools.input.Ramp(start, end, duration)` | Use for a continuous current ramp; preserve the same current unit at both endpoints. |
11
+ | `brainstate.transform.for_loop(step, times, current)` | Use for a native rollout; slice time and drive together and advance the neuron once per sample. |
12
+ | `sim.create(brainspike.step_current_generator, ...)` | Use the NEST device path for piecewise current injection; supply the documented change times and amplitudes rather than a native input array. |
13
+
14
+ ## Run a generated protocol through a native neuron
15
+
16
+ This example calls a public BrainSpike neuron directly inside a native State-aware loop. Normalize generated current to `pA` before the transformed loop: this model stores buffered current in `pA`, and changing its unit metadata during a State-aware transform violates the fixed State tree. Its NEST-compatible `update(x=...)` buffers current for the next step; do not assume same-step injection when porting a timing-sensitive protocol.
17
+
18
+ ```python
19
+ import brainspike
20
+ import brainstate
21
+ import braintools
22
+ import brainunit as u
23
+
24
+ with brainstate.environ.context(dt=0.1*u.ms):
25
+ protocol = braintools.input.Constant([
26
+ (0.0*u.nA, 2.0*u.ms),
27
+ (0.8*u.nA, 4.0*u.ms),
28
+ (0.0*u.nA, 2.0*u.ms),
29
+ ])
30
+ current = protocol().in_unit(u.pA)
31
+ neuron = brainspike.iaf_psc_alpha(
32
+ 1, V_initializer=braintools.init.Constant(-65.0*u.mV),
33
+ )
34
+ brainstate.nn.init_all_states(neuron)
35
+ times = u.math.arange(current.shape[0])*brainstate.environ.get_dt()
36
+
37
+ def step(t, drive):
38
+ with brainstate.environ.context(t=t):
39
+ neuron.update(x=drive)
40
+ return neuron.V.value
41
+
42
+ voltage = brainstate.transform.for_loop(step, times, current)
43
+
44
+ assert voltage.shape == (80, 1)
45
+ ```
46
+
47
+ For the custom `LIF` in `scripts/native_workflows.py`, pass each current sample to the neuron call; its update consumes that sample immediately. Keep this distinction in the scientific exchange contract.
48
+
49
+ For a NEST Simulator graph, open `references/nest-compatible/devices.md` for current-generator parameters and connection direction. `simulate()` has no native time-major-input argument; do not pass a generated array as its duration or replace the graph's loop with manual neuron stepping.
50
+
51
+ Open `references/perturbation-experiment-validity.md` when current delivery is an intervention whose actual spike dose must be calibrated. Generate noisy protocols outside the update, declare whether trials reuse or resample them, and regenerate cached inputs when timestep or stochastic realization changes.
52
+
53
+ ## Source
54
+
55
+ [BrainTools input API](https://brainx.chaobrain.com/braintools/apis/input.html). Use BrainTools 0.4.0 in the declared BrainX release; do not infer newer live-documentation APIs.
@@ -0,0 +1,36 @@
1
+ # Select BrainSpike losses and analysis metrics
2
+
3
+ Choose the observable and its time, neuron, and trial axes before reducing a loss. A valid analysis statistic is not automatically a differentiable training objective.
4
+
5
+ ## Match the metric to the task
6
+
7
+ | API | Use |
8
+ |---|---|
9
+ | `braintools.metric.squared_error(predictions, targets, reduction="mean")` | Use for an aligned continuous target and scalar MSE; normalize physical residuals by a declared scale. |
10
+ | `braintools.metric.softmax_cross_entropy_with_integer_labels(logits, labels)` | Use for mutually exclusive classes from a trained readout; validate label range and reduce the returned example losses deliberately. |
11
+ | `braintools.analysis.spike.firing_rate(spikes, width=..., dt=...)` | Use for population-rate analysis; supply physical times and preserve the time-major binary spike matrix. |
12
+ | `braintools.analysis.spike.van_rossum_distance(...)` | Use for spike-time comparison; supply spike-time trains rather than passing a dense matrix as a list of event times. |
13
+
14
+ ## Normalize a voltage objective
15
+
16
+ ```python
17
+ import braintools
18
+ import brainunit as u
19
+
20
+ observed = u.math.asarray([[-65., -64.], [-63., -62.]])*u.mV
21
+ predicted = observed + 1.0*u.mV
22
+ residual = (predicted-observed)/(2.0*u.mV)
23
+ loss = braintools.metric.squared_error(residual, u.math.zeros_like(residual), reduction="mean")
24
+ assert loss.shape == ()
25
+ assert u.math.allclose(loss, 0.25)
26
+ ```
27
+
28
+ Keep the normalization scale fixed across candidates and conditions. Align sampling, transient removal, recording units, trial masks, and reduction axes before comparing traces. Do not let broadcasting silently pool a trial or neuron axis. A scalar mean over all samples implies equal sample weighting; choose a different reduction when the scientific target requires it.
29
+
30
+ For native surrogate-gradient training, use the differentiable model/readout output described in `references/native-training.md`. For the verified NEST Simulator path, use the continuous multimeter trace described in `references/simulator-training.md`: hard recorded spike counts have zero gradient in the tested configuration. Spike timing, rate, and synchrony metrics remain useful for evaluation, but require separate gradient evidence before optimization.
31
+
32
+ Open `references/braintools/optimizer.md` after the scalar objective and reset boundary are fixed. Open `references/perturbation-experiment-validity.md` before interpreting silent populations or intervention-dependent metrics as scientific evidence.
33
+
34
+ ## Sources
35
+
36
+ [BrainTools metric API](https://brainx.chaobrain.com/braintools/apis/metric.html), [analysis API](https://brainx.chaobrain.com/braintools/apis/analysis.html). The local contracts target BrainTools 0.4.0; preserve physical `dt` rather than relying on function-specific bare-time conventions.
@@ -0,0 +1,50 @@
1
+ # Optimize BrainSpike parameters
2
+
3
+ An optimizer owns persistent update State and changes only its registered parameter collection. The simulation owns hidden dynamical State and must start at the declared independence boundary for every loss evaluation.
4
+
5
+ ## Select the update boundary
6
+
7
+ | API | Use |
8
+ |---|---|
9
+ | `model.states(brainstate.ParamState)` | Select native model parameters; exclude membrane, conductance, spike, random, delay, and eligibility State. |
10
+ | `braintools.optim.Adam(lr=...)` | Use as the verified adaptive baseline for native learning or a normalized Simulator candidate. |
11
+ | `optimizer.register_trainable_weights(params)` | Register the collection once, outside temporal loops and repeated optimizer steps. |
12
+ | `brainstate.transform.grad(loss, params, return_value=True)` | Use for a stateful native objective and a matching gradient tree. |
13
+ | `optimizer.update(grads)` | Apply one update at the declared cadence; use the same collection layout as registration. |
14
+
15
+ ## Register and update a normalized candidate
16
+
17
+ This scalar candidate illustrates the optimizer lifecycle. The complete Simulator example maps the candidate to a physical connection weight; the native example selects the model's actual parameter collection.
18
+
19
+ ```python
20
+ import brainstate
21
+ import braintools
22
+ import brainunit as u
23
+
24
+ weight = brainstate.ParamState(u.math.asarray(0.4))
25
+ params = {"weight": weight}
26
+ optimizer = braintools.optim.Adam(lr=0.05)
27
+ optimizer.register_trainable_weights(params)
28
+
29
+ def objective():
30
+ return braintools.metric.squared_error(weight.value, u.math.asarray(1.7), reduction="mean")
31
+
32
+ differentiate = brainstate.transform.grad(objective, params, return_value=True)
33
+ grads, initial_loss = differentiate()
34
+ optimizer.update(grads)
35
+ assert objective() < initial_loss
36
+ ```
37
+
38
+ ## Preserve the selected execution path
39
+
40
+ For native BPTT, reset model runtime State inside the loss and compile the complete reset-gradient-update step. For pp-prop, reset both model and learner State, advance every sequence step, choose gradient reduction explicitly, and update after the sequence. Open `references/native-training.md` and `scripts/train_native_snn.py` for both complete patterns.
41
+
42
+ For direct NEST voltage fitting, keep the candidate outside a locally constructed Simulator, call `simulate()` for each independent objective, and apply the optimizer between evaluations. The verified pure candidate-to-loss boundary uses `jax.value_and_grad`; do not outer-JIT the full multi-spike-generator builder. Open `references/simulator-training.md` and `scripts/train_nest_simulator.py` for the executable boundary and finite-difference check.
43
+
44
+ Do not reuse optimizer State across independent training replicates unless the experiment requires it. Do not re-register weights at every step or reset learned parameters with runtime State. An optimizer change cannot repair a zero-gradient hard spike objective.
45
+
46
+ For a genuinely discontinuous or bounded black-box fitting objective, check the shared BrainTools optimizer tutorials for `ScipyOptimizer` or optional `NevergradOptimizer` before selecting external infrastructure. These wrappers own an objective and do not use the register/update lifecycle. The separately tested `fit_hard_count()` in `scripts/nest_boundary_workflows.py` uses bounded Powell search for a scalar NEST hard-count objective; open `references/simulator-training.md` for its scope. Verify reset independence, parameter units, bounds, plateaus, and optional dependencies before adapting a different objective.
47
+
48
+ ## Sources
49
+
50
+ [BrainTools optimizer API](https://brainx.chaobrain.com/braintools/apis/optim.html), [optimization tutorials](https://brainx.chaobrain.com/braintools/optim/index.html). The canonical lifecycle targets BrainTools 0.4.0.