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,459 @@
1
+ ---
2
+ name: brainx-acceleration
3
+ description: Audits and refactors BrainX/BrainState simulation code for performance using state-aware BrainState transform patterns. Use for speed, acceleration, GPU performance, batching, vectorization, parameter sweeps, many neurons/trials, compile/runtime separation, memory reduction, throughput, multi-device execution, or performance-audit requests.
4
+ ---
5
+
6
+ # BrainX Acceleration
7
+
8
+ Use when auditing or refactoring BrainX/BrainState simulation code for performance. Systematically finds NumPy/Python-loop inefficiencies and rewrites them into state-aware BrainState transform patterns: `jit`, scan/control flow, `vmap`, `grad`, `checkpointed_scan`, `pmap2`/`shard_map`, `State`/`ParamState`/`RandomState`, PyTrees, batching, RNG, and shape-stable compiled simulation logic.
9
+
10
+ Usually reached from `skills/brainstate/SKILL.md` when speed, acceleration, GPU performance, batching, vectorization, parameter sweeps, many neurons/trials, compile/runtime separation, memory reduction, throughput, multi-device execution, or a performance audit becomes the user request.
11
+
12
+ Use this skill to turn slow BrainX/BrainState simulation code into transform-friendly, state-aware array programs. The goal is not “sprinkle `jit` everywhere.” The goal is to expose the correct simulation axes to BrainState transformations while preserving state semantics, RNG behavior, shapes, gradients, and numerical results.
13
+
14
+ Optimize in this order: **correctness -> state/RNG safety -> shape stability -> warm runtime -> memory -> multi-device scale**.
15
+
16
+ ## Reference usage
17
+
18
+ For any nontrivial State-aware rewrite, route through `skills/brainstate/SKILL.md` first. Load this skill's local references only when the specific rewrite needs exact transform or randomness semantics.
19
+
20
+ Do not invent BrainState arguments. If the exact API is uncertain, inspect local usage/tests or reference markdowns and state the assumption in the patch notes.
21
+
22
+ ## Core mental model
23
+
24
+ Convert this:
25
+
26
+ ```text
27
+ Python controls loops and mutable objects; arrays are small operations inside the loop.
28
+ ```
29
+
30
+ into this:
31
+
32
+ ```text
33
+ Arrays/states represent populations; BrainState transforms control repeated execution.
34
+ ```
35
+
36
+ Axis map:
37
+
38
+ | Axis | Meaning | Slow NumPy/Python pattern | BrainState rewrite target |
39
+ |---|---|---|---|
40
+ | `N` | neurons, synapses, features, compartments | loop over scalar cells/synapses | population-shaped arrays + `jnp` ops inside `jit` |
41
+ | `T` | time/recurrent steps | Python loop calling `step` | `scan`, `for_loop`, `while_loop`; usually wrapped by `jit` |
42
+ | `B` | batch, trials, stimuli, subjects | loop over examples/trials | `vmap` or explicitly batched state |
43
+ | `E` | ensemble, parameter sweep, initial conditions, seeds | loop over model copies/configs | `vmap` with mapped states/parameters/RNG |
44
+ | `P` | trainable parameters/sensitivities | finite differences/manual perturbation loops | `grad`, `value_and_grad`, `jacrev`, `jacfwd` over args or `ParamState` |
45
+ | `D` | devices | multiprocessing/manual sharding | `pmap2`, `shard_map`, explicit sharding after single-device cleanup |
46
+
47
+ ## Non-negotiable rules
48
+
49
+ - Use `brainstate.transform.*` for stateful BrainState code. Use raw `jax.*` transforms only for pure functions with explicit array inputs/outputs and no BrainState state writes.
50
+ - Use `jax.numpy as jnp` in transformed numerical paths. Keep `numpy as np` only for host preprocessing, file I/O, offline analysis, or static setup outside transforms.
51
+ - Mutable simulation quantities belong in explicit `State`, `ParamState`, or BrainState random-stream objects. Do not hide changing transformed values in ordinary Python attributes.
52
+ - Hot-path shapes, dtypes, and PyTree structure must be stable. Use masks, padding, bucketing, or static config instead of runtime shape creation.
53
+ - Do not automatically densify sparse/event/structured connectivity. First choose the right mathematical representation, then transform it.
54
+ - Do not claim acceleration from the first call. Separate compile time from warm execution time.
55
+ - Prefer small reviewable diffs with tiny deterministic equivalence tests.
56
+
57
+ ## Investigation protocol
58
+
59
+ ### 1. Build a hot-path inventory
60
+
61
+ For each candidate function (`step`, `update`, `forward`, `run`, `simulate`, `loss`, `train_step`, data/RNG helper), record:
62
+
63
+ ```text
64
+ function/call site:
65
+ inputs: shapes, dtypes, axis meanings
66
+ states read: State/ParamState/RandomState, shapes, shared or per-trial
67
+ states written: State/ParamState/RandomState, shapes, shared or per-trial
68
+ loops: axis, trip count, nested axes
69
+ current transforms: none / raw jax / brainstate.transform
70
+ outputs: full history vs summary metrics
71
+ RNG: source, key/stream split policy, per-step/per-trial independence
72
+ shape changes: yes/no, cause
73
+ host interaction: print/log/float/item/np.asarray/callbacks
74
+ connectivity: dense/sparse/event/structured
75
+ ```
76
+
77
+ Use searches as a first pass, then read the code before editing:
78
+
79
+ ```bash
80
+ rg -n "import numpy|np\." .
81
+ rg -n "for .*range|while " .
82
+ rg -n "\.append\(|np\.array\(|np\.stack\(|jnp\.stack\(|concatenate\(" .
83
+ rg -n "jax\.jit|jax\.grad|jax\.vmap|brainstate\.transform" .
84
+ rg -n "\.value\s*=|\[[^\]]+\]\s*=" .
85
+ rg -n "random|np\.random|jax\.random|RandomState|split_key|seed" .
86
+ rg -n "finite|epsilon|eps|perturb|theta_plus|theta_minus|jacobian|hessian" .
87
+ rg -n "\.item\(|float\(|int\(|bool\(|np\.asarray|print\(|logging\." .
88
+ rg -n "jit\(|grad\(|vmap\(|scan\(" .
89
+ ```
90
+
91
+ ### 2. Classify every inefficient pattern
92
+
93
+ Use these labels in audit notes and patch comments when useful.
94
+
95
+ | Label | Evidence | Why slow/risky | Rewrite target |
96
+ |---|---|---|---|
97
+ | `loop-N-scalar` | `for i in range(N)` updates neuron/synapse scalars | Python overhead; no fused population kernel | array-shaped state + `jnp.where`/broadcast/scatter/sparse ops under `jit` |
98
+ | `object-neurons` | list/dict of neuron/synapse objects updated one by one | compiler sees Python objects, not arrays | one population/module with state arrays shaped `[N,...]` |
99
+ | `loop-T-python` | Python loop calls `step(x[t])` | dispatch per step; no compiled recurrent loop | `scan`, `for_loop`, or `while_loop` inside `jit` |
100
+ | `dynamic-list-history` | append outputs/states then stack | dynamic Python accumulation; memory waste | `scan` outputs or summary carry |
101
+ | `memory-T-full-history` | stores all `V[t]`/state when only rates/loss needed | unnecessary memory; worse autodiff storage | carry summary; record sparse snapshots; `checkpointed_scan` for differentiable long runs |
102
+ | `loop-B-python` | loop over trials/batch/stimuli | serial Python batch | `vmap` or batched state |
103
+ | `loop-E-sweep` | loop over seeds/configs/model copies | serial ensemble sweep | `vmap` with leading `[E,...]` state/param/RNG axes |
104
+ | `loop-P-finite-diff` | `eps`, `theta_plus`, `theta_minus`, perturb each param | O(P) or O(2P) simulations; noisy gradients | `grad`/`value_and_grad` over args or `ParamState` |
105
+ | `raw-jax-stateful` | `jax.jit/grad/vmap` wraps BrainState module/state writes | state updates may be lost or mishandled | `brainstate.transform.*` or explicit split/pass/return/merge |
106
+ | `np-in-transform` | `np.*` in code used by `jit/grad/vmap/scan` | host execution, tracer conversion, frozen constants | replace with `jnp.*` or move outside transform |
107
+ | `python-control-array` | Python `if/while/bool/int/float` depends on array value | tracer errors or host sync | `jnp.where`, `cond`, `while_loop`, `for_loop`, masks |
108
+ | `wrong-jit-boundary` | jitting tiny helpers, or making jitted functions inside loops | compile overhead; poor fusion | jit largest stable unit: `run`, `loss`, `train_step` |
109
+ | `transform-inside-loop` | `jit(...)`, `vmap(...)`, `grad(...)` constructed repeatedly | repeated tracing/compilation | define transforms once at module/init scope |
110
+ | `dynamic-shape` | shape depends on data/spikes/runtime length | recompilation or unsupported traced shape | static config, padding, masks, bucketing |
111
+ | `hidden-mutable-attr` | ordinary attrs mutated in transformed method | untracked state semantics | `State`/`ParamState`/explicit return value |
112
+ | `state-vmap-ambiguous` | `vmap` over stateful model without explicit state-axis decision | shared vs independent state bugs | set/verify `state_in_axes`, `state_out_axes`, unexpected state policy |
113
+ | `rng-reuse` | same key/seed reused across trials/time; `np.random` in hot path | correlated trials; unreproducible behavior | BrainState random streams or explicit split; map RNG axis under `vmap` |
114
+ | `host-sync` | `print`, `.item()`, `float(x)`, `np.asarray(x)` in hot loop | device-host synchronization | aggregate metrics; log outside compiled loop; debug-only callbacks |
115
+ | `accidental-densify` | converts sparse/event connectivity to dense `[N,N]` | memory/bandwidth blow-up | preserve sparse/event/structured representation |
116
+ | `already-fused` | large `jnp` matmul/conv/reduction already dominates | transforms may not help much | benchmark first; avoid churn |
117
+
118
+ ### 3. Rank findings before rewriting
119
+
120
+ Score each finding:
121
+
122
+ ```text
123
+ impact = loop trip count × work per iteration × call frequency
124
+ risk = state/RNG/gradient/memory semantic risk
125
+ confidence = evidence quality + shape clarity + API certainty
126
+ ```
127
+
128
+ Rewrite high-impact, high-confidence items first. Do not refactor low-impact style issues unless they block a larger transform.
129
+
130
+ ## Rewrite playbook
131
+
132
+ ### A. Population axis `N`: scalar/object loop -> array state
133
+
134
+ Bad:
135
+
136
+ ```python
137
+ for i in range(num_neurons):
138
+ v[i] += dt * (-v[i] + i_ext[i]) / tau[i]
139
+ if v[i] > threshold[i]:
140
+ spike[i] = 1
141
+ v[i] = reset[i]
142
+ ```
143
+
144
+ Good shape pattern:
145
+
146
+ ```python
147
+ v_new = V.value + dt * (-V.value + i_ext) / tau
148
+ spike = v_new > threshold
149
+ V.value = jnp.where(spike, reset, v_new)
150
+ ```
151
+
152
+ Use `jnp.where`/masks for elementwise conditional reset. Use `.at[]` scatter or segment/sparse/event operations when updates are indexed. Avoid Python object-per-neuron design in hot paths.
153
+
154
+ ### B. Time axis `T`: Python simulation loop -> transformed control flow
155
+
156
+ Bad:
157
+
158
+ ```python
159
+ ys = []
160
+ for t in range(T):
161
+ ys.append(step(xs[t]))
162
+ y = jnp.stack(ys)
163
+ ```
164
+
165
+ Good full-history pattern:
166
+
167
+ ```python
168
+ def body(carry, x_t):
169
+ y_t = net(x_t) # may read/write BrainState State
170
+ return carry, y_t
171
+
172
+ @brainstate.transform.jit
173
+ def run(xs_T):
174
+ _, ys_T = brainstate.transform.scan(body, None, xs_T)
175
+ return ys_T
176
+ ```
177
+
178
+ Good summary-only pattern:
179
+
180
+ ```python
181
+ def body(summary, x_t):
182
+ y_t = net(x_t)
183
+ summary = summary + metric(y_t)
184
+ return summary, None
185
+ ```
186
+
187
+ Use `checkpointed_scan` when differentiating through long `T` and activation/state storage dominates memory. Before applying exact control-flow APIs, read `references/brainstate/brainstate-control-flow-patterns.md` if present.
188
+
189
+ ### C. Batch/trial axis `B`: Python batch loop -> `vmap` or batched state
190
+
191
+ Bad:
192
+
193
+ ```python
194
+ outs = []
195
+ for b in range(B):
196
+ outs.append(run_one(xs_B[b]))
197
+ outs = jnp.stack(outs)
198
+ ```
199
+
200
+ Good pattern:
201
+
202
+ ```python
203
+ run_batch = brainstate.transform.jit(
204
+ brainstate.transform.vmap(run_one, in_axes=0, out_axes=0)
205
+ )
206
+ outs = run_batch(xs_B)
207
+ ```
208
+
209
+ Before rewriting, decide for every state:
210
+
211
+ ```text
212
+ shared across B? parameters, shared read-only config, global constants
213
+ independent per B? membrane voltage, refractory state, synaptic traces, trial RNG, optimizer-free simulation state
214
+ written back? final per-trial state, shared aggregate, or discarded temporary?
215
+ ```
216
+
217
+ If independent state is required, use BrainState `vmap` state-axis controls such as `state_in_axes`/`state_out_axes` according to the local API. Read `references/brainstate/transformation-vmap-expansion.md` before editing exact arguments.
218
+
219
+ ### D. Ensemble/sweep axis `E`: serial model copies -> mapped states/params
220
+
221
+ Bad:
222
+
223
+ ```python
224
+ for e in range(E):
225
+ set_params(params[e])
226
+ results.append(run(inputs, seed=e))
227
+ ```
228
+
229
+ Good shape intent:
230
+
231
+ ```text
232
+ params/state/RNG: [E, ...]
233
+ inputs: [E, T, ...] or shared [T, ...]
234
+ outputs: [E, T, ...] or [E, summary]
235
+ ```
236
+
237
+ Good transform intent:
238
+
239
+ ```python
240
+ run_ensemble = brainstate.transform.jit(
241
+ brainstate.transform.vmap(
242
+ run_one_model,
243
+ in_axes=..., out_axes=...,
244
+ state_in_axes=..., state_out_axes=...,
245
+ )
246
+ )
247
+ ```
248
+
249
+ Use this for parameter sweeps, random initial conditions, seeds, lesions, perturbations, and independent circuit replicas. Verify memory: mapping `E` full histories can be huge.
250
+
251
+ ### E. Parameter axis `P`: manual gradients -> `grad`
252
+
253
+ Bad finite differences:
254
+
255
+ ```python
256
+ for i in range(num_params):
257
+ theta_p = theta.at[i].add(eps)
258
+ theta_m = theta.at[i].add(-eps)
259
+ g = (loss(theta_p) - loss(theta_m)) / (2 * eps)
260
+ ```
261
+
262
+ Good training intent:
263
+
264
+ ```python
265
+ params = model.states(brainstate.ParamState)
266
+
267
+ def loss_fn(x, target):
268
+ pred = run(x)
269
+ return jnp.mean((pred - target) ** 2)
270
+
271
+ grad_fn = brainstate.transform.grad(loss_fn, grad_states=params, return_value=True)
272
+
273
+ @brainstate.transform.jit
274
+ def train_step(x, target):
275
+ grads, loss = grad_fn(x, target)
276
+ optimizer.update(grads)
277
+ return loss
278
+ ```
279
+
280
+ Use `grad(loss_over_batch)` for normal batch training. Use `vmap(grad(single_loss))` only for per-sample gradients, influence functions, uncertainty, or diagnostics; it can be memory-heavy. Read `references/brainstate/transformation-grad-expansion.md` before exact state/argument gradient edits.
281
+
282
+ ### F. JIT boundary: compile the largest stable unit
283
+
284
+ Prefer:
285
+
286
+ ```python
287
+ @brainstate.transform.jit
288
+ def train_step(batch):
289
+ loss = ...
290
+ grads = ...
291
+ optimizer.update(grads)
292
+ return loss, metrics
293
+ ```
294
+
295
+ Avoid:
296
+
297
+ ```python
298
+ for t in range(T):
299
+ y = brainstate.transform.jit(tiny_op)(x[t])
300
+ ```
301
+
302
+ Common good boundaries:
303
+
304
+ ```text
305
+ step if called many times and shape-stable
306
+ run when it contains scan/control flow
307
+ loss_fn when repeatedly evaluated
308
+ train_step best boundary for training: forward + loss + grad + optimizer update
309
+ ```
310
+
311
+ Read `references/brainstate/transformation-jit-expansion.md` before changing static args, diagnosing recompilation, or replacing raw `jax.jit` around stateful code.
312
+
313
+ ### G. Composition patterns
314
+
315
+ Use these as intent patterns, then adapt to local BrainState API:
316
+
317
+ ```text
318
+ single trial over time: jit(scan(step))
319
+ batch of independent trials: jit(vmap(run_one_trial))
320
+ time loop with batched state: jit(scan(vmapped_step_or_batched_step))
321
+ ensemble of models: jit(vmap(run_one_model, mapped states))
322
+ normal training: jit(train_step using grad(loss_over_batch))
323
+ per-sample gradients: jit(vmap(grad(single_sample_loss)))
324
+ long differentiable sequence: jit(checkpointed_scan(step))
325
+ multi-device batch/ensemble/shard: pmap2/shard_map after single-device cleanup
326
+ ```
327
+
328
+ Axis order matters. Choose the order that preserves state semantics and minimizes memory. For example, `vmap(scan(step))` creates independent trials with independent recurrent state; `scan(vmap(step))` uses a time loop whose step is already batched.
329
+
330
+ ### H. Randomness
331
+
332
+ Tiny RNG block: use one reproducible root seed or stream, then split/fold/map independent randomness for trials, parameter sweeps, stochastic dynamics, dropout/noise, and transformed execution. Route deeper seed/key restoration details to `references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md`.
333
+
334
+ Bad:
335
+
336
+ ```python
337
+ for b in range(B):
338
+ y = run_one(xs[b], key) # same key reused
339
+ ```
340
+
341
+ Good intent:
342
+
343
+ ```text
344
+ one reproducible root seed/stream
345
+ split/fold/map independent keys for B/E/trials
346
+ split or advance per time step when stochastic dynamics require it
347
+ store RNG in BrainState-compatible state/stream if transformed code mutates it
348
+ ```
349
+
350
+ Under `vmap`, verify each mapped element receives independent randomness. RNG correctness is part of validation, not a style preference.
351
+
352
+ ### I. Multi-device `D`
353
+
354
+ Use `pmap2`, `shard_map`, or explicit sharding only after the single-device program is already transform-friendly. Good candidates: large independent trials, large ensembles, or explicit population/connectivity shards. Bad candidates: tiny Python-bound loops, logging-heavy code, shape-changing workloads, or dense memory blow-ups.
355
+
356
+ ## Implementation sequence for Codex-style agents
357
+
358
+ 1. **Do not rewrite immediately.** First produce an inventory and pattern table.
359
+ 2. **Pick the highest-impact axis.** Usually `T`, then `N`, then `B/E`, then `P`, then `D`.
360
+ 3. **Read reference markdowns only for transforms you will actually use.** Do not load all references by default.
361
+ 4. **Write or identify a tiny deterministic test before refactoring.** Include final state checks, not only outputs.
362
+ 5. **Refactor one semantic unit at a time.** Keep public APIs stable unless the user asks for deeper redesign.
363
+ 6. **Preserve exact state ownership.** When changing `vmap`, explicitly document which states are shared, mapped, written back, or discarded.
364
+ 7. **Preserve RNG semantics or intentionally improve them.** Document seed/key splitting.
365
+ 8. **Avoid cosmetic churn.** Do not convert low-impact host setup code from `np` to `jnp` unless it enters transforms.
366
+ 9. **Benchmark warm execution only after correctness.** Include compile time separately if measured.
367
+ 10. **Leave API assumptions visible.** If BrainState syntax is uncertain, mark it and point to the needed reference markdown/test.
368
+
369
+ ## Validation gates
370
+
371
+ A rewrite is not done until these are addressed:
372
+
373
+ | Gate | Required check |
374
+ |---|---|
375
+ | Outputs | old vs new on tiny deterministic input, with tolerance stated |
376
+ | Final state | compare final `State`/`ParamState` values where semantics require it |
377
+ | Shape stability | same shapes/dtypes/PyTree across repeated calls; no accidental recompiles |
378
+ | RNG | independent mapped trials/seeds; reproducible root seed behavior |
379
+ | Gradients | finite gradients; intended `ParamState`s receive grads; tiny training step moves loss or parameter in expected direction |
380
+ | Timing | cold compile separated from warm runtime; synchronize before timing when needed |
381
+ | Memory | full-history vs summary scan choice justified; no accidental dense `[N,N]` blow-up |
382
+ | State under `vmap` | shared vs independent state documented and tested |
383
+ | Host sync | no print/item/float/np.asarray in hot path except debug-only code |
384
+
385
+ ## When not to transform
386
+
387
+ Be realistic. A transform may not help when:
388
+
389
+ - the workload is tiny and compile overhead dominates;
390
+ - the hot path is already a large fused `jnp`/XLA operation;
391
+ - runtime shapes genuinely change each call and cannot be bucketed/masked;
392
+ - performance is limited by memory bandwidth or sparse representation choices;
393
+ - I/O, logging, plotting, or Python data loading dominates;
394
+ - the proposed rewrite would densify a sparse/event model;
395
+ - state/RNG semantics are not understood well enough to preserve correctness.
396
+
397
+ In these cases, report the bottleneck and propose a safer benchmark or representation change instead of forcing `jit`/`vmap`.
398
+
399
+ ## Required response format when using this skill
400
+
401
+ ```markdown
402
+ ## BrainX acceleration audit
403
+
404
+ | File/area | Pattern | Evidence | Axis | Impact | Risk | Rewrite | Confidence |
405
+ |---|---|---|---|---|---|---|---|
406
+ | ... | `loop-T-python` | `for t ... step(...)` | T | High | Medium | `scan` inside `jit` | High |
407
+
408
+ ## Patch / rewrite plan
409
+
410
+ [Small concrete diff or code blocks. State which reference markdown was used for exact transform semantics. State API assumptions if any.]
411
+
412
+ ## Validation plan
413
+
414
+ [Old/new tiny test, final-state check, RNG check, shape/recompile check, gradient check if training, warm timing method.]
415
+
416
+ ## Remaining risks
417
+
418
+ [State sharing, RNG independence, sparse/dense memory, dynamic shapes, numerical differences, unresolved API questions.]
419
+ ```
420
+
421
+ If the user asks for an actual code rewrite, include the patch. If the user asks only for an audit, do not rewrite yet; provide the table and prioritized plan.
422
+
423
+
424
+ ## Reference routing
425
+
426
+ Do not guess exact BrainState transform syntax when changing transform behavior. `skills/brainstate/SKILL.md` is the required upstream route before any nontrivial State-aware rewrite.
427
+
428
+ This skill owns local transform and randomness references for the exact semantics it audits:
429
+
430
+ ```text
431
+ brainx-acceleration-audit/
432
+ ├── brainstate/
433
+ │ ├── brainstate-control-flow-patterns.md
434
+ │ ├── transformation-jit-expansion.md
435
+ │ ├── transformation-vmap-expansion.md
436
+ │ └── transformation-grad-expansion.md
437
+ └── brainstate-randomness-reproducibility/
438
+ └── randomness-and-reproducibility.md
439
+ └── advanced-randomness.md
440
+ ```
441
+
442
+ ### First-layer routes
443
+
444
+ | Route | Open when |
445
+ |---|---|
446
+ | `skills/brainstate/SKILL.md` | Any nontrivial State-aware rewrite |
447
+ | `skills/brainx-acceleration-audit/references/brainstate/transformation-jit-expansion.md` | JIT boundaries, static arguments, recompilation, or benchmarking |
448
+ | `skills/brainx-acceleration-audit/references/brainstate/transformation-vmap-expansion.md` | Batch, trial, ensemble, State-axis, or RNG mapping |
449
+ | `skills/brainx-acceleration-audit/references/brainstate/transformation-grad-expansion.md` | Finite-difference replacement, training gradients, or `ParamState` differentiation |
450
+ | `skills/brainx-acceleration-audit/references/brainstate/brainstate-control-flow-patterns.md` | Time or recurrent loops, `scan`, `for_loop`, `while_loop`, or checkpointing |
451
+ | `skills/brainx-acceleration-audit/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md` | Seed/key restoration or independent mapped randomness |
452
+
453
+ ### Nested randomness
454
+
455
+ The acceleration skill and its transform references route only to the local randomness parent. That parent alone may select `skills/brainx-acceleration-audit/references/brainstate-randomness-reproducibility/advanced-randomness.md` for advanced stream, mapped-key, or restoration behavior. Do not route directly to the advanced child.
456
+
457
+ ## Script references
458
+
459
+ No fixed or standalone script is bundled with this skill. Build validation cases from the code under audit.
@@ -7,32 +7,24 @@ description: Use first for every BrainX modeling, simulation, training, review,
7
7
 
