Skip to content

feat: automatic mass accuracy calibration (two-pass search) in PeptideSearchEngineFI - #9122

Merged
timosachsenberg merged 6 commits into
developfrom
feat/fi-auto-calibration
Apr 10, 2026
Merged

timosachsenberg merged 6 commits into
developfrom
feat/fi-auto-calibration

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Add optional two-pass calibration search (-Search:calibration:enabled) inspired by MSFragger's calibrate_mass and OpenNuXL's autotune
  • Pass 1: fast search on a subset of spectra (top 10% by TIC, configurable) with user's configured (wide) tolerance
  • Pass 2: main search with calibrated (tighter) tolerances estimated from confident PSMs
  • Uses robust median + 3*MAD estimation for precursor tolerance and NuXL-style 4 × 68th percentile for fragment tolerance
  • Key advantage: no index rebuild — FragmentIndex applies tolerances at query time, so only query-time parameters are updated between passes
  • Calibrated tolerances never widen beyond configured values (only tighten)
  • Falls back to configured tolerances if insufficient PSMs found
  • PSM quality filtering: top 50% by score + precursor error within configured tolerance

Parameters

  • calibration:enabled (default: false) — opt-in
  • calibration:subset_ratio (default: 0.1) — fraction of spectra for calibration pass
  • calibration:min_psms (default: 50) — minimum PSMs needed for reliable estimation

Benchmark: timsTOF DDA HeLa (50ng, 5.6min)

Exact parameters from TOPP_PeptideDataBaseSearchFI_DDA integration test (20/20 ppm, mc=2, Trypsin/P, +Acetyl). FDR applied externally via FalseDiscoveryRate:

Baseline (20/20 ppm) Calibrated (20→10 / 20 ppm) Δ
PSMs at 1% FDR 4,369 4,631 +262 (+6.0%)
Unique peptides 2,887 3,032 +145 (+5.0%)
Protein hits 1,150 1,191 +41 (+3.6%)
Wall time 24.2s 25.0s +0.8s

Calibration estimated: precursor median |error| = 3.77 ppm, MAD = 1.82 ppm → ceil(3.77 + 3×1.82) = 10 ppm.

Relates to #9108 (strategic bet: auto mass recalibration).

Test plan

  • All 15 existing tests pass (calibration disabled by default — no behavioral change)
  • New TOPP_PeptideDataBaseSearchFI_DDA_calibrated integration test (timsTOF DDA + calibration + FDR)
  • Smoke test: calibration correctly tightens tolerances
  • Calibration correctly skips when insufficient PSMs
  • Calibration correctly skips in open-search mode
  • Validated on timsTOF DDA HeLa: +6% PSMs at 1% FDR

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Optional mass-tolerance calibration for peptide searches. When enabled, the tool estimates refined precursor and fragment tolerances (and a fragment shift) from a TIC-ranked subset of spectra and uses them during scoring and PSM post-processing to improve identification accuracy.
    • New calibration settings: enable toggle, subset ratio, and minimum PSMs required.
  • Tests

    • Added end-to-end tests for calibrated search and subsequent FDR evaluation.

@coderabbitai

coderabbitai Bot commented Apr 9, 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 an optional in-process calibration pass to PeptideSearchEngineFIAlgorithm that estimates effective precursor and fragment tolerances (and fragment shift) from a TIC-ranked spectra subset and applies those calibrated tolerances to scoring and post-processing when the pass succeeds.

Changes

Cohort / File(s) Summary
Calibration Core
src/openms/include/OpenMS/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.h, src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp
Added calibration config parameters (calibration.enabled, calibration.subset_ratio, calibration.min_psms), a CalibrationResult_ struct, runCalibrationPass_() declaration/implementation, and new members to hold calibration state.
Search Pipeline Integration
src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp
Invoke calibration pass before scoring in closed-search mode; on success compute effective_precursor_tol/effective_fragment_tol, temporarily update FragmentIndex query-time tolerances, use effective_fragment_tol for scoring and forward effective tolerances to post-processing, then restore original FragmentIndex params (including on early returns).
Calibration Logic & Selection
src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp (calibration block)
Select TIC-ranked subset, collect signed precursor errors and fragment mean errors from top FI candidates, filter by score/top fraction with min_psms, compute robust statistics (median + 3*MAD for precursor; percentile-based for fragment), clamp to configured maxima, and skip calibration if insufficient confident PSMs.
Tests / CI
src/tests/topp/CMakeLists.txt
Added two CTest entries: calibrated TOPP_PeptideDataBaseSearchFI_DDA_calibrated run and dependent TOPP_FalseDiscoveryRate_PeptideDataBaseSearchFIDDA_calibrated run; wired dependency via test properties.

