braintools 0.0.10__tar.gz

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 (57) hide show
  1. braintools-0.0.10/LICENSE +202 -0
  2. braintools-0.0.10/PKG-INFO +87 -0
  3. braintools-0.0.10/README.md +46 -0
  4. braintools-0.0.10/braintools/__init__.py +31 -0
  5. braintools-0.0.10/braintools/_others/__init__.py +26 -0
  6. braintools-0.0.10/braintools/_others/spike_encoder.py +142 -0
  7. braintools-0.0.10/braintools/_others/spike_operation.py +213 -0
  8. braintools-0.0.10/braintools/_others/transform.py +1137 -0
  9. braintools-0.0.10/braintools/_others/transform_test.py +197 -0
  10. braintools-0.0.10/braintools/file/__init__.py +21 -0
  11. braintools-0.0.10/braintools/file/matfile.py +74 -0
  12. braintools-0.0.10/braintools/file/matfile_test.py +147 -0
  13. braintools-0.0.10/braintools/file/msg_checkpoint.py +983 -0
  14. braintools-0.0.10/braintools/file/msg_checkpoint_test.py +71 -0
  15. braintools-0.0.10/braintools/input/__init__.py +27 -0
  16. braintools-0.0.10/braintools/input/currents.py +420 -0
  17. braintools-0.0.10/braintools/input/currents_test.py +118 -0
  18. braintools-0.0.10/braintools/metric/__init__.py +46 -0
  19. braintools-0.0.10/braintools/metric/_classification.py +641 -0
  20. braintools-0.0.10/braintools/metric/_classification_test.py +624 -0
  21. braintools-0.0.10/braintools/metric/_correlation.py +302 -0
  22. braintools-0.0.10/braintools/metric/_correlation_test.py +116 -0
  23. braintools-0.0.10/braintools/metric/_fenchel_young.py +66 -0
  24. braintools-0.0.10/braintools/metric/_fenchel_young_test.py +54 -0
  25. braintools-0.0.10/braintools/metric/_firings.py +92 -0
  26. braintools-0.0.10/braintools/metric/_firings_test.py +44 -0
  27. braintools-0.0.10/braintools/metric/_lfp.py +139 -0
  28. braintools-0.0.10/braintools/metric/_lfp_test.py +14 -0
  29. braintools-0.0.10/braintools/metric/_ranking.py +164 -0
  30. braintools-0.0.10/braintools/metric/_ranking_test.py +242 -0
  31. braintools-0.0.10/braintools/metric/_regression.py +423 -0
  32. braintools-0.0.10/braintools/metric/_regression_test.py +132 -0
  33. braintools-0.0.10/braintools/metric/_smoothing.py +47 -0
  34. braintools-0.0.10/braintools/metric/_smoothing_test.py +55 -0
  35. braintools-0.0.10/braintools/metric/_util.py +25 -0
  36. braintools-0.0.10/braintools/optim/__init__.py +20 -0
  37. braintools-0.0.10/braintools/optim/optimizer.py +702 -0
  38. braintools-0.0.10/braintools/optim/optimizer_test.py +249 -0
  39. braintools-0.0.10/braintools/quad/__init__.py +22 -0
  40. braintools-0.0.10/braintools/quad/_ode_integrator.py +261 -0
  41. braintools-0.0.10/braintools/quad/_ode_integrator_test.py +59 -0
  42. braintools-0.0.10/braintools/quad/_sde_integrator.py +255 -0
  43. braintools-0.0.10/braintools/quad/_sde_integrator_test.py +57 -0
  44. braintools-0.0.10/braintools/tree.py +373 -0
  45. braintools-0.0.10/braintools/visualize/__init__.py +28 -0
  46. braintools-0.0.10/braintools/visualize/animation.py +139 -0
  47. braintools-0.0.10/braintools/visualize/figures.py +49 -0
  48. braintools-0.0.10/braintools/visualize/plots.py +530 -0
  49. braintools-0.0.10/braintools/visualize/style.py +76 -0
  50. braintools-0.0.10/braintools.egg-info/PKG-INFO +87 -0
  51. braintools-0.0.10/braintools.egg-info/SOURCES.txt +55 -0
  52. braintools-0.0.10/braintools.egg-info/dependency_links.txt +1 -0
  53. braintools-0.0.10/braintools.egg-info/requires.txt +7 -0
  54. braintools-0.0.10/braintools.egg-info/top_level.txt +1 -0
  55. braintools-0.0.10/pyproject.toml +68 -0
  56. braintools-0.0.10/setup.cfg +4 -0
  57. braintools-0.0.10/setup.py +102 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [2024] [BrainPy Ecosystem]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: braintools
