Source code for storx.hierarchy.hierarchy_m
"""Contains the hierarchy class."""
import yaml
from pathlib import Path
from .nested_dict_tools_m import search_in_nested_dict, \
convert_nested_dict_to_list, \
print_nested_dict
[docs]
class Hierarchy:
"""
Class that represents the hierarchy of physical quantities.
Essentially a wrapper around dict assuming a special structure given
by the hierarchy file. Contains useful functionality to search within
the dict.
"""
[docs]
def __init__(self, dictionary: dict):
"""Initialize the type through a dictionary."""
self.__dict__ = dictionary
def __repr__(self):
"""Return a representation of the type as a table like output."""
return print_nested_dict(self.__dict__)
[docs]
def __getitem__(self, key):
"""Allow to index the type like a dictionary."""
return getattr(self, key)
[docs]
def as_dict(self):
"""Return the underlying dictionary of the type."""
return self.__dict__
[docs]
def items(self):
"""Return the items of the underlying dictionary of the type."""
return self.__dict__.items()
[docs]
def keys(self):
"""Return the keys of the underlying dictionary of the type."""
return self.__dict__.keys()
[docs]
def values(self):
"""Return the values of the underlying dictionary of the type."""
return self.__dict__.values()
[docs]
@classmethod
def initialize_from_yaml(cls, filepath: Path):
"""Return an object of this type created from a yaml file."""
with open(str(filepath.absolute()), "r") as stream:
hierarchy = yaml.load(stream, Loader=yaml.Loader)
return cls(hierarchy)
[docs]
def search_for_key(self, string: str):
"""Search for a given string in the dictionary given the key."""
return search_in_nested_dict(self.__dict__, string, mode="key")
[docs]
def search_for_value(self, string: str):
"""Search for a given string in the dictionary given the value."""
return search_in_nested_dict(self.__dict__, string, mode="val")
[docs]
def search_for(self, string: str):
"""Search for a given string in the dictionary.
Returns all entries that contain the string in their key, value or
anywhere in the tree.
"""
return search_in_nested_dict(self.__dict__, string, mode="str")
[docs]
def get_all_keys(self):
"""Return a flattened list of all keys available in the dictionary."""
return convert_nested_dict_to_list(self.__dict__)