brainstate 0.1.7__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 -146
  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 -470
  58. brainstate/nn/_delay_test.py +238 -0
  59. brainstate/nn/_dropout.py +426 -426
  60. brainstate/nn/_dropout_test.py +100 -100
  61. brainstate/nn/_dynamics.py +1343 -1361
  62. brainstate/nn/_dynamics_test.py +78 -78
  63. brainstate/nn/_elementwise.py +1119 -1120
  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 -208
  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.7.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.7.dist-info → brainstate-0.1.9.dist-info}/WHEEL +1 -1
  129. {brainstate-0.1.7.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.7.dist-info/RECORD +0 -131
  133. {brainstate-0.1.7.dist-info → brainstate-0.1.9.dist-info}/top_level.txt +0 -0
@@ -1,256 +1,256 @@
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
- from collections.abc import Callable, Sequence
17
-
18
- import jax
19
- import jax.numpy as jnp
20
- import numpy as np
21
-
22
- from brainstate._compatible_import import to_concrete_aval, Tracer
23
- from brainstate._utils import set_module_as
24
- from ._error_if import jit_error_if
25
- from ._make_jaxpr import StatefulFunction
26
- from ._util import wrap_single_fun_in_multi_branches, write_back_state_values
27
-
28
- __all__ = [
29
- 'cond', 'switch', 'ifelse',
30
- ]
31
-
32
-
33
- @set_module_as('brainstate.compile')
34
- def cond(pred, true_fun: Callable, false_fun: Callable, *operands):
35
- """
36
- Conditionally apply ``true_fun`` or ``false_fun``.
37
-
38
- Provided arguments are correctly typed, ``cond()`` has equivalent
39
- semantics to this Python implementation, where ``pred`` must be a
40
- scalar type::
41
-
42
- def cond(pred, true_fun, false_fun, *operands):
43
- if pred:
44
- return true_fun(*operands)
45
- else:
46
- return false_fun(*operands)
47
-
48
-
49
- In contrast with :func:`jax.lax.select`, using ``cond`` indicates that only one of
50
- the two branches is executed (up to compiler rewrites and optimizations).
51
- However, when transformed with :func:`~jax.vmap` to operate over a batch of
52
- predicates, ``cond`` is converted to :func:`~jax.lax.select`.
53
-
54
- Args:
55
- pred: Boolean scalar type, indicating which branch function to apply.
56
- true_fun: Function (A -> B), to be applied if ``pred`` is True.
57
- false_fun: Function (A -> B), to be applied if ``pred`` is False.
58
- operands: Operands (A) input to either branch depending on ``pred``. The
59
- type can be a scalar, array, or any pytree (nested Python tuple/list/dict)
60
- thereof.
61
-
62
- Returns:
63
- Value (B) of either ``true_fun(*operands)`` or ``false_fun(*operands)``,
64
- depending on the value of ``pred``. The type can be a scalar, array, or any
65
- pytree (nested Python tuple/list/dict) thereof.
66
- """
67
- if not (callable(true_fun) and callable(false_fun)):
68
- raise TypeError("true_fun and false_fun arguments should be callable.")
69
-
70
- if pred is None:
71
- raise TypeError("cond predicate is None")
72
- if isinstance(pred, Sequence) or np.ndim(pred) != 0:
73
- raise TypeError(f"Pred must be a scalar, got {pred} of " +
74
- (f"type {type(pred)}" if isinstance(pred, Sequence)
75
- else f"shape {np.shape(pred)}."))
76
-
77
- # check pred
78
- try:
79
- pred_dtype = jax.dtypes.result_type(pred)
80
- except TypeError as err:
81
- raise TypeError("Pred type must be either boolean or number, got {}.".format(pred)) from err
82
- if pred_dtype.kind != 'b':
83
- if pred_dtype.kind in 'iuf':
84
- pred = pred != 0
85
- else:
86
- raise TypeError("Pred type must be either boolean or number, got {}.".format(pred_dtype))
87
-
88
- # not jit
89
- if jax.config.jax_disable_jit and not isinstance(to_concrete_aval(pred), Tracer):
90
- if pred:
91
- return true_fun(*operands)
92
- else:
93
- return false_fun(*operands)
94
-
95
- # evaluate jaxpr
96
- stateful_true = StatefulFunction(true_fun, name='cond:true').make_jaxpr(*operands)
97
- stateful_false = StatefulFunction(false_fun, name='conda:false').make_jaxpr(*operands)
98
-
99
- # state trace and state values
100
- state_trace = stateful_true.get_state_trace() + stateful_false.get_state_trace()
101
- read_state_vals = state_trace.get_read_state_values(True)
102
- write_state_vals = state_trace.get_write_state_values(True)
103
-
104
- # wrap the functions
105
- true_fun = wrap_single_fun_in_multi_branches(stateful_true, state_trace, read_state_vals, True)
106
- false_fun = wrap_single_fun_in_multi_branches(stateful_false, state_trace, read_state_vals, True)
107
-
108
- # cond
109
- write_state_vals, out = jax.lax.cond(pred, true_fun, false_fun, write_state_vals, *operands)
110
-
111
- # assign the written state values and restore the read state values
112
- write_back_state_values(state_trace, read_state_vals, write_state_vals)
113
- return out
114
-
115
-
116
- @set_module_as('brainstate.compile')
117
- def switch(index, branches: Sequence[Callable], *operands):
118
- """
119
- Apply exactly one of ``branches`` given by ``index``.
120
-
121
- If ``index`` is out of bounds, it is clamped to within bounds.
122
-
123
- Has the semantics of the following Python::
124
-
125
- def switch(index, branches, *operands):
126
- index = clamp(0, index, len(branches) - 1)
127
- return branches[index](*operands)
128
-
129
- Internally this wraps XLA's `Conditional
130
- <https://www.tensorflow.org/xla/operation_semantics#conditional>`_
131
- operator. However, when transformed with :func:`~jax.vmap` to operate over a
132
- batch of predicates, ``cond`` is converted to :func:`~jax.lax.select`.
133
-
134
- Args:
135
- index: Integer scalar type, indicating which branch function to apply.
136
- branches: Sequence of functions (A -> B) to be applied based on ``index``.
137
- operands: Operands (A) input to whichever branch is applied.
138
-
139
- Returns:
140
- Value (B) of ``branch(*operands)`` for the branch that was selected based
141
- on ``index``.
142
- """
143
- # check branches
144
- if not all(callable(branch) for branch in branches):
145
- raise TypeError("branches argument should be a sequence of callables.")
146
-
147
- # check index
148
- if len(np.shape(index)) != 0:
149
- raise TypeError(f"Branch index must be scalar, got {index} of shape {np.shape(index)}.")
150
- try:
151
- index_dtype = jax.dtypes.result_type(index)
152
- except TypeError as err:
153
- msg = f"Index type must be an integer, got {index}."
154
- raise TypeError(msg) from err
155
- if index_dtype.kind not in 'iu':
156
- raise TypeError(f"Index type must be an integer, got {index} as {index_dtype}")
157
-
158
- # format branches
159
- branches = tuple(branches)
160
- if len(branches) == 0:
161
- raise ValueError("Empty branch sequence")
162
- elif len(branches) == 1:
163
- return branches[0](*operands)
164
-
165
- # format index
166
- index = jax.lax.convert_element_type(index, np.int32)
167
- lo = np.array(0, np.int32)
168
- hi = np.array(len(branches) - 1, np.int32)
169
- index = jax.lax.clamp(lo, index, hi)
170
-
171
- # not jit
172
- if jax.config.jax_disable_jit and isinstance(jax.core.core.get_aval(index), jax.core.ConcreteArray):
173
- return branches[int(index)](*operands)
174
-
175
- # evaluate jaxpr
176
- wrapped_branches = [StatefulFunction(branch, name='switch') for branch in branches]
177
- for wrapped_branch in wrapped_branches:
178
- wrapped_branch.make_jaxpr(*operands)
179
-
180
- # wrap the functions
181
- state_trace = wrapped_branches[0].get_state_trace() + wrapped_branches[1].get_state_trace()
182
- state_trace.merge(*[wrapped_branch.get_state_trace() for wrapped_branch in wrapped_branches[2:]])
183
- read_state_vals = state_trace.get_read_state_values(True)
184
- write_state_vals = state_trace.get_write_state_values(True)
185
- branches = [
186
- wrap_single_fun_in_multi_branches(wrapped_branch, state_trace, read_state_vals, True)
187
- for wrapped_branch in wrapped_branches
188
- ]
189
-
190
- # switch
191
- write_state_vals, out = jax.lax.switch(index, branches, write_state_vals, *operands)
192
-
193
- # write back state values or restore them
194
- write_back_state_values(state_trace, read_state_vals, write_state_vals)
195
- return out
196
-
197
-
198
- @set_module_as('brainstate.compile')
199
- def ifelse(conditions, branches, *operands, check_cond: bool = True):
200
- """
201
- ``If-else`` control flows looks like native Pythonic programming.
202
-
203
- Examples
204
- --------
205
-
206
- >>> import brainstate
207
- >>> def f(a):
208
- >>> return brainstate.compile.ifelse(conditions=[a > 10, a > 5, a > 2, a > 0],
209
- >>> branches=[lambda: 1,
210
- >>> lambda: 2,
211
- >>> lambda: 3,
212
- >>> lambda: 4,
213
- >>> lambda: 5])
214
- >>> f(1)
215
- 4
216
- >>> f(0)
217
- 5
218
-
219
- Parameters
220
- ----------
221
- conditions: bool, sequence of bool, Array
222
- The boolean conditions.
223
- branches: Any
224
- The branches, at least has two elements. Elements can be functions,
225
- arrays, or numbers. The number of ``branches`` and ``conditions`` has
226
- the relationship of `len(branches) == len(conditions) + 1`.
227
- Each branch should receive one arguement for ``operands``.
228
- *operands: optional, Any
229
- The operands for each branch.
230
- check_cond: bool
231
- Whether to check the conditions. Default is True.
232
-
233
- Returns
234
- -------
235
- res: Any
236
- The results of the control flow.
237
- """
238
- # check branches
239
- if not all(callable(branch) for branch in branches):
240
- raise TypeError("branches argument should be a sequence of callables.")
241
-
242
- # format branches
243
- branches = tuple(branches)
244
- if len(branches) == 0:
245
- raise ValueError("Empty branch sequence")
246
- elif len(branches) == 1:
247
- return branches[0](*operands)
248
- if len(conditions) != len(branches):
249
- raise ValueError("The number of conditions should be equal to the number of branches.")
250
-
251
- # format index
252
- conditions = jnp.asarray(conditions, np.int32)
253
- if check_cond:
254
- jit_error_if(jnp.sum(conditions) != 1, "Only one condition can be True. But got {}.", err_arg=conditions)
255
- index = jnp.where(conditions, size=1, fill_value=len(conditions) - 1)[0][0]
256
- return switch(index, branches, *operands)
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
+ from collections.abc import Callable, Sequence
17
+
18
+ import jax
19
+ import jax.numpy as jnp
20
+ import numpy as np
21
+
22
+ from brainstate._compatible_import import to_concrete_aval, Tracer
23
+ from brainstate._utils import set_module_as
24
+ from ._error_if import jit_error_if
25
+ from ._make_jaxpr import StatefulFunction
26
+ from ._util import wrap_single_fun_in_multi_branches, write_back_state_values
27
+
28
+ __all__ = [
29
+ 'cond', 'switch', 'ifelse',
30
+ ]
31
+
32
+
33
+ @set_module_as('brainstate.compile')
34
+ def cond(pred, true_fun: Callable, false_fun: Callable, *operands):
35
+ """
36
+ Conditionally apply ``true_fun`` or ``false_fun``.
37
+
38
+ Provided arguments are correctly typed, ``cond()`` has equivalent
39
+ semantics to this Python implementation, where ``pred`` must be a
40
+ scalar type::
41
+
42
+ def cond(pred, true_fun, false_fun, *operands):
43
+ if pred:
44
+ return true_fun(*operands)
45
+ else:
46
+ return false_fun(*operands)
47
+
48
+
49
+ In contrast with :func:`jax.lax.select`, using ``cond`` indicates that only one of
50
+ the two branches is executed (up to compiler rewrites and optimizations).
51
+ However, when transformed with :func:`~jax.vmap` to operate over a batch of
52
+ predicates, ``cond`` is converted to :func:`~jax.lax.select`.
53
+
54
+ Args:
55
+ pred: Boolean scalar type, indicating which branch function to apply.
56
+ true_fun: Function (A -> B), to be applied if ``pred`` is True.
57
+ false_fun: Function (A -> B), to be applied if ``pred`` is False.
58
+ operands: Operands (A) input to either branch depending on ``pred``. The
59
+ type can be a scalar, array, or any pytree (nested Python tuple/list/dict)
60
+ thereof.
61
+
62
+ Returns:
63
+ Value (B) of either ``true_fun(*operands)`` or ``false_fun(*operands)``,
64
+ depending on the value of ``pred``. The type can be a scalar, array, or any
65
+ pytree (nested Python tuple/list/dict) thereof.
66
+ """
67
+ if not (callable(true_fun) and callable(false_fun)):
68
+ raise TypeError("true_fun and false_fun arguments should be callable.")
69
+
70
+ if pred is None:
71
+ raise TypeError("cond predicate is None")
72
+ if isinstance(pred, Sequence) or np.ndim(pred) != 0:
73
+ raise TypeError(f"Pred must be a scalar, got {pred} of " +
74
+ (f"type {type(pred)}" if isinstance(pred, Sequence)
75
+ else f"shape {np.shape(pred)}."))
76
+
77
+ # check pred
78
+ try:
79
+ pred_dtype = jax.dtypes.result_type(pred)
80
+ except TypeError as err:
81
+ raise TypeError("Pred type must be either boolean or number, got {}.".format(pred)) from err
82
+ if pred_dtype.kind != 'b':
83
+ if pred_dtype.kind in 'iuf':
84
+ pred = pred != 0
85
+ else:
86
+ raise TypeError("Pred type must be either boolean or number, got {}.".format(pred_dtype))
87
+
88
+ # not jit
89
+ if jax.config.jax_disable_jit and not isinstance(to_concrete_aval(pred), Tracer):
90
+ if pred:
91
+ return true_fun(*operands)
92
+ else:
93
+ return false_fun(*operands)
94
+
95
+ # evaluate jaxpr
96
+ stateful_true = StatefulFunction(true_fun, name='cond:true').make_jaxpr(*operands)
97
+ stateful_false = StatefulFunction(false_fun, name='conda:false').make_jaxpr(*operands)
98
+
99
+ # state trace and state values
100
+ state_trace = stateful_true.get_state_trace() + stateful_false.get_state_trace()
101
+ read_state_vals = state_trace.get_read_state_values(True)
102
+ write_state_vals = state_trace.get_write_state_values(True)
103
+
104
+ # wrap the functions
105
+ true_fun = wrap_single_fun_in_multi_branches(stateful_true, state_trace, read_state_vals, True)
106
+ false_fun = wrap_single_fun_in_multi_branches(stateful_false, state_trace, read_state_vals, True)
107
+
108
+ # cond
109
+ write_state_vals, out = jax.lax.cond(pred, true_fun, false_fun, write_state_vals, *operands)
110
+
111
+ # assign the written state values and restore the read state values
112
+ write_back_state_values(state_trace, read_state_vals, write_state_vals)
113
+ return out
114
+
115
+
116
+ @set_module_as('brainstate.compile')
117
+ def switch(index, branches: Sequence[Callable], *operands):
118
+ """
119
+ Apply exactly one of ``branches`` given by ``index``.
120
+
121
+ If ``index`` is out of bounds, it is clamped to within bounds.
122
+
123
+ Has the semantics of the following Python::
124
+
125
+ def switch(index, branches, *operands):
126
+ index = clamp(0, index, len(branches) - 1)
127
+ return branches[index](*operands)
128
+
129
+ Internally this wraps XLA's `Conditional
130
+ <https://www.tensorflow.org/xla/operation_semantics#conditional>`_
131
+ operator. However, when transformed with :func:`~jax.vmap` to operate over a
132
+ batch of predicates, ``cond`` is converted to :func:`~jax.lax.select`.
133
+
134
+ Args:
135
+ index: Integer scalar type, indicating which branch function to apply.
136
+ branches: Sequence of functions (A -> B) to be applied based on ``index``.
137
+ operands: Operands (A) input to whichever branch is applied.
138
+
139
+ Returns:
140
+ Value (B) of ``branch(*operands)`` for the branch that was selected based
141
+ on ``index``.
142
+ """
143
+ # check branches
144
+ if not all(callable(branch) for branch in branches):
145
+ raise TypeError("branches argument should be a sequence of callables.")
146
+
147
+ # check index
148
+ if len(np.shape(index)) != 0:
149
+ raise TypeError(f"Branch index must be scalar, got {index} of shape {np.shape(index)}.")
150
+ try:
151
+ index_dtype = jax.dtypes.result_type(index)
152
+ except TypeError as err:
153
+ msg = f"Index type must be an integer, got {index}."
154
+ raise TypeError(msg) from err
155
+ if index_dtype.kind not in 'iu':
156
+ raise TypeError(f"Index type must be an integer, got {index} as {index_dtype}")
157
+
158
+ # format branches
159
+ branches = tuple(branches)
160
+ if len(branches) == 0:
161
+ raise ValueError("Empty branch sequence")
162
+ elif len(branches) == 1:
163
+ return branches[0](*operands)
164
+
165
+ # format index
166
+ index = jax.lax.convert_element_type(index, np.int32)
167
+ lo = np.array(0, np.int32)
168
+ hi = np.array(len(branches) - 1, np.int32)
169
+ index = jax.lax.clamp(lo, index, hi)
170
+
171
+ # not jit
172
+ if jax.config.jax_disable_jit and isinstance(jax.core.core.get_aval(index), jax.core.ConcreteArray):
173
+ return branches[int(index)](*operands)
174
+
175
+ # evaluate jaxpr
176
+ wrapped_branches = [StatefulFunction(branch, name='switch') for branch in branches]
177
+ for wrapped_branch in wrapped_branches:
178
+ wrapped_branch.make_jaxpr(*operands)
179
+
180
+ # wrap the functions
181
+ state_trace = wrapped_branches[0].get_state_trace() + wrapped_branches[1].get_state_trace()
182
+ state_trace.merge(*[wrapped_branch.get_state_trace() for wrapped_branch in wrapped_branches[2:]])
183
+ read_state_vals = state_trace.get_read_state_values(True)
184
+ write_state_vals = state_trace.get_write_state_values(True)
185
+ branches = [
186
+ wrap_single_fun_in_multi_branches(wrapped_branch, state_trace, read_state_vals, True)
187
+ for wrapped_branch in wrapped_branches
188
+ ]
189
+
190
+ # switch
191
+ write_state_vals, out = jax.lax.switch(index, branches, write_state_vals, *operands)
192
+
193
+ # write back state values or restore them
194
+ write_back_state_values(state_trace, read_state_vals, write_state_vals)
195
+ return out
196
+
197
+
198
+ @set_module_as('brainstate.compile')
199
+ def ifelse(conditions, branches, *operands, check_cond: bool = True):
200
+ """
201
+ ``If-else`` control flows looks like native Pythonic programming.
202
+
203
+ Examples
204
+ --------
205
+
206
+ >>> import brainstate
207
+ >>> def f(a):
208
+ >>> return brainstate.compile.ifelse(conditions=[a > 10, a > 5, a > 2, a > 0],
209
+ >>> branches=[lambda: 1,
210
+ >>> lambda: 2,
211
+ >>> lambda: 3,
212
+ >>> lambda: 4,
213
+ >>> lambda: 5])
214
+ >>> f(1)
215
+ 4
216
+ >>> f(0)
217
+ 5
218
+
219
+ Parameters
220
+ ----------
221
+ conditions: bool, sequence of bool, Array
222
+ The boolean conditions.
223
+ branches: Any
224
+ The branches, at least has two elements. Elements can be functions,
225
+ arrays, or numbers. The number of ``branches`` and ``conditions`` has
226
+ the relationship of `len(branches) == len(conditions) + 1`.
227
+ Each branch should receive one arguement for ``operands``.
228
+ *operands: optional, Any
229
+ The operands for each branch.
230
+ check_cond: bool
231
+ Whether to check the conditions. Default is True.
232
+
233
+ Returns
234
+ -------
235
+ res: Any
236
+ The results of the control flow.
237
+ """
238
+ # check branches
239
+ if not all(callable(branch) for branch in branches):
240
+ raise TypeError("branches argument should be a sequence of callables.")
241
+
242
+ # format branches
243
+ branches = tuple(branches)
244
+ if len(branches) == 0:
245
+ raise ValueError("Empty branch sequence")
246
+ elif len(branches) == 1:
247
+ return branches[0](*operands)
248
+ if len(conditions) != len(branches):
249
+ raise ValueError("The number of conditions should be equal to the number of branches.")
250
+
251
+ # format index
252
+ conditions = jnp.asarray(conditions, np.int32)
253
+ if check_cond:
254
+ jit_error_if(jnp.sum(conditions) != 1, "Only one condition can be True. But got {}.", err_arg=conditions)
255
+ index = jnp.where(conditions, size=1, fill_value=len(conditions) - 1)[0][0]
256
+ return switch(index, branches, *operands)