Skip to content

feat(ProSE): database chunking for large FASTA inputs - #9177

Merged
timosachsenberg merged 7 commits into
developfrom
feat/prose-database-chunking
Apr 17, 2026
Merged

timosachsenberg merged 7 commits into
developfrom
feat/prose-database-chunking

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR started as a database-chunking feature for ProSE and grew to include three tightly-coupled correctness / quality fixes that surfaced while benchmarking ProSE vs. Sage on the HeLa DDA-PASEF fixture.

Changes

1. -Search:database:chunk_size — memory-bounded search for very large FASTAs

When chunk_size > 0 and the database exceeds that size, the DB is split into fixed-size chunks and each chunk's FragmentIndex is built and freed in turn:

  1. Build full decoy-augmented DB once (FASTA only — no FI).
  2. Preprocess spectra once.
  3. For each chunk: build FI, score all spectra, append hits, free FI.
  4. After all chunks: single postProcessHits_ + PeptideIndexing (against full DB for correct cross-chunk protein mappings) + PSM-level FDR.

Memory: only one chunk's FI in memory at a time. For a 100M-peptide MHC-II variant DB with chunk_size=5000 proteins, each chunk's FI is ~500 MB instead of ~50 GB.
Speed: N scoring passes (one per chunk), linear slowdown in chunk count.
Multi-file mode (-in a.mzML b.mzML) uses chunk-major ordering: build chunk's FI once, score ALL files against it before moving on — C FI builds instead of N×C.
Default chunk_size = 0: existing single-context path, zero overhead.

2. Sage DDA test uses -deisotope true

Flipping this single flag lifts Sage's timsTOF PSM yield from 3,756 → 3,918 at 1% FDR (+4.3%). ProSE already deisotopes internally in preprocessSpectra_, so the flag brings Sage onto comparable preprocessing ground.

3. Bug fixes in Percolator feature annotations

  • precursor_mz_error_ppm in postProcessHits_ now subtracts out the isotope offset FragmentIndex matched at. Previously a ±1 Da FI match reported ~1000 ppm / charge for this feature — corrupted target/decoy discrimination for ~24% of PSMs (fixture had 989 iso_err=+1 and 806 iso_err=-1 out of 7,514 PSMs).
  • fragment_mz_error_median_ppm now computed by a SpectrumAlignment with the actual fragment tolerance (20 ppm in ppm mode) rather than the default 0.3 Da banded DP — 30× looser than the search, pulling in spurious far-off matches that inflated the median fed to Percolator.
  • Same sign-correction applied consistently in runCalibrationPass_ so both code paths agree.

4. Precursor calibration: empirical-quantile formula (NuXL autotune style)

Previous formula precursor_spread = res_median + 3·res_MAD captures only ~94% coverage on Gaussians (≈1.88σ, not the intended 3σ) and less on heavy tails. Replaced with 0.5% / 99.5% empirical quantiles on the signed-error distribution (same approach as OpenNuXL.cpp:4939-4941). Distribution-free — captures 99% regardless of shape.

Calibration subset is now restricted to iso_err=0 PSMs — the gold-standard "monoisotopic peak picked correctly" population — so the quantile estimate isn't contaminated by the extra variance of +1/+2 isotope-peak ambiguity.

PSM yields at 1% FDR — HeLa DDA-PASEF fixture

Configuration Before PR After PR Δ
no calibration, no Percolator 4,373 4,373 0
calibration (HyperScore+FDR) 4,537 4,681 +144
Percolator, no calibration 4,770 4,770 0
calibration + Percolator 5,036 5,090 +54

Reference: Sage with -deisotope true: 3,918 PSMs. ProSE with cal + Percolator: +1,172 PSMs (+30%).

Test plan

  • TOPP_ProSE_5_chunked — chunked output bit-equivalent to non-chunked on small fixture
  • TOPP_FalseDiscoveryRate_ProSEDDA_calibrated_psm_count — floor 4,650
  • TOPP_FalseDiscoveryRate_ProSEDDA_psm_count — floor 4,350
  • TOPP_FalseDiscoveryRate_SimpleSearchEngineDDA_psm_count — floor 4,170
  • ProSEAlgorithm_test calibration assertions updated for quantile semantics
  • Reference ProSE_{1,2,4}_out.idXML regenerated (fewer spurious fragment annotations due to 20 ppm alignment)
  • fragment_annotation whitelisted in diff tests (ARM/x86 float-precision sensitivity at the 20 ppm boundary)

Follow-ups (separate PRs)

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

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
📝 Walkthrough

Walkthrough

Adds optional database chunking to ProSEAlgorithm plus a protected helper to score spectra against a FragmentIndex; when enabled, spectra are preprocessed once, the FASTA is iterated in protein chunks with per-chunk FragmentIndex construction and scoring, and per-spectrum hits are merged and post-processed against the full database.

Changes

