"""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)&(ix100)),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]))