Skip to content

feat: implement layer-ordered heap for FDR sorting (#5160) - #8904

Closed
AsciiHermit wants to merge 1 commit into
OpenMS:developfrom
AsciiHermit:feature/layer-ordered-heap-5160
Closed

AsciiHermit wants to merge 1 commit into
OpenMS:developfrom
AsciiHermit:feature/layer-ordered-heap-5160

Conversation

@AsciiHermit

@AsciiHermit AsciiHermit commented Mar 14, 2026 •

Copy link
Copy Markdown

Description

Adds layer order heaps as part of issue #5160

Implements layer-ordered heaps (LOH) for FDR sorting as described in Lucke et al. (J. Proteome Research 2021, DOI:10.1021/acs.jproteome.0c00711).

Replaces all std::sort calls in FalseDiscoveryRate.cpp with LOH-based sorting via lohSort_() helpers. LOH provides O(n) construction and efficient partial sorting, which benefits FDR calculation where full sorting is often unnecessary.

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

Summary by CodeRabbit

  • New Features

    • Introduced accelerated FDR and filtering pathway for improved processing performance, particularly when applying strict PSM-level FDR thresholds to large peptide datasets.
  • Performance

    • Enhanced computational efficiency in peptide identification workflows through optimized FDR calculation and filtering methods, significantly reducing runtime when extensive filtering is applied.

@coderabbitai

coderabbitai Bot commented Mar 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f4b32a5c-bbea-43f0-931a-6e9c85356cf2

📥 Commits

Reviewing files that changed from the base of the PR and between 6bb2e47 and bc57c1f.

📒 Files selected for processing (1)
  • CHANGELOG
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG

📝 Walkthrough

Walkthrough

Adds a LayerOrderedHeap header-only template data structure enabling O(n) layer-ordered partitioning. Two new methods, applyBasicAndFilter and computeFDRAndFilter_, are added to FalseDiscoveryRate to perform FDR computation and filtering in a single LOH-accelerated pass. The TOPP FalseDiscoveryRate tool and OpenNuXL are updated to use this path. Tests and a changelog entry are included.

Changes

LOH-Accelerated FDR Filtering

Layer / File(s) Summary
LayerOrderedHeap data structure
src/openms/include/OpenMS/DATASTRUCTURES/LayerOrderedHeap.h, src/tests/class_tests/openms/source/LayerOrderedHeap_test.cpp, src/tests/class_tests/openms/executables.cmake
Defines LayerOrderedHeap<T, Compare> with in-place O(n) geometric layer partitioning, per-layer min/max metadata, layerForRank lookup, and a full test suite registered in the test executable list.
FDR class: new LOH-based methods
src/openms/include/OpenMS/ANALYSIS/ID/FalseDiscoveryRate.h, src/openms/source/ANALYSIS/ID/FalseDiscoveryRate.cpp
Adds computeFDRAndFilter_ (static, operates on score-label pairs via LayerOrderedHeap) and applyBasicAndFilter (pre-filters hits by LOH boundary, recomputes FDR, finalizes filtering) to FalseDiscoveryRate.
Tool integration: TOPP FDR and OpenNuXL
src/topp/FalseDiscoveryRate.cpp, src/topp/OpenNuXL.cpp
Replaces the two-step fdr.apply + IDFilter::filterHitsByScore sequence with fdr.applyBasicAndFilter in the PSM-only FDR path in the TOPP tool and consolidates the same two-step call into one in OpenNuXL.
Changelog
CHANGELOG
Adds a General section entry noting the LOH-accelerated FDR+filter path.

Suggested Reviewers

  • jpfeuffer

🐇 A heap of layers, O(n) delight,
FDR and filter merged overnight.
No need to sort the whole array through—
Just peel the layers, let the rabbit do!
One call does all, the scores align,
The PSMs pass at the threshold line. 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely summarizes the main change: implementing a layer-ordered heap data structure for FDR sorting.
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.

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

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

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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

Inline comments:
In `@src/openms/include/OpenMS/DATASTRUCTURES/LayerOrderedHeap.h`:
- Around line 87-120: partitionAtThreshold, partialSort and fullSort assume the
passed-in vector matches the original size used to build layers_ (and thus use
layers_[i].begin/end and n_ for iterator arithmetic); add defensive precondition
checks at the start of each of these methods to validate that data.size() == n_
(or at minimum that for every layer layers_[i].end <= data.size()) and otherwise
throw a clear exception (e.g. std::invalid_argument) or assert; reference the
functions partitionAtThreshold, partialSort, fullSort and the members layers_,
n_, and comp_ when adding these guards so iterator arithmetic cannot go out of
range.
- Around line 48-51: Add complete Doxygen blocks for the LayerOrderedHeap public
API: each public constructor and method (including the explicit constructor
LayerOrderedHeap(std::vector<T>& data, Compare comp = Compare()) and the other
public methods in the LayerOrderedHeap class) must have a `@brief` line and use
parameter direction tags (`@param`[in], `@param`[out], or `@param`[in,out]) for every
parameter and a `@return` tag for any return value; update the Doxygen comments
for the constructor and the other public methods referenced in the review so
that each comment documents purpose, parameter directions, and return value
consistently per the coding guidelines.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8cb1535d-07e4-4d98-a703-b7aa0390f116

📥 Commits

Reviewing files that changed from the base of the PR and between 4c934ac and 09fe574.

📒 Files selected for processing (5)
  • AUTHORS
  • CHANGELOG
  • src/openms/include/OpenMS/DATASTRUCTURES/LayerOrderedHeap.h
  • src/openms/source/ANALYSIS/ID/FalseDiscoveryRate.cpp
  • src/tests/class_tests/openms/source/LayerOrderedHeap_test.cpp

Comment on lines +48 to +51
/**
@brief The input vector is rearranged in-place into layer order
*/
explicit LayerOrderedHeap(std::vector<T>& data, Compare comp = Compare())

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.

🛠️ Refactor suggestion | 🟠 Major

Complete Doxygen tags for the new public API.

Several public methods expose parameters/returns without full Doxygen direction tags (@param[in], @return). Please add complete blocks for the public API surface.

As per coding guidelines: "Doxygen @brief is required for all public APIs; use @param[in], @param[out], or @param[in,out] tags with direction indicators for all parameters."

Also applies to: 58-67, 72-87, 125-155

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

In `@src/openms/include/OpenMS/DATASTRUCTURES/LayerOrderedHeap.h` around lines 48
- 51, Add complete Doxygen blocks for the LayerOrderedHeap public API: each
public constructor and method (including the explicit constructor
LayerOrderedHeap(std::vector<T>& data, Compare comp = Compare()) and the other
public methods in the LayerOrderedHeap class) must have a `@brief` line and use
parameter direction tags (`@param`[in], `@param`[out], or `@param`[in,out]) for every
parameter and a `@return` tag for any return value; update the Doxygen comments
for the constructor and the other public methods referenced in the review so
that each comment documents purpose, parameter directions, and return value
consistently per the coding guidelines.

Comment on lines +87 to +120
size_t partitionAtThreshold(std::vector<T>& data, const T& threshold)
{
if (layers_.empty()) return 0;

size_t boundary = layers_.size(); // default: all layers are below
for (size_t i = 0; i < layers_.size(); ++i)
{
if (!comp_(layers_[i].min_val, threshold))
{
boundary = i;
break;
}
if (comp_(layers_[i].max_val, threshold))
{
continue;
}
boundary = i;
break;
}

if (boundary == layers_.size())
{
return n_;
}

size_t count_below = layers_[boundary].begin;

auto it = std::partition(data.begin() + layers_[boundary].begin,
data.begin() + layers_[boundary].end,
[&](const T& val) { return comp_(val, threshold); });
count_below += std::distance(data.begin() + layers_[boundary].begin, it);

return count_below;
}

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 | 🟠 Major

Guard mutating methods against mismatched input vectors.

partitionAtThreshold, partialSort, and fullSort rely on layer bounds built from the constructor input. If a different (or resized) vector is passed later, iterator arithmetic can go out of range.

💡 Proposed defensive precondition checks
 size_t partitionAtThreshold(std::vector<T>& data, const T& threshold)
 {
+  assert(data.size() == n_);
+  assert(n_ == 0 || data.data() == data_);
   if (layers_.empty()) return 0;
@@
 void partialSort(std::vector<T>& data, size_t n)
 {
+  assert(data.size() == n_);
+  assert(n_ == 0 || data.data() == data_);
   if (n == 0 || layers_.empty()) return;
@@
 void fullSort(std::vector<T>& data)
 {
+  assert(data.size() == n_);
+  assert(n_ == 0 || data.data() == data_);
   for (const auto& lay : layers_)

Also applies to: 125-155

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

In `@src/openms/include/OpenMS/DATASTRUCTURES/LayerOrderedHeap.h` around lines 87
- 120, partitionAtThreshold, partialSort and fullSort assume the passed-in
vector matches the original size used to build layers_ (and thus use
layers_[i].begin/end and n_ for iterator arithmetic); add defensive precondition
checks at the start of each of these methods to validate that data.size() == n_
(or at minimum that for every layer layers_[i].end <= data.size()) and otherwise
throw a clear exception (e.g. std::invalid_argument) or assert; reference the
functions partitionAtThreshold, partialSort, fullSort and the members layers_,
n_, and comp_ when adding these guards so iterator arithmetic cannot go out of
range.

@jpfeuffer

jpfeuffer commented Mar 14, 2026 •

Copy link
Copy Markdown
Contributor

Thanks!
First notes:

  • Did you benchmark this? Without benchmarks I do not feel comfortable merging it.
  • especially since I feel like the actual main use case of LOH is not even used here. Looks to me like it fully sorts everything. I feel like this works best in combined FDR+Filter scenarios.
  • have you looked into just using their code as a library?
  • I personally do not like the ascending annotations.

@AsciiHermit
AsciiHermit force-pushed the feature/layer-ordered-heap-5160 branch from 09fe574 to 6bb2e47 Compare March 16, 2026 08:29
@AsciiHermit

AsciiHermit commented Mar 16, 2026 •

Copy link
Copy Markdown
Author

Thanks for the review @jpfeuffer! Addressing each point:

  1. Benchmarking
    Benchmarked applyBasic + filterHitsByScore (old path) vs applyBasicAndFilter (LOH-accelerated) using the FDR pipeline with synthetic PeptideIdentification data.

Scenario 1: Well-separated target/decoy (typical good search)

N FDR threshold Pass % old (ms) LOH (ms) Improvement Speedup
100K 0.1% 20% 351 182 +169ms 1.93x
100K 1% 56% 328 275 +53ms 1.19x
100K 5% 82% 324 365 -41ms 0.89x
500K 0.1% 22% 1998 873 +1125ms 2.29x
1M 0.1% 23% 4298 1820 +2478ms 2.36x
1M 1% 56% 4233 4659 -426ms 0.91x

Scenario 2: Overlapping target/decoy (poor separation, heavy filtering)

N FDR threshold Pass % old (ms) LOH (ms) Improvement Speedup
100K 0.1% 0% 345 79 +266ms 4.36x
100K 5% 4% 334 105 +230ms 3.20x
500K 1% 0% 2020 397 +1623ms 5.09x
1M 1% 0% 4520 865 +3655ms 5.23x
1M 5% 3% 4322 920 +3402ms 4.70x

LOH gives 2–5x speedup when most PSMs are filtered out (pass rate <25%), but adds overhead when most pass (>50%). The crossover is around 30–40% pass rate. Biggest gains are with strict thresholds or poor target/decoy separation

  1. FDR+Filter use case
    I also compared full sort, partial sort, and partition and they were all slower with LOH. The only win is the combined FDR+filter scenario where LOH walks layers with layer-level q-values to find a coarse boundary, pre-filters by that boundary score, then runs calculateFDRBasic_ on the smaller passing subset only. The LOH code is wired into the TOPP FalseDiscoveryRate tool (PSM-level FDR with filtering) and OpenNuXL (hardcoded 1% FDR filter).

  2. Using their code as a library
    There is no standalone LOH library available in any package manager (conan, vcpkg, PyPI). The only existing code are a few repos with unspecified licenses, making them unsuitable for direct integration. Our implementation is ~60 lines (header-only template) using just std::nth_element with geometric layer sizes.

  3. Ascending annotations
    Fixed — removed those.

Do review the code and let me know if you require more tests or benchmarking for the Loh.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (5)
src/openms/include/OpenMS/DATASTRUCTURES/LayerOrderedHeap.h (1)

142-145: Consider removing unused data_ member or documenting its purpose.

The data_ pointer is stored during construction but is never used after buildLayers_() completes. This creates a potential dangling pointer risk if the original vector is modified or destroyed. Either remove this member if unused, or document that the caller must ensure the vector outlives the heap and remains unmodified.

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

In `@src/openms/include/OpenMS/DATASTRUCTURES/LayerOrderedHeap.h` around lines 142
- 145, The data_ pointer is unused after buildLayers_() and risks dangling;
remove the data_ member and any assignments to it in the LayerOrderedHeap
constructor and related code (search for data_ and constructor initializing it),
and ensure buildLayers_() and other methods use the passed-in container or store
necessary copies inside layers_ instead; alternatively, if you must keep it,
replace raw T* data_ with a documented owning/shared handle (e.g.,
std::shared_ptr or std::span) and add a comment in LayerOrderedHeap explaining
the lifetime requirement so callers know the source vector must outlive the
heap.
src/openms/source/ANALYSIS/ID/FalseDiscoveryRate.cpp (1)

1902-1990: Consider extracting the lambda to reduce method complexity.

Static analysis flagged this method as complex. The find_boundary_layer lambda (lines 1913-1972) could be extracted to a separate private static helper function to improve readability and testability.

The logic itself is correct:

  1. Count targets/decoys per layer
  2. Compute cumulative FDR at each layer boundary
  3. Derive q-values via backward cumulative minimum
  4. Find last passing layer and add safety margin
♻️ Optional refactor suggestion
// Extract as a private static helper
static size_t findBoundaryLayer_(
    const LayerOrderedHeap<Pair, Compare>& loh,
    const ScoreToTgtDecLabelPairs& scores_labels,
    double fdr_threshold,
    bool conservative);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/FalseDiscoveryRate.cpp` around lines 1902 -
1990, The find_boundary_layer lambda inside
FalseDiscoveryRate::computeFDRAndFilter_ should be extracted into a private
static helper (e.g. static size_t findBoundaryLayer_(const
LayerOrderedHeap<Pair, Compare>& loh, const ScoreToTgtDecLabelPairs&
scores_labels, double fdr_threshold, bool conservative)) to reduce method
complexity; move the body (count targets/decoys per layer, compute fdr_at_layer,
qval_at_layer, find last passing layer and add the safety margin) into that
helper, keep the same logic and use Pair and LayerOrderedHeap type parameters
(templated or overload for Compare/std::greater), then replace the lambda calls
in computeFDRAndFilter_ with calls to findBoundaryLayer_ for both
higher_score_better and non-higher branches and return the same
loh.layer(passing_layers - 1).end result.
src/topp/OpenNuXL.cpp (1)

4912-4912: Prefer '\n' over std::endl in the new log statement.

std::endl forces a flush; use \n to avoid unnecessary logging overhead.

Proposed change
-      OPENMS_LOG_INFO << "Calculating FDR and filtering at 1% PSM-FDR..." << endl;
+      OPENMS_LOG_INFO << "Calculating FDR and filtering at 1% PSM-FDR...\n";

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

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

In `@src/topp/OpenNuXL.cpp` at line 4912, The log statement using std::endl should
be changed to use '\n' to avoid forcing a flush; locate the OPENMS_LOG_INFO line
in OpenNuXL.cpp (the "Calculating FDR and filtering at 1% PSM-FDR..." message)
and replace the trailing << endl with << '\n' so the log writes a newline
without the costly flush.
src/topp/FalseDiscoveryRate.cpp (2)

242-242: Use \n instead of std::endl in the new LOH log line.

This avoids forced flushes on hot tool paths.

Proposed change
-          OPENMS_LOG_INFO << "FDR control: Computing PSM FDR and filtering (LOH-accelerated)..." << endl;
+          OPENMS_LOG_INFO << "FDR control: Computing PSM FDR and filtering (LOH-accelerated)...\n";

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

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

In `@src/topp/FalseDiscoveryRate.cpp` at line 242, The new LOH log line uses
std::endl which forces a flush; replace std::endl with '\n' in the
OPENMS_LOG_INFO statement that prints "FDR control: Computing PSM FDR and
filtering (LOH-accelerated)..." so the message ends with '\n' instead of using
std::endl (update the line containing OPENMS_LOG_INFO and that exact message).

239-263: Consider adding a small benchmark guard for this optimization branch.

Since this adds a specialized execution path, a reproducible benchmark (or perf regression test) would help prevent accidental regressions and support merge confidence.

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

In `@src/topp/FalseDiscoveryRate.cpp` around lines 239 - 263, Add a reproducible
micro-benchmark or perf-regression test and a runtime guard flag for the
LOH-accelerated branch around the if (psm_level_fdr && !peptide_level_fdr &&
psm_fdr < 1) block so the optimization is covered and protected from accidental
regressions: create a small benchmark that times
fdr.applyBasicAndFilter(pep_ids, psm_fdr) vs the fallback path
(fdr.apply(pep_ids, peptide_level_fdr) + IDFilter::filterHitsByScore) using
representative pep_ids input and assert a stable performance threshold, and add
a configurable param or internal flag (e.g., enable_loh_accelerated_fdr) checked
before entering the optimized branch to allow toggling in tests/CI; ensure the
benchmark is run in CI as a perf regression test and reference the symbols
fdr.applyBasicAndFilter, fdr.apply, IDFilter::filterHitsByScore, and variables
psm_level_fdr/peptide_level_fdr/psm_fdr when adding tests and the guard.
🤖 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/include/OpenMS/DATASTRUCTURES/LayerOrderedHeap.h`:
- Line 6: Update the file preamble in LayerOrderedHeap.h by replacing the
placeholder "$Authors: $" with the actual contributor name(s) following project
header conventions; locate the header comment block near the top of
src/openms/include/OpenMS/DATASTRUCTURES/LayerOrderedHeap.h (the line containing
"$Authors: $") and insert the correct author string(s) (e.g., "$Authors: Your
Name$") so the Authors marker is populated.

In `@src/tests/class_tests/openms/source/LayerOrderedHeap_test.cpp`:
- Line 6: Replace the empty "$Authors: $" marker in the file preamble with the
actual contributor name(s); locate the file header containing the "$Authors: $"
token (the top-of-file preamble in LayerOrderedHeap_test.cpp) and update it to
include the author(s) following project header style (e.g., "$Authors: Your Name
$") so the Authors marker is not empty.

---

Nitpick comments:
In `@src/openms/include/OpenMS/DATASTRUCTURES/LayerOrderedHeap.h`:
- Around line 142-145: The data_ pointer is unused after buildLayers_() and
risks dangling; remove the data_ member and any assignments to it in the
LayerOrderedHeap constructor and related code (search for data_ and constructor
initializing it), and ensure buildLayers_() and other methods use the passed-in
container or store necessary copies inside layers_ instead; alternatively, if
you must keep it, replace raw T* data_ with a documented owning/shared handle
(e.g., std::shared_ptr or std::span) and add a comment in LayerOrderedHeap
explaining the lifetime requirement so callers know the source vector must
outlive the heap.

In `@src/openms/source/ANALYSIS/ID/FalseDiscoveryRate.cpp`:
- Around line 1902-1990: The find_boundary_layer lambda inside
FalseDiscoveryRate::computeFDRAndFilter_ should be extracted into a private
static helper (e.g. static size_t findBoundaryLayer_(const
LayerOrderedHeap<Pair, Compare>& loh, const ScoreToTgtDecLabelPairs&
scores_labels, double fdr_threshold, bool conservative)) to reduce method
complexity; move the body (count targets/decoys per layer, compute fdr_at_layer,
qval_at_layer, find last passing layer and add the safety margin) into that
helper, keep the same logic and use Pair and LayerOrderedHeap type parameters
(templated or overload for Compare/std::greater), then replace the lambda calls
in computeFDRAndFilter_ with calls to findBoundaryLayer_ for both
higher_score_better and non-higher branches and return the same
loh.layer(passing_layers - 1).end result.

In `@src/topp/FalseDiscoveryRate.cpp`:
- Line 242: The new LOH log line uses std::endl which forces a flush; replace
std::endl with '\n' in the OPENMS_LOG_INFO statement that prints "FDR control:
Computing PSM FDR and filtering (LOH-accelerated)..." so the message ends with
'\n' instead of using std::endl (update the line containing OPENMS_LOG_INFO and
that exact message).
- Around line 239-263: Add a reproducible micro-benchmark or perf-regression
test and a runtime guard flag for the LOH-accelerated branch around the if
(psm_level_fdr && !peptide_level_fdr && psm_fdr < 1) block so the optimization
is covered and protected from accidental regressions: create a small benchmark
that times fdr.applyBasicAndFilter(pep_ids, psm_fdr) vs the fallback path
(fdr.apply(pep_ids, peptide_level_fdr) + IDFilter::filterHitsByScore) using
representative pep_ids input and assert a stable performance threshold, and add
a configurable param or internal flag (e.g., enable_loh_accelerated_fdr) checked
before entering the optimized branch to allow toggling in tests/CI; ensure the
benchmark is run in CI as a perf regression test and reference the symbols
fdr.applyBasicAndFilter, fdr.apply, IDFilter::filterHitsByScore, and variables
psm_level_fdr/peptide_level_fdr/psm_fdr when adding tests and the guard.

In `@src/topp/OpenNuXL.cpp`:
- Line 4912: The log statement using std::endl should be changed to use '\n' to
avoid forcing a flush; locate the OPENMS_LOG_INFO line in OpenNuXL.cpp (the
"Calculating FDR and filtering at 1% PSM-FDR..." message) and replace the
trailing << endl with << '\n' so the log writes a newline without the costly
flush.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e70439d9-a192-4071-9f47-dbcaec6a340f

📥 Commits

Reviewing files that changed from the base of the PR and between 09fe574 and 6bb2e47.

📒 Files selected for processing (9)
  • AUTHORS
  • CHANGELOG
  • src/openms/include/OpenMS/ANALYSIS/ID/FalseDiscoveryRate.h
  • src/openms/include/OpenMS/DATASTRUCTURES/LayerOrderedHeap.h
  • src/openms/source/ANALYSIS/ID/FalseDiscoveryRate.cpp
  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/LayerOrderedHeap_test.cpp
  • src/topp/FalseDiscoveryRate.cpp
  • src/topp/OpenNuXL.cpp
🚧 Files skipped from review as they are similar to previous changes (2)
  • CHANGELOG
  • AUTHORS

//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: $

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

Add author information to the file preamble.

The $Authors: $ marker is empty. Per coding guidelines, the file header preamble should include the Authors marker with the actual contributor name(s).

-// $Authors: $
+// $Authors: YourName $
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// $Authors: $
// $Authors: YourName $
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/include/OpenMS/DATASTRUCTURES/LayerOrderedHeap.h` at line 6,
Update the file preamble in LayerOrderedHeap.h by replacing the placeholder
"$Authors: $" with the actual contributor name(s) following project header
conventions; locate the header comment block near the top of
src/openms/include/OpenMS/DATASTRUCTURES/LayerOrderedHeap.h (the line containing
"$Authors: $") and insert the correct author string(s) (e.g., "$Authors: Your
Name$") so the Authors marker is populated.

//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: $

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

Add author information to the file preamble.

The $Authors: $ marker is empty. Per coding guidelines, the file header preamble should include the Authors marker with the actual contributor name(s).

-// $Authors: $
+// $Authors: YourName $
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/tests/class_tests/openms/source/LayerOrderedHeap_test.cpp` at line 6,
Replace the empty "$Authors: $" marker in the file preamble with the actual
contributor name(s); locate the file header containing the "$Authors: $" token
(the top-of-file preamble in LayerOrderedHeap_test.cpp) and update it to include
the author(s) following project header style (e.g., "$Authors: Your Name $") so
the Authors marker is not empty.

Copy link
Copy Markdown
Contributor

Adversarial review result: no blocking correctness issue proven in static review for the LOH/FDR path.

Cleanup required: git diff --check reports trailing whitespace in src/openms/include/OpenMS/DATASTRUCTURES/LayerOrderedHeap.h and src/openms/source/ANALYSIS/ID/FalseDiscoveryRate.cpp. The CHANGELOG entry also contains a tracker reference (#5160); please remove tracker-style issue references if this branch is cleaned for merge. I did not build/run tests locally.

@AsciiHermit
AsciiHermit force-pushed the feature/layer-ordered-heap-5160 branch from 6bb2e47 to bc57c1f Compare June 23, 2026 16:28

Copy link
Copy Markdown
Contributor

Thanks a lot for the work and for the benchmarks, @AsciiHermit. They made the decision easy. We looked at this against typical workloads and are closing it, for these reasons:

  1. No gain at typical settings. In practice PSM FDR is filtered at 1% (sometimes 5%) on reasonably well-separated searches. That matches your "Scenario 1" rows, where 50–80% of PSMs pass. There the new path is about the same speed or slower: 1.19x at 100K and 0.91x at 1M for 1%, and 0.89x for 5%. The large wins only show up at 0.1% FDR or when almost nothing passes (a failed search). Those are not the cases worth an extra code path.

  2. Whatever speedup there is doesn't come from the LOH. A quick -O2 microbenchmark on score/label pairs: a full std::sort takes ~7 ms at 100K and ~90 ms at 1M, and the LOH build from this PR takes ~2 ms and ~20 ms. So the LOH can save at most ~5 ms (100K) or ~70 ms (1M), against a total of ~330 ms or ~4.3 s for the old path. The Scenario 2 gains come from pre-filtering hits before the std::map is built and before setScores_ writes the q-values. A plain sort could do the same if it ever mattered. Either way, the step is small compared to reading and writing the idXML.

  3. It changes results on the default TOPP path. FalseDiscoveryRate -PSM true -FDR:PSM <1 used to go through apply(), which uses calculateFDRs_ and the D/T estimate. The new path uses calculateFDRBasic_, which estimates (D+1)/(N+1), and it silently ignores treat_runs_separately and split_charge_variants. So the q-values and the set of kept PSMs change; TOPP_FalseDiscoveryRate_6 (-FDR:PSM 0.05) would hit this. OpenNuXL output would change for the same reason.

  4. The cutoff is approximate. q-values are only evaluated at layer boundaries, with a different formula than the final pass, and a one-layer "safety margin" is added. Layer sizes double, so a dip in FDR inside a later layer can't be seen, and neither can a dip when no boundary passes at all (in that case every hit is removed). Either way the PR can drop PSMs that the exact calculation keeps. This is mostly a problem for small inputs, but it is not exact.

That leaves a new data structure plus a second FDR code path to maintain, with no benefit at typical sizes and thresholds, so we'd rather not merge it. Thanks again for the careful work.


Generated by Claude Code

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.

3 participants