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.
- package/README.md +10 -8
- package/adapters/gemini.js +7 -0
- package/adapters/opencode.js +7 -0
- package/adapters/windsurf.js +7 -0
- package/installation/lib/installer.js +4 -1
- package/manifest.json +6 -1
- package/package.json +8 -2
- package/skills/braincell/SKILL.md +182 -0
- package/skills/braincell/references/area-scaled-hh-pattern.md +54 -0
- package/skills/braincell/references/braincell-custom-ion-channel-authoring.md +273 -0
- package/skills/braincell/references/channel-library.md +85 -0
- package/skills/braincell/references/ion-library.md +87 -0
- package/skills/braincell/references/mixions-for-adaptation.md +81 -0
- package/skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +180 -0
- package/skills/braincell/references/multicompartment/cv-policy-reference.md +133 -0
- package/skills/braincell/references/multicompartment/filter-function-library.md +154 -0
- package/skills/braincell/references/multicompartment/morphology-io-loading-validation.md +135 -0
- package/skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +391 -0
- package/skills/braincell/references/multicompartment/probe-reference.md +128 -0
- package/skills/braincell/references/multicompartment/topology-building-and-visualization.md +260 -0
- package/skills/braincell/references/scripts/calcium_channel_gating.py +66 -0
- package/skills/braincell/references/scripts/cell_multicompartment_reference.py +221 -0
- package/skills/braincell/references/scripts/channel_ablation.py +61 -0
- package/skills/braincell/references/scripts/fi_curve.py +68 -0
- package/skills/braincell/references/scripts/hh_neuron_basics.py +59 -0
- package/skills/braincell/references/scripts/spike_frequency_adaptation.py +75 -0
- package/skills/braincell/references/scripts/t_current_rebound.py +72 -0
- package/skills/braincell/references/scripts/thalamic_neurons.py +228 -0
- package/skills/braincell/references/solver-library-with-effects.md +188 -0
- package/skills/brainevent/SKILL.md +268 -0
- package/skills/brainevent/references/connectivity-variants.md +312 -0
- package/skills/brainevent/references/custom-operators-cpu.md +304 -0
- package/skills/brainevent/references/custom-operators-gpu.md +468 -0
- package/skills/brainevent/references/scripts/102_EI_net_1996.py +107 -0
- package/skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +168 -0
- package/skills/brainevent/references/scripts/coba_ei_teaching.py +356 -0
- package/skills/brainevent/references/sparse-formats.md +182 -0
- package/skills/brainevent/references/synaptic-plasticity.md +285 -0
- package/skills/brainmass/SKILL.md +290 -0
- package/skills/brainmass/references/batch-transform-acceleration.md +136 -0
- package/skills/brainmass/references/brainstate/parameter-constraints-regularization.md +214 -0
- package/skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +171 -0
- package/skills/brainmass/references/braintools/cogtask.md +190 -0
- package/skills/brainmass/references/braintools/data-preprocessing.md +83 -0
- package/skills/brainmass/references/braintools/metric.md +157 -0
- package/skills/brainmass/references/braintools/optimizer.md +187 -0
- package/skills/brainmass/references/braintools/parameter-initializer.md +187 -0
- package/skills/brainmass/references/braintools/surrogate.md +151 -0
- package/skills/brainmass/references/coupling-network-api.md +148 -0
- package/skills/brainmass/references/datasets-api.md +72 -0
- package/skills/brainmass/references/fitting-with-objectives-api.md +146 -0
- package/skills/brainmass/references/forward-observation-api.md +131 -0
- package/skills/brainmass/references/horn-task-training.md +199 -0
- package/skills/brainmass/references/modellibrary.md +104 -0
- package/skills/brainmass/references/noiseprocesses.md +121 -0
- package/skills/brainmass/references/parameter-sweeps-and-regime-analysis.md +130 -0
- package/skills/brainmass/references/scripts/eeg-fitting-with-gradients.py +230 -0
- package/skills/brainmass/references/scripts/gradient-free-fitting.py +106 -0
- package/skills/brainmass/references/scripts/hopf-bifurcation-single-node.py +78 -0
- package/skills/brainmass/references/scripts/horn-cognitive-task-training.py +211 -0
- package/skills/brainmass/references/scripts/jansen-rit-eeg-proxy.py +76 -0
- package/skills/brainmass/references/scripts/kuramoto-synchronization.py +81 -0
- package/skills/brainmass/references/scripts/linear-baseline-node.py +81 -0
- package/skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +249 -0
- package/skills/brainmass/references/scripts/seizure-epileptor-case-study.py +126 -0
- package/skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +86 -0
- package/skills/brainmass/references/scripts/wong-wang-decision-making.py +167 -0
- package/skills/brainmass/references/scripts/wong-wang-dmf-resting-state.py +72 -0
- package/skills/brainmass/references/visualization-analysis-api.md +130 -0
- package/skills/brainpy-state/SKILL.md +232 -0
- package/skills/brainpy-state/references/array-creation.md +158 -0
- package/skills/brainpy-state/references/brain-dynamics-delay-protocol.md +96 -0
- package/skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +334 -0
- package/skills/brainpy-state/references/braintools/data-preprocessing.md +79 -0
- package/skills/brainpy-state/references/braintools/metric.md +152 -0
- package/skills/brainpy-state/references/braintools/optimizer.md +179 -0
- package/skills/brainpy-state/references/braintools/parameter-initializer.md +183 -0
- package/skills/brainpy-state/references/braintools/surrogate.md +147 -0
- package/skills/brainpy-state/references/component-selection.md +273 -0
- package/skills/brainpy-state/references/nest-compatible/devices.md +157 -0
- package/skills/brainpy-state/references/nest-compatible/divergence-and-parity.md +114 -0
- package/skills/brainpy-state/references/nest-compatible/integration-categories.md +41 -0
- package/skills/brainpy-state/references/nest-compatible/model-library.md +200 -0
- package/skills/brainpy-state/references/nest-compatible/nest-workflow.md +156 -0
- package/skills/brainpy-state/references/nest-compatible/network-building.md +264 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brette_et_al_2007.py +320 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_alpha.py +108 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/brunel_delta.py +93 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +171 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +147 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/spatial_gaussex.py +112 -0
- package/skills/brainpy-state/references/nest-compatible/scripts/synapsecollection.py +198 -0
- package/skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +153 -0
- package/skills/brainpy-state/references/projection-patterns.md +125 -0
- package/skills/brainpy-state/references/scripts/103_COBA_2005.py +86 -0
- package/skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +181 -0
- package/skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +156 -0
- package/skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +111 -0
- package/skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +221 -0
- package/skills/brainpy-state/references/scripts/training-snn.py +119 -0
- package/skills/brainstate/SKILL.md +1 -1
- package/skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +250 -399
- package/skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +6 -2
- package/skills/brainstate/references/brainstate/parameter-constraints-regularization.md +16 -2
- package/skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +8 -3
- package/skills/brainstate/references/brainstate/randomness-and-reproducibility.md +64 -143
- package/skills/brainstate/references/brainstate/transformation-grad-expansion.md +13 -1
- package/skills/brainstate/references/brainstate/transformation-jit-expansion.md +11 -1
- package/skills/brainstate/references/brainstate/transformation-vmap-expansion.md +35 -7
- package/skills/brainstate/references/collective_model_operations.md +9 -9
- package/skills/brainstate/references/extension_mechanisms.md +12 -1
- package/skills/brainstate/references/libraries/prebuilt-activation-library.md +106 -97
- package/skills/brainstate/references/libraries/prebuilt-layer-library.md +102 -176
- package/skills/brainstate/references/model-interop-and-migration.md +11 -1
- package/skills/brainstate/references/size-inference-variations.md +11 -0
- package/skills/brainstate/references/state-graph-operations.md +13 -15
- package/skills/brainstate/references/state_collections_and_utilities.md +12 -1
- package/skills/brainx-general-guard/SKILL.md +68 -0
- package/skills/brainstate/references/braintools-optimizer-reference.md +0 -133
- package/skills/brainstate/references/libraries/solver-library-with-effects.md +0 -85
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Reference script mirrored from:
|
|
3
|
+
https://brainx.chaobrain.com/braincell/examples/hh_neuron_basics.html
|
|
4
|
+
|
|
5
|
+
Purpose:
|
|
6
|
+
Canonical minimal single-compartment HH simulation. Use as the default full-script reference for building one `SingleCompartment` neuron, adding Na/K/leak currents, initializing state, injecting current through `update(I)`, running a loop, and plotting voltage/spikes.
|
|
7
|
+
|
|
8
|
+
Use this when:
|
|
9
|
+
- The task asks for one end-to-end HH point-neuron current-clamp simulation.
|
|
10
|
+
- The agent needs the default `SingleCompartment` Na/K/leak construction pattern.
|
|
11
|
+
|
|
12
|
+
Do not use this when:
|
|
13
|
+
- The task needs morphology, network wiring, or a channel-level diagnostic instead of a membrane trace.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import brainstate
|
|
17
|
+
import brainunit as u
|
|
18
|
+
import matplotlib.pyplot as plt
|
|
19
|
+
import braincell
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
# Subclass `SingleCompartment`; `size=1` below means one point neuron.
|
|
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
|
+
neuron = HH(1)
|
|
35
|
+
neuron.init_state()
|
|
36
|
+
|
|
37
|
+
# Current clamp is direct: pass density-based injected current to `update(I)`.
|
|
38
|
+
I = 5. * u.uA / u.cm ** 2
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def step(t):
|
|
42
|
+
with brainstate.environ.context(t=t):
|
|
43
|
+
neuron.update(I)
|
|
44
|
+
return neuron.V.value, neuron.spike.value
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
with brainstate.environ.context(dt=0.01 * u.ms):
|
|
48
|
+
times = u.math.arange(0. * u.ms, 100. * u.ms, brainstate.environ.get_dt())
|
|
49
|
+
vs, spikes = brainstate.transform.for_loop(step, times)
|
|
50
|
+
|
|
51
|
+
print('number of spikes:', int(u.math.sum(spikes)))
|
|
52
|
+
|
|
53
|
+
plt.figure(figsize=(8, 3))
|
|
54
|
+
plt.plot(times / u.ms, u.math.squeeze(vs) / u.mV, linewidth=1.2)
|
|
55
|
+
plt.xlabel('Time (ms)')
|
|
56
|
+
plt.ylabel('Membrane potential (mV)')
|
|
57
|
+
plt.title('HH neuron under 5 uA/cm^2 constant current')
|
|
58
|
+
plt.tight_layout()
|
|
59
|
+
plt.show()
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Reference script mirrored from:
|
|
3
|
+
https://brainx.chaobrain.com/braincell/examples/spike_frequency_adaptation.html
|
|
4
|
+
|
|
5
|
+
Purpose:
|
|
6
|
+
Advanced single-cell mechanism script. Use when the task asks for spike-frequency adaptation, calcium-dependent afterhyperpolarization, dynamic calcium, `MixIons(k, ca)`, or AHP/KCa currents.
|
|
7
|
+
|
|
8
|
+
Use this when:
|
|
9
|
+
- The task asks for adaptation or calcium-dependent afterhyperpolarization in a point neuron.
|
|
10
|
+
- The agent needs dynamic calcium plus `MixIons(self.k, self.ca)` for AHP/KCa currents.
|
|
11
|
+
|
|
12
|
+
Do not use this when:
|
|
13
|
+
- The task only needs the minimal HH Na/K/leak current-clamp pattern.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import brainstate
|
|
17
|
+
import braintools
|
|
18
|
+
import brainunit as u
|
|
19
|
+
import numpy as np
|
|
20
|
+
import matplotlib.pyplot as plt
|
|
21
|
+
import braincell
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class AdaptingCell(braincell.SingleCompartment):
|
|
25
|
+
"""A thalamic-relay-style cell with Ca-activated K (AHP) current."""
|
|
26
|
+
def __init__(self, size, solver='ind_exp_euler'):
|
|
27
|
+
super().__init__(size, V_initializer=braintools.init.Constant(-65. * u.mV),
|
|
28
|
+
V_th=20. * u.mV, solver=solver)
|
|
29
|
+
self.na = braincell.ion.SodiumFixed(size, E=50. * u.mV)
|
|
30
|
+
self.na.add(INa=braincell.channel.Na_Ba2002(size, V_sh=-30 * u.mV))
|
|
31
|
+
self.k = braincell.ion.PotassiumFixed(size, E=-90. * u.mV)
|
|
32
|
+
self.k.add(IKL=braincell.channel.K_Leak(size, g_max=0.01 * (u.mS / u.cm ** 2)))
|
|
33
|
+
self.k.add(IDR=braincell.channel.KDR_Ba2002(size, V_sh=-30. * u.mV, q10=2.0, temp=u.celsius2kelvin(16.)))
|
|
34
|
+
# Dynamic calcium is an ODE state used by calcium channels and AHP coupling.
|
|
35
|
+
self.ca = braincell.ion.CalciumDetailed(size, C_rest=5e-5 * u.mM,
|
|
36
|
+
tau=10. * u.ms, d=0.5 * u.um)
|
|
37
|
+
self.ca.add(ICaL=braincell.channel.CaL_IS2008(size, g_max=0.5 * (u.mS / u.cm ** 2)))
|
|
38
|
+
self.ca.add(ICaN=braincell.channel.CaN_IS2008(size, g_max=0.5 * (u.mS / u.cm ** 2)))
|
|
39
|
+
self.ca.add(ICaT=braincell.channel.CaT_HM1992(size, g_max=2.1 * (u.mS / u.cm ** 2)))
|
|
40
|
+
self.ca.add(ICaHT=braincell.channel.CaHT_HM1992(size, g_max=3.0 * (u.mS / u.cm ** 2)))
|
|
41
|
+
# AHP current depends on both potassium reversal and calcium concentration.
|
|
42
|
+
self.kca = braincell.MixIons(self.k, self.ca)
|
|
43
|
+
self.kca.add(IAHP=braincell.channel.AHP_De1994(size, g_max=0.3 * (u.mS / u.cm ** 2)))
|
|
44
|
+
self.IL = braincell.channel.IL(size, g_max=0.0075 * (u.mS / u.cm ** 2), E=-70 * u.mV)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
cell = AdaptingCell(1)
|
|
48
|
+
cell.init_state()
|
|
49
|
+
|
|
50
|
+
I = 2. * u.uA / u.cm ** 2
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def step(t):
|
|
54
|
+
with brainstate.environ.context(t=t):
|
|
55
|
+
cell.update(I)
|
|
56
|
+
return cell.V.value, cell.spike.value
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
with brainstate.environ.context(dt=0.01 * u.ms):
|
|
60
|
+
times = u.math.arange(0. * u.ms, 500. * u.ms, brainstate.environ.get_dt())
|
|
61
|
+
vs, spikes = brainstate.transform.for_loop(step, times)
|
|
62
|
+
|
|
63
|
+
spike_times = np.asarray(times[u.math.squeeze(spikes) > 0] / u.ms)
|
|
64
|
+
isi = np.diff(spike_times)
|
|
65
|
+
print('number of spikes:', spike_times.size)
|
|
66
|
+
print('first ISIs (ms):', np.round(isi[:6], 2).tolist())
|
|
67
|
+
|
|
68
|
+
fig, axs = plt.subplots(2, 1, figsize=(8, 5))
|
|
69
|
+
axs[0].plot(times / u.ms, u.math.squeeze(vs) / u.mV, linewidth=0.8)
|
|
70
|
+
axs[0].set_xlabel('Time (ms)'); axs[0].set_ylabel('V (mV)')
|
|
71
|
+
axs[0].set_title('Membrane potential under sustained drive')
|
|
72
|
+
axs[1].plot(np.arange(1, isi.size + 1), isi, 'o-')
|
|
73
|
+
axs[1].set_xlabel('Inter-spike interval index'); axs[1].set_ylabel('ISI (ms)')
|
|
74
|
+
axs[1].set_title('ISIs lengthen over time (adaptation)')
|
|
75
|
+
plt.tight_layout(); plt.show()
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Reference script mirrored from:
|
|
3
|
+
https://brainx.chaobrain.com/braincell/examples/t_current_rebound.html
|
|
4
|
+
|
|
5
|
+
Purpose:
|
|
6
|
+
Advanced rebound-bursting script. Use when the task asks for post-inhibitory rebound, T-type calcium current, thalamic-style rebound, hyperpolarizing current steps, or release from inhibition.
|
|
7
|
+
|
|
8
|
+
Use this when:
|
|
9
|
+
- The task asks for rebound bursting after a hyperpolarizing current step.
|
|
10
|
+
- The agent needs T-type calcium and HCN currents in a single-compartment thalamic-style cell.
|
|
11
|
+
|
|
12
|
+
Do not use this when:
|
|
13
|
+
- The task asks for a generic HH current-clamp trace without rebound or calcium dynamics.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import brainstate
|
|
17
|
+
import braintools
|
|
18
|
+
import brainunit as u
|
|
19
|
+
import numpy as np
|
|
20
|
+
import matplotlib.pyplot as plt
|
|
21
|
+
import braincell
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ThalamicCell(braincell.SingleCompartment):
|
|
25
|
+
"""Thalamic-relay-style cell with a low-threshold T-type Ca current."""
|
|
26
|
+
def __init__(self, size, solver='ind_exp_euler'):
|
|
27
|
+
super().__init__(size, V_initializer=braintools.init.Constant(-65. * u.mV),
|
|
28
|
+
V_th=20. * u.mV, solver=solver)
|
|
29
|
+
self.na = braincell.ion.SodiumFixed(size, E=50. * u.mV)
|
|
30
|
+
self.na.add(INa=braincell.channel.Na_Ba2002(size, V_sh=-30 * u.mV))
|
|
31
|
+
self.k = braincell.ion.PotassiumFixed(size, E=-90. * u.mV)
|
|
32
|
+
self.k.add(IKL=braincell.channel.K_Leak(size, g_max=0.01 * (u.mS / u.cm ** 2)))
|
|
33
|
+
self.k.add(IDR=braincell.channel.KDR_Ba2002(size, V_sh=-30. * u.mV, q10=2.0, temp=u.celsius2kelvin(16.)))
|
|
34
|
+
self.ca = braincell.ion.CalciumDetailed(size, C_rest=5e-5 * u.mM,
|
|
35
|
+
tau=10. * u.ms, d=0.5 * u.um)
|
|
36
|
+
# T-type calcium current supports post-inhibitory rebound.
|
|
37
|
+
self.ca.add(ICaT=braincell.channel.CaT_HM1992(size, g_max=2.1 * (u.mS / u.cm ** 2)))
|
|
38
|
+
self.ca.add(ICaHT=braincell.channel.CaHT_HM1992(size, g_max=3.0 * (u.mS / u.cm ** 2)))
|
|
39
|
+
self.Ih = braincell.channel.HCN_HM1992(size, g_max=0.01 * (u.mS / u.cm ** 2), E=-43 * u.mV)
|
|
40
|
+
self.IL = braincell.channel.IL(size, g_max=0.0075 * (u.mS / u.cm ** 2), E=-70 * u.mV)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
cell = ThalamicCell(1)
|
|
44
|
+
cell.init_state()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def I_of_t(t):
|
|
48
|
+
return u.math.where(t < 200. * u.ms,
|
|
49
|
+
-2. * u.uA / u.cm ** 2,
|
|
50
|
+
0. * u.uA / u.cm ** 2)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def step(t):
|
|
54
|
+
with brainstate.environ.context(t=t):
|
|
55
|
+
cell.update(I_of_t(t))
|
|
56
|
+
return cell.V.value, cell.spike.value
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
with brainstate.environ.context(dt=0.01 * u.ms):
|
|
60
|
+
times = u.math.arange(0. * u.ms, 500. * u.ms, brainstate.environ.get_dt())
|
|
61
|
+
vs, spikes = brainstate.transform.for_loop(step, times)
|
|
62
|
+
|
|
63
|
+
spike_times = np.asarray(times[u.math.squeeze(spikes) > 0] / u.ms)
|
|
64
|
+
rebound = spike_times[spike_times > 200.]
|
|
65
|
+
print('spikes after release (ms):', np.round(rebound[:10], 1).tolist())
|
|
66
|
+
|
|
67
|
+
plt.figure(figsize=(8, 3))
|
|
68
|
+
plt.plot(times / u.ms, u.math.squeeze(vs) / u.mV, linewidth=0.8)
|
|
69
|
+
plt.axvline(200., color='k', linestyle=':', label='release')
|
|
70
|
+
plt.xlabel('Time (ms)'); plt.ylabel('Membrane potential (mV)')
|
|
71
|
+
plt.title('Post-inhibitory rebound burst (T-type Ca current)')
|
|
72
|
+
plt.legend(); plt.tight_layout(); plt.show()
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Reference script mirrored from:
|
|
3
|
+
https://brainx.chaobrain.com/braincell/examples/thalamic_neurons.html
|
|
4
|
+
|
|
5
|
+
Purpose:
|
|
6
|
+
Advanced phenotype-comparison script. Use when the task asks for richer thalamic point-neuron variants, multiple channel compositions, calcium dynamics, HCN/AHP/T-type mechanisms, or comparing several single-compartment neuron types.
|
|
7
|
+
|
|
8
|
+
Use this when:
|
|
9
|
+
- The task asks for advanced thalamic point-neuron variants or phenotype comparison.
|
|
10
|
+
- The agent needs multiple ion/channel compositions with calcium dynamics, HCN, AHP, and T-type mechanisms.
|
|
11
|
+
|
|
12
|
+
Do not use this when:
|
|
13
|
+
- The task needs the minimal HH default or any morphology/cable/CV workflow.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import time # for timing the simulation
|
|
17
|
+
|
|
18
|
+
import brainstate
|
|
19
|
+
import braintools
|
|
20
|
+
import brainunit as u
|
|
21
|
+
import matplotlib.pyplot as plt
|
|
22
|
+
import braincell
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# Advanced point-neuron base class; still subclasses `SingleCompartment`.
|
|
26
|
+
class ThalamusNeuron(braincell.SingleCompartment):
|
|
27
|
+
def compute_derivative(self, I_ext=0. * u.nA):
|
|
28
|
+
I_ext = self.sum_current_inputs(I_ext, self.V.value) * self.area_factor
|
|
29
|
+
for key, ch in self.nodes(braincell.IonChannel, allowed_hierarchy=(1, 1)).items():
|
|
30
|
+
I_ext = I_ext + ch.current(self.V.value)
|
|
31
|
+
self.V.derivative = I_ext / self.C
|
|
32
|
+
for key, node in self.nodes(braincell.IonChannel, allowed_hierarchy=(1, 1)).items():
|
|
33
|
+
node.compute_derivative(self.V.value)
|
|
34
|
+
|
|
35
|
+
def step_run(self, t, inp):
|
|
36
|
+
# Define update rule at each time step
|
|
37
|
+
with brainstate.environ.context(t=t):
|
|
38
|
+
self.update(inp)
|
|
39
|
+
return self.V.value
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class HTC(ThalamusNeuron):
|
|
43
|
+
def __init__(
|
|
44
|
+
self,
|
|
45
|
+
size,
|
|
46
|
+
gKL=0.01 * (u.mS / u.cm **2), # Potassium leak channel conductance
|
|
47
|
+
V_initializer=braintools.init.Constant(-65. * u.mV), # Initial membrane potential
|
|
48
|
+
solver: str = 'ind_exp_euler' # Integration method
|
|
49
|
+
):
|
|
50
|
+
super().__init__(size, V_initializer=V_initializer, V_th=20. * u.mV, solver=solver)
|
|
51
|
+
|
|
52
|
+
# Membrane area parameter
|
|
53
|
+
self.area_factor = 1e-3 / (2.9e-4 * u.cm** 2)
|
|
54
|
+
|
|
55
|
+
# Sodium channel
|
|
56
|
+
self.na = braincell.ion.SodiumFixed(size, E=50. * u.mV) # Sodium reversal potential 50 mV
|
|
57
|
+
self.na.add(INa=braincell.channel.Na_Ba2002(size, V_sh=-30 * u.mV))
|
|
58
|
+
|
|
59
|
+
# Potassium channel
|
|
60
|
+
self.k = braincell.ion.PotassiumFixed(size, E=-90. * u.mV) # Potassium reversal potential -90 mV
|
|
61
|
+
self.k.add(IKL=braincell.channel.K_Leak(size, g_max=gKL)) # Potassium leak current
|
|
62
|
+
self.k.add(IDR=braincell.channel.KDR_Ba2002(size, V_sh=-30. * u.mV, q10=2.0, temp=u.celsius2kelvin(16.))) # Delayed rectifier potassium current
|
|
63
|
+
|
|
64
|
+
# Calcium channel
|
|
65
|
+
self.ca = braincell.ion.CalciumDetailed(
|
|
66
|
+
size,
|
|
67
|
+
C_rest=5e-5 * u.mM, # Resting calcium concentration
|
|
68
|
+
tau=10. * u.ms, # Calcium decay time constant
|
|
69
|
+
d=0.5 * u.um # Calcium diffusion distance
|
|
70
|
+
)
|
|
71
|
+
self.ca.add(ICaL=braincell.channel.CaL_IS2008(size, g_max=0.5 * (u.mS / u.cm **2))) # L-type calcium channel
|
|
72
|
+
self.ca.add(ICaN=braincell.channel.CaN_IS2008(size, g_max=0.5 * (u.mS / u.cm** 2))) # N-type calcium channel
|
|
73
|
+
self.ca.add(ICaT=braincell.channel.CaT_HM1992(size, g_max=2.1 * (u.mS / u.cm **2))) # T-type calcium channel (low-threshold)
|
|
74
|
+
self.ca.add(ICaHT=braincell.channel.CaHT_HM1992(size, g_max=3.0 * (u.mS / u.cm** 2))) # High-threshold calcium channel
|
|
75
|
+
|
|
76
|
+
# Calcium-activated potassium channel (IAHP)
|
|
77
|
+
self.kca = braincell.MixIons(self.k, self.ca) # Mix potassium and calcium ions
|
|
78
|
+
self.kca.add(IAHP=braincell.channel.AHP_De1994(size, g_max=0.3 * (u.mS / u.cm **2)))
|
|
79
|
+
|
|
80
|
+
# Hyperpolarization-activated cation current (Ih) and leak current (IL)
|
|
81
|
+
self.Ih = braincell.channel.HCN_HM1992(size, g_max=0.01 * (u.mS / u.cm** 2), E=-43 * u.mV) # Regulates resting potential and rhythm
|
|
82
|
+
self.IL = braincell.channel.IL(size, g_max=0.0075 * (u.mS / u.cm **2), E=-70 * u.mV) # Background leak current
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class RTC(ThalamusNeuron):
|
|
86
|
+
def __init__(
|
|
87
|
+
self,
|
|
88
|
+
size,
|
|
89
|
+
gKL=0.01 * (u.mS / u.cm** 2),
|
|
90
|
+
V_initializer=braintools.init.Constant(-65. * u.mV),
|
|
91
|
+
solver: str = 'ind_exp_euler'
|
|
92
|
+
):
|
|
93
|
+
super().__init__(size, V_initializer=V_initializer, V_th=20 * u.mV, solver=solver)
|
|
94
|
+
|
|
95
|
+
self.area_factor = 1e-3 / (2.9e-4 * u.cm **2) # Membrane area parameter
|
|
96
|
+
|
|
97
|
+
# Sodium channel
|
|
98
|
+
self.na = braincell.ion.SodiumFixed(size)
|
|
99
|
+
self.na.add(INa=braincell.channel.Na_Ba2002(size, V_sh=-40 * u.mV))
|
|
100
|
+
|
|
101
|
+
# Potassium channel
|
|
102
|
+
self.k = braincell.ion.PotassiumFixed(size, E=-90. * u.mV)
|
|
103
|
+
self.k.add(IDR=braincell.channel.KDR_Ba2002(size, V_sh=-40 * u.mV, q10=2.0, temp=u.celsius2kelvin(16.))) # Gating shift
|
|
104
|
+
self.k.add(IKL=braincell.channel.K_Leak(size, g_max=gKL))
|
|
105
|
+
|
|
106
|
+
# Calcium channel
|
|
107
|
+
self.ca = braincell.ion.CalciumDetailed(size, C_rest=5e-5 * u.mM, tau=10. * u.ms, d=0.5 * u.um)
|
|
108
|
+
self.ca.add(ICaL=braincell.channel.CaL_IS2008(size, g_max=0.3 * (u.mS / u.cm** 2)))
|
|
109
|
+
self.ca.add(ICaN=braincell.channel.CaN_IS2008(size, g_max=0.6 * (u.mS / u.cm **2)))
|
|
110
|
+
self.ca.add(ICaT=braincell.channel.CaT_HM1992(size, g_max=2.1 * (u.mS / u.cm** 2)))
|
|
111
|
+
self.ca.add(ICaHT=braincell.channel.CaHT_HM1992(size, g_max=0.6 * (u.mS / u.cm **2)))
|
|
112
|
+
|
|
113
|
+
# Calcium-activated potassium channel (IAHP)
|
|
114
|
+
self.kca = braincell.MixIons(self.k, self.ca)
|
|
115
|
+
self.kca.add(IAHP=braincell.channel.AHP_De1994(size, g_max=0.1 * (u.mS / u.cm** 2)))
|
|
116
|
+
|
|
117
|
+
# Ih and IL currents
|
|
118
|
+
self.Ih = braincell.channel.HCN_HM1992(size, g_max=0.01 * (u.mS / u.cm **2), E=-43 * u.mV)
|
|
119
|
+
self.IL = braincell.channel.IL(size, g_max=0.0075 * (u.mS / u.cm** 2), E=-70 * u.mV)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class IN(ThalamusNeuron):
|
|
123
|
+
def __init__(
|
|
124
|
+
self,
|
|
125
|
+
size,
|
|
126
|
+
gKL=0.01 * (u.mS / u.cm **2),
|
|
127
|
+
V_initializer=braintools.init.Constant(-70. * u.mV), # More hyperpolarized initial membrane potential
|
|
128
|
+
solver: str = 'ind_exp_euler'
|
|
129
|
+
):
|
|
130
|
+
super().__init__(size, V_initializer=V_initializer, V_th=20. * u.mV, solver=solver)
|
|
131
|
+
|
|
132
|
+
self.area_factor = 1e-3 / (1.7e-4 * u.cm** 2)
|
|
133
|
+
|
|
134
|
+
# Sodium channel
|
|
135
|
+
self.na = braincell.ion.SodiumFixed(size)
|
|
136
|
+
self.na.add(INa=braincell.channel.Na_Ba2002(size, V_sh=-30 * u.mV))
|
|
137
|
+
|
|
138
|
+
# Potassium channel
|
|
139
|
+
self.k = braincell.ion.PotassiumFixed(size, E=-90. * u.mV)
|
|
140
|
+
self.k.add(IDR=braincell.channel.KDR_Ba2002(size, V_sh=-30 * u.mV, q10=2.0, temp=u.celsius2kelvin(16.)))
|
|
141
|
+
self.k.add(IKL=braincell.channel.K_Leak(size, g_max=gKL))
|
|
142
|
+
|
|
143
|
+
# Calcium channel
|
|
144
|
+
self.ca = braincell.ion.CalciumDetailed(size, C_rest=5e-5 * u.mM, tau=10. * u.ms, d=0.5 * u.um)
|
|
145
|
+
self.ca.add(ICaN=braincell.channel.CaN_IS2008(size, g_max=0.1 * (u.mS / u.cm **2)))
|
|
146
|
+
self.ca.add(ICaHT=braincell.channel.CaHT_HM1992(size, g_max=2.5 * (u.mS / u.cm** 2)))
|
|
147
|
+
|
|
148
|
+
# Calcium-activated potassium channel (IAHP)
|
|
149
|
+
self.kca = braincell.MixIons(self.k, self.ca)
|
|
150
|
+
self.kca.add(IAHP=braincell.channel.AHP_De1994(size, g_max=0.2 * (u.mS / u.cm **2)))
|
|
151
|
+
|
|
152
|
+
# Leak (IL) and hyperpolarization-activated current (Ih)
|
|
153
|
+
self.IL = braincell.channel.IL(size, g_max=0.0075 * (u.mS / u.cm** 2), E=-60 * u.mV)
|
|
154
|
+
self.Ih = braincell.channel.HCN_HM1992(size, g_max=0.05 * (u.mS / u.cm **2), E=-43 * u.mV)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class TRN(ThalamusNeuron):
|
|
158
|
+
def __init__(
|
|
159
|
+
self,
|
|
160
|
+
size,
|
|
161
|
+
gKL=0.01 * (u.mS / u.cm** 2),
|
|
162
|
+
V_initializer=braintools.init.Constant(-70. * u.mV),
|
|
163
|
+
gl=0.0075, # Leak conductance coefficient
|
|
164
|
+
solver: str = 'ind_exp_euler'
|
|
165
|
+
):
|
|
166
|
+
super().__init__(size, V_initializer=V_initializer, V_th=20. * u.mV, solver=solver)
|
|
167
|
+
|
|
168
|
+
self.area_factor = 1e-3 / (1.43e-4 * u.cm **2)
|
|
169
|
+
|
|
170
|
+
# Sodium channel
|
|
171
|
+
self.na = braincell.ion.SodiumFixed(size)
|
|
172
|
+
self.na.add(INa=braincell.channel.Na_Ba2002(size, V_sh=-40 * u.mV))
|
|
173
|
+
|
|
174
|
+
# Potassium channel
|
|
175
|
+
self.k = braincell.ion.PotassiumFixed(size, E=-90. * u.mV)
|
|
176
|
+
self.k.add(IDR=braincell.channel.KDR_Ba2002(size, V_sh=-40 * u.mV, q10=2.0, temp=u.celsius2kelvin(16.)))
|
|
177
|
+
self.k.add(IKL=braincell.channel.K_Leak(size, g_max=gKL))
|
|
178
|
+
|
|
179
|
+
# Calcium channel
|
|
180
|
+
self.ca = braincell.ion.CalciumDetailed(size, C_rest=5e-5 * u.mM, tau=100. * u.ms, d=0.5 * u.um)
|
|
181
|
+
self.ca.add(ICaN=braincell.channel.CaN_IS2008(size, g_max=0.2 * (u.mS / u.cm** 2)))
|
|
182
|
+
self.ca.add(ICaT=braincell.channel.CaT_HP1992(size, g_max=1.3 * (u.mS / u.cm **2)))
|
|
183
|
+
|
|
184
|
+
# Calcium-activated potassium channel (IAHP)
|
|
185
|
+
self.kca = braincell.MixIons(self.k, self.ca)
|
|
186
|
+
self.kca.add(IAHP=braincell.channel.AHP_De1994(size, g_max=0.2 * (u.mS / u.cm** 2)))
|
|
187
|
+
|
|
188
|
+
# Leak current (IL)
|
|
189
|
+
self.IL = braincell.channel.IL(size, g_max=gl * (u.mS / u.cm **2), E=-60 * u.mV)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def try_trn_neuron():
|
|
193
|
+
# Set the simulation time step
|
|
194
|
+
brainstate.environ.set(dt=0.02 * u.ms)
|
|
195
|
+
|
|
196
|
+
# Generate stepwise input current
|
|
197
|
+
I = braintools.input.section(
|
|
198
|
+
values=[0, 0.05, 0], # Current amplitudes
|
|
199
|
+
durations=[50 * u.ms, 200 * u.ms, 100 * u.ms] # Duration of each segment
|
|
200
|
+
) * u.uA
|
|
201
|
+
|
|
202
|
+
# Generate simulation time series
|
|
203
|
+
times = u.math.arange(I.shape[0]) * brainstate.environ.get_dt()
|
|
204
|
+
|
|
205
|
+
# Select the neuron type to simulate (HTC here; can be replaced with RTC, IN, TRN)
|
|
206
|
+
neu = HTC(1, solver='ind_exp_euler') # Use independent exponential Euler method
|
|
207
|
+
neu.init_state() # Initialize neuron state
|
|
208
|
+
|
|
209
|
+
# Run the simulation and record elapsed time
|
|
210
|
+
t0 = time.time()
|
|
211
|
+
vs = brainstate.transform.for_loop(neu.step_run, times, I) # Loop to update neuron state
|
|
212
|
+
t1 = time.time()
|
|
213
|
+
print(f"Simulation elapsed time: {t1 - t0:.4f} seconds") # Output computation time
|
|
214
|
+
|
|
215
|
+
# Visualize membrane potential changes
|
|
216
|
+
plt.plot(
|
|
217
|
+
times.to_decimal(u.ms), # x-axis: time
|
|
218
|
+
u.math.squeeze(vs.to_decimal(u.mV)) # y-axis: membrane potential
|
|
219
|
+
)
|
|
220
|
+
plt.xlabel('Time (ms)')
|
|
221
|
+
plt.ylabel('Membrane Potential (mV)')
|
|
222
|
+
plt.title('HTC neuron response to step current')
|
|
223
|
+
plt.show()
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
# Execute the simulation
|
|
227
|
+
if __name__ == '__main__':
|
|
228
|
+
try_trn_neuron()
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
# BrainCell solver library with effects
|
|
2
|
+
|
|
3
|
+
Use this reference when selecting a registered BrainCell integrator, comparing solver-dependent traces, or deciding whether a numerical difference is stable enough to interpret. Keep `solver` and the unit-aware time step explicit.
|
|
4
|
+
|
|
5
|
+
## Mental model
|
|
6
|
+
|
|
7
|
+
BrainCell cells expose their integrable `DiffEqState` through the `DiffEqModule` protocol, while a solver from `braincell.quad` advances those states by one environment-defined `dt`.
|
|
8
|
+
|
|
9
|
+
Solver order does not by itself determine suitability. Hodgkin-Huxley gating mixes fast and slow time scales, so stability and coupling assumptions often matter more than formal order.
|
|
10
|
+
|
|
11
|
+
## Selection map
|
|
12
|
+
|
|
13
|
+
| Need | Start with | Numerical consequence |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| Accurate single-cell HH waveform | `exp_euler` | Couples the exponential-Euler update across interacting states; the official comparison reports smoother traces and better agreement during rapid changes than the independent variant. |
|
|
16
|
+
| Large vectorized point-cell simulation | `ind_exp_euler` | Linearizes each `DiffEqState` independently; it is faster but can deviate during rapid voltage-gate coupling. |
|
|
17
|
+
| Smooth non-stiff subsystem or explicit-method comparison | `rk4` or another explicit Runge-Kutta method | Higher order improves smooth-problem accuracy at fixed `dt`, but explicit stability can still fail on stiff neuron dynamics. |
|
|
18
|
+
| Very stiff or near-equilibrium dynamics | `backward_euler` or `implicit_exp_euler` | Implicit stepping trades a solve at each step for stronger stability. |
|
|
19
|
+
| Multicompartment cable | `staggered`, `cn_exp_euler`, or another documented cable scheme | These methods account for spatial voltage coupling; select with the multicompartment workflow and verify both temporal and CV convergence. |
|
|
20
|
+
|
|
21
|
+
Pass the solver name explicitly. The solver guide notes that `SingleCompartment` may otherwise default to `rk2`, which is not the normal starting choice for stiff HH dynamics.
|
|
22
|
+
|
|
23
|
+
## Inspect the installed registry
|
|
24
|
+
|
|
25
|
+
The registry is the source of truth for the current installation; static documentation may differ across releases.
|
|
26
|
+
|
|
27
|
+
| API | Description |
|
|
28
|
+
|---|---|
|
|
29
|
+
| `braincell.quad.get_integrator(name_or_callable)` | Use to resolve a registered string name or accept an integrator callable; an unknown name raises `ValueError`. |
|
|
30
|
+
| `braincell.quad.get_registry()` | Use to inspect registered names and metadata such as category, order, and description. |
|
|
31
|
+
| `braincell.quad.all_integrators` | Use as the backwards-compatible mapping view of the process-wide registry. |
|
|
32
|
+
| `braincell.quad.register_integrator(...)` | Use only when implementing a validated custom step function; it adds the function to the global registry. |
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
import braincell.quad as quad
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
registry = quad.get_registry()
|
|
39
|
+
names = sorted(registry.names())
|
|
40
|
+
exp_entry = registry.entry("exp_euler")
|
|
41
|
+
|
|
42
|
+
assert "exp_euler" in names
|
|
43
|
+
assert callable(quad.get_integrator("exp_euler"))
|
|
44
|
+
print(exp_entry.category, exp_entry.order, exp_entry.description)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Inspect metadata rather than assuming every release exposes the same aliases or defaults.
|
|
48
|
+
|
|
49
|
+
## Registered solver families
|
|
50
|
+
|
|
51
|
+
### Exponential integrators
|
|
52
|
+
|
|
53
|
+
Use these for stiff gating dynamics or composite exponential updates.
|
|
54
|
+
|
|
55
|
+
| Solver name | Description |
|
|
56
|
+
|---|---|
|
|
57
|
+
| `exp_euler` | Coupled exponential Euler; use as the accuracy-oriented point-neuron starting choice. |
|
|
58
|
+
| `ind_exp_euler` | Per-state exponential Euler; use when its speed advantage justifies the independent-state approximation. |
|
|
59
|
+
| `exp_exp_euler` | Exponential cable update combined with exponential-Euler channel updates; use only for a compatible cell workflow. |
|
|
60
|
+
|
|
61
|
+
Do not confuse the `ind_exp_euler` solver with the `IndependentIntegration` mixin. The solver linearizes states independently; the mixin removes a subsystem from its parent's integration loop so it can use its own solver.
|
|
62
|
+
|
|
63
|
+
### Explicit Runge-Kutta integrators
|
|
64
|
+
|
|
65
|
+
Use these for method comparisons or smooth, non-stiff `DiffEqModule` systems. Reduce `dt` aggressively when applying them to HH dynamics.
|
|
66
|
+
|
|
67
|
+
| Solver name | Description |
|
|
68
|
+
|---|---|
|
|
69
|
+
| `euler` | First-order forward Euler. |
|
|
70
|
+
| `midpoint` | Explicit midpoint, also called modified Euler. |
|
|
71
|
+
| `rk2` | Generic second-order Runge-Kutta. |
|
|
72
|
+
| `heun2` | Heun's second-order Runge-Kutta. |
|
|
73
|
+
| `ralston2` | Ralston's second-order Runge-Kutta. |
|
|
74
|
+
| `rk3` | Classical third-order Runge-Kutta. |
|
|
75
|
+
| `heun3` | Heun's third-order Runge-Kutta. |
|
|
76
|
+
| `ssprk3` | Third-order strong-stability-preserving Runge-Kutta. |
|
|
77
|
+
| `ralston3` | Ralston's third-order Runge-Kutta. |
|
|
78
|
+
| `rk4` | Classical fourth-order Runge-Kutta. |
|
|
79
|
+
| `ralston4` | Ralston's fourth-order Runge-Kutta. |
|
|
80
|
+
|
|
81
|
+
Higher order reduces truncation error on smooth stable problems. It does not prevent divergence when `dt` lies outside the explicit method's stability region.
|
|
82
|
+
|
|
83
|
+
### Implicit and cable-aware integrators
|
|
84
|
+
|
|
85
|
+
| Solver name | Description |
|
|
86
|
+
|---|---|
|
|
87
|
+
| `backward_euler` | Linearized backward Euler for strongly stable first-order stepping. |
|
|
88
|
+
| `implicit_euler` | Implicit backward-Euler stepping. |
|
|
89
|
+
| `implicit_exp_euler` | Implicit voltage update with exponential-Euler channel updates. |
|
|
90
|
+
| `implicit_rk4` | Implicit voltage update with explicit RK4 channel updates. |
|
|
91
|
+
| `cn_exp_euler` | Crank-Nicolson voltage update with exponential-Euler channels. |
|
|
92
|
+
| `cn_rk4` | Crank-Nicolson voltage update with explicit RK4 channels. |
|
|
93
|
+
| `splitting` | Operator-splitting method for a multicompartment cell. |
|
|
94
|
+
| `staggered` | Staggered multicompartment cable update. |
|
|
95
|
+
| `dhs_voltage` | Specialized voltage-category scheme; inspect its installed registry metadata and use only in a documented compatible workflow. |
|
|
96
|
+
|
|
97
|
+
Open `references/multicompartment/multicompartment-cell-workflow.md` before choosing among cable solvers. Geometry, cable properties, and CV policy are part of the numerical problem.
|
|
98
|
+
|
|
99
|
+
## Compare solver effects
|
|
100
|
+
|
|
101
|
+
Run the same declaration and initial condition under each solver. Change only the solver first; then refine `dt` independently for each method.
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
import braincell
|
|
105
|
+
import brainstate
|
|
106
|
+
import brainunit as u
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class HH(braincell.SingleCompartment):
|
|
110
|
+
def __init__(self, solver):
|
|
111
|
+
super().__init__(size=1, solver=solver)
|
|
112
|
+
|
|
113
|
+
self.na = braincell.ion.SodiumFixed(1, E=50.0 * u.mV)
|
|
114
|
+
self.na.add(INa=braincell.channel.Na_HH1952(1))
|
|
115
|
+
|
|
116
|
+
self.k = braincell.ion.PotassiumFixed(1, E=-77.0 * u.mV)
|
|
117
|
+
self.k.add(IK=braincell.channel.K_HH1952(1))
|
|
118
|
+
|
|
119
|
+
self.IL = braincell.channel.IL(
|
|
120
|
+
1,
|
|
121
|
+
E=-54.387 * u.mV,
|
|
122
|
+
g_max=0.03 * u.mS / u.cm**2,
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def simulate(solver, dt):
|
|
127
|
+
cell = HH(solver)
|
|
128
|
+
cell.init_state()
|
|
129
|
+
|
|
130
|
+
def step(t):
|
|
131
|
+
with brainstate.environ.context(t=t):
|
|
132
|
+
cell.update(10.0 * u.nA / u.cm**2)
|
|
133
|
+
return cell.V.value
|
|
134
|
+
|
|
135
|
+
with brainstate.environ.context(dt=dt):
|
|
136
|
+
times = u.math.arange(0.0 * u.ms, 100.0 * u.ms, dt)
|
|
137
|
+
voltage = brainstate.transform.for_loop(step, times)
|
|
138
|
+
return times, voltage
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
times, v_exp = simulate("exp_euler", 0.1 * u.ms)
|
|
142
|
+
_, v_ind = simulate("ind_exp_euler", 0.1 * u.ms)
|
|
143
|
+
|
|
144
|
+
assert v_exp.shape == v_ind.shape
|
|
145
|
+
assert v_exp.shape[0] == times.shape[0]
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
The official HH comparison reports:
|
|
149
|
+
|
|
150
|
+
- `exp_euler` produces smoother curves and follows tightly coupled voltage-gate changes more accurately.
|
|
151
|
+
- `ind_exp_euler` can deviate slightly during rapid changes but is faster for large simulations.
|
|
152
|
+
- Both can generate spikes; method-dependent peak shape and timing remain numerical effects until convergence is shown.
|
|
153
|
+
|
|
154
|
+
Do not mix solver selection with a channel, current, initialization, or time-step change in the same comparison.
|
|
155
|
+
|
|
156
|
+
## Verify temporal and spatial convergence
|
|
157
|
+
|
|
158
|
+
Use an observable tied to the scientific question, not only visual trace similarity.
|
|
159
|
+
|
|
160
|
+
1. Run the selected solver at `dt` and `dt / 2`.
|
|
161
|
+
2. Compare peak voltage, spike time, latency, integral, or another declared observable.
|
|
162
|
+
3. Repeat with a second suitable solver when the result is sensitive or surprising.
|
|
163
|
+
4. For `Cell`, refine the CV policy as well as `dt`.
|
|
164
|
+
5. Accept the cheaper configuration only when both refinements change the observable by less than the stated tolerance.
|
|
165
|
+
|
|
166
|
+
If `rk4` produces NaN or extreme voltage while an exponential method remains bounded, reduce `dt` before diagnosing the biological model. If two converged methods disagree, inspect model equations, event handling, and coupling assumptions instead of choosing the preferred trace.
|
|
167
|
+
|
|
168
|
+
## Route advanced integration
|
|
169
|
+
|
|
170
|
+
Open the official advanced integration guide when a subsystem needs `IndependentIntegration`, when authoring a registered integrator, or when inspecting the currently unsupported stochastic `DiffEqState.diffusion` slot. Do not register a custom solver merely to rename or wrap a built-in method.
|
|
171
|
+
|
|
172
|
+
## Common failures
|
|
173
|
+
|
|
174
|
+
- Choosing a solver by formal order alone: account for stiffness and voltage-gate coupling.
|
|
175
|
+
- Leaving the constructor default implicit: pass `solver=...` so the numerical method is reviewable.
|
|
176
|
+
- Using a bare `dt`: provide a BrainUnit time quantity for cellular simulations.
|
|
177
|
+
- Treating one same-`dt` comparison as convergence: refine `dt` separately for each solver.
|
|
178
|
+
- Attributing a shifted spike or waveform to biology: hold the model fixed and test solver and time-step sensitivity.
|
|
179
|
+
- Selecting a cable solver for `SingleCompartment`: reserve spatial schemes for a compatible multicompartment model.
|
|
180
|
+
- Comparing `Cell` solvers without refining CVs: temporal convergence does not establish spatial convergence.
|
|
181
|
+
|
|
182
|
+
## Sources
|
|
183
|
+
|
|
184
|
+
- Integration concept: https://brainx.chaobrain.com/braincell/concepts/integration.html
|
|
185
|
+
- Integration API: https://brainx.chaobrain.com/braincell/apis/integration.html
|
|
186
|
+
- Choosing and using solvers: https://brainx.chaobrain.com/braincell/integration/solvers.html
|
|
187
|
+
- Advanced integration: https://brainx.chaobrain.com/braincell/integration/advanced.html
|
|
188
|
+
- Integration-method effects: https://brainx.chaobrain.com/braincell/examples/integration_methods.html
|