Repository navigation
[FEATURE] Simple, targeted, fast IsobaricWorkflow #7298
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
42fab99
8f704fd
f4c7455
6eee06a
bb9f877
821fff3
3bed458
fc427b1
8c95b91
330caa8
404a8b4
e073b20
41ce7ed
36aedc7
2b6b90d
7d9c40f
09f02c4
cb20452
ec4ae91
aa7bad7
c6ebf4b
af4fa16
fe1e028
e7d6c1e
6ed3587
adc42a0
5b6d19b
27dd7cf
068b7c9
a84565c
9538046
934cf4c
a73546e
18d56ea
82b6c6a
43a0fe4
b77d100
a959434
5492a1c
7344ebc
b5e2f04
6cfff54
cc41f46
3b548a4
2f7350d
48e70cd
9b92f09
c6162d4
0d247f7
7551a78
acfffe5
e751b0d
c5458bf
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -13,8 +13,10 @@ | |
| #include <OpenMS/CONCEPT/ProgressLogger.h> | ||
| #include <OpenMS/KERNEL/ConsensusMap.h> | ||
| #include <OpenMS/METADATA/ExperimentalDesign.h> | ||
| #include <OpenMS/METADATA/ProteinIdentification.h> | ||
| #include <OpenMS/METADATA/PeptideIdentificationList.h> | ||
|
|
||
| #include <map> | ||
| #include <unordered_set> | ||
|
|
||
| namespace OpenMS | ||
|
|
@@ -24,26 +26,77 @@ namespace OpenMS | |
| //TODO add another subclass that does score-aware merging? (i.e. only keep best per peptide[sequence]) | ||
|
|
||
| /** | ||
| * @brief Creates a new Protein ID run into which other runs can be inserted. | ||
| * Creates union of protein hits but concatenates PSMs. Checks | ||
| * search engine consistency of all inserted runs. It differs from the IDMerger tool, | ||
| * in that it is an algorithm class and it allows inserting multiple peptide hits per | ||
| * peptide sequence (not only the first occurrence). | ||
| * @brief Algorithm for merging multiple protein and peptide identification runs. | ||
| * | ||
| * @todo allow filtering for peptide sequence to supersede the IDMerger tool. | ||
| * This class creates a new Protein ID run into which other runs can be inserted. | ||
| * It performs the following operations: | ||
| * - Creates a union of protein hits from all inserted runs | ||
| * - Concatenates Peptide-Spectrum Matches (PSMs) from all runs | ||
| * - Checks search engine consistency across all inserted runs | ||
| * - Maintains references between peptide IDs and their corresponding protein IDs | ||
| * | ||
| * The algorithm differs from the IDMerger tool in two key aspects: | ||
| * 1. It is implemented as an algorithm class rather than a tool | ||
| * 2. It allows inserting multiple peptide hits per peptide sequence (not only the first occurrence) | ||
| * | ||
| * The class handles the complexity of merging identification data from different sources | ||
| * while ensuring consistency and maintaining proper references between proteins and peptides. | ||
| * It can be used in workflows where identification results from multiple files or runs | ||
| * need to be combined into a single comprehensive result set. | ||
| * | ||
| * The algorithm can optionally annotate the origin of each identification to maintain | ||
| * traceability of the merged results back to their source files. | ||
| * | ||
| * @see IDMerger | ||
| * | ||
| * @todo Allow filtering for peptide sequence to supersede the IDMerger tool. | ||
| * Make it keep the best PSMs though. | ||
| */ | ||
| class OPENMS_DLLAPI IDMergerAlgorithm: | ||
| public DefaultParamHandler, | ||
| public ProgressLogger | ||
| { | ||
| public: | ||
| explicit IDMergerAlgorithm (const String& runIdentifier = "merged"); | ||
| /** | ||
| * @brief Constructor for the IDMergerAlgorithm. | ||
| * | ||
| * Initializes a new merger with the specified run identifier. | ||
| * | ||
| * @param runIdentifier Base identifier for the merged run (default: "merged") | ||
| * @param addTimeStampToID Whether to append a timestamp to the run identifier for uniqueness (default: true) | ||
| */ | ||
| explicit IDMergerAlgorithm (const String& runIdentifier = "merged", bool addTimeStampToID = true); | ||
|
|
||
| /// Insert (=move and clear) a run with its peptide IDs into the internal merged data structures, | ||
| /// based on the initial mapping from fileorigins to new run | ||
| void insertRuns(std::vector<ProteinIdentification>&& prots, | ||
| /** | ||
| * @brief Insert runs using move semantics. | ||
| * | ||
| * Inserts (moves and clears) protein and peptide identifications into the internal | ||
| * merged data structures. This version uses move semantics for better performance | ||
| * when the source data is no longer needed. | ||
| * Note: | ||
| * - Only inserts PeptideIdentifications from existing runs in @p prots (noop if prots is empty) | ||
| * - Duplicates file origins if multiple (compatible) protein runs from the same spectrumfile | ||
| * are merged | ||
| * | ||
| * @param prots Vector of protein identifications to be merged | ||
| * @param peps Vector of peptide identifications to be merged | ||
| */ | ||
| void insertRuns(std::vector<ProteinIdentification>&& prots, | ||
| PeptideIdentificationList&& peps); | ||
|
|
||
|
Comment on lines
+70
to
+86
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Guard against empty input for move-variant insertRuns. Implementation reads search params from prots[0]; if prots is empty and this is the first insert, this will read out of bounds. Proposed fix in the .cpp (move overload): void IDMergerAlgorithm::insertRuns(
std::vector<ProteinIdentification>&& prots,
PeptideIdentificationList&& peps
)
{
+ if (prots.empty()) return; // or throw; align with copy-variant behavior
🤖 Prompt for AI Agents
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. how to handle?
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧩 Analysis chain@timosachsenberg The potential out-of-bounds issue identified by CodeRabbit is legitimate and should be addressed. Looking at the current implementation, there are a few ways to handle this: Recommended ApproachAdd input validation at the beginning of both void IDMergerAlgorithm::insertRuns(
std::vector<ProteinIdentification>&& prots,
PeptideIdentificationList&& peps)
{
// Validate inputs - both should be non-empty for meaningful merging
if (prots.empty() || peps.empty()) {
OPENMS_LOG_WARN << "Skipping insertion of empty protein or peptide identification vectors" << std::endl;
return;
}
// Rest of existing implementation...
}Alternative Approaches
if (prots.empty() || peps.empty()) {
throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Cannot insert empty identification vectors");
}
if (prots.empty()) {
OPENMS_LOG_WARN << "Skipping insertion due to empty protein identifications" << std::endl;
return;
}Why This MattersThe current implementation accesses I recommend the first approach (log warning and return early) as it's the most user-friendly while preventing crashes. This should be applied to both the move and copy variants for consistency. What's your preference for handling this edge case? 🏁 Script executed: Length of output: 14775 @timosachsenberg Looking at the implementation, I can see the exact issue and the solution is straightforward. The ProblemThe move variant of Move variant (vulnerable): void IDMergerAlgorithm::insertRuns(
std::vector<ProteinIdentification>&& prots,
PeptideIdentificationList&& peps)
{
// No bounds checking here!
if (!filled_)
{
// ...
copySearchParams_(prots[0], prot_result_); // ← CRASH if prots is emptyCopy variant (protected): void IDMergerAlgorithm::insertRuns(
const std::vector<ProteinIdentification>& prots,
const PeptideIdentificationList& peps)
{
// Copy logic...
if (prots.empty() || peps.empty()) return; //error? ← Already has protection!The FixAdd the same guard to the move variant. Insert this line right after the opening brace of the move variant: void IDMergerAlgorithm::insertRuns(
std::vector<ProteinIdentification>&& prots,
PeptideIdentificationList&& peps)
{
if (prots.empty() || peps.empty()) return; // Match copy variant behavior
// Rest of existing implementation...This ensures both variants behave consistently and prevents the out-of-bounds access when LocationThe fix should go at line 50 in This is a simple consistency fix that aligns both method variants to handle empty inputs the same way. |
||
| /** | ||
|
jpfeuffer marked this conversation as resolved.
Resolved
|
||
| * @brief Insert runs using copy semantics. | ||
| * | ||
| * Inserts (copies) protein and peptide identifications into the internal | ||
| * merged data structures. This version preserves the source data. | ||
| * Note: | ||
| * - Only inserts PeptideIdentifications from existing runs in @p prots (noop if prots is empty) | ||
| * - Duplicates file origins if multiple (compatible) protein runs from the same spectrumfile | ||
| * are merged | ||
| * | ||
| * @param prots Vector of protein identifications to be merged | ||
| * @param peps Vector of peptide identifications to be merged | ||
| */ | ||
| void insertRuns(const std::vector<ProteinIdentification>& prots, | ||
| const PeptideIdentificationList& peps); | ||
|
|
||
|
|
@@ -54,83 +107,172 @@ namespace OpenMS | |
| // Current solution would be to clear the ProteinIdentification if you do not need the proteins and add all the | ||
| // necessary information about origin(s) to this ProteinIdentification. | ||
|
|
||
| /// Return the merged results and reset/clear all internal data | ||
| /** | ||
| * @brief Return the merged results and reset internal state. | ||
| * | ||
| * Retrieves the merged protein and peptide identifications and clears all internal | ||
| * data structures, preparing the algorithm instance for potential reuse. | ||
| * | ||
| * This method should be called after all desired runs have been inserted to obtain | ||
| * the final merged result. | ||
| * | ||
| * @param prots [out] The merged protein identification containing the union of all protein hits | ||
| * @param peps [out] The merged peptide identifications containing all PSMs from the inserted runs | ||
| * | ||
| * @note After calling this method, the internal state is reset, and the algorithm | ||
| * can be reused for a new merging operation. | ||
| */ | ||
| void returnResultsAndClear(ProteinIdentification& prots, | ||
| PeptideIdentificationList& peps); | ||
|
jpfeuffer marked this conversation as resolved.
Resolved
|
||
|
|
||
| private: | ||
|
|
||
| /// Returns the new identifier. The initial identifier plus a timestamp. | ||
| String getNewIdentifier_() const; | ||
| /** | ||
| * @brief Generate a new identifier for the merged run. | ||
| * | ||
| * Creates a new identifier by combining the base identifier with a timestamp | ||
| * if requested. | ||
| * | ||
| * @param addTimeStampToID Whether to append a timestamp to the identifier | ||
| * @return The generated identifier string | ||
| */ | ||
| String getNewIdentifier_(bool addTimeStampToID) const; | ||
|
|
||
| /// Copies over search parameters | ||
| /** | ||
| * @brief Copy search parameters between protein identifications. | ||
| * | ||
| * Transfers search parameters from one protein identification to another. | ||
| * | ||
| * @param from Source protein identification | ||
| * @param to Destination protein identification | ||
| */ | ||
| static void copySearchParams_(const ProteinIdentification& from, ProteinIdentification& to); | ||
|
|
||
| /// Checks consistency of search engines and settings across runs before merging. | ||
| /// @param protRuns The runs to check (first = implicit reference) | ||
| /// @param experiment_type allow some mismatches in case of other experiment types (e.g. SILAC) | ||
| /// @return all same? TODO: a merged RunDescription about what to put in the new runs (e.g. for SILAC) | ||
| /// @throws BaseException for disagreeing settings | ||
| /** | ||
| * @brief Check consistency of search engines and settings across runs. | ||
| * | ||
| * Verifies that all runs have compatible search engine settings before merging. | ||
| * Uses the first run as an implicit reference. | ||
| * | ||
| * @param protRuns The runs to check (first = implicit reference) | ||
| * @param experiment_type Experiment type to allow certain mismatches (e.g., "SILAC") | ||
| * @return True if all runs are consistent, false otherwise | ||
| * @throws BaseException for disagreeing settings | ||
| * | ||
| * @todo Return a merged RunDescription about what to put in the new runs (e.g., for SILAC) | ||
| */ | ||
| bool checkOldRunConsistency_( | ||
| const std::vector<ProteinIdentification>& protRuns, | ||
| const String& experiment_type) const; | ||
|
|
||
| /// Same as above, if you want to use a specific reference | ||
| /// @param protRuns The runs to check (first = reference) | ||
| /// @param ref A possibly external protein run reference | ||
| /// @param experiment_type allow some mismatches in case of other experiment types (e.g. SILAC) | ||
| /// @return all same? TODO: a merged RunDescription about what to put in the new runs (e.g. for SILAC) | ||
| /// @throws BaseException for disagreeing settings | ||
| /** | ||
| * @brief Check consistency of search engines and settings against a reference. | ||
| * | ||
| * Verifies that all runs have compatible search engine settings before merging, | ||
| * using an explicitly provided reference run. | ||
| * | ||
| * @param protRuns The runs to check | ||
| * @param ref An external protein run to use as reference | ||
| * @param experiment_type Experiment type to allow certain mismatches (e.g., "SILAC") | ||
| * @return True if all runs are consistent with the reference, false otherwise | ||
| * @throws BaseException for disagreeing settings | ||
| * | ||
| * @todo Return a merged RunDescription about what to put in the new runs (e.g., for SILAC) | ||
| */ | ||
| bool checkOldRunConsistency_( | ||
| const std::vector<ProteinIdentification>& protRuns, | ||
| const ProteinIdentification& ref, | ||
| const String& experiment_type) const; | ||
|
|
||
| /// moves and inserts protein IDs if not yet present | ||
| /// then clears the input | ||
| /** | ||
| * @brief Insert protein identifications into the merged result. | ||
| * | ||
| * Moves and inserts protein IDs if not yet present, then clears the input. | ||
| * | ||
| * @param old_protRuns Vector of protein identifications to insert | ||
| */ | ||
| void insertProteinIDs_( | ||
| std::vector<ProteinIdentification>&& old_protRuns | ||
| ); | ||
|
|
||
| /// updates the references in pepIDs to the new protein ID run | ||
| /// then moves the peptide IDs based on the | ||
| /// mapping in | ||
| /** | ||
| * @brief Update peptide ID references and move them to the result. | ||
| * | ||
| * Updates the references in peptide IDs to point to the new protein ID run, | ||
| * then moves the peptide IDs based on the provided mapping. | ||
| * | ||
| * @param pepIDs Vector of peptide identifications to update and move | ||
| * @param runID_to_runIdx Mapping from run IDs to run indices | ||
| * @param originFiles List of origin files for each run | ||
| * @param annotate_origin Whether to annotate peptide IDs with their origin | ||
| */ | ||
| void updateAndMovePepIDs_( | ||
| PeptideIdentificationList&& pepIDs, | ||
| const std::map<String, Size>& runID_to_runIdx, | ||
| const std::vector<StringList>& originFiles, | ||
| bool annotate_origin | ||
| ); | ||
|
|
||
|
|
||
| /** | ||
| * @brief Optimized method to move peptide IDs and reference proteins to result. | ||
| * | ||
| * A faster implementation for moving peptide IDs and their referenced proteins | ||
| * to the result data structures. | ||
| * | ||
| * @param pepIDs Vector of peptide identifications to move | ||
| * @param old_protRuns Vector of protein identifications to reference | ||
| */ | ||
| void movePepIDsAndRefProteinsToResultFaster_( | ||
| PeptideIdentificationList&& pepIDs, | ||
| std::vector<ProteinIdentification>&& old_protRuns | ||
| ); | ||
|
|
||
| /// the resulting new Protein IDs | ||
| /// The resulting merged protein identification | ||
| ProteinIdentification prot_result_; | ||
|
|
||
| /// the resulting new Peptide IDs | ||
| /// The resulting merged peptide identifications | ||
| PeptideIdentificationList pep_result_; | ||
|
|
||
| /** | ||
| * @brief Hash function for protein hits based on accession. | ||
| * | ||
| * @param p Protein hit to hash | ||
| * @return Hash value for the protein hit | ||
| */ | ||
| static size_t accessionHash_(const ProteinHit& p){ | ||
| return std::hash<String>()(p.getAccession()); | ||
| } | ||
|
|
||
| /** | ||
| * @brief Equality function for protein hits based on accession. | ||
| * | ||
| * @param p1 First protein hit to compare | ||
| * @param p2 Second protein hit to compare | ||
| * @return True if the accessions are equal, false otherwise | ||
| */ | ||
| static bool accessionEqual_(const ProteinHit& p1, const ProteinHit& p2){ | ||
| return p1.getAccession() == p2.getAccession(); | ||
| } | ||
|
|
||
| /// Type alias for the hash function | ||
| using hash_type = std::size_t (*)(const ProteinHit&); | ||
|
|
||
| /// Type alias for the equality function | ||
| using equal_type = bool (*)(const ProteinHit&, const ProteinHit&); | ||
|
|
||
| /// Set of collected protein hits using custom hash and equality functions | ||
| std::unordered_set<ProteinHit, hash_type, equal_type> collected_protein_hits_; | ||
|
|
||
|
Comment on lines
+263
to
265
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Undefined behavior: moving out of unordered_set elements via const_cast. Use node handles. Implementation currently does:
Use C++17 node handles to extract and move values safely; this also gives stable container invariants without const_cast. Fix in the .cpp returnResultsAndClear(): - for (auto& p : collected_protein_hits_)
- prots.getHits().push_back(std::move(const_cast<ProteinHit&>(p)));
- // above invalidates set but we clear right after
-
- collected_protein_hits_.clear();
+ // Safely move hits out using node handles (empties the set)
+ for (auto it = collected_protein_hits_.begin(); it != collected_protein_hits_.end(); )
+ {
+ auto nh = collected_protein_hits_.extract(it++);
+ prots.getHits().push_back(std::move(nh.value()));
+ }Optionally, sort for determinism after the move: + auto& hits = prots.getHits();
+ std::sort(hits.begin(), hits.end(),
+ [](const ProteinHit& a, const ProteinHit& b){ return a.getAccession() < b.getAccession(); });
🤖 Prompt for AI Agents
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. thoughts?
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @timosachsenberg The CodeRabbit feedback is spot-on and should definitely be addressed. This is a legitimate undefined behavior issue that could cause problems in practice. Why this matters:
The suggested C++17 node handle solution is excellent because:
Additional benefits of the suggested fix:
I'd recommend implementing the suggested fix. The code change is straightforward and eliminates a real technical debt issue. Since this is in a core algorithm class that could be used in various contexts, having it be rock-solid and standards-compliant is important. The timing is good too - it's better to fix this kind of issue during active development rather than discovering it later when the code is more widely used.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I am getting Segfaults now because of the stupid AI. Thank you for nothing.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @coderabbitai Come back you useless thing and fix what you destroyed!!
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧩 Analysis chain@jpfeuffer I apologize for the segfault! The issue is likely with the iterator usage in the node handle extraction. Here's the corrected implementation: The problem with the suggested code was the Corrected implementation for // Safely move hits out using node handles
while (!collected_protein_hits_.empty())
{
auto nh = collected_protein_hits_.extract(collected_protein_hits_.begin());
prots.getHits().push_back(std::move(nh.value()));
}
// Optional: sort for determinism
auto& hits = prots.getHits();
std::sort(hits.begin(), hits.end(),
[](const ProteinHit& a, const ProteinHit& b){
return a.getAccession() < b.getAccession();
});Alternative safe pattern: // Reserve space for efficiency
prots.getHits().reserve(prots.getHits().size() + collected_protein_hits_.size());
// Extract all elements safely
for (auto it = collected_protein_hits_.begin(); it != collected_protein_hits_.end();)
{
auto nh = collected_protein_hits_.extract(it); // Note: no increment here
prots.getHits().push_back(std::move(nh.value()));
it = collected_protein_hits_.begin(); // Start over since container changed
}The key issues with the original suggestion:
The while loop approach is safest since it always works with 🏁 Script executed: Length of output: 1937 @jpfeuffer I can see the exact problem! The segfault is from this code in // THIS IS CAUSING THE SEGFAULT:
for (auto it = collected_protein_hits_.begin(); it != collected_protein_hits_.end(); )
{
auto nh = collected_protein_hits_.extract(it++); // ← PROBLEM: it++ after extract
prots.getHits().push_back(std::move(nh.value()));
}The issue: Immediate fix - replace those lines with: // SAFE VERSION - replace the for loop with this while loop:
while (!collected_protein_hits_.empty())
{
auto nh = collected_protein_hits_.extract(collected_protein_hits_.begin());
prots.getHits().push_back(std::move(nh.value()));
}Alternative fix if you prefer the for loop style: // ALTERNATIVE SAFE VERSION:
prots.getHits().reserve(prots.getHits().size() + collected_protein_hits_.size());
while (!collected_protein_hits_.empty())
{
auto it = collected_protein_hits_.begin();
auto nh = collected_protein_hits_.extract(it);
prots.getHits().push_back(std::move(nh.value()));
}The root cause was my flawed original suggestion using The while loop approach is bulletproof because it always uses a fresh ✏ Learnings added
|
||
| /// is the resulting protein ID already filled? | ||
| /// Flag indicating whether the resulting protein ID is already filled | ||
| bool filled_ = false; | ||
|
|
||
| /// to keep track of the mzML origins of spectra | ||
| /// Mapping to keep track of the mzML origins of spectra | ||
| std::map<String, Size> file_origin_to_idx_; | ||
|
|
||
| /// the new identifier string | ||
| /// The new identifier string for the merged run | ||
| String id_; | ||
|
|
||
| /// Flag indicating whether the identifier should be fixed (i.e., not contain a timestamp) | ||
| bool fixed_identifier_; | ||
| }; | ||
| } // namespace OpenMS | ||
Uh oh!
There was an error while loading. Please reload this page.