exponax-spde 0.2.0__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 (68) hide show
  1. exponax_spde/__init__.py +104 -0
  2. exponax_spde/_base_stepper.py +271 -0
  3. exponax_spde/_forced_stepper.py +108 -0
  4. exponax_spde/_interpolation.py +285 -0
  5. exponax_spde/_repeated_stepper.py +139 -0
  6. exponax_spde/_spectral.py +1172 -0
  7. exponax_spde/_stochastic_utils.py +672 -0
  8. exponax_spde/_utils.py +348 -0
  9. exponax_spde/etdrk/__init__.py +22 -0
  10. exponax_spde/etdrk/_base_etdrk.py +80 -0
  11. exponax_spde/etdrk/_etdrk_0.py +34 -0
  12. exponax_spde/etdrk/_etdrk_1.py +82 -0
  13. exponax_spde/etdrk/_etdrk_2.py +102 -0
  14. exponax_spde/etdrk/_etdrk_3.py +212 -0
  15. exponax_spde/etdrk/_etdrk_4.py +224 -0
  16. exponax_spde/etdrk/_utils.py +23 -0
  17. exponax_spde/ic/__init__.py +42 -0
  18. exponax_spde/ic/_base_ic.py +99 -0
  19. exponax_spde/ic/_clamping.py +37 -0
  20. exponax_spde/ic/_diffused_noise.py +81 -0
  21. exponax_spde/ic/_discontinuities.py +168 -0
  22. exponax_spde/ic/_gaussian_blob.py +165 -0
  23. exponax_spde/ic/_gaussian_random_field.py +93 -0
  24. exponax_spde/ic/_multi_channel.py +95 -0
  25. exponax_spde/ic/_scaled.py +41 -0
  26. exponax_spde/ic/_sine_waves_1d.py +179 -0
  27. exponax_spde/ic/_truncated_fourier_series.py +100 -0
  28. exponax_spde/ic/_white_noise.py +32 -0
  29. exponax_spde/metrics/__init__.py +56 -0
  30. exponax_spde/metrics/_correlation.py +60 -0
  31. exponax_spde/metrics/_derivative.py +366 -0
  32. exponax_spde/metrics/_fourier.py +588 -0
  33. exponax_spde/metrics/_spatial.py +637 -0
  34. exponax_spde/metrics/_utils.py +18 -0
  35. exponax_spde/nonlin_fun/__init__.py +104 -0
  36. exponax_spde/nonlin_fun/_base.py +159 -0
  37. exponax_spde/nonlin_fun/_convection.py +245 -0
  38. exponax_spde/nonlin_fun/_general_nonlinear.py +119 -0
  39. exponax_spde/nonlin_fun/_gradient_norm.py +101 -0
  40. exponax_spde/nonlin_fun/_leray.py +136 -0
  41. exponax_spde/nonlin_fun/_polynomial.py +76 -0
  42. exponax_spde/nonlin_fun/_projected_convection.py +226 -0
  43. exponax_spde/nonlin_fun/_tamed_polynomial.py +85 -0
  44. exponax_spde/nonlin_fun/_vorticity_convection.py +182 -0
  45. exponax_spde/nonlin_fun/_zero.py +38 -0
  46. exponax_spde/stepper/__init__.py +94 -0
  47. exponax_spde/stepper/_burgers.py +155 -0
  48. exponax_spde/stepper/_heat_equation.py +122 -0
  49. exponax_spde/stepper/generic/__init__.py +67 -0
  50. exponax_spde/stepper/generic/_convection.py +372 -0
  51. exponax_spde/stepper/generic/_linear.py +339 -0
  52. exponax_spde/stepper/generic/_nonlinear.py +403 -0
  53. exponax_spde/stepper/generic/_polynomial.py +338 -0
  54. exponax_spde/stepper/generic/_utils.py +546 -0
  55. exponax_spde/stepper/reaction/__init__.py +17 -0
  56. exponax_spde/stepper/reaction/_allen_cahn.py +128 -0
  57. exponax_spde/stepper/stochastic/__init__.py +36 -0
  58. exponax_spde/stepper/stochastic/_stochastic_allen_cahn.py +605 -0
  59. exponax_spde/viz/__init__.py +74 -0
  60. exponax_spde/viz/_animate.py +357 -0
  61. exponax_spde/viz/_animate_facet.py +448 -0
  62. exponax_spde/viz/_plot.py +434 -0
  63. exponax_spde/viz/_plot_facet.py +489 -0
  64. exponax_spde/viz/_volume.py +144 -0
  65. exponax_spde-0.2.0.dist-info/METADATA +391 -0
  66. exponax_spde-0.2.0.dist-info/RECORD +68 -0
  67. exponax_spde-0.2.0.dist-info/WHEEL +4 -0
  68. exponax_spde-0.2.0.dist-info/licenses/LICENSE.txt +22 -0
