merge: analysis modules and math
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
42 files changed
+5963
No files matched your search
@@ -0,0 +1,51 @@
|
||||
using Titano.Core.Imaging;
|
||||
|
||||
namespace Titano.Core.Analysis;
|
||||
|
||||
/// <summary>Builds the reduced-size images that analysis passes measure.</summary>
|
||||
public static class AnalysisImage
|
||||
{
|
||||
/// <summary>
|
||||
/// Area-average (box) downscale by the smallest integer factor that brings the long edge to at most
|
||||
/// <paramref name="maxLongEdge"/>. Exact for flat fields; trailing rows/columns that do not fill a block are
|
||||
/// dropped. Returns a copy when no reduction is needed.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
using Titano.Core.Mathematics;
|
||||
|
||||
namespace Titano.Core.Analysis;
|
||||
|
||||
/// <summary>Correlated colour temperature of a near-Planckian colour.</summary>
|
||||
/// <param name="Kelvin">CCT: temperature of the nearest Planckian-locus point in CIE 1960 uv.</param>
|
||||
/// <param name="McCamyKelvin">McCamy's cubic estimate the search started from.</param>
|
||||
/// <param name="Duv">Signed uv distance from the locus (positive towards green).</param>
|
||||
public readonly record struct ColorTemperatureEstimate(double Kelvin, double McCamyKelvin, double Duv);
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <see cref="MaxDuv"/> from the locus have no meaningful CCT and are rejected.
|
||||
/// </summary>
|
||||
public static class ColorTemperature
|
||||
{
|
||||
/// <summary>Validity limit on |Duv| (ANSI C78.377 uses ±0.02 as the edge of "white" light).</summary>
|
||||
public const double MaxDuv = 0.02;
|
||||
|
||||
public const double MinKelvin = 1000;
|
||||
public const double MaxKelvin = 15000;
|
||||
|
||||
/// <summary>McCamy's cubic CCT approximation from CIE 1931 xy (epicentre 0.3320, 0.1858).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Planckian locus in CIE 1960 uv (Krystek 1985; |Δu|, |Δv| < 1e-4 over 1000–15000 K).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Linear Rec.709 RGB of a Planckian radiator's chromaticity, scaled to luminance 1.</summary>
|
||||
public static Vector3D PlanckianRgb(double kelvin) => Matrix3.XyzToRec709 * PlanckianChromaticity(kelvin).ToXyz();
|
||||
|
||||
/// <summary>Estimate from a chromaticity; null outside the locus range or beyond <see cref="MaxDuv"/>.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Estimate from mean linear Rec.709 RGB; null for non-positive or off-locus colours.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Distance to the locus point at <paramref name="kelvin"/>, signed by the side of the locus normal
|
||||
/// that points to larger v (the green side).</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
using Titano.Core.Mathematics;
|
||||
|
||||
namespace Titano.Core.Analysis;
|
||||
|
||||
/// <summary>Parameters of <see cref="DeflickerEngine"/>.</summary>
|
||||
public sealed record DeflickerOptions
|
||||
{
|
||||
public static DeflickerOptions Default { get; } = new();
|
||||
|
||||
/// <summary>Frames in each local fit (see <see cref="FlickerSpectrum"/> for a recommendation).</summary>
|
||||
public int Window { get; init; } = 21;
|
||||
|
||||
/// <summary>Local polynomial degree, 1 or 2.</summary>
|
||||
public int Degree { get; init; } = 1;
|
||||
|
||||
/// <summary>Tukey reweighting passes.</summary>
|
||||
public int RobustIterations { get; init; } = 3;
|
||||
|
||||
/// <summary>1 lands every frame on the fitted curve; lower values let trusted frames keep part of their own deviation.</summary>
|
||||
public double Strength { get; init; } = 1;
|
||||
}
|
||||
|
||||
/// <summary>Flicker before and after correction, in EV.</summary>
|
||||
/// <param name="FlickerBefore">RMS frame-to-frame step of the input relative to the fitted curve.</param>
|
||||
/// <param name="FlickerAfter">The same measure on the target curve.</param>
|
||||
/// <param name="ResidualRms">RMS of input minus fitted curve over valid frames.</param>
|
||||
/// <param name="OutlierCount">Frames whose robust weight fell below ½.</param>
|
||||
public sealed record DeflickerDiagnostics(double FlickerBefore, double FlickerAfter, double ResidualRms, int OutlierCount);
|
||||
|
||||
/// <summary>Per-frame deflicker result; arrays have one entry per frame.</summary>
|
||||
public sealed record DeflickerResult(
|
||||
double[] Target,
|
||||
double[] CorrectionEv,
|
||||
double[] Fitted,
|
||||
double[] RobustWeights,
|
||||
double[] SurvivingFraction,
|
||||
DeflickerDiagnostics Diagnostics);
|
||||
|
||||
/// <summary>
|
||||
/// Deflicker target curve (BRIEF §11.2): robust LOWESS (<see cref="LocalRegression"/>) 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.
|
||||
/// </summary>
|
||||
public static class DeflickerEngine
|
||||
{
|
||||
/// <param name="logLuminance">Measured log2 luminance per frame (NaN = unusable frame, corrected by 0).</param>
|
||||
/// <param name="intentionalOffsets">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.</param>
|
||||
public static DeflickerResult Compute(ReadOnlySpan<double> logLuminance, DeflickerOptions? options = null, ReadOnlySpan<double> 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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Luminance offsets implied by metadata exposure: −(EV − EV of the first known frame). Frames without EV
|
||||
/// inherit the previous known value.
|
||||
/// </summary>
|
||||
public static double[] OffsetsFromExposure(ReadOnlySpan<double?> 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<double> offsets, int i) => offsets.IsEmpty || !double.IsFinite(offsets[i]) ? 0 : offsets[i];
|
||||
|
||||
private static DeflickerDiagnostics Diagnose(double[] flat, double[] fitted, double[] target, ReadOnlySpan<double> 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Titano.Core.Imaging;
|
||||
|
||||
namespace Titano.Core.Analysis;
|
||||
|
||||
/// <summary>Per-channel multiplicative gains in linear light (white balance).</summary>
|
||||
public readonly record struct ChannelGains(double Red, double Green, double Blue)
|
||||
{
|
||||
public static ChannelGains Identity { get; } = new(1, 1, 1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <see cref="Vector{T}"/>; large images are split across cores. A fourth (alpha) channel is left untouched.
|
||||
/// </summary>
|
||||
public static class ExposureProcessor
|
||||
{
|
||||
private const int ParallelThreshold = 1 << 20;
|
||||
private const int Chunk = 1 << 16;
|
||||
|
||||
/// <param name="softClipKnee">When set (0 < knee < 1), values above the knee roll off smoothly towards 1.</param>
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static void ApplyRegion(ImageBuffer image, ReadOnlyMemory<float> 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);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>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.</summary>
|
||||
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<int, int> 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<float> data, float factor)
|
||||
{
|
||||
var vectors = MemoryMarshal.Cast<float, Vector<float>>(data);
|
||||
var f = new Vector<float>(factor);
|
||||
for (var i = 0; i < vectors.Length; i++) vectors[i] *= f;
|
||||
for (var i = vectors.Length * Vector<float>.Count; i < data.Length; i++) data[i] *= factor;
|
||||
}
|
||||
|
||||
private static void Blend(Span<float> data, ReadOnlySpan<float> mask, float baseFactor, float delta)
|
||||
{
|
||||
var vectors = MemoryMarshal.Cast<float, Vector<float>>(data);
|
||||
var masks = MemoryMarshal.Cast<float, Vector<float>>(mask);
|
||||
var b = new Vector<float>(baseFactor);
|
||||
var d = new Vector<float>(delta);
|
||||
for (var i = 0; i < vectors.Length; i++) vectors[i] *= b + masks[i] * d;
|
||||
for (var i = vectors.Length * Vector<float>.Count; i < data.Length; i++) data[i] *= baseFactor + mask[i] * delta;
|
||||
}
|
||||
|
||||
/// <summary>Compresses the largest channel with <see cref="SoftClip(float, float)"/> and scales all three
|
||||
/// channels by the same ratio, so hue and saturation are kept.</summary>
|
||||
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<float, Vector<float>>(r);
|
||||
var vg = MemoryMarshal.Cast<float, Vector<float>>(g);
|
||||
var vb = MemoryMarshal.Cast<float, Vector<float>>(b);
|
||||
var k = new Vector<float>(knee);
|
||||
var inverseRange = new Vector<float>(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<float>.One + excess * inverseRange)) / m;
|
||||
var s = Vector.ConditionalSelect(Vector.GreaterThan(m, k), ratio, Vector<float>.One);
|
||||
vr[i] *= s;
|
||||
vg[i] *= s;
|
||||
vb[i] *= s;
|
||||
}
|
||||
for (var i = vr.Length * Vector<float>.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
namespace Titano.Core.Analysis;
|
||||
|
||||
public enum FindingSeverity
|
||||
{
|
||||
Info,
|
||||
Warning,
|
||||
Error,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One explainable analysis result. <see cref="Key"/> is a stable resource key (e.g. <c>Advisor.Finding.Gaps</c>)
|
||||
/// whose localised text is a composite format filled with <see cref="Arguments"/> (<c>Loc.L(Key, Arguments)</c>).
|
||||
/// </summary>
|
||||
/// <param name="Frames">Indices of the frames concerned (capped at <see cref="MaxFrames"/>).</param>
|
||||
public sealed record Finding(string Key, FindingSeverity Severity, object[] Arguments, IReadOnlyList<int> Frames)
|
||||
{
|
||||
public const int MaxFrames = 256;
|
||||
}
|
||||
|
||||
/// <summary>Resource keys of the findings produced by the analysis modules.</summary>
|
||||
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";
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using Titano.Core.Mathematics;
|
||||
|
||||
namespace Titano.Core.Analysis;
|
||||
|
||||
/// <summary>Parameters of <see cref="FlickerSpectrum"/>.</summary>
|
||||
public sealed record FlickerSpectrumOptions
|
||||
{
|
||||
public static FlickerSpectrumOptions Default { get; } = new();
|
||||
|
||||
/// <summary>Smallest recommended deflicker window (frames, odd).</summary>
|
||||
public int MinimumWindow { get; init; } = 15;
|
||||
|
||||
/// <summary>Largest recommended deflicker window (frames, odd).</summary>
|
||||
public int MaximumWindow { get; init; } = 151;
|
||||
|
||||
/// <summary>A periodic peak must reach this autocorrelation (and 3/√n) to count.</summary>
|
||||
public double PeakThreshold { get; init; } = 0.25;
|
||||
}
|
||||
|
||||
/// <param name="Autocorrelation">r(k) of the detrended luminance for k = 0 … max lag.</param>
|
||||
/// <param name="DominantPeriod">Period of a periodic flicker component in frames (sub-frame), or null.</param>
|
||||
/// <param name="CorrelationLength">Frames until r drops below 1/e: the time scale of aperiodic flicker.</param>
|
||||
/// <param name="RecommendedWindow">4 × (period or correlation length), odd, clamped to the options' bounds.</param>
|
||||
public sealed record FlickerSpectrumResult(double[] Autocorrelation, double? DominantPeriod, double PeakCorrelation, double CorrelationLength, int RecommendedWindow);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class FlickerSpectrum
|
||||
{
|
||||
public static FlickerSpectrumResult Analyze(ReadOnlySpan<double> 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<int>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Mathematics;
|
||||
|
||||
namespace Titano.Core.Analysis;
|
||||
|
||||
/// <summary>Thresholds for <see cref="FrameStatistics.Measure"/>.</summary>
|
||||
public sealed record FrameStatisticsOptions
|
||||
{
|
||||
public static FrameStatisticsOptions Default { get; } = new();
|
||||
|
||||
/// <summary>Weight fraction trimmed from the dark end of the log-luminance distribution.</summary>
|
||||
public double TrimLow { get; init; } = 0.02;
|
||||
|
||||
/// <summary>Weight fraction trimmed from the bright end.</summary>
|
||||
public double TrimHigh { get; init; } = 0.02;
|
||||
|
||||
/// <summary>A pixel is crushed when every channel is below this linear level (1/1024 ≈ −10 EV).</summary>
|
||||
public double ClipLowLevel { get; init; } = 1.0 / 1024;
|
||||
|
||||
/// <summary>A pixel is clipped when any channel reaches this fraction of <see cref="WhiteLevel"/>.</summary>
|
||||
public double ClipHighFraction { get; init; } = 0.98;
|
||||
|
||||
public double WhiteLevel { get; init; } = 1.0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Per-frame (or per-region) measurements of the deep analysis (BRIEF §10.2), taken in one pass over a
|
||||
/// downscaled linear-light image (see <see cref="AnalysisImage"/>) plus one 3×3 neighbourhood pass.
|
||||
/// </summary>
|
||||
public sealed record FrameStatistics
|
||||
{
|
||||
public const int HistogramBins = 256;
|
||||
|
||||
/// <summary>Lower edge of the log-luminance histogram, in EV relative to linear 1.0.</summary>
|
||||
public const double HistogramMinEv = -14;
|
||||
|
||||
/// <summary>Upper edge of the log-luminance histogram, in EV relative to linear 1.0.</summary>
|
||||
public const double HistogramMaxEv = 2;
|
||||
|
||||
public int Width { get; init; }
|
||||
public int Height { get; init; }
|
||||
|
||||
/// <summary>Total sample weight: pixel count, or the mask sum for region statistics.</summary>
|
||||
public double Weight { get; init; }
|
||||
|
||||
/// <summary>Mean of log2 luminance after trimming both tails (luminance floored at 2⁻¹⁴).</summary>
|
||||
public double MeanLogLuminance { get; init; }
|
||||
|
||||
/// <summary>Weight fraction per bin of log2 luminance over [−14, +2) EV; sums to 1.</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>Correlated colour temperature of the mean colour; null when it is not near-Planckian.</summary>
|
||||
public ColorTemperatureEstimate? ColorTemperature { get; init; }
|
||||
|
||||
/// <summary>Variance of the 4-neighbour Laplacian of sRGB-encoded luminance (focus/blur measure).</summary>
|
||||
public double Sharpness { get; init; }
|
||||
|
||||
/// <summary>Noise standard deviation of sRGB-encoded luminance, Immerkær (1996) fast estimator.</summary>
|
||||
public double Noise { get; init; }
|
||||
|
||||
/// <summary>Nearly every pixel is crushed (lens cap, missed exposure).</summary>
|
||||
public bool IsBlack(double fraction = 0.95) => ClipLowFraction >= fraction;
|
||||
|
||||
/// <summary>Nearly every pixel is clipped (blown exposure).</summary>
|
||||
public bool IsWhite(double fraction = 0.95) => ClipHighFraction >= fraction;
|
||||
|
||||
/// <summary>
|
||||
/// True when two frames have practically identical statistics (histogram, level, colour, detail, noise): a
|
||||
/// cheap duplicate test before any pixel or hash comparison.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Measures an image, optionally weighted by a per-pixel <paramref name="mask"/> in [0, 1].</summary>
|
||||
public static FrameStatistics Measure(ImageBuffer image, ReadOnlySpan<float> 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,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Only the trimmed mean of log2 luminance (the deflicker signal), optionally mask-weighted.</summary>
|
||||
public static double MeasureLogLuminance(ImageBuffer image, ReadOnlySpan<float> 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<float> mask)
|
||||
{
|
||||
if (!mask.IsEmpty && mask.Length != image.PlaneLength)
|
||||
throw new ArgumentException("Mask must have one weight per pixel.", nameof(mask));
|
||||
}
|
||||
|
||||
/// <summary>Laplacian variance and Immerkær noise σ over interior pixels, weighted by the mask at the centre.</summary>
|
||||
private static (double Sharpness, double Noise) Detail(float[] e, int width, int height, ReadOnlySpan<float> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Normalised coarse histogram (bins must divide the fine bin count).</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
using Titano.Core.Mathematics;
|
||||
|
||||
namespace Titano.Core.Analysis;
|
||||
|
||||
/// <summary>Parameters of <see cref="HolyGrailEngine"/>.</summary>
|
||||
public sealed record HolyGrailOptions
|
||||
{
|
||||
public static HolyGrailOptions Default { get; } = new();
|
||||
|
||||
/// <summary>Transition length in frames; null = half the typical distance between received steps.</summary>
|
||||
public int? TransitionFrames { get; init; }
|
||||
|
||||
/// <summary>Transition length when fewer than two steps were received and none is configured.</summary>
|
||||
public int SingleStepTransitionFrames { get; init; } = 12;
|
||||
|
||||
/// <summary>Largest allowed frame-to-frame change of the target curve, in EV.</summary>
|
||||
public double MaxStepEv { get; init; } = 0.3;
|
||||
|
||||
/// <summary>Metadata EV changes smaller than this are not steps.</summary>
|
||||
public double MinimumStepEv { get; init; } = 0.05;
|
||||
|
||||
/// <summary>A step is received when the measured jump has the expected sign and at least this fraction of its size.</summary>
|
||||
public double MinimumReceivedFraction { get; init; } = 0.5;
|
||||
|
||||
/// <summary>Frames measured on each side of a step.</summary>
|
||||
public int MeasureFrames { get; init; } = 6;
|
||||
|
||||
public DeflickerOptions Deflicker { get; init; } = DeflickerOptions.Default;
|
||||
}
|
||||
|
||||
/// <summary>One metadata exposure step and how it was redistributed.</summary>
|
||||
/// <param name="Index">First frame shot with the new settings.</param>
|
||||
/// <param name="ExpectedEv">Luminance change implied by the metadata (−ΔEV).</param>
|
||||
/// <param name="MeasuredEv">Detrended luminance jump measured across the step (NaN when not measurable).</param>
|
||||
/// <param name="Received">Whether the pixels actually changed; ignored steps get no transition.</param>
|
||||
/// <param name="Start">Frame position where the smooth transition starts (fractional).</param>
|
||||
/// <param name="Length">Transition length in frames (0 when not received).</param>
|
||||
public sealed record ExposureTransition(int Index, double ExpectedEv, double MeasuredEv, bool Received, double Start, double Length);
|
||||
|
||||
/// <param name="Target">Target log2 luminance per frame.</param>
|
||||
/// <param name="CorrectionEv">Target − measured.</param>
|
||||
/// <param name="StepOffsets">Cumulative received steps (the abrupt exposure offsets in the pixels).</param>
|
||||
/// <param name="SmoothedOffsets">The same steps spread over their transitions.</param>
|
||||
/// <param name="MaxFrameStepEv">Largest |Target[i] − Target[i−1]|.</param>
|
||||
public sealed record HolyGrailResult(
|
||||
double[] Target,
|
||||
double[] CorrectionEv,
|
||||
double[] StepOffsets,
|
||||
double[] SmoothedOffsets,
|
||||
IReadOnlyList<ExposureTransition> Transitions,
|
||||
DeflickerResult Deflicker,
|
||||
double MaxFrameStepEv);
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <see cref="HolyGrailOptions.MaxStepEv"/>; ramps are kept inside the sequence so the total change is preserved.
|
||||
/// </summary>
|
||||
public static class HolyGrailEngine
|
||||
{
|
||||
/// <param name="logLuminance">Measured log2 luminance per frame (NaN = unusable).</param>
|
||||
/// <param name="exposureEv">Metadata EV (ISO 100) per frame; null when unknown.</param>
|
||||
public static HolyGrailResult Compute(ReadOnlySpan<double> logLuminance, ReadOnlySpan<double?> 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<ExposureTransition>(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<ExposureTransition> DetectSteps(double[] luminance, ReadOnlySpan<double?> 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<ExposureTransition>(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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static double MeasureJump(double[] luminance, int from, int index, int to)
|
||||
{
|
||||
var differences = new List<double>();
|
||||
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<double>();
|
||||
var right = new List<double>();
|
||||
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());
|
||||
}
|
||||
|
||||
/// <summary>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.</summary>
|
||||
private static double[] InitialLengths(List<ExposureTransition> 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<ExposureTransition> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Ramp centred on the boundary between frames index − 1 and index, shifted to lie inside [0, n − 1].</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
using Titano.Core.Mathematics;
|
||||
|
||||
namespace Titano.Core.Analysis;
|
||||
|
||||
/// <summary>Parameters of <see cref="LightAnalyzer"/>.</summary>
|
||||
public sealed record LightAnalysisOptions
|
||||
{
|
||||
public static LightAnalysisOptions Default { get; } = new();
|
||||
|
||||
/// <summary>A pause at least this long starts a new capture session.</summary>
|
||||
public double SessionGapMinutes { get; init; } = 45;
|
||||
|
||||
/// <summary>Sessions with fewer frames merge into the previous session (the first into the next).</summary>
|
||||
public int MinimumSessionFrames { get; init; } = 8;
|
||||
|
||||
/// <summary>An interval longer than this multiple of the median interval is a gap.</summary>
|
||||
public double GapFactor { get; init; } = 3;
|
||||
|
||||
/// <summary>Relative shutter-time or f-number change treated as a deliberate setting change.</summary>
|
||||
public double ExposureTolerance { get; init; } = 0.01;
|
||||
|
||||
/// <summary>Interval jitter (MAD) above this fraction of the median interval is reported.</summary>
|
||||
public double IrregularIntervalFraction { get; init; } = 0.1;
|
||||
}
|
||||
|
||||
/// <summary>How the interval leading into a frame was classified.</summary>
|
||||
public enum IntervalKind
|
||||
{
|
||||
Regular,
|
||||
|
||||
/// <summary>Longer than <see cref="LightAnalysisOptions.GapFactor"/> × the median interval.</summary>
|
||||
Gap,
|
||||
|
||||
/// <summary>At least <see cref="LightAnalysisOptions.SessionGapMinutes"/>.</summary>
|
||||
SessionBreak,
|
||||
|
||||
/// <summary>Same capture time as the previous frame.</summary>
|
||||
Duplicate,
|
||||
|
||||
/// <summary>Small step backwards in time (frames out of order).</summary>
|
||||
NonMonotonic,
|
||||
|
||||
/// <summary>Camera clock change: a backward step longer than the gap threshold, or a step exactly one hour off
|
||||
/// the cadence (daylight-saving change).</summary>
|
||||
ClockJump,
|
||||
}
|
||||
|
||||
/// <summary>The interval between the previous timed frame and frame <paramref name="Index"/>.</summary>
|
||||
public readonly record struct FrameInterval(int Index, double Seconds, IntervalKind Kind);
|
||||
|
||||
/// <summary>A run of frames shot without a pause of <see cref="LightAnalysisOptions.SessionGapMinutes"/> or more.</summary>
|
||||
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,
|
||||
}
|
||||
|
||||
/// <summary>A change of exposure settings between frame <paramref name="Index"/> − 1 and <paramref name="Index"/>.</summary>
|
||||
public sealed record ExposureStep(int Index, ExposureChange Changes, double EvBefore, double EvAfter)
|
||||
{
|
||||
/// <summary>Camera EV change; the pixels brighten by −<see cref="DeltaEv"/> stops.</summary>
|
||||
public double DeltaEv => EvAfter - EvBefore;
|
||||
}
|
||||
|
||||
public enum IdentityKind
|
||||
{
|
||||
Camera,
|
||||
Lens,
|
||||
}
|
||||
|
||||
/// <summary>The camera body or lens differs from the previous frame that recorded one.</summary>
|
||||
public sealed record IdentityChange(int Index, IdentityKind Kind, string? Before, string After);
|
||||
|
||||
/// <summary>Result of the metadata-only light analysis (BRIEF §10.1). Frame indices are positions in the input list.</summary>
|
||||
public sealed record LightAnalysisReport
|
||||
{
|
||||
public int FrameCount { get; init; }
|
||||
public int TimedFrameCount { get; init; }
|
||||
|
||||
/// <summary>Median of the positive intervals shorter than the session gap, in seconds.</summary>
|
||||
public double? MedianIntervalSeconds { get; init; }
|
||||
|
||||
/// <summary>Median absolute deviation of the regular intervals, in seconds.</summary>
|
||||
public double? JitterSeconds { get; init; }
|
||||
|
||||
public DateTime? FirstCapture { get; init; }
|
||||
public DateTime? LastCapture { get; init; }
|
||||
|
||||
/// <summary>Capture duration on the clock-corrected timeline (clock jumps count as one median interval).</summary>
|
||||
public TimeSpan CaptureSpan { get; init; }
|
||||
|
||||
/// <summary>Camera clock per frame with clock jumps and backward steps removed; null for untimed frames.</summary>
|
||||
public DateTime?[] AdjustedTimes { get; init; } = [];
|
||||
|
||||
/// <summary>Every interval between consecutive timed frames.</summary>
|
||||
public IReadOnlyList<FrameInterval> Intervals { get; init; } = [];
|
||||
|
||||
/// <summary>Intervals classified as <see cref="IntervalKind.Gap"/> or <see cref="IntervalKind.SessionBreak"/>.</summary>
|
||||
public IReadOnlyList<FrameInterval> Gaps { get; init; } = [];
|
||||
|
||||
/// <summary>Duplicate, non-monotonic and clock-jump intervals.</summary>
|
||||
public IReadOnlyList<FrameInterval> TimestampIssues { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<CaptureSession> Sessions { get; init; } = [];
|
||||
|
||||
/// <summary>EV at ISO 100 per frame; null when shutter time or f-number is missing.</summary>
|
||||
public double?[] ExposureValues { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<ExposureStep> ExposureSteps { get; init; } = [];
|
||||
|
||||
/// <summary>Median number of frames between consecutive exposure steps (null with fewer than two steps).</summary>
|
||||
public double? TypicalStepDistance { get; init; }
|
||||
|
||||
public IReadOnlyList<IdentityChange> IdentityChanges { get; init; } = [];
|
||||
|
||||
/// <summary>Most common oriented size, null when no frame records its size.</summary>
|
||||
public (int Width, int Height)? DominantSize { get; init; }
|
||||
|
||||
public IReadOnlyList<int> ResolutionOutliers { get; init; } = [];
|
||||
public int DominantOrientation { get; init; } = 1;
|
||||
public IReadOnlyList<int> OrientationOutliers { get; init; } = [];
|
||||
|
||||
/// <summary>Light condition per frame from GPS position and capture time; all null without GPS.</summary>
|
||||
public DayPhase?[] DayPhases { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<Finding> Findings { get; init; } = [];
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
using Titano.Core.Mathematics;
|
||||
using Titano.Core.Model;
|
||||
|
||||
namespace Titano.Core.Analysis;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class LightAnalyzer
|
||||
{
|
||||
private const double SameTimeSeconds = 0.001;
|
||||
private const double Hour = 3600;
|
||||
|
||||
public static LightAnalysisReport Analyze(IReadOnlyList<Frame> 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<LightFrame> 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<Finding>();
|
||||
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<FrameInterval> Intervals,
|
||||
List<CaptureSession> Sessions);
|
||||
|
||||
private static Timing AnalyzeTiming(IReadOnlyList<LightFrame> frames, LightAnalysisOptions options, List<Finding> 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<FrameInterval>(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<CaptureSession> BuildSessions(IReadOnlyList<LightFrame> frames, List<FrameInterval> 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<CaptureSession>(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<FrameInterval> intervals, List<CaptureSession> sessions, double? median, double? jitter, LightAnalysisOptions options, List<Finding> 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<FrameInterval> intervals, IntervalKind kind, string key, List<Finding> 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<ExposureStep> Steps, double? TypicalDistance);
|
||||
|
||||
private static Exposure AnalyzeExposure(IReadOnlyList<LightFrame> frames, LightAnalysisOptions options, List<Finding> findings)
|
||||
{
|
||||
var n = frames.Count;
|
||||
var values = new double?[n];
|
||||
var steps = new List<ExposureStep>();
|
||||
var missing = new List<int>();
|
||||
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<IdentityChange> AnalyzeIdentity(IReadOnlyList<LightFrame> frames, List<Finding> findings)
|
||||
{
|
||||
var changes = new List<IdentityChange>();
|
||||
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<int> SizeOutliers, int Orientation, List<int> OrientationOutliers) AnalyzeGeometry(IReadOnlyList<LightFrame> frames, List<Finding> findings)
|
||||
{
|
||||
var sizes = new Dictionary<(int, int), int>();
|
||||
var orientations = new Dictionary<int, int>();
|
||||
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<int>();
|
||||
var orientationOutliers = new List<int>();
|
||||
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<LightFrame> frames, DateTime?[] adjusted, List<Finding> 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;
|
||||
|
||||
/// <summary>Recorded UTC offset, else the camera-clock minus GPS-time difference rounded to 15 minutes.</summary>
|
||||
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<int> Indices(List<FrameInterval> intervals) => Cap(intervals.Select(i => i.Index));
|
||||
|
||||
private static List<int> Cap(IEnumerable<int> indices) => indices.Take(Finding.MaxFrames).ToList();
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
using Titano.Core.Metadata;
|
||||
using Titano.Core.Model;
|
||||
|
||||
namespace Titano.Core.Analysis;
|
||||
|
||||
/// <summary>The metadata the light analysis needs from one frame (BRIEF §10.1).</summary>
|
||||
public sealed record LightFrame
|
||||
{
|
||||
public int Index { get; init; }
|
||||
|
||||
/// <summary>Camera wall-clock capture time (unspecified kind).</summary>
|
||||
public DateTime? CapturedAt { get; init; }
|
||||
|
||||
/// <summary>UTC offset of <see cref="CapturedAt"/> in minutes, when recorded.</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>GPS (satellite) UTC time stamp, used to infer the camera clock's UTC offset.</summary>
|
||||
public DateTime? GpsUtc { get; init; }
|
||||
|
||||
/// <summary>Exposure value at ISO 100: log2(N²/t) − log2(ISO/100).</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Width and height after Exif orientations 5–8 (90° rotations).</summary>
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using Titano.Core.Imaging;
|
||||
|
||||
namespace Titano.Core.Analysis;
|
||||
|
||||
/// <summary>Independent deflicker curves for the sky and land regions.</summary>
|
||||
public sealed record RegionDeflickerResult(DeflickerResult Sky, DeflickerResult Land);
|
||||
|
||||
/// <summary>
|
||||
/// Region deflicker (BRIEF §11.2): sky and land are measured through the soft <see cref="RegionMask"/>, each gets its
|
||||
/// own <see cref="DeflickerEngine"/> 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.
|
||||
/// </summary>
|
||||
public static class RegionDeflicker
|
||||
{
|
||||
/// <summary>Trimmed-mean log2 luminance of the sky and land regions of one analysis image.</summary>
|
||||
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<double> skyLogLuminance, ReadOnlySpan<double> landLogLuminance, DeflickerOptions? options = null, ReadOnlySpan<double> 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));
|
||||
}
|
||||
|
||||
/// <summary>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).</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
namespace Titano.Core.Analysis;
|
||||
|
||||
public enum RegionMethod
|
||||
{
|
||||
/// <summary>Sky above a per-column horizon line.</summary>
|
||||
Horizon,
|
||||
|
||||
/// <summary>Sky = the brighter class of a luminance threshold.</summary>
|
||||
Luminance,
|
||||
}
|
||||
|
||||
/// <summary>Soft sky/land segmentation: per-pixel sky weight in [0, 1] with a feathered transition.</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>Sky weight per pixel, row-major (1 = sky, 0 = land).</summary>
|
||||
public float[] Sky { get; }
|
||||
|
||||
/// <summary>Land weight per pixel (1 − sky).</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Horizon position per column in rows from the top edge (horizon method only).</summary>
|
||||
public double[]? Horizon { get; }
|
||||
|
||||
public RegionMethod Method { get; }
|
||||
|
||||
/// <summary>0 … 1; region deflicker is advisable only when this is high.</summary>
|
||||
public double Confidence { get; }
|
||||
|
||||
/// <summary>Bilinear resampling to another resolution (e.g. analysis size → render size), pixel-centre aligned.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Mathematics;
|
||||
|
||||
namespace Titano.Core.Analysis;
|
||||
|
||||
/// <summary>Parameters of <see cref="RegionSegmenter"/>.</summary>
|
||||
public sealed record RegionSegmenterOptions
|
||||
{
|
||||
public static RegionSegmenterOptions Default { get; } = new();
|
||||
|
||||
/// <summary>Frames sampled evenly from the sequence.</summary>
|
||||
public int MaxFrames { get; init; } = 15;
|
||||
|
||||
/// <summary>Below this the luminance fallback is tried and the more confident mask wins.</summary>
|
||||
public double MinimumHorizonConfidence { get; init; } = 0.4;
|
||||
|
||||
/// <summary>Row-step amplitude in EV that counts as a fully convincing horizon.</summary>
|
||||
public double StrongStepEv { get; init; } = 0.5;
|
||||
|
||||
/// <summary>Width of the feathered transition as a fraction of the image height.</summary>
|
||||
public double FeatherFraction { get; init; } = 0.03;
|
||||
|
||||
/// <summary>Path penalty per row of vertical movement between adjacent columns, relative to the horizon step.</summary>
|
||||
public double SmoothnessPenalty { get; init; } = 0.05;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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].
|
||||
/// </summary>
|
||||
public static class RegionSegmenter
|
||||
{
|
||||
private const float LogFloor = -14;
|
||||
|
||||
public static RegionMask Segment(IReadOnlyList<ImageBuffer> 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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Dynamic programming over columns: each step may move at most <paramref name="slope"/> rows at a
|
||||
/// cost of <paramref name="penalty"/> per row. Returns the row index (within the band) per column.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Otsu (1979) threshold over a 256-bin histogram and its separability η = σ²between / σ²total.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Binary erosion (min) or dilation (max) with a (2r+1)² square, as two separable passes.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Separable box blur with edge-shrunk windows, in place.</summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Mathematics;
|
||||
|
||||
namespace Titano.Core.Analysis;
|
||||
|
||||
/// <summary>Per-frame white-balance smoothing result; ratios are log2(R/G) and log2(B/G).</summary>
|
||||
public sealed record WhiteBalanceResult(
|
||||
ChannelGains[] Gains,
|
||||
double[] RedRatio,
|
||||
double[] BlueRatio,
|
||||
double[] SmoothedRedRatio,
|
||||
double[] SmoothedBlueRatio);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class WhiteBalanceSmoother
|
||||
{
|
||||
public static WhiteBalanceResult Smooth(ReadOnlySpan<double> meanRed, ReadOnlySpan<double> meanGreen, ReadOnlySpan<double> 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;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>A deliberate exposure change written to the metadata from frame <paramref name="Index"/> on; when
|
||||
/// <paramref name="Received"/> is false the pixels ignore it (e.g. a setting the camera did not apply).</summary>
|
||||
/// <param name="DeltaEv">Camera EV change (positive = less light; the pixels darken by this many stops).</param>
|
||||
public sealed record SyntheticExposureStep(int Index, double DeltaEv, ExposureChange Change = ExposureChange.Shutter, bool Received = true);
|
||||
|
||||
/// <summary>Seconds added to the capture clock from frame <paramref name="Index"/> on (pauses, clock jumps).</summary>
|
||||
public sealed record SyntheticTimeShift(int Index, double Seconds);
|
||||
|
||||
/// <summary>Recipe of a synthetic sequence; every field has a neutral default.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Camera wall-clock time of the first frame.</summary>
|
||||
public DateTime Start { get; init; } = new(2024, 6, 21, 19, 0, 0);
|
||||
|
||||
public int? UtcOffsetMinutes { get; init; } = 120;
|
||||
public double IntervalSeconds { get; init; } = 10;
|
||||
|
||||
/// <summary>Uniform ± jitter of each capture time, in seconds.</summary>
|
||||
public double IntervalJitterSeconds { get; init; }
|
||||
|
||||
public IReadOnlyList<SyntheticTimeShift> TimeShifts { get; init; } = [];
|
||||
|
||||
/// <summary>Scene brightness (EV) at the first and last frame; linear ramp in between.</summary>
|
||||
public double StartEv { get; init; }
|
||||
|
||||
public double EndEv { get; init; }
|
||||
|
||||
/// <summary>Global flicker amplitude in EV: uniform in ±amplitude, or a sinusoid when a period is set.</summary>
|
||||
public double FlickerEv { get; init; }
|
||||
|
||||
/// <summary>Period of sinusoidal flicker in frames; 0 = random flicker.</summary>
|
||||
public double FlickerPeriodFrames { get; init; }
|
||||
|
||||
/// <summary>Extra independent uniform flicker of the sky region, in ±EV.</summary>
|
||||
public double SkyFlickerEv { get; init; }
|
||||
|
||||
/// <summary>Extra independent uniform flicker of the land region, in ±EV.</summary>
|
||||
public double LandFlickerEv { get; init; }
|
||||
|
||||
public IReadOnlyList<SyntheticExposureStep> ExposureSteps { get; init; } = [];
|
||||
|
||||
/// <summary>Horizon row at the centre column as a fraction of the height (sky above).</summary>
|
||||
public double HorizonFraction { get; init; } = 0.45;
|
||||
|
||||
/// <summary>Horizon slope in rows per column.</summary>
|
||||
public double HorizonTilt { get; init; }
|
||||
|
||||
/// <summary>Amplitude in rows of one sine period of horizon undulation across the width.</summary>
|
||||
public double HorizonWave { get; init; }
|
||||
|
||||
/// <summary>Linear luminance of the sky (at the horizon) and of the average land pixel at 0 EV.</summary>
|
||||
public double SkyLevel { get; init; } = 0.25;
|
||||
|
||||
public double LandLevel { get; init; } = 0.05;
|
||||
|
||||
/// <summary>Night sky: dark background with point stars instead of a bright gradient.</summary>
|
||||
public bool StarField { get; init; }
|
||||
|
||||
public int StarCount { get; init; } = 40;
|
||||
|
||||
/// <summary>Correlated colour temperature of the light at the first and last frame (linear in mireds).</summary>
|
||||
public double StartKelvin { get; init; } = 5500;
|
||||
|
||||
public double EndKelvin { get; init; } = 5500;
|
||||
|
||||
/// <summary>Uniform ± per-frame jitter of log2(R/G) and log2(B/G).</summary>
|
||||
public double WhiteBalanceJitter { get; init; }
|
||||
|
||||
/// <summary>Additive Gaussian sensor noise (linear units) on every channel.</summary>
|
||||
public double NoiseSigma { get; init; }
|
||||
|
||||
public IReadOnlyList<int> BlackFrames { get; init; } = [];
|
||||
public IReadOnlyList<int> WhiteFrames { get; init; } = [];
|
||||
|
||||
/// <summary>Frames that repeat the previous frame exactly (pixels, capture time and settings).</summary>
|
||||
public IReadOnlyList<int> 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; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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: <c>base(x, y) · 2^(scene + exposure + flicker + regionFlicker) · rgb(kelvin)</c> with rgb at luminance 1,
|
||||
/// so log-luminance shifts equal the truth series exactly.
|
||||
/// </summary>
|
||||
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<int>(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<Frame> Frames { get; }
|
||||
public IReadOnlyList<FrameMetadata> Metadata { get; }
|
||||
|
||||
/// <summary>True scene brightness per frame (EV): the ramp.</summary>
|
||||
public double[] SceneEv { get; }
|
||||
|
||||
/// <summary>Global flicker per frame (EV).</summary>
|
||||
public double[] FlickerEv { get; }
|
||||
|
||||
public double[] SkyFlickerEv { get; }
|
||||
public double[] LandFlickerEv { get; }
|
||||
|
||||
/// <summary>Luminance offset of the received exposure steps (EV).</summary>
|
||||
public double[] ExposureOffsetEv { get; }
|
||||
|
||||
public double[] Kelvin { get; }
|
||||
|
||||
/// <summary>Per-frame white-balance jitter of log2(R/G) and log2(B/G).</summary>
|
||||
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]);
|
||||
|
||||
/// <summary>Light-analysis input of every frame (with camera, lens and GPS).</summary>
|
||||
public IReadOnlyList<LightFrame> LightFrames() => Metadata.Select((m, i) => LightFrame.From(m, i)).ToList();
|
||||
|
||||
/// <summary>Horizon position (rows from the top edge) at column centre <paramref name="x"/>.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Renders frame <paramref name="index"/> (linear RGB); identical calls give identical pixels.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Linear Rec.709 colour of the frame's light at luminance 1, with the white-balance jitter applied.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Uniform [0, 1) from a SplitMix64 hash of the inputs (stable across processes, unlike HashCode).</summary>
|
||||
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<byte> 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
namespace Titano.Core.Mathematics;
|
||||
|
||||
/// <summary>Knot spacing of a Catmull–Rom spline: |Pᵢ₊₁ − Pᵢ|^α with α = 0, ½ or 1.</summary>
|
||||
public enum CatmullRomParameterization
|
||||
{
|
||||
/// <summary>α = 0: the classic spline; can cusp or self-intersect on uneven spacing.</summary>
|
||||
Uniform,
|
||||
|
||||
/// <summary>α = ½: no cusps or self-intersections within a segment (Yuksel, Schaefer & Keyser 2011).</summary>
|
||||
Centripetal,
|
||||
|
||||
/// <summary>α = 1: follows the chord lengths; smoothest on evenly sampled paths.</summary>
|
||||
Chordal,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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₁).
|
||||
/// </summary>
|
||||
public static class CatmullRom
|
||||
{
|
||||
/// <summary>Scalar spline through <paramref name="values"/> (values treated as 1-D points for the knot spacing).</summary>
|
||||
public static double Evaluate(ReadOnlySpan<double> 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;
|
||||
}
|
||||
|
||||
/// <summary>Planar spline through <paramref name="points"/>.</summary>
|
||||
public static Point2 Evaluate(ReadOnlySpan<Point2> 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);
|
||||
}
|
||||
|
||||
/// <summary>Barry–Goldman recursive evaluation of the segment P1→P2 at local parameter u ∈ [0, 1].</summary>
|
||||
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));
|
||||
|
||||
/// <summary>Knot interval; coincident points fall back to a unit interval so the pyramid stays finite.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
namespace Titano.Core.Mathematics;
|
||||
|
||||
/// <summary>CIE 1931 chromaticity coordinates (lower-case x, y in the literature).</summary>
|
||||
public readonly record struct Chromaticity(double X, double Y)
|
||||
{
|
||||
/// <summary>CIE standard illuminant D65 (2° observer).</summary>
|
||||
public static Chromaticity D65 { get; } = new(0.3127, 0.3290);
|
||||
|
||||
/// <summary>CIE standard illuminant D50 (2° observer), the ICC/DNG profile connection white.</summary>
|
||||
public static Chromaticity D50 { get; } = new(0.3457, 0.3585);
|
||||
|
||||
/// <summary>Tristimulus values with luminance <paramref name="luminance"/>: X = x·Y/y, Z = (1 − x − y)·Y/y.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Chromaticity of tristimulus values; NaN coordinates when X + Y + Z is not positive.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>CIE 1960 UCS coordinates u = 4x/(−2x + 12y + 3), v = 6y/(−2x + 12y + 3).</summary>
|
||||
public (double U, double V) ToUv1960()
|
||||
{
|
||||
var d = -2 * X + 12 * Y + 3;
|
||||
return (4 * X / d, 6 * Y / d);
|
||||
}
|
||||
|
||||
/// <summary>Chromaticity from CIE 1960 UCS coordinates.</summary>
|
||||
public static Chromaticity FromUv1960(double u, double v)
|
||||
{
|
||||
var d = 2 * u - 8 * v + 4;
|
||||
return new Chromaticity(3 * u / d, 2 * v / d);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
namespace Titano.Core.Mathematics;
|
||||
|
||||
/// <summary>Planar cubic Bézier curve in Bernstein form; t ∈ [0, 1].</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// CSS-style timing function <c>cubic-bezier(x1, y1, x2, y2)</c> 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.
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
/// <summary>Eased progress for input progress <paramref name="x"/> (clamped to [0, 1]).</summary>
|
||||
public double Evaluate(double x) => Component(Y1, Y2, SolveT(x));
|
||||
|
||||
/// <summary>Curve parameter t with x(t) = <paramref name="x"/>.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>One coordinate of the curve with P0 = 0 and P3 = 1: ((a·t + b)·t + c)·t.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
namespace Titano.Core.Mathematics;
|
||||
|
||||
/// <summary>Output of <see cref="LocalRegression.Smooth"/>; every array has one entry per input sample.</summary>
|
||||
public sealed class LocalRegressionResult
|
||||
{
|
||||
internal LocalRegressionResult(double[] fitted, double[] robustWeights, double[] survivingFraction, int validCount)
|
||||
{
|
||||
Fitted = fitted;
|
||||
RobustWeights = robustWeights;
|
||||
SurvivingFraction = survivingFraction;
|
||||
ValidCount = validCount;
|
||||
}
|
||||
|
||||
/// <summary>Smoothed value at every position, including missing samples (interpolated from their neighbours).
|
||||
/// NaN only when there is no valid sample at all.</summary>
|
||||
public double[] Fitted { get; }
|
||||
|
||||
/// <summary>Tukey biweight each sample carried in the final fit (1 = full inlier, 0 = rejected or missing).</summary>
|
||||
public double[] RobustWeights { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Σ 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.
|
||||
/// </summary>
|
||||
public double[] SurvivingFraction { get; }
|
||||
|
||||
public int ValidCount { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Robust locally weighted regression, LOWESS (Cleveland 1979). Each position is fitted by weighted least squares
|
||||
/// of degree 1 or 2 over its <c>window</c> 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.
|
||||
/// </summary>
|
||||
public static class LocalRegression
|
||||
{
|
||||
/// <param name="y">Samples; NaN/±∞ mark missing values.</param>
|
||||
/// <param name="window">Number of nearest valid samples in each local fit (clamped to the valid count).</param>
|
||||
/// <param name="degree">Local polynomial degree, 1 (linear) or 2 (quadratic).</param>
|
||||
/// <param name="robustIterations">Tukey reweighting passes after the initial fit (Cleveland uses 2–3).</param>
|
||||
/// <param name="x">Non-decreasing positions (e.g. capture seconds); indices when empty.</param>
|
||||
/// <param name="priorWeights">Optional non-negative sample weights; zero marks a sample as missing.</param>
|
||||
public static LocalRegressionResult Smooth(
|
||||
ReadOnlySpan<double> y,
|
||||
int window,
|
||||
int degree = 1,
|
||||
int robustIterations = 2,
|
||||
ReadOnlySpan<double> x = default,
|
||||
ReadOnlySpan<double> 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<int>(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);
|
||||
}
|
||||
|
||||
/// <summary>Start of the contiguous block of <paramref name="q"/> valid samples nearest to each position
|
||||
/// (sliding k-nearest-neighbour window; total O(n + m)).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>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).</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
namespace Titano.Core.Mathematics;
|
||||
|
||||
/// <summary>A 3-vector in double precision (colour triplets, homogeneous 2-D points).</summary>
|
||||
public readonly record struct Vector3D(double X, double Y, double Z);
|
||||
|
||||
/// <summary>Row-major 3×3 matrix in double precision for colour-space and planar projective work.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Bradford cone-response matrix (Lam 1985), XYZ → sharpened LMS.</summary>
|
||||
public static Matrix3 Bradford { get; } = new(
|
||||
0.8951, 0.2664, -0.1614,
|
||||
-0.7502, 1.7135, 0.0367,
|
||||
0.0389, -0.0685, 1.0296);
|
||||
|
||||
/// <summary>Linear Rec.709/sRGB (D65) → CIE XYZ, derived from the primaries.</summary>
|
||||
public static Matrix3 Rec709ToXyz { get; } = RgbToXyz(new(0.64, 0.33), new(0.30, 0.60), new(0.15, 0.06), Chromaticity.D65);
|
||||
|
||||
/// <summary>CIE XYZ → linear Rec.709/sRGB (D65).</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Matrix whose columns are <paramref name="c1"/>, <paramref name="c2"/>, <paramref name="c3"/>.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Inverse by the adjugate; false when the matrix is singular relative to its scale.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <exception cref="InvalidOperationException">The matrix is singular.</exception>
|
||||
public Matrix3 Inverse() => TryInvert(out var inverse) ? inverse : throw new InvalidOperationException("Matrix is singular.");
|
||||
|
||||
/// <summary>
|
||||
/// Bradford chromatic adaptation (von Kries scaling in the Bradford cone space) mapping colours seen under
|
||||
/// <paramref name="sourceWhite"/> to <paramref name="destinationWhite"/>; both whites as XYZ.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>RGB → XYZ matrix of an additive colour space from its primaries and white point (white maps to Y = 1).</summary>
|
||||
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)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
namespace Titano.Core.Mathematics;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class MonotoneSpline
|
||||
{
|
||||
private readonly double[] _x;
|
||||
private readonly double[] _y;
|
||||
private readonly double[] _m;
|
||||
|
||||
/// <param name="x">Strictly increasing, finite knot positions (at least one).</param>
|
||||
/// <param name="y">Finite knot values.</param>
|
||||
public MonotoneSpline(ReadOnlySpan<double> x, ReadOnlySpan<double> 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];
|
||||
|
||||
/// <summary>True when the knot values are entirely non-decreasing or non-increasing (required by <see cref="Inverse"/>).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The x at which the spline reaches <paramref name="y"/> (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.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">The knot values are not monotone.</exception>
|
||||
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<double> x, ReadOnlySpan<double> 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
namespace Titano.Core.Mathematics;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class NaturalCubicSpline
|
||||
{
|
||||
private readonly double[] _x;
|
||||
private readonly double[] _y;
|
||||
private readonly double[] _m;
|
||||
|
||||
/// <param name="x">Strictly increasing, finite knot positions (at least one).</param>
|
||||
/// <param name="y">Finite knot values.</param>
|
||||
public NaturalCubicSpline(ReadOnlySpan<double> x, ReadOnlySpan<double> 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace Titano.Core.Mathematics;
|
||||
|
||||
/// <summary>A point or vector in the plane, double precision.</summary>
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
namespace Titano.Core.Mathematics;
|
||||
|
||||
/// <summary>Light condition by solar elevation (geometric centre of the disc).</summary>
|
||||
public enum DayPhase
|
||||
{
|
||||
/// <summary>Sun below −18°.</summary>
|
||||
Night,
|
||||
|
||||
/// <summary>−18° to −12°.</summary>
|
||||
AstronomicalTwilight,
|
||||
|
||||
/// <summary>−12° to −6°.</summary>
|
||||
NauticalTwilight,
|
||||
|
||||
/// <summary>−6° to sunrise/sunset (−0.833°).</summary>
|
||||
CivilTwilight,
|
||||
|
||||
/// <summary>Sun up but below 6°.</summary>
|
||||
GoldenHour,
|
||||
|
||||
/// <summary>Sun at or above 6°.</summary>
|
||||
Day,
|
||||
}
|
||||
|
||||
/// <summary>Sun position for an instant and place.</summary>
|
||||
/// <param name="Elevation">Apparent elevation in degrees, corrected for standard atmospheric refraction.</param>
|
||||
/// <param name="Azimuth">Degrees clockwise from true north.</param>
|
||||
/// <param name="GeometricElevation">Elevation without refraction, in degrees (used for twilight limits).</param>
|
||||
/// <param name="Declination">Solar declination in degrees.</param>
|
||||
/// <param name="EquationOfTimeMinutes">Apparent minus mean solar time, in minutes.</param>
|
||||
public readonly record struct SolarCoordinates(double Elevation, double Azimuth, double GeometricElevation, double Declination, double EquationOfTimeMinutes)
|
||||
{
|
||||
public DayPhase Phase => SolarPosition.Classify(GeometricElevation);
|
||||
}
|
||||
|
||||
/// <summary>Sun events of one local solar day, all in UTC; null when the event does not occur (polar day/night).</summary>
|
||||
public sealed record SolarDay(
|
||||
DateOnly Date,
|
||||
DateTime SolarNoon,
|
||||
DateTime? Sunrise,
|
||||
DateTime? Sunset,
|
||||
DateTime? CivilDawn,
|
||||
DateTime? CivilDusk,
|
||||
DateTime? NauticalDawn,
|
||||
DateTime? NauticalDusk,
|
||||
DateTime? AstronomicalDawn,
|
||||
DateTime? AstronomicalDusk);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class SolarPosition
|
||||
{
|
||||
/// <summary>Geometric elevation of the disc centre at apparent sunrise/sunset (34′ refraction + 16′ semi-diameter).</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Sun position at <paramref name="utc"/> (a value of unspecified kind is taken as UTC).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Day phase from the geometric elevation in degrees.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>All rise/set and twilight events of the local solar day <paramref name="date"/> (the day whose solar
|
||||
/// noon falls on that calendar date at the given longitude).</summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>UTC solar noon (upper transit) of the local solar day.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UTC time at which the sun's geometric centre crosses <paramref name="elevation"/> degrees on the given
|
||||
/// local solar day, rising (morning) or setting (evening); null when it stays above or below all day.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>NOAA approximation of standard atmospheric refraction, in degrees, for a geometric elevation.</summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,417 @@
|
||||
using System.Buffers;
|
||||
using System.Numerics;
|
||||
|
||||
namespace Titano.Core.Mathematics;
|
||||
|
||||
/// <summary>A robustly fitted straight line <c>y = Intercept + Slope·x</c>.</summary>
|
||||
/// <param name="Scale">Robust residual standard deviation (1.4826 × MAD of the final residuals).</param>
|
||||
public readonly record struct RobustLine(double Slope, double Intercept, double Scale)
|
||||
{
|
||||
public double Evaluate(double x) => Intercept + Slope * x;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public static class Statistics
|
||||
{
|
||||
/// <summary>Scales a median absolute deviation to the standard deviation of a normal distribution (1/Φ⁻¹(3/4)).</summary>
|
||||
public const double MadToSigma = 1.482602218505602;
|
||||
|
||||
/// <summary>
|
||||
/// Rearranges <paramref name="values"/> so that <c>values[k]</c> 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.
|
||||
/// </summary>
|
||||
public static double Select(Span<double> 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<double> 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;
|
||||
}
|
||||
|
||||
/// <summary>Root mean square of the valid values.</summary>
|
||||
public static double Rms(ReadOnlySpan<double> 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);
|
||||
}
|
||||
|
||||
/// <summary>Sample standard deviation (n − 1 denominator) of the valid values.</summary>
|
||||
public static double StandardDeviation(ReadOnlySpan<double> 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<double> values)
|
||||
{
|
||||
var buffer = RentValid(values, out var n);
|
||||
try
|
||||
{
|
||||
return n == 0 ? double.NaN : MedianInPlace(buffer.AsSpan(0, n));
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<double>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Median of NaN-free <paramref name="values"/>, reordering them.</summary>
|
||||
public static double MedianInPlace(Span<double> 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);
|
||||
}
|
||||
|
||||
/// <summary>Raw median absolute deviation about <paramref name="center"/> (the median when omitted).
|
||||
/// Multiply by <see cref="MadToSigma"/> for a normal-consistent scale.</summary>
|
||||
public static double MedianAbsoluteDeviation(ReadOnlySpan<double> 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<double>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Mean after discarding the lowest <paramref name="lowFraction"/> and highest
|
||||
/// <paramref name="highFraction"/> of the valid values (counts rounded down), in linear time.</summary>
|
||||
public static double TrimmedMean(ReadOnlySpan<double> 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<double>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Percentile <paramref name="p"/> ∈ [0, 1] with linear interpolation between order statistics
|
||||
/// (Hyndman–Fan type 7, the spreadsheet/NumPy default).</summary>
|
||||
public static double Percentile(ReadOnlySpan<double> 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<double>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static double WeightedPercentile(ReadOnlySpan<double> values, ReadOnlySpan<double> 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<double>(values.Length);
|
||||
var w = new List<double>(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];
|
||||
}
|
||||
|
||||
/// <summary>Accumulates <paramref name="values"/> (optionally weighted) into equal-width bins over
|
||||
/// [<paramref name="min"/>, <paramref name="max"/>); values outside are clamped into the end bins.</summary>
|
||||
public static void AccumulateHistogram(ReadOnlySpan<double> values, double min, double max, Span<double> bins, ReadOnlySpan<double> 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];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Percentile of a histogram over [<paramref name="min"/>, <paramref name="max"/>), interpolating
|
||||
/// linearly inside the bin that contains the target mass.</summary>
|
||||
public static double HistogramPercentile(ReadOnlySpan<double> 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;
|
||||
}
|
||||
|
||||
/// <summary>Symmetric chi-square distance ½·Σ (aᵢ − bᵢ)² / (aᵢ + bᵢ) between two histograms normalised to unit mass
|
||||
/// (0 = identical, 1 = disjoint).</summary>
|
||||
public static double ChiSquareDistance(ReadOnlySpan<double> a, ReadOnlySpan<double> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static RobustLine RobustLinearFit(ReadOnlySpan<double> x, ReadOnlySpan<double> y, int iterations = 10)
|
||||
{
|
||||
if (x.Length != y.Length) throw new ArgumentException("Lengths differ.", nameof(y));
|
||||
var px = new List<double>(x.Length);
|
||||
var py = new List<double>(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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sample autocorrelation r(k) for k = 0 … <c>result.Length − 1</c> (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.
|
||||
/// </summary>
|
||||
public static void Autocorrelation(ReadOnlySpan<double> values, Span<double> 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<double> values, out int count)
|
||||
{
|
||||
var buffer = ArrayPool<double>.Shared.Rent(Math.Max(1, values.Length));
|
||||
count = 0;
|
||||
foreach (var v in values)
|
||||
{
|
||||
if (!double.IsNaN(v)) buffer[count++] = v;
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user