Repository navigation
perf: fast FragmentIndex build with bitmask modification enumeration - #9088
Conversation
|
@timosachsenberg Please consider adding the following names to the Timo Sachsenberg Here's a patch that does this: --- AUTHORS 2026-04-06 09:28:59.198123444 +0000
+++ AUTHORS.new 2026-04-06 09:29:03.254482530 +0000
@@ -5,17 +5,18 @@
The following authors contributed to OpenMS at some point. For the
authors contributing to a specific piece of code, please refer to
the authors tag in the respective file header.
+ - Michael R. Crusoe
- Achal Bajpai
- Aditya Muzumdar
- Ahmed Khalil
- Alexandra Scherbart
- - Axel Walter
- Alexandra Zerck
- Amanda Wein
- Andreas Bertsch
- Andreas Simon
- Anton Kriese
- Anton Pervukhin
+ - Axel Walter
- Bastian Blank
- Chenghao Zhu
- Chirag Dave
@@ -26,8 +27,8 @@
- Cornelia Friedle
- Daniel Jameson
- Darren Kessner
- - David Wojnar
- David Voigt
+ - David Wojnar
- Dhanmoni Nath
- Dilek Dere
- Dimitri Schachmann
@@ -75,8 +76,8 @@
- Lucia Espona
- Lukas Mueller
- Lukas Zimmermann
- - Marcel Schilling
- Marc Sturm
+ - Marcel Schilling
- Markus Mueller
- Martin Langwisch
- Mateusz Łącki
@@ -84,7 +85,6 @@
- Matteo Pilz
- Matthew The
- Matthias Bernt
- - Michael R. Crusoe
- Michał Startek
- Mohamed Ali
- Nico Pfeifer
@@ -110,11 +110,11 @@
- Sven Nahnsen
- Svetlana Kutuzova
- Swenja Wagner
- - Taraneh Strunk
- Tapasweni Pathak
+ - Taraneh Strunk
+ - Till Englert
- Timo Sachsenberg
- Tinatin Kasradze
- - Till Englert
- Tom David Müller
- Tom Lukas Lankenau
- Tom Waschischeck |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR optimizes fragment generation in Changes
Suggested Labels
Suggested Reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 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
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/openms/source/ANALYSIS/ID/FragmentIndex.cpp (1)
263-276:⚠️ Potential issue | 🟠 MajorPreserve the original variant index before the mass filter.
Line 368 later replays
mod_peptides[pep.modification_idx_], but heremodification_idxonly advances for variants that survive the mass filter. Once an earlier variant is skipped, the stored index points at a different modified peptide and the fragment table is built from the wrong sequence.Proposed fix
- UInt32 modification_idx = 0; - for (const AASequence& modified_peptide : modified_peptides) + for (UInt32 modification_idx = 0; modification_idx < modified_peptides.size(); ++modification_idx) { + const AASequence& modified_peptide = modified_peptides[modification_idx]; float modified_mz = modified_peptide.getMZ(1); if (modified_mz < peptide_min_mass_ || modified_mz > peptide_max_mass_) { continue; } thread_peptides[tid].emplace_back(static_cast<UInt32>(protein_idx), modification_idx, std::make_pair(static_cast<uint16_t>(digested_peptide.first), static_cast<uint16_t>(seq_len)), modified_mz); - ++modification_idx; }Also applies to: 368-395
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/ID/FragmentIndex.cpp` around lines 263 - 276, The stored variant index (modification_idx) is only incremented for variants that pass the mass filter, causing later lookups (e.g., mod_peptides[pep.modification_idx_] used when building the fragment table) to reference the wrong modified peptide; fix by ensuring modification_idx is incremented for every iteration of the modified_peptides loop (i.e., maintain the original variant index across the mass filter) and use that original index when calling thread_peptides[tid].emplace_back so the saved modification_idx matches the index in modified_peptides used later when constructing the fragment table.
🧹 Nitpick comments (1)
src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h (1)
255-289: Use the project Doxygen format for these new declarations.These new header comments use
///blocks, and the helper declaration is missing an@brief, so they don't match the repository's header documentation convention.As per coding guidelines,
Use Doxygen /** */ block comments with @ tags (not \ backslash) for documentationandInclude@brieftag in all Doxygen documentation blocks.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h` around lines 255 - 289, The new header comments use triple-slash style and lack `@brief`; update documentation to the project's Doxygen block style by replacing the /// comments with /** */ blocks and adding `@brief` and appropriate `@param/`@return/@note tags where relevant; apply this to the residue_mass_table_, mass_table_initialized_, initResidueMassTable_(), the IonOffsets struct and ion_offsets_, and the generateFragmentsLightweight_() declaration (include `@param` entries for fragments, sequence, seq_len, peptide_idx, n_term_mod_mass, c_term_mod_mass, residue_mod_masses and a short `@brief` describing the lightweight fragment generation).
🤖 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/source/ANALYSIS/ID/FragmentIndex.cpp`:
- Around line 95-119: The code currently iterates over all seq_len residues and
emits full-length terminal ions (b_n/a_n/c_n and y_n/x_n/z_n); change the loops
that build fragment ions (the one using seq_len, cumulative, sequence and the
corresponding reverse/other-ion loop referenced around lines 131-155) to stop at
the last cleavage position (i < seq_len - 1) so only cleavage fragments are
indexed; handle empty/length-1 peptides safely (check seq_len > 1 before
subtracting) and update both the forward loop that uses
add_b_ions_/add_a_ions_/add_c_ions_ and the reverse/y-ion loop so they do not
emit precursor-length ions.
- Around line 55-60: The residue_mass_table_ is only populated for the 20-letter
aa_codes so residues like 'U' end up with zero mass when has_modifications is
false; fix by iterating over all single-letter residues available from ResidueDB
(use ResidueDB::getInstance() and ResidueDB::getResidue(char)) and fill
residue_mass_table_ for each valid residue with
r->getMonoWeight(Residue::Internal), or alternatively add a runtime fallback in
the code paths that use residue_mass_table_ (when has_modifications is false) to
call ResidueDB::getResidue(...) / getMonoWeight if the table entry is unset;
update the initialization near aa_codes and the lookup sites that read
residue_mass_table_ to use this robust path so non-canonical single-letter
residues get correct masses.
---
Outside diff comments:
In `@src/openms/source/ANALYSIS/ID/FragmentIndex.cpp`:
- Around line 263-276: The stored variant index (modification_idx) is only
incremented for variants that pass the mass filter, causing later lookups (e.g.,
mod_peptides[pep.modification_idx_] used when building the fragment table) to
reference the wrong modified peptide; fix by ensuring modification_idx is
incremented for every iteration of the modified_peptides loop (i.e., maintain
the original variant index across the mass filter) and use that original index
when calling thread_peptides[tid].emplace_back so the saved modification_idx
matches the index in modified_peptides used later when constructing the fragment
table.
---
Nitpick comments:
In `@src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h`:
- Around line 255-289: The new header comments use triple-slash style and lack
`@brief`; update documentation to the project's Doxygen block style by replacing
the /// comments with /** */ blocks and adding `@brief` and appropriate
`@param/`@return/@note tags where relevant; apply this to the residue_mass_table_,
mass_table_initialized_, initResidueMassTable_(), the IonOffsets struct and
ion_offsets_, and the generateFragmentsLightweight_() declaration (include
`@param` entries for fragments, sequence, seq_len, peptide_idx, n_term_mod_mass,
c_term_mod_mass, residue_mod_masses and a short `@brief` describing the
lightweight fragment generation).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 8beba0da-b6b7-4f95-a5dc-efe59ac87523
📒 Files selected for processing (3)
src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.hsrc/openms/source/ANALYSIS/ID/FragmentIndex.cppsrc/tests/class_tests/openms/executables.cmake
|
This somehow does not make sense, in the query PR you said the index build is the bottleneck. Now you have over 90% of the time spent in querying?? |
|
Also it is still very inefficient because fragments of variably modified peptides are heavily shared. |
|
if it is not index and not query then it must be the scoring ;) |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/openms/source/ANALYSIS/ID/FragmentIndex.cpp (1)
268-281:⚠️ Potential issue | 🔴 CriticalKeep
modification_idx_aligned with the full modified-peptide enumeration.Line 373 replays
applyVariableModifications()and indexesmod_peptides[pep.modification_idx_]. Heremodification_idxonly advances after the precursor-m/z window check passes, so any earlier filtered-out variant shifts the stored index onto the wrong modified sequence. That silently generates fragments for a different peptide whenever only some variants survive the mass filter.Proposed fix
- UInt32 modification_idx = 0; - for (const AASequence& modified_peptide : modified_peptides) + for (Size modification_idx = 0; modification_idx < modified_peptides.size(); ++modification_idx) { + const AASequence& modified_peptide = modified_peptides[modification_idx]; float modified_mz = modified_peptide.getMZ(1); if (modified_mz < peptide_min_mass_ || modified_mz > peptide_max_mass_) { continue; } thread_peptides[tid].emplace_back(static_cast<UInt32>(protein_idx), - modification_idx, + static_cast<UInt32>(modification_idx), std::make_pair(static_cast<uint16_t>(digested_peptide.first), static_cast<uint16_t>(seq_len)), modified_mz); - ++modification_idx; }Also applies to: 373-373
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/ID/FragmentIndex.cpp` around lines 268 - 281, The stored modification index must reflect the full enumeration of modified_peptides even when a variant is filtered by the precursor m/z window: in the loop over modified_peptides in FragmentIndex.cpp update modification_idx for every modified_peptide (not only after passing the mass check) so that the saved modification_idx matches the index used later by applyVariableModifications() / mod_peptides[pep.modification_idx_]; move or duplicate the ++modification_idx so it always increments per iteration (or use the loop index) and ensure the tuple pushed into thread_peptides continues to use the correct modification_idx value for that iteration.
🧹 Nitpick comments (1)
src/openms/source/ANALYSIS/ID/FragmentIndex.cpp (1)
244-257: Avoid reintroducing asubstr()allocation in the hot path.Line 246 allocates a new string for every digested peptide just to reject
X/B/Z/J, and that happens before both the modified and unmodified branches. Scanningseq_ptr/seq_lendirectly (or via a non-owning view) keeps the fast path allocation-free.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/ID/FragmentIndex.cpp` around lines 244 - 257, The code currently allocates a temporary string via protein.sequence.substr(...) to check for forbidden AAs before using seq_ptr/seq_len; replace that allocation by scanning the peptide range directly (e.g., construct a non-owning std::string_view sub(protein.sequence.data() + digested_peptide.first, digested_peptide.second) and call sub.find_first_of("XBZJ") or implement a small loop that checks seq_ptr[0..seq_len) for any of 'X','B','Z','J'), then if found perform the `#pragma` omp atomic skipped_peptides++ and continue; update the block around seq_ptr/seq_len to use this non-owning check so no per-peptide allocation occurs.
🤖 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/source/ANALYSIS/ID/FragmentIndex.cpp`:
- Around line 34-35: Wrap the OpenMP include and all OpenMP runtime calls in
FragmentIndex.cpp with preprocessor guards: enclose the line including <omp.h>
and every use of omp_get_max_threads() and omp_get_thread_num() (occurrences
around the blocks that currently call these functions) inside `#ifdef` _OPENMP /
`#endif` so the file compiles when OpenMP is disabled; where thread-count or
thread-id values are used, provide a fallback (e.g., treat as single-threaded /
thread id 0) when _OPENMP is not defined so logic using those values still
works.
- Around line 45-73: Replace the unsynchronized lazy-init in
FragmentIndex::initResidueMassTable_ (which currently checks
mass_table_initialized_ and writes residue_mass_table_ and ion_offsets_) with a
thread-safe one-time initialization: use either a function-local static or
std::call_once with a static std::once_flag to ensure the body that fills
residue_mass_table_ and sets ion_offsets_ runs exactly once across threads, and
remove or stop relying on the plain mass_table_initialized_ flag; keep the same
initialization logic but guarded by the one-time mechanism so
initResidueMassTable_ is race-free.
---
Outside diff comments:
In `@src/openms/source/ANALYSIS/ID/FragmentIndex.cpp`:
- Around line 268-281: The stored modification index must reflect the full
enumeration of modified_peptides even when a variant is filtered by the
precursor m/z window: in the loop over modified_peptides in FragmentIndex.cpp
update modification_idx for every modified_peptide (not only after passing the
mass check) so that the saved modification_idx matches the index used later by
applyVariableModifications() / mod_peptides[pep.modification_idx_]; move or
duplicate the ++modification_idx so it always increments per iteration (or use
the loop index) and ensure the tuple pushed into thread_peptides continues to
use the correct modification_idx value for that iteration.
---
Nitpick comments:
In `@src/openms/source/ANALYSIS/ID/FragmentIndex.cpp`:
- Around line 244-257: The code currently allocates a temporary string via
protein.sequence.substr(...) to check for forbidden AAs before using
seq_ptr/seq_len; replace that allocation by scanning the peptide range directly
(e.g., construct a non-owning std::string_view sub(protein.sequence.data() +
digested_peptide.first, digested_peptide.second) and call
sub.find_first_of("XBZJ") or implement a small loop that checks
seq_ptr[0..seq_len) for any of 'X','B','Z','J'), then if found perform the
`#pragma` omp atomic skipped_peptides++ and continue; update the block around
seq_ptr/seq_len to use this non-owning check so no per-peptide allocation
occurs.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: a5735a82-5707-40b3-a93a-fec6f93955c2
📒 Files selected for processing (1)
src/openms/source/ANALYSIS/ID/FragmentIndex.cpp
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/tests/topp/CMakeLists.txt (1)
2945-2956:⚠️ Potential issue | 🟠 MajorBound thread usage for this integration test.
Line 2956 removes explicit
-threads, so this test now follows host-default threading (often all cores). In parallel CTest runs, that can cause oversubscription and unstable runtime. Please keep an explicit cap here (consistent with the neighboring DDA test).Suggested fix
add_test("TOPP_PeptideDataBaseSearchFI_DDA" ${TOPP_BIN_PATH}/PeptideDataBaseSearchFI -test -in ${OPENTIMS_DDA_SYMLINK} -database ${OPENTIMS_TEST_FASTA} -out ${TESTS_TEMP_DIR}/PeptideDataBaseSearchFI_DDA_out.tmp.idXML -Search:precursor:mass_tolerance 20 -Search:precursor:mass_tolerance_unit ppm -Search:fragment:mass_tolerance 20 -Search:fragment:mass_tolerance_unit ppm -Search:enzyme Trypsin/P -Search:peptide:missed_cleavages 2 "-Search:modifications:variable" "Oxidation (M)" "Acetyl (Protein N-term)" - -Search:decoys) + -Search:decoys + -threads 4)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/tests/topp/CMakeLists.txt` around lines 2945 - 2956, The test "TOPP_PeptideDataBaseSearchFI_DDA" currently omits an explicit -threads setting and thus inherits host-default threading which can oversubscribe CPUs during parallel CTest runs; update the add_test invocation for TOPP_PeptideDataBaseSearchFI_DDA to include an explicit "-threads" argument (matching the cap used by the neighboring DDA test) so the PeptideDataBaseSearchFI invocation is limited to a fixed number of threads and prevents parallel oversubscription.
🤖 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/topp/PeptideDataBaseSearchFI.cpp`:
- Around line 90-94: The current logic in PeptideDataBaseSearchFI.cpp treats
getIntOption_("threads") <= 1 as "auto/all-cores" by calling
TOPPBase::setMaxNumberOfThreads(0), which overrides an explicit -threads 1;
change the branching so that only non-positive or unset values (e.g., < 1) map
to auto/all-cores (setMaxNumberOfThreads(0)), while an explicit threads == 1 is
honored (setMaxNumberOfThreads(1)); update the code around
getIntOption_("threads") to use < 1 for the auto case or explicitly pass
getIntOption_("threads") to setMaxNumberOfThreads, mirroring
SimpleSearchEngine's behavior.
In `@src/topp/SimpleSearchEngine.cpp`:
- Around line 95-99: The current check collapses explicit "-threads 1" into
all-cores mode; change the condition in SimpleSearchEngine.cpp so
TOPPBase::setMaxNumberOfThreads(0) is only called when the user explicitly
requested 0 threads (or left the option unset and you handle that separately),
not when getIntOption_("threads") == 1; specifically replace the if
(getIntOption_("threads") <= 1) with a test for threads == 0 (or use an explicit
option-presence check) so that a user-requested threads==1 remains
single-threaded while threads==0 enables all cores.
---
Outside diff comments:
In `@src/tests/topp/CMakeLists.txt`:
- Around line 2945-2956: The test "TOPP_PeptideDataBaseSearchFI_DDA" currently
omits an explicit -threads setting and thus inherits host-default threading
which can oversubscribe CPUs during parallel CTest runs; update the add_test
invocation for TOPP_PeptideDataBaseSearchFI_DDA to include an explicit
"-threads" argument (matching the cap used by the neighboring DDA test) so the
PeptideDataBaseSearchFI invocation is limited to a fixed number of threads and
prevents parallel oversubscription.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: e3d30e32-36c1-4c2b-a9cb-7a2b21743050
📒 Files selected for processing (4)
src/openms/source/APPLICATIONS/TOPPBase.cppsrc/tests/topp/CMakeLists.txtsrc/topp/PeptideDataBaseSearchFI.cppsrc/topp/SimpleSearchEngine.cpp
Benchmark results (timsTOF DDA, human Swiss-Prot, 20 cores)
The lightweight fragment generation ( CodeRabbit findings addressed
|
|
P.S. Claude was stupid today and reverted the wrong things twice before getting it right. Apologies for the messy git history. |
|
My PR would not help since it only generates the full peptide masses, no fragments. The whole TSG needs to be re-written. |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h (1)
5-6: Fill in the$Maintainer:$and$Authors:$markers.The file preamble has empty maintainer and authors fields. As per coding guidelines, all
.hfiles must include$Maintainer:$and$Authors:$markers with actual values.Proposed fix
-// $Maintainer: $ -// $Authors: $ +// $Maintainer: Timo Sachsenberg $ +// $Authors: Raphael Förster, Timo Sachsenberg $🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h` around lines 5 - 6, Update the file preamble comment to populate the $Maintainer:$ and $Authors:$ markers with the appropriate names/emails for this component (e.g., the person/team responsible for FragmentIndex and the original authors); locate the header comment adjacent to the FragmentIndex class declaration (symbol: FragmentIndex) and replace the empty markers with the correct maintainer and author entries following the project's marker format.src/openms/source/ANALYSIS/ID/FragmentIndex.cpp (1)
462-479: The bucket building is thread-safe; the TODO can be resolved.Regarding the TODO at line 472 ("is this thread safe????"):
- The
#pragma omp criticalserializesbucket_min_mz_.emplace_back(), so insertions don't race- Each thread's
std::sortoperates on a disjoint fragment slice ([bucket_start, bucket_end)), so no data races- Line 479's sort reorders
bucket_min_mz_because the critical section insertions occur in non-deterministic thread orderThe code is correct; the TODO can be removed or replaced with a brief comment explaining the design.
Clarify the TODO
-//TODO: is this thread safe???? +// Thread-safe: each thread sorts a disjoint slice; bucket_min_mz_ insertions are serialized and re-sorted below.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/ID/FragmentIndex.cpp` around lines 462 - 479, Remove the TODO about thread-safety and replace it with a short comment clarifying that the OpenMP construct makes this block safe: the `#pragma` omp critical protects bucket_min_mz_.emplace_back() from races and each thread calls std::sort on a disjoint range (bucket_start..bucket_end) so there is no data race on fi_fragments_; also note that a final std::sort(bucket_min_mz_.begin(), bucket_min_mz_.end()) is required because bucket_min_mz_ entries are appended in non-deterministic thread order. Use the symbols fi_fragments_, bucketsize_, bucket_min_mz_, bucket_start/bucket_end, the lambda sort, and the `#pragma` omp critical in the comment so future readers can locate the relevant code.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h`:
- Around line 5-6: Update the file preamble comment to populate the
$Maintainer:$ and $Authors:$ markers with the appropriate names/emails for this
component (e.g., the person/team responsible for FragmentIndex and the original
authors); locate the header comment adjacent to the FragmentIndex class
declaration (symbol: FragmentIndex) and replace the empty markers with the
correct maintainer and author entries following the project's marker format.
In `@src/openms/source/ANALYSIS/ID/FragmentIndex.cpp`:
- Around line 462-479: Remove the TODO about thread-safety and replace it with a
short comment clarifying that the OpenMP construct makes this block safe: the
`#pragma` omp critical protects bucket_min_mz_.emplace_back() from races and each
thread calls std::sort on a disjoint range (bucket_start..bucket_end) so there
is no data race on fi_fragments_; also note that a final
std::sort(bucket_min_mz_.begin(), bucket_min_mz_.end()) is required because
bucket_min_mz_ entries are appended in non-deterministic thread order. Use the
symbols fi_fragments_, bucketsize_, bucket_min_mz_, bucket_start/bucket_end, the
lambda sort, and the `#pragma` omp critical in the comment so future readers can
locate the relevant code.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 9480369d-fc11-41a6-bb1a-f4d239359a82
📒 Files selected for processing (3)
src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.hsrc/openms/source/ANALYSIS/ID/FragmentIndex.cppsrc/tests/class_tests/openms/source/FragmentIndex_test.cpp
627141b to
a06c84c
Compare
Replace the Array-of-Structs vector<Fragment> with Structure-of-Arrays (separate float[] for m/z and uint32_t[] for peptide indices). This enables SIMD vectorization of the query hot loop. The query inner loop now uses SSE2 via SIMDe to compare 4 fragment m/z values against the tolerance window per iteration, giving ~3-4x speedup on the most performance-critical path in database search. Changes: - FragmentIndex.h: replace fi_fragments_ with fi_fragment_mzs_ and fi_fragment_peptide_idxs_ parallel vectors - FragmentIndex.cpp: permutation-based sorting for SoA, SIMD query loop with scalar remainder, updated clear()/print_slice() - FragmentIndex_test.cpp: update fragmentsSorted() for SoA access Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Add queryScalar() method that uses the same SoA layout but without SIMD intrinsics, for direct performance comparison. Add benchmark test section that runs both paths 1000 iterations and reports speedup. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
getPeptidesInPrecursorRange() returns a half-open range [first, second) via upper_bound, but query() treated second as inclusive. Fix both SIMD and scalar paths to use >= for the exclusive upper bound check. Also fix benchmark test parameter names and types to match actual FragmentIndex defaults, and register FragmentIndex_test in executables.cmake. Benchmark result: ~2.9x speedup (SIMD vs scalar) on small test case. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Fix: after the SIMD loop's pidx early-exit break, advance i past the processed group (i += 4) so the scalar remainder doesn't re-scan the same elements. This caused duplicate hits whenever the last element in a SIMD group exceeded the peptide_idx range. Add 9 new test sections verifying SIMD vs scalar equivalence across: - Multiple peptides and charge states (1-3) - Real FASTA sequences (from SSE/Comet test data) - Empty precursor range [k, k) - Very small index (< 4 fragments, scalar-only path) - PPM tolerance mode - Tolerance boundary (peaks just inside/outside tolerance) - Multiple fragment charges - Wide precursor window (many candidates) - SoA ordering invariants Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ation - Move fragment reserve() after generatePeptides() so fi_peptides_.size() is nonzero and the preallocation actually works (CodeRabbit finding A) - Add SoA size consistency guard in fragmentsSorted() (CodeRabbit B) - Strengthen simdScalarMatch() to compare actual hit content (peptide_idx + fragment_mz) element-wise, not just hit count (CodeRabbit D) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Benchmarking showed the SIMD query loop provides negligible speedup on real workloads because the build phase (digestion, sorting, OMP critical sections) dominates total runtime (~95%). Remove the SIMD code complexity while keeping the beneficial SoA layout, exclusive range fix, and comprehensive edge case tests. Removed: queryScalar(), SIMDe include, SIMD vs scalar benchmark tests Kept: SoA layout, permutation sort, exclusive range semantics, 6 edge case tests (empty range, small bucket, ppm tolerance, tolerance boundary, wide precursor window, SoA invariants) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ctors Replace the serialized omp critical section (55M mutex acquisitions for fragment push_back) with per-thread vector pairs that accumulate fragments lock-free, then merge into the global SoA arrays after the parallel region. Benchmark on HeLa DDA TimsTOF + Human SwissProt (4 threads): - Wall time: 3m40s → 3m14s (1.13x faster) - CPU time: 5m02s → 3m48s (1.32x less contention) - Results identical (same PSM counts at 1% FDR) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ctors Revert SoA layout (was a net regression: 2x slower, 1.8x more memory due to permutation sort overhead). Keep the original AoS Fragment struct and apply per-thread vector accumulation to eliminate the omp critical section that serialized ~55M push_back calls. Each thread accumulates fragments into its own vector, then vectors are merged sequentially after the parallel region. This avoids mutex contention while keeping AoS in-place sort efficiency. Benchmark on DDA TimsTOF + Human SwissProt (4 threads): develop (omp critical): 1m17s wall, 2m30s CPU, 3326 MB this commit: 57s wall, 1m22s CPU, 3326 MB → 1.35x wall speedup, 1.83x CPU reduction, same memory Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Replace AASequence::fromString + TheoreticalSpectrumGenerator with a static residue mass lookup table (char -> internal monoisotopic mass) for direct fragment m/z computation from protein sequence strings. Changes: - Add residue_mass_table_[128] populated from ResidueDB at first use - Add generateFragmentsLightweight_() computing b/y ions via cumulative sum over the lookup table (no AASequence parsing, no TSG overhead) - Unmodified peptide path in generatePeptides() computes precursor m/z directly from lookup table (eliminates AASequence::fromString entirely) - Modified path extracts per-residue mass deltas from AASequence after modification application, then uses lightweight generator - Per-thread vectors in generatePeptides() (eliminates second omp critical) Build phase timing (20 threads, Human SwissProt): generatePeptides: 5.3s -> 2.1s (2.5x faster) generateFragments: kept at 2.3s (already fast from per-thread vectors) Overall benchmark (DDA TimsTOF + Human SwissProt, 20 threads): develop: 1m17s wall, 2m30s CPU this branch: 1m07s wall, 2m19s CPU (same results, same memory) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ght generation Stop prefix (b/a/c) and suffix (y/x/z) ion loops one position early to match TheoreticalSpectrumGenerator default behavior — avoids emitting full-length ions (b_n/y_n) that are effectively precursor masses. Populate residue mass table from all ResidueDB single-letter codes (A–Z) instead of hardcoding the 20 canonical AAs, so selenocysteine (U) and pyrrolysine (O) get correct masses. Also skip peptides with ambiguous codes (B/Z/J) alongside X. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
PeptideDataBaseSearchFI and SimpleSearchEngine now use all available cores when -threads is not explicitly set (matching Sage's default). TOPPBase::setMaxNumberOfThreads treats 0 as all cores via omp_get_num_procs(). Global default stays at 1 for other tools. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…rt)" This reverts commit 1163082.
…ort)" This reverts commit f48a7a3.
Update all INI/toppas reference files and TOPPBase_test.cpp to match the new threads parameter description "(0 = all available cores)". Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Guard #include <omp.h> with #ifdef _OPENMP and add fallbacks for non-OpenMP builds (num_threads=1, tid=0) - Replace static bool init guard with std::call_once for thread-safe residue mass table initialization - Remove search engine thread overrides that hijacked -threads 1 to mean all cores (threads=0 support remains at TOPPBase level) - Remove J from ambiguous AA filter (ResidueDB defines J/Xle with valid mass) - Replace std::cout with OPENMS_LOG_INFO for progress messages - Remove redundant initResidueMassTable_() call from build() - Rename file-scope static computePrecursorMzFromChars_ to drop trailing underscore (not a member function) - Add lightweight_fragment_count test validating 2*(n-1) fragments Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Replace AASequence::fromString + ModifiedPeptideGenerator with direct bitmask enumeration of variable modification combinations: - Add per-AA modification lookup tables (fixed_mod_deltas_, variable_mod_table_) built once from the modification config - Scan peptide sequences to find variable mod slots (position, delta_mass, mod_ptr) — deterministic left-to-right ordering - Enumerate valid bitmask subsets with conflict detection for multi-mod-per-site (mutually exclusive bits for same position) - Compute precursor m/z as base_mass + sum(selected deltas) - Reconstruct per-residue delta arrays from bitmask in build() for fragment generation (no AASequence needed) - Add reconstructModifiedSequence() for output-time AASequence reconstruction (only called for final ~1000 hits, not millions) - Replace modification_idx_ (UInt32) with mod_bitmask_ (uint32_t) supporting up to 32 variable mod slots per peptide - Simplify PeptideSearchEngineFIAlgorithm hit processing from 10 lines of AASequence reconstruction to single method call - Add edge case tests: multi-mod-per-site, fixed+variable mods, fragment count with modifications, AASequence reconstruction Eliminates all AASequence construction from the build hot path. Expected ~20-50x speedup for the modification branch of build(). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ator Add comprehensive test comparing FragmentIndex bitmask-based modification enumeration against ModifiedPeptideGenerator for correctness: - Simple fixed + variable mods (Carbamidomethyl + Oxidation) - Multiple modifiable sites with combinatorial enumeration - N-terminal variable mod coexisting with residue mod - Two different variable mods targeting the same amino acid - No modifiable sites (fixed mods only, no matching residues) - Mixed site types with max_variable_mods=3 Each case validates variant count, precursor masses, and reconstructed AASequence strings match the original ModifiedPeptideGenerator output. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
PROTEIN_N_TERM mods (e.g., Acetyl (Protein N-term)) should only apply to peptides starting at protein position 0, not to every peptide. Similarly, PROTEIN_C_TERM mods only apply at the protein C-terminus. Pass is_protein_nterm/is_protein_cterm flags to buildModSlots_ based on the peptide's position within the protein sequence. This correctly handles these modifications where ModifiedPeptideGenerator silently skipped them entirely. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Add TOPP_FalseDiscoveryRate_SimpleSearchEngineDDA and TOPP_FalseDiscoveryRate_PeptideDataBaseSearchFIDDA tests that apply 1% PSM FDR filtering after the DDA search, matching the existing TOPP_FalseDiscoveryRate_SageDDA test. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
f138c94 to
0633f6c
Compare
Per-phase timing breakdownDDA TimsTOF HeLa + Human SwissProt (with decoys), Trypsin/P, 2 missed cleavages, Oxidation(M) + Acetyl(Protein N-term) variable:
Build phase (peptides + fragments) is now 9.8s. Remaining bottlenecks are fragment sorting (45.6s) and query/scoring (27.4s). Comparison with other engines (same dataset, same settings)
Note: Sage memory was measured with |
Use @brief style for VarModEntry and ModSlot structs, add documentation for static constexpr sentinel values, replace unicode em-dash with ASCII in reconstructModifiedSequence comment. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
e501e72 to
f6d2706
Compare
Replace single-threaded std::sort with boost::sort::block_indirect_sort for the global fragment m/z sort. This uses std::thread internally (no TBB dependency) and provides ~4.6x speedup on the sort phase (45.6s down to 10.0s on 200M fragments). Also add default constructor to Fragment struct (required for parallel sort temporary buffers). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Sage's default min_ion_index=2 skips b1/b2/y1/y2 ions in preliminary scoring while OpenMS engines match all ions. Set to 0 for an apples-to-apples comparison in the DDA integration test. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
This version is now about same speed. |
Skip the first N ions from each series (b/y/a/c/x/z) during fragment generation. Default 0 (include all ions). Setting to 2 skips b1/b2 and y1/y2, matching Sage's default behavior. This allows direct comparison and can reduce noise from unreliable low-index ions. Includes test validating fragment count with min_ion_index=2. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
Nice! Can you commit a benchmark harness in ./tools or so? I want to try some stuff maybe this week. |
|
I have one already for timstof (needs to be enabled with a cmake flag). Will add more in the future. |
Add missing entries for commits since last sync (2026-04-06): - Boost minimum version raised to 1.81 (#9095) - FragmentIndex default min_ion_index=2, skipping b1/b2/y1/y2 (#9094) - FragmentIndex faster build with bitmask/SoA/SIMD (#9088) - AASequence copy constructor fix in pyOpenMS bindings (#9098) Co-authored-by: Copilot <[email protected]>
Add missing entries for commits since last sync (2026-04-06): - Boost minimum version raised to 1.81 (#9095) - FragmentIndex default min_ion_index=2, skipping b1/b2/y1/y2 (#9094) - FragmentIndex faster build with bitmask/SoA/SIMD (#9088) - AASequence copy constructor fix in pyOpenMS bindings (#9098) Co-authored-by: GitHub Copilot <[email protected]> Co-authored-by: Copilot <[email protected]>
Summary
Overhaul of FragmentIndex build pipeline for dramatically faster peptide/fragment generation:
Build performance
#pragma omp criticalin peptide and fragment generation — eliminates serialization bottleneckstd::array<double, 128>) populated from ResidueDB — replacesAASequence::fromString+TheoreticalSpectrumGeneratorin the hot pathgenerateFragmentsLightweight_()computes b/y/a/c/x/z ion m/z via cumulative sum — no string parsing, no object allocationboost::sort::block_indirect_sort— 4.6x speedup on global m/z sort (45s → 10s)Bitmask modification enumeration
AASequence+ModifiedPeptideGeneratorwith direct bitmask enumeration of variable modification combinations(position, mod_type, delta_mass)— deterministic left-to-right orderinguint32_tbitmask subsets with conflict detection (mutually exclusive bits for same-position mods)base_mass + sum(selected deltas)— pure arithmetic, no objectsreconstructModifiedSequence()for AASequence recovery at output time only (~1000 hits, not millions)PROTEIN_N_TERM/PROTEIN_C_TERMmodifications based on peptide position in protein (improvement overModifiedPeptideGeneratorwhich silently skips these)Infrastructure
threads=0support at TOPPBase level (-threads 0= all available cores)std::call_once#ifdef _OPENMPguards on all OpenMP API calls (non-OpenMP build support)std::popcountinstead of__builtin_popcount(MSVC compat)min_ion_index 0for fair comparison (match all ions like OpenMS engines)Benchmark
DDA TimsTOF HeLa + Human SwissProt (with decoys), Trypsin/P, 2 missed cleavages, Oxidation(M) + Acetyl(Protein N-term) variable, matched settings:
45% faster than the baseline (1m47s → 59s). Wall time now matches Sage. Identifies 15% more PSMs with 36% less memory.
Per-phase breakdown (this PR):
Note: Sage memory measured with
/usr/bin/time -von the actual process (SageAdapter reports only the 128 MB wrapper). Sage'smin_ion_indexwas set to 0 for fair comparison (default 2 skips b1/b2/y1/y2 but only affects preliminary scoring — final PSM count is unchanged at 3,756).Test plan
lightweight_fragment_counttest validates 2*(n-1) fragment countmulti_mod_per_siteandfixed_plus_variable_modsedge case testsModifiedPeptideGeneratorfor 6 scenarios (terminal mods, multi-mod-per-site, mixed sites, no sites)🤖 Generated with Claude Code