brainx-skill 1.0.11 → 1.0.13

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 (198) hide show
  1. package/README.md +4 -0
  2. package/installation/lib/bundle.js +51 -13
  3. package/manifest.json +2 -0
  4. package/mcp-servers/codex/README.md +62 -0
  5. package/mcp-servers/codex/UPSTREAM.md +20 -0
  6. package/mcp-servers/codex/server.mjs +140 -0
  7. package/mcp-servers/codex/skills.json +10 -0
  8. package/mcp-servers/codex/system-prompt.md +62 -0
  9. package/mcp-servers/codex/test/fixtures/fake-codex.mjs +6 -0
  10. package/mcp-servers/codex/test/server.test.mjs +88 -0
  11. package/package.json +6 -9
  12. package/skills/brainx-acceleration/SKILL.md +459 -0
  13. package/skills/brainx-general-guard/SKILL.md +67 -37
  14. package/skills/brainx-install/SKILL.md +21 -24
  15. package/skills/brainx-modeling-loop/SKILL.md +268 -0
  16. package/skills/brainx-modeling-loop/agents/openai.yaml +4 -0
  17. package/skills/brainx-modeling-loop/references/monitor-experiment.md +49 -0
  18. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow/scripts/fitting_hh_neuron.py +254 -0
  19. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +232 -0
  20. package/skills/brainx-modeling-loop/references/run-experiment.md +179 -0
  21. package/skills/brainx-modeling-loop/references/training-workflow.md +270 -0
  22. package/skills/{braincell → package-skills/braincell}/SKILL.md +3 -16
  23. package/skills/{braincell → package-skills/braincell}/references/mixions-for-adaptation.md +26 -3
  24. package/skills/{braincell → package-skills/braincell}/references/multicompartment/multicompartment-cell-workflow.md +2 -2
  25. package/skills/package-skills/braincell/references/scripts/fitting_hh_neuron.py +254 -0
  26. package/skills/package-skills/braincell/references/scripts/spike_frequency_adaptation.py +135 -0
  27. package/skills/{brainevent → package-skills/brainevent}/SKILL.md +0 -1
  28. package/skills/package-skills/brainevent/references/synaptic-plasticity.md +129 -0
  29. package/skills/{brainmass → package-skills/brainmass}/SKILL.md +10 -5
  30. package/skills/{brainmass → package-skills/brainmass}/references/batch-transform-acceleration.md +44 -3
  31. package/skills/{brainmass → package-skills/brainmass}/references/brainstate/parameter-constraints-regularization.md +1 -1
  32. package/skills/{brainmass → package-skills/brainmass}/references/coupling-network-api.md +121 -3
  33. package/skills/{brainmass → package-skills/brainmass}/references/modellibrary.md +90 -1
  34. package/skills/package-skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +188 -0
  35. package/skills/package-skills/brainmass/references/simulator-input-monitor-api.md +98 -0
  36. package/skills/{brainmass → package-skills/brainmass}/references/visualization-analysis-api.md +6 -6
  37. package/skills/{brainpy-state → package-skills/brainpy-state}/SKILL.md +17 -8
  38. package/skills/{brainpy-state → package-skills/brainpy-state}/references/brain-dynamics-delay-protocol.md +52 -1
  39. package/skills/package-skills/brainpy-state/references/braintools/connectivity.md +206 -0
  40. package/skills/package-skills/brainpy-state/references/braintools/input-current.md +199 -0
  41. package/skills/{brainpy-state → package-skills/brainpy-state}/references/component-selection.md +20 -5
  42. package/skills/package-skills/brainpy-state/references/perturbation-experiment-validity.md +76 -0
  43. package/skills/{brainpy-state → package-skills/brainpy-state}/references/projection-patterns.md +3 -1
  44. package/skills/package-skills/brainpy-state/references/scripts/sound_localization.py +240 -0
  45. package/skills/{brainstate → package-skills/brainstate}/SKILL.md +12 -15
  46. package/skills/package-skills/brainstate/agents/openai.yaml +4 -0
  47. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/brainstate-control-flow-patterns.md +8 -0
  48. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/brainstate-transformed-diagnostics.md +1 -1
  49. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/parameter-constraints-regularization.md +1 -1
  50. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/randomness-and-reproducibility.md +1 -1
  51. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-grad-expansion.md +2 -2
  52. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-vmap-expansion.md +58 -8
  53. package/skills/{brainstate → package-skills/brainstate}/references/collective_model_operations.md +26 -27
  54. package/skills/{brainstate → package-skills/brainstate}/references/libraries/prebuilt-layer-library.md +1 -1
  55. package/skills/package-skills/brainstate/references/paired-perturbation-execution.md +113 -0
  56. package/skills/package-skills/braintrace/SKILL.md +187 -0
  57. package/skills/package-skills/braintrace/references/Drtrl.md +133 -0
  58. package/skills/{braintrace → package-skills/braintrace}/references/ETP operators.md +31 -4
  59. package/skills/package-skills/braintrace/references/algorithm selection.md +64 -0
  60. package/skills/package-skills/braintrace/references/batching.md +140 -0
  61. package/skills/{braintrace → package-skills/braintrace}/references/compiler_internal.md +2 -2
  62. package/skills/{braintrace → package-skills/braintrace}/references/custom algorithms.md +8 -10
  63. package/skills/package-skills/braintrace/references/pp_pprop workflow.md +179 -0
  64. package/skills/{braintrace → package-skills/braintrace}/references/pre-built-braintrace-layer.md +2 -2
  65. package/skills/{brainpy-state → package-skills/brainunit}/references/array-creation.md +2 -2
  66. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +0 -75
  67. package/skills/brainevent/references/synaptic-plasticity.md +0 -285
  68. package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +0 -130
  69. package/skills/brainstate/references/braintools/optimizer.md +0 -179
  70. package/skills/braintrace/SKILL.md +0 -161
  71. package/skills/braintrace/references/Drtrl.md +0 -179
  72. package/skills/braintrace/references/algorithm selection.md +0 -120
  73. package/skills/braintrace/references/batching.md +0 -150
  74. package/skills/braintrace/references/pp_pprop workflow.md +0 -196
  75. /package/skills/{braincell → package-skills/braincell}/references/area-scaled-hh-pattern.md +0 -0
  76. /package/skills/{braincell → package-skills/braincell}/references/braincell-custom-ion-channel-authoring.md +0 -0
  77. /package/skills/{braincell → package-skills/braincell}/references/channel-library.md +0 -0
  78. /package/skills/{braincell → package-skills/braincell}/references/ion-library.md +0 -0
  79. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/braincell-manual-morphology-construction.md +0 -0
  80. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/cv-policy-reference.md +0 -0
  81. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/filter-function-library.md +0 -0
  82. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/morphology-io-loading-validation.md +0 -0
  83. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/probe-reference.md +0 -0
  84. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/topology-building-and-visualization.md +0 -0
  85. /package/skills/{braincell → package-skills/braincell}/references/scripts/calcium_channel_gating.py +0 -0
  86. /package/skills/{braincell → package-skills/braincell}/references/scripts/cell_multicompartment_reference.py +0 -0
  87. /package/skills/{braincell → package-skills/braincell}/references/scripts/channel_ablation.py +0 -0
  88. /package/skills/{braincell → package-skills/braincell}/references/scripts/fi_curve.py +0 -0
  89. /package/skills/{braincell → package-skills/braincell}/references/scripts/hh_neuron_basics.py +0 -0
  90. /package/skills/{braincell → package-skills/braincell}/references/scripts/t_current_rebound.py +0 -0
  91. /package/skills/{braincell → package-skills/braincell}/references/scripts/thalamic_neurons.py +0 -0
  92. /package/skills/{braincell → package-skills/braincell}/references/solver-library-with-effects.md +0 -0
  93. /package/skills/{brainevent → package-skills/brainevent}/references/connectivity-variants.md +0 -0
  94. /package/skills/{brainevent → package-skills/brainevent}/references/custom-operators-cpu.md +0 -0
  95. /package/skills/{brainevent → package-skills/brainevent}/references/custom-operators-gpu.md +0 -0
  96. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/102_EI_net_1996.py +0 -0
  97. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/204_joglekar_2018_propagation.py +0 -0
  98. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/coba_ei_teaching.py +0 -0
  99. /package/skills/{brainevent → package-skills/brainevent}/references/sparse-formats.md +0 -0
  100. /package/skills/{brainmass → package-skills/brainmass}/references/brainstate/parameter-transforms-regularizers-catalog.md +0 -0
  101. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/cogtask.md +0 -0
  102. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/data-preprocessing.md +0 -0
  103. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/metric.md +0 -0
  104. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/optimizer.md +0 -0
  105. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/parameter-initializer.md +0 -0
  106. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/surrogate.md +0 -0
  107. /package/skills/{brainmass → package-skills/brainmass}/references/datasets-api.md +0 -0
  108. /package/skills/{brainmass → package-skills/brainmass}/references/fitting-with-objectives-api.md +0 -0
  109. /package/skills/{brainmass → package-skills/brainmass}/references/forward-observation-api.md +0 -0
  110. /package/skills/{brainmass → package-skills/brainmass}/references/horn-task-training.md +0 -0
  111. /package/skills/{brainmass → package-skills/brainmass}/references/noiseprocesses.md +0 -0
  112. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/eeg-fitting-with-gradients.py +0 -0
  113. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/gradient-free-fitting.py +0 -0
  114. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/hopf-bifurcation-single-node.py +0 -0
  115. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/horn-cognitive-task-training.py +0 -0
  116. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/jansen-rit-eeg-proxy.py +0 -0
  117. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/kuramoto-synchronization.py +0 -0
  118. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/linear-baseline-node.py +0 -0
  119. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/resting-state-meg-whole-brain-pipeline.py +0 -0
  120. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/seizure-epileptor-case-study.py +0 -0
  121. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wilson-cowan-ei-dynamics.py +0 -0
  122. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wong-wang-decision-making.py +0 -0
  123. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wong-wang-dmf-resting-state.py +0 -0
  124. /package/skills/{brainunit → package-skills/brainpy-state}/references/array-creation.md +0 -0
  125. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/analysis.md +0 -0
  126. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/brainpy legacy workflow.md +0 -0
  127. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/built-in dynamic neuron model.md +0 -0
  128. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/connecting neurons.md +0 -0
  129. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/customize neuron and synpase.md +0 -0
  130. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Input generation.md +0 -0
  131. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/More about simulation.md +0 -0
  132. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +0 -0
  133. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +0 -0
  134. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +0 -0
  135. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +0 -0
  136. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/delays.md +0 -0
  137. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +0 -0
  138. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/integrators.md +0 -0
  139. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/route activity through connectivity.md +0 -0
  140. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/synaptic projections.md +0 -0
  141. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/synpase properties.md +0 -0
  142. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/loss library.md +0 -0
  143. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/optimizers.md +0 -0
  144. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/parameter initializers.md +0 -0
  145. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/prebuilt neural network layers.md +0 -0
  146. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/surrogate gradients.md +0 -0
  147. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/trainer library.md +0 -0
  148. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/trainingworkflows.md +0 -0
  149. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/brainstate-control-flow-patterns.md +0 -0
  150. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/data-preprocessing.md +0 -0
  151. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/metric.md +0 -0
  152. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/optimizer.md +0 -0
  153. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/parameter-initializer.md +0 -0
  154. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/surrogate.md +0 -0
  155. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/devices.md +0 -0
  156. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/divergence-and-parity.md +0 -0
  157. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/integration-categories.md +0 -0
  158. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/model-library.md +0 -0
  159. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/nest-workflow.md +0 -0
  160. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/network-building.md +0 -0
  161. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brette_et_al_2007.py +0 -0
  162. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brunel_alpha.py +0 -0
  163. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brunel_delta.py +0 -0
  164. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +0 -0
  165. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +0 -0
  166. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/spatial_gaussex.py +0 -0
  167. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/synapsecollection.py +0 -0
  168. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/synapse-and-connectivity.md +0 -0
  169. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/103_COBA_2005.py +0 -0
  170. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/106_COBA_HH_2007.py +0 -0
  171. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/107_gamma_oscillation_1996.py +0 -0
  172. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/109_fast_global_oscillation.py +0 -0
  173. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +0 -0
  174. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/training-snn.py +0 -0
  175. /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/parameter-transforms-regularizers-catalog.md +0 -0
  176. /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-jit-expansion.md +0 -0
  177. /package/skills/{brainstate → package-skills/brainstate}/references/extension_mechanisms.md +0 -0
  178. /package/skills/{brainstate → package-skills/brainstate}/references/libraries/prebuilt-activation-library.md +0 -0
  179. /package/skills/{brainstate → package-skills/brainstate}/references/model-interop-and-migration.md +0 -0
  180. /package/skills/{brainstate → package-skills/brainstate}/references/simulation-environment.md +0 -0
  181. /package/skills/{brainstate → package-skills/brainstate}/references/size-inference-variations.md +0 -0
  182. /package/skills/{brainstate → package-skills/brainstate}/references/state-graph-operations.md +0 -0
  183. /package/skills/{brainstate → package-skills/brainstate}/references/state_collections_and_utilities.md +0 -0
  184. /package/skills/{brainstate → package-skills/brainstate}/scripts/integrator_rnn.py +0 -0
  185. /package/skills/{brainstate → package-skills/brainstate}/scripts/lif_neuron_model.py +0 -0
  186. /package/skills/{brainstate → package-skills/brainstate}/scripts/modern_cnn.py +0 -0
  187. /package/skills/{brainstate → package-skills/brainstate}/scripts/resnet.py +0 -0
  188. /package/skills/{braintrace → package-skills/braintrace}/references/custom ETP primitives.md +0 -0
  189. /package/skills/{braintrace → package-skills/braintrace}/references/customizing_primitive_transforms.md +0 -0
  190. /package/skills/{brainunit → package-skills/brainunit}/SKILL.md +0 -0
  191. /package/skills/{brainunit → package-skills/brainunit}/references/array-mechanics/functional-structural-api.md +0 -0
  192. /package/skills/{brainunit → package-skills/brainunit}/references/array-mechanics.md +0 -0
  193. /package/skills/{brainunit → package-skills/brainunit}/references/math-function-library.md +0 -0
  194. /package/skills/{brainunit → package-skills/brainunit}/references/physical-constant-library.md +0 -0
  195. /package/skills/{brainunit → package-skills/brainunit}/references/prefix-library.md +0 -0
  196. /package/skills/{brainunit → package-skills/brainunit}/references/quantity-inspection-and-conversion.md +0 -0
  197. /package/skills/{brainunit → package-skills/brainunit}/references/typing-and-runtime-validation.md +0 -0
  198. /package/skills/{brainunit → package-skills/brainunit}/references/unit-structure-and-definition.md +0 -0
