Release 1.1.4: replace noisy preview modes with patch denoising and fixed stretch
All checks were successful
Release AstroFrame / packages (push) Successful in 59s

This commit is contained in:
Elijah 2026-10-04 14:27:04 -07:00
parent d3362c8341
commit b8ffe97c46
17 changed files with 143 additions and 270 deletions

View file

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

View file

@ -22,7 +22,7 @@ To analyze another dataset, choose **Analyze lights**, select the folder contain
- Select a quality measurement and click the graph to inspect an exposure. One graph shows the selected metric, including stellar flux when selected. Capture order uses UTC timestamps; gaps between sessions are marked rather than drawn to elapsed-time scale.
- 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. **Nebula view** suppresses small stars and noise, then stretches faint structure without reducing the preview dimensions. **Asinh view** offers a different stretch with softer highlights. **Color nebula** uses the FITS Bayer channels, neutralizes the sky and smooths uncertain color; monochrome files fall back to grayscale. Adjust **Preview stretch** to brighten any view. These controls never affect measurements, classifications or original files. Single exposures can still be noisy, and the color is a viewing aid rather than calibrated astrophotography.
- Use **Frame view** for the default area-averaged grayscale preview, or **Denoised** for an alternative that reduces noise using similar nearby image patches. Denoised keeps its stretch parameters from the original thumbnail and is slightly brighter by default. Adjust **Preview stretch** in either view. Both comparison panes use the same viewing mode. 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.

View file

