brainstate 0.0.2.post20241010__py2.py3-none-any.whl → 0.1.0.post20241122__py2.py3-none-any.whl

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 (184) hide show
  1. benchmark/COBA_2005.py +125 -0
  2. benchmark/CUBA_2005.py +149 -0
  3. brainstate/__init__.py +31 -11
  4. brainstate/_state.py +760 -316
  5. brainstate/_state_test.py +41 -12
  6. brainstate/_utils.py +31 -4
  7. brainstate/augment/__init__.py +40 -0
  8. brainstate/augment/_autograd.py +611 -0
  9. brainstate/augment/_autograd_test.py +1193 -0
  10. brainstate/augment/_eval_shape.py +102 -0
  11. brainstate/augment/_eval_shape_test.py +40 -0
  12. brainstate/augment/_mapping.py +525 -0
  13. brainstate/augment/_mapping_test.py +210 -0
  14. brainstate/augment/_random.py +99 -0
  15. brainstate/{transform → compile}/__init__.py +25 -13
  16. brainstate/compile/_ad_checkpoint.py +204 -0
  17. brainstate/compile/_ad_checkpoint_test.py +51 -0
  18. brainstate/compile/_conditions.py +259 -0
  19. brainstate/compile/_conditions_test.py +221 -0
  20. brainstate/compile/_error_if.py +94 -0
  21. brainstate/compile/_error_if_test.py +54 -0
  22. brainstate/compile/_jit.py +314 -0
  23. brainstate/compile/_jit_test.py +143 -0
  24. brainstate/compile/_loop_collect_return.py +516 -0
  25. brainstate/compile/_loop_collect_return_test.py +59 -0
  26. brainstate/compile/_loop_no_collection.py +185 -0
  27. brainstate/compile/_loop_no_collection_test.py +51 -0
  28. brainstate/compile/_make_jaxpr.py +756 -0
  29. brainstate/compile/_make_jaxpr_test.py +134 -0
  30. brainstate/compile/_progress_bar.py +111 -0
  31. brainstate/compile/_unvmap.py +159 -0
  32. brainstate/compile/_util.py +147 -0
  33. brainstate/environ.py +408 -381
  34. brainstate/environ_test.py +34 -32
  35. brainstate/event/__init__.py +27 -0
  36. brainstate/event/_csr.py +316 -0
  37. brainstate/event/_csr_benchmark.py +14 -0
  38. brainstate/event/_csr_test.py +118 -0
  39. brainstate/event/_fixed_probability.py +708 -0
  40. brainstate/event/_fixed_probability_benchmark.py +128 -0
  41. brainstate/event/_fixed_probability_test.py +131 -0
  42. brainstate/event/_linear.py +359 -0
  43. brainstate/event/_linear_benckmark.py +82 -0
  44. brainstate/event/_linear_test.py +117 -0
  45. brainstate/{nn/event → event}/_misc.py +7 -7
  46. brainstate/event/_xla_custom_op.py +312 -0
  47. brainstate/event/_xla_custom_op_test.py +55 -0
  48. brainstate/functional/_activations.py +521 -511
  49. brainstate/functional/_activations_test.py +300 -300
  50. brainstate/functional/_normalization.py +43 -43
  51. brainstate/functional/_others.py +15 -15
  52. brainstate/functional/_spikes.py +49 -49
  53. brainstate/graph/__init__.py +33 -0
  54. brainstate/graph/_graph_context.py +443 -0
  55. brainstate/graph/_graph_context_test.py +65 -0
  56. brainstate/graph/_graph_convert.py +246 -0
  57. brainstate/graph/_graph_node.py +300 -0
  58. brainstate/graph/_graph_node_test.py +75 -0
  59. brainstate/graph/_graph_operation.py +1746 -0
  60. brainstate/graph/_graph_operation_test.py +724 -0
  61. brainstate/init/_base.py +28 -10
  62. brainstate/init/_generic.py +175 -172
  63. brainstate/init/_random_inits.py +470 -415
  64. brainstate/init/_random_inits_test.py +150 -0
  65. brainstate/init/_regular_inits.py +66 -69
  66. brainstate/init/_regular_inits_test.py +51 -0
  67. brainstate/mixin.py +236 -244
  68. brainstate/mixin_test.py +44 -46
  69. brainstate/nn/__init__.py +26 -51
  70. brainstate/nn/_collective_ops.py +199 -0
  71. brainstate/nn/_dyn_impl/__init__.py +46 -0
  72. brainstate/nn/_dyn_impl/_dynamics_neuron.py +290 -0
  73. brainstate/nn/_dyn_impl/_dynamics_neuron_test.py +162 -0
  74. brainstate/nn/_dyn_impl/_dynamics_synapse.py +315 -0
  75. brainstate/nn/_dyn_impl/_dynamics_synapse_test.py +132 -0
  76. brainstate/nn/_dyn_impl/_inputs.py +154 -0
  77. brainstate/nn/{event/__init__.py → _dyn_impl/_projection_alignpost.py} +8 -8
  78. brainstate/nn/_dyn_impl/_rate_rnns.py +400 -0
  79. brainstate/nn/_dyn_impl/_rate_rnns_test.py +64 -0
  80. brainstate/nn/_dyn_impl/_readout.py +128 -0
  81. brainstate/nn/_dyn_impl/_readout_test.py +54 -0
  82. brainstate/nn/_dynamics/__init__.py +37 -0
  83. brainstate/nn/_dynamics/_dynamics_base.py +631 -0
  84. brainstate/nn/_dynamics/_dynamics_base_test.py +79 -0
  85. brainstate/nn/_dynamics/_projection_base.py +346 -0
  86. brainstate/nn/_dynamics/_state_delay.py +453 -0
  87. brainstate/nn/_dynamics/_synouts.py +161 -0
  88. brainstate/nn/_dynamics/_synouts_test.py +58 -0
  89. brainstate/nn/_elementwise/__init__.py +22 -0
  90. brainstate/nn/_elementwise/_dropout.py +418 -0
  91. brainstate/nn/_elementwise/_dropout_test.py +100 -0
  92. brainstate/nn/_elementwise/_elementwise.py +1122 -0
  93. brainstate/nn/_elementwise/_elementwise_test.py +171 -0
  94. brainstate/nn/_exp_euler.py +97 -0
  95. brainstate/nn/_exp_euler_test.py +36 -0
  96. brainstate/nn/_interaction/__init__.py +41 -0
  97. brainstate/nn/_interaction/_conv.py +499 -0
  98. brainstate/nn/_interaction/_conv_test.py +239 -0
  99. brainstate/nn/_interaction/_embedding.py +59 -0
  100. brainstate/nn/_interaction/_linear.py +582 -0
  101. brainstate/nn/_interaction/_linear_test.py +42 -0
  102. brainstate/nn/_interaction/_normalizations.py +388 -0
  103. brainstate/nn/_interaction/_normalizations_test.py +75 -0
  104. brainstate/nn/_interaction/_poolings.py +1179 -0
  105. brainstate/nn/_interaction/_poolings_test.py +219 -0
  106. brainstate/nn/_module.py +328 -0
  107. brainstate/nn/_module_test.py +211 -0
  108. brainstate/nn/metrics.py +309 -309
  109. brainstate/optim/__init__.py +14 -2
  110. brainstate/optim/_base.py +66 -0
  111. brainstate/optim/_lr_scheduler.py +363 -400
  112. brainstate/optim/_lr_scheduler_test.py +25 -24
  113. brainstate/optim/_optax_optimizer.py +121 -176
  114. brainstate/optim/_optax_optimizer_test.py +41 -1
  115. brainstate/optim/_sgd_optimizer.py +950 -1025
  116. brainstate/random/_rand_funs.py +3269 -3268
  117. brainstate/random/_rand_funs_test.py +568 -0
  118. brainstate/random/_rand_seed.py +149 -117
  119. brainstate/random/_rand_seed_test.py +50 -0
  120. brainstate/random/_rand_state.py +1356 -1321
  121. brainstate/random/_random_for_unit.py +13 -13
  122. brainstate/surrogate.py +1262 -1243
  123. brainstate/{nn/_projection/_utils.py → transform.py} +1 -2
  124. brainstate/typing.py +157 -130
  125. brainstate/util/__init__.py +52 -0
  126. brainstate/util/_caller.py +100 -0
  127. brainstate/util/_dict.py +734 -0
  128. brainstate/util/_dict_test.py +160 -0
  129. brainstate/{nn/_projection/__init__.py → util/_error.py} +9 -13
  130. brainstate/util/_filter.py +178 -0
  131. brainstate/util/_others.py +497 -0
  132. brainstate/util/_pretty_repr.py +208 -0
  133. brainstate/util/_scaling.py +260 -0
  134. brainstate/util/_struct.py +524 -0
  135. brainstate/util/_tracers.py +75 -0
  136. brainstate/{_visualization.py → util/_visualization.py} +16 -16
  137. {brainstate-0.0.2.post20241010.dist-info → brainstate-0.1.0.post20241122.dist-info}/METADATA +11 -11
  138. brainstate-0.1.0.post20241122.dist-info/RECORD +144 -0
  139. {brainstate-0.0.2.post20241010.dist-info → brainstate-0.1.0.post20241122.dist-info}/top_level.txt +1 -0
  140. brainstate/_module.py +0 -1637
  141. brainstate/_module_test.py +0 -207
  142. brainstate/nn/_base.py +0 -251
  143. brainstate/nn/_connections.py +0 -686
  144. brainstate/nn/_dynamics.py +0 -426
  145. brainstate/nn/_elementwise.py +0 -1438
  146. brainstate/nn/_embedding.py +0 -66
  147. brainstate/nn/_misc.py +0 -133
  148. brainstate/nn/_normalizations.py +0 -389
  149. brainstate/nn/_others.py +0 -101
  150. brainstate/nn/_poolings.py +0 -1229
  151. brainstate/nn/_poolings_test.py +0 -231
  152. brainstate/nn/_projection/_align_post.py +0 -546
  153. brainstate/nn/_projection/_align_pre.py +0 -599
  154. brainstate/nn/_projection/_delta.py +0 -241
  155. brainstate/nn/_projection/_vanilla.py +0 -101
  156. brainstate/nn/_rate_rnns.py +0 -410
  157. brainstate/nn/_readout.py +0 -136
  158. brainstate/nn/_synouts.py +0 -166
  159. brainstate/nn/event/csr.py +0 -312
  160. brainstate/nn/event/csr_test.py +0 -118
  161. brainstate/nn/event/fixed_probability.py +0 -276
  162. brainstate/nn/event/fixed_probability_test.py +0 -127
  163. brainstate/nn/event/linear.py +0 -220
  164. brainstate/nn/event/linear_test.py +0 -111
  165. brainstate/random/random_test.py +0 -593
  166. brainstate/transform/_autograd.py +0 -585
  167. brainstate/transform/_autograd_test.py +0 -1181
  168. brainstate/transform/_conditions.py +0 -334
  169. brainstate/transform/_conditions_test.py +0 -220
  170. brainstate/transform/_error_if.py +0 -94
  171. brainstate/transform/_error_if_test.py +0 -55
  172. brainstate/transform/_jit.py +0 -265
  173. brainstate/transform/_jit_test.py +0 -118
  174. brainstate/transform/_loop_collect_return.py +0 -502
  175. brainstate/transform/_loop_no_collection.py +0 -170
  176. brainstate/transform/_make_jaxpr.py +0 -739
  177. brainstate/transform/_make_jaxpr_test.py +0 -131
  178. brainstate/transform/_mapping.py +0 -109
  179. brainstate/transform/_progress_bar.py +0 -111
  180. brainstate/transform/_unvmap.py +0 -143
  181. brainstate/util.py +0 -746
  182. brainstate-0.0.2.post20241010.dist-info/RECORD +0 -87
  183. {brainstate-0.0.2.post20241010.dist-info → brainstate-0.1.0.post20241122.dist-info}/LICENSE +0 -0
  184. {brainstate-0.0.2.post20241010.dist-info → brainstate-0.1.0.post20241122.dist-info}/WHEEL +0 -0
