Config

Configuration and model building utilities.

Build Module

build_module(config, hyperpar=None)

Build a module based on the provided configuration. Every (possibly nested) dictionary with a 'class' key will be replaced by an instance initialized with arguments and keywords provided as 'args' and 'kwargs' keys.

Parameters:
  • config (Union[str, Dict, List]) –

    The configuration for building the module.

  • hyperpar (Union[str, Dict, None], default: None ) –

    The hyperparameters for the module. Defaults to None.

Returns:
  • list | dict | Callable

    Union[List, Dict, Callable]: The built module.

Raises:
  • AssertionError

    If hyperpar is provided and is not a dictionary.

Source code in aimnet/config.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def build_module(config: str | dict | list, hyperpar: str | dict | None = None) -> list | dict | Callable:
    """
    Build a module based on the provided configuration.
    Every (possibly nested) dictionary with a 'class' key will be replaced by an instance initialized with
    arguments and keywords provided as 'args' and 'kwargs' keys.

    Args:
        config (Union[str, Dict, List]): The configuration for building the module.
        hyperpar (Union[str, Dict, None], optional): The hyperparameters for the module. Defaults to None.

    Returns:
        Union[List, Dict, Callable]: The built module.

    Raises:
        AssertionError: If `hyperpar` is provided and is not a dictionary.

    """
    if isinstance(hyperpar, str):
        hyperpar = load_yaml(hyperpar)  # type: ignore[assignment]
    if hyperpar and not isinstance(hyperpar, dict):
        raise TypeError("Hyperpar must be a dictionary")
    config = load_yaml(config, hyperpar)
    for d, k, v in _iter_rec_bottomup(config):
        if isinstance(v, dict) and "class" in v:
            d[k] = get_init_module(  # type: ignore[index]
                v["class"],
                args=v.get("args", []),  # type: ignore[assignment]
                kwargs=v.get("kwargs", {}),
            )
    if "class" in config:
        config = get_init_module(  # type: ignore[assignment]
            config["class"],  # type: ignore[call-overload]
            args=config.get("args", []),  # type: ignore[union-attr]
            kwargs=config.get("kwargs", {}),  # type: ignore[union-attr]
        )
    return config  # type: ignore[assignment]