sanvicpatel's picture
Upload reproducible Protostar climate forecasts
993d9a6 verified
Raw History Blame Contribute Delete
8.89 kB
"""Climate response and station homogenization experiments."""
import argparse
import time
from functools import lru_cache
import numpy as np
from inputs import Panel, ROOT, MONTH_LENGTH
from models import Origin, avg, quant, wquant
from experiments import info, reset
class Advanced:
def __init__(self,o): self.o=o; self.sl={}; self.st={}; self.level={}
def fit(self,key,win,band,pool,basis,force,decay=0):
args=(key,win,band,pool,basis,force,decay)
if args in self.sl:return self.sl[args]
o=self.o; t=o.t[:,0,0]; tf=np.arange(1,o.h+1)
if basis=='linear': x=t; f=tf
if basis=='accelerate':
# A convex time trend regularizes the gradual acceleration of forced warming.
x=force*np.expm1(t/force); f=force*np.expm1(tf/force)
if basis=='hinge':
x=t+.9*np.maximum(0,t+force); f=tf+.9*(tf+force)
if basis=='sst':
seas=o.p.sst.loc[:f'{o.year}-12-31']; g=seas.groupby(seas.index.year).mean()['global'].reindex(o.yrs).to_numpy()
g=np.array([g[max(0,i-4):i+1].mean() for i in range(len(g))])
gwin=int(force); a=np.polyfit(t[-gwin:],g[-gwin:],1)
# Recent ocean state and long-term slope are both uncertain; average the anchors.
c=.5*g[-1]+.5*a[1]
x=g-g[-1]; f=c+a[0]*tf-g[-1]
x=x-x[-1]; xx=x[:,None,None]; fut=f[:,None,None]
yy=o.data[key]; zz=np.nan_to_num(yy,nan=0.); ok=np.isfinite(yy)
wt=o.weight(win,decay); ss=0.; sy=0.
for seg in o.segments:
w=wt*seg*ok; n=np.maximum(1e-9,w.sum(0)); ax=(w*xx).sum(0); ay=(w*zz).sum(0)
ss=ss+(w*xx*xx).sum(0)-ax*ax/n
sy=sy+(w*xx*zz).sum(0)-ax*ay/n
sc=o.scale(key)
k=o.spatial(band); b=sy/np.maximum(ss,1e-9)
reg=(k@(sy/sc))/np.maximum(k@ss,1e-9)*sc
al=(1-pool)*np.sqrt(np.clip(ss/np.maximum(ss.max(axis=0),1e-9),0,1))
beta=al*b+(1-al)*reg
self.sl[args]=(xx*beta,fut*beta)
return self.sl[args]
def predict(self,key,past,future,anchor,adjust,skew=.4,decay=0):
o=self.o; y=o.data[key]; z=y-past; ok=np.isfinite(y)
w=o.weight(anchor,decay); wg=w*o.current[:,:,None]
mu=avg(z,w); st=avg(z,wg)
n=(wg*ok).sum(axis=0); alpha=adjust*n/(n+3)
lev=np.where(np.isfinite(st),alpha*st+(1-alpha)*mu,mu)
if skew:
diff=wquant(z,w)-mu
d2=wquant(z,wg)-st
diff=np.where(n>=12,(.55*d2+.45*diff),diff)
# Shrink the noisy sample median toward a regionally estimated distribution asymmetry.
sd=np.sqrt(np.maximum(1e-6,avg((z-mu)**2,w)))
sc=np.nan_to_num(diff/sd,nan=0.)
k=o.spatial(425); v=np.isfinite(diff)&np.isfinite(sd)
smooth=(k@sc)/np.maximum(k@v,1e-10)
lev+=skew*(.55*diff+.45*smooth*sd)
return lev+future
def station_fix(self,key,past,future,anchor,band=425,power=.8,initial=0.):
o=self.o; z=o.data[key]-past; w=o.weight(anchor)
k=o.spatial(band); np.fill_diagonal(k:=k.copy(),0)
y=z-avg(z,w)
# Neighbor anomalies relative to their own stable station levels.
for seg in o.segments:
offset=avg(y,seg*o.weight(max(65,anchor)))
y=np.where(seg,y-offset,y)
sc=o.scale(key)
reg=(np.einsum('ab,tbm->tam',k,np.nan_to_num(y,nan=0.)/sc,optimize=True)/np.maximum(np.einsum('ab,tbm->tam',k,np.isfinite(y).astype(float),optimize=True),1e-9))*sc
y=z-reg
current=w*o.current[:,:,None]; common=avg(y,w); st=avg(y,current)
n=(current*np.isfinite(y)).sum(0); n0=(w*np.isfinite(y)).sum(0)
# Neighbor adjustment estimates site changes while the full window still determines climate.
delta=np.nan_to_num(st-common,nan=0.)*power*n/(n+2.5)
lev=avg(z,w)+delta
if initial:
stable=avg(reg,o.weight(6))-avg(reg,w)
lev+=initial*stable
return lev+future
def degree(self,past,future,anc,adjust=.8,med=.55,calendar=False):
o=self.o; keep=o.age[:,0,0]<anc
warm=o.warm[keep]; d=o.dd[keep]
mean=avg(d,np.ones_like(o.age[keep])); warmmean=avg(warm,np.ones_like(o.age[keep]))
ds=np.where(np.isfinite(d),d,mean); ex=np.where(np.isfinite(warm),warm,warmmean)
good=np.isfinite(d).sum(2)>=11; w=good*(1-adjust+adjust*o.current[keep])
# Exposure is the first derivative of CDD with respect to temperature.
# A smooth shoulder season curvature approximation adds the second-order adjustment.
slope=np.clip(ex*(1-ex)*.105,0,.023)
out=[]
for h in range(o.h):
delta=future[h]-past[keep]
dd=np.maximum(0,ds+delta*ex+.5*delta**2*slope)
annual=np.where(good,np.nansum(dd*MONTH_LENGTH,axis=-1),np.nan)
out.append((1-med)*avg(annual,w)+med*wquant(annual,w))
return np.stack(out)
def precip(self,past,future,anc,adjust=.6,shrink=.8):
o=self.o
avgp=self.predict('annual',past,future,anc,adjust,0)[:,:,1]
yy=o.y[:,:,1]; resid=yy-past[:,:,1]
w=o.weight(anc)[:,:,0]
mu=avg(resid,w); sd2=avg((resid-mu)**2,w)
k=o.spatial(550); good=np.isfinite(sd2)
z=sd2/np.maximum(mu,8)**2
zr=(k@np.nan_to_num(z))/(k@good).clip(1e-9)
return avgp*(1-shrink*(.55*z+.45*zr)/3)
def generate(o):
a=Advanced(o)
def one(n,b):return n,o.final_values(b)
for basis,forces in [('linear',[1]),('accelerate',[18,32,55]),('hinge',[15,25]),('sst',[12,25,45])]:
if basis=='sst' and o.p.sst is None: continue
for f in forces:
for win in [35,55,80]:
for anc in [16,26]:
for band,pool in [(600,.75),(1100,.93)]:
ap,af=a.fit('annual',win,band,pool,basis,f)
sp,sf=a.fit('season',win,band,pool,basis,f)
b=a.predict('annual',ap,af,anc,.8,.55)
tmp=a.predict('season',sp,sf,anc,.8,0)
b[:,:,0]=np.sum(tmp*MONTH_LENGTH,axis=-1)/MONTH_LENGTH.sum()
b[:,:,3]=a.degree(sp,sf,anc)
b[:,:,1]=a.precip(ap,af,anc)
yield one(f'curve:{basis}:{f}:{win}:{anc}:{band}',b)
for win in [22,38,52,70]:
for anc in [12,20,30]:
for gain in [.6,1,1.4,1.9,2.4]:
b=o.line('annual',window=win,anchor=anc,band=900,pool=.88,median=.5,gain=gain)
# Same smooth temperature trend projected through the CDD response.
sp,sf=a.fit('season',win,900,.88,'linear',1)
b[:,:,0]=np.sum(a.predict('season',sp*gain,sf*gain,anc,.83,.25)*MONTH_LENGTH,axis=-1)/MONTH_LENGTH.sum()
b[:,:,3]=a.degree(sp*gain,sf*gain,anc,med=.45)
yield one(f'gain:{win}:{anc}:{gain}',b)
for win in [0,25,40,60]:
for anc in [14,22,30,42]:
for initial in [0,.4,.8]:
sl=o.slope('annual',win,0,True,750,.9)
sp=o.slope('season',win,0,True,750,.9)
b=a.station_fix('annual',o.t*sl,o.future*sl,anc,initial=initial)
tmp=a.station_fix('season',o.t*sp,o.future*sp,anc,initial=initial)
b[:,:,0]=np.sum(tmp*MONTH_LENGTH,axis=-1)/MONTH_LENGTH.sum()
if initial==0:
cdd=a.degree(o.t*sp,o.future*sp,anc)
b[:,:,3]=.5*b[:,:,3]+.5*cdd
yield one(f'station:{win}:{anc}:{initial}',b)
for win in [0,30,45,65,90]:
for anc in [16,26,36]:
for shrink in [.5,1]:
sl=o.slope('annual',win,0,True,850,.92)
b=o.line('annual',window=win,anchor=anc,band=850,pool=.92,median=0)
b[:,:,1]=a.precip(o.t*sl,o.future*sl,anc,shrink=shrink)
yield one(f'gamma:{win}:{anc}:{shrink}',b)
def run(p,origins):
for y in origins:
path=ROOT/'reports'/f'adv_{y}.npz'
if path.exists():continue
t=time.monotonic(); h=8 if y==2010 else 7
o=Origin(p,y,h); names,preds=zip(*generate(o)); preds=np.stack(preds).astype('float32')
a=p.actual(y,h) if y+h<=2018 else np.full(preds.shape[1:],np.nan); b=p.baseline(y,h)
if y+h<=2018:
s=np.array([info(a,b,z)['score'] for z in preds]); ids=s.argsort()[-3:][::-1]
print(y,round(time.monotonic()-t,1),'s',[(names[i],round(s[i],2)) for i in ids],flush=True)
np.savez_compressed(path,models=names,pred=preds,actual=a,base=b)
reset()
if __name__=='__main__':
ap=argparse.ArgumentParser();ap.add_argument('--origins',default='1976,1983,1990,1997,2004,2010,2011,2018');args=ap.parse_args()
origins=[]
for a in args.origins.split(','):origins+=list(range(*map(int,a.split(':')))) if ':' in a else [int(a)]
run(Panel(),sorted(set(origins)))