refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-23 12:45:18 +02:00
1 parent c99842cc86
commit f2b58522b9
1801 files changed
+11804 -10676

No files matched your search

+92
View File
@@ -0,0 +1,92 @@
namespace Chronos.Core.Mathematics;
/// <summary>Knot spacing of a Catmull–Rom spline: |Pᵢ₊₁ − Pᵢ|^α with α = 0, ½ or 1.</summary>
public enum CatmullRomParameterization
{
/// <summary>α = 0: the classic spline; can cusp or self-intersect on uneven spacing.</summary>
Uniform,
/// <summary>α = ½: no cusps or self-intersections within a segment (Yuksel, Schaefer &amp; Keyser 2011).</summary>
Centripetal,
/// <summary>α = 1: follows the chord lengths; smoothest on evenly sampled paths.</summary>
Chordal,
}
/// <summary>
/// Catmull–Rom interpolating splines evaluated with the Barry–Goldman pyramid, so non-uniform (centripetal,
/// chordal) knots are exact. The parameter t ∈ [0, n − 1] selects segment ⌊t⌋; end segments use reflected
/// phantom points (P₋₁ = 2P₀ − P₁).
/// </summary>
public static class CatmullRom
{
/// <summary>Scalar spline through <paramref name="values"/> (values treated as 1-D points for the knot spacing).</summary>
public static double Evaluate(ReadOnlySpan<double> values, double t, CatmullRomParameterization kind = CatmullRomParameterization.Uniform)
{
if (values.IsEmpty) throw new ArgumentException("No control values.", nameof(values));
if (values.Length == 1) return values[0];
var (i, u) = Segment(values.Length, t);
var p1 = values[i];
var p2 = values[i + 1];
var p0 = i > 0 ? values[i - 1] : 2 * p1 - p2;
var p3 = i + 2 < values.Length ? values[i + 2] : 2 * p2 - p1;
return Pyramid(new Point2(p0, 0), new Point2(p1, 0), new Point2(p2, 0), new Point2(p3, 0), u, Alpha(kind)).X;
}
/// <summary>Planar spline through <paramref name="points"/>.</summary>
public static Point2 Evaluate(ReadOnlySpan<Point2> points, double t, CatmullRomParameterization kind = CatmullRomParameterization.Centripetal)
{
if (points.IsEmpty) throw new ArgumentException("No control points.", nameof(points));
if (points.Length == 1) return points[0];
var (i, u) = Segment(points.Length, t);
var p1 = points[i];
var p2 = points[i + 1];
var p0 = i > 0 ? points[i - 1] : 2 * p1 - p2;
var p3 = i + 2 < points.Length ? points[i + 2] : 2 * p2 - p1;
return Pyramid(p0, p1, p2, p3, u, Alpha(kind));
}
private static double Alpha(CatmullRomParameterization kind) => kind switch
{
CatmullRomParameterization.Uniform => 0,
CatmullRomParameterization.Centripetal => 0.5,
CatmullRomParameterization.Chordal => 1,
_ => throw new ArgumentOutOfRangeException(nameof(kind)),
};
private static (int Index, double Local) Segment(int count, double t)
{
if (double.IsNaN(t)) throw new ArgumentOutOfRangeException(nameof(t));
t = Math.Clamp(t, 0, count - 1);
var i = Math.Min((int)t, count - 2);
return (i, t - i);
}
/// <summary>Barry–Goldman recursive evaluation of the segment P1→P2 at local parameter u ∈ [0, 1].</summary>
private static Point2 Pyramid(Point2 p0, Point2 p1, Point2 p2, Point2 p3, double u, double alpha)
{
if (u <= 0) return p1;
if (u >= 1) return p2;
var d1 = Knot(p0, p1, alpha);
var d2 = Knot(p1, p2, alpha);
var d3 = Knot(p2, p3, alpha);
double t0 = 0, t1 = d1, t2 = t1 + d2, t3 = t2 + d3;
var t = t1 + u * d2;
var a1 = Mix(p0, p1, t0, t1, t);
var a2 = Mix(p1, p2, t1, t2, t);
var a3 = Mix(p2, p3, t2, t3, t);
var b1 = Mix(a1, a2, t0, t2, t);
var b2 = Mix(a2, a3, t1, t3, t);
return Mix(b1, b2, t1, t2, t);
}
private static Point2 Mix(Point2 a, Point2 b, double ta, double tb, double t) => ((tb - t) * a + (t - ta) * b) * (1 / (tb - ta));
/// <summary>Knot interval; coincident points fall back to a unit interval so the pyramid stays finite.</summary>
private static double Knot(Point2 a, Point2 b, double alpha)
{
if (alpha == 0) return 1;
var d = Math.Pow(Point2.Distance(a, b), alpha);
return d > 1e-12 ? d : 1;
}
}
+39
View File
@@ -0,0 +1,39 @@
namespace Chronos.Core.Mathematics;
/// <summary>CIE 1931 chromaticity coordinates (lower-case x, y in the literature).</summary>
public readonly record struct Chromaticity(double X, double Y)
{
/// <summary>CIE standard illuminant D65 (2° observer).</summary>
public static Chromaticity D65 { get; } = new(0.3127, 0.3290);
/// <summary>CIE standard illuminant D50 (2° observer), the ICC/DNG profile connection white.</summary>
public static Chromaticity D50 { get; } = new(0.3457, 0.3585);
/// <summary>Tristimulus values with luminance <paramref name="luminance"/>: X = x·Y/y, Z = (1 − x − y)·Y/y.</summary>
public Vector3D ToXyz(double luminance = 1)
{
if (!(Y > 0)) throw new InvalidOperationException("Chromaticity y must be positive.");
return new Vector3D(X * luminance / Y, luminance, (1 - X - Y) * luminance / Y);
}
/// <summary>Chromaticity of tristimulus values; NaN coordinates when X + Y + Z is not positive.</summary>
public static Chromaticity FromXyz(Vector3D xyz)
{
var sum = xyz.X + xyz.Y + xyz.Z;
return sum > 0 ? new Chromaticity(xyz.X / sum, xyz.Y / sum) : new Chromaticity(double.NaN, double.NaN);
}
/// <summary>CIE 1960 UCS coordinates u = 4x/(−2x + 12y + 3), v = 6y/(−2x + 12y + 3).</summary>
public (double U, double V) ToUv1960()
{
var d = -2 * X + 12 * Y + 3;
return (4 * X / d, 6 * Y / d);
}
/// <summary>Chromaticity from CIE 1960 UCS coordinates.</summary>
public static Chromaticity FromUv1960(double u, double v)
{
var d = 2 * u - 8 * v + 4;
return new Chromaticity(3 * u / d, 2 * v / d);
}
}
+95
View File
@@ -0,0 +1,95 @@
namespace Chronos.Core.Mathematics;
/// <summary>Planar cubic Bézier curve in Bernstein form; t ∈ [0, 1].</summary>
public readonly record struct CubicBezier(Point2 P0, Point2 P1, Point2 P2, Point2 P3)
{
public Point2 Evaluate(double t)
{
var s = 1 - t;
return s * s * s * P0 + 3 * s * s * t * P1 + 3 * s * t * t * P2 + t * t * t * P3;
}
public Point2 Derivative(double t)
{
var s = 1 - t;
return 3 * s * s * (P1 - P0) + 6 * s * t * (P2 - P1) + 3 * t * t * (P3 - P2);
}
}
/// <summary>
/// CSS-style timing function <c>cubic-bezier(x1, y1, x2, y2)</c> with end points (0, 0) and (1, 1). x(t) is
/// monotone because x1, x2 ∈ [0, 1]; it is inverted with Newton's method guarded by bisection.
/// </summary>
public readonly record struct CubicBezierEasing
{
public CubicBezierEasing(double x1, double y1, double x2, double y2)
{
if (!(x1 >= 0 && x1 <= 1)) throw new ArgumentOutOfRangeException(nameof(x1), "x1 must lie in [0, 1].");
if (!(x2 >= 0 && x2 <= 1)) throw new ArgumentOutOfRangeException(nameof(x2), "x2 must lie in [0, 1].");
if (!double.IsFinite(y1)) throw new ArgumentOutOfRangeException(nameof(y1));
if (!double.IsFinite(y2)) throw new ArgumentOutOfRangeException(nameof(y2));
X1 = x1;
Y1 = y1;
X2 = x2;
Y2 = y2;
}
public double X1 { get; }
public double Y1 { get; }
public double X2 { get; }
public double Y2 { get; }
public static CubicBezierEasing Linear { get; } = new(0, 0, 1, 1);
public static CubicBezierEasing Ease { get; } = new(0.25, 0.1, 0.25, 1);
public static CubicBezierEasing EaseIn { get; } = new(0.42, 0, 1, 1);
public static CubicBezierEasing EaseOut { get; } = new(0, 0, 0.58, 1);
public static CubicBezierEasing EaseInOut { get; } = new(0.42, 0, 0.58, 1);
/// <summary>Eased progress for input progress <paramref name="x"/> (clamped to [0, 1]).</summary>
public double Evaluate(double x) => Component(Y1, Y2, SolveT(x));
/// <summary>Curve parameter t with x(t) = <paramref name="x"/>.</summary>
public double SolveT(double x)
{
if (!(x > 0)) return 0;
if (x >= 1) return 1;
var t = x;
for (var i = 0; i < 8; i++)
{
var error = Component(X1, X2, t) - x;
if (Math.Abs(error) < 1e-12) return t;
var slope = ComponentDerivative(X1, X2, t);
if (Math.Abs(slope) < 1e-9) break;
t -= error / slope;
if (t is < 0 or > 1) break;
}
double lo = 0, hi = 1;
t = x;
for (var i = 0; i < 64; i++)
{
var value = Component(X1, X2, t);
if (Math.Abs(value - x) < 1e-12) break;
if (value < x) lo = t;
else hi = t;
t = 0.5 * (lo + hi);
}
return t;
}
/// <summary>One coordinate of the curve with P0 = 0 and P3 = 1: ((a·t + b)·t + c)·t.</summary>
private static double Component(double p1, double p2, double t)
{
var c = 3 * p1;
var b = 3 * (p2 - p1) - c;
var a = 1 - c - b;
return ((a * t + b) * t + c) * t;
}
private static double ComponentDerivative(double p1, double p2, double t)
{
var c = 3 * p1;
var b = 3 * (p2 - p1) - c;
var a = 1 - c - b;
return (3 * a * t + 2 * b) * t + c;
}
}
+207
View File
@@ -0,0 +1,207 @@
namespace Chronos.Core.Mathematics;
/// <summary>Output of <see cref="LocalRegression.Smooth"/>; every array has one entry per input sample.</summary>
public sealed class LocalRegressionResult
{
internal LocalRegressionResult(double[] fitted, double[] robustWeights, double[] survivingFraction, int validCount)
{
Fitted = fitted;
RobustWeights = robustWeights;
SurvivingFraction = survivingFraction;
ValidCount = validCount;
}
/// <summary>Smoothed value at every position, including missing samples (interpolated from their neighbours).
/// NaN only when there is no valid sample at all.</summary>
public double[] Fitted { get; }
/// <summary>Tukey biweight each sample carried in the final fit (1 = full inlier, 0 = rejected or missing).</summary>
public double[] RobustWeights { get; }
/// <summary>
/// Σ wᵢⱼ·ρⱼ / Σ wᵢⱼ over the window of each position: the share of its distance (tricube × prior) weight
/// that survived robustness. Near 1 for clean windows, lower where samples were rejected.
/// </summary>
public double[] SurvivingFraction { get; }
public int ValidCount { get; }
}
/// <summary>
/// Robust locally weighted regression, LOWESS (Cleveland 1979). Each position is fitted by weighted least squares
/// of degree 1 or 2 over its <c>window</c> nearest valid samples (asymmetric at the edges, so the count stays
/// constant), with tricube distance weights. Robustness iterations reweight samples with Tukey's biweight of the
/// residuals scaled by 6·MAD. Cost O(n·window) per iteration.
/// </summary>
public static class LocalRegression
{
/// <param name="y">Samples; NaN/±∞ mark missing values.</param>
/// <param name="window">Number of nearest valid samples in each local fit (clamped to the valid count).</param>
/// <param name="degree">Local polynomial degree, 1 (linear) or 2 (quadratic).</param>
/// <param name="robustIterations">Tukey reweighting passes after the initial fit (Cleveland uses 2–3).</param>
/// <param name="x">Non-decreasing positions (e.g. capture seconds); indices when empty.</param>
/// <param name="priorWeights">Optional non-negative sample weights; zero marks a sample as missing.</param>
public static LocalRegressionResult Smooth(
ReadOnlySpan<double> y,
int window,
int degree = 1,
int robustIterations = 2,
ReadOnlySpan<double> x = default,
ReadOnlySpan<double> priorWeights = default)
{
ArgumentOutOfRangeException.ThrowIfLessThan(window, 1);
if (degree is not (1 or 2)) throw new ArgumentOutOfRangeException(nameof(degree), "Degree must be 1 or 2.");
ArgumentOutOfRangeException.ThrowIfNegative(robustIterations);
var n = y.Length;
if (!x.IsEmpty && x.Length != n) throw new ArgumentException("x and y lengths differ.", nameof(x));
if (!priorWeights.IsEmpty && priorWeights.Length != n) throw new ArgumentException("Weight and y lengths differ.", nameof(priorWeights));
var pos = new double[n];
for (var i = 0; i < n; i++)
{
pos[i] = x.IsEmpty ? i : x[i];
if (!double.IsFinite(pos[i])) throw new ArgumentException("Positions must be finite.", nameof(x));
if (i > 0 && pos[i] < pos[i - 1]) throw new ArgumentException("Positions must be non-decreasing.", nameof(x));
}
var valid = new List<int>(n);
for (var i = 0; i < n; i++)
{
var w = priorWeights.IsEmpty ? 1 : priorWeights[i];
if (double.IsFinite(y[i]) && w > 0 && double.IsFinite(w)) valid.Add(i);
}
var m = valid.Count;
var fitted = new double[n];
var robust = new double[n];
var surviving = new double[n];
if (m == 0)
{
Array.Fill(fitted, double.NaN);
return new LocalRegressionResult(fitted, robust, surviving, 0);
}
var vx = new double[m];
var vy = new double[m];
var prior = new double[m];
for (var j = 0; j < m; j++)
{
var i = valid[j];
vx[j] = pos[i];
vy[j] = y[i];
prior[j] = priorWeights.IsEmpty ? 1 : priorWeights[i];
}
var q = Math.Min(window, m);
var p = Math.Min(degree, q - 1);
var windows = BuildWindows(pos, vx, q);
var rho = new double[m];
Array.Fill(rho, 1.0);
var residual = new double[m];
var scaleFloor = 1e-12 * (1 + Math.Abs(Statistics.Median(vy)));
for (var iteration = 0; ; iteration++)
{
FitAll(pos, windows, q, vx, vy, prior, rho, p, fitted, surviving);
if (iteration == robustIterations) break;
for (var j = 0; j < m; j++) residual[j] = vy[j] - fitted[valid[j]];
var mad = Statistics.MedianAbsoluteDeviation(residual, 0);
if (!(mad > scaleFloor)) break;
var c = 6 * mad;
for (var j = 0; j < m; j++)
{
var u = residual[j] / c;
rho[j] = Math.Abs(u) < 1 ? (1 - u * u) * (1 - u * u) : 0;
}
}
for (var j = 0; j < m; j++) robust[valid[j]] = rho[j];
return new LocalRegressionResult(fitted, robust, surviving, m);
}
/// <summary>Start of the contiguous block of <paramref name="q"/> valid samples nearest to each position
/// (sliding k-nearest-neighbour window; total O(n + m)).</summary>
private static int[] BuildWindows(double[] pos, double[] vx, int q)
{
var starts = new int[pos.Length];
var s = 0;
for (var i = 0; i < pos.Length; i++)
{
var xi = pos[i];
while (s + q < vx.Length && xi - vx[s] > vx[s + q] - xi) s++;
starts[i] = s;
}
return starts;
}
private static void FitAll(double[] pos, int[] starts, int q, double[] vx, double[] vy, double[] prior, double[] rho, int degree, double[] fitted, double[] surviving)
{
for (var i = 0; i < pos.Length; i++)
fitted[i] = FitAt(pos[i], starts[i], q, vx, vy, prior, rho, degree, out surviving[i]);
}
private static double FitAt(double xi, int start, int q, double[] vx, double[] vy, double[] prior, double[] rho, int degree, out double surviving)
{
var end = start + q - 1;
var dMax = Math.Max(xi - vx[start], vx[end] - xi);
// One mean sample spacing beyond the farthest neighbour, so every sample in the window keeps a positive weight.
var h = dMax + (q > 1 ? (vx[end] - vx[start]) / (q - 1) : 0);
if (!(h > 0)) h = 1;
double s0 = 0, s1 = 0, s2 = 0, s3 = 0, s4 = 0, t0 = 0, t1 = 0, t2 = 0;
double distanceSum = 0, survivingSum = 0;
double r0 = 0, r1 = 0, r2 = 0, r3 = 0, r4 = 0, rt0 = 0, rt1 = 0, rt2 = 0;
for (var j = start; j <= end; j++)
{
var u = (vx[j] - xi) / h;
var a = 1 - Math.Abs(u * u * u);
var wd = a <= 0 ? 0 : a * a * a * prior[j];
distanceSum += wd;
var w = wd * rho[j];
survivingSum += w;
var uu = u * u;
s0 += w;
s1 += w * u;
s2 += w * uu;
t0 += w * vy[j];
t1 += w * u * vy[j];
r0 += wd;
r1 += wd * u;
r2 += wd * uu;
rt0 += wd * vy[j];
rt1 += wd * u * vy[j];
if (degree == 2)
{
s3 += w * uu * u;
s4 += w * uu * uu;
t2 += w * uu * vy[j];
r3 += wd * uu * u;
r4 += wd * uu * uu;
rt2 += wd * uu * vy[j];
}
}
surviving = distanceSum > 0 ? survivingSum / distanceSum : 0;
// A window whose every sample was rejected falls back to plain distance weights.
return s0 > 1e-12 * distanceSum
? Solve(degree, s0, s1, s2, s3, s4, t0, t1, t2)
: Solve(degree, r0, r1, r2, r3, r4, rt0, rt1, rt2);
}
/// <summary>Intercept of the weighted polynomial fit in centred coordinates, degrading to a lower degree when
/// the normal equations are ill-conditioned (e.g. all weight on one sample).</summary>
private static double Solve(int degree, double s0, double s1, double s2, double s3, double s4, double t0, double t1, double t2)
{
if (!(s0 > 0)) return double.NaN;
if (degree == 2)
{
var c00 = s2 * s4 - s3 * s3;
var c01 = s1 * s4 - s2 * s3;
var c02 = s1 * s3 - s2 * s2;
var det = s0 * c00 - s1 * c01 + s2 * c02;
if (det > 1e-10 * s0 * s2 * s4)
return (t0 * c00 - s1 * (t1 * s4 - s3 * t2) + s2 * (t1 * s3 - s2 * t2)) / det;
}
var det1 = s0 * s2 - s1 * s1;
if (det1 > 1e-10 * s0 * s2) return (s2 * t0 - s1 * t1) / det1;
return t0 / s0;
}
}
+93
View File
@@ -0,0 +1,93 @@
namespace Chronos.Core.Mathematics;
/// <summary>A 3-vector in double precision (colour triplets, homogeneous 2-D points).</summary>
public readonly record struct Vector3D(double X, double Y, double Z);
/// <summary>Row-major 3×3 matrix in double precision for colour-space and planar projective work.</summary>
public readonly record struct Matrix3(
double M11, double M12, double M13,
double M21, double M22, double M23,
double M31, double M32, double M33)
{
public static Matrix3 Identity { get; } = new(1, 0, 0, 0, 1, 0, 0, 0, 1);
/// <summary>Bradford cone-response matrix (Lam 1985), XYZ → sharpened LMS.</summary>
public static Matrix3 Bradford { get; } = new(
0.8951, 0.2664, -0.1614,
-0.7502, 1.7135, 0.0367,
0.0389, -0.0685, 1.0296);
/// <summary>Linear Rec.709/sRGB (D65) → CIE XYZ, derived from the primaries.</summary>
public static Matrix3 Rec709ToXyz { get; } = RgbToXyz(new(0.64, 0.33), new(0.30, 0.60), new(0.15, 0.06), Chromaticity.D65);
/// <summary>CIE XYZ → linear Rec.709/sRGB (D65).</summary>
public static Matrix3 XyzToRec709 { get; } = Rec709ToXyz.Inverse();
public static Matrix3 Diagonal(double a, double b, double c) => new(a, 0, 0, 0, b, 0, 0, 0, c);
/// <summary>Matrix whose columns are <paramref name="c1"/>, <paramref name="c2"/>, <paramref name="c3"/>.</summary>
public static Matrix3 FromColumns(Vector3D c1, Vector3D c2, Vector3D c3) => new(c1.X, c2.X, c3.X, c1.Y, c2.Y, c3.Y, c1.Z, c2.Z, c3.Z);
public static Matrix3 operator *(Matrix3 a, Matrix3 b) => new(
a.M11 * b.M11 + a.M12 * b.M21 + a.M13 * b.M31, a.M11 * b.M12 + a.M12 * b.M22 + a.M13 * b.M32, a.M11 * b.M13 + a.M12 * b.M23 + a.M13 * b.M33,
a.M21 * b.M11 + a.M22 * b.M21 + a.M23 * b.M31, a.M21 * b.M12 + a.M22 * b.M22 + a.M23 * b.M32, a.M21 * b.M13 + a.M22 * b.M23 + a.M23 * b.M33,
a.M31 * b.M11 + a.M32 * b.M21 + a.M33 * b.M31, a.M31 * b.M12 + a.M32 * b.M22 + a.M33 * b.M32, a.M31 * b.M13 + a.M32 * b.M23 + a.M33 * b.M33);
public static Vector3D operator *(Matrix3 m, Vector3D v) => new(
m.M11 * v.X + m.M12 * v.Y + m.M13 * v.Z,
m.M21 * v.X + m.M22 * v.Y + m.M23 * v.Z,
m.M31 * v.X + m.M32 * v.Y + m.M33 * v.Z);
public double Determinant =>
M11 * (M22 * M33 - M23 * M32) - M12 * (M21 * M33 - M23 * M31) + M13 * (M21 * M32 - M22 * M31);
public Matrix3 Transpose() => new(M11, M21, M31, M12, M22, M32, M13, M23, M33);
/// <summary>Inverse by the adjugate; false when the matrix is singular relative to its scale.</summary>
public bool TryInvert(out Matrix3 inverse)
{
var det = Determinant;
var scale = MaxAbs();
if (!(Math.Abs(det) > 1e-14 * scale * scale * scale) || !double.IsFinite(det))
{
inverse = default;
return false;
}
var r = 1 / det;
inverse = new Matrix3(
(M22 * M33 - M23 * M32) * r, (M13 * M32 - M12 * M33) * r, (M12 * M23 - M13 * M22) * r,
(M23 * M31 - M21 * M33) * r, (M11 * M33 - M13 * M31) * r, (M13 * M21 - M11 * M23) * r,
(M21 * M32 - M22 * M31) * r, (M12 * M31 - M11 * M32) * r, (M11 * M22 - M12 * M21) * r);
return true;
}
/// <exception cref="InvalidOperationException">The matrix is singular.</exception>
public Matrix3 Inverse() => TryInvert(out var inverse) ? inverse : throw new InvalidOperationException("Matrix is singular.");
/// <summary>
/// Bradford chromatic adaptation (von Kries scaling in the Bradford cone space) mapping colours seen under
/// <paramref name="sourceWhite"/> to <paramref name="destinationWhite"/>; both whites as XYZ.
/// </summary>
public static Matrix3 BradfordAdaptation(Vector3D sourceWhite, Vector3D destinationWhite)
{
var s = Bradford * sourceWhite;
var d = Bradford * destinationWhite;
if (!(s.X > 0 && s.Y > 0 && s.Z > 0)) throw new ArgumentOutOfRangeException(nameof(sourceWhite), "White point must have positive cone responses.");
return Bradford.Inverse() * Diagonal(d.X / s.X, d.Y / s.Y, d.Z / s.Z) * Bradford;
}
/// <summary>RGB → XYZ matrix of an additive colour space from its primaries and white point (white maps to Y = 1).</summary>
public static Matrix3 RgbToXyz(Chromaticity red, Chromaticity green, Chromaticity blue, Chromaticity white)
{
var primaries = FromColumns(red.ToXyz(), green.ToXyz(), blue.ToXyz());
var s = primaries.Inverse() * white.ToXyz();
return primaries * Diagonal(s.X, s.Y, s.Z);
}
private double MaxAbs()
{
var m = Math.Max(Math.Max(Math.Abs(M11), Math.Abs(M12)), Math.Abs(M13));
m = Math.Max(m, Math.Max(Math.Max(Math.Abs(M21), Math.Abs(M22)), Math.Abs(M23)));
return Math.Max(m, Math.Max(Math.Max(Math.Abs(M31), Math.Abs(M32)), Math.Abs(M33)));
}
}
+177
View File
@@ -0,0 +1,177 @@
namespace Chronos.Core.Mathematics;
/// <summary>
/// Monotone piecewise cubic Hermite interpolant (Fritsch &amp; Carlson 1980): three-point tangents limited to the
/// circle α² + β² ≤ 9 so the curve never overshoots monotone data. Outside the knot range the value is clamped
/// to the end values (derivative 0), which keeps time remaps monotone.
/// </summary>
public sealed class MonotoneSpline
{
private readonly double[] _x;
private readonly double[] _y;
private readonly double[] _m;
/// <param name="x">Strictly increasing, finite knot positions (at least one).</param>
/// <param name="y">Finite knot values.</param>
public MonotoneSpline(ReadOnlySpan<double> x, ReadOnlySpan<double> y)
{
SplineInput.Validate(x, y, minimum: 1);
_x = x.ToArray();
_y = y.ToArray();
_m = new double[_x.Length];
var n = _x.Length;
if (n == 1) return;
var delta = new double[n - 1];
var increasing = true;
var decreasing = true;
for (var k = 0; k < n - 1; k++)
{
delta[k] = (_y[k + 1] - _y[k]) / (_x[k + 1] - _x[k]);
increasing &= delta[k] >= 0;
decreasing &= delta[k] <= 0;
}
IsMonotone = increasing || decreasing;
_m[0] = delta[0];
_m[n - 1] = delta[n - 2];
for (var k = 1; k < n - 1; k++)
{
if (delta[k - 1] * delta[k] <= 0)
{
_m[k] = 0;
continue;
}
// Three-point derivative for non-uniform spacing (exact for quadratics).
var h0 = _x[k] - _x[k - 1];
var h1 = _x[k + 1] - _x[k];
_m[k] = (h1 * delta[k - 1] + h0 * delta[k]) / (h0 + h1);
}
for (var k = 0; k < n - 1; k++)
{
if (delta[k] == 0)
{
_m[k] = 0;
_m[k + 1] = 0;
continue;
}
var alpha = _m[k] / delta[k];
var beta = _m[k + 1] / delta[k];
if (alpha < 0) _m[k] = alpha = 0;
if (beta < 0) _m[k + 1] = beta = 0;
var s = alpha * alpha + beta * beta;
if (s > 9)
{
var tau = 3 / Math.Sqrt(s);
_m[k] = tau * alpha * delta[k];
_m[k + 1] = tau * beta * delta[k];
}
}
}
public int Count => _x.Length;
public double MinX => _x[0];
public double MaxX => _x[^1];
/// <summary>True when the knot values are entirely non-decreasing or non-increasing (required by <see cref="Inverse"/>).</summary>
public bool IsMonotone { get; } = true;
public double Evaluate(double x)
{
if (!(x > _x[0])) return _y[0];
if (x >= _x[^1]) return _y[^1];
var k = Interval(x);
var h = _x[k + 1] - _x[k];
var t = (x - _x[k]) / h;
var t2 = t * t;
var t3 = t2 * t;
// Increment form: rounding scales with the interval's rise, so flat intervals stay exactly flat.
return _y[k] + (_y[k + 1] - _y[k]) * (3 * t2 - 2 * t3) + h * ((t3 - 2 * t2 + t) * _m[k] + (t3 - t2) * _m[k + 1]);
}
public double Derivative(double x)
{
if (!(x > _x[0]) || x >= _x[^1]) return 0;
var k = Interval(x);
var h = _x[k + 1] - _x[k];
var t = (x - _x[k]) / h;
var t2 = t * t;
return ((6 * t2 - 6 * t) * _y[k]
+ (3 * t2 - 4 * t + 1) * h * _m[k]
+ (-6 * t2 + 6 * t) * _y[k + 1]
+ (3 * t2 - 2 * t) * h * _m[k + 1]) / h;
}
/// <summary>
/// The x at which the spline reaches <paramref name="y"/> (values outside the range clamp to the end knots;
/// on a flat stretch the first x is returned). Safeguarded Newton iteration inside the bracketing interval.
/// </summary>
/// <exception cref="InvalidOperationException">The knot values are not monotone.</exception>
public double Inverse(double y)
{
if (!IsMonotone) throw new InvalidOperationException("Inverse requires monotone knot values.");
var n = _x.Length;
var sign = _y[^1] >= _y[0] ? 1.0 : -1.0;
var target = sign * y;
if (n == 1 || !(target > sign * _y[0])) return _x[0];
if (target >= sign * _y[^1]) return FirstAtEnd();
int lo = 0, hi = n - 1;
while (hi - lo > 1)
{
var mid = (lo + hi) >> 1;
if (sign * _y[mid] < target) lo = mid;
else hi = mid;
}
if (sign * _y[hi] == target)
{
while (hi > 0 && _y[hi - 1] == _y[hi]) hi--;
return _x[hi];
}
double a = _x[lo], b = _x[hi];
var x = a + (b - a) * (target - sign * _y[lo]) / (sign * (_y[hi] - _y[lo]));
for (var i = 0; i < 100 && b - a > 1e-14 * (1 + Math.Abs(a)); i++)
{
var f = sign * Evaluate(x) - target;
if (f == 0) return x;
if (f < 0) a = x;
else b = x;
var d = sign * Derivative(x);
var next = d > 0 ? x - f / d : double.NaN;
x = next > a && next < b ? next : 0.5 * (a + b);
}
return x;
}
private double FirstAtEnd()
{
var i = _x.Length - 1;
while (i > 0 && _y[i - 1] == _y[i]) i--;
return _x[i];
}
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);
}
}
internal static class SplineInput
{
public static void Validate(ReadOnlySpan<double> x, ReadOnlySpan<double> y, int minimum)
{
if (x.Length != y.Length) throw new ArgumentException("x and y lengths differ.", nameof(y));
if (x.Length < minimum) throw new ArgumentException($"At least {minimum} knot(s) required.", nameof(x));
for (var i = 0; i < x.Length; i++)
{
if (!double.IsFinite(x[i]) || !double.IsFinite(y[i])) throw new ArgumentException("Knots must be finite.", nameof(x));
if (i > 0 && !(x[i] > x[i - 1])) throw new ArgumentException("x must be strictly increasing.", nameof(x));
}
}
}
@@ -0,0 +1,88 @@
namespace Chronos.Core.Mathematics;
/// <summary>
/// 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.
/// </summary>
public sealed class NaturalCubicSpline
{
private readonly double[] _x;
private readonly double[] _y;
private readonly double[] _m;
/// <param name="x">Strictly increasing, finite knot positions (at least one).</param>
/// <param name="y">Finite knot values.</param>
public NaturalCubicSpline(ReadOnlySpan<double> x, ReadOnlySpan<double> 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);
}
}
+17
View File
@@ -0,0 +1,17 @@
namespace Chronos.Core.Mathematics;
/// <summary>A point or vector in the plane, double precision.</summary>
public readonly record struct Point2(double X, double Y)
{
public static Point2 operator +(Point2 a, Point2 b) => new(a.X + b.X, a.Y + b.Y);
public static Point2 operator -(Point2 a, Point2 b) => new(a.X - b.X, a.Y - b.Y);
public static Point2 operator *(Point2 a, double s) => new(a.X * s, a.Y * s);
public static Point2 operator *(double s, Point2 a) => new(a.X * s, a.Y * s);
public double Length => Math.Sqrt(X * X + Y * Y);
public static double Distance(Point2 a, Point2 b) => (a - b).Length;
}
+219
View File
@@ -0,0 +1,219 @@
namespace Chronos.Core.Mathematics;
/// <summary>Light condition by solar elevation (geometric centre of the disc).</summary>
public enum DayPhase
{
/// <summary>Sun below −18°.</summary>
Night,
/// <summary>−18° to −12°.</summary>
AstronomicalTwilight,
/// <summary>−12° to −6°.</summary>
NauticalTwilight,
/// <summary>−6° to sunrise/sunset (−0.833°).</summary>
CivilTwilight,
/// <summary>Sun up but below 6°.</summary>
GoldenHour,
/// <summary>Sun at or above 6°.</summary>
Day,
}
/// <summary>Sun position for an instant and place.</summary>
/// <param name="Elevation">Apparent elevation in degrees, corrected for standard atmospheric refraction.</param>
/// <param name="Azimuth">Degrees clockwise from true north.</param>
/// <param name="GeometricElevation">Elevation without refraction, in degrees (used for twilight limits).</param>
/// <param name="Declination">Solar declination in degrees.</param>
/// <param name="EquationOfTimeMinutes">Apparent minus mean solar time, in minutes.</param>
public readonly record struct SolarCoordinates(double Elevation, double Azimuth, double GeometricElevation, double Declination, double EquationOfTimeMinutes)
{
public DayPhase Phase => SolarPosition.Classify(GeometricElevation);
}
/// <summary>Sun events of one local solar day, all in UTC; null when the event does not occur (polar day/night).</summary>
public sealed record SolarDay(
DateOnly Date,
DateTime SolarNoon,
DateTime? Sunrise,
DateTime? Sunset,
DateTime? CivilDawn,
DateTime? CivilDusk,
DateTime? NauticalDawn,
DateTime? NauticalDusk,
DateTime? AstronomicalDawn,
DateTime? AstronomicalDusk);
/// <summary>
/// Solar position and rise/set times with the NOAA Solar Calculator equations (after Meeus, "Astronomical
/// Algorithms"). Event times are refined iteratively at the event instant; accuracy is about one minute for
/// latitudes within ±72°. Longitudes are east-positive, latitudes north-positive, times UTC.
/// </summary>
public static class SolarPosition
{
/// <summary>Geometric elevation of the disc centre at apparent sunrise/sunset (34′ refraction + 16′ semi-diameter).</summary>
public const double SunriseElevation = -0.833;
public const double CivilTwilightElevation = -6;
public const double NauticalTwilightElevation = -12;
public const double AstronomicalTwilightElevation = -18;
public const double GoldenHourElevation = 6;
private const double Deg = Math.PI / 180;
private static readonly DateTime J2000 = new(2000, 1, 1, 12, 0, 0, DateTimeKind.Utc);
/// <summary>Sun position at <paramref name="utc"/> (a value of unspecified kind is taken as UTC).</summary>
public static SolarCoordinates Compute(DateTime utc, double latitude, double longitude)
{
ValidateLocation(latitude, longitude);
var sun = Ephemeris(utc);
var minutes = utc.TimeOfDay.TotalMinutes;
var trueSolarTime = Mod(minutes + sun.EquationOfTime + 4 * longitude, 1440);
var hourAngle = trueSolarTime / 4 - 180;
var phi = latitude * Deg;
var delta = sun.Declination * Deg;
var cosZenith = Math.Clamp(Math.Sin(phi) * Math.Sin(delta) + Math.Cos(phi) * Math.Cos(delta) * Math.Cos(hourAngle * Deg), -1, 1);
var zenith = Math.Acos(cosZenith);
var geometric = 90 - zenith / Deg;
double azimuth;
var denominator = Math.Cos(phi) * Math.Sin(zenith);
if (Math.Abs(denominator) < 1e-12)
{
azimuth = latitude > 0 ? 180 : 0;
}
else
{
var a = Math.Acos(Math.Clamp((Math.Sin(phi) * cosZenith - Math.Sin(delta)) / denominator, -1, 1)) / Deg;
azimuth = hourAngle > 0 ? Mod(a + 180, 360) : Mod(540 - a, 360);
}
return new SolarCoordinates(geometric + Refraction(geometric), azimuth, geometric, sun.Declination, sun.EquationOfTime);
}
/// <summary>Day phase from the geometric elevation in degrees.</summary>
public static DayPhase Classify(double geometricElevation) => geometricElevation switch
{
< AstronomicalTwilightElevation => DayPhase.Night,
< NauticalTwilightElevation => DayPhase.AstronomicalTwilight,
< CivilTwilightElevation => DayPhase.NauticalTwilight,
< SunriseElevation => DayPhase.CivilTwilight,
< GoldenHourElevation => DayPhase.GoldenHour,
_ => DayPhase.Day,
};
public static DayPhase Phase(DateTime utc, double latitude, double longitude) => Compute(utc, latitude, longitude).Phase;
/// <summary>All rise/set and twilight events of the local solar day <paramref name="date"/> (the day whose solar
/// noon falls on that calendar date at the given longitude).</summary>
public static SolarDay Events(DateOnly date, double latitude, double longitude)
{
ValidateLocation(latitude, longitude);
return new SolarDay(
date,
SolarNoon(date, longitude),
EventTime(date, latitude, longitude, SunriseElevation, rising: true),
EventTime(date, latitude, longitude, SunriseElevation, rising: false),
EventTime(date, latitude, longitude, CivilTwilightElevation, rising: true),
EventTime(date, latitude, longitude, CivilTwilightElevation, rising: false),
EventTime(date, latitude, longitude, NauticalTwilightElevation, rising: true),
EventTime(date, latitude, longitude, NauticalTwilightElevation, rising: false),
EventTime(date, latitude, longitude, AstronomicalTwilightElevation, rising: true),
EventTime(date, latitude, longitude, AstronomicalTwilightElevation, rising: false));
}
/// <summary>UTC solar noon (upper transit) of the local solar day.</summary>
public static DateTime SolarNoon(DateOnly date, double longitude)
{
var midnight = date.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
var minutes = 720 - 4 * longitude;
for (var i = 0; i < 3; i++)
minutes = 720 - 4 * longitude - Ephemeris(midnight.AddMinutes(minutes)).EquationOfTime;
return midnight.AddMinutes(minutes);
}
/// <summary>
/// UTC time at which the sun's geometric centre crosses <paramref name="elevation"/> degrees on the given
/// local solar day, rising (morning) or setting (evening); null when it stays above or below all day.
/// </summary>
public static DateTime? EventTime(DateOnly date, double latitude, double longitude, double elevation, bool rising)
{
ValidateLocation(latitude, longitude);
var midnight = date.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
var minutes = 720 - 4 * longitude;
for (var i = 0; i < 4; i++)
{
var sun = Ephemeris(midnight.AddMinutes(minutes));
var hourAngle = HourAngle(latitude, sun.Declination, elevation);
if (double.IsNaN(hourAngle)) return null;
var noon = 720 - 4 * longitude - sun.EquationOfTime;
minutes = noon + (rising ? -4 : 4) * hourAngle;
}
return midnight.AddMinutes(minutes);
}
private static double HourAngle(double latitude, double declination, double elevation)
{
var phi = latitude * Deg;
var delta = declination * Deg;
var cosH = (Math.Cos((90 - elevation) * Deg) - Math.Sin(phi) * Math.Sin(delta)) / (Math.Cos(phi) * Math.Cos(delta));
return cosH is < -1 or > 1 || double.IsNaN(cosH) ? double.NaN : Math.Acos(cosH) / Deg;
}
/// <summary>NOAA approximation of standard atmospheric refraction, in degrees, for a geometric elevation.</summary>
private static double Refraction(double elevation)
{
if (elevation > 85) return 0;
var t = Math.Tan(elevation * Deg);
var arcSeconds = elevation switch
{
> 5 => 58.1 / t - 0.07 / (t * t * t) + 0.000086 / Math.Pow(t, 5),
> -0.575 => 1735 + elevation * (-518.2 + elevation * (103.4 + elevation * (-12.79 + elevation * 0.711))),
_ => -20.772 / t,
};
return arcSeconds / 3600;
}
private readonly record struct Sun(double Declination, double EquationOfTime);
private static Sun Ephemeris(DateTime utc)
{
var julianDay = 2451545.0 + (DateTime.SpecifyKind(utc, DateTimeKind.Utc) - J2000).TotalDays;
var t = (julianDay - 2451545.0) / 36525.0;
var meanLongitude = Mod(280.46646 + t * (36000.76983 + t * 0.0003032), 360);
var meanAnomaly = 357.52911 + t * (35999.05029 - 0.0001537 * t);
var eccentricity = 0.016708634 - t * (0.000042037 + 0.0000001267 * t);
var m = meanAnomaly * Deg;
var center = Math.Sin(m) * (1.914602 - t * (0.004817 + 0.000014 * t))
+ Math.Sin(2 * m) * (0.019993 - 0.000101 * t)
+ Math.Sin(3 * m) * 0.000289;
var trueLongitude = meanLongitude + center;
var omega = (125.04 - 1934.136 * t) * Deg;
var apparentLongitude = trueLongitude - 0.00569 - 0.00478 * Math.Sin(omega);
var meanObliquity = 23 + (26 + (21.448 - t * (46.815 + t * (0.00059 - t * 0.001813))) / 60) / 60;
var obliquity = (meanObliquity + 0.00256 * Math.Cos(omega)) * Deg;
var declination = Math.Asin(Math.Sin(obliquity) * Math.Sin(apparentLongitude * Deg)) / Deg;
var y = Math.Tan(obliquity / 2);
y *= y;
var l0 = meanLongitude * Deg;
var e = eccentricity;
var equationOfTime = 4 / Deg * (y * Math.Sin(2 * l0) - 2 * e * Math.Sin(m) + 4 * e * y * Math.Sin(m) * Math.Cos(2 * l0)
- 0.5 * y * y * Math.Sin(4 * l0) - 1.25 * e * e * Math.Sin(2 * m));
return new Sun(declination, equationOfTime);
}
private static double Mod(double value, double modulus)
{
var r = value % modulus;
return r < 0 ? r + modulus : r;
}
private static void ValidateLocation(double latitude, double longitude)
{
if (!(latitude >= -90 && latitude <= 90)) throw new ArgumentOutOfRangeException(nameof(latitude));
if (!(longitude >= -180 && longitude <= 180)) throw new ArgumentOutOfRangeException(nameof(longitude));
}
}
+417
View File
@@ -0,0 +1,417 @@
using System.Buffers;
using System.Numerics;
namespace Chronos.Core.Mathematics;
/// <summary>A robustly fitted straight line <c>y = Intercept + Slope·x</c>.</summary>
/// <param name="Scale">Robust residual standard deviation (1.4826 × MAD of the final residuals).</param>
public readonly record struct RobustLine(double Slope, double Intercept, double Scale)
{
public double Evaluate(double x) => Intercept + Slope * x;
}
/// <summary>
/// Order statistics and robust estimators. Every function ignores NaN inputs and returns NaN when no
/// valid value remains. Selection is linear-time (quickselect with an introsort fallback).
/// </summary>
public static class Statistics
{
/// <summary>Scales a median absolute deviation to the standard deviation of a normal distribution (1/Φ⁻¹(3/4)).</summary>
public const double MadToSigma = 1.482602218505602;
/// <summary>
/// Rearranges <paramref name="values"/> so that <c>values[k]</c> is the k-th smallest, everything before it is
/// ≤ and everything after is ≥ (Hoare quickselect, median-of-three pivot; falls back to sorting the
/// remaining range after too many unbalanced rounds, so the worst case is O(n log n)). NaN-free input.
/// </summary>
public static double Select(Span<double> values, int k)
{
if ((uint)k >= (uint)values.Length) throw new ArgumentOutOfRangeException(nameof(k));
int lo = 0, hi = values.Length - 1;
var budget = 2 * BitOperations.Log2((uint)values.Length) + 4;
while (hi > lo)
{
if (hi - lo < 16 || --budget < 0)
{
values.Slice(lo, hi - lo + 1).Sort();
return values[k];
}
var mid = lo + ((hi - lo) >> 1);
if (values[mid] < values[lo]) (values[mid], values[lo]) = (values[lo], values[mid]);
if (values[hi] < values[lo]) (values[hi], values[lo]) = (values[lo], values[hi]);
if (values[hi] < values[mid]) (values[hi], values[mid]) = (values[mid], values[hi]);
var pivot = values[mid];
int i = lo, j = hi;
while (i <= j)
{
while (values[i] < pivot) i++;
while (values[j] > pivot) j--;
if (i <= j)
{
(values[i], values[j]) = (values[j], values[i]);
i++;
j--;
}
}
if (k <= j) hi = j;
else if (k >= i) lo = i;
else return values[k];
}
return values[k];
}
public static double Mean(ReadOnlySpan<double> values)
{
double sum = 0;
var n = 0;
foreach (var v in values)
{
if (double.IsNaN(v)) continue;
sum += v;
n++;
}
return n == 0 ? double.NaN : sum / n;
}
/// <summary>Root mean square of the valid values.</summary>
public static double Rms(ReadOnlySpan<double> values)
{
double sum = 0;
var n = 0;
foreach (var v in values)
{
if (double.IsNaN(v)) continue;
sum += v * v;
n++;
}
return n == 0 ? double.NaN : Math.Sqrt(sum / n);
}
/// <summary>Sample standard deviation (n − 1 denominator) of the valid values.</summary>
public static double StandardDeviation(ReadOnlySpan<double> values)
{
var mean = Mean(values);
double sum = 0;
var n = 0;
foreach (var v in values)
{
if (double.IsNaN(v)) continue;
sum += (v - mean) * (v - mean);
n++;
}
return n < 2 ? double.NaN : Math.Sqrt(sum / (n - 1));
}
public static double Median(ReadOnlySpan<double> values)
{
var buffer = RentValid(values, out var n);
try
{
return n == 0 ? double.NaN : MedianInPlace(buffer.AsSpan(0, n));
}
finally
{
ArrayPool<double>.Shared.Return(buffer);
}
}
/// <summary>Median of NaN-free <paramref name="values"/>, reordering them.</summary>
public static double MedianInPlace(Span<double> values)
{
var n = values.Length;
if (n == 0) return double.NaN;
var upper = Select(values, n / 2);
if ((n & 1) == 1) return upper;
var lower = double.NegativeInfinity;
foreach (var v in values[..(n / 2)]) lower = Math.Max(lower, v);
return 0.5 * (lower + upper);
}
/// <summary>Raw median absolute deviation about <paramref name="center"/> (the median when omitted).
/// Multiply by <see cref="MadToSigma"/> for a normal-consistent scale.</summary>
public static double MedianAbsoluteDeviation(ReadOnlySpan<double> values, double? center = null)
{
var buffer = RentValid(values, out var n);
try
{
if (n == 0) return double.NaN;
var span = buffer.AsSpan(0, n);
var c = center ?? MedianInPlace(span);
for (var i = 0; i < n; i++) span[i] = Math.Abs(span[i] - c);
return MedianInPlace(span);
}
finally
{
ArrayPool<double>.Shared.Return(buffer);
}
}
/// <summary>Mean after discarding the lowest <paramref name="lowFraction"/> and highest
/// <paramref name="highFraction"/> of the valid values (counts rounded down), in linear time.</summary>
public static double TrimmedMean(ReadOnlySpan<double> values, double lowFraction, double highFraction)
{
if (!(lowFraction >= 0 && highFraction >= 0 && lowFraction + highFraction < 1))
throw new ArgumentOutOfRangeException(nameof(lowFraction), "Fractions must be ≥ 0 and sum below 1.");
var buffer = RentValid(values, out var n);
try
{
if (n == 0) return double.NaN;
var span = buffer.AsSpan(0, n);
var low = (int)(n * lowFraction);
var keep = n - low - (int)(n * highFraction);
if (keep <= 0) return MedianInPlace(span);
if (low > 0) Select(span, low);
var rest = span[low..];
if (keep < rest.Length) Select(rest, keep - 1);
double sum = 0;
foreach (var v in rest[..keep]) sum += v;
return sum / keep;
}
finally
{
ArrayPool<double>.Shared.Return(buffer);
}
}
/// <summary>Percentile <paramref name="p"/> ∈ [0, 1] with linear interpolation between order statistics
/// (Hyndman–Fan type 7, the spreadsheet/NumPy default).</summary>
public static double Percentile(ReadOnlySpan<double> values, double p)
{
if (!(p >= 0 && p <= 1)) throw new ArgumentOutOfRangeException(nameof(p));
var buffer = RentValid(values, out var n);
try
{
if (n == 0) return double.NaN;
var span = buffer.AsSpan(0, n);
var h = (n - 1) * p;
var lo = (int)Math.Floor(h);
var a = Select(span, lo);
if (lo + 1 >= n || h == lo) return a;
var b = double.PositiveInfinity;
foreach (var v in span[(lo + 1)..]) b = Math.Min(b, v);
return a + (h - lo) * (b - a);
}
finally
{
ArrayPool<double>.Shared.Return(buffer);
}
}
/// <summary>
/// Weighted percentile: each value occupies a share of the cumulative weight and is placed at the centre
/// of its share; results interpolate linearly between centres and clamp outside them. Values with NaN or
/// non-positive weight are ignored. Equal weights reproduce the Hazen (type 5) percentile.
/// </summary>
public static double WeightedPercentile(ReadOnlySpan<double> values, ReadOnlySpan<double> weights, double p)
{
if (values.Length != weights.Length) throw new ArgumentException("Lengths differ.", nameof(weights));
if (!(p >= 0 && p <= 1)) throw new ArgumentOutOfRangeException(nameof(p));
var keys = new List<double>(values.Length);
var w = new List<double>(values.Length);
for (var i = 0; i < values.Length; i++)
{
if (double.IsNaN(values[i]) || !(weights[i] > 0) || double.IsInfinity(weights[i])) continue;
keys.Add(values[i]);
w.Add(weights[i]);
}
var n = keys.Count;
if (n == 0) return double.NaN;
var k = keys.ToArray();
var ww = w.ToArray();
Array.Sort(k, ww);
double total = 0;
foreach (var x in ww) total += x;
var target = p * total;
double cumulative = 0;
var previousCentre = 0.0;
for (var i = 0; i < n; i++)
{
var centre = cumulative + 0.5 * ww[i];
if (target <= centre)
{
if (i == 0) return k[0];
var t = (target - previousCentre) / (centre - previousCentre);
return k[i - 1] + t * (k[i] - k[i - 1]);
}
previousCentre = centre;
cumulative += ww[i];
}
return k[n - 1];
}
/// <summary>Accumulates <paramref name="values"/> (optionally weighted) into equal-width bins over
/// [<paramref name="min"/>, <paramref name="max"/>); values outside are clamped into the end bins.</summary>
public static void AccumulateHistogram(ReadOnlySpan<double> values, double min, double max, Span<double> bins, ReadOnlySpan<double> weights = default)
{
if (!(max > min)) throw new ArgumentOutOfRangeException(nameof(max));
if (bins.IsEmpty) throw new ArgumentException("No bins.", nameof(bins));
if (!weights.IsEmpty && weights.Length != values.Length) throw new ArgumentException("Lengths differ.", nameof(weights));
var scale = bins.Length / (max - min);
var last = bins.Length - 1;
for (var i = 0; i < values.Length; i++)
{
var v = values[i];
if (double.IsNaN(v)) continue;
var b = (v - min) * scale;
var index = b <= 0 ? 0 : b >= last ? last : (int)b;
bins[index] += weights.IsEmpty ? 1 : weights[i];
}
}
/// <summary>Percentile of a histogram over [<paramref name="min"/>, <paramref name="max"/>), interpolating
/// linearly inside the bin that contains the target mass.</summary>
public static double HistogramPercentile(ReadOnlySpan<double> bins, double min, double max, double p)
{
if (!(p >= 0 && p <= 1)) throw new ArgumentOutOfRangeException(nameof(p));
double total = 0;
foreach (var b in bins) total += b;
if (!(total > 0)) return double.NaN;
var width = (max - min) / bins.Length;
var target = p * total;
double cumulative = 0;
for (var i = 0; i < bins.Length; i++)
{
if (bins[i] <= 0) continue;
if (cumulative + bins[i] >= target)
return min + width * (i + (target - cumulative) / bins[i]);
cumulative += bins[i];
}
return max;
}
/// <summary>Symmetric chi-square distance ½·Σ (aᵢ − bᵢ)² / (aᵢ + bᵢ) between two histograms normalised to unit mass
/// (0 = identical, 1 = disjoint).</summary>
public static double ChiSquareDistance(ReadOnlySpan<double> a, ReadOnlySpan<double> b)
{
if (a.Length != b.Length) throw new ArgumentException("Lengths differ.", nameof(b));
double sa = 0, sb = 0;
for (var i = 0; i < a.Length; i++)
{
sa += a[i];
sb += b[i];
}
if (!(sa > 0) || !(sb > 0)) return sa > 0 || sb > 0 ? 1 : 0;
double d = 0;
for (var i = 0; i < a.Length; i++)
{
var x = a[i] / sa;
var y = b[i] / sb;
var s = x + y;
if (s > 0) d += (x - y) * (x - y) / s;
}
return 0.5 * d;
}
/// <summary>
/// Robust straight-line fit: Tukey's resistant line (medians of the outer thirds) as the start, then
/// iteratively reweighted least squares with Tukey biweights on residuals scaled by 6·MAD.
/// Pairs with a NaN coordinate are ignored.
/// </summary>
public static RobustLine RobustLinearFit(ReadOnlySpan<double> x, ReadOnlySpan<double> y, int iterations = 10)
{
if (x.Length != y.Length) throw new ArgumentException("Lengths differ.", nameof(y));
var px = new List<double>(x.Length);
var py = new List<double>(x.Length);
for (var i = 0; i < x.Length; i++)
{
if (!double.IsFinite(x[i]) || !double.IsFinite(y[i])) continue;
px.Add(x[i]);
py.Add(y[i]);
}
var n = px.Count;
if (n == 0) return new RobustLine(0, double.NaN, double.NaN);
var xs = px.ToArray();
var ys = py.ToArray();
Array.Sort(xs, ys);
if (n < 3 || xs[^1] == xs[0])
{
var c = Median(ys);
return new RobustLine(0, c, MadToSigma * MedianAbsoluteDeviation(ys, c));
}
var third = Math.Max(1, n / 3);
var xl = Median(xs.AsSpan(0, third));
var xr = Median(xs.AsSpan(n - third));
var slope = xr > xl ? (Median(ys.AsSpan(n - third)) - Median(ys.AsSpan(0, third))) / (xr - xl) : 0;
var residual = new double[n];
for (var i = 0; i < n; i++) residual[i] = ys[i] - slope * xs[i];
var intercept = Median(residual);
var scaleFloor = 1e-12 * (1 + Math.Abs(Median(ys)));
for (var iteration = 0; iteration < iterations; iteration++)
{
for (var i = 0; i < n; i++) residual[i] = ys[i] - intercept - slope * xs[i];
var mad = MedianAbsoluteDeviation(residual, 0);
if (!(mad > scaleFloor)) break;
var c = 6 * mad;
double sw = 0, swx = 0, swy = 0, swxx = 0, swxy = 0;
for (var i = 0; i < n; i++)
{
var u = residual[i] / c;
if (Math.Abs(u) >= 1) continue;
var w = (1 - u * u) * (1 - u * u);
sw += w;
swx += w * xs[i];
swy += w * ys[i];
swxx += w * xs[i] * xs[i];
swxy += w * xs[i] * ys[i];
}
if (!(sw > 0)) break;
var mx = swx / sw;
var sxx = swxx - sw * mx * mx;
if (!(sxx > 1e-300)) break;
var newSlope = (swxy - swx * swy / sw) / sxx;
var newIntercept = swy / sw - newSlope * mx;
var converged = Math.Abs(newSlope - slope) <= 1e-12 * (1 + Math.Abs(slope))
&& Math.Abs(newIntercept - intercept) <= 1e-12 * (1 + Math.Abs(intercept));
slope = newSlope;
intercept = newIntercept;
if (converged) break;
}
for (var i = 0; i < n; i++) residual[i] = ys[i] - intercept - slope * xs[i];
return new RobustLine(slope, intercept, MadToSigma * MedianAbsoluteDeviation(residual, 0));
}
/// <summary>
/// Sample autocorrelation r(k) for k = 0 … <c>result.Length − 1</c> (biased estimator normalised by the lag-0
/// sum, so |r| ≤ 1). Pairs containing NaN are skipped. A constant series yields r(0) = 1 and 0 elsewhere.
/// </summary>
public static void Autocorrelation(ReadOnlySpan<double> values, Span<double> result)
{
result.Clear();
if (result.IsEmpty) return;
var mean = Mean(values);
if (double.IsNaN(mean)) return;
double denominator = 0;
foreach (var v in values)
{
if (!double.IsNaN(v)) denominator += (v - mean) * (v - mean);
}
result[0] = 1;
if (!(denominator > 0)) return;
var maxLag = Math.Min(result.Length - 1, values.Length - 1);
for (var k = 1; k <= maxLag; k++)
{
double sum = 0;
for (var i = 0; i + k < values.Length; i++)
{
var a = values[i];
var b = values[i + k];
if (double.IsNaN(a) || double.IsNaN(b)) continue;
sum += (a - mean) * (b - mean);
}
result[k] = sum / denominator;
}
}
private static double[] RentValid(ReadOnlySpan<double> values, out int count)
{
var buffer = ArrayPool<double>.Shared.Rent(Math.Max(1, values.Length));
count = 0;
foreach (var v in values)
{
if (!double.IsNaN(v)) buffer[count++] = v;
}
return buffer;
}
}