merge: analysis modules and math

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 09:57:39 +00:00
commit 506ead9bc2
42 files changed
+5963

No files matched your search

@@ -0,0 +1,59 @@
using Titano.Core.Analysis;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Core.Imaging;
namespace Titano.Core.Tests.Analysis;
/// <summary>Shared measurement helpers for the analysis tests.</summary>
internal static class AnalysisFixtures
{
/// <summary>Trimmed-mean log2 luminance of every frame, optionally after applying a per-frame correction.</summary>
public static double[] MeasureSeries(SyntheticSequence sequence, Func<int, ImageBuffer, ImageBuffer>? transform = null, float[]? mask = null)
{
var result = new double[sequence.Count];
Parallel.For(0, sequence.Count, new ParallelOptions { MaxDegreeOfParallelism = 2 }, i =>
{
using var image = sequence.Render(i);
var measured = transform is null ? image : transform(i, image);
result[i] = FrameStatistics.MeasureLogLuminance(measured, mask);
});
return result;
}
/// <summary>RMS of the frame-to-frame change of (series − truth): flicker relative to the true curve, free of
/// any constant offset.</summary>
public static double FrameToFrameResidualRms(IReadOnlyList<double> series, IReadOnlyList<double> truth)
{
double sum = 0;
for (var i = 1; i < series.Count; i++)
{
var d = series[i] - series[i - 1] - (truth[i] - truth[i - 1]);
sum += d * d;
}
return Math.Sqrt(sum / (series.Count - 1));
}
/// <summary>Largest |series − truth − c| where c is the mean offset (the measurement constant).</summary>
public static double MaxDeviation(IReadOnlyList<double> series, IReadOnlyList<double> truth)
{
var offset = 0.0;
for (var i = 0; i < series.Count; i++) offset += series[i] - truth[i];
offset /= series.Count;
var max = 0.0;
for (var i = 0; i < series.Count; i++) max = Math.Max(max, Math.Abs(series[i] - truth[i] - offset));
return max;
}
/// <summary>Land pixels at least <paramref name="margin"/> rows below the true horizon (weight 1), else 0.</summary>
public static float[] TrueLandMask(SyntheticSequence sequence, double margin = 2)
{
var o = sequence.Options;
var mask = new float[o.Width * o.Height];
for (var y = 0; y < o.Height; y++)
{
for (var x = 0; x < o.Width; x++)
mask[y * o.Width + x] = y + 0.5 > sequence.HorizonRow(x + 0.5) + margin ? 1 : 0;
}
return mask;
}
}
@@ -0,0 +1,93 @@
using Titano.Core.Analysis;
using Titano.Testing;
namespace Titano.Core.Tests.Analysis;
/// <summary>Seeded random inputs: outputs stay finite where defined and repeat exactly.</summary>
public sealed class AnalysisPropertyTests
{
private static double[] RandomSeries(Random random, int n, double missing)
{
var level = 0.0;
var series = new double[n];
for (var i = 0; i < n; i++)
{
level += 0.05 * (random.NextDouble() - 0.5);
series[i] = random.NextDouble() < missing ? double.NaN : level + 0.3 * (random.NextDouble() - 0.5) + (random.NextDouble() < 0.03 ? 4 : 0);
}
return series;
}
[Test]
public void DeflickerHolyGrailAndSpectrumAreFiniteAndDeterministic()
{
var random = new Random(1234);
for (var trial = 0; trial < 25; trial++)
{
var n = 2 + random.Next(300);
var series = RandomSeries(random, n, missing: 0.1);
if (series.All(double.IsNaN)) series[0] = 0;
var ev = new double?[n];
double camera = 12;
for (var i = 0; i < n; i++)
{
if (random.NextDouble() < 0.05) camera -= Math.Round(random.NextDouble() * 6 - 3) / 3;
ev[i] = random.NextDouble() < 0.05 ? null : camera;
}
var options = new DeflickerOptions { Window = 3 + random.Next(40), Degree = 1 + random.Next(2), Strength = random.NextDouble() };
var a = DeflickerEngine.Compute(series, options);
var b = DeflickerEngine.Compute(series, options);
Assert.True(a.Target.All(double.IsFinite) && a.CorrectionEv.All(double.IsFinite), $"deflicker trial {trial}");
Assert.SequenceEqual(a.Target, b.Target);
var grail = HolyGrailEngine.Compute(series, ev, new HolyGrailOptions { Deflicker = options });
Assert.True(grail.Target.All(double.IsFinite) && grail.CorrectionEv.All(double.IsFinite), $"holy grail trial {trial}");
Assert.SequenceEqual(grail.Target, HolyGrailEngine.Compute(series, ev, new HolyGrailOptions { Deflicker = options }).Target);
var spectrum = FlickerSpectrum.Analyze(series);
Assert.True(spectrum.Autocorrelation.All(double.IsFinite));
Assert.Equal(1, spectrum.RecommendedWindow % 2);
var region = RegionDeflicker.Compute(series, RandomSeries(random, n, 0.2), options);
Assert.True(region.Land.CorrectionEv.All(double.IsFinite));
}
}
[Test]
public void WhiteBalanceAndLightAnalysisSurviveRandomMetadata()
{
var random = new Random(77);
for (var trial = 0; trial < 20; trial++)
{
var n = 1 + random.Next(200);
double Channel() => random.NextDouble() < 0.05 ? 0 : 0.01 + random.NextDouble();
var red = Enumerable.Range(0, n).Select(_ => Channel()).ToArray();
var green = Enumerable.Range(0, n).Select(_ => Channel()).ToArray();
var blue = Enumerable.Range(0, n).Select(_ => Channel()).ToArray();
var wb = WhiteBalanceSmoother.Smooth(red, green, blue, window: 1 + random.Next(40));
Assert.True(wb.Gains.All(g => double.IsFinite(g.Red) && g.Red > 0 && double.IsFinite(g.Blue) && g.Blue > 0), $"wb trial {trial}");
var start = new DateTime(2024, 1, 1);
var frames = Enumerable.Range(0, n).Select(i => new LightFrame
{
Index = i,
CapturedAt = random.NextDouble() < 0.05 ? null : start.AddSeconds(i * 7 + random.Next(-20, 20) + (random.NextDouble() < 0.02 ? 9000 : 0)),
ExposureTime = random.NextDouble() < 0.05 ? null : 1.0 / (1 + random.Next(3)),
FNumber = 2.8,
Iso = random.NextDouble() < 0.5 ? 100 : null,
Width = 100 + random.Next(2),
Height = 80,
Orientation = random.NextDouble() < 0.05 ? 6 : 1,
Latitude = random.NextDouble() < 0.5 ? -60 + 120 * random.NextDouble() : null,
Longitude = 170 * (random.NextDouble() - 0.5),
}).ToList();
var first = LightAnalyzer.Analyze(frames);
var second = LightAnalyzer.Analyze(frames);
Assert.SequenceEqual(first.Intervals, second.Intervals);
Assert.SequenceEqual(first.Findings.Select(f => f.Key), second.Findings.Select(f => f.Key));
Assert.Equal(n, first.Sessions.Sum(s => s.FrameCount));
Assert.True(first.CaptureSpan >= TimeSpan.Zero);
}
}
}
@@ -0,0 +1,96 @@
using System.Globalization;
using Titano.Core.Analysis;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Testing;
namespace Titano.Core.Tests.Analysis;
public sealed class DeflickerEngineTests(TestContext context)
{
/// <summary>BRIEF §20.4: flicker reduction ≥ 60 % on the synthetic ramp with the ramp preserved within 0.05 EV,
/// measured end to end (measure → target curve → apply gains → re-measure).</summary>
[Test]
public void RampSequenceMeetsTheRegressionGate()
{
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
{
FrameCount = 200,
Seed = 3,
StartEv = -2,
EndEv = 1,
FlickerEv = 0.1,
});
var measured = AnalysisFixtures.MeasureSeries(sequence);
var result = DeflickerEngine.Compute(measured, new DeflickerOptions { Window = 21 });
var corrected = AnalysisFixtures.MeasureSeries(sequence, (i, image) =>
{
ExposureProcessor.Apply(image, result.CorrectionEv[i]);
return image;
});
var before = AnalysisFixtures.FrameToFrameResidualRms(measured, sequence.SceneEv);
var after = AnalysisFixtures.FrameToFrameResidualRms(corrected, sequence.SceneEv);
var reduction = 1 - after / before;
var rampError = AnalysisFixtures.MaxDeviation(corrected, sequence.SceneEv);
context.Log(string.Create(CultureInfo.InvariantCulture,
$"flicker before {before:F4} EV, after {after:F4} EV, reduction {reduction:P1}, max ramp deviation {rampError:F4} EV, diagnostics {result.Diagnostics}"));
Assert.GreaterOrEqual(reduction, 0.60);
Assert.LessOrEqual(rampError, 0.05);
Assert.Approximately(after, result.Diagnostics.FlickerAfter, 0.01);
Assert.Approximately(before, result.Diagnostics.FlickerBefore, 0.02);
}
[Test]
public void IntentionalOffsetsAreNotTreatedAsFlicker()
{
var n = 120;
var ramp = Enumerable.Range(0, n).Select(i => -0.01 * i).ToArray();
var offsets = Enumerable.Range(0, n).Select(i => i >= 60 ? 1.0 : 0.0).ToArray();
var measured = ramp.Select((v, i) => v + offsets[i]).ToArray();
var withOffsets = DeflickerEngine.Compute(measured, intentionalOffsets: offsets);
for (var i = 0; i < n; i++) Assert.Approximately(measured[i], withOffsets.Target[i], 1e-9);
// Without them the step is smeared into a ramp over the window.
var naive = DeflickerEngine.Compute(measured);
Assert.Greater(Math.Abs(naive.CorrectionEv[59]), 0.2);
}
[Test]
public void OutliersArePulledOntoTheFitAndStrengthBlendsTheRest()
{
var random = new Random(8);
var n = 150;
var truth = Enumerable.Range(0, n).Select(i => 0.02 * i).ToArray();
var measured = truth.Select(v => v + 0.05 * (2 * random.NextDouble() - 1)).ToArray();
measured[70] += 2.5;
var half = DeflickerEngine.Compute(measured, new DeflickerOptions { Strength = 0.5 });
Assert.Less(half.RobustWeights[70], 0.01);
Assert.Approximately(truth[70], half.Target[70], 0.05);
Assert.Equal(1, half.Diagnostics.OutlierCount);
// An inlier keeps about half of its own deviation from the fit.
var inlier = Enumerable.Range(0, n).First(i => i is > 10 and < 140 && Math.Abs(measured[i] - half.Fitted[i]) > 0.02 && half.RobustWeights[i] > 0.8);
var kept = (half.Target[inlier] - half.Fitted[inlier]) / (measured[inlier] - half.Fitted[inlier]);
Assert.InRange(kept, 0.5 * half.RobustWeights[inlier] * half.SurvivingFraction[inlier] - 1e-9, 0.5 + 1e-9);
Assert.Greater(kept, 0.35);
}
[Test]
public void UnusableFramesGetTargetsButNoCorrection()
{
var measured = Enumerable.Range(0, 40).Select(i => 0.1 * i).ToArray();
measured[12] = double.NaN;
var result = DeflickerEngine.Compute(measured, new DeflickerOptions { Window = 9 });
Assert.Approximately(1.2, result.Target[12], 1e-9);
Assert.Equal(0.0, result.CorrectionEv[12]);
Assert.Throws<ArgumentOutOfRangeException>(() => DeflickerEngine.Compute(measured, new DeflickerOptions { Strength = 2 }));
}
[Test]
public void OffsetsFromExposureFollowMetadata()
{
double?[] ev = [null, 12, 12, 11.5, null, 13];
var offsets = DeflickerEngine.OffsetsFromExposure(ev);
Assert.SequenceEqual([0.0, 0, 0, 0.5, 0.5, -1], offsets);
}
}
@@ -0,0 +1,116 @@
using Titano.Core.Analysis;
using Titano.Core.Imaging;
using Titano.Testing;
namespace Titano.Core.Tests.Analysis;
public sealed class ExposureProcessorTests
{
// 37 × 5 = 185 pixels: not a multiple of any vector width, so the scalar tail runs too.
private static ImageBuffer Ramp(int width = 37, int height = 5, int channels = 3)
{
var image = new ImageBuffer(width, height, channels);
var data = image.Data;
for (var i = 0; i < data.Length; i++) data[i] = 0.001f * (i % 997);
return image;
}
[Test]
public void EvAndChannelGainsMultiply()
{
using var image = Ramp();
using var original = image.Clone();
ExposureProcessor.Apply(image, 1, new ChannelGains(1.5, 1, 0.5));
float[] factors = [3, 2, 1];
for (var c = 0; c < 3; c++)
{
for (var i = 0; i < image.PlaneLength; i++)
Assert.Approximately(factors[c] * original.Plane(c)[i], image.Plane(c)[i], 1e-6);
}
Assert.Throws<ArgumentOutOfRangeException>(() => ExposureProcessor.Apply(image, double.NaN));
Assert.Throws<ArgumentOutOfRangeException>(() => ExposureProcessor.Apply(image, 0, new ChannelGains(0, 1, 1)));
}
[Test]
public void SingleChannelAndAlphaAreHandled()
{
using var grey = Ramp(channels: 1);
using var greyOriginal = grey.Clone();
ExposureProcessor.Apply(grey, -1, new ChannelGains(4, 4, 4));
Assert.Approximately(0.5 * greyOriginal.Plane(0)[100], grey.Plane(0)[100], 1e-7);
using var rgba = Ramp(channels: 4);
using var rgbaOriginal = rgba.Clone();
ExposureProcessor.Apply(rgba, 2);
Assert.SequenceEqual(rgbaOriginal.Plane(3).ToArray(), rgba.Plane(3).ToArray());
Assert.Approximately(4 * rgbaOriginal.Plane(2)[50], rgba.Plane(2)[50], 1e-6);
}
[Test]
public void RegionGainsBlendThroughTheMask()
{
using var image = new ImageBuffer(37, 5, 3);
image.Data.Fill(0.1f);
var mask = new float[image.PlaneLength];
for (var i = 0; i < mask.Length; i++) mask[i] = (i % 3) * 0.5f;
ExposureProcessor.ApplyRegion(image, mask, skyEv: 1, landEv: -1);
for (var i = 0; i < mask.Length; i++)
{
var expected = 0.1 * (0.5 + mask[i] * (2 - 0.5));
Assert.Approximately(expected, image.Plane(1)[i], 1e-7);
}
Assert.Throws<ArgumentException>(() => ExposureProcessor.ApplyRegion(image, new float[3], 0, 0));
}
[Test]
public void SoftClipIsSmoothBoundedAndKeepsHue()
{
const float knee = 0.8f;
Assert.Equal(0.5f, ExposureProcessor.SoftClip(0.5f, knee));
Assert.Approximately(knee, ExposureProcessor.SoftClip(knee + 1e-6f, knee), 1e-5);
var values = Enumerable.Range(0, 400).Select(i => (double)ExposureProcessor.SoftClip(i * 0.05f, knee)).ToList();
Assert.Monotonic(values);
Assert.Less(values.Max(), 1);
// Slope 1 at the knee (C¹): the secant over h above it is 1 / (1 + h / (1 − knee)).
var slope = (ExposureProcessor.SoftClip(knee + 1e-3f, knee) - knee) / 1e-3f;
Assert.Approximately(1 / (1 + 1e-3 / (1 - knee)), slope, 1e-3);
using var image = new ImageBuffer(37, 5, 3);
for (var i = 0; i < image.PlaneLength; i++)
{
image.Plane(0)[i] = 0.02f * i;
image.Plane(1)[i] = 0.01f * i;
image.Plane(2)[i] = 0.005f * i;
}
ExposureProcessor.Apply(image, 0, softClipKnee: knee);
for (var i = 1; i < image.PlaneLength; i++)
{
var r = image.Plane(0)[i];
Assert.LessOrEqual(r, 1);
Assert.Approximately(2, r / image.Plane(1)[i], 1e-4);
Assert.Approximately(2, image.Plane(1)[i] / image.Plane(2)[i], 1e-4);
Assert.Approximately(ExposureProcessor.SoftClip(0.02f * i, knee), r, 1e-5);
}
}
[Test]
public void LargeImagesTakeTheParallelPathWithTheSameResult()
{
using var image = new ImageBuffer(1100, 1000, 3);
var data = image.Data;
for (var i = 0; i < data.Length; i++) data[i] = (i % 1000) * 0.0012f;
using var expected = image.Clone();
ExposureProcessor.Apply(image, 0.5, softClipKnee: 0.9);
var gain = (float)Math.Pow(2, 0.5);
foreach (var index in new[] { 0, 12345, 777_777, 1_099_999 })
{
var r = expected.Plane(0)[index] * gain;
var g = expected.Plane(1)[index] * gain;
var b = expected.Plane(2)[index] * gain;
var m = Math.Max(r, Math.Max(g, b));
var s = m > 0.9f ? ExposureProcessor.SoftClip(m, 0.9f) / m : 1;
Assert.Approximately(r * s, image.Plane(0)[index], 1e-5);
Assert.Approximately(b * s, image.Plane(2)[index], 1e-5);
}
}
}
@@ -0,0 +1,66 @@
using System.Globalization;
using Titano.Core.Analysis;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Testing;
namespace Titano.Core.Tests.Analysis;
public sealed class FlickerSpectrumTests(TestContext context)
{
[Theory]
[Case(12.0)]
[Case(7.5)]
[Case(20.0)]
public void RecoversAKnownPeriodFromRenderedFrames(double period)
{
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
{
Width = 48,
Height = 32,
FrameCount = 240,
Seed = 12,
StartEv = 0,
EndEv = -2,
FlickerEv = 0.1,
FlickerPeriodFrames = period,
LandFlickerEv = 0.02,
});
var measured = AnalysisFixtures.MeasureSeries(sequence);
var result = FlickerSpectrum.Analyze(measured);
context.Log(string.Create(CultureInfo.InvariantCulture,
$"true period {period}, found {result.DominantPeriod:F3} (r = {result.PeakCorrelation:F3}), window {result.RecommendedWindow}"));
var found = Assert.NotNull(result.DominantPeriod);
Assert.Approximately(period, found, 0.5);
Assert.Equal(1, result.RecommendedWindow % 2);
Assert.InRange(result.RecommendedWindow, 4 * period - 1, 4 * period + 2);
}
[Test]
public void WhiteFlickerHasNoPeriodAndGetsTheMinimumWindow()
{
var random = new Random(2);
var series = Enumerable.Range(0, 300).Select(i => -0.01 * i + 0.1 * (2 * random.NextDouble() - 1)).ToArray();
var result = FlickerSpectrum.Analyze(series);
Assert.Null(result.DominantPeriod);
Assert.Less(result.CorrelationLength, 1.5);
Assert.Equal(FlickerSpectrumOptions.Default.MinimumWindow, result.RecommendedWindow);
}
[Test]
public void SlowCorrelatedFlickerWidensTheWindow()
{
// AR(1) flicker with correlation 0.9 per frame: e-folding length about 9.5 frames.
var random = new Random(4);
var series = new double[400];
var state = 0.0;
for (var i = 0; i < series.Length; i++)
{
state = 0.9 * state + 0.05 * (2 * random.NextDouble() - 1);
series[i] = state;
}
var result = FlickerSpectrum.Analyze(series);
Assert.InRange(result.CorrelationLength, 4, 15);
Assert.Greater(result.RecommendedWindow, 15);
Assert.Equal(1, result.RecommendedWindow % 2);
}
}
@@ -0,0 +1,197 @@
using System.Globalization;
using Titano.Core.Analysis;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Core.Imaging;
using Titano.Core.Mathematics;
using Titano.Testing;
namespace Titano.Core.Tests.Analysis;
public sealed class FrameStatisticsTests(TestContext context)
{
/// <summary>
/// Gate: CCT within 100 K for Planckian colours from 2500 K to 10000 K, measured from images. The chromaticities
/// are exact blackbody values (Planck's law integrated against the CIE 1931 2° observer at 1 nm), independent of
/// the Krystek locus used by the estimator.
/// </summary>
[Theory]
[Case(2500, 0.476998, 0.413676)]
[Case(3000, 0.436934, 0.404075)]
[Case(3500, 0.405307, 0.390717)]
[Case(4000, 0.380442, 0.376749)]
[Case(5000, 0.345103, 0.351610)]
[Case(6000, 0.322085, 0.331755)]
[Case(6500, 0.313528, 0.323630)]
[Case(7500, 0.300336, 0.310268)]
[Case(8500, 0.290762, 0.299903)]
[Case(10000, 0.280634, 0.288289)]
public void ColourTemperatureOfPlanckianLightIsWithinOneHundredKelvin(int kelvin, double x, double y)
{
var rgb = Matrix3.XyzToRec709 * new Chromaticity(x, y).ToXyz(0.2);
using var image = new ImageBuffer(16, 16, 3);
image.Plane(0).Fill((float)rgb.X);
image.Plane(1).Fill((float)rgb.Y);
image.Plane(2).Fill((float)rgb.Z);
var estimate = Assert.NotNull(FrameStatistics.Measure(image).ColorTemperature);
context.Log(string.Create(CultureInfo.InvariantCulture,
$"{kelvin} K: estimate {estimate.Kelvin:F1} K (error {estimate.Kelvin - kelvin:F1}), raw McCamy {estimate.McCamyKelvin:F1} K, Duv {estimate.Duv:E2}"));
Assert.Approximately(kelvin, estimate.Kelvin, 100);
Assert.Less(Math.Abs(estimate.Duv), 2e-4);
}
[Test]
public void OffLocusColoursHaveNoTemperature()
{
Assert.Null(ColorTemperature.Estimate(0.1, 0.5, 0.1));
Assert.Null(ColorTemperature.Estimate(0.5, 0.1, 0.5));
Assert.Null(ColorTemperature.Estimate(0, 0, 0));
// 0.01 along the locus normal (towards green) keeps the CCT and stays within the ±0.02 validity band;
// 0.03 falls outside it.
var (u, v) = ColorTemperature.PlanckianUv(5000);
var (u1, v1) = ColorTemperature.PlanckianUv(4990);
var (u2, v2) = ColorTemperature.PlanckianUv(5010);
double nu = v1 - v2, nv = u2 - u1;
if (nv < 0) (nu, nv) = (-nu, -nv);
var length = Math.Sqrt(nu * nu + nv * nv);
Vector3D Tinted(double duv) => Matrix3.XyzToRec709 * Chromaticity.FromUv1960(u + duv * nu / length, v + duv * nv / length).ToXyz();
var green = Tinted(0.01);
var estimate = Assert.NotNull(ColorTemperature.Estimate(green.X, green.Y, green.Z));
Assert.Approximately(0.01, estimate.Duv, 1e-5);
Assert.Approximately(5000, estimate.Kelvin, 1);
var magenta = Tinted(-0.015);
Assert.Approximately(-0.015, Assert.NotNull(ColorTemperature.Estimate(magenta.X, magenta.Y, magenta.Z)).Duv, 1e-5);
var far = Tinted(0.03);
Assert.Null(ColorTemperature.Estimate(far.X, far.Y, far.Z));
}
[Test]
public void TrimmedLogMeanHistogramAndClipping()
{
// 1000 pixels: 900 at 2^-3, 50 crushed at zero, 50 clipped at 1.
using var image = new ImageBuffer(100, 10, 3);
for (var i = 0; i < 1000; i++)
{
var v = i < 50 ? 0f : i < 100 ? 1f : 0.125f;
for (var c = 0; c < 3; c++) image.Plane(c)[i] = v;
}
var stats = FrameStatistics.Measure(image);
Assert.Approximately(0.05, stats.ClipLowFraction, 1e-12);
Assert.Approximately(0.05, stats.ClipHighFraction, 1e-12);
Assert.Approximately(1, stats.Histogram.Sum(), 1e-12);
Assert.Approximately(0.9, stats.Histogram[(int)((-3 - FrameStatistics.HistogramMinEv) * 16)], 1e-12);
// Trimming 2 % per tail removes 20 of the 50 crushed and 20 of the 50 clipped pixels: (30·−14 + 900·−3 + 30·0) / 960.
Assert.Approximately((30 * -14.0 + 900 * -3.0) / 960, stats.MeanLogLuminance, 1e-9);
Assert.Approximately(0.05 + 0.9 * 0.125, stats.MeanGreen, 1e-6);
}
[Test]
public void LogMeanFollowsExposureExactly()
{
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 1 });
using var a = sequence.Render(0);
using var b = a.Clone();
ExposureProcessor.Apply(b, -1.37);
Assert.Approximately(-1.37, FrameStatistics.MeasureLogLuminance(b) - FrameStatistics.MeasureLogLuminance(a), 2e-3);
}
[Test]
public void MaskSelectsTheRegion()
{
using var image = new ImageBuffer(20, 20, 3);
var mask = new float[400];
for (var y = 0; y < 20; y++)
{
for (var x = 0; x < 20; x++)
{
var top = y < 10;
for (var c = 0; c < 3; c++) image[c, x, y] = top ? 0.5f : 0.0625f;
mask[y * 20 + x] = top ? 0 : 1;
}
}
var stats = FrameStatistics.Measure(image, mask);
Assert.Approximately(-4, stats.MeanLogLuminance, 1e-6);
Assert.Approximately(200, stats.Weight, 1e-9);
Assert.Approximately(-1, FrameStatistics.MeasureLogLuminance(image, mask.Select(m => 1 - m).ToArray()), 1e-6);
Assert.Throws<ArgumentException>(() => FrameStatistics.Measure(image, new float[3]));
}
[Test]
public void SharpnessDropsWhenBlurred()
{
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 1, Width = 64, Height = 48 });
using var sharp = sequence.Render(0);
using var blurred = sharp.Clone();
for (var c = 0; c < 3; c++)
{
var plane = blurred.Plane(c);
var source = plane.ToArray();
for (var y = 1; y < 47; y++)
{
for (var x = 1; x < 63; x++)
{
var sum = 0f;
for (var dy = -1; dy <= 1; dy++)
{
for (var dx = -1; dx <= 1; dx++) sum += source[(y + dy) * 64 + x + dx];
}
plane[y * 64 + x] = sum / 9;
}
}
}
Assert.Greater(FrameStatistics.Measure(sharp).Sharpness, 3 * FrameStatistics.Measure(blurred).Sharpness);
}
[Test]
public void ImmerkaerNoiseMatchesTheTrueSigma()
{
// Encoded-domain flat field 0.5 plus Gaussian noise of σ = 0.02 (the estimator works on sRGB-encoded luminance).
var random = new Random(17);
using var image = new ImageBuffer(128, 128, 1);
var plane = image.Plane(0);
for (var i = 0; i < plane.Length; i++)
{
var gaussian = Math.Sqrt(-2 * Math.Log(1 - random.NextDouble())) * Math.Cos(2 * Math.PI * random.NextDouble());
plane[i] = (float)ColorSpace.SrgbToLinear(0.5 + 0.02 * gaussian);
}
var stats = FrameStatistics.Measure(image);
Assert.Approximately(0.02, stats.Noise, 0.001);
Assert.Null(stats.ColorTemperature);
}
[Test]
public void DetectsBlackWhiteAndDuplicateFrames()
{
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
{
FrameCount = 8,
FlickerEv = 0.1,
BlackFrames = [2],
WhiteFrames = [4],
DuplicateFrames = [6],
});
var stats = Enumerable.Range(0, 8).Select(i =>
{
using var image = sequence.Render(i);
return FrameStatistics.Measure(image);
}).ToArray();
Assert.SequenceEqual([2], Enumerable.Range(0, 8).Where(i => stats[i].IsBlack()));
Assert.SequenceEqual([4], Enumerable.Range(0, 8).Where(i => stats[i].IsWhite()));
Assert.SequenceEqual([6], Enumerable.Range(1, 7).Where(i => FrameStatistics.AreLikelyDuplicates(stats[i - 1], stats[i])));
}
[Test]
public void DownscaleAveragesBlocks()
{
using var image = new ImageBuffer(101, 60, 3);
for (var c = 0; c < 3; c++)
{
var plane = image.Plane(c);
for (var i = 0; i < plane.Length; i++) plane[i] = (i % 101) % 2 == 0 ? 0.2f : 0.4f;
}
using var small = AnalysisImage.Downscale(image, 32);
Assert.Equal((25, 15), (small.Width, small.Height));
Assert.True(small.Data.ToArray().All(v => Math.Abs(v - 0.3f) < 1e-6f));
using var same = AnalysisImage.Downscale(image, 200);
Assert.Equal(101, same.Width);
}
}
@@ -0,0 +1,88 @@
using System.Globalization;
using Titano.Core.Analysis;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Testing;
namespace Titano.Core.Tests.Analysis;
public sealed class HolyGrailEngineTests(TestContext context)
{
/// <summary>
/// Sunset: the scene darkens 8 EV while the camera opens up 2/3 EV every 20 frames, plus one metadata change
/// the pixels never received. BRIEF §20.4: no target step above 0.3 EV; the total change is preserved.
/// </summary>
[Test]
public void SunsetStepsAreRedistributedWithinTheGate()
{
var steps = Enumerable.Range(1, 11).Select(k => new SyntheticExposureStep(k * 20, -2.0 / 3, k % 3 == 0 ? ExposureChange.Iso : ExposureChange.Shutter)).ToList();
steps.Add(new SyntheticExposureStep(130, -1.0 / 3, ExposureChange.Aperture, Received: false));
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
{
FrameCount = 240,
Seed = 9,
StartEv = 2,
EndEv = -6,
FlickerEv = 0.03,
ExposureSteps = steps,
});
var measured = AnalysisFixtures.MeasureSeries(sequence);
var ev = sequence.Frames.Select(f => f.ExposureValue).ToArray();
var result = HolyGrailEngine.Compute(measured, ev);
var rawMaxStep = Enumerable.Range(1, measured.Length - 1).Max(i => Math.Abs(measured[i] - measured[i - 1]));
var maxStep = Enumerable.Range(1, measured.Length - 1).Max(i => Math.Abs(result.Target[i] - result.Target[i - 1]));
var truth = sequence.SceneEv.Select((s, i) => s + sequence.ExposureOffsetEv[i]).ToArray();
var totalTruth = truth[^1] - truth[0];
var totalTarget = result.Target[^1] - result.Target[0];
context.Log(string.Create(CultureInfo.InvariantCulture,
$"raw max step {rawMaxStep:F3} EV, target max step {maxStep:F3} EV, total change target {totalTarget:F3} vs truth {totalTruth:F3} EV, transition {result.Transitions[0].Length} frames"));
Assert.Equal(12, result.Transitions.Count);
var ignored = Assert.NotNull(result.Transitions.SingleOrDefault(t => !t.Received));
Assert.Equal(130, ignored.Index);
Assert.True(result.Transitions.Where(t => t.Index != 130).All(t => t.Received));
Assert.Greater(rawMaxStep, 0.5);
Assert.LessOrEqual(maxStep, 0.3);
Assert.Approximately(maxStep, result.MaxFrameStepEv, 1e-12);
Assert.Approximately(totalTruth, totalTarget, 0.05);
// Default transition: half the 20-frame step spacing.
Assert.Equal(10.0, result.Transitions[0].Length);
}
[Test]
public void LargeStepGetsALongerTransition()
{
var n = 100;
var measured = Enumerable.Range(0, n).Select(i => i >= 50 ? 1.5 : 0.0).ToArray();
var ev = Enumerable.Range(0, n).Select(i => (double?)(i >= 50 ? 10.5 : 12.0)).ToArray();
var result = HolyGrailEngine.Compute(measured, ev, new HolyGrailOptions { TransitionFrames = 4 });
Assert.LessOrEqual(result.MaxFrameStepEv, 0.3);
Assert.GreaterOrEqual(result.Transitions[0].Length, 7.5);
Assert.Approximately(1.5, result.Target[^1] - result.Target[0], 1e-9);
Assert.Approximately(1.5, result.Transitions[0].MeasuredEv, 1e-9);
}
[Test]
public void StepsNearTheEndsStayInsideTheSequence()
{
var n = 30;
var measured = Enumerable.Range(0, n).Select(i => i >= 2 ? 1.0 : 0.0).ToArray();
var ev = Enumerable.Range(0, n).Select(i => (double?)(i >= 2 ? 11.0 : 12.0)).ToArray();
var result = HolyGrailEngine.Compute(measured, ev, new HolyGrailOptions { TransitionFrames = 8 });
Assert.Equal(0.0, result.Transitions[0].Start);
Assert.Approximately(0, result.SmoothedOffsets[0], 1e-12);
Assert.Approximately(1, result.SmoothedOffsets[^1], 1e-12);
Assert.LessOrEqual(result.MaxFrameStepEv, 0.3);
}
[Test]
public void NoMetadataStepsMeansPlainDeflicker()
{
var measured = Enumerable.Range(0, 60).Select(i => 0.01 * i + (i % 2 == 0 ? 0.05 : -0.05)).ToArray();
var ev = new double?[60];
var result = HolyGrailEngine.Compute(measured, ev);
var plain = DeflickerEngine.Compute(measured);
Assert.Empty(result.Transitions);
Assert.SequenceEqual(plain.Target, result.Target);
}
}
@@ -0,0 +1,201 @@
using System.Diagnostics;
using System.Globalization;
using Titano.Core.Analysis;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Core.Mathematics;
using Titano.Testing;
namespace Titano.Core.Tests.Analysis;
public sealed class LightAnalyzerTests(TestContext context)
{
private static SyntheticSequence Timeline() => SyntheticSequence.Create(new SyntheticSequenceOptions
{
FrameCount = 200,
IntervalSeconds = 10,
TimeShifts =
[
new(40, 60), // 70 s interval: gap
new(100, 5400), // 90 min: session break
new(150, -3600), // daylight saving ends: clock jump
new(195, 7200), // 2 h break leaving a 5-frame tail session
],
DuplicateFrames = [60],
ExposureSteps =
[
new(50, 1.0 / 3, ExposureChange.Shutter),
new(120, -1, ExposureChange.Iso),
new(170, 0.5, ExposureChange.Aperture),
],
});
[Test]
public void FindsSessionsGapsClockJumpsAndDuplicatesExactly()
{
var report = LightAnalyzer.Analyze(Timeline().LightFrames());
Assert.Equal(200, report.TimedFrameCount);
Assert.Equal(10.0, report.MedianIntervalSeconds);
Assert.Equal(0.0, report.JitterSeconds);
Assert.SequenceEqual([40, 100, 195], report.Gaps.Select(g => g.Index));
Assert.SequenceEqual([IntervalKind.Gap, IntervalKind.SessionBreak, IntervalKind.SessionBreak], report.Gaps.Select(g => g.Kind));
Assert.Approximately(70, report.Gaps[0].Seconds, 1e-9);
// The 5-frame tail merges into the previous session.
Assert.Equal(2, report.Sessions.Count);
Assert.Equal((0, 99), (report.Sessions[0].StartIndex, report.Sessions[0].EndIndex));
Assert.Equal((100, 199), (report.Sessions[1].StartIndex, report.Sessions[1].EndIndex));
Assert.SequenceEqual([(60, IntervalKind.Duplicate), (150, IntervalKind.ClockJump)], report.TimestampIssues.Select(t => (t.Index, t.Kind)));
Assert.Approximately(11050 + 3600, report.CaptureSpan.TotalSeconds, 1e-6);
Assert.Equal(report.AdjustedTimes[149]!.Value.AddSeconds(10), report.AdjustedTimes[150]!.Value);
var keys = report.Findings.Select(f => f.Key).ToList();
foreach (var key in new[] { FindingKeys.Gaps, FindingKeys.Sessions, FindingKeys.DuplicateTimestamps, FindingKeys.ClockJumps, FindingKeys.ExposureSteps })
Assert.Contains(key, keys);
foreach (var key in new[] { FindingKeys.NonMonotonicTimestamps, FindingKeys.CameraChanged, FindingKeys.MixedResolution, FindingKeys.IrregularInterval, FindingKeys.NoTimestamps })
Assert.DoesNotContain(key, keys);
var gaps = report.Findings.Single(f => f.Key == FindingKeys.Gaps);
Assert.Equal(FindingSeverity.Warning, gaps.Severity);
Assert.Equal(3, (int)gaps.Arguments[0]);
Assert.Approximately(7210, (double)gaps.Arguments[1], 1e-9);
// Domain frames (no camera or GPS fields) give the same timing and exposure analysis.
var fromFrames = LightAnalyzer.Analyze(Timeline().Frames);
Assert.SequenceEqual(report.Intervals, fromFrames.Intervals);
Assert.SequenceEqual(report.ExposureSteps.Select(s => s.Index), fromFrames.ExposureSteps.Select(s => s.Index));
}
[Test]
public void FindsExposureStepsWithTheirAmplitude()
{
var report = LightAnalyzer.Analyze(Timeline().LightFrames());
Assert.SequenceEqual([50, 120, 170], report.ExposureSteps.Select(s => s.Index));
Assert.SequenceEqual([ExposureChange.Shutter, ExposureChange.Iso, ExposureChange.Aperture], report.ExposureSteps.Select(s => s.Changes));
Assert.Approximately(1.0 / 3, report.ExposureSteps[0].DeltaEv, 1e-9);
Assert.Approximately(-1, report.ExposureSteps[1].DeltaEv, 1e-9);
Assert.Approximately(0.5, report.ExposureSteps[2].DeltaEv, 1e-9);
Assert.Equal(60.0, report.TypicalStepDistance);
Assert.Approximately(Math.Log2(64 / 0.01), report.ExposureValues[0]!.Value, 1e-9);
}
[Test]
public void SmallBackwardStepIsNonMonotonic()
{
var frames = Timeline().LightFrames().Take(30).ToList();
frames[10] = frames[10] with { CapturedAt = frames[10].CapturedAt!.Value.AddSeconds(-15) };
var report = LightAnalyzer.Analyze(frames);
Assert.SequenceEqual([(10, IntervalKind.NonMonotonic)], report.TimestampIssues.Select(t => (t.Index, t.Kind)));
Assert.Contains(FindingKeys.NonMonotonicTimestamps, report.Findings.Select(f => f.Key));
}
[Test]
public void ForwardHourJumpOnCadenceIsAClockChange()
{
var frames = Timeline().LightFrames().Take(40).Select((f, i) => i >= 20 ? f with { CapturedAt = f.CapturedAt!.Value.AddHours(1) } : f).ToList();
var report = LightAnalyzer.Analyze(frames);
Assert.SequenceEqual([(20, IntervalKind.ClockJump)], report.TimestampIssues.Select(t => (t.Index, t.Kind)));
Assert.Count(1, report.Sessions);
Assert.Approximately(390, report.CaptureSpan.TotalSeconds, 1e-6);
}
[Test]
public void ReportsIdentityResolutionAndOrientationChanges()
{
var frames = Timeline().LightFrames().Take(100).ToList();
frames[30] = frames[30] with { CameraModel = "Other" };
for (var i = 80; i < 100; i++) frames[i] = frames[i] with { Lens = "Zoom 70-200" };
frames[10] = frames[10] with { Width = 50 };
frames[11] = frames[11] with { Orientation = 6 };
frames[12] = frames[12] with { Lens = null, CameraMake = null, CameraModel = null };
var report = LightAnalyzer.Analyze(frames);
Assert.SequenceEqual([(30, IdentityKind.Camera), (31, IdentityKind.Camera), (80, IdentityKind.Lens)], report.IdentityChanges.Select(c => (c.Index, c.Kind)));
Assert.Equal("Titano Synthetic", report.IdentityChanges[1].After);
Assert.Equal((96, 64), report.DominantSize);
Assert.SequenceEqual([10, 11], report.ResolutionOutliers);
Assert.SequenceEqual([11], report.OrientationOutliers);
var keys = report.Findings.Select(f => f.Key).ToList();
foreach (var key in new[] { FindingKeys.CameraChanged, FindingKeys.LensChanged, FindingKeys.MixedResolution, FindingKeys.MixedOrientation })
Assert.Contains(key, keys);
}
[Test]
public void LabelsDayPhasesFromGps()
{
const double lat = 45.07, lon = 7.69;
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
{
FrameCount = 240,
IntervalSeconds = 60,
Start = new DateTime(2024, 6, 21, 19, 0, 0),
UtcOffsetMinutes = 120,
Latitude = lat,
Longitude = lon,
});
var report = LightAnalyzer.Analyze(sequence.LightFrames());
var phases = report.DayPhases.Select(p => (int)Assert.NotNull(p)).ToList();
Assert.Monotonic(phases.Select(p => (double)p), decreasing: true);
Assert.Equal((int)DayPhase.Day, phases[0]);
Assert.LessOrEqual(phases[^1], (int)DayPhase.NauticalTwilight);
var sunset = SolarPosition.Events(new DateOnly(2024, 6, 21), lat, lon).Sunset!.Value.AddHours(2);
var firstTwilight = phases.FindIndex(p => p == (int)DayPhase.CivilTwilight);
var frameTime = new DateTime(2024, 6, 21, 19, 0, 0).AddMinutes(firstTwilight);
Assert.InRange((frameTime - sunset).TotalSeconds, 0, 60);
Assert.Contains(FindingKeys.DayNightTransition, report.Findings.Select(f => f.Key));
Assert.DoesNotContain(FindingKeys.TimeZoneEstimated, report.Findings.Select(f => f.Key));
// A GPS time stamp gives the same offset; without either the zone is estimated from the longitude.
var viaGps = LightAnalyzer.Analyze(sequence.LightFrames().Select(f => f with { UtcOffsetMinutes = null, GpsUtc = f.CapturedAt!.Value.AddHours(-2) }).ToList());
Assert.SequenceEqual(report.DayPhases, viaGps.DayPhases);
var estimated = LightAnalyzer.Analyze(sequence.LightFrames().Select(f => f with { UtcOffsetMinutes = null }).ToList());
var finding = estimated.Findings.Single(f => f.Key == FindingKeys.TimeZoneEstimated);
Assert.Equal(60, (int)finding.Arguments[0]);
var noGps = LightAnalyzer.Analyze(sequence.LightFrames().Select(f => f with { Latitude = null, Longitude = null }).ToList());
Assert.True(noGps.DayPhases.All(p => p is null));
}
[Test]
public void TenThousandFramesTakeWellUnderASecond()
{
var start = new DateTime(2024, 3, 1, 5, 0, 0);
var frames = Enumerable.Range(0, 10_000).Select(i => new LightFrame
{
Index = i,
CapturedAt = start.AddSeconds(i * 5 + (i >= 5000 ? 3600 : 0)),
UtcOffsetMinutes = 60,
ExposureTime = i < 4000 ? 1.0 / 500 : 1.0 / 250,
FNumber = 5.6,
Iso = 100,
Width = 6000,
Height = 4000,
CameraMake = "Maker",
CameraModel = "Body",
Lens = "Lens",
Latitude = 46.5,
Longitude = 11.3,
}).ToList();
LightAnalyzer.Analyze(frames.Take(100).ToList());
var watch = Stopwatch.StartNew();
var report = LightAnalyzer.Analyze(frames);
watch.Stop();
context.Log(string.Create(CultureInfo.InvariantCulture, $"10,000 frames analysed in {watch.Elapsed.TotalMilliseconds:F1} ms"));
Assert.Equal(10_000, report.DayPhases.Length);
Assert.Count(1, report.ExposureSteps);
Assert.Less(watch.Elapsed.TotalSeconds, 2);
}
[Test]
public void HandlesEmptyAndUntimedInput()
{
var empty = LightAnalyzer.Analyze(Array.Empty<LightFrame>());
Assert.Equal(0, empty.FrameCount);
Assert.Empty(empty.Sessions);
var untimed = LightAnalyzer.Analyze(new[] { new LightFrame(), new LightFrame { Index = 1 } });
Assert.Contains(FindingKeys.NoTimestamps, untimed.Findings.Select(f => f.Key));
Assert.Null(untimed.MedianIntervalSeconds);
Assert.Count(1, untimed.Sessions);
}
}
@@ -0,0 +1,201 @@
using System.Globalization;
using Titano.Core.Analysis;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Core.Imaging;
using Titano.Testing;
namespace Titano.Core.Tests.Analysis;
public sealed class RegionTests(TestContext context)
{
private static SyntheticSequence Landscape(int frames, double tilt, double wave, int seed = 5) => SyntheticSequence.Create(new SyntheticSequenceOptions
{
Width = 128,
Height = 80,
FrameCount = frames,
Seed = seed,
StartEv = -1,
EndEv = 0,
HorizonFraction = 0.45,
HorizonTilt = tilt,
HorizonWave = wave,
SkyFlickerEv = 0.15,
LandFlickerEv = 0.15,
});
private static List<ImageBuffer> RenderAll(SyntheticSequence sequence) => Enumerable.Range(0, sequence.Count).Select(sequence.Render).ToList();
[Test]
public void HorizonIsFoundPerColumnWithHighConfidence()
{
var sequence = Landscape(30, tilt: 0.08, wave: 3);
var frames = RenderAll(sequence);
try
{
var mask = RegionSegmenter.Segment(frames);
Assert.Equal(RegionMethod.Horizon, mask.Method);
Assert.Greater(mask.Confidence, 0.6);
var horizon = Assert.NotNull(mask.Horizon);
var worst = Enumerable.Range(0, mask.Width).Max(x => Math.Abs(horizon[x] - sequence.HorizonRow(x + 0.5)));
var agreement = Agreement(mask, sequence);
context.Log(string.Create(CultureInfo.InvariantCulture, $"confidence {mask.Confidence:F3}, worst column error {worst:F3} px, pixel agreement {agreement:P2}"));
Assert.LessOrEqual(worst, 1.0);
Assert.GreaterOrEqual(agreement, 0.98);
}
finally
{
frames.ForEach(f => f.Dispose());
}
}
[Test]
public void HorizonSurvivesPolarityChangesAcrossFrames()
{
var day = Landscape(10, tilt: 0, wave: 0);
var night = SyntheticSequence.Create(day.Options with { SkyLevel = 0.01, LandLevel = 0.2, Seed = 6 });
var frames = RenderAll(day).Concat(RenderAll(night)).ToList();
try
{
var mask = RegionSegmenter.Segment(frames);
Assert.Equal(RegionMethod.Horizon, mask.Method);
var horizon = Assert.NotNull(mask.Horizon);
Assert.True(horizon.All(h => Math.Abs(h - 0.45 * 80) <= 1), "horizon row");
}
finally
{
frames.ForEach(f => f.Dispose());
}
}
[Test]
public void CliffFallsBackToLuminance()
{
// Sky above row 20 on the left half and above row 60 on the right: no single row step explains it.
var frames = new List<ImageBuffer>();
for (var f = 0; f < 6; f++)
{
var image = new ImageBuffer(96, 80, 3);
for (var y = 0; y < 80; y++)
{
for (var x = 0; x < 96; x++)
{
var sky = y < (x < 48 ? 20 : 60);
var v = sky ? 0.4f * (1 + 0.02f * f) : 0.03f * (1 + ((x * 7 + y * 13) % 5) * 0.1f);
for (var c = 0; c < 3; c++) image[c, x, y] = v;
}
}
frames.Add(image);
}
try
{
var mask = RegionSegmenter.Segment(frames);
Assert.Equal(RegionMethod.Luminance, mask.Method);
Assert.Greater(mask.Confidence, 0.5);
var correct = 0;
for (var y = 0; y < 80; y++)
{
for (var x = 0; x < 96; x++)
{
var sky = y < (x < 48 ? 20 : 60);
if (mask.Sky[y * 96 + x] >= 0.5f == sky) correct++;
}
}
Assert.GreaterOrEqual(correct / (96.0 * 80), 0.97);
}
finally
{
frames.ForEach(f => f.Dispose());
}
}
[Test]
public void FeaturelessFramesHaveNoConfidence()
{
using var flat = new ImageBuffer(64, 48, 3);
flat.Data.Fill(0.2f);
var mask = RegionSegmenter.Segment([flat]);
Assert.Less(mask.Confidence, 0.05);
}
/// <summary>BRIEF §20.4: with independent sky and land flicker, the land residual after region deflicker is at
/// most 25 % of the residual left by one global curve.</summary>
[Test]
public void RegionDeflickerMeetsTheRegressionGate()
{
var sequence = Landscape(150, tilt: 0.05, wave: 2);
var frames = RenderAll(sequence);
RegionMask mask;
double[] sky, land, global;
try
{
mask = RegionSegmenter.Segment(frames);
sky = new double[frames.Count];
land = new double[frames.Count];
global = new double[frames.Count];
for (var i = 0; i < frames.Count; i++)
{
(sky[i], land[i]) = RegionDeflicker.Measure(frames[i], mask);
global[i] = FrameStatistics.MeasureLogLuminance(frames[i]);
}
}
finally
{
frames.ForEach(f => f.Dispose());
}
var options = new DeflickerOptions { Window = 31 };
var globalResult = DeflickerEngine.Compute(global, options);
var regionResult = RegionDeflicker.Compute(sky, land, options);
var trueLand = AnalysisFixtures.TrueLandMask(sequence);
var landAfterGlobal = AnalysisFixtures.MeasureSeries(sequence, (i, image) =>
{
ExposureProcessor.Apply(image, globalResult.CorrectionEv[i]);
return image;
}, trueLand);
var landAfterRegion = AnalysisFixtures.MeasureSeries(sequence, (i, image) =>
{
RegionDeflicker.Apply(image, mask, regionResult.Sky.CorrectionEv[i], regionResult.Land.CorrectionEv[i]);
return image;
}, trueLand);
var globalResidual = AnalysisFixtures.FrameToFrameResidualRms(landAfterGlobal, sequence.SceneEv);
var regionResidual = AnalysisFixtures.FrameToFrameResidualRms(landAfterRegion, sequence.SceneEv);
var ratio = regionResidual / globalResidual;
context.Log(string.Create(CultureInfo.InvariantCulture,
$"mask {mask.Method} confidence {mask.Confidence:F3}; land residual global {globalResidual:F4} EV, region {regionResidual:F4} EV, ratio {ratio:P1}"));
Assert.LessOrEqual(ratio, 0.25);
}
[Test]
public void ResampledMaskKeepsTheHorizon()
{
var sequence = Landscape(6, tilt: 0, wave: 0);
var frames = RenderAll(sequence);
try
{
var mask = RegionSegmenter.Segment(frames);
var big = mask.Resample(256, 160);
Assert.Equal(256 * 160, big.Sky.Length);
Assert.Approximately(2 * mask.Horizon![10], big.Horizon![20], 0.6);
Assert.True(big.Sky[5 * 256 + 100] > 0.99f && big.Sky[150 * 256 + 100] < 0.01f);
Assert.Same(mask, mask.Resample(mask.Width, mask.Height));
}
finally
{
frames.ForEach(f => f.Dispose());
}
}
private static double Agreement(RegionMask mask, SyntheticSequence sequence)
{
var correct = 0;
for (var y = 0; y < mask.Height; y++)
{
for (var x = 0; x < mask.Width; x++)
{
if (mask.Sky[y * mask.Width + x] >= 0.5f == sequence.IsSky(x, y)) correct++;
}
}
return correct / (double)(mask.Width * mask.Height);
}
}
@@ -0,0 +1,80 @@
using Titano.Core.Analysis;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Testing;
namespace Titano.Core.Tests.Analysis;
public sealed class SyntheticSequenceTests
{
private static readonly SyntheticSequenceOptions Recipe = new()
{
FrameCount = 30,
Seed = 42,
StartEv = -1,
EndEv = 1,
FlickerEv = 0.1,
SkyFlickerEv = 0.05,
ExposureSteps = [new(10, -1), new(20, 0.5, ExposureChange.Aperture, Received: false)],
StartKelvin = 3000,
EndKelvin = 7000,
NoiseSigma = 0.001,
DuplicateFrames = [15],
Latitude = 45,
Longitude = 9,
};
[Test]
public void IsDeterministic()
{
var a = SyntheticSequence.Create(Recipe);
var b = SyntheticSequence.Create(Recipe);
Assert.SequenceEqual(a.FlickerEv, b.FlickerEv);
Assert.SequenceEqual(a.Frames.Select(f => f.Id), b.Frames.Select(f => f.Id));
foreach (var i in new[] { 0, 7, 29 })
{
using var x = a.Render(i);
using var y = b.Render(i);
using var again = a.Render(i);
Assert.True(x.Data.SequenceEqual(y.Data) && x.Data.SequenceEqual(again.Data), $"frame {i}");
}
var other = SyntheticSequence.Create(Recipe with { Seed = 43 });
Assert.False(other.FlickerEv.SequenceEqual(a.FlickerEv));
}
[Test]
public void MetadataMatchesTheRecipe()
{
var sequence = SyntheticSequence.Create(Recipe);
var ev = sequence.Frames.Select(f => f.ExposureValue!.Value).ToArray();
Assert.Approximately(-1, ev[10] - ev[9], 1e-9);
Assert.Approximately(0.5, ev[20] - ev[19], 1e-9);
Assert.Approximately(1, sequence.ExposureOffsetEv[10], 1e-9);
Assert.Approximately(1, sequence.ExposureOffsetEv[29], 1e-9);
Assert.Equal(sequence.Frames[14].CapturedAt, sequence.Frames[15].CapturedAt);
Assert.Equal(TimeSpan.FromSeconds(10), sequence.Frames[2].CapturedAt!.Value - sequence.Frames[1].CapturedAt!.Value);
Assert.Equal(45.0, sequence.Metadata[0].Gps!.Latitude);
Assert.Equal("Synthetic", sequence.LightFrames()[3].CameraModel);
}
[Test]
public void PixelsCarryTheTruthSeries()
{
var sequence = SyntheticSequence.Create(Recipe with { SkyFlickerEv = 0, NoiseSigma = 0, StartKelvin = 5000, EndKelvin = 5000 });
var measured = AnalysisFixtures.MeasureSeries(sequence);
var truth = sequence.SceneEv.Select((s, i) => s + sequence.ExposureOffsetEv[i] + sequence.FlickerEv[i]).ToArray();
Assert.Less(AnalysisFixtures.MaxDeviation(measured, truth), 2e-3);
Assert.Equal(measured[14], measured[15]);
}
[Test]
public void StarFieldIsDarkWithPointSources()
{
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 1, StarField = true, StarCount = 60, Width = 128, Height = 96 });
using var image = sequence.Render(0);
var stats = FrameStatistics.Measure(image);
Assert.Less(stats.MeanLogLuminance, -8);
var bright = image.Plane(1).ToArray().Count(v => v > 0.2f);
Assert.InRange(bright, 30, 100);
Assert.Throws<ArgumentOutOfRangeException>(() => sequence.Render(1));
}
}
@@ -0,0 +1,71 @@
using System.Globalization;
using Titano.Core.Analysis;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Testing;
namespace Titano.Core.Tests.Analysis;
public sealed class WhiteBalanceSmootherTests(TestContext context)
{
[Test]
public void RemovesJitterAndKeepsTheDrift()
{
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
{
Width = 48,
Height = 32,
FrameCount = 150,
Seed = 21,
StartKelvin = 3500,
EndKelvin = 6500,
WhiteBalanceJitter = 0.08,
FlickerEv = 0.05,
});
var stats = Measure(sequence, null);
var result = WhiteBalanceSmoother.Smooth(stats.Select(s => s.MeanRed).ToArray(), stats.Select(s => s.MeanGreen).ToArray(), stats.Select(s => s.MeanBlue).ToArray());
var corrected = Measure(sequence, result.Gains);
// Truth: the ratio of the drifting light without jitter.
var truthRed = new double[sequence.Count];
var truthBlue = new double[sequence.Count];
for (var i = 0; i < sequence.Count; i++)
{
var rgb = ColorTemperature.PlanckianRgb(sequence.Kelvin[i]);
truthRed[i] = Math.Log2(rgb.X / rgb.Y);
truthBlue[i] = Math.Log2(rgb.Z / rgb.Y);
}
var before = AnalysisFixtures.FrameToFrameResidualRms(result.RedRatio, truthRed);
var after = AnalysisFixtures.FrameToFrameResidualRms(corrected.Select(s => Math.Log2(s.MeanRed / s.MeanGreen)).ToArray(), truthRed);
var afterBlue = AnalysisFixtures.FrameToFrameResidualRms(corrected.Select(s => Math.Log2(s.MeanBlue / s.MeanGreen)).ToArray(), truthBlue);
var drift = AnalysisFixtures.MaxDeviation(result.SmoothedBlueRatio, truthBlue);
context.Log(string.Create(CultureInfo.InvariantCulture, $"R/G jitter before {before:F4}, after {after:F4}; B/G after {afterBlue:F4}; drift deviation {drift:F4}"));
Assert.Less(after, 0.2 * before);
Assert.Less(afterBlue, 0.2 * before);
Assert.Less(drift, 0.03);
// Gains never change exposure.
for (var i = 0; i < sequence.Count; i++)
Assert.Approximately(stats[i].MeanLogLuminance, corrected[i].MeanLogLuminance, 0.01);
}
[Test]
public void InvalidFramesGetIdentityGains()
{
var result = WhiteBalanceSmoother.Smooth([0.5, 0, 0.5, 0.5], [0.5, 0, 0.5, 0.5], [0.5, 0, 0.5, 0.5], window: 3);
Assert.Equal(ChannelGains.Identity, result.Gains[1]);
Assert.Approximately(1, result.Gains[0].Red, 1e-12);
Assert.Throws<ArgumentException>(() => WhiteBalanceSmoother.Smooth([1.0], [1.0, 2.0], [1.0]));
}
private static FrameStatistics[] Measure(SyntheticSequence sequence, ChannelGains[]? gains)
{
var stats = new FrameStatistics[sequence.Count];
Parallel.For(0, sequence.Count, new ParallelOptions { MaxDegreeOfParallelism = 2 }, i =>
{
using var image = sequence.Render(i);
if (gains is not null) ExposureProcessor.Apply(image, 0, gains[i]);
stats[i] = FrameStatistics.Measure(image);
});
return stats;
}
}
@@ -0,0 +1,121 @@
using System.Globalization;
using Titano.Core.Mathematics;
using Titano.Testing;
namespace Titano.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 Titano.Core.Imaging;
using Titano.Core.Mathematics;
using Titano.Testing;
namespace Titano.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 Titano.Core.Mathematics;
using Titano.Testing;
namespace Titano.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);
}
}
+202
View File
@@ -0,0 +1,202 @@
using Titano.Core.Mathematics;
using Titano.Testing;
namespace Titano.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 Titano.Core.Mathematics;
using Titano.Testing;
namespace Titano.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);
}
}