brainx-skill 1.0.15 → 1.0.17

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 (180) hide show
  1. package/README.md +17 -1
  2. package/installation/lib/literature-mcp.js +7 -1
  3. package/manifest.json +1 -1
  4. package/mcp-servers/codex/README.md +46 -20
  5. package/mcp-servers/codex/UPSTREAM.md +20 -16
  6. package/mcp-servers/codex/app-server.mjs +177 -0
  7. package/mcp-servers/codex/cli-invocation.cjs +50 -0
  8. package/mcp-servers/codex/server.mjs +136 -69
  9. package/mcp-servers/codex/skills.json +1 -1
  10. package/mcp-servers/codex/test/fixtures/fake-codex.mjs +80 -3
  11. package/mcp-servers/codex/test/fixtures/run-server.mjs +7 -0
  12. package/mcp-servers/codex/test/server.test.mjs +188 -84
  13. package/package.json +1 -1
  14. package/skills/bio-neuro-lit/SKILL.md +4 -2
  15. package/skills/bio-neuro-lit/references/required-supplements.md +27 -0
  16. package/skills/brainx-acceleration/SKILL.md +30 -437
  17. package/skills/brainx-acceleration/references/audit-and-rewrite-patterns.md +326 -0
  18. package/skills/brainx-general-guard/SKILL.md +24 -8
  19. package/skills/brainx-install/SKILL.md +3 -3
  20. package/skills/brainx-install/references/compatibility-and-release-matching.md +28 -20
  21. package/skills/brainx-install/references/uninstall-and-cleanup.md +11 -4
  22. package/skills/brainx-modeling-loop/SKILL.md +117 -36
  23. package/skills/brainx-modeling-loop/agents/openai.yaml +2 -2
  24. package/skills/brainx-modeling-loop/references/mechanism-comparison.md +62 -0
  25. package/skills/brainx-modeling-loop/references/multiscale-coupling.md +16 -0
  26. package/skills/brainx-modeling-loop/references/paper-reproduction.md +42 -0
  27. package/skills/brainx-modeling-loop/references/parameter-fitting-workflow.md +14 -14
  28. package/skills/brainx-modeling-loop/references/run-experiment.md +1 -1
  29. package/skills/brainx-modeling-loop/references/training-workflow.md +10 -8
  30. package/skills/brainx-visualization/SKILL.md +6 -2
  31. package/skills/brainx-visualization/references/neural-data-visualization.md +1 -1
  32. package/skills/brainx-visualization/references/statistical-and-model-visualization.md +1 -1
  33. package/skills/package-skills/braincell/SKILL.md +23 -14
  34. package/skills/package-skills/braincell/references/braintools/input-current.md +1 -1
  35. package/skills/package-skills/braincell/references/braintools/metric.md +72 -46
  36. package/skills/package-skills/braincell/references/mixions-for-adaptation.md +1 -1
  37. package/skills/package-skills/braincell/references/multicompartment/braincell-manual-morphology-construction.md +1 -1
  38. package/skills/package-skills/braincell/references/multicompartment/cv-policy-reference.md +1 -1
  39. package/skills/package-skills/braincell/references/multicompartment/filter-function-library.md +3 -3
  40. package/skills/package-skills/braincell/references/multicompartment/morphology-io-loading-validation.md +1 -1
  41. package/skills/package-skills/braincell/references/multicompartment/multicompartment-cell-workflow.md +31 -43
  42. package/skills/package-skills/braincell/references/multicompartment/network-workflow.md +49 -0
  43. package/skills/package-skills/braincell/references/multicompartment/probe-reference.md +26 -114
  44. package/skills/package-skills/braincell/references/multicompartment/topology-building-and-visualization.md +40 -28
  45. package/skills/package-skills/braincell/references/scripts/cell_multicompartment_reference.py +13 -17
  46. package/skills/package-skills/brainevent/SKILL.md +0 -3
  47. package/skills/package-skills/brainevent/references/synaptic-plasticity.md +1 -1
  48. package/skills/package-skills/brainmass/SKILL.md +5 -3
  49. package/skills/package-skills/brainmass/references/brainstate/parameter-constraints-regularization.md +9 -7
  50. package/skills/package-skills/brainmass/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
  51. package/skills/package-skills/brainmass/references/braintools/data-preprocessing.md +15 -7
  52. package/skills/package-skills/brainmass/references/braintools/metric.md +72 -46
  53. package/skills/package-skills/brainmass/references/coupling-network-api.md +3 -1
  54. package/skills/package-skills/brainmass/references/fitting-with-objectives-api.md +6 -6
  55. package/skills/package-skills/brainmass/references/horn-task-training.md +9 -9
  56. package/skills/package-skills/brainmass/references/modellibrary.md +12 -10
  57. package/skills/package-skills/brainmass/references/scripts/resting-state-meg-whole-brain-pipeline.py +5 -3
  58. package/skills/package-skills/brainmass/references/scripts/wilson-cowan-ei-dynamics.py +10 -6
  59. package/skills/package-skills/brainmass/references/simulator-input-monitor-api.md +3 -1
  60. package/skills/package-skills/brainmass/references/visualization-analysis-api.md +17 -9
  61. package/skills/package-skills/brainspike/SKILL.md +201 -0
  62. package/skills/package-skills/brainspike/references/braintools/connectivity.md +40 -0
  63. package/skills/package-skills/brainspike/references/braintools/data-preprocessing.md +39 -0
  64. package/skills/package-skills/brainspike/references/braintools/input-current.md +55 -0
  65. package/skills/package-skills/brainspike/references/braintools/metric.md +36 -0
  66. package/skills/package-skills/brainspike/references/braintools/optimizer.md +50 -0
  67. package/skills/package-skills/brainspike/references/braintools/parameter-initializer.md +43 -0
  68. package/skills/package-skills/brainspike/references/braintools/surrogate.md +40 -0
  69. package/skills/package-skills/brainspike/references/migration-boundary.md +38 -0
  70. package/skills/package-skills/brainspike/references/model-and-readout-selection.md +41 -0
  71. package/skills/package-skills/brainspike/references/multirate-coupling.md +31 -0
  72. package/skills/package-skills/brainspike/references/multiscale-composition.md +28 -0
  73. package/skills/package-skills/brainspike/references/native-composition.md +52 -0
  74. package/skills/package-skills/brainspike/references/native-delays.md +34 -0
  75. package/skills/package-skills/brainspike/references/native-projections.md +43 -0
  76. package/skills/package-skills/brainspike/references/native-training.md +36 -0
  77. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/devices.md +33 -33
  78. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/divergence-and-parity.md +15 -15
  79. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/integration-categories.md +1 -1
  80. package/skills/package-skills/brainspike/references/nest-compatible/model-library.md +200 -0
  81. package/skills/package-skills/brainspike/references/nest-compatible/network-building.md +276 -0
  82. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brette_et_al_2007.py +23 -26
  83. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_alpha.py +18 -21
  84. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/brunel_delta.py +16 -19
  85. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/clopath_synapse_spike_pairing.py +11 -12
  86. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/evaluate_tsodyks2_synapse.py +10 -11
  87. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/spatial_gaussex.py +18 -18
  88. package/skills/package-skills/{brainpy-state → brainspike}/references/nest-compatible/scripts/synapsecollection.py +26 -29
  89. package/skills/package-skills/brainspike/references/nest-compatible/synapse-and-connectivity.md +166 -0
  90. package/skills/package-skills/brainspike/references/nest-delay-boundaries.md +31 -0
  91. package/skills/package-skills/brainspike/references/nonlinear-state-sharing.md +26 -0
  92. package/skills/package-skills/{brainpy-state → brainspike}/references/perturbation-experiment-validity.md +2 -2
  93. package/skills/package-skills/brainspike/references/simulator-training.md +61 -0
  94. package/skills/package-skills/brainspike/references/temporal-task-training.md +36 -0
  95. package/skills/package-skills/brainspike/scripts/advanced_native_patterns.py +76 -0
  96. package/skills/package-skills/brainspike/scripts/delay_workflow.py +44 -0
  97. package/skills/package-skills/brainspike/scripts/delayed_cue_training.py +78 -0
  98. package/skills/package-skills/brainspike/scripts/lif_smoke.py +31 -0
  99. package/skills/package-skills/brainspike/scripts/multiscale_workflow.py +35 -0
  100. package/skills/package-skills/brainspike/scripts/native_ei_network.py +47 -0
  101. package/skills/package-skills/brainspike/scripts/native_workflows.py +77 -0
  102. package/skills/package-skills/brainspike/scripts/nest_boundary_workflows.py +108 -0
  103. package/skills/package-skills/brainspike/scripts/train_native_snn.py +65 -0
  104. package/skills/package-skills/brainspike/scripts/train_nest_simulator.py +69 -0
  105. package/skills/package-skills/brainspike/scripts/train_nest_simulator_two_weights.py +220 -0
  106. package/skills/package-skills/brainstate/SKILL.md +16 -21
  107. package/skills/package-skills/brainstate/references/brainstate/brainstate-control-flow-patterns.md +1 -138
  108. package/skills/package-skills/brainstate/references/brainstate/brainstate-transformed-diagnostics.md +1 -1
  109. package/skills/package-skills/brainstate/references/brainstate/delay-buffers.md +45 -0
  110. package/skills/package-skills/brainstate/references/brainstate/parameter-constraints-regularization.md +9 -7
  111. package/skills/package-skills/brainstate/references/brainstate/parameter-transforms-regularizers-catalog.md +4 -4
  112. package/skills/package-skills/brainstate/references/brainstate/randomness-and-reproducibility.md +6 -4
  113. package/skills/package-skills/brainstate/references/brainstate/transformation-grad-expansion.md +4 -4
  114. package/skills/package-skills/brainstate/references/brainstate/transformation-vmap-expansion.md +1 -1
  115. package/skills/package-skills/brainstate/references/braintools-optimizer-reference.md +16 -0
  116. package/skills/package-skills/brainstate/references/libraries/prebuilt-layer-library.md +1 -1
  117. package/skills/package-skills/brainstate/references/simulation-environment.md +5 -5
  118. package/skills/package-skills/braintrace/SKILL.md +17 -38
  119. package/skills/package-skills/braintrace/references/Drtrl.md +9 -26
  120. package/skills/package-skills/braintrace/references/algorithm selection.md +7 -12
  121. package/skills/package-skills/braintrace/references/batching.md +15 -35
  122. package/skills/package-skills/braintrace/references/compiler_internal.md +1 -1
  123. package/skills/package-skills/braintrace/references/custom algorithms.md +1 -2
  124. package/skills/package-skills/braintrace/references/customizing_primitive_transforms.md +26 -15
  125. package/skills/package-skills/braintrace/references/pp_pprop workflow.md +5 -139
  126. package/skills/package-skills/brainunit/SKILL.md +7 -2
  127. package/skills/package-skills/brainunit/references/array-mechanics/functional-structural-api.md +1 -1
  128. package/skills/package-skills/brainunit/references/math-function-library.md +2 -2
  129. package/skills/package-skills/brainunit/references/typing-and-runtime-validation.md +5 -2
  130. package/skills/package-skills/brainevent/references/scripts/102_EI_net_1996.py +0 -107
  131. package/skills/package-skills/brainevent/references/scripts/204_joglekar_2018_propagation.py +0 -168
  132. package/skills/package-skills/brainevent/references/scripts/coba_ei_teaching.py +0 -356
  133. package/skills/package-skills/brainpy-state/SKILL.md +0 -247
  134. package/skills/package-skills/brainpy-state/references/array-creation.md +0 -158
  135. package/skills/package-skills/brainpy-state/references/brain-dynamics-delay-protocol.md +0 -147
  136. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/analysis.md +0 -150
  137. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/brainpy legacy workflow.md +0 -373
  138. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/built-in dynamic neuron model.md +0 -150
  139. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/connecting neurons.md +0 -175
  140. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/customize neuron and synpase.md +0 -286
  141. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Input generation.md +0 -111
  142. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/More about simulation.md +0 -163
  143. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Multi-device array sharding.md +0 -113
  144. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/Parallel experiment execution.md +0 -136
  145. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/array creation and mechanics.md +0 -222
  146. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/brainpy math environment setting.md +0 -123
  147. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/delays.md +0 -107
  148. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/infrastructure/object oriented transformations and control flows.md +0 -185
  149. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/integrators.md +0 -181
  150. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/route activity through connectivity.md +0 -102
  151. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synaptic projections.md +0 -147
  152. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/synpase properties.md +0 -159
  153. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/loss library.md +0 -127
  154. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/optimizers.md +0 -167
  155. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/parameter initializers.md +0 -107
  156. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/prebuilt neural network layers.md +0 -186
  157. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/surrogate gradients.md +0 -104
  158. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainer library.md +0 -89
  159. package/skills/package-skills/brainpy-state/references/brainPy(legacy)/training/trainingworkflows.md +0 -253
  160. package/skills/package-skills/brainpy-state/references/braintools/brainstate-control-flow-patterns.md +0 -334
  161. package/skills/package-skills/brainpy-state/references/braintools/connectivity.md +0 -206
  162. package/skills/package-skills/brainpy-state/references/braintools/data-preprocessing.md +0 -79
  163. package/skills/package-skills/brainpy-state/references/braintools/input-current.md +0 -199
  164. package/skills/package-skills/brainpy-state/references/braintools/metric.md +0 -152
  165. package/skills/package-skills/brainpy-state/references/braintools/optimizer.md +0 -179
  166. package/skills/package-skills/brainpy-state/references/braintools/parameter-initializer.md +0 -183
  167. package/skills/package-skills/brainpy-state/references/braintools/surrogate.md +0 -147
  168. package/skills/package-skills/brainpy-state/references/component-selection.md +0 -288
  169. package/skills/package-skills/brainpy-state/references/nest-compatible/model-library.md +0 -200
  170. package/skills/package-skills/brainpy-state/references/nest-compatible/nest-workflow.md +0 -156
  171. package/skills/package-skills/brainpy-state/references/nest-compatible/network-building.md +0 -264
  172. package/skills/package-skills/brainpy-state/references/nest-compatible/synapse-and-connectivity.md +0 -153
  173. package/skills/package-skills/brainpy-state/references/projection-patterns.md +0 -127
  174. package/skills/package-skills/brainpy-state/references/scripts/103_COBA_2005.py +0 -86
  175. package/skills/package-skills/brainpy-state/references/scripts/106_COBA_HH_2007.py +0 -181
  176. package/skills/package-skills/brainpy-state/references/scripts/107_gamma_oscillation_1996.py +0 -156
  177. package/skills/package-skills/brainpy-state/references/scripts/109_fast_global_oscillation.py +0 -111
  178. package/skills/package-skills/brainpy-state/references/scripts/201_surrogate_grad_lif_fashion_mnist.py +0 -221
  179. package/skills/package-skills/brainpy-state/references/scripts/sound_localization.py +0 -240
  180. package/skills/package-skills/brainpy-state/references/scripts/training-snn.py +0 -119
@@ -1,181 +0,0 @@
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()
@@ -1,156 +0,0 @@
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()
@@ -1,111 +0,0 @@
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()
@@ -1,221 +0,0 @@
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
- Reproduce the results of the``spytorch`` tutorial 2 & 3:
18
-
19
- - https://github.com/surrogate-gradient-learning/spytorch/blob/master/notebooks/SpyTorchTutorial2.ipynb
20
- - https://github.com/surrogate-gradient-learning/spytorch/blob/master/notebooks/SpyTorchTutorial3.ipynb
21
-
22
- """
23
-
24
- import time
25
-
26
- import brainunit as u
27
- import jax.numpy as jnp
28
- import matplotlib.pyplot as plt
29
- import numpy as np
30
- from datasets import load_dataset
31
-
32
- import brainpy
33
- import brainstate
34
- import braintools
35
-
36
- dataset = load_dataset("zalando-datasets/fashion_mnist")
37
-
38
- # images
39
- X_train = np.array(np.stack(dataset['train']['image']), dtype=np.uint8)
40
- X_test = np.array(np.stack(dataset['test']['image']), dtype=np.uint8)
41
- X_train = (X_train / 255).reshape(-1, 28 * 28).astype(jnp.float32)
42
- X_test = (X_test / 255).reshape(-1, 28 * 28).astype(jnp.float32)
43
- print(f'Training image shape: {X_train.shape}, testing image shape: {X_test.shape}')
44
- # labels
45
- Y_train = np.array(dataset['train']['label'], dtype=np.int32)
46
- Y_test = np.array(dataset['test']['label'], dtype=np.int32)
47
-
48
-
49
- class SNN(brainstate.nn.DynamicsGroup):
50
- """
51
- This class implements a spiking neural network model with three layers:
52
-
53
- i >> r >> o
54
-
55
- Each two layers are connected through the exponential synapse model.
56
- """
57
-
58
- def __init__(self, num_in, num_rec, num_out):
59
- super().__init__()
60
-
61
- # parameters
62
- self.num_in = num_in
63
- self.num_rec = num_rec
64
- self.num_out = num_out
65
-
66
- # synapse: i->r
67
- self.i2r = brainstate.nn.Sequential(
68
- brainstate.nn.Linear(num_in, num_rec, w_init=braintools.init.KaimingNormal(scale=40.)),
69
- brainpy.state.Expon(num_rec, tau=10. * u.ms, g_initializer=braintools.init.ZeroInit())
70
- )
71
- # recurrent: r
72
- self.r = brainpy.state.LIF(num_rec, tau=10 * u.ms, V_reset=0 * u.mV, V_rest=0 * u.mV, V_th=1. * u.mV)
73
- # synapse: r->o
74
- self.r2o = brainstate.nn.Sequential(
75
- brainstate.nn.Linear(num_rec, num_out, w_init=braintools.init.KaimingNormal(scale=2.)),
76
- brainpy.state.Expon(num_out, tau=10. * u.ms, g_initializer=braintools.init.ZeroInit())
77
- )
78
-
79
- def update(self, spikes):
80
- r_spikes = self.r(self.i2r(spikes) * u.mA)
81
- out = self.r2o(r_spikes)
82
- return out, r_spikes
83
-
84
- def predict(self, spikes):
85
- r_spikes = self.r(self.i2r(spikes) * u.mA)
86
- out = self.r2o(r_spikes)
87
- return out, r_spikes, self.r.V.value
88
-
89
-
90
- with brainstate.environ.context(dt=1.0 * u.ms):
91
- # inputs
92
- batch_size = 256
93
-
94
- # spiking neural networks
95
- net = SNN(num_in=X_train.shape[-1], num_rec=100, num_out=10)
96
-
97
- # encoding inputs as spikes
98
- encoder = braintools.LatencyEncoder(tau=100 * u.ms)
99
-
100
-
101
- @brainstate.transform.jit
102
- def predict(xs):
103
- brainstate.nn.init_all_states(net, xs.shape[0])
104
- xs = encoder(xs)
105
- outs, spikes, vs = brainstate.transform.for_loop(net.predict, xs)
106
- return outs, spikes, vs
107
-
108
-
109
- def visualize(xs):
110
- # visualization function
111
- outs, spikes, vs = predict(xs)
112
- xs = np.asarray(encoder(xs))
113
- vs = np.asarray(vs.to_decimal(u.mV))
114
- # vs = np.where(spikes, vs, 5.0)
115
- fig, gs = braintools.visualize.get_figure(4, 4, 3., 4.)
116
- for i in range(4):
117
- ax = fig.add_subplot(gs[i, 0])
118
- i_indice, n_indices = np.where(xs[:, i])
119
- ax.plot(i_indice, n_indices, 'r.', markersize=1)
120
- plt.title('Input spikes')
121
- ax = fig.add_subplot(gs[i, 1])
122
- i_indice, n_indices = np.where(spikes[:, i])
123
- ax.plot(i_indice, n_indices, 'r.', markersize=1)
124
- plt.title('Recurrent spikes')
125
- ax = fig.add_subplot(gs[i, 2])
126
- ax.plot(vs[:, i])
127
- plt.title('Membrane potential')
128
- ax = fig.add_subplot(gs[i, 3])
129
- ax.plot(outs[:, i])
130
- plt.title('Output')
131
- plt.show()
132
-
133
-
134
- # visualization of the spiking activity
135
- visualize(X_test[:4])
136
-
137
- # optimizer
138
- optimizer = braintools.optim.Adam(lr=1e-3)
139
- optimizer.register_trainable_weights(net.states(brainstate.ParamState))
140
-
141
-
142
- def loss_fun(xs, ys):
143
- # initialize states
144
- brainstate.nn.init_all_states(net, xs.shape[0])
145
-
146
- # encode inputs
147
- xs = encoder(xs)
148
-
149
- # predictions
150
- outs, r_spikes = brainstate.transform.for_loop(net.update, xs)
151
-
152
- # Here we set up our regularize loss
153
- # The strength parameters here are merely a guess and there should be ample
154
- # room for improvement by tuning these parameters.
155
- l1_loss = 1e-5 * u.math.sum(r_spikes) # L1 loss on total number of spikes
156
- l2_loss = 1e-5 * u.math.mean(
157
- u.math.sum(u.math.sum(r_spikes, axis=0), axis=0) ** 2) # L2 loss on spikes per neuron
158
-
159
- # predictions
160
- predicts = u.math.max(outs, axis=0) # max over time, [T, B, C] -> [B, C]
161
- loss = braintools.metric.softmax_cross_entropy_with_integer_labels(predicts, ys).mean()
162
- correct_n = u.math.sum(ys == u.math.argmax(predicts, axis=1)) # compare to labels
163
- return loss + l2_loss + l1_loss, correct_n
164
-
165
-
166
- @brainstate.transform.jit
167
- def train_fn(xs, ys):
168
- grads, loss, correct_n = brainstate.transform.grad(
169
- loss_fun, net.states(brainstate.ParamState), has_aux=True, return_value=True)(xs, ys)
170
- optimizer.update(grads)
171
- return loss, correct_n
172
-
173
-
174
- n_epoch = 20
175
- train_losses, train_accs = [], []
176
- indices = np.arange(X_train.shape[0])
177
-
178
- for epoch_i in range(n_epoch):
179
- indices = brainstate.random.shuffle(indices)
180
-
181
- # training phase
182
- t0 = time.time()
183
- loss, train_acc = [], 0.
184
- for i in range(0, X_train.shape[0], batch_size):
185
- X = X_train[indices[i: i + batch_size]]
186
- Y = Y_train[indices[i: i + batch_size]]
187
- l, correct_num = train_fn(X, Y)
188
- loss.append(l)
189
- train_acc += correct_num
190
- train_acc /= X_train.shape[0]
191
- train_loss = jnp.mean(jnp.asarray(loss))
192
- optimizer.lr.step_epoch()
193
-
194
- # testing phase
195
- loss, test_acc = [], 0.
196
- for i in range(0, X_test.shape[0], batch_size):
197
- X = X_test[i: i + batch_size]
198
- Y = Y_test[i: i + batch_size]
199
- l, correct_num = loss_fun(X, Y)
200
- loss.append(l)
201
- test_acc += correct_num
202
- test_acc /= X_test.shape[0]
203
- test_loss = jnp.mean(jnp.asarray(loss))
204
-
205
- t = (time.time() - t0) / 60
206
- print(f"Epoch {epoch_i}: train loss={train_loss:.3f}, acc={train_acc:.3f}, "
207
- f"test loss={test_loss:.3f}, acc={test_acc:.3f}, time={t:.2f} min")
208
- train_losses.append(train_loss)
209
- train_accs.append(train_acc)
210
-
211
- fig, gs = braintools.visualize.get_figure(1, 2, 3, 4)
212
- fig.add_subplot(gs[0])
213
- plt.plot(np.asarray(train_losses))
214
- plt.xlabel("Epoch")
215
- plt.ylabel("Loss")
216
- fig.add_subplot(gs[1])
217
- plt.plot(np.asarray(train_accs))
218
- plt.xlabel("Epoch")
219
- plt.ylabel("Accuracy")
220
-
221
- visualize(X_test[:4])