File size: 11,693 Bytes
a03fc9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
264
265
266
267
268
269
270
271
272
273
274
275
276
#!/usr/bin/env python3
"""Replay the frozen UltraMS MSnLib formula-level split (split A) from MSnLib.csv.

The split is defined by one rule: **every spectrum of a molecular formula belongs to
exactly one fold**.  The official multiple-spectrum voting unit is the MSnLib source SMILES
string: 5,002 groups covering 57,436 of the 57,437 test spectra.  The fold of each formula is the frozen assignment carried by the
`fold` column of `MSnLib.csv` (560,084 spectra, 21,107 molecular formulas), and the
per-fold counts are 16,885 / 2,110 / 2,112 formulas and 446,667 / 55,980 / 57,437
spectra for train / validation / test.  This script recomputes the formula of every
spectrum with RDKit, verifies that the fold is formula-consistent, rebuilds the shipped
tables in memory and compares their SHA-256 with the frozen values.  With
`--output-dir` it also writes the tables.

Usage
-----
    # read-only replay + hash check (nothing written):
    python3 build_split_a.py --csv /path/to/workspace/datasets/MSnLib/MSnLib.csv

    # same, and write the tables:
    python3 build_split_a.py --csv ... --output-dir replay_split_a

Requirements: Python >= 3.10 and RDKit 2026.03.5 (the frozen canonicalisation runtime).
Other RDKit patch releases can serialise the same molecule differently; use
`--lenient-rdkit` to downgrade the resulting table-hash mismatches to warnings.
"""
from __future__ import annotations

import argparse
import collections
import csv
import hashlib
import io
import json
import sys

from rdkit import Chem, RDLogger
from rdkit.Chem import rdMolDescriptors

RDLogger.DisableLog("rdApp.*")
csv.field_size_limit(10**9)

FOLD_ORDER = ["train", "val", "test"]

SOURCE_CSV_SHA256 = "be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07"
EXPECTED = {
    "n_data_rows": 560084,
    "n_unique_formula": 21107,
    "n_formula_train": 16885,
    "n_formula_val": 2110,
    "n_formula_test": 2112,
    "n_spectra_train": 446667,
    "n_spectra_val": 55980,
    "n_spectra_test": 57437,
    "n_voting_groups_official": 5002,
    "n_voting_spectra_official": 57436,
    "n_voting_groups_canonical": 4888,
    "n_voting_spectra_canonical": 57436,
}
FROZEN = {
    "formula_split.csv": (424350, "fcc44d1996d25306c884a6f8da30c1447fbe74f93c6fa12a3f271c0475a704b8"),
    "row_formula_fold.csv": (13351630, "ac6113867fdda683304533f097fc7287c13271a2deac8e792d1316dcf00264ff"),
    "test_spectra.csv": (7751575, "f2a870ba8ac9a54a36feaf1ecc12929ad9250ade2d082dc31454028c4b66b548"),
    "val_spectra.csv": (7421554, "f4fa5e0f8875991bf9df2bcb67a05437271ee18c317f33d9108f3ec28a887a82"),
    "test_molecules_voting.csv": (276185, "edad6ec7d6b6f9fc4763deac5245207aee767c78661532621c87acc5a9b1ee07"),
    "test_molecules_voting_canonical_view.csv": (269502, "9fcd16ff4159e665833ea145848f94bee7c44115f4a858dd75fe486f15e92bd0"),
}
CANONICAL_DEPENDENT = {"test_spectra.csv", "val_spectra.csv", "test_molecules_voting.csv",
                       "test_molecules_voting_canonical_view.csv"}