@@ -0,0 +1,254 @@
1
+ # Copyright 2024 BrainX Ecosystem Limited. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+
17
+ from pathlib import Path
18
+ from typing import Union, Callable
19
+
20
+ import brainstate
21
+ import braintools
22
+ import brainunit as u
23
+ import jax
24
+ import matplotlib.pyplot as plt
25
+ import numpy as np
26
+ import pandas as pd
27
+
28
+ import braincell
29
+
30
+ brainstate.environ.set(dt=0.01 * u.ms)
31
+
32
+ # Load Input and Output Data
33
+ DATA_DIR = Path(__file__).resolve().parents[2] / "data" / "neuron_traces"
34
+ df_inp_traces = pd.read_csv(DATA_DIR / 'input_traces_hh.csv')
35
+ df_out_traces = pd.read_csv(DATA_DIR / 'output_traces_hh.csv')
36
+
37
+ area = 20000 * u.um ** 2 # neuronal area
38
+ inp_traces = df_inp_traces.to_numpy()[:, 1:] * 1e9 * u.nA # input currents
39
+ mem_traces = df_out_traces.to_numpy()[:, 1:] * u.mV # membrane potentials to record
40
+
41
+
42
+ class INa(braincell.Channel):
43
+ root_type = braincell.HHTypedNeuron
44
+
45
+ def __init__(
46
+ self,
47
+ size: brainstate.typing.Size,
48
+ ENa: Union[brainstate.typing.ArrayLike, Callable] = 50. * u.mV,
49
+ gNa: Union[brainstate.typing.ArrayLike, Callable] = 120. * u.mS,
50
+ vth: Union[brainstate.typing.ArrayLike, Callable] = -63 * u.mV,
51
+ ):
52
+ super().__init__(size)
53
+ self.ENa = braintools.init.param(ENa, self.varshape)
54
+ self.gNa = braintools.init.param(gNa, self.varshape)
55
+ self.V_th = braintools.init.param(vth, self.varshape)
56
+
57
+ def init_state(self, V, batch_size=None):
58
+ self.m = braincell.state(braintools.init.param(u.math.zeros, self.varshape))
59
+ self.h = braincell.state(braintools.init.param(u.math.zeros, self.varshape))
60
+
61
+ # m channel
62
+ m_alpha = lambda self, V: 0.32 * 4 / u.math.exprel((13. * u.mV - V + self.V_th).to_decimal(u.mV) / 4.)
63
+ m_beta = lambda self, V: 0.28 * 5 / u.math.exprel((V - self.V_th - 40. * u.mV).to_decimal(u.mV) / 5.)
64
+ m_inf = lambda self, V: self.m_alpha(V) / (self.m_alpha(V) + self.m_beta(V))
65
+
66
+ # h channel
67
+ h_alpha = lambda self, V: 0.128 * u.math.exprel((17. * u.mV - V + self.V_th).to_decimal(u.mV) / 18.)
68
+ h_beta = lambda self, V: 4. / (1 + u.math.exp((40. * u.mV - V + self.V_th).to_decimal(u.mV) / 5.))
69
+ h_inf = lambda self, V: self.h_alpha(V) / (self.h_alpha(V) + self.h_beta(V))
70
+
71
+ def compute_derivative(self, V, *args, **kwargs):
72
+ m = self.m.value
73
+ h = self.h.value
74
+ self.m.derivative = (self.m_alpha(V) * (1 - m) - self.m_beta(V) * m) / u.ms
75
+ self.h.derivative = (self.h_alpha(V) * (1 - h) - self.h_beta(V) * h) / u.ms
76
+
77
+ def current(self, V, *args, **kwargs):
78
+ m = self.m.value
79
+ h = self.h.value
80
+ return (self.gNa * m * m * m * h) * (self.ENa - V)
81
+
82
+
83
+ class IK(braincell.Channel):
84
+ root_type = braincell.HHTypedNeuron
85
+
86
+ def __init__(
87
+ self,
88
+ size: brainstate.typing.Size,
89
+ EK: Union[brainstate.typing.ArrayLike, Callable] = -90. * u.mV,
90
+ gK: Union[brainstate.typing.ArrayLike, Callable] = 36. * u.mS,
91
+ vth: Union[brainstate.typing.ArrayLike, Callable] = -63 * u.mV,
92
+ ):
93
+ super().__init__(size)
94
+ self.EK = braintools.init.param(EK, self.varshape)
95
+ self.gK = braintools.init.param(gK, self.varshape)
96
+ self.V_th = braintools.init.param(vth, self.varshape)
97
+
98
+ def init_state(self, V, batch_size=None):
99
+ self.n = braincell.state(braintools.init.param(u.math.zeros, self.varshape))
100
+
101
+ # n channel
102
+ n_alpha = lambda self, V: 0.032 * 5 / u.math.exprel((15. * u.mV - V + self.V_th).to_decimal(u.mV) / 5.)
103
+ n_beta = lambda self, V: .5 * u.math.exp((10. * u.mV - V + self.V_th).to_decimal(u.mV) / 40.)
104
+ n_inf = lambda self, V: self.n_alpha(V) / (self.n_alpha(V) + self.n_beta(V))
105
+
106
+ def compute_derivative(self, V, *args, **kwargs):
107
+ n = self.n.value
108
+ self.n.derivative = (self.n_alpha(V) * (1 - n) - self.n_beta(V) * n) / u.ms
109
+
110
+ def current(self, V, *args, **kwargs):
111
+ n2 = self.n.value ** 2
112
+ return (self.gK * n2 * n2) * (self.EK - V)
113
+
114
+
115
+ class HH(braincell.SingleCompartment):
116
+ def __init__(
117
+ self,
118
+ size,
119
+ v_initializer: Callable = braintools.init.Uniform(-70 * u.mV, -60. * u.mV),
120
+ gL: Union[brainstate.typing.ArrayLike, Callable] = 0.003 * u.mS,
121
+ gNa: Union[brainstate.typing.ArrayLike, Callable] = 120. * u.mS,
122
+ gK: Union[brainstate.typing.ArrayLike, Callable] = 36. * u.mS,
123
+ C: Union[brainstate.typing.ArrayLike, Callable] = 1. * (u.uF / u.cm ** 2),
124
+ solver: str = 'rk4'
125
+ ):
126
+ super().__init__(size, V_initializer=v_initializer, C=C, solver=solver)
127
+ self.ina = INa(size, gNa=gNa)
128
+ self.ik = IK(size, gK=gK)
129
+ self.il = braincell.channel.IL(size, g_max=gL, E=-65. * u.mV)
130
+
131
+
132
+ def visualize_target(voltages):
133
+ fig, gs = braintools.visualize.get_figure(2, voltages.shape[1], 3, 4.5)
134
+ times = np.arange(voltages.shape[0]) * 0.01
135
+ for i in range(voltages.shape[1]):
136
+ ax = fig.add_subplot(gs[0, i])
137
+ ax.plot(times, voltages[:, i], label='target')
138
+ plt.xlabel('Time [ms]')
139
+ plt.legend()
140
+ ax = plt.subplot(gs[1, i])
141
+ ax.plot(times, inp_traces[i])
142
+ plt.xlabel('Time [ms]')
143
+ plt.show()
144
+
145
+
146
+ def visualize(voltages, gl, g_na, g_kd, C):
147
+ # currents: [T, B]
148
+ # voltages: [T, B]
149
+ simulated_vs = simulate_model(gl, g_na, g_kd, C)
150
+ voltages = voltages.mantissa
151
+
152
+ fig, gs = braintools.visualize.get_figure(2, simulated_vs.shape[1], 3, 4.5)
153
+ for i in range(simulated_vs.shape[1]):
154
+ ax = fig.add_subplot(gs[0, i])
155
+ ax.plot(voltages[:, i], label='target')
156
+ ax.plot(simulated_vs[:, i], label='simulated')
157
+ plt.legend()
158
+ ax = plt.subplot(gs[1, i])
159
+ ax.plot(inp_traces[i])
160
+ plt.show()
161
+
162
+
163
+ def simulate_model(gl, g_na, g_kd, C):
164
+ current = inp_traces.T
165
+ assert current.ndim == 2 # [T, B]
166
+ n_input = current.shape[1]
167
+ hh = HH((n_input, 1), gL=gl, gNa=g_na, gK=g_kd, C=C, v_initializer=braintools.init.Constant(-65. * u.mV), )
168
+ hh.init_state()
169
+
170
+ def step_fun(i, inp):
171
+ with brainstate.environ.context(i=i, t=brainstate.environ.get_dt() * i):
172
+ spike = hh(inp)
173
+ return hh.V.value
174
+
175
+ indices = np.arange(current.shape[0])
176
+ current = u.math.expand_dims(current, axis=-1) # [T, B, 1]
177
+ return brainstate.transform.for_loop(step_fun, indices, current) # (T, B)
178
+
179
+
180
+ def compare_potentials(param):
181
+ vs = simulate_model(param['gl'], param['g_na'], param['g_kd'], param['C']) # (T, B)
182
+ losses = braintools.metric.squared_error(vs.mantissa, target_vs.mantissa)
183
+ return losses.mean()
184
+
185
+
186
+ # inp_traces: [B, T]
187
+ # target_vs: [B, T, 1]
188
+ # target_vs = simulate_model(50.37195496 * u.nsiemens,
189
+ # 28.01317016 * u.usiemens,
190
+ # 8.15968937 * u.usiemens,
191
+ # 195.2173985 * u.pfarad)
192
+ target_vs = u.math.expand_dims(mem_traces.T, axis=-1) # [T, B, 1]
193
+
194
+
195
+ # visualize_target(target_vs)
196
+
197
+
198
+ def visualize_hh_input_and_output():
199
+ # Load Input and Output Data
200
+ inp_traces = df_inp_traces.to_numpy()
201
+ inp_traces = inp_traces[:, 1:] * 1e9
202
+
203
+ out_traces = df_out_traces.to_numpy()
204
+ out_traces = out_traces[:, 1:]
205
+
206
+ indices = np.arange(inp_traces.shape[1]) * 0.01
207
+
208
+ fig, gs = braintools.visualize.get_figure(3, 1, 1.2, 6.0)
209
+ ax = fig.add_subplot(gs[0, 0])
210
+ ax.plot(indices, inp_traces.T)
211
+ plt.xticks([])
212
+ plt.ylabel('Current [nA]', fontsize=13)
213
+
214
+ ax2 = fig.add_subplot(gs[1:, 0])
215
+ ax2.plot(indices, out_traces.T)
216
+ plt.ylabel('Potential [mV]', fontsize=13)
217
+ plt.xlabel('Time [ms]')
218
+
219
+ fig.align_ylabels([ax, ax2])
220
+ plt.show()
221
+
222
+
223
+ bounds = {
224
+ 'gl': [1e0, 1e2] * u.nS,
225
+ 'g_na': [1e0, 2e2] * u.uS,
226
+ 'g_kd': [1e0, 1e2] * u.uS,
227
+ 'C': [0.1, 2] * u.uF * u.cm ** -2 * area,
228
+ }
229
+
230
+
231
+ def fitting_by_nevergrad(method='DE', n_sample=200, n_iter=20):
232
+ print(f"Method: {method}, n_sample: {n_sample}")
233
+
234
+ @brainstate.transform.jit
235
+ def loss_with_multiple_run(**params):
236
+ return brainstate.transform.vmap(compare_potentials)(params)
237
+
238
+ opt = braintools.optim.NevergradOptimizer(
239
+ loss_with_multiple_run,
240
+ n_sample=n_sample,
241
+ bounds=bounds,
242
+ method=method,
243
+ )
244
+ opt.initialize()
245
+ param = opt.minimize(n_iter)
246
+ loss = compare_potentials(param)
247
+ print(param)
248
+ print(loss)
249
+ visualize(target_vs, **param)
250
+ return param, loss
251
+
252
+
253
+ if __name__ == '__main__':
254
+ fitting_by_nevergrad(n_sample=100)
@@ -0,0 +1,135 @@
1
+ """Controlled AHP ablation in a calibrated BrainCell teaching model.
2
+
3
+ Mechanism pattern:
4
+ https://brainx.chaobrain.com/braincell/examples/spike_frequency_adaptation.html
5
+
6
+ Ablation pattern:
7
+ https://brainx.chaobrain.com/braincell/examples/channel_ablation.html
8
+
9
+ This is not a reproduction of one literature neuron. It combines classical HH
10
+ spiking with dynamic calcium and AHP_De1994, then sweeps AHP strength so the
11
+ causal effect is visible and sensitivity to the calibrated value is explicit.
12
+ """
13
+
14
+ import braincell
15
+ import brainstate
16
+ import braintools
17
+ import brainunit as u
18
+ import matplotlib.pyplot as plt
19
+ import numpy as np
20
+
21
+
22
+ class AdaptingCell(braincell.SingleCompartment):
23
+ """Single-compartment teaching model with removable Ca-activated K current."""
24
+
25
+ def __init__(self, size, g_ahp, solver="exp_euler"):
26
+ super().__init__(
27
+ size,
28
+ C=1.0 * u.uF / u.cm**2,
29
+ V_initializer=braintools.init.Constant(-75.0 * u.mV),
30
+ V_th=20.0 * u.mV,
31
+ solver=solver,
32
+ )
33
+ self.na = braincell.ion.SodiumFixed(size, E=50.0 * u.mV)
34
+ self.na.add(INa=braincell.channel.Na_HH1952(size))
35
+
36
+ self.k = braincell.ion.PotassiumFixed(size, E=-77.0 * u.mV)
37
+ self.k.add(IK=braincell.channel.K_HH1952(size))
38
+
39
+ # These teaching values are calibrated, not a sourced cell phenotype.
40
+ self.ca = braincell.ion.CalciumDetailed(
41
+ size,
42
+ C_rest=5.0e-5 * u.mM,
43
+ tau=80.0 * u.ms,
44
+ d=0.5 * u.um,
45
+ )
46
+ self.ca.add(
47
+ ICaL=braincell.channel.CaL_IS2008(
48
+ size,
49
+ g_max=5.0 * u.mS / u.cm**2,
50
+ )
51
+ )
52
+
53
+ self.kca = braincell.MixIons(self.k, self.ca)
54
+ self.kca.add(
55
+ IAHP=braincell.channel.AHP_De1994(size, g_max=g_ahp)
56
+ )
57
+ self.IL = braincell.channel.IL(
58
+ size,
59
+ E=-54.387 * u.mV,
60
+ g_max=0.03 * u.mS / u.cm**2,
61
+ )
62
+
63
+
64
+ dt = 0.01 * u.ms
65
+ stimulus_on = 50.0 * u.ms
66
+ stimulus_off = 550.0 * u.ms
67
+ holding_current = -0.5 * u.uA / u.cm**2
68
+ g_ahp = u.math.asarray([0.0, 0.3, 1.0]) * u.mS / u.cm**2
69
+ current = u.math.asarray([10.0, 10.0, 10.0]) * u.uA / u.cm**2
70
+
71
+ cell = AdaptingCell(size=g_ahp.shape, g_ahp=g_ahp)
72
+
73
+ with brainstate.environ.context(dt=dt):
74
+ cell.init_state()
75
+ times = u.math.arange(0.0 * u.ms, 600.0 * u.ms, dt)
76
+
77
+ def step(t):
78
+ injected = u.math.where(
79
+ (t >= stimulus_on) & (t < stimulus_off),
80
+ current,
81
+ holding_current,
82
+ )
83
+ with brainstate.environ.context(t=t):
84
+ spike = cell.update(injected)
85
+ return cell.V.value, spike
86
+
87
+ voltages, spikes = brainstate.transform.for_loop(step, times)
88
+
89
+ times_ms = np.asarray(times.to_decimal(u.ms))
90
+ pre_stimulus_spikes = np.asarray(spikes[times < stimulus_on]).sum()
91
+ assert pre_stimulus_spikes == 0
92
+
93
+ isis = []
94
+ for i, strength in enumerate(g_ahp.to_decimal(u.mS / u.cm**2)):
95
+ spike_times = times_ms[np.asarray(spikes[:, i]) > 0]
96
+ spike_times = spike_times[
97
+ (spike_times >= stimulus_on.to_decimal(u.ms))
98
+ & (spike_times < stimulus_off.to_decimal(u.ms))
99
+ ]
100
+ isi = np.diff(spike_times)
101
+ isis.append(isi)
102
+ print(
103
+ f"g_AHP={strength:.1f} mS/cm^2: {spike_times.size} spikes, "
104
+ f"first ISI={isi[0]:.2f} ms, last ISI={isi[-1]:.2f} ms"
105
+ )
106
+
107
+ # The ablated lane is tonic; the calibrated present-AHP lane adapts strongly.
108
+ assert abs(isis[0][-1] - isis[0][0]) / isis[0][0] < 0.10
109
+ assert isis[-1][-1] / isis[-1][0] > 1.50
110
+
111
+ fig, axes = plt.subplots(2, 1, figsize=(8, 5))
112
+ for i, label in ((0, "AHP removed"), (-1, "AHP present (teaching value)")):
113
+ axes[0].plot(
114
+ times_ms,
115
+ np.asarray(voltages[:, i].to_decimal(u.mV)),
116
+ linewidth=0.8,
117
+ label=label,
118
+ )
119
+ axes[1].plot(
120
+ np.arange(1, isis[i].size + 1),
121
+ isis[i],
122
+ "o-",
123
+ markersize=3,
124
+ label=label,
125
+ )
126
+ axes[0].set(
127
+ xlabel="Time (ms)",
128
+ ylabel="V (mV)",
129
+ title="Matched steady-current conditions from a quiet baseline",
130
+ )
131
+ axes[1].set(xlabel="ISI index", ylabel="ISI (ms)", title="AHP-dependent slowing")
132
+ for axis in axes:
133
+ axis.legend(frameon=False)
134
+ plt.tight_layout()
135
+ plt.show()
@@ -261,7 +261,6 @@ Verify `postsynaptic_input.shape == connectivity.shape[1:]` for vector input and
261
261
  | `references/custom-operators-gpu.md` | Open when a custom operation targets GPU; it contains Numba CUDA, Warp, raw CUDA, GPU and multi-backend registration, stream and ABI rules, compiler controls, caching, diagnostics, and verification workflows. |
