File size: 9,616 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
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
"""Build the TRIP50 Hugging Face release artefacts under ../data/.

Reads from /Users/rpaton/TRIP50/production/:
  - trip50_reference_energies.csv   (DLPNO + 46 DFT totals, Hartree)
  - trip50_species_aliases.csv      (alias → canonical map)
  - xyz_corrected/*.xyz             (156 standard XYZ files; comment line = multiplicity)

Writes to ../data/:
  - trip50.extxyz        : 156 frames, ASE-readable, all energies in info dict
  - species.parquet      : per-species table with atomic_numbers/positions/energies
  - reactions.parquet    : 50 rxn rows, alias-resolved species ids + reference Δs (kcal/mol)
  - aliases.parquet      : alias map mirrored as parquet (CSV is also copied)
  - aliases.csv          : verbatim copy of source alias table
  - methods.json         : slug ↔ display-name mapping for the 46 DFT columns
  - MANIFEST.sha256      : SHA-256 of every payload file (deterministic check)

The build is deterministic: sorted iteration, no timestamps in any payload.
"""

from __future__ import annotations

import hashlib
import json
import shutil
from pathlib import Path

import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
from ase import Atoms
from ase.io import write as ase_write

from trip50_core import (
    HARTREE_TO_KCAL,
    ROLES,
    lookup,
    reaction_quantities,
    slugify_method,
)

SRC = Path("/Users/rpaton/TRIP50/production")
OUT = Path(__file__).resolve().parent.parent / "data"
XYZ_DIR = SRC / "xyz_corrected"

REF_CSV = SRC / "trip50_reference_energies.csv"
ALIAS_CSV = SRC / "trip50_species_aliases.csv"

MULT_TO_INT = {"singlet": 1, "doublet": 2, "triplet": 3}

# Reaction categories from Figure 2 of Hughes, Popescu, Paton, JCTC 2026, 22, 3530.
RXN_CATEGORIES = (
    ("C-C",   range(1, 13)),
    ("C-O",   range(13, 18)),
    ("C-S",   range(18, 22)),
    ("HAT",   range(22, 31)),
    ("Si-X",  range(31, 38)),
    ("C-Hal", range(38, 42)),
    ("N-X",   range(42, 51)),
)
RXN_CATEGORY = {r: name for name, rng in RXN_CATEGORIES for r in rng}
assert set(RXN_CATEGORY) == set(range(1, 51)), "category ranges must tile 1..50 exactly"


def parse_xyz(path: Path) -> tuple[Atoms, str]:
    """Parse a TRIP50 standard-XYZ file. Returns (Atoms, multiplicity_label)."""
    lines = path.read_text().splitlines()
    n = int(lines[0].strip())
    mult = lines[1].strip()
    symbols, coords = [], []
    for line in lines[2:2 + n]:
        parts = line.split()
        symbols.append(parts[0])
        coords.append([float(x) for x in parts[1:4]])
    atoms = Atoms(symbols=symbols, positions=np.asarray(coords, dtype=np.float64))
    return atoms, mult


def species_id_from_filename(path: Path) -> str:
    return path.stem  # e.g. "1-R1.xyz" → "1-R1"


def split_rxn_role(species_id: str) -> tuple[int, str]:
    rxn_str, role = species_id.split("-", 1)
    return int(rxn_str), role


