Skip to content

Commit

Permalink
remove geographic_crs and update info model (#746)
Browse files Browse the repository at this point in the history
* remove geographic_crs and update info model

* update changelog
  • Loading branch information
vincentsarago authored Oct 10, 2024
1 parent bb33ffb commit cd039d3
Show file tree
Hide file tree
Showing 9 changed files with 120 additions and 92 deletions.
36 changes: 36 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,42 @@
>> InvalidColorMapName: Invalid colormap name: Viridis
```

* removed `geographic_crs` attribute in `SpatialMixin` class **breaking change**

* removed `geographic_bounds` property in `SpatialMixin` class **breaking change**

* add `get_geographic_bounds(crs: CRS)` method in `SpatialMixin` class

```python
from rasterio.crs import CRS
from rio_tiler.io import Reader

# before
with Reader("cog.tif", geographic_crs=CRS.from_epsg(4326)) as src:
bounds = src.geographic_bounds

# now
with Reader("cog.tif") as src:
bounds = src.get_geographic_bounds(CRS.from_epsg(4326))
```

* replace `geographic bounds` with dataset bounds in `Reader.info()` method's response **breaking change**

```python
from rio_tiler.io import Reader

# before
with Reader("cog.tif") as src:
assert src.geographic_bounds == src.info().bounds

# now
with Reader("cog.tif") as src:
assert src.bounds == src.info().bounds
```

* add `crs: str` property in `Info` model

* remove `minzoom` and `maxzoom` properties in `Info` model **breaking change**

# 6.7.0 (2024-09-05)

Expand Down
25 changes: 8 additions & 17 deletions rio_tiler/io/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from rasterio.rio.overview import get_maximum_overview_level
from rasterio.warp import calculate_default_transform, transform_bounds

from rio_tiler.constants import WEB_MERCATOR_TMS, WGS84_CRS
from rio_tiler.constants import WEB_MERCATOR_TMS
from rio_tiler.errors import (
AssetAsBandError,
ExpressionMixingWarning,
Expand All @@ -27,7 +27,7 @@
from rio_tiler.models import BandStatistics, ImageData, Info, PointData
from rio_tiler.tasks import multi_arrays, multi_points, multi_values
from rio_tiler.types import AssetInfo, BBox, Indexes
from rio_tiler.utils import cast_to_sequence, normalize_bounds
from rio_tiler.utils import CRS_to_uri, cast_to_sequence, normalize_bounds


@attr.s
Expand All @@ -48,12 +48,9 @@ class SpatialMixin:
height: Optional[int] = attr.ib(default=None, init=False)
width: Optional[int] = attr.ib(default=None, init=False)

geographic_crs: CRS = attr.ib(init=False, default=WGS84_CRS)

@cached_property
def geographic_bounds(self) -> BBox:
"""Return dataset bounds in geographic_crs."""
if self.crs == self.geographic_crs:
def get_geographic_bounds(self, crs: CRS) -> BBox:
"""Return Geographic Bounds for a Geographic CRS."""
if self.crs == crs:
if self.bounds[1] > self.bounds[3]:
warnings.warn(
"BoundingBox of the dataset is inverted (minLat > maxLat).",
Expand All @@ -69,12 +66,7 @@ def geographic_bounds(self) -> BBox:
return self.bounds

try:
bounds = transform_bounds(
self.crs,
self.geographic_crs,
*self.bounds,
densify_pts=21,
)
bounds = transform_bounds(self.crs, crs, *self.bounds, densify_pts=21)
except: # noqa
warnings.warn(
"Cannot determine bounds in geographic CRS, will default to (-180.0, -90.0, 180.0, 90.0).",
Expand Down Expand Up @@ -1085,9 +1077,8 @@ def _reader(band: str, **kwargs: Any) -> Info:
bands_metadata = multi_values(bands, _reader, **kwargs)

meta = {
"bounds": self.geographic_bounds,
"minzoom": self.minzoom,
"maxzoom": self.maxzoom,
"bounds": self.bounds,
"crs": CRS_to_uri(self.crs) or self.crs.to_wkt(),
}

# We only keep the value for the first band.
Expand Down
16 changes: 8 additions & 8 deletions rio_tiler/io/rasterio.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,12 @@
from rio_tiler.io.base import BaseReader
from rio_tiler.models import BandStatistics, ImageData, Info, PointData
from rio_tiler.types import BBox, Indexes, NumType, RIOResampling
from rio_tiler.utils import _validate_shape_input, has_alpha_band, has_mask_band
from rio_tiler.utils import (
CRS_to_uri,
_validate_shape_input,
has_alpha_band,
has_mask_band,
)


@attr.s
Expand All @@ -46,7 +51,6 @@ class Reader(BaseReader):
input (str): dataset path.
dataset (rasterio.io.DatasetReader or rasterio.io.DatasetWriter or rasterio.vrt.WarpedVRT, optional): Rasterio dataset.
tms (morecantile.TileMatrixSet, optional): TileMatrixSet grid definition. Defaults to `WebMercatorQuad`.
geographic_crs (rasterio.crs.CRS, optional): CRS to use as geographic coordinate system. Defaults to WGS84.
colormap (dict, optional): Overwrite internal colormap.
options (dict, optional): Options to forward to low-level reader methods.
Expand Down Expand Up @@ -75,7 +79,6 @@ class Reader(BaseReader):
)

tms: TileMatrixSet = attr.ib(default=WEB_MERCATOR_TMS)
geographic_crs: CRS = attr.ib(default=WGS84_CRS)

colormap: Dict = attr.ib(default=None)

Expand Down Expand Up @@ -177,9 +180,8 @@ def _get_descr(ix):
nodata_type = "None"

meta = {
"bounds": self.geographic_bounds,
"minzoom": self.minzoom,
"maxzoom": self.maxzoom,
"bounds": self.bounds,
"crs": CRS_to_uri(self.crs) or self.crs.to_wkt(),
"band_metadata": [
(f"b{ix}", self.dataset.tags(ix)) for ix in self.dataset.indexes
],
Expand Down Expand Up @@ -596,8 +598,6 @@ class ImageReader(Reader):
tms: TileMatrixSet = attr.ib(init=False)

crs: CRS = attr.ib(init=False, default=None)
geographic_crs: CRS = attr.ib(init=False, default=None)

transform: Affine = attr.ib(init=False)

def __attrs_post_init__(self):
Expand Down
4 changes: 0 additions & 4 deletions rio_tiler/io/stac.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
from cachetools import LRUCache, cached
from cachetools.keys import hashkey
from morecantile import TileMatrixSet
from rasterio.crs import CRS
from rasterio.transform import array_bounds

from rio_tiler.constants import WEB_MERCATOR_TMS, WGS84_CRS
Expand Down Expand Up @@ -198,7 +197,6 @@ class STACReader(MultiBaseReader):
tms (morecantile.TileMatrixSet, optional): TileMatrixSet grid definition. Defaults to `WebMercatorQuad`.
minzoom (int, optional): Set minzoom for the tiles.
maxzoom (int, optional): Set maxzoom for the tiles.
geographic_crs (rasterio.crs.CRS, optional): CRS to use as geographic coordinate system. Defaults to WGS84.
include_assets (set of string, optional): Only Include specific assets.
exclude_assets (set of string, optional): Exclude specific assets.
include_asset_types (set of string, optional): Only include some assets base on their type.
Expand Down Expand Up @@ -234,8 +232,6 @@ class STACReader(MultiBaseReader):
minzoom: int = attr.ib(default=None)
maxzoom: int = attr.ib(default=None)

geographic_crs: CRS = attr.ib(default=WGS84_CRS)

include_assets: Optional[Set[str]] = attr.ib(default=None)
exclude_assets: Optional[Set[str]] = attr.ib(default=None)

Expand Down
9 changes: 3 additions & 6 deletions rio_tiler/io/xarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from rio_tiler.io.base import BaseReader
from rio_tiler.models import BandStatistics, ImageData, Info, PointData
from rio_tiler.types import BBox, NoData, WarpResampling
from rio_tiler.utils import _validate_shape_input
from rio_tiler.utils import CRS_to_uri, _validate_shape_input

try:
import xarray
Expand All @@ -43,7 +43,6 @@ class XarrayReader(BaseReader):
Attributes:
dataset (xarray.DataArray): Xarray DataArray dataset.
tms (morecantile.TileMatrixSet, optional): TileMatrixSet grid definition. Defaults to `WebMercatorQuad`.
geographic_crs (rasterio.crs.CRS, optional): CRS to use as geographic coordinate system. Defaults to WGS84.
Examples:
>>> ds = xarray.open_dataset(
Expand All @@ -62,7 +61,6 @@ class XarrayReader(BaseReader):
input: xarray.DataArray = attr.ib()

tms: TileMatrixSet = attr.ib(default=WEB_MERCATOR_TMS)
geographic_crs: CRS = attr.ib(default=WGS84_CRS)

_dims: List = attr.ib(init=False, factory=list)

Expand Down Expand Up @@ -120,9 +118,8 @@ def info(self) -> Info:
metadata = [band.attrs for d in self._dims for band in self.input[d]]

meta = {
"bounds": self.geographic_bounds,
"minzoom": self.minzoom,
"maxzoom": self.maxzoom,
"bounds": self.bounds,
"crs": CRS_to_uri(self.crs),
"band_metadata": [(f"b{ix}", v) for ix, v in enumerate(metadata, 1)],
"band_descriptions": [(f"b{ix}", v) for ix, v in enumerate(bands, 1)],
"dtype": str(self.input.dtype),
Expand Down
10 changes: 2 additions & 8 deletions rio_tiler/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,16 +61,10 @@ class Bounds(RioTilerBaseModel):
"""Dataset Bounding box"""

bounds: BoundingBox
crs: str


class SpatialInfo(Bounds):
"""Dataset SpatialInfo"""

minzoom: int
maxzoom: int


class Info(SpatialInfo):
class Info(Bounds):
"""Dataset Info."""

band_metadata: List[Tuple[str, Dict]]
Expand Down
18 changes: 18 additions & 0 deletions rio_tiler/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -789,3 +789,21 @@ def cast_to_sequence(val: Optional[Any] = None) -> Sequence:
val = (val,)

return val


def CRS_to_uri(crs: CRS) -> Optional[str]:
"""Convert CRS to URI.
Code adapted from https://github.com/developmentseed/morecantile/blob/1829fe12408e4a1feee7493308f3f02257ef4caf/morecantile/models.py#L148-L161
"""
# attempt to grab the authority, version, and code from the CRS
if authority_code := crs.to_authority(confidence_threshold=70):
version = "0"
authority, code = authority_code
# if we have a version number in the authority, split it out
if "_" in authority:
authority, version = authority.split("_")

return f"http://www.opengis.net/def/crs/{authority}/{version}/{code}"

return None
Loading

0 comments on commit cd039d3

Please sign in to comment.