Skip to content

utils

clean_dic(o)

Convert numpy types to standard types in a nested dictionary containing number and lists.

Parameters:

Name Type Description Default
o Any

The object to convert.

required

Returns:

Type Description
None

None

Source code in study_da/utils/dic_utils.py
def clean_dic(o: Any) -> None:
    """Convert numpy types to standard types in a nested dictionary containing number and lists.

    Args:
        o (Any): The object to convert.

    Returns:
        None
    """
    if not isinstance(o, dict):
        return
    for k, v in o.items():
        if isinstance(v, np.generic):
            o[k] = v.item()
        elif isinstance(v, list):
            for i, x in enumerate(v):
                if isinstance(x, np.generic):
                    v[i] = x.item()
                if isinstance(x, dict):
                    clean_dic(x)
        else:
            clean_dic(v)

find_item_in_dic(obj, key)

Find an item in a nested dictionary.

Parameters:

Name Type Description Default
obj dict

The nested dictionary.

required
key str

The key to find in the nested dictionary.

required

Returns:

Name Type Description
Any Any

The value corresponding to the key in the nested dictionary.

Source code in study_da/utils/dic_utils.py
def find_item_in_dic(obj: dict, key: str) -> Any:
    """Find an item in a nested dictionary.

    Args:
        obj (dict): The nested dictionary.
        key (str): The key to find in the nested dictionary.

    Returns:
        Any: The value corresponding to the key in the nested dictionary.

    """
    if key in obj:
        return obj[key]
    for v in obj.values():
        if isinstance(v, dict):
            item = find_item_in_dic(v, key)
            if item is not None:
                return item

load_dic_from_path(path, ryaml=None)

Load a dictionary from a yaml file.

Parameters:

Name Type Description Default
path str

The path to the yaml file.

required
ryaml YAML

The yaml reader.

None

Returns:

Type Description
tuple[dict, YAML]

tuple[dict, ruamel.yaml.YAML]: The dictionary and the yaml reader.

Source code in study_da/utils/dic_utils.py
def load_dic_from_path(
    path: str, ryaml: ruamel.yaml.YAML | None = None
) -> tuple[dict, ruamel.yaml.YAML]:
    """Load a dictionary from a yaml file.

    Args:
        path (str): The path to the yaml file.
        ryaml (ruamel.yaml.YAML): The yaml reader.

    Returns:
        tuple[dict, ruamel.yaml.YAML]: The dictionary and the yaml reader.

    """

    if ryaml is None:
        # Initialize yaml reader
        ryaml = ruamel.yaml.YAML()

    # Load dic
    with open(path, "r") as fid:
        dic = ryaml.load(fid)

    return dic, ryaml

load_template_configuration_as_dic(template_configuration_name)

Load a template configuration as a dictionary.

Parameters:

Name Type Description Default
template_configuration_name str

The name of the template configuration.

required

Returns:

Name Type Description
dict tuple[dict, YAML]

The template dictionary.

Source code in study_da/utils/template_utils.py
def load_template_configuration_as_dic(
    template_configuration_name: str,
) -> tuple[dict, ruamel.yaml.YAML]:
    """Load a template configuration as a dictionary.

    Args:
        template_configuration_name (str): The name of the template configuration.

    Returns:
        dict: The template dictionary.

    """
    path_local_template_configurations = (
        f"{os.path.dirname(inspect.getfile(GenerateScan))}/../assets/configurations/"
    )

    # Add .yaml extension to template name
    if not template_configuration_name.endswith(".yaml"):
        template_configuration_name = f"{template_configuration_name}.yaml"

    # Get path to template
    path_template_config = f"{path_local_template_configurations}{template_configuration_name}"

    # Load template
    return load_dic_from_path(path_template_config)

load_template_script_as_str(template_script_name)

Load a template script as a string.

Parameters:

Name Type Description Default
template_script_name str

The name of the template script.

required

Returns:

Name Type Description
str str

The template script as a string.