def build():
    OUT.mkdir(parents=True, exist_ok=True)

    # -------------------- inputs --------------------
    ref = pd.read_csv(REF_CSV).set_index("Species")
    aliases_df = pd.read_csv(ALIAS_CSV)
    alias_map = dict(zip(aliases_df["alias"], aliases_df["canonical"]))
    dlpno_col = "DLPNO-CCSD(T)"

    # Method display names → slugs (DLPNO + 46 DFT)
    method_columns = list(ref.columns)
    slug_map = {col: ("energy_dlpno_ccsd_t" if col == dlpno_col
                      else f"energy_{slugify_method(col)}")
                for col in method_columns}
    # Verify uniqueness
    if len(set(slug_map.values())) != len(slug_map):
        dupes = [s for s in slug_map.values() if list(slug_map.values()).count(s) > 1]
        raise RuntimeError(f"Slug collision: {set(dupes)}")

    methods_meta = {
        "energy_columns": [
            {"slug": slug_map[col], "display_name": col,
             "is_reference": col == dlpno_col,
             "units": "hartree"}
            for col in method_columns
        ],
    }
    (OUT / "methods.json").write_text(json.dumps(methods_meta, indent=2) + "\n")

    # -------------------- structures + per-species rows --------------------
    xyz_paths = sorted(XYZ_DIR.glob("*.xyz"),
                       key=lambda p: split_rxn_role(p.stem))

    species_rows = []
    frames: list[Atoms] = []

    for xyz_path in xyz_paths:
        species_id = species_id_from_filename(xyz_path)
        atoms, mult_label = parse_xyz(xyz_path)
        rxn_id, role = split_rxn_role(species_id)

        if mult_label not in MULT_TO_INT:
            raise ValueError(f"Unknown multiplicity {mult_label!r} in {xyz_path}")
        spin_mult = MULT_TO_INT[mult_label]

        # Pull every method's total energy for this species (alias-resolved)
        per_method = {}
        for col in method_columns:
            val = lookup(species_id, ref[col], alias_map)
            if val is None:
                raise RuntimeError(f"Missing {col} energy for {species_id}")
            per_method[slug_map[col]] = float(val)

        # Frame info dict — ASE will serialise this onto the comment line
        info = {
            "species_id": species_id,
            "rxn": rxn_id,
            "role": role,
            "multiplicity": mult_label,
            "spin_multiplicity": spin_mult,
            "charge": 0,
            "units_energy": "hartree",
            **per_method,
        }
        atoms.info.update(info)
        frames.append(atoms)

        species_rows.append({
            "species_id": species_id,
            "rxn_id": rxn_id,
            "role": role,
            "n_atoms": len(atoms),
            "atomic_numbers": atoms.numbers.tolist(),
            "positions": atoms.positions.tolist(),
            "charge": 0,
            "multiplicity": mult_label,
            "spin_multiplicity": spin_mult,
            **per_method,
        })

    # -------------------- write extxyz --------------------
    extxyz_path = OUT / "trip50.extxyz"
    ase_write(extxyz_path, frames, format="extxyz")

    # -------------------- write species.parquet --------------------
    species_df = pd.DataFrame(species_rows)
    species_schema = pa.schema([
        ("species_id", pa.string()),
        ("rxn_id", pa.int32()),
        ("role", pa.string()),
        ("n_atoms", pa.int32()),
        ("atomic_numbers", pa.list_(pa.int8())),
        ("positions", pa.list_(pa.list_(pa.float64(), 3))),
        ("charge", pa.int8()),
        ("multiplicity", pa.string()),
        ("spin_multiplicity", pa.int8()),
        *[(slug_map[col], pa.float64()) for col in method_columns],
    ])
    species_table = pa.Table.from_pandas(species_df, schema=species_schema, preserve_index=False)
    pq.write_table(species_table, OUT / "species.parquet", compression="zstd")

    # -------------------- reactions.parquet --------------------
    dlpno_series = ref[dlpno_col]
    dE_rxn, dE_fwd, dE_rev = reaction_quantities(dlpno_series, dlpno_series, alias_map)

    reaction_rows = []
    for r in range(1, 51):
        present = {role: lookup(f"{r}-{role}", dlpno_series, alias_map) is not None
                   for role in ROLES}

        def canonical(role):
            sid = f"{r}-{role}"
            return alias_map.get(sid, sid) if present[role] else None

        reaction_rows.append({
            "rxn_id": r,
            "category": RXN_CATEGORY[r],
            "r1_species_id": canonical("R1"),
            "r2_species_id": canonical("R2"),
            "ts_species_id": canonical("TS"),
            "p1_species_id": canonical("P1"),
            "p2_species_id": canonical("P2"),
            "is_unimolecular_reactant": not present["R2"],
            "is_unimolecular_product": not present["P2"],
            "dE_rxn_kcal_dlpno": dE_rxn.get(r),
            "dE_fwd_kcal_dlpno": dE_fwd.get(r),
            "dE_rev_kcal_dlpno": dE_rev.get(r),
        })

    reactions_df = pd.DataFrame(reaction_rows)
    reactions_schema = pa.schema([
        ("rxn_id", pa.int32()),
        ("category", pa.string()),
        ("r1_species_id", pa.string()),
        ("r2_species_id", pa.string()),
        ("ts_species_id", pa.string()),
        ("p1_species_id", pa.string()),
        ("p2_species_id", pa.string()),
        ("is_unimolecular_reactant", pa.bool_()),
        ("is_unimolecular_product", pa.bool_()),
        ("dE_rxn_kcal_dlpno", pa.float64()),
        ("dE_fwd_kcal_dlpno", pa.float64()),
        ("dE_rev_kcal_dlpno", pa.float64()),
    ])
    reactions_table = pa.Table.from_pandas(reactions_df, schema=reactions_schema, preserve_index=False)
    pq.write_table(reactions_table, OUT / "reactions.parquet", compression="zstd")

    # -------------------- aliases --------------------
    shutil.copyfile(ALIAS_CSV, OUT / "aliases.csv")
    aliases_table = pa.Table.from_pandas(aliases_df, preserve_index=False)
    pq.write_table(aliases_table, OUT / "aliases.parquet", compression="zstd")

    # -------------------- MANIFEST --------------------
    payload = sorted([
        OUT / "trip50.extxyz",
        OUT / "species.parquet",
        OUT / "reactions.parquet",
        OUT / "aliases.parquet",
        OUT / "aliases.csv",
        OUT / "methods.json",
    ])
    manifest_lines = []
    for path in payload:
        digest = hashlib.sha256(path.read_bytes()).hexdigest()
        manifest_lines.append(f"{digest}  {path.name}")
    (OUT / "MANIFEST.sha256").write_text("\n".join(manifest_lines) + "\n")

    print(f"Wrote {len(species_df)} species frames, {len(reactions_df)} reactions to {OUT}")
    for path in payload + [OUT / "MANIFEST.sha256"]:
        size = path.stat().st_size
        print(f"  {path.name:30s} {size:>10,} B")


if __name__ == "__main__":
    build()