File size: 5,327 Bytes
f02834e | 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 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | #!/usr/bin/env python3
"""Validate the standardized OneScience MP-20 dataset package."""
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import sys
from pathlib import Path
import numpy as np
EXPECTED_SPLITS = {"train": 27136, "val": 9047, "test": 9046}
REQUIRED_COLUMNS = {
"material_id",
"formation_energy_per_atom",
"dft_band_gap",
"pretty_formula",
"elements",
"cif",
"spacegroup_number",
"dft_bulk_modulus",
"dft_mag_density",
}
REQUIRED_ARRAYS = {
"atomic_numbers.npy",
"cell.npy",
"num_atoms.npy",
"pos.npy",
"structure_id.npy",
}
PROPERTY_FILES = {
"formation_energy_per_atom.json",
"dft_band_gap.json",
"dft_bulk_modulus.json",
"dft_mag_density.json",
}
def require_file(path: Path) -> None:
if not path.is_file():
raise FileNotFoundError(f"missing file: {path}")
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 validate_csv(path: Path, expected_rows: int) -> None:
require_file(path)
with path.open(encoding="utf-8", newline="") as handle:
reader = csv.DictReader(handle)
columns = set(reader.fieldnames or [])
missing = REQUIRED_COLUMNS - columns
if missing:
raise ValueError(f"missing CSV columns in {path}: {sorted(missing)}")
rows = sum(1 for _ in reader)
if rows != expected_rows:
raise ValueError(f"unexpected CSV rows in {path}: {rows} != {expected_rows}")
def validate_cache(path: Path, expected_structures: int) -> None:
for name in REQUIRED_ARRAYS | PROPERTY_FILES:
require_file(path / name)
atomic_numbers = np.load(path / "atomic_numbers.npy", mmap_mode="r", allow_pickle=False)
cells = np.load(path / "cell.npy", mmap_mode="r", allow_pickle=False)
num_atoms = np.load(path / "num_atoms.npy", mmap_mode="r", allow_pickle=False)
positions = np.load(path / "pos.npy", mmap_mode="r", allow_pickle=False)
structure_ids = np.load(path / "structure_id.npy", mmap_mode="r", allow_pickle=False)
if cells.shape != (expected_structures, 3, 3):
raise ValueError(f"unexpected cell shape in {path}: {cells.shape}")
if num_atoms.shape != (expected_structures,):
raise ValueError(f"unexpected num_atoms shape in {path}: {num_atoms.shape}")
if structure_ids.shape != (expected_structures,):
raise ValueError(f"unexpected structure_id shape in {path}: {structure_ids.shape}")
total_atoms = int(num_atoms.sum())
if atomic_numbers.shape != (total_atoms,):
raise ValueError(f"atomic_numbers and num_atoms disagree in {path}")
if positions.shape != (total_atoms, 3):
raise ValueError(f"positions and num_atoms disagree in {path}")
for name in PROPERTY_FILES:
payload = json.loads((path / name).read_text(encoding="utf-8"))
if len(payload.get("values", [])) != expected_structures:
raise ValueError(f"unexpected property length in {path / name}")
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, relative_path in entries:
target = package_root / relative_path
require_file(target)
if sha256_file(target) != expected_hash:
raise ValueError(f"checksum mismatch: {relative_path}")
return len(entries)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dataset-root", default="data/MP20")
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)
raw_root = dataset_root / "raw/mp_20"
cache_root = dataset_root / "cache/mp_20"
for split, expected_count in EXPECTED_SPLITS.items():
validate_csv(raw_root / f"{split}.csv", expected_count)
validate_cache(cache_root / split, expected_count)
checksum_count = 0
if not args.skip_checksum:
checksum_count = validate_checksums(package_root, Path(args.checksum_manifest))
print("MP-20 dataset validation passed")
print(f"structures: {sum(EXPECTED_SPLITS.values())}")
print(f"splits: {EXPECTED_SPLITS}")
print(f"checksum entries verified: {checksum_count}")
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except Exception as exc:
print(f"MP-20 dataset validation failed: {exc}", file=sys.stderr)
raise SystemExit(1)
|