brainx-skill 1.0.6 → 1.0.9

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 (120) hide show
  1. package/README.md +10 -8
  2. package/adapters/gemini.js +7 -0
  3. package/adapters/opencode.js +7 -0
  4. package/adapters/windsurf.js +7 -0
  5. package/installation/lib/installer.js +4 -1
  6. package/manifest.json +6 -1
  7. package/package.json +8 -2
  8. package/skills/braincell/SKILL.md +182 -0
  9. package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
  10. package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +273 -0
  11. package/skills/braincell/references/channel-library.md +85 -0
  12. package/skills/braincell/references/ion-library.md +87 -0
  13. package/skills/braincell/references/mixions-for-adaptation.md +81 -0
  14. package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
  15. package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
  16. package/skills/braincell/references/multicompartment/filter-function-library.md +154 -0
  17. package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
  18. package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
  19. package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
  20. package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +260 -0
  21. package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
  22. package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
  23. package/skills/braincell/references/scripts/channel_ablation.py +61 -0
  24. package/skills/braincell/references/scripts/fi_curve.py +68 -0
  25. package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
  26. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
  27. package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
  28. package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
  29. package/skills/braincell/references/solver-library-with-effects.md +188 -0
  30. package/skills/brainevent/SKILL.md +268 -0
  31. package/skills/brainevent/references/connectivity-variants.md +312 -0
  32. package/skills/brainevent/references/custom-operators-cpu.md +304 -0
  33. package/skills/brainevent/references/custom-operators-gpu.md +468 -0
  34. package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
  35. package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
  36. package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
  37. package/skills/brainevent/references/sparse-formats.md +182 -0
  38. package/skills/brainevent/references/synaptic-plasticity.md +285 -0
  39. package/skills/brainmass/SKILL.md +290 -0
  40. package/skills/brainmass/references/batch-transform-acceleration.md +136 -0
  41. package/skills/brainmass/references/brainstate/parameter-constraints-regularization.md +214 -0
  42. package/skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
  43. package/skills/brainmass/references/braintools/cogtask.md +190 -0
  44. package/skills/brainmass/references/braintools/data-preprocessing.md +83 -0
  45. package/skills/brainmass/references/braintools/metric.md +157 -0
  46. package/skills/brainmass/references/braintools/optimizer.md +187 -0
  47. package/skills/brainmass/references/braintools/parameter-initializer.md +187 -0
  48. package/skills/brainmass/references/braintools/surrogate.md +151 -0
  49. package/skills/brainmass/references/coupling-network-api.md +148 -0
  50. package/skills/brainmass/references/datasets-api.md +72 -0
  51. package/skills/brainmass/references/fitting-with-objectives-api.md +146 -0
  52. package/skills/brainmass/references/forward-observation-api.md +131 -0
  53. package/skills/brainmass/references/horn-task-training.md +199 -0
  54. package/skills/brainmass/references/modellibrary.md +104 -0
  55. package/skills/brainmass/references/noiseprocesses.md +121 -0
  56. package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +130 -0
  57. package/skills/brainmass/references/scripts/eeg-fitting-with-gradients.py +230 -0
  58. package/skills/brainmass/references/scripts/gradient-free-fitting.py +106 -0
  59. package/skills/brainmass/references/scripts/hopf-bifurcation-single-node.py +78 -0
  60. package/skills/brainmass/references/scripts/horn-cognitive-task-training.py +211 -0
  61. package/skills/brainmass/references/scripts/jansen-rit-eeg-proxy.py +76 -0
  62. package/skills/brainmass/references/scripts/kuramoto-synchronization.py +81 -0
  63. package/skills/brainmass/references/scripts/linear-baseline-node.py +81 -0
  64. package/skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +249 -0
  65. package/skills/brainmass/references/scripts/seizure-epileptor-case-study.py +126 -0
  66. package/skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +86 -0
  67. package/skills/brainmass/references/scripts/wong-wang-decision-making.py +167 -0
  68. package/skills/brainmass/references/scripts/wong-wang-dmf-resting-state.py +72 -0
  69. package/skills/brainmass/references/visualization-analysis-api.md +130 -0
  70. package/skills/brainpy-state/SKILL.md +232 -0
  71. package/skills/brainpy-state/references/array-creation.md +158 -0
  72. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
  73. package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
  74. package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
  75. package/skills/brainpy-state/references/braintools/metric.md +152 -0
  76. package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
  77. package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
  78. package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
  79. package/skills/brainpy-state/references/component-selection.md +273 -0
  80. package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
  81. package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
  82. package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
  83. package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
  84. package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
  85. package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
  86. package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
  87. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
  88. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
  89. package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
  90. package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
  91. package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
  92. package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
  93. package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
  94. package/skills/brainpy-state/references/projection-patterns.md +125 -0
  95. package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
  96. package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
  97. package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
  98. package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
  99. package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
  100. package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
  101. package/skills/brainstate/SKILL.md +1 -1
  102. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +250 -399
  103. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +6 -2
  104. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +16 -2
  105. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +8 -3
  106. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +64 -143
  107. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +13 -1
  108. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +11 -1
  109. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +35 -7
  110. package/skills/brainstate/references/collective_model_operations.md +9 -9
  111. package/skills/brainstate/references/extension_mechanisms.md +12 -1
  112. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -97
  113. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +102 -176
  114. package/skills/brainstate/references/model-interop-and-migration.md +11 -1
  115. package/skills/brainstate/references/size-inference-variations.md +11 -0
  116. package/skills/brainstate/references/state-graph-operations.md +13 -15
  117. package/skills/brainstate/references/state_collections_and_utilities.md +12 -1
  118. package/skills/brainx-general-guard/SKILL.md +68 -0
  119. package/skills/brainstate/references/braintools-optimizer-reference.md +0 -133
  120. package/skills/brainstate/references/libraries/solver-library-with-effects.md +0 -85
