feat(analysis): add metadata light analyzer with findings
Cadence, jitter, gaps and sessions (small sessions merge), timestamp sanity (duplicates, out-of-order frames, clock jumps incl. DST), EV series and exposure steps, camera/lens identity, resolution and orientation consistency, and NOAA day phases from GPS. Findings carry stable resource keys plus positional arguments. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
4 files changed
+647
No files matched your search
@@ -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,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,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user