Skip to content

(feat,osw): Port pyprophet inference context methods - #9280

Merged
timosachsenberg merged 28 commits into
OpenMS:developfrom
singjc:add/pyprophet_inference_contexts
May 15, 2026
Merged

timosachsenberg merged 28 commits into
OpenMS:developfrom
singjc:add/pyprophet_inference_contexts

Conversation

@singjc

@singjc singjc commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR ports over the peptidoform, peptide, protein and gene inference methods implemented in PyProphet for OpenSWATH analysis. The changes add new data structures, configuration options, and core inference classes, as well as extending the OSWFile interface to read and write inference data.

Main changes:

1. New inference data structures and configuration:

  • Added OpenSwathInferenceData.h defining inference levels, contexts, and row types for peptidoform, peptide, protein, and gene inference, including helper functions for string conversion.
  • Added OpenSwathInferenceConfig.h with configuration structs for error estimation and inference at different levels, closely mirroring PyProphet CLI defaults.

2. Core inference classes:

  • Introduced PeptidoformInference, PeptideInference, ProteinInference, GeneInference, and LevelContextInference classes, each encapsulating logic for their respective inference tasks and exposing clear interfaces for statistical estimation. [1] [2] [3] [4] [5]

3. OSW file interface extensions:

  • Extended OSWFile to support reading and writing of all new inference data types and results, and to provide run/basename mapping utilities. [1] [2] [3]

4. Build system integration:

  • Updated sources.cmake to include all new headers for compilation and installation. [1] [2] [3]

5. Documentation:

  • Added new tool documentation entry for TOPP_OpenSwathInfer.

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

    • New OpenSwathInfer tool to run peptidoform, peptide, protein and gene inference across global/experiment/run contexts; summarizes results at 1% FDR.
    • OSW read/write support for inference evidence and results, plus run-basename handling.
  • Tests

    • Added unit and integration tests covering inference algorithms, IO, and edge cases.
  • Documentation

    • Updated TOPP and changelog entries for the new tool and inference features.

singjc and others added 16 commits May 7, 2026 21:46
…, and gene-level context inference

Co-authored-by: Copilot <[email protected]>
…ptidoform, and level contexts

Co-authored-by: Copilot <[email protected]>
…eInference, PeptidoformInference, and ProteinInference to sources list
…ference, and PeptidoformInference

Co-authored-by: Copilot <[email protected]>
…OpenMS into add/pyprophet_inference_contexts
…ameters for error estimation and context inference

Co-authored-by: Copilot <[email protected]>
@github-actions

github-actions Bot commented May 9, 2026

Copy link
Copy Markdown
Contributor

@singjc The following names might be missing from the AUTHORS file:

  • Justin Sing

  • singjc

Please consider applying the following patch:

--- AUTHORS	2026-05-09 01:58:40.283853501 +0000
+++ AUTHORS.new	2026-05-09 01:58:45.337413289 +0000
@@ -109,6 +109,7 @@
  - Sandro Andreotti
  - Santhil
  - Simon Gene Gottlieb
+ - singjc
  - Steffen Sass
  - Stephan Aiche
  - Sven Nahnsen

@coderabbitai

coderabbitai Bot commented May 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

This PR adds OpenSWATH multi-level inference: data contracts and configs, peptidoform Bayesian inference, level-context error-estimation, OSW SQLite readers/writers, a TOPP tool (OpenSwathInfer) to run tasks, tests, and CMake/docs updates.

Changes

OpenSWATH Multi-Level Inference System