Cohort / File(s) Summary
Header
src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h
Added forward declaration class TheoreticalSpectrumGenerator;, new protected helper scoreSpectraAgainstIndex_(...), and new member Size database_chunk_size_{0}; (0 = disabled; >0 = chunk DB).
Core implementation
src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp
Added database:chunk_size parameter and chunked-search flow: build decoy-augmented FASTA once, preprocess spectra once, iterate protein chunks building per-chunk FragmentIndex, score all spectra per chunk via scoreSpectraAgainstIndex_, prune per-spectrum hits after each chunk, then run unified postProcessHits_, PeptideIndexing on the full DB and PSM/protein-level FDR. Non-chunked path reuses existing SearchContext. Multi-file search adjusted to respect chunking.
Tests / CTest
src/tests/topp/CMakeLists.txt
Added CTest entries TOPP_ProSE_5_chunked and TOPP_ProSE_5_chunked_out to run ProSE with -Search:database:chunk_size 5 and fuzzy-diff the output against the baseline (whitelisting date and DB field).

Sequence Diagram

sequenceDiagram
    participant User as User
    participant ProSE as ProSEAlgorithm
    participant DB as Database
    participant Spectra as Spectra
    participant FIndex as FragmentIndex
    participant Results as Results

    User->>ProSE: search(PeakMap, FASTA, ...)
    alt chunked mode (database_chunk_size_ > 0 && DB large)
        ProSE->>DB: build decoy-augmented FASTA (once)
        ProSE->>Spectra: preprocess spectra (once)
        loop for each protein chunk
            ProSE->>FIndex: build index for chunk
            ProSE->>Spectra: score all spectra against chunk (scoreSpectraAgainstIndex_)
            Spectra-->>Results: append AnnotatedHit_ results
            ProSE->>FIndex: release index
            ProSE->>Results: prune per-spectrum hits to top-N
        end
        ProSE->>Results: postProcessHits_(accumulated)
        ProSE->>DB: PeptideIndexing against full DB
        ProSE->>Results: apply PSM & protein-level FDR
    else non-chunked mode
        ProSE->>FIndex: build full DB index
        ProSE->>Spectra: score spectra
        ProSE->>Results: postProcessHits_ and indexing
    end
    Results-->>User: return identifications
Loading

Possibly related PRs

Suggested reviewers

  • jpfeuffer

Poem

🐰 I nibble through proteins, five by five,
Chunked and careful, the search comes alive.
Spectra prepped once, indexes spun per part,
Hits stitched together, a tidy work of art.
Hooray — results hop home, clever and smart! 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 62.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main feature: adding database chunking to ProSE for handling large FASTA inputs, which is the primary objective of this changeset.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/prose-database-chunking

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

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

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp (1)

1419-1445: ⚠️ Potential issue | 🟠 Major

Multi-file entry point silently ignores database:chunk_size.

searchWithModificationAnalysis(const std::vector<String>&, const std::vector<FASTAFile::FASTAEntry>&, ...) builds a single SearchContext via prepareContext(fasta_db) and dispatches to the SearchContext& overload for every file. That path never consults database_chunk_size_, so the prepareContext call will build the full FragmentIndex and OOM on exactly the inputs this PR is targeting (100M-peptide MHC-II DBs). Users who set -Search:database:chunk_size on a multi-file run will be surprised when they still hit the memory ceiling.

Either:

  • Add a chunk-aware multi-file path that loops files × chunks (build chunk FI once, score every file against it, accumulate per-file hits), which preserves the "build index once, score many files" benefit, or
  • Short-circuit: if database_chunk_size_ > 0 && fasta_db.size() > database_chunk_size_, fall back to per-file search(spectra, fasta_db, ...) calls inside the file loop here, trading the shared-index speedup for the memory cap.

At minimum, log a clear warning when chunk_size is set but ignored in this path, and document the limitation on the parameter description (see comment on lines 214–220).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp` around lines 1419 - 1445,
The multi-file entry path uses prepareContext(fasta_db) to build a full
SearchContext and never respects database_chunk_size_, causing OOM for large
FASTA; modify searchWithModificationAnalysis(const std::vector<String>&, const
std::vector<FASTAFile::FASTAEntry>&, ...) so it checks database_chunk_size_ and
fasta_db.size() before calling prepareContext: if chunking is enabled and
fasta_db.size() > database_chunk_size_, either implement a chunk-aware loop
(build FragmentIndex/SearchContext per chunk and reuse it to score all spectra
files, accumulating per-file SearchResult) or fall back to calling the per-file
search overload search(spectra, fasta_db, ...) for each file; at minimum add an
OPENMS_LOG_WARN when chunking is set but ignored and update the parameter
documentation for database_chunk_size_ to note this multi-file limitation.
🧹 Nitpick comments (3)
src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp (3)

752-755: Drop redundant "Warning:" prefix.

OPENMS_LOG_WARN already tags the stream; prefixing the message with Warning: double-labels it. Minor, but inconsistent with other warnings in this file.

Proposed fix
-      OPENMS_LOG_WARN << "Warning: calibration is skipped in chunked database mode." << std::endl;
+      OPENMS_LOG_WARN << "[ProSE] Calibration is skipped in chunked database mode." << std::endl;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp` around lines 752 - 755,
Remove the redundant "Warning:" prefix from the log message emitted when
calibration_enabled_ is true: in the ProSEAlgorithm code path that calls
OPENMS_LOG_WARN, change the message string to not include "Warning:" so it reads
something like "calibration is skipped in chunked database mode." to match other
warnings; keep the OPENMS_LOG_WARN stream usage and newline handling unchanged.

827-875: Scoring loop body is duplicated verbatim with the context-taking overload.

