Skip to content

add stac search helper methods #70

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions stac_pydantic/api/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
MultiPolygon,
Point,
Polygon,
_GeometryBase,
)
from pydantic import BaseModel, Field, validator

Expand Down Expand Up @@ -87,3 +88,25 @@ def validate_datetime(cls, v):
"Invalid datetime range, must match format (begin_date, end_date)"
)
return v

@property
def spatial_filter(self) -> Optional[_GeometryBase]:
"""Return a geojson-pydantic object representing the spatial filter for the search request.

Check for both because the ``bbox`` and ``intersects`` parameters are mutually exclusive.
"""
if self.bbox:
return Polygon(
coordinates=[
[
[self.bbox[0], self.bbox[3]],
[self.bbox[2], self.bbox[3]],
[self.bbox[2], self.bbox[1]],
[self.bbox[0], self.bbox[1]],
[self.bbox[0], self.bbox[3]],
]
]
)
if self.intersects:
return self.intersects
return
11 changes: 9 additions & 2 deletions tests/test_api_extensions.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from datetime import datetime

import pytest
from shapely.geometry import Polygon
from shapely.geometry import Polygon, shape

from stac_pydantic import Item
from stac_pydantic.api.extensions.fields import FieldsExtension
from stac_pydantic.api.search import Search


def test_fields_filter():
Expand All @@ -29,3 +29,10 @@ def test_fields_filter():

assert not props.get("bar")
assert not d


def test_search_geometry_bbox():
search = Search(collections=["foo", "bar"], bbox=[0, 0, 1, 1])
geom1 = shape(search.spatial_filter)
geom2 = Polygon.from_bounds(*search.bbox)
assert (geom1.intersection(geom2).area / geom1.union(geom2).area) == 1.0