#!/usr/bin/env python3 """Validate the standardized OneScience MatPL dataset package.""" from __future__ import annotations import argparse import hashlib import sys from pathlib import Path import numpy as np EXPECTED_TOP_LEVEL = ["AuAg", "Cu", "HfO2", "LiSiC"] def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def require_file(path: Path) -> None: if not path.is_file(): raise FileNotFoundError(f"missing file: {path}") def require_dir(path: Path) -> None: if not path.is_dir(): raise FileNotFoundError(f"missing directory: {path}") def check_movement(path: Path) -> None: require_file(path) with path.open(encoding="utf-8", errors="replace") as handle: text = handle.read(4096) if not text.strip(): raise ValueError(f"empty MOVEMENT file: {path}") if "Iteration" not in text and "atoms" not in text.lower() and "lattice" not in text.lower(): raise ValueError(f"unexpected MOVEMENT header: {path}") def check_xyz(path: Path) -> None: require_file(path) with path.open(encoding="utf-8", errors="replace") as handle: first = handle.readline().strip() second = handle.readline() atoms = int(first) if atoms <= 0: raise ValueError(f"invalid xyz atom count in {path}") if not second: raise ValueError(f"missing xyz comment line in {path}") def check_npy(path: Path) -> None: require_file(path) arr = np.load(path, allow_pickle=False) if arr.size == 0: raise ValueError(f"empty npy array: {path}") def read_checksum_manifest(path: Path) -> list[tuple[str, str]]: require_file(path) entries: list[tuple[str, str]] = [] with path.open(encoding="utf-8") as handle: for line_no, raw in enumerate(handle, start=1): line = raw.strip() if not line: continue parts = line.split(None, 1) if len(parts) != 2: raise ValueError(f"invalid checksum line {line_no}: {raw!r}") entries.append((parts[0], parts[1])) return entries def validate_checksums(package_root: Path, manifest_path: Path) -> int: entries = read_checksum_manifest(manifest_path) for expected_hash, rel_path in entries: target = package_root / rel_path require_file(target) if sha256_file(target) != expected_hash: raise ValueError(f"checksum mismatch: {rel_path}") return len(entries) def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--dataset-root", default="data/MatPL") parser.add_argument("--checksum-manifest", default="metadata/sha256_manifest.txt") parser.add_argument("--skip-checksum", action="store_true") args = parser.parse_args() package_root = Path.cwd() dataset_root = Path(args.dataset_root) for name in EXPECTED_TOP_LEVEL: require_dir(dataset_root / name) check_movement(dataset_root / "Cu/pwdata/0_300_MOVEMENT") check_movement(dataset_root / "Cu/pwdata/1_500_MOVEMENT") check_movement(dataset_root / "Cu/pwdata/valid_movement") check_xyz(dataset_root / "AuAg/AuAg-5762.xyz") npy_files = sorted(dataset_root.glob("**/*.npy")) if len(npy_files) < 100: raise ValueError(f"too few npy files: {len(npy_files)}") for sample in npy_files[:8]: check_npy(sample) checksum_count = 0 if not args.skip_checksum: checksum_count = validate_checksums(package_root, Path(args.checksum_manifest)) print("MatPL dataset validation passed") print(f"top-level systems: {', '.join(EXPECTED_TOP_LEVEL)}") print(f"npy files: {len(npy_files)}") print(f"checksum entries verified: {checksum_count}") return 0 if __name__ == "__main__": try: raise SystemExit(main()) except Exception as exc: print(f"MatPL dataset validation failed: {exc}", file=sys.stderr) raise SystemExit(1)