brainx-skill 1.0.11 → 1.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +4 -0
  2. package/installation/lib/bundle.js +51 -13
  3. package/manifest.json +2 -0
  4. package/mcp-servers/codex/README.md +62 -0
  5. package/mcp-servers/codex/UPSTREAM.md +20 -0
  6. package/mcp-servers/codex/server.mjs +140 -0
  7. package/mcp-servers/codex/skills.json +10 -0
  8. package/mcp-servers/codex/system-prompt.md +62 -0
  9. package/mcp-servers/codex/test/fixtures/fake-codex.mjs +6 -0
  10. package/mcp-servers/codex/test/server.test.mjs +88 -0
  11. package/package.json +6 -9
  12. package/skills/brainx-acceleration/SKILL.md +459 -0
  13. package/skills/brainx-general-guard/SKILL.md +67 -37
  14. package/skills/brainx-install/SKILL.md +21 -24
  15. package/skills/brainx-modeling-loop/SKILL.md +268 -0
  16. package/skills/brainx-modeling-loop/agents/openai.yaml +4 -0
  17. package/skills/brainx-modeling-loop/references/monitor-experiment.md +49 -0
  18. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow/scripts/fitting_hh_neuron.py +254 -0
  19. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +232 -0
  20. package/skills/brainx-modeling-loop/references/run-experiment.md +179 -0
  21. package/skills/brainx-modeling-loop/references/training-workflow.md +270 -0
  22. package/skills/{braincell → package-skills/braincell}/SKILL.md +3 -16
  23. package/skills/{braincell → package-skills/braincell}/references/mixions-for-adaptation.md +26 -3
  24. package/skills/{braincell → package-skills/braincell}/references/multicompartment/multicompartment-cell-workflow.md +2 -2
  25. package/skills/package-skills/braincell/references/scripts/fitting_hh_neuron.py +254 -0
  26. package/skills/package-skills/braincell/references/scripts/spike_frequency_adaptation.py +135 -0
  27. package/skills/{brainevent → package-skills/brainevent}/SKILL.md +0 -1
  28. package/skills/package-skills/brainevent/references/synaptic-plasticity.md +129 -0
  29. package/skills/{brainmass → package-skills/brainmass}/SKILL.md +10 -5
  30. package/skills/{brainmass → package-skills/brainmass}/references/batch-transform-acceleration.md +44 -3
  31. package/skills/{brainmass → package-skills/brainmass}/references/brainstate/parameter-constraints-regularization.md +1 -1
  32. package/skills/{brainmass → package-skills/brainmass}/references/coupling-network-api.md +121 -3
  33. package/skills/{brainmass → package-skills/brainmass}/references/modellibrary.md +90 -1
  34. package/skills/package-skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +188 -0
  35. package/skills/package-skills/brainmass/references/simulator-input-monitor-api.md +98 -0
  36. package/skills/{brainmass → package-skills/brainmass}/references/visualization-analysis-api.md +6 -6
  37. package/skills/{brainpy-state → package-skills/brainpy-state}/SKILL.md +17 -8
  38. package/skills/{brainpy-state → package-skills/brainpy-state}/references/brain-dynamics-delay-protocol.md +52 -1
  39. package/skills/package-skills/brainpy-state/references/braintools/connectivity.md +206 -0
  40. package/skills/package-skills/brainpy-state/references/braintools/input-current.md +199 -0
  41. package/skills/{brainpy-state → package-skills/brainpy-state}/references/component-selection.md +20 -5
  42. package/skills/package-skills/brainpy-state/references/perturbation-experiment-validity.md +76 -0
  43. package/skills/{brainpy-state → package-skills/brainpy-state}/references/projection-patterns.md +3 -1
  44. package/skills/package-skills/brainpy-state/references/scripts/sound_localization.py +240 -0
  45. package/skills/{brainstate → package-skills/brainstate}/SKILL.md +12 -15
  46. package/skills/package-skills/brainstate/agents/openai.yaml +4 -0
  47. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/brainstate-control-flow-patterns.md +8 -0
  48. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/brainstate-transformed-diagnostics.md +1 -1
  49. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/parameter-constraints-regularization.md +1 -1
  50. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/randomness-and-reproducibility.md +1 -1
  51. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-grad-expansion.md +2 -2
  52. package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-vmap-expansion.md +58 -8
  53. package/skills/{brainstate → package-skills/brainstate}/references/collective_model_operations.md +26 -27
  54. package/skills/{brainstate → package-skills/brainstate}/references/libraries/prebuilt-layer-library.md +1 -1
  55. package/skills/package-skills/brainstate/references/paired-perturbation-execution.md +113 -0
  56. package/skills/package-skills/braintrace/SKILL.md +187 -0
  57. package/skills/package-skills/braintrace/references/Drtrl.md +133 -0
  58. package/skills/{braintrace → package-skills/braintrace}/references/ETP operators.md +31 -4
  59. package/skills/package-skills/braintrace/references/algorithm selection.md +64 -0
  60. package/skills/package-skills/braintrace/references/batching.md +140 -0
  61. package/skills/{braintrace → package-skills/braintrace}/references/compiler_internal.md +2 -2
  62. package/skills/{braintrace → package-skills/braintrace}/references/custom algorithms.md +8 -10
  63. package/skills/package-skills/braintrace/references/pp_pprop workflow.md +179 -0
  64. package/skills/{braintrace → package-skills/braintrace}/references/pre-built-braintrace-layer.md +2 -2
  65. package/skills/{brainpy-state → package-skills/brainunit}/references/array-creation.md +2 -2
  66. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +0 -75
  67. package/skills/brainevent/references/synaptic-plasticity.md +0 -285
  68. package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +0 -130
  69. package/skills/brainstate/references/braintools/optimizer.md +0 -179
  70. package/skills/braintrace/SKILL.md +0 -161
  71. package/skills/braintrace/references/Drtrl.md +0 -179
  72. package/skills/braintrace/references/algorithm selection.md +0 -120
  73. package/skills/braintrace/references/batching.md +0 -150
  74. package/skills/braintrace/references/pp_pprop workflow.md +0 -196
  75. /package/skills/{braincell → package-skills/braincell}/references/area-scaled-hh-pattern.md +0 -0
  76. /package/skills/{braincell → package-skills/braincell}/references/braincell-custom-ion-channel-authoring.md +0 -0
  77. /package/skills/{braincell → package-skills/braincell}/references/channel-library.md +0 -0
  78. /package/skills/{braincell → package-skills/braincell}/references/ion-library.md +0 -0
  79. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/braincell-manual-morphology-construction.md +0 -0
  80. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/cv-policy-reference.md +0 -0
  81. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/filter-function-library.md +0 -0
  82. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/morphology-io-loading-validation.md +0 -0
  83. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/probe-reference.md +0 -0
  84. /package/skills/{braincell → package-skills/braincell}/references/multicompartment/topology-building-and-visualization.md +0 -0
  85. /package/skills/{braincell → package-skills/braincell}/references/scripts/calcium_channel_gating.py +0 -0
  86. /package/skills/{braincell → package-skills/braincell}/references/scripts/cell_multicompartment_reference.py +0 -0
  87. /package/skills/{braincell → package-skills/braincell}/references/scripts/channel_ablation.py +0 -0
  88. /package/skills/{braincell → package-skills/braincell}/references/scripts/fi_curve.py +0 -0
  89. /package/skills/{braincell → package-skills/braincell}/references/scripts/hh_neuron_basics.py +0 -0
  90. /package/skills/{braincell → package-skills/braincell}/references/scripts/t_current_rebound.py +0 -0
  91. /package/skills/{braincell → package-skills/braincell}/references/scripts/thalamic_neurons.py +0 -0
  92. /package/skills/{braincell → package-skills/braincell}/references/solver-library-with-effects.md +0 -0
  93. /package/skills/{brainevent → package-skills/brainevent}/references/connectivity-variants.md +0 -0
  94. /package/skills/{brainevent → package-skills/brainevent}/references/custom-operators-cpu.md +0 -0
  95. /package/skills/{brainevent → package-skills/brainevent}/references/custom-operators-gpu.md +0 -0
  96. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/102_EI_net_1996.py +0 -0
  97. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/204_joglekar_2018_propagation.py +0 -0
  98. /package/skills/{brainevent → package-skills/brainevent}/references/scripts/coba_ei_teaching.py +0 -0
  99. /package/skills/{brainevent → package-skills/brainevent}/references/sparse-formats.md +0 -0
  100. /package/skills/{brainmass → package-skills/brainmass}/references/brainstate/parameter-transforms-regularizers-catalog.md +0 -0
  101. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/cogtask.md +0 -0
  102. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/data-preprocessing.md +0 -0
  103. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/metric.md +0 -0
  104. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/optimizer.md +0 -0
  105. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/parameter-initializer.md +0 -0
  106. /package/skills/{brainmass → package-skills/brainmass}/references/braintools/surrogate.md +0 -0
  107. /package/skills/{brainmass → package-skills/brainmass}/references/datasets-api.md +0 -0
  108. /package/skills/{brainmass → package-skills/brainmass}/references/fitting-with-objectives-api.md +0 -0
  109. /package/skills/{brainmass → package-skills/brainmass}/references/forward-observation-api.md +0 -0
  110. /package/skills/{brainmass → package-skills/brainmass}/references/horn-task-training.md +0 -0
  111. /package/skills/{brainmass → package-skills/brainmass}/references/noiseprocesses.md +0 -0
  112. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/eeg-fitting-with-gradients.py +0 -0
  113. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/gradient-free-fitting.py +0 -0
  114. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/hopf-bifurcation-single-node.py +0 -0
  115. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/horn-cognitive-task-training.py +0 -0
  116. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/jansen-rit-eeg-proxy.py +0 -0
  117. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/kuramoto-synchronization.py +0 -0
  118. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/linear-baseline-node.py +0 -0
  119. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/resting-state-meg-whole-brain-pipeline.py +0 -0
  120. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/seizure-epileptor-case-study.py +0 -0
  121. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wilson-cowan-ei-dynamics.py +0 -0
  122. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wong-wang-decision-making.py +0 -0
  123. /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wong-wang-dmf-resting-state.py +0 -0
  124. /package/skills/{brainunit → package-skills/brainpy-state}/references/array-creation.md +0 -0
  125. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/analysis.md +0 -0
  126. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/brainpy legacy workflow.md +0 -0
  127. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/built-in dynamic neuron model.md +0 -0
  128. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/connecting neurons.md +0 -0
  129. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/customize neuron and synpase.md +0 -0
  130. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Input generation.md +0 -0
  131. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/More about simulation.md +0 -0
  132. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +0 -0
  133. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +0 -0
  134. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +0 -0
  135. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +0 -0
  136. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/delays.md +0 -0
  137. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +0 -0
  138. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/integrators.md +0 -0
  139. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/route activity through connectivity.md +0 -0
  140. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/synaptic projections.md +0 -0
  141. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/synpase properties.md +0 -0
  142. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/loss library.md +0 -0
  143. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/optimizers.md +0 -0
  144. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/parameter initializers.md +0 -0
  145. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/prebuilt neural network layers.md +0 -0
  146. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/surrogate gradients.md +0 -0
  147. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/trainer library.md +0 -0
  148. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/trainingworkflows.md +0 -0
  149. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/brainstate-control-flow-patterns.md +0 -0
  150. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/data-preprocessing.md +0 -0
  151. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/metric.md +0 -0
  152. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/optimizer.md +0 -0
  153. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/parameter-initializer.md +0 -0
  154. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/surrogate.md +0 -0
  155. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/devices.md +0 -0
  156. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/divergence-and-parity.md +0 -0
  157. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/integration-categories.md +0 -0
  158. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/model-library.md +0 -0
  159. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/nest-workflow.md +0 -0
  160. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/network-building.md +0 -0
  161. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brette_et_al_2007.py +0 -0
  162. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brunel_alpha.py +0 -0
  163. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brunel_delta.py +0 -0
  164. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +0 -0
  165. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +0 -0
  166. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/spatial_gaussex.py +0 -0
  167. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/synapsecollection.py +0 -0
  168. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/synapse-and-connectivity.md +0 -0
  169. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/103_COBA_2005.py +0 -0
  170. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/106_COBA_HH_2007.py +0 -0
  171. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/107_gamma_oscillation_1996.py +0 -0
  172. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/109_fast_global_oscillation.py +0 -0
  173. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +0 -0
  174. /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/training-snn.py +0 -0
  175. /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/parameter-transforms-regularizers-catalog.md +0 -0
  176. /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-jit-expansion.md +0 -0
  177. /package/skills/{brainstate → package-skills/brainstate}/references/extension_mechanisms.md +0 -0
  178. /package/skills/{brainstate → package-skills/brainstate}/references/libraries/prebuilt-activation-library.md +0 -0
  179. /package/skills/{brainstate → package-skills/brainstate}/references/model-interop-and-migration.md +0 -0
  180. /package/skills/{brainstate → package-skills/brainstate}/references/simulation-environment.md +0 -0
  181. /package/skills/{brainstate → package-skills/brainstate}/references/size-inference-variations.md +0 -0
  182. /package/skills/{brainstate → package-skills/brainstate}/references/state-graph-operations.md +0 -0
  183. /package/skills/{brainstate → package-skills/brainstate}/references/state_collections_and_utilities.md +0 -0
  184. /package/skills/{brainstate → package-skills/brainstate}/scripts/integrator_rnn.py +0 -0
  185. /package/skills/{brainstate → package-skills/brainstate}/scripts/lif_neuron_model.py +0 -0
  186. /package/skills/{brainstate → package-skills/brainstate}/scripts/modern_cnn.py +0 -0
  187. /package/skills/{brainstate → package-skills/brainstate}/scripts/resnet.py +0 -0
  188. /package/skills/{braintrace → package-skills/braintrace}/references/custom ETP primitives.md +0 -0
  189. /package/skills/{braintrace → package-skills/braintrace}/references/customizing_primitive_transforms.md +0 -0
  190. /package/skills/{brainunit → package-skills/brainunit}/SKILL.md +0 -0
  191. /package/skills/{brainunit → package-skills/brainunit}/references/array-mechanics/functional-structural-api.md +0 -0
  192. /package/skills/{brainunit → package-skills/brainunit}/references/array-mechanics.md +0 -0
  193. /package/skills/{brainunit → package-skills/brainunit}/references/math-function-library.md +0 -0
  194. /package/skills/{brainunit → package-skills/brainunit}/references/physical-constant-library.md +0 -0
  195. /package/skills/{brainunit → package-skills/brainunit}/references/prefix-library.md +0 -0
  196. /package/skills/{brainunit → package-skills/brainunit}/references/quantity-inspection-and-conversion.md +0 -0
  197. /package/skills/{brainunit → package-skills/brainunit}/references/typing-and-runtime-validation.md +0 -0
  198. /package/skills/{brainunit → package-skills/brainunit}/references/unit-structure-and-definition.md +0 -0