Sequence Diagram(s)

sequenceDiagram
    participant SE as SearchEngine
    participant SS as SpectraSubset
    participant FI as FragmentIndex
    participant SC as Scoring(HyperScore)
    participant PP as PostProcessor

    SE->>SS: select TIC-ranked subset (subset_ratio)
    SS->>FI: query top candidates per spectrum
    FI-->>SS: candidate lists
    SS->>SC: score candidates (configured tolerances)
    SC-->>SE: per-PSM errors & scores
    SE->>SE: runCalibrationPass_ -> compute effective_precursor_tol, effective_fragment_tol, fragment_shift
    alt calibration success
        SE->>FI: update query-time params (precursor/fragment tolerances)
        SE->>SC: score spectra using effective_fragment_tol
        SC-->>SE: calibrated scoring results
        SE->>PP: postProcessHits_ (use effective_precursor_tol/effective_fragment_tol)
        SE->>FI: restore original query-time params
    else calibration fail
        SE->>SC: continue with configured tolerances
        SE->>PP: postProcessHits_ (use configured tolerances)
    end
Loading

Possibly related PRs

Suggested reviewers

  • jcharkow
  • cbielow

Poem

🐰 I nibbled spectra by moonlit beams,
tuned shifts and spreads through tiny schemes,
counted peaks, found median and sway,
tightened tolerances to light the way,
hop—now searches sing in truer streams. ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and clearly describes the main feature: automatic mass accuracy calibration implemented as a two-pass search in PeptideSearchEngineFI, which is the central change across all modified files.

✏️ 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/fi-auto-calibration

Warning

Review ran into problems

🔥 Problems

Timed out fetching pipeline failures after 30000ms


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

🧹 Nitpick comments (1)
src/openms/include/OpenMS/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.h (1)

435-447: Use proper Doxygen blocks for the new header declarations.

The new CalibrationResult_ and runCalibrationPass_() comments are in an installed header, but they use one-line /// comments instead of the repo's required @brief block format.

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/PeptideSearchEngineFIAlgorithm.h`
around lines 435 - 447, The new public declarations use single-line /// comments
instead of the project's required Doxygen block format; update the comments for
the struct CalibrationResult_ and the method runCalibrationPass_() to use a
Doxygen block with an `@brief` tag followed by a blank line and any detailed
description, e.g. add a /** `@brief` ... */ block before CalibrationResult_
describing the purpose and members (precursor_tolerance, fragment_tolerance,
fragment_shift, success) and a /** `@brief` ... */ block before
runCalibrationPass_ describing what the function does, its parameters (PeakMap&
spectra, FragmentIndex& fragment_index, const
std::vector<FASTAFile::FASTAEntry>& db) and the returned CalibrationResult_,
following the repository’s `@brief` + blank line + detailed description
convention.
🤖 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/PeptideSearchEngineFIAlgorithm.cpp`:
- Around line 192-196: The help text in the defaults_.setValue call currently
claims a global fragment m/z shift correction which is not implemented
(runCalibrationPass_() hardcodes fragment_shift = 0.0 and search() never applies
a fragment shift); update the string passed to defaults_.setValue to remove or
rephrase the fragment-shift claim (e.g., state that only precursor/fragment
tolerances are tightened and no fragment m/z shift is applied) so the
description matches the behavior of runCalibrationPass_() and search().
- Around line 1395-1406: The code rounds percentile-based tolerances with
std::ceil and forces them to be >= 1.0, which destroys high-resolution Da
calibration; change the logic in the block computing result.precursor_tolerance
and result.fragment_tolerance (where precursor_errors, fragment_errors_abs,
prec_left, prec_right, frag_68 are used) to keep the tolerances as doubles
(remove std::ceil) and replace the hard 1.0 clamp with a tiny positive floor
(e.g., const double min_tolerance = 1e-6 or a configurable parameter) so
calibrated tolerances like 0.02 Da are preserved while still avoiding
non-positive values. Ensure you update both the precursor and fragment branches
(the assignments to result.precursor_tolerance and result.fragment_tolerance)
and keep the percentile indexing logic unchanged.
- Around line 740-765: The calibration code is mutating the shared
ctx.fragment_index via fragment_index_.setParameters(...) inside search(...,
SearchContext&) which makes calibrated tolerances persist across files; change
this to avoid mutating the shared FragmentIndex by applying calibrated
tolerances only locally: obtain the FragmentIndex parameters via
fragment_index_.getParameters() (or clone a local FragmentIndex/parameter set),
update the local copy with effective_precursor_tol/effective_fragment_tol and
use that local parameters/clone for any subsequent query-time operations or
function calls (e.g. pass the local params into whatever methods use the
tolerances) instead of calling fragment_index_.setParameters(); keep
runCalibrationPass_ and the effective_* variables as-is but do not call
setParameters on the shared fragment_index_.

