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, TestTiming.Budget(2)); } [Test] public void HandlesEmptyAndUntimedInput() { var empty = LightAnalyzer.Analyze(Array.Empty()); Assert.Equal(0, empty.FrameCount); Assert.Empty(empty.Sessions); var untimed = LightAnalyzer.Analyze(new[] { new LightFrame(), new LightFrame { Index = 1 } }); Assert.Contains(FindingKeys.NoTimestamps, untimed.Findings.Select(f => f.Key)); Assert.Null(untimed.MedianIntervalSeconds); Assert.Count(1, untimed.Sessions); } }