brainstate 0.2.1__py2.py3-none-any.whl → 0.2.2__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. brainstate/__init__.py +167 -169
  2. brainstate/_compatible_import.py +340 -340
  3. brainstate/_compatible_import_test.py +681 -681
  4. brainstate/_deprecation.py +210 -210
  5. brainstate/_deprecation_test.py +2297 -2319
  6. brainstate/_error.py +45 -45
  7. brainstate/_state.py +2157 -1652
  8. brainstate/_state_test.py +1129 -52
  9. brainstate/_utils.py +47 -47
  10. brainstate/environ.py +1495 -1495
  11. brainstate/environ_test.py +1223 -1223
  12. brainstate/graph/__init__.py +22 -22
  13. brainstate/graph/_node.py +240 -240
  14. brainstate/graph/_node_test.py +589 -589
  15. brainstate/graph/_operation.py +1620 -1624
  16. brainstate/graph/_operation_test.py +1147 -1147
  17. brainstate/mixin.py +1447 -1433
  18. brainstate/mixin_test.py +1017 -1017
  19. brainstate/nn/__init__.py +146 -137
  20. brainstate/nn/_activations.py +1100 -1100
  21. brainstate/nn/_activations_test.py +354 -354
  22. brainstate/nn/_collective_ops.py +635 -633
  23. brainstate/nn/_collective_ops_test.py +774 -774
  24. brainstate/nn/_common.py +226 -226
  25. brainstate/nn/_common_test.py +134 -154
  26. brainstate/nn/_conv.py +2010 -2010
  27. brainstate/nn/_conv_test.py +849 -849
  28. brainstate/nn/_delay.py +575 -575
  29. brainstate/nn/_delay_test.py +243 -243
  30. brainstate/nn/_dropout.py +618 -618
  31. brainstate/nn/_dropout_test.py +480 -477
  32. brainstate/nn/_dynamics.py +870 -1267
  33. brainstate/nn/_dynamics_test.py +53 -67
  34. brainstate/nn/_elementwise.py +1298 -1298
  35. brainstate/nn/_elementwise_test.py +829 -829
  36. brainstate/nn/_embedding.py +408 -408
  37. brainstate/nn/_embedding_test.py +156 -156
  38. brainstate/nn/_event_fixedprob.py +233 -233
  39. brainstate/nn/_event_fixedprob_test.py +115 -115
  40. brainstate/nn/_event_linear.py +83 -83
  41. brainstate/nn/_event_linear_test.py +121 -121
  42. brainstate/nn/_exp_euler.py +254 -254
  43. brainstate/nn/_exp_euler_test.py +377 -377
  44. brainstate/nn/_linear.py +744 -744
  45. brainstate/nn/_linear_test.py +475 -475
  46. brainstate/nn/_metrics.py +1070 -1070
  47. brainstate/nn/_metrics_test.py +611 -611
  48. brainstate/nn/_module.py +391 -384
  49. brainstate/nn/_module_test.py +40 -40
  50. brainstate/nn/_normalizations.py +1334 -1334
  51. brainstate/nn/_normalizations_test.py +699 -699
  52. brainstate/nn/_paddings.py +1020 -1020
  53. brainstate/nn/_paddings_test.py +722 -722
  54. brainstate/nn/_poolings.py +2239 -2239
  55. brainstate/nn/_poolings_test.py +952 -952
  56. brainstate/nn/_rnns.py +946 -946
  57. brainstate/nn/_rnns_test.py +592 -592
  58. brainstate/nn/_utils.py +216 -216
  59. brainstate/nn/_utils_test.py +401 -401
  60. brainstate/nn/init.py +809 -809
  61. brainstate/nn/init_test.py +180 -180
  62. brainstate/random/__init__.py +270 -270
  63. brainstate/random/{_rand_funs.py → _fun.py} +3938 -3938
  64. brainstate/random/{_rand_funs_test.py → _fun_test.py} +638 -640
  65. brainstate/random/_impl.py +672 -0
  66. brainstate/random/{_rand_seed.py → _seed.py} +675 -675
  67. brainstate/random/{_rand_seed_test.py → _seed_test.py} +48 -48
  68. brainstate/random/{_rand_state.py → _state.py} +1320 -1617
  69. brainstate/random/{_rand_state_test.py → _state_test.py} +551 -551
  70. brainstate/transform/__init__.py +56 -59
  71. brainstate/transform/_ad_checkpoint.py +176 -176
  72. brainstate/transform/_ad_checkpoint_test.py +49 -49
  73. brainstate/transform/_autograd.py +1025 -1025
  74. brainstate/transform/_autograd_test.py +1289 -1289
  75. brainstate/transform/_conditions.py +316 -316
  76. brainstate/transform/_conditions_test.py +220 -220
  77. brainstate/transform/_error_if.py +94 -94
  78. brainstate/transform/_error_if_test.py +52 -52
  79. brainstate/transform/_find_state.py +200 -0
  80. brainstate/transform/_find_state_test.py +84 -0
  81. brainstate/transform/_jit.py +399 -399
  82. brainstate/transform/_jit_test.py +143 -143
  83. brainstate/transform/_loop_collect_return.py +675 -675
  84. brainstate/transform/_loop_collect_return_test.py +58 -58
  85. brainstate/transform/_loop_no_collection.py +283 -283
  86. brainstate/transform/_loop_no_collection_test.py +50 -50
  87. brainstate/transform/_make_jaxpr.py +2176 -2016
  88. brainstate/transform/_make_jaxpr_test.py +1634 -1510
  89. brainstate/transform/_mapping.py +607 -529
  90. brainstate/transform/_mapping_test.py +104 -194
  91. brainstate/transform/_progress_bar.py +255 -255
  92. brainstate/transform/_unvmap.py +256 -256
  93. brainstate/transform/_util.py +286 -286
  94. brainstate/typing.py +837 -837
  95. brainstate/typing_test.py +780 -780
  96. brainstate/util/__init__.py +27 -27
  97. brainstate/util/_others.py +1024 -1024
  98. brainstate/util/_others_test.py +962 -962
  99. brainstate/util/_pretty_pytree.py +1301 -1301
  100. brainstate/util/_pretty_pytree_test.py +675 -675
  101. brainstate/util/_pretty_repr.py +462 -462
  102. brainstate/util/_pretty_repr_test.py +696 -696
  103. brainstate/util/filter.py +945 -945
  104. brainstate/util/filter_test.py +911 -911
  105. brainstate/util/struct.py +910 -910
  106. brainstate/util/struct_test.py +602 -602
  107. {brainstate-0.2.1.dist-info → brainstate-0.2.2.dist-info}/METADATA +108 -108
  108. brainstate-0.2.2.dist-info/RECORD +111 -0
  109. {brainstate-0.2.1.dist-info → brainstate-0.2.2.dist-info}/licenses/LICENSE +202 -202
  110. brainstate/transform/_eval_shape.py +0 -145
  111. brainstate/transform/_eval_shape_test.py +0 -38
  112. brainstate/transform/_random.py +0 -171
  113. brainstate-0.2.1.dist-info/RECORD +0 -111
  114. {brainstate-0.2.1.dist-info → brainstate-0.2.2.dist-info}/WHEEL +0 -0
  115. {brainstate-0.2.1.dist-info → brainstate-0.2.2.dist-info}/top_level.txt +0 -0
