-
Notifications
You must be signed in to change notification settings - Fork 4
/
pyEnsLib.py
2304 lines (2008 loc) · 76.7 KB
/
pyEnsLib.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
#!/usr/bin/env python
import configparser
import fnmatch
import getopt
import glob
import itertools
import json
import os
import random
import re
import sys
import time
from itertools import islice
import netCDF4 as nc
import numpy as np
from scipy import linalg as sla
from EET import exhaustive_test
#
# Parse header file of a netcdf to get the variable 3d/2d/1d list
#
def parse_header_file(filename):
command = 'ncdump -h ' + filename
print(command)
retvalue = os.popen(command).readline()
print(retvalue)
#
# Create RMSZ zscores for ensemble file sets
# o_files are not open
# this is used for POP
def calc_rmsz(o_files, var_name3d, var_name2d, opts_dict):
threshold = 1e-12
popens = opts_dict['popens']
tslice = opts_dict['tslice']
nbin = opts_dict['nbin']
minrange = opts_dict['minrange']
maxrange = opts_dict['maxrange']
if not popens:
print('ERROR: should not be calculating rmsz for CAM => EXITING')
sys.exit(2)
first_file = nc.Dataset(o_files[0], 'r')
input_dims = first_file.dimensions
# Create array variables
nlev = len(input_dims['z_t'])
if 'nlon' in input_dims:
nlon = len(input_dims['nlon'])
nlat = len(input_dims['nlat'])
elif 'lon' in input_dims:
nlon = len(input_dims['lon'])
nlat = len(input_dims['lat'])
output3d = np.zeros((len(o_files), nlev, nlat, nlon), dtype=np.float32)
output2d = np.zeros((len(o_files), nlat, nlon), dtype=np.float32)
ens_avg3d = np.zeros((len(var_name3d), nlev, nlat, nlon), dtype=np.float32)
ens_stddev3d = np.zeros((len(var_name3d), nlev, nlat, nlon), dtype=np.float32)
ens_avg2d = np.zeros((len(var_name2d), nlat, nlon), dtype=np.float32)
ens_stddev2d = np.zeros((len(var_name2d), nlat, nlon), dtype=np.float32)
Zscore3d = np.zeros((len(var_name3d), len(o_files), (nbin)), dtype=np.float32)
Zscore2d = np.zeros((len(var_name2d), len(o_files), (nbin)), dtype=np.float32)
first_file.close()
# open all of the files at once
# (not too many for pop - and no longer doing this for cam)
handle_o_files = []
for fname in o_files:
handle_o_files.append(nc.Dataset(fname, 'r'))
# Now lOOP THROUGH 3D
for vcount, vname in enumerate(var_name3d):
# Read in vname's data from all ens. files
for fcount, this_file in enumerate(handle_o_files):
data = this_file.variables[vname]
output3d[fcount, :, :, :] = data[tslice, :, :, :]
# for this variable, Generate ens_avg and ens_stddev to store in the ensemble summary file
moutput3d = np.ma.masked_values(output3d, data._FillValue)
ens_avg3d[vcount] = np.ma.average(moutput3d, axis=0)
ens_stddev3d[vcount] = np.ma.std(moutput3d, axis=0, dtype=np.float32)
# Generate avg, stddev and zscore for this 3d variable
for fcount, this_file in enumerate(handle_o_files):
data = this_file.variables[vname]
# rmask contains a number for each grid point indicating it's region
rmask = this_file.variables['REGION_MASK']
Zscore = pop_zpdf(
output3d[fcount],
nbin,
(minrange, maxrange),
ens_avg3d[vcount],
ens_stddev3d[vcount],
data._FillValue,
threshold,
rmask,
opts_dict,
)
Zscore3d[vcount, fcount, :] = Zscore[:]
# LOOP THROUGH 2D
for vcount, vname in enumerate(var_name2d):
# Read in vname's data of all files
for fcount, this_file in enumerate(handle_o_files):
data = this_file.variables[vname]
output2d[fcount, :, :] = data[tslice, :, :]
# Generate ens_avg and esn_stddev to store in the ensemble summary file
moutput2d = np.ma.masked_values(output2d, data._FillValue)
ens_avg2d[vcount] = np.ma.average(moutput2d, axis=0)
ens_stddev2d[vcount] = np.ma.std(moutput2d, axis=0, dtype=np.float32)
# Generate avg, stddev and zscore for 3d variable
for fcount, this_file in enumerate(handle_o_files):
data = this_file.variables[vname]
rmask = this_file.variables['REGION_MASK']
Zscore = pop_zpdf(
output2d[fcount],
nbin,
(minrange, maxrange),
ens_avg2d[vcount],
ens_stddev2d[vcount],
data._FillValue,
threshold,
rmask,
opts_dict,
)
Zscore2d[vcount, fcount, :] = Zscore[:]
# close files
for this_file in handle_o_files:
this_file.close()
return Zscore3d, Zscore2d, ens_avg3d, ens_stddev3d, ens_avg2d, ens_stddev2d
#
# Calculate pop zscore pass rate (ZPR) or pop zpdf values
#
def pop_zpdf(
input_array, nbin, zrange, ens_avg, ens_stddev, FillValue, threshold, rmask, opts_dict
):
if 'test_failure' in opts_dict:
test_failure = opts_dict['test_failure']
else:
test_failure = False
# print("input_array.ndim = ", input_array.ndim)
# Masked out the missing values (land)
moutput = np.ma.masked_values(input_array, FillValue)
if input_array.ndim == 3:
rmask3d = np.zeros(input_array.shape, dtype=np.int32)
for i in rmask3d:
i[:, :] = rmask[:, :]
rmask_array = rmask3d
elif input_array.ndim == 2:
rmask_array = np.zeros(input_array.shape, dtype=np.int32)
rmask_array[:, :] = rmask[:, :]
# Now we just want the open oceans (not marginal seas)
# - so for g1xv7, those are 1,2,3,4,6
# in the region mask - so we don't want rmask<1 or rmask>6
moutput2 = np.ma.masked_where((rmask_array < 1) | (rmask_array > 6), moutput)
# Use the masked array moutput2 to calculate Zscore_temp=(data-avg)/stddev
Zscore_temp = np.fabs(
(moutput2.astype(np.float64) - ens_avg)
/ np.where(ens_stddev <= threshold, FillValue, ens_stddev)
)
# To retrieve only the valid entries of Zscore_temp
Zscore_nomask = Zscore_temp[~Zscore_temp.mask]
# If just test failure, calculate ZPR only (DEFAULT - not chnagable via cmd line
if test_failure:
# Zpr=the count of Zscore_nomask is less than pop_tol (3.0)/ the total count of Zscore_nomask
Zpr = np.where(Zscore_nomask <= opts_dict['pop_tol'])[0].size / float(Zscore_temp.count())
return Zpr
# Else calculate zpdf and return as zscore
# Count the unmasked value
count = Zscore_temp.count()
Zscore, bins = np.histogram(Zscore_temp.compressed(), bins=nbin, range=zrange)
# Normalize the number by dividing the count
if count != 0:
Zscore = Zscore.astype(np.float32) / count
else:
print(('count=0,sum=', np.sum(Zscore)))
return Zscore
#
# Calculate rmsz score by compare the run file with the ensemble summary file
#
def calculate_raw_score(
k, v, npts3d, npts2d, ens_avg, ens_stddev, is_SE, opts_dict, FillValue, timeslice, rmask
):
count = 0
Zscore = 0
threshold = 1.0e-12
has_zscore = True
popens = opts_dict['popens']
if popens: # POP
minrange = opts_dict['minrange']
maxrange = opts_dict['maxrange']
Zscore = pop_zpdf(
v,
opts_dict['nbin'],
(minrange, maxrange),
ens_avg,
ens_stddev,
FillValue,
threshold,
rmask,
opts_dict,
)
else: # CAM
if k in ens_avg:
if is_SE:
if ens_avg[k].ndim == 1:
npts = npts2d
else:
npts = npts3d
else:
if ens_avg[k].ndim == 2:
npts = npts2d
else:
npts = npts3d
count, return_val = calc_Z(
v, ens_avg[k].astype(np.float64), ens_stddev[k].astype(np.float64), count, False
)
Zscore = np.sum(np.square(return_val.astype(np.float64)))
if npts == count:
Zscore = 0
else:
Zscore = np.sqrt(Zscore / (npts - count))
else:
has_zscore = False
return Zscore, has_zscore
#
# Find the corresponding ensemble summary file from directory
# /glade/p/cesmdata/cseg/inputdata/validation/ when three
# validation files are input from the web server
#
# ifiles are not open
def search_sumfile(opts_dict, ifiles):
sumfile_dir = opts_dict['sumfile']
first_file = nc.Dataset(ifiles[0], 'r')
machineid = ''
compiler = ''
global_att = first_file.ncattrs()
for attr_name in global_att:
val = getattr(first_file, attr_name)
if attr_name == 'model_version':
if val.find('-') != -1:
model_version = val[0 : val.find('-')]
else:
model_version = val
elif attr_name == 'compset':
compset = val
elif attr_name == 'testtype':
testtype = val
if val == 'UF-ECT':
testtype = 'uf_ensembles'
opts_dict['eet'] = len(ifiles)
elif val == 'ECT':
testtype = 'ensembles'
elif val == 'POP':
testtype = val + '_ensembles'
elif attr_name == 'machineid':
machineid = val
elif attr_name == 'compiler':
compiler = val
elif attr_name == 'grid':
grid = val
if 'testtype' in global_att:
sumfile_dir = sumfile_dir + '/' + testtype + '/'
else:
print('ERROR: No global attribute testtype in your validation file => EXITING....')
sys.exit(2)
if 'model_version' in global_att:
sumfile_dir = sumfile_dir + '/' + model_version + '/'
else:
print('ERROR: No global attribute model_version in your validation file => EXITING....')
sys.exit(2)
first_file.close()
if os.path.exists(sumfile_dir):
thefile_id = 0
for i in os.listdir(sumfile_dir):
if os.path.isfile(sumfile_dir + i):
sumfile_id = nc.Dataset(sumfile_dir + i, 'r')
sumfile_gatt = sumfile_id.ncattrs()
if 'grid' not in sumfile_gatt and 'resolution' not in sumfile_gatt:
print(
'ERROR: No global attribute grid or resolution in the summary file => EXITING....'
)
sys.exit(2)
if 'compset' not in sumfile_gatt:
print('ERROR: No global attribute compset in the summary file')
sys.exit(2)
if (
getattr(sumfile_id, 'resolution') == grid
and getattr(sumfile_id, 'compset') == compset
):
thefile_id = sumfile_id
sumfile_id.close()
if thefile_id == 0:
print(
"ERROR: The verification files don't have a matching ensemble summary file to compare => EXITING...."
)
sys.exit(2)
else:
print(('ERROR: Could not locate directory ' + sumfile_dir + ' => EXITING....'))
sys.exit(2)
return sumfile_dir + i, machineid, compiler
#
# Create some variables and call a function to calculate PCA
# now gm comes in at 64 bits...
# pas in exclude list in case we have to add to id
def pre_PCA(gm_orig, all_var_names, ex_list, me):
# initialize
b_exit = False
gm_len = gm_orig.shape
nvar = gm_len[0]
nfile = gm_len[1]
if gm_orig.dtype == np.float32:
gm = gm_orig.astype(np.float64)
else:
gm = gm_orig[:]
sigma_gm = np.std(gm, axis=1, ddof=1)
# keep track of orig vars in exclude file
new_ex_list = ex_list.copy()
orig_len = len(ex_list)
##### check for constants across ensemble
print('STATUS: checking for constant values across ensemble')
for var in range(nvar):
for file in range(nfile):
if np.any(sigma_gm[var] == 0.0) and all_var_names[var] not in set(new_ex_list):
# keep track of zeros standard deviations and append
new_ex_list.append(all_var_names[var])
# did we add vars to exclude?
new_len = len(new_ex_list)
if new_len > orig_len:
sub_list = new_ex_list[orig_len:]
if me.get_rank() == 0:
print('\n')
print(
'*************************************************************************************'
)
print(
'Warning: these ',
new_len - orig_len,
' variables are constant across ensemble members, and will be excluded and added to a copy of the json file (--jsonfile): ',
)
print('\n')
print((','.join(['"{0}"'.format(item) for item in sub_list])))
print(
'*************************************************************************************'
)
print('\n')
#### now check for any variables that have less than 3% (of the ensemble size) unique values
print('STATUS: checking for unique values across ensemble')
cts = np.count_nonzero(np.diff(np.sort(gm)), axis=1) + 1
thresh = 0.03 * gm.shape[1]
result = np.where(cts < thresh)
indices = result[0]
if len(indices) > 0:
nu_list = []
for i in indices:
# only add if not in ex_list already
if all_var_names[i] not in set(new_ex_list):
nu_list.append(all_var_names[i])
if len(nu_list) > 0:
print('\n')
print(
'********************************************************************************************'
)
print(
'Warning: these ',
len(nu_list),
' variables contain fewer than 3% unique values across the ensemble, and will be excluded and added to a copy of the json file (--jsonfile): ',
)
print('\n')
print((','.join(['"{0}"'.format(item) for item in nu_list])))
print(
'********************************************************************************************'
)
print('\n')
new_ex_list.extend(nu_list)
### REMOVE newly excluded stuff before the check for linear dependence
# remove var from nvar, all_var_names, gm, and recalculate: mu_gm, sigma_gm
new_len = len(new_ex_list)
indx = []
if new_len > orig_len:
print('Updating ...')
sub_list = new_ex_list[orig_len:]
for i in sub_list:
indx.append(all_var_names.index(i))
# now delete the rows from gm and names from list
gm_del = np.delete(gm, indx, axis=0)
all_var_names_del = np.delete(all_var_names, indx).tolist()
gm = gm_del
all_var_names = all_var_names_del
nvar = gm.shape[0]
mu_gm = np.average(gm, axis=1)
sigma_gm = np.std(gm, axis=1, ddof=1)
standardized_global_mean = np.zeros(gm.shape, dtype=np.float64)
####### check for linear dependent vars
print('STATUS: checking for linear dependence across ensemble')
for var in range(nvar):
for file in range(nfile):
standardized_global_mean[var, file] = (gm[var, file] - mu_gm[var]) / sigma_gm[var]
eps = np.finfo(np.float32).eps
norm = np.linalg.norm(standardized_global_mean, ord=2)
sh = max(standardized_global_mean.shape)
mytol = sh * norm * eps
# standardized_rank = np.linalg.matrix_rank(standardized_global_mean, mytol)
print('STATUS: using QR...')
# print('sh, norm, eps ', sh, norm, eps)
dep_var_list = get_dependent_vars_index(standardized_global_mean, mytol)
num_dep = len(dep_var_list)
new_len = len(new_ex_list)
for i in dep_var_list:
new_ex_list.append(all_var_names[i])
if num_dep > 0:
sub_list = new_ex_list[new_len:]
print('\n')
print(
'********************************************************************************************'
)
print(
'Warning: these ',
num_dep,
' variables are linearly dependent, and will be excluded and added to a copy of the json file (--jsonfile): ',
)
print('\n')
print((','.join(['"{0}"'.format(item) for item in sub_list])))
print(
'********************************************************************************************'
)
print('\n')
# REMOVE FROM gm, standardized gm and names
indx = []
for i in sub_list:
indx.append(all_var_names.index(i))
# now delete the rows in index from gm, std gm, and names from list
gm_del = np.delete(gm, indx, axis=0)
sgm_del = np.delete(standardized_global_mean, indx, axis=0)
all_var_names_del = np.delete(all_var_names, indx).tolist()
gm = gm_del
standardized_global_mean = sgm_del
all_var_names = all_var_names_del
nvar = gm.shape[0]
mu_gm = np.average(gm, axis=1)
sigma_gm = np.std(gm, axis=1, ddof=1)
# COMPUTE PCA
scores_gm = np.zeros(gm.shape, dtype=np.float64)
# find principal components
loadings_gm = princomp(standardized_global_mean)
# now do coord transformation on the standardized means to get the scores
scores_gm = np.dot(loadings_gm.T, standardized_global_mean)
sigma_scores_gm = np.std(scores_gm, axis=1, ddof=1)
return (
mu_gm,
sigma_gm,
standardized_global_mean,
loadings_gm,
sigma_scores_gm,
new_ex_list,
gm,
b_exit,
)
#
# Performs principal components analysis (PCA) on the p-by-n data matrix A
# rows of A correspond to (p) variables AND cols of A correspond to the (n) tests
# assume already standardized
#
# Returns the loadings: p-by-p matrix, each column containing coefficients
# for one principal component.
#
def princomp(standardized_global_mean):
# find covariance matrix (will be pxp)
co_mat = np.cov(standardized_global_mean)
# Calculate evals and evecs of covariance matrix (evecs are also pxp)
[evals, evecs] = np.linalg.eig(co_mat)
# Above may not be sorted - sort largest first
new_index = np.argsort(evals)[::-1]
evecs = evecs[:, new_index]
evals = evals[new_index]
return evecs
#
# Calculate (val-avg)/stddev and exclude zero value
#
def calc_Z(val, avg, stddev, count, flag):
return_val = np.empty(val.shape, dtype=np.float32, order='C')
tol = 1e-12
if stddev[(stddev > tol)].size == 0:
if flag:
print('WARNING: ALL standard dev are < 1e-12')
flag = False
count = count + stddev[(stddev <= tol)].size
return_val = np.zeros(val.shape, dtype=np.float32, order='C')
else:
if stddev[(stddev <= tol)].size > 0:
if flag:
print('WARNING: some standard dev are < 1e-12')
flag = False
count = count + stddev[(stddev <= tol)].size
return_val[np.where(stddev <= tol)] = 0.0
return_val[np.where(stddev > tol)] = (
val[np.where(stddev > tol)] - avg[np.where(stddev > tol)]
) / stddev[np.where(stddev > tol)]
else:
return_val = (val - avg) / stddev
return count, return_val
#
# Read a json file for the excluded list of variables
# (no longer allowing include files)
def read_jsonlist(metajson, method_name):
# method_name = ES for ensemble summary (CAM, MPAS)
# = ESP for POP ensemble summary
exclude = True
if not os.path.exists(metajson):
print('\n')
print(
'*************************************************************************************'
)
print('Warning: Specified json file does not exist: ', metajson)
print(
'*************************************************************************************'
)
print('\n')
varList = []
return varList, exclude
else:
fd = open(metajson)
try:
metainfo = json.load(fd)
except json.JSONDecodeError:
print(f'ERROR: JSONDecode Error in file{metajson}')
varList = ['JSONERROR']
exclude = []
return varList, exclude
if method_name == 'ES': # CAM or MPAS
exclude = True
if 'ExcludedVar' in metainfo:
varList = metainfo['ExcludedVar']
return varList, exclude
elif method_name == 'ESP': # POP
var2d = metainfo['Var2d']
var3d = metainfo['Var3d']
return var2d, var3d
#
# Calculate Normalized RMSE metric
#
def calc_nrmse(orig_array, comp_array):
orig_size = orig_array.size
sumsqr = np.sum(np.square(orig_array.astype(np.float64) - comp_array.astype(np.float64)))
rng = np.max(orig_array) - np.min(orig_array)
if abs(rng) < 1e-18:
rmse = 0.0
else:
rmse = np.sqrt(sumsqr / orig_size) / rng
return rmse
#
# Calculate weighted global mean for one level of CAM output
# works in dp
def area_avg(data_orig, weight, is_SE):
# TO DO: take into account missing values
if data_orig.dtype == np.float32:
data = data_orig.astype(np.float64)
else:
data = data_orig[:]
if is_SE:
a = np.average(data, weights=weight)
else: # FV
# weights are for lat
a_lat = np.average(data, axis=0, weights=weight)
a = np.average(a_lat)
return a
#
# Calculate weighted global mean for one level of OCN output
#
def pop_area_avg(data_orig, weight):
# Take into account missing values
# weights are for lat
if data_orig.dtype == np.float32:
data = data_orig.astype(np.float64)
else:
data = data_orig[:]
a = np.ma.average(data, weights=weight)
return a
#
def get_nlev(o_files, popens):
first_file = nc.Dataset(o_files[0], 'r')
input_dims = first_file.dimensions
if not popens:
nlev = len(input_dims['lev'])
else:
nlev = len(input_dims['z_t'])
first_file.close()
return nlev
#
# Calculate area_wgt when processes cam se/cam fv/pop files
#
def get_area_wgt(o_files, is_SE, nlev, popens):
z_wgt = {}
first_file = nc.Dataset(o_files[0], 'r')
input_dims = first_file.dimensions
if is_SE:
ncol = len(input_dims['ncol'])
output3d = np.zeros((nlev, ncol), dtype=np.float64)
output2d = np.zeros(ncol, dtype=np.float64)
area_wgt = np.zeros(ncol, dtype=np.float64)
area = first_file.variables['area']
area_wgt[:] = area[:]
total = np.sum(area_wgt)
area_wgt[:] /= total
else:
if not popens:
nlon = len(input_dims['lon'])
nlat = len(input_dims['lat'])
gw = first_file.variables['gw']
else:
if 'nlon' in input_dims:
nlon = len(input_dims['nlon'])
nlat = len(input_dims['nlat'])
elif 'lon' in input_dims:
nlon = len(input_dims['lon'])
nlat = len(input_dims['lat'])
gw = first_file.variables['TAREA']
z_wgt = first_file.variables['dz']
output3d = np.zeros((nlev, nlat, nlon), dtype=np.float64)
output2d = np.zeros((nlat, nlon), dtype=np.float64)
area_wgt = np.zeros(nlat, dtype=np.float64) # note gauss weights are length nlat
area_wgt[:] = gw[:]
first_file.close()
return output3d, output2d, area_wgt, z_wgt
# ofiles are not open
def generate_global_mean_for_summary_MPAS(o_files, var_cell, var_edge, var_vertex, opts_dict):
tslice = opts_dict['tslice']
nCell = len(var_cell)
nEdge = len(var_edge)
nVertex = len(var_vertex)
gmCell = np.zeros((nCell, len(o_files)), dtype=np.float64)
gmEdge = np.zeros((nEdge, len(o_files)), dtype=np.float64)
gmVertex = np.zeros((nVertex, len(o_files)), dtype=np.float64)
# get weights for area
first_file = nc.Dataset(o_files[0], 'r')
input_dims = first_file.dimensions
# cells weighted by areaCell
nCellD = len(input_dims['nCells'])
cell_wgt = np.zeros(nCellD, dtype=np.float64)
cell_area = first_file.variables['areaCell']
cell_wgt[:] = cell_area[:]
# edges weighted by dvEdge
nEdgeD = len(input_dims['nEdges'])
edge_wgt = np.zeros(nEdgeD, dtype=np.float64)
edge_area = first_file.variables['dvEdge']
edge_wgt[:] = edge_area[:]
# vertices weighted by areaTriangle
nVertexD = len(input_dims['nVertices'])
vertex_wgt = np.zeros(nVertexD, dtype=np.float64)
vertex_area = first_file.variables['areaTriangle']
vertex_wgt[:] = vertex_area[:]
weights = {}
weights['cell'] = cell_wgt
weights['edge'] = edge_wgt
weights['vertex'] = vertex_wgt
# loop through the input file list to calculate global means
# print('Examining data from files ...')
for fcount, in_file in enumerate(o_files):
fname = nc.Dataset(in_file, 'r')
(
gmCell[:, fcount],
gmEdge[:, fcount],
gmVertex[:, fcount],
) = calc_global_mean_for_onefile_MPAS(
fname,
weights,
var_cell,
var_edge,
var_vertex,
tslice,
)
fname.close()
return gmCell, gmEdge, gmVertex
# fname is open
def calc_global_mean_for_onefile_MPAS(fname, weight_dict, var_cell, var_edge, var_vertex, tslice):
nan_flag = False
# how many of each variable to work on
nCellVars = len(var_cell)
nEdgeVars = len(var_edge)
nVertexVars = len(var_vertex)
gmCell = np.zeros((nCellVars), dtype=np.float64)
gmEdge = np.zeros((nEdgeVars), dtype=np.float64)
gmVertex = np.zeros((nVertexVars), dtype=np.float64)
cell_wgt = weight_dict['cell']
edge_wgt = weight_dict['edge']
vertex_wgt = weight_dict['vertex']
# calculate global mean for each Cell var
# note: some vars are 2d and some 3d
for count, vname in enumerate(var_cell):
if isinstance(vname, str):
vname_d = vname
else:
vname_d = vname.decode('utf-8')
if vname_d not in fname.variables:
print(
'WARNING 1: the test file does not have the variable ',
vname_d,
' that is in the ensemble summary file ...',
)
continue
data = fname.variables[vname_d]
if not data[tslice].size:
print('ERROR: ', vname_d, ' data is empty => EXITING....')
sys.exit(2)
if np.any(np.isnan(data)):
print('ERROR: ', vname_d, ' data contains NaNs - please check input => EXITING')
nan_flag = True
continue
data_slice = data[tslice]
a = np.average(data_slice, axis=0, weights=cell_wgt)
# print("weightd = ", cell_wgt)
# if 3d, have to average over levels (unweighted)
if len(a.shape) > 0:
a = np.average(a)
gmCell[count] = a
# print("a = ", a)
# calculate global mean for each Edge var
for count, vname in enumerate(var_edge):
if isinstance(vname, str):
vname_d = vname
else:
vname_d = vname.decode('utf-8')
if vname_d not in fname.variables:
print(
'WARNING 1: the test file does not have the variable ',
vname_d,
' that is in the ensemble summary file ...',
)
continue
data = fname.variables[vname_d]
if not data[tslice].size:
print('ERROR: ', vname_d, ' data is empty => EXITING....')
sys.exit(2)
if np.any(np.isnan(data)):
print('ERROR: ', vname_d, ' data contains NaNs - please check input => EXITING')
nan_flag = True
continue
data_slice = data[tslice]
a = np.average(data_slice, axis=0, weights=edge_wgt)
# if 3d, have to average over levels (unweighted)
if len(a.shape) > 0:
a = np.average(a)
gmEdge[count] = a
# calculate global mean for each Vertex var
for count, vname in enumerate(var_vertex):
if isinstance(vname, str):
vname_d = vname
else:
vname_d = vname.decode('utf-8')
if vname_d not in fname.variables:
print(
'WARNING 1: the test file does not have the variable ',
vname_d,
' that is in the ensemble summary file ...',
)
continue
data = fname.variables[vname_d]
if not data[tslice].size:
print('ERROR: ', vname_d, ' data is empty => EXITING....')
sys.exit(2)
if np.any(np.isnan(data)):
print('ERROR: ', vname_d, ' data contains NaNs - please check input => EXITING')
nan_flag = True
continue
data_slice = data[tslice]
a = np.average(data_slice, axis=0, weights=vertex_wgt)
# if 3d, have to average over levels (unweighted)
if len(a.shape) > 0:
a = np.average(a)
gmVertex[count] = a
if nan_flag:
print('ERROR: Nans in input data => EXITING....')
sys.exit()
return gmCell, gmEdge, gmVertex
#
# compute area_wgts, and then loop through all files to call calc_global_means_for_onefile
# o_files are not open for CAM
# 12/19 - summary file will now be double precision
def generate_global_mean_for_summary(o_files, var_name3d, var_name2d, is_SE, opts_dict):
tslice = opts_dict['tslice']
popens = opts_dict['popens']
n3d = len(var_name3d)
n2d = len(var_name2d)
gm3d = np.zeros((n3d, len(o_files)), dtype=np.float64)
gm2d = np.zeros((n2d, len(o_files)), dtype=np.float64)
nlev = get_nlev(o_files, popens)
output3d, output2d, area_wgt, z_wgt = get_area_wgt(o_files, is_SE, nlev, popens)
# loop through the input file list to calculate global means
for fcount, in_file in enumerate(o_files):
fname = nc.Dataset(in_file, 'r')
if popens:
gm3d[:, fcount], gm2d[:, fcount] = calc_global_mean_for_onefile_pop(
fname,
area_wgt,
z_wgt,
var_name3d,
var_name2d,
output3d,
output2d,
tslice,
is_SE,
nlev,
opts_dict,
)
else: # CAM
gm3d[:, fcount], gm2d[:, fcount] = calc_global_mean_for_onefile(
fname,
area_wgt,
var_name3d,
var_name2d,
output3d,
output2d,
tslice,
is_SE,
nlev,
opts_dict,
)
fname.close()
return gm3d, gm2d
# Calculate global means for one OCN input file
# (fname is open) NO LONGER USING GLOBAL MEANS for POP
def calc_global_mean_for_onefile_pop(
fname,
area_wgt,
z_wgt,
var_name3d,
var_name2d,
output3d,
output2d,
tslice,
is_SE,
nlev,
opts_dict,
):
nan_flag = False
n3d = len(var_name3d)
n2d = len(var_name2d)
gm3d = np.zeros((n3d), dtype=np.float64)
gm2d = np.zeros((n2d), dtype=np.float64)
# calculate global mean for each 3D variable
for count, vname in enumerate(var_name3d):
gm_lev = np.zeros(nlev, dtype=np.float64)
data = fname.variables[vname]
if np.any(np.isnan(data)):
print('ERROR: ', vname, ' data contains NaNs - please check input.')
nan_flag = True
output3d[:, :, :] = data[tslice, :, :, :]
dbl_output3d = output3d.astype(dtype=np.float64)
for k in range(nlev):
moutput3d = np.ma.masked_values(dbl_output3d[k, :, :], data._FillValue)
gm_lev[k] = pop_area_avg(moutput3d, area_wgt)
# note: averaging over levels - in future, consider pressure-weighted (?)
gm3d[count] = np.average(gm_lev, weights=z_wgt)
# calculate global mean for each 2D variable
for count, vname in enumerate(var_name2d):
data = fname.variables[vname]
if np.any(np.isnan(data)):
print('ERROR: ', vname, ' data contains NaNs - please check input.')
nan_flag = True
output2d[:, :] = data[tslice, :, :]
dbl_output2d = output2d.astype(dtype=np.float64)
moutput2d = np.ma.masked_values(dbl_output2d[:, :], data._FillValue)
gm2d_mean = pop_area_avg(moutput2d, area_wgt)
gm2d[count] = gm2d_mean