Skip to content
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

improve polygon coordinate handling #506

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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
30 changes: 27 additions & 3 deletions earthaccess/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from typing import Any, Dict, List, Optional, Tuple, Type, Union

import dateutil.parser as parser # type: ignore
import shapely
from cmr import CollectionQuery, GranuleQuery # type: ignore
from requests import exceptions, session

Expand Down Expand Up @@ -731,14 +732,31 @@ def point(self, lon: str, lat: str) -> Type[GranuleQuery]:
super().point(lon, lat)
return self

def polygon(self, coordinates: List[Tuple[str, str]]) -> Type[GranuleQuery]:
def polygon(
self,
coordinates: Union[
shapely.geometry.base.BaseGeometry, str, bytes, List[Tuple[str, str]]
],
) -> Type[GranuleQuery]:
"""Filter by granules that overlap a polygonal area. Must be used in combination with a
collection filtering parameter such as short_name or entry_title.

Parameters:
coordinates: list of (lon, lat) tuples
coordinates: a shapely geometry, WKT or WKB, or a list of (lon, lat) tuples
"""
super().polygon(coordinates)

if isinstance(coordinates, shapely.geometry.base.BaseGeometry):
geom = coordinates
elif isinstance(coordinates, list):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using list is too restrictive. This should likely be Sequence.

geom = shapely.geometry.polygon.Polygon(coordinates)
elif shapely.from_wkt(coordinates, on_invalid="ignore") is not None:
geom = shapely.from_wkt(coordinates)
elif shapely.from_wkb(coordinates, on_invalid="ignore") is not None:
geom = shapely.from_wkb(coordinates)
else:
raise TypeError(f"{coordinates} is not a valid shapely polygon, WKT, WKB, or list of (lon, lat) tuples.")

super().polygon(_to_cmr_poly(geom))
return self

def bounding_box(
Expand Down Expand Up @@ -801,3 +819,9 @@ def doi(self, doi: str) -> Type[GranuleQuery]:
f"earthaccess couldn't find any associated collections with the DOI: {doi}"
)
return self


def _to_cmr_poly(geom: shapely.geometry.base.BaseGeometry) -> list:
if not shapely.is_ccw(geom):
geom = geom.reverse()
return list(geom.exterior.coords)
Loading