File size: 9,250 Bytes
993d9a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
"""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_above<len(a),first_above,last)
    prev=np.where((ws>0)&(ix<k),ix,-1).max(axis=0)
    j=np.where(prev>=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.age<window)*np.exp(-self.age/max(decay,1)) if decay else (self.age<window).astype(float)

    @lru_cache(maxsize=128)
    def scale(self,key):
        y=self.data[key]
        if key=='annual':
            # Share precipitation slopes in fractional terms and CDD slopes per cooling day.
            mu=avg(y,self.weight(35))
            s=np.ones_like(mu)
            s[:,1]=np.maximum(12,mu[:,1]); s[:,3]=np.maximum(25,avg(self.warm,self.weight(35))@MONTH_LENGTH) if self.p.month is not None else np.maximum(25,30+.09*mu[:,3])
            return np.where(np.isfinite(s),s,1.)
        if key=='monthly_p': return np.maximum(.02,np.nan_to_num(avg(y,self.weight(40)),nan=.06))
        return np.ones(y.shape[1:])

    @lru_cache(maxsize=256)
    def raw_slope(self,key,window,decay,station):
        y=self.data[key]; wt=self.weight(window,decay)
        val=np.where(np.isfinite(y),y,0.)
        cov=0.; var=0.; n=0.
        for g in (self.segments if station else [1.]):
            w=wt*g*np.isfinite(y)
            s=w.sum(axis=0); den=np.maximum(1e-10,s)
            sx=(w*self.t).sum(axis=0); sy=(w*val).sum(axis=0)
            cov=cov+(w*self.t*val).sum(axis=0)-sx*sy/den
            var=var+(w*self.t**2).sum(axis=0)-sx*sx/den
            n=n+s
        return np.divide(cov,var,out=np.zeros_like(cov),where=var>1e-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]<anchor)
        days=self.dd[keep]; exposure=self.warm[keep]; age=self.age[keep]
        good=np.isfinite(days).sum(axis=2)>=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]<anchor
        vals=self.data['monthly_max'][keep]; age=self.age[keep]
        good=np.isfinite(self.y[keep,:,2]); w=np.where(good,1.,0.)*(1-adjust+adjust*self.current[keep])
        out=[]
        for h in range(1,self.h+1):
            arr=vals+(age+h)*sl[None]
            aa=np.where(good,np.max(np.where(np.isfinite(arr),arr,-np.inf),axis=-1),np.nan)
            aa=np.where(np.isfinite(aa),aa,np.nan)
            out.append(.5*avg(aa,w)+.5*wquant(aa,w))
        return np.stack(out)

    def recent_persistence(self,key='annual',years=5,base=32,band=650,damp=.5):
        sl=self.slope(key,40,0,True,band,.75)
        y=self.data[key]; lv=self.level(key,sl,base,0,.85,0)
        e=y-self.t*sl-lv
        recent=avg(e,self.weight(years))
        k=self.spatial(band); s=self.scale(key)
        zz=np.isfinite(recent)
        p=(k@np.nan_to_num(recent/s))/np.maximum(k@zz,1e-10)*s
        return (damp**(self.future-1))*p

    def final_values(self,a):
        if 'fallback' not in self.cache:
            self.cache['fallback']=self.line('annual',window=0,anchor=50,adjust=.4)
        return np.where(np.isfinite(a),a,self.cache['fallback'])