brainstate 0.1.8__py2.py3-none-any.whl → 0.1.9__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 (133) hide show
  1. brainstate/__init__.py +58 -51
  2. brainstate/_compatible_import.py +148 -148
  3. brainstate/_state.py +1605 -1663
  4. brainstate/_state_test.py +52 -52
  5. brainstate/_utils.py +47 -47
  6. brainstate/augment/__init__.py +30 -30
  7. brainstate/augment/_autograd.py +778 -778
  8. brainstate/augment/_autograd_test.py +1289 -1289
  9. brainstate/augment/_eval_shape.py +99 -99
  10. brainstate/augment/_eval_shape_test.py +38 -38
  11. brainstate/augment/_mapping.py +1060 -1060
  12. brainstate/augment/_mapping_test.py +597 -597
  13. brainstate/augment/_random.py +151 -151
  14. brainstate/compile/__init__.py +38 -38
  15. brainstate/compile/_ad_checkpoint.py +204 -204
  16. brainstate/compile/_ad_checkpoint_test.py +49 -49
  17. brainstate/compile/_conditions.py +256 -256
  18. brainstate/compile/_conditions_test.py +220 -220
  19. brainstate/compile/_error_if.py +92 -92
  20. brainstate/compile/_error_if_test.py +52 -52
  21. brainstate/compile/_jit.py +346 -346
  22. brainstate/compile/_jit_test.py +143 -143
  23. brainstate/compile/_loop_collect_return.py +536 -536
  24. brainstate/compile/_loop_collect_return_test.py +58 -58
  25. brainstate/compile/_loop_no_collection.py +184 -184
  26. brainstate/compile/_loop_no_collection_test.py +50 -50
  27. brainstate/compile/_make_jaxpr.py +888 -888
  28. brainstate/compile/_make_jaxpr_test.py +156 -156
  29. brainstate/compile/_progress_bar.py +202 -202
  30. brainstate/compile/_unvmap.py +159 -159
  31. brainstate/compile/_util.py +147 -147
  32. brainstate/environ.py +563 -563
  33. brainstate/environ_test.py +62 -62
  34. brainstate/functional/__init__.py +27 -26
  35. brainstate/graph/__init__.py +29 -29
  36. brainstate/graph/_graph_node.py +244 -244
  37. brainstate/graph/_graph_node_test.py +73 -73
  38. brainstate/graph/_graph_operation.py +1738 -1738
  39. brainstate/graph/_graph_operation_test.py +563 -563
  40. brainstate/init/__init__.py +26 -26
  41. brainstate/init/_base.py +52 -52
  42. brainstate/init/_generic.py +244 -244
  43. brainstate/init/_random_inits.py +553 -553
  44. brainstate/init/_random_inits_test.py +149 -149
  45. brainstate/init/_regular_inits.py +105 -105
  46. brainstate/init/_regular_inits_test.py +50 -50
  47. brainstate/mixin.py +365 -363
  48. brainstate/mixin_test.py +77 -73
  49. brainstate/nn/__init__.py +135 -131
  50. brainstate/{functional → nn}/_activations.py +808 -813
  51. brainstate/{functional → nn}/_activations_test.py +331 -331
  52. brainstate/nn/_collective_ops.py +514 -514
  53. brainstate/nn/_collective_ops_test.py +43 -43
  54. brainstate/nn/_common.py +178 -178
  55. brainstate/nn/_conv.py +501 -501
  56. brainstate/nn/_conv_test.py +238 -238
  57. brainstate/nn/_delay.py +509 -502
  58. brainstate/nn/_delay_test.py +238 -184
  59. brainstate/nn/_dropout.py +426 -426
  60. brainstate/nn/_dropout_test.py +100 -100
  61. brainstate/nn/_dynamics.py +1343 -1343
  62. brainstate/nn/_dynamics_test.py +78 -78
  63. brainstate/nn/_elementwise.py +1119 -1119
  64. brainstate/nn/_elementwise_test.py +169 -169
  65. brainstate/nn/_embedding.py +58 -58
  66. brainstate/nn/_exp_euler.py +92 -92
  67. brainstate/nn/_exp_euler_test.py +35 -35
  68. brainstate/nn/_fixedprob.py +239 -239
  69. brainstate/nn/_fixedprob_test.py +114 -114
  70. brainstate/nn/_inputs.py +608 -608
  71. brainstate/nn/_linear.py +424 -424
  72. brainstate/nn/_linear_mv.py +83 -83
  73. brainstate/nn/_linear_mv_test.py +120 -120
  74. brainstate/nn/_linear_test.py +107 -107
  75. brainstate/nn/_ltp.py +28 -28
  76. brainstate/nn/_module.py +377 -377
  77. brainstate/nn/_module_test.py +40 -40
  78. brainstate/nn/_neuron.py +705 -705
  79. brainstate/nn/_neuron_test.py +161 -161
  80. brainstate/nn/_normalizations.py +975 -918
  81. brainstate/nn/_normalizations_test.py +73 -73
  82. brainstate/{functional → nn}/_others.py +46 -46
  83. brainstate/nn/_poolings.py +1177 -1177
  84. brainstate/nn/_poolings_test.py +217 -217
  85. brainstate/nn/_projection.py +486 -486
  86. brainstate/nn/_rate_rnns.py +554 -554
  87. brainstate/nn/_rate_rnns_test.py +63 -63
  88. brainstate/nn/_readout.py +209 -209
  89. brainstate/nn/_readout_test.py +53 -53
  90. brainstate/nn/_stp.py +236 -236
  91. brainstate/nn/_synapse.py +505 -505
  92. brainstate/nn/_synapse_test.py +131 -131
  93. brainstate/nn/_synaptic_projection.py +423 -423
  94. brainstate/nn/_synouts.py +162 -162
  95. brainstate/nn/_synouts_test.py +57 -57
  96. brainstate/nn/_utils.py +89 -89
  97. brainstate/nn/metrics.py +388 -388
  98. brainstate/optim/__init__.py +38 -38
  99. brainstate/optim/_base.py +64 -64
  100. brainstate/optim/_lr_scheduler.py +448 -448
  101. brainstate/optim/_lr_scheduler_test.py +50 -50
  102. brainstate/optim/_optax_optimizer.py +152 -152
  103. brainstate/optim/_optax_optimizer_test.py +53 -53
  104. brainstate/optim/_sgd_optimizer.py +1104 -1104
  105. brainstate/random/__init__.py +24 -24
  106. brainstate/random/_rand_funs.py +3616 -3616
  107. brainstate/random/_rand_funs_test.py +567 -567
  108. brainstate/random/_rand_seed.py +210 -210
  109. brainstate/random/_rand_seed_test.py +48 -48
  110. brainstate/random/_rand_state.py +1409 -1409
  111. brainstate/random/_random_for_unit.py +52 -52
  112. brainstate/surrogate.py +1957 -1957
  113. brainstate/transform.py +23 -23
  114. brainstate/typing.py +304 -304
  115. brainstate/util/__init__.py +50 -50
  116. brainstate/util/caller.py +98 -98
  117. brainstate/util/error.py +55 -55
  118. brainstate/util/filter.py +469 -469
  119. brainstate/util/others.py +540 -540
  120. brainstate/util/pretty_pytree.py +945 -945
  121. brainstate/util/pretty_pytree_test.py +159 -159
  122. brainstate/util/pretty_repr.py +328 -328
  123. brainstate/util/pretty_table.py +2954 -2954
  124. brainstate/util/scaling.py +258 -258
  125. brainstate/util/struct.py +523 -523
  126. {brainstate-0.1.8.dist-info → brainstate-0.1.9.dist-info}/METADATA +91 -99
  127. brainstate-0.1.9.dist-info/RECORD +130 -0
  128. {brainstate-0.1.8.dist-info → brainstate-0.1.9.dist-info}/WHEEL +1 -1
  129. {brainstate-0.1.8.dist-info → brainstate-0.1.9.dist-info/licenses}/LICENSE +202 -202
  130. brainstate/functional/_normalization.py +0 -81
  131. brainstate/functional/_spikes.py +0 -204
  132. brainstate-0.1.8.dist-info/RECORD +0 -132
  133. {brainstate-0.1.8.dist-info → brainstate-0.1.9.dist-info}/top_level.txt +0 -0
@@ -1,35 +1,35 @@
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
-
17
- import unittest
18
-
19
- import brainunit as u
20
-
21
- import brainstate
22
-
23
-
24
- class TestExpEuler(unittest.TestCase):
25
- def test1(self):
26
- def fun(x, tau):
27
- return -x / tau
28
-
29
- with brainstate.environ.context(dt=0.1):
30
- with self.assertRaises(AssertionError):
31
- r = brainstate.nn.exp_euler_step(fun, 1.0 * u.mV, 1. * u.ms)
32
-
33
- with brainstate.environ.context(dt=1. * u.ms):
34
- r = brainstate.nn.exp_euler_step(fun, 1.0 * u.mV, 1. * u.ms)
35
- print(r)
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
+
17
+ import unittest
18
+
19
+ import brainunit as u
20
+
21
+ import brainstate
22
+
23
+
24
+ class TestExpEuler(unittest.TestCase):
25
+ def test1(self):
26
+ def fun(x, tau):
27
+ return -x / tau
28
+
29
+ with brainstate.environ.context(dt=0.1):
30
+ with self.assertRaises(AssertionError):
31
+ r = brainstate.nn.exp_euler_step(fun, 1.0 * u.mV, 1. * u.ms)
32
+
33
+ with brainstate.environ.context(dt=1. * u.ms):
34
+ r = brainstate.nn.exp_euler_step(fun, 1.0 * u.mV, 1. * u.ms)
35
+ print(r)
@@ -1,239 +1,239 @@
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
-
17
- from typing import Union, Callable, Optional
18
-
19
- import brainevent
20
- import brainunit as u
21
- import jax
22
- import jax.numpy as jnp
23
- import numpy as np
24
-
25
- from brainstate import random, augment, environ, init
26
- from brainstate._state import ParamState, FakeState
27
- from brainstate.compile import for_loop
28
- from brainstate.typing import Size, ArrayLike
29
- from ._module import Module
30
-
31
- __all__ = [
32
- 'FixedNumConn',
33
- 'EventFixedNumConn',
34
- 'EventFixedProb',
35
- ]
36
-
37
-
38
- def init_indices_without_replace(
39
- conn_num: int,
40
- n_pre: int,
41
- n_post: int,
42
- seed: int | None,
43
- method: str
44
- ):
45
- rng = random.default_rng(seed)
46
-
47
- if method == 'vmap':
48
- @augment.vmap(axis_size=n_pre)
49
- def rand_indices():
50
- return rng.choice(n_post, size=(conn_num,), replace=False)
51
-
52
- return rand_indices()
53
-
54
- elif method == 'for_loop':
55
- return for_loop(
56
- lambda *args: rng.choice(n_post, size=(conn_num,), replace=False),
57
- length=n_pre
58
- )
59
-
60
- else:
61
- raise ValueError(f"Unknown method: {method}")
62
-
63
-
64
- class FixedNumConn(Module):
65
- """
66
- The ``FixedNumConn`` module implements a fixed probability connection with CSR sparse data structure.
67
-
68
- Parameters
69
- ----------
70
- in_size : Size
71
- Number of pre-synaptic neurons, i.e., input size.
72
- out_size : Size
73
- Number of post-synaptic neurons, i.e., output size.
74
- conn_num : float, int
75
- If it is a float, representing the probability of connection, i.e., connection probability.
76
-
77
- If it is an integer, representing the number of connections.
78
- conn_weight : float or callable or jax.Array or brainunit.Quantity
79
- Maximum synaptic conductance, i.e., synaptic weight.
80
- efferent_target : str, optional
81
- The target of the connection. Default is 'post', meaning that each pre-synaptic neuron connects to
82
- a fixed number of post-synaptic neurons. The connection number is determined by the value of ``n_conn``.
83
-
84
- If 'pre', each post-synaptic neuron connects to a fixed number of pre-synaptic neurons.
85
- conn_init : str, optional
86
- The initialization method of the connection weight. Default is 'vmap', meaning that the connection weight
87
- is initialized by parallelized across multiple threads.
88
-
89
- If 'for_loop', the connection weight is initialized by a for loop.
90
- allow_multi_conn : bool, optional
91
- Whether multiple connections are allowed from a single pre-synaptic neuron.
92
- Default is True, meaning that a value of ``a`` can be selected multiple times.
93
- seed: int, optional
94
- Random seed. Default is None. If None, the default random seed will be used.
95
- name : str, optional
96
- Name of the module.
97
- """
98
-
99
- __module__ = 'brainstate.nn'
100
-
101
- def __init__(
102
- self,
103
- in_size: Size,
104
- out_size: Size,
105
- conn_num: Union[int, float],
106
- conn_weight: Union[Callable, ArrayLike],
107
- efferent_target: str = 'post', # 'pre' or 'post'
108
- afferent_ratio: Union[int, float] = 1.,
109
- allow_multi_conn: bool = True,
110
- seed: Optional[int] = None,
111
- name: Optional[str] = None,
112
- conn_init: str = 'vmap', # 'vmap' or 'for_loop'
113
- param_type: type = ParamState,
114
- ):
115
- super().__init__(name=name)
116
-
117
- # network parameters
118
- self.in_size = in_size
119
- self.out_size = out_size
120
- self.efferent_target = efferent_target
121
- assert efferent_target in ('pre', 'post'), 'The target of the connection must be either "pre" or "post".'
122
- assert 0. <= afferent_ratio <= 1., 'Afferent ratio must be in [0, 1].'
123
- if isinstance(conn_num, float):
124
- assert 0. <= conn_num <= 1., 'Connection probability must be in [0, 1].'
125
- conn_num = (int(self.out_size[-1] * conn_num)
126
- if efferent_target == 'post' else
127
- int(self.in_size[-1] * conn_num))
128
- assert isinstance(conn_num, int), 'Connection number must be an integer.'
129
- self.conn_num = conn_num
130
- self.seed = seed
131
- self.allow_multi_conn = allow_multi_conn
132
-
133
- # connections
134
- if self.conn_num >= 1:
135
- if self.efferent_target == 'post':
136
- n_post = self.out_size[-1]
137
- n_pre = self.in_size[-1]
138
- else:
139
- n_post = self.in_size[-1]
140
- n_pre = self.out_size[-1]
141
-
142
- with jax.ensure_compile_time_eval():
143
- if allow_multi_conn:
144
- rng = np.random if seed is None else np.random.RandomState(seed)
145
- indices = rng.randint(0, n_post, size=(n_pre, self.conn_num))
146
- else:
147
- indices = init_indices_without_replace(self.conn_num, n_pre, n_post, seed, conn_init)
148
- indices = u.math.asarray(indices, dtype=environ.ditype())
149
-
150
- if afferent_ratio == 1.:
151
- conn_weight = u.math.asarray(init.param(conn_weight, (n_pre, self.conn_num), allow_none=False))
152
- self.weight = param_type(conn_weight)
153
- csr = (
154
- brainevent.FixedPostNumConn((conn_weight, indices), shape=(n_pre, n_post))
155
- if self.efferent_target == 'post' else
156
- brainevent.FixedPreNumConn((conn_weight, indices), shape=(n_pre, n_post))
157
- )
158
- self.conn = csr
159
-
160
- else:
161
- self.pre_selected = np.random.random(n_pre) < afferent_ratio
162
- indices = indices[self.pre_selected].flatten()
163
- conn_weight = u.math.asarray(init.param(conn_weight, (indices.size,), allow_none=False))
164
- self.weight = param_type(conn_weight)
165
- indptr = (jnp.arange(1, n_pre + 1) * self.conn_num -
166
- jnp.cumsum(~self.pre_selected) * self.conn_num)
167
- indptr = jnp.insert(indptr, 0, 0) # insert 0 at the beginning
168
- csr = (
169
- brainevent.CSR((conn_weight, indices, indptr), shape=(n_pre, n_post))
170
- if self.efferent_target == 'post' else
171
- brainevent.CSC((conn_weight, indices, indptr), shape=(n_pre, n_post))
172
- )
173
- self.conn = csr
174
-
175
- else:
176
- conn_weight = u.math.asarray(init.param(conn_weight, (), allow_none=False))
177
- self.weight = FakeState(conn_weight)
178
-
179
- def update(self, x: jax.Array) -> Union[jax.Array, u.Quantity]:
180
- if self.conn_num >= 1:
181
- csr = self.conn.with_data(self.weight.value)
182
- return x @ csr
183
- else:
184
- weight = self.weight.value
185
- r = u.math.zeros(x.shape[:-1] + (self.out_size[-1],), dtype=weight.dtype)
186
- r = u.maybe_decimal(u.Quantity(r, unit=u.get_unit(weight)))
187
- return u.math.asarray(r, dtype=environ.dftype())
188
-
189
-
190
- class EventFixedNumConn(FixedNumConn):
191
- """
192
- The FixedProb module implements a fixed probability connection with CSR sparse data structure.
193
-
194
- Parameters
195
- ----------
196
- in_size : Size
197
- Number of pre-synaptic neurons, i.e., input size.
198
- out_size : Size
199
- Number of post-synaptic neurons, i.e., output size.
200
- conn_num : float, int
201
- If it is a float, representing the probability of connection, i.e., connection probability.
202
-
203
- If it is an integer, representing the number of connections.
204
- conn_weight : float or callable or jax.Array or brainunit.Quantity
205
- Maximum synaptic conductance, i.e., synaptic weight.
206
- conn_target : str, optional
207
- The target of the connection. Default is 'post', meaning that each pre-synaptic neuron connects to
208
- a fixed number of post-synaptic neurons. The connection number is determined by the value of ``n_conn``.
209
-
210
- If 'pre', each post-synaptic neuron connects to a fixed number of pre-synaptic neurons.
211
- conn_init : str, optional
212
- The initialization method of the connection weight. Default is 'vmap', meaning that the connection weight
213
- is initialized by parallelized across multiple threads.
214
-
215
- If 'for_loop', the connection weight is initialized by a for loop.
216
- allow_multi_conn : bool, optional
217
- Whether multiple connections are allowed from a single pre-synaptic neuron.
218
- Default is True, meaning that a value of ``a`` can be selected multiple times.
219
- seed: int, optional
220
- Random seed. Default is None. If None, the default random seed will be used.
221
- name : str, optional
222
- Name of the module.
223
- """
224
-
225
- __module__ = 'brainstate.nn'
226
-
227
- def update(self, spk: jax.Array) -> Union[jax.Array, u.Quantity]:
228
- if self.conn_num >= 1:
229
- csr = self.conn.with_data(self.weight.value)
230
- return brainevent.EventArray(spk) @ csr
231
- else:
232
- weight = self.weight.value
233
- unit = u.get_unit(weight)
234
- r = jnp.zeros(spk.shape[:-1] + (self.out_size[-1],), dtype=weight.dtype)
235
- r = u.maybe_decimal(u.Quantity(r, unit=unit))
236
- return u.math.asarray(r, dtype=environ.dftype())
237
-
238
-
239
- EventFixedProb = EventFixedNumConn
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
+
17
+ from typing import Union, Callable, Optional
18
+
19
+ import brainevent
20
+ import brainunit as u
21
+ import jax
22
+ import jax.numpy as jnp
23
+ import numpy as np
24
+
25
+ from brainstate import random, augment, environ, init
26
+ from brainstate._state import ParamState, FakeState
27
+ from brainstate.compile import for_loop
28
+ from brainstate.typing import Size, ArrayLike
29
+ from ._module import Module
30
+
31
+ __all__ = [
32
+ 'FixedNumConn',
33
+ 'EventFixedNumConn',
34
+ 'EventFixedProb',
35
+ ]
36
+
37
+
38
+ def init_indices_without_replace(
39
+ conn_num: int,
40
+ n_pre: int,
41
+ n_post: int,
42
+ seed: int | None,
43
+ method: str
44
+ ):
45
+ rng = random.default_rng(seed)
46
+
47
+ if method == 'vmap':
48
+ @augment.vmap(axis_size=n_pre)
49
+ def rand_indices():
50
+ return rng.choice(n_post, size=(conn_num,), replace=False)
51
+
52
+ return rand_indices()
53
+
54
+ elif method == 'for_loop':
55
+ return for_loop(
56
+ lambda *args: rng.choice(n_post, size=(conn_num,), replace=False),
57
+ length=n_pre
58
+ )
59
+
60
+ else:
61
+ raise ValueError(f"Unknown method: {method}")
62
+
63
+
64
+ class FixedNumConn(Module):
65
+ """
66
+ The ``FixedNumConn`` module implements a fixed probability connection with CSR sparse data structure.
67
+
68
+ Parameters
69
+ ----------
70
+ in_size : Size
71
+ Number of pre-synaptic neurons, i.e., input size.
72
+ out_size : Size
73
+ Number of post-synaptic neurons, i.e., output size.
74
+ conn_num : float, int
75
+ If it is a float, representing the probability of connection, i.e., connection probability.
76
+
77
+ If it is an integer, representing the number of connections.
78
+ conn_weight : float or callable or jax.Array or brainunit.Quantity
79
+ Maximum synaptic conductance, i.e., synaptic weight.
80
+ efferent_target : str, optional
81
+ The target of the connection. Default is 'post', meaning that each pre-synaptic neuron connects to
82
+ a fixed number of post-synaptic neurons. The connection number is determined by the value of ``n_conn``.
83
+
84
+ If 'pre', each post-synaptic neuron connects to a fixed number of pre-synaptic neurons.
85
+ conn_init : str, optional
86
+ The initialization method of the connection weight. Default is 'vmap', meaning that the connection weight
87
+ is initialized by parallelized across multiple threads.
88
+
89
+ If 'for_loop', the connection weight is initialized by a for loop.
90
+ allow_multi_conn : bool, optional
91
+ Whether multiple connections are allowed from a single pre-synaptic neuron.
92
+ Default is True, meaning that a value of ``a`` can be selected multiple times.
93
+ seed: int, optional
94
+ Random seed. Default is None. If None, the default random seed will be used.
95
+ name : str, optional
96
+ Name of the module.
97
+ """
98
+
99
+ __module__ = 'brainstate.nn'
100
+
101
+ def __init__(
102
+ self,
103
+ in_size: Size,
104
+ out_size: Size,
105
+ conn_num: Union[int, float],
106
+ conn_weight: Union[Callable, ArrayLike],
107
+ efferent_target: str = 'post', # 'pre' or 'post'
108
+ afferent_ratio: Union[int, float] = 1.,
109
+ allow_multi_conn: bool = True,
110
+ seed: Optional[int] = None,
111
+ name: Optional[str] = None,
112
+ conn_init: str = 'vmap', # 'vmap' or 'for_loop'
113
+ param_type: type = ParamState,
114
+ ):
115
+ super().__init__(name=name)
116
+
117
+ # network parameters
118
+ self.in_size = in_size
119
+ self.out_size = out_size
120
+ self.efferent_target = efferent_target
121
+ assert efferent_target in ('pre', 'post'), 'The target of the connection must be either "pre" or "post".'
122
+ assert 0. <= afferent_ratio <= 1., 'Afferent ratio must be in [0, 1].'
123
+ if isinstance(conn_num, float):
124
+ assert 0. <= conn_num <= 1., 'Connection probability must be in [0, 1].'
125
+ conn_num = (int(self.out_size[-1] * conn_num)
126
+ if efferent_target == 'post' else
127
+ int(self.in_size[-1] * conn_num))
128
+ assert isinstance(conn_num, int), 'Connection number must be an integer.'
129
+ self.conn_num = conn_num
130
+ self.seed = seed
131
+ self.allow_multi_conn = allow_multi_conn
132
+
133
+ # connections
134
+ if self.conn_num >= 1:
135
+ if self.efferent_target == 'post':
136
+ n_post = self.out_size[-1]
137
+ n_pre = self.in_size[-1]
138
+ else:
139
+ n_post = self.in_size[-1]
140
+ n_pre = self.out_size[-1]
141
+
142
+ with jax.ensure_compile_time_eval():
143
+ if allow_multi_conn:
144
+ rng = np.random if seed is None else np.random.RandomState(seed)
145
+ indices = rng.randint(0, n_post, size=(n_pre, self.conn_num))
146
+ else:
147
+ indices = init_indices_without_replace(self.conn_num, n_pre, n_post, seed, conn_init)
148
+ indices = u.math.asarray(indices, dtype=environ.ditype())
149
+
150
+ if afferent_ratio == 1.:
151
+ conn_weight = u.math.asarray(init.param(conn_weight, (n_pre, self.conn_num), allow_none=False))
152
+ self.weight = param_type(conn_weight)
153
+ csr = (
154
+ brainevent.FixedPostNumConn((conn_weight, indices), shape=(n_pre, n_post))
155
+ if self.efferent_target == 'post' else
156
+ brainevent.FixedPreNumConn((conn_weight, indices), shape=(n_pre, n_post))
157
+ )
158
+ self.conn = csr
159
+
160
+ else:
161
+ self.pre_selected = np.random.random(n_pre) < afferent_ratio
162
+ indices = indices[self.pre_selected].flatten()
163
+ conn_weight = u.math.asarray(init.param(conn_weight, (indices.size,), allow_none=False))
164
+ self.weight = param_type(conn_weight)
165
+ indptr = (jnp.arange(1, n_pre + 1) * self.conn_num -
166
+ jnp.cumsum(~self.pre_selected) * self.conn_num)
167
+ indptr = jnp.insert(indptr, 0, 0) # insert 0 at the beginning
168
+ csr = (
169
+ brainevent.CSR((conn_weight, indices, indptr), shape=(n_pre, n_post))
170
+ if self.efferent_target == 'post' else
171
+ brainevent.CSC((conn_weight, indices, indptr), shape=(n_pre, n_post))
172
+ )
173
+ self.conn = csr
174
+
175
+ else:
176
+ conn_weight = u.math.asarray(init.param(conn_weight, (), allow_none=False))
177
+ self.weight = FakeState(conn_weight)
178
+
179
+ def update(self, x: jax.Array) -> Union[jax.Array, u.Quantity]:
180
+ if self.conn_num >= 1:
181
+ csr = self.conn.with_data(self.weight.value)
182
+ return x @ csr
183
+ else:
184
+ weight = self.weight.value
185
+ r = u.math.zeros(x.shape[:-1] + (self.out_size[-1],), dtype=weight.dtype)
186
+ r = u.maybe_decimal(u.Quantity(r, unit=u.get_unit(weight)))
187
+ return u.math.asarray(r, dtype=environ.dftype())
188
+
189
+
190
+ class EventFixedNumConn(FixedNumConn):
191
+ """
192
+ The FixedProb module implements a fixed probability connection with CSR sparse data structure.
193
+
194
+ Parameters
195
+ ----------
196
+ in_size : Size
197
+ Number of pre-synaptic neurons, i.e., input size.
198
+ out_size : Size
199
+ Number of post-synaptic neurons, i.e., output size.
200
+ conn_num : float, int
201
+ If it is a float, representing the probability of connection, i.e., connection probability.
202
+
203
+ If it is an integer, representing the number of connections.
204
+ conn_weight : float or callable or jax.Array or brainunit.Quantity
205
+ Maximum synaptic conductance, i.e., synaptic weight.
206
+ conn_target : str, optional
207
+ The target of the connection. Default is 'post', meaning that each pre-synaptic neuron connects to
208
+ a fixed number of post-synaptic neurons. The connection number is determined by the value of ``n_conn``.
209
+
210
+ If 'pre', each post-synaptic neuron connects to a fixed number of pre-synaptic neurons.
211
+ conn_init : str, optional
212
+ The initialization method of the connection weight. Default is 'vmap', meaning that the connection weight
213
+ is initialized by parallelized across multiple threads.
214
+
215
+ If 'for_loop', the connection weight is initialized by a for loop.
216
+ allow_multi_conn : bool, optional
217
+ Whether multiple connections are allowed from a single pre-synaptic neuron.
218
+ Default is True, meaning that a value of ``a`` can be selected multiple times.
219
+ seed: int, optional
220
+ Random seed. Default is None. If None, the default random seed will be used.
221
+ name : str, optional
222
+ Name of the module.
223
+ """
224
+
225
+ __module__ = 'brainstate.nn'
226
+
227
+ def update(self, spk: jax.Array) -> Union[jax.Array, u.Quantity]:
228
+ if self.conn_num >= 1:
229
+ csr = self.conn.with_data(self.weight.value)
230
+ return brainevent.EventArray(spk) @ csr
231
+ else:
232
+ weight = self.weight.value
233
+ unit = u.get_unit(weight)
234
+ r = jnp.zeros(spk.shape[:-1] + (self.out_size[-1],), dtype=weight.dtype)
235
+ r = u.maybe_decimal(u.Quantity(r, unit=unit))
236
+ return u.math.asarray(r, dtype=environ.dftype())
237
+
238
+
239
+ EventFixedProb = EventFixedNumConn