brainx-skill 1.0.12 → 1.0.14

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 (226) hide show
  1. package/README.md +30 -0
  2. package/installation/lib/bundle.js +51 -13
  3. package/installation/lib/cli.js +16 -4
  4. package/installation/lib/literature-mcp.js +536 -0
  5. package/manifest.json +4 -0
  6. package/mcp-servers/codex/README.md +82 -0
  7. package/mcp-servers/codex/UPSTREAM.md +22 -0
  8. package/mcp-servers/codex/server.mjs +142 -0
  9. package/mcp-servers/codex/skills.json +10 -0
  10. package/mcp-servers/codex/system-prompt.md +73 -0
  11. package/mcp-servers/codex/test/fixtures/fake-codex.mjs +6 -0
  12. package/mcp-servers/codex/test/server.test.mjs +99 -0
  13. package/mcp-servers/fulltext-resolver/README.md +136 -0
  14. package/mcp-servers/fulltext-resolver/REUSE.md +32 -0
  15. package/mcp-servers/fulltext-resolver/THIRD_PARTY_NOTICES.md +57 -0
  16. package/mcp-servers/fulltext-resolver/server.mjs +128 -0
  17. package/mcp-servers/fulltext-resolver/src/document.mjs +253 -0
  18. package/mcp-servers/fulltext-resolver/src/http.mjs +173 -0
  19. package/mcp-servers/fulltext-resolver/src/identifiers.mjs +123 -0
  20. package/mcp-servers/fulltext-resolver/src/model.mjs +105 -0
  21. package/mcp-servers/fulltext-resolver/src/resolver.mjs +305 -0
  22. package/mcp-servers/fulltext-resolver/src/sources/biorxiv.mjs +135 -0
  23. package/mcp-servers/fulltext-resolver/src/sources/europe-pmc.mjs +132 -0
  24. package/mcp-servers/fulltext-resolver/src/sources/openalex.mjs +165 -0
  25. package/mcp-servers/fulltext-resolver/test/document.test.mjs +82 -0
  26. package/mcp-servers/fulltext-resolver/test/resolver.test.mjs +287 -0
  27. package/mcp-servers/fulltext-resolver/test/server.test.mjs +63 -0
  28. package/mcp-servers/fulltext-resolver/test/sources.test.mjs +229 -0
  29. package/package.json +14 -10
  30. package/skills/bio-neuro-lit/SKILL.md +206 -0
  31. package/skills/bio-neuro-lit/THIRD_PARTY_NOTICES.md +34 -0
  32. package/skills/bio-neuro-lit/agents/openai.yaml +4 -0
  33. package/skills/bio-neuro-lit/references/tool-contracts.md +73 -0
  34. package/skills/bio-neuro-lit/scripts/deepxiv_fetch.py +110 -0
  35. package/skills/bio-neuro-lit/scripts/exa_search.py +190 -0
  36. package/skills/brainx-acceleration/SKILL.md +459 -0
  37. package/skills/brainx-general-guard/SKILL.md +31 -9
  38. package/skills/brainx-modeling-loop/SKILL.md +281 -0
  39. package/skills/brainx-modeling-loop/agents/openai.yaml +4 -0
  40. package/skills/brainx-modeling-loop/references/monitor-experiment.md +49 -0
  41. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow/scripts/fitting_hh_neuron.py +254 -0
  42. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +272 -0
  43. package/skills/brainx-modeling-loop/references/run-experiment.md +179 -0
  44. package/skills/brainx-modeling-loop/references/training-workflow.md +270 -0
  45. package/skills/brainx-visualization/SKILL.md +157 -0
  46. package/skills/brainx-visualization/agents/openai.yaml +4 -0
  47. package/skills/brainx-visualization/references/interactive-and-visualization-styling.md +155 -0
  48. package/skills/brainx-visualization/references/neural-data-visualization.md +141 -0
  49. package/skills/brainx-visualization/references/statistical-and-model-visualization.md +133 -0
  50. package/skills/{braincell → package-skills/braincell}/SKILL.md +17 -6
  51. package/skills/package-skills/braincell/references/braintools/input-current.md +200 -0
  52. package/skills/package-skills/braincell/references/braintools/optimizer.md +179 -0
  53. package/skills/{braincell → package-skills/braincell}/references/multicompartment/multicompartment-cell-workflow.md +2 -2
  54. package/skills/package-skills/braincell/references/scripts/fitting_hh_neuron.py +254 -0
  55. package/skills/{brainmass → package-skills/brainmass}/references/brainstate/parameter-constraints-regularization.md +1 -1
  56. package/skills/{brainmass → package-skills/brainmass}/references/coupling-network-api.md +121 -3
  57. package/skills/{brainmass → package-skills/brainmass}/references/modellibrary.md +79 -1
  58. package/skills/package-skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +188 -0
  59. package/skills/{brainmass → package-skills/brainmass}/references/visualization-analysis-api.md +6 -6
  60. package/skills/{brainpy-state → package-skills/brainpy-state}/SKILL.md +4 -3
  61. package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/connectivity.md +1 -1
  62. package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/input-current.md +1 -1
  63. package/skills/package-skills/brainpy-state/references/braintools/metric.md +152 -0
  64. package/skills/package-skills/brainpy-state/references/perturbation-experiment-validity.md +76 -0
  65. package/skills/{brainpy-state → package-skills/brainpy-state}/references/projection-patterns.md +1 -1
  66. package/skills/{brainstate → package-skills/brainstate}/SKILL.md +1 -0
  67. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/brainstate-transformed-diagnostics.md +1 -1
  68. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/parameter-constraints-regularization.md +1 -1
  69. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/randomness-and-reproducibility.md +1 -1
  70. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-grad-expansion.md +2 -2
  71. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-vmap-expansion.md +1 -1
  72. package/skills/{brainstate → package-skills/brainstate}/references/libraries/prebuilt-layer-library.md +1 -1
  73. package/skills/package-skills/brainstate/references/paired-perturbation-execution.md +113 -0
  74. package/skills/package-skills/braintrace/SKILL.md +187 -0
  75. package/skills/package-skills/braintrace/references/Drtrl.md +133 -0
  76. package/skills/{braintrace → package-skills/braintrace}/references/ETP operators.md +31 -4
  77. package/skills/package-skills/braintrace/references/algorithm selection.md +64 -0
  78. package/skills/package-skills/braintrace/references/batching.md +140 -0
  79. package/skills/{braintrace → package-skills/braintrace}/references/compiler_internal.md +2 -2
  80. package/skills/{braintrace → package-skills/braintrace}/references/custom algorithms.md +8 -10
  81. package/skills/package-skills/braintrace/references/pp_pprop workflow.md +179 -0
  82. package/skills/{braintrace → package-skills/braintrace}/references/pre-built-braintrace-layer.md +2 -2
  83. package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +0 -130
  84. package/skills/braintrace/SKILL.md +0 -161
  85. package/skills/braintrace/references/Drtrl.md +0 -179
  86. package/skills/braintrace/references/algorithm selection.md +0 -120
  87. package/skills/braintrace/references/batching.md +0 -150
  88. package/skills/braintrace/references/pp_pprop workflow.md +0 -196
  89. /package/skills/{braincell → package-skills/braincell}/references/area-scaled-hh-pattern.md +0 -0
  90. /package/skills/{braincell → package-skills/braincell}/references/braincell-custom-ion-channel-authoring.md +0 -0
  91. /package/skills/{brainpy-state → package-skills/braincell}/references/braintools/metric.md +0 -0
  92. /package/skills/{braincell → package-skills/braincell}/references/channel-library.md +0 -0
  93. /package/skills/{braincell → package-skills/braincell}/references/ion-library.md +0 -0
  94. /package/skills/{braincell → package-skills/braincell}/references/mixions-for-adaptation.md +0 -0
  95. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/braincell-manual-morphology-construction.md +0 -0
  96. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/cv-policy-reference.md +0 -0
  97. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/filter-function-library.md +0 -0
  98. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/morphology-io-loading-validation.md +0 -0
  99. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/probe-reference.md +0 -0
  100. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/topology-building-and-visualization.md +0 -0
  101. /package/skills/{braincell → package-skills/braincell}/references/scripts/calcium_channel_gating.py +0 -0
  102. /package/skills/{braincell → package-skills/braincell}/references/scripts/cell_multicompartment_reference.py +0 -0
  103. /package/skills/{braincell → package-skills/braincell}/references/scripts/channel_ablation.py +0 -0
  104. /package/skills/{braincell → package-skills/braincell}/references/scripts/fi_curve.py +0 -0
  105. /package/skills/{braincell → package-skills/braincell}/references/scripts/hh_neuron_basics.py +0 -0
  106. /package/skills/{braincell → package-skills/braincell}/references/scripts/spike_frequency_adaptation.py +0 -0
  107. /package/skills/{braincell → package-skills/braincell}/references/scripts/t_current_rebound.py +0 -0
  108. /package/skills/{braincell → package-skills/braincell}/references/scripts/thalamic_neurons.py +0 -0
  109. /package/skills/{braincell → package-skills/braincell}/references/solver-library-with-effects.md +0 -0
  110. /package/skills/{brainevent → package-skills/brainevent}/SKILL.md +0 -0
  111. /package/skills/{brainevent → package-skills/brainevent}/references/connectivity-variants.md +0 -0
  112. /package/skills/{brainevent → package-skills/brainevent}/references/custom-operators-cpu.md +0 -0
  113. /package/skills/{brainevent → package-skills/brainevent}/references/custom-operators-gpu.md +0 -0
  114. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/102_EI_net_1996.py +0 -0
  115. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/204_joglekar_2018_propagation.py +0 -0
  116. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/coba_ei_teaching.py +0 -0
  117. /package/skills/{brainevent → package-skills/brainevent}/references/sparse-formats.md +0 -0
  118. /package/skills/{brainevent → package-skills/brainevent}/references/synaptic-plasticity.md +0 -0
  119. /package/skills/{brainmass → package-skills/brainmass}/SKILL.md +0 -0
  120. /package/skills/{brainmass → package-skills/brainmass}/references/batch-transform-acceleration.md +0 -0
  121. /package/skills/{brainmass → package-skills/brainmass}/references/brainstate/parameter-transforms-regularizers-catalog.md +0 -0
  122. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/cogtask.md +0 -0
  123. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/data-preprocessing.md +0 -0
  124. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/metric.md +0 -0
  125. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/optimizer.md +0 -0
  126. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/parameter-initializer.md +0 -0
  127. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/surrogate.md +0 -0
  128. /package/skills/{brainmass → package-skills/brainmass}/references/datasets-api.md +0 -0
  129. /package/skills/{brainmass → package-skills/brainmass}/references/fitting-with-objectives-api.md +0 -0
  130. /package/skills/{brainmass → package-skills/brainmass}/references/forward-observation-api.md +0 -0
  131. /package/skills/{brainmass → package-skills/brainmass}/references/horn-task-training.md +0 -0
  132. /package/skills/{brainmass → package-skills/brainmass}/references/noiseprocesses.md +0 -0
  133. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/eeg-fitting-with-gradients.py +0 -0
  134. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/gradient-free-fitting.py +0 -0
  135. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/hopf-bifurcation-single-node.py +0 -0
  136. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/horn-cognitive-task-training.py +0 -0
  137. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/jansen-rit-eeg-proxy.py +0 -0
  138. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/kuramoto-synchronization.py +0 -0
  139. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/linear-baseline-node.py +0 -0
  140. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/resting-state-meg-whole-brain-pipeline.py +0 -0
  141. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/seizure-epileptor-case-study.py +0 -0
  142. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wilson-cowan-ei-dynamics.py +0 -0
  143. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wong-wang-decision-making.py +0 -0
  144. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wong-wang-dmf-resting-state.py +0 -0
  145. /package/skills/{brainmass → package-skills/brainmass}/references/simulator-input-monitor-api.md +0 -0
  146. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/array-creation.md +0 -0
  147. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brain-dynamics-delay-protocol.md +0 -0
  148. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/analysis.md +0 -0
  149. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/brainpy legacy workflow.md +0 -0
  150. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/built-in dynamic neuron model.md +0 -0
  151. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/connecting neurons.md +0 -0
  152. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/customize neuron and synpase.md +0 -0
  153. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Input generation.md +0 -0
  154. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/More about simulation.md +0 -0
  155. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +0 -0
  156. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +0 -0
  157. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +0 -0
  158. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +0 -0
  159. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/delays.md +0 -0
  160. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +0 -0
  161. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/integrators.md +0 -0
  162. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/route activity through connectivity.md +0 -0
  163. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/synaptic projections.md +0 -0
  164. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/synpase properties.md +0 -0
  165. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/loss library.md +0 -0
  166. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/optimizers.md +0 -0
  167. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/parameter initializers.md +0 -0
  168. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/prebuilt neural network layers.md +0 -0
  169. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/surrogate gradients.md +0 -0
  170. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/trainer library.md +0 -0
  171. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/trainingworkflows.md +0 -0
  172. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/brainstate-control-flow-patterns.md +0 -0
  173. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/data-preprocessing.md +0 -0
  174. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/optimizer.md +0 -0
  175. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/parameter-initializer.md +0 -0
  176. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/surrogate.md +0 -0
  177. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/component-selection.md +0 -0
  178. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/devices.md +0 -0
  179. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/divergence-and-parity.md +0 -0
  180. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/integration-categories.md +0 -0
  181. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/model-library.md +0 -0
  182. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/nest-workflow.md +0 -0
  183. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/network-building.md +0 -0
  184. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brette_et_al_2007.py +0 -0
  185. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brunel_alpha.py +0 -0
  186. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brunel_delta.py +0 -0
  187. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +0 -0
  188. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +0 -0
  189. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/spatial_gaussex.py +0 -0
  190. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/synapsecollection.py +0 -0
  191. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/synapse-and-connectivity.md +0 -0
  192. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/103_COBA_2005.py +0 -0
  193. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/106_COBA_HH_2007.py +0 -0
  194. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/107_gamma_oscillation_1996.py +0 -0
  195. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/109_fast_global_oscillation.py +0 -0
  196. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +0 -0
  197. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/sound_localization.py +0 -0
  198. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/training-snn.py +0 -0
  199. /package/skills/{brainstate → package-skills/brainstate}/agents/openai.yaml +0 -0
  200. /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/brainstate-control-flow-patterns.md +0 -0
  201. /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/parameter-transforms-regularizers-catalog.md +0 -0
  202. /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-jit-expansion.md +0 -0
  203. /package/skills/{brainstate → package-skills/brainstate}/references/collective_model_operations.md +0 -0
  204. /package/skills/{brainstate → package-skills/brainstate}/references/extension_mechanisms.md +0 -0
  205. /package/skills/{brainstate → package-skills/brainstate}/references/libraries/prebuilt-activation-library.md +0 -0
  206. /package/skills/{brainstate → package-skills/brainstate}/references/model-interop-and-migration.md +0 -0
  207. /package/skills/{brainstate → package-skills/brainstate}/references/simulation-environment.md +0 -0
  208. /package/skills/{brainstate → package-skills/brainstate}/references/size-inference-variations.md +0 -0
  209. /package/skills/{brainstate → package-skills/brainstate}/references/state-graph-operations.md +0 -0
  210. /package/skills/{brainstate → package-skills/brainstate}/references/state_collections_and_utilities.md +0 -0
  211. /package/skills/{brainstate → package-skills/brainstate}/scripts/integrator_rnn.py +0 -0
  212. /package/skills/{brainstate → package-skills/brainstate}/scripts/lif_neuron_model.py +0 -0
  213. /package/skills/{brainstate → package-skills/brainstate}/scripts/modern_cnn.py +0 -0
  214. /package/skills/{brainstate → package-skills/brainstate}/scripts/resnet.py +0 -0
  215. /package/skills/{braintrace → package-skills/braintrace}/references/custom ETP primitives.md +0 -0
  216. /package/skills/{braintrace → package-skills/braintrace}/references/customizing_primitive_transforms.md +0 -0
  217. /package/skills/{brainunit → package-skills/brainunit}/SKILL.md +0 -0
  218. /package/skills/{brainunit → package-skills/brainunit}/references/array-creation.md +0 -0
  219. /package/skills/{brainunit → package-skills/brainunit}/references/array-mechanics/functional-structural-api.md +0 -0
  220. /package/skills/{brainunit → package-skills/brainunit}/references/array-mechanics.md +0 -0
  221. /package/skills/{brainunit → package-skills/brainunit}/references/math-function-library.md +0 -0
  222. /package/skills/{brainunit → package-skills/brainunit}/references/physical-constant-library.md +0 -0
  223. /package/skills/{brainunit → package-skills/brainunit}/references/prefix-library.md +0 -0
  224. /package/skills/{brainunit → package-skills/brainunit}/references/quantity-inspection-and-conversion.md +0 -0
  225. /package/skills/{brainunit → package-skills/brainunit}/references/typing-and-runtime-validation.md +0 -0
  226. /package/skills/{brainunit → package-skills/brainunit}/references/unit-structure-and-definition.md +0 -0
@@ -0,0 +1,179 @@
1
+ # Braintools optimizer selection
2
+
3
+ Use this reference after the BrainCell objective, rollout, State reset, and gradient target are correct. Select an optimizer interface and learning-rate policy without changing the simulation graph or confusing gradient-step optimizers with standalone search wrappers.
4
+
5
+ ## Choose a gradient optimizer
6
+
7
+ Choose the optimizer family by training regime and resource constraint. Ordinary reverse-mode optimizers register the selected `ParamState` tree once and accept the matching gradient tree through `update(grads)`.
8
+
9
+ ### General minibatch optimizers
10
+
11
+ Use these optimizers for ordinary repeated gradient steps; establish `Adam` or `SGD` as the baseline before selecting a specialized update rule.
12
+
13
+ | API | Description |
14
+ |---|---|
15
+ | `SGD(...)` | Use for stochastic gradient descent with optional momentum and weight decay when a simple non-adaptive baseline is required. |
16
+ | `Momentum(...)` | Use for momentum updates without selecting the broader `SGD` interface. |
17
+ | `MomentumNesterov(...)` | Use when the optimization method requires Nesterov-accelerated momentum. |
18
+ | `Adam(...)` | Use as the canonical adaptive default after validating finite, nonzero gradients. |
19
+ | `AdamW(...)` | Use when the training policy requires decoupled weight decay; set `weight_decay` deliberately. |
20
+ | `Adagrad(...)` | Use when per-parameter learning rates should accumulate squared-gradient history. |
21
+ | `Adadelta(...)` | Use when the Adadelta extension of Adagrad is explicitly required. |
22
+ | `RMSprop(...)` | Use when the method should scale updates by a moving average of squared gradients. |
23
+ | `Adamax(...)` | Use when the infinity-norm Adam variant is required. |
24
+ | `Nadam(...)` | Use when combining Adam with Nesterov acceleration. |
25
+ | `RAdam(...)` | Use when rectifying adaptive learning-rate variance addresses observed early-step instability. |
26
+ | `Yogi(...)` | Use when the Yogi additive second-moment update is part of the intended method. |
27
+ | `Rprop(...)` | Use when resilient backpropagation should adapt per-parameter step sizes from gradient signs. |
28
+ | `AdaBelief(...)` | Use when adapting step size from the optimizer's belief in the gradient direction is required. |
29
+ | `Lion(...)` | Use when a sign-momentum optimizer is chosen to reduce optimizer-State memory. |
30
+ | `Novograd(...)` | Use when layer-wise gradient normalization with momentum is required. |
31
+ | `Fromage(...)` | Use only when the Free-scale Optimal Method for Adaptive Gradient method is explicitly selected. |
32
+
33
+ ### Large-scale and memory-efficient optimizers
34
+
35
+ Use these optimizers only when large-batch scaling or optimizer-State memory is an explicit constraint.
36
+
37
+ | API | Description |
38
+ |---|---|
39
+ | `Lamb(...)` | Use for layer-wise adaptive moments in an explicitly large-batch training regime. |
40
+ | `Lars(...)` | Use for layer-wise adaptive rate scaling in an explicitly large-batch training regime. |
41
+ | `Adafactor(...)` | Use when factorized second-moment estimates are needed to reduce optimizer-State memory. |
42
+ | `SM3(...)` | Use for memory-efficient adaptive updates in a large or sparse model. |
43
+
44
+ ### Wrapper and full-batch optimizers
45
+
46
+ Use these variants when the update requires an optimizer composition or a smooth full-batch objective rather than an ordinary standalone minibatch rule.
47
+
48
+ | API | Description |
49
+ |---|---|
50
+ | `Lookahead(...)` | Use when wrapping an inner Optax gradient transformation with periodic slow-weight interpolation. |
51
+ | `LBFGS(...)` | Use for a small, smooth, full-batch problem suited to limited-memory quasi-Newton updates; verify its step contract before replacing a minibatch optimizer. |
52
+
53
+ ### Custom Optax transformations
54
+
55
+ Use the bridge when no named Braintools optimizer expresses the required Optax transformation.
56
+
57
+ | API | Description |
58
+ |---|---|
59
+ | `OptaxOptimizer(tx=..., lr=...)` | Use when supplying a custom Optax transformation while preserving Braintools parameter registration, optimizer State, gradient clipping, weight decay, and scheduler integration. |
60
+
61
+ Do not switch optimizer, scheduler, surrogate, and temporal reduction simultaneously. Establish an `Adam` loss and gradient baseline, then vary one optimization decision.
62
+
63
+ ## Gradient-step lifecycle
64
+
65
+ Every ordinary gradient optimizer owns persistent optimizer State and mutates exactly the registered trainable State:
66
+
67
+ | API | Use and result |
68
+ |---|---|
69
+ | `model.states(brainstate.ParamState)` | Select trainable model State; dynamical voltage, conductance, spike, and delay State remain outside the optimizer. |
70
+ | `optimizer.register_trainable_weights(params)` | Register the parameter tree and initialize optimizer State. |
71
+ | `brainstate.transform.grad(loss_fn, params, return_value=True)` | Produce a gradient tree matching `params` and the scalar loss. |
72
+ | `optimizer.update(grads)` | Apply one update to the registered parameters. |
73
+
74
+ ```python
75
+ params = net.states(brainstate.ParamState)
76
+ optimizer = braintools.optim.Adam(lr=3e-3)
77
+ optimizer.register_trainable_weights(params)
78
+
79
+ @brainstate.transform.jit
80
+ def train_step():
81
+ brainstate.nn.init_all_states(net, batch_size=batch_size)
82
+ grads, loss = brainstate.transform.grad(
83
+ loss_fn,
84
+ params,
85
+ return_value=True,
86
+ )()
87
+ optimizer.update(grads)
88
+ return loss
89
+ ```
90
+
91
+ Register the same tree passed to `grad`. Do not rebuild or re-register that tree inside every compiled step.
92
+
93
+ Use `braintools.optim.UniqueStateManager(...)` only when an arbitrary nested PyTree may contain repeated references to the same `State`; it deduplicates State identity before optimization. An ordinary `model.states(brainstate.ParamState)` collection already expresses the canonical model-owned target.
94
+
95
+ ## Learning-rate schedulers
96
+
97
+ Pass an `LRScheduler` instance as `lr=` to any gradient-based `OptaxOptimizer`. A float is treated as a constant learning rate.
98
+
99
+ | API | Description |
100
+ |---|---|
101
+ | `LRScheduler(...)` | Subclass when implementing a custom schedule; it defines attachment, stepping, current-rate access, and State serialization. |
102
+ | `StepLR(...)` | Use for staircase decay by `gamma` every `step_size` scheduler steps. |
103
+ | `MultiStepLR(...)` | Use for multiplicative decay at explicitly chosen milestones. |
104
+ | `ConstantLR(...)` | Use to multiply the base learning rate by a constant factor for a configured interval. |
105
+ | `LinearLR(...)` | Use to scale the learning rate linearly between configured factors. |
106
+ | `ExponentialLR(...)` | Use for smooth multiplicative decay by `gamma` at every scheduler step. |
107
+ | `PolynomialLR(...)` | Use when the learning rate must follow a polynomial decay. |
108
+ | `ExponentialDecayLR(...)` | Use for exponential decay with explicit step-based control. |
109
+ | `CosineAnnealingLR(...)` | Use for smooth cosine annealing from the base rate toward `eta_min`; match `T_max` to the scheduler-call cadence. |
110
+ | `CosineAnnealingWarmRestarts(...)` | Use for cosine annealing that periodically restarts its cycle. |
111
+ | `WarmupCosineSchedule(...)` | Use when one schedule must warm up first and then anneal by cosine. |
112
+ | `CyclicLR(...)` | Use to oscillate the learning rate between configured bounds. |
113
+ | `OneCycleLR(...)` | Use for a single super-convergence cycle; derive `total_steps` from the actual number of scheduler calls. |
114
+ | `ReduceLROnPlateau(...)` | Use when a validation metric should trigger decay after stalled improvement; call `step(metric=...)`. |
115
+ | `WarmupScheduler(...)` | Use to increase the learning rate linearly during a warmup phase. |
116
+ | `PiecewiseConstantSchedule(...)` | Use for step-wise transitions among explicitly configured constant rates. |
117
+ | `ChainedScheduler(...)` | Use to apply multiple scheduler transformations together. |
118
+ | `SequentialLR(...)` | Use to switch among schedulers at configured epoch milestones. |
119
+
120
+ ```python
121
+ scheduler = braintools.optim.StepLR(
122
+ base_lr=3e-3,
123
+ step_size=20,
124
+ gamma=0.5,
125
+ )
126
+ optimizer = braintools.optim.Adam(lr=scheduler)
127
+ optimizer.register_trainable_weights(params)
128
+
129
+ # After each epoch, outside the neural time-step transform:
130
+ optimizer.lr.step()
131
+ current_lr = optimizer.lr.get_last_lr()
132
+ ```
133
+
134
+ For validation-driven scheduling, use the different call contract:
135
+
136
+ ```python
137
+ scheduler = braintools.optim.ReduceLROnPlateau(
138
+ base_lr=3e-3,
139
+ mode="min",
140
+ factor=0.5,
141
+ patience=5,
142
+ )
143
+ optimizer = braintools.optim.Adam(lr=scheduler)
144
+
145
+ # After validation:
146
+ scheduler.step(metric=float(validation_loss))
147
+ ```
148
+
149
+ Count scheduler calls explicitly. Stepping an epoch-configured schedule once per batch silently changes its effective timescale.
150
+
151
+ ## Standalone and forward-mode optimizers
152
+
153
+ These interfaces own more of the optimization operation than `update(grads)`:
154
+
155
+ | API | Description |
156
+ |---|---|
157
+ | `ScipyOptimizer(loss_fun, bounds, method=...)` | Use for a smooth bounded or constrained objective solved as one optimization problem; match sequence bounds to `loss_fun(*params)` or dict bounds to `loss_fun(**params)`, then call `minimize(n_iter=...)` to obtain a SciPy result whose `x` matches the bounds structure. |
158
+ | `NevergradOptimizer(batched_loss_fun, bounds, n_sample, ...)` | Use when gradients are unavailable or unreliable; accept candidate-stacked parameters, return one loss per candidate, and call `minimize(n_iter=...)` to obtain the best parameter structure. |
159
+ | `SOFO(model, loss_fn, ...)` | Use for a feed-forward model when sampled forward-mode second-order directions are required; register its `ParamState`s, then call `step(inputs, targets)` to compute and apply the direction and return the pre-update loss. |
160
+ | `SOFOScan(rnn_cell, loss_fn, ...)` | Use for a stateful one-step recurrent cell with `(latent, inputs) -> (new_latent, output)`; `step(inputs, targets)` propagates forward-mode tangents through the sequence and applies one update. |
161
+
162
+ `ScipyOptimizer` and `NevergradOptimizer` deliberately raise for the State-based register/update methods. Do not place either inside the canonical compiled minibatch train step.
163
+
164
+ When SciPy bounds carry BrainUnit quantities, the wrapper optimizes numeric mantissas and calls `loss_fun` without units; reconstruct any required physical quantities inside the objective. Nevergrad reattaches units to returned parameters when the corresponding bounds carry units. Apply either optimizer's returned parameters to model State explicitly.
165
+
166
+ For Nevergrad, total objective evaluations are approximately `n_iter * n_sample`. `budget=` configures Nevergrad's internal strategy but does not cap that outer evaluation count.
167
+
168
+ ## Routing and official sources
169
+
170
+ Open `metric.md` for loss and reduction choice and `input-current.md` for generated current-clamp protocols. Open `../scripts/fitting_hh_neuron.py` for the complete BrainCell candidate-evaluation and Nevergrad composition; reconcile its source-version APIs with the BrainCell root skill before adapting it.
171
+
172
+ Official sources:
173
+
174
+ - `https://brainx.chaobrain.com/braintools/apis/optim.html`
175
+ - `https://brainx.chaobrain.com/braintools/optim/01_nevergrad_optimizer.html`
176
+ - `https://brainx.chaobrain.com/braintools/optim/02_scipy_optimizer.html`
177
+ - `https://brainx.chaobrain.com/braintools/optim/03_optax_getting_started.html`
178
+ - `https://brainx.chaobrain.com/braintools/optim/04_learning_rate_scheduling.html`
179
+ - `https://brainx.chaobrain.com/braintools/optim/05_advanced_optimizers.html`
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## Purpose and boundary
4
4
 
5
- Use this reference when a BrainCell simulation depends on geometry, axial current, regional biophysics, or location-specific stimulation and recording. Keep isopotential cells in `skills/braincell/SKILL.md` and cross-cell connections or training in `skills/brainpy-state/SKILL.md`; never model compartments with `SingleCompartment.size`.
5
+ Use this reference when a BrainCell simulation depends on geometry, axial current, regional biophysics, or location-specific stimulation and recording. Keep isopotential cells in `skills/package-skills/braincell/SKILL.md` and cross-cell connections or training in `skills/package-skills/brainpy-state/SKILL.md`; never model compartments with `SingleCompartment.size`.
6
6
 
7
7
  ## Underlying principle of BrainCell multicompartment cells
8
8
 
@@ -373,7 +373,7 @@ Use continuation, State reset, declaration reset, or a new cell according to wha
373
373
 
374
374
  ## Reference routing
375
375
 
376
- Open the smallest child for the next decision; `skills/braincell/SKILL.md` routes multicompartment work here before these children.
376
+ Open the smallest child for the next decision; `skills/package-skills/braincell/SKILL.md` routes multicompartment work here before these children.
377
377
 
378
378
  | Reference | Open when |
379
379
  |---|---|
@@ -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)
@@ -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
@@ -1,6 +1,6 @@
1
1
  # Coupling and network API
2
2
 
3
- Use this reference when configuring structural connectivity, delays, coupling families, self-connections, network-level noise, trainable coupling parameters, or direct coupling objects. Use `brainmass.Network` unless custom wiring requires lower-level prefetch and coupling composition.
3
+ Use this reference when configuring structural connectivity, delays, coupling families, self-connections, network-level noise, trainable coupling parameters, or direct coupling objects. Use `brainmass.Network` unless custom wiring or an independent drive on the coupled input channel requires direct composition.
4
4
 
5
5
  ## Construct the network
6
6
 
@@ -10,7 +10,7 @@ Use this reference when configuring structural connectivity, delays, coupling fa
10
10
  |---|---|
11
11
  | `brainmass.Network(node, *, conn, distance=None, speed=None, coupling="diffusive", coupled_var, k=1.0, delay_init=..., self_connection=False, noise=None)` | Use for the high-level whole-brain path; it validates `coupled_var`, constructs delays and coupling, and exposes the wrapped dynamics as `.node`. |
12
12
  | `Network.init_state(...)` | Use indirectly through `Simulator`; it initializes the node, coupling, delay history, and optional network noise. |
13
- | `Network.update(*node_inputs)` | Use for one custom step; it computes coupling plus optional noise, forwards that as the first node input, and returns the node update result. |
13
+ | `Network.update(*node_inputs)` | Use for one custom step; it inserts coupling plus optional noise as the node's first positional input, forwards `node_inputs` after it, and returns the node update result. |
14
14
  | `brainmass.Simulator(network, dt=...)` | Use for the canonical execution path; monitor wrapped State through `network.node`. |
15
15
 
16
16
  ```python
@@ -43,6 +43,18 @@ assert result["output"].shape == (3000, n_region)
43
43
 
44
44
  **Invariant:** set global `dt` before constructing a delayed network and use the same value in `Simulator`. The delay buffer is sized at construction.
45
45
 
46
+ ### Route coupling and external inputs
47
+
48
+ Choose the path from the node's positional input contract.
49
+
50
+ | Need | Use |
51
+ |---|---|
52
+ | Coupling alone on the first node input | `Network`; do not pass another input. |
53
+ | Coupling on the first input plus an independent drive on the second or later input | `Network`; pass the drive through `Simulator.run(inputs=...)`, which `Network.update()` forwards after coupling. |
54
+ | Coupling plus an independent drive summed on the same first input | Direct composition; retrieve the delayed source, call the functional coupling kernel, add the drive, and pass the sum to the node. |
55
+
56
+ Do not expect a caller-supplied first value to be added to `Network` coupling. It becomes the node's second positional input.
57
+
46
58
  ## Preserve connectivity semantics
47
59
 
48
60
  Use the convention `W[i, j] = source j -> target i`. Each row therefore contains the incoming weights for one target.
@@ -98,7 +110,7 @@ Use the `Network` string selector for standard defaults. Construct a coupling cl
98
110
 
99
111
  Start with normalized or otherwise scientifically calibrated weights and a modest `k`. Changing weight normalization changes the meaning of `k`.
100
112
 
101
- ## Direct construction
113
+ ## Compose custom source and target wiring
102
114
 
103
115
  Use direct construction only when a built-in `Network` cannot represent the source/target wiring. A diffusive coupling requires one delayed `(target, source)` read and one current target read.
104
116
 
@@ -127,6 +139,112 @@ coupling = brainmass.DiffusiveCoupling(
127
139
 
128
140
  Do not replace the delay prefetch protocol with a manually shifted Python container.
129
141
 
142
+ ## Vary delay with a same-channel drive
143
+
144
+ Use a fixed-capacity `brainstate.nn.Delay` when mapped conditions vary retrieval delay while State shape must remain static; construct it under the final `dt`, insert the current source once per step, then retrieve the declared integer offset.
145
+
146
+ | API | Description |
147
+ |---|---|
148
+ | `brainstate.nn.Delay(target_info, time=max_delay, init=...)` | Use for package-owned short-term history with capacity fixed by `max_delay`; construct it while the rollout's `dt` is active and initialize the intended prehistory explicitly. |
149
+ | `Delay.update(current)` | Use exactly once at the start of each model step to insert the source State at the current simulation time. |
150
+ | `Delay.retrieve_at_step(delay_steps)` | Use after insertion with a scalar or traced integer offset no greater than the fixed capacity; step 0 is current and step `d` is exactly `d` completed updates earlier. |
151
+ | `brainmass.<coupling>_coupling(...)` | Use the functional kernel to compute coupling before adding an independent same-channel drive. |
152
+
153
+ Initialize delay history from the intended pre-run source State, not from an
154
+ arbitrary numeric zero. For diffusive coupling, startup history should reproduce
155
+ the source baseline that the current target sees; a homogeneous equilibrium then
156
+ produces zero startup current. If no defensible prehistory exists, warm up the
157
+ same model and coupling path and exclude the warm-up from classification. Verify
158
+ the first retrieved value and resulting coupling current before interpreting
159
+ timing.
160
+
161
+ ```python
162
+ import brainmass
163
+ import brainstate
164
+ import braintools
165
+ import brainunit as u
166
+ import jax.numpy as jnp
167
+
168
+ dt = 0.1 * u.ms
169
+ max_delay = 12.0 * u.ms
170
+ conn = jnp.asarray([
171
+ [0.0, 0.0, 0.0],
172
+ [1.0, 0.0, 0.0],
173
+ [0.0, 1.0, 0.0],
174
+ ])
175
+
176
+
177
+ class DrivenChain(brainstate.nn.Module):
178
+ def __init__(self):
179
+ super().__init__()
180
+ self.node = brainmass.FitzHughNagumoStep(
181
+ in_size=3,
182
+ init_V=braintools.init.Constant(0.0),
183
+ init_w=braintools.init.Constant(0.0),
184
+ )
185
+ self.history = brainstate.nn.Delay(
186
+ jnp.zeros(3),
187
+ time=max_delay,
188
+ init=braintools.init.Constant(0.0),
189
+ )
190
+
191
+ def update(self, stimulus, k, delay):
192
+ self.history.update(self.node.V.value)
193
+ delay_steps = jnp.rint(delay / dt).astype(jnp.int32)
194
+ delayed = self.history.retrieve_at_step(delay_steps)
195
+ sources = jnp.broadcast_to(delayed, conn.shape)
196
+ current = brainmass.additive_coupling(sources, conn, k)
197
+ return self.node(current + stimulus)
198
+
199
+
200
+ def run_condition(k, delay):
201
+ with brainstate.environ.context(dt=dt):
202
+ model = DrivenChain()
203
+ brainstate.nn.init_all_states(model)
204
+ indices = jnp.arange(200)
205
+
206
+ def step(i):
207
+ stimulus = jnp.where(
208
+ i < 20,
209
+ jnp.asarray([0.5, 0.0, 0.0]),
210
+ jnp.zeros(3),
211
+ )
212
+ with brainstate.environ.context(i=i, t=i * dt):
213
+ return model(stimulus, k, delay)
214
+
215
+ return brainstate.transform.for_loop(step, indices)
216
+
217
+
218
+ traces = brainstate.transform.vmap(run_condition)(
219
+ jnp.asarray([0.2, 0.4]),
220
+ jnp.asarray([4.0, 8.0]) * u.ms,
221
+ )
222
+ assert traces.shape == (2, 200, 3)
223
+ ```
224
+
225
+ Keep `max_delay` static. Constructing `Network` or `Delay` with a mapped delay can make buffer capacity depend on a tracer and fail during shape allocation. Map the complete independent condition, vary only the integer retrieval step, and preserve the same `dt` across construction, initialization, and execution.
226
+
227
+ Lock the phase convention with an impulse check before interpreting neural output:
228
+
229
+ ```python
230
+ with brainstate.environ.context(dt=1.0 * u.ms):
231
+ delay = brainstate.nn.Delay(jnp.zeros(()), time=3.0 * u.ms)
232
+ brainstate.nn.init_all_states(delay)
233
+
234
+ def delayed_impulse(value):
235
+ delay.update(value)
236
+ return delay.retrieve_at_step(jnp.asarray(3, dtype=jnp.int32))
237
+
238
+ observed = brainstate.transform.for_loop(
239
+ delayed_impulse,
240
+ jnp.asarray([1.0, 0.0, 0.0, 0.0, 0.0]),
241
+ )
242
+
243
+ assert jnp.array_equal(observed, jnp.asarray([0.0, 0.0, 0.0, 1.0, 0.0]))
244
+ ```
245
+
246
+ If retrieval occurs before insertion, the buffer still ends at the previous simulation time and the same integer offset shifts the physical delay by one `dt`. Do not compensate with an unexplained `delay_steps - 1`; keep one call order and verify it directly.
247
+
130
248
  ## Application script
131
249
 
132
250
  Open `scripts/resting-state-meg-whole-brain-pipeline.py` when the task needs the complete connectome-to-network-to-MEG-to-functional-connectivity workflow.