File size: 4,988 Bytes
e579e7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Round-trip verification of the TRIP50 release artefacts.

Three checks, run in order:

  1.  MANIFEST.sha256 matches every payload file's actual digest.
  2.  Recomputed per-method MAE table from species.parquet reproduces the
      published trip50_dft_mae.csv to within 0.005 kcal/mol per cell.
  3.  Extended-XYZ round-trip: every frame's species_id, atomic_numbers, and
      positions agree with species.parquet to within 1e-7 Å (extxyz default
      8-digit precision).

Run from the release root or the examples/ directory.
"""

from __future__ import annotations

import hashlib
import sys
from pathlib import Path

import numpy as np
import pandas as pd
from ase.io import read

ROOT = Path(__file__).resolve().parent.parent
DATA = ROOT / "data"
PRODUCTION = Path("/Users/rpaton/TRIP50/production")

sys.path.insert(0, str(ROOT / "scripts"))
from trip50_core import reaction_quantities  # noqa: E402

POSITION_TOL = 1e-7
MAE_TOL = 0.005  # kcal/mol; published table has 3-dp rounding


def check_manifest() -> int:
    manifest = DATA / "MANIFEST.sha256"
    failed = 0
    for line in manifest.read_text().strip().splitlines():
        digest, name = line.split("  ", 1)
        actual = hashlib.sha256((DATA / name).read_bytes()).hexdigest()
        ok = actual == digest
        print(f"  {'ok ' if ok else 'BAD'} {name}")
        if not ok:
            failed += 1
    return failed


def _build_series(species: pd.DataFrame, slug_to_canonical: dict[str, str]) -> dict[str, pd.Series]:
    """For every method slug, return a Series indexed by species_id (post-alias
    canonical names) with energies in Hartree."""
    out = {}
    for slug, _display in slug_to_canonical.items():
        out[slug] = species.set_index("species_id")[slug]
    return out


def check_mae_table() -> int:
    species = pd.read_parquet(DATA / "species.parquet")
    methods = pd.read_json(DATA / "methods.json")["energy_columns"]
    slug_to_display = {m["slug"]: m["display_name"] for m in methods}
    aliases_df = pd.read_parquet(DATA / "aliases.parquet")
    alias_map = dict(zip(aliases_df["alias"], aliases_df["canonical"]))

    sp_indexed = species.set_index("species_id")
    dlpno = sp_indexed["energy_dlpno_ccsd_t"]
    ref_rxn, ref_fwd, ref_rev = reaction_quantities(dlpno, dlpno, alias_map)

    pub_path = PRODUCTION / "trip50_dft_mae.csv"
    if not pub_path.exists():
        print(f"  SKIP: {pub_path} not present (offline verification only)")
        return 0
    pub = pd.read_csv(pub_path).set_index("Theory")

    failed = 0
    for slug, display in slug_to_display.items():
        if display == "DLPNO-CCSD(T)" or display not in pub.index:
            continue
        col = sp_indexed[slug]
        t_rxn, t_fwd, t_rev = reaction_quantities(col, dlpno, alias_map)
        keys = sorted(set(ref_rxn) & set(t_rxn))
        mae_rxn = sum(abs(ref_rxn[k] - t_rxn[k]) for k in keys) / len(keys)
        mae_fwd = sum(abs(ref_fwd[k] - t_fwd[k]) for k in keys) / len(keys)
        mae_rev = sum(abs(ref_rev[k] - t_rev[k]) for k in keys) / len(keys)
        diffs = [
            abs(round(mae_rxn, 3) - pub.loc[display, "ΔE_rxn (P-R)"]),
            abs(round(mae_fwd, 3) - pub.loc[display, "ΔE_fwd (TS-R)"]),
            abs(round(mae_rev, 3) - pub.loc[display, "ΔE_rev (TS-P)"]),
        ]
        ok = max(diffs) < MAE_TOL
        if not ok:
            failed += 1
            print(f"  BAD {display}: max abs diff = {max(diffs):.4f} kcal/mol")
    print(f"  {'ok ' if failed == 0 else 'BAD'} MAE table reproduces "
          f"trip50_dft_mae.csv (max tol {MAE_TOL})")
    return failed


def check_extxyz_roundtrip() -> int:
    frames = read(DATA / "trip50.extxyz", index=":")
    species = pd.read_parquet(DATA / "species.parquet").set_index("species_id")
    failed = 0
    for atoms in frames:
        sid = atoms.info.get("species_id")
        if sid is None or sid not in species.index:
            print(f"  BAD frame missing/unknown species_id: {sid!r}")
            failed += 1
            continue
        row = species.loc[sid]
        if atoms.numbers.tolist() != list(row["atomic_numbers"]):
            print(f"  BAD {sid}: atomic_numbers mismatch")
            failed += 1
            continue
        pos = np.asarray(row["positions"].tolist())
        max_dev = float(np.abs(atoms.positions - pos).max())
        if max_dev > POSITION_TOL:
            print(f"  BAD {sid}: positions max dev {max_dev:.2e} Å > {POSITION_TOL}")
            failed += 1
    print(f"  {'ok ' if failed == 0 else 'BAD'} extxyz round-trip "
          f"({len(frames)} frames, tol {POSITION_TOL} Å)")
    return failed


def main() -> int:
    print("MANIFEST")
    f1 = check_manifest()
    print("\nMAE table")
    f2 = check_mae_table()
    print("\nExtxyz round-trip")
    f3 = check_extxyz_roundtrip()
    total = f1 + f2 + f3
    print(f"\n{'PASS' if total == 0 else 'FAIL'} ({total} failure(s))")
    return total


if __name__ == "__main__":
    sys.exit(main())