brainx-skill 1.0.3 → 1.0.8

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 (117) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +29 -64
  3. package/adapters/gemini.js +7 -0
  4. package/adapters/opencode.js +7 -0
  5. package/adapters/windsurf.js +7 -0
  6. package/{lib → installation/lib}/installer.js +8 -5
  7. package/manifest.json +7 -1
  8. package/package.json +25 -10
  9. package/skills/braincell/SKILL.md +182 -0
  10. package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
  11. package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +210 -0
  12. package/skills/braincell/references/channel-library.md +170 -0
  13. package/skills/braincell/references/ion-library.md +154 -0
  14. package/skills/braincell/references/mixions-for-adaptation.md +81 -0
  15. package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
  16. package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
  17. package/skills/braincell/references/multicompartment/filter-function-library.md +162 -0
  18. package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
  19. package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
  20. package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
  21. package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +121 -0
  22. package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
  23. package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
  24. package/skills/braincell/references/scripts/channel_ablation.py +61 -0
  25. package/skills/braincell/references/scripts/fi_curve.py +68 -0
  26. package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
  27. package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
  28. package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
  29. package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
  30. package/skills/braincell/references/solver-library-with-effects.md +188 -0
  31. package/skills/brainevent/SKILL.md +268 -0
  32. package/skills/brainevent/references/connectivity-variants.md +312 -0
  33. package/skills/brainevent/references/custom-operators-cpu.md +304 -0
  34. package/skills/brainevent/references/custom-operators-gpu.md +468 -0
  35. package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
  36. package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
  37. package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
  38. package/skills/brainevent/references/sparse-formats.md +182 -0
  39. package/skills/brainevent/references/synaptic-plasticity.md +285 -0
  40. package/skills/brainpy-state/SKILL.md +232 -0
  41. package/skills/brainpy-state/references/array-creation.md +158 -0
  42. package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
  43. package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
  44. package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
  45. package/skills/brainpy-state/references/braintools/metric.md +152 -0
  46. package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
  47. package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
  48. package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
  49. package/skills/brainpy-state/references/component-selection.md +273 -0
  50. package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
  51. package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
  52. package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
  53. package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
  54. package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
  55. package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
  56. package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
  57. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
  58. package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
  59. package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
  60. package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
  61. package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
  62. package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
  63. package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
  64. package/skills/brainpy-state/references/projection-patterns.md +125 -0
  65. package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
  66. package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
  67. package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
  68. package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
  69. package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
  70. package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
  71. package/skills/brainstate/SKILL.md +399 -0
  72. package/skills/brainstate/agents/openai.yaml +4 -0
  73. package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +334 -0
  74. package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +180 -0
  75. package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +213 -0
  76. package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
  77. package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +131 -0
  78. package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +462 -0
  79. package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +167 -0
  80. package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +314 -0
  81. package/skills/brainstate/references/collective_model_operations.md +195 -0
  82. package/skills/brainstate/references/extension_mechanisms.md +293 -0
  83. package/skills/brainstate/references/libraries/prebuilt-activation-library.md +115 -0
  84. package/skills/brainstate/references/libraries/prebuilt-layer-library.md +143 -0
  85. package/skills/brainstate/references/model-interop-and-migration.md +305 -0
  86. package/skills/brainstate/references/simulation-environment.md +117 -0
  87. package/skills/brainstate/references/size-inference-variations.md +279 -0
  88. package/skills/brainstate/references/state-graph-operations.md +216 -0
  89. package/skills/brainstate/references/state_collections_and_utilities.md +235 -0
  90. package/skills/brainstate/scripts/integrator_rnn.py +359 -0
  91. package/skills/brainstate/scripts/lif_neuron_model.py +52 -0
  92. package/skills/brainstate/scripts/modern_cnn.py +73 -0
  93. package/skills/brainstate/scripts/resnet.py +130 -0
  94. package/skills/brainunit/SKILL.md +287 -0
  95. package/skills/brainunit/references/array-creation.md +158 -0
  96. package/skills/brainunit/references/array-mechanics/functional-structural-api.md +90 -0
  97. package/skills/brainunit/references/array-mechanics.md +165 -0
  98. package/skills/brainunit/references/math-function-library.md +433 -0
  99. package/skills/brainunit/references/physical-constant-library.md +58 -0
  100. package/skills/brainunit/references/prefix-library.md +116 -0
  101. package/skills/brainunit/references/quantity-inspection-and-conversion.md +104 -0
  102. package/skills/brainunit/references/typing-and-runtime-validation.md +203 -0
  103. package/skills/brainunit/references/unit-structure-and-definition.md +140 -0
  104. package/skills/brainx-general-guard/SKILL.md +153 -0
  105. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/advanced-randomness.md +303 -0
  106. package/skills/brainx-general-guard/references/brainstate-randomness-reproducibility/randomness-and-reproducibility.md +62 -0
  107. package/skills/brainx-install/SKILL.md +2 -2
  108. package/skills/brainx-install/references/compatibility-and-release-matching.md +3 -3
  109. /package/{bin → installation/bin}/brainx.js +0 -0
  110. /package/{lib → installation/lib}/adapter-transaction.js +0 -0
  111. /package/{lib → installation/lib}/bundle.js +0 -0
  112. /package/{lib → installation/lib}/cli.js +0 -0
  113. /package/{lib → installation/lib}/constants.js +0 -0
  114. /package/{lib → installation/lib}/hash.js +0 -0
  115. /package/{lib → installation/lib}/paths.js +0 -0
  116. /package/{lib → installation/lib}/prompts.js +0 -0
  117. /package/{lib → installation/lib}/receipt.js +0 -0