@@ -0,0 +1,290 @@
1
+ # Copyright 2024 BDP 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
+ # -*- coding: utf-8 -*-
17
+
18
+ from __future__ import annotations
19
+
20
+ from typing import Callable, Optional
21
+
22
+ import brainunit as u
23
+ import jax
24
+
25
+ from brainstate import init, surrogate, environ
26
+ from brainstate._state import HiddenState, ShortTermState
27
+ from brainstate.nn._dynamics._dynamics_base import Dynamics
28
+ from brainstate.nn._exp_euler import exp_euler_step
29
+ from brainstate.typing import ArrayLike, Size
30
+
31
+ __all__ = [
32
+ 'Neuron', 'IF', 'LIF', 'LIFRef', 'ALIF',
33
+ ]
34
+
35
+
36
+ class Neuron(Dynamics):
37
+ """
38
+ Base class for neuronal dynamics.
39
+
40
+ All neuron models are differentiable since they use surrogate gradient functions to
41
+ generate the spiking state.
42
+ """
43
+ __module__ = 'brainstate.nn'
44
+
45
+ def __init__(
46
+ self,
47
+ in_size: Size,
48
+ spk_fun: Callable = surrogate.InvSquareGrad(),
49
+ spk_reset: str = 'soft',
50
+ name: Optional[str] = None,
51
+ ):
52
+ super().__init__(in_size, name=name)
53
+ self.spk_reset = spk_reset
54
+ self.spk_fun = spk_fun
55
+
56
+ def get_spike(self, *args, **kwargs):
57
+ raise NotImplementedError
58
+
59
+
60
+ class IF(Neuron):
61
+ """
62
+ Integrate-and-fire neuron model.
63
+ """
64
+
65
+ __module__ = 'brainstate.nn'
66
+
67
+ def __init__(
68
+ self,
69
+ in_size: Size,
70
+ R: ArrayLike = 1. * u.ohm,
71
+ tau: ArrayLike = 5. * u.ms,
72
+ V_th: ArrayLike = 1. * u.mV, # should be positive
73
+ V_initializer: Callable = init.Constant(0. * u.mV),
74
+ spk_fun: Callable = surrogate.ReluGrad(),
75
+ spk_reset: str = 'soft',
76
+ name: str = None,
77
+ ):
78
+ super().__init__(in_size, name=name, spk_fun=spk_fun, spk_reset=spk_reset)
79
+
80
+ # parameters
81
+ self.R = init.param(R, self.varshape)
82
+ self.tau = init.param(tau, self.varshape)
83
+ self.V_th = init.param(V_th, self.varshape)
84
+ self.V_initializer = V_initializer
85
+
86
+ def init_state(self, batch_size: int = None, **kwargs):
87
+ self.V = HiddenState(init.param(self.V_initializer, self.varshape, batch_size))
88
+
89
+ def reset_state(self, batch_size: int = None, **kwargs):
90
+ self.V.value = init.param(self.V_initializer, self.varshape, batch_size)
91
+
92
+ def get_spike(self, V=None):
93
+ V = self.V.value if V is None else V
94
+ v_scaled = (V - self.V_th) / self.V_th
95
+ return self.spk_fun(v_scaled)
96
+
97
+ def update(self, x=0. * u.mA):
98
+ # reset
99
+ last_V = self.V.value
100
+ last_spike = self.get_spike(self.V.value)
101
+ V_th = self.V_th if self.spk_reset == 'soft' else jax.lax.stop_gradient(last_V)
102
+ V = last_V - V_th * last_spike
103
+ # membrane potential
104
+ dv = lambda v: (-v + self.R * self.sum_current_inputs(x, v)) / self.tau
105
+ V = exp_euler_step(dv, V)
106
+ V = self.sum_delta_inputs(V)
107
+ self.V.value = V
108
+ return self.get_spike(V)
109
+
110
+
111
+ class LIF(Neuron):
112
+ """
113
+ Leaky integrate-and-fire neuron model.
114
+ """
115
+ __module__ = 'brainstate.nn'
116
+
117
+ def __init__(
118
+ self,
119
+ in_size: Size,
120
+ R: ArrayLike = 1. * u.ohm,
121
+ tau: ArrayLike = 5. * u.ms,
122
+ V_th: ArrayLike = 1. * u.mV,
123
+ V_reset: ArrayLike = 0. * u.mV,
124
+ V_rest: ArrayLike = 0. * u.mV,
125
+ V_initializer: Callable = init.Constant(0. * u.mV),
126
+ spk_fun: Callable = surrogate.ReluGrad(),
127
+ spk_reset: str = 'soft',
128
+ name: str = None,
129
+ ):
130
+ super().__init__(in_size, name=name, spk_fun=spk_fun, spk_reset=spk_reset)
131
+
132
+ # parameters
133
+ self.R = init.param(R, self.varshape)
134
+ self.tau = init.param(tau, self.varshape)
135
+ self.V_th = init.param(V_th, self.varshape)
136
+ self.V_rest = init.param(V_rest, self.varshape)
137
+ self.V_reset = init.param(V_reset, self.varshape)
138
+ self.V_initializer = V_initializer
139
+
140
+ def init_state(self, batch_size: int = None, **kwargs):
141
+ self.V = HiddenState(init.param(self.V_initializer, self.varshape, batch_size))
142
+
143
+ def reset_state(self, batch_size: int = None, **kwargs):
144
+ self.V.value = init.param(self.V_initializer, self.varshape, batch_size)
145
+
146
+ def get_spike(self, V: ArrayLike = None):
147
+ V = self.V.value if V is None else V
148
+ v_scaled = (V - self.V_th) / (self.V_th - self.V_reset)
149
+ return self.spk_fun(v_scaled)
150
+
151
+ def update(self, x=0. * u.mA):
152
+ last_v = self.V.value
153
+ lst_spk = self.get_spike(last_v)
154
+ V_th = self.V_th if self.spk_reset == 'soft' else jax.lax.stop_gradient(last_v)
155
+ V = last_v - (V_th - self.V_reset) * lst_spk
156
+ # membrane potential
157
+ dv = lambda v: (-v + self.V_rest + self.R * self.sum_current_inputs(x, v)) / self.tau
158
+ V = exp_euler_step(dv, V)
159
+ V = self.sum_delta_inputs(V)
160
+ self.V.value = V
161
+ return self.get_spike(V)
162
+
163
+
164
+ class LIFRef(Neuron):
165
+ """
166
+ Leaky integrate-and-fire neuron model with refractory period.
167
+ """
168
+ __module__ = 'brainstate.nn'
169
+
170
+ def __init__(
171
+ self,
172
+ in_size: Size,
173
+ R: ArrayLike = 1. * u.ohm,
174
+ tau: ArrayLike = 5. * u.ms,
175
+ tau_ref: ArrayLike = 5. * u.ms,
176
+ V_th: ArrayLike = 1. * u.mV,
177
+ V_reset: ArrayLike = 0. * u.mV,
178
+ V_rest: ArrayLike = 0. * u.mV,
179
+ V_initializer: Callable = init.Constant(0. * u.mV),
180
+ spk_fun: Callable = surrogate.ReluGrad(),
181
+ spk_reset: str = 'soft',
182
+ name: str = None,
183
+ ):
184
+ super().__init__(in_size, name=name, spk_fun=spk_fun, spk_reset=spk_reset)
185
+
186
+ # parameters
187
+ self.R = init.param(R, self.varshape)
188
+ self.tau = init.param(tau, self.varshape)
189
+ self.tau_ref = init.param(tau_ref, self.varshape)
190
+ self.V_th = init.param(V_th, self.varshape)
191
+ self.V_rest = init.param(V_rest, self.varshape)
192
+ self.V_reset = init.param(V_reset, self.varshape)
193
+ self.V_initializer = V_initializer
194
+
195
+ def init_state(self, batch_size: int = None, **kwargs):
196
+ self.V = HiddenState(init.param(self.V_initializer, self.varshape, batch_size))
197
+ self.last_spike_time = ShortTermState(init.param(init.Constant(-1e7 * u.ms), self.varshape, batch_size))
198
+
199
+ def reset_state(self, batch_size: int = None, **kwargs):
200
+ self.V.value = init.param(self.V_initializer, self.varshape, batch_size)
201
+ self.last_spike_time.value = init.param(init.Constant(-1e7 * u.ms), self.varshape, batch_size)
202
+
203
+ def get_spike(self, V: ArrayLike = None):
204
+ V = self.V.value if V is None else V
205
+ v_scaled = (V - self.V_th) / (self.V_th - self.V_reset)
206
+ return self.spk_fun(v_scaled)
207
+
208
+ def update(self, x=0. * u.mA):
209
+ t = environ.get('t')
210
+ last_v = self.V.value
211
+ lst_spk = self.get_spike(last_v)
212
+ V_th = self.V_th if self.spk_reset == 'soft' else jax.lax.stop_gradient(last_v)
213
+ last_v = last_v - (V_th - self.V_reset) * lst_spk
214
+ # membrane potential
215
+ dv = lambda v: (-v + self.V_rest + self.R * self.sum_current_inputs(x, v)) / self.tau
216
+ V = exp_euler_step(dv, last_v)
217
+ V = self.sum_delta_inputs(V)
218
+ self.V.value = u.math.where(t - self.last_spike_time.value < self.tau_ref, last_v, V)
219
+ # spike time evaluation
220
+ lst_spk_time = u.math.where(self.V.value >= self.V_th, environ.get('t'), self.last_spike_time.value)
221
+ self.last_spike_time.value = jax.lax.stop_gradient(lst_spk_time)
222
+ return self.get_spike()
223
+
224
+
225
+ class ALIF(Neuron):
226
+ """
227
+ Adaptive Leaky Integrate-and-Fire (LIF) neuron model.
228
+ """
229
+ __module__ = 'brainstate.nn'
230
+
231
+ def __init__(
232
+ self,
233
+ in_size: Size,
234
+ R: ArrayLike = 1. * u.ohm,
235
+ tau: ArrayLike = 5. * u.ms,
236
+ tau_a: ArrayLike = 100. * u.ms,
237
+ V_th: ArrayLike = 1. * u.mV,
238
+ V_reset: ArrayLike = 0. * u.mV,
239
+ V_rest: ArrayLike = 0. * u.mV,
240
+ beta: ArrayLike = 0.1 * u.mV,
241
+ spk_fun: Callable = surrogate.ReluGrad(),
242
+ spk_reset: str = 'soft',
243
+ V_initializer: Callable = init.Constant(0. * u.mV),
244
+ a_initializer: Callable = init.Constant(0.),
245
+ name: str = None,
246
+ ):
247
+ super().__init__(in_size, name=name, spk_fun=spk_fun, spk_reset=spk_reset)
248
+
249
+ # parameters
250
+ self.R = init.param(R, self.varshape)
251
+ self.tau = init.param(tau, self.varshape)
252
+ self.tau_a = init.param(tau_a, self.varshape)
253
+ self.V_th = init.param(V_th, self.varshape)
254
+ self.V_reset = init.param(V_reset, self.varshape)
255
+ self.V_rest = init.param(V_rest, self.varshape)
256
+ self.beta = init.param(beta, self.varshape)
257
+
258
+ # functions
259
+ self.V_initializer = V_initializer
260
+ self.a_initializer = a_initializer
261
+
262
+ def init_state(self, batch_size: int = None, **kwargs):
263
+ self.V = HiddenState(init.param(self.V_initializer, self.varshape, batch_size))
264
+ self.a = HiddenState(init.param(self.a_initializer, self.varshape, batch_size))
265
+
266
+ def reset_state(self, batch_size: int = None, **kwargs):
267
+ self.V.value = init.param(self.V_initializer, self.varshape, batch_size)
268
+ self.a.value = init.param(self.a_initializer, self.varshape, batch_size)
269
+
270
+ def get_spike(self, V=None, a=None):
271
+ V = self.V.value if V is None else V
272
+ a = self.a.value if a is None else a
273
+ v_scaled = (V - self.V_th - self.beta * a) / (self.V_th - self.V_reset)
274
+ return self.spk_fun(v_scaled)
275
+
276
+ def update(self, x=0. * u.mA):
277
+ last_v = self.V.value
278
+ last_a = self.a.value
279
+ lst_spk = self.get_spike(last_v, last_a)
280
+ V_th = self.V_th if self.spk_reset == 'soft' else jax.lax.stop_gradient(last_v)
281
+ V = last_v - (V_th - self.V_reset) * lst_spk
282
+ a = last_a + lst_spk
283
+ # membrane potential
284
+ dv = lambda v: (-v + self.V_rest + self.R * self.sum_current_inputs(x, v)) / self.tau
285
+ da = lambda a: -a / self.tau_a
286
+ V = exp_euler_step(dv, V)
287
+ a = exp_euler_step(da, a)
288
+ self.V.value = self.sum_delta_inputs(V)
289
+ self.a.value = a
290
+ return self.get_spike(self.V.value, self.a.value)
@@ -0,0 +1,162 @@
1
+ # Copyright 2024 BDP 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
+ # -*- coding: utf-8 -*-
17
+
18
+ from __future__ import annotations
19
+
20
+ import unittest
21
+
22
+ import brainunit as u
23
+ import jax
24
+ import jax.numpy as jnp
25
+
26
+ import brainstate as bst
27
+ from brainstate.nn import IF, LIF, ALIF
28
+
29
+
30
+ class TestNeuron(unittest.TestCase):
31
+ def setUp(self):
32
+ self.in_size = 10
33
+ self.batch_size = 5
34
+ self.time_steps = 100
35
+
36
+ def test_neuron_base_class(self):
37
+ with self.assertRaises(NotImplementedError):
38
+ bst.nn.Neuron(self.in_size).get_spike() # Neuron is an abstract base class
39
+
40
+ def generate_input(self):
41
+ return bst.random.randn(self.time_steps, self.batch_size, self.in_size) * u.mA
42
+
43
+ def test_if_neuron(self):
44
+ with bst.environ.context(dt=0.1 * u.ms):
45
+ neuron = IF(self.in_size)
46
+ inputs = self.generate_input()
47
+
48
+ # Test initialization
49
+ self.assertEqual(neuron.in_size, (self.in_size,))
50
+ self.assertEqual(neuron.out_size, (self.in_size,))
51
+
52
+ # Test forward pass
53
+ state = neuron.init_state(self.batch_size)
54
+
55
+ for t in range(self.time_steps):
56
+ out = neuron(inputs[t])
57
+ self.assertEqual(out.shape, (self.batch_size, self.in_size))
58
+
59
+ # Test spike generation
60
+ v = jnp.linspace(-1, 1, 100) * u.mV
61
+ spikes = neuron.get_spike(v)
62
+ self.assertTrue(jnp.all((spikes >= 0) & (spikes <= 1)))
63
+
64
+ def test_lif_neuron(self):
65
+ with bst.environ.context(dt=0.1 * u.ms):
66
+ tau = 20.0 * u.ms
67
+ neuron = LIF(self.in_size, tau=tau)
68
+ inputs = self.generate_input()
69
+
70
+ # Test initialization
71
+ self.assertEqual(neuron.in_size, (self.in_size,))
72
+ self.assertEqual(neuron.out_size, (self.in_size,))
73
+ self.assertEqual(neuron.tau, tau)
74
+
75
+ # Test forward pass
76
+ state = neuron.init_state(self.batch_size)
77
+ call = bst.compile.jit(neuron)
78
+
79
+ for t in range(self.time_steps):
80
+ out = call(inputs[t])
81
+ self.assertEqual(out.shape, (self.batch_size, self.in_size))
82
+
83
+ def test_alif_neuron(self):
84
+ tau = 20.0 * u.ms
85
+ tau_ada = 100.0 * u.ms
86
+ neuron = ALIF(self.in_size, tau=tau, tau_a=tau_ada)
87
+ inputs = self.generate_input()
88
+
89
+ # Test initialization
90
+ self.assertEqual(neuron.in_size, (self.in_size,))
91
+ self.assertEqual(neuron.out_size, (self.in_size,))
92
+ self.assertEqual(neuron.tau, tau)
93
+ self.assertEqual(neuron.tau_a, tau_ada)
94
+
95
+ # Test forward pass
96
+ neuron.init_state(self.batch_size)
97
+ call = bst.compile.jit(neuron)
98
+ with bst.environ.context(dt=0.1 * u.ms):
99
+ for t in range(self.time_steps):
100
+ out = call(inputs[t])
101
+ self.assertEqual(out.shape, (self.batch_size, self.in_size))
102
+
103
+ def test_spike_function(self):
104
+ for NeuronClass in [IF, LIF, ALIF]:
105
+ neuron = NeuronClass(self.in_size)
106
+ neuron.init_state()
107
+ v = jnp.linspace(-1, 1, self.in_size) * u.mV
108
+ spikes = neuron.get_spike(v)
109
+ self.assertTrue(jnp.all((spikes >= 0) & (spikes <= 1)))
110
+
111
+ def test_soft_reset(self):
112
+ for NeuronClass in [IF, LIF, ALIF]:
113
+ neuron = NeuronClass(self.in_size, spk_reset='soft')
114
+ inputs = self.generate_input()
115
+ state = neuron.init_state(self.batch_size)
116
+ call = bst.compile.jit(neuron)
117
+ with bst.environ.context(dt=0.1 * u.ms):
118
+ for t in range(self.time_steps):
119
+ out = call(inputs[t])
120
+ self.assertTrue(jnp.all(neuron.V.value <= neuron.V_th))
121
+
122
+ def test_hard_reset(self):
123
+ for NeuronClass in [IF, LIF, ALIF]:
124
+ neuron = NeuronClass(self.in_size, spk_reset='hard')
125
+ inputs = self.generate_input()
126
+ state = neuron.init_state(self.batch_size)
127
+ call = bst.compile.jit(neuron)
128
+ with bst.environ.context(dt=0.1 * u.ms):
129
+ for t in range(self.time_steps):
130
+ out = call(inputs[t])
131
+ self.assertTrue(jnp.all((neuron.V.value < neuron.V_th) | (neuron.V.value == 0. * u.mV)))
132
+
133
+ def test_detach_spike(self):
134
+ for NeuronClass in [IF, LIF, ALIF]:
135
+ neuron = NeuronClass(self.in_size)
136
+ inputs = self.generate_input()
137
+ state = neuron.init_state(self.batch_size)
138
+ call = bst.compile.jit(neuron)
139
+ with bst.environ.context(dt=0.1 * u.ms):
140
+ for t in range(self.time_steps):
141
+ out = call(inputs[t])
142
+ self.assertFalse(jax.tree_util.tree_leaves(out)[0].aval.weak_type)
143
+
144
+ def test_keep_size(self):
145
+ in_size = (2, 3)
146
+ for NeuronClass in [IF, LIF, ALIF]:
147
+ neuron = NeuronClass(in_size)
148
+ self.assertEqual(neuron.in_size, in_size)
149
+ self.assertEqual(neuron.out_size, in_size)
150
+
151
+ inputs = bst.random.randn(self.time_steps, self.batch_size, *in_size) * u.mA
152
+ state = neuron.init_state(self.batch_size)
153
+ call = bst.compile.jit(neuron)
154
+ with bst.environ.context(dt=0.1 * u.ms):
155
+ for t in range(self.time_steps):
156
+ out = call(inputs[t])
157
+ self.assertEqual(out.shape, (self.batch_size, *in_size))
158
+
159
+
160
+ if __name__ == '__main__':
161
+ with bst.environ.context(dt=0.1):
162
+ unittest.main()