Datasets:
Download code/climate.py from sanvicpatel/protostar-climate-ensemble: direct link, hf CLI and curl.
- Browser
- Download file 5.3 kB
-
https://huggingface.co/datasets/sanvicpatel/protostar-climate-ensemble/resolve/main/code/climate.py
- Command line
-
hf download hf://datasets/sanvicpatel/protostar-climate-ensemble/code/climate.py
-
curl -L -o climate.py https://huggingface.co/datasets/sanvicpatel/protostar-climate-ensemble/resolve/main/code/climate.py
5.3 kB
| """Global climate pattern scaling and seasonal extremes.""" | |
| import argparse | |
| import time | |
| import numpy as np | |
| from models import Origin, avg, wquant | |
| from advanced import Advanced | |
| from inputs import ROOT, Panel, MONTH_LENGTH | |
| from experiments import info, reset | |
| def ref_curve(g,h,win,soft=0.): | |
| # A slope through the recent global record plus a smoothed estimate of its initial state. | |
| t=np.arange(len(g))-len(g)+1 | |
| t0=t[-win:]; gg=g[-win:] | |
| w=np.exp(t0/(win*.8)); xm=np.average(t0,weights=w); ym=np.average(gg,weights=w) | |
| slope=np.sum(w*(t0-xm)*(gg-ym))/np.sum(w*(t0-xm)**2) | |
| ols=ym-xm*slope | |
| short=np.mean(g[-6:]-slope*t[-6:]); intercept=(1-soft)*ols+soft*short | |
| # Local linear smoothing inside the training window, including at its right edge. | |
| age=t[:,None]-t[None,:] | |
| kw=np.exp(-.5*(age/4)**2); x=age | |
| s=kw.sum(1); sx=(kw*x).sum(1); sxx=(kw*x*x).sum(1) | |
| xy=(kw*x)@g; y=kw@g | |
| z=(y*sxx-sx*xy)/np.maximum(s*sxx-sx*sx,1e-12) | |
| z=np.where(np.isfinite(z),z,g) | |
| return z,intercept+slope*np.arange(1,h+1) | |
| def pattern(o,key,win,band,pool,curves,residual=.15): | |
| z,zf=curves; y=o.data[key]; sc=o.scale(key); yy=y/sc | |
| g=(z-z[-1])[:,None,None]; future=(zf-z[-1])[:,None,None]; t=o.t | |
| w0=o.weight(win); val=np.nan_to_num(yy,nan=0.) | |
| ss=0.; sy=0.; st=0.; tt=0.; ty=0. | |
| for seg in o.segments: | |
| w=w0*seg*np.isfinite(yy); n=np.maximum(w.sum(axis=0),1e-10) | |
| sx=(w*g).sum(0); sy0=(w*val).sum(0); st0=(w*t).sum(0) | |
| ss=ss+(w*g*g).sum(0)-sx*sx/n | |
| sy=sy+(w*g*val).sum(0)-sx*sy0/n | |
| st=st+(w*g*t).sum(0)-sx*st0/n | |
| tt=tt+(w*t*t).sum(0)-st0*st0/n | |
| ty=ty+(w*t*val).sum(0)-st0*sy0/n | |
| k=o.spatial(band) | |
| local=sy/np.maximum(ss,.03); reg=(k@sy)/np.maximum(k@ss,.03) | |
| w=(1-pool)*np.sqrt(np.clip(ss/np.maximum(ss.max(0),.03),0,1)) | |
| b=(w*local+(1-w)*reg) | |
| resid=ty-b*st | |
| trend=.22*resid/np.maximum(tt,1.)+.78*(k@resid)/np.maximum(k@tt,1.) | |
| return (g*b+t*trend*residual)*sc,(future*b+o.future*trend*residual)*sc | |
| def extreme(o,past,future,anc,skew=.6,trend=.8): | |
| keep=o.age[:,0,0]<anc | |
| vals=o.data['monthly_max'][keep]; good=np.isfinite(o.y[keep,:,2]); w=good*(.2+.8*o.current[keep]); out=[] | |
| for h in range(o.h): | |
| adj=vals+(future[h]-past[keep])*trend | |
| aa=np.where(good,np.max(np.where(np.isfinite(adj),adj,-np.inf),axis=-1),np.nan) | |
| aa=np.where(np.isfinite(aa),aa,np.nan) | |
| out.append((1-skew)*avg(aa,w)+skew*wquant(aa,w)) | |
| return np.stack(out) | |
| def generate(o): | |
| a=Advanced(o) | |
| if o.p.global_temp is not None: | |
| for var in ['globe','north','land']: | |
| g=o.p.global_temp.loc[:o.year,var].reindex(o.yrs).to_numpy() | |
| if not np.isfinite(g).all(): raise ValueError('No valid global climate series at this origin') | |
| for gwin in [18,30,45]: | |
| for soft in [.3,.75]: | |
| curve=ref_curve(g,o.h,gwin,soft) | |
| for win in [38,65]: | |
| for band in [650,1200]: | |
| ap,af=pattern(o,'annual',win,band,.86,curve) | |
| sp,sf=pattern(o,'season',win,band,.86,curve) | |
| for anc in [16,27]: | |
| b=a.predict('annual',ap,af,anc,.85,.35) | |
| b[:,:,1]=a.precip(ap,af,anc,shrink=.85) | |
| tmp=a.predict('season',sp,sf,anc,.85,0) | |
| b[:,:,0]=np.sum(tmp*MONTH_LENGTH,axis=-1)/MONTH_LENGTH.sum() | |
| b[:,:,3]=a.degree(sp,sf,anc,med=.46) | |
| yield f'pattern:{var}:{gwin}:{soft}:{win}:{band}:{anc}',o.final_values(b) | |
| o.data['q90']=o.p.month['Q90'][(o.p.yrs>=1900)&(o.p.yrs<=o.year)] | |
| for win in [20,38,60,85]: | |
| for anc in [16,25,35]: | |
| for key in ['q90','monthly_max','day']: | |
| sl=o.slope(key,win,0,True,850,.87) | |
| for mix in [0,.6,1]: | |
| s=o.slope('annual',win,0,True,850,.87)[:,2:3] | |
| slope=mix*sl+(1-mix)*s | |
| b=o.line('annual',window=win,anchor=anc,band=850,pool=.87,median=.5) | |
| b[:,:,2]=extreme(o,o.t*slope,o.future*slope,anc,skew=.42) | |
| yield f'extreme:{win}:{anc}:{key}:{mix}',o.final_values(b) | |
| def 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)] | |
| p=Panel() | |
| for year in sorted(set(origins)): | |
| path=ROOT/'reports'/f'climate_{year}.npz' | |
| if path.exists(): continue | |
| t=time.monotonic(); h=8 if year==2010 else 7; o=Origin(p,year,h) | |
| names,pred=zip(*generate(o)); pr=np.stack(pred).astype('float32'); b=p.baseline(year,h) | |
| a=p.actual(year,h) if year+h<=2018 else np.full(pr.shape[1:],np.nan) | |
| if year+h<=2018: | |
| s=np.array([info(a,b,z)['score'] for z in pr]); ids=s.argsort()[-3:][::-1] | |
| print(year,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=pr,actual=a,base=b) | |
| reset() | |
| if __name__=='__main__':main() | |