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
@@ -0,0 +1,260 @@
1
+ # Topology building and visualization
2
+
3
+ Use this reference after `references/multicompartment/multicompartment-cell-workflow.md` when branch topology, CV coverage, runtime nodes, selector placement, or spatial values must be visualized. Keep morphology construction and validation, selector design, CV-policy choice, probe behavior, and simulation in their owning references.
4
+
5
+ ## Choose the view
6
+
7
+ Morphology branches, CVs, and runtime nodes are different layers of one cell; visualize the layer that owns the question.
8
+
9
+ | API | Use when | Constraint |
10
+ |---|---|---|
11
+ | `morphology.topo()` | Check the named parent-child branch tree before discretization. | It does not show CVs or runtime nodes. |
12
+ | `morphology.select(expr)` | Confirm region intervals or locset points before plotting. | Use the filter reference when the selection itself is wrong. |
13
+ | `cell.vis_branch(...)` | Inspect compact branch topology or region coverage. | It supports regions, not locsets or values. |
14
+ | `cell.vis_cv(...)` | Inspect discretization, region coverage, locset ownership, or CV values. | Region/locset highlight mode is exclusive with value mode. |
15
+ | `cell.vis_node(...)` | Inspect the full runtime point graph, lowered placement, or point values. | Call `cell.init_state()` first. |
16
+ | `cell.vis_topology(level=...)` | Dispatch dynamically among `"branch"`, `"cv"`, and `"node"`. | Branch level rejects locset and value arguments. |
17
+ | `braincell.vis.plot2d()` / `plot3d()` | Inspect physical morphology geometry. | Use these instead of topology layouts when length, radius, or 3D position matters. |
18
+
19
+ The morphology defines continuous cable, the CV policy defines isopotential intervals, and `init_state()` lowers them into the execution-oriented `NodeTree`. Do not equate morphology points, branches, CVs, and runtime nodes.
20
+
21
+ ## Prepare the visualization context
22
+
23
+ Reuse the validated morphology, selectors, CV policy, and declarations from the multicompartment workflow. This minimal setup exists only to make the visualization snippets executable.
24
+
25
+ ```python
26
+ import braincell
27
+ import braincell.mech as mech
28
+ import brainunit as u
29
+ import matplotlib.pyplot as plt
30
+ from braincell.filter import AllRegion, RootLocation, Terminals, branch_in
31
+
32
+
33
+ morphology = braincell.Morphology.from_swc("neuron.swc")
34
+ target_region = branch_in(
35
+ "type",
36
+ ("dendrite", "basal_dendrite", "apical_dendrite"),
37
+ )
38
+ target_sites = RootLocation(0.5) | Terminals()
39
+
40
+ assert morphology.select(target_region).intervals
41
+ assert morphology.select(target_sites).points
42
+
43
+ cell = braincell.Cell(
44
+ morphology,
45
+ cv_policy=braincell.MaxCVLen(25.0 * u.um),
46
+ )
47
+ cell.paint(
48
+ AllRegion(),
49
+ mech.Channel(
50
+ "IL",
51
+ g_max=0.03 * u.mS / u.cm**2,
52
+ E=-65.0 * u.mV,
53
+ ),
54
+ )
55
+ cell.init_state()
56
+
57
+ assert cell.n_cv == len(cell.cvs)
58
+ assert len(cell.node_tree.edges) == len(cell.node_tree.nodes) - 1
59
+ ```
60
+
61
+ Access `cell.node_tree` and node value mode only after `init_state()`. Return to the morphology reference if initialization does not produce one connected rooted tree.
62
+
63
+ ## Compare structure and selector placement
64
+
65
+ Render one selection across structural levels, then show a locset at runtime level. This distinguishes a branch-selection error from CV coverage or point-lowering errors.
66
+
67
+ ```python
68
+ fig, axes = plt.subplots(2, 2, figsize=(10, 9), dpi=140)
69
+
70
+ cell.vis_branch(
71
+ region=target_region,
72
+ coverage_mode="fraction",
73
+ layout="dot",
74
+ ax=axes[0, 0],
75
+ show=False,
76
+ )
77
+ axes[0, 0].set_title("Branch region")
78
+
79
+ cell.vis_cv(
80
+ region=target_region,
81
+ coverage_mode="fraction",
82
+ layout="dot",
83
+ ax=axes[0, 1],
84
+ show=False,
85
+ )
86
+ axes[0, 1].set_title(f"CV region: n={cell.n_cv}")
87
+
88
+ cell.vis_node(
89
+ region=target_region,
90
+ coverage_mode="fraction",
91
+ layout="dot",
92
+ ax=axes[1, 0],
93
+ show=False,
94
+ )
95
+ axes[1, 0].set_title("Runtime region")
96
+
97
+ cell.vis_node(
98
+ locset=target_sites,
99
+ highlight_color="#f97316",
100
+ layout="dot",
101
+ ax=axes[1, 1],
102
+ show=False,
103
+ )
104
+ axes[1, 1].set_title("Runtime locset")
105
+
106
+ fig.tight_layout()
107
+ plt.show()
108
+ ```
109
+
110
+ Use `coverage_mode="fraction"` to blend by overlap, `"any"` to fully highlight any overlap, and `"all"` to highlight only complete coverage. Node-level regions and locsets map to owning CV midpoint points; they do not render literal morphology coordinates.
111
+
112
+ ## Compare layouts
113
+
114
+ Hold the initialized cell and data fixed while choosing the layout that makes topology easiest to inspect.
115
+
116
+ ```python
117
+ fig, axes = plt.subplots(1, 3, figsize=(13, 4), dpi=140)
118
+
119
+ cell.vis_node(
120
+ preset="dendrotweaks",
121
+ ax=axes[0],
122
+ show=False,
123
+ )
124
+ axes[0].set_title("dendrotweaks")
125
+
126
+ cell.vis_node(
127
+ layout="dot",
128
+ ax=axes[1],
129
+ show=False,
130
+ )
131
+ axes[1].set_title("dot")
132
+
133
+ cell.vis_node(
134
+ layout="kamada_kawai",
135
+ layout_scale=1.5,
136
+ ax=axes[2],
137
+ show=False,
138
+ )
139
+ axes[2].set_title("kamada_kawai")
140
+
141
+ fig.tight_layout()
142
+ plt.show()
143
+ ```
144
+
145
+ Available presets are `"dendrotweaks"`, `"mono"`, and `"depth"`; documented layouts are `"twopi"`, `"dot"`, `"neato"`, and `"kamada_kawai"`. `layout_scale` changes global spacing without changing topology.
146
+
147
+ The default topology preset ignores physical length and radius. Do not interpret graph spacing as cable distance; route physical geometry inspection to the morphology reference.
148
+
149
+ ## Color runtime and mechanism values
150
+
151
+ Use value mode on an initialized or already simulated cell. Named selectors avoid manually extracting and aligning runtime arrays.
152
+
153
+ ```python
154
+ fig, axes = plt.subplots(1, 2, figsize=(10, 4), dpi=140)
155
+
156
+ cell.vis_node(
157
+ value="V",
158
+ cmap="viridis",
159
+ vmin=-80.0,
160
+ vmax=-40.0,
161
+ value_label="Voltage",
162
+ ax=axes[0],
163
+ show=False,
164
+ )
165
+ axes[0].set_title("Membrane voltage")
166
+
167
+ cell.vis_node(
168
+ value=("channel", "IL", "g_max"),
169
+ cmap="magma",
170
+ value_label="IL g_max",
171
+ ax=axes[1],
172
+ show=False,
173
+ )
174
+ axes[1].set_title("Leak conductance")
175
+
176
+ fig.tight_layout()
177
+ plt.show()
178
+ ```
179
+
180
+ Keep `vmin`, `vmax`, and `cmap` fixed when comparing cells or time points. Run the cell through the parent workflow first when the figure must show post-stimulus rather than initialized State.
181
+
182
+ ## Color a custom node metric
183
+
184
+ Pass one scalar per runtime point when the built-in value selectors do not own the diagnostic quantity. This example maps graph depth from the runtime root.
185
+
186
+ ```python
187
+ from collections import deque
188
+
189
+ import numpy as np
190
+
191
+
192
+ def node_depths(tree):
193
+ depths = np.full(len(tree.nodes), np.nan)
194
+ depths[tree.root_node_id] = 0.0
195
+ children = {node.id: [] for node in tree.nodes}
196
+
197
+ for edge in tree.edges:
198
+ children[edge.parent_node_id].append(edge.child_node_id)
199
+
200
+ queue = deque([tree.root_node_id])
201
+ while queue:
202
+ parent = queue.popleft()
203
+ for child in children[parent]:
204
+ depths[child] = depths[parent] + 1.0
205
+ queue.append(child)
206
+
207
+ return depths
208
+
209
+
210
+ depth = node_depths(cell.node_tree)
211
+ assert depth.shape == (len(cell.node_tree.nodes),)
212
+ assert not np.isnan(depth).any()
213
+
214
+ fig, ax = plt.subplots(figsize=(7, 7), dpi=140)
215
+ cell.vis_node(
216
+ value=depth,
217
+ cmap="magma",
218
+ value_label="Runtime graph depth",
219
+ ax=ax,
220
+ show=False,
221
+ )
222
+ fig.tight_layout()
223
+ plt.show()
224
+ ```
225
+
226
+ A point-space array must have length `n_point`. A CV-space array must have length `n_cv`; `vis_node()` scatters it into point space. Other shapes raise `ValueError`.
227
+
228
+ ## Lookup
229
+
230
+ | Level | Region | Locset | Value | Best use |
231
+ |---|---|---|---|---|
232
+ | `"branch"` | Yes | No | No | Compact branch topology and region coverage. |
233
+ | `"cv"` | Yes | Yes | Yes | Discretization, owning-CV placement, and compartment values. |
234
+ | `"node"` | Yes | Yes | Yes | Full runtime topology, lowered placement, and point values. |
235
+
236
+ | `value` form | Result |
237
+ |---|---|
238
+ | Point array of length `n_point` | Color runtime nodes directly. |
239
+ | CV array of length `n_cv` | Scatter CV values into point space. |
240
+ | `"V"` or `"voltage"` | Color membrane voltage. |
241
+ | `("ion", ion_name, field)` | Color one ion field. |
242
+ | `("channel", class_name, field)` | Color one channel field. |
243
+ | `("layout_id", layout_id, field)` | Color one resolved layout field. |
244
+
245
+ | Control | Use |
246
+ |---|---|
247
+ | `highlight_color` / `coverage_mode` | Style region or locset highlights. |
248
+ | `cmap`, `vmin`, `vmax`, `norm` | Control value normalization. |
249
+ | `value_label`, `show_colorbar` | Control the colorbar. |
250
+ | `node_color`, `edge_color`, `root_color` | Style topology without entering value mode. |
251
+ | `ax=...`, `show=False` | Compose subplots; call `plt.show()` or `fig.savefig(...)` once afterward. |
252
+
253
+ Highlight mode and value mode are mutually exclusive. Fix selectors in `filter-function-library.md`, discretization in `cv-policy-reference.md`, morphology geometry in the IO or manual-construction reference, and recorded-trace mismatches in `probe-reference.md`.
254
+
255
+ ## Sources
256
+
257
+ - [Point tree visualization](https://brainx.chaobrain.com/braincell/tutorials/vis.html)
258
+ - [Region and locset filters](https://brainx.chaobrain.com/braincell/tutorials/filter.html)
259
+ - [Morphology](https://brainx.chaobrain.com/braincell/concepts/morphology.html)
260
+ - [Cell API](https://brainx.chaobrain.com/braincell/apis/generated/braincell.Cell.html)
@@ -0,0 +1,66 @@
1
+ """
2
+ Reference script mirrored from:
3
+ https://brainx.chaobrain.com/braincell/examples/calcium_channel_gating.html
4
+
5
+ Purpose:
6
+ Channel gating diagnostic script. Use when the task asks for voltage-dependent activation/inactivation curves, low-threshold vs high-threshold calcium channel comparison, steady-state gating, or direct channel methods such as `f_p_inf` / `f_q_inf`.
7
+
8
+ Use this when:
9
+ - The task asks for calcium channel gating curves or steady-state activation/inactivation.
10
+ - The agent needs direct channel-method inspection rather than membrane-potential simulation.
11
+
12
+ Do not use this when:
13
+ - The task needs the default current-clamp simulation pattern for membrane traces.
14
+ """
15
+
16
+ import braintools
17
+ import brainunit as u
18
+ import matplotlib.pyplot as plt
19
+ import braincell
20
+
21
+
22
+ # Channel-level diagnostic: instantiate channel classes directly, no cell update loop.
23
+ # Create Low-Threshold T-Type Calcium Channel (ICaT)
24
+ cat = braincell.channel.CaT_HP1992(1)
25
+
26
+ # Create High-Threshold Calcium Channel (ICaHT)
27
+ caht = braincell.channel.CaHT_HM1992(1)
28
+
29
+ # Generate Voltage Sequence
30
+ vs = u.math.arange(-100 * u.mV, 0 * u.mV, 0.1 * u.mV)
31
+
32
+ # These channels' steady-state gates depend only on voltage, but the API
33
+ # requires a calcium IonInfo argument; supply a resting calcium state.
34
+ ca = braincell.IonInfo(Ci=5e-5 * u.mM, Co=2. * u.mM, E=120. * u.mV, valence=2)
35
+
36
+ # Create Figure and Subplot Layout
37
+ fig, gs = braintools.visualize.get_figure(1, 2, 3., 4.5)
38
+
39
+ # Compute steady-state values of activation and inactivation gates for low-threshold channel
40
+ q_inf = cat.f_q_inf(vs, ca)
41
+ p_inf = cat.f_p_inf(vs, ca)
42
+
43
+ # Add subplot 1
44
+ fig.add_subplot(gs[0, 0])
45
+ plt.plot(vs / u.mV, q_inf, label='q_inf (activation gate)') # Convert x-axis to mV for readability
46
+ plt.plot(vs / u.mV, p_inf, label='p_inf (inactivation gate)')
47
+ plt.legend() # Show legend
48
+ plt.fill_between([-80, -60], 1., alpha=0.2) # Highlight typical activation range for low-threshold channel
49
+ plt.title('Low-Threshold Calcium Channel (ICaT)')
50
+ plt.xlabel('Membrane Potential (mV)')
51
+
52
+ # Compute q_inf and p_inf for high-threshold channel
53
+ q_inf = caht.f_q_inf(vs, ca)
54
+ p_inf = caht.f_p_inf(vs, ca)
55
+
56
+ # Add subplot 2
57
+ fig.add_subplot(gs[0, 1])
58
+ plt.plot(vs / u.mV, q_inf, label='q_inf (activation gate)')
59
+ plt.plot(vs / u.mV, p_inf, label='p_inf (inactivation gate)')
60
+ plt.fill_between([-60, -40], 1., alpha=0.2) # Highlight typical activation range for high-threshold channel
61
+ plt.legend()
62
+ plt.xlabel('Membrane Potential (mV)')
63
+ plt.title('High-Threshold Calcium Channel (ICaHT)')
64
+
65
+ # Display figure
66
+ plt.show()
@@ -0,0 +1,221 @@
1
+ """
2
+ This script is mirrored and reorganized from:
3
+ https://brainx.chaobrain.com/braincell/tutorials/cell.html
4
+
5
+ It is the primary full-script reference for BrainCell multicompartment modeling.
6
+ All BrainCell reference scripts live in this directory.
7
+ """
8
+
9
+ # 1. Imports and CPU/JAX setup.
10
+ # Set the platform before importing JAX-backed BrainCell/BrainState packages.
11
+ import os
12
+
13
+ os.environ.setdefault("JAX_PLATFORMS", "cpu")
14
+
15
+ import braincell
16
+ import brainstate
17
+ import brainunit as u
18
+ import matplotlib.pyplot as plt
19
+
20
+ from braincell import Cell, Morphology
21
+ from braincell import CVPerBranch, MaxCVLen
22
+ from braincell.filter import BranchSlice, RootLocation, at
23
+ from braincell.mech import CableProperty, Channel, CurrentClamp, StateProbe
24
+
25
+
26
+ # 2. Load morphology from SWC.
27
+ # Canonical tutorial path. Adjust this path only if your repository layout differs.
28
+ MORPHOLOGY_PATH = "../../data/morphology/example_tree.swc"
29
+ morpho = Morphology.from_swc(MORPHOLOGY_PATH)
30
+
31
+ print("Morphology topology:")
32
+ print(morpho.topo())
33
+
34
+
35
+ # 3. Build Cell(morpho) and inspect Cell summary fields.
36
+ cell = Cell(morpho)
37
+ print("\nDefault Cell summary:")
38
+ print(cell)
39
+
40
+
41
+ # 4. Inspect cell.cvs.
42
+ # A CV is the discretized compartment interval that BrainCell solves over.
43
+ print("\nCV collection:")
44
+ print("n_cv:", cell.n_cv)
45
+ print("len(cell.cvs):", len(cell.cvs))
46
+ print("first three CV intervals:")
47
+ for cv in cell.cvs[:3]:
48
+ print(
49
+ f" CV {cv.id}: branch_id={cv.branch_id}, "
50
+ f"branch_type={cv.branch_type}, prox={cv.prox}, dist={cv.dist}"
51
+ )
52
+
53
+
54
+ # 5. Print important CV attributes.
55
+ # CVs carry topology, geometry, cable properties, and mechanism containers.
56
+ cv0 = cell.cvs[0]
57
+ print("\nFirst CV detail:")
58
+ print(cv0)
59
+
60
+ print("id:", cv0.id)
61
+ print("branch_id:", cv0.branch_id)
62
+ print("branch_type:", cv0.branch_type)
63
+ print("parent_cv:", cv0.parent_cv)
64
+ print("children_cv:", cv0.children_cv)
65
+
66
+ print("length:", cv0.length)
67
+ print("area:", cv0.area)
68
+ print("r_axial:", cv0.r_axial)
69
+
70
+ print("cm:", cv0.cm)
71
+ print("ra:", cv0.ra)
72
+ print("v:", cv0.v)
73
+ print("temp:", cv0.temp)
74
+
75
+ print("density_mech:", cv0.density_mech)
76
+ print("point_mech:", cv0.point_mech)
77
+
78
+
79
+ # 6. Compare CV policies.
80
+ default_cell = Cell(morpho)
81
+ split_cell = Cell(morpho, cv_policy=CVPerBranch(cv_per_branch=2))
82
+ auto_cell = Cell(morpho, cv_policy=MaxCVLen(max_cv_len=20.0 * u.um))
83
+
84
+ print("\nCV policy comparison:")
85
+ print("default policy")
86
+ print(default_cell)
87
+ print()
88
+ print("CVPerBranch(cv_per_branch=2)")
89
+ print(split_cell)
90
+ print()
91
+ print("MaxCVLen(max_cv_len=20 um)")
92
+ print(auto_cell)
93
+ print()
94
+ print("first four CV intervals under CVPerBranch(cv_per_branch=2):")
95
+ for cv in split_cell.cvs[:4]:
96
+ print(f" CV {cv.id}: branch_id={cv.branch_id}, prox={cv.prox}, dist={cv.dist}")
97
+
98
+
99
+ # 7. Initialize state and inspect the node tree.
100
+ # init_state() builds runtime structures such as node_tree from the CV layout.
101
+ split_cell.init_state()
102
+ node_tree = split_cell.node_tree
103
+ print("\nNode tree after init_state():")
104
+ print(node_tree)
105
+ print("n_nodes:", len(node_tree.nodes))
106
+ print("n_edges:", len(node_tree.edges))
107
+ print(
108
+ "expected n_nodes = n_cv + n_branches + 1:",
109
+ split_cell.n_cv + len(split_cell.morpho.branches) + 1,
110
+ )
111
+
112
+
113
+ # 8. paint(...): cable properties.
114
+ # paint(region, CableProperty(...)) assigns passive cable values over CV midpoints.
115
+ cable_cell = Cell(morpho, cv_policy=CVPerBranch(cv_per_branch=2))
116
+ cable_cell.paint(
117
+ BranchSlice(branch_index=0, prox=0.0, dist=1.0),
118
+ CableProperty(
119
+ resting_potential=-70.0 * u.mV,
120
+ membrane_capacitance=2.0 * (u.uF / u.cm ** 2),
121
+ axial_resistivity=200.0 * (u.ohm * u.cm),
122
+ temperature=u.celsius2kelvin(20.0),
123
+ ),
124
+ )
125
+
126
+ print("\nCable-property paint result:")
127
+ print(cable_cell)
128
+ print("painted soma CV example:")
129
+ print("v:", cable_cell.cvs[0].v)
130
+ print("cm:", cable_cell.cvs[0].cm)
131
+ print("ra:", cable_cell.cvs[0].ra)
132
+ print("temp:", cable_cell.cvs[0].temp)
133
+
134
+
135
+ # 9. paint(...): density mechanisms.
136
+ # Channel("IL", ...) is declarative; init_state() lowers it into runtime layouts.
137
+ channel_cell = Cell(morpho)
138
+ channel_cell.paint(
139
+ BranchSlice(branch_index=[0, 1], prox=0.0, dist=1.0),
140
+ Channel("IL", g_max=4.0 * (u.mS / u.cm ** 2), E=-68.0 * u.mV),
141
+ )
142
+
143
+ channel_cell.init_state()
144
+ layout = channel_cell.layouts[0]
145
+ point_id = int(layout.point_index[0])
146
+
147
+ print("\nDensity mechanism layout:")
148
+ print("layout.kind:", layout.kind)
149
+ print("layout.target:", layout.target)
150
+ print("layout.n_active:", layout.n_active)
151
+ print("layout.source_cv_ids:", layout.source_cv_ids)
152
+ print("layout.point_index:", layout.point_index.tolist())
153
+ print("sample g_max at one active point:", channel_cell.get_point_state(point_id)[layout.id]["g_max"])
154
+ print("sample E at one active point:", channel_cell.get_point_state(point_id)[layout.id]["E"])
155
+
156
+
157
+ # 10. place(...): point mechanisms.
158
+ # place(locset, mechanism) attaches point mechanisms such as clamps and probes.
159
+ place_cell = Cell(morpho, cv_policy=CVPerBranch(2))
160
+ place_cell.place(
161
+ RootLocation(x=0.5),
162
+ CurrentClamp(delay=1.0 * u.ms, durations=2.0 * u.ms, amplitudes=0.1 * u.nA),
163
+ )
164
+
165
+ place_cell.init_state()
166
+ layout = place_cell.layouts[0]
167
+
168
+ print("\nPoint mechanism layout:")
169
+ print(place_cell)
170
+ print("layout.kind:", layout.kind)
171
+ print("layout.target:", layout.target)
172
+ print("layout.n_active:", layout.n_active)
173
+ print("layout.point_index:", layout.point_index.tolist())
174
+ print("amplitudes:", place_cell.get_state(layout.id, "amplitudes"))
175
+ print("durations:", place_cell.get_state(layout.id, "durations"))
176
+ print("start:", place_cell.get_state(layout.id, "start"))
177
+
178
+
179
+ # 11. Minimal runnable multicompartment simulation.
180
+ # This is the canonical Cell(morpho) simulation shape: choose CV policy and solver,
181
+ # paint density mechanisms, place point mechanisms/probes, initialize, reset, run.
182
+ sim_cell = Cell(
183
+ morpho,
184
+ cv_policy=CVPerBranch(cv_per_branch=2),
185
+ solver="staggered",
186
+ )
187
+
188
+ sim_cell.paint(
189
+ BranchSlice(branch_index=[0, 1], prox=0.0, dist=1.0),
190
+ Channel("IL", g_max=0.03 * (u.mS / u.cm ** 2), E=-54.387 * u.mV),
191
+ Channel("Na_HH1952", g_max=120.0 * (u.mS / u.cm ** 2)),
192
+ Channel("K_HH1952", g_max=36.0 * (u.mS / u.cm ** 2)),
193
+ )
194
+
195
+ sim_cell.place(
196
+ RootLocation(x=0.5),
197
+ CurrentClamp(delay=20.0 * u.ms, durations=60.0 * u.ms, amplitudes=0.2 * u.nA),
198
+ )
199
+
200
+ sim_cell.place(
201
+ at("soma", 0.5),
202
+ StateProbe(),
203
+ )
204
+
205
+ sim_cell.init_state()
206
+ sim_cell.reset_state()
207
+
208
+ dt = 0.1 * u.ms
209
+ duration = 100.0 * u.ms
210
+ result = sim_cell.run(dt=dt, duration=duration)
211
+
212
+ times_ms = u.math.concatenate([result.time])
213
+ soma_v_mV = u.math.concatenate([result.traces["soma(0.5)_v"]])
214
+
215
+ plt.figure(figsize=(6, 4))
216
+ plt.plot(times_ms, soma_v_mV, label="soma(0.5)_v")
217
+ plt.xlabel("Time (ms)")
218
+ plt.ylabel("Voltage (mV)")
219
+ plt.legend()
220
+ plt.tight_layout()
221
+ plt.show()
@@ -0,0 +1,61 @@
1
+ """
2
+ Reference script mirrored from:
3
+ https://brainx.chaobrain.com/braincell/examples/channel_ablation.html
4
+
5
+ Purpose:
6
+ Canonical ablation script. Use when the task asks to remove, suppress, or compare a channel/current contribution, especially by setting conductance such as `gK=0` while keeping the ion/channel structure intact.
7
+
8
+ Use this when:
9
+ - The task asks for intact-vs-ablated point-neuron comparisons.
10
+ - The agent needs to suppress a current by changing `g_max` while preserving the ion/channel structure.
11
+
12
+ Do not use this when:
13
+ - The task asks for custom channel authoring or morphology-based mechanism removal.
14
+ """
15
+
16
+ import brainstate
17
+ import brainunit as u
18
+ import matplotlib.pyplot as plt
19
+ import braincell
20
+
21
+
22
+ class HH(braincell.SingleCompartment):
23
+ def __init__(self, size, gK=36. * (u.mS / u.cm ** 2), solver='exp_euler'):
24
+ super().__init__(size, V_th=20. * u.mV, solver=solver)
25
+ self.na = braincell.ion.SodiumFixed(size, E=50. * u.mV)
26
+ self.na.add(INa=braincell.channel.Na_HH1952(size))
27
+ self.k = braincell.ion.PotassiumFixed(size, E=-77. * u.mV)
28
+ # Ablation is controlled by `gK`; the potassium ion/channel path remains present.
29
+ self.k.add(IK=braincell.channel.K_HH1952(size, g_max=gK))
30
+ self.IL = braincell.channel.IL(size, E=-54.387 * u.mV,
31
+ g_max=0.03 * (u.mS / u.cm ** 2))
32
+
33
+
34
+ intact = HH(1)
35
+ ablated = HH(1, gK=0. * (u.mS / u.cm ** 2))
36
+ intact.init_state()
37
+ ablated.init_state()
38
+
39
+ I = 5. * u.uA / u.cm ** 2
40
+
41
+
42
+ def step(t):
43
+ with brainstate.environ.context(t=t):
44
+ intact.update(I)
45
+ ablated.update(I)
46
+ return intact.V.value, ablated.V.value
47
+
48
+
49
+ with brainstate.environ.context(dt=0.01 * u.ms):
50
+ times = u.math.arange(0. * u.ms, 80. * u.ms, brainstate.environ.get_dt())
51
+ v_intact, v_ablated = brainstate.transform.for_loop(step, times)
52
+
53
+ plt.figure(figsize=(8, 3))
54
+ plt.plot(times / u.ms, u.math.squeeze(v_intact) / u.mV, label='intact')
55
+ plt.plot(times / u.ms, u.math.squeeze(v_ablated) / u.mV, label='no $I_K$', linestyle='--')
56
+ plt.xlabel('Time (ms)')
57
+ plt.ylabel('Membrane potential (mV)')
58
+ plt.title('Effect of ablating the potassium current')
59
+ plt.legend()
60
+ plt.tight_layout()
61
+ plt.show()
@@ -0,0 +1,68 @@
1
+ """
2
+ Reference script mirrored from:
3
+ https://brainx.chaobrain.com/braincell/examples/fi_curve.html
4
+
5
+ Purpose:
6
+ Canonical vectorized current-sweep script. Use when the task asks for FI curves, current sweeps, firing-rate extraction, warm-up discard, or using `size=N` as independent point neurons.
7
+
8
+ Use this when:
9
+ - The task asks for FI curves, current sweeps, spike counts, or firing-rate extraction.
10
+ - The agent needs a vectorized `SingleCompartment` pattern where `size=N` means independent point neurons.
11
+
12
+ Do not use this when:
13
+ - The task asks for morphology, network connectivity, or one detailed single-cell trace only.
14
+ """
15
+
16
+ import brainstate
17
+ import brainunit as u
18
+ import numpy as np
19
+ import matplotlib.pyplot as plt
20
+ import braincell
21
+
22
+
23
+ class HH(braincell.SingleCompartment):
24
+ def __init__(self, size, solver='exp_euler'):
25
+ super().__init__(size, V_th=20. * u.mV, solver=solver)
26
+ self.na = braincell.ion.SodiumFixed(size, E=50. * u.mV)
27
+ self.na.add(INa=braincell.channel.Na_HH1952(size))
28
+ self.k = braincell.ion.PotassiumFixed(size, E=-77. * u.mV)
29
+ self.k.add(IK=braincell.channel.K_HH1952(size))
30
+ self.IL = braincell.channel.IL(size, E=-54.387 * u.mV,
31
+ g_max=0.03 * (u.mS / u.cm ** 2))
32
+
33
+
34
+ n_levels = 11
35
+ amplitudes = np.linspace(0., 20., n_levels) # uA/cm^2
36
+ I = amplitudes * (u.uA / u.cm ** 2)
37
+
38
+ # `HH(n_levels)` creates independent point neurons, not compartments.
39
+ net = HH(n_levels)
40
+ net.init_state()
41
+
42
+ warmup = 100. * u.ms
43
+ total = 600. * u.ms
44
+
45
+
46
+ def step(t):
47
+ with brainstate.environ.context(t=t):
48
+ net.update(I)
49
+ return t, net.spike.value
50
+
51
+
52
+ with brainstate.environ.context(dt=0.01 * u.ms):
53
+ times = u.math.arange(0. * u.ms, total, brainstate.environ.get_dt())
54
+ ts, spikes = brainstate.transform.for_loop(step, times)
55
+
56
+ # Discard warm-up before converting spike counts to firing rate.
57
+ mask = (ts >= warmup)
58
+ counts = np.asarray(u.math.sum(spikes[mask], axis=0))
59
+ rate = counts / float((total - warmup) / u.second) # Hz
60
+ print('spike counts:', counts.astype(int).tolist())
61
+
62
+ plt.figure(figsize=(5, 4))
63
+ plt.plot(amplitudes, rate, 'o-')
64
+ plt.xlabel('Input current density (uA/cm$^2$)')
65
+ plt.ylabel('Firing rate (Hz)')
66
+ plt.title('F\u2013I curve of an HH neuron')
67
+ plt.tight_layout()
68
+ plt.show()