Skip to content

[PERFORMANCE] Direct FLASH MS1 work to precursor hypotheses - #10533

Merged
poshul merged 3 commits into
developfrom
feature/nase-directed-ms1
Oct 15, 2026
Merged

poshul merged 3 commits into
developfrom
feature/nase-directed-ms1

Conversation

@poshul

@poshul poshul commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

NASE batches selected ions by parent MS1 and restricts FLASH envelope construction to their hypotheses and competing explanations. Complete parent peaks remain available for isotope recruitment, SNR, noise, harmonics and global mass-bin competition; queries receive no targeting exemption. The selected confident zero-only isotope policy and signed-charge convention from #10532 are unchanged.

The generic C++/pyOpenMS API now uses setQueryMasses(std::vector<std::pair<double,int>>) followed by the existing three-argument deconvolution call. Queries are non-protecting and consumed at call entry, including rejected non-MS1 and empty-spectrum calls. Nonfinite/nonpositive m/z values are rejected. Empty queries use ordinary FLASH. Sorted parents retain the direct path; unsorted parents are sorted in a temporary copy without rearranging the original experiment or arrays.

Candidate construction uses one serial loop for both full and directed runs. The directed-only parallel loop and /256 worker heuristic are removed. Scoring uses the same configured OpenMP workers for both modes. Competition still uses the union of the batch's query and evidence intervals; the overlap regressions do not establish universal invariance across arbitrary subsets. Callers requiring identical context must use the same batch or ordinary full-MS1 deconvolution.

A new benchmark of this revision compares full/directed FLASH with caller-side PeakPickerHiRes centroiding and NLargest 500/1000 filtering. It uses three warmups and 20 repetitions, one OpenMP thread, RNA averagine, 10 ppm tolerance, cosine 0.85, SNR 0.25, max mass 8800.181396484375 Da, and charge ranges 1–20 (reduced fixtures) or 1–5 (synthetic). Full/directed order alternates. Alternative timings include spectrum transformation and deconvolution; initialization, averagine and result checks are excluded.

Input Full ms Directed ms Centroid + full ms Top 500 + full ms Top 1000 + full ms
competition_1_rejected_query 3.314 1.466 0.531 1.849 3.029
competition_2_mono_query 8.884 2.597 3.289 5.150 6.997
synthetic_RNA_isotope_1_query 0.409 0.465 0.026 0.446 0.446

Directed/full queried decisions, candidate fields and complete queried-envelope fingerprints are exact in all repetitions. Centroiding preserves the rejected first fixture but loses the accepted monoisotope in the second fixture, and loses the synthetic envelope. Top-500/1000 filtering preserves the second fixture's monoisotopic status but changes its confidence fields and envelope evidence. Filtering is therefore not an exact substitute in these examples. These are only two reduced parents and one synthetic envelope; no universal speed-up or full-search throughput claim follows. The synthetic directed case remains slower than full FLASH. Raw settings, scripts, timings and binary hashes are preserved with the review artifacts.

Validation of this follow-up: 11 focused C++/TOPP tests passed, all four relevant class tests passed with 32 OpenMP threads, and 115 Python FLASH cases plus direct unittest execution passed. New class regressions cover query consumption after successful, rejected and empty calls, plus invalid m/z rejection. Scoped Doxygen 1.18 validation of the changed public header produced no warnings; full-project documentation was not rerun. The earlier Windows portability fix is retained, and the preceding head's Windows/macOS/Linux CI is green; CI for this follow-up must rerun.

Stacked on #10532 and inherits the shared FLASH normalization/cosine fix merged in #10543. Earlier full-suite validation and frozen historical lab comparisons are preserved; neither constitutes repeated validation of this follow-up.

Summary by CodeRabbit

  • New Features
    • Added precursor-guided spectral deconvolution using full-spectrum evidence while preserving the original spectrum.
    • RNA precursor correction now evaluates selected ions together against their shared parent MS1 spectrum, supporting multiple queries, unsorted spectra, and cases where the monoisotope is missing.
    • Correction reports now include parent-scan peak counts and the number of distinct precursor queries.
  • Documentation
    • Clarified how parent MS1 spectra and isotope shifts are handled during RNA precursor correction.

@timosachsenberg timosachsenberg left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed d95b21c7df6f against #10532. One [P3] helper-contract question, with a reproduced behavior change, remains.

At RNAPrecursorCorrector.cpp:180, the parent is now passed directly to FLASH. #10532 first copied it and called sortByPosition(). With the same synthetic isotope envelope, reversing only the interior peaks changes the result:

sorted=1 status=corrected isotope=1 corrected_mz=1253.18
sorted=0 status=no_envelope isotope=-1 corrected_mz=1253.68