262
262
 
263
263
  ## Application script examples
264
-
265
264
  | Reference | Open when |
266
265
  |---|---|
267
266
  | `references/scripts/coba_ei_teaching.py` | Open for the shared BrainEvent and BrainPy teaching example; it uses `BinaryArray` with interchangeable `FixedNumPerPre`, `CSR`, and dense connectivity for efficient event-driven communication into BrainPy `LIFRef`, `Expon`, and `COBA` dynamics inside one compiled BrainState loop. |
@@ -0,0 +1,129 @@
1
+ # BrainEvent synaptic plasticity
2
+
3
+ Use this reference when binary pre- or postsynaptic events must modify stored synaptic weights. Plasticity is an overlay on the core `BinaryArray @ connectivity` workflow, not a prerequisite for ordinary event-driven communication.
4
+
5
+ BrainEvent's event-driven plasticity operators touch only weights connected to neurons that fired. Keep persistent weights and temporal traces in BrainState State so the complete online update can run inside State-aware transforms.
6
+
7
+ ## Choose the update operator
8
+
9
+ | Weight storage | Presynaptic event triggers update | Postsynaptic event triggers update | Use when |
10
+ |---|---|---|---|
11
+ | CSR | `update_csr_on_binary_pre()` | `update_csr_on_binary_post()` | Connectivity is sparse and fixed; only stored synapses should be visited. |
12
+ | Dense | `update_dense_on_binary_pre()` | `update_dense_on_binary_post()` | A small fully connected layer already uses a dense weight matrix. |
13
+
14
+ Use the `*_on_binary_pre` direction when the source neuron firing triggers the rule. Use the `*_on_binary_post` direction when the target neuron firing triggers it. For a bidirectional STDP rule, apply both directions with the traces and signs defined by that rule; do not substitute one trigger direction for the other.
15
+
16
+ ## Run online plasticity through State
17
+
18
+ Each timestep reads event arrays, advances trace State, and writes persistent weight State; lower that complete ordered update through `for_loop` and compile it with BrainState `jit`.
19
+
20
+ | API | Description |
21
+ |---|---|
22
+ | `brainstate.LongTermState(weight)` | Use for learned weights that must persist across trial resets and later rollouts; assign the update result through `.value`. |
23
+ | `brainstate.ShortTermState(trace)` | Use for decaying pre- or postsynaptic traces that belong to one sequence; reset them at every independent sequence boundary. |
24
+ | `update_csr_on_binary_pre(...)` | Use when active presynaptic rows update stored CSR data from a postsynaptic trace; it returns new data with the same shape and optionally clips it to `w_min` and `w_max`. |
25
+ | `brainstate.transform.for_loop(step, *events)` | Use for the ordered event sequence; it slices the leading time axis and preserves State effects between steps. |
26
+ | `brainstate.transform.jit(run)` | Use around the complete online sequence so State discovery and write-back remain transform-aware. |
27
+
28
+ ```python
29
+ import brainevent
30
+ import brainstate
31
+ import brainunit as u
32
+ import jax.numpy as jnp
33
+
34
+
35
+ class PlasticCSR(brainstate.nn.Module):
36
+ def __init__(self):
37
+ super().__init__()
38
+ self.shape = (3, 2)
39
+ self.indices = jnp.array([0, 1, 0, 1, 0, 1], dtype=jnp.int32)
40
+ self.indptr = jnp.array([0, 2, 4, 6], dtype=jnp.int32)
41
+ self.weight = brainstate.LongTermState(
42
+ jnp.full(6, 0.2, dtype=jnp.float32)
43
+ )
44
+ self.post_trace = brainstate.ShortTermState(
45
+ jnp.zeros(2, dtype=jnp.float32)
46
+ )
47
+
48
+ def update(self, pre_spike, post_spike):
49
+ decay = u.math.exp(-brainstate.environ.get_dt() / (20.0 * u.ms))
50
+ self.post_trace.value = (
51
+ self.post_trace.value * decay
52
+ + post_spike.astype(jnp.float32)
53
+ )
54
+ self.weight.value = brainevent.update_csr_on_binary_pre(
55
+ weight=self.weight.value,
56
+ indices=self.indices,
57
+ indptr=self.indptr,
58
+ pre_spike=pre_spike,
59
+ post_trace=self.post_trace.value * 0.01,
60
+ w_min=0.0,
61
+ w_max=1.0,
62
+ shape=self.shape,
63
+ )
64
+ return self.weight.value
65
+
66
+
67
+ pre_events = jnp.array(
68
+ [[False, False, False], [True, False, False], [False, True, False]]
69
+ )
70
+ post_events = jnp.array(
71
+ [[True, False], [False, False], [False, True]]
72
+ )
73
+
74
+ with brainstate.environ.context(dt=1.0 * u.ms):
75
+ rule = PlasticCSR()
76
+
77
+ @brainstate.transform.jit
78
+ def learn():
79
+ return brainstate.transform.for_loop(
80
+ rule.update,
81
+ pre_events,
82
+ post_events,
83
+ )
84
+
85
+ weight_history = learn()
86
+
87
+ learned = brainevent.CSR(
88
+ (rule.weight.value, rule.indices, rule.indptr),
89
+ shape=rule.shape,
90
+ )
91
+ drive = brainevent.BinaryArray(jnp.array([True, False, False])) @ learned
92
+
93
+ assert weight_history.shape == (3, 6)
94
+ assert drive.shape == (2,)
95
+ ```
96
+
97
+ Preserve `indices`, `indptr`, and `shape`; the operator updates stored weight values, not sparse topology. When trials are independent except for learned weights, keep `weight` sequential but reset `post_trace`, neural State, delays, and other per-trial State at every trial boundary; a silent interval is not a reset. If mapped lanes learn independently, give each lane separate weight and trace State. Do not `vmap` sequential trials when trial N+1 must consume weights learned in trial N.
98
+
99
+ ## Storage boundary
100
+
101
+ - Prefer CSR plasticity for large sparse networks with fixed connectivity.
102
+ - Prefer dense plasticity for small fully connected layers already represented densely.
103
+ - Do not choose JITC when individual connection weights must be persistently updated; use stored CSR or dense weights.
104
+ - Keep dimensionless efficacy weights dimensionless until a named synaptic or current boundary scales them into a physical quantity.
105
+
106
+ ## Exact API routing
107
+
108
+ Open the Matrix Operations API for exact signatures and associated primitives:
109
+
110
+ - CSR: `update_csr_on_binary_pre`, `update_csr_on_binary_post`, and their `*_p` primitives.
111
+ - Dense: `update_dense_on_binary_pre`, `update_dense_on_binary_post`, and their `*_p` primitives.
112
+
113
+ API: https://brainx.chaobrain.com/brainevent/reference/apis/operations.html
114
+
115
+ Open the official Synaptic Plasticity tutorial when choosing trace equations, update signs, or a bidirectional learning rule. The BrainEvent operator applies the supplied update; it does not choose the scientific learning rule.
116
+
117
+ ## Common failures
118
+
119
+ - Storing learned weights or traces in ordinary attributes while a transformed timestep mutates them.
120
+ - Running timesteps in a Python loop instead of one State-aware transformed sequence.
121
+ - Resetting persistent learned weights together with per-sequence traces.
122
+ - Updating CSR data while changing or discarding `indices`, `indptr`, or `shape`.
123
+ - Using a presynaptic-triggered operator for a postsynaptic-triggered term.
124
+ - Interpreting a potentiation-only example as a complete STDP rule.
125
+
126
+ ## Sources
127
+
128
+ - Tutorial 5: Synaptic Plasticity Modeling - Foundation of Learning and Memory: https://brainx.chaobrain.com/brainevent/tutorials/data-structures/05_synaptic_plasticity.html
129
+ - Apply event-driven synaptic plasticity: https://brainx.chaobrain.com/brainevent/how-to/data-structures/synaptic-plasticity.html
@@ -44,8 +44,8 @@ Every public regional model follows the same `*Step` contract, so choose by scie
44
44
  |---|---|