@@ -0,0 +1,254 @@
1
+ # Copyright 2024 BrainX Ecosystem Limited. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+
17
+ from pathlib import Path
18
+ from typing import Union, Callable
19
+
20
+ import brainstate
21
+ import braintools
22
+ import brainunit as u
23
+ import jax
24
+ import matplotlib.pyplot as plt
25
+ import numpy as np
26
+ import pandas as pd
27
+
28
+ import braincell
29
+
30
+ brainstate.environ.set(dt=0.01 * u.ms)
31
+
32
+ # Load Input and Output Data
33
+ DATA_DIR = Path(__file__).resolve().parents[2] / "data" / "neuron_traces"
34
+ df_inp_traces = pd.read_csv(DATA_DIR / 'input_traces_hh.csv')
35
+ df_out_traces = pd.read_csv(DATA_DIR / 'output_traces_hh.csv')
36
+
37
+ area = 20000 * u.um ** 2 # neuronal area
38
+ inp_traces = df_inp_traces.to_numpy()[:, 1:] * 1e9 * u.nA # input currents
39
+ mem_traces = df_out_traces.to_numpy()[:, 1:] * u.mV # membrane potentials to record
40
+
41
+
42
+ class INa(braincell.Channel):
43
+ root_type = braincell.HHTypedNeuron
44
+
45
+ def __init__(
46
+ self,
47
+ size: brainstate.typing.Size,
48
+ ENa: Union[brainstate.typing.ArrayLike, Callable] = 50. * u.mV,
49
+ gNa: Union[brainstate.typing.ArrayLike, Callable] = 120. * u.mS,
50
+ vth: Union[brainstate.typing.ArrayLike, Callable] = -63 * u.mV,
51
+ ):
52
+ super().__init__(size)
53
+ self.ENa = braintools.init.param(ENa, self.varshape)
54
+ self.gNa = braintools.init.param(gNa, self.varshape)
55
+ self.V_th = braintools.init.param(vth, self.varshape)
56
+
57
+ def init_state(self, V, batch_size=None):
58
+ self.m = braincell.state(braintools.init.param(u.math.zeros, self.varshape))
59
+ self.h = braincell.state(braintools.init.param(u.math.zeros, self.varshape))
60
+
61
+ # m channel
62
+ m_alpha = lambda self, V: 0.32 * 4 / u.math.exprel((13. * u.mV - V + self.V_th).to_decimal(u.mV) / 4.)
63
+ m_beta = lambda self, V: 0.28 * 5 / u.math.exprel((V - self.V_th - 40. * u.mV).to_decimal(u.mV) / 5.)
64
+ m_inf = lambda self, V: self.m_alpha(V) / (self.m_alpha(V) + self.m_beta(V))
65
+
66
+ # h channel
67
+ h_alpha = lambda self, V: 0.128 * u.math.exprel((17. * u.mV - V + self.V_th).to_decimal(u.mV) / 18.)
68
+ h_beta = lambda self, V: 4. / (1 + u.math.exp((40. * u.mV - V + self.V_th).to_decimal(u.mV) / 5.))
69
+ h_inf = lambda self, V: self.h_alpha(V) / (self.h_alpha(V) + self.h_beta(V))
70
+
71
+ def compute_derivative(self, V, *args, **kwargs):
72
+ m = self.m.value
73
+ h = self.h.value
74
+ self.m.derivative = (self.m_alpha(V) * (1 - m) - self.m_beta(V) * m) / u.ms
75
+ self.h.derivative = (self.h_alpha(V) * (1 - h) - self.h_beta(V) * h) / u.ms
76
+
77
+ def current(self, V, *args, **kwargs):
78
+ m = self.m.value
79
+ h = self.h.value
80
+ return (self.gNa * m * m * m * h) * (self.ENa - V)
81
+
82
+
83
+ class IK(braincell.Channel):
84
+ root_type = braincell.HHTypedNeuron
85
+
86
+ def __init__(
87
+ self,
88
+ size: brainstate.typing.Size,
89
+ EK: Union[brainstate.typing.ArrayLike, Callable] = -90. * u.mV,
90
+ gK: Union[brainstate.typing.ArrayLike, Callable] = 36. * u.mS,
91
+ vth: Union[brainstate.typing.ArrayLike, Callable] = -63 * u.mV,
92
+ ):
93
+ super().__init__(size)
94
+ self.EK = braintools.init.param(EK, self.varshape)
95
+ self.gK = braintools.init.param(gK, self.varshape)
96
+ self.V_th = braintools.init.param(vth, self.varshape)
97
+
98
+ def init_state(self, V, batch_size=None):
99
+ self.n = braincell.state(braintools.init.param(u.math.zeros, self.varshape))
100
+
101
+ # n channel
102
+ n_alpha = lambda self, V: 0.032 * 5 / u.math.exprel((15. * u.mV - V + self.V_th).to_decimal(u.mV) / 5.)
103
+ n_beta = lambda self, V: .5 * u.math.exp((10. * u.mV - V + self.V_th).to_decimal(u.mV) / 40.)
104
+ n_inf = lambda self, V: self.n_alpha(V) / (self.n_alpha(V) + self.n_beta(V))
105
+
106
+ def compute_derivative(self, V, *args, **kwargs):
107
+ n = self.n.value
108
+ self.n.derivative = (self.n_alpha(V) * (1 - n) - self.n_beta(V) * n) / u.ms
109
+
110
+ def current(self, V, *args, **kwargs):
111
+ n2 = self.n.value ** 2
112
+ return (self.gK * n2 * n2) * (self.EK - V)
113
+
114
+
115
+ class HH(braincell.SingleCompartment):
116
+ def __init__(
117
+ self,
118
+ size,
119
+ v_initializer: Callable = braintools.init.Uniform(-70 * u.mV, -60. * u.mV),
120
+ gL: Union[brainstate.typing.ArrayLike, Callable] = 0.003 * u.mS,
121
+ gNa: Union[brainstate.typing.ArrayLike, Callable] = 120. * u.mS,
122
+ gK: Union[brainstate.typing.ArrayLike, Callable] = 36. * u.mS,
123
+ C: Union[brainstate.typing.ArrayLike, Callable] = 1. * (u.uF / u.cm ** 2),
124
+ solver: str = 'rk4'
125
+ ):
126
+ super().__init__(size, V_initializer=v_initializer, C=C, solver=solver)
127
+ self.ina = INa(size, gNa=gNa)
128
+ self.ik = IK(size, gK=gK)
129
+ self.il = braincell.channel.IL(size, g_max=gL, E=-65. * u.mV)
130
+
131
+
132
+ def visualize_target(voltages):
133
+ fig, gs = braintools.visualize.get_figure(2, voltages.shape[1], 3, 4.5)
134
+ times = np.arange(voltages.shape[0]) * 0.01
135
+ for i in range(voltages.shape[1]):
136
+ ax = fig.add_subplot(gs[0, i])
137
+ ax.plot(times, voltages[:, i], label='target')
138
+ plt.xlabel('Time [ms]')
139
+ plt.legend()
140
+ ax = plt.subplot(gs[1, i])
141
+ ax.plot(times, inp_traces[i])
142
+ plt.xlabel('Time [ms]')
143
+ plt.show()
144
+
145
+
146
+ def visualize(voltages, gl, g_na, g_kd, C):
147
+ # currents: [T, B]
148
+ # voltages: [T, B]
149
+ simulated_vs = simulate_model(gl, g_na, g_kd, C)
150
+ voltages = voltages.mantissa
151
+
152
+ fig, gs = braintools.visualize.get_figure(2, simulated_vs.shape[1], 3, 4.5)
153
+ for i in range(simulated_vs.shape[1]):
154
+ ax = fig.add_subplot(gs[0, i])
155
+ ax.plot(voltages[:, i], label='target')
156
+ ax.plot(simulated_vs[:, i], label='simulated')
157
+ plt.legend()
158
+ ax = plt.subplot(gs[1, i])
159
+ ax.plot(inp_traces[i])
160
+ plt.show()
161
+
162
+
163
+ def simulate_model(gl, g_na, g_kd, C):
164
+ current = inp_traces.T
165
+ assert current.ndim == 2 # [T, B]
166
+ n_input = current.shape[1]
167
+ hh = HH((n_input, 1), gL=gl, gNa=g_na, gK=g_kd, C=C, v_initializer=braintools.init.Constant(-65. * u.mV), )
168
+ hh.init_state()
169
+
170
+ def step_fun(i, inp):
171
+ with brainstate.environ.context(i=i, t=brainstate.environ.get_dt() * i):
172
+ spike = hh(inp)
173
+ return hh.V.value
174
+
175
+ indices = np.arange(current.shape[0])
176
+ current = u.math.expand_dims(current, axis=-1) # [T, B, 1]
177
+ return brainstate.transform.for_loop(step_fun, indices, current) # (T, B)
178
+
179
+
180
+ def compare_potentials(param):
181
+ vs = simulate_model(param['gl'], param['g_na'], param['g_kd'], param['C']) # (T, B)
182
+ losses = braintools.metric.squared_error(vs.mantissa, target_vs.mantissa)
183
+ return losses.mean()
184
+
185
+
186
+ # inp_traces: [B, T]
187
+ # target_vs: [B, T, 1]
188
+ # target_vs = simulate_model(50.37195496 * u.nsiemens,
189
+ # 28.01317016 * u.usiemens,
190
+ # 8.15968937 * u.usiemens,
191
+ # 195.2173985 * u.pfarad)
192
+ target_vs = u.math.expand_dims(mem_traces.T, axis=-1) # [T, B, 1]
193
+
194
+
195
+ # visualize_target(target_vs)
196
+
197
+
198
+ def visualize_hh_input_and_output():
199
+ # Load Input and Output Data
200
+ inp_traces = df_inp_traces.to_numpy()
201
+ inp_traces = inp_traces[:, 1:] * 1e9
202
+
203
+ out_traces = df_out_traces.to_numpy()
204
+ out_traces = out_traces[:, 1:]
205
+
206
+ indices = np.arange(inp_traces.shape[1]) * 0.01
207
+
208
+ fig, gs = braintools.visualize.get_figure(3, 1, 1.2, 6.0)
209
+ ax = fig.add_subplot(gs[0, 0])
210
+ ax.plot(indices, inp_traces.T)
211
+ plt.xticks([])
212
+ plt.ylabel('Current [nA]', fontsize=13)
213
+
214
+ ax2 = fig.add_subplot(gs[1:, 0])
215
+ ax2.plot(indices, out_traces.T)
216
+ plt.ylabel('Potential [mV]', fontsize=13)
217
+ plt.xlabel('Time [ms]')
218
+
219
+ fig.align_ylabels([ax, ax2])
220
+ plt.show()
221
+
222
+
223
+ bounds = {
224
+ 'gl': [1e0, 1e2] * u.nS,
225
+ 'g_na': [1e0, 2e2] * u.uS,
226
+ 'g_kd': [1e0, 1e2] * u.uS,
227
+ 'C': [0.1, 2] * u.uF * u.cm ** -2 * area,
228
+ }
229
+
230
+
231
+ def fitting_by_nevergrad(method='DE', n_sample=200, n_iter=20):
232
+ print(f"Method: {method}, n_sample: {n_sample}")
233
+
234
+ @brainstate.transform.jit
235
+ def loss_with_multiple_run(**params):
236
+ return brainstate.transform.vmap(compare_potentials)(params)
237
+
238
+ opt = braintools.optim.NevergradOptimizer(
239
+ loss_with_multiple_run,
240
+ n_sample=n_sample,
241
+ bounds=bounds,
242
+ method=method,
243
+ )
244
+ opt.initialize()
245
+ param = opt.minimize(n_iter)
246
+ loss = compare_potentials(param)
247
+ print(param)
248
+ print(loss)
249
+ visualize(target_vs, **param)
250
+ return param, loss
251
+
252
+
253
+ if __name__ == '__main__':
254
+ fitting_by_nevergrad(n_sample=100)
@@ -0,0 +1,232 @@
1
+ # BrainX parameter-fitting workflow
2
+
3
+ ## Purpose and boundary
4
+
5
+ Use this reference after `brainx-general-guard` selects the represented biological scales and their owning model skills. Keep model construction, simulation, physical units, dynamical State, observation, and biological meaning inside the active BrainX route while estimating unknown parameters from observed data.
6
+
7
+ Use this reference for the `parameter-fitting` part of `brainx-modeling-loop` steps 2-5. Keep task-training objectives, data splits, and State lifecycles separate during a `hybrid` workflow. Route parameter sweeps without observed targets to the active model skill instead.
8
+
9
+ ## Underlying mental model
10
+
11
+ A parameter map represents the scientific unknowns. It binds every optimizer coordinate to one named BrainX value, physical unit, valid domain, transform, and reporting meaning.
12
+
13
+ The BrainX simulator represents the generative model. Fitted parameter State persists while membrane, channel, synaptic, delay, noise, monitor, and other runtime State follow an explicit reset policy for every independent candidate and protocol.
14
+
15
+ The observation model represents measurement. It maps latent BrainX output into the same signal, axes, time base, preprocessing, missingness, and units as the observed data before the objective is evaluated.
16
+
17
+ The objective represents the fitting claim. It defines which discrepancy is minimized, how components are weighted and reduced, and which observations are reserved for validation.
18
+
19
+ Parameter recovery represents the interpretation gate. A fitted value may support a mechanistic claim only when the exact fitting pipeline can recover that parameter under the actual observation protocol.
20
+
21
+ ## API structure overview
22
+
23
+ | Need | Required route |
24
+ |---|---|
25
+ | Ion, channel, compartment, morphology, or conductance fitting | Open `braincell` for the model and `brainstate` for custom State-aware differentiation. Recreate or reset all cell runtime State for every independent candidate. |
26
+ | Point-neuron, synapse, or spiking-network fitting | Open `brainpy-state`. Route custom gradients through `brainstate`; open the BrainPy-State surrogate reference only when gradients must cross a discrete spike operation. |
27
+ | Aggregate population, region, or whole-brain fitting | Open `brainmass`. Prefer `brainmass.Fitter` and its routed fitting reference before building a custom optimizer loop. |
28
+ | Physical parameters or observations | Open `brainunit`. Preserve quantities through parameter application, simulation, observation, and unit-compatible comparison. |
29
+ | Constrained parameters or regularization | Open the active package's BrainState parameter reference. Record both the unconstrained optimizer value and constrained physical value. |
30
+ | Objective or optimizer selection | Open the active package's Braintools metric or optimizer reference. Prefer package-owned BrainMass objectives when they express the scientific comparison. |
31
+
32
+ Study the selected package skills and their fitting-related examples before implementing. Trace construction, initialization, parameter application, runtime State reset, protocol execution, observation, and reduction end to end.
33
+
34
+ ## Lock the fitting contract
35
+
36
+ Lock these decisions before inspecting observed-data fit results.
37
+
38
+ | Contract field | Required decision |
39
+ |---|---|
40
+ | Scientific target | Classify fitted, fixed, nuisance, observation, hierarchical, and initial-state parameters. State which fitted values require mechanistic interpretation. |
41
+ | Parameter domain | Record name, BrainX destination, unit, valid bounds, transform, initialization, and provenance. Do not invent biological precision. |
42
+ | Data contract | Record independence unit, axes, sampling or time base, physical units, missingness, and immutable fit, validation, and held-out partitions. |
43
+ | Protocol | Match input currents, stimuli, duration, trial count, conditions, noise, initial conditions, and reset boundaries to the observed experiment. |
44
+ | Observation model | Define filtering, mixing, forward modeling, delays, downsampling, feature extraction, normalization, and measurement noise from latent State to data. |
45
+ | Objective | Define every component, direction, weight, reduction axis, normalization, regularizer, and invalid-domain result. |
46
+ | Estimator | Lock backend, starts, seeds, budget, convergence or stopping rule, and candidate-selection rule. |
47
+ | Validation | Lock domain tests, gradient or candidate-batch checks, recovery design, predictive checks, and parameter-specific interpretation criteria. |
48
+
49
+ Use one explicit map whenever parameters cross a flat-array or optimizer boundary:
50
+
51
+ | Position | Name | BrainX destination | Role | Unit | Transform | Bounds | Reported value |
52
+ |---:|---|---|---|---|---|---|---|
53
+
54
+ Never rely on dictionary order or an unlabeled vector to preserve scientific meaning. Test encode -> decode -> encode round trips at nominal and boundary values.
55
+
56
+ ## Select the fitting backend
57
+
58
+ Choose the simplest backend supported by the simulator and objective.
59
+
60
+ | Condition | Use | Required checks |
61
+ |---|---|---|
62
+ | The complete simulator-to-objective path is differentiable and numerically stable | `brainmass.Fitter(..., backend="grad")` or `brainstate.transform.grad` with a Braintools gradient optimizer | Finite and nonzero gradients, a small finite-difference comparison, multiple starts, exact-pipeline recovery, and held-out prediction. |
63
+ | A required branch, observation, or objective is discontinuous, discrete, black-box, or has unreliable gradients | Bounded `brainmass.Fitter` gradient-free backend or the routed Braintools `NevergradOptimizer` or `ScipyOptimizer` | Finite bounds, correct candidate-batch semantics, full evaluation budget, multiple starts, landscape or sensitivity evidence, recovery, and held-out prediction. |
64
+
65
+ Prefer gradients when they are valid. Do not select derivative-free fitting merely because the BrainCell example uses Nevergrad; that example establishes a custom candidate-evaluation pattern, not a universal backend choice.
66
+
67
+ ## Apply the scale-specific pattern
68
+
69
+ | Route | Pattern to preserve |
70
+ |---|---|
71
+ | BrainCell | The HH fitting example constructs and initializes one cell rollout for each unit-bearing conductance and capacitance candidate, evaluates time-major current protocols, and batches derivative-free candidates. Preserve candidate independence and unit-bounded search; reconcile exact channel and State APIs with the current BrainCell skill. |
72
+ | BrainPy-State | The training examples initialize runtime State at each independent sequence, differentiate only the selected `ParamState` collection, transform the complete loss step, and update parameters outside the temporal loop. Reuse that lifecycle for an inverse objective; task loss itself is not parameter fitting. |
73
+ | BrainMass | The fitting examples prefer `Fitter`, mark fitted values with `brainstate.nn.Param(..., fit=True)`, and fit phase-appropriate observations such as settled amplitude rather than an unaligned oscillatory waveform. Use gradient fitting first and change backends only when the objective requires it. |
74
+ | Braintools | Gradient optimizers register trainable State and consume matching gradient trees. `ScipyOptimizer` and `NevergradOptimizer` instead own a complete objective and do not use the register/update lifecycle; Nevergrad requires one loss per candidate. |
75
+
76
+ ## Construct one candidate evaluation
77
+
78
+ One candidate evaluation must apply parameters, reset independent runtime State, execute the exact protocol, build the declared observation, and return one declared scalar loss.
79
+
80
+ | API | Description |
81
+ |---|---|
82
+ | `brainstate.nn.Param(..., fit=True)` | Use for a fitted model value that needs BrainState discovery, a valid-domain transform, or regularization. Read its constrained physical value in the model. |
83
+ | `brainstate.nn.init_all_states(model, ...)` | Use at an independent rollout boundary when the selected model route requires model-wide runtime State initialization. Do not reset fitted parameter State. |
84
+ | `brainstate.transform.grad(loss_fn, grad_states=..., return_value=True)` | Use for a custom stateful differentiable objective. Select only intended parameter State and transform the complete loss evaluation. |
85
+ | `brainmass.Fitter(...)` | Use when BrainMass owns the simulator and its loss, prediction, objective, and backend interfaces express the inverse problem. |
86
+ | `braintools.optim.NevergradOptimizer(...)` | Use for a custom black-box objective that accepts candidate-stacked parameters and returns one loss per candidate. Preserve unit-bearing bounds and independent runtime State. |
87
+ | `braintools.metric.*` | Use when the selected model package has no owning objective. Declare orientation and reduction because many metrics return arrays. |
88
+
89
+ Use the BrainMass path as the canonical high-level workflow:
90
+
91
+ ```python
92
+ import brainmass
93
+ import brainstate
94
+ import braintools
95
+ import brainunit as u
96
+
97
+
98
+ def settled_amplitude(model):
99
+ result = brainmass.Simulator(model, dt=0.1 * u.ms).run(
100
+ 300.0 * u.ms,
101
+ monitors=["x"],
102
+ transient=150.0 * u.ms,
103
+ )
104
+ x = u.get_magnitude(result["x"])
105
+ x = x - u.math.mean(x)
106
+ return u.math.sqrt(u.math.mean(x ** 2))
107
+
108
+
109
+ target = settled_amplitude(
110
+ brainmass.HopfStep(
111
+ in_size=1,
112
+ a=1.5,
113
+ w=0.3,
114
+ beta=1.0,
115
+ init_x=braintools.init.Constant(0.5),
116
+ init_y=braintools.init.Constant(0.0),
117
+ )
118
+ )
119
+ model = brainmass.HopfStep(
120
+ in_size=1,
121
+ a=brainstate.nn.Param(
122
+ 0.1,
123
+ t=brainstate.nn.SigmoidT(0.05, 3.0),
124
+ fit=True,
125
+ ),
126
+ w=0.3,
127
+ beta=1.0,
128
+ init_x=braintools.init.Constant(0.5),
129
+ init_y=braintools.init.Constant(0.0),
130
+ )
131
+
132
+
133
+ def loss_fn(candidate):
134
+ prediction = settled_amplitude(candidate)
135
+ return (prediction - target) ** 2, prediction
136
+
137
+
138
+ fit = brainmass.Fitter(
139
+ model,
140
+ braintools.optim.Adam(lr=0.05),
141
+ loss_fn=loss_fn,
142
+ backend="grad",
143
+ ).fit(n_steps=100)
144
+
145
+ assert fit.best_loss <= fit.history[0]
146
+ assert u.math.isfinite(fit.best_params["a"])
147
+ assert u.math.abs(fit.best_params["a"] - 1.5) < 0.1
148
+ ```
149
+
150
+ This proves only that one synthetic target is mechanically recoverable. It does not establish identifiability across the parameter domain or under the observed protocol.
151
+
152
+ ## Validate fitting mechanics
153
+
154
+ 1. Evaluate nominal, boundary, and invalid parameter values. Verify shapes, units, finite outputs, expected failures, and constraint behavior.
155
+ 2. Verify deterministic replay or characterize stochastic variation under declared seeds. Reset every State whose carryover is not part of the protocol.
156
+ 3. Inspect every objective component before reduction. Confirm its direction, unit behavior, weight, and contribution at nominal values.
157
+ 4. For oscillatory data, use scientifically justified phase-insensitive observations such as amplitude, spectrum, FC, or FCD when waveform phase is not aligned.
158
+ 5. For gradient fitting, compare autodiff with finite differences on a small stable case and inspect zero, exploding, `NaN`, or parameter-missing gradients.
159
+ 6. For derivative-free fitting, verify candidate-axis shape, one loss per candidate, unit reconstruction, bounds, invalid-candidate behavior, and total evaluation count.
160
+ 7. Inspect sensitivity, tradeoffs, flat directions, discontinuities, and numerical boundaries before running the full fit.
161
+
162
+ ## Run exact-pipeline parameter recovery
163
+
164
+ Recovery must use the same simulator, protocol, observation model, preprocessing, bounds, starts, seeds, objective, backend, budget, stopping rule, and candidate-selection rule as the observed-data fit.
165
+
166
+ | Step | Action | Required evidence |
167
+ |---|---|---|
168
+ | 1. Draw truth | Sample labeled physical parameter sets across the full plausible joint domain, including nuisance variation. | Generating table with names, units, provenance, and seeds. |
169
+ | 2. Generate observations | Run the BrainX model with the real duration, stimuli, sampling, noise, missingness, and State reset policy. | Latent and observed outputs plus simulation diagnostics. |
170
+ | 3. Fit blindly | Run the unchanged fitting pipeline without exposing truth to initialization, stopping, or selection. | Every start, trace, failure, boundary hit, and selected candidate. |
171
+ | 4. Compare | Join recovered and generating values by parameter name and unit. | Bias, MAE or RMSE, recovered-versus-true association, boundary rate, and fit-failure rate. |
172
+ | 5. Inspect tradeoffs | Examine paired errors, sensitivity, profile losses, or objective contours. | Ridges, compensating parameters, flat regions, and failure regions. |
173
+ | 6. Gate interpretation | Apply criteria locked before observed fitting to each parameter separately. | `interpretable`, `weakly-identified`, or `non-identifiable-under-this-protocol`. |
174
+
175
+ Do not copy universal sample counts or correlation thresholds from another model. Choose enough generating datasets to resolve the error, tradeoff, and failure behavior required by the scientific claim, then justify and lock that count.
176
+
177
+ High recovered-versus-true correlation can coexist with large bias. Low aggregate loss can coexist with parameter tradeoffs. Report multiple diagnostics and preserve failed fits rather than dropping them.
178
+
179
+ Poor parameter recovery may still permit a predictive result. In that case, report prediction under the tested protocol and explicitly withhold parameter-level interpretation.
180
+
181
+ ## Fit observed data and check predictions
182
+
183
+ Fit observed data only after recovery passes the locked parameter-specific criteria or the researcher approves a narrower predictive claim.
184
+
185
+ - Preserve every start, seed, trace, failed evaluation, boundary hit, and candidate-selection decision.
186
+ - Select candidates with the locked rule; do not report only the most favorable start or seed.
187
+ - Evaluate held-out data or protocols through the same observation and reset path used during fitting.
188
+ - Report raw predictions, residuals, parameter uncertainty or start-to-start variability, and protocol-wise metrics.
189
+ - Treat good prediction as evidence about prediction under the tested protocol, not parameter identifiability or biological validity.
190
+
191
+ ## Return fitting evidence
192
+
193
+ | Artifact | Required contents |
194
+ |---|---|
195
+ | Fitting contract | Parameter map, data partitions, protocol, observation model, objective, estimator, budgets, seeds, and locked criteria. |
196
+ | Mechanics checks | Parameter round trips, State reset, unit and shape tests, nominal and boundary runs, gradient or candidate-batch checks. |
197
+ | Recovery evidence | Generating parameters, every recovered estimate, bias and error summaries, tradeoffs, boundary and failure rates, and parameter classifications. |
198
+ | Observed fit | Every run, trace, failure, selected result, constrained physical parameters, and reproducibility metadata. |
199
+ | Predictive evidence | Held-out simulations, raw observations, residuals, variability or uncertainty, and protocol-wise metrics. |
200
+ | Claim boundary | Supported parameter interpretations, prediction-only results, non-identifiable targets, model limitations, and unresolved alternatives. |
201
+
202
+ ## Package routing
203
+
204
+ | Route | Open when |
205
+ |---|---|
206
+ | `parameter-fitting-workflow/scripts/fitting_hh_neuron.py` | Studying the official complete BrainCell HH derivative-free fitting composition: custom channels, unit-bearing bounds, per-candidate cell initialization, time-major rollout, voltage loss, candidate `vmap`, and Nevergrad. Supply the upstream `input_traces_hh.csv` and `output_traces_hh.csv` files, and reconcile its source-version BrainCell and BrainState APIs with the current package skills before adapting it. |
207
+ | `brainmass` -> `references/fitting-with-objectives-api.md` | Selecting `Fitter` interfaces, objectives, callbacks, `FitResult` fields, or gradient versus gradient-free backends. |
208
+ | `brainmass` -> `references/scripts/eeg-fitting-with-gradients.py` | Studying a complete phase-insensitive EEG fitting and synthetic-recovery example. |
209
+ | `brainmass` -> `references/scripts/gradient-free-fitting.py` | A bounded non-differentiable or black-box BrainMass objective requires Nevergrad or SciPy. |
210
+ | `brainstate` -> gradient and parameter references | Differentiating custom BrainCell or BrainPy-State rollouts, selecting parameter State, or applying constraints and regularization. |
211
+ | Active model package -> Braintools optimizer reference | Selecting gradient optimizers, schedules, SciPy, Nevergrad, or their distinct lifecycle and unit contracts. |
212
+ | Active model package -> Braintools metric reference | Selecting regression, spike-train, spectral, synchronization, FC, or other observation-space metrics. |
213
+
214
+ ## Boundaries and common failures
215
+
216
+ - Fitting latent State directly to measured data without the declared observation model.
217
+ - Flattening unit-bearing parameters without a tested name, order, unit, and transform map.
218
+ - Resetting fitted parameters between candidates or carrying runtime State across independent candidates.
219
+ - Treating a surrogate gradient as evidence that a fitted spiking parameter is identifiable.
220
+ - Fitting raw oscillatory waveforms when phase is not experimentally aligned.
221
+ - Selecting derivative-free fitting before checking whether gradients are valid.
222
+ - Changing bounds, summaries, exclusions, weights, or recovery criteria after inspecting observed-data results.
223
+ - Running recovery with longer, cleaner, denser, or easier data than the real protocol.
224
+ - Interpreting aggregate fit quality as parameter recovery.
225
+ - Hiding failed starts, invalid simulations, or boundary solutions.
226
+
227
+ ## BrainX source patterns
228
+
229
+ - BrainCell HH fitting: `parameter-fitting-workflow/scripts/fitting_hh_neuron.py`, mirrored from `https://github.com/chaobrain/braincell/blob/main/examples/single_compartment/SC01_fitting_a_hh_neuron.py`
230
+ - BrainPy-State SNN training lifecycle: `https://brainx.chaobrain.com/brainpy-state/brainpy-style/tutorials/04-train-an-snn.html`
231
+ - BrainMass gradient fitting: `https://brainx.chaobrain.com/brainmass/tutorials/06_fitting_with_gradients.html`
232
+ - BrainMass gradient-free fitting: `https://brainx.chaobrain.com/brainmass/tutorials/07_gradient_free_fitting.html`