The normal NASE mzML loader sorts peaks by default, so this reproduction does not establish a failure of that normal CLI path. It concerns direct use of the helper, whose documented input only specifies acquisition order for spectra.

@poshul, is sorted m/z order an intended precondition of RNAPrecursorCorrector::correct? If it is, documenting/enforcing it would resolve the contract question; if unsorted helper input should remain supported, the removed sorting needs preserving. Please confirm whether this merits a fix or is outside the supported contract.

Focused helper reproducer

Compile with this branch's NASE helper implementation and headers:

#include "RNAPrecursorCorrector.h"
#include <OpenMS/CHEMISTRY/NASequence.h>
#include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <algorithm>
#include <iostream>

using namespace OpenMS;

int main()
{
  MSSpectrum parent;
  parent.setMSLevel(1);
  parent.setNativeID("scan=1");
  const auto formula = NASequence::fromString("ACGUACGU").getFormula();
  const auto isotopes = formula.getIsotopeDistribution(CoarseIsotopePatternGenerator(8));
  for (Size i = 0; i < isotopes.size(); ++i)
  {
    parent.emplace_back((formula.getMonoWeight() + i * Constants::C13C12_MASSDIFF_U) / 2 - Constants::PROTON_MASS_U,
                        isotopes[i].getIntensity() * 10000);
  }
  MSSpectrum child;
  child.setMSLevel(2);
  child.setNativeID("scan=2");
  Precursor precursor;
  precursor.setMZ(parent[1].getMZ());
  precursor.setCharge(2);
  child.getPrecursors().push_back(precursor);
  for (bool sorted : {true, false})
  {
    MSSpectrum input = parent;
    if (!sorted) std::reverse(input.begin() + 1, input.end() - 1);
    MSExperiment experiment;
    experiment.setSpectra({input, child});
    RNAPrecursorCorrector corrector(10, 1, 5, false, 8000);
    const auto result = corrector.correct(experiment)[0];
    std::cout << "sorted=" << sorted << " status=" << result.status << " isotope=" << result.isotope
              << " corrected_mz=" << result.corrected_mz << '\n';
  }
}

Validation: the changed corrector and SpectralDeconvolution implementation were compiled for this focused test against existing supporting OpenMS build libraries. The complete FLASH/NASE test matrix was not rerun. Earlier-layer MVH/bedRMod concerns remain tracked on #10526/#10529.

Review performed with Codex.

@poshul

poshul commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed in 1a92d49. Sorted parents keep the direct path; an unsorted parent is sorted in a temporary copy, preserving the original scan and arrays. The existing NASE class test compares all correction fields and corrected MS2 output against the sorted case in both ionization modes. Local validation: 11 C++/TOPP tests and 115 Python FLASH cases pass.

@coderabbitai

coderabbitai Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 058fc3d3-54cf-43fa-9af7-68ee8b6d4dbc
📥 Commits

Reviewing files that changed from the base of the PR and between 562e12e and 4b3578e.

📒 Files selected for processing (8)
  • src/openms/include/OpenMS/ANALYSIS/TOPDOWN/SpectralDeconvolution.h
  • src/openms/source/ANALYSIS/TOPDOWN/SpectralDeconvolution.cpp
  • src/pyOpenMS/bindings/bind_misc.cpp
  • src/pyOpenMS/tests/unittests/test_FLASHDeconv.py
  • src/topp/NucleicAcidSearchEngine/NucleicAcidSearchEngine.cpp
  • src/topp/NucleicAcidSearchEngine/include/RNAPrecursorCorrector.h
  • src/topp/NucleicAcidSearchEngine/source/RNAPrecursorCorrector.cpp
  • src/topp/NucleicAcidSearchEngine/test/NASEDigestion_test.cpp

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review.

📝 Walkthrough

FLASH deconvolution now accepts precursor queries for MS1 spectra. RNA precursor correction batches queries by parent MS1, deconvolves each parent once, and records parent peak and query counts.

Changes: Precursor-directed FLASH and RNA correction

