"""Station-aware climatologies, spatial trend shrinkage and seasonal ensembles.""" from functools import lru_cache import warnings import numpy as np from scipy.spatial.distance import cdist from inputs import MONTH_LENGTH def avg(a,w,axis=0): ok=np.isfinite(a); z=np.where(ok,a,0.) den=(ok*w).sum(axis=axis) return np.divide((z*w).sum(axis=axis),den,out=np.full(den.shape,np.nan),where=den>1e-12) def quant(a,q=.5,axis=0): with warnings.catch_warnings(): warnings.simplefilter('ignore',RuntimeWarning) return np.nanquantile(a,q,axis=axis) def wquant(a,w,q=.5): ind=np.argsort(a,axis=0); v=np.take_along_axis(a,ind,axis=0) ws=np.take_along_axis(np.where(np.isfinite(a),w,0.),ind,axis=0) cum=np.cumsum(ws,axis=0); tot=cum[-1] # Interpolate between adjacent positive-weight observations. mid=cum-.5*ws; target=q*tot ix=np.arange(len(a)).reshape((len(a),)+(1,)*(a.ndim-1)) first_above=np.where((ws>0)&(mid>=target),ix,len(a)).min(axis=0) last=np.where(ws>0,ix,0).max(axis=0) k=np.where(first_above0)&(ix=0,prev,k) take=lambda x,i:np.take_along_axis(x,i[None],axis=0)[0] y0=take(v,j); y1=take(v,k); m0=take(mid,j); m1=take(mid,k) t=np.clip((target-m0)/np.maximum(m1-m0,1e-12),0,1) with np.errstate(invalid='ignore'): return np.where(tot>0,y0+(y1-y0)*t,np.nan) def kernel(lat,lon,band): # Great-circle chord distances in kilometers; slightly prefer east/west neighbors. la=np.deg2rad(lat); lo=np.deg2rad(lon) xyz=np.column_stack([np.cos(la)*np.cos(lo),np.cos(la)*np.sin(lo),np.sin(la)]) dist=6371*cdist(xyz,xyz) dy=111*(lat[:,None]-lat[None,:]); dist=np.sqrt(dist**2+.30*dy**2) return np.exp(-.5*(dist/band)**2) class Origin: def __init__(self,p,year,horizon): if year>2018: raise ValueError('Training origin exceeds weather cutoff') sel=(p.yrs>=1900)&(p.yrs<=year) self.p=p; self.year=year; self.h=horizon; self.yrs=p.yrs[sel] self.age=(year-self.yrs)[:,None,None]; self.t=-self.age self.future=np.arange(1,horizon+1)[:,None,None] self.y=p.y[sel]; self.seg=p.segment[sel]; self.change=p.changes[sel] self.lastseg=np.nanmax(self.seg,axis=0) self.current=(self.seg==self.lastseg[None,:])&(self.change==0) self.segments=[((self.seg==k)&(self.change==0))[:,:,None] for k in range(1,int(np.nanmax(self.seg))+1)] self.lat=p.lat; self.lon=p.lon self.data={'annual':self.y,'season':p.month['T'][sel], 'night':p.month['TN'][sel], 'day':p.month['TX'][sel], 'monthly_max':p.month['MAX'][sel], 'monthly_p':p.month['P'][sel]} if p.month is not None else {'annual':self.y} self.data['log']=np.copy(self.y); self.data['log'][:,:,1]=np.log1p(self.y[:,:,1]); self.data['log'][:,:,3]=np.sqrt(np.maximum(0,self.y[:,:,3])) if p.month is not None: self.dd=p.month['CDD'][sel]; self.warm=p.month['WARM'][sel] self.cache={} @lru_cache(maxsize=128) def weight(self,window,decay=0): return (self.age1e-6),np.maximum(var,0.) @lru_cache(maxsize=16) def spatial(self,band): return kernel(self.lat,self.lon,band) @lru_cache(maxsize=512) def slope(self,key,window,decay,station,band,pool): if not window: return np.zeros(self.data[key].shape[1:]) slope,quality=self.raw_slope(key,window,decay,station) if pool==0: return slope s=self.scale(key) k=self.spatial(band) loc=np.divide(k@(slope*quality/s),k@quality,out=np.zeros_like(slope),where=(k@quality)>1e-12)*s info=np.divide(quality,np.maximum(1,np.max(quality,axis=0)),out=np.zeros_like(quality)) mix=(1-pool)*np.sqrt(info) return mix*slope+(1-mix)*loc def level(self,key,slope,window,decay=0,adjust=.6,median=0): y=self.data[key]; v=y-self.t*slope w=self.weight(window,decay); wg=w*self.current[:,:,None] level=avg(v,w); same=avg(v,wg) if median: med=wquant(v,w,median); medsame=wquant(v,wg,median) # Quantile corrections use the whole window when a station segment is short. level=level+.8*(med-level) same=np.where((wg*np.isfinite(y)).sum(axis=0)>8,same+.8*(medsame-same),same+.8*(med-avg(v,w))) n=(wg*np.isfinite(y)).sum(axis=0) alpha=adjust*n/(n+3) level=np.where(np.isfinite(same),alpha*same+(1-alpha)*level,level) backup=avg(v,self.weight(120,24)) return np.where(np.isfinite(level),level,backup) def line(self,key,window=40,decay=0,band=650,pool=.65,anchor=22,anchor_decay=0,station=True,adjust=.85,median=0,gain=1): sl=self.slope(key,window,decay,station,band,pool)*gain lv=self.level(key,sl,anchor,anchor_decay,adjust,median) return lv[None]+self.future*sl[None] def season_cdd(self,window,anchor,pool,band,decay=0,adjust=.8,gain=1,method='shift',quantile=.5): temp=self.data['season'] sl=self.slope('season',window,decay,True,band,pool)*gain if method=='monthly': # Calendar month trend scaled by the fraction of days above the CDD threshold. w=avg(self.warm,self.weight(max(anchor,20))) dsl=sl*np.nan_to_num(w,nan=0) dd=np.where(np.isfinite(self.dd),self.dd,np.nan) old=self.data.get('degree') self.data['degree']=dd lev=self.level('degree',dsl,anchor,0,adjust,0) fit=np.nansum(np.maximum(lev+self.future*dsl,0)*MONTH_LENGTH,axis=-1) return fit # Shift each recent year's seasonal degree-days by its climatological temperature trend. keep=(self.age[:,0,0]=11 lv=avg(days,self.weight(200)[keep]); exposure=np.where(np.isfinite(exposure),exposure,avg(exposure,np.ones_like(age))) w=np.where(good,1.,0.)*(1-adjust+adjust*self.current[keep]) out=[] for h in range(1,self.h+1): delta=(age+h)*sl[None] adjusted=np.maximum(0,np.where(np.isfinite(days),days,lv)+delta*exposure) aa=np.where(good,np.nansum(adjusted*MONTH_LENGTH,axis=-1),np.nan) mean=avg(aa,w); med=wquant(aa,w,quantile) out.append(.30*mean+.70*med) return np.stack(out) def season_max(self,window,anchor,pool,band,gain=1,adjust=.75,use_day=False): # Annual maximum of the 12 historical monthly maxima with separate monthly trends. key='day' if use_day else 'monthly_max' sl=self.slope(key,window,0,True,band,pool)*gain keep=self.age[:,0,0]