@ -57,11 +57,11 @@ Version 1.1.0 selects up to 16 workers from CPU capacity, leaving two logical pr
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.
Display caches have a separate version. They contain compressed, linear, area-averaged thumbnails rather than a permanently stretched byte image. **Frame view** retains its noise-aware black point and adjustable median brightness. **Nebula view** applies a 3×3 median and four separable binomial smoothing passes at the existing thumbnail dimensions, suppressing small stars and noise while retaining faint filaments. Its black point also includes the lower background percentile, and its median is displayed slightly brighter. **Asinh view** applies an adjustable inverse-hyperbolic-sine transfer to this same smoothed plane, with a brightness-adjusted gamma fallback when its normalized median already exceeds the requested brightness.
Display caches have a separate version. They contain compressed, linear, area-averaged thumbnails rather than a permanently stretched byte image. **Frame view** retains its noise-aware black point and adjustable median brightness. **Denoised** is the only alternative. It performs non-local means on the linear thumbnail using 5×5 patches, a 13×13 search window, reflected borders, noise-bias subtraction and a filter strength of 0.8 times the estimated noise sigma. Its black point, white point and normalized median come from the original thumbnail; they are never recomputed from the denoised result. This prevents the stretch from amplifying residual noise after denoising. It adds 0.07 to the requested display median, matching the approved samples' default brightness of 0.25 at slider value 0.18.
**Color nebula** reads recognized RGGB, GRBG, GBRG or BGGR Bayer layouts and their offsets through a separate streaming display reader. It bins linear RGB superpixels, uses the same diffuse luminance preview, neutralizes each channel's median sky, smooths chroma and suppresses departures consistent with noise. A linked channel scale limits saturation and preserves neutral black and white highlights. Color is approximate and uncalibrated; no color is invented for monochrome or unknown Bayer layouts, which show the grayscale nebula preview with an explanatory label. Color has a separate fingerprinted linear cache generated only on demand. Neither display reader changes the monochrome analysis path, classifications, or original FITS files.
The previous Nebula, Asinh and Color nebula modes are removed. The denoised result stays in the selected viewer's memory and is computed only when requested. It needs no new disk cache or FITS reader and works on monochrome and Bayer-derived grayscale thumbnails alike. Existing linear caches remain compatible, and existing color caches are simply unused. The analysis path, classifications and original FITS files are unaffected.
Prepared display statistics are cached in the viewer so slider changes remain responsive. Disk loading and first-time thumbnail creation run off the UI thread, with cancellation and a single preview-loading gate preventing queued FITS reads during rapid navigation. Both comparison panes use the selected mode and shared zoom/pan. Old projects regenerate only requested displays on demand. Single-frame previews cannot recover signal absent from the exposure and can remain noisy; these are human-readable viewing aids, not stacked images.
Prepared display statistics and the denoised plane are retained in the viewer so slider changes remain responsive. Loading and denoising run off the UI thread, with cancellation, atomic memory reservations and a single preview-loading gate preventing queued work during rapid navigation. The original Frame preview remains available while denoising runs. Both comparison panes use the selected mode and shared zoom/pan. Old projects regenerate only requested displays on demand. Denoising is a viewing aid and may soften weak detail; Frame view and source-star inspection remain available for judging unfiltered morphology.
The preview is not an input to classification. Source-star inspection reads two originals, maps identical stars through their stored alignment, and displays enlarged source superpixels without interpolation. Crops are independently normalized to judge morphology. See [Siril's screen-transfer discussion](https://siril.readthedocs.io/en/latest/processing/stretching.html) for the distinction between display stretching and linear image data.

View file

@ -2,7 +2,7 @@
The owner selected the Graphite Studio palette and Plum Atlas layout from the standalone concepts. The application combines their charcoal backgrounds, silver accents, restrained decision colors, compact summaries and three-column workspace. The exposure queue is on the left, the largest column holds the preview, and the right column contains one selectable quality graph above permanently accessible evidence and measurements. A compact selector above the workspace switches sessions, including All sessions. Filtering, sorting, graph selection, keyboard review, saved overrides, undo and accepted-frame export remain available.
Frame/Nebula view, cloud overlay and nearby comparison sit above the preview. Preview stretch has a dedicated 48-pixel row below it and a visible silver thumb. The single verdict/time caption, filename and decision buttons follow the stretch. Long evidence lines present a concise first clause, with their complete engine-generated message available on hover. The evidence panel scrolls when needed; no measurements or saved explanations are discarded.
The Frame view / Denoised dropdown, cloud overlay and nearby comparison sit above the preview. Denoised uses the approved patch-based noise reduction with the original thumbnail's stretch parameters. Nebula, Asinh and Color nebula options are removed. Preview stretch has a dedicated 48-pixel row below it and a visible silver thumb. The single verdict/time caption, filename and decision buttons follow the stretch. Long evidence lines present a concise first clause, with their complete engine-generated message available on hover. The evidence panel scrolls when needed; no measurements or saved explanations are discarded.
The header now has a plain graphite background. Its height is reduced from 100 to 74 logical pixels: a 36-pixel native caption row and a 38-pixel project/action row. The project name and light/session counts sit on one line. Removing the photographic background also removes its display-bitmap allocation; the original asset remains preserved with the standalone design concepts.

View file

@ -0,0 +1,9 @@
# AstroFrame 1.1.4
- Keep the preview dropdown with just **Frame view** and **Denoised**. Remove Nebula view, Asinh view and Color nebula.
- Add the approved patch-based denoising alternative. Keep the stretch parameters derived from the original thumbnail so residual noise is not amplified into blotches. The denoised preview is slightly brighter by default and still supports the Preview stretch slider.
- Apply the selected mode to both comparison panes, preserving zoom, pan and overlays. Compute denoising in the background only when requested, reuse it for brightness changes, and cancel obsolete work when switching exposures.
Frame view's rendering and existing linear caches are unchanged. Display processing never changes original FITS files, quality measurements, classifications or manual decisions.
Validation: 95 engine, 23 updater, 10 mocked publisher and 65 isolated Windows interaction checks, with rendering at 96 and 144 DPI. Covers noise reduction, retained stretch parameters, stars and diffuse signal, constant fields, reflected borders, input preservation and cancellation. Across 11 exposures from all seven sample targets, the production renderer matches the approved samples within one gray level out of 255; Frame outputs match their previous pixels exactly. Verification uses workspace fixtures and leaves the installed app untouched. The server workflow builds Windows and Linux packages and checks the packaged Linux settings page.

View file

@ -127,7 +127,7 @@ For preview and processing-status changes, build the source and run the isolated
./tools/Verify-Preview.ps1 -FixtureProject 'path/to/saved-project' -Output artifacts/preview-verification
```
This checks comparison overlays, zoom/pan, all four preview modes in both panes, Bayer color loading across frame changes, monochrome fallback, processing-memory visibility, elongation crops and guide toggling, absent comparisons, loading cancellation, and native window controls. It renders normal and minimum-size controls at 96 and 144 DPI. Inspect the PNG files in the output's `qa` directory. It launches only the source build in diagnostic mode, which bypasses installed settings and updates. Source `--capture` diagnostics accept `--preview=0` (Frame), `1` (Nebula), `2` (Asinh) or `3` (Color nebula) for real-exposure visual checks against copied workspace projects.
This checks comparison overlays, zoom/pan, Frame and Denoised in both panes, on-demand denoising, rapid frame/mode changes, monochrome sources, processing-memory visibility, elongation crops and guide toggling, absent comparisons, loading cancellation, and native window controls. It renders normal and minimum-size controls at 96 and 144 DPI. Inspect the PNG files in the output's `qa` directory. It launches only the source build in diagnostic mode, which bypasses installed settings and updates. Source `--capture` diagnostics accept `--preview=0` (Frame) or `--preview=1` (Denoised) for real-exposure visual checks against copied workspace projects.
`./tools/Verify-ReleaseAutomation.ps1` exercises version/tag mismatch, upload failure, draft resumption, conflicting assets, immutable published releases and package integrity with a mocked release API. It never publishes a real release.

View file

@ -27,6 +27,7 @@ public sealed partial class MainWindow
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");
Check(preview.Mode==AstroFrame.Engine.PreviewMode.Frame&&!preview.HasDenoised&&!comparison.HasDenoised,"Frame is the default and does not compute denoising before selection");
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);
@ -42,7 +43,7 @@ public sealed partial class MainWindow
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");
Check(preview.Viewport==comparison.Viewport&&viewport.Zoom==zoom&&viewport.Pan==pan,"comparison, overlay and denoised view preserve the same viewport");
Capture("comparison-overlay");
Check(preview.Spatial&&comparison.Spatial&&comparison.HasImage,"Overlay applies to both loaded comparison frames");
Capture("zoom-overlay-update");Width=1120;Height=740;await Task.Delay(150);Capture("minimum-zoom",144);
@ -54,23 +55,23 @@ public sealed partial class MainWindow
spatial.IsChecked=true;compare.IsChecked=false;compare.IsChecked=true;Select(visible[0]);await WaitForPreviews();await Task.Delay(150);
Check(preview.Spatial&&comparison.Spatial&&comparison.HasImage,"Overlay persists on both panes after toggling comparison and changing frame");
Capture("comparison-fit",144);
double retainedZoom=viewport.Zoom;var retainedPan=viewport.Pan;previewMode.SelectedIndex=2;
Check(preview.Mode==AstroFrame.Engine.PreviewMode.Asinh&&comparison.Mode==preview.Mode&&viewport.Zoom==retainedZoom&&viewport.Pan==retainedPan,"Asinh view switches both panes without changing zoom or pan");Capture("asinh-comparison",144);
previewMode.SelectedIndex=3;await WaitForPreviews();await Task.Delay(100);
Check(preview.Mode==AstroFrame.Engine.PreviewMode.Color&&comparison.Mode==preview.Mode&&preview.HasColor&&comparison.HasColor,"Color nebula loads real Bayer RGB for both comparison frames");Capture("color-comparison",144);
Select(visible[1]);await WaitForPreviews();Check(preview.HasColor&&comparison.HasColor&&preview.Mode==AstroFrame.Engine.PreviewMode.Color,"color mode survives exposure changes and cached previews");
foreach(var frame in visible.Take(6))Select(frame);previewMode.SelectedIndex=2;previewMode.SelectedIndex=3;await WaitForPreviews();
Check(preview.HasColor&&comparison.HasColor&&preview.Frame==selected&&preview.Mode==AstroFrame.Engine.PreviewMode.Color,"rapid exposure and mode changes cancel stale color requests and retain the latest preview");
Check(previewMode.Items.Cast<string>().SequenceEqual(new[]{"Frame view","Denoised"}),"preview dropdown contains only Frame view and Denoised");
Check(preview.HasDenoised&&comparison.HasDenoised&&preview.Mode==AstroFrame.Engine.PreviewMode.Denoised&&comparison.Mode==preview.Mode,"Denoised applies to both comparison panes");Capture("denoised-comparison",144);
double retainedZoom=viewport.Zoom;var retainedPan=viewport.Pan;previewMode.SelectedIndex=0;previewMode.SelectedIndex=1;await WaitForPreviews();
Check(viewport.Zoom==retainedZoom&&viewport.Pan==retainedPan,"switching Frame and Denoised retains shared zoom and pan");
Select(visible[1]);await WaitForPreviews();Check(preview.HasDenoised&&comparison.HasDenoised,"denoised mode survives exposure changes");
foreach(var frame in visible.Take(6))Select(frame);previewMode.SelectedIndex=0;previewMode.SelectedIndex=1;await WaitForPreviews();
Check(preview.HasDenoised&&comparison.HasDenoised&&preview.Frame==selected,"rapid exposure and mode changes cancel stale denoising and retain the latest preview");
Select(visible[1]);await WaitForPreviews();
previewMode.SelectedIndex=0;Check(preview.Mode==AstroFrame.Engine.PreviewMode.Frame&&comparison.Mode==preview.Mode,"Frame view restores both original grayscale previews");previewMode.SelectedIndex=1;
previewMode.SelectedIndex=0;Check(preview.Mode==AstroFrame.Engine.PreviewMode.Frame&&comparison.Mode==preview.Mode,"Frame view restores both original grayscale previews");
string monoPath=System.IO.Path.Combine(output,"mono-source.fit");var monoBytes=File.ReadAllBytes(selected!.Path);
using(var sourceStream=File.OpenRead(selected.Path))
{
var(_,headerBytes)=AstroFrame.Engine.Fits.ReadHeader(sourceStream);
for(int offset=0;offset<headerBytes;offset+=80)if(System.Text.Encoding.ASCII.GetString(monoBytes,offset,8)=="BAYERPAT")System.Text.Encoding.ASCII.GetBytes("COMMENT ").CopyTo(monoBytes,offset);
}
File.WriteAllBytes(monoPath,monoBytes);var monoFrame=AstroFrame.Engine.Fits.Inspect(monoPath);var monoView=new ExposureView();monoView.SetMode(AstroFrame.Engine.PreviewMode.Color);monoView.Load(output,monoFrame);await monoView.Loading;
Check(monoView.HasImage&&!monoView.HasColor&&monoView.Mode==AstroFrame.Engine.PreviewMode.Color,"color mode falls back to readable grayscale for a monochrome FITS source");monoView.Dispose();
File.WriteAllBytes(monoPath,monoBytes);var monoFrame=AstroFrame.Engine.Fits.Inspect(monoPath);var monoView=new ExposureView();monoView.SetMode(AstroFrame.Engine.PreviewMode.Denoised);monoView.Load(output,monoFrame);await monoView.Loading;
Check(monoView.HasImage&&monoView.HasDenoised,"Denoised works with monochrome FITS sources");monoView.Dispose();previewMode.SelectedIndex=1;
Busy(true);progress.Value=57;status.Text="Analyzing lights · 57 / 100 · "+selected!.Name;await Task.Delay(1100);
Check(memoryUsage.IsVisible&&memoryTimer.IsEnabled&&memoryUsage.Text!.StartsWith("Memory: ")&&memoryUsage.Text.EndsWith(" MB"),"processing shows a live process memory statistic");
Check(!inspectElongation.IsEnabled,"star inspection is disabled during processing");

View file

@ -30,7 +30,7 @@ public sealed partial class MainWindow:Window
readonly DispatcherTimer memoryTimer=new(){Interval=TimeSpan.FromSeconds(1)};
StarInspector? starInspector;
readonly Border previewPanel,comparisonBorder,previewControls;
readonly ComboBox previewMode=new(){ItemsSource=new[]{"Frame view","Nebula view","Asinh view","Color nebula"},SelectedIndex=0,MinWidth=150};
readonly ComboBox previewMode=new(){ItemsSource=new[]{"Frame view","Denoised"},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)};
@ -59,7 +59,7 @@ public sealed partial class MainWindow:Window
// 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.SetMode((PreviewMode)Math.Max(0,previewMode.SelectedIndex));comparison.SetMode((PreviewMode)Math.Max(0,previewMode.SelectedIndex));};
ToolTip.SetTip(previewMode,"Frame: original grayscale stretch. Nebula: smooth faint detail with less star dominance. Asinh: an alternative smooth stretch. Color: sky-neutralized Bayer RGB when available. Display options do not change analysis.");
ToolTip.SetTip(previewMode,"Frame: original grayscale preview. Denoised: reduce preview noise while keeping the original stretch parameters. Display options do not change analysis.");
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;
@ -170,9 +170,9 @@ public sealed partial class MainWindow:Window
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)
public void CaptureExposure(string filename)
{
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);
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=0;frames.SelectedItem=f;Select(f);
}
public Task WaitForPreviews()=>Task.WhenAll(preview.Loading,comparison.Loading);
public void CaptureMetric(string name)
@ -181,7 +181,7 @@ public sealed partial class MainWindow:Window
if(index<0)throw new ArgumentException("Unknown quality metric",nameof(name));metric.SelectedIndex=index;
}
public void CapturePreviewMode(int mode)
{if(mode<0||mode>3)throw new ArgumentOutOfRangeException(nameof(mode));previewMode.SelectedIndex=mode;}
{if(mode<0||mode>1)throw new ArgumentOutOfRangeException(nameof(mode));previewMode.SelectedIndex=mode;}
public async Task SmokeTest(string report)
{
if(project==null)throw new InvalidOperationException("Project not loaded");
@ -202,7 +202,7 @@ public sealed partial class MainWindow:Window
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");
previewMode.SelectedIndex=1;displayStretch.Value=.26;await WaitForPreviews();Check(preview.Mode==PreviewMode.Denoised&&Math.Abs(preview.Stretch-.26)<.001,"denoised 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");

View file

@ -78,7 +78,7 @@ public sealed class App:Application
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"));
if(Program.Arguments[3].EndsWith(".fit",StringComparison.OrdinalIgnoreCase))window.CaptureExposure(Program.Arguments[3]);
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..]);

View file

@ -74,10 +74,8 @@ public sealed class ExposureView:Control,IDisposable
{
static readonly SemaphoreSlim LoadGate=new(1);
WriteableBitmap? bitmap;
PreviewDisplay? frameDisplay,nebulaDisplay;
ColorPreviewDisplay? colorDisplay;
bool colorAttempted;
string directory="";
PreviewDisplay? frameDisplay,denoisedDisplay;
bool denoiseAttempted;
byte[] overlayMask=[];
CancellationTokenSource? request;
string message="Select an exposure";
@ -86,13 +84,12 @@ public sealed class ExposureView:Control,IDisposable
public Frame? Frame {get;private set;}
public bool Spatial {get;set;}
public PreviewMode Mode {get;private set;}
public bool Nebula {get=>Mode==PreviewMode.Nebula;set=>SetMode(value?PreviewMode.Nebula:PreviewMode.Frame);}
public bool HasColor=>colorDisplay!=null;
public bool HasDenoised=>denoisedDisplay!=null;
public double Stretch {get;set;}=.18;
public string Caption {get;set;}="";
public PreviewViewport Viewport {get;}
Point? dragStart;IPointer? dragPointer;
string ModeNote=>Mode switch{PreviewMode.Nebula=>"Faint detail · smoothed",PreviewMode.Asinh=>"Asinh · smoothed",PreviewMode.Color=>colorDisplay!=null?"Color · neutral sky":colorAttempted?"Color unavailable · grayscale":"Loading color…",_=>""};
string ModeNote=>Mode==PreviewMode.Denoised?(denoisedDisplay!=null?"Denoised preview":denoiseAttempted?"Denoising unavailable":"Denoising…"):"";
Rect ImageArea=>new(0,(Caption!=""?26:0)+(Spatial?22:0)+(ModeNote!=""?20:0),Math.Max(1,Bounds.Width),Math.Max(1,Bounds.Height-(Caption!=""?26:0)-(Spatial?22:0)-(ModeNote!=""?20:0)));
public ExposureView():this(new PreviewViewport()){}
public ExposureView(PreviewViewport viewport)
@ -109,7 +106,7 @@ public sealed class ExposureView:Control,IDisposable
void EndDrag(){dragStart=null;dragPointer?.Capture(null);dragPointer=null;Cursor=Cursor.Default;}
public void Load(string projectDirectory,Frame? f,IReadOnlyList<Frame>? frames=null)
{
Dispose();directory=projectDirectory;Frame=f;message=f==null?"Select an exposure":"Loading preview…";InvalidateVisual();
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,frames??[],request.Token);
}
@ -118,7 +115,7 @@ public sealed class ExposureView:Control,IDisposable
try
{
await LoadGate.WaitAsync(token);
(PreviewDisplay Frame,PreviewDisplay Nebula,byte[] Overlay) prepared;
(PreviewDisplay Frame,byte[] Overlay) prepared;
try
{
prepared=await Task.Run(async()=>
@ -131,12 +128,12 @@ public sealed class ExposureView:Control,IDisposable
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,false,token),PreviewRenderer.Prepare(plane,true,token),SkyOverlay.LoadMask(directory,f,frames,token));
token.ThrowIfCancellationRequested();return(PreviewRenderer.Prepare(plane,token),SkyOverlay.LoadMask(directory,f,frames,token));
},token);
}
finally{LoadGate.Release();}
token.ThrowIfCancellationRequested();frameDisplay=prepared.Frame;nebulaDisplay=prepared.Nebula;overlayMask=prepared.Overlay;RefreshDisplay();
if(Mode==PreviewMode.Color)await LoadColor(directory,f,token);
token.ThrowIfCancellationRequested();frameDisplay=prepared.Frame;overlayMask=prepared.Overlay;RefreshDisplay();
if(Mode==PreviewMode.Denoised)await LoadDenoised(token);
}
catch(OperationCanceledException){}
catch(Exception e){if(!token.IsCancellationRequested){message="Preview unavailable: "+e.Message;InvalidateVisual();}}
@ -144,44 +141,37 @@ public sealed class ExposureView:Control,IDisposable
public void SetMode(PreviewMode mode)
{
Mode=mode;RefreshDisplay();InvalidateVisual();
if(mode==PreviewMode.Color&&!colorAttempted&&Frame is {} frame&&request is {} active)
{var previous=Loading;Loading=LoadColorAfter(previous,directory,frame,active.Token);}
if(mode==PreviewMode.Denoised&&!denoiseAttempted&&request is {} active)
{var previous=Loading;Loading=LoadDenoisedAfter(previous,active.Token);}
}
async Task LoadColorAfter(Task previous,string projectDirectory,Frame frame,CancellationToken token)
{await previous;if(!token.IsCancellationRequested)await LoadColor(projectDirectory,frame,token);}
async Task LoadColor(string projectDirectory,Frame frame,CancellationToken token)
async Task LoadDenoisedAfter(Task previous,CancellationToken token)
{await previous;if(!token.IsCancellationRequested)await LoadDenoised(token);}
async Task LoadDenoised(CancellationToken token)
{
try
{
await LoadGate.WaitAsync(token);
try
{
if(colorAttempted)return;
if(denoiseAttempted||frameDisplay is not {} original)return;
var prepared=await Task.Run(async()=>
{
var info=new FileInfo(frame.Path);if(!info.Exists||info.Length!=frame.Length||info.LastWriteTimeUtc.Ticks!=frame.Modified)throw new IOException("Source changed; reanalyze before inspecting");
string path=ColorPreview.PathFor(projectDirectory,frame);ColorPreviewPlane? color=null;
try{if(File.Exists(path))color=ColorPreview.Read(path,frame);}catch(IOException){}
if(color==null)
{
using var memory=await ResourcePolicy.Acquire(ResourcePolicy.EstimateFrameBytes(frame.Width,frame.Height,2),token);
color=ColorPreview.ReadFits(frame.Path,token);token.ThrowIfCancellationRequested();if(color!=null)ColorPreview.Write(color,path,frame);
}
return color==null?null:ColorPreview.Prepare(color,token);
using var memory=await ResourcePolicy.Acquire(64L*1024*1024+original.Plane.Pixels.LongLength*40,token);
return DenoisedPreview.Prepare(original,token);
},token);
token.ThrowIfCancellationRequested();colorDisplay=prepared;colorAttempted=true;RefreshDisplay();InvalidateVisual();
token.ThrowIfCancellationRequested();denoisedDisplay=prepared;denoiseAttempted=true;RefreshDisplay();InvalidateVisual();
}
finally{LoadGate.Release();}
}
catch(OperationCanceledException){}
catch(Exception){if(!token.IsCancellationRequested){colorAttempted=true;RefreshDisplay();InvalidateVisual();}}
catch(Exception){if(!token.IsCancellationRequested){denoiseAttempted=true;RefreshDisplay();InvalidateVisual();}}
}
public void RefreshDisplay()
{
var display=Mode==PreviewMode.Frame?frameDisplay:nebulaDisplay;if(display==null)return;
bool color=Mode==PreviewMode.Color&&colorDisplay!=null;byte[] pixels=color?ColorPreview.Render(colorDisplay!,Stretch):PreviewRenderer.Render(display,Stretch,Mode==PreviewMode.Asinh);int w=color?colorDisplay!.Luminance.Plane.Width:display.Plane.Width,h=color?colorDisplay!.Luminance.Plane.Height:display.Plane.Height;bitmap?.Dispose();
var display=Mode==PreviewMode.Denoised&&denoisedDisplay!=null?denoisedDisplay: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++){if(color)Array.Copy(pixels,y*w*4,row,0,row.Length);else 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();
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)
{
@ -212,5 +202,5 @@ public sealed class ExposureView:Control,IDisposable
}
}
}
public void Dispose(){EndDrag();request?.Cancel();request?.Dispose();request=null;bitmap?.Dispose();bitmap=null;frameDisplay=nebulaDisplay=null;colorDisplay=null;colorAttempted=false;overlayMask=[];}
public void Dispose(){EndDrag();request?.Cancel();request?.Dispose();request=null;bitmap?.Dispose();bitmap=null;frameDisplay=denoisedDisplay=null;denoiseAttempted=false;overlayMask=[];}
}

View file

@ -1,106 +0,0 @@
using System.Buffers.Binary;
using System.Globalization;
using System.IO.Compression;
using System.Runtime.InteropServices;
namespace AstroFrame.Engine;
public sealed record ColorPreviewPlane(int Width,int Height,float[] Red,float[] Green,float[] Blue);
public sealed record ColorPreviewDisplay(PreviewDisplay Luminance,float[][] Chroma,double ChromaThreshold);
/// <summary>Display-only Bayer binning. Does not alter the monochrome analysis reader or caches.</summary>
public static class ColorPreview
{
const int Magic=0x41504331;
public static ColorPreviewPlane? ReadFits(string path,CancellationToken ct=default)
{
using var stream=File.OpenRead(path);var(header,_)=Fits.ReadHeader(stream);
double Number(string key,double fallback=0)=>header.TryGetValue(key,out var value)&&double.TryParse(value.Replace('D','E'),NumberStyles.Float,CultureInfo.InvariantCulture,out double number)?number:fallback;
string pattern=header.GetValueOrDefault("BAYERPAT","").Trim().ToUpperInvariant();
if(pattern is not ("RGGB" or "GRBG" or "GBRG" or "BGGR"))return null;
int w=(int)Number("NAXIS1"),h=(int)Number("NAXIS2"),bit=(int)Number("BITPIX");
if(Number("NAXIS")!=2||w<32||h<32||(long)w*h>100_000_000)throw new InvalidDataException("Unsupported color preview dimensions");
if(bit is not (8 or 16 or 32 or -32 or -64))throw new InvalidDataException("Unsupported FITS BITPIX");
int bytes=Math.Abs(bit)/8,uw=w/2,uh=h/2,step=Math.Max((uh+899)/900,(int)Math.Ceiling(Math.Sqrt((double)uw*uh/2_000_000))),ow=(uw+step-1)/step,oh=(uh+step-1)/step;
if(stream.Length-stream.Position<(long)w*h*bytes)throw new InvalidDataException("Truncated FITS pixels");
double zero=Number("BZERO"),factor=Number("BSCALE",1);int ox=((int)Number("XBAYROFF")%2+2)%2,oy=((int)Number("YBAYROFF")%2+2)%2;
double[][] sums=[new double[ow*oh],new double[ow*oh],new double[ow*oh]];byte[] rows=new byte[w*bytes*2];
for(int y=0;y<uh;y++)
{
ct.ThrowIfCancellationRequested();stream.ReadExactly(rows);
for(int x=0;x<uw;x++)for(int dy=0;dy<2;dy++)for(int dx=0;dx<2;dx++)
{
var span=rows.AsSpan((dy*w+x*2+dx)*bytes,bytes);
double raw=bit switch{8=>span[0],16=>BinaryPrimitives.ReadInt16BigEndian(span),32=>BinaryPrimitives.ReadInt32BigEndian(span),-32=>BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32BigEndian(span)),_=>BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64BigEndian(span))};
double value=raw*factor+zero;if(!double.IsFinite(value)||Math.Abs(value)>float.MaxValue)throw new InvalidDataException("Nonfinite color preview");
int channel=pattern[((dy+oy)%2)*2+(dx+ox)%2] switch{'R'=>0,'G'=>1,_=>2};sums[channel][y/step*ow+x/step]+=value;
}
}
float[][] channels=[new float[ow*oh],new float[ow*oh],new float[ow*oh]];
for(int y=0;y<oh;y++)for(int x=0;x<ow;x++)
{
int i=y*ow+x,count=(Math.Min((y+1)*step,uh)-y*step)*(Math.Min((x+1)*step,uw)-x*step);
for(int c=0;c<3;c++)channels[c][i]=(float)(sums[c][i]/(count*(c==1?2:1)));
}
return new(ow,oh,channels[0],channels[1],channels[2]);
}
public static ColorPreviewDisplay Prepare(ColorPreviewPlane color,CancellationToken ct=default)
{
int count=color.Width*color.Height;float[][] channels=[color.Red,color.Green,color.Blue],chroma=new float[3][];double[] noise=new double[3];
float[] luma=new float[count];for(int i=0;i<count;i++)luma[i]=(float)(((double)color.Red[i]+color.Green[i]+color.Blue[i])/3);
for(int c=0;c<3;c++)
{
List<double> diff=[];for(int y=0;y<color.Height;y++)for(int x=0;x<color.Width-1;x++)diff.Add(Math.Abs(channels[c][y*color.Width+x]-channels[c][y*color.Width+x+1]));
noise[c]=Robust.Median(diff)/.953872;
chroma[c]=PreviewRenderer.Smooth(new(color.Width,color.Height,channels[c]),12,ct).Pixels;
double median=Robust.Median(chroma[c].Select(v=>(double)v));for(int i=0;i<count;i++)chroma[c][i]-=(float)median;
}
for(int i=0;i<count;i++)
{float mean=(chroma[0][i]+chroma[1][i]+chroma[2][i])/3;for(int c=0;c<3;c++)chroma[c][i]-=mean;}
// A 12-pass binomial filter has ~0.065 of the original 2D white-noise sigma.
// Suppress uncertain color excursions instead of painting noise with saturated hues.
return new(PreviewRenderer.Prepare(new(color.Width,color.Height,luma),true,ct),chroma,Math.Max(.001,noise.Average()*.065*2.5));
}
public static byte[] Render(ColorPreviewDisplay display,double target=.18)
{
byte[] mono=PreviewRenderer.Render(display.Luminance,target),output=new byte[mono.Length*4];
for(int i=0;i<mono.Length;i++)
{
double maximum=Math.Max(Math.Abs(display.Chroma[0][i]),Math.Max(Math.Abs(display.Chroma[1][i]),Math.Abs(display.Chroma[2][i]))),certainty=maximum>display.ChromaThreshold?1-Math.Pow(display.ChromaThreshold/maximum,2):0;
double level=Math.Max(.001,display.Luminance.Plane.Pixels[i]-display.Luminance.Black);
// Keep the linked luminance and scale all channels together into gamut.
// Bright star cores tend to neutral white, without clipped colored rings.
double scale=maximum>0?Math.Min(.6*certainty*mono[i]/level,Math.Min(.45*mono[i],255-mono[i])/maximum):0;
for(int c=0;c<3;c++)output[4*i+(2-c)]=(byte)Math.Clamp(mono[i]+scale*display.Chroma[c][i],0,255);
output[4*i+3]=255;
}
return output;
}
public static string PathFor(string directory,Frame frame)=>Path.Combine(directory,"previews",frame.Id+"-color1.bin");
public static void Write(ColorPreviewPlane color,string path,Frame frame)
{
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);string temp=path+".tmp";
try
{
using(var stream=File.Create(temp))
{
using(var header=new BinaryWriter(stream,System.Text.Encoding.UTF8,true)){header.Write(Magic);header.Write(frame.Length);header.Write(frame.Modified);header.Write(color.Width);header.Write(color.Height);}
using var compressed=new DeflateStream(stream,CompressionLevel.Fastest,true);
using var writer=new BinaryWriter(compressed);
foreach(var channel in new[]{color.Red,color.Green,color.Blue})
{if(BitConverter.IsLittleEndian)compressed.Write(MemoryMarshal.AsBytes(channel.AsSpan()));else foreach(float value in channel)writer.Write(value);}
}
File.Move(temp,path,true);
}
finally{if(File.Exists(temp))File.Delete(temp);}
}
public static ColorPreviewPlane Read(string path,Frame frame)
{
using var stream=File.OpenRead(path);using var header=new BinaryReader(stream,System.Text.Encoding.UTF8,true);
if(header.ReadInt32()!=Magic||header.ReadInt64()!=frame.Length||header.ReadInt64()!=frame.Modified)throw new InvalidDataException("Color 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("Color preview dimensions exceed safety budget");
float[][] channels=[new float[w*h],new float[w*h],new float[w*h]];using var compressed=new DeflateStream(stream,CompressionMode.Decompress);using var reader=new BinaryReader(compressed);
foreach(var channel in channels)
{if(BitConverter.IsLittleEndian)compressed.ReadExactly(MemoryMarshal.AsBytes(channel.AsSpan()));else for(int i=0;i<channel.Length;i++)channel[i]=reader.ReadSingle();if(channel.Any(v=>!float.IsFinite(v)))throw new InvalidDataException("Nonfinite color preview");}
return new(w,h,channels[0],channels[1],channels[2]);
}
}

View file

@ -0,0 +1,56 @@
namespace AstroFrame.Engine;
/// <summary>Display-only non-local means using 5x5 patches and a 13x13 search window.</summary>
public static class DenoisedPreview
{
public static PreviewDisplay Prepare(PreviewDisplay original,CancellationToken ct=default)
=>original with{Plane=Denoise(original.Plane,ct),Denoised=true};
public static PreviewPlane Denoise(PreviewPlane plane,CancellationToken ct=default)
{
ct.ThrowIfCancellationRequested();int w=plane.Width,h=plane.Height,count=plane.Pixels.Length;var input=plane.Pixels;
List<double> differences=[];for(int y=0;y<h;y++)for(int x=0;x<w-1;x++)differences.Add(Math.Abs((double)input[y*w+x]-input[y*w+x+1]));
float sigma=(float)(Robust.Median(differences)/.953872),variance=sigma*sigma,strength=.64f*variance;
if(!float.IsFinite(strength)||strength<=0)return new(w,h,(float[])input.Clone());
float[] output=(float[])input.Clone(),weights=Enumerable.Repeat(1f,count).ToArray(),distance=new float[count],horizontal=new float[count],local=new float[count];
// Keep offset and accumulation order consistent with the approved preview experiment.
for(int dy=-6;dy<=6;dy++)for(int dx=-6;dx<=6;dx++)
{
if(dx==0&&dy==0)continue;
for(int y=0;y<h;y++)
{
ct.ThrowIfCancellationRequested();int row=y*w,otherRow=Reflect(y+dy,h)*w;
for(int x=0;x<w;x++){float delta=input[row+x]-input[otherRow+Reflect(x+dx,w)];distance[row+x]=delta*delta;}
}
Mean5(distance,horizontal,local,w,h,ct);
for(int y=0;y<h;y++)
{
ct.ThrowIfCancellationRequested();int row=y*w,otherRow=Reflect(y+dy,h)*w;
for(int x=0;x<w;x++)
{
int i=row+x;float weight=MathF.Exp(-Math.Max(0,local[i]-2*variance)/strength);
weights[i]+=weight;output[i]+=weight*input[otherRow+Reflect(x+dx,w)];
}
}
}
for(int i=0;i<count;i++)output[i]/=weights[i];return new(w,h,output);
}
static int Reflect(int position,int length)
{
if(length==1)return 0;
while(position<0||position>=length)position=position<0?-position:2*length-2-position;
return position;
}
static void Mean5(float[] input,float[] horizontal,float[] output,int w,int h,CancellationToken ct)
{
for(int y=0;y<h;y++)
{
ct.ThrowIfCancellationRequested();int row=y*w;
for(int x=0;x<w;x++){float sum=0;for(int k=-2;k<=2;k++)sum+=input[row+Reflect(x+k,w)];horizontal[row+x]=sum/5;}
}
for(int y=0;y<h;y++)
{
ct.ThrowIfCancellationRequested();for(int x=0;x<w;x++){float sum=0;for(int k=-2;k<=2;k++)sum+=horizontal[Reflect(y+k,h)*w+x];output[y*w+x]=sum/5;}
}
}
}

View file

@ -3,8 +3,8 @@ 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,bool Diffuse=false);
public enum PreviewMode { Frame, Nebula, Asinh, Color }
public sealed record PreviewDisplay(PreviewPlane Plane,double Black,double White,double Mid,bool Denoised=false);
public enum PreviewMode { Frame, Denoised }
/// <summary>Display-only area reduction and screen transfer. Never used by a quality detector.</summary>
public static class PreviewRenderer
{
@ -20,56 +20,22 @@ public static class PreviewRenderer
}
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,CancellationToken ct=default)
public static byte[] Render(PreviewPlane image,double target=.18)
=>Render(Prepare(image),target);
public static PreviewDisplay Prepare(PreviewPlane image,CancellationToken ct=default)
{
ct.ThrowIfCancellationRequested();var plane=nebula?Diffuse(image,ct):image;
ct.ThrowIfCancellationRequested();var plane=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;
if(nebula){black=Math.Min(black,Robust.Quantile(values,.005));span=white-black;}
return new(plane,black,white,(median-black)/span,nebula);
return new(plane,black,white,(median-black)/span);
}
public static byte[] Render(PreviewDisplay display,double target=.18,bool asinh=false)
public static byte[] Render(PreviewDisplay display,double target=.18)
{
double mid=display.Mid,t=Math.Clamp(target+(display.Diffuse?.07:0),.06,.48),m=mid*(t-1)/((2*t-1)*mid-t),span=display.White-display.Black;byte[] output=new byte[display.Plane.Pixels.Length];
double strength=asinh?AsinhStrength(mid,t):0;
for(int i=0;i<output.Length;i++){double v=Math.Clamp((display.Plane.Pixels[i]-display.Black)/span,0,1);double result=asinh?(strength>0?Math.Asinh(strength*v)/Math.Asinh(strength):Math.Pow(v,Math.Log(t)/Math.Log(mid))):(m-1)*v/((2*m-1)*v-m);output[i]=(byte)Math.Clamp(255*result,0,255);}
double mid=display.Mid,t=Math.Clamp(target+(display.Denoised?.07:0),.06,.48),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);double result=(m-1)*v/((2*m-1)*v-m);output[i]=(byte)Math.Clamp(255*result,0,255);}
return output;
}
static double AsinhStrength(double mid,double target)
{
if(mid>=target)return 0;double lo=.001,hi=1e10;
for(int n=0;n<64;n++){double k=(lo+hi)/2;if(Math.Asinh(k*mid)/Math.Asinh(k)<target)lo=k;else hi=k;}return hi;
}
public static PreviewPlane Diffuse(PreviewPlane image,CancellationToken ct=default)
{
int w=image.Width,h=image.Height;float[] median=new float[w*h];Span<float> samples=stackalloc float[9];
for(int y=0;y<h;y++)
{
ct.ThrowIfCancellationRequested();for(int x=0;x<w;x++)
{int n=0;for(int dy=-1;dy<=1;dy++)for(int dx=-1;dx<=1;dx++)samples[n++]=image.Pixels[Math.Clamp(y+dy,0,h-1)*w+Math.Clamp(x+dx,0,w-1)];samples.Sort();median[y*w+x]=samples[4];}
}
return Smooth(new(w,h,median),4,ct);
}
public static PreviewPlane Smooth(PreviewPlane image,int passes,CancellationToken ct=default)
{
int w=image.Width,h=image.Height;float[] input=(float[])image.Pixels.Clone(),horizontal=new float[w*h],output=new float[w*h];int[] kernel=[1,6,15,20,15,6,1];
for(int n=0;n<passes;n++)
{
for(int y=0;y<h;y++)
{
ct.ThrowIfCancellationRequested();for(int x=0;x<w;x++){double sum=0;for(int k=0;k<7;k++)sum+=kernel[k]*input[y*w+Math.Clamp(x+k-3,0,w-1)];horizontal[y*w+x]=(float)(sum/64);}
}
for(int y=0;y<h;y++)
{
ct.ThrowIfCancellationRequested();for(int x=0;x<w;x++){double sum=0;for(int k=0;k<7;k++)sum+=kernel[k]*horizontal[Math.Clamp(y+k-3,0,h-1)*w+x];output[y*w+x]=(float)(sum/64);}
}
(input,output)=(output,input);
}
return new(w,h,input);
}
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))!);

View file

@ -1,43 +0,0 @@
using AstroFrame.Engine;
using System.Security.Cryptography;
static class ColorPreviewRegression
{
public static void Run(Action<bool,string> check)
{
string directory=Path.Combine(Path.GetTempPath(),"AstroFrame-color-"+Guid.NewGuid());Directory.CreateDirectory(directory);
try
{
const int size=128;ColorPreviewPlane? last=null;Frame? frame=null;
foreach(string pattern in new[]{"RGGB","GRBG","GBRG","BGGR"})foreach(var offset in new[]{(X:0,Y:0),(X:1,Y:0),(X:0,Y:1),(X:1,Y:1)})
{
float[] pixels=new float[size*size];for(int y=0;y<size;y++)for(int x=0;x<size;x++)pixels[y*size+x]=pattern[((y+offset.Y)%2)*2+(x+offset.X)%2] switch{'R'=>600,'G'=>1000,_=>1400};
string path=Path.Combine(directory,$"{pattern}-{offset.X}-{offset.Y}.fit");ImageRegression.WriteFits(path,pixels,size,size,0,pattern,offset.X,offset.Y);
var color=ColorPreview.ReadFits(path)!;bool correct=color.Red.All(v=>v==600)&&color.Green.All(v=>v==1000)&&color.Blue.All(v=>v==1400);
check(correct,$"Bayer color channels respect {pattern} with offsets {offset.X},{offset.Y}");
check(Fits.Read(path).Pixels.All(v=>v==1000),$"color support preserves analysis grayscale for {pattern} with offsets {offset.X},{offset.Y}");
last=color;frame=Fits.Inspect(path);
}
byte[] sourceHash=SHA256.HashData(File.ReadAllBytes(frame!.Path));string cache=ColorPreview.PathFor(directory,frame!);ColorPreview.Write(last!,cache,frame!);var restored=ColorPreview.Read(cache,frame!);
check(restored.Red.SequenceEqual(last!.Red)&&restored.Green.SequenceEqual(last.Green)&&restored.Blue.SequenceEqual(last.Blue),"color caches retain linear RGB samples without losing channel order");
var neutral=ColorPreview.Render(ColorPreview.Prepare(restored));
check(Enumerable.Range(0,neutral.Length/4).All(i=>neutral[i*4]==neutral[i*4+1]&&neutral[i*4+1]==neutral[i*4+2]),"sky neutralization does not turn a constant colored pedestal into false nebula color");
check(sourceHash.SequenceEqual(SHA256.HashData(File.ReadAllBytes(frame.Path))),"color reading, preparing, rendering and caching preserve source FITS bytes");
bool refused=false;try{ColorPreview.Read(cache,new Frame{Length=frame.Length+1,Modified=frame.Modified});}catch(InvalidDataException){refused=true;}
check(refused,"changed sources invalidate color caches independently of quality data");
const int w=96,h=96;var random=new Random(1902);float[][] channels=[new float[w*h],new float[w*h],new float[w*h]];
for(int y=0;y<h;y++)for(int x=0;x<w;x++)for(int c=0;c<3;c++)channels[c][y*w+x]=(float)(1000+(c==0?80:0)*Math.Exp(-Math.Pow((x-48)/12.0,2)-Math.Pow((y-48)/20.0,2))+(random.NextDouble()-.5)*12);
var input=(float[])channels[0].Clone();var display=ColorPreview.Prepare(new(w,h,channels[0],channels[1],channels[2]));var output=ColorPreview.Render(display);
check(Enumerable.Range(0,w*h).Count(i=>output[i*4+2]>output[i*4]+30&&output[i*4+2]>output[i*4+1]+30)>20,"color nebula preserves a real red diffuse signal through the linked stretch");
var extremes=ColorPreview.Render(new(new(new(2,1,[0,10]),0,10,.5,true),[[100,100],[-50,-50],[-50,-50]],1));
check(extremes.Take(3).All(v=>v==0)&&extremes.Skip(4).Take(3).All(v=>v==255),"linked color stays neutral at black and white instead of clipping individual channels");
check(channels[0].SequenceEqual(input)&&Enumerable.Range(0,w*h).All(i=>output[i*4+3]==255),"color display leaves linear channels untouched and emits opaque pixels");
using(var cancel=new CancellationTokenSource()){cancel.Cancel();bool cancelled=false;try{ColorPreview.ReadFits(frame.Path,cancel.Token);}catch(OperationCanceledException){cancelled=true;}check(cancelled,"color FITS reading cancels before processing rows");}
string mono=Path.Combine(directory,"mono.fit");ImageRegression.WriteFits(mono,Enumerable.Repeat(1000f,128*128).ToArray(),128,128,0);
check(ColorPreview.ReadFits(mono)==null,"monochrome FITS files never acquire fabricated color channels");
string invalid=Path.Combine(directory,"invalid.fit");ImageRegression.WriteFits(invalid,Enumerable.Repeat(1000f,128*128).ToArray(),128,128,0,"XXXX");
check(ColorPreview.ReadFits(invalid)==null,"unknown Bayer layouts fall back to grayscale instead of guessing color");
}
finally{Directory.Delete(directory,true);}
}
}

View file

@ -60,11 +60,11 @@ static class ImageRegression
}
finally{Directory.Delete(directory,true);}
}
internal static void WriteFits(string path,float[] pixels,int width,int height,int n,string bayer="",int offsetX=0,int offsetY=0)
internal static void WriteFits(string path,float[] pixels,int width,int height,int n)
{
string Card(string key,string value)=>(key.PadRight(8)+"= "+value).PadRight(80);
string date=new DateTime(2026,9,20,8,0,0,DateTimeKind.Utc).AddSeconds(n*30).ToString("yyyy-MM-ddTHH:mm:ss",CultureInfo.InvariantCulture);
string header=Card("SIMPLE","T")+Card("BITPIX","-32")+Card("NAXIS","2")+Card("NAXIS1",width.ToString())+Card("NAXIS2",height.ToString())+Card("EXPTIME","30")+Card("OBJECT","'Synthetic field'")+Card("DATE-OBS",$"'{date}'")+(bayer==""?"":Card("BAYERPAT",$"'{bayer}'")+Card("XBAYROFF",offsetX.ToString())+Card("YBAYROFF",offsetY.ToString()))+"END".PadRight(80);
string header=Card("SIMPLE","T")+Card("BITPIX","-32")+Card("NAXIS","2")+Card("NAXIS1",width.ToString())+Card("NAXIS2",height.ToString())+Card("EXPTIME","30")+Card("OBJECT","'Synthetic field'")+Card("DATE-OBS",$"'{date}'")+"END".PadRight(80);
using var stream=File.Create(path);stream.Write(Encoding.ASCII.GetBytes(header.PadRight((header.Length+2879)/2880*2880)));
byte[] row=new byte[width*4];for(int y=0;y<height;y++){for(int x=0;x<width;x++)BinaryPrimitives.WriteInt32BigEndian(row.AsSpan(x*4,4),BitConverter.SingleToInt32Bits(pixels[y*width+x]));stream.Write(row);}
}

View file

@ -7,24 +7,25 @@ static class PreviewRegression
const int w=360,h=640;var random=new Random(839);float[] pixels=new float[w*h];
for(int y=0;y<h;y++)for(int x=0;x<w;x++)pixels[y*w+x]=(float)(1000+40*Math.Exp(-Math.Pow((x-190)/90.0,2)-Math.Pow((y-300)/200.0,2))+(random.NextDouble()-.5)*100);
pixels[290*w+172]=5000;var image=new ImagePlane(w,h,pixels,1);float[] untouched=(float[])pixels.Clone();
var reduced=PreviewRenderer.Reduce(image,3);var frame=PreviewRenderer.Render(reduced);var diffuse=PreviewRenderer.Render(reduced,.18,true);
var reduced=PreviewRenderer.Reduce(image,3);var frame=PreviewRenderer.Render(reduced);
List<double> diff=[];for(int y=0;y<reduced.Height;y++)for(int x=0;x<reduced.Width-1;x++)diff.Add(Math.Abs(frame[y*reduced.Width+x]-frame[y*reduced.Width+x+1])/255.0);
check(Robust.Median(diff)<.06&&Robust.Median(frame.Select(v=>v/255.0))<.25,"preview transfer keeps background grain subordinate to the image");
check(untouched.SequenceEqual(pixels),"preview reduction, stretching and nebula mode never alter analysis pixels");
check(frame.Max()>frame[0]+80&&diffuse.Length==frame.Length&&!diffuse.SequenceEqual(frame),"frame preview preserves conspicuous stars and diffuse view retains the full preview geometry");
float[] filament=new float[w*h];random=new Random(8461);
for(int y=0;y<h;y++)for(int x=0;x<w;x++)filament[y*w+x]=(float)(1000+10*Math.Exp(-Math.Pow((x-160-25*Math.Sin(y/120.0))/5,2))+(random.NextDouble()-.5)*60);
float[] original=(float[])filament.Clone();var enhanced=PreviewRenderer.Prepare(new(w,h,filament),true);var enhancedPixels=PreviewRenderer.Render(enhanced);List<double> core=[],sky=[];
for(int y=20;y<h-20;y++){int x=(int)Math.Round(160+25*Math.Sin(y/120.0));core.Add(enhancedPixels[y*w+x]);sky.Add(enhancedPixels[y*w+x+30]);}
check(Robust.Median(core)-Robust.Median(sky)>20,"nebula preview makes a faint narrow filament visible above adjacent sky");
check(original.SequenceEqual(filament),"faint-detail smoothing never modifies the original linear preview samples");
var alternate=PreviewRenderer.Render(enhanced,.18,true);var brighter=PreviewRenderer.Render(enhanced,.30,true);
check(!alternate.SequenceEqual(enhancedPixels)&&alternate.Zip(brighter).All(pair=>pair.Second>=pair.First),"asinh offers a distinct monotonic stretch and responds to brightness adjustments");
var highMedian=new PreviewDisplay(new(1,1,[.7f]),0,1,.7,true);
check(Math.Abs(PreviewRenderer.Render(highMedian,.18,true)[0]-255*.25)<2&&PreviewRenderer.Render(highMedian,.30,true)[0]>PreviewRenderer.Render(highMedian,.18,true)[0],"asinh brightness remains adjustable when the source median already exceeds the display target");
var flat=PreviewRenderer.Prepare(new(32,32,Enumerable.Repeat(1000f,1024).ToArray()),true);
check(PreviewRenderer.Render(flat).Distinct().Count()==1&&PreviewRenderer.Render(flat,.18,true).Distinct().Count()==1,"constant fields remain constant without invented diffuse structure");
using(var cancel=new CancellationTokenSource()){cancel.Cancel();bool cancelled=false;try{PreviewRenderer.Diffuse(new(w,h,filament),cancel.Token);}catch(OperationCanceledException){cancelled=true;}check(cancelled,"diffuse preview preparation cancels while smoothing");}
check(untouched.SequenceEqual(pixels),"preview reduction and stretching never alter analysis pixels");
check(frame.Max()>frame[0]+80,"frame preview preserves conspicuous stars");
const int side=96;random=new Random(7461);float[] sky=new float[side*side];for(int i=0;i<sky.Length;i++)sky[i]=(float)(1000+(random.NextDouble()-.5)*60);
float[] original=(float[])sky.Clone();var standard=PreviewRenderer.Prepare(new(side,side,sky));var denoised=DenoisedPreview.Prepare(standard);
double Spread(byte[] values){double mean=values.Average(v=>(double)v);return Math.Sqrt(values.Average(v=>Math.Pow(v-mean,2)));}
check(Spread(PreviewRenderer.Render(denoised))<Spread(PreviewRenderer.Render(standard))*.5,"denoised view reduces displayed empty-sky noise instead of amplifying residual blotches");
check(denoised.Black==standard.Black&&denoised.White==standard.White&&denoised.Mid==standard.Mid,"denoising retains the original screen-transfer parameters");
check(sky.SequenceEqual(original)&&denoised.Plane.Width==side&&denoised.Plane.Height==side,"denoising preserves input pixels and preview geometry");
var dim=PreviewRenderer.Render(denoised,.10);var bright=PreviewRenderer.Render(denoised,.30);
check(dim.Zip(bright).All(pair=>pair.Second>=pair.First),"denoised brightness adjustments remain monotonic");
sky[48*side+48]=3000;for(int y=0;y<side;y++)for(int x=0;x<side;x++)sky[y*side+x]+=(float)(20*Math.Exp(-Math.Pow((x-30)/10.0,2)-Math.Pow((y-30)/14.0,2)));
var detail=DenoisedPreview.Denoise(new(side,side,sky));
check(detail.Pixels[48*side+48]>2900&&detail.Pixels[30*side+30]>1010,"patch denoising preserves bright stars and diffuse signal");
var flat=Enumerable.Repeat(1000f,1024).ToArray();check(DenoisedPreview.Denoise(new(32,32,flat)).Pixels.SequenceEqual(flat),"denoising a constant field invents no structure");
check(DenoisedPreview.Denoise(new(1,3,[1000,1001,999])).Pixels.All(float.IsFinite),"small preview dimensions use safe reflected borders");
using(var cancel=new CancellationTokenSource()){cancel.Cancel();bool cancelled=false;try{DenoisedPreview.Denoise(new(side,side,sky),cancel.Token);}catch(OperationCanceledException){cancelled=true;}check(cancelled,"denoised preview preparation respects cancellation");}
string path=Path.Combine(Path.GetTempPath(),"AstroFrame-preview-"+Guid.NewGuid()+".bin");var f=new Frame{Length=7654,Modified=4321};
try
{

View file

@ -130,5 +130,4 @@ QualityRegression.Run(Check);
OverlayRegression.Run(Check);
PreviewRegression.Run(Check);
StellarDetailRegression.Run(Check);
ColorPreviewRegression.Run(Check);
Console.WriteLine($"{passed} checks passed. Synthetic tests validate mechanics, not astrophotography stack quality.");