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.
- package/README.md +4 -0
- package/installation/lib/bundle.js +51 -13
- package/manifest.json +2 -0
- package/mcp-servers/codex/README.md +62 -0
- package/mcp-servers/codex/UPSTREAM.md +20 -0
- package/mcp-servers/codex/server.mjs +140 -0
- package/mcp-servers/codex/skills.json +10 -0
- package/mcp-servers/codex/system-prompt.md +62 -0
- package/mcp-servers/codex/test/fixtures/fake-codex.mjs +6 -0
- package/mcp-servers/codex/test/server.test.mjs +88 -0
- package/package.json +6 -9
- package/skills/brainx-acceleration/SKILL.md +459 -0
- package/skills/brainx-general-guard/SKILL.md +14 -9
- package/skills/brainx-modeling-loop/SKILL.md +268 -0
- package/skills/brainx-modeling-loop/agents/openai.yaml +4 -0
- package/skills/brainx-modeling-loop/references/monitor-experiment.md +49 -0
- package/skills/brainx-modeling-loop/references/parameter-fitting-workflow/scripts/fitting_hh_neuron.py +254 -0
- package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +232 -0
- package/skills/brainx-modeling-loop/references/run-experiment.md +179 -0
- package/skills/brainx-modeling-loop/references/training-workflow.md +270 -0
- package/skills/{braincell → package-skills/braincell}/SKILL.md +2 -1
- package/skills/{braincell → package-skills/braincell}/references/multicompartment/multicompartment-cell-workflow.md +2 -2
- package/skills/package-skills/braincell/references/scripts/fitting_hh_neuron.py +254 -0
- package/skills/{brainmass → package-skills/brainmass}/references/brainstate/parameter-constraints-regularization.md +1 -1
- package/skills/{brainmass → package-skills/brainmass}/references/coupling-network-api.md +121 -3
- package/skills/{brainmass → package-skills/brainmass}/references/modellibrary.md +79 -1
- package/skills/package-skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +188 -0
- package/skills/{brainmass → package-skills/brainmass}/references/visualization-analysis-api.md +6 -6
- package/skills/{brainpy-state → package-skills/brainpy-state}/SKILL.md +4 -3
- package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/connectivity.md +1 -1
- package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/input-current.md +1 -1
- package/skills/package-skills/brainpy-state/references/perturbation-experiment-validity.md +76 -0
- package/skills/{brainpy-state → package-skills/brainpy-state}/references/projection-patterns.md +1 -1
- package/skills/{brainstate → package-skills/brainstate}/SKILL.md +1 -0
- package/skills/{brainstate → package-skills/brainstate}/references/brainstate/brainstate-transformed-diagnostics.md +1 -1
- package/skills/{brainstate → package-skills/brainstate}/references/brainstate/parameter-constraints-regularization.md +1 -1
- package/skills/{brainstate → package-skills/brainstate}/references/brainstate/randomness-and-reproducibility.md +1 -1
- package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-grad-expansion.md +2 -2
- package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-vmap-expansion.md +1 -1
- package/skills/{brainstate → package-skills/brainstate}/references/libraries/prebuilt-layer-library.md +1 -1
- package/skills/package-skills/brainstate/references/paired-perturbation-execution.md +113 -0
- package/skills/package-skills/braintrace/SKILL.md +187 -0
- package/skills/package-skills/braintrace/references/Drtrl.md +133 -0
- package/skills/{braintrace → package-skills/braintrace}/references/ETP operators.md +31 -4
- package/skills/package-skills/braintrace/references/algorithm selection.md +64 -0
- package/skills/package-skills/braintrace/references/batching.md +140 -0
- package/skills/{braintrace → package-skills/braintrace}/references/compiler_internal.md +2 -2
- package/skills/{braintrace → package-skills/braintrace}/references/custom algorithms.md +8 -10
- package/skills/package-skills/braintrace/references/pp_pprop workflow.md +179 -0
- package/skills/{braintrace → package-skills/braintrace}/references/pre-built-braintrace-layer.md +2 -2
- package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +0 -130
- package/skills/braintrace/SKILL.md +0 -161
- package/skills/braintrace/references/Drtrl.md +0 -179
- package/skills/braintrace/references/algorithm selection.md +0 -120
- package/skills/braintrace/references/batching.md +0 -150
- package/skills/braintrace/references/pp_pprop workflow.md +0 -196
- /package/skills/{braincell → package-skills/braincell}/references/area-scaled-hh-pattern.md +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/braincell-custom-ion-channel-authoring.md +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/channel-library.md +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/ion-library.md +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/mixions-for-adaptation.md +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/multicompartment/braincell-manual-morphology-construction.md +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/multicompartment/cv-policy-reference.md +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/multicompartment/filter-function-library.md +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/multicompartment/morphology-io-loading-validation.md +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/multicompartment/probe-reference.md +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/multicompartment/topology-building-and-visualization.md +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/scripts/calcium_channel_gating.py +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/scripts/cell_multicompartment_reference.py +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/scripts/channel_ablation.py +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/scripts/fi_curve.py +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/scripts/hh_neuron_basics.py +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/scripts/spike_frequency_adaptation.py +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/scripts/t_current_rebound.py +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/scripts/thalamic_neurons.py +0 -0
- /package/skills/{braincell → package-skills/braincell}/references/solver-library-with-effects.md +0 -0
- /package/skills/{brainevent → package-skills/brainevent}/SKILL.md +0 -0
- /package/skills/{brainevent → package-skills/brainevent}/references/connectivity-variants.md +0 -0
- /package/skills/{brainevent → package-skills/brainevent}/references/custom-operators-cpu.md +0 -0
- /package/skills/{brainevent → package-skills/brainevent}/references/custom-operators-gpu.md +0 -0
- /package/skills/{brainevent → package-skills/brainevent}/references/scripts/102_EI_net_1996.py +0 -0
- /package/skills/{brainevent → package-skills/brainevent}/references/scripts/204_joglekar_2018_propagation.py +0 -0
- /package/skills/{brainevent → package-skills/brainevent}/references/scripts/coba_ei_teaching.py +0 -0
- /package/skills/{brainevent → package-skills/brainevent}/references/sparse-formats.md +0 -0
- /package/skills/{brainevent → package-skills/brainevent}/references/synaptic-plasticity.md +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/SKILL.md +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/batch-transform-acceleration.md +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/brainstate/parameter-transforms-regularizers-catalog.md +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/braintools/cogtask.md +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/braintools/data-preprocessing.md +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/braintools/metric.md +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/braintools/optimizer.md +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/braintools/parameter-initializer.md +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/braintools/surrogate.md +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/datasets-api.md +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/fitting-with-objectives-api.md +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/forward-observation-api.md +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/horn-task-training.md +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/noiseprocesses.md +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/scripts/eeg-fitting-with-gradients.py +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/scripts/gradient-free-fitting.py +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/scripts/hopf-bifurcation-single-node.py +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/scripts/horn-cognitive-task-training.py +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/scripts/jansen-rit-eeg-proxy.py +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/scripts/kuramoto-synchronization.py +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/scripts/linear-baseline-node.py +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/scripts/resting-state-meg-whole-brain-pipeline.py +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/scripts/seizure-epileptor-case-study.py +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wilson-cowan-ei-dynamics.py +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wong-wang-decision-making.py +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/scripts/wong-wang-dmf-resting-state.py +0 -0
- /package/skills/{brainmass → package-skills/brainmass}/references/simulator-input-monitor-api.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/array-creation.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brain-dynamics-delay-protocol.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/analysis.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/brainpy legacy workflow.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/built-in dynamic neuron model.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/connecting neurons.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/customize neuron and synpase.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Input generation.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/More about simulation.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/delays.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/integrators.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/route activity through connectivity.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/synaptic projections.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/synpase properties.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/loss library.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/optimizers.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/parameter initializers.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/prebuilt neural network layers.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/surrogate gradients.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/trainer library.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/brainPy(legacy)/training/trainingworkflows.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/brainstate-control-flow-patterns.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/data-preprocessing.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/metric.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/optimizer.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/parameter-initializer.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/braintools/surrogate.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/component-selection.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/devices.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/divergence-and-parity.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/integration-categories.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/model-library.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/nest-workflow.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/network-building.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brette_et_al_2007.py +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brunel_alpha.py +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/brunel_delta.py +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/spatial_gaussex.py +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/scripts/synapsecollection.py +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/nest-compatible/synapse-and-connectivity.md +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/103_COBA_2005.py +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/106_COBA_HH_2007.py +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/107_gamma_oscillation_1996.py +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/109_fast_global_oscillation.py +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/sound_localization.py +0 -0
- /package/skills/{brainpy-state → package-skills/brainpy-state}/references/scripts/training-snn.py +0 -0
- /package/skills/{brainstate → package-skills/brainstate}/agents/openai.yaml +0 -0
- /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/brainstate-control-flow-patterns.md +0 -0
- /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/parameter-transforms-regularizers-catalog.md +0 -0
- /package/skills/{brainstate → package-skills/brainstate}/references/brainstate/transformation-jit-expansion.md +0 -0
- /package/skills/{brainstate → package-skills/brainstate}/references/collective_model_operations.md +0 -0
- /package/skills/{brainstate → package-skills/brainstate}/references/extension_mechanisms.md +0 -0
- /package/skills/{brainstate → package-skills/brainstate}/references/libraries/prebuilt-activation-library.md +0 -0
- /package/skills/{brainstate → package-skills/brainstate}/references/model-interop-and-migration.md +0 -0
- /package/skills/{brainstate → package-skills/brainstate}/references/simulation-environment.md +0 -0
- /package/skills/{brainstate → package-skills/brainstate}/references/size-inference-variations.md +0 -0
- /package/skills/{brainstate → package-skills/brainstate}/references/state-graph-operations.md +0 -0
- /package/skills/{brainstate → package-skills/brainstate}/references/state_collections_and_utilities.md +0 -0
- /package/skills/{brainstate → package-skills/brainstate}/scripts/integrator_rnn.py +0 -0
- /package/skills/{brainstate → package-skills/brainstate}/scripts/lif_neuron_model.py +0 -0
- /package/skills/{brainstate → package-skills/brainstate}/scripts/modern_cnn.py +0 -0
- /package/skills/{brainstate → package-skills/brainstate}/scripts/resnet.py +0 -0
- /package/skills/{braintrace → package-skills/braintrace}/references/custom ETP primitives.md +0 -0
- /package/skills/{braintrace → package-skills/braintrace}/references/customizing_primitive_transforms.md +0 -0
- /package/skills/{brainunit → package-skills/brainunit}/SKILL.md +0 -0
- /package/skills/{brainunit → package-skills/brainunit}/references/array-creation.md +0 -0
- /package/skills/{brainunit → package-skills/brainunit}/references/array-mechanics/functional-structural-api.md +0 -0
- /package/skills/{brainunit → package-skills/brainunit}/references/array-mechanics.md +0 -0
- /package/skills/{brainunit → package-skills/brainunit}/references/math-function-library.md +0 -0
- /package/skills/{brainunit → package-skills/brainunit}/references/physical-constant-library.md +0 -0
- /package/skills/{brainunit → package-skills/brainunit}/references/prefix-library.md +0 -0
- /package/skills/{brainunit → package-skills/brainunit}/references/quantity-inspection-and-conversion.md +0 -0
- /package/skills/{brainunit → package-skills/brainunit}/references/typing-and-runtime-validation.md +0 -0
- /package/skills/{brainunit → package-skills/brainunit}/references/unit-structure-and-definition.md +0 -0
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: brainx-modeling-loop
|
|
3
|
+
description: Use first for an end-to-end BrainX modeling project. Start fresh or resume from brainmodeling-memory.md, write a compact NeuroSpecification.md, study the relevant BrainX skills deeply, implement and accelerate the model, run experiments, send code and results to Codex through MCP, repeat from implementation when review refuses, and visualize only after review passes.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# BrainX modeling loop
|
|
7
|
+
|
|
8
|
+
## Get started
|
|
9
|
+
|
|
10
|
+
Read `brainmodeling-memory.md` first when it exists, then choose exactly one entry case.
|
|
11
|
+
|
|
12
|
+
| Entry case | Use when | Action |
|
|
13
|
+
|---|---|---|
|
|
14
|
+
| `fresh-new` | `brainmodeling-memory.md` does not exist and no prior loop work must be preserved. | Create the memory file, set the current position to step 0, and start the specification. |
|
|
15
|
+
| `resume` | `brainmodeling-memory.md` or prior loop artifacts exist. | Read the recorded step, verify its referenced artifacts, and continue from the first unfinished action in that step. |
|
|
16
|
+
|
|
17
|
+
Do not create another entry case. Recover missing or inconsistent state inside `resume` by using existing artifacts to locate the earliest unfinished step. Do not repeat a completed experiment or Codex review merely because terminal context was lost.
|
|
18
|
+
|
|
19
|
+
Use this complete append-only memory contract:
|
|
20
|
+
|
|
21
|
+
```markdown
|
|
22
|
+
# Brain modeling memory
|
|
23
|
+
|
|
24
|
+
## Checkpoint
|
|
25
|
+
- Iteration: <integer>
|
|
26
|
+
- Step: 0 | 1 | 2 | 3 | 4 | 5 | 6
|
|
27
|
+
|
|
28
|
+
### Artifacts
|
|
29
|
+
- `<path or stable identifier>`: <contents and status>
|
|
30
|
+
|
|
31
|
+
### Important milestones
|
|
32
|
+
- <decision, review outcome, blocker, or completed result with its evidence pointer>
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
For `fresh-new`, create the file with its title, start iteration 1 at step 0, and
|
|
36
|
+
append the first checkpoint after step 0 finishes or blocks. After every step,
|
|
37
|
+
including a blocked step, append a new `## Checkpoint` block. `Iteration` and `Step` are metadata identifying
|
|
38
|
+
the step whose artifacts and milestones the block records; `Artifacts` and
|
|
39
|
+
`Important milestones` are the checkpoint content.
|
|
40
|
+
|
|
41
|
+
Never overwrite an earlier checkpoint. Append corrections as a new checkpoint
|
|
42
|
+
with the same iteration and step and state which earlier record it supersedes.
|
|
43
|
+
For `resume`, read the checkpoints in order, verify the latest artifact pointers,
|
|
44
|
+
and continue from the first unfinished action after the latest valid checkpoint.
|
|
45
|
+
|
|
46
|
+
```text
|
|
47
|
+
fresh-new -> step 0 -> step 1 -> step 2 -> step 3 -> step 4 -> step 5
|
|
48
|
+
^ |
|
|
49
|
+
|-------- REFUSE ----------|
|
|
50
|
+
|
|
51
|
+
step 5 PASS -> step 6 -> complete
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Each checkpoint contains the artifacts created or updated by that step and the
|
|
55
|
+
important milestones reached during it. Keep full code, logs, results, and
|
|
56
|
+
reviews in their owning artifacts and point to them from the checkpoint.
|
|
57
|
+
|
|
58
|
+
## Step 0: Write the specification
|
|
59
|
+
|
|
60
|
+
Turn the researcher's request and inspected data into a short `NeuroSpecification.md`. Ask the researcher only for missing decisions that would change the model, data interpretation, or acceptance boundary. Do not infer them.
|
|
61
|
+
|
|
62
|
+
Use only this core structure:
|
|
63
|
+
|
|
64
|
+
```markdown
|
|
65
|
+
# NeuroSpecification
|
|
66
|
+
|
|
67
|
+
- Status: draft | locked
|
|
68
|
+
- Researcher approval:
|
|
69
|
+
|
|
70
|
+
## Researcher request
|
|
71
|
+
- Brain-modeling question or behavior:
|
|
72
|
+
- Requested model, experiment, or comparison:
|
|
73
|
+
- Execution mode: forward-simulation | task-training | parameter-fitting | hybrid
|
|
74
|
+
- Required outputs:
|
|
75
|
+
- Constraints:
|
|
76
|
+
|
|
77
|
+
## Inspected data contract
|
|
78
|
+
- Data sources and inspected contents:
|
|
79
|
+
- Shapes, axes, sampling/time base, and physical units:
|
|
80
|
+
- Required preprocessing and the subset used to fit each transform:
|
|
81
|
+
- Mapping from data to model inputs, targets, and observables:
|
|
82
|
+
- Known data limitations or unresolved mismatches:
|
|
83
|
+
|
|
84
|
+
## Acceptance boundary
|
|
85
|
+
- Evidence required for success, failure, or an inconclusive result:
|
|
86
|
+
- Required baselines and controls:
|
|
87
|
+
- Invalid-result conditions:
|
|
88
|
+
- Allowed claims and explicit non-claims:
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Inspect supplied data before completing its contract. Keep raw data read-only, preserve units and axis meaning, and prevent preprocessing leakage. Lock the specification with researcher approval before step 1.
|
|
92
|
+
|
|
93
|
+
**Step result:** a locked `NeuroSpecification.md` and a memory checkpoint pointing to step 1.
|
|
94
|
+
|
|
95
|
+
## Step 1: Study the relevant BrainX modeling skills
|
|
96
|
+
|
|
97
|
+
Study before implementing. Understand the selected BrainX abstractions, exact APIs, execution lifecycle, invariants, and canonical scripts deeply enough to design the model without guessing.
|
|
98
|
+
|
|
99
|
+
1. Open `brainx-general-guard` and identify every biological scale explicitly represented by `NeuroSpecification.md`.
|
|
100
|
+
2. Read each selected modeling skill completely:
|
|
101
|
+
- `braincell` for ions, channels, compartments, or morphology;
|
|
102
|
+
- `brainpy-state` for point neurons, synapses, or spiking networks;
|
|
103
|
+
- `brainmass` for aggregate populations, regions, or whole-brain dynamics.
|
|
104
|
+
3. Open supporting package skills only when the model requires them:
|
|
105
|
+
- `brainunit` for physical quantities and unit-aware boundaries;
|
|
106
|
+
- `brainstate` for State, Modules, environments, initialization, randomness, and transforms;
|
|
107
|
+
- `brainevent` for event data, connectivity, and event-driven plasticity;
|
|
108
|
+
- `braintrace` only for temporal training limited by BPTT memory.
|
|
109
|
+
4. Follow every selected skill's routing instructions. Read all references and canonical scripts likely to affect this model.
|
|
110
|
+
5. Trace construction, initialization, State and data flow, update order, execution, outputs, and validation through the relevant examples.
|
|
111
|
+
6. Verify unfamiliar API names and signatures in the owning skill or its routed documentation. Do not inspect installed package source for modeling knowledge.
|
|
112
|
+
7. Save the study record as an artifact and record its completion and selected training/fitting coverage as important milestones.
|
|
113
|
+
|
|
114
|
+
Do not write the implementation during step 1. Finish the study record first.
|
|
115
|
+
|
|
116
|
+
**Step result:** a complete BrainX study record and an implementation design grounded in the selected skills, then a memory checkpoint pointing to step 2.
|
|
117
|
+
|
|
118
|
+
## Optional training and fitting coverage for steps 2-5
|
|
119
|
+
|
|
120
|
+
Training and fitting extend the same loop; they do not create separate stages or entry cases.
|
|
121
|
+
|
|
122
|
+
| Specification mode | Coverage for steps 2-5 |
|
|
123
|
+
|---|---|
|
|
124
|
+
| `forward-simulation` | Open neither optional reference. |
|
|
125
|
+
| `task-training` | Open `references/training-workflow.md` at the start of step 2 and keep its requirements active through implementation, acceleration, experiment execution, and Codex review. |
|
|
126
|
+
| `parameter-fitting` | Open `references/parameter-fitting-workflow.md` at the start of step 2 and keep its requirements active through implementation, acceleration, experiment execution, and Codex review. |
|
|
127
|
+
| `hybrid` | Open `references/training-workflow.md` and `references/parameter-fitting-workflow.md` at step 2, then keep their objectives, State lifecycles, validation evidence, and review coverage distinct through step 5. |
|
|
128
|
+
|
|
129
|
+
Record the active coverage as an important milestone. A step is incomplete until its modeling requirements and every active training/fitting requirement are satisfied.
|
|
130
|
+
|
|
131
|
+
## Step 2: Implement the model and experiment code
|
|
132
|
+
|
|
133
|
+
Implement from the step-1 study record and the locked specification. Open the selected training or parameter-fitting reference before coding and apply it throughout this step.
|
|
134
|
+
|
|
135
|
+
1. Build the model through the selected BrainX package abstractions and highest-level owning APIs.
|
|
136
|
+
2. Implement required data processing, initialization, inputs, interventions, controls, observation mapping, training or fitting workflow, metrics, and artifact outputs.
|
|
137
|
+
3. Preserve BrainUnit quantities, BrainState lifecycle, package update order, randomness, and represented biological scale.
|
|
138
|
+
4. Add focused checks for equations or components, shapes, units, State initialization/reset, update order, inputs, controls, observables, and metrics.
|
|
139
|
+
5. Run only small implementation checks needed to prove the code is ready for acceleration and the experiment runner. Leave production execution to step 4.
|
|
140
|
+
6. Record the code and test artifacts plus any important implementation milestone.
|
|
141
|
+
|
|
142
|
+
When step 5 returns `REFUSE`, begin a new iteration here. Read every reviewer finding, preserve the locked specification, make the smallest sufficient implementation or experiment-design correction, update memory, and then repeat steps 3, 4, and 5.
|
|
143
|
+
|
|
144
|
+
**Step result:** BrainX-native model and experiment code with focused checks, then a memory checkpoint pointing to step 3.
|
|
145
|
+
|
|
146
|
+
## Step 3: Accelerate the code
|
|
147
|
+
|
|
148
|
+
Open `brainx-acceleration` and study the parts relevant to the implemented workload. Apply its workflow while keeping any active training/fitting coverage in force.
|
|
149
|
+
|
|
150
|
+
1. Establish the representative baseline and relevant outputs before changing performance code.
|
|
151
|
+
2. Apply only acceleration changes supported by the acceleration skill.
|
|
152
|
+
3. Compare model outputs, State, units, randomness, and numerical tolerances against the baseline.
|
|
153
|
+
4. When training is active, also preserve losses, gradients, parameter updates, reset behavior, and checkpoint meaning. When fitting is active, preserve objectives, parameter order/units, recovery behavior, and inference outputs.
|
|
154
|
+
5. Reject an optimization that changes the scientific result.
|
|
155
|
+
6. Record the acceleration and parity artifacts plus the important outcome milestone.
|
|
156
|
+
|
|
157
|
+
**Step result:** accelerated code with parity evidence, or an explicit unchanged decision, then a memory checkpoint pointing to step 4.
|
|
158
|
+
|
|
159
|
+
## Step 4: Run the experiment
|
|
160
|
+
|
|
161
|
+
Hand the locked specification, implementation, acceleration evidence, run configuration, seeds, expected outputs, artifact locations, and active training/fitting requirements to `references/run-experiment.md`. Follow it through target-device smoke and immutable production or replication launch, then open `references/monitor-experiment.md` for monitoring and artifact collection.
|
|
162
|
+
|
|
163
|
+
Step 4 must eventually return inspectable run artifacts: the exact configuration, code/data/environment identity, logs, raw results, metrics, training/fitting evidence when active, and artifact paths. Process completion does not imply review acceptance.
|
|
164
|
+
|
|
165
|
+
**Step result:** completed experiment artifacts and a memory checkpoint pointing to step 5.
|
|
166
|
+
|
|
167
|
+
## Step 5: Ask Codex to review code and results
|
|
168
|
+
|
|
169
|
+
Use the configured BrainX Codex MCP server. Its
|
|
170
|
+
`mcp-servers/codex/system-prompt.md` is the authoritative review contract and is
|
|
171
|
+
injected as `base-instructions` into every fresh `mcp__codex__codex` call. Do not
|
|
172
|
+
duplicate that contract in this skill or paste it into the review request.
|
|
173
|
+
|
|
174
|
+
Start one fresh `mcp__codex__codex` call for each completed iteration. Send the
|
|
175
|
+
locked specification, step-1 study record, implementation and tests, acceleration
|
|
176
|
+
evidence, experiment configuration, raw run artifacts, metrics, deterministic
|
|
177
|
+
result assessment, claim-evidence matrix, proposed next action, and all evidence
|
|
178
|
+
required by active training/fitting coverage. Preserve the returned raw response
|
|
179
|
+
and `threadId` as review artifacts. Treat the returned `content` as the reviewer
|
|
180
|
+
response in the calling agent's current turn: classify it immediately, update
|
|
181
|
+
the loop checkpoint, and report or act on the verdict without asking the
|
|
182
|
+
researcher to open another context. Preserve `threadId` for reviewer follow-up;
|
|
183
|
+
it is not needed for the calling agent to read the initial response.
|
|
184
|
+
|
|
185
|
+
Before calling, verify that every listed path exists. Set the MCP call's working
|
|
186
|
+
directory to the project root when the tool exposes a working-directory argument,
|
|
187
|
+
then call `mcp__codex__codex` with a `prompt` in this form:
|
|
188
|
+
|
|
189
|
+
```text
|
|
190
|
+
Review completed BrainX iteration <N>.
|
|
191
|
+
|
|
192
|
+
PROJECT_ROOT: <absolute project-root path>
|
|
193
|
+
ACTIVE_COVERAGE: none | training | fitting | training+fitting
|
|
194
|
+
|
|
195
|
+
SPECIFICATION:
|
|
196
|
+
- <path>/NeuroSpecification.md
|
|
197
|
+
|
|
198
|
+
LOOP_MEMORY:
|
|
199
|
+
- <path>/brainmodeling-memory.md
|
|
200
|
+
|
|
201
|
+
BRAINX_STUDY_RECORD:
|
|
202
|
+
- <path to the step-1 study artifact>
|
|
203
|
+
|
|
204
|
+
IMPLEMENTATION:
|
|
205
|
+
- <path to each model, data-processing, and experiment source file>
|
|
206
|
+
|
|
207
|
+
TESTS:
|
|
208
|
+
- <path to each relevant test and its result artifact>
|
|
209
|
+
|
|
210
|
+
ACCELERATION_AND_PARITY:
|
|
211
|
+
- <path to baseline, parity, runtime, and memory evidence>
|
|
212
|
+
|
|
213
|
+
EXPERIMENT_RUN:
|
|
214
|
+
- <path to exact run configuration>
|
|
215
|
+
- <path to code, data, and environment provenance>
|
|
216
|
+
- <path to logs>
|
|
217
|
+
- <path to raw results>
|
|
218
|
+
- <path to metrics>
|
|
219
|
+
- <path to artifact manifest>
|
|
220
|
+
|
|
221
|
+
RESULT_ASSESSMENT:
|
|
222
|
+
- <path to deterministic assessment and claim-evidence matrix>
|
|
223
|
+
|
|
224
|
+
TRAINING_OR_FITTING_EVIDENCE:
|
|
225
|
+
- <path to every active coverage artifact, or none>
|
|
226
|
+
|
|
227
|
+
PRIOR_REVIEW_EVIDENCE:
|
|
228
|
+
- <path to prior raw reviews and addressed findings, or none>
|
|
229
|
+
|
|
230
|
+
Read every listed artifact and review this iteration using the injected reviewer
|
|
231
|
+
contract. Do not edit files. Return the required structured outcome.
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
List concrete files, not only directories. Keep large data in place and provide
|
|
235
|
+
its manifest, provenance, and the exact result files needed for verification.
|
|
236
|
+
Do not omit an unfavorable, failed, or excluded run when it affects the proposed
|
|
237
|
+
scientific outcome.
|
|
238
|
+
|
|
239
|
+
Do not start an iteration review with `mcp__codex__codex-reply`; only a fresh
|
|
240
|
+
`codex` call receives the injected system prompt. If the configured MCP server is
|
|
241
|
+
unavailable, record step 5 as blocked in `brainmodeling-memory.md` and preserve
|
|
242
|
+
all completed experiment artifacts.
|
|
243
|
+
|
|
244
|
+
Configure the Codex MCP registration with `tool_timeout_sec = 1800`, or another
|
|
245
|
+
explicit budget longer than the largest expected review. A host timeout may be
|
|
246
|
+
reported as `user cancelled MCP tool call`; when no `threadId` or response is
|
|
247
|
+
returned, diagnose the MCP budget before treating it as researcher cancellation.
|
|
248
|
+
|
|
249
|
+
Record the full Codex response and one of two outcomes:
|
|
250
|
+
|
|
251
|
+
| Outcome | Transition |
|
|
252
|
+
|---|---|
|
|
253
|
+
| `REFUSE` | Record every finding and required correction, increment the iteration, set the current step to 2, and repeat steps 2-5 with the same optional coverage. |
|
|
254
|
+
| `PASS` | Record the accepted code/result scope and set the current step to 6. |
|
|
255
|
+
|
|
256
|
+
Do not argue with a refusal inside step 5 and do not substitute self-review for the MCP Codex call. The next Codex call occurs only after the revised implementation has passed again through acceleration and experiment execution.
|
|
257
|
+
|
|
258
|
+
**Step result:** a preserved Codex response and either a return to step 2 or a memory checkpoint pointing to step 6.
|
|
259
|
+
|
|
260
|
+
## Step 6: Visualize the accepted result
|
|
261
|
+
|
|
262
|
+
Hand the review-passed specification, code, run artifacts, results, and accepted scope to the BrainX visualization workflow.
|
|
263
|
+
|
|
264
|
+
The planned route is `references/visualization-workflow.md`. That instruction will be authored later; do not embed or invent it here. Until it exists, preserve the accepted artifacts and record step 6 as blocked in `brainmodeling-memory.md`.
|
|
265
|
+
|
|
266
|
+
After visualization completes, record the figure paths as artifacts and loop completion as an important milestone, then report the accepted result and remaining limitations.
|
|
267
|
+
|
|
268
|
+
**Step result:** visualization linked to review-passed evidence and a completed memory checkpoint.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# Monitor BrainX experiments
|
|
2
|
+
|
|
3
|
+
Use this reference after `run-experiment.md` launches a BrainX run. Monitor process and artifact health, stop only under declared rules, retry only transient failures, collect inspectable outputs, and return mechanical status to `brainx-modeling-loop`; do not tune the experiment or decide scientific acceptance.
|
|
4
|
+
|
|
5
|
+
## Inspect the recorded run
|
|
6
|
+
|
|
7
|
+
Start from `RUN_SPEC.md`, `status.json`, and the recorded process, session, scheduler, or provider handle. Verify that the handle still identifies the recorded command, working directory, and start time; never select a run by broad process-name matching.
|
|
8
|
+
|
|
9
|
+
| Signal | Check | Meaning |
|
|
10
|
+
|---|---|---|
|
|
11
|
+
| Liveness | Process/job/session/provider status | Whether execution is active; absence requires exit and artifact inspection. |
|
|
12
|
+
| Progress | New append-only logs or declared heartbeat | Whether the run advances at its expected cadence. |
|
|
13
|
+
| CPU/GPU resources | Memory, disk, utilization, device errors, and recorded PID/device | Resource health and target placement, not scientific quality. |
|
|
14
|
+
| Checkpoint | Existence, freshness, size, completion marker, and parseability | Recovery freshness; partial writes are invalid. |
|
|
15
|
+
| Output | Required files, sizes, parseability, and declared finite-value checks | Mechanical completeness or deterministic invalidity. |
|
|
16
|
+
| Existing telemetry | Run state and predeclared metrics | Secondary evidence; immutable local artifacts remain authoritative. |
|
|
17
|
+
|
|
18
|
+
Poll at a cadence proportional to the declared heartbeat/checkpoint interval. External scheduling may wake on machine-checkable conditions such as exit code, job state, file existence, or logged step; never schedule a scientific verdict.
|
|
19
|
+
|
|
20
|
+
## Classify before acting
|
|
21
|
+
|
|
22
|
+
| Status | Evidence | Action |
|
|
23
|
+
|---|---|---|
|
|
24
|
+
| `running-healthy` | Live handle, advancing progress, resources within bounds | Wait and report the latest raw progress. |
|
|
25
|
+
| `running-uncertain` | Live handle but no new signal within one expected interval | Inspect logs/resources; wait unless a declared limit is crossed. |
|
|
26
|
+
| `done` | Exit code zero and every required artifact exists and parses | Record completion and collect artifacts. |
|
|
27
|
+
| `failed-deterministic` | Reproducible code/config/data, NaN/Inf, corruption, leakage, or broken locked metric | Preserve evidence; do not retry unchanged. Return to implementation. |
|
|
28
|
+
| `failed-transient` | Preemption, transport interruption, temporary host/device, or recoverable scheduler failure | Retry only within budget under a new linked run ID. |
|
|
29
|
+
| `stopped` | Declared kill condition or authorized cancellation | Preserve partial artifacts and the reason. |
|
|
30
|
+
|
|
31
|
+
An unexpected finite result, noisy metric, weak interim effect, or insufficient samples is not deterministic invalidity. Do not stop because the hypothesis appears unsupported.
|
|
32
|
+
|
|
33
|
+
## Stop and retry safely
|
|
34
|
+
|
|
35
|
+
For a declared stop condition, record the evidence, request graceful termination, allow the checkpoint/cleanup grace period, verify exit and output finalization, and force termination only when the process remains active and the scope authorizes it. Preserve logs, partial outputs, checkpoints, exit/signal status, and device diagnostics.
|
|
36
|
+
|
|
37
|
+
Retry only a transient fault within the frozen retry budget. Create a new run ID with `parent_run_id` and `retry_of`; preserve the specification, code, config, data, precision, backend, and seed policy. Apply the checkpoint gate in `run-experiment.md` before resuming. A different batch size, precision, solver, `dt`, backend, seed rule, checkpoint cadence, or model code is a new scientific run, not a retry.
|
|
38
|
+
|
|
39
|
+
Never delete a failed run or overwrite collected artifacts. Never destroy paid remote compute until copied artifacts and hashes are verified and teardown is explicitly authorized.
|
|
40
|
+
|
|
41
|
+
## Collect and report
|
|
42
|
+
|
|
43
|
+
For remote runs, copy into a new local collection path and verify the artifact manifest and hashes before marking collection complete. Report raw values before interpretation:
|
|
44
|
+
|
|
45
|
+
| Run ID | Level | Backend/device | Progress or exit | Primary declared metric | Artifacts |
|
|
46
|
+
|---|---|---|---|---|---|
|
|
47
|
+
| `<id>` | `production` | `cuda / GPU UUID` | `done / 0` | `<raw value and unit>` | `complete` |
|
|
48
|
+
|
|
49
|
+
Also report start/end time, duration, exact command path, log path, checkpoint path/status, missing or corrupt outputs, retry lineage, and paid-compute cost when applicable. Compare only runs the locked contract declares comparable and label every differing field. Return `done`, `failed`, or `stopped`; never return `accepted`.
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
# Copyright 2024 BrainX Ecosystem Limited. All Rights Reserved.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
# ==============================================================================
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Union, Callable
|
|
19
|
+
|
|
20
|
+
import brainstate
|
|
21
|
+
import braintools
|
|
22
|
+
import brainunit as u
|
|
23
|
+
import jax
|
|
24
|
+
import matplotlib.pyplot as plt
|
|
25
|
+
import numpy as np
|
|
26
|
+
import pandas as pd
|
|
27
|
+
|
|
28
|
+
import braincell
|
|
29
|
+
|
|
30
|
+
brainstate.environ.set(dt=0.01 * u.ms)
|
|
31
|
+
|
|
32
|
+
# Load Input and Output Data
|
|
33
|
+
DATA_DIR = Path(__file__).resolve().parents[2] / "data" / "neuron_traces"
|
|
34
|
+
df_inp_traces = pd.read_csv(DATA_DIR / 'input_traces_hh.csv')
|
|
35
|
+
df_out_traces = pd.read_csv(DATA_DIR / 'output_traces_hh.csv')
|
|
36
|
+
|
|
37
|
+
area = 20000 * u.um ** 2 # neuronal area
|
|
38
|
+
inp_traces = df_inp_traces.to_numpy()[:, 1:] * 1e9 * u.nA # input currents
|
|
39
|
+
mem_traces = df_out_traces.to_numpy()[:, 1:] * u.mV # membrane potentials to record
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class INa(braincell.Channel):
|
|
43
|
+
root_type = braincell.HHTypedNeuron
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
size: brainstate.typing.Size,
|
|
48
|
+
ENa: Union[brainstate.typing.ArrayLike, Callable] = 50. * u.mV,
|
|
49
|
+
gNa: Union[brainstate.typing.ArrayLike, Callable] = 120. * u.mS,
|
|
50
|
+
vth: Union[brainstate.typing.ArrayLike, Callable] = -63 * u.mV,
|
|
51
|
+
):
|
|
52
|
+
super().__init__(size)
|
|
53
|
+
self.ENa = braintools.init.param(ENa, self.varshape)
|
|
54
|
+
self.gNa = braintools.init.param(gNa, self.varshape)
|
|
55
|
+
self.V_th = braintools.init.param(vth, self.varshape)
|
|
56
|
+
|
|
57
|
+
def init_state(self, V, batch_size=None):
|
|
58
|
+
self.m = braincell.state(braintools.init.param(u.math.zeros, self.varshape))
|
|
59
|
+
self.h = braincell.state(braintools.init.param(u.math.zeros, self.varshape))
|
|
60
|
+
|
|
61
|
+
# m channel
|
|
62
|
+
m_alpha = lambda self, V: 0.32 * 4 / u.math.exprel((13. * u.mV - V + self.V_th).to_decimal(u.mV) / 4.)
|
|
63
|
+
m_beta = lambda self, V: 0.28 * 5 / u.math.exprel((V - self.V_th - 40. * u.mV).to_decimal(u.mV) / 5.)
|
|
64
|
+
m_inf = lambda self, V: self.m_alpha(V) / (self.m_alpha(V) + self.m_beta(V))
|
|
65
|
+
|
|
66
|
+
# h channel
|
|
67
|
+
h_alpha = lambda self, V: 0.128 * u.math.exprel((17. * u.mV - V + self.V_th).to_decimal(u.mV) / 18.)
|
|
68
|
+
h_beta = lambda self, V: 4. / (1 + u.math.exp((40. * u.mV - V + self.V_th).to_decimal(u.mV) / 5.))
|
|
69
|
+
h_inf = lambda self, V: self.h_alpha(V) / (self.h_alpha(V) + self.h_beta(V))
|
|
70
|
+
|
|
71
|
+
def compute_derivative(self, V, *args, **kwargs):
|
|
72
|
+
m = self.m.value
|
|
73
|
+
h = self.h.value
|
|
74
|
+
self.m.derivative = (self.m_alpha(V) * (1 - m) - self.m_beta(V) * m) / u.ms
|
|
75
|
+
self.h.derivative = (self.h_alpha(V) * (1 - h) - self.h_beta(V) * h) / u.ms
|
|
76
|
+
|
|
77
|
+
def current(self, V, *args, **kwargs):
|
|
78
|
+
m = self.m.value
|
|
79
|
+
h = self.h.value
|
|
80
|
+
return (self.gNa * m * m * m * h) * (self.ENa - V)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class IK(braincell.Channel):
|
|
84
|
+
root_type = braincell.HHTypedNeuron
|
|
85
|
+
|
|
86
|
+
def __init__(
|
|
87
|
+
self,
|
|
88
|
+
size: brainstate.typing.Size,
|
|
89
|
+
EK: Union[brainstate.typing.ArrayLike, Callable] = -90. * u.mV,
|
|
90
|
+
gK: Union[brainstate.typing.ArrayLike, Callable] = 36. * u.mS,
|
|
91
|
+
vth: Union[brainstate.typing.ArrayLike, Callable] = -63 * u.mV,
|
|
92
|
+
):
|
|
93
|
+
super().__init__(size)
|
|
94
|
+
self.EK = braintools.init.param(EK, self.varshape)
|
|
95
|
+
self.gK = braintools.init.param(gK, self.varshape)
|
|
96
|
+
self.V_th = braintools.init.param(vth, self.varshape)
|
|
97
|
+
|
|
98
|
+
def init_state(self, V, batch_size=None):
|
|
99
|
+
self.n = braincell.state(braintools.init.param(u.math.zeros, self.varshape))
|
|
100
|
+
|
|
101
|
+
# n channel
|
|
102
|
+
n_alpha = lambda self, V: 0.032 * 5 / u.math.exprel((15. * u.mV - V + self.V_th).to_decimal(u.mV) / 5.)
|
|
103
|
+
n_beta = lambda self, V: .5 * u.math.exp((10. * u.mV - V + self.V_th).to_decimal(u.mV) / 40.)
|
|
104
|
+
n_inf = lambda self, V: self.n_alpha(V) / (self.n_alpha(V) + self.n_beta(V))
|
|
105
|
+
|
|
106
|
+
def compute_derivative(self, V, *args, **kwargs):
|
|
107
|
+
n = self.n.value
|
|
108
|
+
self.n.derivative = (self.n_alpha(V) * (1 - n) - self.n_beta(V) * n) / u.ms
|
|
109
|
+
|
|
110
|
+
def current(self, V, *args, **kwargs):
|
|
111
|
+
n2 = self.n.value ** 2
|
|
112
|
+
return (self.gK * n2 * n2) * (self.EK - V)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class HH(braincell.SingleCompartment):
|
|
116
|
+
def __init__(
|
|
117
|
+
self,
|
|
118
|
+
size,
|
|
119
|
+
v_initializer: Callable = braintools.init.Uniform(-70 * u.mV, -60. * u.mV),
|
|
120
|
+
gL: Union[brainstate.typing.ArrayLike, Callable] = 0.003 * u.mS,
|
|
121
|
+
gNa: Union[brainstate.typing.ArrayLike, Callable] = 120. * u.mS,
|
|
122
|
+
gK: Union[brainstate.typing.ArrayLike, Callable] = 36. * u.mS,
|
|
123
|
+
C: Union[brainstate.typing.ArrayLike, Callable] = 1. * (u.uF / u.cm ** 2),
|
|
124
|
+
solver: str = 'rk4'
|
|
125
|
+
):
|
|
126
|
+
super().__init__(size, V_initializer=v_initializer, C=C, solver=solver)
|
|
127
|
+
self.ina = INa(size, gNa=gNa)
|
|
128
|
+
self.ik = IK(size, gK=gK)
|
|
129
|
+
self.il = braincell.channel.IL(size, g_max=gL, E=-65. * u.mV)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def visualize_target(voltages):
|
|
133
|
+
fig, gs = braintools.visualize.get_figure(2, voltages.shape[1], 3, 4.5)
|
|
134
|
+
times = np.arange(voltages.shape[0]) * 0.01
|
|
135
|
+
for i in range(voltages.shape[1]):
|
|
136
|
+
ax = fig.add_subplot(gs[0, i])
|
|
137
|
+
ax.plot(times, voltages[:, i], label='target')
|
|
138
|
+
plt.xlabel('Time [ms]')
|
|
139
|
+
plt.legend()
|
|
140
|
+
ax = plt.subplot(gs[1, i])
|
|
141
|
+
ax.plot(times, inp_traces[i])
|
|
142
|
+
plt.xlabel('Time [ms]')
|
|
143
|
+
plt.show()
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def visualize(voltages, gl, g_na, g_kd, C):
|
|
147
|
+
# currents: [T, B]
|
|
148
|
+
# voltages: [T, B]
|
|
149
|
+
simulated_vs = simulate_model(gl, g_na, g_kd, C)
|
|
150
|
+
voltages = voltages.mantissa
|
|
151
|
+
|
|
152
|
+
fig, gs = braintools.visualize.get_figure(2, simulated_vs.shape[1], 3, 4.5)
|
|
153
|
+
for i in range(simulated_vs.shape[1]):
|
|
154
|
+
ax = fig.add_subplot(gs[0, i])
|
|
155
|
+
ax.plot(voltages[:, i], label='target')
|
|
156
|
+
ax.plot(simulated_vs[:, i], label='simulated')
|
|
157
|
+
plt.legend()
|
|
158
|
+
ax = plt.subplot(gs[1, i])
|
|
159
|
+
ax.plot(inp_traces[i])
|
|
160
|
+
plt.show()
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def simulate_model(gl, g_na, g_kd, C):
|
|
164
|
+
current = inp_traces.T
|
|
165
|
+
assert current.ndim == 2 # [T, B]
|
|
166
|
+
n_input = current.shape[1]
|
|
167
|
+
hh = HH((n_input, 1), gL=gl, gNa=g_na, gK=g_kd, C=C, v_initializer=braintools.init.Constant(-65. * u.mV), )
|
|
168
|
+
hh.init_state()
|
|
169
|
+
|
|
170
|
+
def step_fun(i, inp):
|
|
171
|
+
with brainstate.environ.context(i=i, t=brainstate.environ.get_dt() * i):
|
|
172
|
+
spike = hh(inp)
|
|
173
|
+
return hh.V.value
|
|
174
|
+
|
|
175
|
+
indices = np.arange(current.shape[0])
|
|
176
|
+
current = u.math.expand_dims(current, axis=-1) # [T, B, 1]
|
|
177
|
+
return brainstate.transform.for_loop(step_fun, indices, current) # (T, B)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def compare_potentials(param):
|
|
181
|
+
vs = simulate_model(param['gl'], param['g_na'], param['g_kd'], param['C']) # (T, B)
|
|
182
|
+
losses = braintools.metric.squared_error(vs.mantissa, target_vs.mantissa)
|
|
183
|
+
return losses.mean()
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
# inp_traces: [B, T]
|
|
187
|
+
# target_vs: [B, T, 1]
|
|
188
|
+
# target_vs = simulate_model(50.37195496 * u.nsiemens,
|
|
189
|
+
# 28.01317016 * u.usiemens,
|
|
190
|
+
# 8.15968937 * u.usiemens,
|
|
191
|
+
# 195.2173985 * u.pfarad)
|
|
192
|
+
target_vs = u.math.expand_dims(mem_traces.T, axis=-1) # [T, B, 1]
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
# visualize_target(target_vs)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def visualize_hh_input_and_output():
|
|
199
|
+
# Load Input and Output Data
|
|
200
|
+
inp_traces = df_inp_traces.to_numpy()
|
|
201
|
+
inp_traces = inp_traces[:, 1:] * 1e9
|
|
202
|
+
|
|
203
|
+
out_traces = df_out_traces.to_numpy()
|
|
204
|
+
out_traces = out_traces[:, 1:]
|
|
205
|
+
|
|
206
|
+
indices = np.arange(inp_traces.shape[1]) * 0.01
|
|
207
|
+
|
|
208
|
+
fig, gs = braintools.visualize.get_figure(3, 1, 1.2, 6.0)
|
|
209
|
+
ax = fig.add_subplot(gs[0, 0])
|
|
210
|
+
ax.plot(indices, inp_traces.T)
|
|
211
|
+
plt.xticks([])
|
|
212
|
+
plt.ylabel('Current [nA]', fontsize=13)
|
|
213
|
+
|
|
214
|
+
ax2 = fig.add_subplot(gs[1:, 0])
|
|
215
|
+
ax2.plot(indices, out_traces.T)
|
|
216
|
+
plt.ylabel('Potential [mV]', fontsize=13)
|
|
217
|
+
plt.xlabel('Time [ms]')
|
|
218
|
+
|
|
219
|
+
fig.align_ylabels([ax, ax2])
|
|
220
|
+
plt.show()
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
bounds = {
|
|
224
|
+
'gl': [1e0, 1e2] * u.nS,
|
|
225
|
+
'g_na': [1e0, 2e2] * u.uS,
|
|
226
|
+
'g_kd': [1e0, 1e2] * u.uS,
|
|
227
|
+
'C': [0.1, 2] * u.uF * u.cm ** -2 * area,
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def fitting_by_nevergrad(method='DE', n_sample=200, n_iter=20):
|
|
232
|
+
print(f"Method: {method}, n_sample: {n_sample}")
|
|
233
|
+
|
|
234
|
+
@brainstate.transform.jit
|
|
235
|
+
def loss_with_multiple_run(**params):
|
|
236
|
+
return brainstate.transform.vmap(compare_potentials)(params)
|
|
237
|
+
|
|
238
|
+
opt = braintools.optim.NevergradOptimizer(
|
|
239
|
+
loss_with_multiple_run,
|
|
240
|
+
n_sample=n_sample,
|
|
241
|
+
bounds=bounds,
|
|
242
|
+
method=method,
|
|
243
|
+
)
|
|
244
|
+
opt.initialize()
|
|
245
|
+
param = opt.minimize(n_iter)
|
|
246
|
+
loss = compare_potentials(param)
|
|
247
|
+
print(param)
|
|
248
|
+
print(loss)
|
|
249
|
+
visualize(target_vs, **param)
|
|
250
|
+
return param, loss
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
if __name__ == '__main__':
|
|
254
|
+
fitting_by_nevergrad(n_sample=100)
|