brainx-skill 1.0.12 → 1.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/README.md +4 -0
  2. package/installation/lib/bundle.js +51 -13
  3. package/manifest.json +2 -0
  4. package/mcp-servers/codex/README.md +62 -0
  5. package/mcp-servers/codex/UPSTREAM.md +20 -0
  6. package/mcp-servers/codex/server.mjs +140 -0
  7. package/mcp-servers/codex/skills.json +10 -0
  8. package/mcp-servers/codex/system-prompt.md +62 -0
  9. package/mcp-servers/codex/test/fixtures/fake-codex.mjs +6 -0
  10. package/mcp-servers/codex/test/server.test.mjs +88 -0
  11. package/package.json +6 -9
  12. package/skills/brainx-acceleration/SKILL.md +459 -0
  13. package/skills/brainx-general-guard/SKILL.md +14 -9
  14. package/skills/brainx-modeling-loop/SKILL.md +268 -0
  15. package/skills/brainx-modeling-loop/agents/openai.yaml +4 -0
  16. package/skills/brainx-modeling-loop/references/monitor-experiment.md +49 -0
  17. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow/scripts/fitting_hh_neuron.py +254 -0
  18. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +232 -0
  19. package/skills/brainx-modeling-loop/references/run-experiment.md +179 -0
  20. package/skills/brainx-modeling-loop/references/training-workflow.md +270 -0
  21. package/skills/{braincell → package-skills/braincell}/SKILL.md +2 -1
  22. package/skills/{braincell → package-skills/braincell}/references/multicompartment/multicompartment-cell-workflow.md +2 -2
  23. package/skills/package-skills/braincell/references/scripts/fitting_hh_neuron.py +254 -0
  24. package/skills/{brainmass → package-skills/brainmass}/references/brainstate/parameter-constraints-regularization.md +1 -1
  25. package/skills/{brainmass → package-skills/brainmass}/references/coupling-network-api.md +121 -3
  26. package/skills/{brainmass → package-skills/brainmass}/references/modellibrary.md +79 -1
  27. package/skills/package-skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +188 -0
  28. package/skills/{brainmass → package-skills/brainmass}/references/visualization-analysis-api.md +6 -6
  29. package/skills/{brainpy-state → package-skills/brainpy-state}/SKILL.md +4 -3
  30. package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/connectivity.md +1 -1
  31. package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/input-current.md +1 -1
  32. package/skills/package-skills/brainpy-state/references/perturbation-experiment-validity.md +76 -0
  33. package/skills/{brainpy-state → package-skills/brainpy-state}/references/projection-patterns.md +1 -1
  34. package/skills/{brainstate → package-skills/brainstate}/SKILL.md +1 -0
  35. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/brainstate-transformed-diagnostics.md +1 -1
  36. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/parameter-constraints-regularization.md +1 -1
  37. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/randomness-and-reproducibility.md +1 -1
  38. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-grad-expansion.md +2 -2
  39. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-vmap-expansion.md +1 -1
  40. package/skills/{brainstate → package-skills/brainstate}/references/libraries/prebuilt-layer-library.md +1 -1
  41. package/skills/package-skills/brainstate/references/paired-perturbation-execution.md +113 -0
  42. package/skills/package-skills/braintrace/SKILL.md +187 -0
  43. package/skills/package-skills/braintrace/references/Drtrl.md +133 -0
  44. package/skills/{braintrace → package-skills/braintrace}/references/ETP operators.md +31 -4
  45. package/skills/package-skills/braintrace/references/algorithm selection.md +64 -0
  46. package/skills/package-skills/braintrace/references/batching.md +140 -0
  47. package/skills/{braintrace → package-skills/braintrace}/references/compiler_internal.md +2 -2
  48. package/skills/{braintrace → package-skills/braintrace}/references/custom algorithms.md +8 -10
  49. package/skills/package-skills/braintrace/references/pp_pprop workflow.md +179 -0
  50. package/skills/{braintrace → package-skills/braintrace}/references/pre-built-braintrace-layer.md +2 -2
  51. package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +0 -130
  52. package/skills/braintrace/SKILL.md +0 -161
  53. package/skills/braintrace/references/Drtrl.md +0 -179
  54. package/skills/braintrace/references/algorithm selection.md +0 -120
  55. package/skills/braintrace/references/batching.md +0 -150
  56. package/skills/braintrace/references/pp_pprop workflow.md +0 -196
  57. /package/skills/{braincell → package-skills/braincell}/references/area-scaled-hh-pattern.md +0 -0
  58. /package/skills/{braincell → package-skills/braincell}/references/braincell-custom-ion-channel-authoring.md +0 -0
  59. /package/skills/{braincell → package-skills/braincell}/references/channel-library.md +0 -0
  60. /package/skills/{braincell → package-skills/braincell}/references/ion-library.md +0 -0
  61. /package/skills/{braincell → package-skills/braincell}/references/mixions-for-adaptation.md +0 -0
  62. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/braincell-manual-morphology-construction.md +0 -0
  63. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/cv-policy-reference.md +0 -0
  64. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/filter-function-library.md +0 -0
  65. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/morphology-io-loading-validation.md +0 -0
  66. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/probe-reference.md +0 -0
  67. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/topology-building-and-visualization.md +0 -0
  68. /package/skills/{braincell → package-skills/braincell}/references/scripts/calcium_channel_gating.py +0 -0
  69. /package/skills/{braincell → package-skills/braincell}/references/scripts/cell_multicompartment_reference.py +0 -0
  70. /package/skills/{braincell → package-skills/braincell}/references/scripts/channel_ablation.py +0 -0
  71. /package/skills/{braincell → package-skills/braincell}/references/scripts/fi_curve.py +0 -0
  72. /package/skills/{braincell → package-skills/braincell}/references/scripts/hh_neuron_basics.py +0 -0
  73. /package/skills/{braincell → package-skills/braincell}/references/scripts/spike_frequency_adaptation.py +0 -0
  74. /package/skills/{braincell → package-skills/braincell}/references/scripts/t_current_rebound.py +0 -0
  75. /package/skills/{braincell → package-skills/braincell}/references/scripts/thalamic_neurons.py +0 -0
  76. /package/skills/{braincell → package-skills/braincell}/references/solver-library-with-effects.md +0 -0
  77. /package/skills/{brainevent → package-skills/brainevent}/SKILL.md +0 -0
  78. /package/skills/{brainevent → package-skills/brainevent}/references/connectivity-variants.md +0 -0
  79. /package/skills/{brainevent → package-skills/brainevent}/references/custom-operators-cpu.md +0 -0
  80. /package/skills/{brainevent → package-skills/brainevent}/references/custom-operators-gpu.md +0 -0
  81. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/102_EI_net_1996.py +0 -0
  82. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/204_joglekar_2018_propagation.py +0 -0
  83. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/coba_ei_teaching.py +0 -0
  84. /package/skills/{brainevent → package-skills/brainevent}/references/sparse-formats.md +0 -0
  85. /package/skills/{brainevent → package-skills/brainevent}/references/synaptic-plasticity.md +0 -0
  86. /package/skills/{brainmass → package-skills/brainmass}/SKILL.md +0 -0
  87. /package/skills/{brainmass → package-skills/brainmass}/references/batch-transform-acceleration.md +0 -0
  88. /package/skills/{brainmass → package-skills/brainmass}/references/brainstate/parameter-transforms-regularizers-catalog.md +0 -0
  89. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/cogtask.md +0 -0
  90. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/data-preprocessing.md +0 -0
  91. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/metric.md +0 -0
  92. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/optimizer.md +0 -0
  93. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/parameter-initializer.md +0 -0
  94. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/surrogate.md +0 -0
  95. /package/skills/{brainmass → package-skills/brainmass}/references/datasets-api.md +0 -0
  96. /package/skills/{brainmass → package-skills/brainmass}/references/fitting-with-objectives-api.md +0 -0
  97. /package/skills/{brainmass → package-skills/brainmass}/references/forward-observation-api.md +0 -0
  98. /package/skills/{brainmass → package-skills/brainmass}/references/horn-task-training.md +0 -0
  99. /package/skills/{brainmass → package-skills/brainmass}/references/noiseprocesses.md +0 -0
  100. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/eeg-fitting-with-gradients.py +0 -0
  101. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/gradient-free-fitting.py +0 -0
  102. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/hopf-bifurcation-single-node.py +0 -0
  103. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/horn-cognitive-task-training.py +0 -0
  104. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/jansen-rit-eeg-proxy.py +0 -0
  105. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/kuramoto-synchronization.py +0 -0
  106. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/linear-baseline-node.py +0 -0
  107. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/resting-state-meg-whole-brain-pipeline.py +0 -0
  108. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/seizure-epileptor-case-study.py +0 -0
  109. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wilson-cowan-ei-dynamics.py +0 -0
  110. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wong-wang-decision-making.py +0 -0
  111. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wong-wang-dmf-resting-state.py +0 -0
  112. /package/skills/{brainmass → package-skills/brainmass}/references/simulator-input-monitor-api.md +0 -0
  113. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/array-creation.md +0 -0
  114. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brain-dynamics-delay-protocol.md +0 -0
  115. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/analysis.md +0 -0
  116. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/brainpy legacy workflow.md +0 -0
  117. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/built-in dynamic neuron model.md +0 -0
  118. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/connecting neurons.md +0 -0
  119. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/customize neuron and synpase.md +0 -0
  120. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Input generation.md +0 -0
  121. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/More about simulation.md +0 -0
  122. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +0 -0
  123. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +0 -0
  124. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +0 -0
  125. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +0 -0
  126. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/delays.md +0 -0
  127. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +0 -0
  128. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/integrators.md +0 -0
  129. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/route activity through connectivity.md +0 -0
  130. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/synaptic projections.md +0 -0
  131. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/synpase properties.md +0 -0
  132. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/loss library.md +0 -0
  133. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/optimizers.md +0 -0
  134. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/parameter initializers.md +0 -0
  135. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/prebuilt neural network layers.md +0 -0
  136. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/surrogate gradients.md +0 -0
  137. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/trainer library.md +0 -0
  138. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/trainingworkflows.md +0 -0
  139. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/brainstate-control-flow-patterns.md +0 -0
  140. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/data-preprocessing.md +0 -0
  141. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/metric.md +0 -0
  142. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/optimizer.md +0 -0
  143. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/parameter-initializer.md +0 -0
  144. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/surrogate.md +0 -0
  145. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/component-selection.md +0 -0
  146. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/devices.md +0 -0
  147. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/divergence-and-parity.md +0 -0
  148. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/integration-categories.md +0 -0
  149. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/model-library.md +0 -0
  150. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/nest-workflow.md +0 -0
  151. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/network-building.md +0 -0
  152. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brette_et_al_2007.py +0 -0
  153. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brunel_alpha.py +0 -0
  154. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brunel_delta.py +0 -0
  155. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +0 -0
  156. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +0 -0
  157. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/spatial_gaussex.py +0 -0
  158. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/synapsecollection.py +0 -0
  159. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/synapse-and-connectivity.md +0 -0
  160. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/103_COBA_2005.py +0 -0
  161. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/106_COBA_HH_2007.py +0 -0
  162. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/107_gamma_oscillation_1996.py +0 -0
  163. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/109_fast_global_oscillation.py +0 -0
  164. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +0 -0
  165. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/sound_localization.py +0 -0
  166. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/training-snn.py +0 -0
  167. /package/skills/{brainstate → package-skills/brainstate}/agents/openai.yaml +0 -0
  168. /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/brainstate-control-flow-patterns.md +0 -0
  169. /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/parameter-transforms-regularizers-catalog.md +0 -0
  170. /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-jit-expansion.md +0 -0
  171. /package/skills/{brainstate → package-skills/brainstate}/references/collective_model_operations.md +0 -0
  172. /package/skills/{brainstate → package-skills/brainstate}/references/extension_mechanisms.md +0 -0
  173. /package/skills/{brainstate → package-skills/brainstate}/references/libraries/prebuilt-activation-library.md +0 -0
  174. /package/skills/{brainstate → package-skills/brainstate}/references/model-interop-and-migration.md +0 -0
  175. /package/skills/{brainstate → package-skills/brainstate}/references/simulation-environment.md +0 -0
  176. /package/skills/{brainstate → package-skills/brainstate}/references/size-inference-variations.md +0 -0
  177. /package/skills/{brainstate → package-skills/brainstate}/references/state-graph-operations.md +0 -0
  178. /package/skills/{brainstate → package-skills/brainstate}/references/state_collections_and_utilities.md +0 -0
  179. /package/skills/{brainstate → package-skills/brainstate}/scripts/integrator_rnn.py +0 -0
  180. /package/skills/{brainstate → package-skills/brainstate}/scripts/lif_neuron_model.py +0 -0
  181. /package/skills/{brainstate → package-skills/brainstate}/scripts/modern_cnn.py +0 -0
  182. /package/skills/{brainstate → package-skills/brainstate}/scripts/resnet.py +0 -0
  183. /package/skills/{braintrace → package-skills/braintrace}/references/custom ETP primitives.md +0 -0
  184. /package/skills/{braintrace → package-skills/braintrace}/references/customizing_primitive_transforms.md +0 -0
  185. /package/skills/{brainunit → package-skills/brainunit}/SKILL.md +0 -0
  186. /package/skills/{brainunit → package-skills/brainunit}/references/array-creation.md +0 -0
  187. /package/skills/{brainunit → package-skills/brainunit}/references/array-mechanics/functional-structural-api.md +0 -0
  188. /package/skills/{brainunit → package-skills/brainunit}/references/array-mechanics.md +0 -0
  189. /package/skills/{brainunit → package-skills/brainunit}/references/math-function-library.md +0 -0
  190. /package/skills/{brainunit → package-skills/brainunit}/references/physical-constant-library.md +0 -0
  191. /package/skills/{brainunit → package-skills/brainunit}/references/prefix-library.md +0 -0
  192. /package/skills/{brainunit → package-skills/brainunit}/references/quantity-inspection-and-conversion.md +0 -0
  193. /package/skills/{brainunit → package-skills/brainunit}/references/typing-and-runtime-validation.md +0 -0
  194. /package/skills/{brainunit → package-skills/brainunit}/references/unit-structure-and-definition.md +0 -0