@@ -0,0 +1,104 @@
1
+ """
2
+ exponax-spde
3
+ ============
4
+ Stochastic PDE solvers built on top of `exponax`.
5
+
6
+ Public API
7
+ ----------
8
+ StochasticAllenCahn
9
+ Exponential Euler-Maruyama (EEM) integrator for the stochastic
10
+ Allen-Cahn SPDE with additive or multiplicative Q-Wiener noise,
11
+ in 1-D, 2-D, and 3-D on periodic domains.
12
+
13
+ TamedPolynomialNonlinearFun
14
+ Drop-in replacement for ``exponax.nonlin_fun.PolynomialNonlinearFun``
15
+ with optional Hutzenthaler-Jentzen taming; useful for any SPDE whose
16
+ nonlinear term grows super-linearly (polynomial order ≥ 3).
17
+
18
+ Stochastic utilities (also available as ``spde.<fn>``):
19
+ stochastic_rollout
20
+ stochastic_ensemble_rollout
21
+ stochastic_structure_factor
22
+ structure_factor
23
+ richardson_weak_extrapolation
24
+ strang_split_step
25
+
26
+ Usage
27
+ -----
28
+ import exponax_spde as spde
29
+
30
+ stepper = spde.StochasticAllenCahn(
31
+ num_spatial_dims=1, domain_extent=1.0, num_points=128, dt=5e-4,
32
+ diffusivity=0.01, lambda_=1.0, sigma=0.1, noise_alpha=1.5,
33
+ )
34
+ trajectory = jax.jit(
35
+ spde.stochastic_rollout(stepper, num_steps=500, include_init=True)
36
+ )(u0, jax.random.PRNGKey(0))
37
+ """
38
+
39
+ import importlib.metadata
40
+
41
+ from . import _spectral as spectral
42
+ from . import etdrk, ic, metrics, nonlin_fun, stepper, viz
43
+ from ._base_stepper import BaseStepper
44
+ from ._forced_stepper import ForcedStepper
45
+ from ._interpolation import FourierInterpolator, map_between_resolutions
46
+ from ._repeated_stepper import RepeatedStepper
47
+ from ._spectral import derivative, fft, get_spectrum, ifft
48
+ from ._stochastic_utils import (
49
+ richardson_weak_extrapolation,
50
+ stochastic_ensemble_rollout,
51
+ stochastic_rollout,
52
+ stochastic_structure_factor,
53
+ strang_split_step,
54
+ structure_factor,
55
+ )
56
+ from ._utils import (
57
+ build_ic_set,
58
+ make_grid,
59
+ repeat,
60
+ rollout,
61
+ stack_sub_trajectories,
62
+ wrap_bc,
63
+ )
64
+ from .stepper.stochastic import (
65
+ NoiseRegularityWarning,
66
+ StochasticAllenCahn,
67
+ TamingOrderWarning,
68
+ )
69
+
70
+ __version__ = importlib.metadata.version("exponax-spde")
71
+
72
+ __all__ = [
73
+ "BaseStepper",
74
+ "NoiseRegularityWarning",
75
+ "StochasticAllenCahn",
76
+ "TamingOrderWarning",
77
+ "ForcedStepper",
78
+ "RepeatedStepper",
79
+ "derivative",
80
+ "fft",
81
+ "ifft",
82
+ "get_spectrum",
83
+ "make_grid",
84
+ "rollout",
85
+ "repeat",
86
+ "richardson_weak_extrapolation",
87
+ "stack_sub_trajectories",
88
+ "stochastic_ensemble_rollout",
89
+ "stochastic_rollout",
90
+ "stochastic_structure_factor",
91
+ "strang_split_step",
92
+ "structure_factor",
93
+ "build_ic_set",
94
+ "wrap_bc",
95
+ "metrics",
96
+ "etdrk",
97
+ "ic",
98
+ "nonlin_fun",
99
+ "stepper",
100
+ "viz",
101
+ "spectral",
102
+ "FourierInterpolator",
103
+ "map_between_resolutions",
104
+ ]
@@ -0,0 +1,271 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+ import equinox as eqx
4
+ from jaxtyping import Array, Complex, Float
5
+
6
+ from ._spectral import (
7
+ build_derivative_operator,
8
+ fft,
9
+ ifft,
10
+ spatial_shape,
11
+ wavenumber_shape,
12
+ )
13
+ from .etdrk import ETDRK0, ETDRK1, ETDRK2, ETDRK3, ETDRK4, BaseETDRK
14
+ from .nonlin_fun import BaseNonlinearFun
15
+
16
+
17
+ class BaseStepper(eqx.Module, ABC):
18
+ num_spatial_dims: int
19
+ domain_extent: float
20
+ num_points: int
21
+ num_channels: int
22
+ dt: float
23
+ dx: float
24
+
25
+ _integrator: BaseETDRK
26
+
27
+ def __init__(
28
+ self,
29
+ num_spatial_dims: int,
30
+ domain_extent: float,
31
+ num_points: int,
32
+ dt: float,
33
+ *,
34
+ num_channels: int,
35
+ order: int,
36
+ num_circle_points: int = 16,
37
+ circle_radius: float = 1.0,
38
+ ):
39
+ """
40
+ Baseclass for timesteppers based on Fourier pseudo-spectral Exponential
41
+ Time Differencing Runge Kutta methods (ETDRK); efficiently solving
42
+ semi-linear PDEs of the form
43
+
44
+ uₜ = ℒu + 𝒩(u)
45
+
46
+ with a linear differential operator ℒ and a nonlinear differential
47
+ operator 𝒩(...).
48
+
49
+ A subclass must implement the methods `_build_linear_operator` and
50
+ `_build_nonlinear_fun`. The former returns the diagonal linear operator
51
+ in Fourier space. The latter returns a subclass of `BaseNonlinearFun`.
52
+ See the `exponax_spde.ic` submodule for pre-defined nonlinear operators and
53
+ how to subclass your own.
54
+
55
+ Save attributes specific to the concrete PDE before calling the parent
56
+ constructor because it will call the abstract methods.
57
+
58
+ **Arguments:**
59
+
60
+ - `num_spatial_dims`: The number of spatial dimensions.
61
+ - `domain_extent`: The size of the domain `L`; in higher dimensions
62
+ the domain is assumed to be a scaled hypercube `Ω = (0, L)ᵈ`.
63
+ - `num_points`: The number of points `N` used to discretize the
64
+ domain. This **includes** the left boundary point and **excludes**
65
+ the right boundary point. In higher dimensions; the number of points
66
+ in each dimension is the same. Hence, the total number of degrees of
67
+ freedom is `Nᵈ`.
68
+ - `dt`: The timestep size `Δt` between two consecutive states.
69
+ - `num_channels`: The number of channels `C` in the state vector/tensor.
70
+ For most problem, like simple linear PDEs this will be one (because
71
+ the temperature field in a heat/diffusion PDE is a scalar field).
72
+ Some other problems like Burgers equation in higher dimensions or
73
+ reaction-diffusion equations with multiple species will have more
74
+ than one channel. This information is only used to check the shape
75
+ of the input state vector in the `__call__` method. (keyword-only)
76
+ - `order`: The order of the ETDRK method to use. Must be one of {0, 1,
77
+ 2, 3, 4}. The option `0` only solves the linear part of the
78
+ equation. Hence, only use this for linear PDEs. For nonlinear PDEs,
79
+ a higher order method tends to be more stable and accurate. `2` is
80
+ often a good compromise in single-precision. Use `4` together with
81
+ double precision (`jax.config.update("jax_enable_x64", True)`) for
82
+ highest accuracy. (keyword-only)
83
+ - `num_circle_points`: How many points to use in the complex contour
84
+ integral method to compute the coefficients of the exponential time
85
+ differencing Runge Kutta method. Default: 16.
86
+ - `circle_radius`: The radius of the contour used to compute the
87
+ coefficients of the exponential time differencing Runge Kutta
88
+ method. Default: 1.0.
89
+ """
90
+ self.num_spatial_dims = num_spatial_dims
91
+ self.domain_extent = domain_extent
92
+ self.num_points = num_points
93
+ self.dt = dt
94
+ self.num_channels = num_channels
95
+
96
+ # Uses the convention that N does **not** include the right boundary
97
+ # point
98
+ self.dx = domain_extent / num_points
99
+
100
+ derivative_operator = build_derivative_operator(
101
+ num_spatial_dims, domain_extent, num_points
102
+ )
103
+
104
+ linear_operator = self._build_linear_operator(derivative_operator)
105
+ single_channel_shape = (1,) + wavenumber_shape(
106
+ self.num_spatial_dims, self.num_points
107
+ ) # Same operator for each channel (i.e., we broadcast)
108
+ multi_channel_shape = (self.num_channels,) + wavenumber_shape(
109
+ self.num_spatial_dims, self.num_points
110
+ ) # Different operator for each channel
111
+ if linear_operator.shape not in (single_channel_shape, multi_channel_shape):
112
+ raise ValueError(
113
+ f"""Expected linear operator to have shape
114
+ {single_channel_shape} or {multi_channel_shape}, got
115
+ {linear_operator.shape}."""
116
+ )
117
+ nonlinear_fun = self._build_nonlinear_fun(derivative_operator)
118
+
119
+ if order == 0:
120
+ self._integrator = ETDRK0(
121
+ dt,
122
+ linear_operator,
123
+ )
124
+ elif order == 1:
125
+ self._integrator = ETDRK1(
126
+ dt,
127
+ linear_operator,
128
+ nonlinear_fun,
129
+ num_circle_points=num_circle_points,
130
+ circle_radius=circle_radius,
131
+ )
132
+ elif order == 2:
133
+ self._integrator = ETDRK2(
134
+ dt,
135
+ linear_operator,
136
+ nonlinear_fun,
137
+ num_circle_points=num_circle_points,
138
+ circle_radius=circle_radius,
139
+ )
140
+ elif order == 3:
141
+ self._integrator = ETDRK3(
142
+ dt,
143
+ linear_operator,
144
+ nonlinear_fun,
145
+ num_circle_points=num_circle_points,
146
+ circle_radius=circle_radius,
147
+ )
148
+ elif order == 4:
149
+ self._integrator = ETDRK4(
150
+ dt,
151
+ linear_operator,
152
+ nonlinear_fun,
153
+ num_circle_points=num_circle_points,
154
+ circle_radius=circle_radius,
155
+ )
156
+ else:
157
+ raise NotImplementedError(f"Order {order} not implemented.")
158
+
159
+ @abstractmethod
160
+ def _build_linear_operator(
161
+ self,
162
+ derivative_operator: Complex[Array, "D ... (N//2)+1"],
163
+ ) -> Complex[Array, "C ... (N//2)+1"]:
164
+ """
165
+ Assemble the L operator in Fourier space.
166
+
167
+ **Arguments:**
168
+
169
+ - `derivative_operator`: The derivative operator, shape `( D, ...,
170
+ N//2+1 )`. The ellipsis are (D-1) axis of size N (**not** of size
171
+ N//2+1).
172
+
173
+ **Returns:**
174
+
175
+ - `L`: The linear operator, shape `( C, ..., N//2+1 )`.
176
+ """
177
+ pass
178
+
179
+ @abstractmethod
180
+ def _build_nonlinear_fun(
181
+ self,
182
+ derivative_operator: Complex[Array, "D ... (N//2)+1"],
183
+ ) -> BaseNonlinearFun:
184
+ """
185
+ Build the function that evaluates nonlinearity in physical space,
186
+ transforms to Fourier space, and evaluates derivatives there.
187
+
188
+ **Arguments:**
189
+
190
+ - `derivative_operator`: The derivative operator, shape `( D, ...,
191
+ N//2+1 )`.
192
+
193
+ **Returns:**
194
+
195
+ - `nonlinear_fun`: A function that evaluates the nonlinearities in
196
+ time space, transforms to Fourier space, and evaluates the
197
+ derivatives there. Should be a subclass of `BaseNonlinearFun`.
198
+ """
199
+ pass
200
+
201
+ def step(self, u: Float[Array, "C ... N"]) -> Float[Array, "C ... N"]:
202
+ """
203
+ Perform one step of the time integration.
204
+
205
+ **Arguments:**
206
+
207
+ - `u`: The state vector, shape `(C, ..., N,)`.
208
+
209
+ **Returns:**
210
+
211
+ - `u_next`: The state vector after one step, shape `(C, ..., N,)`.
212
+ """
213
+ u_hat = fft(u, num_spatial_dims=self.num_spatial_dims)
214
+ u_next_hat = self.step_fourier(u_hat)
215
+ u_next = ifft(
216
+ u_next_hat,
217
+ num_spatial_dims=self.num_spatial_dims,
218
+ num_points=self.num_points,
219
+ )
220
+ return u_next
221
+
222
+ def step_fourier(
223
+ self, u_hat: Complex[Array, "C ... (N//2)+1"]
224
+ ) -> Complex[Array, "C ... (N//2)+1"]:
225
+ """
226
+ Perform one step of the time integration in Fourier space. Oftentimes,
227
+ this is more efficient than `step` since it avoids back and forth
228
+ transforms.
229
+
230
+ **Arguments:**
231
+
232
+ - `u_hat`: The (real) Fourier transform of the state vector
233
+
234
+ **Returns:**
235
+
236
+ - `u_next_hat`: The (real) Fourier transform of the state vector
237
+ after one step
238
+ """
239
+ return self._integrator.step_fourier(u_hat)
240
+
241
+ def __call__(
242
+ self,
243
+ u: Float[Array, "C ... N"],
244
+ ) -> Float[Array, "C ... N"]:
245
+ """
246
+ Perform one step of the time integration for a single state.
247
+
248
+ **Arguments:**
249
+
250
+ - `u`: The state vector, shape `(C, ..., N,)`.
251
+
252
+ **Returns:**
253
+
254
+ - `u_next`: The state vector after one step, shape `(C, ..., N,)`.
255
+
256
+ !!! tip
257
+ Use this call method together with `exponax_spde.rollout` to efficiently
258
+ produce temporal trajectories.
259
+
260
+ !!! info
261
+ For batched operation, use `jax.vmap` on this function.
262
+ """
263
+ expected_shape = (self.num_channels,) + spatial_shape(
264
+ self.num_spatial_dims, self.num_points
265
+ )
266
+ if u.shape != expected_shape:
267
+ raise ValueError(
268
+ f"""Expected shape {expected_shape}, got {u.shape}. For batched
269
+ operation use `jax.vmap` on this function."""
270
+ )
271
+ return self.step(u)
@@ -0,0 +1,108 @@
1
+ import equinox as eqx
2
+ from jaxtyping import Array, Complex, Float
3
+
4
+ from ._base_stepper import BaseStepper
5
+
6
+
7
+ class ForcedStepper(eqx.Module):
8
+ stepper: BaseStepper
9
+
10
+ def __init__(
11
+ self,
12
+ stepper: BaseStepper,
13
+ ):
14
+ """
15
+ Transform a stepper of signature `(u,) -> u_next` into a stepper of
16
+ signature `(u, f) -> u_next` that also accepts a forcing vector `f`.
17
+
18
+ Transforms a stepper for a PDE of the form u_t = Lu + N(u) into a stepper
19
+ for a PDE of the form u_t = Lu + N(u) + f, where f is a forcing term. For
20
+ this, we split by operators
21
+
22
+ v_t = f
23
+
24
+ u_t = Lv + N(v)
25
+
26
+ Since we assume to only have access to the forcing function evaluated at one
27
+ time level (but on the same grid as the state), we use a forward Euler
28
+ scheme to integrate the first equation. The second equation is integrated
29
+ using the original stepper.
30
+
31
+ Note: This operator splitting makes the total scheme only first order
32
+ accurate in time. It is a quick hack to extend the other sophisticated
33
+ transient integrators to forced problems.
34
+
35
+ **Arguments**:
36
+
37
+ - `stepper`: The stepper to be transformed.
38
+ """
39
+ self.stepper = stepper
40
+
41
+ def step(
42
+ self,
43
+ u: Float[Array, "C ... N"],
44
+ f: Float[Array, "C ... N"],
45
+ ) -> Float[Array, "C ... N"]:
46
+ """
47
+ Step the PDE forward in time by one time step given the current state
48
+ `u` and the forcing term `f`.
49
+
50
+ The forcing term `f` is assumed to be evaluated on the same grid as `u`.
51
+
52
+ **Arguments**:
53
+
54
+ - `u`: The current state.
55
+ - `f`: The forcing term.
56
+
57
+ **Returns**:
58
+
59
+ - `u_next`: The state after one time step.
60
+ """
61
+ u_with_force = u + self.stepper.dt * f
62
+ return self.stepper.step(u_with_force)
63
+
64
+ def step_fourier(
65
+ self,
66
+ u_hat: Complex[Array, "C ... (N//2)+1"],
67
+ f_hat: Complex[Array, "C ... (N//2)+1"],
68
+ ) -> Complex[Array, "C ... (N//2)+1"]:
69
+ """
70
+ Step the PDE forward in time by one time step given the current state
71
+ `u_hat` in Fourier space and the forcing term `f_hat` in Fourier space.
72
+
73
+ The forcing term `f_hat` is assumed to be evaluated on the same grid as
74
+ `u_hat`.
75
+
76
+ **Arguments**:
77
+
78
+ - `u_hat`: The current state in Fourier space.
79
+ - `f_hat`: The forcing term in Fourier space.
80
+
81
+ **Returns**:
82
+
83
+ - `u_next_hat`: The state after one time step in Fourier space.
84
+ """
85
+ u_hat_with_force = u_hat + self.stepper.dt * f_hat
86
+ return self.stepper.step_fourier(u_hat_with_force)
87
+
88
+ def __call__(
89
+ self,
90
+ u: Float[Array, "C ... N"],
91
+ f: Float[Array, "C ... N"],
92
+ ) -> Float[Array, "C ... N"]:
93
+ """
94
+ Step the PDE forward in time by one time step given the current state
95
+ `u` and the forcing term `f`.
96
+
97
+ The forcing term `f` is assumed to be evaluated on the same grid as `u`.
98
+
99
+ **Arguments:**
100
+
101
+ - `u`: The current state.
102
+ - `f`: The forcing term.
103
+
104
+ **Returns:**
105
+
106
+ - `u_next`: The state after one time step.
107
+ """
108
+ return self.step(u, f)