-
Notifications
You must be signed in to change notification settings - Fork 123
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
Add basic ItemCollection implementation #430
Merged
duckontheweb
merged 14 commits into
stac-utils:main
from
duckontheweb:add/371-item-collection
Jun 14, 2021
Merged
Changes from 5 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
8bf40b6
Basic ItemCollection implementation
duckontheweb 5d58dc1
Add ItemCollection to top-level I/O functions
duckontheweb 2a8cfa1
Add ItemCollection documentation
duckontheweb c6b461b
Fix lint issues
duckontheweb 61b12d1
Update CHANGELOG
duckontheweb 9b1fed2
Option to not clone Items when instantiating ItemCollection
duckontheweb 542f8c6
Make ItemCollection a typing.Collection
duckontheweb 31beb9d
Allow Iterable items argument to ItemCollection
duckontheweb 698c54b
Do not clone Items in ItemCollection.from_dict
duckontheweb 702a26f
Accept Iterable of dicts or Items in ItemCollection.__init__
duckontheweb 1ead0d5
Ability to add ItemCollections
duckontheweb 97354cd
Default to not cloning Items on instantiation
duckontheweb 2bb16a1
Remove ItemCollection from top-level functions
duckontheweb 47017df
Remove ITEMCOLLECTION from STACObjectTypes
duckontheweb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
from copy import deepcopy | ||
from pystac.errors import STACTypeError | ||
from typing import Any, Dict, Iterator, List, Optional, Sized, Iterable | ||
|
||
import pystac | ||
from pystac.utils import make_absolute_href, is_absolute_href | ||
from pystac.serialization.identify import identify_stac_object_type | ||
|
||
|
||
class ItemCollection(Sized, Iterable[pystac.Item]): | ||
duckontheweb marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""Implementation of a GeoJSON FeatureCollection whose features are all STAC | ||
Items. | ||
|
||
All :class:`~pystac.Item` instances passed to the :class:`~ItemCollection` instance | ||
during instantiation are cloned and have their ``"root"`` URL cleared. Instances of | ||
this class are iterable and sized (see examples below). | ||
|
||
Any additional top-level fields in the FeatureCollection are retained in | ||
:attr:`~ItemCollection.extra_fields` by the :meth:`~ItemCollection.from_dict` and | ||
:meth:`~ItemCollection.from_file` methods and will be present in the serialized file | ||
from :meth:`~ItemCollection.save_object`. | ||
|
||
Examples: | ||
|
||
Loop over all items in the ItemCollection | ||
|
||
>>> item_collection: ItemCollection = ... | ||
>>> for item in item_collection: | ||
... ... | ||
|
||
Get the number of Items in the ItemCollection | ||
|
||
>>> length: int = len(item_collection) | ||
|
||
""" | ||
|
||
items: List[pystac.Item] | ||
"""The list of :class:`pystac.Item` instances contained in this | ||
``ItemCollection``.""" | ||
|
||
extra_fields: Dict[str, Any] | ||
"""Dictionary containing additional top-level fields for the GeoJSON | ||
FeatureCollection.""" | ||
|
||
def __init__( | ||
self, items: List[pystac.Item], extra_fields: Optional[Dict[str, Any]] = None | ||
): | ||
self.items = [item.clone() for item in items] | ||
duckontheweb marked this conversation as resolved.
Show resolved
Hide resolved
|
||
for item in self.items: | ||
item.clear_links("root") | ||
duckontheweb marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.extra_fields = extra_fields or {} | ||
|
||
def __getitem__(self, idx: int) -> pystac.Item: | ||
return self.items[idx] | ||
|
||
def __iter__(self) -> Iterator[pystac.Item]: | ||
return iter(self.items) | ||
|
||
def __len__(self) -> int: | ||
return len(self.items) | ||
|
||
def to_dict(self) -> Dict[str, Any]: | ||
"""Serializes an :class:`ItemCollection` instance to a JSON-like dictionary.""" | ||
return { | ||
"type": "FeatureCollection", | ||
"features": [item.to_dict() for item in self.items], | ||
**self.extra_fields, | ||
} | ||
|
||
def clone(self) -> "ItemCollection": | ||
"""Creates a clone of this instance. This clone is a deep copy; all | ||
:class:`~pystac.Item` instances are cloned and all additional top-level fields | ||
are deep copied.""" | ||
return self.__class__( | ||
items=[item.clone() for item in self.items], | ||
extra_fields=deepcopy(self.extra_fields), | ||
) | ||
|
||
@classmethod | ||
def from_dict(cls, d: Dict[str, Any]) -> "ItemCollection": | ||
"""Creates a :class:`ItemCollection` instance from a dictionary.""" | ||
if identify_stac_object_type(d) != pystac.STACObjectType.ITEMCOLLECTION: | ||
raise STACTypeError("Dict is not a valid ItemCollection") | ||
|
||
items = [pystac.Item.from_dict(item) for item in d.get("features", [])] | ||
extra_fields = {k: v for k, v in d.items() if k not in ("features", "type")} | ||
|
||
return cls(items=items, extra_fields=extra_fields) | ||
|
||
@classmethod | ||
def from_file( | ||
cls, href: str, stac_io: Optional[pystac.StacIO] = None | ||
) -> "ItemCollection": | ||
"""Reads a :class:`ItemCollection` from a JSON file. | ||
|
||
Arguments: | ||
href : Path to the file. | ||
stac_io : A :class:`~pystac.StacIO` instance to use for file I/O | ||
""" | ||
if stac_io is None: | ||
stac_io = pystac.StacIO.default() | ||
|
||
if not is_absolute_href(href): | ||
href = make_absolute_href(href) | ||
|
||
d = stac_io.read_json(href) | ||
|
||
return cls.from_dict(d) | ||
|
||
def save_object( | ||
self, | ||
dest_href: str, | ||
stac_io: Optional[pystac.StacIO] = None, | ||
) -> None: | ||
"""Saves this instance to the ``dest_href`` location. | ||
|
||
Args: | ||
dest_href : Location to which the file will be saved. | ||
stac_io: Optional :class:`~pystac.StacIO` instance to use. If not provided, | ||
will use the default instance. | ||
""" | ||
if stac_io is None: | ||
stac_io = pystac.StacIO.default() | ||
|
||
stac_io.save_json(dest_href, self.to_dict()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure it makes sense to change these top level package read/write methods to include ItemCollection. It breaks user code that may rely on the STACObject type, forcing the type differentiation to happen by the caller. Also the last two parameters of
write_file
make it feel a bit shoe-horned. On the other hand, I can see people getting confused about whyread_file
wouldn't work on an ItemCollection if they didn't know it wasn't a core stac object.I think my preference would be to keep these methods working with core STAC types, and force users to treat ItemCollections as a separate concept, which makes more sense with the spec as it currently stands.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, I agree with all of the points you make here, and I think my preference would be to not change the top-level functions as well. If that ends up being the decision, I will add more clear documentation to the
ItemCollection
class indicating that it is not aSTACObject
and cannot be read using those top-level methods.@scottyhq I'm curious how much of a priority it is for you to be able to read Item Collections using
pystac.read_file
vs.ItemCollection.from_file
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for all the work on this! Yes, I'm coming at this primarily from someone new to STAC, who is unfamiliar with spec details. The key expectation I have is that after searching a STAC API for data, and saving 'results.json' to work with later, there is an straightforward way to open that file and navigate it. For Python it seems like
pystac_client
takes care of the searching andpystac
should care of the I/O and navigation of the results. I don't think people should have to understand the concepts of ItemCollections versus Collections, Core vs Not, for this fundamental workflow.So if
pystac.read_file
can't handle ItemCollections, and a separateItemCollection.from_file()
is the way forward (or pystac_client.read_file()`?), I think that just needs to be clearly documented.Also useful (and I think a non-breaking change) would then be for
pystac.read_file
to have error handing that can recognize the json is an ItemCollection and suggest the correct method to open it, rather than the currentKeyError: 'id'
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks @scottyhq, that all makes sense to me. I'll change those top-level functions back to their original signatures and make sure we have clear docs on how to work with ItemCollections. I'm pretty sure the issue with a
KeyError
being raised inpystac.read_file
is fixed by #402, but I'll add a test to be sure.@matthewhanson Looking back at the code example in the original issue it seems like the name of the
ItemSearch.items_as_collection
method might also be misleading. Maybe we should rename that toitems_as_item_collection
so that users don't think they are saving a STAC Collection?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Removed
ItemCollection
handling from top-level functions and added test thatpystac.read_file
raises aSTACTypeError
instead of theKeyError
in 404bb99There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@duckontheweb
ItemSearch.items_as_collection
was misleading. I've renamed it already, there's nowget_pages
(get the raw JSON of the pages),get_item_collection
(gets pages as item collections),get_items
(iterator through all pages and items), andget_all_items
(gets all items from all pages and returns as single ItemCollection). This matches theget_
syntax used in PySTAC