Layer / File(s) Summary
Data Structures and Enums
src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathInferenceData.h
Enums InferenceLevel/InferenceContext with toString helpers and IPF/level-context row structs.
Configuration Structures
src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathInferenceConfig.h
ErrorEstimationConfig, PeptidoformInferenceConfig, LevelContextInferenceConfig with defaults and fields for pi0/LFDR and IPF controls.
Level-Context Inference
src/openms/include/.../LevelContextInference.h, src/openms/source/.../LevelContextInference.cpp
Static infer() builds error statistics from target/decoy scores, computes pvalue/qvalue/pep, supports global/experiment/run-specific grouping and nearest-cutoff projection.
Peptidoform Inference API
src/openms/include/.../PeptidoformInference.h
Declares BayesianModelRow/PosteriorRow and methods: computeModelFDR, preparePrecursorBM, applyBM, precursorInference, infer.
Peptidoform Inference Implementation
src/openms/source/.../PeptidoformInference.cpp
Implements precursor inference, transition hypothesis expansion (H0 handling), optional cross-run propagation by alignment group, Bayesian application, posterior→PEP conversion, and grouped/global q-value computation.
Wrapper Classes
src/openms/include/.../PeptideInference.h, .../PeptideInference.cpp, .../OpenSwathProteinInference.h, .../OpenSwathProteinInference.cpp, .../GeneInference.h, .../GeneInference.cpp
Level-specific wrappers validate config.level and delegate to LevelContextInference.
OSW Database I/O
src/openms/include/OpenMS/FORMAT/OSWFile.h, src/openms/source/FORMAT/OSWFile.cpp
Adds readIPFPrecursorData, readIPFTransitionData, readIPFAlignmentData (overloads), writeIPFResults, readLevelContextData, writeLevelContextResults, and readRunBasenames with SQLite helpers and transactions.
TOPP Command-Line Tool
src/topp/OpenSwathInfer.cpp
New TOPP tool OpenSwathInfer orchestrates enabled inference tasks, registers CLI/INI options for peptidoform/peptide/protein/gene inference per context, manages working output OSW, and logs per-task summary statistics.
Build Configuration
src/openms/include/.../sources.cmake, src/openms/source/.../sources.cmake, src/topp/executables.cmake, src/tests/class_tests/openms/executables.cmake
CMake lists updated to include new headers, sources, TOPP executable, and test executables.
Tool Registry & Docs
src/openms/source/APPLICATIONS/ToolHandler.cpp, doc/doxygen/public/TOPP.doxygen, CHANGELOG
Register OpenSwathInfer in tool registry and TOPP Doxygen listing; add changelog entry.
Unit and Integration Tests
src/tests/class_tests/openms/source/LevelContextInference_test.cpp, OSWFileInference_test.cpp, PeptidoformInference_test.cpp
Tests for inference behavior (empty/global/run-specific/experiment-wide), peptidoform Bayesian model and propagation, OSWFile reader/writer persistence and thresholds, and KernelDensityEstimation degenerate-case fallback.
Supporting Fix
src/openms/source/MATH/STATISTICS/KernelDensityEstimation.cpp, src/tests/class_tests/openms/source/KernelDensityEstimation_test.cpp
bwNrd0 fallback chain updated for degenerate inputs and covered by a new test.

Possibly related PRs

Suggested labels

enhancement, Review effort [1-5]: 3

Suggested reviewers

  • jpfeuffer

"🐰 I hopped through rows and cutoffs bright,
I nudged priors gently toward the light,
Across runs and genes the posteriors sing,
Now peptidoforms dance — let statistics spring!"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.53% 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
Title check ✅ Passed The PR title '(feat,osw): Port pyprophet inference context methods' clearly and specifically describes the main change: porting PyProphet's inference context methods to the OpenSWATH module. The title is concise, uses appropriate conventions (feat type prefix), and accurately reflects the changeset's primary objective.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (8)
src/openms/include/OpenMS/ANALYSIS/OPENSWATH/ProteinInference.h (2)

24-30: ⚡ Quick win

Three near-identical wrapper classes — consider consolidating.

ProteinInference, PeptideInference, and GeneInference are stateless classes whose infer(...) const methods only differ in a single config.level == InferenceLevel::{Protein,Peptide,Gene} precondition before delegating to LevelContextInference::infer. This duplicates three header/source pairs and adds ABI surface for no behavioral benefit, since the actual dispatch is already driven by config.level.

Possible consolidations:

  • Drop the wrappers and call LevelContextInference::infer directly from OpenSwathInfer.cpp (the level is already in config.level).
  • Or keep one entry point and expose three static helpers (inferPeptide/inferProtein/inferGene) on LevelContextInference that set/check the level and forward.

Either avoids the maintenance burden of keeping three header/source/sources.cmake entries in sync. Also note the methods are currently non-static const on stateless classes — if the wrappers are kept, prefer static to match LevelContextInference::infer.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/include/OpenMS/ANALYSIS/OPENSWATH/ProteinInference.h` around lines
24 - 30, The three near-identical wrapper classes ProteinInference,
PeptideInference, and GeneInference duplicate ABI and logic; consolidate by
removing two wrappers and either call LevelContextInference::infer(...) directly
from OpenSwathInfer.cpp (since config.level already drives behavior) or
implement a single entrypoint (e.g., keep one wrapper or add three static
helpers on LevelContextInference like inferProtein/inferPeptide/inferGene) that
validate config.level and forward to LevelContextInference::infer; if you keep
wrappers, make their infer methods static (not instance const) to reflect
stateless behavior and remove the extra header/source/sources.cmake entries.

27-29: 💤 Low value

Add [in] parameter direction tags.

Single-line /// doc lacks parameter direction annotations and the @throws Exception::Precondition thrown for mismatched config.level. Same applies to the sibling PeptideInference.h and GeneInference.h. As per coding guidelines: "Use [in], [out], or [in,out] parameter direction tags for all Doxygen parameters".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/include/OpenMS/ANALYSIS/OPENSWATH/ProteinInference.h` around lines
27 - 29, Update the Doxygen comment for the method infer in class
ProteinInference (function signature infer(const
std::vector<LevelContextInputRow>& input, const LevelContextInferenceConfig&
config) const) to include parameter direction tags for both parameters (e.g.,
`@param[in] input` and `@param[in] config`) and add the `@throws
Exception::Precondition` clause documenting the mismatch case for
`config.level`; apply the same change to the corresponding infer declarations in
PeptideInference.h and GeneInference.h so all three headers include `[in]` tags
and the throws annotation.
src/tests/class_tests/openms/source/OSWFileInference_test.cpp (1)