Lines 835–874 are essentially identical to lines 1101–1145 in the other search() overload (same querySpectrum → HyperScore → AnnotatedHit_ construction, same open-search delta-mass arithmetic). Any fix to scoring or annotation will need to be applied in both places. Consider extracting a helper such as scoreSpectraAgainstIndex_(spectra, fragment_index, db, annotated_hits, /*open_search*/, /*effective_frag_tol*/) and calling it from both paths.

Not urgent, but the current duplication is what made issues #2/#3 (missing diagnostics, FDR divergence) easy to miss.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp` around lines 827 - 875, The
scoring/annotation loop in the two search() overloads is duplicated
(querySpectrum → HyperScore::computeWithDetail → AnnotatedHit_ construction and
open-search delta mass logic); extract that block into a single helper (e.g.,
scoreSpectraAgainstIndex_ or processSpectrumMatches_) that accepts the
FragmentIndex reference (chunk_fi), spectra list, SpectrumGenerator
(spectrum_generator), chunk_db, annotated_hits container, open_search_mode flag,
effective_fragment_tol/fragment_mass_tolerance_unit_ppm, proton_mass_u, and any
thread-synchronization needs; replace the duplicated bodies in both search()
overloads by calling this helper (ensure the OpenMP
parallelization/synchronization is preserved—either keep the pragma in the
helper or have the callers handle parallel loops and call a thread-safe
per-spectrum helper), and move the HyperScore::computeWithDetail, AnnotatedHit_
population, and delta_mass calculation (ah.sequence.getMZ(1) / exp_mz /
exp_mh_plus arithmetic) into that helper so future changes apply in one place.

757-777: Decoy augmentation is a verbatim copy of prepareContext; also missing braces.

Lines 760–777 duplicate the decoy logic from prepareContext() (lines 683–709). Any future fix (e.g., handling non-standard residues, alternative decoy strategies) will have to be made in two places and will silently drift. Additionally, per the repo's brace guideline, the single-line if/else bodies here need braces (the copy in prepareContext already uses them).

Suggested extraction (sketch)
// In class (private):
static void appendShuffledDecoys_(std::vector<FASTAFile::FASTAEntry>& db,
                                  EnzymaticDigestion::Specificity spec,
                                  const String& enzyme,
                                  const String& decoy_prefix);

// Then both prepareContext() and the chunked path call:
if (decoys_) {
  appendShuffledDecoys_(full_db, peptide_enzyme_specificity_, enzyme_, decoy_prefix_);
}

Minimum fix if you'd rather not refactor now — at least add the braces:

-        if (peptide_enzyme_specificity_ == EnzymaticDigestion::SPEC_NONE)
-          e.sequence = decoy_generator.reverseProtein(AASequence::fromString(e.sequence)).toString();
-        else
-          e.sequence = decoy_generator.reversePeptides(AASequence::fromString(e.sequence), enzyme_).toString();
+        if (peptide_enzyme_specificity_ == EnzymaticDigestion::SPEC_NONE)
+        {
+          e.sequence = decoy_generator.reverseProtein(AASequence::fromString(e.sequence)).toString();
+        }
+        else
+        {
+          e.sequence = decoy_generator.reversePeptides(AASequence::fromString(e.sequence), enzyme_).toString();
+        }

As per coding guidelines: "Always use braces for code blocks in C++, even for single-line blocks (unless trivial one-liners)".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp` around lines 757 - 777,
This block duplicates decoy-generation logic from prepareContext() and also uses
single-line if/else bodies without braces; extract the shared logic into a
single private helper (e.g., static void
appendShuffledDecoys_(std::vector<FASTAFile::FASTAEntry>& db,
EnzymaticDigestion::Specificity spec, const String& enzyme, const String&
decoy_prefix)) that encapsulates creating decoy entries (using
DecoyGenerator::reverseProtein / reversePeptides, setting identifier to
decoy_prefix_ + identifier, and shuffling via
Math::RandomShuffler::portable_random_shuffle) and call it from both
prepareContext() and this location when decoys_ is true, or at minimum add
braces around the if/else bodies here and mirror the exact logic from
prepareContext() to avoid drift; refer to symbols decoys_,
peptide_enzyme_specificity_, enzyme_, decoy_prefix_, FASTAFile::FASTAEntry,
DecoyGenerator, reverseProtein, reversePeptides, and Math::RandomShuffler to
locate code.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp`:
- Around line 882-899: The chunked-search branch fails to set the sentinel
member last_mod_match_tolerance_used_, causing downstream
OpenSearchModificationAnalysis::analyzeModificationsWithStatistics(...) to
receive a stale or -1.0 tolerance; fix this by assigning
last_mod_match_tolerance_used_ = computeModMatchTolerance_(); in the chunked
path inside searchWithModificationAnalysis (after calibration is skipped and
before calling postProcessHits_), mirroring the explicit set performed in the
context-taking overload so the correct mod-match tolerance is always propagated.
- Around line 214-220: The parameter documentation for "database:chunk_size"
must warn about its limitation with multi-file runs: update the description
passed to defaults_.setValue (the string for "database:chunk_size") to
explicitly state that chunking is not honored by the multi-file entry point
searchWithModificationAnalysis(...) and that enabling chunking will not prevent
full-DB loading in multi-file mode; alternatively, implement wiring so
searchWithModificationAnalysis(...) respects the chunk_size setting (ensure the
chunk_size value from defaults_ is read and propagated into the logic that
splits databases in searchWithModificationAnalysis or its helper functions) and
add a note in the defaults_.setValue string if full support is not feasible
immediately.
- Around line 952-953: The chunked-mode overload in ProSEAlgorithm.cpp returns
before emitting the final diagnostics; add a call to
logSearchDiagnostics_(spectra, protein_ids, peptide_ids) just before the return
in the chunked return path so chunked-mode runs produce the same search-summary
/ tolerance-estimation output as the non-chunked overload; locate the early
return in the ProSEAlgorithm chunked processing function and insert the
logSearchDiagnostics_ call using the existing spectra, protein_ids, and
peptide_ids variables.
- Around line 925-950: The chunked path applies protein-level FDR inline
(FalseDiscoveryRate::applyPickedProteinFDR on protein_ids) and sets
FalseDiscoveryRate param "algorithm:add_decoy_peptides" whereas the non-chunked
search(...) path does not, causing divergent results; fix by making behavior
identical: remove the inline protein FDR and decoy-peptide param mutation from
the chunked branch (the block that uses BasicProteinInferenceAlgorithm bpia,
FalseDiscoveryRate fdr; fdr.applyPickedProteinFDR(...);
IDFilter::filterHitsByScore(...); IDFilter::removeDecoyHits(...); etc.) and
instead invoke the same protein-level FDR and any
fdr_param.setValue("algorithm:add_decoy_peptides","true") from the file-wrapper
/ caller that already handles the non-chunked path (or, if you prefer the other
option, set the same fdr parameters and defer picked-protein FDR in the
non-chunked search overload so both code paths call the same FalseDiscoveryRate
logic), ensuring the symbols BasicProteinInferenceAlgorithm,
FalseDiscoveryRate::setParameters/getParameters, applyPickedProteinFDR,
IDFilter::filterHitsByScore, and IDFilter::removeDecoyHits are used consistently
in only one caller-managed location.

