Skip to content

Commit

Permalink
feat(api): update existing elements
Browse files Browse the repository at this point in the history
  • Loading branch information
almutlue committed Feb 7, 2024
1 parent 5f2e6de commit f78a6e4
Showing 1 changed file with 36 additions and 9 deletions.
45 changes: 36 additions & 9 deletions modo/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from .rdf import attrs_to_graph
from .storage import add_metadata_group, init_zarr, list_zarr_items
from .file_utils import extract_metadata
from .helpers import dict_to_instance
from .helpers import dict_to_instance, class_from_name


class MODO:
Expand Down Expand Up @@ -206,21 +206,48 @@ def add_element(
add_metadata_group(parent_group, attrs)
zarr.consolidate_metadata(self.archive.store)

def update_element(
self,
element_id: str,
new: model.DataEntity | model.Sample | model.Assay | model.MODO,
):
"""Update element by adding new values from model object"""
attrs = self.archive[element_id].attrs
attr_dict = attrs.asdict()
if not isinstance(new, class_from_name(attr_dict.get("@type"))):
raise ValueError(
f"Class {attr_dict['@type']} of {element_id} does not match {new.class_name}."
)
new_items = {
field: value
for field, value in new._items()
if field not in attrs.keys()
and field != "id"
and value is not None
or isinstance(value, list)
and len(value) == 0
}
attrs.update(**new_items)

def extract_metadata(self):
"""Add metadata and corresponding elements extracted from object associated data to the MODO object"""
new_elements = []
instances = [
dict_to_instance(entity, id)
for id, entity in self.metadata.items()
]
inst_names = [inst.name for inst in instances]
inst_names = {inst.name: inst.id for inst in instances}
for inst in instances:
elements = extract_metadata(inst)
new_elements += [
ele
for ele in elements
for ele in elements:
# NOTE: Need to compare names here as ids differ
if ele.name not in inst_names and ele not in new_elements
]
for ele in new_elements:
self.add_element(ele)
if (
ele.name not in inst_names.keys()
and ele not in new_elements
):
new_elements.append(ele)
self.add_element(ele)
elif ele.name in inst_names.keys():
self.update_element(inst_names[ele.name], ele)
else:
continue

0 comments on commit f78a6e4

Please sign in to comment.