Skip to content

Changes to DecoyDatabase - #8338

Closed
t0mdavid-m wants to merge 2 commits into
developfrom
decoy_database
Closed

t0mdavid-m wants to merge 2 commits into
developfrom
decoy_database

Conversation

@t0mdavid-m

@t0mdavid-m t0mdavid-m commented Oct 30, 2025 •

Copy link
Copy Markdown
Member

Description

Checklist

  • Make sure that you are listed in the AUTHORS file
  • Add relevant changes and new features to the CHANGELOG file
  • I have commented my code, particularly in hard-to-understand areas
  • New and existing unit tests pass locally with my changes
  • Updated or added python bindings for changed or new classes (Tick if no updates were necessary.)

How can I get additional information on failed tests during CI

Click to expand If your PR is failing you can check out

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.
  • setting the label "NoJenkins" will skip tests for this PR on jenkins (saves resources e.g., on edits that do not affect tests)
  • commenting with rebuild jenkins will retrigger Jenkins-based CI builds

⚠️ Note: Once you opened a PR try to minimize the number of pushes to it as every push will trigger CI (automated builds and test) and is rather heavy on our infrastructure (e.g., if several pushes per day are performed).

Summary by CodeRabbit

  • New Features
    • Added a shuffle_decoy_ratio option to generate multiple decoy variants per target sequence.
    • Introduced per-repeat decoy generation with a repeat-specific suffix applied to decoy identifiers.
    • Per-repeat writing of decoys and related neighbor entries to align output with repeats.
    • Deterministic reseeding for protein shuffles to ensure consistent decoy variants across repeats.

@t0mdavid-m t0mdavid-m mentioned this pull request Oct 30, 2025
8 of 13 tasks
@coderabbitai

coderabbitai Bot commented Oct 30, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds a per-repeat decoy generation loop driven by a new shuffle_decoy_ratio option and propagates a per-repeat suffix into decoy identifiers; moves RNA and protein decoy generation and output writing inside that loop and updates getDecoyIdentifier_() signature to accept a suffix.

Changes

Cohort / File(s) Summary
Multi-repeat decoy generation
src/topp/DecoyDatabase.cpp
Adds shuffle_decoy_ratio option and a per-repeat generation loop when ratio > 1; moves RNA and protein decoy generation and output writing inside the loop; appends a per-repeat suffix_string to decoy identifiers; updates getDecoyIdentifier_() signature to add suffix_string; preserves validation, neighbor-mode handling, duplicate checks, and deterministic reseeding across repeats.

Sequence Diagram

sequenceDiagram
    participant User
    participant DecoyDB as DecoyDatabase
    participant GenLoop as Per-Repeat<br/>Generation
    participant SeqProc as Sequence<br/>Processor
    participant Output

    User->>DecoyDB: Run with shuffle_decoy_ratio N
    DecoyDB->>GenLoop: initialize num_repeats = N

    loop For each repeat (i = 1..N)
        GenLoop->>SeqProc: build suffix_string (e.g., "_r{i}")
        alt RNA path
            SeqProc->>SeqProc: handle terminal phosphate/tokenize
            SeqProc->>SeqProc: shuffle or reverse tokens
            SeqProc->>SeqProc: reinject terminal markers
        else Protein path
            SeqProc->>SeqProc: digest to peptides
            SeqProc->>SeqProc: per-peptide shuffle/reverse (deterministic reseed)
            SeqProc->>SeqProc: concatenate peptides
        end
        GenLoop->>DecoyDB: getDecoyIdentifier_(id, decoy_str, suffix_string, as_prefix)
        GenLoop->>Output: write decoy entries (and neighbors if requested)
    end

    Output->>User: N decoy variants per target produced
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Areas to focus:
    • getDecoyIdentifier_() signature change and all call sites within src/topp/DecoyDatabase.cpp.
    • Per-repeat loop correctness and state isolation between repeats (including reseeding logic).
    • Correctness of per-repeat output writing and neighbor-mode handling.
    • Edge cases: shuffle_decoy_ratio = 1, terminal marker handling, and duplicate identifier checks across repeats.