8
8
  ## Purpose and boundary
9
9
 
10
- Route every BrainX modeling, simulation, training, review, debugging, or optimization task to the package skills that own it, then enforce the ecosystem-wide rules that no single package skill owns: never mine the installed packages for knowledge, write BrainX-native code, prefer high-level APIs, and transform stateful execution.
10
+ Use this guard first to identify the represented modeling scales, open their owning package skills, and keep package orchestration ahead of lower-level infrastructure. Keep it active for cross-cutting API selection, execution, interoperability, and validation decisions.
11
11
 
12
- This skill supplies no modeling APIs of its own. It selects the owning skills and hands the task to them; every signature, constructor, and workflow comes from those skills and their references.
13
-
14
- ## Never inspect BrainX packages in the venv for knowledge
15
-
16
- Treat BrainX packages in the active virtual environment only as execution dependencies, never as sources of modeling knowledge.
17
-
18
- - **ONLY check presence.** Determine whether each required BrainX package is present, then stop inspecting the environment.
19
- - **NEVER investigate installed content.** Do not enumerate package files, modules, symbols, signatures, docstrings, runtime definitions, or object internals.
20
- - **NEVER read installed source code.** Do not open or read any BrainX source code in the virtual environment.
12
+ ## Check package presence without inspecting installed BrainX
21
13
 