---

Outside diff comments:
In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp`:
- Around line 1419-1445: The multi-file entry path uses prepareContext(fasta_db)
to build a full SearchContext and never respects database_chunk_size_, causing
OOM for large FASTA; modify searchWithModificationAnalysis(const
std::vector<String>&, const std::vector<FASTAFile::FASTAEntry>&, ...) so it
checks database_chunk_size_ and fasta_db.size() before calling prepareContext:
if chunking is enabled and fasta_db.size() > database_chunk_size_, either
implement a chunk-aware loop (build FragmentIndex/SearchContext per chunk and
reuse it to score all spectra files, accumulating per-file SearchResult) or fall
back to calling the per-file search overload search(spectra, fasta_db, ...) for
each file; at minimum add an OPENMS_LOG_WARN when chunking is set but ignored
and update the parameter documentation for database_chunk_size_ to note this
multi-file limitation.

---

Nitpick comments:
In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp`:
- Around line 752-755: Remove the redundant "Warning:" prefix from the log
message emitted when calibration_enabled_ is true: in the ProSEAlgorithm code
path that calls OPENMS_LOG_WARN, change the message string to not include
"Warning:" so it reads something like "calibration is skipped in chunked
database mode." to match other warnings; keep the OPENMS_LOG_WARN stream usage
and newline handling unchanged.
- Around line 827-875: The scoring/annotation loop in the two search() overloads
is duplicated (querySpectrum → HyperScore::computeWithDetail → AnnotatedHit_
construction and open-search delta mass logic); extract that block into a single
helper (e.g., scoreSpectraAgainstIndex_ or processSpectrumMatches_) that accepts
the FragmentIndex reference (chunk_fi), spectra list, SpectrumGenerator
(spectrum_generator), chunk_db, annotated_hits container, open_search_mode flag,
effective_fragment_tol/fragment_mass_tolerance_unit_ppm, proton_mass_u, and any
thread-synchronization needs; replace the duplicated bodies in both search()
overloads by calling this helper (ensure the OpenMP
parallelization/synchronization is preserved—either keep the pragma in the
helper or have the callers handle parallel loops and call a thread-safe
per-spectrum helper), and move the HyperScore::computeWithDetail, AnnotatedHit_
population, and delta_mass calculation (ah.sequence.getMZ(1) / exp_mz /
exp_mh_plus arithmetic) into that helper so future changes apply in one place.
- Around line 757-777: This block duplicates decoy-generation logic from
prepareContext() and also uses single-line if/else bodies without braces;
extract the shared logic into a single private helper (e.g., static void
appendShuffledDecoys_(std::vector<FASTAFile::FASTAEntry>& db,
EnzymaticDigestion::Specificity spec, const String& enzyme, const String&
decoy_prefix)) that encapsulates creating decoy entries (using
DecoyGenerator::reverseProtein / reversePeptides, setting identifier to
decoy_prefix_ + identifier, and shuffling via
Math::RandomShuffler::portable_random_shuffle) and call it from both
prepareContext() and this location when decoys_ is true, or at minimum add
braces around the if/else bodies here and mirror the exact logic from
prepareContext() to avoid drift; refer to symbols decoys_,
peptide_enzyme_specificity_, enzyme_, decoy_prefix_, FASTAFile::FASTAEntry,
DecoyGenerator, reverseProtein, reversePeptides, and Math::RandomShuffler to
locate code.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f61b696b-e3af-42a2-bfa1-0c01ba011406

📥 Commits

Reviewing files that changed from the base of the PR and between 3a6ad57 and 874cca4.