---

Nitpick comments:
In `@src/openms/include/OpenMS/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.h`:
- Around line 435-447: The new public declarations use single-line /// comments
instead of the project's required Doxygen block format; update the comments for
the struct CalibrationResult_ and the method runCalibrationPass_() to use a
Doxygen block with an `@brief` tag followed by a blank line and any detailed
description, e.g. add a /** `@brief` ... */ block before CalibrationResult_
describing the purpose and members (precursor_tolerance, fragment_tolerance,
fragment_shift, success) and a /** `@brief` ... */ block before
runCalibrationPass_ describing what the function does, its parameters (PeakMap&
spectra, FragmentIndex& fragment_index, const
std::vector<FASTAFile::FASTAEntry>& db) and the returned CalibrationResult_,
following the repository’s `@brief` + blank line + detailed description
convention.
🪄 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: d461d35b-8360-41d9-878e-045c27dbb69b

📥 Commits

Reviewing files that changed from the base of the PR and between 248e51a and 97ff1d0.

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

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Benchmark: timsTOF DDA HeLa (50ng, 5.6min)

Validated with FileInfo on FDR-filtered (1% PSM FDR) output:

Baseline (20 ppm) Calibrated (20→9 ppm) Δ
Matched spectra 2,656 2,958 +302 (+11.4%)
Unique peptide sequences 1,854 2,023 +169 (+9.1%)
Non-redundant peptide hits 1,859 2,028 +169
Protein hits 912 958 +46 (+5.0%)
Calibration stats — median=3.35 ppm, MAD=1.82 ppm —
Wall time 19.5s 20.5s +1.0s

⚠️ Performance note

There appears to be a performance regression: despite the tighter calibrated precursor tolerance (9 vs 20 ppm), the main search does not run faster. Expected behavior would be fewer candidates per spectrum → less scoring work → faster search. Possible causes:

  1. FragmentIndex precursor lookup is already O(log n) via binary search — the narrower window saves comparisons but not lookups
  2. The scoring bottleneck (TheoreticalSpectrumGenerator + HyperScore per candidate) may dominate over candidate enumeration
  3. The calibration pass adds ~1s overhead (scoring 10% of spectra) that offsets any gain
  4. For this database size (~20k proteins), the candidate count reduction from 20→9 ppm may be modest

This should be profiled on a larger dataset to determine whether the tighter tolerance provides any speed benefit, or if the calibration's value is purely in improved FDR discrimination.

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Updated benchmark: exact test parameters (20/20 ppm, mc=2, +Acetyl, Trypsin/P)

Using the exact parameters from the TOPP_PeptideDataBaseSearchFI_DDA integration test, with FDR applied externally via FalseDiscoveryRate tool:

Baseline (20/20 ppm) Calibrated (20→10 / 20 ppm) Δ
PSMs at 1% FDR 4,369 4,631 +262 (+6.0%)
Unique peptides 2,887 3,032 +145 (+5.0%)
Protein hits 1,150 1,191 +41 (+3.6%)
Unfiltered PSMs 7,501 7,033 -468
Wall time 24.2s 25.0s +0.8s

Calibration estimated: precursor median |error| = 3.77 ppm, MAD = 1.82 ppm → ceil(3.77 + 3×1.82) = 10 ppm. Fragment tolerance stayed at 20 ppm (already appropriate).

Previous benchmark used wrong parameters (mc=1, no Acetyl, fragment=10 ppm) and internal FDR — corrected above.

⚠️ Performance note remains: tighter precursor tolerance (10 vs 20 ppm) does not yield a measurable speed improvement (+0.8s overhead from calibration pass). The scoring bottleneck appears to be per-candidate TheoreticalSpectrumGenerator + HyperScore, not candidate enumeration.

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

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

1412-1413: ⚠️ Potential issue | 🟠 Major

ceil + hard >=1.0 clamp prevents sub-1 calibration tightening

At Line 1412 and Line 1420, rounding and forcing a minimum of 1.0 can make calibration ineffective in high-resolution settings (especially Da mode). Keep double precision and clamp only to a tiny positive floor.

🛠️ Suggested numeric fix
-    result.precursor_tolerance = std::ceil(prec_median + 3.0 * prec_mad);
-    if (result.precursor_tolerance < 1.0) result.precursor_tolerance = 1.0;
+    const double min_tolerance = 1e-6;
+    result.precursor_tolerance = prec_median + 3.0 * prec_mad;
+    if (result.precursor_tolerance < min_tolerance) result.precursor_tolerance = min_tolerance;
@@
-      result.fragment_tolerance = std::ceil(4.0 * frag_68);
-      if (result.fragment_tolerance < 1.0) result.fragment_tolerance = 1.0;
+      result.fragment_tolerance = 4.0 * frag_68;
+      if (result.fragment_tolerance < min_tolerance) result.fragment_tolerance = min_tolerance;

Also applies to: 1420-1421

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

In `@src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp` around
lines 1412 - 1413, The code currently forces result.precursor_tolerance =
std::ceil(prec_median + 3.0 * prec_mad) and then clamps to 1.0, which loses
sub-1.0 precision; change this to keep the double precision (remove std::ceil)
and replace the hard floor of 1.0 with a tiny positive floor (e.g. 1e-6) so
high-resolution/Da-mode calibrations can tighten below 1.0; apply the same
change to the other occurrence that sets result.precursor_tolerance (the block
using prec_median and prec_mad around lines 1420-1421) so both assignments keep
full double precision and use the small positive clamp.

192-196: ⚠️ Potential issue | 🟡 Minor

Help text still overpromises fragment-shift correction

At Line 195, the description says calibration applies a global fragment m/z shift correction, but the implementation keeps fragment_shift = 0.0 and does not apply a shift in scoring/querying.