45
45
  | `brainmass.list_models()` | Use before choosing a model; it returns `ModelInfo` records with name, category, state-variable count, and use case. |
46
46
  | `brainmass.<Model>Step(in_size, **params)` | Use after selecting a model family; `in_size` sets the number of regions or parallel units and parameters broadcast to that shape. |
47
- | `brainmass.Simulator(model, dt=...)` | Use for the default, standard run path; it stores the model and integration step without changing the model equations. |
48
- | `Simulator.run(duration, ..., monitors=..., transient=...)` | Use to initialize State, execute the compiled loop, discard a warm-up interval, and return a dict of time-major trajectories plus unit-aware `ts`. |
47
+ | `brainmass.Simulator(model, dt=...)` | Use for the default run path; it stores the model and integration step without changing the model equations. |
48
+ | `Simulator.run(duration, *, inputs=None, monitors=None, transient=None, sample_every=None, batch_size=None, init_states=True, jit=True)` | Use to drive and observe the model through the standard runner; it initializes State by default, executes the complete State-aware loop with JIT by default, applies transient removal and post-update sampling, and returns time-major trajectories plus unit-aware `ts`. |
49
49
 
50
50
  ```python
51
51
  import brainmass
@@ -67,11 +67,13 @@ assert result["x"].shape == (1800, 1)
67
67
  assert result["ts"].shape == (1800,)
68
68
  ```
