File size: 7,937 Bytes
d0a5d19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#!/usr/bin/env python3
"""Validate the standardized OC20 extxyz dataset package."""

from __future__ import annotations

import argparse
import hashlib
import re
from pathlib import Path


EXPECTED_SPLITS = {
    "s2ef_200k_uncompressed": {
        "files": ["0.extxyz", "1.extxyz"],
        "expected_total_frames": 10000,
    },
    "s2ef_val_id_uncompressed": {
        "files": ["0.extxyz", "1.extxyz", "2.extxyz", "3.extxyz"],
        "expected_total_frames": 20000,
    },
}
EXPECTED_ENERGY_KEY = "energy"
EXPECTED_FORCES_KEY = "forces"
EXPECTED_ELEMENTS = {
    "Ag", "Al", "As", "Au", "B", "Bi", "C", "Ca", "Cd", "Cl", "Co", "Cr", "Cs", "Cu",
    "Fe", "Ga", "Ge", "H", "Hf", "Hg", "In", "Ir", "K", "Mn", "Mo", "N", "Na", "Nb",
    "Ni", "O", "Os", "P", "Pb", "Pd", "Pt", "Rb", "Re", "Rh", "Ru", "S", "Sb", "Sc",
    "Se", "Si", "Sn", "Sr", "Ta", "Tc", "Te", "Ti", "Tl", "V", "W", "Y", "Zn", "Zr",
}


def sha256_file(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(1024 * 1024), b""):
            h.update(chunk)
    return h.hexdigest()


