Skip to content

[OSW,auto_iRT] Add priority peptides for sampling - #8373

Merged
timosachsenberg merged 7 commits into
OpenMS:developfrom
singjc:feature/auto_irt_priority_irt_sampling
Nov 18, 2025
Merged

timosachsenberg merged 7 commits into
OpenMS:developfrom
singjc:feature/auto_irt_priority_irt_sampling

Conversation

@singjc

@singjc singjc commented Nov 18, 2025 •

Copy link
Copy Markdown
Contributor

Description

This PR adds support for prioritizing specific peptide sequences during iRT peptide sampling in the OpenSwath workflow (when using -auto_irt). Users can specify a custom transition TSV file containing priority peptides, which will be sampled first (alongside the share/OpenMS/CHEMISTRY irtkit and cirtkit peptides), ensuring a set of peptides that are typically conserved/more likely to be present are included in the iRT sampling for calibration.

iRT Peptide Sampling Improvements

  • Added a new priority_peptides parameter to the sampleExperiment function, allowing users to specify peptide sequences that should be prioritized during sampling. Priority peptides are sampled first, followed by regular candidates to fill the remaining quota. [1] [2] [3] [4] [5]
  • Priority and regular candidate peptides are now sorted independently by intensity, and the sampling logic ensures that priority peptides are distributed across RT bins before regular peptides are considered.

Command-Line Interface & Configuration

  • Added a new CLI parameter tr_irt_priority_sampling to allow users to specify a custom TSV file containing priority peptides for iRT sampling. The workflow validates the existence and format of this file. [1] [2] [3]

Integration with Built-In Kits

  • When auto_irt is enabled, the workflow automatically loads built-in irtkit and cirtkit peptide sequences as priority peptides, and includes any user-specified custom priority file if provided.

Supporting Functions

  • Added a helper function loadPriorityPeptideSequences to load peptide sequences from one or more TSV files, used to aggregate all priority peptides for sampling.

Workflow Updates

  • Updated calls to sampleExperiment in the main workflow to pass the new priority_peptides parameter for both linear and nonlinear iRT calibration steps. [1] [2]

Checklist

  • Make sure that you are listed in the AUTHORS file
  • Add relevant changes and new features to the CHANGELOG file
  • I have commented my code, particularly in hard-to-understand areas
  • New and existing unit tests pass locally with my changes
  • Updated or added python bindings for changed or new classes (Tick if no updates were necessary.)

How can I get additional information on failed tests during CI

Click to expand If your PR is failing you can check out

Advanced commands (admins / reviewer only)

Click to expand
  • /reformat (experimental) applies the clang-format style changes as additional commit. Note: your branch must have a different name (e.g., yourrepo:feature/XYZ) than the receiving branch (e.g., OpenMS:develop). Otherwise, reformat fails to push.
  • setting the label "NoJenkins" will skip tests for this PR on jenkins (saves resources e.g., on edits that do not affect tests)
  • commenting with rebuild jenkins will retrigger Jenkins-based CI builds

⚠️ Note: Once you opened a PR try to minimize the number of pushes to it as every push will trigger CI (automated builds and test) and is rather heavy on our infrastructure (e.g., if several pushes per day are performed).

Summary by CodeRabbit

  • New Features
    • Priority peptide inclusion for automated iRT calibration: users can supply built-in or custom TSV priority lists; listed peptides are preferentially sampled if present.
    • New configuration option to specify priority TSV files; the tool logs files found and the count of loaded sequences, warns if none are available, and proceeds without priority peptides.

@coderabbitai

coderabbitai Bot commented Nov 18, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds priority-peptide support to automated iRT sampling: a new optional priority_peptides parameter to OpenSwathHelper::sampleExperiment, sampling now picks priority peptides first per RT bin, and TOPP OpenSwathWorkflow loads TSV priority lists and passes them into sampling.

Changes

Cohort / File(s) Change Summary
Changelog
CHANGELOG.md
Added feature note describing priority inclusion list for iRT sampling when using automated iRT calibration.
OpenSwath Helper API
src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathHelper.h
Added optional parameter priority_peptides (std::unordered_set<std::string>) to sampleExperiment() signature with a default empty set.
OpenSwath Helper Implementation
src/openms/source/ANALYSIS/OPENSWATH/OpenSwathHelper.cpp
Implemented two-phase sampling: split candidates into priority vs regular, sort priority by intensity, sample priority per RT bin first (with per-bin limits and deduplication), then fill remaining slots from regular candidates; update RT-range checks, logging, and error messages to use combined candidate pool.
Workflow Integration
src/topp/OpenSwathWorkflow.cpp
Added loadPriorityPeptideSequences() helper to read TSV priority files (built-ins and optional custom), validate inputs, log counts, and pass loaded priority sequences into both linear and nonlinear auto iRT sampling paths.

