Skip to content

Commit

Permalink
Make hierarchy search more efficient
Browse files Browse the repository at this point in the history
  • Loading branch information
jpolchlo committed Jun 26, 2023
1 parent 83c58af commit 1cda6f0
Showing 1 changed file with 26 additions and 11 deletions.
37 changes: 26 additions & 11 deletions pystac/stac_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,26 +138,41 @@ def remove_hierarchical_links(self, add_canonical: bool = False) -> List[Link]:
return remove

def target_in_hierarchy(self, target: Union[str, STACObject]) -> bool:
"""Recursively collects all the targets referred to by the hierarchical
links of the current STACObject.
"""Determine if target lin is somewhere in the hierarchical link tree of
a STACObject.
Args:
target: A string or STACObject describing the target to search for
Returns:
Set[Union[str, STACObject]]: All encountered targets
bool: Returns True if the target was found in the hierarchical link tree
for the current STACObject
"""

def traverse(
obj: Union[str, STACObject], visited: Set[Union[str, STACObject]]
) -> Set[Union[str, STACObject]]:
) -> bool:
if obj == target:
return True

Check warning on line 156 in pystac/stac_object.py

View check run for this annotation

Codecov / codecov/patch

pystac/stac_object.py#L156

Added line #L156 was not covered by tests
if isinstance(obj, str):
return visited
return False

new_targets = [
link.target
for link in obj.links
if link.is_hierarchical() and link.target not in visited
]
if target in new_targets:
return True

for subtree in new_targets:
visited.add(subtree)
if traverse(subtree, visited):
return True

Check warning on line 171 in pystac/stac_object.py

View check run for this annotation

Codecov / codecov/patch

pystac/stac_object.py#L171

Added line #L171 was not covered by tests

hierarchical_links = [link for link in obj.links if link.is_hierarchical()]
new_targets = set([link.target for link in hierarchical_links]) - visited
for target in new_targets:
visited = traverse(target, visited.union(set([target])))
return visited
return False

return target in traverse(self, set([self]))
return traverse(self, set([self]))

def get_single_link(
self,
Expand Down

0 comments on commit 1cda6f0

Please sign in to comment.