-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyEnsLib.py
1326 lines (1194 loc) · 45.8 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 sys, getopt, os
import numpy as np
import Nio
import time
import re
import json
import random
import asaptools.simplecomm as simplecomm
import fnmatch
import glob
#
# Parse header file of a netcdf to get the varaible 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
#
def calc_rmsz(o_files,var_name3d,var_name2d,is_SE,opts_dict):
threshold=1e-12
popens = opts_dict['popens']
tslice = opts_dict['tslice']
if 'cumul' in opts_dict:
cumul=opts_dict['cumul']
else:
cumul=False
input_dims = o_files[0].dimensions
if popens:
nbin = opts_dict['nbin']
minrange = opts_dict['minrange']
maxrange = opts_dict['maxrange']
nlev=input_dims['z_t']
else:
nlev=input_dims["lev"]
# Create array variables based on is_SE
if (is_SE == True):
ncol=input_dims["ncol"]
npts2d=ncol
npts3d=nlev*ncol
output3d = np.zeros((len(o_files),nlev,ncol),dtype=np.float32)
output2d = np.zeros((len(o_files),ncol),dtype=np.float32)
ens_avg3d=np.zeros((len(var_name3d),nlev,ncol),dtype=np.float32)
ens_stddev3d=np.zeros((len(var_name3d),nlev,ncol),dtype=np.float32)
ens_avg2d=np.zeros((len(var_name2d),ncol),dtype=np.float32)
ens_stddev2d=np.zeros((len(var_name2d),ncol),dtype=np.float32)
else:
if 'nlon' in input_dims:
nlon = input_dims["nlon"]
nlat = input_dims["nlat"]
elif 'lon' in input_dims:
nlon = input_dims["lon"]
nlat = input_dims["lat"]
npts2d=nlat*nlon
npts3d=nlev*nlat*nlon
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)
if popens:
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)
else:
Zscore3d = np.zeros((len(var_name3d),len(o_files)),dtype=np.float32)
Zscore2d = np.zeros((len(var_name2d),len(o_files)),dtype=np.float32)
avg3d={}
stddev3d={}
avg2d={}
stddev2d={}
indices = np.arange(0,len(o_files),1)
gm3d=[]
gm2d=[]
if cumul:
temp1,temp2,area_wgt,z_wgt=get_area_wgt(o_files,is_SE,input_dims,nlev,popens)
gm3d = np.zeros((len(var_name3d)),dtype=np.float32)
gm2d = np.zeros((len(var_name2d)),dtype=np.float32)
for vcount,vname in enumerate(var_name3d):
#Read in vname's data of all files
for fcount, this_file in enumerate(o_files):
data=this_file.variables[vname]
if (is_SE == True):
output3d[fcount,:,:]=data[tslice,:,:]
else:
output3d[fcount,:,:,:]=data[tslice,:,:,:]
#Generate ens_avg and ens_stddev to store in the ensemble summary file
if popens:
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)
else:
ens_avg3d[vcount]=np.average(output3d,axis=0).astype(np.float32)
ens_stddev3d[vcount]=np.std(output3d.astype(np.float64),axis=0,dtype=np.float64).astype(np.float32)
if cumul:
gm3d[vcount],temp3=calc_global_mean_for_onefile(this_file,area_wgt,[vname],[],ens_avg3d[vcount],temp2,tslice,is_SE,nlev,opts_dict)
if not cumul:
#Generate avg, stddev and zscore for 3d variable
for fcount,this_file in enumerate(o_files):
data=this_file.variables[vname]
if not popens:
new_index=np.where(indices!=fcount)
ensemble3d = output3d[new_index]
avg3d=np.average(ensemble3d,axis=0)
stddev3d=np.std(ensemble3d,axis=0,dtype=np.float64)
flag3d = False
count3d = 0
count3d,ret_val=calc_Z(output3d[fcount].astype(np.float64),avg3d.astype(np.float64),stddev3d.astype(np.float64),count3d,flag3d)
Zscore=np.sum(np.square(ret_val))
if (count3d < npts3d):
Zscore3d[vcount,fcount]=np.sqrt(Zscore/(npts3d-count3d))
else:
print "WARNING: no variance in "+vname
else:
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)
#if fcount == 0 & vcount ==0:
# time_val = this_file.variables['time'][0]
# fout = "Zscore_"+str(time_val)+".txt"
# print Zscore.shape
# np.savetxt(fout,Zscore[0,3,:], fmt='%.3e')
Zscore3d[vcount,fcount,:]=Zscore[:]
#print 'zscore3d vcount,fcount=',vcount,fcount,Zscore3d[vcount,fcount]
for vcount,vname in enumerate(var_name2d):
#Read in vname's data of all files
for fcount, this_file in enumerate(o_files):
data=this_file.variables[vname]
if (is_SE == True):
output2d[fcount,:]=data[tslice,:]
else:
output2d[fcount,:,:]=data[tslice,:,:]
#Generate ens_avg and esn_stddev to store in the ensemble summary file
if popens:
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)
else:
ens_avg2d[vcount]=np.average(output2d,axis=0).astype(np.float32)
ens_stddev2d[vcount]=np.std(output2d,axis=0,dtype=np.float64).astype(np.float32)
if cumul:
temp3,gm2d[vcount]=calc_global_mean_for_onefile(this_file,area_wgt,[],[vname],temp1,ens_avg2d[vcount],tslice,is_SE,nlev,opts_dict)
if not cumul:
#Generate avg, stddev and zscore for 3d variable
for fcount,this_file in enumerate(o_files):
data=this_file.variables[vname]
if not popens:
new_index=np.where(indices!=fcount)
ensemble2d = output2d[new_index]
avg2d=np.average(ensemble2d,axis=0)
stddev2d=np.std(ensemble2d,axis=0,dtype=np.float64)
flag2d = False
count2d = 0
count2d,ret_val=calc_Z(output2d[fcount].astype(np.float64),avg2d.astype(np.float64),stddev2d.astype(np.float64),count2d,flag2d)
Zscore=np.sum(np.square(ret_val))
if (count2d < npts2d):
Zscore2d[vcount,fcount]=np.sqrt(Zscore/(npts2d-count2d))
else:
print "WARNING: no variance in "+vname
else:
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[:]
#print 'zscore2d vcount,fcount=',vcount,fcount,Zscore2d[vcount,fcount]
return Zscore3d,Zscore2d,ens_avg3d,ens_stddev3d,ens_avg2d,ens_stddev2d,gm3d,gm2d
#
# 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
#Masked the missing value
moutput=np.ma.masked_values(input_array,FillValue)
#print 'before count=',moutput.count()
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[:,:]
#Masked the rmask<1 or rmask>6
moutput2=np.ma.masked_where((rmask_array<1)|(rmask_array>6),moutput)
#print 'moutput2 count=',moutput2.count()
#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
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()
#print 'Zscore count=',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
print 'sum=',np.sum(Zscore)
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:
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:
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))
if npts == count:
Zscore=0
else:
Zscore=np.sqrt(Zscore/(npts-count))
else:
has_zscore=False
return Zscore,has_zscore
#
# Create some variables and call a function to calculate PCA
#
def pre_PCA(gm):
threshold= 1.0e-12
FillValue= 1.0e+30
gm_len=gm.shape
nvar=gm_len[0]
nfile=gm_len[1]
mu_gm=np.average(gm,axis=1).astype(np.float64)
sigma_gm=np.std(gm,axis=1,dtype=np.float64)
standardized_global_mean=np.zeros(gm.shape,dtype=np.float64)
scores_gm=np.zeros(gm.shape,dtype=np.float64)
for var in range(nvar):
for file in range(nfile):
standardized_global_mean[var,file]=(gm[var,file]-mu_gm[var])/np.where(sigma_gm[var]<=threshold,FillValue,sigma_gm[var])
loadings_gm=princomp(standardized_global_mean)
#now do coord transformation on the standardized meana to get the scores
scores_gm=np.dot(loadings_gm.T,standardized_global_mean)
sigma_scores_gm =np.std(scores_gm,axis=1,dtype=np.float64)
return mu_gm.astype(np.float32),sigma_gm.astype(np.float32),standardized_global_mean.astype(np.float32),loadings_gm.astype(np.float32),sigma_scores_gm.astype(np.float32)
#
# 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 = 0"
flag = False
count =count + stddev[(stddev <= tol)].size
return_val = 0.
else:
if stddev[(stddev <= tol)].size > 0:
if flag:
print "WARNING: some standard dev = 0"
flag =False
count =count + stddev[(stddev <= tol)].size
return_val[np.where(stddev <= tol)]=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
#
def read_jsonlist(metajson,method_name):
fd=open(metajson)
metainfo = json.load(fd)
if method_name == 'ES':
varList = metainfo['ExcludedVar']
return varList
elif method_name == 'ESP':
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
#
def area_avg(data, weight, is_SE):
#TO DO: tke into account missing values
if (is_SE == True):
a = np.average(data, weights=weight)
else: #FV
#a = wgt_areaave(data, weight, 1.0, 1)
#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, weight):
#Take into account missing values
#a = wgt_areaave(data, weight, 1.0, 1)
#weights are for lat
a = np.ma.average(data, weights=weight)
return a
def get_lev(file_dim_dict,lev_name):
return file_dim_dict[lev_name]
#
# Get dimension 'lev' or 'z_t'
#
def get_nlev(o_files,popens):
#get dimensions and compute area_wgts
input_dims = o_files[0].dimensions
if not popens:
nlev = get_lev(input_dims,'lev')
else:
nlev = get_lev(input_dims,'z_t')
return input_dims,nlev
#
# Calculate area_wgt when processes cam se/cam fv/pop files
#
def get_area_wgt(o_files,is_SE,input_dims,nlev,popens):
z_wgt={}
if (is_SE == True):
ncol = input_dims["ncol"]
output3d = np.zeros((nlev, ncol))
output2d = np.zeros(ncol)
area_wgt = np.zeros(ncol)
area = o_files[0].variables["area"]
area_wgt[:] = area[:]
total = np.sum(area_wgt)
area_wgt[:] /= total
else:
if not popens:
nlon = get_lev(input_dims,'lon')
nlat = get_lev(input_dims,'lat')
gw = o_files[0].variables["gw"]
else:
if 'nlon' in input_dims:
nlon = get_lev(input_dims,'nlon')
nlat = get_lev(input_dims,'nlat')
elif 'lon' in input_dims:
nlon = get_lev(input_dims,'lon')
nlat = get_lev(input_dims,'lat')
gw = o_files[0].variables["TAREA"]
z_wgt = o_files[0].variables["dz"]
output3d = np.zeros((nlev, nlat, nlon))
output2d = np.zeros((nlat, nlon))
#area_wgt = np.zeros(nlat) #note gaues weights are length nlat
area_wgt = gw
return output3d,output2d,area_wgt,z_wgt
#
# Open input files,compute area_wgts, and then loop through all files to call calc_global_means_for_onefile
#
def generate_global_mean_for_summary(o_files,var_name3d,var_name2d,is_SE,pepsi_gm,opts_dict):
tslice=opts_dict['tslice']
popens=opts_dict['popens']
#openfile - should have already been opened by Nio.open_file()
n3d = len(var_name3d)
n2d = len(var_name2d)
tot = n3d + n2d
gm3d = np.zeros((n3d,len(o_files)),dtype=np.float32)
gm2d = np.zeros((n2d,len(o_files)),dtype=np.float32)
input_dims,nlev=get_nlev(o_files,popens)
output3d,output2d,area_wgt,z_wgt=get_area_wgt(o_files,is_SE,input_dims,nlev,popens)
#loop through the input file list to calculate global means
#var_name3d=[]
for fcount,fname in enumerate(o_files):
if pepsi_gm:
# Generate global mean for pepsi challenge data timeseries daily files, they all are 2d variables
var_name2d=[]
for k,v in fname.variables.iteritems():
if v.typecode() == 'f':
var_name2d.append(k)
fout = open(k+"_33.txt","w")
if k == 'time':
ntslice=v[:]
for i in np.nditer(ntslice):
temp1,temp2=calc_global_mean_for_onefile(fname,area_wgt,var_name3d,var_name2d,output3d,output2d,int(i),is_SE,nlev,opts_dict)
fout.write(str(temp2[0])+'\n')
elif 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:
gm3d[:,fcount],gm2d[:,fcount]=calc_global_mean_for_onefile(fname,area_wgt,var_name3d,var_name2d,output3d,output2d,tslice,is_SE,nlev,opts_dict)
return gm3d,gm2d
#
# Calculate global means for one OCN input file
#
def calc_global_mean_for_onefile_pop(fname, area_wgt,z_wgt,var_name3d, var_name2d,output3d,output2d, tslice, is_SE, nlev,opts_dict):
n3d = len(var_name3d)
n2d = len(var_name2d)
gm3d = np.zeros((n3d),dtype=np.float32)
gm2d = np.zeros((n2d),dtype=np.float32)
#calculate global mean for each 3D variable
for count, vname in enumerate(var_name3d):
#if (verbose == True):
# print "calculating GM for variable ", vname
gm_lev = np.zeros(nlev)
data = fname.variables[vname]
output3d[:,:,:] = data[tslice,:,:,:]
for k in range(nlev):
moutput3d=np.ma.masked_values(output3d[k,:,:],data._FillValue)
gm_lev[k] = pop_area_avg(moutput3d, area_wgt)
#note: averaging over levels should probably be pressure-weighted(TO DO)
gm3d[count] = np.average(gm_lev,weights=z_wgt)
#calculate global mean for each 2D variable
for count, vname in enumerate(var_name2d):
#if (verbose == True):
# print "calculating GM for variable ", vname
data = fname.variables[vname]
output2d[:,:] = data[tslice,:,:]
moutput2d=np.ma.masked_values(output2d[:,:],data._FillValue)
gm2d_mean = pop_area_avg(moutput2d, area_wgt)
gm2d[count]=gm2d_mean
return gm3d,gm2d
#
# Calculate global means for one CAM input file
#
def calc_global_mean_for_onefile(fname, area_wgt,var_name3d, var_name2d,output3d,output2d, tslice, is_SE, nlev,opts_dict):
if 'cumul' in opts_dict:
cumul = opts_dict['cumul']
else:
cumul = False
n3d = len(var_name3d)
n2d = len(var_name2d)
gm3d = np.zeros((n3d),dtype=np.float32)
gm2d = np.zeros((n2d),dtype=np.float32)
#calculate global mean for each 3D variable
for count, vname in enumerate(var_name3d):
#if (verbose == True):
# print "calculating GM for variable ", vname
gm_lev = np.zeros(nlev)
if vname not in fname.variables:
print 'Error: the testing file does not have the variable '+vname+' that in the ensemble summary file'
continue
data = fname.variables[vname]
if (is_SE == True):
if not cumul:
output3d[:,:] = data[tslice,:,:]
for k in range(nlev):
gm_lev[k] = area_avg(output3d[k,:], area_wgt, is_SE)
else:
if not cumul:
output3d[:,:,:] = data[tslice,:,:,:]
for k in range(nlev):
gm_lev[k] = area_avg(output3d[k,:,:], area_wgt, is_SE)
#note: averaging over levels should probably be pressure-weighted(TO DO)
gm3d[count] = np.mean(gm_lev)
#calculate global mean for each 2D variable
for count, vname in enumerate(var_name2d):
#if (verbose == True):
# print "calculating GM for variable ", vname
if vname not in fname.variables:
print 'Error: the testing file does not have the variable '+vname+' that in the ensemble summary file'
continue
data = fname.variables[vname]
if (is_SE == True):
if not cumul:
output2d[:] = data[tslice,:]
gm2d_mean = area_avg(output2d[:], area_wgt, is_SE)
else:
if not cumul:
output2d[:,:] = data[tslice,:,:]
gm2d_mean = area_avg(output2d[:,:], area_wgt, is_SE)
gm2d[count]=gm2d_mean
return gm3d,gm2d
#
# Read variable values from ensemble summary file
#
def read_ensemble_summary(ens_file):
if(os.path.isfile(ens_file)):
fens = Nio.open_file(ens_file,"r")
else:
print 'file ens summary: ',ens_file,' Not found'
sys.exit(2)
is_SE = False
dims=fens.dimensions
if 'ncol' in dims:
is_SE = True
ens_avg={}
ens_stddev={}
ens_var_name=[]
ens_rmsz={}
ens_gm={}
#mu_gm={}
#sigma_gm={}
#loadings_gm={}
#sigma_scores_gm={}
# Retrieve the variable list from ensemble file
for k,v in fens.variables.iteritems():
if k== 'vars':
for i in v[0:len(v)]:
l=0
for j in i:
if j:
l=l+1
ens_var_name.append(i[0:l].tostring().strip())
elif k== 'var3d':
num_var3d=len(v)
elif k== 'var2d':
num_var2d=len(v)
for k,v in fens.variables.iteritems():
# Retrieve the ens_avg3d or ens_avg2d array
if k == 'ens_avg3d' or k=='ens_avg2d':
if k== 'ens_avg2d':
m=num_var3d
else:
m=0
if v:
for i in v[0:len(v)]:
temp_name=ens_var_name[m]
ens_avg[temp_name] = i
m=m+1
# Retrieve the ens_stddev3d or ens_stddev2d array
elif k == 'ens_stddev3d' or k == 'ens_stddev2d':
if k== 'ens_stddev2d':
m=num_var3d
else:
m=0
if v:
for i in v[0:len(v)]:
temp_name=ens_var_name[m]
ens_stddev[temp_name] = i
m=m+1
# Retrieve the RMSZ score array
elif k == 'RMSZ':
m=0
for i in v[0:len(v)]:
temp_name=ens_var_name[m]
ens_rmsz[temp_name]=i
m=m+1
elif k == 'global_mean':
m=0
for i in v[0:len(v)]:
temp_name=ens_var_name[m]
ens_gm[temp_name]=i
m=m+1
elif k == 'mu_gm':
mu_gm=np.zeros((num_var3d+num_var2d),dtype=np.float32)
mu_gm[:]=v[:]
elif k == 'sigma_gm':
sigma_gm=np.zeros((num_var3d+num_var2d),dtype=np.float32)
sigma_gm[:]=v[:]
elif k == 'loadings_gm':
loadings_gm=np.zeros((num_var3d+num_var2d,num_var3d+num_var2d),dtype=np.float32)
loadings_gm[:,:]=v[:,:]
elif k == 'sigma_scores_gm':
sigma_scores_gm=np.zeros((num_var3d+num_var2d),dtype=np.float32)
sigma_scores_gm[:]=v[:]
return ens_var_name,ens_avg,ens_stddev,ens_rmsz,ens_gm,num_var3d,mu_gm,sigma_gm,loadings_gm,sigma_scores_gm,is_SE
#
# Get the ncol and nlev value from cam run file
#
def get_ncol_nlev(frun):
input_dims=frun.dimensions
ncol = -1
nlev = -1
ilev = -1
nlat = -1
nlon = -1
icol = -1
ilat = -1
ilon = -1
for k,v in input_dims.iteritems():
if k == 'lev':
nlev = v
if k == 'ncol':
ncol = v
if (k == 'lat') or (k=='nlat'):
nlat = v
if (k == 'lon') or (k=='nlon'):
nlon = v
if ncol == -1 :
one_spatial_dim = False
else:
one_spatial_dim = True
#if nlev == -1 or ncol == -1:
# print "Error: cannot find ncol or nlev dimension in "+run_file
# sys.exit(2)
if one_spatial_dim:
npts3d=float(nlev*ncol)
npts2d=float(ncol)
else:
npts3d=float(nlev*nlat*nlon)
npts2d=float(nlat*nlon)
return npts3d,npts2d,one_spatial_dim
#
# Calculate max norm ensemble value for each variable base on all ensemble run files
# the inputdir should only have all ensemble run files
#
def calculate_maxnormens(opts_dict,var_list):
ifiles=[]
Maxnormens={}
threshold=1e-12
# input file directory
inputdir=opts_dict['indir']
# the timeslice that we want to process
tstart=opts_dict['tslice']
# open all files
for frun_file in os.listdir(inputdir):
if (os.path.isfile(inputdir+frun_file)):
ifiles.append(Nio.open_file(inputdir+frun_file,"r"))
else:
print "COULD NOT LOCATE FILE "+inputdir+frun_file+" EXISTING"
sys.exit()
comparision={}
# loop through each variable
for k in var_list:
output=[]
# read all data of variable k from all files
for f in ifiles:
v=f.variables
output.append(v[k][tstart])
max_val=0
# open an output file
outmaxnormens=k+"_ens_maxnorm.txt"
fout=open(outmaxnormens,"w")
Maxnormens[k]=[]
# calculate E(i=0:n)(maxnormens[i][x])=max(comparision[i]-E(x=0:n)(output[x]))
for n in range(len(ifiles)):
Maxnormens[k].append(0)
comparision[k]=ifiles[n].variables[k][tstart]
for m in range(len(ifiles)):
max_val=np.max(np.abs(comparision[k]-output[m]))
if Maxnormens[k][n] < max_val:
Maxnormens[k][n]=max_val
range_max=np.max((comparision[k]))
range_min=np.min((comparision[k]))
if range_max-range_min < threshold:
Maxnormens[k][n]=0.
else:
Maxnormens[k][n]=Maxnormens[k][n]/(range_max-range_min)
fout.write(str(Maxnormens[k][n])+'\n')
strtmp = k + ' : ' + 'ensmax min max' + ' : ' + '{0:9.2e}'.format(min(Maxnormens[k]))+' '+'{0:9.2e}'.format(max(Maxnormens[k]))
print strtmp
fout.close()
#
# Parse options from command line or from config file
#
def getopt_parseconfig(opts,optkeys,caller,opts_dict):
# integer
integer = '-[0-9]+'
int_p=re.compile(integer)
# scientific notation
flt = '-*[0-9]+\.[0-9]+'
flt_p=re.compile(flt)
for opt,arg in opts:
if opt =='-h' and caller=='CECT':
CECT_usage()
sys.exit()
elif opt == '-h' and caller == 'ES':
EnsSum_usage()
sys.exit()
elif opt == '-h' and caller == 'ESP':
EnsSumPop_usage()
sys.exit()
elif opt == '-f':
opts_dict['orig']=arg
elif opt == '-m':
opts_dict['reqmeth']=arg
#parse config file
elif opt in ("--config"):
configfile=arg
config=ConfigParser.ConfigParser()
config.read(configfile)
for sec in config.sections():
for name,value in config.items(sec):
if sec== 'bool_arg' or sec == 'metrics':
opts_dict[name]=config.getboolean(sec,name)
elif sec == 'int_arg':
opts_dict[name]=config.getint(sec,name)
elif sec == 'float_arg':
opts_dict[name]=config.getfloat(sec,name)
else:
opts_dict[name]=value
#parse command line options which might replace the settings in the config file
else:
for k in optkeys:
if k.find("=") != -1:
keyword=k[0:k.find('=')]
if opt == '--'+keyword:
if arg.isdigit():
opts_dict[keyword]=int(arg)
else:
if flt_p.match(arg) :
opts_dict[keyword]=float(arg)
elif int_p.match(arg) :
opts_dict[keyword]=int(arg)
else:
opts_dict[keyword]=arg
else:
if opt == '--'+k:
opts_dict[k]=True
return opts_dict
#
# Figure out the scores of the 3 new runs, standardized global means, then multiple by the loadings_gm
#
def standardized(gm,mu_gm,sigma_gm,loadings_gm):
threshold=1.0e-12
FillValue=1.0e+30
nvar=gm.shape[0]
nfile=gm.shape[1]
standardized_mean=np.zeros(gm.shape,dtype=np.float64)
for var in range(nvar):
for file in range(nfile):
standardized_mean[var,file]=(gm[var,file].astype(np.float64)-mu_gm[var].astype(np.float64))/np.where(sigma_gm[var].astype(np.float64)<=threshold, FillValue,sigma_gm[var])
new_scores=np.dot(loadings_gm.T.astype(np.float64),standardized_mean)
return new_scores
#
# Insert rmsz scores, global mean of new run to the dictionary results
#
def addresults(results,key,value,var,thefile):
if var in results:
temp = results[var]
if key in temp:
temp2 = temp[key]
if thefile in temp2:
temp3 = results[var][key][thefile]
else:
temp3={}
else:
temp[key]={}
temp2={}
temp3={}
temp3=value
temp2[thefile]=temp3
temp[key]=temp2
results[var]=temp
else:
results[var]={}
results[var][key]={}
results[var][key][thefile]=value
return results
#
# Print out rmsz score failure, global mean failure summary
#
def printsummary(results,key,name,namerange,thefilecount,variables,label):
thefile='f'+str(thefilecount)
for k,v in results.iteritems():
if 'status' in v:
temp0 = v['status']
if key in temp0:
if thefile in temp0[key]:
temp = temp0[key][thefile]
if temp < 1:
print ' '
print k+' ('+'{0:9.2e}'.format(v[name][thefile])+' outside of ['+'{0:9.2e}'.format(variables[k][namerange][0])+' '+'{0:9.2e}'.format(variables[k][namerange][1])+'])'
#
# Insert the range of rmsz score and global mean of the ensemble summary file to the dictionary variables
#
def addvariables(variables,var,vrange,thearray):
if var in variables:
variables[var][vrange]=(np.min(thearray),np.max(thearray))
else:
variables[var]={}
variables[var][vrange]=(np.min(thearray),np.max(thearray))
return variables
#
# Evaluate if the new run rmsz score/global mean in the range of rmsz scores/global mean of the ensemble summary
#
def evaluatestatus(name,rangename,variables,key,results,thefile):
totalcount=0
for k,v in results.iteritems():
if name in v and rangename in variables[k]:
temp0=results[k]
xrange = variables[k][rangename]
if v[name][thefile] > xrange[1] or v[name][thefile] < xrange[0]:
val=0
else:
val=1
if 'status' in temp0:
temp=temp0['status']
if key in temp:
temp2 = temp[key]
else:
temp[key] = temp2 = {}
if val == 0:
totalcount = totalcount+1
temp2[thefile]=val
temp[key]=temp2
results[k]['status']==temp
else:
temp0['status']={}
temp0['status'][key]={}
temp0['status'][key][thefile]=val
if val == 0:
totalcount = totalcount+1
return totalcount
#
# Evaluate if the new run PCA scores pass or fail by comparing with the PCA scores of the ensemble summary
#
def comparePCAscores(ifiles,new_scores,sigma_scores_gm,opts_dict):
comp_array=np.zeros(new_scores.shape,dtype=np.int32)
sum=np.zeros(new_scores.shape[0],dtype=np.int32)
eachruncount=np.zeros(new_scores.shape[1],dtype=np.int32)
totalcount=0
sum_index=[]
print '*********************************************** '
print 'PCA Test Results'
print '*********************************************** '
#Test to check if new_scores out of range of sigMul*sigma_scores_gm
#for i in range(new_scores.shape[0]):
for i in range(opts_dict['nPC']):
for j in range(new_scores.shape[1]):
if abs(new_scores[i][j]) > opts_dict['sigMul'] * (sigma_scores_gm[i]):
comp_array[i][j] = 1
eachruncount[j]=eachruncount[j]+1
#Only check the first nPC number of scores, and sum comp_array together
sum[i]=sum[i]+comp_array[i][j]
if len(ifiles) >= opts_dict['minRunFail']:
num_run_less = False
else:
num_run_less = True
#Check to see if sum is larger than min_run_fail, if so save the index of the sum
for i in range(opts_dict['nPC']):
if sum[i] >= opts_dict['minRunFail']:
totalcount=totalcount+1
sum_index.append(i+1)
false_positive=check_falsepositive(opts_dict,sum_index)
#If the length of sum_index is larger than min_PC_fail, the three runs failed
if len(sum_index) >= opts_dict['minPCFail']:
decision='FAILED'
else:
decision='PASSED'
if num_run_less == False:
print ' '
print "Summary: "+str(totalcount)+" PC scores failed at least "+str(opts_dict['minRunFail'])+" runs: ",sum_index
print ' '
print 'These runs '+decision+' according to our testing criterion.'
if decision == 'FAILED' and false_positive != 1.0:
print 'The probability of this test failing although everything functions correctly (false positive) is '+'{0:5.2f}'.format(false_positive*100)+'%.'
print ' '
print ' '
else:
print ' '
print 'The number of run files is less than minRunFail (=2), so we cannot determin an overall pass or fail.'
print ' '
#Record the histogram of comp_array which value is one by the PCA scores
for i in range(opts_dict['nPC']):
index_list=[]
for j in range(comp_array.shape[1]):
if comp_array[i][j] == 1:
index_list.append(j+1)
if len(index_list) > 0:
print "PC "+str(i+1)+": failed "+str(len(index_list))+" runs ",index_list
print ' '