File size: 5,081 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
"""Predictable SST modes fitted separately at each forecast origin."""
import numpy as np
from models import avg

class Ocean:
    def __init__(self,o):
        self.o=o
        d=o.p.sst.loc[:f'{o.year}-12-31']
        annual=d.groupby(d.index.year).mean().reindex(o.yrs)
        nd=d[d.index.month.isin([10,11,12])]; nd=nd.groupby(nd.index.year).mean().reindex(o.yrs)
        self.year=o.yrs.astype(float)
        g=annual['global'].to_numpy(); self.g=g
        self.modes={
            'global':np.column_stack([g]),
            'climate':np.column_stack([g,annual['north_atlantic']-annual['north'],annual['ne_pacific']-annual['north'],annual['north_pacific']-annual['north']]),
            'enso':np.column_stack([nd['nino34']-nd['tropical'],nd['nino3']-nd['nino4']]),
            'pacific':np.column_stack([nd['nino34']-nd['tropical'],annual['ne_pacific']-annual['north'],annual['north_pacific']-annual['north']]),
            'all':np.column_stack([nd['nino34']-nd['tropical'],nd['nino3']-nd['nino4'],annual['ne_pacific']-annual['north'],annual['north_pacific']-annual['north'],annual['north_atlantic']-annual['north'],annual['subpolar_atlantic']-annual['north_atlantic'],annual['gulf']-annual['north_atlantic'],annual['indian']-annual['tropical'],g]),
        }

    def forced(self,window,anchor,globalwin,pool,band,gain=1,kind='global',persist=.4):
        o=self.o; y=o.y
        # A trailing average suppresses ENSO; fit levels and sensitivities after removing station effects.
        g=self.g
        gs=np.array([np.mean(g[max(0,i-5):i+1]) for i in range(len(g))])
        age=o.age[:,0,0]; win=age<globalwin
        slope=np.polyfit(self.year[win]-o.year,gs[win],1)[0]
        offset=np.mean(gs[-3:]+np.arange(2,-1,-1)*slope)
        gf=offset+slope*np.arange(1,o.h+1)
        xs=gs-gs[-1]; xf=gf-gs[-1]
        t=o.t
        scale=o.scale('annual'); yy=y/scale
        valid=np.isfinite(yy); z=np.where(valid,yy,0.); ww=o.weight(window)
        var=0.; cov=0.; time_cov=0.; tv=0.; tc=0.
        for seg in o.segments:
            w=ww*valid*seg; n=np.maximum(1e-10,w.sum(axis=0))
            x=xs[:,None,None]
            sx=(w*x).sum(axis=0); st=(w*t).sum(axis=0); sy=(w*z).sum(axis=0)
            var=var+(w*x*x).sum(axis=0)-sx*sx/n
            cov=cov+(w*x*z).sum(axis=0)-sx*sy/n
            tv=tv+(w*t*t).sum(axis=0)-st*st/n
            tc=tc+(w*x*t).sum(axis=0)-sx*st/n
            time_cov=time_cov+(w*t*z).sum(axis=0)-st*sy/n
        # Temperature response to ocean warming is pooled; residual trends are heavily shrunk.
        k=o.spatial(band)
        local=cov/np.maximum(var,.01)
        reg=(k@cov)/np.maximum(k@var,.01)
        beta=((1-pool)*local+pool*reg)*gain
        residual_trend=(time_cov-beta*tc)/np.maximum(tv,1)
        reg_trend=(k@(residual_trend*tv))/np.maximum(k@tv,1)
        trend=(.25*residual_trend+.75*reg_trend)*persist
        expected=xs[:,None,None]*beta+t*trend
        res=yy-expected
        w=o.weight(anchor); wg=w*o.current[:,:,None]
        aa=avg(res,w); bb=avg(res,wg); n=(wg*valid).sum(axis=0); a=.85*n/(n+3)
        lev=np.where(np.isfinite(bb),a*bb+(1-a)*aa,aa)
        return (lev+xf[:,None,None]*beta+o.future*trend)*scale

    def correction(self,mode='all',window=65,band=750,ridge=10,shape='direct',anchor=30):
        o=self.o; age=o.age[:,0,0]
        sl=o.slope('annual',45,0,True,650,.75)
        lv=o.level('annual',sl,anchor,0,.8,0)
        y=(o.y-o.t*sl-lv)/o.scale('annual')
        # Segment offsets prevent location changes from masquerading as teleconnections.
        for seg in o.segments:
            s=avg(y,o.weight(90)*seg)
            y=np.where(seg,y-s,y)
        x=self.modes[mode].copy()
        if mode=='all':
            x=np.column_stack([x,np.diff(x[:,[0,2,3]],axis=0,prepend=x[:1,[0,2,3]])])
        # Trailing climatological departures only. All feature rows are known at their own origins.
        if shape=='detrend':
            for j in range(x.shape[1]):
                slp,off=np.polyfit(self.year[-window:]-o.year,x[-window:,j],1)
                x[:,j]-=slp*(self.year-o.year)+off
        else:
            x=np.stack([row-x[max(0,i-20):i+1].mean(axis=0) for i,row in enumerate(x)])
        st=np.maximum(x[-window:].std(axis=0),1e-4); x/=st
        k=o.spatial(band); out=[]
        for h in range(1,o.h+1):
            X=x[:-h]; yy=y[h:]; take=age[:-h]<window
            X=X[take]; yy=yy[take]
            w=np.isfinite(yy).astype(float); y0=np.nan_to_num(yy,nan=0.)
            n=np.maximum(1,w.sum(axis=0)); wmean=np.einsum('ti,tcm->icm',X,w)/n
            v=np.einsum('ti,tcm->icm',X,y0)-wmean*y0.sum(axis=0)
            # One covariance per regional sample, rather than pretending all cities are independent.
            v=(np.einsum('ab,ibm->iam',k,v)/np.maximum(k@n,1)[None])*len(X)
            xc=X-X.mean(axis=0)
            coef=np.linalg.solve(xc.T@xc+ridge*np.eye(xc.shape[1]),v.reshape(len(st),-1)).reshape(v.shape)
            corr=np.einsum('i,icm->cm',x[-1]-X.mean(axis=0),coef)
            out.append(corr*o.scale('annual'))
        return np.stack(out)