예제 #1
0
 def grid_mapping(self):
     """
     str: The CF grid_mapping attribute. 'spatial_ref' is the default.
     """
     try:
         return self._obj.attrs["grid_mapping"]
     except KeyError:
         pass
     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:
             try:
                 # pylint: disable=pointless-statement
                 self._obj[var].rio.x_dim
                 self._obj[var].rio.y_dim
             except DimensionError:
                 continue
             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
예제 #2
0
 def crs(self):
     """:obj:`rasterio.crs.CRS`:
     Retrieve projection from `xarray.Dataset`
     """
     if self._crs is not None:
         return None if self._crs is False else self._crs
     self._crs = super().crs
     if self._crs is not None:
         return self._crs
     # ensure all the CRS of the variables are the same
     crs_list = []
     for var in self.vars:
         if self._obj[var].rio.crs is not None:
             crs_list.append(self._obj[var].rio.crs)
     try:
         crs = crs_list[0]
     except IndexError:
         crs = None
     if crs is None:
         self._crs = False
         return None
     if all(crs_i == crs for crs_i in crs_list):
         self._crs = crs
     else:
         raise RioXarrayError(
             f"CRS in DataArrays differ in the Dataset: {crs_list}")
     return self._crs
예제 #3
0
 def grid_mapping(self):
     """
     str: The CF grid_mapping attribute. 'spatial_ref' is the default.
     """
     grid_mapping = self._obj.encoding.get(
         "grid_mapping", self._obj.attrs.get("grid_mapping")
     )
     if grid_mapping is not None:
         return grid_mapping
     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 not _has_spatial_dims(self._obj, var):
                 continue
             var_grid_mapping = self._obj[var].encoding.get(
                 "grid_mapping", self._obj[var].attrs.get("grid_mapping")
             )
             if var_grid_mapping is not None:
                 grid_mapping = var_grid_mapping
                 grid_mappings.add(grid_mapping)
         if len(grid_mappings) > 1:
             raise RioXarrayError("Multiple grid mappings exist.")
     return grid_mapping
예제 #4
0
    def _get_indexer(self, key):
        """Get indexer for rasterio array.

        Parameter
        ---------
        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 = []
        for i, (k, n) in enumerate(zip(key[1:], self.shape[1:])):
            if isinstance(k, slice):
                # step is always positive. see indexing.decompose_indexer
                start, stop, step = k.indices(n)
                np_inds.append(slice(None, None, step))
            elif is_scalar(k):
                # windowed operations will always return an array
                # we will have to squeeze it later
                squeeze_axis.append(-(2 - i))
                start = k
                stop = k + 1
            else:
                start, stop = np.min(k), np.max(k) + 1
                np_inds.append(k - start)
            window.append((start, stop))

        if isinstance(key[1], np.ndarray) and isinstance(key[2], np.ndarray):
            # do outer-style indexing
            np_inds[-2:] = np.ix_(*np_inds[-2:])

        return band_key, tuple(window), tuple(squeeze_axis), tuple(np_inds)
예제 #5
0
def _write_metatata_to_raster(raster_handle, xarray_dataset, tags):
    """
    Write the metadata stored in the xarray object to raster metadata
    """
    tags = xarray_dataset.attrs if tags is None else {**xarray_dataset.attrs, **tags}

    # write scales and offsets
    try:
        raster_handle.scales = tags["scales"]
    except KeyError:
        scale_factor = tags.get(
            "scale_factor", xarray_dataset.encoding.get("scale_factor")
        )
        if scale_factor is not None:
            raster_handle.scales = (scale_factor,) * raster_handle.count
    try:
        raster_handle.offsets = tags["offsets"]
    except KeyError:
        add_offset = tags.get("add_offset", xarray_dataset.encoding.get("add_offset"))
        if add_offset is not None:
            raster_handle.offsets = (add_offset,) * raster_handle.count

    # filter out attributes that should be written in a different location
    skip_tags = (
        UNWANTED_RIO_ATTRS
        + FILL_VALUE_NAMES
        + (
            "transform",
            "scales",
            "scale_factor",
            "add_offset",
            "offsets",
            "grid_mapping",
        )
    )
    # 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)
예제 #6
0
    def interpolate_na(self, method="nearest"):
        """
        This method uses scipy.interpolate.griddata to interpolate missing data.

        .. warning:: scipy is an optional dependency.

        Parameters
        ----------
        method: {‘linear’, ‘nearest’, ‘cubic’}, optional
            The method to use for interpolation in `scipy.interpolate.griddata`.

        Returns
        -------
        :obj:`xarray.DataArray`:
            An interpolated :obj:`xarray.DataArray` object.
        """
        if self.nodata is None:
            raise RioXarrayError(
                "nodata not found. Please set the nodata with 'rio.write_nodata()'."
                f"{_get_data_var_message(self._obj)}")

        extra_dim = self._check_dimensions()
        if extra_dim:
            interp_data = []
            for _, sub_xds in self._obj.groupby(extra_dim):
                interp_data.append(
                    self._interpolate_na(sub_xds.load().data, method=method))
            interp_data = np.array(interp_data)
        else:
            interp_data = self._interpolate_na(self._obj.load().data,
                                               method=method)

        interp_array = xarray.DataArray(
            name=self._obj.name,
            data=interp_data,
            coords=self._obj.coords,
            dims=self._obj.dims,
            attrs=self._obj.attrs,
        )
        interp_array.encoding = self._obj.encoding

        # make sure correct attributes preserved & projection added
        _add_attrs_proj(interp_array, self._obj)

        return interp_array
예제 #7
0
    def to_raster(
        self,
        raster_path,
        driver=None,
        dtype=None,
        tags=None,
        windowed=False,
        recalc_transform=True,
        lock=None,
        compute=True,
        **profile_kwargs,
    ):
        """
        Export the Dataset to a raster file. Only works with 2D data.

        ..versionadded:: 0.2 lock

        Parameters
        ----------
        raster_path: str
            The path to output the raster to.
        driver: str, optional
            The name of the GDAL/rasterio driver to use to export the raster.
            Default is "GTiff" if rasterio < 1.2 otherwise it will autodetect.
        dtype: str, optional
            The data type to write the raster to. Default is the datasets dtype.
        tags: dict, optional
            A dictionary of tags to write to the raster.
        windowed: bool, optional
            If True, it will write using the windows of the output raster.
            This is useful for loading data in chunks when writing. Does not
            do anything when writing with dask.
            Default is False.
        lock: boolean or Lock, optional
            Lock to use to write data using dask.
            If not supplied, it will use a single process for writing.
        compute: bool, optional
            If True and data is a dask array, then compute and save
            the data immediately. If False, return a dask Delayed object.
            Call ".compute()" on the Delayed object to compute the result
            later. Call ``dask.compute(delayed1, delayed2)`` to save
            multiple delayed files at once. Default is True.
        **profile_kwargs
            Additional keyword arguments to pass into writing the raster. The
            nodata, transform, crs, count, width, and height attributes
            are ignored.

        Returns
        -------
        :obj:`dask.Delayed`:
            If the data array is a dask array and compute
            is True. Otherwise None is returned.

        """
        variable_dim = f"band_{uuid4()}"
        data_array = self._obj.to_array(dim=variable_dim)
        # write data array names to raster
        data_array.attrs["long_name"] = data_array[variable_dim].values.tolist(
        )
        # ensure raster metadata preserved
        scales = []
        offsets = []
        nodatavals = []
        for data_var in data_array[variable_dim].values:
            scales.append(self._obj[data_var].attrs.get("scale_factor", 1.0))
            offsets.append(self._obj[data_var].attrs.get("add_offset", 0.0))
            nodatavals.append(self._obj[data_var].rio.nodata)
        data_array.attrs["scales"] = scales
        data_array.attrs["offsets"] = offsets
        nodata = nodatavals[0]
        if (all(nodataval == nodata for nodataval in nodatavals)
                or np.isnan(nodatavals).all()):
            data_array.rio.write_nodata(nodata, inplace=True)
        else:
            raise RioXarrayError(
                "All nodata values must be the same when exporting to raster. "
                f"Current values: {nodatavals}")
        if self.crs is not None:
            data_array.rio.write_crs(self.crs, inplace=True)
        # write it to a raster
        return data_array.rio.set_spatial_dims(
            x_dim=self.x_dim,
            y_dim=self.y_dim,
            inplace=True,
        ).rio.to_raster(
            raster_path=raster_path,
            driver=driver,
            dtype=dtype,
            tags=tags,
            windowed=windowed,
            recalc_transform=recalc_transform,
            lock=lock,
            compute=compute,
            **profile_kwargs,
        )
예제 #8
0
    def reproject(
        self,
        dst_crs,
        resolution=None,
        shape=None,
        transform=None,
        resampling=Resampling.nearest,
    ):
        """
        Reproject :obj:`xarray.DataArray` objects

        Powered by `rasterio.warp.reproject`

        .. note:: Only 2D/3D arrays with dimensions 'x'/'y' are currently supported.
            Requires either a grid mapping variable with 'spatial_ref' or
            a 'crs' attribute to be set containing a valid CRS.
            If using a WKT (e.g. from spatiareference.org), make sure it is an OGC WKT.

        .. versionadded:: 0.0.27 shape
        .. versionadded:: 0.0.28 transform

        Parameters
        ----------
        dst_crs: str
            OGC WKT string or Proj.4 string.
        resolution: float or tuple(float, float), optional
            Size of a destination pixel in destination projection units
            (e.g. degrees or metres).
        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 'rio.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

        extra_dim = self._check_dimensions()
        if extra_dim:
            dst_data = np.zeros(
                (self._obj[extra_dim].size, dst_height, dst_width),
                dtype=self._obj.dtype.type,
            )
        else:
            dst_data = np.zeros((dst_height, dst_width),
                                dtype=self._obj.dtype.type)

        dst_nodata = self._obj.dtype.type(
            self.nodata if self.nodata is not None else -9999)
        src_nodata = self._obj.dtype.type(
            self.nodata if self.nodata is not None else dst_nodata)
        rasterio.warp.reproject(
            source=self._obj.values,
            destination=dst_data,
            src_transform=src_affine,
            src_crs=self.crs,
            src_nodata=src_nodata,
            dst_transform=dst_affine,
            dst_crs=dst_crs,
            dst_nodata=dst_nodata,
            resampling=resampling,
        )
        # add necessary attributes
        new_attrs = _generate_attrs(self._obj, dst_nodata)
        # make sure dimensions with coordinates renamed to x,y
        dst_dims = []
        for dim in self._obj.dims:
            if dim == self.x_dim:
                dst_dims.append("x")
            elif dim == self.y_dim:
                dst_dims.append("y")
            else:
                dst_dims.append(dim)
        xda = xarray.DataArray(
            name=self._obj.name,
            data=dst_data,
            coords=_make_coords(self._obj, dst_affine, dst_width, dst_height),
            dims=tuple(dst_dims),
            attrs=new_attrs,
        )
        xda.encoding = self._obj.encoding
        xda.rio.write_transform(dst_affine, inplace=True)
        xda.rio.write_crs(dst_crs, inplace=True)
        xda.rio.write_coordinate_system(inplace=True)
        return xda
예제 #9
0
    def reproject(
        self,
        dst_crs,
        resolution=None,
        shape=None,
        transform=None,
        resampling=Resampling.nearest,
        nodata=None,
        **kwargs,
    ):
        """
        Reproject :obj:`xarray.DataArray` objects

        Powered by :func:`rasterio.warp.reproject`

        .. note:: Only 2D/3D arrays with dimensions 'x'/'y' are currently supported.
            Requires either a grid mapping variable with 'spatial_ref' or
            a 'crs' attribute to be set containing a valid CRS.
            If using a WKT (e.g. from spatiareference.org), make sure it is an OGC WKT.

        .. versionadded:: 0.0.27 shape
        .. versionadded:: 0.0.28 transform
        .. versionadded:: 0.5.0 nodata, kwargs

        Parameters
        ----------
        dst_crs: str
            OGC WKT string or Proj.4 string.
        resolution: float or tuple(float, float), optional
            Size of a destination pixel in destination projection units
            (e.g. degrees or metres).
        shape: tuple(int, int), optional
            Shape of the destination in pixels (dst_height, dst_width). Cannot be used
            together with resolution.
        transform: Affine, optional
            The destination transform.
        resampling: rasterio.enums.Resampling, optional
            See :func:`rasterio.warp.reproject` for more details.
        nodata: float, optional
            The nodata value used to initialize the destination;
            it will remain in all areas not covered by the reprojected source.
            Defaults to the nodata value of the source image if none provided
            and exists or attempts to find an appropriate value by dtype.
        **kwargs: dict
            Additional keyword arguments to pass into :func:`rasterio.warp.reproject`.
            To override:
            - src_transform: `rio.write_transform`
            - src_crs: `rio.write_crs`
            - src_nodata: `rio.write_nodata`


        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 'rio.write_crs()'."
                f"{_get_data_var_message(self._obj)}")
        gcps = self.get_gcps()
        if gcps:
            kwargs.setdefault("gcps", gcps)

        src_affine = None if "gcps" in kwargs else 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, **kwargs)
        else:
            dst_affine = transform
            if shape is not None:
                dst_height, dst_width = shape
            else:
                dst_height, dst_width = self.shape

        dst_data = self._create_dst_data(dst_height, dst_width)

        dst_nodata = self._get_dst_nodata(nodata)

        rasterio.warp.reproject(
            source=self._obj.values,
            destination=dst_data,
            src_transform=src_affine,
            src_crs=self.crs,
            src_nodata=self.nodata,
            dst_transform=dst_affine,
            dst_crs=dst_crs,
            dst_nodata=dst_nodata,
            resampling=resampling,
            **kwargs,
        )
        # add necessary attributes
        new_attrs = _generate_attrs(self._obj, dst_nodata)
        # make sure dimensions with coordinates renamed to x,y
        dst_dims = []
        for dim in self._obj.dims:
            if dim == self.x_dim:
                dst_dims.append("x")
            elif dim == self.y_dim:
                dst_dims.append("y")
            else:
                dst_dims.append(dim)
        xda = xarray.DataArray(
            name=self._obj.name,
            data=dst_data,
            coords=_make_coords(self._obj, dst_affine, dst_width, dst_height),
            dims=tuple(dst_dims),
            attrs=new_attrs,
        )
        xda.encoding = self._obj.encoding
        xda.rio.write_transform(dst_affine, inplace=True)
        xda.rio.write_crs(dst_crs, inplace=True)
        xda.rio.write_coordinate_system(inplace=True)
        return xda