@@ -0,0 +1,391 @@
1
+ # BrainCell multicompartment cell workflow
2
+
3
+ ## Purpose and boundary
4
+
5
+ Use this reference when a BrainCell simulation depends on geometry, axial current, regional biophysics, or location-specific stimulation and recording. Keep isopotential cells in `skills/braincell/SKILL.md` and cross-cell connections or training in `skills/brainpy-state/SKILL.md`; never model compartments with `SingleCompartment.size`.
6
+
7
+ ## Underlying principle of BrainCell multicompartment cells
8
+
9
+ `braincell.filter` expressions represent spatial targets. Regions select cable for `paint()`; locsets select points for `place()`.
10
+
11
+ `braincell.mech` declarations represent cellular biophysics and point processes. Paint cable properties, ions, and channels over regions; place clamps and probes at locsets.
12
+
13
+ ## Workflow map
14
+
15
+ ```text
16
+ ┌──────────────────────────────────────────────────────────────────┐
17
+ │ Declaration (what to model) │
18
+ │ • Morphology geometry: branches, radii, tree │
19
+ │ • mech.* channels, ions, clamps, synapses │
20
+ │ • filter.* regions and locsets (where) │
21
+ └──────────────────────────────────────────────────────────────────┘
22
+ │
23
+ paint / place
24
+ │
25
+ ▼
26
+ ┌──────────────────────────────────────────────────────────────────┐
27
+ │ Discretization (_cv) │
28
+ │ • CV one isopotential control volume │
29
+ │ • CVPolicy how many CVs each branch gets │
30
+ └──────────────────────────────────────────────────────────────────┘
31
+ │
32
+ build
33
+ │
34
+ ▼
35
+ ┌──────────────────────────────────────────────────────────────────┐
36
+ │ Runtime (_compute) │
37
+ │ • PointTree execution graph over CVs │
38
+ │ • CellRuntimeState frozen, JAX-friendly state │
39
+ └──────────────────────────────────────────────────────────────────┘
40
+ │
41
+ step
42
+ │
43
+ ▼
44
+ ┌──────────────────────────────────────────────────────────────────┐
45
+ │ Integration (quad) │
46
+ │ • DiffEqModule defines f(t, y) │
47
+ │ • solver advances y by dt │
48
+ └──────────────────────────────────────────────────────────────────┘
49
+ ```
50
+
51
+ ## Prepare and validate the morphology
52
+
53
+ `Morphology` is the continuous geometric source of truth, so validate it before selectors, discretization, or mechanisms inherit its mistakes.
54
+
55
+ | API | Description |
56
+ |---|---|
57
+ | `braincell.Morphology.from_swc(path, ...)` | Use for an SWC reconstruction; it maps structure identifiers to branch types and returns a `Morphology`. |
58
+ | `braincell.Morphology.from_asc(path, ...)` | Use for a Neurolucida ASC reconstruction; inspect its metadata and validation report before modeling. |
59
+ | `braincell.Morphology.from_neuromorpho(neuron_id, ...)` | Use for a NeuroMorpho.Org record; it downloads or reuses cached data and returns a `Morphology`. |
60
+ | `braincell.Morphology.from_swc(path, return_report=True)` | Use when parser findings or applied fixes must be reviewed; it returns `(morphology, report)`. |
61
+ | `braincell.io.SwcReadOptions(...)` | Use when SWC validation policy must change, including safe standardization, unknown-type handling, or root-soma requirements. |
62
+ | `morphology.topo()` | Use immediately after loading to inspect branch names, types, and parent-child structure before writing selectors. |
63
+
64
+ ```python
65
+ import braincell
66
+ from braincell.io import SwcReadOptions
67
+
68
+
69
+ options = SwcReadOptions(
70
+ standardize_safe_fixes=True,
71
+ unknown_type_as_custom=True,
72
+ require_root_type_soma=True,
73
+ )
74
+ morphology, report = braincell.Morphology.from_swc(
75
+ "neuron.swc",
76
+ options=options,
77
+ return_report=True,
78
+ )
79
+
80
+ print(report)
81
+ print(morphology.topo())
82
+ ```
83
+
84
+ A successful parse proves readability only; verify the root, connectivity, geometry, branch names, and anatomical types before writing selectors.
85
+
86
+ Open `references/multicompartment/morphology-io-loading-validation.md` for other loaders, validation, or checkpoints; open `references/multicompartment/braincell-manual-morphology-construction.md` for hand-built geometry.
87
+
88
+ ## Choose and inspect the CV policy
89
+
90
+ A CV policy chooses the State resolution of the cable model; morphology branches and source sample points do not determine the number of simulation compartments.
91
+
92
+ | API | Description |
93
+ |---|---|
94
+ | `braincell.Cell(morphology, cv_policy=None)` | Use only when the package default is acceptable; it currently uses `CVPerBranch()`, which is predictable but is not proof of spatial convergence. |
95
+ | `braincell.CVPerBranch(cv_per_branch=N)` | Use for controlled examples, tests, or a fixed resolution per branch; it gives every branch the same CV count regardless of physical or electrical length. |
96
+ | `braincell.MaxCVLen(max_cv_len=length)` | Use when no CV may exceed a physical length; long branches receive more CVs. |
97
+ | `braincell.DLambda(d_lambda=..., frequency=..., keep_odd=True)` | Use as the normal detailed-cable starting point; it refines electrically long cable using the AC length constant and requires uniform capacitance and axial resistivity within each branch. |
98
+ | `braincell.CVPolicyByTypeRule(...)` | Use when soma, dendrite, and axon require different rules. |
99
+ | `cell.n_cv` / `cell.cvs` | Use before initialization to inspect the resolved CV count and intervals; each CV exposes branch identity, normalized boundaries, geometry, topology, and cable properties. |
100
+
101
+ ```python
102
+ import braincell
103
+ import braincell.mech as mech
104
+ import brainunit as u
105
+ from braincell.filter import AllRegion
106
+
107
+
108
+ policy = braincell.DLambda(
109
+ d_lambda=0.1,
110
+ frequency=100.0 * u.Hz,
111
+ )
112
+ cell = braincell.Cell(
113
+ morphology,
114
+ cv_policy=policy,
115
+ solver="staggered",
116
+ )
117
+
118
+ # DLambda consumes capacitance and axial resistivity from paint rules.
119
+ cell.paint(
120
+ AllRegion(),
121
+ mech.CableProperty(
122
+ resting_potential=-65.0 * u.mV,
123
+ membrane_capacitance=1.0 * u.uF / u.cm**2,
124
+ axial_resistivity=100.0 * u.ohm * u.cm,
125
+ ),
126
+ )
127
+
128
+ # Inspect final CVs only after recording the intended cable properties.
129
+ print("n_cv:", cell.n_cv)
130
+ for cv in cell.cvs[:3]:
131
+ print(cv.id, cv.branch_id, cv.prox, cv.dist, cv.length, cv.area)
132
+ ```
133
+
134
+ Validate every policy by refining it and comparing the target observable. Resolve cable properties before `DLambda`; split capacitance or axial-resistivity changes at branch boundaries.
135
+
136
+ Open `references/multicompartment/cv-policy-reference.md` for by-type or composite policies, probe mapping, and convergence.
137
+
138
+ ## Declare distributed biophysics
139
+
140
+ Distributed declarations define the membrane and cable equations over regions; paint a complete passive baseline first, then add regional active mechanisms.
141
+
142
+ | API | Description |
143
+ |---|---|
144
+ | `braincell.filter.AllRegion()` | Use for passive cable values or density mechanisms that cover the entire morphology. |
145
+ | `braincell.filter.branch_in(property, value)` | Use to select branches by metadata such as `type="soma"`; it returns a region for `paint()`. |
146
+ | `braincell.filter.BranchSlice(...)` | Use to target a normalized interval of one or more branches when whole-type selection is too broad. |
147
+ | `braincell.mech.CableProperty(...)` | Use to declare resting potential, membrane-capacitance density, axial resistivity, and temperature over a region. |
148
+ | `braincell.mech.Ion(name_or_class, **parameters)` | Use when a density channel requires an explicit fixed, Nernst, or dynamic ion declaration or a named ion owner. |
149
+ | `braincell.mech.Channel(name_or_class, **parameters)` | Use to install a registered density channel with unit-aware conductance and channel parameters. |
150
+ | `cell.paint(region, *declarations)` | Use only in DECLARING; it records cable or density declarations over the selected cable and returns the cell for chaining. |
151
+
152
+ ```python
153
+ import braincell.mech as mech
154
+ import brainunit as u
155
+ from braincell.filter import AllRegion, branch_in
156
+
157
+
158
+ cell.paint(
159
+ AllRegion(),
160
+ mech.Channel(
161
+ "IL",
162
+ g_max=0.03 * u.mS / u.cm**2,
163
+ E=-54.387 * u.mV,
164
+ ),
165
+ )
166
+ cell.paint(
167
+ branch_in("type", "soma"),
168
+ mech.Channel("Na_HH1952", g_max=120.0 * u.mS / u.cm**2),
169
+ mech.Channel("K_HH1952", g_max=36.0 * u.mS / u.cm**2),
170
+ )
171
+ ```
172
+
173
+ BrainCell area-scales capacitance and conductance densities during lowering; keep axial resistivity in resistance-length units and all physical values as BrainUnit quantities. Paint an explicit global `CableProperty` baseline before regional overrides.
174
+
175
+ Open `references/multicompartment/filter-function-library.md` for composed or geometry-based regions, `references/ion-library.md` or `references/channel-library.md` for non-canonical mechanisms, and `references/mixions-for-adaptation.md` for calcium-dependent or multi-ion coupling.
176
+
177
+ ## Place stimuli and probes
178
+
179
+ Point declarations define where current enters and what the simulation exposes; use locsets for both and place at least one probe before `run()`.
180
+
181
+ | API | Description |
182
+ |---|---|
183
+ | `braincell.filter.RootLocation(x)` | Use for one point on the root branch; `x` is the normalized position from 0 to 1. |
184
+ | `braincell.filter.at(branch, position)` | Use for one named branch position; the branch argument identifies a branch, not an anatomical type. |
185
+ | `braincell.filter.Terminals()` | Use when a point declaration must resolve at every terminal tip. |
186
+ | `braincell.mech.CurrentClamp(...)` | Use for piecewise current injection; declare delay, durations, and amplitudes with time and current units. Currents from clamps at the same runtime point add. |
187
+ | `braincell.mech.StateProbe(field="v")` | Use to record cell-owned membrane voltage; `v` is the current multicompartment State field. |
188
+ | `braincell.mech.MechanismProbe(mechanism=..., field=...)` | Use to record a real runtime State field on a named channel or ion; do not request a static parameter or derived property. |
189
+ | `braincell.mech.CurrentProbe(...)` | Use to record one mechanism current or the total current owned by a named ion. |
190
+ | `cell.place(locset, *point_mechanisms)` | Use only in DECLARING; it records point declarations at every resolved location and returns the cell for chaining. |
191
+
192
+ ```python
193
+ from braincell.filter import RootLocation
194
+
195
+
196
+ soma_midpoint = RootLocation(x=0.5)
197
+ cell.place(
198
+ soma_midpoint,
199
+ mech.CurrentClamp(
200
+ delay=20.0 * u.ms,
201
+ durations=60.0 * u.ms,
202
+ amplitudes=0.2 * u.nA,
203
+ ),
204
+ )
205
+ cell.place(soma_midpoint, mech.StateProbe())
206
+ ```
207
+
208
+ A multi-point locset creates one probe per resolved point. Inspect `sample_probes()` for keys; assign unique names only when stable keys are required.
209
+
210
+ Open `references/multicompartment/filter-function-library.md` for composed locsets and `references/multicompartment/probe-reference.md` for probe selection or missing and ambiguous keys.
211
+
212
+ ## Initialize and inspect the lowered runtime
213
+
214
+ `init_state()` is the declaration-to-runtime boundary; call it explicitly when model-construction errors and target resolution must be checked before a long run.
215
+
216
+ | API | Description |
217
+ |---|---|
218
+ | `cell.init_state(batch_size=None)` | Use after every `paint()` and `place()` call; it lowers declarations, allocates evolving model State, materializes clamp and probe layouts, and raises if the cell is already initialized. |
219
+ | `cell.node_tree` | Use after initialization to inspect the point-and-edge execution topology derived from the CV tree. |
220
+ | `cell.layouts` | Use after initialization to inspect each lowered mechanism layout, including its kind, target, active count, source CVs, and runtime point indices. |
221
+ | `cell.sample_probe(name)` | Use after initialization to read the current value of one probe by its resolved name. |
222
+ | `cell.sample_probes()` | Use after initialization to read all current probe values and discover the exact probe-key surface. |
223
+
224
+ ```python
225
+ cell.init_state()
226
+
227
+ samples = cell.sample_probes()
228
+ print("probe keys:", sorted(samples))
229
+ print("runtime nodes:", len(cell.node_tree.nodes))
230
+ for layout in cell.layouts:
231
+ print(layout.kind, layout.target, layout.n_active)
232
+ ```
233
+
234
+ Inspect `cell.cvs` before initialization; inspect `cell.node_tree`, `cell.layouts`, and probes afterward. Runtime surfaces raise in DECLARING; call `reset()` before changing `paint()` or `place()` rules.
235
+
236
+ Open `references/multicompartment/topology-building-and-visualization.md` to visualize CV, branch, node, or placement topology; open `references/multicompartment/probe-reference.md` for sampling failures.
237
+
238
+ ## Run and interpret the result
239
+
240
+ `run()` advances the initialized cell from its current time and samples every placed probe at each step, so repeated calls continue the same simulation unless State is reset.
241
+
242
+ | API | Description |
243
+ |---|---|
244
+ | `cell.run(dt=..., duration=...)` | Use with positive time quantities to advance the cell; it calls `init_state()` only when still DECLARING and raises `ValueError` when no probe is placed. |
245
+ | `braincell.RunResult.time` | Use as the unit-aware `(n_steps,)` time axis spanning `[start_t, start_t + duration)`. |
246
+ | `braincell.RunResult.traces` | Use as the probe-name to trace mapping; every trace has the same leading time dimension as `RunResult.time`. |
247
+ | `cell.current_time` | Use after a run to inspect the endpoint from which the next `run()` call will continue. |
248
+ | `Quantity.to_decimal(unit)` | Use only at plotting, serialization, or external-library boundaries to obtain values in an explicit compatible unit. |
249
+
250
+ ```python
251
+ result = cell.run(
252
+ dt=0.05 * u.ms,
253
+ duration=100.0 * u.ms,
254
+ )
255
+
256
+ voltage_key = next(key for key in result.traces if key.endswith("_v"))
257
+ voltage = result.traces[voltage_key]
258
+
259
+ assert result.time.shape[0] == voltage.shape[0]
260
+ times_ms = result.time.to_decimal(u.ms)
261
+ voltage_mV = voltage.to_decimal(u.mV)
262
+ ```
263
+
264
+ Keep quantities unit-aware and convert only at external boundaries. Validate `dt` by comparing the target observable at `dt / 2`.
265
+
266
+ Open `references/solver-library-with-effects.md` for cable-solver choice or method-dependent traces.
267
+
268
+ ## Canonical end-to-end workflow
269
+
270
+ This current-clamp pattern uses an explicit passive baseline, `DLambda` with staggered integration, somatic active channels, runtime target checks, and one voltage probe.
271
+
272
+ ```python
273
+ import braincell
274
+ import braincell.mech as mech
275
+ import brainunit as u
276
+ from braincell.filter import AllRegion, RootLocation, branch_in
277
+ from braincell.io import SwcReadOptions
278
+
279
+
280
+ # 1. Load and validate continuous cable geometry.
281
+ options = SwcReadOptions(
282
+ standardize_safe_fixes=True,
283
+ unknown_type_as_custom=True,
284
+ require_root_type_soma=True,
285
+ )
286
+ morphology, report = braincell.Morphology.from_swc(
287
+ "neuron.swc",
288
+ options=options,
289
+ return_report=True,
290
+ )
291
+ print(report)
292
+ print(morphology.topo())
293
+
294
+ # 2. Choose spatial and temporal integration policies.
295
+ cell = braincell.Cell(
296
+ morphology,
297
+ cv_policy=braincell.DLambda(
298
+ d_lambda=0.1,
299
+ frequency=100.0 * u.Hz,
300
+ ),
301
+ solver="staggered",
302
+ )
303
+
304
+ # 3. Declare passive cable everywhere and active HH channels on the soma.
305
+ cell.paint(
306
+ AllRegion(),
307
+ mech.CableProperty(
308
+ resting_potential=-65.0 * u.mV,
309
+ membrane_capacitance=1.0 * u.uF / u.cm**2,
310
+ axial_resistivity=100.0 * u.ohm * u.cm,
311
+ ),
312
+ mech.Channel(
313
+ "IL",
314
+ g_max=0.03 * u.mS / u.cm**2,
315
+ E=-54.387 * u.mV,
316
+ ),
317
+ )
318
+ cell.paint(
319
+ branch_in("type", "soma"),
320
+ mech.Channel("Na_HH1952", g_max=120.0 * u.mS / u.cm**2),
321
+ mech.Channel("K_HH1952", g_max=36.0 * u.mS / u.cm**2),
322
+ )
323
+
324
+ # 4. Place one stimulus and one readout at the root midpoint.
325
+ soma_midpoint = RootLocation(x=0.5)
326
+ cell.place(
327
+ soma_midpoint,
328
+ mech.CurrentClamp(
329
+ delay=20.0 * u.ms,
330
+ durations=60.0 * u.ms,
331
+ amplitudes=0.2 * u.nA,
332
+ ),
333
+ )
334
+ cell.place(soma_midpoint, mech.StateProbe())
335
+
336
+ # 5. Inspect the final spatial layout before allocating runtime State.
337
+ print("n_cv:", cell.n_cv)
338
+ for cv in cell.cvs[:3]:
339
+ print(cv.id, cv.branch_id, cv.prox, cv.dist, cv.length, cv.area)
340
+
341
+ # 6. Lower declarations, verify resolved targets, and run.
342
+ cell.init_state()
343
+ initial_samples = cell.sample_probes()
344
+ assert len(initial_samples) == 1
345
+ voltage_key = next(iter(initial_samples))
346
+ assert voltage_key.endswith("_v")
347
+
348
+ for layout in cell.layouts:
349
+ print(layout.kind, layout.target, layout.n_active)
350
+
351
+ result = cell.run(dt=0.05 * u.ms, duration=100.0 * u.ms)
352
+ voltage = result.traces[voltage_key]
353
+
354
+ assert result.time.shape[0] == voltage.shape[0]
355
+ times_ms = result.time.to_decimal(u.ms)
356
+ voltage_mV = voltage.to_decimal(u.mV)
357
+ ```
358
+
359
+ Replace the example morphology, mechanisms, stimulus, readout, `dt`, and CV policy, then validate the target observable under numerical refinement.
360
+
361
+ Open `references/scripts/cell_multicompartment_reference.py` for the full tutorial with CV, node-tree, layout, policy, and plotting inspection.
362
+
363
+ ## Reset, continue, or revise
364
+
365
+ Use continuation, State reset, declaration reset, or a new cell according to what must change.
366
+
367
+ | Intent | API | Result |
368
+ |---|---|---|
369
+ | Continue the same trajectory | Call `cell.run(...)` again. | The next run starts at `cell.current_time`; the cell is not reinitialized. |
370
+ | Repeat the same declaration from reset State | Call `cell.reset_state()`, then `cell.run(...)`. | The cell remains INITIALIZED while voltage, spike, time, and mechanism State are reseeded through their reset hooks. |
371
+ | Change mechanisms, regions, locsets, or probes | Call `cell.reset()`, edit with `paint()` or `place()`, then call `init_state()`. | Runtime State is discarded and the cell returns to DECLARING while its declaration rules remain available for revision. |
372
+ | Compare CV policies or independent numerical trials | Construct separate cells from one model-building function. | Each comparison has independent declarations, runtime State, and time. |
373
+
374
+ ## Reference routing
375
+
376
+ Open the smallest child for the next decision; `skills/braincell/SKILL.md` routes multicompartment work here before these children.
377
+
378
+ | Reference | Open when |
379
+ |---|---|
380
+ | `references/multicompartment/morphology-io-loading-validation.md` | Loading SWC, ASC, NeuroML2, NeuroMorpho.Org, or checkpoint data; configuring validation; or checking loaded geometry. |
381
+ | `references/multicompartment/braincell-manual-morphology-construction.md` | Constructing branches, points, radii, types, and parent-child topology without an existing morphology file. |
382
+ | `references/multicompartment/filter-function-library.md` | Selecting or composing non-canonical regions and locsets for `paint()` and `place()`. |
383
+ | `references/multicompartment/cv-policy-reference.md` | Selecting advanced CV policies or evaluating spatial resolution, cost, probe mapping, and convergence. |
384
+ | `references/multicompartment/probe-reference.md` | Selecting State, mechanism, or current probes; stabilizing trace keys; or resolving empty and ambiguous traces. |
385
+ | `references/multicompartment/topology-building-and-visualization.md` | Inspecting and visualizing morphology, branch, CV, node, region, locset, or runtime topology. |
386
+ | `references/ion-library.md` | Choosing fixed, Nernst, or dynamic ion declarations and concentration behavior. |
387
+ | `references/channel-library.md` | Choosing registered sodium, potassium, calcium, leak, HCN, or mixed-ion density channels. |
388
+ | `references/mixions-for-adaptation.md` | Adding calcium-dependent adaptation, AHP/KCa currents, rebound, or multi-ion dependencies. |
389
+ | `references/solver-library-with-effects.md` | Choosing or comparing cable-aware solvers, step sizes, stability, accuracy, and solver-dependent traces. |
390
+ | `references/braincell-custom-ion-channel-authoring.md` | Implementing a custom ion or channel after confirming that no built-in declaration fits. |
391
+ | `references/scripts/cell_multicompartment_reference.py` | Inspecting the complete official tutorial workflow and its runtime structures in one script. |
@@ -0,0 +1,128 @@
1
+ # Probe reference
2
+
3
+ Use this reference after opening `references/multicompartment/multicompartment-cell-workflow.md` when a multicompartment `Cell` must record membrane voltage, mechanism or ion State, or membrane current, or when a probe produces a missing or unexpected trace.
4
+
5
+ ## Choose the observed value
6
+
7
+ Probes are point declarations that read State or current already owned by the initialized runtime; they do not allocate evolving State of their own.
8
+
9
+ | API | Use when | Important behavior and result |
10
+ |---|---|---|
11
+ | `StateProbe(name=None, field="v")` | Record cell-owned membrane voltage at a locset. | The current multicompartment implementation supports only `field="v"` and produces one voltage probe per resolved point. |
12
+ | `MechanismProbe(mechanism, field, name=None)` | Record a runtime `brainstate.State` field owned by a named channel or ion. | Use for gate variables such as `Na_HH1952.p` or dynamic ion State such as `ca_dyn.Ci`; static parameters and derived properties are not probeable fields. |
13
+ | `CurrentProbe(ion=None, mechanism=None, name=None)` | Record one mechanism current or the total current owned by one ion. | Set `mechanism` for a mechanism current, `ion` for an ion total, or both to select a mechanism under a named ion. |
14
+ | `cell.place(locset, *probes)` | Attach probes to concrete morphology locations before initialization. | A locset resolving to several points creates one resolved probe at each point. |
15
+ | `cell.sample_probe(name)` | Read one placed probe after `init_state()`. | It returns the current snapshot for the exact resolved probe name. |
16
+ | `cell.sample_probes()` | Read every placed probe after `init_state()`. | It returns `{probe_name: current_value}`. |
17
+ | `cell.run(dt=..., duration=...)` | Record the same probes at every integration step. | It returns `RunResult(time=..., traces=...)`, where `traces` is keyed by resolved probe name. |
18
+
19
+ Use `StateProbe` for cell voltage. Use `MechanismProbe` only for stored runtime State. Use `CurrentProbe` when the requested observable is computed current rather than stored State.
20
+
21
+ ## Place and read probes
22
+
23
+ Place probes with the mechanisms they observe, initialize once, inspect snapshot keys, then use the same declarations for time-series recording.
24
+
25
+ ```python
26
+ import braincell
27
+ import braincell.mech as mech
28
+ import brainunit as u
29
+ from braincell.filter import AllRegion, at
30
+
31
+
32
+ morphology = braincell.Morphology.from_swc("neuron.swc")
33
+ cell = braincell.Cell(morphology, solver="staggered")
34
+
35
+ cell.paint(
36
+ AllRegion(),
37
+ mech.Channel(
38
+ "IL",
39
+ g_max=0.03 * u.mS / u.cm**2,
40
+ E=-54.387 * u.mV,
41
+ ),
42
+ mech.Channel(
43
+ "Na_HH1952",
44
+ g_max=120.0 * u.mS / u.cm**2,
45
+ ),
46
+ )
47
+ cell.place(
48
+ at("soma", 0.5),
49
+ mech.StateProbe(),
50
+ mech.MechanismProbe(mechanism="Na_HH1952", field="p"),
51
+ mech.CurrentProbe(mechanism="IL"),
52
+ )
53
+
54
+ cell.init_state()
55
+ samples = cell.sample_probes()
56
+
57
+ assert "soma(0.5)_v" in samples
58
+ assert "soma(0.5)_Na_HH1952_p" in samples
59
+ assert "soma(0.5)_IL_current" in samples
60
+
61
+ result = cell.run(dt=0.05 * u.ms, duration=12.0 * u.ms)
62
+ assert result.traces["soma(0.5)_v"].shape[0] == result.time.shape[0]
63
+ ```
64
+
65
+ Declare probes before `init_state()`. Call `reset()` before adding or changing a probe on an initialized cell; `reset_state()` only reseeds the existing runtime and does not reopen declaration.
66
+
67
+ ## Predict probe names
68
+
69
+ When `name` is omitted, the lowerer combines the resolved location with the observed target.
70
+
71
+ | Probe declaration | Generated key pattern | Documented example |
72
+ |---|---|---|
73
+ | `StateProbe()` | `<location>_v` | `soma(0.5)_v` |
74
+ | `MechanismProbe(mechanism=M, field=F)` | `<location>_<M>_<F>` | `soma(0.5)_Na_HH1952_p` |
75
+ | `CurrentProbe(mechanism=M)` | `<location>_<M>_current` | `soma(0.5)_IL_current` |
76
+ | `CurrentProbe(ion=I)` | `<location>_<I>_current` | `soma(0.5)_na_current` |
77
+
78
+ Use `sorted(cell.sample_probes())` after initialization to discover the actual keys instead of reconstructing them from memory. If `name=...` is supplied, keep it globally unique; duplicate names make snapshot and run results ambiguous.
79
+
80
+ A multi-point locset expands into separate concrete names. For example, `RootLocation(0.5) | Terminals()` creates one voltage key for the root midpoint and one for each terminal selected by the morphology.
81
+
82
+ ## Probe mechanism and ion State
83
+
84
+ `MechanismProbe` resolves a named runtime owner, then reads one field that is stored as `brainstate.State`.
85
+
86
+ | Request | Use | Do not use |
87
+ |---|---|---|
88
+ | Channel gate | `MechanismProbe(mechanism="Na_HH1952", field="p")` | A parameter such as `g_max`; it is not evolving State. |
89
+ | Dynamic ion concentration | `MechanismProbe(mechanism="ca_dyn", field="Ci")` | A derived Nernst property such as `E` when it is computed rather than stored. |
90
+ | Cell voltage | `StateProbe(field="v")` | `MechanismProbe` without a mechanism owner. |
91
+
92
+ The mechanism or ion must exist at the selected runtime point. A valid field on a mechanism painted elsewhere is still invalid at the probe location.
93
+
94
+ ## Probe current ownership
95
+
96
+ Choose between one mechanism current and an ion owner's total current:
97
+
98
+ | Request | Probe |
99
+ |---|---|
100
+ | One ion-bound mechanism | `CurrentProbe(ion="na", mechanism="Na_HH1952")` |
101
+ | One mechanism that can evaluate current without an explicit ion selector | `CurrentProbe(mechanism="IL")` |
102
+ | Sum of currents owned by an ion | `CurrentProbe(ion="na")` |
103
+
104
+ An ion total may equal a mechanism current when that ion owns only one channel. Do not rely on that equality: adding another channel changes the ion total but not the individual mechanism trace.
105
+
106
+ For mixed-ion channels, distinguish the current owner from ions that only modulate gating. Use `CurrentProbe(mechanism=...)` for the channel's own current and `CurrentProbe(ion=...)` for the owning ion's aggregate current.
107
+
108
+ ## Diagnose missing or wrong traces
109
+
110
+ Check failures in declaration-to-runtime order:
111
+
112
+ 1. Confirm that the probe was placed before `init_state()` and that `run()` has at least one placed probe.
113
+ 2. Resolve the locset with `morphology.select(locset)` and inspect its `points` and `display_names`.
114
+ 3. Inspect `sorted(cell.sample_probes())`; do not guess the trace key.
115
+ 4. Confirm that the named mechanism or ion is painted at the resolved point.
116
+ 5. For `MechanismProbe`, confirm that the field is stored runtime State rather than a parameter or derived property.
117
+ 6. For `CurrentProbe`, confirm whether the request means one mechanism current or an ion-owner total.
118
+ 7. Check explicit names for global uniqueness and multi-point locsets for automatic expansion.
119
+ 8. Compare `result.time.shape[0]` with every requested trace length after `run()`.
120
+
121
+ Open `references/multicompartment/topology-building-and-visualization.md` when the locset-to-CV mapping or runtime placement remains uncertain.
122
+
123
+ ## Sources
124
+
125
+ - [Mechanisms in BrainCell](https://brainx.chaobrain.com/braincell/tutorials/mech.html)
126
+ - [StateProbe API](https://brainx.chaobrain.com/braincell/apis/generated/braincell.mech.StateProbe.html)
127
+ - [MechanismProbe API](https://brainx.chaobrain.com/braincell/apis/generated/braincell.mech.MechanismProbe.html)
128
+ - [CurrentProbe API](https://brainx.chaobrain.com/braincell/apis/generated/braincell.mech.CurrentProbe.html)
@@ -0,0 +1,121 @@
1
+ # Topology building and visualization
2
+
3
+ Use this reference after opening `references/multicompartment/multicompartment-cell-workflow.md` when branch topology, control-volume splitting, locset placement, runtime nodes, or spatial values must be inspected rather than inferred.
4
+
5
+ ## Choose the structural view
6
+
7
+ Morphology branches, CVs, and runtime nodes are different layers of one cell; inspect the layer that owns the suspected error.
8
+
9
+ | API or object | Use when | Important behavior and result |
10
+ |---|---|---|
11
+ | `morphology.topo()` | Check imported or manually built parent-child branch structure before discretization. | It renders the named branch tree; it does not show CVs or runtime nodes. |
12
+ | `morphology.select(region_or_locset)` | Verify a selector before attaching mechanisms. | A region returns interval data; a locset returns points and `display_names`. |
13
+ | `cell.cvs` / `cell.n_cv` | Inspect the membrane-oriented discretization. | The CV preview is resolved lazily from morphology, CV policy, and paint rules and is available before runtime initialization. |
14
+ | `cell.init_state()` | Build the execution-oriented runtime. | It transitions the cell from `DECLARING` to `INITIALIZED` and materializes `node_tree`, layouts, State, and probes. |
15
+ | `cell.node_tree` | Inspect runtime point and edge connectivity after initialization. | It exposes `nodes`, `edges`, and `root_node_id`; accessing runtime topology while declaring raises `RuntimeError`. |
16
+ | `cell.vis_branch(...)` | Inspect compact morphology topology or region coverage. | It draws one node per branch and supports regions only, not locsets or value colormaps. |
17
+ | `cell.vis_cv(...)` | Inspect discretization, region coverage, locset ownership, or CV-level values. | It draws one node per CV and supports region, locset, or value mode. |
18
+ | `cell.vis_node(...)` | Inspect the full runtime graph, exact lowered placement, or point-level values. | It requires an initialized cell and draws the execution-oriented node tree. |
19
+ | `cell.vis_topology(level=...)` | Choose `"branch"`, `"cv"`, or `"node"` dynamically. | It dispatches to the matching visualization method and returns the rendered Matplotlib axes. |
20
+
21
+ Do not equate morphology sample points, branches, CVs, and runtime nodes. The morphology defines continuous cable, the CV policy defines isopotential intervals, and `init_state()` lowers those intervals and declarations into the node tree.
22
+
23
+ ## Build and inspect runtime topology
24
+
25
+ Validate selectors against the morphology, inspect CVs before initialization, then inspect the node tree and visual placement after initialization.
26
+
27
+ ```python
28
+ import braincell
29
+ import braincell.mech as mech
30
+ import brainunit as u
31
+ import matplotlib.pyplot as plt
32
+ from braincell.filter import Terminals, branch_in
33
+
34
+
35
+ morphology = braincell.Morphology.from_swc("neuron.swc")
36
+ dendrites = branch_in(
37
+ "type",
38
+ ("dendrite", "basal_dendrite", "apical_dendrite"),
39
+ )
40
+ terminal_sites = Terminals()
41
+
42
+ print(morphology.topo())
43
+ print("dendrite intervals:", morphology.select(dendrites).intervals)
44
+ print("terminal points:", morphology.select(terminal_sites).display_names)
45
+
46
+ cell = braincell.Cell(
47
+ morphology,
48
+ cv_policy=braincell.MaxCVLen(20.0 * u.um),
49
+ )
50
+ cell.place(terminal_sites, mech.StateProbe())
51
+
52
+ assert cell.n_cv == len(cell.cvs)
53
+ cell.init_state()
54
+
55
+ print("CVs:", cell.n_cv)
56
+ print("runtime nodes:", len(cell.node_tree.nodes))
57
+ print("runtime edges:", len(cell.node_tree.edges))
58
+ print("root node:", cell.node_tree.root_node_id)
59
+
60
+ fig, axes = plt.subplots(1, 3, figsize=(12, 4))
61
+ cell.vis_branch(region=dendrites, ax=axes[0], show=False)
62
+ cell.vis_cv(
63
+ region=dendrites,
64
+ coverage_mode="fraction",
65
+ ax=axes[1],
66
+ show=False,
67
+ )
68
+ cell.vis_node(locset=terminal_sites, ax=axes[2], show=False)
69
+ plt.tight_layout()
70
+
71
+ fig, ax = plt.subplots()
72
+ cell.vis_node(value="V", cmap="viridis", ax=ax, show=False)
73
+ plt.show()
74
+ ```
75
+
76
+ Use selection inspection to verify semantic targeting and visualization to verify the lowering. A correct branch label can still produce an unsuitable CV layout, and a correct CV layout can still expose a wrong locset or mechanism placement.
77
+
78
+ ## Select a visualization level
79
+
80
+ | Level | Region highlight | Locset highlight | Value color | Best use |
81
+ |---|---|---|---|---|
82
+ | `"branch"` | Yes | No | No | Compact branch topology and whole-branch or partial-region coverage. |
83
+ | `"cv"` | Yes | Yes | Yes | Spatial discretization, owning-CV placement, and compartment-level values. |
84
+ | `"node"` | Yes | Yes | Yes | Full runtime topology, lowered point placement, and point-level State or parameters. |
85
+
86
+ Use `coverage_mode="fraction"` to blend by overlap fraction, `"any"` to fully highlight any overlap, and `"all"` to highlight only complete coverage. These modes apply to region coverage; locset hits are full-intensity point selections.
87
+
88
+ ## Highlight targets or color values
89
+
90
+ Highlight mode verifies where a declaration resolves. Value mode displays runtime or user-supplied scalar data.
91
+
92
+ | `value` form | Result |
93
+ |---|---|
94
+ | Point-space array of length `n_point` | Color runtime nodes directly. |
95
+ | CV-space array of length `n_cv` | Scatter each CV value into point space. |
96
+ | `"V"` or `"voltage"` | Color by membrane voltage. |
97
+ | `("ion", ion_name, field)` | Color by one ion runtime field. |
98
+ | `("channel", class_name, field)` | Color by one channel field, such as `("channel", "IL", "g_max")`. |
99
+ | `("layout_id", layout_id, field)` | Color by one resolved runtime layout field. |
100
+
101
+ Do not combine `value` with `region` or `locset`; highlight mode and value mode are mutually exclusive. At node level, regions and locsets map to the midpoint point of the owning CV, so a highlight is a runtime-placement view rather than a literal rendering of every morphology coordinate.
102
+
103
+ ## Control layout and rendering
104
+
105
+ | Parameter | Use |
106
+ |---|---|
107
+ | `preset="dendrotweaks"`, `"mono"`, or `"depth"` | Choose a documented topology styling preset. |
108
+ | `layout="twopi"`, `"dot"`, `"neato"`, or `"kamada_kawai"` | Override the graph layout algorithm. |
109
+ | `layout_scale=float` | Tighten values below `1.0` or spread values above `1.0`. |
110
+ | `highlight_color=...` | Set the selection overlay color. |
111
+ | `cmap`, `vmin`, `vmax`, `norm`, `value_label`, `show_colorbar` | Control value-mode normalization and labeling. |
112
+ | `node_color`, `edge_color`, `root_color` | Override low-level topology colors. |
113
+ | `ax=...`, `show=False` | Render into an existing Matplotlib axes without calling `plt.show()`. |
114
+
115
+ For debugging, keep the selector and CV policy fixed while changing visualization levels. Keep the visualization level fixed while comparing CV policies. This isolates whether the mismatch comes from branch selection, discretization, or runtime lowering.
116
+
117
+ ## Sources
118
+
119
+ - [Point tree visualization](https://brainx.chaobrain.com/braincell/tutorials/vis.html)
120
+ - [Region and locset filters](https://brainx.chaobrain.com/braincell/tutorials/filter.html)
121
+ - [Cell API](https://brainx.chaobrain.com/braincell/apis/generated/braincell.Cell.html)