serializer.py

1.9 kB · python · 53 lines

1import numpy as np2from typing import Any, Dict, List, TYPE_CHECKING34if TYPE_CHECKING:5    from .models import Cell3d67def to_dict_3d(cell: "Cell3d") -> Dict[str, Any]:8    data = {9        "width": cell.width,10        "height": cell.height,11        "depth": cell.depth,12    }13    if cell._types is not None:14        types_list: Any = cell._types.tolist()15        data["types"] = types_list16    if cell._colors is not None:17        colors_list: Any = cell._colors.tolist()18        data["colors"] = colors_list19    if cell._tags is not None:20        tags_list: Any = cell._tags.tolist()21        data["tags"] = tags_list22    return data2324def from_dict_3d(data: Dict[str, Any]) -> "Cell3d":25    from .models import Cell3d26    width = data.get("width")27    height = data.get("height")28    depth = data.get("depth")29    types = np.array(data["types"], dtype=np.int8) if "types" in data else None30    colors = np.array(data["colors"], dtype=np.uint8) if "colors" in data else None31    tags = np.array(data["tags"], dtype=np.uint8) if "tags" in data else None32    return Cell3d(width=width, height=height, depth=depth, types=types, colors=colors, tags=tags)3334def to_array_3d(cell: "Cell3d") -> np.ndarray:35    return cell.types3637def from_array_3d(array: np.ndarray) -> "Cell3d":38    from .models import Cell3d39    return Cell3d(types=array)4041def to_list_3d(cell: "Cell3d") -> List[List[List[int]]]:42    return cell.types.tolist()4344def from_list_3d(data: List[List[List[int]]]) -> "Cell3d":45    from .models import Cell3d46    return Cell3d(types=np.array(data, dtype=np.int8))4748def to_strings_3d(cell: "Cell3d") -> List[List[str]]:49    return [["".join(map(str, row)) for row in layer] for layer in cell.types]5051def from_strings_3d(data: List[List[str]]) -> "Cell3d":52    from .models import Cell3d53    return Cell3d(types=np.array([[[int(char) for char in row] for row in layer] for layer in data], dtype=np.int8))