Download scripts/validate_mp20.py from OneScience-Group/mp20: direct link, hf CLI and curl.
- Browser
- Download file 5.33 kB
-
https://huggingface.co/datasets/OneScience-Group/mp20/resolve/main/scripts/validate_mp20.py
- Command line
-
hf download hf://datasets/OneScience-Group/mp20/scripts/validate_mp20.py
-
curl -L -o validate_mp20.py https://huggingface.co/datasets/OneScience-Group/mp20/resolve/main/scripts/validate_mp20.py
5.33 kB
| #!/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) | |