Source code in study_da/utils/template_utils.py
def load_template_script_as_str(template_script_name: str) -> str:
    """Load a template script as a string.

    Args:
        template_script_name (str): The name of the template script.

    Returns:
        str: The template script as a string.

    """
    path_local_template_scripts = (
        f"{os.path.dirname(inspect.getfile(GenerateScan))}/../assets/template_scripts/"
    )

    # Get path to template
    path_template_script = f"{path_local_template_scripts}{template_script_name}"

    # Load template
    with open(path_template_script, "r") as fid:
        template_script = fid.read()

    return template_script

nested_get(dic, keys)

Get the value from a nested dictionary using a list of keys.

Parameters:

Name Type Description Default
dic dict

The nested dictionary.

required
keys list

The list of keys to traverse the nested dictionary.

required

Returns:

Name Type Description
Any Any

The value corresponding to the keys in the nested dictionary.

Source code in study_da/utils/dic_utils.py
def nested_get(dic: dict, keys: list) -> Any:
    # Adapted from https://stackoverflow.com/questions/14692690/access-nested-dictionary-items-via-a-list-of-keys
    """Get the value from a nested dictionary using a list of keys.

    Args:
        dic (dict): The nested dictionary.
        keys (list): The list of keys to traverse the nested dictionary.

    Returns:
        Any: The value corresponding to the keys in the nested dictionary.

    """
    for key in keys:
        dic = dic[key]
    return dic

nested_set(dic, keys, value)

Set a value in a nested dictionary using a list of keys.

Parameters:

Name Type Description Default
dic dict

The nested dictionary.

required
keys list

The list of keys to traverse the nested dictionary.

required
value Any

The value to set in the nested dictionary.

required

Returns:

Type Description
None

None

Source code in study_da/utils/dic_utils.py
def nested_set(dic: dict, keys: list, value: Any) -> None:
    """Set a value in a nested dictionary using a list of keys.

    Args:
        dic (dict): The nested dictionary.
        keys (list): The list of keys to traverse the nested dictionary.
        value (Any): The value to set in the nested dictionary.

    Returns:
        None

    """
    for key in keys[:-1]:
        dic = dic.setdefault(key, {})
    dic[keys[-1]] = value

set_item_in_dic(obj, key, value, found=False)

Set an item in a nested dictionary.

Parameters:

Name Type Description Default
obj dict

The nested dictionary.

required
key str

The key to set in the nested dictionary.

required
value Any

The value to set in the nested dictionary.

required
found bool

Whether the key has been found in the nested dictionary.

False

Returns:

Type Description
None

None

Source code in study_da/utils/dic_utils.py
def set_item_in_dic(obj: dict, key: str, value: Any, found: bool = False) -> None:
    """Set an item in a nested dictionary.

    Args:
        obj (dict): The nested dictionary.
        key (str): The key to set in the nested dictionary.
        value (Any): The value to set in the nested dictionary.
        found (bool): Whether the key has been found in the nested dictionary.

    Returns:
        None

    """
    if key in obj:
        if found:
            raise ValueError(f"Key {key} found more than once in the nested dictionary.")

        obj[key] = value
        found = True
    for v in obj.values():
        if isinstance(v, dict):
            set_item_in_dic(v, key, value, found)

write_dic_to_path(dic, path, ryaml=None)

Write a dictionary to a yaml file.

Parameters:

Name Type Description Default
dic dict

The dictionary to write.

required
path str

The path to the yaml file.

required
ryaml YAML

The yaml reader.

None

Returns:

Type Description
None

None

Source code in study_da/utils/dic_utils.py
def write_dic_to_path(dic: dict, path: str, ryaml: ruamel.yaml.YAML | None = None) -> None:
    """Write a dictionary to a yaml file.

    Args:
        dic (dict): The dictionary to write.
        path (str): The path to the yaml file.
        ryaml (ruamel.yaml.YAML): The yaml reader.

    Returns:
        None

    """

    if ryaml is None:
        # Initialize yaml reader
        ryaml = ruamel.yaml.YAML()

    # Write dic
    with open(path, "w") as fid:
        ryaml.dump(dic, fid)
        # Force os to write to disk now, to avoid race conditions
        fid.flush()
        os.fsync(fid.fileno())