Repository navigation
refactor: reduce the use of assignRanks - #7991
Conversation
WalkthroughThis change set removes the Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Identification
participant Hit
User->>Identification: Add hits
User->>Identification: sort()
Identification->>Hit: (Hits are sorted by score)
Note over Identification: No explicit rank assignment performed
Suggested labels
Suggested reviewers
Poem
Tip ⚡️ Faster reviews with caching
Enjoy the performance boost—your workflow just got faster. ✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
next step could be:
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h (2)
916-924: Floating‑point equality test causes duplicate‑rank artefactsUsing direct equality on two
doublescores (lit->getScore() != last_score) is brittle – tiny FP round‑off differences will create artificial new ranks.Consider comparing with a small tolerance or, simpler, compare the ordered scores:
- if ((double)lit->getScore() != last_score) + if (lit->getScore() != last_score) // still raw equalityBetter:
constexpr double EPS = 1e-12; if (std::fabs(lit->getScore() - last_score) > EPS)This prevents inflated rank numbers when scores differ only by machine precision.
927-977: Inefficient two‑phase erase / copy logic – useerase-remove_ifonceThe current implementation
- Builds a
std::vectorof iterators,- Erases in reverse order,
- Re‑creates
ranks,- Copies kept hits to a brand‑new container for the max‑rank step.
This is O(n) extra allocations and considerable code. A single
erase-remove_ifwith a lambda capturingranks(or recomputing rank on the fly) is clearer and faster:- // Apply min_rank filter ... - std::vector<typename std::vector<typename IdentificationType::HitType>::iterator> to_remove; - ... - for (auto it = to_remove.rbegin(); it != to_remove.rend(); ++it) - { - hits.erase(*it); - } + hits.erase( + std::remove_if(hits.begin(), hits.end(), + [&](const auto&, Size idx = 0) mutable + { + return ranks[idx++] < min_rank; + }), + hits.end());A similar single pass can then keep
rank <= max_rank. Less code, fewer temporaries, and fewer iterator invalidation pitfalls.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (35)
src/openms/include/OpenMS/METADATA/PeptideIdentification.h(0 hunks)src/openms/include/OpenMS/METADATA/ProteinIdentification.h(1 hunks)src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h(1 hunks)src/openms/source/ANALYSIS/ID/ConsensusIDAlgorithm.cpp(1 hunks)src/openms/source/ANALYSIS/ID/ConsensusIDAlgorithmRanks.cpp(1 hunks)src/openms/source/ANALYSIS/ID/FalseDiscoveryRate.cpp(1 hunks)src/openms/source/ANALYSIS/ID/PercolatorFeatureSetHelper.cpp(3 hunks)src/openms/source/ANALYSIS/ID/SimpleSearchEngineAlgorithm.cpp(1 hunks)src/openms/source/FORMAT/InspectOutfile.cpp(1 hunks)src/openms/source/FORMAT/MzTab.cpp(2 hunks)src/openms/source/FORMAT/OMSSAXMLFile.cpp(1 hunks)src/openms/source/FORMAT/XTandemXMLFile.cpp(1 hunks)src/openms/source/METADATA/PeptideIdentification.cpp(0 hunks)src/openms/source/METADATA/ProteinIdentification.cpp(0 hunks)src/openms_gui/source/VISUAL/MetaDataBrowser.cpp(2 hunks)src/tests/class_tests/openms/source/ConsensusIDAlgorithmAverage_test.cpp(0 hunks)src/tests/class_tests/openms/source/ConsensusIDAlgorithmBest_test.cpp(0 hunks)src/tests/class_tests/openms/source/ConsensusIDAlgorithmRanks_test.cpp(0 hunks)src/tests/class_tests/openms/source/ConsensusIDAlgorithmWorst_test.cpp(0 hunks)src/tests/class_tests/openms/source/IDFilter_test.cpp(2 hunks)src/tests/class_tests/openms/source/InspectOutfile_test.cpp(0 hunks)src/tests/class_tests/openms/source/MzIdentMLFile_test.cpp(0 hunks)src/tests/class_tests/openms/source/PepNovoOutfile_test.cpp(0 hunks)src/tests/class_tests/openms/source/PeptideIdentification_test.cpp(0 hunks)src/tests/class_tests/openms/source/ProteinIdentification_test.cpp(2 hunks)src/tests/topp/FalseDiscoveryRate_7_output.idXML(1 hunks)src/tests/topp/IDFilter_10_output.idXML(2 hunks)src/tests/topp/IDFilter_11_output.idXML(1 hunks)src/tests/topp/IDFilter_24_output.consensusXML(24 hunks)src/tests/topp/PSMFeatureExtractor_2_out.mzid(4 hunks)src/topp/FalseDiscoveryRate.cpp(0 hunks)src/topp/IDFilter.cpp(0 hunks)src/topp/LuciphorAdapter.cpp(1 hunks)src/topp/MascotAdapterOnline.cpp(1 hunks)src/topp/MetaProSIP.cpp(2 hunks)
💤 Files with no reviewable changes (13)
- src/openms/source/METADATA/PeptideIdentification.cpp
- src/topp/FalseDiscoveryRate.cpp
- src/tests/class_tests/openms/source/PeptideIdentification_test.cpp
- src/tests/class_tests/openms/source/PepNovoOutfile_test.cpp
- src/topp/IDFilter.cpp
- src/tests/class_tests/openms/source/ConsensusIDAlgorithmRanks_test.cpp
- src/tests/class_tests/openms/source/InspectOutfile_test.cpp
- src/openms/include/OpenMS/METADATA/PeptideIdentification.h
- src/tests/class_tests/openms/source/MzIdentMLFile_test.cpp
- src/tests/class_tests/openms/source/ConsensusIDAlgorithmBest_test.cpp
- src/tests/class_tests/openms/source/ConsensusIDAlgorithmAverage_test.cpp
- src/tests/class_tests/openms/source/ConsensusIDAlgorithmWorst_test.cpp
- src/openms/source/METADATA/ProteinIdentification.cpp
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/tests/class_tests/openms/source/ProteinIdentification_test.cpp (2)
src/openms/source/METADATA/PeptideIdentification.cpp (2)
sort(226-229)sort(226-226)src/openms/source/METADATA/ProteinIdentification.cpp (2)
sort(574-584)sort(574-574)
⏰ Context from checks skipped due to timeout of 90000ms (6)
- GitHub Check: build-and-test (macos-13, xcode, 14.2)
- GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
- GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
- GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
- GitHub Check: build-and-test (windows-2022, cl.exe, default)
- GitHub Check: cppcheck-test
🔇 Additional comments (47)
src/tests/topp/IDFilter_10_output.idXML (6)
7-7: Standardize significance_threshold to floating-point
Changedsignificance_thresholdfrom integer "0" to "0.0" for consistency with floating-point representation.
14-17: Swap ProteinHit accessions to match sorted order
The order and accession ofPH_3andPH_4have been swapped (nowPH_3="P01876|IGHA1_HUMAN"andPH_4="P01877|IGHA2_HUMAN"), aligning with the new sorting logic after removingassignRanks().
21-21: Update protein_group_3 to reflect new hit grouping
protein_group_3now listsPH_3,PH_4in the updated order, matching the swappedProteinHitelements.
22-25: Normalize indistinguishable_proteins values
Converted user parametersindistinguishable_proteins_0through_3to use "0.0" and updated the PH references for group 3 (PH_3,PH_4), ensuring consistency in floating-point formatting and grouping.
27-27: Standardize PeptideIdentification threshold to floating-point
Convertedsignificance_thresholdfrom "0" to "0.0" in thePeptideIdentificationelement for consistency.
68-68: Align peptide hitprotein_refswith swapped proteins
Updatedprotein_refsto"PH_3 PH_4"on the sixthPeptideHitto reflect the reordered protein hits.src/topp/LuciphorAdapter.cpp (1)
640-640: Sort function replaces assignRanks for maintaining peptide hit orderThis change replaces the call to
assignRanks()withsort()for ordering peptide hits. This is part of a broader refactoring to reduce the usage of rank assignment in favor of sorting to simplify rank management across the codebase.src/openms/source/FORMAT/OMSSAXMLFile.cpp (1)
55-55: Sort function replaces assignRanks for maintaining peptide hit orderThe call to
assignRanks()is replaced withsort()as part of a broader refactoring to eliminate explicit rank assignment in favor of relying on sorting for hit ordering. This change aligns with similar modifications across the OpenMS codebase.src/topp/MascotAdapterOnline.cpp (1)
222-222: Sort function replaces assignRanks in merge operationThe change from
assignRanks()tosort()in themergeIDs_method aligns with the codebase-wide refactoring to remove explicit rank assignment. After inserting hits from one peptide identification into another, sorting is now used instead of rank assignment to maintain the ordering of peptide hits.src/openms/include/OpenMS/METADATA/ProteinIdentification.h (1)
366-366: API change: assignRanks method has been removedThe
assignRanks()method has been removed from theProteinIdentificationclass as part of the refactoring to reduce rank usage. This API change is consistent with similar removals from other classes such asPeptideIdentification. Thesort()method on line 365 is now used exclusively to order protein hits instead of explicit rank assignment.src/openms/source/ANALYSIS/ID/ConsensusIDAlgorithm.cpp (1)
117-117: Replaced assignRanks() with sort() call.The change aligns with the broader refactoring effort to remove
assignRanks()across the codebase and simplify rank management. The replacement withsort()maintains the functionality of ordering peptide hits while eliminating explicit rank assignment.src/openms/source/FORMAT/InspectOutfile.cpp (1)
270-270: Replaced assignRanks() with sort() call for peptide identifications.This change is consistent with the codebase-wide refactoring to remove
assignRanks()methods. Usingsort()ensures peptide hits will be ordered correctly without explicitly assigning ranks.src/openms/source/ANALYSIS/ID/SimpleSearchEngineAlgorithm.cpp (1)
341-341: Replaced assignRanks() with sort() in postProcessHits_ method.The modification is part of the consistent pattern of changes across the codebase to reduce rank usage. This will maintain the correct ordering of peptide hits without explicitly assigning rank values.
src/openms/source/ANALYSIS/ID/PercolatorFeatureSetHelper.cpp (3)
204-204: Replaced assignRanks() with sort() in addMASCOTFeatures function.This change aligns with the PR objective to reduce the use of
assignRanks()in favor ofsort(), simplifying rank management across the codebase.
229-229: Replaced assignRanks() with sort() in addCONCATSEFeatures function.The replacement fits with the larger refactoring effort to simplify rank management by using
sort()instead of explicit rank assignment.
606-606: Replaced assignRanks() with sort() in addMULTISEFeatures function.Consistent with the refactoring approach in other functions, this change replaces explicit rank assignment with sorting operations, which aligns with the PR objectives.
src/openms_gui/source/VISUAL/MetaDataBrowser.cpp (2)
351-351: Refactoring from assignRanks() to sort() is correct.This change aligns with the PR objective of reducing the use of
assignRanks(). Since this visualization method only needs the peptide hits to be properly ordered for display, usingsort()is appropriate and sufficient.
386-386: Refactoring from assignRanks() to sort() is correct.Similar to the peptide identification change, replacing
assignRanks()withsort()for protein hits maintains the proper ordering needed for visualization while removing the explicit rank assignment.src/openms/source/FORMAT/XTandemXMLFile.cpp (2)
63-63: Appropriate replacement of assignRanks() with sort().This change correctly maintains the ordering of peptide hits after they are swapped from the peptide_hits_ map. Using sort() ensures hits are properly ordered before being added to the peptide_ids vector.
71-71: Appropriate replacement of assignRanks() with sort().This change correctly ensures protein hits are properly ordered after being swapped into the protein_identification object, while removing the explicit rank assignment.
src/openms/source/ANALYSIS/ID/ConsensusIDAlgorithmRanks.cpp (1)
44-52: Well-implemented replacement for assignRanks() functionality.This refactoring not only replaces the
assignRanks()call withsort(), but also explicitly implements the rank-based scoring logic that was previously hidden in theassignRanks()method.The implementation correctly:
- Sorts the hits by score
- Maintains an explicit rank counter starting at 1
- Sets each hit's score to rank-1 (best hit gets 0, second gets 1, etc.)
This approach improves code clarity by making the rank computation logic explicit.
src/openms/source/ANALYSIS/ID/FalseDiscoveryRate.cpp (1)
398-398: Appropriate replacement of assignRanks() with sort().This change correctly replaces the explicit rank assignment with a simple sort after FDR/q-value calculation. Since the actual rank values don't appear to be used after this point, the substitution maintains the required functionality of ensuring hits are properly ordered by their newly assigned FDR/q-value scores.
src/tests/class_tests/openms/source/ProteinIdentification_test.cpp (1)
432-450: Test section renamed and modified to use sort() instead of assignRanks()The test section has been renamed from
assignRanks()tosort()and now calls thesort()method rather thanassignRanks(). This change aligns with the PR objective to reduce the use ofassignRanks()in favor of sorting the protein hits, which simplifies rank management by making explicit rank assignment unnecessary.The test still properly verifies that the protein hits are correctly ordered by score (in descending order), with "FIRSTPROTEIN", "SECONDPROTEIN", and "THIRDPROTEIN" as expected.
src/openms/source/FORMAT/MzTab.cpp (2)
837-837: Changed assignRanks() to sort() method callThe method call has been changed from
assignRanks()tosort()to align with the PR objective of reducing explicit rank assignment. This modification ensures that peptide hits are ordered by score before selecting the best hit, maintaining functional equivalence while simplifying the rank management approach.
1171-1171: Formatting adjustment after removing significance thresholdA trailing whitespace was added after removing
Constants::UserParam::SIGNIFICANCE_THRESHOLDfrom the set of meta keys. This is a minor formatting adjustment that doesn't affect functionality but maintains code style consistency.src/tests/topp/PSMFeatureExtractor_2_out.mzid (3)
7-7: Updated metadata timestamps and version informationTimestamps and version information have been updated to reflect the current build date. This is expected when regenerating test output files and doesn't affect the functionality being tested.
Also applies to: 19-19, 44-44
209-209: Changed rank attribute from "1" to "0" in SpectrumIdentificationItemThe rank attribute in the SpectrumIdentificationItem has been changed from "1" to "0", reflecting the refactored approach to rank management. This change aligns with the PR objective of reducing explicit rank assignments, as the rank value now starts at 0 instead of 1.
216-216: Minor floating-point precision adjustmentA very slight adjustment to the floating-point precision of the MS-GF:EValue value, changing from 9.678856999999999e-24 to 9.678857000000001e-24. This is likely due to minor differences in floating-point handling and doesn't affect the functional correctness of the test.
src/tests/class_tests/openms/source/IDFilter_test.cpp (2)
56-56: Sort added for test setup consistencyThis change is part of the overall transition from using
assignRanks()to usingsort()for ordering hits. Sorting the test data at the beginning makes it easier to compare results in subsequent tests.
883-884: Replaced assignRanks() with sort() in testThis change replaces a call to
assignRanks()withsort(), aligning with the PR's goal of removing explicit rank assignments and relying on sorting for hit ordering.src/topp/MetaProSIP.cpp (2)
3190-3190: Replaced assignRanks() with sort() for peptide IDsThe call to
assignRanks()has been replaced withsort()as part of the codebase-wide refactoring to eliminate the use of rank assignments. This change maintains the same ordering behavior for the subsequent operations on the peptide hits.
3202-3202: Replaced assignRanks() with sort() for temporary peptide IDSimilar to the previous change, this replaces the explicit rank assignment with a sort operation. This is consistent with the PR's goal to remove the
assignRanks()functionality across the codebase.src/tests/topp/IDFilter_24_output.consensusXML (1)
15-38: Generated test artefact – no code behaviour affected. Skipping detailed review.src/tests/topp/FalseDiscoveryRate_7_output.idXML (1)
7-55: Test output update only; schema remains valid. Nothing to review here.src/tests/topp/IDFilter_11_output.idXML (13)
14-14: Alignsignificance_thresholdto floating‑point format
The<ProteinIdentification>element now usessignificance_threshold="0.0"instead of"0", which matches the refactored code treating thresholds as floats.
15-15: ConvertProteinHitscore to floating‑point
The first<ProteinHit>now hasscore="0.0". Confirm that the test harness compares this exact string and does not strip trailing zeros.
18-18: Verify updated ordering for secondProteinHit
The second hit is nowid="PH_1"withscore="0.0"after sorting. Ensure this new ordering aligns with the sort‑based logic replacingassignRanks().
21-21: Check thirdProteinHitfloat formatting
The third hit usesid="PH_2"andscore="0.0". Confirm that the test output’s ordering and literal formatting match the XML writer’s output.
24-24: Confirm fourthProteinHitmapping
Updated toid="PH_3"withscore="0.0". Please verify the ID-to-score association remains correct after rank removal.
35-35: Floating‑point forFido_prob_spurious
Changed tovalue="0.0"; this aligns with the refactored probability outputs. Ensure no unintended rounding or truncation occurs during serialization.
36-41: Verify reorderedindistinguishable_proteins_*entries
The indices and associatedPH_*IDs have been re‑ordered to reflect sorted probabilities. Confirm the sequence (0…5) matches descending probability order and that the numbering is contiguous.
43-44: High‑precision floats in firstPeptideIdentificationandPeptideHit
Updatedsignificance_threshold="0.0",MZ="486.475325031900013",RT="358.379999999999995"andscore="0.0486". Verify that the XML writer emits exactly these representations to pass string‑based tests.
49-50: Apply float formatting to second peptide entry
The second<PeptideIdentification>now hassignificance_threshold="0.0"and its<PeptideHit>usesscore="0.0". Ensure the test comparator expects the new literal values and formatting.
55-56: Precision check for third peptide match
MZ="345.193225031899999"andRT="377.29000000000002"withscore="0.0"may be sensitive to rounding. Confirm that these long‑form floats match exactly what the code outputs.
61-62: Validate fourth peptide float precision
MZ="350.700875031900011",RT="378.29000000000002", andscore="0.0"should correspond precisely to the computed values. Check for any off-by-one rounding errors.
67-68: Consistent float formatting for fifth peptide
MZ="804.383175031900009",RT="383.879999999999996", andscore="0.0"have high precision. Ensure the XML serializer doesn’t collapse or alter these values in practice.
73-74: Float representation in last peptide match
The final entry updatedMZ="383.217350031900025"andRT="391.0". Verify thatRTis serialized as"391.0"(not"391") to satisfy exact string comparison in tests.
| <ProteinHit id="PH_4" accession="sp|Q96QS3|ARX_HUMAN" score="0.0" sequence="" > | ||
| <UserParam type="string" name="isDecoy" value="false"/> | ||
| </ProteinHit> | ||
| <ProteinHit id="PH_5" accession="sp|Q96NH3|BROMI_HUMAN" score="0.0" sequence="" > | ||
| <UserParam type="string" name="isDecoy" value="false"/> |
There was a problem hiding this comment.
Inconsistent decoy flag attribute names
The entries for PH_4 and PH_5 still use name="isDecoy", whereas the earlier protein hits use name="target_decoy". This mismatch can break parsers expecting a uniform attribute.
Recommend renaming isDecoy → target_decoy for those two <UserParam> elements.
|
Doesn't look so bad. Unfortunately sorting changed a bit so test output is hard to compare. But an initial check showed that it's really just the order of the proteins that changes. Not their score or associations. |
| TEST_EQUAL(hits[2].getSequence(), AASequence::fromString("C")); | ||
| TEST_REAL_SIMILAR(hits[2].getScore(), 0.3); | ||
|
|
||
| // hits with the same score get assigned the same rank: |
There was a problem hiding this comment.
| // hits with the same score get assigned the same rank: |
There was a problem hiding this comment.
this use case is not directly supported anymore. would need to be done on the score itself
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
CHANGELOG (1)
27-28: Consider clarifying the changelog entry.The current entry "Removed assignRanks and sortByRanks in PeptideIdentifications and sort and filter by score" could be more specific about what was removed vs. what replaces it.
Consider rewording for clarity:
- - Removed assignRanks and sortByRanks in PeptideIdentifications and sort and filter by score. + - Removed assignRanks() and sortByRank() methods from PeptideIdentification class. Sorting peptide hits by their main score (order in getHits() vector) now implicitly assigns ranks.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
CHANGELOG(1 hunks)src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h
⏰ Context from checks skipped due to timeout of 90000ms (6)
- GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
- GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
- GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
- GitHub Check: build-and-test (macos-13, xcode, 14.2)
- GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
- GitHub Check: cppcheck-test
jpfeuffer
left a comment
There was a problem hiding this comment.
Looks good. I checked the smallest test and only the sorting of the proteins changed, not the actual associations so it should be fine.
| updateHitRanks(ids); | ||
| if (min_rank > 1) | ||
| // calculate ranks and store them in a vector of ints | ||
| for (auto id_it = ids.begin(); id_it != ids.end(); ++id_it) |
There was a problem hiding this comment.
this whole thing can be shortened to
template<class IdentificationType>
static void filterHitsByRank(std::vector<IdentificationType>& ids, Size min_rank, Size max_rank)
{
for (auto& id : ids)
{
auto& hits = id.getHits();
if (hits.empty()) continue;
id.sort(); // Ensure hits are properly sorted
// ignore max_rank?
if (max_rank < min_rank) max_rank = hits.size();
Size rank = 1;
double last_score = hits.front().getScore();
// Remove hits not within [min_rank, max_rank], while computing rank on the fly
hits.erase(
std::remove_if(hits.begin(), hits.end(),
[&](const auto& hit) {
if (hit.getScore() != last_score)
{
++rank;
last_score = hit.getScore();
}
return rank < min_rank || rank > max_rank;
}),
hits.end()
);
}
}
There was a problem hiding this comment.
will add it to the next PR. I'm not done with ranks ;)
Description
Having assignRanks() in PeptideIdentification was kind of a strange design decision (probably motivated by some file formats).
In principle, a simple sort is sufficient to implicitly assign ranks to peptide hits based on the main score (e.g., the order in the getHits() vector determines the rank).
This PR is a first step to getting rid of the ranks_ member and further simplify the id datastructures.
Checklist
How can I get additional information on failed tests during CI
Click to expand
If your PR is failing you can check outIf you click in the column that lists the failed tests you will get detailed error messages.
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.rebuild jenkinswill retrigger Jenkins-based CI buildsSummary by CodeRabbit
Summary by CodeRabbit
Refactor
Tests
Style
End-users will observe peptide and protein hits ordered by score without explicit rank annotations.