📒 Files selected for processing (2)
  • src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h
  • src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp

@timosachsenberg
timosachsenberg force-pushed the feat/prose-database-chunking branch from 874cca4 to 59c2c51 Compare April 17, 2026 12:35

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

♻️ Duplicate comments (3)
src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp (3)

951-953: ⚠️ Potential issue | 🟡 Minor

Missing logSearchDiagnostics_(...) before the chunked return.

The non-chunked overload ends with logSearchDiagnostics_(spectra, protein_ids, peptide_ids); at line 1271 to emit the ID-rate / tolerance-estimation summary. This chunked return path skips it, so users in chunked mode lose that block. Same as flagged previously.

+    logSearchDiagnostics_(spectra, protein_ids, peptide_ids);
     return ExitCodes::EXECUTION_OK;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp` around lines 951 - 953, The
chunked return path in ProSEAlgorithm::execute currently returns
ExitCodes::EXECUTION_OK without calling logSearchDiagnostics_, so emit the same
diagnostics as the non-chunked path by calling logSearchDiagnostics_(spectra,
protein_ids, peptide_ids) just before the chunked return; locate the early
return in the chunked-mode branch in ProSEAlgorithm::execute and insert the call
to logSearchDiagnostics_ with the existing variables spectra, protein_ids,
peptide_ids to ensure the ID-rate/tolerance summary is logged for chunked runs.

882-899: ⚠️ Potential issue | 🟠 Major

last_mod_match_tolerance_used_ still not set in the chunked branch — downstream OSMA will use a stale/sentinel value.

This is the same concern flagged previously and still holds against the current code: searchWithModificationAnalysis(PeakMap&, fasta_db, ...) at line 1345 delegates to search(spectra, fasta_db, ...), which in chunked mode returns via line 952 without touching last_mod_match_tolerance_used_. Then line 1369 reads that member into analyzeModificationsWithStatistics(...). On a fresh instance this is -1.0; on a reused instance it's whatever the previous non-chunked run left behind.

Mirror the explicit assignment from the context-taking overload (line 1062) just before postProcessHits_ runs, e.g.:

+    // No calibration in chunked mode, but downstream OSMA reads this member.
+    last_mod_match_tolerance_used_ = computeModMatchTolerance_();
+
     startProgress(0, 1, "Post-processing PSMs...");
     postProcessHits_(spectra,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp` around lines 882 - 899, The
chunked-search path in search(spectra, ...) fails to set the member
last_mod_match_tolerance_used_, causing analyzeModificationsWithStatistics(...)
later to read a stale sentinel; fix by assigning last_mod_match_tolerance_used_
just before the postProcessHits_ call in the chunked-return branch the same way
the context-taking overload does (mirror the explicit assignment around line
1062), so that postProcessHits_(...) and subsequent
analyzeModificationsWithStatistics(...) see the correct tolerance; update the
code in the chunked branch inside searchWithModificationAnalysis/search to set
last_mod_match_tolerance_used_ to the computed tolerance value.

925-950: ⚠️ Potential issue | 🟠 Major

FDR behavior still diverges from the non-chunked path — toggling chunk_size silently changes results.

Same concern as the prior review round, still present:

  • The non-chunked search(PeakMap&, SearchContext&, ...) overload applies only PSM-FDR (lines 1249–1262) and defers protein-level FDR to the caller (the file wrapper at 1311–1324, which exists only for the single-file entry point; the multi-file aggregate explicitly does not apply it — see comment at 1563–1567). This chunked path, in contrast, runs BasicProteinInferenceAlgorithm + applyPickedProteinFDR + decoy removal inline (lines 942–949).
  • Line 933 sets algorithm:add_decoy_peptides=true for PSM FDR, which changes the q-value computation itself. The non-chunked path at lines 1249–1253 uses defaults.

Net effect: flipping database:chunk_size from 0 to >0 on the same input silently produces a different PSM table and different protein inference behavior. In particular, the multi-file searchWithModificationAnalysis(...) wrapper will gain per-file protein FDR only in chunked mode — users running the same DB with and without chunking will not get comparable outputs.

Please align the two paths (preferred: hoist the protein-FDR block out of here into the caller, matching the existing layering; alternatively: mirror add_decoy_peptides=true and per-file protein FDR in the non-chunked path).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp` around lines 925 - 950, The
chunked search path applies protein-level FDR and sets
"algorithm:add_decoy_peptides" for PSM FDR inline, causing different results
versus the non-chunked overload; move the protein-FDR and decoy-removal steps
out of the chunked block so behavior matches the single-file path: remove the
BasicProteinInferenceAlgorithm run,
FalseDiscoveryRate::applyPickedProteinFDR(...) call, and the
IDFilter::removeDecoyHits/removeEmptyIdentifications/removeUnreferencedProteins
invocations from the chunked branch in ProSEAlgorithm (where decoy_prefix_,
fdr_protein_, fdr_psm_ are checked) and instead invoke protein-level inference
and picked-protein FDR at the same caller/wrapper that handles the non-chunked
search, or alternatively make the non-chunked path mirror the chunked settings
by setting "algorithm:add_decoy_peptides" before fdr.apply(peptide_ids) and
performing per-file protein FDR there so both paths produce identical PSM and
protein behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp`:
- Around line 747-777: The info log and decoy-augmentation are inconsistent and
duplicated: move the database-decoy augmentation into a new private helper (e.g.
augmentWithDecoys_(std::vector<FASTAFile::FASTAEntry>& entries)) that implements
the same logic used in prepareContext() (respecting peptide_enzyme_specificity_,
enzyme_, decoy_prefix_, Math::RandomShuffler, etc.), call that helper to produce
full_db from fasta_db when decoys_ is true, and then log chunk counts using
full_db.size() (and compute chunk count from full_db) instead of
fasta_db.size(); while extracting, ensure you restore braces around the if/else
arms to match coding guidelines.

