Inital Version

This commit is contained in:
Elijah 2026-10-03 18:29:15 -07:00
commit 94cd6b984b
211 changed files with 4765 additions and 0 deletions

34
tools/Verify-Desktop.ps1 Normal file
View file

@ -0,0 +1,34 @@
param([string]$Application='src/AstroFrame.Desktop/bin/Release/net8.0/AstroFrame.Desktop.exe')
$ErrorActionPreference='Stop'
Set-Location (Split-Path $PSScriptRoot)
$app=Join-Path $PWD $Application
$projectPath=Join-Path $PWD 'projects/Sample Survey'
$out=Join-Path $PWD 'docs/screenshots'
New-Item -ItemType Directory -Force $out | Out-Null
$records=@()
foreach($case in @('pleiades','small','reject','dpi120','dpi144','nebula','all-flux','all-flux-small','smoke')) {
$file=Join-Path $out $(if($case -eq 'smoke'){'smoke-checks.txt'}else{$case+'.png'})
$argsList=@($(if($case -eq 'smoke'){'--smoke'}else{'--capture'}),('"'+$projectPath+'"'),('"'+$file+'"'))
if($case -ne 'smoke'){$argsList+=$(if($case -eq 'reject'){'reject'}elseif($case -eq 'nebula'){'Light_NGC 7000_30.0s_LP_20260816-222249.fit'}elseif($case -like 'all-flux*'){'all'}else{'pleiades'})}
if($case -eq 'nebula'){$argsList[$argsList.Length-1]='"'+$argsList[$argsList.Length-1]+'"';$argsList+='nebula'}
if($case -eq 'small'){$argsList+='1120'}
if($case -eq 'dpi120'){$argsList+=@('1120','--dpi=120')}
if($case -eq 'dpi144'){$argsList+=@('1120','--dpi=144')}
if($case -eq 'all-flux-small'){$argsList+='1120'}
if($case -like 'all-flux*'){$argsList+='"--metric=Forced stellar flux"'}
$process=Start-Process -FilePath $app -ArgumentList $argsList -WindowStyle Hidden -PassThru
$timer=[Diagnostics.Stopwatch]::StartNew();$workingPeak=0L;$privatePeak=0L
while(!$process.HasExited) {
$process.Refresh()
$workingPeak=[math]::Max($workingPeak,$process.WorkingSet64)
$privatePeak=[math]::Max($privatePeak,$process.PrivateMemorySize64)
if($privatePeak -gt 1536MB -or $timer.Elapsed.TotalSeconds -gt 25){Stop-Process -Id $process.Id -Force;throw "Resource/time bound exceeded for $case"}
Start-Sleep -Milliseconds 100
}
$records+=[pscustomobject]@{case=$case;peakWorkingMB=[math]::Round($workingPeak/1MB,1);peakPrivateMB=[math]::Round($privatePeak/1MB,1);exitCode=$process.ExitCode;seconds=[math]::Round($timer.Elapsed.TotalSeconds,2)}
$records | ConvertTo-Json | Set-Content (Join-Path $out 'resource-checks.json')
if($process.ExitCode -ne 0){throw "Desktop verification failed for $case (exit $($process.ExitCode))"}
if(!(Test-Path $file)){throw "Missing verification output for $case"}
}
$records | ConvertTo-Json | Set-Content (Join-Path $out 'resource-checks.json')
$records | Format-Table -AutoSize

Binary file not shown.

View file

@ -0,0 +1,11 @@
"""Real preview regression: background grain must not dominate the display."""
from pathlib import Path
import struct,sys,json
import numpy as np
from PIL import Image
path=Path(sys.argv[1] if len(sys.argv)>1 else 'docs/diagnostics/ngc7000-after.bin')
data=path.read_bytes();w,h=struct.unpack('<ii',data[:8]);a=np.frombuffer(data[8:],dtype=np.uint8).reshape(h,w).astype(float)
grain=float(np.median(np.abs(a[:,1:]-a[:,:-1]))/255)
Image.fromarray(a.astype(np.uint8)).save(path.with_suffix('.png'))
print(json.dumps({'file':str(path),'medianDisplay':float(np.median(a)/255),'adjacentGrain':grain,'pass':grain<.06},indent=2))
sys.exit(0 if grain<.06 else 1)