@@ -0,0 +1,270 @@
1
+ # BrainX task-training workflow
2
+
3
+ Use this reference when `NeuroSpecification.md` selects `task-training` or the
4
+ training phase of `hybrid`. It owns the experimental contract around task data,
5
+ BrainX State, optimization, monitoring, tuning, checkpoint selection, and
6
+ held-out evaluation. The routed package skills still own model equations,
7
+ construction, simulation, and package-specific APIs.
8
+
9
+ Use task training to optimize model or readout weights over many input-target
10
+ examples. Use `parameter-fitting-workflow.md` instead to estimate
11
+ scientific model parameters against observations. In `hybrid`, keep the two
12
+ objectives, trainable State collections, data partitions, checkpoints, and
13
+ reported evidence distinct.
14
+
15
+ ## Underlying training principle
16
+
17
+ Training reuses the scientific forward model: reset runtime State at the
18
+ declared independence boundary, execute the same BrainX rollout used for
19
+ evaluation, reduce aligned outputs and targets to one scalar loss,
20
+ differentiate only the declared parameter State, and apply one optimizer update
21
+ at the declared cadence.
22
+
23
+ `ParamState` represents learned values that persist across batches. Hidden,
24
+ short-term, random, delay, eligibility, monitor, membrane, conductance, and
25
+ other runtime State represent the condition of one rollout; reset or preserve
26
+ each role according to the scientific protocol, never because an optimizer or
27
+ batch loop makes reset convenient.
28
+
29
+ Do not put a framework-neutral learner around a BrainX simulator callback. Keep
30
+ the forward model, trainable State, runtime State, reset lifecycle, temporal
31
+ execution, physical units, and represented biological scale BrainX-native.
32
+
33
+ ## Lock the training contract
34
+
35
+ Declare the experiment before writing the train step. A later change to the
36
+ task, target, independence unit, data inclusion, primary metric, or accepted
37
+ claim changes the locked specification; do not treat it as hyperparameter
38
+ tuning.
39
+
40
+ | Contract field | Required decision |
41
+ |---|---|
42
+ | Samples | Identify the independence unit: trial, sequence, subject, animal, session, recording, or another declared unit. |
43
+ | Axes and units | Name batch, time, feature, neuron, region, and target axes; record every transpose, temporal alignment, reduction, and unit boundary. |
44
+ | Partitions | Split immutable sample IDs by the independence unit before fitting preprocessing; prevent subject, session, temporal-neighbor, augmentation, and preprocessing leakage. |
45
+ | State lifecycle | Declare which State resets at sample, batch, sequence, phase, training/evaluation, and seed boundaries and which learned State persists. |
46
+ | Trainables | Select only intended parameter State; enumerate every excluded runtime State and any frozen parameter State. |
47
+ | Objective | Lock loss inputs, target alignment, reduction axes, units, regularization, primary metric, metric direction, and chance or null baseline. |
48
+ | Update cadence | Declare whether one optimizer update follows a timestep, window, complete sequence, batch, or accumulated set of batches. |
49
+ | Selection | Lock validation metric, checkpoint rule, seed aggregation, search space, budget, minimum evidence, patience, and stop rule before tuning. |
50
+ | Held-out use | Reserve held-out data until configuration and checkpoint selection are complete; never use it to continue, stop, tune, or choose a seed. |
51
+
52
+ Record the contract as an iteration artifact:
53
+
54
+ ```yaml
55
+ training_contract:
56
+ independence_unit: subject
57
+ axes:
58
+ input: [batch, time, feature]
59
+ target: [batch, class]
60
+ rollout_input: [time, batch, feature]
61
+ reset_boundary: independent_sequence
62
+ trainable_state: declared ParamState collection only
63
+ split_fit_scope: training subjects
64
+ update_cadence: one update per minibatch of complete sequences
65
+ primary_metric: validation loss
66
+ metric_direction: minimize
67
+ checkpoint_rule: minimum validation loss within each run
68
+ config_selection_rule: minimum mean validation loss across declared seeds
69
+ seed_aggregation: mean and declared uncertainty interval
70
+ tuning_budget: 12 completed or invalidated configurations
71
+ held_out_access: after all model and checkpoint selection
72
+ ```
73
+
74
+ Replace the example values with the locked scientific design. Store exact
75
+ sample IDs, preprocessing state, seeds, code/data/environment identity, and
76
+ configuration outside this compact contract and point to those artifacts.
77
+
78
+ ## Pass the mechanical gates
79
+
80
+ Do not start a production baseline until every gate passes on a small case.
81
+
82
+ | Gate | Required evidence |
83
+ |---|---|
84
+ | Data and leakage | Disjoint split IDs, training-only preprocessing fit, expected shapes/units, target range, class or target distribution, and explicit time alignment. |
85
+ | Forward parity | Training and evaluation call the same scientific rollout and observation path; only declared fit/evaluation behavior differs. |
86
+ | State reset | Replaying one sample from the same declared initial State reproduces its output; reordering independent samples does not change their predictions. |
87
+ | Gradient reach | Loss and every intended gradient are finite; expected trainables receive nonzero signal; excluded State is absent from the gradient and optimizer trees. |
88
+ | Update isolation | One update changes intended trainables and optimizer State only; it does not silently change frozen parameters, data transforms, or persistent scientific configuration. |
89
+ | Temporal reduction | A synthetic target at a known timestep changes only the intended scored output or window; masks exclude padding and ignored phases. |
90
+ | Tiny-case overfit | The unchanged pipeline can overfit a tiny batch or short sequence and move the declared metric in the expected direction. |
91
+ | Replay and compilation | Declared seeds replay exactly where promised, and repeated shape-compatible calls reuse the model graph without State-shape drift. |
92
+
93
+ Treat failure as diagnostic evidence. Fix data, State, alignment, gradient, or
94
+ objective mechanics before changing learning rate, optimizer, surrogate,
95
+ architecture, or model dynamics.
96
+
97
+ ## Establish the baseline and run ledger
98
+
99
+ Run 0 is the unchanged declared baseline. Give every run an immutable identity
100
+ and append it to one ledger before interpreting results.
101
+
102
+ | Run field | Record |
103
+ |---|---|
104
+ | Identity | Run ID, parent or warm-start ancestor, status, start/end time, and artifact paths. |
105
+ | Provenance | Exact code revision, data/split manifest, preprocessing state, package/environment identity, device, seed, and command or entry point. |
106
+ | Configuration | Complete resolved model, training, optimizer, schedule, reset, batching, and stopping configuration; do not store only overrides. |
107
+ | Outcomes | Raw training/validation curves, gradient and State diagnostics, checkpoints, runtime/resource data, and the primary plus guardrail metrics. |
108
+ | Decision | `CONTINUE`, `WAIT`, `STOP_INVALID`, `STOP_RULE`, `STOP_BUDGET`, or `COMPLETE`, with the evidence and locked rule that justified it. |
109
+
110
+ Do not compare a tuned run only with another tuned run. Preserve run 0 even
111
+ when it fails, because its failure constrains the next hypothesis.
112
+
113
+ ## Monitor process health and training quality
114
+
115
+ Check process liveness, device activity, checkpoint/log freshness, loss,
116
+ validation metric, learning rate, and gradient norm at the declared cadence. A
117
+ live process can train invalidly; unavailable metrics mean unknown, not failed.
118
+
119
+ | Evidence over the declared window | Decision | Action |
120
+ |---|---|---|
121
+ | Metrics are temporarily unreachable but the process is observable | `WAIT` | Retry observation; preserve the last evidence and make no quality claim. |
122
+ | Process exit, unexpected idle device, stale outputs, storage failure, or no checkpoint progress is confirmed | `STOP_INVALID` | Preserve logs and the last valid checkpoint; retry only the identical compatible run. |
123
+ | NaN/Inf, invalid gradients, State leakage, or target/reset misalignment appears | `STOP_INVALID` | Preserve the first failing step and diagnostics; return to implementation. |
124
+ | Training loss and the locked validation metric improve | `CONTINUE` | Continue; widen the check interval only after repeated healthy checks. |
125
+ | Metrics are flat, noisy, or slightly worse before minimum evidence or patience | `WAIT` | Keep or shorten the interval and gather the next planned checkpoint. |
126
+ | Loss diverges across the window, validation degradation exceeds patience, or gradients repeatedly explode or vanish | `STOP_RULE` | Stop under the locked rule and preserve the metric window and reason. |
127
+ | Maximum epochs or target criterion is reached with valid artifacts | `COMPLETE` | Close the run and compare it through the locked selection rule. |
128
+ | The tuning budget is exhausted | `STOP_BUDGET` | Launch no new configuration; compare every completed or invalidated run. |
129
+
130
+ Do not stop on one noisy point. For every stop, record the run ID, metric window,
131
+ checkpoint and log paths, exact rule, and reason. Monitoring ends or invalidates
132
+ a run; it never validates a scientific claim.
133
+
134
+ ## Tune hyperparameters with bounded evidence
135
+
136
+ Use this bounded hyperparameter-tuning loop: `run -> analyze -> record ->
137
+ choose`. Do not launch tuning until run 0 and the mechanical gates establish
138
+ what needs improvement.
139
+
140
+ 1. Diagnose the limiting signal from the complete run history: optimization,
141
+ generalization, temporal credit assignment, gradient scale, State leakage,
142
+ capacity, or compute/memory.
143
+ 2. State one falsifiable tuning hypothesis and the validation result that would
144
+ support or reject it.
145
+ 3. Choose the smallest coherent parameter set that tests that hypothesis. Give
146
+ each value a type, range, scale, default, and scientific or optimization
147
+ rationale.
148
+ 4. Create a complete new run record before execution. Change no unrecorded
149
+ model, split, preprocessing, reset, metric, seed aggregation, or stop rule.
150
+ 5. Analyze the primary validation metric with its guardrails, gradient/State
151
+ diagnostics, resource cost, and variability. Append failed, stopped, and
152
+ pruned runs to the same ledger.
153
+ 6. Stop when the locked budget or patience is exhausted, the hypothesis is
154
+ rejected, gradients or data become invalid, or no remaining candidate can
155
+ answer the declared question.
156
+
157
+ Establish `Adam` or another routed canonical baseline before a specialized
158
+ optimizer. Do not change optimizer, scheduler, surrogate, temporal reduction,
159
+ reset policy, and architecture together. When parallel resources are available,
160
+ run independent configurations concurrently only if each has an allocated
161
+ budget entry, isolated BrainState/RNG/checkpoint artifacts, and the same locked
162
+ comparison contract.
163
+
164
+ ## Resume and reuse checkpoints safely
165
+
166
+ Checkpoint compatibility is a State-graph and experiment-contract decision,
167
+ not a matching filename.
168
+
169
+ | Case | Rule |
170
+ |---|---|
171
+ | Resume an interrupted run | Restore model parameters, optimizer and scheduler State, RNG State, counters, preprocessing identity, and runtime configuration only when the complete configuration and State tree are identical. |
172
+ | Compare independent hyperparameter candidates | Start every candidate from the same declared initialization or base checkpoint. Do not give one candidate inherited training progress and compare it as an independent run. |
173
+ | Warm-start a later phase | Permit only when the plan declares a dependent phase and parameter structure, shapes, dtypes, units, task, targets, preprocessing, partitions, model dynamics, and runtime-State contract remain compatible. Record the ancestor checkpoint. |
174
+ | Change optimizer or schedule | Parameter-only restore may be valid, but do not restore incompatible optimizer or scheduler State; treat the run as a warm start, not an identical resume. |
175
+ | Change architecture, parameter shapes, solver, `dt`, surrogate, target semantics, preprocessing, data partitions, or State/reset meaning | Restart from the declared initialization. Do not coerce or partially load State to preserve progress. |
176
+
177
+ Save checkpoint metadata with the full State-tree signature and resolved
178
+ configuration. Validate a restored checkpoint with one deterministic evaluation
179
+ before training continues.
180
+
181
+ ## Select without touching held-out data
182
+
183
+ Apply the locked checkpoint rule to validation evidence only. Confirm the
184
+ selected configuration across every declared seed or replication and report
185
+ seed-wise results plus the locked aggregate; never select or present the best
186
+ seed alone.
187
+
188
+ After every modeling, preprocessing, tuning, checkpoint, seed, and stop decision
189
+ is frozen, restore the selected checkpoint for each declared replica, reset
190
+ evaluation State, and evaluate the untouched held-out partition. Preserve raw
191
+ predictions, sample IDs, per-sample or per-group metrics, aggregation, and
192
+ uncertainty. Do not tune, choose another checkpoint, or suppress a seed after
193
+ seeing held-out results.
194
+
195
+ Successful optimization proves that the declared training pipeline can learn
196
+ the task under its tested conditions. It does not by itself establish
197
+ biological validity, mechanism recovery, identifiability, or generalization
198
+ beyond the locked held-out population.
199
+
200
+ ## Return training evidence to the modeling loop
201
+
202
+ Return these artifacts through steps 2-5 of `brainx-modeling-loop`:
203
+
204
+ - the locked training contract, split IDs, and fitted preprocessing state;
205
+ - axis, unit, target-alignment, State-selection, reset, gradient, and tiny-case
206
+ tests;
207
+ - run 0 and the immutable ledger for every completed, stopped, failed, or pruned
208
+ run;
209
+ - raw training and validation curves plus process, gradient, State, runtime, and
210
+ resource diagnostics;
211
+ - every checkpoint, its selection trace, State-tree signature, and compatibility
212
+ decision;
213
+ - seed-wise and aggregate validation results;
214
+ - the untouched held-out predictions, metrics, aggregation, and uncertainty;
215
+ - unresolved training limitations and every claim this evidence does not
216
+ support.
217
+
218
+ Report an out-of-contract request to change the task, target, independence unit,
219
+ data inclusion, primary metric, or accepted claim. Do not edit the locked
220
+ specification inside this coverage. Report implementation, optimizer, schedule,
221
+ reset, checkpoint, or bounded-tuning defects as exact in-contract corrections.
222
+ Step 5 still emits only `REFUSE` or `PASS` and owns the loop transition.
223
+
224
+ ## Common failures
225
+
226
+ - Random row splitting when subjects, sessions, sequences, or neighboring time
227
+ windows are the independence unit.
228
+ - Learned preprocessing fitted outside the training partition.
229
+ - BrainCell scientific-parameter estimation mislabeled as task training.
230
+ - Hidden or runtime State included in the optimizer collection.
231
+ - Dynamical State carried across independent samples or reset across a boundary
232
+ that should preserve it.
233
+ - Raw `jax.grad`, `jax.jit`, or a non-BrainX trainer wrapped around
234
+ State-mutating BrainX code.
235
+ - Target indices shifted relative to the temporal output being scored, or padded
236
+ timesteps included in the loss.
237
+ - Optimizer updates placed inside a temporal loop when the contract specifies
238
+ one update per complete sequence or minibatch.
239
+ - Tuning started before finite gradients and tiny-case overfitting pass.
240
+ - Multiple optimizer, surrogate, architecture, reset, and reduction decisions
241
+ changed in one run without a testable hypothesis.
242
+ - Checkpoint selection, early stopping, seed choice, or tuning influenced by
243
+ held-out metrics.
244
+ - A warm-started run compared as if it were an independent candidate.
245
+ - Best-seed reporting, silent failed-run exclusion, or aggregation changed after
246
+ results.
247
+ - BrainTrace activated for generic speed rather than a demonstrated temporal
248
+ memory bottleneck and an accepted estimator boundary.
249
+
250
+ ## Package and reference routing
251
+
252
+ Read every active modeling skill before implementing training, then open only
253
+ the smallest routed reference that owns the next decision. The package skills
254
+ own model construction and train-step mechanics; this reference owns the
255
+ training contract, gates, experiment discipline, and evidence.
256
+
257
+ | Need | Required route |
258
+ |---|---|
259
+ | Large temporal workloads limited by sequence-length-dependent BPTT activation memory | First open the active package's checkpointed-control-flow reference. When ordinary BPTT remains memory-limited and an online eligibility-trace estimator is scientifically acceptable, open `skills/package-skills/braintrace/SKILL.md` and use BrainTrace as the memory-efficient alternative. Its memory is constant only in sequence length and still scales with batch size, participating parameters, hidden dimensions, and estimator choice. |
260
+
261
+ ### Choose Braintools training components
262
+
263
+ | Decision | BrainPy-State route | BrainMass route |
264
+ |---|---|---|
265
+ | Loss or neuroscience metric | `skills/package-skills/brainpy-state/references/braintools/metric.md` | `skills/package-skills/brainmass/references/braintools/metric.md` |
266
+ | Optimizer, scheduler, clipping, or update lifecycle | `skills/package-skills/brainpy-state/references/braintools/optimizer.md` | `skills/package-skills/brainmass/references/braintools/optimizer.md` |
267
+ | Parameter initialization | `skills/package-skills/brainpy-state/references/braintools/parameter-initializer.md` | `skills/package-skills/brainmass/references/braintools/parameter-initializer.md` |
268
+ | Input encoding | `skills/package-skills/brainpy-state/references/braintools/data-preprocessing.md` | `skills/package-skills/brainmass/references/braintools/data-preprocessing.md` |
269
+ | Hard-spike backward derivative | `skills/package-skills/brainpy-state/references/braintools/surrogate.md` | `skills/package-skills/brainmass/references/braintools/surrogate.md` |
270
+ | Phase-structured cognitive trials | Open the shared `skills/package-skills/brainmass/references/braintools/cogtask.md`, then preserve the BrainPy-State model's time-major input contract. | `skills/package-skills/brainmass/references/braintools/cogtask.md` |
@@ -13,7 +13,7 @@ Use BrainCell for cellular biophysics at either of its two supported spatial sca
13
13
  - Use `Cell` when soma, dendrite, axon, branch geometry, spatial channel distribution, or location-specific stimulation and recording affect the result.
