|
| 1 | +from pydantic import BaseModel |
| 2 | + |
| 3 | +from pydantic import model_validator |
| 4 | +from typing import List, Optional |
| 5 | + |
| 6 | +from .kinds import Lattice |
| 7 | +from .kinds.all_elements import get_all_elements_as_annotation |
| 8 | +from .functions import load_file_to_dict, store_dict_to_file |
| 9 | + |
| 10 | + |
| 11 | +Facility = List[get_all_elements_as_annotation()] |
| 12 | + |
| 13 | + |
| 14 | +class PALSroot(BaseModel): |
| 15 | + """Represent the roo PALS structure""" |
| 16 | + |
| 17 | + version: Optional[str] = None |
| 18 | + |
| 19 | + facility: Facility |
| 20 | + |
| 21 | + @model_validator(mode="before") |
| 22 | + @classmethod |
| 23 | + def unpack_json_structure(cls, data): |
| 24 | + """Deserialize the JSON/YAML/...-like dict for facility elements""" |
| 25 | + from pals.kinds.mixin.all_element_mixin import unpack_element_list_structure |
| 26 | + |
| 27 | + return unpack_element_list_structure(data, "facility", "facility") |
| 28 | + |
| 29 | + def model_dump(self, *args, **kwargs): |
| 30 | + """Custom model dump for facility to handle element list formatting""" |
| 31 | + from pals.kinds.mixin.all_element_mixin import dump_element_list |
| 32 | + |
| 33 | + data = {} |
| 34 | + data["PALS"] = {} |
| 35 | + data["PALS"]["version"] = self.version |
| 36 | + data["PALS"] = dump_element_list(self, "facility", *args, **kwargs) |
| 37 | + return data |
| 38 | + |
| 39 | + @staticmethod |
| 40 | + def from_file(filename: str) -> "PALSroot": |
| 41 | + """Load a facility from a text file""" |
| 42 | + pals_dict = load_file_to_dict(filename) |
| 43 | + return PALSroot(**pals_dict) |
| 44 | + |
| 45 | + def to_file(self, filename: str): |
| 46 | + """Save a facility to a text file""" |
| 47 | + pals_dict = self.model_dump() |
| 48 | + store_dict_to_file(filename, pals_dict) |
| 49 | + |
| 50 | + |
| 51 | +def load(filename: str) -> PALSroot: |
| 52 | + """Load a facility from a text file""" |
| 53 | + pals_dict = load_file_to_dict(filename) |
| 54 | + return PALSroot(**pals_dict) |
| 55 | + |
| 56 | + |
| 57 | +def store(filename: str, pals_root: PALSroot | Facility | Lattice): |
| 58 | + # wrap single elements in a list, facility in a PALSroot |
| 59 | + if isinstance(pals_root, Lattice): |
| 60 | + pals_root = PALSroot(version=None, facility=[pals_root]) |
| 61 | + elif isinstance(pals_root, list): |
| 62 | + pals_root = PALSroot(version=None, facility=pals_root) |
| 63 | + |
| 64 | + pals_dict = pals_root.model_dump() |
| 65 | + store_dict_to_file(filename, pals_dict) |
0 commit comments