3
+ Version: 0.0.10
4
+ Summary: The Toolbox for Brain Modeling Ecosystem.
5
+ Home-page: https://github.com/chaobrain/braintools
6
+ Author: BrainTools Developers
7
+ Author-email: BrainTools Developers <chao.brain@qq.com>
8
+ License: Apache-2.0 license
9
+ Project-URL: homepage, http://github.com/chaobrain/braintools
10
+ Project-URL: repository, http://github.com/chaobrain/braintools
11
+ Keywords: brain dynamics programming,brain simulation,brain-inspired computing
12
+ Classifier: Natural Language :: English
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: License :: OSI Approved :: Apache Software License
23
+ Classifier: Programming Language :: Python
24
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
25
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
26
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
27
+ Classifier: Topic :: Software Development :: Libraries
28
+ Requires-Python: >=3.10
29
+ Description-Content-Type: text/markdown
30
+ License-File: LICENSE
31
+ Requires-Dist: numpy
32
+ Requires-Dist: brainstate>=0.1.0
33
+ Requires-Dist: brainunit>=0.0.8
34
+ Requires-Dist: typing_extensions
35
+ Provides-Extra: testing
36
+ Requires-Dist: pytest; extra == "testing"
37
+ Dynamic: author
38
+ Dynamic: home-page
39
+ Dynamic: license-file
40
+ Dynamic: requires-python
41
+
42
+ # Tools/utilities for brain dynamics programming
43
+
44
+ <p align="center">
45
+ <img alt="Header image of braintools." src="https://raw.githubusercontent.com/chaobrain/braintools/main/docs/_static/braintools.jpg" width=50%>
46
+ </p>
47
+
48
+
49
+ <p align="center">
50
+ <a href="https://pypi.org/project/braintools/"><img alt="Supported Python Version" src="https://img.shields.io/pypi/pyversions/braintools"></a>
51
+ <a href="https://github.com/brainpy/braintools/blob/main/LICENSE"><img alt="LICENSE" src="https://img.shields.io/badge/License-Apache%202.0-blue.svg"></a>
52
+ <a href='https://braintools.readthedocs.io/?badge=latest'>
53
+ <img src='https://readthedocs.org/projects/braintools/badge/?version=latest' alt='Documentation Status' />
54
+ </a>
55
+ <a href="https://badge.fury.io/py/braintools"><img alt="PyPI version" src="https://badge.fury.io/py/braintools.svg"></a>
56
+ <a href="https://github.com/brainpy/braintools/actions/workflows/CI.yml"><img alt="Continuous Integration" src="https://github.com/brainpy/braintools/actions/workflows/CI.yml/badge.svg"></a>
57
+ </p>
58
+
59
+
60
+ [``braintools``](https://github.com/brainpy/braintools) provides common toolboxes for brain dynamics programming (BDP).
61
+
62
+
63
+ ## Installation
64
+
65
+ You can install ``braintools`` via pip:
66
+
67
+ ```bash
68
+ pip install braintools --upgrade
69
+ ```
70
+
71
+ Alternatively, you can install `BrainX`, which bundles `braintools` with other compatible packages for a comprehensive brain modeling ecosystem:
72
+
73
+ ```bash
74
+ pip install BrainX -U
75
+ ```
76
+
77
+
78
+ ## Documentation
79
+
80
+ The official documentation is hosted on Read the Docs: [https://braintools.readthedocs.io](https://braintools.readthedocs.io)
81
+
82
+
83
+
84
+
85
+ ## See also the brain modeling ecosystem
86
+
87
+ We are building the brain modeling ecosystem: https://brainmodeling.readthedocs.io/
@@ -0,0 +1,46 @@
1
+ # Tools/utilities for brain dynamics programming
2
+
3
+ <p align="center">
4
+ <img alt="Header image of braintools." src="https://raw.githubusercontent.com/chaobrain/braintools/main/docs/_static/braintools.jpg" width=50%>
5
+ </p>
6
+
7
+
8
+ <p align="center">
9
+ <a href="https://pypi.org/project/braintools/"><img alt="Supported Python Version" src="https://img.shields.io/pypi/pyversions/braintools"></a>
10
+ <a href="https://github.com/brainpy/braintools/blob/main/LICENSE"><img alt="LICENSE" src="https://img.shields.io/badge/License-Apache%202.0-blue.svg"></a>
11
+ <a href='https://braintools.readthedocs.io/?badge=latest'>
12
+ <img src='https://readthedocs.org/projects/braintools/badge/?version=latest' alt='Documentation Status' />
13
+ </a>
14
+ <a href="https://badge.fury.io/py/braintools"><img alt="PyPI version" src="https://badge.fury.io/py/braintools.svg"></a>
15
+ <a href="https://github.com/brainpy/braintools/actions/workflows/CI.yml"><img alt="Continuous Integration" src="https://github.com/brainpy/braintools/actions/workflows/CI.yml/badge.svg"></a>
16
+ </p>
17
+
18
+
19
+ [``braintools``](https://github.com/brainpy/braintools) provides common toolboxes for brain dynamics programming (BDP).
20
+
21
+
22
+ ## Installation
23
+
24
+ You can install ``braintools`` via pip:
25
+
26
+ ```bash
27
+ pip install braintools --upgrade
28
+ ```
29
+
30
+ Alternatively, you can install `BrainX`, which bundles `braintools` with other compatible packages for a comprehensive brain modeling ecosystem:
31
+
32
+ ```bash
33
+ pip install BrainX -U
34
+ ```
35
+
36
+
37
+ ## Documentation
38
+
39
+ The official documentation is hosted on Read the Docs: [https://braintools.readthedocs.io](https://braintools.readthedocs.io)
40
+
41
+
42
+
43
+
44
+ ## See also the brain modeling ecosystem
45
+
46
+ We are building the brain modeling ecosystem: https://brainmodeling.readthedocs.io/
@@ -0,0 +1,31 @@
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
+ __version__ = "0.0.10"
18
+
19
+ from . import file
20
+ from . import quad
21
+ from . import input
22
+ from . import metric
23
+ from . import optim
24
+ from . import tree
25
+ from . import visualize
26
+ from ._others import *
27
+ from ._others import __all__ as _other_all
28
+
29
+ __all__ = ['input', 'file', 'metric', 'visualize', 'optim', 'tree', 'quad'] + _other_all
30
+
31
+ del _other_all
@@ -0,0 +1,26 @@
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 .spike_operation import *
18
+ from .spike_operation import __all__ as operation_all
19
+ from .spike_encoder import *
20
+ from .spike_encoder import __all__ as encoder_all
21
+ from .transform import *
22
+ from .transform import __all__ as transform_all
23
+
24
+ __all__ = encoder_all + transform_all + operation_all
25
+
26
+ del encoder_all, transform_all, operation_all
@@ -0,0 +1,142 @@
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 numpy as np
23
+
24
+ __all__ = [
25
+ 'LatencyEncoder',
26
+ ]
27
+
28
+
29
+ class LatencyEncoder:
30
+ r"""Encode the rate input as the spike train using the latency encoding.
31
+
32
+ Use input features to determine time-to-first spike.
33
+
34
+ Expected inputs should be between 0 and 1. If not, the latency encoder will encode ``x``
35
+ (normalized into ``[0, 1]`` according to
36
+ :math:`x_{\text{normalize}} = \frac{x-\text{min_val}}{\text{max_val} - \text{min_val}}`)
37
+ to spikes whose firing time is :math:`0 \le t_f \le \text{num_period}-1`.
38
+ A larger ``x`` will cause the earlier firing time.
39
+
40
+
41
+ Example::
42
+
43
+ >>> import jax
44
+ >>> a = jax.numpy.array([0.02, 0.5, 1])
45
+ >>> encoder = LatencyEncoder(method='linear', normalize=True)
46
+ >>> encoder(a, n_time=5)
47
+ Array([[0., 0., 1.],
48
+ [0., 0., 0.],
49
+ [0., 1., 0.],
50
+ [0., 0., 0.],
51
+ [1., 0., 0.]])
52
+
53
+
54
+ Args:
55
+ min_val: float. The minimal value in the given data `x`, used to the data normalization.
56
+ max_val: float. The maximum value in the given data `x`, used to the data normalization.
57
+ method: str. How to convert intensity to firing time. Currently, we support `linear` or `log`.
58
+ - If ``method='linear'``, the firing rate is calculated as
59
+ :math:`t_f(x) = (\text{num_period} - 1)(1 - x)`.
60
+ - If ``method='log'``, the firing rate is calculated as
61
+ :math:`t_f(x) = (\text{num_period} - 1) - ln(\alpha * x + 1)`,
62
+ where :math:`\alpha` satisfies :math:`t_f(1) = \text{num_period} - 1`.
63
+ threshold: float. Input features below the threhold will fire at the
64
+ final time step unless ``clip=True`` in which case they will not
65
+ fire at all, defaults to ``0.01``.
66
+ clip: bool. Option to remove spikes from features that fall
67
+ below the threshold, defaults to ``False``.
68
+ tau: float. RC Time constant for LIF model used to calculate
69
+ firing time, defaults to ``1``.
70
+ normalize: bool. Option to normalize the latency code such that
71
+ the final spike(s) occur within num_steps, defaults to ``False``.
72
+ epsilon: float. A tiny positive value to avoid rounding errors when
73
+ using torch.arange, defaults to ``1e-7``.
74
+ """
75
+
76
+ def __init__(
77
+ self,
78
+ min_val: float = None,
79
+ max_val: float = None,
80
+ method: str = 'log',
81
+ threshold: float = 0.01,
82
+ clip: bool = False,
83
+ tau: float = 1. * u.ms,
84
+ normalize: bool = False,
85
+ first_spk_time: float = 0. * u.ms,
86
+ epsilon: float = 1e-7,
87
+ ):
88
+ super().__init__()
89
+
90
+ if method not in ['linear', 'log']:
91
+ raise ValueError('The conversion method can only be "linear" and "log".')
92
+ self.method = method
93
+ self.min_val = min_val
94
+ self.max_val = max_val
95
+ if threshold < 0 or threshold > 1:
96
+ raise ValueError(f"``threshold`` [{threshold}] must be between [0, 1]")
97
+ self.threshold = threshold
98
+ self.clip = clip
99
+ self.tau = tau
100
+ self.normalize = normalize
101
+ self.first_spk_time = first_spk_time
102
+ self.first_spk_step = int(first_spk_time / brainstate.environ.get_dt())
103
+ self.epsilon = epsilon
104
+
105
+ def __call__(self, data, n_time: Optional[brainstate.typing.ArrayLike] = None):
106
+ """Generate latency spikes according to the given input data.
107
+
108
+ Ensuring x in [0., 1.].
109
+
110
+ Args:
111
+ data: The rate-based input.
112
+ n_time: float. The total time to generate data. If None, use ``tau`` instead.
113
+
114
+ Returns:
115
+ out: array. The output spiking trains.
116
+ """
117
+ with jax.ensure_compile_time_eval():
118
+ if n_time is None:
119
+ n_time = self.tau
120
+ tau = n_time if self.normalize else self.tau
121
+ x = data
122
+ if self.min_val is not None and self.max_val is not None:
123
+ x = (x - self.min_val) / (self.max_val - self.min_val)
124
+
125
+ # Calculate the spike time
126
+ dt = brainstate.environ.get_dt()
127
+ if self.method == 'linear':
128
+ spike_time = (tau - self.first_spk_time - dt) * (1 - x) + self.first_spk_time
129
+
130
+ elif self.method == 'log':
131
+ x = u.math.maximum(x, self.threshold + self.epsilon) # saturates all values below threshold.
132
+ spike_time = (tau - self.first_spk_time - dt) * u.math.log(
133
+ x / (x - self.threshold)) + self.first_spk_time
134
+
135
+ else:
136
+ raise ValueError(f'Unsupported method: {self.method}. Only support "log" and "linear".')
137
+
138
+ # Clip the spike time
139
+ if self.clip:
140
+ spike_time = u.math.where(data < self.threshold, np.inf, spike_time)
141
+ spike_steps = u.math.round(spike_time / dt).astype(int)
142
+ return brainstate.functional.one_hot(spike_steps, num_classes=int(n_time / dt), axis=0, dtype=x.dtype)