14
+ Treat installed BrainX packages only as execution dependencies: check whether each required package is importable, then move to the owning skills or route an absent package to BrainX-install. Never inspect installed versions, metadata, files, modules, symbols, signatures, docstrings, runtime definitions, source code, or object internals for modeling knowledge.
22
15
 
23
16
  ## Study modeling skills and task-relevant scripts
24
17
 
25
- 1. Treat the selected modeling skills as the authoritative guide to BrainX modeling, dive deep into the skill.
26
- 2. Follow the skill's exact routing instructions. Open every reference that are likely relevant by the user's task.
18
+ 1. Treat the selected modeling skills as the authoritative guides to BrainX modeling. Read each selected skill completely.
19
+ 2. Follow each skill's exact routing instructions. Open every reference likely to affect the user's task.
27
20
  3. Identify the example scripts referenced by the skill or its routed references. Open and study every script that is highly related to the user's task.
28
21
  4. Trace each relevant script end to end.
29
- 5. Derive the implementation from those canonical patterns, then adapt only the parts required by the user's scientific model.
30
-
31
-
22
+ 5. Reconcile each script with the current root skill before copying infrastructure. Keep its scientific pattern, but replace superseded low-level execution with the owning package's current canonical API.
23
+ 6. Derive the implementation from the reconciled patterns, then adapt only the parts required by the user's scientific model.
32
24
 
33
25
  ## Select modeling skills by represented scale
34
26
 
35
- Select every row supported by the user's task. A single-scale task opens one modeling skill; a multiscale task may open two or all three of the scale skills.
27
+ Select every row supported by the user's task. A single-scale task opens one modeling skill; a multiscale task may open two or all three.
36
28
 
37
29
  | The task explicitly represents | Open |
38
30
  |---|---|
@@ -44,21 +36,27 @@ Select every row supported by the user's task. A single-scale task opens one mod
44
36
  | Cellular mechanisms coupled to aggregate neural-mass dynamics | BrainCell + BrainMass |
45
37
  | Cellular biophysics, point-neuron networks, and aggregate population dynamics interacting in one workflow | BrainCell + BrainPy-State + BrainMass |
46
38
 
47
- ## Also select skills by cross-cutting concern
39
+ Keep the implementation at the selected scale. Do not introduce aggregate population-rate State into a point-neuron model, or point neurons into an aggregate model, merely to simplify execution. When both mechanisms are scientifically represented, treat the task as multiscale and open both owning skills.
48
40
 
49
- Scale is not the only axis. Open each row whose concern the task contains, in addition to every scale skill selected above.
41
+ ## Write BrainX-native code
50
42
 
51
- | The task also involves | Open |
52
- |---|---|
53
- | Physical quantities, units, dimensional mismatches, unit-aware math, or suspicious bare numbers | BrainUnit |
54
- | Mutable State and `.value`, Module graphs, state initialization, environment scoping, or state-aware `jit`/`grad`/`vmap` | BrainState |
55
- | Binary firing events, sparse or probabilistic connectivity, spike-driven postsynaptic input, or activity-dependent weight changes | BrainEvent |
56
- | Eligibility-trace online learning, D-RTRL or pp-prop selection, or training a recurrent or spiking model without BPTT | BrainTrace |
57
- | Installing, upgrading, pinning, migrating, or removing BrainX packages | BrainX-Install |
43
+ Start from the scientific concept and use the selected BrainX skills to construct the workflow. Keep ordinary Python, NumPy, or JAX at explicit boundaries for documented dimensionless model inputs, host-side statistics, serialization, timing, device reporting, or custom presentation logic. Preserve units and State until that boundary, and verify an API gap before writing generic numerical infrastructure.
58
44
 
59
- ## Write BrainX-native code
45
+ ## Import package namespaces once
46
+
47
+ Import each required BrainX package once, then access its APIs through the package namespace. Use `import brainunit as u` for BrainUnit and the full package name for other BrainX packages. This keeps API ownership visible and avoids parallel aliases for the same package.
48
+
49
+ ```python
50
+ import brainmass
51
+ import brainstate
52
+ import braintools
53
+ import brainunit as u
54
+ ```
55
+ Do not import functions or classes individually.
56
+ ## Enforce absolute coding simplicity
57
+
58
+ Invest substantial effort before coding. Study every routed skill, relevant example and reference, and authoritative BrainX API needed to understand the task and discover which BrainX operations remove custom logic. Then deliver absolutely simple code. Simplicity is an output criterion, not permission to skip study or guess an API.
60
59
 
61
- Start from the scientific concept and use the selected BrainX skills to construct the workflow. Avoid raw NumPy or JAX unless at an explicit interoperability boundary or after verifying an API gap.
62
60
 
63
61
  ## Prefer high-level BrainX APIs
64
62
 
@@ -66,40 +64,72 @@ Use high-level APIs as the abstraction boundary: simulation code should state th
66
64
 
67
65
  | Need | Prefer |
68
66
  |---|---|
69
- | array creation or structure, mathematical operations | BrainUnit quantities and `brainunit.math` |
70
- | Connectivity, encoding, inputs, initialization, integration, metrics, optimization, surrogate gradients, training, visualization | `braintools` |
71
-
67
+ | Package-owned simulation, fitting, training, or analysis | The selected modeling package's named orchestrator or Module, such as `brainmass.Simulator`, `Network`, `Fitter`, or `brainmass.viz` |
68
+ | Physical quantities, unit-aware arrays, or mathematical operations | BrainUnit quantities and `brainunit.math` |
69
+ | State, randomness, initialization, environments, or State-aware transforms | BrainState, after checking whether the selected package orchestrator already owns the operation |
70
+ | Connectivity, encoding, inputs, integration, metrics, optimization, surrogate gradients, training, or visualization | `braintools` |
72
71
 
73
72
  Do not let code grow around manual indexing, reshaping, reductions, equations, loops, or bookkeeping. Prefer one named BrainX operation or Module over a chain of generic primitives.
74
73
 
75
74
  Write custom logic only when it expresses model behavior that the ecosystem does not already provide. Verify the owning skill, reference, or official API page before using an unfamiliar name or signature.
76
75
 
77
- ## Keep plotting code short without lowering figure quality
76
+ Use the highest-level API in the selected owning package that preserves the scientific operation. Open lower-level BrainState control flow only when the package orchestrator cannot express the required inputs, monitors, State effects, or stable compilation boundary.
77
+
78
+ ## Validate scientific claims
79
+
80
+ Derive claims from observables that distinguish the claimed mechanism; validate the baseline and mechanism before calibration, and mark unsourced calibrated regimes as phenomenological.
81
+
82
+ - Freeze parameters, evaluation seeds, metrics or scores, thresholds or windows, and displayed cases before viewing intervention outcomes; otherwise calibrate separately and report held-out or nearby sensitivity.
83
+ - Validate each matched control independently, then compare and save control and intervention evidence at every nuisance setting and aligned physical time or event landmark; a normalized summary is not a substitute for those paired observables.
84
+ - At each causal branch, verify and save every relevant State and protocol input, vary only the declared intervention, and preserve per-condition evidence plus its aggregation. State causality at the intervention level; claim event mediation only when a mediator-specific manipulation and per-condition event dose agree with the outcome.
85
+ - Apply each claim's full temporal predicate: require time-resolved source-to-route-to-target order for propagation and exact element order for sequence direction rather than a regression sign or proxy. Identify supplied drive or retained boundary State as an external seed even when stochastic.
86
+ - For categorical maps, retain every continuous boundary observable, plot and save the exact reduction tested at each threshold, and verify each label's full predicate. Require measured departure before sustained recovery, and never force a requested category to appear.
87
+ - Claim an interval or region only when sampling resolves its extent across multiple points; otherwise report a sampled point or optimum and refine the sampling.
88
+
89
+ Run independent controls and mechanism checks in the same mapped or batched path as the intervention.
78
90
 