37-47: 💤 Low value

scalarInt64_ should bail when sqlite3_step does not yield a row.

TEST_EQUAL in OpenMS class tests is non-fatal, so when sqlite3_step returns anything other than SQLITE_ROW the helper still calls sqlite3_column_int64 on a non-data statement and returns 0. That can silently mask query/schema regressions (a legitimate failure becomes a 0 == expected mismatch with no diagnostic). Returning a sentinel/throwing on non-ROW makes the failure mode obvious.

🛡️ Proposed fix
   Int64 scalarInt64_(const String& filename, const String& query)
   {
     SqliteConnector conn(filename, SqliteConnector::SqlOpenMode::READ_ONLY);
     sqlite3_stmt* stmt = nullptr;
     conn.prepareStatement(&stmt, query);
     const int state = sqlite3_step(stmt);
     TEST_EQUAL(state, SQLITE_ROW)
-    const Int64 value = sqlite3_column_int64(stmt, 0);
+    const Int64 value = (state == SQLITE_ROW) ? sqlite3_column_int64(stmt, 0) : Int64{-1};
     sqlite3_finalize(stmt);
     return value;
   }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/class_tests/openms/source/OSWFileInference_test.cpp` around lines
37 - 47, The helper scalarInt64_ currently calls sqlite3_column_int64 even when
sqlite3_step(stmt) != SQLITE_ROW (TEST_EQUAL is non-fatal), which can mask
failures; update scalarInt64_ to check the step result and if it is not
SQLITE_ROW immediately finalize the statement and fail fast (either throw a
descriptive exception or use a fatal test macro) instead of returning 0,
ensuring sqlite3_finalize(stmt) is always called before bailing; reference
sqlite3_step, sqlite3_column_int64, sqlite3_finalize, and TEST_EQUAL in your
changes.
src/openms/include/OpenMS/ANALYSIS/OPENSWATH/LevelContextInference.h (1)

31-55: ⚡ Quick win

Document parameter directions and exception contract.

The Doxygen block lacks [in] direction tags on @param and does not list the precondition exceptions thrown by the implementation. The implementation in LevelContextInference.cpp throws Exception::Precondition for InferenceLevel::Peptidoform, for missing run_id in run-specific mode, and for empty/all-NaN target/decoy distributions — none of these are visible from the header. As per coding guidelines: "Use [in], [out], or [in,out] parameter direction tags for all Doxygen parameters" and "Document possible exceptions in Doxygen comments using @throws or @exception tags".

📝 Proposed Doxygen update
-      `@param` input Compact input rows selected for one inference level
-      `@param` config Inference and error-estimation configuration
-
-      `@return` Result rows containing the original entity and score plus derived
-              p-value, q-value, and PEP estimates
+      `@param`[in] input Compact input rows selected for one inference level
+      `@param`[in] config Inference and error-estimation configuration
+
+      `@return` Result rows containing the original entity and score plus derived
+              p-value, q-value, and PEP estimates
+
+      `@throws` Exception::Precondition if `@p` config.level is InferenceLevel::Peptidoform,
+              if `@p` config.context is RunSpecific and any input row is missing a run_id,
+              or if the target/decoy score distribution is empty / contains only non-finite values.
     */
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/include/OpenMS/ANALYSIS/OPENSWATH/LevelContextInference.h` around
lines 31 - 55, Update the Doxygen for LevelContextInference::infer to mark
parameters with direction tags (e.g., `@param` [in] input and `@param` [in] config)
and add `@throws/`@exception entries documenting the precondition violations
thrown by the implementation: Exception::Precondition for when config.level ==
InferenceLevel::Peptidoform, for missing/empty RUN_ID when config.mode is
run-specific, and for empty or all-NaN target/decoy score distributions;
reference the classes/types LevelContextInputRow and LevelContextInferenceConfig
in the descriptions so callers can locate the preconditions.
src/openms/source/ANALYSIS/OPENSWATH/LevelContextInference.cpp (2)

117-203: ⚡ Quick win

Dead computation: statMetrics_ results are discarded, and its inner fdr/fnr/tn locals are never stored.

statMetrics_ produces a Metrics struct whose only field (svalues) is computed but the call at line 281 throws the result away with (void)statMetrics_(...). Inside the loop (lines 138-191), fdr, fnr, and tn are recomputed every iteration, never written to any output container, and tn is even silenced with (void)tn;. The retained comment ("Keep the PyProphet metric construction order even though only p/q/pep are returned") acknowledges this is intentional for porting fidelity, but it leaves dead numerics in a hot path of the new inference and obscures what the function actually contributes.

