|
3 | 3 | from typing import Union
|
4 | 4 | import pathlib
|
5 | 5 | import yaml
|
| 6 | +import ast |
| 7 | +import sys |
6 | 8 |
|
7 |
| -# To enable compatiblity with Python<=3.6 (e.g. for sinergym dockerfile) |
8 |
| -try: |
| 9 | +import beobench.utils |
| 10 | + |
| 11 | +# To enable compatiblity with Python<=3.8 (e.g. for sinergym dockerfile) |
| 12 | +if sys.version_info[1] >= 9: |
9 | 13 | import importlib.resources
|
10 |
| -except ImportError: |
| 14 | +else: |
11 | 15 | import importlib_resources
|
12 | 16 | import importlib
|
13 | 17 |
|
14 | 18 | importlib.resources = importlib_resources
|
15 | 19 |
|
16 | 20 |
|
17 |
| -def parse(config: Union[str, pathlib.Path]) -> dict: |
18 |
| - """Parse experiment config from yaml file to dict. |
| 21 | +def parse(config: Union[dict, str, pathlib.Path, list]) -> dict: |
| 22 | + """Parse experiment config to dict. |
19 | 23 |
|
20 | 24 | Args:
|
21 |
| - config (Union[str, pathlib.Path]): path of yaml file |
| 25 | + config (Union[dict, str, pathlib.Path, list]): path of yaml file |
22 | 26 |
|
23 | 27 | Returns:
|
24 | 28 | dict: config in dictionary
|
25 | 29 | """
|
26 |
| - |
27 |
| - # load config dict if path given |
28 |
| - if isinstance(config, (str, pathlib.Path)): |
29 |
| - # make sure config is a real path |
30 |
| - if isinstance(config, str): |
31 |
| - config = pathlib.Path(config) |
| 30 | + if isinstance(config, list): |
| 31 | + # get list of config dicts |
| 32 | + parsed_configs = [] |
| 33 | + for single_config in config: |
| 34 | + parsed_configs.append(parse(single_config)) |
| 35 | + |
| 36 | + # merge config dicts |
| 37 | + parsed_config = {} |
| 38 | + for conf in parsed_configs: |
| 39 | + parsed_config = beobench.utils.merge_dicts(parsed_config, conf) |
| 40 | + |
| 41 | + elif isinstance(config, pathlib.Path): |
| 42 | + # load config yaml to dict if path given |
32 | 43 | with open(config, "r", encoding="utf-8") as config_file:
|
33 |
| - config_dict = yaml.safe_load(config_file) |
| 44 | + parsed_config = yaml.safe_load(config_file) |
| 45 | + |
| 46 | + elif isinstance(config, str): |
| 47 | + if config[0] in ["{", "["]: |
| 48 | + # if json str or list |
| 49 | + parsed_config = parse(ast.literal_eval(config)) |
| 50 | + else: |
| 51 | + # make sure config is a real path |
| 52 | + config_path = pathlib.Path(config) |
| 53 | + parsed_config = parse(config_path) |
| 54 | + |
| 55 | + elif isinstance(config, dict): |
| 56 | + parsed_config = config |
| 57 | + |
34 | 58 | else:
|
35 |
| - config_dict = config |
| 59 | + raise ValueError( |
| 60 | + f"Config not one of allowed types (dict, str, pathlib.Path, list): {config}" |
| 61 | + ) |
36 | 62 |
|
37 |
| - return config_dict |
| 63 | + return parsed_config |
38 | 64 |
|
39 | 65 |
|
40 | 66 | def create_rllib_config(config: dict) -> dict:
|
|
0 commit comments