79
- Use high-level `matplotlib.pyplot` APIs for standard scientific plots. Prefer a compact sequence of `plt.figure()`, `plt.plot()`, labeling, layout, and display calls over low-level Figure, Axes, Artist, or styling machinery when the high-level API expresses the same figure clearly.
91
+ ## Keep visualization simple without lowering figure quality
80
92
 
93
+ Use the simplest highest-level API that expresses the required scientific figure. Prefer the selected BrainX package's visualization API, such as `brainmass.viz`, then BrainTools visualization APIs, then high-level `matplotlib.pyplot`.
81
94
 
82
- Brevity applies to the code, not the figure's scientific content or visual quality.
95
+ Write absolutely simple Matplotlib code: compose every figure with exactly one `plt.subplots(...)` call and only basic high-level plotting methods. Use `plt.figure`, `GridSpec`, `add_subplot`, projection-specific axes, custom artists, manual axes placement, style systems, or layout scaffolding only when the user explicitly requests a result that `subplots()` cannot express.
83
96
 
97
+ Simplicity applies to implementation, not scientific content or figure quality. Preserve intentional size, units, readable labels, title, comparison styles, legend, unclipped layout, and sufficient output resolution.
84
98
 
85
99
  ## Transform stateful execution
86
100
 
87
- Transform the complete stateful operation with `brainstate.transform` whenever practical.
101
+ Use the owning package's orchestrator for workflows it already implements. When a custom stateful operation is necessary, transform the complete operation with `brainstate.transform`.
88
102
 