69
69
 
70
- Open `references/modellibrary.md` when choosing among model families, distinguishing similarly named Wong-Wang variants, comparing state cost, or locating a model's observable. Open `references/datasets-api.md` when the workflow needs bundled or registered input data.
70
+ Use `Simulator` before constructing an environment context or transformed loop yourself. Open `references/simulator-input-monitor-api.md` when supplying driven inputs, defining callable or named monitors, controlling initialization/JIT, sampling outputs, or separating model and trial axes. Open `references/batch-transform-acceleration.md` only when `Simulator` cannot express the workflow or a benchmark requires one stable explicit compilation boundary.
71
+
72
+ Open `references/modellibrary.md` when choosing among model families, distinguishing similarly named Wong-Wang variants or decision rules, comparing state cost, or locating a model's observable. Open `references/datasets-api.md` when the workflow needs bundled or registered input data.
71
73
 
72
74
  ## Noise and stochastic run
73
75
 
74
- Noise belongs to the model, while `batch_size` asks `Simulator` to initialize and run independent State realizations in one time-major result.
76
+ Noise belongs to the model. Use `in_size` for each realization's region or decision-unit shape and `batch_size` for independent State realizations; stochastic output is ordered `(time, batch, in_size...)`.
75
77
 
76
78
  | API | Description |
