-
Notifications
You must be signed in to change notification settings - Fork 13
/
LMR_utils.py
2457 lines (1982 loc) · 91.7 KB
/
LMR_utils.py
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
"""
Module: LMR_utils.py
Purpose: Contains miscellaneous "utility" functions used throughout the LMR code,
including verification modules.
Originators: Greg Hakim & Robert Tardif | U. of Washington
| March 2015
Revisions:
- Added the get_distance function for more efficient calculation of distances
between lat/lon points on the globe. [R. Tardif, U. of Washington, January 2016]
- Added fexibility in handling missing data in the global_hemispheric_means function.
[R. Tardif, U. of Washington, Aug. 2017]
- Added the option to save full fields of variables. [M. Erb, U. Southern California,
June 2017]
- Renamed the proxy databases to less-confusing convention.
'pages' renamed as 'PAGES2kv1' and 'NCDC' renamed as 'LMRdb'
[R. Tardif, U. of Washington, Sept 2017]
"""
import glob
import os
import numpy as np
import re
import pickle
import collections
import copy
import ESMF
from time import time
from os.path import join
from math import radians, cos, sin, asin, sqrt
from scipy import signal, special
from scipy.spatial import cKDTree
from spharm import Spharmt, getspecindx, regrid
def atoi(text):
try:
return int(text)
except ValueError:
return text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
'''
return [ atoi(c) for c in re.split('([-]?\d+)', text) ]
def natural_sort(input):
return sorted(input, key=natural_keys)
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = list(map(np.radians, [lon1, lat1, lon2, lat2]))
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat/2.)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.)**2
c = 2 * np.arcsin(np.sqrt(a))
km = 6367.0 * c
return km
def get_distance(lon_pt, lat_pt, lon_ref, lat_ref):
"""
Vectorized calculation the great circle distances between lat-lon points
on the Earth (lat/lon are specified in decimal degrees)
Input:
lon_pt , lat_pt : longitude, latitude of site w.r.t. which distances
are to be calculated. Both should be scalars.
lon_ref, lat_ref : longitudes, latitudes of reference field
(e.g. calibration dataset, reconstruction grid)
May be scalar, 1D arrays, or 2D arrays.
Output: Returns array containing distances between (lon_pt, lat_pt) and all other points
in (lon_ref,lat_ref). Array has dimensions [dim(lon_ref),dim(lat_ref)].
Originator: R. Tardif, Atmospheric sciences, U. of Washington, January 2016
"""
# Convert decimal degrees to radians
lon_pt, lat_pt, lon_ref, lat_ref = list(map(np.radians, [lon_pt, lat_pt, lon_ref, lat_ref]))
# check dimension of lon_ref and lat_ref
dims_ref = len(lon_ref.shape)
if dims_ref == 0:
lats = lat_ref
lons = lon_ref
elif dims_ref == 1:
lon_dim = len(lon_ref)
lat_dim = len(lat_ref)
nbpts = lon_dim*lat_dim
lats = np.array([lat_ref,]*lon_dim).transpose()
lons = np.array([lon_ref,]*lat_dim)
elif dims_ref == 2:
lats = lat_ref
lons = lon_ref
else:
print('ERROR in get_distance!')
raise SystemExit()
# Haversine formula using arrays as input
dlon = lons - lon_pt
dlat = lats - lat_pt
a = np.sin(dlat/2.)**2 + np.cos(lat_pt) * np.cos(lats) * np.sin(dlon/2.)**2
c = 2. * np.arcsin(np.sqrt(a))
km = 6367.0 * c
return km
def get_data_closest_gridpt(data,lon_data,lat_data,lon_pt,lat_pt,getvalid=None):
"""
Extracts data from a gridded field (data) at the gridpt closest to the
reference location (lat_pt, lon_pt) which has valid (i.e. non-NaN) values.
Parameters
----------
data: ndarray
Gridded data matching dimensions of (sample, lat, lon) -> gridded form
or (lat*lon, sample) -> state vector form.
lon_data: ndarray
Longitudes pertaining to the input data. Can have shape as a single
vector (lat), a grid (lat, lon), or a flattened grid (lat*lon).
lat_data: ndarray
Latitudes pertaining to the input data. Can have shape as a single
vector (lon), a grid (lat, lon), or a flattened grid (lat*lon).
lon_pt: float
Longitude of the reference point (proxy site or other).
lat_pt: float
Latitude of the reference point (proxy site or other).
getvalid: bool
...
Returns
-------
pt_data: ndarray
Grid point data closest to the lat/lon of the reference location.
Dimension of returned array is 1D along sample axis).
Originator: R. Tardif, Atmospheric sciences, U. of Washington, December 2016
"""
# Initialize returned array to missing (nan)
# sample axis is assumed to be axis=0
pt_data = np.zeros(shape=data.shape[0])
pt_data[:] = np.nan
# Representative distance between grid pts.
dist = haversine(np.roll(lon_data,1), np.roll(lat_data,1), lon_data, lat_data)
meandist = np.mean(dist)
# Calculate distances
dist = haversine(lon_pt, lat_pt, lon_data, lat_data)
workdist = np.ravel(dist)
sorteddist = np.sort(workdist)
# Find closest grid point with *valid* data.
# Impose max of search distance equal to twice the representative distance
# Start with min dist.
distptmin = sorteddist[0]
i = 0
distpt = distptmin
inds2 = np.where(workdist == distpt)[0][0]
inds = np.unravel_index(inds2, dist.shape)
if getvalid:
valid = False
while not valid and distpt < meandist*2.:
inds2 = np.where(workdist == distpt)[0][0]
inds = np.unravel_index(inds2, dist.shape)
if len(inds) == 2:
test_valid = np.isfinite(data[:,inds[0],inds[1]])
elif len(inds) == 1:
#test_valid = np.isfinite(data[:,inds])
test_valid = np.isfinite(data[inds,:])
else:
print('ERROR in distance calc in get_data_closest_gridpt!')
raise SystemExit(1)
if np.all(test_valid): valid = True
i +=1
distpt = sorteddist[i]
else:
pass
# Extract the data at the identified grid pt.
if len(inds) == 2:
pt_data = data[:,inds[0],inds[1]]
elif len(inds) == 1:
#pt_data = data[:,inds[0]]
pt_data = data[inds[0],:]
else:
pass
return pt_data
def year_fix(t):
"""
pad the year with leading zeros for file I/O
"""
# Originator: Greg Hakim
# University of Washington
# March 2015
#
# revised 16 June 2015 (GJH)
# make sure t is an integer
t = int(t)
if t < 10:
ypad = '000'+str(t)
elif t >= 10 and t < 100:
ypad = '00'+str(t)
elif t >= 100 and t < 1000:
ypad = '0'+str(t)
else:
ypad = str(t)
return ypad
def smooth2D(im, n=15):
"""
Smooth a 2D array im by convolving with a Gaussian kernel of size n
Input:
im (2D array): Array of values to be smoothed
n (int) : number of points to include in the smoothing
Output:
improc(2D array): smoothed array (same dimensions as the input array)
"""
# Originator: Greg Hakim
# University of Washington
# May 2015
# Calculate a normalised Gaussian kernel to apply as the smoothing function.
size = int(n)
x,y = np.mgrid[-n:n+1,-n:n+1]
gk = np.exp(-(x**2/float(n)+y**2/float(n)))
g = gk / gk.sum()
#bndy = 'symm'
bndy = 'wrap'
improc = signal.convolve2d(im, g, mode='same', boundary=bndy)
return(improc)
def ensemble_stats(cfg_core, y_assim, y_eval=None):
"""
Compute the ensemble mean and variance for files in the input directory
Originator: Greg Hakim
University of Washington
May 2015
Revised 16 June 2015 (GJH)
Revised 24 June 2015 (R Tardif, UW)
: func. renamed from ensemble_mean to ensemble_stats
: computes and output the ensemble variance as well
: now handles state vector possibly containing multiple variables
Revised 15 July 2015 (R Tardif, UW)
: extracts Ye's from augmented state vector (Ye=HXa), match with corresponding
proxy sites from master list of proxies and output to analysis_Ye.pckl file
Rrevised June 2016 (Michael Erb, USC)
: Fixed a bug where the analysis Ye values were not being
indexed by year properly in forming analysis_Ye.pckl
Revised February 2017 (R Tardif, UW)
: Added flexibility by getting rid of originally hard-coded features.
: Added use of new "natural_sort" function to sort filenames composed with negative years.
Revised August 2017 (G. Hakim, UW)
: Added boolean flag to control the generation of analysis_Ye.pckl file.
Revised August 2017 (M. Erb; G. Hakim git port)
: added full-ensemble saving facility
Revised August 2017 (R. Tardif, UW)
: Modified load_precalculated_ye_vals_psm_per_proxy function to upload Ye values
either from assimilated or withheld proxy sets
Revised February 2018 (R. Tardif, UW)
: More streamlined handling of full-ensemble saving facility
as attempt to prevent occurrences of MemoryError even though full-ensemble
save was not activated
Revised April 2018 (R. Tardif, UW)
: Enabled option for possible regridding of 2D reanalysis fields at the archiving stage.
Revised April 2018 (R. Tardif, UW)
: Added options for archiving information on the reanalysis ensemble other than
the mean (i.e. full ensemble, ensemble variance, percentiles or subset of members)
TODO: Look into how to prevent occurences of MemoryError when
full-ensemble saving is activated.
"""
workdir = cfg_core.datadir_output
write_posterior_Ye = cfg_core.write_posterior_Ye
# ---
prior_filn = workdir + '/Xb_one.npz'
# get the prior and basic info
npzfile = np.load(prior_filn)
npzfile.files
Xbtmp = npzfile['Xb_one']
Xb_coords = npzfile['Xb_one_coords']
# get state vector content info (state variables and their position in vector)
# note: the .item() is necessary to access a dict stored in a npz file
state_info = npzfile['state_info'].item()
nens = np.size(Xbtmp,1)
# get a listing of the analysis files
files = glob.glob(workdir+"/year*")
# sorted
sfiles = natural_sort(files)
nyears = len(sfiles)
# loop on state variables
for var in state_info.keys():
print('State variable:', var)
ibeg = state_info[var]['pos'][0]
iend = state_info[var]['pos'][1]
# Determine variable type (2D lat/lon, 2D lat/depth, time series etc.)
# Look for the 'vartype' entry in the state vector dict.
# Possibilities are: '2D:horizontal', '2D:meridional_vertical',
# '1D:meridional', '0D:time series'
if state_info[var]['vartype'] == '2D:horizontal':
# 2D:horizontal variable
# ----------------------
# Extracting info on reanalysis grid
ndim1 = state_info[var]['spacedims'][0]
ndim2 = state_info[var]['spacedims'][1]
nlat = state_info[var]['spacedims'][state_info[var]['spacecoords'].index('lat')]
nlon = state_info[var]['spacedims'][state_info[var]['spacecoords'].index('lon')]
lats = Xb_coords[ibeg:iend+1,state_info[var]['spacecoords'].index('lat')]
lons = Xb_coords[ibeg:iend+1,state_info[var]['spacecoords'].index('lon')]
# -- Prior --
if cfg_core.archive_regrid_method is not None:
# option to regrid the reanalysis is activated
target_grid = cfg_core.archive_esmpy_grid_def
lat_2d = lats.reshape(nlat, nlon)
lon_2d = lons.reshape(nlat, nlon)
[priorVariabletoArchive,
lat_new,
lon_new] = regrid_esmpy(target_grid['nlat'],
target_grid['nlon'],
nens,
Xbtmp[ibeg:iend+1,:],
lat_2d,
lon_2d,
nlat,
nlon,
include_poles=target_grid['include_poles'],
method=cfg_core.archive_esmpy_interp_method)
ndim1_archive = lat_new.shape[0]
ndim2_archive = lon_new.shape[1]
lats_archive = lat_new.flatten()
lons_archive = lon_new.flatten()
else:
# no regridding
ndim1_archive = ndim1
ndim2_archive = ndim2
lats_archive = lats
lons_archive = lons
priorVariabletoArchive = Xbtmp[ibeg:iend+1,:]
Xb = np.reshape(priorVariabletoArchive,(ndim1_archive,ndim2_archive,nens))
xbm = np.mean(Xb,axis=2) # ensemble mean
if cfg_core.save_archive == 'ens_variance':
xbv = np.var(Xb,axis=2,ddof=1) # ensemble variance
elif cfg_core.save_archive == 'ens_percentiles':
xb_pctl = np.zeros([ndim1_archive,ndim2_archive,2])
xb_pctl[:,:,0] = np.percentile(Xb,cfg_core.save_archive_percentiles[0],axis=2)
xb_pctl[:,:,1] = np.percentile(Xb,cfg_core.save_archive_percentiles[1],axis=2)
elif cfg_core.save_archive == 'ens_subsample':
xb_sub = Xb[:,:,0:cfg_core.save_archive_ens_subsample]
# -- Process the **analysis** (i.e. posterior) files --
years = []
if cfg_core.save_archive == 'ens_full':
if 'xa_ens' in dir():
del xa_ens
xa_ens = np.zeros([nyears,ndim1_archive,ndim2_archive,nens])
xam = np.zeros([nyears,ndim1_archive,ndim2_archive])
if cfg_core.save_archive == 'ens_variance':
xav = np.zeros([nyears,ndim1_archive,ndim2_archive],dtype=np.float64)
elif cfg_core.save_archive == 'ens_percentiles':
xa_pctl = np.zeros([nyears,ndim1_archive,ndim2_archive,2])
elif cfg_core.save_archive == 'ens_subsample':
xa_sub = np.zeros([nyears,ndim1_archive,ndim2_archive,cfg_core.save_archive_ens_subsample])
k = -1
for f in sfiles:
k += 1
fname_end = f.split('/')[-1]
year = fname_end.rstrip('.npy').lstrip('year')
years.append(year)
Xatmp = np.load(f)
if cfg_core.archive_regrid_method is not None:
# option to regrid the reanalysis is activated
# nlat, nlon, lat_2d, lon_2d are same as for prior above
[posteriorVariabletoArchive,
lat_new,
lon_new] = regrid_esmpy(target_grid['nlat'],
target_grid['nlon'],
nens,
Xatmp[ibeg:iend+1,:],
lat_2d,
lon_2d,
nlat,
nlon,
include_poles=target_grid['include_poles'],
method=cfg_core.archive_esmpy_interp_method)
else:
posteriorVariabletoArchive = Xatmp[ibeg:iend+1,:]
Xa = np.reshape(posteriorVariabletoArchive,(ndim1_archive,ndim2_archive,nens))
xam[k,:,:] = np.mean(Xa,axis=2) # ensemble mean
if cfg_core.save_archive == 'ens_full':
xa_ens[k,:,:,:] = Xa # total ensemble
elif cfg_core.save_archive == 'ens_variance':
xav[k,:,:] = np.var(Xa,axis=2,ddof=1) # ensemble variance
elif cfg_core.save_archive == 'ens_percentiles':
xa_pctl[k,:,:,0] = np.percentile(Xa,cfg_core.save_archive_percentiles[0],axis=2)
xa_pctl[k,:,:,1] = np.percentile(Xa,cfg_core.save_archive_percentiles[1],axis=2)
elif cfg_core.save_archive == 'ens_subsample':
xa_sub[k,:,:,:] = Xa[:,:,:cfg_core.save_archive_ens_subsample]
# form dictionary containing variables to save, including info on array dimensions
coordname1 = state_info[var]['spacecoords'][0]
coordname2 = state_info[var]['spacecoords'][1]
dimcoord1 = 'n'+coordname1
dimcoord2 = 'n'+coordname2
if coordname1 == 'lat':
coord1 = lats_archive.reshape(ndim1_archive, ndim2_archive)
coord2 = lons_archive.reshape(ndim1_archive, ndim2_archive)
else:
coord1 = lons_archive.reshape(ndim1_archive, ndim2_archive)
coord2 = lats_archive.reshape(ndim1_archive, ndim2_archive)
# ensemble mean
vars_to_save_mean = {'nens':nens, 'years':years, \
dimcoord1:ndim1_archive, dimcoord2:ndim2_archive, \
coordname1:coord1, coordname2:coord2, \
'xbm':xbm, 'xam':xam}
if cfg_core.save_archive == 'ens_full':
vars_to_save_ens = {'nens':nens, 'years':years, \
dimcoord1:ndim1_archive, dimcoord2:ndim2_archive, \
coordname1:coord1, coordname2:coord2, \
'xb_ens':Xb, 'xa_ens':xa_ens}
elif cfg_core.save_archive == 'ens_variance':
vars_to_save_var = {'nens':nens, 'years':years, \
dimcoord1:ndim1_archive, dimcoord2:ndim2_archive, \
coordname1:coord1, coordname2:coord2, \
'xbv':xbv, 'xav':xav}
elif cfg_core.save_archive == 'ens_percentiles':
vars_to_save_var = {'nens':nens, 'years':years, \
dimcoord1:ndim1_archive, dimcoord2:ndim2_archive, \
coordname1:coord1, coordname2:coord2, \
'percentiles': cfg_core.save_archive_percentiles, \
'xb_pctl':xb_pctl, 'xa_pctl':xa_pctl}
elif cfg_core.save_archive == 'ens_subsample':
vars_to_save_var = {'nens':nens, 'nsubsample': cfg_core.save_archive_ens_subsample, \
'years':years, dimcoord1:ndim1_archive, dimcoord2:ndim2_archive, \
coordname1:coord1, coordname2:coord2, \
'xb_subsample':xb_sub, 'xa_subsample':xa_sub}
elif state_info[var]['vartype'] == '2D:meridional_vertical':
ndim1 = state_info[var]['spacedims'][0]
ndim2 = state_info[var]['spacedims'][1]
# Prior
Xb = np.reshape(Xbtmp[ibeg:iend+1,:],(ndim1,ndim2,nens))
xbm = np.mean(Xb,axis=2) # ensemble mean
if cfg_core.save_archive == 'ens_variance':
xbv = np.var(Xb,axis=2,ddof=1) # ensemble variance
elif cfg_core.save_archive == 'ens_percentiles':
xb_pctl = np.zeros([ndim1,ndim2,2])
xb_pctl[:,:,0] = np.percentile(Xb,cfg_core.save_archive_percentiles[0],axis=2)
xb_pctl[:,:,1] = np.percentile(Xb,cfg_core.save_archive_percentiles[1],axis=2)
elif cfg_core.save_archive == 'ens_subsample':
xb_sub = Xb[:,:,0:cfg_core.save_archive_ens_subsample]
# Process the **analysis** (i.e. posterior) files
years = []
# ensemble mean
xam = np.zeros([nyears,ndim1,ndim2])
if cfg_core.save_archive == 'ens_full':
if 'xa_ens' in dir():
del xa_ens
xa_ens = np.zeros([nyears,ndim1,ndim2,nens])
elif cfg_core.save_archive == 'ens_variance':
xav = np.zeros([nyears,ndim1,ndim2],dtype=np.float64)
elif cfg_core.save_archive == 'ens_percentiles':
xa_pctl = np.zeros([nyears,ndim1,ndim2,2])
elif cfg_core.save_archive == 'ens_subsample':
xa_sub = np.zeros([nyears,ndim1,ndim2,cfg_core.save_archive_ens_subsample])
k = -1
for f in sfiles:
k += 1
fname_end = f.split('/')[-1]
year = fname_end.rstrip('.npy').lstrip('year')
years.append(year)
Xatmp = np.load(f)
Xa = np.reshape(Xatmp[ibeg:iend+1,:],(ndim1,ndim2,nens))
xam[k,:,:] = np.mean(Xa,axis=2) # ensemble mean
if cfg_core.save_archive == 'ens_full':
xa_ens[k,:,:,:] = Xa # total ensemble
elif cfg_core.save_archive == 'ens_variance':
xav[k,:,:] = np.var(Xa,axis=2,ddof=1) # ensemble variance
elif cfg_core.save_archive == 'ens_percentiles':
xa_pctl[k,:,:,0] = np.percentile(Xa,cfg_core.save_archive_percentiles[0],axis=2)
xa_pctl[k,:,:,1] = np.percentile(Xa,cfg_core.save_archive_percentiles[1],axis=2)
elif cfg_core.save_archive == 'ens_subsample':
xa_sub[k,:,:,:] = Xa[:,:,:cfg_core.save_archive_ens_subsample]
# form dictionary containing variables to save, including info on array dimensions
coordname1 = state_info[var]['spacecoords'][0]
coordname2 = state_info[var]['spacecoords'][1]
dimcoord1 = 'n'+coordname1
dimcoord2 = 'n'+coordname2
coord1 = np.reshape(Xb_coords[ibeg:iend+1,0],(state_info[var]['spacedims'][0],state_info[var]['spacedims'][1]))
coord2 = np.reshape(Xb_coords[ibeg:iend+1,1],(state_info[var]['spacedims'][0],state_info[var]['spacedims'][1]))
# ensemble mean
vars_to_save_mean = {'nens':nens, 'years':years, \
dimcoord1:state_info[var]['spacedims'][0], \
dimcoord2:state_info[var]['spacedims'][1], \
coordname1:coord1, coordname2:coord2,
'xbm':xbm, 'xam':xam}
if cfg_core.save_archive == 'ens_full':
vars_to_save_ens = {'nens':nens, 'years':years, \
dimcoord1:state_info[var]['spacedims'][0], \
dimcoord2:state_info[var]['spacedims'][1], \
coordname1:coord1, coordname2:coord2, \
'xb_ens':Xb, 'xa_ens':xa_ens}
elif cfg_core.save_archive == 'ens_variance':
vars_to_save_var = {'nens':nens, 'years':years, \
dimcoord1:state_info[var]['spacedims'][0], \
dimcoord2:state_info[var]['spacedims'][1], \
coordname1:coord1, coordname2:coord2, \
'xbv':xbv, 'xav':xav}
elif cfg_core.save_archive == 'ens_percentiles':
vars_to_save_var = {'nens':nens, 'years':years, \
dimcoord1:state_info[var]['spacedims'][0], \
dimcoord2:state_info[var]['spacedims'][1], \
coordname1:coord1, coordname2:coord2, \
'percentiles': cfg_core.save_archive_percentiles, \
'xb_pctl':xb_pctl, 'xa_pctl':xa_pctl}
elif cfg_core.save_archive == 'ens_subsample':
vars_to_save_var = {'nens':nens, 'nsubsample': cfg_core.save_archive_ens_subsample, \
'years':years, dimcoord1:state_info[var]['spacedims'][0], \
dimcoord2:state_info[var]['spacedims'][1], \
coordname1:coord1, coordname2:coord2, \
'xb_subsample':xb_sub, 'xa_subsample':xa_sub}
elif state_info[var]['vartype'] == '1D:meridional':
ndim1 = state_info[var]['spacedims'][0]
# Prior
Xb = np.reshape(Xbtmp[ibeg:iend+1,:],(ndim1,nens))
xbm = np.mean(Xb,axis=1) # ensemble mean
if cfg_core.save_archive == 'ens_variance':
xbv = np.var(Xb,axis=1,ddof=1) # ensemble variance
elif cfg_core.save_archive == 'ens_percentiles':
xb_pctl = np.zeros([ndim1,2])
xb_pctl[:,0] = np.percentile(Xb,cfg_core.save_archive_percentiles[0],axis=1)
xb_pctl[:,1] = np.percentile(Xb,cfg_core.save_archive_percentiles[1],axis=1)
elif cfg_core.save_archive == 'ens_subsample':
xb_sub = Xb[:,0:cfg_core.save_archive_ens_subsample]
# Process the **analysis** (i.e. posterior) files
years = []
# ensemble mean
xam = np.zeros([nyears,ndim1])
if cfg_core.save_archive == 'ens_full':
if 'xa_ens' in dir():
del xa_ens
xa_ens = np.zeros([nyears,ndim1,nens])
elif cfg_core.save_archive == 'ens_variance':
xav = np.zeros([nyears,ndim1],dtype=np.float64)
elif cfg_core.save_archive == 'ens_percentiles':
xa_pctl = np.zeros([nyears,ndim1,2])
elif cfg_core.save_archive == 'ens_subsample':
xa_sub = np.zeros([nyears,ndim1,cfg_core.save_archive_ens_subsample])
k = -1
for f in sfiles:
k += 1
fname_end = f.split('/')[-1]
year = fname_end.rstrip('.npy').lstrip('year')
years.append(year)
Xatmp = np.load(f)
Xa = np.reshape(Xatmp[ibeg:iend+1,:],(ndim1,nens))
xam[k,:] = np.mean(Xa,axis=1) # ensemble mean
if cfg_core.save_archive == 'ens_full':
xa_ens[k,:,:] = Xa # total ensemble
elif cfg_core.save_archive == 'ens_variance':
xav[k,:] = np.var(Xa,axis=1,ddof=1) # ensemble variance
elif cfg_core.save_archive == 'ens_percentiles':
xa_pctl[k,:,0] = np.percentile(Xa,cfg_core.save_archive_percentiles[0],axis=1)
xa_pctl[k,:,1] = np.percentile(Xa,cfg_core.save_archive_percentiles[1],axis=1)
elif cfg_core.save_archive == 'ens_subsample':
xa_sub[k,:,:] = Xa[:,0:cfg_core.save_archive_ens_subsample]
# form dictionary containing variables to save, including info on array dimensions
coordname1 = state_info[var]['spacecoords'][0]
dimcoord1 = 'n'+coordname1
coord1 = np.reshape(Xb_coords[ibeg:iend+1,0],(state_info[var]['spacedims'][0]))
# ensemble mean
vars_to_save_mean = {'nens':nens, 'years':years, \
dimcoord1:state_info[var]['spacedims'][0], \
coordname1:coord1, 'xbm':xbm, 'xam':xam}
if cfg_core.save_archive == 'ens_full':
vars_to_save_ens = {'nens':nens, 'years':years, \
dimcoord1:state_info[var]['spacedims'][0], \
coordname1:coord1, 'xb_ens':Xb, 'xa_ens':xa_ens}
elif cfg_core.save_archive == 'ens_variance':
vars_to_save_var = {'nens':nens, 'years':years, \
dimcoord1:state_info[var]['spacedims'][0], \
coordname1:coord1, 'xbv':xbv, 'xav':xav}
elif cfg_core.save_archive == 'ens_percentiles':
vars_to_save_var = {'nens':nens, 'years':years, \
dimcoord1:state_info[var]['spacedims'][0], \
coordname1:coord1, \
'percentiles': cfg_core.save_archive_percentiles, \
'xb_pctl':xb_pctl, 'xa_pctl':xa_pctl}
elif cfg_core.save_archive == 'ens_subsample':
vars_to_save_var = {'nens':nens, 'nsubsample': cfg_core.save_archive_ens_subsample, \
'years':years, dimcoord1:state_info[var]['spacedims'][0], \
coordname1:coord1, \
'xb_subsample':xb_sub, 'xa_subsample':xa_sub}
elif state_info[var]['vartype'] == '0D:time series':
# 0D:time series variable (no spatial dims)
Xb = Xbtmp[ibeg:iend+1,:] # prior (full) ensemble
xbm = np.mean(Xb,axis=1) # ensemble mean
if cfg_core.save_archive == 'ens_variance':
xbv = np.var(Xb,axis=1,ddof=1) # ensemble variance
elif cfg_core.save_archive == 'ens_percentiles':
xb_pctl = np.zeros([2])
xb_pctl[0] = np.percentile(Xb,cfg_core.save_archive_percentiles[0],axis=1)
xb_pctl[1] = np.percentile(Xb,cfg_core.save_archive_percentiles[1],axis=1)
elif cfg_core.save_archive == 'ens_subsample':
xb_sub = Xb[:,0:cfg_core.save_archive_ens_subsample]
# process the **analysis** files
years = []
xa_ens = np.zeros((nyears, Xb.shape[1]))
xam = np.zeros([nyears])
if cfg_core.save_archive == 'ens_variance':
xav = np.zeros([nyears],dtype=np.float64)
elif cfg_core.save_archive == 'ens_percentiles':
xa_pctl = np.zeros([nyears,2])
elif cfg_core.save_archive == 'ens_subsample':
xa_sub = np.zeros([nyears,cfg_core.save_archive_ens_subsample])
k = -1
for f in sfiles:
k += 1
fname_end = f.split('/')[-1]
year = fname_end.rstrip('.npy').lstrip('year')
years.append(year)
Xatmp = np.load(f)
Xa = Xatmp[ibeg:iend+1,:]
xa_ens[k] = Xa # total ensemble
xam[k] = np.mean(Xa,axis=1) # ensemble mean
if cfg_core.save_archive == 'ens_variance':
xav[k] = np.var(Xa,axis=1,ddof=1) # ensemble variance
elif cfg_core.save_archive == 'ens_percentiles':
xa_pctl = np.zeros([nyears,2])
xa_pctl[k,0] = np.percentile(Xa,cfg_core.save_archive_percentiles[0],axis=1)
xa_pctl[k,1] = np.percentile(Xa,cfg_core.save_archive_percentiles[1],axis=1)
elif cfg_core.save_archive == 'ens_subsample':
xa_sub[k,:] = Xa[:,0:cfg_core.save_archive_ens_subsample]
vars_to_save_ens = {'nens':nens, 'years':years, 'xb_ens':Xb, 'xa_ens':xa_ens}
vars_to_save_mean = {'nens':nens, 'years':years, 'xbm':xbm, 'xam':xam}
if cfg_core.save_archive == 'ens_variance':
vars_to_save_var = {'nens':nens, 'years':years, 'xbv':xbv, 'xav':xav}
elif cfg_core.save_archive == 'ens_percentiles':
vars_to_save_var = {'nens':nens, 'years':years, \
'percentiles': cfg_core.save_archive_percentiles, \
'xb_pctl':xb_pctl, 'xa_pctl':xa_pctl}
elif cfg_core.save_archive == 'ens_subsample':
vars_to_save_var = {'nens':nens, 'nsubsample': cfg_core.save_archive_ens_subsample, \
'years':years, 'xb_subsample':xb_sub, 'xa_subsample':xa_sub}
# (full) ensemble to file for this variable type
filen = workdir + '/ensemble_full_' + var
print('writing the new ensemble file' + filen)
np.savez(filen, **vars_to_save_ens)
else:
print('ERROR in ensemble_stats: Variable of unrecognized (space) dimensions! Skipping variable:', var)
continue
# --- Write data to archive files ---
# ens. mean to file
filen = workdir + '/ensemble_mean_' + var
print('writing the new ensemble mean file...' + filen)
np.savez(filen, **vars_to_save_mean)
if (state_info[var]['vartype'] != '0D:time series') and cfg_core.save_archive == 'ens_full':
filen = workdir + '/ensemble_full_' + var
print('writing the new ensemble file' + filen)
np.savez(filen, **vars_to_save_ens)
elif cfg_core.save_archive == 'ens_variance':
filen = workdir + '/ensemble_variance_' + var
print('writing the new ensemble variance file...' + filen)
np.savez(filen, **vars_to_save_var)
elif cfg_core.save_archive == 'ens_percentiles':
filen = workdir + '/ensemble_percentiles_' + var
print('writing the new ensemble percentiles file...' + filen)
np.savez(filen, **vars_to_save_var)
elif cfg_core.save_archive == 'ens_subsample':
filen = workdir + '/ensemble_subsample_' + var
print('writing the new ensemble members subsample file...' + filen)
np.savez(filen, **vars_to_save_var)
# --------------------------------------------------------
# Extract the analyzed Ye ensemble for diagnostic purposes
# --------------------------------------------------------
if write_posterior_Ye:
if 'xa_ens' in dir():
del xa_ens
# get information on dim of state without the Ye's (before augmentation)
stateDim = npzfile['stateDim']
Xbtmp_aug = npzfile['Xb_one_aug']
# dim of entire state vector (augmented)
totDim = Xbtmp_aug.shape[0]
nbye = (totDim - stateDim)
Ye_s = np.zeros([nbye,nyears,nens])
# Loop over **analysis** files & extract the Ye's
years = []
for k, f in enumerate(sfiles):
i = f.rfind('year')
fname_end = f[i+4:]
ii = fname_end.rfind('.')
year = fname_end[:ii]
years.append(float(year))
Xatmp = np.load(f)
# Extract the Ye's from augmented state (beyond stateDim 'til end of
# state vector).
# RT Aug 2017: These now include Ye's from assimilated AND withheld proxies.
Ye_s[:, k, :] = Xatmp[stateDim:, :]
years = np.array(years)
int_recon = years[1] - years[0]
# Build dictionary
YeDict = {}
# loop over assimilated proxies
nbassim = 0
for i, pobj in enumerate(y_assim):
# build boolean of indices to pull from HXa
if int_recon == 1.:
yr_idxs = np.array([year in pobj.time for year in years],
dtype=np.bool)
else:
yr_idxs = np.zeros([len(years)],dtype=np.bool) # init. w/ all False
for k in range(len(years)):
if [ pyr for pyr in pobj.time if ((pyr > years[k]-int_recon/2.)
and (pyr <= years[k]+int_recon/2.)) ]:
yr_idxs[k] = True
else:
yr_idxs[k] = False
YeDict[(pobj.type, pobj.id)] = {}
YeDict[(pobj.type, pobj.id)]['status'] = 'assimilated'
YeDict[(pobj.type, pobj.id)]['lat'] = pobj.lat
YeDict[(pobj.type, pobj.id)]['lon'] = pobj.lon
YeDict[(pobj.type, pobj.id)]['R'] = pobj.psm_obj.R
#YeDict[(pobj.type, pobj.id)]['years'] = pobj.time
YeDict[(pobj.type, pobj.id)]['years'] = years[yr_idxs]
YeDict[(pobj.type, pobj.id)]['HXa'] = Ye_s[i, yr_idxs, :]
YeDict[(pobj.type, pobj.id)]['augStateIndex'] = i
nbassim +=1
# loop over non-assimilated (withheld) proxies
if y_eval:
for j, pobj in enumerate(y_eval):
# build boolean of indices to pull from HXa
if int_recon == 1.:
yr_idxs = np.array([year in pobj.time for year in years],
dtype=np.bool)
ye_years = pobj.time
else:
yr_idxs = np.zeros([len(years)],dtype=np.bool) # init. w/ all False
for k in range(len(years)):
if [ pyr for pyr in pobj.time if ((pyr > years[k]-int_recon/2.)
and (pyr <= years[k]+int_recon/2.)) ]:
yr_idxs[k] = True
else:
yr_idxs[k] = False
YeDict[(pobj.type, pobj.id)] = {}
YeDict[(pobj.type, pobj.id)]['status'] = 'withheld'
YeDict[(pobj.type, pobj.id)]['lat'] = pobj.lat
YeDict[(pobj.type, pobj.id)]['lon'] = pobj.lon
YeDict[(pobj.type, pobj.id)]['R'] = pobj.psm_obj.R
#YeDict[(pobj.type, pobj.id)]['years'] = pobj.time
YeDict[(pobj.type, pobj.id)]['years'] = years[yr_idxs]
YeDict[(pobj.type, pobj.id)]['HXa'] = Ye_s[nbassim+j, yr_idxs, :]
YeDict[(pobj.type, pobj.id)]['augStateIndex'] = nbassim+j
# Dump dictionary to pickle file
# using protocol 2 for more efficient storing
outfile = open('{}/analysis_Ye.pckl'.format(workdir), 'wb')
pickle.dump(YeDict, outfile, protocol=2)
outfile.close()
return
def lon_lat_to_cartesian(lon, lat, R=6371.):
"""
"""
lon_r = np.radians(lon)
lat_r = np.radians(lat)
x = R * np.cos(lat_r) * np.cos(lon_r)
y = R * np.cos(lat_r) * np.sin(lon_r)
z = R * np.sin(lat_r)
return x, y, z
def regrid_simple(Nens,X,X_coords,ind_lat,ind_lon,ntrunc):
"""
Truncate lat,lon grid to another resolution using local distance-weighted
averages.
Inputs:
Nens : number of ensemble members
X : data array of shape (nlat*nlon,Nens)
X_coords : array of lat-lon coordinates of variable contained in X
w/ shape (nlat*nlon,2)
ind_lat : array index (column) at which X_ccords contains latitudes
ind_lon : array index (column) at which X_ccords contains longitudes
ntrunc : triangular truncation (e.g., use 42 for T42)
Outputs :
lat_new : 2D latitude array on the new grid (nlat_new,nlon_new)
lon_new : 2D longitude array on the new grid (nlat_new,nlon_new)
X_new : truncated data array of shape (nlat_new*nlon_new, Nens)
Originator: Robert Tardif
University of Washington
March 2017
"""
# truncate to a lower resolution grid (triangular truncation)
ifix = np.remainder(ntrunc,2.0).astype(int)
nlat_new = ntrunc + ifix
nlon_new = int(nlat_new*1.5)
# create new lat,lon grid arrays
# Note: AP - According to github.com/jswhit/pyspharm documentation the
# latitudes will not include the equator or poles when nlats is even.
# TODO: Decide whether this should be tied to spherical regridding grids
if nlat_new % 2 == 0:
include_poles = False
else:
include_poles = True
lat_new, lon_new, _, _ = generate_latlon(nlat_new, nlon_new,
include_endpts=include_poles)
# cartesian coords of target grid
xt,yt,zt = lon_lat_to_cartesian(lon_new.flatten(), lat_new.flatten())
# cartesian coords of source grid
lats = X_coords[:, ind_lat]
lons = X_coords[:, ind_lon]
xs,ys,zs = lon_lat_to_cartesian(lons, lats)
# cKDtree object of source grid
tree = cKDTree(list(zip(xs,ys,zs)))
# inverse distance weighting (N pts)
N = 20
fracvalid = 0.7
d, inds = tree.query(list(zip(xt,yt,zt)), k=N)
L = 200.
w = np.exp(-np.square(d)/np.square(L))
# transform each ensemble member, one at a time
X_new = np.zeros([nlat_new*nlon_new,Nens])
X_new[:] = np.nan
for k in range(Nens):
tmp = np.ma.masked_invalid(X[:,k][inds])
mask = tmp.mask
# apply tmp mask to weights array
w = np.ma.masked_where(np.ma.getmask(tmp),w)
# compute weighted-average of surrounding data
datagrid = np.sum(w*tmp, axis=1)/np.sum(w, axis=1)
# keep track of valid data involved in averges
nbvalid = np.sum(~mask,axis=1)
nonvalid = np.where(nbvalid < int(fracvalid*N))[0]
# make sure to mask grid points where too few valid data were used
datagrid[nonvalid] = np.nan
X_new[:,k] = datagrid
# make sure a masked array is returned, if at
# least one invalid data is found
if np.isnan(X_new).any():
X_new = np.ma.masked_invalid(X_new)
return X_new,lat_new,lon_new
def regrid_esmpy(target_nlat, target_nlon, X_nens, X, X_lat2D, X_lon2D,
X_nlat, X_nlon, include_poles=False, method='bilinear'):
"""
Regrid field to target resolution using the ESMF package.
Parameters
----------
target_nlat: int
number of latitude points for destination grid
target_nlon: int
number of longitude points for the destination grid
X_nens: int
number of ensemble members in the data array
X: ndarray
data array to be regridded of shape (nlat*nlon, nens)
X_lat2D: ndarray
2D array of latitudes corresponding to the source field of shape (
nlat, nlon)
X_lon2D: ndarray