Changeset 762 in lmdz_wrf
- Timestamp:
- May 9, 2016, 8:50:45 AM (9 years ago)
- Location:
- trunk/tools
- Files:
-
- 3 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/tools/generic_tools.py
r745 r762 3327 3327 return seasvals 3328 3328 3329 def seasmean(timename, filename, varn):3330 """ Function to compute the seasonal mean of a variable3331 timename= name of the variable time in the file3332 filename= netCDF file name3333 varn= name of the variable3334 """3335 fillValue=1.e203336 3337 ncf = NetCDFFile(filename,'a')3338 ofile = 'seasmean_' + varn + '.nc'3339 3340 if not ncf.variables.has_key(varn):3341 print errormsg3342 print ' seasmean: File "' + filename + '" does not have variable ' + varn + ' !!!!'3343 print errormsg3344 ncf.close()3345 quit(-1)3346 3347 varobj = ncf.variables[varn]3348 varinf = variable_inf(varobj)3349 timeobj = ncf.variables[timename]3350 timeinf = cls_time_information(ncf, timename)3351 3352 timevals=timeobj[:]3353 netcdftimes = netCDFdatetime_realdatetime(timeinf.units + ' since ' + timeinf.Urefdate, timeinf.calendar, timevals)3354 3355 timeseasons=times_4seasons(netcdftimes, True)3356 3357 timeseasvals=seasonal_means(netcdftimes, timevals)3358 3359 ncfnew = NetCDFFile(ofile,'w')3360 ncfnew.createDimension('seastime', timeinf.dimt/4)3361 ncfnew.createDimension('seas', 4)3362 3363 newvarobj = ncfnew.createVariable('seastime', 'f4', ('seastime', 'seas',), fill_value=fillValue)3364 newvarobj[:]=timeseasvals3365 attr = newvarobj.setncattr('calendar', timeinf.calendar)3366 attr = newvarobj.setncattr('units', timeinf.units)3367 3368 newvarobj = ncfnew.createVariable('seasn', str, ('seas'))3369 attr = newvarobj.setncattr('standard_name', 'seasn')3370 attr = newvarobj.setncattr('long_name', 'name of the season')3371 attr = newvarobj.setncattr('units', '3-months')3372 newvarobj[0]='DJF'3373 newvarobj[1]='MAM'3374 newvarobj[2]='JJA'3375 newvarobj[3]='SON'3376 3377 newdims=[]3378 idim = 03379 3380 for ndim in varinf.dimns:3381 if ndim == timename:3382 newdims.append(unicode('seastime'))3383 if not idim == 0:3384 print errormsg3385 print ' seasmean: File "' + filename + '" does not have time dimension "' + timename + '" as the first one. It has it as # ', idim, ' !!!!'3386 print errormsg3387 ncf.close()3388 quit(-1)3389 else:3390 newdims.append(ndim)3391 3392 if not ncfnew.dimensions.has_key(ndim):3393 ncfnew.sync()3394 ncfnew.close()3395 ncf.close()3396 3397 fdimadd(filename + ',' + ndim, ofile)3398 ncf = NetCDFFile(filename,'r')3399 ncfnew = NetCDFFile(ofile,'a')3400 3401 print ncfnew.dimensions3402 namedims=tuple(newdims)3403 print namedims3404 3405 varobj = ncf.variables[varn]3406 varinf = variable_inf(varobj)3407 3408 newvarobj=ncfnew.createVariable(varn + '_seasmean', 'f4', namedims, fill_value=fillValue)3409 attr = newvarobj.setncattr('standard_name', varn + '_seasmean')3410 attr = newvarobj.setncattr('long_name', 'seasonal mean of ' + varn)3411 attr = newvarobj.setncattr('units', varinf.units)3412 3413 newvar = np.ones(varinf.dims[0], dtype=varinf.dtype)3414 if varinf.Ndims == 1:3415 newvar = newvarobj[:]3416 newvarobj[:] = seasonal_means(netcdftimes, newvar)3417 if varinf.Ndims == 2:3418 for i in range(varinf.dims[1]):3419 newvar = newvarobj[:,i]3420 newvarobj[:,i] = seasonal_means(netcdftimes, newvar)3421 if varinf.Ndims == 3:3422 for i in range(varinf.dims[1]):3423 for j in range(varinf.dims[2]):3424 newvar = newvarobj[:,i,j]3425 newvarobj[:,i,j] = seasonal_means(netcdftimes, newvar)3426 if varinf.Ndims == 4:3427 for i in range(varinf.dims[1]):3428 for j in range(varinf.dims[2]):3429 for k in range(varinf.dims[3]):3430 newvar = newvarobj[:,i,j,k]3431 newvarobj[:,i,j,k] = seasonal_means(netcdftimes, newvar)3432 if varinf.Ndims == 5:3433 for i in range(varinf.dims[1]):3434 for j in range(varinf.dims[2]):3435 for k in range(varinf.dims[3]):3436 for l in range(varinf.dims[4]):3437 newvar = newvarobj[:,i,j,k,l]3438 newvarobj[:,i,j,k,l] = seasonal_means(netcdftimes, newvar)3439 if varinf.Ndims == 6:3440 for i in range(varinf.dims[1]):3441 for j in range(varinf.dims[2]):3442 for k in range(varinf.dims[3]):3443 for l in range(varinf.dims[4]):3444 for m in range(varinf.dims[5]):3445 newvar = newvarobj[:,i,j,k,l,m]3446 newvarobj[:,i,j,k,l,m] = seasonal_means(netcdftimes, newvar)3447 else:3448 print errormsg3449 print ' seasmean: number of dimensions ', varinf.Ndims, ' not ready !!!!'3450 print errormsg3451 ncf.close()3452 quit(-1)3453 3454 ncfnew.sync()3455 ncfnew.close()3456 3457 print 'seasmean: Seasonal mean file "' + ofile + '" written!'3458 3459 3329 def load_variable_lastdims(var, prevdims, Nlastdims): 3460 3330 """ Function to load the last [Nlastdims] dimensions of a variable [var] at the other dimensions at [prevdims] … … 5278 5148 5279 5149 return Nvals 5280 5281 def get_namelist_vars(values, namelist):5282 """ Function to get namelist-like values ([varname] = [value])5283 get_namelist_vars(namelist)5284 values= [sectionname],[kout]5285 [sectionname]: name of the section from which one want the values ('all', for all)5286 [kout]: kind of output5287 'tex3': printed output as LaTeX table of three columns \verb+namelist_name+ & value5288 'column': printed output as namelist_name value5289 'dict': as two python dictionary object (namelistname, value and namelistname, sectionname)5290 namelist= namelist_like file to retrieve values5291 >>> get_namelist_vars('geogrid,dic','/home/lluis/etudes/domains/medic950116/namelist.wps')5292 {'e_sn': '32, 97,', 'stand_lon': '0.', 'opt_geogrid_tbl_path': "'./'", 'geog_data_path': "'/home/lluis/DATA/WRF/geog'", 'pole_lat': '90.0', 'ref_lat': '35.0,', 'map_proj': "'lat-lon',", 'parent_id': '1, 1,', 'geog_data_res': "'2m','2m',", 'e_we': '32, 112,', 'dx': '0.35,', 'dy': '0.35,', 'parent_grid_ratio': '1, 3,', 'pole_lon': '0.0', 'ref_lon': '20,', 'j_parent_start': '1, 17,', 'i_parent_start': '1, 31,'}5293 """5294 5295 fname = 'get_namelist_vars'5296 5297 # List of characters which split pairs name/value5298 valuessep = ['=']5299 # List of characters which indicate a comment5300 commentchars = ['#']5301 5302 if values == 'h':5303 print fname + '_____________________________________________________________'5304 print get_namelist_vars.__doc__5305 quit()5306 5307 expectargs = '[sectionname],[kout]'5308 check_arguments(fname,values,expectargs,',')5309 5310 secname = values.split(',')[0]5311 kout = values.split(',')[1]5312 5313 if not os.path.isfile(namelist):5314 print errormsg5315 print ' ' + fname + ": namelist file '" + namelist + "' does not exist !!"5316 quit(-1)5317 5318 ncml = open(namelist, 'r')5319 5320 sections = {}5321 namelistvals = {}5322 namelistsecs = {}5323 sectionnames = []5324 namessec = []5325 allnames = []5326 namelistvalssec = {}5327 namelistsecssec = {}5328 nmlname = ''5329 sectionname = ''5330 5331 for line in ncml:5332 linevals = reduce_spaces(line)5333 Nvals = len(linevals)5334 5335 if Nvals >= 1 and linevals[0][0:1] == '&':5336 if len(sectionnames) > 1:5337 sections[sectionname] = namessec5338 5339 sectionname = linevals[0][1:len(linevals[0])+1]5340 # print ' ' + fname + ": new section '" + sectionname + "' !!!"5341 sectionnames.append(sectionname)5342 namessec = []5343 nmlname = ''5344 elif Nvals >= 1 and not searchInlist(commentchars,linevals[0][0:1]):5345 if Nvals >= 3 and searchInlist(valuessep,linevals[1]):5346 nmlname = linevals[0]5347 nmlval = numVector_String(linevals[2:Nvals],' ')5348 elif Nvals == 1:5349 for valsep in valuessep:5350 if linevals[0].find(valsep) != -1:5351 nmlname = linevals[0].split(valsep)[0]5352 nmlval = linevals[0].split(valsep)[1]5353 break5354 elif Nvals == 2:5355 for valsep in valuessep:5356 if linevals[0].find(valsep) != -1:5357 nmlname = linevals[0].split(valsep)[0]5358 nmlval = linevals[1]5359 break5360 elif linevals[1].find(valsep) != -1:5361 nmlname = linevals[0]5362 nmlval = linevals[1].split(valsep)[0]5363 break5364 else:5365 print warnmsg5366 print ' ' + fname + ': wrong number of values', Nvals, \5367 'in the namelist line!'5368 print ' line: ',line5369 print ' line values:',linevals5370 # quit(-1)5371 5372 namelistvals[nmlname] = nmlval5373 namelistsecs[nmlname] = sectionname5374 5375 namessec.append(nmlname)5376 allnames.append(nmlname)5377 5378 if len(sectionname) > 1:5379 sections[sectionname] = namessec5380 5381 if secname != 'all':5382 if not searchInlist(sections.keys(),secname):5383 print errormsg5384 print ' ' + fname + ": section '" + values + "' does not exist !!"5385 print ' only found:',sectionnames5386 quit(-1)5387 5388 namestouse = []5389 for nml in allnames:5390 for nnml in sections[secname]:5391 namelistvalssec[nnml] = namelistvals[nnml]5392 namelistsecssec[nnml] = secname5393 if nml == nnml: namestouse.append(nml)5394 else:5395 namestouse = allnames5396 namelistvalssec = namelistvals5397 namelistsecssec = namelistsecs5398 5399 if kout == 'tex3':5400 ofile='get_namelist_vars_3col.tex'5401 fobj = open(ofile, 'w')5402 5403 vals = namestouse5404 Nvals = len(vals)5405 Nvals3 = int(Nvals/3)5406 latextab = '\\begin{center}\n\\begin{tabular}{lclclc}\n'5407 for il in range(2):5408 latextab = latextab + '{\\bfseries{name}} & {\\bfseries{value}} & '5409 latextab= latextab+ '{\\bfseries{name}} & {\\bfseries{value}} \\\\ \\hline\n'5410 5411 if np.mod(Nvals,3) != 0:5412 Nvals0 = Nvals - np.mod(Nvals,3)5413 else:5414 Nvals0 = Nvals5415 5416 for ival in range(0,Nvals0,3):5417 line = ''5418 print ' ival:',ival5419 for il in range(2):5420 line = line + '\\verb+' + vals[ival+il] + '+ & ' + \5421 namelistvalssec[vals[ival+il]].replace('_','\\_') +' & '5422 line = line + '\\verb+' + vals[ival+2] + '+ & ' + \5423 namelistvalssec[vals[ival+2]].replace('_','\\_') + ' \\\\\n'5424 latextab = latextab + line5425 5426 latextab = latextab + '%not multiple of three!!!!\n'5427 print 'mod:', np.mod(Nvals,3),Nvals0,Nvals5428 if np.mod(Nvals,3) != 0:5429 ival = Nvals05430 line = ''5431 for il in range(np.mod(Nvals,3)):5432 print 'ival:',ival + il5433 line = line + '\\verb+' + vals[ival+il] + '+ & ' + \5434 namelistvalssec[vals[ival+il]].replace('_','\\_') + ' & '5435 for il in range(2-np.mod(Nvals,3)):5436 line = line + ' & & '5437 latextab = latextab + line + ' & \\\\\n'5438 latextab = latextab + '\\end{tabular}\n\\end{center}\n'5439 5440 # print latextab5441 fobj.write(latextab)5442 5443 fobj.close()5444 print fname + ": successful writen '" + ofile + "' LaTeX tale file !!"5445 5446 return5447 elif kout == 'column':5448 for dictv in namestouse:5449 print dictv + ' = ' + namelistvalssec[dictv]5450 return5451 elif kout == 'dict':5452 return namelistvalssec, namelistsecssec5453 else:5454 print errormsg5455 print ' ' + fname + ": kind of output '" + kout + "' not ready!!!"5456 quit(-1)5457 5458 return5459 5460 def WRF_d0Nref(values, geofold):5461 """ Function for the generation of an extra WRF domain from a given one5462 field_stats(values, ncfile, varn)5463 [values]= [namelist],[minLON],[minLAT],[maxLON],[maxLAT],[Ndomref],[factor],[geogres]5464 [namelist]: namelist.wps to use5465 [minLON],[minLAT]: minimum longitude and latitude5466 [maxLON],[maxLAT]: maximum longitude and latitude5467 [Ndomref]: domain reference number5468 [factor]: resolution factor with respect d015469 [geogres]: which topography resolution to use5470 [geofold]= folder where to found the geo_em.d0[N-1].nc file5471 """5472 5473 fname='WRF_d0Nref'5474 5475 if values == 'h':5476 print fname + '_____________________________________________________________'5477 print WRF_d0Nref.__doc__5478 quit()5479 5480 expectargs = '[namelist],[minLON],[minLAT],[maxLON],[maxLAT],[Ndomref],[factor],'5481 expectargs = expectargs + '[geogres]'5482 5483 check_arguments(fname,values,expectargs,',')5484 5485 namelist = values.split(',')[0]5486 minLON = np.float(values.split(',')[1])5487 minLAT = np.float(values.split(',')[2])5488 maxLON = np.float(values.split(',')[3])5489 maxLAT = np.float(values.split(',')[4])5490 Ndomref = int(values.split(',')[5])5491 factor = int(values.split(',')[6])5492 geogres = values.split(',')[7]5493 5494 onml = 'namelist.wps_d0' + str(Ndomref+1)5495 5496 # Namelist variables to which new value is a copy of the last one5497 repeatvalue = ['start_date' ,'end_date']5498 # Namelist variables to which value is increased by 1 (single value)5499 add1 = ['max_dom']5500 # Namelist variables to which new value is an increase by 1 of the last one5501 add1value = ['parent_id']5502 5503 # ncfile = geofold + '/geo_em.d' + zeros(Ndomref,2) + '.nc'5504 ncfile = geofold + '/geo_em.d0' + str(Ndomref) + '.nc'5505 5506 if not os.path.isfile(ncfile):5507 print errormsg5508 print ' ' + fname + ': geo_em file "' + ncfile + '" does not exist !!'5509 quit(-1)5510 5511 ncobj = NetCDFFile(ncfile, 'r')5512 5513 nlon='XLONG_M'5514 nlat='XLAT_M'5515 5516 lonobj = ncobj.variables[nlon]5517 latobj = ncobj.variables[nlat]5518 5519 lon = lonobj[0,:,:]5520 lat = latobj[0,:,:]5521 5522 ncobj.close()5523 5524 diffmin = np.sqrt((lon - minLON)**2. + (lat - minLAT)**2.)5525 diffmax = np.sqrt((lon - maxLON)**2. + (lat - maxLAT)**2.)5526 5527 posdiffmin = index_mat(diffmin,np.min(diffmin))5528 posdiffmax = index_mat(diffmax,np.min(diffmax))5529 # print 'min vals. min:',np.min(diffmin),'max:',np.min(diffmax)5530 5531 # print 'min:', minLON, ',', minLAT, ':', posdiffmin, '.', lon[tuple(posdiffmin)], \5532 # ',', lat[tuple(posdiffmin)]5533 # print 'max:', maxLON, ',', maxLAT, ':', posdiffmax, '.', lon[tuple(posdiffmax)], \5534 # ',', lat[tuple(posdiffmax)]5535 5536 print ' ' + fname +': coordinates of the SW corner:', posdiffmin, ' NE corner:',\5537 posdiffmax5538 5539 nmlobj = open(namelist, 'r')5540 onmlobj = open(onml, 'w')5541 for line in nmlobj:5542 listline = reduce_spaces(line)5543 nvals = len(listline)5544 if nvals > 0:5545 if searchInlist(add1,listline[0]):5546 nmlval = int(listline[nvals-1].replace(',','')) + 15547 onmlobj.write(' ' + listline[0] + ' = ' + str(nmlval) + ',\n')5548 elif searchInlist(add1value,listline[0]):5549 if Ndomref == 1:5550 nmlval = 15551 else:5552 nmlval = int(listline[nvals-1].replace(',','')) + 15553 onmlobj.write(' ' + listline[0] + ' = ' + \5554 numVector_String(listline[2:nvals+1], ' ') + ' ' +str(nmlval)+',\n')5555 elif searchInlist(repeatvalue,listline[0]):5556 nmlval = listline[nvals-1]5557 onmlobj.write(' ' + listline[0] + ' = ' + \5558 numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+'\n')5559 elif listline[0] == 'parent_grid_ratio':5560 nmlval = factor5561 onmlobj.write(' ' + listline[0] + ' = ' + \5562 numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n')5563 elif listline[0] == 'i_parent_start':5564 nmlval = posdiffmin[1] - 105565 onmlobj.write(' ' + listline[0] + ' = ' + \5566 numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n')5567 elif listline[0] == 'j_parent_start':5568 nmlval = posdiffmin[0] - 105569 onmlobj.write(' ' + listline[0] + ' = ' + \5570 numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n')5571 elif listline[0] == 'e_we':5572 nmlval = (posdiffmax[1] - posdiffmin[1] + 20)*factor5573 nmlval = nmlval + np.mod(nmlval,factor) + 15574 onmlobj.write(' ' + listline[0] + ' = ' + \5575 numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n')5576 elif listline[0] == 'e_sn':5577 nmlval = (posdiffmax[0] - posdiffmin[0] + 20)*factor5578 nmlval = nmlval + np.mod(nmlval,factor) + 15579 onmlobj.write(' ' + listline[0] + ' = ' + \5580 numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n')5581 elif listline[0] == 'geog_data_res':5582 nmlval = "'" + geogres + "'"5583 onmlobj.write(' ' + listline[0] + ' = ' + \5584 numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n')5585 else:5586 onmlobj.write(line)5587 else:5588 onmlobj.write('\n')5589 5590 nmlobj.close()5591 onmlobj.close()5592 5593 print fname + ": successfully written new namelist '" + onml + "' !!"5594 5595 return5596 5150 5597 5151 def coincident_CFtimes(tvalB, tunitA, tunitB): -
trunk/tools/nc_var.py
r759 r762 171 171 ncvar.get_attribute(opts.values, opts.ncfile, opts.varname) 172 172 elif oper == 'get_namelist_vars': 173 ncvar.get_namelist_vars(opts.values, opts.ncfile)173 gen.get_namelist_vars(opts.values, opts.ncfile) 174 174 elif oper == 'getvalues_lonlat': 175 175 ncvar.getvalues_lonlat(opts.values, opts.ncfile) -
trunk/tools/nc_var_tools.py
r761 r762 824 824 if not os.path.isfile(ncfile): 825 825 print errormsg 826 print ' ' + fname + ': File "' + ncfile + '" does not exist !!'826 print ' ' + fname +": File '" + ncfile + "' does not exist !!" 827 827 print errormsg 828 828 quit(-1) … … 1288 1288 return 1289 1289 1290 def seasmean(timename, filename, varn): 1291 """ Function to compute the seasonal mean of a variable 1292 timename= name of the variable time in the file 1293 filename= netCDF file name 1294 varn= name of the variable 1295 """ 1296 fillValue=1.e20 1297 1298 ncf = NetCDFFile(filename,'a') 1299 ofile = 'seasmean_' + varn + '.nc' 1300 1301 if not ncf.variables.has_key(varn): 1302 print errormsg 1303 print ' seasmean: File "' + filename + '" does not have variable ' + varn + ' !!!!' 1304 print errormsg 1305 ncf.close() 1306 quit(-1) 1307 1308 varobj = ncf.variables[varn] 1309 varinf = variable_inf(varobj) 1310 timeobj = ncf.variables[timename] 1311 timeinf = cls_time_information(ncf, timename) 1312 1313 timevals=timeobj[:] 1314 netcdftimes = netCDFdatetime_realdatetime(timeinf.units + ' since ' + \ 1315 timeinf.Urefdate, timeinf.calendar, timevals) 1316 1317 timeseasons=times_4seasons(netcdftimes, True) 1318 1319 timeseasvals=seasonal_means(netcdftimes, timevals) 1320 1321 ncfnew = NetCDFFile(ofile,'w') 1322 ncfnew.createDimension('seastime', timeinf.dimt/4) 1323 ncfnew.createDimension('seas', 4) 1324 1325 newvarobj = ncfnew.createVariable('seastime', 'f4', ('seastime', 'seas',), \ 1326 fill_value=fillValue) 1327 newvarobj[:]=timeseasvals 1328 attr = newvarobj.setncattr('calendar', timeinf.calendar) 1329 attr = newvarobj.setncattr('units', timeinf.units) 1330 1331 newvarobj = ncfnew.createVariable('seasn', str, ('seas')) 1332 attr = newvarobj.setncattr('standard_name', 'seasn') 1333 attr = newvarobj.setncattr('long_name', 'name of the season') 1334 attr = newvarobj.setncattr('units', '3-months') 1335 newvarobj[0]='DJF' 1336 newvarobj[1]='MAM' 1337 newvarobj[2]='JJA' 1338 newvarobj[3]='SON' 1339 1340 newdims=[] 1341 idim = 0 1342 1343 for ndim in varinf.dimns: 1344 if ndim == timename: 1345 newdims.append(unicode('seastime')) 1346 if not idim == 0: 1347 print errormsg 1348 print ' ' + fname + ': File "' + filename + '" does not have ' + \ 1349 'time dimension "' + timename + '" as the first one. It has it as #'\ 1350 , idim, ' !!!!' 1351 ncf.close() 1352 quit(-1) 1353 else: 1354 newdims.append(ndim) 1355 1356 if not ncfnew.dimensions.has_key(ndim): 1357 ncfnew.sync() 1358 ncfnew.close() 1359 ncf.close() 1360 1361 fdimadd(filename + ',' + ndim, ofile) 1362 ncf = NetCDFFile(filename,'r') 1363 ncfnew = NetCDFFile(ofile,'a') 1364 1365 print ncfnew.dimensions 1366 namedims=tuple(newdims) 1367 print namedims 1368 1369 varobj = ncf.variables[varn] 1370 varinf = variable_inf(varobj) 1371 1372 newvarobj=ncfnew.createVariable(varn + '_seasmean', 'f4', namedims, \ 1373 fill_value=fillValue) 1374 attr = newvarobj.setncattr('standard_name', varn + '_seasmean') 1375 attr = newvarobj.setncattr('long_name', 'seasonal mean of ' + varn) 1376 attr = newvarobj.setncattr('units', varinf.units) 1377 1378 newvar = np.ones(varinf.dims[0], dtype=varinf.dtype) 1379 if varinf.Ndims == 1: 1380 newvar = newvarobj[:] 1381 newvarobj[:] = seasonal_means(netcdftimes, newvar) 1382 if varinf.Ndims == 2: 1383 for i in range(varinf.dims[1]): 1384 newvar = newvarobj[:,i] 1385 newvarobj[:,i] = seasonal_means(netcdftimes, newvar) 1386 if varinf.Ndims == 3: 1387 for i in range(varinf.dims[1]): 1388 for j in range(varinf.dims[2]): 1389 newvar = newvarobj[:,i,j] 1390 newvarobj[:,i,j] = seasonal_means(netcdftimes, newvar) 1391 if varinf.Ndims == 4: 1392 for i in range(varinf.dims[1]): 1393 for j in range(varinf.dims[2]): 1394 for k in range(varinf.dims[3]): 1395 newvar = newvarobj[:,i,j,k] 1396 newvarobj[:,i,j,k] = seasonal_means(netcdftimes, newvar) 1397 if varinf.Ndims == 5: 1398 for i in range(varinf.dims[1]): 1399 for j in range(varinf.dims[2]): 1400 for k in range(varinf.dims[3]): 1401 for l in range(varinf.dims[4]): 1402 newvar = newvarobj[:,i,j,k,l] 1403 newvarobj[:,i,j,k,l] = seasonal_means(netcdftimes, newvar) 1404 if varinf.Ndims == 6: 1405 for i in range(varinf.dims[1]): 1406 for j in range(varinf.dims[2]): 1407 for k in range(varinf.dims[3]): 1408 for l in range(varinf.dims[4]): 1409 for m in range(varinf.dims[5]): 1410 newvar = newvarobj[:,i,j,k,l,m] 1411 newvarobj[:,i,j,k,l,m] = seasonal_means(netcdftimes, newvar) 1412 else: 1413 print errormsg 1414 print ' seasmean: number of dimensions ', varinf.Ndims, ' not ready !!!!' 1415 print errormsg 1416 ncf.close() 1417 quit(-1) 1418 1419 ncfnew.sync() 1420 ncfnew.close() 1421 1422 print 'seasmean: Seasonal mean file "' + ofile + '" written!' 1423 1424 return 1425 1290 1426 def ivars(ncfile): 1291 1427 """Give all the variable names of a file … … 3095 3231 3096 3232 arguments = '[Nflipdim]:[flipdim]' 3097 check_arguments(fname, values, arguments, ':')3233 gen.check_arguments(fname, values, arguments, ':') 3098 3234 3099 3235 ncf = NetCDFFile(filename,'a') … … 3104 3240 if not ncf.variables.has_key(varn): 3105 3241 print errormsg 3106 print ' flipdim: File "' + filename + '" does not have variable ' + varn + ' !!!!' 3242 print ' ' + fname + ': File "' + filename + '" does not have variable ' +\ 3243 varn + ' !!!!' 3107 3244 print errormsg 3108 3245 ncf.close() … … 3114 3251 if varinf.Ndims < Nflipdim: 3115 3252 print errormsg 3116 print ' flipdim: variable "' + varn + '" has less dimensions ', varinf.Ndims, 'than the required to flip "', Nflipdim, '!!!!'3117 print errormsg3253 print ' ' + fname + ': variable "' + varn + '" has less dimensions ', \ 3254 varinf.Ndims, 'than the required to flip "', Nflipdim, '!!!!' 3118 3255 quit(-1) 3119 3256 3120 3257 if flipdim == 'yes': 3121 3258 flipdimname = varinf.dimns[Nflipdim] 3122 print ' flipdim: Flipping also associated dimension variable "' + flipdimname + '"' 3259 print ' ' + fname + ': Flipping also associated dimension variable "' + \ 3260 flipdimname + '"' 3123 3261 3124 3262 flipdim = ncf.variables[flipdimname] … … 3138 3276 else: 3139 3277 print errormsg 3140 print ' flipdim: dimension to flip has ', len(flipdim.shape), ' dimensions, not ready to be flipped !!!'3141 print errormsg3278 print ' ' + fname + ': dimension to flip has ', len(flipdim.shape), \ 3279 ' dimensions, not ready to be flipped !!!' 3142 3280 quit(-1) 3143 3281 … … 3234 3372 else: 3235 3373 print errormsg 3236 print ' flipdim: Number of dimensions ', varinf.Ndims, ' not ready!!!!'3237 print errormsg3374 print ' ' + fname + ': Number of dimensions ', varinf.Ndims, \ 3375 ' not ready!!!!' 3238 3376 quit(-1) 3239 3377 … … 4011 4149 return 4012 4150 4151 def get_namelist_vars(values, namelist): 4152 """ Function to get namelist-like values ([varname] = [value]) 4153 get_namelist_vars(namelist) 4154 values= [sectionname],[kout] 4155 [sectionname]: name of the section from which one want the values ('all', for all) 4156 [kout]: kind of output 4157 'tex3': printed output as LaTeX table of three columns \verb+namelist_name+ & value 4158 'column': printed output as namelist_name value 4159 'dict': as two python dictionary object (namelistname, value and namelistname, sectionname) 4160 namelist= namelist_like file to retrieve values 4161 >>> get_namelist_vars('geogrid,dic','/home/lluis/etudes/domains/medic950116/namelist.wps') 4162 {'e_sn': '32, 97,', 'stand_lon': '0.', 'opt_geogrid_tbl_path': "'./'", 'geog_data_path': "'/home/lluis/DATA/WRF/geog'", 'pole_lat': '90.0', 'ref_lat': '35.0,', 'map_proj': "'lat-lon',", 'parent_id': '1, 1,', 'geog_data_res': "'2m','2m',", 'e_we': '32, 112,', 'dx': '0.35,', 'dy': '0.35,', 'parent_grid_ratio': '1, 3,', 'pole_lon': '0.0', 'ref_lon': '20,', 'j_parent_start': '1, 17,', 'i_parent_start': '1, 31,'} 4163 """ 4164 4165 fname = 'get_namelist_vars' 4166 4167 # List of characters which split pairs name/value 4168 valuessep = ['='] 4169 # List of characters which indicate a comment 4170 commentchars = ['#'] 4171 4172 if values == 'h': 4173 print fname + '_____________________________________________________________' 4174 print get_namelist_vars.__doc__ 4175 quit() 4176 4177 expectargs = '[sectionname],[kout]' 4178 check_arguments(fname,values,expectargs,',') 4179 4180 secname = values.split(',')[0] 4181 kout = values.split(',')[1] 4182 4183 if not os.path.isfile(namelist): 4184 print errormsg 4185 print ' ' + fname + ": namelist file '" + namelist + "' does not exist !!" 4186 quit(-1) 4187 4188 ncml = open(namelist, 'r') 4189 4190 sections = {} 4191 namelistvals = {} 4192 namelistsecs = {} 4193 sectionnames = [] 4194 namessec = [] 4195 allnames = [] 4196 namelistvalssec = {} 4197 namelistsecssec = {} 4198 nmlname = '' 4199 sectionname = '' 4200 4201 for line in ncml: 4202 linevals = reduce_spaces(line) 4203 Nvals = len(linevals) 4204 4205 if Nvals >= 1 and linevals[0][0:1] == '&': 4206 if len(sectionnames) > 1: 4207 sections[sectionname] = namessec 4208 4209 sectionname = linevals[0][1:len(linevals[0])+1] 4210 # print ' ' + fname + ": new section '" + sectionname + "' !!!" 4211 sectionnames.append(sectionname) 4212 namessec = [] 4213 nmlname = '' 4214 elif Nvals >= 1 and not searchInlist(commentchars,linevals[0][0:1]): 4215 if Nvals >= 3 and searchInlist(valuessep,linevals[1]): 4216 nmlname = linevals[0] 4217 nmlval = numVector_String(linevals[2:Nvals],' ') 4218 elif Nvals == 1: 4219 for valsep in valuessep: 4220 if linevals[0].find(valsep) != -1: 4221 nmlname = linevals[0].split(valsep)[0] 4222 nmlval = linevals[0].split(valsep)[1] 4223 break 4224 elif Nvals == 2: 4225 for valsep in valuessep: 4226 if linevals[0].find(valsep) != -1: 4227 nmlname = linevals[0].split(valsep)[0] 4228 nmlval = linevals[1] 4229 break 4230 elif linevals[1].find(valsep) != -1: 4231 nmlname = linevals[0] 4232 nmlval = linevals[1].split(valsep)[0] 4233 break 4234 else: 4235 print warnmsg 4236 print ' ' + fname + ': wrong number of values', Nvals, \ 4237 'in the namelist line!' 4238 print ' line: ',line 4239 print ' line values:',linevals 4240 # quit(-1) 4241 4242 namelistvals[nmlname] = nmlval 4243 namelistsecs[nmlname] = sectionname 4244 4245 namessec.append(nmlname) 4246 allnames.append(nmlname) 4247 4248 if len(sectionname) > 1: 4249 sections[sectionname] = namessec 4250 4251 if secname != 'all': 4252 if not searchInlist(sections.keys(),secname): 4253 print errormsg 4254 print ' ' + fname + ": section '" + values + "' does not exist !!" 4255 print ' only found:',sectionnames 4256 quit(-1) 4257 4258 namestouse = [] 4259 for nml in allnames: 4260 for nnml in sections[secname]: 4261 namelistvalssec[nnml] = namelistvals[nnml] 4262 namelistsecssec[nnml] = secname 4263 if nml == nnml: namestouse.append(nml) 4264 else: 4265 namestouse = allnames 4266 namelistvalssec = namelistvals 4267 namelistsecssec = namelistsecs 4268 4269 if kout == 'tex3': 4270 ofile='get_namelist_vars_3col.tex' 4271 fobj = open(ofile, 'w') 4272 4273 vals = namestouse 4274 Nvals = len(vals) 4275 Nvals3 = int(Nvals/3) 4276 latextab = '\\begin{center}\n\\begin{tabular}{lclclc}\n' 4277 for il in range(2): 4278 latextab = latextab + '{\\bfseries{name}} & {\\bfseries{value}} & ' 4279 latextab= latextab+ '{\\bfseries{name}} & {\\bfseries{value}} \\\\ \\hline\n' 4280 4281 if np.mod(Nvals,3) != 0: 4282 Nvals0 = Nvals - np.mod(Nvals,3) 4283 else: 4284 Nvals0 = Nvals 4285 4286 for ival in range(0,Nvals0,3): 4287 line = '' 4288 print ' ival:',ival 4289 for il in range(2): 4290 line = line + '\\verb+' + vals[ival+il] + '+ & ' + \ 4291 namelistvalssec[vals[ival+il]].replace('_','\\_') +' & ' 4292 line = line + '\\verb+' + vals[ival+2] + '+ & ' + \ 4293 namelistvalssec[vals[ival+2]].replace('_','\\_') + ' \\\\\n' 4294 latextab = latextab + line 4295 4296 latextab = latextab + '%not multiple of three!!!!\n' 4297 print 'mod:', np.mod(Nvals,3),Nvals0,Nvals 4298 if np.mod(Nvals,3) != 0: 4299 ival = Nvals0 4300 line = '' 4301 for il in range(np.mod(Nvals,3)): 4302 print 'ival:',ival + il 4303 line = line + '\\verb+' + vals[ival+il] + '+ & ' + \ 4304 namelistvalssec[vals[ival+il]].replace('_','\\_') + ' & ' 4305 for il in range(2-np.mod(Nvals,3)): 4306 line = line + ' & & ' 4307 latextab = latextab + line + ' & \\\\\n' 4308 latextab = latextab + '\\end{tabular}\n\\end{center}\n' 4309 4310 # print latextab 4311 fobj.write(latextab) 4312 4313 fobj.close() 4314 print fname + ": successful writen '" + ofile + "' LaTeX tale file !!" 4315 4316 return 4317 elif kout == 'column': 4318 for dictv in namestouse: 4319 print dictv + ' = ' + namelistvalssec[dictv] 4320 return 4321 elif kout == 'dict': 4322 return namelistvalssec, namelistsecssec 4323 else: 4324 print errormsg 4325 print ' ' + fname + ": kind of output '" + kout + "' not ready!!!" 4326 quit(-1) 4327 4328 return 4329 4013 4330 def check_times_file(values, filename, timen): 4014 4331 """ Function to check time-steps of a given file … … 4136 4453 Lchar = length of the string in the netCDF file 4137 4454 """ 4455 fname = 'writing_str_nc' 4138 4456 4139 4457 Nvals = len(values) … … 4150 4468 charvals[ich] = stringv[ich:ich+1] 4151 4469 4470 print 'Lluis: ' + fname + 'stringv:', stringv, 'charvals:', charvals 4471 quit() 4152 4472 varo[iv,:] = charvals 4153 4473 … … 8534 8854 8535 8855 #file_oper_alongdims('time:-1|z:-1|x:-1|y:-1,time:y,mean,pressure:lat', '/home/lluis/etudes/WRF_LMDZ/WaquaL/WRF_LMDZ/AR40/vertical_interpolation_WRFp.nc', 'WRFt') 8856 8857 def WRF_d0Nref(values, geofold): 8858 """ Function for the generation of an extra WRF domain from a given one 8859 field_stats(values, ncfile, varn) 8860 [values]= [namelist],[minLON],[minLAT],[maxLON],[maxLAT],[Ndomref],[factor],[geogres] 8861 [namelist]: namelist.wps to use 8862 [minLON],[minLAT]: minimum longitude and latitude 8863 [maxLON],[maxLAT]: maximum longitude and latitude 8864 [Ndomref]: domain reference number 8865 [factor]: resolution factor with respect d01 8866 [geogres]: which topography resolution to use 8867 [geofold]= folder where to found the geo_em.d0[N-1].nc file 8868 """ 8869 8870 fname='WRF_d0Nref' 8871 8872 if values == 'h': 8873 print fname + '_____________________________________________________________' 8874 print WRF_d0Nref.__doc__ 8875 quit() 8876 8877 expectargs = '[namelist],[minLON],[minLAT],[maxLON],[maxLAT],[Ndomref],[factor],' 8878 expectargs = expectargs + '[geogres]' 8879 8880 check_arguments(fname,values,expectargs,',') 8881 8882 namelist = values.split(',')[0] 8883 minLON = np.float(values.split(',')[1]) 8884 minLAT = np.float(values.split(',')[2]) 8885 maxLON = np.float(values.split(',')[3]) 8886 maxLAT = np.float(values.split(',')[4]) 8887 Ndomref = int(values.split(',')[5]) 8888 factor = int(values.split(',')[6]) 8889 geogres = values.split(',')[7] 8890 8891 onml = 'namelist.wps_d0' + str(Ndomref+1) 8892 8893 # Namelist variables to which new value is a copy of the last one 8894 repeatvalue = ['start_date' ,'end_date'] 8895 # Namelist variables to which value is increased by 1 (single value) 8896 add1 = ['max_dom'] 8897 # Namelist variables to which new value is an increase by 1 of the last one 8898 add1value = ['parent_id'] 8899 8900 # ncfile = geofold + '/geo_em.d' + zeros(Ndomref,2) + '.nc' 8901 ncfile = geofold + '/geo_em.d0' + str(Ndomref) + '.nc' 8902 8903 if not os.path.isfile(ncfile): 8904 print errormsg 8905 print ' ' + fname + ': geo_em file "' + ncfile + '" does not exist !!' 8906 quit(-1) 8907 8908 ncobj = NetCDFFile(ncfile, 'r') 8909 8910 nlon='XLONG_M' 8911 nlat='XLAT_M' 8912 8913 lonobj = ncobj.variables[nlon] 8914 latobj = ncobj.variables[nlat] 8915 8916 lon = lonobj[0,:,:] 8917 lat = latobj[0,:,:] 8918 8919 ncobj.close() 8920 8921 diffmin = np.sqrt((lon - minLON)**2. + (lat - minLAT)**2.) 8922 diffmax = np.sqrt((lon - maxLON)**2. + (lat - maxLAT)**2.) 8923 8924 posdiffmin = index_mat(diffmin,np.min(diffmin)) 8925 posdiffmax = index_mat(diffmax,np.min(diffmax)) 8926 # print 'min vals. min:',np.min(diffmin),'max:',np.min(diffmax) 8927 8928 # print 'min:', minLON, ',', minLAT, ':', posdiffmin, '.', lon[tuple(posdiffmin)], \ 8929 # ',', lat[tuple(posdiffmin)] 8930 # print 'max:', maxLON, ',', maxLAT, ':', posdiffmax, '.', lon[tuple(posdiffmax)], \ 8931 # ',', lat[tuple(posdiffmax)] 8932 8933 print ' ' + fname +': coordinates of the SW corner:', posdiffmin, ' NE corner:',\ 8934 posdiffmax 8935 8936 nmlobj = open(namelist, 'r') 8937 onmlobj = open(onml, 'w') 8938 for line in nmlobj: 8939 listline = reduce_spaces(line) 8940 nvals = len(listline) 8941 if nvals > 0: 8942 if searchInlist(add1,listline[0]): 8943 nmlval = int(listline[nvals-1].replace(',','')) + 1 8944 onmlobj.write(' ' + listline[0] + ' = ' + str(nmlval) + ',\n') 8945 elif searchInlist(add1value,listline[0]): 8946 if Ndomref == 1: 8947 nmlval = 1 8948 else: 8949 nmlval = int(listline[nvals-1].replace(',','')) + 1 8950 onmlobj.write(' ' + listline[0] + ' = ' + \ 8951 numVector_String(listline[2:nvals+1], ' ') + ' ' +str(nmlval)+',\n') 8952 elif searchInlist(repeatvalue,listline[0]): 8953 nmlval = listline[nvals-1] 8954 onmlobj.write(' ' + listline[0] + ' = ' + \ 8955 numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+'\n') 8956 elif listline[0] == 'parent_grid_ratio': 8957 nmlval = factor 8958 onmlobj.write(' ' + listline[0] + ' = ' + \ 8959 numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n') 8960 elif listline[0] == 'i_parent_start': 8961 nmlval = posdiffmin[1] - 10 8962 onmlobj.write(' ' + listline[0] + ' = ' + \ 8963 numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n') 8964 elif listline[0] == 'j_parent_start': 8965 nmlval = posdiffmin[0] - 10 8966 onmlobj.write(' ' + listline[0] + ' = ' + \ 8967 numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n') 8968 elif listline[0] == 'e_we': 8969 nmlval = (posdiffmax[1] - posdiffmin[1] + 20)*factor 8970 nmlval = nmlval + np.mod(nmlval,factor) + 1 8971 onmlobj.write(' ' + listline[0] + ' = ' + \ 8972 numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n') 8973 elif listline[0] == 'e_sn': 8974 nmlval = (posdiffmax[0] - posdiffmin[0] + 20)*factor 8975 nmlval = nmlval + np.mod(nmlval,factor) + 1 8976 onmlobj.write(' ' + listline[0] + ' = ' + \ 8977 numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n') 8978 elif listline[0] == 'geog_data_res': 8979 nmlval = "'" + geogres + "'" 8980 onmlobj.write(' ' + listline[0] + ' = ' + \ 8981 numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n') 8982 else: 8983 onmlobj.write(line) 8984 else: 8985 onmlobj.write('\n') 8986 8987 nmlobj.close() 8988 onmlobj.close() 8989 8990 print fname + ": successfully written new namelist '" + onml + "' !!" 8991 8992 return 8536 8993 8537 8994 def WRF_CFtime_creation(values, ncfile, varn):
Note: See TracChangeset
for help on using the changeset viewer.