def setStInShape(self,shpfile): """ Функция возвращает список станций попадающий в полигон(ы) из шэйпфайла файла """ import shapefile as shp import geocalc from shapely.geometry import Polygon,Point res=[] sf = shp.Reader(shpfile) for sp in sf.shapes(): res_tmp=[] lonmin,latmin,lonmax,latmax=sp.bbox lonmin,lonmax=geocalc.cLon(lonmin),geocalc.cLon(lonmax) if lonmin<0 or lonmax<0: polygonPoints=[[geocalc.cLon(cors[0]),cors[1]] for cors in sp.points] else: polygonPoints=sp.points poly=Polygon(polygonPoints) indsInBox=[ind for ind in self.stInds if lonmin<=geocalc.cLon(self.stMeta[ind]['lon'])<=lonmax and latmin<=self.stMeta[ind]['lat']<=latmax] for ind in indsInBox: lat,lon=self.stMeta[ind]['lat'], geocalc.cLon(self.stMeta[ind]['lon']) pnt=Point(lon,lat) if poly.contains(pnt): res_tmp.append(ind) res=res+res_tmp return list(set(res))
def setLatLon(self, year=None, month=None): f, r = self.getDataObj(self.firstObservation.year, self.firstObservation.month) self.lat = f.select('Latitude') self.latvals = self.lat.get()[:,0] self.lon = f.select('Longitude') self.lonvals = [cLon(v) for v in self.lon.get()[0,:]] self.seaLandMask = f.select('LandSeaMask').get() return self.latvals, self.lonvals
def __init__(self, fn, convert=True): fn=os.path.abspath(fn) try: self.f=nc.Dataset(fn) except RuntimeError: raise IOError, "no such file or dir %s"%fn if self.f.project_id!='CMIP5': print 'projet_id is "%s" not "CMIP5"'%self.f.project_id # определяем основную переменную в массиве, это так которая зависит от трёх других dtList=[v for v in self.f.variables if self.f.variables[v].ndim==3] if len(dtList)>1: dtList=[tmpDt for tmpDt in dtList if tmpDt in elSynom] if len(dtList)>1: raise TypeError, "Unknown data type in nc file" self.dt=dtList[0] if self.dt=='tas' and convert is True: from tempConvert import kelvin2celsius self.convertValue=lambda val,year,month: kelvin2celsius(val) self.convertArray=lambda arr: np.subtract(arr,273.15) elif self.dt=='pr' and convert is True: if self.f.frequency=='day': from precConvert import si2mmPerDay self.convertValue=si2mmPerDay elif self.f.frequency=='mon': from precConvert import si2mmPerMonth self.convertValue=si2mmPerMonth self.convertArray=np.vectorize(lambda val: val*86400*30.5, otypes=[np.float]) else: self.convertValue=lambda val,year,month: val self.convertArray=lambda arr: arr # print "Warning! There is no converter for data type = '%s'"%self.dt self.var=self.f.variables[self.dt] self.lat=self.f.variables['lat'] self.latvals=[self.lat[l] for l in range(self.lat.size)] self.lon=self.f.variables['lon'] self.lonvals=[cLon(self.lon[l]) for l in range(self.lon.size)] if self.f.variables['time'].units=='days since 1-01-01 00:00:00': self.timeUnits='days since 0001-01-01 00:00:00' elif self.f.variables['time'].units=='days since 850-1-1 00:00:00': self.timeUnits='days since 0850-1-1 00:00:00' else: self.timeUnits=self.f.variables['time'].units try: self.startDate=nc.num2date(self.f.variables['time'][0], self.timeUnits, self.f.variables['time'].calendar) except ValueError: raise print 'Warning! failed to parse date string -%s. Model id - %s. startDate set to 0850-1-1 assuming model is MPI'%(self.f.variables['time'].units,self.f.model_id) # if self.f.variables['time'].units=='days since 1-01-01 00:00:00': # self.startDate=datetime(1,1,1) # else: # print 'Warning! failed to parse date string -%s. Model id - %s. startDate '\ # 'set to 0850-1-1 assuming model is MPI'%(self.f.variables['time'].units,self.f.model_id) # self.startDate=datetime(850,1,1) self.startYear = int(self.startDate.year) self.startMonth = int(self.startDate.month) self.warningShown = False self.cliSetMeta = {'modelId':self.f.model_id, 'calendar':self.f.variables['time'].calendar, 'source':fn, 'scenario':self.f.experiment_id, 'dt':self.dt}
def setLatLon(self, latName='lat', lonName='lon'): self.lat=self.f.variables[latName] self.latvals=[self.lat[l] for l in range(self.lat.size)] self.lon=self.f.variables[lonName] self.lonvals=[cLon(self.lon[l]) for l in range(self.lon.size)]