|
| 1 | +"""Class for loading a LinkML model from a YAML file.""" |
| 2 | + |
| 3 | +from typing import Type, Union |
| 4 | + |
| 5 | +import numpy as np |
| 6 | +import yaml |
| 7 | +from linkml_runtime import SchemaView |
| 8 | +from linkml_runtime.linkml_model import ClassDefinition |
| 9 | +from linkml_runtime.loaders.loader_root import Loader |
| 10 | +from linkml_runtime.utils.yamlutils import YAMLRoot |
| 11 | +from pydantic import BaseModel |
| 12 | + |
| 13 | + |
| 14 | +def _iterate_element( |
| 15 | + input_dict: dict, element_type: ClassDefinition, schemaview: SchemaView |
| 16 | +) -> dict: |
| 17 | + """Recursively iterate through the elements of a LinkML model and load them into a dict. |
| 18 | +
|
| 19 | + Datasets are loaded into NumPy arrays. |
| 20 | + """ |
| 21 | + ret_dict = dict() |
| 22 | + for k, v in input_dict.items(): |
| 23 | + found_slot = schemaview.induced_slot(k, element_type.name) |
| 24 | + if "linkml:elements" in found_slot.implements: |
| 25 | + v = np.asarray(v) |
| 26 | + elif isinstance(v, dict): |
| 27 | + found_slot_range = schemaview.get_class(found_slot.range) |
| 28 | + v = _iterate_element(v, found_slot_range, schemaview) |
| 29 | + # else: do not transform v |
| 30 | + ret_dict[k] = v |
| 31 | + |
| 32 | + return ret_dict |
| 33 | + |
| 34 | + |
| 35 | +class YamlLoader(Loader): |
| 36 | + """Class for loading a LinkML model from a YAML file.""" |
| 37 | + |
| 38 | + def load_any(self, source: str, **kwargs): |
| 39 | + """Create an instance of the target class from a YAML file.""" |
| 40 | + return self.load(source, **kwargs) |
| 41 | + |
| 42 | + def loads(self, source: str, **kwargs): |
| 43 | + """Create an instance of the target class from a YAML file.""" |
| 44 | + return self.load(source, **kwargs) |
| 45 | + |
| 46 | + def load( |
| 47 | + self, |
| 48 | + source: str, |
| 49 | + target_class: Type[Union[YAMLRoot, BaseModel]], |
| 50 | + schemaview: SchemaView, |
| 51 | + **kwargs, |
| 52 | + ): |
| 53 | + """Create an instance of the target class from a YAML file.""" |
| 54 | + input_dict = yaml.safe_load(source) |
| 55 | + |
| 56 | + element_type = schemaview.get_class(target_class.__name__) |
| 57 | + element = _iterate_element(input_dict, element_type, schemaview) |
| 58 | + obj = target_class(**element) |
| 59 | + |
| 60 | + return obj |
0 commit comments