using Chronos.Core.Motion; using Chronos.Testing; namespace Chronos.Core.Tests.Motion; public sealed class PlaneOpsTests { private const int Width = 37; private const int Height = 23; [Theory] [Case(1)] [Case(2)] public void MedianFilterMatchesBruteForce(int radius) { var source = RandomPlane(seed: radius); var output = new float[source.Length]; PlaneOps.MedianFilter(source, output, Width, Height, radius); for (var y = 0; y < Height; y++) { for (var x = 0; x < Width; x++) { var window = new List(); for (var dy = -radius; dy <= radius; dy++) for (var dx = -radius; dx <= radius; dx++) window.Add(source[int.Clamp(y + dy, 0, Height - 1) * Width + int.Clamp(x + dx, 0, Width - 1)]); window.Sort(); Assert.Equal(window[window.Count / 2], output[y * Width + x]); } } } [Theory] [Case(1)] [Case(3)] public void BoxFilterMatchesBruteForce(int radius) { var source = RandomPlane(seed: 10 + radius); var output = new float[source.Length]; PlaneOps.BoxFilter(source, output, new float[source.Length], Width, Height, radius); for (var y = 0; y < Height; y++) { for (var x = 0; x < Width; x++) { double sum = 0; for (var dy = -radius; dy <= radius; dy++) for (var dx = -radius; dx <= radius; dx++) sum += source[int.Clamp(y + dy, 0, Height - 1) * Width + int.Clamp(x + dx, 0, Width - 1)]; Assert.Approximately(sum / ((2 * radius + 1) * (2 * radius + 1)), output[y * Width + x], 1e-5); } } } [Test] public void BinomialBlurKeepsConstantsAndMean() { var flat = new float[Width * Height]; flat.AsSpan().Fill(0.7f); PlaneOps.Binomial5(flat, flat, new float[flat.Length], Width, Height); Assert.True(flat.All(v => double.Abs(v - 0.7) < 1e-6)); var impulse = new float[Width * Height]; impulse[11 * Width + 17] = 1; var blurred = new float[impulse.Length]; PlaneOps.Binomial5(impulse, blurred, new float[impulse.Length], Width, Height); Assert.Approximately(1, blurred.Sum(v => (double)v), 1e-6); Assert.Approximately(36.0 / 256, blurred[11 * Width + 17], 1e-7); } [Test] public void SelectionAndMedian() { var values = new float[] { 5, 1, 4, 2, 3 }; Assert.Equal(3f, PlaneOps.Median(values)); Assert.Equal(2.5f, PlaneOps.Median(new float[] { 4, 1, 3, 2 })); Assert.Equal(1f, PlaneOps.Select(new float[] { 3, 1, 2 }, 0)); Assert.Equal(7f, PlaneOps.Median(new float[] { 7 })); } [Test] public void BilinearIsExactAtPixelCentresAndClamps() { var plane = RandomPlane(seed: 3); Assert.Equal(plane[5 * Width + 9], PlaneOps.Bilinear(plane, Width, Height, 9, 5)); Assert.Equal(plane[0], PlaneOps.Bilinear(plane, Width, Height, -3, -8)); var mid = 0.5f * (plane[5 * Width + 9] + plane[5 * Width + 10]); Assert.Approximately(mid, PlaneOps.Bilinear(plane, Width, Height, 9.5f, 5), 1e-6); } private static float[] RandomPlane(int seed) { var random = new Random(seed); var plane = new float[Width * Height]; for (var i = 0; i < plane.Length; i++) plane[i] = (float)random.NextDouble(); return plane; } }