"""Seasonal ocean-to-station anomaly transfer with damped ocean dynamics.""" import argparse import time import numpy as np from inputs import Panel, ROOT, MONTH_LENGTH from models import Origin, avg from experiments import info, reset from advanced import Advanced def oce_modes(o): d=o.p.sst.loc[:f'{o.year}-12-31'] assert len(d)==len(o.yrs)*12 x=np.column_stack([d.nino34-d.tropical,d.nino3-d.nino4, d.ne_pacific-d.north,d.north_pacific-d.north, d.tropical_atlantic-d.tropical,d.subpolar_atlantic-d.north_atlantic, d.gulf-d.north_atlantic,d.indian-d.tropical]) x=x.reshape(-1,12,x.shape[-1]); t=np.arange(len(x))-len(x)+1 # Remove each calendar month's slow background without using later observations. w=np.exp(-.5*((t[:,None]-t[None,:])/12)**2); w/=w.sum(axis=1,keepdims=True) trend=(w@x.reshape(len(x),-1)).reshape(x.shape) x=(x-trend).reshape(len(d),-1) sd=np.maximum(.05,x.std(0)); return x/sd def evolve(x,h,fit,ridge,mode): # Pool adjacent months in fitting, but keep seasonal effects on coupling. t=np.arange(6,len(x)-1); months=np.arange(len(x))%12 lag=np.concatenate([x[t],x[t-2],x[t-5]],axis=1) y=x[t+1]; win=t>=len(x)-12*fit beta=[] for month in range(12): dt=(months[t]-month)%12; w=np.exp(-.5*(np.minimum(dt,12-dt)/2.3)**2)*win L=lag.T*w; b=np.linalg.solve(L@lag+ridge*np.eye(lag.shape[1]),L@y) beta.append(b) prev=list(x[-6:]); out=[] for m in range(h*12): forecast=np.concatenate([prev[-1],prev[-3],prev[-6]])@beta[(m-1)%12] forecast=np.clip(forecast,-3,3)*.995 prev.append(forecast); out.append(forecast) z=np.stack(out).reshape(h,12,x.shape[1]) if mode=='damped': z*=np.exp(-np.arange(h*12).reshape(h,12,1)/20) return z def station_model(o,key,x,fit,band,ridge): y=o.data[key] slope=o.slope(key,40,0,True,850,.87) z=y-o.t*slope for seg in o.segments: mu=avg(z,seg*o.weight(90)) z=np.where(seg,z-mu,z) z=z[-fit:]; x=x.reshape(-1,12,x.shape[-1])[-fit:] k=o.spatial(band) sc=np.maximum(o.scale(key),.05) z=z/sc co=[] for month in range(12): # Pool same-month and adjacent-month relationships. ind=[(month-1)%12,month,(month+1)%12] yy=z[:,:,ind].transpose(0,2,1).reshape(-1,z.shape[1]); ok=np.isfinite(yy).astype(float) xx=x[:,ind].reshape(len(yy),-1) weights=np.tile([.35,1,.35],len(z)); y0=np.nan_to_num(yy)*weights[:,None] n=np.maximum(1,k@(ok.T@weights)); v=(k@(y0.T@xx))/n[:,None] vx=xx.T*weights b=np.linalg.solve(vx@xx/weights.sum()+ridge*np.eye(xx.shape[1]),v.T).T co.append(b*sc[:,month,None]) return np.stack(co,axis=1) def run(o): x=oce_modes(o); a=Advanced(o) ref=o.line('annual',window=42,anchor=26,band=900,pool=.88,median=.5) sp,sf=a.fit('season',45,900,.88,'accelerate',30) m=a.predict('season',sp,sf,26,.85,0) ref[:,:,0]=(m*MONTH_LENGTH).sum(-1)/MONTH_LENGTH.sum();ref[:,:,3]=a.degree(sp,sf,26) ref=o.final_values(ref) warm=np.nan_to_num(avg(o.warm,o.weight(27))) wmax=avg(o.data['monthly_max'],o.weight(30)); wmax=np.nan_to_num(wmax,nan=-15) wmax=np.exp((wmax-wmax.max(axis=1,keepdims=True))/3); wmax/=wmax.sum(axis=1,keepdims=True) for fit in [42,65,90]: for band in [550,1100]: beta=[station_model(o,key,x,fit,band,.30) for key in ['season','monthly_p','day']] for mode in ['damped','full']: f=evolve(x,o.h,fit,20,mode) z,p,t=[np.einsum('hmi,cmi->hcm',f,b) for b in beta] corr=np.stack([(z*MONTH_LENGTH).sum(-1)/MONTH_LENGTH.sum(), (p*MONTH_LENGTH).sum(-1),(t*wmax).sum(-1),(z*warm*MONTH_LENGTH).sum(-1)],axis=-1) for gain in [.5,1]: yield f'tele:{fit}:{band}:{mode}:{gain}',o.final_values(ref+corr*gain) yield 'tele:none',ref def main(): ap=argparse.ArgumentParser();ap.add_argument('--origins',default='1976,1983,1990,1995,1997,1999,2001,2003,2004,2005,2007,2009,2010,2011,2018');args=ap.parse_args() p=Panel() for yr in map(int,args.origins.split(',')): path=ROOT/'reports'/f'tele_{yr}.npz'; t=time.monotonic() if path.exists():continue h=8 if yr==2010 else 7;o=Origin(p,yr,h);names,preds=zip(*run(o));pr=np.stack(preds).astype('float32') a=p.actual(yr,h) if yr+h<=2018 else np.full(pr.shape[1:],np.nan); b=p.baseline(yr,h) if yr+h<=2018: s=np.array([info(a,b,z)['score'] for z in pr]); i=s.argmax();print(yr,round(time.monotonic()-t,1),'s',names[i],round(s[i],2),flush=True) np.savez_compressed(path,models=names,pred=pr,actual=a,base=b);reset() if __name__=='__main__':main()