💡 Suggested text fix
-    defaults_.setValue("calibration:enabled", "false",
-      "If enabled, run a fast calibration pass on a subset of spectra before the main search. "
-      "Estimates tighter precursor and fragment tolerances from confident PSMs and applies a "
-      "global fragment m/z shift correction. The fragment index is NOT rebuilt — only query-time "
-      "tolerances change. Inspired by MSFragger's calibrate_mass and OpenNuXL's autotune.");
+    defaults_.setValue("calibration:enabled", "false",
+      "If enabled, run a fast calibration pass on a subset of spectra before the main search. "
+      "Estimates tighter precursor and fragment tolerances from confident PSMs. "
+      "The fragment index is NOT rebuilt — only query-time tolerances change. "
+      "Inspired by MSFragger's calibrate_mass and OpenNuXL's autotune.");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp` around
lines 192 - 196, The help text for the "calibration:enabled" default overstates
behavior: it claims a "global fragment m/z shift correction" while the code
(e.g., the fragment_shift variable in PeptideSearchEngineFIAlgorithm.cpp)
remains 0.0 and no shift is applied; update the string passed to
defaults_.setValue in PeptideSearchEngineFIAlgorithm.cpp to remove or qualify
the fragment-shift claim (or explicitly state that fragment shift is not
currently applied) so documentation matches the implementation, referencing the
calibration:enabled key and the fragment_shift usage.

740-765: ⚠️ Potential issue | 🔴 Critical

Reset shared FragmentIndex tolerances per search invocation

At Line 764, ctx.fragment_index is mutated with calibrated tolerances. In multi-file mode with a reused SearchContext, this can leak one file’s calibrated window into later files (especially when later calibration is skipped or fails fallback), causing incorrect query-time behavior.

🛠️ Minimal safe fix
     // Reference the prepared (decoy-augmented) database and prebuilt fragment index from the context.
     std::vector<FASTAFile::FASTAEntry>& db = ctx.db;
     FragmentIndex& fragment_index_ = ctx.fragment_index;
+    // Reset query-time tolerances for every search call to avoid cross-file leakage
+    // when SearchContext is reused.
+    Param fi_params = fragment_index_.getParameters();
+    fi_params.setValue("precursor:mass_tolerance", precursor_mass_tolerance_);
+    fi_params.setValue("fragment:mass_tolerance", fragment_mass_tolerance_);
+    fragment_index_.setParameters(fi_params);

     // Effective tolerances: may be overridden by calibration pass below.
     double effective_precursor_tol = precursor_mass_tolerance_;
     double effective_fragment_tol = fragment_mass_tolerance_;
@@
         // Update the fragment index's query-time tolerances (no index rebuild)
-        Param fi_params = fragment_index_.getParameters();
+        fi_params = fragment_index_.getParameters();
         fi_params.setValue("precursor:mass_tolerance", effective_precursor_tol);
         fi_params.setValue("fragment:mass_tolerance", effective_fragment_tol);
         fragment_index_.setParameters(fi_params);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp` around
lines 740 - 765, The code mutates the shared ctx.fragment_index parameters (via
fragment_index_.setParameters) during calibration which can leak tuned
tolerances across files; to fix, capture the original Param from
fragment_index_.getParameters() before calling runCalibrationPass_ and only
apply calibrated values to a temporary Param (or to fragment_index_) for the
duration of this search invocation, then restore the saved original Param on
fragment_index_ after the search (or if calibration is skipped/fails); reference
symbols: ctx.fragment_index / fragment_index_, runCalibrationPass_,
getParameters(), setParameters(), effective_precursor_tol,
effective_fragment_tol, calibration_enabled_, open_search.
🧹 Nitpick comments (1)
src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp (1)

1309-1310: Prefer '\n' over std::endl in new calibration logs

The newly added calibration log lines use std::endl; prefer '\n' to avoid unnecessary stream flushes on hot paths.

As per coding guidelines: "Avoid std::endl for performance reasons; prefer \n in C++."

Also applies to: 1397-1399, 1442-1449

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

