Changeset 667 in lmdz_wrf for trunk/tools/nc_var_tools.py
- Timestamp:
- Jan 14, 2016, 10:45:54 AM (9 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/tools/nc_var_tools.py
r663 r667 13 13 fillValueC = '-' 14 14 fillValueI = -99999 15 fillValueI16 = -99999 16 fillValueF64 = 1.e20 17 fillValueI32 = -99999 15 18 16 19 def values_line(line, splitv, chars): … … 9875 9878 ... 9876 9879 [dim1]_N 9880 NOTE: for character values, use '!' for space 9877 9881 ncfile= netCDF file to use 9878 9882 varname= variable to use … … 9917 9921 for line in objasciif: 9918 9922 val = (line.replace('\n','').replace(' ','').replace('\t','')) 9919 valfinal[0] = retype(val, vartype) 9920 if it <= values.shape[0]-1: 9921 values[it] = retype(valfinal[0], vartype) 9922 it = it +1 9923 if vartype != '|S1': 9924 valfinal[0] = retype(val, vartype) 9925 if it <= values.shape[0]-1: 9926 values[it] = retype(valfinal[0], vartype) 9927 it = it +1 9928 else: 9929 for i1 in range(len(val)): 9930 values[it] = val.replace('!',' ') 9923 9931 elif Ndims == 2: 9924 9932 iline=0 9925 9933 for line in objasciif: 9926 9934 vals = line.replace('\n','').replace('\t','').split(' ') 9927 if len(vals) != values.shape[1]: 9928 print errormsg 9929 print ' ' + fname + ': given: ',len(vals),' but variable reaquires: ',values.shape[1],'!!!' 9930 exit(-1) 9931 for i1 in range(len(vals)): 9932 values[iline,i1] = retype(vals[i1], vartype) 9935 if vartype != '|S1': 9936 if len(vals) != values.shape[1]: 9937 print errormsg 9938 print ' ' + fname + ': given: ',len(vals),' but variable ' + \ 9939 'reaquires: ',values.shape[1],'!!!' 9940 exit(-1) 9941 for i1 in range(len(vals)): 9942 values[iline,i1] = retype(vals[i1], vartype) 9943 else: 9944 for i1 in range(len(vals)): 9945 values[iline,i1] = vals[i1].replace('!',' ') 9933 9946 iline=iline+1 9934 9947 else: … … 14469 14482 if [dsize] = 'None', give a third value with the real size 14470 14483 [attributes]: [std_name]@[long_name]@[units], standard name, long name and units of the variable 14484 ('!' for spaces) 14471 14485 [kind]: type of variable (standard netCDF4/C-like values, 'c', 'i', 'f', 'f8',...) 14472 14486 ncfile= name of the file … … 14485 14499 14486 14500 dimensions = values.split('|')[0].split(',') 14487 attributes = values.split('|')[1] 14501 attributes = values.split('|')[1].replace('!',' ') 14488 14502 kind = values.split('|')[2] 14489 14503 … … 14521 14535 newvar = onc.createVariable(varn, 'c', tuple(dnames)) 14522 14536 # newvar[:] = np.zeros(tuple(dsize), dtype=np.float) 14523 if kind == 'f' or kind == 'f4':14537 elif kind == 'f' or kind == 'f4': 14524 14538 newvar = onc.createVariable(varn, 'f4', tuple(dnames), fill_value=fillValue) 14525 14539 newvar[:] = np.zeros(tuple(dsize), dtype=np.float) … … 17158 17172 'inv': inverse of the values 1/[varname] 17159 17173 'nothing': direct values 17174 'prodinv': inverse of the product between 2 variables ([varname1]*[varname2]), 17175 NOTE: [varname] = [varname1]:[varname2] 17160 17176 * 'reglonlat',[lonname],[latname]: regular lon/lat projection to compute the area size 17161 17177 [xdimname]: name of the dimension for the x-axis … … 17171 17187 quit() 17172 17188 17173 operations = ['inv','nothing' ]17189 operations = ['inv','nothing','prodinv'] 17174 17190 17175 17191 weightk = values.split(',')[0] … … 17229 17245 17230 17246 if weightk == 'varnames': 17231 if not onc.variables.has_key(varname): 17232 print errormsg 17233 print ' ' + fname + ": file '" + filen + "' does not have variable '" + \ 17234 varname + "' !!" 17235 quit(-1) 17236 iovarwgt = onc.variables[varname] 17237 17238 ivarwgtv = iovarwgt[:] 17247 if oper == 'inv': 17248 if not onc.variables.has_key(varname): 17249 print errormsg 17250 print ' ' + fname + ": file '" + filen + "' does not have " + \ 17251 "variable '" + varname + "' !!" 17252 quit(-1) 17253 iovarwgt = onc.variables[varname] 17254 ivarwgtv = iovarwgt[:] 17255 elif oper == 'nothing': 17256 if not onc.variables.has_key(varname): 17257 print errormsg 17258 print ' ' + fname + ": file '" + filen + "' does not have " + \ 17259 "variable '" + varname + "' !!" 17260 quit(-1) 17261 iovarwgt = onc.variables[varname] 17262 ivarwgtv = iovarwgt[:] 17263 elif oper == 'prodinv': 17264 varname1 = varname.split(':')[0] 17265 varname2 = varname.split(':')[1] 17266 if not onc.variables.has_key(varname1): 17267 print errormsg 17268 print ' ' + fname + ": file '" + filen + "' does not have " + \ 17269 "variable '" + varname1 + "' !!" 17270 quit(-1) 17271 if not onc.variables.has_key(varname2): 17272 print errormsg 17273 print ' ' + fname + ": file '" + filen + "' does not have " + \ 17274 "variable '" + varname2 + "' !!" 17275 quit(-1) 17276 iovarwgt = onc.variables[varname1] 17277 ivarwgtv = iovarwgt[:]*onc.variables[varname2] 17278 17239 17279 if oper == 'inv': 17240 17280 longvarname = 'using inverse of variable ' + varname + ' as space weights' … … 17265 17305 newvals[id1,id2,id3]= np.mean(ivarv[tuple(slicevalues)]/ \ 17266 17306 ivarwgtv[tuple(slicewgt)]) 17307 outweightvals = 1./ivarwgtv[tuple(slicewgt)] 17267 17308 elif oper == 'nothing': 17268 17309 longvarname = 'using variable ' + varname + ' as space weights' … … 17293 17334 newvals[id1,id2,id3]=np.mean(ivarv[tuple(slicevalues)]* \ 17294 17335 ivarwgtv[tuple(slicewgt)]) 17336 outweightvals = ivarwgtv[tuple(slicewgt)] 17337 if oper == 'prodinv': 17338 longvarname = 'using inverse of product of variables ' + varname1 + '*' \ 17339 + varname2 + ' as space weights' 17340 if len(loopshape) == 1: 17341 newvals = np.ones((loopshape[0]), dtype=np.float)*fillValueF 17342 for id1 in range(loopshape[0]): 17343 slicevalues = SliceVar(iovar,dimsloop,[id1]) 17344 slicewgt = SliceVar(iovarwgt,dimsloop,[id1]) 17345 newvals[id1] = np.mean(ivarv[tuple(slicevalues)] / \ 17346 ivarwgtv[tuple(slicewgt)]) 17347 elif len(loopshape) == 2: 17348 newvals = np.ones((loopshape[0],loopshape[1]),dtype=np.float)* \ 17349 fillValueF 17350 for id1 in range(loopshape[0]): 17351 for id2 in range(loopshape[1]): 17352 slicevalues = SliceVar(iovar,dimsloop,[id1,id2]) 17353 slicewgt = SliceVar(iovarwgt,dimsloop,[id1,id2]) 17354 newvals[id1,id2] = np.mean(ivarv[tuple(slicevalues)] / \ 17355 ivarwgtv[tuple(slicewgt)]) 17356 elif len(loopshape) == 3: 17357 newvals = np.ones((loopshape[0],loopshape[1],loopshape[2]), \ 17358 dtype=np.float)*fillValueF 17359 for id1 in range(loopshape[0]): 17360 for id2 in range(loopshape[1]): 17361 for id3 in range(loopshape[1]): 17362 slicevalues = SliceVar(iovar,dimsloop,[id1,id2,id3]) 17363 slicewgt = SliceVar(iovarwgt,dimsloop,[id1,id2,id3]) 17364 newvals[id1,id2,id3]= np.mean(ivarv[tuple(slicevalues)]/ \ 17365 ivarwgtv[tuple(slicewgt)]) 17366 outweightvals = 1./ivarwgtv[tuple(slicewgt)] 17295 17367 elif weightk == 'reglonlat': 17296 17368 longvarname = 'using cos(latitude) variable ' + latname + ' as space weights' … … 17313 17385 lonv, latv = lonlat2D(ilonv, ilatv) 17314 17386 17315 ivarwgtv = np.abs(np.cos(latv*np.pi/180.)) 17387 ivarwgtv = np.abs(np.cos(latv*np.pi/180.))/(lonv.shape[0]*lonv.shape[1]) 17316 17388 if len(loopshape) == 1: 17317 17389 newvals = np.ones((loopshape[0]), dtype=np.float)*fillValueF … … 17334 17406 newvals[id1,id2,id3] = np.mean(ivarv[tuple(slicevalues)] * \ 17335 17407 ivarwgtv) 17408 outweightvals = ivarwgtv 17336 17409 17337 17410 # Writting output file … … 17351 17424 longvarname, iovar.getncattr('units')) 17352 17425 newvar[:] = newvals 17426 17427 # Spatial weight 17428 ## 17429 newdim = onewnc.createDimension(ydimname, outweightvals.shape[0]) 17430 newdim = onewnc.createDimension(xdimname, outweightvals.shape[1]) 17431 newvar = onewnc.createVariable('spatialweight', 'f4',tuple([ydimname, xdimname]),\ 17432 fill_value=fillValueF) 17433 basicvardef(newvar, 'spatialweight', 'space weight ' + longvarname, '-') 17434 newvar[:] = outweightvals 17353 17435 17354 17436 # Global attributes … … 17372 17454 #SpatialWeightedMean('varnames,MAPFAC_M,inv,west_east,south_north','wrfout_d01_2001-11-11_00:00:00','HGT') 17373 17455 #SpatialWeightedMean('reglonlat,XLONG,XLAT,west_east,south_north','wrfout_d01_2001-11-11_00:00:00','HGT') 17456 17457 def fill_value(vartype, fillval0): 17458 """ Function to provide the fiven fill_Value for a kind of variable 17459 [vartype]= type of the variable 17460 [fillval0]= value to take as fill value, 'std' for the standard value 17461 Float = 1.e20 17462 Character = '-' 17463 Integer = -99999 17464 Integer16 = -99999 17465 Float64 = 1.e20 17466 Integer32 = -99999 17467 """ 17468 fname = 'fill_value' 17469 17470 if vartype == '|S': 17471 if fillval0 == 'std': 17472 fillval = fillvalueC 17473 else: 17474 fillval = fillval0 17475 elif vartype == type(int(1)): 17476 if fillval0 == 'std': 17477 fillval = fillValueI 17478 else: 17479 fillval = int(fillval0) 17480 elif vartype == type(np.int16(1)): 17481 if fillval0 == 'std': 17482 fillval = np.int16(fillValueI) 17483 else: 17484 fillval = np.int16(fillval0) 17485 elif vartype == type(np.int32(1)): 17486 if fillval0 == 'std': 17487 fillval = np.int32(fillValueI) 17488 else: 17489 fillval = np.int32(fillval0) 17490 elif vartype == type(np.float(1.)): 17491 if fillval0 == 'std': 17492 fillval = np.float(fillValueF) 17493 else: 17494 fillval = np.float(fillval0) 17495 elif vartype == type(np.float32(1.)): 17496 if fillval0 == 'std': 17497 fillval = np.float32(fillValueF) 17498 else: 17499 fillval = np.float32(fillval0) 17500 elif vartype == type(np.float64(1.)): 17501 if fillval0 == 'std': 17502 fillval = np.float64(fillValueF) 17503 else: 17504 fillval = np.float64(fillval0) 17505 else: 17506 print errormsg 17507 print ' ' + fname + ': variable type', vartype, 'not ready !!' 17508 quit(-1) 17509 17510 return fillval 17511 17512 def VarVal_FillValue(values, filen, varn): 17513 """ Function to transform a given value from a given variable to _FillValue in a netCDF file 17514 values= [value],[fillVal] 17515 [value]: value to pass to '_FillValue' 17516 [fillVal]: value for '_FillValue', 'std' for the standard value 17517 Float = 1.e20 17518 Character = '-' 17519 Integer = -99999 17520 Float64 = np.float(Float) 17521 Integer32 = np.int32(Integer) 17522 filen= name of the netCDF file 17523 varn= name of the variable 17524 """ 17525 fname = 'VarVal_FillValue' 17526 17527 if values == 'h': 17528 print fname + '_____________________________________________________________' 17529 print VarVal_FillValue.__doc__ 17530 quit() 17531 17532 onc = NetCDFFile(filen, 'a') 17533 if not onc.variables.has_key(varn): 17534 print errormsg 17535 print ' ' + fname + ": file '" + filen + "' does not have " + \ 17536 "variable '" + varn + "' !!" 17537 quit(-1) 17538 17539 value = values.split(',')[0] 17540 fval0 = values.split(',')[1] 17541 17542 varo = onc.variables[varn] 17543 varvals = varo[:] 17544 vartype = varo.dtype 17545 17546 if vartype == '|S': 17547 valchk = value 17548 elif vartype == type(int(1)): 17549 valchk = int(value) 17550 elif vartype == type(np.int32(1)): 17551 valchk = np.int32(value) 17552 elif vartype == type(np.float(1.)): 17553 valchk = np.float(value) 17554 elif vartype == type(np.float32(1.)): 17555 valchk = np.float32(value) 17556 elif vartype == type(np.float64(1.)): 17557 valchk = np.float64(value) 17558 else: 17559 print errormsg 17560 print ' ' + fname + ': variable type', vartype, 'not ready !!' 17561 quit(-1) 17562 17563 fval = fill_value(vartype, fval0) 17564 newvarvals = np.where(varvals==valchk, fval, varvals) 17565 17566 if searchInlist(varo.ncattrs(), 'missing_value'): 17567 missval = varo.getncattr('missing_value') 17568 difvals = fval*10.**(-np.log10(valchk)) - missval*10.**(-np.log10(missval)) 17569 if missval == valchk or np.abs(difvals) < 1.e-6: 17570 print warnmsg 17571 print ' ' + fname + ': same missing and checking Value!' 17572 print ' renaming missing_value' 17573 varo.renameAttribute('missing_value','_FillValue') 17574 else: 17575 set_attribute(varo, '_FillValue', fval) 17576 else: 17577 set_attribute(varo, '_FillValue', fval) 17578 17579 varo[:] = newvarvals 17580 17581 onc.sync() 17582 onc.close() 17583 17584 print fname +': Successfull change to _FillValue !!' 17585 17586 return 17587 17588 #VarVal_FillValue('0.,std', '/home/lluis/etudes/DYNAMICO/ORCHIDEE/interpolation/data/new_lai2D.nc', 'LAI') 17589 17590 def Partialmap_Entiremap(values, filen, varn): 17591 """ Function to transform from a partial global map (e.g.: only land points) to an entire one 17592 values= [lonmame],[latname] 17593 [lonname]: name of the longitude variable 17594 [latname]: name of the latitude variable 17595 [fillVal]: value for '_FillValue', 'std' for the standard value 17596 Float = 1.e20 17597 Character = '-' 17598 Integer = -99999 17599 Float64 = 1.e20 17600 Integer32 = -99999 17601 filen= name of the netCDF file 17602 varn= name of the variable 17603 """ 17604 import numpy.ma as ma 17605 fname = 'Partialmap_Entiremap' 17606 17607 if values == 'h': 17608 print fname + '_____________________________________________________________' 17609 print Partialmap_Entiremap.__doc__ 17610 quit() 17611 17612 ofile = 'EntireGlobalMap.nc' 17613 17614 onc = NetCDFFile(filen, 'r') 17615 if not onc.variables.has_key(varn): 17616 print errormsg 17617 print ' ' + fname + ": file '" + filen + "' does not have " + \ 17618 "variable '" + varn + "' !!" 17619 quit(-1) 17620 17621 lonname = values.split(',')[0] 17622 latname = values.split(',')[1] 17623 fval0 = values.split(',')[2] 17624 17625 if not onc.variables.has_key(lonname): 17626 print errormsg 17627 print ' ' + fname + ": file '" + filen + "' does not have " + \ 17628 "longitude '" + lonname + "' !!" 17629 quit(-1) 17630 if not onc.variables.has_key(latname): 17631 print errormsg 17632 print ' ' + fname + ": file '" + filen + "' does not have " + \ 17633 "latitude '" + latname + "' !!" 17634 quit(-1) 17635 17636 olon = onc.variables[lonname] 17637 olat = onc.variables[latname] 17638 17639 lonvs = olon[:] 17640 latvs = olat[:] 17641 17642 nlat = np.min(latvs) 17643 nlon = np.min(lonvs) 17644 17645 minlat = np.min(np.abs(latvs)) 17646 minlon = np.min(np.abs(lonvs)) 17647 17648 print ' ' + fname + ': Closest latitude to Equator:', minlat 17649 print ' ' + fname + ': Closest longitude to Greenwich Meridian:', minlon 17650 17651 # Existing longitudes along/closest to the Equator 17652 eqlons = [] 17653 for i in range(len(latvs)): 17654 if latvs[i] == minlat: eqlons.append(lonvs[i]) 17655 17656 # Existing latitudes along/closest to the Greenwich Meridian 17657 grlats = [] 17658 for i in range(len(lonvs)): 17659 if lonvs[i] == minlon: grlats.append(latvs[i]) 17660 17661 sorteqlons = np.sort(eqlons) 17662 sortgrlats = np.sort(grlats) 17663 17664 Neqlons = len(sorteqlons) 17665 Ngrlats = len(sortgrlats) 17666 17667 if Neqlons > 1: 17668 diffeqlons = sorteqlons[1:Neqlons-1] - sorteqlons[0:Neqlons-2] 17669 mindeqlon = np.min(diffeqlons) 17670 print 'N sorteqlons:',Neqlons,'min deqlon:', mindeqlon 17671 else: 17672 mindeqlon = None 17673 17674 if Ngrlats > 1: 17675 mindgrlat = np.min(diffgrlats) 17676 diffgrlats = sortgrlats[1:Ngrlats-1] - sortgrlats[0:Ngrlats-2] 17677 print 'N sortgrlats:',Ngrlats,'min dgrlat:', mindgrlat 17678 latmap = np.range(0,360.,360./mindeqlon) 17679 else: 17680 mindgrlat = None 17681 17682 # Global sorting 17683 17684 # TOTlons = lonvs.shape[0] 17685 # TOTlats = lonvs.shape[0] 17686 17687 # sortlons = np.sort(lonvs) 17688 # sortlats = np.sort(latvs) 17689 17690 # difflons = sortlons[1:TOTlons-1] - sortlons[0:TOTlons-2] 17691 # difflats = sortlats[1:TOTlons-1] - sortlats[0:TOTlons-2] 17692 17693 # madifflons = ma.masked_equal(difflons, 0.) 17694 # madifflats = ma.masked_equal(difflats, 0.) 17695 17696 # print 'Nmadifflons:',len(madifflons.compressed()),'Nmadifflats:',len(madifflats.compressed()) 17697 17698 # sortdifflons = np.sort(madifflons) 17699 # sortdifflats = np.sort(madifflats) 17700 17701 # print 'sortdifflons:',sortdifflons[0:10] 17702 # print 'sortdifflats:',sortdifflats[0:10] 17703 17704 # Fixing in case it has not worked 17705 if mindeqlon is not None and mindgrlat is None: mindgrlat = mindeqlon 17706 if mindeqlon is None and mindgrlat is not None: mindeqlon = mindgrlat 17707 if mindeqlon is None and mindgrlat is None: 17708 print errormsg 17709 print fname + ': Not enough values along the Equator and Greenwich!!' 17710 quit(-1) 17711 17712 if nlon < 0.: 17713 lonmap = np.arange(-180.+mindeqlon,180.,mindeqlon) 17714 else: 17715 lonmap = np.arange(0.,360.-mindeqlon,mindeqlon) 17716 17717 if nlat < 0.: 17718 latmap = np.arange(-90.+mindgrlat,90.,mindgrlat) 17719 else: 17720 latmap = np.arange(0.,180.-mindgrlat,mindgrlat) 17721 17722 print ' ' + fname + '_________' 17723 print ' final longitudes:',lonmap 17724 print ' final latitudes:',latmap 17725 17726 Nmaplon = len(lonmap) 17727 Nmaplat = len(latmap) 17728 print ' ' + fname + ': desired map will be:',Nmaplon,'x',Nmaplat 17729 17730 quit() 17731 17732 # Matrix map creation 17733 ## 17734 ovar = onc.variables[varn] 17735 vartype = ovar.dtype 17736 varlongname = ovar.long_name 17737 varunits = ovar.units 17738 17739 fval = fill_value(vartype, fval0) 17740 17741 mapval = np.ones((Nmaplat,Nmaplon), dtype=np.float)*fval 17742 17743 Ntotvals = lonvs.shape[0] 17744 for iv in range(Ntotvals): 17745 if np.mod(iv*100./Ntotvals, 10.) == 0: print ' done:',iv*100./Ntotvals,'%' 17746 difflon = np.abs(lonmap - lonvs[iv]) 17747 difflat = np.abs(latmap - latvs[iv]) 17748 17749 # print np.min(difflon), ':', np.min(difflat) 17750 17751 ilon = index_mat(difflon, np.min(difflon)) 17752 ilat = index_mat(difflat, np.min(difflat)) 17753 if np.min(difflon) != 0. or np.min(difflat) !=0.: 17754 print 'No zero diffs!!:', lonvs[iv],latvs[iv],':',np.min(difflon),np.min(difflat),'i j',ilon,ilat 17755 print lonmap[ilon], latmap[ilat] 17756 quit() 17757 17758 if ilon > 0 and ilat > 0: 17759 mapval[ilat,ilon] = ovar[iv] 17760 else: 17761 print errormsg 17762 print ' ' + fname + ': point:',lonvs[iv],',',latvs[iv],' not relocated !!' 17763 quit(-1) 17764 17765 # Final map creation 17766 ## 17767 newnc = NetCDFFile(ofile, 'w') 17768 17769 # dimensions 17770 newdim = newnc.createDimension('lon',Nmaplon) 17771 newdim = newnc.createDimension('lat',Nmaplat) 17772 17773 # Variables 17774 newvar = newnc.createVariable('lon','f8',('lon')) 17775 basicvardef(newvar, 'lon', 'Longitudes','degrees East') 17776 nevar[:] = lonmap 17777 17778 newvar = newnc.createVariable('lat','f8',('lat')) 17779 basicvardef(newvar, 'lat', 'Latitudes','degrees North') 17780 nevar[:] = latmap 17781 17782 # map variable 17783 newvar = newnc.createVariable(varn,'f4',('lat','lon'), fill_value=fval) 17784 basicvardef(newvar, varn, 'Longitudes','degrees East') 17785 nevar[:] = lonmap 17786 17787 newnc.sync() 17788 # Global attributes 17789 ## 17790 newnc.setncattr('script', fname) 17791 newnc.setncattr('version', '1.0') 17792 newnc.setncattr('author', 'L. Fita') 17793 newnc.setncattr('institution', 'Laboratoire de Meteorology Dynamique') 17794 newnc.setncattr('university', 'Pierre et Marie Curie') 17795 newnc.setncattr('country', 'France') 17796 for attrs in onc.ncattrs(): 17797 attrv = onc.getncattr(attrs) 17798 attr = set_attribute(newnc, attrs, attrv) 17799 17800 newnc.sync() 17801 onc.close() 17802 newnc.close() 17803 17804 print fname + ": Successfull written of file: '" + ofile + "' !!" 17805 17806 return 17807 17808 #Partialmap_Entiremap('longitude,latitude,std', '/home/lluis/etudes/DYNAMICO/ORCHIDEE/interpolation/data/carteveg5km.nc', 'vegetation_map') 17374 17809 #quit() 17375 17810
Note: See TracChangeset
for help on using the changeset viewer.