89
103
  | API | Use |
90
104
  |---|---|
91
- | `brainstate.transform.jit`, `grad`, `vmap` | Compile, differentiate, or batch a complete stateful forward, simulation, or training operation. |
105
+ | `brainstate.transform.jit` | Compile a complete custom stateful operation. Construct one stable callable outside warm-up and timed repetitions when measuring compilation or steady execution. |
106
+ | `brainstate.transform.grad` | Differentiate a complete custom stateful forward, simulation, or training operation. |
107
+ | `brainstate.transform.vmap` | Batch a complete custom stateful operation when the owning package does not already expose the required batch axis. |
92
108
  | `brainstate.transform.for_loop` | Run a fixed time or data sequence when iteration-to-iteration effects live in `State`; it slices leading input axes and stacks per-step outputs. |
93
109
  | `brainstate.transform.scan` | Run a sequence when an ordinary explicit carry must pass between iterations. |
94
110
 
95
- Do not use a Python loop for simulation timesteps, recurrent sequences, or other repeated State updates that should execute as one compiled operation.
111
+ Do not add a transform only to construct parameter axes or satisfy a named-API checklist. When the owning package already represents independent conditions through a native batch or `size` axis, use that path and reserve `vmap` for a callable the owning package does not already batch.
112
+
113
+ Map only independent operations. If trial N mutates weights or other State that trial N+1 consumes, keep those trials sequential; batch only independent evaluation trials or ensembles, with separate dynamical State and deliberately shared read-only State. Mapping input construction or offline scoring does not batch the stateful simulation itself. Open `skills/package-skills/brainstate/references/brainstate/transformation-vmap-expansion.md` when a complete mapped operation reads or writes State, for the State-axis contracts and independent-lane pattern.
114
+
115
+ A mapped complete per-step transition called inside one `for_loop` is a stateful simulation batch: the mapping owns independent conditions and the loop owns time. Select mapped State by semantic role, such as `Any(OfType(HiddenState), OfType(ShortTermState))`; do not infer State ownership from array rank, shape, or a coincidental leading size. Open `skills/package-skills/brainstate/references/brainstate/transformation-vmap-expansion.md` for the canonical initialization, mapping, and loop composition.
116
+
117
+ Describe the transform that actually runs. Native batched State, vmapped input construction, and vmapped host scoring are not stateful `vmap`. When the user explicitly requires `vmap`, map the complete independent operation or report why the requirement cannot be met.
118
+
119
+ Separate dependency order from State lifetime. When only learned or long-term State must carry from trial N to trial N+1, preserve that State but reset membrane, refractory, delay, trace, and other per-trial State at the logical boundary unless continuous carryover is part of the model. A silent interval advances State; it does not reset it.
120
+
121
+ Do not use a Python loop for simulation timesteps, recurrent sequences, or repeated State updates inside one logical rollout. A small host loop is valid across causally sequential trials when each iteration calls one compiled trial rollout and the boundary must reset selected State while preserving learned State.
96
122
 
97
123
  Use raw JAX transformations only for pure array or PyTree functions that do not close over BrainState `State`.
98
124
 
99
125
  ## Boundaries and common failures
100
126
 
101
127
  - Generic NumPy or JAX used as the starting architecture for a BrainX simulation.
128
+ - BrainX functions or classes imported individually when the package namespace already exposes them.
129
+ - Point-neuron and aggregate population mechanisms mixed without selecting both owning skills or declaring the multiscale boundary.
130
+ - A custom BrainState loop that duplicates the selected package's runner, inputs, monitoring, initialization, or sampling.
102
131
  - Manual array or mathematical machinery that duplicates BrainUnit or BrainTools.
103
- - Python loops around stateful simulation or training steps.
132
+ - Python timestep loops or host loops inside a stable logical rollout.
104
133
  - Raw `jax.jit`, `jax.grad`, or `jax.vmap` applied to State-aware code.
134
+ - Host-side statistics, serialization, timing, device reporting, or custom presentation forced into BrainX without an owning API.
105
135
  - Fabricated APIs or signatures accepted without checking the owning documentation.