View file

@ -0,0 +1,15 @@
"""Assert explicitly labeled real FITS examples against persisted automatic decisions."""
import json,sys
from pathlib import Path
p=json.loads(Path(sys.argv[1] if len(sys.argv)>1 else 'projects/Sample Survey/project.json').read_text(encoding='utf-8'))
if not p['Complete']:
raise SystemExit('Analysis is incomplete; no classification regression result can be reported.')
labels=json.loads(Path('tests/real-frame-labels.json').read_text(encoding='utf-8'))['frames']
by_name={Path(f['Path']).name:f for f in p['Frames']}
failures=0
for label in labels:
f=by_name[label['file']];actual=f['Automatic'];good=actual==label['expected'];failures+=not good
print(f"{'PASS' if good else 'FAIL'} {label['file']}: {actual} -> expected {label['expected']}")
print(' '+f['Cause'])
print(f'{len(labels)-failures}/{len(labels)} real regression examples pass. These examples do not establish general accuracy.')
sys.exit(1 if failures else 0)

View file

@ -0,0 +1,12 @@
"""Provisional cloud-only screen of fixed time samples, selected before v2 results."""
import json,sys
from pathlib import Path
p=json.loads(Path(sys.argv[1] if len(sys.argv)>1 else 'projects/Sample Survey/project.json').read_text())
labels=json.loads(Path('tests/visual-cloud-holdout.json').read_text())['frames']
by_name={Path(f['Path']).name:f for f in p['Frames']};failures=[]
for label in labels:
f=by_name[label['file']]
good=(f['Automatic']=='Reject') if label['expected']=='Reject' else (f['Automatic']!='Reject')
if not good:failures.append({'file':label['file'],'expected':label['expected'],'actual':f['Automatic'],'cause':f['Cause']})
report={'samples':len(labels),'passes':len(labels)-len(failures),'failures':failures,'limitation':'Provisional cloud-only visual screen of fixed time samples. No PSF validation, unbiased accuracy estimate, or stack-quality proof.'}
print(json.dumps(report,indent=2));sys.exit(bool(failures))

View file

@ -0,0 +1,45 @@
"""Read-only display/PSF experiment; does not participate in classification."""
from pathlib import Path
import json,sys,struct
import numpy as np
from PIL import Image,ImageDraw,ImageFont
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from explore_cloud_maps import plane
root=Path('Sample Data/NGC 7000');out=Path('docs/diagnostics');out.mkdir(exist_ok=True)
files=['20260816-213449','20260816-222249','20260816-224840']
font=ImageFont.truetype('C:/Windows/Fonts/consola.ttf',14)
def stretch(a,target=.18):
center=np.median(a);noise=np.median(np.abs(np.diff(a,axis=1)))/.954
black=center-2.8*noise;white=max(np.percentile(a,99.95),center+30*noise)
x=np.clip((a-black)/(white-black),0,1);median=(center-black)/(white-black)
m=median*(target-1)/((2*target-1)*median-target)
return np.uint8(np.clip((m-1)*x/((2*m-1)*x-m),0,1)*255)
sheet=Image.new('RGB',(900,695),(15,21,32));draw=ImageDraw.Draw(sheet)
images=[]
for j,suffix in enumerate(files):
a=plane(root/f'Light_NGC 7000_30.0s_LP_{suffix}.fit');images.append(a)
for k,step in enumerate([3,6]):
b=a.reshape(a.shape[0]//step,step,a.shape[1]//step,step).mean(axis=(1,3));im=Image.fromarray(stretch(b));im.thumbnail((285,610))
x=j*300+k*145;sheet.paste(im,(x,45));draw.text((x,5),f'bin{step}',font=font,fill='white');draw.text((j*300,655),suffix,font=font,fill='white')
sheet.save(out/'ngc7000-display-probe.png')
# Coordinates from the unchanged deterministic detector catalog, extracted from the saved user project.
p=json.loads((out/'ngc7000-v2-project.json').read_text());f=next(f for f in p['Frames'] if f['Path'].endswith(files[0]+'.fit'))
catalog=Path.home()/'AppData/Local/AstroFrame/Projects/6FF325B017871EF7/catalogs'/f"{f['Id']}-v2.bin"
with catalog.open('rb') as r:
length=r.read(1)[0];r.read(length+16);count=struct.unpack('<i',r.read(4))[0];stars=np.frombuffer(r.read(count*40),dtype='<f8').reshape(count,5)
chosen=[]
for s in stars:
if .06<s[0]<.94 and .06<s[1]<.94 and all(np.hypot(s[0]-t[0],(s[1]-t[1])*3840/2160)>.04 for t in chosen):chosen.append(s)
if len(chosen)==8:break
# Local centroids change slightly; recenter on the strongest local peak for comparison only.
crops=Image.new('RGB',(780,8*95),(15,21,32));d=ImageDraw.Draw(crops)
for j,a in enumerate(images):
observed=next(frame for frame in p['Frames'] if frame['Path'].endswith(files[j]+'.fit'))
aa,bb,tx,ty=f['Alignment'];ta,tb,ttx,tty=observed['Alignment'];aspect=f['Height']/f['Width']
for i,s in enumerate(chosen):
sx=s[0]-tx;sy=s[1]*aspect-ty;denom=aa*aa+bb*bb;rx=(aa*sx+bb*sy)/denom;ry=(-bb*sx+aa*sy)/denom
x=int((ta*rx-tb*ry+ttx)*a.shape[1]);y=int((tb*rx+ta*ry+tty)/aspect*a.shape[0]);search=a[y-2:y+3,x-2:x+3];yy,xx=np.unravel_index(np.argmax(search),search.shape);x+=xx-2;y+=yy-2
b=a[y-6:y+7,x-6:x+7];bg=np.median(b);v=np.clip((b-bg)/max(1,np.max(b)-bg),0,1)
im=Image.fromarray(np.uint8(v*255)).resize((78,78),Image.Resampling.NEAREST);crops.paste(im,(j*260, i*95));d.text((j*260+85,i*95+10),files[j][-6:],font=font,fill='white')
crops.save(out/'ngc7000-psf-probe.png')
print('Wrote display and raw-star crop comparisons')

View file

@ -0,0 +1,61 @@
"""Read-only, one-frame-at-a-time diagnostic of aligned sky structure. NumPy only."""
from pathlib import Path
import json
import numpy as np
def plane(path):
with open(path,'rb') as f:
header={};done=False
while not done:
block=f.read(2880)
for i in range(0,2880,80):
s=block[i:i+80].decode('ascii');key=s[:8].strip()
if key=='END':done=True;break
if s[8:10]=='= ':header[key]=s[10:].split('/')[0].strip().strip("'").strip()
offset=f.tell()
raw=np.memmap(path,dtype='>i2',mode='r',offset=offset,shape=(int(header['NAXIS2']),int(header['NAXIS1'])))
a=raw.astype(np.float32)+float(header.get('BZERO',0))
return (a[::2,::2]+a[1::2,::2]+a[::2,1::2]+a[1::2,1::2])/4
def detrend(v):
good=np.isfinite(v);coef=np.zeros(3)
for _ in range(5):
coef=np.linalg.lstsq(design[good],v[good],rcond=None)[0]
residual=v-design@coef
sigma=max(1,1.4826*np.nanmedian(np.abs(residual[good]-np.nanmedian(residual[good]))))
good=np.isfinite(v)&(np.abs(residual)<3*sigma)
return v-design@coef
if __name__=='__main__':
p=json.loads(Path('projects/Sample Survey/project.json').read_text())
frames=[f for f in p['Frames'] if f['Target']=='NGC 1432' and f['Timestamp'].startswith('2026-09-20')]
cache=Path('docs/diagnostics/cloud-maps.npz');cache.parent.mkdir(exist_ok=True)
cols,rows=24,40
xx,yy=np.meshgrid((np.arange(cols)+.5)/cols,(np.arange(rows)+.5)/rows)
x,y=xx.ravel(),yy.ravel();design=np.column_stack([np.ones(len(x)),x-.5,y-.5])
if cache.exists():maps=np.load(cache)['maps']
else:
maps=[]
for i,f in enumerate(frames):
a=plane(f['Path']);m=np.median(a.reshape(rows,a.shape[0]//rows,cols,a.shape[1]//cols),axis=(1,3))
aa,b,tx,ty=f['Alignment'];aspect=f['Height']/f['Width']
u=(aa*x-b*y*aspect+tx)*cols-.5;v=(b*x+aa*y*aspect+ty)/aspect*rows-.5
ix=np.floor(u).astype(int);iy=np.floor(v).astype(int);valid=(ix>=0)&(iy>=0)&(ix<cols-1)&(iy<rows-1)
ix=np.clip(ix,0,cols-2);iy=np.clip(iy,0,rows-2);dx=u-ix;dy=v-iy
aligned=(m[iy,ix]*(1-dx)+m[iy,ix+1]*dx)*(1-dy)+(m[iy+1,ix]*(1-dx)+m[iy+1,ix+1]*dx)*dy
aligned[~valid]=np.nan;maps.append(detrend(aligned))
if i%50==0:print(f'maps {i}/{len(frames)}',flush=True)
maps=np.array(maps);np.savez(cache,maps=maps)
reference=np.nanmedian(maps,axis=0)
for _ in range(3):
residual=np.array([detrend(m-reference) for m in maps]);amplitude=np.nanpercentile(np.abs(residual),95,axis=1)
clean=amplitude<np.percentile(amplitude,40)
reference=np.nanmedian(maps[clean],axis=0)
residual=np.array([detrend(m-reference) for m in maps]);amp=np.nanpercentile(np.abs(residual),95,axis=1)
print('residual q:',np.percentile(amp,[0,10,25,40,50,75,90,95,99,100]).round(2).tolist())
labels=json.loads(Path('tests/real-frame-labels.json').read_text())['frames']
for label in labels:
i=next(i for i,f in enumerate(frames) if Path(f['Path']).name==label['file'])
print(label['file'],label['expected'],'amp',round(amp[i],2),'above100',round(float(np.nanmean(np.abs(residual[i])>100)),3))
np.savez('docs/diagnostics/cloud-residuals.npz',maps=maps,residual=residual,reference=reference,amplitude=amp)
Path('docs/diagnostics/cloud-map-index.json').write_text(json.dumps([f['Path'] for f in frames]))

33
tools/fetch_packages.py Normal file
View file

@ -0,0 +1,33 @@
"""Populate local NuGet source where Windows TLS cannot reach NuGet."""
import urllib.request,zipfile,xml.etree.ElementTree as ET,re,sys
from pathlib import Path
root=Path('.tools/feed'); root.mkdir(parents=True,exist_ok=True)
seen=set()
def fetch(name,version):
name=name.lower(); version=version.strip('[]()').split(',')[0]
if (name,version) in seen:return
seen.add((name,version)); p=root/f'{name}.{version}.nupkg'
if not p.exists():
print(name,version,flush=True)
urllib.request.urlretrieve(f'https://api.nuget.org/v3-flatcontainer/{name}/{version}/{name}.{version}.nupkg',p)
with zipfile.ZipFile(p) as z:
nuspec=next(n for n in z.namelist() if n.endswith('.nuspec'))
node=ET.fromstring(z.read(nuspec)); ns={'n':node.tag.split('}')[0].strip('{')}
deps=node.find('n:metadata/n:dependencies',ns)
if deps is None:return
groups=deps.findall('n:group',ns)
chosen=[]
if groups:
def rank(g):
t=g.get('targetFramework','').lower()
if t in ('net8.0','net8.0-windows7.0'):return 100
if t in ('net6.0','net7.0'):return 90
if t in ('.netstandard2.0','netstandard2.0','.netstandard2.1','netstandard2.1'):return 80
if not t:return 60
return 0
best=max(groups,key=rank); chosen=best.findall('n:dependency',ns)
else:chosen=deps.findall('n:dependency',ns)
for dep in chosen:fetch(dep.get('id'),dep.get('version'))
for n in ('Avalonia.Desktop','Avalonia.Themes.Fluent','Avalonia.Fonts.Inter'):fetch(n,'11.3.9')
for pair in sys.argv[1:]:
n,v=pair.split('=');fetch(n,v)

45
tools/inspect_data.py Normal file
View file

@ -0,0 +1,45 @@
"""Read-only FITS inventory and exploratory measurements. Requires NumPy only."""
from pathlib import Path
import json, datetime, collections
import numpy as np
def header(path):
h={}
with open(path,'rb') as f:
done=False
while not done:
block=f.read(2880)
if len(block)!=2880: raise ValueError('Truncated header')
for i in range(0,2880,80):
s=block[i:i+80].decode('ascii'); k=s[:8].strip()
if k=='END': done=True; break
if s[8:10]=='= ':
v=s[10:].split('/')[0].strip().strip("'").strip(); h[k]=v
return h,f.tell()
def image(path):
h,offset=header(path)
a=np.memmap(path,dtype='>i2',mode='r',offset=offset,shape=(int(h['NAXIS2']),int(h['NAXIS1'])))
a=a.astype(np.float32)*float(h.get('BSCALE',1))+float(h.get('BZERO',0))
# Same Bayer phase per superpixel; no color interpolation or sharpening.
a=(a[::2,::2]+a[1::2,::2]+a[::2,1::2]+a[1::2,1::2])/4
return h,a
def measurements(path):
h,a=image(path); bg=float(np.median(a)); noise=float(np.median(np.abs(a[:,1:]-a[:,:-1]))/0.954)
p=a[1:-1,1:-1]; peaks=p>bg+8*max(noise,1)
for dy,dx in [(0,1),(0,-1),(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1)]:
peaks &= p>a[1+dy:a.shape[0]-1+dy,1+dx:a.shape[1]-1+dx]
return {'file':str(path),'date':h.get('DATE-OBS'),'background':round(bg,2),'noise':round(noise,2),'peaks':int(peaks.sum()),'p99':float(np.percentile(a,99))}
root=Path('Sample Data'); report={}
for folder in sorted(root.iterdir()):
files=sorted(folder.glob('*.fit')); records=[]
for p in files:
h,_=header(p); records.append((h.get('DATE-OBS',''),h))
nights=collections.Counter(x[0][:10] for x in records)
samples=[measurements(files[i]) for i in np.linspace(0,len(files)-1,min(14,len(files)),dtype=int)]
report[folder.name]={'count':len(files),'dates':dict(nights),'formats':list({(h.get('NAXIS1'),h.get('NAXIS2'),h.get('BITPIX'),h.get('BAYERPAT'),h.get('EXPTIME'),h.get('FILTER'),h.get('GAIN')) for _,h in records}),'samples':samples}
Path('docs').mkdir(exist_ok=True)
Path('docs/dataset-inspection.json').write_text(json.dumps(report,indent=2))
print(json.dumps(report,indent=2))

14
tools/make_app_icon.py Normal file
View file

@ -0,0 +1,14 @@
"""Rasterize the simple orbital mark for the taskbar and executable icon."""
from pathlib import Path
from PIL import Image, ImageDraw
out=Path(__file__).resolve().parent.parent/'src/AstroFrame.Desktop/Assets'
out.mkdir(parents=True,exist_ok=True)
im=Image.new('RGBA',(256,256),(0,0,0,0));d=ImageDraw.Draw(im)
d.rounded_rectangle((8,8,248,248),radius=54,fill='#101925')
d.ellipse((49,49,207,207),outline='#6D8DAB',width=7)
d.line((35,192,221,64),fill='#A0BEDD',width=9)
d.polygon([(128,70),(141,115),(186,128),(141,141),(128,186),(115,141),(70,128),(115,115)],fill='#E1E7EF')
d.ellipse((194,56,219,81),fill='#83CDB8')
im.save(out/'astroframe.ico',sizes=[(16,16),(24,24),(32,32),(48,48),(64,64),(128,128),(256,256)])
im.resize((64,64),Image.Resampling.LANCZOS).save(out/'astroframe.png')

View file

@ -0,0 +1,33 @@
"""Fixed capture-order samples, chosen independently of automatic verdicts."""
import json,sys,struct,zlib
import numpy as np
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
pdir=Path(sys.argv[1] if len(sys.argv)>1 else 'projects/Sample Survey')
p=json.loads((pdir/'project.json').read_text());sessions=sorted({f['Session'] for f in p['Frames']})
out=Path('docs/validation-sheets');out.mkdir(exist_ok=True)
font=ImageFont.truetype('C:/Windows/Fonts/consola.ttf',12)
index=[]
for number,session in enumerate(sessions):
frames=sorted([f for f in p['Frames'] if f['Session']==session],key=lambda f:f['Timestamp'])
count=16 if '1432' in session else 8
chosen=[frames[int((i+.5)*len(frames)/count)] for i in range(count)]
sheet=Image.new('RGB',(800,340*((count+3)//4)),(15,21,32));draw=ImageDraw.Draw(sheet)
for i,f in enumerate(chosen):
x=(i%4)*200;y=(i//4)*340
current=pdir/'previews'/f"{f['Id']}-display3.bin"
if current.exists():
data=current.read_bytes();_,_,_,w,h=struct.unpack('<iqqii',data[:28]);a=np.frombuffer(zlib.decompress(data[28:],-15),dtype='<f4').reshape(h,w)
center=float(np.median(a));noise=max(.001,float(np.median(np.abs(np.diff(a,axis=1))))/.953872);black=center-2.8*noise;white=max(float(np.percentile(a,99.95)),center+30*noise)
xx=np.clip((a-black)/(white-black),0,1);mid=(center-black)/(white-black);target=.18;m=mid*(target-1)/((2*target-1)*mid-target);gray=np.uint8(np.clip((m-1)*xx/((2*m-1)*xx-m),0,1)*255);im=Image.fromarray(gray).convert('RGB')
else:
data=(pdir/'previews'/f"{f['Id']}.bin").read_bytes();w,h=struct.unpack('<ii',data[:8]);im=Image.frombytes('L',(w,h),data[8:]).convert('RGB')
im.thumbnail((180,290));sheet.paste(im,(x+10+(180-im.width)//2,y+5))
suffix=Path(f['Path']).stem.split('_')[-1]
caption=f"{i+1:02d} {suffix}\n{f['Timestamp'][11:19]} UTC"
if len(sys.argv)>2 and sys.argv[2]=='decisions':caption+=f"\n{f['Automatic']} cloud {f.get('CloudCoverage',0):.0%}"
draw.multiline_text((x+6,y+297),caption,font=font,fill=(224,234,244))
index.append({'session':session,'sheet':number,'position':i+1,'file':Path(f['Path']).name})
sheet.save(out/f'session-{number}.png')
Path('docs/validation-sheets/index.json').write_text(json.dumps(index,indent=2))
print('\n'.join(f'{i}: {s}' for i,s in enumerate(sessions)))