dsadd4 commited on
Commit
a03fc9f
·
verified ·
1 Parent(s): d6ee4da

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +5 -0
  2. NOTICE.md +93 -0
  3. README.md +424 -0
  4. SHA256SUMS +60 -0
  5. VERIFY.md +338 -0
  6. figures_mapping.md +124 -0
  7. hf_dataset_card.md +207 -0
  8. hf_upload_commands.sh +129 -0
  9. libraries/neg_test_library.csv +3 -0
  10. libraries/neg_test_library.csv.gz +3 -0
  11. libraries/neg_val_library.csv +3 -0
  12. libraries/neg_val_library.csv.gz +3 -0
  13. libraries/pos_test_library.csv +3 -0
  14. libraries/pos_test_library.csv.gz +3 -0
  15. libraries/pos_val_library.csv +3 -0
  16. libraries/pos_val_library.csv.gz +3 -0
  17. protocol/README.md +75 -0
  18. protocol/adducts_neg.json +3 -0
  19. protocol/adducts_pos.json +3 -0
  20. protocol/derived/row_metadata_neg.npz +3 -0
  21. protocol/derived/row_metadata_pos.npz +3 -0
  22. protocol/manifest_summary.json +126 -0
  23. protocol/protocol_neg.npz +3 -0
  24. protocol/protocol_pos.npz +3 -0
  25. protocol/smiles_neg.json +0 -0
  26. protocol/smiles_pos.json +0 -0
  27. queries/neg_test_queries.csv +0 -0
  28. queries/neg_test_queries.csv.gz +3 -0
  29. queries/neg_val_queries.csv +0 -0
  30. queries/neg_val_queries.csv.gz +3 -0
  31. queries/pos_test_queries.csv +0 -0
  32. queries/pos_test_queries.csv.gz +3 -0
  33. queries/pos_val_queries.csv +0 -0
  34. queries/pos_val_queries.csv.gz +3 -0
  35. rebuild/LICENSE-APACHE-2.0.txt +202 -0
  36. rebuild/README.md +103 -0
  37. rebuild/baseline_common.py +345 -0
  38. rebuild/build_library_manifest.py +333 -0
  39. rebuild/verify_release.py +511 -0
  40. split_A_full_msnlib/README.md +107 -0
  41. split_A_full_msnlib/REPORT.json +484 -0
  42. split_A_full_msnlib/VERIFY.md +270 -0
  43. split_A_full_msnlib/build_split_a.py +275 -0
  44. split_A_full_msnlib/formula_split.csv +0 -0
  45. split_A_full_msnlib/formula_split.csv.gz +3 -0
  46. split_A_full_msnlib/msnlib_rt.csv.gz +3 -0
  47. split_A_full_msnlib/row_formula_fold.csv +3 -0
  48. split_A_full_msnlib/row_formula_fold.csv.gz +3 -0
  49. split_A_full_msnlib/test_molecules_voting.csv +0 -0
  50. split_A_full_msnlib/test_molecules_voting.csv.gz +3 -0
