feat(diagnostics): add deterministic synthetic sequence generator

Known-answer fixtures: brightness ramp, seeded global/sky/land flicker,
metadata and pixel exposure steps, horizon split, colour temperature
drift and white-balance jitter, star field, black/white/duplicate
frames, gaps and clock shifts. Covers frame statistics (CCT against
exact blackbody chromaticities) and the light analyzer with it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 09:51:43 +00:00
1 parent 3b3d7b7f6b
commit 353143b953
5 files changed
+906

No files matched your search

@@ -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);
}
}