Exemple #1
0
def test_from_esri_wkt_no_fix(projection_string):
    """Test ESRI CRS morphing with no datum fixing"""
    with Env():
        crs = CRS.from_wkt(projection_string)
        assert 'DATUM["D_North_American_1983"' in crs.wkt
Exemple #2
0
def test_from_wkt():
    wgs84 = CRS.from_string('+proj=longlat +datum=WGS84 +no_defs')
    from_wkt = CRS.from_wkt(wgs84.wkt)
    assert wgs84.wkt == from_wkt.wkt
Exemple #3
0
def test_from_wkt_invalid():
    with Env(), pytest.raises(CRSError):
        CRS.from_wkt('trash')
def write_geotiff_from_xr(tif_path,
                          dataset,
                          bands=[],
                          no_data=-9999,
                          crs="EPSG:4326"):
    """Write a geotiff from an xarray dataset.

    Args:
        tif_path: path for the tif to be written to.
        dataset: xarray dataset
        bands: list of strings representing the bands in the order they should be written
        no_data: nodata value for the dataset
        crs: requested crs.
        Affine(a,b,c,d,e,f)
        a = width of a pixel
        b = row rotation (typically zero)
        c = x-coordinate of the upper-left corner of the upper-left pixel
        d = column rotation (typically zero)
        e = height of a pixel (typically negative)
        f = y-coordinate of the of the upper-left corner of the upper-left pixel

    """
    from rasterio.crs import CRS as CRS_rasterio
    bands = list(dataset.data_vars.keys())
    assert isinstance(bands, list), "Bands must a list of strings"
    assert len(bands) > 0 and isinstance(
        bands[0], str), "You must supply at least one band."

    logging.info('write_geotiff_from_xr: dataset {} - {}'.format(
        type(dataset), dataset))

    #print(dataset.crs)
    #if dataset.crs is not None:
    #    if isinstance(dataset.crs, xr.DataArray):
    #        print(type(dataset.crs))
    #        crs_dict = dataset.crs.to_dict()
    #        crs = CRS_rasterio.from_wkt(crs_dict['attrs']['crs_wkt'])
    #        print(crs_dict['attrs'])
    #        geobox = calculate_bounds_geotransform(dataset)
    #        bounds = BoundingBox(left=geobox['left'], bottom=geobox['bottom'], right=geobox['right'], top=geobox['top'])
    #    else:
    #        crs = dataset.crs.crs_str
    #else:
    #    print("no entra")
    #    transform = _get_transform_from_xr(dataset)

    #transform = _get_transform_from_xr(dataset)

    if isinstance(dataset.crs, xr.DataArray):
        crs_dict = dataset.crs.to_dict()
        crs = CRS_rasterio.from_wkt(crs_dict['attrs']['crs_wkt'])

    elif isinstance(dataset.crs, datacube.utils.geometry._base.CRS):
        crs = CRS_rasterio.from_string(dataset.crs.crs_str)
    else:
        raise Exception(
            'dataset.crs datatype not know (please check calculate_bounds_geotransform)'
        )

    geobox = calculate_bounds_geotransform(dataset)
    bounds = BoundingBox(left=geobox['left'],
                         bottom=geobox['bottom'],
                         right=geobox['right'],
                         top=geobox['top'])

    transform = _get_transform_from_xr(dataset)

    with rasterio.open(
            tif_path,
            'w',
            driver='GTiff',
            height=dataset.dims['latitude'],
            width=dataset.dims['longitude'],
            count=len(bands),
            dtype=dataset[bands[0]].dtype,  #str(dataset[bands[0]].dtype),
            crs=crs,
            transform=transform,
            bounds=bounds,
            nodata=no_data) as dst:
        for index, band in enumerate(bands):
            print(dataset[band].dtype)
            dst.write_band(
                index + 1,
                dataset[band].values.astype(dataset[bands[0]].dtype),
            )
            tag = {'Band_' + str(index + 1): bands[index]}
            dst.update_tags(**tag)
            dst.set_band_description(index + 1, band)
        dst.close()
Exemple #5
0
def _to_crs_osr(value):
    return CRS.from_wkt(value.ExportToWkt())
Exemple #6
0
def test_exception():
    """Get the exception we expect"""
    with pytest.raises(CRSError):
        CRS.from_wkt("bogus")
