jaxtfwaves 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.
@@ -0,0 +1,265 @@
1
+ #! /usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Interpolation module for tfwaves package, providing access to JAX-compatible classes.
5
+ Authors:
6
+ Quentin Baghi <quentin.baghi@protonmail.com>
7
+ Saptarshi Ghosh <saptarshi.ghosh@apc.in2p3.fr>
8
+ Gael Servignat <servignat@apc.in2p3.fr>
9
+ """
10
+
11
+ import flax
12
+ import jax
13
+ import jax.numpy as jnp
14
+
15
+ from .utils import extract_y0_y1_m0_m1_t, hermite_interp_build, hermite_interp_eval
16
+
17
+
18
+ # ============================
19
+ # JAX-compatible cubic spline
20
+ # ============================
21
+ @flax.struct.dataclass
22
+ class JAXCubicSpline:
23
+ """Fast JAX/Flax-compatible cubic spline with 1st and 2nd derivatives.
24
+ Default boundary condition: not-a-knot.
25
+ """
26
+
27
+ x: jax.Array
28
+ y: jax.Array
29
+ b: jax.Array
30
+ c: jax.Array
31
+ d: jax.Array
32
+ extrapolate: bool = True
33
+
34
+ # ------------------------------------------------------------
35
+ # Fast Thomas tridiagonal solver (jitted)
36
+ # ------------------------------------------------------------
37
+ @staticmethod
38
+ # @jax.jit
39
+ def _solve_tridiagonal(a, b, c, d):
40
+ """Solve tridiagonal system Ax = d for x (Thomas algorithm)."""
41
+ n = b.size
42
+
43
+ def forward_step(carry, i):
44
+ a_, b_, c_, d_ = carry
45
+ w = a_[i - 1] / b_[i - 1]
46
+ b_ = b_.at[i].set(b_[i] - w * c_[i - 1])
47
+ d_ = d_.at[i].set(d_[i] - w * d_[i - 1])
48
+ return (a_, b_, c_, d_), None
49
+
50
+ (a, b, c, d), _ = jax.lax.scan(forward_step, (a, b, c, d), jnp.arange(1, n))
51
+
52
+ def backward_step(carry, i):
53
+ c_, b_, d_, x = carry
54
+ j = n - 2 - i
55
+ xj = (d_[j] - c_[j] * x[j + 1]) / b_[j]
56
+ x = x.at[j].set(xj)
57
+ return (c_, b_, d_, x), None
58
+
59
+ x_init = jnp.zeros(n).at[-1].set(d[-1] / b[-1])
60
+ (_, _, _, x), _ = jax.lax.scan(backward_step, (c, b, d, x_init), jnp.arange(n - 1))
61
+ return x
62
+
63
+ # ------------------------------------------------------------
64
+ # Factory method (builds coefficients)
65
+ # ------------------------------------------------------------
66
+ @classmethod
67
+ def build(cls, x, y, extrapolate: bool = True) -> "JAXCubicSpline":
68
+ """Construct cubic spline coefficients with not-a-knot BC."""
69
+ x = jnp.asarray(x)
70
+ y = jnp.asarray(y)
71
+ n = x.size
72
+ h = x[1:] - x[:-1]
73
+
74
+ # Tridiagonal system setup for c coefficients
75
+ a = jnp.zeros(n)
76
+ b = jnp.zeros(n)
77
+ c = jnp.zeros(n)
78
+ rhs = jnp.zeros(n)
79
+
80
+ # --- Not-a-knot boundary conditions ---
81
+ # Left BC: c0 and c1 related by 1/h0 * c0 + (h0 + h1)/h1 * c1 - h0^2/h1^2 * c2 = ...
82
+ # For simplicity, use the equivalent polynomial continuity condition:
83
+ b = b.at[0].set(h[1])
84
+ c = c.at[0].set(-(h[0] + h[1]))
85
+ rhs = rhs.at[0].set(((y[2] - y[1]) / h[1] - (y[1] - y[0]) / h[0]) * (h[1] / (h[0] + h[1])))
86
+
87
+ # Interior points
88
+ a = a.at[1:-1].set(h[:-1])
89
+ b = b.at[1:-1].set(2 * (h[:-1] + h[1:]))
90
+ c = c.at[1:-1].set(h[1:])
91
+ rhs = rhs.at[1:-1].set(3 * ((y[2:] - y[1:-1]) / h[1:] - (y[1:-1] - y[:-2]) / h[:-1]))
92
+
93
+ # Right not-a-knot BC (mirror of left)
94
+ a = a.at[-1].set(-(h[-2] + h[-1]))
95
+ b = b.at[-1].set(h[-2])
96
+ rhs = rhs.at[-1].set(
97
+ ((y[-1] - y[-2]) / h[-1] - (y[-2] - y[-3]) / h[-2]) * (h[-2] / (h[-2] + h[-1]))
98
+ )
99
+
100
+ # Solve for c (second-derivative-like coefficients)
101
+ ccoef = cls._solve_tridiagonal(a[1:], b, c[:-1], rhs)
102
+
103
+ # Compute b and d coefficients
104
+ bcoef = (y[1:] - y[:-1]) / h - h * (2 * ccoef[:-1] + ccoef[1:]) / 3
105
+ dcoef = (ccoef[1:] - ccoef[:-1]) / (3 * h)
106
+
107
+ return cls(x=x, y=y, b=bcoef, c=ccoef, d=dcoef, extrapolate=extrapolate)
108
+
109
+ # ------------------------------------------------------------
110
+ # Evaluate spline
111
+ # ------------------------------------------------------------
112
+ def __call__(self, xq: jax.typing.ArrayLike) -> jax.Array:
113
+ xq = jnp.asarray(xq)
114
+ idx = jnp.clip(jnp.searchsorted(self.x, xq) - 1, 0, self.x.size - 2)
115
+ dx = xq - self.x[idx]
116
+ yq = self.y[idx] + self.b[idx] * dx + self.c[idx] * dx**2 + self.d[idx] * dx**3
117
+ # JAX tracing-safe branch: avoid Python bool conversion on traced values.
118
+ mask = (xq >= self.x[0]) & (xq <= self.x[-1])
119
+ return jnp.where(jnp.asarray(self.extrapolate), yq, yq * mask)
120
+
121
+ # ------------------------------------------------------------
122
+ # Derivative accessors
123
+ # ------------------------------------------------------------
124
+ def derivative(self, order: int = 1):
125
+ """Computes the derivatives of order 1 or 2 and returns them as callables.
126
+
127
+ Args:
128
+ order (int, optional): Order of derivative. Defaults to 1.
129
+
130
+ Raises:
131
+ ValueError: If the derivative is asked to be of order >2.
132
+
133
+ Returns:
134
+ callable: Function that computes the first or second derivative.
135
+ """
136
+ if order == 1:
137
+
138
+ def d1(xq):
139
+ idx = jnp.clip(jnp.searchsorted(self.x, xq) - 1, 0, self.x.size - 2)
140
+ dx = xq - self.x[idx]
141
+ return self.b[idx] + 2 * self.c[idx] * dx + 3 * self.d[idx] * dx**2
142
+
143
+ return d1
144
+ if order == 2:
145
+
146
+ def d2(xq):
147
+ idx = jnp.clip(jnp.searchsorted(self.x, xq) - 1, 0, self.x.size - 2)
148
+ dx = xq - self.x[idx]
149
+ return 2 * self.c[idx] + 6 * self.d[idx] * dx
150
+
151
+ return d2
152
+ raise ValueError("Only first and second derivatives supported.")
153
+
154
+
155
+ @flax.struct.dataclass
156
+ class JAXHermiteSpline:
157
+ """
158
+ Ultra-fast JAX/Flax-compatible cubic Hermite interpolator on a uniform grid.
159
+ - Supports first and second derivatives analytically.
160
+ - Optional periodic boundary conditions.
161
+ - Slopes computed via high-order finite differences.
162
+ """
163
+
164
+ x: jax.Array
165
+ y: jax.Array
166
+ m: jax.Array
167
+ h: float
168
+ periodic: bool = False
169
+
170
+ # ------------------------------------------------------------
171
+ # Factory method (precompute slopes)
172
+ # ------------------------------------------------------------
173
+ @classmethod
174
+ def build(cls, x, y, periodic: bool = False) -> "JAXHermiteSpline":
175
+ """Classmethod constructor
176
+
177
+ Args:
178
+ x (array): abscissas
179
+ y (array): ordinates
180
+ periodic (bool, optional): Possibility to impose periodic boundary condition.
181
+ Defaults to False.
182
+
183
+ Returns:
184
+ JAXHermiteSpline: Class that interpolates with regular grid Hermite Cubic Spline.
185
+ """
186
+ x = jnp.asarray(x)
187
+ y = jnp.asarray(y)
188
+ _, _, m, h = hermite_interp_build(x, y, periodic)
189
+
190
+ return cls(x=x, y=y, m=m, h=h, periodic=periodic)
191
+
192
+ # ------------------------------------------------------------
193
+ # Core Hermite interpolation (vectorized, JIT-friendly)
194
+ # ------------------------------------------------------------
195
+ @staticmethod
196
+ @jax.jit
197
+ def _hermite_eval(x, y, m, h, x_p):
198
+ mask = (x_p >= x[0]) & (x_p <= x[-1])
199
+
200
+ return jnp.where(mask, hermite_interp_eval(x, y, m, h, x_p), 0.0)
201
+
202
+ # ------------------------------------------------------------
203
+ # Evaluation
204
+ # ------------------------------------------------------------
205
+ def __call__(self, xq: jax.typing.ArrayLike) -> jax.Array:
206
+ return self._hermite_eval(self.x, self.y, self.m, self.h, xq)
207
+
208
+ # ------------------------------------------------------------
209
+ # Derivative accessors (analytic derivatives)
210
+ # ------------------------------------------------------------
211
+ # TO TRY!!!! THIS VS JAX.GRAD OF __call__ METHOD
212
+ def derivative(self, order: int = 1):
213
+ """Computes the derivatives of order 1 or 2 and returns them as callables.
214
+
215
+ Args:
216
+ order (int, optional): Order of derivative. Defaults to 1.
217
+
218
+ Raises:
219
+ ValueError: If the derivative is asked to be of order >2.
220
+
221
+ Returns:
222
+ callable: Function that computes the first or second derivative.
223
+ """
224
+ if order == 1:
225
+
226
+ @jax.jit
227
+ def d1_eval(x, y, m, h, x_p):
228
+ y0, y1, m0, m1, t = extract_y0_y1_m0_m1_t(x, y, m, h, x_p)
229
+
230
+ # derivative of basis w.r.t x (divide by h because t = (x - x_i)/h)
231
+ h00p = (6 * t**2 - 6 * t) / h
232
+ h10p = (3 * t**2 - 4 * t + 1) / h
233
+ h01p = (-6 * t**2 + 6 * t) / h
234
+ h11p = (3 * t**2 - 2 * t) / h
235
+
236
+ mask = (x_p >= x[0]) & (x_p <= x[-1])
237
+
238
+ return jnp.where(mask, h00p * y0 + h10p * h * m0 + h01p * y1 + h11p * h * m1, 0.0)
239
+
240
+ return lambda xq: d1_eval(self.x, self.y, self.m, self.h, xq)
241
+
242
+ if order == 2:
243
+
244
+ @jax.jit
245
+ def d2_eval(x, y, m, h, x_p):
246
+ y0, y1, m0, m1, t = extract_y0_y1_m0_m1_t(x, y, m, h, x_p)
247
+
248
+ # second derivative of basis / h^2
249
+ h00pp = (12 * t - 6) / (h**2)
250
+ h10pp = (6 * t - 4) / (h**2)
251
+ h01pp = (-12 * t + 6) / (h**2)
252
+ h11pp = (6 * t - 2) / (h**2)
253
+
254
+ mask = (x_p >= x[0]) & (x_p <= x[-1])
255
+
256
+ return (h00pp * y0 + h10pp * h * m0 + h01pp * y1 + h11pp * h * m1) * mask
257
+
258
+ return lambda xq: d2_eval(self.x, self.y, self.m, self.h, xq)
259
+ raise ValueError("Only first and second derivatives supported.")
260
+
261
+
262
+ ### jit constructors
263
+
264
+ spline_cubic_jit = jax.jit(JAXCubicSpline.build)
265
+ spline_hermite_jit = jax.jit(JAXHermiteSpline.build)