diff --git a/src/Titano.Core/Analysis/AnalysisImage.cs b/src/Titano.Core/Analysis/AnalysisImage.cs new file mode 100644 index 00000000..ffbb24e9 --- /dev/null +++ b/src/Titano.Core/Analysis/AnalysisImage.cs @@ -0,0 +1,51 @@ +using Titano.Core.Imaging; + +namespace Titano.Core.Analysis; + +/// Builds the reduced-size images that analysis passes measure. +public static class AnalysisImage +{ + /// + /// Area-average (box) downscale by the smallest integer factor that brings the long edge to at most + /// . Exact for flat fields; trailing rows/columns that do not fill a block are + /// dropped. Returns a copy when no reduction is needed. + /// + public static ImageBuffer Downscale(ImageBuffer source, int maxLongEdge) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentOutOfRangeException.ThrowIfLessThan(maxLongEdge, 1); + var factor = (Math.Max(source.Width, source.Height) + maxLongEdge - 1) / maxLongEdge; + if (factor <= 1) return source.Clone(); + var fx = Math.Min(factor, source.Width); + var fy = Math.Min(factor, source.Height); + var width = source.Width / fx; + var height = source.Height / fy; + var result = new ImageBuffer(width, height, source.Channels, clear: false); + var scale = 1f / (fx * fy); + + void Row(int index) + { + var c = index / height; + var y = index % height; + var target = result.Row(c, y); + target.Clear(); + for (var dy = 0; dy < fy; dy++) + { + var src = source.Row(c, y * fy + dy); + for (var x = 0; x < width; x++) + { + var block = src.Slice(x * fx, fx); + var sum = 0f; + foreach (var v in block) sum += v; + target[x] += sum; + } + } + foreach (ref var v in target) v *= scale; + } + + var rows = height * source.Channels; + if ((long)source.PlaneLength * source.Channels >= 1 << 20) Parallel.For(0, rows, Row); + else for (var i = 0; i < rows; i++) Row(i); + return result; + } +} diff --git a/src/Titano.Core/Analysis/ColorTemperature.cs b/src/Titano.Core/Analysis/ColorTemperature.cs new file mode 100644 index 00000000..ff446f2e --- /dev/null +++ b/src/Titano.Core/Analysis/ColorTemperature.cs @@ -0,0 +1,118 @@ +using Titano.Core.Mathematics; + +namespace Titano.Core.Analysis; + +/// Correlated colour temperature of a near-Planckian colour. +/// CCT: temperature of the nearest Planckian-locus point in CIE 1960 uv. +/// McCamy's cubic estimate the search started from. +/// Signed uv distance from the locus (positive towards green). +public readonly record struct ColorTemperatureEstimate(double Kelvin, double McCamyKelvin, double Duv); + +/// +/// Colour temperature from chromaticity: McCamy (1992) cubic as the starting point, refined to the closest point +/// of the Planckian locus (Krystek 1985 rational approximation, 1000–15000 K) in CIE 1960 uv. Colours farther than +/// from the locus have no meaningful CCT and are rejected. +/// +public static class ColorTemperature +{ + /// Validity limit on |Duv| (ANSI C78.377 uses ±0.02 as the edge of "white" light). + public const double MaxDuv = 0.02; + + public const double MinKelvin = 1000; + public const double MaxKelvin = 15000; + + /// McCamy's cubic CCT approximation from CIE 1931 xy (epicentre 0.3320, 0.1858). + public static double McCamy(Chromaticity xy) + { + var n = (xy.X - 0.3320) / (0.1858 - xy.Y); + return ((449 * n + 3525) * n + 6823.3) * n + 5520.33; + } + + /// Planckian locus in CIE 1960 uv (Krystek 1985; |Δu|, |Δv| < 1e-4 over 1000–15000 K). + public static (double U, double V) PlanckianUv(double kelvin) + { + var t = kelvin; + var u = (0.860117757 + 1.54118254e-4 * t + 1.28641212e-7 * t * t) / (1 + 8.42420235e-4 * t + 7.08145163e-7 * t * t); + var v = (0.317398726 + 4.22806245e-5 * t + 4.20481691e-8 * t * t) / (1 - 2.89741816e-5 * t + 1.61456053e-7 * t * t); + return (u, v); + } + + public static Chromaticity PlanckianChromaticity(double kelvin) + { + var (u, v) = PlanckianUv(kelvin); + return Chromaticity.FromUv1960(u, v); + } + + /// Linear Rec.709 RGB of a Planckian radiator's chromaticity, scaled to luminance 1. + public static Vector3D PlanckianRgb(double kelvin) => Matrix3.XyzToRec709 * PlanckianChromaticity(kelvin).ToXyz(); + + /// Estimate from a chromaticity; null outside the locus range or beyond . + public static ColorTemperatureEstimate? Estimate(Chromaticity xy) + { + if (!double.IsFinite(xy.X) || !double.IsFinite(xy.Y) || !(xy.Y > 0)) return null; + var mcCamy = McCamy(xy); + if (!(mcCamy >= MinKelvin && mcCamy <= MaxKelvin)) return null; + + var (u, v) = xy.ToUv1960(); + // Golden-section search in mireds (the locus is far more uniform in 1/T) around the McCamy seed. + var seed = 1e6 / mcCamy; + double lo = Math.Max(1e6 / MaxKelvin, seed - 40), hi = Math.Min(1e6 / MinKelvin, seed + 40); + const double ratio = 0.6180339887498949; + var a = hi - ratio * (hi - lo); + var b = lo + ratio * (hi - lo); + double fa = Distance2(u, v, a), fb = Distance2(u, v, b); + while (hi - lo > 1e-7) + { + if (fa <= fb) + { + hi = b; + b = a; + fb = fa; + a = hi - ratio * (hi - lo); + fa = Distance2(u, v, a); + } + else + { + lo = a; + a = b; + fa = fb; + b = lo + ratio * (hi - lo); + fb = Distance2(u, v, b); + } + } + var kelvin = 1e6 / (0.5 * (lo + hi)); + var duv = SignedDistance(u, v, kelvin); + if (!(Math.Abs(duv) <= MaxDuv)) return null; + return new ColorTemperatureEstimate(kelvin, mcCamy, duv); + } + + /// Estimate from mean linear Rec.709 RGB; null for non-positive or off-locus colours. + public static ColorTemperatureEstimate? Estimate(double red, double green, double blue) + { + if (!(red > 0 && green > 0 && blue > 0) || !double.IsFinite(red + green + blue)) return null; + return Estimate(Chromaticity.FromXyz(Matrix3.Rec709ToXyz * new Vector3D(red, green, blue))); + } + + private static double Distance2(double u, double v, double mired) + { + var (pu, pv) = PlanckianUv(1e6 / mired); + return (u - pu) * (u - pu) + (v - pv) * (v - pv); + } + + /// Distance to the locus point at , signed by the side of the locus normal + /// that points to larger v (the green side). + private static double SignedDistance(double u, double v, double kelvin) + { + var (pu, pv) = PlanckianUv(kelvin); + var (qu, qv) = PlanckianUv(kelvin * 1.001); + // Normal to the locus tangent, oriented towards +v. + double nu = pv - qv, nv = qu - pu; + if (nv < 0) + { + nu = -nu; + nv = -nv; + } + var distance = Math.Sqrt((u - pu) * (u - pu) + (v - pv) * (v - pv)); + return (u - pu) * nu + (v - pv) * nv >= 0 ? distance : -distance; + } +} diff --git a/src/Titano.Core/Analysis/DeflickerEngine.cs b/src/Titano.Core/Analysis/DeflickerEngine.cs new file mode 100644 index 00000000..634dff88 --- /dev/null +++ b/src/Titano.Core/Analysis/DeflickerEngine.cs @@ -0,0 +1,130 @@ +using Titano.Core.Mathematics; + +namespace Titano.Core.Analysis; + +/// Parameters of . +public sealed record DeflickerOptions +{ + public static DeflickerOptions Default { get; } = new(); + + /// Frames in each local fit (see for a recommendation). + public int Window { get; init; } = 21; + + /// Local polynomial degree, 1 or 2. + public int Degree { get; init; } = 1; + + /// Tukey reweighting passes. + public int RobustIterations { get; init; } = 3; + + /// 1 lands every frame on the fitted curve; lower values let trusted frames keep part of their own deviation. + public double Strength { get; init; } = 1; +} + +/// Flicker before and after correction, in EV. +/// RMS frame-to-frame step of the input relative to the fitted curve. +/// The same measure on the target curve. +/// RMS of input minus fitted curve over valid frames. +/// Frames whose robust weight fell below ½. +public sealed record DeflickerDiagnostics(double FlickerBefore, double FlickerAfter, double ResidualRms, int OutlierCount); + +/// Per-frame deflicker result; arrays have one entry per frame. +public sealed record DeflickerResult( + double[] Target, + double[] CorrectionEv, + double[] Fitted, + double[] RobustWeights, + double[] SurvivingFraction, + DeflickerDiagnostics Diagnostics); + +/// +/// Deflicker target curve (BRIEF §11.2): robust LOWESS () of per-frame log2 luminance +/// after removing intentional exposure offsets, then blended per frame. A frame keeps +/// (1 − Strength)·ρ·S of its deviation from the fit, where ρ is its own Tukey weight and S the surviving fraction of +/// its window, so outliers and frames in contaminated windows are pulled fully onto the fit. Corrections are +/// target − measured, in EV. +/// +public static class DeflickerEngine +{ + /// Measured log2 luminance per frame (NaN = unusable frame, corrected by 0). + /// Optional luminance change in EV caused on purpose (e.g. exposure steps); + /// it is removed before fitting and restored in the target so it is never treated as flicker. + public static DeflickerResult Compute(ReadOnlySpan logLuminance, DeflickerOptions? options = null, ReadOnlySpan intentionalOffsets = default) + { + options ??= DeflickerOptions.Default; + if (!(options.Strength >= 0 && options.Strength <= 1)) throw new ArgumentOutOfRangeException(nameof(options), "Strength must lie in [0, 1]."); + var n = logLuminance.Length; + if (!intentionalOffsets.IsEmpty && intentionalOffsets.Length != n) throw new ArgumentException("Offsets must have one value per frame.", nameof(intentionalOffsets)); + + var flat = new double[n]; + for (var i = 0; i < n; i++) flat[i] = logLuminance[i] - Offset(intentionalOffsets, i); + var fit = LocalRegression.Smooth(flat, options.Window, options.Degree, options.RobustIterations); + + var target = new double[n]; + var correction = new double[n]; + var keepScale = 1 - options.Strength; + for (var i = 0; i < n; i++) + { + var offset = Offset(intentionalOffsets, i); + var curve = fit.Fitted[i]; + if (!double.IsFinite(flat[i])) + { + target[i] = curve + offset; + continue; + } + var keep = keepScale * fit.RobustWeights[i] * fit.SurvivingFraction[i]; + target[i] = curve + keep * (flat[i] - curve) + offset; + correction[i] = target[i] - logLuminance[i]; + } + + return new DeflickerResult(target, correction, fit.Fitted, fit.RobustWeights, fit.SurvivingFraction, + Diagnose(flat, fit.Fitted, target, intentionalOffsets, fit.RobustWeights)); + } + + /// + /// Luminance offsets implied by metadata exposure: −(EV − EV of the first known frame). Frames without EV + /// inherit the previous known value. + /// + public static double[] OffsetsFromExposure(ReadOnlySpan exposureValues) + { + var offsets = new double[exposureValues.Length]; + double? reference = null; + double current = 0; + for (var i = 0; i < exposureValues.Length; i++) + { + if (exposureValues[i] is { } ev && double.IsFinite(ev)) + { + reference ??= ev; + current = reference.Value - ev; + } + offsets[i] = current; + } + return offsets; + } + + private static double Offset(ReadOnlySpan offsets, int i) => offsets.IsEmpty || !double.IsFinite(offsets[i]) ? 0 : offsets[i]; + + private static DeflickerDiagnostics Diagnose(double[] flat, double[] fitted, double[] target, ReadOnlySpan offsets, double[] robust) + { + double before = 0, after = 0, residual = 0; + int steps = 0, valid = 0, outliers = 0; + for (var i = 0; i < flat.Length; i++) + { + if (!double.IsFinite(flat[i])) continue; + valid++; + residual += (flat[i] - fitted[i]) * (flat[i] - fitted[i]); + if (robust[i] < 0.5) outliers++; + if (i == 0 || !double.IsFinite(flat[i - 1])) continue; + var curveStep = fitted[i] - fitted[i - 1]; + var inputStep = flat[i] - flat[i - 1] - curveStep; + var outputStep = target[i] - Offset(offsets, i) - (target[i - 1] - Offset(offsets, i - 1)) - curveStep; + before += inputStep * inputStep; + after += outputStep * outputStep; + steps++; + } + return new DeflickerDiagnostics( + steps > 0 ? Math.Sqrt(before / steps) : 0, + steps > 0 ? Math.Sqrt(after / steps) : 0, + valid > 0 ? Math.Sqrt(residual / valid) : 0, + outliers); + } +} diff --git a/src/Titano.Core/Analysis/ExposureProcessor.cs b/src/Titano.Core/Analysis/ExposureProcessor.cs new file mode 100644 index 00000000..06b1b7f7 --- /dev/null +++ b/src/Titano.Core/Analysis/ExposureProcessor.cs @@ -0,0 +1,149 @@ +using System.Numerics; +using System.Runtime.InteropServices; +using Titano.Core.Imaging; + +namespace Titano.Core.Analysis; + +/// Per-channel multiplicative gains in linear light (white balance). +public readonly record struct ChannelGains(double Red, double Green, double Blue) +{ + public static ChannelGains Identity { get; } = new(1, 1, 1); +} + +/// +/// Applies per-frame corrections to linear-light images in place: an EV gain, white-balance channel gains, sky/land +/// gains blended through a soft mask, and an optional hue-preserving highlight soft clip. Vectorised with +/// ; large images are split across cores. A fourth (alpha) channel is left untouched. +/// +public static class ExposureProcessor +{ + private const int ParallelThreshold = 1 << 20; + private const int Chunk = 1 << 16; + + /// When set (0 < knee < 1), values above the knee roll off smoothly towards 1. + public static void Apply(ImageBuffer image, double ev, ChannelGains? gains = null, double? softClipKnee = null) + { + ArgumentNullException.ThrowIfNull(image); + var factors = Factors(image, ev, gains); + var knee = Knee(softClipKnee); + ForChunks(image.PlaneLength, (start, length) => + { + for (var c = 0; c < factors.Length; c++) Scale(image.Plane(c).Slice(start, length), factors[c]); + if (knee is { } k && image.Channels >= 3) SoftClip(image, start, length, k); + }); + } + + /// + /// Sky/land correction: per pixel the gain is 2^landEv + m·(2^skyEv − 2^landEv) with m the sky weight, i.e. + /// gains blend linearly across the feathered transition. + /// + public static void ApplyRegion(ImageBuffer image, ReadOnlyMemory skyMask, double skyEv, double landEv, ChannelGains? gains = null, double? softClipKnee = null) + { + ArgumentNullException.ThrowIfNull(image); + if (skyMask.Length != image.PlaneLength) throw new ArgumentException("Mask must have one weight per pixel.", nameof(skyMask)); + if (!double.IsFinite(skyEv)) throw new ArgumentOutOfRangeException(nameof(skyEv)); + var land = Factors(image, landEv, gains); + var sky = Factors(image, skyEv, gains); + var knee = Knee(softClipKnee); + ForChunks(image.PlaneLength, (start, length) => + { + var m = skyMask.Span.Slice(start, length); + for (var c = 0; c < land.Length; c++) Blend(image.Plane(c).Slice(start, length), m, land[c], sky[c] - land[c]); + if (knee is { } k && image.Channels >= 3) SoftClip(image, start, length, k); + }); + } + + /// Scalar reference of the soft clip: identity up to the knee, then knee + e/(1 + e/(1 − knee)) with + /// e = value − knee, which is C¹ at the knee and approaches 1 asymptotically. + public static float SoftClip(float value, float knee) + { + if (!(value > knee)) return value; + var excess = value - knee; + return knee + excess / (1 + excess / (1 - knee)); + } + + private static float[] Factors(ImageBuffer image, double ev, ChannelGains? gains) + { + if (!double.IsFinite(ev)) throw new ArgumentOutOfRangeException(nameof(ev)); + var scale = Math.Pow(2, ev); + if (image.Channels == 1) return [(float)scale]; + var g = gains ?? ChannelGains.Identity; + if (!(g.Red > 0 && g.Green > 0 && g.Blue > 0) || !double.IsFinite(g.Red + g.Green + g.Blue)) + throw new ArgumentOutOfRangeException(nameof(gains), "Gains must be positive and finite."); + return [(float)(scale * g.Red), (float)(scale * g.Green), (float)(scale * g.Blue)]; + } + + private static float? Knee(double? knee) + { + if (knee is not { } k) return null; + if (!(k > 0 && k < 1)) throw new ArgumentOutOfRangeException(nameof(knee), "Knee must lie in (0, 1)."); + return (float)k; + } + + private static void ForChunks(int length, Action body) + { + if (length < ParallelThreshold) + { + body(0, length); + return; + } + var chunks = (length + Chunk - 1) / Chunk; + Parallel.For(0, chunks, i => + { + var start = i * Chunk; + body(start, Math.Min(Chunk, length - start)); + }); + } + + private static void Scale(Span data, float factor) + { + var vectors = MemoryMarshal.Cast>(data); + var f = new Vector(factor); + for (var i = 0; i < vectors.Length; i++) vectors[i] *= f; + for (var i = vectors.Length * Vector.Count; i < data.Length; i++) data[i] *= factor; + } + + private static void Blend(Span data, ReadOnlySpan mask, float baseFactor, float delta) + { + var vectors = MemoryMarshal.Cast>(data); + var masks = MemoryMarshal.Cast>(mask); + var b = new Vector(baseFactor); + var d = new Vector(delta); + for (var i = 0; i < vectors.Length; i++) vectors[i] *= b + masks[i] * d; + for (var i = vectors.Length * Vector.Count; i < data.Length; i++) data[i] *= baseFactor + mask[i] * delta; + } + + /// Compresses the largest channel with and scales all three + /// channels by the same ratio, so hue and saturation are kept. + private static void SoftClip(ImageBuffer image, int start, int length, float knee) + { + var r = image.Plane(0).Slice(start, length); + var g = image.Plane(1).Slice(start, length); + var b = image.Plane(2).Slice(start, length); + var vr = MemoryMarshal.Cast>(r); + var vg = MemoryMarshal.Cast>(g); + var vb = MemoryMarshal.Cast>(b); + var k = new Vector(knee); + var inverseRange = new Vector(1 / (1 - knee)); + for (var i = 0; i < vr.Length; i++) + { + var m = Vector.Max(vr[i], Vector.Max(vg[i], vb[i])); + if (!Vector.GreaterThanAny(m, k)) continue; + var excess = m - k; + var ratio = (k + excess / (Vector.One + excess * inverseRange)) / m; + var s = Vector.ConditionalSelect(Vector.GreaterThan(m, k), ratio, Vector.One); + vr[i] *= s; + vg[i] *= s; + vb[i] *= s; + } + for (var i = vr.Length * Vector.Count; i < length; i++) + { + var m = MathF.Max(r[i], MathF.Max(g[i], b[i])); + if (!(m > knee)) continue; + var s = SoftClip(m, knee) / m; + r[i] *= s; + g[i] *= s; + b[i] *= s; + } + } +} diff --git a/src/Titano.Core/Analysis/Finding.cs b/src/Titano.Core/Analysis/Finding.cs new file mode 100644 index 00000000..217208d6 --- /dev/null +++ b/src/Titano.Core/Analysis/Finding.cs @@ -0,0 +1,38 @@ +namespace Titano.Core.Analysis; + +public enum FindingSeverity +{ + Info, + Warning, + Error, +} + +/// +/// One explainable analysis result. is a stable resource key (e.g. Advisor.Finding.Gaps) +/// whose localised text is a composite format filled with (Loc.L(Key, Arguments)). +/// +/// Indices of the frames concerned (capped at ). +public sealed record Finding(string Key, FindingSeverity Severity, object[] Arguments, IReadOnlyList Frames) +{ + public const int MaxFrames = 256; +} + +/// Resource keys of the findings produced by the analysis modules. +public static class FindingKeys +{ + public const string NoTimestamps = "Advisor.Finding.NoTimestamps"; + public const string Gaps = "Advisor.Finding.Gaps"; + public const string Sessions = "Advisor.Finding.Sessions"; + public const string IrregularInterval = "Advisor.Finding.IrregularInterval"; + public const string DuplicateTimestamps = "Advisor.Finding.DuplicateTimestamps"; + public const string NonMonotonicTimestamps = "Advisor.Finding.NonMonotonicTimestamps"; + public const string ClockJumps = "Advisor.Finding.ClockJumps"; + public const string ExposureSteps = "Advisor.Finding.ExposureSteps"; + public const string MissingExposure = "Advisor.Finding.MissingExposure"; + public const string CameraChanged = "Advisor.Finding.CameraChanged"; + public const string LensChanged = "Advisor.Finding.LensChanged"; + public const string MixedResolution = "Advisor.Finding.MixedResolution"; + public const string MixedOrientation = "Advisor.Finding.MixedOrientation"; + public const string TimeZoneEstimated = "Advisor.Finding.TimeZoneEstimated"; + public const string DayNightTransition = "Advisor.Finding.DayNightTransition"; +} diff --git a/src/Titano.Core/Analysis/FlickerSpectrum.cs b/src/Titano.Core/Analysis/FlickerSpectrum.cs new file mode 100644 index 00000000..47484cff --- /dev/null +++ b/src/Titano.Core/Analysis/FlickerSpectrum.cs @@ -0,0 +1,87 @@ +using Titano.Core.Mathematics; + +namespace Titano.Core.Analysis; + +/// Parameters of . +public sealed record FlickerSpectrumOptions +{ + public static FlickerSpectrumOptions Default { get; } = new(); + + /// Smallest recommended deflicker window (frames, odd). + public int MinimumWindow { get; init; } = 15; + + /// Largest recommended deflicker window (frames, odd). + public int MaximumWindow { get; init; } = 151; + + /// A periodic peak must reach this autocorrelation (and 3/√n) to count. + public double PeakThreshold { get; init; } = 0.25; +} + +/// r(k) of the detrended luminance for k = 0 … max lag. +/// Period of a periodic flicker component in frames (sub-frame), or null. +/// Frames until r drops below 1/e: the time scale of aperiodic flicker. +/// 4 × (period or correlation length), odd, clamped to the options' bounds. +public sealed record FlickerSpectrumResult(double[] Autocorrelation, double? DominantPeriod, double PeakCorrelation, double CorrelationLength, int RecommendedWindow); + +/// +/// Flicker time scale from the autocorrelation of luminance residuals (BRIEF §10.2): the series is detrended with a +/// wide robust LOWESS, its autocorrelation searched for the strongest peak that follows a negative lobe (a true +/// oscillation), and the deflicker window set to four periods so each local fit averages several cycles. +/// +public static class FlickerSpectrum +{ + public static FlickerSpectrumResult Analyze(ReadOnlySpan logLuminance, FlickerSpectrumOptions? options = null) + { + options ??= FlickerSpectrumOptions.Default; + if (options.MinimumWindow < 3 || options.MaximumWindow < options.MinimumWindow) + throw new ArgumentOutOfRangeException(nameof(options), "Window bounds are invalid."); + var n = logLuminance.Length; + var maxLag = Math.Max(1, n / 4); + var detrendWindow = Math.Clamp(n / 3, 15, 501); + var trend = LocalRegression.Smooth(logLuminance, detrendWindow, degree: 2, robustIterations: 2).Fitted; + var residual = new double[n]; + for (var i = 0; i < n; i++) residual[i] = logLuminance[i] - trend[i]; + var r = new double[maxLag + 1]; + Statistics.Autocorrelation(residual, r); + + var threshold = Math.Max(options.PeakThreshold, 3 / Math.Sqrt(Math.Max(1, n))); + var seenNegative = false; + var peaks = new List(); + for (var k = 1; k < maxLag; k++) + { + if (r[k] < 0) seenNegative = true; + if (k >= 2 && seenNegative && r[k] >= threshold && r[k] >= r[k - 1] && r[k] > r[k + 1]) peaks.Add(k); + } + // The fundamental is the first peak close to the strongest: when the period falls between lags, a multiple + // of it can land on a lag and outscore it. + var best = -1; + if (peaks.Count > 0) + { + var strongest = peaks.Max(k => r[k]); + best = peaks.First(k => r[k] >= 0.8 * strongest); + } + + double? period = null; + if (best > 0) + { + var denominator = r[best - 1] - 2 * r[best] + r[best + 1]; + var shift = denominator < 0 ? 0.5 * (r[best - 1] - r[best + 1]) / denominator : 0; + period = best + Math.Clamp(shift, -0.5, 0.5); + } + + var correlationLength = (double)maxLag; + for (var k = 1; k <= maxLag; k++) + { + if (r[k] >= 1 / Math.E) continue; + // Linear interpolation of the 1/e crossing between k − 1 and k. + correlationLength = k - 1 + (r[k - 1] - 1 / Math.E) / (r[k - 1] - r[k]); + break; + } + + var scale = period ?? correlationLength; + var window = (int)Math.Round(4 * scale); + window = Math.Clamp(window, options.MinimumWindow, options.MaximumWindow); + if (window % 2 == 0) window = window + 1 <= options.MaximumWindow ? window + 1 : window - 1; + return new FlickerSpectrumResult(r, period, best > 0 ? r[best] : 0, correlationLength, window); + } +} diff --git a/src/Titano.Core/Analysis/FrameStatistics.cs b/src/Titano.Core/Analysis/FrameStatistics.cs new file mode 100644 index 00000000..e817906d --- /dev/null +++ b/src/Titano.Core/Analysis/FrameStatistics.cs @@ -0,0 +1,268 @@ +using Titano.Core.Imaging; +using Titano.Core.Mathematics; + +namespace Titano.Core.Analysis; + +/// Thresholds for . +public sealed record FrameStatisticsOptions +{ + public static FrameStatisticsOptions Default { get; } = new(); + + /// Weight fraction trimmed from the dark end of the log-luminance distribution. + public double TrimLow { get; init; } = 0.02; + + /// Weight fraction trimmed from the bright end. + public double TrimHigh { get; init; } = 0.02; + + /// A pixel is crushed when every channel is below this linear level (1/1024 ≈ −10 EV). + public double ClipLowLevel { get; init; } = 1.0 / 1024; + + /// A pixel is clipped when any channel reaches this fraction of . + public double ClipHighFraction { get; init; } = 0.98; + + public double WhiteLevel { get; init; } = 1.0; +} + +/// +/// Per-frame (or per-region) measurements of the deep analysis (BRIEF §10.2), taken in one pass over a +/// downscaled linear-light image (see ) plus one 3×3 neighbourhood pass. +/// +public sealed record FrameStatistics +{ + public const int HistogramBins = 256; + + /// Lower edge of the log-luminance histogram, in EV relative to linear 1.0. + public const double HistogramMinEv = -14; + + /// Upper edge of the log-luminance histogram, in EV relative to linear 1.0. + public const double HistogramMaxEv = 2; + + public int Width { get; init; } + public int Height { get; init; } + + /// Total sample weight: pixel count, or the mask sum for region statistics. + public double Weight { get; init; } + + /// Mean of log2 luminance after trimming both tails (luminance floored at 2⁻¹⁴). + public double MeanLogLuminance { get; init; } + + /// Weight fraction per bin of log2 luminance over [−14, +2) EV; sums to 1. + public double[] Histogram { get; init; } = []; + + public double ClipLowFraction { get; init; } + public double ClipHighFraction { get; init; } + public double MeanRed { get; init; } + public double MeanGreen { get; init; } + public double MeanBlue { get; init; } + + /// Correlated colour temperature of the mean colour; null when it is not near-Planckian. + public ColorTemperatureEstimate? ColorTemperature { get; init; } + + /// Variance of the 4-neighbour Laplacian of sRGB-encoded luminance (focus/blur measure). + public double Sharpness { get; init; } + + /// Noise standard deviation of sRGB-encoded luminance, Immerkær (1996) fast estimator. + public double Noise { get; init; } + + /// Nearly every pixel is crushed (lens cap, missed exposure). + public bool IsBlack(double fraction = 0.95) => ClipLowFraction >= fraction; + + /// Nearly every pixel is clipped (blown exposure). + public bool IsWhite(double fraction = 0.95) => ClipHighFraction >= fraction; + + /// + /// True when two frames have practically identical statistics (histogram, level, colour, detail, noise): a + /// cheap duplicate test before any pixel or hash comparison. + /// + public static bool AreLikelyDuplicates(FrameStatistics a, FrameStatistics b, double tolerance = 1e-6) + { + ArgumentNullException.ThrowIfNull(a); + ArgumentNullException.ThrowIfNull(b); + if (a.Width != b.Width || a.Height != b.Height || a.Histogram.Length != b.Histogram.Length) return false; + static bool Close(double x, double y, double tolerance) => Math.Abs(x - y) <= tolerance * (1 + Math.Abs(x) + Math.Abs(y)); + return Close(a.MeanLogLuminance, b.MeanLogLuminance, tolerance) + && Statistics.ChiSquareDistance(a.Histogram, b.Histogram) <= tolerance + && Close(a.MeanRed, b.MeanRed, tolerance) + && Close(a.MeanGreen, b.MeanGreen, tolerance) + && Close(a.MeanBlue, b.MeanBlue, tolerance) + && Close(a.Sharpness, b.Sharpness, tolerance) + && Close(a.Noise, b.Noise, tolerance); + } + + /// Measures an image, optionally weighted by a per-pixel in [0, 1]. + public static FrameStatistics Measure(ImageBuffer image, ReadOnlySpan mask = default, FrameStatisticsOptions? options = null) + { + ArgumentNullException.ThrowIfNull(image); + options ??= FrameStatisticsOptions.Default; + ValidateMask(image, mask); + var n = image.PlaneLength; + var r = image.Plane(0); + var g = image.Channels >= 3 ? image.Plane(1) : r; + var b = image.Channels >= 3 ? image.Plane(2) : r; + var low = (float)options.ClipLowLevel; + var high = (float)(options.ClipHighFraction * options.WhiteLevel); + + var histogram = new LogHistogram(); + var encoded = new float[n]; + double weight = 0, clipLow = 0, clipHigh = 0, sumR = 0, sumG = 0, sumB = 0; + for (var i = 0; i < n; i++) + { + var w = mask.IsEmpty ? 1f : mask[i]; + var y = ColorSpace.Luminance(r[i], g[i], b[i]); + encoded[i] = ColorSpace.EncodeFast(y); + if (!(w > 0)) continue; + weight += w; + histogram.Add(y, w); + var max = MathF.Max(r[i], MathF.Max(g[i], b[i])); + if (max < low) clipLow += w; + if (max >= high) clipHigh += w; + sumR += w * r[i]; + sumG += w * g[i]; + sumB += w * b[i]; + } + + var (sharpness, noise) = Detail(encoded, image.Width, image.Height, mask); + var inverse = weight > 0 ? 1 / weight : double.NaN; + var meanR = sumR * inverse; + var meanG = sumG * inverse; + var meanB = sumB * inverse; + return new FrameStatistics + { + Width = image.Width, + Height = image.Height, + Weight = weight, + MeanLogLuminance = histogram.TrimmedMean(options.TrimLow, options.TrimHigh), + Histogram = histogram.Coarse(HistogramBins), + ClipLowFraction = clipLow * inverse, + ClipHighFraction = clipHigh * inverse, + MeanRed = meanR, + MeanGreen = meanG, + MeanBlue = meanB, + ColorTemperature = image.Channels >= 3 ? Analysis.ColorTemperature.Estimate(meanR, meanG, meanB) : null, + Sharpness = sharpness, + Noise = noise, + }; + } + + /// Only the trimmed mean of log2 luminance (the deflicker signal), optionally mask-weighted. + public static double MeasureLogLuminance(ImageBuffer image, ReadOnlySpan mask = default, double trimLow = 0.02, double trimHigh = 0.02) + { + ArgumentNullException.ThrowIfNull(image); + ValidateMask(image, mask); + var r = image.Plane(0); + var g = image.Channels >= 3 ? image.Plane(1) : r; + var b = image.Channels >= 3 ? image.Plane(2) : r; + var histogram = new LogHistogram(); + for (var i = 0; i < r.Length; i++) + { + var w = mask.IsEmpty ? 1f : mask[i]; + if (w > 0) histogram.Add(ColorSpace.Luminance(r[i], g[i], b[i]), w); + } + return histogram.TrimmedMean(trimLow, trimHigh); + } + + private static void ValidateMask(ImageBuffer image, ReadOnlySpan mask) + { + if (!mask.IsEmpty && mask.Length != image.PlaneLength) + throw new ArgumentException("Mask must have one weight per pixel.", nameof(mask)); + } + + /// Laplacian variance and Immerkær noise σ over interior pixels, weighted by the mask at the centre. + private static (double Sharpness, double Noise) Detail(float[] e, int width, int height, ReadOnlySpan mask) + { + if (width < 3 || height < 3) return (0, 0); + double sw = 0, sl = 0, sl2 = 0, sn = 0; + for (var y = 1; y < height - 1; y++) + { + var row = y * width; + for (var x = 1; x < width - 1; x++) + { + var i = row + x; + var w = mask.IsEmpty ? 1f : mask[i]; + if (!(w > 0)) continue; + double up = e[i - width], down = e[i + width], left = e[i - 1], right = e[i + 1], c = e[i]; + var laplacian = up + down + left + right - 4 * c; + var immerkaer = e[i - width - 1] + e[i - width + 1] + e[i + width - 1] + e[i + width + 1] + - 2 * (up + down + left + right) + 4 * c; + sw += w; + sl += w * laplacian; + sl2 += w * laplacian * laplacian; + sn += w * Math.Abs(immerkaer); + } + } + if (!(sw > 0)) return (0, 0); + var mean = sl / sw; + return (Math.Max(0, sl2 / sw - mean * mean), Math.Sqrt(Math.PI / 2) / 6 * sn / sw); + } + + /// + /// Weighted histogram of log2 luminance with 1/256 EV bins over [−14, +2) that also keeps the weighted sum of + /// the exact log values per bin, so trimmed means are exact except for the one partially trimmed bin per tail. + /// + private sealed class LogHistogram + { + private const int BinsPerEv = 256; + private const int Count = (int)(HistogramMaxEv - HistogramMinEv) * BinsPerEv; + private readonly double[] _weight = new double[Count]; + private readonly double[] _sum = new double[Count]; + + public void Add(float luminance, float weight) + { + var log = luminance > 6.1035156e-05f ? Math.Log2(luminance) : HistogramMinEv; + var bin = (int)((log - HistogramMinEv) * BinsPerEv); + bin = Math.Clamp(bin, 0, Count - 1); + _weight[bin] += weight; + _sum[bin] += weight * log; + } + + public double TrimmedMean(double trimLow, double trimHigh) + { + if (!(trimLow >= 0 && trimHigh >= 0 && trimLow + trimHigh < 1)) + throw new ArgumentOutOfRangeException(nameof(trimLow), "Trim fractions must be ≥ 0 and sum below 1."); + double total = 0; + foreach (var w in _weight) total += w; + if (!(total > 0)) return double.NaN; + var kept = (double[])_weight.Clone(); + var remaining = trimLow * total; + for (var i = 0; i < Count && remaining > 0; i++) + { + var take = Math.Min(kept[i], remaining); + kept[i] -= take; + remaining -= take; + } + remaining = trimHigh * total; + for (var i = Count - 1; i >= 0 && remaining > 0; i--) + { + var take = Math.Min(kept[i], remaining); + kept[i] -= take; + remaining -= take; + } + double keptWeight = 0, keptSum = 0; + for (var i = 0; i < Count; i++) + { + if (!(kept[i] > 0)) continue; + keptWeight += kept[i]; + keptSum += _sum[i] * (kept[i] / _weight[i]); + } + return keptWeight > 0 ? keptSum / keptWeight : double.NaN; + } + + /// Normalised coarse histogram (bins must divide the fine bin count). + public double[] Coarse(int bins) + { + var result = new double[bins]; + var group = Count / bins; + double total = 0; + for (var i = 0; i < Count; i++) + { + result[i / group] += _weight[i]; + total += _weight[i]; + } + if (total > 0) + { + for (var i = 0; i < bins; i++) result[i] /= total; + } + return result; + } + } +} diff --git a/src/Titano.Core/Analysis/HolyGrailEngine.cs b/src/Titano.Core/Analysis/HolyGrailEngine.cs new file mode 100644 index 00000000..38c4e5ca --- /dev/null +++ b/src/Titano.Core/Analysis/HolyGrailEngine.cs @@ -0,0 +1,221 @@ +using Titano.Core.Mathematics; + +namespace Titano.Core.Analysis; + +/// Parameters of . +public sealed record HolyGrailOptions +{ + public static HolyGrailOptions Default { get; } = new(); + + /// Transition length in frames; null = half the typical distance between received steps. + public int? TransitionFrames { get; init; } + + /// Transition length when fewer than two steps were received and none is configured. + public int SingleStepTransitionFrames { get; init; } = 12; + + /// Largest allowed frame-to-frame change of the target curve, in EV. + public double MaxStepEv { get; init; } = 0.3; + + /// Metadata EV changes smaller than this are not steps. + public double MinimumStepEv { get; init; } = 0.05; + + /// A step is received when the measured jump has the expected sign and at least this fraction of its size. + public double MinimumReceivedFraction { get; init; } = 0.5; + + /// Frames measured on each side of a step. + public int MeasureFrames { get; init; } = 6; + + public DeflickerOptions Deflicker { get; init; } = DeflickerOptions.Default; +} + +/// One metadata exposure step and how it was redistributed. +/// First frame shot with the new settings. +/// Luminance change implied by the metadata (−ΔEV). +/// Detrended luminance jump measured across the step (NaN when not measurable). +/// Whether the pixels actually changed; ignored steps get no transition. +/// Frame position where the smooth transition starts (fractional). +/// Transition length in frames (0 when not received). +public sealed record ExposureTransition(int Index, double ExpectedEv, double MeasuredEv, bool Received, double Start, double Length); + +/// Target log2 luminance per frame. +/// Target − measured. +/// Cumulative received steps (the abrupt exposure offsets in the pixels). +/// The same steps spread over their transitions. +/// Largest |Target[i] − Target[i−1]|. +public sealed record HolyGrailResult( + double[] Target, + double[] CorrectionEv, + double[] StepOffsets, + double[] SmoothedOffsets, + IReadOnlyList Transitions, + DeflickerResult Deflicker, + double MaxFrameStepEv); + +/// +/// Holy-grail exposure-step redistribution (BRIEF §10.3, §11.2). Metadata EV steps are checked against the measured +/// luminance (detrended medians on both sides), steps the pixels did not receive are ignored, and each received step +/// is removed from the series, the step-free series deflickered, and the step added back as a smoothstep transition +/// centred on it. Transitions lengthen until no frame-to-frame change of the target exceeds +/// ; ramps are kept inside the sequence so the total change is preserved. +/// +public static class HolyGrailEngine +{ + /// Measured log2 luminance per frame (NaN = unusable). + /// Metadata EV (ISO 100) per frame; null when unknown. + public static HolyGrailResult Compute(ReadOnlySpan logLuminance, ReadOnlySpan exposureEv, HolyGrailOptions? options = null) + { + options ??= HolyGrailOptions.Default; + var n = logLuminance.Length; + if (exposureEv.Length != n) throw new ArgumentException("One exposure value per frame is required.", nameof(exposureEv)); + if (!(options.MaxStepEv > 0)) throw new ArgumentOutOfRangeException(nameof(options), "MaxStepEv must be positive."); + var luminance = logLuminance.ToArray(); + + var transitions = DetectSteps(luminance, exposureEv, options); + var offsets = new double[n]; + foreach (var t in transitions) + { + if (!t.Received) continue; + for (var i = t.Index; i < n; i++) offsets[i] += t.ExpectedEv; + } + var flat = new double[n]; + for (var i = 0; i < n; i++) flat[i] = luminance[i] - offsets[i]; + var deflicker = DeflickerEngine.Compute(flat, options.Deflicker); + + var received = transitions.Where(t => t.Received).ToList(); + var lengths = InitialLengths(received, deflicker.Target, n, options); + var smoothed = new double[n]; + var target = new double[n]; + var maxStep = 0.0; + for (var attempt = 0; attempt < 40; attempt++) + { + Ramps(received, lengths, n, smoothed); + for (var i = 0; i < n; i++) target[i] = deflicker.Target[i] + smoothed[i]; + maxStep = MaxStep(target); + if (maxStep <= options.MaxStepEv || lengths.All(l => l >= n - 1)) break; + for (var k = 0; k < lengths.Length; k++) lengths[k] = Math.Min(n - 1, Math.Max(lengths[k] + 1, lengths[k] * 1.25)); + } + + var correction = new double[n]; + for (var i = 0; i < n; i++) correction[i] = double.IsFinite(luminance[i]) ? target[i] - luminance[i] : 0; + var report = new List(transitions.Count); + var r = 0; + foreach (var t in transitions) + { + if (!t.Received) + { + report.Add(t); + continue; + } + report.Add(t with { Start = RampStart(t.Index, lengths[r], n), Length = lengths[r] }); + r++; + } + return new HolyGrailResult(target, correction, offsets, smoothed, report, deflicker, maxStep); + } + + private static List DetectSteps(double[] luminance, ReadOnlySpan exposureEv, HolyGrailOptions options) + { + var candidates = new List<(int Index, double Expected)>(); + double? last = null; + for (var i = 0; i < exposureEv.Length; i++) + { + if (exposureEv[i] is not { } ev || !double.IsFinite(ev)) continue; + if (last is { } p && Math.Abs(ev - p) >= options.MinimumStepEv) candidates.Add((i, -(ev - p))); + last = ev; + } + + var result = new List(candidates.Count); + for (var c = 0; c < candidates.Count; c++) + { + var (index, expected) = candidates[c]; + var from = Math.Max(c > 0 ? candidates[c - 1].Index : 0, index - options.MeasureFrames); + var to = Math.Min(c + 1 < candidates.Count ? candidates[c + 1].Index : luminance.Length, index + options.MeasureFrames); + var measured = MeasureJump(luminance, from, index, to); + var received = double.IsNaN(measured) + || (Math.Sign(measured) == Math.Sign(expected) && Math.Abs(measured) >= options.MinimumReceivedFraction * Math.Abs(expected)); + result.Add(new ExposureTransition(index, expected, measured, received, 0, 0)); + } + return result; + } + + /// + /// Jump between frames [from, index) and [index, to): the scene trend (median first difference on both sides, + /// excluding the step itself) is removed, then the medians of the two sides are compared. NaN when a side has no + /// valid frame. + /// + private static double MeasureJump(double[] luminance, int from, int index, int to) + { + var differences = new List(); + for (var j = from + 1; j < to; j++) + { + if (j == index) continue; + var d = luminance[j] - luminance[j - 1]; + if (double.IsFinite(d)) differences.Add(d); + } + var slope = differences.Count > 0 ? Statistics.Median(differences.ToArray()) : 0; + var left = new List(); + var right = new List(); + for (var j = from; j < to; j++) + { + if (!double.IsFinite(luminance[j])) continue; + var detrended = luminance[j] - slope * (j - (index - 0.5)); + (j < index ? left : right).Add(detrended); + } + if (left.Count == 0 || right.Count == 0) return double.NaN; + return Statistics.Median(right.ToArray()) - Statistics.Median(left.ToArray()); + } + + /// Half the typical spacing of received steps (or the configured length), lengthened per step so a lone + /// smoothstep (peak slope 1.5·|s|/L) fits in the budget left by the scene's own frame-to-frame change. + private static double[] InitialLengths(List received, double[] sceneTarget, int n, HolyGrailOptions options) + { + double baseLength; + if (options.TransitionFrames is { } configured) baseLength = configured; + else if (received.Count >= 2) + { + var spacing = new double[received.Count - 1]; + for (var i = 1; i < received.Count; i++) spacing[i - 1] = received[i].Index - received[i - 1].Index; + baseLength = Math.Round(Statistics.Median(spacing) / 2); + } + else baseLength = options.SingleStepTransitionFrames; + baseLength = Math.Max(2, baseLength); + + var budget = options.MaxStepEv - MaxStep(sceneTarget); + var lengths = new double[received.Count]; + for (var k = 0; k < lengths.Length; k++) + { + var needed = budget > 0 ? Math.Ceiling(1.5 * Math.Abs(received[k].ExpectedEv) / budget) : n - 1; + lengths[k] = Math.Min(Math.Max(1, n - 1), Math.Max(baseLength, needed)); + } + return lengths; + } + + private static void Ramps(List received, double[] lengths, int n, double[] smoothed) + { + Array.Clear(smoothed); + for (var k = 0; k < received.Count; k++) + { + var length = lengths[k]; + var start = RampStart(received[k].Index, length, n); + var amount = received[k].ExpectedEv; + for (var i = 0; i < n; i++) + { + var t = Math.Clamp((i - start) / length, 0, 1); + smoothed[i] += amount * t * t * (3 - 2 * t); + } + } + } + + /// Ramp centred on the boundary between frames index − 1 and index, shifted to lie inside [0, n − 1]. + private static double RampStart(int index, double length, int n) => Math.Clamp(index - 0.5 - length / 2, 0, Math.Max(0, n - 1 - length)); + + private static double MaxStep(double[] series) + { + var max = 0.0; + for (var i = 1; i < series.Length; i++) + { + var d = Math.Abs(series[i] - series[i - 1]); + if (double.IsFinite(d)) max = Math.Max(max, d); + } + return max; + } +} diff --git a/src/Titano.Core/Analysis/LightAnalysisReport.cs b/src/Titano.Core/Analysis/LightAnalysisReport.cs new file mode 100644 index 00000000..501ca433 --- /dev/null +++ b/src/Titano.Core/Analysis/LightAnalysisReport.cs @@ -0,0 +1,135 @@ +using Titano.Core.Mathematics; + +namespace Titano.Core.Analysis; + +/// Parameters of . +public sealed record LightAnalysisOptions +{ + public static LightAnalysisOptions Default { get; } = new(); + + /// A pause at least this long starts a new capture session. + public double SessionGapMinutes { get; init; } = 45; + + /// Sessions with fewer frames merge into the previous session (the first into the next). + public int MinimumSessionFrames { get; init; } = 8; + + /// An interval longer than this multiple of the median interval is a gap. + public double GapFactor { get; init; } = 3; + + /// Relative shutter-time or f-number change treated as a deliberate setting change. + public double ExposureTolerance { get; init; } = 0.01; + + /// Interval jitter (MAD) above this fraction of the median interval is reported. + public double IrregularIntervalFraction { get; init; } = 0.1; +} + +/// How the interval leading into a frame was classified. +public enum IntervalKind +{ + Regular, + + /// Longer than × the median interval. + Gap, + + /// At least . + SessionBreak, + + /// Same capture time as the previous frame. + Duplicate, + + /// Small step backwards in time (frames out of order). + NonMonotonic, + + /// Camera clock change: a backward step longer than the gap threshold, or a step exactly one hour off + /// the cadence (daylight-saving change). + ClockJump, +} + +/// The interval between the previous timed frame and frame . +public readonly record struct FrameInterval(int Index, double Seconds, IntervalKind Kind); + +/// A run of frames shot without a pause of or more. +public sealed record CaptureSession(int StartIndex, int EndIndex, DateTime? Start, DateTime? End) +{ + public int FrameCount => EndIndex - StartIndex + 1; +} + +[Flags] +public enum ExposureChange +{ + None = 0, + Shutter = 1, + Aperture = 2, + Iso = 4, +} + +/// A change of exposure settings between frame − 1 and . +public sealed record ExposureStep(int Index, ExposureChange Changes, double EvBefore, double EvAfter) +{ + /// Camera EV change; the pixels brighten by − stops. + public double DeltaEv => EvAfter - EvBefore; +} + +public enum IdentityKind +{ + Camera, + Lens, +} + +/// The camera body or lens differs from the previous frame that recorded one. +public sealed record IdentityChange(int Index, IdentityKind Kind, string? Before, string After); + +/// Result of the metadata-only light analysis (BRIEF §10.1). Frame indices are positions in the input list. +public sealed record LightAnalysisReport +{ + public int FrameCount { get; init; } + public int TimedFrameCount { get; init; } + + /// Median of the positive intervals shorter than the session gap, in seconds. + public double? MedianIntervalSeconds { get; init; } + + /// Median absolute deviation of the regular intervals, in seconds. + public double? JitterSeconds { get; init; } + + public DateTime? FirstCapture { get; init; } + public DateTime? LastCapture { get; init; } + + /// Capture duration on the clock-corrected timeline (clock jumps count as one median interval). + public TimeSpan CaptureSpan { get; init; } + + /// Camera clock per frame with clock jumps and backward steps removed; null for untimed frames. + public DateTime?[] AdjustedTimes { get; init; } = []; + + /// Every interval between consecutive timed frames. + public IReadOnlyList Intervals { get; init; } = []; + + /// Intervals classified as or . + public IReadOnlyList Gaps { get; init; } = []; + + /// Duplicate, non-monotonic and clock-jump intervals. + public IReadOnlyList TimestampIssues { get; init; } = []; + + public IReadOnlyList Sessions { get; init; } = []; + + /// EV at ISO 100 per frame; null when shutter time or f-number is missing. + public double?[] ExposureValues { get; init; } = []; + + public IReadOnlyList ExposureSteps { get; init; } = []; + + /// Median number of frames between consecutive exposure steps (null with fewer than two steps). + public double? TypicalStepDistance { get; init; } + + public IReadOnlyList IdentityChanges { get; init; } = []; + + /// Most common oriented size, null when no frame records its size. + public (int Width, int Height)? DominantSize { get; init; } + + public IReadOnlyList ResolutionOutliers { get; init; } = []; + public int DominantOrientation { get; init; } = 1; + public IReadOnlyList OrientationOutliers { get; init; } = []; + + /// Light condition per frame from GPS position and capture time; all null without GPS. + public DayPhase?[] DayPhases { get; init; } = []; + + public IReadOnlyList Findings { get; init; } = []; +} diff --git a/src/Titano.Core/Analysis/LightAnalyzer.cs b/src/Titano.Core/Analysis/LightAnalyzer.cs new file mode 100644 index 00000000..0fc5dc9b --- /dev/null +++ b/src/Titano.Core/Analysis/LightAnalyzer.cs @@ -0,0 +1,390 @@ +using Titano.Core.Mathematics; +using Titano.Core.Model; + +namespace Titano.Core.Analysis; + +/// +/// Metadata-only sequence analysis run at import/scan (BRIEF §10.1): cadence, gaps and sessions, timestamp +/// sanity, exposure series and steps, camera/lens identity, size and orientation consistency, and day phases +/// from GPS. Linear in the number of frames apart from two medians; deterministic. +/// +public static class LightAnalyzer +{ + private const double SameTimeSeconds = 0.001; + private const double Hour = 3600; + + public static LightAnalysisReport Analyze(IReadOnlyList frames, LightAnalysisOptions? options = null) + { + ArgumentNullException.ThrowIfNull(frames); + var light = new LightFrame[frames.Count]; + for (var i = 0; i < light.Length; i++) light[i] = LightFrame.From(frames[i]); + return Analyze(light, options); + } + + public static LightAnalysisReport Analyze(IReadOnlyList frames, LightAnalysisOptions? options = null) + { + ArgumentNullException.ThrowIfNull(frames); + options ??= LightAnalysisOptions.Default; + if (!(options.GapFactor > 1)) throw new ArgumentOutOfRangeException(nameof(options), "GapFactor must exceed 1."); + var findings = new List(); + var timing = AnalyzeTiming(frames, options, findings); + var exposure = AnalyzeExposure(frames, options, findings); + var identity = AnalyzeIdentity(frames, findings); + var (dominantSize, sizeOutliers, orientation, orientationOutliers) = AnalyzeGeometry(frames, findings); + var phases = AnalyzeDayPhases(frames, timing.Adjusted, findings); + + return new LightAnalysisReport + { + FrameCount = frames.Count, + TimedFrameCount = timing.TimedCount, + MedianIntervalSeconds = timing.Median, + JitterSeconds = timing.Jitter, + FirstCapture = timing.First, + LastCapture = timing.Last, + CaptureSpan = timing.Span, + AdjustedTimes = timing.Adjusted, + Intervals = timing.Intervals, + Gaps = timing.Intervals.Where(i => i.Kind is IntervalKind.Gap or IntervalKind.SessionBreak).ToList(), + TimestampIssues = timing.Intervals.Where(i => i.Kind is IntervalKind.Duplicate or IntervalKind.NonMonotonic or IntervalKind.ClockJump).ToList(), + Sessions = timing.Sessions, + ExposureValues = exposure.Values, + ExposureSteps = exposure.Steps, + TypicalStepDistance = exposure.TypicalDistance, + IdentityChanges = identity, + DominantSize = dominantSize, + ResolutionOutliers = sizeOutliers, + DominantOrientation = orientation, + OrientationOutliers = orientationOutliers, + DayPhases = phases, + Findings = findings, + }; + } + + private sealed record Timing( + int TimedCount, + double? Median, + double? Jitter, + DateTime? First, + DateTime? Last, + TimeSpan Span, + DateTime?[] Adjusted, + List Intervals, + List Sessions); + + private static Timing AnalyzeTiming(IReadOnlyList frames, LightAnalysisOptions options, List findings) + { + var n = frames.Count; + var sessionGap = options.SessionGapMinutes * 60; + var raw = new List<(int Index, double Seconds)>(); + int? previous = null; + var timedCount = 0; + for (var i = 0; i < n; i++) + { + if (frames[i].CapturedAt is not { } t) continue; + timedCount++; + if (previous is { } p) raw.Add((i, (t - frames[p].CapturedAt!.Value).TotalSeconds)); + previous = i; + } + if (timedCount < 2 && n >= 2) + findings.Add(new Finding(FindingKeys.NoTimestamps, FindingSeverity.Warning, [timedCount, n], [])); + + var cadence = raw.Where(d => d.Seconds > SameTimeSeconds && d.Seconds < sessionGap).Select(d => d.Seconds).ToArray(); + if (cadence.Length == 0) cadence = raw.Where(d => d.Seconds > SameTimeSeconds).Select(d => d.Seconds).ToArray(); + double? median = cadence.Length > 0 ? Statistics.Median(cadence) : null; + double? jitter = null; + if (median is { } m) + { + var regular = raw.Where(d => d.Seconds > SameTimeSeconds && d.Seconds <= options.GapFactor * m).Select(d => d.Seconds).ToArray(); + jitter = regular.Length > 0 ? Statistics.MedianAbsoluteDeviation(regular) : 0; + } + var tolerance = median is { } med ? Math.Max(2, Math.Max(3 * Statistics.MadToSigma * (jitter ?? 0), 0.05 * med)) : 0; + + var intervals = new List(raw.Count); + foreach (var (index, seconds) in raw) + intervals.Add(new FrameInterval(index, seconds, Classify(seconds, median, tolerance, sessionGap, options.GapFactor))); + + // Clock-corrected timeline: jumps count as one cadence step, backward steps as none. + var adjusted = new DateTime?[n]; + var first = -1; + var last = -1; + for (var i = 0; i < n; i++) + { + if (frames[i].CapturedAt is null) continue; + if (first < 0) first = i; + last = i; + } + if (first >= 0) adjusted[first] = frames[first].CapturedAt; + var previousTimed = first; + foreach (var interval in intervals) + { + var advance = interval.Kind switch + { + IntervalKind.ClockJump => median ?? 0, + IntervalKind.Duplicate or IntervalKind.NonMonotonic => 0, + _ => interval.Seconds, + }; + adjusted[interval.Index] = adjusted[previousTimed]!.Value.AddSeconds(advance); + previousTimed = interval.Index; + } + var span = first >= 0 ? adjusted[last]!.Value - adjusted[first]!.Value : TimeSpan.Zero; + + var sessions = BuildSessions(frames, intervals, options.MinimumSessionFrames); + ReportTiming(intervals, sessions, median, jitter, options, findings); + return new Timing(timedCount, median, jitter, first >= 0 ? frames[first].CapturedAt : null, last >= 0 ? frames[last].CapturedAt : null, + span, adjusted, intervals, sessions); + } + + private static IntervalKind Classify(double seconds, double? median, double tolerance, double sessionGap, double gapFactor) + { + if (Math.Abs(seconds) < SameTimeSeconds) return IntervalKind.Duplicate; + if (median is not { } m) return seconds < 0 ? IntervalKind.NonMonotonic : IntervalKind.Regular; + // A daylight-saving change shifts the clock by exactly one hour while the cadence continues. Longer + // whole-hour pauses are left alone: scheduled intervalometer breaks look the same. + var hours = Math.Round((seconds - m) / Hour); + var hourAligned = Math.Abs(hours) == 1 && m < Hour / 2 && Math.Abs(seconds - m - hours * Hour) <= tolerance; + if (seconds < 0) return hourAligned || -seconds > gapFactor * m ? IntervalKind.ClockJump : IntervalKind.NonMonotonic; + if (hourAligned) return IntervalKind.ClockJump; + if (seconds >= sessionGap) return IntervalKind.SessionBreak; + return seconds > gapFactor * m ? IntervalKind.Gap : IntervalKind.Regular; + } + + private static List BuildSessions(IReadOnlyList frames, List intervals, int minimumFrames) + { + var n = frames.Count; + var ranges = new List<(int Start, int End)>(); + if (n == 0) return []; + var start = 0; + foreach (var interval in intervals) + { + if (interval.Kind != IntervalKind.SessionBreak) continue; + ranges.Add((start, interval.Index - 1)); + start = interval.Index; + } + ranges.Add((start, n - 1)); + + for (var i = 0; i < ranges.Count && ranges.Count > 1;) + { + if (ranges[i].End - ranges[i].Start + 1 >= minimumFrames) + { + i++; + continue; + } + if (i > 0) + { + ranges[i - 1] = (ranges[i - 1].Start, ranges[i].End); + ranges.RemoveAt(i); + } + else + { + ranges[1] = (ranges[0].Start, ranges[1].End); + ranges.RemoveAt(0); + } + } + + var sessions = new List(ranges.Count); + foreach (var (s, e) in ranges) + { + DateTime? first = null, last = null; + for (var i = s; i <= e; i++) + { + if (frames[i].CapturedAt is not { } t) continue; + first ??= t; + last = t; + } + sessions.Add(new CaptureSession(s, e, first, last)); + } + return sessions; + } + + private static void ReportTiming(List intervals, List sessions, double? median, double? jitter, LightAnalysisOptions options, List findings) + { + var gaps = intervals.Where(i => i.Kind is IntervalKind.Gap or IntervalKind.SessionBreak).ToList(); + if (gaps.Count > 0) + findings.Add(new Finding(FindingKeys.Gaps, FindingSeverity.Warning, [gaps.Count, gaps.Max(g => g.Seconds)], Indices(gaps))); + if (sessions.Count > 1) + findings.Add(new Finding(FindingKeys.Sessions, FindingSeverity.Info, [sessions.Count], Cap(sessions.Select(s => s.StartIndex)))); + if (median is { } m && jitter is { } j && j > options.IrregularIntervalFraction * m) + findings.Add(new Finding(FindingKeys.IrregularInterval, FindingSeverity.Info, [j, m], [])); + AddIssue(intervals, IntervalKind.Duplicate, FindingKeys.DuplicateTimestamps, findings); + AddIssue(intervals, IntervalKind.NonMonotonic, FindingKeys.NonMonotonicTimestamps, findings); + var jumps = intervals.Where(i => i.Kind == IntervalKind.ClockJump).ToList(); + if (jumps.Count > 0) + { + var largest = jumps.MaxBy(i => Math.Abs(i.Seconds - (median ?? 0))); + findings.Add(new Finding(FindingKeys.ClockJumps, FindingSeverity.Warning, [jumps.Count, largest.Seconds - (median ?? 0)], Indices(jumps))); + } + } + + private static void AddIssue(List intervals, IntervalKind kind, string key, List findings) + { + var issues = intervals.Where(i => i.Kind == kind).ToList(); + if (issues.Count > 0) findings.Add(new Finding(key, FindingSeverity.Warning, [issues.Count], Indices(issues))); + } + + private sealed record Exposure(double?[] Values, List Steps, double? TypicalDistance); + + private static Exposure AnalyzeExposure(IReadOnlyList frames, LightAnalysisOptions options, List findings) + { + var n = frames.Count; + var values = new double?[n]; + var steps = new List(); + var missing = new List(); + var logTolerance = Math.Log(1 + options.ExposureTolerance); + var previous = -1; + for (var i = 0; i < n; i++) + { + var f = frames[i]; + values[i] = f.ExposureValue; + if (values[i] is null) + { + missing.Add(i); + continue; + } + if (previous >= 0) + { + var p = frames[previous]; + var changes = ExposureChange.None; + if (Math.Abs(Math.Log(f.ExposureTime!.Value / p.ExposureTime!.Value)) > logTolerance) changes |= ExposureChange.Shutter; + if (Math.Abs(Math.Log(f.FNumber!.Value / p.FNumber!.Value)) > logTolerance) changes |= ExposureChange.Aperture; + if ((f.Iso ?? 100) != (p.Iso ?? 100)) changes |= ExposureChange.Iso; + if (changes != ExposureChange.None) steps.Add(new ExposureStep(i, changes, values[previous]!.Value, values[i]!.Value)); + } + previous = i; + } + + double? typical = null; + if (steps.Count >= 2) + { + var distances = new double[steps.Count - 1]; + for (var i = 1; i < steps.Count; i++) distances[i - 1] = steps[i].Index - steps[i - 1].Index; + typical = Statistics.Median(distances); + } + if (steps.Count > 0) + { + var total = steps.Sum(s => s.DeltaEv); + findings.Add(new Finding(FindingKeys.ExposureSteps, FindingSeverity.Info, [steps.Count, typical ?? 0, total], Cap(steps.Select(s => s.Index)))); + } + if (missing.Count > 0 && n > 0) + findings.Add(new Finding(FindingKeys.MissingExposure, FindingSeverity.Info, [missing.Count], Cap(missing))); + return new Exposure(values, steps, typical); + } + + private static List AnalyzeIdentity(IReadOnlyList frames, List findings) + { + var changes = new List(); + string? camera = null, lens = null; + for (var i = 0; i < frames.Count; i++) + { + var f = frames[i]; + var body = Join(f.CameraMake, f.CameraModel, f.CameraSerial); + if (body is not null) + { + if (camera is not null && !string.Equals(camera, body, StringComparison.Ordinal)) + changes.Add(new IdentityChange(i, IdentityKind.Camera, camera, body)); + camera = body; + } + var l = string.IsNullOrWhiteSpace(f.Lens) ? null : f.Lens.Trim(); + if (l is not null) + { + if (lens is not null && !string.Equals(lens, l, StringComparison.Ordinal)) + changes.Add(new IdentityChange(i, IdentityKind.Lens, lens, l)); + lens = l; + } + } + var bodyChanges = changes.Where(c => c.Kind == IdentityKind.Camera).Select(c => c.Index).ToList(); + if (bodyChanges.Count > 0) findings.Add(new Finding(FindingKeys.CameraChanged, FindingSeverity.Warning, [bodyChanges.Count], Cap(bodyChanges))); + var lensChanges = changes.Where(c => c.Kind == IdentityKind.Lens).Select(c => c.Index).ToList(); + if (lensChanges.Count > 0) findings.Add(new Finding(FindingKeys.LensChanged, FindingSeverity.Warning, [lensChanges.Count], Cap(lensChanges))); + return changes; + } + + private static string? Join(params string?[] parts) + { + var present = parts.Where(p => !string.IsNullOrWhiteSpace(p)).Select(p => p!.Trim()).ToArray(); + return present.Length == 0 ? null : string.Join(' ', present); + } + + private static ((int, int)? Size, List SizeOutliers, int Orientation, List OrientationOutliers) AnalyzeGeometry(IReadOnlyList frames, List findings) + { + var sizes = new Dictionary<(int, int), int>(); + var orientations = new Dictionary(); + foreach (var f in frames) + { + if (f.Width > 0 && f.Height > 0) sizes[f.OrientedSize] = sizes.GetValueOrDefault(f.OrientedSize) + 1; + orientations[f.Orientation] = orientations.GetValueOrDefault(f.Orientation) + 1; + } + // Dictionaries preserve first-insertion order here (no removals), so ties go to the first value seen. + (int, int)? dominant = sizes.Count > 0 ? sizes.MaxBy(kv => kv.Value).Key : null; + var orientation = orientations.Count > 0 ? orientations.MaxBy(kv => kv.Value).Key : 1; + var sizeOutliers = new List(); + var orientationOutliers = new List(); + for (var i = 0; i < frames.Count; i++) + { + var f = frames[i]; + if (dominant is { } d && f.Width > 0 && f.Height > 0 && f.OrientedSize != d) sizeOutliers.Add(i); + if (f.Orientation != orientation) orientationOutliers.Add(i); + } + if (sizeOutliers.Count > 0 && dominant is { } ds) + findings.Add(new Finding(FindingKeys.MixedResolution, FindingSeverity.Warning, [sizeOutliers.Count, ds.Item1, ds.Item2], Cap(sizeOutliers))); + if (orientationOutliers.Count > 0) + findings.Add(new Finding(FindingKeys.MixedOrientation, FindingSeverity.Warning, [orientationOutliers.Count], Cap(orientationOutliers))); + return (dominant, sizeOutliers, orientation, orientationOutliers); + } + + private static DayPhase?[] AnalyzeDayPhases(IReadOnlyList frames, DateTime?[] adjusted, List findings) + { + var n = frames.Count; + var phases = new DayPhase?[n]; + (double Lat, double Lon)? fallback = null; + int? sequenceOffset = null; + foreach (var f in frames) + { + fallback ??= Location(f); + sequenceOffset ??= Offset(f); + } + if (fallback is not { } site) return phases; + if (sequenceOffset is null) + { + // No recorded offset: assume the nominal zone of the longitude. + sequenceOffset = (int)Math.Round(site.Lon / 15) * 60; + findings.Add(new Finding(FindingKeys.TimeZoneEstimated, FindingSeverity.Info, [sequenceOffset.Value], [])); + } + + int day = 0, twilight = 0, night = 0; + for (var i = 0; i < n; i++) + { + if (adjusted[i] is not { } local) continue; + var (lat, lon) = Location(frames[i]) ?? site; + var utc = DateTime.SpecifyKind(local.AddMinutes(-(Offset(frames[i]) ?? sequenceOffset.Value)), DateTimeKind.Utc); + var phase = SolarPosition.Phase(utc, lat, lon); + phases[i] = phase; + switch (phase) + { + case DayPhase.Day or DayPhase.GoldenHour: day++; break; + case DayPhase.Night or DayPhase.AstronomicalTwilight: night++; break; + default: twilight++; break; + } + } + if (day > 0 && night > 0) + findings.Add(new Finding(FindingKeys.DayNightTransition, FindingSeverity.Info, [day, twilight, night], [])); + return phases; + } + + private static (double, double)? Location(LightFrame f) => + f.Latitude is { } lat && f.Longitude is { } lon && lat is >= -90 and <= 90 && lon is >= -180 and <= 180 && (lat != 0 || lon != 0) + ? (lat, lon) + : null; + + /// Recorded UTC offset, else the camera-clock minus GPS-time difference rounded to 15 minutes. + private static int? Offset(LightFrame f) + { + if (f.UtcOffsetMinutes is { } recorded) return recorded; + if (f.CapturedAt is not { } local || f.GpsUtc is not { } gps) return null; + var minutes = (local - gps).TotalMinutes; + return Math.Abs(minutes) <= 14 * 60 ? (int)Math.Round(minutes / 15) * 15 : null; + } + + private static List Indices(List intervals) => Cap(intervals.Select(i => i.Index)); + + private static List Cap(IEnumerable indices) => indices.Take(Finding.MaxFrames).ToList(); +} diff --git a/src/Titano.Core/Analysis/LightFrame.cs b/src/Titano.Core/Analysis/LightFrame.cs new file mode 100644 index 00000000..40529c0f --- /dev/null +++ b/src/Titano.Core/Analysis/LightFrame.cs @@ -0,0 +1,84 @@ +using Titano.Core.Metadata; +using Titano.Core.Model; + +namespace Titano.Core.Analysis; + +/// The metadata the light analysis needs from one frame (BRIEF §10.1). +public sealed record LightFrame +{ + public int Index { get; init; } + + /// Camera wall-clock capture time (unspecified kind). + public DateTime? CapturedAt { get; init; } + + /// UTC offset of in minutes, when recorded. + public int? UtcOffsetMinutes { get; init; } + + public double? ExposureTime { get; init; } + public double? FNumber { get; init; } + public int? Iso { get; init; } + public double? ExposureBias { get; init; } + public int Width { get; init; } + public int Height { get; init; } + public int Orientation { get; init; } = 1; + public string? CameraMake { get; init; } + public string? CameraModel { get; init; } + public string? CameraSerial { get; init; } + public string? Lens { get; init; } + public double? Latitude { get; init; } + public double? Longitude { get; init; } + + /// GPS (satellite) UTC time stamp, used to infer the camera clock's UTC offset. + public DateTime? GpsUtc { get; init; } + + /// Exposure value at ISO 100: log2(N²/t) − log2(ISO/100). + public double? ExposureValue => ExposureTime is > 0 && FNumber is > 0 + ? Math.Log2(FNumber.Value * FNumber.Value / ExposureTime.Value) - Math.Log2((Iso is > 0 ? Iso.Value : 100) / 100.0) + : null; + + /// Width and height after Exif orientations 5–8 (90° rotations). + public (int Width, int Height) OrientedSize => Orientation is >= 5 and <= 8 ? (Height, Width) : (Width, Height); + + public static LightFrame From(Frame frame) + { + ArgumentNullException.ThrowIfNull(frame); + return new LightFrame + { + Index = frame.Index, + CapturedAt = frame.CapturedAt, + UtcOffsetMinutes = frame.UtcOffsetMinutes, + ExposureTime = frame.ExposureTime, + FNumber = frame.FNumber, + Iso = frame.Iso, + ExposureBias = frame.ExposureBias, + Width = frame.Width, + Height = frame.Height, + Orientation = frame.Orientation, + }; + } + + public static LightFrame From(FrameMetadata metadata, int index) + { + ArgumentNullException.ThrowIfNull(metadata); + return new LightFrame + { + Index = index, + CapturedAt = metadata.CapturedAt, + UtcOffsetMinutes = metadata.UtcOffsetMinutes, + ExposureTime = metadata.ExposureTime, + FNumber = metadata.FNumber, + Iso = metadata.Iso, + ExposureBias = metadata.ExposureBias, + Width = metadata.Width, + Height = metadata.Height, + Orientation = metadata.Orientation, + CameraMake = metadata.Make, + CameraModel = metadata.Model, + CameraSerial = metadata.BodySerial, + Lens = metadata.LensModel, + Latitude = metadata.Gps?.Latitude, + Longitude = metadata.Gps?.Longitude, + GpsUtc = metadata.Gps?.UtcTimestamp, + }; + } +} diff --git a/src/Titano.Core/Analysis/RegionDeflicker.cs b/src/Titano.Core/Analysis/RegionDeflicker.cs new file mode 100644 index 00000000..4f8e0aa7 --- /dev/null +++ b/src/Titano.Core/Analysis/RegionDeflicker.cs @@ -0,0 +1,43 @@ +using Titano.Core.Imaging; + +namespace Titano.Core.Analysis; + +/// Independent deflicker curves for the sky and land regions. +public sealed record RegionDeflickerResult(DeflickerResult Sky, DeflickerResult Land); + +/// +/// Region deflicker (BRIEF §11.2): sky and land are measured through the soft , each gets its +/// own target curve, and the two corrections are blended per pixel through the mask. +/// Use it when the regions flicker independently (moving clouds, city lights) and the mask confidence is high. +/// +public static class RegionDeflicker +{ + /// Trimmed-mean log2 luminance of the sky and land regions of one analysis image. + public static (double Sky, double Land) Measure(ImageBuffer analysisImage, RegionMask mask, double trimLow = 0.02, double trimHigh = 0.02) + { + ArgumentNullException.ThrowIfNull(analysisImage); + ArgumentNullException.ThrowIfNull(mask); + if (mask.Width != analysisImage.Width || mask.Height != analysisImage.Height) + throw new ArgumentException("Mask and image sizes differ.", nameof(mask)); + return (FrameStatistics.MeasureLogLuminance(analysisImage, mask.Sky, trimLow, trimHigh), + FrameStatistics.MeasureLogLuminance(analysisImage, mask.Land, trimLow, trimHigh)); + } + + public static RegionDeflickerResult Compute(ReadOnlySpan skyLogLuminance, ReadOnlySpan landLogLuminance, DeflickerOptions? options = null, ReadOnlySpan intentionalOffsets = default) + { + if (skyLogLuminance.Length != landLogLuminance.Length) throw new ArgumentException("Series lengths differ.", nameof(landLogLuminance)); + return new RegionDeflickerResult( + DeflickerEngine.Compute(skyLogLuminance, options, intentionalOffsets), + DeflickerEngine.Compute(landLogLuminance, options, intentionalOffsets)); + } + + /// Applies one frame's sky and land corrections (EV) in place; the mask is resampled to the image size + /// when needed (resample once up front when rendering many frames). + public static void Apply(ImageBuffer image, RegionMask mask, double skyEv, double landEv, ChannelGains? gains = null, double? softClipKnee = null) + { + ArgumentNullException.ThrowIfNull(image); + ArgumentNullException.ThrowIfNull(mask); + var fitted = mask.Resample(image.Width, image.Height); + ExposureProcessor.ApplyRegion(image, fitted.Sky, skyEv, landEv, gains, softClipKnee); + } +} diff --git a/src/Titano.Core/Analysis/RegionMask.cs b/src/Titano.Core/Analysis/RegionMask.cs new file mode 100644 index 00000000..c7c1a22c --- /dev/null +++ b/src/Titano.Core/Analysis/RegionMask.cs @@ -0,0 +1,98 @@ +namespace Titano.Core.Analysis; + +public enum RegionMethod +{ + /// Sky above a per-column horizon line. + Horizon, + + /// Sky = the brighter class of a luminance threshold. + Luminance, +} + +/// Soft sky/land segmentation: per-pixel sky weight in [0, 1] with a feathered transition. +public sealed class RegionMask +{ + private float[]? _land; + + public RegionMask(int width, int height, float[] sky, double[]? horizon, RegionMethod method, double confidence) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + ArgumentNullException.ThrowIfNull(sky); + if (sky.Length != width * height) throw new ArgumentException("One weight per pixel required.", nameof(sky)); + if (horizon is not null && horizon.Length != width) throw new ArgumentException("One horizon row per column required.", nameof(horizon)); + Width = width; + Height = height; + Sky = sky; + Horizon = horizon; + Method = method; + Confidence = confidence; + } + + public int Width { get; } + public int Height { get; } + + /// Sky weight per pixel, row-major (1 = sky, 0 = land). + public float[] Sky { get; } + + /// Land weight per pixel (1 − sky). + public float[] Land + { + get + { + if (_land is not null) return _land; + var land = new float[Sky.Length]; + for (var i = 0; i < land.Length; i++) land[i] = 1 - Sky[i]; + return _land = land; + } + } + + /// Horizon position per column in rows from the top edge (horizon method only). + public double[]? Horizon { get; } + + public RegionMethod Method { get; } + + /// 0 … 1; region deflicker is advisable only when this is high. + public double Confidence { get; } + + /// Bilinear resampling to another resolution (e.g. analysis size → render size), pixel-centre aligned. + public RegionMask Resample(int width, int height) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + if (width == Width && height == Height) return this; + var sky = new float[width * height]; + var sx = (double)Width / width; + var sy = (double)Height / height; + Parallel.For(0, height, y => + { + var fy = Math.Clamp((y + 0.5) * sy - 0.5, 0, Height - 1); + var y0 = (int)fy; + var y1 = Math.Min(y0 + 1, Height - 1); + var ty = (float)(fy - y0); + for (var x = 0; x < width; x++) + { + var fx = Math.Clamp((x + 0.5) * sx - 0.5, 0, Width - 1); + var x0 = (int)fx; + var x1 = Math.Min(x0 + 1, Width - 1); + var tx = (float)(fx - x0); + var top = Sky[y0 * Width + x0] + (Sky[y0 * Width + x1] - Sky[y0 * Width + x0]) * tx; + var bottom = Sky[y1 * Width + x0] + (Sky[y1 * Width + x1] - Sky[y1 * Width + x0]) * tx; + sky[y * width + x] = top + (bottom - top) * ty; + } + }); + double[]? horizon = null; + if (Horizon is not null) + { + horizon = new double[width]; + for (var x = 0; x < width; x++) + { + var fx = Math.Clamp((x + 0.5) * sx - 0.5, 0, Width - 1); + var x0 = (int)fx; + var x1 = Math.Min(x0 + 1, Width - 1); + horizon[x] = (Horizon[x0] + (Horizon[x1] - Horizon[x0]) * (fx - x0)) / sy; + } + } + return new RegionMask(width, height, sky, horizon, Method, Confidence); + } +} diff --git a/src/Titano.Core/Analysis/RegionSegmenter.cs b/src/Titano.Core/Analysis/RegionSegmenter.cs new file mode 100644 index 00000000..043174e1 --- /dev/null +++ b/src/Titano.Core/Analysis/RegionSegmenter.cs @@ -0,0 +1,370 @@ +using Titano.Core.Imaging; +using Titano.Core.Mathematics; + +namespace Titano.Core.Analysis; + +/// Parameters of . +public sealed record RegionSegmenterOptions +{ + public static RegionSegmenterOptions Default { get; } = new(); + + /// Frames sampled evenly from the sequence. + public int MaxFrames { get; init; } = 15; + + /// Below this the luminance fallback is tried and the more confident mask wins. + public double MinimumHorizonConfidence { get; init; } = 0.4; + + /// Row-step amplitude in EV that counts as a fully convincing horizon. + public double StrongStepEv { get; init; } = 0.5; + + /// Width of the feathered transition as a fraction of the image height. + public double FeatherFraction { get; init; } = 0.03; + + /// Path penalty per row of vertical movement between adjacent columns, relative to the horizon step. + public double SmoothnessPenalty { get; init; } = 0.05; +} + +/// +/// Sky/land segmentation for region deflicker (BRIEF §10.2, §11.2). Horizon: the strongest step of the +/// column-averaged log-luminance profile (median over frames, so robust to day/night polarity changes), refined per +/// column by a dynamic-programming path that maximises the local step with a smoothness penalty, then feathered. +/// Fallback: Otsu threshold of the temporal-median log luminance (brighter class = sky) cleaned by morphological +/// opening and closing. Each method reports a confidence in [0, 1]. +/// +public static class RegionSegmenter +{ + private const float LogFloor = -14; + + public static RegionMask Segment(IReadOnlyList frames, RegionSegmenterOptions? options = null) + { + ArgumentNullException.ThrowIfNull(frames); + options ??= RegionSegmenterOptions.Default; + if (frames.Count == 0) throw new ArgumentException("At least one frame is required.", nameof(frames)); + var width = frames[0].Width; + var height = frames[0].Height; + foreach (var f in frames) + { + if (f.Width != width || f.Height != height) throw new ArgumentException("Frames must share one size.", nameof(frames)); + } + if (height < 8) throw new ArgumentException("Frames must be at least 8 rows tall.", nameof(frames)); + + var count = Math.Min(Math.Max(1, options.MaxFrames), frames.Count); + var logs = new float[count][]; + Parallel.For(0, count, i => logs[i] = LogLuminance(frames[(int)((long)i * (frames.Count - 1) / Math.Max(1, count - 1))])); + var feather = Math.Max(1.5, options.FeatherFraction * height); + + var (horizon, horizonConfidence) = DetectHorizon(logs, width, height, options); + if (horizon is not null && horizonConfidence >= options.MinimumHorizonConfidence) + return new RegionMask(width, height, HorizonWeights(horizon, width, height, feather), horizon, RegionMethod.Horizon, horizonConfidence); + + var (sky, luminanceConfidence) = LuminanceWeights(logs, width, height, feather); + if (horizon is not null && horizonConfidence >= luminanceConfidence) + return new RegionMask(width, height, HorizonWeights(horizon, width, height, feather), horizon, RegionMethod.Horizon, horizonConfidence); + return new RegionMask(width, height, sky, null, RegionMethod.Luminance, luminanceConfidence); + } + + private static float[] LogLuminance(ImageBuffer image) + { + var y = new float[image.PlaneLength]; + ColorSpace.Luminance(image, y); + for (var i = 0; i < y.Length; i++) y[i] = y[i] > 6.1035156e-05f ? MathF.Log2(y[i]) : LogFloor; + return y; + } + + private static (double[]? Horizon, double Confidence) DetectHorizon(float[][] logs, int width, int height, RegionSegmenterOptions options) + { + var frames = logs.Length; + var k = Math.Max(2, height / 24); + var steps = new float[frames][]; + var profiles = new double[frames][]; + Parallel.For(0, frames, f => (steps[f], profiles[f]) = ColumnSteps(logs[f], width, height, k)); + + var score = new double[height]; + var column = new double[frames]; + for (var y = k; y <= height - k; y++) + { + for (var f = 0; f < frames; f++) column[f] = Math.Abs(profiles[f][y]); + score[y] = Statistics.MedianInPlace(column); + } + var y0 = k; + for (var y = k; y <= height - k; y++) + { + if (score[y] > score[y0]) y0 = y; + } + var peak = score[y0]; + if (!(peak > 1e-6)) return (null, 0); + + double second = 0; + for (var y = k; y <= height - k; y++) + { + if (Math.Abs(y - y0) > 2 * k) second = Math.Max(second, score[y]); + } + var consistent = 0; + var signs = new int[frames]; + for (var f = 0; f < frames; f++) + { + var best = k; + for (var y = k; y <= height - k; y++) + { + if (Math.Abs(profiles[f][y]) > Math.Abs(profiles[f][best])) best = y; + } + if (Math.Abs(best - y0) <= k) consistent++; + signs[f] = profiles[f][y0] < 0 ? -1 : 1; + } + var confidence = Math.Min(1, peak / options.StrongStepEv) * (1 - second / peak) * consistent / frames; + + // Per-column refinement: minimum-cost path through −(signed local step), median over frames. + var band = Math.Max(2 * k, height / 4); + var yLo = Math.Max(k, y0 - band); + var yHi = Math.Min(height - k, y0 + band); + var rows = yHi - yLo + 1; + var cost = new double[width * rows]; + Parallel.For(0, width, x => + { + var values = new double[frames]; + for (var j = 0; j < rows; j++) + { + var i = (yLo + j) * width + x; + for (var f = 0; f < frames; f++) values[f] = signs[f] * steps[f][i]; + cost[x * rows + j] = -Statistics.MedianInPlace(values); + } + }); + var path = MinimumPath(cost, width, rows, Math.Max(2, height / 48), options.SmoothnessPenalty * peak); + + var horizon = new double[width]; + for (var x = 0; x < width; x++) + { + var j = path[x]; + var offset = 0.0; + if (j > 0 && j < rows - 1) + { + double a = cost[x * rows + j - 1], c = cost[x * rows + j], b = cost[x * rows + j + 1]; + var curvature = a - 2 * c + b; + if (curvature > 0) offset = Math.Clamp(0.5 * (a - b) / curvature, -0.5, 0.5); + } + horizon[x] = yLo + j + offset; + } + return (horizon, Math.Clamp(confidence, 0, 1)); + } + + /// + /// Vertical box-difference step (mean of k rows above minus k rows below each row boundary) on a horizontally + /// box-smoothed log image, plus its column average. + /// + private static (float[] Steps, double[] Profile) ColumnSteps(float[] log, int width, int height, int k) + { + var radius = Math.Max(1, width / 64); + var smooth = new float[log.Length]; + var prefix = new double[width + 1]; + for (var y = 0; y < height; y++) + { + var row = y * width; + for (var x = 0; x < width; x++) prefix[x + 1] = prefix[x] + log[row + x]; + for (var x = 0; x < width; x++) + { + var a = Math.Max(0, x - radius); + var b = Math.Min(width, x + radius + 1); + smooth[row + x] = (float)((prefix[b] - prefix[a]) / (b - a)); + } + } + + var steps = new float[log.Length]; + var profile = new double[height]; + var columnPrefix = new double[height + 1]; + for (var x = 0; x < width; x++) + { + for (var y = 0; y < height; y++) columnPrefix[y + 1] = columnPrefix[y] + smooth[y * width + x]; + for (var y = k; y <= height - k; y++) + { + var above = columnPrefix[y] - columnPrefix[y - k]; + var below = columnPrefix[y + k] - columnPrefix[y]; + var step = (above - below) / k; + steps[y * width + x] = (float)step; + profile[y] += step; + } + } + for (var y = 0; y < height; y++) profile[y] /= width; + return (steps, profile); + } + + /// Dynamic programming over columns: each step may move at most rows at a + /// cost of per row. Returns the row index (within the band) per column. + private static int[] MinimumPath(double[] cost, int width, int rows, int slope, double penalty) + { + var energy = new double[width * rows]; + var from = new int[width * rows]; + Array.Copy(cost, energy, rows); + for (var x = 1; x < width; x++) + { + for (var j = 0; j < rows; j++) + { + var best = double.PositiveInfinity; + var arg = j; + for (var d = -slope; d <= slope; d++) + { + var p = j + d; + if (p < 0 || p >= rows) continue; + var e = energy[(x - 1) * rows + p] + penalty * Math.Abs(d); + if (e < best) + { + best = e; + arg = p; + } + } + energy[x * rows + j] = cost[x * rows + j] + best; + from[x * rows + j] = arg; + } + } + var path = new int[width]; + var end = 0; + for (var j = 1; j < rows; j++) + { + if (energy[(width - 1) * rows + j] < energy[(width - 1) * rows + end]) end = j; + } + path[width - 1] = end; + for (var x = width - 1; x > 0; x--) path[x - 1] = from[x * rows + path[x]]; + return path; + } + + private static float[] HorizonWeights(double[] horizon, int width, int height, double feather) + { + var sky = new float[width * height]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var t = Math.Clamp(0.5 + (horizon[x] - (y + 0.5)) / feather, 0, 1); + sky[y * width + x] = (float)(t * t * (3 - 2 * t)); + } + } + return sky; + } + + private static (float[] Sky, double Confidence) LuminanceWeights(float[][] logs, int width, int height, double feather) + { + var n = width * height; + var median = new double[n]; + var values = new double[logs.Length]; + for (var i = 0; i < n; i++) + { + for (var f = 0; f < logs.Length; f++) values[f] = logs[f][i]; + median[i] = Statistics.MedianInPlace(values); + } + + double min = double.PositiveInfinity, max = double.NegativeInfinity; + foreach (var v in median) + { + min = Math.Min(min, v); + max = Math.Max(max, v); + } + if (!(max - min > 1e-6)) return (new float[n], 0); + + var (threshold, separability) = Otsu(median, min, max); + var binary = new byte[n]; + for (var i = 0; i < n; i++) binary[i] = median[i] > threshold ? (byte)1 : (byte)0; + var radius = Math.Max(1, Math.Min(width, height) / 64); + binary = MinMax(MinMax(binary, width, height, radius, dilate: false), width, height, radius, dilate: true); + binary = MinMax(MinMax(binary, width, height, radius, dilate: true), width, height, radius, dilate: false); + + var sky = new float[n]; + for (var i = 0; i < n; i++) sky[i] = binary[i]; + BoxBlur(sky, width, height, Math.Max(1, (int)Math.Round(feather / 2))); + // Otsu's η is 2/π for a single Gaussian mode: rescale so a unimodal image scores 0 and two spikes score 1. + var confidence = Math.Clamp((separability - 2 / Math.PI) / (1 - 2 / Math.PI), 0, 1); + return (sky, confidence); + } + + /// Otsu (1979) threshold over a 256-bin histogram and its separability η = σ²between / σ²total. + private static (double Threshold, double Separability) Otsu(double[] values, double min, double max) + { + const int bins = 256; + var histogram = new double[bins]; + Statistics.AccumulateHistogram(values, min, max + (max - min) * 1e-9, histogram); + var width = (max - min) / bins; + double total = values.Length, sumAll = 0, sumSquares = 0; + for (var i = 0; i < bins; i++) + { + var centre = min + (i + 0.5) * width; + sumAll += histogram[i] * centre; + sumSquares += histogram[i] * centre * centre; + } + var mean = sumAll / total; + var variance = sumSquares / total - mean * mean; + double w0 = 0, sum0 = 0, bestBetween = -1; + var bestBin = 0; + for (var i = 0; i < bins - 1; i++) + { + w0 += histogram[i]; + sum0 += histogram[i] * (min + (i + 0.5) * width); + var w1 = total - w0; + if (w0 <= 0 || w1 <= 0) continue; + var m0 = sum0 / w0; + var m1 = (sumAll - sum0) / w1; + var between = w0 * w1 * (m0 - m1) * (m0 - m1) / (total * total); + if (between > bestBetween) + { + bestBetween = between; + bestBin = i; + } + } + return (min + (bestBin + 1) * width, variance > 0 ? Math.Max(0, bestBetween) / variance : 0); + } + + /// Binary erosion (min) or dilation (max) with a (2r+1)² square, as two separable passes. + private static byte[] MinMax(byte[] source, int width, int height, int radius, bool dilate) + { + var horizontal = new byte[source.Length]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var v = dilate ? (byte)0 : (byte)1; + for (var d = -radius; d <= radius; d++) + { + var s = source[y * width + Math.Clamp(x + d, 0, width - 1)]; + v = dilate ? Math.Max(v, s) : Math.Min(v, s); + } + horizontal[y * width + x] = v; + } + } + var result = new byte[source.Length]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var v = dilate ? (byte)0 : (byte)1; + for (var d = -radius; d <= radius; d++) + { + var s = horizontal[Math.Clamp(y + d, 0, height - 1) * width + x]; + v = dilate ? Math.Max(v, s) : Math.Min(v, s); + } + result[y * width + x] = v; + } + } + return result; + } + + /// Separable box blur with edge-shrunk windows, in place. + private static void BoxBlur(float[] data, int width, int height, int radius) + { + var line = new double[Math.Max(width, height) + 1]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) line[x + 1] = line[x] + data[y * width + x]; + for (var x = 0; x < width; x++) + { + int a = Math.Max(0, x - radius), b = Math.Min(width, x + radius + 1); + data[y * width + x] = (float)((line[b] - line[a]) / (b - a)); + } + } + for (var x = 0; x < width; x++) + { + for (var y = 0; y < height; y++) line[y + 1] = line[y] + data[y * width + x]; + for (var y = 0; y < height; y++) + { + int a = Math.Max(0, y - radius), b = Math.Min(height, y + radius + 1); + data[y * width + x] = (float)((line[b] - line[a]) / (b - a)); + } + } + } +} diff --git a/src/Titano.Core/Analysis/WhiteBalanceSmoother.cs b/src/Titano.Core/Analysis/WhiteBalanceSmoother.cs new file mode 100644 index 00000000..293503e1 --- /dev/null +++ b/src/Titano.Core/Analysis/WhiteBalanceSmoother.cs @@ -0,0 +1,55 @@ +using Titano.Core.Imaging; +using Titano.Core.Mathematics; + +namespace Titano.Core.Analysis; + +/// Per-frame white-balance smoothing result; ratios are log2(R/G) and log2(B/G). +public sealed record WhiteBalanceResult( + ChannelGains[] Gains, + double[] RedRatio, + double[] BlueRatio, + double[] SmoothedRedRatio, + double[] SmoothedBlueRatio); + +/// +/// White-balance smoothing (BRIEF §11.2): the channel ratios log2(R/G) and log2(B/G) of each frame's mean colour are +/// smoothed with robust LOWESS, and each frame gets the channel gains that move its ratios onto the smoothed ones. +/// Gains are normalised so the Rec.709 luminance of the frame's mean colour is unchanged (WB never alters exposure). +/// Frames with a non-positive channel mean get identity gains. +/// +public static class WhiteBalanceSmoother +{ + public static WhiteBalanceResult Smooth(ReadOnlySpan meanRed, ReadOnlySpan meanGreen, ReadOnlySpan meanBlue, int window = 31, int robustIterations = 2) + { + var n = meanRed.Length; + if (meanGreen.Length != n || meanBlue.Length != n) throw new ArgumentException("Channel series lengths differ.", nameof(meanGreen)); + var red = new double[n]; + var blue = new double[n]; + for (var i = 0; i < n; i++) + { + var valid = meanRed[i] > 0 && meanGreen[i] > 0 && meanBlue[i] > 0 && double.IsFinite(meanRed[i] + meanGreen[i] + meanBlue[i]); + red[i] = valid ? Math.Log2(meanRed[i] / meanGreen[i]) : double.NaN; + blue[i] = valid ? Math.Log2(meanBlue[i] / meanGreen[i]) : double.NaN; + } + var smoothRed = LocalRegression.Smooth(red, window, 1, robustIterations).Fitted; + var smoothBlue = LocalRegression.Smooth(blue, window, 1, robustIterations).Fitted; + + var gains = new ChannelGains[n]; + for (var i = 0; i < n; i++) + { + if (double.IsNaN(red[i])) + { + gains[i] = ChannelGains.Identity; + continue; + } + var gr = Math.Pow(2, smoothRed[i] - red[i]); + var gb = Math.Pow(2, smoothBlue[i] - blue[i]); + double r = meanRed[i], g = meanGreen[i], b = meanBlue[i]; + var k = Luma(r, g, b) / Luma(gr * r, g, gb * b); + gains[i] = new ChannelGains(k * gr, k, k * gb); + } + return new WhiteBalanceResult(gains, red, blue, smoothRed, smoothBlue); + } + + private static double Luma(double r, double g, double b) => ColorSpace.LumaR * r + ColorSpace.LumaG * g + ColorSpace.LumaB * b; +} diff --git a/src/Titano.Core/Diagnostics/Synthetic/SyntheticSequence.cs b/src/Titano.Core/Diagnostics/Synthetic/SyntheticSequence.cs new file mode 100644 index 00000000..53a02c98 --- /dev/null +++ b/src/Titano.Core/Diagnostics/Synthetic/SyntheticSequence.cs @@ -0,0 +1,374 @@ +using Titano.Core.Analysis; +using Titano.Core.Imaging; +using Titano.Core.Metadata; +using Titano.Core.Model; + +namespace Titano.Core.Diagnostics.Synthetic; + +/// A deliberate exposure change written to the metadata from frame on; when +/// is false the pixels ignore it (e.g. a setting the camera did not apply). +/// Camera EV change (positive = less light; the pixels darken by this many stops). +public sealed record SyntheticExposureStep(int Index, double DeltaEv, ExposureChange Change = ExposureChange.Shutter, bool Received = true); + +/// Seconds added to the capture clock from frame on (pauses, clock jumps). +public sealed record SyntheticTimeShift(int Index, double Seconds); + +/// Recipe of a synthetic sequence; every field has a neutral default. +public sealed record SyntheticSequenceOptions +{ + public int Width { get; init; } = 96; + public int Height { get; init; } = 64; + public int FrameCount { get; init; } = 120; + public int Seed { get; init; } = 1; + + /// Camera wall-clock time of the first frame. + public DateTime Start { get; init; } = new(2024, 6, 21, 19, 0, 0); + + public int? UtcOffsetMinutes { get; init; } = 120; + public double IntervalSeconds { get; init; } = 10; + + /// Uniform ± jitter of each capture time, in seconds. + public double IntervalJitterSeconds { get; init; } + + public IReadOnlyList TimeShifts { get; init; } = []; + + /// Scene brightness (EV) at the first and last frame; linear ramp in between. + public double StartEv { get; init; } + + public double EndEv { get; init; } + + /// Global flicker amplitude in EV: uniform in ±amplitude, or a sinusoid when a period is set. + public double FlickerEv { get; init; } + + /// Period of sinusoidal flicker in frames; 0 = random flicker. + public double FlickerPeriodFrames { get; init; } + + /// Extra independent uniform flicker of the sky region, in ±EV. + public double SkyFlickerEv { get; init; } + + /// Extra independent uniform flicker of the land region, in ±EV. + public double LandFlickerEv { get; init; } + + public IReadOnlyList ExposureSteps { get; init; } = []; + + /// Horizon row at the centre column as a fraction of the height (sky above). + public double HorizonFraction { get; init; } = 0.45; + + /// Horizon slope in rows per column. + public double HorizonTilt { get; init; } + + /// Amplitude in rows of one sine period of horizon undulation across the width. + public double HorizonWave { get; init; } + + /// Linear luminance of the sky (at the horizon) and of the average land pixel at 0 EV. + public double SkyLevel { get; init; } = 0.25; + + public double LandLevel { get; init; } = 0.05; + + /// Night sky: dark background with point stars instead of a bright gradient. + public bool StarField { get; init; } + + public int StarCount { get; init; } = 40; + + /// Correlated colour temperature of the light at the first and last frame (linear in mireds). + public double StartKelvin { get; init; } = 5500; + + public double EndKelvin { get; init; } = 5500; + + /// Uniform ± per-frame jitter of log2(R/G) and log2(B/G). + public double WhiteBalanceJitter { get; init; } + + /// Additive Gaussian sensor noise (linear units) on every channel. + public double NoiseSigma { get; init; } + + public IReadOnlyList BlackFrames { get; init; } = []; + public IReadOnlyList WhiteFrames { get; init; } = []; + + /// Frames that repeat the previous frame exactly (pixels, capture time and settings). + public IReadOnlyList DuplicateFrames { get; init; } = []; + + public double BaseExposureTime { get; init; } = 1.0 / 100; + public double BaseFNumber { get; init; } = 8; + public int BaseIso { get; init; } = 100; + public string CameraMake { get; init; } = "Titano"; + public string CameraModel { get; init; } = "Synthetic"; + public string Lens { get; init; } = "Synthetic 24mm"; + public double? Latitude { get; init; } + public double? Longitude { get; init; } +} + +/// +/// Deterministic synthetic time-lapse with known answers (the analysis self-test fixture): a scene-brightness +/// ramp, seeded flicker (global and per region), exposure steps in metadata and pixels, a sky/land split along a +/// horizon, colour-temperature drift, an optional star field, and black/white/duplicate frames. Pixels are linear +/// light: base(x, y) · 2^(scene + exposure + flicker + regionFlicker) · rgb(kelvin) with rgb at luminance 1, +/// so log-luminance shifts equal the truth series exactly. +/// +public sealed class SyntheticSequence +{ + private readonly int[] _source; + + private SyntheticSequence(SyntheticSequenceOptions options) + { + Options = options; + var n = options.FrameCount; + var random = new Random(options.Seed); + _source = new int[n]; + SceneEv = new double[n]; + FlickerEv = new double[n]; + SkyFlickerEv = new double[n]; + LandFlickerEv = new double[n]; + ExposureOffsetEv = new double[n]; + Kelvin = new double[n]; + RedJitter = new double[n]; + BlueJitter = new double[n]; + var phase = random.NextDouble() * 2 * Math.PI; + for (var i = 0; i < n; i++) + { + var t = n > 1 ? (double)i / (n - 1) : 0; + SceneEv[i] = options.StartEv + (options.EndEv - options.StartEv) * t; + FlickerEv[i] = options.FlickerPeriodFrames > 0 + ? options.FlickerEv * Math.Sin(2 * Math.PI * i / options.FlickerPeriodFrames + phase) + : options.FlickerEv * (2 * random.NextDouble() - 1); + SkyFlickerEv[i] = options.SkyFlickerEv * (2 * random.NextDouble() - 1); + LandFlickerEv[i] = options.LandFlickerEv * (2 * random.NextDouble() - 1); + Kelvin[i] = 1e6 / (1e6 / options.StartKelvin + (1e6 / options.EndKelvin - 1e6 / options.StartKelvin) * t); + RedJitter[i] = options.WhiteBalanceJitter * (2 * random.NextDouble() - 1); + BlueJitter[i] = options.WhiteBalanceJitter * (2 * random.NextDouble() - 1); + } + + var frames = new Frame[n]; + var metadata = new FrameMetadata[n]; + var sequenceId = DeterministicGuid(options.Seed, -1); + double exposureTime = options.BaseExposureTime, fNumber = options.BaseFNumber, pixelOffset = 0; + var iso = options.BaseIso; + var timeShift = 0.0; + var duplicates = new HashSet(options.DuplicateFrames); + for (var i = 0; i < n; i++) + { + foreach (var shift in options.TimeShifts) + { + if (shift.Index == i) timeShift += shift.Seconds; + } + foreach (var step in options.ExposureSteps) + { + if (step.Index != i) continue; + var before = Ev(exposureTime, fNumber, iso); + switch (step.Change) + { + case ExposureChange.Aperture: fNumber *= Math.Pow(2, step.DeltaEv / 2); break; + case ExposureChange.Iso: iso = (int)Math.Round(iso * Math.Pow(2, -step.DeltaEv)); break; + default: exposureTime *= Math.Pow(2, -step.DeltaEv); break; + } + if (step.Received) pixelOffset -= Ev(exposureTime, fNumber, iso) - before; + } + ExposureOffsetEv[i] = pixelOffset; + var jitter = options.IntervalJitterSeconds * (2 * random.NextDouble() - 1); + var captured = options.Start.AddSeconds(i * options.IntervalSeconds + jitter + timeShift); + _source[i] = i; + if (duplicates.Contains(i) && i > 0) + { + _source[i] = _source[i - 1]; + captured = metadata[i - 1].CapturedAt!.Value; + CopyTruth(i, i - 1); + } + var exposure = duplicates.Contains(i) && i > 0 ? metadata[i - 1] : null; + metadata[i] = new FrameMetadata + { + Format = ImageFileFormat.Tiff, + Make = options.CameraMake, + Model = options.CameraModel, + LensModel = options.Lens, + CapturedAt = captured, + UtcOffsetMinutes = options.UtcOffsetMinutes, + TimestampSource = TimestampSource.ExifOriginal, + ExposureTime = exposure?.ExposureTime ?? exposureTime, + FNumber = exposure?.FNumber ?? fNumber, + Iso = exposure?.Iso ?? iso, + Width = options.Width, + Height = options.Height, + Gps = options.Latitude is { } lat && options.Longitude is { } lon ? new GpsPosition(lat, lon, null, null) : null, + }; + var name = $"IMG_{i + 1:D4}.tif"; + frames[i] = new Frame + { + Id = DeterministicGuid(options.Seed, i), + SequenceId = sequenceId, + Index = i, + RelativePath = "synthetic/" + name, + FileName = name, + CapturedAt = captured, + UtcOffsetMinutes = options.UtcOffsetMinutes, + TimestampSource = TimestampSource.ExifOriginal, + ExposureTime = metadata[i].ExposureTime, + FNumber = metadata[i].FNumber, + Iso = metadata[i].Iso, + Width = options.Width, + Height = options.Height, + Format = ImageFileFormat.Tiff, + }; + } + Frames = frames; + Metadata = metadata; + } + + public SyntheticSequenceOptions Options { get; } + public IReadOnlyList Frames { get; } + public IReadOnlyList Metadata { get; } + + /// True scene brightness per frame (EV): the ramp. + public double[] SceneEv { get; } + + /// Global flicker per frame (EV). + public double[] FlickerEv { get; } + + public double[] SkyFlickerEv { get; } + public double[] LandFlickerEv { get; } + + /// Luminance offset of the received exposure steps (EV). + public double[] ExposureOffsetEv { get; } + + public double[] Kelvin { get; } + + /// Per-frame white-balance jitter of log2(R/G) and log2(B/G). + public double[] RedJitter { get; } + + public double[] BlueJitter { get; } + + public int Count => Options.FrameCount; + + public bool IsBlack(int index) => Options.BlackFrames.Contains(_source[index]); + + public bool IsWhite(int index) => Options.WhiteFrames.Contains(_source[index]); + + /// Light-analysis input of every frame (with camera, lens and GPS). + public IReadOnlyList LightFrames() => Metadata.Select((m, i) => LightFrame.From(m, i)).ToList(); + + /// Horizon position (rows from the top edge) at column centre . + public double HorizonRow(double x) + { + var o = Options; + var centre = o.Width / 2.0; + return o.HorizonFraction * o.Height + o.HorizonTilt * (x - centre) + o.HorizonWave * Math.Sin(2 * Math.PI * x / o.Width); + } + + public bool IsSky(int x, int y) => y + 0.5 < HorizonRow(x + 0.5); + + public static SyntheticSequence Create(SyntheticSequenceOptions options) + { + ArgumentNullException.ThrowIfNull(options); + ArgumentOutOfRangeException.ThrowIfLessThan(options.Width, 4); + ArgumentOutOfRangeException.ThrowIfLessThan(options.Height, 4); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(options.FrameCount); + return new SyntheticSequence(options); + } + + /// Renders frame (linear RGB); identical calls give identical pixels. + public ImageBuffer Render(int index) + { + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, Count); + var o = Options; + var source = _source[index]; + var image = new ImageBuffer(o.Width, o.Height, 3); + if (IsWhite(index)) + { + image.Data.Fill(1f); + return image; + } + if (IsBlack(index)) return image; + + var colour = ColourOf(source); + var common = SceneEv[source] + ExposureOffsetEv[source] + FlickerEv[source]; + var skyGain = Math.Pow(2, common + SkyFlickerEv[source]); + var landGain = Math.Pow(2, common + LandFlickerEv[source]); + var noise = o.NoiseSigma > 0 ? new Random(unchecked(o.Seed * 7919 + source * 104729)) : null; + var r = image.Plane(0); + var g = image.Plane(1); + var b = image.Plane(2); + for (var y = 0; y < o.Height; y++) + { + for (var x = 0; x < o.Width; x++) + { + var horizon = HorizonRow(x + 0.5); + double value; + if (y + 0.5 < horizon) + { + value = skyGain * (o.StarField + ? StarOrBackground(x, y) + : o.SkyLevel * (0.7 + 0.3 * Math.Clamp((y + 0.5) / Math.Max(1, horizon), 0, 1))); + } + else + { + value = landGain * o.LandLevel * (o.StarField ? 1.0 / 32 : 1) * (0.5 + Hash(x, y, o.Seed)); + } + var i = y * o.Width + x; + r[i] = (float)(value * colour.Red + Noise(noise)); + g[i] = (float)(value * colour.Green + Noise(noise)); + b[i] = (float)(value * colour.Blue + Noise(noise)); + } + } + return image; + } + + private double StarOrBackground(int x, int y) + { + var o = Options; + var star = Hash(x, y, o.Seed + 1); + var density = (double)o.StarCount / (o.Width * o.Height * o.HorizonFraction); + return star < density ? 0.25 + 0.75 * Hash(y, x, o.Seed + 2) : 1.0 / 2048; + } + + private double Noise(Random? random) + { + if (random is null) return 0; + // Box–Muller transform of two uniform deviates. + var u = 1 - random.NextDouble(); + var v = random.NextDouble(); + return Options.NoiseSigma * Math.Sqrt(-2 * Math.Log(u)) * Math.Cos(2 * Math.PI * v); + } + + /// Linear Rec.709 colour of the frame's light at luminance 1, with the white-balance jitter applied. + private ChannelGains ColourOf(int index) + { + var rgb = ColorTemperature.PlanckianRgb(Kelvin[index]); + var red = rgb.X * Math.Pow(2, RedJitter[index]); + var blue = rgb.Z * Math.Pow(2, BlueJitter[index]); + var luminance = ColorSpace.LumaR * red + ColorSpace.LumaG * rgb.Y + ColorSpace.LumaB * blue; + return new ChannelGains(red / luminance, rgb.Y / luminance, blue / luminance); + } + + private void CopyTruth(int to, int from) + { + SceneEv[to] = SceneEv[from]; + FlickerEv[to] = FlickerEv[from]; + SkyFlickerEv[to] = SkyFlickerEv[from]; + LandFlickerEv[to] = LandFlickerEv[from]; + ExposureOffsetEv[to] = ExposureOffsetEv[from]; + Kelvin[to] = Kelvin[from]; + RedJitter[to] = RedJitter[from]; + BlueJitter[to] = BlueJitter[from]; + } + + private static double Ev(double exposureTime, double fNumber, int iso) => Math.Log2(fNumber * fNumber / exposureTime) - Math.Log2(iso / 100.0); + + /// Uniform [0, 1) from a SplitMix64 hash of the inputs (stable across processes, unlike HashCode). + private static double Hash(int x, int y, int seed) + { + var z = unchecked((ulong)(uint)x * 0x9E3779B97F4A7C15UL ^ (ulong)(uint)y * 0xC2B2AE3D27D4EB4FUL ^ (ulong)(uint)seed * 0x165667B19E3779F9UL); + z = unchecked((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL); + z = unchecked((z ^ (z >> 27)) * 0x94D049BB133111EBUL); + z ^= z >> 31; + return (z >> 11) * (1.0 / (1UL << 53)); + } + + private static Guid DeterministicGuid(int seed, int index) + { + Span bytes = stackalloc byte[16]; + BitConverter.TryWriteBytes(bytes, (long)seed); + BitConverter.TryWriteBytes(bytes[8..], (long)index); + bytes[7] = (byte)((bytes[7] & 0x0F) | 0x40); + bytes[8] = (byte)((bytes[8] & 0x3F) | 0x80); + return new Guid(bytes); + } +} diff --git a/src/Titano.Core/Math/CatmullRom.cs b/src/Titano.Core/Math/CatmullRom.cs new file mode 100644 index 00000000..d0d4bd51 --- /dev/null +++ b/src/Titano.Core/Math/CatmullRom.cs @@ -0,0 +1,92 @@ +namespace Titano.Core.Mathematics; + +/// Knot spacing of a Catmull–Rom spline: |Pᵢ₊₁ − Pᵢ|^α with α = 0, ½ or 1. +public enum CatmullRomParameterization +{ + /// α = 0: the classic spline; can cusp or self-intersect on uneven spacing. + Uniform, + + /// α = ½: no cusps or self-intersections within a segment (Yuksel, Schaefer & Keyser 2011). + Centripetal, + + /// α = 1: follows the chord lengths; smoothest on evenly sampled paths. + Chordal, +} + +/// +/// Catmull–Rom interpolating splines evaluated with the Barry–Goldman pyramid, so non-uniform (centripetal, +/// chordal) knots are exact. The parameter t ∈ [0, n − 1] selects segment ⌊t⌋; end segments use reflected +/// phantom points (P₋₁ = 2P₀ − P₁). +/// +public static class CatmullRom +{ + /// Scalar spline through (values treated as 1-D points for the knot spacing). + public static double Evaluate(ReadOnlySpan values, double t, CatmullRomParameterization kind = CatmullRomParameterization.Uniform) + { + if (values.IsEmpty) throw new ArgumentException("No control values.", nameof(values)); + if (values.Length == 1) return values[0]; + var (i, u) = Segment(values.Length, t); + var p1 = values[i]; + var p2 = values[i + 1]; + var p0 = i > 0 ? values[i - 1] : 2 * p1 - p2; + var p3 = i + 2 < values.Length ? values[i + 2] : 2 * p2 - p1; + return Pyramid(new Point2(p0, 0), new Point2(p1, 0), new Point2(p2, 0), new Point2(p3, 0), u, Alpha(kind)).X; + } + + /// Planar spline through . + public static Point2 Evaluate(ReadOnlySpan points, double t, CatmullRomParameterization kind = CatmullRomParameterization.Centripetal) + { + if (points.IsEmpty) throw new ArgumentException("No control points.", nameof(points)); + if (points.Length == 1) return points[0]; + var (i, u) = Segment(points.Length, t); + var p1 = points[i]; + var p2 = points[i + 1]; + var p0 = i > 0 ? points[i - 1] : 2 * p1 - p2; + var p3 = i + 2 < points.Length ? points[i + 2] : 2 * p2 - p1; + return Pyramid(p0, p1, p2, p3, u, Alpha(kind)); + } + + private static double Alpha(CatmullRomParameterization kind) => kind switch + { + CatmullRomParameterization.Uniform => 0, + CatmullRomParameterization.Centripetal => 0.5, + CatmullRomParameterization.Chordal => 1, + _ => throw new ArgumentOutOfRangeException(nameof(kind)), + }; + + private static (int Index, double Local) Segment(int count, double t) + { + if (double.IsNaN(t)) throw new ArgumentOutOfRangeException(nameof(t)); + t = Math.Clamp(t, 0, count - 1); + var i = Math.Min((int)t, count - 2); + return (i, t - i); + } + + /// Barry–Goldman recursive evaluation of the segment P1→P2 at local parameter u ∈ [0, 1]. + private static Point2 Pyramid(Point2 p0, Point2 p1, Point2 p2, Point2 p3, double u, double alpha) + { + if (u <= 0) return p1; + if (u >= 1) return p2; + var d1 = Knot(p0, p1, alpha); + var d2 = Knot(p1, p2, alpha); + var d3 = Knot(p2, p3, alpha); + double t0 = 0, t1 = d1, t2 = t1 + d2, t3 = t2 + d3; + var t = t1 + u * d2; + var a1 = Mix(p0, p1, t0, t1, t); + var a2 = Mix(p1, p2, t1, t2, t); + var a3 = Mix(p2, p3, t2, t3, t); + var b1 = Mix(a1, a2, t0, t2, t); + var b2 = Mix(a2, a3, t1, t3, t); + return Mix(b1, b2, t1, t2, t); + } + + private static Point2 Mix(Point2 a, Point2 b, double ta, double tb, double t) => ((tb - t) * a + (t - ta) * b) * (1 / (tb - ta)); + + /// Knot interval; coincident points fall back to a unit interval so the pyramid stays finite. + private static double Knot(Point2 a, Point2 b, double alpha) + { + if (alpha == 0) return 1; + var d = Math.Pow(Point2.Distance(a, b), alpha); + return d > 1e-12 ? d : 1; + } +} diff --git a/src/Titano.Core/Math/Chromaticity.cs b/src/Titano.Core/Math/Chromaticity.cs new file mode 100644 index 00000000..49e123bd --- /dev/null +++ b/src/Titano.Core/Math/Chromaticity.cs @@ -0,0 +1,39 @@ +namespace Titano.Core.Mathematics; + +/// CIE 1931 chromaticity coordinates (lower-case x, y in the literature). +public readonly record struct Chromaticity(double X, double Y) +{ + /// CIE standard illuminant D65 (2° observer). + public static Chromaticity D65 { get; } = new(0.3127, 0.3290); + + /// CIE standard illuminant D50 (2° observer), the ICC/DNG profile connection white. + public static Chromaticity D50 { get; } = new(0.3457, 0.3585); + + /// Tristimulus values with luminance : X = x·Y/y, Z = (1 − x − y)·Y/y. + public Vector3D ToXyz(double luminance = 1) + { + if (!(Y > 0)) throw new InvalidOperationException("Chromaticity y must be positive."); + return new Vector3D(X * luminance / Y, luminance, (1 - X - Y) * luminance / Y); + } + + /// Chromaticity of tristimulus values; NaN coordinates when X + Y + Z is not positive. + public static Chromaticity FromXyz(Vector3D xyz) + { + var sum = xyz.X + xyz.Y + xyz.Z; + return sum > 0 ? new Chromaticity(xyz.X / sum, xyz.Y / sum) : new Chromaticity(double.NaN, double.NaN); + } + + /// CIE 1960 UCS coordinates u = 4x/(−2x + 12y + 3), v = 6y/(−2x + 12y + 3). + public (double U, double V) ToUv1960() + { + var d = -2 * X + 12 * Y + 3; + return (4 * X / d, 6 * Y / d); + } + + /// Chromaticity from CIE 1960 UCS coordinates. + public static Chromaticity FromUv1960(double u, double v) + { + var d = 2 * u - 8 * v + 4; + return new Chromaticity(3 * u / d, 2 * v / d); + } +} diff --git a/src/Titano.Core/Math/CubicBezier.cs b/src/Titano.Core/Math/CubicBezier.cs new file mode 100644 index 00000000..a210b02f --- /dev/null +++ b/src/Titano.Core/Math/CubicBezier.cs @@ -0,0 +1,95 @@ +namespace Titano.Core.Mathematics; + +/// Planar cubic Bézier curve in Bernstein form; t ∈ [0, 1]. +public readonly record struct CubicBezier(Point2 P0, Point2 P1, Point2 P2, Point2 P3) +{ + public Point2 Evaluate(double t) + { + var s = 1 - t; + return s * s * s * P0 + 3 * s * s * t * P1 + 3 * s * t * t * P2 + t * t * t * P3; + } + + public Point2 Derivative(double t) + { + var s = 1 - t; + return 3 * s * s * (P1 - P0) + 6 * s * t * (P2 - P1) + 3 * t * t * (P3 - P2); + } +} + +/// +/// CSS-style timing function cubic-bezier(x1, y1, x2, y2) with end points (0, 0) and (1, 1). x(t) is +/// monotone because x1, x2 ∈ [0, 1]; it is inverted with Newton's method guarded by bisection. +/// +public readonly record struct CubicBezierEasing +{ + public CubicBezierEasing(double x1, double y1, double x2, double y2) + { + if (!(x1 >= 0 && x1 <= 1)) throw new ArgumentOutOfRangeException(nameof(x1), "x1 must lie in [0, 1]."); + if (!(x2 >= 0 && x2 <= 1)) throw new ArgumentOutOfRangeException(nameof(x2), "x2 must lie in [0, 1]."); + if (!double.IsFinite(y1)) throw new ArgumentOutOfRangeException(nameof(y1)); + if (!double.IsFinite(y2)) throw new ArgumentOutOfRangeException(nameof(y2)); + X1 = x1; + Y1 = y1; + X2 = x2; + Y2 = y2; + } + + public double X1 { get; } + public double Y1 { get; } + public double X2 { get; } + public double Y2 { get; } + + public static CubicBezierEasing Linear { get; } = new(0, 0, 1, 1); + public static CubicBezierEasing Ease { get; } = new(0.25, 0.1, 0.25, 1); + public static CubicBezierEasing EaseIn { get; } = new(0.42, 0, 1, 1); + public static CubicBezierEasing EaseOut { get; } = new(0, 0, 0.58, 1); + public static CubicBezierEasing EaseInOut { get; } = new(0.42, 0, 0.58, 1); + + /// Eased progress for input progress (clamped to [0, 1]). + public double Evaluate(double x) => Component(Y1, Y2, SolveT(x)); + + /// Curve parameter t with x(t) = . + public double SolveT(double x) + { + if (!(x > 0)) return 0; + if (x >= 1) return 1; + var t = x; + for (var i = 0; i < 8; i++) + { + var error = Component(X1, X2, t) - x; + if (Math.Abs(error) < 1e-12) return t; + var slope = ComponentDerivative(X1, X2, t); + if (Math.Abs(slope) < 1e-9) break; + t -= error / slope; + if (t is < 0 or > 1) break; + } + double lo = 0, hi = 1; + t = x; + for (var i = 0; i < 64; i++) + { + var value = Component(X1, X2, t); + if (Math.Abs(value - x) < 1e-12) break; + if (value < x) lo = t; + else hi = t; + t = 0.5 * (lo + hi); + } + return t; + } + + /// One coordinate of the curve with P0 = 0 and P3 = 1: ((a·t + b)·t + c)·t. + private static double Component(double p1, double p2, double t) + { + var c = 3 * p1; + var b = 3 * (p2 - p1) - c; + var a = 1 - c - b; + return ((a * t + b) * t + c) * t; + } + + private static double ComponentDerivative(double p1, double p2, double t) + { + var c = 3 * p1; + var b = 3 * (p2 - p1) - c; + var a = 1 - c - b; + return (3 * a * t + 2 * b) * t + c; + } +} diff --git a/src/Titano.Core/Math/LocalRegression.cs b/src/Titano.Core/Math/LocalRegression.cs new file mode 100644 index 00000000..6f2386a6 --- /dev/null +++ b/src/Titano.Core/Math/LocalRegression.cs @@ -0,0 +1,207 @@ +namespace Titano.Core.Mathematics; + +/// Output of ; every array has one entry per input sample. +public sealed class LocalRegressionResult +{ + internal LocalRegressionResult(double[] fitted, double[] robustWeights, double[] survivingFraction, int validCount) + { + Fitted = fitted; + RobustWeights = robustWeights; + SurvivingFraction = survivingFraction; + ValidCount = validCount; + } + + /// Smoothed value at every position, including missing samples (interpolated from their neighbours). + /// NaN only when there is no valid sample at all. + public double[] Fitted { get; } + + /// Tukey biweight each sample carried in the final fit (1 = full inlier, 0 = rejected or missing). + public double[] RobustWeights { get; } + + /// + /// Σ wᵢⱼ·ρⱼ / Σ wᵢⱼ over the window of each position: the share of its distance (tricube × prior) weight + /// that survived robustness. Near 1 for clean windows, lower where samples were rejected. + /// + public double[] SurvivingFraction { get; } + + public int ValidCount { get; } +} + +/// +/// Robust locally weighted regression, LOWESS (Cleveland 1979). Each position is fitted by weighted least squares +/// of degree 1 or 2 over its window nearest valid samples (asymmetric at the edges, so the count stays +/// constant), with tricube distance weights. Robustness iterations reweight samples with Tukey's biweight of the +/// residuals scaled by 6·MAD. Cost O(n·window) per iteration. +/// +public static class LocalRegression +{ + /// Samples; NaN/±∞ mark missing values. + /// Number of nearest valid samples in each local fit (clamped to the valid count). + /// Local polynomial degree, 1 (linear) or 2 (quadratic). + /// Tukey reweighting passes after the initial fit (Cleveland uses 2–3). + /// Non-decreasing positions (e.g. capture seconds); indices when empty. + /// Optional non-negative sample weights; zero marks a sample as missing. + public static LocalRegressionResult Smooth( + ReadOnlySpan y, + int window, + int degree = 1, + int robustIterations = 2, + ReadOnlySpan x = default, + ReadOnlySpan priorWeights = default) + { + ArgumentOutOfRangeException.ThrowIfLessThan(window, 1); + if (degree is not (1 or 2)) throw new ArgumentOutOfRangeException(nameof(degree), "Degree must be 1 or 2."); + ArgumentOutOfRangeException.ThrowIfNegative(robustIterations); + var n = y.Length; + if (!x.IsEmpty && x.Length != n) throw new ArgumentException("x and y lengths differ.", nameof(x)); + if (!priorWeights.IsEmpty && priorWeights.Length != n) throw new ArgumentException("Weight and y lengths differ.", nameof(priorWeights)); + + var pos = new double[n]; + for (var i = 0; i < n; i++) + { + pos[i] = x.IsEmpty ? i : x[i]; + if (!double.IsFinite(pos[i])) throw new ArgumentException("Positions must be finite.", nameof(x)); + if (i > 0 && pos[i] < pos[i - 1]) throw new ArgumentException("Positions must be non-decreasing.", nameof(x)); + } + + var valid = new List(n); + for (var i = 0; i < n; i++) + { + var w = priorWeights.IsEmpty ? 1 : priorWeights[i]; + if (double.IsFinite(y[i]) && w > 0 && double.IsFinite(w)) valid.Add(i); + } + var m = valid.Count; + var fitted = new double[n]; + var robust = new double[n]; + var surviving = new double[n]; + if (m == 0) + { + Array.Fill(fitted, double.NaN); + return new LocalRegressionResult(fitted, robust, surviving, 0); + } + + var vx = new double[m]; + var vy = new double[m]; + var prior = new double[m]; + for (var j = 0; j < m; j++) + { + var i = valid[j]; + vx[j] = pos[i]; + vy[j] = y[i]; + prior[j] = priorWeights.IsEmpty ? 1 : priorWeights[i]; + } + + var q = Math.Min(window, m); + var p = Math.Min(degree, q - 1); + var windows = BuildWindows(pos, vx, q); + var rho = new double[m]; + Array.Fill(rho, 1.0); + var residual = new double[m]; + var scaleFloor = 1e-12 * (1 + Math.Abs(Statistics.Median(vy))); + + for (var iteration = 0; ; iteration++) + { + FitAll(pos, windows, q, vx, vy, prior, rho, p, fitted, surviving); + if (iteration == robustIterations) break; + for (var j = 0; j < m; j++) residual[j] = vy[j] - fitted[valid[j]]; + var mad = Statistics.MedianAbsoluteDeviation(residual, 0); + if (!(mad > scaleFloor)) break; + var c = 6 * mad; + for (var j = 0; j < m; j++) + { + var u = residual[j] / c; + rho[j] = Math.Abs(u) < 1 ? (1 - u * u) * (1 - u * u) : 0; + } + } + + for (var j = 0; j < m; j++) robust[valid[j]] = rho[j]; + return new LocalRegressionResult(fitted, robust, surviving, m); + } + + /// Start of the contiguous block of valid samples nearest to each position + /// (sliding k-nearest-neighbour window; total O(n + m)). + private static int[] BuildWindows(double[] pos, double[] vx, int q) + { + var starts = new int[pos.Length]; + var s = 0; + for (var i = 0; i < pos.Length; i++) + { + var xi = pos[i]; + while (s + q < vx.Length && xi - vx[s] > vx[s + q] - xi) s++; + starts[i] = s; + } + return starts; + } + + private static void FitAll(double[] pos, int[] starts, int q, double[] vx, double[] vy, double[] prior, double[] rho, int degree, double[] fitted, double[] surviving) + { + for (var i = 0; i < pos.Length; i++) + fitted[i] = FitAt(pos[i], starts[i], q, vx, vy, prior, rho, degree, out surviving[i]); + } + + private static double FitAt(double xi, int start, int q, double[] vx, double[] vy, double[] prior, double[] rho, int degree, out double surviving) + { + var end = start + q - 1; + var dMax = Math.Max(xi - vx[start], vx[end] - xi); + // One mean sample spacing beyond the farthest neighbour, so every sample in the window keeps a positive weight. + var h = dMax + (q > 1 ? (vx[end] - vx[start]) / (q - 1) : 0); + if (!(h > 0)) h = 1; + + double s0 = 0, s1 = 0, s2 = 0, s3 = 0, s4 = 0, t0 = 0, t1 = 0, t2 = 0; + double distanceSum = 0, survivingSum = 0; + double r0 = 0, r1 = 0, r2 = 0, r3 = 0, r4 = 0, rt0 = 0, rt1 = 0, rt2 = 0; + for (var j = start; j <= end; j++) + { + var u = (vx[j] - xi) / h; + var a = 1 - Math.Abs(u * u * u); + var wd = a <= 0 ? 0 : a * a * a * prior[j]; + distanceSum += wd; + var w = wd * rho[j]; + survivingSum += w; + var uu = u * u; + s0 += w; + s1 += w * u; + s2 += w * uu; + t0 += w * vy[j]; + t1 += w * u * vy[j]; + r0 += wd; + r1 += wd * u; + r2 += wd * uu; + rt0 += wd * vy[j]; + rt1 += wd * u * vy[j]; + if (degree == 2) + { + s3 += w * uu * u; + s4 += w * uu * uu; + t2 += w * uu * vy[j]; + r3 += wd * uu * u; + r4 += wd * uu * uu; + rt2 += wd * uu * vy[j]; + } + } + surviving = distanceSum > 0 ? survivingSum / distanceSum : 0; + // A window whose every sample was rejected falls back to plain distance weights. + return s0 > 1e-12 * distanceSum + ? Solve(degree, s0, s1, s2, s3, s4, t0, t1, t2) + : Solve(degree, r0, r1, r2, r3, r4, rt0, rt1, rt2); + } + + /// Intercept of the weighted polynomial fit in centred coordinates, degrading to a lower degree when + /// the normal equations are ill-conditioned (e.g. all weight on one sample). + private static double Solve(int degree, double s0, double s1, double s2, double s3, double s4, double t0, double t1, double t2) + { + if (!(s0 > 0)) return double.NaN; + if (degree == 2) + { + var c00 = s2 * s4 - s3 * s3; + var c01 = s1 * s4 - s2 * s3; + var c02 = s1 * s3 - s2 * s2; + var det = s0 * c00 - s1 * c01 + s2 * c02; + if (det > 1e-10 * s0 * s2 * s4) + return (t0 * c00 - s1 * (t1 * s4 - s3 * t2) + s2 * (t1 * s3 - s2 * t2)) / det; + } + var det1 = s0 * s2 - s1 * s1; + if (det1 > 1e-10 * s0 * s2) return (s2 * t0 - s1 * t1) / det1; + return t0 / s0; + } +} diff --git a/src/Titano.Core/Math/Matrix3.cs b/src/Titano.Core/Math/Matrix3.cs new file mode 100644 index 00000000..3e1bfc91 --- /dev/null +++ b/src/Titano.Core/Math/Matrix3.cs @@ -0,0 +1,93 @@ +namespace Titano.Core.Mathematics; + +/// A 3-vector in double precision (colour triplets, homogeneous 2-D points). +public readonly record struct Vector3D(double X, double Y, double Z); + +/// Row-major 3×3 matrix in double precision for colour-space and planar projective work. +public readonly record struct Matrix3( + double M11, double M12, double M13, + double M21, double M22, double M23, + double M31, double M32, double M33) +{ + public static Matrix3 Identity { get; } = new(1, 0, 0, 0, 1, 0, 0, 0, 1); + + /// Bradford cone-response matrix (Lam 1985), XYZ → sharpened LMS. + public static Matrix3 Bradford { get; } = new( + 0.8951, 0.2664, -0.1614, + -0.7502, 1.7135, 0.0367, + 0.0389, -0.0685, 1.0296); + + /// Linear Rec.709/sRGB (D65) → CIE XYZ, derived from the primaries. + public static Matrix3 Rec709ToXyz { get; } = RgbToXyz(new(0.64, 0.33), new(0.30, 0.60), new(0.15, 0.06), Chromaticity.D65); + + /// CIE XYZ → linear Rec.709/sRGB (D65). + public static Matrix3 XyzToRec709 { get; } = Rec709ToXyz.Inverse(); + + public static Matrix3 Diagonal(double a, double b, double c) => new(a, 0, 0, 0, b, 0, 0, 0, c); + + /// Matrix whose columns are , , . + public static Matrix3 FromColumns(Vector3D c1, Vector3D c2, Vector3D c3) => new(c1.X, c2.X, c3.X, c1.Y, c2.Y, c3.Y, c1.Z, c2.Z, c3.Z); + + public static Matrix3 operator *(Matrix3 a, Matrix3 b) => new( + a.M11 * b.M11 + a.M12 * b.M21 + a.M13 * b.M31, a.M11 * b.M12 + a.M12 * b.M22 + a.M13 * b.M32, a.M11 * b.M13 + a.M12 * b.M23 + a.M13 * b.M33, + a.M21 * b.M11 + a.M22 * b.M21 + a.M23 * b.M31, a.M21 * b.M12 + a.M22 * b.M22 + a.M23 * b.M32, a.M21 * b.M13 + a.M22 * b.M23 + a.M23 * b.M33, + a.M31 * b.M11 + a.M32 * b.M21 + a.M33 * b.M31, a.M31 * b.M12 + a.M32 * b.M22 + a.M33 * b.M32, a.M31 * b.M13 + a.M32 * b.M23 + a.M33 * b.M33); + + public static Vector3D operator *(Matrix3 m, Vector3D v) => new( + m.M11 * v.X + m.M12 * v.Y + m.M13 * v.Z, + m.M21 * v.X + m.M22 * v.Y + m.M23 * v.Z, + m.M31 * v.X + m.M32 * v.Y + m.M33 * v.Z); + + public double Determinant => + M11 * (M22 * M33 - M23 * M32) - M12 * (M21 * M33 - M23 * M31) + M13 * (M21 * M32 - M22 * M31); + + public Matrix3 Transpose() => new(M11, M21, M31, M12, M22, M32, M13, M23, M33); + + /// Inverse by the adjugate; false when the matrix is singular relative to its scale. + public bool TryInvert(out Matrix3 inverse) + { + var det = Determinant; + var scale = MaxAbs(); + if (!(Math.Abs(det) > 1e-14 * scale * scale * scale) || !double.IsFinite(det)) + { + inverse = default; + return false; + } + var r = 1 / det; + inverse = new Matrix3( + (M22 * M33 - M23 * M32) * r, (M13 * M32 - M12 * M33) * r, (M12 * M23 - M13 * M22) * r, + (M23 * M31 - M21 * M33) * r, (M11 * M33 - M13 * M31) * r, (M13 * M21 - M11 * M23) * r, + (M21 * M32 - M22 * M31) * r, (M12 * M31 - M11 * M32) * r, (M11 * M22 - M12 * M21) * r); + return true; + } + + /// The matrix is singular. + public Matrix3 Inverse() => TryInvert(out var inverse) ? inverse : throw new InvalidOperationException("Matrix is singular."); + + /// + /// Bradford chromatic adaptation (von Kries scaling in the Bradford cone space) mapping colours seen under + /// to ; both whites as XYZ. + /// + public static Matrix3 BradfordAdaptation(Vector3D sourceWhite, Vector3D destinationWhite) + { + var s = Bradford * sourceWhite; + var d = Bradford * destinationWhite; + if (!(s.X > 0 && s.Y > 0 && s.Z > 0)) throw new ArgumentOutOfRangeException(nameof(sourceWhite), "White point must have positive cone responses."); + return Bradford.Inverse() * Diagonal(d.X / s.X, d.Y / s.Y, d.Z / s.Z) * Bradford; + } + + /// RGB → XYZ matrix of an additive colour space from its primaries and white point (white maps to Y = 1). + public static Matrix3 RgbToXyz(Chromaticity red, Chromaticity green, Chromaticity blue, Chromaticity white) + { + var primaries = FromColumns(red.ToXyz(), green.ToXyz(), blue.ToXyz()); + var s = primaries.Inverse() * white.ToXyz(); + return primaries * Diagonal(s.X, s.Y, s.Z); + } + + private double MaxAbs() + { + var m = Math.Max(Math.Max(Math.Abs(M11), Math.Abs(M12)), Math.Abs(M13)); + m = Math.Max(m, Math.Max(Math.Max(Math.Abs(M21), Math.Abs(M22)), Math.Abs(M23))); + return Math.Max(m, Math.Max(Math.Max(Math.Abs(M31), Math.Abs(M32)), Math.Abs(M33))); + } +} diff --git a/src/Titano.Core/Math/MonotoneSpline.cs b/src/Titano.Core/Math/MonotoneSpline.cs new file mode 100644 index 00000000..718e4918 --- /dev/null +++ b/src/Titano.Core/Math/MonotoneSpline.cs @@ -0,0 +1,177 @@ +namespace Titano.Core.Mathematics; + +/// +/// Monotone piecewise cubic Hermite interpolant (Fritsch & Carlson 1980): three-point tangents limited to the +/// circle α² + β² ≤ 9 so the curve never overshoots monotone data. Outside the knot range the value is clamped +/// to the end values (derivative 0), which keeps time remaps monotone. +/// +public sealed class MonotoneSpline +{ + private readonly double[] _x; + private readonly double[] _y; + private readonly double[] _m; + + /// Strictly increasing, finite knot positions (at least one). + /// Finite knot values. + public MonotoneSpline(ReadOnlySpan x, ReadOnlySpan y) + { + SplineInput.Validate(x, y, minimum: 1); + _x = x.ToArray(); + _y = y.ToArray(); + _m = new double[_x.Length]; + var n = _x.Length; + if (n == 1) return; + + var delta = new double[n - 1]; + var increasing = true; + var decreasing = true; + for (var k = 0; k < n - 1; k++) + { + delta[k] = (_y[k + 1] - _y[k]) / (_x[k + 1] - _x[k]); + increasing &= delta[k] >= 0; + decreasing &= delta[k] <= 0; + } + IsMonotone = increasing || decreasing; + + _m[0] = delta[0]; + _m[n - 1] = delta[n - 2]; + for (var k = 1; k < n - 1; k++) + { + if (delta[k - 1] * delta[k] <= 0) + { + _m[k] = 0; + continue; + } + // Three-point derivative for non-uniform spacing (exact for quadratics). + var h0 = _x[k] - _x[k - 1]; + var h1 = _x[k + 1] - _x[k]; + _m[k] = (h1 * delta[k - 1] + h0 * delta[k]) / (h0 + h1); + } + + for (var k = 0; k < n - 1; k++) + { + if (delta[k] == 0) + { + _m[k] = 0; + _m[k + 1] = 0; + continue; + } + var alpha = _m[k] / delta[k]; + var beta = _m[k + 1] / delta[k]; + if (alpha < 0) _m[k] = alpha = 0; + if (beta < 0) _m[k + 1] = beta = 0; + var s = alpha * alpha + beta * beta; + if (s > 9) + { + var tau = 3 / Math.Sqrt(s); + _m[k] = tau * alpha * delta[k]; + _m[k + 1] = tau * beta * delta[k]; + } + } + } + + public int Count => _x.Length; + + public double MinX => _x[0]; + + public double MaxX => _x[^1]; + + /// True when the knot values are entirely non-decreasing or non-increasing (required by ). + public bool IsMonotone { get; } = true; + + public double Evaluate(double x) + { + if (!(x > _x[0])) return _y[0]; + if (x >= _x[^1]) return _y[^1]; + var k = Interval(x); + var h = _x[k + 1] - _x[k]; + var t = (x - _x[k]) / h; + var t2 = t * t; + var t3 = t2 * t; + // Increment form: rounding scales with the interval's rise, so flat intervals stay exactly flat. + return _y[k] + (_y[k + 1] - _y[k]) * (3 * t2 - 2 * t3) + h * ((t3 - 2 * t2 + t) * _m[k] + (t3 - t2) * _m[k + 1]); + } + + public double Derivative(double x) + { + if (!(x > _x[0]) || x >= _x[^1]) return 0; + var k = Interval(x); + var h = _x[k + 1] - _x[k]; + var t = (x - _x[k]) / h; + var t2 = t * t; + return ((6 * t2 - 6 * t) * _y[k] + + (3 * t2 - 4 * t + 1) * h * _m[k] + + (-6 * t2 + 6 * t) * _y[k + 1] + + (3 * t2 - 2 * t) * h * _m[k + 1]) / h; + } + + /// + /// The x at which the spline reaches (values outside the range clamp to the end knots; + /// on a flat stretch the first x is returned). Safeguarded Newton iteration inside the bracketing interval. + /// + /// The knot values are not monotone. + public double Inverse(double y) + { + if (!IsMonotone) throw new InvalidOperationException("Inverse requires monotone knot values."); + var n = _x.Length; + var sign = _y[^1] >= _y[0] ? 1.0 : -1.0; + var target = sign * y; + if (n == 1 || !(target > sign * _y[0])) return _x[0]; + if (target >= sign * _y[^1]) return FirstAtEnd(); + + int lo = 0, hi = n - 1; + while (hi - lo > 1) + { + var mid = (lo + hi) >> 1; + if (sign * _y[mid] < target) lo = mid; + else hi = mid; + } + if (sign * _y[hi] == target) + { + while (hi > 0 && _y[hi - 1] == _y[hi]) hi--; + return _x[hi]; + } + + double a = _x[lo], b = _x[hi]; + var x = a + (b - a) * (target - sign * _y[lo]) / (sign * (_y[hi] - _y[lo])); + for (var i = 0; i < 100 && b - a > 1e-14 * (1 + Math.Abs(a)); i++) + { + var f = sign * Evaluate(x) - target; + if (f == 0) return x; + if (f < 0) a = x; + else b = x; + var d = sign * Derivative(x); + var next = d > 0 ? x - f / d : double.NaN; + x = next > a && next < b ? next : 0.5 * (a + b); + } + return x; + } + + private double FirstAtEnd() + { + var i = _x.Length - 1; + while (i > 0 && _y[i - 1] == _y[i]) i--; + return _x[i]; + } + + private int Interval(double x) + { + var i = Array.BinarySearch(_x, x); + if (i < 0) i = ~i - 1; + return Math.Clamp(i, 0, _x.Length - 2); + } +} + +internal static class SplineInput +{ + public static void Validate(ReadOnlySpan x, ReadOnlySpan y, int minimum) + { + if (x.Length != y.Length) throw new ArgumentException("x and y lengths differ.", nameof(y)); + if (x.Length < minimum) throw new ArgumentException($"At least {minimum} knot(s) required.", nameof(x)); + for (var i = 0; i < x.Length; i++) + { + if (!double.IsFinite(x[i]) || !double.IsFinite(y[i])) throw new ArgumentException("Knots must be finite.", nameof(x)); + if (i > 0 && !(x[i] > x[i - 1])) throw new ArgumentException("x must be strictly increasing.", nameof(x)); + } + } +} diff --git a/src/Titano.Core/Math/NaturalCubicSpline.cs b/src/Titano.Core/Math/NaturalCubicSpline.cs new file mode 100644 index 00000000..363f572f --- /dev/null +++ b/src/Titano.Core/Math/NaturalCubicSpline.cs @@ -0,0 +1,88 @@ +namespace Titano.Core.Mathematics; + +/// +/// Interpolating cubic spline with natural end conditions (zero second derivative), second derivatives solved +/// with the Thomas tridiagonal algorithm. C² inside the knot range; extrapolates linearly with the end slopes. +/// +public sealed class NaturalCubicSpline +{ + private readonly double[] _x; + private readonly double[] _y; + private readonly double[] _m; + + /// Strictly increasing, finite knot positions (at least one). + /// Finite knot values. + public NaturalCubicSpline(ReadOnlySpan x, ReadOnlySpan y) + { + SplineInput.Validate(x, y, minimum: 1); + _x = x.ToArray(); + _y = y.ToArray(); + var n = _x.Length; + _m = new double[n]; + if (n < 3) return; + + // Interior equations: h[i-1]·M[i-1] + 2(h[i-1]+h[i])·M[i] + h[i]·M[i+1] = 6(δ[i] − δ[i-1]). + var c = new double[n]; + var d = new double[n]; + for (var i = 1; i < n - 1; i++) + { + var h0 = _x[i] - _x[i - 1]; + var h1 = _x[i + 1] - _x[i]; + var rhs = 6 * ((_y[i + 1] - _y[i]) / h1 - (_y[i] - _y[i - 1]) / h0); + var diag = 2 * (h0 + h1) - h0 * c[i - 1]; + c[i] = h1 / diag; + d[i] = (rhs - h0 * d[i - 1]) / diag; + } + for (var i = n - 2; i >= 1; i--) _m[i] = d[i] - c[i] * _m[i + 1]; + } + + public int Count => _x.Length; + + public double Evaluate(double x) + { + var n = _x.Length; + if (n == 1) return _y[0]; + if (x < _x[0]) return _y[0] + Slope(0, atEnd: false) * (x - _x[0]); + if (x > _x[^1]) return _y[^1] + Slope(n - 2, atEnd: true) * (x - _x[^1]); + var k = Interval(x); + var h = _x[k + 1] - _x[k]; + var a = (_x[k + 1] - x) / h; + var b = 1 - a; + return a * _y[k] + b * _y[k + 1] + ((a * a * a - a) * _m[k] + (b * b * b - b) * _m[k + 1]) * h * h / 6; + } + + public double Derivative(double x) + { + var n = _x.Length; + if (n == 1) return 0; + if (x < _x[0]) return Slope(0, atEnd: false); + if (x > _x[^1]) return Slope(n - 2, atEnd: true); + var k = Interval(x); + var h = _x[k + 1] - _x[k]; + var a = (_x[k + 1] - x) / h; + var b = 1 - a; + return (_y[k + 1] - _y[k]) / h - (3 * a * a - 1) / 6 * h * _m[k] + (3 * b * b - 1) / 6 * h * _m[k + 1]; + } + + public double SecondDerivative(double x) + { + if (_x.Length == 1 || x <= _x[0] || x >= _x[^1]) return 0; + var k = Interval(x); + var a = (_x[k + 1] - x) / (_x[k + 1] - _x[k]); + return a * _m[k] + (1 - a) * _m[k + 1]; + } + + private double Slope(int k, bool atEnd) + { + var h = _x[k + 1] - _x[k]; + var secant = (_y[k + 1] - _y[k]) / h; + return atEnd ? secant + h * (_m[k] + 2 * _m[k + 1]) / 6 : secant - h * (2 * _m[k] + _m[k + 1]) / 6; + } + + private int Interval(double x) + { + var i = Array.BinarySearch(_x, x); + if (i < 0) i = ~i - 1; + return Math.Clamp(i, 0, _x.Length - 2); + } +} diff --git a/src/Titano.Core/Math/Point2.cs b/src/Titano.Core/Math/Point2.cs new file mode 100644 index 00000000..d1c1522c --- /dev/null +++ b/src/Titano.Core/Math/Point2.cs @@ -0,0 +1,17 @@ +namespace Titano.Core.Mathematics; + +/// A point or vector in the plane, double precision. +public readonly record struct Point2(double X, double Y) +{ + public static Point2 operator +(Point2 a, Point2 b) => new(a.X + b.X, a.Y + b.Y); + + public static Point2 operator -(Point2 a, Point2 b) => new(a.X - b.X, a.Y - b.Y); + + public static Point2 operator *(Point2 a, double s) => new(a.X * s, a.Y * s); + + public static Point2 operator *(double s, Point2 a) => new(a.X * s, a.Y * s); + + public double Length => Math.Sqrt(X * X + Y * Y); + + public static double Distance(Point2 a, Point2 b) => (a - b).Length; +} diff --git a/src/Titano.Core/Math/SolarPosition.cs b/src/Titano.Core/Math/SolarPosition.cs new file mode 100644 index 00000000..bfa7eb16 --- /dev/null +++ b/src/Titano.Core/Math/SolarPosition.cs @@ -0,0 +1,219 @@ +namespace Titano.Core.Mathematics; + +/// Light condition by solar elevation (geometric centre of the disc). +public enum DayPhase +{ + /// Sun below −18°. + Night, + + /// −18° to −12°. + AstronomicalTwilight, + + /// −12° to −6°. + NauticalTwilight, + + /// −6° to sunrise/sunset (−0.833°). + CivilTwilight, + + /// Sun up but below 6°. + GoldenHour, + + /// Sun at or above 6°. + Day, +} + +/// Sun position for an instant and place. +/// Apparent elevation in degrees, corrected for standard atmospheric refraction. +/// Degrees clockwise from true north. +/// Elevation without refraction, in degrees (used for twilight limits). +/// Solar declination in degrees. +/// Apparent minus mean solar time, in minutes. +public readonly record struct SolarCoordinates(double Elevation, double Azimuth, double GeometricElevation, double Declination, double EquationOfTimeMinutes) +{ + public DayPhase Phase => SolarPosition.Classify(GeometricElevation); +} + +/// Sun events of one local solar day, all in UTC; null when the event does not occur (polar day/night). +public sealed record SolarDay( + DateOnly Date, + DateTime SolarNoon, + DateTime? Sunrise, + DateTime? Sunset, + DateTime? CivilDawn, + DateTime? CivilDusk, + DateTime? NauticalDawn, + DateTime? NauticalDusk, + DateTime? AstronomicalDawn, + DateTime? AstronomicalDusk); + +/// +/// Solar position and rise/set times with the NOAA Solar Calculator equations (after Meeus, "Astronomical +/// Algorithms"). Event times are refined iteratively at the event instant; accuracy is about one minute for +/// latitudes within ±72°. Longitudes are east-positive, latitudes north-positive, times UTC. +/// +public static class SolarPosition +{ + /// Geometric elevation of the disc centre at apparent sunrise/sunset (34′ refraction + 16′ semi-diameter). + public const double SunriseElevation = -0.833; + + public const double CivilTwilightElevation = -6; + public const double NauticalTwilightElevation = -12; + public const double AstronomicalTwilightElevation = -18; + public const double GoldenHourElevation = 6; + + private const double Deg = Math.PI / 180; + private static readonly DateTime J2000 = new(2000, 1, 1, 12, 0, 0, DateTimeKind.Utc); + + /// Sun position at (a value of unspecified kind is taken as UTC). + public static SolarCoordinates Compute(DateTime utc, double latitude, double longitude) + { + ValidateLocation(latitude, longitude); + var sun = Ephemeris(utc); + var minutes = utc.TimeOfDay.TotalMinutes; + var trueSolarTime = Mod(minutes + sun.EquationOfTime + 4 * longitude, 1440); + var hourAngle = trueSolarTime / 4 - 180; + + var phi = latitude * Deg; + var delta = sun.Declination * Deg; + var cosZenith = Math.Clamp(Math.Sin(phi) * Math.Sin(delta) + Math.Cos(phi) * Math.Cos(delta) * Math.Cos(hourAngle * Deg), -1, 1); + var zenith = Math.Acos(cosZenith); + var geometric = 90 - zenith / Deg; + + double azimuth; + var denominator = Math.Cos(phi) * Math.Sin(zenith); + if (Math.Abs(denominator) < 1e-12) + { + azimuth = latitude > 0 ? 180 : 0; + } + else + { + var a = Math.Acos(Math.Clamp((Math.Sin(phi) * cosZenith - Math.Sin(delta)) / denominator, -1, 1)) / Deg; + azimuth = hourAngle > 0 ? Mod(a + 180, 360) : Mod(540 - a, 360); + } + return new SolarCoordinates(geometric + Refraction(geometric), azimuth, geometric, sun.Declination, sun.EquationOfTime); + } + + /// Day phase from the geometric elevation in degrees. + public static DayPhase Classify(double geometricElevation) => geometricElevation switch + { + < AstronomicalTwilightElevation => DayPhase.Night, + < NauticalTwilightElevation => DayPhase.AstronomicalTwilight, + < CivilTwilightElevation => DayPhase.NauticalTwilight, + < SunriseElevation => DayPhase.CivilTwilight, + < GoldenHourElevation => DayPhase.GoldenHour, + _ => DayPhase.Day, + }; + + public static DayPhase Phase(DateTime utc, double latitude, double longitude) => Compute(utc, latitude, longitude).Phase; + + /// All rise/set and twilight events of the local solar day (the day whose solar + /// noon falls on that calendar date at the given longitude). + public static SolarDay Events(DateOnly date, double latitude, double longitude) + { + ValidateLocation(latitude, longitude); + return new SolarDay( + date, + SolarNoon(date, longitude), + EventTime(date, latitude, longitude, SunriseElevation, rising: true), + EventTime(date, latitude, longitude, SunriseElevation, rising: false), + EventTime(date, latitude, longitude, CivilTwilightElevation, rising: true), + EventTime(date, latitude, longitude, CivilTwilightElevation, rising: false), + EventTime(date, latitude, longitude, NauticalTwilightElevation, rising: true), + EventTime(date, latitude, longitude, NauticalTwilightElevation, rising: false), + EventTime(date, latitude, longitude, AstronomicalTwilightElevation, rising: true), + EventTime(date, latitude, longitude, AstronomicalTwilightElevation, rising: false)); + } + + /// UTC solar noon (upper transit) of the local solar day. + public static DateTime SolarNoon(DateOnly date, double longitude) + { + var midnight = date.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc); + var minutes = 720 - 4 * longitude; + for (var i = 0; i < 3; i++) + minutes = 720 - 4 * longitude - Ephemeris(midnight.AddMinutes(minutes)).EquationOfTime; + return midnight.AddMinutes(minutes); + } + + /// + /// UTC time at which the sun's geometric centre crosses degrees on the given + /// local solar day, rising (morning) or setting (evening); null when it stays above or below all day. + /// + public static DateTime? EventTime(DateOnly date, double latitude, double longitude, double elevation, bool rising) + { + ValidateLocation(latitude, longitude); + var midnight = date.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc); + var minutes = 720 - 4 * longitude; + for (var i = 0; i < 4; i++) + { + var sun = Ephemeris(midnight.AddMinutes(minutes)); + var hourAngle = HourAngle(latitude, sun.Declination, elevation); + if (double.IsNaN(hourAngle)) return null; + var noon = 720 - 4 * longitude - sun.EquationOfTime; + minutes = noon + (rising ? -4 : 4) * hourAngle; + } + return midnight.AddMinutes(minutes); + } + + private static double HourAngle(double latitude, double declination, double elevation) + { + var phi = latitude * Deg; + var delta = declination * Deg; + var cosH = (Math.Cos((90 - elevation) * Deg) - Math.Sin(phi) * Math.Sin(delta)) / (Math.Cos(phi) * Math.Cos(delta)); + return cosH is < -1 or > 1 || double.IsNaN(cosH) ? double.NaN : Math.Acos(cosH) / Deg; + } + + /// NOAA approximation of standard atmospheric refraction, in degrees, for a geometric elevation. + private static double Refraction(double elevation) + { + if (elevation > 85) return 0; + var t = Math.Tan(elevation * Deg); + var arcSeconds = elevation switch + { + > 5 => 58.1 / t - 0.07 / (t * t * t) + 0.000086 / Math.Pow(t, 5), + > -0.575 => 1735 + elevation * (-518.2 + elevation * (103.4 + elevation * (-12.79 + elevation * 0.711))), + _ => -20.772 / t, + }; + return arcSeconds / 3600; + } + + private readonly record struct Sun(double Declination, double EquationOfTime); + + private static Sun Ephemeris(DateTime utc) + { + var julianDay = 2451545.0 + (DateTime.SpecifyKind(utc, DateTimeKind.Utc) - J2000).TotalDays; + var t = (julianDay - 2451545.0) / 36525.0; + var meanLongitude = Mod(280.46646 + t * (36000.76983 + t * 0.0003032), 360); + var meanAnomaly = 357.52911 + t * (35999.05029 - 0.0001537 * t); + var eccentricity = 0.016708634 - t * (0.000042037 + 0.0000001267 * t); + var m = meanAnomaly * Deg; + var center = Math.Sin(m) * (1.914602 - t * (0.004817 + 0.000014 * t)) + + Math.Sin(2 * m) * (0.019993 - 0.000101 * t) + + Math.Sin(3 * m) * 0.000289; + var trueLongitude = meanLongitude + center; + var omega = (125.04 - 1934.136 * t) * Deg; + var apparentLongitude = trueLongitude - 0.00569 - 0.00478 * Math.Sin(omega); + var meanObliquity = 23 + (26 + (21.448 - t * (46.815 + t * (0.00059 - t * 0.001813))) / 60) / 60; + var obliquity = (meanObliquity + 0.00256 * Math.Cos(omega)) * Deg; + var declination = Math.Asin(Math.Sin(obliquity) * Math.Sin(apparentLongitude * Deg)) / Deg; + + var y = Math.Tan(obliquity / 2); + y *= y; + var l0 = meanLongitude * Deg; + var e = eccentricity; + var equationOfTime = 4 / Deg * (y * Math.Sin(2 * l0) - 2 * e * Math.Sin(m) + 4 * e * y * Math.Sin(m) * Math.Cos(2 * l0) + - 0.5 * y * y * Math.Sin(4 * l0) - 1.25 * e * e * Math.Sin(2 * m)); + return new Sun(declination, equationOfTime); + } + + private static double Mod(double value, double modulus) + { + var r = value % modulus; + return r < 0 ? r + modulus : r; + } + + private static void ValidateLocation(double latitude, double longitude) + { + if (!(latitude >= -90 && latitude <= 90)) throw new ArgumentOutOfRangeException(nameof(latitude)); + if (!(longitude >= -180 && longitude <= 180)) throw new ArgumentOutOfRangeException(nameof(longitude)); + } +} diff --git a/src/Titano.Core/Math/Statistics.cs b/src/Titano.Core/Math/Statistics.cs new file mode 100644 index 00000000..587aefa6 --- /dev/null +++ b/src/Titano.Core/Math/Statistics.cs @@ -0,0 +1,417 @@ +using System.Buffers; +using System.Numerics; + +namespace Titano.Core.Mathematics; + +/// A robustly fitted straight line y = Intercept + Slope·x. +/// Robust residual standard deviation (1.4826 × MAD of the final residuals). +public readonly record struct RobustLine(double Slope, double Intercept, double Scale) +{ + public double Evaluate(double x) => Intercept + Slope * x; +} + +/// +/// Order statistics and robust estimators. Every function ignores NaN inputs and returns NaN when no +/// valid value remains. Selection is linear-time (quickselect with an introsort fallback). +/// +public static class Statistics +{ + /// Scales a median absolute deviation to the standard deviation of a normal distribution (1/Φ⁻¹(3/4)). + public const double MadToSigma = 1.482602218505602; + + /// + /// Rearranges so that values[k] is the k-th smallest, everything before it is + /// ≤ and everything after is ≥ (Hoare quickselect, median-of-three pivot; falls back to sorting the + /// remaining range after too many unbalanced rounds, so the worst case is O(n log n)). NaN-free input. + /// + public static double Select(Span values, int k) + { + if ((uint)k >= (uint)values.Length) throw new ArgumentOutOfRangeException(nameof(k)); + int lo = 0, hi = values.Length - 1; + var budget = 2 * BitOperations.Log2((uint)values.Length) + 4; + while (hi > lo) + { + if (hi - lo < 16 || --budget < 0) + { + values.Slice(lo, hi - lo + 1).Sort(); + return values[k]; + } + var mid = lo + ((hi - lo) >> 1); + if (values[mid] < values[lo]) (values[mid], values[lo]) = (values[lo], values[mid]); + if (values[hi] < values[lo]) (values[hi], values[lo]) = (values[lo], values[hi]); + if (values[hi] < values[mid]) (values[hi], values[mid]) = (values[mid], values[hi]); + var pivot = values[mid]; + int i = lo, j = hi; + while (i <= j) + { + while (values[i] < pivot) i++; + while (values[j] > pivot) j--; + if (i <= j) + { + (values[i], values[j]) = (values[j], values[i]); + i++; + j--; + } + } + if (k <= j) hi = j; + else if (k >= i) lo = i; + else return values[k]; + } + return values[k]; + } + + public static double Mean(ReadOnlySpan values) + { + double sum = 0; + var n = 0; + foreach (var v in values) + { + if (double.IsNaN(v)) continue; + sum += v; + n++; + } + return n == 0 ? double.NaN : sum / n; + } + + /// Root mean square of the valid values. + public static double Rms(ReadOnlySpan values) + { + double sum = 0; + var n = 0; + foreach (var v in values) + { + if (double.IsNaN(v)) continue; + sum += v * v; + n++; + } + return n == 0 ? double.NaN : Math.Sqrt(sum / n); + } + + /// Sample standard deviation (n − 1 denominator) of the valid values. + public static double StandardDeviation(ReadOnlySpan values) + { + var mean = Mean(values); + double sum = 0; + var n = 0; + foreach (var v in values) + { + if (double.IsNaN(v)) continue; + sum += (v - mean) * (v - mean); + n++; + } + return n < 2 ? double.NaN : Math.Sqrt(sum / (n - 1)); + } + + public static double Median(ReadOnlySpan values) + { + var buffer = RentValid(values, out var n); + try + { + return n == 0 ? double.NaN : MedianInPlace(buffer.AsSpan(0, n)); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + /// Median of NaN-free , reordering them. + public static double MedianInPlace(Span values) + { + var n = values.Length; + if (n == 0) return double.NaN; + var upper = Select(values, n / 2); + if ((n & 1) == 1) return upper; + var lower = double.NegativeInfinity; + foreach (var v in values[..(n / 2)]) lower = Math.Max(lower, v); + return 0.5 * (lower + upper); + } + + /// Raw median absolute deviation about (the median when omitted). + /// Multiply by for a normal-consistent scale. + public static double MedianAbsoluteDeviation(ReadOnlySpan values, double? center = null) + { + var buffer = RentValid(values, out var n); + try + { + if (n == 0) return double.NaN; + var span = buffer.AsSpan(0, n); + var c = center ?? MedianInPlace(span); + for (var i = 0; i < n; i++) span[i] = Math.Abs(span[i] - c); + return MedianInPlace(span); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + /// Mean after discarding the lowest and highest + /// of the valid values (counts rounded down), in linear time. + public static double TrimmedMean(ReadOnlySpan values, double lowFraction, double highFraction) + { + if (!(lowFraction >= 0 && highFraction >= 0 && lowFraction + highFraction < 1)) + throw new ArgumentOutOfRangeException(nameof(lowFraction), "Fractions must be ≥ 0 and sum below 1."); + var buffer = RentValid(values, out var n); + try + { + if (n == 0) return double.NaN; + var span = buffer.AsSpan(0, n); + var low = (int)(n * lowFraction); + var keep = n - low - (int)(n * highFraction); + if (keep <= 0) return MedianInPlace(span); + if (low > 0) Select(span, low); + var rest = span[low..]; + if (keep < rest.Length) Select(rest, keep - 1); + double sum = 0; + foreach (var v in rest[..keep]) sum += v; + return sum / keep; + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + /// Percentile ∈ [0, 1] with linear interpolation between order statistics + /// (Hyndman–Fan type 7, the spreadsheet/NumPy default). + public static double Percentile(ReadOnlySpan values, double p) + { + if (!(p >= 0 && p <= 1)) throw new ArgumentOutOfRangeException(nameof(p)); + var buffer = RentValid(values, out var n); + try + { + if (n == 0) return double.NaN; + var span = buffer.AsSpan(0, n); + var h = (n - 1) * p; + var lo = (int)Math.Floor(h); + var a = Select(span, lo); + if (lo + 1 >= n || h == lo) return a; + var b = double.PositiveInfinity; + foreach (var v in span[(lo + 1)..]) b = Math.Min(b, v); + return a + (h - lo) * (b - a); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + /// + /// Weighted percentile: each value occupies a share of the cumulative weight and is placed at the centre + /// of its share; results interpolate linearly between centres and clamp outside them. Values with NaN or + /// non-positive weight are ignored. Equal weights reproduce the Hazen (type 5) percentile. + /// + public static double WeightedPercentile(ReadOnlySpan values, ReadOnlySpan weights, double p) + { + if (values.Length != weights.Length) throw new ArgumentException("Lengths differ.", nameof(weights)); + if (!(p >= 0 && p <= 1)) throw new ArgumentOutOfRangeException(nameof(p)); + var keys = new List(values.Length); + var w = new List(values.Length); + for (var i = 0; i < values.Length; i++) + { + if (double.IsNaN(values[i]) || !(weights[i] > 0) || double.IsInfinity(weights[i])) continue; + keys.Add(values[i]); + w.Add(weights[i]); + } + var n = keys.Count; + if (n == 0) return double.NaN; + var k = keys.ToArray(); + var ww = w.ToArray(); + Array.Sort(k, ww); + double total = 0; + foreach (var x in ww) total += x; + var target = p * total; + double cumulative = 0; + var previousCentre = 0.0; + for (var i = 0; i < n; i++) + { + var centre = cumulative + 0.5 * ww[i]; + if (target <= centre) + { + if (i == 0) return k[0]; + var t = (target - previousCentre) / (centre - previousCentre); + return k[i - 1] + t * (k[i] - k[i - 1]); + } + previousCentre = centre; + cumulative += ww[i]; + } + return k[n - 1]; + } + + /// Accumulates (optionally weighted) into equal-width bins over + /// [, ); values outside are clamped into the end bins. + public static void AccumulateHistogram(ReadOnlySpan values, double min, double max, Span bins, ReadOnlySpan weights = default) + { + if (!(max > min)) throw new ArgumentOutOfRangeException(nameof(max)); + if (bins.IsEmpty) throw new ArgumentException("No bins.", nameof(bins)); + if (!weights.IsEmpty && weights.Length != values.Length) throw new ArgumentException("Lengths differ.", nameof(weights)); + var scale = bins.Length / (max - min); + var last = bins.Length - 1; + for (var i = 0; i < values.Length; i++) + { + var v = values[i]; + if (double.IsNaN(v)) continue; + var b = (v - min) * scale; + var index = b <= 0 ? 0 : b >= last ? last : (int)b; + bins[index] += weights.IsEmpty ? 1 : weights[i]; + } + } + + /// Percentile of a histogram over [, ), interpolating + /// linearly inside the bin that contains the target mass. + public static double HistogramPercentile(ReadOnlySpan bins, double min, double max, double p) + { + if (!(p >= 0 && p <= 1)) throw new ArgumentOutOfRangeException(nameof(p)); + double total = 0; + foreach (var b in bins) total += b; + if (!(total > 0)) return double.NaN; + var width = (max - min) / bins.Length; + var target = p * total; + double cumulative = 0; + for (var i = 0; i < bins.Length; i++) + { + if (bins[i] <= 0) continue; + if (cumulative + bins[i] >= target) + return min + width * (i + (target - cumulative) / bins[i]); + cumulative += bins[i]; + } + return max; + } + + /// Symmetric chi-square distance ½·Σ (aᵢ − bᵢ)² / (aᵢ + bᵢ) between two histograms normalised to unit mass + /// (0 = identical, 1 = disjoint). + public static double ChiSquareDistance(ReadOnlySpan a, ReadOnlySpan b) + { + if (a.Length != b.Length) throw new ArgumentException("Lengths differ.", nameof(b)); + double sa = 0, sb = 0; + for (var i = 0; i < a.Length; i++) + { + sa += a[i]; + sb += b[i]; + } + if (!(sa > 0) || !(sb > 0)) return sa > 0 || sb > 0 ? 1 : 0; + double d = 0; + for (var i = 0; i < a.Length; i++) + { + var x = a[i] / sa; + var y = b[i] / sb; + var s = x + y; + if (s > 0) d += (x - y) * (x - y) / s; + } + return 0.5 * d; + } + + /// + /// Robust straight-line fit: Tukey's resistant line (medians of the outer thirds) as the start, then + /// iteratively reweighted least squares with Tukey biweights on residuals scaled by 6·MAD. + /// Pairs with a NaN coordinate are ignored. + /// + public static RobustLine RobustLinearFit(ReadOnlySpan x, ReadOnlySpan y, int iterations = 10) + { + if (x.Length != y.Length) throw new ArgumentException("Lengths differ.", nameof(y)); + var px = new List(x.Length); + var py = new List(x.Length); + for (var i = 0; i < x.Length; i++) + { + if (!double.IsFinite(x[i]) || !double.IsFinite(y[i])) continue; + px.Add(x[i]); + py.Add(y[i]); + } + var n = px.Count; + if (n == 0) return new RobustLine(0, double.NaN, double.NaN); + var xs = px.ToArray(); + var ys = py.ToArray(); + Array.Sort(xs, ys); + if (n < 3 || xs[^1] == xs[0]) + { + var c = Median(ys); + return new RobustLine(0, c, MadToSigma * MedianAbsoluteDeviation(ys, c)); + } + + var third = Math.Max(1, n / 3); + var xl = Median(xs.AsSpan(0, third)); + var xr = Median(xs.AsSpan(n - third)); + var slope = xr > xl ? (Median(ys.AsSpan(n - third)) - Median(ys.AsSpan(0, third))) / (xr - xl) : 0; + var residual = new double[n]; + for (var i = 0; i < n; i++) residual[i] = ys[i] - slope * xs[i]; + var intercept = Median(residual); + + var scaleFloor = 1e-12 * (1 + Math.Abs(Median(ys))); + for (var iteration = 0; iteration < iterations; iteration++) + { + for (var i = 0; i < n; i++) residual[i] = ys[i] - intercept - slope * xs[i]; + var mad = MedianAbsoluteDeviation(residual, 0); + if (!(mad > scaleFloor)) break; + var c = 6 * mad; + double sw = 0, swx = 0, swy = 0, swxx = 0, swxy = 0; + for (var i = 0; i < n; i++) + { + var u = residual[i] / c; + if (Math.Abs(u) >= 1) continue; + var w = (1 - u * u) * (1 - u * u); + sw += w; + swx += w * xs[i]; + swy += w * ys[i]; + swxx += w * xs[i] * xs[i]; + swxy += w * xs[i] * ys[i]; + } + if (!(sw > 0)) break; + var mx = swx / sw; + var sxx = swxx - sw * mx * mx; + if (!(sxx > 1e-300)) break; + var newSlope = (swxy - swx * swy / sw) / sxx; + var newIntercept = swy / sw - newSlope * mx; + var converged = Math.Abs(newSlope - slope) <= 1e-12 * (1 + Math.Abs(slope)) + && Math.Abs(newIntercept - intercept) <= 1e-12 * (1 + Math.Abs(intercept)); + slope = newSlope; + intercept = newIntercept; + if (converged) break; + } + for (var i = 0; i < n; i++) residual[i] = ys[i] - intercept - slope * xs[i]; + return new RobustLine(slope, intercept, MadToSigma * MedianAbsoluteDeviation(residual, 0)); + } + + /// + /// Sample autocorrelation r(k) for k = 0 … result.Length − 1 (biased estimator normalised by the lag-0 + /// sum, so |r| ≤ 1). Pairs containing NaN are skipped. A constant series yields r(0) = 1 and 0 elsewhere. + /// + public static void Autocorrelation(ReadOnlySpan values, Span result) + { + result.Clear(); + if (result.IsEmpty) return; + var mean = Mean(values); + if (double.IsNaN(mean)) return; + double denominator = 0; + foreach (var v in values) + { + if (!double.IsNaN(v)) denominator += (v - mean) * (v - mean); + } + result[0] = 1; + if (!(denominator > 0)) return; + var maxLag = Math.Min(result.Length - 1, values.Length - 1); + for (var k = 1; k <= maxLag; k++) + { + double sum = 0; + for (var i = 0; i + k < values.Length; i++) + { + var a = values[i]; + var b = values[i + k]; + if (double.IsNaN(a) || double.IsNaN(b)) continue; + sum += (a - mean) * (b - mean); + } + result[k] = sum / denominator; + } + } + + private static double[] RentValid(ReadOnlySpan values, out int count) + { + var buffer = ArrayPool.Shared.Rent(Math.Max(1, values.Length)); + count = 0; + foreach (var v in values) + { + if (!double.IsNaN(v)) buffer[count++] = v; + } + return buffer; + } +} diff --git a/tests/Titano.Core.Tests/Analysis/AnalysisFixtures.cs b/tests/Titano.Core.Tests/Analysis/AnalysisFixtures.cs new file mode 100644 index 00000000..35d6bf2f --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/AnalysisFixtures.cs @@ -0,0 +1,59 @@ +using Titano.Core.Analysis; +using Titano.Core.Diagnostics.Synthetic; +using Titano.Core.Imaging; + +namespace Titano.Core.Tests.Analysis; + +/// Shared measurement helpers for the analysis tests. +internal static class AnalysisFixtures +{ + /// Trimmed-mean log2 luminance of every frame, optionally after applying a per-frame correction. + public static double[] MeasureSeries(SyntheticSequence sequence, Func? 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; + } + + /// RMS of the frame-to-frame change of (series − truth): flicker relative to the true curve, free of + /// any constant offset. + public static double FrameToFrameResidualRms(IReadOnlyList series, IReadOnlyList 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)); + } + + /// Largest |series − truth − c| where c is the mean offset (the measurement constant). + public static double MaxDeviation(IReadOnlyList series, IReadOnlyList 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; + } + + /// Land pixels at least rows below the true horizon (weight 1), else 0. + 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; + } +} diff --git a/tests/Titano.Core.Tests/Analysis/AnalysisPropertyTests.cs b/tests/Titano.Core.Tests/Analysis/AnalysisPropertyTests.cs new file mode 100644 index 00000000..008f0fae --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/AnalysisPropertyTests.cs @@ -0,0 +1,93 @@ +using Titano.Core.Analysis; +using Titano.Testing; + +namespace Titano.Core.Tests.Analysis; + +/// Seeded random inputs: outputs stay finite where defined and repeat exactly. +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); + } + } +} diff --git a/tests/Titano.Core.Tests/Analysis/DeflickerEngineTests.cs b/tests/Titano.Core.Tests/Analysis/DeflickerEngineTests.cs new file mode 100644 index 00000000..874bc701 --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/DeflickerEngineTests.cs @@ -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) +{ + /// 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). + [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(() => 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); + } +} diff --git a/tests/Titano.Core.Tests/Analysis/ExposureProcessorTests.cs b/tests/Titano.Core.Tests/Analysis/ExposureProcessorTests.cs new file mode 100644 index 00000000..a4ad4bdc --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/ExposureProcessorTests.cs @@ -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(() => ExposureProcessor.Apply(image, double.NaN)); + Assert.Throws(() => 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(() => 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); + } + } +} diff --git a/tests/Titano.Core.Tests/Analysis/FlickerSpectrumTests.cs b/tests/Titano.Core.Tests/Analysis/FlickerSpectrumTests.cs new file mode 100644 index 00000000..33fa43f0 --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/FlickerSpectrumTests.cs @@ -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); + } +} diff --git a/tests/Titano.Core.Tests/Analysis/FrameStatisticsTests.cs b/tests/Titano.Core.Tests/Analysis/FrameStatisticsTests.cs new file mode 100644 index 00000000..c01652c3 --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/FrameStatisticsTests.cs @@ -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) +{ + /// + /// 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); + } +} diff --git a/tests/Titano.Core.Tests/Analysis/HolyGrailEngineTests.cs b/tests/Titano.Core.Tests/Analysis/HolyGrailEngineTests.cs new file mode 100644 index 00000000..3becabf6 --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/HolyGrailEngineTests.cs @@ -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) +{ + /// + /// 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. + /// + [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); + } +} diff --git a/tests/Titano.Core.Tests/Analysis/LightAnalyzerTests.cs b/tests/Titano.Core.Tests/Analysis/LightAnalyzerTests.cs new file mode 100644 index 00000000..75cdb54b --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/LightAnalyzerTests.cs @@ -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()); + 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); + } +} diff --git a/tests/Titano.Core.Tests/Analysis/RegionTests.cs b/tests/Titano.Core.Tests/Analysis/RegionTests.cs new file mode 100644 index 00000000..ad06ce20 --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/RegionTests.cs @@ -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 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(); + 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); + } + + /// 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. + [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); + } +} diff --git a/tests/Titano.Core.Tests/Analysis/SyntheticSequenceTests.cs b/tests/Titano.Core.Tests/Analysis/SyntheticSequenceTests.cs new file mode 100644 index 00000000..8ed0539f --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/SyntheticSequenceTests.cs @@ -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(() => sequence.Render(1)); + } +} diff --git a/tests/Titano.Core.Tests/Analysis/WhiteBalanceSmootherTests.cs b/tests/Titano.Core.Tests/Analysis/WhiteBalanceSmootherTests.cs new file mode 100644 index 00000000..dad739b9 --- /dev/null +++ b/tests/Titano.Core.Tests/Analysis/WhiteBalanceSmootherTests.cs @@ -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(() => 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; + } +} diff --git a/tests/Titano.Core.Tests/Math/LocalRegressionTests.cs b/tests/Titano.Core.Tests/Math/LocalRegressionTests.cs new file mode 100644 index 00000000..194b6724 --- /dev/null +++ b/tests/Titano.Core.Tests/Math/LocalRegressionTests.cs @@ -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(); + 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(() => LocalRegression.Smooth([1.0], 0)); + Assert.Throws(() => 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); + } + } +} diff --git a/tests/Titano.Core.Tests/Math/Matrix3Tests.cs b/tests/Titano.Core.Tests/Math/Matrix3Tests.cs new file mode 100644 index 00000000..23128b2f --- /dev/null +++ b/tests/Titano.Core.Tests/Math/Matrix3Tests.cs @@ -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(() => 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}"); + } +} diff --git a/tests/Titano.Core.Tests/Math/SolarPositionTests.cs b/tests/Titano.Core.Tests/Math/SolarPositionTests.cs new file mode 100644 index 00000000..306b14ca --- /dev/null +++ b/tests/Titano.Core.Tests/Math/SolarPositionTests.cs @@ -0,0 +1,111 @@ +using System.Globalization; +using Titano.Core.Mathematics; +using Titano.Testing; + +namespace Titano.Core.Tests.Mathematics; + +/// +/// Reference values are NOAA Solar Calculator results (spreadsheet equations as implemented by the +/// astral package, cross-checked against PyEphem/VSOP87 to within 35 s), UTC, for the local solar day. +/// +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(() => SolarPosition.Compute(DateTime.UtcNow, 91, 0)); + } + + /// Expected "HH:mm:ss" on ; a leading '-' or '+' means the previous or next UTC day. + /// Returns the absolute deviation in seconds (0 when the event is correctly absent). + 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); + } +} diff --git a/tests/Titano.Core.Tests/Math/SplineTests.cs b/tests/Titano.Core.Tests/Math/SplineTests.cs new file mode 100644 index 00000000..669ae785 --- /dev/null +++ b/tests/Titano.Core.Tests/Math/SplineTests.cs @@ -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(() => new MonotoneSpline([0, 1, 2], [0, 1, 0]).Inverse(0.5)); + } + + [Test] + public void SplinesRejectInvalidKnots() + { + Assert.Throws(() => new MonotoneSpline([0, 0], [1, 2])); + Assert.Throws(() => new NaturalCubicSpline([0, 1], [1, double.NaN])); + Assert.Throws(() => 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()) + { + 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(() => new CubicBezierEasing(1.5, 0, 0.5, 1)); + } +} diff --git a/tests/Titano.Core.Tests/Math/StatisticsTests.cs b/tests/Titano.Core.Tests/Math/StatisticsTests.cs new file mode 100644 index 00000000..b845d789 --- /dev/null +++ b/tests/Titano.Core.Tests/Math/StatisticsTests.cs @@ -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(() => 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); + } +}