TheBird

serialization.py

2.3 kB · python · 80 lines

1import json2import mrlypy.two as m23import mrlypy.three as m34from mrlypy.core.colors import blue, red, white5from mrlypy.core.enums import Mode6import numpy as np7from config import DATA_DIR89def cell_2d():10    cell = m2.carpet_2d(3, 1)11    cell.neighbors(m2.net_2d(3).types)12    cell.paint({0: [red, blue], 1: [white]}, mode=Mode.TAG)13    return cell1415def cell_3d():16    cell = m3.carpet_3d(3, 1)17    cell.neighbors()18    cell.paint({0: [red, blue], 1: [white]}, mode=Mode.TAG)19    return cell2021def test_dict(name, cls, cell):22    fp = f"{DATA_DIR}/cell_{name}_dict.json"23    data = cell.to_dict()24    with open(fp, "w") as f:25        json.dump(data, f)26    print(f"Saved: {fp}")27    with open(fp, "r") as f:28        data = json.load(f)29    print(f"Loaded: {fp}")30    cell = cls.from_dict(data)31    print(json.dumps(cell.to_dict()))3233def test_strings(name, cls, cell):34    fp = f"{DATA_DIR}/cell_{name}_strings.json"35    data = cell.to_strings()36    with open(fp, "w") as f:37        json.dump(data, f)38    print(f"Saved: {fp}")39    with open(fp, "r") as f:40        data = json.load(f)41    print(f"Loaded: {fp}")42    cell = cls.from_strings(data)43    print(json.dumps(cell.to_strings()))4445def test_array(name, cls, cell):46    fp = f"{DATA_DIR}/cell_{name}_array.json"47    data = cell.to_array()48    with open(fp, "w") as f:49        json.dump(data.tolist(), f)50    print(f"Saved: {fp}")51    with open(fp, "r") as f:52        data = json.load(f)53    print(f"Loaded: {fp}")54    cell = cls.from_array(np.array(data, dtype=np.int8))55    print(json.dumps(cell.to_array().tolist()))5657def test_list(name, cls, cell):58    fp = f"{DATA_DIR}/cell_{name}_list.json"59    data = cell.to_list()60    with open(fp, "w") as f:61        json.dump(data, f)62    print(f"Saved: {fp}")63    with open(fp, "r") as f:64        data = json.load(f)65    print(f"Loaded: {fp}")66    cell = cls.from_list(data)67    print(json.dumps(cell.to_list()))6869def main():70    test_dict("2d", m2.Cell2d, cell_2d())71    test_dict("3d", m3.Cell3d, cell_3d())72    test_strings("2d", m2.Cell2d, cell_2d())73    test_strings("3d", m3.Cell3d, cell_3d())74    test_array("2d", m2.Cell2d, cell_2d())75    test_array("3d", m3.Cell3d, cell_3d())76    test_list("2d", m2.Cell2d, cell_2d())77    test_list("3d", m3.Cell3d, cell_3d())7879if __name__ == "__main__":80    main()