def find_nearest_latlon_xarray(arr, lat=37.102400, lon=-76.392900, radius=12e3): """Short summary. Parameters ---------- arr : type Description of parameter `arr`. lat : type Description of parameter `lat` (the default is 37.102400). lon : type Description of parameter `lon` (the default is -76.392900). radius : type Description of parameter `radius` (the default is 12e3). Returns ------- type Description of returned object. """ from pyresample import utils, geometry from numpy import array, vstack grid1 = geometry.GridDefinition(lons=arr.longitude, lats=arr.latitude) grid2 = geometry.GridDefinition(lons=vstack([lon]), lats=vstack([lat])) row, col = utils.generate_nearest_neighbour_linesample_arrays( grid1, grid2, radius) row = row.flatten() col = col.flatten() return arr.sel(x=col).sel(y=row).squeeze()
def test_nearest_neighbor_grid_grid(self): from pyresample import utils, geometry lon_arr = create_test_longitude(-95.0, -85.0, (40, 50), dtype=np.float64) lat_arr = create_test_latitude(25.0, 35.0, (40, 50), dtype=np.float64) grid_dst = geometry.GridDefinition(lons=lon_arr, lats=lat_arr) lon_arr = create_test_longitude(-100.0, -80.0, (400, 500), dtype=np.float64) lat_arr = create_test_latitude(20.0, 40.0, (400, 500), dtype=np.float64) grid = geometry.GridDefinition(lons=lon_arr, lats=lat_arr) rows, cols = utils.generate_nearest_neighbour_linesample_arrays(grid, grid_dst, 12000.)
def test_nearest_neighbor_grid_grid(self): from pyresample import utils, geometry lon_arr = create_test_longitude(-95.0, -85.0, (40, 50), dtype=np.float64) lat_arr = create_test_latitude(25.0, 35.0, (40, 50), dtype=np.float64) grid_dst = geometry.GridDefinition(lons=lon_arr, lats=lat_arr) lon_arr = create_test_longitude(-100.0, -80.0, (400, 500), dtype=np.float64) lat_arr = create_test_latitude(20.0, 40.0, (400, 500), dtype=np.float64) grid = geometry.GridDefinition(lons=lon_arr, lats=lat_arr) rows, cols = utils.generate_nearest_neighbour_linesample_arrays(grid, grid_dst, 12000.)
def nearest_latlon(self, lat=None, lon=None, **kwargs): """Short summary. Parameters ---------- lat : type Description of parameter `lat`. lon : type Description of parameter `lon`. **kwargs : type Description of parameter `**kwargs`. Returns ------- type Description of returned object. """ try: from pyresample import utils from .util.interp_util import nearest_point_swathdefinition as npsd from .util.interp_util import lonlat_to_swathdefinition as llsd has_pyresample = True except ImportError: has_pyresample = False if has_pyresample: lons, lats = utils.check_and_wrap(self.obj.longitude.values, self.obj.latitude.values) swath = llsd(longitude=lons, latitude=lats) pswath = npsd(longitude=float(lon), latitude=float(lat)) row, col = utils.generate_nearest_neighbour_linesample_arrays( swath, pswath, float(1e6)) y, x = row[0][0], col[0][0] return self.obj.isel(x=x, y=y) else: vars = pd.Series(self.obj.variables) skip_keys = ['latitude', 'longitude', 'time', 'TFLAG'] loop_vars = vars.loc[~vars.isin(skip_keys)] kwargs = self._check_kwargs_and_set_defaults(**kwargs) kwargs['reuse_weights'] = True orig = self.obj[loop_vars.iloc[0]].monet.nearest_latlon( lat=lat, lon=lon, cleanup=False, **kwargs) dset = orig.to_dataset() dset.attrs = self.obj.attrs.copy() for i in loop_vars[1:-1].values: dset[i] = self.obj[i].monet.nearest_latlon(lat=lat, lon=lon, cleanup=False, **kwargs) i = loop_vars.values[-1] dset[i] = self.obj[i].monet.nearest_latlon(lat=lat, lon=lon, cleanup=True, **kwargs) return dset
def test_nearest_neighbor_grid_area(self): from pyresample import utils, geometry proj_str = "+proj=lcc +datum=WGS84 +ellps=WGS84 +lat_0=25 +lat_1=25 +lon_0=-95 +units=m +no_defs" proj_dict = pyresample.utils._proj4.proj4_str_to_dict(proj_str) extents = [0, 0, 1000. * 2500., 1000. * 2000.] area_def = geometry.AreaDefinition('CONUS', 'CONUS', 'CONUS', proj_dict, 40, 50, extents) lon_arr = create_test_longitude(-100.0, -60.0, (550, 500), dtype=np.float64) lat_arr = create_test_latitude(20.0, 45.0, (550, 500), dtype=np.float64) grid = geometry.GridDefinition(lons=lon_arr, lats=lat_arr) rows, cols = utils.generate_nearest_neighbour_linesample_arrays(grid, area_def, 12000.)
def test_nearest_neighbor_area_area(self): from pyresample import utils, geometry proj_str = "+proj=lcc +datum=WGS84 +ellps=WGS84 +lat_0=25 +lat_1=25 +lon_0=-95 +units=m +no_defs" proj_dict = pyresample.utils._proj4.proj4_str_to_dict(proj_str) extents = [0, 0, 1000. * 5000, 1000. * 5000] area_def = geometry.AreaDefinition('CONUS', 'CONUS', 'CONUS', proj_dict, 400, 500, extents) extents2 = [-1000, -1000, 1000. * 4000, 1000. * 4000] area_def2 = geometry.AreaDefinition('CONUS', 'CONUS', 'CONUS', proj_dict, 600, 700, extents2) rows, cols = utils.generate_nearest_neighbour_linesample_arrays(area_def, area_def2, 12000.)
def test_nearest_neighbor_area_grid(self): from pyresample import utils, geometry lon_arr = create_test_longitude(-94.9, -90.0, (50, 100), dtype=np.float64) lat_arr = create_test_latitude(25.1, 30.0, (50, 100), dtype=np.float64) grid = geometry.GridDefinition(lons=lon_arr, lats=lat_arr) proj_str = "+proj=lcc +datum=WGS84 +ellps=WGS84 +lat_0=25 +lat_1=25 +lon_0=-95 +units=m +no_defs" proj_dict = utils.proj4.proj4_str_to_dict(proj_str) extents = [0, 0, 1000. * 5000, 1000. * 5000] area_def = geometry.AreaDefinition('CONUS', 'CONUS', 'CONUS', proj_dict, 400, 500, extents) rows, cols = utils.generate_nearest_neighbour_linesample_arrays(area_def, grid, 12000.)
def test_nearest_neighbor_grid_area(self): from pyresample import utils, geometry proj_str = "+proj=lcc +datum=WGS84 +ellps=WGS84 +lat_0=25 +lat_1=25 +lon_0=-95 +units=m +no_defs" proj_dict = utils._proj4.proj4_str_to_dict(proj_str) extents = [0, 0, 1000. * 2500., 1000. * 2000.] area_def = geometry.AreaDefinition('CONUS', 'CONUS', 'CONUS', proj_dict, 40, 50, extents) lon_arr = create_test_longitude(-100.0, -60.0, (550, 500), dtype=np.float64) lat_arr = create_test_latitude(20.0, 45.0, (550, 500), dtype=np.float64) grid = geometry.GridDefinition(lons=lon_arr, lats=lat_arr) rows, cols = utils.generate_nearest_neighbour_linesample_arrays(grid, area_def, 12000.)
def test_nearest_neighbor_area_area(self): from pyresample import utils, geometry proj_str = "+proj=lcc +datum=WGS84 +ellps=WGS84 +lat_0=25 +lat_1=25 +lon_0=-95 +units=m +no_defs" proj_dict = utils._proj4.proj4_str_to_dict(proj_str) extents = [0, 0, 1000. * 5000, 1000. * 5000] area_def = geometry.AreaDefinition('CONUS', 'CONUS', 'CONUS', proj_dict, 400, 500, extents) extents2 = [-1000, -1000, 1000. * 4000, 1000. * 4000] area_def2 = geometry.AreaDefinition('CONUS', 'CONUS', 'CONUS', proj_dict, 600, 700, extents2) rows, cols = utils.generate_nearest_neighbour_linesample_arrays(area_def, area_def2, 12000.)
def test_nearest_neighbour_multi_preproc(self): data1 = numpy.fromfunction(lambda y, x: y*x*10**-6, (3712, 3712)) data2 = numpy.fromfunction(lambda y, x: y*x*10**-6, (3712, 3712)) * 2 data = numpy.dstack((data1, data2)) msg_con = image.ImageContainer(data, self.msg_area) #area_con = msg_con.resample_area_nearest_neighbour(self.area_def, 50000) row_indices, col_indices = \ utils.generate_nearest_neighbour_linesample_arrays(self.msg_area, self.area_def, 50000) res = msg_con.get_array_from_linesample(row_indices, col_indices) cross_sum1 = res[:, :, 0].sum() expected1 = 399936.783062 self.assertAlmostEqual(cross_sum1, expected1, msg='ImageContainer resampling nearest neighbour multi preproc failed') cross_sum2 = res[:, :, 1].sum() expected2 = 399936.783062 * 2 self.assertAlmostEqual(cross_sum2, expected2, msg='ImageContainer resampling nearest neighbour multi preproc failed')
def test_nearest_neighbour_multi_preproc(self): data1 = numpy.fromfunction(lambda y, x: y * x * 10 ** -6, (3712, 3712)) data2 = numpy.fromfunction( lambda y, x: y * x * 10 ** -6, (3712, 3712)) * 2 data = numpy.dstack((data1, data2)) msg_con = image.ImageContainer(data, self.msg_area) #area_con = msg_con.resample_area_nearest_neighbour(self.area_def, 50000) row_indices, col_indices = \ utils.generate_nearest_neighbour_linesample_arrays(self.msg_area, self.area_def, 50000) res = msg_con.get_array_from_linesample(row_indices, col_indices) cross_sum1 = res[:, :, 0].sum() expected1 = 399936.783062 self.assertAlmostEqual(cross_sum1, expected1, msg='ImageContainer resampling nearest neighbour multi preproc failed') cross_sum2 = res[:, :, 1].sum() expected2 = 399936.783062 * 2 self.assertAlmostEqual(cross_sum2, expected2, msg='ImageContainer resampling nearest neighbour multi preproc failed')
def readE_P(): x_size = 251 y_size = 251 description = 'Arctic EASE grid' proj_id = 'ease_nh' from pyresample import geometry, utils, image area_id = 'ease_nh' area_extent = (-7326849.0625,-7326849.0625,7326849.0625,7326849.0625) proj_dict = {'a': '6371228.0', 'units': 'm', 'lon_0': '0', \ 'proj': 'laea', 'lat_0': '90'} area_def = geometry.AreaDefinition(area_id, description, proj_id, \ proj_dict, x_size, y_size, area_extent) e_p=np.zeros((20,241,480),float) nc=Dataset('evap_precip201411.nc','r') t=nc.variables['time'][:][20*4+2:30*4+2] t0=nc.variables['time'][:][0:1] e=nc.variables['e'][21*4+2:31*4+2,::-1,:] p=nc.variables['tp'][21*4+2:31*4+2,::-1,:] for i in range(1,e.shape[0],2): e[i,:,:]=e[i,:,:]-e[i-1,:,:] p[i,:,:]=p[i,:,:]-p[i-1,:,:] print datetime.datetime(1900,1,1)+datetime.timedelta(hours=int(t[0])) print datetime.datetime(1900,1,1)+datetime.timedelta(hours=int(t0[0])) print datetime.datetime(1900,1,1)+datetime.timedelta(hours=int(t[-1])) e_p=(e+p) lon,lat=np.meshgrid(0+np.arange(480)*0.75,-90+np.arange(241)*0.75) lon[lon>180]-=360. grid_def = geometry.GridDefinition(lons=lon, lats=lat) row_indices, \ col_indices = \ utils.generate_nearest_neighbour_linesample_arrays(grid_def, area_def, 200000) msg_con = image.ImageContainer(e_p.sum(axis=0), grid_def) e_p_grid = msg_con.get_array_from_linesample(row_indices, col_indices) return e_p_grid
proj_id = 'ease_nh' from pyresample import geometry, utils, image area_id = 'ease_nh' area_extent = (-7326849.0625, -7326849.0625, 7326849.0625, 7326849.0625) proj_dict = {'a': '6371228.0', 'units': 'm', 'lon_0': '0', \ 'proj': 'laea', 'lat_0': '90'} area_def = geometry.AreaDefinition(area_id, description, proj_id, \ proj_dict, x_size, y_size, area_extent) import numpy as np lon, lat = np.meshgrid(-180 + 0.75 / 2 + np.arange(480) * 0.75, -90 + np.arange(241) * 0.75) grid_def = geometry.GridDefinition(lons=lon, lats=lat) row_indices, \ col_indices = \ utils.generate_nearest_neighbour_linesample_arrays(grid_def, area_def, 200000) msg_con = image.ImageContainer(e_p.sum(axis=0), grid_def) e_p_grid = msg_con.get_array_from_linesample(row_indices, col_indices) import matplotlib.pyplot as plt import matplotlib matplotlib.rcParams.update({'font.size': 13}) m = Basemap(projection='npstere', boundinglat=20, lon_0=0, resolution='l') plt.suptitle('Moisture Transport from Lagrangian Analysis', fontsize=14) plt.subplot(111) m.drawcoastlines() m.drawparallels(np.arange(-80., 81., 20.), labels=[True, False, False, False]) m.drawmeridians(np.arange(-180., 181., 20.), labels=[False, False, True, True])
def window(self, lat_min, lon_min, lat_max, lon_max): """Function to window, ie select a specific region, given the lower left latitude and longitude and the upper right latitude and longitude Parameters ---------- lat_min : float lower left latitude . lon_min : float lower left longitude. lat_max : float upper right latitude. lon_max : float upper right longitude. Returns ------- xr.DataSet returns the windowed object. """ try: from pyresample import utils from .util.interp_util import nearest_point_swathdefinition as npsd from .util.interp_util import lonlat_to_swathdefinition as llsd from numpy import concatenate has_pyresample = True except ImportError: has_pyresample = False try: if has_pyresample: lons, lats = utils.check_and_wrap(self.obj.longitude.values, self.obj.latitude.values) swath = llsd(longitude=lons, latitude=lats) pswath_ll = npsd(longitude=float(lon_min), latitude=float(lat_min)) pswath_ur = npsd(longitude=float(lon_max), latitude=float(lat_max)) row, col = utils.generate_nearest_neighbour_linesample_arrays( swath, pswath_ll, float(1e6)) y_ll, x_ll = row[0][0], col[0][0] row, col = utils.generate_nearest_neighbour_linesample_arrays( swath, pswath_ur, float(1e6)) y_ur, x_ur = row[0][0], col[0][0] if x_ur < x_ll: x1 = self.obj.x.where(self.obj.x >= x_ll, drop=True).values x2 = self.obj.x.where(self.obj.x <= x_ur, drop=True).values xrange = concatenate([x1, x2]).astype(int) self.obj['longitude'][:] = utils.wrap_longitudes( self.obj.longitude.values) # xrange = arange(float(x_ur), float(x_ll), dtype=int) else: xrange = slice(x_ll, x_ur) if y_ur < y_ll: y1 = self.obj.y.where(self.obj.y >= y_ll, drop=True).values y2 = self.obj.y.where(self.obj.y <= y_ur, drop=True).values yrange = concatenate([y1, y2]).astype(int) else: yrange = slice(y_ll, y_ur) return self.obj.sel(x=xrange, y=yrange) else: raise ImportError except ImportError: print('Window functionality is unavailable without pyresample')
def nearest_latlon(self, lat=None, lon=None, cleanup=True, esmf=False, **kwargs): """Uses xesmf to intepolate to a given latitude and longitude. Note that the conservative method is not available. Parameters ---------- lat : type Description of parameter `lat`. lon : type Description of parameter `lon`. **kwargs : type Description of parameter `**kwargs`. Returns ------- type Description of returned object. """ try: from pyresample import geometry, utils from .util.resample import resample_dataset from .util.interp_util import nearest_point_swathdefinition as npsd from .util.interp_util import lonlat_to_swathdefinition as llsd has_pyresample = True except ImportError: has_pyresample = False if esmf: has_pyresample = False from .util.interp_util import lonlat_to_xesmf from .util.resample import resample_xesmf try: if lat is None or lon is None: raise RuntimeError except RuntimeError: print('Must provide latitude and longitude') if has_pyresample: lons, lats = utils.check_and_wrap(self.obj.longitude.values, self.obj.latitude.values) swath = llsd(longitude=lons, latitude=lats) pswath = npsd(longitude=float(lon), latitude=float(lat)) row, col = utils.generate_nearest_neighbour_linesample_arrays( swath, pswath, float(1e6)) y, x = row[0][0], col[0][0] return self.obj.sel(x=x, y=y) else: kwargs = self._check_kwargs_and_set_defaults(**kwargs) self.obj = rename_latlon(self.obj) target = lonlat_to_xesmf(longitude=lon, latitude=lat) output = resample_xesmf(self.obj, target, **kwargs) if cleanup: output = resample_xesmf(self.obj, target, cleanup=True, **kwargs) return rename_latlon(output.squeeze())