refactor!: rename Titano to Chronos and move CI and releases to Gitea
CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s

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. 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) and
  pe-check.

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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-23 11:34:48 +02:00
1 parent c99842cc86
commit 5f27a86406
1799 files changed
+11728 -10668

No files matched your search

@@ -0,0 +1,121 @@
using System.Globalization;
using Chronos.Core.Mathematics;
using Chronos.Testing;
namespace Chronos.Core.Tests.Mathematics;
public sealed class LocalRegressionTests(TestContext context)
{
[Theory]
[Case(1)]
[Case(2)]
public void ReproducesPolynomialsOfItsDegreeIncludingEdges(int degree)
{
var y = Enumerable.Range(0, 60).Select(i => degree == 1 ? 3 - 0.2 * i : 1 + 0.1 * i - 0.004 * i * i).ToArray();
var result = LocalRegression.Smooth(y, window: 11, degree: degree, robustIterations: 2);
for (var i = 0; i < y.Length; i++) Assert.Approximately(y[i], result.Fitted[i], 1e-9);
Assert.True(result.SurvivingFraction.All(f => Math.Abs(f - 1) < 1e-12));
}
[Test]
public void TimeSpaceWindowsHandleUnevenSpacing()
{
var random = new Random(4);
var x = new double[80];
for (var i = 1; i < x.Length; i++) x[i] = x[i - 1] + 1 + 9 * random.NextDouble();
var y = x.Select(v => 5 + 0.01 * v).ToArray();
var result = LocalRegression.Smooth(y, window: 9, x: x);
for (var i = 0; i < y.Length; i++) Assert.Approximately(y[i], result.Fitted[i], 1e-9);
}
[Test]
public void TwentyPercentOutliersBarelyMoveTheRobustFit()
{
var random = new Random(21);
var n = 300;
var clean = Enumerable.Range(0, n).Select(i => Math.Sin(i / 40.0) + 0.02 * (random.NextDouble() - 0.5)).ToArray();
var truth = Enumerable.Range(0, n).Select(i => Math.Sin(i / 40.0)).ToArray();
var contaminated = (double[])clean.Clone();
var outliers = new HashSet<int>();
while (outliers.Count < n / 5) outliers.Add(random.Next(n));
foreach (var i in outliers) contaminated[i] += (random.NextDouble() < 0.5 ? -1 : 1) * (1 + 2 * random.NextDouble());
var reference = LocalRegression.Smooth(clean, window: 31, robustIterations: 3);
var robust = LocalRegression.Smooth(contaminated, window: 31, robustIterations: 3);
var plain = LocalRegression.Smooth(contaminated, window: 31, robustIterations: 0);
var robustShift = Enumerable.Range(0, n).Max(i => Math.Abs(robust.Fitted[i] - reference.Fitted[i]));
var plainShift = Enumerable.Range(0, n).Max(i => Math.Abs(plain.Fitted[i] - reference.Fitted[i]));
var robustError = Enumerable.Range(0, n).Max(i => Math.Abs(robust.Fitted[i] - truth[i]));
context.Log(string.Create(CultureInfo.InvariantCulture,
$"20 % outliers: robust fit moved {robustShift:F4} (error vs truth {robustError:F4}), non-robust fit moved {plainShift:F4}"));
Assert.Less(robustShift, 0.03, "robust fit moved by the outliers");
Assert.Less(robustError, 0.04);
Assert.Greater(plainShift, 10 * robustShift);
// Outliers are rejected; their windows report the lost weight.
Assert.True(outliers.All(i => robust.RobustWeights[i] < 0.05));
var inlierWeight = Enumerable.Range(0, n).Where(i => !outliers.Contains(i)).Average(i => robust.RobustWeights[i]);
Assert.Greater(inlierWeight, 0.8);
Assert.InRange(robust.SurvivingFraction.Average(), 0.6, 0.9);
}
[Test]
public void MissingSamplesAreInterpolatedAndReportedAsRejected()
{
var y = Enumerable.Range(0, 40).Select(i => 0.5 * i).ToArray();
y[0] = double.NaN;
y[10] = double.NaN;
y[11] = double.PositiveInfinity;
y[39] = double.NaN;
var result = LocalRegression.Smooth(y, window: 7);
Assert.Equal(36, result.ValidCount);
foreach (var i in new[] { 0, 10, 11, 39 })
{
Assert.Approximately(0.5 * i, result.Fitted[i], 1e-9);
Assert.Equal(0.0, result.RobustWeights[i]);
}
}
[Test]
public void PriorWeightsExcludeSamples()
{
var y = Enumerable.Range(0, 30).Select(i => (double)i).ToArray();
y[15] = 1000;
var weights = Enumerable.Repeat(1.0, 30).ToArray();
weights[15] = 0;
var result = LocalRegression.Smooth(y, window: 5, robustIterations: 0, priorWeights: weights);
Assert.Approximately(15, result.Fitted[15], 1e-9);
}
[Test]
public void DegenerateInputs()
{
Assert.True(double.IsNaN(LocalRegression.Smooth([double.NaN, double.NaN], 3).Fitted[1]));
Assert.Equal(4.0, LocalRegression.Smooth([4.0], 5).Fitted[0]);
var two = LocalRegression.Smooth([1.0, 3.0, double.NaN], 5);
Assert.Approximately(5, two.Fitted[2], 1e-12);
Assert.Throws<ArgumentOutOfRangeException>(() => LocalRegression.Smooth([1.0], 0));
Assert.Throws<ArgumentException>(() => LocalRegression.Smooth([1.0, 2.0], 3, x: [1.0, 0.0]));
}
[Test]
public void RandomInputsGiveFiniteDeterministicOutputs()
{
var random = new Random(99);
for (var trial = 0; trial < 20; trial++)
{
var n = 1 + random.Next(400);
var y = Enumerable.Range(0, n).Select(_ => random.NextDouble() < 0.15 ? double.NaN : 100 * (random.NextDouble() - 0.5)).ToArray();
if (y.All(double.IsNaN)) y[0] = 1;
var window = 1 + random.Next(60);
var degree = 1 + random.Next(2);
var a = LocalRegression.Smooth(y, window, degree, robustIterations: 3);
var b = LocalRegression.Smooth(y, window, degree, robustIterations: 3);
Assert.True(a.Fitted.All(double.IsFinite), $"trial {trial}");
Assert.True(a.SurvivingFraction.All(f => f is >= 0 and <= 1 + 1e-12));
Assert.SequenceEqual(a.Fitted, b.Fitted);
Assert.SequenceEqual(a.RobustWeights, b.RobustWeights);
}
}
}
@@ -0,0 +1,70 @@
using Chronos.Core.Imaging;
using Chronos.Core.Mathematics;
using Chronos.Testing;
namespace Chronos.Core.Tests.Mathematics;
public sealed class Matrix3Tests
{
[Test]
public void InverseAndTranspose()
{
var m = new Matrix3(2, -1, 0.5, 0.3, 4, 1, -2, 0.7, 3);
AssertClose(Matrix3.Identity, m * m.Inverse(), 1e-12);
AssertClose(Matrix3.Identity, m.Inverse() * m, 1e-12);
Assert.Equal(m, m.Transpose().Transpose());
Assert.Equal(m.M12, m.Transpose().M21);
Assert.Approximately(m.Determinant, m.Transpose().Determinant, 1e-12);
Assert.False(new Matrix3(1, 2, 3, 2, 4, 6, 0, 1, 1).TryInvert(out _));
Assert.Throws<InvalidOperationException>(() => new Matrix3(0, 0, 0, 0, 0, 0, 0, 0, 0).Inverse());
}
[Test]
public void BradfordD65ToD50MatchesLindbloom()
{
// Lindbloom's published matrix uses these tristimulus whites.
var d65 = new Vector3D(0.95047, 1.0, 1.08883);
var d50 = new Vector3D(0.96422, 1.0, 0.82521);
var expected = new Matrix3(
1.0478112, 0.0228866, -0.0501270,
0.0295424, 0.9904844, -0.0170491,
-0.0092345, 0.0150436, 0.7521316);
var adaptation = Matrix3.BradfordAdaptation(d65, d50);
AssertClose(expected, adaptation, 1e-6);
var mapped = adaptation * d65;
Assert.Approximately(d50.X, mapped.X, 1e-12);
Assert.Approximately(d50.Z, mapped.Z, 1e-12);
}
[Test]
public void Rec709MatrixMatchesLumaWeightsAndWhite()
{
var m = Matrix3.Rec709ToXyz;
Assert.Approximately(ColorSpace.LumaR, m.M21, 1e-4);
Assert.Approximately(ColorSpace.LumaG, m.M22, 1e-4);
Assert.Approximately(ColorSpace.LumaB, m.M23, 1e-4);
var white = Chromaticity.FromXyz(m * new Vector3D(1, 1, 1));
Assert.Within(0.3127, 0.3290, white.X, white.Y, 1e-12);
AssertClose(Matrix3.Identity, Matrix3.XyzToRec709 * m, 1e-12);
}
[Test]
public void ChromaticityRoundTrips()
{
var xyz = Chromaticity.D50.ToXyz(0.4);
var back = Chromaticity.FromXyz(xyz);
Assert.Within(0.3457, 0.3585, back.X, back.Y, 1e-14);
Assert.Approximately(0.4, xyz.Y, 1e-15);
var (u, v) = Chromaticity.D65.ToUv1960();
var again = Chromaticity.FromUv1960(u, v);
Assert.Within(0.3127, 0.3290, again.X, again.Y, 1e-14);
Assert.True(double.IsNaN(Chromaticity.FromXyz(new Vector3D(0, 0, 0)).X));
}
private static void AssertClose(Matrix3 expected, Matrix3 actual, double tolerance)
{
double[] e = [expected.M11, expected.M12, expected.M13, expected.M21, expected.M22, expected.M23, expected.M31, expected.M32, expected.M33];
double[] a = [actual.M11, actual.M12, actual.M13, actual.M21, actual.M22, actual.M23, actual.M31, actual.M32, actual.M33];
for (var i = 0; i < 9; i++) Assert.Approximately(e[i], a[i], tolerance, $"element {i}");
}
}
@@ -0,0 +1,111 @@
using System.Globalization;
using Chronos.Core.Mathematics;
using Chronos.Testing;
namespace Chronos.Core.Tests.Mathematics;
/// <summary>
/// Reference values are NOAA Solar Calculator results (spreadsheet equations as implemented by the
/// <c>astral</c> package, cross-checked against PyEphem/VSOP87 to within 35 s), UTC, for the local solar day.
/// </summary>
public sealed class SolarPositionTests(TestContext context)
{
private const double OneMinute = 60;
[Theory]
[Case("Greenwich summer", 51.4769, -0.0005, "2024-06-21", "03:43:13", "20:20:36", "02:54:34", "21:09:14", "01:40:14", "22:23:33", null, null)]
[Case("Greenwich winter", 51.4769, -0.0005, "2024-12-21", "08:03:42", "15:52:56", "07:22:37", "16:34:01", "06:39:40", "17:16:58", "05:58:57", "17:57:41")]
[Case("New York equinox", 40.7128, -74.0060, "2024-03-20", "10:58:42", "23:08:28", "10:30:54", "23:36:20", "09:59:06", "+00:08:13", "09:26:36", "+00:40:50")]
[Case("Sydney winter", -33.8688, 151.2093, "2024-06-21", "-21:00:18", "06:53:41", "-20:32:02", "07:21:57", "-20:00:56", "07:53:03", "-19:30:30", "08:23:28")]
[Case("Quito equinox", -0.1807, -78.4678, "2024-09-22", "11:03:17", "23:09:26", "10:42:14", "23:30:29", "10:18:21", "23:54:22", "09:54:23", "+00:18:19")]
[Case("Tromso March", 69.6492, 18.9553, "2024-03-01", "06:08:32", "15:46:01", "05:06:36", "16:48:12", "03:57:47", "17:57:27", "02:44:21", "19:11:43")]
// The sun grazes −6° here, so tiny ephemeris differences move the crossing by minutes: astral's single-pass
// NOAA value is 77 s early, while the iterated NOAA solution and PyEphem agree on 08:31:31 / 12:53:21.
[Case("Tromso polar night", 69.6492, 18.9553, "2024-12-21", null, null, "08:31:31", "12:53:21", "06:46:35", "14:38:21", "05:28:22", "15:56:34")]
[Case("Tromso midnight sun", 69.6492, 18.9553, "2024-06-21", null, null, null, null, null, null, null, null)]
[Case("Golden NREL SPA site", 39.742476, -105.1786, "2003-10-17", "13:12:57", "+00:18:36", "12:45:10", "+00:46:21", "12:13:59", "+01:17:30", "11:42:47", "+01:48:39")]
public void EventsMatchNoaaWithinOneMinute(string place, double latitude, double longitude, string date,
string? sunrise, string? sunset, string? civilDawn, string? civilDusk, string? nauticalDawn, string? nauticalDusk, string? astroDawn, string? astroDusk)
{
var day = DateOnly.ParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture);
var events = SolarPosition.Events(day, latitude, longitude);
double[] deviations =
[
Check(place + " sunrise", day, sunrise, events.Sunrise),
Check(place + " sunset", day, sunset, events.Sunset),
Check(place + " civil dawn", day, civilDawn, events.CivilDawn),
Check(place + " civil dusk", day, civilDusk, events.CivilDusk),
Check(place + " nautical dawn", day, nauticalDawn, events.NauticalDawn),
Check(place + " nautical dusk", day, nauticalDusk, events.NauticalDusk),
Check(place + " astronomical dawn", day, astroDawn, events.AstronomicalDawn),
Check(place + " astronomical dusk", day, astroDusk, events.AstronomicalDusk),
];
context.Log(string.Create(CultureInfo.InvariantCulture, $"{place}: worst deviation {deviations.Max():F1} s"));
}
[Theory]
[Case(51.4769, -0.0005, "2024-06-21", "12:01:49")]
[Case(-33.8688, 151.2093, "2024-06-21", "01:56:58")]
[Case(39.742476, -105.1786, "2003-10-17", "18:46:14")]
public void SolarNoonMatchesNoaa(double latitude, double longitude, string date, string noon)
{
_ = latitude;
var day = DateOnly.ParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Check("noon", day, noon, SolarPosition.SolarNoon(day, longitude));
}
[Theory]
[Case(39.742476, -105.1786, "2003-10-17T19:30:30", 39.8914, 39.8721, 194.3426)]
[Case(51.4769, -0.0005, "2024-06-21T12:00:00", 61.9665, 61.9579, 179.0598)]
[Case(-33.8688, 151.2093, "2024-01-15T06:30:00", 30.7712, 30.7442, 263.8208)]
[Case(35.6762, 139.6503, "2024-09-01T21:00:00", 8.4899, 8.3861, 86.3181)]
[Case(64.1466, -21.9426, "2024-12-01T15:00:00", 1.9248, 1.6140, 203.7679)]
public void PositionMatchesNoaa(double latitude, double longitude, string utc, double elevation, double geometric, double azimuth)
{
var time = DateTime.SpecifyKind(DateTime.ParseExact(utc, "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture), DateTimeKind.Utc);
var sun = SolarPosition.Compute(time, latitude, longitude);
Assert.Approximately(geometric, sun.GeometricElevation, 0.01);
Assert.Approximately(elevation, sun.Elevation, 0.01);
Assert.Approximately(azimuth, sun.Azimuth, 0.01);
}
[Theory]
[Case(10.0, DayPhase.Day)]
[Case(3.0, DayPhase.GoldenHour)]
[Case(-0.5, DayPhase.GoldenHour)]
[Case(-3.0, DayPhase.CivilTwilight)]
[Case(-8.0, DayPhase.NauticalTwilight)]
[Case(-15.0, DayPhase.AstronomicalTwilight)]
[Case(-30.0, DayPhase.Night)]
public void ClassifiesElevation(double elevation, DayPhase expected) => Assert.Equal(expected, SolarPosition.Classify(elevation));
[Test]
public void PhaseFollowsTheEvents()
{
var day = new DateOnly(2024, 12, 21);
var events = SolarPosition.Events(day, 51.4769, -0.0005);
Assert.Equal(DayPhase.Day, SolarPosition.Phase(events.SolarNoon, 51.4769, -0.0005));
Assert.Equal(DayPhase.GoldenHour, SolarPosition.Phase(events.Sunset!.Value.AddMinutes(-5), 51.4769, -0.0005));
Assert.Equal(DayPhase.CivilTwilight, SolarPosition.Phase(events.Sunset!.Value.AddMinutes(5), 51.4769, -0.0005));
Assert.Equal(DayPhase.Night, SolarPosition.Phase(events.AstronomicalDusk!.Value.AddMinutes(5), 51.4769, -0.0005));
Assert.Throws<ArgumentOutOfRangeException>(() => SolarPosition.Compute(DateTime.UtcNow, 91, 0));
}
/// <summary>Expected "HH:mm:ss" on <paramref name="day"/>; a leading '-' or '+' means the previous or next UTC day.
/// Returns the absolute deviation in seconds (0 when the event is correctly absent).</summary>
private static double Check(string label, DateOnly day, string? expected, DateTime? actual)
{
if (expected is null)
{
Assert.Null(actual);
return 0;
}
var offsetDays = expected[0] switch { '-' => -1, '+' => 1, _ => 0 };
var clock = TimeOnly.ParseExact(expected.TrimStart('+', '-'), "HH:mm:ss", CultureInfo.InvariantCulture);
var reference = day.AddDays(offsetDays).ToDateTime(clock, DateTimeKind.Utc);
var value = Assert.NotNull(actual, label);
var deviation = (value - reference).TotalSeconds;
Assert.Approximately(0, deviation, OneMinute, label);
return Math.Abs(deviation);
}
}
@@ -0,0 +1,202 @@
using Chronos.Core.Mathematics;
using Chronos.Testing;
namespace Chronos.Core.Tests.Mathematics;
public sealed class SplineTests
{
// Monotone data with a plateau and a sharp rise: the classic overshoot trap for C² splines.
private static readonly double[] StepX = [0, 1, 2, 3, 4, 5, 6];
private static readonly double[] StepY = [0, 0, 0, 1, 1, 1, 1];
[Test]
public void MonotoneSplineInterpolatesKnots()
{
var spline = new MonotoneSpline(StepX, StepY);
for (var i = 0; i < StepX.Length; i++) Assert.Equal(StepY[i], spline.Evaluate(StepX[i]));
Assert.Equal(0.0, spline.Evaluate(-5));
Assert.Equal(1.0, spline.Evaluate(50));
}
[Test]
public void MonotoneSplineNeverOvershootsWhileNaturalSplineDoes()
{
var monotone = new MonotoneSpline(StepX, StepY);
var natural = new NaturalCubicSpline(StepX, StepY);
var samples = Enumerable.Range(0, 601).Select(i => monotone.Evaluate(i / 100.0)).ToList();
Assert.Monotonic(samples);
Assert.InRange(samples.Min(), 0, 0);
Assert.InRange(samples.Max(), 1, 1);
var naturalMax = Enumerable.Range(0, 601).Max(i => natural.Evaluate(i / 100.0));
Assert.Greater(naturalMax, 1.01);
}
[Test]
public void MonotoneSplineOnRandomMonotoneDataIsMonotoneAndBounded()
{
var random = new Random(5);
for (var trial = 0; trial < 50; trial++)
{
var n = 2 + random.Next(20);
var x = new double[n];
var y = new double[n];
for (var i = 1; i < n; i++)
{
x[i] = x[i - 1] + 0.01 + random.NextDouble() * 3;
y[i] = y[i - 1] + (random.NextDouble() < 0.3 ? 0 : random.NextDouble() * random.NextDouble() * 10);
}
var spline = new MonotoneSpline(x, y);
Assert.True(spline.IsMonotone);
var values = Enumerable.Range(0, 400).Select(i => spline.Evaluate(x[^1] * i / 399.0)).ToList();
Assert.True(values.All(double.IsFinite));
Assert.Monotonic(values, message: $"trial {trial}");
for (var k = 0; k < n - 1; k++)
{
var mid = spline.Evaluate(0.5 * (x[k] + x[k + 1]));
Assert.InRange(mid, y[k], y[k + 1], $"interval {k} of trial {trial}");
}
}
}
[Test]
public void MonotoneSplineDerivativeMatchesFiniteDifference()
{
double[] x = [0, 0.5, 2, 3, 5];
double[] y = [1, 1.5, 2.2, 4, 4.5];
var spline = new MonotoneSpline(x, y);
foreach (var at in new[] { 0.2, 0.9, 2.5, 4.1 })
{
const double h = 1e-6;
var numeric = (spline.Evaluate(at + h) - spline.Evaluate(at - h)) / (2 * h);
Assert.Approximately(numeric, spline.Derivative(at), 1e-6);
}
}
[Test]
public void MonotoneSplineInverseRoundTrips()
{
double[] x = [0, 1, 2.5, 4, 6];
double[] y = [10, 8, 8, 3, -1];
var spline = new MonotoneSpline(x, y);
for (var i = 0; i <= 120; i++)
{
var at = i * 0.05;
var value = spline.Evaluate(at);
var back = spline.Inverse(value);
Assert.Approximately(value, spline.Evaluate(back), 1e-10);
}
Assert.Equal(1.0, spline.Inverse(8));
Assert.Equal(0.0, spline.Inverse(99));
Assert.Equal(6.0, spline.Inverse(-99));
Assert.Throws<InvalidOperationException>(() => new MonotoneSpline([0, 1, 2], [0, 1, 0]).Inverse(0.5));
}
[Test]
public void SplinesRejectInvalidKnots()
{
Assert.Throws<ArgumentException>(() => new MonotoneSpline([0, 0], [1, 2]));
Assert.Throws<ArgumentException>(() => new NaturalCubicSpline([0, 1], [1, double.NaN]));
Assert.Throws<ArgumentException>(() => new MonotoneSpline([], []));
}
[Test]
public void NaturalSplineReproducesLinesAndHasFreeEnds()
{
double[] x = [0, 1, 3, 4, 7];
var line = new NaturalCubicSpline(x, x.Select(v => 2 - 0.5 * v).ToArray());
foreach (var at in new[] { -2.0, 0.3, 2.2, 6.9, 9 }) Assert.Approximately(2 - 0.5 * at, line.Evaluate(at), 1e-12);
var sine = new NaturalCubicSpline(Enumerable.Range(0, 21).Select(i => i * Math.PI / 10).ToArray(),
Enumerable.Range(0, 21).Select(i => Math.Sin(i * Math.PI / 10)).ToArray());
Assert.Approximately(0, sine.SecondDerivative(1e-9), 1e-6);
for (var i = 0; i < 100; i++)
{
var at = 0.3 + i * 0.055;
Assert.Approximately(Math.Sin(at), sine.Evaluate(at), 2e-4);
Assert.Approximately(Math.Cos(at), sine.Derivative(at), 5e-3);
}
}
[Test]
public void CatmullRomPassesThroughControlPoints()
{
Point2[] points = [new(0, 0), new(1, 2), new(3, 3), new(4, 1), new(6, 0)];
foreach (var kind in Enum.GetValues<CatmullRomParameterization>())
{
for (var i = 0; i < points.Length; i++)
{
var p = CatmullRom.Evaluate(points, i, kind);
Assert.Within(points[i].X, points[i].Y, p.X, p.Y, 1e-12);
}
}
}
[Test]
public void UniformScalarCatmullRomMatchesClosedForm()
{
double[] v = [1, 4, 2, 5, 3];
for (var i = 0; i <= 40; i++)
{
var t = 1 + i * 0.025;
var u = t - 1;
double p0 = v[0], p1 = v[1], p2 = v[2], p3 = v[3];
var expected = 0.5 * (2 * p1 + (-p0 + p2) * u + (2 * p0 - 5 * p1 + 4 * p2 - p3) * u * u + (-p0 + 3 * p1 - 3 * p2 + p3) * u * u * u);
Assert.Approximately(expected, CatmullRom.Evaluate(v, t), 1e-12);
}
}
[Test]
public void CentripetalCatmullRomDoesNotBacktrackOnUnevenSpacing()
{
// Collinear points with a very short middle segment: the uniform spline overshoots past 10.1 and
// turns back; the centripetal one stays monotone along the line.
Point2[] points = [new(0, 0), new(10, 0), new(10.1, 0), new(20, 0)];
double MaxX(CatmullRomParameterization kind) => Enumerable.Range(0, 101).Max(i => CatmullRom.Evaluate(points, 1 + i / 100.0, kind).X);
Assert.Greater(MaxX(CatmullRomParameterization.Uniform), 10.15);
var centripetal = Enumerable.Range(0, 101).Select(i => CatmullRom.Evaluate(points, 1 + i / 100.0, CatmullRomParameterization.Centripetal).X).ToList();
Assert.Monotonic(centripetal);
Assert.LessOrEqual(centripetal.Max(), 10.1 + 1e-12);
}
[Test]
public void BezierEndpointsAndDerivative()
{
var curve = new CubicBezier(new(0, 0), new(1, 2), new(3, 2), new(4, 0));
Assert.Equal(new Point2(0, 0), curve.Evaluate(0));
Assert.Equal(new Point2(4, 0), curve.Evaluate(1));
var d0 = curve.Derivative(0);
Assert.Within(3, 6, d0.X, d0.Y, 1e-12);
var mid = curve.Evaluate(0.5);
Assert.Within(2, 1.5, mid.X, mid.Y, 1e-12);
}
[Theory]
[Case("ease", 0.5, 0.802403387585)]
[Case("ease-in", 0.5, 0.315356812573)]
[Case("ease-out", 0.25, 0.378138130825)]
[Case("ease-in-out", 0.5, 0.5)]
[Case("linear", 0.37, 0.37)]
public void CssEasingMatchesReference(string name, double x, double expected)
{
var easing = name switch
{
"ease" => CubicBezierEasing.Ease,
"ease-in" => CubicBezierEasing.EaseIn,
"ease-out" => CubicBezierEasing.EaseOut,
"ease-in-out" => CubicBezierEasing.EaseInOut,
_ => CubicBezierEasing.Linear,
};
Assert.Approximately(expected, easing.Evaluate(x), 1e-9);
}
[Test]
public void EasingIsMonotoneAndClamped()
{
var easing = new CubicBezierEasing(0.9, -0.2, 0.1, 1.2);
Assert.Equal(0.0, easing.Evaluate(-1));
Assert.Equal(1.0, easing.Evaluate(2));
var ts = Enumerable.Range(0, 201).Select(i => easing.SolveT(i / 200.0)).ToList();
Assert.Monotonic(ts);
Assert.Throws<ArgumentOutOfRangeException>(() => new CubicBezierEasing(1.5, 0, 0.5, 1));
}
}
@@ -0,0 +1,136 @@
using Chronos.Core.Mathematics;
using Chronos.Testing;
namespace Chronos.Core.Tests.Mathematics;
public sealed class StatisticsTests
{
[Test]
public void SelectMatchesSortedOrderOnRandomInput()
{
var random = new Random(7);
for (var trial = 0; trial < 200; trial++)
{
var n = 1 + random.Next(300);
// Few distinct values exercise the equal-to-pivot path.
var values = Enumerable.Range(0, n).Select(_ => (double)random.Next(trial % 2 == 0 ? 5 : 1000)).ToArray();
var sorted = values.OrderBy(v => v).ToArray();
var k = random.Next(n);
var work = (double[])values.Clone();
Assert.Equal(sorted[k], Statistics.Select(work, k));
for (var i = 0; i < k; i++) Assert.True(work[i] <= work[k]);
for (var i = k + 1; i < n; i++) Assert.True(work[i] >= work[k]);
}
}
[Test]
public void MedianHandlesOddEvenAndNaN()
{
Assert.Equal(3.0, Statistics.Median([5, 1, 3, double.NaN, 4, 2]));
Assert.Equal(2.5, Statistics.Median([4, 1, 3, 2]));
Assert.True(double.IsNaN(Statistics.Median([double.NaN])));
Assert.True(double.IsNaN(Statistics.Median([])));
}
[Test]
public void MadAndTrimmedMean()
{
double[] values = [1, 2, 3, 4, 100];
Assert.Equal(1.0, Statistics.MedianAbsoluteDeviation(values));
Assert.Equal(3.0, Statistics.MedianAbsoluteDeviation(values, 0));
// 20 % trimmed each side of 1..10 keeps 3..8.
var oneToTen = Enumerable.Range(1, 10).Select(i => (double)i).ToArray();
Assert.Approximately(5.5, Statistics.TrimmedMean(oneToTen, 0.2, 0.2), 1e-12);
Assert.Approximately(2.5, Statistics.TrimmedMean([1, 2, 3, 4, 1000], 0, 0.2), 1e-12);
Assert.Throws<ArgumentOutOfRangeException>(() => Statistics.TrimmedMean(values, 0.6, 0.4));
}
[Theory]
[Case(0.0, 1.0)]
[Case(0.25, 1.75)]
[Case(0.5, 2.5)]
[Case(1.0, 4.0)]
public void PercentileIsTypeSeven(double p, double expected) =>
Assert.Approximately(expected, Statistics.Percentile([4, 2, 1, 3], p), 1e-12);
[Test]
public void WeightedPercentileWithEqualWeightsIsHazen()
{
double[] v = [10, 20, 30, 40];
double[] w = [1, 1, 1, 1];
Assert.Approximately(25, Statistics.WeightedPercentile(v, w, 0.5), 1e-12);
Assert.Approximately(10, Statistics.WeightedPercentile(v, w, 0.1), 1e-12);
Assert.Approximately(40, Statistics.WeightedPercentile(v, w, 0.95), 1e-12);
// A heavy weight drags the median towards its value: centres 0.5, 1.5, 2.5, 8 of 13 → 30 + 10·4/5.5.
Assert.Approximately(30 + 40 / 5.5, Statistics.WeightedPercentile(v, [1, 1, 1, 10], 0.5), 1e-12);
Assert.Approximately(40, Statistics.WeightedPercentile(v, [1, 1, 1, 10], 0.7), 1e-12);
}
[Test]
public void HistogramPercentileAndDistance()
{
var bins = new double[10];
var values = Enumerable.Range(0, 1000).Select(i => i / 100.0).ToArray();
Statistics.AccumulateHistogram(values, 0, 10, bins);
Assert.True(bins.All(b => b == 100));
Assert.Approximately(5.0, Statistics.HistogramPercentile(bins, 0, 10, 0.5), 1e-12);
Assert.Approximately(0.0, Statistics.ChiSquareDistance(bins, bins), 1e-15);
Assert.Approximately(1.0, Statistics.ChiSquareDistance([1, 0], [0, 3]), 1e-15);
}
[Test]
public void RobustLineIgnoresTwentyPercentOutliers()
{
var random = new Random(3);
var n = 200;
var x = new double[n];
var y = new double[n];
for (var i = 0; i < n; i++)
{
x[i] = i * 0.5;
y[i] = 2.0 + 0.75 * x[i] + 0.05 * (random.NextDouble() - 0.5);
if (i % 5 == 0) y[i] += 20 + 10 * random.NextDouble();
}
var fit = Statistics.RobustLinearFit(x, y);
Assert.Approximately(0.75, fit.Slope, 0.002);
Assert.Approximately(2.0, fit.Intercept, 0.05);
Assert.Less(fit.Scale, 0.05);
}
[Test]
public void AutocorrelationPeaksAtThePeriod()
{
var series = Enumerable.Range(0, 240).Select(i => Math.Sin(2 * Math.PI * i / 12)).ToArray();
var r = new double[40];
Statistics.Autocorrelation(series, r);
Assert.Equal(1.0, r[0]);
Assert.Less(r[6], -0.9);
Assert.Greater(r[12], 0.9);
Assert.True(r[12] > r[11] && r[12] > r[13]);
Statistics.Autocorrelation([2, 2, 2, double.NaN, 2], r);
Assert.Equal(1.0, r[0]);
Assert.True(r.Skip(1).All(v => v == 0));
}
[Test]
public void RandomInputsAreDeterministicAndFinite()
{
var random = new Random(11);
var values = Enumerable.Range(0, 501).Select(_ => random.NextDouble() < 0.1 ? double.NaN : random.NextDouble() * 10 - 5).ToArray();
double Run() => Statistics.Median(values) + Statistics.MedianAbsoluteDeviation(values) + Statistics.TrimmedMean(values, 0.02, 0.02)
+ Statistics.Percentile(values, 0.9) + Statistics.Mean(values) + Statistics.StandardDeviation(values) + Statistics.Rms(values);
var first = Run();
Assert.True(double.IsFinite(first));
Assert.Equal(first, Run());
}
[Test]
public void MomentsOfAKnownSet()
{
double[] values = [2, 4, double.NaN, 4, 4, 5, 5, 7, 9];
Assert.Approximately(5, Statistics.Mean(values), 1e-12);
Assert.Approximately(Math.Sqrt(32.0 / 7), Statistics.StandardDeviation(values), 1e-12);
Assert.Approximately(Math.Sqrt(232.0 / 8), Statistics.Rms(values), 1e-12);
}
}