using System.Globalization; using Chronos.Core.Analysis; using Chronos.Core.Diagnostics.Synthetic; using Chronos.Testing; namespace Chronos.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(() => 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; } }