Poem

🐰
I hop through repeats with suffix in tow,
Shuffling strands so new variants grow,
Peptides and RNA twirl in a loop,
Decoys multiply—hop, hop, regroup!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title Check ❓ Inconclusive The title "Changes to DecoyDatabase" is vague and generic, using a non-descriptive pattern that simply references the modified component without conveying the substantive nature of the changes. While the title does correctly identify the file being modified, it fails to communicate what aspect of DecoyDatabase has been changed. Based on the raw summary, the actual changes involve introducing a shuffle_decoy_ratio option, implementing per-repeat decoy generation, extending decoy identifier construction with suffix parameters, and reorganizing output writing logic—none of which are reflected in the title. A developer scanning the repository history would not understand what the primary change entails. Revise the title to be more specific and descriptive about the actual changes. Consider something like "Add per-repeat decoy generation with shuffle_decoy_ratio support" or "Implement multi-variant decoy generation with shuffle ratio" to clearly communicate the primary feature being added and help reviewers and future maintainers quickly understand the purpose of this changeset.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch decoy_database

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bc88568 and 4c0201c.

📒 Files selected for processing (1)
  • src/topp/DecoyDatabase.cpp (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (ubuntu-22.04-arm, g++, 11)
  • GitHub Check: build-and-test (macos-15-intel, xcode, 16.0.0)
  • GitHub Check: build-and-test (macos-26, xcode, 26.0)
  • GitHub Check: cppcheck-test

Comment thread src/topp/DecoyDatabase.cpp Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

♻️ Duplicate comments (1)
src/topp/DecoyDatabase.cpp (1)

396-432: CRITICAL: RNA branch operates on wrong variable—decoys have target sequences!

The RNA processing reads from and writes to entry.sequence (lines 398, 431) instead of decoy_entry.sequence. Since line 471 writes decoy_entry, the output contains:

  • Correct decoy identifier (set at line 394)
  • Incorrect sequence (still the original target sequence)

This completely breaks decoy generation for RNA. Additionally, entry is mutated, so the second repeat would start from the first decoy sequence instead of the target.

Apply this diff to operate on the copy:

-          if (input_type == SeqType::RNA)
-          {
-            string quick_seq = entry.sequence;
-            bool five_p = (entry.sequence.front() == 'p');
-            bool three_p = (entry.sequence.back() == 'p');
+          if (input_type == SeqType::RNA)
+          {
+            string quick_seq = decoy_entry.sequence;
+            bool five_p = (decoy_entry.sequence.front() == 'p');
+            bool three_p = (decoy_entry.sequence.back() == 'p');
             if (five_p) // we don't want to reverse terminal phosphates
             {
               quick_seq.erase(0, 1);
             }
             if (three_p) { quick_seq.pop_back(); }

             vector<String> tokenized;
             std::smatch m;
             std::string pattern = R"([^\[]|(\[[^\[\]]*\]))";
             std::regex re(pattern);

             while (std::regex_search(quick_seq, m, re))
             {
               tokenized.emplace_back(m.str(0));
               quick_seq = m.suffix();
             }

             if (shuffle) { shuffler.portable_random_shuffle(tokenized.begin(), tokenized.end()); }
             else // reverse
             {
               reverse(tokenized.begin(), tokenized.end()); // reverse the tokens
             }
             if (five_p) // add back 5'
             {
               tokenized.insert(tokenized.begin(), String("p"));
             }
             if (three_p) // add back 3'
             {
               tokenized.emplace_back("p");
             }
-            entry.sequence = ListUtils::concatenate(tokenized, "");
+            decoy_entry.sequence = ListUtils::concatenate(tokenized, "");
           }
🧹 Nitpick comments (1)
src/topp/DecoyDatabase.cpp (1)

470-470: Remove misleading comment.

This comment appears after the RNA/protein branches have already executed, suggesting it documents intent rather than upcoming code. Once the branches correctly operate on decoy_entry.sequence, this comment adds no value.

Apply this diff:

           } // protein entry
-
-          //-------------------------------------------------------------
-          // writing output
-          //-------------------------------------------------------------
-          // build decoy_entry.sequence from target_entry.sequence (RNA / protein branches)
           f.writeNext(decoy_entry);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4c0201c and a40d2ed.

📒 Files selected for processing (1)
  • src/topp/DecoyDatabase.cpp (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-26, xcode, 26.0)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (ubuntu-22.04-arm, g++, 11)
  • GitHub Check: build-and-test (macos-15-intel, xcode, 16.0.0)
  • GitHub Check: cppcheck-test
🔇 Additional comments (3)
src/topp/DecoyDatabase.cpp (3)

100-101: LGTM!

The shuffle_decoy_ratio parameter is correctly registered with an appropriate minimum value of 1.


138-142: LGTM!

The signature change correctly adds suffix_string parameter and appends it to both prefix and suffix decoy identifiers.


389-394: LGTM!

The loop structure correctly creates a fresh decoy_entry copy from the immutable target_entry for each repeat, and the per-repeat suffix and identifier are properly constructed.

Comment on lines +433 to +465
else // protein input
{
// sequence
if (shuffle)
// if (terminal_aminos != "none")
if (enzyme != "no cleavage" && (keepN || keepC))
{
shuffler.seed(seed); // identical proteins are shuffled the same way -> re-seed
shuffler.portable_random_shuffle(entry.sequence.begin(), entry.sequence.end());
std::vector<AASequence> peptides;
digestion.digest(AASequence::fromString(entry.sequence), peptides);
String new_sequence = "";
for (auto const& peptide : peptides)
{
p.sequence = peptide.toString();
// TODO why are the functions from TargetedExperiment and MRMDecoy not anywhere more general?
// No soul would look there.
auto decoy_p = shuffle ? m.shufflePeptide(p, identity_threshold, seed, max_attempts)
: MRMDecoy::reversePeptide(p, keepN, keepC, keep_const_pattern);
new_sequence += decoy_p.sequence;
}
entry.sequence = new_sequence;
}
else // reverse
else // no cleavage
{
entry.sequence.reverse();
// sequence
if (shuffle)
{
shuffler.seed(seed); // identical proteins are shuffled the same way -> re-seed
shuffler.portable_random_shuffle(entry.sequence.begin(), entry.sequence.end());
}
else // reverse
{
entry.sequence.reverse();
}
}
} // protein entry

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

CRITICAL: Protein branch operates on wrong variable—decoys have target sequences!

The protein processing reads from and writes to entry.sequence (lines 439, 450, 458, 462) instead of decoy_entry.sequence. This mirrors the RNA issue: line 471 writes decoy_entry with a decoy identifier but the original target sequence.

Apply this diff to operate on the copy:

           else // protein input
           {
             // if (terminal_aminos != "none")
             if (enzyme != "no cleavage" && (keepN || keepC))
             {
               std::vector<AASequence> peptides;
-              digestion.digest(AASequence::fromString(entry.sequence), peptides);
+              digestion.digest(AASequence::fromString(decoy_entry.sequence), peptides);
               String new_sequence = "";
               for (auto const& peptide : peptides)
               {
                 p.sequence = peptide.toString();
                 // TODO why are the functions from TargetedExperiment and MRMDecoy not anywhere more general?
                 //  No soul would look there.
                 auto decoy_p = shuffle ? m.shufflePeptide(p, identity_threshold, seed, max_attempts) 
                                       : MRMDecoy::reversePeptide(p, keepN, keepC, keep_const_pattern);
                 new_sequence += decoy_p.sequence;
               }
-              entry.sequence = new_sequence;
+              decoy_entry.sequence = new_sequence;
             }
             else // no cleavage
             {
               // sequence
               if (shuffle)
               {
                 shuffler.seed(seed); // identical proteins are shuffled the same way -> re-seed
-                shuffler.portable_random_shuffle(entry.sequence.begin(), entry.sequence.end());
+                shuffler.portable_random_shuffle(decoy_entry.sequence.begin(), decoy_entry.sequence.end());
               }
               else // reverse
               {
-                entry.sequence.reverse();
+                decoy_entry.sequence.reverse();
               }
             }
           } // protein entry
📝 Committable suggestion

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

Suggested change
else // protein input
{
// sequence
if (shuffle)
// if (terminal_aminos != "none")
if (enzyme != "no cleavage" && (keepN || keepC))
{
shuffler.seed(seed); // identical proteins are shuffled the same way -> re-seed
shuffler.portable_random_shuffle(entry.sequence.begin(), entry.sequence.end());
std::vector<AASequence> peptides;
digestion.digest(AASequence::fromString(entry.sequence), peptides);
String new_sequence = "";
for (auto const& peptide : peptides)
{
p.sequence = peptide.toString();
// TODO why are the functions from TargetedExperiment and MRMDecoy not anywhere more general?
// No soul would look there.
auto decoy_p = shuffle ? m.shufflePeptide(p, identity_threshold, seed, max_attempts)
: MRMDecoy::reversePeptide(p, keepN, keepC, keep_const_pattern);
new_sequence += decoy_p.sequence;
}
entry.sequence = new_sequence;
}
else // reverse
else // no cleavage
{
entry.sequence.reverse();
// sequence
if (shuffle)
{
shuffler.seed(seed); // identical proteins are shuffled the same way -> re-seed
shuffler.portable_random_shuffle(entry.sequence.begin(), entry.sequence.end());
}
else // reverse
{
entry.sequence.reverse();
}
}
} // protein entry
else // protein input
{
// if (terminal_aminos != "none")
if (enzyme != "no cleavage" && (keepN || keepC))
{
std::vector<AASequence> peptides;
digestion.digest(AASequence::fromString(decoy_entry.sequence), peptides);
String new_sequence = "";
for (auto const& peptide : peptides)
{
p.sequence = peptide.toString();
// TODO why are the functions from TargetedExperiment and MRMDecoy not anywhere more general?
// No soul would look there.
auto decoy_p = shuffle ? m.shufflePeptide(p, identity_threshold, seed, max_attempts)
: MRMDecoy::reversePeptide(p, keepN, keepC, keep_const_pattern);
new_sequence += decoy_p.sequence;
}
decoy_entry.sequence = new_sequence;
}
else // no cleavage
{
// sequence
if (shuffle)
{
shuffler.seed(seed); // identical proteins are shuffled the same way -> re-seed
shuffler.portable_random_shuffle(decoy_entry.sequence.begin(), decoy_entry.sequence.end());
}
else // reverse
{
decoy_entry.sequence.reverse();
}
}
} // protein entry
🤖 Prompt for AI Agents
In src/topp/DecoyDatabase.cpp around lines 433-465, the protein branch
mistakenly reads from and writes to entry.sequence (so decoys keep the original
target sequence); change it to build and modify decoy_entry.sequence instead:
when digesting, generate peptides from entry.sequence but append
decoy_p.sequence to decoy_entry.sequence (not new_sequence/entry.sequence); in
the no-cleavage path initialize decoy_entry.sequence = entry.sequence and then
perform shuffler.portable_random_shuffle on decoy_entry.sequence.begin()/end()
(after seeding) or call decoy_entry.sequence.reverse() for reversal; update any
assignments that set p.sequence or accumulate decoy sequence to use
decoy_entry.sequence so the final written decoy_entry contains the decoy
sequence.

p.sequence = peptide.toString();
// TODO why are the functions from TargetedExperiment and MRMDecoy not anywhere more general?
// No soul would look there.
auto decoy_p = shuffle ? m.shufflePeptide(p, identity_threshold, seed, max_attempts)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify that peptide-level shuffling produces distinct decoys per repeat.

The shufflePeptide call uses the same seed for every repeat. If shufflePeptide reinitializes its RNG with seed each time (rather than advancing shared state), all repeats will produce identical shuffles—similar to the issue at line 457.

Run this script to check whether multiple repeats generate distinct or identical decoy sequences:

If the output shows 3 identical sequences, the seed should be varied by repeat, e.g., seed + num_repeat * 1000.


🏁 Script executed:

#!/bin/bash
# Create a minimal test FASTA with one protein
echo -e ">test_protein\nMKLAVLGAAVGIDLGTTYSCAVAHHFKKEFV" > test_input.fasta

# Run DecoyDatabase with shuffle_decoy_ratio=3
./DecoyDatabase -in test_input.fasta -out test_output.fasta \
  -method shuffle -shuffle_decoy_ratio 3 -enzyme Trypsin \
  -seed 42 -only_decoy

# Extract decoy sequences and check for duplicates
rg -A1 "^>DECOY_test_protein" test_output.fasta | \
  gawk '/^[^>]/ {print}' | \
  sort | uniq -c

# Expected: 3 unique sequences if working correctly
# Bug: 3 identical sequences (count=3 for one sequence)

Length of output: 119



This will help identify where shufflePeptide is defined and how it uses the seed parameter.

---

🏁 Script executed:

```shell
#!/bin/bash
# Search for shufflePeptide function implementation and context around line 446
rg -n "shufflePeptide" --type=cpp -B5 -A10

Length of output: 33090



🏁 Script executed:

#!/bin/bash
# Find the full shufflePeptide implementation to see RNG initialization
rg -n "OpenMS::TargetedExperiment::Peptide MRMDecoy::shufflePeptide" -A 100 src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp | head -120

Length of output: 4466


Peptide-level shuffling generates identical decoys per repeat due to constant seed initialization.

The issue is confirmed. Line 117 of MRMDecoy.cpp shows boost::mt19937 generator(seed); creates a fresh RNG initialized with the same seed value on each call. Since line 446 passes the same seed for every repeat iteration, all shuffles are deterministic and identical.

Fix: Vary the seed by repeat index, e.g., seed + num_repeat * 1000, matching the pattern used for RNA/protein-no-cleavage methods.

                auto decoy_p = shuffle ? m.shufflePeptide(p, identity_threshold, seed + num_repeat * 1000, max_attempts) 
🤖 Prompt for AI Agents
In src/topp/DecoyDatabase.cpp around line 446, the shuffle call uses the same
seed for every repeat, producing identical decoys; update the call to vary the
RNG seed by the repeat index (for example add num_repeat * 1000 to the base
seed) so each repeat gets a distinct seed (matching the pattern used for
RNA/protein-no-cleavage methods).

// sequence
if (shuffle)
{
shuffler.seed(seed); // identical proteins are shuffled the same way -> re-seed

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Re-seeding with the same seed produces identical decoys across repeats.

Line 457 re-seeds with the same seed inside the repeat loop, so every repeat generates an identical shuffled sequence (only the identifier suffix differs). This defeats the purpose of shuffle_decoy_ratio > 1, which should produce distinct decoy variants to improve FDR estimation.

The RNA branch (line 418) correctly avoids re-seeding in the loop, producing different shuffles per repeat.

Apply this diff to vary the seed by repeat number:

               if (shuffle)
               {
-                shuffler.seed(seed); // identical proteins are shuffled the same way -> re-seed
+                shuffler.seed(seed + num_repeat * 1000); // vary seed per repeat; identical proteins in the same repeat still shuffle identically
                 shuffler.portable_random_shuffle(decoy_entry.sequence.begin(), decoy_entry.sequence.end());
               }
📝 Committable suggestion

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

Suggested change
shuffler.seed(seed); // identical proteins are shuffled the same way -> re-seed
if (shuffle)
{
shuffler.seed(seed + num_repeat * 1000); // vary seed per repeat; identical proteins in the same repeat still shuffle identically
shuffler.portable_random_shuffle(decoy_entry.sequence.begin(), decoy_entry.sequence.end());
}
🤖 Prompt for AI Agents
In src/topp/DecoyDatabase.cpp around line 457, the shuffler is re-seeded inside
the repeat loop using the same seed which causes identical decoys for every
repeat; change the logic to derive a unique seed per repeat (for example add or
xor the repeat index to the base seed, or use a hash of seed and repeat) and use
that derived seed when seeding the shuffler so each repeat produces a different
shuffled sequence (match the RNA branch behavior that avoids re-seeding with the
same value).

@jpfeuffer
jpfeuffer deleted the decoy_database branch November 14, 2025 12:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants