forked from nansencenter/DAPPER
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathda_methods.py
More file actions
2004 lines (1645 loc) · 61.2 KB
/
da_methods.py
File metadata and controls
2004 lines (1645 loc) · 61.2 KB
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from common import *
@DA_Config
def EnKF(upd_a,N,infl=1.0,rot=False,**kwargs):
"""
The EnKF.
Ref: Evensen, Geir. (2009):
"The ensemble Kalman filter for combined state and parameter estimation."
Settings for reproducing literature benchmarks may be found in
mods/Lorenz95/sak08.py
"""
def assimilator(stats,twin,xx,yy):
f,h,chrono,X0 = twin.f, twin.h, twin.t, twin.X0
# Init
E = X0.sample(N)
stats.assess(0,E=E)
# Loop
for k,kObs,t,dt in progbar(chrono.forecast_range):
E = f(E,t-dt,dt)
E = add_noise(E, dt, f.noise, kwargs)
# Analysis update
if kObs is not None:
stats.assess(k,kObs,'f',E=E)
E = EnKF_analysis(E,h(E,t),h.noise,yy[kObs],upd_a,stats,kObs)
E = post_process(E,infl,rot)
stats.assess(k,kObs,E=E)
return assimilator
def EnKF_analysis(E,hE,hnoise,y,upd_a,stats,kObs):
"""
The EnKF analysis update.
'upd_a' selects between the different versions.
References:
Sakov and Oke (2008). "Implications of the Form of the ... EnSRF..."
Sakov and Oke (2008). "A deterministic formulation of the EnKF..."
"""
R = hnoise.C
N,m = E.shape
mu = mean(E,0)
A = E - mu
hx = mean(hE,0)
Y = hE-hx
dy = y - hx
if 'PertObs' in upd_a:
# Uses perturbed observations (burgers'98)
C = Y.T @ Y + R.full*(N-1)
D = center(hnoise.sample(N))
YC = mrdiv(Y, C)
KG = A.T @ YC
HK = Y.T @ YC
dE = (KG @ ( y + D - hE ).T).T
E = E + dE
elif 'Sqrt' in upd_a:
# Uses a symmetric square root (ETKF)
# to deterministically transform the ensemble.
#
# The various versions below differ only numerically.
# EVD is default, but for large N use SVD version.
if upd_a == 'Sqrt' and N>m: upd_a = 'Sqrt svd'
#
if 'explicit' in upd_a:
# Not recommended.
# Implementation using inv (in ens space)
Pw = inv(Y @ R.inv @ Y.T + (N-1)*eye(N))
T = sqrtm(Pw) * sqrt(N-1)
HK = R.inv @ Y.T @ Pw @ Y
#KG = R.inv @ Y.T @ Pw @ A
elif 'svd' in upd_a:
# Implementation using svd of Y R^{-1/2}.
V,s,_ = svd0(Y @ R.sym_sqrt_inv.T)
d = pad0(s**2,N) + (N-1)
Pw = ( V * d**(-1.0) ) @ V.T
T = ( V * d**(-0.5) ) @ V.T * sqrt(N-1)
trHK = np.sum( (s**2+(N-1))**(-1.0) * s**2 ) # see docs/trHK.jpg
elif 'sS' in upd_a:
# Same as 'svd', but with slightly different notation
# (sometimes used by Sakov) using the normalization sqrt(N-1).
S = Y @ R.sym_sqrt_inv.T / sqrt(N-1)
V,s,_ = svd0(S)
d = pad0(s**2,N) + 1
Pw = ( V * d**(-1.0) )@V.T / (N-1) # = G/(N-1)
T = ( V * d**(-0.5) )@V.T
trHK = np.sum( (s**2 + 1)**(-1.0)*s**2 ) # see docs/trHK.jpg
else: # 'eig' in upd_a:
# Implementation using eig. val. decomp.
d,V = eigh(Y @ R.inv @ Y.T + (N-1)*eye(N))
T = V@diag(d**(-0.5))@V.T * sqrt(N-1)
Pw = V@diag(d**(-1.0))@V.T
HK = R.inv @ Y.T @ (V@ diag(d**(-1)) @V.T) @ Y
w = dy @ R.inv @ Y.T @ Pw
E = mu + w@A + T@A
elif 'Serial' in upd_a:
# Observations assimilator one-at-a-time.
# Even though it's derived as "serial ETKF",
# it's not equivalent to 'Sqrt' for the actual ensemble,
# although it does yield the same mean/cov.
# See DAPPER/Misc/batch_vs_serial.py for more details.
inds = serial_inds(upd_a, y, R, A)
z = dy@ R.sym_sqrt_inv.T / sqrt(N-1)
S = Y @ R.sym_sqrt_inv.T / sqrt(N-1)
T = eye(N)
for j in inds:
# Possibility: re-compute Sj by non-lin h.
Sj = S[:,j]
Dj = Sj@Sj + 1
Tj = np.outer(Sj, Sj / (Dj + sqrt(Dj)))
T -= Tj @ T
S -= Tj @ S
GS = S.T @ T
E = mu + z@GS@A + T@A
trHK = trace(R.sym_sqrt_inv.T@GS@Y)/sqrt(N-1) # Correct?
elif 'DEnKF' is upd_a:
# Uses "Deterministic EnKF" (sakov'08)
C = Y.T @ Y + R.full*(N-1)
YC = mrdiv(Y, C)
KG = A.T @ YC
HK = Y.T @ YC
E = E + KG@dy - 0.5*(KG@Y.T).T
else:
raise KeyError("No analysis update method found: '" + upd_a + "'.")
# Diagnostic: relative influence of observations
if 'trHK' in locals(): stats.trHK[kObs] = trHK /hnoise.m
elif 'HK' in locals(): stats.trHK[kObs] = trace(HK)/hnoise.m
return E
def post_process(E,infl,rot):
"""
Inflate, Rotate.
To avoid recomputing/recombining anomalies, this should be inside EnKF_analysis().
But for readability it is nicer to keep it as a separate function,
also since it avoids inflating/rotationg smoothed states (for the EnKS).
"""
do_infl = infl!=1.0
if do_infl or rot:
A, mu = anom(E)
N,m = E.shape
T = eye(N)
if do_infl:
T = infl * T
if rot:
T = genOG_1(N,rot) @ T
E = mu + T@A
return E
def add_noise(E, dt, noise, config):
"""
Treatment of additive noise for ensembles.
Settings for reproducing literature benchmarks may be found in
mods/LA/raanes2015.py
Ref: Raanes, Patrick Nima, Alberto Carrassi, and Laurent Bertino (2015):
"Extending the square root method to account for additive forecast noise in ensemble methods."
"""
method = config.get('fnoise_treatm','Stoch')
if noise.C is 0: return E
N,m = E.shape
A,mu = anom(E)
Q12 = noise.C.Left
Q = noise.C.full
def sqrt_core():
T = np.nan # cause error if used
Qa12 = np.nan # cause error if used
A2 = A.copy() # Instead of using (the implicitly nonlocal) A,
# which changes A outside as well. NB: This is a bug in Datum!
if N<=m:
Ainv = tinv(A2.T)
Qa12 = Ainv@Q12
T = funm_psd(eye(N) + dt*(N-1)*(Qa12@Qa12.T), sqrt)
A2 = T@A2
else: # "Left-multiplying" form
P = A2.T @ A2 /(N-1)
L = funm_psd(eye(m) + dt*mrdiv(Q,P), sqrt)
A2= A2 @ L.T
E = mu + A2
return E, T, Qa12
if method == 'Stoch':
# In-place addition works (also) for empty [] noise sample.
E += sqrt(dt)*noise.sample(N)
elif method == 'none':
pass
elif method == 'Mult-1':
varE = np.var(E,axis=0,ddof=1).sum()
ratio = (varE + dt*diag(Q).sum())/varE
E = mu + sqrt(ratio)*A
E = reconst(*tsvd(E,0.999)) # Explained in Datum
elif method == 'Mult-m':
varE = np.var(E,axis=0)
ratios = sqrt( (varE + dt*diag(Q))/varE )
E = mu + A*ratios
E = reconst(*tsvd(E,0.999)) # Explained in Datum
elif method == 'Sqrt-Core':
E = sqrt_core()[0]
elif method == 'Sqrt-Add-Z':
E, _, Qa12 = sqrt_core()
if N<=m:
Z = Q12 - A.T@Qa12
E += sqrt(dt)*(Z@randn((Z.shape[1],N))).T
elif method == 'Sqrt-Dep':
E, T, Qa12 = sqrt_core()
if N<=m:
# Q_hat12: reuse svd for both inversion and projection.
Q_hat12 = A.T @ Qa12
U,s,VT = tsvd(Q_hat12,0.99)
Q_hat12_inv = (VT.T * s**(-1.0)) @ U.T
Q_hat12_proj = VT.T@VT
rQ = Q12.shape[1]
# Calc D_til
Z = Q12 - Q_hat12
D_hat = A.T@(T-eye(N))
Xi_hat = Q_hat12_inv @ D_hat
Xi_til = (eye(rQ) - Q_hat12_proj)@randn((rQ,N))
D_til = Z@(Xi_hat + sqrt(dt)*Xi_til)
E += D_til.T
else:
raise KeyError('No such method')
return E
# Reshapings used in smoothers to go to/from
# 3D arrays, where the 0th axis is the Lag index.
def reshape_to(E):
K,N,m = E.shape
return E.transpose([1,0,2]).reshape((N,K*m))
def reshape_fr(E,m):
N,Km = E.shape
K = Km//m
return E.reshape((N,K,m)).transpose([1,0,2])
@DA_Config
def EnKS(upd_a,N,tLag,infl=1.0,rot=False,**kwargs):
"""
EnKS (ensemble Kalman smoother)
Ref: Evensen, Geir. (2009):
"The ensemble Kalman filter for combined state and parameter estimation."
The only difference to the EnKF is the management of the lag and the reshapings.
Settings for reproducing literature benchmarks may be found in
mods/Lorenz95/raanes2016.py
"""
def assimilator(stats,twin,xx,yy):
f,h,chrono,X0 = twin.f, twin.h, twin.t, twin.X0
E = zeros((chrono.K+1,N,f.m))
E[0] = X0.sample(N)
for k,kObs,t,dt in progbar(chrono.forecast_range):
E[k] = f(E[k-1],t-dt,dt)
E[k] = add_noise(E[k], dt, f.noise, kwargs)
if kObs is not None:
stats.assess(k,kObs,'f',E=E[k])
kLag = find_1st_ind(chrono.tt >= t-tLag)
kkLag = range(kLag, k+1)
ELag = E[kkLag]
hE = h(E[k],t)
y = yy[kObs]
ELag = reshape_to(ELag)
ELag = EnKF_analysis(ELag,hE,h.noise,y,upd_a,stats,kObs)
E[kkLag] = reshape_fr(ELag,f.m)
E[k] = post_process(E[k],infl,rot)
stats.assess(k,kObs,'a',E=E[k])
for k in progbar(range(chrono.K+1),desc='Assessing'):
stats.assess(k,None,'u',E=E[k])
return assimilator
@DA_Config
def EnRTS(upd_a,N,cntr,infl=1.0,rot=False,**kwargs):
"""
EnRTS (Rauch-Tung-Striebel) smoother.
Ref: Raanes, Patrick Nima. (2016):
"On the ensemble Rauch‐Tung‐Striebel smoother..."
Settings for reproducing literature benchmarks may be found in
mods/Lorenz95/raanes2016.py
"""
def assimilator(stats,twin,xx,yy):
f,h,chrono,X0 = twin.f, twin.h, twin.t, twin.X0
E = zeros((chrono.K+1,N,f.m))
Ef = E.copy()
E[0] = X0.sample(N)
# Forward pass
for k,kObs,t,dt in progbar(chrono.forecast_range):
E[k] = f(E[k-1],t-dt,dt)
E[k] = add_noise(E[k], dt, f.noise, kwargs)
Ef[k] = E[k]
if kObs is not None:
stats.assess(k,kObs,'f',E=E[k])
hE = h(E[k],t)
y = yy[kObs]
E[k] = EnKF_analysis(E[k],hE,h.noise,y,upd_a,stats,kObs)
E[k] = post_process(E[k],infl,rot)
stats.assess(k,kObs,'a',E=E[k])
# Backward pass
for k in progbar(range(chrono.K)[::-1]):
A = anom(E[k])[0]
Af = anom(Ef[k+1])[0]
J = tinv(Af) @ A
J *= cntr
E[k] += ( E[k+1] - Ef[k+1] ) @ J
for k in progbar(range(chrono.K+1),desc='Assessing'):
stats.assess(k,E=E[k])
return assimilator
def serial_inds(upd_a, y, cvR, A):
if 'mono' in upd_a:
# Not robust?
inds = arange(len(y))
elif 'sorted' in upd_a:
dC = cvR.diag
if np.all(dC == dC[0]):
# Sort y by P
dC = np.sum(A*A,0)/(N-1)
inds = np.argsort(dC)
else: # Default: random ordering
inds = np.random.permutation(len(y))
return inds
@DA_Config
def SL_EAKF(loc_rad,N,taper='GC',ordr='rand',infl=1.0,rot=False,**kwargs):
"""
Serial, covariance-localized EAKF.
Ref: Karspeck, Alicia R., and Jeffrey L. Anderson. (2007):
"Experimental implementation of an ensemble adjustment filter..."
Used without localization, this should be equivalent
(full ensemble equality) to the EnKF 'Serial'.
See DAPPER/Misc/batch_vs_serial.py for some details.
"""
def assimilator(stats,twin,xx,yy):
f,h,chrono,X0 = twin.f, twin.h, twin.t, twin.X0
n = N-1
R = h.noise
Rm12 = h.noise.C.sym_sqrt_inv
E = X0.sample(N)
stats.assess(0,E=E)
for k,kObs,t,dt in progbar(chrono.forecast_range):
E = f(E,t-dt,dt)
E = add_noise(E, dt, f.noise, kwargs)
if kObs is not None:
stats.assess(k,kObs,'f',E=E)
y = yy[kObs]
inds = serial_inds(ordr, y, R, anom(E)[0])
locf_at = h.loc_f(loc_rad, 'y2x', t, taper)
for i,j in enumerate(inds):
hE = h(E,t)
hx = mean(hE,0)
Y = (hE - hx).T
mu = mean(E ,0)
A = E-mu
# Update j-th component of observed ensemble
Yj = Rm12[j,:] @ Y
dyj = Rm12[j,:] @ (y - hx)
#
skk = Yj@Yj
su = 1/( 1/skk + 1/n )
alpha = (n/(n+skk))**(0.5)
#
dy2 = su*dyj/n # (mean is absorbed in dyj)
Y2 = alpha*Yj
if skk<1e-9: continue
# Update state (regression), with localization
# Localize
local, coeffs = locf_at(j)
if len(local) == 0: continue
Regression = (A[:,local]*coeffs).T @ Yj/np.sum(Yj**2)
mu[ local] += Regression*dy2
A[:,local] += np.outer(Y2 - Yj, Regression)
# Without localization:
#Regression = A.T @ Yj/np.sum(Yj**2)
#mu += Regression*dy2
#A += np.outer(Y2 - Yj, Regression)
E = mu + A
E = post_process(E,infl,rot)
stats.assess(k,kObs,E=E)
return assimilator
@DA_Config
def LETKF(loc_rad,N,taper='GC',approx=False,infl=1.0,rot=False,**kwargs):
"""
Same as EnKF (sqrt), but with localization.
Settings for reproducing literature benchmarks may be found in
mods/Lorenz95/sak08.py
Ref: Hunt, Brian R., Eric J. Kostelich, and Istvan Szunyogh. (2007):
"Efficient data assimilation for spatiotemporal chaos..."
"""
def assimilator(stats,twin,xx,yy):
f,h,chrono,X0 = twin.f, twin.h, twin.t, twin.X0
Rm12 = h.noise.C.sym_sqrt_inv
E = X0.sample(N)
stats.assess(0,E=E)
for k,kObs,t,dt in progbar(chrono.forecast_range):
E = f(E,t-dt,dt)
E = add_noise(E, dt, f.noise, kwargs)
if kObs is not None:
stats.assess(k,kObs,'f',E=E)
mu = mean(E,0)
A = E - mu
hE = h(E,t)
hx = mean(hE,0)
YR = (hE-hx) @ Rm12.T
yR = (yy[kObs] - hx) @ Rm12.T
locf_at = h.loc_f(loc_rad, 'x2y', t, taper)
for i in range(f.m):
# Localize
local, coeffs = locf_at(i)
if len(local) == 0: continue
iY = YR[:,local] * sqrt(coeffs)
idy = yR[local] * sqrt(coeffs)
# Do analysis
if approx:
# Approximate alternative, derived by pretending that Y_loc = H @ A_i,
# even though the local cropping of Y happens after application of H.
# Anyways, with an explicit H, one can apply Woodbury
# to go to state space (dim==1), before reverting to HA_i = Y_loc.
n = N-1
B = A[:,i]@A[:,i] / n
AY = A[:,i]@iY
BmR = AY@AY.T
T2 = (1 + BmR/(B*n**2))**(-1)
AT = sqrt(T2) * A[:,i]
P = T2 * B
dmu = P*(AY/(n*B))@idy
else:
# Non-Approximate
if len(local) < N:
# SVD version
V,sd,_ = svd0(iY)
d = pad0(sd**2,N) + (N-1)
Pw = (V * d**(-1.0)) @ V.T
T = (V * d**(-0.5)) @ V.T * sqrt(N-1)
else:
# EVD version
d,V = eigh(iY @ iY.T + (N-1)*eye(N))
T = V@diag(d**(-0.5))@V.T * sqrt(N-1)
Pw = V@diag(d**(-1.0))@V.T
AT = T@A[:,i]
dmu = idy@iY.T@Pw@A[:,i]
E[:,i] = mu[i] + dmu + AT
E = post_process(E,infl,rot)
if 'sd' in locals():
stats.trHK[kObs] = (sd**(-1.0) * sd**2).sum()/h.noise.m
#else:
# nevermind
stats.assess(k,kObs,E=E)
return assimilator
# Notes on optimizers for the 'dual' EnKF-N:
# ----------------------------------------
# Using minimize_scalar:
# - don't accept dJdx. Pro: only need J :-)
# - method='bounded' not necessary and slower than 'brent'.
# - bracket not necessary either...
# Using multivariate minimization: fmin_cg, fmin_bfgs, fmin_ncg
# - these also accept dJdx. But only fmin_bfgs approaches
# the speed of the scalar minimizers.
# Using scalar root-finders:
# - brenth(dJ1, LowB, 1e2, xtol=1e-6) # Same speed as minimmization
# - newton(dJ1,1.0, fprime=dJ2, tol=1e-6) # No improvement
# - newton(dJ1,1.0, fprime=dJ2, tol=1e-6, fprime2=dJ3) # No improvement
# - Newton_m(dJ1,dJ2, 1.0) # Significantly faster. Also slightly better CV?
# => Despite inconvienience of defining analytic derivatives,
# Newton_m seems like the best option.
# - In extreme (or just non-linear h) cases,
# the EnKF-N cost function may have multiple minima.
# Then: should use more robust optimizer!
#
# For 'primal'
# ----------------------------------------
#
# Similarly, Newton_m seems like the best option,
# although alternatives are provided (commented out).
def Newton_m(fun,deriv,x0,is_inverted=False,
conf=1.0,xtol=1e-4,ytol=1e-7,itermax=10**2):
"Simple (and quick) implementation of Newton root-finding"
itr, dx, Jx = 0, np.inf, fun(x0)
norm = lambda x: sqrt(np.sum(x**2))
while ytol<norm(Jx) and xtol<norm(dx) and itr<itermax:
Dx = deriv(x0)
if is_inverted:
dx = Dx @ Jx
elif isinstance(Dx,float):
dx = Jx/Dx
else:
dx = mldiv(Dx,Jx)
dx *= conf
x0 -= dx
Jx = fun(x0)
return x0
@DA_Config
def EnKF_N(N,dual=True,Hess=False,g=0,nu=1.0,infl=1.0,rot=False,**kwargs):
"""
Finite-size EnKF (EnKF-N).
Reference:
Boc15: Bocquet, Marc, Patrick N. Raanes, and Alexis Hannart. (2015):
"Expanding the validity of the ensemble Kalman filter..."
This implementation favours the efficiency of the 'dual' formulation.
The 'primal' formulation is there mainly to show equivalence
(to the dual, provided the same minimum is found by the optimizers),
and to allow comparison with iEnKS_N(), which uses the full, non-lin h.
'infl' should be unnecessary.
'Hess': use non-approx Hessian for ensemble transform matrix?
'g' is the nullity of A (state anom's), ie. g=max(1,N-m).
But we have made it an input argument instead, with default 0,
because we don't think it's beneficial.
'nu' (not yet described in litteture)
allows tuning the hyper-prior for the inflation:
- nu=1: is fully agnostic, i.e. assumes the ensemble is generated
from a highly chaotic or stochastic model.
- nu>1: increases the certainty of the hyper-prior,
which is appropriate for more linear and deterministic systems.
- nu<1: yields a more (than 'fully') agnostic hyper-prior,
as if N were smaller than it truly is.
- nu<=0 is not meaningful.
Mode-correction is used (almost) as in eqn 36 of Boc15.
Settings for reproducing literature benchmarks may be found in
mods/Lorenz95/sak08.py
mods/Lorenz63/sak12.py
"""
def assimilator(stats,twin,xx,yy):
# Unpack
f,h,chrono,X0,R = twin.f, twin.h, twin.t, twin.X0, twin.h.noise.C
# EnKF-N constants
N1 = N-1 # Abbrev
eN_ = (N+1)/N # Effect of unknown mean
cL_ = (N+g)/N1 # Coeff in front of log term
prior_mode = eN_/cL_ # Mode of l1 (un-corrected)
# Init
E = X0.sample(N)
stats.assess(0,E=E)
# Loop
for k,kObs,t,dt in progbar(chrono.forecast_range):
# Forecast
E = f(E,t-dt,dt)
E = add_noise(E, dt, f.noise, kwargs)
# Analysis
if kObs is not None:
stats.assess(k,kObs,'f',E=E)
hE = h(E,t)
y = yy[kObs]
mu = mean(E,0)
A = E - mu
hx = mean(hE,0)
Y = hE-hx
dy = y - hx
V,s,UT = svd0 (Y @ R.sym_sqrt_inv.T)
du = UT @ (dy @ R.sym_sqrt_inv.T)
dgn_N = lambda l: pad0( (l*s)**2, N ) + N1
# As a func of I-KH ("prior's weight"), adjust l1's mode towards 1.
# Note: I-HK = mean( dgn_N(1.0)**(-1) )/N ≈ 1/(1 + HBH/R).
I_KH = mean( dgn_N(1.0)**(-1) )*N1 # Normalize by f.m ?
#I_KH = 1/(1 + (s**2).sum()/N1) # Alternative: use tr(HBH/R).
mc = sqrt(prior_mode**I_KH) # "mode correction".
# Certainty (nu) estimation
if nu is 'adapt':
L = 40
# Memorize inflation values
if kObs==0: infls = 1+sqrt(0.082)*randn(L) # Init st. nu becomes 1
else: infls = roll_n_sub(infls,stats.infl[kObs-1],0) # FIFO
weights = arange(L,0,-1) / (L*(L+1)/2) # 1,2,...L normalized
infl_var = weights@(infls - weights@infls)**2
nu_ = 0.75-0.1*log(infl_var) # Empirisism based on L95 experiments
nu_ = max(0.64,nu_)
else:
nu_ = nu
# Apply adjustments
eN = eN_*nu_/mc
cL = cL_*nu_*mc
if dual:
# Make dual cost function (in terms of l1)
pad_rk = lambda arr: pad0( arr, min(N,h.m) )
dgn_rk = lambda l: pad_rk((l*s)**2) + N1
J = lambda l: np.sum(du**2/dgn_rk(l)) \
+ eN/l**2 \
+ cL*log(l**2)
# Derivatives
Jp = lambda l: -2*l * np.sum(pad_rk(s**2) * du**2/dgn_rk(l)**2) \
+ -2*eN/l**3 \
+ 2*cL/l
Jpp = lambda l: 8*l**2 * np.sum(pad_rk(s**4) * du**2/dgn_rk(l)**3) \
+ 6*eN/l**4 \
+ -2*cL/l**2
# Find inflation factor (optimize)
l1 = Newton_m(Jp,Jpp,1.0)
#l1 = fmin_bfgs(J, x0=[1], gtol=1e-4, disp=0)
#l1 = minimize_scalar(J, bracket=(sqrt(prior_mode), 1e2), tol=1e-4).x
else:
# Primal form, in a fully linearized version.
za = lambda w: N1*cL/(eN + w@w) # zeta_a
J = lambda w: .5*np.sum(( (dy-w@Y)@R.sym_sqrt_inv.T)**2 ) + \
.5*N1*cL*log(eN + w@w)
# Derivatives
Jp = lambda w: -Y@R.inv@(dy-w@Y) + N1*cL*w/(eN + w@w)
#Jpp = lambda w: Y@R.inv@Y.T + za(w)*(eye(N) - 2*np.outer(w,w)/(eN + w@w))
#Jpp = lambda w: Y@R.inv@Y.T + za(w)*eye(N) # approx: no radial-angular cross-deriv
nvrs = lambda w: (V * (pad0(s**2,N) + za(w))**-1.0) @ V.T # inverse of Jpp-approx
# Find w (optimize)
wa = Newton_m(Jp,nvrs,zeros(N),is_inverted=True)
#wa = Newton_m(Jp,Jpp ,zeros(N))
#wa = fmin_bfgs(J,zeros(N),Jp,disp=0)
l1 = sqrt(N1/za(wa))
# Uncomment to revert to ETKF
#l1 = 1.0
# Explicitly inflate prior => formulae look different from Boc15.
A *= l1
Y *= l1
# Compute sqrt update
Pw = (V * dgn_N(l1)**(-1.0)) @ V.T
w = dy@R.inv@Y.T@Pw
# For the anomalies:
if not Hess:
# Regular ETKF (i.e. sym sqrt) update (with inflation)
T = (V * dgn_N(l1)**(-0.5)) @ V.T * sqrt(N1)
# = (Y@R.inv@Y.T/N1 + eye(N))**(-0.5)
else:
# Also include angular-radial co-dependence.
Hw = Y@R.inv@Y.T/N1 + eye(N) - 2*np.outer(w,w)/(eN + w@w)
T = funm_psd(Hw, lambda x: x**-.5) # is there a sqrtm Woodbury?
E = mu + w@A + T@A
E = post_process(E,infl,rot)
stats.infl[kObs] = l1
stats.trHK[kObs] = (((l1*s)**2 + N1)**(-1.0)*s**2).sum()/h.noise.m
stats.assess(k,kObs,E=E)
return assimilator
# It is necessary to have a prior mode lower than 1:
# This sets up "tension" (negative feedback) in the inflation cycle:
# the prior pulls downwards, while the likelihood tends to pull upwards.
# and the possibility of high values due to the likelihood.
# Mode correction obviously becomes necessary, however, when R-->infty,
# because then there should be no ensemble update (and also no inflation!).
@DA_Config
def iEnKS(upd_a,N,Lag=1,iMax=10,nu=1.0,bundle=False,infl=1.0,rot=False,**kwargs):
"""
Iterative EnKS-N
References:
Boc14: Marc Bocquet, and Pavel Sakov. (2014):
"An iterative ensemble Kalman smoother."
Boc12: Marc Bocquet, and Pavel Sakov. (2012):
"Combining inflation-free and iterative EnKFs ..."
Options:
- upd_a : 'Sqrt' (i.e. ETKF) or '-N' (i.e. EnKF-N)
- Lag : the length of the data assimilation window (DAW).
Its default, 1 (dkObs) yields the iterative "filter" iEnKF.
- bundle: Use bundle (finite difference) or transform (regression)
linearizations. For details, see Boc12.
If True, then the statistics for spread (etc) will
be very small, but we have not bothered to correct this.
As in Boc14, the minimization is done with Gauss-Newton.
See Boc12 for a Levenberg-Marquardt approach.
As in Boc14, the shift (S) is fixed at 1.
MDA (progressive assimilation) is not implemented because
- The balancing step is convoluted
- Trouble playing nice with '-N'
Settings for reproducing literature benchmarks may be found in
mods/Lorenz95/sak08.py
mods/Lorenz95/sak12.py
mods/Lorenz95/boc12.py
"""
N1 = N-1
# Hessian of analysis cost function for w: Y@R.inv@Y + za(w)*I,
# both for EnKF-N and ETKF. Here we define za.
if upd_a == 'Sqrt':
# No adaptive inflation
def zeta_a(_,__): return N1
elif upd_a == '-N':
# See EnKF_N() for details
g = 0
eN_ = (N+1)/N
cL_ = (N+g)/N1
prior_mode = eN_/cL_
def zeta_a(s,w):
diagonal = pad0( s**2, N ) + N1
I_KH = mean( diagonal**(-1) )*N1
mc = sqrt(prior_mode**I_KH)
eN = eN_*nu/mc
cL = cL_*nu*mc
za = N1*cL/(eN + w@w)
return za
def assimilator(stats,twin,xx,yy):
f,h,chrono,X0,R,KObs = twin.f, twin.h, twin.t, twin.X0, twin.h.noise.C, twin.t.KObs
assert f.noise.C is 0, "Q>0 not supported"
# Init DA cycles
E = X0.sample(N)
stats.iters = np.full(KObs+1,nan)
# Loop DA cycles
for kObs in progbar(arange(KObs+1)):
# Store 0th (iteration) estimate as (xf,Af)
Af,xf = anom(E)
# Init iterations
w = zeros(N)
Tinv = eye(N)
T = eye(N)
# Set (shifting) DA Window
DAW_0 = kObs-Lag+1
DAW = arange(max(0,DAW_0),DAW_0+Lag)
# Loop iterations
for iteration in arange(iMax):
if bundle:
T = 1e-4*eye(N)
Tinv = 1e+4*eye(N)
# Forecast
E = xf + w @ Af + T @ Af # Current estimate of E[kObs-Lag]
for kDAW in DAW: # Loop Lag cycles
for k,t,dt in chrono.obs_range(kDAW): # Loop dkObs steps (1 cycle)
E = f(E,t-dt,dt) # Forecast 1 dt step (1 dkObs)
if iteration==0:
stats.assess(k,kObs,'f',E=E)
# Analysis of y[kObs] (already assim'd [:kObs])
y = yy[kObs]
Y,hx = anom(h(E,t))
# "Uncondition" the observation anomalies
# (and yet this linearization of h improves with iterations)
Y = Tinv @ Y
# Transform obs space
Y = Y @ R.sym_sqrt_inv.T
dy = (y - hx) @ R.sym_sqrt_inv.T
# Prepare analysis: do SVD
V,s,UT = svd0(Y)
za = zeta_a(s,w)
# Gauss-Newton ingredients
grad = -Y@dy + w*za
Pw = (V * (pad0(s**2,N) + za)**-1.0) @ V.T
# Linearization improvement
T = (V * (pad0(s**2,N) + za)**-0.5) @ V.T * sqrt(N1)
Tinv = (V * (pad0(s**2,N) + za)**+0.5) @ V.T / sqrt(N1)
# Gauss-Newton step
dw = Pw@grad
w -= dw
# Stopping condition
if np.linalg.norm(dw) < N*1e-4:
break
# Analysis 'a' stats for E[kObs].
stats.assess(k,kObs,'a',E=E)
stats.trHK [kObs] = trace(Y.T @ Pw @ Y)/h.noise.m
stats.iters[kObs] = iteration+1
stats.infl [kObs] = sqrt(N1/za)
# Final (smoothed) estimate of E[kObs-Lag]
E = xf + w @ Af + T @ Af
E = post_process(E,infl,rot)
# Forecast smoothed ensemble by shift (1*dkObs)
if DAW_0 >= 0:
for k,t,dt in chrono.obs_range(DAW_0):
stats.assess(k-1,None,'u',E=E)
E = f(E,t-dt,dt)
# Assess the last (Lag-1) obs ranges
for kDAW in arange(DAW[0]+1,KObs+1):
for k,t,dt in chrono.obs_range(kDAW):
stats.assess(k-1,None,'u',E=E)
E = f(E,t-dt,dt)
stats.assess(chrono.K,None,'u',E=E)
return assimilator
@DA_Config
def EnKF_AdInf(N,infl=1.0,rot=False,Sb2=1.0,Nb=4,Fb=0.99,br=1.0,g=0,**kwargs):
"""
"""
def assimilator(stats,twin,xx,yy):
# Unpack
f,h,chrono,X0 = twin.f, twin.h, twin.t, twin.X0
nonlocal Nb, Sb2
stats.aa = zeros(chrono.KObs+1)
stats.bb = zeros(chrono.KObs+1)
stats.Nb = zeros(chrono.KObs+1)
for k,kObs,t,dt in progbar(chrono.forecast_range):
E = f(E,t-dt,dt)
E = add_noise(E, dt, f.noise, kwargs)
Nb = Nb*Fb # NB
Sb2 -= (Sb2-1)*br # NB
if kObs is not None:
stats.assess(k,kObs,'f',E=E)
# Make dual cost function (in terms of lambda^1)
m_Nm = min(N,h.m)
dgn = lambda l: pad0( (l*s)**2, m_Nm ) + (N-1)
J = lambda ab: np.sum(du**2/dgn(ab[0]*ab[1])) \
+ eN/mc/ab[0]**2 \
+ cL *mc*log(ab[0]**2) \
+ Sb2*rb/ab[1]**2 \
+ rb*log(ab[1]**2)
# Find inflation factors
a, b = sp.optimize.fmin_bfgs(J, x0=[1,sqrt(Sb2)], gtol=1e-4, disp=0)
# TODO: Update Nb, Sb2
Sb2 = (Nb*Sb2 + b**2)/(Nb + 1)
Nb += 1
# Aggregate factor
l1 = a*b
# Turns it into ETKF:
#l1 = 1.0
stats.aa[kObs] = a
stats.bb[kObs] = b
stats.Nb[kObs] = Nb
@DA_Config
def BnKF(N,infl=1.0,rot=False,**kwargs):
import scipy.optimize as opt
def assimilator(stats,twin,xx,yy):
# Test settings:
#from mods.Lorenz95.sak08 import setup
#cfgs += EnKF_N(N=28)
#cfgs += EnKF('PertObs',N=39,infl=1.06)
#cfgs += BnKF(N=39,infl=1.03)
# Unpack
f,h,chrono,X0 = twin.f, twin.h, twin.t, twin.X0
Rm12 = h.noise.C.sym_sqrt_inv
Ri = h.noise.C.inv
# constants
nu = N-1
invm = lambda x: funm_psd(x, np.reciprocal)
IN = eye(N)
Pi1 = np.outer(ones(N),ones(N))/N
PiC = IN - Pi1
# Init
bb = N*ones(N)
E = X0.sample(N)
stats.assess(0,E=E)
for k,kObs,t,dt in progbar(chrono.forecast_range):
E = f(E,t-dt,dt)
E = add_noise(E, dt, f.noise, kwargs)
if kObs is not None:
stats.assess(k,kObs,'f',E=E)
hE = h(E,t)
y = yy[kObs]
mu = mean(E,0)
A = E - mu
hx = mean(hE,0)
Y = hE-hx
dy = y - hx
# V,s,U_T = svd0( Y @ Rm12.T )
# # Compute ETKF (sym sqrt) update
# l1 = 1.0
# dgn = lambda l: pad0( (l*s)**2, N ) + (N-1)
# Pw = (V * dgn(l1)**(-1.0)) @ V.T
# w = dy@Ri@Y.T@Pw
# T = (V * dgn(l1)**(-0.5)) @ V.T * sqrt(N-1)
# E = mu + w@A + T@A
# Prepare
V,s,_ = svd0( Y @ Rm12.T )
target = invm( Y@Ri@Y.T/nu + eye(N) ) # = nu*Pwn
dC = np.zeros((N,N))
def resulting_Pw(rr):
for n in arange(N):
dn = y-hE[n]
an = nu*rr[n]/bb[n]
#xn += A@Y.T @ invm( Y@Y.T + an*R ) @ (y-xn+noise)
#Pwn = invm( Y.T @ Ri @ Y/an + eye(N))/an
dgn = pad0(s**2,N) + an
Pwn = ( V * dgn**(-1.0) ) @ V.T
dC[:,n] = IN[:,n] + Pwn@Y@Ri@dn
Ca = dC @ PiC @ dC.T
return Ca
def inpT(logr):
assert len(logr)==(N-1)