package/README.md CHANGED
@@ -1,13 +1,8 @@
1
1
  # BrainX Skill
2
2
 
3
- [![Supported BrainX release](https://img.shields.io/badge/BrainX-v2026.7.9-007EC6?style=flat)](skills/brainx-install/references/compatibility-and-release-matching.md#version-compatibility-matrix)
4
- [![License](https://img.shields.io/badge/License-Apache%202.0-4C1?style=flat)](LICENSE)
5
- [![npm downloads](https://img.shields.io/npm/dm/brainx-skill?label=npm&color=007EC6&style=flat)](https://www.npmjs.com/package/brainx-skill)
6
- [![Skills](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2Fchaobrain%2FBrainX-skill%2Fmain%2Fmanifest.json&query=%24.skills.length&label=Skills&color=007EC6&style=flat)](manifest.json)
7
- [![Agent Skills validation](https://img.shields.io/github/actions/workflow/status/chaobrain/BrainX-skill/agent-skills-validation.yml?branch=main&label=Agent%20Skills&style=flat)](https://github.com/chaobrain/BrainX-skill/actions/workflows/agent-skills-validation.yml)
8
- [![OpenSSF Scorecard](https://img.shields.io/ossf-scorecard/github.com/chaobrain/BrainX-skill?label=OpenSSF&style=flat)](https://scorecard.dev/viewer/?uri=github.com/chaobrain/BrainX-skill)
3
+ [![Supported BrainX release](https://img.shields.io/badge/BrainX-v2026.7.9-007EC6?style=flat)](skills/brainx-install/references/compatibility-and-release-matching.md#version-compatibility-matrix) [![License](https://img.shields.io/badge/License-Apache%202.0-4C1?style=flat)](LICENSE) [![npm downloads](https://img.shields.io/npm/dm/brainx-skill?label=npm&color=007EC6&style=flat)](https://www.npmjs.com/package/brainx-skill) [![Skills](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2Fchaobrain%2FBrainX-skill%2Fmain%2Fmanifest.json&query=%24.skills.length&label=Skills&color=007EC6&style=flat)](manifest.json) [![Agent Skills validation](https://img.shields.io/github/actions/workflow/status/chaobrain/BrainX-skill/agent-skills-validation.yml?branch=main&label=Agent%20Skills&style=flat)](https://github.com/chaobrain/BrainX-skill/actions/workflows/agent-skills-validation.yml) [![OpenSSF Scorecard](https://img.shields.io/ossf-scorecard/github.com/chaobrain/BrainX-skill?label=OpenSSF&style=flat)](https://scorecard.dev/viewer/?uri=github.com/chaobrain/BrainX-skill)
9
4
 
10
- [![Works with Claude Code, Codex, and Cursor](https://img.shields.io/badge/Works%20with-Claude%20Code%20%7C%20Codex%20%7C%20Cursor-007EC6?style=flat)](#installation-locations)
5
+ [![Works with Claude Code, Codex, Cursor, Windsurf, Gemini CLI, and OpenCode](https://img.shields.io/badge/Works%20with-Claude%20Code%20%7C%20Codex%20%7C%20Cursor%20%7C%20Windsurf%20%7C%20Gemini%20CLI%20%7C%20OpenCode-007EC6?style=flat)](#installation-locations)
11
6
 
12
7
  make your coding agent understand the power of BrainX
13
8
 
@@ -43,10 +38,14 @@ npx brainx-skill update
43
38
  ```
44
39
 
45
40
 
46
- ## Install when the internet connection is low
41
+ ## When the internet connection is low
47
42
 
48
43
  ```bash
44
+ # install
49
45
  npx --registry=https://registry.npmmirror.com brainx-skill install
46
+
47
+ # update
48
+ npx --registry=https://registry.npmmirror.com brainx-skill update
50
49
  ```
51
50
 
52
51
  ## Installation locations
@@ -57,6 +56,9 @@ Depending on the selected scope, the canonical `brainx-install` skill is install
57
56
  Claude Code: ~/.claude/skills/<skill-name> or <cwd>/.claude/skills/<skill-name>
58
57
  Codex: ~/.agents/skills/<skill-name> or <cwd>/.agents/skills/<skill-name>
59
58
  Cursor: ~/.cursor/skills/<skill-name> or <cwd>/.cursor/skills/<skill-name>
59
+ Windsurf: ~/.codeium/windsurf/skills/<skill-name> or <cwd>/.codeium/windsurf/skills/<skill-name>
60
+ Gemini CLI: ~/.gemini/skills/<skill-name> or <cwd>/.gemini/skills/<skill-name>
61
+ OpenCode: ~/.config/opencode/skills/<skill-name> or <cwd>/.config/opencode/skills/<skill-name>
60
62
  ```
61
63
 
62
64
  Installation ownership is recorded in `~/.brainx/receipt.json`.
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ module.exports = Object.freeze({
4
+ id: 'gemini',
5
+ label: 'Gemini CLI',
6
+ homePath: ['.gemini', 'skills'],
7
+ });
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ module.exports = Object.freeze({
4
+ id: 'opencode',
5
+ label: 'OpenCode',
6
+ homePath: ['.config', 'opencode', 'skills'],
7
+ });
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ module.exports = Object.freeze({
4
+ id: 'windsurf',
5
+ label: 'Windsurf',
6
+ homePath: ['.codeium', 'windsurf', 'skills'],
7
+ });
@@ -6,13 +6,16 @@ const path = require('node:path');
6
6
  const codex = require('../../adapters/codex');
7
7
  const claude = require('../../adapters/claude');
8
8
  const cursor = require('../../adapters/cursor');
9
+ const windsurf = require('../../adapters/windsurf');
10
+ const gemini = require('../../adapters/gemini');
11
+ const opencode = require('../../adapters/opencode');
9
12
  const { prepareAdapter, AdapterOperationError } = require('./adapter-transaction');
10
13
  const { validateBundle } = require('./bundle');
11
14
  const { PACKAGE_NAME, RECEIPT_SCHEMA_VERSION } = require('./constants');
12
15
  const { resolveDestinationRoot, resolveLocations } = require('./paths');
13
16
  const { readReceipt, writeReceiptAtomic } = require('./receipt');
14
17
 
15
- const DEFAULT_ADAPTERS = [claude, codex, cursor];
18
+ const DEFAULT_ADAPTERS = [claude, codex, cursor, windsurf, gemini, opencode];
16
19
 
17
20
  function writeLine(stream, text = '') {
18
21
  stream.write(`${text}\n`);
package/manifest.json CHANGED
@@ -1,8 +1,13 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "skills": [
4
+ "brainx-general-guard",
5
+ "braincell",
6
+ "brainmass",
4
7
  "brainx-install",
5
8
  "brainunit",
6
- "brainstate"
9
+ "brainstate",
10
+ "brainevent",
11
+ "brainpy-state"
7
12
  ]
8
13
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "brainx-skill",
3
- "version": "1.0.6",
4
- "description": "Portable BrainX Agent Skills for Claude Code, Codex, and Cursor",
3
+ "version": "1.0.9",
4
+ "description": "Portable BrainX Agent Skills for Claude Code, Codex, Cursor, Windsurf, Gemini CLI, and OpenCode",
5
5
  "license": "Apache-2.0",
6
6
  "type": "commonjs",
7
7
  "scripts": {
@@ -14,9 +14,14 @@
14
14
  "files": [
15
15
  "adapters/",
16
16
  "installation/",
17
+ "skills/braincell/",
18
+ "skills/brainmass/",
17
19
  "skills/brainx-install/",
18
20
  "skills/brainunit/",
19
21
  "skills/brainstate/",
22
+ "skills/brainevent/",
23
+ "skills/brainpy-state/",
24
+ "skills/brainx-general-guard/",
20
25
  "manifest.json",
21
26
  "README.md",
22
27
  "LICENSE"
@@ -43,6 +48,7 @@
43
48
  "agent-skills",
44
49
  "brainx",
45
50
  "brainunit",
51
+ "brainevent",
46
52
  "claude-code",
47
53
  "codex",
48
54
  "cursor"
@@ -0,0 +1,182 @@
1
+ ---
2
+ name: braincell
3
+ description: Use for cell modeling with conductance-based or Hodgkin-Huxley ions, channels, compartments, or morphology. Use alone for cell studies or together with BrainPy-State and/or BrainMass when cellular mechanisms participate in a multiscale model.
4
+ ---
5
+
6
+ # BrainCell
7
+
8
+ ## Purpose and boundary
9
+
10
+ Use BrainCell for cellular biophysics at either of its two supported spatial scales:
11
+
12
+ - Use `SingleCompartment` when voltage is uniform across one isopotential cell and the task is channel prototyping, current injection, fitting, or a batch of independent point neurons.
13
+ - Use `Cell` when soma, dendrite, axon, branch geometry, spatial channel distribution, or location-specific stimulation and recording affect the result.
14
+
15
+
16
+ Keep network wiring, projections, and network training outside this skill. Open `skills/brainpy-state/SKILL.md` when multiple cells must communicate.
17
+
18
+ ## Underlying principle of BrainCell
19
+
20
+ `HHTypedNeuron` represents conductance-based membrane dynamics. It supplies the shared ion, channel, state, and integration contract used by both cell front ends.
21
+
22
+ `SingleCompartment` represents one isopotential neuron. It collapses morphology and discretization and attaches ions and channels imperatively.
23
+
24
+ `Morphology` represents cable geometry and topology. `Cell` discretizes that geometry into isopotential control volumes whose axial coupling produces spatial voltage dynamics.
25
+
26
+ `braincell.mech` declarations represent what cellular mechanisms exist, while `braincell.filter` expressions represent where they apply. `paint()` distributes density mechanisms over cable regions; `place()` attaches point mechanisms at locations.
27
+
28
+ ### API structure
29
+
30
+ | Module | Use |
31
+ |---|---|
32
+ | `braincell` | Use the public modeling surface for cells, morphology and branch types, control-volume policies, ion-channel bases, clamps, and run results. |
33
+ | `braincell.morph` | Represent, manipulate, and measure neuronal morphology structures before simulation. |
34
+ | `braincell.ion` | Choose sodium, potassium, and calcium ion models and their reversal-potential or concentration dynamics. |
35
+ | `braincell.channel` | Choose built-in membrane-channel dynamics for calcium, HCN, leak, potassium, potassium-calcium, and sodium currents. |
36
+ | `braincell.synapse` | Choose built-in AMPA, GABAa, and NMDA Markov synapse models. |
37
+ | `braincell.mech` | Declare what a multicompartment `Cell` installs: cable properties, density ions and channels, point mechanisms, and probes. |
38
+ | `braincell.filter` | Build regions for `paint()` and locsets for `place()`, including composed spatial selections. |
39
+ | `braincell.io` | Load, validate, checkpoint, and retrieve morphologies from supported file formats and NeuroMorpho.Org. |
40
+ | `braincell.quad` | Define differential-equation modules and choose, inspect, or register numerical integrators. |
41
+ | `braincell.vis` | Visualize morphologies, topology, control volumes, values, traces, and morphometric analyses in 2D or 3D. |
42
+
43
+ ## Build and run a single-compartment cell
44
+
45
+ A `SingleCompartment` cell stores one membrane voltage per independent neuron and advances its attached ion and channel states from an external current supplied to `update()`.
46
+
47
+ | API | Description |
48
+ |---|---|
49
+ | `braincell.SingleCompartment(size, ..., solver=...)` | Use for a conductance-based point cell; `size` sets the independent population shape, `n_compartment` remains one, and `solver` selects a registered integrator. |
50
+ | `braincell.ion.*Fixed(size, E=...)` | Use when an ion's reversal potential is constant; it owns `E` and receives channels driven by that ion. |
51
+ | `ion.add(name=channel)` | Use after constructing an ion; it registers a channel under that ion so the channel reads the correct reversal potential. |
52
+ | `braincell.channel.*` | Use for membrane-current and gating dynamics; inspect `root_type` before attachment, and attach root-cell channels such as `IL` directly to the cell. |
53
+ | `cell.init_state()` / `cell.reset_state()` | Use before the first step or to reseed an existing cell; they initialize or reset voltage, spike, ion, and channel State without changing the model declaration. |
54
+ | `cell.update(I_ext)` | Use for one integration step; pass a current-density or total-current `Quantity`, let the cell area normalize total current, update all cellular State, and receive the spike output. |
55
+ | `brainstate.environ.context()` / `brainstate.transform.for_loop()` | Use to provide `dt` and `t` and to execute a transformed time loop that returns recorded State instead of mutating Python containers. |
56
+
57
+ ```python
58
+ import braincell
59
+ import brainstate
60
+ import brainunit as u
61
+
62
+
63
+ class HH(braincell.SingleCompartment):
64
+ def __init__(self, size, solver="exp_euler"):
65
+ super().__init__(size, V_th=20.0 * u.mV, solver=solver)
66
+
67
+ self.na = braincell.ion.SodiumFixed(size, E=50.0 * u.mV)
68
+ self.na.add(INa=braincell.channel.Na_HH1952(size))
69
+
70
+ self.k = braincell.ion.PotassiumFixed(size, E=-77.0 * u.mV)
71
+ self.k.add(IK=braincell.channel.K_HH1952(size))
72
+
73
+ self.IL = braincell.channel.IL(
74
+ size,
75
+ E=-54.387 * u.mV,
76
+ g_max=0.03 * u.mS / u.cm**2,
77
+ )
78
+
79
+
80
+ cell = HH(1)
81
+ cell.init_state()
82
+ current = 5.0 * u.uA / u.cm**2
83
+
84
+
85
+ def step(t):
86
+ with brainstate.environ.context(t=t):
87
+ spike = cell.update(current)
88
+ return cell.V.value, spike
89
+
90
+
91
+ with brainstate.environ.context(dt=0.01 * u.ms):
92
+ times = u.math.arange(
93
+ 0.0 * u.ms,
94
+ 100.0 * u.ms,
95
+ brainstate.environ.get_dt(),
96
+ )
97
+ voltages, spikes = brainstate.transform.for_loop(step, times)
98
+
99
+ assert voltages.shape[:1] == times.shape
100
+ assert spikes.shape[:1] == times.shape
101
+ ```
102
+
103
+ Treat `V_th` only as the spike-event threshold; it does not change the membrane equation. Keep membrane capacitance and channel conductance density-based in the canonical path. `update()` accepts current density or total current and uses `SingleCompartment.area` to normalize total input; do not manually area-scale only part of the model. Use `size=N` for `N` independent cells, never for `N` compartments.
104
+
105
+ Open `references/area-scaled-hh-pattern.md` when changing cell geometry or explicitly converting density parameters to total quantities. Open `references/ion-library.md`, `references/channel-library.md`, or `references/mixions-for-adaptation.md` only when the classical fixed-ion HH path is insufficient.
106
+
107
+ ## Build and run a multicompartment cell
108
+
109
+ A `Cell` lowers morphology, spatial selectors, and declarative mechanisms into coupled control-volume State, then returns only the traces defined by placed probes.
110
+
111
+ | API | Description |
112
+ |---|---|
113
+ | `braincell.Morphology` | Use to load or construct branch geometry and topology before creating a cell; it describes continuous cable, not simulation compartments. |
114
+ | `braincell.Cell(morpho, cv_policy=..., solver=...)` | Use when spatial structure matters; it clones the morphology, applies a CV policy, and owns distinct declaration and initialized runtime phases. |
115
+ | `braincell.CVPolicy` | Use to control spatial resolution; it divides branches into isopotential control volumes, trading accuracy against State size and computation. |
116
+ | `cell.paint(region, *mechanisms)` | Use for cable properties and density mechanisms; it records declarations over a cable region and returns the cell for chaining. |
117
+ | `cell.place(locset, *mechanisms)` | Use for clamps, probes, and other point mechanisms; it records declarations at selected locations and returns the cell for chaining. |
118
+ | `cell.init_state()` | Use after all `paint()` and `place()` calls; it lowers declarations and allocates runtime State, and it raises if the cell is already initialized. |
119
+ | `cell.run(dt=..., duration=...)` | Use to advance the initialized cell and collect probe traces; it initializes on first use when needed and requires at least one placed probe. |
120
+ | `cell.reset_state()` / `cell.reset()` | Use `reset_state()` to reseed State while remaining initialized; use `reset()` to discard runtime State and return to the declaration phase before changing `paint()` or `place()` rules. |
121
+
122
+ ```python
123
+ import braincell
124
+ import braincell.mech as mech
125
+ import brainunit as u
126
+ from braincell.filter import AllRegion, RootLocation, at, branch_in
127
+
128
+
129
+ morphology = braincell.Morphology.from_swc("neuron.swc")
130
+ cell = braincell.Cell(
131
+ morphology,
132
+ cv_policy=braincell.CVPerBranch(cv_per_branch=2),
133
+ solver="staggered",
134
+ )
135
+
136
+ cell.paint(
137
+ AllRegion(),
138
+ mech.CableProperty(
139
+ resting_potential=-65.0 * u.mV,
140
+ membrane_capacitance=1.0 * u.uF / u.cm**2,
141
+ axial_resistivity=100.0 * u.ohm * u.cm,
142
+ ),
143
+ mech.Channel("IL", g_max=0.03 * u.mS / u.cm**2, E=-54.387 * u.mV),
144
+ )
145
+ cell.paint(
146
+ branch_in("type", "soma"),
147
+ mech.Channel("Na_HH1952", g_max=120.0 * u.mS / u.cm**2),
148
+ mech.Channel("K_HH1952", g_max=36.0 * u.mS / u.cm**2),
149
+ )
150
+ cell.place(
151
+ RootLocation(x=0.5),
152
+ mech.CurrentClamp(
153
+ delay=20.0 * u.ms,
154
+ durations=60.0 * u.ms,
155
+ amplitudes=0.2 * u.nA,
156
+ ),
157
+ )
158
+ cell.place(at("soma", 0.5), mech.StateProbe())
159
+
160
+ cell.init_state()
161
+ result = cell.run(dt=0.1 * u.ms, duration=100.0 * u.ms)
162
+
163
+ assert "soma(0.5)_v" in result.traces
164
+ ```
165
+
166
+ Use `paint()` only with regions and density mechanisms. Use `place()` only with locsets and point mechanisms. Declare all mechanisms before `init_state()`; call `reset()` before altering the declaration of an initialized cell.
167
+
168
+ Open `references/multicompartment/multicompartment-cell-workflow.md` for the complete advanced morphology-to-simulation path. Let that workflow select the exclusive morphology, filter, CV-policy, probe, or topology reference; do not open those leaves directly from this root skill.
169
+
170
+ ## Reference routing
171
+
172
+ Open only the smallest reference that owns the non-canonical decision.
173
+
174
+ | Reference | Open when |
175
+ |---|---|
176
+ | `references/area-scaled-hh-pattern.md` | Changing single-compartment geometry or converting density parameters consistently to total capacitance and conductance. |
177
+ | `references/braincell-custom-ion-channel-authoring.md` | Implementing a custom ion or channel after confirming that no built-in mechanism fits. |
178
+ | `references/channel-library.md` | Selecting a built-in sodium, potassium, calcium, leak, HCN, or mixed-ion channel. |
179
+ | `references/ion-library.md` | Choosing fixed, Nernst-initialized, or dynamic ions and their concentration behavior. |
180
+ | `references/mixions-for-adaptation.md` | Adding calcium-dependent adaptation, AHP/KCa currents, rebound, dynamic calcium, or multi-ion channel dependencies. |
181
+ | `references/multicompartment/multicompartment-cell-workflow.md` | Extending the canonical `Morphology -> Cell -> paint/place -> run` path and selecting the exclusive multicompartment references. |
182
+ | `references/solver-library-with-effects.md` | Comparing registered integrators, stability, accuracy, and solver-dependent trace effects. |
@@ -0,0 +1,54 @@
1
+ # Area-Scaled HH Pattern
2
+
3
+ Use this reference when a single-compartment HH model provides cell area, total capacitance, or conductance densities that must be converted to total conductance and total capacitance.
4
+
5
+ ## Rule
6
+
7
+ Keep `C`, `g_max`, and injected `I` all density-based by default. Only multiply by area when converting the entire model consistently to total capacitance, total conductance, and total current.
8
+
9
+ ## Pattern
10
+
11
+ ```python
12
+ import braincell
13
+ import brainunit as u
14
+
15
+
16
+ area = (20000. * u.um ** 2).in_unit(u.cm ** 2)
17
+ Cm = (1. * u.uF / u.cm ** 2) * area
18
+
19
+
20
+ class AreaHH(braincell.SingleCompartment):
21
+ def __init__(self, size, solver="ind_exp_euler"):
22
+ super().__init__(size, C=Cm, solver=solver)
23
+
24
+ self.na = braincell.ion.SodiumFixed(size, E=50. * u.mV)
25
+ self.na.add(
26
+ INa=braincell.channel.Na_TM1991(
27
+ size,
28
+ g_max=(100. * u.mS / u.cm ** 2) * area,
29
+ V_sh=-63. * u.mV,
30
+ )
31
+ )
32
+
33
+ self.k = braincell.ion.PotassiumFixed(size, E=-90. * u.mV)
34
+ self.k.add(
35
+ IK=braincell.channel.K_TM1991(
36
+ size,
37
+ g_max=(30. * u.mS / u.cm ** 2) * area,
38
+ V_sh=-63. * u.mV,
39
+ )
40
+ )
41
+
42
+ self.IL = braincell.channel.IL(
43
+ size,
44
+ E=-60. * u.mV,
45
+ g_max=(5. * u.nS / u.cm ** 2) * area,
46
+ )
47
+ ```
48
+
49
+ ## Checks
50
+
51
+ - Density conductance times area should become conductance.
52
+ - Capacitance density times area should become capacitance.
53
+ - If conductances and capacitance are total quantities, injected current should also be a total current rather than a current density.
54
+ - If the model remains density-based, do not multiply only one channel by area.
@@ -0,0 +1,273 @@
1
+ # BrainCell custom ion channel authoring
2
+
3
+ Use this reference only after `references/ion-library.md` and `references/channel-library.md` confirm that no built-in or literature-derived mechanism fits. For a multicompartment task, establish the `Cell` workflow in `references/multicompartment/multicompartment-cell-workflow.md` before applying the authoring patterns here.
4
+
5
+ ## Mental model
6
+
7
+ An ion owns reversal-potential and concentration information; a channel owns gating State and computes current from voltage plus the `IonInfo` supplied by its declared `root_type`.
8
+
9
+ Keep custom dynamics inside BrainCell's lifecycle:
10
+
11
+ `declare dependency and parameters -> allocate/reset State -> compute derivatives -> compute current -> integrate through the cell -> validate against a reference`
12
+
13
+ Do not replace this lifecycle with detached ODE functions or raw JAX arrays.
14
+
15
+ ## Choose the channel extension level
16
+
17
+ | Use | Need |
18
+ |---|---|
19
+ | `braincell.channel._base.HH` | Use for independent Hodgkin-Huxley gates. Declare `Gate` objects, implement one recognized kinetic form per gate, and implement `current()`. |
20
+ | `braincell.channel._base.Markov` | Use for coupled probabilistic channel states. Declare transitions, one dependent state, a conservation total, transition-rate methods, and current from open-state probability. |
21
+ | `braincell.Channel` | Use for dynamics that HH and Markov templates cannot express. Implement State initialization/reset, derivatives, required lifecycle hooks, and current directly. |
22
+ | `register_channel` | Use when `mech.Channel(...)` must resolve the custom channel by name. Register a unique name when the defining module is imported. |
23
+
24
+ `braincell.channel._base` is a lower-level authoring module. Inspect the installed version before relying on it across releases.
25
+
26
+ ## Define the channel contract
27
+
28
+ | API | Description |
29
+ |---|---|
30
+ | `root_type` | Set to the required ion class, ordered joint-ion dependency, or `HHTypedNeuron` for a root-cell channel; BrainCell uses it to validate attachment and supply the correct arguments. |
31
+ | `braincell.IonInfo` | Read `Ci`, `Co`, `E`, and `valence` from this value passed by the ion owner; do not reach into the parent ion object. |
32
+ | `init_state(V, *ion_info, batch_size=None)` | Allocate channel State for first use. |
33
+ | `reset_state(V, *ion_info, batch_size=None)` | Restore the channel's documented initial or steady-state condition without changing its declaration. |
34
+ | `compute_derivative(V, *ion_info)` | Write every integrable channel State derivative for the current voltage and ion information. |
35
+ | `current(V, *ion_info)` | Return the channel current with the same unit convention expected by the owning cell. |
36
+ | `pre_integral(V, *ion_info)` | Override only when work must occur before the solver advances State. |
37
+ | `post_integral(V, *ion_info)` | Override only when work must occur after the solver advances State. |
38
+
39
+ For a single-ion channel, the method argument order follows `root_type`. For a mixed-ion channel, it follows the ordered joint type exactly.
40
+
41
+ ## Author an HH-template channel
42
+
43
+ Use `HH` when each gate follows either an `inf/tau` or `alpha/beta` first-order equation.
44
+
45
+ | API | Description |
46
+ |---|---|
47
+ | `Gate(name, power=..., phi=...)` | Declare one gating State, its conductance exponent, and an optional direct temperature factor. |
48
+ | `f_<gate>_inf(...)` and `f_<gate>_tau(...)` | Implement the steady-state and time-constant form; `tau` returns a plain number whose natural unit is milliseconds. |
49
+ | `f_<gate>_alpha(...)` and `f_<gate>_beta(...)` | Implement the forward/backward-rate form; rates return plain numbers whose natural unit is inverse milliseconds. |
50
+ | `conductance_factor(V, *ion_info)` | Use inside `current()` to obtain the product of all declared gate values raised to their configured powers. |
51
+
52
+ ```python
53
+ import braincell
54
+ import brainunit as u
55
+ import jax.numpy as jnp
56
+ from braincell import IonInfo
57
+ from braincell.channel._base import Gate, HH
58
+ from braincell.mech import register_channel
59
+
60
+
61
+ @register_channel("DemoK")
62
+ class DemoKChannel(HH):
63
+ root_type = braincell.ion.Potassium
64
+ gates = (Gate("n", power=4, phi=2.0),)
65
+
66
+ def __init__(
67
+ self,
68
+ size,
69
+ g_max=1.0 * u.mS / u.cm**2,
70
+ ):
71
+ super().__init__(size=size)
72
+ self.g_max = g_max
73
+
74
+ def current(self, V, K: IonInfo):
75
+ return (
76
+ self.g_max
77
+ * self.conductance_factor(V, K)
78
+ * (K.E - V)
79
+ )
80
+
81
+ def f_n_inf(self, V, K: IonInfo):
82
+ _ = K
83
+ voltage_mV = V.to_decimal(u.mV)
84
+ return 1.0 / (
85
+ 1.0 + u.math.exp(-(voltage_mV + 35.0) / 10.0)
86
+ )
87
+
88
+ def f_n_tau(self, V, K: IonInfo):
89
+ _ = (V, K)
90
+ return 5.0
91
+
92
+
93
+ V = jnp.array([-55.0]) * u.mV
94
+ k_info = IonInfo(
95
+ Ci=jnp.array([54.4]) * u.mM,
96
+ Co=jnp.array([2.5]) * u.mM,
97
+ E=jnp.array([-90.0]) * u.mV,
98
+ valence=1,
99
+ )
100
+
101
+ channel = DemoKChannel(size=1)
102
+ channel.init_state(V, k_info)
103
+ channel.n.value = jnp.array([0.2])
104
+ channel.compute_derivative(V, k_info)
105
+ current = channel.current(V, k_info)
106
+
107
+ assert channel.n.derivative.shape == (1,)
108
+ assert current.shape == (1,)
109
+ channel.n.derivative.to_decimal(u.Hz)
110
+ current.to_decimal(u.mA / u.cm**2)
111
+ ```
112
+
113
+ For the `inf/tau` form, `HH` applies
114
+
115
+ `dx/dt = phi * (x_inf - x) / tau / ms`.
116
+
117
+ For the `alpha/beta` form, it applies
118
+
119
+ `dx/dt = phi * (alpha * (1 - x) - beta * x) / ms`.
120
+
121
+ Implement only one recognized form for each gate. Keep unit conversion at formula boundaries, such as `V.to_decimal(u.mV)`, and return the convention expected by the template.
122
+
123
+ ## Use Markov or the lower-level channel interface
124
+
125
+ Use `Markov` when channel-state probabilities are coupled through a transition graph rather than independent gates.
126
+
127
+ | API | Description |
128
+ |---|---|
129
+ | `Transition(src, dst, forward, backward)` | Declare one bidirectional edge and the names of its rate methods. |
130
+ | `Markov.pairs` | Declare the complete transition graph. |
131
+ | `Markov.dependent_state` | Name the probability reconstructed from the conservation law instead of integrated independently. |
132
+ | `Markov.conserve` | Set the conserved total, normally `1.0` for state probabilities. |
133
+
134
+ Use `braincell.Channel` directly only when neither HH gates nor a conserved Markov graph represent the equations. In that path, allocate every `DiffEqState`, define a reproducible reset rule, write every derivative in `compute_derivative()`, and preserve units in `current()`. Leave `pre_integral()` and `post_integral()` as inherited no-ops unless the equations require an ordering-specific operation.
135
+
136
+ Do not implement all Markov probabilities as independent States when they must sum to one. Choose one dependent state and test conservation after stepping.
137
+
138
+ ## Choose the ion extension level
139
+
140
+ | Use | Need |
141
+ |---|---|
142
+ | `braincell.ion._base.FixedIon` or a matching concrete ion base | Use for a custom ion with fixed `Ci`, `Co`, `E`, and `valence`. Preserve the ion/channel ownership contract. |
143
+ | `braincell.ion._base.InitNernstIon` | Use when concentrations stay fixed but initialization and reset must compute `E` from concentrations, valence, and temperature. |
144
+ | `braincell.ion._base.DynamicNernstIon` | Use when intracellular concentration is dynamic. Define its initializer, `derivative(Ci, V, total_current=...)`, and whether the total owned current is required. |
145
+ | `register_ion` | Use when `mech.Ion(...)` must resolve the custom ion by name. Register a unique name when the defining module is imported. |
146
+
147
+ `braincell.ion._base` is a lower-level authoring module. Inspect the installed version before relying on it across releases.
148
+
149
+ ## Author a custom ion only when required
150
+
151
+ Use a custom ion when the missing behavior belongs to reversal potential or concentration dynamics, not when only the current equation is new.
152
+
153
+ 1. Choose `FixedIon`, `InitNernstIon`, or `DynamicNernstIon` from the concentration behavior.
154
+ 2. Define `Ci`, `Co`, `E`, `valence`, temperature, and initialization with BrainUnit quantities.
155
+ 3. For a dynamic ion, implement `derivative(Ci, V, total_current=...)` and declare whether the total current of owned channels is required.
156
+ 4. Package ion state through the inherited `IonInfo` path; do not pass the ion object directly into channels.
157
+ 5. Register the concrete class only when string-based `mech.Ion(...)` declarations need it.
158
+
159
+ This custom calcium pool uses the owned channel current for influx and a saturating removal pump:
160
+
161
+ ```python
162
+ import braincell
163
+ import braintools
164
+ import brainunit as u
165
+ import jax.numpy as jnp
166
+ from braincell.ion import Calcium
167
+ from braincell.ion._base import DynamicNernstIon
168
+
169
+ DEFAULT_TEMP = u.celsius2kelvin(36.0)
170
+
171
+
172
+ class DemoSaturatingCalcium(Calcium, DynamicNernstIon):
173
+ uses_total_current = True
174
+
175
+ def __init__(
176
+ self,
177
+ size,
178
+ temp=DEFAULT_TEMP,
179
+ depth=1.0 * u.um,
180
+ pump_max=1.0e-4 * u.mM / u.ms,
181
+ pump_half=1.0e-4 * u.mM,
182
+ Co=None,
183
+ Ci_initializer=2.4e-4 * u.mM,
184
+ ):
185
+ super().__init__(size=size)
186
+ self._init_dynamic_nernst_ion(
187
+ Co=Co,
188
+ temp=temp,
189
+ valence=None,
190
+ Ci_initializer=Ci_initializer,
191
+ )
192
+ self.depth = braintools.init.param(
193
+ depth, self.varshape, allow_none=False
194
+ )
195
+ self.pump_max = braintools.init.param(
196
+ pump_max, self.varshape, allow_none=False
197
+ )
198
+ self.pump_half = braintools.init.param(
199
+ pump_half, self.varshape, allow_none=False
200
+ )
201
+
202
+ def derivative(self, Ci, V, total_current=None):
203
+ _ = V
204
+ influx = total_current / (
205
+ self.valence * u.faraday_constant * self.depth
206
+ )
207
+ influx = u.math.maximum(influx, u.math.zeros_like(influx))
208
+ pump = self.pump_max * Ci / (Ci + self.pump_half)
209
+ return influx - pump
210
+
211
+
212
+ V = jnp.array([-65.0]) * u.mV
213
+ initial_Ci = 2.4e-4 * u.mM
214
+
215
+ calcium = DemoSaturatingCalcium(size=1, Ci_initializer=initial_Ci)
216
+ calcium.add(
217
+ ICaT=braincell.channel.CaT_HM1992(
218
+ size=1,
219
+ g_max=2.0 * u.mS / u.cm**2,
220
+ )
221
+ )
222
+ calcium.init_state(V)
223
+ calcium.compute_derivative(V)
224
+
225
+ total_current = calcium.current(V, include_external=True)
226
+ expected = calcium.derivative(
227
+ calcium.Ci.value,
228
+ V,
229
+ total_current=total_current,
230
+ )
231
+ assert u.math.allclose(
232
+ calcium.Ci.derivative.to_decimal(u.mM / u.ms),
233
+ expected.to_decimal(u.mM / u.ms),
234
+ )
235
+
236
+ E_before = calcium.E
237
+ calcium.Ci.value = jnp.array([1.0e-3]) * u.mM
238
+ assert not u.math.allclose(
239
+ E_before.to_decimal(u.mV),
240
+ calcium.E.to_decimal(u.mV),
241
+ )
242
+
243
+ calcium.reset_state(V)
244
+ assert u.math.allclose(
245
+ calcium.Ci.value.to_decimal(u.mM),
246
+ initial_Ci.to_decimal(u.mM),
247
+ )
248
+ ```
249
+
250
+ Use `CalciumFixed`, `CalciumInitNernst`, and `CalciumDetailed` as the three concrete source patterns. Do not author a custom ion merely to change a channel's `g_max`, gating kinetics, or current formula.
251
+
252
+ ## Validate the extension
253
+
254
+ Validate the mechanism at three levels:
255
+
256
+ | Level | Required checks |
257
+ |---|---|
258
+ | Formula | Compare steady state, time constants or transition rates, current sign, reversal behavior, and units against the governing equations. |
259
+ | Lifecycle | Exercise `init_state()`, `reset_state()`, derivative computation, one solver step, batching, and the expected `root_type` failure. |
260
+ | Model | Compare a voltage-clamp curve, analytic limit, published trace, or trusted simulator under matched parameters, temperature, units, `dt`, and solver. |
261
+
262
+ For an ohmic current written as `g * gates * (E - V)`, verify that current approaches zero at `V == E`. For an HH channel, perturb each gate away from steady state and verify that the derivative points back toward its expected equilibrium. For a Markov channel, verify non-negative probabilities and conservation.
263
+
264
+ Add a co-located test when the extension becomes repository code. Registration success alone does not validate kinetics.
265
+
266
+
267
+
268
+ ## Sources
269
+
270
+ - Ions & Channels: https://brainx.chaobrain.com/braincell/concepts/ions_channels.html
271
+ - Channels tutorial: https://brainx.chaobrain.com/braincell/tutorials/channel.html
272
+ - Ions tutorial: https://brainx.chaobrain.com/braincell/tutorials/ion.html
273
+ - Extending BrainCell: https://brainx.chaobrain.com/braincell/developer/extending.html