Skip to content

Add get/add/remove_derived_from to pystac.Item #1136

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 4 commits into from
May 31, 2023
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
- Windows `\\` path delimiters are converted to POSIX style `/` delimiters ([#1125](https://github.com/stac-utils/pystac/pull/1125))
- Updated raster extension to work with the item_assets extension's AssetDefinition objects ([#1110](https://github.com/stac-utils/pystac/pull/1110))
- Classification extension ([#1093](https://github.com/stac-utils/pystac/pull/1093)), with support for adding classification information to item_assets' `AssetDefinition`s and raster's `RasterBand` objects.
- `get_derived_from`, `add_derived_from` and `remove_derived_from` to Items ([#1136](https://github.com/stac-utils/pystac/pull/1136))

### Changed

Expand Down
53 changes: 53 additions & 0 deletions pystac/item.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,59 @@ def get_collection(self) -> Optional[Collection]:
else:
return cast(Collection, collection_link.resolve_stac_object().target)

def add_derived_from(self, *items: Union[Item, str]) -> Item:
"""Add one or more items that this is derived from.

This method will add to any existing "derived_from" links.

Args:
items : Items (or href of items) to add to derived_from links.

Returns:
Item: self
"""
for item in items:
self.add_link(Link.derived_from(item))
return self

def remove_derived_from(self, item_id: str) -> None:
"""Remove an item that this is derived from.

This method will remove from existing "derived_from" links.

Args:
item_id : ID of item to remove from derived_from links.
"""
new_links: List[pystac.Link] = []

for link in self.links:
if link.rel != pystac.RelType.DERIVED_FROM:
new_links.append(link)
else:
try:
item = cast(Item, link.resolve_stac_object().target)
except Exception as e:
raise pystac.STACError(
"Link failed to resolve. Use remove_links instead."
) from e
if item.id != item_id:
new_links.append(link)
self.links = new_links

def get_derived_from(self) -> List[Item]:
"""Get the items that this is derived from.

Returns:
List[Item]: Returns a reference to the derived_from items.
"""
links = self.get_links(pystac.RelType.DERIVED_FROM)
try:
return [cast(Item, link.resolve_stac_object().target) for link in links]
except Exception as e:
raise pystac.STACError(
"Link failed to resolve. Use get_links instead."
) from e

def to_dict(
self, include_self_link: bool = True, transform_hrefs: bool = True
) -> Dict[str, Any]:
Expand Down
12 changes: 12 additions & 0 deletions pystac/link.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,18 @@ def item(cls: Type[L], item: Item, title: Optional[str] = None) -> L:
pystac.RelType.ITEM, item, title=title, media_type=pystac.MediaType.JSON
)

@classmethod
def derived_from(
cls: Type[L], item: Union[Item, str], title: Optional[str] = None
) -> L:
"""Creates a link to a derived_from Item."""
return cls(
pystac.RelType.DERIVED_FROM,
item,
title=title,
media_type=pystac.MediaType.JSON,
)

@classmethod
def canonical(
cls: Type[L],
Expand Down
62 changes: 62 additions & 0 deletions tests/test_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -486,3 +486,65 @@ def test_duplicate_self_links(tmp_path: Path, sample_item: pystac.Item) -> None:
sample_item.save_object(include_self_link=True, dest_href=str(path))
sample_item = Item.from_file(str(path))
assert len(sample_item.get_links(rel="self")) == 1


def test_get_derived_from_when_none_exists(test_case_1_catalog: Catalog) -> None:
item = next(test_case_1_catalog.get_items(recursive=True))
assert item.get_derived_from() == []
for link in item.links:
assert link.rel != pystac.RelType.DERIVED_FROM
assert item.get_single_link(pystac.RelType.DERIVED_FROM) is None


def test_add_derived_from(test_case_1_catalog: Catalog) -> None:
items = list(test_case_1_catalog.get_items(recursive=True))
item_0 = items[0]
item_1 = items[1]
item_2 = items[2]
item_0.add_derived_from(item_1, item_2.self_href)
derived_from = item_0.get_derived_from()
assert len(derived_from) == 2
assert derived_from[0].id == item_1.id
assert derived_from[1].id == item_2.id
filtered = [
link for link in item_0.links if link.rel == pystac.RelType.DERIVED_FROM
]
assert len(filtered) == 2
assert filtered[0].to_dict()["href"] == item_1.self_href
assert filtered[1].to_dict()["href"] == item_2.self_href


def test_get_unresolvable_derived_from(test_case_1_catalog: Catalog) -> None:
item = next(test_case_1_catalog.get_items(recursive=True))
item.add_derived_from("foo")
with pytest.raises(
pystac.STACError, match="Link failed to resolve. Use get_links instead"
):
item.get_derived_from()

links = item.get_links(pystac.RelType.DERIVED_FROM)
assert len(links) == 1


def test_remove_unresolvable_derived_from(test_case_1_catalog: Catalog) -> None:
item = next(test_case_1_catalog.get_items(recursive=True))
item.add_derived_from("foo")
with pytest.raises(
pystac.STACError, match="Link failed to resolve. Use remove_links instead"
):
item.remove_derived_from("foo")

item.remove_links(pystac.RelType.DERIVED_FROM)
assert item.get_derived_from() == []


def test_remove_derived_from(test_case_1_catalog: Catalog) -> None:
items = list(test_case_1_catalog.get_items(recursive=True))
item_0 = items[0]
item_1 = items[1]
item_0.add_derived_from(item_1)
item_0.remove_derived_from(item_1.id)
assert item_0.get_derived_from() == []
for link in item_0.links:
assert link.rel != pystac.RelType.DERIVED_FROM
assert item_0.get_single_link(pystac.RelType.DERIVED_FROM) is None