braintools 0.0.13__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.
- braintools/__init__.py +39 -0
- braintools/_misc.py +42 -0
- braintools/_spike_encoder.py +777 -0
- braintools/_spike_encoder_test.py +483 -0
- braintools/_spike_operation.py +213 -0
- braintools/_spike_operation_test.py +94 -0
- braintools/_transform.py +1150 -0
- braintools/_transform_test.py +197 -0
- braintools/conn/__init__.py +120 -0
- braintools/conn/_base.py +1034 -0
- braintools/conn/_base_test.py +1029 -0
- braintools/conn/_biological.py +296 -0
- braintools/conn/_biological_test.py +480 -0
- braintools/conn/_compartment.py +1705 -0
- braintools/conn/_compartment_test.py +1326 -0
- braintools/conn/_kernel.py +1219 -0
- braintools/conn/_kernel_test.py +1683 -0
- braintools/conn/_random.py +602 -0
- braintools/conn/_random_test.py +872 -0
- braintools/conn/_regular.py +231 -0
- braintools/conn/_regular_test.py +263 -0
- braintools/conn/_spatial.py +1505 -0
- braintools/conn/_spatial_test.py +322 -0
- braintools/conn/_topological.py +1628 -0
- braintools/conn/_topological_test.py +1616 -0
- braintools/file/__init__.py +25 -0
- braintools/file/_matfile.py +77 -0
- braintools/file/_matfile_test.py +148 -0
- braintools/file/_msg_checkpoint.py +845 -0
- braintools/file/_msg_checkpoint_test.py +320 -0
- braintools/init/__init__.py +37 -0
- braintools/init/_distance_base.py +349 -0
- braintools/init/_distance_base_test.py +190 -0
- braintools/init/_distance_impl.py +664 -0
- braintools/init/_distance_impl_test.py +755 -0
- braintools/init/_init_base.py +437 -0
- braintools/init/_init_base_test.py +676 -0
- braintools/init/_init_basic.py +455 -0
- braintools/init/_init_basic_test.py +468 -0
- braintools/init/_init_composite.py +275 -0
- braintools/init/_init_composite_test.py +341 -0
- braintools/init/_init_orthogonal.py +226 -0
- braintools/init/_init_orthogonal_test.py +236 -0
- braintools/init/_init_variance_scaling.py +389 -0
- braintools/init/_init_variance_scaling_test.py +255 -0
- braintools/init/_init_with_distance.py +83 -0
- braintools/init/_init_with_distance_test.py +454 -0
- braintools/input/__init__.py +73 -0
- braintools/input/_composable_base.py +1186 -0
- braintools/input/_composable_base_test.py +588 -0
- braintools/input/_composable_basic.py +634 -0
- braintools/input/_composable_basic_test.py +560 -0
- braintools/input/_composable_pulses.py +870 -0
- braintools/input/_composable_pulses_test.py +548 -0
- braintools/input/_composable_stochastic.py +621 -0
- braintools/input/_composable_stochastic_test.py +561 -0
- braintools/input/_composable_waveforms.py +1156 -0
- braintools/input/_composable_waveforms_test.py +736 -0
- braintools/input/_deprecation.py +142 -0
- braintools/input/_functional_basic.py +607 -0
- braintools/input/_functional_basic_test.py +319 -0
- braintools/input/_functional_pulses.py +720 -0
- braintools/input/_functional_pulses_test.py +393 -0
- braintools/input/_functional_stochastic.py +518 -0
- braintools/input/_functional_stochastic_test.py +337 -0
- braintools/input/_functional_waveforms.py +1172 -0
- braintools/input/_functional_waveforms_test.py +372 -0
- braintools/metric/__init__.py +46 -0
- braintools/metric/_classification.py +1079 -0
- braintools/metric/_classification_test.py +625 -0
- braintools/metric/_correlation.py +556 -0
- braintools/metric/_correlation_test.py +503 -0
- braintools/metric/_fenchel_young.py +122 -0
- braintools/metric/_fenchel_young_test.py +53 -0
- braintools/metric/_firings.py +923 -0
- braintools/metric/_firings_test.py +358 -0
- braintools/metric/_lfp.py +620 -0
- braintools/metric/_lfp_test.py +377 -0
- braintools/metric/_pariwise.py +114 -0
- braintools/metric/_ranking.py +300 -0
- braintools/metric/_ranking_test.py +242 -0
- braintools/metric/_regression.py +822 -0
- braintools/metric/_regression_test.py +131 -0
- braintools/metric/_smoothing.py +165 -0
- braintools/metric/_smoothing_test.py +54 -0
- braintools/metric/_util.py +25 -0
- braintools/optim/__init__.py +31 -0
- braintools/optim/_base.py +54 -0
- braintools/optim/_nevergrad_optimizer.py +342 -0
- braintools/optim/_nevergrad_optimizer_test.py +241 -0
- braintools/optim/_optax_lr_scheduler.py +4818 -0
- braintools/optim/_optax_lr_scheduler_test.py +1886 -0
- braintools/optim/_optax_optimizer.py +4781 -0
- braintools/optim/_optax_optimizer_test.py +3445 -0
- braintools/optim/_scipy_optimizer.py +482 -0
- braintools/optim/_scipy_optimizer_test.py +113 -0
- braintools/optim/_state_uniquifier.py +347 -0
- braintools/optim/_state_uniquifier_test.py +336 -0
- braintools/quad/__init__.py +53 -0
- braintools/quad/_dde_integrator.py +365 -0
- braintools/quad/_dde_integrator_test.py +206 -0
- braintools/quad/_imex_integrator.py +237 -0
- braintools/quad/_imex_integrator_test.py +161 -0
- braintools/quad/_ode_integrator.py +1179 -0
- braintools/quad/_ode_integrator_test.py +180 -0
- braintools/quad/_sde_integrator.py +621 -0
- braintools/quad/_sde_integrator_test.py +200 -0
- braintools/tree.py +514 -0
- braintools/tree_test.py +206 -0
- braintools/visualize/__init__.py +49 -0
- braintools/visualize/_animation.py +149 -0
- braintools/visualize/_colormaps.py +340 -0
- braintools/visualize/_colormaps_test.py +59 -0
- braintools/visualize/_figures.py +58 -0
- braintools/visualize/_interactive.py +898 -0
- braintools/visualize/_interactive_test.py +57 -0
- braintools/visualize/_neural.py +1083 -0
- braintools/visualize/_neural_test.py +116 -0
- braintools/visualize/_plots.py +628 -0
- braintools/visualize/_plots_test.py +72 -0
- braintools/visualize/_statistical.py +1094 -0
- braintools/visualize/_statistical_test.py +121 -0
- braintools/visualize/_style.py +82 -0
- braintools/visualize/_three_d.py +696 -0
- braintools/visualize/_three_d_test.py +63 -0
- braintools/visualize/_visualize_test.py +72 -0
- braintools-0.0.13.dist-info/METADATA +356 -0
- braintools-0.0.13.dist-info/RECORD +131 -0
- braintools-0.0.13.dist-info/WHEEL +5 -0
- braintools-0.0.13.dist-info/licenses/LICENSE +202 -0
- braintools-0.0.13.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,777 @@
|
|
|
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 Optional
|
|
18
|
+
|
|
19
|
+
import brainstate
|
|
20
|
+
import brainunit as u
|
|
21
|
+
import jax
|
|
22
|
+
import jax.numpy as jnp
|
|
23
|
+
import numpy as np
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
'LatencyEncoder',
|
|
27
|
+
'RateEncoder',
|
|
28
|
+
'PoissonEncoder',
|
|
29
|
+
'PopulationEncoder',
|
|
30
|
+
'BernoulliEncoder',
|
|
31
|
+
'DeltaEncoder',
|
|
32
|
+
'StepCurrentEncoder',
|
|
33
|
+
'SpikeCountEncoder',
|
|
34
|
+
'TemporalEncoder',
|
|
35
|
+
'RankOrderEncoder',
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class LatencyEncoder:
|
|
40
|
+
r"""
|
|
41
|
+
Encode the rate input as the spike train using the latency encoding.
|
|
42
|
+
|
|
43
|
+
Use input features to determine time-to-first spike.
|
|
44
|
+
|
|
45
|
+
Expected inputs should be between 0 and 1. If not, the latency encoder will encode ``x``
|
|
46
|
+
(normalized into ``[0, 1]`` according to
|
|
47
|
+
:math:`x_{\text{normalize}} = \frac{x-\text{min_val}}{\text{max_val} - \text{min_val}}`)
|
|
48
|
+
to spikes whose firing time is :math:`0 \le t_f \le \text{num_period}-1`.
|
|
49
|
+
A larger ``x`` will cause the earlier firing time.
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
Example::
|
|
53
|
+
|
|
54
|
+
>>> import jax
|
|
55
|
+
>>> a = jax.numpy.array([0.02, 0.5, 1])
|
|
56
|
+
>>> encoder = LatencyEncoder(method='linear', normalize=True)
|
|
57
|
+
>>> encoder(a, n_time=5)
|
|
58
|
+
Array([[0., 0., 1.],
|
|
59
|
+
[0., 0., 0.],
|
|
60
|
+
[0., 1., 0.],
|
|
61
|
+
[0., 0., 0.],
|
|
62
|
+
[1., 0., 0.]])
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
min_val: float. The minimal value in the given data `x`, used to the data normalization.
|
|
67
|
+
max_val: float. The maximum value in the given data `x`, used to the data normalization.
|
|
68
|
+
method: str. How to convert intensity to firing time. Currently, we support `linear` or `log`.
|
|
69
|
+
- If ``method='linear'``, the firing rate is calculated as
|
|
70
|
+
:math:`t_f(x) = (\text{num_period} - 1)(1 - x)`.
|
|
71
|
+
- If ``method='log'``, the firing rate is calculated as
|
|
72
|
+
:math:`t_f(x) = (\text{num_period} - 1) - ln(\alpha * x + 1)`,
|
|
73
|
+
where :math:`\alpha` satisfies :math:`t_f(1) = \text{num_period} - 1`.
|
|
74
|
+
threshold: float. Input features below the threhold will fire at the
|
|
75
|
+
final time step unless ``clip=True`` in which case they will not
|
|
76
|
+
fire at all, defaults to ``0.01``.
|
|
77
|
+
clip: bool. Option to remove spikes from features that fall
|
|
78
|
+
below the threshold, defaults to ``False``.
|
|
79
|
+
tau: float. RC Time constant for LIF model used to calculate
|
|
80
|
+
firing time, defaults to ``1``.
|
|
81
|
+
normalize: bool. Option to normalize the latency code such that
|
|
82
|
+
the final spike(s) occur within num_steps, defaults to ``False``.
|
|
83
|
+
epsilon: float. A tiny positive value to avoid rounding errors when
|
|
84
|
+
using torch.arange, defaults to ``1e-7``.
|
|
85
|
+
"""
|
|
86
|
+
__module__ = 'braintools'
|
|
87
|
+
|
|
88
|
+
def __init__(
|
|
89
|
+
self,
|
|
90
|
+
min_val: float = None,
|
|
91
|
+
max_val: float = None,
|
|
92
|
+
method: str = 'log',
|
|
93
|
+
threshold: float = 0.01,
|
|
94
|
+
clip: bool = False,
|
|
95
|
+
tau: float = 1. * u.ms,
|
|
96
|
+
normalize: bool = False,
|
|
97
|
+
first_spk_time: float = 0. * u.ms,
|
|
98
|
+
epsilon: float = 1e-7,
|
|
99
|
+
):
|
|
100
|
+
super().__init__()
|
|
101
|
+
|
|
102
|
+
if method not in ['linear', 'log']:
|
|
103
|
+
raise ValueError('The conversion method can only be "linear" and "log".')
|
|
104
|
+
self.method = method
|
|
105
|
+
self.min_val = min_val
|
|
106
|
+
self.max_val = max_val
|
|
107
|
+
if threshold < 0 or threshold > 1:
|
|
108
|
+
raise ValueError(f"``threshold`` [{threshold}] must be between [0, 1]")
|
|
109
|
+
self.threshold = threshold
|
|
110
|
+
self.clip = clip
|
|
111
|
+
self.tau = tau
|
|
112
|
+
self.normalize = normalize
|
|
113
|
+
self.first_spk_time = first_spk_time
|
|
114
|
+
self.first_spk_step = int(u.get_mantissa(first_spk_time) / u.get_mantissa(brainstate.environ.get_dt()))
|
|
115
|
+
self.epsilon = epsilon
|
|
116
|
+
|
|
117
|
+
def __call__(self, data, n_time: Optional[brainstate.typing.ArrayLike] = None):
|
|
118
|
+
"""Generate latency spikes according to the given input data.
|
|
119
|
+
|
|
120
|
+
Ensuring x in [0., 1.].
|
|
121
|
+
|
|
122
|
+
Args:
|
|
123
|
+
data: The rate-based input.
|
|
124
|
+
n_time: float. The total time to generate data. If None, use ``tau`` instead.
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
out: array. The output spiking trains.
|
|
128
|
+
"""
|
|
129
|
+
with jax.ensure_compile_time_eval():
|
|
130
|
+
if n_time is None:
|
|
131
|
+
n_time = self.tau
|
|
132
|
+
tau = n_time if self.normalize else self.tau
|
|
133
|
+
x = data
|
|
134
|
+
if self.min_val is not None and self.max_val is not None:
|
|
135
|
+
x = (x - self.min_val) / (self.max_val - self.min_val)
|
|
136
|
+
|
|
137
|
+
# Calculate the spike time
|
|
138
|
+
dt = brainstate.environ.get_dt()
|
|
139
|
+
dt_val = u.get_mantissa(dt)
|
|
140
|
+
tau_val = u.get_mantissa(tau) if hasattr(tau, 'mantissa') else tau
|
|
141
|
+
first_spk_val = u.get_mantissa(self.first_spk_time)
|
|
142
|
+
|
|
143
|
+
if self.method == 'linear':
|
|
144
|
+
spike_time = (tau_val - first_spk_val - dt_val) * (1 - x) + first_spk_val
|
|
145
|
+
|
|
146
|
+
elif self.method == 'log':
|
|
147
|
+
x = u.math.maximum(x, self.threshold + self.epsilon) # saturates all values below threshold.
|
|
148
|
+
spike_time = (tau_val - first_spk_val - dt_val) * u.math.log(
|
|
149
|
+
x / (x - self.threshold)) + first_spk_val
|
|
150
|
+
|
|
151
|
+
else:
|
|
152
|
+
raise ValueError(f'Unsupported method: {self.method}. Only support "log" and "linear".')
|
|
153
|
+
|
|
154
|
+
# Clip the spike time
|
|
155
|
+
if self.clip:
|
|
156
|
+
spike_time = u.math.where(data < self.threshold, jnp.inf, spike_time)
|
|
157
|
+
spike_steps = u.math.round(spike_time / dt_val).astype(int)
|
|
158
|
+
return brainstate.functional.one_hot(spike_steps, num_classes=int(tau_val / dt_val), axis=0, dtype=x.dtype)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class RateEncoder:
|
|
162
|
+
r"""
|
|
163
|
+
Encode analog values into spike rates using various rate encoding methods.
|
|
164
|
+
|
|
165
|
+
The rate encoder converts continuous input values into spike trains where the
|
|
166
|
+
firing rate is proportional to the input intensity. Higher input values result
|
|
167
|
+
in higher firing rates.
|
|
168
|
+
|
|
169
|
+
Example::
|
|
170
|
+
|
|
171
|
+
>>> import jax.numpy as jnp
|
|
172
|
+
>>> data = jnp.array([0.1, 0.5, 0.9])
|
|
173
|
+
>>> encoder = RateEncoder(gain=100, method='linear')
|
|
174
|
+
>>> spikes = encoder(data, n_time=100)
|
|
175
|
+
>>> firing_rates = jnp.mean(spikes, axis=0) # Should be ~[10, 50, 90] Hz
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
gain: float. Scaling factor to convert normalized input to firing rate (Hz).
|
|
179
|
+
method: str. Rate encoding method ('linear', 'exponential', 'sqrt').
|
|
180
|
+
min_rate: float. Minimum firing rate in Hz.
|
|
181
|
+
max_rate: float. Maximum firing rate in Hz.
|
|
182
|
+
normalize: bool. Whether to normalize inputs to [0, 1] range.
|
|
183
|
+
min_val: float. Minimum value for normalization.
|
|
184
|
+
max_val: float. Maximum value for normalization.
|
|
185
|
+
"""
|
|
186
|
+
__module__ = 'braintools'
|
|
187
|
+
|
|
188
|
+
def __init__(
|
|
189
|
+
self,
|
|
190
|
+
gain: float = 100.0,
|
|
191
|
+
method: str = 'linear',
|
|
192
|
+
min_rate: float = 0.0,
|
|
193
|
+
max_rate: float = None,
|
|
194
|
+
normalize: bool = False,
|
|
195
|
+
min_val: float = None,
|
|
196
|
+
max_val: float = None,
|
|
197
|
+
):
|
|
198
|
+
if method not in ['linear', 'exponential', 'sqrt']:
|
|
199
|
+
raise ValueError('Method must be "linear", "exponential", or "sqrt"')
|
|
200
|
+
|
|
201
|
+
self.gain = gain
|
|
202
|
+
self.method = method
|
|
203
|
+
self.min_rate = min_rate
|
|
204
|
+
self.max_rate = max_rate if max_rate is not None else gain
|
|
205
|
+
self.normalize = normalize
|
|
206
|
+
self.min_val = min_val
|
|
207
|
+
self.max_val = max_val
|
|
208
|
+
|
|
209
|
+
def __call__(self, data, n_time: int):
|
|
210
|
+
"""Generate rate-encoded spikes.
|
|
211
|
+
|
|
212
|
+
Args:
|
|
213
|
+
data: Input array to encode.
|
|
214
|
+
n_time: Number of time steps.
|
|
215
|
+
|
|
216
|
+
Returns:
|
|
217
|
+
Spike trains with shape (n_time, *data.shape).
|
|
218
|
+
"""
|
|
219
|
+
x = data
|
|
220
|
+
if self.normalize and self.min_val is not None and self.max_val is not None:
|
|
221
|
+
x = (x - self.min_val) / (self.max_val - self.min_val)
|
|
222
|
+
|
|
223
|
+
# Convert to rates based on method
|
|
224
|
+
if self.method == 'linear':
|
|
225
|
+
rates = self.min_rate + x * (self.max_rate - self.min_rate)
|
|
226
|
+
elif self.method == 'exponential':
|
|
227
|
+
rates = self.min_rate + (u.math.exp(x) - 1) / (u.math.exp(1) - 1) * (self.max_rate - self.min_rate)
|
|
228
|
+
elif self.method == 'sqrt':
|
|
229
|
+
rates = self.min_rate + u.math.sqrt(x) * (self.max_rate - self.min_rate)
|
|
230
|
+
else:
|
|
231
|
+
raise ValueError(f'Unsupported method: {self.method}.')
|
|
232
|
+
|
|
233
|
+
# Convert rates to probabilities per time step
|
|
234
|
+
dt = brainstate.environ.get_dt()
|
|
235
|
+
dt_val = u.get_mantissa(dt) if hasattr(dt, 'mantissa') else dt
|
|
236
|
+
probs = rates * dt_val / 1000.0 # Convert Hz to probability per ms
|
|
237
|
+
probs = u.math.clip(probs, 0, 1)
|
|
238
|
+
|
|
239
|
+
# Generate spikes using Bernoulli process
|
|
240
|
+
spikes = brainstate.random.bernoulli(probs, size=(n_time,) + data.shape)
|
|
241
|
+
return spikes.astype(data.dtype)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
class PoissonEncoder:
|
|
245
|
+
r"""
|
|
246
|
+
Encode inputs as Poisson spike trains.
|
|
247
|
+
|
|
248
|
+
Generates spike trains where inter-spike intervals follow a Poisson distribution.
|
|
249
|
+
The input intensity determines the rate parameter of the Poisson process.
|
|
250
|
+
|
|
251
|
+
Example::
|
|
252
|
+
|
|
253
|
+
>>> data = jnp.array([10.0, 50.0, 100.0]) # Hz
|
|
254
|
+
>>> encoder = PoissonEncoder()
|
|
255
|
+
>>> spikes = encoder(data, n_time=1000) # 1 second at 1ms resolution
|
|
256
|
+
>>> # Mean spike counts should be ~[10, 50, 100]
|
|
257
|
+
|
|
258
|
+
Args:
|
|
259
|
+
time_window: float. Time window in ms for rate calculation.
|
|
260
|
+
normalize: bool. Whether to treat inputs as rates (False) or normalize to rates (True).
|
|
261
|
+
max_rate: float. Maximum rate when normalizing.
|
|
262
|
+
"""
|
|
263
|
+
__module__ = 'braintools'
|
|
264
|
+
|
|
265
|
+
def __init__(
|
|
266
|
+
self,
|
|
267
|
+
time_window: float = 1000.0, # ms
|
|
268
|
+
normalize: bool = False,
|
|
269
|
+
max_rate: float = 100.0,
|
|
270
|
+
):
|
|
271
|
+
self.time_window = time_window
|
|
272
|
+
self.normalize = normalize
|
|
273
|
+
self.max_rate = max_rate
|
|
274
|
+
|
|
275
|
+
def __call__(self, data, n_time: int):
|
|
276
|
+
"""Generate Poisson spike trains.
|
|
277
|
+
|
|
278
|
+
Args:
|
|
279
|
+
data: Input rates in Hz, or values to normalize to rates.
|
|
280
|
+
n_time: Number of time steps.
|
|
281
|
+
key: JAX random key.
|
|
282
|
+
|
|
283
|
+
Returns:
|
|
284
|
+
Poisson spike trains with shape (n_time, *data.shape).
|
|
285
|
+
"""
|
|
286
|
+
rates = data
|
|
287
|
+
if self.normalize:
|
|
288
|
+
rates = data * self.max_rate
|
|
289
|
+
|
|
290
|
+
dt = brainstate.environ.get_dt() # ms
|
|
291
|
+
dt_val = u.get_mantissa(dt) if hasattr(dt, 'mantissa') else dt
|
|
292
|
+
# Rate parameter for each time step
|
|
293
|
+
lam = rates * dt_val / 1000.0 # Convert Hz to expected spikes per time step
|
|
294
|
+
|
|
295
|
+
# Generate Poisson spikes
|
|
296
|
+
spikes = brainstate.random.poisson(lam, size=(n_time,) + data.shape)
|
|
297
|
+
# Convert to binary spikes (1 if >= 1 spike, 0 otherwise)
|
|
298
|
+
return (spikes > 0).astype(data.dtype)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
class PopulationEncoder:
|
|
302
|
+
r"""
|
|
303
|
+
Encode scalar values using population coding.
|
|
304
|
+
|
|
305
|
+
Each input value is encoded by a population of neurons with overlapping
|
|
306
|
+
receptive fields. The population response forms a bell curve centered
|
|
307
|
+
on the input value.
|
|
308
|
+
|
|
309
|
+
Example::
|
|
310
|
+
|
|
311
|
+
>>> encoder = PopulationEncoder(n_neurons=10, min_val=0, max_val=1)
|
|
312
|
+
>>> spikes = encoder(0.5, n_time=100) # Should peak at neuron 5
|
|
313
|
+
|
|
314
|
+
Args:
|
|
315
|
+
n_neurons: int. Number of neurons in the population.
|
|
316
|
+
min_val: float. Minimum input value.
|
|
317
|
+
max_val: float. Maximum input value.
|
|
318
|
+
sigma: float. Width of receptive fields (standard deviation).
|
|
319
|
+
max_rate: float. Maximum firing rate of neurons.
|
|
320
|
+
"""
|
|
321
|
+
__module__ = 'braintools'
|
|
322
|
+
|
|
323
|
+
def __init__(
|
|
324
|
+
self,
|
|
325
|
+
n_neurons: int,
|
|
326
|
+
min_val: float = 0.0,
|
|
327
|
+
max_val: float = 1.0,
|
|
328
|
+
sigma: float = None,
|
|
329
|
+
max_rate: float = 100.0,
|
|
330
|
+
):
|
|
331
|
+
self.n_neurons = n_neurons
|
|
332
|
+
self.min_val = min_val
|
|
333
|
+
self.max_val = max_val
|
|
334
|
+
self.sigma = sigma if sigma is not None else (max_val - min_val) / (n_neurons - 1)
|
|
335
|
+
self.max_rate = max_rate
|
|
336
|
+
|
|
337
|
+
# Create neuron preferred values (centers of receptive fields)
|
|
338
|
+
self.centers = u.math.linspace(min_val, max_val, n_neurons)
|
|
339
|
+
|
|
340
|
+
def __call__(self, data, n_time: int):
|
|
341
|
+
"""Generate population-encoded spikes.
|
|
342
|
+
|
|
343
|
+
Args:
|
|
344
|
+
data: Input scalar or array to encode.
|
|
345
|
+
n_time: Number of time steps.
|
|
346
|
+
key: JAX random key.
|
|
347
|
+
|
|
348
|
+
Returns:
|
|
349
|
+
Population spike trains with shape (n_time, n_neurons, *data.shape).
|
|
350
|
+
"""
|
|
351
|
+
data = u.math.asarray(data)
|
|
352
|
+
# Calculate distances from each neuron's preferred value
|
|
353
|
+
distances = u.math.abs(data[..., None] - self.centers)
|
|
354
|
+
|
|
355
|
+
# Gaussian activation
|
|
356
|
+
activations = u.math.exp(-0.5 * (distances / self.sigma) ** 2)
|
|
357
|
+
rates = activations * self.max_rate
|
|
358
|
+
|
|
359
|
+
# Convert to spike probabilities
|
|
360
|
+
dt = brainstate.environ.get_dt()
|
|
361
|
+
dt_val = u.get_mantissa(dt) if hasattr(dt, 'mantissa') else dt
|
|
362
|
+
probs = rates * dt_val / 1000.0
|
|
363
|
+
probs = u.math.clip(probs, 0, 1)
|
|
364
|
+
|
|
365
|
+
# Generate spikes
|
|
366
|
+
if data.ndim == 0: # scalar input
|
|
367
|
+
shape = (n_time, self.n_neurons)
|
|
368
|
+
spikes = brainstate.random.bernoulli(probs, size=shape)
|
|
369
|
+
else:
|
|
370
|
+
# For array inputs, we need to handle the shape correctly
|
|
371
|
+
# probs has shape (*data.shape, n_neurons)
|
|
372
|
+
# We want output shape (n_time, n_neurons, *data.shape)
|
|
373
|
+
shape = (n_time,) + probs.shape
|
|
374
|
+
spikes = brainstate.random.bernoulli(probs, size=shape)
|
|
375
|
+
# Transpose to get (n_time, n_neurons, *data.shape)
|
|
376
|
+
axes = (0, data.ndim + 1) + tuple(range(1, data.ndim + 1))
|
|
377
|
+
spikes = u.math.transpose(spikes, axes)
|
|
378
|
+
|
|
379
|
+
return spikes.astype(u.math.float32)
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
class BernoulliEncoder:
|
|
383
|
+
r"""
|
|
384
|
+
Encode inputs using independent Bernoulli processes.
|
|
385
|
+
|
|
386
|
+
Each input value is converted to a probability, and spikes are generated
|
|
387
|
+
independently at each time step according to this probability.
|
|
388
|
+
|
|
389
|
+
Example::
|
|
390
|
+
|
|
391
|
+
>>> encoder = BernoulliEncoder()
|
|
392
|
+
>>> data = jnp.array([0.1, 0.5, 0.9])
|
|
393
|
+
>>> spikes = encoder(data, n_time=1000)
|
|
394
|
+
>>> # Spike rates should be ~[100, 500, 900] Hz
|
|
395
|
+
|
|
396
|
+
Args:
|
|
397
|
+
scale: float. Scaling factor for input-to-probability conversion.
|
|
398
|
+
normalize: bool. Whether to normalize inputs to [0, 1].
|
|
399
|
+
min_val: float. Minimum value for normalization.
|
|
400
|
+
max_val: float. Maximum value for normalization.
|
|
401
|
+
"""
|
|
402
|
+
__module__ = 'braintools'
|
|
403
|
+
|
|
404
|
+
def __init__(
|
|
405
|
+
self,
|
|
406
|
+
scale: float = 1.0,
|
|
407
|
+
normalize: bool = True,
|
|
408
|
+
min_val: float = None,
|
|
409
|
+
max_val: float = None,
|
|
410
|
+
):
|
|
411
|
+
self.scale = scale
|
|
412
|
+
self.normalize = normalize
|
|
413
|
+
self.min_val = min_val
|
|
414
|
+
self.max_val = max_val
|
|
415
|
+
|
|
416
|
+
def __call__(self, data, n_time: int):
|
|
417
|
+
"""Generate Bernoulli-encoded spikes.
|
|
418
|
+
|
|
419
|
+
Args:
|
|
420
|
+
data: Input probabilities or values to normalize.
|
|
421
|
+
n_time: Number of time steps.
|
|
422
|
+
key: JAX random key.
|
|
423
|
+
|
|
424
|
+
Returns:
|
|
425
|
+
Bernoulli spike trains with shape (n_time, *data.shape).
|
|
426
|
+
"""
|
|
427
|
+
x = data
|
|
428
|
+
if self.normalize and self.min_val is not None and self.max_val is not None:
|
|
429
|
+
x = (x - self.min_val) / (self.max_val - self.min_val)
|
|
430
|
+
|
|
431
|
+
probs = x * self.scale
|
|
432
|
+
probs = u.math.clip(probs, 0, 1)
|
|
433
|
+
|
|
434
|
+
spikes = brainstate.random.bernoulli(probs, size=(n_time,) + data.shape)
|
|
435
|
+
return spikes.astype(data.dtype)
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
class DeltaEncoder:
|
|
439
|
+
r"""
|
|
440
|
+
Encode temporal differences (delta changes) in input signals.
|
|
441
|
+
|
|
442
|
+
Generates spikes when the input signal changes significantly between
|
|
443
|
+
time steps. Useful for encoding dynamic signals and temporal patterns.
|
|
444
|
+
|
|
445
|
+
Example::
|
|
446
|
+
|
|
447
|
+
>>> # Encode a changing signal
|
|
448
|
+
>>> time_series = jnp.array([0, 0.1, 0.8, 0.7, 0.2])
|
|
449
|
+
>>> encoder = DeltaEncoder(threshold=0.1)
|
|
450
|
+
>>> spikes = encoder(time_series) # Spikes at significant changes
|
|
451
|
+
|
|
452
|
+
Args:
|
|
453
|
+
threshold: float. Minimum change required to generate a spike.
|
|
454
|
+
positive_only: bool. Whether to encode only positive changes.
|
|
455
|
+
absolute: bool. Whether to use absolute value of changes.
|
|
456
|
+
normalize: bool. Whether to normalize the input signal.
|
|
457
|
+
"""
|
|
458
|
+
__module__ = 'braintools'
|
|
459
|
+
|
|
460
|
+
def __init__(
|
|
461
|
+
self,
|
|
462
|
+
threshold: float = 0.1,
|
|
463
|
+
positive_only: bool = False,
|
|
464
|
+
absolute: bool = False,
|
|
465
|
+
normalize: bool = True,
|
|
466
|
+
):
|
|
467
|
+
self.threshold = threshold
|
|
468
|
+
self.positive_only = positive_only
|
|
469
|
+
self.absolute = absolute
|
|
470
|
+
self.normalize = normalize
|
|
471
|
+
|
|
472
|
+
def __call__(self, data):
|
|
473
|
+
"""Generate delta-encoded spikes.
|
|
474
|
+
|
|
475
|
+
Args:
|
|
476
|
+
data: Time series data with shape (n_time, *features).
|
|
477
|
+
|
|
478
|
+
Returns:
|
|
479
|
+
Delta spike trains with same shape as input.
|
|
480
|
+
"""
|
|
481
|
+
if data.ndim == 1:
|
|
482
|
+
data = data[..., None] # Add feature dimension
|
|
483
|
+
|
|
484
|
+
x = data
|
|
485
|
+
if self.normalize:
|
|
486
|
+
x_min, x_max = u.math.min(x, axis=0, keepdims=True), u.math.max(x, axis=0, keepdims=True)
|
|
487
|
+
x = (x - x_min) / (x_max - x_min + 1e-8)
|
|
488
|
+
|
|
489
|
+
# Calculate differences
|
|
490
|
+
diffs = u.math.diff(x, axis=0, prepend=x[0:1])
|
|
491
|
+
|
|
492
|
+
if self.absolute:
|
|
493
|
+
diffs = u.math.abs(diffs)
|
|
494
|
+
elif self.positive_only:
|
|
495
|
+
diffs = u.math.maximum(diffs, 0)
|
|
496
|
+
|
|
497
|
+
# Generate spikes where changes exceed threshold
|
|
498
|
+
spikes = (u.math.abs(diffs) >= self.threshold).astype(data.dtype)
|
|
499
|
+
|
|
500
|
+
return spikes.squeeze() if data.shape[-1] == 1 else spikes
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
class StepCurrentEncoder:
|
|
504
|
+
r"""
|
|
505
|
+
Encode inputs as step current injections for LIF neurons.
|
|
506
|
+
|
|
507
|
+
Converts input values to constant current levels that can be injected
|
|
508
|
+
into integrate-and-fire neurons. The current amplitude determines the
|
|
509
|
+
firing rate of the neuron.
|
|
510
|
+
|
|
511
|
+
Example::
|
|
512
|
+
|
|
513
|
+
>>> encoder = StepCurrentEncoder(current_scale=10.0)
|
|
514
|
+
>>> currents = encoder(jnp.array([0.1, 0.5, 1.0]), n_time=100)
|
|
515
|
+
>>> # Returns current levels [1.0, 5.0, 10.0] nA
|
|
516
|
+
|
|
517
|
+
Args:
|
|
518
|
+
current_scale: float. Scaling factor to convert inputs to current (nA).
|
|
519
|
+
offset: float. Baseline current offset.
|
|
520
|
+
normalize: bool. Whether to normalize inputs.
|
|
521
|
+
min_val: float. Minimum value for normalization.
|
|
522
|
+
max_val: float. Maximum value for normalization.
|
|
523
|
+
"""
|
|
524
|
+
__module__ = 'braintools'
|
|
525
|
+
|
|
526
|
+
def __init__(
|
|
527
|
+
self,
|
|
528
|
+
current_scale: float = 10.0, # nA
|
|
529
|
+
offset: float = 0.0,
|
|
530
|
+
normalize: bool = True,
|
|
531
|
+
min_val: float = None,
|
|
532
|
+
max_val: float = None,
|
|
533
|
+
):
|
|
534
|
+
self.current_scale = current_scale
|
|
535
|
+
self.offset = offset
|
|
536
|
+
self.normalize = normalize
|
|
537
|
+
self.min_val = min_val
|
|
538
|
+
self.max_val = max_val
|
|
539
|
+
|
|
540
|
+
def __call__(self, data, n_time: int):
|
|
541
|
+
"""Generate step current signals.
|
|
542
|
+
|
|
543
|
+
Args:
|
|
544
|
+
data: Input values to convert to currents.
|
|
545
|
+
n_time: Number of time steps.
|
|
546
|
+
|
|
547
|
+
Returns:
|
|
548
|
+
Step current signals with shape (n_time, *data.shape).
|
|
549
|
+
"""
|
|
550
|
+
x = data
|
|
551
|
+
if self.normalize and self.min_val is not None and self.max_val is not None:
|
|
552
|
+
x = (x - self.min_val) / (self.max_val - self.min_val)
|
|
553
|
+
|
|
554
|
+
currents = x * self.current_scale + self.offset
|
|
555
|
+
|
|
556
|
+
# Repeat for all time steps
|
|
557
|
+
return u.math.tile(currents, (n_time,) + (1,) * currents.ndim)
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
class SpikeCountEncoder:
|
|
561
|
+
r"""
|
|
562
|
+
Encode inputs as exact spike counts over time windows.
|
|
563
|
+
|
|
564
|
+
Distributes a specific number of spikes (determined by input value)
|
|
565
|
+
randomly or regularly over the encoding time window.
|
|
566
|
+
|
|
567
|
+
Example::
|
|
568
|
+
|
|
569
|
+
>>> encoder = SpikeCountEncoder(max_spikes=10)
|
|
570
|
+
>>> data = jnp.array([0.2, 0.5, 1.0])
|
|
571
|
+
>>> spikes = encoder(data, n_time=100)
|
|
572
|
+
>>> # Should generate [2, 5, 10] total spikes respectively
|
|
573
|
+
|
|
574
|
+
Args:
|
|
575
|
+
max_spikes: int. Maximum number of spikes for input value of 1.0.
|
|
576
|
+
distribution: str. How to distribute spikes ('uniform', 'random').
|
|
577
|
+
normalize: bool. Whether to normalize inputs to [0, 1].
|
|
578
|
+
"""
|
|
579
|
+
__module__ = 'braintools'
|
|
580
|
+
|
|
581
|
+
def __init__(
|
|
582
|
+
self,
|
|
583
|
+
max_spikes: int = 10,
|
|
584
|
+
distribution: str = 'random',
|
|
585
|
+
normalize: bool = True,
|
|
586
|
+
):
|
|
587
|
+
if distribution not in ['uniform', 'random']:
|
|
588
|
+
raise ValueError('Distribution must be "uniform" or "random"')
|
|
589
|
+
|
|
590
|
+
self.max_spikes = max_spikes
|
|
591
|
+
self.distribution = distribution
|
|
592
|
+
self.normalize = normalize
|
|
593
|
+
|
|
594
|
+
def __call__(self, data, n_time: int):
|
|
595
|
+
"""Generate spike count-encoded trains.
|
|
596
|
+
|
|
597
|
+
Args:
|
|
598
|
+
data: Input values determining spike counts.
|
|
599
|
+
n_time: Number of time steps.
|
|
600
|
+
key: JAX random key.
|
|
601
|
+
|
|
602
|
+
Returns:
|
|
603
|
+
Spike trains with exact spike counts.
|
|
604
|
+
"""
|
|
605
|
+
x = data
|
|
606
|
+
if self.normalize:
|
|
607
|
+
x = u.math.clip(x, 0, 1)
|
|
608
|
+
|
|
609
|
+
spike_counts = (x * self.max_spikes).astype(int)
|
|
610
|
+
spikes = u.math.zeros((n_time,) + data.shape, dtype=data.dtype)
|
|
611
|
+
|
|
612
|
+
if self.distribution == 'uniform':
|
|
613
|
+
# Distribute spikes uniformly
|
|
614
|
+
spike_counts_flat = spike_counts.flatten()
|
|
615
|
+
for i in range(data.size):
|
|
616
|
+
idx = np.unravel_index(i, data.shape)
|
|
617
|
+
count = spike_counts_flat[i]
|
|
618
|
+
if count > 0:
|
|
619
|
+
spike_times = u.math.linspace(0, n_time - 1, count).astype(int)
|
|
620
|
+
spikes = spikes.at[(spike_times,) + idx].set(1)
|
|
621
|
+
|
|
622
|
+
elif self.distribution == 'random':
|
|
623
|
+
# Distribute spikes randomly using a simpler approach
|
|
624
|
+
spike_counts_flat = spike_counts.flatten()
|
|
625
|
+
for i in range(data.size):
|
|
626
|
+
idx = jnp.unravel_index(i, data.shape)
|
|
627
|
+
count = int(spike_counts_flat[i])
|
|
628
|
+
if count > 0 and count <= n_time:
|
|
629
|
+
spike_times = brainstate.random.choice(n_time, (count,), replace=False)
|
|
630
|
+
spikes = spikes.at[(spike_times,) + idx].set(1)
|
|
631
|
+
|
|
632
|
+
return spikes
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
class TemporalEncoder:
|
|
636
|
+
r"""
|
|
637
|
+
Encode temporal patterns using synchronized spike timing.
|
|
638
|
+
|
|
639
|
+
Encodes input sequences by mapping values to precise spike times,
|
|
640
|
+
creating temporal patterns that preserve sequence information.
|
|
641
|
+
|
|
642
|
+
Example::
|
|
643
|
+
|
|
644
|
+
>>> encoder = TemporalEncoder(n_patterns=3)
|
|
645
|
+
>>> sequence = jnp.array([0, 1, 2, 1, 0])
|
|
646
|
+
>>> spikes = encoder(sequence) # Creates temporal spike pattern
|
|
647
|
+
|
|
648
|
+
Args:
|
|
649
|
+
n_patterns: int. Number of distinct temporal patterns.
|
|
650
|
+
pattern_length: int. Length of each temporal pattern in time steps.
|
|
651
|
+
jitter: float. Temporal jitter to add to spike times (fraction of pattern_length).
|
|
652
|
+
"""
|
|
653
|
+
__module__ = 'braintools'
|
|
654
|
+
|
|
655
|
+
def __init__(
|
|
656
|
+
self,
|
|
657
|
+
n_patterns: int,
|
|
658
|
+
pattern_length: int = 10,
|
|
659
|
+
jitter: float = 0.1,
|
|
660
|
+
):
|
|
661
|
+
self.n_patterns = n_patterns
|
|
662
|
+
self.pattern_length = pattern_length
|
|
663
|
+
self.jitter = jitter
|
|
664
|
+
|
|
665
|
+
# Pre-define temporal patterns
|
|
666
|
+
self.patterns = self._create_patterns()
|
|
667
|
+
|
|
668
|
+
def _create_patterns(self):
|
|
669
|
+
"""Create distinct temporal patterns for each input value."""
|
|
670
|
+
patterns = {}
|
|
671
|
+
for i in range(self.n_patterns):
|
|
672
|
+
# Create a unique temporal pattern
|
|
673
|
+
pattern_times = u.math.linspace(0, self.pattern_length - 1,
|
|
674
|
+
max(1, int(self.pattern_length * 0.3))).astype(int)
|
|
675
|
+
# Shift pattern based on index
|
|
676
|
+
pattern_times = (pattern_times + i * 2) % self.pattern_length
|
|
677
|
+
patterns[i] = pattern_times
|
|
678
|
+
return patterns
|
|
679
|
+
|
|
680
|
+
def __call__(self, data):
|
|
681
|
+
"""Generate temporally-encoded spikes.
|
|
682
|
+
|
|
683
|
+
Args:
|
|
684
|
+
data: Sequence of integer values to encode.
|
|
685
|
+
key: JAX random key for jitter.
|
|
686
|
+
|
|
687
|
+
Returns:
|
|
688
|
+
Temporal spike patterns with shape (len(data) * pattern_length, n_patterns).
|
|
689
|
+
"""
|
|
690
|
+
sequence_length = len(data)
|
|
691
|
+
total_time = sequence_length * self.pattern_length
|
|
692
|
+
spikes = u.math.zeros((total_time, self.n_patterns))
|
|
693
|
+
|
|
694
|
+
for t, value in enumerate(data):
|
|
695
|
+
if 0 <= value < self.n_patterns:
|
|
696
|
+
pattern_times = self.patterns[int(value)]
|
|
697
|
+
|
|
698
|
+
# Add temporal jitter
|
|
699
|
+
jitter_offset = brainstate.random.randn(*pattern_times.shape) * self.jitter * self.pattern_length
|
|
700
|
+
jittered_times = pattern_times + jitter_offset
|
|
701
|
+
jittered_times = u.math.clip(jittered_times, 0, self.pattern_length - 1).astype(int)
|
|
702
|
+
|
|
703
|
+
# Place spikes in global time
|
|
704
|
+
global_times = t * self.pattern_length + jittered_times
|
|
705
|
+
global_times = u.math.clip(global_times, 0, total_time - 1).astype(int)
|
|
706
|
+
|
|
707
|
+
spikes = spikes.at[global_times, value].set(1)
|
|
708
|
+
|
|
709
|
+
return spikes
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
class RankOrderEncoder:
|
|
713
|
+
r"""
|
|
714
|
+
Encode inputs using rank order coding.
|
|
715
|
+
|
|
716
|
+
Orders input features by their values and generates spikes in rank order.
|
|
717
|
+
The most active features spike first, followed by less active ones.
|
|
718
|
+
This preserves the relative ordering of input features.
|
|
719
|
+
|
|
720
|
+
Example::
|
|
721
|
+
|
|
722
|
+
>>> encoder = RankOrderEncoder()
|
|
723
|
+
>>> data = jnp.array([0.1, 0.8, 0.3, 0.9, 0.2])
|
|
724
|
+
>>> spikes = encoder(data, n_time=10)
|
|
725
|
+
>>> # Feature 3 spikes first (0.9), then feature 1 (0.8), etc.
|
|
726
|
+
|
|
727
|
+
Args:
|
|
728
|
+
use_values: bool. Whether to use actual values for timing or just ranks.
|
|
729
|
+
normalize: bool. Whether to normalize input values.
|
|
730
|
+
invert: bool. Whether to invert the order (smallest first).
|
|
731
|
+
"""
|
|
732
|
+
__module__ = 'braintools'
|
|
733
|
+
|
|
734
|
+
def __init__(
|
|
735
|
+
self,
|
|
736
|
+
use_values: bool = True,
|
|
737
|
+
normalize: bool = True,
|
|
738
|
+
invert: bool = False,
|
|
739
|
+
):
|
|
740
|
+
self.use_values = use_values
|
|
741
|
+
self.normalize = normalize
|
|
742
|
+
self.invert = invert
|
|
743
|
+
|
|
744
|
+
def __call__(self, data, n_time: int):
|
|
745
|
+
"""Generate rank-order encoded spikes.
|
|
746
|
+
|
|
747
|
+
Args:
|
|
748
|
+
data: Input feature vector to encode.
|
|
749
|
+
n_time: Number of time steps available for encoding.
|
|
750
|
+
|
|
751
|
+
Returns:
|
|
752
|
+
Rank-order spike trains with shape (n_time, len(data)).
|
|
753
|
+
"""
|
|
754
|
+
x = data
|
|
755
|
+
if self.normalize:
|
|
756
|
+
x_min, x_max = u.math.min(x), u.math.max(x)
|
|
757
|
+
if x_max > x_min:
|
|
758
|
+
x = (x - x_min) / (x_max - x_min)
|
|
759
|
+
|
|
760
|
+
if self.invert:
|
|
761
|
+
x = 1 - x
|
|
762
|
+
|
|
763
|
+
if self.use_values:
|
|
764
|
+
# Use actual values to determine spike timing
|
|
765
|
+
spike_times = ((1 - x) * (n_time - 1)).astype(int)
|
|
766
|
+
else:
|
|
767
|
+
# Use only ranks
|
|
768
|
+
ranks = u.math.argsort(u.math.argsort(-x)) # Descending rank order
|
|
769
|
+
spike_times = (ranks * (n_time - 1) // len(data)).astype(int)
|
|
770
|
+
|
|
771
|
+
spike_times = u.math.clip(spike_times, 0, n_time - 1)
|
|
772
|
+
|
|
773
|
+
# Create spike trains
|
|
774
|
+
spikes = u.math.zeros((n_time, len(data)), dtype=data.dtype)
|
|
775
|
+
spikes = spikes.at[spike_times, u.math.arange(len(data))].set(1)
|
|
776
|
+
|
|
777
|
+
return spikes
|