From Mass Spectrometry Peaks to Molecular Structure: An Engineering Path to Higher Accuracy
This article explains why inferring molecular structures from mass spectrometry peak lists is a difficult inverse problem and how an engineering pipeline can raise structure identification accuracy from below 4% to 97%. It covers structured spectrum representation, hard chemical constraints, tool-based computation, retrieval augmentation, and verifiable candidate output, along with evaluation design, production architecture, and common pitfalls. The intended takeaway is a reusable pattern for making large language models more reliable in specialized scientific computing tasks.
1. The Core Problem: Why Inferring Structures from Peaks Is So Hard
Mass spectrometry (MS) analysis aims to infer molecular formulas and connectivity from a peak list composed of m/z (mass-to-charge ratio) values and relative abundances. This is a typical underdetermined inverse problem: the same set of peaks can be explained by multiple candidate structures, and peak intensities are affected by ionization method, collision energy, and matrix effects. Noise and isotope distributions further amplify the ambiguity.
Under closed conditions with no network access and no additional skills, a comparative test on several general-purpose large models showed that three mainstream general models achieved less than 4% accuracy in structure identification from peak lists. This result is not surprising. It exposes three capability gaps:
- Representation gap: the model sees a sequence of numbers rather than the physical constraints of mass, elements, and bonding.
- Knowledge gap: fragmentation rules, isotope abundances, and common neutral losses are domain priors that are sparsely covered in general corpora.
- Verification gap: generative decoding only optimizes whether an answer “looks right” and lacks a closed loop that performs forward verification on candidate structures.
2. Four Key Abstractions Behind the Jump from 4% to 97%
2.1 Representation: Turning Numbers into Computable Constraints
Structure the peak list and attach the precursor ion, adduct form, charge, resolution, and error tolerance (for example, ±5 ppm). Inject elemental masses, isotope abundances, and a table of common adduct masses as explicit context. Example structure:
{"spectrum": {"peaks": [[118.086, 100.0], [133.089, 42.0]], "tolerance_ppm": 5},"precursor": {"adduct": "[M+H]+", "charge": 1},"candidate_formula": ["C5H12N2O", "C6H14NO"]}
2.2 Knowledge Constraints: Encoding Chemical Priors as Hard Rules
Encode the nitrogen rule, a non-negative and reasonable ring plus double bond equivalent (RDBE), isotope peak spacing and abundance ratios, and common neutral losses (such as 18, 28, and 44) as executable validators. Any candidate that violates a hard constraint is eliminated immediately, compressing the search space from combinatorial explosion to an enumerable level.
2.3 Tool Orchestration: Making the Model Compute Instead of Guess
Wrap exact mass calculation, isotope simulation, and fragment tree generation behind a common tool interface (a function-calling or plugin mechanism). The model is responsible only for proposing hypotheses and selecting tools, while numerical results come from deterministic programs. Pseudocode:
def solve(peaks, adduct, tol_ppm=5):formulas = enumerate_formulas(peaks, adduct, tol_ppm) # mass matchingformulas = [f for f in formulas if hard_rules(f)] # hard chemical constraintsscored = []for f in formulas:sim = simulate_isotopes(f) # tool computationscore = match_score(peaks, sim, tol_ppm)scored.append((score, f))return sorted(scored, reverse=True)[:5] # return candidates, not a single verdict
2.4 Retrieval Augmentation and Verifiable Decoding
Use vector retrieval over similar spectra and fragmentation pathways from the literature to provide empirical evidence for candidates. In the decoding stage, replace free generation with candidate scoring plus forward verification: each candidate must pass a similarity threshold between the simulated spectrum and the measured spectrum; otherwise, resampling is triggered. The output changes from a piece of natural language to a candidate set with evidence.
3. Evaluation Design: Making Conclusions Reproducible
- Stratified sampling: bucket samples by compound class, adduct type, and resolution to prevent averages from hiding weaknesses.
- Two-tier evaluation: compare a closed tier (no network, no tools) with an augmented tier (knowledge base plus tools) to quantify the sources of improvement.
- Metric combination: Top-1/Top-5 accuracy, candidate coverage, average number of candidates, verification pass rate, and latency.
- Ablation studies: remove hard constraints, tools, and retrieval one by one to observe accuracy decay and identify key factors.
- Leakage prevention: deduplicate spectra between training and evaluation to avoid memorization-driven high scores.
4. Engineering Implementation: An Enterprise-Grade Pipeline
- Data layer: store raw spectra and metadata in object storage, and index features and candidates in a database.
- Compute layer: use a container platform to host tool services (mass calculation, isotope simulation, and fragment prediction), with a message queue to smooth traffic peaks.
- Orchestration layer: combine model services with a tool registry, and provide unified authentication, rate limiting, and timeouts.
- Observability: use a logging service to record every candidate and verification trace, and use monitoring and alerting to track accuracy and latency drift.
- Human-in-the-loop: route low-confidence samples to manual review, and feed review results back into the retrieval library and evaluation set.
5. Common Pitfalls and How to Avoid Them
- Overfitting to a single ionization method: augmented evaluation should cover multiple matrices and multiple energy settings.
- Overly strict hard rules: distinguish hard constraints (physically impossible) from soft preferences (lower probability).
- Providing answers without evidence: require candidates, scores, and verification conclusions in the output.
- Ignoring error tolerance: set the ppm window dynamically according to resolution.
6. Conclusion
The gap from 4% to 97% is not fundamentally about a “smarter model.” It comes from connecting chemical priors, deterministic computation, and a verifiable closed loop into the inference chain. For developers, the reusable pattern is structured representation, hard-constraint validation, tool-based computation, retrieval augmentation, and candidate-based verifiable output, continuously calibrated through stratified evaluation and ablation studies. Using general capabilities such as object storage, container platforms, message queues, and monitoring and alerting on Baidu AI Cloud, this pipeline can be built quickly, helping large models move from “being able to talk” to “being trustworthy” in specialized scientific computing scenarios.
