using AstroFrame.Engine; using System.Diagnostics; using System.Security.Cryptography; using System.Text; using System.Text.Json; ResourcePolicy.InstallWindowsLimit(); if(args.Length>0&&args[0]=="quality-regression") { int failed=0;QualityRegression.Run((ok,name)=>{Console.WriteLine($"{(ok?"PASS":"FAIL")} {name}");if(!ok)failed++;}); if(failed>0)throw new Exception($"{failed} quality regressions failed");return; } if(args.Length>0&&args[0]=="preview") { var plane=PreviewRenderer.Reduce(Fits.Read(Path.GetFullPath(args[1])),3);var pixels=PreviewRenderer.Render(plane);using var writer=new BinaryWriter(File.Create(args[2]));writer.Write(plane.Width);writer.Write(plane.Height);writer.Write(pixels);return; } 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();var timer=Stopwatch.StartNew(); await Parallel.ForEachAsync(files,new ParallelOptions{MaxDegreeOfParallelism=workers},async(path,ct)=> {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") { var(total,available)=ResourcePolicy.PhysicalMemory();Console.WriteLine(JsonSerializer.Serialize(new{totalPhysical=total,availablePhysical=available,reserve=ResourcePolicy.Reserve(total),processLimit=ResourcePolicy.ProcessLimit,heapLimit=GC.GetGCMemoryInfo().TotalAvailableMemoryBytes,windowsLimitEnforced=ResourcePolicy.WindowsLimitEnforced}));return; } if(args.Length>0&&args[0]=="labels") { var p=ProjectStore.Load(Path.GetFullPath(args[1]));var labeled=p.Frames.Where(f=>f.Override.HasValue).ToArray(); var result=new{total=p.Frames.Count,labeled=labeled.Length,unlabeled=p.Frames.Count-labeled.Length, falseRejectFrames=labeled.Count(f=>f.Override==Verdict.Keep&&f.Automatic==Verdict.Reject), falseRejectSeconds=labeled.Where(f=>f.Override==Verdict.Keep&&f.Automatic==Verdict.Reject).Sum(f=>f.Exposure), falseKeepFrames=labeled.Count(f=>f.Override==Verdict.Reject&&f.Automatic==Verdict.Keep), humanAmbiguous=labeled.Count(f=>f.Override==Verdict.Review), confusion=labeled.GroupBy(f=>$"auto:{f.Automatic} human:{f.Override}").ToDictionary(g=>g.Key,g=>g.Count()), sessions=p.Frames.GroupBy(f=>f.Session).Select(g=>new{session=g.Key,total=g.Count(),labeled=g.Count(f=>f.Override.HasValue),falseRejectSeconds=g.Where(f=>f.Override==Verdict.Keep&&f.Automatic==Verdict.Reject).Sum(f=>f.Exposure),falseKeepFrames=g.Count(f=>f.Override==Verdict.Reject&&f.Automatic==Verdict.Keep)}), limitation="Only explicitly overridden frames are labels. Unlabeled frames are not assumed correct; selected review samples are not an unbiased accuracy estimate."}; Console.WriteLine(JsonSerializer.Serialize(result,new JsonSerializerOptions{WriteIndented=true}));return; } if(args.Length>0&&args[0]=="analyze") { string source=Path.GetFullPath(args[1]),directory=Path.GetFullPath(args[2]);var watch=Stopwatch.StartNew();int last=-1; var existing=File.Exists(Path.Combine(directory,"project.json"))?ProjectStore.Load(directory):null; if(args.Contains("--fresh")&&existing!=null)foreach(var f in existing.Frames)f.Measured=false; 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=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") { foreach(string path in args.Skip(1)){var f=Fits.Inspect(path);var sw=Stopwatch.StartNew();new StellarDetector().Measure(f,Fits.Read(path),CancellationToken.None);Console.WriteLine($"{f.Name}: {sw.ElapsedMilliseconds} ms; stars {f.StarCount}; FWHM {f.Fwhm:0.00}; ellipticity {f.Ellipticity:0.00}");}return; } if(args.Length>0&&args[0]=="classify") { string directory=Path.GetFullPath(args[1]);var p=ProjectStore.Load(directory); if(!p.Complete)throw new InvalidOperationException("Reanalyze incomplete or outdated measurements before classification"); Classification.Run(p.Frames);ProjectStore.Save(p,directory);File.WriteAllText(Path.Combine(directory,"decisions.csv"),Export.Manifest(p)); Console.WriteLine(JsonSerializer.Serialize(p.Frames.GroupBy(f=>f.Session).Select(g=>new{session=g.Key,keep=g.Count(f=>f.Automatic==Verdict.Keep),review=g.Count(f=>f.Automatic==Verdict.Review),reject=g.Count(f=>f.Automatic==Verdict.Reject)}),new JsonSerializerOptions{WriteIndented=true}));return; } static double[] Range(IEnumerable v)=>new[]{Robust.Quantile(v,.05),Robust.Median(v),Robust.Quantile(v,.95)}; int passed=0; void Check(bool condition,string name){if(!condition)throw new Exception("FAILED: "+name);passed++;Console.WriteLine("PASS "+name);} Frame Synthetic(int n,double flux=1,int count=160,double background=1000,double width=4,double ellipticity=.15) { Random random=new(123);List stars=[];for(int i=0;i4&&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"); var clouds=Enumerable.Range(0,101).Select(i=>Synthetic(i)).ToList();clouds[50]=Synthetic(50,.38,80,1250);Classification.Run(clouds); Check(clouds[50].Automatic==Verdict.Reject,"strong star loss plus flux loss and elevated background rejects"); Check(clouds.Where((_,i)=>i!=50).All(f=>f.Automatic==Verdict.Keep),"isolated cloudy frame does not reject clean neighbors"); Check(clouds[50].Evidence.Count>=3,"rejection retains multiple explanations"); var isolated=Enumerable.Range(0,101).Select(i=>Synthetic(i)).ToList();isolated[50].Fwhm=6;Classification.Run(isolated); Check(isolated[50].Automatic==Verdict.Review,"one noncatastrophic bad metric routes to review"); var tracking=Enumerable.Range(0,101).Select(i=>Synthetic(i)).ToList();tracking[50].Fwhm=8;tracking[50].Ellipticity=.7;Classification.Run(tracking);Check(tracking[50].Automatic==Verdict.Reject,"severe width and ellipticity degradation rejects"); var small=Enumerable.Range(0,8).Select(i=>Synthetic(i,.5,60)).ToList();Classification.Run(small);Check(small.All(f=>f.Automatic==Verdict.Review),"small sessions disable rejection"); var sessions=new List{Synthetic(0),Synthetic(1),Synthetic(2)};sessions[2].Timestamp=sessions[2].Timestamp?.AddDays(3);Classification.Sessions(sessions);Check(sessions[0].Session==sessions[1].Session&&sessions[0].Session!=sessions[2].Session,"separate nights get separate baselines"); var missing=Synthetic(0);missing.Timestamp=null;Classification.Run([missing]);Check(missing.Automatic==Verdict.Review,"missing timestamps cannot auto reject"); var refFrame=Synthetic(0);var rotated=Synthetic(1);double aspect=(double)refFrame.Height/refFrame.Width,angle=.09; rotated.Stars=rotated.Stars.Select(s=>{double x=s.X-.5,y=(s.Y-.5)*aspect;return s with{X=Math.Cos(angle)*x-Math.Sin(angle)*y+.51,Y=(Math.Sin(angle)*x+Math.Cos(angle)*y)/aspect+.5};}).ToList();Matching.Measure(refFrame,rotated);Check(rotated.MatchFraction>.9&&Math.Abs(rotated.Transparency-1)<.01,"catalog alignment handles rotation and drift"); var impulses=new float[256*256];Array.Fill(impulses,1000);impulses[128*256+128]=50000;var impulse=Synthetic(1);new StellarDetector().Measure(impulse,new(256,256,impulses,1),CancellationToken.None);Check(impulse.StarCount==0,"single pixel hot impulse is not a star"); string temp=Path.Combine(Path.GetTempPath(),"AstroFrame-test-"+Guid.NewGuid());Directory.CreateDirectory(temp); try { var project=new Project{Name="Test",Frames=clouds,Complete=true};clouds[50].Override=Verdict.Keep;clouds[50].Note="Human review";ProjectStore.Save(project,temp);var restored=ProjectStore.Load(temp);Check(restored.Frames[50].Override==Verdict.Keep&&restored.Frames[50].Note=="Human review","manual override and labels persist"); Check(restored.Frames[0].Stars.Count==0&&ProjectStore.LoadCatalog(temp,restored.Frames[0])&&restored.Frames[0].Stars.Count==160,"binary catalogs restore independently from review metadata"); Check(new FileInfo(Path.Combine(temp,"project.json")).Length<250000,"review metadata excludes bulk star catalogs"); string metadata=Path.Combine(temp,"project.json");File.WriteAllText(metadata,File.ReadAllText(metadata).Replace(Project.EngineVersion,"outdated-engine"));var outdated=ProjectStore.Load(temp); Check(!outdated.Complete&&!outdated.Frames[0].Measured&&outdated.Frames[50].Override==Verdict.Keep&&outdated.Frames[50].Note=="Human review","engine upgrades invalidate automatic measurements while retaining human decisions"); string original=Path.Combine(temp,"source.fit");File.WriteAllBytes(original,Encoding.ASCII.GetBytes("Original source bytes"));var info=new FileInfo(original);var ef=Synthetic(1);ef.Path=original;ef.Length=info.Length;ef.Modified=info.LastWriteTimeUtc.Ticks;ef.Automatic=Verdict.Keep;var ep=new Project{Source=temp,Complete=true,Frames=[ef]};byte[] hash=SHA256.HashData(File.ReadAllBytes(original)); string output=temp+"-export"; try {var result=await Export.AcceptedAsync(ep,output,false,false,null,CancellationToken.None);Check(result.Copied==1&&hash.SequenceEqual(SHA256.HashData(File.ReadAllBytes(original))),"copy export preserves source bytes");Check(File.Exists(Path.Combine(output,"accepted.txt")),"export includes accepted manifest");bool refused=false;try{await Export.AcceptedAsync(ep,output,false,false,null,CancellationToken.None);}catch(InvalidOperationException){refused=true;}Check(refused,"export refuses existing nonempty folder");} finally{if(Directory.Exists(output))Directory.Delete(output,true);} var other=Synthetic(2);other.Path=original;other.Length=info.Length;other.Modified=info.LastWriteTimeUtc.Ticks;other.Target="Other target";other.Automatic=Verdict.Keep;ep.Frames.Add(other); try{var result=await Export.AcceptedAsync(ep,output,false,true,null,CancellationToken.None);Check(result.Linked+result.Copied==2&&Directory.GetDirectories(output).Length==2,"multi-target export separates targets and supports hardlinks");Check(hash.SequenceEqual(SHA256.HashData(File.ReadAllBytes(original))),"hardlink export does not alter source contents");} finally{if(Directory.Exists(output))Directory.Delete(output,true);} bool insideRefused=false;try{await Export.AcceptedAsync(ep,Path.Combine(temp,"export"),false,false,null,CancellationToken.None);}catch(InvalidOperationException){insideRefused=true;}Check(insideRefused,"export cannot write inside source tree"); ep.Complete=false;bool partialRefused=false;try{await Export.AcceptedAsync(ep,temp+"-export",false,false,null,CancellationToken.None);}catch(InvalidOperationException){partialRefused=true;}Check(partialRefused,"incomplete analysis cannot export accepted lights"); } finally{Directory.Delete(temp,true);} await ImageRegression.Run(Check); QualityRegression.Run(Check); OverlayRegression.Run(Check); PreviewRegression.Run(Check); StellarDetailRegression.Run(Check); Console.WriteLine($"{passed} checks passed. Synthetic tests validate mechanics, not astrophotography stack quality.");