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,125 @@
1
+ # Projection patterns
2
+
3
+ Use this reference after selecting neuron, synapse, output, and communication semantics. Choose alignment from synapse linearity and reuse direction before choosing the class or functional API form.
4
+
5
+ ## Projection anatomy
6
+
7
+ Every native chemical projection separates four roles:
8
+
9
+ | Role | Decision |
10
+ |---|---|
11
+ | `comm` | Choose how presynaptic values are weighted and mapped to postsynaptic values. Use event operators for sparse binary spikes and dense linear operators for dense continuous values. |
12
+ | `syn` | Choose temporal filtering and determine whether its dynamics satisfy AlignPost's linear exponential condition. |
13
+ | `out` | Choose conductance-based, current-based, or voltage-blocked conversion into postsynaptic current. |
14
+ | `post` | Supply the receiving neuron population; projections accumulate input into it before its update. |
15
+
16
+ Call each chemical projection before `post(...)` in the step. Read the presynaptic spike from the previous completed update, route it through the projection, then update the source and target populations.
17
+
18
+ Subclass `brainpy.state.Projection` only when the concrete projections cannot express the required lifecycle. Register communication, dynamics, and output Modules as attributes and preserve the postsynaptic current/delta-input contract.
19
+
20
+ ## Alignment decision
21
+
22
+ Choose alignment from synapse linearity and trace reuse; use a filter-free or electrical projection only when the connection does not require aligned chemical-synapse State.
23
+
24
+ ### Linear convergent fan-in
25
+
26
+ Use this family for exponential-family linear synapses when many sources converge on a target and exact State should scale with the postsynaptic dimension.
27
+
28
+ | API | Use when |
29
+ |---|---|
30
+ | `brainpy.state.AlignPostProj(*modules, comm=..., syn=..., out=..., post=..., label=None, delay=None)` | Use the direct push form when the caller supplies presynaptic events at update time; it stores exact synaptic State with memory proportional to `N_post`. |
31
+ | `brainpy.state.align_post_projection(*spike_generator, comm=..., syn=..., out=..., post=..., stp=None)` | Use the builder form when presynaptic extraction or short-term plasticity belongs to projection construction. |
32
+
33
+ ### Nonlinear or reusable fan-out
34
+
35
+ Use this family for nonlinear receptor kinetics or when one source population fans out to several targets and outgoing parameters are homogeneous per source.
36
+
37
+ | API | Use when |
38
+ |---|---|
39
+ | `brainpy.state.align_pre_projection(*spike_generator, syn=..., comm=..., out=..., post=..., stp=None)` | Use when exact synaptic traces should live on and be reusable from the presynaptic dimension, with memory proportional to `N_pre`. |
40
+
41
+ ### Filter-free chemical projections
42
+
43
+ Use this family when communication should deposit continuous current or an instantaneous event without temporal synapse dynamics.
44
+
45
+ | API | Use when |
46
+ |---|---|
47
+ | `brainpy.state.CurrentProj(*prefetch, comm=..., out=..., post=..., delay=None)` | Use when continuous input requires communication and output conversion before current is deposited into `post`. |
48
+ | `brainpy.state.DeltaProj(*prefetch, comm=..., post=..., label=None)` | Use when an event should produce an instantaneous target increment without temporal synapse State. |
49
+
50
+ ### Electrical coupling
51
+
52
+ Use this family when voltage differences should drive reciprocal or directed gap-junction current rather than a chemical synapse.
53
+
54
+ | API | Use when |
55
+ |---|---|
56
+ | `brainpy.state.SymmetryGapJunction(couples, states, conn, weight, param_type=brainstate.ParamState)` | Use when the same conductance applies reciprocally in both coupling directions. |
57
+ | `brainpy.state.AsymmetryGapJunction(pre, pre_state, post, post_state, conn, weight, param_type=brainstate.ParamState)` | Use when the two coupling directions require distinct conductances. |
58
+
59
+ AlignPre and AlignPost are exact only under their stated conditions. They change State ownership and memory, not the intended dynamics.
60
+
61
+ ## AlignPost API forms
62
+
63
+ Use `AlignPostProj` for the direct push form:
64
+
65
+ ```python
66
+ proj = brainpy.state.AlignPostProj(
67
+ comm=brainstate.nn.EventFixedProb(
68
+ n_pre,
69
+ n_post,
70
+ conn_num=0.1,
71
+ conn_weight=0.5 * u.mS,
72
+ ),
73
+ syn=brainpy.state.Expon.desc(n_post, tau=5.0 * u.ms),
74
+ out=brainpy.state.COBA.desc(E=0.0 * u.mV),
75
+ post=post,
76
+ )
77
+
78
+ proj(pre.get_spike() != 0.0)
79
+ ```
80
+
81
+ Use the functional builder when presynaptic extraction or short-term plasticity belongs to projection construction. Open `references/component-selection.md` for the canonical `stp=STP.desc(...)` composition.
82
+
83
+ Do not pass both a pulled presynaptic source and a second explicit spike array at update time.
84
+
85
+ When `syn` and `out` are matching `.desc(...)` objects, compatible AlignPost projections targeting the same population can merge and share the postsynaptic synapse/output instances. When `syn` is a concrete synapse instance, pass a concrete output instance as well; that pair is not merged.
86
+
87
+ ## AlignPre form
88
+
89
+ Use the function `align_pre_projection`; there is no AlignPre projection class:
90
+
91
+ ```python
92
+ proj = brainpy.state.align_pre_projection(
93
+ pre,
94
+ syn=brainpy.state.AMPA(n_pre),
95
+ comm=brainstate.nn.Linear(
96
+ n_pre,
97
+ n_post,
98
+ w_init=braintools.init.KaimingNormal(unit=u.mS),
99
+ b_init=None,
100
+ ),
101
+ out=brainpy.state.COBA(E=0.0 * u.mV),
102
+ post=post,
103
+ )
104
+ ```
105
+
106
+ Use AlignPre only when synaptic parameters are homogeneous for the outgoing synapses represented by each presynaptic trace. If connection-specific nonlinear kinetics are required, the shared-trace premise does not hold.
107
+
108
+ ## Delayed projections
109
+
110
+ Choose projection alignment before adding a delay. Open `references/brain-dynamics-delay-protocol.md` when selecting direct `delay=` versus delayed prefetch, applying scalar or per-presynaptic delays, preserving the fixed-`dt` buffer invariant, or separating BrainPy projection delays from general BrainState delay buffers.
111
+
112
+ ## Communication boundary
113
+
114
+ Use `brainstate.nn.EventFixedProb` for the canonical probabilistic sparse-spike connection shown in BrainPy-State tutorials. Open `skills/brainevent/SKILL.md` when the decision involves `EventLinear`, fixed-number event connectivity, sparse formats, plasticity operators, custom kernels, or dense-to-event performance conversion.
115
+
116
+ Open `references/scripts/103_COBA_2005.py` for a complete E/I COBA projection workflow. Open `references/scripts/109_fast_global_oscillation.py` when the projection uses `DeltaProj` with delayed recurrent input.
117
+
118
+ ## Official sources
119
+
120
+ - `https://brainx.chaobrain.com/brainpy-state/concepts/model-anatomy.html`
121
+ - `https://brainx.chaobrain.com/brainpy-state/concepts/alignpre-alignpost.html`
122
+ - `https://brainx.chaobrain.com/brainpy-state/brainpy-style/tutorials/02-synapse-and-projection.html`
123
+ - `https://brainx.chaobrain.com/brainpy-state/brainpy-style/howto/sim-short-term-plasticity.html`
124
+ - `https://brainx.chaobrain.com/brainpy-state/brainpy-style/howto/sim-delays.html`
125
+ - `https://brainx.chaobrain.com/brainpy-state/apis/brainpy-projections.html`
@@ -0,0 +1,86 @@
1
+ # Copyright 2024 BrainX Ecosystem Limited. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ #
17
+ # Implementation of the paper:
18
+ #
19
+ # - Brette, R., Rudolph, M., Carnevale, T., Hines, M., Beeman, D., Bower, J. M., et al. (2007),
20
+ # Simulation of networks of spiking neurons: a review of tools and strategies., J. Comput. Neurosci., 23, 3, 349–98
21
+ #
22
+ # which is based on the balanced network proposed by:
23
+ #
24
+ # - Vogels, T. P. and Abbott, L. F. (2005), Signal propagation and logic gating in networks of integrate-and-fire neurons., J. Neurosci., 25, 46, 10786–95
25
+ #
26
+
27
+
28
+ import brainunit as u
29
+ import matplotlib.pyplot as plt
30
+
31
+ import brainpy
32
+ import brainstate
33
+ import braintools
34
+
35
+
36
+ class EINet(brainstate.nn.Module):
37
+ def __init__(self):
38
+ super().__init__()
39
+ self.n_exc = 3200
40
+ self.n_inh = 800
41
+ self.num = self.n_exc + self.n_inh
42
+ self.N = brainpy.state.LIFRef(
43
+ self.num, V_rest=-60. * u.mV, V_th=-50. * u.mV, V_reset=-60. * u.mV,
44
+ tau=20. * u.ms, tau_ref=5. * u.ms,
45
+ V_initializer=braintools.init.Normal(-55., 2., unit=u.mV)
46
+ )
47
+ self.E = brainpy.state.AlignPostProj(
48
+ comm=brainstate.nn.EventFixedProb(self.n_exc, self.num, conn_num=0.02, conn_weight=0.6 * u.mS),
49
+ syn=brainpy.state.Expon.desc(self.num, tau=5. * u.ms),
50
+ out=brainpy.state.COBA.desc(E=0. * u.mV),
51
+ post=self.N
52
+ )
53
+ self.I = brainpy.state.AlignPostProj(
54
+ comm=brainstate.nn.EventFixedProb(self.n_inh, self.num, conn_num=0.02, conn_weight=6.7 * u.mS),
55
+ syn=brainpy.state.Expon.desc(self.num, tau=10. * u.ms),
56
+ out=brainpy.state.COBA.desc(E=-80. * u.mV),
57
+ post=self.N
58
+ )
59
+
60
+ def update(self, t, inp):
61
+ with brainstate.environ.context(t=t):
62
+ spk = self.N.get_spike() != 0.
63
+ self.E(spk[:self.n_exc])
64
+ self.I(spk[self.n_exc:])
65
+ self.N(inp)
66
+ return self.N.get_spike()
67
+
68
+
69
+ # network
70
+ net = EINet()
71
+ brainstate.nn.init_all_states(net)
72
+
73
+ # simulation
74
+ with brainstate.environ.context(dt=0.1 * u.ms):
75
+ times = u.math.arange(0. * u.ms, 1000. * u.ms, brainstate.environ.get_dt())
76
+ spikes = brainstate.transform.for_loop(
77
+ lambda t: net.update(t, 20. * u.mA), times,
78
+ pbar=brainstate.transform.ProgressBar(10)
79
+ )
80
+
81
+ # visualization
82
+ t_indices, n_indices = u.math.where(spikes)
83
+ plt.scatter(times[t_indices], n_indices, s=1)
84
+ plt.xlabel('Time (ms)')
85
+ plt.ylabel('Neuron index')
86
+ plt.show()
@@ -0,0 +1,181 @@
1
+ # Copyright 2024 BrainX Ecosystem Limited. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ #
17
+ # Implementation of the paper:
18
+ #
19
+ # - Brette, R., Rudolph, M., Carnevale, T., Hines, M., Beeman, D., Bower, J. M., et al. (2007),
20
+ # Simulation of networks of spiking neurons: a review of tools and strategies., J. Comput. Neurosci., 23, 3, 349–98
21
+ #
22
+ # This is the Hodgkin-Huxley variant (benchmark 3) of the FACETS simulator review.
23
+ # The integrate-and-fire benchmarks 1 (COBA, iaf_cond_exp) and 2 (CUBA, iaf_psc_exp)
24
+ # of the same review are ported on the brainpy.state Simulator API, with live-NEST
25
+ # rate-band parity, in ``examples/nest_like/brette_et_al_2007.py``.
26
+ #
27
+
28
+ import brainunit as u
29
+ import matplotlib.pyplot as plt
30
+ import numpy as np
31
+
32
+ import brainpy
33
+ import brainstate
34
+
35
+ # brainstate.environ.set(precision='bf16')
36
+
37
+ num_exc = 3200
38
+ num_inh = 800
39
+
40
+ area = 20000 * u.um ** 2
41
+ area = area.in_unit(u.cm ** 2)
42
+ Cm = (1 * u.uF * u.cm ** -2) * area # Membrane Capacitance [pF]
43
+
44
+ gl = (5. * u.nS * u.cm ** -2) * area # Leak Conductance [nS]
45
+ g_Na = (100. * u.mS * u.cm ** -2) * area # Sodium Conductance [nS]
46
+ g_Kd = (30. * u.mS * u.cm ** -2) * area # K Conductance [nS]
47
+
48
+ El = -60. * u.mV # Resting Potential [mV]
49
+ ENa = 50. * u.mV # reversal potential (Sodium) [mV]
50
+ EK = -90. * u.mV # reversal potential (Potassium) [mV]
51
+ VT = -63. * u.mV # Threshold Potential [mV]
52
+ V_th = -20. * u.mV # Spike Threshold [mV]
53
+
54
+ # Time constants
55
+ taue = 5. * u.ms # Excitatory synaptic time constant [ms]
56
+ taui = 10. * u.ms # Inhibitory synaptic time constant [ms]
57
+
58
+ # Reversal potentials
59
+ Ee = 0. * u.mV # Excitatory reversal potential (mV)
60
+ Ei = -80. * u.mV # Inhibitory reversal potential (Potassium) [mV]
61
+
62
+ # excitatory synaptic weight
63
+ we = 6. * u.nS # excitatory synaptic conductance [nS]
64
+
65
+ # inhibitory synaptic weight
66
+ wi = 67. * u.nS # inhibitory synaptic conductance [nS]
67
+
68
+
69
+ class HH(brainpy.state.Neuron):
70
+ """
71
+ Hodgkin-Huxley neuron model.
72
+ """
73
+
74
+ def __init__(self, in_size):
75
+ super().__init__(in_size)
76
+
77
+ def init_state(self, *args, **kwargs):
78
+ # variables
79
+ self.V = brainstate.HiddenState(El + (brainstate.random.randn(*self.varshape) * 5 - 5) * u.mV)
80
+ self.m = brainstate.HiddenState(u.math.zeros(self.varshape, dtype=brainstate.environ.dftype()))
81
+ self.n = brainstate.HiddenState(u.math.zeros(self.varshape, dtype=brainstate.environ.dftype()))
82
+ self.h = brainstate.HiddenState(u.math.zeros(self.varshape, dtype=brainstate.environ.dftype()))
83
+ self.spike = brainstate.HiddenState(u.math.zeros(self.varshape, dtype=bool))
84
+
85
+ def reset_state(self, *args, **kwargs):
86
+ self.V.value = El + (brainstate.random.randn(self.varshape) * 5 - 5)
87
+ self.m.value = u.math.zeros(self.varshape)
88
+ self.n.value = u.math.zeros(self.varshape)
89
+ self.h.value = u.math.zeros(self.varshape)
90
+ self.spike.value = u.math.zeros(self.varshape, dtype=bool)
91
+
92
+ def dV(self, V, m, h, n, Isyn):
93
+ gna = g_Na * (m * m * m) * h
94
+ gkd = g_Kd * (n * n * n * n)
95
+ dVdt = (-gl * (V - El) - gna * (V - ENa) - gkd * (V - EK) + self.sum_current_inputs(Isyn, V)) / Cm
96
+ return dVdt
97
+
98
+ def dm(self, m, V, ):
99
+ a = (- V + VT) / u.mV + 13
100
+ b = (V - VT) / u.mV - 40
101
+ m_alpha = 0.32 * 4 / u.math.exprel(a / 4)
102
+ m_beta = 0.28 * 5 / u.math.exprel(b / 5)
103
+ dmdt = (m_alpha * (1 - m) - m_beta * m) / u.ms
104
+ return dmdt
105
+
106
+ def dh(self, h, V):
107
+ c = (- V + VT) / u.mV + 17
108
+ d = (V - VT) / u.mV - 40
109
+ h_alpha = 0.128 * u.math.exp(c / 18)
110
+ h_beta = 4. / (1 + u.math.exp(-d / 5))
111
+ dhdt = (h_alpha * (1 - h) - h_beta * h) / u.ms
112
+ return dhdt
113
+
114
+ def dn(self, n, V):
115
+ c = (- V + VT) / u.mV + 15
116
+ d = (- V + VT) / u.mV + 10
117
+ n_alpha = 0.032 * 5 / u.math.exprel(c / 5)
118
+ n_beta = .5 * u.math.exp(d / 40)
119
+ dndt = (n_alpha * (1 - n) - n_beta * n) / u.ms
120
+ return dndt
121
+
122
+ def update(self, x=0. * u.mA):
123
+ last_V = self.V.value
124
+ V = brainstate.nn.exp_euler_step(self.dV, last_V, self.m.value, self.h.value, self.n.value, x)
125
+ m = brainstate.nn.exp_euler_step(self.dm, self.m.value, last_V)
126
+ h = brainstate.nn.exp_euler_step(self.dh, self.h.value, last_V)
127
+ n = brainstate.nn.exp_euler_step(self.dn, self.n.value, last_V)
128
+ self.spike.value = u.math.logical_and(last_V < V_th, V >= V_th)
129
+ self.m.value = m
130
+ self.h.value = h
131
+ self.n.value = n
132
+ self.V.value = V
133
+ return self.spike.value
134
+
135
+
136
+ class EINet(brainstate.nn.Module):
137
+ def __init__(self):
138
+ super().__init__()
139
+ self.n_exc = 3200
140
+ self.n_inh = 800
141
+ self.varshape = self.n_exc + self.n_inh
142
+ self.N = HH(self.varshape)
143
+
144
+ self.E = brainpy.state.AlignPostProj(
145
+ comm=brainstate.nn.EventFixedProb(self.n_exc, self.varshape, conn_num=0.02, conn_weight=we),
146
+ syn=brainpy.state.Expon(self.varshape, tau=taue),
147
+ out=brainpy.state.COBA(E=Ee),
148
+ post=self.N
149
+ )
150
+ self.I = brainpy.state.AlignPostProj(
151
+ comm=brainstate.nn.EventFixedProb(self.n_inh, self.varshape, conn_num=0.02, conn_weight=wi),
152
+ syn=brainpy.state.Expon(self.varshape, tau=taui),
153
+ out=brainpy.state.COBA(E=Ei),
154
+ post=self.N
155
+ )
156
+
157
+ def update(self, t):
158
+ with brainstate.environ.context(t=t):
159
+ spk = self.N.spike.value
160
+ self.E(spk[:self.n_exc])
161
+ self.I(spk[self.n_exc:])
162
+ r = self.N()
163
+ return r
164
+
165
+
166
+ # network
167
+ net = EINet()
168
+ brainstate.nn.init_all_states(net)
169
+
170
+ # simulation
171
+ with brainstate.environ.context(dt=0.04 * u.ms):
172
+ times = u.math.arange(0. * u.ms, 300. * u.ms, brainstate.environ.get_dt())
173
+ times = u.math.asarray(times, dtype=brainstate.environ.dftype())
174
+ spikes = brainstate.transform.for_loop(net.update, times, pbar=brainstate.transform.ProgressBar(100))
175
+
176
+ # visualization
177
+ t_indices, n_indices = u.math.where(spikes)
178
+ plt.scatter(u.math.asarray(times[t_indices] / u.ms, dtype=np.float32), n_indices, s=1)
179
+ plt.xlabel('Time (ms)')
180
+ plt.ylabel('Neuron index')
181
+ plt.show()
@@ -0,0 +1,156 @@
1
+ # Copyright 2024 BrainX Ecosystem Limited. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+
17
+ #
18
+ # Implementation of the paper:
19
+ #
20
+ # - Wang X J, Buzsáki G. Gamma oscillation by synaptic inhibition in a hippocampal interneuronal network model[J]. Journal of neuroscience, 1996, 16(20): 6402-6413.
21
+ #
22
+
23
+ import brainunit as u
24
+ import matplotlib.pyplot as plt
25
+
26
+ import brainpy
27
+ import brainstate
28
+ import braintools
29
+
30
+
31
+ class HH(brainpy.state.Neuron):
32
+ def __init__(
33
+ self, in_size, ENa=55. * u.mV, EK=-90. * u.mV, EL=-65 * u.mV, C=1.0 * u.uF,
34
+ gNa=35. * u.msiemens, gK=9. * u.msiemens, gL=0.1 * u.msiemens, V_th=20. * u.mV, phi=5.0
35
+ ):
36
+ super().__init__(in_size)
37
+
38
+ # parameters
39
+ self.ENa = ENa
40
+ self.EK = EK
41
+ self.EL = EL
42
+ self.C = C
43
+ self.gNa = gNa
44
+ self.gK = gK
45
+ self.gL = gL
46
+ self.V_th = V_th
47
+ self.phi = phi
48
+
49
+ def init_state(self, *args, **kwargs):
50
+ # variables
51
+ self.V = brainstate.HiddenState(-70. * u.mV + brainstate.random.randn(*self.varshape) * 20 * u.mV)
52
+ self.h = brainstate.HiddenState(braintools.init.param(braintools.init.Constant(0.6), self.varshape))
53
+ self.n = brainstate.HiddenState(braintools.init.param(braintools.init.Constant(0.3), self.varshape))
54
+ self.spike = brainstate.HiddenState(
55
+ braintools.init.param(lambda s: u.math.zeros(s, dtype=bool), self.varshape))
56
+
57
+ def dh(self, h, t, V):
58
+ alpha = 0.07 * u.math.exp(-(V / u.mV + 58) / 20)
59
+ beta = 1 / (u.math.exp(-0.1 * (V / u.mV + 28)) + 1)
60
+ dhdt = alpha * (1 - h) - beta * h
61
+ return self.phi * dhdt / u.ms
62
+
63
+ def dn(self, n, t, V):
64
+ alpha = -0.01 * (V / u.mV + 34) / (u.math.exp(-0.1 * (V / u.mV + 34)) - 1)
65
+ beta = 0.125 * u.math.exp(-(V / u.mV + 44) / 80)
66
+ dndt = alpha * (1 - n) - beta * n
67
+ return self.phi * dndt / u.ms
68
+
69
+ def dV(self, V, t, h, n, Iext):
70
+ m_alpha = -0.1 * (V / u.mV + 35) / (u.math.exp(-0.1 * (V / u.mV + 35)) - 1)
71
+ m_beta = 4 * u.math.exp(-(V / u.mV + 60) / 18)
72
+ m = m_alpha / (m_alpha + m_beta)
73
+ INa = self.gNa * m ** 3 * h * (V - self.ENa)
74
+ IK = self.gK * n ** 4 * (V - self.EK)
75
+ IL = self.gL * (V - self.EL)
76
+ dVdt = (- INa - IK - IL + self.sum_current_inputs(Iext, V)) / self.C
77
+ return dVdt
78
+
79
+ def update(self, x=0. * u.uA):
80
+ t = brainstate.environ.get('t')
81
+ V = brainstate.nn.exp_euler_step(self.dV, self.V.value, t, self.h.value, self.n.value, x)
82
+ h = brainstate.nn.exp_euler_step(self.dh, self.h.value, t, V)
83
+ n = brainstate.nn.exp_euler_step(self.dn, self.n.value, t, V)
84
+ self.spike.value = u.math.logical_and(self.V.value < self.V_th, V >= self.V_th)
85
+ self.V.value = V
86
+ self.h.value = h
87
+ self.n.value = n
88
+ return self.V.value
89
+
90
+
91
+ class Synapse(brainpy.state.Synapse):
92
+ def __init__(self, in_size, alpha=12 / u.ms, beta=0.1 / u.ms):
93
+ super().__init__(in_size=in_size)
94
+ self.alpha = alpha
95
+ self.beta = beta
96
+
97
+ def init_state(self, *args, **kwargs):
98
+ self.g = brainstate.HiddenState(
99
+ braintools.init.param(braintools.init.ZeroInit(), self.varshape)
100
+ )
101
+
102
+ def update(self, pre_V):
103
+ f_v = lambda v: 1 / (1 + u.math.exp(-v / u.mV / 2))
104
+ ds = lambda s: self.alpha * f_v(pre_V) * (1 - s) - self.beta * s
105
+ self.g.value = brainstate.nn.exp_euler_step(ds, self.g.value)
106
+ return self.g.value
107
+
108
+
109
+ class GammaNet(brainstate.nn.Module):
110
+ def __init__(self, num: int = 100):
111
+ super().__init__()
112
+ self.neu = HH(num)
113
+ # self.syn = brainstate.nn.GABAa(num, alpha=12 / (u.ms * u.mM), beta=0.1 / u.ms)
114
+ self.syn = Synapse(num)
115
+ self.proj = brainpy.state.CurrentProj(
116
+ self.syn.prefetch('g'),
117
+ comm=brainstate.nn.AllToAll(
118
+ self.neu.varshape, self.neu.varshape, include_self=False, w_init=0.1 * u.msiemens / num
119
+ ),
120
+ out=brainpy.state.COBA(E=-75. * u.mV),
121
+ post=self.neu
122
+ )
123
+
124
+ def update(self, t):
125
+ with brainstate.environ.context(t=t):
126
+ self.proj()
127
+ self.syn(self.neu(I_inp))
128
+ # visualize spikes and membrane potentials of the first 5 neurons
129
+ return self.neu.spike.value, self.neu.V.value[:5]
130
+
131
+
132
+ # background input
133
+ I_inp = 1.0 * u.uA
134
+
135
+ # network
136
+ net = GammaNet()
137
+ brainstate.nn.init_all_states(net)
138
+
139
+ # simulation
140
+ with brainstate.environ.context(dt=0.01 * u.ms):
141
+ times = u.math.arange(0. * u.ms, 500. * u.ms, brainstate.environ.get_dt())
142
+ spikes, vs = brainstate.transform.for_loop(net.update, times, pbar=100)
143
+
144
+ # visualization
145
+ fig, gs = braintools.visualize.get_figure(1, 2, 4, 4)
146
+ fig.add_subplot(gs[0, 0])
147
+ plt.plot(times, vs.to_decimal(u.mV))
148
+ plt.xlabel('Time (ms)')
149
+ plt.ylabel('Membrane potential (mV)')
150
+
151
+ fig.add_subplot(gs[0, 1])
152
+ t_indices, n_indices = u.math.where(spikes)
153
+ plt.plot(times[t_indices], n_indices, 'k.')
154
+ plt.xlabel('Time (ms)')
155
+ plt.ylabel('Neuron index')
156
+ plt.show()
@@ -0,0 +1,111 @@
1
+ # Copyright 2024 BrainX Ecosystem Limited. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+
17
+ #
18
+ # Implementation of the paper:
19
+ #
20
+ # - Brunel, Nicolas, and Vincent Hakim. “Fast global oscillations in networks of integrate-and-fire neurons with low firing rates.” Neural computation 11.7 (1999): 1621-1671.
21
+ #
22
+
23
+
24
+ import brainunit as u
25
+ import jax
26
+ import matplotlib.pyplot as plt
27
+
28
+ import brainpy
29
+ import brainstate
30
+ import braintools
31
+
32
+ Vr = 10. * u.mV
33
+ theta = 20. * u.mV
34
+ tau = 20. * u.ms
35
+ delta = 2. * u.ms
36
+ taurefr = 2. * u.ms
37
+ duration = 100. * u.ms
38
+ J = .1 * u.mV
39
+ muext = 25. * u.mV
40
+ sigmaext = 1.0 * u.mV
41
+ C = 1000
42
+ N = 5000
43
+ sparseness = C / N
44
+
45
+
46
+ class LIF(brainpy.state.Neuron):
47
+ def __init__(self, in_size, **kwargs):
48
+ super().__init__(in_size, **kwargs)
49
+
50
+ def init_state(self, *args, **kwargs):
51
+ # variables
52
+ self.V = brainstate.HiddenState(braintools.init.param(braintools.init.Constant(Vr), self.varshape))
53
+ self.t_last_spike = brainstate.ShortTermState(
54
+ braintools.init.param(braintools.init.Constant(-1e7 * u.ms), self.varshape)
55
+ )
56
+
57
+ def update(self):
58
+ # integrate membrane potential
59
+ fv = lambda V: (-V + self.sum_current_inputs(muext, V)) / tau
60
+ gv = lambda V: sigmaext / u.math.sqrt(tau)
61
+ V = brainstate.nn.exp_euler_step(fv, gv, self.V.value)
62
+ V = self.sum_delta_inputs(V)
63
+
64
+ # refractory period
65
+ t = brainstate.environ.get('t')
66
+ in_ref = (t - self.t_last_spike.value) <= taurefr
67
+ V = u.math.where(in_ref, self.V.value, V)
68
+
69
+ # spike
70
+ spike = V >= theta
71
+ self.V.value = u.math.where(spike, Vr, V)
72
+ self.t_last_spike.value = u.math.where(spike, t, self.t_last_spike.value)
73
+ return spike
74
+
75
+
76
+ class Net(brainstate.nn.Module):
77
+ def __init__(self, num):
78
+ super().__init__()
79
+ self.group = LIF(num)
80
+ self.delay = brainstate.nn.Delay(jax.ShapeDtypeStruct((num,), bool), delta)
81
+ self.syn = brainpy.state.DeltaProj(
82
+ comm=brainstate.nn.EventFixedProb(num, num, sparseness, -J),
83
+ post=self.group
84
+ )
85
+
86
+ def update(self, t, i):
87
+ with brainstate.environ.context(t=t, i=i):
88
+ self.syn(self.delay.retrieve_at_step(jax.numpy.asarray(delta / brainstate.environ.get_dt(), dtype=int)))
89
+ spike = self.group()
90
+ self.delay(spike)
91
+ return spike
92
+
93
+
94
+ with brainstate.environ.context(dt=0.1 * u.ms):
95
+ # initialize network
96
+ net = Net(N)
97
+ brainstate.nn.init_all_states(net)
98
+
99
+ # simulation
100
+ times = u.math.arange(0. * u.ms, duration, brainstate.environ.get_dt())
101
+ indices = u.math.arange(times.size)
102
+ spikes = brainstate.transform.for_loop(net.update, times, indices, pbar=brainstate.transform.ProgressBar(10))
103
+
104
+ # visualization
105
+ times = times.to_decimal(u.ms)
106
+ t_indices, n_indices = u.math.where(spikes)
107
+ plt.scatter(times[t_indices], n_indices, s=1)
108
+ plt.xlabel('Time (ms)')
109
+ plt.ylabel('Neuron index')
110
+ plt.xlim([0, duration.to_decimal(u.ms)])
111
+ plt.show()