Changeset 2352 in lmdz_wrf
- Timestamp:
- Feb 19, 2019, 5:48:44 PM (6 years ago)
- Location:
- trunk/tools
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/tools/nc_var.py
r2343 r2352 72 72 ## e.g. # nc_var.py -o compute_slices_stats_areaweighted -S 'lat,-63.,19.,2.;orog,500.,7000.,500.;rangefaces,fixed,-2.5|-0.5,-0.5|0.5,0.5|2.5@time|time:lon|lon:lat|lat@time@lon|lon_bnds,lat|lat_bnds@lon|lon_bnds,lat|lat_bnds@lat,lon@time' -f /media/lluis/ExtDiskC_ext3/DATA/estudios/Andes/DATA/concatenated/historical/tasmin/tasmin_Amon_ACCESS1-0_historical_r1i1p1_185001-200512_Andes_19600101000000-19900101000000.nc -v tasmin 73 73 ## e.g. # nc_var.py -o except_fillValue -S 'orog:range,500.,7000.:None' -f /home/lluis/estudios/Andes/cmip_data/fx/orog_fx_ACCESS1-0_historical_r0i0p0.nc -v 'all' 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' 74 75 75 76 from optparse import OptionParser … … 202 203 # TimeSplitmat: Function to transform a file with CFtimes to a matrix [Nyear,Nmonth,Nday,Nhour,Nminute,Nsecond] 203 204 # timemean: Function to retrieve a time mean series from a multidimensional variable of a file 205 # usefile_compute_slices_stats_areaweighted: Function to compute stats of variables of 206 # a file splitting variables by slices along sets of ranges for a series of 207 # variables weighting by the area covered by each grid (defined as polygon) within 208 # the slice using pre-calculated area-weights from an existing file 204 209 # valmod: Function to modify the value of a variable 205 210 # valmod_dim: Function to modify the value of a variable at a given dimension and value … … 251 256 'splitfile_dim', 'statcompare_files', \ 252 257 'subbasin', 'submns', 'subyrs', 'temporal_stats', 'TimeInf', 'time_reset', \ 253 'TimeSplitmat', 'timemean', 'valmod', 'valmod_dim','varaddattrk', 'varaddattr', \ 258 'TimeSplitmat', 'timemean', 'usefile_compute_slices_stats_areaweighted', \ 259 'valmod', 'valmod_dim','varaddattrk', 'varaddattr', \ 254 260 'varaddref', \ 255 261 'var_creation', 'varout', 'varoutold', 'varrmattr', 'varrm', 'VarVal_FillValue', \ … … 554 560 elif oper == 'timemean': 555 561 ncvar.timemean(opts.values, opts.ncfile, opts.varname) 562 elif oper == 'usefile_compute_slices_stats_areaweighted': 563 ncvar.usefile_compute_slices_stats_areaweighted(opts.values, opts.ncfile, \ 564 opts.varname) 556 565 elif oper == 'valmod': 557 566 ncvar.valmod(opts.values, opts.ncfile, opts.varname) -
trunk/tools/nc_var_tools.py
r2350 r2352 187 187 # TimeSplitmat: Function to transform a file with CFtimes to a matrix [Nyear,Nmonth,Nday,Nhour,Nminute,Nsecond] 188 188 # uploading_timestep: Function to upload a given time-step of a variable inside a netCDF 189 # usefile_compute_slices_stats_areaweighted: Function to compute stats of variables of 190 # a file splitting variables by slices along sets of ranges for a series of 191 # variables weighting by the area covered by each grid (defined as polygon) within 192 # the slice using pre-calculated area-weights from an existing file 189 193 # valmod: Function to modify the value of a variable 190 194 # valmod_dim: Function to modify the value of a variable at a given dimension and value … … 29724 29728 #except_fillValue('orog:range,500.,7000.:None:value,0', '/home/lluis/estudios/Andes/cmip_data/fx/orog_fx_ACCESS1-0_historical_r0i0p0.nc', 'all') 29725 29729 29730 29731 def usefile_compute_slices_stats_areaweighted(values, ncfile, variable): 29732 """ Function to compute stats of variables of a file splitting variables by 29733 slices along sets of ranges for a series of variables weighting by the area 29734 covered by each grid (defined as polygon) within the slice using 29735 pre-calculated area-weights from an existing file 29736 values=[areaweightsfile]@[slicen]@[dimvars]@[slicestatsdim] 29737 [areaweightsfile]: file with the pre-calculated area-weights 29738 [slicen]: name of the slice 29739 [dimvars]: ':' separated list of [dimn]|[vardimn] dimension name [dimn] and 29740 its associated dimension-variable to get its values to provide values for 29741 the final file. 29742 'WRFtime': to compute CF-compilant times from WRF's variable 'Times' 29743 'INTrange': variable as dimension-length series of consecutive integers 29744 [slicestatsdim]: ',' list of name of dimensions to do not use for computing 29745 statistics of variables at each slice ('any' for not leaving any 29746 dimension out, resulting on scalar statistics) 29747 ncfile= netCDF file to use 29748 variable: ',' list of variables ('all' for all variables) 29749 """ 29750 fname = 'usefile_compute_slices_stats_areaweighted' 29751 29752 # Statistics from values within final slice 29753 statns = ['min', 'max', 'mean', 'mean2', 'stddev', 'median', 'count'] 29754 Lstatns = {'min': 'space minimum', 'max': 'space maximum', 'mean': 'space mean', \ 29755 'mean2': 'space quadratic mean', 'stddev': 'spcae standard deviation', \ 29756 'median': 'median', 'count': 'amount of grids'} 29757 Ustatns = {'min': 'vu', 'max': 'vu', 'mean': 'vu', 'mean2': 'vu', 'stddev': 'vu',\ 29758 'median': 'vu', 'count': 'counts'} 29759 29760 if values == 'h': 29761 print fname + '_____________________________________________________________' 29762 print usefile_compute_slices_stats_areaweighted.__doc__ 29763 quit() 29764 29765 expectargs = '[areaweightsfile]@[slicen]@[dimvars]@[slicestatsdim]' 29766 gen.check_arguments(fname, values, expectargs, '@') 29767 29768 areaweightsfile = values.split('@')[0] 29769 slicen = values.split('@')[1] 29770 dimvars0 = values.split('@')[2] 29771 slicestatsdim = values.split('@')[3].split(',') 29772 29773 dimvars = gen.stringS_dictvar(dimvars0, Dc=':', DVs='|') 29774 29775 if not os.path.isfile(areaweightsfile): 29776 print errormsg 29777 print ' '+fname+ ": pre calculated area-weights file '" + areaweightsfile + \ 29778 "' does not exist !!" 29779 quit(-1) 29780 29781 awonc = NetCDFFile(areaweightsfile, 'r') 29782 29783 if variable == 'all': 29784 varns = awonc.variables.keys() 29785 else: 29786 varns = variable.split(',') 29787 29788 vsurnames = ['Ngrid', 'gridin', 'areagridpercen', 'area'] 29789 29790 invarn = slicen + vsurnames[0] 29791 29792 if not awonc.variables.has_key(invarn): 29793 print errormsg 29794 print ' '+fname+ ": pre calculated area-weights file '" + areaweightsfile + \ 29795 "' does not have slice '" + invarn + "' !!" 29796 Varns = list(awonc.variables) 29797 Varns.sort() 29798 vvns = [] 29799 for vn in Varns: 29800 Lvn = len(vn) 29801 if vn[Lvn-5:Lvn] == 'Ngrid': vvns.append(vn) 29802 print ' available ones:', vn 29803 quit(-1) 29804 29805 osN = awonc.variables[slicen+vsurnames[0]] 29806 osin = awonc.variables[slicen+vsurnames[1]] 29807 osgpa = awonc.variables[slicen+vsurnames[2]] 29808 osga = awonc.variables[slicen+vsurnames[3]] 29809 29810 sN = osN[:] 29811 sin = osin[:] 29812 sgpa = osgpa[:] 29813 29814 # removing monotones. Fortran only accepts rank <= 7 arrays !! 29815 sN, Ndims = gen.remove_monotones(sN, osN.dimensions) 29816 sin, indims = gen.remove_monotones(sin, osin.dimensions) 29817 sgpa, gpadims = gen.remove_monotones(sgpa, osga.dimensions) 29818 29819 ssh = sN.shape 29820 dimsslice = list(Ndims) 29821 shapeslice = list(sN.shape) 29822 29823 sNt = sN.transpose() 29824 #sint = sin.transpose() 29825 sint0 = sin.transpose() 29826 ## We are going to use them in Fortran thus (dx,dy) and 1st:1 !!!! 29827 sint = np.ones((sint0.shape), dtype=np.float)*gen.fillValueF 29828 sint[...,0] = sint0[...,1] 29829 sint[...,1] = sint0[...,0] 29830 sint = sint + 1 29831 spt = sgpa.transpose() 29832 29833 print ' ' + infmsg 29834 print ' final slice:', Ndims, 'shape:', sN.shape 29835 onc = NetCDFFile(ncfile, 'r') 29836 29837 onewnc = NetCDFFile(fname + '.nc', 'w') 29838 29839 # Adding slicing dimensions and variables to the output file 29840 slcvn = slicen.split('-') 29841 for slcvn in slcvn: 29842 vn = 'slice_' + slcvn 29843 if not onewnc.variables.has_key(vn): add_vars(awonc, onewnc, [vn]) 29844 onewnc.sync() 29845 if awonc.variables.has_key('slice_fake'): add_vars(awonc, onewnc, ['slice_fake']) 29846 29847 awonc.close() 29848 29849 for varn in varns: 29850 if not onc.variables.has_key(varn): 29851 print errormsg 29852 print ' '+fname+ ": file '" + ncfile + "' does not have variable '" + varn + "' !!" 29853 Varns = list(onc.variables) 29854 Varns.sort() 29855 print ' available ones:', Varns 29856 quit(-1) 29857 print ' ' + varn + ' ...' 29858 29859 ovar = onc.variables[varn] 29860 vdimns = list(ovar.dimensions) 29861 vshape = list(ovar.shape) 29862 vu = ovar.units 29863 29864 # Looking for possible new dimensions and dim-variables 29865 vardims = [] 29866 varshape = [] 29867 idd = 0 29868 for dnn in vdimns: 29869 vdimn = dimvars[dnn] 29870 if vdimn == 'WRFtime': 29871 vdimn = 'time' 29872 if not onewnc.variables.has_key('time'): 29873 odimvar = onc.variables['Times'] 29874 timewrfv = odimvar[:] 29875 tvals, urefvals = compute_WRFtime(timewrfv, \ 29876 refdate='19491201000000', tunitsval='minutes') 29877 tvals = np.array(tvals) 29878 dimtwrf = len(tvals) 29879 if not gen.searchInlist(onewnc.dimensions,vdimn): 29880 newdim = onewnc.createDimension(vdimn, None) 29881 if not gen.searchInlist(onewnc.variables,vdimn): 29882 newvar = onewnc.createVariable(vdimn, 'f', ('time')) 29883 newvar[:] = tvals 29884 basicvardef(newvar, 'time', 'Time', urefvals) 29885 newvar.setncattr('calendar','gregorian') 29886 onewnc.sync() 29887 if gen.searchInlist(slicestatsdim, dnn): 29888 vardims.append(vdimn) 29889 varshape.append(dimtwrf) 29890 elif vdimn == 'INTrange': 29891 vdimn = dnn + '_intrange' 29892 if not onewnc.variables.has_key(vdimn): 29893 Lvdim = len(onc.dimensions[dnn]) 29894 if not gen.searchInlist(onewnc.dimensions,dnn): 29895 newdim = onewnc.createDimension(dnn, Lvdim) 29896 if not gen.searchInlist(onewnc.variables,vdimn): 29897 print " creation of '" + vdimn + "' " 29898 newvar = onewnc.createVariable(vdimn, 'i', (dnn)) 29899 newvar[:] = np.arange(Lvdim) 29900 basicvardef(newvar, vdimn, vdimn, '1') 29901 onewnc.sync() 29902 if gen.searchInlist(slicestatsdim, dnn): 29903 vardims.append(dnn) 29904 varshape.append(Lvdim) 29905 else: 29906 if gen.searchInlist(slicestatsdim, dnn): 29907 vardims.append(vdimn) 29908 varshape.append(len(onc.dimensions[dnn])) 29909 if not gen.searchInlist(onewnc.dimensions,dnn): 29910 add_dims(onc, onewnc, [dnn]) 29911 if not gen.searchInlist(onewnc.variables,vdimn): add_vars(onc, \ 29912 onewnc, [vdimn]) 29913 idd = idd + 1 29914 29915 newvardims = vardims + dimsslice 29916 newvarshape = varshape + shapeslice 29917 29918 print 'Lluis newvardims:', newvardims, 'newvarshape:', newvarshape 29919 print 'Lluis file dims:', onewnc.dimensions.keys() 29920 # Generic newvar slice 29921 newvarslice = [] 29922 for idd in range(len(newvarshape)): 29923 newvarslice.append(slice(0,newvarshape[idd])) 29924 29925 onewvars = {} 29926 for statn in statns: 29927 Lstn = Lstatns[statn] 29928 if Ustatns[statn] == 'vu': vvu = vu 29929 else: 29930 if statn == 'mean2': vvu = vu + '2' 29931 else: vvu = Ustatns[statn] 29932 newvar= onewnc.createVariable(varn+'sliced'+statn,'f', tuple(newvardims),\ 29933 fill_value = gen.fillValueF) 29934 basicvardef(newvar, varn+'sliced'+statn, Lstn + ' ' + varn + \ 29935 ' within slice by '+ slicen, vvu) 29936 onewvars[statn] = newvar 29937 onewnc.sync() 29938 29939 vout = None 29940 voutt = None 29941 varvt = None 29942 29943 # Checking for size... 29944 Nvdims = len(vshape) 29945 newvarslc = {} 29946 varslc = {} 29947 if Nvdims == 4: 29948 vSIZE = np.prod(ovar.shape[:])*8. 29949 if vSIZE > gen.oneGB*3.: 29950 print ' ' + infmsg 29951 print ' variable size: ', vSIZE / gen.oneGB,' larger than 3GB !!' 29952 print ' splitting time evolution to compute' 29953 vHSIZE = np.prod(ovar.shape[1:3])*8. 29954 print ' var. horizontal size:', vHSIZE, 'dimt:', ovar.shape[0] 29955 tsteps = gen.oneGB*3. / vHSIZE 29956 tslices = range(0,ovar.shape[0],tsteps) 29957 print ' time-slices:', tslices 29958 for itt in tslcices[1,len(tslices)]: 29959 iit = tslices[itt-1] 29960 eet = tslices[itt] 29961 varslc[itt-1] = [slice(iit,eet), slice(0,vshape[1]), \ 29962 slice(0,vbshape[2]), slice(0,vbshape[3])] 29963 newvarslc[itt-1] = [slice(iit,eet)] + newvarslice[1:4] 29964 else: 29965 tslices = range(0,ovar.shape[0]) 29966 varslc[0] = [slice(0,vshape[0]), slice(0,vshape[1]), \ 29967 slice(0,vshape[2]), slice(0,vshape[3])] 29968 newvarslc[0] = newvarslice 29969 elif Nvdims == 3: 29970 vSIZE = np.prod(ovar.shape[:])*8. 29971 if vSIZE > gen.oneGB*3.: 29972 print ' ' + infmsg 29973 print ' variable size: ', vSIZE / gen.oneGB,' larger than 3GB !!' 29974 print ' splitting time evolution to compute' 29975 vHSIZE = np.prod(ovar.shape[1:3])*8. 29976 print ' var. horizontal size:', vHSIZE, 'dimt:', ovar.shape[0] 29977 tsteps = gen.oneGB*3. / vHSIZE 29978 tslices = range(0,ovar.shape[0],tsteps) 29979 print ' time-slices:', tslices 29980 for itt in tslcices[1,len(tslices)]: 29981 iit = tslices[itt-1] 29982 eet = tslices[itt] 29983 varslc[itt-1] = [slice(iit,eet), slice(0,vshape[1]), \ 29984 slice(0,vbshape[2])] 29985 newvarslc[itt-1] = [slice(iit,eet)] + newvarslice[1:3] 29986 else: 29987 tslices = range(0,ovar.shape[0]) 29988 varslc[0] = [slice(0,vshape[0]), slice(0,vshape[1]), \ 29989 slice(0,vshape[2])] 29990 newvarslc[0] = newvarslice 29991 else: 29992 slicevv = [] 29993 for iid in range(Nvdims): 29994 slicevv.append(slice(0,vshape[0])) 29995 varslc[0] = slicevv 29996 newvarslc[0] = newvarslice 29997 29998 if Nvdims == 4: 29999 d0 = ovar.shape[0] 30000 d1 = ovar.shape[1] 30001 d2 = ovar.shape[2] 30002 d3 = ovar.shape[3] 30003 elif Nvdims == 3: 30004 d0 = ovar.shape[0] 30005 d1 = ovar.shape[1] 30006 d2 = ovar.shape[2] 30007 elif Nvdims == 2: 30008 d0 = ovar.shape[0] 30009 d1 = ovar.shape[1] 30010 elif Nvdims == 1: 30011 d0 = ovar.shape[0] 30012 if slicespacedim.count(vdimns[0]) != 1: 30013 print errormsg 30014 print ' ' + fname + ": there is no way to be able to compute " + \ 30015 "sliced statistics for variable '" + varn + "' because it " + \ 30016 "does not have any horizontal spatial dimension:", slicespacedim, \ 30017 "!!" 30018 quit(-1) 30019 ind = slicespacedim.index(vdimns[0]) 30020 else: 30021 print errormsg 30022 print ' ' + fname + ": rank ", Nvdims, " of variable '" + varn + \ 30023 "' not ready !!" 30024 quit(-1) 30025 30026 print ' computing statistics ...' 30027 30028 for itt in varslc.keys(): 30029 nslcv = newvarslc[itt] 30030 slcv = varslc[itt] 30031 varv = ovar[tuple(slcv)] 30032 30033 if Nvdims == 4: 30034 d0 = varv.shape[0] 30035 d1 = varv.shape[1] 30036 d2 = varv.shape[2] 30037 d3 = varv.shape[3] 30038 elif Nvdims == 3: 30039 d0 = varv.shape[0] 30040 d1 = varv.shape[1] 30041 d2 = varv.shape[2] 30042 elif Nvdims == 2: 30043 d0 = varv.shape[0] 30044 d1 = varv.shape[1] 30045 elif Nvdims == 1: 30046 d0 = varv.shape[0] 30047 if slicespacedim.count(vdimns[0]) != 1: 30048 print errormsg 30049 print ' ' + fname + ": there is no way to be able to compute " + \ 30050 "sliced statistics for variable '" + varn + "' because it " + \ 30051 "does not have any horizontal spatial dimension:", \ 30052 slicespacedim, "!!" 30053 quit(-1) 30054 ind = slicespacedim.index(vdimns[0]) 30055 else: 30056 print errormsg 30057 print ' ' + fname + ": rank ", Nvdims, " of variable '" + varn + \ 30058 "' not ready !!" 30059 quit(-1) 30060 30061 varvt = varv.transpose() 30062 if Nvdims == 3 and len(sN.shape) == 4: 30063 voutt=fsci.module_scientific.multi_spaceweightstats_in3drk3_slc3v4( \ 30064 varin=varvt, ngridsin=sNt, gridsin=sint, percentages=spt, \ 30065 di1=d2, di2=d1, di3=d0, ds1=ssh[3], ds2=ssh[2], ds3=ssh[1], \ 30066 ds4=ssh[0], maxngridsin=sin.shape[1]) 30067 elif Nvdims == 4 and len(sN.shape) == 3: 30068 voutt=fsci.module_scientific.multi_spaceweightstats_in4drk3_4_slc3v3( \ 30069 varin=varvt, ngridsin=sNt, gridsin=sint, percentages=spt, \ 30070 di1=d3, di2=d2, di3=d1, di4=d0, ds1=ssh[2], ds2=ssh[1], ds3=ssh[0], \ 30071 maxngridsin=sin.shape[1]) 30072 elif Nvdims == 3 and len(sN.shape) == 3: 30073 voutt=fsci.module_scientific.multi_spaceweightstats_in3drk3_slc3v3( \ 30074 varin=varvt, ngridsin=sNt, gridsin=sint, percentages=spt, \ 30075 di1=d2, di2=d1, di3=d0, ds1=ssh[2], ds2=ssh[1], ds3=ssh[0], \ 30076 maxngridsin=sin.shape[1]) 30077 elif Nvdims == 2 and len(sN.shape) == 3: 30078 voutt=fsci.module_scientific.multi_spaceweightstats_in2drkno_slc3v3( \ 30079 varin=varvt, ngridsin=sNt, gridsin=sint, percentages=spt, \ 30080 di1=d1, di2=d0, ds1=ssh[2], ds2=ssh[1], ds3=ssh[0], \ 30081 maxngridsin=sin.shape[1]) 30082 elif Nvdims == 1 and len(sN.shape) == 3: 30083 voutt=fsci.module_scientific.multi_spaceweightstats_in1drkno_slc3v3( \ 30084 varin=varvt, idv=ind, ngridsin=sNt, gridsin=sint, percentages=spt, \ 30085 di1=d0, ds1=ssh[2], ds2=ssh[1], ds3=ssh[0], maxngridsin=sin.shape[1]) 30086 else: 30087 print errormsg 30088 print ' ' + fname + ": variable rank:", Nvdims, 'combined with', \ 30089 ' slice rank:', len(sN.shape), 'not ready!!' 30090 print ' available ones _______' 30091 print ' var_rank: 3 slice_rank: 4' 30092 print ' var_rank: 4 slice_rank: 3' 30093 print ' var_rank: 3 slice_rank: 3' 30094 print ' var_rank: 2 slice_rank: 3' 30095 print ' var_rank: 1 slice_rank: 3' 30096 quit(-1) 30097 30098 vout = voutt.transpose() 30099 ist = 0 30100 for statn in statns: 30101 newvar = onewvars[statn] 30102 rightvals = np.where(vout[6] == 0, gen.fillValueF, vout[ist]) 30103 newvar[tuple(nslcv)] = rightvals 30104 onewnc.sync() 30105 ist = ist + 1 30106 onewnc.sync() 30107 30108 # Add global attributes 30109 add_global_PyNCplot(onewnc, 'nc_var_tools', fname, '1.0') 30110 add_globattrs(onc,onewnc,'all') 30111 onewnc.sync() 30112 onc.close() 30113 onewnc.close() 30114 print fname + ": successfull written of file '" + fname + ".nc' !!" 30115 30116 return 30117 30118 #values='compute_slices_stats_areaweighted.nc:XLAT_M-HGT_M-rangefaces' 30119 #usefile_compute_slices_stats_areaweighted(values, '/media/lluis/ExtDiskC_ext4/bkup/llamp/estudios/dominios/SA5k/geo_em.d01.nc', 'LANDUSEF') 30120 29726 30121 #quit() 29727 30122
Note: See TracChangeset
for help on using the changeset viewer.