---

Duplicate comments:
In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp`:
- Around line 951-953: The chunked return path in ProSEAlgorithm::execute
currently returns ExitCodes::EXECUTION_OK without calling logSearchDiagnostics_,
so emit the same diagnostics as the non-chunked path by calling
logSearchDiagnostics_(spectra, protein_ids, peptide_ids) just before the chunked
return; locate the early return in the chunked-mode branch in
ProSEAlgorithm::execute and insert the call to logSearchDiagnostics_ with the
existing variables spectra, protein_ids, peptide_ids to ensure the
ID-rate/tolerance summary is logged for chunked runs.
- Around line 882-899: The chunked-search path in search(spectra, ...) fails to
set the member last_mod_match_tolerance_used_, causing
analyzeModificationsWithStatistics(...) later to read a stale sentinel; fix by
assigning last_mod_match_tolerance_used_ just before the postProcessHits_ call
in the chunked-return branch the same way the context-taking overload does
(mirror the explicit assignment around line 1062), so that postProcessHits_(...)
and subsequent analyzeModificationsWithStatistics(...) see the correct
tolerance; update the code in the chunked branch inside
searchWithModificationAnalysis/search to set last_mod_match_tolerance_used_ to
the computed tolerance value.
- Around line 925-950: The chunked search path applies protein-level FDR and
sets "algorithm:add_decoy_peptides" for PSM FDR inline, causing different
results versus the non-chunked overload; move the protein-FDR and decoy-removal
steps out of the chunked block so behavior matches the single-file path: remove
the BasicProteinInferenceAlgorithm run,
FalseDiscoveryRate::applyPickedProteinFDR(...) call, and the
IDFilter::removeDecoyHits/removeEmptyIdentifications/removeUnreferencedProteins
invocations from the chunked branch in ProSEAlgorithm (where decoy_prefix_,
fdr_protein_, fdr_psm_ are checked) and instead invoke protein-level inference
and picked-protein FDR at the same caller/wrapper that handles the non-chunked
search, or alternatively make the non-chunked path mirror the chunked settings
by setting "algorithm:add_decoy_peptides" before fdr.apply(peptide_ids) and
performing per-file protein FDR there so both paths produce identical PSM and
protein behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ee58d7de-9534-4102-abfb-57f1ff2060ff

📥 Commits

Reviewing files that changed from the base of the PR and between 874cca4 and 59c2c51.

📒 Files selected for processing (3)
  • src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h
  • src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp
  • src/tests/topp/CMakeLists.txt
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h

@timosachsenberg
timosachsenberg force-pushed the feat/prose-database-chunking branch from 59c2c51 to a68296b Compare April 17, 2026 12:52

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp`:
- Around line 930-947: When fdr_psm_ > 0 but no decoys are present the chunked
path currently silently skips PSM FDR; add the same warning the non-chunked path
emits by checking has_decoys (computed from full_db and decoy_prefix_) and if
false call OPENMS_LOG_WARN with a message that FDR:PSM was requested but no
decoys/external decoy file were found so PSM FDR was skipped; place this check
just before the existing if (fdr_psm_ > 0.0 && has_decoys) block (i.e. when
fdr_psm_>0 and !has_decoys) so peptide_ids / FalseDiscoveryRate usage is
unchanged.
- Around line 800-877: The per-spectrum accumulator annotated_hits grows
unbounded across chunks; after finishing scoring a chunk (inside the chunk loop,
after the parallel for completes) trim each annotated_hits[scan_index] to at
most report_top_hits_ using the same pattern as postProcessHits_ — perform a
partial_sort on annotated_hits[i].begin()/begin()+report_top_hits_ by score and
then resize to report_top_hits_; this keeps memory bounded to N_spectra ×
report_top_hits_ while preserving the top candidates before the next chunk.
Ensure to reference AnnotatedHit_.score, annotated_hits, report_top_hits_, and
reuse the partial_sort + resize approach used in postProcessHits_.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b0b1ba83-648d-4df0-8877-d0db5d4407c8

📥 Commits

Reviewing files that changed from the base of the PR and between 59c2c51 and a68296b.

📒 Files selected for processing (3)
  • src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h
  • src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp
  • src/tests/topp/CMakeLists.txt
✅ Files skipped from review due to trivial changes (1)
  • src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/tests/topp/CMakeLists.txt

@timosachsenberg
timosachsenberg force-pushed the feat/prose-database-chunking branch 7 times, most recently from 0043fd0 to 0a09eb2 Compare April 17, 2026 15:21
timosachsenberg and others added 2 commits April 17, 2026 19:02
Add -Search:database:chunk_size <int> parameter (default 0 = disabled).
When set, the protein database is split into chunks of that many
proteins; each chunk builds its own FragmentIndex, all spectra are
scored against each chunk, and hits are accumulated across chunks
before a single postProcessHits + PeptideIndexing + FDR pass.