def validate_checksum_manifest(dataset_root: Path, manifest_path: Path) -> None:
    checked = 0
    with manifest_path.open("r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            digest, rel = line.split(maxsplit=1)
            path = dataset_root.parent.parent / rel
            if not path.exists():
                raise SystemExit(f"[FAIL] 清单文件不存在: {path}")
            actual = sha256_file(path)
            if actual != digest:
                raise SystemExit(f"[FAIL] SHA256 不一致: {rel}")
            checked += 1
    print(f"[OK] SHA256 清单验证通过: {checked} 个文件")


def parse_properties(comment: str) -> list[tuple[str, str, int]]:
    match = re.search(r'Properties=("[^"]+"|\S+)', comment)
    if not match:
        raise SystemExit("[FAIL] extxyz comment 缺少 Properties")
    raw = match.group(1).strip('"')
    parts = raw.split(":")
    if len(parts) % 3:
        raise SystemExit(f"[FAIL] Properties 格式异常: {raw}")
    parsed = []
    for i in range(0, len(parts), 3):
        name, kind, width = parts[i], parts[i + 1], int(parts[i + 2])
        parsed.append((name, kind, width))
    return parsed


def validate_xyz(path: Path) -> int:
    frames = 0
    elements: set[str] = set()
    min_atoms: int | None = None
    max_atoms = 0

    with path.open("r", encoding="utf-8") as f:
        while True:
            first = f.readline()
            if not first:
                break
            if not first.strip():
                continue
            try:
                atom_count = int(first.strip())
            except ValueError as exc:
                raise SystemExit(f"[FAIL] 原子数行不是整数: {path}:{frames + 1}") from exc
            comment = f.readline().rstrip("\n")
            if f"{EXPECTED_ENERGY_KEY}=" not in comment:
                raise SystemExit(f"[FAIL] comment 缺少 {EXPECTED_ENERGY_KEY}: {path} frame {frames}")
            if "free_energy=" not in comment:
                raise SystemExit(f"[FAIL] comment 缺少 free_energy: {path} frame {frames}")
            if "pbc=" not in comment:
                raise SystemExit(f"[FAIL] comment 缺少 pbc: {path} frame {frames}")
            if "Lattice=" not in comment:
                raise SystemExit(f"[FAIL] comment 缺少 Lattice: {path} frame {frames}")
            props = parse_properties(comment)
            prop_names = [p[0] for p in props]
            if prop_names[0:2] != ["species", "pos"]:
                raise SystemExit(f"[FAIL] Properties 前两项必须是 species,pos: {path} frame {frames}")
            if EXPECTED_FORCES_KEY not in prop_names:
                raise SystemExit(f"[FAIL] Properties 缺少 {EXPECTED_FORCES_KEY}: {path} frame {frames}")
            if "move_mask" not in prop_names:
                raise SystemExit(f"[FAIL] Properties 缺少 move_mask: {path} frame {frames}")
            if "tags" not in prop_names:
                raise SystemExit(f"[FAIL] Properties 缺少 tags: {path} frame {frames}")
            expected_cols = sum(width for _, _, width in props)

            for atom_index in range(atom_count):
                atom_line = f.readline()
                if not atom_line:
                    raise SystemExit(f"[FAIL] 文件提前结束: {path} frame {frames}")
                cols = atom_line.split()
                if len(cols) != expected_cols:
                    raise SystemExit(
                        f"[FAIL] 原子列数异常: {path} frame {frames} atom {atom_index}: "
                        f"{len(cols)} != {expected_cols}"
                    )
                elements.add(cols[0])
                col_idx = 1
                for _, kind, width in props:
                    if kind == "S":
                        continue
                    values = cols[col_idx:col_idx + width]
                    if kind == "R":
                        for value in values:
                            float(value)
                    elif kind == "I":
                        for value in values:
                            int(value)
                    elif kind == "L":
                        for value in values:
                            if value not in ("T", "F"):
                                raise SystemExit(
                                    f"[FAIL] bool 字段值异常: {value} at {path} frame {frames}"
                                )
                    else:
                        raise SystemExit(f"[FAIL] 不支持的 Properties 类型: {kind}")
                    col_idx += width
            frames += 1
            min_atoms = atom_count if min_atoms is None else min(min_atoms, atom_count)
            max_atoms = max(max_atoms, atom_count)

    if not elements.issubset(EXPECTED_ELEMENTS):
        raise SystemExit(f"[FAIL] 元素集合异常: {sorted(elements)}")
    print(
        f"[OK] {path.name}: frames={frames}, atoms={min_atoms}-{max_atoms}, "
        f"elements={sorted(elements)[:5]}..."
    )
    return frames


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--dataset-root", default="data/oc20")
    parser.add_argument("--checksum-manifest", default="metadata/sha256_manifest.txt")
    args = parser.parse_args()

    repo_root = Path.cwd()
    dataset_root = Path(args.dataset_root)
    if not dataset_root.is_absolute():
        dataset_root = repo_root / dataset_root
    checksum_manifest = Path(args.checksum_manifest)
    if not checksum_manifest.is_absolute():
        checksum_manifest = repo_root / checksum_manifest

    if not dataset_root.exists():
        raise SystemExit(f"[FAIL] 数据目录不存在: {dataset_root}")

    for split_name, split_info in EXPECTED_SPLITS.items():
        split_dir = dataset_root / split_name
        if not split_dir.exists():
            raise SystemExit(f"[FAIL] 缺少 split 目录: {split_dir}")
        total_frames = 0
        for file_name in split_info["files"]:
            path = split_dir / file_name
            if not path.exists():
                raise SystemExit(f"[FAIL] 缺少文件: {path}")
            if path.stat().st_size <= 0:
                raise SystemExit(f"[FAIL] 文件为空: {path}")
            total_frames += validate_xyz(path)
        expected = split_info["expected_total_frames"]
        if total_frames != expected:
            raise SystemExit(
                f"[FAIL] {split_name} 总帧数异常: {total_frames} != {expected}"
            )
        print(f"[OK] {split_name}: total_frames={total_frames}")

    validate_checksum_manifest(dataset_root, checksum_manifest)
    print("[OK] OC20 数据集读取验证通过")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())