namespace Chronos.Core.Mathematics;
///
/// Interpolating cubic spline with natural end conditions (zero second derivative), second derivatives solved
/// with the Thomas tridiagonal algorithm. C² inside the knot range; extrapolates linearly with the end slopes.
///
public sealed class NaturalCubicSpline
{
private readonly double[] _x;
private readonly double[] _y;
private readonly double[] _m;
/// Strictly increasing, finite knot positions (at least one).
/// Finite knot values.
public NaturalCubicSpline(ReadOnlySpan x, ReadOnlySpan y)
{
SplineInput.Validate(x, y, minimum: 1);
_x = x.ToArray();
_y = y.ToArray();
var n = _x.Length;
_m = new double[n];
if (n < 3) return;
// Interior equations: h[i-1]·M[i-1] + 2(h[i-1]+h[i])·M[i] + h[i]·M[i+1] = 6(δ[i] − δ[i-1]).
var c = new double[n];
var d = new double[n];
for (var i = 1; i < n - 1; i++)
{
var h0 = _x[i] - _x[i - 1];
var h1 = _x[i + 1] - _x[i];
var rhs = 6 * ((_y[i + 1] - _y[i]) / h1 - (_y[i] - _y[i - 1]) / h0);
var diag = 2 * (h0 + h1) - h0 * c[i - 1];
c[i] = h1 / diag;
d[i] = (rhs - h0 * d[i - 1]) / diag;
}
for (var i = n - 2; i >= 1; i--) _m[i] = d[i] - c[i] * _m[i + 1];
}
public int Count => _x.Length;
public double Evaluate(double x)
{
var n = _x.Length;
if (n == 1) return _y[0];
if (x < _x[0]) return _y[0] + Slope(0, atEnd: false) * (x - _x[0]);
if (x > _x[^1]) return _y[^1] + Slope(n - 2, atEnd: true) * (x - _x[^1]);
var k = Interval(x);
var h = _x[k + 1] - _x[k];
var a = (_x[k + 1] - x) / h;
var b = 1 - a;
return a * _y[k] + b * _y[k + 1] + ((a * a * a - a) * _m[k] + (b * b * b - b) * _m[k + 1]) * h * h / 6;
}
public double Derivative(double x)
{
var n = _x.Length;
if (n == 1) return 0;
if (x < _x[0]) return Slope(0, atEnd: false);
if (x > _x[^1]) return Slope(n - 2, atEnd: true);
var k = Interval(x);
var h = _x[k + 1] - _x[k];
var a = (_x[k + 1] - x) / h;
var b = 1 - a;
return (_y[k + 1] - _y[k]) / h - (3 * a * a - 1) / 6 * h * _m[k] + (3 * b * b - 1) / 6 * h * _m[k + 1];
}
public double SecondDerivative(double x)
{
if (_x.Length == 1 || x <= _x[0] || x >= _x[^1]) return 0;
var k = Interval(x);
var a = (_x[k + 1] - x) / (_x[k + 1] - _x[k]);
return a * _m[k] + (1 - a) * _m[k + 1];
}
private double Slope(int k, bool atEnd)
{
var h = _x[k + 1] - _x[k];
var secant = (_y[k + 1] - _y[k]) / h;
return atEnd ? secant + h * (_m[k] + 2 * _m[k + 1]) / 6 : secant - h * (2 * _m[k] + _m[k + 1]) / 6;
}
private int Interval(double x)
{
var i = Array.BinarySearch(_x, x);
if (i < 0) i = ~i - 1;
return Math.Clamp(i, 0, _x.Length - 2);
}
}