#!/usr/bin/env python3 """Validate the standardized OneScience oxide ASE databases.""" from __future__ import annotations import argparse import hashlib import json import math from pathlib import Path import numpy as np from ase.db import connect EXPECTED_COUNTS = {"train": 238, "val": 28, "test": 29} REQUIRED_METADATA = {"oxide", "polymorph", "xc"} 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 validate_split(path: Path, expected_count: int) -> dict[str, int]: require_file(path) database = connect(path) if database.count() != expected_count: raise ValueError(f"unexpected row count in {path}: {database.count()} != {expected_count}") oxides: set[str] = set() groups: set[tuple[str, str]] = set() for row in database.select(): missing = REQUIRED_METADATA - set(row.key_value_pairs) if missing: raise ValueError(f"missing metadata in {path} row {row.id}: {sorted(missing)}") if row.xc != "PBE": raise ValueError(f"unexpected xc in {path} row {row.id}: {row.xc!r}") atoms = row.toatoms() if len(atoms) == 0 or not atoms.pbc.all() or abs(atoms.get_volume()) <= 0: raise ValueError(f"invalid periodic structure in {path} row {row.id}") forces = np.asarray(row.forces, dtype=float) stress = np.asarray(row.stress, dtype=float) if forces.shape != (len(atoms), 3): raise ValueError(f"invalid forces shape in {path} row {row.id}: {forces.shape}") if stress.shape != (6,): raise ValueError(f"invalid stress shape in {path} row {row.id}: {stress.shape}") values = np.concatenate(([float(row.energy)], forces.reshape(-1), stress)) if not np.isfinite(values).all(): raise ValueError(f"non-finite target in {path} row {row.id}") oxides.add(str(row.oxide)) groups.add((str(row.oxide), str(row.polymorph))) return {"structures": database.count(), "oxide_count": len(oxides), "group_count": len(groups)} def validate_checksums(package_root: Path, manifest: Path) -> int: require_file(manifest) count = 0 for line_number, raw in enumerate(manifest.read_text(encoding="utf-8").splitlines(), 1): if not raw.strip(): continue digest, relative = raw.split(None, 1) target = package_root / relative require_file(target) if sha256_file(target) != digest: raise ValueError(f"checksum mismatch on line {line_number}: {relative}") count += 1 return count def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--dataset-root", default="data/OXIDES") parser.add_argument("--checksum-manifest", default="metadata/sha256_manifest.txt") parser.add_argument("--skip-checksum", action="store_true") args = parser.parse_args() root = Path(args.dataset_root) summary = { split: validate_split(root / "prepared" / f"{split}.db", count) for split, count in EXPECTED_COUNTS.items() } manifest = root / "manifest.json" require_file(manifest) metadata = json.loads(manifest.read_text(encoding="utf-8")) if metadata.get("counts") != EXPECTED_COUNTS: raise ValueError(f"manifest counts do not match expected counts: {metadata.get('counts')}") checksums = 0 if args.skip_checksum else validate_checksums(Path.cwd(), Path(args.checksum_manifest)) print("Oxides dataset validation passed") print(json.dumps(summary, sort_keys=True)) print(f"checksum entries verified: {checksums}") return 0 if __name__ == "__main__": raise SystemExit(main())