Changeset 2168 in lmdz_wrf for trunk/tools
- Timestamp:
- Oct 5, 2018, 10:19:51 PM (7 years ago)
- Location:
- trunk/tools
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/tools/nc_var.py
r2165 r2168 61 61 ## e.g. # nc_var.py -o merge_files -S 'plev|plev,time|time:merged.nc' -f 'ncobs/AliceSprings/snd_94326_198201-198201.nc,ncobs/AliceSprings/snd_94326_198202-198202.nc' -v 'plev,time' 62 62 ## e.g. # nc_var.py -o temporal_stats -S 'Time:WRFtime:day@1@min,LTday@-3@1@min:bottom_top@ZNU,south_north@XLAT,west_east@XLONG' -f wrfout_d01_1995-01-01_00:00:00 -v T2,Q2 63 ## e.g. # nc_var.py -o retrieve_stations -f wrfout_d01_1995-01-01_00:00:00 -S 'tmin_percentiles.nc:stname:None:stlon:stlat:None:nearest:west_east:XLONG:south_north:XLAT:HGT:Time:WRFtime' -v T2,QVAPOR 63 64 64 65 from optparse import OptionParser … … 158 159 # pinterp: Function to vertically interpolate using subroutines from the p_interp.F90 NCAR program 159 160 # remapnn: Function to remap to the nearest neightbor a variable using projection from another file 161 # retrieve_stations: Function to retrieve temporal values at given stations provided by a secondary netcdf 160 162 # seasmean: Function to compute the seasonal mean of a variable 161 163 # sellonlatbox: Function to select a lotlan box from a data-set … … 219 221 'netcdf_fold_concatenation_HMT', 'reproject', 'Partialmap_Entiremap', \ 220 222 'Partialmap_EntiremapFor', 'Partialmap_EntiremapForExact', \ 221 'pinterp', 'reconstruct_matrix_from_vector', 'remapnn', 'rm_FillValue', \ 223 'pinterp', 'reconstruct_matrix_from_vector', 'remapnn', 'retrieve_stations', \ 224 'rm_FillValue', \ 222 225 'seasmean', 'sellonlatbox', 'sellonlatlevbox', 'selvar', 'setvar_asciivalues', \ 223 226 'setvar_nc', 'sorttimesmat', 'spacemean', 'SpatialWeightedMean', \ … … 470 473 elif oper == 'reproject': 471 474 ncvar.reproject(opts.values, opts.ncfile, opts.varname) 475 elif oper == 'retrieve_stations': 476 ncvar.retrieve_stations(opts.values, opts.ncfile, opts.varname) 472 477 elif oper == 'rm_FillValue': 473 478 ncvar.rm_FillValue(opts.values, opts.ncfile, opts.varname) -
trunk/tools/nc_var_tools.py
r2167 r2168 112 112 # maskvar: Function to mask a variable using a mask. It is assumed that mask[...,dimM,dimJ,dimK] and var[...,dimM,dimJ,dimK] share the last dimensions 113 113 # merge_files: Function to merge variables from two files 114 # mindist: Function to pro ivde the minimum distance toa pair of lon,lat114 # mindist: Function to provide the minimum distance toa pair of lon,lat 115 115 # ModelChar: Class object to determine major characterisitcs of a given model output 116 116 # model_characteristics: Functino to provide major characterisitcs of a given model output … … 135 135 # remapnn_old: Function to remap to the nearest neightbor a variable using projection from another fil 136 136 # reproject: Function to reproject values to another one 137 # retrieve_stations: Function to retrieve temporal values at given stations provided by a secondary netcdf 137 138 # rm_FillValue: Operation to remove the _FillValue from a variable inside a netCDF file 138 139 # seasmean: Function to compute the seasonal mean of a variable … … 25381 25382 stats = [] 25382 25383 for timest in timestatsS: 25384 print 'Lluis timest:', timest, 'split:', timest.split('@') 25383 25385 timestatsv = [] 25384 25386 period = timest.split('@')[0] … … 25512 25514 25513 25515 # Adding period dimension and variables 25514 newdim = onewnc.createDimension(periodn+'_time', Ntslc) 25515 newvart = onewnc.createVariable(periodn+'_time', 'f8', \ 25516 (periodn+'_time')) 25517 basicvardef(newvart, periodn+'_time', 'time for ' + periodn, timeu) 25518 newvart.setncattr('calendar', timec) 25519 newvart.setncattr('bounds', periodn+'_time_bounds') 25520 newvarb = onewnc.createVariable(periodn+'_time_bounds', 'f8', \ 25521 (periodn+'_time', 'bounds')) 25522 basicvardef(newvarb, periodn+'_time_bounds', 'time boundaries for '+ periodn,\ 25523 timeu) 25524 newvarb.setncattr('calendar', timec) 25525 for it in range(Ntslc): 25526 timeslcev = tslcs[it] 25527 islc = timevc[timeslcev[0]] 25528 eslc = timevc[timeslcev[1]] 25529 25530 newvart[it] = (eslc + islc) / 2. 25531 newvarb[it,:] = [islc, eslc] 25532 onewnc.sync() 25516 if not gen.searchInlist(onewnc.dimensions, periodn+'_time'): 25517 newdim = onewnc.createDimension(periodn+'_time', Ntslc) 25518 newvart = onewnc.createVariable(periodn+'_time', 'f8', \ 25519 (periodn+'_time')) 25520 basicvardef(newvart, periodn+'_time', 'time for ' + periodn, timeu) 25521 newvart.setncattr('calendar', timec) 25522 newvart.setncattr('bounds', periodn+'_time_bounds') 25523 newvarb = onewnc.createVariable(periodn+'_time_bounds', 'f8', \ 25524 (periodn+'_time', 'bounds')) 25525 basicvardef(newvarb, periodn+'_time_bounds', 'time boundaries for '+ \ 25526 periodn, timeu) 25527 newvarb.setncattr('calendar', timec) 25528 for it in range(Ntslc): 25529 timeslcev = tslcs[it] 25530 islc = timevc[timeslcev[0]] 25531 eslc = timevc[timeslcev[1]] 25532 25533 newvart[it] = (eslc + islc) / 2. 25534 newvarb[it,:] = [islc, eslc] 25535 onewnc.sync() 25533 25536 25534 25537 for varn in varnames: … … 25576 25579 newvarn = varn+str(amount)+periodn+statn 25577 25580 25578 newvar = onewnc.createVariable(newvarn, 'f', tuple(dimntstat),\25581 newvarv = onewnc.createVariable(newvarn, 'f', tuple(dimntstat), \ 25579 25582 fill_value=gen.fillValueR) 25580 25583 varunits = get_varunits(ovar) … … 25584 25587 CFvarattr[4].replace('|',' ') 25585 25588 add_varattrs(onc,onewnc,[varn],[newvarn]) 25586 basicvardef(newvar, newvarn, Lname, varunits) 25587 newvar.setncattr('cell_method', 'time: ' + Lstatn[statn]) 25588 newvar.setncattr('bounds', periodn+'_time_bounds') 25589 if periodn == 'LTday': set_attributek(newvar, 'UTCshift', UTCshift, 'I') 25590 25591 tstat = np.ones(tuple(shapetstat), dtype=np.float)*gen.fillValueR 25589 basicvardef(newvarv, newvarn, Lname, varunits) 25590 newvarv.setncattr('cell_method', 'time: ' + Lstatn[statn]) 25591 newvarv.setncattr('bounds', periodn+'_time_bounds') 25592 if periodn == 'LTday': set_attributek(newvarv, 'UTCshift', UTCshift, 'I') 25593 25594 newvarN = onewnc.createVariable(newvarn+'_Nsteps', 'i', (periodn+'_time')) 25595 basicvardef(newvarN, newvarn+'_Nsteps', 'Number of time steps used to ' +\ 25596 'compute ' + Lname, '1') 25597 25598 #tstat = np.ones(tuple(shapetstat), dtype=np.float)*gen.fillValueR 25592 25599 25593 25600 # Looping into the period 25594 25601 for islc in range(Ntslc): 25595 25602 timeslcv = tslcs[islc] 25603 newvarN[islc] = timeslcv[1]-timeslcv[0]+1 25596 25604 25597 25605 timeslc = [] … … 25611 25619 tvals = ovar[tuple(timeslc)] 25612 25620 if statn == 'min': 25613 tstat[tuple(tstatslc)] = np.min(tvals, axis=itdim)25621 newvarv[tuple(tstatslc)] = np.min(tvals, axis=itdim) 25614 25622 elif statn == 'max': 25615 tstat[tuple(tstatslc)] = np.max(tvals, axis=itdim)25623 newvarv[tuple(tstatslc)] = np.max(tvals, axis=itdim) 25616 25624 elif statn == 'mean': 25617 tstat[tuple(tstatslc)] = np.mean(tvals, axis=itdim)25625 newvarv[tuple(tstatslc)] = np.mean(tvals, axis=itdim) 25618 25626 elif statn == 'mean2': 25619 tstat[tuple(tstatslc)] = np.mean(tvals**2, axis=itdim)25627 newvarv[tuple(tstatslc)] = np.mean(tvals**2, axis=itdim) 25620 25628 elif statn == 'std': 25621 tstat[tuple(tstatslc)] = np.std(tvals, axis=itdim)25629 newvarv[tuple(tstatslc)] = np.std(tvals, axis=itdim) 25622 25630 else: 25623 25631 print errormsg … … 25627 25635 print ' available ones:', statnor 25628 25636 quit(-1) 25629 25630 newvar[:] = tstat 25637 onewnc.sync() 25638 25639 #newvar[:] = tstat 25631 25640 onewnc.sync() 25632 25641 … … 25646 25655 #temporal_stats(vals, '/home/lluis/PY/wrfout_d01_1995-01-01_00:00:00', 'T2') 25647 25656 25648 #quit() 25657 def retrieve_stations(values, ncfile, variable): 25658 """ Function to retrieve temporal values at given stations provided by a 25659 secondary netcdf 25660 values=[stnetcdf]:[stvnamen]:[stvidn]:[stvlonn]:[stvlatn]: 25661 [stvheight]:[method]:[datadlonn]:[datavlonn]:[datadlatn]:[datavlatn]: 25662 [datavheightn]:[datadtimen]:[datavtimen] 25663 [stnetcdf]: name of the file with the stations 25664 [stvnamen]: name of the variable in [stnetcdf] with the names of the stations 25665 (None for inexstent) 25666 [stvidn]: name of the variable in [stnetcdf] with the ids of the stations 25667 (None for inexstent) 25668 [stvlonn]: name of the variable in [stnetcdf] with the longitudes of the 25669 stations (None for inexstent) 25670 [stvlatn]: name of the variable in [stnetcdf] with the latitudes of the 25671 stations (None for inexstent) 25672 [stvheightn]: name of the variable in [stnetcdf] with the heights of the 25673 stations (None for inexstent) 25674 [method]: methodology to use to retrieve the values 25675 'nearest': nearest grid point 25676 'mean': mean of the closest 4 grid points 25677 'dist': inverse distance weighted mean of the closest 4 grid points 25678 [datadlonn]: name of dimension in datafile for the lon axis 25679 [datavlonn]: name of variable in datafile with the longitudes 25680 [datadlatn]: name of dimension in datafile for the lat axis 25681 [datavlatn]: name of variable in datafile with the latitudes 25682 [datavheightn]: name of variable in datafile with the heighs (None for 25683 inexistent) 25684 [datadtimen]: name of dimension in datafile for the time axis 25685 [datavtimen]: name of variable in datafile for the time values ('WRFtime' 25686 for WRF times) 25687 ncfile= file from which retrieve values of stations 25688 variable= ',' list of values to retrieve values ('all' for all variables) 25689 """ 25690 fname = 'retrieve_stations' 25691 availmethod = ['nearest', 'mean', 'dist'] 25692 methoddesc = {'nearest': 'nearest grid point', 'mean': 'mean of the closest 4 '+ \ 25693 'grid points', 'dist': 'inverse distance weighted mean of the closest 4 ' + \ 25694 'grid points'} 25695 25696 if values == 'h': 25697 print fname + '_____________________________________________________________' 25698 print retrieve_stations.__doc__ 25699 quit() 25700 25701 expectargs = '[stnetcdf]:[stvnamen]:[stvidn]:[stvlonn]:[stvlatn]:[stvheightn]:'+ \ 25702 '[method]:[datadlonn]:[datavlonn]:[datadlatn]:[datavlatn]:[datavheightn]:' + \ 25703 '[datadtimen]:[datavtimen]' 25704 gen.check_arguments(fname, values, expectargs, ':') 25705 25706 stnetcdf = values.split(':')[0] 25707 stvnamen = values.split(':')[1] 25708 stvidn = values.split(':')[2] 25709 stvlonn = values.split(':')[3] 25710 stvlatn = values.split(':')[4] 25711 stvheightn = values.split(':')[5] 25712 method = values.split(':')[6] 25713 datadlonn = values.split(':')[7] 25714 datavlonn = values.split(':')[8] 25715 datadlatn = values.split(':')[9] 25716 datavlatn = values.split(':')[10] 25717 datavheightn = values.split(':')[11] 25718 datadtimen = values.split(':')[12] 25719 datavtimen = values.split(':')[13] 25720 25721 # Retrieving station information 25722 25723 # Getting variables 25724 filestinf = {} 25725 stinf = [] 25726 if stvnamen != 'None': 25727 filestinf['station_name'] = stvnamen 25728 stinf.append('station_name') 25729 else: 25730 filestinf['station_name'] = None 25731 if stvidn != 'None': 25732 filestinf['station_id'] = stvidn 25733 stinf.append('station_id') 25734 else: 25735 filestinf['station_id'] = None 25736 if stvlonn != 'None': 25737 filestinf['station_lon'] = stvlonn 25738 stinf.append('station_lon') 25739 else: 25740 print errormsg 25741 print ' ' + fname + ": at least a variable with longitudes of the " + \ 25742 "stations is required !!" 25743 quit(-1) 25744 if stvlatn != 'None': 25745 filestinf['station_lat'] = stvlatn 25746 stinf.append('station_lat') 25747 else: 25748 print errormsg 25749 print ' ' + fname + ": at least a variable with latitudes of the " + \ 25750 "stations is required !!" 25751 quit(-1) 25752 if stvheightn != 'None': 25753 filestinf['station_height'] = stvheightn 25754 stinf.append('station_height') 25755 else: 25756 filestinf['station_height'] = None 25757 25758 # Getting values 25759 if not os.path.isfile(stnetcdf): 25760 print errormsg 25761 print ' ' + fname + ": file with stations information '" + stnetcdf + \ 25762 "' does not exist !!" 25763 quit(-1) 25764 ostnc = NetCDFFile(stnetcdf, 'r') 25765 25766 stationsinf = {} 25767 for sti in stinf: 25768 varn = filestinf[sti] 25769 if not ostnc.variables.has_key(varn): 25770 print errormsg 25771 print ' ' + fname + ": stations does not have variable '" + varn + \ 25772 "' for '" + sti + "' !!" 25773 varns = ostnc.variables.keys() 25774 varns.sort() 25775 print ' available ones:', varns 25776 quit(-1) 25777 25778 ovar = ostnc.variables[varn] 25779 if sti == 'station_name': 25780 stvals = get_str_nc(ovar, ovar.shape[1]) 25781 stnames = [] 25782 for ist in range(len(stvals)): 25783 stnames.append(''.join(stvals[ist])) 25784 stnames.remove('') 25785 stationsinf[sti] = stnames 25786 else: 25787 stationsinf[sti] = ovar[:] 25788 25789 #print infmsg 25790 #print ' ' + fname + ': stations _______' 25791 #gen.printing_dictionary(stationsinf) 25792 25793 # Getting stations points 25794 donc = NetCDFFile(ncfile, 'r') 25795 25796 if not donc.variables.has_key(datavlonn): 25797 print errormsg 25798 print ' ' + fname + ": data file does not have '" + datavlonn + "' for " + \ 25799 "longitudes !!" 25800 varns = donc.variables.keys() 25801 varns.sort() 25802 print ' available ones:', varns 25803 quit(-1) 25804 25805 if not donc.variables.has_key(datavlatn): 25806 print errormsg 25807 print ' ' + fname + ": data file does not have '" + datavlatn + "' for " + \ 25808 "latitudes !!" 25809 varns = donc.variables.keys() 25810 varns.sort() 25811 print ' available ones:', varns 25812 quit(-1) 25813 25814 if datavheightn != 'None' and not donc.variables.has_key(datavheightn): 25815 print errormsg 25816 print ' ' + fname + ": data file does not have '" + datavheightn + "' for "+\ 25817 "Heights !!" 25818 varns = donc.variables.keys() 25819 varns.sort() 25820 print ' available ones:', varns 25821 quit(-1) 25822 25823 if datavtimen != 'WRFtime' and not donc.variables.has_key(datavtimen): 25824 print errormsg 25825 print ' ' + fname + ": data file does not have '" + datavtimen + "' for " + \ 25826 "times !!" 25827 varns = donc.variables.keys() 25828 varns.sort() 25829 print ' available ones:', varns 25830 quit(-1) 25831 25832 olon = donc.variables[datavlonn] 25833 lon0 = olon[:] 25834 olat = donc.variables[datavlatn] 25835 lat0 = olat[:] 25836 oheight = donc.variables[datavheightn] 25837 height0 = oheight[:] 25838 25839 lon, lat = gen.lonlat2D(lon0, lat0) 25840 ddimx = lon.shape[1] 25841 ddimy = lon.shape[0] 25842 25843 if datavheightn != 'None': 25844 if len(height0.shape) == 3: height = height0[0,:,:] 25845 elif len(height0.shape) == 2: height = height0[:] 25846 else: 25847 print errormsg 25848 print ' ' + fname + ": height variable has not 2D, 3D shape:", height0.shape 25849 quit(-1) 25850 else: 25851 height = None 25852 25853 if datavtimen != 'WRFtime': 25854 otime = donc.variables[datavtimen] 25855 timev = otime[:] 25856 timeu = time.units 25857 if gen.searchInlist(otime.ncattrs(), 'calendar'): 25858 timec = time.calendar 25859 else: 25860 print warnsmg 25861 print ' ' + fname + ": variable time without calendar attribute !" 25862 print " assuming 'standard/greogorian'" 25863 timec = 'standard' 25864 else: 25865 otimev = donc.variables['Times'] 25866 timewrfv = otimev[:] 25867 timev, timeu = compute_WRFtime(timewrfv, refdate='19491201000000', \ 25868 tunitsval='minutes') 25869 timec = 'standard' 25870 25871 if variable == 'all': 25872 varns = donc.variables.keys() 25873 # Removing that variables without lon,lat dimensoins 25874 for vn in varns: 25875 ovn = donc.variables[vn] 25876 vdims = ovn.dimensions 25877 if not gen.searchInlist(vdims, datadlonn) or not \ 25878 gen.searchInlist(vdims, datadlonn): varns.remove(vn) 25879 else: 25880 varns = gen.str_list(variable, ',') 25881 25882 stns = stationsinf['station_name'] 25883 stlons = stationsinf['station_lon'] 25884 stlats = stationsinf['station_lat'] 25885 25886 Nstations = len(stns) 25887 print infmsg 25888 print ' ' + fname + ': to process', Nstations, 'stations !!' 25889 25890 # File creation 25891 ## 25892 ofile = fname + '.nc' 25893 onewnc = NetCDFFile(ofile, 'w') 25894 25895 # Creation of dimensions 25896 newdim = onewnc.createDimension('Lstring',256) 25897 newdim = onewnc.createDimension(datadtimen,None) 25898 newdim = onewnc.createDimension('station',Nstations) 25899 newdim = onewnc.createDimension('time',None) 25900 25901 # Create variable-dimensions 25902 newvar = onewnc.createVariable('station_name','c', ('station', 'Lstring')) 25903 writing_str_nc(newvar, stns, 256) 25904 basicvardef(newvar, 'station_name', 'Name of the station', '-') 25905 25906 newvar = onewnc.createVariable('time','f8', ('time')) 25907 newvar[:] = timev 25908 basicvardef(newvar, 'time', 'Time', timeu) 25909 newvar.setncattr('calendar', timec) 25910 25911 newvari = onewnc.createVariable('station_i','i', ('station')) 25912 basicvardef(newvari, 'station_i', 'x-axis index of the station in the grid', '-') 25913 25914 newvarj = onewnc.createVariable('station_j','i', ('station')) 25915 basicvardef(newvarj, 'station_j', 'y-axis index of the station in the grid', '-') 25916 25917 newvarlon = onewnc.createVariable('station_lon','f', ('station')) 25918 basicvardef(newvarlon, 'station_lon', 'Longitude of the station in the grid', \ 25919 'degrees_east') 25920 25921 newvarlat = onewnc.createVariable('station_lat','f', ('station')) 25922 basicvardef(newvarlat, 'station_lat', 'Latitude of the station in the grid', \ 25923 'degrees_north') 25924 25925 newvardist = onewnc.createVariable('station_dist','f', ('station')) 25926 basicvardef(newvardist, 'station_dist', 'Distance of the station in the grid', \ 25927 'degrees') 25928 25929 if datavheightn != 'None': 25930 newvarhgt = onewnc.createVariable('station_hight','f', ('station')) 25931 basicvardef(newvarhgt, 'station_height', 'Height of the station in the grid',\ 25932 'm') 25933 25934 if method == 'nearest': 25935 newdim = onewnc.createDimension('Nweight', 1) 25936 else: 25937 newdim = onewnc.createDimension('Nweight', 4) 25938 newvarwght = onewnc.createVariable('station_weights','f',('station','Nweight')) 25939 basicvardef(newvarwght, 'station_weights', 'Weights to retrieve station ' + \ 25940 'values from grid', '1') 25941 newvarwght.setncattr('method',method) 25942 25943 stdataij = {} 25944 stslice = {} 25945 stweight = {} 25946 25947 if method == 'dist': stdist = {} 25948 25949 pointdatavals = datavlonn+':'+datavlatn+':'+datadlonn+'|-1,'+datadlatn+'|-1,' + \ 25950 datadtimen+'|0' 25951 for ist in range(Nstations): 25952 25953 ijst, dst = get_point(pointdatavals, ncfile, str(stlons[ist])+','+ \ 25954 str(stlats[ist])) 25955 stdataij[stns[ist]] = [ijst, dst] 25956 dlon = lon[ijst[0],ijst[1]] 25957 dlat = lat[ijst[0],ijst[1]] 25958 25959 # Writing in file station values from grid 25960 newvari[ist] = ijst[1] 25961 newvarj[ist] = ijst[0] 25962 newvarlon[ist] = dlon 25963 newvarlat[ist] = dlat 25964 newvardist[ist] = dst 25965 if height is not None: newvarhgt[ist] = height[ijst[0],ijst[1]] 25966 onewnc.sync() 25967 25968 ptvslice = [] 25969 if method == 'nearest': 25970 ptvslice = ijst + [] 25971 weights = np.ones((1), dtype=np.float) 25972 elif method == 'mean' or method == 'dist': 25973 ddx = lon[ijst[0],ijst[1]+1] - dlon 25974 ddy = lat[ijst[0]+1,ijst[1]] - dlat 25975 signx = np.abs(ddx)/ddx 25976 signy = np.abs(ddy)/ddy 25977 25978 if stlons[ist] >= dlon: incx = 1*signx 25979 else: incx = -1*signx 25980 if stlats[ist] >= dlat: incy = 1*signy 25981 else: incy = -1*signy 25982 25983 # Avoiding outside shape 25984 xij = np.min([ijst[1]+incx, ddimx-1]) 25985 yij = np.min([ijst[0]+incy, ddimy-1]) 25986 xij = int(np.max([0, xij])) 25987 yij = int(np.max([0, yij])) 25988 25989 ptvslice.append(ijst) 25990 ptvslice.append([ijst[0],xij]) 25991 ptvslice.append([yij,ijst[1]]) 25992 ptvslice.append([yij,xij]) 25993 25994 weights = np.ones((4), dtype=np.float) 25995 if method == 'dist': 25996 dists = np.zeros((4), dtype=np.float) 25997 dists[0] = dst 25998 for ineig in range(1,4): 25999 ij = ptvslice[ineig] 26000 distv = (lon[ij[1],ij[0]]-stlons[ist])**2 + \ 26001 (lat[ij[1],ij[0]]-stlats[ist])**2 26002 dists[ineig] = np.sqrt(distv) 26003 weights = 1./dists 26004 stdist[stns[ist]] = dists 26005 weights = weights/np.sum(weights) 26006 else: 26007 print errormsg 26008 print ' ' + fname + ": method '" + + "' not ready !!" 26009 print ' available ones:', availmethod 26010 quit(-1) 26011 stslice[stns[ist]] = ptvslice 26012 stweight[stns[ist]] = weights 26013 newvarwght[ist,:] = weights 26014 26015 for ist in range(Nstations): 26016 ptvslice = stslice[stns[ist]] 26017 26018 if type(ptvslice[0]) == type(np.int64(1)): Nstpts = 1 26019 else: Nstpts = len(ptvslice) 26020 wghts = stweight[stns[ist]] 26021 26022 for varn in varns: 26023 if not donc.variables.has_key(varn): 26024 print errormsg 26025 print ' ' + fname + ": data file does not have variable '" + varn + \ 26026 "' !!" 26027 fvarns = donc.variables.keys() 26028 fvarns.sort() 26029 print ' available ones:', varns 26030 quit(-1) 26031 26032 if ist == 0: 26033 print varn + " ..." 26034 26035 ovarn = donc.variables[varn] 26036 26037 vslice = [] 26038 idd = 0 26039 ilon = -1 26040 ilat = -1 26041 vstshape = [Nstpts] 26042 vstslice = [Nstpts] 26043 vardimns = ['station'] 26044 stgridvals = [Nstations] 26045 for dn in ovarn.dimensions: 26046 if dn == datadlonn: 26047 vslice.append(0) 26048 ilon = idd 26049 elif dn == datadlatn: 26050 vslice.append(0) 26051 ilat = idd 26052 else: 26053 dshape = ovarn.shape[idd] 26054 vslice.append(slice(0,dshape)) 26055 vstshape.append(dshape) 26056 vstslice.append(slice(0,dshape)) 26057 vardimns.append(ovarn.dimensions[idd]) 26058 if ist == 0 and not gen.searchInlist(onewnc.dimensions, dn): 26059 newdim=onewnc.createDimension(dn, dshape) 26060 stgridvals.append(slice(0,dshape)) 26061 idd = idd + 1 26062 26063 if ist == 0: 26064 varattrs = ovarn.ncattrs() 26065 if gen.searchInlist(varattrs, '_fillValue'): 26066 fillval = ovarn.getncattr('_fillValue') 26067 newvar= onewnc.createVariable(varn, ovarn.dtype, tuple(vardimns),\ 26068 fill_value=fillval) 26069 varatttrs.remove('_fillValue') 26070 else: 26071 newvar= onewnc.createVariable(varn, ovarn.dtype, tuple(vardimns)) 26072 for attrn in varattrs: 26073 attrv = ovarn.getncattr(attrn) 26074 newvar.setncattr(attrn,attrv) 26075 26076 onewnc.sync() 26077 else: 26078 newvar = onewnc.variables[varn] 26079 26080 varvalues = np.zeros((vstshape), dtype=ovar.dtype) 26081 vwghts = np.ones((vstshape), dtype=np.float) 26082 if Nstpts > 2: 26083 for istpts in range(Nstpts): 26084 vstslice[0] = istpts 26085 istp = ptvslice[istpts] 26086 vslice[ilat] = istp[0] 26087 vslice[ilon] = istp[1] 26088 26089 varvalues[tuple(vstslice)] = ovarn[tuple(vslice)] 26090 vwghts[tuple(vstslice)] = wghts[istpts] 26091 else: 26092 vslice[ilat] = ptvslice[0] 26093 vslice[ilon] = ptvslice[1] 26094 varvalues[0] = ovarn[tuple(vslice)] 26095 26096 # Shapping weights 26097 vwghts = np.ones(varvalues.shape, dtype=np.float) 26098 26099 stvarv = np.sum(varvalues*vwghts, axis=0) 26100 26101 stgridvals[0] = ist 26102 if ist == 1: 26103 print 'Lluis shapes ____' 26104 print 'newvar:', newvar.shape 26105 print 'vslice:', vslice 26106 print 'vstslice:', vstslice 26107 print 'stgridvals:', stgridvals 26108 print 'varvalues:', varvalues.shape 26109 print 'weights:', vwghts.shape 26110 print 'stvarv:', stvarv.shape 26111 vvv = varvalues*vwghts 26112 print ' Lluis shape prod:', vvv.shape 26113 26114 newvar[tuple(stgridvals)] = stvarv[:] 26115 onewnc.sync() 26116 26117 #quit() 26118 26119 # Adding PyNCplot 26120 add_global_PyNCplot(onewnc, 'nc_var_tools', fname, '1.0') 26121 onewnc.setncattr('description', 'Values at different stations from a grid file') 26122 onewnc.setncattr('stations_file', stnetcdf) 26123 onewnc.setncattr('grid_file', ncfile) 26124 onewnc.setncattr('method', method) 26125 onewnc.setncattr('method_description', methoddesc[method]) 26126 onewnc.sync() 26127 26128 add_globattrs(ostnc, onewnc, 'all') 26129 onewnc.sync() 26130 26131 ostnc.close() 26132 onewnc.close() 26133 print fname + ": successfull creation of file '" + ofile + "' !!" 26134 26135 return 26136 26137 #values = '/home/lluis/estudios/WRFsensSFC/dyn-stat/stat/tmin_percentiles.nc:stname:None:stlon:stlat:None:dist:west_east:XLONG:south_north:XLAT:HGT:Time:WRFtime' 26138 26139 #retrieve_stations(values, '/home/lluis/PY/wrfout_d01_1995-01-01_00:00:00', 'T2') 26140 26141 #quit()
Note: See TracChangeset
for help on using the changeset viewer.