Recommend either:

  1. Drop the line 281 call entirely (and remove statMetrics_/Metrics if no caller remains), since pvalues/qvalues/peps are already produced by Math::MultipleTesting::qValue/lfdr.
  2. Or, if s-values are needed for parity with PyProphet output, propagate them through ErrorStatistics and the public LevelContextResultRow instead of computing-and-discarding.

Either way, the unused fdr/fnr/tn arithmetic and the (void)tn; line should go.

Also applies to: 280-281

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/ANALYSIS/OPENSWATH/LevelContextInference.cpp` around lines
117 - 203, The call to statMetrics_ and its internal fdr/fnr/tn math are dead:
statMetrics_ (and Metrics) only fills svalues but its result is discarded where
invoked, while fdr/fnr/tn are never stored (tn even silenced). Either remove the
unused call and delete statMetrics_/Metrics (and any dead math in
LevelContextInference) if you rely solely on Math::MultipleTesting::qValue/lfdr
for p/q/pep, or modify ErrorStatistics and LevelContextResultRow to carry the
svalues produced by statMetrics_ so the function's results are propagated; in
both cases eliminate the unused per-iteration computations (fdr/fnr/tn and the
“(void)tn;” line) from statMetrics_ if you choose removal or refactor them into
stored fields if you choose propagation.

337-389: ⚖️ Poor tradeoff

Run-specific grouping triple-copies input rows.

input → indexed_rows (vector of pair<Size, LevelContextInputRow>) → grouped_rows (map<Int64, vector<pair<Size, LevelContextInputRow>>>). For large peptide/protein inference workloads this materializes the entire input three times in memory. A vector of indices grouped per run_id (or storing pointers/reference_wrapper in indexed_rows) achieves the same and avoids the copies.

Minor since correctness is unaffected and the rows are compact, but worth tightening if inference is run on whole-experiment OSW DBs.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/ANALYSIS/OPENSWATH/LevelContextInference.cpp` around lines
337 - 389, The code currently copies LevelContextInputRow into indexed_rows and
then again into grouped_rows, tripling memory; change this to group indices
(Size) or pointers instead: in LevelContextInference::infer replace indexed_rows
(vector<pair<Size, LevelContextInputRow>>) with a vector<Size> (or
vector<pair<Size, const LevelContextInputRow*>>) and build grouped_rows as
map<Int64, vector<Size>> (or vector<const LevelContextInputRow*>), then modify
or overload assignErrorStatistics_ (referenced by name assignErrorStatistics_)
to accept the new index/pointer-based grouping along with the original input
vector so it can look up rows by index (use the existing results vector and
config.error unchanged); ensure run-specific validation still checks run_id via
input[index] and update the try/catch that reports RUN_ID to use the index-based
grouping.
src/tests/class_tests/openms/source/LevelContextInference_test.cpp (1)

179-182: ⚡ Quick win

Use the test framework’s numeric assertions instead of booleanized std::fabs checks.

These assertions bypass the active tolerance helpers and make failures harder to diagnose. Please use TEST_REAL_SIMILAR with the appropriate tolerance settings here, or FuzzyDiff if you want fixture-style fuzzy matching.

As per coding guidelines "Use FuzzyDiff for numeric comparisons in tests; use whitelist for unstable lines."

