File size: 3,970 Bytes
0933029 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | #!/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())
|