.gitattributes CHANGED
@@ -58,3 +58,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ libraries/neg_test_library.csv filter=lfs diff=lfs merge=lfs -text
62
+ libraries/neg_val_library.csv filter=lfs diff=lfs merge=lfs -text
63
+ libraries/pos_test_library.csv filter=lfs diff=lfs merge=lfs -text
64
+ libraries/pos_val_library.csv filter=lfs diff=lfs merge=lfs -text
65
+ split_A_full_msnlib/row_formula_fold.csv filter=lfs diff=lfs merge=lfs -text
NOTICE.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NOTICE — upstream attribution, provenance and licensing
2
+
3
+ This package is a **derived benchmark manifest**, not a re-release of the MSnLib spectra.
4
+ It contains compound identities (raw and RDKit canonical SMILES), molecular formulas,
5
+ source-row pointers into `MSnLib.csv`, precursor m/z, adduct, collision energy and the
6
+ train / validation / test assignments of two independent, frozen benchmark splits. The
7
+ manifest itself contains no mass spectra (`mzs` / `intensities`).
8
+
9
+ The Hugging Face dataset that mirrors this manifest additionally hosts two large source
10
+ files, because every table points into them:
11
+
12
+ | hosted file | bytes | SHA-256 | content |
13
+ | --- | ---: | --- | --- |
14
+ | `MSnLib.csv` | 752,707,651 | `be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07` | one row per MSnLib spectrum (560,084 rows), including the `mzs` / `intensities` peak lists |
15
+ | `MSnLib_candidates.json` | 1,368,264,026 | `125a1cdcc57a3fcef8cc76d5322ac0c434cd09b0bfb9e0c9d28bddf052f45fcc` | candidate SMILES lists behind the single-spectrum candidate-ranking task (JSON object: query SMILES → candidate SMILES list; 9,886 query entries) |
16
+
17
+ Both hosted files derive from the MSnLib release and remain under **CC BY 4.0** with
18
+ attribution to the MSnLib authors; the candidate lists are derived from the MSnLib compound
19
+ set by UltraMS.
20
+
21
+ ## Upstream resource: MSnLib
22
+
23
+ * Brungs C., Schmid R., Pluskal T. *MSnLib: efficient generation of open multi-stage
24
+ fragmentation mass spectral libraries.* Nature Methods (2025),
25
+ doi:[10.1038/s41592-025-02813-0](https://doi.org/10.1038/s41592-025-02813-0).
26
+ * Data release: *MSnLib mass spectral libraries*,
27
+ Zenodo [10.5281/zenodo.11163380](https://doi.org/10.5281/zenodo.11163380) (2024).
28
+ * License: **Creative Commons Attribution 4.0 International (CC BY 4.0)**.
29
+ Attribution to the MSnLib authors is required for any reuse of the material derived from
30
+ it, including the compound identities, formulas and metadata distributed here.
31
+
32
+ The 18 MSnLib original per-file MS2 JSONL releases contain exactly **560,084 records**,
33
+ equal to the number of data rows of the `MSnLib.csv` file this package indexes. `MSnLib.csv`
34
+ is the UltraMS CSV conversion of those records (one row per spectrum; peaks stored as
35
+ comma-separated strings; 752,707,651 bytes; SHA-256
36
+ `be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07`). It is not part of this
37
+ manifest; it is hosted with the Hugging Face mirror (see `README.md` §8.1).
38
+
39
+ ## Retention times
40
+
41
+ `split_A_full_msnlib/msnlib_rt.csv.gz` contains the per-spectrum retention time
42
+ (`row_index, rt` in seconds). RT is **source metadata from the MSnLib records** and remains
43
+ under CC BY 4.0 with attribution to the MSnLib authors. The table was exported from
44
+ `MSnLib_with_rt.csv` (755,984,910 bytes, SHA-256
45
+ `a5b7c38228287c5c1de401050445319b331ee9a5f17993d6e104e9a734fe2964`) after verifying that
46
+ its row order and first seven columns are identical to `MSnLib.csv` (560,084 rows, 0
47
+ mismatches; see `split_A_full_msnlib/VERIFY.md` §5.4).
48
+
49
+ ## What UltraMS added (the original contribution of this package)
50
+
51
+ * the CSV representation of the MSnLib release and the source-row pointers,
52
+ * the frozen **formula-level split A** (all adducts: 21,107 formulas; 16,885 / 2,110 / 2,112
53
+ formulas and 446,667 / 55,980 / 57,437 spectra for train / validation / test),
54
+ * the frozen **strict-adduct molecule-level split B** (70/15/15 by canonical isomeric
55
+ SMILES, per polarity, with frozen query and library definitions),
56
+ * the query / library / voting tables, row metadata, protocol arrays, rebuild scripts and
57
+ verification artifacts derived from them.
58
+
59
+ The split assignments themselves are an original creation of this work and may be reused
60
+ with attribution. The compound identities and metadata derived from MSnLib remain under
61
+ CC BY 4.0.
62
+
63
+ ## UltraMS code (rebuild scripts only)
64
+
65
+ * Li Y., Zhong Y., Liu P., Xia J. *UltraMS.* Apache License 2.0
66
+ (repository: <https://github.com/Dsadd4/UltraMS>).
67
+ * `rebuild/build_library_manifest.py` and `rebuild/baseline_common.py` are byte-identical
68
+ copies of files from the UltraMS public release
69
+ (`benchmarks/molecular_identification/source_code/original/`). Their license text is
70
+ reproduced in `rebuild/LICENSE-APACHE-2.0.txt`; the files keep their original copyright
71
+ and attribution.
72
+ * `rebuild/verify_release.py` and `split_A_full_msnlib/build_split_a.py` are original
73
+ verifier / replay scripts of this release.
74
+
75
+ ## Recommended license for this package
76
+
77
+ **CC BY 4.0.** Rationale:
78
+
79
+ * the largest share of the derived content (compound identities, molecular formulas,
80
+ metadata, source-row pointers) comes from MSnLib under CC BY 4.0, so redistribution must
81
+ keep at least that attribution requirement;
82
+ * the split assignments and the derived tables added by UltraMS are released under the same
83
+ permissive, attribution-preserving terms so that the whole package has one simple
84
+ license;
85
+ * a single license keeps the benchmark usable for academic and commercial research.
86
+
87
+ If you redistribute this package, keep `NOTICE.md`, `README.md` and `SHA256SUMS`, and cite
88
+ MSnLib and UltraMS as described in `README.md` §12.
89
+
90
+ ## Third-party names
91
+
92
+ MSnLib, UltraMS, RDKit, Nature Methods and Zenodo are names/trademarks of their respective
93
+ owners. Their use here is descriptive only and does not imply endorsement.
README.md ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # UltraMS MSnLib benchmark
2
+
3
+ Version **1.0.0** · 2026-11-04 · license **CC BY 4.0** (see [NOTICE.md](NOTICE.md))
4
+
5
+ Two frozen, independent benchmark splits of the [MSnLib](https://doi.org/10.1038/s41592-025-02813-0)
6
+ tandem mass spectral library, built and released by UltraMS:
7
+
8
+ * **Split A — UltraMS MSnLib formula-level split**: the complete library (560,084 spectra,
9
+ all adducts) split by molecular formula into train / validation / test
10
+ (16,885 / 2,110 / 2,112 formulas, 446,667 / 55,980 / 57,437 spectra). Formula-disjoint.
11
+ This is the population for single-spectrum candidate ranking, multiple-spectrum voting,
12
+ label-blind grouping and embedding analyses.
13
+ * **Split B — strict-adduct molecule-level split**: the strict `[M+H]+` and `[M-H]-`
14
+ subsets (447,956 source rows) re-split 70 / 15 / 15 at the level of RDKit canonical
15
+ isomeric SMILES, separately per polarity, with frozen queries and libraries for
16
+ spectrum-to-spectrum library search. Molecule-disjoint within each polarity.
17
+
18
+ Both splits are frozen benchmark definitions with published checksums; neither is a
19
+ redistribution of the MSnLib spectra.
20
+
21
+ ---
22
+
23
+ ## 1. At a glance
24
+
25
+ | | Split A (formula-level, all adducts) | Split B `[M+H]+` | Split B `[M-H]-` |
26
+ | --- | ---: | ---: | ---: |
27
+ | compounds / molecules | — (21,107 formulas) | 41,348 | 21,293 |
28
+ | spectra | 560,084 | 301,636 | 140,193 |
29
+ | train | 16,885 formulas · 446,667 spectra | 28,944 compounds · 211,745 spectra | 14,907 · 98,401 |
30
+ | validation | 2,110 formulas · 55,980 spectra | 6,202 compounds · 44,881 spectra | 3,193 · 20,927 |
31
+ | test | 2,112 formulas · 57,437 spectra | 6,202 compounds · 45,010 spectra | 3,193 · 20,865 |
32
+ | test task | candidate ranking / voting (57,437 queries) | 6,202 queries vs 295,434 library spectra | 3,193 vs 137,000 |
33
+ | queries with an exact-adduct library positive | — | 6,201 | 3,160 |
34
+ | validation task | — | 6,202 vs 250,424 | 3,193 vs 116,135 |
35
+
36
+ Split A test fold: 57,437 spectra, 2,112 formulas, 5,003 distinct MSnLib source SMILES,
37
+ 4,889 distinct RDKit canonical isomeric SMILES. The **official** multiple-spectrum voting
38
+ unit is the MSnLib source SMILES string: 5,002 groups covering 57,436 spectra (canonical
39
+ view: 4,888 groups).
40
+
41
+ Split B split seeds: 42 (`[M+H]+`) / 43 (`[M-H]-`); query seed 119. Split A has no seed:
42
+ its fold assignment is frozen in the `fold` column of `MSnLib.csv` and replayed exactly by
43
+ `split_A_full_msnlib/build_split_a.py`.
44
+
45
+ ## 2. Disjointness: what is claimed — and what is not
46
+
47
+ | split | disjointness unit | claimed |
48
+ | --- | --- | --- |
49
+ | A | molecular formula | every spectrum of a formula lies in exactly one fold; no formula occurs in two folds (0 conflicts out of 21,107) |
50
+ | B | RDKit canonical isomeric SMILES, per polarity | the train / validation / test compound sets of each polarity are pairwise disjoint |
51
+
52
+ **A and B are different objects and must not be combined into a global-disjointness claim.**
53
+ About 41 % of split-B compounds are in a *different* split-A fold, and a spectrum can be a
54
+ split-A test spectrum while its compound is a split-B train compound. Concrete numbers:
55
+
56
+ * split B `[M+H]+` test compounds: 654 are split-A test, 4,922 are split-A train, 626 are
57
+ split-A validation;
58
+ * split B `[M-H]-` test compounds: 303 are split-A test, 2,541 are split-A train, 349 are
59
+ split-A validation;
60
+ * 31,570 split-A test spectra are `[M+H]+` rows of split B and 13,413 are `[M-H]-` rows.
61
+
62
+ The full cross-tabulation (compound level and spectra level, per polarity, plus the
63
+ relation of the split-A test fold to split B) is in [figures_mapping.md](figures_mapping.md) §2.
64
+ Never report a cross-split score as a held-out result: train and evaluate inside one split.
65
+
66
+ ## 3. Package layout
67
+
68
+ ```text
69
+ ultrams_msnlib_benchmark_v1/
70
+ ├── README.md this file
71
+ ├── figures_mapping.md which manuscript panel uses which split (+ cross-split statistics)
72
+ ├── VERIFY.md full verification record and reproducible commands
73
+ ├── NOTICE.md MSnLib attribution, provenance and licensing
74
+ ├── SHA256SUMS checksums of every file except itself
75
+ ├── stats.json machine-readable release summary (all counts + file hashes)
76
+ ├── split_A_full_msnlib/ split A (formula-level, full library)
77
+ │ ├── README.md
78
+ │ ├── VERIFY.md split-A verification record
79
+ │ ├── REPORT.json split-A machine-readable report
80
+ │ ├── build_split_a.py replay of split A from MSnLib.csv + hash check
81
+ │ ├── formula_split.csv(.gz) 21,107 formulas → fold, n_spectra
82
+ │ ├── row_formula_fold.csv(.gz) 560,084 rows → formula, fold
83
+ │ ├── test_spectra.csv(.gz) 57,437 test spectra
84
+ │ ├── val_spectra.csv(.gz) 55,980 validation spectra
85
+ │ ├── test_molecules_voting.csv(.gz) 5,002 official source-SMILES voting units
86
+ │ ├── test_molecules_voting_canonical_view.csv(.gz) 4,888 canonical-SMILES alternative view
87
+ │ └── msnlib_rt.csv.gz 560,084 row_index → retention time (seconds)
88
+ ├── splits/ split B compound tables (70/15/15, per polarity)
89
+ │ ├── pos_compound_split.csv(.gz) 41,348 compounds
90
+ │ └── neg_compound_split.csv(.gz) 21,293 compounds
91
+ ├── queries/ split B query spectra
92
+ │ ├── pos_val_queries.csv(.gz) 6,202
93
+ │ ├── pos_test_queries.csv(.gz) 6,202
94
+ │ ├── neg_val_queries.csv(.gz) 3,193
95
+ │ └── neg_test_queries.csv(.gz) 3,193
96
+ ├── libraries/ split B library spectra
97
+ │ ├── pos_val_library.csv(.gz) 250,424
98
+ │ ├── pos_test_library.csv(.gz) 295,434
99
+ │ ├── neg_val_library.csv(.gz) 116,135
100
+ │ └── neg_test_library.csv(.gz) 137,000
101
+ ├── protocol/ frozen split-B protocol arrays and manifest
102
+ │ ├── manifest_summary.json
103
+ │ ├── protocol_{pos,neg}.npz
104
+ │ ├── smiles_{pos,neg}.json
105
+ │ ├── adducts_{pos,neg}.json
106
+ │ ├── derived/row_metadata_{pos,neg}.npz
107
+ │ └── README.md
108
+ ├── rebuild/
109
+ │ ├── build_library_manifest.py the split-B producer (replays MSnLib.csv)
110
+ │ ├── baseline_common.py its helper module
111
+ │ ├── verify_release.py self-contained verifier for the whole package
112
+ │ ├── LICENSE-APACHE-2.0.txt
113
+ │ └── README.md
114
+ ├── hf_dataset_card.md Hugging Face dataset card draft
115
+ ├── hf_upload_commands.sh upload commands, dry-run by default, not executed
116
+ └── zenodo_metadata.json Zenodo deposition metadata draft
117
+ ```
118
+
119
+ Every plain `.csv` has a byte-identical `.csv.gz` twin; `rebuild/verify_release.py` checks
120
+ this, all counts, all orderings, the cross-split statistics and the checksums.
121
+
122
+ ## 4. Split A — UltraMS MSnLib formula-level split
123
+
124
+ ### 4.1 Definition
125
+
126
+ For every MSnLib spectrum the neutral molecular formula is computed from the source SMILES
127
+ with RDKit (`rdMolDescriptors.CalcMolFormula(Chem.MolFromSmiles(smiles))`). The frozen
128
+ `fold` column of `MSnLib.csv` assigns each formula to exactly one fold; the split is the
129
+ formula-grouped 80/10/10 partition that results. The rule was verified for all 560,084
130
+ spectra: 21,107 formulas, none in more than one fold. This is the frozen benchmark
131
+ definition; `build_split_a.py` replays it from `MSnLib.csv` and reproduces every table
132
+ byte-for-byte.
133
+
134
+ ### 4.2 Tables
135
+
136
+ | file | rows | columns |
137
+ | --- | ---: | --- |
138
+ | `formula_split.csv` | 21,107 | `formula, fold, n_spectra` — ordered by fold (train, valid, test) then formula |
139
+ | `row_formula_fold.csv` | 560,084 | `row_index, formula, fold` — 0-based `MSnLib.csv` data row → formula → fold |
140
+ | `test_spectra.csv` | 57,437 | `row_index, smiles, precursor_mz, adduct, collision_energy, fold, canonical_isomeric_smiles` |
141
+ | `val_spectra.csv` | 55,980 | same schema for the validation fold |
142
+ | `test_molecules_voting.csv` | 5,002 | `group_id, smiles, n_spectra` — **official** voting units (MSnLib source SMILES) |
143
+ | `test_molecules_voting_canonical_view.csv` | 4,888 | `group_id, canonical_isomeric_smiles, n_spectra` — alternative canonical view |
144
+ | `msnlib_rt.csv.gz` | 560,084 | `row_index, rt` — per-spectrum retention time in seconds (gzipped only, see §4.5) |
145
+
146
+ `row_index` is the 0-based data row of `MSnLib.csv` (physical line = data row + 2). The
147
+ tables do not carry peak data; join on `row_index` against `MSnLib.csv` (see §8).
148
+
149
+ ### 4.3 Official voting units — read this before using the voting tables
150
+
151
+ The **official multiple-spectrum voting units are the 5,002 MSnLib source-SMILES groups
152
+ covering 57,436 spectra**, exactly the grouping used by the published multiple-spectrum
153
+ voting task (Figure 3d and the Figure 3a voting readouts, `n_molecules = 5002`). The test
154
+ fold contains 5,003 distinct source SMILES strings; one occurs in only one spectrum, hence
155
+ 5,002 groups. This table is `test_molecules_voting.csv` (columns `group_id, smiles,
156
+ n_spectra`) and it is verified member-for-member against the repository voting table
157
+ (`benchmarks/molecular_identification/data/multiple_spectrum_voting_per_group.csv.gz`).
158
+
159
+ An **alternative canonical view** is provided as `test_molecules_voting_canonical_view.csv`:
160
+ the same test spectra grouped by RDKit canonical isomeric SMILES give 4,888 groups covering
161
+ the same 57,436 spectra (114 source-string groups merge into chemically identical
162
+ molecules; the single excluded molecule is `CC(C)(C)OC(=O)NCC1(CC(=O)O)CCCCC1`). This view
163
+ is not the official voting unit.
164
+
165
+ No data was altered to force either count. See `split_A_full_msnlib/VERIFY.md` §7 and
166
+ `REPORT.json` → `anomalies`.
167
+
168
+ ### 4.5 Retention times (RT)
169
+
170
+ `split_A_full_msnlib/msnlib_rt.csv.gz` is a compact companion table needed by the
171
+ label-blind grouping and multiple-spectrum voting analyses (Figure 3d): `row_index` is the
172
+ 0-based `MSnLib.csv` data row (0 … 560,083) and `rt` is the retention time in seconds, kept
173
+ in the source text representation.
174
+
175
+ RT is **source metadata from the MSnLib records** (CC BY 4.0, Zenodo
176
+ 10.5281/zenodo.11163380; see `NOTICE.md`). The table was exported from
177
+ `MSnLib_with_rt.csv` (755,984,910 bytes, SHA-256
178
+ `a5b7c38228287c5c1de401050445319b331ee9a5f17993d6e104e9a734fe2964`) after verifying
179
+ row-by-row that its first seven columns are identical to `MSnLib.csv` in the same order
180
+ (560,084/560,084 rows, 0 mismatches; see `split_A_full_msnlib/VERIFY.md` §5.4). The full
181
+ 756 MB CSV is not duplicated; only this 1.4 MB gzipped table is shipped.
182
+
183
+ ```python
184
+ import pandas as pd
185
+
186
+ test = pd.read_csv("split_A_full_msnlib/test_spectra.csv")
187
+ rt = pd.read_csv("split_A_full_msnlib/msnlib_rt.csv.gz") # row_index, rt
188
+ test_rt = test.merge(rt, on="row_index", how="left")
189
+ assert test_rt["rt"].notna().all()
190
+ ```
191
+
192
+ The same `row_index` join works for every row of `row_formula_fold.csv`.
193
+
194
+ #### Provenance of split A
195
+
196
+ Source rows, formulas and folds were computed read-only in an isolated data-preparation
197
+ environment with RDKit 2026.03.5. The split-A tables were frozen from that run; cross-checks against the
198
+ historical per-fold CSV files, against the MSnLib original JSON `formula` fields, and
199
+ against the repository voting table are recorded in `split_A_full_msnlib/VERIFY.md`.
200
+
201
+ ## 5. Split B — strict-adduct molecule-level split
202
+
203
+ ### 5.1 Definition
204
+
205
+ Split B keeps only the strict `[M+H]+` (303,709 source rows) and `[M-H]-` (144,247 source
206
+ rows) spectra. After the frozen spectrum preprocessing (drop `m/z ≤ 0` peaks, require at
207
+ least 3 peaks, normalise to the base peak, keep the 150 most intense peaks and sort by m/z)
208
+ 2,073 positive and 4,054 negative rows are dropped, leaving **301,636** and **140,193**
209
+ preprocessed spectra. Compound identity is RDKit canonical isomeric SMILES (frozen with
210
+ RDKit 2026.03.5). Per polarity the sorted compound list is shuffled with
211
+ `random.Random(42)` (`[M+H]+`) / `random.Random(43)` (`[M-H]-`) and split 70 / 15 / 15;
212
+ one query spectrum per validation/test compound is drawn with a fresh `random.Random(119)`.
213
+
214
+ ### 5.2 Tables
215
+
216
+ | table | schema |
217
+ | --- | --- |
218
+ | `splits/{pos,neg}_compound_split.csv` | `polarity, compound_id, canonical_isomeric_smiles, split, n_spectra, n_frozen_queries, n_raw_smiles_variants, first_msnlib_csv_data_row` |
219
+ | `queries/{pos,neg}_{val,test}_queries.csv` | `polarity, split, query_index, compound_id, canonical_isomeric_smiles, adduct, msnlib_csv_data_row, msnlib_csv_line, precursor_mz, n_peaks, collision_energy, source_smiles_raw, n_library_positives` |
220
+ | `libraries/{pos,neg}_{val,test}_library.csv` | same as queries with `library_index` and `compound_split` instead of `query_index`; row order is the frozen library order |
221
+
222
+ ### 5.3 Protocol
223
+
224
+ 1. Score every query against the **complete** library of its task (no candidate short list).
225
+ 2. A retrieved library spectrum is correct iff its canonical isomeric SMILES equals the
226
+ query's (exact same-adduct spectrum of the same molecule).
227
+ 3. Empirical FDR = `(accepted − correct) / accepted`; identification recall =
228
+ `correct / n_queries_with_library_positive` (6,201 / 3,160 for the two test tasks).
229
+ Queries without a library positive enter the FDR denominator but not the recall
230
+ denominator; `n_library_positives` is published per query.
231
+ 4. The **test library** is every preprocessed spectrum of the polarity except the selected
232
+ test queries (it therefore still contains further spectra of the test molecules; a query
233
+ never occurs in its own library). The **validation library** contains train and
234
+ validation compounds only, so test compounds never influence validation scores.
235
+ 5. Validation is for model selection only; the test fold is evaluated once.
236
+
237
+ The split-B tables deliberately do **not** carry the formula-level fold of the spectra:
238
+ that label belongs to split A. To obtain each split-B row's split-A fold, join
239
+ `msnlib_csv_data_row` (queries/libraries) or `first_msnlib_csv_data_row` (compound split)
240
+ against `split_A_full_msnlib/row_formula_fold.csv`; the packaged verifier does exactly this
241
+ for the cross-split statistics.
242
+
243
+ The frozen row-index arrays behind these tables are in `protocol/`; the CSV tables are a
244
+ human-readable view. `rebuild/build_library_manifest.py` replays them bit-for-bit from
245
+ `MSnLib.csv`, and `rebuild/verify_release.py` checks the tables against the arrays and the
246
+ frozen manifest.
247
+
248
+ ### 5.4 Cross-collision-energy subtask
249
+
250
+ The cross-collision-energy library-search task uses split B test queries that were measured
251
+ at two or more collision energies: **6,161 positive** and **2,999 negative** queries (out of
252
+ 6,202 / 3,193 split-B test queries). The task pairs a low-energy query spectrum with a
253
+ high-energy reference library (or vice versa) and asks for the same-molecule hit; the
254
+ query identities are a subset of the split-B test queries published here. The CE values in
255
+ MSnLib are 15, 20, 30, 45, 60 and 75 eV. The cross-CE pairing manifest and readouts are
256
+ part of the UltraMS repository, not of this split package.
257
+
258
+ ## 6. Relation to split A
259
+
260
+ Split A and split B are independent; see §2 for the disjointness statement and
261
+ [figures_mapping.md](figures_mapping.md) §2 for the full cross-tabulation. Summary: 58.9 %
262
+ positive and 59.4 % negative split-B compounds keep the same fold in split A; 654 positive
263
+ and 303 negative split-B test compounds are also split-A test compounds; 31,570 / 13,413
264
+ split-A test spectra are `[M+H]+` / `[M-H]-` rows of split B.
265
+
266
+ ## 7. Manuscript figures
267
+
268
+ [figures_mapping.md](figures_mapping.md) maps every figure panel to the split it uses:
269
+
270
+ * **A**: Figure 2b, Figure 2j, Figure 3a, 3b, 3d, 3g, 3a_sp_4, 3a_sp_5 and the
271
+ single-spectrum baselines Top-1 table;
272
+ * **B**: Figure 3e, 3f, 3h, 3h_sp_1 and the cross-collision-energy task (6,161 / 2,999);
273
+ * **not this dataset**: NPLIB1 and MassSpecGym comparison panels (independent external
274
+ benchmarks); Figure 3c / 3i case studies are not split-defined.
275
+
276
+ Candidate-ranking tables (the per-formula candidate lists behind Figure 3a/3b/3d/3g) are
277
+ part of the UltraMS repository, not of this split package; this package provides the frozen
278
+ queries, identities and folds they are evaluated on.
279
+
280
+ ## 8. Data acquisition and rebuilding
281
+
282
+ ### 8.1 The spectra are not part of this manifest
283
+
284
+ This package publishes splits and identifiers, not peak arrays. Every table is joined back
285
+ to the spectra through `row_index` / `msnlib_csv_data_row`, which point into `MSnLib.csv`;
286
+ both large files are hosted in the same Hugging Face dataset (see the managed-file table
287
+ below) rather than duplicated in this manifest.
288
+
289
+ | item | value |
290
+ | --- | --- |
291
+ | file | `MSnLib.csv` — one row per MSnLib spectrum |
292
+ | rows | 560,084 data rows (560,085 physical lines, no embedded newlines) |
293
+ | bytes | 752,707,651 |
294
+ | SHA-256 | `be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07` |
295
+ | columns | `mzs, intensities, smiles, precursor_mz, adduct, collision_energy, fold` |
296
+ | CSV format | peaks stored as comma-separated strings (`mzs`, `intensities`), one spectrum per row |
297
+
298
+ **Managed files on Hugging Face.** The dataset is planned for Hugging Face under the
299
+ placeholder id **`dsadd4/UltraMS-MSnLib-Benchmark`** (dataset card and upload commands are
300
+ drafted here as `hf_dataset_card.md` and `hf_upload_commands.sh`; the upload has **not**
301
+ been executed). The repository will host:
302
+
303
+ | hosted file | bytes | SHA-256 | purpose |
304
+ | --- | ---: | --- | --- |
305
+ | every file of this manifest (`split_A_full_msnlib/`, `splits/`, `queries/`, `libraries/`, `protocol/`, `rebuild/`, docs; 59 files) | ≈ 185.2 MiB total | see `SHA256SUMS` | the two benchmark splits, verifier, docs |
306
+ | `split_A_full_msnlib/msnlib_rt.csv.gz` | 1,483,069 | `994053612db874f7ac7985f278e04cc3463f3b93cd649a195bd167c4c6c7d3d8` | compact per-spectrum retention time (`row_index, rt` in seconds); joins `MSnLib.csv` rows 1:1 and supplies the RT used by the label-blind grouping analysis (Figure 3d) |
307
+ | `MSnLib.csv` | 752,707,651 | `be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07` | the full source CSV: one row per MSnLib spectrum; every `row_index` / `msnlib_csv_data_row` / `first_msnlib_csv_data_row` pointer resolves here |
308
+ | `MSnLib_candidates.json` | 1,368,264,026 | `125a1cdcc57a3fcef8cc76d5322ac0c434cd09b0bfb9e0c9d28bddf052f45fcc` | candidate SMILES lists behind the single-spectrum candidate-ranking task: a JSON object mapping a query SMILES string to its candidate SMILES list (9,886 query entries) |
309
+
310
+ The large files are hosted because every table points into them: spectra (`MSnLib.csv`) and
311
+ candidate rankings (`MSnLib_candidates.json`). The upload script keeps them in a separate
312
+ step and remains dry-run by default.
313
+
314
+ It can also be rebuilt from the **MSnLib original release** (Brungs et al., Zenodo
315
+ [10.5281/zenodo.11163380](https://doi.org/10.5281/zenodo.11163380), CC BY 4.0): the release
316
+ provides 18 per-file MS2 JSONL record lists with exactly 560,084 records in total (equal to
317
+ the CSV data-row count), each record carrying `peaks`, `smiles`, `precursor_mz`, `adduct`
318
+ and `collision_energy`. The UltraMS CSV conversion writes one row per record in the frozen
319
+ conversion order with the columns above and carries the frozen fold labels. The
320
+ authoritative row → formula → fold mapping is shipped independently as
321
+ `split_A_full_msnlib/row_formula_fold.csv`, so downstream work never depends on
322
+ reconstructing the conversion order.
323
+
324
+ ### 8.2 Rebuilding split A
325
+
326
+ ```bash
327
+ python3 split_A_full_msnlib/build_split_a.py \
328
+ --csv /path/to/MSnLib.csv \
329
+ --output-dir replay_split_a
330
+ ```
331
+
332
+ Needs Python ≥ 3.10 and RDKit 2026.03.5 (the frozen canonicalisation runtime). The script
333
+ verifies all counts and all six table SHA-256 values; with a different RDKit patch release
334
+ the canonical-string tables can differ textually while every count still matches (the
335
+ script reports that, or downgrades it to a warning with `--lenient-rdkit`).
336
+
337
+ ### 8.3 Rebuilding split B
338
+
339
+ See [rebuild/README.md](rebuild/README.md). In short:
340
+
341
+ ```bash
342
+ python3 rebuild/build_library_manifest.py \
343
+ --csv /path/to/MSnLib.csv --skip-reference-regression \
344
+ --output-dir replay_manifest
345
+ ```
346
+
347
+ This regenerates `protocol/*.npz`, `smiles_*.json`, `adducts_*.json` and
348
+ `manifest_summary.json` (needs NumPy, h5py, RDKit). The CSV tables are then rebuilt from the
349
+ protocol arrays through `protocol/derived/row_metadata_*.npz` (see `protocol/README.md`).
350
+
351
+ ## 9. Verification
352
+
353
+ ```bash
354
+ python3 rebuild/verify_release.py # self-contained; no network, no MSnLib download
355
+ sha256sum -c SHA256SUMS # or: shasum -a 256 -c SHA256SUMS (macOS)
356
+ ```
357
+
358
+ `rebuild/verify_release.py` re-derives every published count, ordering hash, disjointness
359
+ statement, query/library partition, per-query library positive, cross-split statistic and
360
+ file checksum from the shipped files; the complete transcript is in [VERIFY.md](VERIFY.md).
361
+ Split-A-specific evidence (including the read-only replay and the voting-unit check) is in
362
+ `split_A_full_msnlib/VERIFY.md`.
363
+
364
+ ## 10. Known properties and caveats
365
+
366
+ 1. **Two splits, two disjointness units.** Split A is formula-disjoint; split B is
367
+ compound-disjoint within each polarity. Do not merge them into one global-disjointness
368
+ claim and do not reuse a fold label across splits (§2).
369
+ 2. **Voting units: official 5,002 source-SMILES groups / 57,436 spectra, alternative
370
+ canonical view 4,888 groups / 57,436 spectra.** The official unit is the one used by the
371
+ published `n_molecules = 5002` grouping; both tables are shipped (§4.3).
372
+ 3. **Retention times are split-A row metadata.** `split_A_full_msnlib/msnlib_rt.csv.gz`
373
+ (`row_index, rt` in seconds) is source metadata from the MSnLib release, verified
374
+ row-aligned to `MSnLib.csv`; it is not part of split B and carries no fold label of its
375
+ own.
376
+ 4. **Queries without a library positive are expected** in split B: 1 positive and 33
377
+ negative *test* queries (and 8 / 30 *validation* queries) are singleton compounds whose
378
+ only spectrum is the query. They enter the FDR denominator but not the recall
379
+ denominator; `n_library_positives` is published per query.
380
+ 5. **Singleton compounds are retained** in split B (39 positive and 202 negative compounds
381
+ have exactly one spectrum). Filtering them changes the benchmark.
382
+ 6. **Compound identity is frozen text** (RDKit 2026.03.5 canonical isomeric SMILES). Other
383
+ RDKit patch releases can serialise the same molecule differently; compare the published
384
+ strings, not freshly canonicalised ones. Molecular formulas are stable across RDKit
385
+ patch releases.
386
+ 7. **Precursor m/z** is the source CSV text value; the split-B protocol stores it as
387
+ float32 and all 441,829 preprocessed rows agree exactly after the cast.
388
+ 8. **Collision energy is source metadata**, not a selection criterion; all six values
389
+ (15, 20, 30, 45, 60, 75 eV) occur in both polarities.
390
+ 9. **Split B libraries are large by design** (≈47.6 positive / ≈42.9 negative spectra per
391
+ query on average); ranking must cover the full library, there is no candidate short list.
392
+ 10. **Split A includes all adducts** (11 distinct adducts in the test fold), not only the
393
+ strict `[M+H]+` / `[M-H]-` subset used by split B.
394
+
395
+ ## 11. Provenance and licensing
396
+
397
+ The upstream MSnLib release (spectra and molecule metadata) is CC BY 4.0 (Brungs et al.,
398
+ Zenodo 10.5281/zenodo.11163380). The split definitions, tables and scripts added by UltraMS
399
+ are released under CC BY 4.0 as well. `rebuild/build_library_manifest.py` and
400
+ `rebuild/baseline_common.py` are Apache-2.0 files copied from the UltraMS public release.
401
+ See [NOTICE.md](NOTICE.md) for the full attribution and licensing statement, and
402
+ `protocol/manifest_summary.json` for the frozen split-B manifest (one path field is
403
+ redacted to a placeholder; every count, seed and hash is byte-identical).
404
+
405
+ ## 12. Citation
406
+
407
+ If you use this benchmark, please cite MSnLib and UltraMS:
408
+
409
+ * MSnLib: Brungs C., Schmid R., Pluskal T. *MSnLib: efficient generation of open
410
+ multi-stage fragmentation mass spectral libraries.* Nature Methods (2025),
411
+ doi:10.1038/s41592-025-02813-0; data: Zenodo 10.5281/zenodo.11163380 (CC BY 4.0).
412
+ * UltraMS: Li Y., Zhong Y., Liu P., Xia J. *UltraMS* (manuscript in preparation;
413
+ code: <https://github.com/Dsadd4/UltraMS>).
414
+
415
+ Machine-readable citation metadata is in [`zenodo_metadata.json`](zenodo_metadata.json) and
416
+ [`hf_dataset_card.md`](hf_dataset_card.md).
417
+
418
+ ## 13. Versioning
419
+
420
+ `1.0.0` is the first joint release of splits A and B. Its content is defined by
421
+ `stats.json`, `SHA256SUMS` and the frozen `protocol/manifest_summary.json`. Any change to
422
+ the splits, the compound/formula identity or the library scope requires a new version
423
+ directory and new manifests — the frozen tables must stay frozen so that published
424
+ FDR/recall/ranking numbers remain comparable.
SHA256SUMS ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 65f9b5fa3b480f9bfae9945d1378cb038af4a92b3c089deb1b237916ba6b732a NOTICE.md
2
+ f220ec2683bb5f2a027544f6cd551a00d92e182f02cfc941c0f2b9f561e6a9d1 README.md
3
+ bd39a17757949532c6b35b41cdeeb5cce11eb6bde2e9db138f11fdc4038421d5 VERIFY.md
4
+ 5e96809613cb866fd39988ecffe396b1ac6d1788743603c498acbff67814372d figures_mapping.md
5
+ 8eb64ecf94c13d4c36fa069782a0a4baa84fede3af16049a64299e682493d4fa hf_dataset_card.md
6
+ 357526d01bf04d8a1423a5a3b6b3da948aa326336e8bc2350de225144ac671f0 hf_upload_commands.sh
7
+ d0ebc03945ef98d0ab812461f1bf5ac3aeb739d01022ff39e16fe389adba75ad libraries/neg_test_library.csv
8
+ e1d9a677f399a8c3ebadb8d8851fb95cf2a3c33800bb22333360aaef65f82048 libraries/neg_test_library.csv.gz
9
+ 9af61236009ea964ca36648ed7159dcea67d7cac69af753998006ac84aab0b2e libraries/neg_val_library.csv
10
+ 350374662395d238ab050c36cc9d61f100b51efb6e93f6ea5fea88c96ef90721 libraries/neg_val_library.csv.gz
11
+ 42ce92e4f7b38235cda9aaf4b0e920af7b57dc6baee269932caeb6e1f5eec862 libraries/pos_test_library.csv
12
+ 967f23c327a738febccd50c6db405ec1d59b10e0daedc559a347bf114da4ac3b libraries/pos_test_library.csv.gz
13
+ 9c9b0d8a9f9c12fc3ccef32da2ea9909214c401e762fb679389167f5debe5852 libraries/pos_val_library.csv
14
+ 3fad6edbd573b9c65286d7c75968881566e280fdfe1b782318b928cce0b6fd74 libraries/pos_val_library.csv.gz
15
+ bdd82008e3c59a7539199b40016872c942d59154b847c77acbcc05a6e76e30bc protocol/README.md
16
+ 6d2086ae948fe762ee80695f8f04505516b1259bd9c5ce3719ff47fa951622b5 protocol/adducts_neg.json
17
+ cafcaae472d3dda2337afb48801e37d9f3a318f5bcfcc9ca013f61815066ccd0 protocol/adducts_pos.json
18
+ e566e864b2a8e34d222a7442f8e561367c92cd8d3d80c12246c0320efe5e7374 protocol/derived/row_metadata_neg.npz
19
+ 02aee46a092b4950fa46a5bded773e1946a1296a42aa33e45a8ed24313813b24 protocol/derived/row_metadata_pos.npz
20
+ 6129ed094df59265a684f436da146ef554d9c774e01768363bf58704f87ec237 protocol/manifest_summary.json
21
+ 7183fca678aa0f97dffdc6f4d4719ac993ca97592e0a468680893d0c0f3741db protocol/protocol_neg.npz
22
+ 51a4a10ee4752b3e9bacd08084ec50a802aa4d852c5d599295fd62d99155f537 protocol/protocol_pos.npz
23
+ 15a4ed45dd55ef27d05ad7a0a14ffcaa9a86e62f5f2120a18c358f748a98b989 protocol/smiles_neg.json
24
+ bd4514be073297afd51ad3700661d0a15b2a223b1ebffd449a6a1f4084be6b8f protocol/smiles_pos.json
25
+ 973e3a0d7ace69760291b87b3c9a606d2aa0805f1fdbc803bace3cdf3f1303f6 queries/neg_test_queries.csv
26
+ 95fb67a3e43dcee01e1356fa6cfc8f6ed1f14bacc9c07a0ffdf4bba4de6fad24 queries/neg_test_queries.csv.gz
27
+ dfa1e331a5f8faa00c3f1bed7f28c2aa82eec15c1b41c1d7e4ef8ac4b16d0ef0 queries/neg_val_queries.csv
28
+ 9a728d2cc2d2ea1ebfa2789bcdb9368e3e752e6121aefeda4aa88d0e5dbfca28 queries/neg_val_queries.csv.gz
29
+ 35f52f575dda7759076a68d3c789e5fe34925967a76a10397c19e6f92022f693 queries/pos_test_queries.csv
30
+ 839bcfaaed05f8a38638385c01df776626156d43127f40a61ccdfe7c197c9fc9 queries/pos_test_queries.csv.gz
31
+ 9d8bf61b62012b1988fd9cbe14a6831dba92ac1d05b3a087928461a6ea7fd986 queries/pos_val_queries.csv
32
+ 6b49651ae096ebb313568c9b48789f61f63192eaaf73f1a611c6fb8716bb8268 queries/pos_val_queries.csv.gz
33
+ cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 rebuild/LICENSE-APACHE-2.0.txt
34
+ 5df97c810ff6600bab35a67fe92662f4979feb0b5fe66d8db7ce395ae81f3ce5 rebuild/README.md
35
+ 72969bc51f39dc8ae044ebaf47cdd3546f90b32edfc2b467c356b10ff0232000 rebuild/baseline_common.py
36
+ 969760ce3a1a1f85e7bcd3e2b9c9c042675624e6df6940ee6a79a124877930e3 rebuild/build_library_manifest.py
37
+ 3feac7c761dd3bce05c55847c83e97700c2cc018a13f4d6f37633e5fca7eedf6 rebuild/verify_release.py
38
+ 58a650850a9ed63c1c2a9b7593f9c392322b0f802bbeddc400b600a656ec664c split_A_full_msnlib/README.md
39
+ 20a06ed04036fddbd757f90006a39f339fc45562237bd3e22a28e052f9b5b1dc split_A_full_msnlib/REPORT.json
40
+ 2cde59c95c6633807b5b87fd43e3eb17a8fa5c2dac21f9541f29c5193ec1aa4e split_A_full_msnlib/VERIFY.md
41
+ 00d07d8711af4282ae5984cee6d46b8b7ddf0f6baa62077fc748b46453e770bf split_A_full_msnlib/build_split_a.py
42
+ fcc44d1996d25306c884a6f8da30c1447fbe74f93c6fa12a3f271c0475a704b8 split_A_full_msnlib/formula_split.csv
43
+ d52d77139c06d8662972fa638981894cf9f88fb3a5da1e1b73017b939d19fd4a split_A_full_msnlib/formula_split.csv.gz
44
+ 994053612db874f7ac7985f278e04cc3463f3b93cd649a195bd167c4c6c7d3d8 split_A_full_msnlib/msnlib_rt.csv.gz
45
+ ac6113867fdda683304533f097fc7287c13271a2deac8e792d1316dcf00264ff split_A_full_msnlib/row_formula_fold.csv
46
+ 86150a89fb601a117d43c995065c3abc95ab0710cb80ffe47dfa5413aa57e686 split_A_full_msnlib/row_formula_fold.csv.gz
47
+ edad6ec7d6b6f9fc4763deac5245207aee767c78661532621c87acc5a9b1ee07 split_A_full_msnlib/test_molecules_voting.csv
48
+ 72ae163ce88b15d89fb1d556fbb8a698d001dd1e923df11399df13dfddec3db2 split_A_full_msnlib/test_molecules_voting.csv.gz
49
+ 9fcd16ff4159e665833ea145848f94bee7c44115f4a858dd75fe486f15e92bd0 split_A_full_msnlib/test_molecules_voting_canonical_view.csv
50
+ 332c03eab3e9f91b0f956c59cd01c22f633166bd285e9942f5507839625f5bc0 split_A_full_msnlib/test_molecules_voting_canonical_view.csv.gz
51
+ f2a870ba8ac9a54a36feaf1ecc12929ad9250ade2d082dc31454028c4b66b548 split_A_full_msnlib/test_spectra.csv
52
+ afb5c538d969bbfccd626a02a78572083a0830a8af0c52a39a45403e3ec71352 split_A_full_msnlib/test_spectra.csv.gz
53
+ f4fa5e0f8875991bf9df2bcb67a05437271ee18c317f33d9108f3ec28a887a82 split_A_full_msnlib/val_spectra.csv
54
+ d2e45289b564b40998479e7c3fe7b283097f1a9aebe798e369b259c7f1851cce split_A_full_msnlib/val_spectra.csv.gz
55
+ d961586838f3601a7dc35a788105cab5e2cfd601df3e5604a6e5f9a18425f5a6 splits/neg_compound_split.csv
56
+ b5a104342d57249ec4633558b324c04eb5fe5491345ff872a91d5271fe9853e8 splits/neg_compound_split.csv.gz
57
+ b3ee3261afca60e3195bef739b45b7a4f1f27935f153455ee7dca985d8cb4398 splits/pos_compound_split.csv
58
+ fe2e8c2c970c685a1b1fc28c957c4a3abc2e5eabef0dad77f0e81c9fbdf1ed04 splits/pos_compound_split.csv.gz
59
+ c6817d22237ec92f5187e0595020f63b07c2a864f8610b7d946ce9ce1d299fe7 stats.json
60
+ af1a18d25e14f24a35c308ec9f695777d6268a2ee505553b0b590be85babc412 zenodo_metadata.json
VERIFY.md ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # VERIFY — verification record for ultrams_msnlib_benchmark_v1
2
+
3
+ Every number, ordering and overlap statement in this package was re-derived from the frozen
4
+ protocol artifacts and checked against the CSV tables shipped here. No discrepancy was
5
+ found. This file records **what was checked, how, and with which exact values**, including
6
+ the checks that can only be performed against the original data-preparation-side artifacts.
7
+
8
+ The package consists of two independent splits. Split-A-specific evidence (counts,
9
+ cross-checks against the MSnLib original JSON `formula` fields, the repository voting
10
+ table, and the read-only replay of all six split-A tables) is recorded in
11
+ [`split_A_full_msnlib/VERIFY.md`](split_A_full_msnlib/VERIFY.md); this file summarises it
12
+ and covers the split-B payload, the cross-split statistics, and the release integrity.
13
+
14
+ ## 1. Environments
15
+
16
+ | side | runtime |
17
+ | --- | --- |
18
+ | frozen split-B manifest producer / split-A table producer (isolated data-preparation environment, read-only) | Linux, Python 3.10.12, NumPy 2.2.6, h5py 3.16.0, RDKit 2026.03.5 |
19
+ | this verification run (local) | macOS, Python 3.13.11, NumPy 2.4.4, pandas 3.0.3, RDKit 2026.03.3 |
20
+
21
+ Access to the data-preparation environment was **read-only**: `MSnLib.csv` and small metadata files
22
+ were streamed out; nothing was written or modified on the remote side.
23
+
24
+ ## 2. Inputs actually used
25
+
26
+ | input | identity |
27
+ | --- | --- |
28
+ | `MSnLib.csv` | 560,084 data rows, 560,085 physical lines (no embedded newlines), 752,707,651 bytes, SHA-256 `be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07` |
29
+ | frozen split-B manifest | `fig3h_manifest_strict_adduct_v4`, original SHA-256 `b83656b2b4d265d1d4ea49df30372e844e207863a7ab768f44f241bd68b8186e`; shipped copy redacted in one path field, SHA-256 `6129ed094df59265a684f436da146ef554d9c774e01768363bf58704f87ec237` |
30
+ | frozen preprocessed spectra (not redistributed) | 110,091,598 bytes, SHA-256 `9296d42e060e7019604e16b20ba80ae13128e03b3e8ee912ee2efeb60bafdf59`; only its small metadata columns are shipped in `protocol/derived/` |
31
+ | MSnLib original release (formula cross-check) | 18 per-file MS2 JSONL record lists, 560,084 records total, Zenodo 10.5281/zenodo.11163380, CC BY 4.0 |
32
+ | repository multiple-spectrum voting table (voting-unit cross-check) | `benchmarks/molecular_identification/data/multiple_spectrum_voting_per_group.csv.gz` (5,002 groups, 57,436 spectra) |
33
+ | hosted candidate file (not part of this manifest) | `MSnLib_candidates.json`, 1,368,264,026 bytes, SHA-256 `125a1cdcc57a3fcef8cc76d5322ac0c434cd09b0bfb9e0c9d28bddf052f45fcc`; candidate SMILES lists for the single-spectrum candidate-ranking task |
34
+ | retention-time source | `MSnLib_with_rt.csv`, 755,984,910 bytes, SHA-256 `a5b7c38228287c5c1de401050445319b331ee9a5f17993d6e104e9a734fe2964`, columns `mzs,intensities,smiles,precursor_mz,adduct,collision_energy,fold,rt` |
35
+ | retention-time table (shipped) | `split_A_full_msnlib/msnlib_rt.csv.gz`, 1,483,069 bytes, SHA-256 `994053612db874f7ac7985f278e04cc3463f3b93cd649a195bd167c4c6c7d3d8`, 560,084 rows |
36
+
37
+ ## 3. Split A — formula-level split (summary)
38
+
39
+ Read-only replay in the isolated data-preparation environment with RDKit 2026.03.5 (`split_A_full_msnlib/build_split_a.py`)
40
+ reproduced every count and **all six table SHA-256 values byte-for-byte**:
41
+
42
+ | quantity | observed |
43
+ | --- | --- |
44
+ | data rows | 560,084 |
45
+ | unique molecular formulas | 21,107 |
46
+ | formulas train / validation / test | 16,885 / 2,110 / 2,112 |
47
+ | spectra train / validation / test | 446,667 / 55,980 / 57,437 |
48
+ | formulas occurring in more than one fold | 0 |
49
+ | RDKit SMILES parse failures | 0 (48,597 distinct source SMILES) |
50
+ | test spectra | 57,437 (2,112 formulas, 5,003 source SMILES, 4,889 canonical molecules) |
51
+ | official voting units — MSnLib source SMILES | 5,002 groups / 57,436 spectra |
52
+ | alternative canonical view — RDKit canonical isomeric SMILES | 4,888 groups / 57,436 spectra |
53
+
54
+ Cross-checks: the test and validation spectra tables match the historical `MSnLib_test.csv` /
55
+ `MSnLib_val.csv` row by row on `smiles`, `precursor_mz`, `adduct`, `collision_energy`
56
+ (0 mismatches); the RDKit formula agrees with the recorded `formula` field of the MSnLib
57
+ original JSON records (18/18 first records, 0 mismatches over 37,177 streamed records, and
58
+ all three located C10H10BrN5O2 records); the MSnLib-source-SMILES voting table is
59
+ member-for-member identical to the repository voting table. Details:
60
+ [`split_A_full_msnlib/VERIFY.md`](split_A_full_msnlib/VERIFY.md).
61
+
62
+ ## 4. Split B — strict-adduct molecule-level split
63
+
64
+ `rebuild/verify_release.py` re-derived from the shipped CSV tables and the frozen
65
+ `protocol/` arrays:
66
+
67
+ * counts against `protocol/manifest_summary.json` (compounds, spectra, queries, libraries,
68
+ valid/dropped rows, per-query exact-adduct library positives 6,201 / 3,160);
69
+ * ordered query / library SMILES SHA-256 and source-row SHA-256 values for both polarities
70
+ and both folds;
71
+ * table row order equals the frozen `query_index` / `library_index`;
72
+ * query↔library row disjointness, the test partition of all preprocessed rows, one query
73
+ per validation/test compound, library fold scope;
74
+ * table ↔ `protocol_*.npz` row-id mapping and `precursor_mz` / `n_peaks` agreement with the
75
+ frozen row metadata;
76
+ * compound-level disjointness of the train / validation / test sets per polarity, and the
77
+ cross-polarity relation recorded in `stats.json` (354 shared positive/negative test
78
+ compounds).
79
+
80
+ All 97 split-B checks passed. The ordered-sequence hashes for both test tasks are:
81
+
82
+ | task | queries | library |
83
+ | --- | --- | --- |
84
+ | `[M+H]+` test | `356f355727380d1df02abbb0aaa3391b180a5c7b93b2103058ba54e8dfae51f0` | `4d69c6f65f8c3ed84df54fc2aa6addd7b28fd1c28909386f4e4ced88d31aacce` |
85
+ | `[M-H]-` test | `db0aa2c39a1e5bc3c4463f97166c9d3e3ac150cba323f44bd29b636ccbd6553b` | `00dd373d9e175b070c2bd39595ee9532fdbd94f02a344897e81480e4b7784bc2` |
86
+
87
+ ## 5. Cross-split A × B
88
+
89
+ Rebuilt from the shipped tables (`rebuild/verify_release.py`) and reproduced exactly in
90
+ `stats.json` → `cross_split`:
91
+
92
+ * all 441,829 preprocessed split-B rows exist in `row_formula_fold.csv`, each mapped to
93
+ exactly one split-A fold;
94
+ * compound-level cross-tab (per polarity), spectra-level cross-tab (per split-B table and
95
+ role) and row-level cross-tab all reproduce the published matrices;
96
+ * the split-A test-fold overlap counts (31,570 `[M+H]+` rows and 13,413 `[M-H]-` rows) are
97
+ reproduced;
98
+ * every split-B compound maps to a single formula and therefore a single split-A fold.
99
+
100
+ Key numbers (see [figures_mapping.md](figures_mapping.md) §2 for the full matrices):
101
+
102
+ | quantity | `[M+H]+` | `[M-H]-` |
103
+ | --- | ---: | ---: |
104
+ | split-B compounds | 41,348 | 21,293 |
105
+ | split-B compounds in the same split-A fold | 24,360 (58.9 %) | 12,645 (59.4 %) |
106
+ | split-B test compounds that are split-A test compounds | 654 / 6,202 | 303 / 3,193 |
107
+ | split-A test spectra inside the split-B tables | 31,570 / 57,437 | 13,413 / 57,437 |
108
+
109
+ ### 5.4 Retention times (split A row metadata)
110
+
111
+ `split_A_full_msnlib/msnlib_rt.csv.gz` was exported from `MSnLib_with_rt.csv` after reading
112
+ both files in parallel and comparing them row by row:
113
+
114
+ | check | result |
115
+ | --- | --- |
116
+ | header prefix | 7-column `MSnLib.csv` header equals the first seven columns of the 8-column with-RT header | PASS |
117
+ | rows compared | 560,084 / 560,084 | PASS |
118
+ | first seven columns identical at every row | 0 mismatches | PASS |
119
+ | extra rows at the end of either file | 0 / 0 | PASS |
120
+ | unparsable RT values | 0 / 560,084 | PASS |
121
+ | distinct RT strings | 8,369 (RT is not constant) | PASS |
122
+
123
+ Shipped table: `row_index,rt`, 560,084 rows, 1,483,069 bytes, SHA-256
124
+ `994053612db874f7ac7985f278e04cc3463f3b93cd649a195bd167c4c6c7d3d8`; gzipped only (no
125
+ plain twin) to keep the package compact, and recorded in `stats.json` →
126
+ `splits.A.retention_times` and `verification.rt_export`.
127
+
128
+ ## 6. Release integrity
129
+
130
+ `rebuild/verify_release.py` also verifies:
131
+
132
+ * every plain `.csv` is byte-identical to its `.csv.gz` twin (16 pairs);
133
+ * `stats.json` documents exactly the shipped files (except `stats.json` and `SHA256SUMS`)
134
+ and every recorded byte size and SHA-256 matches;
135
+ * `SHA256SUMS` lists every shipped file except itself and every digest matches;
136
+ * no retired legacy project naming appears anywhere in the shipped text files (the check
137
+ itself is written so that the verifier does not contain the forbidden string);
138
+ * no internal absolute paths (data-preparation workspaces, cluster scratch directories,
139
+ user home directories) and no private keys appear in the shipped text files.
140
+
141
+ Package size: 58 shipped data/document files (plus `stats.json` and `SHA256SUMS`);
142
+ 192,701,913 bytes. The `.csv.gz`-only upload subset is ≈ 23.0 MiB; the full upload is
143
+ ≈ 183.8 MiB.
144
+
145
+ ## 7. Voting units: official 5,002 source-SMILES groups and 4,888 canonical groups
146
+
147
+ The published multiple-spectrum voting task reports `n_molecules = 5002`. Verified
148
+ member-for-member: those 5,002 groups are the test spectra grouped by the **MSnLib source
149
+ SMILES string** (5,003 distinct strings, one occurring in a single spectrum → 5,002 groups
150
+ covering 57,436 spectra). This is the **official voting unit** and is shipped as
151
+ `split_A_full_msnlib/test_molecules_voting.csv`.
152
+
153
+ An alternative chemical-deduplication view groups the same test spectra by **RDKit
154
+ canonical isomeric SMILES**: 114 source-string groups merge into chemically identical
155
+ molecules, giving **4,888 groups** covering the same 57,436 spectra (the single excluded
156
+ molecule is `CC(C)(C)OC(=O)NCC1(CC(=O)O)CCCCC1`). It is shipped as
157
+ `split_A_full_msnlib/test_molecules_voting_canonical_view.csv` and is **not** the official
158
+ voting unit.
159
+
160
+ No data was altered to force either count. Details: `split_A_full_msnlib/VERIFY.md` §7 and
161
+ `stats.json` → `splits.A.anomaly`.
162
+
163
+ ## 8. What could not be verified from this package alone
164
+
165
+ * The peak arrays themselves (`mzs`/`intensities`) are not part of this manifest; they are
166
+ hosted in the same Hugging Face dataset (`dsadd4/UltraMS-MSnLib-Benchmark`) as
167
+ `MSnLib.csv` (752,707,651 bytes, SHA-256
168
+ `be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07`), together with
169
+ `MSnLib_candidates.json` (1,368,264,026 bytes, SHA-256
170
+ `125a1cdcc57a3fcef8cc76d5322ac0c434cd09b0bfb9e0c9d28bddf052f45fcc`). The row pointers and
171
+ `row_formula_fold.csv` are the authoritative link back to the spectra.
172
+ * The historical Figure-3 analysis artifacts themselves; only the published repository
173
+ voting-group table and the frozen protocol arrays were cross-checked.
174
+ * The exact physical row order of `MSnLib.csv` beyond what the shipped tables encode; the
175
+ package depends on the row pointers, not on reconstructing the file order.
176
+
177
+ ## 9. Reproduce this verification
178
+
179
+ ```bash
180
+ python3 rebuild/verify_release.py # 140 checks, exit 0
181
+ shasum -a 256 -c SHA256SUMS # macOS; sha256sum -c SHA256SUMS on Linux
182
+ ```
183
+
184
+ ## 10. Transcript of `rebuild/verify_release.py`
185
+
186
+ Unedited output against the final package contents (140 checks, exit status 0):
187
+
188
+ ```text
189
+ [PASS] csv.gz twins byte-identical to plain csv
190
+ [PASS] B/pos: protocol adduct vocabulary == [M+H]+ :: ['[M+H]+']
191
+ [PASS] B/pos: preprocessed row metadata covers all 301,636 rows uniquely
192
+ [PASS] B/pos: compound split counts match manifest :: {'train': 28944, 'val': 6202, 'test': 6202} vs {'test': 6202, 'train': 28944, 'val': 6202}
193
+ [PASS] B/pos: compound vocabulary is exactly the frozen smiles vocabulary :: 41348 vs 41348
194
+ [PASS] B/pos: compound_ids unique
195
+ [PASS] B/pos: spectra per compound sum to manifest valid rows :: 301636
196
+ [PASS] B/pos: split table columns are the released schema :: ['polarity', 'compound_id', 'canonical_isomeric_smiles', 'split', 'n_spectra', 'n_frozen_queries', 'n_raw_smiles_variants', 'first_msnlib_csv_data_row']
197
+ [PASS] B/pos: train/val/test compound sets pairwise disjoint
198
+ [PASS] B/pos: the three compound sets cover the whole vocabulary
199
+ [PASS] B/pos/val: query count 6,202 matches manifest :: 6202 vs 6202
200
+ [PASS] B/pos/val: library count 250,424 matches manifest :: 250424 vs 250424
201
+ [PASS] B/pos/val: ordered query SMILES sha256 matches manifest
202
+ [PASS] B/pos/val: ordered library SMILES sha256 matches manifest
203
+ [PASS] B/pos/val: table row order == frozen query_index/library_index
204
+ [PASS] B/pos/val: query rows and library rows are disjoint :: 0 shared rows
205
+ [PASS] B/pos/val: queries are one spectrum per compound in this fold
206
+ [PASS] B/pos/val: library compounds respect the fold scope
207
+ [PASS] B/pos/val: query table maps to protocol_pos.npz query rows
208
+ [PASS] B/pos/val: library table maps to protocol_pos.npz library rows
209
+ [PASS] B/pos/val: source rows unique in each table
210
+ [PASS] B/pos/val: n_library_positives column reproduces from the library table
211
+ (pos/val queries with a library positive: 6,194 / 6,202)
212
+ [PASS] B/pos/val: adduct column is strict [M+H]+ everywhere
213
+ [PASS] B/pos/val: csv line = data row + 2 (header offset, no embedded newlines)
214
+ [PASS] B/pos/val: precursor_mz/n_peaks agree with frozen row metadata (queries)
215
+ [PASS] B/pos/val: query/library table columns are the released schema
216
+ [PASS] B/pos/test: query count 6,202 matches manifest :: 6202 vs 6202
217
+ [PASS] B/pos/test: library count 295,434 matches manifest :: 295434 vs 295434
218
+ [PASS] B/pos/test: ordered query SMILES sha256 matches manifest
219
+ [PASS] B/pos/test: ordered library SMILES sha256 matches manifest
220
+ [PASS] B/pos/test: table row order == frozen query_index/library_index
221
+ [PASS] B/pos/test: query rows and library rows are disjoint :: 0 shared rows
222
+ [PASS] B/pos/test: queries are one spectrum per compound in this fold
223
+ [PASS] B/pos/test: library compounds respect the fold scope
224
+ [PASS] B/pos/test: query table maps to protocol_pos.npz query rows
225
+ [PASS] B/pos/test: library table maps to protocol_pos.npz library rows
226
+ [PASS] B/pos/test: source rows unique in each table
227
+ [PASS] B/pos/test: n_library_positives column reproduces from the library table
228
+ [PASS] B/pos/test: queries with an exact-adduct library positive == manifest (6,201) :: 6201
229
+ [PASS] B/pos/test: source-row hashes match manifest
230
+ [PASS] B/pos/test: adduct column is strict [M+H]+ everywhere
231
+ [PASS] B/pos/test: csv line = data row + 2 (header offset, no embedded newlines)
232
+ [PASS] B/pos/test: precursor_mz/n_peaks agree with frozen row metadata (queries)
233
+ [PASS] B/pos/test: query/library table columns are the released schema
234
+ [PASS] B/pos: test queries + test library partition all preprocessed rows
235
+ [PASS] B/pos: protocol train_rows all belong to train compounds
236
+ [PASS] B/pos: protocol val_query_rows all belong to val compounds
237
+ [PASS] B/pos: protocol test_query_rows all belong to test compounds
238
+ [PASS] B/pos: source MSnLib.csv sha256 recorded
239
+ [PASS] B/neg: protocol adduct vocabulary == [M-H]- :: ['[M-H]-']
240
+ [PASS] B/neg: preprocessed row metadata covers all 140,193 rows uniquely
241
+ [PASS] B/neg: compound split counts match manifest :: {'train': 14907, 'val': 3193, 'test': 3193} vs {'test': 3193, 'train': 14907, 'val': 3193}
242
+ [PASS] B/neg: compound vocabulary is exactly the frozen smiles vocabulary :: 21293 vs 21293
243
+ [PASS] B/neg: compound_ids unique
244
+ [PASS] B/neg: spectra per compound sum to manifest valid rows :: 140193
245
+ [PASS] B/neg: split table columns are the released schema :: ['polarity', 'compound_id', 'canonical_isomeric_smiles', 'split', 'n_spectra', 'n_frozen_queries', 'n_raw_smiles_variants', 'first_msnlib_csv_data_row']
246
+ [PASS] B/neg: train/val/test compound sets pairwise disjoint
247
+ [PASS] B/neg: the three compound sets cover the whole vocabulary
248
+ [PASS] B/neg/val: query count 3,193 matches manifest :: 3193 vs 3193
249
+ [PASS] B/neg/val: library count 116,135 matches manifest :: 116135 vs 116135
250
+ [PASS] B/neg/val: ordered query SMILES sha256 matches manifest
251
+ [PASS] B/neg/val: ordered library SMILES sha256 matches manifest
252
+ [PASS] B/neg/val: table row order == frozen query_index/library_index
253
+ [PASS] B/neg/val: query rows and library rows are disjoint :: 0 shared rows
254
+ [PASS] B/neg/val: queries are one spectrum per compound in this fold
255
+ [PASS] B/neg/val: library compounds respect the fold scope
256
+ [PASS] B/neg/val: query table maps to protocol_neg.npz query rows
257
+ [PASS] B/neg/val: library table maps to protocol_neg.npz library rows
258
+ [PASS] B/neg/val: source rows unique in each table
259
+ [PASS] B/neg/val: n_library_positives column reproduces from the library table
260
+ (neg/val queries with a library positive: 3,163 / 3,193)
261
+ [PASS] B/neg/val: adduct column is strict [M-H]- everywhere
262
+ [PASS] B/neg/val: csv line = data row + 2 (header offset, no embedded newlines)
263
+ [PASS] B/neg/val: precursor_mz/n_peaks agree with frozen row metadata (queries)
264
+ [PASS] B/neg/val: query/library table columns are the released schema
265
+ [PASS] B/neg/test: query count 3,193 matches manifest :: 3193 vs 3193
266
+ [PASS] B/neg/test: library count 137,000 matches manifest :: 137000 vs 137000
267
+ [PASS] B/neg/test: ordered query SMILES sha256 matches manifest
268
+ [PASS] B/neg/test: ordered library SMILES sha256 matches manifest
269
+ [PASS] B/neg/test: table row order == frozen query_index/library_index
270
+ [PASS] B/neg/test: query rows and library rows are disjoint :: 0 shared rows
271
+ [PASS] B/neg/test: queries are one spectrum per compound in this fold
272
+ [PASS] B/neg/test: library compounds respect the fold scope
273
+ [PASS] B/neg/test: query table maps to protocol_neg.npz query rows
274
+ [PASS] B/neg/test: library table maps to protocol_neg.npz library rows
275
+ [PASS] B/neg/test: source rows unique in each table
276
+ [PASS] B/neg/test: n_library_positives column reproduces from the library table
277
+ [PASS] B/neg/test: queries with an exact-adduct library positive == manifest (3,160) :: 3160
278
+ [PASS] B/neg/test: source-row hashes match manifest
279
+ [PASS] B/neg/test: adduct column is strict [M-H]- everywhere
280
+ [PASS] B/neg/test: csv line = data row + 2 (header offset, no embedded newlines)
281
+ [PASS] B/neg/test: precursor_mz/n_peaks agree with frozen row metadata (queries)
282
+ [PASS] B/neg/test: query/library table columns are the released schema
283
+ [PASS] B/neg: test queries + test library partition all preprocessed rows
284
+ [PASS] B/neg: protocol train_rows all belong to train compounds
285
+ [PASS] B/neg: protocol val_query_rows all belong to val compounds
286
+ [PASS] B/neg: protocol test_query_rows all belong to test compounds
287
+ [PASS] B/neg: source MSnLib.csv sha256 recorded
288
+ [PASS] B: cross-polarity pos-test x neg-test intersection reproduces stats.json :: 354 vs 354
289
+ [PASS] A: formula_split columns :: ['formula', 'fold', 'n_spectra']
290
+ [PASS] A: formula_split has 21,107 unique formulas
291
+ [PASS] A: formula fold values are train/val/test
292
+ [PASS] A: formula-level counts 16,885 / 2,110 / 2,112 :: {'train': 16885, 'val': 2110, 'test': 2112}
293
+ [PASS] A: spectra counts 446,667 / 55,980 / 57,437 :: {'train': 446667, 'val': 55980, 'test': 57437}
294
+ [PASS] A: total spectra = 560,084
295
+ [PASS] A: row_formula_fold covers rows 0..560,083 in order
296
+ [PASS] A: every formula occurs in exactly one fold
297
+ [PASS] A: row_formula_fold agrees with formula_split (fold and n_spectra)
298
+ [PASS] A: row-level fold totals match formula_split
299
+ [PASS] A: test_spectra columns are the released schema :: ['row_index', 'smiles', 'precursor_mz', 'adduct', 'collision_energy', 'fold', 'canonical_isomeric_smiles']
300
+ [PASS] A: test_spectra has 57,437 rows, all fold=test
301
+ [PASS] A: test_spectra row_index equals the rows marked test in row_formula_fold
302
+ [PASS] A: val_spectra has 55,980 rows, all fold=val
303
+ [PASS] A: val_spectra row_index equals the rows marked val in row_formula_fold
304
+ [PASS] A: official voting-unit table columns are group_id, smiles, n_spectra :: ['group_id', 'smiles', 'n_spectra']
305
+ [PASS] A: official voting-unit table (MSnLib source SMILES) reproduces from test_spectra
306
+ [PASS] A: official voting-unit table has 5,002 groups / 57,436 spectra
307
+ [PASS] A: canonical-view table columns are group_id, canonical_isomeric_smiles, n_spectra :: ['group_id', 'canonical_isomeric_smiles', 'n_spectra']
308
+ [PASS] A: canonical-view table reproduces from test_spectra
309
+ [PASS] A: canonical-view table has 4,888 groups / 57,436 spectra
310
+ [PASS] A: exactly one test spectrum lies outside the voting tables :: CC(C)(C)OC(=O)NCC1(CC(=O)O)CCCCC1
311
+ [PASS] A: retention-time companion table is shipped and matches stats.json :: split_A_full_msnlib/msnlib_rt.csv.gz
312
+ [PASS] A: retention-time table columns are row_index, rt :: ['row_index', 'rt']
313
+ [PASS] A: retention-time table has 560,084 rows in row order
314
+ [PASS] A: every retention time is present and numeric :: 0 empty, 0 non-numeric
315
+ [PASS] A/B: every split-B table row exists in row_formula_fold :: 0 missing
316
+ [PASS] A/B: split-B tables cover all 441,829 preprocessed spectra :: 441829
317
+ [PASS] A/B: compound-level cross tab reproduces stats.json
318
+ [PASS] A/B: spectra-level cross tab reproduces stats.json
319
+ [PASS] A/B: row-level split-B x split-A cross tab reproduces stats.json
320
+ [PASS] A/B: row-level split-B totals equal the manifest split-spectra counts
321
+ [PASS] A/B/pos: A-test rows inside the split-B tables reproduce stats.json :: 31570 vs 31570
322
+ [PASS] A/B/neg: A-test rows inside the split-B tables reproduce stats.json :: 13413 vs 13413
323
+ [PASS] A/B: every split-B compound has a single split-A fold (same formula)
324
+ [PASS] stats.json documents exactly the shipped files (except stats.json and SHA256SUMS) :: missing=[] extra=[]
325
+ [PASS] stats.json byte sizes and sha256 match every shipped file
326
+ [PASS] SHA256SUMS parses as '<sha256> <path>' lines
327
+ [PASS] SHA256SUMS covers every shipped file except itself :: 60 entries
328
+ [PASS] SHA256SUMS hashes match the files
329
+ [PASS] no retired legacy project naming anywhere in the shipped text files
330
+ [PASS] no internal absolute paths or private keys in the shipped text files
331
+
332
+ 140/140 checks passed
333
+ ```
334
+
335
+ ## 11. Version
336
+
337
+ Release `1.0.0`, generated 2026-11-04. Any change to the tables or protocol files
338
+ invalidates these hashes and requires a new version directory.
figures_mapping.md ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Figure → split mapping
2
+
3
+ This package contains the two frozen MSnLib splits behind the UltraMS manuscript. They are
4
+ different objects and answer different questions:
5
+
6
+ * **Split A — UltraMS MSnLib formula-level split** (`split_A_full_msnlib/`): the complete
7
+ MSnLib library (560,084 spectra, all adducts) split by molecular formula into 16,885 /
8
+ 2,110 / 2,112 formulas and 446,667 / 55,980 / 57,437 spectra (train / validation / test).
9
+ Formula-disjoint, not molecule-disjoint. Test fold: 57,437 spectra, 2,112 formulas,
10
+ 5,003 source SMILES / 4,889 canonical molecules.
11
+ * **Split B — strict-adduct molecule-level split** (`splits/`, `queries/`, `libraries/`):
12
+ the strict `[M+H]+` and `[M-H]-` subsets (447,956 source rows) re-split 70/15/15 at the
13
+ level of RDKit canonical isomeric SMILES, separately per polarity, with frozen queries
14
+ and libraries for spectrum-to-spectrum library search. Molecule-disjoint within each
15
+ polarity. Test tasks: 6,202 positive and 3,193 negative queries against 295,434 and
16
+ 137,000 library spectra.
17
+
18
+ ## 1. Panel mapping
19
+
20
+ | figure panel | split | evaluation population / task |
21
+ | --- | --- | --- |
22
+ | Figure 2b — ionization-polarity recognition | **A** | polarity prediction over the split-A evaluation population (A test fold; A train / validation used for fitting and reference). |
23
+ | Figure 2j — peak-token embedding chemical atlas | **A** | peak-token embedding visualization/analysis over the split-A test fold with split-A reference spectra; colours are chemical properties, not a model output. |
24
+ | Figure 3a — single-spectrum candidate ranking (Hit@1/5/20) | **A** | 57,437 split-A test spectra as queries, ranked against the per-formula candidate tables used by the manuscript (candidate ranking tables are part of the UltraMS repository, not of this split package). |
25
+ | Figure 3b — score/rank density and cumulative Top-k | **A** | same 57,437 split-A test queries and their candidate rankings. |
26
+ | Figure 3d — multiple-spectrum voting | **A** | 57,437 split-A test spectra grouped into the **official voting units: 5,002 MSnLib source-SMILES groups covering 57,436 spectra** (`split_A_full_msnlib/test_molecules_voting.csv`); the alternative canonical-isomeric-SMILES view (4,888 groups, same 57,436 spectra) is `split_A_full_msnlib/test_molecules_voting_canonical_view.csv`; the retention times used by this analysis are `split_A_full_msnlib/msnlib_rt.csv.gz` (`row_index, rt`). See the parent `README.md` §4.3/§4.5. |
27
+ | Figure 3g — empirical rank CDF | **A** | 57,437 split-A test queries. |
28
+ | Figure 3a_sp_4 — label-blind consensus grouping | **A** | split-A test fold, label-blind grouping of same-molecule spectra. |
29
+ | Figure 3a_sp_5 — promoted MSnLib fingerprint analysis | **A** | split-A fingerprint-prediction evaluation population (split-A train / validation for fitting). |
30
+ | baselines — single-spectrum Top-1 table | **A** | 57,437 split-A test queries, one ranking per method. |
31
+ | Figure 3e — strict-adduct library search, FDR–recall | **B** | strict `[M+H]+`: 6,202 test queries vs 295,434 library spectra (recall denominator 6,201); strict `[M-H]-`: 3,193 vs 137,000 (denominator 3,160). Validation tasks: 6,202 / 250,424 and 3,193 / 116,135. |
32
+ | Figure 3f — cross-polarity molecular retrieval | **B** | molecule-level split-B compounds; one polarity's spectra query the other polarity's library. |
33
+ | Figure 3h — seven-method strict-adduct FDR–recall (unused figure) | **B** | same split-B query / library sets as Figure 3e. |
34
+ | Figure 3h_sp_1 — FDR threshold transfer | **B** | split-B validation/test query identities; 200 paired molecule-disjoint calibration/held-out assignments over those identities. |
35
+ | cross-collision-energy search | **B** | split-B test queries that have at least two collision energies: **6,161** positive and **2,999** negative cross-CE queries (from 6,202 / 3,193 split-B test queries). |
36
+ | NPLIB1 and MassSpecGym comparison panels | **not this dataset** | NPLIB1 (3,699 test molecules) and MassSpecGym are independent external benchmarks with their own splits and libraries; they are not derived from MSnLib and are not covered by this package. |
37
+ | Figure 3c / Figure 3i case studies | **neither** | case-study panels use specific MSnLib spectra and MAGMa peak annotations; they are not defined by either split table. |
38
+
39
+ ## 2. Cross-split inconsistency: split A (formulas) vs split B (compounds)
40
+
41
+ The two splits are built on different units (formula vs canonical molecule) and different
42
+ populations (all adducts vs strict `[M+H]+`/`[M-H]-`), so their fold labels disagree for a
43
+ large share of compounds. The tables below are computed by mapping every split-B compound
44
+ to its molecular formula through `msnlib_csv_data_row` → `split_A_full_msnlib/row_formula_fold.csv`.
45
+ Compound counts are split-B compounds (a compound belongs to one polarity and one split-B
46
+ fold).
47
+
48
+ ### `[M+H]+` — 41,348 compounds
49
+
50
+ | split B ↓ / split A → | train | validation | test | total |
51
+ | --- | ---: | ---: | ---: | ---: |
52
+ | **train** | 23,059 | 2,901 | 2,984 | 28,944 |
53
+ | **validation** | 4,924 | 647 | 631 | 6,202 |
54
+ | **test** | 4,922 | 626 | **654** | 6,202 |
55
+ | total | 32,905 | 4,174 | 4,269 | 41,348 |
56
+
57
+ Same-fold compounds: **24,360 / 41,348 (58.9 %)**.
58
+ Of the 6,202 split-B positive test compounds only **654 (10.5 %)** are split-A test
59
+ compounds; 4,922 (79.4 %) are split-A train compounds.
60
+
61
+ ### `[M-H]-` — 21,293 compounds
62
+
63
+ | split B ↓ / split A → | train | validation | test | total |
64
+ | --- | ---: | ---: | ---: | ---: |
65
+ | **train** | 12,035 | 1,447 | 1,425 | 14,907 |
66
+ | **validation** | 2,552 | 307 | 334 | 3,193 |
67
+ | **test** | 2,541 | 349 | **303** | 3,193 |
68
+ | total | 17,128 | 2,103 | 2,062 | 21,293 |
69
+
70
+ Same-fold compounds: **12,645 / 21,293 (59.4 %)**.
71
+ Of the 3,193 split-B negative test compounds only **303 (9.5 %)** are split-A test
72
+ compounds.
73
+
74
+ ### Spectra-level view
75
+
76
+ The split-B tables cover all 441,829 preprocessed strict-adduct spectra (301,636 positive +
77
+ 140,193 negative); each maps to exactly one split-A fold:
78
+
79
+ `[M+H]+` — 301,636 preprocessed spectra:
80
+
81
+ | split B ↓ / split A → | train | validation | test | total |
82
+ | --- | ---: | ---: | ---: | ---: |
83
+ | **train** | 168,804 | 20,917 | 22,024 | 211,745 |
84
+ | **validation** | 35,535 | 4,604 | 4,742 | 44,881 |
85
+ | **test** | 35,716 | 4,490 | **4,804** | 45,010 |
86
+ | total | 240,055 | 30,011 | 31,570 | 301,636 |
87
+
88
+ `[M-H]-` — 140,193 preprocessed spectra:
89
+
90
+ | split B ↓ / split A → | train | validation | test | total |
91
+ | --- | ---: | ---: | ---: | ---: |
92
+ | **train** | 79,644 | 9,523 | 9,234 | 98,401 |
93
+ | **validation** | 16,760 | 1,981 | 2,186 | 20,927 |
94
+ | **test** | 16,609 | 2,263 | **1,993** | 20,865 |
95
+ | total | 113,013 | 13,767 | 13,413 | 140,193 |
96
+
97
+ The spectra-level matrix is computed from the frozen `protocol/` row metadata (each
98
+ preprocessed row → its compound → its split-B fold) and `split_A_full_msnlib/row_formula_fold.csv`;
99
+ the per-split totals equal the split-B `split_spectra_counts` of the frozen manifest
100
+ (211,745 / 44,881 / 45,010 positive and 98,401 / 20,927 / 20,865 negative).
101
+
102
+ (Recompute with `rebuild/verify_release.py`, which rebuilds both matrices from the shipped
103
+ tables.)
104
+
105
+ ### Relation of the split-A test fold to split B
106
+
107
+ * 57,437 split-A test spectra in total;
108
+ * **31,570 (55.0 %)** are strict `[M+H]+` spectra of the split-B tables, **13,413 (23.3 %)**
109
+ are strict `[M-H]-` spectra; 44,983 (78.3 %) therefore lie inside split B;
110
+ * the remaining 12,454 split-A test spectra carry other adducts (`[M+FA]-`, `[M+Cl]-`,
111
+ `[M+Na]+`, `[M+NH4]+`, `[M+H-H2O]+`, …) and never occur in split B.
112
+
113
+ ### What this means — and what must not be claimed
114
+
115
+ * Split A is **formula-disjoint only**; split B is **compound-disjoint within each
116
+ polarity**. Each property holds only inside its own split.
117
+ * The two splits **cannot be merged into a global-disjointness claim**: about 41 % of the
118
+ split-B compounds are in a different split-A fold, and the same spectrum can be a *test*
119
+ spectrum in split A while belonging to a *train* compound in split B (e.g. 4,922 of the
120
+ 6,202 positive split-B test compounds are split-A train compounds).
121
+ * A score computed on an split-A test spectrum whose compound is split-B train must not be
122
+ reported as a "held-out molecule" result, and vice versa. Train and evaluate within one
123
+ split only; if a cross-split experiment is unavoidable, state explicitly which split
124
+ defines the training population and which defines the test population.
hf_dataset_card.md ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: UltraMS MSnLib benchmark (formula-level split A + strict-adduct molecule-level split B)
3
+ license: cc-by-4.0
4
+ language:
5
+ - en
6
+ size_categories:
7
+ - 100K<n<1M
8
+ task_categories:
9
+ - other
10
+ configs:
11
+ - config_name: split_A_formula_split
12
+ data_files: split_A_full_msnlib/formula_split.csv
13
+ - config_name: split_A_row_formula_fold
14
+ data_files: split_A_full_msnlib/row_formula_fold.csv
15
+ - config_name: split_A_test_spectra
16
+ data_files: split_A_full_msnlib/test_spectra.csv
17
+ - config_name: split_A_val_spectra
18
+ data_files: split_A_full_msnlib/val_spectra.csv
19
+ - config_name: split_A_test_molecules_voting_official
20
+ data_files: split_A_full_msnlib/test_molecules_voting.csv
21
+ - config_name: split_A_test_molecules_voting_canonical_view
22
+ data_files: split_A_full_msnlib/test_molecules_voting_canonical_view.csv
23
+ - config_name: split_A_msnlib_rt
24
+ data_files: split_A_full_msnlib/msnlib_rt.csv.gz
25
+ - config_name: split_B_pos_compound_split
26
+ data_files: splits/pos_compound_split.csv
27
+ - config_name: split_B_neg_compound_split
28
+ data_files: splits/neg_compound_split.csv
29
+ - config_name: split_B_pos_val_queries
30
+ data_files: queries/pos_val_queries.csv
31
+ - config_name: split_B_pos_test_queries
32
+ data_files: queries/pos_test_queries.csv
33
+ - config_name: split_B_neg_val_queries
34
+ data_files: queries/neg_val_queries.csv
35
+ - config_name: split_B_neg_test_queries
36
+ data_files: queries/neg_test_queries.csv
37
+ - config_name: split_B_pos_val_library
38
+ data_files: libraries/pos_val_library.csv
39
+ - config_name: split_B_pos_test_library
40
+ data_files: libraries/pos_test_library.csv
41
+ - config_name: split_B_neg_val_library
42
+ data_files: libraries/neg_val_library.csv
43
+ - config_name: split_B_neg_test_library
44
+ data_files: libraries/neg_test_library.csv
45
+ tags:
46
+ - chemistry
47
+ - mass-spectrometry
48
+ - metabolomics
49
+ - small-molecules
50
+ - tandem-ms
51
+ - spectrum-library-search
52
+ - molecule-retrieval
53
+ - benchmark
54
+ - ultraMS
55
+ ---
56
+
57
+ # UltraMS MSnLib benchmark
58
+
59
+ Two frozen, independent benchmark splits of the [MSnLib](https://doi.org/10.1038/s41592-025-02813-0)
60
+ tandem mass spectral library, released by UltraMS. The splits are different objects:
61
+
62
+ * **Split A — UltraMS MSnLib formula-level split** (all 560,084 spectra, all adducts):
63
+ 21,107 molecular formulas, split 16,885 / 2,110 / 2,112 formulas and
64
+ 446,667 / 55,980 / 57,437 spectra into train / validation / test. Formula-disjoint. Test
65
+ fold: 57,437 spectra, 2,112 formulas, 5,003 source SMILES / 4,889 canonical molecules.
66
+ Population for single-spectrum candidate ranking, multiple-spectrum voting, label-blind
67
+ grouping, fingerprint prediction and embedding analyses (Figure 2b/2j, 3a/3b/3d/3g,
68
+ 3a_sp_4, 3a_sp_5, single-spectrum baselines). The **official multiple-spectrum voting
69
+ units are the 5,002 MSnLib source-SMILES groups covering 57,436 spectra**
70
+ (`test_molecules_voting.csv`); a canonical-SMILES alternative view (4,888 groups) is also
71
+ provided (`test_molecules_voting_canonical_view.csv`). Per-spectrum retention times
72
+ (`row_index, rt` in seconds) are in `msnlib_rt.csv.gz` for the label-blind grouping and
73
+ multiple-spectrum voting analyses.
74
+ * **Split B — strict-adduct molecule-level split** (`[M+H]+` and `[M-H]-` only): 41,348 /
75
+ 21,293 compounds and 301,636 / 140,193 preprocessed spectra, split 70/15/15 per polarity
76
+ by RDKit canonical isomeric SMILES, with frozen queries and libraries for
77
+ spectrum-to-spectrum library search. Population for Figure 3e/3f/3h, 3h_sp_1 and the
78
+ cross-collision-energy task (6,161 positive / 2,999 negative queries).
79
+
80
+ | split-B task | queries | library spectra | queries with an exact-adduct library positive |
81
+ | --- | ---: | ---: | ---: |
82
+ | `[M+H]+` test | 6,202 | 295,434 | 6,201 |
83
+ | `[M+H]+` validation | 6,202 | 250,424 | 6,194 |
84
+ | `[M-H]-` test | 3,193 | 137,000 | 3,160 |
85
+ | `[M-H]-` validation | 3,193 | 116,135 | 3,163 |
86
+
87
+ > **Disjointness.** Split A is formula-disjoint (no formula in two folds); split B is
88
+ > molecule-disjoint within each polarity (the train / validation / test compound sets are
89
+ > pairwise empty). The two splits must **not** be merged into a global-disjointness claim:
90
+ > about 41 % of split-B compounds lie in a different split-A fold, and a spectrum can be
91
+ > split-A test while its compound is split-B train. See the package
92
+ > `figures_mapping.md` §2 for the full cross-tabulation.
93
+
94
+ ## Usage
95
+
96
+ ```python
97
+ import pandas as pd
98
+
99
+ base = "https://huggingface.co/datasets/dsadd4/UltraMS-MSnLib-Benchmark/resolve/main/"
100
+
101
+ # split A — formula-level split of the full library
102
+ formulas = pd.read_csv(base + "split_A_full_msnlib/formula_split.csv")
103
+ rows = pd.read_csv(base + "split_A_full_msnlib/row_formula_fold.csv") # 560,084 rows
104
+ test = pd.read_csv(base + "split_A_full_msnlib/test_spectra.csv") # 57,437 rows
105
+ assert formulas.groupby("formula")["fold"].nunique().max() == 1
106
+
107
+ # split B — strict-adduct molecule-level library search
108
+ compound_split = pd.read_csv(base + "splits/pos_compound_split.csv")
109
+ queries = pd.read_csv(base + "queries/pos_test_queries.csv")
110
+ library = pd.read_csv(base + "libraries/pos_test_library.csv")
111
+
112
+ positives = library.groupby("canonical_isomeric_smiles").size()
113
+ n_pos = queries["canonical_isomeric_smiles"].map(positives).fillna(0).astype(int)
114
+ denominator = int((n_pos > 0).sum()) # 6,201
115
+ ```
116
+
117
+ With `datasets` (one config per table, see the YAML header):
118
+
119
+ ```python
120
+ from datasets import load_dataset
121
+ queries = load_dataset("dsadd4/UltraMS-MSnLib-Benchmark", "split_B_pos_test_queries", split="train")
122
+ ```
123
+
124
+ Peak data are **not** part of the split tables. Every row is joined back to the spectra by
125
+ `row_index` / `msnlib_csv_data_row` / `first_msnlib_csv_data_row`, which point into
126
+ `MSnLib.csv`. `MSnLib.csv` and `MSnLib_candidates.json` are hosted in the same dataset; see
127
+ **Hosted files** below.
128
+
129
+ ## Columns
130
+
131
+ * `split_A_full_msnlib/formula_split.csv`: `formula, fold, n_spectra`
132
+ * `split_A_full_msnlib/row_formula_fold.csv`: `row_index, formula, fold`
133
+ * `split_A_full_msnlib/{test,val}_spectra.csv`: `row_index, smiles, precursor_mz, adduct,
134
+ collision_energy, fold, canonical_isomeric_smiles`
135
+ * `split_A_full_msnlib/test_molecules_voting.csv`: `group_id, smiles, n_spectra` —
136
+ **official** voting units: 5,002 MSnLib-source-SMILES groups covering 57,436 spectra, the
137
+ grouping of the published multiple-spectrum voting task (`n_molecules = 5002`)
138
+ * `split_A_full_msnlib/test_molecules_voting_canonical_view.csv`: `group_id,
139
+ canonical_isomeric_smiles, n_spectra` — alternative canonical view: 4,888 groups covering
140
+ the same 57,436 spectra
141
+ * `split_A_full_msnlib/msnlib_rt.csv.gz`: `row_index, rt` — per-spectrum retention time in
142
+ seconds, aligned 1:1 to the `MSnLib.csv` data rows (560,084 rows)
143
+ * `splits/*_compound_split.csv`: `polarity, compound_id, canonical_isomeric_smiles, split,
144
+ n_spectra, n_frozen_queries, n_raw_smiles_variants, first_msnlib_csv_data_row`
145
+ * `queries/*.csv`: `polarity, split, query_index, compound_id, canonical_isomeric_smiles,
146
+ adduct, msnlib_csv_data_row, msnlib_csv_line, precursor_mz, n_peaks, collision_energy,
147
+ source_smiles_raw, n_library_positives`
148
+ * `libraries/*.csv`: same as queries with `library_index` and `compound_split` instead of
149
+ `query_index`; row order is the frozen library order
150
+
151
+ ## Split-B evaluation protocol
152
+
153
+ 1. Score every query against the complete library of its task (no candidate short list).
154
+ 2. Correct = the top-1 library spectrum has the same canonical compound identity.
155
+ 3. Empirical FDR = `(accepted − correct) / accepted`; identification recall =
156
+ `correct / n_queries_with_library_positive` (6,201 / 3,160 for the two test tasks).
157
+ Queries without a library positive enter the FDR denominator but not the recall
158
+ denominator; `n_library_positives` is provided per query.
159
+ 4. The test library contains all preprocessed spectra of the polarity except the selected
160
+ test queries; the validation library contains train and validation compounds only.
161
+ 5. Validation is for model selection only; evaluate the test fold once.
162
+
163
+ ## Hosted files
164
+
165
+ The dataset hosts the complete manifest plus two large source files. Every file of the
166
+ manifest is checksummed in `SHA256SUMS`; the two large files are kept in a separate upload
167
+ step (see `hf_upload_commands.sh`, dry-run by default).
168
+
169
+ | hosted file | bytes | SHA-256 | purpose |
170
+ | --- | ---: | --- | --- |
171
+ | manifest: `split_A_full_msnlib/`, `splits/`, `queries/`, `libraries/`, `protocol/`, `rebuild/`, docs (59 files) | ≈ 185.2 MiB | see `SHA256SUMS` | the two benchmark splits, verifier, docs |
172
+ | `split_A_full_msnlib/msnlib_rt.csv.gz` | 1,483,069 | `994053612db874f7ac7985f278e04cc3463f3b93cd649a195bd167c4c6c7d3d8` | compact per-spectrum retention time (`row_index, rt` in seconds), aligned 1:1 to `MSnLib.csv`; used by the label-blind grouping analysis |
173
+ | `MSnLib.csv` | 752,707,651 | `be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07` | full source CSV: one row per MSnLib spectrum (560,084 rows); every row pointer in the split tables resolves here |
174
+ | `MSnLib_candidates.json` | 1,368,264,026 | `125a1cdcc57a3fcef8cc76d5322ac0c434cd09b0bfb9e0c9d28bddf052f45fcc` | candidate SMILES lists behind the single-spectrum candidate-ranking task: a JSON object mapping a query SMILES string to its candidate SMILES list (9,886 query entries) |
175
+
176
+ `MSnLib.csv` is the UltraMS CSV conversion of the MSnLib original release (Zenodo
177
+ 10.5281/zenodo.11163380, CC BY 4.0), whose 18 per-file MS2 JSONL record lists contain the
178
+ same 560,084 spectra. `MSnLib_candidates.json` contains candidate SMILES lists derived from
179
+ the MSnLib compound set; both files carry the MSnLib attribution.
180
+
181
+ ## Provenance, verification, license
182
+
183
+ * Source rows: `MSnLib.csv` (560,084 rows) converted from the MSnLib original release
184
+ (Brungs et al., CC BY 4.0; Zenodo 10.5281/zenodo.11163380).
185
+ * Hosted source files: `MSnLib.csv` (752,707,651 bytes, SHA-256 `be54b330…`) and
186
+ `MSnLib_candidates.json` (1,368,264,026 bytes, SHA-256 `125a1cdc…`).
187
+ * Frozen split-B manifest, seeds 42 / 43, query seed 119; frozen split-A fold assignment
188
+ from the `fold` column of `MSnLib.csv`.
189
+ * `SHA256SUMS` covers every file; `rebuild/verify_release.py` is a self-contained verifier
190
+ that re-checks every count, ordering hash, disjointness statement, cross-split statistic
191
+ and checksum offline.
192
+ * License **CC BY 4.0**, with attribution to MSnLib (CC BY 4.0); Apache-2.0 for the two
193
+ UltraMS producer scripts. See the package `NOTICE.md`.
194
+
195
+ ## Citation
196
+
197
+ ```bibtex
198
+ @misc{ultrams_msnlib_benchmark_2026,
199
+ title = {UltraMS MSnLib benchmark: full-library formula-level split and strict-adduct molecule-level library-search split},
200
+ author = {Li, Yifan and Zhong, Yunhua and Liu, Pan and Xia, Jun},
201
+ year = {2026},
202
+ note = {Derived from MSnLib (Brungs, Schmid, Pluskal; CC BY 4.0, Zenodo 10.5281/zenodo.11163380)},
203
+ howpublished = {Hugging Face / Zenodo dataset, version 1.0.0}
204
+ }
205
+ ```
206
+
207
+ Please also cite MSnLib (doi:10.1038/s41592-025-02813-0) and the UltraMS manuscript.
hf_upload_commands.sh ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Upload ultrams_msnlib_benchmark_v1 to Hugging Face.
3
+ #
4
+ # THIS SCRIPT HAS NOT BEEN EXECUTED for this package. It is a reviewed command draft:
5
+ # every command is printed first, and nothing is uploaded unless you pass --execute.
6
+ #
7
+ # ./hf_upload_commands.sh # print the commands and the pre-flight checklist
8
+ # ./hf_upload_commands.sh --gz-only # same, but upload only the *.csv.gz tables
9
+ # ./hf_upload_commands.sh --execute # actually run them (requires HF_TOKEN in the env)
10
+ #
11
+ # Managed files: every file of this manifest (~185 MiB, including the compact retention-time
12
+ # table split_A_full_msnlib/msnlib_rt.csv.gz), plus two large source files that
13
+ # are hosted alongside it because the split tables point into them:
14
+ # MSnLib.csv 752,707,651 B sha256 be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07
15
+ # MSnLib_candidates.json 1,368,264,026 B sha256 125a1cdcc57a3fcef8cc76d5322ac0c434cd09b0bfb9e0c9d28bddf052f45fcc
16
+ # Set MSNLIB_DATA_DIR to the directory that contains those two files (or override the two
17
+ # individual paths).
18
+ #
19
+ # Prerequisites (not installed by this script):
20
+ # python -m pip install -U "huggingface_hub[cli]"
21
+ # export HF_TOKEN=... # never commit a token, never paste one into this repo
22
+ set -euo pipefail
23
+
24
+ PKG_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
25
+ REPO_TYPE="dataset"
26
+ # Dataset id placeholder agreed for the UltraMS MSnLib benchmark.
27
+ REPO_ID="${HF_DATASET_REPO_ID:-dsadd4/UltraMS-MSnLib-Benchmark}"
28
+ VISIBILITY="${HF_DATASET_VISIBILITY:-public}"
29
+ COMMIT_MESSAGE="UltraMS MSnLib benchmark v1.0.0 (formula-level split A + strict-adduct molecule-level split B)"
30
+ # Large hosted files (not part of this manifest).
31
+ DATA_DIR="${MSNLIB_DATA_DIR:-/path/to/data-workspace/datasets/MSnLib}"
32
+ MSNLIB_CSV="${MSNLIB_CSV:-$DATA_DIR/MSnLib.csv}"
33
+ MSNLIB_CANDIDATES="${MSNLIB_CANDIDATES:-$DATA_DIR/MSnLib_candidates.json}"
34
+ MSNLIB_CSV_SHA256="be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07"
35
+ MSNLIB_CANDIDATES_SHA256="125a1cdcc57a3fcef8cc76d5322ac0c434cd09b0bfb9e0c9d28bddf052f45fcc"
36
+
37
+ GZ_ONLY=0
38
+ EXECUTE=0
39
+ for arg in "$@"; do
40
+ case "$arg" in
41
+ --gz-only) GZ_ONLY=1 ;;
42
+ --execute) EXECUTE=1 ;;
43
+ -h|--help)
44
+ sed -n '2,17p' "${BASH_SOURCE[0]}"
45
+ exit 0
46
+ ;;
47
+ *)
48
+ echo "unknown argument: $arg" >&2
49
+ exit 2
50
+ ;;
51
+ esac
52
+ done
53
+
54
+ UPLOAD_ARGS=("$REPO_ID" "$PKG_DIR" --repo-type "$REPO_TYPE" --commit-message "$COMMIT_MESSAGE")
55
+ if [[ "$GZ_ONLY" == 1 ]]; then
56
+ # skip the plain CSV copies and the local-only bookkeeping files
57
+ UPLOAD_ARGS+=(--exclude "*.csv" --exclude ".DS_Store")
58
+ fi
59
+
60
+ echo "package : $PKG_DIR"
61
+ echo "repo : $REPO_ID (type=$REPO_TYPE, visibility=$VISIBILITY)"
62
+ echo "mode : $([[ $GZ_ONLY == 1 ]] && echo '*.csv.gz + docs + protocol only' || echo 'everything')"
63
+ echo "large : $MSNLIB_CSV (752,707,651 B)"
64
+ echo " $MSNLIB_CANDIDATES (1,368,264,026 B)"
65
+ echo
66
+ echo "--- pre-flight checklist (all must be true before uploading) ---"
67
+ cat <<'CHECKLIST'
68
+ [ ] 1. shasum -a 256 -c SHA256SUMS (macOS) or sha256sum -c SHA256SUMS (Linux)
69
+ reports OK for every file.
70
+ [ ] 2. python3 rebuild/verify_release.py exits 0 with every check PASS and no FAIL.
71
+ [ ] 3. No retired legacy project naming: grep -rni "<retired project name>" . | wc -l -> 0
72
+ (the verifier checks this automatically; do not create files that reintroduce it).
73
+ [ ] 4. No internal absolute paths from the build environment (data-preparation
74
+ workspaces, cluster scratch directories, user home directories) and no password/token value
75
+ is present in any file; the verifier checks this automatically.
76
+ [ ] 5. Human sign-off on: dataset id (dsadd4/UltraMS-MSnLib-Benchmark), visibility, author
77
+ list in hf_dataset_card.md, license (CC BY 4.0) and the MSnLib attribution in NOTICE.md.
78
+ [ ] 6. HF_TOKEN is exported in the current shell only (never written to disk).
79
+ [ ] 7. Total upload size is understood: ~185 MiB manifest (+ ~24 MiB with --gz-only instead
80
+ of the plain CSVs) plus 752,707,651 B MSnLib.csv and 1,368,264,026 B
81
+ MSnLib_candidates.json (≈ 2.1 GiB in total).
82
+ [ ] 8. The two large hosted files are checked before upload:
83
+ sha256sum "$MSNLIB_CSV" -> be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07
84
+ sha256sum "$MSNLIB_CANDIDATES" -> 125a1cdcc57a3fcef8cc76d5322ac0c434cd09b0bfb9e0c9d28bddf052f45fcc
85
+ [ ] 9. The dataset card upload must refresh hf_dataset_card.md as the card (YAML header first).
86
+ CHECKLIST
87
+ echo
88
+ echo "--- commands ---"
89
+ cat <<EOF
90
+ hf auth whoami
91
+ hf auth login --token "\$HF_TOKEN" # or: python -m huggingface_hub.commands.huggingface_cli login
92
+ hf repo create "$REPO_ID" --repo-type "$REPO_TYPE" --$VISIBILITY
93
+ # 1) the manifest (splits, protocol, rebuild scripts, docs; no spectra)
94
+ hf upload ${UPLOAD_ARGS[*]}
95
+ # 2) the large hosted source files (separate step; ~2.1 GiB of data)
96
+ hf upload "$REPO_ID" "$MSNLIB_CSV" "MSnLib.csv" --repo-type "$REPO_TYPE" --commit-message "$COMMIT_MESSAGE"
97
+ hf upload "$REPO_ID" "$MSNLIB_CANDIDATES" "MSnLib_candidates.json" --repo-type "$REPO_TYPE" --commit-message "$COMMIT_MESSAGE"
98
+ EOF
99
+ echo
100
+ echo "--- post-upload ---"
101
+ cat <<'EOF'
102
+ Refresh the dataset card from hf_dataset_card.md (the YAML header must stay at the top),
103
+ then verify the remote file list and sizes against SHA256SUMS, and finally re-download one
104
+ table (both a split-A and a split-B table) and compare its SHA-256 with the local copy.
105
+ Nothing in this repository is required for that check.
106
+ EOF
107
+
108
+ if [[ "$EXECUTE" != 1 ]]; then
109
+ echo
110
+ echo "dry run: nothing uploaded. Re-run with --execute once the checklist is signed off."
111
+ exit 0
112
+ fi
113
+
114
+ : "${HF_TOKEN:?set HF_TOKEN in the environment before using --execute}"
115
+ command -v hf >/dev/null || {
116
+ echo "the 'hf' CLI is not installed: python -m pip install -U 'huggingface_hub[cli]'" >&2
117
+ exit 1
118
+ }
119
+
120
+ : "${MSNLIB_CSV:?set MSNLIB_DATA_DIR or MSNLIB_CSV to the MSnLib.csv path}"
121
+ : "${MSNLIB_CANDIDATES:?set MSNLIB_DATA_DIR or MSNLIB_CANDIDATES to the MSnLib_candidates.json path}"
122
+ set -x
123
+ hf auth login --token "$HF_TOKEN"
124
+ hf repo create "$REPO_ID" --repo-type "$REPO_TYPE" "--$VISIBILITY" || true
125
+ hf upload "${UPLOAD_ARGS[@]}"
126
+ hf upload "$REPO_ID" "$MSNLIB_CSV" "MSnLib.csv" --repo-type "$REPO_TYPE" --commit-message "$COMMIT_MESSAGE"
127
+ hf upload "$REPO_ID" "$MSNLIB_CANDIDATES" "MSnLib_candidates.json" --repo-type "$REPO_TYPE" --commit-message "$COMMIT_MESSAGE"
128
+ set +x
129
+ echo "upload finished; verify the remote tree and checksums before announcing the release."
libraries/neg_test_library.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0ebc03945ef98d0ab812461f1bf5ac3aeb739d01022ff39e16fe389adba75ad
3
+ size 23043794
libraries/neg_test_library.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1d9a677f399a8c3ebadb8d8851fb95cf2a3c33800bb22333360aaef65f82048
3
+ size 2318848
libraries/neg_val_library.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9af61236009ea964ca36648ed7159dcea67d7cac69af753998006ac84aab0b2e
3
+ size 19394902
libraries/neg_val_library.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:350374662395d238ab050c36cc9d61f100b51efb6e93f6ea5fea88c96ef90721
3
+ size 1964913
libraries/pos_test_library.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:42ce92e4f7b38235cda9aaf4b0e920af7b57dc6baee269932caeb6e1f5eec862
3
+ size 48095578
libraries/pos_test_library.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:967f23c327a738febccd50c6db405ec1d59b10e0daedc559a347bf114da4ac3b
3
+ size 4870739
libraries/pos_val_library.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c9b0d8a9f9c12fc3ccef32da2ea9909214c401e762fb679389167f5debe5852
3
+ size 40549305
libraries/pos_val_library.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3fad6edbd573b9c65286d7c75968881566e280fdfe1b782318b928cce0b6fd74
3
+ size 4130848
protocol/README.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Frozen protocol files
2
+
3
+ These files are the authoritative definition of the benchmark. The CSV tables in
4
+ `splits/`, `queries/` and `libraries/` are a human-readable view of them; if the two ever
5
+ disagree, the protocol files win.
6
+
7
+ ## Files
8
+
9
+ | file | content |
10
+ | --- | --- |
11
+ | `manifest_summary.json` | the frozen manifest of the historical Figure 3h producer: counts, seeds, per-split sizes, ordered-SMILES and source-row SHA-256 values, vocabulary sizes, artifact hashes, input CSV/h5 hashes |
12
+ | `protocol_pos.npz` | row-index arrays of the `[M+H]+` task |
13
+ | `protocol_neg.npz` | row-index arrays of the `[M-H]-` task |
14
+ | `smiles_pos.json` | list of canonical isomeric SMILES of the 41,348 positive compounds; a row's compound is `smiles_pos.json[smiles_index]` |
15
+ | `smiles_neg.json` | same for the 21,293 negative compounds |
16
+ | `adducts_pos.json`, `adducts_neg.json` | `["[M+H]+"]`, `["[M-H]-"]` — the strict adduct of each task |
17
+ | `derived/row_metadata_pos.npz`, `derived/row_metadata_neg.npz` | per-preprocessed-row metadata extracted from the (not redistributed) preprocessed-spectra HDF5 file |
18
+
19
+ ## `protocol_*.npz` arrays
20
+
21
+ Each archive has five 1-D `int64` arrays. Their indices are **frozen preprocessed row
22
+ ids**: `0 … 301,635` for `pos`, `0 … 140,192` for `neg`. Row ids follow the source order of
23
+ `MSnLib.csv` after the strict-adduct filter and the peak preprocessing; `derived/row_metadata_*.npz`
24
+ maps them to `MSnLib.csv` data rows.
25
+
26
+ | array | content | length (`pos` / `neg`) |
27
+ | --- | --- | --- |
28
+ | `train_rows` | training spectra, ordered "sorted train compound, then source order" | 211,745 / 98,401 |
29
+ | `val_query_rows` | the validation queries, ordered by sorted validation compound | 6,202 / 3,193 |
30
+ | `val_library_rows` | validation library, canonical-compound insertion order minus the validation queries | 250,424 / 116,135 |
31
+ | `test_query_rows` | the test queries, ordered by sorted test compound | 6,202 / 3,193 |
32
+ | `test_library_rows` | test library, canonical-compound insertion order minus the test queries | 295,434 / 137,000 |
33
+
34
+ Invariants (all checked by `rebuild/verify_release.py`):
35
+
36
+ * `test_query_rows` and `test_library_rows` are disjoint and together are exactly
37
+ `0 … N-1`: the test library is every preprocessed spectrum of the polarity minus the
38
+ selected test queries.
39
+ * `val_query_rows` and `val_library_rows` are disjoint and only contain compounds of the
40
+ train or validation fold; test compounds never appear in the validation task.
41
+ * The compound sets behind `train_rows`, `val_query_rows` and `test_query_rows` are the
42
+ pairwise-disjoint train / validation / test compound sets.
43
+
44
+ ## `derived/row_metadata_*.npz` arrays
45
+
46
+ | array | dtype | meaning |
47
+ | --- | --- | --- |
48
+ | `source_row` | int64 | 0-based data row in `MSnLib.csv` (physical line = `source_row + 2`) |
49
+ | `smiles_index` | int32 | index into `smiles_*.json` |
50
+ | `adduct_index` | int16 | index into `adducts_*.json` (always 0 here) |
51
+ | `n_peaks` | uint16 | peaks kept by the preprocessing (≤ 150) |
52
+ | `precursor_mz` | float32 | precursor m/z as stored by the frozen protocol |
53
+
54
+ These arrays are *derived* from the historical preprocessed-spectra file and are not part
55
+ of the original manifest; they are included so that the package can be joined back to
56
+ `MSnLib.csv` and to the row-index arrays without that file. Their hashes are in
57
+ `../SHA256SUMS` like every other file.
58
+
59
+ ## `manifest_summary.json` redaction
60
+
61
+ The frozen file recorded the absolute path of the original data-preparation workspace in
62
+ its `csv` field. The released copy replaces only that string with
63
+ `<original data-preparation workspace>/datasets/MSnLib/MSnLib.csv`; every count, seed, hash
64
+ and identity field is byte-identical. Original file SHA-256
65
+ `b83656b2b4d265d1d4ea49df30372e844e207863a7ab768f44f241bd68b8186e`; released copy SHA-256
66
+ `6129ed094df59265a684f436da146ef554d9c774e01768363bf58704f87ec237`. See `../VERIFY.md`.
67
+
68
+ ## Ordered-list hashes
69
+
70
+ `ordered_query_smiles_sha256`, `ordered_library_smiles_sha256` (validation and test),
71
+ `query_source_row_sha256` and `library_source_row_sha256` (test) are SHA-256 digests of the
72
+ corresponding sequence joined with `"\n"` (no trailing newline), computed over the strings
73
+ in frozen order. They can be recomputed directly from the CSV tables — see
74
+ `rebuild/verify_release.py`, which does exactly that and compares against
75
+ `manifest_summary.json`.
protocol/adducts_neg.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [
2
+ "[M-H]-"
3
+ ]
protocol/adducts_pos.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [
2
+ "[M+H]+"
3
+ ]
protocol/derived/row_metadata_neg.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e566e864b2a8e34d222a7442f8e561367c92cd8d3d80c12246c0320efe5e7374
3
+ size 439353
protocol/derived/row_metadata_pos.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:02aee46a092b4950fa46a5bded773e1946a1296a42aa33e45a8ed24313813b24
3
+ size 927520
protocol/manifest_summary.json ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "adduct_sets": {
3
+ "neg": [
4
+ "[M-H]-"
5
+ ],
6
+ "pos": [
7
+ "[M+H]+"
8
+ ]
9
+ },
10
+ "compound_identity": "RDKit canonical isomeric SMILES",
11
+ "csv": "<original data-preparation workspace>/datasets/MSnLib/MSnLib.csv",
12
+ "csv_sha256": "be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07",
13
+ "h5": {
14
+ "bytes": 110091598,
15
+ "path": "train/output/comparison/fig3_simple_baselines_20260821/fig3h_manifest_strict_adduct_v4/msnlib_fig3h_spectra.h5",
16
+ "sha256": "9296d42e060e7019604e16b20ba80ae13128e03b3e8ee912ee2efeb60bafdf59"
17
+ },
18
+ "mode_labels": {
19
+ "neg": "[M-H]-",
20
+ "pos": "[M+H]+"
21
+ },
22
+ "modes": {
23
+ "neg": {
24
+ "artifacts": {
25
+ "adducts_neg.json": {
26
+ "sha256": "6d2086ae948fe762ee80695f8f04505516b1259bd9c5ce3719ff47fa951622b5"
27
+ },
28
+ "protocol_neg.npz": {
29
+ "sha256": "7183fca678aa0f97dffdc6f4d4719ac993ca97592e0a468680893d0c0f3741db"
30
+ },
31
+ "smiles_neg.json": {
32
+ "sha256": "15a4ed45dd55ef27d05ad7a0a14ffcaa9a86e62f5f2120a18c358f748a98b989"
33
+ }
34
+ },
35
+ "invalid_rows": 4054,
36
+ "query_seed": 119,
37
+ "raw_adduct_rows": 144247,
38
+ "singleton_compounds_retained": 202,
39
+ "split_compound_counts": {
40
+ "test": 3193,
41
+ "train": 14907,
42
+ "val": 3193
43
+ },
44
+ "split_seed": 43,
45
+ "test": {
46
+ "library_source_row_sha256": "99b8d480087a6e90a17cfa8d0653e785285fce1e60cfd3596b4d1cf6d5ca97a4",
47
+ "n_library": 137000,
48
+ "n_queries_with_library_positive": 3160,
49
+ "n_query": 3193,
50
+ "ordered_library_smiles_sha256": "00dd373d9e175b070c2bd39595ee9532fdbd94f02a344897e81480e4b7784bc2",
51
+ "ordered_query_smiles_sha256": "db0aa2c39a1e5bc3c4463f97166c9d3e3ac150cba323f44bd29b636ccbd6553b",
52
+ "query_source_row_sha256": "2c9e896b1a267295882f6658ad664d6aab1648c37c7d02dfe98248fab69c42c8"
53
+ },
54
+ "train_spectra": 98401,
55
+ "valid_compounds": 21293,
56
+ "valid_preprocessed_rows_before_singleton_filter": 140193,
57
+ "validation": {
58
+ "library_scope": "train and validation compounds only; selected validation query excluded",
59
+ "n_library": 116135,
60
+ "n_query": 3193,
61
+ "ordered_library_smiles_sha256": "3fb782c8fbad923500cc392c5a080ad0718969519b5f69ae63adde0563cd955a",
62
+ "ordered_query_smiles_sha256": "3000c6a8bd24ae9dd082706d0ef3bcbd40939e1040f5ffe704a9923665f88412"
63
+ },
64
+ "vocabulary": {
65
+ "adducts": [
66
+ "[M-H]-"
67
+ ],
68
+ "n_adducts": 1,
69
+ "n_smiles": 21293
70
+ }
71
+ },
72
+ "pos": {
73
+ "artifacts": {
74
+ "adducts_pos.json": {
75
+ "sha256": "cafcaae472d3dda2337afb48801e37d9f3a318f5bcfcc9ca013f61815066ccd0"
76
+ },
77
+ "protocol_pos.npz": {
78
+ "sha256": "51a4a10ee4752b3e9bacd08084ec50a802aa4d852c5d599295fd62d99155f537"
79
+ },
80
+ "smiles_pos.json": {
81
+ "sha256": "bd4514be073297afd51ad3700661d0a15b2a223b1ebffd449a6a1f4084be6b8f"
82
+ }
83
+ },
84
+ "invalid_rows": 2073,
85
+ "query_seed": 119,
86
+ "raw_adduct_rows": 303709,
87
+ "singleton_compounds_retained": 39,
88
+ "split_compound_counts": {
89
+ "test": 6202,
90
+ "train": 28944,
91
+ "val": 6202
92
+ },
93
+ "split_seed": 42,
94
+ "test": {
95
+ "library_source_row_sha256": "044dc90f6ff8a69a847b9a289a9225a701a907be84d5a14d854e732c9423e0d0",
96
+ "n_library": 295434,
97
+ "n_queries_with_library_positive": 6201,
98
+ "n_query": 6202,
99
+ "ordered_library_smiles_sha256": "4d69c6f65f8c3ed84df54fc2aa6addd7b28fd1c28909386f4e4ced88d31aacce",
100
+ "ordered_query_smiles_sha256": "356f355727380d1df02abbb0aaa3391b180a5c7b93b2103058ba54e8dfae51f0",
101
+ "query_source_row_sha256": "6dd85e3f3ab28de89b5b3363314a7d84810cf7a53853e150e2160a712610bf9e"
102
+ },
103
+ "train_spectra": 211745,
104
+ "valid_compounds": 41348,
105
+ "valid_preprocessed_rows_before_singleton_filter": 301636,
106
+ "validation": {
107
+ "library_scope": "train and validation compounds only; selected validation query excluded",
108
+ "n_library": 250424,
109
+ "n_query": 6202,
110
+ "ordered_library_smiles_sha256": "fd4c3083f8930973ca7f1439284b5cec5dff35f4167f1d9da386ca26599b5500",
111
+ "ordered_query_smiles_sha256": "39ead3a4ce7f7bed717167cea96f5c929abacae13787db8dd018eb775cd74339"
112
+ },
113
+ "vocabulary": {
114
+ "adducts": [
115
+ "[M+H]+"
116
+ ],
117
+ "n_adducts": 1,
118
+ "n_smiles": 41348
119
+ }
120
+ }
121
+ },
122
+ "query_seed": 119,
123
+ "runtime_seconds": 144.18453192710876,
124
+ "split_seed": 42,
125
+ "status": "complete"
126
+ }
protocol/protocol_neg.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7183fca678aa0f97dffdc6f4d4719ac993ca97592e0a468680893d0c0f3741db
3
+ size 582720
protocol/protocol_pos.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:51a4a10ee4752b3e9bacd08084ec50a802aa4d852c5d599295fd62d99155f537
3
+ size 1252149
protocol/smiles_neg.json ADDED
The diff for this file is too large to render. See raw diff
 
protocol/smiles_pos.json ADDED
The diff for this file is too large to render. See raw diff
 
queries/neg_test_queries.csv ADDED
The diff for this file is too large to render. See raw diff
 
queries/neg_test_queries.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:95fb67a3e43dcee01e1356fa6cfc8f6ed1f14bacc9c07a0ffdf4bba4de6fad24
3
+ size 126602
queries/neg_val_queries.csv ADDED
The diff for this file is too large to render. See raw diff
 
queries/neg_val_queries.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9a728d2cc2d2ea1ebfa2789bcdb9368e3e752e6121aefeda4aa88d0e5dbfca28
3
+ size 125864
queries/pos_test_queries.csv ADDED
The diff for this file is too large to render. See raw diff
 
queries/pos_test_queries.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:839bcfaaed05f8a38638385c01df776626156d43127f40a61ccdfe7c197c9fc9
3
+ size 238703
queries/pos_val_queries.csv ADDED
The diff for this file is too large to render. See raw diff
 
queries/pos_val_queries.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6b49651ae096ebb313568c9b48789f61f63192eaaf73f1a611c6fb8716bb8268
3
+ size 238016
rebuild/LICENSE-APACHE-2.0.txt ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
rebuild/README.md ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Rebuilding the frozen artifacts, and verifying this package
2
+
3
+ This directory contains the split-B producer and the package verifier. The split-A replay
4
+ script is shipped next to the split-A tables:
5
+ [`../split_A_full_msnlib/build_split_a.py`](../split_A_full_msnlib/build_split_a.py).
6
+
7
+ ## `verify_release.py` — no external data needed
8
+
9
+ ```bash
10
+ python3 rebuild/verify_release.py
11
+ ```
12
+
13
+ Runs a self-consistency check over the files shipped here (Python ≥ 3.10 + NumPy, no
14
+ network, no MSnLib download):
15
+
16
+ * split B: counts against `protocol/manifest_summary.json`, ordered SMILES and source-row
17
+ hashes recomputed from the CSV tables, compound-level disjointness, query↔library row
18
+ disjointness, the test partition, per-query library positives, the table ↔
19
+ `protocol_*.npz` row-id mapping, the frozen column schemas;
20
+ * split A: formula-level uniqueness, the 21,107 / 16,885 / 2,110 / 2,112 and
21
+ 446,667 / 55,980 / 57,437 counts, `row_formula_fold` ↔ `formula_split` agreement, the
22
+ test/validation row-index sequences, and both voting tables reproduced from
23
+ `test_spectra.csv`;
24
+ * cross-split A × B: compound-level, spectra-level and row-level cross-tabulations, the
25
+ split-A test-fold overlap, and the single-formula-per-split-B-compound property;
26
+ * release integrity: every `.csv`/`.csv.gz` twin, `stats.json` file sizes and hashes,
27
+ `SHA256SUMS`, and the absence of retired legacy naming, internal absolute paths and
28
+ private keys in the shipped text files.
29
+
30
+ It exits non-zero on any failure. The transcript is in `../VERIFY.md`.
31
+
32
+ ## `build_library_manifest.py` — full replay of split B from MSnLib.csv
33
+
34
+ These two scripts are byte-identical copies of the producer used by the UltraMS public
35
+ release (`benchmarks/molecular_identification/source_code/original/build_library_manifest.py`
36
+ and `baseline_common.py`; Apache-2.0, see `LICENSE-APACHE-2.0.txt`):
37
+
38
+ | file | SHA-256 |
39
+ | --- | --- |
40
+ | `build_library_manifest.py` | `969760ce3a1a1f85e7bcd3e2b9c9c042675624e6df6940ee6a79a124877930e3` |
41
+ | `baseline_common.py` | `72969bc51f39dc8ae044ebaf47cdd3546f90b32edfc2b467c356b10ff0232000` |
42
+
43
+ Requirements: `numpy`, `h5py`, `rdkit`. The script writes a ~110 MB HDF5 cache of the
44
+ preprocessed spectra plus the protocol artifacts.
45
+
46
+ ```bash
47
+ # 1) obtain MSnLib.csv (see ../README.md §8); verify its SHA-256:
48
+ # be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07
49
+
50
+ # 2) replay
51
+ python build_library_manifest.py \
52
+ --csv /path/to/workspace/datasets/MSnLib/MSnLib.csv \
53
+ --skip-reference-regression \
54
+ --output-dir /path/to/workspace/manifest_replay \
55
+ --split-seed 42 --query-seed 119
56
+
57
+ # 3) compare with the frozen copies shipped here
58
+ cd /path/to/workspace/manifest_replay
59
+ sha256sum protocol_pos.npz protocol_neg.npz smiles_pos.json smiles_neg.json \
60
+ adducts_pos.json adducts_neg.json
61
+ ```
62
+
63
+ Expected artifact hashes (from `protocol/manifest_summary.json`):
64
+
65
+ | artifact | SHA-256 |
66
+ | --- | --- |
67
+ | `protocol_pos.npz` | `51a4a10ee4752b3e9bacd08084ec50a802aa4d852c5d599295fd62d99155f537` |
68
+ | `protocol_neg.npz` | `7183fca678aa0f97dffdc6f4d4719ac993ca97592e0a468680893d0c0f3741db` |
69
+ | `smiles_pos.json` | `bd4514be073297afd51ad3700661d0a15b2a223b1ebffd449a6a1f4084be6b8f` |
70
+ | `smiles_neg.json` | `15a4ed45dd55ef27d05ad7a0a14ffcaa9a86e62f5f2120a18c358f748a98b989` |
71
+ | `adducts_pos.json` | `cafcaae472d3dda2337afb48801e37d9f3a318f5bcfcc9ca013f61815066ccd0` |
72
+ | `adducts_neg.json` | `6d2086ae948fe762ee80695f8f04505516b1259bd9c5ce3719ff47fa951622b5` |
73
+
74
+ Notes:
75
+
76
+ * The negative task uses `--split-seed 42 + 1 = 43` internally; this is not a CLI flag.
77
+ * `--skip-reference-regression` skips the comparison against the historical embedding
78
+ SMILES files (they are not in this package). Without the flag you must also pass
79
+ `--reference-embedding-dir`.
80
+ * The regenerated `manifest_summary.json` records the absolute paths of *your* machine and
81
+ therefore differs textually from the shipped copy (which has one path field redacted).
82
+ Compare the `modes` subtree and the artifact hashes, not the whole file.
83
+ * The regenerated HDF5 file must have SHA-256
84
+ `9296d42e060e7019604e16b20ba80ae13128e03b3e8ee912ee2efeb60bafdf59` when built with the
85
+ same `MSnLib.csv`, RDKit runtime and h5py compression defaults.
86
+
87
+ ## Rebuilding split A
88
+
89
+ ```bash
90
+ python3 split_A_full_msnlib/build_split_a.py --csv /path/to/MSnLib.csv
91
+ python3 split_A_full_msnlib/build_split_a.py --csv /path/to/MSnLib.csv --output-dir replay_split_a
92
+ ```
93
+
94
+ The first form is a read-only replay and hash check, the second writes the six split-A
95
+ tables. RDKit 2026.03.5 is required for byte-identical canonical SMILES strings.
96
+
97
+ ## Chaining the split-B replay back to the CSV tables
98
+
99
+ `build_library_manifest.py` only writes row indices. To regenerate the split-B tables in
100
+ `splits/`, `queries/` and `libraries/`, join `protocol/*.npz` through
101
+ `derived/row_metadata_*.npz` (`source_row` → `MSnLib.csv` row) and `smiles_*.json`
102
+ (`smiles_index` → compound); `verify_release.py` documents the join it checks, and the
103
+ schema is described in `../README.md` §5.2 and `../protocol/README.md`.
rebuild/baseline_common.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Shared, audit-oriented utilities for the Figure 3 simple baselines."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import csv
7
+ import hashlib
8
+ import json
9
+ import math
10
+ import os
11
+ import random
12
+ import tempfile
13
+ from collections import Counter, defaultdict
14
+ from pathlib import Path
15
+ from typing import Iterable, Sequence
16
+
17
+ import numpy as np
18
+
19
+
20
+ POSITIVE_ADDUCTS = frozenset(
21
+ {"[M+H]+", "[M+Na]+", "[M+NH4]+", "[M+K]+", "[M+H-H2O]+"}
22
+ )
23
+ NEGATIVE_ADDUCTS = frozenset(
24
+ {"[M-H]-", "[M+Cl]-", "[M+FA]-", "[M+FA-H]-", "[M+CH3COO]-"}
25
+ )
26
+ FOLD_TO_CODE = {"train": 0, "val": 1, "test": 2}
27
+ CODE_TO_FOLD = {v: k for k, v in FOLD_TO_CODE.items()}
28
+
29
+
30
+ def sha256_file(path: str | os.PathLike[str], block_size: int = 16 << 20) -> str:
31
+ digest = hashlib.sha256()
32
+ with open(path, "rb") as handle:
33
+ while True:
34
+ block = handle.read(block_size)
35
+ if not block:
36
+ break
37
+ digest.update(block)
38
+ return digest.hexdigest()
39
+
40
+
41
+ def sha256_lines(values: Iterable[str]) -> str:
42
+ digest = hashlib.sha256()
43
+ first = True
44
+ for value in values:
45
+ if not first:
46
+ digest.update(b"\n")
47
+ digest.update(str(value).encode("utf-8"))
48
+ first = False
49
+ return digest.hexdigest()
50
+
51
+
52
+ def stable_uint32(text: str, base_seed: int = 0) -> int:
53
+ payload = f"{base_seed}\0{text}".encode("utf-8")
54
+ return int.from_bytes(hashlib.sha256(payload).digest()[:4], "big")
55
+
56
+
57
+ def atomic_write_json(path: str | os.PathLike[str], payload: object) -> None:
58
+ path = Path(path)
59
+ path.parent.mkdir(parents=True, exist_ok=True)
60
+ with tempfile.NamedTemporaryFile("w", dir=path.parent, delete=False) as handle:
61
+ json.dump(payload, handle, indent=2, sort_keys=True)
62
+ handle.write("\n")
63
+ temporary = Path(handle.name)
64
+ os.replace(temporary, path)
65
+
66
+
67
+ def parse_peak_strings(mzs_text: object, intensities_text: object) -> tuple[np.ndarray, np.ndarray]:
68
+ mzs = np.fromstring(str(mzs_text), dtype=np.float32, sep=",")
69
+ intensities = np.fromstring(str(intensities_text), dtype=np.float32, sep=",")
70
+ n = min(mzs.size, intensities.size)
71
+ if n == 0:
72
+ return np.empty(0, np.float32), np.empty(0, np.float32)
73
+ mzs = mzs[:n]
74
+ intensities = intensities[:n]
75
+ valid = np.isfinite(mzs) & np.isfinite(intensities) & (mzs > 0) & (intensities >= 0)
76
+ return mzs[valid], intensities[valid]
77
+
78
+
79
+ def fingerprint_ffn_bins(
80
+ mzs: np.ndarray,
81
+ intensities: np.ndarray,
82
+ *,
83
+ max_mz: int = 1005,
84
+ bin_width: float = 1.0,
85
+ ) -> np.ndarray:
86
+ """MassSpecGym-style sum binning followed by maximum normalization."""
87
+ n_bins = int(math.ceil(max_mz / bin_width))
88
+ out = np.zeros(n_bins, dtype=np.float32)
89
+ if mzs.size == 0:
90
+ return out
91
+ idx = np.floor(mzs / bin_width).astype(np.int64)
92
+ keep = (idx >= 0) & (idx < n_bins) & (intensities > 0)
93
+ if keep.any():
94
+ np.add.at(out, idx[keep], intensities[keep])
95
+ maximum = float(out.max())
96
+ if maximum > 0:
97
+ out /= maximum
98
+ return out
99
+
100
+
101
+ def raw_binned_sparse_row(
102
+ mzs: np.ndarray,
103
+ intensities: np.ndarray,
104
+ *,
105
+ max_peaks: int = 150,
106
+ bin_width: float = 0.02,
107
+ max_mz: float | None = None,
108
+ ) -> tuple[np.ndarray, np.ndarray]:
109
+ """Return sorted sparse indices/values for the frozen raw-cosine protocol."""
110
+ if mzs.size < 3 or intensities.size < 3:
111
+ return np.empty(0, np.int32), np.empty(0, np.float32)
112
+ maximum = float(intensities.max(initial=0.0))
113
+ if maximum <= 0:
114
+ return np.empty(0, np.int32), np.empty(0, np.float32)
115
+ scaled = np.clip(intensities / maximum, 0.0, 1.0)
116
+ if mzs.size > max_peaks:
117
+ chosen = np.argpartition(scaled, -max_peaks)[-max_peaks:]
118
+ mzs = mzs[chosen]
119
+ scaled = scaled[chosen]
120
+ idx = np.rint(mzs / bin_width).astype(np.int64)
121
+ keep = (idx >= 0) & (scaled > 0)
122
+ if max_mz is not None:
123
+ keep &= idx < int(math.ceil(max_mz / bin_width))
124
+ idx = idx[keep]
125
+ vals = np.sqrt(scaled[keep], dtype=np.float32)
126
+ if idx.size == 0:
127
+ return np.empty(0, np.int32), np.empty(0, np.float32)
128
+ order = np.argsort(idx, kind="stable")
129
+ idx, vals = idx[order], vals[order]
130
+ unique_idx, first = np.unique(idx, return_index=True)
131
+ summed = np.add.reduceat(vals, first).astype(np.float32, copy=False)
132
+ norm = float(np.linalg.norm(summed))
133
+ if norm > 0:
134
+ summed /= norm
135
+ return unique_idx.astype(np.int32, copy=False), summed
136
+
137
+
138
+ def exact_tie_aware_fdr_curve(
139
+ top1_score: Sequence[float],
140
+ top1_correct: Sequence[bool],
141
+ *,
142
+ denominator: int,
143
+ min_hits: int = 10,
144
+ ) -> dict[str, np.ndarray]:
145
+ """Accept equal-score observations as one block and sweep every observed score."""
146
+ scores = np.asarray(top1_score, dtype=np.float64)
147
+ correct = np.asarray(top1_correct, dtype=bool)
148
+ if scores.ndim != 1 or scores.shape != correct.shape:
149
+ raise ValueError("score/correct arrays must be aligned one-dimensional arrays")
150
+ if denominator <= 0:
151
+ raise ValueError("recall denominator must be positive")
152
+ finite = np.isfinite(scores)
153
+ scores, correct = scores[finite], correct[finite]
154
+ order = np.argsort(-scores, kind="stable")
155
+ scores, correct = scores[order], correct[order]
156
+ if scores.size == 0:
157
+ empty = np.empty(0, dtype=np.float64)
158
+ return {"threshold": empty, "accepted": empty.astype(np.int64), "correct": empty.astype(np.int64), "fdr": empty, "recall": empty}
159
+ block_end = np.r_[scores[1:] != scores[:-1], True]
160
+ accepted_all = np.arange(1, scores.size + 1, dtype=np.int64)
161
+ correct_all = np.cumsum(correct, dtype=np.int64)
162
+ accepted = accepted_all[block_end]
163
+ n_correct = correct_all[block_end]
164
+ thresholds = scores[block_end]
165
+ fdr = np.full(accepted.shape, np.nan, dtype=np.float64)
166
+ eligible = accepted >= int(min_hits)
167
+ fdr[eligible] = (accepted[eligible] - n_correct[eligible]) / accepted[eligible]
168
+ recall = n_correct.astype(np.float64) / float(denominator)
169
+ return {
170
+ "threshold": thresholds,
171
+ "accepted": accepted,
172
+ "correct": n_correct,
173
+ "fdr": fdr,
174
+ "recall": recall,
175
+ }
176
+
177
+
178
+ def fdr_envelope(curve: dict[str, np.ndarray], *, maximum: float = 0.35, n_grid: int = 500) -> dict[str, np.ndarray]:
179
+ fdr = np.asarray(curve["fdr"], dtype=np.float64)
180
+ recall = np.asarray(curve["recall"], dtype=np.float64)
181
+ valid = np.isfinite(fdr)
182
+ grid = np.linspace(0.0, maximum, n_grid)
183
+ envelope = np.zeros_like(grid)
184
+ for idx, budget in enumerate(grid):
185
+ eligible = valid & (fdr <= budget)
186
+ if eligible.any():
187
+ envelope[idx] = recall[eligible].max()
188
+ return {"fdr_grid": grid, "recall_envelope": envelope}
189
+
190
+
191
+ def fdr_working_point(curve: dict[str, np.ndarray], target: float = 0.05) -> dict[str, float | int | None]:
192
+ fdr = np.asarray(curve["fdr"], dtype=np.float64)
193
+ recall = np.asarray(curve["recall"], dtype=np.float64)
194
+ valid = np.isfinite(fdr) & (fdr <= target)
195
+ if not valid.any():
196
+ return {"threshold": None, "fdr": None, "recall": 0.0, "accepted": 0, "correct": 0}
197
+ candidates = np.where(valid)[0]
198
+ # Highest recall, then lower FDR, then stricter threshold.
199
+ best = sorted(candidates, key=lambda i: (-recall[i], fdr[i], -curve["threshold"][i]))[0]
200
+ return {
201
+ "threshold": float(curve["threshold"][best]),
202
+ "fdr": float(fdr[best]),
203
+ "recall": float(recall[best]),
204
+ "accepted": int(curve["accepted"][best]),
205
+ "correct": int(curve["correct"][best]),
206
+ }
207
+
208
+
209
+ def threshold_metrics(
210
+ top1_score: Sequence[float],
211
+ top1_correct: Sequence[bool],
212
+ threshold: float,
213
+ *,
214
+ denominator: int,
215
+ ) -> dict[str, float | int]:
216
+ score = np.asarray(top1_score, dtype=np.float64)
217
+ correct = np.asarray(top1_correct, dtype=bool)
218
+ accepted = np.isfinite(score) & (score >= float(threshold))
219
+ n_accepted = int(accepted.sum())
220
+ n_correct = int((accepted & correct).sum())
221
+ return {
222
+ "threshold": float(threshold),
223
+ "accepted": n_accepted,
224
+ "correct": n_correct,
225
+ "coverage": n_accepted / len(score) if len(score) else 0.0,
226
+ "fdr": (n_accepted - n_correct) / n_accepted if n_accepted else float("nan"),
227
+ "recall": n_correct / denominator if denominator else 0.0,
228
+ }
229
+
230
+
231
+ def rank_metrics(ranks: Sequence[int], ks: Sequence[int] = (1, 5, 10, 20)) -> dict[str, float | int]:
232
+ values = np.asarray(ranks, dtype=np.int64)
233
+ if values.ndim != 1 or values.size == 0 or (values < 1).any():
234
+ raise ValueError("ranks must be a nonempty vector of positive integers")
235
+ result: dict[str, float | int] = {"n_queries": int(values.size)}
236
+ for k in ks:
237
+ result[f"top{k}"] = float(np.mean(values <= k))
238
+ result["mrr"] = float(np.mean(1.0 / values))
239
+ result["median_rank"] = float(np.median(values))
240
+ return result
241
+
242
+
243
+ def candidate_consensus(
244
+ top_candidates: Sequence[Sequence[str]],
245
+ top_scores: Sequence[Sequence[float]],
246
+ *,
247
+ depth: int = 50,
248
+ ) -> list[str]:
249
+ """Frozen hard-plurality ranking with normalized-Borda tie support."""
250
+ votes: Counter[str] = Counter()
251
+ support: defaultdict[str, float] = defaultdict(float)
252
+ for candidates, _scores in zip(top_candidates, top_scores):
253
+ row = list(candidates[:depth])
254
+ if row:
255
+ votes[row[0]] += 1
256
+ denom = max(1, len(row))
257
+ for rank0, candidate in enumerate(row):
258
+ support[candidate] += (denom - rank0) / denom
259
+ return sorted(support, key=lambda c: (-votes[c], -support[c], c))
260
+
261
+
262
+ def bootstrap_cluster_delta(
263
+ baseline: Sequence[float],
264
+ comparator: Sequence[float],
265
+ cluster_ids: Sequence[str],
266
+ *,
267
+ n_bootstrap: int = 10_000,
268
+ seed: int = 20260821,
269
+ ) -> dict[str, object]:
270
+ """Paired cluster bootstrap of the mean comparator-minus-baseline difference."""
271
+ a = np.asarray(baseline, dtype=np.float64)
272
+ b = np.asarray(comparator, dtype=np.float64)
273
+ clusters = np.asarray(cluster_ids, dtype=object)
274
+ if a.shape != b.shape or a.shape != clusters.shape:
275
+ raise ValueError("paired arrays and cluster ids must align")
276
+ unique, inverse = np.unique(clusters, return_inverse=True)
277
+ cluster_sum = np.bincount(inverse, weights=b - a)
278
+ cluster_n = np.bincount(inverse)
279
+ rng = np.random.default_rng(seed)
280
+ draws = np.empty(n_bootstrap, dtype=np.float64)
281
+ for idx in range(n_bootstrap):
282
+ sampled = rng.integers(0, len(unique), size=len(unique))
283
+ draws[idx] = cluster_sum[sampled].sum() / cluster_n[sampled].sum()
284
+ return {
285
+ "estimate": float(np.mean(b - a)),
286
+ "ci_low": float(np.quantile(draws, 0.025)),
287
+ "ci_high": float(np.quantile(draws, 0.975)),
288
+ "n_clusters": int(len(unique)),
289
+ "n_observations": int(len(a)),
290
+ "n_bootstrap": int(n_bootstrap),
291
+ "seed": int(seed),
292
+ "draws": draws,
293
+ }
294
+
295
+
296
+ def read_csv_rows(path: str | os.PathLike[str]) -> Iterable[dict[str, str]]:
297
+ with open(path, newline="") as handle:
298
+ yield from csv.DictReader(handle)
299
+
300
+
301
+ def split_compounds(smiles: Sequence[str], *, seed: int = 42, val_ratio: float = 0.15, test_ratio: float = 0.15) -> dict[str, list[str]]:
302
+ ordered = sorted(smiles)
303
+ rng = random.Random(seed)
304
+ rng.shuffle(ordered)
305
+ n_test = int(len(ordered) * test_ratio)
306
+ n_val = int(len(ordered) * val_ratio)
307
+ return {
308
+ "test": ordered[:n_test],
309
+ "val": ordered[n_test : n_test + n_val],
310
+ "train": ordered[n_test + n_val :],
311
+ }
312
+
313
+
314
+ def choose_query_row_ids(
315
+ row_ids_by_smiles: dict[str, list[int]],
316
+ compounds: Sequence[str],
317
+ *,
318
+ seed: int = 119,
319
+ ) -> tuple[list[int], list[str]]:
320
+ rng = random.Random(seed)
321
+ rows: list[int] = []
322
+ smiles: list[str] = []
323
+ for smi in sorted(compounds):
324
+ rows.append(rng.choice(row_ids_by_smiles[smi]))
325
+ smiles.append(smi)
326
+ return rows, smiles
327
+
328
+
329
+ def build_library_row_ids(
330
+ row_ids_by_smiles: dict[str, list[int]],
331
+ excluded_query_rows: Sequence[int],
332
+ *,
333
+ allowed_compounds: set[str] | None = None,
334
+ ) -> tuple[list[int], list[str]]:
335
+ excluded = set(int(x) for x in excluded_query_rows)
336
+ rows: list[int] = []
337
+ smiles: list[str] = []
338
+ for smi in sorted(row_ids_by_smiles):
339
+ if allowed_compounds is not None and smi not in allowed_compounds:
340
+ continue
341
+ for row_id in row_ids_by_smiles[smi]:
342
+ if row_id not in excluded:
343
+ rows.append(row_id)
344
+ smiles.append(smi)
345
+ return rows, smiles
rebuild/build_library_manifest.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Replay and freeze the exact Figure 3h query/library construction with source rows."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import random
9
+ import time
10
+ from collections import defaultdict
11
+ from pathlib import Path
12
+
13
+ import h5py
14
+ import numpy as np
15
+ from rdkit import Chem
16
+
17
+ from baseline_common import (
18
+ atomic_write_json,
19
+ read_csv_rows,
20
+ sha256_file,
21
+ sha256_lines,
22
+ split_compounds,
23
+ )
24
+
25
+
26
+ MODE_ADDUCT = {"pos": "[M+H]+", "neg": "[M-H]-"}
27
+
28
+
29
+ def producer_preprocess(mzs_text: object, intensities_text: object, max_peaks: int = 150):
30
+ mz = np.fromstring(str(mzs_text), dtype=np.float32, sep=",")
31
+ intensity = np.fromstring(str(intensities_text), dtype=np.float32, sep=",")
32
+ n = min(len(mz), len(intensity))
33
+ mz, intensity = mz[:n], intensity[:n]
34
+ valid = mz > 0
35
+ mz, intensity = mz[valid], intensity[valid]
36
+ if len(mz) < 3:
37
+ return None
38
+ maximum = float(intensity.max())
39
+ if maximum <= 0:
40
+ return None
41
+ intensity = np.clip(intensity / maximum, 0, 1)
42
+ if len(mz) > max_peaks:
43
+ chosen = np.sort(np.argsort(intensity)[-max_peaks:])
44
+ mz, intensity = mz[chosen], intensity[chosen]
45
+ order = np.argsort(mz)
46
+ return np.stack([mz[order], intensity[order]], axis=-1).astype(np.float32)
47
+
48
+
49
+ class ModeWriter:
50
+ def __init__(self, group: h5py.Group, mode: str, buffer_size: int = 5000) -> None:
51
+ self.mode = mode
52
+ self.buffer_size = buffer_size
53
+ self.spectra = group.create_dataset(
54
+ "spectra",
55
+ shape=(0, 150, 2),
56
+ maxshape=(None, 150, 2),
57
+ dtype="f4",
58
+ chunks=(256, 150, 2),
59
+ compression="lzf",
60
+ )
61
+ self.n_peaks = group.create_dataset(
62
+ "n_peaks", shape=(0,), maxshape=(None,), dtype="u2", chunks=True, compression="lzf"
63
+ )
64
+ self.source_row = group.create_dataset(
65
+ "source_row", shape=(0,), maxshape=(None,), dtype="i8", chunks=True, compression="lzf"
66
+ )
67
+ self.precursor_mz = group.create_dataset(
68
+ "precursor_mz", shape=(0,), maxshape=(None,), dtype="f4", chunks=True, compression="lzf"
69
+ )
70
+ self.smiles_index = group.create_dataset(
71
+ "smiles_index", shape=(0,), maxshape=(None,), dtype="i4", chunks=True, compression="lzf"
72
+ )
73
+ self.adduct_index = group.create_dataset(
74
+ "adduct_index", shape=(0,), maxshape=(None,), dtype="i2", chunks=True, compression="lzf"
75
+ )
76
+ self.smiles: list[str] = []
77
+ self.smiles_to_idx: dict[str, int] = {}
78
+ self.adducts: list[str] = []
79
+ self.adduct_to_idx: dict[str, int] = {}
80
+ self.row_ids_by_smiles: defaultdict[str, list[int]] = defaultdict(list)
81
+ self.buffer: list[tuple[np.ndarray, int, int, float, int, int]] = []
82
+ self.count = 0
83
+
84
+ def append(self, spectrum: np.ndarray, source_row: int, precursor_mz: float, smiles: str, adduct: str) -> None:
85
+ if smiles not in self.smiles_to_idx:
86
+ self.smiles_to_idx[smiles] = len(self.smiles)
87
+ self.smiles.append(smiles)
88
+ if adduct not in self.adduct_to_idx:
89
+ self.adduct_to_idx[adduct] = len(self.adducts)
90
+ self.adducts.append(adduct)
91
+ local_row = self.count + len(self.buffer)
92
+ self.row_ids_by_smiles[smiles].append(local_row)
93
+ padded = np.zeros((150, 2), dtype=np.float32)
94
+ padded[: len(spectrum)] = spectrum
95
+ self.buffer.append(
96
+ (
97
+ padded,
98
+ len(spectrum),
99
+ source_row,
100
+ precursor_mz,
101
+ self.smiles_to_idx[smiles],
102
+ self.adduct_to_idx[adduct],
103
+ )
104
+ )
105
+ if len(self.buffer) >= self.buffer_size:
106
+ self.flush()
107
+
108
+ def flush(self) -> None:
109
+ if not self.buffer:
110
+ return
111
+ start, end = self.count, self.count + len(self.buffer)
112
+ for dataset in (
113
+ self.spectra,
114
+ self.n_peaks,
115
+ self.source_row,
116
+ self.precursor_mz,
117
+ self.smiles_index,
118
+ self.adduct_index,
119
+ ):
120
+ dataset.resize((end,) + dataset.shape[1:])
121
+ self.spectra[start:end] = np.stack([row[0] for row in self.buffer])
122
+ self.n_peaks[start:end] = [row[1] for row in self.buffer]
123
+ self.source_row[start:end] = [row[2] for row in self.buffer]
124
+ self.precursor_mz[start:end] = [row[3] for row in self.buffer]
125
+ self.smiles_index[start:end] = [row[4] for row in self.buffer]
126
+ self.adduct_index[start:end] = [row[5] for row in self.buffer]
127
+ self.count = end
128
+ self.buffer.clear()
129
+
130
+
131
+ def choose_queries(row_ids_by_smiles: dict[str, list[int]], compounds: list[str], seed: int) -> tuple[list[int], list[str]]:
132
+ rng = random.Random(seed)
133
+ rows, smiles = [], []
134
+ for smi in sorted(compounds):
135
+ rows.append(rng.choice(row_ids_by_smiles[smi]))
136
+ smiles.append(smi)
137
+ return rows, smiles
138
+
139
+
140
+ def build_library(
141
+ row_ids_by_smiles: dict[str, list[int]],
142
+ excluded: list[int],
143
+ allowed: set[str] | None = None,
144
+ ) -> tuple[list[int], list[str]]:
145
+ excluded_set = set(excluded)
146
+ rows, smiles = [], []
147
+ # Historical producer retained canonical-compound insertion order from the
148
+ # source CSV. This order is part of the frozen embedding/library identity.
149
+ for smi in row_ids_by_smiles:
150
+ if allowed is not None and smi not in allowed:
151
+ continue
152
+ for row_id in row_ids_by_smiles[smi]:
153
+ if row_id not in excluded_set:
154
+ rows.append(row_id)
155
+ smiles.append(smi)
156
+ return rows, smiles
157
+
158
+
159
+ def build(args: argparse.Namespace) -> None:
160
+ out = Path(args.output_dir)
161
+ out.mkdir(parents=True, exist_ok=True)
162
+ h5_path = out / "msnlib_fig3h_spectra.h5"
163
+ if h5_path.exists() and not args.force:
164
+ raise FileExistsError(f"refusing to overwrite {h5_path}; use --force only for a fresh versioned run")
165
+ if h5_path.exists():
166
+ h5_path.unlink()
167
+ started = time.time()
168
+ raw_counts = {"pos": 0, "neg": 0}
169
+ invalid_counts = {"pos": 0, "neg": 0}
170
+ # The frozen Figure 3h producer used the two strict adduct subsets below.
171
+ # A newer fine-tuning script in the snapshot broadened these to composite
172
+ # ion-mode sets, but those sets do not reproduce the frozen embeddings.
173
+ mode_sets = {mode: {adduct} for mode, adduct in MODE_ADDUCT.items()}
174
+ with h5py.File(h5_path, "w") as h5:
175
+ writers = {mode: ModeWriter(h5.create_group(mode), mode) for mode in ("pos", "neg")}
176
+ for source_row, row in enumerate(read_csv_rows(args.csv)):
177
+ adduct = str(row.get("adduct", ""))
178
+ mode = "pos" if adduct == MODE_ADDUCT["pos"] else "neg" if adduct == MODE_ADDUCT["neg"] else None
179
+ if mode is None:
180
+ continue
181
+ raw_counts[mode] += 1
182
+ spectrum = producer_preprocess(row["mzs"], row["intensities"], max_peaks=150)
183
+ raw_smiles = str(row.get("smiles", "")).strip()
184
+ molecule = None if raw_smiles in ("", "nan") else Chem.MolFromSmiles(raw_smiles)
185
+ smiles = Chem.MolToSmiles(molecule, canonical=True) if molecule is not None else ""
186
+ if spectrum is None or not smiles:
187
+ invalid_counts[mode] += 1
188
+ continue
189
+ writers[mode].append(
190
+ spectrum,
191
+ source_row,
192
+ float(row["precursor_mz"]),
193
+ smiles,
194
+ adduct,
195
+ )
196
+ total = raw_counts["pos"] + raw_counts["neg"]
197
+ if total % 50_000 == 0:
198
+ print(f"eligible_rows_seen={total:,}", flush=True)
199
+ for writer in writers.values():
200
+ writer.flush()
201
+
202
+ summary: dict[str, object] = {
203
+ "status": "complete",
204
+ "csv": str(Path(args.csv).resolve()),
205
+ "csv_sha256": sha256_file(args.csv),
206
+ "split_seed": args.split_seed,
207
+ "query_seed": args.query_seed,
208
+ "mode_labels": {"pos": "[M+H]+", "neg": "[M-H]-"},
209
+ "compound_identity": "RDKit canonical isomeric SMILES",
210
+ "adduct_sets": {mode: sorted(values) for mode, values in mode_sets.items()},
211
+ "modes": {},
212
+ }
213
+ for mode, writer in writers.items():
214
+ # The historical producer split every valid canonical compound,
215
+ # including singletons. A test singleton has no remaining library
216
+ # positive after its only spectrum becomes the query (1 positive,
217
+ # 33 negative in the frozen benchmark).
218
+ valid_rows = dict(writer.row_ids_by_smiles)
219
+ singleton_spectra = sum(len(rows) for rows in valid_rows.values() if len(rows) == 1)
220
+ mode_offset = 0 if mode == "pos" else 1
221
+ mode_split_seed = args.split_seed + mode_offset
222
+ mode_query_seed = args.query_seed
223
+ splits = split_compounds(list(valid_rows), seed=mode_split_seed)
224
+ test_query_rows, test_query_smis = choose_queries(valid_rows, splits["test"], mode_query_seed)
225
+ test_library_rows, test_library_smis = build_library(valid_rows, test_query_rows)
226
+ val_query_rows, val_query_smis = choose_queries(valid_rows, splits["val"], mode_query_seed)
227
+ val_allowed = set(splits["train"]) | set(splits["val"])
228
+ val_library_rows, val_library_smis = build_library(
229
+ valid_rows, val_query_rows, allowed=val_allowed
230
+ )
231
+ train_rows = [row for smi in sorted(splits["train"]) for row in valid_rows[smi]]
232
+
233
+ if not args.skip_reference_regression:
234
+ if not args.reference_embedding_dir:
235
+ raise ValueError("--reference-embedding-dir is required for reference regression")
236
+ reference_dir = Path(args.reference_embedding_dir)
237
+ reference_query = json.loads(
238
+ (reference_dir / f"emb_msnlib_{mode}_query_smis.json").read_text()
239
+ )
240
+ reference_library = json.loads(
241
+ (reference_dir / f"emb_msnlib_{mode}_lib_smis.json").read_text()
242
+ )
243
+ if reference_query != test_query_smis:
244
+ raise RuntimeError(f"{mode} replayed query SMILES differ from frozen reference")
245
+ if reference_library != test_library_smis:
246
+ raise RuntimeError(f"{mode} replayed library SMILES differ from frozen reference")
247
+
248
+ smiles_path = out / f"smiles_{mode}.json"
249
+ adduct_path = out / f"adducts_{mode}.json"
250
+ atomic_write_json(smiles_path, writer.smiles)
251
+ atomic_write_json(adduct_path, writer.adducts)
252
+ protocol_path = out / f"protocol_{mode}.npz"
253
+ np.savez_compressed(
254
+ protocol_path,
255
+ train_rows=np.asarray(train_rows, dtype=np.int64),
256
+ val_query_rows=np.asarray(val_query_rows, dtype=np.int64),
257
+ val_library_rows=np.asarray(val_library_rows, dtype=np.int64),
258
+ test_query_rows=np.asarray(test_query_rows, dtype=np.int64),
259
+ test_library_rows=np.asarray(test_library_rows, dtype=np.int64),
260
+ )
261
+ library_counts = defaultdict(int)
262
+ for smi in test_library_smis:
263
+ library_counts[smi] += 1
264
+ n_eligible = sum(library_counts[smi] > 0 for smi in test_query_smis)
265
+ source_rows_array = np.asarray(writer.source_row)
266
+ mode_summary = {
267
+ "raw_adduct_rows": raw_counts[mode],
268
+ "invalid_rows": invalid_counts[mode],
269
+ "valid_preprocessed_rows_before_singleton_filter": writer.count,
270
+ "singleton_compounds_retained": singleton_spectra,
271
+ "valid_compounds": len(valid_rows),
272
+ "split_seed": mode_split_seed,
273
+ "query_seed": mode_query_seed,
274
+ "split_compound_counts": {key: len(value) for key, value in splits.items()},
275
+ "train_spectra": len(train_rows),
276
+ "validation": {
277
+ "n_query": len(val_query_rows),
278
+ "n_library": len(val_library_rows),
279
+ "ordered_query_smiles_sha256": sha256_lines(val_query_smis),
280
+ "ordered_library_smiles_sha256": sha256_lines(val_library_smis),
281
+ "library_scope": "train and validation compounds only; selected validation query excluded",
282
+ },
283
+ "test": {
284
+ "n_query": len(test_query_rows),
285
+ "n_library": len(test_library_rows),
286
+ "n_queries_with_library_positive": n_eligible,
287
+ "ordered_query_smiles_sha256": sha256_lines(test_query_smis),
288
+ "ordered_library_smiles_sha256": sha256_lines(test_library_smis),
289
+ "query_source_row_sha256": sha256_lines(
290
+ map(str, source_rows_array[np.asarray(test_query_rows)].tolist())
291
+ ),
292
+ "library_source_row_sha256": sha256_lines(
293
+ map(str, source_rows_array[np.asarray(test_library_rows)].tolist())
294
+ ),
295
+ },
296
+ "vocabulary": {
297
+ "n_smiles": len(writer.smiles),
298
+ "n_adducts": len(writer.adducts),
299
+ "adducts": writer.adducts,
300
+ },
301
+ "artifacts": {
302
+ protocol_path.name: {"sha256": sha256_file(protocol_path)},
303
+ smiles_path.name: {"sha256": sha256_file(smiles_path)},
304
+ adduct_path.name: {"sha256": sha256_file(adduct_path)},
305
+ },
306
+ }
307
+ summary["modes"][mode] = mode_summary
308
+
309
+ summary["h5"] = {
310
+ "path": str(h5_path),
311
+ "sha256": sha256_file(h5_path),
312
+ "bytes": h5_path.stat().st_size,
313
+ }
314
+ summary["runtime_seconds"] = time.time() - started
315
+ atomic_write_json(out / "manifest_summary.json", summary)
316
+ print(json.dumps(summary, indent=2), flush=True)
317
+
318
+
319
+ def main() -> None:
320
+ parser = argparse.ArgumentParser()
321
+ parser.add_argument("--csv", required=True)
322
+ parser.add_argument("--reference-embedding-dir")
323
+ parser.add_argument("--output-dir", required=True)
324
+ parser.add_argument("--split-seed", type=int, default=42)
325
+ parser.add_argument("--query-seed", type=int, default=119)
326
+ parser.add_argument("--skip-reference-regression", action="store_true")
327
+ parser.add_argument("--force", action="store_true")
328
+ args = parser.parse_args()
329
+ build(args)
330
+
331
+
332
+ if __name__ == "__main__":
333
+ main()
rebuild/verify_release.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Self-contained verifier for ultrams_msnlib_benchmark_v1.
3
+
4
+ Runs only on files shipped in this package (Python 3.10+, NumPy). It re-derives every
5
+ published count, ordering hash, overlap statement and cross-split statistic from the CSV
6
+ tables and the frozen protocol arrays, checks the checksums in SHA256SUMS, and exits
7
+ non-zero if anything disagrees.
8
+
9
+ python3 rebuild/verify_release.py
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import csv
14
+ import gzip
15
+ import hashlib
16
+ import json
17
+ import sys
18
+ from collections import Counter, defaultdict
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+
23
+ PKG = Path(__file__).resolve().parent.parent
24
+ MODES = ("pos", "neg")
25
+ A_DIR = PKG / "split_A_full_msnlib"
26
+ CHECKS: list[tuple[str, bool, str]] = []
27
+
28
+ # Built as concatenations so that this verifier itself does not contain the strings it
29
+ # forbids anywhere in the release.
30
+ FORBIDDEN_NAMES = ("spec" + "bridge",)
31
+ FORBIDDEN_PATH_TOKENS = (
32
+ "/hpc" + "2hdd/",
33
+ "/gem" + "ini/",
34
+ "/Us" + "ers/" + "yifanliscn",
35
+ "BEGIN RSA " + "PRIVATE KEY",
36
+ "BEGIN OPENSSH " + "PRIVATE KEY",
37
+ "yli" + "994",
38
+ "aims" + "lab",
39
+ )
40
+
41
+ A_EXPECTED = {
42
+ "n_formula": 21107,
43
+ "n_formula_train": 16885,
44
+ "n_formula_val": 2110,
45
+ "n_formula_test": 2112,
46
+ "n_spectra_train": 446667,
47
+ "n_spectra_val": 55980,
48
+ "n_spectra_test": 57437,
49
+ "n_spectra_total": 560084,
50
+ "n_test_spectra": 57437,
51
+ "n_val_spectra": 55980,
52
+ "n_voting_official": 5002,
53
+ "n_voting_official_spectra": 57436,
54
+ "n_voting_canonical": 4888,
55
+ "n_voting_canonical_spectra": 57436,
56
+ }
57
+
58
+
59
+ def check(name: str, ok: bool, detail: str = "") -> None:
60
+ CHECKS.append((name, bool(ok), detail))
61
+ print(f"[{'PASS' if ok else 'FAIL'}] {name}" + (f" :: {detail}" if detail else ""))
62
+
63
+
64
+ def sha256_lines(values) -> str:
65
+ digest = hashlib.sha256()
66
+ first = True
67
+ for value in values:
68
+ if not first:
69
+ digest.update(b"\n")
70
+ digest.update(str(value).encode("utf-8"))
71
+ first = False
72
+ return digest.hexdigest()
73
+
74
+
75
+ def sha256_file(path: Path) -> str:
76
+ digest = hashlib.sha256()
77
+ with path.open("rb") as fh:
78
+ while block := fh.read(8 << 20):
79
+ digest.update(block)
80
+ return digest.hexdigest()
81
+
82
+
83
+ def read_csv(path: Path) -> list[dict[str, str]]:
84
+ with open(path, newline="", encoding="utf-8") as fh:
85
+ return list(csv.DictReader(fh))
86
+
87
+
88
+ def main() -> int:
89
+ manifest = json.loads((PKG / "protocol/manifest_summary.json").read_text())
90
+ stats = json.loads((PKG / "stats.json").read_text())
91
+
92
+ # every shipped .csv must be byte-identical to its .csv.gz twin
93
+ mismatched = []
94
+ for plain in sorted(PKG.rglob("*.csv")):
95
+ gz = plain.with_suffix(plain.suffix + ".gz")
96
+ if not gz.exists():
97
+ mismatched.append(f"{plain.name}: missing .gz")
98
+ continue
99
+ if gzip.open(gz, "rb").read() != plain.read_bytes():
100
+ mismatched.append(plain.name)
101
+ check("csv.gz twins byte-identical to plain csv", not mismatched, ",".join(mismatched))
102
+
103
+ # ---------------------------------------------------------------- split B
104
+ for mode in MODES:
105
+ label = manifest["mode_labels"][mode]
106
+ adduct = manifest["adduct_sets"][mode][0]
107
+ m = manifest["modes"][mode]
108
+ meta = np.load(PKG / f"protocol/derived/row_metadata_{mode}.npz")
109
+ npz = np.load(PKG / f"protocol/protocol_{mode}.npz")
110
+ smiles = json.loads((PKG / f"protocol/smiles_{mode}.json").read_text())
111
+ adducts = json.loads((PKG / f"protocol/adducts_{mode}.json").read_text())
112
+ check(f"B/{mode}: protocol adduct vocabulary == {adduct}", adducts == [adduct], str(adducts))
113
+
114
+ src = meta["source_row"]
115
+ smi_idx = meta["smiles_index"]
116
+ row_smiles = [smiles[int(i)] for i in smi_idx]
117
+ src_to_row = {int(s): i for i, s in enumerate(src.tolist())}
118
+ check(f"B/{mode}: preprocessed row metadata covers all {len(src):,} rows uniquely",
119
+ len(src_to_row) == len(src) and int(src.max()) < 560084)
120
+
121
+ # ---- splits table ----
122
+ split_rows = read_csv(PKG / f"splits/{mode}_compound_split.csv")
123
+ split_of: dict[str, str] = {}
124
+ for row in split_rows:
125
+ split_of[row["canonical_isomeric_smiles"]] = row["split"]
126
+ counts = Counter(split_of.values())
127
+ check(f"B/{mode}: compound split counts match manifest",
128
+ dict(counts) == m["split_compound_counts"],
129
+ f"{dict(counts)} vs {m['split_compound_counts']}")
130
+ check(f"B/{mode}: compound vocabulary is exactly the frozen smiles vocabulary",
131
+ set(split_of) == set(smiles), f"{len(split_of)} vs {len(smiles)}")
132
+ check(f"B/{mode}: compound_ids unique",
133
+ len({r["compound_id"] for r in split_rows}) == len(split_rows))
134
+ n_spectra_sum = sum(int(r["n_spectra"]) for r in split_rows)
135
+ check(f"B/{mode}: spectra per compound sum to manifest valid rows",
136
+ n_spectra_sum == m["valid_preprocessed_rows_before_singleton_filter"],
137
+ f"{n_spectra_sum}")
138
+ check(f"B/{mode}: split table columns are the released schema",
139
+ list(split_rows[0]) == ["polarity", "compound_id", "canonical_isomeric_smiles", "split",
140
+ "n_spectra", "n_frozen_queries", "n_raw_smiles_variants",
141
+ "first_msnlib_csv_data_row"],
142
+ str(list(split_rows[0])))
143
+
144
+ # compound-level identity disjointness across the three folds
145
+ train_set = {s for s, v in split_of.items() if v == "train"}
146
+ val_set = {s for s, v in split_of.items() if v == "val"}
147
+ test_set = {s for s, v in split_of.items() if v == "test"}
148
+ check(f"B/{mode}: train/val/test compound sets pairwise disjoint",
149
+ not (train_set & val_set) and not (train_set & test_set) and not (val_set & test_set))
150
+ check(f"B/{mode}: the three compound sets cover the whole vocabulary",
151
+ len(train_set) + len(val_set) + len(test_set) == len(smiles))
152
+
153
+ # ---- queries / libraries ----
154
+ for split, manifest_key in (("val", "validation"), ("test", "test")):
155
+ q = read_csv(PKG / f"queries/{mode}_{split}_queries.csv")
156
+ lib = read_csv(PKG / f"libraries/{mode}_{split}_library.csv")
157
+ q_smiles = [r["canonical_isomeric_smiles"] for r in q]
158
+ l_smiles = [r["canonical_isomeric_smiles"] for r in lib]
159
+ q_src = [int(r["msnlib_csv_data_row"]) for r in q]
160
+ l_src = [int(r["msnlib_csv_data_row"]) for r in lib]
161
+ exp = m[manifest_key]
162
+
163
+ check(f"B/{mode}/{split}: query count {len(q):,} matches manifest",
164
+ len(q) == exp["n_query"], f"{len(q)} vs {exp['n_query']}")
165
+ check(f"B/{mode}/{split}: library count {len(lib):,} matches manifest",
166
+ len(lib) == exp["n_library"], f"{len(lib)} vs {exp['n_library']}")
167
+ check(f"B/{mode}/{split}: ordered query SMILES sha256 matches manifest",
168
+ sha256_lines(q_smiles) == exp["ordered_query_smiles_sha256"])
169
+ check(f"B/{mode}/{split}: ordered library SMILES sha256 matches manifest",
170
+ sha256_lines(l_smiles) == exp["ordered_library_smiles_sha256"])
171
+ check(f"B/{mode}/{split}: table row order == frozen query_index/library_index",
172
+ [int(r["query_index"]) for r in q] == list(range(len(q)))
173
+ and [int(r["library_index"]) for r in lib] == list(range(len(lib))))
174
+ check(f"B/{mode}/{split}: query rows and library rows are disjoint",
175
+ not (set(q_src) & set(l_src)), f"{len(set(q_src) & set(l_src))} shared rows")
176
+ check(f"B/{mode}/{split}: queries are one spectrum per compound in this fold",
177
+ sorted(q_smiles) == sorted(val_set if split == "val" else test_set))
178
+ check(f"B/{mode}/{split}: library compounds respect the fold scope",
179
+ all(split_of[s] in ({"train", "val"} if split == "val" else {"train", "val", "test"})
180
+ for s in l_smiles))
181
+ # tables <-> frozen protocol row ids
182
+ q_rows = npz[f"{split}_query_rows"]
183
+ l_rows = npz[f"{split}_library_rows"]
184
+ check(f"B/{mode}/{split}: query table maps to protocol_{mode}.npz query rows",
185
+ [src_to_row[s] for s in q_src] == q_rows.tolist())
186
+ check(f"B/{mode}/{split}: library table maps to protocol_{mode}.npz library rows",
187
+ [src_to_row[s] for s in l_src] == l_rows.tolist())
188
+ check(f"B/{mode}/{split}: source rows unique in each table",
189
+ len(set(q_src)) == len(q_src) and len(set(l_src)) == len(l_src))
190
+ # per-query exact-adduct library positives
191
+ lib_counts = Counter(l_smiles)
192
+ recomputed = [lib_counts.get(s, 0) for s in q_smiles]
193
+ check(f"B/{mode}/{split}: n_library_positives column reproduces from the library table",
194
+ recomputed == [int(r["n_library_positives"]) for r in q])
195
+ n_pos = sum(1 for c in recomputed if c > 0)
196
+ if split == "test":
197
+ check(f"B/{mode}/test: queries with an exact-adduct library positive == manifest ({exp['n_queries_with_library_positive']:,})",
198
+ n_pos == exp["n_queries_with_library_positive"], f"{n_pos}")
199
+ check(f"B/{mode}/test: source-row hashes match manifest",
200
+ sha256_lines(map(str, q_src)) == exp["query_source_row_sha256"]
201
+ and sha256_lines(map(str, l_src)) == exp["library_source_row_sha256"])
202
+ else:
203
+ print(f" ({mode}/val queries with a library positive: {n_pos:,} / {len(q):,})")
204
+ # adduct / fold / CE sanity
205
+ check(f"B/{mode}/{split}: adduct column is strict {adduct} everywhere",
206
+ {r["adduct"] for r in q + lib} == {adduct})
207
+ check(f"B/{mode}/{split}: csv line = data row + 2 (header offset, no embedded newlines)",
208
+ all(int(r["msnlib_csv_line"]) == int(r["msnlib_csv_data_row"]) + 2 for r in q + lib))
209
+ # precursor_mz and peak counts agree with the frozen row metadata
210
+ pmz_rows = [src_to_row[s] for s in q_src]
211
+ pmz_ok = all(
212
+ np.float32(float(r["precursor_mz"])) == np.float32(meta["precursor_mz"][row])
213
+ and int(r["n_peaks"]) == int(meta["n_peaks"][row])
214
+ for r, row in zip(q, pmz_rows)
215
+ )
216
+ check(f"B/{mode}/{split}: precursor_mz/n_peaks agree with frozen row metadata (queries)", pmz_ok)
217
+ check(f"B/{mode}/{split}: query/library table columns are the released schema",
218
+ set(q[0]) == {"polarity", "split", "query_index", "compound_id", "canonical_isomeric_smiles",
219
+ "adduct", "msnlib_csv_data_row", "msnlib_csv_line", "precursor_mz", "n_peaks",
220
+ "collision_energy", "source_smiles_raw", "n_library_positives"}
221
+ and set(lib[0]) == {"polarity", "split", "library_index", "compound_id", "compound_split",
222
+ "canonical_isomeric_smiles", "adduct", "msnlib_csv_data_row",
223
+ "msnlib_csv_line", "precursor_mz", "n_peaks", "collision_energy",
224
+ "source_smiles_raw"},
225
+ "")
226
+
227
+ # partition: test library + test query rows cover every preprocessed row exactly once
228
+ tq = npz["test_query_rows"]
229
+ tl = npz["test_library_rows"]
230
+ check(f"B/{mode}: test queries + test library partition all preprocessed rows",
231
+ sorted(tq.tolist() + tl.tolist()) == list(range(len(src))))
232
+ # fold scope: train rows all belong to train compounds
233
+ check(f"B/{mode}: protocol train_rows all belong to train compounds",
234
+ all(split_of[row_smiles[i]] == "train" for i in npz["train_rows"].tolist()))
235
+ check(f"B/{mode}: protocol val_query_rows all belong to val compounds",
236
+ all(split_of[row_smiles[i]] == "val" for i in npz["val_query_rows"].tolist()))
237
+ check(f"B/{mode}: protocol test_query_rows all belong to test compounds",
238
+ all(split_of[row_smiles[i]] == "test" for i in npz["test_query_rows"].tolist()))
239
+
240
+ # recorded provenance of the source CSV
241
+ check(f"B/{mode}: source MSnLib.csv sha256 recorded",
242
+ manifest["csv_sha256"] == stats["source"]["msnlib_csv"]["sha256"])
243
+
244
+ # ---- cross-polarity relations recorded in stats ----
245
+ cross = stats["splits"]["B"]["cross_polarity"]
246
+ pos_test = {r["canonical_isomeric_smiles"] for r in read_csv(PKG / "splits/pos_compound_split.csv") if r["split"] == "test"}
247
+ neg_test = {r["canonical_isomeric_smiles"] for r in read_csv(PKG / "splits/neg_compound_split.csv") if r["split"] == "test"}
248
+ check("B: cross-polarity pos-test x neg-test intersection reproduces stats.json",
249
+ len(pos_test & neg_test) == cross["pos_test_intersect_neg_test"],
250
+ f"{len(pos_test & neg_test)} vs {cross['pos_test_intersect_neg_test']}")
251
+
252
+ # ---------------------------------------------------------------- split A
253
+ formulas = read_csv(A_DIR / "formula_split.csv")
254
+ rff = read_csv(A_DIR / "row_formula_fold.csv")
255
+ test_spectra = read_csv(A_DIR / "test_spectra.csv")
256
+ val_spectra = read_csv(A_DIR / "val_spectra.csv")
257
+ vote_official = read_csv(A_DIR / "test_molecules_voting.csv")
258
+ vote_canonical = read_csv(A_DIR / "test_molecules_voting_canonical_view.csv")
259
+
260
+ check("A: formula_split columns", list(formulas[0]) == ["formula", "fold", "n_spectra"], str(list(formulas[0])))
261
+ check("A: formula_split has 21,107 unique formulas",
262
+ len(formulas) == A_EXPECTED["n_formula"] and len({r["formula"] for r in formulas}) == A_EXPECTED["n_formula"])
263
+ check("A: formula fold values are train/val/test",
264
+ {r["fold"] for r in formulas} == {"train", "val", "test"})
265
+ check("A: formula-level counts 16,885 / 2,110 / 2,112",
266
+ dict(Counter(r["fold"] for r in formulas)) ==
267
+ {"train": A_EXPECTED["n_formula_train"], "val": A_EXPECTED["n_formula_val"], "test": A_EXPECTED["n_formula_test"]},
268
+ str(dict(Counter(r["fold"] for r in formulas))))
269
+ spectra_by_fold = Counter()
270
+ for r in formulas:
271
+ spectra_by_fold[r["fold"]] += int(r["n_spectra"])
272
+ check("A: spectra counts 446,667 / 55,980 / 57,437",
273
+ dict(spectra_by_fold) ==
274
+ {"train": A_EXPECTED["n_spectra_train"], "val": A_EXPECTED["n_spectra_val"], "test": A_EXPECTED["n_spectra_test"]},
275
+ str(dict(spectra_by_fold)))
276
+ check("A: total spectra = 560,084", sum(spectra_by_fold.values()) == A_EXPECTED["n_spectra_total"])
277
+
278
+ check("A: row_formula_fold covers rows 0..560,083 in order",
279
+ [int(r["row_index"]) for r in rff] == list(range(A_EXPECTED["n_spectra_total"])))
280
+ per_formula = defaultdict(set)
281
+ per_formula_count = Counter()
282
+ per_row_fold = Counter()
283
+ for r in rff:
284
+ per_formula[r["formula"]].add(r["fold"])
285
+ per_formula_count[r["formula"]] += 1
286
+ per_row_fold[r["fold"]] += 1
287
+ check("A: every formula occurs in exactly one fold",
288
+ len(per_formula) == A_EXPECTED["n_formula"] and max(len(v) for v in per_formula.values()) == 1)
289
+ check("A: row_formula_fold agrees with formula_split (fold and n_spectra)",
290
+ all(per_formula_count[r["formula"]] == int(r["n_spectra"]) and per_formula[r["formula"]] == {r["fold"]}
291
+ for r in formulas))
292
+ check("A: row-level fold totals match formula_split",
293
+ dict(per_row_fold) == dict(spectra_by_fold))
294
+ fold_by_row = {int(r["row_index"]): r["fold"] for r in rff}
295
+
296
+ check("A: test_spectra columns are the released schema",
297
+ list(test_spectra[0]) == ["row_index", "smiles", "precursor_mz", "adduct", "collision_energy",
298
+ "fold", "canonical_isomeric_smiles"], str(list(test_spectra[0])))
299
+ check("A: test_spectra has 57,437 rows, all fold=test",
300
+ len(test_spectra) == A_EXPECTED["n_test_spectra"]
301
+ and {r["fold"] for r in test_spectra} == {"test"})
302
+ test_rows_expected = [i for i, fold in fold_by_row.items() if fold == "test"]
303
+ check("A: test_spectra row_index equals the rows marked test in row_formula_fold",
304
+ [int(r["row_index"]) for r in test_spectra] == test_rows_expected)
305
+ check("A: val_spectra has 55,980 rows, all fold=val",
306
+ len(val_spectra) == A_EXPECTED["n_val_spectra"]
307
+ and {r["fold"] for r in val_spectra} == {"val"})
308
+ val_rows_expected = [i for i, fold in fold_by_row.items() if fold == "val"]
309
+ check("A: val_spectra row_index equals the rows marked val in row_formula_fold",
310
+ [int(r["row_index"]) for r in val_spectra] == val_rows_expected)
311
+
312
+ smiles_groups = Counter(r["smiles"] for r in test_spectra)
313
+ smiles_ge2 = sorted((smi, n) for smi, n in smiles_groups.items() if n >= 2)
314
+ check("A: official voting-unit table columns are group_id, smiles, n_spectra",
315
+ list(vote_official[0]) == ["group_id", "smiles", "n_spectra"], str(list(vote_official[0])))
316
+ check("A: official voting-unit table (MSnLib source SMILES) reproduces from test_spectra",
317
+ [(r["smiles"], int(r["n_spectra"])) for r in vote_official] == smiles_ge2)
318
+ check("A: official voting-unit table has 5,002 groups / 57,436 spectra",
319
+ len(vote_official) == A_EXPECTED["n_voting_official"]
320
+ and sum(int(r["n_spectra"]) for r in vote_official) == A_EXPECTED["n_voting_official_spectra"])
321
+ canon_groups = Counter(r["canonical_isomeric_smiles"] for r in test_spectra)
322
+ canon_ge2 = sorted((smi, n) for smi, n in canon_groups.items() if n >= 2)
323
+ check("A: canonical-view table columns are group_id, canonical_isomeric_smiles, n_spectra",
324
+ list(vote_canonical[0]) == ["group_id", "canonical_isomeric_smiles", "n_spectra"],
325
+ str(list(vote_canonical[0])))
326
+ check("A: canonical-view table reproduces from test_spectra",
327
+ [(r["canonical_isomeric_smiles"], int(r["n_spectra"])) for r in vote_canonical] == canon_ge2)
328
+ check("A: canonical-view table has 4,888 groups / 57,436 spectra",
329
+ len(vote_canonical) == A_EXPECTED["n_voting_canonical"]
330
+ and sum(int(r["n_spectra"]) for r in vote_canonical) == A_EXPECTED["n_voting_canonical_spectra"])
331
+ singletons = [smi for smi, n in canon_groups.items() if n == 1]
332
+ check("A: exactly one test spectrum lies outside the voting tables",
333
+ len(singletons) == 1 and smiles_groups[singletons[0]] == 1,
334
+ singletons[0] if singletons else "")
335
+
336
+ # retention-time companion table (split A row metadata, gzipped only)
337
+ rt_path = A_DIR / "msnlib_rt.csv.gz"
338
+ rt_doc = stats["splits"]["A"].get("retention_times", {})
339
+ check("A: retention-time companion table is shipped and matches stats.json",
340
+ rt_path.is_file() and rt_doc.get("bytes") == rt_path.stat().st_size
341
+ and rt_doc.get("sha256") == sha256_file(rt_path),
342
+ str(rt_doc.get("file")))
343
+ with gzip.open(rt_path, "rt", newline="") as fh:
344
+ rt_rows = list(csv.DictReader(fh))
345
+ check("A: retention-time table columns are row_index, rt",
346
+ bool(rt_rows) and list(rt_rows[0]) == ["row_index", "rt"],
347
+ str(list(rt_rows[0]) if rt_rows else []))
348
+ check("A: retention-time table has 560,084 rows in row order",
349
+ len(rt_rows) == A_EXPECTED["n_spectra_total"]
350
+ and [int(r["row_index"]) for r in rt_rows] == list(range(A_EXPECTED["n_spectra_total"])))
351
+ nonnumeric = []
352
+ empty = []
353
+ for r in rt_rows:
354
+ if not r["rt"].strip():
355
+ empty.append(r["row_index"])
356
+ continue
357
+ try:
358
+ float(r["rt"])
359
+ except ValueError:
360
+ nonnumeric.append(r["row_index"])
361
+ check("A: every retention time is present and numeric",
362
+ not empty and not nonnumeric, f"{len(empty)} empty, {len(nonnumeric)} non-numeric")
363
+
364
+ # ---------------------------------------------------------------- cross-split A x B
365
+ cross_stats = stats["cross_split"]
366
+ b_rows = set()
367
+ for mode in MODES:
368
+ for split in ("val", "test"):
369
+ for sub, role in (("queries", "query"), ("libraries", "library")):
370
+ path = PKG / f"{sub}/{mode}_{split}_{'queries' if role == 'query' else 'library'}.csv"
371
+ for r in read_csv(path):
372
+ b_rows.add(int(r["msnlib_csv_data_row"]))
373
+ check("A/B: every split-B table row exists in row_formula_fold",
374
+ b_rows <= set(fold_by_row), f"{len(b_rows - set(fold_by_row))} missing")
375
+ check("A/B: split-B tables cover all 441,829 preprocessed spectra",
376
+ len(b_rows) == 301636 + 140193, f"{len(b_rows)}")
377
+
378
+ compound_matrix = {}
379
+ spectra_matrix = {}
380
+ for mode in MODES:
381
+ split_rows = read_csv(PKG / f"splits/{mode}_compound_split.csv")
382
+ matrix = defaultdict(Counter)
383
+ for r in split_rows:
384
+ matrix[r["split"]][fold_by_row[int(r["first_msnlib_csv_data_row"])]] += 1
385
+ compound_matrix[mode] = {b: dict(sorted(c.items())) for b, c in sorted(matrix.items())}
386
+ smatrix = defaultdict(Counter)
387
+ for split in ("val", "test"):
388
+ for sub, role in (("queries", "query"), ("libraries", "library")):
389
+ path = PKG / f"{sub}/{mode}_{split}_{'queries' if role == 'query' else 'library'}.csv"
390
+ for r in read_csv(path):
391
+ b_split = r["split"] if role == "query" else r["compound_split"]
392
+ smatrix[f"{b_split}/{role}"][fold_by_row[int(r["msnlib_csv_data_row"])]] += 1
393
+ spectra_matrix[mode] = {k: dict(sorted(c.items())) for k, c in sorted(smatrix.items())}
394
+ check("A/B: compound-level cross tab reproduces stats.json",
395
+ compound_matrix == cross_stats["compound_cross_tab"])
396
+ check("A/B: spectra-level cross tab reproduces stats.json",
397
+ spectra_matrix == cross_stats["spectra_cross_tab"])
398
+
399
+ # row-level matrix: every preprocessed split-B row -> compound -> split-B fold -> split-A fold
400
+ row_matrix = {}
401
+ for mode in MODES:
402
+ mode_smiles = json.loads((PKG / f"protocol/smiles_{mode}.json").read_text())
403
+ mode_meta = np.load(PKG / f"protocol/derived/row_metadata_{mode}.npz")
404
+ mode_split = {r["canonical_isomeric_smiles"]: r["split"]
405
+ for r in read_csv(PKG / f"splits/{mode}_compound_split.csv")}
406
+ matrix = defaultdict(Counter)
407
+ for source_row, smiles_index in zip(mode_meta["source_row"].tolist(),
408
+ mode_meta["smiles_index"].tolist()):
409
+ matrix[mode_split[mode_smiles[int(smiles_index)]]][fold_by_row[int(source_row)]] += 1
410
+ row_matrix[mode] = {b: dict(sorted(c.items())) for b, c in sorted(matrix.items())}
411
+ check("A/B: row-level split-B x split-A cross tab reproduces stats.json",
412
+ row_matrix == cross_stats["row_cross_tab"])
413
+ check("A/B: row-level split-B totals equal the manifest split-spectra counts",
414
+ all(sum(sum(c.values()) for c in row_matrix[mode].values()) ==
415
+ sum(stats["splits"]["B"]["modes"][mode]["split_spectra_counts"].values())
416
+ for mode in MODES))
417
+
418
+ a_test = {row for row, fold in fold_by_row.items() if fold == "test"}
419
+ for mode in MODES:
420
+ overlap = cross_stats["overlap"][mode]
421
+ mode_rows = set()
422
+ for split in ("val", "test"):
423
+ for sub, role in (("queries", "query"), ("libraries", "library")):
424
+ path = PKG / f"{sub}/{mode}_{split}_{'queries' if role == 'query' else 'library'}.csv"
425
+ for r in read_csv(path):
426
+ mode_rows.add(int(r["msnlib_csv_data_row"]))
427
+ check(f"A/B/{mode}: A-test rows inside the split-B tables reproduce stats.json",
428
+ len(a_test & mode_rows) == overlap["A_test_rows_present_in_B_tables"],
429
+ f"{len(a_test & mode_rows)} vs {overlap['A_test_rows_present_in_B_tables']}")
430
+
431
+ # every split-B compound must map to one formula -> one split-A fold
432
+ consistent = True
433
+ for mode in MODES:
434
+ rows_of_compound = defaultdict(set)
435
+ for split in ("val", "test"):
436
+ for sub, role in (("queries", "query"), ("libraries", "library")):
437
+ path = PKG / f"{sub}/{mode}_{split}_{'queries' if role == 'query' else 'library'}.csv"
438
+ for r in read_csv(path):
439
+ rows_of_compound[r["canonical_isomeric_smiles"]].add(
440
+ fold_by_row[int(r["msnlib_csv_data_row"])])
441
+ consistent = consistent and all(len(v) == 1 for v in rows_of_compound.values())
442
+ check("A/B: every split-B compound has a single split-A fold (same formula)", consistent)
443
+
444
+ # ---------------------------------------------------------------- manifest integrity
445
+ documented_files = set(stats["files"])
446
+ shipped = {str(p.relative_to(PKG)) for p in PKG.rglob("*") if p.is_file()}
447
+ shipped.discard("stats.json")
448
+ shipped.discard("SHA256SUMS")
449
+ check("stats.json documents exactly the shipped files (except stats.json and SHA256SUMS)",
450
+ documented_files == shipped,
451
+ f"missing={sorted(shipped - documented_files)[:5]} extra={sorted(documented_files - shipped)[:5]}")
452
+ bad_files = []
453
+ for rel, info in stats["files"].items():
454
+ path = PKG / rel
455
+ if path.stat().st_size != info["bytes"] or sha256_file(path) != info["sha256"]:
456
+ bad_files.append(rel)
457
+ check("stats.json byte sizes and sha256 match every shipped file", not bad_files, ",".join(bad_files[:5]))
458
+
459
+ sums = (PKG / "SHA256SUMS").read_text().splitlines()
460
+ listed = {}
461
+ sums_ok = True
462
+ for line in sums:
463
+ if not line.strip():
464
+ continue
465
+ digest, _, rel = line.partition(" ")
466
+ if len(digest) != 64 or not rel:
467
+ sums_ok = False
468
+ break
469
+ listed[rel] = digest
470
+ check("SHA256SUMS parses as '<sha256> <path>' lines", sums_ok)
471
+ check("SHA256SUMS covers every shipped file except itself",
472
+ set(listed) == {str(p.relative_to(PKG)) for p in PKG.rglob("*") if p.is_file()} - {"SHA256SUMS"},
473
+ f"{len(listed)} entries")
474
+ check("SHA256SUMS hashes match the files",
475
+ all(sha256_file(PKG / rel) == digest for rel, digest in listed.items()))
476
+
477
+ # ---------------------------------------------------------------- release hygiene
478
+ text_suffixes = {".md", ".py", ".json", ".sh", ".csv", ".txt", ".cff", ""}
479
+ offenders = []
480
+ secret_hits = []
481
+ for path in PKG.rglob("*"):
482
+ if not path.is_file() or path.suffix not in text_suffixes:
483
+ continue
484
+ if path.name == "SHA256SUMS":
485
+ continue
486
+ try:
487
+ text = path.read_text(errors="ignore")
488
+ except OSError:
489
+ continue
490
+ lowered = text.lower()
491
+ for name in FORBIDDEN_NAMES:
492
+ if name in lowered:
493
+ offenders.append(f"{path.relative_to(PKG)}:{name}")
494
+ for pattern in FORBIDDEN_PATH_TOKENS:
495
+ if pattern in text:
496
+ secret_hits.append(f"{path.relative_to(PKG)}:{pattern}")
497
+ check("no retired legacy project naming anywhere in the shipped text files",
498
+ not offenders, ",".join(offenders[:5]))
499
+ check("no internal absolute paths or private keys in the shipped text files",
500
+ not secret_hits, ",".join(secret_hits[:5]))
501
+
502
+ failed = [name for name, ok, _ in CHECKS if not ok]
503
+ print(f"\n{len(CHECKS) - len(failed)}/{len(CHECKS)} checks passed")
504
+ if failed:
505
+ print("FAILED:", *failed, sep="\n ")
506
+ return 1
507
+ return 0
508
+
509
+
510
+ if __name__ == "__main__":
511
+ sys.exit(main())
split_A_full_msnlib/README.md ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # UltraMS MSnLib formula-level split (split A)
2
+
3
+ Version **1.0.0** · 2026-11-04 · license **CC BY 4.0**
4
+
5
+ The frozen, **formula-disjoint** 80/10/10 train / validation / test split of the complete
6
+ MSnLib tandem mass spectral library (560,084 spectra, all adducts). This directory is also
7
+ shipped as `split_A_full_msnlib/` inside `ultrams_msnlib_benchmark_v1/`.
8
+
9
+ | | train | validation | test | total |
10
+ | --- | ---: | ---: | ---: | ---: |
11
+ | molecular formulas | 16,885 | 2,110 | 2,112 | 21,107 |
12
+ | spectra | 446,667 | 55,980 | 57,437 | 560,084 |
13
+
14
+ Every spectrum of a molecular formula lies in exactly one fold; no formula occurs in two
15
+ folds. The frozen assignment is the `fold` column of `MSnLib.csv` and the split is replayed
16
+ exactly by [`build_split_a.py`](build_split_a.py).
17
+
18
+ ## Files
19
+
20
+ | file | rows | content |
21
+ | --- | ---: | --- |
22
+ | `formula_split.csv(.gz)` | 21,107 | `formula, fold, n_spectra` — one row per molecular formula |
23
+ | `row_formula_fold.csv(.gz)` | 560,084 | `row_index, formula, fold` — authoritative row → formula → fold map for all spectra |
24
+ | `test_spectra.csv(.gz)` | 57,437 | `row_index, smiles, precursor_mz, adduct, collision_energy, fold, canonical_isomeric_smiles` |
25
+ | `val_spectra.csv(.gz)` | 55,980 | same schema for the validation fold |
26
+ | `msnlib_rt.csv.gz` | 560,084 | `row_index, rt` — compact per-spectrum retention time (seconds); gzipped only |
27
+ | `test_molecules_voting.csv(.gz)` | 5,002 | **official** multiple-spectrum voting units (Figure 3d / 3a voting): the test spectra grouped by the MSnLib source SMILES string, group size ≥ 2 (57,436 spectra); reproduces the published voting task's `n_molecules = 5002` grouping member-for-member |
28
+ | `test_molecules_voting_canonical_view.csv(.gz)` | 4,888 | alternative canonical view (not the official unit): the same test spectra grouped by RDKit canonical isomeric SMILES, group size ≥ 2 (57,436 spectra) |
29
+ | `REPORT.json` | | machine-readable report: counts, expected values, hashes, cross-checks, anomaly record |
30
+ | `VERIFY.md` | | full verification record (inputs, counts, cross-checks, replay transcript) |
31
+ | `build_split_a.py` | | replay from `MSnLib.csv` and SHA-256 check against the frozen tables |
32
+
33
+ `row_index` is the 0-based data row of `MSnLib.csv` (560,084 rows, 752,707,651 bytes,
34
+ SHA-256 `be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07`; physical
35
+ line = data row + 2). Every `.csv` has a `.csv.gz` twin that decompresses to the identical
36
+ bytes.
37
+
38
+ ## Official voting units (Figure 3d / Figure 3a voting)
39
+
40
+ The official multiple-spectrum voting unit is the **MSnLib source SMILES string**. The
41
+ 57,437 test spectra contain 5,003 distinct source strings; one of them occurs in only one
42
+ spectrum, so `test_molecules_voting.csv` has **5,002 groups covering 57,436 spectra**. This
43
+ is the grouping of the published multiple-spectrum voting task and it is verified
44
+ member-for-member against the repository voting table (`n_molecules = 5002`).
45
+
46
+ For a chemically deduplicated view, `test_molecules_voting_canonical_view.csv` groups the
47
+ same spectra by RDKit canonical isomeric SMILES: 4,889 distinct molecules, of which
48
+ **4,888 groups cover the same 57,436 spectra**. 114 source-string groups merge into
49
+ chemically identical molecules, and the single excluded molecule is
50
+ `CC(C)(C)OC(=O)NCC1(CC(=O)O)CCCCC1`. The canonical view is an alternative, **not** the
51
+ official voting unit. See `VERIFY.md` §7.
52
+
53
+ ## Retention times (RT)
54
+
55
+ `msnlib_rt.csv.gz` is a compact companion table (1.4 MB gzipped, no 756 MB full CSV):
56
+ `row_index` is the 0-based `MSnLib.csv` data row (0 … 560,083) and `rt` is the retention time
57
+ in seconds, kept in the source text representation. It was exported from
58
+ `MSnLib_with_rt.csv` (755,984,910 bytes, SHA-256
59
+ `a5b7c38228287c5c1de401050445319b331ee9a5f17993d6e104e9a734fe2964`, columns
60
+ `mzs,intensities,smiles,precursor_mz,adduct,collision_energy,fold,rt`) after verifying
61
+ row-by-row that its first seven columns are identical to `MSnLib.csv` in the same order
62
+ (560,084/560,084 rows, 0 mismatches). RT is source metadata from the MSnLib records
63
+ (CC BY 4.0; see `NOTICE.md` / the parent package `NOTICE.md`).
64
+
65
+ ```python
66
+ import gzip
67
+ import pandas as pd
68
+
69
+ test = pd.read_csv("test_spectra.csv")
70
+ rt = pd.read_csv("msnlib_rt.csv.gz") # row_index, rt
71
+ test_rt = test.merge(rt, on="row_index", how="left")
72
+ assert test_rt["rt"].notna().all()
73
+ ```
74
+
75
+ The table is needed by the label-blind grouping / multiple-spectrum voting analyses
76
+ (Figure 3d), which use RT as spectrum metadata.
77
+
78
+ ## Quick start
79
+
80
+ ```python
81
+ import pandas as pd
82
+
83
+ formulas = pd.read_csv("formula_split.csv")
84
+ test = pd.read_csv("test_spectra.csv")
85
+ rows = pd.read_csv("row_formula_fold.csv") # 560,084 rows
86
+
87
+ # formula-level disjointness: one fold per formula
88
+ assert formulas.groupby("formula")["fold"].nunique().max() == 1
89
+ assert formulas["n_spectra"].sum() == 560_084
90
+ ```
91
+
92
+ ## Rebuild and verify
93
+
94
+ ```bash
95
+ # read-only replay + hash check (needs MSnLib.csv and RDKit 2026.03.5):
96
+ python3 build_split_a.py --csv /path/to/datasets/MSnLib/MSnLib.csv
97
+
98
+ # write the tables (byte-identical with the frozen copies under RDKit 2026.03.5):
99
+ python3 build_split_a.py --csv /path/to/MSnLib.csv --output-dir replay_split_a
100
+ ```
101
+
102
+ The split is **formula-disjoint, not molecule-disjoint**: different molecules can share a
103
+ formula and therefore a fold. The molecule-disjoint benchmark is split B
104
+ (strict-adduct 70/15/15) of `ultrams_msnlib_benchmark_v1/`; the two splits must never be
105
+ combined into a single global-disjointness claim. See `figures_mapping.md` in the parent
106
+ package for which manuscript panels use which split, and `NOTICE.md` for the MSnLib
107
+ attribution (Brungs et al., Zenodo 10.5281/zenodo.11163380, CC BY 4.0).
split_A_full_msnlib/REPORT.json ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "UltraMS MSnLib formula-level split",
3
+ "short_name": "UltraMS MSnLib split A (full library, formula-disjoint 80/10/10)",
4
+ "version": "1.0.0",
5
+ "date": "2026-11-04",
6
+ "license": "CC BY 4.0",
7
+ "description": "Frozen formula-level train/validation/test split of the complete MSnLib tandem mass spectral library (560,084 spectra, all adducts). Every spectrum of a molecular formula lies in exactly one fold; the three folds are disjoint at the molecular-formula level. This is the benchmark population for candidate ranking, multiple-spectrum voting, label-blind grouping and embedding analyses of the UltraMS manuscript (Figures 2b/2j, 3a/3b/3d/3g, 3a_sp_4, 3a_sp_5 and the single-spectrum baselines).",
8
+ "definition": {
9
+ "unit": "neutral molecular formula, computed with RDKit rdMolDescriptors.CalcMolFormula(Chem.MolFromSmiles(smiles))",
10
+ "assignment": "the frozen `fold` column of MSnLib.csv; this file is the frozen benchmark definition",
11
+ "proportions": "frozen, approximately 80/10/10 by formula group (train 80.0%, val 10.0%, test 10.0%)",
12
+ "rule": "formula-disjoint: all spectra sharing a formula lie in the same fold (0 conflicting formulas observed)",
13
+ "not_molecule_disjoint": "the same canonical molecule can occur in more than one fold when its SMILES variants have different molecular formulas is impossible, but a formula can contain several molecules; molecule-level disjointness is provided only by split B of the UltraMS MSnLib benchmark package"
14
+ },
15
+ "source": {
16
+ "msnlib_csv": {
17
+ "path_in_data_workspace": "datasets/MSnLib/MSnLib.csv",
18
+ "data_rows": 560084,
19
+ "bytes": 752707651,
20
+ "sha256": "be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07",
21
+ "columns": [
22
+ "mzs",
23
+ "intensities",
24
+ "smiles",
25
+ "precursor_mz",
26
+ "adduct",
27
+ "collision_energy",
28
+ "fold"
29
+ ],
30
+ "csv_line_to_data_row": "physical line = data row + 2 (header = line 1, no embedded newlines)"
31
+ },
32
+ "msnlib_original_release": {
33
+ "citation": "Brungs C., Schmid R., Pluskal T. MSnLib: efficient generation of open multi-stage fragmentation mass spectral libraries. Zenodo record 10.5281/zenodo.11163380 (2024), CC BY 4.0.",
34
+ "zenodo_record": "11163380",
35
+ "format": "per-file JSONL record lists (*_ms2.json)",
36
+ "n_files": 18,
37
+ "n_records_total": 560084,
38
+ "note": "the 18 MSnLib original MS2 JSONL files contain exactly 560,084 records, equal to the MSnLib.csv data-row count"
39
+ },
40
+ "msnlib_with_rt": {
41
+ "path_in_data_workspace": "datasets/MSnLib/MSnLib_with_rt.csv",
42
+ "bytes": 755984910,
43
+ "sha256": "a5b7c38228287c5c1de401050445319b331ee9a5f17993d6e104e9a734fe2964",
44
+ "columns": [
45
+ "mzs",
46
+ "intensities",
47
+ "smiles",
48
+ "precursor_mz",
49
+ "adduct",
50
+ "collision_energy",
51
+ "fold",
52
+ "rt"
53
+ ],
54
+ "note": "source of the compact retention-time table; verified row-by-row to have the same row order and the same first seven columns as MSnLib.csv (560,084 rows, 0 mismatches)"
55
+ }
56
+ },
57
+ "method": [
58
+ "read MSnLib.csv in source order (560,084 data rows)",
59
+ "cache RDKit formula and canonical isomeric SMILES per distinct source SMILES string (48,597 distinct strings)",
60
+ "verify that the fold label is a function of the molecular formula: every formula occurs in exactly one fold",
61
+ "write formula_split.csv (formula, fold, n_spectra), row_formula_fold.csv (all 560,084 rows), the test and validation spectra tables and the two multiple-spectrum voting tables",
62
+ "cross-check the exported test/validation spectra against the historical per-fold CSV files and sample the recorded `formula` fields of the MSnLib original JSON records"
63
+ ],
64
+ "environment": {
65
+ "run": "isolated data-preparation environment with read-only access to the MSnLib data workspace; nothing was written on the remote side",
66
+ "python": "3.10.12",
67
+ "rdkit": "2026.03.5",
68
+ "numpy": "2.2.6",
69
+ "local_postprocessing": "macOS, Python 3.13.11, numpy 2.4.4, pandas 3.0.3, RDKit 2026.03.3 (only gzip generation, the canonical voting view and cross-checks)"
70
+ },
71
+ "expected_vs_observed": {
72
+ "n_data_rows": {
73
+ "expected": 560084,
74
+ "observed": 560084,
75
+ "match": true
76
+ },
77
+ "n_unique_formula": {
78
+ "expected": 21107,
79
+ "observed": 21107,
80
+ "match": true
81
+ },
82
+ "n_formula_groups_train": {
83
+ "expected": 16885,
84
+ "observed": 16885,
85
+ "match": true
86
+ },
87
+ "n_formula_groups_val": {
88
+ "expected": 2110,
89
+ "observed": 2110,
90
+ "match": true
91
+ },
92
+ "n_formula_groups_test": {
93
+ "expected": 2112,
94
+ "observed": 2112,
95
+ "match": true
96
+ },
97
+ "n_spectra_train": {
98
+ "expected": 446667,
99
+ "observed": 446667,
100
+ "match": true
101
+ },
102
+ "n_spectra_val": {
103
+ "expected": 55980,
104
+ "observed": 55980,
105
+ "match": true
106
+ },
107
+ "n_spectra_test": {
108
+ "expected": 57437,
109
+ "observed": 57437,
110
+ "match": true
111
+ },
112
+ "n_formula_conflicts": {
113
+ "expected": 0,
114
+ "observed": 0,
115
+ "match": true
116
+ },
117
+ "n_rdkit_parse_failures": {
118
+ "expected": 0,
119
+ "observed": 0,
120
+ "match": true
121
+ },
122
+ "voting_groups_official_source_smiles": {
123
+ "expected": 5002,
124
+ "observed": 5002,
125
+ "match": true
126
+ },
127
+ "voting_spectra_official_source_smiles": {
128
+ "expected": 57436,
129
+ "observed": 57436,
130
+ "match": true
131
+ },
132
+ "voting_groups_canonical_view": {
133
+ "expected": 4888,
134
+ "observed": 4888,
135
+ "match": true
136
+ },
137
+ "voting_spectra_canonical_view": {
138
+ "expected": 57436,
139
+ "observed": 57436,
140
+ "match": true
141
+ }
142
+ },
143
+ "counts": {
144
+ "unique_formula_total": 21107,
145
+ "unique_formula_by_fold": {
146
+ "train": 16885,
147
+ "val": 2110,
148
+ "test": 2112
149
+ },
150
+ "spectra_by_fold": {
151
+ "train": 446667,
152
+ "val": 55980,
153
+ "test": 57437
154
+ },
155
+ "spectra_per_formula": {
156
+ "min": 1,
157
+ "max": 627,
158
+ "mean": 26.535,
159
+ "median": 15,
160
+ "n_formulas_with_one_spectrum": 25
161
+ },
162
+ "unique_raw_smiles_total": 48597,
163
+ "unique_canonical_isomeric_smiles_total": 47662,
164
+ "canonical_smiles_with_multiple_source_variants": 935,
165
+ "test": {
166
+ "n_spectra": 57437,
167
+ "n_formulas": 2112,
168
+ "n_unique_source_smiles": 5003,
169
+ "n_unique_canonical_isomeric_smiles": 4889,
170
+ "n_adducts": 11,
171
+ "adduct_counts": {
172
+ "[M+H]+": 31763,
173
+ "[M-H]-": 13824,
174
+ "[M+FA]-": 5884,
175
+ "[M+Cl]-": 2403,
176
+ "[M+H-H2O]+": 1252,
177
+ "[M+NH4]+": 1189,
178
+ "[M+Na]+": 583,
179
+ "[M]+": 287,
180
+ "[M+H-2H2O]+": 169,
181
+ "[M-H2O]+": 59,
182
+ "[M]-": 24
183
+ },
184
+ "collision_energy_counts": {
185
+ "15.0": 4264,
186
+ "20.0": 30383,
187
+ "30.0": 6041,
188
+ "45.0": 3289,
189
+ "60.0": 13429,
190
+ "75.0": 31
191
+ }
192
+ },
193
+ "validation": {
194
+ "n_spectra": 55980,
195
+ "n_formulas": 2110,
196
+ "n_unique_source_smiles": 4883,
197
+ "n_unique_canonical_isomeric_smiles": 4786,
198
+ "n_adducts": 11,
199
+ "adduct_counts": {
200
+ "[M+H]+": 30210,
201
+ "[M-H]-": 14160,
202
+ "[M+FA]-": 5700,
203
+ "[M+Cl]-": 2614,
204
+ "[M+H-H2O]+": 1070,
205
+ "[M+NH4]+": 1043,
206
+ "[M+Na]+": 597,
207
+ "[M]+": 330,
208
+ "[M+H-2H2O]+": 193,
209
+ "[M-H2O]+": 36,
210
+ "[M]-": 27
211
+ }
212
+ }
213
+ },
214
+ "tables": {
215
+ "formula_split.csv": {
216
+ "columns": [
217
+ "formula",
218
+ "fold",
219
+ "n_spectra"
220
+ ],
221
+ "n_rows": 21107,
222
+ "ordering": "fold order train, val, test; then formula lexicographically",
223
+ "bytes": 424350,
224
+ "sha256": "fcc44d1996d25306c884a6f8da30c1447fbe74f93c6fa12a3f271c0475a704b8",
225
+ "gzip": {
226
+ "bytes": 86748,
227
+ "sha256": "d52d77139c06d8662972fa638981894cf9f88fb3a5da1e1b73017b939d19fd4a"
228
+ }
229
+ },
230
+ "row_formula_fold.csv": {
231
+ "columns": [
232
+ "row_index",
233
+ "formula",
234
+ "fold"
235
+ ],
236
+ "n_rows": 560084,
237
+ "ordering": "MSnLib.csv data-row order (row_index = 0 .. 560,083)",
238
+ "bytes": 13351630,
239
+ "sha256": "ac6113867fdda683304533f097fc7287c13271a2deac8e792d1316dcf00264ff",
240
+ "gzip": {
241
+ "bytes": 1248826,
242
+ "sha256": "86150a89fb601a117d43c995065c3abc95ab0710cb80ffe47dfa5413aa57e686"
243
+ }
244
+ },
245
+ "test_spectra.csv": {
246
+ "columns": [
247
+ "row_index",
248
+ "smiles",
249
+ "precursor_mz",
250
+ "adduct",
251
+ "collision_energy",
252
+ "fold",
253
+ "canonical_isomeric_smiles"
254
+ ],
255
+ "n_rows": 57437,
256
+ "ordering": "MSnLib.csv data-row order",
257
+ "bytes": 7751575,
258
+ "sha256": "f2a870ba8ac9a54a36feaf1ecc12929ad9250ade2d082dc31454028c4b66b548",
259
+ "gzip": {
260
+ "bytes": 409844,
261
+ "sha256": "afb5c538d969bbfccd626a02a78572083a0830a8af0c52a39a45403e3ec71352"
262
+ }
263
+ },
264
+ "val_spectra.csv": {
265
+ "columns": [
266
+ "row_index",
267
+ "smiles",
268
+ "precursor_mz",
269
+ "adduct",
270
+ "collision_energy",
271
+ "fold",
272
+ "canonical_isomeric_smiles"
273
+ ],
274
+ "n_rows": 55980,
275
+ "ordering": "MSnLib.csv data-row order",
276
+ "bytes": 7421554,
277
+ "sha256": "f4fa5e0f8875991bf9df2bcb67a05437271ee18c317f33d9108f3ec28a887a82",
278
+ "gzip": {
279
+ "bytes": 401530,
280
+ "sha256": "d2e45289b564b40998479e7c3fe7b283097f1a9aebe798e369b259c7f1851cce"
281
+ }
282
+ },
283
+ "test_molecules_voting.csv": {
284
+ "columns": [
285
+ "group_id",
286
+ "smiles",
287
+ "n_spectra"
288
+ ],
289
+ "n_rows": 5002,
290
+ "n_spectra": 57436,
291
+ "role": "official multiple-spectrum voting units (Figure 3d / 3a voting): test spectra grouped by the MSnLib source SMILES string; group_id = 0-based rank over sorted source SMILES",
292
+ "bytes": 276185,
293
+ "sha256": "edad6ec7d6b6f9fc4763deac5245207aee767c78661532621c87acc5a9b1ee07",
294
+ "gzip": {
295
+ "bytes": 72880,
296
+ "sha256": "72ae163ce88b15d89fb1d556fbb8a698d001dd1e923df11399df13dfddec3db2"
297
+ }
298
+ },
299
+ "test_molecules_voting_canonical_view.csv": {
300
+ "columns": [
301
+ "group_id",
302
+ "canonical_isomeric_smiles",
303
+ "n_spectra"
304
+ ],
305
+ "n_rows": 4888,
306
+ "n_spectra": 57436,
307
+ "role": "alternative canonical view (not the official voting unit): the same test spectra grouped by RDKit canonical isomeric SMILES",
308
+ "bytes": 269502,
309
+ "sha256": "9fcd16ff4159e665833ea145848f94bee7c44115f4a858dd75fe486f15e92bd0",
310
+ "gzip": {
311
+ "bytes": 70897,
312
+ "sha256": "332c03eab3e9f91b0f956c59cd01c22f633166bd285e9942f5507839625f5bc0"
313
+ }
314
+ },
315
+ "msnlib_rt.csv.gz": {
316
+ "columns": [
317
+ "row_index",
318
+ "rt"
319
+ ],
320
+ "n_rows": 560084,
321
+ "role": "compact per-spectrum retention time (seconds), 0-based MSnLib.csv data row order; gzipped only to keep the package compact",
322
+ "bytes": 1483069,
323
+ "sha256": "994053612db874f7ac7985f278e04cc3463f3b93cd649a195bd167c4c6c7d3d8",
324
+ "note": "exported from MSnLib_with_rt.csv after a row-by-row first-seven-column alignment check (560,084 rows, 0 mismatches, 0 unparsable RT values)"
325
+ }
326
+ },
327
+ "verification": {
328
+ "formula_level_consistency": {
329
+ "n_formulas_with_more_than_one_fold": 0,
330
+ "n_raw_smiles_with_more_than_one_fold": 0,
331
+ "n_canonical_molecules_with_more_than_one_fold": 0,
332
+ "status": "PASS (every formula belongs to exactly one fold)"
333
+ },
334
+ "rdkit_parsing": {
335
+ "n_parse_failures": 0,
336
+ "n_unique_smiles": 48597,
337
+ "status": "PASS (all 48,597 distinct source SMILES parse)"
338
+ },
339
+ "historical_fold_csv_cross_check": {
340
+ "test": {
341
+ "path": "datasets/MSnLib/MSnLib_test.csv",
342
+ "label": "test",
343
+ "status": "match",
344
+ "n_rows": 57437,
345
+ "n_expected": 57437,
346
+ "mismatch_examples": []
347
+ },
348
+ "validation": {
349
+ "path": "datasets/MSnLib/MSnLib_val.csv",
350
+ "label": "val",
351
+ "status": "match",
352
+ "n_rows": 55980,
353
+ "n_expected": 55980,
354
+ "mismatch_examples": []
355
+ },
356
+ "checked_columns": [
357
+ "smiles",
358
+ "precursor_mz",
359
+ "adduct",
360
+ "collision_energy"
361
+ ],
362
+ "status": "PASS (row order and values identical)"
363
+ },
364
+ "msnlib_original_formula_cross_check": {
365
+ "files_checked_first_record": 18,
366
+ "first_record_formula_mismatches": 0,
367
+ "streamed_records": 37177,
368
+ "streamed_formula_mismatches": 0,
369
+ "streamed_files": [
370
+ "20241003_enammol_neg_ms2.json",
371
+ "20241003_enammol_pos_ms2.json"
372
+ ],
373
+ "sample_formula_C10H10BrN5O2": {
374
+ "n_original_records_checked": 3,
375
+ "n_rdkit_equals_record_formula": 3,
376
+ "records": [
377
+ {
378
+ "file": "20241003_mcescaf_pos_ms2.json",
379
+ "line": 9998,
380
+ "smiles": "O=C1CNC(=O)N1C1CN(c2ncc(Br)cn2)C1",
381
+ "record_formula": "C10H10BrN5O2",
382
+ "rdkit_formula": "C10H10BrN5O2",
383
+ "adduct": "[M+H]+"
384
+ },
385
+ {
386
+ "file": "20250828_mcediv_50k_sub_neg_ms2.json",
387
+ "line": 23736,
388
+ "smiles": "O=C1CNC(=O)N1C1CN(c2ncc(Br)cn2)C1",
389
+ "record_formula": "C10H10BrN5O2",
390
+ "rdkit_formula": "C10H10BrN5O2",
391
+ "adduct": "[M-H]-"
392
+ },
393
+ {
394
+ "file": "20250828_mcediv_50k_sub_pos_ms2.json",
395
+ "line": 2551,
396
+ "smiles": "COc1ccc(Br)cc1C(=O)Nc1nnn(C)n1",
397
+ "record_formula": "C10H10BrN5O2",
398
+ "rdkit_formula": "C10H10BrN5O2",
399
+ "adduct": "[M+H]+"
400
+ }
401
+ ],
402
+ "msnlib_csv_spectra_with_this_formula": 23,
403
+ "msnlib_csv_folds": {
404
+ "train": 23
405
+ }
406
+ },
407
+ "status": "PASS (recorded formula field equals the RDKit formula of the recorded SMILES)"
408
+ },
409
+ "repository_voting_table_cross_check": {
410
+ "repository_file": "benchmarks/molecular_identification/data/multiple_spectrum_voting_summary.csv",
411
+ "repository_n_molecules": 5002,
412
+ "our_grouping_matching_repository": "test_molecules_voting.csv",
413
+ "repository_comparison_table": "benchmarks/molecular_identification/data/multiple_spectrum_voting_per_group.csv.gz",
414
+ "repo_groups": 5002,
415
+ "repo_spectra": 57436,
416
+ "smiles_grouping_member_sets_identical": true,
417
+ "canonical_grouping_member_sets_identical": false,
418
+ "canonical_groups_merged_from_smiles_groups": 114,
419
+ "repo_strings_are_source_smiles": true,
420
+ "status": "PASS for the MSnLib-source-SMILES grouping (member sets identical); the canonical-isomeric-SMILES grouping merges 114 of those groups into 4,888 chemically identical molecules"
421
+ },
422
+ "rt_export": {
423
+ "source_file": "MSnLib_with_rt.csv",
424
+ "source_bytes": 755984910,
425
+ "source_sha256": "a5b7c38228287c5c1de401050445319b331ee9a5f17993d6e104e9a734fe2964",
426
+ "alignment_method": "row-by-row equality of the first seven columns (mzs, intensities, smiles, precursor_mz, adduct, collision_energy, fold) between MSnLib.csv and MSnLib_with_rt.csv, in file order",
427
+ "n_rows": 560084,
428
+ "n_row_mismatches": 0,
429
+ "n_extra_rows": 0,
430
+ "n_unparsable_rt": 0,
431
+ "n_distinct_rt_strings": 8369,
432
+ "rt_is_constant": false,
433
+ "status": "PASS (same row order and identical first seven columns; RT exported as row_index,rt)"
434
+ },
435
+ "replay": {
436
+ "script": "build_split_a.py",
437
+ "command": "python3 build_split_a.py --csv datasets/MSnLib/MSnLib.csv # read-only, no output dir",
438
+ "run_on": "isolated data-preparation environment (read-only), RDKit 2026.03.5",
439
+ "status": "PASS (all 12 count checks and all 6 table SHA-256 checks matched; exit 0)",
440
+ "transcript": [
441
+ "[PASS] n_data_rows: 560,084 (expected 560,084)",
442
+ "[PASS] n_unique_formula: 21,107 (expected 21,107)",
443
+ "[PASS] n_formula_train: 16,885 (expected 16,885)",
444
+ "[PASS] n_formula_val: 2,110 (expected 2,110)",
445
+ "[PASS] n_formula_test: 2,112 (expected 2,112)",
446
+ "[PASS] n_spectra_train: 446,667 (expected 446,667)",
447
+ "[PASS] n_spectra_val: 55,980 (expected 55,980)",
448
+ "[PASS] n_spectra_test: 57,437 (expected 57,437)",
449
+ "[PASS] n_voting_groups_official: 5,002 (expected 5,002)",
450
+ "[PASS] n_voting_spectra_official: 57,436 (expected 57,436)",
451
+ "[PASS] n_voting_groups_canonical: 4,888 (expected 4,888)",
452
+ "[PASS] n_voting_spectra_canonical: 57,436 (expected 57,436)",
453
+ "[PASS] formula_split.csv: 424,350 bytes sha256 fcc44d1996d25306c884a6f8da30c1447fbe74f93c6fa12a3f271c0475a704b8",
454
+ "[PASS] row_formula_fold.csv: 13,351,630 bytes sha256 ac6113867fdda683304533f097fc7287c13271a2deac8e792d1316dcf00264ff",
455
+ "[PASS] test_spectra.csv: 7,751,575 bytes sha256 f2a870ba8ac9a54a36feaf1ecc12929ad9250ade2d082dc31454028c4b66b548",
456
+ "[PASS] val_spectra.csv: 7,421,554 bytes sha256 f4fa5e0f8875991bf9df2bcb67a05437271ee18c317f33d9108f3ec28a887a82",
457
+ "[PASS] test_molecules_voting.csv: 276,185 bytes sha256 edad6ec7d6b6f9fc4763deac5245207aee767c78661532621c87acc5a9b1ee07",
458
+ "[PASS] test_molecules_voting_canonical_view.csv: 269,502 bytes sha256 9fcd16ff4159e665833ea145848f94bee7c44115f4a858dd75fe486f15e92bd0"
459
+ ]
460
+ }
461
+ },
462
+ "anomalies": [
463
+ {
464
+ "id": "official_voting_unit_source_smiles",
465
+ "severity": "documented definition difference, not a data error",
466
+ "expected_by_task": "5,002 groups / 57,436 spectra for the published multiple-spectrum voting task (n_molecules = 5002)",
467
+ "observed": "official MSnLib-source-SMILES grouping: 5,002 groups / 57,436 spectra (test_molecules_voting.csv); RDKit canonical-isomeric-SMILES grouping: 4,888 groups / 57,436 spectra (test_molecules_voting_canonical_view.csv)",
468
+ "explanation": "The published multiple-spectrum-voting task groups the 57,437 test spectra by the `smiles` field of its frozen single-spectrum records, which is the MSnLib source SMILES string. 5,003 distinct source strings exist for the test fold, one of which occurs in only one spectrum, leaving 5,002 groups covering 57,436 spectra. RDKit canonical isomeric SMILES merges SMILES variants of the same molecule: the test fold has 4,889 distinct canonical molecules, 4,888 of which have >= 2 spectra, again covering 57,436 spectra and leaving the same single-spectrum molecule (CC(C)(C)OC(=O)NCC1(CC(=O)O)CCCCC1) outside the voting table.",
469
+ "evidence": "our official MSnLib-source-SMILES grouping reproduces the repository `multiple_spectrum_voting_per_group.csv.gz` member sets and group sizes exactly (5,002 groups, 57,436 spectra); the canonical view merges 114 pairs/sets of those groups into chemically identical molecules",
470
+ "resolution": "the 5,002 source-SMILES groups are the official voting unit for Figure 3d and the Figure 3a voting readouts; the 4,888-group canonical table is an alternative chemical-deduplication view",
471
+ "tables": [
472
+ "test_molecules_voting.csv (official, source-string, 5,002 groups)",
473
+ "test_molecules_voting_canonical_view.csv (alternative canonical view, 4,888 groups)"
474
+ ]
475
+ }
476
+ ],
477
+ "known_caveats": [
478
+ "Retention times are source metadata from the MSnLib release (CC BY 4.0). `msnlib_rt.csv.gz` aligns them to `MSnLib.csv` by 0-based data row (`row_index`); it is not one of the six replayable split tables and is shipped gzipped only.",
479
+ "Molecule identity strings (canonical_isomeric_smiles) were frozen with RDKit 2026.03.5; other RDKit patch releases can serialise the same molecule differently, so compare the published strings, not freshly canonicalised ones. Molecular formulas are stable across RDKit patch releases.",
480
+ "Split A is formula-disjoint, not molecule-disjoint: different molecules can share a formula and therefore a fold, and a molecule's spectra always share one formula and thus one fold. Split B (molecule-level, strict-adduct) is the only molecule-disjoint resource in this package; the two splits must not be combined into a global disjointness claim.",
481
+ "Mass spectra are not redistributed in this split directory: the tables carry source row pointers into MSnLib.csv (752,707,651 bytes, SHA-256 be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07) and the MSnLib original release is available under CC BY 4.0.",
482
+ "row_index refers to MSnLib.csv data rows; its row order follows the frozen UltraMS MSnLib conversion of the MSnLib release records. The authoritative row -> formula -> fold mapping is row_formula_fold.csv."
483
+ ]
484
+ }
split_A_full_msnlib/VERIFY.md ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # VERIFY — UltraMS MSnLib formula-level split (split A)
2
+
3
+ This document records **what was checked, how, and with which exact values** for the
4
+ `msnlib_split_a_v1` tables. The split is a frozen benchmark definition: every spectrum of a
5
+ molecular formula lies in exactly one fold. All numbers below were re-derived from the
6
+ source `MSnLib.csv` and the shipped tables; nothing was written on the remote side.
7
+
8
+ ## 1. Environments
9
+
10
+ | side | runtime |
11
+ | --- | --- |
12
+ | isolated data-preparation environment (read-only access) | Linux, Python 3.10.12, RDKit 2026.03.5, NumPy 2.2.6 |
13
+ | local post-processing (gzip twins, auxiliary voting table, cross-checks) | macOS, Python 3.13.11, NumPy 2.4.4, pandas 3.0.3, RDKit 2026.03.3 |
14
+
15
+ The molecular formula and the frozen fold assignment do not depend on the RDKit patch
16
+ release. The canonical isomeric SMILES strings were frozen with RDKit **2026.03.5**; other
17
+ patch releases can serialise the same molecule differently (see §7).
18
+
19
+ ## 2. Inputs
20
+
21
+ | input | identity |
22
+ | --- | --- |
23
+ | `MSnLib.csv` | 560,084 data rows, 560,085 physical lines (no embedded newlines), 752,707,651 bytes, SHA-256 `be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07`, columns `mzs,intensities,smiles,precursor_mz,adduct,collision_energy,fold` |
24
+ | MSnLib original release | 18 per-file MS2 JSONL releases; 560,084 records in total (equal to the CSV data-row count); CC BY 4.0, Zenodo record 10.5281/zenodo.11163380 |
25
+ | historical per-fold CSV files (cross-check only) | `MSnLib_test.csv` (57,437 rows) and `MSnLib_val.csv` (55,980 rows) in the same data workspace |
26
+ | `MSnLib_with_rt.csv` (retention-time source) | 755,984,910 bytes, SHA-256 `a5b7c38228287c5c1de401050445319b331ee9a5f17993d6e104e9a734fe2964`; columns `mzs,intensities,smiles,precursor_mz,adduct,collision_energy,fold,rt` |
27
+
28
+ Access to the data workspace was read-only: `MSnLib.csv` and the original JSON records
29
+ were streamed out, the tables were computed in memory, and nothing was written or modified
30
+ on the remote side.
31
+
32
+ ## 3. Definition replayed
33
+
34
+ 1. For every data row, parse `smiles` with `Chem.MolFromSmiles` and compute the neutral
35
+ molecular formula with `rdMolDescriptors.CalcMolFormula`.
36
+ 2. Read the frozen `fold` label of the row.
37
+ 3. Require that the fold is a function of the formula only: every formula occurs in exactly
38
+ one fold.
39
+ 4. Export the tables. `row_formula_fold.csv` is the authoritative row → formula → fold
40
+ mapping for all 560,084 spectra.
41
+
42
+ ## 4. Counts — expected versus observed (all match)
43
+
44
+ | quantity | expected | observed | status |
45
+ | --- | ---: | ---: | --- |
46
+ | data rows | 560,084 | 560,084 | PASS |
47
+ | unique molecular formulas | 21,107 | 21,107 | PASS |
48
+ | formulas train / validation / test | 16,885 / 2,110 / 2,112 | 16,885 / 2,110 / 2,112 | PASS |
49
+ | spectra train / validation / test | 446,667 / 55,980 / 57,437 | 446,667 / 55,980 / 57,437 | PASS |
50
+ | formulas occurring in more than one fold | 0 | 0 | PASS |
51
+ | RDKit SMILES parse failures | 0 | 0 | PASS |
52
+ | test spectra | 57,437 | 57,437 | PASS |
53
+ | validation spectra | 55,980 | 55,980 | PASS |
54
+ | voting groups, official (MSnLib source SMILES) | 5,002 | 5,002 | PASS |
55
+ | voting spectra, official (MSnLib source SMILES) | 57,436 | 57,436 | PASS |
56
+ | voting groups, canonical view | 4,888 | 4,888 | PASS |
57
+ | voting spectra, canonical view | 57,436 | 57,436 | PASS |
58
+
59
+ The formula-level proportions are 16,885 / 2,110 / 2,112 formulas (80.00 % / 10.00 % /
60
+ 10.01 %) and 446,667 / 55,980 / 57,437 spectra (79.75 % / 9.99 % / 10.25 %).
61
+
62
+ Additional structure:
63
+
64
+ | quantity | value |
65
+ | --- | --- |
66
+ | unique source SMILES strings (all adducts) | 48,597 |
67
+ | unique canonical isomeric SMILES (all adducts) | 47,662 |
68
+ | canonical molecules with more than one source SMILES variant | 935 |
69
+ | spectra per formula: min / median / mean / max | 1 / 15 / 26.535 / 627 |
70
+ | formulas with exactly one spectrum | 25 |
71
+ | test formulas | 2,112 |
72
+ | test unique source SMILES / canonical molecules | 5,003 / 4,889 |
73
+ | validation unique source SMILES / canonical molecules | 4,883 / 4,786 |
74
+ | adducts present in the test / validation folds | 11 / 11 |
75
+
76
+ Test-fold adduct distribution: `[M+H]+` 31,763, `[M-H]-` 13,824, `[M+FA]-` 5,884,
77
+ `[M+Cl]-` 2,403, `[M+H-H2O]+` 1,252, `[M+NH4]+` 1,189, `[M+Na]+` 583, `[M]+` 287,
78
+ `[M+H-2H2O]+` 169, `[M-H2O]+` 59, `[M]-` 24. Collision energies: 15 (4,264), 20 (30,383),
79
+ 30 (6,041), 45 (3,289), 60 (13,429) and 75 eV (31).
80
+
81
+ ## 5. Cross-checks against independent sources
82
+
83
+ ### 5.1 Historical per-fold CSV files
84
+
85
+ The exported test and validation spectra tables were compared row by row (same order) with
86
+ `MSnLib_test.csv` and `MSnLib_val.csv` on `smiles`, `precursor_mz`, `adduct` and
87
+ `collision_energy`:
88
+
89
+ | file | rows | mismatches | status |
90
+ | --- | ---: | ---: | --- |
91
+ | `MSnLib_test.csv` | 57,437 | 0 | PASS |
92
+ | `MSnLib_val.csv` | 55,980 | 0 | PASS |
93
+
94
+ ### 5.2 `formula` field of the MSnLib original JSON records
95
+
96
+ The MSnLib original release records carry an independent `formula` field. For every one of
97
+ the 18 original files, the RDKit formula of the **first** record equals the recorded
98
+ `formula` (18/18). Two complete files were streamed and compared record by record:
99
+
100
+ | file | records | RDKit formula ≠ recorded formula |
101
+ | --- | ---: | ---: |
102
+ | `20241003_enammol_neg_ms2.json` | 12,825 | 0 |
103
+ | `20241003_enammol_pos_ms2.json` | 24,352 | 0 |
104
+
105
+ For the sample formula **C10H10BrN5O2**, three original records were located and checked;
106
+ the recorded `formula` equals the RDKit formula of the recorded SMILES in all three. Two of
107
+ them are different molecules that share the formula, which is exactly what the formula-level
108
+ split groups together:
109
+
110
+ | file | line | smiles | adduct |
111
+ | --- | ---: | --- | --- |
112
+ | `20241003_mcescaf_pos_ms2.json` | 9,998 | `O=C1CNC(=O)N1C1CN(c2ncc(Br)cn2)C1` | `[M+H]+` |
113
+ | `20250828_mcediv_50k_sub_neg_ms2.json` | 23,736 | `O=C1CNC(=O)N1C1CN(c2ncc(Br)cn2)C1` | `[M-H]-` |
114
+ | `20250828_mcediv_50k_sub_pos_ms2.json` | 2,551 | `COc1ccc(Br)cc1C(=O)Nc1nnn(C)n1` | `[M+H]+` |
115
+
116
+ `MSnLib.csv` contains **23** spectra with formula C10H10BrN5O2, all in the **train** fold
117
+ (so the sample formula does not leak into test).
118
+
119
+ ### 5.3 Multiple-spectrum voting table of the UltraMS repository
120
+
121
+ The repository summary
122
+ `benchmarks/molecular_identification/data/multiple_spectrum_voting_summary.csv` reports
123
+ `n_molecules = 5002` for the multiple-spectrum voting task. The per-group table
124
+ `multiple_spectrum_voting_per_group.csv.gz` (5,002 groups, 57,436 spectra) was compared
125
+ with our groupings:
126
+
127
+ | comparison | result |
128
+ | --- | --- |
129
+ | repository groups vs. the **official** grouping by MSnLib source SMILES string (`test_molecules_voting.csv`) | **identical** member sets and group sizes (5,002 groups, 57,436 spectra) |
130
+ | repository group strings vs. test-fold source SMILES set | all 5,002 repository strings are source SMILES strings of the test fold |
131
+ | repository groups vs. grouping by RDKit canonical isomeric SMILES | **not identical**: the canonical grouping merges 114 of the repository groups into 4,888 chemically identical molecules |
132
+
133
+ This is the only definition difference found; it is documented in §7 and in
134
+ `REPORT.json` → `anomalies`.
135
+
136
+ ### 5.4 Retention-time export
137
+
138
+ `msnlib_rt.csv.gz` was exported from `MSnLib_with_rt.csv` in the data-preparation
139
+ environment. Two files were read in parallel and compared row by row:
140
+
141
+ | check | result |
142
+ | --- | --- |
143
+ | headers | 7-column `MSnLib.csv` header vs 8-column with-RT header, prefix identical | PASS |
144
+ | rows compared | 560,084 / 560,084 | PASS |
145
+ | first seven columns identical at every row | 0 mismatches | PASS |
146
+ | extra rows at the end of either file | 0 / 0 | PASS |
147
+ | unparsable RT values | 0 / 560,084 | PASS |
148
+ | distinct RT strings | 8,369 (RT is not constant) | PASS |
149
+
150
+ Because the row order and the first seven columns are identical, `row_index` alone is a
151
+ complete join key to `MSnLib.csv`. The exported table is
152
+
153
+ `msnlib_rt.csv.gz` — 1,483,069 bytes, SHA-256
154
+ `994053612db874f7ac7985f278e04cc3463f3b93cd649a195bd167c4c6c7d3d8`, 560,084 data rows,
155
+ columns `row_index,rt`, gzipped only (no plain twin) to keep the package compact.
156
+
157
+ ## 6. Frozen table hashes
158
+
159
+ SHA-256 of the plain CSV files (the `.csv.gz` twins decompress to exactly these bytes):
160
+
161
+ | file | rows | bytes | SHA-256 |
162
+ | --- | ---: | ---: | --- |
163
+ | `formula_split.csv` | 21,107 | 424,350 | `fcc44d1996d25306c884a6f8da30c1447fbe74f93c6fa12a3f271c0475a704b8` |
164
+ | `row_formula_fold.csv` | 560,084 | 13,351,630 | `ac6113867fdda683304533f097fc7287c13271a2deac8e792d1316dcf00264ff` |
165
+ | `test_spectra.csv` | 57,437 | 7,751,575 | `f2a870ba8ac9a54a36feaf1ecc12929ad9250ade2d082dc31454028c4b66b548` |
166
+ | `val_spectra.csv` | 55,980 | 7,421,554 | `f4fa5e0f8875991bf9df2bcb67a05437271ee18c317f33d9108f3ec28a887a82` |
167
+ | `test_molecules_voting.csv` | 5,002 | 276,185 | `edad6ec7d6b6f9fc4763deac5245207aee767c78661532621c87acc5a9b1ee07` |
168
+ | `test_molecules_voting_canonical_view.csv` | 4,888 | 269,502 | `9fcd16ff4159e665833ea145848f94bee7c44115f4a858dd75fe486f15e92bd0` |
169
+
170
+ Gzipped-only companion: `msnlib_rt.csv.gz` — 560,084 rows, 1,483,069 bytes, SHA-256
171
+ `994053612db874f7ac7985f278e04cc3463f3b93cd649a195bd167c4c6c7d3d8`.
172
+
173
+ ## 7. Voting-unit definitions: official 5,002 source-SMILES groups vs 4,888 canonical groups
174
+
175
+ The **official** multiple-spectrum voting unit is the MSnLib source SMILES string. The test
176
+ fold contains 5,003 distinct source SMILES strings and 4,889 distinct RDKit canonical
177
+ isomeric molecules:
178
+
179
+ * grouping by the **source SMILES string** gives **5,002 groups** with ≥2 spectra covering
180
+ **57,436 spectra** (one source string occurs in only one spectrum), and this grouping is
181
+ **member-for-member identical** to the published repository table that defines
182
+ `n_molecules = 5002`; it is shipped as `test_molecules_voting.csv`;
183
+ * grouping by **RDKit canonical isomeric SMILES** gives **4,888 groups** covering the same
184
+ 57,436 spectra, leaving exactly one single-spectrum molecule
185
+ (`CC(C)(C)OC(=O)NCC1(CC(=O)O)CCCCC1`); it is shipped as
186
+ `test_molecules_voting_canonical_view.csv` and is an **alternative chemical-deduplication
187
+ view, not the official voting unit**.
188
+
189
+ The difference is a property of the source library: 114 canonical molecules are written with
190
+ more than one SMILES string among their test spectra. No data was altered to force either
191
+ count.
192
+
193
+ ## 8. Replay from `MSnLib.csv`
194
+
195
+ `build_split_a.py` replays the complete split (formula computation, frozen fold assignment,
196
+ all six tables) from `MSnLib.csv`. It was run **read-only in the isolated data-preparation environment**
197
+ (RDKit 2026.03.5) without an output directory:
198
+
199
+ ```bash
200
+ python3 build_split_a.py --csv datasets/MSnLib/MSnLib.csv
201
+ ```
202
+
203
+ Result: all 12 count checks passed, all 6 table SHA-256 values matched the frozen files, and
204
+ the script exited 0. Transcript:
205
+
206
+ ```text
207
+ [PASS] n_data_rows: 560,084 (expected 560,084)
208
+ [PASS] n_unique_formula: 21,107 (expected 21,107)
209
+ [PASS] n_formula_train: 16,885 (expected 16,885)
210
+ [PASS] n_formula_val: 2,110 (expected 2,110)
211
+ [PASS] n_formula_test: 2,112 (expected 2,112)
212
+ [PASS] n_spectra_train: 446,667 (expected 446,667)
213
+ [PASS] n_spectra_val: 55,980 (expected 55,980)
214
+ [PASS] n_spectra_test: 57,437 (expected 57,437)
215
+ [PASS] n_voting_groups_official: 5,002 (expected 5,002)
216
+ [PASS] n_voting_spectra_official: 57,436 (expected 57,436)
217
+ [PASS] n_voting_groups_canonical: 4,888 (expected 4,888)
218
+ [PASS] n_voting_spectra_canonical: 57,436 (expected 57,436)
219
+ [PASS] formula_split.csv: 424,350 bytes sha256 fcc44d1996d25306c884a6f8da30c1447fbe74f93c6fa12a3f271c0475a704b8
220
+ [PASS] row_formula_fold.csv: 13,351,630 bytes sha256 ac6113867fdda683304533f097fc7287c13271a2deac8e792d1316dcf00264ff
221
+ [PASS] test_spectra.csv: 7,751,575 bytes sha256 f2a870ba8ac9a54a36feaf1ecc12929ad9250ade2d082dc31454028c4b66b548
222
+ [PASS] val_spectra.csv: 7,421,554 bytes sha256 f4fa5e0f8875991bf9df2bcb67a05437271ee18c317f33d9108f3ec28a887a82
223
+ [PASS] test_molecules_voting.csv: 276,185 bytes sha256 edad6ec7d6b6f9fc4763deac5245207aee767c78661532621c87acc5a9b1ee07
224
+ [PASS] test_molecules_voting_canonical_view.csv: 269,502 bytes sha256 9fcd16ff4159e665833ea145848f94bee7c44115f4a858dd75fe486f15e92bd0
225
+ ```
226
+
227
+ A local replay needs `MSnLib.csv` (752,707,651 bytes, SHA-256 as in §2) and RDKit
228
+ 2026.03.5. With a different RDKit patch release, the tables that carry canonical
229
+ strings can differ textually while every count above still matches; the script reports that
230
+ as a `DIFF` with an explanatory message (or a warning under `--lenient-rdkit`) and the
231
+ formula tables are unaffected.
232
+
233
+ ## 9. Simple structural checks
234
+
235
+ ```bash
236
+ # rows
237
+ wc -l formula_split.csv row_formula_fold.csv test_spectra.csv val_spectra.csv \
238
+ test_molecules_voting.csv test_molecules_voting_canonical_view.csv
239
+ # 21108 / 560085 / 57438 / 55981 / 5003 / 4889 (incl. header)
240
+ # gzip -dc msnlib_rt.csv.gz | wc -l -> 560085 (incl. header)
241
+
242
+ # csv.gz twins are byte-identical after decompression
243
+ for f in *.csv; do cmp <(gzip -dc "$f.gz") "$f" || echo "MISMATCH $f"; done
244
+
245
+ # formula-level uniqueness
246
+ python3 - <<'PY'
247
+ import csv, collections
248
+ fold = {}
249
+ for r in csv.DictReader(open("formula_split.csv")):
250
+ fold[r["formula"]] = r["fold"]
251
+ print(len(fold), collections.Counter(fold.values()))
252
+ PY
253
+ ```
254
+
255
+ ## 10. What could not be verified from this directory alone
256
+
257
+ * The actual peak arrays (`mzs`/`intensities`) are not shipped; they live in `MSnLib.csv`.
258
+ The row pointers and the row → formula → fold mapping in `row_formula_fold.csv` are the
259
+ authoritative link back to the spectra.
260
+ * The exact physical row order of `MSnLib.csv` (which follows the frozen UltraMS conversion
261
+ of the MSnLib release records); the package depends on the row pointers, not on
262
+ reconstructing that order from the release files.
263
+ * The historical Figure-3 analysis artifacts themselves; only the published repository
264
+ voting-group table was cross-checked (§5.3).
265
+
266
+ ## 11. Version
267
+
268
+ Split A release `1.0.0`, generated 2026-11-04. Any change to the tables, the fold
269
+ assignment or the formula computation invalidates the hashes above and requires a new
270
+ version directory.
split_A_full_msnlib/build_split_a.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Replay the frozen UltraMS MSnLib formula-level split (split A) from MSnLib.csv.
3
+
4
+ The split is defined by one rule: **every spectrum of a molecular formula belongs to
5
+ exactly one fold**. The official multiple-spectrum voting unit is the MSnLib source SMILES
6
+ 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
7
+ `fold` column of `MSnLib.csv` (560,084 spectra, 21,107 molecular formulas), and the
8
+ per-fold counts are 16,885 / 2,110 / 2,112 formulas and 446,667 / 55,980 / 57,437
9
+ spectra for train / validation / test. This script recomputes the formula of every
10
+ spectrum with RDKit, verifies that the fold is formula-consistent, rebuilds the shipped
11
+ tables in memory and compares their SHA-256 with the frozen values. With
12
+ `--output-dir` it also writes the tables.
13
+
14
+ Usage
15
+ -----
16
+ # read-only replay + hash check (nothing written):
17
+ python3 build_split_a.py --csv /path/to/workspace/datasets/MSnLib/MSnLib.csv
18
+
19
+ # same, and write the tables:
20
+ python3 build_split_a.py --csv ... --output-dir replay_split_a
21
+
22
+ Requirements: Python >= 3.10 and RDKit 2026.03.5 (the frozen canonicalisation runtime).
23
+ Other RDKit patch releases can serialise the same molecule differently; use
24
+ `--lenient-rdkit` to downgrade the resulting table-hash mismatches to warnings.
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import collections
30
+ import csv
31
+ import hashlib
32
+ import io
33
+ import json
34
+ import sys
35
+
36
+ from rdkit import Chem, RDLogger
37
+ from rdkit.Chem import rdMolDescriptors
38
+
39
+ RDLogger.DisableLog("rdApp.*")
40
+ csv.field_size_limit(10**9)
41
+
42
+ FOLD_ORDER = ["train", "val", "test"]
43
+
44
+ SOURCE_CSV_SHA256 = "be54b33039cf18675751ea3c6354b592177c899a0cd5df303ae616330133ec07"
45
+ EXPECTED = {
46
+ "n_data_rows": 560084,
47
+ "n_unique_formula": 21107,
48
+ "n_formula_train": 16885,
49
+ "n_formula_val": 2110,
50
+ "n_formula_test": 2112,
51
+ "n_spectra_train": 446667,
52
+ "n_spectra_val": 55980,
53
+ "n_spectra_test": 57437,
54
+ "n_voting_groups_official": 5002,
55
+ "n_voting_spectra_official": 57436,
56
+ "n_voting_groups_canonical": 4888,
57
+ "n_voting_spectra_canonical": 57436,
58
+ }
59
+ FROZEN = {
60
+ "formula_split.csv": (424350, "fcc44d1996d25306c884a6f8da30c1447fbe74f93c6fa12a3f271c0475a704b8"),
61
+ "row_formula_fold.csv": (13351630, "ac6113867fdda683304533f097fc7287c13271a2deac8e792d1316dcf00264ff"),
62
+ "test_spectra.csv": (7751575, "f2a870ba8ac9a54a36feaf1ecc12929ad9250ade2d082dc31454028c4b66b548"),
63
+ "val_spectra.csv": (7421554, "f4fa5e0f8875991bf9df2bcb67a05437271ee18c317f33d9108f3ec28a887a82"),
64
+ "test_molecules_voting.csv": (276185, "edad6ec7d6b6f9fc4763deac5245207aee767c78661532621c87acc5a9b1ee07"),
65
+ "test_molecules_voting_canonical_view.csv": (269502, "9fcd16ff4159e665833ea145848f94bee7c44115f4a858dd75fe486f15e92bd0"),
66
+ }
67
+ CANONICAL_DEPENDENT = {"test_spectra.csv", "val_spectra.csv", "test_molecules_voting.csv",
68
+ "test_molecules_voting_canonical_view.csv"}
69
+
70
+
71
+ def sha256(data: bytes) -> str:
72
+ return hashlib.sha256(data).hexdigest()
73
+
74
+
75
+ def compute(smiles):
76
+ mol = Chem.MolFromSmiles(smiles)
77
+ if mol is None:
78
+ return None, None
79
+ return rdMolDescriptors.CalcMolFormula(mol), Chem.MolToSmiles(mol)
80
+
81
+
82
+ def replay(csv_path: str):
83
+ cache = {}
84
+ bad = []
85
+ bad_folds = collections.Counter()
86
+ fold_counts = collections.Counter()
87
+ formula_spectra = collections.Counter()
88
+ formula_folds = collections.defaultdict(set)
89
+ fold_formulas = collections.defaultdict(set)
90
+ formula_rows = []
91
+ test_rows = []
92
+ val_rows = []
93
+
94
+ with open(csv_path, newline="") as fh:
95
+ reader = csv.reader(fh)
96
+ header = next(reader)
97
+ col = {name: i for i, name in enumerate(header)}
98
+ for row_index, row in enumerate(reader):
99
+ smiles = row[col["smiles"]]
100
+ fold = row[col["fold"]]
101
+ if smiles not in cache:
102
+ cache[smiles] = compute(smiles)
103
+ formula, canon = cache[smiles]
104
+ if formula is None:
105
+ bad.append({"row_index": row_index, "smiles": smiles})
106
+ continue
107
+ if fold not in FOLD_ORDER:
108
+ bad_folds[fold] += 1
109
+ fold_counts[fold] += 1
110
+ formula_spectra[formula] += 1
111
+ formula_folds[formula].add(fold)
112
+ fold_formulas[fold].add(formula)
113
+ formula_rows.append((row_index, formula, fold))
114
+ if fold in ("test", "val"):
115
+ target = test_rows if fold == "test" else val_rows
116
+ target.append((row_index, smiles, row[col["precursor_mz"]], row[col["adduct"]],
117
+ row[col["collision_energy"]], fold, canon))
118
+ n_rows = len(formula_rows) + len(bad)
119
+
120
+ conflicts = {f: sorted(s) for f, s in formula_folds.items() if len(s) > 1}
121
+
122
+ # ---- tables (byte-identical to the frozen files) ----
123
+ fold_rank = {f: i for i, f in enumerate(FOLD_ORDER)}
124
+ buf = io.StringIO()
125
+ w = csv.writer(buf, lineterminator="\n")
126
+ w.writerow(["formula", "fold", "n_spectra"])
127
+ for formula, n in sorted(
128
+ formula_spectra.items(), key=lambda kv: (fold_rank.get(sorted(formula_folds[kv[0]])[0], 99), kv[0])
129
+ ):
130
+ w.writerow([formula, sorted(formula_folds[formula])[0], n])
131
+ tables = {"formula_split.csv": buf.getvalue()}
132
+
133
+ buf = io.StringIO()
134
+ w = csv.writer(buf, lineterminator="\n")
135
+ w.writerow(["row_index", "formula", "fold"])
136
+ for row_index, formula, fold in formula_rows:
137
+ w.writerow([row_index, formula, fold])
138
+ tables["row_formula_fold.csv"] = buf.getvalue()
139
+
140
+ def spectra_csv(rows):
141
+ buf = io.StringIO()
142
+ w = csv.writer(buf, lineterminator="\n")
143
+ w.writerow(["row_index", "smiles", "precursor_mz", "adduct", "collision_energy", "fold",
144
+ "canonical_isomeric_smiles"])
145
+ for r in rows:
146
+ w.writerow([r[0], r[1], r[2], r[3], r[4], r[5], r[6]])
147
+ return buf.getvalue()
148
+
149
+ tables["test_spectra.csv"] = spectra_csv(test_rows)
150
+ tables["val_spectra.csv"] = spectra_csv(val_rows)
151
+
152
+ canon_groups = collections.Counter(r[6] for r in test_rows)
153
+ canon_ge2 = sorted((k, v) for k, v in canon_groups.items() if v >= 2)
154
+ buf = io.StringIO()
155
+ w = csv.writer(buf, lineterminator="\n")
156
+ w.writerow(["group_id", "canonical_isomeric_smiles", "n_spectra"])
157
+ for group_id, (canon, n) in enumerate(canon_ge2):
158
+ w.writerow([group_id, canon, n])
159
+ tables["test_molecules_voting_canonical_view.csv"] = buf.getvalue()
160
+
161
+ smiles_groups = collections.Counter(r[1] for r in test_rows)
162
+ smiles_ge2 = sorted((k, v) for k, v in smiles_groups.items() if v >= 2)
163
+ buf = io.StringIO()
164
+ w = csv.writer(buf, lineterminator="\n")
165
+ w.writerow(["group_id", "smiles", "n_spectra"])
166
+ for group_id, (smiles, n) in enumerate(smiles_ge2):
167
+ w.writerow([group_id, smiles, n])
168
+ tables["test_molecules_voting.csv"] = buf.getvalue()
169
+
170
+ summary = {
171
+ "n_data_rows": n_rows,
172
+ "n_unique_formula": len(formula_spectra),
173
+ "n_formula_by_fold": {f: len(fold_formulas[f]) for f in FOLD_ORDER},
174
+ "n_spectra_by_fold": {f: fold_counts[f] for f in FOLD_ORDER},
175
+ "n_formula_with_multiple_folds": len(conflicts),
176
+ "formula_conflicts": conflicts,
177
+ "n_rdkit_parse_failures": len(bad),
178
+ "parse_failure_examples": bad[:5],
179
+ "unexpected_folds": dict(bad_folds),
180
+ "n_voting_groups_official": len(smiles_ge2),
181
+ "n_voting_spectra_official": sum(n for _, n in smiles_ge2),
182
+ "n_voting_groups_canonical": len(canon_ge2),
183
+ "n_voting_spectra_canonical": sum(n for _, n in canon_ge2),
184
+ }
185
+ return tables, summary
186
+
187
+
188
+ def main() -> int:
189
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
190
+ parser.add_argument("--csv", required=True, help="path to MSnLib.csv (560,084 data rows)")
191
+ parser.add_argument("--output-dir", default=None, help="write the tables here")
192
+ parser.add_argument("--lenient-rdkit", action="store_true",
193
+ help="downgrade canonical-string hash mismatches caused by a different RDKit release to warnings")
194
+ args = parser.parse_args()
195
+
196
+ digest = hashlib.sha256()
197
+ with open(args.csv, "rb") as fh:
198
+ while block := fh.read(8 << 20):
199
+ digest.update(block)
200
+ source_sha = digest.hexdigest()
201
+ print(f"source csv : {args.csv}")
202
+ print(f"source sha : {source_sha}")
203
+ if source_sha != SOURCE_CSV_SHA256:
204
+ print(f"[WARN] source SHA-256 differs from the frozen MSnLib.csv ({SOURCE_CSV_SHA256})")
205
+
206
+ tables, summary = replay(args.csv)
207
+
208
+ failures = []
209
+ actuals = {
210
+ "n_data_rows": summary["n_data_rows"],
211
+ "n_unique_formula": summary["n_unique_formula"],
212
+ "n_formula_train": summary["n_formula_by_fold"]["train"],
213
+ "n_formula_val": summary["n_formula_by_fold"]["val"],
214
+ "n_formula_test": summary["n_formula_by_fold"]["test"],
215
+ "n_spectra_train": summary["n_spectra_by_fold"]["train"],
216
+ "n_spectra_val": summary["n_spectra_by_fold"]["val"],
217
+ "n_spectra_test": summary["n_spectra_by_fold"]["test"],
218
+ "n_voting_groups_official": summary["n_voting_groups_official"],
219
+ "n_voting_spectra_official": summary["n_voting_spectra_official"],
220
+ "n_voting_groups_canonical": summary["n_voting_groups_canonical"],
221
+ "n_voting_spectra_canonical": summary["n_voting_spectra_canonical"],
222
+ }
223
+ for key, expected in EXPECTED.items():
224
+ actual = actuals[key]
225
+ ok = actual == expected
226
+ print(f"[{'PASS' if ok else 'FAIL'}] {key}: {actual:,} (expected {expected:,})")
227
+ if not ok:
228
+ failures.append(key)
229
+ if summary["n_formula_with_multiple_folds"]:
230
+ print(f"[FAIL] {summary['n_formula_with_multiple_folds']} formulas occur in more than one fold")
231
+ failures.append("formula_fold_consistency")
232
+ if summary["n_rdkit_parse_failures"]:
233
+ print(f"[FAIL] {summary['n_rdkit_parse_failures']} SMILES could not be parsed")
234
+ failures.append("rdkit_parse")
235
+ if summary["unexpected_folds"]:
236
+ print(f"[FAIL] unexpected fold labels: {summary['unexpected_folds']}")
237
+ failures.append("unexpected_folds")
238
+
239
+ canonical_diffs = []
240
+ for name, (expected_bytes, expected_sha) in FROZEN.items():
241
+ data = tables[name].encode()
242
+ got_sha = sha256(data)
243
+ ok = len(data) == expected_bytes and got_sha == expected_sha
244
+ print(f"[{'PASS' if ok else 'DIFF'}] {name}: {len(data):,} bytes sha256 {got_sha}")
245
+ if not ok:
246
+ if name in CANONICAL_DEPENDENT:
247
+ canonical_diffs.append(name)
248
+ else:
249
+ failures.append(name)
250
+
251
+ if args.output_dir:
252
+ import os
253
+ os.makedirs(args.output_dir, exist_ok=True)
254
+ for name, text in tables.items():
255
+ with open(os.path.join(args.output_dir, name), "w", newline="") as fh:
256
+ fh.write(text)
257
+ print(f"wrote {len(tables)} tables to {args.output_dir}")
258
+
259
+ print("\nsummary:")
260
+ print(json.dumps(summary, indent=2))
261
+
262
+ if canonical_diffs:
263
+ message = ("canonical-string tables differ from the frozen copies; the frozen tables were produced with "
264
+ "RDKit 2026.03.5 and a different patch release may serialise the same molecule differently")
265
+ if args.lenient_rdkit:
266
+ print(f"[WARN] {message}: {', '.join(canonical_diffs)}")
267
+ else:
268
+ print(f"[FAIL] {message}: {', '.join(canonical_diffs)}")
269
+ failures.extend(canonical_diffs)
270
+
271
+ return 1 if failures else 0
272
+
273
+
274
+ if __name__ == "__main__":
275
+ sys.exit(main())
split_A_full_msnlib/formula_split.csv ADDED
The diff for this file is too large to render. See raw diff
 
split_A_full_msnlib/formula_split.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d52d77139c06d8662972fa638981894cf9f88fb3a5da1e1b73017b939d19fd4a
3
+ size 86748
split_A_full_msnlib/msnlib_rt.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:994053612db874f7ac7985f278e04cc3463f3b93cd649a195bd167c4c6c7d3d8
3
+ size 1483069
split_A_full_msnlib/row_formula_fold.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac6113867fdda683304533f097fc7287c13271a2deac8e792d1316dcf00264ff
3
+ size 13351630
split_A_full_msnlib/row_formula_fold.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:86150a89fb601a117d43c995065c3abc95ab0710cb80ffe47dfa5413aa57e686
3
+ size 1248826
split_A_full_msnlib/test_molecules_voting.csv ADDED
The diff for this file is too large to render. See raw diff
 
split_A_full_msnlib/test_molecules_voting.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:72ae163ce88b15d89fb1d556fbb8a698d001dd1e923df11399df13dfddec3db2
3
+ size 72880