refactor!: rename Titano to Chronos and move CI and releases to Gitea
CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout. The release cross-compiles the Windows programs, checks their
  icon, version and DPI manifest, packs installers and zips, publishes the
  Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only
  tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow) and
  pe-check.

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-23 11:34:48 +02:00
1 parent c99842cc86
commit 5f27a86406
1799 files changed
+11728 -10668

No files matched your search

@@ -0,0 +1,59 @@
using Chronos.Core.Analysis;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Imaging;
namespace Chronos.Core.Tests.Analysis;
/// <summary>Shared measurement helpers for the analysis tests.</summary>
internal static class AnalysisFixtures
{
/// <summary>Trimmed-mean log2 luminance of every frame, optionally after applying a per-frame correction.</summary>
public static double[] MeasureSeries(SyntheticSequence sequence, Func<int, ImageBuffer, ImageBuffer>? transform = null, float[]? mask = null)
{
var result = new double[sequence.Count];
Parallel.For(0, sequence.Count, new ParallelOptions { MaxDegreeOfParallelism = 2 }, i =>
{
using var image = sequence.Render(i);
var measured = transform is null ? image : transform(i, image);
result[i] = FrameStatistics.MeasureLogLuminance(measured, mask);
});
return result;
}
/// <summary>RMS of the frame-to-frame change of (series − truth): flicker relative to the true curve, free of
/// any constant offset.</summary>
public static double FrameToFrameResidualRms(IReadOnlyList<double> series, IReadOnlyList<double> truth)
{
double sum = 0;
for (var i = 1; i < series.Count; i++)
{
var d = series[i] - series[i - 1] - (truth[i] - truth[i - 1]);
sum += d * d;
}
return Math.Sqrt(sum / (series.Count - 1));
}
/// <summary>Largest |series − truth − c| where c is the mean offset (the measurement constant).</summary>
public static double MaxDeviation(IReadOnlyList<double> series, IReadOnlyList<double> truth)
{
var offset = 0.0;
for (var i = 0; i < series.Count; i++) offset += series[i] - truth[i];
offset /= series.Count;
var max = 0.0;
for (var i = 0; i < series.Count; i++) max = Math.Max(max, Math.Abs(series[i] - truth[i] - offset));
return max;
}
/// <summary>Land pixels at least <paramref name="margin"/> rows below the true horizon (weight 1), else 0.</summary>
public static float[] TrueLandMask(SyntheticSequence sequence, double margin = 2)
{
var o = sequence.Options;
var mask = new float[o.Width * o.Height];
for (var y = 0; y < o.Height; y++)
{
for (var x = 0; x < o.Width; x++)
mask[y * o.Width + x] = y + 0.5 > sequence.HorizonRow(x + 0.5) + margin ? 1 : 0;
}
return mask;
}
}
@@ -0,0 +1,93 @@
using Chronos.Core.Analysis;
using Chronos.Testing;
namespace Chronos.Core.Tests.Analysis;
/// <summary>Seeded random inputs: outputs stay finite where defined and repeat exactly.</summary>
public sealed class AnalysisPropertyTests
{
private static double[] RandomSeries(Random random, int n, double missing)
{
var level = 0.0;
var series = new double[n];
for (var i = 0; i < n; i++)
{
level += 0.05 * (random.NextDouble() - 0.5);
series[i] = random.NextDouble() < missing ? double.NaN : level + 0.3 * (random.NextDouble() - 0.5) + (random.NextDouble() < 0.03 ? 4 : 0);
}
return series;
}
[Test]
public void DeflickerHolyGrailAndSpectrumAreFiniteAndDeterministic()
{
var random = new Random(1234);
for (var trial = 0; trial < 25; trial++)
{
var n = 2 + random.Next(300);
var series = RandomSeries(random, n, missing: 0.1);
if (series.All(double.IsNaN)) series[0] = 0;
var ev = new double?[n];
double camera = 12;
for (var i = 0; i < n; i++)
{
if (random.NextDouble() < 0.05) camera -= Math.Round(random.NextDouble() * 6 - 3) / 3;
ev[i] = random.NextDouble() < 0.05 ? null : camera;
}
var options = new DeflickerOptions { Window = 3 + random.Next(40), Degree = 1 + random.Next(2), Strength = random.NextDouble() };
var a = DeflickerEngine.Compute(series, options);
var b = DeflickerEngine.Compute(series, options);
Assert.True(a.Target.All(double.IsFinite) && a.CorrectionEv.All(double.IsFinite), $"deflicker trial {trial}");
Assert.SequenceEqual(a.Target, b.Target);
var grail = HolyGrailEngine.Compute(series, ev, new HolyGrailOptions { Deflicker = options });
Assert.True(grail.Target.All(double.IsFinite) && grail.CorrectionEv.All(double.IsFinite), $"holy grail trial {trial}");
Assert.SequenceEqual(grail.Target, HolyGrailEngine.Compute(series, ev, new HolyGrailOptions { Deflicker = options }).Target);
var spectrum = FlickerSpectrum.Analyze(series);
Assert.True(spectrum.Autocorrelation.All(double.IsFinite));
Assert.Equal(1, spectrum.RecommendedWindow % 2);
var region = RegionDeflicker.Compute(series, RandomSeries(random, n, 0.2), options);
Assert.True(region.Land.CorrectionEv.All(double.IsFinite));
}
}
[Test]
public void WhiteBalanceAndLightAnalysisSurviveRandomMetadata()
{
var random = new Random(77);
for (var trial = 0; trial < 20; trial++)
{
var n = 1 + random.Next(200);
double Channel() => random.NextDouble() < 0.05 ? 0 : 0.01 + random.NextDouble();
var red = Enumerable.Range(0, n).Select(_ => Channel()).ToArray();
var green = Enumerable.Range(0, n).Select(_ => Channel()).ToArray();
var blue = Enumerable.Range(0, n).Select(_ => Channel()).ToArray();
var wb = WhiteBalanceSmoother.Smooth(red, green, blue, window: 1 + random.Next(40));
Assert.True(wb.Gains.All(g => double.IsFinite(g.Red) && g.Red > 0 && double.IsFinite(g.Blue) && g.Blue > 0), $"wb trial {trial}");
var start = new DateTime(2024, 1, 1);
var frames = Enumerable.Range(0, n).Select(i => new LightFrame
{
Index = i,
CapturedAt = random.NextDouble() < 0.05 ? null : start.AddSeconds(i * 7 + random.Next(-20, 20) + (random.NextDouble() < 0.02 ? 9000 : 0)),
ExposureTime = random.NextDouble() < 0.05 ? null : 1.0 / (1 + random.Next(3)),
FNumber = 2.8,
Iso = random.NextDouble() < 0.5 ? 100 : null,
Width = 100 + random.Next(2),
Height = 80,
Orientation = random.NextDouble() < 0.05 ? 6 : 1,
Latitude = random.NextDouble() < 0.5 ? -60 + 120 * random.NextDouble() : null,
Longitude = 170 * (random.NextDouble() - 0.5),
}).ToList();
var first = LightAnalyzer.Analyze(frames);
var second = LightAnalyzer.Analyze(frames);
Assert.SequenceEqual(first.Intervals, second.Intervals);
Assert.SequenceEqual(first.Findings.Select(f => f.Key), second.Findings.Select(f => f.Key));
Assert.Equal(n, first.Sessions.Sum(s => s.FrameCount));
Assert.True(first.CaptureSpan >= TimeSpan.Zero);
}
}
}
@@ -0,0 +1,344 @@
using Chronos.Core.Analysis;
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Imaging;
using Chronos.Testing;
namespace Chronos.Core.Tests.Analysis.Deep;
public sealed class DeepAnalyzerTests(TestContext context)
{
[Test]
public async Task NightSkyShowsStarsDarknessFlickerAndNoShake()
{
var report = await DeepReports.Night;
context.Log($"{report.Sky} {report.Flicker} {report.Shake}");
Assert.True(report.Sky.StarField);
Assert.Equal(DayNight.Night, report.Sky.Light);
Assert.Equal(report.FrameCount, report.Sky.StarFrames);
// Uniform ±0.12 EV flicker has an RMS of 0.069 EV.
Assert.Approximately(0.069, report.Flicker.AmplitudeEv, 0.01);
Assert.Equal(15, report.Flicker.RecommendedWindow);
Assert.Less(report.Shake.RmsPx, 0.05);
Assert.Equal(1.0, report.Shake.MeasuredFraction);
Assert.Empty(report.Issues.SceneChanges);
Assert.Equal(0.0, report.Motion.P95Px!.Value);
Assert.Equal(RegionMethod.Horizon, report.Regions!.Method);
Assert.Contains(report.Findings, f => f.Key == DeepFindingKeys.StarField);
Assert.Contains(report.Findings, f => f.Key == DeepFindingKeys.Flicker);
Assert.True(report.Frames.FlagsOf(0).HasFlag(DeepFrameFlags.StarField | DeepFrameFlags.Dark));
}
[Test]
public async Task InjectedCameraJitterIsMeasuredAsShake()
{
var report = await DeepReports.NightJitter;
context.Log($"{report.Shake} {report.Motion}");
// Integer offsets uniform in −2..2 per axis: 2 px RMS in 2D.
Assert.InRange(report.Shake.RmsPx, 1.6, 2.4);
Assert.InRange(report.Shake.CropCost, 0.02, 0.2);
Assert.False(report.Shake.PanDetected);
Assert.Greater(report.Motion.P95Px!.Value, 1);
Assert.Contains(report.Findings, f => f.Key == DeepFindingKeys.Shake);
}
[Test]
public async Task HolyGrailStepsAreReceivedAndSpacedByHalfTheirDistance()
{
var report = await DeepReports.HolyGrail;
Assert.Equal(5, report.Exposure.MetadataSteps);
Assert.Equal(5, report.Exposure.ReceivedSteps);
Assert.Equal(40.0, report.Exposure.TypicalSpacing);
Assert.Equal(20, report.Exposure.TransitionLength);
Assert.True(report.Exposure.Steps.All(s => s.MeasuredEv is > 0.9 and < 1.1));
Assert.InRange(report.Exposure.SceneRangeEv, 5, 6);
Assert.Equal(DayNight.DayToNight, report.Sky.Light);
// Brightness ramps and steps are levelled before the flow, so the static scene shows no motion.
Assert.Equal(0.0, report.Motion.P95Px!.Value);
Assert.Empty(report.Issues.SceneChanges);
}
[Theory]
[Case(8.0, 33)]
[Case(12.5, 51)]
[Case(40.0, 151)]
public async Task PeriodicFlickerGivesAWindowOfFourPeriods(double period, int window)
{
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
{
Width = 96,
Height = 64,
FrameCount = 240,
FlickerEv = 0.15,
FlickerPeriodFrames = period,
});
var report = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence), DeepScenes.Options);
Assert.Approximately(period, report.Flicker.PeriodFrames!.Value, 0.05 * period);
Assert.Equal(window, report.Flicker.RecommendedWindow);
Assert.Equal(1, window % 2);
}
[Test]
public async Task BlackWhiteDuplicateAndUnreadableFramesAreFlagged()
{
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
{
Width = 96,
Height = 64,
FrameCount = 60,
FlickerEv = 0.02,
BlackFrames = [10],
WhiteFrames = [20],
DuplicateFrames = [30],
});
var report = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence) { Undecodable = [40] }, DeepScenes.Options);
Assert.SequenceEqual([10], report.Issues.Black);
Assert.SequenceEqual([20], report.Issues.White);
Assert.SequenceEqual([30], report.Issues.Duplicate);
Assert.SequenceEqual([40], report.Issues.Undecodable);
Assert.SequenceEqual([10, 20, 30, 40], report.Issues.Excludable());
Assert.Empty(report.Issues.SceneChanges);
Assert.Null(report.Frames.LogLuminance[40]);
Assert.True(report.Frames.FlagsOf(40).HasFlag(DeepFrameFlags.Undecodable));
Assert.False(report.Issues.Excludable().Contains(report.HeroIndex!.Value));
foreach (var key in new[] { DeepFindingKeys.BlackFrames, DeepFindingKeys.WhiteFrames, DeepFindingKeys.DuplicateFrames, DeepFindingKeys.UnreadableFrames })
Assert.Equal(FindingSeverity.Warning, report.Findings.Single(f => f.Key == key).Severity);
Assert.Equal(4, AnalysisSummary.From(report).WarningCount);
}
[Test]
public async Task ACutToAnotherViewIsASceneChange()
{
var first = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64, FrameCount = 50, FlickerEv = 0.05 }));
var second = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions
{
Width = 96,
Height = 64,
FrameCount = 50,
FlickerEv = 0.05,
Seed = 5,
HorizonFraction = 0.75,
SkyLevel = 0.6,
LandLevel = 0.01,
}));
var report = await DeepAnalyzer.AnalyzeAsync(new SplicedSource(first, second, 30), DeepScenes.Options);
Assert.SequenceEqual([30], report.Issues.SceneChanges);
Assert.True(report.Frames.FlagsOf(30).HasFlag(DeepFrameFlags.SceneChange));
}
[Test]
public async Task ResumingFromACheckpointGivesTheSameReport()
{
var expected = (await DeepReports.HolyGrail).ToJson();
var checkpoint = new MemoryCheckpoint();
var crashing = new SyntheticFrameSource(DeepScenes.HolyGrail())
{
OnLoad = i =>
{
if (i == 101) throw new IOException("simulated crash");
},
};
await Assert.ThrowsAsync<IOException>(() => DeepAnalyzer.AnalyzeAsync(crashing, DeepScenes.Options, checkpoint));
var persisted = checkpoint.Frames.Count;
Assert.InRange(persisted, 90, 101);
var resumed = new SyntheticFrameSource(DeepScenes.HolyGrail());
var report = await DeepAnalyzer.AnalyzeAsync(resumed, DeepScenes.Options, checkpoint);
Assert.Equal(expected, report.ToJson());
// Region sample + one priming frame + the frames not yet persisted.
Assert.Equal(DeepScenes.Options.RegionSampleFrames + 1 + (240 - persisted), resumed.Loads);
Assert.Equal(240, checkpoint.Frames.Count);
}
[Test]
public async Task FileCheckpointDropsATornLineAndResumes()
{
var path = Path.Combine(context.CreateTempDirectory(), ".chronos", DeepAnalysisCheckpointFile.FileName);
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64, FrameCount = 40, FlickerEv = 0.05, DuplicateFrames = [7] });
var expected = (await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence), DeepScenes.Options)).ToJson();
var file = new DeepAnalysisCheckpointFile(path);
var crashing = new SyntheticFrameSource(sequence) { OnLoad = i => { if (i == 21) throw new IOException("crash"); } };
await Assert.ThrowsAsync<IOException>(() => DeepAnalyzer.AnalyzeAsync(crashing, DeepScenes.Options, file));
await File.AppendAllTextAsync(path, "{\"index\":20,\"flags\":\"No", context.Cancellation);
var report = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence), DeepScenes.Options, file);
Assert.Equal(expected, report.ToJson());
Assert.Equal(41, File.ReadAllLines(path).Length);
// Other options: the stale checkpoint is discarded instead of mixed in.
var other = DeepScenes.Options with { FlowEvery = 3 };
var fresh = await new DeepAnalysisCheckpointFile(path).LoadAsync(DeepAnalyzer.Fingerprint(40, other), context.Cancellation);
Assert.Empty(fresh);
file.Delete();
Assert.FileMissing(path);
}
[Test]
public async Task ReportRoundTripsThroughJsonWithinTheSizeBudget()
{
var report = await DeepReports.NightJitter;
var json = report.ToJson();
var copy = DeepAnalysisReport.FromJson(json);
Assert.Equal(json, copy.ToJson());
var perFrame = (double)System.Text.Encoding.UTF8.GetByteCount(json) / report.FrameCount;
context.Log($"{perFrame:0.0} bytes per frame");
Assert.LessOrEqual(perFrame, 120);
var path = Path.Combine(context.CreateTempDirectory(), DeepAnalysisReport.FileName);
report.Save(path);
Assert.Equal(json, DeepAnalysisReport.Load(path).ToJson());
var summary = AnalysisSummary.From(report);
Assert.Equal(summary, AnalysisSummary.FromJson(summary.ToJson()));
Assert.True(summary.StarField);
Assert.Equal(DayNight.Night, summary.Light);
Assert.Equal(report.HeroIndex, summary.HeroIndex);
Assert.Less(summary.ToJson().Length, 400);
Assert.Throws<InvalidDataException>(() => DeepAnalysisReport.FromJson(json.Replace("\"version\":1", "\"version\":99", StringComparison.Ordinal)));
}
[Test]
public async Task ResultsDoNotDependOnParallelism()
{
var sequence = DeepScenes.NightSky(frames: 40, jitter: 2);
var serial = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence, 2), DeepScenes.Options with { MaxDegreeOfParallelism = 1 });
var parallel = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence, 2), DeepScenes.Options with { MaxDegreeOfParallelism = 3 });
Assert.Equal(serial.ToJson(), parallel.ToJson());
}
[Test]
public async Task CancellationStopsWithinOneBatch()
{
using var cancellation = new CancellationTokenSource();
var checkpoint = new MemoryCheckpoint();
var source = new SyntheticFrameSource(DeepScenes.HolyGrail())
{
OnLoad = i =>
{
if (i == 50) cancellation.Cancel();
},
};
await Assert.ThrowsAsync<OperationCanceledException>(() => DeepAnalyzer.AnalyzeAsync(source, DeepScenes.Options, checkpoint, null, cancellation.Token));
Assert.LessOrEqual(source.Loads, DeepScenes.Options.RegionSampleFrames + 52);
Assert.Equal(50, checkpoint.Frames.Count);
}
[Test]
public async Task ProgressCountsEveryFrameUpToTheTotal()
{
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 64, Height = 48, FrameCount = 21 });
var reports = new List<AnalysisProgress>();
await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence), DeepScenes.Options, progress: new SyncProgress(reports.Add));
Assert.Equal(11, reports.Count);
Assert.Monotonic(reports.Select(r => (double)r.Done), strict: true);
Assert.Equal(21, reports[^1].Done);
Assert.True(reports.All(r => r.Total == 21 && r.FramesPerSecond > 0));
Assert.Equal(TimeSpan.Zero, reports[^1].Eta);
}
[Test]
public async Task EmptyAndUnreadableSequencesGiveEmptyReports()
{
var empty = await DeepAnalyzer.AnalyzeAsync(new SplicedSource(new SyntheticFrameSource(DeepScenes.HolyGrail()), null!, 0) { Count = 0 }, DeepScenes.Options);
Assert.Equal(0, empty.FrameCount);
Assert.Equal(DayNight.Unknown, empty.Sky.Light);
Assert.Empty(empty.Findings);
var unreadable = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 3 })) { Undecodable = [0, 1, 2] }, DeepScenes.Options);
Assert.Equal(DayNight.Unknown, unreadable.Sky.Light);
Assert.Null(unreadable.HeroIndex);
Assert.Null(unreadable.Regions);
Assert.SequenceEqual([0, 1, 2], unreadable.Issues.Undecodable);
Assert.Equal(unreadable.ToJson(), DeepAnalysisReport.FromJson(unreadable.ToJson()).ToJson());
}
[Test]
public void StarDetectorCountsPointsButNotBlobs()
{
using var image = new ImageBuffer(128, 96, 3);
image.Data.Fill(1f / 2048);
var random = new Random(3);
var stars = 0;
for (var y = 6; y < 90; y += 12)
{
for (var x = 6; x < 122; x += 12)
{
var v = (float)(0.2 + 0.8 * random.NextDouble());
for (var c = 0; c < 3; c++) image[c, x, y] = v;
stars++;
}
}
// A lit window: 4×4 bright block (extended, not a star).
for (var y = 40; y < 44; y++)
{
for (var x = 60; x < 64; x++)
{
for (var c = 0; c < 3; c++) image[c, x, y] = 0.8f;
}
}
var density = StarFieldDetector.Density(image, noiseSigma: 0);
Assert.Approximately(stars * 1e6 / (128 * 96), density, 1e-6);
}
[Test]
public void CloudCoverageCountsTexturedSkyBlocks()
{
using var image = new ImageBuffer(128, 64, 3);
var sky = new float[image.PlaneLength];
var random = new Random(9);
for (var y = 0; y < 64; y++)
{
for (var x = 0; x < 128; x++)
{
var i = y * 128 + x;
sky[i] = y < 32 ? 1 : 0;
// Smooth gradient everywhere; cloud texture on the left half of the sky.
var v = 0.2 + 0.002 * y + (y < 32 && x < 64 ? 0.15 * random.NextDouble() : 0);
for (var c = 0; c < 3; c++) image[c, x, y] = (float)v;
}
}
Assert.Approximately(0.5, CloudCoverage.Estimate(image, sky), 1e-9);
Assert.True(double.IsNaN(CloudCoverage.Estimate(image, new float[image.PlaneLength])));
}
[Test]
public void HistogramDistanceIgnoresExposureButNotContent()
{
using var scene = SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64 }).Render(0);
using var brighter = scene.Clone();
foreach (ref var v in brighter.Data) v *= 1.7f;
using var other = SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64, HorizonFraction = 0.8, SkyLevel = 0.6 }).Render(0);
var a = FrameStatistics.Measure(scene);
Assert.Less(HistogramDistance.ExposureAligned(a, FrameStatistics.Measure(brighter)), 0.02);
Assert.Greater(HistogramDistance.ExposureAligned(a, FrameStatistics.Measure(other)), 0.3);
}
/// <summary>Frames of <paramref name="first"/> before <paramref name="cut"/>, then frames of <paramref name="second"/>.</summary>
private sealed class SplicedSource(IFrameSource first, IFrameSource second, int cut) : IFrameSource
{
public int Count { get; init; } = first.Count;
public LightFrame Metadata(int index) => first.Metadata(index);
public ValueTask<ImageBuffer?> LoadAsync(int index, int maxLongEdge, CancellationToken cancellationToken) =>
(index < cut ? first : second).LoadAsync(index, maxLongEdge, cancellationToken);
}
/// <summary>Reports synchronously (Progress&lt;T&gt; posts to the thread pool and may reorder).</summary>
private sealed class SyncProgress(Action<AnalysisProgress> report) : IProgress<AnalysisProgress>
{
public void Report(AnalysisProgress value) => report(value);
}
}
/// <summary>Deep reports of the shared scenes, computed once per test run.</summary>
internal static class DeepReports
{
private static readonly Lazy<Task<DeepAnalysisReport>> NightReport = new(() => DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(DeepScenes.NightSky()), DeepScenes.Options));
private static readonly Lazy<Task<DeepAnalysisReport>> NightJitterReport = new(() => DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2), DeepScenes.Options));
private static readonly Lazy<Task<DeepAnalysisReport>> HolyGrailReport = new(() => DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(DeepScenes.HolyGrail()), DeepScenes.Options));
public static Task<DeepAnalysisReport> Night => NightReport.Value;
public static Task<DeepAnalysisReport> NightJitter => NightJitterReport.Value;
public static Task<DeepAnalysisReport> HolyGrail => HolyGrailReport.Value;
}
@@ -0,0 +1,125 @@
using Chronos.Core.Analysis;
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Imaging;
namespace Chronos.Core.Tests.Analysis.Deep;
/// <summary>
/// <see cref="IFrameSource"/> over a <see cref="SyntheticSequence"/>. With <paramref name="jitter"/> &gt; 0 the sequence is
/// rendered <paramref name="jitter"/> pixels larger on every side and each frame is cropped at a seeded integer offset
/// in ±jitter, which shakes the camera by a known amount.
/// </summary>
internal sealed class SyntheticFrameSource(SyntheticSequence sequence, int jitter = 0, int seed = 11) : IFrameSource
{
private readonly (int X, int Y)[] _offsets = Offsets(sequence.Count, jitter, seed);
private int _loads;
public SyntheticSequence Sequence { get; } = sequence;
public int Width => Sequence.Options.Width - 2 * jitter;
public int Height => Sequence.Options.Height - 2 * jitter;
public int Count => Sequence.Count;
/// <summary>Total calls of <see cref="LoadAsync"/>.</summary>
public int Loads => Volatile.Read(ref _loads);
/// <summary>Frames that "fail to decode".</summary>
public HashSet<int> Undecodable { get; init; } = [];
/// <summary>Called on every load before decoding (may throw to simulate a crash, or cancel a token).</summary>
public Action<int>? OnLoad { get; set; }
/// <summary>Metadata without shutter time and aperture when true.</summary>
public bool StripExposure { get; init; }
public LightFrame Metadata(int index)
{
var frame = LightFrame.From(Sequence.Metadata[index], index) with { Width = Width, Height = Height };
return StripExposure ? frame with { ExposureTime = null, FNumber = null } : frame;
}
public ValueTask<ImageBuffer?> LoadAsync(int index, int maxLongEdge, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
Interlocked.Increment(ref _loads);
OnLoad?.Invoke(index);
if (Undecodable.Contains(index)) return ValueTask.FromResult<ImageBuffer?>(null);
using var full = Sequence.Render(index);
var (dx, dy) = _offsets[index];
var image = new ImageBuffer(Width, Height, 3, clear: false);
for (var c = 0; c < 3; c++)
{
for (var y = 0; y < Height; y++)
full.Row(c, y + jitter + dy).Slice(jitter + dx, Width).CopyTo(image.Row(c, y));
}
if (int.Max(Width, Height) <= maxLongEdge) return ValueTask.FromResult<ImageBuffer?>(image);
using (image) return ValueTask.FromResult<ImageBuffer?>(AnalysisImage.Downscale(image, maxLongEdge));
}
private static (int, int)[] Offsets(int count, int jitter, int seed)
{
var random = new Random(seed);
var offsets = new (int, int)[count];
for (var i = 0; i < count; i++) offsets[i] = jitter > 0 ? (random.Next(-jitter, jitter + 1), random.Next(-jitter, jitter + 1)) : (0, 0);
return offsets;
}
}
/// <summary>In-memory checkpoint that records what was persisted.</summary>
internal sealed class MemoryCheckpoint : IDeepAnalysisCheckpoint
{
private string? _fingerprint;
public List<DeepFrame> Frames { get; } = [];
public ValueTask<IReadOnlyList<DeepFrame>> LoadAsync(string fingerprint, CancellationToken cancellationToken)
{
if (_fingerprint != fingerprint) Frames.Clear();
_fingerprint = fingerprint;
return ValueTask.FromResult<IReadOnlyList<DeepFrame>>([.. Frames]);
}
public ValueTask AppendAsync(IReadOnlyList<DeepFrame> frames, CancellationToken cancellationToken)
{
Frames.AddRange(frames);
return ValueTask.CompletedTask;
}
}
/// <summary>The synthetic scenes the deep-analysis and advisor tests share (small frames, fast).</summary>
internal static class DeepScenes
{
/// <summary>Options for the tests: small sources are analysed at native size, flow on every 5th pair, two workers.</summary>
public static DeepAnalysisOptions Options { get; } = new() { MinAnalysisLongEdge = 64, FlowEvery = 5, MaxDegreeOfParallelism = 2, RegionSampleFrames = 9 };
/// <summary>Night sky with stars over dark land and random flicker.</summary>
public static SyntheticSequence NightSky(int frames = 90, int jitter = 0) => SyntheticSequence.Create(new SyntheticSequenceOptions
{
Width = 160 + 2 * jitter,
Height = 112 + 2 * jitter,
FrameCount = frames,
IntervalSeconds = 20,
BaseExposureTime = 15,
BaseFNumber = 2.8,
BaseIso = 3200,
StarField = true,
StarCount = 160,
FlickerEv = 0.12,
Start = new DateTime(2024, 8, 12, 23, 0, 0),
});
/// <summary>Sunset: the scene darkens 6 EV while the camera opens up 1 EV every 40 frames.</summary>
public static SyntheticSequence HolyGrail(int frames = 240) => SyntheticSequence.Create(new SyntheticSequenceOptions
{
Width = 160,
Height = 112,
FrameCount = frames,
IntervalSeconds = 15,
BaseExposureTime = 1.0 / 250,
StartEv = 0.5,
EndEv = -5.5,
FlickerEv = 0.03,
ExposureSteps = [new(40, -1), new(80, -1), new(120, -1), new(160, -1), new(200, -1)],
});
}
@@ -0,0 +1,96 @@
using System.Globalization;
using Chronos.Core.Analysis;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Testing;
namespace Chronos.Core.Tests.Analysis;
public sealed class DeflickerEngineTests(TestContext context)
{
/// <summary>BRIEF §20.4: flicker reduction ≥ 60 % on the synthetic ramp with the ramp preserved within 0.05 EV,
/// measured end to end (measure → target curve → apply gains → re-measure).</summary>
[Test]
public void RampSequenceMeetsTheRegressionGate()
{
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
{
FrameCount = 200,
Seed = 3,
StartEv = -2,
EndEv = 1,
FlickerEv = 0.1,
});
var measured = AnalysisFixtures.MeasureSeries(sequence);
var result = DeflickerEngine.Compute(measured, new DeflickerOptions { Window = 21 });
var corrected = AnalysisFixtures.MeasureSeries(sequence, (i, image) =>
{
ExposureProcessor.Apply(image, result.CorrectionEv[i]);
return image;
});
var before = AnalysisFixtures.FrameToFrameResidualRms(measured, sequence.SceneEv);
var after = AnalysisFixtures.FrameToFrameResidualRms(corrected, sequence.SceneEv);
var reduction = 1 - after / before;
var rampError = AnalysisFixtures.MaxDeviation(corrected, sequence.SceneEv);
context.Log(string.Create(CultureInfo.InvariantCulture,
$"flicker before {before:F4} EV, after {after:F4} EV, reduction {reduction:P1}, max ramp deviation {rampError:F4} EV, diagnostics {result.Diagnostics}"));
Assert.GreaterOrEqual(reduction, 0.60);
Assert.LessOrEqual(rampError, 0.05);
Assert.Approximately(after, result.Diagnostics.FlickerAfter, 0.01);
Assert.Approximately(before, result.Diagnostics.FlickerBefore, 0.02);
}
[Test]
public void IntentionalOffsetsAreNotTreatedAsFlicker()
{
var n = 120;
var ramp = Enumerable.Range(0, n).Select(i => -0.01 * i).ToArray();
var offsets = Enumerable.Range(0, n).Select(i => i >= 60 ? 1.0 : 0.0).ToArray();
var measured = ramp.Select((v, i) => v + offsets[i]).ToArray();
var withOffsets = DeflickerEngine.Compute(measured, intentionalOffsets: offsets);
for (var i = 0; i < n; i++) Assert.Approximately(measured[i], withOffsets.Target[i], 1e-9);
// Without them the step is smeared into a ramp over the window.
var naive = DeflickerEngine.Compute(measured);
Assert.Greater(Math.Abs(naive.CorrectionEv[59]), 0.2);
}
[Test]
public void OutliersArePulledOntoTheFitAndStrengthBlendsTheRest()
{
var random = new Random(8);
var n = 150;
var truth = Enumerable.Range(0, n).Select(i => 0.02 * i).ToArray();
var measured = truth.Select(v => v + 0.05 * (2 * random.NextDouble() - 1)).ToArray();
measured[70] += 2.5;
var half = DeflickerEngine.Compute(measured, new DeflickerOptions { Strength = 0.5 });
Assert.Less(half.RobustWeights[70], 0.01);
Assert.Approximately(truth[70], half.Target[70], 0.05);
Assert.Equal(1, half.Diagnostics.OutlierCount);
// An inlier keeps about half of its own deviation from the fit.
var inlier = Enumerable.Range(0, n).First(i => i is > 10 and < 140 && Math.Abs(measured[i] - half.Fitted[i]) > 0.02 && half.RobustWeights[i] > 0.8);
var kept = (half.Target[inlier] - half.Fitted[inlier]) / (measured[inlier] - half.Fitted[inlier]);
Assert.InRange(kept, 0.5 * half.RobustWeights[inlier] * half.SurvivingFraction[inlier] - 1e-9, 0.5 + 1e-9);
Assert.Greater(kept, 0.35);
}
[Test]
public void UnusableFramesGetTargetsButNoCorrection()
{
var measured = Enumerable.Range(0, 40).Select(i => 0.1 * i).ToArray();
measured[12] = double.NaN;
var result = DeflickerEngine.Compute(measured, new DeflickerOptions { Window = 9 });
Assert.Approximately(1.2, result.Target[12], 1e-9);
Assert.Equal(0.0, result.CorrectionEv[12]);
Assert.Throws<ArgumentOutOfRangeException>(() => DeflickerEngine.Compute(measured, new DeflickerOptions { Strength = 2 }));
}
[Test]
public void OffsetsFromExposureFollowMetadata()
{
double?[] ev = [null, 12, 12, 11.5, null, 13];
var offsets = DeflickerEngine.OffsetsFromExposure(ev);
Assert.SequenceEqual([0.0, 0, 0, 0.5, 0.5, -1], offsets);
}
}
@@ -0,0 +1,116 @@
using Chronos.Core.Analysis;
using Chronos.Core.Imaging;
using Chronos.Testing;
namespace Chronos.Core.Tests.Analysis;
public sealed class ExposureProcessorTests
{
// 37 × 5 = 185 pixels: not a multiple of any vector width, so the scalar tail runs too.
private static ImageBuffer Ramp(int width = 37, int height = 5, int channels = 3)
{
var image = new ImageBuffer(width, height, channels);
var data = image.Data;
for (var i = 0; i < data.Length; i++) data[i] = 0.001f * (i % 997);
return image;
}
[Test]
public void EvAndChannelGainsMultiply()
{
using var image = Ramp();
using var original = image.Clone();
ExposureProcessor.Apply(image, 1, new ChannelGains(1.5, 1, 0.5));
float[] factors = [3, 2, 1];
for (var c = 0; c < 3; c++)
{
for (var i = 0; i < image.PlaneLength; i++)
Assert.Approximately(factors[c] * original.Plane(c)[i], image.Plane(c)[i], 1e-6);
}
Assert.Throws<ArgumentOutOfRangeException>(() => ExposureProcessor.Apply(image, double.NaN));
Assert.Throws<ArgumentOutOfRangeException>(() => ExposureProcessor.Apply(image, 0, new ChannelGains(0, 1, 1)));
}
[Test]
public void SingleChannelAndAlphaAreHandled()
{
using var grey = Ramp(channels: 1);
using var greyOriginal = grey.Clone();
ExposureProcessor.Apply(grey, -1, new ChannelGains(4, 4, 4));
Assert.Approximately(0.5 * greyOriginal.Plane(0)[100], grey.Plane(0)[100], 1e-7);
using var rgba = Ramp(channels: 4);
using var rgbaOriginal = rgba.Clone();
ExposureProcessor.Apply(rgba, 2);
Assert.SequenceEqual(rgbaOriginal.Plane(3).ToArray(), rgba.Plane(3).ToArray());
Assert.Approximately(4 * rgbaOriginal.Plane(2)[50], rgba.Plane(2)[50], 1e-6);
}
[Test]
public void RegionGainsBlendThroughTheMask()
{
using var image = new ImageBuffer(37, 5, 3);
image.Data.Fill(0.1f);
var mask = new float[image.PlaneLength];
for (var i = 0; i < mask.Length; i++) mask[i] = (i % 3) * 0.5f;
ExposureProcessor.ApplyRegion(image, mask, skyEv: 1, landEv: -1);
for (var i = 0; i < mask.Length; i++)
{
var expected = 0.1 * (0.5 + mask[i] * (2 - 0.5));
Assert.Approximately(expected, image.Plane(1)[i], 1e-7);
}
Assert.Throws<ArgumentException>(() => ExposureProcessor.ApplyRegion(image, new float[3], 0, 0));
}
[Test]
public void SoftClipIsSmoothBoundedAndKeepsHue()
{
const float knee = 0.8f;
Assert.Equal(0.5f, ExposureProcessor.SoftClip(0.5f, knee));
Assert.Approximately(knee, ExposureProcessor.SoftClip(knee + 1e-6f, knee), 1e-5);
var values = Enumerable.Range(0, 400).Select(i => (double)ExposureProcessor.SoftClip(i * 0.05f, knee)).ToList();
Assert.Monotonic(values);
Assert.Less(values.Max(), 1);
// Slope 1 at the knee (C¹): the secant over h above it is 1 / (1 + h / (1 − knee)).
var slope = (ExposureProcessor.SoftClip(knee + 1e-3f, knee) - knee) / 1e-3f;
Assert.Approximately(1 / (1 + 1e-3 / (1 - knee)), slope, 1e-3);
using var image = new ImageBuffer(37, 5, 3);
for (var i = 0; i < image.PlaneLength; i++)
{
image.Plane(0)[i] = 0.02f * i;
image.Plane(1)[i] = 0.01f * i;
image.Plane(2)[i] = 0.005f * i;
}
ExposureProcessor.Apply(image, 0, softClipKnee: knee);
for (var i = 1; i < image.PlaneLength; i++)
{
var r = image.Plane(0)[i];
Assert.LessOrEqual(r, 1);
Assert.Approximately(2, r / image.Plane(1)[i], 1e-4);
Assert.Approximately(2, image.Plane(1)[i] / image.Plane(2)[i], 1e-4);
Assert.Approximately(ExposureProcessor.SoftClip(0.02f * i, knee), r, 1e-5);
}
}
[Test]
public void LargeImagesTakeTheParallelPathWithTheSameResult()
{
using var image = new ImageBuffer(1100, 1000, 3);
var data = image.Data;
for (var i = 0; i < data.Length; i++) data[i] = (i % 1000) * 0.0012f;
using var expected = image.Clone();
ExposureProcessor.Apply(image, 0.5, softClipKnee: 0.9);
var gain = (float)Math.Pow(2, 0.5);
foreach (var index in new[] { 0, 12345, 777_777, 1_099_999 })
{
var r = expected.Plane(0)[index] * gain;
var g = expected.Plane(1)[index] * gain;
var b = expected.Plane(2)[index] * gain;
var m = Math.Max(r, Math.Max(g, b));
var s = m > 0.9f ? ExposureProcessor.SoftClip(m, 0.9f) / m : 1;
Assert.Approximately(r * s, image.Plane(0)[index], 1e-5);
Assert.Approximately(b * s, image.Plane(2)[index], 1e-5);
}
}
}
@@ -0,0 +1,66 @@
using System.Globalization;
using Chronos.Core.Analysis;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Testing;
namespace Chronos.Core.Tests.Analysis;
public sealed class FlickerSpectrumTests(TestContext context)
{
[Theory]
[Case(12.0)]
[Case(7.5)]
[Case(20.0)]
public void RecoversAKnownPeriodFromRenderedFrames(double period)
{
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
{
Width = 48,
Height = 32,
FrameCount = 240,
Seed = 12,
StartEv = 0,
EndEv = -2,
FlickerEv = 0.1,
FlickerPeriodFrames = period,
LandFlickerEv = 0.02,
});
var measured = AnalysisFixtures.MeasureSeries(sequence);
var result = FlickerSpectrum.Analyze(measured);
context.Log(string.Create(CultureInfo.InvariantCulture,
$"true period {period}, found {result.DominantPeriod:F3} (r = {result.PeakCorrelation:F3}), window {result.RecommendedWindow}"));
var found = Assert.NotNull(result.DominantPeriod);
Assert.Approximately(period, found, 0.5);
Assert.Equal(1, result.RecommendedWindow % 2);
Assert.InRange(result.RecommendedWindow, 4 * period - 1, 4 * period + 2);
}
[Test]
public void WhiteFlickerHasNoPeriodAndGetsTheMinimumWindow()
{
var random = new Random(2);
var series = Enumerable.Range(0, 300).Select(i => -0.01 * i + 0.1 * (2 * random.NextDouble() - 1)).ToArray();
var result = FlickerSpectrum.Analyze(series);
Assert.Null(result.DominantPeriod);
Assert.Less(result.CorrelationLength, 1.5);
Assert.Equal(FlickerSpectrumOptions.Default.MinimumWindow, result.RecommendedWindow);
}
[Test]
public void SlowCorrelatedFlickerWidensTheWindow()
{
// AR(1) flicker with correlation 0.9 per frame: e-folding length about 9.5 frames.
var random = new Random(4);
var series = new double[400];
var state = 0.0;
for (var i = 0; i < series.Length; i++)
{
state = 0.9 * state + 0.05 * (2 * random.NextDouble() - 1);
series[i] = state;
}
var result = FlickerSpectrum.Analyze(series);
Assert.InRange(result.CorrelationLength, 4, 15);
Assert.Greater(result.RecommendedWindow, 15);
Assert.Equal(1, result.RecommendedWindow % 2);
}
}
@@ -0,0 +1,197 @@
using System.Globalization;
using Chronos.Core.Analysis;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Imaging;
using Chronos.Core.Mathematics;
using Chronos.Testing;
namespace Chronos.Core.Tests.Analysis;
public sealed class FrameStatisticsTests(TestContext context)
{
/// <summary>
/// Gate: CCT within 100 K for Planckian colours from 2500 K to 10000 K, measured from images. The chromaticities
/// are exact blackbody values (Planck's law integrated against the CIE 1931 2° observer at 1 nm), independent of
/// the Krystek locus used by the estimator.
/// </summary>
[Theory]
[Case(2500, 0.476998, 0.413676)]
[Case(3000, 0.436934, 0.404075)]
[Case(3500, 0.405307, 0.390717)]
[Case(4000, 0.380442, 0.376749)]
[Case(5000, 0.345103, 0.351610)]
[Case(6000, 0.322085, 0.331755)]
[Case(6500, 0.313528, 0.323630)]
[Case(7500, 0.300336, 0.310268)]
[Case(8500, 0.290762, 0.299903)]
[Case(10000, 0.280634, 0.288289)]
public void ColourTemperatureOfPlanckianLightIsWithinOneHundredKelvin(int kelvin, double x, double y)
{
var rgb = Matrix3.XyzToRec709 * new Chromaticity(x, y).ToXyz(0.2);
using var image = new ImageBuffer(16, 16, 3);
image.Plane(0).Fill((float)rgb.X);
image.Plane(1).Fill((float)rgb.Y);
image.Plane(2).Fill((float)rgb.Z);
var estimate = Assert.NotNull(FrameStatistics.Measure(image).ColorTemperature);
context.Log(string.Create(CultureInfo.InvariantCulture,
$"{kelvin} K: estimate {estimate.Kelvin:F1} K (error {estimate.Kelvin - kelvin:F1}), raw McCamy {estimate.McCamyKelvin:F1} K, Duv {estimate.Duv:E2}"));
Assert.Approximately(kelvin, estimate.Kelvin, 100);
Assert.Less(Math.Abs(estimate.Duv), 2e-4);
}
[Test]
public void OffLocusColoursHaveNoTemperature()
{
Assert.Null(ColorTemperature.Estimate(0.1, 0.5, 0.1));
Assert.Null(ColorTemperature.Estimate(0.5, 0.1, 0.5));
Assert.Null(ColorTemperature.Estimate(0, 0, 0));
// 0.01 along the locus normal (towards green) keeps the CCT and stays within the ±0.02 validity band;
// 0.03 falls outside it.
var (u, v) = ColorTemperature.PlanckianUv(5000);
var (u1, v1) = ColorTemperature.PlanckianUv(4990);
var (u2, v2) = ColorTemperature.PlanckianUv(5010);
double nu = v1 - v2, nv = u2 - u1;
if (nv < 0) (nu, nv) = (-nu, -nv);
var length = Math.Sqrt(nu * nu + nv * nv);
Vector3D Tinted(double duv) => Matrix3.XyzToRec709 * Chromaticity.FromUv1960(u + duv * nu / length, v + duv * nv / length).ToXyz();
var green = Tinted(0.01);
var estimate = Assert.NotNull(ColorTemperature.Estimate(green.X, green.Y, green.Z));
Assert.Approximately(0.01, estimate.Duv, 1e-5);
Assert.Approximately(5000, estimate.Kelvin, 1);
var magenta = Tinted(-0.015);
Assert.Approximately(-0.015, Assert.NotNull(ColorTemperature.Estimate(magenta.X, magenta.Y, magenta.Z)).Duv, 1e-5);
var far = Tinted(0.03);
Assert.Null(ColorTemperature.Estimate(far.X, far.Y, far.Z));
}
[Test]
public void TrimmedLogMeanHistogramAndClipping()
{
// 1000 pixels: 900 at 2^-3, 50 crushed at zero, 50 clipped at 1.
using var image = new ImageBuffer(100, 10, 3);
for (var i = 0; i < 1000; i++)
{
var v = i < 50 ? 0f : i < 100 ? 1f : 0.125f;
for (var c = 0; c < 3; c++) image.Plane(c)[i] = v;
}
var stats = FrameStatistics.Measure(image);
Assert.Approximately(0.05, stats.ClipLowFraction, 1e-12);
Assert.Approximately(0.05, stats.ClipHighFraction, 1e-12);
Assert.Approximately(1, stats.Histogram.Sum(), 1e-12);
Assert.Approximately(0.9, stats.Histogram[(int)((-3 - FrameStatistics.HistogramMinEv) * 16)], 1e-12);
// Trimming 2 % per tail removes 20 of the 50 crushed and 20 of the 50 clipped pixels: (30·−14 + 900·−3 + 30·0) / 960.
Assert.Approximately((30 * -14.0 + 900 * -3.0) / 960, stats.MeanLogLuminance, 1e-9);
Assert.Approximately(0.05 + 0.9 * 0.125, stats.MeanGreen, 1e-6);
}
[Test]
public void LogMeanFollowsExposureExactly()
{
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 1 });
using var a = sequence.Render(0);
using var b = a.Clone();
ExposureProcessor.Apply(b, -1.37);
Assert.Approximately(-1.37, FrameStatistics.MeasureLogLuminance(b) - FrameStatistics.MeasureLogLuminance(a), 2e-3);
}
[Test]
public void MaskSelectsTheRegion()
{
using var image = new ImageBuffer(20, 20, 3);
var mask = new float[400];
for (var y = 0; y < 20; y++)
{
for (var x = 0; x < 20; x++)
{
var top = y < 10;
for (var c = 0; c < 3; c++) image[c, x, y] = top ? 0.5f : 0.0625f;
mask[y * 20 + x] = top ? 0 : 1;
}
}
var stats = FrameStatistics.Measure(image, mask);
Assert.Approximately(-4, stats.MeanLogLuminance, 1e-6);
Assert.Approximately(200, stats.Weight, 1e-9);
Assert.Approximately(-1, FrameStatistics.MeasureLogLuminance(image, mask.Select(m => 1 - m).ToArray()), 1e-6);
Assert.Throws<ArgumentException>(() => FrameStatistics.Measure(image, new float[3]));
}
[Test]
public void SharpnessDropsWhenBlurred()
{
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 1, Width = 64, Height = 48 });
using var sharp = sequence.Render(0);
using var blurred = sharp.Clone();
for (var c = 0; c < 3; c++)
{
var plane = blurred.Plane(c);
var source = plane.ToArray();
for (var y = 1; y < 47; y++)
{
for (var x = 1; x < 63; x++)
{
var sum = 0f;
for (var dy = -1; dy <= 1; dy++)
{
for (var dx = -1; dx <= 1; dx++) sum += source[(y + dy) * 64 + x + dx];
}
plane[y * 64 + x] = sum / 9;
}
}
}
Assert.Greater(FrameStatistics.Measure(sharp).Sharpness, 3 * FrameStatistics.Measure(blurred).Sharpness);
}
[Test]
public void ImmerkaerNoiseMatchesTheTrueSigma()
{
// Encoded-domain flat field 0.5 plus Gaussian noise of σ = 0.02 (the estimator works on sRGB-encoded luminance).
var random = new Random(17);
using var image = new ImageBuffer(128, 128, 1);
var plane = image.Plane(0);
for (var i = 0; i < plane.Length; i++)
{
var gaussian = Math.Sqrt(-2 * Math.Log(1 - random.NextDouble())) * Math.Cos(2 * Math.PI * random.NextDouble());
plane[i] = (float)ColorSpace.SrgbToLinear(0.5 + 0.02 * gaussian);
}
var stats = FrameStatistics.Measure(image);
Assert.Approximately(0.02, stats.Noise, 0.001);
Assert.Null(stats.ColorTemperature);
}
[Test]
public void DetectsBlackWhiteAndDuplicateFrames()
{
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
{
FrameCount = 8,
FlickerEv = 0.1,
BlackFrames = [2],
WhiteFrames = [4],
DuplicateFrames = [6],
});
var stats = Enumerable.Range(0, 8).Select(i =>
{
using var image = sequence.Render(i);
return FrameStatistics.Measure(image);
}).ToArray();
Assert.SequenceEqual([2], Enumerable.Range(0, 8).Where(i => stats[i].IsBlack()));
Assert.SequenceEqual([4], Enumerable.Range(0, 8).Where(i => stats[i].IsWhite()));
Assert.SequenceEqual([6], Enumerable.Range(1, 7).Where(i => FrameStatistics.AreLikelyDuplicates(stats[i - 1], stats[i])));
}
[Test]
public void DownscaleAveragesBlocks()
{
using var image = new ImageBuffer(101, 60, 3);
for (var c = 0; c < 3; c++)
{
var plane = image.Plane(c);
for (var i = 0; i < plane.Length; i++) plane[i] = (i % 101) % 2 == 0 ? 0.2f : 0.4f;
}
using var small = AnalysisImage.Downscale(image, 32);
Assert.Equal((25, 15), (small.Width, small.Height));
Assert.True(small.Data.ToArray().All(v => Math.Abs(v - 0.3f) < 1e-6f));
using var same = AnalysisImage.Downscale(image, 200);
Assert.Equal(101, same.Width);
}
}
@@ -0,0 +1,88 @@
using System.Globalization;
using Chronos.Core.Analysis;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Testing;
namespace Chronos.Core.Tests.Analysis;
public sealed class HolyGrailEngineTests(TestContext context)
{
/// <summary>
/// Sunset: the scene darkens 8 EV while the camera opens up 2/3 EV every 20 frames, plus one metadata change
/// the pixels never received. BRIEF §20.4: no target step above 0.3 EV; the total change is preserved.
/// </summary>
[Test]
public void SunsetStepsAreRedistributedWithinTheGate()
{
var steps = Enumerable.Range(1, 11).Select(k => new SyntheticExposureStep(k * 20, -2.0 / 3, k % 3 == 0 ? ExposureChange.Iso : ExposureChange.Shutter)).ToList();
steps.Add(new SyntheticExposureStep(130, -1.0 / 3, ExposureChange.Aperture, Received: false));
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
{
FrameCount = 240,
Seed = 9,
StartEv = 2,
EndEv = -6,
FlickerEv = 0.03,
ExposureSteps = steps,
});
var measured = AnalysisFixtures.MeasureSeries(sequence);
var ev = sequence.Frames.Select(f => f.ExposureValue).ToArray();
var result = HolyGrailEngine.Compute(measured, ev);
var rawMaxStep = Enumerable.Range(1, measured.Length - 1).Max(i => Math.Abs(measured[i] - measured[i - 1]));
var maxStep = Enumerable.Range(1, measured.Length - 1).Max(i => Math.Abs(result.Target[i] - result.Target[i - 1]));
var truth = sequence.SceneEv.Select((s, i) => s + sequence.ExposureOffsetEv[i]).ToArray();
var totalTruth = truth[^1] - truth[0];
var totalTarget = result.Target[^1] - result.Target[0];
context.Log(string.Create(CultureInfo.InvariantCulture,
$"raw max step {rawMaxStep:F3} EV, target max step {maxStep:F3} EV, total change target {totalTarget:F3} vs truth {totalTruth:F3} EV, transition {result.Transitions[0].Length} frames"));
Assert.Equal(12, result.Transitions.Count);
var ignored = Assert.NotNull(result.Transitions.SingleOrDefault(t => !t.Received));
Assert.Equal(130, ignored.Index);
Assert.True(result.Transitions.Where(t => t.Index != 130).All(t => t.Received));
Assert.Greater(rawMaxStep, 0.5);
Assert.LessOrEqual(maxStep, 0.3);
Assert.Approximately(maxStep, result.MaxFrameStepEv, 1e-12);
Assert.Approximately(totalTruth, totalTarget, 0.05);
// Default transition: half the 20-frame step spacing.
Assert.Equal(10.0, result.Transitions[0].Length);
}
[Test]
public void LargeStepGetsALongerTransition()
{
var n = 100;
var measured = Enumerable.Range(0, n).Select(i => i >= 50 ? 1.5 : 0.0).ToArray();
var ev = Enumerable.Range(0, n).Select(i => (double?)(i >= 50 ? 10.5 : 12.0)).ToArray();
var result = HolyGrailEngine.Compute(measured, ev, new HolyGrailOptions { TransitionFrames = 4 });
Assert.LessOrEqual(result.MaxFrameStepEv, 0.3);
Assert.GreaterOrEqual(result.Transitions[0].Length, 7.5);
Assert.Approximately(1.5, result.Target[^1] - result.Target[0], 1e-9);
Assert.Approximately(1.5, result.Transitions[0].MeasuredEv, 1e-9);
}
[Test]
public void StepsNearTheEndsStayInsideTheSequence()
{
var n = 30;
var measured = Enumerable.Range(0, n).Select(i => i >= 2 ? 1.0 : 0.0).ToArray();
var ev = Enumerable.Range(0, n).Select(i => (double?)(i >= 2 ? 11.0 : 12.0)).ToArray();
var result = HolyGrailEngine.Compute(measured, ev, new HolyGrailOptions { TransitionFrames = 8 });
Assert.Equal(0.0, result.Transitions[0].Start);
Assert.Approximately(0, result.SmoothedOffsets[0], 1e-12);
Assert.Approximately(1, result.SmoothedOffsets[^1], 1e-12);
Assert.LessOrEqual(result.MaxFrameStepEv, 0.3);
}
[Test]
public void NoMetadataStepsMeansPlainDeflicker()
{
var measured = Enumerable.Range(0, 60).Select(i => 0.01 * i + (i % 2 == 0 ? 0.05 : -0.05)).ToArray();
var ev = new double?[60];
var result = HolyGrailEngine.Compute(measured, ev);
var plain = DeflickerEngine.Compute(measured);
Assert.Empty(result.Transitions);
Assert.SequenceEqual(plain.Target, result.Target);
}
}
@@ -0,0 +1,201 @@
using System.Diagnostics;
using System.Globalization;
using Chronos.Core.Analysis;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Mathematics;
using Chronos.Testing;
namespace Chronos.Core.Tests.Analysis;
public sealed class LightAnalyzerTests(TestContext context)
{
private static SyntheticSequence Timeline() => SyntheticSequence.Create(new SyntheticSequenceOptions
{
FrameCount = 200,
IntervalSeconds = 10,
TimeShifts =
[
new(40, 60), // 70 s interval: gap
new(100, 5400), // 90 min: session break
new(150, -3600), // daylight saving ends: clock jump
new(195, 7200), // 2 h break leaving a 5-frame tail session
],
DuplicateFrames = [60],
ExposureSteps =
[
new(50, 1.0 / 3, ExposureChange.Shutter),
new(120, -1, ExposureChange.Iso),
new(170, 0.5, ExposureChange.Aperture),
],
});
[Test]
public void FindsSessionsGapsClockJumpsAndDuplicatesExactly()
{
var report = LightAnalyzer.Analyze(Timeline().LightFrames());
Assert.Equal(200, report.TimedFrameCount);
Assert.Equal(10.0, report.MedianIntervalSeconds);
Assert.Equal(0.0, report.JitterSeconds);
Assert.SequenceEqual([40, 100, 195], report.Gaps.Select(g => g.Index));
Assert.SequenceEqual([IntervalKind.Gap, IntervalKind.SessionBreak, IntervalKind.SessionBreak], report.Gaps.Select(g => g.Kind));
Assert.Approximately(70, report.Gaps[0].Seconds, 1e-9);
// The 5-frame tail merges into the previous session.
Assert.Equal(2, report.Sessions.Count);
Assert.Equal((0, 99), (report.Sessions[0].StartIndex, report.Sessions[0].EndIndex));
Assert.Equal((100, 199), (report.Sessions[1].StartIndex, report.Sessions[1].EndIndex));
Assert.SequenceEqual([(60, IntervalKind.Duplicate), (150, IntervalKind.ClockJump)], report.TimestampIssues.Select(t => (t.Index, t.Kind)));
Assert.Approximately(11050 + 3600, report.CaptureSpan.TotalSeconds, 1e-6);
Assert.Equal(report.AdjustedTimes[149]!.Value.AddSeconds(10), report.AdjustedTimes[150]!.Value);
var keys = report.Findings.Select(f => f.Key).ToList();
foreach (var key in new[] { FindingKeys.Gaps, FindingKeys.Sessions, FindingKeys.DuplicateTimestamps, FindingKeys.ClockJumps, FindingKeys.ExposureSteps })
Assert.Contains(key, keys);
foreach (var key in new[] { FindingKeys.NonMonotonicTimestamps, FindingKeys.CameraChanged, FindingKeys.MixedResolution, FindingKeys.IrregularInterval, FindingKeys.NoTimestamps })
Assert.DoesNotContain(key, keys);
var gaps = report.Findings.Single(f => f.Key == FindingKeys.Gaps);
Assert.Equal(FindingSeverity.Warning, gaps.Severity);
Assert.Equal(3, (int)gaps.Arguments[0]);
Assert.Approximately(7210, (double)gaps.Arguments[1], 1e-9);
// Domain frames (no camera or GPS fields) give the same timing and exposure analysis.
var fromFrames = LightAnalyzer.Analyze(Timeline().Frames);
Assert.SequenceEqual(report.Intervals, fromFrames.Intervals);
Assert.SequenceEqual(report.ExposureSteps.Select(s => s.Index), fromFrames.ExposureSteps.Select(s => s.Index));
}
[Test]
public void FindsExposureStepsWithTheirAmplitude()
{
var report = LightAnalyzer.Analyze(Timeline().LightFrames());
Assert.SequenceEqual([50, 120, 170], report.ExposureSteps.Select(s => s.Index));
Assert.SequenceEqual([ExposureChange.Shutter, ExposureChange.Iso, ExposureChange.Aperture], report.ExposureSteps.Select(s => s.Changes));
Assert.Approximately(1.0 / 3, report.ExposureSteps[0].DeltaEv, 1e-9);
Assert.Approximately(-1, report.ExposureSteps[1].DeltaEv, 1e-9);
Assert.Approximately(0.5, report.ExposureSteps[2].DeltaEv, 1e-9);
Assert.Equal(60.0, report.TypicalStepDistance);
Assert.Approximately(Math.Log2(64 / 0.01), report.ExposureValues[0]!.Value, 1e-9);
}
[Test]
public void SmallBackwardStepIsNonMonotonic()
{
var frames = Timeline().LightFrames().Take(30).ToList();
frames[10] = frames[10] with { CapturedAt = frames[10].CapturedAt!.Value.AddSeconds(-15) };
var report = LightAnalyzer.Analyze(frames);
Assert.SequenceEqual([(10, IntervalKind.NonMonotonic)], report.TimestampIssues.Select(t => (t.Index, t.Kind)));
Assert.Contains(FindingKeys.NonMonotonicTimestamps, report.Findings.Select(f => f.Key));
}
[Test]
public void ForwardHourJumpOnCadenceIsAClockChange()
{
var frames = Timeline().LightFrames().Take(40).Select((f, i) => i >= 20 ? f with { CapturedAt = f.CapturedAt!.Value.AddHours(1) } : f).ToList();
var report = LightAnalyzer.Analyze(frames);
Assert.SequenceEqual([(20, IntervalKind.ClockJump)], report.TimestampIssues.Select(t => (t.Index, t.Kind)));
Assert.Count(1, report.Sessions);
Assert.Approximately(390, report.CaptureSpan.TotalSeconds, 1e-6);
}
[Test]
public void ReportsIdentityResolutionAndOrientationChanges()
{
var frames = Timeline().LightFrames().Take(100).ToList();
frames[30] = frames[30] with { CameraModel = "Other" };
for (var i = 80; i < 100; i++) frames[i] = frames[i] with { Lens = "Zoom 70-200" };
frames[10] = frames[10] with { Width = 50 };
frames[11] = frames[11] with { Orientation = 6 };
frames[12] = frames[12] with { Lens = null, CameraMake = null, CameraModel = null };
var report = LightAnalyzer.Analyze(frames);
Assert.SequenceEqual([(30, IdentityKind.Camera), (31, IdentityKind.Camera), (80, IdentityKind.Lens)], report.IdentityChanges.Select(c => (c.Index, c.Kind)));
Assert.Equal("Chronos Synthetic", report.IdentityChanges[1].After);
Assert.Equal((96, 64), report.DominantSize);
Assert.SequenceEqual([10, 11], report.ResolutionOutliers);
Assert.SequenceEqual([11], report.OrientationOutliers);
var keys = report.Findings.Select(f => f.Key).ToList();
foreach (var key in new[] { FindingKeys.CameraChanged, FindingKeys.LensChanged, FindingKeys.MixedResolution, FindingKeys.MixedOrientation })
Assert.Contains(key, keys);
}
[Test]
public void LabelsDayPhasesFromGps()
{
const double lat = 45.07, lon = 7.69;
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
{
FrameCount = 240,
IntervalSeconds = 60,
Start = new DateTime(2024, 6, 21, 19, 0, 0),
UtcOffsetMinutes = 120,
Latitude = lat,
Longitude = lon,
});
var report = LightAnalyzer.Analyze(sequence.LightFrames());
var phases = report.DayPhases.Select(p => (int)Assert.NotNull(p)).ToList();
Assert.Monotonic(phases.Select(p => (double)p), decreasing: true);
Assert.Equal((int)DayPhase.Day, phases[0]);
Assert.LessOrEqual(phases[^1], (int)DayPhase.NauticalTwilight);
var sunset = SolarPosition.Events(new DateOnly(2024, 6, 21), lat, lon).Sunset!.Value.AddHours(2);
var firstTwilight = phases.FindIndex(p => p == (int)DayPhase.CivilTwilight);
var frameTime = new DateTime(2024, 6, 21, 19, 0, 0).AddMinutes(firstTwilight);
Assert.InRange((frameTime - sunset).TotalSeconds, 0, 60);
Assert.Contains(FindingKeys.DayNightTransition, report.Findings.Select(f => f.Key));
Assert.DoesNotContain(FindingKeys.TimeZoneEstimated, report.Findings.Select(f => f.Key));
// A GPS time stamp gives the same offset; without either the zone is estimated from the longitude.
var viaGps = LightAnalyzer.Analyze(sequence.LightFrames().Select(f => f with { UtcOffsetMinutes = null, GpsUtc = f.CapturedAt!.Value.AddHours(-2) }).ToList());
Assert.SequenceEqual(report.DayPhases, viaGps.DayPhases);
var estimated = LightAnalyzer.Analyze(sequence.LightFrames().Select(f => f with { UtcOffsetMinutes = null }).ToList());
var finding = estimated.Findings.Single(f => f.Key == FindingKeys.TimeZoneEstimated);
Assert.Equal(60, (int)finding.Arguments[0]);
var noGps = LightAnalyzer.Analyze(sequence.LightFrames().Select(f => f with { Latitude = null, Longitude = null }).ToList());
Assert.True(noGps.DayPhases.All(p => p is null));
}
[Test]
public void TenThousandFramesTakeWellUnderASecond()
{
var start = new DateTime(2024, 3, 1, 5, 0, 0);
var frames = Enumerable.Range(0, 10_000).Select(i => new LightFrame
{
Index = i,
CapturedAt = start.AddSeconds(i * 5 + (i >= 5000 ? 3600 : 0)),
UtcOffsetMinutes = 60,
ExposureTime = i < 4000 ? 1.0 / 500 : 1.0 / 250,
FNumber = 5.6,
Iso = 100,
Width = 6000,
Height = 4000,
CameraMake = "Maker",
CameraModel = "Body",
Lens = "Lens",
Latitude = 46.5,
Longitude = 11.3,
}).ToList();
LightAnalyzer.Analyze(frames.Take(100).ToList());
var watch = Stopwatch.StartNew();
var report = LightAnalyzer.Analyze(frames);
watch.Stop();
context.Log(string.Create(CultureInfo.InvariantCulture, $"10,000 frames analysed in {watch.Elapsed.TotalMilliseconds:F1} ms"));
Assert.Equal(10_000, report.DayPhases.Length);
Assert.Count(1, report.ExposureSteps);
Assert.Less(watch.Elapsed.TotalSeconds, 2);
}
[Test]
public void HandlesEmptyAndUntimedInput()
{
var empty = LightAnalyzer.Analyze(Array.Empty<LightFrame>());
Assert.Equal(0, empty.FrameCount);
Assert.Empty(empty.Sessions);
var untimed = LightAnalyzer.Analyze(new[] { new LightFrame(), new LightFrame { Index = 1 } });
Assert.Contains(FindingKeys.NoTimestamps, untimed.Findings.Select(f => f.Key));
Assert.Null(untimed.MedianIntervalSeconds);
Assert.Count(1, untimed.Sessions);
}
}
@@ -0,0 +1,201 @@
using System.Globalization;
using Chronos.Core.Analysis;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Imaging;
using Chronos.Testing;
namespace Chronos.Core.Tests.Analysis;
public sealed class RegionTests(TestContext context)
{
private static SyntheticSequence Landscape(int frames, double tilt, double wave, int seed = 5) => SyntheticSequence.Create(new SyntheticSequenceOptions
{
Width = 128,
Height = 80,
FrameCount = frames,
Seed = seed,
StartEv = -1,
EndEv = 0,
HorizonFraction = 0.45,
HorizonTilt = tilt,
HorizonWave = wave,
SkyFlickerEv = 0.15,
LandFlickerEv = 0.15,
});
private static List<ImageBuffer> RenderAll(SyntheticSequence sequence) => Enumerable.Range(0, sequence.Count).Select(sequence.Render).ToList();
[Test]
public void HorizonIsFoundPerColumnWithHighConfidence()
{
var sequence = Landscape(30, tilt: 0.08, wave: 3);
var frames = RenderAll(sequence);
try
{
var mask = RegionSegmenter.Segment(frames);
Assert.Equal(RegionMethod.Horizon, mask.Method);
Assert.Greater(mask.Confidence, 0.6);
var horizon = Assert.NotNull(mask.Horizon);
var worst = Enumerable.Range(0, mask.Width).Max(x => Math.Abs(horizon[x] - sequence.HorizonRow(x + 0.5)));
var agreement = Agreement(mask, sequence);
context.Log(string.Create(CultureInfo.InvariantCulture, $"confidence {mask.Confidence:F3}, worst column error {worst:F3} px, pixel agreement {agreement:P2}"));
Assert.LessOrEqual(worst, 1.0);
Assert.GreaterOrEqual(agreement, 0.98);
}
finally
{
frames.ForEach(f => f.Dispose());
}
}
[Test]
public void HorizonSurvivesPolarityChangesAcrossFrames()
{
var day = Landscape(10, tilt: 0, wave: 0);
var night = SyntheticSequence.Create(day.Options with { SkyLevel = 0.01, LandLevel = 0.2, Seed = 6 });
var frames = RenderAll(day).Concat(RenderAll(night)).ToList();
try
{
var mask = RegionSegmenter.Segment(frames);
Assert.Equal(RegionMethod.Horizon, mask.Method);
var horizon = Assert.NotNull(mask.Horizon);
Assert.True(horizon.All(h => Math.Abs(h - 0.45 * 80) <= 1), "horizon row");
}
finally
{
frames.ForEach(f => f.Dispose());
}
}
[Test]
public void CliffFallsBackToLuminance()
{
// Sky above row 20 on the left half and above row 60 on the right: no single row step explains it.
var frames = new List<ImageBuffer>();
for (var f = 0; f < 6; f++)
{
var image = new ImageBuffer(96, 80, 3);
for (var y = 0; y < 80; y++)
{
for (var x = 0; x < 96; x++)
{
var sky = y < (x < 48 ? 20 : 60);
var v = sky ? 0.4f * (1 + 0.02f * f) : 0.03f * (1 + ((x * 7 + y * 13) % 5) * 0.1f);
for (var c = 0; c < 3; c++) image[c, x, y] = v;
}
}
frames.Add(image);
}
try
{
var mask = RegionSegmenter.Segment(frames);
Assert.Equal(RegionMethod.Luminance, mask.Method);
Assert.Greater(mask.Confidence, 0.5);
var correct = 0;
for (var y = 0; y < 80; y++)
{
for (var x = 0; x < 96; x++)
{
var sky = y < (x < 48 ? 20 : 60);
if (mask.Sky[y * 96 + x] >= 0.5f == sky) correct++;
}
}
Assert.GreaterOrEqual(correct / (96.0 * 80), 0.97);
}
finally
{
frames.ForEach(f => f.Dispose());
}
}
[Test]
public void FeaturelessFramesHaveNoConfidence()
{
using var flat = new ImageBuffer(64, 48, 3);
flat.Data.Fill(0.2f);
var mask = RegionSegmenter.Segment([flat]);
Assert.Less(mask.Confidence, 0.05);
}
/// <summary>BRIEF §20.4: with independent sky and land flicker, the land residual after region deflicker is at
/// most 25 % of the residual left by one global curve.</summary>
[Test]
public void RegionDeflickerMeetsTheRegressionGate()
{
var sequence = Landscape(150, tilt: 0.05, wave: 2);
var frames = RenderAll(sequence);
RegionMask mask;
double[] sky, land, global;
try
{
mask = RegionSegmenter.Segment(frames);
sky = new double[frames.Count];
land = new double[frames.Count];
global = new double[frames.Count];
for (var i = 0; i < frames.Count; i++)
{
(sky[i], land[i]) = RegionDeflicker.Measure(frames[i], mask);
global[i] = FrameStatistics.MeasureLogLuminance(frames[i]);
}
}
finally
{
frames.ForEach(f => f.Dispose());
}
var options = new DeflickerOptions { Window = 31 };
var globalResult = DeflickerEngine.Compute(global, options);
var regionResult = RegionDeflicker.Compute(sky, land, options);
var trueLand = AnalysisFixtures.TrueLandMask(sequence);
var landAfterGlobal = AnalysisFixtures.MeasureSeries(sequence, (i, image) =>
{
ExposureProcessor.Apply(image, globalResult.CorrectionEv[i]);
return image;
}, trueLand);
var landAfterRegion = AnalysisFixtures.MeasureSeries(sequence, (i, image) =>
{
RegionDeflicker.Apply(image, mask, regionResult.Sky.CorrectionEv[i], regionResult.Land.CorrectionEv[i]);
return image;
}, trueLand);
var globalResidual = AnalysisFixtures.FrameToFrameResidualRms(landAfterGlobal, sequence.SceneEv);
var regionResidual = AnalysisFixtures.FrameToFrameResidualRms(landAfterRegion, sequence.SceneEv);
var ratio = regionResidual / globalResidual;
context.Log(string.Create(CultureInfo.InvariantCulture,
$"mask {mask.Method} confidence {mask.Confidence:F3}; land residual global {globalResidual:F4} EV, region {regionResidual:F4} EV, ratio {ratio:P1}"));
Assert.LessOrEqual(ratio, 0.25);
}
[Test]
public void ResampledMaskKeepsTheHorizon()
{
var sequence = Landscape(6, tilt: 0, wave: 0);
var frames = RenderAll(sequence);
try
{
var mask = RegionSegmenter.Segment(frames);
var big = mask.Resample(256, 160);
Assert.Equal(256 * 160, big.Sky.Length);
Assert.Approximately(2 * mask.Horizon![10], big.Horizon![20], 0.6);
Assert.True(big.Sky[5 * 256 + 100] > 0.99f && big.Sky[150 * 256 + 100] < 0.01f);
Assert.Same(mask, mask.Resample(mask.Width, mask.Height));
}
finally
{
frames.ForEach(f => f.Dispose());
}
}
private static double Agreement(RegionMask mask, SyntheticSequence sequence)
{
var correct = 0;
for (var y = 0; y < mask.Height; y++)
{
for (var x = 0; x < mask.Width; x++)
{
if (mask.Sky[y * mask.Width + x] >= 0.5f == sequence.IsSky(x, y)) correct++;
}
}
return correct / (double)(mask.Width * mask.Height);
}
}
@@ -0,0 +1,80 @@
using Chronos.Core.Analysis;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Testing;
namespace Chronos.Core.Tests.Analysis;
public sealed class SyntheticSequenceTests
{
private static readonly SyntheticSequenceOptions Recipe = new()
{
FrameCount = 30,
Seed = 42,
StartEv = -1,
EndEv = 1,
FlickerEv = 0.1,
SkyFlickerEv = 0.05,
ExposureSteps = [new(10, -1), new(20, 0.5, ExposureChange.Aperture, Received: false)],
StartKelvin = 3000,
EndKelvin = 7000,
NoiseSigma = 0.001,
DuplicateFrames = [15],
Latitude = 45,
Longitude = 9,
};
[Test]
public void IsDeterministic()
{
var a = SyntheticSequence.Create(Recipe);
var b = SyntheticSequence.Create(Recipe);
Assert.SequenceEqual(a.FlickerEv, b.FlickerEv);
Assert.SequenceEqual(a.Frames.Select(f => f.Id), b.Frames.Select(f => f.Id));
foreach (var i in new[] { 0, 7, 29 })
{
using var x = a.Render(i);
using var y = b.Render(i);
using var again = a.Render(i);
Assert.True(x.Data.SequenceEqual(y.Data) && x.Data.SequenceEqual(again.Data), $"frame {i}");
}
var other = SyntheticSequence.Create(Recipe with { Seed = 43 });
Assert.False(other.FlickerEv.SequenceEqual(a.FlickerEv));
}
[Test]
public void MetadataMatchesTheRecipe()
{
var sequence = SyntheticSequence.Create(Recipe);
var ev = sequence.Frames.Select(f => f.ExposureValue!.Value).ToArray();
Assert.Approximately(-1, ev[10] - ev[9], 1e-9);
Assert.Approximately(0.5, ev[20] - ev[19], 1e-9);
Assert.Approximately(1, sequence.ExposureOffsetEv[10], 1e-9);
Assert.Approximately(1, sequence.ExposureOffsetEv[29], 1e-9);
Assert.Equal(sequence.Frames[14].CapturedAt, sequence.Frames[15].CapturedAt);
Assert.Equal(TimeSpan.FromSeconds(10), sequence.Frames[2].CapturedAt!.Value - sequence.Frames[1].CapturedAt!.Value);
Assert.Equal(45.0, sequence.Metadata[0].Gps!.Latitude);
Assert.Equal("Synthetic", sequence.LightFrames()[3].CameraModel);
}
[Test]
public void PixelsCarryTheTruthSeries()
{
var sequence = SyntheticSequence.Create(Recipe with { SkyFlickerEv = 0, NoiseSigma = 0, StartKelvin = 5000, EndKelvin = 5000 });
var measured = AnalysisFixtures.MeasureSeries(sequence);
var truth = sequence.SceneEv.Select((s, i) => s + sequence.ExposureOffsetEv[i] + sequence.FlickerEv[i]).ToArray();
Assert.Less(AnalysisFixtures.MaxDeviation(measured, truth), 2e-3);
Assert.Equal(measured[14], measured[15]);
}
[Test]
public void StarFieldIsDarkWithPointSources()
{
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 1, StarField = true, StarCount = 60, Width = 128, Height = 96 });
using var image = sequence.Render(0);
var stats = FrameStatistics.Measure(image);
Assert.Less(stats.MeanLogLuminance, -8);
var bright = image.Plane(1).ToArray().Count(v => v > 0.2f);
Assert.InRange(bright, 30, 100);
Assert.Throws<ArgumentOutOfRangeException>(() => sequence.Render(1));
}
}
@@ -0,0 +1,71 @@
using System.Globalization;
using Chronos.Core.Analysis;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Testing;
namespace Chronos.Core.Tests.Analysis;
public sealed class WhiteBalanceSmootherTests(TestContext context)
{
[Test]
public void RemovesJitterAndKeepsTheDrift()
{
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
{
Width = 48,
Height = 32,
FrameCount = 150,
Seed = 21,
StartKelvin = 3500,
EndKelvin = 6500,
WhiteBalanceJitter = 0.08,
FlickerEv = 0.05,
});
var stats = Measure(sequence, null);
var result = WhiteBalanceSmoother.Smooth(stats.Select(s => s.MeanRed).ToArray(), stats.Select(s => s.MeanGreen).ToArray(), stats.Select(s => s.MeanBlue).ToArray());
var corrected = Measure(sequence, result.Gains);
// Truth: the ratio of the drifting light without jitter.
var truthRed = new double[sequence.Count];
var truthBlue = new double[sequence.Count];
for (var i = 0; i < sequence.Count; i++)
{
var rgb = ColorTemperature.PlanckianRgb(sequence.Kelvin[i]);
truthRed[i] = Math.Log2(rgb.X / rgb.Y);
truthBlue[i] = Math.Log2(rgb.Z / rgb.Y);
}
var before = AnalysisFixtures.FrameToFrameResidualRms(result.RedRatio, truthRed);
var after = AnalysisFixtures.FrameToFrameResidualRms(corrected.Select(s => Math.Log2(s.MeanRed / s.MeanGreen)).ToArray(), truthRed);
var afterBlue = AnalysisFixtures.FrameToFrameResidualRms(corrected.Select(s => Math.Log2(s.MeanBlue / s.MeanGreen)).ToArray(), truthBlue);
var drift = AnalysisFixtures.MaxDeviation(result.SmoothedBlueRatio, truthBlue);
context.Log(string.Create(CultureInfo.InvariantCulture, $"R/G jitter before {before:F4}, after {after:F4}; B/G after {afterBlue:F4}; drift deviation {drift:F4}"));
Assert.Less(after, 0.2 * before);
Assert.Less(afterBlue, 0.2 * before);
Assert.Less(drift, 0.03);
// Gains never change exposure.
for (var i = 0; i < sequence.Count; i++)
Assert.Approximately(stats[i].MeanLogLuminance, corrected[i].MeanLogLuminance, 0.01);
}
[Test]
public void InvalidFramesGetIdentityGains()
{
var result = WhiteBalanceSmoother.Smooth([0.5, 0, 0.5, 0.5], [0.5, 0, 0.5, 0.5], [0.5, 0, 0.5, 0.5], window: 3);
Assert.Equal(ChannelGains.Identity, result.Gains[1]);
Assert.Approximately(1, result.Gains[0].Red, 1e-12);
Assert.Throws<ArgumentException>(() => WhiteBalanceSmoother.Smooth([1.0], [1.0, 2.0], [1.0]));
}
private static FrameStatistics[] Measure(SyntheticSequence sequence, ChannelGains[]? gains)
{
var stats = new FrameStatistics[sequence.Count];
Parallel.For(0, sequence.Count, new ParallelOptions { MaxDegreeOfParallelism = 2 }, i =>
{
using var image = sequence.Render(i);
if (gains is not null) ExposureProcessor.Apply(image, 0, gains[i]);
stats[i] = FrameStatistics.Measure(image);
});
return stats;
}
}