- Timestamp:
- Mar 8, 2019, 2:04:38 PM (6 years ago)
- Location:
- trunk/tools
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/tools/nc_var.py
r2382 r2384 74 74 ## e.g. # nc_var.py -o usefile_compute_slices_stats_areaweighted -S 'compute_slices_stats_areaweighted.nc@XLAT_M-HGT_M-rangefaces@Time|WRFtime:west_east|XLONG_M:south_north|XLAT_M:land_cat|INTrange@Time,land_cat' -f 'geo_em.d01.nc' -v 'LANDUSEF' 75 75 ## e.g. # nc_var.py -o compress_data -S 'XLAND:Time|0:single,1:X|west_east|XLONG,Y|south_north|XLAT' -f wrfout_d01_1995-01-01_00:00:00 -v T2,LU_INDEX,Times 76 ## e.g. # nc_var.py -o CFfile_creation -S 'lon|360,lat|180,time|None@20:global' -v 'tas#time;lat;lon#f#None,time#time#f8#units|seconds!since!1949-12-01!00:00:00|S' -f newCF.nc 76 77 77 78 from optparse import OptionParser … … 90 91 # of matrices assuming regular lon/lat projections without taking into account Earth's curvature 91 92 # CDO_toCF: Function to pass a CDO output file to CF-conventions 93 # CFfile_creation: Operation to create a file folowing CF-conventions 92 94 # CFmorzization: Function to provide a CF-compilation version of a variable within a file 93 95 # chdimname: Changing the name of the dimension … … 229 231 230 232 operations=['addDim', 'addVar', 'addvals', 'area_weighted', 'CDO_toCF', \ 231 'CF morzization', 'chdimname', 'changevartype',\233 'CFfile_creation', 'CFmorzization', 'chdimname', 'changevartype', \ 232 234 'checkallvars', 'checkAllValues', 'checkNaNs', \ 233 235 'chgtimestep', 'chvarname', 'cleaning_varsfile', 'compress_data', \ … … 311 313 312 314 # Operations which file name is not a real file 313 NotCheckingFile = ['area_weighted', ' DatesFiles', 'compute_opersvarsfiles',\314 ' file_creation',\315 NotCheckingFile = ['area_weighted', 'CFfile_creation','DatesFiles', \ 316 'compute_opersvarsfiles', 'file_creation', \ 315 317 'join_singlestation_obsfiles', 'join_sounding_obsfiles', 'list_operations', \ 316 318 'merge_files', \ … … 352 354 elif oper == 'CDO_toCF': 353 355 ncvar.CDO_toCF(opts.ncfile) 356 elif oper == 'CFfile_creation': 357 ncvar.CFfile_creation(opts.values, opts.ncfile, opts.varname) 354 358 elif oper == 'CFmorzization': 355 359 ncvar.CFmorzization(opts.values, opts.ncfile, opts.varname) -
trunk/tools/nc_var_tools.py
r2383 r2384 33 33 # basicvardef: Function to give the basic attributes to a variable (std_name, long_name, units) 34 34 # CDO_toCF: Function to pass a CDO output file to CF-conventions 35 # CFfile_creation: Operation to create a file folowing CF-conventions 35 36 # CFmorzization: Function to provide a CF-compilation version of a variable within a file 36 37 # CFvars: Function to adapt a given variable and file following CF-standards … … 31068 31069 """ Operation to create a file folowing CF-conventions 31069 31070 values= [dimensions]:[lonlatbox] 31070 [dimensions]: lon|[dsizelon],lat|[dsizelat],...,[dimnN]:[dsizeN], ',' pairs of variable 31071 name [dimn] and [size] 31072 if [dsize] = 'None' (for UNLIMITED), give a third value with the real size 31071 [dimensions]: lon|[dsizelon],lat|[dsizelat],...,[dimnN]|[dsizeN], ',' pairs 31072 of variable name [dimn] and [size] 31073 * if [dsize] = 'None' (for UNLIMITED), provide size of dimension as 31074 'None'@[size] 31073 31075 [lonlatbox]: ',' separated list of the extremes of the domain [SWlon],[SWlat], 31074 31076 [NElon],[NElat] or 'global' for a global file [assuing lon/lat regular 31075 31077 projection] 31076 ncfile= name of the file 31077 variables= ',' list of variables to create [varn] :[dims]:[kind]:[varaddattributes]31078 ncfile= name of the file to produce 31079 variables= ',' list of variables to create [varn]#[dims]#[kind]#[vaddattributes] 31078 31080 and its characterisitcs 31079 [varn]: CF name of the variable ( attributes will be retrived from31080 'variables_values.dat')31081 [dims]: ' ,' python sorted list of dimensions of the variable31081 [varn]: CF name of the variable (basic attributes: standard_name, long_name 31082 and units, will be retrived from 'variables_values.dat') 31083 [dims]: ';' sorted list of dimensions of the variable ([...], [t], [z], y, x) 31082 31084 [kind]: type of variable (standard netCDF4/C-like values, 'c', 'i', 'f', 31083 31085 'f8',...) 31084 [varaddattributes]: ',' list of additional attributes and their values for 31085 the variable [attrn]|[attrv] 31086 [varaddattributes]: ';' list of additional attributes and their values for 31087 the variable [attrn]|[attrv]|[attrk] ('None' for any) '!' for spaces in 31088 string attributes 31089 [attrn]: name of the attribute 31090 [attrv]: value of the attribute 31091 [attrk]: kind of the attribute('S': string, 'I': integer, 'F': float, ...) 31086 31092 """ 31087 31093 fname = 'CFfile_creation' 31094 availkind = ['c', 'i', 'f', 'f8'] 31088 31095 31089 31096 if values == 'h': … … 31109 31116 onewnc = NetCDFFile(ncfile, 'w') 31110 31117 31111 dimx = dimensions['lon']31112 dimy = dimensions['lat']31118 dimx = int(dimensions['lon']) 31119 dimy = int(dimensions['lat']) 31113 31120 31114 31121 # Assuming regular lon/lat projection 31115 31122 if lonlatbox == 'global': 31116 ddx = 360./(dimx -1)31123 ddx = 360./(dimx) 31117 31124 ddx2 = ddx/2. 31118 31125 lons = np.arange(-180.+ddx2,180.+ddx2,ddx) 31119 ddy = 180./(dimy -1)31126 ddy = 180./(dimy) 31120 31127 ddy2 = ddy/2. 31121 31128 lats = np.arange(-90.+ddy2,90.+ddy2,ddy) 31122 31129 elif lonlatbox.count(',') == 3: 31123 31130 [lonSW, latSW, lonNE, latNE] = str_listk(lonlatbox, ',', 'F') 31124 ddx = (lonNE-lonSW)/(dimx -1)31131 ddx = (lonNE-lonSW)/(dimx) 31125 31132 ddx2 = ddx/2. 31126 31133 lons = np.arange(lonSW-ddx2,lonNE+ddx2,ddx) 31127 ddy = (latNE-latSW)/(dimy -1)31134 ddy = (latNE-latSW)/(dimy) 31128 31135 ddy2 = ddy/2. 31129 31136 lats = np.arange(latSW-ddy2,latNE+ddy2,ddy) 31130 31137 31138 print 'Lluis shapes lons:', lons.shape, 'lats:', lats.shape 31131 31139 # Sorting lon/lat_bounds 31132 lon_bnds = np.zeros(( 2,dimx), dtype=np.float64)31133 lat_bnds = np.zeros(( 2,dimy), dtype=np.float64)31140 lon_bnds = np.zeros((dimx,2), dtype=np.float64) 31141 lat_bnds = np.zeros((dimy,2), dtype=np.float64) 31134 31142 for i in range(dimx): 31135 lon_bnds[ 0,i] = lons[i]-ddx231136 lon_bnds[ 1,i] = lons[i]+ddx231143 lon_bnds[i,0] = lons[i]-ddx2 31144 lon_bnds[i,1] = lons[i]+ddx2 31137 31145 for j in range(dimy): 31138 lat_bnds[ 0,j] = lats[j]-ddy231139 lat_bnds[ 1,j] = lats[j]+ddy231146 lat_bnds[j,0] = lats[j]-ddy2 31147 lat_bnds[j,1] = lats[j]+ddy2 31140 31148 31141 31149 # Dimensions … … 31147 31155 for dn in dimensions: 31148 31156 if dn != 'lon' and dn != 'lat': 31149 if d n == 'time': dl = None31150 else: dl = dimensions[dn]31151 newdim = onewnc.createDimension(dn, None)31157 if dimensions[dn][0:4] == 'None': dl = None 31158 else: dl = int(dimensions[dn]) 31159 newdim = onewnc.createDimension(dn, dl) 31152 31160 onewnc.sync() 31153 31161 … … 31159 31167 newvar.setncattr('axis', 'X') 31160 31168 newvar.setncattr('_CoordinateAxisType', 'Lon') 31169 newvar.setncattr('bounds', 'lon_bnds') 31161 31170 31162 31171 newvar = onewnc.createVariable('lat', 'f4', ('lat')) … … 31166 31175 newvar.setncattr('axis', 'Y') 31167 31176 newvar.setncattr('_CoordinateAxisType', 'Lat') 31177 newvar.setncattr('bounds', 'lat_bnds') 31178 31179 # Creation of variable dimensions 31180 newvar = onewnc.createVariable('lon_bnds', 'f4', ('lon', 'bnds')) 31181 newvar[:] = lon_bnds[:] 31182 newvar = onewnc.createVariable('lat_bnds', 'f4', ('lat', 'bnds')) 31183 newvar[:] = lat_bnds[:] 31184 31185 # Projection 31186 projn = 'regular_latlon' 31187 newvar = onewnc.createVariable(projn, 'c') 31188 newvar.setncattr('grid_mapping_name', 'latitude_longitude') 31168 31189 31169 31190 onewnc.sync() 31170 31191 31171 31192 varns = variables.split(',') 31172 for varn in varns: 31173 print varn 31174 31175 dnames = [] 31176 dsize = [] 31177 for dim in dimensions: 31178 # print " Adding: '" + dim + "' ..." 31179 dimn = dim.split(':')[0] 31180 dimv = dim.split(':')[1] 31181 if dimv == 'None': 31182 if len(dim.split(':')) != 3: 31193 for varvn in varns: 31194 varn = varvn.split('#')[0] 31195 dims = varvn.split('#')[1].split(';') 31196 kind = varvn.split('#')[2] 31197 31198 # Checking variable's dimensions 31199 varshape = [] 31200 for dn in dims: 31201 if not onewnc.dimensions.has_key(dn): 31183 31202 print errormsg 31184 print ' ' + fname + ": dimension '" + dimn + "' is None but the " + \ 31185 'size is requried!!' 31203 print ' ' + fname + ": CF netCDF file does not have dimension '" + \ 31204 dn + "' !!" 31205 print " provide values for the dimension as [dimensions]= " + \ 31206 "[dimnN]|[dsizeN]" 31207 Dims = list(onewnc.dimensions.keys()) 31208 Dims.sort() 31209 print ' available ones:', Dims 31186 31210 quit(-1) 31187 31211 else: 31188 dv = None 31189 dsize.append(int(dim.split(':')[2])) 31212 if dimensions[dn][0:4] == 'None': 31213 dsize = int(dimensions[dn].split('@')[1]) 31214 else: 31215 dsize = len(onewnc.dimensions[dn]) 31216 varshape.append(dsize) 31217 31218 # Getting variable basic attributes 31219 cfvarvals = gen.variables_values(varn) 31220 31221 print ' ' + fname + ": adding '" + varn + "' (", dims, ") '", kind, "' ..." 31222 31223 varaddattributes = varvn.split('#')[3] 31224 if varaddattributes != 'None': 31225 vaddattr = {} 31226 addattr = varaddattributes.split(';') 31227 for attr in addattr: 31228 attrv = attr.split('|') 31229 vaddattr[attrv[0]] = attrv[1:4] 31230 print ' addiditional attributes _______' 31231 gen.printing_dictionary(vaddattr) 31190 31232 else: 31191 dv = int(dimv) 31192 dsize.append(dv) 31193 31194 dnames.append(dimn) 31195 31196 newdim = onc.createDimension(dimn, dv) 31233 vaddattr = None 31234 31235 # creation 31236 if kind == 'c': 31237 newvar = onewnc.createVariable(varn, 'c', tuple(dims)) 31238 if kind == 'f' or kind == 'f4': 31239 newvar = onewnc.createVariable(varn, 'f4', tuple(dims), \ 31240 fill_value=gen.fillValueF) 31241 newvar[:] = np.zeros(tuple(varshape), dtype=np.float) 31242 elif kind == 'f8': 31243 newvar = onewnc.createVariable(varn, 'f8', tuple(dims), \ 31244 fill_value= gen.fillValueD) 31245 newvar[:] = np.zeros(tuple(varshape), dtype=np.float64) 31246 elif kind == 'i': 31247 newvar = onewnc.createVariable(varn, 'i', tuple(dims), \ 31248 fill_value=gen.fillValueI) 31249 newvar[:] = np.zeros(tuple(varshape), dtype=int) 31250 else: 31251 print errormsg 31252 print ' ' + fname + ": variable kind '" + kind + "' not ready!!" 31253 print ' available ones:', availkind 31254 quit(-1) 31197 31255 31198 onc.sync() 31199 31200 # Variable 31201 if kind == 'c': 31202 newvar = onc.createVariable(varn, 'c', tuple(dnames)) 31203 # newvar[:] = np.zeros(tuple(dsize), dtype=np.float) 31204 if kind == 'f' or kind == 'f4': 31205 newvar = onc.createVariable(varn, 'f4', tuple(dnames), \ 31206 fill_value=gen.fillValueF) 31207 newvar[:] = np.zeros(tuple(dsize), dtype=np.float) 31208 elif kind == 'f8': 31209 newvar = onc.createVariable(varn, 'f8', tuple(dnames), \ 31210 fill_value= gen.fillValueD) 31211 newvar[:] = np.zeros(tuple(dsize), dtype=np.float64) 31212 elif kind == 'i': 31213 newvar = onc.createVariable(varn, 'i', tuple(dnames), \ 31214 fill_value=gen.fillValueI) 31215 newvar[:] = np.zeros(tuple(dsize), dtype=int) 31216 else: 31217 print errormsg 31218 print ' ' + fname + ": variable kind '" + kind + "' not ready!!" 31219 quit(-1) 31220 31221 sname = attributes.split('@')[0].replace('!', ' ') 31222 lname = attributes.split('@')[1].replace('!', ' ') 31223 u = attributes.split('@')[2].replace('!', ' ') 31224 31225 newattr = basicvardef(newvar, sname, lname, u) 31226 31227 onc.sync() 31228 31229 # Global attributes 31230 newattr = set_attribute(onc, 'description', "file creation using " + fname ) 31231 onc.sync() 31232 onc.close() 31233 31234 #file_creation('time_counter:12,sizes:24|time@time@seconds since 1949-12-01 00:00:00|f8', 'test.nc', 't_instant') 31256 basicvardef(newvar, cfvarvals[1], cfvarvals[4].replace('|',' '), cfvarvals[5]) 31257 newvar.setncattr('grid_mapping', projn) 31258 if vaddattr is not None: 31259 for attrn in vaddattr.keys(): 31260 attrv = vaddattr[attrn] 31261 if attrv[1] == 'S': 31262 set_attributek(newvar, attrn, attrv[0].replace('!', ' '), attrv[1]) 31263 else: 31264 set_attributek(newvar, attrn, attrv[0], attrv[1]) 31265 31266 onewnc.sync() 31267 31268 # Global attributes 31269 onewnc.setncattr('Conventions', 'CF-1.5') 31270 add_global_PyNCplot(onewnc, 'nc_var_tools', fname, '1.0') 31271 31272 onewnc.sync() 31273 onewnc.close() 31274 31275 print fname + ": Successfully written CF-file '" + ncfile + "' !!" 31276 31277 return 31278 31279 #values='lon|360,lat|180,time|None@20:global' 31280 #varsS='tas#time;lat;lon#f#None,time#time#f8#units|seconds!since!1949-12-01!00:00:00|S' 31281 #CFfile_creation(values, 'CFtest.nc', varsS) 31235 31282 31236 31283
Note: See TracChangeset
for help on using the changeset viewer.