77
79
  |---|---|
@@ -106,7 +108,9 @@ assert trials["x"].shape == (1000, 8, 1)
106
108
 
107
109
  Seed again before a repeated run when exact replay matters.
108
110
 
109
- Open `references/noiseprocesses.md` when choosing white, OU, Brownian, or colored noise, using a noise process directly, or checking units and State behavior. Open `references/batch-transform-acceleration.md` when batching parameters, writing a custom transformed loop, or checkpointing a long differentiated rollout.
111
+ Do not flatten experimental conditions and stochastic trials into `in_size` unless a required external layout or numerical baseline demands it.
112
+
113
+ Open `references/noiseprocesses.md` when choosing white, OU, Brownian, or colored noise, using a noise process directly, or checking units and State behavior. Open `references/simulator-input-monitor-api.md` when batching stochastic trials or driving multiple conditions. Open `references/batch-transform-acceleration.md` when batching parameters, writing a custom transformed loop that `Simulator` cannot express, or checkpointing a long differentiated rollout.
110
114
 
111
115
  ## Build a delay-coupled network
112
116
 
@@ -256,6 +260,7 @@ Choose the workflow category first, then open only the smallest reference that o
256
260
  | Reference | Open when |
257
261
  |---|---|
258
262
  | `references/modellibrary.md` | Choosing a model family, observable, state cost, or similarly named variant. |
