Changeset 747 in lmdz_wrf


Ignore:
Timestamp:
May 4, 2016, 11:19:50 AM (9 years ago)
Author:
lfita
Message:

Ready version to test and suffer with the use of `generic_tools'.

Now each function (when used) will demand the readiness with gen

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/nc_var_tools.py

    r746 r747  
    601601                  ncf = NetCDFFile(ncfile,'a')
    602602
    603     return
     603  return
    604604
    605605def chvarname(values, ncfile, varn):
     
    18771877                self.dimx=self.dims[3]
    18781878
    1879     return
     1879        return
    18801880
    18811881def subyrs(values, ncfile, varn):
     
    33193319    return loadvar
    33203320
    3321 AQUI AQUI AQUI AQUI AQUI AQUI AQUI
    3322 
    3323 
    33243321def fill_ncvariable_lastdims(ncf, varn, prevdims, Nlastdims, fillvals):
    33253322    """ Function to fill the last [Nlastdims] dimensions of a variable [varn] from a netCDF object at the other dimensions at [prevdims]
     
    33933390        quit(-1)
    33943391
     3392    return
     3393
    33953394def maskvar(values, filename, varn):
    33963395    """ Function to mask a variable using a mask. It is assumed that mask[...,dimM,dimJ,dimK] and
     
    35403539    print 'masked file "' + ofile + '" generated !!!'
    35413540
    3542 def lonlat2D(ncfobj, lonn, latn):
    3543     """ Function to create 2D matricies of longitudes and latitudes from the file
    3544     ncfobj= netCDF object file
    3545     lonn= longitude name
    3546     latn= latitude name
    3547     """
    3548     fname='lonlat2D'
    3549 
    3550     lonvar = ncfobj.variables[lonn]
    3551     latvar = ncfobj.variables[latn]
    3552 
    3553     loninf = variable_inf(lonvar)
    3554     latinf = variable_inf(latvar)
    3555 
    3556     if loninf.Ndims == 1:
    3557         lonv = lonvar[:]
    3558         latv = latvar[:]
    3559         dx=loninf.dims[0]
    3560         dy=latinf.dims[0]
    3561         lonval = np.zeros((dy, dx), dtype=float)   
    3562         latval = np.zeros((dy, dx), dtype=float)   
    3563         for iy in range(dy):
    3564             lonval[iy,:] = lonv
    3565         for ix in range(dx):
    3566             latval[:,ix] = latv
    3567     elif loninf.Ndims == 2:
    3568         lonval = lonvar[:]
    3569         latval = latvar[:]
    3570     elif loninf.Ndims == 3:
    3571         lonval = lonvar[0,:,:]
    3572         latval = latvar[0,:,:]
    3573     else:
    3574         print errormsg
    3575         print '  ' + fname + ' dimension ', lonvar.Ndims, ' of the lon/lat matrices not ready !!!!'
    3576 
    3577     return lonval, latval
    3578 
    3579 def indices_mask(mask):
    3580     """ Function to retrieve the indices from a 2D mask
    3581     mask= 2D mask matrix
    3582     mat=np.array(range(100), dtype=float).reshape((10,10))
    3583     >>> mask1= mat >= 45.
    3584     >>> mask2= mat <= 55.
    3585     >>> mask = mask1 * mask2
    3586     indices_mask(mask)
    3587     [[4 5]
    3588     [4 6]
    3589     [4 7]
    3590     [4 8]
    3591     [4 9]
    3592     [5 0]
    3593     [5 1]
    3594     [5 2]
    3595     [5 3]
    3596     [5 4]
    3597     [5 5]]
    3598     """
    3599     dy=mask.shape[0]
    3600     dx=mask.shape[1]
    3601 
    3602     Nptmask = np.sum(mask)
    3603     maskindices = np.zeros((Nptmask,2), dtype=int)
    3604     ij=0
    3605     for j in range(dy):
    3606         for i in range(dx):
    3607             if mask[j,i] == True:
    3608                 maskindices[ij,0] = j
    3609                 maskindices[ij,1] = i
    3610                 ij = ij + 1
    3611 
    3612     return maskindices
     3541    return
    36133542
    36143543def chgtimestep(values, origfile, varN):
     
    36913620    ncofile.close()
    36923621
     3622    return
     3623
    36933624def uploading_timestep(ncfile, varN, time_step):
    36943625    """ Function to upload a given time-step of a variable inside a netCDF
     
    38473778    fileobj.close()
    38483779
    3849 def typemod(value, typeval):
    3850     """ Function to give back a value in a given dtype
    3851     >>> print(typemod(8.2223, 'np.float64'))
    3852     <type 'numpy.float64'>
    3853     >>> print(typemod(8.2223, 'tuple'))
    3854     <type 'tuple'>
    3855     """
    3856     fname='typemod'
    3857 
    3858     if typeval == 'int':
    3859         return int(value)
    3860     elif typeval == 'long':
    3861         return long(value)
    3862     elif typeval == 'float':
    3863         return float(value)
    3864     elif typeval == 'complex':
    3865         return complex(value)
    3866     elif typeval == 'str':
    3867         return str(value)
    3868     elif typeval == 'bool':
    3869         return bool(value)
    3870     elif typeval == 'list':
    3871         newval = []
    3872         newval.append(value)
    3873         return newval
    3874     elif typeval == 'dic':
    3875         newval = {}
    3876         newval[value] = value
    3877         return newval
    3878     elif typeval == 'tuple':
    3879         newv = []
    3880         newv.append(value)
    3881         newval = tuple(newv)
    3882         return newval
    3883     elif typeval == 'np.int8':
    3884         return np.int8(value)
    3885     elif typeval == 'np.int16':
    3886         return np.int16(value)
    3887     elif typeval == 'np.int32':
    3888         return np.int32(value)
    3889     elif typeval == 'np.int64':
    3890         return np.int64(value)
    3891     elif typeval == 'np.uint8':
    3892         return np.uint8(value)
    3893     elif typeval == 'np.uint16':
    3894         return np.uint16(value)
    3895     elif typeval == 'np.np.uint32':
    3896         return np.uint32(value)
    3897     elif typeval == 'np.uint64':
    3898         return np.uint64(value)
    3899     elif typeval == 'np.float':
    3900         return np.float(value)
    3901     elif typeval == 'np.float16':
    3902         return np.float16(value)
    3903     elif typeval == 'np.float32':
    3904         return np.float32(value)
    3905     elif typeval == 'float32':
    3906         return np.float32(value)
    3907     elif typeval == 'np.float64':
    3908         return np.float64(value)
    3909     elif typeval == 'float64':
    3910         return np.float64(value)
    3911     elif typeval == 'np.complex':
    3912         return np.complex(value)
    3913     elif typeval == 'np.complex64':
    3914         return np.complex64(value)
    3915     elif typeval == 'np.complex128':
    3916         return np.complex128(value)
    3917     else:
    3918         print errormsg
    3919         print fname + ':  data type "' + typeval + '" is not ready !'
    3920         print errormsg
    3921         quit(-1)
     3780    return
    39223781
    39233782def addvals(values, filename, varN):
     
    40983957        quit(-1)   
    40993958
     3959    return
     3960
    41003961def TimeInf(filename, tname):
    41013962    """ Function to print all the information from the variable time
     
    41083969    fmtprinting_class(timeinf)
    41093970    ncfobj.close()
     3971
     3972    return
    41103973
    41113974def sorttimesmat(filename, tname):
     
    41514014    ncft.close()
    41524015
    4153 def diffdate_units(diffdate, units):
    4154     """ Function to transform a difference of dates to a certain units
    4155     diffdate = difference of dates (as timedelta)
    4156     units = units to transform: 'weeks', 'days', 'hours', 'minutes', 'seconds', 'miliseconds', 'nanoseconds'
    4157     >>> diffdate_units(dt.datetime(1976, 2, 17, 8, 32, 5) - dt.datetime(1949, 12, 1, 0, 0, 0), 'seconds')
    4158     827224325.0
    4159     """
    4160     fname = 'diffdate_units'
    4161 
    4162     if units == 'weeks':
    4163         diffunits = diffdate.days/7. + diffdate.seconds/(3600.*24.*7.)
    4164     elif units == 'days':
    4165         diffunits = diffdate.days + diffdate.seconds/(3600.*24.)
    4166     elif units == 'hours':
    4167         diffunits = diffdate.days*24. + diffdate.seconds/(3600.)
    4168     elif units == 'minutes':
    4169         diffunits = diffdate.days*24.*60. + diffdate.seconds/(60.)
    4170     elif units == 'seconds':
    4171         diffunits = diffdate.days*24.*3600. + diffdate.seconds
    4172     elif units == 'miliseconds':
    4173         diffunits = diffdate.days*24.*3600.*1000. + diffdate.seconds*1000.
    4174     elif units == 'nanoseconds':
    4175         diffunits = diffdate.days*24.*3600.*1000000. + diffdate.seconds*1000000.
    4176     else:
    4177         print errormsg
    4178         print fname + ': time units "' + units + '" not ready!!!'
    4179         print errormsg
    4180         quit(-1)
    4181 
    4182     return diffunits
    4183 
    4184 def days_month(year,month):
    4185     """ Function to give the number of days of a month of a given year
    4186     >>> days_month(1976,2)
    4187     29
    4188     """
    4189     import datetime as dt
    4190 
    4191     date1=dt.date(year,month,1)
    4192     date2=dt.date(year,month+1,1)
    4193 
    4194     diffdate = date2-date1
    4195     return diffdate.days
    4196 
    4197 def mid_period(yr1,mon1,day1,hour1,min1,sec1,yr2,mon2,day2,hour2,min2,sec2):
    4198     """ Function to give the mid poiint of a period
    4199     >>> mid_period(1976,2,1,0,0,0,1976,3,1,0,0,0)
    4200     [1976    2   15   12    0    0]
    4201     """
    4202     import datetime as dt
    4203 
    4204     date1=dt.datetime(yr1,mon1,day1,hour1,min1,sec1)
    4205     date2=dt.datetime(yr2,mon2,day2,hour2,min2,sec2)
    4206 
    4207     diffdate = date2-date1
    4208     diffseconds = diffdate.days*24*3600 + diffdate.seconds
    4209     diff2 = dt.timedelta(seconds=diffseconds/2)
    4210     datenew = date1 + diff2
    4211     datenewvals = np.array([datenew.year, datenew.month, datenew.day, datenew.hour,  \
    4212       datenew.minute, datenew.second])
    4213 
    4214     return datenewvals
    4215 
    4216 def days_year(year):
    4217     """ Function to give the number of days of a year
    4218     >>> days_year(1976)
    4219     366
    4220     """
    4221     import datetime as dt
    4222 
    4223     date1=dt.date(year,1,1)
    4224     date2=dt.date(year+1,1,1)
    4225 
    4226     diffdate = date2-date1
    4227     return diffdate.days
    4228 
    4229 def days_period(yeari,yearf):
    4230     """ Function to give the number of days for a period
    4231     >>> days_period(1976,1980)
    4232     1827
    4233     """
    4234 
    4235     ndays=0   
    4236     for iyr in range(yearf-yeari+1):
    4237         ndays=ndays+days_year(yeari+iyr)
    4238 
    4239     return ndays
     4016    return
    42404017
    42414018def check_times_file(values, filename, timen):
     
    43564133                print matdates[it,:]
    43574134
     4135    return
     4136
    43584137def writing_str_nc(varo, values, Lchar):
    43594138    """ Function to write string values in a netCDF variable as a chain of 1char values
     
    44454224
    44464225    return strings
    4447 
    4448 class ysubsetstats(object):
    4449     """ Class to compute multi-year statistics of a given subset of values
    4450     values= values to use
    4451     dates=dates of the values in matrix format ([year], [month], [day], [hour], [minute], [second])
    4452     sec=section to use for the period='year', 'month', 'day', 'hour', 'minute', 'second'
    4453     vali=initial value of the period
    4454     valf=final value of the period
    4455     Nq= number of quantiles (20 for 5% bins, it is going to produce 21 values)
    4456     missval= missing value
    4457       self.Nvalues = Number of non masked values
    4458       self.min = minimum non masked value
    4459       self.max = maximum non masked value
    4460       self.mean = mean non masked value
    4461       self.mean2 = quandratic mean non masked value
    4462       self.stdev = standard deviation non masked value
    4463       self.quantiles = quantiles non masked value
    4464     """ 
    4465     def __init__(self, values, dates, sec, vali, valf, Nq, missVal):
    4466         import numpy.ma as ma
    4467 
    4468         fname = 'ysubsetstats'
    4469  
    4470         if values is None:
    4471             self.Nvalues = None
    4472             self.min = None
    4473 
    4474             self.max = None
    4475             self.mean = None
    4476             self.mean2 = None
    4477             self.stdev = None
    4478             self.quantiles = None
    4479 
    4480         else:
    4481             Nvalues = len(values)
    4482             Ndates = len(dates)
    4483 
    4484             if Nvalues != Ndates:
    4485                 print errormsg
    4486                 print fname + ': number of values ', Nvalues,' does not coincide with the number of dates ',Ndates, '!!!!!!'
    4487                 print errormsg
    4488                 quit(-1)
    4489 
    4490             initialsub = np.zeros(Nvalues, dtype=bool)
    4491             endsub = initialsub.copy()
    4492 
    4493             if missVal > 0.:
    4494                 valuesmask = ma.masked_greater_equal(values, missVal*0.9)
    4495             else:
    4496                 valuesmask = ma.masked_less_equal(values, missVal*0.9)
    4497 
    4498             if sec == 'year':
    4499                 isec = 0
    4500             elif sec == 'month':
    4501                 isec = 1
    4502             elif sec == 'day':
    4503                 isec = 2
    4504             elif sec == 'hour':
    4505                 isec = 3
    4506             elif sec == 'minute':
    4507                 isec = 4
    4508             elif sec == 'second':
    4509                 isec = 5
    4510             else:
    4511                 print errormsg
    4512                 print fname + ': sction "' + sec + '" not ready!!!!'
    4513                 print errormsg
    4514                 quit(-1)
    4515    
    4516             if vali < valf:
    4517                 timesmaskperi = ma.masked_less(dates[:,isec], vali)
    4518                 timesmaskperf = ma.masked_greater(dates[:,isec], valf)
    4519             else:
    4520                 timesmaskperi = ma.masked_less(dates[:,isec], valf)
    4521                 timesmaskperf = ma.masked_greater(dates[:,isec], vali)
    4522 
    4523             finalmask = valuesmask.mask+timesmaskperi.mask+timesmaskperf.mask
    4524             finalvalues = ma.array(values, mask=finalmask)
    4525 
    4526             finalvalues2 = finalvalues*finalvalues
    4527 
    4528             self.Nvalues = finalvalues.count()
    4529             self.min = finalvalues.min()
    4530             self.max = finalvalues.max()
    4531             self.mean = finalvalues.mean()
    4532             self.mean2 = finalvalues2.mean()
    4533             self.stdev = finalvalues.std()
    4534             self.quantiles = mask_quantiles(finalvalues, Nq)
    45354226
    45364227def remapnn(values, filename, varname):
     
    47864477
    47874478    print 'remapnn: new file "' + ofile + '" with remapped variable written !!'
     4479
     4480    return
    47884481
    47894482#remapnn('met_em.d01.1979-01-01_00:00:00.nc|XLONG_M,XLAT_M|east_weast,south_north|longitude,latitude|longitude,latitude', \
     
    49594652
    49604653    print 'remapnn: new file "' + ofile + '" with remapped variable written !!'
     4654
     4655    return
    49614656#remapnn('data/R1_CCRC_NARCliM_MOM_1950-2009_pracc.nc:lon,lat:lon,lat', 'data/AWAP_pre_1950-2009_pre_mask.nc', 'pre', 1. , 1.)
    49624657#quit()
     
    50934788    ncobj.close()
    50944789
    5095 def give_fix1dim_values(mat,iddim,dimval):
    5096     """ Function to return matrix values when one dimension has been removed at a
    5097       given value
    5098     mat = matrix
    5099     iddim = dimesion to remove (starting from 0 tacking the right most)
    5100     dimval = value of the dimension
    5101 
    5102     >>> matrix = np.array( (range(27)), dtype=np.float).reshape(3,3,3)
    5103     give_fix1dim_values(matrix,2,2)
    5104     [[[  0.   1.   2.]
    5105       [  3.   4.   5.]
    5106       [  6.   7.   8.]]
    5107 
    5108      [[  9.  10.  11.]
    5109       [ 12.  13.  14.]
    5110       [ 15.  16.  17.]]]
     4790    return
     4791
     4792def valmod_dim(values, ncfile, varn):
     4793    """ Function to modify the value of a variable at a given dimension and value
     4794    values = dimn,dimval,modins,modval1,[modval2,...]
     4795      dimn = name of the dimension
     4796      dimval = value of the dimension at which change the values
     4797      modins = instruction:
     4798        'sumc', add [modval1]
     4799        'subc', substraction [modval1]
     4800        'mulc', multiply by [modval1]
     4801        'divc', divide by [modval1]
     4802        'lowthres': modify all values below [modval1] to [modval2]
     4803        'upthres': modify all values above [modval1] to [modval2]
     4804    ncfile = netCDF file name
     4805    varn = name of the variable
     4806    >>> valmod_dim('num_metgrid_levels,10,mulc,-1','aqua_met-em_control.nc','PRES')
    51114807    """
    5112     fname='give_fix1dim_values'
    5113 
    5114 # Not working ma.squeeze
    5115 ##    import numpy.ma as ma
    5116 ##    print ma.squeeze(mat, axis = (idim,))
    5117    
    5118     matshape = mat.shape
    5119     mattype = mat.dtype
    5120     matmask = np.ones( tuple(matshape), dtype=bool)
     4808    fname = 'valmod_dim'
     4809
     4810    if values == '-h':
     4811        print """ Function to modify the value of a variable at a given dimension and value
     4812          values = dimn,dimval,modins,modval1,[modval2,...]
     4813          dimn = name of the dimension
     4814          dimval = value of the dimension at which change the values
     4815          modins = instruction:
     4816            'sumc', add [modval1]
     4817            'subc', substraction [modval1]
     4818            'mulc', multiply by [modval1]
     4819            'divc', divide by [modval1]
     4820            'lowthres': modify all values below [modval1] to [modval2]
     4821            'upthres': modify all values above [modval1] to [modval2]
     4822          ncfile = netCDF file name
     4823          varn = name of the variable
     4824          >>> valmod_dim('num_metgrid_levels,10,mulc,-1','aqua_met-em_control.nc','PRES')
     4825          """
     4826        quit()
     4827
     4828##  mat = np.array( (range(27)), dtype=np.float).reshape(3,3,3)
     4829
     4830    vals = values.split(',')
     4831    Lvals = len(vals)
     4832
     4833    dimn = vals[0]
     4834    dimval = np.int(vals[1])
     4835    modins = vals[2]
     4836    modval = np.float(vals[3])
     4837    newvalues = ','.join(vals[2:Lvals])
     4838
     4839    if not os.path.isfile(ncfile):
     4840      print errormsg
     4841      print '   valmod: File "' + ncfile + '" does not exist !!'
     4842      print errormsg
     4843      quit(-1)   
     4844
     4845    ncf = NetCDFFile(ncfile,'a')
     4846
     4847    if ncf.dimensions.has_key('plev'):
     4848      # removing pressure level from variable name
     4849      varn = re.sub("\d+", "", varn)
     4850
     4851    if not ncf.dimensions.has_key(dimn):
     4852      print errormsg
     4853      print '   ' + fname + ': File "' + ncfile + '" does not have dimension "' +    \
     4854        dimn + '" !!!!'
     4855      ncf.close()
     4856      quit(-1)
     4857
     4858    if not ncf.variables.has_key(varn):
     4859      print errormsg
     4860      print '   ' + fname + ': File "' + ncfile + '" does not have variable "' +     \
     4861        varn + '" !!!!'
     4862      ncf.close()
     4863      quit(-1)
     4864
     4865    varobj = ncf.variables[varn]
     4866    varinf = variable_inf(varobj)
     4867
     4868    varvals = varobj[:]
     4869
     4870# Dimension id
     4871    iddim=varinf.Ndims - 1
     4872    for idimn in varinf.dimns:
     4873#        print iddim, idimn
     4874        if dimn == idimn:
     4875            break
     4876
     4877        iddim = iddim - 1
     4878
     4879    matshape = varvals.shape
     4880    mattype = varvals.dtype
     4881    matmask = np.zeros( tuple(matshape), dtype=bool)
    51214882
    51224883    zerodims=np.ones( (6), dtype=int)
    51234884    Ndims = len(matshape)
     4885
    51244886    if Ndims > 6:
    51254887        print errmsg
     
    51294891    zerodims[5-Ndims+1:6] = matshape
    51304892
    5131     newdims = list(matshape)
    5132     newdims[Ndims-1-iddim] = matshape[iddim]-1
    5133 
    5134     mask = np.ones(tuple(zerodims), dtype=bool)
    5135     vals = np.zeros(tuple(zerodims), dtype=mattype)
    5136     vals[0:zerodims[0],0:zerodims[1],0:zerodims[2],0:zerodims[3],0:zerodims[4],
    5137       0:zerodims[5]] = mat
    5138 
    5139     for i5 in range(zerodims[5]):
    5140         for i4 in range(zerodims[4]):
    5141             for i3 in range(zerodims[3]):
    5142                 for i2 in range(zerodims[2]):
    5143                     for i1 in range(zerodims[1]):
    5144                         for i0 in range(zerodims[0]):
    5145 #                            print 'iddim:',iddim,'dimval:',dimval,'-->',i0,i1,i2,i3,i4,i5
    5146                             if iddim == 5 and dimval == i0:
    5147                                 mask[i0,i1,i2,i3,i4,i5] = False
    5148                             elif iddim == 4 and dimval == i1:
    5149                                 mask[i0,i1,i2,i3,i4,i5] = False
    5150                             elif iddim == 3 and dimval == i2:
    5151                                 mask[i0,i1,i2,i3,i4,i5] = False
    5152                             elif iddim == 2 and dimval == i3:
    5153                                 mask[i0,i1,i2,i3,i4,i5] = False
    5154                             elif iddim == 1 and dimval == i4:
    5155                                 mask[i0,i1,i2,i3,i4,i5] = False
    5156                             elif iddim == 0 and dimval == i5:
    5157                                 mask[i0,i1,i2,i3,i4,i5] = False
    5158 
    5159     newmat = vals[mask].reshape(tuple(newdims))
    5160 #    print 'newmat dim:',iddim,'val:',dimval,':',newdims,'______'
    5161 #    print newmat
    5162    
    5163     return newmat
    5164 
    5165 def portion_fix1dim_values(mat,iddim,dimval):
    5166     """ Function to return that portion of the matrix values when one dimension has
    5167       been removed at a given value
    5168     mat = matrix
    5169     iddim = dimesion to remove (starting from 0 tacking the right most)
    5170     dimval = value of the dimension
    5171 
    5172     >>> matrix = np.array( (range(27)), dtype=np.float).reshape(3,3,3)
    5173     portion_fix1dim_values(matrix,2,2)
    5174     [[ 18.  19.  20.]
    5175      [ 21.  22.  23.]
    5176      [ 24.  25.  26.]]
    5177     """
    5178     fname='portion_fix1dim_values'
    5179 
    5180 # Not working ma.squeeze
    5181 ##    import numpy.ma as ma
    5182 ##    print ma.squeeze(mat, axis = (idim,))
    5183    
    5184     matshape = mat.shape
    5185     mattype = mat.dtype
    5186     matmask = np.zeros( tuple(matshape), dtype=bool)
    5187 
    5188     zerodims=np.ones( (6), dtype=int)
    5189     Ndims = len(matshape)
    5190 
    5191     if Ndims > 6:
    5192         print errmsg
    5193         print '  ' + fname + ' number of dimensions: ',Ndims,' not ready!!!!!'
    5194         quit(-1)
    5195 
    5196     zerodims[5-Ndims+1:6] = matshape
    5197 
    51984893    newdims = []
    51994894    for idim in range(Ndims):
     4895#        print idim,'matshape[idim]:',matshape[Ndims-1-idim],'iddim:',iddim
    52004896        if idim != iddim:
    5201             newdims.append(matshape[idim])
     4897            newdims.append(matshape[Ndims-1-idim])
    52024898
    52034899    newdims.reverse()
     
    52054901    mask = np.zeros(tuple(zerodims), dtype=bool)
    52064902    vals = np.zeros(tuple(zerodims), dtype=mattype)
    5207     vals[0:zerodims[0],0:zerodims[1],0:zerodims[2],0:zerodims[3],0:zerodims[4],
    5208       0:zerodims[5]] = mat
     4903    newvals = np.zeros(tuple(zerodims), dtype=mattype)
     4904
     4905    vals[0:zerodims[0],0:zerodims[1],0:zerodims[2],0:zerodims[3],0:zerodims[4],      \
     4906      0:zerodims[5]] = varvals
     4907
     4908#    print 'vals shape:',vals.shape,':',newdims
    52094909
    52104910    for i5 in range(zerodims[5]):
     
    52304930#    print 'newmat dim:',iddim,'val:',dimval,':',newdims,'______'
    52314931    newmat = vals[mask].reshape(tuple(newdims))
    5232 #    print newmat
    5233    
    5234     return newmat
    5235 
    5236 def valmod_dim(values, ncfile, varn):
    5237     """ Function to modify the value of a variable at a given dimension and value
    5238     values = dimn,dimval,modins,modval1,[modval2,...]
    5239       dimn = name of the dimension
    5240       dimval = value of the dimension at which change the values
    5241       modins = instruction:
    5242         'sumc', add [modval1]
    5243         'subc', substraction [modval1]
    5244         'mulc', multiply by [modval1]
    5245         'divc', divide by [modval1]
    5246         'lowthres': modify all values below [modval1] to [modval2]
    5247         'upthres': modify all values above [modval1] to [modval2]
    5248     ncfile = netCDF file name
    5249     varn = name of the variable
    5250     >>> valmod_dim('num_metgrid_levels,10,mulc,-1','aqua_met-em_control.nc','PRES')
    5251     """
    5252     fname = 'valmod_dim'
    5253 
    5254     if values == '-h':
    5255         print """ Function to modify the value of a variable at a given dimension and value
    5256           values = dimn,dimval,modins,modval1,[modval2,...]
    5257           dimn = name of the dimension
    5258           dimval = value of the dimension at which change the values
    5259           modins = instruction:
    5260             'sumc', add [modval1]
    5261             'subc', substraction [modval1]
    5262             'mulc', multiply by [modval1]
    5263             'divc', divide by [modval1]
    5264             'lowthres': modify all values below [modval1] to [modval2]
    5265             'upthres': modify all values above [modval1] to [modval2]
    5266           ncfile = netCDF file name
    5267           varn = name of the variable
    5268           >>> valmod_dim('num_metgrid_levels,10,mulc,-1','aqua_met-em_control.nc','PRES')
    5269           """
    5270         quit()
    5271 
    5272 ##  mat = np.array( (range(27)), dtype=np.float).reshape(3,3,3)
    5273 
    5274     vals = values.split(',')
    5275     Lvals = len(vals)
    5276 
    5277     dimn = vals[0]
    5278     dimval = np.int(vals[1])
    5279     modins = vals[2]
    5280     modval = np.float(vals[3])
    5281     newvalues = ','.join(vals[2:Lvals])
    5282 
    5283     if not os.path.isfile(ncfile):
    5284       print errormsg
    5285       print '   valmod: File "' + ncfile + '" does not exist !!'
    5286       print errormsg
    5287       quit(-1)   
    5288 
    5289     ncf = NetCDFFile(ncfile,'a')
    5290 
    5291     if ncf.dimensions.has_key('plev'):
    5292       # removing pressure level from variable name
    5293       varn = re.sub("\d+", "", varn)
    5294 
    5295     if not ncf.dimensions.has_key(dimn):
    5296       print errormsg
    5297       print '   ' + fname + ': File "' + ncfile + '" does not have dimension "' +    \
    5298         dimn + '" !!!!'
    5299       ncf.close()
    5300       quit(-1)
    5301 
    5302     if not ncf.variables.has_key(varn):
    5303       print errormsg
    5304       print '   ' + fname + ': File "' + ncfile + '" does not have variable "' +     \
    5305         varn + '" !!!!'
    5306       ncf.close()
    5307       quit(-1)
    5308 
    5309     varobj = ncf.variables[varn]
    5310     varinf = variable_inf(varobj)
    5311 
    5312     varvals = varobj[:]
    5313 
    5314 # Dimension id
    5315     iddim=varinf.Ndims - 1
    5316     for idimn in varinf.dimns:
    5317 #        print iddim, idimn
    5318         if dimn == idimn:
    5319             break
    5320 
    5321         iddim = iddim - 1
    5322 
    5323     matshape = varvals.shape
    5324     mattype = varvals.dtype
    5325     matmask = np.zeros( tuple(matshape), dtype=bool)
    5326 
    5327     zerodims=np.ones( (6), dtype=int)
    5328     Ndims = len(matshape)
    5329 
    5330     if Ndims > 6:
    5331         print errmsg
    5332         print '  ' + fname + ' number of dimensions: ',Ndims,' not ready!!!!!'
    5333         quit(-1)
    5334 
    5335     zerodims[5-Ndims+1:6] = matshape
    5336 
    5337     newdims = []
    5338     for idim in range(Ndims):
    5339 #        print idim,'matshape[idim]:',matshape[Ndims-1-idim],'iddim:',iddim
    5340         if idim != iddim:
    5341             newdims.append(matshape[Ndims-1-idim])
    5342 
    5343     newdims.reverse()
    5344 
    5345     mask = np.zeros(tuple(zerodims), dtype=bool)
    5346     vals = np.zeros(tuple(zerodims), dtype=mattype)
    5347     newvals = np.zeros(tuple(zerodims), dtype=mattype)
    5348 
    5349     vals[0:zerodims[0],0:zerodims[1],0:zerodims[2],0:zerodims[3],0:zerodims[4],      \
    5350       0:zerodims[5]] = varvals
    5351 
    5352 #    print 'vals shape:',vals.shape,':',newdims
    5353 
    5354     for i5 in range(zerodims[5]):
    5355         for i4 in range(zerodims[4]):
    5356             for i3 in range(zerodims[3]):
    5357                 for i2 in range(zerodims[2]):
    5358                     for i1 in range(zerodims[1]):
    5359                         for i0 in range(zerodims[0]):
    5360 #                            print 'iddim:',iddim,'dimval:',dimval,'-->',i0,i1,i2,i3,i4,i5
    5361                             if iddim == 5 and dimval == i0:
    5362                                 mask[i0,i1,i2,i3,i4,i5] = True
    5363                             elif iddim == 4 and dimval == i1:
    5364                                 mask[i0,i1,i2,i3,i4,i5] = True
    5365                             elif iddim == 3 and dimval == i2:
    5366                                 mask[i0,i1,i2,i3,i4,i5] = True
    5367                             elif iddim == 2 and dimval == i3:
    5368                                 mask[i0,i1,i2,i3,i4,i5] = True
    5369                             elif iddim == 1 and dimval == i4:
    5370                                 mask[i0,i1,i2,i3,i4,i5] = True
    5371                             elif iddim == 0 and dimval == i5:
    5372                                 mask[i0,i1,i2,i3,i4,i5] = True
    5373 
    5374 #    print 'newmat dim:',iddim,'val:',dimval,':',newdims,'______'
    5375     newmat = vals[mask].reshape(tuple(newdims))
    53764932    varmod = np.zeros(tuple(newdims), dtype=mattype)
    53774933
     
    54134969    ncf.sync()
    54144970    ncf.close()
     4971
     4972    return
    54154973
    54164974def checkNaNs(values, filen):
     
    55135071    ncobj.close()
    55145072
     5073    return
     5074
    55155075##checkNaNs(10.e10, '/d4/lflmd/etudes/WRF_LMDZ/WaquaL/WRF/control/wrfout_d01_1979-12-01_00:00:00')
    55165076##checkNaNs(10.e10, '/d4/lflmd/etudes/FF/tests/em_quarter_ss/run/wrfout_d01_0001-01-01_00:00:00')
     
    55495109
    55505110    ncobj.close()
     5111
     5112    return
    55515113
    55525114##checkAllValues(0., '/d4/lflmd/etudes/WRF_LMDZ/WaquaL/WRF/control/wrfout_d01_1979-12-01_00:00:00')
     
    61105672
    61115673    return
    6112 
    61135674
    61145675def sellonlatboxold(values, ncfile, varn):
     
    70096570#compute_opervaralltime('add|time', 'obs/PRCP.nc', 'product')
    70106571
    7011 def retype(val, vtype):
    7012     """ Function to transform a value to a given type
    7013     retype(val, vtype)
    7014       [val]= value
    7015       [vtype]= type to transform
    7016     >>> retype(0, type(True))
    7017     False
    7018     """
    7019 
    7020     fname = 'retype'
    7021 
    7022     if val == 'h':
    7023         print fname + '_____________________________________________________________'
    7024         print retype.__doc__
    7025         quit()
    7026 
    7027     if vtype == type(int(1)):
    7028         newval = int(val)
    7029     elif vtype == type(float(1)):
    7030         newval = float(val)
    7031 #    elif vtype == type(float32(1)):
    7032 #        newval = float32(val)
    7033     elif vtype == type(np.int(1)):
    7034         typeinf = np.iinfo(np.int)
    7035         if (abs(np.float64(val)) > typeinf.max):
    7036             print warnmsg
    7037             print '  ' + fname + ': value to transform ', val,' overpasses type:',   \
    7038                vtype,' limits!!'
    7039             print '  Changing value to kind largest allowed value:', typeinf.max
    7040             newval = abs(np.float64(val))/np.float64(val) * np.int(typeinf.max)
    7041         else:
    7042             newval = np.int(val)
    7043     elif vtype == type(np.int16(1)):
    7044         typeinf = np.iinfo(np.int16)
    7045         if (abs(np.float64(val)) > typeinf.max):
    7046             print warnmsg
    7047             print '  ' + fname + ': value to transform ', val,' overpasses type:',   \
    7048                vtype,' limits!!'
    7049             print '  Changing value to kind largest allowed value:', typeinf.max
    7050             newval = abs(np.float64(val))/np.float64(val) * np.int16(typeinf.max)
    7051         else:
    7052             newval = np.int16(val)
    7053     elif vtype == type(np.int32(1)):
    7054         typeinf = np.iinfo(np.int32)
    7055         if (np.abs(np.float64(val)) > typeinf.max):
    7056             print warnmsg
    7057             print '  ' + fname + ': value to transform ', val,' overpasses type:',   \
    7058                vtype,' limits!!'
    7059             print '  Changing value to kind largest allowed value:', typeinf.max
    7060             newval = abs(np.float64(val))/np.float64(val) * np.int32(typeinf.max)
    7061         else:
    7062             newval = np.int32(np.float64(val))
    7063     elif vtype == type(np.int64(1)):
    7064         newval = np.int64(val)
    7065     elif vtype == type(np.float(1)):
    7066         newval = np.float(val)
    7067 #    elif vtype == type(np.float16(1)):
    7068 #        newval = np.float16(val)
    7069     elif vtype == type(np.float32(1)):
    7070         newval = np.float32(val)
    7071     elif vtype == type(np.float64(1)):
    7072         newval = np.float64(val)
    7073     elif vtype == type(True):
    7074         if val == 0:
    7075             newval = False
    7076         else:
    7077             newval = True
    7078     elif vtype == '|S1':
    7079         newval = str(val)
    7080     else:
    7081         print errormsg
    7082         print '  ' + fname + ': variable type "', vtype, '" not ready!!!'
    7083         quit(-1)
    7084 
    7085     return newval
    7086 
    70876572def setvar_asciivalues(values, ncfile, varname):
    70886573    """ Function to set de values of a variable with an ASCII file (common
     
    71706655    objnc.close()
    71716656
     6657    return
     6658
    71726659#setvar_asciivalues('obstimes.inf', 'obs/re_project_accumulated-1h_PRCP.nc', 'time')
    7173 
    7174 class stats_space2D(object):
    7175     """spatial statistics for a 2D file:
    7176       vals= variable ro check (assuming var[t,dy,dx])
    7177         self.minv[t]: spatial minimum at each time-step
    7178         self.maxv[t]: spatial maximum at each time-step
    7179         self.meanv[t]: spatial mean at each time-step
    7180         self.mean2v[t]: spatial quadratic mean at each time-step
    7181         self.stdv[t]: spatial standard deviation at each time-step
    7182         self.anomv[t]: spatial anomaly from the whole mean at each time-step
    7183     """
    7184  
    7185     def __init__(self, vals):
    7186         from scipy import stats as sts
    7187         fname = 'stats_space2D'
    7188 
    7189         if vals1 == 'h':
    7190             print fname + '_____________________________________________________________'
    7191             print stats_space2Dvars.__doc__
    7192             quit()
    7193 
    7194         if vals1 is None:
    7195             self.minv = None
    7196             self.maxv = None
    7197             self.meanv = None
    7198             self.mean2v = None
    7199             self.stdv = None
    7200         else:
    7201             dimt = vals.shape[0]
    7202             stats=np.zeros((dimt,5), dtype=np.float)
    7203             absmean = np.mean(vals)
    7204 
    7205             for it in range(dimt):
    7206                 stats[it,0]=np.min(vals[it,:,:])
    7207                 stats[it,1]=np.max(vals[it,:,:])
    7208                 stats[it,2]=np.mean(vals[it,:,:])
    7209                 stats[it,3]=np.mean(vals[it,:,:]*vals[it,:,:])
    7210                 stats[it,4]=absmean - stats[it,2]
    7211 
    7212             stats = np.where(stats > 0.1*fillValue, fillValue, stats)
    7213             stats = np.where(stats is nan, fillValue, stats)
    7214             stats = np.where(stats is np.inf, fillValue, stats)
    7215             stats = np.where(stats is None, fillValue, stats)
    7216 
    7217             self.minv=stats[:,0]
    7218             self.maxv=stats[:,1]
    7219             self.meanv=stats[:,2]
    7220             self.mean2v=stats[:,3]
    7221             self.stdv=np.sqrt(stats[:,3]-stats[:,2]*stats[:,2])
    7222             self.anomv=stats[:,4]
    7223 
    7224 class stats_space2Dvars(object):
    7225     """spatial statistics beween 2 2D files:
    7226     valsA = variable 1 (assuming var[t,dy,dx])
    7227     valsB = variable 2 (assuming var[t,dy,dx])
    7228     self.min[t,var], self.max[t,var], self.mean[t,var], self.mean2[t,var],
    7229       self.std[t,var]
    7230       [var] = var1+var2[v1Av2], var1-var2[v1Sv2], var1/var2[v1Dv2], var1*var2[v1Pv2]
    7231 
    7232     self.mae=mean[t,abs(var1-var2)]
    7233     self.correlation=correlation[var1,var2] (and p-value)
    7234     self.bias=[t,mean(var1)-mean(var2)]
    7235     self.meancorrelation=correlation[mean(var1),mean(var2)] (and p-value)
    7236     """
    7237 
    7238     def __init__(self, vals1, vals2):
    7239         from scipy import stats as sts
    7240         fname = 'stats_space2Dvars'
    7241 
    7242         if vals1 == 'h':
    7243             print fname + '_____________________________________________________________'
    7244             print stats_space2Dvars.__doc__
    7245             quit()
    7246 
    7247         if vals1 is None:
    7248             self.minv1Av2 = None
    7249             self.maxv1Av2 = None
    7250             self.meanv1Av2 = None
    7251             self.mean2v1Av2 = None
    7252             self.stdv1Av2 = None
    7253             self.minv1Sv2 = None
    7254             self.maxv1Sv2 = None
    7255             self.meanv1Sv2 = None
    7256             self.mean2v1Sv2 = None
    7257             self.stdv1Sv2 = None
    7258             self.minv1Dv2 = None
    7259             self.maxv1Dv2 = None
    7260             self.meanv1Dv2 = None
    7261             self.mean2v1Dv2 = None
    7262             self.stdv1Dv2 = None
    7263             self.minv1Pv2 = None
    7264             self.maxv1Pv2 = None
    7265             self.meanv1Pv2 = None
    7266             self.mean2v1Pv2 = None
    7267             self.stdv1Pv2 = None
    7268             self.mae = None
    7269             self.corr = None
    7270         else:
    7271             dimt = vals1.shape[0]
    7272             stats=np.zeros((dimt,26), dtype=np.float)
    7273             meanvals1 = np.zeros((dimt), dtype=np.float)
    7274             meanvals2 = np.zeros((dimt), dtype=np.float)
    7275    
    7276             for it in range(dimt):
    7277                 v1 = vals1[it,:,:].flatten()
    7278                 v2 = vals2[it,:,:].flatten()
    7279 
    7280 # add
    7281                 vs = v1 + v2
    7282                 stats[it,0] = np.min(vs)
    7283                 stats[it,1] = np.max(vs)
    7284                 stats[it,2] = np.mean(vs)
    7285                 stats[it,3] = np.mean(vs*vs)
    7286                 stats[it,4] = np.sqrt(stats[it,3] - stats[it,2]*stats[it,2])
    7287 # sub
    7288                 stats[it,20] = np.mean(np.abs(v1-v2))
    7289                 vs = v1 - v2
    7290                 stats[it,5] = np.min(vs)
    7291                 stats[it,6] = np.max(vs)
    7292                 stats[it,7] = np.mean(vs)
    7293                 stats[it,8] = np.mean(vs*vs)
    7294                 stats[it,9] = np.sqrt(stats[it,8] - stats[it,7]*stats[it,7])
    7295 
    7296 # mul
    7297                 vs = v1 * v2
    7298                 stats[it,10] = np.min(vs)
    7299                 stats[it,11] = np.max(vs)
    7300                 stats[it,12] = np.mean(vs)
    7301                 stats[it,13] = np.mean(vs*vs)
    7302                 stats[it,14] = np.sqrt(stats[it,13] - stats[it,12]*stats[it,12])
    7303 # div
    7304                 vs = v1 / v2
    7305                 stats[it,15] = np.min(vs)
    7306                 stats[it,16] = np.max(vs)
    7307                 stats[it,17] = np.mean(vs)
    7308                 stats[it,18] = np.mean(vs*vs)
    7309                 stats[it,19] = np.sqrt(stats[it,18] - stats[it,17]*stats[it,17])
    7310 # corr
    7311                 stats[it,21], stats[it,22] = mask_pearsonr(v1, v2)
    7312 
    7313 # Mean values
    7314                 meanvals1[it] = np.mean(v1)
    7315                 meanvals2[it] = np.mean(v2)
    7316                 stats[it,23] =  meanvals1[it] - meanvals2[it]
    7317            
    7318             stats = np.where(stats > 0.1*fillValue, fillValue, stats)
    7319             stats = np.where(stats is np.nan, fillValue, stats)
    7320             stats = np.where(stats is np.inf, fillValue, stats)
    7321             stats = np.where(stats is None, fillValue, stats)
    7322 
    7323             self.minv1Av2 = stats[:,0]
    7324             self.maxv1Av2 = stats[:,1]
    7325             self.meanv1Av2 = stats[:,2]
    7326             self.meanv21Av2 = stats[:,3]
    7327             self.stdv1Av2 = stats[:,4]
    7328 
    7329             self.minv1Sv2 = stats[:,5]
    7330             self.maxv1Sv2 = stats[:,6]
    7331             self.meanv1Sv2 = stats[:,7]
    7332             self.meanv21Sv2 = stats[:,8]
    7333             self.stdv1Sv2 = stats[:,9]
    7334 
    7335             self.minv1Pv2 = stats[:,10]
    7336             self.maxv1Pv2 = stats[:,11]
    7337             self.meanv1Pv2 = stats[:,12]
    7338             self.meanv21Pv2 = stats[:,13]
    7339             self.stdv1Pv2 = stats[:,14]
    7340 
    7341             self.minv1Dv2 = stats[:,15]
    7342             self.maxv1Dv2 = stats[:,16]
    7343             self.meanv1Dv2 = stats[:,17]
    7344             self.meanv21Dv2 = stats[:,18]
    7345             self.stdv1Dv2 = stats[:,19]
    7346 
    7347             self.mae = stats[:,20]
    7348             self.corr = stats[:,21]
    7349             self.p_value = stats[:,22]
    7350 
    7351             self.bias = stats[:,23]
    7352             self.meancorr, self.meanp_value = sts.pearsonr(meanvals1, meanvals2)
    7353 
    7354 class stats_time2D(object):
    7355     """temporal statistics for a 2D file:
    7356       vals= variable ro check (assuming var[t,dy,dx])
    7357         self.minv[t]: temporal minimum at each grid point
    7358         self.maxv[t]: temporal maximum at each grid point
    7359         self.meanv[t]: temporal mean at each grid point
    7360         self.mean2v[t]: temporal quadratic mean at each grid point
    7361         self.stdv[t]: temporal standard deviation at each grid point
    7362         self.anomv[t]: temporal anomaly from the whole mean at each grid point
    7363     """
    7364  
    7365     def __init__(self, vals):
    7366         from scipy import stats as sts
    7367         fname = 'stats_time2D'
    7368 
    7369         if vals1 == 'h':
    7370             print fname + '_____________________________________________________________'
    7371             print stats_time2Dvars.__doc__
    7372             quit()
    7373 
    7374         if vals1 is None:
    7375             self.minv = None
    7376             self.maxv = None
    7377             self.meanv = None
    7378             self.mean2v = None
    7379             self.stdv = None
    7380         else:
    7381             dimx = vals.shape[2]
    7382             dimy = vals.shape[1]
    7383             stats=np.zeros((dimy,dimx,5), dtype=np.float)
    7384             absmean = np.mean(vals,axis=0)
    7385 
    7386             stats[:,:,0]=np.min(vals, axis=0)
    7387             stats[:,:,1]=np.max(vals, axis=0)
    7388             stats[:,:,2]=np.mean(vals, axis=0)
    7389             stats[:,:,3]=np.mean(vals*vals, axis=0)
    7390             stats[:,:,4]=absmean - stats[:,:,2]
    7391 
    7392             stats = np.where(stats > 0.1*fillValue, fillValue, stats)
    7393             stats = np.where(stats is np.nan, fillValue, stats)
    7394             stats = np.where(stats is np.inf, fillValue, stats)
    7395             stats = np.where(stats is None, fillValue, stats)
    7396 
    7397             self.minv=stats[:,:,0]
    7398             self.maxv=stats[:,:,1]
    7399             self.meanv=stats[:,:,2]
    7400             self.mean2v=stats[:,:,3]
    7401             self.stdv=np.sqrt(stats[:,:,3]-stats[:,:,2]*stats[:,:,2])
    7402             self.anomv=stats[:,:,4]
    7403 
    7404 class stats_time2Dvars(object):
    7405     """temporal statistics beween 2 2D files:
    7406     valsA = variable 1 (assuming var[t,dy,dx])
    7407     valsB = variable 2 (assuming var[t,dy,dx])
    7408     self.min[dy,dx,var], self.max[dy,dx,var], self.mean[dy,dx,var],
    7409       self.mean2[dy,dx,var], self.std[dy,dx,var]
    7410       [var] = var1+var2[v1Av2], var1-var2[v1Sv2], var1/var2[v1Dv2], var1*var2[v1Pv2]
    7411 
    7412     self.mae=mean[dy,dx,abs(var1-var2)]
    7413     self.correlation=correlation[var1,var2] (and p-value)
    7414     self.bias=[dy,dx,mean(var1)-mean(var2)]
    7415     self.meancorrelation=correlation[mean(var1),mean(var2)] (and p-value)
    7416     """
    7417 
    7418     def __init__(self, vals1, vals2):
    7419         from scipy import stats as sts
    7420         fname = 'stats_time2Dvars'
    7421 
    7422         if vals1 == 'h':
    7423             print fname + '_____________________________________________________________'
    7424             print stats_time2Dvars.__doc__
    7425             quit()
    7426 
    7427         if vals1 is None:
    7428             self.minv1Av2 = None
    7429             self.maxv1Av2 = None
    7430             self.meanv1Av2 = None
    7431             self.mean2v1Av2 = None
    7432             self.stdv1Av2 = None
    7433             self.minv1Sv2 = None
    7434             self.maxv1Sv2 = None
    7435             self.meanv1Sv2 = None
    7436             self.mean2v1Sv2 = None
    7437             self.stdv1Sv2 = None
    7438             self.minv1Dv2 = None
    7439             self.maxv1Dv2 = None
    7440             self.meanv1Dv2 = None
    7441             self.mean2v1Dv2 = None
    7442             self.stdv1Dv2 = None
    7443             self.minv1Pv2 = None
    7444             self.maxv1Pv2 = None
    7445             self.meanv1Pv2 = None
    7446             self.mean2v1Pv2 = None
    7447             self.stdv1Pv2 = None
    7448             self.mae = None
    7449             self.corr = None
    7450         else:
    7451             dimx = vals1.shape[1]
    7452             dimy = vals1.shape[1]
    7453             stats=np.zeros((dimy,dimx,24), dtype=np.float)
    7454             meanvals1 = np.zeros((dimy,dimx), dtype=np.float)
    7455             meanvals2 = np.zeros((dimy,dimx), dtype=np.float)
    7456 # add
    7457             vs = vals1 + vals2
    7458             stats[:,:,0] = np.min(vs,axis=0)
    7459             stats[:,:,1] = np.max(vs,axis=0)
    7460             stats[:,:,2] = np.mean(vs,axis=0)
    7461             stats[:,:,3] = np.mean(vs*vs,axis=0)
    7462             stats[:,:,4] = np.sqrt(stats[:,:,3] - stats[:,:,2]*stats[:,:,2])
    7463 # sub
    7464             stats[:,:,20] = np.mean(np.abs(vals1-vals2), axis=0)
    7465             vs = vals1 - vals2
    7466             stats[:,:,5] = np.min(vs,axis=0)
    7467             stats[:,:,6] = np.max(vs,axis=0)
    7468             stats[:,:,7] = np.mean(vs,axis=0)
    7469             stats[:,:,8] = np.mean(vs*vs,axis=0)
    7470             stats[:,:,9] = np.sqrt(stats[:,:,8] - stats[:,:,7]*stats[:,:,7])
    7471 # mul
    7472             vs = vals1 * vals2
    7473             stats[:,:,10] = np.min(vs,axis=0)
    7474             stats[:,:,11] = np.max(vs,axis=0)
    7475             stats[:,:,12] = np.mean(vs,axis=0)
    7476             stats[:,:,13] = np.mean(vs*vs,axis=0)
    7477             stats[:,:,14] = np.sqrt(stats[:,:,13] - stats[:,:,12]*stats[:,:,12])
    7478 # div
    7479             vs = vals1 / vals2
    7480             stats[:,:,15] = np.min(vs,axis=0)
    7481             stats[:,:,16] = np.max(vs,axis=0)
    7482             stats[:,:,17] = np.mean(vs,axis=0)
    7483             stats[:,:,18] = np.mean(vs*vs,axis=0)
    7484             stats[:,:,19] = np.sqrt(stats[:,:,18] - stats[:,:,17]*stats[:,:,17])
    7485 
    7486 
    7487 # Mean values
    7488             meanvals1[:,:] = np.mean(vals1,axis=0)
    7489             meanvals2[:,:] = np.mean(vals2,axis=0)
    7490             stats[:,:,23] =  meanvals1[:,:] - meanvals2[:,:]
    7491            
    7492 # corr
    7493             self.meancorr, self.meanp_value = sts.pearsonr(meanvals1.flatten(), meanvals2.flatten())
    7494 
    7495             for j in range(dimy):
    7496                 for i in range(dimx):
    7497                     stats[j,i,21], stats[j,i,22] = sts.pearsonr(vals1[:,j,i], vals2[:,j,i])
    7498 
    7499             stats = np.where(stats > 0.1*fillValue, fillValue, stats)
    7500             stats = np.where(stats is np.nan, fillValue, stats)
    7501             stats = np.where(stats is np.inf, fillValue, stats)
    7502             stats = np.where(stats is None, fillValue, stats)
    7503 
    7504             self.minv1Av2 = stats[:,:,0]
    7505             self.maxv1Av2 = stats[:,:,1]
    7506             self.meanv1Av2 = stats[:,:,2]
    7507             self.meanv21Av2 = stats[:,:,3]
    7508             self.stdv1Av2 = stats[:,:,4]
    7509 
    7510             self.minv1Sv2 = stats[:,:,5]
    7511             self.maxv1Sv2 = stats[:,:,6]
    7512             self.meanv1Sv2 = stats[:,:,7]
    7513             self.meanv21Sv2 = stats[:,:,8]
    7514             self.stdv1Sv2 = stats[:,:,9]
    7515 
    7516             self.minv1Pv2 = stats[:,:,10]
    7517             self.maxv1Pv2 = stats[:,:,11]
    7518             self.meanv1Pv2 = stats[:,:,12]
    7519             self.meanv21Pv2 = stats[:,:,13]
    7520             self.stdv1Pv2 = stats[:,:,14]
    7521 
    7522             self.minv1Dv2 = stats[:,:,15]
    7523             self.maxv1Dv2 = stats[:,:,16]
    7524             self.meanv1Dv2 = stats[:,:,17]
    7525             self.meanv21Dv2 = stats[:,:,18]
    7526             self.stdv1Dv2 = stats[:,:,19]
    7527 
    7528             self.mae = stats[:,:,20]
    7529             self.corr = stats[:,:,21]
    7530             self.p_value = stats[:,:,22]
    7531 
    7532             self.bias = stats[:,:,23]
    7533 
    7534 #vals1 = np.arange(27).reshape(3,3,3)*1.
    7535 #vals2 = np.arange(1,28).reshape(3,3,3)*1.
    7536 
    7537 #printing_class(stats_time2Dvars(vals1,vals2))
    75386660
    75396661def statcompare_files(values):
     
    77886910
    77896911#statcompare_files('control/sellonlatbox_wss_17-20.nc:wss,obs/re_project_Vu_17-20.nc:wss')
    7790 
    77916912
    77926913def sellonlatlevbox(values, ncfile, varn):
     
    81167237
    81177238#sellonlatlevbox('XLONG,XLAT,ZNU,-12.4,25.35,32.4,52.65,0,0', 'control/wrfout_d01_2001-11-09_00:00:00', 'P')
    8118 
    8119 def file_nlines(filen,char):
    8120     """ Function to provide the number of lines of a file
    8121     filen= name of the file
    8122     char= character as no line
    8123     >>> file_nlines('trajectory.dat','#')
    8124     49
    8125     """
    8126     fname = 'file_nlines'
    8127 
    8128     if not os.path.isfile(filen):
    8129         print errormsg
    8130         print '  ' + fname + ' file: "' + filen + '" does not exist !!'
    8131         quit(-1)
    8132 
    8133     fo = open(filen,'r')
    8134 
    8135     nlines=0
    8136     for line in fo:
    8137         if line[0:1] != char: nlines = nlines + 1
    8138 
    8139     fo.close()
    8140 
    8141     return nlines
    8142 
    8143 def datetimeStr_conversion(StringDT,typeSi,typeSo):
    8144     """ Function to transform a string date to an another date object
    8145     StringDT= string with the date and time
    8146     typeSi= type of datetime string input
    8147     typeSo= type of datetime string output
    8148       [typeSi/o]
    8149         'cfTime': [time],[units]; ]time in CF-convention format [units] = [tunits] since [refdate]
    8150         'matYmdHMS': numerical vector with [[YYYY], [MM], [DD], [HH], [MI], [SS]]
    8151         'YmdHMS': [YYYY][MM][DD][HH][MI][SS] format
    8152         'Y-m-d_H:M:S': [YYYY]-[MM]-[DD]_[HH]:[MI]:[SS] format
    8153         'Y-m-d H:M:S': [YYYY]-[MM]-[DD] [HH]:[MI]:[SS] format
    8154         'Y/m/d H-M-S': [YYYY]/[MM]/[DD] [HH]-[MI]-[SS] format
    8155         'WRFdatetime': [Y], [Y], [Y], [Y], '-', [M], [M], '-', [D], [D], '_', [H],
    8156           [H], ':', [M], [M], ':', [S], [S]
    8157     >>> datetimeStr_conversion('1976-02-17_08:32:05','Y-m-d_H:M:S','matYmdHMS')
    8158     [1976    2   17    8   32    5]
    8159     >>> datetimeStr_conversion(str(137880)+',minutes since 1979-12-01_00:00:00','cfTime','Y/m/d H-M-S')
    8160     1980/03/05 18-00-00
    8161     """
    8162     import datetime as dt
    8163 
    8164     fname = 'datetimeStr_conversion'
    8165 
    8166     if StringDT[0:1] == 'h':
    8167         print fname + '_____________________________________________________________'
    8168         print datetimeStr_conversion.__doc__
    8169         quit()
    8170 
    8171     if typeSi == 'cfTime':
    8172         timeval = np.float(StringDT.split(',')[0])
    8173         tunits = StringDT.split(',')[1].split(' ')[0]
    8174         Srefdate = StringDT.split(',')[1].split(' ')[2]
    8175 
    8176 # Does reference date contain a time value [YYYY]-[MM]-[DD] [HH]:[MI]:[SS]
    8177 ##
    8178         yrref=Srefdate[0:4]
    8179         monref=Srefdate[5:7]
    8180         dayref=Srefdate[8:10]
    8181 
    8182         trefT = Srefdate.find(':')
    8183         if not trefT == -1:
    8184 #            print '  ' + fname + ': refdate with time!'
    8185             horref=Srefdate[11:13]
    8186             minref=Srefdate[14:16]
    8187             secref=Srefdate[17:19]
    8188             refdate = datetimeStr_datetime( yrref + '-' + monref + '-' + dayref +    \
    8189               '_' + horref + ':' + minref + ':' + secref)
    8190         else:
    8191             refdate = datetimeStr_datetime( yrref + '-' + monref + '-' + dayref +    \
    8192               + '_00:00:00')
    8193 
    8194         if tunits == 'weeks':
    8195             newdate = refdate + dt.timedelta(weeks=float(timeval))
    8196         elif tunits == 'days':
    8197             newdate = refdate + dt.timedelta(days=float(timeval))
    8198         elif tunits == 'hours':
    8199             newdate = refdate + dt.timedelta(hours=float(timeval))
    8200         elif tunits == 'minutes':
    8201             newdate = refdate + dt.timedelta(minutes=float(timeval))
    8202         elif tunits == 'seconds':
    8203             newdate = refdate + dt.timedelta(seconds=float(timeval))
    8204         elif tunits == 'milliseconds':
    8205             newdate = refdate + dt.timedelta(milliseconds=float(timeval))
    8206         else:
    8207               print errormsg
    8208               print '    timeref_datetime: time units "' + tunits + '" not ready!!!!'
    8209               quit(-1)
    8210 
    8211         yr = newdate.year
    8212         mo = newdate.month
    8213         da = newdate.day
    8214         ho = newdate.hour
    8215         mi = newdate.minute
    8216         se = newdate.second
    8217     elif typeSi == 'matYmdHMS':
    8218         yr = StringDT[0]
    8219         mo = StringDT[1]
    8220         da = StringDT[2]
    8221         ho = StringDT[3]
    8222         mi = StringDT[4]
    8223         se = StringDT[5]
    8224     elif typeSi == 'YmdHMS':
    8225         yr = int(StringDT[0:4])
    8226         mo = int(StringDT[4:6])
    8227         da = int(StringDT[6:8])
    8228         ho = int(StringDT[8:10])
    8229         mi = int(StringDT[10:12])
    8230         se = int(StringDT[12:14])
    8231     elif typeSi == 'Y-m-d_H:M:S':
    8232         dateDT = StringDT.split('_')
    8233         dateD = dateDT[0].split('-')
    8234         timeT = dateDT[1].split(':')
    8235         yr = int(dateD[0])
    8236         mo = int(dateD[1])
    8237         da = int(dateD[2])
    8238         ho = int(timeT[0])
    8239         mi = int(timeT[1])
    8240         se = int(timeT[2])
    8241     elif typeSi == 'Y-m-d H:M:S':
    8242         dateDT = StringDT.split(' ')
    8243         dateD = dateDT[0].split('-')
    8244         timeT = dateDT[1].split(':')
    8245         yr = int(dateD[0])
    8246         mo = int(dateD[1])
    8247         da = int(dateD[2])
    8248         ho = int(timeT[0])
    8249         mi = int(timeT[1])
    8250         se = int(timeT[2])
    8251     elif typeSi == 'Y/m/d H-M-S':
    8252         dateDT = StringDT.split(' ')
    8253         dateD = dateDT[0].split('/')
    8254         timeT = dateDT[1].split('-')
    8255         yr = int(dateD[0])
    8256         mo = int(dateD[1])
    8257         da = int(dateD[2])
    8258         ho = int(timeT[0])
    8259         mi = int(timeT[1])
    8260         se = int(timeT[2])
    8261     elif typeSi == 'WRFdatetime':
    8262         yr = int(StringDT[0])*1000 + int(StringDT[1])*100 + int(StringDT[2])*10 +    \
    8263           int(StringDT[3])
    8264         mo = int(StringDT[5])*10 + int(StringDT[6])
    8265         da = int(StringDT[8])*10 + int(StringDT[9])
    8266         ho = int(StringDT[11])*10 + int(StringDT[12])
    8267         mi = int(StringDT[14])*10 + int(StringDT[15])
    8268         se = int(StringDT[17])*10 + int(StringDT[18])
    8269     else:
    8270         print errormsg
    8271         print '  ' + fname + ': type of String input date "' + typeSi +              \
    8272           '" not ready !!!!'
    8273         quit(-1)
    8274 
    8275     if typeSo == 'matYmdHMS':
    8276         dateYmdHMS = np.zeros((6), dtype=int)
    8277         dateYmdHMS[0] =  yr
    8278         dateYmdHMS[1] =  mo
    8279         dateYmdHMS[2] =  da
    8280         dateYmdHMS[3] =  ho
    8281         dateYmdHMS[4] =  mi
    8282         dateYmdHMS[5] =  se
    8283     elif typeSo == 'YmdHMS':
    8284         dateYmdHMS = str(yr).zfill(4) + str(mo).zfill(2) + str(da).zfill(2) +        \
    8285           str(ho).zfill(2) + str(mi).zfill(2) + str(se).zfill(2)
    8286     elif typeSo == 'Y-m-d_H:M:S':
    8287         dateYmdHMS = str(yr).zfill(4) + '-' + str(mo).zfill(2) + '-' +               \
    8288           str(da).zfill(2) + '_' + str(ho).zfill(2) + ':' + str(mi).zfill(2) + ':' + \
    8289           str(se).zfill(2)
    8290     elif typeSo == 'Y-m-d H:M:S':
    8291         dateYmdHMS = str(yr).zfill(4) + '-' + str(mo).zfill(2) + '-' +               \
    8292           str(da).zfill(2) + ' ' + str(ho).zfill(2) + ':' + str(mi).zfill(2) + ':' + \
    8293           str(se).zfill(2)
    8294     elif typeSo == 'Y/m/d H-M-S':
    8295         dateYmdHMS = str(yr).zfill(4) + '/' + str(mo).zfill(2) + '/' +               \
    8296           str(da).zfill(2) + ' ' + str(ho).zfill(2) + '-' + str(mi).zfill(2) + '-' + \
    8297           str(se).zfill(2)
    8298     elif typeSo == 'WRFdatetime':
    8299         dateYmdHMS = []
    8300         yM = yr/1000
    8301         yC = (yr-yM*1000)/100
    8302         yD = (yr-yM*1000-yC*100)/10
    8303         yU = yr-yM*1000-yC*100-yD*10
    8304 
    8305         mD = mo/10
    8306         mU = mo-mD*10
    8307        
    8308         dD = da/10
    8309         dU = da-dD*10
    8310 
    8311         hD = ho/10
    8312         hU = ho-hD*10
    8313 
    8314         miD = mi/10
    8315         miU = mi-miD*10
    8316 
    8317         sD = se/10
    8318         sU = se-sD*10
    8319 
    8320         dateYmdHMS.append(str(yM))
    8321         dateYmdHMS.append(str(yC))
    8322         dateYmdHMS.append(str(yD))
    8323         dateYmdHMS.append(str(yU))
    8324         dateYmdHMS.append('-')
    8325         dateYmdHMS.append(str(mD))
    8326         dateYmdHMS.append(str(mU))
    8327         dateYmdHMS.append('-')
    8328         dateYmdHMS.append(str(dD))
    8329         dateYmdHMS.append(str(dU))
    8330         dateYmdHMS.append('_')
    8331         dateYmdHMS.append(str(hD))
    8332         dateYmdHMS.append(str(hU))
    8333         dateYmdHMS.append(':')
    8334         dateYmdHMS.append(str(miD))
    8335         dateYmdHMS.append(str(miU))
    8336         dateYmdHMS.append(':')
    8337         dateYmdHMS.append(str(sD))
    8338         dateYmdHMS.append(str(sU))
    8339     else:
    8340         print errormsg
    8341         print '  ' + fname + ': type of output date "' + typeSo + '" not ready !!!!'
    8342         quit(-1)
    8343 
    8344     return dateYmdHMS
    8345 
    8346 def table_tex(tablevals, colnames, rownames, of):
    8347     """ Function to write into a LaTeX tabukar from a table of values
    8348       tablevals = (ncol nrow) of values
    8349       colnames = list with ncol labels for the columns
    8350       rownames = list with nrow labels for the rows
    8351       of= object ASCII file to write the table
    8352     """
    8353     errormsg = 'ERROR -- error -- ERROR -- error'
    8354 
    8355     fname = 'table_tex'
    8356 
    8357     Ncol = tablevals.shape[0]
    8358     Nrow = tablevals.shape[1]
    8359 
    8360     if Ncol + 1 != len(colnames):
    8361         print errormsg
    8362         print '  ' + fname + ': wrong number of column names!!'
    8363         print '    data has:', Ncol, 'and you provided:', len(colnames)
    8364         print '    remember to provide one more for the label of the rows!'
    8365         print '    you provide:',colnames
    8366         quit(-1)
    8367 
    8368     if Nrow != len(rownames):
    8369         print errormsg
    8370         print '  ' + fname + ': wrong number of row names!!'
    8371         print '    data has:', Nrow, 'and you provided:', len(rownames)
    8372         print '    you provide:',rownames
    8373         quit(-1)
    8374 
    8375     colcs = ''
    8376     colns = ''
    8377     for icol in colnames:
    8378         colcs = colcs + 'c'
    8379         if icol == colnames[0]:
    8380             colns = ' {\\bfseries{' + icol + '}}'
    8381         else:
    8382             colns = colns + ' & {\\bfseries{' + icol + '}}'
    8383 
    8384     of.write('\n')
    8385     of.write("%Automatically written file from function '" + fname + "'\n")
    8386     of.write('\\begin{tabular}{l'+colcs+'}\n')
    8387     of.write(colns + ' \\\\ \\hline\n')
    8388 
    8389     ir = 0
    8390     for irow in rownames:
    8391         rowns = '{\\bfseries{' + irow + '}}'
    8392         for ic in range(Ncol):
    8393             rowns = rowns + ' & ' + str(tablevals[ic,ir])
    8394         rowns = rowns + ' \\\\'
    8395 
    8396         of.write(rowns + '\n')
    8397         ir = ir + 1
    8398 
    8399     of.write('\\end{tabular}\n')
    8400 
    8401     return
    8402 
    8403 def radius_dist(dx,dy,ptx,pty):
    8404     """ Function to generate a matrix with the distance at a given point
    8405     radius_dist(dx,dy,ptx,pty)
    8406       [dx/y]: dimension of the matrix
    8407       [ptx/y]: grid point coordinates of the point
    8408     >>> radius_dist(3,5,2,2)
    8409     [[ 1.41421356  1.          1.41421356  2.23606798  3.16227766]
    8410      [ 1.          0.          1.          2.          3.        ]
    8411      [ 1.41421356  1.          1.41421356  2.23606798  3.16227766]]
    8412     """
    8413 
    8414     fname = 'radius_dist'
    8415 
    8416     if ptx < 0 or ptx > dx-1 or pty < 0 or pty > dy-1:
    8417         print errormsg
    8418         print '  ' + fname + ': wrong point coordinates:',dx,',',dy,'for matrix;',dx \
    8419          ,'x',dy
    8420         quit(-1)
    8421 
    8422     xdist =  np.zeros((dx,dy), dtype=np.float)
    8423     ydist =  np.zeros((dx,dy), dtype=np.float)
    8424     dist =  np.zeros((dx,dy), dtype=np.float)
    8425 
    8426     for ix in range(dx):
    8427         xdist[ix,:] = np.float(ix-ptx)
    8428     for iy in range(dy):
    8429         ydist[:,iy] = np.float(iy-pty)
    8430 
    8431     dist = np.sqrt(xdist*xdist + ydist*ydist)
    8432 
    8433     return dist
    8434 
    8435 def lonlat2D(lon,lat):
    8436     """ Function to return lon, lat 2D matrices from any lon,lat matrix
    8437       lon= matrix with longitude values
    8438       lat= matrix with latitude values
    8439     """
    8440     fname = 'lonlat2D'
    8441 
    8442     if len(lon.shape) != len(lat.shape):
    8443         print errormsg
    8444         print '  ' + fname + ': longitude values with shape:', lon.shape,            \
    8445           'is different that latitude values with shape:', lat.shape, '(dif. size) !!'
    8446         quit(-1)
    8447 
    8448     if len(lon.shape) == 3:
    8449         lonvv = lon[0,:,:]
    8450         latvv = lat[0,:,:]
    8451     elif len(lon.shape) == 2:
    8452         lonvv = lon[:]
    8453         latvv = lat[:]
    8454     elif len(lon.shape) == 1:
    8455         lonlatv = np.meshgrid(lon[:],lat[:])
    8456         lonvv = lonlatv[0]
    8457         latvv = lonlatv[1]
    8458 
    8459     return lonvv, latvv
    84607239
    84617240def compute_tevolboxtraj(values, ncfile, varn):
     
    93578136#compute_tevolboxtraj('001/trajectory.dat@0,XLONG,XLAT,ZNU,Times,wrf,3,3',       \
    93588137#  '001/full_concatenated.nc', 'PSFC')
    9359 
    9360 def interpolate_locs(locs,coords,kinterp):
    9361     """ Function to provide interpolate locations on a given axis
    9362     interpolate_locs(locs,axis,kinterp)
    9363       locs= locations to interpolate
    9364       coords= axis values with the reference of coordinates
    9365       kinterp: kind of interpolation
    9366         'lin': linear
    9367     >>> coordinates = np.arange((10), dtype=np.float)
    9368     >>> values = np.array([-1.2, 2.4, 5.6, 7.8, 12.0])
    9369     >>> interpolate_locs(values,coordinates,'lin')
    9370     [ -1.2   2.4   5.6   7.8  13. ]
    9371     >>> coordinates[0] = 0.5
    9372     >>> coordinates[2] = 2.5
    9373     >>> interpolate_locs(values,coordinates,'lin')
    9374     [ -3.4          1.93333333   5.6          7.8         13.        ]
    9375     """
    9376 
    9377     fname = 'interpolate_locs'
    9378 
    9379     if locs == 'h':
    9380         print fname + '_____________________________________________________________'
    9381         print interpolate_locs.__doc__
    9382         quit()
    9383 
    9384     Nlocs = locs.shape[0]
    9385     Ncoords = coords.shape[0]
    9386 
    9387     dcoords = coords[Ncoords-1] - coords[0]
    9388 
    9389     intlocs = np.zeros((Nlocs), dtype=np.float)
    9390     minc = np.min(coords)
    9391     maxc = np.max(coords)
    9392 
    9393     for iloc in range(Nlocs):
    9394         for icor in range(Ncoords-1):
    9395             if locs[iloc] < minc and dcoords > 0.:
    9396                 a = 0.
    9397                 b = 1. / (coords[1] - coords[0])
    9398                 c = coords[0]
    9399             elif locs[iloc] > maxc and dcoords > 0.:
    9400                 a = (Ncoords-1)*1.
    9401                 b = 1. / (coords[Ncoords-1] - coords[Ncoords-2])
    9402                 c = coords[Ncoords-2]
    9403             elif locs[iloc] < minc and dcoords < 0.:
    9404                 a = (Ncoords-1)*1.
    9405                 b = 1. / (coords[Ncoords-1] - coords[Ncoords-2])
    9406                 c = coords[Ncoords-2]
    9407             elif locs[iloc] > maxc and dcoords < 0.:
    9408                 a = 0.
    9409                 b = 1. / (coords[1] - coords[0])
    9410                 c = coords[0]
    9411             elif locs[iloc] >= coords[icor] and locs[iloc] < coords[icor+1] and dcoords > 0.:
    9412                 a = icor*1.
    9413                 b = 1. / (coords[icor+1] - coords[icor])
    9414                 c = coords[icor]
    9415                 print coords[icor], locs[iloc], coords[icor+1], ':', icor, '->', a, b
    9416             elif locs[iloc] <= coords[icor] and locs[iloc] > coords[icor+1] and dcoords < 0.:
    9417                 a = icor*1.
    9418                 b = 1. / (coords[icor+1] - coords[icor])
    9419                 c = coords[icor]
    9420 
    9421         if kinterp == 'lin':
    9422             intlocs[iloc] = a + (locs[iloc] - c)*b
    9423         else:
    9424             print errormsg
    9425             print '  ' + fname + ": interpolation kind '" + kinterp + "' not ready !!!!!"
    9426             quit(-1)
    9427 
    9428     return intlocs
    9429 
    9430 def vertical_interpolation2D(varb,vart,zorigvals,znewval,kinterp):
    9431     """ Function to vertically integrate a 3D variable
    9432     vertical_interpolation2D(varb,vart,zorigvals,znewval)
    9433       varb= values at the base of the interval of interpolation (2D field)
    9434       vart= values at the top of the interval of interpolation (2D field)
    9435       zorigvals= pair of original values (2, 2D field)
    9436       znewval= new value to interpolate
    9437       Possible cases:
    9438         zorigvals[0,:,:] <= znewval < zorigvals[1,:,:]
    9439         znewval <= zorigvals[0,:,:] < zorigvals[1,:,:]
    9440         zorigvals[0,:,:] < zorigvals[1,:,:] <= znewval
    9441       kinterp: kind of interpolation
    9442         'lin': linear
    9443     >>> dx=5
    9444     >>> dy=7
    9445     >>> vals1 = np.ones((dy,dx), dtype=np.float)
    9446     >>> vals2 = np.ones((dy,dx), dtype=np.float)*2.
    9447 
    9448     >>> zbase = np.zeros((2,dy,dx), dtype=np.float)
    9449     >>> zbase[0,:,:] = 0.5
    9450     >>> zbase[1,:,:] = 1.
    9451 
    9452     >>> vertical_interpolation2D(vals1,vals2, zbase, newz,'lin')
    9453     [[ 1.5  1.5  1.5  1.5  1.5]
    9454      [ 1.5  1.5  1.5  1.5  1.5]
    9455      [ 1.5  1.5  1.5  1.5  1.5]
    9456      [ 1.5  1.5  1.5  1.5  1.5]
    9457      [ 1.5  1.5  1.5  1.5  1.5]
    9458      [ 1.5  1.5  1.5  1.5  1.5]
    9459      [ 1.5  1.5  1.5  1.5  1.5]]
    9460     """
    9461 
    9462     fname = 'vertical_interpolation2D'
    9463 
    9464     if varb == 'h':
    9465         print fname + '_____________________________________________________________'
    9466         print vertical_interpolation2D.__doc__
    9467         quit()
    9468 
    9469     newvar = np.zeros((varb.shape), dtype=np.float)
    9470     if kinterp == 'lin':
    9471 ##        print '  ' + fname + ' Vertical linear interpolation at',znewval
    9472 # Standard linear interpolation (y = a + b*incz)
    9473 #   a = zorig[0], b = (vart-varb)/(zorig[1]-zorig[0])), incz = znewval - zorig[0]
    9474         a = varb
    9475         b = np.where(zorigvals[1,:,:] == zorigvals[0,:,:], 0.,                       \
    9476           (vart - varb)/(zorigvals[1,:,:] - zorigvals[0,:,:]))
    9477         incz = np.ones((varb.shape), dtype=np.float)*znewval - zorigvals[0,:,:]
    9478 
    9479         newvar = a + b*incz
    9480 # Too code for not be used... but maybe?
    9481 #        dx=varb.shape[1]
    9482 #        dy=varb.shape[0]
    9483 #        for j in range(dy):
    9484 #            for i in range(dx):
    9485 #                  if zorigvals[1,j,i] == zorigvals[0,j,i]: print 'equals!',          \
    9486 #                    zorigvals[1,j,i], zorigvals[0,j,i],':',newvar[j,i],'@',vart[j,i]
    9487 #                  if zorigvals[0,j,i] != zorigvals[0,j,i]: print '0 Nan',            \
    9488 #                    zorigvals[0,j,i],':',newvar[j,i],'@',vart[j,i]
    9489 #                  if zorigvals[1,j,i] != zorigvals[1,j,i]: print '1 Nan',            \
    9490 #                    zorigvals[1,j,i],':',newvar[j,i],'@',vart[j,i]
    9491 #                  if zorigvals[0,j,i] is None: print '0 None', zorigvals[0,j,i],':', \
    9492 #                    newvar[j,i],'@',vart[j,i]
    9493 #                  if zorigvals[1,j,i] is None: print '1 None', zorigvals[1,j,i],':', \
    9494 #                    newvar[j,i],'@',vart[j,i]
    9495     else:
    9496         print errormsg
    9497         print '  ' + fname + ": interpolation kind '" + kinterp + "' not ready !!!!!"
    9498         quit(-1)
    9499 
    9500     return newvar
    9501 
    9502 #dx=5
    9503 #dy=7
    9504 #vals1 = np.ones((dy,dx), dtype=np.float)
    9505 #vals2 = np.ones((dy,dx), dtype=np.float)*2.
    9506 
    9507 #zbase = np.zeros((2,dy,dx), dtype=np.float)
    9508 #zbase[0,:,:] = 0.5
    9509 #for i in range(dx):
    9510 #    for j in range(dy):
    9511 #        zbase[1,j,i] = np.sqrt((j-dy/2.)**2. + (i-dx/2.)**2.) /                      \
    9512 #          np.sqrt((dy/2.)**2.+(dy/2.)**2.) + 1.
    9513 
    9514 #zbase[1,:,:] = 1.
    9515 
    9516 #newz = 0.75
    9517 
    9518 #print vertical_interpolation2D(vals1,vals2, zbase, newz,'lin')
    9519 
    9520 def vertical_interpolation(varb,vart,zorigvals,znewval,kinterp):
    9521     """ Function to vertically integrate a 1D variable
    9522     vertical_interpolation(varb,vart,zorigvals,znewval)
    9523       varb= values at the base of the interval of interpolation
    9524       vart= values at the top of the interval of interpolation
    9525       zorigvals= pair of original values (2)
    9526       znewval= new value to interpolate
    9527       Possible cases:
    9528         zorigvals[0,:] <= znewval < zorigvals[1,:]
    9529         znewval <= zorigvals[0,:] < zorigvals[1,:]
    9530         zorigvals[0,:] < zorigvals[1,:] <= znewval
    9531       kinterp: kind of interpolation
    9532         'lin': linear
    9533     >>> dx=5
    9534     >>> vals1 = np.ones((dx), dtype=np.float)
    9535     >>> vals2 = np.ones((dx), dtype=np.float)*2.
    9536 
    9537     >>> zbase = np.zeros((2,dx), dtype=np.float)
    9538     >>> zbase[0,:] = 0.5
    9539     >>> for i in range(dx):
    9540     >>>     zbase[1,i] = i + 1.
    9541 
    9542     >>> newz = 0.75
    9543     >>> vertical_interpolation2D(vals1,vals2, zbase, newz,'lin')
    9544     [ 1.5         1.16666667  1.1         1.07142857  1.05555556]
    9545     """
    9546 
    9547     fname = 'vertical_interpolation'
    9548 
    9549     if varb == 'h':
    9550         print fname + '_____________________________________________________________'
    9551         print vertical_interpolation.__doc__
    9552         quit()
    9553 
    9554     newvar = np.zeros((varb.shape), dtype=np.float)
    9555     if kinterp == 'lin':
    9556 ##        print '  ' + fname + ' Vertical linear interpolation at',znewval
    9557 # Standard linear interpolation (y = a + b*incz)
    9558 #   a = zorig[0], b = (vart-varb)/(zorig[1]-zorig[0])), incz = znewval - zorig[0]
    9559         a = varb
    9560         b = np.where(zorigvals[1,:] == zorigvals[0,:], 0.,                           \
    9561           (vart - varb)/(zorigvals[1,:] - zorigvals[0,:]))
    9562         incz = np.ones((varb.shape), dtype=np.float)*znewval - zorigvals[0,:]
    9563 
    9564         newvar = a + b*incz
    9565     else:
    9566         print errormsg
    9567         print '  ' + fname + ": interpolation kind '" + kinterp + "' not ready !!!!!"
    9568         quit(-1)
    9569 
    9570     return newvar
    9571 
    9572 def interpolate_3D(zorigvs, varv, zintvs, kint):
    9573     """ Function to interpolate a 3D variable
    9574     interpolate_3D(zintvs, varv, zorigvals)
    9575       zorigvs= original 3D z values
    9576       varv= 3D variable to interpolate
    9577       zintvs= new series of z values to interpolate
    9578       kint= kind of interpolation
    9579         'lin': linear
    9580     """
    9581     fname = 'interpolate_3D'
    9582 
    9583     if zorigvs == 'h':
    9584         print fname + '_____________________________________________________________'
    9585         print interpolate_3D.__doc__
    9586         quit()
    9587 
    9588     Ninv = len(zintvs)
    9589     dimv = varv.shape
    9590 
    9591 # Sense of the original z-variable
    9592     Lzorig = zorigvs.shape[0]
    9593     incz = zorigvs[Lzorig-1,0,0] - zorigvs[0,0,0]
    9594 
    9595     varin = np.zeros((Ninv,dimv[1],dimv[2]), dtype=np.float)
    9596 
    9597     for ilev in range(Ninv):
    9598 #        print ' vertical interpolate level: ',zintvs[ilev]
    9599         valinf = np.zeros((dimv[1], dimv[2]), dtype=np.float)
    9600         valsup = np.zeros((dimv[1], dimv[2]), dtype=np.float)
    9601         zorigv = np.zeros((2,dimv[1], dimv[2]), dtype=np.float)
    9602         for j in range(valinf.shape[0]):
    9603             for i in range(valinf.shape[1]):
    9604                
    9605                 if np.min(zorigvs[:,j,i]) > zintvs[ilev] and incz > 0.:
    9606                     valinf[j,i] = varv[0,j,i]
    9607                     valsup[j,i] = varv[1,j,i]
    9608                     zorigv[0,j,i] = zorigvs[0,j,i]
    9609                     zorigv[1,j,i] = zorigvs[1,j,i]
    9610                 elif np.max(zorigvs[:,j,i]) < zintvs[ilev] and incz < 0.:
    9611                     valinf[j,i] = varv[0,j,i]
    9612                     valsup[j,i] = varv[1,j,i]
    9613                     zorigv[0,j,i] = zorigvs[0,j,i]
    9614                     zorigv[1,j,i] = zorigvs[1,j,i]
    9615                 elif np.max(zorigvs[:,j,i]) < zintvs[ilev] and incz > 0.:
    9616                     valinf[j,i] = varv[Lzorig-2,j,i]
    9617                     valsup[j,i] = varv[Lzorig-1,j,i]
    9618                     zorigv[0,j,i] = zorigvs[Lzorig-2,j,i]
    9619                     zorigv[1,j,i] = zorigvs[Lzorig-1,j,i]
    9620                 elif np.min(zorigvs[:,j,i]) > zintvs[ilev] and incz < 0.:
    9621                     valinf[j,i] = varv[Lzorig-2,j,i]
    9622                     valsup[j,i] = varv[Lzorig-1,j,i]
    9623                     zorigv[0,j,i] = zorigvs[Lzorig-2,j,i]
    9624                     zorigv[1,j,i] = zorigvs[Lzorig-1,j,i]
    9625 #                    print 'top: ',i,j,':',zorigv[0,j,i], zintvs[ilev], zorigv[1,j,i]
    9626                 else:
    9627                     for z in range(Lzorig-1):
    9628                         if (zorigvs[z,j,i]-zintvs[ilev])*(zorigvs[z+1,j,i]-          \
    9629                           zintvs[ilev]) <= 0.:
    9630                             valinf[j,i] = varv[z,j,i]
    9631                             valsup[j,i] = varv[z+1,j,i]
    9632                             zorigv[0,j,i] = zorigvs[z,j,i]
    9633                             zorigv[1,j,i] = zorigvs[z+1,j,i]
    9634                             break
    9635 
    9636 #        print 'zorigvs: ',zorigvs[:,0,0]
    9637 #        print '  valinf:', valinf[0,0]
    9638 #        print '  valsup:', valsup[0,0]
    9639 #        print '  zorigv 0:',zorigv[0,0,0]
    9640 #        print '  zorigv 1:',zorigv[1,0,0]
    9641 
    9642         varin[ilev,:,:] = vertical_interpolation2D(valinf,valsup,zorigv,             \
    9643           zintvs[ilev], kint)
    9644 #        print '  varin:',varin[ilev,0,0]
    9645 #        quit()
    9646 
    9647 #    quit()
    9648     return varin
    9649 
    9650 def interpolate_2D(zorigvs0, varv0, zdim, zintvs, kint):
    9651     """ Function to interpolate a 2D variable
    9652     interpolate_2D(zintvs, varv, zorigvals)
    9653       zorigvs= original 2D z values
    9654       varv= 2D variable to interpolate
    9655       zdim= number of the dimension with the z-values
    9656       zintvs= new series of z values to interpolate
    9657       kint= kind of interpolation
    9658         'lin': linear
    9659     """
    9660     fname = 'interpolate_2D'
    9661 
    9662     if zorigvs0 == 'h':
    9663         print fname + '_____________________________________________________________'
    9664         print interpolate_2D.__doc__
    9665         quit()
    9666 
    9667     Ninv = len(zintvs)
    9668     if zdim == 0:
    9669         varv = varv0
    9670         zorigvs = zorigvs0
    9671     else:
    9672         varv = np.transpose(varv0)
    9673         zorigvs = np.transpose(zorigvs0)
    9674 
    9675     dimv = varv.shape
    9676 
    9677 # Sense of the original z-variable
    9678     Lzorig = zorigvs.shape[0]
    9679     incz = zorigvs[Lzorig-1,0] - zorigvs[0,0]
    9680 
    9681     varin = np.zeros((Ninv,dimv[1]), dtype=np.float)
    9682 
    9683     for ilev in range(Ninv):
    9684         valinf = np.zeros((dimv[1]), dtype=np.float)
    9685         valsup = np.zeros((dimv[1]), dtype=np.float)
    9686         zorigv = np.zeros((2,dimv[1]), dtype=np.float)
    9687         for i in range(valinf.shape[0]):   
    9688             if np.min(zorigvs[:,i]) > zintvs[ilev] and incz > 0.:
    9689                 valinf[i] = varv[0,i]
    9690                 valsup[i] = varv[1,i]
    9691                 zorigv[0,i] = zorigvs[0,i]
    9692                 zorigv[1,i] = zorigvs[1,i]
    9693             elif np.max(zorigvs[:,i]) < zintvs[ilev] and incz < 0.:
    9694                 valinf[i] = varv[0,i]
    9695                 valsup[i] = varv[1,i]
    9696                 zorigv[0,i] = zorigvs[0,i]
    9697                 zorigv[1,i] = zorigvs[1,i]
    9698             elif np.max(zorigvs[:,i]) < zintvs[ilev] and incz > 0.:
    9699                 valinf[i] = varv[Lzorig-2,i]
    9700                 valsup[i] = varv[Lzorig-1,i]
    9701                 zorigv[0,i] = zorigvs[Lzorig-2,i]
    9702                 zorigv[1,i] = zorigvs[Lzorig-1,i]
    9703             elif np.min(zorigvs[:,i]) > zintvs[ilev] and incz < 0.:
    9704                 valinf[i] = varv[Lzorig-2,i]
    9705                 valsup[i] = varv[Lzorig-1,i]
    9706                 zorigv[0,i] = zorigvs[Lzorig-2,i]
    9707                 zorigv[1,i] = zorigvs[Lzorig-1,i]
    9708             else:
    9709                 for z in range(Lzorig-1):
    9710                     if (zorigvs[z,i]-zintvs[ilev])*(zorigvs[z+1,i]-                  \
    9711                       zintvs[ilev]) <= 0.:
    9712                         valinf[i] = varv[z,i]
    9713                         valsup[i] = varv[z+1,i]
    9714                         zorigv[0,i] = zorigvs[z,i]
    9715                         zorigv[1,i] = zorigvs[z+1,i]
    9716                         break
    9717 
    9718         varin[ilev,:] = vertical_interpolation(valinf,valsup,zorigv,                 \
    9719           zintvs[ilev], kint)
    9720 
    9721     if zdim == 0:
    9722         varin0 = varin
    9723     else:
    9724         varin0 = np.transpose(varin)
    9725 
    9726     return varin0
    9727 
    9728 
    9729 def list_toVec(listv, kind):
    9730     """ Function to transform from a list of values to a vector
    9731     list_toVec(listv, kind)
    9732       listv= list with the values
    9733       kind= kind of values
    9734       >>> list_toVec(['1', 2, '3', 4, 5, '6.9', 7, 9], 'npfloat')
    9735       [ 1.   2.   3.   4.   5.   6.9  7.   9. ]
    9736     """
    9737 
    9738     fname = 'list_toVec'
    9739 
    9740     if listv == 'h':
    9741         print fname + '_____________________________________________________________'
    9742         print list_toVec.__doc__
    9743         quit()
    9744 
    9745     Nvals = len(listv)
    9746 
    9747     if kind == 'npfloat':
    9748         vecv = np.zeros((Nvals), dtype=np.float)
    9749         for iv in range(Nvals):
    9750             vecv[iv] = np.float(listv[iv])
    9751     else:
    9752         print errormsg
    9753         print '  ' + fname + ': type of value "' + kind + '" not ready!!'
    9754         quit(-1)
    9755 
    9756     return vecv
    9757 
    9758 def running_mean(values, run):
    9759     """ Function to compute a running mean of a series of values
    9760       running_mean(vals, int)
    9761       [vals]: series of values
    9762       [run]: interval to use to compute the running mean
    9763         NOTE: resultant size would be the same but with None except at [run/2,size(vals)-run/2]
    9764       >>> running_mean(np.arange(100),10)
    9765       [None None None None None 4.5 5.5 6.5 7.5 8.5 9.5 10.5 11.5 12.5 13.5 14.5
    9766        15.5 16.5 17.5 18.5 19.5 20.5 21.5 22.5 23.5 24.5 25.5 26.5 27.5 28.5 29.5
    9767        30.5 31.5 32.5 33.5 34.5 35.5 36.5 37.5 38.5 39.5 40.5 41.5 42.5 43.5 44.5
    9768        45.5 46.5 47.5 48.5 49.5 50.5 51.5 52.5 53.5 54.5 55.5 56.5 57.5 58.5 59.5
    9769        60.5 61.5 62.5 63.5 64.5 65.5 66.5 67.5 68.5 69.5 70.5 71.5 72.5 73.5 74.5
    9770        75.5 76.5 77.5 78.5 79.5 80.5 81.5 82.5 83.5 84.5 85.5 86.5 87.5 88.5 89.5
    9771        90.5 91.5 92.5 93.5 None None None None None]
    9772     """
    9773     fname = 'running_mean'
    9774 
    9775     if values == 'h':
    9776         print fname + '_____________________________________________________________'
    9777         print running_mean.__doc__
    9778         quit()
    9779 
    9780     runmean = np.ones((len(values)), dtype=np.float)*fillValue
    9781 
    9782     for ip in range(run/2,len(values)-run/2):
    9783         runmean[ip] = np.mean(values[ip-run/2:ip+run/2])
    9784 
    9785     runmean = np.where(runmean == fillValue, None, runmean)
    9786 
    9787     return runmean
    97888138
    97898139def slice_variable(varobj, dimslice):
     
    105598909#WRF_CFlon_creation('longitude', 'wrfout_d01_1980-03-01_00:00:00_Time_B0-E48-I1.nc', 'XLONG')
    105608910
    10561 
    105628911def dimVar_creation(values, ncfile):
    105638912    """ Function to add a 1D variable with the size of a given dimension in a file
     
    106048953
    106058954#dimVar_creation('bottom_top', 'wrfout_d01_1979-12-01_00:00:00_south_north_B3-E3-I1_west_east_B26-E26-I1.nc')
    10606 
    10607 def files_folder(folder,headfile):
    10608     """ Function to retrieve a list of files from a folder [fold] and head [headfile]
    10609     >>> files_folder('/media/data2/etudes/WRF_LMDZ/WL_HyMeX_HighRes/medic950116/',
    10610       'wrfout_d03')
    10611     ['wrfout_d03_1995-01-13_02:00:00', 'wrfout_d03_1995-01-13_04:00:00', 'wrfout_d03_1995-01-13_06:00:00',
    10612      'wrfout_d03_1995-01-13_06:15:00', 'wrfout_d03_1995-01-13_08:15:00', 'wrfout_d03_1995-01-13_10:15:00',
    10613      'wrfout_d03_1995-01-13_12:15:00', 'wrfout_d03_1995-01-13_14:15:00', 'wrfout_d03_1995-01-13_16:15:00',     
    10614      (...)
    10615      'wrfout_d03_1995-01-17_18:15:00', 'wrfout_d03_1995-01-17_20:15:00', 'wrfout_d03_1995-01-17_22:15:00']
    10616     """
    10617     import subprocess as sub
    10618     fname = 'files_folder'
    10619 
    10620     if folder == 'h':
    10621         print fname + '_____________________________________________________________'
    10622         print files_folder.__doc__
    10623         quit()
    10624 
    10625 #    ins = folder + "/" + headfile + "*"
    10626     ins = folder + "/"
    10627     print 'ins:',ins
    10628     files = sub.Popen(["/bin/ls","-1",ins], stdout=sub.PIPE)
    10629     fileslist = files.communicate()
    10630     listfiles0 = str(fileslist).split('\\n')
    10631 
    10632 # Filtering output
    10633     Lheader=len(headfile)
    10634     listfiles = []
    10635     for ifile in listfiles0:
    10636         if ifile[0:Lheader] == headfile:
    10637             listfiles.append(ifile)
    10638 
    10639     return listfiles
    106408955
    106418956def netcdf_fold_concatenation(values, ncfile, varn):
     
    108929207#netcdf_concatenation('mean_pluc.nc@all|mean_dtcon.nc@all')
    108939208
    10894 def count_cond(var, val, con):
    10895     """ Function to count values of a variable which attain a condition
    10896       [var]= variable
    10897       [val]= value
    10898       [con]= statistics/condition
    10899         'eq': equal than [val]
    10900         'neq': not equal than [val]
    10901         'lt': less than [val]
    10902         'le': less and equal than [val]
    10903         'gt': greater than [val]
    10904         'ge': greater and equal than [val]
    10905         'in': inside the range [val[0]] <= [var] <= [val[1]] (where [val]=[val1, val2]
    10906         'out': inside the range [val[0]] > [var]; [val[1]] < [var] (where [val]=[val1, val2]
    10907       >>> vals = np.arange(100)
    10908       >>> count_cond(vals,50,'eq')
    10909       1
    10910       >>> count_cond(vals,50,'neq')
    10911       99
    10912       >>> count_cond(vals,50,'lt')
    10913       50
    10914       >>> count_cond(vals,50,'le')
    10915       51
    10916       >>> count_cond(vals,50,'gt')
    10917       49
    10918       >>> count_cond(vals,50,'ge')
    10919       50
    10920       >>> count_cond(vals,[25,75],'in')
    10921       51
    10922       >>> count_cond(vals,[25,75],'out')
    10923       49
    10924     """
    10925     fname = 'count_cond'
    10926 
    10927     cons = ['eq', 'neq', 'lt', 'le', 'gt', 'ge', 'in', 'out']
    10928 
    10929     if con == 'eq':
    10930         Nvals = np.sum(var == val)
    10931     elif con == 'neq':
    10932         Nvals = np.sum(var != val)
    10933     elif con == 'lt':
    10934         Nvals = np.sum(var < val)
    10935     elif con == 'le':
    10936         Nvals = np.sum(var <= val)
    10937     elif con == 'gt':
    10938         Nvals = np.sum(var > val)
    10939     elif con == 'ge':
    10940         Nvals = np.sum(var >= val)
    10941     elif con == 'in':
    10942         if len(val) != 2:
    10943             print errormsg
    10944             print '  ' + fname + ": for condition '" + con + "' we must have two " + \
    10945               " values!!"
    10946             print '  we have:',  val
    10947             quit(-1)
    10948         Nvals = np.sum((var >= val[0])*(var <= val[1]))
    10949     elif con == 'out':
    10950         if len(val) != 2:
    10951             print errormsg
    10952             print '  ' + fname + ": for condition '" + con + "' we must have two " + \
    10953               " values!!"
    10954             print '  we have:',  val
    10955             quit(-1)
    10956         Nvals = np.sum((var < val[0])+(var > val[1]))
    10957     else:
    10958         print errormsg
    10959         print '  ' + fname + ": condition '" + con + "' not ready!!"
    10960         print '  only ready:', cons
    10961         quit(-1)
    10962 
    10963     return Nvals
    10964 
    109659209def field_stats(values, ncfile, varn):
    109669210    """ Function to retrieve statistics from a field
     
    110749318
    110759319#field_stats('full', 'geo_em.d01.nc', 'HGT_M')
    11076 
    11077 def get_namelist_vars(values, namelist):
    11078     """ Function to get namelist-like  values ([varname] = [value])
    11079     get_namelist_vars(namelist)
    11080       values= [sectionname],[kout]
    11081         [sectionname]: name of the section from which one want the values ('all', for all)
    11082         [kout]: kind of output
    11083           'tex3': printed output as LaTeX table of three columns \verb+namelist_name+ & value
    11084           'column': printed output as namelist_name value
    11085           'dict': as two python dictionary object (namelistname, value and namelistname, sectionname)
    11086       namelist= namelist_like file to retrieve values
    11087     >>> get_namelist_vars('geogrid,dic','/home/lluis/etudes/domains/medic950116/namelist.wps')
    11088     {'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,'}
    11089     """
    11090 
    11091     fname = 'get_namelist_vars'
    11092 
    11093 # List of characters which split pairs name/value
    11094     valuessep = ['=']
    11095 # List of characters which indicate a comment
    11096     commentchars = ['#']
    11097 
    11098     if values == 'h':
    11099         print fname + '_____________________________________________________________'
    11100         print get_namelist_vars.__doc__
    11101         quit()
    11102 
    11103     expectargs = '[sectionname],[kout]'
    11104     check_arguments(fname,values,expectargs,',')
    11105 
    11106     secname = values.split(',')[0]
    11107     kout = values.split(',')[1]
    11108 
    11109     if not os.path.isfile(namelist):
    11110         print errormsg
    11111         print '  ' + fname + ": namelist file '" + namelist + "' does not exist !!"
    11112         quit(-1)
    11113 
    11114     ncml = open(namelist, 'r')
    11115 
    11116     sections = {}
    11117     namelistvals = {}
    11118     namelistsecs = {}
    11119     sectionnames = []
    11120     namessec = []
    11121     allnames = []
    11122     namelistvalssec = {}
    11123     namelistsecssec = {}
    11124     nmlname = ''
    11125     sectionname = ''
    11126 
    11127     for line in ncml:
    11128         linevals = reduce_spaces(line)
    11129         Nvals = len(linevals)
    11130 
    11131         if Nvals >= 1 and linevals[0][0:1] == '&':
    11132             if len(sectionnames) > 1:
    11133                 sections[sectionname] = namessec
    11134 
    11135             sectionname = linevals[0][1:len(linevals[0])+1]
    11136 #            print '    ' + fname + ": new section '" + sectionname + "' !!!"
    11137             sectionnames.append(sectionname)
    11138             namessec = []
    11139             nmlname = ''
    11140         elif Nvals >= 1 and not searchInlist(commentchars,linevals[0][0:1]):
    11141             if Nvals >= 3 and searchInlist(valuessep,linevals[1]):
    11142                 nmlname = linevals[0]
    11143                 nmlval = numVector_String(linevals[2:Nvals],' ')
    11144             elif Nvals == 1:
    11145                 for valsep in valuessep:
    11146                     if linevals[0].find(valsep) != -1:
    11147                         nmlname = linevals[0].split(valsep)[0]
    11148                         nmlval = linevals[0].split(valsep)[1]
    11149                         break
    11150             elif Nvals == 2:
    11151                 for valsep in valuessep:
    11152                     if linevals[0].find(valsep) != -1:
    11153                         nmlname = linevals[0].split(valsep)[0]
    11154                         nmlval = linevals[1]
    11155                         break
    11156                     elif linevals[1].find(valsep) != -1:
    11157                         nmlname = linevals[0]
    11158                         nmlval = linevals[1].split(valsep)[0]
    11159                         break
    11160             else:
    11161                 print warnmsg
    11162                 print '  ' + fname + ': wrong number of values', Nvals,              \
    11163                   'in the namelist line!'
    11164                 print '    line: ',line
    11165                 print '    line values:',linevals
    11166 #                quit(-1)
    11167 
    11168             namelistvals[nmlname] = nmlval
    11169             namelistsecs[nmlname] = sectionname
    11170 
    11171             namessec.append(nmlname)
    11172             allnames.append(nmlname)
    11173 
    11174     if len(sectionname) > 1:
    11175         sections[sectionname] = namessec
    11176 
    11177     if secname != 'all':
    11178         if not searchInlist(sections.keys(),secname):
    11179             print errormsg
    11180             print '  ' + fname + ": section '" + values + "' does not exist !!"
    11181             print '    only found:',sectionnames
    11182             quit(-1)
    11183 
    11184         namestouse = []
    11185         for nml in allnames:
    11186             for nnml in sections[secname]:
    11187                 namelistvalssec[nnml] = namelistvals[nnml]
    11188                 namelistsecssec[nnml] = secname
    11189                 if nml == nnml: namestouse.append(nml)
    11190     else:
    11191         namestouse = allnames
    11192         namelistvalssec = namelistvals
    11193         namelistsecssec = namelistsecs
    11194 
    11195     if kout == 'tex3':
    11196         ofile='get_namelist_vars_3col.tex'
    11197         fobj = open(ofile, 'w')
    11198 
    11199         vals = namestouse
    11200         Nvals = len(vals)
    11201         Nvals3 = int(Nvals/3)
    11202         latextab = '\\begin{center}\n\\begin{tabular}{lclclc}\n'
    11203         for il in range(2):
    11204             latextab = latextab + '{\\bfseries{name}} & {\\bfseries{value}} & '
    11205         latextab= latextab+ '{\\bfseries{name}} & {\\bfseries{value}} \\\\ \\hline\n'
    11206 
    11207         if np.mod(Nvals,3) != 0:
    11208             Nvals0 = Nvals - np.mod(Nvals,3)
    11209         else:
    11210             Nvals0 = Nvals
    11211 
    11212         for ival in range(0,Nvals0,3):
    11213             line = ''
    11214             print '  ival:',ival
    11215             for il in range(2):
    11216                 line = line + '\\verb+' + vals[ival+il] + '+ & ' +                   \
    11217                    namelistvalssec[vals[ival+il]].replace('_','\\_') +' & '
    11218             line = line + '\\verb+' + vals[ival+2] + '+ & ' +                       \
    11219                namelistvalssec[vals[ival+2]].replace('_','\\_') + ' \\\\\n'
    11220             latextab = latextab + line
    11221 
    11222         latextab = latextab + '%not multiple of three!!!!\n'
    11223         print 'mod:', np.mod(Nvals,3),Nvals0,Nvals
    11224         if np.mod(Nvals,3) != 0:
    11225             ival = Nvals0
    11226             line = ''
    11227             for il in range(np.mod(Nvals,3)):
    11228                 print 'ival:',ival + il
    11229                 line = line + '\\verb+' + vals[ival+il] + '+ & ' +                   \
    11230                       namelistvalssec[vals[ival+il]].replace('_','\\_') + ' & '
    11231             for il in range(2-np.mod(Nvals,3)):
    11232                 line = line + ' & & '
    11233             latextab = latextab + line + ' & \\\\\n'
    11234         latextab = latextab + '\\end{tabular}\n\\end{center}\n'
    11235 
    11236 #        print latextab
    11237         fobj.write(latextab)
    11238  
    11239         fobj.close()
    11240         print fname + ": successful writen '" + ofile + "' LaTeX tale file !!"
    11241 
    11242         return
    11243     elif kout == 'column':
    11244         for dictv in namestouse:
    11245             print dictv + ' = ' + namelistvalssec[dictv]
    11246         return
    11247     elif kout == 'dict':
    11248         return namelistvalssec, namelistsecssec
    11249     else:
    11250         print errormsg
    11251         print '  ' + fname + ": kind of output '" + kout + "' not ready!!!"
    11252         quit(-1)
    11253 
    11254     return
    11255 
    11256 def WRF_d0Nref(values, geofold):
    11257     """ Function for the generation of an extra WRF domain from a given one
    11258     field_stats(values, ncfile, varn)
    11259       [values]= [namelist],[minLON],[minLAT],[maxLON],[maxLAT],[Ndomref],[factor],[geogres]
    11260         [namelist]: namelist.wps to use
    11261         [minLON],[minLAT]: minimum longitude and latitude
    11262         [maxLON],[maxLAT]: maximum longitude and latitude
    11263         [Ndomref]: domain reference number
    11264         [factor]: resolution factor with respect d01
    11265         [geogres]: which topography resolution to use
    11266       [geofold]= folder where to found the geo_em.d0[N-1].nc file
    11267     """
    11268 
    11269     fname='WRF_d0Nref'
    11270 
    11271     if values == 'h':
    11272         print fname + '_____________________________________________________________'
    11273         print WRF_d0Nref.__doc__
    11274         quit()
    11275 
    11276     expectargs = '[namelist],[minLON],[minLAT],[maxLON],[maxLAT],[Ndomref],[factor],'
    11277     expectargs = expectargs + '[geogres]'
    11278  
    11279     check_arguments(fname,values,expectargs,',')
    11280 
    11281     namelist = values.split(',')[0]
    11282     minLON = np.float(values.split(',')[1])
    11283     minLAT = np.float(values.split(',')[2])
    11284     maxLON = np.float(values.split(',')[3])
    11285     maxLAT = np.float(values.split(',')[4])
    11286     Ndomref = int(values.split(',')[5])
    11287     factor = int(values.split(',')[6])
    11288     geogres = values.split(',')[7]
    11289 
    11290     onml = 'namelist.wps_d0' + str(Ndomref+1)
    11291 
    11292 # Namelist variables to which new value is a copy of the last one
    11293     repeatvalue = ['start_date' ,'end_date']
    11294 # Namelist variables to which value is increased by 1 (single value)
    11295     add1 = ['max_dom']
    11296 # Namelist variables to which new value is an increase by 1 of the last one
    11297     add1value = ['parent_id']
    11298 
    11299 #    ncfile = geofold + '/geo_em.d' + zeros(Ndomref,2) + '.nc'
    11300     ncfile = geofold + '/geo_em.d0' + str(Ndomref) + '.nc'
    11301 
    11302     if not os.path.isfile(ncfile):
    11303         print errormsg
    11304         print '  ' + fname + ': geo_em file "' + ncfile + '" does not exist !!'
    11305         quit(-1)   
    11306 
    11307     ncobj = NetCDFFile(ncfile, 'r')
    11308 
    11309     nlon='XLONG_M'
    11310     nlat='XLAT_M'
    11311 
    11312     lonobj = ncobj.variables[nlon]
    11313     latobj = ncobj.variables[nlat]
    11314 
    11315     lon = lonobj[0,:,:]
    11316     lat = latobj[0,:,:]
    11317 
    11318     ncobj.close()
    11319 
    11320     diffmin = np.sqrt((lon - minLON)**2. + (lat - minLAT)**2.)
    11321     diffmax = np.sqrt((lon - maxLON)**2. + (lat - maxLAT)**2.)
    11322 
    11323     posdiffmin = index_mat(diffmin,np.min(diffmin))
    11324     posdiffmax = index_mat(diffmax,np.min(diffmax))
    11325 #    print 'min vals. min:',np.min(diffmin),'max:',np.min(diffmax)
    11326 
    11327 #    print 'min:', minLON, ',', minLAT, ':', posdiffmin, '.', lon[tuple(posdiffmin)], \
    11328 #      ',', lat[tuple(posdiffmin)]
    11329 #    print 'max:', maxLON, ',', maxLAT, ':', posdiffmax, '.', lon[tuple(posdiffmax)], \
    11330 #      ',', lat[tuple(posdiffmax)]
    11331 
    11332     print '  ' + fname +': coordinates of the SW corner:', posdiffmin, ' NE corner:',\
    11333       posdiffmax
    11334 
    11335     nmlobj = open(namelist, 'r')
    11336     onmlobj = open(onml, 'w')
    11337     for line in nmlobj:
    11338         listline = reduce_spaces(line)
    11339         nvals = len(listline)
    11340         if nvals > 0:
    11341             if searchInlist(add1,listline[0]):
    11342                 nmlval = int(listline[nvals-1].replace(',','')) + 1
    11343                 onmlobj.write(' ' + listline[0] + ' = ' + str(nmlval) + ',\n')
    11344             elif searchInlist(add1value,listline[0]):
    11345                 if Ndomref == 1:
    11346                     nmlval = 1
    11347                 else:
    11348                     nmlval = int(listline[nvals-1].replace(',','')) + 1   
    11349                 onmlobj.write(' ' + listline[0] + ' = ' +                            \
    11350                   numVector_String(listline[2:nvals+1], ' ') + ' ' +str(nmlval)+',\n')
    11351             elif searchInlist(repeatvalue,listline[0]):
    11352                 nmlval = listline[nvals-1]
    11353                 onmlobj.write(' ' + listline[0] + ' = ' +                            \
    11354                   numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+'\n')
    11355             elif listline[0] == 'parent_grid_ratio':
    11356                 nmlval = factor
    11357                 onmlobj.write(' ' + listline[0] + ' = ' +                            \
    11358                   numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n')
    11359             elif listline[0] == 'i_parent_start':
    11360                 nmlval = posdiffmin[1] - 10
    11361                 onmlobj.write(' ' + listline[0] + ' = ' +                            \
    11362                   numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n')
    11363             elif listline[0] == 'j_parent_start':
    11364                 nmlval = posdiffmin[0] - 10
    11365                 onmlobj.write(' ' + listline[0] + ' = ' +                            \
    11366                   numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n')
    11367             elif listline[0] == 'e_we':
    11368                 nmlval = (posdiffmax[1] - posdiffmin[1] + 20)*factor
    11369                 nmlval = nmlval + np.mod(nmlval,factor) + 1
    11370                 onmlobj.write(' ' + listline[0] + ' = ' +                            \
    11371                   numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n')
    11372             elif listline[0] == 'e_sn':
    11373                 nmlval = (posdiffmax[0] - posdiffmin[0] + 20)*factor
    11374                 nmlval = nmlval + np.mod(nmlval,factor) + 1
    11375                 onmlobj.write(' ' + listline[0] + ' = ' +                            \
    11376                   numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n')
    11377             elif listline[0] == 'geog_data_res':
    11378                 nmlval = "'" + geogres + "'"
    11379                 onmlobj.write(' ' + listline[0] + ' = ' +                            \
    11380                   numVector_String(listline[2:nvals+1],' ') + ' ' + str(nmlval)+',\n')
    11381             else:
    11382                 onmlobj.write(line)
    11383         else:
    11384             onmlobj.write('\n')
    11385 
    11386     nmlobj.close()
    11387     onmlobj.close()
    11388 
    11389     print fname + ": successfully written new namelist '" + onml + "' !!"
    11390 
    11391     return
    113929320
    113939321def filter_2dim(values, ncfile, varn):
     
    1247710405#selvar('x@lon,y@lat,time@time,shan@int', '/home/lluis/PY/test.nc', 'var')
    1247810406
    12479 def coincident_CFtimes(tvalB, tunitA, tunitB):
    12480     """ Function to make coincident times for two different sets of CFtimes
    12481     tvalB= time values B
    12482     tunitA= time units times A to which we want to make coincidence
    12483     tunitB= time units times B
    12484     >>> coincident_CFtimes(np.arange(10),'seconds since 1949-12-01 00:00:00',
    12485       'hours since 1949-12-01 00:00:00')
    12486     [     0.   3600.   7200.  10800.  14400.  18000.  21600.  25200.  28800.  32400.]
    12487     >>> coincident_CFtimes(np.arange(10),'seconds since 1949-12-01 00:00:00',
    12488       'hours since 1979-12-01 00:00:00')
    12489     [  9.46684800e+08   9.46688400e+08   9.46692000e+08   9.46695600e+08
    12490        9.46699200e+08   9.46702800e+08   9.46706400e+08   9.46710000e+08
    12491        9.46713600e+08   9.46717200e+08]
    12492     """
    12493     import datetime as dt
    12494     fname = 'coincident_CFtimes'
    12495 
    12496     trefA = tunitA.split(' ')[2] + ' ' + tunitA.split(' ')[3]
    12497     trefB = tunitB.split(' ')[2] + ' ' + tunitB.split(' ')[3]
    12498     tuA = tunitA.split(' ')[0]
    12499     tuB = tunitB.split(' ')[0]
    12500 
    12501     if tuA != tuB:
    12502         if tuA == 'microseconds':
    12503             if tuB == 'microseconds':
    12504                 tB = tvalB*1.
    12505             elif tuB == 'seconds':
    12506                 tB = tvalB*10.e6
    12507             elif tuB == 'minutes':
    12508                 tB = tvalB*60.*10.e6
    12509             elif tuB == 'hours':
    12510                 tB = tvalB*3600.*10.e6
    12511             elif tuB == 'days':
    12512                 tB = tvalB*3600.*24.*10.e6
    12513             else:
    12514                 print errormsg
    12515                 print '  ' + fname + ": combination of time untis: '" + tuA +        \
    12516                   "' & '" + tuB + "' not ready !!"
    12517                 quit(-1)
    12518         elif tuA == 'seconds':
    12519             if tuB == 'microseconds':
    12520                 tB = tvalB/10.e6
    12521             elif tuB == 'seconds':
    12522                 tB = tvalB*1.
    12523             elif tuB == 'minutes':
    12524                 tB = tvalB*60.
    12525             elif tuB == 'hours':
    12526                 tB = tvalB*3600.
    12527             elif tuB == 'days':
    12528                 tB = tvalB*3600.*24.
    12529             else:
    12530                 print errormsg
    12531                 print '  ' + fname + ": combination of time untis: '" + tuA +        \
    12532                   "' & '" + tuB + "' not ready !!"
    12533                 quit(-1)
    12534         elif tuA == 'minutes':
    12535             if tuB == 'microseconds':
    12536                 tB = tvalB/(60.*10.e6)
    12537             elif tuB == 'seconds':
    12538                 tB = tvalB/60.
    12539             elif tuB == 'minutes':
    12540                 tB = tvalB*1.
    12541             elif tuB == 'hours':
    12542                 tB = tvalB*60.
    12543             elif tuB == 'days':
    12544                 tB = tvalB*60.*24.
    12545             else:
    12546                 print errormsg
    12547                 print '  ' + fname + ": combination of time untis: '" + tuA +        \
    12548                   "' & '" + tuB + "' not ready !!"
    12549                 quit(-1)
    12550         elif tuA == 'hours':
    12551             if tuB == 'microseconds':
    12552                 tB = tvalB/(3600.*10.e6)
    12553             elif tuB == 'seconds':
    12554                 tB = tvalB/3600.
    12555             elif tuB == 'minutes':
    12556                 tB = tvalB/60.
    12557             elif tuB == 'hours':
    12558                 tB = tvalB*1.
    12559             elif tuB == 'days':
    12560                 tB = tvalB*24.
    12561             else:
    12562                 print errormsg
    12563                 print '  ' + fname + ": combination of time untis: '" + tuA +        \
    12564                   "' & '" + tuB + "' not ready !!"
    12565                 quit(-1)
    12566         elif tuA == 'days':
    12567             if tuB == 'microseconds':
    12568                 tB = tvalB/(24.*3600.*10.e6)
    12569             elif tuB == 'seconds':
    12570                 tB = tvalB/(24.*3600.)
    12571             elif tuB == 'minutes':
    12572                 tB = tvalB/(24.*60.)
    12573             elif tuB == 'hours':
    12574                 tB = tvalB/24.
    12575             elif tuB == 'days':
    12576                 tB = tvalB*1.
    12577             else:
    12578                 print errormsg
    12579                 print '  ' + fname + ": combination of time untis: '" + tuA +        \
    12580                   "' & '" + tuB + "' not ready !!"
    12581                 quit(-1)
    12582         else:
    12583             print errormsg
    12584             print '  ' + fname + ": time untis: '" + tuA + "' not ready !!"
    12585             quit(-1)
    12586     else:
    12587         tB = tvalB*1.
    12588 
    12589     if trefA != trefB:
    12590         trefTA = dt.datetime.strptime(trefA, '%Y-%m-%d %H:%M:%S')
    12591         trefTB = dt.datetime.strptime(trefB, '%Y-%m-%d %H:%M:%S')
    12592 
    12593         difft = trefTB - trefTA
    12594         diffv = difft.days*24.*3600.*10.e6 + difft.seconds*10.e6 + difft.microseconds
    12595         print '  ' + fname + ': different reference refA:',trefTA,'refB',trefTB
    12596         print '    difference:',difft,':',diffv,'microseconds'
    12597 
    12598         if tuA == 'microseconds':
    12599             tB = tB + diffv
    12600         elif tuA == 'seconds':
    12601             tB = tB + diffv/10.e6
    12602         elif tuA == 'minutes':
    12603             tB = tB + diffv/(60.*10.e6)
    12604         elif tuA == 'hours':
    12605             tB = tB + diffv/(3600.*10.e6)
    12606         elif tuA == 'dayss':
    12607             tB = tB + diffv/(24.*3600.*10.e6)
    12608         else:
    12609             print errormsg
    12610             print '  ' + fname + ": time untis: '" + tuA + "' not ready !!"
    12611             quit(-1)
    12612 
    12613     return tB
    12614 
    12615 def wdismean(pos,val4):
    12616     """ Function to compute the mean value weighted to its 4 distances
    12617       pos= x,y position within the 'square'
    12618       val4= values at the four vertexs (2,2)
    12619     >>>position = [0.005,0.005]
    12620     >>>val4 = np.zeros((2,2), dtype=np.float)
    12621     >>>val4 = np.arange(4).reshape(2,2)
    12622     0.035707955234
    12623     """
    12624     fname = 'wdismean'
    12625 
    12626     dist = np.zeros((2,2), dtype=np.float)   
    12627     dist[0,0] = np.sqrt(pos[0]*pos[0]+pos[1]*pos[1])
    12628     dist[0,1] = np.sqrt(pos[0]*pos[0]+(1.-pos[1])*(1.-pos[1]))
    12629     dist[1,0] = np.sqrt((1.-pos[0])*(1.-pos[0])+pos[1]*pos[1])
    12630     dist[1,1] = np.sqrt((1.-pos[0])*(1.-pos[0])+(1.-pos[1])*(1.-pos[1]))
    12631 
    12632     if np.min(dist) == 0.:
    12633         pos0 = index_mat(dist, 0.)
    12634         dist[:,:] = 0.
    12635         posmean = val4[pos0[0], pos0[1]]
    12636     else:
    12637         totdist = np.sum(1./dist)
    12638         posmean = np.sum(val4.flatten()/dist.flatten())/totdist
    12639 
    12640     return posmean
    12641 
    12642 def read_ASCIIlist(filen):
    12643     """ Function to build a list from an ASCII lines file
    12644       filen= name of the ASCII file
    12645     """
    12646     import os
    12647     fname = 'read_ASCIIlist'
    12648 
    12649     if not os.path.isfile(filen):
    12650         print errormsg
    12651         print '  ' + fname + ":  ASCII types file '" + filen + "' does not exist !!"
    12652         quit(-1)
    12653 
    12654     of = open(filen, 'r')
    12655     filevals = []
    12656     for linef in of:
    12657         filevals.append(linef.replace('\n',''))
    12658     of.close()
    12659 
    12660     return filevals
    12661 
    12662 def radial_points(angle,dist):
    12663     """ Function to provide a number of grid point positions for a given angle
    12664       angle= desired angle (rad)
    12665       dist= number of grid points
    12666     >>> radial_points(0.5*np.pi,5)
    12667     [[  6.12323400e-17   1.00000000e+00]
    12668      [  1.22464680e-16   2.00000000e+00]
    12669      [  1.83697020e-16   3.00000000e+00]
    12670      [  2.44929360e-16   4.00000000e+00]
    12671      [  3.06161700e-16   5.00000000e+00]]
    12672     """
    12673     fname = 'radial_points'
    12674     radpos = np.zeros((dist,2), dtype=np.float)
    12675 
    12676     for ip in range(dist):
    12677         radpos[ip,0] = (ip+1.)*np.cos(angle)
    12678         radpos[ip,1] = (ip+1.)*np.sin(angle)
    12679 
    12680     return radpos
    12681 
    12682 def read_SQradii(filename='SQradii.dat', Npt=-1, maxradii=None):
    12683     """ Function to read the outcome of the function `squared_radial'
    12684       filename= Name of the outcome file of the function
    12685       Npt= Number of points on each grid
    12686       maxradii= allowed maximum radii
    12687       'SQradii.dat': file with the radii and paris of integers after ran squared_radial(1000)
    12688     """
    12689     fname = 'read_SQradii'
    12690 
    12691     if not os.path.isfile(filename):
    12692         print errormsg
    12693         print '  ' + fname + ": file '" + filename + "' not found!!"
    12694         quit(-1)
    12695 
    12696     infile = open(filename, 'r')
    12697 
    12698     gridradii = {}
    12699     Nradii = {}
    12700     radii = []
    12701     for line in infile:
    12702         values = values_line(line, ' ', ['[', ']'])
    12703         rad = np.float(values[0])
    12704 # Limited by a given radii
    12705         if maxradii is not None and rad > maxradii: break
    12706         Nrad = int(values[2])
    12707         couples = []
    12708         Nradgood = 0
    12709         if Nrad > 1:
    12710            Ncouples = 0
    12711            for ic in range(Nrad):
    12712                ix = int(values[3 + ic*2])
    12713                iy = int(values[3 + ic*2 + 1])
    12714                if ix <= Npt and iy <= Npt:
    12715                    couples.append(np.array([ix,iy]))
    12716                    Nradgood = Nradgood + 1
    12717                elif ix > Npt and iy > Npt: break
    12718         else:
    12719              ix = int(values[3])
    12720              iy = int(values[4])
    12721              if ix <= Npt and iy <= Npt:
    12722                  couples.append(np.array([ix,iy]))
    12723                  Nradgood = Nradgood + 1
    12724              elif ix > Npt and iy > Npt: break
    12725 
    12726         if Nradgood > 0:
    12727             Nradii[rad] = Nradgood
    12728             finalcouples = np.zeros((Nradgood,2), dtype=int)
    12729             for ic in range(Nradgood):
    12730                 finalcouples[ic,:] = couples[ic]
    12731             gridradii[rad] = finalcouples
    12732 
    12733 #    for rad in sorted(gridradii.keys()):
    12734 #        print rad, gridradii[rad]
    12735 
    12736     return gridradii
    12737 
    12738 def grid_combinations(x,y):
    12739     """ Function to provide all the possible grid points combination for a given pair of values
    12740       x,y= pair of grid points
    12741     >>>grid_combinations(1,2)
    12742     [[1, 2], [-1, 2], [-1, -2], [1, -2], [2, 1], [-2, 1], [-2, -1], [2, -1]]
    12743     """
    12744     fname = 'grid_combinations'
    12745 
    12746     gridcomb = []
    12747     gridcomb.append([x,y])
    12748     if x != 0: gridcomb.append([-x,y])
    12749     if x != 0 and y != 0: gridcomb.append([-x,-y])
    12750     if y != 0: gridcomb.append([x,-y])
    12751 
    12752     if x != y:
    12753         gridcomb.append([y,x])
    12754         if y != 0: gridcomb.append([-y,x])
    12755         if x != 0 and y != 0: gridcomb.append([-y,-x])
    12756         if x != 0: gridcomb.append([y,-x])
    12757 
    12758     return gridcomb
    12759 
    12760 def radii_points(xpos,ypos,Lrad,Nang,dx,dy):
    12761     """ Function to provide the grid points for radial cross sections, by angle and radii and `squared' radii
    12762       xpos= x position of the center
    12763       ypos= y position of the center
    12764       Lrad= length of the maximum radi in grid points
    12765       Nang= number of equivalent angles
    12766       dx= x size of the domain of values
    12767       dy= y size of the domain of values
    12768       >>> radpos, SQradpos = radii_points(12,12,1,8,25,25)
    12769       radpos:
    12770       [[[ 13.          12.        ]]
    12771        [[ 12.70710678  12.70710678]]
    12772        [[ 12.          13.        ]]
    12773        [[ 11.29289322  12.70710678]]
    12774        [[ 11.          12.        ]]
    12775        [[ 11.29289322  11.29289322]]
    12776        [[ 12.          11.        ]]
    12777        [[ 12.70710678  11.29289322]]]
    12778       SQradpos:
    12779       {1.0: [[13, 12], [11, 12], [12, 13], [12, 11]], 1.41421356237: [[13, 13], [11, 13], [11, 11], [13, 11]]}
    12780     """
    12781     fname = 'radii_points'
    12782 
    12783     radiipos = np.zeros((Nang, Lrad, 2), dtype = np.float)
    12784     SQradiipos = {}
    12785 
    12786 # Getting the range of radii:
    12787     pairsSQradii = read_SQradii(Npt=Lrad)
    12788     SQradii = pairsSQradii.keys()
    12789     Nradii = len(SQradii)
    12790 
    12791 # Angle loop
    12792     for ia in range(Nang):
    12793         angle = 2.*np.pi*ia/Nang
    12794         posangle = np.zeros((Lrad,2), dtype=np.float)
    12795 
    12796 # Points at that given angle
    12797         pangle = radial_points(angle,Lrad)
    12798         posangle[:,0] = pangle[:,0] + xpos
    12799         posangle[:,1] = pangle[:,1] + ypos
    12800 
    12801         for ip in range(Lrad):
    12802             iipos = int(posangle[ip,0])
    12803             jjpos = int(posangle[ip,1])
    12804 
    12805 # Creation of a matrix with all the grid points at each time-step
    12806             if iipos >= 0 and iipos < dx-1 and jjpos >= 0 and jjpos < dy-1:
    12807                 radiipos[ia,ip,0] = posangle[ip,0]
    12808                 radiipos[ia,ip,1] = posangle[ip,1]
    12809 
    12810 # SQ radii values
    12811 
    12812 # Radii loop (avoiding 0)
    12813     pairswithin = {}
    12814     for ir in range(1,Nradii):
    12815         pairs = pairsSQradii[SQradii[ir]]
    12816 
    12817 # pairs loop
    12818         Npairs = len(pairs.flatten())/2
    12819         pairsw = []
    12820         for ip in range(Npairs):
    12821             if Npairs == 0:
    12822                 break
    12823             else:
    12824                 allpairs = grid_combinations(pairs[ip,0],pairs[ip,1])               
    12825             for iap in range(len(allpairs)):
    12826                 ppos = allpairs[iap]
    12827                 iipos = xpos + ppos[0]
    12828                 jjpos = ypos + ppos[1]
    12829 
    12830 # Creation of a matrix with all the grid points at each time-step
    12831                 if iipos >= 0 and iipos < dx and jjpos >= 0 and jjpos < dy:
    12832                     pairsw.append([iipos,jjpos])
    12833 
    12834         SQradiipos[SQradii[ir]] = pairsw
    12835 
    12836     return radiipos, SQradiipos
    12837 
    12838 def hor_weight_int(SWval, SEval, NWval, NEval, xpos, ypos):
    12839     """ Function to weighted by distance interpolate a horizontal value from it closest 4 neighbourgs
    12840       field= a 4 points representing the environment of a given point
    12841       xpos, ypos: position to which one want to interpolate (relative to 0,0 at the corner SW)
    12842     >>> hor_weight_int(1., 1., 1., 2., 0.75, 0.75)
    12843     1.44888128193
    12844     """
    12845     fname = 'hor_weight_int'
    12846 
    12847     vals = np.array([SWval, SEval, NWval, NEval])
    12848     print vals
    12849     if xpos > 1.:
    12850         print errormsg
    12851         print '  ' + fname + ': Wrong position to interpolate! (',xpos,',',ypos,     \
    12852           ') must be within (1,1) !!'
    12853         quit(-1)
    12854 
    12855     vertexs = np.zeros((4,2), dtype=np.float)
    12856     vertexs[0,0] = 0.
    12857     vertexs[0,1] = 0.
    12858     vertexs[1,0] = 1.
    12859     vertexs[1,1] = 0.
    12860     vertexs[2,0] = 0.
    12861     vertexs[2,1] = 1.
    12862     vertexs[3,0] = 1.
    12863     vertexs[3,1] = 1.
    12864     print vertexs
    12865 
    12866     dist = np.sqrt((vertexs[:,0]-xpos)**2 + (vertexs[:,1]-ypos)**2)
    12867     print dist
    12868     done = False
    12869     for id in range(4):
    12870         if dist[id] == 0.:
    12871             intval = vals[id]
    12872             done = True
    12873 
    12874     if not done: intval = np.sum(vals/dist)/np.sum(1./dist)
    12875 
    12876     return intval
    12877 
    1287810407def compute_tevolboxtraj_radialsec(values, ncfile, varn):
    1287910408    """ Function to compute tevolboxtraj_radialsec: temporal evolution at a given point along
     
    1371211241#  '/bdd/PCER/workspace/lfita/etudes/FF/medic051215_2km/run/wrfout/wrfout_d02_2005-12-13_00:00:00', 'QVAPOR')
    1371311242#quit()
    13714 
    1371511243
    1371611244def DatesFiles(values, ncfile, varn):
     
    1404711575#fileobj = NetCDFFile('/home/lluis/PY/ERAI_pl199501_130-133.nc', 'r')
    1404811576#TimeSplitmat(fileobj, 'time', 'time', 'all', 'd,H')
    14049 
    14050 def rmNOnum(string):
    14051     """ Removing from a string all that characters which are not numbers
    14052     # From: http://stackoverflow.com/questions/4289331/python-extract-numbers-from-a-string
    14053     """
    14054     fname = 'rmNOnum'
    14055 
    14056     newstr = str(re.findall("[-+]?\d+[\.]?\d*", string)[0])
    14057 
    14058     return newstr
    14059 
    14060 def values_fortran_fmt(lin,fFMT):
    14061     """ Function to give back the values of an ASCII line according to its fortran printing format
    14062       lin= ASCII line
    14063       fFMT= list with the fortran FORMAT formats
    14064     forline = 'Natchitoches (RGNL)        1 11 0011  ( 31.733, -93.100) (  28, 157) ( 31.761, -93.113)   41.2 meters'
    14065     formats = ['A26', 'I2', 'I3', 'A6', 'A2', 'F7.3', 'A1', 'F8.3', 'A3', 'I4', 'A1', 'I4',
    14066       'A3', 'F7.3', 'A1', 'F8.3', 'A2', 'F6.1', 'A7']
    14067     >>> values_fortran_fmt(forline, formats)
    14068     ['Natchitoches (RGNL)        ', 1, 11, ' 0011  ', ' ( ', 31.733, ', ', -93.1, ') ( ', 28, ', ', 157, ')
    14069       ( ', 31.761, ', ', -93.113, ')  ', 41.2, ' meters']
    14070     """
    14071     fname = 'values_fortran_fmt'
    14072 
    14073     afmts = ['A', 'D', 'F', 'I']
    14074 
    14075     if lin == 'h':
    14076         print fname + '_____________________________________________________________'
    14077         print values_fortran_fmt.__doc__
    14078         quit()
    14079 
    14080     fvalues = []
    14081     ichar=0
    14082     ival = 0
    14083     for ft in fFMT:
    14084         Lft = len(ft)
    14085         if ft[0:1] == 'A' or ft[0:1] == 'a':
    14086             Lfmt = int(ft[1:Lft+1])
    14087             fvalues.append(lin[ichar:ichar+Lfmt+1])
    14088             ichar = ichar + Lfmt
    14089         elif ft[0:1] == 'F' or ft[0:1] == 'f':
    14090             if ft.find('.') != -1:
    14091                 Lft = len(ft.split('.')[0])
    14092             Lfmt = int(ft[1:Lft])
    14093             fvalues.append(np.float(rmNOnum(lin[ichar:ichar+Lfmt+1])))
    14094             ichar = ichar + Lfmt
    14095         elif ft[0:1] == 'D' or ft[0:1] == 'd':
    14096             if ft.find('.') != -1:
    14097                 Lft = len(ft.split('.')[0])
    14098             Lfmt = int(ft[1:Lft])
    14099             fvalues.append(np.float64(rmNOnum(lin[ichar:ichar+Lfmt+1])))
    14100             ichar = ichar + Lfmt
    14101         elif ft[0:1] == 'I' or ft[0:1] == 'i':
    14102             Lfmt = int(ft[1:Lft+1])
    14103             fvalues.append(int(rmNOnum(lin[ichar:ichar+Lfmt+1])))
    14104             ichar = ichar + Lfmt
    14105         elif ft.find('X') != -1 or ft.find('x') != -1:
    14106             print '    ' + fname + ': skipping space'
    14107             ichar = ichar + int(rmNOnum(ft))
    14108         else:
    14109             print errormsg
    14110             print '  ' + fname + ": format '" + ft[0:1] + "' not ready!!"
    14111             print '    Available formats:',afmts
    14112             quit(-1)
    14113 
    14114         ival = ival + 1
    14115 
    14116     return fvalues
    14117 
    14118 def reduce_last_spaces(string):
    14119     """ Function to reduce the last right spaces from a string
    14120       string= string to remove the spaces at the righ side of the string
    14121     >>> reduce_last_spaces('Hola Lluis      ')
    14122     'Hola Lluis'
    14123     """
    14124     fname = 'reduce_last_spaces'
    14125 
    14126     Lstring = len(string)
    14127 
    14128     firstspace = -1
    14129     for istr in range(Lstring-1,0,-1):
    14130         if string[istr:istr+1] == ' ':
    14131             firstspace = istr
    14132         else:
    14133             break
    14134 
    14135     if firstspace == -1:
    14136         print errormsg
    14137         print '  ' + fname + ": string '" + string + "' is not ended by spaces!!"
    14138         print '    char. number of last character:',ord(string[Lstring:Lstring+1])
    14139         quit(-1)
    14140 
    14141     newstr = string[0:firstspace]
    14142 
    14143     return newstr
    14144 
    14145 def squared_radial(Npt):
    14146     """ Function to provide the series of radii as composite of pairs (x,y) of gid cells
    14147       Npt= largest amount of grid points on x and y directions
    14148     >>> squared_radial(5)
    14149     [[0.0, 0, 0], [1.0, 1, 0], [1.4142135623730951, 1, 1], [2.0, 2, 0], [2.2360679774997898, 2, 1], [2.8284271247461903, 2, 2], [3.0, 3, 0], [3.1622776601683795, 3, 1], [3.6055512754639891, 3, 2], [4.0, 4, 0], [4.1231056256176606, 4, 1], [4.2426406871192848, 3, 3], [4.4721359549995796, 4, 2], [5.0, array([4, 3]), array([5, 0])], [5.0990195135927845, 5, 1], [5.3851648071345037, 5, 2], [5.6568542494923806, 4, 4], [5.8309518948453007, 5, 3], [6.4031242374328485, 5, 4], [7.0710678118654755, 5, 5]]
    14150     """
    14151     fname = 'squared_radial'
    14152 
    14153     radii = []
    14154     gridradii = {}
    14155     singradii = []
    14156     Nradii = {}
    14157 
    14158 # Computing all radii
    14159 ##
    14160     for i in range(Npt+1):
    14161         if np.mod(i,100) == 0: print 'done: ',i
    14162         for j in range(i+1):
    14163 #            ir = np.float(i)
    14164 #            jr = np.float(j)
    14165             ir = np.float64(i)
    14166             jr = np.float64(j)
    14167             rad = np.sqrt(ir*ir + jr*jr)
    14168             if not searchInlist(singradii, rad):
    14169                 singradii.append(rad)
    14170                 gridradii[rad] = np.array([i,j], dtype=int)
    14171                 Nradii[rad] = 1
    14172             else:
    14173 #                print warnmsg
    14174 #                print '  ' + fname + ': repeated radii',rad,'!!'
    14175 #                print '    Previous values:', gridradii[rad]
    14176 
    14177                 oldvalues = gridradii[rad]
    14178                 Nradii[rad] = Nradii[rad] + 1
    14179                 newvalues = np.zeros((Nradii[rad],2), dtype=int)
    14180                 if Nradii[rad] == 2:
    14181                     newvalues[0,:] = oldvalues
    14182                     Nstart = 1
    14183                 else:
    14184                     Nstart = 0
    14185                 for Nr in range(Nstart,Nradii[rad]-1):
    14186                     newvalues[Nr,:] = oldvalues[Nr,:]
    14187                 newvalues[Nradii[rad]-1,:] = np.array([i,j], dtype=int)
    14188                 gridradii[rad] = newvalues
    14189 
    14190 # Sorting values
    14191 ##
    14192 ## Only required to downwrite the output file
    14193 #    radiif = open('SQradii.dat', 'w')
    14194 #    radii = []
    14195 #    prevrad = 0.
    14196 #    for rad in sorted(gridradii.keys()):
    14197 #        dradii = rad - prevrad
    14198 ## Check fo repeated values
    14199 #        radii.append([rad, gridradii[rad][0], gridradii[rad][1]])
    14200 #        radiif.write(str(rad) + ' ' + str(dradii) + ' ' + str(Nradii[rad]) + ' [ '+  \
    14201 #          numVector_String(gridradii[rad].flatten(), ' ') + ' ] \n')
    14202 #        prevrad = rad.copy()
    14203 
    14204 #    radiif.close()
    14205     return gridradii
    1420611577
    1420711578def getvalues_lonlat(values, ncfile):
     
    1505712428#SpatialWeightedMean('reglonlat,XLONG,XLAT,west_east,south_north','wrfout_d01_2001-11-11_00:00:00','HGT')
    1505812429
    15059 def fillvalue_kind(vartype, fillval0):
    15060     """ Function to provide the fiven fill_Value for a kind of variable
    15061       [vartype]= type of the variable
    15062       [fillval0]= value to take as fill value, 'std' for the standard value
    15063            Float = 1.e20
    15064            Character = '-'
    15065            Integer = -99999
    15066            Integer16 = -99999
    15067            Float64 = 1.e20
    15068            Integer32 = -99999
    15069     """
    15070     fname = 'fillvalue_kind'
    15071 
    15072     if vartype == type('c'):
    15073         if fillval0 == 'std':
    15074             fillval = fillvalueC
    15075         else:
    15076             fillval = fillval0
    15077     elif vartype == type(int(1)):
    15078         if fillval0 == 'std':
    15079             fillval = fillValueI
    15080         else:
    15081             fillval = int(fillval0)
    15082     elif vartype == type(np.int16(1)):
    15083         if fillval0 == 'std':
    15084             fillval = np.int(9999999)
    15085         else:
    15086             fillval = np.int16(fillval0)
    15087     elif vartype == type(np.int32(1)):
    15088         if fillval0 == 'std':
    15089             fillval = np.int32(fillValueI)
    15090         else:
    15091             fillval = np.int32(fillval0)
    15092     elif vartype == type(np.float(1.)):
    15093         if fillval0 == 'std':
    15094             fillval = np.float(fillValueF)
    15095         else:
    15096             fillval = np.float(fillval0)
    15097     elif vartype == type(np.float32(1.)):
    15098         if fillval0 == 'std':
    15099             fillval = np.float32(fillValueF)
    15100         else:
    15101             fillval = np.float32(fillval0)
    15102     elif vartype == type(np.float64(1.)):
    15103         if fillval0 == 'std':
    15104             fillval = np.float64(fillValueF)
    15105         else:
    15106             fillval = np.float64(fillval0)
    15107     else:
    15108         print errormsg
    15109         print '  ' + fname + ': variable type', vartype, 'not ready !!'
    15110         quit(-1)
    15111 
    15112     return fillval
    15113 
    1511412430def nctype(vartype):
    1511512431    """ Function to provide the string for the variable creation in a netCDF file
     
    1514112457    return ncs
    1514212458
    15143 def varval_ind(var, ind):
    15144     """ Function to provide a value from a variable providing a value for each index
    15145       var= variable
    15146       ind= list of indices for each dimension of the variable
    15147     """
    15148     fname = 'varval_ind'
    15149     if len(var.shape) != len(ind):
    15150         print errormsg
    15151         print '  ' + fname + ': different shape:', var.shape,'and indices:', ind, '!!'
    15152         quit(-1)
    15153 
    15154     varslice=[]
    15155     for iv in ind:
    15156         varslice.append(iv)
    15157 
    15158     val = varval_ind[slice(varslice)]
    15159 
    15160     return val
    15161 
    1516212459def VarVal_FillValue(values, filen, varn):
    1516312460    """ Function to transform a given value from a given variable to _FillValue in a netCDF file
     
    1540212699#lonlatProj(100000.,100000.,'lonlat',True)
    1540312700#quit()
    15404 
    15405 def CoarselonlatFind(ilon, ilat, lonv, latv, per):
    15406     """ Function to search a given value from a coarser version of the data
    15407       ilon, ilat= original 2D matrices with the longitudes and the latitudes
    15408       lonv, latv= longitude and latitude to find
    15409       per= period (as fraction over 1) of the fractions of the original grid to use to explore
    15410       >>> npt=100
    15411       >>> lonval0 = np.arange(0.,npt*1.,1.)
    15412       >>> latval0 = np.arange(0.,npt*1.,1.)
    15413       >>> lonval = np.zeros((npt,npt), dtype=np.float)
    15414       >>> latval = np.zeros((npt,npt), dtype=np.float)
    15415 
    15416       >>> for i in range(npt):
    15417       >>>     lonval[:,i] = lonval0[i]
    15418       >>>     latval[i,:] = latval0[i]
    15419       >>> CoarselonlatFind(lonval, latval, 5.25, 5.25, .1)
    15420       (array([5, 5]), 0.35355339059327379)
    15421     """
    15422     fname = 'CoarselonlatFind'
    15423 
    15424     dx = ilon.shape[1]
    15425     dy = ilon.shape[0]
    15426 
    15427     nlon = np.min(ilon)
    15428     xlon = np.max(ilon)
    15429     nlat = np.min(ilat)
    15430     xlat = np.max(ilat)
    15431 
    15432     if lonv < nlon or lonv > xlon:
    15433         print errormsg
    15434         print '  ' + fname + ': longitude outside data range!!'
    15435         print '    given value:', lonv,'outside [',nlon,',',xlon,']'
    15436         quit(-1)
    15437     if latv < nlat or latv > xlat:
    15438         print errormsg
    15439         print '  ' + fname + ': latitude outside data range!!'
    15440         print '    given value:', latv,'outside [',nlat,',',xlat,']'
    15441         quit(-1)
    15442 
    15443     fracx = int(dx*per)
    15444     fracy = int(dy*per)
    15445 
    15446     fraclon = ilon[::fracy,::fracx]
    15447     fraclat = ilat[::fracy,::fracx]
    15448     fracdx = fraclon.shape[1]
    15449     fracdy = fraclon.shape[0]
    15450 
    15451 #    print 'fraclon _______'
    15452 #    print fraclon
    15453 
    15454 #    print 'fraclat _______'
    15455 #    print fraclat
    15456 
    15457 # Fraction point
    15458     difffraclonlat = np.sqrt((fraclon-lonv)**2. + (fraclat-latv)**2.)
    15459     mindifffracLl = np.min(difffraclonlat)
    15460     ilatlonfrac = index_mat(difffraclonlat, mindifffracLl)
    15461 
    15462 #    print 'mindifffracLl:', mindifffracLl, 'ilatlonfrac:', ilatlonfrac
    15463 #    print 'frac lon, lat:', fraclon[ilatlonfrac[0],ilatlonfrac[1]], ',',             \
    15464 #      fraclat[ilatlonfrac[0],ilatlonfrac[1]]
    15465 #    print 'values lon, lat:', lonv, latv
    15466      
    15467 # Providing fraction range
    15468     if fraclon[ilatlonfrac[0],ilatlonfrac[1]] >= lonv and                            \
    15469       fraclat[ilatlonfrac[0],ilatlonfrac[1]] >= latv:
    15470 #        ifracbeg = [ilatlonfrac[0]-1, ilatlonfrac[1]-1]
    15471 #        ifracend = [ilatlonfrac[0], ilatlonfrac[1]]
    15472         if ilatlonfrac[0] > 0:
    15473             iybeg = (ilatlonfrac[0]-1)*fracy
    15474             iyend = ilatlonfrac[0]*fracy+1
    15475         else:
    15476             iybeg = 0
    15477             iyend = fracy+1
    15478         if ilatlonfrac[1] > 0:
    15479             ixbeg = (ilatlonfrac[1]-1)*fracx
    15480             ixend = ilatlonfrac[1]*fracx+1
    15481         else:
    15482             ixbeg = 0
    15483             ixend = fracx+1
    15484     elif fraclon[ilatlonfrac[0],ilatlonfrac[1]] < lonv and                           \
    15485       fraclat[ilatlonfrac[0],ilatlonfrac[1]] >= latv:
    15486 #        ifracbeg = [ilatlonfrac[0]-1, ilatlonfrac[1]]
    15487 #        ifracend = [ilatlonfrac[0], ilatlonfrac[1]+1]
    15488         if ilatlonfrac[0] > 0:
    15489             iybeg = (ilatlonfrac[0]-1)*fracy
    15490             iyend = ilatlonfrac[0]*fracy+1
    15491         else:
    15492             iybeg = 0
    15493             iyend = fracy+1
    15494         if ilatlonfrac[1] < fracdx:
    15495             if ilatlonfrac[1] != 0:
    15496                 ixbeg = (ilatlonfrac[1]-1)*fracx
    15497                 ixend = ilatlonfrac[1]*fracx+1
    15498             else:
    15499                 ixbeg = 0
    15500                 ixend = fracx+1
    15501         else:
    15502             ixbeg = fracdx*fracx
    15503             ixend = dx+1
    15504     elif fraclon[ilatlonfrac[0],ilatlonfrac[1]] < lonv and                           \
    15505       fraclat[ilatlonfrac[0],ilatlonfrac[1]] < latv:
    15506 #        ifracbeg = [ilatlonfrac[0], ilatlonfrac[1]]
    15507 #        ifracend = [ilatlonfrac[0]+1, ilatlonfrac[1]+1]
    15508         if ilatlonfrac[0] < fracdy:
    15509             if ilatlonfrac[0] != 0:
    15510                 iybeg = (ilatlonfrac[0]-1)*fracy
    15511                 iyend = ilatlonfrac[0]*fracy+1
    15512             else:
    15513                 iybeg = 0
    15514                 iyend = fracy+1
    15515         else:
    15516             iybeg = fracdy*fracy
    15517             iyend = dy+1
    15518         if ilatlonfrac[1] < fracdx:
    15519             if ilatlonfrac[1] != 0:
    15520                 ixbeg = (ilatlonfrac[1]-1)*fracx
    15521                 ixend = ilatlonfrac[1]*fracx+1
    15522             else:
    15523                 ixbeg = 0
    15524                 ixend = fracx+1
    15525         else:
    15526             ixbeg = fracdx*fracx
    15527             ixend = dx+1
    15528     elif fraclon[ilatlonfrac[0],ilatlonfrac[1]] >= lonv and                          \
    15529       fraclat[ilatlonfrac[0],ilatlonfrac[1]] < latv:
    15530 #        ifracbeg = [ilatlonfrac[0], ilatlonfrac[1]-1]
    15531 #        ifracend = [ilatlonfrac[0]+1, ilatlonfrac[1]]
    15532         if ilatlonfrac[0] < fracdy:
    15533             if ilatlonfrac[0] != 0:
    15534                 iybeg = (ilatlonfrac[0]-1)*fracy
    15535                 iyend = ilatlonfrac[0]*fracy+1
    15536             else:
    15537                 iybeg = 0
    15538                 iyend = fracy+1
    15539         else:
    15540             iybeg = fracdy*fracy
    15541             iyend = dy+1
    15542         if ilatlonfrac[1] > 0:
    15543             ixbeg = (ilatlonfrac[1]-1)*fracx
    15544             ixend = ilatlonfrac[1]*fracx+1
    15545         else:
    15546             ixbeg = 0
    15547             ixend = fracx+1
    15548 
    15549 #    ibeg = [iybeg, ixbeg]
    15550 #    iend = [iyend, ixend]
    15551 #    print 'find window; beginning', ibeg, 'end:', iend
    15552     lon = ilon[iybeg:iyend,ixbeg:ixend]
    15553     lat = ilat[iybeg:iyend,ixbeg:ixend]
    15554 
    15555 #    print 'lon _______'
    15556 #    print lon
    15557 #    print 'lat _______'
    15558 #    print lat
    15559 
    15560 # Find point
    15561     difflonlat = np.sqrt((lon-lonv)**2. + (lat-latv)**2.)
    15562     mindiffLl = np.min(difflonlat)
    15563     ilatlon = index_mat(difflonlat, mindiffLl)
    15564 
    15565     ilatlon[0] = ilatlon[0] + iybeg
    15566     ilatlon[1] = ilatlon[1] + ixbeg
    15567 
    15568 #    print 'mindiffLl:', mindiffLl, 'ilatlon:', ilatlon
    15569 #    print 'lon, lat:', lon[ilatlon[0],ilatlon[1]], ',', lat[ilatlon[0],ilatlon[1]]
    15570 #    quit()
    15571 
    15572     return ilatlon, mindiffLl
    15573 
    15574 def CoarselonlatFindAll(onc, ilon, ilat, longvs, latvs, per, frac, out):
    15575     """ Function to search all values from a coarser version of the data
    15576       onc= netCDF object from an existing file
    15577       ilon, ilat= original 2D matrices with the longitudes and the latitudes
    15578       lonv, latv= longitude and latitude to find
    15579       per= period (as fraction over 1) of the fractions of the original grid to use to explore
    15580       frac= frequency of points at which syncronize file with calculations
    15581       out= True/False if outcome is required
    15582       >>> npt=100
    15583       >>> lonval0 = np.arange(0.,npt*1.,1.)
    15584       >>> latval0 = np.arange(0.,npt*1.,1.)
    15585       >>> lonval = np.zeros((npt,npt), dtype=np.float)
    15586       >>> latval = np.zeros((npt,npt), dtype=np.float)
    15587       >>> lonvalues = np.arange(0.25,10.,0.25)
    15588       >>> latvalues = np.arange(0.25,10.,0.25)
    15589 
    15590       >>> for i in range(npt):
    15591       >>>     lonval[:,i] = lonval0[i]
    15592       >>>     latval[i,:] = latval0[i]
    15593       >>> CoarselonlatFindAll(onewnc, lonval, latval, lovalues, latvalues, .1, 100)
    15594       (array([5, 5]), 0.35355339059327379)
    15595     """
    15596     fname = 'CoarselonlatFindAll'
    15597 
    15598     dx = ilon.shape[1]
    15599     dy = ilon.shape[0]
    15600 
    15601     nlon = np.min(ilon)
    15602     xlon = np.max(ilon)
    15603     nlat = np.min(ilat)
    15604     xlat = np.max(ilat)
    15605 
    15606     Nallpts = len(longvs)
    15607 
    15608     fracx = int(dx*per)
    15609     fracy = int(dy*per)
    15610 
    15611     fraclon = ilon[::fracy,::fracx]
    15612     fraclat = ilat[::fracy,::fracx]
    15613     fracdx = fraclon.shape[1]
    15614     fracdy = fraclon.shape[0]
    15615 
    15616 #    print 'fraclon _______'
    15617 #    print fraclon
    15618 
    15619 #    print 'fraclat _______'
    15620 #    print fraclat
    15621 
    15622     if out:
    15623         ilatlon = np.zeros((2,Nallpts), dtype=int)
    15624         mindiffLl = np.zeros((Nallpts), dtype=np.float)
    15625 
    15626     iptpos=0
    15627     for iv in range(Nallpts):
    15628         lonv = longvs[iv]
    15629         latv = latvs[iv]
    15630 
    15631         if lonv < nlon or lonv > xlon:
    15632             print errormsg
    15633             print '  ' + fname + ': longitude outside data range!!'
    15634             print '    given value:', lonv,'outside [',nlon,',',xlon,']'
    15635             quit(-1)
    15636         if latv < nlat or latv > xlat:
    15637             print errormsg
    15638             print '  ' + fname + ': latitude outside data range!!'
    15639             print '    given value:', latv,'outside [',nlat,',',xlat,']'
    15640             quit(-1)
    15641 
    15642 # Fraction point
    15643         difffraclonlat = np.sqrt((fraclon-lonv)**2. + (fraclat-latv)**2.)
    15644         mindifffracLl = np.min(difffraclonlat)
    15645         ilatlonfrac = index_mat(difffraclonlat, mindifffracLl)
    15646 
    15647 #        print 'values lon, lat:', lonv, latv
    15648 #        print 'mindifffracLl:', mindifffracLl, 'ilatlonfrac:', ilatlonfrac
    15649 #        print 'frac lon, lat:', fraclon[ilatlonfrac[0],ilatlonfrac[1]], ',',         \
    15650 #          fraclat[ilatlonfrac[0],ilatlonfrac[1]]
    15651      
    15652 # Providing fraction range
    15653         if fraclon[ilatlonfrac[0],ilatlonfrac[1]] >= lonv and                        \
    15654           fraclat[ilatlonfrac[0],ilatlonfrac[1]] >= latv:
    15655 #            ifracbeg = [ilatlonfrac[0]-1, ilatlonfrac[1]-1]
    15656 #            ifracend = [ilatlonfrac[0], ilatlonfrac[1]]
    15657             if ilatlonfrac[0] > 0:
    15658                 iybeg = (ilatlonfrac[0]-1)*fracy
    15659                 iyend = ilatlonfrac[0]*fracy+1
    15660             else:
    15661                 iybeg = 0
    15662                 iyend = fracy+1
    15663             if ilatlonfrac[1] > 0:
    15664                 ixbeg = (ilatlonfrac[1]-1)*fracx
    15665                 ixend = ilatlonfrac[1]*fracx+1
    15666             else:
    15667                 ixbeg = 0
    15668                 ixend = fracx+1
    15669         elif fraclon[ilatlonfrac[0],ilatlonfrac[1]] < lonv and                       \
    15670           fraclat[ilatlonfrac[0],ilatlonfrac[1]] >= latv:
    15671 #            ifracbeg = [ilatlonfrac[0]-1, ilatlonfrac[1]]
    15672 #            ifracend = [ilatlonfrac[0], ilatlonfrac[1]+1]
    15673             if ilatlonfrac[0] > 0:
    15674                 iybeg = (ilatlonfrac[0]-1)*fracy
    15675                 iyend = ilatlonfrac[0]*fracy+1
    15676             else:
    15677                 iybeg = 0
    15678                 iyend = fracy+1
    15679             if ilatlonfrac[1] < fracdx:
    15680                 if ilatlonfrac[1] != 0:
    15681                     ixbeg = (ilatlonfrac[1]-1)*fracx
    15682                     ixend = ilatlonfrac[1]*fracx+1
    15683                 else:
    15684                     ixbeg = 0
    15685                     ixend = fracx+1
    15686             else:
    15687                 ixbeg = fracdx*fracx
    15688                 ixend = dx+1
    15689         elif fraclon[ilatlonfrac[0],ilatlonfrac[1]] < lonv and                       \
    15690           fraclat[ilatlonfrac[0],ilatlonfrac[1]] < latv:
    15691 #            ifracbeg = [ilatlonfrac[0], ilatlonfrac[1]]
    15692 #            ifracend = [ilatlonfrac[0]+1, ilatlonfrac[1]+1]
    15693             if ilatlonfrac[0] < fracdy:
    15694                 if ilatlonfrac[0] != 0:
    15695                     iybeg = (ilatlonfrac[0]-1)*fracy
    15696                     iyend = ilatlonfrac[0]*fracy+1
    15697                 else:
    15698                     iybeg = 0
    15699                     iyend = fracy+1
    15700             else:
    15701                 iybeg = fracdy*fracy
    15702                 iyend = dy+1
    15703             if ilatlonfrac[1] < fracdx:
    15704                 if ilatlonfrac[1] != 0:
    15705                     ixbeg = (ilatlonfrac[1]-1)*fracx
    15706                     ixend = ilatlonfrac[1]*fracx+1
    15707                 else:
    15708                     ixbeg = 0
    15709                     ixend = fracx+1
    15710             else:
    15711                 ixbeg = fracdx*fracx
    15712                 ixend = dx+1
    15713         elif fraclon[ilatlonfrac[0],ilatlonfrac[1]] >= lonv and                      \
    15714           fraclat[ilatlonfrac[0],ilatlonfrac[1]] < latv:
    15715 #            ifracbeg = [ilatlonfrac[0], ilatlonfrac[1]-1]
    15716 #            ifracend = [ilatlonfrac[0]+1, ilatlonfrac[1]]
    15717             if ilatlonfrac[0] < fracdy:
    15718                 if ilatlonfrac[0] != 0:
    15719                     iybeg = (ilatlonfrac[0]-1)*fracy
    15720                     iyend = ilatlonfrac[0]*fracy+1
    15721                 else:
    15722                     iybeg = 0
    15723                     iyend = fracy+1
    15724             else:
    15725                 iybeg = fracdy*fracy
    15726                 iyend = dy+1
    15727             if ilatlonfrac[1] > 0:
    15728                 ixbeg = (ilatlonfrac[1]-1)*fracx
    15729                 ixend = ilatlonfrac[1]*fracx+1
    15730             else:
    15731                 ixbeg = 0
    15732                 ixend = fracx+1
    15733    
    15734 #        ibeg = [iybeg, ixbeg]
    15735 #        iend = [iyend, ixend]
    15736 #        print 'find window; beginning', ibeg, 'end:', iend
    15737         lon = ilon[iybeg:iyend,ixbeg:ixend]
    15738         lat = ilat[iybeg:iyend,ixbeg:ixend]
    15739 #        print 'Looking within _______'
    15740 #        print 'lon:',lon[0,0],',',lon[-1,-1]
    15741 #        print 'lat:',lat[0,0],',',lat[-1,-1]
    15742    
    15743 #        print 'lon _______'
    15744 #        print lon
    15745 #        print 'lat _______'
    15746 #        print lat
    15747    
    15748 # Find point
    15749         difflonlat = np.sqrt((lon-lonv)**2. + (lat-latv)**2.)
    15750         if out:
    15751             mindiffLl[iv] = np.min(difflonlat)
    15752             ilatlon[:,iv] = index_mat(difflonlat, mindiffLl)
    15753             ilatlon[0,iv] = ilatlon[0,iv] + iybeg
    15754             ilatlon[1,iv] = ilatlon[1,iv] + ixbeg
    15755         else:
    15756             mindiffLl = np.min(difflonlat)
    15757             ilatlon = index_mat(difflonlat, mindiffLl)
    15758             ilatlon[0] = ilatlon[0] + iybeg
    15759             ilatlon[1] = ilatlon[1] + ixbeg
    15760 
    15761 #        print 'mindiffLl:', mindiffLl, 'ilatlon:', ilatlon
    15762 #        print 'lon, lat:', lon[ilatlon[0],ilatlon[1]], ',', lat[ilatlon[0],ilatlon[1]]
    15763 #        quit()
    15764 
    15765 #        if mindiffLl == 0. and type(newvar[ilatlon[0],ilatlon[1]]) == type(amsk):
    15766 #            percendone(iv,Ninpts,0.5,'done:')
    15767         if mindiffLl == 0.:
    15768             iptpos = iptpos + 1
    15769 # Speeding it up!
    15770 #            if mindiffLl > mindiff:
    15771 #                print errormsg
    15772 #                print '  ' + fname + ': for point #', iv,'lon,lat in ' +             \
    15773 #                  'incomplet map:', lonvs[iv], ',', latvs[iv], 'there is ' +         \
    15774 #                  'not a set of lon,lat in the completed map closer than: ',         \
    15775 #                  mindiff, '!!'
    15776 #                print '    minimum difference:', mindiffLl
    15777 #                quit(-1)
    15778 
    15779 # Speeding it up!
    15780 #            if ilatlon[0] >= 0 and ilatlon[1] >= 0:
    15781 #                newvar[ilatlon[0],ilatlon[1]] = ovar[iv]
    15782 #                newvarin[ilatlon[0],ilatlon[1]] = iv
    15783 #                newvarinpt[iv] = 1
    15784 #                newvarindiff[iv] = mindiffLl
    15785             newvar[ilatlon[0],ilatlon[1]] = ovar[iv]
    15786             newvarin[ilatlon[0],ilatlon[1]] = iv
    15787             newvarinpt[iv] = 1
    15788             newvarindiff[iv] = mindiffLl
    15789 
    15790 #                print 'Lluis iv:', newvarin[ilatlon[0],ilatlon[1]],                  \
    15791 #                  'localized:', newvarinpt[iv], 'values:',                           \
    15792 #                  newvar[ilatlon[0],ilatlon[1]], 'invalues:', ovar[iv],              \
    15793 #                  'mindist:', newvarindiff[iv], 'point:',ilatlon   
    15794 #            else:
    15795 #                print errormsg
    15796 #                print '  ' + fname + ': point iv:', iv, 'at', lonvs[iv], ',',        \
    15797 #                  latvs[iv],' not relocated !!'
    15798 #                print '    mindiffl:', mindiffLl, 'ilon:', ilatlon[1],               \
    15799 #                  'ilatlon:', ilatlon[1]
    15800 #                quit(-1)
    15801             if np.mod(iptpos,fracs) == 0:
    15802                 print 'Lluis syncronizing!'
    15803                 onc.sync()
    15804     if out:
    15805         return ilatlon, mindiffLl
    15806     else:
    15807         return
    15808 
    15809 def lonlatFind(ilon, ilat, lonv, latv):
    15810     """ Function to search a given value from a lon, lat 2D data
    15811       ilon, ilat= original 2D matrices with the longitudes and the latitudes
    15812       lonv, latv= longitude and latitude to find
    15813       >>> npt=100
    15814       >>> lonval0 = np.arange(0.,npt*1.,1.)
    15815       >>> latval0 = np.arange(0.,npt*1.,1.)
    15816       >>> lonval = np.zeros((npt,npt), dtype=np.float)
    15817       >>> latval = np.zeros((npt,npt), dtype=np.float)
    15818 
    15819       >>> for i in range(npt):
    15820       >>>     lonval[:,i] = lonval0[i]
    15821       >>>     latval[i,:] = latval0[i]
    15822       >>> lonlatFind(lonval, latval, 5.25, 5.25)
    15823       (array([5, 5]), 0.35355339059327379)
    15824     """
    15825     fname = 'lonlatFind'
    15826 
    15827     dx = ilon.shape[1]
    15828     dy = ilon.shape[0]
    15829 
    15830     nlon = np.min(ilon)
    15831     xlon = np.max(ilon)
    15832     nlat = np.min(ilat)
    15833     xlat = np.max(ilat)
    15834 
    15835     if lonv < nlon or lonv > xlon:
    15836         print errormsg
    15837         print '  ' + fname + ': longitude outside data range!!'
    15838         print '    given value:', lonv,'outside [',nlon,',',xlon,']'
    15839         quit(-1)
    15840     if latv < nlat or latv > xlat:
    15841         print errormsg
    15842         print '  ' + fname + ': latitude outside data range!!'
    15843         print '    given value:', latv,'outside [',nlat,',',xlat,']'
    15844         quit(-1)
    15845 
    15846 # Find point
    15847     difflonlat = np.sqrt((ilon-lonv)**2. + (ilat-latv)**2.)
    15848     mindiffLl = np.min(difflonlat)
    15849     ilatlon = index_mat(difflonlat, mindiffLl)
    15850 
    15851 #    print 'mindiffLl:', mindiffLl, 'ilatlon:', ilatlon
    15852 #    print 'lon, lat:', lon[ilatlon[0],ilatlon[1]], ',', lat[ilatlon[0],ilatlon[1]]
    15853 
    15854     return ilatlon, mindiffLl
    1585512701
    1585612702def Partialmap_Entiremap(values, filen, varn):
Note: See TracChangeset for help on using the changeset viewer.