Also applies to: 204-207, 220-220

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/class_tests/openms/source/LevelContextInference_test.cpp` around
lines 179 - 182, The test uses booleanized fabs checks for numeric comparisons
(peptide_row->score, peptide_row->pvalue, peptide_row->qvalue, peptide_row->pep)
which bypass the framework's tolerance helpers; replace each
TEST_EQUAL(std::fabs(...) < tol, true) with the test framework's numeric
assertion (e.g. TEST_REAL_SIMILAR or the FuzzyDiff helper) using appropriate
tolerances (match the existing tol values like 1e-8 and 5e-4) so failures show
diffs; apply the same replacement pattern for the other occurrences flagged (the
checks around the peptide_row fields at lines noted in the comment).
src/openms/include/OpenMS/FORMAT/OSWFile.h (1)

112-142: ⚡ Quick win

Document the new OSW inference API with full Doxygen blocks.

These are new public header methods, but they currently only have short /// summaries. Please switch them to /** ... */ docs with @brief, @param[in], @return, and any relevant @throws so the generated API docs stay complete and consistent.

As per coding guidelines "Add Doxygen comments for new public methods and classes" and "Include parameter direction tags [in], [out], [in,out] for all Doxygen method parameters."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/include/OpenMS/FORMAT/OSWFile.h` around lines 112 - 142, Convert
the short "///" summaries for the new public methods into full Doxygen blocks
using "/** ... */" and include `@brief`, `@param`[in] (or [out]/[in,out] where
applicable), `@return` and any relevant `@throws` tags; specifically update
readIPFPrecursorData(const PeptidoformInferenceConfig& config),
readIPFTransitionData(const PeptidoformInferenceConfig& config),
readIPFAlignmentData(const PeptidoformInferenceConfig& config), the historical
overload readIPFAlignmentData(double ipf_max_alignment_pep),
writeIPFResults(const String& output_filename, const std::vector<IPFResultRow>&
results), readLevelContextData(InferenceLevel level, InferenceContext context),
writeLevelContextResults(const String& output_filename, InferenceLevel level,
InferenceContext context, const std::vector<LevelContextResultRow>& results) and
readRunBasenames(); for each comment add a short `@brief` describing the purpose,
`@param`[in] entries for all input parameters (note `@param`[out] only if returning
via arguments), `@return` describing the returned container and contents, and
`@throws` if the method can raise exceptions (e.g. IO or DB errors) so the public
API docs are complete and consistent with the project's Doxygen conventions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/openms/source/ANALYSIS/OPENSWATH/PeptidoformInference.cpp`:
- Around line 48-57: The code incorrectly treats row.feature_id ==
row.alignment_group_id as a sentinel for “no alignment group”; change the
sentinel to a dedicated marker (e.g. alignment_group_id < 0) or make
alignment_group_id optional so real DENSE_RANK group IDs aren’t conflated with
feature IDs. Update the checks around row.feature_id and row.alignment_group_id
(both the block that pushes to result vs grouped_rows and the similar check at
lines ~379-381) to test the new sentinel (e.g. if alignment_group_id is missing
or <0 then result.push_back(row) else
grouped_rows[alignment_group_id].push_back(&row)); ensure any code that
constructs rows sets the reserved negative value or the optional explicitly for
“no group.”
- Around line 191-202: The fallback currently inserts synthetic bm_rows with
impossible evidence (true-state evidence = 0.0), which
applyBM()/precursorInference() treats as a forced-zero posterior; change the
synthetic evidence to neutral values instead of impossible ones: in the block
that pushes into bm_rows (using variables rows, missing_rows_added, bm_rows)
replace the hard-coded 0.0 and 1.0 evidence entries with a neutral probability
(e.g. 0.5) for both true and false synthetic rows so the fallback provides
non-informative/neutral evidence rather than excluding the feature.

In `@src/openms/source/FORMAT/OSWFile.cpp`:
- Around line 63-106: The readers currently call createIPFIndexes_ and
createLevelContextIndexes_ which call tryCreateIndexIfTableExists_ and reopen
the DB as READWRITE, mutating input OSWs; change the behavior so read-only read*
APIs never create indexes: either (A) make createIPFIndexes_ and
createLevelContextIndexes_ no-ops when the SqliteConnector reports read-only
(add and use a isReadOnly()/isReadOnlyMode flag on SqliteConnector or check its
open mode), or (B) move all index creation out of these readers into an explicit
update/upgrade path (e.g., a new ensureIndexesForWrite()/upgradeIndexes
function) that callers invoke only when they intend to write; update
tryCreateIndexIfTableExists_ to respect the read-only flag and return without
executing DDL when read-only.
- Around line 818-821: The code currently calls
requireTable_("SCORE_TRANSITION") when either config.ipf_ms1_scoring or
config.ipf_ms2_scoring is true, which incorrectly blocks MS1-only runs; change
the precondition to only require the SCORE_TRANSITION table when MS2 scoring is
enabled (i.e., when config.ipf_ms2_scoring is true) by updating the if condition
that wraps the requireTable_ call in OSWFile.cpp so it checks
config.ipf_ms2_scoring (or config.ipf_ms1_scoring && config.ipf_ms2_scoring)
instead of config.ipf_ms1_scoring || config.ipf_ms2_scoring.

---

Nitpick comments:
In `@src/openms/include/OpenMS/ANALYSIS/OPENSWATH/LevelContextInference.h`:
- Around line 31-55: Update the Doxygen for LevelContextInference::infer to mark
parameters with direction tags (e.g., `@param` [in] input and `@param` [in] config)
and add `@throws/`@exception entries documenting the precondition violations
thrown by the implementation: Exception::Precondition for when config.level ==
InferenceLevel::Peptidoform, for missing/empty RUN_ID when config.mode is
run-specific, and for empty or all-NaN target/decoy score distributions;
reference the classes/types LevelContextInputRow and LevelContextInferenceConfig
in the descriptions so callers can locate the preconditions.

