Download split_A_full_msnlib/build_split_a.py from dsadd4/UltraMS-MSnLib-Benchmark: direct link, hf CLI and curl.
- Browser
- Download file 11.7 kB
-
https://huggingface.co/datasets/dsadd4/UltraMS-MSnLib-Benchmark/resolve/main/split_A_full_msnlib/build_split_a.py
- Command line
-
hf download hf://datasets/dsadd4/UltraMS-MSnLib-Benchmark/split_A_full_msnlib/build_split_a.py
-
curl -L -o build_split_a.py https://huggingface.co/datasets/dsadd4/UltraMS-MSnLib-Benchmark/resolve/main/split_A_full_msnlib/build_split_a.py
11.7 kB
| #!/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()) | |