braintools 0.0.2__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 (38) hide show
  1. braintools/__init__.py +27 -0
  2. braintools/functional/__init__.py +25 -0
  3. braintools/functional/_activations.py +733 -0
  4. braintools/functional/_normalization.py +62 -0
  5. braintools/functional/_spikes.py +90 -0
  6. braintools/init/__init__.py +26 -0
  7. braintools/init/_base.py +36 -0
  8. braintools/init/_generic.py +205 -0
  9. braintools/init/_random_inits.py +489 -0
  10. braintools/init/_regular_inits.py +109 -0
  11. braintools/input/__init__.py +27 -0
  12. braintools/input/currents.py +380 -0
  13. braintools/input/currents_test.py +111 -0
  14. braintools/metric/__init__.py +46 -0
  15. braintools/metric/_classification.py +569 -0
  16. braintools/metric/_classification_test.py +625 -0
  17. braintools/metric/_correlation.py +302 -0
  18. braintools/metric/_correlation_test.py +124 -0
  19. braintools/metric/_fenchel_young.py +67 -0
  20. braintools/metric/_fenchel_young_test.py +55 -0
  21. braintools/metric/_firings.py +85 -0
  22. braintools/metric/_firings_test.py +41 -0
  23. braintools/metric/_lfp.py +139 -0
  24. braintools/metric/_ranking.py +163 -0
  25. braintools/metric/_ranking_test.py +242 -0
  26. braintools/metric/_regression.py +425 -0
  27. braintools/metric/_regression_test.py +133 -0
  28. braintools/metric/_smoothing.py +46 -0
  29. braintools/metric/_smoothing_test.py +43 -0
  30. braintools/metric/_util.py +25 -0
  31. braintools/optim/__init__.py +23 -0
  32. braintools/optim/_lr_scheduler.py +482 -0
  33. braintools/optim/_sgd_optimizer.py +1130 -0
  34. braintools-0.0.2.dist-info/LICENSE +202 -0
  35. braintools-0.0.2.dist-info/METADATA +93 -0
  36. braintools-0.0.2.dist-info/RECORD +38 -0
  37. braintools-0.0.2.dist-info/WHEEL +6 -0
  38. braintools-0.0.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,62 @@
1
+ # Copyright 2024- BrainPy 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
+ from __future__ import annotations
17
+ from typing import Sequence, Optional
18
+
19
+ import jax
20
+ import jax.numpy as jnp
21
+ import numpy as np
22
+
23
+
24
+ __all__ = [
25
+ 'weight_standardization',
26
+ ]
27
+
28
+
29
+ def weight_standardization(
30
+ w: jax.typing.ArrayLike,
31
+ axes: Sequence[int],
32
+ eps: float,
33
+ gain: Optional[jax.Array] = None
34
+ ):
35
+ """
36
+ Scaled Weight Standardization.
37
+
38
+ Parameters
39
+ ----------
40
+ w : jax.typing.ArrayLike
41
+ The weight tensor.
42
+ axes : Sequence[int]
43
+ The axes to calculate the mean and variance.
44
+ eps : float
45
+ A small value to avoid division by zero.
46
+ gain : Array
47
+ The gain function, by default None.
48
+
49
+ Returns
50
+ -------
51
+ jax.typing.ArrayLike
52
+ The scaled weight tensor.
53
+
54
+ """
55
+ # Get Scaled WS weight HWIO;
56
+ fan_in = np.prod(w.shape[:-1])
57
+ mean = jnp.mean(w, axis=axes[:-1], keepdims=True)
58
+ var = jnp.var(w, axis=axes[:-1], keepdims=True)
59
+ weight = (w - mean) / (var * fan_in + eps) ** 0.5
60
+ if gain is not None:
61
+ weight = gain * weight
62
+ return weight
@@ -0,0 +1,90 @@
1
+ # Copyright 2024- BrainPy 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
+ from __future__ import annotations
17
+
18
+ __all__ = [
19
+ 'spike_bitwise_or',
20
+ 'spike_bitwise_and',
21
+ 'spike_bitwise_iand',
22
+ 'spike_bitwise_not',
23
+ 'spike_bitwise_xor',
24
+ 'spike_bitwise_ixor',
25
+ 'spike_bitwise',
26
+ ]
27
+
28
+
29
+ def spike_bitwise_or(x, y):
30
+ """Bitwise OR operation for spike tensors."""
31
+ return x + y - x * y
32
+
33
+
34
+ def spike_bitwise_and(x, y):
35
+ """Bitwise AND operation for spike tensors."""
36
+ return x * y
37
+
38
+
39
+ def spike_bitwise_iand(x, y):
40
+ """Bitwise IAND operation for spike tensors."""
41
+ return (1 - x) * y
42
+
43
+
44
+ def spike_bitwise_not(x):
45
+ """Bitwise NOT operation for spike tensors."""
46
+ return 1 - x
47
+
48
+
49
+ def spike_bitwise_xor(x, y):
50
+ """Bitwise XOR operation for spike tensors."""
51
+ return x + y - 2 * x * y
52
+
53
+
54
+ def spike_bitwise_ixor(x, y):
55
+ """Bitwise IXOR operation for spike tensors."""
56
+ return x * (1 - y) + (1 - x) * y
57
+
58
+
59
+ def spike_bitwise(x, y, op: str):
60
+ r"""Bitwise operation for spike tensors.
61
+
62
+ .. math::
63
+
64
+ \begin{array}{ccc}
65
+ \hline \text { Mode } & \text { Expression for } \mathrm{g}(\mathrm{x}, \mathrm{y}) & \text { Code for } \mathrm{g}(\mathrm{x}, \mathrm{y}) \\
66
+ \hline \text { ADD } & x+y & x+y \\
67
+ \text { AND } & x \cap y & x \cdot y \\
68
+ \text { IAND } & (\neg x) \cap y & (1-x) \cdot y \\
69
+ \text { OR } & x \cup y & (x+y)-(x \cdot y) \\
70
+ \hline
71
+ \end{array}
72
+
73
+ Args:
74
+ x: A spike tensor.
75
+ y: A spike tensor.
76
+ op: A string indicating the bitwise operation to perform.
77
+ """
78
+ if op == 'or':
79
+ return spike_bitwise_or(x, y)
80
+ elif op == 'and':
81
+ return spike_bitwise_and(x, y)
82
+ elif op == 'iand':
83
+ return spike_bitwise_iand(x, y)
84
+ elif op == 'xor':
85
+ return spike_bitwise_xor(x, y)
86
+ elif op == 'ixor':
87
+ return spike_bitwise_ixor(x, y)
88
+ else:
89
+ raise NotImplementedError(f"Unsupported bitwise operation: {op}.")
90
+
@@ -0,0 +1,26 @@
1
+ # Copyright 2024- BrainPy 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 ._base import *
18
+ from ._base import __all__ as _base_all
19
+ from ._generic import *
20
+ from ._generic import __all__ as _generic_all
21
+ from ._random_inits import *
22
+ from ._random_inits import __all__ as _random_inits_all
23
+ from ._regular_inits import *
24
+ from ._regular_inits import __all__ as _regular_inits_all
25
+
26
+ __all__ = _generic_all + _base_all + _regular_inits_all + _random_inits_all
@@ -0,0 +1,36 @@
1
+ # Copyright 2024- BrainPy 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 Optional, Tuple
18
+
19
+ import numpy as np
20
+
21
+ __all__ = ['Initializer', 'to_size']
22
+
23
+
24
+ class Initializer(object):
25
+ def __call__(self, *args, **kwargs):
26
+ raise NotImplementedError
27
+
28
+
29
+ def to_size(x) -> Optional[Tuple[int]]:
30
+ if isinstance(x, (tuple, list)):
31
+ return tuple(x)
32
+ if isinstance(x, (int, np.integer)):
33
+ return (x,)
34
+ if x is None:
35
+ return x
36
+ raise ValueError(f'Cannot make a size for {x}')
@@ -0,0 +1,205 @@
1
+ # Copyright 2024- BrainPy 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
+ import numbers
19
+ from typing import Union, Callable, Optional, Sequence
20
+
21
+ import braincore as bc
22
+ import jax
23
+ import jax.numpy as jnp
24
+ import numpy as np
25
+
26
+ from ._base import to_size
27
+
28
+ __all__ = [
29
+ 'parameter',
30
+ 'state',
31
+ 'noise',
32
+ ]
33
+
34
+
35
+ def _is_scalar(x):
36
+ return isinstance(x, numbers.Number)
37
+
38
+
39
+ def parameter(
40
+ param: Union[Callable, np.ndarray, jax.Array, float, int, bool],
41
+ sizes: Union[int, Sequence[int]],
42
+ batch_or_mode: Optional[Union[int, bool, bc.mixin.Mode]] = None,
43
+ allow_none: bool = True,
44
+ allow_scalar: bool = True,
45
+ ):
46
+ """Initialize parameters.
47
+
48
+ Parameters
49
+ ----------
50
+ param: callable, Initializer, bm.ndarray, jnp.ndarray, onp.ndarray, float, int, bool
51
+ The initialization of the parameter.
52
+ - If it is None, the created parameter will be None.
53
+ - If it is a callable function :math:`f`, the ``f(size)`` will be returned.
54
+ - If it is an instance of :py:class:`init.Initializer``, the ``f(size)`` will be returned.
55
+ - If it is a tensor, then this function check whether ``tensor.shape`` is equal to the given ``size``.
56
+ sizes: int, sequence of int
57
+ The shape of the parameter.
58
+ batch_or_mode: int, bool, braincore.mixin.Mode
59
+ The batch size or the mode.
60
+ allow_none: bool
61
+ Whether allow the parameter is None.
62
+ allow_scalar: bool
63
+ Whether allow the parameter is a scalar value.
64
+
65
+ Returns
66
+ -------
67
+ param: ArrayType, float, int, bool, None
68
+ The initialized parameter.
69
+
70
+ See Also
71
+ --------
72
+ variable_, noise, delay
73
+ """
74
+ if param is None:
75
+ if allow_none:
76
+ return None
77
+ else:
78
+ raise ValueError(f'Expect a parameter with type of float, ArrayType, Initializer, or '
79
+ f'Callable function, but we got None. ')
80
+ sizes = list(to_size(sizes))
81
+ if allow_scalar and _is_scalar(param):
82
+ return param
83
+
84
+ batch_axis = None
85
+ batch_size = None
86
+ if isinstance(batch_or_mode, bc.mixin.Mode):
87
+ if batch_or_mode.has(bc.mixin.Batching):
88
+ batch_axis = batch_or_mode.batch_axis
89
+ batch_size = batch_or_mode.batch_size
90
+ elif batch_or_mode in (None, False):
91
+ pass
92
+ elif isinstance(batch_or_mode, int):
93
+ batch_axis = 0
94
+ batch_size = batch_or_mode
95
+ else:
96
+ raise ValueError('Unknown batch_or_mode.')
97
+ if batch_size is not None:
98
+ sizes.insert(batch_axis, batch_size)
99
+
100
+ if callable(param):
101
+ return param(sizes)
102
+ elif isinstance(param, (np.ndarray, jax.Array)):
103
+ param = jnp.asarray(param)
104
+ if batch_size is not None:
105
+ param = jnp.repeat(jnp.expand_dims(param, axis=batch_axis), batch_size, axis=batch_axis)
106
+ elif isinstance(param, bc.State):
107
+ param = param
108
+ if batch_size is not None:
109
+ param = bc.State(jnp.repeat(jnp.expand_dims(param.value, axis=batch_axis), batch_size, axis=batch_axis))
110
+ else:
111
+ raise ValueError(f'Unknown parameter type: {type(param)}')
112
+
113
+ if allow_scalar:
114
+ if param.shape == () or param.shape == (1,):
115
+ return param
116
+ if param.shape != tuple(sizes):
117
+ raise ValueError(f'The shape of the parameters should be {sizes}, but we got {param.shape}')
118
+ return param
119
+
120
+
121
+ def state(
122
+ init: Union[Callable, np.ndarray, jax.Array],
123
+ sizes: Union[int, Sequence[int]] = None,
124
+ batch_or_mode: Optional[Union[int, bool, bc.mixin.Mode]] = None,
125
+ ):
126
+ """
127
+ Initialize a :math:`~.State` from a callable function or a data.
128
+ """
129
+ sizes = to_size(sizes)
130
+
131
+ if callable(init):
132
+ if sizes is None:
133
+ raise ValueError('"varshape" cannot be None when data is a callable function.')
134
+ sizes = list(sizes)
135
+ if isinstance(batch_or_mode, bc.mixin.Mode):
136
+ if batch_or_mode.has(bc.mixin.Batching):
137
+ sizes.insert(batch_or_mode.batch_axis, batch_or_mode.batch_size)
138
+ elif batch_or_mode in (None, False):
139
+ pass
140
+ elif isinstance(batch_or_mode, int):
141
+ sizes.insert(0, batch_or_mode)
142
+ else:
143
+ raise ValueError(f'Unknown batch_size_or_mode: {batch_or_mode}')
144
+ return bc.State(init(sizes))
145
+
146
+ else:
147
+ if sizes is not None:
148
+ if jnp.shape(init) != sizes:
149
+ raise ValueError(f'The shape of "data" {jnp.shape(init)} does not match with "var_shape" {sizes}')
150
+ batch_axis = None
151
+ batch_size = None
152
+ if isinstance(batch_or_mode, bc.mixin.Mode):
153
+ if batch_or_mode.has(bc.mixin.Batching):
154
+ batch_axis = batch_or_mode.batch_axis
155
+ batch_size = batch_or_mode.batch_size
156
+ elif batch_or_mode in (None, False):
157
+ pass
158
+ elif isinstance(batch_or_mode, int):
159
+ batch_axis = 0
160
+ batch_size = batch_or_mode
161
+ else:
162
+ raise ValueError('Unknown batch_size_or_mode.')
163
+ data = bc.State(jnp.repeat(jnp.expand_dims(init, axis=batch_axis), batch_size, axis=batch_axis))
164
+ return data
165
+
166
+
167
+ def noise(
168
+ noises: Optional[Union[int, float, np.ndarray, jax.Array, Callable]],
169
+ size: Union[int, Sequence[int]],
170
+ num_vars: int = 1,
171
+ noise_idx: int = 0,
172
+ ) -> Optional[Callable]:
173
+ """Initialize a noise function.
174
+
175
+ Parameters
176
+ ----------
177
+ noises: Any
178
+ size: Shape
179
+ The size of the noise.
180
+ num_vars: int
181
+ The number of variables.
182
+ noise_idx: int
183
+ The index of the current noise among all noise variables.
184
+
185
+ Returns
186
+ -------
187
+ noise_func: function, None
188
+ The noise function.
189
+
190
+ See Also
191
+ --------
192
+ variable_, parameter, delay
193
+
194
+ """
195
+ if callable(noises):
196
+ return noises
197
+ elif noises is None:
198
+ return None
199
+ else:
200
+ noises = parameter(noises, size, allow_none=False)
201
+ if num_vars > 1:
202
+ noises_ = [None] * num_vars
203
+ noises_[noise_idx] = noises
204
+ noises = tuple(noises_)
205
+ return lambda *args, **kwargs: noises