Sequence Diagram(s)

sequenceDiagram
    participant WF as OpenSwathWorkflow
    participant Helper as OpenSwathHelper
    participant Pool as Candidate Pool

    WF->>WF: loadPriorityPeptideSequences(irtkit.tsv, cirtkit.tsv, custom?)
    WF->>Helper: sampleExperiment(exp, bins, per_bin, ..., priority_peptides)
    Helper->>Pool: partition -> priority_candidates + regular_candidates
    rect rgb(220,245,220)
      note over Helper: Phase 1 — Priority sampling
      Helper->>Pool: sample priority per RT bin (dedupe by sequence)
      Helper->>Helper: mark picked sequences
    end
    rect rgb(240,240,255)
      note over Helper: Phase 2 — Fill remaining slots
      Helper->>Pool: sample from regular (skip already picked)
    end
    Helper-->>WF: return sampled LightTargetedExperiment
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Areas needing extra attention:
    • OpenSwathHelper::sampleExperiment two-phase logic (edge cases, deduplication, bin quotas)
    • Correct propagation of priority_peptides through both linear and nonlinear iRT paths
    • Duplicate occurrences of loadPriorityPeptideSequences logic for consolidation

Possibly related PRs

Suggested reviewers

  • timosachsenberg
  • jcharkow

Poem

🐰 I hopped through TSVs and peptide rows,

I nudged the top ones up where their priority grows,
Per bin I pick first the seeds you chose,
Then fill the gaps where the sampler goes,
Calibrated hops — precise as my nose.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ 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 clearly and concisely summarizes the main change: adding priority peptides support for sampling in the OpenSwath auto_iRT workflow.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b08edaa and 7b25bcd.

📒 Files selected for processing (1)
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathHelper.cpp (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/openms/**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathHelper.cpp
🧠 Learnings (1)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathHelper.cpp
🧬 Code graph analysis (1)
src/openms/source/ANALYSIS/OPENSWATH/OpenSwathHelper.cpp (2)
src/openms/source/CONCEPT/Exception.cpp (1)
  • IllegalArgument (247-250)
src/openms/include/OpenMS/MATH/MathFunctions.h (1)
  • seed (501-504)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
  • GitHub Check: build-lnx-arm
  • GitHub Check: build-macos
  • GitHub Check: build-lnx
  • GitHub Check: build-win
  • GitHub Check: build-macos-arm
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (ubuntu-22.04-arm, g++, 11)
  • GitHub Check: build-and-test (macos-26, xcode, 26.0)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-15-intel, xcode, 16.0.0)
🔇 Additional comments (6)
src/openms/source/ANALYSIS/OPENSWATH/OpenSwathHelper.cpp (6)

176-177: Well-designed API extension for priority peptide support.

The addition of the priority_peptides parameter using std::unordered_set provides O(1) lookup performance for membership checks during sampling. Passing by const reference is efficient and follows best practices.


184-209: Correct candidate separation logic.

The partitioning of compounds into priority_candidates and candidates is clean and efficient. Decoy filtering is correctly preserved, and the early separation makes the subsequent two-phase sampling logic straightforward.


212-237: Correct intensity-based sorting with differential treatment.

The implementation correctly sorts both candidate pools by intensity while applying different trimming strategies: regular candidates are trimmed to top_fraction, but priority candidates are preserved in full. This ensures user-specified priority peptides remain available regardless of their library intensities, which aligns with the feature's intent.


239-259: Correct validation and RT range estimation using combined candidate pool.

The combined pool approach ensures that RT range estimation accounts for both priority and regular candidates, which is necessary for accurate bin boundaries. The error handling correctly reports the total available candidates when insufficient candidates are present.


262-302: Well-implemented priority peptide sampling with proper deduplication.

The first-pass sampling correctly:

  • Tracks picked sequences to prevent duplicate sampling across phases
  • Maintains per-bin quotas by sampling up to peptides_per_bin from each bin
  • Uses portable random shuffling for reproducibility
  • Provides informative logging for observability

The sequence-based deduplication is appropriate for iRT sampling, where the goal is to avoid sampling the same peptide sequence multiple times regardless of charge state or modifications.


304-348: Correct second-pass sampling that respects per-bin quotas.

The regular candidate sampling correctly:

  • Calculates per-bin needs by accounting for priority peptides already sampled in each bin
  • Enforces cross-phase deduplication by checking picked_sequences
  • Gracefully handles bins with insufficient regular candidates by taking min(needed, bucket.size())
  • Maintains the overall constraint that each bin should have up to peptides_per_bin total

The implementation correctly handles the edge case where the total number of picked peptides may fall short of the quota if regular candidates are sparse in certain bins, which is acceptable given the priority and per-bin constraints.


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.

…ingjc/OpenMS into feature/auto_irt_priority_irt_sampling

@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: 0

Caution

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

⚠️ Outside diff range comments (2)
src/topp/OpenSwathWorkflow.cpp (1)

1092-1099: Nonlinear iRT top_fraction constant disagrees with the comment

In the nonlinear auto-iRT path you log:

  • Comment (lines 1095–1098): “we set top fraction to 80% …”
  • Actual call (lines 1100–1107): OpenSwathHelper::sampleExperiment(..., /*top_fraction=*/0.7, priority_peptides);