Exemple #7
0
def test_implicit_proj_dict(projection_string):
    """Ensure that old behavior is preserved"""
    assert CRS.from_wkt(projection_string)['proj'] == 'aea'
Exemple #8
0
def test_exception():
    """Get the exception we expect"""
    with pytest.raises(CRSError):
        CRS.from_wkt("bogus")
Exemple #9
0
def test_crs_private_wkt(projection_string):
    """Original WKT is saved"""
    CRS.from_wkt(projection_string)._wkt == projection_string
Exemple #10
0
def test_from_esri_wkt_fix_datum(projection_string):
    """Test ESRI CRS morphing with datum fixing"""
    with Env(GDAL_FIX_ESRI_WKT='DATUM'):
        crs = CRS.from_wkt(projection_string, morph_from_esri_dialect=True)
        assert 'DATUM["North_American_Datum_1983"' in crs.wkt
Exemple #11
0
def test_compound_crs():
    wkt = """COMPD_CS["unknown",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4326"]],VERT_CS["unknown",VERT_DATUM["unknown",2005],UNIT["metre",1.0,AUTHORITY["EPSG","9001"]],AXIS["Up",UP]]]"""
    assert CRS.from_wkt(wkt).wkt.startswith('COMPD_CS')
Exemple #12
0
def test_from_esri_wkt_no_fix(projection_string):
    """Test ESRI CRS morphing with no datum fixing"""
    with Env():
        crs = CRS.from_wkt(projection_string)
        assert 'DATUM["D_North_American_1983"' in crs.wkt
Exemple #13
0
def test_from_wkt_invalid():
    with Env(), pytest.raises(CRSError):
        CRS.from_wkt('trash')
Exemple #14
0
def test_from_wkt():
    wgs84 = CRS.from_string('+proj=longlat +datum=WGS84 +no_defs')
    from_wkt = CRS.from_wkt(wgs84.wkt)
    assert wgs84.wkt == from_wkt.wkt
Exemple #15
0
def test_from_esri_wkt_fix_datum(projection_string):
    """Test ESRI CRS morphing with datum fixing"""
    with Env(GDAL_FIX_ESRI_WKT='DATUM'):
        crs = CRS.from_wkt(projection_string, morph_from_esri_dialect=True)
        assert 'DATUM["North_American_Datum_1983"' in crs.wkt
Exemple #16
0
def test_implicit_proj_dict(projection_string):
    """Ensure that old behavior is preserved"""
    assert CRS.from_wkt(projection_string)['proj'] == 'aea'
Exemple #17
0
def test_compound_crs():
    wkt = """COMPD_CS["unknown",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4326"]],VERT_CS["unknown",VERT_DATUM["unknown",2005],UNIT["metre",1.0,AUTHORITY["EPSG","9001"]],AXIS["Up",UP]]]"""
    assert CRS.from_wkt(wkt).wkt.startswith('COMPD_CS')
Exemple #18
0
def test_issue1620():
    """Different forms of EPSG:3857 are equal"""
    assert CRS.from_wkt(
        'PROJCS["WGS 84 / Pseudo-Mercator",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Mercator_1SP"],PARAMETER["central_meridian",0],PARAMETER["scale_factor",1],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["X",EAST],AXIS["Y",NORTH],EXTENSION["PROJ4","+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs"],AUTHORITY["EPSG","3857"]]'
    ) == CRS.from_dict(init='epsg:3857')
Exemple #19
0
def test_crs_private_wkt(projection_string):
    """Original WKT is saved"""
    CRS.from_wkt(projection_string)._wkt == projection_string
Exemple #20
0
"""rio_tiler.main: raster processing."""

import mercantile
import morecantile
import rasterio
from rasterio.crs import CRS
from rasterio.warp import transform_bounds

from rio_tiler import utils
from rio_tiler.errors import TileOutsideBounds

dst_crs = CRS.from_wkt(
    'PROJCS["S-JTSK / Krovak East North",GEOGCS["S-JTSK",DATUM["System_Jednotne_Trigonometricke_Site_Katastralni",SPHEROID["Bessel 1841",6377397.155,299.1528128,AUTHORITY["EPSG","7004"]],TOWGS84[589,76,480,0,0,0,0],AUTHORITY["EPSG","6156"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4156"]],PROJECTION["Krovak"],PARAMETER["latitude_of_center",49.5],PARAMETER["longitude_of_center",24.83333333333333],PARAMETER["azimuth",30.28813972222222],PARAMETER["pseudo_standard_parallel_1",78.5],PARAMETER["scale_factor",0.9999],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["X",EAST],AXIS["Y",NORTH],AUTHORITY["EPSG","5514"]]'
)
extent = [-951499.37, -1276279.09, -159365.31, -983013.08]
EPSG5514_TMS = morecantile.TileMatrixSet.custom(extent,
                                                dst_crs,
                                                title="S-JTSK (EPSG:5514)")


def bounds(address):
    """
    Retrieve image bounds.

    Attributes
    ----------
    address : str
        file url.

    Returns
    -------
Exemple #21
0
def test_issue1620():
    """Different forms of EPSG:3857 are equal"""
    assert CRS.from_wkt('PROJCS["WGS 84 / Pseudo-Mercator",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Mercator_1SP"],PARAMETER["central_meridian",0],PARAMETER["scale_factor",1],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["X",EAST],AXIS["Y",NORTH],EXTENSION["PROJ4","+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs"],AUTHORITY["EPSG","3857"]]') == CRS.from_dict(init='epsg:3857')
    def clip(
        self,
        geometries,
        crs=None,
        all_touched=False,
        drop=True,
        invert=False,
        from_disk=False,
    ):
        """
        Crops a :obj:`xarray.DataArray` by geojson like geometry dicts.

        Powered by `rasterio.features.geometry_mask`.

        Examples:

            >>> geometry = ''' {"type": "Polygon",
            ...                 "coordinates": [
            ...                 [[-94.07955380199459, 41.69085871273774],
            ...                 [-94.06082436942204, 41.69103313774798],
            ...                 [-94.06063203899649, 41.67932439500822],
            ...                 [-94.07935807746362, 41.679150041277325],
            ...                 [-94.07955380199459, 41.69085871273774]]]}'''
            >>> cropping_geometries = [geojson.loads(geometry)]
            >>> xds = xarray.open_rasterio('cool_raster.tif')
            >>> cropped = xds.rio.clip(geometries=cropping_geometries, crs=4326)


        .. versionadded:: 0.2 from_disk

        Parameters
        ----------
        geometries: list
            A list of geojson geometry dicts or objects with __geom_interface__ with
            if you have rasterio 1.2+.
        crs: :obj:`rasterio.crs.CRS`, optional
            The CRS of the input geometries. Default is to assume it is the same
            as the dataset.
        all_touched : bool, optional
            If True, all pixels touched by geometries will be burned in.  If
            false, only pixels whose center is within the polygon or that
            are selected by Bresenham's line algorithm will be burned in.
        drop: bool, optional
            If True, drop the data outside of the extent of the mask geoemtries
            Otherwise, it will return the same raster with the data masked.
            Default is True.
        invert: boolean, optional
            If False, pixels that do not overlap shapes will be set as nodata.
            Otherwise, pixels that overlap the shapes will be set as nodata.
            False by default.
        from_disk: boolean, optional
            If True, it will clip from disk using rasterio.mask.mask if possible.
            This is beneficial when the size of the data is larger than memory.
            Default is False.

        Returns
        -------
        :obj:`xarray.DataArray`:
            The clipped object.
        """
        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)}")
        crs = CRS.from_wkt(crs_to_wkt(crs)) if crs is not None else self.crs
        if self.crs != crs:
            if LooseVersion(rasterio.__version__) >= LooseVersion("1.2"):
                geometries = rasterio.warp.transform_geom(
                    crs, self.crs, geometries)
            else:
                geometries = [
                    rasterio.warp.transform_geom(crs, self.crs, geometry)
                    for geometry in geometries
                ]
        cropped_ds = None
        if from_disk:
            cropped_ds = _clip_from_disk(
                self._obj,
                geometries=geometries,
                all_touched=all_touched,
                drop=drop,
                invert=invert,
            )
        if cropped_ds is None:
            cropped_ds = _clip_xarray(
                self._obj,
                geometries=geometries,
                all_touched=all_touched,
                drop=drop,
                invert=invert,
            )

        if (cropped_ds.coords[self.x_dim].size < 1
                or cropped_ds.coords[self.y_dim].size < 1):
            raise NoDataInBounds(
                f"No data found in bounds.{_get_data_var_message(self._obj)}")

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

        return cropped_ds