serializer.py
1.7 kB · python · 51 lines
1import numpy as np2from typing import Any, Dict, List, TYPE_CHECKING34if TYPE_CHECKING:5 from .models import Cell2d67def to_dict_2d(cell: "Cell2d") -> Dict[str, Any]:8 data = {9 "width": cell.width,10 "height": cell.height,11 }12 if cell._types is not None:13 types_list: Any = cell._types.tolist()14 data["types"] = types_list15 if cell._colors is not None:16 colors_list: Any = cell._colors.tolist()17 data["colors"] = colors_list18 if cell._tags is not None:19 tags_list: Any = cell._tags.tolist()20 data["tags"] = tags_list21 return data2223def from_dict_2d(data: Dict[str, Any]) -> "Cell2d":24 from .models import Cell2d25 width = data.get("width")26 height = data.get("height")27 types = np.array(data["types"], dtype=np.int8) if "types" in data else None28 colors = np.array(data["colors"], dtype=np.uint8) if "colors" in data else None29 tags = np.array(data["tags"], dtype=np.uint8) if "tags" in data else None30 return Cell2d(width=width, height=height, types=types, colors=colors, tags=tags)3132def to_array_2d(cell: "Cell2d") -> np.ndarray:33 return cell.types3435def from_array_2d(array: np.ndarray) -> "Cell2d":36 from .models import Cell2d37 return Cell2d(types=array)3839def to_list_2d(cell: "Cell2d") -> List[List[int]]:40 return cell.types.tolist()4142def from_list_2d(data: List[List[int]]) -> "Cell2d":43 from .models import Cell2d44 return Cell2d(types=np.array(data, dtype=np.int8))4546def to_strings_2d(cell: "Cell2d") -> List[str]:47 return ["".join(map(str, row)) for row in cell.types]4849def from_strings_2d(data: List[str]) -> "Cell2d":50 from .models import Cell2d51 return Cell2d(types=np.array([[int(char) for char in row] for row in data], dtype=np.int8))