Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_reproject_resolution_and_shape_transform():
test_da = xarray.DataArray(
numpy.zeros((5, 5)),
dims=("y", "x"),
coords={"y": numpy.arange(1, 6), "x": numpy.arange(2, 7)},
attrs={"crs": "epsg:3857"},
)
affine = Affine.from_gdal(0, 0.005, 0, 0, 0, 0.005)
with pytest.raises(RioXarrayError):
test_da.rio.reproject(4326, resolution=1, shape=(1, 1))
with pytest.raises(RioXarrayError):
test_da.rio.reproject(4326, resolution=1, transform=affine)
with pytest.raises(RioXarrayError):
test_da.rio.reproject(4326, resolution=1, shape=(1, 1), transform=affine)
def test_to_raster__custom_description__wrong(tmpdir):
tmp_raster = tmpdir.join("planet_3d_raster.tif")
with xarray.open_dataset(
os.path.join(TEST_INPUT_DATA_DIR, "PLANET_SCOPE_3D.nc")
) as mda:
xds = mda.green.fillna(mda.green.rio.encoded_nodata)
xds.attrs["long_name"] = ("one", "two", "three")
with pytest.raises(RioXarrayError):
xds.rio.to_raster(str(tmp_raster))
grid_mapping = DEFAULT_GRID_MAP
# search the dataset for the grid mapping name
if hasattr(self._obj, "data_vars"):
grid_mappings = set()
for var in self._obj.data_vars:
if (
self.x_dim in self._obj[var].dims
and self.y_dim in self._obj[var].dims
):
try:
grid_mapping = self._obj[var].attrs["grid_mapping"]
grid_mappings.add(grid_mapping)
except KeyError:
pass
if len(grid_mappings) > 1:
raise RioXarrayError("Multiple grid mappings exist.")
return grid_mapping
---------
key: tuple of int
Returns
-------
band_key: an indexer for the 1st dimension
window: two tuples. Each consists of (start, stop).
squeeze_axis: axes to be squeezed
np_ind: indexer for loaded numpy array
See also
--------
indexing.decompose_indexer
"""
if len(key) != 3:
raise RioXarrayError("rasterio datasets should always be 3D")
# bands cannot be windowed but they can be listed
band_key = key[0]
np_inds = []
# bands (axis=0) cannot be windowed but they can be listed
if isinstance(band_key, slice):
start, stop, step = band_key.indices(self.shape[0])
band_key = np.arange(start, stop, step)
# be sure we give out a list
band_key = (np.asarray(band_key) + 1).tolist()
if isinstance(band_key, list): # if band_key is not a scalar
np_inds.append(slice(None))
# but other dims can only be windowed
window = []
squeeze_axis = []
# -*- coding: utf-8 -*-
"""
This contains exceptions for rioxarray.
"""
class RioXarrayError(RuntimeError):
"""This is the base exception for errors in the rioxarray extension."""
class NoDataInBounds(RioXarrayError):
"""This is for when there are no data in the bounds for clipping a raster."""
class SingleVariableDataset(RioXarrayError):
"""This is for when you have a dataset with a single variable."""
class DimensionError(RioXarrayError):
"""This is raised when there are more dimensions than is supported by the method"""
class TooManyDimensions(DimensionError):
"""This is raised when there are more dimensions than is supported by the method"""
class InvalidDimensionOrder(DimensionError):
"""This is raised when there are more dimensions than is supported by the method"""
class TooManyDimensions(DimensionError):
"""This is raised when there are more dimensions than is supported by the method"""
class InvalidDimensionOrder(DimensionError):
"""This is raised when there the dimensions are not ordered correctly."""
class OneDimensionalRaster(DimensionError):
"""This is an error when you have a 1 dimensional raster."""
class DimensionMissingCoordinateError(RioXarrayError):
"""This is raised when the dimension does not have the supporting coordinate."""
class MissingCRS(RioXarrayError):
"""Missing the CRS in the dataset."""
UNWANTED_RIO_ATTRS
+ FILL_VALUE_NAMES
+ ("transform", "scales", "scale_factor", "add_offset", "offsets")
)
# this is for when multiple values are used
# in this case, it will be stored in the raster description
if not isinstance(tags.get("long_name"), str):
skip_tags += ("long_name",)
tags = {key: value for key, value in tags.items() if key not in skip_tags}
raster_handle.update_tags(**tags)
# write band name information
long_name = xarray_dataset.attrs.get("long_name")
if isinstance(long_name, (tuple, list)):
if len(long_name) != raster_handle.count:
raise RioXarrayError(
"Number of names in the 'long_name' attribute does not equal "
"the number of bands."
)
for iii, band_description in enumerate(long_name):
raster_handle.set_band_description(iii + 1, band_description)
else:
band_description = long_name or xarray_dataset.name
if band_description:
for iii in range(raster_handle.count):
raster_handle.set_band_description(iii + 1, band_description)
shape: tuple(int, int), optional
Shape of the destination in pixels (dst_height, dst_width). Cannot be used
together with resolution.
transform: optional
The destination transform.
resampling: Resampling method, optional
See rasterio.warp.reproject for more details.
Returns
-------
:obj:`xarray.DataArray`:
The reprojected DataArray.
"""
if resolution is not None and (shape is not None or transform is not None):
raise RioXarrayError("resolution cannot be used with shape or transform.")
if self.crs is None:
raise MissingCRS(
"CRS not found. Please set the CRS with 'set_crs()' or 'write_crs()'."
f"{_get_data_var_message(self._obj)}"
)
src_affine = self.transform(recalc=True)
if transform is None:
dst_affine, dst_width, dst_height = _make_dst_affine(
self._obj, self.crs, dst_crs, resolution, shape
)
else:
dst_affine = transform
if shape is not None:
dst_height, dst_width = shape
else:
dst_height, dst_width = self.shape