def test_apply_invalid_input(): def func(x): return 0 # invalid dims (must be 2d) zones = xa.DataArray(np.array([1, 2, 0])) values = xa.DataArray(np.array([[[1, 2, 0.5]]])) with pytest.raises(Exception) as e_info: apply(zones, values, func) # invalid zones data dtype (must be int) zones = xa.DataArray(np.array([[1, 2, 0.5]])) values = xa.DataArray(np.array([[[1, 2, 0.5]]])) with pytest.raises(Exception) as e_info: apply(zones, values, func) # invalid values data dtype (must be int or float) values = xa.DataArray(np.array([['apples', 'foobar', 'cowboy']])) zones = xa.DataArray(np.array([[1, 2, 0]])) with pytest.raises(Exception) as e_info: apply(zones, values, func) # invalid values dim (must be 2d or 3d) values = xa.DataArray(np.array([1, 2, 0.5])) zones = xa.DataArray(np.array([[1, 2, 0]])) with pytest.raises(Exception) as e_info: apply(zones, values, func) zones = xa.DataArray(np.array([[1, 2, 0], [1, 2, 3]])) values = xa.DataArray(np.array([[1, 2, 0.5]])) # mis-match zones.shape and values.shape with pytest.raises(Exception) as e_info: # noqa apply(zones, values, func)
def test_apply(): def func(x): return 0 zones_val = np.zeros((3, 3), dtype=np.int) # define some zones zones_val[0, ...] = 1 zones_val[1, ...] = 2 zones = xa.DataArray(zones_val) values_val = np.array([[0, 1, 2], [3, 4, 5], [6, 7, np.nan]]) values = xa.DataArray(values_val) # add crs for tests values = _add_EPSG4326_crs_to_da(values) values_copy = values.copy() apply(zones, values, func) # agg.shape remains the same assert values.shape == values_copy.shape # crs tests assert values.attrs == values_copy.attrs for coord in values_copy.coords: assert np.all(values[coord] == values_copy[coord]) values_val = values.values # values within zones are all 0s assert (values_val[0] == [0, 0, 0]).all() assert (values_val[1] == [0, 0, 0]).all() # values outside zones remain assert (values_val[2, :2] == values_copy.values[2, :2]).all() # last element of the last row is nan assert np.isnan(values_val[2, 2])
def test_apply(): def func(x): return 0 zones_val = np.zeros((3, 3), dtype=int) # define some zones zones_val[1] = 1 zones_val[2] = 2 zones = xr.DataArray(zones_val) values_val = np.array([[0, 1, 2], [3, 4, 5], [6, 7, np.nan]]) values = xr.DataArray(values_val) values_copy = values.copy() apply(zones, values, func, nodata=2) # agg.shape remains the same assert values.shape == values_copy.shape values_val = values.values # values within zones are all 0s assert (values_val[0] == [0, 0, 0]).all() assert (values_val[1] == [0, 0, 0]).all() # values outside zones remain assert np.isclose(values_val[2], values_copy.values[2], equal_nan=True).all()