water / scripts /validate_water.py
Zhongning's picture
Upload folder using huggingface_hub
d4402d6 verified
Raw
History Blame Contribute Delete
6.19 kB
#!/usr/bin/env python3
"""Validate the standardized water extxyz dataset package."""
from __future__ import annotations
import argparse
import hashlib
import re
from pathlib import Path
EXPECTED_FILES = {
"dataset_1593.xyz": 1593,
"water_train.xyz": 1393,
"water_test.xyz": 200,
}
EXPECTED_ATOMS_PER_FRAME = 192
EXPECTED_ELEMENTS = {"H", "O"}
def sha256_file(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def validate_checksum_manifest(dataset_root: Path, manifest_path: Path) -> None:
checked = 0
with manifest_path.open("r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
digest, rel = line.split(maxsplit=1)
path = dataset_root / rel
if not path.exists():
raise SystemExit(f"[FAIL] 清单文件不存在: {path}")
actual = sha256_file(path)
if actual != digest:
raise SystemExit(f"[FAIL] SHA256 不一致: {rel}")
checked += 1
expected_manifest_files = len(EXPECTED_FILES) + 1
if checked != expected_manifest_files:
raise SystemExit(f"[FAIL] SHA256 清单文件数异常: {checked}")
print(f"[OK] SHA256 清单验证通过: {checked} 个文件")
def parse_properties(comment: str) -> list[tuple[str, str, int]]:
match = re.search(r'Properties=("[^"]+"|\S+)', comment)
if not match:
raise SystemExit("[FAIL] extxyz comment 缺少 Properties")
raw = match.group(1).strip('"')
parts = raw.split(":")
if len(parts) % 3:
raise SystemExit(f"[FAIL] Properties 格式异常: {raw}")
parsed = []
for i in range(0, len(parts), 3):
name, kind, width = parts[i], parts[i + 1], int(parts[i + 2])
parsed.append((name, kind, width))
return parsed
def validate_xyz(path: Path, expected_frames: int) -> None:
frames = 0
elements: set[str] = set()
with path.open("r", encoding="utf-8") as f:
while True:
first = f.readline()
if not first:
break
if not first.strip():
continue
try:
atom_count = int(first.strip())
except ValueError as exc:
raise SystemExit(f"[FAIL] 原子数行不是整数: {path}:{frames + 1}") from exc
if atom_count != EXPECTED_ATOMS_PER_FRAME:
raise SystemExit(
f"[FAIL] 原子数异常: {path.name} frame {frames}: "
f"{atom_count} != {EXPECTED_ATOMS_PER_FRAME}"
)
comment = f.readline().rstrip("\n")
for key in ("TotEnergy=", "pbc=", "Lattice=", "Properties="):
if key not in comment:
raise SystemExit(f"[FAIL] comment 缺少 {key}: {path} frame {frames}")
props = parse_properties(comment)
prop_names = [p[0] for p in props]
if prop_names != ["species", "pos", "force", "Z"]:
raise SystemExit(f"[FAIL] Properties 必须是 species,pos,force,Z: {path} frame {frames}")
expected_cols = sum(width for _, _, width in props)
if expected_cols != 8:
raise SystemExit(f"[FAIL] 原子列数 schema 异常: {path} frame {frames}")
for atom_index in range(atom_count):
atom_line = f.readline()
if not atom_line:
raise SystemExit(f"[FAIL] 文件提前结束: {path} frame {frames}")
cols = atom_line.split()
if len(cols) != expected_cols:
raise SystemExit(
f"[FAIL] 原子列数异常: {path} frame {frames} atom {atom_index}: "
f"{len(cols)} != {expected_cols}"
)
elements.add(cols[0])
for value in cols[1:7]:
float(value)
int(cols[7])
frames += 1
if frames != expected_frames:
raise SystemExit(f"[FAIL] 帧数异常: {path.name}: {frames} != {expected_frames}")
if not elements.issubset(EXPECTED_ELEMENTS):
raise SystemExit(f"[FAIL] 元素集合异常: {sorted(elements)}")
print(f"[OK] {path.name}: frames={frames}, atoms_per_frame=192, elements={sorted(elements)}")
def validate_split_reconstruction(dataset_root: Path) -> None:
full = (dataset_root / "dataset_1593.xyz").read_bytes()
train = (dataset_root / "water_train.xyz").read_bytes()
test = (dataset_root / "water_test.xyz").read_bytes()
if train + test != full:
raise SystemExit("[FAIL] water_train.xyz + water_test.xyz 不能字节级还原 dataset_1593.xyz")
print("[OK] train/test split 可字节级还原原始 dataset_1593.xyz")
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--dataset-root", default="data/water")
parser.add_argument("--checksum-manifest", default="metadata/sha256_manifest.txt")
args = parser.parse_args()
repo_root = Path.cwd()
dataset_root = Path(args.dataset_root)
if not dataset_root.is_absolute():
dataset_root = repo_root / dataset_root
checksum_manifest = Path(args.checksum_manifest)
if not checksum_manifest.is_absolute():
checksum_manifest = repo_root / checksum_manifest
if not dataset_root.exists():
raise SystemExit(f"[FAIL] 数据目录不存在: {dataset_root}")
for name, expected_frames in EXPECTED_FILES.items():
path = dataset_root / name
if not path.exists():
raise SystemExit(f"[FAIL] 缺少文件: {path}")
if path.stat().st_size <= 0:
raise SystemExit(f"[FAIL] 文件为空: {path}")
validate_xyz(path, expected_frames)
validate_split_reconstruction(dataset_root)
validate_checksum_manifest(dataset_root, checksum_manifest)
print("[OK] water 数据集读取验证通过")
return 0
if __name__ == "__main__":
raise SystemExit(main())