Trades speed (N scoring passes over spectra) for memory (only one
chunk's FragmentIndex in memory at a time). Designed for MHC-II
immunopeptidomics and other non-specific/variant-heavy searches
where the full fragment index exceeds available memory.

Implementation:
- Full decoy-augmented DB built once upfront (FASTA entries only,
  no FragmentIndex — cheap).
- Spectra preprocessed once.
- Per-chunk: slice DB → build FI → score all spectra → append hits.
- After all chunks: postProcessHits_ (sort, annotate, delta score),
  PeptideIndexing against full DB (correct cross-chunk mappings),
  PSM-level FDR, protein-level picked-protein FDR.
- Calibration skipped in chunked mode (logged as warning if enabled).
- Default 0 preserves existing single-context behavior exactly.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Raises the timsTOF DDA-PASEF PSM yield at 1% FDR from 3756 to 3918
(+4.3%) at no runtime cost. Sage's other tuning flags (chimera,
predict_rt) are inert on this fixture because SageAdapter hardcodes
report_psms=1, so only the top-1 PSM per scan is surfaced.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@timosachsenberg
timosachsenberg force-pushed the feat/prose-database-chunking branch from 0a09eb2 to 3d98847 Compare April 17, 2026 17:14
timosachsenberg and others added 2 commits April 17, 2026 20:34
…ical quantiles

Three related fixes to Percolator-bound features and precursor calibration
uncovered while comparing ProSE vs Sage yield on the DDA_HeLa fixture.

1. precursor_mz_error_ppm annotation now subtracts the isotope offset FI
   matched at. Without this, a ±1 Da match reports ~1000 ppm / charge for
   the Percolator feature — corrupts target/decoy discrimination.

2. The SpectrumAlignment used for fragment_mz_error_median_ppm and ion-
   annotation features now runs at the actual fragment tolerance (20 ppm
   ppm-mode MatchedIterator) instead of the default 0.3 Da banded DP —
   ~30× looser than the search, pulled in spurious far-off matches and
   inflated the median error fed to Percolator.

3. runCalibrationPass_: replaced res_median + 3*res_MAD with 0.5%/99.5%
   empirical quantiles on signed precursor errors (same style as NuXL
   autotune, OpenNuXL.cpp:4939). Distribution-free — captures 99% of the
   error distribution by construction, not ~94% as the MAD formula did
   on Gaussians and less on heavy tails.

HeLa DDA-PASEF, 1% FDR, Percolator on:
  baseline (no cal):              4770 (was 4770)
  calibration + Percolator:       5036 (was 4711, +6.9%)
  calibration alone (HyperScore): 4471 (was 4537, -1.5%)

The calibrated HyperScore yield is down 66 PSMs because the quantile
window is ~2x wider than the old MAD window — fewer decoys are filtered
at the tails, which marginally hurts the raw hyperscore+FDR ranking.
Percolator prefers the wider window because the tail PSMs are now
represented in its training data; net +325 PSMs over the MAD path when
Percolator is enabled.

Floor for TOPP_FalseDiscoveryRate_ProSEDDA_calibrated_psm_count dropped
from 4510 to 4450 accordingly. Reference idXMLs for ProSE_{1,2,4}_out
regenerated — fragment_annotation lists now contain only matches within
the actual fragment tolerance.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…otation diff

CI surfaced two follow-ups to the previous calibration commit:

1. Quantile calibration on small or biased distributions: strict
   inequality (hi <= 0 || lo >= 0) flagged legitimate single-sided
   distributions as "extreme" even when they had a usable spread. When
   the fixture on ARM yields only ~4 PSMs with strictly-positive signed
   errors, the calibration was discarded and the test fixture broke.
   Relaxed to flag extreme only when the distribution is degenerate
   (hi - lo < min_tolerance) — one-sided distributions now produce a
   valid half-line window (cal_upper clamped to min_tolerance).
   Also restored the precursor_shift assignment lost in the refactor.

2. fragment_annotation is a long exact-match string on the idXML diff
   tests. With the 20 ppm SpectrumAlignment the fixture landed a b-ion
   exactly on the tolerance boundary — ARM's IEEE-754 rounding
   included it where x86 excluded it. Whitelisted "fragment_annotation"
   in ProSE_{1,2,4,5_chunked,3_multi_idXML}_out so the diffs no longer
   flag this string; the meaningful scalar features (precursor error,
   matched ions, HyperScore, delta) still get diffed.

Also updated ProSEAlgorithm_test to drop MAD-formula-specific assertions
(cal_lower == spread + shift / cal_upper == spread - shift) that no
longer hold under the quantile formula. Invariant checks (cal_lower >
cal_upper for positive bias, tightening vs user bounds) are preserved.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
timosachsenberg and others added 3 commits April 17, 2026 21:23
…leanup