In `@src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp` around
lines 1309 - 1310, Replace occurrences of std::endl used in the calibration
logging with '\n' to avoid unnecessary stream flushes; specifically update the
OPENMS_LOG_INFO statements in PeptideSearchEngineFIAlgorithm (the lines logging
"[PDBS-FI] Calibration: scoring ..." and the subsequent calibration logs around
the block that includes subset_size, spectra.size(), and other messages
referenced at ~1309, ~1397-1399, and ~1442-1449) so they end with '\n' instead
of std::endl; ensure each affected OPENMS_LOG_INFO line concatenates '\n' (not
std::endl) and preserves the same message text and spacing.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp`:
- Around line 1412-1413: The code currently forces result.precursor_tolerance =
std::ceil(prec_median + 3.0 * prec_mad) and then clamps to 1.0, which loses
sub-1.0 precision; change this to keep the double precision (remove std::ceil)
and replace the hard floor of 1.0 with a tiny positive floor (e.g. 1e-6) so
high-resolution/Da-mode calibrations can tighten below 1.0; apply the same
change to the other occurrence that sets result.precursor_tolerance (the block
using prec_median and prec_mad around lines 1420-1421) so both assignments keep
full double precision and use the small positive clamp.
- Around line 192-196: The help text for the "calibration:enabled" default
overstates behavior: it claims a "global fragment m/z shift correction" while
the code (e.g., the fragment_shift variable in
PeptideSearchEngineFIAlgorithm.cpp) remains 0.0 and no shift is applied; update
the string passed to defaults_.setValue in PeptideSearchEngineFIAlgorithm.cpp to
remove or qualify the fragment-shift claim (or explicitly state that fragment
shift is not currently applied) so documentation matches the implementation,
referencing the calibration:enabled key and the fragment_shift usage.
- Around line 740-765: The code mutates the shared ctx.fragment_index parameters
(via fragment_index_.setParameters) during calibration which can leak tuned
tolerances across files; to fix, capture the original Param from
fragment_index_.getParameters() before calling runCalibrationPass_ and only
apply calibrated values to a temporary Param (or to fragment_index_) for the
duration of this search invocation, then restore the saved original Param on
fragment_index_ after the search (or if calibration is skipped/fails); reference
symbols: ctx.fragment_index / fragment_index_, runCalibrationPass_,
getParameters(), setParameters(), effective_precursor_tol,
effective_fragment_tol, calibration_enabled_, open_search.

---

Nitpick comments:
In `@src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp`:
- Around line 1309-1310: Replace occurrences of std::endl used in the
calibration logging with '\n' to avoid unnecessary stream flushes; specifically
update the OPENMS_LOG_INFO statements in PeptideSearchEngineFIAlgorithm (the
lines logging "[PDBS-FI] Calibration: scoring ..." and the subsequent
calibration logs around the block that includes subset_size, spectra.size(), and
other messages referenced at ~1309, ~1397-1399, and ~1442-1449) so they end with
'\n' instead of std::endl; ensure each affected OPENMS_LOG_INFO line
concatenates '\n' (not std::endl) and preserves the same message text and
spacing.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 259afc1a-9ada-4c1e-be8a-25d83154cd4f

📥 Commits

Reviewing files that changed from the base of the PR and between 97ff1d0 and cd17bb7.

📒 Files selected for processing (1)
  • src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp

@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 (1)
src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp (1)

748-752: ⚠️ Potential issue | 🟠 Major

Restore FragmentIndex parameters on every exit path.

The new tail restore only runs on the happy path. The earlier return statements in the PeptideIndexing error block still bypass it, so a failed calibrated run can leak tightened tolerances into the reused SearchContext for the next file. Please move the restore into a scope guard / RAII helper so it also runs on failures and exceptions.

🛠️ Minimal fix
     const Param fi_params_original = fragment_index_.getParameters();
     bool fi_params_modified = false;
+    struct FIParamsRestoreGuard
+    {
+      FragmentIndex& fragment_index;
+      const Param& original_params;
+      bool& modified;
+
+      ~FIParamsRestoreGuard()
+      {
+        if (modified)
+        {
+          fragment_index.setParameters(original_params);
+        }
+      }
+    } fi_params_restore_guard{fragment_index_, fi_params_original, fi_params_modified};
@@
-    // Restore original FragmentIndex parameters if calibration modified them,
-    // so the shared SearchContext is unchanged for subsequent per-file searches.
-    if (fi_params_modified)
-    {
-      fragment_index_.setParameters(fi_params_original);
-    }
-
     return ExitCodes::EXECUTION_OK;

Also applies to: 766-771, 942-947

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

In `@src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp` around
lines 748 - 752, The fragment_index_ parameters saved in fi_params_original and
the fi_params_modified flag must be restored on every exit path (including early
returns/exceptions) instead of only on the happy path; wrap the save/restore in
a small RAII/scope-guard object (or use std::unique_ptr with custom deleter)
that captures fragment_index_ and fi_params_original and restores them in its
destructor, then replace the existing manual tail-restore code with this guard
wherever fragment_index_.getParameters() is saved (the blocks that set
fi_params_original/fi_params_modified around the calibration/PeptideIndexing
logic and the later similar blocks that mirror lines ~766-771 and ~942-947);
ensure the guard is created immediately after obtaining fi_params_original so it
runs for all exits.
🧹 Nitpick comments (1)
src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp (1)

1323-1324: Prefer '\n' over std::endl in the new calibration logs.

These added log lines force a flush each time. The repo guideline asks to avoid that in C++ logging paths.

As per coding guidelines, "Avoid std::endl for performance reasons; prefer \n in C++".

Also applies to: 1411-1413, 1458-1465

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

In `@src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp` around
lines 1323 - 1324, The new calibration log statements use std::endl which forces
a flush; replace std::endl with '\n' in all added OPENMS_LOG_INFO calls (e.g.,
the logging lines that print "[PDBS-FI] Calibration: scoring ..." and the
similar messages around the later blocks) to avoid unnecessary flushes—search
for OPENMS_LOG_INFO usages in PeptideSearchEngineFIAlgorithm (the
calibration/logging blocks around the newly added lines) and change << std::endl
to << '\n' for each occurrence.
🤖 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/PeptideSearchEngineFIAlgorithm.cpp`:
- Around line 1388-1395: The current selection uses
std::max(calibration_min_psms_, cal_hits.size() / 2) which can keep >50% of
cal_hits; change logic to strictly keep the top 50% (cal_hits.size() / 2) and
only apply that cropping when that 50% is at least calibration_min_psms_;
specifically compute Size keep = cal_hits.size() / 2; if (keep >=
calibration_min_psms_ && keep < cal_hits.size()) cal_hits.resize(keep);
otherwise leave cal_hits unchanged so the existing calibration_min_psms_
fallback can disable calibration as intended (refer to variables cal_hits,
CalHit, and calibration_min_psms_).

---

Duplicate comments:
In `@src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp`:
- Around line 748-752: The fragment_index_ parameters saved in
fi_params_original and the fi_params_modified flag must be restored on every
exit path (including early returns/exceptions) instead of only on the happy
path; wrap the save/restore in a small RAII/scope-guard object (or use
std::unique_ptr with custom deleter) that captures fragment_index_ and
fi_params_original and restores them in its destructor, then replace the
existing manual tail-restore code with this guard wherever
fragment_index_.getParameters() is saved (the blocks that set
fi_params_original/fi_params_modified around the calibration/PeptideIndexing
logic and the later similar blocks that mirror lines ~766-771 and ~942-947);
ensure the guard is created immediately after obtaining fi_params_original so it
runs for all exits.

---

Nitpick comments:
In `@src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp`:
- Around line 1323-1324: The new calibration log statements use std::endl which
forces a flush; replace std::endl with '\n' in all added OPENMS_LOG_INFO calls
(e.g., the logging lines that print "[PDBS-FI] Calibration: scoring ..." and the
similar messages around the later blocks) to avoid unnecessary flushes—search
for OPENMS_LOG_INFO usages in PeptideSearchEngineFIAlgorithm (the
calibration/logging blocks around the newly added lines) and change << std::endl
to << '\n' for each occurrence.
🪄 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: b677f345-00b0-418a-bc1d-59c45963b82a

📥 Commits

Reviewing files that changed from the base of the PR and between bcbdcb2 and 849e4c6.

📒 Files selected for processing (2)
  • src/openms/include/OpenMS/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.h
  • src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/openms/include/OpenMS/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.h

timosachsenberg and others added 6 commits April 10, 2026 11:05
…eSearchEngineFI

Add optional calibration pass (`-Search:calibration:enabled true`) that
estimates tighter precursor and fragment tolerances from a fast first-pass
search on a subset of spectra (default: top 10% by TIC).

The calibration uses NuXL-inspired percentile statistics:
- Precursor: 0.5th-99.5th percentile range (99% coverage)
- Fragment: 4 × 68th percentile (≈4σ, following NuXL/identipy convention)

Key architectural advantage: the FragmentIndex applies tolerances at query
time, not build time, so the calibration tightens tolerances WITHOUT
rebuilding the index — only the scoring pass is repeated with the
calibrated (typically much tighter) window.

This is similar in spirit to MSFragger's calibrate_mass=2 and OpenNuXL's
autotune feature, adapted for the FragmentIndex architecture.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…and median+MAD estimation