In `@src/openms/include/OpenMS/ANALYSIS/OPENSWATH/ProteinInference.h`:
- Around line 24-30: The three near-identical wrapper classes ProteinInference,
PeptideInference, and GeneInference duplicate ABI and logic; consolidate by
removing two wrappers and either call LevelContextInference::infer(...) directly
from OpenSwathInfer.cpp (since config.level already drives behavior) or
implement a single entrypoint (e.g., keep one wrapper or add three static
helpers on LevelContextInference like inferProtein/inferPeptide/inferGene) that
validate config.level and forward to LevelContextInference::infer; if you keep
wrappers, make their infer methods static (not instance const) to reflect
stateless behavior and remove the extra header/source/sources.cmake entries.
- Around line 27-29: Update the Doxygen comment for the method infer in class
ProteinInference (function signature infer(const
std::vector<LevelContextInputRow>& input, const LevelContextInferenceConfig&
config) const) to include parameter direction tags for both parameters (e.g.,
`@param[in] input` and `@param[in] config`) and add the `@throws
Exception::Precondition` clause documenting the mismatch case for
`config.level`; apply the same change to the corresponding infer declarations in
PeptideInference.h and GeneInference.h so all three headers include `[in]` tags
and the throws annotation.

In `@src/openms/include/OpenMS/FORMAT/OSWFile.h`:
- Around line 112-142: Convert the short "///" summaries for the new public
methods into full Doxygen blocks using "/** ... */" and include `@brief`,
`@param`[in] (or [out]/[in,out] where applicable), `@return` and any relevant
`@throws` tags; specifically update readIPFPrecursorData(const
PeptidoformInferenceConfig& config), readIPFTransitionData(const
PeptidoformInferenceConfig& config), readIPFAlignmentData(const
PeptidoformInferenceConfig& config), the historical overload
readIPFAlignmentData(double ipf_max_alignment_pep), writeIPFResults(const
String& output_filename, const std::vector<IPFResultRow>& results),
readLevelContextData(InferenceLevel level, InferenceContext context),
writeLevelContextResults(const String& output_filename, InferenceLevel level,
InferenceContext context, const std::vector<LevelContextResultRow>& results) and
readRunBasenames(); for each comment add a short `@brief` describing the purpose,
`@param`[in] entries for all input parameters (note `@param`[out] only if returning
via arguments), `@return` describing the returned container and contents, and
`@throws` if the method can raise exceptions (e.g. IO or DB errors) so the public
API docs are complete and consistent with the project's Doxygen conventions.

In `@src/openms/source/ANALYSIS/OPENSWATH/LevelContextInference.cpp`:
- Around line 117-203: The call to statMetrics_ and its internal fdr/fnr/tn math
are dead: statMetrics_ (and Metrics) only fills svalues but its result is
discarded where invoked, while fdr/fnr/tn are never stored (tn even silenced).
Either remove the unused call and delete statMetrics_/Metrics (and any dead math
in LevelContextInference) if you rely solely on
Math::MultipleTesting::qValue/lfdr for p/q/pep, or modify ErrorStatistics and
LevelContextResultRow to carry the svalues produced by statMetrics_ so the
function's results are propagated; in both cases eliminate the unused
per-iteration computations (fdr/fnr/tn and the “(void)tn;” line) from
statMetrics_ if you choose removal or refactor them into stored fields if you
choose propagation.
- Around line 337-389: The code currently copies LevelContextInputRow into
indexed_rows and then again into grouped_rows, tripling memory; change this to
group indices (Size) or pointers instead: in LevelContextInference::infer
replace indexed_rows (vector<pair<Size, LevelContextInputRow>>) with a
vector<Size> (or vector<pair<Size, const LevelContextInputRow*>>) and build
grouped_rows as map<Int64, vector<Size>> (or vector<const
LevelContextInputRow*>), then modify or overload assignErrorStatistics_
(referenced by name assignErrorStatistics_) to accept the new
index/pointer-based grouping along with the original input vector so it can look
up rows by index (use the existing results vector and config.error unchanged);
ensure run-specific validation still checks run_id via input[index] and update
the try/catch that reports RUN_ID to use the index-based grouping.

In `@src/tests/class_tests/openms/source/LevelContextInference_test.cpp`:
- Around line 179-182: The test uses booleanized fabs checks for numeric
comparisons (peptide_row->score, peptide_row->pvalue, peptide_row->qvalue,
peptide_row->pep) which bypass the framework's tolerance helpers; replace each
TEST_EQUAL(std::fabs(...) < tol, true) with the test framework's numeric
assertion (e.g. TEST_REAL_SIMILAR or the FuzzyDiff helper) using appropriate
tolerances (match the existing tol values like 1e-8 and 5e-4) so failures show
diffs; apply the same replacement pattern for the other occurrences flagged (the
checks around the peptide_row fields at lines noted in the comment).

In `@src/tests/class_tests/openms/source/OSWFileInference_test.cpp`:
- Around line 37-47: The helper scalarInt64_ currently calls
sqlite3_column_int64 even when sqlite3_step(stmt) != SQLITE_ROW (TEST_EQUAL is
non-fatal), which can mask failures; update scalarInt64_ to check the step
result and if it is not SQLITE_ROW immediately finalize the statement and fail
fast (either throw a descriptive exception or use a fatal test macro) instead of
returning 0, ensuring sqlite3_finalize(stmt) is always called before bailing;
reference sqlite3_step, sqlite3_column_int64, sqlite3_finalize, and TEST_EQUAL
in your changes.
🪄 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: b64f7d31-096c-4b85-a959-0fff4aeedda8

📥 Commits

Reviewing files that changed from the base of the PR and between 7e8e710 and 9155ee4.

📒 Files selected for processing (25)
  • doc/doxygen/public/TOPP.doxygen
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/GeneInference.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/LevelContextInference.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathInferenceConfig.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathInferenceData.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/PeptideInference.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/PeptidoformInference.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/ProteinInference.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/sources.cmake
  • src/openms/include/OpenMS/FORMAT/OSWFile.h
  • src/openms/source/ANALYSIS/OPENSWATH/GeneInference.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/LevelContextInference.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/PeptideInference.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/PeptidoformInference.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/ProteinInference.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/sources.cmake
  • src/openms/source/APPLICATIONS/ToolHandler.cpp
  • src/openms/source/FORMAT/OSWFile.cpp
  • src/tests/class_tests/openms/data/PyProphet_inference_test.osw
  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/LevelContextInference_test.cpp
  • src/tests/class_tests/openms/source/OSWFileInference_test.cpp
  • src/tests/class_tests/openms/source/PeptidoformInference_test.cpp
  • src/topp/OpenSwathInfer.cpp
  • src/topp/executables.cmake

