|
| 1 | +"""Coefficient fitting routines for 1-D interpolation methods. |
| 2 | +
|
| 3 | +Every public function in this module takes sorted ``x`` and ``y`` arrays and |
| 4 | +returns a data structure (NumPy array / tuple) that the corresponding |
| 5 | +evaluation factory can close over. |
| 6 | +""" |
| 7 | + |
| 8 | +import warnings |
| 9 | + |
| 10 | +import numpy as np |
| 11 | +from scipy import linalg |
| 12 | + |
| 13 | + |
| 14 | +def fit_polynomial(x, y): |
| 15 | + """Fit a single polynomial of degree ``len(x) - 1`` through all points. |
| 16 | +
|
| 17 | + Parameters |
| 18 | + ---------- |
| 19 | + x : ndarray, shape (n,) |
| 20 | + y : ndarray, shape (n,) |
| 21 | +
|
| 22 | + Returns |
| 23 | + ------- |
| 24 | + coeffs : ndarray, shape (n,) |
| 25 | + Coefficients in *ascending* power order: ``c[0] + c[1]*x + …``. |
| 26 | + """ |
| 27 | + degree = len(x) - 1 |
| 28 | + if np.amax(np.abs(x)) ** degree > 1e308: |
| 29 | + warnings.warn( |
| 30 | + "Polynomial interpolation of too many points can't be done. " |
| 31 | + "Once the degree is too high, numbers get too large. " |
| 32 | + "Falling back to spline coefficients.", |
| 33 | + stacklevel=3, |
| 34 | + ) |
| 35 | + return None # caller should fall back to spline |
| 36 | + V = np.vander(x, increasing=True) |
| 37 | + return np.linalg.solve(V, y) |
| 38 | + |
| 39 | + |
| 40 | +def fit_spline(x, y): |
| 41 | + r"""Fit a natural cubic spline in local coordinates. |
| 42 | +
|
| 43 | + Returns coefficients ``[a, b, c, d]`` for each interval stored as a |
| 44 | + ``(4, n-1)`` array, where the polynomial for segment *i* is |
| 45 | +
|
| 46 | + .. math:: |
| 47 | + p_i(t) = a_i + b_i t + c_i t^2 + d_i t^3, \quad t = x - x_i |
| 48 | +
|
| 49 | + Parameters |
| 50 | + ---------- |
| 51 | + x : ndarray, shape (n,) |
| 52 | + y : ndarray, shape (n,) |
| 53 | +
|
| 54 | + Returns |
| 55 | + ------- |
| 56 | + coeffs : ndarray, shape (4, n-1) |
| 57 | + Rows are ``[a, b, c, d]``. |
| 58 | + """ |
| 59 | + n = len(x) |
| 60 | + h = np.diff(x) |
| 61 | + |
| 62 | + # Build tridiagonal system for the c coefficients (natural BC: c[0]=c[-1]=0) |
| 63 | + banded = np.zeros((3, n)) |
| 64 | + banded[1, 0] = banded[1, -1] = 1.0 |
| 65 | + banded[2, :-2] = h[:-1] |
| 66 | + banded[1, 1:-1] = 2.0 * (h[:-1] + h[1:]) |
| 67 | + banded[0, 2:] = h[1:] |
| 68 | + |
| 69 | + rhs = np.zeros(n) |
| 70 | + rhs[1:-1] = 3.0 * ((y[2:] - y[1:-1]) / h[1:] - (y[1:-1] - y[:-2]) / h[:-1]) |
| 71 | + |
| 72 | + c = linalg.solve_banded((1, 1), banded, rhs, overwrite_ab=True, overwrite_b=True) |
| 73 | + |
| 74 | + b = (y[1:] - y[:-1]) / h - h * (2.0 * c[:-1] + c[1:]) / 3.0 |
| 75 | + d = (c[1:] - c[:-1]) / (3.0 * h) |
| 76 | + |
| 77 | + return np.vstack([y[:-1], b, c[:-1], d]) |
| 78 | + |
| 79 | + |
| 80 | +def fit_akima(x, y): |
| 81 | + r"""Fit an Akima spline in local coordinates. |
| 82 | +
|
| 83 | + The slopes at each knot are computed using the original Akima weighting |
| 84 | + of adjacent finite differences, extended at the boundaries by reflected |
| 85 | + values. This is fully vectorised — no Python loop. |
| 86 | +
|
| 87 | + Returns coefficients ``[a, b, c, d]`` for each interval in a ``(4, n-1)`` |
| 88 | + array identical in layout to :func:`fit_spline`. |
| 89 | +
|
| 90 | + Parameters |
| 91 | + ---------- |
| 92 | + x : ndarray, shape (n,) |
| 93 | + y : ndarray, shape (n,) |
| 94 | +
|
| 95 | + Returns |
| 96 | + ------- |
| 97 | + coeffs : ndarray, shape (4, n-1) |
| 98 | + """ |
| 99 | + n = len(x) |
| 100 | + h = np.diff(x) |
| 101 | + m = np.diff(y) / h # slopes of segments, shape (n-1,) |
| 102 | + |
| 103 | + # Extend m with 2 ghost values on each side (Akima boundary reflection) |
| 104 | + # m_ext indices: 0..n+2 (n-1 interior + 2 left + 2 right) |
| 105 | + m_ext = np.empty(n + 3) |
| 106 | + m_ext[2:-2] = m |
| 107 | + m_ext[1] = 2.0 * m[0] - m[1] |
| 108 | + m_ext[0] = 2.0 * m_ext[1] - m[0] |
| 109 | + m_ext[-2] = 2.0 * m[-1] - m[-2] |
| 110 | + m_ext[-1] = 2.0 * m_ext[-2] - m[-1] |
| 111 | + |
| 112 | + # Weights: |m_{i+1} - m_i| |
| 113 | + dm = np.abs(np.diff(m_ext)) # shape (n+2,) |
| 114 | + |
| 115 | + # Akima slope at each knot: weighted average of adjacent segment slopes. |
| 116 | + # w1 = |m_{i+1} - m_i|, w2 = |m_{i-1} - m_{i-2}| |
| 117 | + # t_i = (w1 * m_{i-1} + w2 * m_i) / (w1 + w2) |
| 118 | + # When w1 + w2 == 0, fall back to simple average. |
| 119 | + w1 = dm[2:] # |m_{i+1} - m_i| for i in 0..n-1 |
| 120 | + w2 = dm[:-2] # |m_{i-1} - m_{i-2}| for i in 0..n-1 |
| 121 | + m_left = m_ext[1:-2] # m_{i-1} |
| 122 | + m_right = m_ext[2:-1] # m_i |
| 123 | + |
| 124 | + wsum = w1 + w2 |
| 125 | + t = 0.5 * (m_left + m_right) |
| 126 | + np.divide( |
| 127 | + w1 * m_left + w2 * m_right, |
| 128 | + wsum, |
| 129 | + out=t, |
| 130 | + where=wsum > 0, |
| 131 | + ) |
| 132 | + |
| 133 | + # Hermite-to-local coefficients: |
| 134 | + # a = y_i |
| 135 | + # b = t_i |
| 136 | + # c = (3*m_i - 2*t_i - t_{i+1}) / h_i |
| 137 | + # d = (t_i + t_{i+1} - 2*m_i) / h_i^2 |
| 138 | + a = y[:-1] |
| 139 | + b = t[:-1] |
| 140 | + c_coeff = (3.0 * m - 2.0 * t[:-1] - t[1:]) / h |
| 141 | + d_coeff = (t[:-1] + t[1:] - 2.0 * m) / (h * h) |
| 142 | + |
| 143 | + return np.vstack([a, b, c_coeff, d_coeff]) |
| 144 | + |
| 145 | + |
| 146 | +def fit_pchip(x, y): |
| 147 | + r"""Fit a PCHIP (Piecewise Cubic Hermite Interpolating Polynomial). |
| 148 | +
|
| 149 | + Uses the Fritsch–Carlson method to compute monotone-preserving slopes |
| 150 | + and converts them to local-coordinate cubic coefficients identical in |
| 151 | + layout to :func:`fit_spline`. |
| 152 | +
|
| 153 | + Parameters |
| 154 | + ---------- |
| 155 | + x : ndarray, shape (n,) |
| 156 | + y : ndarray, shape (n,) |
| 157 | +
|
| 158 | + Returns |
| 159 | + ------- |
| 160 | + coeffs : ndarray, shape (4, n-1) |
| 161 | + """ |
| 162 | + n = len(x) |
| 163 | + h = np.diff(x) |
| 164 | + m = np.diff(y) / h |
| 165 | + |
| 166 | + # Compute slopes at each knot |
| 167 | + t = np.zeros(n) |
| 168 | + |
| 169 | + # Interior knots |
| 170 | + if n > 2: |
| 171 | + # Harmonic mean weighted by segment lengths |
| 172 | + w1 = 2.0 * h[1:] + h[:-1] |
| 173 | + w2 = h[1:] + 2.0 * h[:-1] |
| 174 | + |
| 175 | + # Where signs differ or either is zero, slope is zero (monotonicity) |
| 176 | + sign_change = (m[:-1] * m[1:]) <= 0 |
| 177 | + pos_mask = ~sign_change |
| 178 | + |
| 179 | + # Safe harmonic mean |
| 180 | + t[1:-1] = np.where( |
| 181 | + pos_mask, |
| 182 | + (w1 + w2) / (w1 / m[:-1] + w2 / m[1:]), |
| 183 | + 0.0, |
| 184 | + ) |
| 185 | + |
| 186 | + # Boundary slopes: one-sided, clamped for monotonicity |
| 187 | + t[0] = _pchip_edge_slope( |
| 188 | + h[0], h[1] if n > 2 else h[0], m[0], m[1] if n > 2 else m[0] |
| 189 | + ) |
| 190 | + t[-1] = _pchip_edge_slope( |
| 191 | + h[-1], h[-2] if n > 2 else h[-1], m[-1], m[-2] if n > 2 else m[-1] |
| 192 | + ) |
| 193 | + |
| 194 | + # Convert to local Hermite coefficients (same as akima) |
| 195 | + a = y[:-1] |
| 196 | + b = t[:-1] |
| 197 | + c_coeff = (3.0 * m - 2.0 * t[:-1] - t[1:]) / h |
| 198 | + d_coeff = (t[:-1] + t[1:] - 2.0 * m) / (h * h) |
| 199 | + |
| 200 | + return np.vstack([a, b, c_coeff, d_coeff]) |
| 201 | + |
| 202 | + |
| 203 | +def _pchip_edge_slope(h0, h1, m0, m1): |
| 204 | + """Compute boundary slope for PCHIP (non-centred 3-point formula, |
| 205 | + clamped to preserve monotonicity).""" |
| 206 | + t = ((2.0 * h0 + h1) * m0 - h0 * m1) / (h0 + h1) |
| 207 | + if np.sign(t) != np.sign(m0): |
| 208 | + t = 0.0 |
| 209 | + elif np.sign(m0) != np.sign(m1) and np.abs(t) > 3.0 * np.abs(m0): |
| 210 | + t = 3.0 * m0 |
| 211 | + return t |
| 212 | + |
| 213 | + |
| 214 | +def precompute_linear_deriv_integral(x, y): |
| 215 | + """Pre-compute data for analytical linear derivative and integral. |
| 216 | +
|
| 217 | + Parameters |
| 218 | + ---------- |
| 219 | + x : ndarray, shape (n,) |
| 220 | + y : ndarray, shape (n,) |
| 221 | +
|
| 222 | + Returns |
| 223 | + ------- |
| 224 | + slopes : ndarray, shape (n-1,) |
| 225 | + Piecewise-constant derivative values. |
| 226 | + cum_integrals : ndarray, shape (n,) |
| 227 | + Cumulative trapezoid integral from x[0] to x[i]. |
| 228 | + """ |
| 229 | + h = np.diff(x) |
| 230 | + slopes = np.diff(y) / h |
| 231 | + # Cumulative trapezoid: area of each trapezoid is 0.5*(y[i]+y[i+1])*h[i] |
| 232 | + trap_areas = 0.5 * (y[:-1] + y[1:]) * h |
| 233 | + cum_integrals = np.empty(len(x)) |
| 234 | + cum_integrals[0] = 0.0 |
| 235 | + np.cumsum(trap_areas, out=cum_integrals[1:]) |
| 236 | + return slopes, cum_integrals |
| 237 | + |
| 238 | + |
| 239 | +def precompute_cubic_cumulative_integrals(x, coeffs): |
| 240 | + """Pre-compute cumulative integrals over full intervals for cubic methods. |
| 241 | +
|
| 242 | + For piece *i* with local polynomial ``a + b*t + c*t² + d*t³``, |
| 243 | + the integral over the full interval ``[0, h_i]`` is |
| 244 | + ``a*h + b*h²/2 + c*h³/3 + d*h⁴/4``. |
| 245 | +
|
| 246 | + Parameters |
| 247 | + ---------- |
| 248 | + x : ndarray, shape (n,) |
| 249 | + coeffs : ndarray, shape (4, n-1) |
| 250 | +
|
| 251 | + Returns |
| 252 | + ------- |
| 253 | + cum : ndarray, shape (n,) |
| 254 | + ``cum[0] = 0``; ``cum[i] = ∫_{x[0]}^{x[i]} p(t) dt``. |
| 255 | + """ |
| 256 | + h = np.diff(x) |
| 257 | + a, b, c, d = coeffs |
| 258 | + h2 = h * h |
| 259 | + h3 = h2 * h |
| 260 | + h4 = h3 * h |
| 261 | + piece_integrals = a * h + b * h2 / 2.0 + c * h3 / 3.0 + d * h4 / 4.0 |
| 262 | + cum = np.empty(len(x)) |
| 263 | + cum[0] = 0.0 |
| 264 | + np.cumsum(piece_integrals, out=cum[1:]) |
| 265 | + return cum |
0 commit comments