@@ -1,377 +1,377 @@
1
- # Copyright 2024 BrainX Ecosystem Limited. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- # ==============================================================================
15
-
16
-
17
- import unittest
18
-
19
- import brainunit as u
20
- import jax.numpy as jnp
21
- import numpy as np
22
-
23
- import brainstate
24
-
25
-
26
- class TestExpEulerODE(unittest.TestCase):
27
- """Test cases for ODE integration using exp_euler_step."""
28
-
29
- def test_exponential_decay(self):
30
- """Test simple exponential decay: dx/dt = -x"""
31
- def drift(x, t):
32
- return -x
33
-
34
- with brainstate.environ.context(dt=0.01):
35
- x0 = jnp.array(1.0)
36
- x1 = brainstate.nn.exp_euler_step(drift, x0, None)
37
-
38
- # Expected: x(t+dt) ≈ x(t) * exp(-dt) ≈ 0.99004983
39
- expected = np.exp(-0.01)
40
- np.testing.assert_allclose(x1, expected)
41
-
42
- def test_exponential_decay_with_time_constant(self):
43
- """Test exponential decay with time constant: dx/dt = -x/tau"""
44
- def drift(x, tau):
45
- return -x / tau
46
-
47
- with brainstate.environ.context(dt=1.0 * u.ms):
48
- x0 = u.math.asarray(1.0 * u.mV)
49
- tau = 10.0 * u.ms
50
- x1 = brainstate.nn.exp_euler_step(drift, x0, tau)
51
-
52
- # Expected: x(t+dt) ≈ x(t) * exp(-dt/tau)
53
- expected = np.exp(-0.1) * u.mV
54
- assert u.math.allclose(x1, expected)
55
-
56
- def test_linear_growth(self):
57
- """Test linear growth: dx/dt = a"""
58
- def drift(x):
59
- return jnp.asarray([2.0])
60
-
61
- with brainstate.environ.context(dt=0.1):
62
- x0 = jnp.asarray([1.0])
63
- x1 = brainstate.nn.exp_euler_step(drift, x0)
64
-
65
- # For constant derivative, result should be x0 + a*dt
66
- expected = 1.0 + 2.0 * 0.1
67
- np.testing.assert_allclose(x1, expected)
68
-
69
- def test_multidimensional_system(self):
70
- """Test multi-dimensional ODE: harmonic oscillator"""
71
- def drift(x, t):
72
- # dx/dt = [x1, -x0] (circular motion)
73
- return jnp.array([x[1], -x[0]])
74
-
75
- with brainstate.environ.context(dt=0.01):
76
- x0 = jnp.array([1.0, 0.0])
77
- x1 = brainstate.nn.exp_euler_step(drift, x0, None)
78
-
79
- # Check that energy is approximately conserved
80
- energy0 = np.sum(x0 ** 2)
81
- energy1 = np.sum(x1 ** 2)
82
- np.testing.assert_allclose(energy1, energy0, rtol=0.1)
83
-
84
- def test_stiff_equation(self):
85
- """Test stiff equation where exponential Euler should be stable"""
86
- def drift(x, t):
87
- # Stiff equation: dx/dt = -100*x
88
- return -100.0 * x
89
-
90
- with brainstate.environ.context(dt=0.1):
91
- x0 = jnp.array(1.0)
92
- x1 = brainstate.nn.exp_euler_step(drift, x0, None)
93
-
94
- # Should remain stable and decay
95
- expected = np.exp(-10.0)
96
- np.testing.assert_allclose(x1, expected, rtol=1e-2)
97
- self.assertGreater(x1, 0.0) # Should not become negative
98
-
99
-
100
- class TestExpEulerSDE(unittest.TestCase):
101
- """Test cases for SDE integration using exp_euler_step."""
102
-
103
- def test_simple_sde_with_constant_diffusion(self):
104
- """Test SDE with constant diffusion: dx = -x*dt + sigma*dW"""
105
- def drift(x, t):
106
- return -x
107
-
108
- def diffusion(x, t):
109
- return jnp.array(0.1)
110
-
111
- with brainstate.environ.context(dt=0.01):
112
- brainstate.random.seed(42)
113
- x0 = jnp.array(1.0)
114
- x1 = brainstate.nn.exp_euler_step(drift, diffusion, x0, None)
115
-
116
- # Result should have both drift and diffusion components
117
- # Cannot test exact value due to randomness, but check it's reasonable
118
- self.assertIsInstance(x1, (jnp.ndarray, float))
119
-
120
- def test_ornstein_uhlenbeck_process(self):
121
- """Test Ornstein-Uhlenbeck process: dx = -theta*x*dt + sigma*dW"""
122
- theta = 0.5
123
- sigma = 0.3
124
-
125
- def drift(x, t):
126
- return -theta * x
127
-
128
- def diffusion(x, t):
129
- return jnp.full_like(x, sigma)
130
-
131
- with brainstate.environ.context(dt=0.01):
132
- brainstate.random.seed(123)
133
- x0 = jnp.array(1.0)
134
- x1 = brainstate.nn.exp_euler_step(drift, diffusion, x0, None)
135
-
136
- # Mean should decrease (drift dominates initially)
137
- # Run multiple steps and check statistics
138
- x = x0
139
- results = []
140
- for _ in range(100):
141
- x = brainstate.nn.exp_euler_step(drift, diffusion, x, None)
142
- results.append(x)
143
-
144
- # Mean should converge toward 0
145
- final_mean = np.mean(results[-10:])
146
- self.assertLess(abs(final_mean), 0.5)
147
-
148
- def test_sde_multidimensional(self):
149
- """Test multi-dimensional SDE"""
150
- def drift(x, t):
151
- return -0.5 * x
152
-
153
- def diffusion(x, t):
154
- return jnp.array([0.1, 0.2])
155
-
156
- with brainstate.environ.context(dt=0.01):
157
- brainstate.random.seed(456)
158
- x0 = jnp.array([1.0, 1.0])
159
- x1 = brainstate.nn.exp_euler_step(drift, diffusion, x0, None)
160
-
161
- self.assertEqual(x1.shape, (2,))
162
-
163
- def test_state_dependent_diffusion(self):
164
- """Test SDE with state-dependent diffusion: dx = -x*dt + sqrt(x)*dW"""
165
- def drift(x, t):
166
- return -0.1 * x
167
-
168
- def diffusion(x, t):
169
- return jnp.sqrt(jnp.abs(x) + 1e-8)
170
-
171
- with brainstate.environ.context(dt=0.01):
172
- brainstate.random.seed(789)
173
- x0 = jnp.array(1.0)
174
- x1 = brainstate.nn.exp_euler_step(drift, diffusion, x0, None)
175
-
176
- self.assertIsInstance(x1, (jnp.ndarray, float))
177
-
178
-
179
- class TestExpEulerUnits(unittest.TestCase):
180
- """Test cases for unit handling in exp_euler_step."""
181
-
182
- def test_unit_compatibility_drift(self):
183
- """Test that drift function units are validated correctly"""
184
- def drift(x, tau):
185
- return -x / tau
186
-
187
- with brainstate.environ.context(dt=1.0 * u.ms):
188
- x0 = 1.0 * u.mV
189
- tau = 10.0 * u.ms
190
- x1 = brainstate.nn.exp_euler_step(drift, x0, tau)
191
-
192
- # Result should have same units as input
193
- self.assertEqual(u.get_unit(x1), u.get_unit(x0))
194
-
195
- def test_unit_mismatch_raises_error(self):
196
- """Test that incompatible diffusion units raise an error"""
197
- def drift(x, t):
198
- return -x / (10.0 * u.ms)
199
-
200
- def diffusion(x, t):
201
- # Wrong units: should be mV/sqrt(ms) but returning mV
202
- return 0.1 * u.mV
203
-
204
- with brainstate.environ.context(dt=1.0 * u.ms):
205
- x0 = 1.0 * u.mV
206
- with self.assertRaises(ValueError):
207
- brainstate.nn.exp_euler_step(drift, diffusion, x0, None)
208
-
209
- def test_correct_diffusion_units(self):
210
- """Test SDE with correct diffusion units"""
211
- def drift(x, tau):
212
- return -x / tau
213
-
214
- def diffusion(x, t):
215
- # Correct units: mV/sqrt(ms)
216
- return 0.1 * u.mV / u.ms ** 0.5
217
-
218
- with brainstate.environ.context(dt=1.0 * u.ms):
219
- brainstate.random.seed(42)
220
- x0 = 1.0 * u.mV
221
- tau = 10.0 * u.ms
222
- x1 = brainstate.nn.exp_euler_step(drift, diffusion, x0, tau)
223
-
224
- self.assertEqual(u.get_unit(x1), u.get_unit(x0))
225
-
226
- def test_dimensionless_with_time_units(self):
227
- """Test dimensionless state with time units in dt"""
228
- def drift(x, t):
229
- return -2.0 * x / u.second
230
-
231
- with brainstate.environ.context(dt=0.1 * u.second):
232
- x0 = jnp.array(1.0)
233
- x1 = brainstate.nn.exp_euler_step(drift, x0, None)
234
-
235
- expected = np.exp(-0.2)
236
- np.testing.assert_allclose(x1, expected, rtol=1e-5)
237
-
238
-
239
- class TestExpEulerInputValidation(unittest.TestCase):
240
- """Test cases for input validation in exp_euler_step."""
241
-
242
- def test_non_callable_drift_raises_error(self):
243
- """Test that non-callable drift raises AssertionError"""
244
- with brainstate.environ.context(dt=0.01):
245
- x0 = jnp.array(1.0)
246
- with self.assertRaises(AssertionError):
247
- brainstate.nn.exp_euler_step("not a function", x0, None)
248
-
249
- def test_no_state_variable_raises_error(self):
250
- """Test that missing state variable raises AssertionError"""
251
- def drift(x, t):
252
- return -x
253
-
254
- with brainstate.environ.context(dt=0.01):
255
- with self.assertRaises(AssertionError):
256
- brainstate.nn.exp_euler_step(drift)
257
-
258
- def test_invalid_dtype_raises_error(self):
259
- """Test that invalid dtype raises ValueError"""
260
- def drift(x, t):
261
- return -x
262
-
263
- with brainstate.environ.context(dt=0.01):
264
- x0 = jnp.array(1, dtype=jnp.int32)
265
- with self.assertRaises(ValueError):
266
- brainstate.nn.exp_euler_step(drift, x0, None)
267
-
268
- def test_float16_dtype_accepted(self):
269
- """Test that float16 dtype is accepted"""
270
- def drift(x, t):
271
- return -x
272
-
273
- with brainstate.environ.context(dt=0.01):
274
- x0 = jnp.array(1.0, dtype=jnp.float16)
275
- x1 = brainstate.nn.exp_euler_step(drift, x0, None)
276
- self.assertEqual(x1.dtype, jnp.float16)
277
-
278
- def test_bfloat16_dtype_accepted(self):
279
- """Test that bfloat16 dtype is accepted"""
280
- def drift(x, t):
281
- return -x
282
-
283
- with brainstate.environ.context(dt=0.01):
284
- x0 = jnp.array(1.0, dtype=jnp.bfloat16)
285
- x1 = brainstate.nn.exp_euler_step(drift, x0, None)
286
- self.assertEqual(x1.dtype, jnp.bfloat16)
287
-
288
- def test_diffusion_without_state_raises_error(self):
289
- """Test that diffusion function without state variable raises error"""
290
- def drift(x, t):
291
- return -x
292
-
293
- def diffusion(x, t):
294
- return 0.1
295
-
296
- with brainstate.environ.context(dt=0.01):
297
- with self.assertRaises(AssertionError):
298
- brainstate.nn.exp_euler_step(drift, diffusion)
299
-
300
-
301
- class TestExpEulerEdgeCases(unittest.TestCase):
302
- """Test edge cases and special scenarios."""
303
-
304
- def test_zero_initial_condition(self):
305
- """Test with zero initial condition"""
306
- def drift(x, t):
307
- return -x + 1.0
308
-
309
- with brainstate.environ.context(dt=0.01):
310
- x0 = jnp.array(0.0)
311
- x1 = brainstate.nn.exp_euler_step(drift, x0, None)
312
-
313
- # Should move toward equilibrium at x=1
314
- self.assertGreater(x1, 0.0)
315
-
316
- def test_very_small_timestep(self):
317
- """Test with very small timestep"""
318
- def drift(x, t):
319
- return -x
320
-
321
- with brainstate.environ.context(dt=1e-8):
322
- x0 = jnp.array(1.0)
323
- x1 = brainstate.nn.exp_euler_step(drift, x0, None)
324
-
325
- # Should barely change
326
- np.testing.assert_allclose(x1, x0)
327
-
328
- def test_large_timestep_stability(self):
329
- """Test stability with large timestep (advantage of exponential Euler)"""
330
- def drift(x, t):
331
- return -10.0 * x
332
-
333
- with brainstate.environ.context(dt=1.0):
334
- x0 = jnp.array(1.0)
335
- x1 = brainstate.nn.exp_euler_step(drift, x0, None)
336
-
337
- # Should remain stable (not blow up or oscillate)
338
- expected = np.exp(-10.0)
339
- np.testing.assert_allclose(x1, expected, rtol=1e-1)
340
- self.assertGreater(x1, 0.0)
341
-
342
- def test_kwargs_passed_correctly(self):
343
- """Test that kwargs are passed to drift and diffusion functions"""
344
- def drift(x, scale=1., **kwargs):
345
- return -scale * x
346
-
347
- def diffusion(x, noise_level=0.1, **kwargs):
348
- return noise_level
349
-
350
- with brainstate.environ.context(dt=0.01):
351
- brainstate.random.seed(42)
352
- x0 = jnp.array(1.0)
353
- x1 = brainstate.nn.exp_euler_step(
354
- drift, diffusion, x0,
355
- scale=2.0, noise_level=0.2
356
- )
357
-
358
- self.assertIsInstance(x1, (jnp.ndarray, float))
359
-
360
- def test_reproducibility_with_seed(self):
361
- """Test that results are reproducible with same random seed"""
362
- def drift(x):
363
- return -0.5 * x
364
-
365
- def diffusion(x):
366
- return 0.1
367
-
368
- with brainstate.environ.context(dt=0.01):
369
- x0 = jnp.array(1.0)
370
-
371
- brainstate.random.seed(42)
372
- x1_first = brainstate.nn.exp_euler_step(drift, diffusion, x0)
373
-
374
- brainstate.random.seed(42)
375
- x1_second = brainstate.nn.exp_euler_step(drift, diffusion, x0)
376
-
377
- np.testing.assert_array_equal(x1_first, x1_second)
1
+ # Copyright 2024 BrainX Ecosystem Limited. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+
17
+ import unittest
18
+
19
+ import brainunit as u
20
+ import jax.numpy as jnp
21
+ import numpy as np
22
+
23
+ import brainstate
24
+
25
+
26
+ class TestExpEulerODE(unittest.TestCase):
27
+ """Test cases for ODE integration using exp_euler_step."""
28
+
29
+ def test_exponential_decay(self):
30
+ """Test simple exponential decay: dx/dt = -x"""
31
+ def drift(x, t):
32
+ return -x
33
+
34
+ with brainstate.environ.context(dt=0.01):
35
+ x0 = jnp.array(1.0)
36
+ x1 = brainstate.nn.exp_euler_step(drift, x0, None)
37
+
38
+ # Expected: x(t+dt) ≈ x(t) * exp(-dt) ≈ 0.99004983
39
+ expected = np.exp(-0.01)
40
+ np.testing.assert_allclose(x1, expected)
41
+
42
+ def test_exponential_decay_with_time_constant(self):
43
+ """Test exponential decay with time constant: dx/dt = -x/tau"""
44
+ def drift(x, tau):
45
+ return -x / tau
46
+
47
+ with brainstate.environ.context(dt=1.0 * u.ms):
48
+ x0 = u.math.asarray(1.0 * u.mV)
49
+ tau = 10.0 * u.ms
50
+ x1 = brainstate.nn.exp_euler_step(drift, x0, tau)
51
+
52
+ # Expected: x(t+dt) ≈ x(t) * exp(-dt/tau)
53
+ expected = np.exp(-0.1) * u.mV
54
+ assert u.math.allclose(x1, expected)
55
+
56
+ def test_linear_growth(self):
57
+ """Test linear growth: dx/dt = a"""
58
+ def drift(x):
59
+ return jnp.asarray([2.0])
60
+
61
+ with brainstate.environ.context(dt=0.1):
62
+ x0 = jnp.asarray([1.0])
63
+ x1 = brainstate.nn.exp_euler_step(drift, x0)
64
+
65
+ # For constant derivative, result should be x0 + a*dt
66
+ expected = 1.0 + 2.0 * 0.1
67
+ np.testing.assert_allclose(x1, expected)
68
+
69
+ def test_multidimensional_system(self):
70
+ """Test multi-dimensional ODE: harmonic oscillator"""
71
+ def drift(x, t):
72
+ # dx/dt = [x1, -x0] (circular motion)
73
+ return jnp.array([x[1], -x[0]])
74
+
75
+ with brainstate.environ.context(dt=0.01):
76
+ x0 = jnp.array([1.0, 0.0])
77
+ x1 = brainstate.nn.exp_euler_step(drift, x0, None)
78
+
79
+ # Check that energy is approximately conserved
80
+ energy0 = np.sum(x0 ** 2)
81
+ energy1 = np.sum(x1 ** 2)
82
+ np.testing.assert_allclose(energy1, energy0, rtol=0.1)
83
+
84
+ def test_stiff_equation(self):
85
+ """Test stiff equation where exponential Euler should be stable"""
86
+ def drift(x, t):
87
+ # Stiff equation: dx/dt = -100*x
88
+ return -100.0 * x
89
+
90
+ with brainstate.environ.context(dt=0.1):
91
+ x0 = jnp.array(1.0)
92
+ x1 = brainstate.nn.exp_euler_step(drift, x0, None)
93
+
94
+ # Should remain stable and decay
95
+ expected = np.exp(-10.0)
96
+ np.testing.assert_allclose(x1, expected, rtol=1e-2)
97
+ self.assertGreater(x1, 0.0) # Should not become negative
98
+
99
+
100
+ class TestExpEulerSDE(unittest.TestCase):
101
+ """Test cases for SDE integration using exp_euler_step."""
102
+
103
+ def test_simple_sde_with_constant_diffusion(self):
104
+ """Test SDE with constant diffusion: dx = -x*dt + sigma*dW"""
105
+ def drift(x, t):
106
+ return -x
107
+
108
+ def diffusion(x, t):
109
+ return jnp.array(0.1)
110
+
111
+ with brainstate.environ.context(dt=0.01):
112
+ brainstate.random.seed(42)
113
+ x0 = jnp.array(1.0)
114
+ x1 = brainstate.nn.exp_euler_step(drift, diffusion, x0, None)
115
+
116
+ # Result should have both drift and diffusion components
117
+ # Cannot test exact value due to randomness, but check it's reasonable
118
+ self.assertIsInstance(x1, (jnp.ndarray, float))
119
+
120
+ def test_ornstein_uhlenbeck_process(self):
121
+ """Test Ornstein-Uhlenbeck process: dx = -theta*x*dt + sigma*dW"""
122
+ theta = 0.5
123
+ sigma = 0.3
124
+
125
+ def drift(x, t):
126
+ return -theta * x
127
+
128
+ def diffusion(x, t):
129
+ return jnp.full_like(x, sigma)
130
+
131
+ with brainstate.environ.context(dt=0.01):
132
+ brainstate.random.seed(123)
133
+ x0 = jnp.array(1.0)
134
+ x1 = brainstate.nn.exp_euler_step(drift, diffusion, x0, None)
135
+
136
+ # Mean should decrease (drift dominates initially)
137
+ # Run multiple steps and check statistics
138
+ x = x0
139
+ results = []
140
+ for _ in range(100):
141
+ x = brainstate.nn.exp_euler_step(drift, diffusion, x, None)
142
+ results.append(x)
143
+
144
+ # Mean should converge toward 0
145
+ final_mean = np.mean(results[-10:])
146
+ self.assertLess(abs(final_mean), 0.5)
147
+
148
+ def test_sde_multidimensional(self):
149
+ """Test multi-dimensional SDE"""
150
+ def drift(x, t):
151
+ return -0.5 * x
152
+
153
+ def diffusion(x, t):
154
+ return jnp.array([0.1, 0.2])
155
+
156
+ with brainstate.environ.context(dt=0.01):
157
+ brainstate.random.seed(456)
158
+ x0 = jnp.array([1.0, 1.0])
159
+ x1 = brainstate.nn.exp_euler_step(drift, diffusion, x0, None)
160
+
161
+ self.assertEqual(x1.shape, (2,))
162
+
163
+ def test_state_dependent_diffusion(self):
164
+ """Test SDE with state-dependent diffusion: dx = -x*dt + sqrt(x)*dW"""
165
+ def drift(x, t):
166
+ return -0.1 * x
167
+
168
+ def diffusion(x, t):
169
+ return jnp.sqrt(jnp.abs(x) + 1e-8)
170
+
171
+ with brainstate.environ.context(dt=0.01):
172
+ brainstate.random.seed(789)
173
+ x0 = jnp.array(1.0)
174
+ x1 = brainstate.nn.exp_euler_step(drift, diffusion, x0, None)
175
+
176
+ self.assertIsInstance(x1, (jnp.ndarray, float))
177
+
178
+
179
+ class TestExpEulerUnits(unittest.TestCase):
180
+ """Test cases for unit handling in exp_euler_step."""
181
+
182
+ def test_unit_compatibility_drift(self):
183
+ """Test that drift function units are validated correctly"""
184
+ def drift(x, tau):
185
+ return -x / tau
186
+
187
+ with brainstate.environ.context(dt=1.0 * u.ms):
188
+ x0 = 1.0 * u.mV
189
+ tau = 10.0 * u.ms
190
+ x1 = brainstate.nn.exp_euler_step(drift, x0, tau)
191
+
192
+ # Result should have same units as input
193
+ self.assertEqual(u.get_unit(x1), u.get_unit(x0))
194
+
195
+ def test_unit_mismatch_raises_error(self):
196
+ """Test that incompatible diffusion units raise an error"""
197
+ def drift(x, t):
198
+ return -x / (10.0 * u.ms)
199
+
200
+ def diffusion(x, t):
201
+ # Wrong units: should be mV/sqrt(ms) but returning mV
202
+ return 0.1 * u.mV
203
+
204
+ with brainstate.environ.context(dt=1.0 * u.ms):
205
+ x0 = 1.0 * u.mV
206
+ with self.assertRaises(ValueError):
207
+ brainstate.nn.exp_euler_step(drift, diffusion, x0, None)
208
+
209
+ def test_correct_diffusion_units(self):
210
+ """Test SDE with correct diffusion units"""
211
+ def drift(x, tau):
212
+ return -x / tau
213
+
214
+ def diffusion(x, t):
215
+ # Correct units: mV/sqrt(ms)
216
+ return 0.1 * u.mV / u.ms ** 0.5
217
+
218
+ with brainstate.environ.context(dt=1.0 * u.ms):
219
+ brainstate.random.seed(42)
220
+ x0 = 1.0 * u.mV
221
+ tau = 10.0 * u.ms
222
+ x1 = brainstate.nn.exp_euler_step(drift, diffusion, x0, tau)
223
+
224
+ self.assertEqual(u.get_unit(x1), u.get_unit(x0))
225
+
226
+ def test_dimensionless_with_time_units(self):
227
+ """Test dimensionless state with time units in dt"""
228
+ def drift(x, t):
229
+ return -2.0 * x / u.second
230
+
231
+ with brainstate.environ.context(dt=0.1 * u.second):
232
+ x0 = jnp.array(1.0)
233
+ x1 = brainstate.nn.exp_euler_step(drift, x0, None)
234
+
235
+ expected = np.exp(-0.2)
236
+ np.testing.assert_allclose(x1, expected, rtol=1e-5)
237
+
238
+
239
+ class TestExpEulerInputValidation(unittest.TestCase):
240
+ """Test cases for input validation in exp_euler_step."""
241
+
242
+ def test_non_callable_drift_raises_error(self):
243
+ """Test that non-callable drift raises AssertionError"""
244
+ with brainstate.environ.context(dt=0.01):
245
+ x0 = jnp.array(1.0)
246
+ with self.assertRaises(AssertionError):
247
+ brainstate.nn.exp_euler_step("not a function", x0, None)
248
+
249
+ def test_no_state_variable_raises_error(self):
250
+ """Test that missing state variable raises AssertionError"""
251
+ def drift(x, t):
252
+ return -x
253
+
254
+ with brainstate.environ.context(dt=0.01):
255
+ with self.assertRaises(AssertionError):
256
+ brainstate.nn.exp_euler_step(drift)
257
+
258
+ def test_invalid_dtype_raises_error(self):
259
+ """Test that invalid dtype raises ValueError"""
260
+ def drift(x, t):
261
+ return -x
262
+
263
+ with brainstate.environ.context(dt=0.01):
264
+ x0 = jnp.array(1, dtype=jnp.int32)
265
+ with self.assertRaises(ValueError):
266
+ brainstate.nn.exp_euler_step(drift, x0, None)
267
+
268
+ def test_float16_dtype_accepted(self):
269
+ """Test that float16 dtype is accepted"""
270
+ def drift(x, t):
271
+ return -x
272
+
273
+ with brainstate.environ.context(dt=0.01):
274
+ x0 = jnp.array(1.0, dtype=jnp.float16)
275
+ x1 = brainstate.nn.exp_euler_step(drift, x0, None)
276
+ self.assertEqual(x1.dtype, jnp.float16)
277
+
278
+ def test_bfloat16_dtype_accepted(self):
279
+ """Test that bfloat16 dtype is accepted"""
280
+ def drift(x, t):
281
+ return -x
282
+
283
+ with brainstate.environ.context(dt=0.01):
284
+ x0 = jnp.array(1.0, dtype=jnp.bfloat16)
285
+ x1 = brainstate.nn.exp_euler_step(drift, x0, None)
286
+ self.assertEqual(x1.dtype, jnp.bfloat16)
287
+
288
+ def test_diffusion_without_state_raises_error(self):
289
+ """Test that diffusion function without state variable raises error"""
290
+ def drift(x, t):
291
+ return -x
292
+
293
+ def diffusion(x, t):
294
+ return 0.1
295
+
296
+ with brainstate.environ.context(dt=0.01):
297
+ with self.assertRaises(AssertionError):
298
+ brainstate.nn.exp_euler_step(drift, diffusion)
299
+
300
+
301
+ class TestExpEulerEdgeCases(unittest.TestCase):
302
+ """Test edge cases and special scenarios."""
303
+
304
+ def test_zero_initial_condition(self):
305
+ """Test with zero initial condition"""
306
+ def drift(x, t):
307
+ return -x + 1.0
308
+
309
+ with brainstate.environ.context(dt=0.01):
310
+ x0 = jnp.array(0.0)
311
+ x1 = brainstate.nn.exp_euler_step(drift, x0, None)
312
+
313
+ # Should move toward equilibrium at x=1
314
+ self.assertGreater(x1, 0.0)
315
+
316
+ def test_very_small_timestep(self):
317
+ """Test with very small timestep"""
318
+ def drift(x, t):
319
+ return -x
320
+
321
+ with brainstate.environ.context(dt=1e-8):
322
+ x0 = jnp.array(1.0)
323
+ x1 = brainstate.nn.exp_euler_step(drift, x0, None)
324
+
325
+ # Should barely change
326
+ np.testing.assert_allclose(x1, x0)
327
+
328
+ def test_large_timestep_stability(self):
329
+ """Test stability with large timestep (advantage of exponential Euler)"""
330
+ def drift(x, t):
331
+ return -10.0 * x
332
+
333
+ with brainstate.environ.context(dt=1.0):
334
+ x0 = jnp.array(1.0)
335
+ x1 = brainstate.nn.exp_euler_step(drift, x0, None)
336
+
337
+ # Should remain stable (not blow up or oscillate)
338
+ expected = np.exp(-10.0)
339
+ np.testing.assert_allclose(x1, expected, rtol=1e-1)
340
+ self.assertGreater(x1, 0.0)
341
+
342
+ def test_kwargs_passed_correctly(self):
343
+ """Test that kwargs are passed to drift and diffusion functions"""
344
+ def drift(x, scale=1., **kwargs):
345
+ return -scale * x
346
+
347
+ def diffusion(x, noise_level=0.1, **kwargs):
348
+ return noise_level
349
+
350
+ with brainstate.environ.context(dt=0.01):
351
+ brainstate.random.seed(42)
352
+ x0 = jnp.array(1.0)
353
+ x1 = brainstate.nn.exp_euler_step(
354
+ drift, diffusion, x0,
355
+ scale=2.0, noise_level=0.2
356
+ )
357
+
358
+ self.assertIsInstance(x1, (jnp.ndarray, float))
359
+
360
+ def test_reproducibility_with_seed(self):
361
+ """Test that results are reproducible with same random seed"""
362
+ def drift(x):
363
+ return -0.5 * x
364
+
365
+ def diffusion(x):
366
+ return 0.1
367
+
368
+ with brainstate.environ.context(dt=0.01):
369
+ x0 = jnp.array(1.0)
370
+
371
+ brainstate.random.seed(42)
372
+ x1_first = brainstate.nn.exp_euler_step(drift, diffusion, x0)
373
+
374
+ brainstate.random.seed(42)
375
+ x1_second = brainstate.nn.exp_euler_step(drift, diffusion, x0)
376
+
377
+ np.testing.assert_array_equal(x1_first, x1_second)