def sha256(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def compute(smiles):
    mol = Chem.MolFromSmiles(smiles)
    if mol is None:
        return None, None
    return rdMolDescriptors.CalcMolFormula(mol), Chem.MolToSmiles(mol)


def replay(csv_path: str):
    cache = {}
    bad = []
    bad_folds = collections.Counter()
    fold_counts = collections.Counter()
    formula_spectra = collections.Counter()
    formula_folds = collections.defaultdict(set)
    fold_formulas = collections.defaultdict(set)
    formula_rows = []
    test_rows = []
    val_rows = []

    with open(csv_path, newline="") as fh:
        reader = csv.reader(fh)
        header = next(reader)
        col = {name: i for i, name in enumerate(header)}
        for row_index, row in enumerate(reader):
            smiles = row[col["smiles"]]
            fold = row[col["fold"]]
            if smiles not in cache:
                cache[smiles] = compute(smiles)
            formula, canon = cache[smiles]
            if formula is None:
                bad.append({"row_index": row_index, "smiles": smiles})
                continue
            if fold not in FOLD_ORDER:
                bad_folds[fold] += 1
            fold_counts[fold] += 1
            formula_spectra[formula] += 1
            formula_folds[formula].add(fold)
            fold_formulas[fold].add(formula)
            formula_rows.append((row_index, formula, fold))
            if fold in ("test", "val"):
                target = test_rows if fold == "test" else val_rows
                target.append((row_index, smiles, row[col["precursor_mz"]], row[col["adduct"]],
                               row[col["collision_energy"]], fold, canon))
        n_rows = len(formula_rows) + len(bad)

    conflicts = {f: sorted(s) for f, s in formula_folds.items() if len(s) > 1}

    # ---- tables (byte-identical to the frozen files) ----
    fold_rank = {f: i for i, f in enumerate(FOLD_ORDER)}
    buf = io.StringIO()
    w = csv.writer(buf, lineterminator="\n")
    w.writerow(["formula", "fold", "n_spectra"])
    for formula, n in sorted(
        formula_spectra.items(), key=lambda kv: (fold_rank.get(sorted(formula_folds[kv[0]])[0], 99), kv[0])
    ):
        w.writerow([formula, sorted(formula_folds[formula])[0], n])
    tables = {"formula_split.csv": buf.getvalue()}

    buf = io.StringIO()
    w = csv.writer(buf, lineterminator="\n")
    w.writerow(["row_index", "formula", "fold"])
    for row_index, formula, fold in formula_rows:
        w.writerow([row_index, formula, fold])
    tables["row_formula_fold.csv"] = buf.getvalue()

    def spectra_csv(rows):
        buf = io.StringIO()
        w = csv.writer(buf, lineterminator="\n")
        w.writerow(["row_index", "smiles", "precursor_mz", "adduct", "collision_energy", "fold",
                    "canonical_isomeric_smiles"])
        for r in rows:
            w.writerow([r[0], r[1], r[2], r[3], r[4], r[5], r[6]])
        return buf.getvalue()

    tables["test_spectra.csv"] = spectra_csv(test_rows)
    tables["val_spectra.csv"] = spectra_csv(val_rows)

    canon_groups = collections.Counter(r[6] for r in test_rows)
    canon_ge2 = sorted((k, v) for k, v in canon_groups.items() if v >= 2)
    buf = io.StringIO()
    w = csv.writer(buf, lineterminator="\n")
    w.writerow(["group_id", "canonical_isomeric_smiles", "n_spectra"])
    for group_id, (canon, n) in enumerate(canon_ge2):
        w.writerow([group_id, canon, n])
    tables["test_molecules_voting_canonical_view.csv"] = buf.getvalue()

    smiles_groups = collections.Counter(r[1] for r in test_rows)
    smiles_ge2 = sorted((k, v) for k, v in smiles_groups.items() if v >= 2)
    buf = io.StringIO()
    w = csv.writer(buf, lineterminator="\n")
    w.writerow(["group_id", "smiles", "n_spectra"])
    for group_id, (smiles, n) in enumerate(smiles_ge2):
        w.writerow([group_id, smiles, n])
    tables["test_molecules_voting.csv"] = buf.getvalue()

    summary = {
        "n_data_rows": n_rows,
        "n_unique_formula": len(formula_spectra),
        "n_formula_by_fold": {f: len(fold_formulas[f]) for f in FOLD_ORDER},
        "n_spectra_by_fold": {f: fold_counts[f] for f in FOLD_ORDER},
        "n_formula_with_multiple_folds": len(conflicts),
        "formula_conflicts": conflicts,
        "n_rdkit_parse_failures": len(bad),
        "parse_failure_examples": bad[:5],
        "unexpected_folds": dict(bad_folds),
        "n_voting_groups_official": len(smiles_ge2),
        "n_voting_spectra_official": sum(n for _, n in smiles_ge2),
        "n_voting_groups_canonical": len(canon_ge2),
        "n_voting_spectra_canonical": sum(n for _, n in canon_ge2),
    }
    return tables, summary


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--csv", required=True, help="path to MSnLib.csv (560,084 data rows)")
    parser.add_argument("--output-dir", default=None, help="write the tables here")
    parser.add_argument("--lenient-rdkit", action="store_true",
                        help="downgrade canonical-string hash mismatches caused by a different RDKit release to warnings")
    args = parser.parse_args()

    digest = hashlib.sha256()
    with open(args.csv, "rb") as fh:
        while block := fh.read(8 << 20):
            digest.update(block)
    source_sha = digest.hexdigest()
    print(f"source csv : {args.csv}")
    print(f"source sha : {source_sha}")
    if source_sha != SOURCE_CSV_SHA256:
        print(f"[WARN] source SHA-256 differs from the frozen MSnLib.csv ({SOURCE_CSV_SHA256})")

    tables, summary = replay(args.csv)

    failures = []
    actuals = {
        "n_data_rows": summary["n_data_rows"],
        "n_unique_formula": summary["n_unique_formula"],
        "n_formula_train": summary["n_formula_by_fold"]["train"],
        "n_formula_val": summary["n_formula_by_fold"]["val"],
        "n_formula_test": summary["n_formula_by_fold"]["test"],
        "n_spectra_train": summary["n_spectra_by_fold"]["train"],
        "n_spectra_val": summary["n_spectra_by_fold"]["val"],
        "n_spectra_test": summary["n_spectra_by_fold"]["test"],
        "n_voting_groups_official": summary["n_voting_groups_official"],
        "n_voting_spectra_official": summary["n_voting_spectra_official"],
        "n_voting_groups_canonical": summary["n_voting_groups_canonical"],
        "n_voting_spectra_canonical": summary["n_voting_spectra_canonical"],
    }
    for key, expected in EXPECTED.items():
        actual = actuals[key]
        ok = actual == expected
        print(f"[{'PASS' if ok else 'FAIL'}] {key}: {actual:,} (expected {expected:,})")
        if not ok:
            failures.append(key)
    if summary["n_formula_with_multiple_folds"]:
        print(f"[FAIL] {summary['n_formula_with_multiple_folds']} formulas occur in more than one fold")
        failures.append("formula_fold_consistency")
    if summary["n_rdkit_parse_failures"]:
        print(f"[FAIL] {summary['n_rdkit_parse_failures']} SMILES could not be parsed")
        failures.append("rdkit_parse")
    if summary["unexpected_folds"]:
        print(f"[FAIL] unexpected fold labels: {summary['unexpected_folds']}")
        failures.append("unexpected_folds")

    canonical_diffs = []
    for name, (expected_bytes, expected_sha) in FROZEN.items():
        data = tables[name].encode()
        got_sha = sha256(data)
        ok = len(data) == expected_bytes and got_sha == expected_sha
        print(f"[{'PASS' if ok else 'DIFF'}] {name}: {len(data):,} bytes sha256 {got_sha}")
        if not ok:
            if name in CANONICAL_DEPENDENT:
                canonical_diffs.append(name)
            else:
                failures.append(name)

    if args.output_dir:
        import os
        os.makedirs(args.output_dir, exist_ok=True)
        for name, text in tables.items():
            with open(os.path.join(args.output_dir, name), "w", newline="") as fh:
                fh.write(text)
        print(f"wrote {len(tables)} tables to {args.output_dir}")

    print("\nsummary:")
    print(json.dumps(summary, indent=2))

    if canonical_diffs:
        message = ("canonical-string tables differ from the frozen copies; the frozen tables were produced with "
                   "RDKit 2026.03.5 and a different patch release may serialise the same molecule differently")
        if args.lenient_rdkit:
            print(f"[WARN] {message}: {', '.join(canonical_diffs)}")
        else:
            print(f"[FAIL] {message}: {', '.join(canonical_diffs)}")
            failures.extend(canonical_diffs)

    return 1 if failures else 0


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