263
+ | `references/simulator-input-monitor-api.md` | Supplying model inputs, selecting monitor forms, sampling, controlling initialization/JIT, or separating model and trial axes. |
259
264
  | `references/noiseprocesses.md` | Selecting a noise spectrum, correlation structure, State behavior, units, or direct noise workflow. |
260
265
  | `references/datasets-api.md` | Loading, inspecting, generating, or registering BrainMass data containers. |
261
266
  | `references/coupling-network-api.md` | Selecting or configuring coupling, delays, connectivity conventions, direct coupling objects, or trainable network parameters. |
@@ -115,9 +115,49 @@ Keep the same body signature and result structure when switching. Validate both
115
115
 
116
116
  ## Benchmark correctly
117
117
 
118
- - Warm up the exact function and shape once before timing.
119
- - Call `jax.block_until_ready(result)` before stopping the timer because JAX dispatch is asynchronous.
120
- - Compare steady-state compiled runs separately from first-call compilation.
118
+ Define the step once, define the full rollout once, and transform that rollout once outside every timed call. The first call measures compilation plus execution; later compatible calls to the same callable measure steady execution.
119
+
120
+ ```python
121
+ import time
122
+
123
+ import brainmass
124
+ import brainstate
125
+ import brainunit as u
126
+ import jax
127
+ import jax.numpy as jnp
128
+
129
+ dt = 0.1 * u.ms
130
+ node = brainmass.HopfStep(in_size=64, a=0.25, w=0.3)
131
+ brainstate.nn.init_all_states(node)
132
+ steps = jnp.arange(300)
133
+
134
+ def step(index):
135
+ with brainstate.environ.context(i=index, t=index * dt):
136
+ node.update()
137
+ return node.x.value
138
+
139
+ def rollout():
140
+ with brainstate.environ.context(dt=dt):
141
+ return brainstate.transform.for_loop(step, steps)
142
+
143
+ run_once = brainstate.transform.jit(rollout)
144
+
145
+ start = time.perf_counter()
146
+ first_result = run_once()
147
+ jax.block_until_ready(first_result)
148
+ first_call_seconds = time.perf_counter() - start
149
+
150
+ steady_seconds = []
151
+ for _ in range(5):
152
+ start = time.perf_counter()
153
+ result = run_once()
154
+ jax.block_until_ready(result)
155
+ steady_seconds.append(time.perf_counter() - start)
156
+ ```
157
+
158
+ - Warm up the exact callable and shape once before reporting steady timing; report the first call separately when compilation cost matters.
159
+ - Block every timed result before stopping the timer because JAX dispatch is asynchronous.
160
+ - Restore the same initial State outside the timed region, or include the same reset inside every measured callable, when comparisons require identical starting conditions.
121
161
  - Batch enough work to occupy an accelerator; one small neural-mass node may run faster on CPU.
122
162
  - Keep `dt`, duration, shape, dtype, and monitor set identical across comparisons.
123
163
 
@@ -128,6 +168,7 @@ Keep the same body signature and result structure when switching. Validate both
128
168
  - `scan` used when no explicit carry exists.
129
169
  - A model constructed outside a parameter-mapped function and mutated across mapped values.
130
170
  - Variable-shape or Python-object results returned from transformed loop bodies.
171
+ - A step or rollout function reconstructed inside each timed repetition.
131
172
  - JAX timing measured without warmup or `block_until_ready`.
132
173
  - Checkpointing enabled before memory pressure is established.
133
174
 
@@ -1,6 +1,6 @@
1
1
  # BrainState constrained and regularized parameters
2
2
 
3
- Use this reference after `skills/brainmass/SKILL.md` has selected
3
+ Use this reference after `skills/package-skills/brainmass/SKILL.md` has selected
4
4
  `brainstate.nn.Param` for a fitted or directly trained BrainMass value that
5
5
  needs a valid-domain transform, a regularization penalty, a modeling prior, or
6
6
  fixed parameter-like storage. It owns the operational workflow and common