Skip to content

fix(ProSE): asymmetric calibration bounds + strided cal subset for chunked search - #9185

Merged
timosachsenberg merged 2 commits into
developfrom
fix/prose-chunked-calibration
Apr 18, 2026
Merged

timosachsenberg merged 2 commits into
developfrom
fix/prose-chunked-calibration

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Apr 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Follow-up to PR #9177. Fixes two chunked-calibration bugs discovered during post-merge validation:

Both fixes are in the chunked paths only (searchChunked_ and the chunk-major multi-file branch of searchWithModificationAnalysis). The non-chunked search(spectra, ctx, ...) path is unchanged — it was already correct on both fronts.

PSM yields (HeLa DDA-PASEF, 1% FDR)

Configuration Non-chunked chunked (chunk=500, before) chunked (chunk=500, after)
no calibration 4,373 4,373 4,373
calibration (HyperScore+FDR) 4,681 4,373 (silently skipped) 4,438
calibration + Percolator 5,090 4,806 4,951

Strict improvement in the chunked paths; non-chunked yields are unchanged.

Test plan

  • TOPP_ProSE_DDA_chunked_calibrated — new test, runs ProSE with chunk_size=500 -calibration:enabled on DDA_HeLa.d and verifies PSMs at 1% FDR ≥ 4,400. Would have tripped on ProSE chunked calibration: first-chunk-only subset can be too small to meet min_psms #9182 (calibration silently skipped → 4,373 = uncalibrated baseline) before the fix.
  • Existing TOPP_ProSE_5_chunked (no-cal chunked equivalence) — still green.
  • Existing non-chunked calibration tests — unchanged.

Residual gap (follow-up: #9184)

Chunked calibration leaves a ~2% yield gap vs non-chunked. Traced to calibration PSM pool size: strided 5,000-protein sample produces ~100 PSMs vs ~276 for full-DB calibration. PROSE_CAL_SAMPLE=full A/B test confirms that once the PSM pool is large enough, chunked matches non-chunked exactly (5,090 / 4,681) — the fixes in this PR are necessary and sufficient given adequate cal PSMs.

Closing the remaining gap needs pooling cal PSMs across the first-K main-search chunks (no extra memory cost, small time cost). Tracked in #9184.

Related issues

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Configurable database chunking (Search:database:chunk_size) to run chunk-major searches and limit memory growth.
  • Improvements

    • Decoy-augmented FASTA handling, strided calibration sampling, and asymmetric empirical tolerance estimation.
    • Centralized scoring, per-spectrum hit accumulation/pruning, improved fragment alignment, isotope-corrected precursor-error reporting, and deduplication of peak counts.
  • Tests

    • Added/updated regression tests and expected outputs for chunked and calibrated search modes; adjusted test thresholds and outputs.

@coderabbitai

coderabbitai Bot commented Apr 18, 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

Added configurable database chunking and related protected helpers to ProSEAlgorithm: forward-declared TheoreticalSpectrumGenerator, decoy-augmented FASTA builder, strided calibration sampling, chunk-major search that builds per-chunk FragmentIndex instances and accumulates/prunes per-spectrum hits, centralized spectrum-vs-fragment-index scoring, database_chunk_size_ member, and calibration/annotation adjustments.

Changes

Cohort / File(s) Summary
Header Declarations
src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h
Forward-declared TheoreticalSpectrumGenerator; added protected helpers buildDecoyAugmentedDB_, buildCalibrationSample_, searchChunked_, scoreSpectraAgainstIndex_ and new member database_chunk_size_.
Core Algorithm Implementation
src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp
Added Search:database:chunk_size parameter and implemented chunk-major search: decoy-augmented DB builder, strided calibration sampling, per-chunk FragmentIndex construction, centralized scoring helper, per-spectrum hit accumulation/pruning, isotope-corrected precursor-error annotation, and quantile-based asymmetric calibration bounds; wired chunked path into multi-file flow.
Unit Tests
src/tests/class_tests/openms/source/ProSEAlgorithm_test.cpp
Relaxed calibration test assertions to match new signed-error convention (removed numeric endpoint equality checks).
TOPP Tests & Config
src/tests/topp/CMakeLists.txt
Expanded FuzzyDiff whitelist for fragment_annotation, added chunked regression tests and chunked+calibrated checks with updated PSM thresholds, and toggled SageAdapter DDA -deisotope flag.
Expected Outputs / Fixtures
src/tests/topp/ProSE_1_out.idXML, src/tests/topp/ProSE_2_out.idXML, src/tests/topp/ProSE_4_out.idXML
Updated SearchParameters DB paths and search_engine_version; adjusted PeptideHit numeric fields and fragment_annotation content/order to reflect new scoring/calibration outputs.
TOPP Fixture Additions
src/tests/topp/ProSE_5_chunked* (new)
New regression tests exercising -Search:database:chunk_size (chunked mode) and comparing against existing reference outputs.

Sequence Diagram(s)

sequenceDiagram
    participant Spectra
    participant ProSE as ProSEAlgorithm
    participant FullDB as Full_FASTA_DB
    participant Chunk as DB_Chunk_i
    participant FI as FragmentIndex
    participant Hits as Accumulated_Hits

    rect rgba(135, 206, 235, 0.5)
    Note over ProSE,FullDB: Initialization
    ProSE->>FullDB: load full DB
    ProSE->>FullDB: buildDecoyAugmentedDB_()
    FullDB-->>ProSE: decoy-augmented DB
    end

    rect rgba(144, 238, 144, 0.5)
    Note over ProSE,FI: Calibration Sampling
    ProSE->>FullDB: buildCalibrationSample_() (strided)
    FullDB-->>ProSE: calibration sample
    ProSE->>FI: build FI on sample
    ProSE->>Spectra: scoreSpectraAgainstIndex_() → cal hits
    ProSE->>ProSE: runCalibrationPass_() → cal_lower, cal_upper
    end

    rect rgba(255, 182, 193, 0.5)
    Note over Chunk,Hits: Chunk-major Search
    loop for each chunk i
      ProSE->>Chunk: extract chunk i
      Chunk->>FI: build FragmentIndex (apply cal_lower/cal_upper)
      ProSE->>Spectra: scoreSpectraAgainstIndex_() vs FI
      FI-->>ProSE: hits per spectrum
      ProSE->>Hits: accumulate & prune per-spectrum top-N
    end
    end

    rect rgba(255, 215, 0, 0.5)
    Note over ProSE,Hits: Post-processing
    ProSE->>Hits: postProcessHits_, PeptideIndexing, FDR
    Hits-->>ProSE: final annotated PSMs
    end
Loading

Possibly related issues

Possibly related PRs

Suggested reviewers

  • jpfeuffer
  • cbielow

Poem

🐰 I hop through chunks and calibrate with glee,

Strided samples fetch PSMs for me,
Asymmetric bounds now travel true,
Spectra meet indexes, hits accrue,
My tiny paws keep memory light and free.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 61.54% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main changes: asymmetric calibration bounds and strided calibration subset for chunked search, matching the core fixes in the changeset.
Linked Issues check ✅ Passed All objectives from #9180 and #9182 are met: asymmetric cal_lower/cal_upper are threaded separately to FragmentIndex, buildCalibrationSample_ creates a strided sample across the full database, and searchChunked_ uses chunked search with proper calibration.
Out of Scope Changes check ✅ Passed All changes are within scope: header additions for new helper methods, implementation of chunked/calibration fixes, annotation refinements (MIC dedup, precursor-error PPM correction), and test updates validating the new behavior.

✏️ 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 fix/prose-chunked-calibration

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: 2

Caution

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

⚠️ Outside diff range comments (1)
src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h (1)

418-433: ⚠️ Potential issue | 🟠 Major

Thread lower and upper precursor tolerances through post-processing.

postProcessHits_ still accepts only a single precursor_mass_tolerance parameter (line 426). Every call site collapses the asymmetric bounds via std::max(precursor_mass_tolerance_lower_, precursor_mass_tolerance_upper_) before passing (see lines 1086, 1304, 1781 in the cpp file). This reintroduces the precision loss this PR aims to fix.

Update the method signature to accept separate bounds:

-      double precursor_mass_tolerance,
+      double precursor_mass_tolerance_lower,
+      double precursor_mass_tolerance_upper,
       double fragment_mass_tolerance,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h` around lines 418 -
433, The postProcessHits_ declaration currently takes a single
precursor_mass_tolerance which collapses asymmetric tolerances and loses
precision; change the signature of ProSEAlgorithm::postProcessHits_ to accept
two separate precursor tolerance parameters (precursor_mass_tolerance_lower and
precursor_mass_tolerance_upper, same type as the existing
precursor_mass_tolerance) and update every call site that passed
std::max(precursor_mass_tolerance_lower_, precursor_mass_tolerance_upper_) to
pass the two new parameters instead; ensure the function body and any internal
uses of the single precursor_mass_tolerance are adapted to use the appropriate
lower/upper values (function name: postProcessHits_, update all callers that
previously passed the max value).
🧹 Nitpick comments (3)
src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h (1)

359-392: Use full Doxygen blocks for the new header helpers.

These new header declarations use plain /// prose. Please convert them to the project’s @brief Doxygen format for generated API docs.

Example format to apply to the new helper declarations
-    /// Build a decoy-augmented copy of the input FASTA (no FragmentIndex).
-    /// Used by prepareContext() and the chunked search path.
+    /**
+     * `@brief` Build a decoy-augmented copy of the input FASTA.
+     *
+     * Used by prepareContext() and the chunked search path without building a
+     * FragmentIndex.
+     */
     std::vector<FASTAFile::FASTAEntry> buildDecoyAugmentedDB_(
         const std::vector<FASTAFile::FASTAEntry>& fasta_db) const;

As per coding guidelines, Use @brief plus blank line plus detailed description in Doxygen comments; required @brief tag.

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

In `@src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h` around lines 359 -
392, Replace the plain "///" prose comments for the new helper declarations with
full Doxygen blocks that use an `@brief` tag followed by a blank line and then the
detailed description; update the comments for buildDecoyAugmentedDB_,
buildCalibrationSample_, searchChunked_, and scoreSpectraAgainstIndex_ to follow
the project's pattern (/** `@brief` ... [blank line] detailed explanation... */)
so generated API docs include the brief and the longer description.
src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp (2)

1746-1748: Dead restore: chunk_fi goes out of scope at the next loop iteration.

chunk_fi is declared inside the chunk loop (line 1718) and re-created each iteration, so resetting its params just before the iteration ends has no observable effect on the next chunk. This can be dropped; the inner per-file block at 1732–1738 already writes fresh params from base_fi_params every time before scoring.

♻️ Proposed fix
-        // Restore base FI params for next chunk (in case calibration modified them).
-        if (calibration_enabled_ && !open_search_mode)
-          chunk_fi.setParameters(base_fi_params);
-
         // Per-chunk pruning for each file.
🤖 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 1746 - 1748,
The final restore of parameters on chunk_fi is dead code because chunk_fi is
recreated each loop iteration; remove the redundant lines that reset
chunk_fi.setParameters(base_fi_params) guarded by calibration_enabled_ &&
!open_search_mode. Instead, rely on the existing per-file initialization that
sets base_fi_params into the new chunk_fi (see the block around the inner
per-file/1732–1738 and the chunk_fi declaration near line 1718); delete the
restore to avoid misleading/no-op code.

1078-1094: Nit: prefer the effective_precursor_tol_* locals over re-reading mutated members.

Line 1086 uses std::max(precursor_mass_tolerance_lower_, precursor_mass_tolerance_upper_), which works only because lines 984–985 also mutate the (mutable) members to the calibration values. The function already tracks the correct post-calibration values in effective_precursor_tol_lower/_upper, and the sibling multi-file chunk-major path at lines 1785–1786 uses exactly that idiom. Using the locals here would decouple the call from the member-mutation side effect and match the intent of the PR's asymmetric-bound threading.

♻️ Proposed fix
-      std::max(precursor_mass_tolerance_lower_, precursor_mass_tolerance_upper_),
+      std::max(effective_precursor_tol_lower, effective_precursor_tol_upper),
       effective_fragment_tol,
🤖 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 1078 - 1094,
The call to postProcessHits_ uses std::max(precursor_mass_tolerance_lower_,
precursor_mass_tolerance_upper_) which relies on mutated member variables;
replace that with the already-computed locals effective_precursor_tol_lower and
effective_precursor_tol_upper so the post-calibration bounds are used explicitly
(i.e. pass std::max(effective_precursor_tol_lower,
effective_precursor_tol_upper) instead of using
precursor_mass_tolerance_lower_/upper_); update the invocation site of
postProcessHits_ to use those local effective_precursor_tol_* variables to
decouple from member mutation and match the multi-file chunk-major path
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 215-223: Update the help text passed to
defaults_.setValue("database:chunk_size", ...) to remove the incorrect claim
that "Calibration (when enabled) runs on the first chunk only" and instead
describe the current behavior: calibration is performed on a strided,
size‑bounded sample of the full database using buildCalibrationSample_ (so small
chunk_size values do not starve the calibration pool); keep the rest of the
chunking explanation intact and ensure the new wording mentions
buildCalibrationSample_ and that calibration samples are taken across the full
DB rather than only from the first chunk.

In `@src/tests/class_tests/openms/source/ProSEAlgorithm_test.cpp`:
- Around line 1270-1275: The assertion uses the wrong endpoint convention: swap
the comparison so the positive-side calibrated magnitude `cal.cal_upper` is
greater than the negative-side `cal.cal_lower`. Update the test assertion that
currently reads `TEST_EQUAL(cal.cal_lower > cal.cal_upper, true)` to assert
`cal.cal_upper > cal.cal_lower` (using the existing `TEST_EQUAL` or equivalent)
so the test correctly validates the positive ppm bias; keep references to
`cal.cal_lower`, `cal.cal_upper`, and the `TEST_EQUAL` check when making the
change.

---

Outside diff comments:
In `@src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h`:
- Around line 418-433: The postProcessHits_ declaration currently takes a single
precursor_mass_tolerance which collapses asymmetric tolerances and loses
precision; change the signature of ProSEAlgorithm::postProcessHits_ to accept
two separate precursor tolerance parameters (precursor_mass_tolerance_lower and
precursor_mass_tolerance_upper, same type as the existing
precursor_mass_tolerance) and update every call site that passed
std::max(precursor_mass_tolerance_lower_, precursor_mass_tolerance_upper_) to
pass the two new parameters instead; ensure the function body and any internal
uses of the single precursor_mass_tolerance are adapted to use the appropriate
lower/upper values (function name: postProcessHits_, update all callers that
previously passed the max value).

---

Nitpick comments:
In `@src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h`:
- Around line 359-392: Replace the plain "///" prose comments for the new helper
declarations with full Doxygen blocks that use an `@brief` tag followed by a blank
line and then the detailed description; update the comments for
buildDecoyAugmentedDB_, buildCalibrationSample_, searchChunked_, and
scoreSpectraAgainstIndex_ to follow the project's pattern (/** `@brief` ... [blank
line] detailed explanation... */) so generated API docs include the brief and
the longer description.

In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp`:
- Around line 1746-1748: The final restore of parameters on chunk_fi is dead
code because chunk_fi is recreated each loop iteration; remove the redundant
lines that reset chunk_fi.setParameters(base_fi_params) guarded by
calibration_enabled_ && !open_search_mode. Instead, rely on the existing
per-file initialization that sets base_fi_params into the new chunk_fi (see the
block around the inner per-file/1732–1738 and the chunk_fi declaration near line
1718); delete the restore to avoid misleading/no-op code.
- Around line 1078-1094: The call to postProcessHits_ uses
std::max(precursor_mass_tolerance_lower_, precursor_mass_tolerance_upper_) which
relies on mutated member variables; replace that with the already-computed
locals effective_precursor_tol_lower and effective_precursor_tol_upper so the
post-calibration bounds are used explicitly (i.e. pass
std::max(effective_precursor_tol_lower, effective_precursor_tol_upper) instead
of using precursor_mass_tolerance_lower_/upper_); update the invocation site of
postProcessHits_ to use those local effective_precursor_tol_* variables to
decouple from member mutation and match the multi-file chunk-major path
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: 6d5aaae0-d982-4b65-bce2-5317cdb6fc00

📥 Commits

Reviewing files that changed from the base of the PR and between af5b0a5 and a934630.

📒 Files selected for processing (7)
  • src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h
  • src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp
  • src/tests/class_tests/openms/source/ProSEAlgorithm_test.cpp
  • src/tests/topp/CMakeLists.txt
  • src/tests/topp/ProSE_1_out.idXML
  • src/tests/topp/ProSE_2_out.idXML
  • src/tests/topp/ProSE_4_out.idXML

@timosachsenberg
timosachsenberg force-pushed the fix/prose-chunked-calibration branch from a934630 to 51219f3 Compare April 18, 2026 07:28

@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

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

215-223: ⚠️ Potential issue | 🟡 Minor

Update the stale database:chunk_size help text.

Line 220 still says calibration runs on the first chunk only, but this PR now uses buildCalibrationSample_() to draw a strided sample from the full decoy-augmented DB. This is user-facing parameter documentation and contradicts the implemented behavior.

Proposed wording
-      "Calibration (when enabled) runs on the first chunk only. In multi-file mode "
+      "Calibration (when enabled) runs on a strided, size-bounded sample drawn "
+      "from the full database, not just the first chunk. In multi-file mode "
🤖 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 215 - 223, The
help text for the "database:chunk_size" default is stale: it claims "Calibration
(when enabled) runs on the first chunk only" but the implementation uses
buildCalibrationSample_() to draw a strided sample from the full decoy-augmented
database; update the string passed to defaults_.setValue for the
"database:chunk_size" key to remove or reword the first-chunk-only statement and
instead state that calibration samples are drawn from the full (decoy-augmented)
database via buildCalibrationSample_(), ensuring the description matches the
implemented behavior.
🧹 Nitpick comments (1)
src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h (1)

359-396: Use the required Doxygen format for the new helper declarations.

These new header declarations are documented with plain /// comments, but header method documentation is expected to use @brief plus a blank-line detail section; for methods that can allocate/build indices or call indexing/scoring components, include relevant preconditions/exception behavior as well.

Documentation shape to apply
-    /// Build a decoy-augmented copy of the input FASTA (no FragmentIndex).
-    /// Used by prepareContext() and the chunked search path.
+    /**
+     * `@brief` Build a decoy-augmented copy of the input FASTA.
+     *
+     * Used by prepareContext() and the chunked search path without constructing
+     * a FragmentIndex.
+     *
+     * `@throws` Exception::Base Propagates exceptions from decoy generation.
+     */
     std::vector<FASTAFile::FASTAEntry> buildDecoyAugmentedDB_(
         const std::vector<FASTAFile::FASTAEntry>& fasta_db) const;

As per coding guidelines, **/*.h: “Use @brief plus blank line plus detailed description in Doxygen comments; required @brief tag” and “Document possible exceptions in C++ function/method documentation.”

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

In `@src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h` around lines 359 -
396, Update the three new helper declarations to use Doxygen `@brief` style:
replace the plain "///" summaries with a `@brief` tag followed by a blank line and
a short detailed paragraph for each function; for buildDecoyAugmentedDB_, state
it builds a decoy-augmented FASTA copy and document preconditions/behavior
(e.g., does not build a FragmentIndex, potential exceptions on I/O or memory
allocation); for buildCalibrationSample_, explain strided sampling tied to
database_chunk_size_, effect on calibration pool size, and note when calibration
may no-op; for searchChunked_, document that full_db must already contain decoys
when decoys_ is true, that full_db is non-const because PeptideIndexing::run()
mutates it, and list possible failure ExitCodes and thrown exceptions; for
scoreSpectraAgainstIndex_, describe that it scores spectra against a
FragmentIndex, list preconditions (valid fi, spectrum_generator, tolerances),
and any exception/alloc behavior. Ensure each comment block includes the
required `@brief` line, a blank line, and a detailed section mentioning
preconditions and exception behavior, referencing the exact symbol names
(buildDecoyAugmentedDB_, buildCalibrationSample_, searchChunked_,
scoreSpectraAgainstIndex_).
🤖 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 474-478: The code enables ppm alignment via sa.setParameters /
sa.getSpectrumAlignment (filling variable alignment between theoretical_spec and
spec) but the MIC computation still assumes each exp_idx appears once, causing
double-counting in ppm mode; update the matched-ion-current summation code (the
loop that processes alignment to compute MATCHED_ION_CURRENT / MIC) to first
detect ppm mode (fragment_mass_tolerance_unit_ppm == "ppm") and de-duplicate
experimental peaks by tracking seen exp_idx values (e.g., a boolean/bitset or
std::unordered_set) and only add each exp peak's intensity once; apply the same
de-duplication logic in the analogous block around lines 563-569 so ppm-mode
duplicate exp peaks are never summed multiple times.
- Around line 929-937: The current logic checks fasta_db.size() against
database_chunk_size_ before calling buildDecoyAugmentedDB_, so when decoys_ is
enabled the augmented (doubled/shuffled) DB can exceed the chunk threshold
unnoticed; change the flow to first call buildDecoyAugmentedDB_(fasta_db) to
produce full_db, then decide whether to use chunking by comparing full_db.size()
(or the resulting FragmentIndex size) to database_chunk_size_ and branch to
either search(...) or searchChunked_(...) accordingly; apply the same fix in the
multi-file branch where use_chunked is computed (lines around the use_chunked
variable) so the decision is based on the decoy-augmented DB.
- Around line 2341-2342: The code uses a hardcoded extreme_bias_threshold_ppm
and compares it directly to (hi - lo), which is in the current calibration unit,
so Da-mode windows get misclassified; change this to compute a unit-aware
threshold: keep a nominal_ppm_threshold (1.0) but convert it to Da when the
calibration/tolerance is in Da by computing threshold_da = nominal_ppm_threshold
* precursor_mz / 1e6 (use the precursor m/z available in the current context)
and otherwise use nominal_ppm_threshold directly for ppm mode, then set
result.extreme_bias = (hi - lo) < threshold_in_current_unit; update the variable
name (e.g., extreme_bias_threshold_ppm) and the comparison site
(result.extreme_bias assignment) accordingly and use the existing flag or mode
that indicates ppm vs Da to choose the conversion.
- Around line 1799-1808: The PeptideIndexing::run() return value is ignored here
causing failed indexing to still mark result as EXECUTION_OK; modify this
chunk-major multi-file path to capture the PeptideIndexing::ExitCodes from
indexer.run(full_db, result.protein_ids, result.peptide_ids), check for
non-success codes and map them to the same error handling used in the
non-chunked/searchChunked_ paths (e.g., set result.status to EXECUTION_ERROR or
the appropriate failure enum, log the failure via the same logger calls, and
avoid marking the file as successful), and ensure any cleanup/early-return
mirrors the existing behavior in searchChunked_().

---

Duplicate comments:
In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp`:
- Around line 215-223: The help text for the "database:chunk_size" default is
stale: it claims "Calibration (when enabled) runs on the first chunk only" but
the implementation uses buildCalibrationSample_() to draw a strided sample from
the full decoy-augmented database; update the string passed to
defaults_.setValue for the "database:chunk_size" key to remove or reword the
first-chunk-only statement and instead state that calibration samples are drawn
from the full (decoy-augmented) database via buildCalibrationSample_(), ensuring
the description matches the implemented behavior.

---

Nitpick comments:
In `@src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h`:
- Around line 359-396: Update the three new helper declarations to use Doxygen
`@brief` style: replace the plain "///" summaries with a `@brief` tag followed by a
blank line and a short detailed paragraph for each function; for
buildDecoyAugmentedDB_, state it builds a decoy-augmented FASTA copy and
document preconditions/behavior (e.g., does not build a FragmentIndex, potential
exceptions on I/O or memory allocation); for buildCalibrationSample_, explain
strided sampling tied to database_chunk_size_, effect on calibration pool size,
and note when calibration may no-op; for searchChunked_, document that full_db
must already contain decoys when decoys_ is true, that full_db is non-const
because PeptideIndexing::run() mutates it, and list possible failure ExitCodes
and thrown exceptions; for scoreSpectraAgainstIndex_, describe that it scores
spectra against a FragmentIndex, list preconditions (valid fi,
spectrum_generator, tolerances), and any exception/alloc behavior. Ensure each
comment block includes the required `@brief` line, a blank line, and a detailed
section mentioning preconditions and exception behavior, referencing the exact
symbol names (buildDecoyAugmentedDB_, buildCalibrationSample_, searchChunked_,
scoreSpectraAgainstIndex_).
🪄 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: 7b4a119f-b20f-4ad4-ac30-0248865d1985

📥 Commits

Reviewing files that changed from the base of the PR and between a934630 and 51219f3.

📒 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/tests/topp/CMakeLists.txt

@timosachsenberg
timosachsenberg force-pushed the fix/prose-chunked-calibration branch 2 times, most recently from 2db1b53 to 24972d0 Compare April 18, 2026 07:43

@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

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

1824-1833: ⚠️ Potential issue | 🟠 Major

Handle PeptideIndexing::run() failures in the chunk-major multi-file path.

The return value is ignored, then Line 1851 marks the result successful. Failed peptide indexing would produce successful-looking per-file results with unreliable protein mappings.

Mirror the existing error handling
-        indexer.run(full_db, result.protein_ids, result.peptide_ids);
+        PeptideIndexing::ExitCodes indexer_exit =
+          indexer.run(full_db, result.protein_ids, result.peptide_ids);
+        if ((indexer_exit != PeptideIndexing::ExitCodes::EXECUTION_OK) &&
+            (indexer_exit != PeptideIndexing::ExitCodes::PEPTIDE_IDS_EMPTY))
+        {
+          if (indexer_exit == PeptideIndexing::ExitCodes::DATABASE_EMPTY)
+          {
+            result.exit_code = ExitCodes::INPUT_FILE_EMPTY;
+          }
+          else if (indexer_exit == PeptideIndexing::ExitCodes::UNEXPECTED_RESULT)
+          {
+            result.exit_code = ExitCodes::UNEXPECTED_RESULT;
+          }
+          else
+          {
+            result.exit_code = ExitCodes::UNKNOWN_ERROR;
+          }
+          mfres.per_file.push_back(std::move(result));
+          continue;
+        }
🤖 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 1824 - 1833,
The PeptideIndexing::run return value is ignored which can mark per-file chunks
as successful despite failures; change the call to capture its boolean result
(e.g., bool ok = indexer.run(full_db, result.protein_ids, result.peptide_ids))
and, if ok is false, set the corresponding result.successful = false (and
propagate/log an error similarly to the existing single-file error handling),
avoid marking the chunk as successful, and ensure any downstream code that
assumes valid protein mappings is skipped or handled when result.successful is
false.

563-569: ⚠️ Potential issue | 🟠 Major

De-duplicate experimental peaks before summing MIC in ppm mode.

Line 476 enables ppm alignment, where one experimental peak can align to multiple theoretical peaks. MATCHED_ION_CURRENT can therefore double-count intensity unless exp_idx is tracked.

Guard the intensity sum
             std::vector<PeptideHit::PeakAnnotation> peak_annotations;
             std::vector<int> prefix_ordinals, suffix_ordinals;
+            std::vector<char> counted_exp_peaks(annotation_matched_ion_current ? spec.size() : 0, 0);
             double matched_ion_current = 0.0;
             peak_annotations.reserve(alignment.size());
@@
               if (annotation_matched_ion_current)
               {
-                // Safe: SpectrumAlignment's default Da path returns 1-to-1
-                // matches, so each exp_idx appears at most once. If ppm mode
-                // ever gets enabled here, one exp peak could match multiple
-                // theo peaks and this would double-count — revisit then.
-                matched_ion_current += spec[exp_idx].getIntensity();
+                if (!counted_exp_peaks[exp_idx])
+                {
+                  matched_ion_current += spec[exp_idx].getIntensity();
+                  counted_exp_peaks[exp_idx] = 1;
+                }
               }
🤖 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 563 - 569, The
matched_ion_current summation can double-count when ppm alignment allows one
experimental peak (exp_idx) to match multiple theoretical peaks; modify the
block where matched_ion_current is increased (the code referencing
matched_ion_current and spec[exp_idx].getIntensity()) to guard by a
per-spectrum/per-scoring-unit seen set of exp indices (e.g., an
unordered_set<int> or vector<bool>) — check if exp_idx is already present before
adding its intensity, insert it when first used, and ensure the seen container
is cleared/recreated at the correct scope so it's reset between independent
scoring contexts.

215-223: ⚠️ Potential issue | 🟡 Minor

Update the stale chunking help text.

Line 220 still says calibration runs on the first chunk only, which contradicts the strided-sample calibration path and will mislead users configuring database:chunk_size.

Proposed wording
-      "Calibration (when enabled) runs on the first chunk only. In multi-file mode "
+      "Calibration (when enabled) runs on a strided sample drawn from the full "
+      "database, so it is not limited to the first chunk. In multi-file mode "
🤖 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 215 - 223, The
help text for the "database:chunk_size" option is stale: update the string
passed to defaults_.setValue("database:chunk_size", 0, ...) in
ProSEAlgorithm.cpp to remove the incorrect claim that "Calibration (when
enabled) runs on the first chunk only" and replace it with wording that reflects
the current strided-sample calibration behavior (e.g., state that calibration,
when enabled, uses a strided-sample across chunks or is performed across chunks
rather than only on the first chunk); keep the rest of the explanatory text and
leave defaults_.setMinInt("database:chunk_size", 0) unchanged.

949-960: ⚠️ Potential issue | 🟠 Major

Decide chunking after decoy augmentation.

Both chunked entry points compare fasta_db.size() to database_chunk_size_ before buildDecoyAugmentedDB_(). With decoys_ enabled, the actual DB passed to FragmentIndex can exceed the configured chunk budget while still taking the non-chunked path.

Apply the same ordering in both entry points
-    // Non-chunked path: single context (existing behavior).
-    if (database_chunk_size_ == 0 || fasta_db.size() <= database_chunk_size_)
+    if (database_chunk_size_ == 0)
     {
       SearchContext ctx = prepareContext(fasta_db);
       return search(spectra, ctx, protein_ids, peptide_ids);
     }
 
-    warnIfChunkingUnnecessary_(fasta_db);
-
-    // Chunked path: build decoy-augmented DB once, then delegate.
     auto full_db = buildDecoyAugmentedDB_(fasta_db);
+    if (full_db.size() <= database_chunk_size_)
+    {
+      SearchContext ctx;
+      ctx.db = std::move(full_db);
+      startProgress(0, 1, "Building fragment index...");
+      ctx.fragment_index.setParameters(getParameters());
+      ctx.fragment_index.build(ctx.db);
+      endProgress();
+      return search(spectra, ctx, protein_ids, peptide_ids);
+    }
+
+    warnIfChunkingUnnecessary_(fasta_db);
     return searchChunked_(spectra, full_db, protein_ids, peptide_ids);

Also applies to: 1602-1613

🤖 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 949 - 960, The
code decides chunking using fasta_db.size() before decoy augmentation, which
lets decoys_ cause the actual DB (used by FragmentIndex) to exceed
database_chunk_size_ while taking the non-chunked path; fix by calling
buildDecoyAugmentedDB_(fasta_db) first (or when decoys_ is enabled), then use
the resulting full_db.size() to decide whether to take the non-chunked path
(call prepareContext(full_db) and return search(spectra, ctx, protein_ids,
peptide_ids)) or the chunked path (warnIfChunkingUnnecessary_(fasta_db) then
return searchChunked_(spectra, full_db, ...)); apply the same change to the
other entry point referenced (lines 1602-1613) so both code paths make the
chunking decision after decoy augmentation.

2366-2367: ⚠️ Potential issue | 🟠 Major

Make the extreme-bias threshold unit-aware.

hi - lo is in the configured precursor unit, so a hardcoded 1.0 works as “1 ppm” only in ppm mode. In Da mode, normal sub-Da calibrated windows can be misclassified as extreme and discarded.

Use a unit-aware threshold
-    const double extreme_bias_threshold_ppm = 1.0;
-    result.extreme_bias = (hi - lo) < extreme_bias_threshold_ppm;
+    const double extreme_bias_threshold =
+      (precursor_mass_tolerance_unit_ == "ppm") ? 1.0 : min_tolerance;
+    result.extreme_bias = (hi - lo) < extreme_bias_threshold;
🤖 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 2366 - 2367,
The code uses a hardcoded extreme_bias_threshold_ppm = 1.0 and compares (hi -
lo) to that value, but hi and lo are in the configured precursor unit; change
this to compute a unit-aware threshold and compare in the same units as hi/lo:
detect the configured precursor mass tolerance unit (ppm vs Da) and if units are
PPM convert 1.0 ppm to Daltons at the relevant m/z (use the midpoint (hi+lo)/2
or the precursor m/z available in scope) via the project’s ppm->Da helper (or
implement convertPpmToDa), otherwise use 1.0 Da directly; then replace the use
of extreme_bias_threshold_ppm and set result.extreme_bias = (hi - lo) <
threshold_in_configured_units so the comparison is correct for both ppm and Da
modes.
🧹 Nitpick comments (1)
src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h (1)

359-405: Convert the new helper docs to Doxygen @brief blocks.

These new header declarations use plain /// prose but omit the required @brief format and exception notes. Please align them with the surrounding method documentation before merging. As per coding guidelines, “Use @brief plus blank line plus detailed description in Doxygen comments; required @brief tag” and “Document possible exceptions in C++ function/method documentation.”

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

In `@src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h` around lines 359 -
405, The header comments for buildDecoyAugmentedDB_, buildCalibrationSample_,
warnIfChunkingUnnecessary_, searchChunked_, and scoreSpectraAgainstIndex_ are
plain prose; convert each to proper Doxygen style by adding an explicit `@brief`
line followed by a blank line and then the detailed description (matching
surrounding docs), and add a brief `@throw/`@exception note describing any
exceptions the function may emit (e.g., allocation, file I/O, or runtime errors)
where applicable; ensure the updated comments follow the project's
Doxygen/coding guideline format.
🤖 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 896-898: The theoretical spectrum is always generated for charge 1
but the FragmentIndex uses a configurable fragment:max_charge (default 2),
causing rescoring mismatches; update the call to
spectrum_generator.getSpectrum(theo_spectrum, mod_candidate, 1, 1) to generate
fragments across the same charge range used by the FragmentIndex (e.g.,
1..max_charge) — retrieve the configured max charge from the FragmentIndex or
the scorer config (e.g., FragmentIndex::getMaxCharge() or the
fragment_max_charge parameter) and pass that as the upper charge argument so
theo_spectrum covers all fragment charges the index may have matched.
- Around line 779-817: The calibration sample currently uses
database_chunk_size_ to compute cal_target (in the function building cal_db),
which ties calibration quality to chunk size; change cal_target to be
independent by capping it with a dedicated calibration sample size (e.g., a new
member like calibration_sample_size_ or a constant
DEFAULT_CALIBRATION_SAMPLE_SIZE) or derive it from calibration_min_psms_ (not
database_chunk_size_); update the cal_target line (replace
std::min(std::max<Size>(database_chunk_size_, Size(1)), full_db.size())) to use
std::min(std::max<Size>(calibration_sample_size_or_min_psms, Size(1)),
full_db.size()) so the strided sample pool is fixed-size regardless of
database_chunk_size_, and add the new config/member and any needed validation
where class members are initialized.

In `@src/tests/topp/CMakeLists.txt`:
- Around line 3090-3124: The test uses a large chunk size (the
-Search:database:chunk_size 5000 argument in the add_test
"TOPP_ProSE_DDA_chunked_calibrated" test) which will miss the
calibration-starvation regression; change that chunk_size value to the small
chunk size used in the PR objective/summary that reproduces `#9182` so the test
actually exercises the pre-#9182 behavior (update the
-Search:database:chunk_size argument only in the
TOPP_ProSE_DDA_chunked_calibrated add_test).

---

Duplicate comments:
In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp`:
- Around line 1824-1833: The PeptideIndexing::run return value is ignored which
can mark per-file chunks as successful despite failures; change the call to
capture its boolean result (e.g., bool ok = indexer.run(full_db,
result.protein_ids, result.peptide_ids)) and, if ok is false, set the
corresponding result.successful = false (and propagate/log an error similarly to
the existing single-file error handling), avoid marking the chunk as successful,
and ensure any downstream code that assumes valid protein mappings is skipped or
handled when result.successful is false.
- Around line 563-569: The matched_ion_current summation can double-count when
ppm alignment allows one experimental peak (exp_idx) to match multiple
theoretical peaks; modify the block where matched_ion_current is increased (the
code referencing matched_ion_current and spec[exp_idx].getIntensity()) to guard
by a per-spectrum/per-scoring-unit seen set of exp indices (e.g., an
unordered_set<int> or vector<bool>) — check if exp_idx is already present before
adding its intensity, insert it when first used, and ensure the seen container
is cleared/recreated at the correct scope so it's reset between independent
scoring contexts.
- Around line 215-223: The help text for the "database:chunk_size" option is
stale: update the string passed to defaults_.setValue("database:chunk_size", 0,
...) in ProSEAlgorithm.cpp to remove the incorrect claim that "Calibration (when
enabled) runs on the first chunk only" and replace it with wording that reflects
the current strided-sample calibration behavior (e.g., state that calibration,
when enabled, uses a strided-sample across chunks or is performed across chunks
rather than only on the first chunk); keep the rest of the explanatory text and
leave defaults_.setMinInt("database:chunk_size", 0) unchanged.
- Around line 949-960: The code decides chunking using fasta_db.size() before
decoy augmentation, which lets decoys_ cause the actual DB (used by
FragmentIndex) to exceed database_chunk_size_ while taking the non-chunked path;
fix by calling buildDecoyAugmentedDB_(fasta_db) first (or when decoys_ is
enabled), then use the resulting full_db.size() to decide whether to take the
non-chunked path (call prepareContext(full_db) and return search(spectra, ctx,
protein_ids, peptide_ids)) or the chunked path
(warnIfChunkingUnnecessary_(fasta_db) then return searchChunked_(spectra,
full_db, ...)); apply the same change to the other entry point referenced (lines
1602-1613) so both code paths make the chunking decision after decoy
augmentation.
- Around line 2366-2367: The code uses a hardcoded extreme_bias_threshold_ppm =
1.0 and compares (hi - lo) to that value, but hi and lo are in the configured
precursor unit; change this to compute a unit-aware threshold and compare in the
same units as hi/lo: detect the configured precursor mass tolerance unit (ppm vs
Da) and if units are PPM convert 1.0 ppm to Daltons at the relevant m/z (use the
midpoint (hi+lo)/2 or the precursor m/z available in scope) via the project’s
ppm->Da helper (or implement convertPpmToDa), otherwise use 1.0 Da directly;
then replace the use of extreme_bias_threshold_ppm and set result.extreme_bias =
(hi - lo) < threshold_in_configured_units so the comparison is correct for both
ppm and Da modes.

---

Nitpick comments:
In `@src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h`:
- Around line 359-405: The header comments for buildDecoyAugmentedDB_,
buildCalibrationSample_, warnIfChunkingUnnecessary_, searchChunked_, and
scoreSpectraAgainstIndex_ are plain prose; convert each to proper Doxygen style
by adding an explicit `@brief` line followed by a blank line and then the detailed
description (matching surrounding docs), and add a brief `@throw/`@exception note
describing any exceptions the function may emit (e.g., allocation, file I/O, or
runtime errors) where applicable; ensure the updated comments follow the
project's Doxygen/coding guideline format.
🪄 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: 1b7c3335-3e88-4a7a-b903-8fd0ac2f43cf

📥 Commits

Reviewing files that changed from the base of the PR and between 51219f3 and 2db1b53.

📒 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

Comment thread src/tests/topp/CMakeLists.txt Resolved
timosachsenberg added a commit that referenced this pull request Apr 18, 2026
Six small correctness and documentation fixes from the PR #9185 review:

- Update database:chunk_size docstring to reflect the strided-sample
  calibration introduced in this PR; the old text still said "first chunk
  only" which contradicts buildCalibrationSample_.
- Dedupe experimental peak indices in the matched_ion_current summation:
  ppm-mode SpectrumAlignment can match the same exp peak to multiple
  theoretical peaks, which would have double-counted intensity in MIC.
  Previously guarded by a comment; now enforced with a seen-index bitset.
- Decide chunking AFTER decoy augmentation in both entry points. With
  decoys enabled the augmented DB is 2× the input, so a target DB just
  under chunk_size could have skipped chunking and built an FI that
  exceeded the user's memory budget by 2×. Augment eagerly when
  chunk_size > 0; if the augmented DB fits in one chunk, reuse it in the
  non-chunked path.
- Capture PeptideIndexing::run() exit code in the chunk-major multi-file
  path — previously ignored, so indexing failures produced results
  marked EXECUTION_OK with incomplete protein mappings. Mirrors error
  handling already present in searchChunked_ and the non-chunked path.
- Unit-aware extreme_bias threshold: 1 ppm is the right floor for ppm
  tolerances but 1 Da would flag every realistic Da-mode calibration as
  extreme, silently disabling precursor calibration for Da users. Fall
  back to min_tolerance in Da mode.
- Convert the four new helper-method declarations in ProSEAlgorithm.h to
  the project's @brief Doxygen format (plain /// had been used).

All 25 ProSE-related tests remain green; no yield change on the HeLa
DDA-PASEF fixture (chunked+cal still 4438, chunked+cal+Percolator
still 4951).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
timosachsenberg added a commit that referenced this pull request Apr 18, 2026
Six small correctness and documentation fixes from the PR #9185 review:

- Update database:chunk_size docstring to reflect the strided-sample
  calibration introduced in this PR; the old text still said "first chunk
  only" which contradicts buildCalibrationSample_.
- Dedupe experimental peak indices in the matched_ion_current summation:
  ppm-mode SpectrumAlignment can match the same exp peak to multiple
  theoretical peaks, which would have double-counted intensity in MIC.
  Previously guarded by a comment; now enforced with a seen-index bitset.
- Decide chunking AFTER decoy augmentation in both entry points. With
  decoys enabled the augmented DB is 2× the input, so a target DB just
  under chunk_size could have skipped chunking and built an FI that
  exceeded the user's memory budget by 2×. Augment eagerly when
  chunk_size > 0; if the augmented DB fits in one chunk, reuse it in the
  non-chunked path.
- Capture PeptideIndexing::run() exit code in the chunk-major multi-file
  path — previously ignored, so indexing failures produced results
  marked EXECUTION_OK with incomplete protein mappings. Mirrors error
  handling already present in searchChunked_ and the non-chunked path.
- Unit-aware extreme_bias threshold: 1 ppm is the right floor for ppm
  tolerances but 1 Da would flag every realistic Da-mode calibration as
  extreme, silently disabling precursor calibration for Da users. Fall
  back to min_tolerance in Da mode.
- Convert the four new helper-method declarations in ProSEAlgorithm.h to
  the project's @brief Doxygen format (plain /// had been used).

All 25 ProSE-related tests remain green; no yield change on the HeLa
DDA-PASEF fixture (chunked+cal still 4438, chunked+cal+Percolator
still 4951).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@timosachsenberg
timosachsenberg force-pushed the fix/prose-chunked-calibration branch from 3fc7a3b to 03240a6 Compare April 18, 2026 07:58

@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

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

880-882: ⚠️ Potential issue | 🟠 Major

Theoretical spectrum still generated at charge 1 only in the centralized scorer.

Line 881 uses getSpectrum(theo_spectrum, mod_candidate, 1, 1) while FragmentIndex is parameterized with fragment:max_charge (default 2). Candidates that the index matched through z≥2 fragments will be re-scored against a theoretical spectrum missing those peaks, which suppresses HyperScore for exactly the high-charge candidates the index surfaced. This centralized helper is now on both chunked and non-chunked hot paths, so the inconsistency propagates everywhere.

🤖 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 880 - 882, The
theoretical spectrum is being generated only for charge 1 causing high-charge
candidates found by FragmentIndex to be rescored incorrectly; in
ProSEAlgorithm.cpp replace the fixed call to
spectrum_generator.getSpectrum(theo_spectrum, mod_candidate, 1, 1) with a call
that covers the full fragment charge range used by the index (e.g.
1..fragment_max_charge) so the theo_spectrum includes z≥2 peaks; use the same
configuration/variable that parameterizes FragmentIndex (fragment:max_charge) or
the class member that stores max fragment charge when constructing the spectrum
(refer to symbols spectrum_generator.getSpectrum, mod_candidate, theo_spectrum
and FragmentIndex/fragment:max_charge) so chunked and non-chunked paths use
identical charge ranges.
🧹 Nitpick comments (1)
src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp (1)

1786-1788: Dead restore — chunk_fi is loop-local.

chunk_fi is declared inside the chunk loop (line 1758) and destructed at the iteration end, so resetting its params after the per-file loop has no observable effect. Harmless, but removing it makes the intent clearer and avoids suggesting that chunk_fi state is reused across chunks.

✏️ Suggested cleanup
-        // Restore base FI params for next chunk (in case calibration modified them).
-        if (calibration_enabled_ && !open_search_mode)
-          chunk_fi.setParameters(base_fi_params);
-
         // Per-chunk pruning for each file.
🤖 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 1786 - 1788,
The restore of parameters on chunk_fi is dead because chunk_fi is created
per-chunk and destroyed at iteration end; remove the conditional block that
calls chunk_fi.setParameters(base_fi_params) (the lines guarded by
calibration_enabled_ && !open_search_mode) to avoid implying chunk_fi is reused
across chunks; keep base_fi_params and the calibration flags as-is and ensure no
other code relies on chunk_fi surviving past the loop.
🤖 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 1001-1028: The chunked path currently stores the calibration
result only in a local variable `cal` (returned by `runCalibrationPass_`) so
`last_calibration_result_` is not updated; change the chunked entry point to
assign the returned `CalibrationResult_` into `last_calibration_result_` (or
into a per-file field if you prefer per-file fidelity) after
`runCalibrationPass_` completes, mirroring the non-chunked path (ensure the same
variable names `cal` / `last_calibration_result_` are used and keep existing
logic that sets `calibration_applied`, `precursor_mass_tolerance_lower_`,
`precursor_mass_tolerance_upper_`, and logging intact).
- Around line 2388-2389: The current quantile extraction uses integer-indexed
picks that collapse to min/max for small n (see variables sorted_errs, lo, hi,
and n in ProSEAlgorithm.cpp), so change the logic to compute fractional quantile
indices (e.g., idx = (n-1) * q), then take floor/ceil and linearly interpolate
between sorted_errs[floor] and sorted_errs[ceil] to produce lo at q=0.005 and hi
at q=0.995; alternatively enforce a higher effective minimum (use max(n,
calibration:min_psms_threshold)) before applying quantiles—implement the
fractional-index linear interpolation approach to avoid sensitivity to tail
outliers for small sample sizes.

---

Duplicate comments:
In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp`:
- Around line 880-882: The theoretical spectrum is being generated only for
charge 1 causing high-charge candidates found by FragmentIndex to be rescored
incorrectly; in ProSEAlgorithm.cpp replace the fixed call to
spectrum_generator.getSpectrum(theo_spectrum, mod_candidate, 1, 1) with a call
that covers the full fragment charge range used by the index (e.g.
1..fragment_max_charge) so the theo_spectrum includes z≥2 peaks; use the same
configuration/variable that parameterizes FragmentIndex (fragment:max_charge) or
the class member that stores max fragment charge when constructing the spectrum
(refer to symbols spectrum_generator.getSpectrum, mod_candidate, theo_spectrum
and FragmentIndex/fragment:max_charge) so chunked and non-chunked paths use
identical charge ranges.

---

Nitpick comments:
In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp`:
- Around line 1786-1788: The restore of parameters on chunk_fi is dead because
chunk_fi is created per-chunk and destroyed at iteration end; remove the
conditional block that calls chunk_fi.setParameters(base_fi_params) (the lines
guarded by calibration_enabled_ && !open_search_mode) to avoid implying chunk_fi
is reused across chunks; keep base_fi_params and the calibration flags as-is and
ensure no other code relies on chunk_fi surviving past the loop.
🪄 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: b5ed1862-c769-49bf-b832-a6b9c0384702

📥 Commits

Reviewing files that changed from the base of the PR and between 24972d0 and 3fc7a3b.

📒 Files selected for processing (2)
  • src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h
  • src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp
✅ Files skipped from review due to trivial changes (1)
  • src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.h

timosachsenberg and others added 2 commits April 18, 2026 10:40
Closes #9180 and #9182, which manifested together in the chunked
calibration path:

#9180 — the chunked paths (searchChunked_ and the chunk-major multi-file
branch) collapsed the calibrated asymmetric precursor window to a
symmetric max(cal_lower, cal_upper) before passing it to FragmentIndex,
losing the tight side. Quantile calibration makes bounds more asymmetric
than MAD did, so this became visible as a Percolator yield regression.
Fix: plumb cal.cal_lower and cal.cal_upper as separate FI params; split
PerFileCalibration::effective_precursor_tol into lower/upper fields.

#9182 — calibration ran only on the first database_chunk_size_ proteins.
At small chunk_size the PSM pool fell below calibration_min_psms_ and
calibration silently didn't fire. Fix: new buildCalibrationSample_
helper produces a strided sample across the full DB, with sample size
tied to database_chunk_size_ so calibration FI memory stays bounded by
the user's declared memory budget (critical for non-specific digestion
on variant DBs, where a fixed 5000-protein sample could generate tens
of GB of fragment index).

Also added state restoration in searchChunked_ so mutated algo-level
tolerance members are reset on all return paths.

Yields on DDA_HeLa (HeLa timsTOF DDA-PASEF, 1% FDR):
  non-chunked cal alone:                4681  (reference)
  non-chunked cal + Percolator:         5090  (reference)
  chunked (chunk=5000) cal alone:       4373 before -> 4438 after
  chunked (chunk=5000) cal + Percolator: 4806 before -> 4951 after

Residual gap vs non-chunked (~2%) remains: chunked calibration has
access to fewer proteins → fewer PSMs → noisier quantile bounds.
Closing that gap requires pooling cal PSMs across the first K chunks
of the main search loop — tracked separately.

Note on small chunk_size: when chunk_size is very small (e.g. MHC-II
immunopeptidomics with ~100 proteins per chunk), the calibration PSM
pool can fall below min_psms and calibration silently no-ops. This is
the expected memory-vs-quality tradeoff; the follow-up pooled-cal
issue addresses it.

Tests:
- TOPP_ProSE_DDA_chunked_calibrated + floor at 4400: new regression
  guard for chunk_size=5000 (where cal fires reliably under the
  cal_target=chunk_size strategy).
- All pre-existing ProSE tests unchanged and passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Six small correctness and documentation fixes from the PR #9185 review:

- Update database:chunk_size docstring to reflect the strided-sample
  calibration introduced in this PR; the old text still said "first chunk
  only" which contradicts buildCalibrationSample_.
- Dedupe experimental peak indices in the matched_ion_current summation:
  ppm-mode SpectrumAlignment can match the same exp peak to multiple
  theoretical peaks, which would have double-counted intensity in MIC.
  Previously guarded by a comment; now enforced with a seen-index bitset.
- Decide chunking AFTER decoy augmentation in both entry points. With
  decoys enabled the augmented DB is 2× the input, so a target DB just
  under chunk_size could have skipped chunking and built an FI that
  exceeded the user's memory budget by 2×. Augment eagerly when
  chunk_size > 0; if the augmented DB fits in one chunk, reuse it in the
  non-chunked path.
- Capture PeptideIndexing::run() exit code in the chunk-major multi-file
  path — previously ignored, so indexing failures produced results
  marked EXECUTION_OK with incomplete protein mappings. Mirrors error
  handling already present in searchChunked_ and the non-chunked path.
- Unit-aware extreme_bias threshold: 1 ppm is the right floor for ppm
  tolerances but 1 Da would flag every realistic Da-mode calibration as
  extreme, silently disabling precursor calibration for Da users. Fall
  back to min_tolerance in Da mode.
- Convert the four new helper-method declarations in ProSEAlgorithm.h to
  the project's @brief Doxygen format (plain /// had been used).

All 25 ProSE-related tests remain green; no yield change on the HeLa
DDA-PASEF fixture (chunked+cal still 4438, chunked+cal+Percolator
still 4951).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@timosachsenberg
timosachsenberg force-pushed the fix/prose-chunked-calibration branch from 03240a6 to 7aff1d6 Compare April 18, 2026 08:44
@timosachsenberg
timosachsenberg merged commit a4dff53 into develop Apr 18, 2026
15 checks passed
@timosachsenberg
timosachsenberg deleted the fix/prose-chunked-calibration branch April 18, 2026 09:50
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

1 participant