14
14
 
15
15
 
16
- Keep network wiring, projections, and network training outside this skill. Open `skills/brainpy-state/SKILL.md` when multiple cells must communicate.
16
+ Keep network wiring, projections, and network training outside this skill. Open `skills/package-skills/brainpy-state/SKILL.md` when multiple cells must communicate.
17
17
 
18
18
  ## Underlying principle of BrainCell
19
19
 
@@ -176,6 +176,7 @@ Open only the smallest reference that owns the non-canonical decision.
176
176
  | `references/area-scaled-hh-pattern.md` | Changing single-compartment geometry or converting density parameters consistently to total capacitance and conductance. |
177
177
  | `references/braincell-custom-ion-channel-authoring.md` | Implementing a custom ion or channel after confirming that no built-in mechanism fits. |
178
178
  | `references/channel-library.md` | Selecting a built-in sodium, potassium, calcium, leak, HCN, or mixed-ion channel. |
179
+ | `references/scripts/fitting_hh_neuron.py` | Studying the official complete HH fitting composition: custom sodium and potassium channels, trace loading, unit-bearing bounds, independent cell initialization, time-major rollout, voltage loss, candidate `vmap`, and Nevergrad. Supply the upstream trace CSVs and reconcile its source-version APIs with the current BrainCell and BrainState skills before adapting it. |
179
180
  | `references/ion-library.md` | Choosing fixed, Nernst-initialized, or dynamic ions and their concentration behavior. |
180
181
  | `references/mixions-for-adaptation.md` | Adding calcium-dependent adaptation, AHP/KCa currents, rebound, dynamic calcium, or multi-ion channel dependencies. |
181
182
  | `references/multicompartment/multicompartment-cell-workflow.md` | Extending the canonical `Morphology -> Cell -> paint/place -> run` path and selecting the exclusive multicompartment references. |
@@ -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