1. runCalibrationPass_ was using obs - iso_err*C13C12/charge to compute
   the isotope-corrected precursor error, while postProcessHits_ was fixed
   in the previous commit to use obs + iso_err*C13C12/charge (the correct
   sign — FragmentIndex stores shifted_mass = precursor_mass + iso_err *
   C13C12, so the monoiso correction adds). The two code paths now agree.

   In practice the bug was latent because the calibration subset (top-scoring
   PSMs) is dominated by iso_err=0, where both signs produce 0. But any
   fixture that exercises iso_err != 0 in top hits would have skewed the
   quantile bounds by ~1000 ppm / charge for those PSMs.

   Side effect on the DDA_HeLa fixture: corrected iso_err ±1 PSMs now have
   small errors instead of huge ones, so they pass the wrong-match filter
   and join the calibration subset. The slightly-different window gives
   4433 PSMs at 1% FDR (was 4471) — floor updated from 4450 to 4410.

2. Updated stale docs:
   - database:chunk_size param description no longer claims "Calibration
     is skipped in chunked mode" (it runs, using the first chunk).
   - Removed the stale "discard the precursor calibration" comment that
     described the pre-relaxation extreme_bias condition.
   - Raised extreme_bias threshold from 1e-6 to 1 ppm (the previous value
     could never fire on realistic input — calibration spreads are never
     less than ~0.01 ppm in practice).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Follow-up to the previous sign-fix commit. With the sign corrected,
iso_err=±1 PSMs now have small isotope-adjusted errors and pass the
wrong-match filter, so they joined the calibration subset — adding
extra variance from the inherent uncertainty of +1/+2 isotope-peak
picking. This noisier distribution made the 0.5%/99.5% quantile window
wider, which hurt the downstream target/decoy competition (−230 PSMs
at 1% FDR in cal+Percolator, 5036 → 4806).

Restrict the calibration subset to iso_err=0 PSMs — the gold-standard
"monoisotopic peak picked correctly" population — so bias and spread
are estimated from the cleanest possible target population. This was
previously happening accidentally via the sign bug (which gave iso±1
PSMs ~1000 ppm errors that the wrong-match filter excluded). Now it's
explicit.

Yields on DDA_HeLa (HeLa timsTOF DDA-PASEF fixture, 1% FDR):
  cal alone (HyperScore+FDR): 4537 → 4681  (+144 vs pre-PR baseline)
  cal + Percolator:           5036 → 5090  (+54 vs pre-PR baseline)

Floor for TOPP_FalseDiscoveryRate_ProSEDDA_calibrated_psm_count raised
4410 → 4650 accordingly.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…path

MSVC /WX promoted "C4189: local variable initialized but not referenced"
to an error on the windows-2025 CI build. The unused variable was a
leftover from the chunk-major refactor — per-file calibrated fragment
tolerances are stored in per_file_cal[i].effective_fragment_tol now.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@timosachsenberg
timosachsenberg merged commit bc7bd9e into develop Apr 17, 2026
15 checks passed
@timosachsenberg
timosachsenberg deleted the feat/prose-database-chunking branch April 17, 2026 21:21
github-actions Bot pushed a commit that referenced this pull request Apr 18, 2026
Add missing entries for commits since the 2026-04-17 sync:
- CometAdapter #9168: Bruker native-ID rewrite covers mzML inputs too
- ProSE #9166: new -out_pin parameter for Percolator input file output
- ProSE #9167: fix ions:add_* parameters honored in scoring path
- ProSE #9175: BREAKING rename matched_b/y_ions → matched_prefix/suffix_ions; delta_score and matched_ion_current added; HyperScore ETD/EThcD fix
- ProSE #9177: database chunking (-Search:database:chunk_size); Percolator feature and calibration fixes

Co-authored-by: Copilot <[email protected]>
timosachsenberg pushed a commit that referenced this pull request Apr 18, 2026
Add missing entries for commits since the 2026-04-17 sync:
- CometAdapter #9168: Bruker native-ID rewrite covers mzML inputs too
- ProSE #9166: new -out_pin parameter for Percolator input file output
- ProSE #9167: fix ions:add_* parameters honored in scoring path
- ProSE #9175: BREAKING rename matched_b/y_ions → matched_prefix/suffix_ions; delta_score and matched_ion_current added; HyperScore ETD/EThcD fix
- ProSE #9177: database chunking (-Search:database:chunk_size); Percolator feature and calibration fixes

Co-authored-by: GitHub Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
github-actions Bot pushed a commit that referenced this pull request Apr 19, 2026
Add missing entries for commits since the 2026-04-18 sync:
- Constants #9181: new MEAN_INVERSE_REDUCED_ION_MOBILITY_ARRAY constant
  (CV MS:1003006) + IMDataConverter::getIMUnit extended to cover all
  three IM array name prefixes
- ProSE #9185: calibration in chunked search now uses a strided sample
  across the full DB; asymmetric calibrated precursor bounds correctly
  preserved through chunked/multi-file paths; corrects stale 'calibration
  is skipped in chunked mode' text in the #9177 chunking entry

Co-authored-by: Copilot <[email protected]>
timosachsenberg pushed a commit that referenced this pull request Apr 19, 2026
Add missing entries for commits since the 2026-04-18 sync:
- Constants #9181: new MEAN_INVERSE_REDUCED_ION_MOBILITY_ARRAY constant
  (CV MS:1003006) + IMDataConverter::getIMUnit extended to cover all
  three IM array name prefixes
- ProSE #9185: calibration in chunked search now uses a strided sample
  across the full DB; asymmetric calibrated precursor bounds correctly
  preserved through chunked/multi-file paths; corrects stale 'calibration
  is skipped in chunked mode' text in the #9177 chunking entry

Co-authored-by: GitHub Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
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.

1 participant