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

make_tree() updates #575

Merged
merged 2 commits into from
Jul 7, 2024
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 HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
* Add `User.annotated_observations_count` field
* Add `root_id` filter to `taxon.make_tree()` to explicitly set the root taxon instead of determining it automatically
* Fix `taxon.make_tree()` rank filtering to allow skipping any number of rank levels
* `taxon.make_tree()` now returns copies of original taxon objects instead of modifying them in-place

### Rate limits, timeouts, and error handling
* Increase default request timeout from 10 to 20 seconds
Expand Down
11 changes: 10 additions & 1 deletion pyinaturalist/models/taxon.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import re
from copy import deepcopy
from itertools import chain, groupby
from logging import getLogger
from typing import Any, Callable, Dict, Iterable, List, Optional
Expand Down Expand Up @@ -413,7 +414,8 @@ def make_tree(
sort_key: Optional[TaxonSortKey] = None,
root_id: Optional[int] = None,
) -> Taxon:
"""Organize a list of taxa into a taxonomic tree. Expects exactly one root taxon.
"""Organize a list of taxa into a taxonomic tree, defined by ``children`` and ``ancestors``
attributes. Expects exactly one root taxon.

Args:
taxa: Taxon objects to organize
Expand All @@ -427,6 +429,7 @@ def make_tree(
"""
include_ranks = [r.lower() for r in include_ranks or []]
sort_key = sort_key if sort_key is not None else _sort_rank_name
taxa = [deepcopy(t) for t in taxa]
root = _find_root(taxa, include_ranks, root_id)

# Group taxa by parent ID, including any ungrafted children added directly to root
Expand All @@ -440,6 +443,8 @@ def add_descendants(taxon, ancestors=None) -> Taxon:
taxon.ancestors = ancestors or []
for child in get_included_children(taxon):
child = add_descendants(child, taxon.ancestors + [taxon])
child.ancestor_ids = [a.id for a in child.ancestors]
child.parent_id = taxon.id
taxon.children.append(child)

taxon.children = sorted(taxon.children, key=sort_key)
Expand Down Expand Up @@ -504,6 +509,10 @@ def _find_and_graft_root(taxa: Iterable[Taxon], include_ranks: Optional[List[str
# If there are multiple branches, we need to insert a 'Life' root above them
root = TaxonCount(id=ROOT_TAXON_ID, name='Life', rank='stateofmatter', is_active=True) # type: ignore
root.children = root_taxa
for t in root.children:
t.ancestors = [root]
t.ancestor_ids = [root.id]
t.parent_id = root.id
return root


Expand Down
53 changes: 37 additions & 16 deletions test/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1116,25 +1116,33 @@ def test_make_tree():
assert node.name == 'Bombus'
children = [t.name for t in node.children]
assert children == ['Bombus', 'Psithyrus', 'Pyrobombus', 'Subterraneobombus', 'Thoracobombus']
assert (
node.child_ids == [t.id for t in node.children] == [538903, 538893, 538900, 415027, 538902]
)

# Ensure ancestors are updated
assert root.ancestors == []
assert [t.id for t in node.ancestors] == [
48460,
1,
47120,
372739,
47158,
184884,
47201,
124417,
326777,
47222,
630955,
47221,
199939,
538883,
]
assert node.parent_id == 538883
assert (
node.ancestor_ids
== [t.id for t in node.ancestors]
== [
48460,
1,
47120,
372739,
47158,
184884,
47201,
124417,
326777,
47222,
630955,
47221,
199939,
538883,
]
)


def test_make_tree__filtered():
Expand Down Expand Up @@ -1169,6 +1177,18 @@ def test_make_tree__filtered():
]


def test_make_tree__preserves_originals():
"""Children/ancestors of original taxon objects should be preserved"""
taxa = Taxon.from_json_list(j_life_list_2)
animalia = taxa[1]
animalia.ancestors = [Taxon(name='Life')]
animalia.children = [Taxon(name='Arthropoda')]
make_tree(taxa, include_ranks=['kingdom', 'class', 'family', 'genus', 'species'])

assert animalia.ancestors[0].name == 'Life'
assert animalia.children[0].name == 'Arthropoda'


def test_make_tree__flattened():
flat_list = make_tree(Taxon.from_json_list(j_life_list_1)).flatten()
assert [t.id for t in flat_list] == [48460, 1, 2, 3, 573, 574, 889, 890, 980, 981]
Expand Down Expand Up @@ -1237,6 +1257,7 @@ def test_make_tree__ungrafted():
assert root.name == 'Life'
assert root.children[0].name == 'Animalia'
assert root.children[1].name == 'Monocots'
assert root.children[0].children[0].name == 'Arthropoda'


def test_make_tree__explicit_root():
Expand Down
Loading