Layer / File(s) Summary
Precursor API and candidate selection
src/openms/include/OpenMS/ANALYSIS/TOPDOWN/SpectralDeconvolution.h, src/openms/source/ANALYSIS/TOPDOWN/SpectralDeconvolution.cpp, src/pyOpenMS/bindings/bind_misc.cpp, src/pyOpenMS/tests/unittests/test_FLASHDeconv.py, src/tests/class_tests/openms/source/SpectralDeconvolution_test.cpp
The API accepts precursor queries. Nonempty queries on non-MS1 spectra raise IllegalArgument. For queried MS1 spectra, FLASH restricts candidate bins around precursor mass intervals, then expands them using matched observed-peak evidence. The Python binding and tests cover the overload and query behavior.
Directed recruitment and scoring
src/openms/include/OpenMS/ANALYSIS/TOPDOWN/SpectralDeconvolution.h, src/openms/source/ANALYSIS/TOPDOWN/SpectralDeconvolution.cpp
Directed mass-bin processing uses independent peak lookup and restores groups to mass-bin order. Scoring and harmonic removal use the selected worker count.
Parent-MS1 batching and correction
src/topp/NucleicAcidSearchEngine/include/RNAPrecursorCorrector.h, src/topp/NucleicAcidSearchEngine/source/RNAPrecursorCorrector.cpp, src/topp/NucleicAcidSearchEngine/NucleicAcidSearchEngine.cpp
The corrector deduplicates queries by m/z and charge, deconvolves each parent MS1 once, and assigns results to the associated inputs. Results and reports include parent peak and query counts. Observation-match metadata propagates these counts when present.
Batch correction validation
src/topp/NucleicAcidSearchEngine/test/NASEDigestion_test.cpp, src/tests/class_tests/openms/data/RNAPrecursorCorrector_competition.mzML
Tests compare sorted and unsorted parent scans, shared queries, charge interpretations, and envelope competition. The mzML fixture contains two parent MS1 spectra and two linked MS2 queries.

Sequence Diagram(s)

sequenceDiagram
  participant MS2Inputs
  participant RNAPrecursorCorrector
  participant ParentMS1
  participant SpectralDeconvolution
  MS2Inputs->>RNAPrecursorCorrector: collect precursor queries by parent
  RNAPrecursorCorrector->>ParentMS1: retrieve parent spectrum
  RNAPrecursorCorrector->>SpectralDeconvolution: deconvolve parent with distinct queries
  SpectralDeconvolution->>RNAPrecursorCorrector: return peak groups
  RNAPrecursorCorrector->>RNAPrecursorCorrector: match queries and assign corrections
Loading

Suggested reviewers: timosachsenberg

Priority: ➖ Normal

Change: Refactor

Merge Risk: ⚪ Minimal · up to 4b357

This change speeds up FLASH precursor correction in the nucleic acid search by batching queries per parent MS1 scan. Existing calls keep their prior behavior. The supplied evidence shows no actionable merge-blocking risk.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 24 functions across 9 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed Issue #10534 is closed and supplies historical context only. No active directly linked issue supplies coding requirements for this pull request. The reported NASE and FLASH changes therefore have no l…
Out of Scope Changes check Passed The changes stay within the precursor-directed NASE and FLASH scope. They add query batching, directed deconvolution, result retention, metadata, bindings, and related tests and fixtures. The changed …
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: directing FLASH MS1 processing toward precursor hypotheses for performance.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

A rabbit watched the spectra shine,
And sorted peaks in neat design.
By parent scan, the queries meet,
While FLASH finds groups in order neat.
The rabbit hops; the counts align.

Comment @coderabbitai help to get the list of available commands.

@poshul
poshul force-pushed the feature/nase-directed-ms1 branch from 2b67f60 to b0ba101 Compare October 12, 2026 13:04

@timosachsenberg timosachsenberg left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Placement review. Restricting construction inside SpectralDeconvolution is a defensible layer: cropping the MS1 in the caller would lose SNR and competition evidence. Existing three-argument callers and FLASHDeconv look unaffected: the cursor write-back is equivalent and the parallel region is if(directed). My concerns are about the API shape and the evidence for the speed-up:

  1. API: a query setter mirroring setTargetMasses() would fit better than a fourth-argument overload that takes an unused PeakGroup and ignores queries for MS2 (inline).
  2. Reproducibility: the directed result for one scan depends on which other MS2 scans share its parent. That is worth a co-batching equivalence test (inline).
  3. Benchmark: the 2.44× figure is historical and unpaired. The comment about profile samples creating "millions of duplicate bands" suggests profile MS1 is the real cost. Centroiding the MS1 (PeakPickerHiRes), or reusing FLASH's own peak filtering in the caller, might give a similar gain with no new library API. A paired benchmark on this branch against that alternative would settle whether the directed path is worth its complexity.
  4. Separable improvement: removing the omp critical from scoring benefits every FLASH user and could go in on its own.

Smaller items: a redundant audit counter, seed groups built and scored twice, and a Python test placed after the __main__ guard (inline).

Suggested split: (a) the scoring omp critical removal on its own; (b) the directed restriction, with a neutral API, a co-batching test and a paired benchmark, merged only if it beats caller-side peak reduction.


Generated by Claude Code