The initial percentile-based approach was sensitive to outlier PSMs (wrong
matches with huge precursor errors). Now:
- Filter calibration PSMs to top 50% by score (removes low-confidence matches)
- Discard PSMs with precursor error exceeding configured tolerance (removes
  clearly wrong matches that survived score filtering)
- Use median + 3*MAD of |precursor error| instead of 0.5th/99.5th percentiles
  (robust to remaining outliers, follows InternalCalibration.cpp pattern)

Validated on timsTOF DDA HeLa data: calibration tightens precursor tolerance
from 20 ppm to 9 ppm (median=3.35, MAD=1.82), yielding +604 PSMs (+11.4%)
at 1% FDR compared to the uncalibrated baseline.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Adds TOPP_PeptideDataBaseSearchFI_DDA_calibrated test that runs the same
timsTOF DDA HeLa search with -Search:calibration:enabled, followed by
FDR filtering. Validates the calibration code path in CI.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
1. Remove false fragment-shift claim from calibration:enabled help text
   (runCalibrationPass_ hardcodes fragment_shift=0.0, search() never
   applies a shift).

2. Remove std::ceil and 1.0 floor from tolerance estimation — these
   destroy sub-Da calibration (e.g. 0.02 Da). Use a tiny 1e-6 floor
   instead to avoid non-positive values while preserving precision.

3. Don't mutate shared SearchContext FragmentIndex — save original
   parameters before calibration, restore after the scoring loop. This
   prevents calibrated tolerances from persisting across multi-file
   searches sharing the same context.

4. (nitpick) Update CalibrationResult_ and runCalibrationPass_ comments
   to use Doxygen /** @brief */ block format per project convention.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Wrap fi_params restore in a lambda and call before all early-return
  paths (PeptideIndexing failures). Previously, returning early left
  the shared SearchContext's FragmentIndex permanently modified.
- Fix 68th percentile index: use (n-1)*0.68 instead of n*0.68 to
  correctly index into a 0-based sorted array.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The previous std::max(min_psms, n/2) could keep >50% of hits when
min_psms > n/2. Now: crop to top 50% only when that still meets the
minimum PSM threshold; otherwise leave all hits unchanged and let the
downstream min_psms check disable calibration as intended.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@timosachsenberg
timosachsenberg force-pushed the feat/fi-auto-calibration branch from 6c75fa2 to 6e5cfa4 Compare April 10, 2026 09:07
@timosachsenberg
timosachsenberg merged commit 1017611 into develop Apr 10, 2026
14 checks passed
@timosachsenberg
timosachsenberg deleted the feat/fi-auto-calibration branch April 10, 2026 09:24
github-actions Bot pushed a commit that referenced this pull request Apr 11, 2026
Add missing changelog entries for commits merged after the last sync:
- #9127: Fix LinearResampler right_index bounds clamping (intensity spike bug)
- #9126: CometAdapter Bruker .d DDA-PASEF input support
- #9121: PeptideDataBaseSearchFI runtime search diagnostics and tolerance estimation
- #9122: PeptideDataBaseSearchFI automatic mass accuracy calibration (two-pass search)
- #9123: PeptideDataBaseSearchFI protein-level FDR (picked-protein)
- #9129: OpenSwathWorkflow Bruker DIA MS2 frame aggregation, denoising, and streaming

Co-authored-by: Copilot <[email protected]>
timosachsenberg pushed a commit that referenced this pull request Apr 11, 2026
Add missing changelog entries for commits merged after the last sync:
- #9127: Fix LinearResampler right_index bounds clamping (intensity spike bug)
- #9126: CometAdapter Bruker .d DDA-PASEF input support
- #9121: PeptideDataBaseSearchFI runtime search diagnostics and tolerance estimation
- #9122: PeptideDataBaseSearchFI automatic mass accuracy calibration (two-pass search)
- #9123: PeptideDataBaseSearchFI protein-level FDR (picked-protein)
- #9129: OpenSwathWorkflow Bruker DIA MS2 frame aggregation, denoising, and streaming

Co-authored-by: GitHub Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
@github-actions github-actions Bot mentioned this pull request Apr 12, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Jun 16, 2026
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