Changeset 747 in lmdz_wrf
- Timestamp:
- May 4, 2016, 11:19:50 AM (9 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/tools/nc_var_tools.py
r746 r747 601 601 ncf = NetCDFFile(ncfile,'a') 602 602 603 603 return 604 604 605 605 def chvarname(values, ncfile, varn): … … 1877 1877 self.dimx=self.dims[3] 1878 1878 1879 return1879 return 1880 1880 1881 1881 def subyrs(values, ncfile, varn): … … 3319 3319 return loadvar 3320 3320 3321 AQUI AQUI AQUI AQUI AQUI AQUI AQUI3322 3323 3324 3321 def fill_ncvariable_lastdims(ncf, varn, prevdims, Nlastdims, fillvals): 3325 3322 """ Function to fill the last [Nlastdims] dimensions of a variable [varn] from a netCDF object at the other dimensions at [prevdims] … … 3393 3390 quit(-1) 3394 3391 3392 return 3393 3395 3394 def maskvar(values, filename, varn): 3396 3395 """ Function to mask a variable using a mask. It is assumed that mask[...,dimM,dimJ,dimK] and … … 3540 3539 print 'masked file "' + ofile + '" generated !!!' 3541 3540 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 3613 3542 3614 3543 def chgtimestep(values, origfile, varN): … … 3691 3620 ncofile.close() 3692 3621 3622 return 3623 3693 3624 def uploading_timestep(ncfile, varN, time_step): 3694 3625 """ Function to upload a given time-step of a variable inside a netCDF … … 3847 3778 fileobj.close() 3848 3779 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 3922 3781 3923 3782 def addvals(values, filename, varN): … … 4098 3957 quit(-1) 4099 3958 3959 return 3960 4100 3961 def TimeInf(filename, tname): 4101 3962 """ Function to print all the information from the variable time … … 4108 3969 fmtprinting_class(timeinf) 4109 3970 ncfobj.close() 3971 3972 return 4110 3973 4111 3974 def sorttimesmat(filename, tname): … … 4151 4014 ncft.close() 4152 4015 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 4240 4017 4241 4018 def check_times_file(values, filename, timen): … … 4356 4133 print matdates[it,:] 4357 4134 4135 return 4136 4358 4137 def writing_str_nc(varo, values, Lchar): 4359 4138 """ Function to write string values in a netCDF variable as a chain of 1char values … … 4445 4224 4446 4225 return strings 4447 4448 class ysubsetstats(object):4449 """ Class to compute multi-year statistics of a given subset of values4450 values= values to use4451 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 period4454 valf=final value of the period4455 Nq= number of quantiles (20 for 5% bins, it is going to produce 21 values)4456 missval= missing value4457 self.Nvalues = Number of non masked values4458 self.min = minimum non masked value4459 self.max = maximum non masked value4460 self.mean = mean non masked value4461 self.mean2 = quandratic mean non masked value4462 self.stdev = standard deviation non masked value4463 self.quantiles = quantiles non masked value4464 """4465 def __init__(self, values, dates, sec, vali, valf, Nq, missVal):4466 import numpy.ma as ma4467 4468 fname = 'ysubsetstats'4469 4470 if values is None:4471 self.Nvalues = None4472 self.min = None4473 4474 self.max = None4475 self.mean = None4476 self.mean2 = None4477 self.stdev = None4478 self.quantiles = None4479 4480 else:4481 Nvalues = len(values)4482 Ndates = len(dates)4483 4484 if Nvalues != Ndates:4485 print errormsg4486 print fname + ': number of values ', Nvalues,' does not coincide with the number of dates ',Ndates, '!!!!!!'4487 print errormsg4488 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 = 04500 elif sec == 'month':4501 isec = 14502 elif sec == 'day':4503 isec = 24504 elif sec == 'hour':4505 isec = 34506 elif sec == 'minute':4507 isec = 44508 elif sec == 'second':4509 isec = 54510 else:4511 print errormsg4512 print fname + ': sction "' + sec + '" not ready!!!!'4513 print errormsg4514 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.mask4524 finalvalues = ma.array(values, mask=finalmask)4525 4526 finalvalues2 = finalvalues*finalvalues4527 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)4535 4226 4536 4227 def remapnn(values, filename, varname): … … 4786 4477 4787 4478 print 'remapnn: new file "' + ofile + '" with remapped variable written !!' 4479 4480 return 4788 4481 4789 4482 #remapnn('met_em.d01.1979-01-01_00:00:00.nc|XLONG_M,XLAT_M|east_weast,south_north|longitude,latitude|longitude,latitude', \ … … 4959 4652 4960 4653 print 'remapnn: new file "' + ofile + '" with remapped variable written !!' 4654 4655 return 4961 4656 #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.) 4962 4657 #quit() … … 5093 4788 ncobj.close() 5094 4789 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 4792 def 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') 5111 4807 """ 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) 5121 4882 5122 4883 zerodims=np.ones( (6), dtype=int) 5123 4884 Ndims = len(matshape) 4885 5124 4886 if Ndims > 6: 5125 4887 print errmsg … … 5129 4891 zerodims[5-Ndims+1:6] = matshape 5130 4892 5131 newdims = list(matshape)5132 newdims[Ndims-1-iddim] = matshape[iddim]-15133 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]] = mat5138 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,i55146 if iddim == 5 and dimval == i0:5147 mask[i0,i1,i2,i3,i4,i5] = False5148 elif iddim == 4 and dimval == i1:5149 mask[i0,i1,i2,i3,i4,i5] = False5150 elif iddim == 3 and dimval == i2:5151 mask[i0,i1,i2,i3,i4,i5] = False5152 elif iddim == 2 and dimval == i3:5153 mask[i0,i1,i2,i3,i4,i5] = False5154 elif iddim == 1 and dimval == i4:5155 mask[i0,i1,i2,i3,i4,i5] = False5156 elif iddim == 0 and dimval == i5:5157 mask[i0,i1,i2,i3,i4,i5] = False5158 5159 newmat = vals[mask].reshape(tuple(newdims))5160 # print 'newmat dim:',iddim,'val:',dimval,':',newdims,'______'5161 # print newmat5162 5163 return newmat5164 5165 def portion_fix1dim_values(mat,iddim,dimval):5166 """ Function to return that portion of the matrix values when one dimension has5167 been removed at a given value5168 mat = matrix5169 iddim = dimesion to remove (starting from 0 tacking the right most)5170 dimval = value of the dimension5171 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.squeeze5181 ## import numpy.ma as ma5182 ## print ma.squeeze(mat, axis = (idim,))5183 5184 matshape = mat.shape5185 mattype = mat.dtype5186 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 errmsg5193 print ' ' + fname + ' number of dimensions: ',Ndims,' not ready!!!!!'5194 quit(-1)5195 5196 zerodims[5-Ndims+1:6] = matshape5197 5198 4893 newdims = [] 5199 4894 for idim in range(Ndims): 4895 # print idim,'matshape[idim]:',matshape[Ndims-1-idim],'iddim:',iddim 5200 4896 if idim != iddim: 5201 newdims.append(matshape[ idim])4897 newdims.append(matshape[Ndims-1-idim]) 5202 4898 5203 4899 newdims.reverse() … … 5205 4901 mask = np.zeros(tuple(zerodims), dtype=bool) 5206 4902 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 5209 4909 5210 4910 for i5 in range(zerodims[5]): … … 5230 4930 # print 'newmat dim:',iddim,'val:',dimval,':',newdims,'______' 5231 4931 newmat = vals[mask].reshape(tuple(newdims)) 5232 # print newmat5233 5234 return newmat5235 5236 def valmod_dim(values, ncfile, varn):5237 """ Function to modify the value of a variable at a given dimension and value5238 values = dimn,dimval,modins,modval1,[modval2,...]5239 dimn = name of the dimension5240 dimval = value of the dimension at which change the values5241 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 name5249 varn = name of the variable5250 >>> 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 value5256 values = dimn,dimval,modins,modval1,[modval2,...]5257 dimn = name of the dimension5258 dimval = value of the dimension at which change the values5259 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 name5267 varn = name of the variable5268 >>> 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 errormsg5285 print ' valmod: File "' + ncfile + '" does not exist !!'5286 print errormsg5287 quit(-1)5288 5289 ncf = NetCDFFile(ncfile,'a')5290 5291 if ncf.dimensions.has_key('plev'):5292 # removing pressure level from variable name5293 varn = re.sub("\d+", "", varn)5294 5295 if not ncf.dimensions.has_key(dimn):5296 print errormsg5297 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 errormsg5304 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 id5315 iddim=varinf.Ndims - 15316 for idimn in varinf.dimns:5317 # print iddim, idimn5318 if dimn == idimn:5319 break5320 5321 iddim = iddim - 15322 5323 matshape = varvals.shape5324 mattype = varvals.dtype5325 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 errmsg5332 print ' ' + fname + ' number of dimensions: ',Ndims,' not ready!!!!!'5333 quit(-1)5334 5335 zerodims[5-Ndims+1:6] = matshape5336 5337 newdims = []5338 for idim in range(Ndims):5339 # print idim,'matshape[idim]:',matshape[Ndims-1-idim],'iddim:',iddim5340 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]] = varvals5351 5352 # print 'vals shape:',vals.shape,':',newdims5353 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,i55361 if iddim == 5 and dimval == i0:5362 mask[i0,i1,i2,i3,i4,i5] = True5363 elif iddim == 4 and dimval == i1:5364 mask[i0,i1,i2,i3,i4,i5] = True5365 elif iddim == 3 and dimval == i2:5366 mask[i0,i1,i2,i3,i4,i5] = True5367 elif iddim == 2 and dimval == i3:5368 mask[i0,i1,i2,i3,i4,i5] = True5369 elif iddim == 1 and dimval == i4:5370 mask[i0,i1,i2,i3,i4,i5] = True5371 elif iddim == 0 and dimval == i5:5372 mask[i0,i1,i2,i3,i4,i5] = True5373 5374 # print 'newmat dim:',iddim,'val:',dimval,':',newdims,'______'5375 newmat = vals[mask].reshape(tuple(newdims))5376 4932 varmod = np.zeros(tuple(newdims), dtype=mattype) 5377 4933 … … 5413 4969 ncf.sync() 5414 4970 ncf.close() 4971 4972 return 5415 4973 5416 4974 def checkNaNs(values, filen): … … 5513 5071 ncobj.close() 5514 5072 5073 return 5074 5515 5075 ##checkNaNs(10.e10, '/d4/lflmd/etudes/WRF_LMDZ/WaquaL/WRF/control/wrfout_d01_1979-12-01_00:00:00') 5516 5076 ##checkNaNs(10.e10, '/d4/lflmd/etudes/FF/tests/em_quarter_ss/run/wrfout_d01_0001-01-01_00:00:00') … … 5549 5109 5550 5110 ncobj.close() 5111 5112 return 5551 5113 5552 5114 ##checkAllValues(0., '/d4/lflmd/etudes/WRF_LMDZ/WaquaL/WRF/control/wrfout_d01_1979-12-01_00:00:00') … … 6110 5672 6111 5673 return 6112 6113 5674 6114 5675 def sellonlatboxold(values, ncfile, varn): … … 7009 6570 #compute_opervaralltime('add|time', 'obs/PRCP.nc', 'product') 7010 6571 7011 def retype(val, vtype):7012 """ Function to transform a value to a given type7013 retype(val, vtype)7014 [val]= value7015 [vtype]= type to transform7016 >>> retype(0, type(True))7017 False7018 """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 warnmsg7037 print ' ' + fname + ': value to transform ', val,' overpasses type:', \7038 vtype,' limits!!'7039 print ' Changing value to kind largest allowed value:', typeinf.max7040 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 warnmsg7047 print ' ' + fname + ': value to transform ', val,' overpasses type:', \7048 vtype,' limits!!'7049 print ' Changing value to kind largest allowed value:', typeinf.max7050 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 warnmsg7057 print ' ' + fname + ': value to transform ', val,' overpasses type:', \7058 vtype,' limits!!'7059 print ' Changing value to kind largest allowed value:', typeinf.max7060 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 = False7076 else:7077 newval = True7078 elif vtype == '|S1':7079 newval = str(val)7080 else:7081 print errormsg7082 print ' ' + fname + ': variable type "', vtype, '" not ready!!!'7083 quit(-1)7084 7085 return newval7086 7087 6572 def setvar_asciivalues(values, ncfile, varname): 7088 6573 """ Function to set de values of a variable with an ASCII file (common … … 7170 6655 objnc.close() 7171 6656 6657 return 6658 7172 6659 #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-step7178 self.maxv[t]: spatial maximum at each time-step7179 self.meanv[t]: spatial mean at each time-step7180 self.mean2v[t]: spatial quadratic mean at each time-step7181 self.stdv[t]: spatial standard deviation at each time-step7182 self.anomv[t]: spatial anomaly from the whole mean at each time-step7183 """7184 7185 def __init__(self, vals):7186 from scipy import stats as sts7187 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 = None7196 self.maxv = None7197 self.meanv = None7198 self.mean2v = None7199 self.stdv = None7200 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 sts7240 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 = None7249 self.maxv1Av2 = None7250 self.meanv1Av2 = None7251 self.mean2v1Av2 = None7252 self.stdv1Av2 = None7253 self.minv1Sv2 = None7254 self.maxv1Sv2 = None7255 self.meanv1Sv2 = None7256 self.mean2v1Sv2 = None7257 self.stdv1Sv2 = None7258 self.minv1Dv2 = None7259 self.maxv1Dv2 = None7260 self.meanv1Dv2 = None7261 self.mean2v1Dv2 = None7262 self.stdv1Dv2 = None7263 self.minv1Pv2 = None7264 self.maxv1Pv2 = None7265 self.meanv1Pv2 = None7266 self.mean2v1Pv2 = None7267 self.stdv1Pv2 = None7268 self.mae = None7269 self.corr = None7270 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 # add7281 vs = v1 + v27282 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 # sub7288 stats[it,20] = np.mean(np.abs(v1-v2))7289 vs = v1 - v27290 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 # mul7297 vs = v1 * v27298 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 # div7304 vs = v1 / v27305 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 # corr7311 stats[it,21], stats[it,22] = mask_pearsonr(v1, v2)7312 7313 # Mean values7314 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 point7358 self.maxv[t]: temporal maximum at each grid point7359 self.meanv[t]: temporal mean at each grid point7360 self.mean2v[t]: temporal quadratic mean at each grid point7361 self.stdv[t]: temporal standard deviation at each grid point7362 self.anomv[t]: temporal anomaly from the whole mean at each grid point7363 """7364 7365 def __init__(self, vals):7366 from scipy import stats as sts7367 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 = None7376 self.maxv = None7377 self.meanv = None7378 self.mean2v = None7379 self.stdv = None7380 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 sts7420 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 = None7429 self.maxv1Av2 = None7430 self.meanv1Av2 = None7431 self.mean2v1Av2 = None7432 self.stdv1Av2 = None7433 self.minv1Sv2 = None7434 self.maxv1Sv2 = None7435 self.meanv1Sv2 = None7436 self.mean2v1Sv2 = None7437 self.stdv1Sv2 = None7438 self.minv1Dv2 = None7439 self.maxv1Dv2 = None7440 self.meanv1Dv2 = None7441 self.mean2v1Dv2 = None7442 self.stdv1Dv2 = None7443 self.minv1Pv2 = None7444 self.maxv1Pv2 = None7445 self.meanv1Pv2 = None7446 self.mean2v1Pv2 = None7447 self.stdv1Pv2 = None7448 self.mae = None7449 self.corr = None7450 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 # add7457 vs = vals1 + vals27458 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 # sub7464 stats[:,:,20] = np.mean(np.abs(vals1-vals2), axis=0)7465 vs = vals1 - vals27466 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 # mul7472 vs = vals1 * vals27473 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 # div7479 vs = vals1 / vals27480 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 values7488 meanvals1[:,:] = np.mean(vals1,axis=0)7489 meanvals2[:,:] = np.mean(vals2,axis=0)7490 stats[:,:,23] = meanvals1[:,:] - meanvals2[:,:]7491 7492 # corr7493 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))7538 6660 7539 6661 def statcompare_files(values): … … 7788 6910 7789 6911 #statcompare_files('control/sellonlatbox_wss_17-20.nc:wss,obs/re_project_Vu_17-20.nc:wss') 7790 7791 6912 7792 6913 def sellonlatlevbox(values, ncfile, varn): … … 8116 7237 8117 7238 #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 file8121 filen= name of the file8122 char= character as no line8123 >>> file_nlines('trajectory.dat','#')8124 498125 """8126 fname = 'file_nlines'8127 8128 if not os.path.isfile(filen):8129 print errormsg8130 print ' ' + fname + ' file: "' + filen + '" does not exist !!'8131 quit(-1)8132 8133 fo = open(filen,'r')8134 8135 nlines=08136 for line in fo:8137 if line[0:1] != char: nlines = nlines + 18138 8139 fo.close()8140 8141 return nlines8142 8143 def datetimeStr_conversion(StringDT,typeSi,typeSo):8144 """ Function to transform a string date to an another date object8145 StringDT= string with the date and time8146 typeSi= type of datetime string input8147 typeSo= type of datetime string output8148 [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] format8152 'Y-m-d_H:M:S': [YYYY]-[MM]-[DD]_[HH]:[MI]:[SS] format8153 'Y-m-d H:M:S': [YYYY]-[MM]-[DD] [HH]:[MI]:[SS] format8154 'Y/m/d H-M-S': [YYYY]/[MM]/[DD] [HH]-[MI]-[SS] format8155 '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-008161 """8162 import datetime as dt8163 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 errormsg8208 print ' timeref_datetime: time units "' + tunits + '" not ready!!!!'8209 quit(-1)8210 8211 yr = newdate.year8212 mo = newdate.month8213 da = newdate.day8214 ho = newdate.hour8215 mi = newdate.minute8216 se = newdate.second8217 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 errormsg8271 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] = yr8278 dateYmdHMS[1] = mo8279 dateYmdHMS[2] = da8280 dateYmdHMS[3] = ho8281 dateYmdHMS[4] = mi8282 dateYmdHMS[5] = se8283 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/10008301 yC = (yr-yM*1000)/1008302 yD = (yr-yM*1000-yC*100)/108303 yU = yr-yM*1000-yC*100-yD*108304 8305 mD = mo/108306 mU = mo-mD*108307 8308 dD = da/108309 dU = da-dD*108310 8311 hD = ho/108312 hU = ho-hD*108313 8314 miD = mi/108315 miU = mi-miD*108316 8317 sD = se/108318 sU = se-sD*108319 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 errormsg8341 print ' ' + fname + ': type of output date "' + typeSo + '" not ready !!!!'8342 quit(-1)8343 8344 return dateYmdHMS8345 8346 def table_tex(tablevals, colnames, rownames, of):8347 """ Function to write into a LaTeX tabukar from a table of values8348 tablevals = (ncol nrow) of values8349 colnames = list with ncol labels for the columns8350 rownames = list with nrow labels for the rows8351 of= object ASCII file to write the table8352 """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 errormsg8362 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:',colnames8366 quit(-1)8367 8368 if Nrow != len(rownames):8369 print errormsg8370 print ' ' + fname + ': wrong number of row names!!'8371 print ' data has:', Nrow, 'and you provided:', len(rownames)8372 print ' you provide:',rownames8373 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 = 08390 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 + 18398 8399 of.write('\\end{tabular}\n')8400 8401 return8402 8403 def radius_dist(dx,dy,ptx,pty):8404 """ Function to generate a matrix with the distance at a given point8405 radius_dist(dx,dy,ptx,pty)8406 [dx/y]: dimension of the matrix8407 [ptx/y]: grid point coordinates of the point8408 >>> 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 errormsg8418 print ' ' + fname + ': wrong point coordinates:',dx,',',dy,'for matrix;',dx \8419 ,'x',dy8420 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 dist8434 8435 def lonlat2D(lon,lat):8436 """ Function to return lon, lat 2D matrices from any lon,lat matrix8437 lon= matrix with longitude values8438 lat= matrix with latitude values8439 """8440 fname = 'lonlat2D'8441 8442 if len(lon.shape) != len(lat.shape):8443 print errormsg8444 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, latvv8460 7239 8461 7240 def compute_tevolboxtraj(values, ncfile, varn): … … 9357 8136 #compute_tevolboxtraj('001/trajectory.dat@0,XLONG,XLAT,ZNU,Times,wrf,3,3', \ 9358 8137 # '001/full_concatenated.nc', 'PSFC') 9359 9360 def interpolate_locs(locs,coords,kinterp):9361 """ Function to provide interpolate locations on a given axis9362 interpolate_locs(locs,axis,kinterp)9363 locs= locations to interpolate9364 coords= axis values with the reference of coordinates9365 kinterp: kind of interpolation9366 'lin': linear9367 >>> 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.59372 >>> coordinates[2] = 2.59373 >>> 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, b9416 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)*b9423 else:9424 print errormsg9425 print ' ' + fname + ": interpolation kind '" + kinterp + "' not ready !!!!!"9426 quit(-1)9427 9428 return intlocs9429 9430 def vertical_interpolation2D(varb,vart,zorigvals,znewval,kinterp):9431 """ Function to vertically integrate a 3D variable9432 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 interpolate9437 Possible cases:9438 zorigvals[0,:,:] <= znewval < zorigvals[1,:,:]9439 znewval <= zorigvals[0,:,:] < zorigvals[1,:,:]9440 zorigvals[0,:,:] < zorigvals[1,:,:] <= znewval9441 kinterp: kind of interpolation9442 'lin': linear9443 >>> dx=59444 >>> dy=79445 >>> 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.59450 >>> 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',znewval9472 # Standard linear interpolation (y = a + b*incz)9473 # a = zorig[0], b = (vart-varb)/(zorig[1]-zorig[0])), incz = znewval - zorig[0]9474 a = varb9475 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*incz9480 # 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 errormsg9497 print ' ' + fname + ": interpolation kind '" + kinterp + "' not ready !!!!!"9498 quit(-1)9499 9500 return newvar9501 9502 #dx=59503 #dy=79504 #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.59509 #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.759517 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 variable9522 vertical_interpolation(varb,vart,zorigvals,znewval)9523 varb= values at the base of the interval of interpolation9524 vart= values at the top of the interval of interpolation9525 zorigvals= pair of original values (2)9526 znewval= new value to interpolate9527 Possible cases:9528 zorigvals[0,:] <= znewval < zorigvals[1,:]9529 znewval <= zorigvals[0,:] < zorigvals[1,:]9530 zorigvals[0,:] < zorigvals[1,:] <= znewval9531 kinterp: kind of interpolation9532 'lin': linear9533 >>> dx=59534 >>> 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.59539 >>> for i in range(dx):9540 >>> zbase[1,i] = i + 1.9541 9542 >>> newz = 0.759543 >>> 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',znewval9557 # Standard linear interpolation (y = a + b*incz)9558 # a = zorig[0], b = (vart-varb)/(zorig[1]-zorig[0])), incz = znewval - zorig[0]9559 a = varb9560 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*incz9565 else:9566 print errormsg9567 print ' ' + fname + ": interpolation kind '" + kinterp + "' not ready !!!!!"9568 quit(-1)9569 9570 return newvar9571 9572 def interpolate_3D(zorigvs, varv, zintvs, kint):9573 """ Function to interpolate a 3D variable9574 interpolate_3D(zintvs, varv, zorigvals)9575 zorigvs= original 3D z values9576 varv= 3D variable to interpolate9577 zintvs= new series of z values to interpolate9578 kint= kind of interpolation9579 'lin': linear9580 """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.shape9590 9591 # Sense of the original z-variable9592 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 break9635 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 varin9649 9650 def interpolate_2D(zorigvs0, varv0, zdim, zintvs, kint):9651 """ Function to interpolate a 2D variable9652 interpolate_2D(zintvs, varv, zorigvals)9653 zorigvs= original 2D z values9654 varv= 2D variable to interpolate9655 zdim= number of the dimension with the z-values9656 zintvs= new series of z values to interpolate9657 kint= kind of interpolation9658 'lin': linear9659 """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 = varv09670 zorigvs = zorigvs09671 else:9672 varv = np.transpose(varv0)9673 zorigvs = np.transpose(zorigvs0)9674 9675 dimv = varv.shape9676 9677 # Sense of the original z-variable9678 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 break9717 9718 varin[ilev,:] = vertical_interpolation(valinf,valsup,zorigv, \9719 zintvs[ilev], kint)9720 9721 if zdim == 0:9722 varin0 = varin9723 else:9724 varin0 = np.transpose(varin)9725 9726 return varin09727 9728 9729 def list_toVec(listv, kind):9730 """ Function to transform from a list of values to a vector9731 list_toVec(listv, kind)9732 listv= list with the values9733 kind= kind of values9734 >>> 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 errormsg9753 print ' ' + fname + ': type of value "' + kind + '" not ready!!'9754 quit(-1)9755 9756 return vecv9757 9758 def running_mean(values, run):9759 """ Function to compute a running mean of a series of values9760 running_mean(vals, int)9761 [vals]: series of values9762 [run]: interval to use to compute the running mean9763 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.59766 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.59767 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.59768 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.59769 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.59770 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.59771 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)*fillValue9781 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 runmean9788 8138 9789 8139 def slice_variable(varobj, dimslice): … … 10559 8909 #WRF_CFlon_creation('longitude', 'wrfout_d01_1980-03-01_00:00:00_Time_B0-E48-I1.nc', 'XLONG') 10560 8910 10561 10562 8911 def dimVar_creation(values, ncfile): 10563 8912 """ Function to add a 1D variable with the size of a given dimension in a file … … 10604 8953 10605 8954 #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 sub10618 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:',ins10628 files = sub.Popen(["/bin/ls","-1",ins], stdout=sub.PIPE)10629 fileslist = files.communicate()10630 listfiles0 = str(fileslist).split('\\n')10631 10632 # Filtering output10633 Lheader=len(headfile)10634 listfiles = []10635 for ifile in listfiles0:10636 if ifile[0:Lheader] == headfile:10637 listfiles.append(ifile)10638 10639 return listfiles10640 8955 10641 8956 def netcdf_fold_concatenation(values, ncfile, varn): … … 10892 9207 #netcdf_concatenation('mean_pluc.nc@all|mean_dtcon.nc@all') 10893 9208 10894 def count_cond(var, val, con):10895 """ Function to count values of a variable which attain a condition10896 [var]= variable10897 [val]= value10898 [con]= statistics/condition10899 '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 110910 >>> count_cond(vals,50,'neq')10911 9910912 >>> count_cond(vals,50,'lt')10913 5010914 >>> count_cond(vals,50,'le')10915 5110916 >>> count_cond(vals,50,'gt')10917 4910918 >>> count_cond(vals,50,'ge')10919 5010920 >>> count_cond(vals,[25,75],'in')10921 5110922 >>> count_cond(vals,[25,75],'out')10923 4910924 """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 errormsg10944 print ' ' + fname + ": for condition '" + con + "' we must have two " + \10945 " values!!"10946 print ' we have:', val10947 quit(-1)10948 Nvals = np.sum((var >= val[0])*(var <= val[1]))10949 elif con == 'out':10950 if len(val) != 2:10951 print errormsg10952 print ' ' + fname + ": for condition '" + con + "' we must have two " + \10953 " values!!"10954 print ' we have:', val10955 quit(-1)10956 Nvals = np.sum((var < val[0])+(var > val[1]))10957 else:10958 print errormsg10959 print ' ' + fname + ": condition '" + con + "' not ready!!"10960 print ' only ready:', cons10961 quit(-1)10962 10963 return Nvals10964 10965 9209 def field_stats(values, ncfile, varn): 10966 9210 """ Function to retrieve statistics from a field … … 11074 9318 11075 9319 #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 output11083 'tex3': printed output as LaTeX table of three columns \verb+namelist_name+ & value11084 'column': printed output as namelist_name value11085 'dict': as two python dictionary object (namelistname, value and namelistname, sectionname)11086 namelist= namelist_like file to retrieve values11087 >>> 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/value11094 valuessep = ['=']11095 # List of characters which indicate a comment11096 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 errormsg11111 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] = namessec11134 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 break11150 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 break11156 elif linevals[1].find(valsep) != -1:11157 nmlname = linevals[0]11158 nmlval = linevals[1].split(valsep)[0]11159 break11160 else:11161 print warnmsg11162 print ' ' + fname + ': wrong number of values', Nvals, \11163 'in the namelist line!'11164 print ' line: ',line11165 print ' line values:',linevals11166 # quit(-1)11167 11168 namelistvals[nmlname] = nmlval11169 namelistsecs[nmlname] = sectionname11170 11171 namessec.append(nmlname)11172 allnames.append(nmlname)11173 11174 if len(sectionname) > 1:11175 sections[sectionname] = namessec11176 11177 if secname != 'all':11178 if not searchInlist(sections.keys(),secname):11179 print errormsg11180 print ' ' + fname + ": section '" + values + "' does not exist !!"11181 print ' only found:',sectionnames11182 quit(-1)11183 11184 namestouse = []11185 for nml in allnames:11186 for nnml in sections[secname]:11187 namelistvalssec[nnml] = namelistvals[nnml]11188 namelistsecssec[nnml] = secname11189 if nml == nnml: namestouse.append(nml)11190 else:11191 namestouse = allnames11192 namelistvalssec = namelistvals11193 namelistsecssec = namelistsecs11194 11195 if kout == 'tex3':11196 ofile='get_namelist_vars_3col.tex'11197 fobj = open(ofile, 'w')11198 11199 vals = namestouse11200 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 = Nvals11211 11212 for ival in range(0,Nvals0,3):11213 line = ''11214 print ' ival:',ival11215 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 + line11221 11222 latextab = latextab + '%not multiple of three!!!!\n'11223 print 'mod:', np.mod(Nvals,3),Nvals0,Nvals11224 if np.mod(Nvals,3) != 0:11225 ival = Nvals011226 line = ''11227 for il in range(np.mod(Nvals,3)):11228 print 'ival:',ival + il11229 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 latextab11237 fobj.write(latextab)11238 11239 fobj.close()11240 print fname + ": successful writen '" + ofile + "' LaTeX tale file !!"11241 11242 return11243 elif kout == 'column':11244 for dictv in namestouse:11245 print dictv + ' = ' + namelistvalssec[dictv]11246 return11247 elif kout == 'dict':11248 return namelistvalssec, namelistsecssec11249 else:11250 print errormsg11251 print ' ' + fname + ": kind of output '" + kout + "' not ready!!!"11252 quit(-1)11253 11254 return11255 11256 def WRF_d0Nref(values, geofold):11257 """ Function for the generation of an extra WRF domain from a given one11258 field_stats(values, ncfile, varn)11259 [values]= [namelist],[minLON],[minLAT],[maxLON],[maxLAT],[Ndomref],[factor],[geogres]11260 [namelist]: namelist.wps to use11261 [minLON],[minLAT]: minimum longitude and latitude11262 [maxLON],[maxLAT]: maximum longitude and latitude11263 [Ndomref]: domain reference number11264 [factor]: resolution factor with respect d0111265 [geogres]: which topography resolution to use11266 [geofold]= folder where to found the geo_em.d0[N-1].nc file11267 """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 one11293 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 one11297 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 errormsg11304 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 posdiffmax11334 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(',','')) + 111343 onmlobj.write(' ' + listline[0] + ' = ' + str(nmlval) + ',\n')11344 elif searchInlist(add1value,listline[0]):11345 if Ndomref == 1:11346 nmlval = 111347 else:11348 nmlval = int(listline[nvals-1].replace(',','')) + 111349 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 = factor11357 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] - 1011361 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] - 1011365 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)*factor11369 nmlval = nmlval + np.mod(nmlval,factor) + 111370 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)*factor11374 nmlval = nmlval + np.mod(nmlval,factor) + 111375 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 return11392 9320 11393 9321 def filter_2dim(values, ncfile, varn): … … 12477 10405 #selvar('x@lon,y@lat,time@time,shan@int', '/home/lluis/PY/test.nc', 'var') 12478 10406 12479 def coincident_CFtimes(tvalB, tunitA, tunitB):12480 """ Function to make coincident times for two different sets of CFtimes12481 tvalB= time values B12482 tunitA= time units times A to which we want to make coincidence12483 tunitB= time units times B12484 >>> 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+0812490 9.46699200e+08 9.46702800e+08 9.46706400e+08 9.46710000e+0812491 9.46713600e+08 9.46717200e+08]12492 """12493 import datetime as dt12494 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.e612507 elif tuB == 'minutes':12508 tB = tvalB*60.*10.e612509 elif tuB == 'hours':12510 tB = tvalB*3600.*10.e612511 elif tuB == 'days':12512 tB = tvalB*3600.*24.*10.e612513 else:12514 print errormsg12515 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.e612521 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 errormsg12531 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 errormsg12547 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 errormsg12563 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 errormsg12579 print ' ' + fname + ": combination of time untis: '" + tuA + \12580 "' & '" + tuB + "' not ready !!"12581 quit(-1)12582 else:12583 print errormsg12584 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 - trefTA12594 diffv = difft.days*24.*3600.*10.e6 + difft.seconds*10.e6 + difft.microseconds12595 print ' ' + fname + ': different reference refA:',trefTA,'refB',trefTB12596 print ' difference:',difft,':',diffv,'microseconds'12597 12598 if tuA == 'microseconds':12599 tB = tB + diffv12600 elif tuA == 'seconds':12601 tB = tB + diffv/10.e612602 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 errormsg12610 print ' ' + fname + ": time untis: '" + tuA + "' not ready !!"12611 quit(-1)12612 12613 return tB12614 12615 def wdismean(pos,val4):12616 """ Function to compute the mean value weighted to its 4 distances12617 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.03570795523412623 """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())/totdist12639 12640 return posmean12641 12642 def read_ASCIIlist(filen):12643 """ Function to build a list from an ASCII lines file12644 filen= name of the ASCII file12645 """12646 import os12647 fname = 'read_ASCIIlist'12648 12649 if not os.path.isfile(filen):12650 print errormsg12651 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 filevals12661 12662 def radial_points(angle,dist):12663 """ Function to provide a number of grid point positions for a given angle12664 angle= desired angle (rad)12665 dist= number of grid points12666 >>> 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 radpos12681 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 function12685 Npt= Number of points on each grid12686 maxradii= allowed maximum radii12687 '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 errormsg12693 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 radii12705 if maxradii is not None and rad > maxradii: break12706 Nrad = int(values[2])12707 couples = []12708 Nradgood = 012709 if Nrad > 1:12710 Ncouples = 012711 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 + 112717 elif ix > Npt and iy > Npt: break12718 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 + 112724 elif ix > Npt and iy > Npt: break12725 12726 if Nradgood > 0:12727 Nradii[rad] = Nradgood12728 finalcouples = np.zeros((Nradgood,2), dtype=int)12729 for ic in range(Nradgood):12730 finalcouples[ic,:] = couples[ic]12731 gridradii[rad] = finalcouples12732 12733 # for rad in sorted(gridradii.keys()):12734 # print rad, gridradii[rad]12735 12736 return gridradii12737 12738 def grid_combinations(x,y):12739 """ Function to provide all the possible grid points combination for a given pair of values12740 x,y= pair of grid points12741 >>>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 gridcomb12759 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' radii12762 xpos= x position of the center12763 ypos= y position of the center12764 Lrad= length of the maximum radi in grid points12765 Nang= number of equivalent angles12766 dx= x size of the domain of values12767 dy= y size of the domain of values12768 >>> 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 loop12792 for ia in range(Nang):12793 angle = 2.*np.pi*ia/Nang12794 posangle = np.zeros((Lrad,2), dtype=np.float)12795 12796 # Points at that given angle12797 pangle = radial_points(angle,Lrad)12798 posangle[:,0] = pangle[:,0] + xpos12799 posangle[:,1] = pangle[:,1] + ypos12800 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-step12806 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 values12811 12812 # Radii loop (avoiding 0)12813 pairswithin = {}12814 for ir in range(1,Nradii):12815 pairs = pairsSQradii[SQradii[ir]]12816 12817 # pairs loop12818 Npairs = len(pairs.flatten())/212819 pairsw = []12820 for ip in range(Npairs):12821 if Npairs == 0:12822 break12823 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-step12831 if iipos >= 0 and iipos < dx and jjpos >= 0 and jjpos < dy:12832 pairsw.append([iipos,jjpos])12833 12834 SQradiipos[SQradii[ir]] = pairsw12835 12836 return radiipos, SQradiipos12837 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 neighbourgs12840 field= a 4 points representing the environment of a given point12841 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.4488812819312844 """12845 fname = 'hor_weight_int'12846 12847 vals = np.array([SWval, SEval, NWval, NEval])12848 print vals12849 if xpos > 1.:12850 print errormsg12851 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 vertexs12865 12866 dist = np.sqrt((vertexs[:,0]-xpos)**2 + (vertexs[:,1]-ypos)**2)12867 print dist12868 done = False12869 for id in range(4):12870 if dist[id] == 0.:12871 intval = vals[id]12872 done = True12873 12874 if not done: intval = np.sum(vals/dist)/np.sum(1./dist)12875 12876 return intval12877 12878 10407 def compute_tevolboxtraj_radialsec(values, ncfile, varn): 12879 10408 """ Function to compute tevolboxtraj_radialsec: temporal evolution at a given point along … … 13712 11241 # '/bdd/PCER/workspace/lfita/etudes/FF/medic051215_2km/run/wrfout/wrfout_d02_2005-12-13_00:00:00', 'QVAPOR') 13713 11242 #quit() 13714 13715 11243 13716 11244 def DatesFiles(values, ncfile, varn): … … 14047 11575 #fileobj = NetCDFFile('/home/lluis/PY/ERAI_pl199501_130-133.nc', 'r') 14048 11576 #TimeSplitmat(fileobj, 'time', 'time', 'all', 'd,H') 14049 14050 def rmNOnum(string):14051 """ Removing from a string all that characters which are not numbers14052 # From: http://stackoverflow.com/questions/4289331/python-extract-numbers-from-a-string14053 """14054 fname = 'rmNOnum'14055 14056 newstr = str(re.findall("[-+]?\d+[\.]?\d*", string)[0])14057 14058 return newstr14059 14060 def values_fortran_fmt(lin,fFMT):14061 """ Function to give back the values of an ASCII line according to its fortran printing format14062 lin= ASCII line14063 fFMT= list with the fortran FORMAT formats14064 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=014082 ival = 014083 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 + Lfmt14089 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 + Lfmt14095 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 + Lfmt14101 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 + Lfmt14105 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 errormsg14110 print ' ' + fname + ": format '" + ft[0:1] + "' not ready!!"14111 print ' Available formats:',afmts14112 quit(-1)14113 14114 ival = ival + 114115 14116 return fvalues14117 14118 def reduce_last_spaces(string):14119 """ Function to reduce the last right spaces from a string14120 string= string to remove the spaces at the righ side of the string14121 >>> reduce_last_spaces('Hola Lluis ')14122 'Hola Lluis'14123 """14124 fname = 'reduce_last_spaces'14125 14126 Lstring = len(string)14127 14128 firstspace = -114129 for istr in range(Lstring-1,0,-1):14130 if string[istr:istr+1] == ' ':14131 firstspace = istr14132 else:14133 break14134 14135 if firstspace == -1:14136 print errormsg14137 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 newstr14144 14145 def squared_radial(Npt):14146 """ Function to provide the series of radii as composite of pairs (x,y) of gid cells14147 Npt= largest amount of grid points on x and y directions14148 >>> 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 radii14159 ##14160 for i in range(Npt+1):14161 if np.mod(i,100) == 0: print 'done: ',i14162 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] = 114172 else:14173 # print warnmsg14174 # print ' ' + fname + ': repeated radii',rad,'!!'14175 # print ' Previous values:', gridradii[rad]14176 14177 oldvalues = gridradii[rad]14178 Nradii[rad] = Nradii[rad] + 114179 newvalues = np.zeros((Nradii[rad],2), dtype=int)14180 if Nradii[rad] == 2:14181 newvalues[0,:] = oldvalues14182 Nstart = 114183 else:14184 Nstart = 014185 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] = newvalues14189 14190 # Sorting values14191 ##14192 ## Only required to downwrite the output file14193 # radiif = open('SQradii.dat', 'w')14194 # radii = []14195 # prevrad = 0.14196 # for rad in sorted(gridradii.keys()):14197 # dradii = rad - prevrad14198 ## Check fo repeated values14199 # 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 gridradii14206 11577 14207 11578 def getvalues_lonlat(values, ncfile): … … 15057 12428 #SpatialWeightedMean('reglonlat,XLONG,XLAT,west_east,south_north','wrfout_d01_2001-11-11_00:00:00','HGT') 15058 12429 15059 def fillvalue_kind(vartype, fillval0):15060 """ Function to provide the fiven fill_Value for a kind of variable15061 [vartype]= type of the variable15062 [fillval0]= value to take as fill value, 'std' for the standard value15063 Float = 1.e2015064 Character = '-'15065 Integer = -9999915066 Integer16 = -9999915067 Float64 = 1.e2015068 Integer32 = -9999915069 """15070 fname = 'fillvalue_kind'15071 15072 if vartype == type('c'):15073 if fillval0 == 'std':15074 fillval = fillvalueC15075 else:15076 fillval = fillval015077 elif vartype == type(int(1)):15078 if fillval0 == 'std':15079 fillval = fillValueI15080 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 errormsg15109 print ' ' + fname + ': variable type', vartype, 'not ready !!'15110 quit(-1)15111 15112 return fillval15113 15114 12430 def nctype(vartype): 15115 12431 """ Function to provide the string for the variable creation in a netCDF file … … 15141 12457 return ncs 15142 12458 15143 def varval_ind(var, ind):15144 """ Function to provide a value from a variable providing a value for each index15145 var= variable15146 ind= list of indices for each dimension of the variable15147 """15148 fname = 'varval_ind'15149 if len(var.shape) != len(ind):15150 print errormsg15151 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 val15161 15162 12459 def VarVal_FillValue(values, filen, varn): 15163 12460 """ Function to transform a given value from a given variable to _FillValue in a netCDF file … … 15402 12699 #lonlatProj(100000.,100000.,'lonlat',True) 15403 12700 #quit() 15404 15405 def CoarselonlatFind(ilon, ilat, lonv, latv, per):15406 """ Function to search a given value from a coarser version of the data15407 ilon, ilat= original 2D matrices with the longitudes and the latitudes15408 lonv, latv= longitude and latitude to find15409 per= period (as fraction over 1) of the fractions of the original grid to use to explore15410 >>> npt=10015411 >>> 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 errormsg15434 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 errormsg15439 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 fraclon15453 15454 # print 'fraclat _______'15455 # print fraclat15456 15457 # Fraction point15458 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:', ilatlonfrac15463 # print 'frac lon, lat:', fraclon[ilatlonfrac[0],ilatlonfrac[1]], ',', \15464 # fraclat[ilatlonfrac[0],ilatlonfrac[1]]15465 # print 'values lon, lat:', lonv, latv15466 15467 # Providing fraction range15468 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)*fracy15474 iyend = ilatlonfrac[0]*fracy+115475 else:15476 iybeg = 015477 iyend = fracy+115478 if ilatlonfrac[1] > 0:15479 ixbeg = (ilatlonfrac[1]-1)*fracx15480 ixend = ilatlonfrac[1]*fracx+115481 else:15482 ixbeg = 015483 ixend = fracx+115484 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)*fracy15490 iyend = ilatlonfrac[0]*fracy+115491 else:15492 iybeg = 015493 iyend = fracy+115494 if ilatlonfrac[1] < fracdx:15495 if ilatlonfrac[1] != 0:15496 ixbeg = (ilatlonfrac[1]-1)*fracx15497 ixend = ilatlonfrac[1]*fracx+115498 else:15499 ixbeg = 015500 ixend = fracx+115501 else:15502 ixbeg = fracdx*fracx15503 ixend = dx+115504 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)*fracy15511 iyend = ilatlonfrac[0]*fracy+115512 else:15513 iybeg = 015514 iyend = fracy+115515 else:15516 iybeg = fracdy*fracy15517 iyend = dy+115518 if ilatlonfrac[1] < fracdx:15519 if ilatlonfrac[1] != 0:15520 ixbeg = (ilatlonfrac[1]-1)*fracx15521 ixend = ilatlonfrac[1]*fracx+115522 else:15523 ixbeg = 015524 ixend = fracx+115525 else:15526 ixbeg = fracdx*fracx15527 ixend = dx+115528 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)*fracy15535 iyend = ilatlonfrac[0]*fracy+115536 else:15537 iybeg = 015538 iyend = fracy+115539 else:15540 iybeg = fracdy*fracy15541 iyend = dy+115542 if ilatlonfrac[1] > 0:15543 ixbeg = (ilatlonfrac[1]-1)*fracx15544 ixend = ilatlonfrac[1]*fracx+115545 else:15546 ixbeg = 015547 ixend = fracx+115548 15549 # ibeg = [iybeg, ixbeg]15550 # iend = [iyend, ixend]15551 # print 'find window; beginning', ibeg, 'end:', iend15552 lon = ilon[iybeg:iyend,ixbeg:ixend]15553 lat = ilat[iybeg:iyend,ixbeg:ixend]15554 15555 # print 'lon _______'15556 # print lon15557 # print 'lat _______'15558 # print lat15559 15560 # Find point15561 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] + iybeg15566 ilatlon[1] = ilatlon[1] + ixbeg15567 15568 # print 'mindiffLl:', mindiffLl, 'ilatlon:', ilatlon15569 # print 'lon, lat:', lon[ilatlon[0],ilatlon[1]], ',', lat[ilatlon[0],ilatlon[1]]15570 # quit()15571 15572 return ilatlon, mindiffLl15573 15574 def CoarselonlatFindAll(onc, ilon, ilat, longvs, latvs, per, frac, out):15575 """ Function to search all values from a coarser version of the data15576 onc= netCDF object from an existing file15577 ilon, ilat= original 2D matrices with the longitudes and the latitudes15578 lonv, latv= longitude and latitude to find15579 per= period (as fraction over 1) of the fractions of the original grid to use to explore15580 frac= frequency of points at which syncronize file with calculations15581 out= True/False if outcome is required15582 >>> npt=10015583 >>> 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 fraclon15618 15619 # print 'fraclat _______'15620 # print fraclat15621 15622 if out:15623 ilatlon = np.zeros((2,Nallpts), dtype=int)15624 mindiffLl = np.zeros((Nallpts), dtype=np.float)15625 15626 iptpos=015627 for iv in range(Nallpts):15628 lonv = longvs[iv]15629 latv = latvs[iv]15630 15631 if lonv < nlon or lonv > xlon:15632 print errormsg15633 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 errormsg15638 print ' ' + fname + ': latitude outside data range!!'15639 print ' given value:', latv,'outside [',nlat,',',xlat,']'15640 quit(-1)15641 15642 # Fraction point15643 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, latv15648 # print 'mindifffracLl:', mindifffracLl, 'ilatlonfrac:', ilatlonfrac15649 # print 'frac lon, lat:', fraclon[ilatlonfrac[0],ilatlonfrac[1]], ',', \15650 # fraclat[ilatlonfrac[0],ilatlonfrac[1]]15651 15652 # Providing fraction range15653 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)*fracy15659 iyend = ilatlonfrac[0]*fracy+115660 else:15661 iybeg = 015662 iyend = fracy+115663 if ilatlonfrac[1] > 0:15664 ixbeg = (ilatlonfrac[1]-1)*fracx15665 ixend = ilatlonfrac[1]*fracx+115666 else:15667 ixbeg = 015668 ixend = fracx+115669 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)*fracy15675 iyend = ilatlonfrac[0]*fracy+115676 else:15677 iybeg = 015678 iyend = fracy+115679 if ilatlonfrac[1] < fracdx:15680 if ilatlonfrac[1] != 0:15681 ixbeg = (ilatlonfrac[1]-1)*fracx15682 ixend = ilatlonfrac[1]*fracx+115683 else:15684 ixbeg = 015685 ixend = fracx+115686 else:15687 ixbeg = fracdx*fracx15688 ixend = dx+115689 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)*fracy15696 iyend = ilatlonfrac[0]*fracy+115697 else:15698 iybeg = 015699 iyend = fracy+115700 else:15701 iybeg = fracdy*fracy15702 iyend = dy+115703 if ilatlonfrac[1] < fracdx:15704 if ilatlonfrac[1] != 0:15705 ixbeg = (ilatlonfrac[1]-1)*fracx15706 ixend = ilatlonfrac[1]*fracx+115707 else:15708 ixbeg = 015709 ixend = fracx+115710 else:15711 ixbeg = fracdx*fracx15712 ixend = dx+115713 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)*fracy15720 iyend = ilatlonfrac[0]*fracy+115721 else:15722 iybeg = 015723 iyend = fracy+115724 else:15725 iybeg = fracdy*fracy15726 iyend = dy+115727 if ilatlonfrac[1] > 0:15728 ixbeg = (ilatlonfrac[1]-1)*fracx15729 ixend = ilatlonfrac[1]*fracx+115730 else:15731 ixbeg = 015732 ixend = fracx+115733 15734 # ibeg = [iybeg, ixbeg]15735 # iend = [iyend, ixend]15736 # print 'find window; beginning', ibeg, 'end:', iend15737 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 lon15745 # print 'lat _______'15746 # print lat15747 15748 # Find point15749 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] + iybeg15754 ilatlon[1,iv] = ilatlon[1,iv] + ixbeg15755 else:15756 mindiffLl = np.min(difflonlat)15757 ilatlon = index_mat(difflonlat, mindiffLl)15758 ilatlon[0] = ilatlon[0] + iybeg15759 ilatlon[1] = ilatlon[1] + ixbeg15760 15761 # print 'mindiffLl:', mindiffLl, 'ilatlon:', ilatlon15762 # 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 + 115769 # Speeding it up!15770 # if mindiffLl > mindiff:15771 # print errormsg15772 # 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:', mindiffLl15777 # 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]] = iv15783 # newvarinpt[iv] = 115784 # newvarindiff[iv] = mindiffLl15785 newvar[ilatlon[0],ilatlon[1]] = ovar[iv]15786 newvarin[ilatlon[0],ilatlon[1]] = iv15787 newvarinpt[iv] = 115788 newvarindiff[iv] = mindiffLl15789 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:',ilatlon15794 # else:15795 # print errormsg15796 # 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, mindiffLl15806 else:15807 return15808 15809 def lonlatFind(ilon, ilat, lonv, latv):15810 """ Function to search a given value from a lon, lat 2D data15811 ilon, ilat= original 2D matrices with the longitudes and the latitudes15812 lonv, latv= longitude and latitude to find15813 >>> npt=10015814 >>> 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 errormsg15837 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 errormsg15842 print ' ' + fname + ': latitude outside data range!!'15843 print ' given value:', latv,'outside [',nlat,',',xlat,']'15844 quit(-1)15845 15846 # Find point15847 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:', ilatlon15852 # print 'lon, lat:', lon[ilatlon[0],ilatlon[1]], ',', lat[ilatlon[0],ilatlon[1]]15853 15854 return ilatlon, mindiffLl15855 12701 15856 12702 def Partialmap_Entiremap(values, filen, varn):
Note: See TracChangeset
for help on using the changeset viewer.