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,254 +1,254 @@
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
- from typing import Callable
18
-
19
- import brainunit as u
20
- import jax.numpy as jnp
21
-
22
- from brainstate import environ, random
23
- from brainstate.transform import vector_grad
24
-
25
- __all__ = [
26
- 'exp_euler_step',
27
- ]
28
-
29
-
30
- def exp_euler_step(
31
- fn: Callable, *args, **kwargs
32
- ):
33
- r"""
34
- One-step Exponential Euler method for solving ODEs and SDEs.
35
-
36
- The Exponential Euler method is a numerical integration scheme that provides improved
37
- stability for stiff differential equations by exactly integrating the linear part of
38
- the equation. For ODEs, it solves equations of the form:
39
-
40
- .. math::
41
- \frac{dx}{dt} = f(x, t)
42
-
43
- For SDEs, it handles equations of the form:
44
-
45
- .. math::
46
- dx = f(x, t)dt + g(x, t)dW
47
-
48
- where :math:`f(x, t)` is the drift term and :math:`g(x, t)` is the diffusion term.
49
-
50
- The method linearizes the drift function around the current state and uses the
51
- matrix exponential to integrate the linear part exactly, while treating the
52
- remainder with standard Euler stepping.
53
-
54
- Parameters
55
- ----------
56
- fn : Callable
57
- The drift function :math:`f(x, t)` to be integrated. This function should
58
- take the state variable as the first argument, followed by optional time
59
- and other arguments. It should return the derivative :math:`dx/dt`.
60
- *args
61
- Variable arguments. If the first argument is callable, it is treated as
62
- the diffusion function for SDE integration. Otherwise, arguments are
63
- passed to the drift function. The first non-callable argument should be
64
- the state variable :math:`x`.
65
- **kwargs
66
- Additional keyword arguments passed to the drift and diffusion functions.
67
-
68
- Returns
69
- -------
70
- x_next : ArrayLike
71
- The state variable after one integration step of size ``dt``, where ``dt``
72
- is obtained from the environment via ``environ.get('dt')``.
73
-
74
- Raises
75
- ------
76
- ValueError
77
- If the input state variable dtype is not float16, bfloat16, float32, or float64.
78
- ValueError
79
- If drift and diffusion terms have incompatible units.
80
- AssertionError
81
- If ``fn`` is not callable or if no state variable is provided in ``*args``.
82
-
83
- Notes
84
- -----
85
- **Unit Compatibility:**
86
-
87
- - If the state variable :math:`x` has units :math:`[X]`, the drift function
88
- :math:`f(x, t)` should return values with units :math:`[X]/[T]`, where
89
- :math:`[T]` is the unit of time.
90
-
91
- - If the state variable :math:`x` has units :math:`[X]`, the diffusion function
92
- :math:`g(x, t)` should return values with units :math:`[X]/\sqrt{[T]}`.
93
-
94
- **Algorithm:**
95
-
96
- The method computes the Jacobian :math:`J = \frac{\partial f}{\partial x}` and
97
- uses the exponential-related function :math:`\varphi(z) = (e^z - 1)/z` to update:
98
-
99
- .. math::
100
- x_{n+1} = x_n + dt \cdot \varphi(dt \cdot J) \cdot f(x_n, t_n)
101
-
102
- For SDEs, a stochastic term is added:
103
-
104
- .. math::
105
- x_{n+1} = x_{n+1} + g(x_n, t_n) \sqrt{dt} \cdot \mathcal{N}(0, I)
106
-
107
- Examples
108
- --------
109
- **ODE Integration:**
110
-
111
- Simple exponential decay equation :math:`\frac{dx}{dt} = -x`:
112
-
113
- .. code-block:: python
114
-
115
- >>> import brainstate as bst
116
- >>> import jax.numpy as jnp
117
- >>>
118
- >>> # Set time step in environment
119
- >>> bst.environ.set(dt=0.01)
120
- >>>
121
- >>> # Define drift function
122
- >>> def drift(x, t):
123
- ... return -x
124
- >>>
125
- >>> # Initial condition
126
- >>> x0 = jnp.array(1.0)
127
- >>>
128
- >>> # Single integration step
129
- >>> x1 = bst.nn.exp_euler_step(drift, x0, None)
130
- >>> print(x1) # Should be close to exp(-0.01) ≈ 0.99
131
-
132
- **SDE Integration:**
133
-
134
- Ornstein-Uhlenbeck process :math:`dx = -\theta x dt + \sigma dW`:
135
-
136
- .. code-block:: python
137
-
138
- >>> import brainstate as bst
139
- >>> import jax.numpy as jnp
140
- >>>
141
- >>> # Set time step
142
- >>> bst.environ.set(dt=0.01)
143
- >>>
144
- >>> # Define drift and diffusion
145
- >>> theta = 0.5
146
- >>> sigma = 0.3
147
- >>>
148
- >>> def drift(x, t):
149
- ... return -theta * x
150
- >>>
151
- >>> def diffusion(x, t):
152
- ... return jnp.full_like(x, sigma)
153
- >>>
154
- >>> # Initial condition
155
- >>> x0 = jnp.array(1.0)
156
- >>>
157
- >>> # Single SDE integration step
158
- >>> x1 = bst.nn.exp_euler_step(drift, diffusion, x0, None)
159
-
160
- **Multi-dimensional system:**
161
-
162
- .. code-block:: python
163
-
164
- >>> import brainstate as bst
165
- >>> import jax.numpy as jnp
166
- >>>
167
- >>> bst.environ.set(dt=0.01)
168
- >>>
169
- >>> # Coupled oscillator system
170
- >>> def drift(x, t):
171
- ... x1, x2 = x[0], x[1]
172
- ... return jnp.array([-x1 + x2, -x2 - x1])
173
- >>>
174
- >>> x0 = jnp.array([1.0, 0.0])
175
- >>> x1 = bst.nn.exp_euler_step(drift, x0, None)
176
-
177
- See Also
178
- --------
179
- brainstate.transform.vector_grad : Compute vector-Jacobian product used internally.
180
- brainstate.environ.get : Retrieve environment variables like ``dt``.
181
-
182
- References
183
- ----------
184
- .. [1] Hochbruck, M., & Ostermann, A. (2010). Exponential integrators.
185
- Acta Numerica, 19, 209-286.
186
- .. [2] Cox, S. M., & Matthews, P. C. (2002). Exponential time differencing
187
- for stiff systems. Journal of Computational Physics, 176(2), 430-455.
188
- """
189
- # Validate inputs
190
- assert callable(fn), 'The drift function should be callable.'
191
- assert len(args) > 0, 'The input arguments should not be empty.'
192
-
193
- # Parse arguments: check if first arg is diffusion function
194
- diffusion = None
195
- if callable(args[0]):
196
- diffusion = args[0]
197
- args = args[1:]
198
- assert len(args) > 0, 'State variable is required after diffusion function.'
199
-
200
- # Validate state variable dtype
201
- state = u.math.asarray(args[0])
202
- dtype = u.math.get_dtype(state)
203
- if dtype not in [jnp.float16, jnp.bfloat16, jnp.float32, jnp.float64]:
204
- raise ValueError(
205
- f'State variable dtype must be float16, bfloat16, float32, or float64 '
206
- f'for Exponential Euler method, but got {dtype}.'
207
- )
208
-
209
- # Get time step from environment
210
- dt = environ.get_dt()
211
-
212
- # Compute drift term with Jacobian
213
- # vector_grad returns (Jacobian, function_value)
214
- jacobian, drift_value = vector_grad(fn, argnums=0, return_value=True)(*args, **kwargs)
215
-
216
- # Convert Jacobian to proper units: [derivative_unit / state_unit] = [1/T]
217
- jacobian_with_unit = u.Quantity(
218
- u.get_mantissa(jacobian),
219
- u.get_unit(drift_value) / u.get_unit(jacobian)
220
- )
221
-
222
- # Compute phi function: phi(z) = (exp(z) - 1) / z
223
- # This is the exponential-related function for stability
224
- phi = u.math.exprel(dt * jacobian_with_unit)
225
-
226
- # Update state using exponential Euler scheme
227
- x_next = state + dt * phi * drift_value
228
-
229
- # Add diffusion term for SDE if provided
230
- if diffusion is not None:
231
- # Compute diffusion coefficient
232
- diffusion_coef = diffusion(*args, **kwargs)
233
-
234
- # Generate random noise and scale by sqrt(dt)
235
- noise = random.randn_like(state)
236
- diffusion_term = diffusion_coef * u.math.sqrt(dt) * noise
237
-
238
- # Validate unit compatibility between drift and diffusion
239
- if u.get_dim(x_next) != u.get_dim(diffusion_term):
240
- drift_unit = u.get_unit(x_next)
241
- time_unit = u.get_unit(dt)
242
- expected_diffusion_unit = drift_unit / time_unit ** 0.5
243
- actual_diffusion_unit = u.get_unit(diffusion_term)
244
- raise ValueError(
245
- f"Unit mismatch between drift and diffusion terms. "
246
- f"State has unit {u.get_unit(state)}, "
247
- f"drift produces unit {drift_unit}, "
248
- f"expected diffusion unit {expected_diffusion_unit}, "
249
- f"but got {actual_diffusion_unit}."
250
- )
251
-
252
- x_next = x_next + diffusion_term
253
-
254
- return x_next
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
+ from typing import Callable
18
+
19
+ import brainunit as u
20
+ import jax.numpy as jnp
21
+
22
+ from brainstate import environ, random
23
+ from brainstate.transform import vector_grad
24
+
25
+ __all__ = [
26
+ 'exp_euler_step',
27
+ ]
28
+
29
+
30
+ def exp_euler_step(
31
+ fn: Callable, *args, **kwargs
32
+ ):
33
+ r"""
34
+ One-step Exponential Euler method for solving ODEs and SDEs.
35
+
36
+ The Exponential Euler method is a numerical integration scheme that provides improved
37
+ stability for stiff differential equations by exactly integrating the linear part of
38
+ the equation. For ODEs, it solves equations of the form:
39
+
40
+ .. math::
41
+ \frac{dx}{dt} = f(x, t)
42
+
43
+ For SDEs, it handles equations of the form:
44
+
45
+ .. math::
46
+ dx = f(x, t)dt + g(x, t)dW
47
+
48
+ where :math:`f(x, t)` is the drift term and :math:`g(x, t)` is the diffusion term.
49
+
50
+ The method linearizes the drift function around the current state and uses the
51
+ matrix exponential to integrate the linear part exactly, while treating the
52
+ remainder with standard Euler stepping.
53
+
54
+ Parameters
55
+ ----------
56
+ fn : Callable
57
+ The drift function :math:`f(x, t)` to be integrated. This function should
58
+ take the state variable as the first argument, followed by optional time
59
+ and other arguments. It should return the derivative :math:`dx/dt`.
60
+ *args
61
+ Variable arguments. If the first argument is callable, it is treated as
62
+ the diffusion function for SDE integration. Otherwise, arguments are
63
+ passed to the drift function. The first non-callable argument should be
64
+ the state variable :math:`x`.
65
+ **kwargs
66
+ Additional keyword arguments passed to the drift and diffusion functions.
67
+
68
+ Returns
69
+ -------
70
+ x_next : ArrayLike
71
+ The state variable after one integration step of size ``dt``, where ``dt``
72
+ is obtained from the environment via ``environ.get('dt')``.
73
+
74
+ Raises
75
+ ------
76
+ ValueError
77
+ If the input state variable dtype is not float16, bfloat16, float32, or float64.
78
+ ValueError
79
+ If drift and diffusion terms have incompatible units.
80
+ AssertionError
81
+ If ``fn`` is not callable or if no state variable is provided in ``*args``.
82
+
83
+ Notes
84
+ -----
85
+ **Unit Compatibility:**
86
+
87
+ - If the state variable :math:`x` has units :math:`[X]`, the drift function
88
+ :math:`f(x, t)` should return values with units :math:`[X]/[T]`, where
89
+ :math:`[T]` is the unit of time.
90
+
91
+ - If the state variable :math:`x` has units :math:`[X]`, the diffusion function
92
+ :math:`g(x, t)` should return values with units :math:`[X]/\sqrt{[T]}`.
93
+
94
+ **Algorithm:**
95
+
96
+ The method computes the Jacobian :math:`J = \frac{\partial f}{\partial x}` and
97
+ uses the exponential-related function :math:`\varphi(z) = (e^z - 1)/z` to update:
98
+
99
+ .. math::
100
+ x_{n+1} = x_n + dt \cdot \varphi(dt \cdot J) \cdot f(x_n, t_n)
101
+
102
+ For SDEs, a stochastic term is added:
103
+
104
+ .. math::
105
+ x_{n+1} = x_{n+1} + g(x_n, t_n) \sqrt{dt} \cdot \mathcal{N}(0, I)
106
+
107
+ Examples
108
+ --------
109
+ **ODE Integration:**
110
+
111
+ Simple exponential decay equation :math:`\frac{dx}{dt} = -x`:
112
+
113
+ .. code-block:: python
114
+
115
+ >>> import brainstate as brainstate
116
+ >>> import jax.numpy as jnp
117
+ >>>
118
+ >>> # Set time step in environment
119
+ >>> brainstate.environ.set(dt=0.01)
120
+ >>>
121
+ >>> # Define drift function
122
+ >>> def drift(x, t):
123
+ ... return -x
124
+ >>>
125
+ >>> # Initial condition
126
+ >>> x0 = jnp.array(1.0)
127
+ >>>
128
+ >>> # Single integration step
129
+ >>> x1 = brainstate.nn.exp_euler_step(drift, x0, None)
130
+ >>> print(x1) # Should be close to exp(-0.01) ≈ 0.99
131
+
132
+ **SDE Integration:**
133
+
134
+ Ornstein-Uhlenbeck process :math:`dx = -\theta x dt + \sigma dW`:
135
+
136
+ .. code-block:: python
137
+
138
+ >>> import brainstate as brainstate
139
+ >>> import jax.numpy as jnp
140
+ >>>
141
+ >>> # Set time step
142
+ >>> brainstate.environ.set(dt=0.01)
143
+ >>>
144
+ >>> # Define drift and diffusion
145
+ >>> theta = 0.5
146
+ >>> sigma = 0.3
147
+ >>>
148
+ >>> def drift(x, t):
149
+ ... return -theta * x
150
+ >>>
151
+ >>> def diffusion(x, t):
152
+ ... return jnp.full_like(x, sigma)
153
+ >>>
154
+ >>> # Initial condition
155
+ >>> x0 = jnp.array(1.0)
156
+ >>>
157
+ >>> # Single SDE integration step
158
+ >>> x1 = brainstate.nn.exp_euler_step(drift, diffusion, x0, None)
159
+
160
+ **Multi-dimensional system:**
161
+
162
+ .. code-block:: python
163
+
164
+ >>> import brainstate as brainstate
165
+ >>> import jax.numpy as jnp
166
+ >>>
167
+ >>> brainstate.environ.set(dt=0.01)
168
+ >>>
169
+ >>> # Coupled oscillator system
170
+ >>> def drift(x, t):
171
+ ... x1, x2 = x[0], x[1]
172
+ ... return jnp.array([-x1 + x2, -x2 - x1])
173
+ >>>
174
+ >>> x0 = jnp.array([1.0, 0.0])
175
+ >>> x1 = brainstate.nn.exp_euler_step(drift, x0, None)
176
+
177
+ See Also
178
+ --------
179
+ brainstate.transform.vector_grad : Compute vector-Jacobian product used internally.
180
+ brainstate.environ.get : Retrieve environment variables like ``dt``.
181
+
182
+ References
183
+ ----------
184
+ .. [1] Hochbruck, M., & Ostermann, A. (2010). Exponential integrators.
185
+ Acta Numerica, 19, 209-286.
186
+ .. [2] Cox, S. M., & Matthews, P. C. (2002). Exponential time differencing
187
+ for stiff systems. Journal of Computational Physics, 176(2), 430-455.
188
+ """
189
+ # Validate inputs
190
+ assert callable(fn), 'The drift function should be callable.'
191
+ assert len(args) > 0, 'The input arguments should not be empty.'
192
+
193
+ # Parse arguments: check if first arg is diffusion function
194
+ diffusion = None
195
+ if callable(args[0]):
196
+ diffusion = args[0]
197
+ args = args[1:]
198
+ assert len(args) > 0, 'State variable is required after diffusion function.'
199
+
200
+ # Validate state variable dtype
201
+ state = u.math.asarray(args[0])
202
+ dtype = u.math.get_dtype(state)
203
+ if dtype not in [jnp.float16, jnp.bfloat16, jnp.float32, jnp.float64]:
204
+ raise ValueError(
205
+ f'State variable dtype must be float16, bfloat16, float32, or float64 '
206
+ f'for Exponential Euler method, but got {dtype}.'
207
+ )
208
+
209
+ # Get time step from environment
210
+ dt = environ.get_dt()
211
+
212
+ # Compute drift term with Jacobian
213
+ # vector_grad returns (Jacobian, function_value)
214
+ jacobian, drift_value = vector_grad(fn, argnums=0, return_value=True)(*args, **kwargs)
215
+
216
+ # Convert Jacobian to proper units: [derivative_unit / state_unit] = [1/T]
217
+ jacobian_with_unit = u.Quantity(
218
+ u.get_mantissa(jacobian),
219
+ u.get_unit(drift_value) / u.get_unit(jacobian)
220
+ )
221
+
222
+ # Compute phi function: phi(z) = (exp(z) - 1) / z
223
+ # This is the exponential-related function for stability
224
+ phi = u.math.exprel(dt * jacobian_with_unit)
225
+
226
+ # Update state using exponential Euler scheme
227
+ x_next = state + dt * phi * drift_value
228
+
229
+ # Add diffusion term for SDE if provided
230
+ if diffusion is not None:
231
+ # Compute diffusion coefficient
232
+ diffusion_coef = diffusion(*args, **kwargs)
233
+
234
+ # Generate random noise and scale by sqrt(dt)
235
+ noise = random.randn_like(state)
236
+ diffusion_term = diffusion_coef * u.math.sqrt(dt) * noise
237
+
238
+ # Validate unit compatibility between drift and diffusion
239
+ if u.get_dim(x_next) != u.get_dim(diffusion_term):
240
+ drift_unit = u.get_unit(x_next)
241
+ time_unit = u.get_unit(dt)
242
+ expected_diffusion_unit = drift_unit / time_unit ** 0.5
243
+ actual_diffusion_unit = u.get_unit(diffusion_term)
244
+ raise ValueError(
245
+ f"Unit mismatch between drift and diffusion terms. "
246
+ f"State has unit {u.get_unit(state)}, "
247
+ f"drift produces unit {drift_unit}, "
248
+ f"expected diffusion unit {expected_diffusion_unit}, "
249
+ f"but got {actual_diffusion_unit}."
250
+ )
251
+
252
+ x_next = x_next + diffusion_term
253
+
254
+ return x_next