using System.Globalization;
using Chronos.Core.Analysis;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Imaging;
using Chronos.Core.Mathematics;
using Chronos.Testing;
namespace Chronos.Core.Tests.Analysis;
public sealed class FrameStatisticsTests(TestContext context)
{
///
/// 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.
///
[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(() => 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);
}
}