Comment thread src/openms/source/FORMAT/OSWFile.cpp Resolved
Comment thread src/openms/source/FORMAT/OSWFile.cpp Resolved

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/openms/source/ANALYSIS/OPENSWATH/PeptidoformInference.cpp`:
- Around line 78-85: The propagation gate is incorrectly using per-transition
PEP (row_ptr->pep) instead of precursor-level confidence; change the conditional
in the propagation block so it checks row_ptr->precursor_peakgroup_pep against
confidence_threshold (i.e., use row_ptr->precursor_peakgroup_pep <=
confidence_threshold) when deciding whether to create and push the propagated
TransitionInferenceRow (the code that clones *row_ptr, sets
propagated.feature_id = target_feature_id and pushes to propagated_rows should
remain unchanged).
🪄 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: 934ecd51-061f-4691-9551-c0ac0a9df4d5

📥 Commits

Reviewing files that changed from the base of the PR and between bb4ff63 and 000bdac.

📒 Files selected for processing (5)
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathInferenceConfig.h
  • src/openms/source/ANALYSIS/OPENSWATH/PeptidoformInference.cpp
  • src/openms/source/FORMAT/OSWFile.cpp
  • src/openms/source/MATH/STATISTICS/KernelDensityEstimation.cpp
  • src/tests/class_tests/openms/source/KernelDensityEstimation_test.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathInferenceConfig.h

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathProteinInference.h`:
- Around line 27-29: The Doxygen for the infer method is missing required tags;
update the comment for infer(const std::vector<LevelContextInputRow>& input,
const LevelContextInferenceConfig& config) const to include an `@brief` describing
its purpose, `@param`[in] tags for both input (vector of LevelContextInputRow) and
config (LevelContextInferenceConfig), an `@return` describing the returned
std::vector<LevelContextResultRow>, and a `@throws` documenting that it may throw
Exception::Precondition (with brief condition when thrown); place these tags
above the infer declaration so tools and users get complete API docs.
- Around line 19-23: The class Doxygen comment for OpenSwathProteinInference is
missing a required `@brief` tag; update the class comment block in
OpenSwathProteinInference.h to include an explicit `@brief` line describing the
class purpose (e.g., "@brief OpenSwath protein-level context inference.") so it
complies with the coding guidelines, leaving the rest of the `@ingroup` and other
tags unchanged and ensuring the `@brief` appears immediately after the /**
opening.

In `@src/tests/class_tests/openms/source/OSWFileInference_test.cpp`:
- Line 43: The TEST_EQUAL macro invocation is missing a terminating semicolon
which causes a compile error; update the test line invoking TEST_EQUAL(state,
SQLITE_ROW) to end with a semicolon so the statement becomes a valid expression
(i.e., add ';' after TEST_EQUAL(state, SQLITE_ROW)) in the
OSWFileInference_test.cpp test function.
🪄 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: 1749ab71-b5ec-4a70-ae91-1df330a8bb98

📥 Commits

Reviewing files that changed from the base of the PR and between 000bdac and 58fb373.

📒 Files selected for processing (13)
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/GeneInference.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/LevelContextInference.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathInferenceConfig.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathInferenceData.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathProteinInference.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/PeptideInference.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/PeptidoformInference.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/sources.cmake
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathProteinInference.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/sources.cmake
  • src/tests/class_tests/openms/source/LevelContextInference_test.cpp
  • src/tests/class_tests/openms/source/OSWFileInference_test.cpp
  • src/topp/OpenSwathInfer.cpp
✅ Files skipped from review due to trivial changes (3)
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/GeneInference.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/sources.cmake
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/PeptidoformInference.h
🚧 Files skipped from review as they are similar to previous changes (6)
  • src/openms/source/ANALYSIS/OPENSWATH/sources.cmake
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/LevelContextInference.h
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/PeptideInference.h
  • src/topp/OpenSwathInfer.cpp
  • src/tests/class_tests/openms/source/LevelContextInference_test.cpp
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathInferenceData.h

Comment on lines +27 to +29
/// Infer protein-level statistics for the provided rows.
std::vector<LevelContextResultRow> infer(const std::vector<LevelContextInputRow>& input,
const LevelContextInferenceConfig& config) const;

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Complete method documentation with required Doxygen tags.

The method documentation is missing several required elements:

  • @brief tag (mandatory, not auto-generated)
  • [in] parameter direction tags for input and config
  • @return description
  • @throws documentation (the implementation throws Exception::Precondition)
📝 Proposed fix
-   /// Infer protein-level statistics for the provided rows.
+   /**
+     `@brief` Infer protein-level statistics for the provided rows.
+
+     `@param`[in] input Vector of level-context input rows containing analyte scores
+     `@param`[in] config Inference configuration (must have config.level == InferenceLevel::Protein)
+     `@return` Vector of level-context result rows with computed statistics
+     `@throws` Exception::Precondition if config.level != InferenceLevel::Protein
+   */
    std::vector<LevelContextResultRow> infer(const std::vector<LevelContextInputRow>& input,
                                             const LevelContextInferenceConfig& config) const;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathProteinInference.h`
around lines 27 - 29, The Doxygen for the infer method is missing required tags;
update the comment for infer(const std::vector<LevelContextInputRow>& input,
const LevelContextInferenceConfig& config) const to include an `@brief` describing
its purpose, `@param`[in] tags for both input (vector of LevelContextInputRow) and
config (LevelContextInferenceConfig), an `@return` describing the returned
std::vector<LevelContextResultRow>, and a `@throws` documenting that it may throw
Exception::Precondition (with brief condition when thrown); place these tags
above the infer declaration so tools and users get complete API docs.

…re values are within [0.0, 1.0]

feat(OSWFileInference): refactor row counting to use a temporary view for filtered queries
@timosachsenberg
timosachsenberg requested a review from jpfeuffer May 9, 2026 17:02

@ingroup TargetedQuantitation
*/
class OPENMS_DLLAPI PeptideInference

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.

I wonder if we should put this into a different namespace (pyprophet?) @jpfeuffer @singjc .
We now have basicproteininference, the bayesian one, and percolator that might do overlapping tasks +
the ones from pyprophet.

What do you guys think?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Ahh, I did initially have ProteinInference, but renamed to OpenSwathProteinInference to avoid conflict with the existing ProteinInference in QUANTITATION. I can do the same for the PeptidoformInference, PeptideInference and GeneInference?

I think at a another stage, we would could compare and see if we could use some of the existing inferences for OpenSwath results. At some point we did have an undergrad student try to use the bayesian one (EPIFANY) for protein inference in OpenSwath, but I don't think the results were optimal at the time..

singjc added 2 commits May 14, 2026 12:00
…vels

- Introduced OpenSwathGeneInference class for gene-level context inference.
- Introduced OpenSwathPeptideInference class for peptide-level context inference.
- Introduced OpenSwathPeptidoformInference class for peptidoform-level context inference.
- Updated source files and headers to reflect the new class names and structures.
- Modified tests to utilize the new OpenSwath inference classes.
- Ensured proper integration of new classes within the existing OpenMS framework.
@singjc
singjc requested a review from timosachsenberg May 14, 2026 19:55
@timosachsenberg
timosachsenberg merged commit 00543ed into OpenMS:develop May 15, 2026
38 of 39 checks passed
timosachsenberg pushed a commit that referenced this pull request May 18, 2026
…9374)

The TOPP tool OpenSwathInfer was already listed under 'New tools' in the
TOPP tools section and doc/doxygen/public/TOPP.doxygen was already updated
by the originating PR, but the corresponding OpenMS Library additions were
missing from the 'Added' sub-section.

Add entries for:
- OpenSwathInferenceData (row types and enums)
- OpenSwathInferenceConfig (configuration structs)
- LevelContextInference (shared context inference)
- OpenSwathGeneInference, OpenSwathPeptideInference, OpenSwathProteinInference
- OpenSwathPeptidoformInference (IPF)
- OSWFile new inference methods
- KernelDensityEstimation bandwidth fallback for degenerate inputs

Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants