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,281 @@
1
+ ---
2
+ name: brainx-modeling-loop
3
+ description: Use first for an end-to-end BrainX modeling project. Start fresh or resume from brainmodeling-memory.md, write a compact NeuroSpecification.md, study the relevant BrainX skills deeply, implement and accelerate the model, run experiments, send code and results to Codex through MCP, restudy the affected BrainX skills when review refuses, and visualize only after review passes.
4
+ ---
5
+
6
+ # BrainX modeling loop
7
+
8
+ ## Get started
9
+
10
+ Read `brainmodeling-memory.md` first when it exists, then choose exactly one entry case.
11
+
12
+ | Entry case | Use when | Action |
13
+ |---|---|---|
14
+ | `fresh-new` | `brainmodeling-memory.md` does not exist and no prior loop work must be preserved. | Create the memory file, set the current position to step 0, and start the specification. |
15
+ | `resume` | `brainmodeling-memory.md` or prior loop artifacts exist. | Read the recorded step, verify its referenced artifacts, and continue from the first unfinished action in that step. |
16
+
17
+ Do not create another entry case. Recover missing or inconsistent state inside `resume` by using existing artifacts to locate the earliest unfinished step. Do not repeat a completed experiment or Codex review merely because terminal context was lost.
18
+
19
+ Use this complete append-only memory contract:
20
+
21
+ ```markdown
22
+ # Brain modeling memory
23
+
24
+ ## Checkpoint
25
+ - Iteration: <integer>
26
+ - Step: 0 | 1 | 2 | 3 | 4 | 5 | 6
27
+
28
+ ### Artifacts
29
+ - `<path or stable identifier>`: <contents and status>
30
+
31
+ ### Important milestones
32
+ - <decision, review outcome, blocker, or completed result with its evidence pointer>
33
+
34
+ ## Literature evidence: <topic> - <YYYY-MM-DD>
35
+ - Research question: <question addressed>
36
+ - Review artifact: <path or stable identifier>
37
+ - Essential papers and modeling consequences: <concise evidence records>
38
+ - Cross-paper synthesis: <supported decisions, uncertainty, and required tests>
39
+ ```
40
+
41
+ For `fresh-new`, create the file with its title, start iteration 1 at step 0, and
42
+ append the first checkpoint after step 0 finishes or blocks. After every step,
43
+ including a blocked step, append a new `## Checkpoint` block. `Iteration` and `Step` are metadata identifying
44
+ the step whose artifacts and milestones the block records; `Artifacts` and
45
+ `Important milestones` are the checkpoint content.
46
+
47
+ Never overwrite an earlier checkpoint. Append corrections as a new checkpoint
48
+ with the same iteration and step and state which earlier record it supersedes.
49
+ For `resume`, read the checkpoints in order, verify the latest artifact pointers,
50
+ and continue from the first unfinished action after the latest valid checkpoint.
51
+
52
+ ```text
53
+ fresh-new -> step 0 -> step 1 -> step 2 -> step 3 -> step 4 -> step 5
54
+ ^ |
55
+ |--------- REFUSE ---------|
56
+
57
+ step 5 PASS -> step 6 -> complete
58
+ ```
59
+
60
+ Each checkpoint contains the artifacts created or updated by that step and the
61
+ important milestones reached during it. Keep full code, logs, results, and
62
+ reviews in their owning artifacts and point to them from the checkpoint.
63
+
64
+ The `bio-neuro-lit` skill may append repeatable `## Literature evidence` blocks when selected papers materially affect the model. Treat these blocks as evidence records, not checkpoints: they do not change the current iteration or step. Read them before step 0 specification decisions and during step 1 study, and preserve their source identifiers, evidence depth, publication version, modeling implications, and limitations.
65
+
66
+ ## Step 0: Write the specification
67
+
68
+ Turn the researcher's request and inspected data into a short `NeuroSpecification.md`. Ask the researcher only for missing decisions that would change the model, data interpretation, or acceptance boundary. Do not infer them.
69
+
70
+ Use only this core structure:
71
+
72
+ ```markdown
73
+ # NeuroSpecification
74
+
75
+ - Status: draft | locked
76
+ - Researcher approval:
77
+
78
+ ## Researcher request
79
+ - Brain-modeling question or behavior:
80
+ - Requested model, experiment, or comparison:
81
+ - Execution mode: forward-simulation | task-training | parameter-fitting | hybrid
82
+ - Required outputs:
83
+ - Constraints:
84
+
85
+ ## Inspected data contract
86
+ - Data sources and inspected contents:
87
+ - Shapes, axes, sampling/time base, and physical units:
88
+ - Required preprocessing and the subset used to fit each transform:
89
+ - Mapping from data to model inputs, targets, and observables:
90
+ - Known data limitations or unresolved mismatches:
91
+
92
+ ## Acceptance boundary
93
+ - Evidence required for success, failure, or an inconclusive result:
94
+ - Required baselines and controls:
95
+ - Invalid-result conditions:
96
+ - Allowed claims and explicit non-claims:
97
+ ```
98
+
99
+ Inspect supplied data before completing its contract. Keep raw data read-only, preserve units and axis meaning, and prevent preprocessing leakage. Lock the specification with researcher approval before step 1.
100
+
101
+ **Step result:** a locked `NeuroSpecification.md` and a memory checkpoint pointing to step 1.
102
+
103
+ ## Step 1: Study the relevant BrainX modeling skills
104
+
105
+ Study before implementing. Understand the selected BrainX abstractions, exact APIs, execution lifecycle, invariants, and canonical scripts deeply enough to design the model without guessing.
106
+
107
+ 1. Open `brainx-general-guard` and identify every biological scale explicitly represented by `NeuroSpecification.md`.
108
+ 2. Read each selected modeling skill completely:
109
+ - `braincell` for ions, channels, compartments, or morphology;
110
+ - `brainpy-state` for point neurons, synapses, or spiking networks;
111
+ - `brainmass` for aggregate populations, regions, or whole-brain dynamics.
112
+ 3. Open supporting package skills only when the model requires them:
113
+ - `brainunit` for physical quantities and unit-aware boundaries;
114
+ - `brainstate` for State, Modules, environments, initialization, randomness, and transforms;
115
+ - `brainevent` for event data, connectivity, and event-driven plasticity;
116
+ - `braintrace` only for temporal training limited by BPTT memory.
117
+ 4. Follow every selected skill's routing instructions. Read all references and canonical scripts likely to affect this model.
118
+ 5. Trace construction, initialization, State and data flow, update order, execution, outputs, and validation through the relevant examples.
119
+ 6. Verify unfamiliar API names and signatures in the owning skill or its routed documentation. Do not inspect installed package source for modeling knowledge.
120
+ 7. Save the study record as an artifact and record its completion and selected training/fitting coverage as important milestones.
121
+
122
+ Do not write the implementation during step 1. Finish the study record first.
123
+
124
+ When step 5 returns `REFUSE`, increment the iteration and return here before changing code. Map every reviewer finding to the owning BrainX package or workflow skill, reopen `brainx-general-guard`, and restudy every affected package skill, routed reference, and canonical script that can change the correction. Recheck high-level BrainX and BrainTools APIs before retaining custom or external infrastructure. Open the active training or fitting reference during this restudy when a finding concerns its objective, architecture, optimizer, input, metric, recovery, or evidence contract.
125
+
126
+ Preserve the original study artifact. For iteration 1, use `brainx-study-record.md`; after a refusal, write `brainx-study-record-iteration-<N>.md` with the reviewer-finding map, newly studied sources, changed or reaffirmed API decisions, and the resulting implementation design. Append a step-1 memory checkpoint pointing to the new artifact. Do not begin step 2 until this iteration-specific restudy is complete.
127
+
128
+ **Step result:** a complete BrainX study record and an implementation design grounded in the selected skills, then a memory checkpoint pointing to step 2.
129
+
130
+ ## Optional training and fitting coverage for steps 2-5
131
+
132
+ Training and fitting extend the same loop; they do not create separate stages or entry cases.
133
+
134
+ | Specification mode | Coverage for steps 2-5 |
135
+ |---|---|
136
+ | `forward-simulation` | Open neither optional reference. |
137
+ | `task-training` | Open `references/training-workflow.md` at the start of step 2 and keep its requirements active through implementation, acceleration, experiment execution, and Codex review. |
138
+ | `parameter-fitting` | Open `references/parameter-fitting-workflow.md` at the start of step 2 and keep its requirements active through implementation, acceleration, experiment execution, and Codex review. |
139
+ | `hybrid` | Open `references/training-workflow.md` and `references/parameter-fitting-workflow.md` at step 2, then keep their objectives, State lifecycles, validation evidence, and review coverage distinct through step 5. |
140
+
141
+ Record the active coverage as an important milestone. A step is incomplete until its modeling requirements and every active training/fitting requirement are satisfied.
142
+
143
+ ## Step 2: Implement the model and experiment code
144
+
145
+ Implement from the step-1 study record and the locked specification. Open the selected training or parameter-fitting reference before coding and apply it throughout this step.
146
+
147
+ 1. Build the model through the selected BrainX package abstractions and highest-level owning APIs.
148
+ 2. Implement required data processing, initialization, inputs, interventions, controls, observation mapping, training or fitting workflow, metrics, and artifact outputs.
149
+ 3. Preserve BrainUnit quantities, BrainState lifecycle, package update order, randomness, and represented biological scale.
150
+ 4. Add focused checks for equations or components, shapes, units, State initialization/reset, update order, inputs, controls, observables, and metrics.
151
+ 5. Run only small implementation checks needed to prove the code is ready for acceleration and the experiment runner. Leave production execution to step 4.
152
+ 6. Record the code and test artifacts plus any important implementation milestone.
153
+
154
+ **Step result:** BrainX-native model and experiment code with focused checks, then a memory checkpoint pointing to step 3.
155
+
156
+ ## Step 3: Accelerate the code
157
+
158
+ Open `brainx-acceleration` and study the parts relevant to the implemented workload. Apply its workflow while keeping any active training/fitting coverage in force.
159
+
160
+ 1. Establish the representative baseline and relevant outputs before changing performance code.
161
+ 2. Apply only acceleration changes supported by the acceleration skill.
162
+ 3. Compare model outputs, State, units, randomness, and numerical tolerances against the baseline.
163
+ 4. When training is active, also preserve losses, gradients, parameter updates, reset behavior, and checkpoint meaning. When fitting is active, preserve objectives, parameter order/units, recovery behavior, and inference outputs.
164
+ 5. Reject an optimization that changes the scientific result.
165
+ 6. Record the acceleration and parity artifacts plus the important outcome milestone.
166
+
167
+ **Step result:** accelerated code with parity evidence, or an explicit unchanged decision, then a memory checkpoint pointing to step 4.
168
+
169
+ ## Step 4: Run the experiment
170
+
171
+ Hand the locked specification, implementation, acceleration evidence, run configuration, seeds, expected outputs, artifact locations, and active training/fitting requirements to `references/run-experiment.md`. Follow it through target-device smoke and immutable production or replication launch, then open `references/monitor-experiment.md` for monitoring and artifact collection.
172
+
173
+ Step 4 must eventually return inspectable run artifacts: the exact configuration, code/data/environment identity, logs, raw results, metrics, training/fitting evidence when active, and artifact paths. Process completion does not imply review acceptance.
174
+
175
+ **Step result:** completed experiment artifacts and a memory checkpoint pointing to step 5.
176
+
177
+ ## Step 5: Ask Codex to review code and results
178
+
179
+ Use the configured BrainX Codex MCP server. Its
180
+ `mcp-servers/codex/system-prompt.md` is the authoritative review contract and is
181
+ injected as `base-instructions` into every fresh `mcp__codex__codex` call. Do not
182
+ duplicate that contract in this skill or paste it into the review request.
183
+
184
+ Start one fresh `mcp__codex__codex` call for each completed iteration. Send the
185
+ locked specification, step-1 study record, implementation and tests, acceleration
186
+ evidence, experiment configuration, raw run artifacts, metrics, deterministic
187
+ result assessment, claim-evidence matrix, proposed next action, and all evidence
188
+ required by active training/fitting coverage. The returned `content` is the
189
+ reviewer's Markdown report in the calling agent's current turn. Before
190
+ classifying it, save it verbatim as `reviews/iteration-<N>.md`; do not reformat,
191
+ summarize, or mix the main agent's analysis into that file. Then read its verdict,
192
+ update the loop checkpoint with the report path, and report or act on it without
193
+ asking the researcher to open another context. Preserve the returned `threadId`
194
+ in the checkpoint for reviewer follow-up; it is not needed to read the report.
195
+
196
+ Before calling, verify that every listed path exists. Set the MCP call's working
197
+ directory to the project root when the tool exposes a working-directory argument,
198
+ then call `mcp__codex__codex` with a `prompt` in this form:
199
+
200
+ ```text
201
+ Review completed BrainX iteration <N>.
202
+
203
+ PROJECT_ROOT: <absolute project-root path>
204
+ ACTIVE_COVERAGE: none | training | fitting | training+fitting
205
+
206
+ SPECIFICATION:
207
+ - <path>/NeuroSpecification.md
208
+
209
+ LOOP_MEMORY:
210
+ - <path>/brainmodeling-memory.md
211
+
212
+ BRAINX_STUDY_RECORD:
213
+ - <path to every step-1 study artifact through this iteration>
214
+
215
+ IMPLEMENTATION:
216
+ - <path to each model, data-processing, and experiment source file>
217
+
218
+ TESTS:
219
+ - <path to each relevant test and its result artifact>
220
+
221
+ ACCELERATION_AND_PARITY:
222
+ - <path to baseline, parity, runtime, and memory evidence>
223
+
224
+ EXPERIMENT_RUN:
225
+ - <path to exact run configuration>
226
+ - <path to code, data, and environment provenance>
227
+ - <path to logs>
228
+ - <path to raw results>
229
+ - <path to metrics>
230
+ - <path to artifact manifest>
231
+
232
+ RESULT_ASSESSMENT:
233
+ - <path to deterministic assessment and claim-evidence matrix>
234
+
235
+ TRAINING_OR_FITTING_EVIDENCE:
236
+ - <path to every active coverage artifact, or none>
237
+
238
+ PRIOR_REVIEW_EVIDENCE:
239
+ - <path to prior raw reviews and addressed findings, or none>
240
+
241
+ Read every listed artifact and review this iteration using the injected reviewer
242
+ contract. Do not edit files. Return only the required Markdown report.
243
+ ```
244
+
245
+ List concrete files, not only directories. Keep large data in place and provide
246
+ its manifest, provenance, and the exact result files needed for verification.
247
+ Do not omit an unfavorable, failed, or excluded run when it affects the proposed
248
+ scientific outcome.
249
+
250
+ Do not start an iteration review with `mcp__codex__codex-reply`; only a fresh
251
+ `codex` call receives the injected system prompt. If the configured MCP server is
252
+ unavailable, record step 5 as blocked in `brainmodeling-memory.md` and preserve
253
+ all completed experiment artifacts.
254
+
255
+ For a non-interactive Codex host, configure the MCP registration with
256
+ `default_tools_approval_mode = "approve"`; otherwise the host cannot present an
257
+ MCP approval prompt and may report the denied call as `user cancelled MCP tool
258
+ call`. Also set `tool_timeout_sec = 1800`, or another explicit budget longer than
259
+ the largest expected review. When no `threadId` or response is returned, verify
260
+ approval first and timeout second before treating it as researcher cancellation.
261
+
262
+ Record the verbatim Markdown report path, `threadId`, and one of two outcomes:
263
+
264
+ | Outcome | Transition |
265
+ |---|---|
266
+ | `REFUSE` | Record every finding and required correction, increment the iteration, set the current step to 1, restudy the affected BrainX package and workflow skills, and repeat steps 1-5 with the same optional coverage. |
267
+ | `PASS` | Record the accepted code/result scope and set the current step to 6. |
268
+
269
+ Do not argue with a refusal inside step 5 and do not substitute self-review for the MCP Codex call. The next Codex call occurs only after the refusal has passed through package restudy, revised implementation, acceleration, and experiment execution.
270
+
271
+ **Step result:** a preserved `reviews/iteration-<N>.md` report and either a return to step 1 or a memory checkpoint pointing to step 6.
272
+
273
+ ## Step 6: Visualize the accepted result
274
+
275
+ Hand the review-passed specification, code, run artifacts, results, and accepted scope to the BrainX visualization workflow.
276
+
277
+ The planned route is `references/visualization-workflow.md`. That instruction will be authored later; do not embed or invent it here. Until it exists, preserve the accepted artifacts and record step 6 as blocked in `brainmodeling-memory.md`.
278
+
279
+ After visualization completes, record the figure paths as artifacts and loop completion as an important milestone, then report the accepted result and remaining limitations.
280
+
281
+ **Step result:** visualization linked to review-passed evidence and a completed memory checkpoint.
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "BrainX Modeling Loop"
3
+ short_description: "Run rigorous iterative BrainX modeling projects"
4
+ default_prompt: "Use $brainx-modeling-loop to start or resume my iterative BrainX model, with training or fitting coverage when required."
@@ -0,0 +1,49 @@
1
+ # Monitor BrainX experiments
2
+
3
+ Use this reference after `run-experiment.md` launches a BrainX run. Monitor process and artifact health, stop only under declared rules, retry only transient failures, collect inspectable outputs, and return mechanical status to `brainx-modeling-loop`; do not tune the experiment or decide scientific acceptance.
4
+
5
+ ## Inspect the recorded run
6
+
7
+ Start from `RUN_SPEC.md`, `status.json`, and the recorded process, session, scheduler, or provider handle. Verify that the handle still identifies the recorded command, working directory, and start time; never select a run by broad process-name matching.
8
+
9
+ | Signal | Check | Meaning |
10
+ |---|---|---|
11
+ | Liveness | Process/job/session/provider status | Whether execution is active; absence requires exit and artifact inspection. |
12
+ | Progress | New append-only logs or declared heartbeat | Whether the run advances at its expected cadence. |
13
+ | CPU/GPU resources | Memory, disk, utilization, device errors, and recorded PID/device | Resource health and target placement, not scientific quality. |
14
+ | Checkpoint | Existence, freshness, size, completion marker, and parseability | Recovery freshness; partial writes are invalid. |
15
+ | Output | Required files, sizes, parseability, and declared finite-value checks | Mechanical completeness or deterministic invalidity. |
16
+ | Existing telemetry | Run state and predeclared metrics | Secondary evidence; immutable local artifacts remain authoritative. |
17
+
18
+ Poll at a cadence proportional to the declared heartbeat/checkpoint interval. External scheduling may wake on machine-checkable conditions such as exit code, job state, file existence, or logged step; never schedule a scientific verdict.
19
+
20
+ ## Classify before acting
21
+
22
+ | Status | Evidence | Action |
23
+ |---|---|---|
24
+ | `running-healthy` | Live handle, advancing progress, resources within bounds | Wait and report the latest raw progress. |
25
+ | `running-uncertain` | Live handle but no new signal within one expected interval | Inspect logs/resources; wait unless a declared limit is crossed. |
26
+ | `done` | Exit code zero and every required artifact exists and parses | Record completion and collect artifacts. |
27
+ | `failed-deterministic` | Reproducible code/config/data, NaN/Inf, corruption, leakage, or broken locked metric | Preserve evidence; do not retry unchanged. Return to implementation. |
28
+ | `failed-transient` | Preemption, transport interruption, temporary host/device, or recoverable scheduler failure | Retry only within budget under a new linked run ID. |
29
+ | `stopped` | Declared kill condition or authorized cancellation | Preserve partial artifacts and the reason. |
30
+
31
+ An unexpected finite result, noisy metric, weak interim effect, or insufficient samples is not deterministic invalidity. Do not stop because the hypothesis appears unsupported.
32
+
33
+ ## Stop and retry safely
34
+
35
+ For a declared stop condition, record the evidence, request graceful termination, allow the checkpoint/cleanup grace period, verify exit and output finalization, and force termination only when the process remains active and the scope authorizes it. Preserve logs, partial outputs, checkpoints, exit/signal status, and device diagnostics.
36
+
37
+ Retry only a transient fault within the frozen retry budget. Create a new run ID with `parent_run_id` and `retry_of`; preserve the specification, code, config, data, precision, backend, and seed policy. Apply the checkpoint gate in `run-experiment.md` before resuming. A different batch size, precision, solver, `dt`, backend, seed rule, checkpoint cadence, or model code is a new scientific run, not a retry.
38
+
39
+ Never delete a failed run or overwrite collected artifacts. Never destroy paid remote compute until copied artifacts and hashes are verified and teardown is explicitly authorized.
40
+
41
+ ## Collect and report
42
+
43
+ For remote runs, copy into a new local collection path and verify the artifact manifest and hashes before marking collection complete. Report raw values before interpretation:
44
+
45
+ | Run ID | Level | Backend/device | Progress or exit | Primary declared metric | Artifacts |
46
+ |---|---|---|---|---|---|
47
+ | `<id>` | `production` | `cuda / GPU UUID` | `done / 0` | `<raw value and unit>` | `complete` |
48
+
49
+ Also report start/end time, duration, exact command path, log path, checkpoint path/status, missing or corrupt outputs, retry lineage, and paid-compute cost when applicable. Compare only runs the locked contract declares comparable and label every differing field. Return `done`, `failed`, or `stopped`; never return `accepted`.
@@ -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)