|
| 1 | +import warnings |
| 2 | +from dataclasses import dataclass |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +from radiosim.ppdisk.config import Parser, Variables |
| 8 | + |
| 9 | +__all__ = ["FargoParameterConfig", "FargoParameterEntry"] |
| 10 | + |
| 11 | + |
| 12 | +@dataclass |
| 13 | +class FargoParameterEntry: |
| 14 | + key: str |
| 15 | + value: object |
| 16 | + comment: str |
| 17 | + |
| 18 | + def get_line(self, max_key_len: int, max_value_len: int): |
| 19 | + return ( |
| 20 | + f"{self.key:<{max_key_len + 2}}{self.value:<{max_value_len + 2}}" |
| 21 | + f"{self.comment if self.comment is not None else ''}\n" |
| 22 | + ) |
| 23 | + |
| 24 | + |
| 25 | +class FargoParameterConfig: |
| 26 | + def __init__(self, setup: str, autosave: bool = False): |
| 27 | + self._path: Path = Variables.get("FARGO_ROOT") / f"setups/{setup}/{setup}.par" |
| 28 | + self._autosave: bool = autosave |
| 29 | + |
| 30 | + if not self._path.exists(): |
| 31 | + raise NameError(f"The given setup '{setup}' does not exist!") |
| 32 | + |
| 33 | + self._parameters: dict[str, FargoParameterEntry] = dict() |
| 34 | + |
| 35 | + self.load() |
| 36 | + if self._parameters["Setup"].value != setup: |
| 37 | + warnings.warn( |
| 38 | + "The given setup name exists but the 'Setup' parameter in the" |
| 39 | + " config gives a different name. A missmatch might lead to " |
| 40 | + "execution problems.", |
| 41 | + stacklevel=1, |
| 42 | + ) |
| 43 | + |
| 44 | + def _get_entries(self) -> list[FargoParameterEntry]: |
| 45 | + values = [] |
| 46 | + for _key, value in self._parameters.items(): |
| 47 | + if isinstance(value, dict): |
| 48 | + values.extend(list(value.values())) |
| 49 | + else: |
| 50 | + values.append(value) |
| 51 | + |
| 52 | + return values |
| 53 | + |
| 54 | + def load(self) -> None: |
| 55 | + with open(self._path) as file: |
| 56 | + lines = file.readlines() |
| 57 | + |
| 58 | + current_category = None |
| 59 | + for line in lines: |
| 60 | + if line.strip() == "": |
| 61 | + continue |
| 62 | + |
| 63 | + if line.startswith("### ") and "[" in line and "]" in line: |
| 64 | + current_category = ( |
| 65 | + line.removeprefix("### ").split("[")[1].split("]")[0] |
| 66 | + ) |
| 67 | + self._parameters[current_category] = dict() |
| 68 | + continue |
| 69 | + |
| 70 | + components = line.split() |
| 71 | + |
| 72 | + if len(components) < 2: |
| 73 | + continue |
| 74 | + |
| 75 | + entry = FargoParameterEntry( |
| 76 | + key=components[0], |
| 77 | + value=Parser().parse(components[1]), |
| 78 | + comment=None if len(components) == 2 else " ".join(components[2:]), |
| 79 | + ) |
| 80 | + |
| 81 | + if current_category is None: |
| 82 | + self._parameters[components[0]] = entry |
| 83 | + else: |
| 84 | + self._parameters[current_category][components[0]] = entry |
| 85 | + |
| 86 | + def save(self) -> None: |
| 87 | + with open(self._path) as file: |
| 88 | + old_content = file.read() |
| 89 | + with open(self._path, "w") as file: |
| 90 | + try: |
| 91 | + key_lens = [] |
| 92 | + value_lens = [] |
| 93 | + for entry in self._get_entries(): |
| 94 | + key_lens.append(len(str(entry.key))) |
| 95 | + value_lens.append(len(str(entry.value))) |
| 96 | + |
| 97 | + max_key_len = np.max(key_lens) |
| 98 | + max_value_len = np.max(value_lens) |
| 99 | + |
| 100 | + lines = [] |
| 101 | + |
| 102 | + for key, entry in self._parameters.items(): |
| 103 | + if isinstance(entry, dict): |
| 104 | + lines.append("\n") |
| 105 | + lines.append(f"### [{key}]\n") |
| 106 | + lines.append("\n") |
| 107 | + |
| 108 | + for _subkey, subentry in self._parameters[key].items(): |
| 109 | + lines.append( |
| 110 | + subentry.get_line( |
| 111 | + max_key_len=max_key_len, max_value_len=max_value_len |
| 112 | + ) |
| 113 | + ) |
| 114 | + else: |
| 115 | + lines.append( |
| 116 | + entry.get_line( |
| 117 | + max_key_len=max_key_len, max_value_len=max_value_len |
| 118 | + ) |
| 119 | + ) |
| 120 | + |
| 121 | + file.writelines(lines) |
| 122 | + except Exception as e: |
| 123 | + warnings.warn( |
| 124 | + "An error occured while saving. Rolling back configuration files.", |
| 125 | + stacklevel=1, |
| 126 | + ) |
| 127 | + file.write(old_content) |
| 128 | + raise e |
| 129 | + |
| 130 | + def __getitem__(self, key: str) -> FargoParameterEntry: |
| 131 | + key_components = key.split(".") |
| 132 | + |
| 133 | + match len(key_components): |
| 134 | + case 1: |
| 135 | + return self._parameters[key_components[0]] |
| 136 | + case 2: |
| 137 | + return self._parameters[key_components[0]][key_components[1]] |
| 138 | + case _: |
| 139 | + if len(key_components) > 2: |
| 140 | + raise KeyError( |
| 141 | + "The maximum depth of a config key is 2 (catgeory -> entry)!" |
| 142 | + ) |
| 143 | + |
| 144 | + def __setitem__(self, key: str, value: object) -> None: |
| 145 | + key_components = key.split(".") |
| 146 | + |
| 147 | + match len(key_components): |
| 148 | + case 1: |
| 149 | + if isinstance(value, dict): |
| 150 | + self._parameters[key_components[0]] = value |
| 151 | + return None |
| 152 | + if isinstance(value, FargoParameterEntry): |
| 153 | + self._parameters[key_components[0]] = value |
| 154 | + elif isinstance( |
| 155 | + self._parameters[key_components[0]], FargoParameterEntry |
| 156 | + ): |
| 157 | + self._parameters[key_components[0]].value = value |
| 158 | + else: |
| 159 | + raise TypeError( |
| 160 | + "Values at root level must either be a dict or a valid entry!" |
| 161 | + ) |
| 162 | + case 2: |
| 163 | + if isinstance(value, FargoParameterEntry): |
| 164 | + self._parameters[key_components[0]][key_components[1]] = value |
| 165 | + elif isinstance( |
| 166 | + self._parameters[key_components[0]][key_components[1]], |
| 167 | + FargoParameterEntry, |
| 168 | + ): |
| 169 | + self._parameters[key_components[0]][key_components[1]].value = value |
| 170 | + else: |
| 171 | + raise TypeError( |
| 172 | + "This key does not point to a valid entry! Enter an instance " |
| 173 | + "of a 'FargoParameterEntry'" |
| 174 | + ) |
| 175 | + |
| 176 | + case _: |
| 177 | + if len(key_components) > 2: |
| 178 | + raise KeyError( |
| 179 | + "The maximum depth of a config key is 2 (catgeory -> entry)!" |
| 180 | + ) |
| 181 | + |
| 182 | + if self._autosave: |
| 183 | + self.save() |
0 commit comments