If the intent is indeed to use the top 80% of intense peptides, top_fraction should be 0.8. If 70% is the new intended behavior, the explanatory comment (and any external docs that mention 80%) should be updated accordingly to avoid confusion.

-        0.7,
+        0.8,

(or adjust the comment if 0.7 is desired).

Also applies to: 1100-1107

src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathHelper.h (1)

185-213: Add explicit <unordered_set> include to OpenSwathHelper.h

Verification confirms the issue. OpenSwathHelper.h declares std::unordered_set<std::string> on line 212 but does not include <unordered_set>. None of the currently included OpenMS headers provide this include transitively.

Additionally, OpenSwathHelper.cpp includes this header at line 11 before including <unordered_set> at line 13, which will cause a compilation error when the header tries to use the unordered_set type.

Other OpenMS headers in the same codebase (QTClusterFinder.h, IDScoreGetterSetter.h, IDMergerAlgorithm.h, FalseDiscoveryRate.h) explicitly include <unordered_set> when using it, establishing the correct pattern.

Add the include as suggested:

 #include <OpenMS/KERNEL/StandardTypes.h>
 #include <OpenMS/KERNEL/MSExperiment.h>
 #include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
 #include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h>
 #include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h>
 #include <OpenMS/CONCEPT/LogStream.h>
+#include <unordered_set>
🧹 Nitpick comments (3)
src/topp/OpenSwathWorkflow.cpp (2)

396-398: Priority iRT sampling parameter and wiring look good; consider two behavioral tweaks

The new Calibration:tr_irt_priority_sampling option and the associated validation and wiring into auto-iRT sampling are coherent overall (TSV-only, existence check, usage when auto_irt is enabled, and loading via loadPriorityPeptideSequences). Two points to consider:

  1. Validation even when auto_irt is disabled (lines 713–714, 788–804)
    The priority file is validated unconditionally. This means a user can hit a fatal “must be TSV / does not exist” error even if auto_irt is false and the file will never be used. To avoid surprising failures, you could gate the validation on auto_irt:

  • // Validate priority iRT sampling file format if provided
  • if (!priority_sampling_irt_tr_file.empty())
  • // Validate priority iRT sampling file format if provided and used
  • if (auto_irt && !priority_sampling_irt_tr_file.empty())

2. **TSV reader parameters for priority files (lines 1004–1051)**  
`loadPriorityPeptideSequences` is called with `TransitionTSVFile().getDefaults()` rather than the user-tuned `Library:` parameters used for the main `-tr` file. If users customize their TSV column mapping for the main library and expect the same layout for the priority TSV, this might be surprising.

If you intend the priority TSV to share the same schema as the main library, consider reusing `tsv_reader_param` here instead of a fresh defaults object. If you intentionally want a fixed, canonical TSV layout for priority lists, it might be worth calling that out more explicitly in the parameter doc string.



Also applies to: 713-714, 788-804, 1004-1051

---

`609-661`: **`loadPriorityPeptideSequences`: solid helper; optional refinements**

The helper cleanly loads multiple priority TSV-like files, deduplicates by `compound.sequence`, and degrades gracefully on missing/failed files with WARN logs rather than hard failures. That’s a good fit for an optional priority feature.

Two optional refinements you may want to consider:

- **Decoy filtering**: If any of the input files can contain decoy compounds, you might want to mirror the main sampling logic and ignore decoys when building `priority_sequences` to avoid prioritizing decoy-only sequences by accident (e.g., by checking a decoy flag on transitions and cross-filtering compounds before insertion, if available for these files).

- **Log loaded unique sequences per file**: Currently you log total compounds per file (line 647–648) and a global unique count (657–658). If you care about how many unique sequences actually contributed from each file (especially when there are duplicates across irtkit/cirtkit/custom), you could also log per-file unique sequence counts, but that’s purely diagnostic sugar.

Overall, the function is clear and robust as-is.

</blockquote></details>
<details>
<summary>src/openms/source/ANALYSIS/OPENSWATH/OpenSwathHelper.cpp (1)</summary><blockquote>

`169-377`: **Priority-aware sampling logic looks consistent with intended behavior**

The extended `sampleExperiment` implementation correctly integrates priority peptides:

- Decoy filtering is preserved via `good_ids`.
- Compounds are partitioned into `priority_candidates` vs regular `candidates` based on exact `cmp.sequence` membership in `priority_peptides`.
- Intensity-based ranking and `top_fraction` are applied only to regular candidates, ensuring priority peptides are not trimmed away.
- RT binning and `all_candidates` ensure the RT span is computed from everything that is eligible for sampling, with a sanity check requiring at least 3 candidates.
- The two-phase per-bin sampling (priority-first, then regular to fill remaining per-bin quota) together with `picked_sequences` keeps the total selected peptides bounded by `bins * peptides_per_bin` and avoids reusing the same sequence across bins.

One behavioral nuance worth keeping in mind: matching is done on the raw `LightCompound::sequence` string, so priority peptides must use exactly the same sequence representation (including any modification encoding and case) as the main library to be recognized.

Otherwise, this looks well factored and in line with the described priority sampling design.

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used**: CodeRabbit UI

**Review profile**: CHILL

**Plan**: Pro

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between f870cf00913ff4adf8ad43daaf668066ab30b120 and b08edaaedbf792808a2021613c0305f66d22fcd6.

</details>

<details>
<summary>📒 Files selected for processing (4)</summary>

* `CHANGELOG` (1 hunks)
* `src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathHelper.h` (2 hunks)
* `src/openms/source/ANALYSIS/OPENSWATH/OpenSwathHelper.cpp` (3 hunks)
* `src/topp/OpenSwathWorkflow.cpp` (7 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>📓 Path-based instructions (2)</summary>

<details>
<summary>src/openms/**/*.{cpp,h,hpp,cc,cxx}</summary>


**📄 CodeRabbit inference engine (.github/copilot-instructions.md)**

> `src/openms/**/*.{cpp,h,hpp,cc,cxx}`: Follow the existing C++ coding conventions in the codebase
> Use the established naming patterns for classes, methods, and variables
> Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
> Follow the established error handling patterns
> Utilize OpenMS logging mechanisms
> Be mindful of memory usage when processing large datasets
> Consider algorithmic complexity for data processing operations
> Use appropriate OpenMS containers and algorithms

Files:
- `src/openms/source/ANALYSIS/OPENSWATH/OpenSwathHelper.cpp`
- `src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathHelper.h`

</details>
<details>
<summary>src/openms/include/OpenMS/**/*.h</summary>


**📄 CodeRabbit inference engine (.github/copilot-instructions.md)**

> Add Doxygen comments for new public methods and classes

Files:
- `src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathHelper.h`

</details>

</details><details>
<summary>🧠 Learnings (2)</summary>

<details>
<summary>📚 Learning: 2025-08-05T12:43:11.681Z</summary>

Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)


**Applied to files:**
- `src/openms/source/ANALYSIS/OPENSWATH/OpenSwathHelper.cpp`
- `src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathHelper.h`

</details>
<details>
<summary>📚 Learning: 2025-08-29T19:09:45.997Z</summary>

Learnt from: jcharkow
Repo: OpenMS/OpenMS PR: 8188
File: src/topp/OpenSwathWorkflow.cpp:1118-1123
Timestamp: 2025-08-29T19:09:45.997Z
Learning: In OpenMS OpenSwathWorkflow, the use_ms1_ion_mobility parameter should be respected when applying estimated MS1 ion mobility extraction windows. The apply_window calls for MS1 ion mobility should check both pasef AND use_ms1_ion_mobility to avoid re-enabling disabled functionality.


**Applied to files:**
- `src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathHelper.h`

</details>

</details><details>
<summary>🧬 Code graph analysis (2)</summary>

<details>
<summary>src/openms/source/ANALYSIS/OPENSWATH/OpenSwathHelper.cpp (2)</summary><blockquote>

<details>
<summary>src/openms/source/CONCEPT/Exception.cpp (1)</summary>

* `IllegalArgument` (247-250)

</details>
<details>
<summary>src/openms/include/OpenMS/MATH/MathFunctions.h (1)</summary>

* `seed` (501-504)

</details>

</blockquote></details>
<details>
<summary>src/topp/OpenSwathWorkflow.cpp (1)</summary><blockquote>

<details>
<summary>src/openms/source/APPLICATIONS/OpenSwathBase.cpp (2)</summary>

* `loadTransitionList` (211-246)
* `loadTransitionList` (211-213)

</details>

</blockquote></details>

</details>

</details>

<details>
<summary>🔇 Additional comments (1)</summary><blockquote>

<details>
<summary>CHANGELOG (1)</summary><blockquote>

`85-85`: **LGTM! Changelog entry is accurate and well-formatted.**

The changelog entry appropriately summarizes the new priority peptide feature for iRT sampling. The description is clear, follows the established format, and correctly references PR #8373.

</blockquote></details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants