Inital Version
This commit is contained in:
commit
94cd6b984b
211 changed files with 4765 additions and 0 deletions
BIN
src/AstroFrame.Desktop/Assets/astroframe.ico
Normal file
BIN
src/AstroFrame.Desktop/Assets/astroframe.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
BIN
src/AstroFrame.Desktop/Assets/astroframe.png
Normal file
BIN
src/AstroFrame.Desktop/Assets/astroframe.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5 KiB |
21
src/AstroFrame.Desktop/AstroFrame.Desktop.csproj
Normal file
21
src/AstroFrame.Desktop/AstroFrame.Desktop.csproj
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<ApplicationIcon>Assets/astroframe.ico</ApplicationIcon>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AvaloniaResource Include="Assets/**" />
|
||||
<RuntimeHostConfigurationOption Include="System.GC.HeapHardLimit" Value="3221225472" />
|
||||
<RuntimeHostConfigurationOption Include="System.GC.Server" Value="false" />
|
||||
<ProjectReference Include="../AstroFrame.Engine/AstroFrame.Engine.csproj" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="11.3.9" />
|
||||
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.3.9" />
|
||||
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.3.9" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
28
src/AstroFrame.Desktop/DesktopState.cs
Normal file
28
src/AstroFrame.Desktop/DesktopState.cs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
using System.Text.Json;
|
||||
|
||||
namespace AstroFrame.Desktop;
|
||||
|
||||
internal static class DesktopState
|
||||
{
|
||||
static string PathName=>System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"AstroFrame","desktop.json");
|
||||
public static void Remember(string projectDirectory)
|
||||
{
|
||||
if(Program.Arguments.Any(a=>a.StartsWith("--capture",StringComparison.Ordinal)||a=="--smoke"))return;
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(PathName)!);
|
||||
File.WriteAllText(PathName+".tmp",JsonSerializer.Serialize(new Dictionary<string,string>{{"LastProject",projectDirectory}}));File.Move(PathName+".tmp",PathName,true);
|
||||
}
|
||||
catch(IOException){}catch(UnauthorizedAccessException){}
|
||||
}
|
||||
public static string? LastProject()
|
||||
{
|
||||
try
|
||||
{
|
||||
if(!File.Exists(PathName)||new FileInfo(PathName).Length>4096)return null;
|
||||
var state=JsonSerializer.Deserialize<Dictionary<string,string>>(File.ReadAllText(PathName));
|
||||
string? directory=state?.GetValueOrDefault("LastProject");return directory!=null&&File.Exists(System.IO.Path.Combine(directory,"project.json"))?directory:null;
|
||||
}
|
||||
catch(IOException){return null;}catch(JsonException){return null;}catch(UnauthorizedAccessException){return null;}
|
||||
}
|
||||
}
|
||||
296
src/AstroFrame.Desktop/MainWindow.cs
Normal file
296
src/AstroFrame.Desktop/MainWindow.cs
Normal file
|
|
@ -0,0 +1,296 @@
|
|||
using AstroFrame.Engine;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Templates;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Platform.Storage;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.Styling;
|
||||
using Avalonia.VisualTree;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace AstroFrame.Desktop;
|
||||
public sealed class MainWindow:Window
|
||||
{
|
||||
Project? project;string projectDirectory="";CancellationTokenSource? cancellation;bool busy,refreshing,saving;
|
||||
readonly SemaphoreSlim saveGate=new(1);
|
||||
readonly ComboBox sessions=new(){Width=380,MinWidth=290,HorizontalAlignment=HorizontalAlignment.Left};
|
||||
readonly ListBox frames=new();
|
||||
readonly ComboBox filter=new(){ItemsSource=new[]{"All decisions","REVIEW","REJECT","KEEP","Manual decisions"},SelectedIndex=0,MinWidth=135};
|
||||
readonly ComboBox sort=new(){ItemsSource=new[]{"Capture time","Most concerning","Lowest star count","Lowest stellar flux","Highest FWHM"},SelectedIndex=0,MinWidth=155};
|
||||
readonly ComboBox metric=new(){ItemsSource=QualityChart.Metrics.Select(x=>x.Name).ToArray(),SelectedIndex=0,MinWidth=145};
|
||||
readonly QualityChart chart=new();
|
||||
readonly ExposureView preview=new(),comparison=new();
|
||||
readonly Border previewPanel,comparisonBorder,previewControls;
|
||||
readonly ComboBox previewMode=new(){ItemsSource=new[]{"Frame view","Nebula view"},SelectedIndex=0,MinWidth=150};
|
||||
readonly Slider displayStretch=new(){Minimum=.08,Maximum=.40,Value=.18};
|
||||
readonly StackPanel inspector=new(){Spacing=9};
|
||||
readonly Grid previewWorkspace=new(){ColumnDefinitions=new("*,0"),Margin=new(0,8,0,6)};
|
||||
readonly Border details=new();
|
||||
readonly TextBlock queueTitle=Palette.Label("Exposures",14),position=Palette.Label("",11,Palette.Muted),stretchValue=Palette.Label("0.18",11,Palette.Muted);
|
||||
readonly TextBlock exposureName=Palette.Label("",11,Palette.Muted),exposureStatus=Palette.Label("",12);
|
||||
readonly TextBlock title=Palette.Label("Light frames",18),subtitle=Palette.Label("Choose a folder to begin",11,Palette.Muted);
|
||||
readonly TextBlock status=Palette.Label("",11,Palette.Muted);
|
||||
readonly TextBlock keep=Palette.Label("—",22,Palette.Keep),review=Palette.Label("—",22,Palette.Review),reject=Palette.Label("—",22,Palette.Reject),integration=Palette.Label("—",22);
|
||||
readonly TextBlock keepTime=Palette.Label("",11,Palette.Muted),reviewTime=Palette.Label("",11,Palette.Muted),rejectTime=Palette.Label("",11,Palette.Muted),totalTime=Palette.Label("",11,Palette.Muted);
|
||||
readonly ProgressBar progress=new(){Height=3,Minimum=0,Maximum=100,IsVisible=false};
|
||||
readonly Button analyze=Button("Analyze lights",true),export=Button("Export accepted"),stop=Button("Cancel");
|
||||
readonly CheckBox spatial=new(){Content="Spatial overlay",FontSize=12},compare=new(){Content="Compare nearby",FontSize=12};
|
||||
Frame? selected;List<Frame> visible=[];
|
||||
readonly Stack<(Frame Frame,Verdict? Verdict,string Note,DateTime? At)> undo=[];
|
||||
public MainWindow()
|
||||
{
|
||||
previewPanel=Panel(preview);comparisonBorder=Panel(comparison);
|
||||
var displayPanel=new Grid{RowDefinitions=new("Auto,48")};var stretchHeading=new Grid{ColumnDefinitions=new("*,Auto")};stretchHeading.Children.Add(Palette.Label("Preview stretch",11,Palette.Muted));Grid.SetColumn(stretchValue,1);stretchHeading.Children.Add(stretchValue);displayPanel.Children.Add(stretchHeading);
|
||||
var stretchRow=new Grid{ColumnDefinitions=new("*,Auto")};displayStretch.MinHeight=44;displayStretch.VerticalAlignment=VerticalAlignment.Center;displayStretch.Margin=new(0,0,12,0);stretchRow.Children.Add(displayStretch);
|
||||
var resetStretch=Button("Reset");resetStretch.Padding=new(9,5);resetStretch.FontSize=11;resetStretch.VerticalAlignment=VerticalAlignment.Center;resetStretch.Click+=(_,_)=>displayStretch.Value=.18;Grid.SetColumn(resetStretch,1);stretchRow.Children.Add(resetStretch);Grid.SetRow(stretchRow,1);displayPanel.Children.Add(stretchRow);previewControls=new(){Child=displayPanel};
|
||||
// Keep the native slider's input behavior; give its thumb a visible silver face and room for the full circle.
|
||||
Styles.Add(new Style(x=>x.OfType<Slider>().Template().OfType<Avalonia.Controls.Primitives.Thumb>()){Setters={new Setter(Avalonia.Controls.Primitives.TemplatedControl.TemplateProperty,new FuncControlTemplate<Avalonia.Controls.Primitives.Thumb>((_,_)=>new Border{Width=20,Height=20,CornerRadius=new(10),Background=Palette.Accent,BorderBrush=Palette.Panel,BorderThickness=new(3),HorizontalAlignment=HorizontalAlignment.Center,VerticalAlignment=VerticalAlignment.Center}))}});
|
||||
previewMode.SelectionChanged+=(_,_)=>{preview.Nebula=comparison.Nebula=previewMode.SelectedIndex==1;preview.RefreshDisplay();comparison.RefreshDisplay();};
|
||||
displayStretch.PropertyChanged+=(_,e)=>{if(e.Property==Slider.ValueProperty){stretchValue.Text=displayStretch.Value.ToString("0.00");preview.Stretch=comparison.Stretch=displayStretch.Value;preview.RefreshDisplay();comparison.RefreshDisplay();}};
|
||||
Title="AstroFrame";Width=1450;Height=940;MinWidth=1120;MinHeight=740;Background=Palette.Background;FontFamily="Inter";FontSize=13;
|
||||
ExtendClientAreaToDecorationsHint=true;ExtendClientAreaChromeHints=Avalonia.Platform.ExtendClientAreaChromeHints.PreferSystemChrome;ExtendClientAreaTitleBarHeightHint=36;
|
||||
Icon=new WindowIcon(Avalonia.Platform.AssetLoader.Open(new Uri("avares://AstroFrame.Desktop/Assets/astroframe.ico")));
|
||||
var root=new Grid{RowDefinitions=new("Auto,Auto,*,Auto")};
|
||||
var headerSurface=new Grid{RowDefinitions=new("36,38"),Background=Palette.Background};root.Children.Add(headerSurface);
|
||||
var titlebar=new Grid{ColumnDefinitions=new("Auto,*"),Background=Brushes.Transparent,Margin=new(18,0,145,0)};
|
||||
Win32Properties.SetNonClientHitTestResult(titlebar,Win32Properties.Win32HitTestValue.Caption);
|
||||
titlebar.Children.Add(new Image{Source=new Avalonia.Media.Imaging.Bitmap(Avalonia.Platform.AssetLoader.Open(new Uri("avares://AstroFrame.Desktop/Assets/astroframe.png"))),Width=24,Height=24});
|
||||
var brand=Palette.Label("AstroFrame",13);brand.FontWeight=FontWeight.SemiBold;brand.Margin=new(9,0,0,0);brand.VerticalAlignment=VerticalAlignment.Center;Grid.SetColumn(brand,1);titlebar.Children.Add(brand);
|
||||
titlebar.PointerPressed+=(_,e)=>{if(e.GetCurrentPoint(this).Properties.IsLeftButtonPressed){if(e.ClickCount==2)WindowState=WindowState==WindowState.Maximized?WindowState.Normal:WindowState.Maximized;else BeginMoveDrag(e);e.Handled=true;}};
|
||||
headerSurface.Children.Add(titlebar);
|
||||
var header=new Grid{ColumnDefinitions=new("*,Auto"),Margin=new(22,0,22,2)};Grid.SetRow(header,1);
|
||||
var heading=new StackPanel{Orientation=Orientation.Horizontal,Spacing=12,VerticalAlignment=VerticalAlignment.Center};title.MinWidth=140;title.MaxWidth=330;title.TextTrimming=TextTrimming.CharacterEllipsis;title.VerticalAlignment=subtitle.VerticalAlignment=VerticalAlignment.Center;heading.Children.Add(title);heading.Children.Add(subtitle);header.Children.Add(heading);
|
||||
var toolbar=new WrapPanel{Orientation=Orientation.Horizontal,HorizontalAlignment=HorizontalAlignment.Right,VerticalAlignment=VerticalAlignment.Center};
|
||||
foreach(var b in new[]{analyze,export}){b.Margin=new(8,1,0,1);toolbar.Children.Add(b);}Grid.SetColumn(toolbar,1);header.Children.Add(toolbar);headerSurface.Children.Add(header);
|
||||
var scope=new Grid{ColumnDefinitions=new("*,Auto"),Margin=new(20,7,20,7)};
|
||||
sessions.ItemTemplate=new FuncDataTemplate<string>((text,_)=>SessionRow(text??""));sessions.SelectionChanged+=(_,_)=>{if(!refreshing)RefreshFrames();};scope.Children.Add(sessions);
|
||||
var stats=new StackPanel{Orientation=Orientation.Horizontal,Spacing=28,VerticalAlignment=VerticalAlignment.Center};
|
||||
foreach(var item in new[]{Summary("KEEP",keep,keepTime),Summary("REVIEW",review,reviewTime),Summary("REJECT",reject,rejectTime),Summary("ACCEPTED TIME",integration,totalTime)})stats.Children.Add(item);
|
||||
Grid.SetColumn(stats,1);scope.Children.Add(stats);var scopeBorder=new Border{BorderBrush=Palette.Line,BorderThickness=new(0,1,0,1),Child=scope};Grid.SetRow(scopeBorder,1);root.Children.Add(scopeBorder);
|
||||
var body=new Grid{ColumnDefinitions=new("280,1.27*,1*"),Margin=new(18,16,18,0)};Grid.SetRow(body,2);
|
||||
var queue=new Grid{RowDefinitions=new("Auto,Auto,Auto,*")};
|
||||
queueTitle.Margin=new(12,12,12,10);queue.Children.Add(queueTitle);
|
||||
var listControls=new StackPanel{Spacing=6,Margin=new(12,0,12,8)};filter.MinWidth=128;filter.FontSize=11;filter.HorizontalAlignment=HorizontalAlignment.Stretch;listControls.Children.Add(filter);
|
||||
sort.HorizontalAlignment=HorizontalAlignment.Stretch;sort.FontSize=11;listControls.Children.Add(sort);Grid.SetRow(listControls,1);queue.Children.Add(listControls);
|
||||
var columns=new Grid{ColumnDefinitions=new("*,61,48,44"),Margin=new(14,8,14,8)};int ci=0;foreach(string label in new[]{"Time (UTC)","Decision","Stars","FWHM"}){var text=Palette.Label(label,10,Palette.Muted);if(ci>1)text.HorizontalAlignment=HorizontalAlignment.Right;Grid.SetColumn(text,ci++);columns.Children.Add(text);}Grid.SetRow(columns,2);queue.Children.Add(columns);
|
||||
frames.Background=Brushes.Transparent;frames.Padding=new(0);frames.ItemTemplate=new FuncDataTemplate<Frame>((f,_)=>f==null?new Border():FrameRow(f));frames.SelectionChanged+=(_,_)=>{if(!refreshing&&frames.SelectedItem is Frame f)Select(f);};Grid.SetRow(frames,3);queue.Children.Add(frames);var queuePanel=Panel(queue);queuePanel.Margin=new(0,0,16,0);body.Children.Add(queuePanel);
|
||||
var center=new Grid{RowDefinitions=new("Auto,Auto,*,Auto,Auto,Auto"),Margin=new(0,0,16,0),MinWidth=310};Grid.SetColumn(center,1);body.Children.Add(center);
|
||||
var previewHeading=new Grid{ColumnDefinitions=new("*,Auto"),Margin=new(0,6,0,8)};previewHeading.Children.Add(Palette.Label("Exposure preview",14));position.HorizontalAlignment=HorizontalAlignment.Right;position.VerticalAlignment=VerticalAlignment.Center;Grid.SetColumn(position,1);previewHeading.Children.Add(position);center.Children.Add(previewHeading);
|
||||
var viewRow=new Grid{ColumnDefinitions=new("Auto,*,Auto")};previewMode.MinWidth=125;previewMode.FontSize=11;viewRow.Children.Add(previewMode);var switches=new StackPanel{Orientation=Orientation.Horizontal,VerticalAlignment=VerticalAlignment.Center};spatial.Content="Overlay";compare.Content="Compare";spatial.Margin=new(0,0,12,0);switches.Children.Add(spatial);switches.Children.Add(compare);Grid.SetColumn(switches,2);viewRow.Children.Add(switches);Grid.SetRow(viewRow,1);center.Children.Add(viewRow);
|
||||
previewWorkspace.Children.Add(previewPanel);Grid.SetColumn(comparisonBorder,1);previewWorkspace.Children.Add(comparisonBorder);comparisonBorder.IsVisible=false;Grid.SetRow(previewWorkspace,2);center.Children.Add(previewWorkspace);
|
||||
Grid.SetRow(previewControls,3);center.Children.Add(previewControls);
|
||||
var caption=new StackPanel{Spacing=4,Margin=new(0,0,0,12)};exposureName.TextTrimming=TextTrimming.CharacterEllipsis;caption.Children.Add(exposureName);caption.Children.Add(exposureStatus);Grid.SetRow(caption,4);center.Children.Add(caption);
|
||||
var decisions=new Grid{ColumnDefinitions=new("*,*,*,Auto")};int decisionColumn=0;
|
||||
foreach(var verdict in new[]{Verdict.Keep,Verdict.Review,Verdict.Reject}){var b=Button(verdict.ToString());b.Foreground=Palette.Verdict(verdict);b.Margin=new(0,0,6,0);b.HorizontalAlignment=HorizontalAlignment.Stretch;ToolTip.SetTip(b,$"{verdict} · {(int)verdict+1}");b.Click+=async(_,_)=>await Override(verdict);Grid.SetColumn(b,decisionColumn++);decisions.Children.Add(b);}var resetDecision=Button("Reset");resetDecision.Click+=async(_,_)=>await Override(null,false);Grid.SetColumn(resetDecision,3);decisions.Children.Add(resetDecision);Grid.SetRow(decisions,5);center.Children.Add(decisions);
|
||||
var right=new Grid{RowDefinitions=new("2*,3*"),MinWidth=320};Grid.SetColumn(right,2);body.Children.Add(right);
|
||||
var graphs=new Grid{RowDefinitions=new("Auto,*"),Margin=new(12)};var graphHeader=new Grid{ColumnDefinitions=new("*,Auto"),Margin=new(0,0,0,8)};var graphTitle=Palette.Label("Quality",14);graphTitle.VerticalAlignment=VerticalAlignment.Center;graphHeader.Children.Add(graphTitle);metric.MaxWidth=205;metric.FontSize=11;Grid.SetColumn(metric,1);graphHeader.Children.Add(metric);graphs.Children.Add(graphHeader);Grid.SetRow(chart,1);graphs.Children.Add(chart);var graphPanel=Panel(graphs);graphPanel.Margin=new(0,0,0,14);right.Children.Add(graphPanel);
|
||||
inspector.Margin=new(14);details.Child=new ScrollViewer{Content=inspector,HorizontalScrollBarVisibility=Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled};details.Background=Palette.Panel;details.BorderBrush=Palette.Line;details.BorderThickness=new(.5);details.CornerRadius=new(2);Grid.SetRow(details,1);right.Children.Add(details);root.Children.Add(body);
|
||||
var footer=new Grid{RowDefinitions=new("Auto,Auto"),Margin=new(20,7,20,7)};footer.Children.Add(progress);var footerLine=new Grid{ColumnDefinitions=new("*,Auto")};footerLine.Children.Add(status);stop.IsVisible=false;Grid.SetColumn(stop,1);footerLine.Children.Add(stop);Grid.SetRow(footerLine,1);footer.Children.Add(footerLine);Grid.SetRow(footer,3);root.Children.Add(footer);Content=root;
|
||||
analyze.Click+=async(_,_)=>await Analyze();export.Click+=async(_,_)=>await ExportAccepted();stop.Click+=(_,_)=>cancellation?.Cancel();
|
||||
filter.SelectionChanged+=(_,_)=>{if(!refreshing)RefreshFrames();};sort.SelectionChanged+=(_,_)=>{if(!refreshing)RefreshFrames();};metric.SelectionChanged+=(_,_)=>{chart.Metric=QualityChart.Metrics[Math.Max(0,metric.SelectedIndex)];chart.InvalidateVisual();};
|
||||
chart.FrameClicked+=f=>{if(!visible.Contains(f))filter.SelectedIndex=0;frames.SelectedItem=f;frames.ScrollIntoView(f);Select(f);};
|
||||
spatial.IsCheckedChanged+=(_,_)=>{preview.Spatial=spatial.IsChecked==true;preview.InvalidateVisual();};compare.IsCheckedChanged+=(_,_)=>UpdateComparison();
|
||||
KeyDown+=async(_,e)=>
|
||||
{
|
||||
if(busy||e.Source is TextBox)return;
|
||||
if(e.Key==Key.J){Move(-1);e.Handled=true;}if(e.Key==Key.K){Move(1);e.Handled=true;}
|
||||
if(e.Key is Key.D1 or Key.NumPad1){await Override(Verdict.Keep);e.Handled=true;}if(e.Key is Key.D2 or Key.NumPad2){await Override(Verdict.Review);e.Handled=true;}if(e.Key is Key.D3 or Key.NumPad3){await Override(Verdict.Reject);e.Handled=true;}
|
||||
if(e.Key==Key.Z&&e.KeyModifiers.HasFlag(KeyModifiers.Control)&&undo.Count>0){var item=undo.Pop();item.Frame.Override=item.Verdict;item.Frame.Note=item.Note;item.Frame.ReviewedAt=item.At;await Save();RefreshFrames(item.Frame);e.Handled=true;}
|
||||
};
|
||||
Closing+=(_,e)=>{if(busy){e.Cancel=true;cancellation?.Cancel();status.Text="Stopping safely; close again when finished";}};
|
||||
Closed+=(_,_)=>{preview.Dispose();comparison.Dispose();};ShowEmpty();
|
||||
}
|
||||
static Button Button(string text,bool primary=false)=>new(){Content=text,Padding=new(12,7),CornerRadius=new(2),Background=primary?Palette.Accent:Palette.Raised,Foreground=primary?Palette.Background:Palette.Text};
|
||||
static Border Panel(Control child)=>new(){Background=Palette.Panel,BorderBrush=Palette.Line,BorderThickness=new(.5),CornerRadius=new(2),ClipToBounds=true,Child=child};
|
||||
static Control Summary(string label,TextBlock value,TextBlock detail)
|
||||
{var s=new StackPanel{Spacing=2};var line=new StackPanel{Orientation=Orientation.Horizontal,Spacing=7};line.Children.Add(value);var caption=Palette.Label(label,9,Palette.Muted);caption.VerticalAlignment=VerticalAlignment.Bottom;caption.Margin=new(0,0,0,4);line.Children.Add(caption);s.Children.Add(line);s.Children.Add(detail);return s;}
|
||||
Control SessionRow(string text)
|
||||
{
|
||||
var parts=text.Split('·',StringSplitOptions.TrimEntries);var s=new StackPanel{Spacing=3,Margin=new(2,2)};s.Children.Add(Palette.Label(parts[0],14));
|
||||
if(project!=null){var scoped=project.Frames.Where(f=>text=="All sessions"||f.Session==text).ToArray();string date=parts.Length>1?parts[1]+" UTC · ":"";s.Children.Add(Palette.Label(date+$"{scoped.Length:N0} lights"+(parts.Length>3?" · "+parts[3]:""),10,Palette.Muted));}return s;
|
||||
}
|
||||
static Control FrameRow(Frame f)
|
||||
{
|
||||
var g=new Grid{ColumnDefinitions=new("*,61,48,44"),Margin=new(8,13)};var time=new StackPanel{Spacing=3};time.Children.Add(Palette.Label(f.Time.Length>=8?f.Time[^8..]:f.Time,11));time.Children.Add(Palette.Label(f.Time.Length>8?f.Time[..^9]:"",9,Palette.Muted));g.Children.Add(time);
|
||||
var badge=Palette.Label(f.Status,10,Palette.Verdict(f.Effective));badge.FontWeight=FontWeight.SemiBold;badge.VerticalAlignment=VerticalAlignment.Center;Grid.SetColumn(badge,1);g.Children.Add(badge);
|
||||
var stars=Palette.Label(f.StarCount.ToString("N0"),11);stars.VerticalAlignment=VerticalAlignment.Center;stars.HorizontalAlignment=HorizontalAlignment.Right;Grid.SetColumn(stars,2);g.Children.Add(stars);var width=Palette.Label(f.Fwhm.ToString("0.00"),11,Palette.Muted);width.VerticalAlignment=VerticalAlignment.Center;width.HorizontalAlignment=HorizontalAlignment.Right;Grid.SetColumn(width,3);g.Children.Add(width);ToolTip.SetTip(g,f.Name+(f.Override.HasValue?" · Manual decision":"")+" · "+f.Exposure+" s");return g;
|
||||
}
|
||||
void ShowEmpty()
|
||||
{
|
||||
inspector.Children.Clear();inspector.Children.Add(Palette.Label("Analyze a folder of FITS lights to begin.",12,Palette.Muted));
|
||||
export.IsEnabled=false;details.IsVisible=false;
|
||||
}
|
||||
public void LoadProject(string directory)
|
||||
{
|
||||
project=ProjectStore.Load(directory);projectDirectory=directory;undo.Clear();
|
||||
foreach(var f in project.Frames.Where(f=>f.Error==""))
|
||||
{var info=new FileInfo(f.Path);if(!info.Exists||info.Length!=f.Length||info.LastWriteTimeUtc.Ticks!=f.Modified){project.Complete=false;f.Warning="Source is missing or changed; reanalyze before export";}}
|
||||
int sessionCount=project.Frames.Select(f=>f.Session).Distinct().Count();title.Text=project.Name;subtitle.Text=$"{project.Frames.Count:N0} lights · {sessionCount} "+(sessionCount==1?"session":"sessions");
|
||||
refreshing=true;sessions.ItemsSource=new[]{"All sessions"}.Concat(project.Frames.Select(f=>f.Session).Distinct().Order()).ToArray();sessions.SelectedIndex=0;refreshing=false;
|
||||
RefreshFrames();status.Text=project.Complete?"":"Incomplete or changed project · reanalyze before exporting";export.IsEnabled=project.Complete;
|
||||
DesktopState.Remember(directory);
|
||||
}
|
||||
void RefreshFrames(Frame? prefer=null)
|
||||
{
|
||||
if(project==null)return;refreshing=true;
|
||||
var scoped=project.Frames.Where(f=>sessions.SelectedIndex<=0||f.Session==(string?)sessions.SelectedItem).OrderBy(f=>f.Timestamp).ToList();
|
||||
keep.Text=scoped.Count(f=>f.Effective==Verdict.Keep).ToString("N0");review.Text=scoped.Count(f=>f.Effective==Verdict.Review).ToString("N0");reject.Text=scoped.Count(f=>f.Effective==Verdict.Reject).ToString("N0");
|
||||
string Duration(double seconds)=>TimeSpan.FromSeconds(seconds).TotalHours>=1?$"{seconds/3600:0.0} h":$"{seconds/60:0.0} min";
|
||||
keepTime.Text=Duration(scoped.Where(f=>f.Effective==Verdict.Keep).Sum(f=>f.Exposure));reviewTime.Text=Duration(scoped.Where(f=>f.Effective==Verdict.Review).Sum(f=>f.Exposure));rejectTime.Text=Duration(scoped.Where(f=>f.Effective==Verdict.Reject).Sum(f=>f.Exposure));integration.Text=keepTime.Text;totalTime.Text=Duration(scoped.Sum(f=>f.Exposure))+" total";
|
||||
chart.Frames=scoped;
|
||||
var query=scoped.Where(f=>filter.SelectedIndex switch{1=>f.Effective==Verdict.Review,2=>f.Effective==Verdict.Reject,3=>f.Effective==Verdict.Keep,4=>f.Override!=null,_=>true});
|
||||
visible=(sort.SelectedIndex switch{1=>query.OrderBy(f=>f.Score),2=>query.OrderBy(f=>f.StarCount),3=>query.OrderBy(f=>f.Transparency),4=>query.OrderByDescending(f=>f.Fwhm),_=>query.OrderBy(f=>f.Timestamp)}).ToList();
|
||||
queueTitle.Text=$"Exposures · {visible.Count:N0}";
|
||||
frames.ItemsSource=null;frames.ItemsSource=visible;frames.SelectedItem=prefer!=null&&visible.Contains(prefer)?prefer:visible.FirstOrDefault();refreshing=false;
|
||||
if(frames.SelectedItem is Frame f)Select(f);else{selected=null;ShowNoSelection();}
|
||||
chart.InvalidateVisual();
|
||||
}
|
||||
public void CaptureSelection(bool rejected=false)
|
||||
{
|
||||
if(project==null)return;
|
||||
var f=rejected?project.Frames.FirstOrDefault(x=>x.Effective==Verdict.Reject):project.Frames.FirstOrDefault(x=>x.Target.Contains("1432"));
|
||||
if(f==null)return;sessions.SelectedItem=f.Session;filter.SelectedIndex=rejected?2:0;spatial.IsChecked=rejected;compare.IsChecked=rejected;frames.SelectedItem=f;Select(f);
|
||||
}
|
||||
public void CaptureExposure(string filename,bool nebula=false)
|
||||
{
|
||||
if(project==null)return;var f=project.Frames.First(x=>x.Name.Contains(filename,StringComparison.OrdinalIgnoreCase));sessions.SelectedItem=f.Session;filter.SelectedIndex=0;spatial.IsChecked=false;compare.IsChecked=false;previewMode.SelectedIndex=nebula?1:0;frames.SelectedItem=f;Select(f);
|
||||
}
|
||||
public Task WaitForPreviews()=>Task.WhenAll(preview.Loading,comparison.Loading);
|
||||
public void CaptureMetric(string name)
|
||||
{
|
||||
int index=Array.FindIndex(QualityChart.Metrics,m=>m.Name==name);
|
||||
if(index<0)throw new ArgumentException("Unknown quality metric",nameof(name));metric.SelectedIndex=index;
|
||||
}
|
||||
public async Task SmokeTest(string report)
|
||||
{
|
||||
if(project==null)throw new InvalidOperationException("Project not loaded");
|
||||
var results=new List<string>();void Check(bool value,string text){if(!value)throw new Exception(text);results.Add("PASS "+text);}
|
||||
Width=1120;Height=740;await Task.Delay(150);
|
||||
var countText=new FormattedText(queueTitle.Text??"",System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface(queueTitle.FontFamily),queueTitle.FontSize,queueTitle.Foreground);
|
||||
Check(queueTitle.Bounds.Width>=countText.WidthIncludingTrailingWhitespace,"full project exposure count fits at minimum window size");
|
||||
string original=projectDirectory;projectDirectory=System.IO.Path.Combine(System.IO.Path.GetDirectoryName(report)!,"smoke-project");Directory.CreateDirectory(System.IO.Path.Combine(projectDirectory,"previews"));
|
||||
project.Frames=project.Frames.Take(40).ToList();
|
||||
foreach(var f in project.Frames){var input=ProjectStore.PreviewPath(original,f);if(File.Exists(input))File.Copy(input,ProjectStore.PreviewPath(projectDirectory,f),true);}
|
||||
RefreshFrames();Check(visible.Count==40,"all-frame filter");
|
||||
foreach(var f in visible.ToArray())Select(f);Check(preview.Parent==previewPanel,"switching 40 exposures retains preview parent");
|
||||
compare.IsChecked=true;spatial.IsChecked=true;Select(visible[0]);Select(visible[1]);Check(comparison.Parent==comparisonBorder,"comparison can switch exposures repeatedly");
|
||||
var reviewed=visible[1];selected=reviewed;reviewed.Note="Existing label";await Override(Verdict.Reject,false);Check(reviewed.Override==Verdict.Reject,"manual override updates verdict");
|
||||
filter.SelectedIndex=2;Check(visible.Contains(reviewed),"reject filter includes manual override");
|
||||
var restored=ProjectStore.Load(projectDirectory);Check(restored.Frames.First(f=>f.Id==reviewed.Id).Note=="Existing label","existing notes survive decisions without a note editor");
|
||||
selected=reviewed;await Override(null,false);Check(reviewed.Override==null,"reset restores automatic verdict");
|
||||
filter.SelectedIndex=0;sort.SelectedIndex=2;Check(visible[0].StarCount==visible.Min(f=>f.StarCount),"metric sorting");
|
||||
metric.SelectedIndex=Array.FindIndex(QualityChart.Metrics,m=>m.Name=="Background");Check(chart.Metric.Name=="Background","graph metric switching");
|
||||
await WaitForPreviews();Check(preview.HasImage,"latest preview loads after rapid exposure switching");
|
||||
previewMode.SelectedIndex=1;displayStretch.Value=.26;Check(preview.Nebula&&Math.Abs(preview.Stretch-.26)<.001,"nebula view and adjustable stretch render without changing classification");
|
||||
Width=1120;Height=740;await Task.Delay(100);Check(Bounds.Width>=1120,"minimum window size");
|
||||
compare.IsChecked=false;await Task.Delay(100);
|
||||
Check(this.GetVisualDescendants().OfType<QualityChart>().Count()==1,"one selectable quality graph");
|
||||
Check(preview.Bounds.Height>330,"preview grows into available window height");
|
||||
Check(!this.GetVisualDescendants().OfType<Button>().Any(b=>b.Content is string s&&(s=="Manifest"||s=="Open project"||s=="Save note"||s=="Inspect stars")),"removed controls stay absent");
|
||||
Check(details.IsVisible&&inspector.GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text=="MEASUREMENT"),"decision evidence and measurements visible without expanding a panel");
|
||||
var thumb=displayStretch.GetVisualDescendants().OfType<Avalonia.Controls.Primitives.Thumb>().First(t=>t.IsVisible);
|
||||
var thumbTop=thumb.TranslatePoint(new Point(0,0),displayStretch)!.Value;
|
||||
Check(thumbTop.Y>=0&&thumbTop.Y+thumb.Bounds.Height<=displayStretch.Bounds.Height,"stretch thumb fits entirely inside slider");
|
||||
Check(frames.TranslatePoint(new Point(0,0),this)!.Value.X<preview.TranslatePoint(new Point(0,0),this)!.Value.X&&preview.TranslatePoint(new Point(0,0),this)!.Value.X<chart.TranslatePoint(new Point(0,0),this)!.Value.X,"exposure list, preview and quality evidence follow Atlas column order");
|
||||
var session=sessions.SelectedItem;int previousCount=visible.Count;sessions.SelectedIndex=1;Check(visible.Count<=previousCount&&visible.All(f=>f.Session==(string?)sessions.SelectedItem),"compact session selector scopes exposures");sessions.SelectedItem=session;
|
||||
await NativeDesktopChecks.Verify(this,Check);
|
||||
File.WriteAllLines(report,results);projectDirectory=original;
|
||||
}
|
||||
void ShowNoSelection(){inspector.Children.Clear();position.Text="";exposureName.Text="No exposures match this filter";exposureStatus.Text="";details.IsVisible=false;preview.Load(projectDirectory,null);comparison.Load(projectDirectory,null);chart.Selected=null;}
|
||||
void Select(Frame f)
|
||||
{
|
||||
selected=f;chart.Selected=f;chart.InvalidateVisual();details.IsVisible=true;inspector.Children.Clear();
|
||||
position.Text=$"{visible.IndexOf(f)+1:N0} / {visible.Count:N0}";
|
||||
preview.Load(projectDirectory,f);preview.Spatial=spatial.IsChecked==true;UpdateComparison();
|
||||
exposureName.Text=f.Name;ToolTip.SetTip(exposureName,f.Name);exposureStatus.Text=f.Status+" · "+f.Time+" UTC"+(f.Override.HasValue?" · Manual":"");exposureStatus.Foreground=Palette.Verdict(f.Effective);
|
||||
inspector.Children.Add(Palette.Label("DECISION EVIDENCE",10,Palette.Muted));
|
||||
inspector.Children.Add(new TextBlock{Text=f.Cause,FontSize=14,Foreground=Palette.Text,TextWrapping=TextWrapping.Wrap});
|
||||
foreach(var evidence in f.Evidence)
|
||||
{
|
||||
string summary=evidence.Message.Split(';')[0];int technical=summary.IndexOf(" (");if(technical>=0)summary=summary[..technical];
|
||||
var explanation=new TextBlock{Text="• "+summary,TextWrapping=TextWrapping.Wrap,Foreground=evidence.Severity>5?Palette.Review:Palette.Muted,FontSize=12};
|
||||
ToolTip.SetTip(explanation,evidence.Message);inspector.Children.Add(explanation);
|
||||
}
|
||||
var metrics=new Grid{ColumnDefinitions=new("*,Auto,Auto"),RowDefinitions=new("Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto")};
|
||||
string[] names=["Cloud structure","Cloud area (%)","Star count","Stellar flux","FWHM","Ellipticity","Background","Noise","Background variation"];
|
||||
double[] values=[f.CloudSignificance,100*f.CloudCoverage,f.StarCount,f.Transparency,f.Fwhm,f.Ellipticity,f.Background,f.Noise,f.BackgroundVariation];
|
||||
var caption=Palette.Label("MEASUREMENT",10,Palette.Muted);metrics.Children.Add(caption);var vcap=Palette.Label("FRAME",10,Palette.Muted);Grid.SetColumn(vcap,1);metrics.Children.Add(vcap);var bcap=Palette.Label("BASELINE",10,Palette.Muted);bcap.Margin=new(14,0,0,0);Grid.SetColumn(bcap,2);metrics.Children.Add(bcap);
|
||||
for(int i=0;i<names.Length;i++){var label=Palette.Label(names[i],12,Palette.Muted);label.Margin=new(0,7,0,0);Grid.SetRow(label,i+1);metrics.Children.Add(label);var value=Palette.Label(values[i].ToString("0.##"),12);value.Margin=new(0,7,0,0);Grid.SetRow(value,i+1);Grid.SetColumn(value,1);metrics.Children.Add(value);var baseline=Palette.Label(f.Baselines.TryGetValue(names[i],out double d)?d.ToString("0.##"):"—",12,Palette.Accent);baseline.Margin=new(14,7,0,0);Grid.SetRow(baseline,i+1);Grid.SetColumn(baseline,2);metrics.Children.Add(baseline);}inspector.Children.Add(Panel(new Border{Padding=new(12),Child=metrics}));
|
||||
inspector.Children.Add(Palette.Label($"Matched stars {f.MatchFraction:P0} · reference overlap {f.AdditionalMeasurements.GetValueOrDefault("Reference overlap"):P0}",11,Palette.Muted));
|
||||
}
|
||||
void UpdateComparison()
|
||||
{
|
||||
bool show=compare.IsChecked==true;comparisonBorder.IsVisible=show;previewWorkspace.ColumnDefinitions[1].Width=show?new GridLength(1,GridUnitType.Star):new GridLength(0);previewPanel.Margin=show?new(0,0,6,0):new(0);
|
||||
preview.Caption=show?"Selected":"";comparison.Caption=show?"Nearby":"";preview.InvalidateVisual();
|
||||
if(selected==null||project==null||!show){comparison.Load(projectDirectory,null);return;}
|
||||
var nearby=project.Frames.Where(f=>f.Session==selected.Session&&f.Id!=selected.Id&&f.Timestamp.HasValue&&selected.Timestamp.HasValue&&f.Error=="").OrderBy(f=>Math.Abs((f.Timestamp!.Value-selected.Timestamp!.Value).TotalSeconds)).FirstOrDefault();comparison.Load(projectDirectory,nearby);ToolTip.SetTip(comparisonBorder,nearby==null?"No comparable nearby exposure":"Nearby · "+nearby.Time+" · "+nearby.Status);
|
||||
}
|
||||
void Move(int step){if(visible.Count==0)return;int index=selected==null?0:visible.IndexOf(selected);var f=visible[Math.Clamp(index+step,0,visible.Count-1)];frames.SelectedItem=f;frames.ScrollIntoView(f);}
|
||||
async Task Override(Verdict? verdict,bool advance=true)
|
||||
{
|
||||
if(selected==null||busy||saving)return;var f=selected;int index=visible.IndexOf(f);undo.Push((f,f.Override,f.Note,f.ReviewedAt));f.Override=verdict;f.ReviewedAt=DateTime.UtcNow;
|
||||
if(!await Save()){var previous=undo.Pop();f.Override=previous.Verdict;f.Note=previous.Note;f.ReviewedAt=previous.At;RefreshFrames(f);status.Text="Review could not be saved; decision restored";return;}
|
||||
var next=advance?visible.ElementAtOrDefault(index+1)??visible.ElementAtOrDefault(index-1):f;RefreshFrames(next);status.Text="Manual decision saved · Ctrl+Z to undo";
|
||||
}
|
||||
async Task<bool> Save()
|
||||
{
|
||||
if(project==null)return false;await saveGate.WaitAsync();saving=true;analyze.IsEnabled=export.IsEnabled=false;
|
||||
try{var p=project;var directory=projectDirectory;await Task.Run(()=>ProjectStore.Save(p,directory));return true;}
|
||||
catch(Exception e){await Message("Could not save project",e.Message);return false;}
|
||||
finally{saving=false;analyze.IsEnabled=!busy;export.IsEnabled=!busy&&project.Complete;saveGate.Release();}
|
||||
}
|
||||
async Task<string?> Folder(string title)
|
||||
{var result=await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions{Title=title,AllowMultiple=false});return result.FirstOrDefault()?.TryGetLocalPath();}
|
||||
void Busy(bool value){busy=value;analyze.IsEnabled=!value;export.IsEnabled=!value&&project?.Complete==true;frames.IsEnabled=sessions.IsEnabled=chart.IsEnabled=filter.IsEnabled=sort.IsEnabled=metric.IsEnabled=!value;inspector.IsEnabled=!value;stop.IsVisible=progress.IsVisible=value;}
|
||||
async Task Analyze()
|
||||
{
|
||||
string? source=project?.Source;
|
||||
if(source!=null)
|
||||
{
|
||||
bool same=await Confirm("Analyze lights","Reanalyze the current source folder using cached measurements, or choose another folder?","Current source","Choose folder");if(!same)source=null;
|
||||
}
|
||||
source??=await Folder("Choose a folder containing raw FITS lights");if(source==null)return;
|
||||
if(project?.Source!=source)
|
||||
{
|
||||
string hash=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(source)))[..16];
|
||||
projectDirectory=System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"AstroFrame","Projects",hash);
|
||||
project=File.Exists(System.IO.Path.Combine(projectDirectory,"project.json"))?ProjectStore.Load(projectDirectory):null;
|
||||
}
|
||||
Busy(true);cancellation=new();progress.Value=0;
|
||||
var updates=new Progress<ProgressInfo>(p=>{progress.Value=p.Total==0?0:100.0*p.Done/p.Total;status.Text=$"{p.Stage} · {p.Done:N0} / {p.Total:N0} · {p.File}";});
|
||||
try
|
||||
{
|
||||
var previous=project;await Task.Run(async()=>project=await new Analyzer().AnalyzeAsync(source,projectDirectory,previous,updates,cancellation.Token));LoadProject(projectDirectory);
|
||||
}
|
||||
catch(OperationCanceledException){if(File.Exists(System.IO.Path.Combine(projectDirectory,"project.json")))LoadProject(projectDirectory);status.Text="Cancelled · completed measurements saved; reanalyze to resume";}
|
||||
catch(ResourcePressureException e){if(File.Exists(System.IO.Path.Combine(projectDirectory,"project.json")))LoadProject(projectDirectory);status.Text="Paused safely for RAM pressure · completed measurements saved";await Message("RAM headroom unavailable",e.Message);}
|
||||
catch(Exception e){await Message("Analysis could not finish",e.Message);status.Text="Analysis failed · check source folder and project storage";}
|
||||
finally{Busy(false);cancellation.Dispose();cancellation=null;}
|
||||
}
|
||||
async Task ExportAccepted()
|
||||
{
|
||||
if(project?.Complete!=true)return;
|
||||
var options=new Window{Title="Export accepted lights",Width=470,SizeToContent=SizeToContent.Height,CanResize=false,WindowStartupLocation=WindowStartupLocation.CenterOwner,Background=Palette.Panel};
|
||||
var layout=new StackPanel{Margin=new(24),Spacing=14};layout.Children.Add(Palette.Label("Prepare lights for Siril",21));layout.Children.Add(new TextBlock{Text="KEEP frames are included. Originals are opened read-only. Select an empty output folder outside your input tree.",TextWrapping=TextWrapping.Wrap,Foreground=Palette.Muted});
|
||||
var scopes=new List<(string Name,List<Frame> Frames)>();
|
||||
if(sessions.SelectedIndex>0)scopes.Add(("Selected observing session",project.Frames.Where(f=>f.Session==(string?)sessions.SelectedItem).ToList()));
|
||||
foreach(var target in project.Frames.Select(f=>f.Target).Distinct())scopes.Add((target+" · all sessions",project.Frames.Where(f=>f.Target==target).ToList()));
|
||||
scopes.Add(("Entire project · separate target folders",project.Frames));
|
||||
var scope=new ComboBox{ItemsSource=scopes.Select(x=>x.Name).ToArray(),SelectedIndex=sessions.SelectedIndex>0?0:scopes.Count-1,HorizontalAlignment=HorizontalAlignment.Stretch};layout.Children.Add(Palette.Label("EXPORT SCOPE",10,Palette.Muted));layout.Children.Add(scope);
|
||||
var include=new CheckBox{Content="Also include unresolved REVIEW frames",IsChecked=false};var links=new CheckBox{Content="Use hardlinks when available (copy fallback)",IsChecked=true};layout.Children.Add(include);layout.Children.Add(links);layout.Children.Add(new TextBlock{Text="Hardlinks share source bytes. Use Siril to read and process these inputs into separate outputs. Choose copies if another tool may overwrite input files.",FontSize=11,TextWrapping=TextWrapping.Wrap,Foreground=Palette.Muted});var buttons=new WrapPanel();var go=Button("Choose output folder",true);var cancel=Button("Cancel");cancel.Margin=new(8,0,0,0);buttons.Children.Add(go);buttons.Children.Add(cancel);layout.Children.Add(buttons);options.Content=layout;go.Click+=(_,_)=>options.Close(true);cancel.Click+=(_,_)=>options.Close(false);
|
||||
if(!await options.ShowDialog<bool>(this))return;string? output=await Folder("Choose an empty output folder for accepted lights");if(output==null)return;
|
||||
var exportProject=new Project{Name=project.Name,Source=project.Source,Complete=project.Complete,Frames=scopes[scope.SelectedIndex].Frames};
|
||||
Busy(true);cancellation=new();try{var result=await Export.AcceptedAsync(exportProject,output,include.IsChecked==true,links.IsChecked==true,new Progress<ProgressInfo>(p=>{progress.Value=100.0*p.Done/Math.Max(1,p.Total);status.Text=$"{p.Stage} · {p.Done}/{p.Total}";}),cancellation.Token);status.Text=$"Export complete · {result.Linked} hardlinks, {result.Copied} copies · {output}";}
|
||||
catch(OperationCanceledException){status.Text="Export cancelled · completed output files retained; choose a new empty folder to retry";}catch(Exception e){await Message("Export could not finish",e.Message);}finally{Busy(false);cancellation.Dispose();cancellation=null;}
|
||||
}
|
||||
async Task Message(string heading,string message){await Confirm(heading,message,"OK",null);}
|
||||
internal async Task ReportLoadFailure(string message)=>await Message("Could not reopen the last project",message);
|
||||
async Task<bool> Confirm(string heading,string message,string yes,string? no)
|
||||
{
|
||||
var window=new Window{Title=heading,Width=460,SizeToContent=SizeToContent.Height,CanResize=false,WindowStartupLocation=WindowStartupLocation.CenterOwner,Background=Palette.Panel};var layout=new StackPanel{Margin=new(24),Spacing=18};layout.Children.Add(Palette.Label(heading,20));layout.Children.Add(new TextBlock{Text=message,TextWrapping=TextWrapping.Wrap,Foreground=Palette.Muted});var buttons=new WrapPanel();var accept=Button(yes,true);accept.Click+=(_,_)=>window.Close(true);buttons.Children.Add(accept);if(no!=null){var decline=Button(no);decline.Margin=new(8,0,0,0);decline.Click+=(_,_)=>window.Close(false);buttons.Children.Add(decline);}layout.Children.Add(buttons);window.Content=layout;return await window.ShowDialog<bool>(this);
|
||||
}
|
||||
}
|
||||
39
src/AstroFrame.Desktop/NativeDesktopChecks.cs
Normal file
39
src/AstroFrame.Desktop/NativeDesktopChecks.cs
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.VisualTree;
|
||||
|
||||
namespace AstroFrame.Desktop;
|
||||
|
||||
/// <summary>Opt-in smoke verification of actual native styles and caption hit tests.</summary>
|
||||
internal static class NativeDesktopChecks
|
||||
{
|
||||
[DllImport("user32.dll")]static extern nint GetWindowLongPtrW(nint window,int index);
|
||||
[DllImport("user32.dll")]static extern nint SendMessageW(nint window,uint message,nint wParam,nint lParam);
|
||||
[DllImport("user32.dll")]static extern bool GetWindowRect(nint window,out NativeRect rect);
|
||||
[DllImport("user32.dll")]static extern bool IsIconic(nint window);
|
||||
[StructLayout(LayoutKind.Sequential)]struct NativeRect{public int Left,Top,Right,Bottom;}
|
||||
static nint Coordinates(PixelPoint point)=>new(unchecked((point.Y&0xffff)<<16|(point.X&0xffff)));
|
||||
public static async Task Verify(Window window,Action<bool,string> check)
|
||||
{
|
||||
if(!OperatingSystem.IsWindows())return;
|
||||
nint handle=window.TryGetPlatformHandle()!.Handle;long style=GetWindowLongPtrW(handle,-16).ToInt64();
|
||||
check((style&0x00040000)!=0&&(style&0x00020000)!=0&&(style&0x00010000)!=0,"native resize, minimize and maximize styles retained");
|
||||
check(window.IsExtendedIntoWindowDecorations,"title bar is integrated into the client area");
|
||||
int Hit(PixelPoint point)=>(int)SendMessageW(handle,0x84,0,Coordinates(point));
|
||||
check(Hit(window.PointToScreen(new Point(300,20)))==2,"title bar provides native caption dragging and double-click");
|
||||
var buttons=window.GetVisualDescendants().OfType<Button>().ToArray();
|
||||
foreach(var (name,expected) in new[]{("PART_MinimizeButton",8),("PART_RestoreButton",9),("PART_CloseButton",20)})
|
||||
{
|
||||
var button=buttons.Single(b=>b.Name==name);check(Hit(button.PointToScreen(new Point(button.Bounds.Width/2,button.Bounds.Height/2)))==expected,"native caption hit target: "+name);
|
||||
}
|
||||
GetWindowRect(handle,out var normal);check(Hit(new PixelPoint(normal.Left+1,(normal.Top+normal.Bottom)/2))==10,"native left-edge resize hit target");
|
||||
window.WindowState=WindowState.Maximized;await Task.Delay(200);GetWindowRect(handle,out var maximized);
|
||||
var area=window.Screens.ScreenFromWindow(window)!.WorkingArea;
|
||||
check(window.WindowState==WindowState.Maximized&&maximized.Left>=area.X-24&&maximized.Top>=area.Y-24&&maximized.Right<=area.Right+24&&maximized.Bottom<=area.Bottom+24,"maximize respects the monitor working area");
|
||||
window.WindowState=WindowState.Minimized;await Task.Delay(100);check(IsIconic(handle),"native minimize succeeds");
|
||||
// Windows restores a minimized maximized window to its previous maximized state.
|
||||
window.WindowState=WindowState.Normal;await Task.Delay(150);check(window.WindowState==WindowState.Maximized,"native restore preserves the previous maximized state");
|
||||
window.WindowState=WindowState.Normal;await Task.Delay(150);check(window.WindowState==WindowState.Normal,"native unmaximize succeeds");
|
||||
}
|
||||
}
|
||||
75
src/AstroFrame.Desktop/Program.cs
Normal file
75
src/AstroFrame.Desktop/Program.cs
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Themes.Fluent;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.Media.Imaging;
|
||||
using AstroFrame.Engine;
|
||||
|
||||
namespace AstroFrame.Desktop;
|
||||
internal static class Program
|
||||
{
|
||||
public static string[] Arguments=[];
|
||||
static Mutex? instance;
|
||||
[STAThread] public static void Main(string[] args)
|
||||
{
|
||||
instance=new Mutex(true,"AstroFrame.Desktop.OneInstance",out bool created);if(!created)return;
|
||||
try
|
||||
{
|
||||
ResourcePolicy.InstallWindowsLimit();Arguments=args;
|
||||
AppBuilder.Configure<App>().UsePlatformDetect().With(new Win32PlatformOptions{RenderingMode=[Win32RenderingMode.Software]}).WithInterFont().LogToTrace().StartWithClassicDesktopLifetime(args);
|
||||
}
|
||||
catch(Exception e){File.WriteAllText(System.IO.Path.Combine(AppContext.BaseDirectory,"startup-error.log"),e.ToString());Environment.ExitCode=1;}
|
||||
finally{instance.ReleaseMutex();instance.Dispose();}
|
||||
}
|
||||
}
|
||||
public sealed class App:Application
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
RequestedThemeVariant=Avalonia.Styling.ThemeVariant.Dark;Styles.Add(new FluentTheme());
|
||||
foreach(string key in new[]{"SystemAccentColor","SystemAccentColorLight1","SystemAccentColorLight2","SystemAccentColorLight3","SystemAccentColorDark1","SystemAccentColorDark2","SystemAccentColorDark3"})Resources[key]=Color.Parse("#343638");
|
||||
}
|
||||
public override void OnFrameworkInitializationCompleted()
|
||||
{
|
||||
if(ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
if(Program.Arguments.Length>=4&&Program.Arguments[0]=="--capture-stars")
|
||||
{
|
||||
string directory=System.IO.Path.GetFullPath(Program.Arguments[1]);var project=ProjectStore.Load(directory);var frame=project.Frames.First(f=>f.Name.Contains(Program.Arguments[3],StringComparison.OrdinalIgnoreCase));desktop.MainWindow=new StarInspector(project,directory,frame,Program.Arguments[2]);base.OnFrameworkInitializationCompleted();return;
|
||||
}
|
||||
var window=new MainWindow();desktop.MainWindow=window;
|
||||
if(Program.Arguments.Length>=3&&Program.Arguments[0] is "--capture" or "--smoke")
|
||||
{
|
||||
window.Opened+=async(_,_)=>
|
||||
{
|
||||
try
|
||||
{
|
||||
window.LoadProject(System.IO.Path.GetFullPath(Program.Arguments[1]));
|
||||
if(Program.Arguments[0]=="--smoke"){await window.SmokeTest(Program.Arguments[2]);desktop.Shutdown(0);return;}
|
||||
if(Program.Arguments.Length>3)
|
||||
{
|
||||
if(Program.Arguments[3].EndsWith(".fit",StringComparison.OrdinalIgnoreCase))window.CaptureExposure(Program.Arguments[3],Program.Arguments.Contains("nebula"));
|
||||
else if(Program.Arguments[3]!="all")window.CaptureSelection(Program.Arguments[3]=="reject");
|
||||
}
|
||||
string? metricOption=Program.Arguments.FirstOrDefault(a=>a.StartsWith("--metric="));if(metricOption!=null)window.CaptureMetric(metricOption[9..]);
|
||||
if(Program.Arguments.Length>4&&double.TryParse(Program.Arguments[4],System.Globalization.NumberStyles.Float,System.Globalization.CultureInfo.InvariantCulture,out double width)){window.Width=width;window.Height=740;}
|
||||
await window.WaitForPreviews();await Task.Delay(400);
|
||||
if(window.Content is Control content)
|
||||
{
|
||||
string? dpiOption=Program.Arguments.FirstOrDefault(a=>a.StartsWith("--dpi="));double dpi=dpiOption==null?96:double.Parse(dpiOption[6..],System.Globalization.CultureInfo.InvariantCulture);
|
||||
if(dpi<96||dpi>240)throw new ArgumentOutOfRangeException(nameof(dpi));
|
||||
using var bitmap=new RenderTargetBitmap(new PixelSize((int)Math.Ceiling(window.Bounds.Width*dpi/96),(int)Math.Ceiling(window.Bounds.Height*dpi/96)),new Vector(dpi,dpi));bitmap.Render(window);bitmap.Save(Program.Arguments[2]);
|
||||
}
|
||||
desktop.Shutdown(0);
|
||||
}
|
||||
catch(Exception e){System.IO.File.WriteAllText(Program.Arguments[2]+".error",e.ToString());desktop.Shutdown(1);}
|
||||
};
|
||||
}
|
||||
else if(Program.Arguments.Length>=2&&Program.Arguments[0]=="--project")window.Opened+=(_,_)=>window.LoadProject(System.IO.Path.GetFullPath(Program.Arguments[1]));
|
||||
else if(DesktopState.LastProject() is string last)window.Opened+=async(_,_)=>{try{window.LoadProject(last);}catch(Exception e){await window.ReportLoadFailure(e.Message);}};
|
||||
}
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
}
|
||||
56
src/AstroFrame.Desktop/StarInspector.cs
Normal file
56
src/AstroFrame.Desktop/StarInspector.cs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
using AstroFrame.Engine;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Media.Imaging;
|
||||
using Avalonia.Platform;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace AstroFrame.Desktop;
|
||||
public sealed class StarInspector:Window
|
||||
{
|
||||
readonly List<WriteableBitmap> bitmaps=[];
|
||||
readonly CancellationTokenSource cancellation=new();
|
||||
public StarInspector(Project project,string directory,Frame selected,string? capture=null)
|
||||
{
|
||||
Title="AstroFrame · Matched star detail";Width=900;Height=790;MinWidth=660;MinHeight=520;Background=Palette.Background;FontFamily="Inter";WindowStartupLocation=WindowStartupLocation.CenterOwner;
|
||||
var panel=new StackPanel{Margin=new(24),Spacing=12};Content=new Border{Background=Palette.Background,Child=new ScrollViewer{Content=panel}};var progress=Palette.Label("Reading matched source stars…",16);panel.Children.Add(progress);
|
||||
Opened+=async(_,_)=>
|
||||
{
|
||||
try
|
||||
{
|
||||
var peer=StellarDetail.Comparison(project,selected)??throw new InvalidDataException("No comparable KEEP exposure in this session");
|
||||
var detail=await Task.Run(async()=>{await ResourcePolicy.WaitForHeadroom(ResourcePolicy.EstimateFrameBytes(selected.Width,selected.Height,selected.Bayer!=""?2:1)*2,cancellation.Token);return StellarDetail.Read(directory,selected,peer,cancellation.Token);},cancellation.Token);
|
||||
cancellation.Token.ThrowIfCancellationRequested();panel.Children.Clear();panel.Children.Add(Palette.Label("Matched stars · original source samples",21));
|
||||
panel.Children.Add(new TextBlock{Text="Identical stars, aligned between exposures. Each crop has its own brightness normalization. Pixels are enlarged without smoothing; Bayer samples are combined 2×2. Judge shape here, and transparency from the flux measurements.",FontSize=12,Foreground=Palette.Muted,TextWrapping=TextWrapping.Wrap});
|
||||
var header=new Grid{ColumnDefinitions=new("45,*,*")};
|
||||
TextBlock Label(string text)=>new(){Text=text,Foreground=Palette.Text,TextWrapping=TextWrapping.Wrap,FontSize=12,Margin=new(8,0)};
|
||||
var left=Label(selected.Status+" · "+selected.Time+" UTC\n"+selected.Name+$"\nFWHM {selected.Fwhm:0.00} px · ellipticity {selected.Ellipticity:0.00}");Grid.SetColumn(left,1);header.Children.Add(left);
|
||||
var right=Label(peer.Status+" · "+peer.Time+" UTC\n"+peer.Name+$"\nFWHM {peer.Fwhm:0.00} px · ellipticity {peer.Ellipticity:0.00}");Grid.SetColumn(right,2);header.Children.Add(right);panel.Children.Add(header);
|
||||
foreach(var star in detail.Stars)
|
||||
{
|
||||
var row=new Grid{ColumnDefinitions=new("45,*,*"),Margin=new(0,6)};row.Children.Add(Palette.Label(star.Number.ToString("00"),12,Palette.Muted));
|
||||
foreach(var entry in new[]{(Pixels:star.Selected,Column:1),(Pixels:star.Comparison,Column:2)})
|
||||
{
|
||||
var bitmap=Gray(entry.Pixels,detail.Size);bitmaps.Add(bitmap);var image=new Image{Source=bitmap,Width=130,Height=130,HorizontalAlignment=HorizontalAlignment.Left,Margin=new(8,0)};RenderOptions.SetBitmapInterpolationMode(image,BitmapInterpolationMode.None);Grid.SetColumn(image,entry.Column);row.Children.Add(image);
|
||||
}
|
||||
panel.Children.Add(row);
|
||||
}
|
||||
if(capture!=null)
|
||||
{
|
||||
await Task.Delay(200);if(Content is Control content){using var bitmap=new RenderTargetBitmap(new PixelSize((int)content.Bounds.Width,(int)content.Bounds.Height),new Vector(96,96));bitmap.Render(content);bitmap.Save(capture);}((IClassicDesktopStyleApplicationLifetime)Application.Current!.ApplicationLifetime!).Shutdown(0);
|
||||
}
|
||||
}
|
||||
catch(OperationCanceledException){}
|
||||
catch(Exception e){progress.Text="Star detail unavailable: "+e.Message;if(capture!=null){File.WriteAllText(capture+".error",e.ToString());((IClassicDesktopStyleApplicationLifetime)Application.Current!.ApplicationLifetime!).Shutdown(1);}}
|
||||
};
|
||||
Closing+=(_,_)=>cancellation.Cancel();Closed+=(_,_)=>{foreach(var bitmap in bitmaps)bitmap.Dispose();cancellation.Dispose();};
|
||||
}
|
||||
static WriteableBitmap Gray(byte[] pixels,int size)
|
||||
{
|
||||
var bitmap=new WriteableBitmap(new(size,size),new(96,96),PixelFormat.Bgra8888,AlphaFormat.Opaque);using var locked=bitmap.Lock();byte[] row=new byte[size*4];
|
||||
for(int y=0;y<size;y++){for(int x=0;x<size;x++){byte v=pixels[y*size+x];row[4*x]=row[4*x+1]=row[4*x+2]=v;row[4*x+3]=255;}Marshal.Copy(row,0,locked.Address+y*locked.RowBytes,row.Length);}return bitmap;
|
||||
}
|
||||
}
|
||||
155
src/AstroFrame.Desktop/Visuals.cs
Normal file
155
src/AstroFrame.Desktop/Visuals.cs
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
using AstroFrame.Engine;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Media.Imaging;
|
||||
using Avalonia.Platform;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace AstroFrame.Desktop;
|
||||
public static class Palette
|
||||
{
|
||||
public static readonly IBrush Background=Brush("#151617"),Panel=Brush("#1E2021"),Raised=Brush("#292B2D"),Muted=Brush("#A2A5A7"),Text=Brush("#E6E7E7"),Accent=Brush("#D3D5D4"),Keep=Brush("#A8BFB0"),Review=Brush("#D5BF91"),Reject=Brush("#DBA2A6"),Line=Brush("#3B3E40");
|
||||
public static IBrush Brush(string hex)=>new SolidColorBrush(Color.Parse(hex));
|
||||
public static IBrush Verdict(Verdict v)=>v switch{AstroFrame.Engine.Verdict.Keep=>Keep,AstroFrame.Engine.Verdict.Reject=>Reject,_=>Review};
|
||||
public static readonly IBrush GraphKeep=Brush("#68DE96"),GraphReview=Brush("#F2C366"),GraphReject=Brush("#FF8794");
|
||||
public static IBrush GraphVerdict(Verdict v)=>v switch{AstroFrame.Engine.Verdict.Keep=>GraphKeep,AstroFrame.Engine.Verdict.Reject=>GraphReject,_=>GraphReview};
|
||||
public static TextBlock Label(string text,double size=13,IBrush? color=null)=>new(){Text=text,FontSize=size,Foreground=color??Text};
|
||||
}
|
||||
public sealed record Metric(string Name,Func<Frame,double> Value,string Baseline,string Unit);
|
||||
public sealed class QualityChart:Control
|
||||
{
|
||||
public static readonly Metric[] Metrics=[new("Cloud structure",f=>f.CloudSignificance,"","reference scatter"),new("Cloud affected area",f=>100*f.CloudCoverage,"","% of overlap"),new("Detected stars",f=>f.StarCount,"Star count","stars"),new("Forced stellar flux",f=>f.Transparency,"Stellar flux","relative"),new("FWHM",f=>f.Fwhm,"FWHM","pixels"),new("Ellipticity",f=>f.Ellipticity,"Ellipticity","1 − b/a"),new("Background",f=>f.Background,"Background","ADU"),new("Sky noise",f=>f.Noise,"Noise","ADU"),new("Spatial background variation",f=>f.BackgroundVariation,"Background variation","ADU"),new("Matched star fraction",f=>f.MatchFraction,"","fraction")];
|
||||
public List<Frame> Frames {get;set;}=[];
|
||||
public Metric Metric {get;set;}=Metrics[0];
|
||||
public Frame? Selected {get;set;}
|
||||
public event Action<Frame>? FrameClicked;
|
||||
public QualityChart(){MinHeight=110;PointerPressed+=OnPointer;}
|
||||
(double Min,double Max) Range()
|
||||
{
|
||||
var values=Frames.Where(f=>f.Measured&&f.Error=="").Select(Metric.Value).ToArray();
|
||||
double min=Robust.Quantile(values,.01),max=Robust.Quantile(values,.99),padding=Math.Max((max-min)*.12,Math.Abs(max)*.025);
|
||||
min-=padding;max+=padding;if(Metric.Name!="Background")min=Math.Max(0,min);if(max<=min)max=min+1;
|
||||
return(min,max);
|
||||
}
|
||||
void OnPointer(object? sender,PointerPressedEventArgs e)
|
||||
{
|
||||
if(Frames.Count==0)return;var pointer=e.GetPosition(this);var(min,max)=Range();
|
||||
Frame? nearest=null;double best=double.MaxValue;
|
||||
for(int i=0;i<Frames.Count;i++)
|
||||
{
|
||||
var f=Frames[i];if(!f.Measured||f.Error!="")continue;
|
||||
double x=54+Math.Max(1,Bounds.Width-72)*i/Math.Max(1,Frames.Count-1),y=Bounds.Height-27-Math.Clamp((Metric.Value(f)-min)/Math.Max(max-min,.001),0,1)*(Bounds.Height-53);
|
||||
double distance=(x-pointer.X)*(x-pointer.X)+(y-pointer.Y)*(y-pointer.Y);if(distance<best){best=distance;nearest=f;}
|
||||
}
|
||||
if(nearest!=null)FrameClicked?.Invoke(nearest);
|
||||
}
|
||||
static void Text(DrawingContext c,string text,double x,double y,IBrush? color=null,double size=11)=>c.DrawText(new FormattedText(text,System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),size,color??Palette.Muted),new Point(x,y));
|
||||
public override void Render(DrawingContext c)
|
||||
{
|
||||
base.Render(c);double w=Bounds.Width,h=Bounds.Height,left=54,right=w-18,top=26,bottom=h-27;
|
||||
Text(c,Metric.Unit,14,7,Palette.Muted,10);
|
||||
if(Frames.Count==0){Text(c,"Analyze a folder to explore exposure quality",left,top+30);return;}
|
||||
var(min,max)=Range();
|
||||
double Y(double v)=>bottom-Math.Clamp((v-min)/Math.Max(max-min,.001),0,1)*(bottom-top);
|
||||
double X(int i)=>left+(right-left)*i/Math.Max(Frames.Count-1,1);
|
||||
for(int n=0;n<3;n++){double yy=top+n*(bottom-top)/2;c.DrawLine(new Pen(Palette.Line,.7),new(left,yy),new(right,yy));Text(c,(max-n*(max-min)/2).ToString("0.##"),4,yy-7);}
|
||||
Frame? prev=null;
|
||||
for(int i=0;i<Frames.Count;i++)
|
||||
{
|
||||
var f=Frames[i];double x=X(i);if(prev!=null&&f.Session!=prev.Session)c.DrawLine(new Pen(Palette.Muted,1,new DashStyle([2,4],0)),new(x,top),new(x,bottom));
|
||||
if(f.Measured&&f.Error=="")
|
||||
{
|
||||
if(i>0&&f.Session==prev?.Session&&f.Baselines.TryGetValue(Metric.Baseline,out double baseline)&&prev.Baselines.TryGetValue(Metric.Baseline,out double previous))c.DrawLine(new Pen(Palette.Accent,1),new(X(i-1),Y(previous)),new(x,Y(baseline)));
|
||||
c.DrawEllipse(Palette.GraphVerdict(f.Effective),null,new(x,Y(Metric.Value(f))),Selected?.Id==f.Id?4.5:2.5,Selected?.Id==f.Id?4.5:2.5);
|
||||
}
|
||||
if(Selected?.Id==f.Id)c.DrawLine(new Pen(Palette.Text,.8),new(x,top),new(x,bottom));prev=f;
|
||||
}
|
||||
Text(c,Frames[0].Time,left,bottom+7);Text(c,Frames[^1].Time,Math.Max(left,right-110),bottom+7);
|
||||
if(w>430&&Metric.Baseline!="")Text(c,"Reference",right-60,6,Palette.Accent,10);
|
||||
}
|
||||
}
|
||||
public sealed class ExposureView:Control,IDisposable
|
||||
{
|
||||
static readonly SemaphoreSlim LoadGate=new(1);
|
||||
WriteableBitmap? bitmap;
|
||||
PreviewDisplay? frameDisplay,nebulaDisplay;
|
||||
CancellationTokenSource? request;
|
||||
string message="Select an exposure";
|
||||
public Task Loading {get;private set;}=Task.CompletedTask;
|
||||
public bool HasImage=>bitmap!=null;
|
||||
public Frame? Frame {get;private set;}
|
||||
public bool Spatial {get;set;}
|
||||
public bool Nebula {get;set;}
|
||||
public double Stretch {get;set;}=.18;
|
||||
public string Caption {get;set;}="";
|
||||
public ExposureView(){RenderOptions.SetBitmapInterpolationMode(this,BitmapInterpolationMode.HighQuality);}
|
||||
public void Load(string projectDirectory,Frame? f)
|
||||
{
|
||||
Dispose();Frame=f;message=f==null?"Select an exposure":"Loading preview…";InvalidateVisual();
|
||||
if(f==null){Loading=Task.CompletedTask;return;}
|
||||
request=new();Loading=LoadCore(projectDirectory,f,request.Token);
|
||||
}
|
||||
async Task LoadCore(string directory,Frame f,CancellationToken token)
|
||||
{
|
||||
try
|
||||
{
|
||||
await LoadGate.WaitAsync(token);
|
||||
(PreviewDisplay Frame,PreviewDisplay Nebula) prepared;
|
||||
try
|
||||
{
|
||||
prepared=await Task.Run(async()=>
|
||||
{
|
||||
string path=ProjectStore.PreviewPath(directory,f);PreviewPlane? plane=null;
|
||||
var info=new FileInfo(f.Path);if(!info.Exists||info.Length!=f.Length||info.LastWriteTimeUtc.Ticks!=f.Modified)throw new IOException("Source changed; reanalyze before inspecting");
|
||||
try{if(File.Exists(path))plane=PreviewRenderer.Read(path,f);}catch(IOException){}
|
||||
if(plane==null)
|
||||
{
|
||||
await ResourcePolicy.WaitForHeadroom(ResourcePolicy.EstimateFrameBytes(f.Width,f.Height,f.Bayer!=""?2:1),token);
|
||||
var image=Fits.Read(f.Path,token);token.ThrowIfCancellationRequested();Fits.Preview(image,path,f);plane=PreviewRenderer.Read(path,f);
|
||||
}
|
||||
token.ThrowIfCancellationRequested();return(PreviewRenderer.Prepare(plane),PreviewRenderer.Prepare(plane,true));
|
||||
},token);
|
||||
}
|
||||
finally{LoadGate.Release();}
|
||||
token.ThrowIfCancellationRequested();frameDisplay=prepared.Frame;nebulaDisplay=prepared.Nebula;RefreshDisplay();
|
||||
}
|
||||
catch(OperationCanceledException){}
|
||||
catch(Exception e){if(!token.IsCancellationRequested){message="Preview unavailable: "+e.Message;InvalidateVisual();}}
|
||||
}
|
||||
public void RefreshDisplay()
|
||||
{
|
||||
var display=Nebula?nebulaDisplay:frameDisplay;if(display==null)return;
|
||||
byte[] pixels=PreviewRenderer.Render(display,Stretch);int w=display.Plane.Width,h=display.Plane.Height;bitmap?.Dispose();
|
||||
bitmap=new WriteableBitmap(new PixelSize(w,h),new Vector(96,96),PixelFormat.Bgra8888,AlphaFormat.Opaque);
|
||||
using var locked=bitmap.Lock();byte[] row=new byte[w*4];for(int y=0;y<h;y++){for(int x=0;x<w;x++){byte v=pixels[y*w+x];row[x*4]=v;row[x*4+1]=v;row[x*4+2]=v;row[x*4+3]=255;}Marshal.Copy(row,0,locked.Address+y*locked.RowBytes,row.Length);}InvalidateVisual();
|
||||
}
|
||||
public override void Render(DrawingContext c)
|
||||
{
|
||||
base.Render(c);c.FillRectangle(Palette.Background,new Rect(Bounds.Size));
|
||||
if(bitmap==null){c.DrawText(new FormattedText(message,System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),13,Palette.Muted){MaxTextWidth=Math.Max(100,Bounds.Width-32)},new(16,20));return;}
|
||||
double header=Caption!=""?26:0;
|
||||
if(header>0)c.DrawText(new FormattedText(Caption+" · "+Frame?.Time,System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),10,Palette.Muted),new(8,7));
|
||||
double scale=Math.Min(Bounds.Width/bitmap.PixelSize.Width,Math.Max(1,Bounds.Height-header)/bitmap.PixelSize.Height),w=bitmap.PixelSize.Width*scale,h=bitmap.PixelSize.Height*scale;var rect=new Rect((Bounds.Width-w)/2,header+(Bounds.Height-header-h)/2,w,h);c.DrawImage(bitmap,new Rect(bitmap.Size),rect);
|
||||
if(Spatial&&Frame!=null&&Frame.Alignment.Length==4)
|
||||
{
|
||||
var f=Frame;double aspect=(double)f.Height/f.Width;var a=f.Alignment;
|
||||
Point Map(double x,double y)=>new(rect.X+(a[0]*x-a[1]*y*aspect+a[2])*w,rect.Y+(a[1]*x+a[0]*y*aspect+a[3])/aspect*h);
|
||||
using(c.PushClip(rect))
|
||||
{
|
||||
StreamGeometry Cell(double x,double y,double dx,double dy)
|
||||
{var geometry=new StreamGeometry();using(var g=geometry.Open()){g.BeginFigure(Map(x,y),true);g.LineTo(Map(x+dx,y));g.LineTo(Map(x+dx,y+dy));g.LineTo(Map(x,y+dy));g.EndFigure(true);}return geometry;}
|
||||
if(f.CloudMask.Length==SkyModel.Count)for(int i=0;i<SkyModel.Count;i++)if(f.CloudMask[i]>0)
|
||||
c.DrawGeometry(new SolidColorBrush(Color.FromArgb(85,245,142,155)),null,Cell((double)(i%SkyModel.Columns)/SkyModel.Columns,(double)(i/SkyModel.Columns)/SkyModel.Rows,1.0/SkyModel.Columns,1.0/SkyModel.Rows));
|
||||
for(int i=0;i<12;i++)
|
||||
{
|
||||
double baseline=f.Baselines.GetValueOrDefault($"Region {i+1}"),ratio=baseline>0?f.RegionFlux[i]/baseline:1;
|
||||
var brush=f.RegionMatches[i]<5?Palette.Muted:ratio<.65?Palette.Reject:Palette.Keep;
|
||||
c.DrawGeometry(null,new Pen(brush,.7),Cell((i%3)/3.0,(i/3)/4.0,1/3.0,.25));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public void Dispose(){request?.Cancel();request?.Dispose();request=null;bitmap?.Dispose();bitmap=null;frameDisplay=nebulaDisplay=null;}
|
||||
}
|
||||
9
src/AstroFrame.Engine/AstroFrame.Engine.csproj
Normal file
9
src/AstroFrame.Engine/AstroFrame.Engine.csproj
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
93
src/AstroFrame.Engine/Classification.cs
Normal file
93
src/AstroFrame.Engine/Classification.cs
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
namespace AstroFrame.Engine;
|
||||
public static class Classification
|
||||
{
|
||||
public static void Sessions(List<Frame> frames)
|
||||
{
|
||||
foreach(var group in frames.GroupBy(f=>$"{f.Target}|{f.Instrument}|{f.Filter}|{f.Gain}|{f.Exposure}|{f.Width}x{f.Height}|{f.Bayer}"))
|
||||
{
|
||||
string label="";DateTime? previous=null;Frame? previousFrame=null;int segment=0;
|
||||
foreach(var f in group.OrderBy(f=>f.Timestamp).ThenBy(f=>f.Path))
|
||||
{
|
||||
if(previous==null||f.Timestamp==null||f.Timestamp-previous>TimeSpan.FromHours(2)||previousFrame!=null&&(Math.Abs(f.Ra-previousFrame.Ra)>.3||Math.Abs(f.Dec-previousFrame.Dec)>.3))label=$"{f.Target} · {f.Timestamp?.ToString("yyyy-MM-dd HH:mm")??"unknown"} · {++segment} · {f.Filter}";
|
||||
f.Session=label;previous=f.Timestamp;previousFrame=f;
|
||||
}
|
||||
}
|
||||
}
|
||||
public static void Run(List<Frame> frames,CancellationToken ct=default)
|
||||
{
|
||||
Sessions(frames);
|
||||
foreach(var session in frames.GroupBy(f=>f.Session))
|
||||
{
|
||||
var a=session.Where(f=>f.Measured&&f.Error=="").OrderBy(f=>f.Timestamp).ToArray();if(a.Length==0)continue;
|
||||
// Catalog-only callers cannot claim spatial evidence.
|
||||
bool spatial=a.Any(f=>f.SkyMap.Length==SkyModel.Count||f.CloudMask.Length==SkyModel.Count);
|
||||
if(!spatial)
|
||||
{
|
||||
var reference=a.OrderBy(f=>Math.Abs(f.StarCount-Robust.Median(a.Select(x=>(double)x.StarCount)))).First();
|
||||
foreach(var f in a)Matching.Measure(reference,f);
|
||||
}
|
||||
var clear=a.Where(f=>spatial?f.AdditionalMeasurements.GetValueOrDefault("Clear reference member")>0&&f.CloudSignificance<5:f.Transparency>=Robust.Quantile(a.Select(x=>x.Transparency),.5)*.8).ToArray();
|
||||
for(int i=0;i<a.Length;i++)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();var f=a[i];f.Evidence=[];f.Baselines=[];
|
||||
var local=clear.Where(x=>x.Id!=f.Id).OrderBy(x=>Math.Abs((x.Timestamp.GetValueOrDefault()-f.Timestamp.GetValueOrDefault()).TotalSeconds)).Take(40).ToArray();
|
||||
bool reliable=a.Length>=20&&local.Length>=12&&f.Timestamp!=null&&(!spatial||f.ReferenceConfidence>.6);
|
||||
double Metric(string name,Func<Frame,double> get,bool low,double floor)
|
||||
{
|
||||
var values=local.Select(get).Where(x=>x>0&&double.IsFinite(x)).ToArray();double normal=Robust.Median(values),value=get(f),spread=Math.Max(Robust.Mad(values),Math.Abs(normal)*floor);
|
||||
f.Baselines[name]=normal;return normal>0?(low?normal-value:value-normal)/Math.Max(spread,.0001):0;
|
||||
}
|
||||
double countZ=Metric("Star count",x=>x.StarCount,true,.10),fluxZ=Metric("Stellar flux",x=>x.Transparency,true,.06),widthZ=Metric("FWHM",x=>x.Fwhm,false,.08),shapeZ=Metric("Ellipticity",x=>x.Ellipticity,false,.15),bgZ=Metric("Background",x=>x.Background,false,.06),noiseZ=Metric("Noise",x=>x.Noise,false,.08);
|
||||
Metric("Background variation",x=>x.BackgroundVariation,false,.20);
|
||||
double Ratio(string key,double value)=>value/Math.Max(f.Baselines.GetValueOrDefault(key),.00001);
|
||||
double countRatio=Ratio("Star count",f.StarCount),fluxRatio=Ratio("Stellar flux",f.Transparency),widthRatio=Ratio("FWHM",f.Fwhm);
|
||||
double connected=f.AdditionalMeasurements.GetValueOrDefault("Cloud connected coverage");
|
||||
// A single sky detector must be overwhelming to discard integration on its own.
|
||||
// Smaller coherent changes remain REVIEW unless stellar measurements corroborate them.
|
||||
bool strongStructure=spatial&&f.CloudSignificance>=25&&f.CloudCoverage>=.08&&connected>=.035;
|
||||
bool moderateStructure=spatial&&f.CloudSignificance>=5&&f.CloudCoverage>=.02&&connected>=.01;
|
||||
bool fluxLoss=fluxZ>=4&&fluxRatio<.78,starLoss=countZ>=3&&countRatio<.75;
|
||||
bool strongFlux=fluxZ>=5&&fluxRatio<.60&&starLoss;
|
||||
bool regionLoss=false;
|
||||
for(int r=0;r<12;r++)
|
||||
{
|
||||
var peers=local.Where(x=>x.RegionMatches[r]>=5&&x.RegionFlux[r]>0).ToArray();if(peers.Length<8||f.RegionMatches[r]<5)continue;
|
||||
double normal=Robust.Median(peers.Select(x=>x.RegionFlux[r]));f.Baselines[$"Region {r+1}"]=normal;
|
||||
double z=(normal-f.RegionFlux[r])/Math.Max(Robust.Mad(peers.Select(x=>x.RegionFlux[r])),normal*.10);
|
||||
if(z>=4&&f.RegionFlux[r]<normal*.65)
|
||||
{
|
||||
regionLoss=true;f.Evidence.Add(new($"Region {r+1}",f.RegionFlux[r],normal,z,$"{RegionName(r)}: forced stellar flux {f.RegionFlux[r]/normal:P0} of clear-frame baseline ({f.RegionMatches[r]} reference apertures, including undetected stars)"));
|
||||
}
|
||||
}
|
||||
if(moderateStructure||strongStructure)
|
||||
{
|
||||
int[] areas=new int[12];for(int cell=0;cell<f.CloudMask.Length;cell++)if(f.CloudMask[cell]>0)areas[cell/SkyModel.Columns/(SkyModel.Rows/4)*3+cell%SkyModel.Columns/(SkyModel.Columns/3)]++;
|
||||
int strongest=Array.IndexOf(areas,areas.Max());
|
||||
f.Evidence.Add(new("Cloud structure",f.CloudCoverage,0,f.CloudSignificance,$"Transient sky structure covers {f.CloudCoverage:P0} of the aligned overlap, strongest in {RegionName(strongest).ToLowerInvariant()}; largest connected area {connected:P0}, residual {f.AdditionalMeasurements.GetValueOrDefault("Sky residual ADU"):0.0} ADU ({f.CloudSignificance:0.0} × reference scatter). Offset and smooth gradient removed; compared with {f.AdditionalMeasurements.GetValueOrDefault("Reference frames"):0} reference exposures."));
|
||||
}
|
||||
if(fluxLoss)f.Evidence.Add(new("Stellar flux",f.Transparency,f.Baselines["Stellar flux"],fluxZ,$"Forced stellar flux reduced to {fluxRatio:P0} of nearby clear-frame baseline; lost detections remain in the measurement"));
|
||||
if(starLoss)f.Evidence.Add(new("Star count",f.StarCount,f.Baselines["Star count"],countZ,$"Detected stars reduced to {countRatio:P0} of clear-frame baseline"));
|
||||
bool widthBad=widthZ>4&&widthRatio>1.25,shapeBad=shapeZ>4&&f.Ellipticity>f.Baselines["Ellipticity"]+.15;
|
||||
if(widthBad)f.Evidence.Add(new("FWHM",f.Fwhm,f.Baselines["FWHM"],widthZ,$"Stellar width {widthRatio:0.00} × clear-frame baseline"));
|
||||
if(shapeBad)f.Evidence.Add(new("Ellipticity",f.Ellipticity,f.Baselines["Ellipticity"],shapeZ,$"Substantial stellar elongation ({f.Ellipticity:0.00} vs {f.Baselines["Ellipticity"]:0.00})"));
|
||||
bool optics=widthBad&&shapeBad&&widthRatio>1.65;
|
||||
bool catastrophic=f.StarCount<3&&f.Baselines["Star count"]>50;
|
||||
bool cloud=strongStructure||moderateStructure&&(fluxLoss||regionLoss||starLoss)||strongFlux;
|
||||
bool weak=f.MatchFraction<.35||f.Transparency<=0||f.Fwhm<=0||(spatial&&f.AdditionalMeasurements.GetValueOrDefault("Forced flux samples")<20);
|
||||
bool skyNoise=bgZ>5&&noiseZ>4&&Ratio("Background",f.Background)>1.4;
|
||||
if(skyNoise)f.Evidence.Add(new("Sky noise",f.Noise,f.Baselines["Noise"],noiseZ,"Background and sky noise are substantially above the clear-frame baseline"));
|
||||
bool suspicious=moderateStructure||fluxLoss||regionLoss||widthBad||shapeBad||skyNoise||starLoss;
|
||||
f.Automatic=reliable&&(catastrophic||!weak&&(cloud||optics))?Verdict.Reject:!reliable||weak||suspicious||f.Warning!=""?Verdict.Review:Verdict.Keep;
|
||||
f.Cause=!reliable?"Insufficient reliable session reference":catastrophic?"Severe disappearance of reference stars":weak?"Uncertain alignment / reference photometry":cloud?"Likely cloud / transparency loss":optics?"Likely tracking or focus failure":suspicious?"Quality change needs review":"Consistent with the clean session reference";
|
||||
if(!reliable)f.Evidence.Add(new("Reference",local.Length,12,0,"Automatic rejection disabled: insufficient clear comparison frames, timestamp or aligned overlap"));
|
||||
if(weak)f.Evidence.Add(new("Matching",f.MatchFraction,.35,0,"Uncertain star alignment or reference aperture coverage; inspect manually"));
|
||||
if(f.Warning!="")f.Evidence.Add(new("Metadata",0,0,0,f.Warning));
|
||||
if(!widthBad)f.Evidence.Add(new("FWHM",f.Fwhm,f.Baselines["FWHM"],0,"Stellar width is within the practical tolerance of nearby clear frames"));
|
||||
if(f.Evidence.Count==1)f.Evidence.Add(new("Reference",f.Transparency,f.Baselines["Stellar flux"],0,"Aligned sky structure, stellar flux and morphology show no substantial degradation"));
|
||||
f.Score=Math.Clamp(100-4*Math.Max(0,f.CloudSignificance)-25*Math.Max(0,1-fluxRatio)-10*Math.Max(0,widthRatio-1),0,100);
|
||||
}
|
||||
}
|
||||
foreach(var f in frames.Where(f=>f.Error!="")){f.Automatic=Verdict.Review;f.Cause="Unreadable or unsupported FITS";f.Evidence=[new("Read error",0,0,0,f.Error)];}
|
||||
}
|
||||
public static string RegionName(int i)=>new[]{"Upper","Upper-middle","Lower-middle","Lower"}[i/3]+" "+new[]{"left","center","right"}[i%3];
|
||||
}
|
||||
53
src/AstroFrame.Engine/Export.cs
Normal file
53
src/AstroFrame.Engine/Export.cs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
namespace AstroFrame.Engine;
|
||||
public static class Export
|
||||
{
|
||||
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)]static extern bool CreateHardLink(string destination,string source,IntPtr reserved);
|
||||
[DllImport("libc",SetLastError=true)]static extern int link(string source,string destination);
|
||||
public static bool Hardlink(string source,string destination)=>OperatingSystem.IsWindows()?CreateHardLink(destination,source,IntPtr.Zero):link(source,destination)==0;
|
||||
static string Csv(string s)=>"\""+s.Replace("\"","\"\"")+"\"";
|
||||
public static string Manifest(Project p)
|
||||
{
|
||||
var b=new StringBuilder("source,target,session,timestamp,exposure_seconds,automatic,manual,effective,cause,note,cloud_area_fraction,cloud_significance,forced_flux,reference_overlap,engine_version\n");
|
||||
string Number(double value)=>value.ToString("G6",System.Globalization.CultureInfo.InvariantCulture);
|
||||
foreach(var f in p.Frames)b.AppendLine(string.Join(',',new[]{f.Path,f.Target,f.Session,f.Timestamp?.ToString("O")??"",Number(f.Exposure),f.Automatic.ToString(),f.Override?.ToString()??"",f.Effective.ToString(),f.Cause,f.Note,Number(f.CloudCoverage),Number(f.CloudSignificance),Number(f.Transparency),Number(f.AdditionalMeasurements.GetValueOrDefault("Reference overlap")),p.Version}.Select(Csv)));
|
||||
return b.ToString();
|
||||
}
|
||||
public static async Task<(int Linked,int Copied)> AcceptedAsync(Project p,string output,bool includeReview,bool hardlinks,IProgress<ProgressInfo>? progress,CancellationToken ct)
|
||||
{
|
||||
if(!p.Complete)throw new InvalidOperationException("Complete analysis before exporting accepted lights");
|
||||
string full=System.IO.Path.GetFullPath(output),source=System.IO.Path.GetFullPath(p.Source);
|
||||
if(full.Equals(source,StringComparison.OrdinalIgnoreCase)||full.StartsWith(source+System.IO.Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase))throw new InvalidOperationException("Choose an export folder outside the input tree");
|
||||
if(Directory.Exists(full)&&Directory.EnumerateFileSystemEntries(full).Any())throw new InvalidOperationException("Choose an empty export folder");
|
||||
var accepted=p.Frames.Where(f=>f.Error==""&&(f.Effective==Verdict.Keep||includeReview&&f.Effective==Verdict.Review)).ToArray();
|
||||
if(accepted.Length==0)throw new InvalidOperationException("No accepted readable frames");
|
||||
// Verify all sources before creating any output; originals are always opened read-only.
|
||||
foreach(var f in accepted){var info=new FileInfo(f.Path);if(!info.Exists||info.Length!=f.Length||info.LastWriteTimeUtc.Ticks!=f.Modified)throw new IOException("Source changed since analysis: "+f.Name);}
|
||||
Directory.CreateDirectory(full);int linked=0,copied=0;
|
||||
var targets=accepted.Select(f=>f.Target).Distinct().ToArray();Dictionary<string,string> targetFolders=[];
|
||||
if(targets.Length>1)foreach(string target in targets)
|
||||
{
|
||||
string name=System.Text.RegularExpressions.Regex.Replace(target,"[^\\p{L}\\p{N} _.-]","_").Trim('.',' ');if(name=="")name="Target";
|
||||
if(targetFolders.Values.Contains(name,StringComparer.OrdinalIgnoreCase))name+="_"+Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(target)))[..6];targetFolders[target]=name;
|
||||
}
|
||||
string Destination(Frame f,int i)=>System.IO.Path.Combine(full,targetFolders.GetValueOrDefault(f.Target,""),$"{i+1:000000}_{f.Name}");
|
||||
await Task.Run(()=>
|
||||
{
|
||||
for(int i=0;i<accepted.Length;i++)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();var f=accepted[i];string dest=Destination(f,i);Directory.CreateDirectory(System.IO.Path.GetDirectoryName(dest)!);
|
||||
if(hardlinks&&Hardlink(f.Path,dest))linked++;else
|
||||
{
|
||||
string tmp=dest+".partial";
|
||||
try {using var src=new FileStream(f.Path,FileMode.Open,FileAccess.Read,FileShare.Read);using(var dst=new FileStream(tmp,FileMode.CreateNew,FileAccess.Write)){byte[] buffer=new byte[1024*1024];int n;while((n=src.Read(buffer))>0){ct.ThrowIfCancellationRequested();dst.Write(buffer,0,n);}}File.Move(tmp,dest);copied++;}
|
||||
finally{if(File.Exists(tmp))File.Delete(tmp);}
|
||||
}
|
||||
progress?.Report(new(i+1,accepted.Length,"Exporting accepted lights",f.Name));
|
||||
}
|
||||
File.WriteAllText(System.IO.Path.Combine(full,"decisions.csv"),Manifest(p));
|
||||
File.WriteAllLines(System.IO.Path.Combine(full,"accepted.txt"),accepted.Select(Destination));
|
||||
},ct);
|
||||
return(linked,copied);
|
||||
}
|
||||
}
|
||||
70
src/AstroFrame.Engine/Fits.cs
Normal file
70
src/AstroFrame.Engine/Fits.cs
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
using System.Buffers.Binary;
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace AstroFrame.Engine;
|
||||
public sealed record ImagePlane(int Width,int Height,float[] Pixels,int Scale);
|
||||
public static class Fits
|
||||
{
|
||||
public static (Dictionary<string,string> Header,long Offset) ReadHeader(Stream stream)
|
||||
{
|
||||
Dictionary<string,string> h=[];byte[] block=new byte[2880];
|
||||
for(int n=0;n<1024;n++)
|
||||
{
|
||||
stream.ReadExactly(block);
|
||||
for(int i=0;i<2880;i+=80)
|
||||
{
|
||||
string card=Encoding.ASCII.GetString(block,i,80),key=card[..8].Trim();
|
||||
if(key=="END")return(h,stream.Position);
|
||||
if(card[8]!='=')continue;
|
||||
string v=card[10..].Trim();
|
||||
if(v.StartsWith('\'')) { int end=v.IndexOf('\'',1);v=end>0?v[1..end].Trim():v.Trim('\''); }
|
||||
else v=v.Split('/')[0].Trim();
|
||||
h[key]=v;
|
||||
}
|
||||
}
|
||||
throw new InvalidDataException("FITS header exceeds supported size");
|
||||
}
|
||||
static double Number(Dictionary<string,string> h,string key,double fallback=0)=>h.TryGetValue(key,out var v)&&double.TryParse(v.Replace('D','E'),NumberStyles.Float,CultureInfo.InvariantCulture,out double d)?d:fallback;
|
||||
public static Frame Inspect(string path)
|
||||
{
|
||||
FileInfo fi=new(path);using var s=File.OpenRead(path);var(h,_)=ReadHeader(s);
|
||||
string Get(string k,string fallback="")=>h.GetValueOrDefault(k,fallback);
|
||||
DateTime? time=DateTime.TryParse(Get("DATE-OBS"),CultureInfo.InvariantCulture,DateTimeStyles.AssumeUniversal|DateTimeStyles.AdjustToUniversal,out var t)?t:null;
|
||||
var f=new Frame{Path=fi.FullName,Id=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(fi.FullName)))[..24],Length=fi.Length,Modified=fi.LastWriteTimeUtc.Ticks,
|
||||
Target=Get("OBJECT",fi.Directory?.Name??"Unknown"),Instrument=Get("CREATOR",Get("INSTRUME")),Filter=Get("FILTER"),Gain=Get("GAIN"),Bayer=Get("BAYERPAT"),Timestamp=time,
|
||||
Exposure=Number(h,"EXPTIME",Number(h,"EXPOSURE")),Width=(int)Number(h,"NAXIS1"),Height=(int)Number(h,"NAXIS2"),Ra=Number(h,"RA"),Dec=Number(h,"DEC")};
|
||||
if(Get("IMAGETYP","Light").Contains("Light",StringComparison.OrdinalIgnoreCase)==false)throw new InvalidDataException("Not a light frame");
|
||||
if(time==null)f.Warning="Missing FITS timestamp; session baseline is uncertain";
|
||||
return f;
|
||||
}
|
||||
public static ImagePlane Read(string path,CancellationToken ct=default)
|
||||
{
|
||||
using var s=File.OpenRead(path);var(h,_)=ReadHeader(s);
|
||||
int w=(int)Number(h,"NAXIS1"),height=(int)Number(h,"NAXIS2"),bit=(int)Number(h,"BITPIX"),axes=(int)Number(h,"NAXIS");
|
||||
if(axes!=2 || w<32 || height<32 || (long)w*height>100_000_000)throw new InvalidDataException("Only 2D primary FITS images up to 100 MP are supported");
|
||||
if(bit is not (8 or 16 or 32 or -32 or -64))throw new InvalidDataException("Unsupported FITS BITPIX");
|
||||
int b=Math.Abs(bit)/8,scale=h.ContainsKey("BAYERPAT")?2:1,ow=w/scale,oh=height/scale;
|
||||
ResourcePolicy.CheckFrame(w,height,scale);
|
||||
if(s.Length-s.Position<(long)w*height*b)throw new InvalidDataException("Truncated FITS pixels");
|
||||
double zero=Number(h,"BZERO"),factor=Number(h,"BSCALE",1);float[] pixels=new float[ow*oh];byte[] rows=new byte[w*b*scale];
|
||||
for(int y=0;y<oh;y++)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();s.ReadExactly(rows);
|
||||
for(int x=0;x<ow;x++)
|
||||
{
|
||||
double sum=0;
|
||||
for(int dy=0;dy<scale;dy++)for(int dx=0;dx<scale;dx++)
|
||||
{
|
||||
var span=rows.AsSpan(((dy*w)+(x*scale+dx))*b,b);
|
||||
double v=bit switch{8=>span[0],16=>BinaryPrimitives.ReadInt16BigEndian(span),32=>BinaryPrimitives.ReadInt32BigEndian(span),-32=>BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32BigEndian(span)),_=>BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64BigEndian(span))};
|
||||
sum+=v*factor+zero;
|
||||
}
|
||||
float value=(float)(sum/(scale*scale));if(!float.IsFinite(value))throw new InvalidDataException("Nonfinite image pixels");pixels[y*ow+x]=value;
|
||||
}
|
||||
}
|
||||
return new(ow,oh,pixels,scale);
|
||||
}
|
||||
public static void Preview(ImagePlane image,string path,Frame? frame=null)=>PreviewRenderer.Write(image,path,frame);
|
||||
}
|
||||
101
src/AstroFrame.Engine/Matching.cs
Normal file
101
src/AstroFrame.Engine/Matching.cs
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
namespace AstroFrame.Engine;
|
||||
public sealed record Transform(double A,double B,double Tx,double Ty)
|
||||
{
|
||||
public (double X,double Y) Apply(double x,double y)=>(A*x-B*y+Tx,B*x+A*y+Ty);
|
||||
}
|
||||
public static class Matching
|
||||
{
|
||||
const double Cell=.005;
|
||||
sealed class Grid
|
||||
{
|
||||
readonly Dictionary<(int,int),List<Star>> cells=[];
|
||||
readonly double aspect;
|
||||
public Grid(IEnumerable<Star> stars,double aspect)
|
||||
{this.aspect=aspect;foreach(var s in stars){var k=((int)(s.X/Cell),(int)(s.Y*aspect/Cell));if(!cells.TryGetValue(k,out var a))cells[k]=a=[];a.Add(s);}}
|
||||
public Star? Nearest(double x,double y)
|
||||
{
|
||||
int cx=(int)(x/Cell),cy=(int)(y/Cell);Star? best=null;double dist=Cell*Cell;
|
||||
for(int dx=-1;dx<=1;dx++)for(int dy=-1;dy<=1;dy++)if(cells.TryGetValue((cx+dx,cy+dy),out var a))foreach(var s in a){double d=(s.X-x)*(s.X-x)+(s.Y*aspect-y)*(s.Y*aspect-y);if(d<dist){dist=d;best=s;}}
|
||||
return best;
|
||||
}
|
||||
}
|
||||
public static Transform? Align(Frame reference,Frame frame)
|
||||
{
|
||||
if(reference.Id==frame.Id)return new(1,0,0,0);
|
||||
double aspect=(double)reference.Height/reference.Width;
|
||||
var refs=reference.Stars.Take(16).ToArray();var observed=frame.Stars.Take(28).ToArray();
|
||||
if(refs.Length<8||observed.Length<8)return null;
|
||||
var grid=new Grid(frame.Stars.Take(400),aspect);Transform? best=null;int bestN=0;
|
||||
for(int i=0;i<refs.Length;i++)for(int j=i+1;j<refs.Length;j++)
|
||||
{
|
||||
double rx=refs[j].X-refs[i].X,ry=(refs[j].Y-refs[i].Y)*aspect,rd=rx*rx+ry*ry;if(rd<.02)continue;
|
||||
for(int k=0;k<observed.Length;k++)for(int l=0;l<observed.Length;l++)
|
||||
{
|
||||
if(k==l)continue;double ox=observed[l].X-observed[k].X,oy=(observed[l].Y-observed[k].Y)*aspect,ratio=(ox*ox+oy*oy)/rd;
|
||||
if(Math.Abs(ratio-1)>.025)continue;
|
||||
double a=(rx*ox+ry*oy)/rd,b=(rx*oy-ry*ox)/rd;
|
||||
var tr=new Transform(a,b,observed[k].X-a*refs[i].X+b*refs[i].Y*aspect,observed[k].Y*aspect-b*refs[i].X-a*refs[i].Y*aspect);
|
||||
int n=0;foreach(var star in refs){var(x,y)=tr.Apply(star.X,star.Y*aspect);if(grid.Nearest(x,y)!=null)n++;}
|
||||
if(n>bestN){bestN=n;best=tr;}
|
||||
if(n>=refs.Length-1)return Refine(reference,frame,tr);
|
||||
}
|
||||
}
|
||||
return bestN>=Math.Max(7,refs.Length*.5)&&best!=null?Refine(reference,frame,best):null;
|
||||
}
|
||||
static Transform Refine(Frame reference,Frame frame,Transform tr)
|
||||
{
|
||||
double aspect=(double)reference.Height/reference.Width;var grid=new Grid(frame.Stars,aspect);
|
||||
for(int iteration=0;iteration<4;iteration++)
|
||||
{
|
||||
List<(double X,double Y,double U,double V)> pairs=[];HashSet<Star> used=[];
|
||||
foreach(var s in reference.Stars.Take(400))
|
||||
{
|
||||
var(x,y)=tr.Apply(s.X,s.Y*aspect);var other=grid.Nearest(x,y);
|
||||
if(other!=null&&used.Add(other))pairs.Add((s.X,s.Y*aspect,other.X,other.Y*aspect));
|
||||
}
|
||||
if(pairs.Count<12)break;
|
||||
double x0=pairs.Average(p=>p.X),y0=pairs.Average(p=>p.Y),u0=pairs.Average(p=>p.U),v0=pairs.Average(p=>p.V);
|
||||
double d=pairs.Sum(p=>(p.X-x0)*(p.X-x0)+(p.Y-y0)*(p.Y-y0));if(d<=0)break;
|
||||
double a=pairs.Sum(p=>(p.X-x0)*(p.U-u0)+(p.Y-y0)*(p.V-v0))/d,b=pairs.Sum(p=>(p.X-x0)*(p.V-v0)-(p.Y-y0)*(p.U-u0))/d;
|
||||
tr=new(a,b,u0-a*x0+b*y0,v0-b*x0-a*y0);
|
||||
}
|
||||
return tr;
|
||||
}
|
||||
public static double[] ForcedFlux(Frame reference,Frame frame,ImagePlane image)
|
||||
{
|
||||
var stars=reference.Stars.Take(600).ToArray();double[] flux=Enumerable.Repeat(double.NaN,stars.Length).ToArray();
|
||||
if(frame.Alignment.Length!=4)return flux;
|
||||
double aspect=(double)reference.Height/reference.Width;var a=frame.Alignment;var p=image.Pixels;int w=image.Width,h=image.Height;
|
||||
for(int j=0;j<stars.Length;j++)
|
||||
{
|
||||
var s=stars[j];int x=(int)Math.Round((a[0]*s.X-a[1]*s.Y*aspect+a[2])*w),y=(int)Math.Round((a[1]*s.X+a[0]*s.Y*aspect+a[3])/aspect*h);
|
||||
if(x<10||y<10||x>=w-10||y>=h-10)continue;
|
||||
List<double> annulus=[];for(int dy=-8;dy<=8;dy++)for(int dx=-8;dx<=8;dx++)if(dx*dx+dy*dy>=36&&dx*dx+dy*dy<=64)annulus.Add(p[(y+dy)*w+x+dx]);
|
||||
double bg=Robust.Median(annulus),sum=0;bool saturated=false;
|
||||
for(int dy=-4;dy<=4;dy++)for(int dx=-4;dx<=4;dx++)if(dx*dx+dy*dy<=16){double value=p[(y+dy)*w+x+dx];sum+=value-bg;saturated|=value>=64000;}
|
||||
if(!saturated)flux[j]=sum/Math.Max(1,frame.Exposure);
|
||||
}
|
||||
return flux;
|
||||
}
|
||||
public static void Measure(Frame reference,Frame frame)
|
||||
{
|
||||
frame.Transparency=0;frame.MatchFraction=0;frame.RegionFlux=new double[12];frame.RegionLoss=new double[12];frame.RegionMatches=new int[12];
|
||||
frame.Alignment=[];frame.ReferenceId=reference.Id;
|
||||
var tr=Align(reference,frame);if(tr==null)return;
|
||||
frame.Alignment=[tr.A,tr.B,tr.Tx,tr.Ty];
|
||||
double aspect=(double)reference.Height/reference.Width;var grid=new Grid(frame.Stars,aspect);
|
||||
List<double> ratios=[];List<double>[] regional=Enumerable.Range(0,12).Select(_=>new List<double>()).ToArray();int[] expected=new int[12],found=new int[12];HashSet<Star> used=[];
|
||||
foreach(var s in reference.Stars.Take(600))
|
||||
{
|
||||
var(x,y)=tr.Apply(s.X,s.Y*aspect);y/=aspect;
|
||||
if(x<.025||x>.975||y<.025||y>.975)continue;
|
||||
int region=Math.Clamp((int)(s.Y*4),0,3)*3+Math.Clamp((int)(s.X*3),0,2);expected[region]++;
|
||||
var other=grid.Nearest(x,y*aspect);if(other==null||!used.Add(other))continue;found[region]++;
|
||||
double ratio=other.Flux/Math.Max(s.Flux,.001);if(double.IsFinite(ratio)&&ratio>0){ratios.Add(ratio);regional[region].Add(ratio);}
|
||||
}
|
||||
frame.MatchFraction=(double)found.Sum()/Math.Max(expected.Sum(),1);
|
||||
if(ratios.Count>=15)frame.Transparency=Robust.Median(ratios);
|
||||
for(int i=0;i<12;i++){frame.RegionMatches[i]=regional[i].Count;frame.RegionLoss[i]=expected[i]>=8?1-(double)found[i]/expected[i]:0;frame.RegionFlux[i]=regional[i].Count>=5?Robust.Median(regional[i]):0;}
|
||||
frame.SpatialLoss=frame.RegionLoss.Max();
|
||||
}
|
||||
}
|
||||
56
src/AstroFrame.Engine/Measurements.cs
Normal file
56
src/AstroFrame.Engine/Measurements.cs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
namespace AstroFrame.Engine;
|
||||
|
||||
/// <summary>Deterministic superpixel photometry. Widths are moment estimates, not Siril PSF fits.</summary>
|
||||
public sealed class StellarDetector:IFrameDetector
|
||||
{
|
||||
public string Name=>"Local-sky stellar measurements v2";
|
||||
public void Measure(Frame f,ImagePlane image,CancellationToken ct)
|
||||
{
|
||||
int w=image.Width,h=image.Height;var p=image.Pixels;
|
||||
SkyModel.Measure(f,image,ct);f.CacheDirty=true;
|
||||
List<Region> tiles=[];
|
||||
for(int row=0;row<4;row++)for(int col=0;col<3;col++)
|
||||
{
|
||||
List<double> values=[],diff=[];
|
||||
for(int y=row*h/4+2;y<(row+1)*h/4-2;y+=5)for(int x=col*w/3+2;x<(col+1)*w/3-2;x+=5){values.Add(p[y*w+x]);diff.Add(Math.Abs(p[y*w+x]-p[y*w+x+1]));}
|
||||
tiles.Add(new(Robust.Median(values),Math.Max(.001,Robust.Median(diff)/.953872),0));
|
||||
}
|
||||
f.Background=Robust.Median(tiles.Select(t=>t.Background));f.Noise=Robust.Median(tiles.Select(t=>t.Noise));f.BackgroundVariation=Robust.Mad(tiles.Select(t=>t.Background));
|
||||
float[] smooth=new float[p.Length];
|
||||
for(int y=1;y<h-1;y++)for(int x=1;x<w-1;x++)
|
||||
{int i=y*w+x;smooth[i]=(p[i]*4+(p[i-1]+p[i+1]+p[i-w]+p[i+w])*2+p[i-w-1]+p[i-w+1]+p[i+w-1]+p[i+w+1])/16;}
|
||||
// Kernel reduces white-noise sigma by 0.375. Require 7 sigma plus shape checks.
|
||||
List<Star> stars=[];int[] counts=new int[12];
|
||||
for(int y=8;y<h-8;y++)
|
||||
{
|
||||
if(y%64==0)ct.ThrowIfCancellationRequested();
|
||||
for(int x=8;x<w-8;x++)
|
||||
{
|
||||
int i=y*w+x,tile=Math.Min(3,y*4/h)*3+Math.Min(2,x*3/w);var r=tiles[tile];double peak=smooth[i];
|
||||
double localBackground=SkyModel.Sample(f.SkyMap,(double)x/w,(double)y/h),localNoise=SkyModel.Sample(f.SkyNoise,(double)x/w,(double)y/h);
|
||||
if(peak<localBackground+7*.375*localNoise)continue;
|
||||
bool maximum=true;for(int dy=-2;dy<=2&&maximum;dy++)for(int dx=-2;dx<=2;dx++)if((dx!=0||dy!=0)&&smooth[i+dy*w+dx]>=peak){maximum=false;break;}
|
||||
if(!maximum)continue;
|
||||
List<double> annulus=[];for(int dy=-6;dy<=6;dy++)for(int dx=-6;dx<=6;dx++)if(dx*dx+dy*dy>=25&&dx*dx+dy*dy<=36)annulus.Add(p[i+dy*w+dx]);
|
||||
double bg=Robust.Median(annulus),sum=0,mx=0,my=0,xx=0,yy=0,xy=0;
|
||||
// A peak on diffuse cloud structure is not a star above its own local sky.
|
||||
if(peak-bg<7*.375*localNoise)continue;
|
||||
// Positive core weighting is used only for morphology, signed sum for photometry.
|
||||
double flux=0;for(int dy=-4;dy<=4;dy++)for(int dx=-4;dx<=4;dx++)
|
||||
{if(dx*dx+dy*dy>16)continue;double v=p[i+dy*w+dx]-bg;flux+=v;double weight=Math.Max(0,v-r.Noise);sum+=weight;mx+=dx*weight;my+=dy*weight;xx+=dx*dx*weight;yy+=dy*dy*weight;xy+=dx*dy*weight;}
|
||||
if(sum<=0||flux<12*localNoise||p[i]>=64000)continue;
|
||||
mx/=sum;my/=sum;xx=xx/sum-mx*mx;yy=yy/sum-my*my;xy=xy/sum-mx*my;
|
||||
double d=Math.Sqrt((xx-yy)*(xx-yy)+4*xy*xy),major=(xx+yy+d)/2,minor=(xx+yy-d)/2;
|
||||
if(minor<.18||major>12||Math.Abs(mx)>2||Math.Abs(my)>2)continue; // remove impulses and unstable centroids
|
||||
double fwhm=2.35482*Math.Sqrt((major+minor)/2)*image.Scale,ellip=1-Math.Sqrt(minor/major);
|
||||
stars.Add(new((x+mx)/w,(y+my)/h,flux/Math.Max(f.Exposure,1),fwhm,ellip));counts[tile]++;
|
||||
}
|
||||
}
|
||||
f.StarCount=stars.Count;
|
||||
// Stronger, isolated stars provide more stable moments and matching than threshold detections.
|
||||
var strong=stars.OrderByDescending(s=>s.Flux).Take(250).ToList();
|
||||
f.Fwhm=Robust.Median(strong.Select(s=>s.Fwhm));f.Ellipticity=Robust.Median(strong.Select(s=>s.Ellipticity));
|
||||
f.Stars=stars.OrderByDescending(s=>s.Flux).Take(1600).ToList();
|
||||
f.Regions=tiles.Select((t,i)=>t with{Stars=counts[i]}).ToList();f.Measured=true;
|
||||
}
|
||||
}
|
||||
95
src/AstroFrame.Engine/Models.cs
Normal file
95
src/AstroFrame.Engine/Models.cs
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
namespace AstroFrame.Engine;
|
||||
|
||||
public enum Verdict { Keep, Review, Reject }
|
||||
public sealed record Star(double X,double Y,double Flux,double Fwhm,double Ellipticity);
|
||||
public sealed record Region(double Background,double Noise,int Stars);
|
||||
public sealed record Evidence(string Metric,double Value,double Baseline,double Severity,string Message);
|
||||
public sealed class Frame
|
||||
{
|
||||
public string Id {get;set;}="";
|
||||
public string Path {get;set;}="";
|
||||
public long Length {get;set;}
|
||||
public long Modified {get;set;}
|
||||
public string Target {get;set;}="";
|
||||
public string Instrument {get;set;}="";
|
||||
public string Filter {get;set;}="";
|
||||
public string Gain {get;set;}="";
|
||||
public string Bayer {get;set;}="";
|
||||
public DateTime? Timestamp {get;set;}
|
||||
public double Exposure {get;set;}
|
||||
public int Width {get;set;}
|
||||
public int Height {get;set;}
|
||||
public double Ra {get;set;}
|
||||
public double Dec {get;set;}
|
||||
public string Session {get;set;}="";
|
||||
public double Background {get;set;}
|
||||
public double Noise {get;set;}
|
||||
public int StarCount {get;set;}
|
||||
public double Fwhm {get;set;}
|
||||
public double Ellipticity {get;set;}
|
||||
public double Transparency {get;set;}
|
||||
public double MatchFraction {get;set;}
|
||||
public double SpatialLoss {get;set;}
|
||||
public double BackgroundVariation {get;set;}
|
||||
public double CloudCoverage {get;set;}
|
||||
public double CloudSignificance {get;set;}
|
||||
public double ReferenceConfidence {get;set;}
|
||||
public byte[] CloudMask {get;set;}=[];
|
||||
[System.Text.Json.Serialization.JsonIgnore] public float[] SkyMap {get;set;}=[];
|
||||
[System.Text.Json.Serialization.JsonIgnore] public float[] SkyNoise {get;set;}=[];
|
||||
[System.Text.Json.Serialization.JsonIgnore] public double[] ForcedFlux {get;set;}=[];
|
||||
[System.Text.Json.Serialization.JsonIgnore] public string ForcedReferenceId {get;set;}="";
|
||||
[System.Text.Json.Serialization.JsonIgnore] public bool CacheDirty {get;set;}
|
||||
public double Score {get;set;}
|
||||
public double[] RegionFlux {get;set;}=new double[12];
|
||||
public double[] RegionLoss {get;set;}=new double[12];
|
||||
public int[] RegionMatches {get;set;}=new int[12];
|
||||
public double[] Alignment {get;set;}=[];
|
||||
public string ReferenceId {get;set;}="";
|
||||
[System.Text.Json.Serialization.JsonIgnore] public List<Star> Stars {get;set;}=[];
|
||||
public List<Region> Regions {get;set;}=[];
|
||||
public List<Evidence> Evidence {get;set;}=[];
|
||||
public Dictionary<string,double> Baselines {get;set;}=[];
|
||||
public Dictionary<string,double> AdditionalMeasurements {get;set;}=[];
|
||||
public Verdict Automatic {get;set;}=Verdict.Review;
|
||||
public Verdict? Override {get;set;}
|
||||
public string Note {get;set;}="";
|
||||
public DateTime? ReviewedAt {get;set;}
|
||||
public string Error {get;set;}="";
|
||||
public string Warning {get;set;}="";
|
||||
public string Cause {get;set;}="Awaiting analysis";
|
||||
public bool Measured {get;set;}
|
||||
[System.Text.Json.Serialization.JsonIgnore] public Verdict Effective=>Override??Automatic;
|
||||
[System.Text.Json.Serialization.JsonIgnore] public string Name=>System.IO.Path.GetFileName(Path);
|
||||
[System.Text.Json.Serialization.JsonIgnore] public string Status=>Effective.ToString().ToUpperInvariant();
|
||||
[System.Text.Json.Serialization.JsonIgnore] public string Time=>Timestamp?.ToString("MM-dd HH:mm:ss")??"Unknown time";
|
||||
[System.Text.Json.Serialization.JsonIgnore] public string Summary=>Override.HasValue?"Manual decision · "+Cause:Cause;
|
||||
}
|
||||
public sealed class Project
|
||||
{
|
||||
public const string EngineVersion="0.2.0-spatial-reference-1";
|
||||
public string Version {get;set;}=EngineVersion;
|
||||
public string Name {get;set;}="Untitled";
|
||||
public string Source {get;set;}="";
|
||||
public DateTime Updated {get;set;}=DateTime.UtcNow;
|
||||
public bool Complete {get;set;}
|
||||
public List<Frame> Frames {get;set;}=[];
|
||||
}
|
||||
public sealed record ProgressInfo(int Done,int Total,string Stage,string File);
|
||||
public interface IFrameDetector
|
||||
{
|
||||
string Name {get;}
|
||||
void Measure(Frame frame,ImagePlane image,CancellationToken cancellationToken);
|
||||
}
|
||||
public static class Robust
|
||||
{
|
||||
public static double Median(IEnumerable<double> values)=>Quantile(values,.5);
|
||||
public static double Quantile(IEnumerable<double> values,double q)
|
||||
{
|
||||
var a=values.Where(double.IsFinite).Order().ToArray(); if(a.Length==0)return 0;
|
||||
double p=Math.Clamp(q,0,1)*(a.Length-1);int i=(int)p;
|
||||
return a[i]+(a[Math.Min(i+1,a.Length-1)]-a[i])*(p-i);
|
||||
}
|
||||
public static double Mad(IEnumerable<double> values)
|
||||
{var a=values.Where(double.IsFinite).ToArray();double m=Median(a);return 1.4826*Median(a.Select(x=>Math.Abs(x-m)));}
|
||||
}
|
||||
65
src/AstroFrame.Engine/PreviewRenderer.cs
Normal file
65
src/AstroFrame.Engine/PreviewRenderer.cs
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
using System.IO.Compression;
|
||||
using System.Runtime.InteropServices;
|
||||
namespace AstroFrame.Engine;
|
||||
|
||||
public sealed record PreviewPlane(int Width,int Height,float[] Pixels);
|
||||
public sealed record PreviewDisplay(PreviewPlane Plane,double Black,double White,double Mid);
|
||||
/// <summary>Display-only area reduction and screen transfer. Never used by a quality detector.</summary>
|
||||
public static class PreviewRenderer
|
||||
{
|
||||
const int Magic=0x41504633;
|
||||
public static PreviewPlane Reduce(ImagePlane image,int step)
|
||||
{
|
||||
int w=(image.Width+step-1)/step,h=(image.Height+step-1)/step;float[] pixels=new float[w*h];
|
||||
for(int y=0;y<h;y++)for(int x=0;x<w;x++)
|
||||
{
|
||||
double sum=0;int count=0;
|
||||
for(int dy=y*step;dy<Math.Min((y+1)*step,image.Height);dy++)for(int dx=x*step;dx<Math.Min((x+1)*step,image.Width);dx++){sum+=image.Pixels[dy*image.Width+dx];count++;}
|
||||
pixels[y*w+x]=(float)(sum/Math.Max(count,1));
|
||||
}
|
||||
return new(w,h,pixels);
|
||||
}
|
||||
public static byte[] Render(PreviewPlane image,double target=.18,bool nebula=false)
|
||||
=>Render(Prepare(image,nebula),target);
|
||||
public static PreviewDisplay Prepare(PreviewPlane image,bool nebula=false)
|
||||
{
|
||||
var plane=nebula?Reduce(new(image.Width,image.Height,image.Pixels,1),2):image;
|
||||
var values=plane.Pixels.Select(v=>(double)v).ToArray();double median=Robust.Median(values);
|
||||
List<double> differences=[];for(int y=0;y<plane.Height;y++)for(int x=0;x<plane.Width-1;x++)differences.Add(Math.Abs(plane.Pixels[y*plane.Width+x]-plane.Pixels[y*plane.Width+x+1]));
|
||||
double noise=Math.Max(.001,Robust.Median(differences)/.953872),black=median-2.8*noise,white=Math.Max(Robust.Quantile(values,.9995),median+30*noise),span=white-black;
|
||||
return new(plane,black,white,(median-black)/span);
|
||||
}
|
||||
public static byte[] Render(PreviewDisplay display,double target=.18)
|
||||
{
|
||||
double mid=display.Mid,t=Math.Clamp(target,.06,.45),m=mid*(t-1)/((2*t-1)*mid-t),span=display.White-display.Black;byte[] output=new byte[display.Plane.Pixels.Length];
|
||||
for(int i=0;i<output.Length;i++){double v=Math.Clamp((display.Plane.Pixels[i]-display.Black)/span,0,1);output[i]=(byte)Math.Clamp(255*(m-1)*v/((2*m-1)*v-m),0,255);}
|
||||
return output;
|
||||
}
|
||||
public static void Write(ImagePlane image,string path,Frame? frame=null)
|
||||
{
|
||||
var plane=Reduce(image,Math.Max(1,(image.Height+899)/900));string tmp=path+".tmp";Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
|
||||
try
|
||||
{
|
||||
using(var stream=File.Create(tmp))
|
||||
{
|
||||
using(var writer=new BinaryWriter(stream,System.Text.Encoding.UTF8,true)){writer.Write(Magic);writer.Write(frame?.Length??0);writer.Write(frame?.Modified??0);writer.Write(plane.Width);writer.Write(plane.Height);}
|
||||
using var compressed=new DeflateStream(stream,CompressionLevel.Fastest,true);
|
||||
if(BitConverter.IsLittleEndian)compressed.Write(MemoryMarshal.AsBytes(plane.Pixels.AsSpan()));
|
||||
else{using var data=new BinaryWriter(compressed);foreach(float v in plane.Pixels)data.Write(v);}
|
||||
}
|
||||
File.Move(tmp,path,true);
|
||||
}
|
||||
finally{if(File.Exists(tmp))File.Delete(tmp);}
|
||||
}
|
||||
public static PreviewPlane Read(string path,Frame? frame=null)
|
||||
{
|
||||
using var stream=File.OpenRead(path);using var header=new BinaryReader(stream,System.Text.Encoding.UTF8,true);
|
||||
if(header.ReadInt32()!=Magic)throw new InvalidDataException("Outdated preview cache");
|
||||
long length=header.ReadInt64(),modified=header.ReadInt64();if(frame!=null&&(length!=frame.Length||modified!=frame.Modified))throw new InvalidDataException("Preview source fingerprint changed");
|
||||
int w=header.ReadInt32(),h=header.ReadInt32();if(w<=0||h<=0||(long)w*h>2_000_000)throw new InvalidDataException("Preview dimensions exceed safety budget");
|
||||
float[] pixels=new float[w*h];using var compressed=new DeflateStream(stream,CompressionMode.Decompress);using var reader=new BinaryReader(compressed);
|
||||
if(BitConverter.IsLittleEndian)compressed.ReadExactly(MemoryMarshal.AsBytes(pixels.AsSpan()));else for(int i=0;i<pixels.Length;i++)pixels[i]=reader.ReadSingle();
|
||||
if(pixels.Any(v=>!float.IsFinite(v)))throw new InvalidDataException("Nonfinite preview");
|
||||
return new(w,h,pixels);
|
||||
}
|
||||
}
|
||||
85
src/AstroFrame.Engine/ProjectStore.cs
Normal file
85
src/AstroFrame.Engine/ProjectStore.cs
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
namespace AstroFrame.Engine;
|
||||
public static class ProjectStore
|
||||
{
|
||||
static readonly JsonSerializerOptions Options=new(){WriteIndented=false,Converters={new JsonStringEnumConverter()}};
|
||||
public static Project Load(string directory)
|
||||
{
|
||||
string path=System.IO.Path.Combine(directory,"project.json");
|
||||
if(new FileInfo(path).Length>64L*1024*1024)throw new InvalidDataException("Project metadata exceeds the 64 MB safety limit. Create a new project with catalog caching.");
|
||||
using var stream=File.OpenRead(path);var p=JsonSerializer.Deserialize<Project>(stream,Options)??throw new InvalidDataException("Empty project");
|
||||
if(p.Version!=Project.EngineVersion){p.Complete=false;foreach(var f in p.Frames){f.Measured=false;f.Automatic=Verdict.Review;f.Cause="Analysis version changed; reanalyze";}}
|
||||
return p;
|
||||
}
|
||||
public static void Save(Project p,string directory)
|
||||
{
|
||||
Directory.CreateDirectory(directory);p.Updated=DateTime.UtcNow;p.Version=Project.EngineVersion;
|
||||
Directory.CreateDirectory(System.IO.Path.Combine(directory,"catalogs"));
|
||||
foreach(var f in p.Frames.Where(f=>f.Measured&&f.Stars.Count>0))
|
||||
{
|
||||
string catalog=CatalogPath(directory,f);bool valid=false;
|
||||
if(File.Exists(catalog)){using var reader=new BinaryReader(File.OpenRead(catalog));valid=reader.ReadString()==Project.EngineVersion&&reader.ReadInt64()==f.Length&&reader.ReadInt64()==f.Modified;}
|
||||
if(valid&&!f.CacheDirty)continue;
|
||||
string catalogTmp=catalog+".tmp";
|
||||
using(var writer=new BinaryWriter(File.Create(catalogTmp))){writer.Write(Project.EngineVersion);writer.Write(f.Length);writer.Write(f.Modified);writer.Write(f.Stars.Count);foreach(var s in f.Stars){writer.Write(s.X);writer.Write(s.Y);writer.Write(s.Flux);writer.Write(s.Fwhm);writer.Write(s.Ellipticity);}writer.Write(f.SkyMap.Length);foreach(float v in f.SkyMap)writer.Write(v);foreach(float v in f.SkyNoise)writer.Write(v);writer.Write(f.ForcedReferenceId);writer.Write(f.ForcedFlux.Length);foreach(double v in f.ForcedFlux)writer.Write(v);}
|
||||
File.Move(catalogTmp,catalog,true);f.CacheDirty=false;
|
||||
}
|
||||
string path=System.IO.Path.Combine(directory,"project.json"),tmp=path+".tmp";File.WriteAllText(tmp,JsonSerializer.Serialize(p,Options));File.Move(tmp,path,true);
|
||||
}
|
||||
static string CatalogPath(string directory,Frame f)=>System.IO.Path.Combine(directory,"catalogs",f.Id+"-v2.bin");
|
||||
public static bool LoadCatalog(string directory,Frame f)
|
||||
{
|
||||
string path=CatalogPath(directory,f);if(!File.Exists(path))return false;
|
||||
try
|
||||
{
|
||||
using var reader=new BinaryReader(File.OpenRead(path));if(reader.ReadString()!=Project.EngineVersion||reader.ReadInt64()!=f.Length||reader.ReadInt64()!=f.Modified)return false;
|
||||
int n=reader.ReadInt32();if(n<0||n>1600)return false;f.Stars=[];
|
||||
for(int i=0;i<n;i++)f.Stars.Add(new(reader.ReadDouble(),reader.ReadDouble(),reader.ReadDouble(),reader.ReadDouble(),reader.ReadDouble()));
|
||||
int cells=reader.ReadInt32();if(cells!=SkyModel.Count&&cells!=0)return false;f.SkyMap=new float[cells];f.SkyNoise=new float[cells];for(int i=0;i<cells;i++)f.SkyMap[i]=reader.ReadSingle();for(int i=0;i<cells;i++)f.SkyNoise[i]=reader.ReadSingle();
|
||||
f.ForcedReferenceId=reader.ReadString();int count=reader.ReadInt32();if(count<0||count>600)return false;f.ForcedFlux=new double[count];for(int i=0;i<count;i++)f.ForcedFlux[i]=reader.ReadDouble();return true;
|
||||
}
|
||||
catch(IOException){return false;}
|
||||
}
|
||||
public static string PreviewPath(string directory,Frame f)=>System.IO.Path.Combine(directory,"previews",f.Id+"-display3.bin");
|
||||
}
|
||||
public sealed class Analyzer
|
||||
{
|
||||
public IReadOnlyList<IFrameDetector> Detectors {get;init;}=[new StellarDetector()];
|
||||
public async Task<Project> AnalyzeAsync(string source,string directory,Project? existing,IProgress<ProgressInfo>? progress,CancellationToken ct,int workers=0)
|
||||
{
|
||||
var old=existing?.Frames.ToDictionary(f=>f.Path,StringComparer.OrdinalIgnoreCase)??[];List<Frame> frames=[];
|
||||
var paths=Directory.EnumerateFiles(source,"*",SearchOption.AllDirectories).Where(p=>new[]{".fit",".fits",".fts"}.Contains(System.IO.Path.GetExtension(p).ToLowerInvariant())).Order().ToArray();
|
||||
if(paths.Length==0)throw new InvalidDataException("No .fit, .fits or .fts light frames found in this folder");
|
||||
int inspected=0;
|
||||
foreach(var path in paths)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();Frame f;
|
||||
try{f=Fits.Inspect(path);if(old.TryGetValue(f.Path,out var cached))
|
||||
{f.Override=cached.Override;f.Note=cached.Note;f.ReviewedAt=cached.ReviewedAt;if(cached.Length==f.Length&&cached.Modified==f.Modified&&cached.Measured&&existing?.Version==Project.EngineVersion&&ProjectStore.LoadCatalog(directory,cached))f=cached;}}
|
||||
catch(Exception e)when(e is IOException or InvalidDataException or OverflowException){f=new(){Path=System.IO.Path.GetFullPath(path),Error=e.Message};}
|
||||
frames.Add(f);progress?.Report(new(++inspected,paths.Length,"Reading FITS metadata",System.IO.Path.GetFileName(path)));
|
||||
}
|
||||
Project p=new(){Source=System.IO.Path.GetFullPath(source),Name=new DirectoryInfo(source).Name,Frames=frames};
|
||||
Directory.CreateDirectory(System.IO.Path.Combine(directory,"previews"));int done=0;
|
||||
try
|
||||
{
|
||||
int activeWorkers=workers<=0?ResourcePolicy.DefaultWorkers:Math.Clamp(workers,1,4);
|
||||
await Parallel.ForEachAsync(frames,new ParallelOptions{MaxDegreeOfParallelism=activeWorkers,CancellationToken=ct},async(f,token)=>
|
||||
{
|
||||
if(f.Error==""&&(!f.Measured||!File.Exists(ProjectStore.PreviewPath(directory,f))))
|
||||
{
|
||||
await ResourcePolicy.WaitForHeadroom(ResourcePolicy.EstimateFrameBytes(f.Width,f.Height,f.Bayer!=""?2:1),token,message=>progress?.Report(new(done,frames.Count,message,f.Name)));
|
||||
try{var image=Fits.Read(f.Path,token);if(!f.Measured)foreach(var detector in Detectors)detector.Measure(f,image,token);Fits.Preview(image,ProjectStore.PreviewPath(directory,f),f);}
|
||||
catch(Exception e)when(e is not (OperationCanceledException or OutOfMemoryException or ResourcePressureException)){f.Error=e.Message;f.Measured=false;}
|
||||
}
|
||||
progress?.Report(new(Interlocked.Increment(ref done),frames.Count,"Measuring stars and sky",f.Name));
|
||||
});
|
||||
progress?.Report(new(0,frames.Count,"Building aligned clean references",""));
|
||||
await SpatialReference.RunAsync(frames,progress,ct);
|
||||
await Task.Run(()=>Classification.Run(frames,ct),ct);p.Complete=true;
|
||||
}
|
||||
finally {ProjectStore.Save(p,directory);}
|
||||
progress?.Report(new(frames.Count,frames.Count,"Analysis complete",""));return p;
|
||||
}
|
||||
}
|
||||
65
src/AstroFrame.Engine/ResourcePolicy.cs
Normal file
65
src/AstroFrame.Engine/ResourcePolicy.cs
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
namespace AstroFrame.Engine;
|
||||
public static class ResourcePolicy
|
||||
{
|
||||
public const long GiB=1024L*1024*1024;
|
||||
public const long ProcessLimit=6*GiB;
|
||||
public const long HeapLimit=3*GiB;
|
||||
public static int DefaultWorkers=>Math.Clamp(Environment.ProcessorCount-2,1,4);
|
||||
public const long FrameBudget=256L*1024*1024;
|
||||
public static long Reserve(long total)=>Math.Min(8*GiB,total/4);
|
||||
[StructLayout(LayoutKind.Sequential)]struct MemoryStatus
|
||||
{
|
||||
public uint Length,Load;public ulong TotalPhysical,AvailablePhysical,TotalPage,AvailablePage,TotalVirtual,AvailableVirtual,AvailableExtended;
|
||||
}
|
||||
[DllImport("kernel32.dll",SetLastError=true)]static extern bool GlobalMemoryStatusEx(ref MemoryStatus status);
|
||||
public static (long Total,long Available) PhysicalMemory()
|
||||
{
|
||||
if(OperatingSystem.IsWindows()){var s=new MemoryStatus{Length=(uint)Marshal.SizeOf<MemoryStatus>()};if(GlobalMemoryStatusEx(ref s))return((long)s.TotalPhysical,(long)s.AvailablePhysical);}
|
||||
if(OperatingSystem.IsLinux())
|
||||
{
|
||||
var values=File.ReadLines("/proc/meminfo").Take(20).Select(x=>x.Split(':')).Where(x=>x.Length==2).ToDictionary(x=>x[0],x=>long.Parse(x[1].Trim().Split(' ',StringSplitOptions.RemoveEmptyEntries)[0])*1024);
|
||||
return(values.GetValueOrDefault("MemTotal"),values.GetValueOrDefault("MemAvailable"));
|
||||
}
|
||||
var info=GC.GetGCMemoryInfo();return(info.TotalAvailableMemoryBytes,Math.Max(0,info.TotalAvailableMemoryBytes-Process.GetCurrentProcess().WorkingSet64));
|
||||
}
|
||||
public static bool CanAnalyze(long total,long available,long estimatedBytes)=>available-estimatedBytes>=Reserve(total);
|
||||
public static long EstimateFrameBytes(int width,int height,int scale)=>(long)(width/scale)*(height/scale)*16;
|
||||
public static void CheckFrame(int width,int height,int scale)
|
||||
{if(EstimateFrameBytes(width,height,scale)>FrameBudget)throw new InvalidDataException("Image exceeds the 256 MB per-frame analysis budget; this frame needs a memory-bounded detector");}
|
||||
public static async Task WaitForHeadroom(long estimate,CancellationToken ct,Action<string>? report=null)
|
||||
{
|
||||
for(int i=0;i<20;i++)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();using var process=Process.GetCurrentProcess();
|
||||
if(process.PrivateMemorySize64>ProcessLimit*3/4)throw new ResourcePressureException("Analysis stopped before reaching the 6 GB process limit; completed measurements will be saved");
|
||||
var(total,available)=PhysicalMemory();if(total>0&&CanAnalyze(total,available,estimate))return;
|
||||
report?.Invoke($"Paused for RAM headroom · {available/(double)GiB:0.0} GB available · reserving {Reserve(total)/(double)GiB:0.0} GB");
|
||||
await Task.Delay(1000,ct);
|
||||
}
|
||||
throw new ResourcePressureException("Physical RAM is busy. Analysis stopped safely after waiting for headroom; completed measurements were saved. Resume when other applications have released memory.");
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential)]struct BasicLimits
|
||||
{public long ProcessTime,JobTime;public uint Flags;public UIntPtr MinWorkingSet,MaxWorkingSet;public uint ActiveProcessLimit;public UIntPtr Affinity;public uint Priority,Scheduling;}
|
||||
[StructLayout(LayoutKind.Sequential)]struct IoCounters{public ulong ReadOps,WriteOps,OtherOps,ReadBytes,WriteBytes,OtherBytes;}
|
||||
[StructLayout(LayoutKind.Sequential)]struct ExtendedLimits
|
||||
{public BasicLimits Basic;public IoCounters Io;public UIntPtr ProcessMemory,JobMemory,PeakProcessMemory,PeakJobMemory;}
|
||||
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)]static extern IntPtr CreateJobObject(IntPtr attributes,string? name);
|
||||
[DllImport("kernel32.dll",SetLastError=true)]static extern bool SetInformationJobObject(IntPtr job,int infoClass,ref ExtendedLimits info,uint length);
|
||||
[DllImport("kernel32.dll",SetLastError=true)]static extern bool AssignProcessToJobObject(IntPtr job,IntPtr process);
|
||||
[DllImport("kernel32.dll",SetLastError=true)]static extern bool QueryInformationJobObject(IntPtr job,int infoClass,out ExtendedLimits info,uint length,out uint returned);
|
||||
static IntPtr job;
|
||||
public static bool WindowsLimitEnforced {get;private set;}
|
||||
public static bool InstallWindowsLimit()
|
||||
{
|
||||
if(!OperatingSystem.IsWindows())return false;
|
||||
job=CreateJobObject(IntPtr.Zero,null);if(job==IntPtr.Zero)throw new InvalidOperationException("Cannot create the memory-limit job: "+Marshal.GetLastWin32Error());
|
||||
var limits=new ExtendedLimits{Basic=new(){Flags=0x100},ProcessMemory=new UIntPtr((ulong)ProcessLimit)};uint size=(uint)Marshal.SizeOf<ExtendedLimits>();
|
||||
if(!SetInformationJobObject(job,9,ref limits,size)||!AssignProcessToJobObject(job,Process.GetCurrentProcess().Handle))throw new InvalidOperationException("Cannot enforce the 6 GB process limit: "+Marshal.GetLastWin32Error());
|
||||
WindowsLimitEnforced=QueryInformationJobObject(job,9,out var actual,size,out _)&&actual.ProcessMemory.ToUInt64()==(ulong)ProcessLimit;
|
||||
if(!WindowsLimitEnforced)throw new InvalidOperationException("Cannot verify the 6 GB process memory limit");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
public sealed class ResourcePressureException(string message):IOException(message);
|
||||
85
src/AstroFrame.Engine/SkyModel.cs
Normal file
85
src/AstroFrame.Engine/SkyModel.cs
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
namespace AstroFrame.Engine;
|
||||
|
||||
/// <summary>Small background maps. All transforms operate in the anchor's aspect-correct coordinates.</summary>
|
||||
public static class SkyModel
|
||||
{
|
||||
public const int Columns=24,Rows=40,Count=Columns*Rows;
|
||||
public static void Measure(Frame f,ImagePlane image,CancellationToken ct)
|
||||
{
|
||||
f.SkyMap=new float[Count];f.SkyNoise=new float[Count];
|
||||
for(int row=0;row<Rows;row++)for(int col=0;col<Columns;col++)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();List<double> values=[],diff=[];
|
||||
for(int y=row*image.Height/Rows;y<(row+1)*image.Height/Rows;y+=2)
|
||||
for(int x=col*image.Width/Columns;x<(col+1)*image.Width/Columns-1;x+=2)
|
||||
{values.Add(image.Pixels[y*image.Width+x]);diff.Add(Math.Abs(image.Pixels[y*image.Width+x]-image.Pixels[y*image.Width+x+1]));}
|
||||
double center=Robust.Median(values),sigma=Math.Max(.001,Robust.Mad(values));
|
||||
// Reject stellar cores and extreme pixels before estimating the smooth sky.
|
||||
f.SkyMap[row*Columns+col]=(float)Robust.Median(values.Where(v=>Math.Abs(v-center)<3*sigma));
|
||||
f.SkyNoise[row*Columns+col]=(float)Math.Max(.001,Robust.Median(diff)/.953872);
|
||||
}
|
||||
}
|
||||
public static double Sample(float[] map,double x,double y)
|
||||
{
|
||||
double u=Math.Clamp(x*Columns-.5,0,Columns-1),v=Math.Clamp(y*Rows-.5,0,Rows-1);
|
||||
int col=Math.Min((int)u,Columns-2),row=Math.Min((int)v,Rows-2);double dx=u-col,dy=v-row;
|
||||
return (map[row*Columns+col]*(1-dx)+map[row*Columns+col+1]*dx)*(1-dy)+(map[(row+1)*Columns+col]*(1-dx)+map[(row+1)*Columns+col+1]*dx)*dy;
|
||||
}
|
||||
public static double[] Aligned(Frame f)
|
||||
{
|
||||
double[] map=Enumerable.Repeat(double.NaN,Count).ToArray();if(f.Alignment.Length!=4||f.SkyMap.Length!=Count)return map;
|
||||
var a=f.Alignment;double aspect=(double)f.Height/f.Width;
|
||||
for(int i=0;i<Count;i++)
|
||||
{
|
||||
double x=(i%Columns+.5)/Columns,y=(i/Columns+.5)/Rows;
|
||||
double u=a[0]*x-a[1]*y*aspect+a[2],v=(a[1]*x+a[0]*y*aspect+a[3])/aspect;
|
||||
if(u>.025&&u<.975&&v>.025&&v<.975)map[i]=Sample(f.SkyMap,u,v);
|
||||
}
|
||||
return Detrend(map);
|
||||
}
|
||||
public static double[] Detrend(double[] values)
|
||||
{
|
||||
bool[] good=values.Select(double.IsFinite).ToArray();double[] residual=(double[])values.Clone();
|
||||
if(good.Count(v=>v)<12)return residual;
|
||||
for(int iteration=0;iteration<5;iteration++)
|
||||
{
|
||||
double[,] system=new double[3,4];
|
||||
for(int i=0;i<Count;i++)if(good[i])
|
||||
{
|
||||
double[] v=[1,(i%Columns+.5)/Columns-.5,(i/Columns+.5)/Rows-.5];
|
||||
for(int r=0;r<3;r++){for(int c=0;c<3;c++)system[r,c]+=v[r]*v[c];system[r,3]+=v[r]*values[i];}
|
||||
}
|
||||
double[] coefficients=Solve(system);for(int i=0;i<Count;i++)residual[i]=values[i]-coefficients[0]-coefficients[1]*((i%Columns+.5)/Columns-.5)-coefficients[2]*((i/Columns+.5)/Rows-.5);
|
||||
double median=Robust.Median(residual.Where((_,i)=>good[i])),sigma=Math.Max(1,Robust.Mad(residual.Where((_,i)=>good[i])));
|
||||
for(int i=0;i<Count;i++)good[i]=double.IsFinite(residual[i])&&Math.Abs(residual[i]-median)<3*sigma;
|
||||
if(good.Count(v=>v)<12)break;
|
||||
}
|
||||
return residual;
|
||||
}
|
||||
static double[] Solve(double[,] m)
|
||||
{
|
||||
for(int k=0;k<3;k++)
|
||||
{
|
||||
int pivot=k;for(int r=k+1;r<3;r++)if(Math.Abs(m[r,k])>Math.Abs(m[pivot,k]))pivot=r;
|
||||
if(Math.Abs(m[pivot,k])<1e-8)return [Robust.Median([m[0,3]/Math.Max(m[0,0],1)]),0,0];
|
||||
for(int c=k;c<4;c++)(m[k,c],m[pivot,c])=(m[pivot,c],m[k,c]);
|
||||
double divisor=m[k,k];for(int c=k;c<4;c++)m[k,c]/=divisor;
|
||||
for(int r=0;r<3;r++)if(r!=k){double factor=m[r,k];for(int c=k;c<4;c++)m[r,c]-=factor*m[k,c];}
|
||||
}
|
||||
return [m[0,3],m[1,3],m[2,3]];
|
||||
}
|
||||
public static int LargestComponent(bool[] mask)
|
||||
{
|
||||
bool[] seen=new bool[Count];int largest=0;Queue<int> queue=new();
|
||||
for(int i=0;i<Count;i++)if(mask[i]&&!seen[i])
|
||||
{
|
||||
int size=0;queue.Enqueue(i);seen[i]=true;
|
||||
while(queue.TryDequeue(out int j))
|
||||
{
|
||||
size++;foreach(int k in new[]{j-Columns,j+Columns,j%Columns>0?j-1:-1,j%Columns<Columns-1?j+1:-1})if(k>=0&&k<Count&&!seen[k]&&mask[k]){seen[k]=true;queue.Enqueue(k);}
|
||||
}
|
||||
largest=Math.Max(largest,size);
|
||||
}
|
||||
return largest;
|
||||
}
|
||||
}
|
||||
83
src/AstroFrame.Engine/SpatialReference.cs
Normal file
83
src/AstroFrame.Engine/SpatialReference.cs
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
namespace AstroFrame.Engine;
|
||||
|
||||
/// <summary>Session reference construction and forced photometry, independent of classification/UI.</summary>
|
||||
public static class SpatialReference
|
||||
{
|
||||
public static async Task RunAsync(List<Frame> frames,IProgress<ProgressInfo>? progress,CancellationToken ct)
|
||||
{
|
||||
Classification.Sessions(frames);int done=0;
|
||||
foreach(var session in frames.GroupBy(f=>f.Session))
|
||||
{
|
||||
var a=session.Where(f=>f.Measured&&f.Error==""&&f.SkyMap.Length==SkyModel.Count).OrderBy(f=>f.Timestamp).ToArray();if(a.Length==0)continue;
|
||||
double Curvature(Frame f)=>Robust.Quantile(SkyModel.Detrend(f.SkyMap.Select(v=>(double)v).ToArray()).Select(Math.Abs),.95);
|
||||
var candidate=a.Where(f=>f.Stars.Count>=30).Select(f=>(Frame:f,Curvature:Curvature(f))).OrderBy(x=>x.Curvature).Take(Math.Max(1,a.Length*2/5)).ToArray();
|
||||
if(candidate.Length==0)continue;
|
||||
double population=Robust.Median(candidate.Select(x=>(double)x.Frame.StarCount));
|
||||
var anchor=candidate.OrderBy(x=>Math.Abs(x.Frame.StarCount-population)/Math.Max(population,1)+x.Frame.Ellipticity).First().Frame;
|
||||
foreach(var f in a){ct.ThrowIfCancellationRequested();Matching.Measure(anchor,f);}
|
||||
var maps=a.Select(SkyModel.Aligned).ToArray();double[] reference=MedianMap(maps);int[] clean=[];
|
||||
// Rebuild from the least transient 40%, not cloud-contaminated rolling neighborhoods.
|
||||
// This selection establishes a reference population; it is not a rejection quota.
|
||||
for(int pass=0;pass<3;pass++)
|
||||
{
|
||||
var deviations=maps.Select(m=>Amplitude(Difference(m,reference))).ToArray();
|
||||
clean=Enumerable.Range(0,a.Length).Where(i=>a[i].MatchFraction>.45&&maps[i].Count(double.IsFinite)>SkyModel.Count*.65).OrderBy(i=>deviations[i]).Take(Math.Max(1,a.Length*2/5)).ToArray();
|
||||
if(clean.Length==0)break;reference=MedianMap(clean.Select(i=>maps[i]).ToArray());
|
||||
}
|
||||
if(clean.Length==0)continue;
|
||||
int stars=Math.Min(600,anchor.Stars.Count);
|
||||
string apertureReference=$"{anchor.Id}:{anchor.Length}:{anchor.Modified}";
|
||||
foreach(var f in a)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if(f.Alignment.Length==4&&(f.ForcedReferenceId!=apertureReference||f.ForcedFlux.Length!=stars))
|
||||
{
|
||||
await ResourcePolicy.WaitForHeadroom(ResourcePolicy.EstimateFrameBytes(f.Width,f.Height,f.Bayer!=""?2:1),ct,message=>progress?.Report(new(done,frames.Count,message,f.Name)));
|
||||
try{f.ForcedFlux=Matching.ForcedFlux(anchor,f,Fits.Read(f.Path,ct));f.ForcedReferenceId=apertureReference;f.CacheDirty=true;}
|
||||
catch(Exception e)when(e is not (OperationCanceledException or OutOfMemoryException or ResourcePressureException)){f.Error=e.Message;}
|
||||
}
|
||||
progress?.Report(new(++done,frames.Count,"Forced photometry against session reference",f.Name));
|
||||
}
|
||||
double[] normal=new double[stars];
|
||||
for(int j=0;j<stars;j++)normal[j]=Robust.Median(clean.Where(i=>a[i].ForcedFlux.Length==stars).Select(i=>a[i].ForcedFlux[j]));
|
||||
foreach(var f in a)
|
||||
{
|
||||
f.Transparency=0;f.RegionFlux=new double[12];f.RegionMatches=new int[12];
|
||||
if(f.ForcedFlux.Length!=stars)continue;
|
||||
List<double> ratios=[];List<double>[] regional=Enumerable.Range(0,12).Select(_=>new List<double>()).ToArray();
|
||||
for(int j=0;j<stars;j++)
|
||||
{
|
||||
// Reference S/N eligibility is independent of whether this frame detects the star.
|
||||
if(normal[j]*anchor.Exposure<30*anchor.Noise||!double.IsFinite(f.ForcedFlux[j]))continue;
|
||||
var s=anchor.Stars[j];double ratio=f.ForcedFlux[j]/normal[j];ratios.Add(ratio);
|
||||
regional[Math.Clamp((int)(s.Y*4),0,3)*3+Math.Clamp((int)(s.X*3),0,2)].Add(ratio);
|
||||
}
|
||||
if(ratios.Count>=20)f.Transparency=Math.Max(0,Robust.Median(ratios));
|
||||
for(int r=0;r<12;r++){f.RegionMatches[r]=regional[r].Count;if(regional[r].Count>=5)f.RegionFlux[r]=Robust.Median(regional[r]);}
|
||||
f.AdditionalMeasurements["Forced flux samples"]=ratios.Count;
|
||||
}
|
||||
var residuals=clean.Select(i=>Difference(maps[i],reference)).ToArray();
|
||||
double referenceNoise=Robust.Median(clean.Select(i=>a[i].Noise));
|
||||
double referenceResidual=Robust.Median(residuals.Select(Amplitude));
|
||||
double stability=Math.Min(1,referenceNoise*.5/Math.Max(referenceResidual,.1));
|
||||
double floor=Math.Max(.1,referenceNoise*.08);
|
||||
double[] scatter=Enumerable.Range(0,SkyModel.Count).Select(j=>Math.Max(floor,Robust.Mad(residuals.Select(m=>m[j])))).ToArray();
|
||||
for(int i=0;i<a.Length;i++)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();var f=a[i];var residual=Difference(maps[i],reference);int valid=residual.Count(double.IsFinite);
|
||||
var z=residual.Select((v,j)=>Math.Abs(v)/scatter[j]).ToArray();bool[] mask=z.Select(v=>double.IsFinite(v)&&v>5).ToArray();
|
||||
f.CloudMask=mask.Select(v=>(byte)(v?1:0)).ToArray();f.CloudCoverage=(double)mask.Count(v=>v)/Math.Max(valid,1);f.CloudSignificance=Robust.Quantile(z,.95);
|
||||
f.ReferenceConfidence=stability*Math.Min(1,clean.Length/20.0)*(double)valid/SkyModel.Count;
|
||||
f.AdditionalMeasurements["Cloud connected coverage"]=(double)SkyModel.LargestComponent(mask)/Math.Max(valid,1);
|
||||
f.AdditionalMeasurements["Sky residual ADU"]=Amplitude(residual);f.AdditionalMeasurements["Reference frames"]=clean.Length;
|
||||
f.AdditionalMeasurements["Clear reference member"]=clean.Contains(i)?1:0;
|
||||
f.AdditionalMeasurements["Reference overlap"]=(double)valid/SkyModel.Count;
|
||||
f.AdditionalMeasurements["Reference residual ADU"]=referenceResidual;
|
||||
f.AdditionalMeasurements["Reference stability"]=stability;
|
||||
}
|
||||
}
|
||||
}
|
||||
static double Amplitude(double[] map)=>Robust.Quantile(map.Select(Math.Abs),.95);
|
||||
static double[] Difference(double[] map,double[] reference)=>SkyModel.Detrend(map.Select((v,j)=>v-reference[j]).ToArray());
|
||||
static double[] MedianMap(double[][] maps)=>Enumerable.Range(0,SkyModel.Count).Select(j=>maps.Any(m=>double.IsFinite(m[j]))?Robust.Median(maps.Select(m=>m[j])):double.NaN).ToArray();
|
||||
}
|
||||
44
src/AstroFrame.Engine/StellarDetail.cs
Normal file
44
src/AstroFrame.Engine/StellarDetail.cs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
namespace AstroFrame.Engine;
|
||||
|
||||
public sealed record StarSnippet(int Number,byte[] Selected,byte[] Comparison);
|
||||
public sealed record StarDetail(string SelectedName,string ComparisonName,List<StarSnippet> Stars,int Size=13);
|
||||
/// <summary>Read-only matched source samples for human morphology review; no quality decisions.</summary>
|
||||
public static class StellarDetail
|
||||
{
|
||||
public static Frame? Comparison(Project project,Frame selected)
|
||||
{
|
||||
double normal=selected.Baselines.GetValueOrDefault("Ellipticity"),width=selected.Baselines.GetValueOrDefault("FWHM");
|
||||
var available=project.Frames.Where(f=>f.Id!=selected.Id&&f.Session==selected.Session&&f.Effective==Verdict.Keep&&f.Error==""&&f.MatchFraction>.5);
|
||||
var representative=available.Where(f=>(normal<=0||f.Ellipticity<normal+.06)&&(width<=0||f.Fwhm<width*1.15)).ToArray();
|
||||
return (representative.Length>0?representative:available).OrderBy(f=>Math.Abs((f.Timestamp.GetValueOrDefault()-selected.Timestamp.GetValueOrDefault()).TotalSeconds)).FirstOrDefault();
|
||||
}
|
||||
public static StarDetail Read(string directory,Frame selected,Frame comparison,CancellationToken ct=default)
|
||||
{
|
||||
ImagePlane Source(Frame f)
|
||||
{var info=new FileInfo(f.Path);if(!info.Exists||info.Length!=f.Length||info.LastWriteTimeUtc.Ticks!=f.Modified)throw new IOException("Source changed; reanalyze before inspecting");return Fits.Read(f.Path,ct);}
|
||||
var a=Source(selected);var b=Source(comparison);List<Star> stars;
|
||||
if(ProjectStore.LoadCatalog(directory,selected))stars=selected.Stars;
|
||||
else{var measured=Fits.Inspect(selected.Path);new StellarDetector().Measure(measured,a,ct);stars=measured.Stars;}
|
||||
if(selected.ReferenceId!=comparison.ReferenceId||selected.Alignment.Length!=4||comparison.Alignment.Length!=4)throw new InvalidDataException("Matched source comparison is unavailable: no shared reliable alignment");
|
||||
double aspect=(double)selected.Height/selected.Width;var from=selected.Alignment;var to=comparison.Alignment;List<Star> chosen=[];List<StarSnippet> snippets=[];
|
||||
foreach(var s in stars)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();if(s.X<.04||s.X>.96||s.Y<.04||s.Y>.96||chosen.Any(t=>Math.Pow(t.X-s.X,2)+Math.Pow((t.Y-s.Y)*aspect,2)<.04*.04))continue;
|
||||
double sx=s.X-from[2],sy=s.Y*aspect-from[3],d=from[0]*from[0]+from[1]*from[1];if(d<.5)throw new InvalidDataException("Unreliable image alignment");
|
||||
double rx=(from[0]*sx+from[1]*sy)/d,ry=(-from[1]*sx+from[0]*sy)/d,x=to[0]*rx-to[1]*ry+to[2],y=(to[1]*rx+to[0]*ry+to[3])/aspect;
|
||||
if(x<.04||x>.96||y<.04||y>.96)continue;chosen.Add(s);
|
||||
snippets.Add(new(snippets.Count+1,Crop(a,s.X,s.Y),Crop(b,x,y)));if(snippets.Count==8)break;
|
||||
}
|
||||
if(snippets.Count==0)throw new InvalidDataException("No suitable matched stars in the overlapping field");
|
||||
return new(selected.Name,comparison.Name,snippets);
|
||||
}
|
||||
static byte[] Crop(ImagePlane image,double px,double py)
|
||||
{
|
||||
int x=(int)Math.Round(px*image.Width),y=(int)Math.Round(py*image.Height);double peak=double.MinValue;int bestX=x,bestY=y;
|
||||
for(int dy=-2;dy<=2;dy++)for(int dx=-2;dx<=2;dx++)if(image.Pixels[(y+dy)*image.Width+x+dx]>peak){peak=image.Pixels[(y+dy)*image.Width+x+dx];bestX=x+dx;bestY=y+dy;}
|
||||
List<double> edge=[];for(int dy=-6;dy<=6;dy++)for(int dx=-6;dx<=6;dx++)if(dx*dx+dy*dy>=25)edge.Add(image.Pixels[(bestY+dy)*image.Width+bestX+dx]);
|
||||
double sky=Robust.Median(edge),range=Math.Max(1,peak-sky);byte[] pixels=new byte[169];
|
||||
for(int dy=-6;dy<=6;dy++)for(int dx=-6;dx<=6;dx++)pixels[(dy+6)*13+dx+6]=(byte)Math.Clamp(255*(image.Pixels[(bestY+dy)*image.Width+bestX+dx]-sky)/range,0,255);
|
||||
return pixels;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue