Release 1.1.0 with adaptive RAM and interactive previews
All checks were successful
Release AstroFrame / packages (push) Successful in 1m13s

Replace fixed process, heap, frame and worker caps with physical RAM admission and CPU-scaled concurrency. Round Windows job budgets to native allocation boundaries. Add persistent cursor-centered zoom, drag and reset, fresh launches, cerulean update indicators and grey native startup backgrounds. Validate with isolated fixtures and a fake updater.
This commit is contained in:
Elijah 2026-10-04 09:33:44 -07:00
parent 6b56c0b122
commit a8e7a87b94
21 changed files with 271 additions and 80 deletions

View file

@ -1,6 +1,6 @@
<Project>
<PropertyGroup>
<Version>1.0.2</Version>
<Version>1.1.0</Version>
<Authors>Elijah Kuntz</Authors>
<Product>AstroFrame</Product>
</PropertyGroup>

View file

@ -6,13 +6,13 @@ An independent Windows/Linux desktop application for selecting astrophotography
For packaged installations, run `AstroFrame-win-x64-Setup.exe`. Linux users can use `AstroFrame-linux-x64.AppImage` and the accompanying `install-linux.sh` for an application-menu entry. Both target x64 PCs. See [installation and releases](docs/releases.md) for Debian/Arch prerequisites and package-building instructions.
**Settings → Updates** shows the installed version and update status, with automatic and manual checks. Installed packages check the [public repository releases](https://git.elijahkuntz.com/Elijah/AstroFrame/releases) on startup and every six hours. A newer stable release adds an update indicator to Settings. **Install update and restart** downloads the release package and restarts after saving; active analysis/export must finish first. Preferences and projects survive updates. Git pushes become app updates only after a versioned release and its packages are published.
**Settings → Updates** shows the installed version and update status, with automatic and manual checks. Installed packages check the [public repository releases](https://git.elijahkuntz.com/Elijah/AstroFrame/releases) on startup and every six hours. A newer stable release turns Settings cerulean blue and adds an update indicator. **Install update and restart** downloads the release package and restarts after saving; active analysis/export must finish first. Preferences and projects survive updates. Git pushes become app updates only after a versioned release and its packages are published.
Open `artifacts/AstroFrame/AstroFrame.Desktop.exe`. This self-contained build does not require Python, a GPU, or a separate .NET installation. Keep the entire application folder together.
Windows enforces a **6 GiB process allocation limit** and a **3 GiB managed-heap limit**. Only one desktop instance can run at a time. Analysis uses up to four workers, leaving at least two logical processors unused where available. It rejects images exceeding a 256 MiB per-frame budget and pauses when it cannot leave roughly 25% of physical RAM free (up to 8 GiB). If pressure persists for 20 seconds, completed measurements are saved for resuming. The page file is not counted as available physical RAM. Windows software rendering is used during this release. The larger limit provides headroom; it does not allocate 6 GiB in advance.
Analysis scales its memory budget with physical RAM and samples available headroom before admitting each frame. It reserves one quarter of RAM (up to 8 GiB) for the OS and other applications, counts concurrent frame reservations atomically, and stops safely after 20 seconds of sustained pressure once active frames finish. Windows enforces a process ceiling of physical RAM minus that reserve; the old fixed process, heap and per-frame caps have been removed. Per-frame estimates include working buffers and are bounded by half the machine budget, with the existing 100 MP FITS limit retained. Up to 16 workers are selected from CPU capacity, leaving two logical processors unused where possible. Only one ordinary desktop instance runs at a time. The page file is not treated as available physical RAM. Windows uses software rendering.
`Open Sample Survey.cmd` opens all supplied datasets, including NGC 7000. `Open NGC 7000.cmd` opens its separate project. Normal launches reopen the last project automatically. Reopening a completed project uses saved measurements. New display caches are generated on demand for older projects without recomputing classifications; subsequent previews use cached linear thumbnails. An explicit project can also be opened with `AstroFrame.Desktop.exe --project "project folder"`.
`Open Sample Survey.cmd` opens all supplied datasets, including NGC 7000. `Open NGC 7000.cmd` opens its separate project. Normal launches start with an empty session. Saved projects and decisions remain available when explicitly reopened or when their source folder is selected again. Reopening a completed project uses saved measurements. New display caches are generated on demand for older projects without recomputing classifications; subsequent previews use cached linear thumbnails. An explicit project can also be opened with `AstroFrame.Desktop.exe --project "project folder"`.
To analyze another dataset, choose **Analyze lights**, select the folder containing original `.fit`, `.fits`, or `.fts` files, and wait for analysis. Subfolders are included. New projects are saved separately under `%LOCALAPPDATA%/AstroFrame/Projects/` on Windows (the equivalent local application-data location on Linux). The input folder is not used for project storage.
@ -23,6 +23,7 @@ To analyze another dataset, choose **Analyze lights**, select the folder contain
- Filter **REVIEW** or **REJECT**, and sort by concern, star count, stellar flux, or FWHM.
- Toggle **Compare nearby** and **Spatial overlay**. Red fill shows transient sky structure in the aligned reference grid. Region outlines show forced stellar flux loss. Previews have independent display stretches; use measured flux to compare transparency.
- Use **Frame view** for an area-averaged exposure preview, or **Nebula view** for additional averaging of faint diffuse structure. Adjust **Stretch** to brighten the display. These controls never affect measurements, classifications or original files.
- Scroll the mouse wheel over either preview to zoom around the cursor, and hold the left mouse button to drag. Zoom and image position persist across frames and are shared with the nearby comparison. **Reset view** restores the fitted, centered image. These display controls do not alter source pixels or analysis.
- Press **1**, **2**, **3** for KEEP, REVIEW, REJECT. Decisions save and advance. **J/K** navigates. **Reset** restores the automatic decision. **Ctrl+Z** undoes a manual decision.
- Decision evidence and measurements remain visible below the quality graph. Hover over an evidence line to read its full technical detail, and scroll the panel for additional measurements. Preview stretch and manual decisions sit below the image. Existing notes remain in saved projects and exports; the note editor has been removed. Automatic decisions and human overrides remain separate.
@ -62,7 +63,7 @@ dotnet publish src/AstroFrame.Desktop -c Release -r linux-x64 --self-contained t
The Windows build and rendered layout were tested here. Linux uses Avalonia's X11 backend and bundled Skia/Harfbuzz binaries; packaged Linux startup, settings rendering, installation and self-updates were also exercised under Ubuntu WSL. Debian/Arch desktop acceptance remains to be checked directly. A Linux desktop with the usual X11/font/ICU libraries is required; see [installation and releases](docs/releases.md).
Prebuilt Linux files are in `artifacts/AstroFrame-linux`. On Linux, run `chmod +x AstroFrame.Desktop` before launching if executable permissions were lost during transfer. The managed-heap limit and RAM-pressure monitoring also apply on Linux; the Windows kernel job limit does not.
Prebuilt Linux files are in `artifacts/AstroFrame-linux`. On Linux, run `chmod +x AstroFrame.Desktop` before launching if executable permissions were lost during transfer. RAM admission and physical headroom monitoring also apply on Linux; the Windows kernel job ceiling does not.
Batch analysis and review-label summaries:

View file

@ -48,7 +48,7 @@ Small sessions and unreliable references cannot automatically reject. Reference
## Memory, caching and safety
Up to four workers are now selected automatically, leaving two logical processors unused where possible. A 48-frame NGC 7000 measurement benchmark took 9.04/4.99/2.94 seconds with one/two/four workers, with identical star counts and four-worker peak RAM of 250 MiB. This measures the stellar/background stage, not whole-project speedup. No full-resolution image collection or stack is held in RAM. Reference maps are only 960 values per frame. Windows enforces a verified 6 GiB process allocation cap; both executables use a 3 GiB managed-heap cap. A 256 MiB estimated per-frame budget rejects oversized allocations. Analysis checks physical memory before both image passes, reserving up to 8 GiB or one quarter of physical RAM. The page file does not satisfy this reserve. Sustained pressure stops safely and saves measurements.
Version 1.1.0 selects up to 16 workers from CPU capacity, leaving two logical processors unused where possible. A 48-frame measurement run on a 16-logical-processor machine took 2.93 seconds with four workers and 1.32 seconds with fourteen, with identical star counts (peak working sets 251 and 762 MiB). This measures stellar/background processing, not whole-project speedup. No full-resolution image collection or stack is held in RAM. Windows uses a verified process ceiling based on physical RAM minus its reserve, rounded to an allocation boundary. Fixed 6 GiB process, 3 GiB heap and 256 MiB frame caps have been removed. Per-frame estimates include a 64 MiB working margin and are limited to half the machine budget. Both image passes, previews and star detail acquire atomic memory reservations, sampling physical headroom for every frame. The OS/desktop reserve remains one quarter of RAM up to 8 GiB; page-file capacity does not satisfy it. Sustained external pressure stops safely after active frames finish and saves completed measurements.
Small JSON metadata stores decisions, notes, evidence and compact masks. Binary versioned caches hold stars, sky maps and forced photometry, validated against source size and modification time and reference identity. A new engine version invalidates analysis without losing human labels. Repeated analysis uses cached measurements and forced apertures when valid. Project writes replace a temporary file atomically. Cancellation leaves analysis incomplete and export disabled.

View file

@ -0,0 +1,9 @@
# AstroFrame 1.1.0
- Processing uses more available RAM and CPU capacity. Fixed memory caps have been replaced with a physical-RAM budget and atomic reservations for concurrent frames, retaining headroom for the operating system and other applications. Processing pauses under RAM pressure and preserves completed work if pressure persists.
- Scroll over a preview to zoom around the cursor and drag with the left mouse button to pan. Zoom and position carry across frames and the nearby comparison. **Reset view** fits and centers both previews. Overlays follow the transformed image.
- Ordinary launches begin with a fresh, empty session. Saved projects and decisions remain on disk; explicit project opening and update restarts still restore the requested project.
- **Settings · Update available** turns cerulean blue when an update is available.
- The native startup background matches the application's charcoal grey.
Validation covers engine/resource policy, updater safety, mocked publication, routed mouse events, preview resets and frame switching, rendered layouts at normal and minimum size including 144 DPI, and Windows native window behavior. A 48-frame measurement benchmark on a 16-thread machine improved from 2.93 seconds with four workers to 1.32 seconds with fourteen workers, with identical star counts; this is not a whole-project speed guarantee. Development verification uses workspace fixtures and a fake updater, leaving installed copies untouched.

View file

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
@ -10,7 +10,6 @@
<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" />

View file

@ -1,28 +0,0 @@
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;}
}
}

View file

@ -0,0 +1,11 @@
namespace AstroFrame.Desktop;
// Diagnostic rendering never initializes the installed update locator or reads preferences.
internal sealed class DiagnosticUpdateBackend : IUpdateBackend
{
public bool IsInstalled=>true;
public string InstalledVersion=>typeof(MainWindow).Assembly.GetName().Version?.ToString(3)??"1.1.0";
public Task<string?> Check()=>Task.FromResult<string?>("9.0.0");
public Task Download(Action<int> progress,CancellationToken cancellation)=>throw new InvalidOperationException("Rendering diagnostics cannot download updates.");
public void ApplyAndRestart(string[] arguments)=>throw new InvalidOperationException("Rendering diagnostics cannot install updates.");
}

View file

@ -1,25 +1,30 @@
using Avalonia.Controls;
using Avalonia.Threading;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia;
using Avalonia.Styling;
using Avalonia.Controls.Presenters;
namespace AstroFrame.Desktop;
public sealed partial class MainWindow
{
readonly AppUpdates updates = new();
readonly AppUpdates updates = Program.Diagnostic ? new(new DiagnosticUpdateBackend(),new AppSettings(),_=>{}) : new();
readonly Button settingsButton = Button("Settings");
readonly DispatcherTimer updateTimer = new() { Interval = TimeSpan.FromHours(6) };
SettingsWindow? settingsWindow;
void InitializeUpdates()
{
Styles.Add(new Style(x=>x.OfType<Button>().Class("update-available").Template().OfType<ContentPresenter>())
{Setters={new Setter(ContentPresenter.BackgroundProperty,Palette.Update),new Setter(ContentPresenter.ForegroundProperty,Palette.Text)}});
settingsButton.Click += (_, _) => ShowSettings();
updates.Changed += () =>
{
settingsButton.Content = updates.AvailableVersion == null ? "Settings" : "Settings · Update available";
UpdateSettingsButton(updates.AvailableVersion!=null);
if (updates.Applying) { analyze.IsEnabled = false; export.IsEnabled = false; }
};
bool diagnostic = Program.Arguments.Any(a => a.StartsWith("--capture") || a == "--smoke");
bool diagnostic = Program.Diagnostic;
if (!diagnostic)
{
Opened += async (_, _) => await updates.Check(automatic: true);
@ -28,6 +33,13 @@ public sealed partial class MainWindow
}
Closed += (_, _) => { updateTimer.Stop(); updates.Dispose(); settingsWindow?.Close(); };
}
void UpdateSettingsButton(bool available)
{
settingsButton.Content=available?"Settings · Update available":"Settings";
settingsButton.Classes.Set("update-available",available);
settingsButton.Background=available?Palette.Update:Palette.Raised;
settingsButton.Foreground=Palette.Text;
}
public SettingsWindow ShowSettings()
{
if (settingsWindow != null) { settingsWindow.Activate(); return settingsWindow; }

View file

@ -0,0 +1,53 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Input.Raw;
using Avalonia.Interactivity;
using Avalonia.Media.Imaging;
using Avalonia.VisualTree;
namespace AstroFrame.Desktop;
public sealed partial class MainWindow
{
public async Task VerifyInteractions(string fixture,string output)
{
if(!Program.Diagnostic)throw new InvalidOperationException("UI verification requires an isolated diagnostic launch.");
Directory.CreateDirectory(output);var results=new List<string>();
void Check(bool value,string text){if(!value)throw new Exception(text);results.Add("PASS "+text);}
void Capture(string name,double dpi=96)
{
using var bitmap=new RenderTargetBitmap(new PixelSize((int)Math.Ceiling(Bounds.Width*dpi/96),(int)Math.Ceiling(Bounds.Height*dpi/96)),new Vector(dpi,dpi));
bitmap.Render(this);bitmap.Save(System.IO.Path.Combine(output,name+".png"));
}
Check(project==null&&selected==null&&visible.Count==0,"ordinary startup starts a fresh session");
Check(Background==Palette.Background&&TransparencyBackgroundFallback==Palette.Background&&NativeWindowBackground.IsApplied(this),"managed and native startup backgrounds match the application grey");
Capture("fresh-session");
await updates.Check();Check(settingsButton.Background==Palette.Update&&settingsButton.Classes.Contains("update-available"),"available update turns Settings cerulean blue");
UpdateSettingsButton(false);Check(settingsButton.Background==Palette.Raised&&!settingsButton.Classes.Contains("update-available"),"no update restores the normal Settings color");UpdateSettingsButton(true);
LoadProject(System.IO.Path.GetFullPath(fixture));await WaitForPreviews();await Task.Delay(200);Check(preview.HasImage,"fixture preview loads");
using var pointer=new Pointer(Pointer.GetNextFreeId(),PointerType.Mouse,true);
var idle=new PointerPointProperties(RawInputModifiers.None,PointerUpdateKind.Other);
var held=new PointerPointProperties(RawInputModifiers.LeftMouseButton,PointerUpdateKind.LeftButtonPressed);
Point Local(double x,double y)=>preview.TranslatePoint(new Point(x,y),this)!.Value;
var at=Local(preview.Bounds.Width*.65,preview.Bounds.Height*.55);
var wheel=new PointerWheelEventArgs(preview,pointer,this,at,0,idle,KeyModifiers.None,new Vector(0,4));preview.RaiseEvent(wheel);
Check(viewport.Zoom>2&&wheel.Handled,"mouse wheel zooms through the actual preview handler");
var before=viewport.Pan;preview.RaiseEvent(new PointerPressedEventArgs(preview,pointer,this,at,0,held,KeyModifiers.None));
Check(pointer.Captured==preview,"left mouse press captures the preview for dragging");
preview.RaiseEvent(new PointerEventArgs(InputElement.PointerMovedEvent,preview,pointer,this,at+new Vector(35,22),0,held,KeyModifiers.None));
preview.RaiseEvent(new PointerReleasedEventArgs(preview,pointer,this,at+new Vector(35,22),0,idle,KeyModifiers.None,MouseButton.Left));
Check(viewport.Pan!=before&&pointer.Captured==null,"mouse drag pans and release ends capture");
double zoom=viewport.Zoom;var pan=viewport.Pan;
Select(visible.Skip(1).First());await WaitForPreviews();Check(viewport.Zoom==zoom&&viewport.Pan==pan,"zoom and position persist when switching frames");
previewMode.SelectedIndex=1;displayStretch.Value=.26;spatial.IsChecked=true;compare.IsChecked=true;await WaitForPreviews();await Task.Delay(150);
Check(preview.Viewport==comparison.Viewport&&viewport.Zoom==zoom&&viewport.Pan==pan,"comparison, overlay and nebula view preserve the same viewport");
Capture("zoom-overlay-update");Width=1120;Height=740;await Task.Delay(150);Capture("minimum-zoom",144);
resetView.RaiseEvent(new RoutedEventArgs(Avalonia.Controls.Button.ClickEvent));Check(viewport.Zoom==1&&viewport.Pan==default,"Reset view resets both zoom and position");
var bounds=resetView.TranslatePoint(default,this)!.Value;
Check(bounds.X>=0&&bounds.X+resetView.Bounds.Width<=Bounds.Width,"Reset view stays visible at minimum window width");
Capture("minimum-reset",144);
await SmokeTest(System.IO.Path.Combine(output,"smoke-checks.txt"));
File.WriteAllLines(System.IO.Path.Combine(output,"interaction-checks.txt"),results);
}
}

View file

@ -23,7 +23,9 @@ public sealed partial class MainWindow:Window
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 PreviewViewport viewport=new();
readonly ExposureView preview,comparison;
readonly Button resetView=Button("Reset view");
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};
@ -43,6 +45,9 @@ public sealed partial class MainWindow:Window
readonly Stack<(Frame Frame,Verdict? Verdict,string Note,DateTime? At)> undo=[];
public MainWindow()
{
Background=TransparencyBackgroundFallback=Palette.Background;
NativeWindowBackground.Apply(this);
preview=new(viewport);comparison=new(viewport);
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);
@ -79,7 +84,8 @@ public sealed partial class MainWindow:Window
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 previewHeading=new Grid{ColumnDefinitions=new("*,Auto,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);
resetView.Padding=new(9,5);resetView.FontSize=11;resetView.Margin=new(10,0,0,0);resetView.Click+=(_,_)=>viewport.Reset();ToolTip.SetTip(resetView,"Reset image zoom and position");Grid.SetColumn(resetView,2);previewHeading.Children.Add(resetView);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);
@ -133,7 +139,7 @@ public sealed partial class MainWindow:Window
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);
// Projects remain saved on disk; each ordinary launch begins with an empty workspace.
}
void RefreshFrames(Frame? prefer=null)
{

View file

@ -0,0 +1,19 @@
using System.Runtime.InteropServices;
using Avalonia.Controls;
namespace AstroFrame.Desktop;
// Avalonia creates a native class without a background brush. Supply the same
// grey used by the content so Windows erases newly exposed pixels before rendering.
internal static class NativeWindowBackground
{
[DllImport("gdi32.dll")]static extern nint CreateSolidBrush(uint color);
[DllImport("user32.dll",EntryPoint="SetClassLongPtrW")]static extern nint SetClassLongPtr(nint window,int index,nint value);
[DllImport("user32.dll",EntryPoint="GetClassLongPtrW")]static extern nint GetClassLongPtr(nint window,int index);
static readonly nint brush=OperatingSystem.IsWindows()?CreateSolidBrush(0x00171615):0;
public static void Apply(Window window)
{
if(OperatingSystem.IsWindows()&&window.TryGetPlatformHandle() is { } handle)SetClassLongPtr(handle.Handle,-10,brush);
}
public static bool IsApplied(Window window)=>!OperatingSystem.IsWindows()||GetClassLongPtr(window.TryGetPlatformHandle()!.Handle,-10)==brush&&brush!=0;
}

View file

@ -0,0 +1,33 @@
using Avalonia;
namespace AstroFrame.Desktop;
// Pan is measured relative to the fitted image, preserving the same image region
// when frames change or the window/comparison pane changes size.
public sealed class PreviewViewport
{
public double Zoom {get;private set;}=1;
public Vector Pan {get;private set;}
public event Action? Changed;
public Rect ImageRect(Rect area,Size image)
{
double fit=Math.Min(area.Width/image.Width,area.Height/image.Height);
double w=image.Width*fit,h=image.Height*fit;
return new(area.Center.X-w*Zoom/2+Pan.X*w,area.Center.Y-h*Zoom/2+Pan.Y*h,w*Zoom,h*Zoom);
}
public void ZoomAt(double delta,Point pointer,Rect area,Size image)
{
var before=ImageRect(area,image);double next=Math.Clamp(Zoom*Math.Pow(1.2,Math.Clamp(delta,-10,10)),1,16);
double factor=next/Zoom;
Zoom=next;
var after=ImageRect(area,image);
Pan+=new Vector((pointer.X-(pointer.X-before.X)*factor-after.X)/(after.Width/Zoom),(pointer.Y-(pointer.Y-before.Y)*factor-after.Y)/(after.Height/Zoom));
Clamp();Changed?.Invoke();
}
public void Drag(Vector pixels,Rect area,Size image)
{
var rect=ImageRect(area,image);Pan+=new Vector(pixels.X/(rect.Width/Zoom),pixels.Y/(rect.Height/Zoom));Clamp();Changed?.Invoke();
}
void Clamp()=>Pan=new Vector(Math.Clamp(Pan.X,-(Zoom-1)/2,(Zoom-1)/2),Math.Clamp(Pan.Y,-(Zoom-1)/2,(Zoom-1)/2));
public void Reset(){Zoom=1;Pan=default;Changed?.Invoke();}
}

View file

@ -11,18 +11,20 @@ namespace AstroFrame.Desktop;
internal static class Program
{
public static string[] Arguments=[];
public static bool Diagnostic=>Arguments.Any(a=>a.StartsWith("--capture",StringComparison.Ordinal)||a=="--smoke"||a=="--verify-ui");
static Mutex? instance;
[STAThread] public static void Main(string[] args)
{
Velopack.VelopackApp.Build().SetAutoApplyOnStartup(false).Run();
Arguments=args;
if(!Diagnostic)Velopack.VelopackApp.Build().SetAutoApplyOnStartup(false).Run();
if(args.Length>=3&&args[0]=="--verify-update"){Environment.ExitCode=UpdateDiagnostics.Run(args).GetAwaiter().GetResult();return;}
instance=new Mutex(true,"AstroFrame.Desktop.OneInstance",out bool created);if(!created)return;
instance=new Mutex(true,Diagnostic?"AstroFrame.Desktop.Diagnostics":"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){try{Directory.CreateDirectory(AppSettings.DataDirectory);File.WriteAllText(System.IO.Path.Combine(AppSettings.DataDirectory,"startup-error.log"),e.ToString());}catch{}Environment.ExitCode=1;}
catch(Exception e){if(Diagnostic)Console.Error.WriteLine(e);else try{Directory.CreateDirectory(AppSettings.DataDirectory);File.WriteAllText(System.IO.Path.Combine(AppSettings.DataDirectory,"startup-error.log"),e.ToString());}catch{}Environment.ExitCode=1;}
finally{instance.ReleaseMutex();instance.Dispose();}
}
}
@ -42,7 +44,15 @@ public sealed class App:Application
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>=2&&Program.Arguments[0]=="--capture-settings")
if(Program.Arguments.Length>=3&&Program.Arguments[0]=="--verify-ui")
{
window.Opened+=async(_,_)=>
{
try{await window.VerifyInteractions(Program.Arguments[1],Program.Arguments[2]);desktop.Shutdown(0);}
catch(Exception e){File.WriteAllText(System.IO.Path.Combine(Program.Arguments[2],"error.txt"),e.ToString());desktop.Shutdown(1);}
};
}
else if(Program.Arguments.Length>=2&&Program.Arguments[0]=="--capture-settings")
{
window.Opened+=async(_,_)=>
{
@ -86,7 +96,6 @@ public sealed class App:Application
};
}
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();
}

View file

@ -22,7 +22,7 @@ public sealed class StarInspector:Window
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);
var detail=await Task.Run(async()=>{using var memory=await ResourcePolicy.Acquire(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,*,*")};

View file

@ -13,7 +13,7 @@ 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 readonly IBrush Update=Brush("#007BA7"),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};
}
@ -85,7 +85,22 @@ public sealed class ExposureView:Control,IDisposable
public bool Nebula {get;set;}
public double Stretch {get;set;}=.18;
public string Caption {get;set;}="";
public ExposureView(){RenderOptions.SetBitmapInterpolationMode(this,BitmapInterpolationMode.HighQuality);}
public PreviewViewport Viewport {get;}
Point? dragStart;IPointer? dragPointer;
Rect ImageArea=>new(0,(Caption!=""?26:0)+(Spatial?22:0),Math.Max(1,Bounds.Width),Math.Max(1,Bounds.Height-(Caption!=""?26:0)-(Spatial?22:0)));
public ExposureView():this(new PreviewViewport()){}
public ExposureView(PreviewViewport viewport)
{
Viewport=viewport;Viewport.Changed+=InvalidateVisual;ClipToBounds=true;
RenderOptions.SetBitmapInterpolationMode(this,BitmapInterpolationMode.HighQuality);
ToolTip.SetTip(this,"Scroll to zoom · Drag to pan · Reset view to fit");
PointerWheelChanged+=(_,e)=>{if(bitmap==null||!ImageArea.Contains(e.GetPosition(this)))return;Viewport.ZoomAt(e.Delta.Y,e.GetPosition(this),ImageArea,bitmap.Size);e.Handled=true;};
PointerPressed+=(_,e)=>{if(bitmap==null||!ImageArea.Contains(e.GetPosition(this))||!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)return;dragStart=e.GetPosition(this);dragPointer=e.Pointer;e.Pointer.Capture(this);Cursor=new Cursor(StandardCursorType.SizeAll);e.Handled=true;};
PointerMoved+=(_,e)=>{if(dragStart is not Point last||bitmap==null)return;var now=e.GetPosition(this);Viewport.Drag(now-last,ImageArea,bitmap.Size);dragStart=now;e.Handled=true;};
PointerReleased+=(_,e)=>{if(dragStart==null)return;EndDrag();e.Handled=true;};
PointerCaptureLost+=(_,_)=>{dragStart=null;dragPointer=null;Cursor=Cursor.Default;};
}
void EndDrag(){dragStart=null;dragPointer?.Capture(null);dragPointer=null;Cursor=Cursor.Default;}
public void Load(string projectDirectory,Frame? f,IReadOnlyList<Frame>? frames=null)
{
Dispose();Frame=f;message=f==null?"Select an exposure":"Loading preview…";InvalidateVisual();
@ -107,7 +122,7 @@ public sealed class ExposureView:Control,IDisposable
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);
using var memory=await ResourcePolicy.Acquire(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),SkyOverlay.LoadMask(directory,f,frames,token));
@ -133,7 +148,8 @@ public sealed class ExposureView:Control,IDisposable
double captionHeight=Caption!=""?26:0,header=captionHeight+(Spatial?22:0);
if(captionHeight>0)c.DrawText(new FormattedText(Caption+" · "+Frame?.Time,System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),10,Palette.Muted),new(8,7));
if(Spatial)c.DrawText(new FormattedText(overlayMask.Length==SkyModel.Count?"Pink: excess sky · Grid: stellar flux":"Sky overlay unavailable · cached reference required",System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),10,Palette.Muted){MaxTextWidth=Math.Max(1,Bounds.Width-16)},new(8,captionHeight+5));
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);
using var imageClip=c.PushClip(ImageArea);
var rect=Viewport.ImageRect(ImageArea,bitmap.Size);double w=rect.Width,h=rect.Height;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;
@ -153,5 +169,5 @@ public sealed class ExposureView:Control,IDisposable
}
}
}
public void Dispose(){request?.Cancel();request?.Dispose();request=null;bitmap?.Dispose();bitmap=null;frameDisplay=nebulaDisplay=null;overlayMask=[];}
public void Dispose(){EndDrag();request?.Cancel();request?.Dispose();request=null;bitmap?.Dispose();bitmap=null;frameDisplay=nebulaDisplay=null;overlayMask=[];}
}

View file

@ -64,12 +64,12 @@ public sealed class Analyzer
Directory.CreateDirectory(System.IO.Path.Combine(directory,"previews"));int done=0;
try
{
int activeWorkers=workers<=0?ResourcePolicy.DefaultWorkers:Math.Clamp(workers,1,4);
int activeWorkers=workers<=0?ResourcePolicy.DefaultWorkers:Math.Clamp(workers,1,ResourcePolicy.DefaultWorkers);
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)));
using var memory=await ResourcePolicy.Acquire(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;}
}

View file

@ -4,10 +4,11 @@ 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 ProcessLimit=>MemoryBudget(PhysicalMemory().Total);
public static int DefaultWorkers=>WorkerLimit(Environment.ProcessorCount);
public static int WorkerLimit(int processors)=>Math.Clamp(processors-2,1,16);
public static long MemoryBudget(long total)=>total>0?Math.Max(0,total-Reserve(total))/65536*65536:GiB;
public static long FrameBudget=>MemoryBudget(PhysicalMemory().Total)/2;
public static long Reserve(long total)=>Math.Min(8*GiB,total/4);
[StructLayout(LayoutKind.Sequential)]struct MemoryStatus
{
@ -24,22 +25,16 @@ public static class ResourcePolicy
}
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 bool CanAnalyze(long total,long available,long estimatedBytes)=>total>0&&estimatedBytes>0&&available>=estimatedBytes&&available-estimatedBytes>=Reserve(total);
public static long EstimateFrameBytes(int width,int height,int scale)=>checked((long)(width/scale)*(height/scale)*16+64L*1024*1024);
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)
{if(width<1||height<1||scale<1||(long)width*height>100_000_000||EstimateFrameBytes(width,height,scale)>FrameBudget)throw new InvalidDataException("Image exceeds the safe per-frame budget for this computer's physical RAM");}
static readonly MemoryAdmission admission=new(() =>
{
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.");
}
var(total,available)=PhysicalMemory();using var process=Process.GetCurrentProcess();
return(total,Math.Min(available,Math.Max(0,MemoryBudget(total)-process.PrivateMemorySize64)+Reserve(total)));
});
public static Task<IDisposable> Acquire(long estimate,CancellationToken ct,Action<string>? report=null)=>admission.Acquire(estimate,ct,report);
[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;}
@ -56,10 +51,43 @@ public static class ResourcePolicy
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());
if(!SetInformationJobObject(job,9,ref limits,size)||!AssignProcessToJobObject(job,Process.GetCurrentProcess().Handle))throw new InvalidOperationException("Cannot enforce the physical RAM 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");
if(!WindowsLimitEnforced)throw new InvalidOperationException("Cannot verify the physical RAM process memory limit");
return true;
}
}
// Reserve each in-flight frame atomically. Available RAM is sampled for every admission,
// so workers cannot all spend the same headroom. Counting full active reservations is
// deliberately conservative even after their allocations appear in OS memory statistics.
public sealed class MemoryAdmission(Func<(long Total,long Available)> memory)
{
readonly object gate=new();long reserved;
public long ReservedBytes {get{lock(gate)return reserved;}}
public async Task<IDisposable> Acquire(long estimate,CancellationToken ct,Action<string>? report=null)
{
if(estimate<=0)throw new ArgumentOutOfRangeException(nameof(estimate));
int idleWaits=0,waits=0;
while(true)
{
ct.ThrowIfCancellationRequested();
var(total,available)=memory();
if(estimate>ResourcePolicy.MemoryBudget(total))throw new ResourcePressureException("This frame exceeds the safe physical RAM budget; completed measurements will be saved.");
lock(gate)
{
if(ResourcePolicy.CanAnalyze(total,available,checked(estimate+reserved)))
{reserved+=estimate;return new Lease(this,estimate);}
idleWaits=reserved==0?idleWaits+1:0;
}
if(waits++%10==0)report?.Invoke($"Paused for RAM headroom · {available/(double)ResourcePolicy.GiB:0.0} GB available · reserving {ResourcePolicy.Reserve(total)/(double)ResourcePolicy.GiB:0.0} GB");
if(idleWaits>=200)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.");
await Task.Delay(100,ct);
}
}
sealed class Lease(MemoryAdmission owner,long bytes):IDisposable
{
int disposed;
public void Dispose(){if(Interlocked.Exchange(ref disposed,1)==0)lock(owner.gate)owner.reserved-=bytes;}
}
}
public sealed class ResourcePressureException(string message):IOException(message);

View file

@ -32,7 +32,7 @@ public static class SpatialReference
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)));
using var memory=await ResourcePolicy.Acquire(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;}
}

View file

@ -5,6 +5,14 @@ using Velopack.Sources;
int passed = 0;
void Check(bool value, string label) { if (!value) throw new Exception(label); Console.WriteLine("PASS " + label); passed++; }
var viewport=new PreviewViewport();var area=new Avalonia.Rect(0,26,600,500);var image=new Avalonia.Size(800,600);var anchor=new Avalonia.Point(365,250);
var beforeZoom=viewport.ImageRect(area,image);viewport.ZoomAt(3,anchor,area,image);var afterZoom=viewport.ImageRect(area,image);
Check(Math.Abs((anchor.X-beforeZoom.X)/beforeZoom.Width-(anchor.X-afterZoom.X)/afterZoom.Width)<1e-10&&Math.Abs((anchor.Y-beforeZoom.Y)/beforeZoom.Height-(anchor.Y-afterZoom.Y)/afterZoom.Height)<1e-10,"zoom preserves the image point under the cursor");
var centerBefore=(area.Center.X-afterZoom.X)/afterZoom.Width;var resized=viewport.ImageRect(new Avalonia.Rect(0,26,300,250),image);
Check(Math.Abs(centerBefore-(150-resized.X)/resized.Width)<1e-10,"resizing preserves the normalized image position");
viewport.ZoomAt(1000,area.Center,area,image);viewport.ZoomAt(1000,area.Center,area,image);Check(viewport.Zoom==16,"zoom stays bounded at maximum magnification");
viewport.Drag(new Avalonia.Vector(1e6,-1e6),area,image);Check(Math.Abs(viewport.Pan.X)<viewport.Zoom/2&&Math.Abs(viewport.Pan.Y)<viewport.Zoom/2,"drag limits keep the image reachable");
viewport.Reset();Check(viewport.Zoom==1&&viewport.Pan==default,"reset restores fitted and centered image");
var temp = Path.Combine(Path.GetTempPath(), "AstroFrame-update-tests-" + Guid.NewGuid());
Directory.CreateDirectory(temp);
try

View file

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
@ -9,7 +9,6 @@
<ItemGroup>
<None Update="Fixtures/*.json" CopyToOutputDirectory="PreserveNewest" />
<ProjectReference Include="../../src/AstroFrame.Engine/AstroFrame.Engine.csproj" />
<RuntimeHostConfigurationOption Include="System.GC.HeapHardLimit" Value="3221225472" />
<RuntimeHostConfigurationOption Include="System.GC.Server" Value="false" />
</ItemGroup>

View file

@ -14,7 +14,7 @@ if(args.Length>0&&args[0]=="profile-workers")
string[] all=Directory.GetFiles(args[1],"*.fit").Order().ToArray();int count=Math.Min(int.Parse(args[2]),all.Length),workers=int.Parse(args[3]);
var files=Enumerable.Range(0,count).Select(i=>all[i*all.Length/count]).ToArray();var summaries=new System.Collections.Concurrent.ConcurrentDictionary<string,int>();var timer=Stopwatch.StartNew();
await Parallel.ForEachAsync(files,new ParallelOptions{MaxDegreeOfParallelism=workers},async(path,ct)=>
{var f=Fits.Inspect(path);await ResourcePolicy.WaitForHeadroom(ResourcePolicy.EstimateFrameBytes(f.Width,f.Height,2),ct);new StellarDetector().Measure(f,Fits.Read(path,ct),ct);summaries[f.Name]=f.StarCount;});
{var f=Fits.Inspect(path);using var memory=await ResourcePolicy.Acquire(ResourcePolicy.EstimateFrameBytes(f.Width,f.Height,2),ct);new StellarDetector().Measure(f,Fits.Read(path,ct),ct);summaries[f.Name]=f.StarCount;});
using var process=Process.GetCurrentProcess();Console.WriteLine(JsonSerializer.Serialize(new{workers,count,elapsedSeconds=timer.Elapsed.TotalSeconds,peakWorkingMiB=process.PeakWorkingSet64/1048576.0,peakPrivateMiB=process.PeakPagedMemorySize64/1048576.0,logicalProcessors=Environment.ProcessorCount,starCounts=summaries.OrderBy(x=>x.Key).Select(x=>x.Value)}));return;
}
if(args.Length>0&&args[0]=="resources")
@ -42,7 +42,7 @@ if(args.Length>0&&args[0]=="analyze")
var p=await new Analyzer().AnalyzeAsync(source,directory,existing,
new DirectProgress(x=>{int pct=x.Total==0?0:x.Done*100/x.Total;if(pct/10!=last){last=pct/10;Console.WriteLine($"{x.Stage}: {x.Done}/{x.Total}");}}),CancellationToken.None);
File.WriteAllText(Path.Combine(directory,"decisions.csv"),Export.Manifest(p));
using var process=Process.GetCurrentProcess();var report=new {elapsedSeconds=watch.Elapsed.TotalSeconds,peakWorkingMB=process.PeakWorkingSet64/(1024.0*1024),peakCommittedMB=process.PeakPagedMemorySize64/(1024.0*1024),processLimitMB=ResourcePolicy.ProcessLimit/(1024*1024),heapLimitMB=ResourcePolicy.HeapLimit/(1024*1024),windowsLimitEnforced=ResourcePolicy.WindowsLimitEnforced,engine=Project.EngineVersion,validation="Unlabeled exploratory results; no evidence of stack parity",sessions=p.Frames.GroupBy(f=>f.Session).Select(g=>new{session=g.Key,frames=g.Count(),keep=g.Count(f=>f.Effective==Verdict.Keep),review=g.Count(f=>f.Effective==Verdict.Review),reject=g.Count(f=>f.Effective==Verdict.Reject),totalMinutes=g.Sum(f=>f.Exposure)/60,keepMinutes=g.Where(f=>f.Effective==Verdict.Keep).Sum(f=>f.Exposure)/60,stars=Range(g.Select(f=>(double)f.StarCount)),fwhm=Range(g.Select(f=>f.Fwhm)),flux=Range(g.Select(f=>f.Transparency)),matching=Range(g.Select(f=>f.MatchFraction)),causes=g.GroupBy(f=>f.Cause).ToDictionary(x=>x.Key,x=>x.Count())})};
using var process=Process.GetCurrentProcess();var report=new {elapsedSeconds=watch.Elapsed.TotalSeconds,peakWorkingMB=process.PeakWorkingSet64/(1024.0*1024),peakCommittedMB=process.PeakPagedMemorySize64/(1024.0*1024),processLimitMB=ResourcePolicy.ProcessLimit/(1024*1024),heapLimitMB=GC.GetGCMemoryInfo().TotalAvailableMemoryBytes/(1024*1024),windowsLimitEnforced=ResourcePolicy.WindowsLimitEnforced,engine=Project.EngineVersion,validation="Unlabeled exploratory results; no evidence of stack parity",sessions=p.Frames.GroupBy(f=>f.Session).Select(g=>new{session=g.Key,frames=g.Count(),keep=g.Count(f=>f.Effective==Verdict.Keep),review=g.Count(f=>f.Effective==Verdict.Review),reject=g.Count(f=>f.Effective==Verdict.Reject),totalMinutes=g.Sum(f=>f.Exposure)/60,keepMinutes=g.Where(f=>f.Effective==Verdict.Keep).Sum(f=>f.Exposure)/60,stars=Range(g.Select(f=>(double)f.StarCount)),fwhm=Range(g.Select(f=>f.Fwhm)),flux=Range(g.Select(f=>f.Transparency)),matching=Range(g.Select(f=>f.MatchFraction)),causes=g.GroupBy(f=>f.Cause).ToDictionary(x=>x.Key,x=>x.Count())})};
string json=JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true});File.WriteAllText(Path.Combine(directory,"report.json"),json);Console.WriteLine(json);return;
}
if(args.Length>0&&args[0]=="benchmark")
@ -69,6 +69,22 @@ Check(!OperatingSystem.IsWindows()||ResourcePolicy.WindowsLimitEnforced,"Windows
Check(ResourcePolicy.Reserve(32*ResourcePolicy.GiB)==8*ResourcePolicy.GiB,"32 GB machines reserve 8 GB physical RAM");
Check(!ResourcePolicy.CanAnalyze(32*ResourcePolicy.GiB,7*ResourcePolicy.GiB,32*1024*1024),"low physical RAM pauses analysis");
Check(ResourcePolicy.CanAnalyze(32*ResourcePolicy.GiB,12*ResourcePolicy.GiB,32*1024*1024),"sufficient RAM allows bounded analysis");
Check(ResourcePolicy.MemoryBudget(32*ResourcePolicy.GiB)==24*ResourcePolicy.GiB&&ResourcePolicy.MemoryBudget(64*ResourcePolicy.GiB)==56*ResourcePolicy.GiB,"memory ceiling scales beyond 6 GB with installed RAM");
Check(ResourcePolicy.MemoryBudget(4*ResourcePolicy.GiB)==3*ResourcePolicy.GiB,"small computers retain physical RAM headroom");
Check(ResourcePolicy.WorkerLimit(16)>4&&ResourcePolicy.WorkerLimit(2)==1&&ResourcePolicy.WorkerLimit(64)==16,"worker count scales with CPU while leaving capacity for desktop work");
var admission=new MemoryAdmission(()=>(8*ResourcePolicy.GiB,4*ResourcePolicy.GiB));
using(var first=await admission.Acquire(2*ResourcePolicy.GiB,CancellationToken.None))
{
using var cancel=new CancellationTokenSource();var second=admission.Acquire(ResourcePolicy.GiB,cancel.Token);
await Task.Delay(120);Check(!second.IsCompleted,"concurrent frames cannot spend the same RAM headroom");
cancel.Cancel();bool canceled=false;try{await second;}catch(OperationCanceledException){canceled=true;}Check(canceled&&admission.ReservedBytes==2*ResourcePolicy.GiB,"waiting frames cancel without leaking reservations");
}
Check(admission.ReservedBytes==0,"completed frames release RAM admission");
using(var next=await admission.Acquire(ResourcePolicy.GiB,CancellationToken.None)){next.Dispose();next.Dispose();Check(admission.ReservedBytes==0,"RAM leases release only once");}
long free=ResourcePolicy.GiB;var changing=new MemoryAdmission(()=>(8*ResourcePolicy.GiB,Interlocked.Read(ref free)));
var waiting=changing.Acquire(ResourcePolicy.GiB,CancellationToken.None);await Task.Delay(120);Check(!waiting.IsCompleted,"external memory pressure pauses allocation");
Interlocked.Exchange(ref free,4*ResourcePolicy.GiB);using(var resumed=await waiting.WaitAsync(TimeSpan.FromSeconds(2)))Check(changing.ReservedBytes==ResourcePolicy.GiB,"available RAM increases resume processing dynamically");
var ample=new MemoryAdmission(()=>(64*ResourcePolicy.GiB,40*ResourcePolicy.GiB));using(var large=await ample.Acquire(8*ResourcePolicy.GiB,CancellationToken.None))Check(ample.ReservedBytes>6*ResourcePolicy.GiB,"large machines admit work beyond the former fixed ceiling");
bool budgetRefused=false;try{ResourcePolicy.CheckFrame(16000,16000,1);}catch(InvalidDataException){budgetRefused=true;}Check(budgetRefused,"oversized images refused before allocating pixels");
var trend=Enumerable.Range(0,121).Select(i=>Synthetic(i,1-i*.002,160,1000+i*3)).ToList();Classification.Run(trend);
Check(trend.All(f=>f.Automatic!=Verdict.Reject),"gradual transparency and background trends do not reject");