Repository navigation
feat: implement layer-ordered heap for FDR sorting (#5160) - #8904
AsciiHermit wants to merge 1 commit into
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
📝 WalkthroughWalkthroughAdds a ChangesLOH-Accelerated FDR Filtering
Suggested Reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (5)
AUTHORSCHANGELOGsrc/openms/include/OpenMS/DATASTRUCTURES/LayerOrderedHeap.hsrc/openms/source/ANALYSIS/ID/FalseDiscoveryRate.cppsrc/tests/class_tests/openms/source/LayerOrderedHeap_test.cpp
| /** | ||
| @brief The input vector is rearranged in-place into layer order | ||
| */ | ||
| explicit LayerOrderedHeap(std::vector<T>& data, Compare comp = Compare()) |
There was a problem hiding this comment.
🛠️ 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.
| 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; | ||
| } |
There was a problem hiding this comment.
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.
|
Thanks!
|
09fe574 to
6bb2e47
Compare
|
Thanks for the review @jpfeuffer! Addressing each point:
Scenario 1: Well-separated target/decoy (typical good search)
Scenario 2: Overlapping target/decoy (poor separation, heavy filtering)
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
Do review the code and let me know if you require more tests or benchmarking for the Loh. |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (5)
src/openms/include/OpenMS/DATASTRUCTURES/LayerOrderedHeap.h (1)
142-145: Consider removing unuseddata_member or documenting its purpose.The
data_pointer is stored during construction but is never used afterbuildLayers_()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_layerlambda (lines 1913-1972) could be extracted to a separate private static helper function to improve readability and testability.The logic itself is correct:
- Count targets/decoys per layer
- Compute cumulative FDR at each layer boundary
- Derive q-values via backward cumulative minimum
- 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'overstd::endlin the new log statement.
std::endlforces a flush; use\nto 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::endlfor 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\ninstead ofstd::endlin 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::endlfor 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
📒 Files selected for processing (9)
AUTHORSCHANGELOGsrc/openms/include/OpenMS/ANALYSIS/ID/FalseDiscoveryRate.hsrc/openms/include/OpenMS/DATASTRUCTURES/LayerOrderedHeap.hsrc/openms/source/ANALYSIS/ID/FalseDiscoveryRate.cppsrc/tests/class_tests/openms/executables.cmakesrc/tests/class_tests/openms/source/LayerOrderedHeap_test.cppsrc/topp/FalseDiscoveryRate.cppsrc/topp/OpenNuXL.cpp
🚧 Files skipped from review as they are similar to previous changes (2)
- CHANGELOG
- AUTHORS
| // | ||
| // -------------------------------------------------------------------------- | ||
| // $Maintainer: Chris Bielow $ | ||
| // $Authors: $ |
There was a problem hiding this comment.
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.
| // $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: $ |
There was a problem hiding this comment.
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.
|
Adversarial review result: no blocking correctness issue proven in static review for the LOH/FDR path. Cleanup required: |
6bb2e47 to
bc57c1f
Compare
|
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:
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 |
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
Summary by CodeRabbit
New Features
Performance