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,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.");