- Timestamp:
- Apr 25, 2016, 6:56:05 PM (9 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/tools/nc_var_tools.py
r713 r714 19203 19203 return 19204 19204 19205 def Partialmap_EntiremapFor(values, filen, varn): 19206 """ Function to transform from a partial global map (e.g.: only land points) to an entire one usinf Fortran code 19207 Coincidence of points is done throughout a first guess from fractions of the total domain of search 19208 Using fortran codes: module_ForInterpolate.F90, module_generic.F90 19209 f2py -m module_ForInterpolate --f90exec=/usr/bin/gfortran-4.7 -c module_ForInterpolate.F90 module_generic.F90 >& run_f2py.log 19210 values= [lonmame],[latname],[fillVal],[resolution],[kind],[lonlatProjfile],[fracd] 19211 [lonname]: name of the longitude variable 19212 [latname]: name of the latitude variable 19213 [fillVal]: value for '_FillValue', 'std' for the standard value 19214 Float = 1.e20 19215 Character = '-' 19216 Integer = -99999 19217 Float64 = 1.e20 19218 Integer32 = -99999 19219 [resolution]: resolution of the map 19220 [kind]: kind of target projection 19221 'lonlat': standard lon/lat projection tacking number of points from [dx/dy]res at the Equator 19222 'lonlat_dxdyFix': projection with a fixed grid distance 19223 'Goode': Goode projection 19224 [lonlatProjfile]: file with the lon,lat of the desired projection. 'None' to be computed and written on fly 19225 [fracd]: Percentage of the fractions within perform the first guess search 19226 filen= name of the netCDF file 19227 varn= name of the variable 19228 """ 19229 import numpy.ma as ma 19230 import subprocess as sub 19231 19232 fname = 'Partialmap_Entiremap' 19233 19234 if values == 'h': 19235 print fname + '_____________________________________________________________' 19236 print Partialmap_Entiremap.__doc__ 19237 quit() 19238 19239 arguments = '[lonmame],[latname],[fillVal],[resolution],[kind],' + \ 19240 '[lonlatProjfile],[fracd]' 19241 check_arguments(fname, values, arguments, ',') 19242 19243 ofile = 'EntireGlobalMap.nc' 19244 19245 onc = NetCDFFile(filen, 'r') 19246 if not onc.variables.has_key(varn): 19247 print errormsg 19248 print ' ' + fname + ": file '" + filen + "' does not have " + \ 19249 "variable '" + varn + "' !!" 19250 quit(-1) 19251 19252 lonname = values.split(',')[0] 19253 latname = values.split(',')[1] 19254 fval0 = values.split(',')[2] 19255 resolution = np.float(values.split(',')[3]) 19256 kind = values.split(',')[4] 19257 Projfile = values.split(',')[5] 19258 fracd = np.float(values.split(',')[6]) 19259 19260 if Projfile == 'None': 19261 lonlatProjfile = None 19262 else: 19263 lonlatProjfile = Projfile 19264 19265 if not onc.variables.has_key(lonname): 19266 print errormsg 19267 print ' ' + fname + ": file '" + filen + "' does not have " + \ 19268 "longitude '" + lonname + "' !!" 19269 quit(-1) 19270 if not onc.variables.has_key(latname): 19271 print errormsg 19272 print ' ' + fname + ": file '" + filen + "' does not have " + \ 19273 "latitude '" + latname + "' !!" 19274 quit(-1) 19275 19276 olon = onc.variables[lonname] 19277 olat = onc.variables[latname] 19278 19279 lonvs = olon[:] 19280 latvs = olat[:] 19281 19282 Ninpts = len(lonvs) 19283 19284 nlat = np.min(latvs) 19285 nlon = np.min(lonvs) 19286 19287 minlat = np.min(np.abs(latvs)) 19288 minlon = np.min(np.abs(lonvs)) 19289 19290 # mindiff = np.min([minlat, minlon])/1. 19291 mindiff = np.min([minlat, minlon])*10.e6 19292 19293 print ' ' + fname + ': Closest latitude to Equator:', minlat 19294 print ' ' + fname + ': Closest longitude to Greenwich Meridian:', minlon 19295 print ' ' + fname + ': Minium distance for point coincidence:', mindiff 19296 19297 # Existing longitudes along/closest to the Equator 19298 eqlons = [] 19299 for i in range(len(latvs)): 19300 if latvs[i] == minlat: eqlons.append(lonvs[i]) 19301 19302 # Existing latitudes along/closest to the Greenwich Meridian 19303 grlats = [] 19304 for i in range(len(lonvs)): 19305 if lonvs[i] == minlon: grlats.append(latvs[i]) 19306 19307 sorteqlons = np.sort(eqlons) 19308 sortgrlats = np.sort(grlats) 19309 19310 Neqlons = len(sorteqlons) 19311 Ngrlats = len(sortgrlats) 19312 19313 if Neqlons > 1: 19314 diffeqlons = sorteqlons[1:Neqlons-1] - sorteqlons[0:Neqlons-2] 19315 mindeqlon = np.min(diffeqlons) 19316 print 'N sorteqlons:',Neqlons,'min deqlon:', mindeqlon 19317 else: 19318 mindeqlon = None 19319 19320 if Ngrlats > 1: 19321 mindgrlat = np.min(diffgrlats) 19322 diffgrlats = sortgrlats[1:Ngrlats-1] - sortgrlats[0:Ngrlats-2] 19323 print 'N sortgrlats:',Ngrlats,'min dgrlat:', mindgrlat 19324 latmap = np.range(0,360.,360./mindeqlon) 19325 else: 19326 mindgrlat = None 19327 19328 # Fixing in case it has not worked 19329 if mindeqlon is not None and mindgrlat is None: mindgrlat = mindeqlon 19330 if mindeqlon is None and mindgrlat is not None: mindeqlon = mindgrlat 19331 if mindeqlon is None and mindgrlat is None: 19332 print errormsg 19333 print fname + ': Not enough values along the Equator and Greenwich!!' 19334 quit(-1) 19335 19336 if lonlatProjfile is None: 19337 lonlatProjfile = kind + '.nc' 19338 print warnmsg 19339 print ' ' + fname + ": no reference map !!" 19340 print " creation of '" + lonlatProjfile + "'" 19341 print ' creating it via: lonlatProj(', resolution, ',', resolution, \ 19342 ', ' + kind + ', True)' 19343 lonmap, latmap = lonlatProj(resolution, resolution, kind, True) 19344 sub.call(['mv','lonlatProj.nc',lonlatProjfile]) 19345 19346 oproj = NetCDFFile(lonlatProjfile, 'r') 19347 if kind == 'Goode': 19348 olon = oproj.variables['lon'] 19349 olat = oproj.variables['lat'] 19350 lonmap = olon[:] 19351 latmap = olat[:] 19352 projlon = olon[:] 19353 projlat = olat[:] 19354 omapvals = oproj.variables['ptid'] 19355 Ntotvals = omapvals.shape[0] * omapvals.shape[1] 19356 Nmaplon = olon.shape[1] 19357 Nmaplat = olat.shape[0] 19358 19359 elif kind == 'lonlat': 19360 olon = oproj.variables['lon'] 19361 olat = oproj.variables['lat'] 19362 lonmap = olon[:] 19363 latmap = olat[:] 19364 projlon = olon[:] 19365 projlat = olat[:] 19366 omapvals = oproj.variables['points'] 19367 Ntotvals = omapvals.shape[0] * omapvals.shape[1] 19368 Nmaplon = olon.shape[0] 19369 Nmaplat = olat.shape[0] 19370 19371 elif kind == 'lonlat_dxdyFix': 19372 oprojlon = oproj.variables['loncirc'] 19373 oprojlat = oproj.variables['latcirc'] 19374 oNprojlon = oproj.variables['Nloncirc'] 19375 projlat = oprojlat[:] 19376 Nprojlon = oNprojlon[:] 19377 Ntotvals = len(oproj.dimensions['Npts']) 19378 olon = oproj.variables['lon'] 19379 olat = oproj.variables['lat'] 19380 lonmap = olon[:] 19381 latmap = olat[:] 19382 omapvals = oproj.variables['points'] 19383 19384 # Ntotvals = len(lonmap) 19385 Nmaplon = Ntotvals 19386 Nmaplat = Ntotvals 19387 else: 19388 print errormsg 19389 print ' ' + fname + ": projection kind '" + kind + "' not ready!!" 19390 quit(-1) 19391 19392 # Matrix map creation 19393 ## 19394 ovar = onc.variables[varn] 19395 vartype = type(ovar[0]) 19396 varlongname = ovar.long_name 19397 varunits = ovar.units 19398 19399 fval = fillvalue_kind(type(ovar[0]), fval0) 19400 19401 # Final map creation 19402 ## 19403 if not os.path.isfile(ofile): 19404 print ' ' + fname + "File '" + ofile + "' does not exist !!" 19405 print ' cration of output file' 19406 newnc = NetCDFFile(ofile, 'w') 19407 # dimensions 19408 newdim = newnc.createDimension('lon',Nmaplon) 19409 newdim = newnc.createDimension('lat',Nmaplat) 19410 newdim = newnc.createDimension('inpts', Ninpts) 19411 newdim = newnc.createDimension('pts', Ntotvals) 19412 19413 # Variables 19414 if kind == 'Goode': 19415 newvar = newnc.createVariable('lon','f8',('lat', 'lon')) 19416 else: 19417 newvar = newnc.createVariable('lon','f8',('lon')) 19418 basicvardef(newvar, 'lon', 'Longitudes','degrees_East') 19419 newvar[:] = lonmap 19420 newvar.setncattr('axis', 'X') 19421 newvar.setncattr('_CoordinateAxisType', 'Lon') 19422 19423 if kind == 'Goode': 19424 newvar = newnc.createVariable('lat','f8',('lat','lon')) 19425 else: 19426 newvar = newnc.createVariable('lat','f8',('lat')) 19427 basicvardef(newvar, 'lat', 'Latitudes','degrees_North') 19428 newvar[:] = latmap 19429 newvar.setncattr('axis', 'Y') 19430 newvar.setncattr('_CoordinateAxisType', 'Lat') 19431 19432 newvarinpt = newnc.createVariable('locinpt','i',('inpts')) 19433 basicvardef(newvarinpt, 'locinpt', 'input point located: 0: no, 1: yes','-') 19434 19435 newvarindiff = newnc.createVariable('locindiff','f4',('inpts')) 19436 basicvardef(newvarindiff, 'locindiff', 'distance between input point and its final location','degree') 19437 19438 # map variable 19439 Lmapvalsshape = len(omapvals.shape) 19440 if Lmapvalsshape == 1: 19441 newvar = newnc.createVariable(varn, nctype(vartype), ('pts'), fill_value=fval) 19442 else: 19443 newvar = newnc.createVariable(varn, nctype(vartype), ('lat','lon'), fill_value=fval) 19444 19445 basicvardef(newvar, varn, varlongname, varunits) 19446 newvar.setncattr('coordinates', 'lon lat') 19447 19448 if Lmapvalsshape == 1: 19449 newvarin = newnc.createVariable('inpts', 'i4', ('pts')) 19450 else: 19451 newvarin = newnc.createVariable('inpts', 'i4', ('lat','lon')) 19452 19453 basicvardef(newvarin, 'inpts', 'Equivalent point from the input source', '-') 19454 newvar.setncattr('coordinates', 'lon lat') 19455 19456 else: 19457 print ' ' + fname + "File '" + ofile + "' exists !!" 19458 print ' reading values from file' 19459 newnc = NetCDFFile(ofile, 'a') 19460 newvar = newnc.variables[varn] 19461 newvarin = newnc.variables['inpts'] 19462 newvarinpt = newnc.variables['locinpt'] 19463 newvarindiff = newnc.variables['locindiff'] 19464 19465 amsk = np.arange(3) 19466 amsk = ma.masked_equal(amsk, 0) 19467 19468 # fraclon = projlon[::Nmaplon*0.1] 19469 # fraclat = projlat[::Nmaplat*0.1] 19470 19471 # print 'fraclon________________', fraclon.shape 19472 # print fraclon 19473 19474 # print 'fraclat________________', fraclat.shape 19475 # print fraclat 19476 19477 # Reducing the searching points 19478 newvarinvals = newvarinpt[:] 19479 maskpt = np.where(newvarinvals.mask == True, False, True) 19480 points = np.arange(Ninpts) 19481 mapoints = ma.array(points, mask=maskpt) 19482 ptsf = mapoints.compressed() 19483 19484 Nptsf = len(ptsf) 19485 print Ninpts,'Npoints to find:', len(ptsf), ptsf[0:10], newvarindiff[ptsf[0:10]] 19486 # Error at 150024, 150025, 151709, 153421 19487 print ' ' + fname + ': from:', Ninpts,'re-locating:',Nptsf,'points...' 19488 fracs = 1000 19489 if kind == 'Goode': 19490 # newvar,newvarin,newvarinpt,newvarindiff = \ 19491 # fin.module_forinterpolate.coarseinterpolate(projlon, projlat, lonvs, \ 19492 # latvs, percen, mindiff, ivar, dimx, dimy, ninpts) 19493 for ir in range(0,Ninpts,fracs): 19494 iri = ir 19495 ire = ir + fracs + 1 19496 print iri,',',ire 19497 newvar,newvarin,newvarinpt,newvarindiff = \ 19498 fin.module_forinterpolate.coarseinterpolate(projlon, projlat, \ 19499 lonvs[iri:ire], latvs[iri:ire], fracd, mindiff, ivar, Nmaplon, \ 19500 Nmaplat, fracs) 19501 newnc.sync() 19502 19503 elif kind == 'lonlat': 19504 for iv in range(Ntotvals): 19505 difflat = np.abs(projlat - latvs[iv]) 19506 mindiffL = np.min(difflat) 19507 ilat = index_mat(difflat, mindiffL) 19508 difflon = np.abs(projlon - lonvs[iv]) 19509 mindiffl = difflon.min() 19510 ilon = index_mat(difflon, mindiffl) 19511 percendone(iv,Ntotvals,0.5,'done:') 19512 if mindiffl > mindiff or mindiffL > mindiff: 19513 print errormsg 19514 print ' ' + fname + ': for point #', iv,'lon,lat in incomplet map:', \ 19515 lonvs[iv], ',', latvs[iv], 'there is not a set of lon,lat in the ' + \ 19516 'completed map closer than: ', mindiff, '!!' 19517 print ' minimum difflon:', np.min(difflon), 'difflat:', np.min(difflat) 19518 quit() 19519 19520 if ilon >= 0 and ilat >= 0: 19521 newvar[ilat,ilon] = ovar[iv] 19522 newnc.sync() 19523 else: 19524 print errormsg 19525 print ' ' + fname + ': point iv:',iv,'at',lonvs[iv],',',latvs[iv],' not relocated !!' 19526 print ' mindiffl:',mindiffl,'mindiffL:',mindiffL,'ilon:',ilon,'ilat:',ilat 19527 quit(-1) 19528 19529 newnc.sync() 19530 19531 elif kind == 'lonlat_dxdyFix': 19532 19533 for iv in range(Ntotvals): 19534 # for iv in range(15): 19535 # print 'Lluis:',iv,'lon lat:',lonvs[iv],',',latvs[iv] 19536 difflat = np.abs(projlat - latvs[iv]) 19537 mindiffL = np.min(difflat) 19538 ilat = index_mat(difflat, mindiffL) 19539 # print ' Lluis mindiffL:',mindiffL,'<> ilat:',ilat,'lat_ilat:',projlat[ilat],'Nprojlon:',Nprojlon[ilat],'shape oporjlon:',oprojlon[ilat,:].shape, type(oprojlon[ilat,:]) 19540 loncirc = np.zeros((Nprojlon[ilat]), dtype=np.float) 19541 loncirc[:] = np.asarray(oprojlon[ilat,0:int(Nprojlon[ilat])].flatten()) 19542 difflon = np.abs(loncirc - lonvs[iv]) 19543 mindiffl = difflon.min() 19544 ilon = index_mat(difflon, mindiffl) 19545 # print ' difflon:',type(difflon),'shape difflon',difflon.shape,'shape loncirc:', loncirc.shape 19546 # print ' Lluis mindiffl:',mindiffl,'<> ilon:',ilon,'oprojlon:', loncirc[ilon] 19547 19548 percendone(iv,Ntotvals,0.5,'done:') 19549 if mindiffl > mindiff or mindiffL > mindiff: 19550 print errormsg 19551 print ' ' + fname + ': for point #', iv,'lon,lat in incomplet map:', \ 19552 lonvs[iv], ',', latvs[iv], 'there is not a set of lon,lat in the ' + \ 19553 'completed map closer than: ', mindiff, '!!' 19554 print ' minimum difflon:', np.min(difflon), 'difflat:', np.min(difflat) 19555 quit() 19556 19557 if ilon >= 0 and ilat >= 0: 19558 if Lmapvalsshape ==1: 19559 newvar[iv] = ovar[iv] 19560 newnc.sync() 19561 else: 19562 print errormsg 19563 print ' ' + fname + ': point iv:',iv,'at',lonvs[iv],',',latvs[iv],' not relocated !!' 19564 print ' mindiffl:',mindiffl,'mindiffL:',mindiffL,'ilon:',ilon,'ilat:',ilat 19565 quit(-1) 19566 19567 newnc.sync() 19568 # Global attributes 19569 ## 19570 newnc.setncattr('script', fname) 19571 newnc.setncattr('version', '1.0') 19572 newnc.setncattr('author', 'L. Fita') 19573 newnc.setncattr('institution', 'Laboratoire de Meteorology Dynamique') 19574 newnc.setncattr('university', 'Pierre et Marie Curie') 19575 newnc.setncattr('country', 'France') 19576 for attrs in onc.ncattrs(): 19577 attrv = onc.getncattr(attrs) 19578 attr = set_attribute(newnc, attrs, attrv) 19579 19580 newnc.sync() 19581 onc.close() 19582 newnc.close() 19583 19584 print fname + ": Successfull written of file: '" + ofile + "' !!" 19585 19586 return 19587 19205 19588 #Partialmap_Entiremap('longitude,latitude,std,5000.,Goode,Goode_5km.nc', '/home/lluis/etudes/DYNAMICO/ORCHIDEE/interpolation/data/#carteveg5km.nc', 'vegetation_map') 19206 19589 #Partialmap_Entiremap('longitude,latitude,std,5000.,lonlat_dxdyFix', '/home/lluis/etudes/DYNAMICO/ORCHIDEE/interpolation/data/carteveg5km.nc', 'vegetation_map')
Note: See TracChangeset
for help on using the changeset viewer.