You've already forked HeurAMS-Legacy
80 lines
2.4 KiB
Python
80 lines
2.4 KiB
Python
from .electron import Electron
|
|
from .nucleon import Nucleon
|
|
from typing import TypedDict
|
|
import pathlib
|
|
import typing
|
|
import toml
|
|
import json
|
|
|
|
class AtomRegister(TypedDict):
|
|
nucleon: Nucleon
|
|
nucleon_path: pathlib.Path
|
|
nucleon_fmt: str
|
|
electron: Electron
|
|
electron_path: pathlib.Path
|
|
electron_fmt: str
|
|
orbital: dict
|
|
orbital_path: pathlib.Path
|
|
orbital_fmt: str
|
|
|
|
class Atom():
|
|
"""
|
|
统一处理一系列对象的所有信息与持久化:
|
|
关联电子 (算法数据)
|
|
关联核子 (内容数据)
|
|
关联轨道 (策略数据)
|
|
以及关联路径
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, ident = ""):
|
|
self.ident = ident
|
|
self.register: AtomRegister = { # type: ignore
|
|
"nucleon": None,
|
|
"nucleon_path": None,
|
|
"nucleon_fmt": "toml",
|
|
"electron": None,
|
|
"electron_path": None,
|
|
"electron_fmt": "json",
|
|
"orbital": None,
|
|
"orbital_path": None, # 允许设置为 None, 此时使用 nucleon 文件内的推荐配置
|
|
"orbital_fmt": "toml",
|
|
}
|
|
|
|
def link(self, key, value):
|
|
if key in self.register.keys():
|
|
self.register[key] = value
|
|
else:
|
|
raise ValueError("不受支持的原子元数据链接操作")
|
|
|
|
def persist(self, key):
|
|
path: pathlib.Path | None = self.register[key + "_path"]
|
|
if isinstance(path, pathlib.Path):
|
|
path = typing.cast(pathlib.Path, path)
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
if self.register[key + "_fmt"] == "toml":
|
|
with open(path, "w") as f:
|
|
toml.dump(self.register[key], f)
|
|
elif self.register[key + "_fmt"] == "json":
|
|
with open(path, "w") as f:
|
|
json.dump(self.register[key], f)
|
|
else:
|
|
raise KeyError("不受支持的持久化格式")
|
|
else:
|
|
raise TypeError("对未初始化的路径对象操作")
|
|
|
|
def __getitem__(self, key):
|
|
if key in self.register:
|
|
return self.register[key]
|
|
raise KeyError(f"不支持的键: {key}")
|
|
|
|
def __setitem__(self, key, value):
|
|
if key in self.register:
|
|
self.register[key] = value
|
|
else:
|
|
raise KeyError(f"不支持的键: {key}")
|
|
|
|
@staticmethod
|
|
def placeholder():
|
|
return (Electron.placeholder(), Nucleon.placeholder(), {}) |