def test_bounds_to_vertices(): # 1D case ds = airds.cf.add_bounds(["lon", "lat", "time"]) lat_c = cfxr.bounds_to_vertices(ds.lat_bounds, bounds_dim="bounds") assert_array_equal(ds.lat.values + 1.25, lat_c.values[:-1]) # 2D case, CF- order lat_c = cfxr.bounds_to_vertices(mollwds.lat_bounds, bounds_dim="bounds") assert_equal(mollwds.lat_vertices, lat_c) # Transposing the array changes the bounds direction ds = mollwds.transpose("bounds", "y", "x", "y_vertices", "x_vertices") lon_c = cfxr.bounds_to_vertices(ds.lon_bounds, bounds_dim="bounds", order="clockwise") lon_c2 = cfxr.bounds_to_vertices(ds.lon_bounds, bounds_dim="bounds", order=None) assert_equal(ds.lon_vertices, lon_c) assert_equal(ds.lon_vertices, lon_c2) # Preserves dask-backed arrays if DaskArray is not None: lon_bounds = ds.lon_bounds.chunk() lon_c = cfxr.bounds_to_vertices(lon_bounds, bounds_dim="bounds", order="clockwise") assert isinstance(lon_c.data, DaskArray)
def _get_lon_lat_bounds(ds): """Return bounds of lon and lat extracted from ds.""" if 'lat_b' in ds and 'lon_b' in ds: # Old way. return ds['lon_b'], ds['lat_b'] # else : cf-xarray way try: lon_bnds = ds.cf.get_bounds('longitude') lat_bnds = ds.cf.get_bounds('latitude') except KeyError: # bounds are not already present if ds.cf['longitude'].ndim > 1: # We cannot infer 2D bounds, raise KeyError as custom "lon_b" is missing. raise KeyError('lon_b') lon_name = ds.cf['longitude'].name lat_name = ds.cf['latitude'].name ds = ds.cf.add_bounds([lon_name, lat_name]) lon_bnds = ds.cf.get_bounds('longitude') lat_bnds = ds.cf.get_bounds('latitude') # Convert from CF bounds to xESMF bounds. # order=None is because we don't want to assume the dimension order for 2D bounds. lon_b = cfxr.bounds_to_vertices(lon_bnds, ds.cf.get_bounds_dim_name('longitude'), order=None) lat_b = cfxr.bounds_to_vertices(lat_bnds, ds.cf.get_bounds_dim_name('latitude'), order=None) return lon_b, lat_b
def test_vertices_to_bounds(): # 1D case ds = airds.cf.add_bounds(["lon", "lat", "time"]) lat_c = cfxr.bounds_to_vertices(ds.lat_bounds, bounds_dim="bounds") lat_b = cfxr.vertices_to_bounds(lat_c, out_dims=("bounds", "lat")) assert_array_equal(ds.lat_bounds, lat_b) # Datetime time_c = cfxr.bounds_to_vertices(ds.time_bounds, bounds_dim="bounds") time_b = cfxr.vertices_to_bounds(time_c, out_dims=("bounds", "time")) assert_array_equal(ds.time_bounds, time_b) # 2D case lon_b = cfxr.vertices_to_bounds(mollwds.lon_vertices, out_dims=("bounds", "x", "y")) assert_array_equal(mollwds.lon_bounds, lon_b)