File size: 4,129 Bytes
783ad76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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)