Comment on lines +65 to +79
/** @brief Restrict MS1 envelope construction to precursor hypotheses and their competitors.

The complete spectrum remains available for isotope recruitment, noise,
and harmonic checks. Candidate mass bin selection retains its global
intensity competition. An empty list uses ordinary untargeted FLASH.
Unlike setTargetMasses(), this does not prioritize or protect hypotheses.
@param[in] spec Complete parent MS1 spectrum.
@param[in] scan_number Scan number from the input spectrum.
@param[in] precursor_peak_group Precursor peak group (unused for MS1).
@param[in] precursors Selected ions sharing this parent MS1; charge zero
considers every configured charge. Reported charges are interpreted by magnitude.
*/
void performSpectrumDeconvolution(const MSSpectrum& spec, int scan_number,
const PeakGroup& precursor_peak_group,
const std::vector<Precursor>& precursors);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Restricting inside the library is defensible: the caller can't crop the MS1 without losing SNR, noise and other-charge evidence. The API shape doesn't fit the generic class, though:

  • Unused and ignored arguments: it takes Precursor objects plus a precursor_peak_group that is documented as unused for MS1, and the queries are silently ignored for MS2.
  • A second entry point: it adds an overload of the main entry point instead of a mode.

A neutral setter mirroring the existing setTargetMasses() would fit better. Something like setQueryMasses(std::vector<std::pair<double,int>> mz_charge) or mass windows, cleared after each call, plus a documented "non-protecting" semantics. Then performSpectrumDeconvolution keeps one signature, and the pyOpenMS docstring ("Deconvolve RNA envelopes…") doesn't describe a generic class as RNA-specific.


Generated by Claude Code

Comment on lines +1161 to +1165
int SpectralDeconvolution::getThreadCount_(Size group_count, bool directed)
{
#ifdef _OPENMP
const int maximum = omp_get_max_threads();
return directed ? std::min(maximum, std::max(1, int(group_count / 256))) : maximum;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Directed mode now has its own parallel construction path and a /256 team-size heuristic, while untargeted mode stays serial. If the parallel path is equivalent (it looks deterministic, since output is packed in bin order), either enable it for everyone or drop it. Two code paths through the core loop are harder to maintain. The 256 constant has no test or benchmark behind it.

Removing the omp critical from scoring is a general FLASH improvement and could go in on its own.


Generated by Claude Code

@timosachsenberg timosachsenberg left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review at 3ef97b9, which has the same content as 9497528 after the rebase. The rest of the stack (#10529 → #10532) is approved. This PR still has open items:

  1. Windows CI is red in the new competition test (inline). The fixture is borderline at the quality cutoff, so it needs an unambiguous envelope rather than a changed expectation.
  2. The two earlier threads are still open with no reply:
    • The API shape: a 4-argument overload of the generic entry point that takes Precursor objects plus a PeakGroup it never uses. A query setter mirroring setTargetMasses() would fit the class better. Throwing on non-empty MS2 queries is an improvement, but the shape remains.
    • The directed-only parallel construction path, with an untested /256 team-size rule. The omp critical removal in scoring benefits every FLASH user and could still go in separately.
  3. Evidence for the speed-up: the paired microbenchmark shows 2.3–3.4× on the two reduced fixtures and is slower on the synthetic case. It still doesn't compare against centroiding the parent MS1 (or FLASH's own peak filtering in the caller), which might give the gain without a new library API. That comparison would settle whether the directed path is worth its complexity.

Improvements since the first review:

  • the co-batching equivalence test and its documentation;
  • removal of the redundant input_peaks counter;
  • the Python test now runs before the __main__ guard and uses a real envelope.

Generated by Claude Code

@poshul
poshul force-pushed the feature/nase-directed-ms1 branch 3 times, most recently from 32d1499 to f9ae3dc Compare October 14, 2026 12:13
Base automatically changed from feature/nase-flash-ms1 to develop October 14, 2026 12:13
@poshul
poshul force-pushed the feature/nase-directed-ms1 branch from f9ae3dc to 738cd25 Compare October 14, 2026 12:13

@timosachsenberg timosachsenberg left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me. It adds quite some complexity. Maybe talk to the top-down guys if your modification would better fit in a subdirectory of your tool. Note that it is now possible to have include and source subfolders for top tools where you can put more specialized code. Take, for example, a look at openNuXL, where I demonstrate how this is done

@poshul
poshul merged commit e0b7731 into develop Oct 15, 2026
32 checks passed
@poshul
poshul deleted the feature/nase-directed-ms1 branch October 15, 2026 07:04
timosachsenberg pushed a commit that referenced this pull request Oct 15, 2026
… names, #10584 CHANGELOG)

Only the CHANGELOG conflicted: develop consolidated its entries (#10584),
this branch keeps its own next to them. NucleicAcidSearchEngine copies the
two new FLASH precursor annotations (flash_precursor_parent_peaks,
flash_precursor_parent_queries) to the matches of the owning model, as it
does the others; the new NASEDigestion tests cover RNAPrecursorCorrector
only and need no port.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01B51nRFoHvZuVXD7cT8XZav
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants