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

Optimize implementation of SchemaView get_classes_by_slot() method #281

Draft
wants to merge 3 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
20 changes: 10 additions & 10 deletions linkml_runtime/utils/schemaview.py
Original file line number Diff line number Diff line change
Expand Up @@ -1435,29 +1435,29 @@ def slot_range_as_union(self, slot: SlotDefinition) -> List[ElementName]:
if x.range:
range_union_of.append(x.range)
return range_union_of

def get_classes_by_slot(self, slot: SlotDefinition, include_induced: bool = False) -> List[ClassDefinitionName]:
"""Get all classes that use a given slot, either as a direct or induced slot.

:param slot: slot in consideration
:param include_induced: supplement all direct slots with induced slots, defaults to False
:return: list of slots, either direct, or both direct and induced
"""
slots_list = [] # list of all direct or induced slots
direct_classes_list = [] # list of classes associated with slot directly
induced_classes_list = [] # list of classes associated with slot indirectly

for c_name, c in self.all_classes().items():
# check if slot is direct specification on class
if slot.name in c.slots:
slots_list.append(c_name)

# include induced classes also if requested
if include_induced:
for c_name, c in self.all_classes().items():
direct_classes_list.append(c_name)
elif include_induced:
for ind_slot in self.class_induced_slots(c_name):
if ind_slot.name == slot.name:
slots_list.append(c_name)
induced_classes_list.append(c_name)

return list(dict.fromkeys(slots_list))
if include_induced:
return list(set(direct_classes_list + induced_classes_list))
else:
return list(set(direct_classes_list))

@lru_cache()
def get_slots_by_enum(self, enum_name: ENUM_NAME = None) -> List[SlotDefinition]:
Expand Down
2 changes: 1 addition & 1 deletion tests/test_utils/test_schemaview.py
Original file line number Diff line number Diff line change
Expand Up @@ -735,7 +735,7 @@ def test_get_classes_by_slot(self):
actual_result = sv.get_classes_by_slot(slot, include_induced=True)
expected_result = ["Person", "Adult"]

self.assertListEqual(actual_result, expected_result)
self.assertListEqual(sorted(actual_result), sorted(expected_result))

def test_materialize_patterns(self):
sv = SchemaView(SCHEMA_WITH_STRUCTURED_PATTERNS)
Expand Down
Loading