|
| 1 | +from pydantic import model_validator |
| 2 | +from typing import List, Literal |
| 3 | + |
| 4 | +from .all_elements import get_all_elements_as_annotation |
| 5 | +from .mixin import BaseElement |
| 6 | +from ..functions import load_file_to_dict, store_dict_to_file |
| 7 | + |
| 8 | + |
| 9 | +class Lattice(BaseElement): |
| 10 | + """A line of elements and/or other lines""" |
| 11 | + |
| 12 | + kind: Literal["Lattice"] = "Lattice" |
| 13 | + |
| 14 | + line: List[get_all_elements_as_annotation()] |
| 15 | + |
| 16 | + @model_validator(mode="before") |
| 17 | + @classmethod |
| 18 | + def unpack_json_structure(cls, data): |
| 19 | + """Deserialize the JSON/YAML/...-like dict for Lattice elements""" |
| 20 | + from pals.kinds.mixin.all_element_mixin import unpack_element_list_structure |
| 21 | + |
| 22 | + return unpack_element_list_structure(data, "line", "line") |
| 23 | + |
| 24 | + def model_dump(self, *args, **kwargs): |
| 25 | + """Custom model dump for Lattice to handle element list formatting""" |
| 26 | + from pals.kinds.mixin.all_element_mixin import dump_element_list |
| 27 | + |
| 28 | + return dump_element_list(self, "line", *args, **kwargs) |
| 29 | + |
| 30 | + @staticmethod |
| 31 | + def from_file(filename: str) -> "Lattice": |
| 32 | + """Load a Lattice from a text file""" |
| 33 | + pals_dict = load_file_to_dict(filename) |
| 34 | + return Lattice(**pals_dict) |
| 35 | + |
| 36 | + def to_file(self, filename: str): |
| 37 | + """Save a Lattice to a text file""" |
| 38 | + pals_dict = self.model_dump() |
| 39 | + store_dict_to_file(filename, pals_dict) |
0 commit comments