MPAS-JEDI
writediag_modelspace_ci.py
Go to the documentation of this file.
1 import os
2 import sys
3 import numpy
4 import numpy as np
5 from netCDF4 import Dataset
6 import matplotlib.cm as cm
7 import matplotlib.pyplot as plt
8 from mpl_toolkits.basemap import Basemap
9 from copy import deepcopy
10 import datetime as dt
11 from datetime import datetime, timedelta
12 import numpy.random as npr
13 import modelsp_utils as mu
14 
15 expStats = 'expmgfsci'
16 allmetrics = ['RMS'] #,'MS']
17 
18 def readdata():
19 
20  if os.path.exists(expStats+'.nc'):
21  os.remove(expStats+'.nc')
22 
23  varNamesListAll = []
24  for metrics in allmetrics:
25  #only for 3dim variables
26  for varName in mu.varNames3d:
27  for latBand in mu.latBands:
28  for fcTDelta in np.arange(0, mu.fcRange+mu.interval,mu.interval):
29  varNamesList = ['expmgfs_day'+str(fcTDelta)+'_'+ latBand +'_'+ varName + '_' + metrics]
30  varNamesListAll.append(varNamesList)
31  for metrics in allmetrics:
32  #for 2dim and 3dim variables:
33  for varName in mu.varNames:
34  for latBand in mu.latBands:
35  varNamesList2 = ['expmgfs_'+ latBand +'_'+ varName + '_' + metrics]
36  varNamesListAll.append(varNamesList2)
37  for i in range(0,len(varNamesListAll)):
38  alldata = []
39  alldatacon = []
40  alldiffdata = []
41  alldiffdata_rmsdiv = []
42  xlabeltime = []
43  TDATE = mu.SDATE
44  while TDATE <= mu.EDATE:
45  data1 = []
46  diffdata = []
47  diffdata_rmsdiv = []
48  date = TDATE.strftime('%Y%m%d%H')
49  xlabeltime = np.append(xlabeltime,date[4:][:-2])
50  nc_file1 = mu.EXP_DIR1+'/'+date+'/diagnostic_stats/expmgfs.nc'
51  nc_fid1 = Dataset(nc_file1, "r", format="NETCDF4")
52  #data1: exp1-GFSANA
53  data1 = np.array( nc_fid1.variables[''.join(varNamesListAll[i])][:] )
54  alldata = np.append(alldata, data1)
55 
56  nc_file2 = mu.EXP_DIR2+'/'+date+'/diagnostic_stats/expmgfs.nc'
57  nc_fid2 = Dataset(nc_file2, "r", format="NETCDF4")
58  #data2: exp2-GFSANA
59  data2 = np.array( nc_fid2.variables[''.join(varNamesListAll[i])][:] )
60  #diffdata, e.g. rms(exp1-GFSANA)-rms(exp2-GFSANA)
61  diffdata = data2 - data1
62  alldiffdata = np.append(alldiffdata, diffdata)
63 
64  TDATE += mu.DATEINC
65 
66  alldiffdata = alldiffdata.reshape(len(xlabeltime),len(diffdata)).T
67  newfile = write_stats(alldiffdata,''.join(varNamesListAll[i]))
68 #TODO: move the following functions to plot_utils.py or basic_plot_functions.py
69 def write_stats(array_f,varNames):
70  lows =[]
71  highs = []
72  mean = []
73  rms = []
74 
75  #get dimesion for array_f (function of fcnums or levels)
76  x, y = array_f.shape
77 
78  #loop for every fcnums or levels:
79  for i in range(0,x):
80 
81  STATS = {}
82  STATS['Mean'] = np.nanmean(array_f,axis=1)
83 
84  low, high = bootstrap(array_f[i,:], 10000, np.mean, 0.05)
85  lows = np.append(lows, low)
86  highs = np.append(highs,high)
87  stat = np.column_stack((STATS['Mean'], lows, highs))
88 
89  if os.path.exists(expStats+'.nc'):
90  w_nc_fid = Dataset(expStats+'.nc', 'a', format='NETCDF4')
91  else:
92  w_nc_fid = Dataset(expStats+'.nc', 'w', format='NETCDF4')
93  w_nc_fid.description = "MPAS diagnostics/statistics"
94  w_nc_fid.createDimension('level',int(mu.nlevels))
95  w_nc_fid.createDimension('levelP1',int(mu.nlevelsP1))
96  w_nc_fid.createDimension('fcnums',int(mu.fcNums))
97  w_nc_fid.createDimension('stat',3)
98  if x == 55:
99  w_nc_var = w_nc_fid.createVariable(varNames,'f4', ('level','stat'))
100  elif (x == 56):
101  w_nc_var = w_nc_fid.createVariable(varNames,'f4', ('levelP1','stat'))
102  else:
103  w_nc_var = w_nc_fid.createVariable(varNames,'f4', ('fcnums','stat'))
104  w_nc_fid.variables[varNames][:] = stat
105  w_nc_fid.close()
106 
107 def bootstrap(data, num_samples, statistic, alpha):
108  #Returns bootstrap estimate of 100.0*(1-alpha) CI for statistic.
109  n = data.size
110  idx = npr.randint(0, n, (num_samples, n))
111  samples_with_replacement = data[idx]
112  stat = np.sort(statistic(samples_with_replacement, 1))
113  return (stat[int((alpha/2.0)*num_samples)], stat[int((1-alpha/2.0)*num_samples)])
114 
115 def main():
116  readdata()
117 
118 if __name__ == '__main__': main()
def write_stats(array_f, varNames)
def bootstrap(data, num_samples, statistic, alpha)