Repository navigation
feat(ProSE): SNES variable modifications (v1.1) - #9191
Conversation
…v1, opt-in) Implements the Single-N / Single-C mother-peptide trick from Rolfs, Millikin & Smith (Curr Bioinform 2020, PMC7943061) used in MetaMorpheus. For non- specific enzyme searches (peptide:enzyme_specificity=none, the typical immunopeptidomics workload) the FragmentIndex can now index ~2L mother peptides per protein instead of O(L^2) sub-peptides, with one ion series per mother (b for Single-N, y for Single-C). ProSEAlgorithm realizes the sub-peptide whose precursor mass matches the observed spectrum and re-scores with full b+y HyperScore, preserving score fidelity against a naive search. Smoke-tested on SimpleSearchEngine_1.mzML with enzyme_specificity=none: SNES path yields an identical top-PSM (DFASSGGYVLHLHR, score 16.84) to the naive non-specific path. Implementation: - FragmentIndex bit-31 of mod_bitmask_ distinguishes Single-N (0) from Single-C (1) mothers. Non-SNES searches use all 32 bits as variable-mod slots — zero behavioural or size impact on the trypsin-full path. - is_snes_mode_ gates every SNES code path; non-SNES queries go through the existing precursor-window lookup unchanged. - generateSNESMothers_ enumerates mothers per anchor; build() dispatches fragment-series selection to the new generateFragmentsForSeries_ helper. - getSNESCandidatesForMass provides the one-sided "mother_mass >= P - tol" candidate filter; realizeSNESLength + reconstructRealizedSubSequence recover the true sub-peptide. - Calibration is guarded off in SNES mode (circular with realization). - Variable modifications on mothers are disabled in v1 (documented; v2). Defaults: snes_enabled=false (opt-in while external workloads are validated). Will flip to true in a follow-up. Tests: - Unit: mother count (24 = 2*12 for L=19, window [8,12]), kind-bit tagging, realizeSNESLength on Single-N + Single-C, end-to-end spectrum-to-mother candidate matching. - Regression: all 18 TOPP_ProSE and 8 FalseDiscoveryRate_ProSE* tests still pass unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…tness clang-17 rejects namespace-scope constants referenced inside an omp parallel region with default(none) unless they are explicitly declared in the shared() clause. GCC is permissive here. Mirror the existing proton_mass_u pattern: hoist Constants::C13C12_MASSDIFF_U to a local before the pragma and add it to shared(), so the SNES iso-shift line compiles under both toolchains.
Self-review picked up a handful of documentation, code-hygiene, and test- coverage gaps. Fixes: - FragmentIndex.h: isSnesMode() doc no longer claims auto-enablement; the flag is opt-in in v1 (snes_enabled=false by default). - FragmentIndex.h: generateFragmentsForSeries_ doxygen expanded to one @PARAM per parameter — the compact "add_b/a/c/y/x/z" form tripped the Doxygen_Warning_test on CI. - FragmentIndex.cpp: mother-mass upper-bound comment reworded. It's unambiguously an upper bound regardless of terminal-mod scope; the earlier phrasing suggested otherwise. - FragmentIndex.cpp: per-protein X/B/Z fast path. When the protein has no ambiguous residues (the 99% case), skip the per-mother scan; when it does, locate the next bad residue via find_first_of from the mother start. Removes an O(L^2) hotspot on clean FASTA. - FragmentIndex.cpp: schedule(dynamic, 8) → default schedule, matching the surrounding OMP loops for consistency. - FragmentIndex.cpp: variable-mods warning collapsed from multiple << into a single ListUtils::concatenate emission. Tests: - New: SNES fragment-index size must be smaller than naive SPEC_NONE (confirms mother-peptide enumeration is actually shrinking the index). - New: reconstructRealizedSubSequence with Carbamidomethyl (C) — verifies fixed modifications are applied to the realized sub-peptide. All FragmentIndex/ProSE/FDR tests (26) still pass locally. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…Morpheus-style)
The v1 SNES design used a one-sided mother-mass filter (mother_mass >= P - tol)
to admit candidates. On realistic MHC-II-scale fixtures this admitted roughly
the top half of the index per spectrum, which combined with the max-candidates
top-50 cut pushed real hits off the list and made SNES 19× slower than naive
non-specific search with 20% fewer IDs at 1% FDR.
This commit replaces that primitive with MetaMorpheus's fragment-index-as-
precursor-filter technique (Rolfs/Smith 2020, as implemented in
NonSpecificEnzymeSearchEngine.cs):
1. Byte-count scoring pass. Walk every experimental peak, increment a
per-thread uint16_t score table at every peptide_idx whose indexed
fragment falls within fragment tolerance. No peptide_idx pre-filter.
Reuses a thread_local buffer via .assign() — zero allocations per
spectrum.
2. Candidate collection via fragment-bin precursor lookup. For each
(precursor charge, isotope error), walk fragment buckets at the
target m/z that a realized sub-peptide's terminal ion would occupy:
- Single-N / b-ion: target = (M+H)+ - water
(M_sub+H+ = b_k + water, so the mother's b_k ion lands at the
observed precursor minus water when the realization matches.)
- Single-C / y-ion: target = (M+H)+
(M_sub+H+ = y_k exactly.)
Mothers with a fragment in the target bin that (a) have the correct
kind and (b) meet the min-matched-peaks threshold are emitted as
candidates.
The candidate set is now sized like a single fragment-bin hit — dozens
per spectrum instead of ~N/2. Removes the top-50 cap entirely for SNES.
Benchmark on 2000-protein human DB, length 12-25, 20 ppm, 4 threads:
Naive SNES v1 SNES v2
Wall time 1:19 24:45 1:59 (v1 → v2: 12x faster)
Peak RSS 22 GB 6.6 GB 4.0 GB (5.5x less than naive)
1% FDR PSMs 84 67 69
Page faults 11 M 2.4 B 1.3 M (1800x fewer than v1)
SNES v2 now trades ~1.5× runtime for 5.5× memory reduction — the right
shape for MHC-II workloads that don't fit naive in RAM. The remaining
−18% PSM gap vs naive is not the filter; likely realization-tolerance
detail, to investigate in a follow-up.
Removes the dead v1 primitive getSNESCandidatesForMass() and the SNES
branch in searchDifferentPrecursorRanges().
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…lizations
The fragment-index-as-precursor-filter trick (b-ion target = M+H+ - water,
y-ion target = M+H+) catches every realization at length k where the
mother's b_k or y_k is INDEXED. But the fragment-generation loop emits only
b_1..b_{L-1} and y_1..y_{L-1} — it stops one short of b_L / y_L. So any
realization at k == mother_length is systematically missed.
Cases this matters in practice:
- Sub-peptides of length == max_length (no "longer-mother" partial-
realization alternative to find them)
- Proteins shorter than max_length (every mother is at full protein
length, so full-length realization is the ONLY realization)
MetaMorpheus handles this with a separate PrecursorIndex built from mother
monoisotopic masses (NonSpecificEnzymeSearchEngine.cs:108-114). ProSE
already sorts fi_peptides_ by precursor_mz_, so a direct binary search
recovers the same primitive with zero extra storage.
Added as a third lookup in querySpectrumSNES_, after the two fragment-bin
walks. Shares the same emitted-dedup guard so a mother found via both
paths is only emitted once.
Benchmark — 2000-protein human DB, length 12-25, no variable mods
(apples-to-apples vs naive):
Naive SNES
Wall time 57.5 s 1:58 (2× slower; the tradeoff)
Peak RSS 14.8 GB 4.0 GB (3.7× less — the win)
1% FDR PSMs 68 69 (SNES +1 — parity)
The earlier "−18% PSM gap" turned out to be entirely an artifact of ProSE
defaulting Oxidation (M) as a variable mod. Naive used it, SNES v1
cannot (mother-peptide variable-mod enumeration is deferred to v2). With
variable mods explicitly disabled for both paths the ID counts match.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Handful of correctness + hygiene fixes surfaced by three parallel analysis passes (code review, performance, memory agents). All 26 FragmentIndex/ ProSE/FDR tests pass; benchmark PSM count at 1% FDR unchanged (69). Correctness: - B1: target m/z in the fragment-bin candidate lookup now accounts for fixed terminal modifications. Single-N b-ion target becomes (M+H)+ − water − fixed_cterm_delta_; Single-C y-ion target becomes (M+H)+ − fixed_nterm_delta_. The previous formulas assumed both deltas were zero, so users configuring e.g. Acetyl (N-term) silently lost every SNES candidate. Not triggered by any existing test — bench ran with residue-only Carbamidomethyl (C). - Q2: byte-scan fragment-charge walk now bounded by the max charge in the spectrum's `charges` list (capped by max_fragment_charge_) instead of the static max_precursor_charge_. Matches the non-SNES queryPeaks policy. - L1: generateSNESMothers_ clamps peptide_min_length_ to 1 locally before the Single-C anchor loop, guarding against size_t underflow if the user sets peptide:min_size=0. Preserves the existing FragmentIndex tests that explicitly use min_size=0 — no global minInt guard imposed. Performance: - P1: querySpectrumSNES_ now calls trimHits() at its end, capping the candidate set at max_processed_hits_ like the non-SNES path. On the MHC-II benchmark the candidate count per spectrum is already below the default 50, so wall-time is unchanged — but this provides a safety net for pathological spectra that fire many high-match mothers. - P2: scoreSpectraAgainstIndex_ no longer calls theo_spectrum.sortByPosition() after getSpectrum. TheoreticalSpectrumGenerator already emits sorted output when add_metainfo is true (via sortByPositionPresorted); the extra pass was a redundant O(N) isSorted scan per candidate. Memory: - M2: theo_spectrum is hoisted out of the per-candidate inner loop in scoreSpectraAgainstIndex_ and reused across candidates within a spectrum (cleared with clear(true) before each getSpectrum). Cuts per-candidate heap churn for PeakSpectrum + StringDataArray + IntegerDataArray. Deferred to follow-ups (out-of-scope for this PR): - P3/P5 (bypass AASequence+TSG+HyperScore-by-ion-name for pure fixed-mod SNES) — requires API additions. - M1 (free FragmentIndex before PeptideIndexing) — needs shared context refactor. - Finer fragment-index bucketing (1 mDa) — real root cause of the 2× gap vs naive; separate, larger refactor. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- **#2**: honor `peptide:max_size=0` as "no max" in SNES mother enumeration. Previous code did `std::min(0, L) = 0` → empty index whenever the user relied on the documented "0 disables the limit" semantics. - **#5**: drop `peptide_max_mass_` filter from mother-generation. A mother heavier than peptide_max_mass_ can still have realizable sub-peptides in the configured mass range; the upper bound is enforced later at realization via the precursor-tolerance window. Only the lower bound (`peptide_min_mass_`) is safe to apply at mother-generation time. - **#6**: force SNES mothers to b-only (Single-N) / y-only (Single-C) regardless of the user's add_*_ions toggles. `querySpectrumSNES_` only targets b-ions and y-ions in the candidate lookup, so indexing a/c/x/z on mothers would be wasted storage and silently lose candidates if a user disabled the primary b/y series. Docs/style: - FragmentIndex.h SNES doc: stop referencing the renamed `search:snes_enabled` parameter; clarify that the lower 31 bits of mod_bitmask_ are currently unused (variable mods on mothers are not enumerated in v1). - ProSEAlgorithm.cpp: replace `std::endl` with `\n` in the SNES calibration warning (project guideline). Deferred to roadmap: - CodeRabbit #1 (X/B/Z spanning): current code skips whole mothers when they extend into an ambiguous residue; valid shorter realizations with the same anchor are lost. Fix is to split proteins into unambiguous spans before mother generation — logged in the PR description roadmap as v1.1. - CodeRabbit #3 (one-series min_matched_ions): pre-rescore filter threshold operates on a single ion series and can drop peptides with evidence split across b and y. Needs a separate low prefilter threshold + real threshold after full-series rescoring — logged as v1.1. All 26 FragmentIndex / ProSEAlgorithm / TOPP_ProSE / FalseDiscoveryRate_ProSE tests pass unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Follow-up to internal review of the SNES PR (#9189). - **I1**: The SNES fragment index and its query path hard-code b-ions for Single-N mothers and y-ions for Single-C mothers. Downstream scoring (ProSEAlgorithm) builds theoretical spectra using the user's add_b_ions / add_y_ions toggles, so if a user disabled either series, SNES would admit candidates that then scored against an incomplete theoretical spectrum — silent score-quality degradation. Reject the configuration explicitly in updateMembers_ with an InvalidParameter exception (v1). a/c/x/z remain freely configurable for downstream scoring. - **I2**: Add a one-line INVARIANT comment on the dedup guard reset inside the (charge, iso_err) loop in querySpectrumSNES_. Hoisting the reset above the loop would suppress valid candidates at iso_err != 0 because distinct (charge, iso_err) tuples produce independent candidate rows that must be allowed to re-emit the same mother. - **I3**: Add two new FragmentIndex_test sections: - SNES with Acetyl (N-term) fixed modification: synthesizes a spectrum from a sub-peptide with the acetyl applied, queries the SNES index, and verifies the candidate is found. Exercises the fixed_nterm_delta_ branches at both build-time fragment emission and query-time precursor-target derivation. Regression guard against silent-miss when fixed_[n|c]term_delta_ != 0 (the default Carbamidomethyl (C) fixture has both == 0). - SNES rejects add_b_ions=false / add_y_ions=false: positive case for each disabled toggle + negative case verifying snes_enabled=false accepts the configuration freely. 30/30 FragmentIndex_test sections pass (+2 new). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The Doxygen rule is all-or-nothing per function: if any @PARAM is present, all parameters must be documented. The SNES commit added @PARAM entries only for the six ion-series toggles, leaving seven earlier params (fragments, sequence, seq_len, peptide_idx, n_term_mod_mass, c_term_mod_mass, residue_mod_masses) undocumented. This trips the CI's Doxygen_Warning_test on all 4 Linux/macOS runners (8 errors: 7 undocumented params + 1 per-function header). Add the missing @PARAM entries, copying the wording from generateFragmentsLightweight_ which has the same signature prefix. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Follow-up feature design for the feat/prose-snes-variable-mods branch. Captures: - Scope: query-time variable-mod enumeration (M1, approach A — MetaMorpheus style delta-bag precursor filter + direct per-candidate rescore). - Architecture: mother indexing unchanged; Σ_delta set precomputed in updateMembers_; D× expanded precursor bin walks; subset enumeration via existing buildModSlots_ scoped to realized sub-peptide range. - Components: SpectrumMatch + subset_bitmask_ field; defensive SNES_KIND_BIT_MASK masking in reconstructModifiedSequence; extended reconstructRealizedSubSequence with subset bitmask. - Data-flow worked example (ACDEFMGR with Oxidation on M). - Performance expectations + non-SNES impact (none, additive to SNES paths). - Failure modes, per-tuple subset cap, roadmap for B′ shift-aware filter. Design approved via brainstorming session; implementation plan next. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Reviewer flagged 3 Critical + 4 Important items plus suggestions. Fixes: **Critical**: - C-1 (§5): rewrite data-flow example. Remove proton double-count in observed-(M+H)+ description; reconcile peptide name (ACDEFMGR throughout, not a mix of AKACDEFMGR and ACDEFMGR); document the `shifted_mh` convention explicitly; add explicit note that the Σ subtraction happens in two separate arithmetic contexts (bin-walk target vs realization target). - C-2 (§4.2): spec now defines how bin walks select only protein-anchored mothers — `collect_candidates` gains `require_prot_anchor` enum parameter (NONE / PROT_NTERM / PROT_CTERM) with explicit post-kind-check filter. Pseudocode updated. - C-3 (§3, §4.2, §5): disambiguate the two separate Σ_delta subtractions. Realization target uses the *iso-corrected observed mh+* as input, NOT the fragment-bin target m/z. **Important**: - I-1 (§4.2): min_matched_ions is now applied *uniformly* to all candidates regardless of Σ (no bypass). The Σ>0 under-counting is documented as the accepted tradeoff for v1.1; B′ is the lever if benchmarks show the filter drops true positives. - I-2 (§4.1, §4.2, §4.4): added C-term symmetry — `snes_sigma_delta_set_with_prot_cterm_`, matching walks, matching test. - I-3 (§4.2): changed per-tuple cap to per-mother cap across all (k, Σ) tuples. Rationale: per-tuple caps interact poorly with trimHits (deterministically drops entire mother-subset groups). - I-4 (§4.4): Σ-set test uses precise Unimod deltas (0.984016, 15.994915, 31.989830, etc.) + TEST_REAL_SIMILAR with 1e-4 Da tolerance instead of TEST_EQUAL. **Suggestions addressed**: - S-1 (§4.1): explicit SpectrumMatch field ordering to avoid padding (num_matched_ + subset_bitmask_ adjacent; total 24 B, no padding). - S-2 (§4.1): dedup tolerance rationale (1e-6 Da chosen for FP error absorption across ~16 summed deltas, not just DB dedup). - S-3 (§4.1): clarify subset_bitmask_ indexes into slot list, not raw peptide positions. - S-4 (§6): performance estimates now explicit about D × K scaling; removed unverifiable 2–3× claim vs non-SNES; added benchmark gate before shipping as default-safe. - S-6 (§9): implementation split flagged as open item for plan time. - S-7 (§4.4): separated Σ-set computation unit test from query-path protein-N-term specificity test. **Also added**: - New SpectrumMatch field `sigma_delta_` (float, 4 B) so ProSE knows the mod Σ to subtract from the realization target without re-deriving it. Net struct size unchanged (24 B, no new padding). - Identical-delta mods test (E-5) — regression guard against dedup tolerance swallowing legitimate subsets. - Additional failure-mode row: protein-term-only Σ hitting mid-protein mother gated by require_prot_anchor → no ghost candidate. Verdict was "approve with changes"; all Critical + Important items addressed inline. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
13 tasks, TDD-structured, bite-sized (2-5 min per step): Foundation: 1. Extend SpectrumMatch with subset_bitmask_ and sigma_delta_ 2. Defensive SNES_SLOT_MASK masking in reconstructModifiedSequence Σ-set helper: 3. computeSnesSigmaDeltaSet_ with protein-term specificity flags 4. Populate three sets in updateMembers_ + >64 warning Reconstruction support: 5. Extend reconstructRealizedSubSequence with subset_bitmask parameter Query path: 6. Extend collect_candidates with SnesAnchor + sigma_tag params 7. Restructure querySpectrumSNES_ bin walks (baseline + prot_n/c_term extras) 8. Per-candidate subset enumeration + per-mother cap (16) Integration: 9. ProSE: subtract sigma_delta_, pass subset_bitmask_ Tests: 10. Emit-both degenerate-subset policy 11. Position conflict, max_mods cap, identical-delta mods 12. Protein-N-term and Protein-C-term anchor gating 13. Regression check + CI push Natural PR split at Task 5 documented as optional. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…a_ (SNES v1.1) Adds two 4-byte fields needed by SNES variable-mod support: - subset_bitmask_: indexes into the slot list from buildModSlots_ to identify which variable mods are active for this match. - sigma_delta_: Σ of variable-mod deltas; used by ProSE to subtract from the realization target during AASequence reconstruction. Field layout preserves 8-byte alignment without padding (struct grows 16 B → 24 B). Zero-initialized so non-SNES and unmodified-SNES hits carry identical semantics to v1. No behavior change yet — subsequent commits will populate and consume these fields. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
reconstructModifiedSequence iterated `peptide.mod_bitmask_` directly to select active slots. In SNES mode, bit 31 encodes Single-C-ness rather than a slot, so a bitmask containing only bit 31 (v1 SNES mother with no variable mods) entered the slot-iteration block unnecessarily. Today the loop is no-op because n_slots = 0, but v1.1 will make n_slots > 0 on SNES mothers and the latent bug would materialize. Fix: mask off SNES_KIND_BIT_MASK before the check and during iteration. No behavior change for non-SNES callers (bit 31 is never set there). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Follow-up to 9164556 after code review. reconstructModifiedSequence was hardened, but the parallel slot-iteration path in the fragment- generation pass used the raw pep.mod_bitmask_ too. No current-code bug (non-SNES enumeration caps at n_slots=31 because `1u << n_slots` implicitly UBs at 32), but applying the mask everywhere makes the invariant self-documenting and forward-compatible. Also: tighten the Task 2 test assertion (direct size equality instead of >0 check) and refine the masking comment. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Configuration-global enumeration of distinct Σ values reachable by any subset of variable mods capped by max_variable_mods_per_peptide_. Always includes 0.0. Dedup tolerance: 1e-6 Da (chosen to absorb compounded FP error across up to ~16 summed deltas in double precision, not just modification-database duplicates). Protein-term-specificity gated by two bool parameters; callers will produce three sets (baseline, +PROTEIN_N_TERM, +PROTEIN_C_TERM) to support anchor-dependent bin walks in querySpectrumSNES_. The function calls initModificationTables_() lazily so it can be invoked independently of build()/generatePeptides() (needed by tests and future callers in updateMembers_). Tested with Oxidation (M) + Deamidated (N) + Deamidated (Q) at max=2 → six distinct Σ values matching Unimod reference deltas within 1e-4 Da (deduplication collapses the two identical +0.984016 Da entries). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Follow-up to fdc9522. Code review identified three fixes: 1. computeSnesSigmaDeltaSet_ was non-const to accommodate a lazy initModificationTables_() call because updateMembers_() did not trigger it. Fix the root cause: call initModificationTables_() at the end of updateMembers_() so mod tables reflect current params after every setParameters call. Helper and expose wrapper reverted to const. 2. Dedup eligible_deltas at collection time (halves BFS work when multiple registered mods share a delta, e.g. Deamidated(N)+(Q)). 3. Typo: `/ Respect` → `// Respect`. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Three sets support anchor-dependent bin walks: - baseline: ANYWHERE + peptide-term variable mods - with_prot_nterm: above + PROTEIN_N_TERM mods, for Single-N @ protein pos 0 - with_prot_cterm: above + PROTEIN_C_TERM mods, for Single-C @ protein C-term Warning emitted at log level WARN if any set exceeds 64 entries (per-spectrum query cost scales linearly with set size). No hard reject — degrades gracefully if the user knowingly configures many variable mods. Populated unconditionally (not gated on is_snes_mode_) so toggling snes_enabled at runtime does not require a rebuild — the sets are cheap to compute and tiny. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
New optional parameter subset_bitmask (default 0) indexes into the slot list produced by buildModSlots_(seq_ptr, realized_length, ...) to apply SNES v1.1 variable modifications during AASequence reconstruction. Default argument preserves backward compatibility: existing callers passing only three arguments get the same unmodified reconstruction as before. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Follow-up to 404e5a6 after code review: - reconstructRealizedSubSequence: the has_mods early-return at line 608 fired before the new subset_bitmask block, silently skipping variable-mod application if a caller passed subset_bitmask != 0 on a FragmentIndex with no configured mods. Current callers ensure that combination never occurs, but relax the guard defensively to \`!has_mods && subset_bitmask == 0\`. - Task 5 test: add a comment explaining why \`subset_bitmask = 1u\` targets the Oxidation slot on the M residue (buildModSlots_ enumeration order → no pure N-term mods in this config → slot 0 is the residue-bound M slot). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…d walks Adds SnesAnchor enum (NONE / PROT_NTERM / PROT_CTERM) and threads it through the collect_candidates lambda together with a sigma_tag float that annotates emitted SpectrumMatch entries with their Σ_delta provenance. Current call sites pass NONE / 0.0f — no behavior change. v1.1 query-path restructuring (subsequent commit) will introduce anchor-specific walks for PROTEIN_N_TERM and PROTEIN_C_TERM variable-mod Σ values. Also adds protein_lengths_ member vector populated at build() time to support the PROT_CTERM anchor check without re-passing fasta_entries through the query path. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Follow-up to 2c5cf2a after code review. PROT_CTERM anchor check in collect_candidates compared a promoted-to-int sum against uint32_t protein_lengths_ entry. Cast the sum to uint32_t for a clean compare. Also marks the supplementary full-length-realization lookup block with a TODO for Task 7 which will extend it to participate in the Σ loop. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
querySpectrumSNES_ now loops over snes_sigma_delta_set_ (baseline) plus two
supplementary loops over the PROTEIN_N_TERM-extra and PROTEIN_C_TERM-extra
Σ values. Each iteration:
- shifts the precursor target by −Σ before the bin walk,
- resets emitted[] so the same mother can produce distinct SpectrumMatch
entries at different Σ values,
- tags each emitted match with sm.sigma_delta_ for downstream use,
- runs the full-length supplementary lookup at the same shifted target.
Anchor-specific walks (PROT_NTERM, PROT_CTERM) use collect_candidates's
anchor filter to skip mid-protein mothers that cannot host protein-term
variable mods.
When modifications:variable is empty, snes_sigma_delta_set_ = {0} and the
new code collapses to exactly the v1 behavior — existing tests unchanged.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…mSNES_ Follow-up to ca00044. The function-entry emitted.assign() is a thread-local size-safe init, not the dedup reset. The actual resets now live in the three std::fill calls inside the Σ loops. Update the comment so a future reader doesn't think the function-entry assign is the dedup reset. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
After Σ-expanded bin walks produce (mother, Σ) pairs, enumerate valid variable-mod bitmask subsets on each realized sub-peptide and emit one SpectrumMatch per valid subset. Subsets are rejected if: - popcount > max_variable_mods_per_peptide - two active bits share a residue position (conflict) - subset Σ ≠ hit's sigma_delta_ (within 1e-6 Da tolerance) Per-mother cap of 16 subsets across all (k, Σ) tuples prevents pathological mothers with many eligible residues from dominating the candidate set. Σ=0 hits pass through unchanged (bitmask=0). For these, the query reduces to v1 behavior. Cache fasta_entries pointer at build() time to avoid re-threading the FASTA through the query API. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ime doc Follow-up to b6dbd86 after code review. Three fixes: 1. Subset enumeration loop used `(1u << n_slots)` for the upper bound, UB at n_slots=32 and buggy at n_slots=31 (ghost bitmasks with bit 31 set iterated 2x too much, and the all-32-slots bitmask was silently skipped). Use uint64_t sentinel to correctly span [1, 2^n_slots - 1] for n_slots in [1, 32]. 2. Two stale strings claimed variable mods are "disabled" / "not supported" in SNES, which contradicts v1.1 behavior. Updated the log warning and parameter docstring to describe the actual design (mothers indexed unmodified; subsets applied at query time). 3. Document the fasta_entries_ptr_for_snes_ lifetime precondition on both build()'s Doxygen and the member itself. Caller must keep the FASTA vector alive for subsequent queries. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Subtract sm.sigma_delta_ from the iso-corrected realization target so realizeSNESLength compares against the unmodified realized mass (as it was designed). For v1 unmodified hits, sigma_delta_ == 0 → same behavior. - Forward sm.subset_bitmask_ into reconstructRealizedSubSequence so the reconstructed AASequence carries the chosen variable-mod subset. - HyperScore scoring path unchanged — it operates on the modified AASequence the same way it handles non-SNES peptide mods. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Regression guard for the emit-both degenerate-subset policy. With two M residues and Oxidation (M) max=1, Σ=15.995 is reachable by activating either M individually. Test asserts ≥ 2 distinct subset_bitmask_ values at that Σ — each a separate SpectrumMatch rather than collapsing to a single representative. Peptide ACDEFMGMR is used (M at positions 5 and 7) so that b3/b4/b5 are unmodified and the SNES byte-scan meets min_matched_ions=3. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Three tests: - Position conflict: Σ-set enumeration allows sums that would require position-conflicting subsets. The conflict is rejected at subset- enumeration time (covered by the identical-delta test below). - max_variable_mods_per_peptide: Σ-set size directly reflects the cap (one Oxidation M → set size 2 at max=1, 3 at max=2). - Identical-delta mods (Oxidation M + Oxidation W, both +15.995): subset enumeration emits distinct bitmasks for each valid placement, not a single collapsed representative. Note: Oxidation (HW) is not a valid OpenMS mod name; Oxidation (W) is used instead (same delta, W origin only). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two query-path tests verifying the SnesAnchor filter in collect_candidates: - Acetyl (Protein N-term): admits only Single-N mothers at protein pos 0. Mid-protein sub-peptide with the same sequence is NOT matched. - Amidated (Protein C-term): symmetric — admits only Single-C mothers at the protein C-terminus. Tests use unmodified fragment spectra with modification-shifted precursor MZ so the SNES phase-1 fragment scoring works against the unmodified index. Also fixes a pre-existing float→double precision bug in the subset enumeration Σ match check: 1e-6 tolerance was too tight for modifications like Acetyl (+42.010565 Da) whose float representation differs from the double by ~1.7e-6 Da, causing valid subsets to be silently dropped. Widened to 1e-4 Da (~0.1 mDa), safe given Unimod's ≥1 mDa delta spacing. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Addresses merge-readiness review findings: 1. SNES v1.1 "variables mods are not enumerated on mothers" log message is informational, not a warning. Downgraded WARN → INFO. 2. Per-mother subset cap (16 subsets across all k, Σ tuples) now emits an OPENMS_LOG_DEBUG when triggered, per spec requirement. 3. Added query-path test verifying subset-enumeration rejects position conflicts (Acetyl + Carbamyl both at N-term → no hit at Σ=85.017). 4. clear() nulls fasta_entries_ptr_for_snes_ and clears protein_lengths_. 5. Stale "v2" comment reference updated to "v1.2+". Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
fasta_entries_ptr_for_snes_ cached the vector pointer during build(). ProSEAlgorithm::prepareContext returns SearchContext by value, moving ctx.db to a new memory location; the cached pointer then points to a moved-from (empty) std::vector. Crash reproduced on human proteome search with Oxidation(M) at 127s under gdb — segfault in realizeSNESLength → operator[] on empty vector. Fix: stop caching. Add a querySpectrum(spec, fasta, sms) overload that threads the FASTA through to querySpectrumSNES_. Keep the 2-arg overload for non-SNES and SNES-without-var-mods callers; those paths never dereference fasta in the subset-enumeration block (sigma_delta_ is always 0 → the guarded early-continue skips the deref). In the 2-arg overload, log an error and return if SNES mode + non-empty modifications_variable_ is configured without a FASTA. Update ProSEAlgorithm.scoreSpectraAgainstIndex_ to pass db via the new 3-arg overload (db is already a parameter there). Calibration's fragment_index.querySpectrum call stays on the 2-arg overload — the calibration pass returns early in SNES mode so it never hits the SNES+var-mods path. Update FragmentIndex_test.cpp to use the 3-arg overload in all SNES variable-mod test sections (6 call sites). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… plan These were working documents for the development of the feature and are not intended as user-facing or long-lived references. The code + commit history on this branch is the canonical record. Removing to avoid doc drift (e.g., the plan proposed the fasta_entries_ptr_for_snes_ caching design that was subsequently replaced by threading in commit 78c9f86). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…g overload Before: the 2-arg querySpectrum(spectrum, sms) and the 3-arg querySpectrum(spectrum, fasta_entries, sms) duplicated ~50 lines — preconditions (isBuild / empty / MSLevel / precursor count) and the non-SNES search path (charges loop + searchDifferentPrecursorRanges + trimHits). Only the SNES branch actually differed. After: the 2-arg overload is 8 lines — it applies the SNES-mode guard (reject SNES + var-mods configuration outright), then delegates to the 3-arg overload with an empty static FASTA. The shared logic lives in one place; future changes to preconditions or the non-SNES path touch only the 3-arg overload. No behavior change for any existing caller. All 44 FragmentIndex_test sections pass. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Re-posted from the now-closed #9189 (originally by @timosachsenberg) so the backlog stays visible on the active PR. Status markers updated to reflect what this PR (v1.1) actually lands. SNES roadmap — what's leftRecording a follow-up backlog before this drops out of working memory. Ordered by priority / release target. v1 blockers (before flipping
|
A sub-peptide [i, i+k) can be produced by both a Single-N mother anchored at i and a Single-C mother ending at i+k-1. Without dedup, both realize to the same AASequence (same protein_idx, realized_start, realized_length, subset_bitmask) and both get scored + pushed into annotated_hits, inflating the candidate list and biasing delta scores / Percolator features with redundant PSMs per spectrum. Fix: maintain a per-spectrum std::set<(protein_idx, realized_start, realized_length, subset_bitmask)> in scoreSpectraAgainstIndex_; skip candidates already seen. Bounded by max_candidates_per_spectrum (default 50), so log-n insertion is trivially cheap per spectrum. Empty for non-SNES queries (no Single-N/C kinds). Key includes subset_bitmask: two DIFFERENT variable-mod subsets at the same (start, length) are legitimately distinct peptide variants and must both be retained. Addresses review finding L2 from the roadmap on #9191. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
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:
📝 WalkthroughWalkthroughAdds SNES v1.1 support across FragmentIndex and ProSEAlgorithm: SpectrumMatch layout extended, FASTA-aware query overloads, SNES configuration/inspection APIs, realization/reconstruction helpers, SNES-index/build/query control flow, ProSE integration changes, and extensive SNES-targeted tests. (No subjective commentary.) Changes
Sequence Diagram(s)sequenceDiagram
participant App as Application
participant PSE as ProSEAlgorithm
participant FI as FragmentIndex
participant FASTA as FASTA_DB
App->>PSE: scoreSpectra(..., snes_enabled=true)
PSE->>FI: build(fasta_entries, config)
FI->>FI: generateSNESMothers_ / computeSnesSigmaDeltaSet_
PSE->>FI: querySpectrum(spectrum, fasta_entries, sms)
FI->>FI: querySpectrumSNES_()
FI->>FI: compute byte-score candidates
FI->>FI: filter by asymmetric precursor windows (using Σ / sigma_delta_)
FI->>FI: expand subset_bitmask_ per-mother and realize sequences
FI-->>PSE: SpectrumMatch results (subset_bitmask_, sigma_delta_)
PSE->>PSE: score, deduplicate realizations
PSE-->>App: final scored assignments
Possibly related PRs
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: 9
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)
37-42:⚠️ Potential issue | 🟠 MajorInclude
<atomic>for the newstd::atomicusage.Line 694 declares
std::atomic<size_t> skipped_peptides, but this translation unit does not include<atomic>. Relying on transitive includes is not portable and can break stricter toolchains. OpenMS itself uses this pattern elsewhere (e.g.,File.cppexplicitly includes<atomic>forstd::atomic_int).Build fix
`#include` <bit> +#include <atomic> `#include` <cmath> `#include` <functional> `#include` <mutex>🤖 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 37 - 42, The translation unit uses std::atomic<size_t> skipped_peptides in FragmentIndex.cpp but does not include <atomic>, which can break strict builds; add an `#include` <atomic> near the other standard headers (alongside <bit>, <cmath>, <functional>, etc.) so the declaration of skipped_peptides and any atomic usage resolve portably.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h`:
- Around line 357-367: Add a Doxygen `@brief` + detailed description block for the
public method reconstructRealizedSubSequence in FragmentIndex.h: replace the
current triple-slash comment with a Doxygen comment that starts with `@brief`
(one-line summary), a blank line, then a short paragraph describing what the
method does (reconstructs a realized SNES sub-peptide into an AASequence and
applies variable modifications from subset_bitmask), document parameters
(mother, fasta_entries, realized_length, subset_bitmask) and explicitly list any
exceptions that can be thrown during sequence reconstruction/mod application
(e.g., invalid indices, modification application failures), and indicate return
value; ensure the comment is placed immediately above the AASequence
reconstructRealizedSubSequence(...) declaration.
In `@src/openms/source/ANALYSIS/ID/FragmentIndex.cpp`:
- Around line 736-770: The current emitMother lambda (and the
protein_has_ambiguous check using seq.find_first_of("XBZ")) drops an entire
mother whenever an ambiguous residue lies inside it, which loses valid shorter
SNES realizations; instead, when a bad index (bad = seq.find_first_of("XBZ",
start)) is found and bad < start + length, truncate the candidate mother length
to length = bad - start (and only skip if that truncated length <
peptide_min_length_), increment skipped_peptides for truly discarded cases, and
continue emitting mothers up to effective_max_length from the same start; update
emitMother (and any loops calling it) to use this shortened length rather than
returning immediately so shorter realizations before the ambiguous residue
remain searchable.
- Around line 1688-1698: The realization step currently uses a symmetric
prec_tol computed as max(precursor_mass_tolerance_lower_,
precursor_mass_tolerance_upper_), which lets matches outside the intended
asymmetric window pass; change the realization check to apply the asymmetric
signed bounds instead: compute separate mass offsets for the negative (lower)
and positive (upper) sides using Math::ppmToMass when
precursor_mass_tolerance_unit_ppm_ is true (e.g., prec_tol_lower =
ppmToMass(lower, prec_tol_ref_mz) and prec_tol_upper = ppmToMass(upper,
prec_tol_ref_mz)), or use the raw signed values when not ppm, and then check
candidate mz against shifted_mh using [-prec_tol_lower, +prec_tol_upper] (or
equivalent signed comparison) instead of using prec_tol; make the same change
for the other occurrence around lines 1868-1871, referencing the variables
precursor_mass_tolerance_lower_, precursor_mass_tolerance_upper_,
prec_tol_ref_mz, precursor_mass_tolerance_unit_ppm_, and Math::ppmToMass.
- Around line 1496-1508: The code casts potentially negative
precursor.getCharge() into uint16_t (vector<uint16_t> charges), which turns
negative charges into large positive values; change the charges container to a
signed type (e.g., vector<int16_t> or vector<int>) and only push_back
static_cast<int16_t>(precursor.getCharge()) when precursor.getCharge() > 0;
otherwise fall back to populating charges from the configured range
(min_precursor_charge_ .. max_precursor_charge_) as before. Ensure you update
usages of charges if they assume unsigned types elsewhere in the function/class
(FragmentIndex.cpp, references around precursor.getCharge(), charges,
min_precursor_charge_, max_precursor_charge_).
- Around line 1897-1900: The loop over bitmasks uses bm as uint32_t which can
wrap when max_bitmask64 == 2^32; change the loop variable to uint64_t (i.e.,
iterate uint64_t bm = 1; bm < max_bitmask64; ++bm) and where bm is used as an
index or passed to APIs expecting uint32_t cast it explicitly
(static_cast<uint32_t>(bm)); update any comparisons/usages in the surrounding
code in FragmentIndex.cpp (symbols: n_slots, max_bitmask64, bm, and the
per-mother cap logic) to avoid implicit narrowing and prevent the infinite-wrap
issue.
In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp`:
- Around line 891-935: realizeSNESLength currently uses a symmetric
snes_realize_tol which can admit candidates outside the original asymmetric
precursor window; after getting realized_len, compute the realized unmodified
mass for that realized peptide length (use sms_pep and the same unmodified-mass
semantics used for realization, e.g., derive the AASequence of length
realized_len anchored appropriately and get its mono mass) and compare it to the
iso_shifted_target using the original signed bounds
precursor_mass_tolerance_lower_ and precursor_mass_tolerance_upper_ (or compute
ppm-equivalent bounds if prec_tol_ppm is true); if the realized mass falls
outside [iso_shifted_target - precursor_mass_tolerance_lower_,
iso_shifted_target + precursor_mass_tolerance_upper_] then continue to skip this
candidate instead of accepting it. Ensure you reference sms_pep, realized_len,
iso_shifted_target, precursor_mass_tolerance_lower_,
precursor_mass_tolerance_upper_, and prec_tol_ppm in the check so SNES scoring
preserves the asymmetric tolerance.
- Around line 160-168: Update the snes_enabled help text passed to
defaults_.setValue(...) to reflect v1.1 behavior: replace the sentence "Variable
modifications on mothers are not supported in v1." with a brief note that v1.1
supports query-time variable-mod subset enumeration for mother peptides (e.g.,
"Variable modifications on mothers are supported in v1.1 via query-time
variable-mod subset enumeration"). Ensure the rest of the description
(experimental, v1.1 opt-in, scope when enzyme_specificity=none, ignored for
specific/semi-specific enzymes) remains intact and keep the valid strings call
defaults_.setValidStrings("snes_enabled", {"true", "false"}) unchanged.
In `@src/tests/class_tests/openms/source/FragmentIndex_test.cpp`:
- Around line 2047-2051: The test currently only checks deltas.size() >= 3 so
the two-mod conflict (Σ ≈ 85.016379) might never be enumerated; update the
assertion after calling fi.getSnesSigmaDeltaSet() to explicitly check that the
summed delta value 85.016379 (or 85.016379xxx within tolerance) is present in
deltas (use deltas.count(...) or a find with fabs(delta - 85.016379) < epsilon)
so the later position-conflict rejection is actually exercised by the test.
- Line 1943: The test uses std::abs and std::set but doesn't include the
required headers; add `#include` <cmath> to cover std::abs usages (e.g.
expressions like std::abs(hit.sigma_delta_ - 15.994915f)) and `#include` <set> to
cover std::set usage (e.g. any declarations/uses of std::set in the test) near
the other standard includes in FragmentIndex_test.cpp so the file compiles on
strict toolchains.
---
Outside diff comments:
In `@src/openms/source/ANALYSIS/ID/FragmentIndex.cpp`:
- Around line 37-42: The translation unit uses std::atomic<size_t>
skipped_peptides in FragmentIndex.cpp but does not include <atomic>, which can
break strict builds; add an `#include` <atomic> near the other standard headers
(alongside <bit>, <cmath>, <functional>, etc.) so the declaration of
skipped_peptides and any atomic usage resolve portably.
🪄 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: dd713e42-81d5-432a-a506-98fa49ff994c
📒 Files selected for processing (4)
src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.hsrc/openms/source/ANALYSIS/ID/FragmentIndex.cppsrc/openms/source/ANALYSIS/ID/ProSEAlgorithm.cppsrc/tests/class_tests/openms/source/FragmentIndex_test.cpp
| /// Reconstruct a realized SNES sub-peptide as an AASequence. | ||
| /// @param mother the SNES mother Peptide entry | ||
| /// @param fasta_entries the FASTA entries used to build the index | ||
| /// @param realized_length the length of the realized sub-peptide (from realizeSNESLength) | ||
| /// @param subset_bitmask SNES v1.1: active slots from buildModSlots_(seq_ptr, realized_length, ...) | ||
| /// to apply as variable modifications. 0 = unmodified (backward compatible). | ||
| /// @return AASequence representing the realized sub-peptide with any variable mods from subset_bitmask applied | ||
| AASequence reconstructRealizedSubSequence(const Peptide& mother, | ||
| const std::vector<FASTAFile::FASTAEntry>& fasta_entries, | ||
| size_t realized_length, | ||
| uint32_t subset_bitmask = 0) const; |
There was a problem hiding this comment.
Add the required Doxygen @brief block for this public API.
reconstructRealizedSubSequence() is a new public method but its comment does not use the required @brief format or document possible exceptions from sequence reconstruction/modification application.
Documentation fix
- /// Reconstruct a realized SNES sub-peptide as an AASequence.
- /// `@param` mother the SNES mother Peptide entry
- /// `@param` fasta_entries the FASTA entries used to build the index
- /// `@param` realized_length the length of the realized sub-peptide (from realizeSNESLength)
- /// `@param` subset_bitmask SNES v1.1: active slots from buildModSlots_(seq_ptr, realized_length, ...)
- /// to apply as variable modifications. 0 = unmodified (backward compatible).
- /// `@return` AASequence representing the realized sub-peptide with any variable mods from subset_bitmask applied
+ /**
+ * `@brief` Reconstruct a realized SNES sub-peptide as an AASequence.
+ *
+ * Applies fixed modifications and, when `@p` subset_bitmask is non-zero,
+ * variable modifications from the realized sub-peptide slot list.
+ *
+ * `@param`[in] mother The SNES mother Peptide entry.
+ * `@param`[in] fasta_entries The FASTA entries used to build the index.
+ * `@param`[in] realized_length The length returned by realizeSNESLength().
+ * `@param`[in] subset_bitmask Active SNES v1.1 mod slots; 0 means unmodified.
+ * `@return` The realized sub-peptide sequence with applicable modifications.
+ *
+ * `@throws` Exception::Base if sequence reconstruction or modification assignment fails.
+ */As per coding guidelines, src/openms/include/OpenMS/**/*.h: “Add Doxygen comments for new public methods and classes” and **/*.h: “Use @brief plus blank line plus detailed description in Doxygen comments; required @brief tag” / “Document possible exceptions in C++ function/method documentation.”
🤖 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 357 -
367, Add a Doxygen `@brief` + detailed description block for the public method
reconstructRealizedSubSequence in FragmentIndex.h: replace the current
triple-slash comment with a Doxygen comment that starts with `@brief` (one-line
summary), a blank line, then a short paragraph describing what the method does
(reconstructs a realized SNES sub-peptide into an AASequence and applies
variable modifications from subset_bitmask), document parameters (mother,
fasta_entries, realized_length, subset_bitmask) and explicitly list any
exceptions that can be thrown during sequence reconstruction/mod application
(e.g., invalid indices, modification application failures), and indicate return
value; ensure the comment is placed immediately above the AASequence
reconstructRealizedSubSequence(...) declaration.
| // Fast path: for the overwhelmingly common case of a protein with no | ||
| // ambiguous residues, a single linear scan tells us we can skip the per- | ||
| // mother X/B/Z check entirely. For the rare protein with X/B/Z, we fall | ||
| // back to checking only the next-bad-position via std::string::find_first_of | ||
| // starting from the mother's start index — still O(length) in the worst | ||
| // case, but only if the mother actually overlaps a bad region. | ||
| // | ||
| // Follow-up: a protein-wide skip here is overly conservative. A max-length | ||
| // mother spanning an `X` is discarded, but shorter realizations with the | ||
| // same anchor *not* covering the `X` could be valid. CodeRabbit #1. | ||
| // Correct fix: split the protein into contiguous unambiguous spans and | ||
| // generate mothers per-span. Deferred to v1.1. | ||
| const bool protein_has_ambiguous = seq.find_first_of("XBZ") != std::string::npos; | ||
|
|
||
| // Honor peptide:max_size=0 as "no maximum" (the documented semantics of | ||
| // the non-SNES path). Using raw peptide_max_length_ in std::min would give | ||
| // length 0 and an empty SNES index. | ||
| const size_t effective_max_length = (peptide_max_length_ == 0) ? L : peptide_max_length_; | ||
|
|
||
| auto emitMother = [&](size_t start, size_t length, bool is_single_c) | ||
| { | ||
| if (length < peptide_min_length_) return; | ||
| const char* seq_ptr = seq.c_str() + start; | ||
|
|
||
| // Reject mothers containing ambiguous codes — any realized sub-peptide | ||
| // spanning an X/B/Z would fail AASequence::fromString downstream. | ||
| if (protein_has_ambiguous) | ||
| { | ||
| const size_t bad = seq.find_first_of("XBZ", start); | ||
| if (bad != std::string::npos && bad < start + length) | ||
| { | ||
| skipped_peptides.fetch_add(1); | ||
| return; | ||
| } | ||
| } |
There was a problem hiding this comment.
Do not drop valid shorter SNES realizations around ambiguous residues.
This rejects the entire longest mother when it spans X/B/Z, but shorter realizations from the same anchor that stop before the ambiguous residue are valid and become unsearchable. Split proteins into contiguous unambiguous spans, or shorten emitted mothers to the next ambiguous boundary instead of skipping the anchor.
🤖 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 736 - 770, The
current emitMother lambda (and the protein_has_ambiguous check using
seq.find_first_of("XBZ")) drops an entire mother whenever an ambiguous residue
lies inside it, which loses valid shorter SNES realizations; instead, when a bad
index (bad = seq.find_first_of("XBZ", start)) is found and bad < start + length,
truncate the candidate mother length to length = bad - start (and only skip if
that truncated length < peptide_min_length_), increment skipped_peptides for
truly discarded cases, and continue emitting mothers up to effective_max_length
from the same start; update emitMother (and any loops calling it) to use this
shortened length rather than returning immediately so shorter realizations
before the ambiguous residue remain searchable.
| bool found_modified = false; | ||
| for (const auto& hit : sms.hits_) | ||
| { | ||
| if (hit.subset_bitmask_ != 0 && std::abs(hit.sigma_delta_ - 15.994915f) < 0.01f) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify direct includes exist for the standard-library symbols used by this test.
rg -n '#include <(cmath|set)>|std::(abs|set)\b' src/tests/class_tests/openms/source/FragmentIndex_test.cppRepository: OpenMS/OpenMS
Length of output: 600
🏁 Script executed:
#!/bin/bash
# Read the include section of the file (first 100 lines to capture all includes)
head -100 src/tests/class_tests/openms/source/FragmentIndex_test.cpp | grep -n '#include'Repository: OpenMS/OpenMS
Length of output: 572
🏁 Script executed:
#!/bin/bash
# Check if any of the included OpenMS headers transitively include <cmath> or <set>
# Start with the main header being tested
rg -l '#include <cmath>|#include <set>' src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h 2>/dev/null
# Also check a few key headers
for header in "src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h" \
"src/openms/include/OpenMS/KERNEL/Peak1D.h" \
"src/openms/include/OpenMS/KERNEL/MSSpectrum.h"; do
if [ -f "$header" ]; then
echo "=== Checking $header ==="
grep -n '#include <cmath>\|#include <set>' "$header" 2>/dev/null | head -5 || echo "Not found"
fi
doneRepository: OpenMS/OpenMS
Length of output: 249
🏁 Script executed:
#!/bin/bash
# Get all includes from FragmentIndex.h (first 200 lines) to see what it brings in
head -200 src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h | grep '#include' | head -20
echo "---"
# Also check if the code actually compiles by examining test infrastructure
# Search for any special compiler flags or if FuzzyDiff/test passes indicate compilation
rg -i 'add_test.*FragmentIndex' src/tests/class_tests/openms/source/ --max-count=3Repository: OpenMS/OpenMS
Length of output: 516
🏁 Script executed:
#!/bin/bash
# Find where FragmentIndex_test is registered
rg 'FragmentIndex_test' src/tests/class_tests/openms/source/ --max-count=5
echo "---"
# Check CMakeLists for registration
rg -i 'FragmentIndex_test' src/tests/class_tests/openms/ --type cmakeRepository: OpenMS/OpenMS
Length of output: 599
🏁 Script executed:
#!/bin/bash
# Check ClassTest.h for std includes
grep '#include <cmath>\|#include <set>' src/openms/include/OpenMS/CONCEPT/ClassTest.h
echo "---"
# Check test_config.h
grep '#include <cmath>\|#include <set>' src/openms/source/config/test_config.h.in 2>/dev/null || \
grep '#include <cmath>\|#include <set>' src/tests/test_config.h.in 2>/dev/null || echo "test_config not found or no match"
echo "---"
# Check if Peak1D.h might include these indirectly
head -50 src/openms/include/OpenMS/KERNEL/Peak1D.h | grep '#include'Repository: OpenMS/OpenMS
Length of output: 255
🏁 Script executed:
#!/bin/bash
# Check if Types.h includes our needed headers
grep '#include <cmath>\|#include <set>' src/openms/include/OpenMS/CONCEPT/Types.h
echo "---"
# Check HashUtils.h
grep '#include <cmath>\|#include <set>' src/openms/include/OpenMS/CONCEPT/HashUtils.h
echo "---"
# Do a broad search: which OpenMS headers DO include <cmath> or <set>?
echo "Files that include <cmath>:"
rg '#include <cmath>' src/openms/include/OpenMS/ --type h | head -10
echo "---"
echo "Files that include <set>:"
rg '#include <set>' src/openms/include/OpenMS/ --type h | head -10Repository: OpenMS/OpenMS
Length of output: 1556
🏁 Script executed:
#!/bin/bash
# Show the include section with context to verify the proposed diff placement
sed -n '8,25p' src/tests/class_tests/openms/source/FragmentIndex_test.cpp | cat -nRepository: OpenMS/OpenMS
Length of output: 723
Add missing standard-library headers for std::abs and std::set usage.
This test file uses std::abs (lines 1943, 2017, 2158, 2238, 2318, 2393) and std::set (lines 2013, 2154) without including <cmath> or <set>. These headers are not provided transitively by the OpenMS includes, and compilation will fail on stricter toolchains.
Proposed fix
`#include` <OpenMS/KERNEL/MSSpectrum.h>
`#include` <OpenMS/KERNEL/Peak1D.h>
+#include <cmath>
`#include` <limits>
+#include <set>📝 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.
| if (hit.subset_bitmask_ != 0 && std::abs(hit.sigma_delta_ - 15.994915f) < 0.01f) | |
| `#include` <OpenMS/KERNEL/MSSpectrum.h> | |
| `#include` <OpenMS/KERNEL/Peak1D.h> | |
| `#include` <cmath> | |
| `#include` <limits> | |
| `#include` <set> |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/tests/class_tests/openms/source/FragmentIndex_test.cpp` at line 1943, The
test uses std::abs and std::set but doesn't include the required headers; add
`#include` <cmath> to cover std::abs usages (e.g. expressions like
std::abs(hit.sigma_delta_ - 15.994915f)) and `#include` <set> to cover std::set
usage (e.g. any declarations/uses of std::set in the test) near the other
standard includes in FragmentIndex_test.cpp so the file compiles on strict
toolchains.
| // Σ_delta set should contain 0, +42.011 (Acetyl), +43.006 (Carbamyl), | ||
| // and the SUM +85.017 (activating both — but at query time this subset | ||
| // is rejected by position conflict). | ||
| const auto& deltas = fi.getSnesSigmaDeltaSet(); | ||
| TEST_EQUAL(deltas.size() >= 3u, true) |
There was a problem hiding this comment.
Pin the conflicting Σ value so the rejection test cannot pass vacuously.
size() >= 3 still passes if the two-mod conflict sum is never enumerated, which means the later query-path rejection can pass without exercising position-conflict filtering. Assert the 85.016379 Σ is present here.
Proposed test strengthening
const auto& deltas = fi.getSnesSigmaDeltaSet();
TEST_EQUAL(deltas.size() >= 3u, true)
+ bool has_conflict_sum = false;
+ for (const double delta : deltas)
+ {
+ if (std::abs(delta - 85.016379) < 0.01)
+ {
+ has_conflict_sum = true;
+ break;
+ }
+ }
+ TEST_EQUAL(has_conflict_sum, true)As per coding guidelines, Write unit tests for new functionality and ensure existing tests pass before suggesting changes.
📝 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.
| // Σ_delta set should contain 0, +42.011 (Acetyl), +43.006 (Carbamyl), | |
| // and the SUM +85.017 (activating both — but at query time this subset | |
| // is rejected by position conflict). | |
| const auto& deltas = fi.getSnesSigmaDeltaSet(); | |
| TEST_EQUAL(deltas.size() >= 3u, true) | |
| // Σ_delta set should contain 0, +42.011 (Acetyl), +43.006 (Carbamyl), | |
| // and the SUM +85.017 (activating both — but at query time this subset | |
| // is rejected by position conflict). | |
| const auto& deltas = fi.getSnesSigmaDeltaSet(); | |
| TEST_EQUAL(deltas.size() >= 3u, true) | |
| bool has_conflict_sum = false; | |
| for (const double delta : deltas) | |
| { | |
| if (std::abs(delta - 85.016379) < 0.01) | |
| { | |
| has_conflict_sum = true; | |
| break; | |
| } | |
| } | |
| TEST_EQUAL(has_conflict_sum, true) |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/tests/class_tests/openms/source/FragmentIndex_test.cpp` around lines 2047
- 2051, The test currently only checks deltas.size() >= 3 so the two-mod
conflict (Σ ≈ 85.016379) might never be enumerated; update the assertion after
calling fi.getSnesSigmaDeltaSet() to explicitly check that the summed delta
value 85.016379 (or 85.016379xxx within tolerance) is present in deltas (use
deltas.count(...) or a find with fabs(delta - 85.016379) < epsilon) so the later
position-conflict rejection is actually exercised by the test.
querySpectrumSNES_ and realizeSNESLength previously collapsed the asymmetric precursor window to max(lower, upper). For calibrated windows like [100 ppm, 5 ppm] (common after bias correction) this over-admitted candidates by up to ~20× on the tighter side. Changes: - realizeSNESLength: take (tolerance_lower_magnitude, tolerance_upper_magnitude) and compare the signed delta (realized_mass - target) against asymmetric Da bounds. - querySpectrumSNES_: compute the asymmetric window once per (charge, iso_err) via computeMassWindow_; use (tol_lo <= 0, tol_hi >= 0) in the bin walks and supplementary lookups across all three Σ-tier paths (baseline, PROT_NTERM, PROT_CTERM). - collect_candidates lambda: signature now (target, tol_lo, tol_hi); the inner filter checks signed delta ∈ [tol_lo, tol_hi]. - ProSEAlgorithm: pass lower / upper separately to realizeSNESLength from scoreSpectraAgainstIndex_ and the subset-enumeration post-pass. New regression test: asymmetric-tolerance assertion on a shifted-high target — tight lower rejects, loose lower admits; same upper in both. Would silently pass under the old max-collapse. Addresses review finding L3. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 4
♻️ Duplicate comments (5)
src/openms/source/ANALYSIS/ID/FragmentIndex.cpp (3)
1909-1914:⚠️ Potential issue | 🔴 CriticalUse a
uint64_tloop variable to prevent wraparound at 32 slots.When
n_slots == 32,max_bitmask64is2^32;uint32_t bmwraps fromUINT32_MAXto0, so the loop can become infinite if the per-mother cap is not reached. This was already flagged previously and is still present.Loop fix
- for (uint32_t bm = 1; static_cast<uint64_t>(bm) < max_bitmask64; ++bm) + for (uint64_t bm = 1; bm < max_bitmask64; ++bm) { - if (static_cast<size_t>(std::popcount(bm)) > max_variable_mods_per_peptide_) continue; + const uint32_t bm32 = static_cast<uint32_t>(bm); + if (static_cast<size_t>(std::popcount(bm32)) > max_variable_mods_per_peptide_) continue; // Position-conflict check. bool conflict = false; for (size_t a = 0; a < n_slots && !conflict; ++a) { - if (!(bm & (1u << a))) continue; + if (!(bm32 & (1u << a))) continue; for (size_t b = a + 1; b < n_slots; ++b) { - if (!(bm & (1u << b))) continue; + if (!(bm32 & (1u << b))) continue; if (slots[a].position == slots[b].position) { conflict = true; break; } } } @@ double subset_sigma = 0.0; for (size_t s = 0; s < n_slots; ++s) { - if (bm & (1u << s)) subset_sigma += slots[s].delta_mass; + if (bm32 & (1u << s)) subset_sigma += slots[s].delta_mass; } @@ SpectrumMatch sm_variant = sm_raw; - sm_variant.subset_bitmask_ = bm; + sm_variant.subset_bitmask_ = bm32;Verify no remaining
uint32_tloop is compared against a2^32upper bound:#!/bin/bash # Description: Locate SNES bitmask enumeration loops and confirm the loop # variable is wide enough for a 2^32 upper bound. rg -n -C4 'max_bitmask64|for \(uint32_t bm|for \(uint64_t bm' src/openms/source/ANALYSIS/ID/FragmentIndex.cpp🤖 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 1909 - 1914, The loop uses uint32_t bm while max_bitmask64 can be 2^32, causing wraparound when n_slots == 32; update the loop variable to uint64_t bm (and adjust comparisons to use bm < max_bitmask64 directly) so iteration stops correctly, and ensure std::popcount is called on the 64-bit value (or cast appropriately) when checking max_variable_mods_per_peptide_.
763-778:⚠️ Potential issue | 🟠 MajorDo not drop valid shorter SNES realizations around ambiguous residues.
This still rejects the whole longest mother when it spans
X/B/Z, so shorter realizations from the same anchor that stop before the ambiguous residue remain unsearchable. This was already flagged previously.Fix direction
- if (bad != std::string::npos && bad < start + length) - { - skipped_peptides.fetch_add(1); - return; - } + if (bad != std::string::npos && bad < start + length) + { + length = bad - start; + if (length < peptide_min_length_) + { + skipped_peptides.fetch_add(1); + return; + } + }🤖 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 763 - 778, The emitMother lambda currently aborts emitting any peptides when an ambiguous residue (XBZ) is found anywhere in the mother, which prevents producing shorter realizations that end before the ambiguous site; instead, locate the first ambiguous position (bad) inside the proposed window and truncate length to bad - start so you only drop residues at/after the ambiguous code, then check peptide_min_length_ on the truncated length and only increment skipped_peptides and return if the truncated length is still too short; update references in emitMother (seq, start, length, protein_has_ambiguous, skipped_peptides) accordingly so shorter SNES realizations are emitted.
1504-1516:⚠️ Potential issue | 🟠 MajorTreat non-positive precursor charges as unknown before casting.
precursor.getCharge()can be negative;static_cast<uint16_t>(-2)becomes a large positive charge and corrupts SNES precursor targets. This was already flagged previously.Charge handling fix
const auto& precursor = spectrum.getPrecursors()[0]; vector<uint16_t> charges; - if (precursor.getCharge()) + const Int precursor_charge = precursor.getCharge(); + if (precursor_charge > 0) { - charges.push_back(static_cast<uint16_t>(precursor.getCharge())); + charges.push_back(static_cast<uint16_t>(precursor_charge)); } elseBased on learnings, “In mass spectrometry data, precursor charges can be negative, so signed integer types ... should be used instead of unsigned integers ... when storing charge values.”
🤖 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 1504 - 1516, The code casts precursor.getCharge() to uint16_t without checking for negative values which can wrap; change the charge handling so you first treat non-positive charges as unknown (i.e., only accept positive charges) and avoid unsigned wrapping: use a signed container (e.g., vector<int16_t> charges) or at minimum check precursor.getCharge() > 0 before static_casting and pushing; when falling back to the charge range use int16_t for z or static_cast<int16_t>(z) and push those into charges; update uses of charges accordingly (symbols: precursor.getCharge(), charges, min_precursor_charge_, max_precursor_charge_).src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp (1)
160-168:⚠️ Potential issue | 🟡 MinorUpdate the
snes_enabledhelp text for v1.1 variable mods.The parameter description still says variable modifications “are not supported in v1”, but this PR supports them through query-time subset enumeration. This was already flagged previously and remains user-visible.
Documentation fix
- "specific enzymes. Variable modifications on mothers are not supported in v1."); + "specific enzymes. Variable modifications are applied at query time via " + "subset enumeration on realized sub-peptides.");🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp` around lines 160 - 168, Update the help text passed to defaults_.setValue for the "snes_enabled" parameter to remove the statement that "Variable modifications on mothers are not supported in v1" and instead state that variable modifications are supported in v1.1 via query-time subset enumeration (or similar concise phrasing). Edit the string literal passed to defaults_.setValue tied to "snes_enabled" so it documents v1.1 support for variable mods and mentions the mechanism "query-time subset enumeration" and version "v1.1"; keep the rest of the description unchanged.src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h (1)
361-371:⚠️ Potential issue | 🟡 MinorAdd the required Doxygen block for this public reconstruction API.
This public method still lacks the required
@briefDoxygen format and exception documentation. This was already flagged previously and still appears unresolved.Documentation fix
- /// Reconstruct a realized SNES sub-peptide as an AASequence. - /// `@param` mother the SNES mother Peptide entry - /// `@param` fasta_entries the FASTA entries used to build the index - /// `@param` realized_length the length of the realized sub-peptide (from realizeSNESLength) - /// `@param` subset_bitmask SNES v1.1: active slots from buildModSlots_(seq_ptr, realized_length, ...) - /// to apply as variable modifications. 0 = unmodified (backward compatible). - /// `@return` AASequence representing the realized sub-peptide with any variable mods from subset_bitmask applied + /** + * `@brief` Reconstruct a realized SNES sub-peptide as an AASequence. + * + * Reconstructs the realized sub-pequence represented by an SNES mother peptide + * and applies fixed modifications plus variable modifications encoded by + * `@p` subset_bitmask. + * + * `@param`[in] mother The SNES mother Peptide entry. + * `@param`[in] fasta_entries The FASTA entries used to build the index. + * `@param`[in] realized_length The length returned by realizeSNESLength(). + * `@param`[in] subset_bitmask Active SNES v1.1 variable-mod slots; 0 means unmodified. + * `@return` AASequence representing the realized sub-peptide. + * + * `@throws` Exception::Base if sequence reconstruction or modification assignment fails. + */As per coding guidelines,
src/openms/include/OpenMS/**/*.h: “Add Doxygen comments for new public methods and classes” and**/*.h: “Use@briefplus blank line plus detailed description in Doxygen comments; required@brieftag” / “Document possible exceptions in C++ function/method documentation.”🤖 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 361 - 371, Add a proper Doxygen block for the public method reconstructRealizedSubSequence: include an `@brief` line followed by a blank line and a concise detailed description, keep the existing `@param` tags for mother, fasta_entries, realized_length and subset_bitmask, add a `@return` tag (AASequence) and explicitly document any exceptions the method can throw (e.g., invalid argument, out_of_range, or OpenMS::Exception types) using `@exception` or `@throws`; ensure the comment appears immediately above the declaration of reconstructRealizedSubSequence and follows the project's Doxygen format conventions.
🤖 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 552-560: fixed_nterm_delta_ and fixed_cterm_delta_ are being
applied to every realized sub-peptide regardless of whether the fixed mod was
protein-terminal; update the member state to preserve terminal specificity (e.g.
store fixed_nterm_delta_, fixed_cterm_delta_ plus booleans or enum flags like
fixed_nterm_is_protein_terminal_ / fixed_cterm_is_protein_terminal_), then when
computing masses in FragmentIndex::... (the base calculation using water +
Constants::PROTON_MASS_U + fixed_nterm_delta_ + fixed_cterm_delta_) only add the
nterm delta if the realized peptide start == 0 and the nterm flag indicates a
protein-terminal mod, and only add the cterm delta if the realized peptide end
== protein_seq.size() and the cterm flag indicates a protein-terminal mod; apply
the same conditional logic where these deltas are used later (the other
occurrence around lines 629-630) so internal SNES realizations do not inherit
protein-terminal fixed modifications.
- Around line 1696-1700: The SNES path currently iterates iso_err from
min_isotope_error_ to max_isotope_error_, causing duplicate/mislabelled
candidates in open-search; mirror the non-SNES behavior by detecting open-search
mode and collapsing the isotope loop to a single iteration (iso_err == 0) in the
SNES code path. Locate the loop using min_isotope_error_, max_isotope_error_,
mh_plus and Constants::C13C12_MASSDIFF_U in FragmentIndex.cpp and guard or
override the isotope range when the search is open (use the same open-search
condition used in the non-SNES branch) so shifted_mh is only computed for
iso_err = 0 in open-search. Ensure min_isotope_error_/max_isotope_error_ remain
unchanged for regular (non-open) searches.
In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp`:
- Around line 2331-2335: The warning in ProSEAlgorithm.cpp emitted when
fragment_index.isSnesMode() is true still says "SNES mode (v1)"; update the
message text in the OPENMS_LOG_WARN call inside the isSnesMode() branch to use
the correct v1.1 wording (e.g., "SNES mode (v1.1)") or otherwise remove the
incorrect version tag so the runtime message reflects the current PR; keep the
rest of the log string and the early return from the function intact.
---
Duplicate comments:
In `@src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h`:
- Around line 361-371: Add a proper Doxygen block for the public method
reconstructRealizedSubSequence: include an `@brief` line followed by a blank line
and a concise detailed description, keep the existing `@param` tags for mother,
fasta_entries, realized_length and subset_bitmask, add a `@return` tag
(AASequence) and explicitly document any exceptions the method can throw (e.g.,
invalid argument, out_of_range, or OpenMS::Exception types) using `@exception` or
`@throws`; ensure the comment appears immediately above the declaration of
reconstructRealizedSubSequence and follows the project's Doxygen format
conventions.
In `@src/openms/source/ANALYSIS/ID/FragmentIndex.cpp`:
- Around line 1909-1914: The loop uses uint32_t bm while max_bitmask64 can be
2^32, causing wraparound when n_slots == 32; update the loop variable to
uint64_t bm (and adjust comparisons to use bm < max_bitmask64 directly) so
iteration stops correctly, and ensure std::popcount is called on the 64-bit
value (or cast appropriately) when checking max_variable_mods_per_peptide_.
- Around line 763-778: The emitMother lambda currently aborts emitting any
peptides when an ambiguous residue (XBZ) is found anywhere in the mother, which
prevents producing shorter realizations that end before the ambiguous site;
instead, locate the first ambiguous position (bad) inside the proposed window
and truncate length to bad - start so you only drop residues at/after the
ambiguous code, then check peptide_min_length_ on the truncated length and only
increment skipped_peptides and return if the truncated length is still too
short; update references in emitMother (seq, start, length,
protein_has_ambiguous, skipped_peptides) accordingly so shorter SNES
realizations are emitted.
- Around line 1504-1516: The code casts precursor.getCharge() to uint16_t
without checking for negative values which can wrap; change the charge handling
so you first treat non-positive charges as unknown (i.e., only accept positive
charges) and avoid unsigned wrapping: use a signed container (e.g.,
vector<int16_t> charges) or at minimum check precursor.getCharge() > 0 before
static_casting and pushing; when falling back to the charge range use int16_t
for z or static_cast<int16_t>(z) and push those into charges; update uses of
charges accordingly (symbols: precursor.getCharge(), charges,
min_precursor_charge_, max_precursor_charge_).
In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp`:
- Around line 160-168: Update the help text passed to defaults_.setValue for the
"snes_enabled" parameter to remove the statement that "Variable modifications on
mothers are not supported in v1" and instead state that variable modifications
are supported in v1.1 via query-time subset enumeration (or similar concise
phrasing). Edit the string literal passed to defaults_.setValue tied to
"snes_enabled" so it documents v1.1 support for variable mods and mentions the
mechanism "query-time subset enumeration" and version "v1.1"; keep the rest of
the description unchanged.
🪄 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: 141d8407-2706-4d9a-82be-b234474490cb
📒 Files selected for processing (4)
src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.hsrc/openms/source/ANALYSIS/ID/FragmentIndex.cppsrc/openms/source/ANALYSIS/ID/ProSEAlgorithm.cppsrc/tests/class_tests/openms/source/FragmentIndex_test.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
- src/tests/class_tests/openms/source/FragmentIndex_test.cpp
…i-charge)
Three new sections addressing gaps in the SNES roadmap:
1. X/B/Z rejection: build a protein containing X at position 8; verify
no retained mother's span crosses position 8, and at least one
mother from the unambiguous prefix (start=0, length=8) survives.
Guards against a regression where the `protein_has_ambiguous` fast
path or the per-mother `find_first_of("XBZ", start)` check silently
drops or retains wrong mothers.
2. Full-length supplementary lookup: configure min_size == max_size ==
protein length so every mother is the full peptide. The fragment
index only stores b_1..b_{L-1} / y_1..y_{L-1}; the realized length
== mother length case is served by the direct binary search on
fi_peptides_.precursor_mz_ (the supplementary block at the tail of
each Σ-tier in querySpectrumSNES_). Assert candidate is returned.
3. Multi-charge precursor: query a spectrum whose Precursor.charge == 0
against an index configured with min_charge=2, max_charge=3. Assert
at least one hit carries precursor_charge_ ∈ {2, 3} — the
multi-charge iteration path in querySpectrumSNES_ fires when the
spectrum has no declared charge.
47 FragmentIndex_test sections now pass (was 44).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
src/tests/class_tests/openms/source/FragmentIndex_test.cpp (2)
2066-2067:⚠️ Potential issue | 🟡 MinorPin the conflicting Σ value explicitly.
deltas.size() >= 3udoes not prove the invalid conflict sum is enumerated, so the query-path rejection can still pass vacuously. Assert that Σ ≈85.016379is present.Proposed test strengthening
const auto& deltas = fi.getSnesSigmaDeltaSet(); TEST_EQUAL(deltas.size() >= 3u, true) + bool has_conflict_sum = false; + for (const double delta : deltas) + { + if (std::abs(delta - 85.016379) < 0.01) + { + has_conflict_sum = true; + break; + } + } + TEST_EQUAL(has_conflict_sum, true)As per coding guidelines,
Write unit tests for new functionality and ensure existing tests pass before suggesting changes.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/tests/class_tests/openms/source/FragmentIndex_test.cpp` around lines 2066 - 2067, The test currently checks only that fi.getSnesSigmaDeltaSet() returns at least 3 entries which can pass vacuously; modify the test around the deltas variable to explicitly assert that a value approximately equal to 85.016379 (Σ ≈ 85.016379) is present by scanning deltas for an element within a small tolerance (e.g., 1e-6) and replace or supplement the existing TEST_EQUAL(deltas.size() >= 3u, true) with an explicit presence assertion using the deltas container and the test helper macro (e.g., TEST_EQUAL/TEST_REAL_SIMILAR or equivalent) so the invalid conflict sum is guaranteed to be enumerated.
1959-1959:⚠️ Potential issue | 🔴 CriticalAdd the missing standard-library includes.
This file uses
std::absandstd::set, but the include block only adds<limits>. Add<cmath>and<set>near the other standard headers to avoid strict-toolchain compile failures.Proposed fix
`#include` <OpenMS/KERNEL/MSSpectrum.h> `#include` <OpenMS/KERNEL/Peak1D.h> +#include <cmath> `#include` <limits> +#include <set>Also applies to: 2029-2029
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/tests/class_tests/openms/source/FragmentIndex_test.cpp` at line 1959, This file is missing standard headers for symbols used: add `#include` <cmath> for std::abs and `#include` <set> for std::set in the include block alongside the other standard headers so strict toolchains compile; locate the top-of-file include section (around existing <limits> include) and insert these two headers to satisfy usages like std::abs(hit.sigma_delta_) and any std::set declarations.
🤖 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/tests/class_tests/openms/source/FragmentIndex_test.cpp`:
- Around line 1428-1477: The test currently verifies SNES reduces peptide count
but not fragments; update the test in FragmentIndex_test to directly compare
fragment counts by calling fi_naive.getFragments().size() and
fi_snes.getFragments().size() (in addition to the existing peptide checks) and
assert fi_snes.getFragments().size() < fi_naive.getFragments().size(); keep the
existing setup and validation of isSnesMode(), getPeptides(), build(), and
parameter toggles, and ensure both getFragments() sizes are > 0 as
cross-validation.
---
Duplicate comments:
In `@src/tests/class_tests/openms/source/FragmentIndex_test.cpp`:
- Around line 2066-2067: The test currently checks only that
fi.getSnesSigmaDeltaSet() returns at least 3 entries which can pass vacuously;
modify the test around the deltas variable to explicitly assert that a value
approximately equal to 85.016379 (Σ ≈ 85.016379) is present by scanning deltas
for an element within a small tolerance (e.g., 1e-6) and replace or supplement
the existing TEST_EQUAL(deltas.size() >= 3u, true) with an explicit presence
assertion using the deltas container and the test helper macro (e.g.,
TEST_EQUAL/TEST_REAL_SIMILAR or equivalent) so the invalid conflict sum is
guaranteed to be enumerated.
- Line 1959: This file is missing standard headers for symbols used: add
`#include` <cmath> for std::abs and `#include` <set> for std::set in the include
block alongside the other standard headers so strict toolchains compile; locate
the top-of-file include section (around existing <limits> include) and insert
these two headers to satisfy usages like std::abs(hit.sigma_delta_) and any
std::set declarations.
🪄 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: 1569f4b5-6a5e-4ebb-8509-98840ec0b58e
📒 Files selected for processing (1)
src/tests/class_tests/openms/source/FragmentIndex_test.cpp
…g (M1) The RSS high-water mark of a ProSE search is inside PeptideIndexing::run() (Aho-Corasick) with the FragmentIndex still resident. On human-proteome searches this overlap costs hundreds of MB of steady-state peak (~500 MB measured on the PR #9191 benchmark). Fix is NOT unconditional: search(spectra, ctx, ...) is a public API documented for reuse — externally-owned contexts (prepareContext + multiple search() calls, multi-file non-chunked path, ProSEAlgorithm_test line 1078) must NOT see their ctx.fragment_index freed by a single search() call. Adding an unconditional clear() broke those paths (ProSEAlgorithm_test regression caught locally). Instead: add `SearchContext::release_fragment_index_after_scoring` (default false). The search(spectra, ctx, ...) path honors it after scoreSpectraAgainstIndex_ returns. The internal wrapper search(spectra, fasta_db, ...) sets it true on the throw-away ctx it creates (both the non-chunked case at line 1020 and the "augmented DB fits in one chunk" case at line 1034). External callers keep the reuse contract intact. Also: FragmentIndex::clear() now uses the swap-to-empty idiom on its bulk vectors (fi_fragments_, fi_peptides_, bucket_min_mz_, protein_lengths_) so the heap capacity is actually released, not just the logical size. std::vector::clear() alone is a no-op on RSS — the swap is the only portable way to force deallocation. All 29 FragmentIndex + ProSE tests pass, including the context-reuse scenario. Addresses memory agent finding M1. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (7)
src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp (2)
160-168:⚠️ Potential issue | 🟡 MinorUpdate the SNES help text to v1.1 behavior.
Line 167 still says variable modifications are unsupported, but this PR applies them via query-time subset enumeration.
Documentation fix
- // takes effect when peptide:enzyme_specificity=none. v1 opt-in (default false). + // takes effect when peptide:enzyme_specificity=none. v1.1 opt-in (default false). defaults_.setValue("snes_enabled", "false", - "[experimental, v1 opt-in] When peptide:enzyme_specificity=none, use mother-" + "[experimental, v1.1 opt-in] When peptide:enzyme_specificity=none, use mother-" "peptide indexing (Single-N + Single-C, one ion series per mother) instead of " "naïve O(L^2) sub-peptide enumeration. Much smaller index and faster search on " "non-specific workloads (immunopeptidomics). Ignored for specific/semi-" - "specific enzymes. Variable modifications on mothers are not supported in v1."); + "specific enzymes. Variable modifications are applied at query time via " + "subset enumeration on realized sub-peptides.");🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp` around lines 160 - 168, The SNES help text for the "snes_enabled" default is outdated about variable modifications; update the string passed to defaults_.setValue (the description for "snes_enabled") to reflect v1.1 behavior by replacing the sentence "Variable modifications on mothers are not supported in v1." with a statement such as "Variable modifications on mothers are supported in v1.1 via query-time subset enumeration." Ensure you only edit the description string associated with defaults_.setValue("snes_enabled", ...) so the key and valid strings remain unchanged.
2341-2351:⚠️ Potential issue | 🟡 MinorUse current SNES wording in the calibration warning.
The runtime message still reports “SNES mode (v1)”, which is stale for this v1.1 path.
Message fix
- OPENMS_LOG_WARN << "[ProSE] Calibration is not supported in SNES mode (v1). " + OPENMS_LOG_WARN << "[ProSE] Calibration is not supported in SNES mode (v1.1). " << "Using configured precursor tolerance unchanged.\n";🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp` around lines 2341 - 2351, Update the calibration warning message emitted in the fragment_index.isSnesMode() branch to use the current SNES wording (replace the stale "SNES mode (v1)" text with the up-to-date label, e.g. "SNES (v1.1)"); modify the string passed to OPENMS_LOG_WARN in ProSEAlgorithm.cpp so the log reads the new wording while keeping the rest of the message and the early return (return result) unchanged.src/openms/source/ANALYSIS/ID/FragmentIndex.cpp (5)
750-783:⚠️ Potential issue | 🟠 MajorDo not discard valid shorter realizations before ambiguous residues.
When a max-length mother overlaps
X/B/Z, the whole anchor is skipped, even though shorter realized peptides ending before the ambiguous residue are valid and searchable. Truncate to the next ambiguous boundary or generate mothers per contiguous unambiguous span.I can draft the span-based mother generation patch if helpful.
🤖 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 750 - 783, The current emitMother lambda rejects any mother that overlaps an ambiguous residue by using protein_has_ambiguous and seq.find_first_of(start) to skip the whole span, which discards valid shorter realizations before the ambiguous position; change emitMother to truncate the proposed mother at the next ambiguous residue instead of rejecting the whole mother (or iterate contiguous unambiguous spans): when creating a mother (emitMother(start,length,...)) compute bad = seq.find_first_of("XBZ", start) and if bad != npos and bad < start+length reduce length = bad - start (and re-check length >= peptide_min_length_), and ensure effective_max_length uses peptide_max_length_ logic unchanged so mothers are generated per unambiguous span rather than skipped entirely; alternatively implement splitting logic that walks seq to find contiguous unambiguous spans and calls emitMother for each span respecting effective_max_length and peptide_min_length_.
1911-1920:⚠️ Potential issue | 🔴 CriticalUse a
uint64_tloop variable to avoid wraparound.When
n_slots == 32,max_bitmask64is2^32;uint32_t bmwraps fromUINT32_MAXto0, and the loop condition stays true. The per-mother cap does not save cases with fewer than 16 valid subsets.Loop fix
- for (uint32_t bm = 1; static_cast<uint64_t>(bm) < max_bitmask64; ++bm) + for (uint64_t bm = 1; bm < max_bitmask64; ++bm) { - if (static_cast<size_t>(std::popcount(bm)) > max_variable_mods_per_peptide_) continue; + const uint32_t bm32 = static_cast<uint32_t>(bm); + if (static_cast<size_t>(std::popcount(bm32)) > max_variable_mods_per_peptide_) continue; // Position-conflict check. bool conflict = false; for (size_t a = 0; a < n_slots && !conflict; ++a) { - if (!(bm & (1u << a))) continue; + if (!(bm32 & (1u << a))) continue; for (size_t b = a + 1; b < n_slots; ++b) { - if (!(bm & (1u << b))) continue; + if (!(bm32 & (1u << b))) continue; if (slots[a].position == slots[b].position) { conflict = true; break; } } } @@ - if (bm & (1u << s)) subset_sigma += slots[s].delta_mass; + if (bm32 & (1u << s)) subset_sigma += slots[s].delta_mass; @@ - sm_variant.subset_bitmask_ = bm; + sm_variant.subset_bitmask_ = bm32;Run this read-only check to confirm whether the 32-bit loop remains:
#!/bin/bash rg -n -C4 'max_bitmask64|for \(uint32_t bm' src/openms/source/ANALYSIS/ID/FragmentIndex.cpp🤖 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 1911 - 1920, The loop uses a uint32_t iterator bm against a uint64_t max_bitmask64 so when n_slots==32 bm wraps from UINT32_MAX to 0 and the loop never terminates; change the loop variable type to uint64_t (i.e., iterate uint64_t bm = 1; bm < max_bitmask64; ++bm) and keep the existing checks (std::popcount(bm) and max_variable_mods_per_peptide_) so behaviour is identical for n_slots ≤ MAX_MOD_SLOTS while preventing wraparound; update any casts or uses of bm elsewhere in this scope to match uint64_t where needed.
1697-1705:⚠️ Potential issue | 🟠 MajorCollapse SNES isotope iteration in open-search mode.
The non-SNES path uses only isotope error
0for open search, but SNES still iterates the configured isotope range. With wide precursor windows this can emit duplicate or mislabeled candidates and distort isotope-error features.SNES isotope-loop fix
- for (int16_t iso_err = min_isotope_error_; iso_err <= max_isotope_error_; ++iso_err) + const bool open_mode = isOpenSearchMode_(); + const int16_t iso_lo = open_mode ? 0 : min_isotope_error_; + const int16_t iso_hi = open_mode ? 0 : max_isotope_error_; + for (int16_t iso_err = iso_lo; iso_err <= iso_hi; ++iso_err)🤖 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 1697 - 1705, The SNES path still iterates min_isotope_error_..max_isotope_error_ during open-search, causing duplicate/mislabeled candidates; inside the loop in FragmentIndex.cpp that enumerates uint16_t charge and int16_t iso_err, detect open-search mode and collapse the isotope iteration to only iso_err==0 when SNES/open-search is active (i.e., replace the full-range for (int16_t iso_err = min_isotope_error_; iso_err <= max_isotope_error_; ++iso_err) with logic that sets iso_err to 0 if open-search+SNES is true, otherwise iterate the configured range), referencing the variables min_isotope_error_, max_isotope_error_, iso_err, charges and the existing MH/shifted_mh computation so behavior and downstream use of Constants::C13C12_MASSDIFF_U stays consistent.
1510-1522:⚠️ Potential issue | 🟠 MajorTreat non-positive precursor charges as unknown.
precursor.getCharge()can be negative; casting it touint16_tturns-2into a huge charge and corrupts SNES precursor targets. Only accept positive charges, otherwise fall back to the configured range. Based on learnings, in mass spectrometry data, precursor charges can be negative, so signed integer types should be used instead of unsigned integers when storing charge values.Charge handling fix
- vector<uint16_t> charges; - if (precursor.getCharge()) + vector<uint16_t> charges; + const Int precursor_charge = precursor.getCharge(); + if (precursor_charge > 0) { - charges.push_back(static_cast<uint16_t>(precursor.getCharge())); + charges.push_back(static_cast<uint16_t>(precursor_charge)); } else🤖 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 1510 - 1522, The code incorrectly treats negative precursor charges as valid by casting them to uint16_t; change vector<uint16_t> charges to a signed type (e.g., vector<int16_t>) and only accept precursor.getCharge() when it is > 0 (use if (precursor.getCharge() > 0) { charges.push_back(static_cast<int16_t>(precursor.getCharge())); } ), otherwise fall back to populating the range using signed loop indices (for (int16_t z = static_cast<int16_t>(min_precursor_charge_); z <= static_cast<int16_t>(max_precursor_charge_); ++z) { charges.push_back(z); } ); update any related casts/usages to the new signed type to avoid unsigned wraparound from negative charges.
544-560:⚠️ Potential issue | 🟠 MajorGate protein-specific fixed terminal mods by realized protein boundaries.
fixed_nterm_delta_/fixed_cterm_delta_still get applied to every realized SNES peptide. ForPROTEIN_N_TERM/PROTEIN_C_TERMfixed mods, internal realizations get incorrect masses and reported sequences unless terminal specificity is preserved and checked againstrealized_start == 0/realized_end == protein_seq.size().Also applies to: 635-636
🤖 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 544 - 560, realizeSNESLength currently always adds fixed_nterm_delta_ / fixed_cterm_delta_ to the computed base mass which wrongly applies protein-specific terminal mods to internal realizations; update FragmentIndex::realizeSNESLength so that when computing base (and later when handling realized_start/end at the logic around lines referenced ~635-636) you only apply fixed_nterm_delta_ if the fixed N-term mod is not protein-specific OR (it is PROTEIN_N_TERM and realized_start == 0), and only apply fixed_cterm_delta_ if the fixed C-term mod is not protein-specific OR (it is PROTEIN_C_TERM and realized_end == protein_seq.size()); use the existing mother_start/mother_length/protein_seq and realized_start/realized_end values and the PROTEIN_N_TERM / PROTEIN_C_TERM specificity checks to gate adding those deltas so internal realizations preserve correct mass and reported sequence.
🤖 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 1673-1695: The code only precomputes σ sets for baseline,
PROTEIN_N_TERM and PROTEIN_C_TERM, so peptides carrying both protein-terminal
variable mods (Σ = nterm + cterm) are never considered; add a combined set by
calling computeSnesSigmaDeltaSet_(true, true) (or the equivalent routine used to
build snes_sigma_delta_set_with_prot_nterm_/prot_cterm_) and compute its
set-difference versus snes_sigma_delta_set_ (using the same set_difference_tol
helper) into a new vector like prot_both_term_extra, then update the
candidate-collection logic (the SnesAnchor-gated extra bin-walks in
collect_candidates) to include a walk for that combined σ when the mother spans
both protein boundaries (i.e., gate it with the same SnesAnchor condition used
for single-term walks but checking both protein-terminal anchors). Ensure you
reference snes_sigma_delta_set_with_prot_nterm_,
snes_sigma_delta_set_with_prot_cterm_, set_difference_tol,
computeSnesSigmaDeltaSet_(true,true) and collect_candidates so the new vector is
computed and the extra walk is executed when both protein-term mods apply.
---
Duplicate comments:
In `@src/openms/source/ANALYSIS/ID/FragmentIndex.cpp`:
- Around line 750-783: The current emitMother lambda rejects any mother that
overlaps an ambiguous residue by using protein_has_ambiguous and
seq.find_first_of(start) to skip the whole span, which discards valid shorter
realizations before the ambiguous position; change emitMother to truncate the
proposed mother at the next ambiguous residue instead of rejecting the whole
mother (or iterate contiguous unambiguous spans): when creating a mother
(emitMother(start,length,...)) compute bad = seq.find_first_of("XBZ", start) and
if bad != npos and bad < start+length reduce length = bad - start (and re-check
length >= peptide_min_length_), and ensure effective_max_length uses
peptide_max_length_ logic unchanged so mothers are generated per unambiguous
span rather than skipped entirely; alternatively implement splitting logic that
walks seq to find contiguous unambiguous spans and calls emitMother for each
span respecting effective_max_length and peptide_min_length_.
- Around line 1911-1920: The loop uses a uint32_t iterator bm against a uint64_t
max_bitmask64 so when n_slots==32 bm wraps from UINT32_MAX to 0 and the loop
never terminates; change the loop variable type to uint64_t (i.e., iterate
uint64_t bm = 1; bm < max_bitmask64; ++bm) and keep the existing checks
(std::popcount(bm) and max_variable_mods_per_peptide_) so behaviour is identical
for n_slots ≤ MAX_MOD_SLOTS while preventing wraparound; update any casts or
uses of bm elsewhere in this scope to match uint64_t where needed.
- Around line 1697-1705: The SNES path still iterates
min_isotope_error_..max_isotope_error_ during open-search, causing
duplicate/mislabeled candidates; inside the loop in FragmentIndex.cpp that
enumerates uint16_t charge and int16_t iso_err, detect open-search mode and
collapse the isotope iteration to only iso_err==0 when SNES/open-search is
active (i.e., replace the full-range for (int16_t iso_err = min_isotope_error_;
iso_err <= max_isotope_error_; ++iso_err) with logic that sets iso_err to 0 if
open-search+SNES is true, otherwise iterate the configured range), referencing
the variables min_isotope_error_, max_isotope_error_, iso_err, charges and the
existing MH/shifted_mh computation so behavior and downstream use of
Constants::C13C12_MASSDIFF_U stays consistent.
- Around line 1510-1522: The code incorrectly treats negative precursor charges
as valid by casting them to uint16_t; change vector<uint16_t> charges to a
signed type (e.g., vector<int16_t>) and only accept precursor.getCharge() when
it is > 0 (use if (precursor.getCharge() > 0) {
charges.push_back(static_cast<int16_t>(precursor.getCharge())); } ), otherwise
fall back to populating the range using signed loop indices (for (int16_t z =
static_cast<int16_t>(min_precursor_charge_); z <=
static_cast<int16_t>(max_precursor_charge_); ++z) { charges.push_back(z); } );
update any related casts/usages to the new signed type to avoid unsigned
wraparound from negative charges.
- Around line 544-560: realizeSNESLength currently always adds
fixed_nterm_delta_ / fixed_cterm_delta_ to the computed base mass which wrongly
applies protein-specific terminal mods to internal realizations; update
FragmentIndex::realizeSNESLength so that when computing base (and later when
handling realized_start/end at the logic around lines referenced ~635-636) you
only apply fixed_nterm_delta_ if the fixed N-term mod is not protein-specific OR
(it is PROTEIN_N_TERM and realized_start == 0), and only apply
fixed_cterm_delta_ if the fixed C-term mod is not protein-specific OR (it is
PROTEIN_C_TERM and realized_end == protein_seq.size()); use the existing
mother_start/mother_length/protein_seq and realized_start/realized_end values
and the PROTEIN_N_TERM / PROTEIN_C_TERM specificity checks to gate adding those
deltas so internal realizations preserve correct mass and reported sequence.
In `@src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp`:
- Around line 160-168: The SNES help text for the "snes_enabled" default is
outdated about variable modifications; update the string passed to
defaults_.setValue (the description for "snes_enabled") to reflect v1.1 behavior
by replacing the sentence "Variable modifications on mothers are not supported
in v1." with a statement such as "Variable modifications on mothers are
supported in v1.1 via query-time subset enumeration." Ensure you only edit the
description string associated with defaults_.setValue("snes_enabled", ...) so
the key and valid strings remain unchanged.
- Around line 2341-2351: Update the calibration warning message emitted in the
fragment_index.isSnesMode() branch to use the current SNES wording (replace the
stale "SNES mode (v1)" text with the up-to-date label, e.g. "SNES (v1.1)");
modify the string passed to OPENMS_LOG_WARN in ProSEAlgorithm.cpp so the log
reads the new wording while keeping the rest of the message and the early return
(return result) unchanged.
🪄 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: b115be74-f39a-48a7-b3e2-a559970fe205
📒 Files selected for processing (3)
src/openms/include/OpenMS/ANALYSIS/ID/ProSEAlgorithm.hsrc/openms/source/ANALYSIS/ID/FragmentIndex.cppsrc/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp
CI Doxygen_Warning_test failed across all 4 Linux/macOS builds with "parameter 'fasta_entries' is not documented" on querySpectrumSNES_. The param was added in commit 78c9f86 (dangling-pointer fix) but the Doxygen @PARAM entries weren't updated. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h (1)
295-318:⚠️ Potential issue | 🟡 MinorDocument the SNES contract on the legacy overload too.
The new overload explains why FASTA context is needed, but the existing two-argument overload still reads as generally valid. Add a short note there so external callers do not accidentally bypass SNES v1.1 variable-mod realization.
Documentation fix
* `@param`[in] spectrum experimental spectrum * `@param`[out] sms The n best Spectrum matches + * + * `@note` In SNES mode, prefer the overload accepting `@c` fasta_entries so + * query-time variable modification candidates can be realized with + * protein context. */ void querySpectrum(const MSSpectrum& spectrum, SpectrumMatchesTopN& sms);As per coding guidelines,
src/openms/include/OpenMS/**/*.h: “Add Doxygen comments for new public methods and classes, and update relevant documentation when modifying existing functionality”.🤖 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 295 - 318, The two-argument overload querySpectrum(const MSSpectrum& spectrum, SpectrumMatchesTopN& sms) lacks the SNES-specific contract documented on the three-argument overload; update its Doxygen to state that when FragmentIndex was built in SNES mode with variable modifications callers must use the FASTA-taking overload so sub-peptides and variable mods are realized, and that the legacy overload ignores FASTA context and should only be used for non-SNES or SNES-without-variable-mods paths (add a short sentence and a “see also” reference to the overload taking std::vector<FASTAFile::FASTAEntry> and SpectrumMatchesTopN).
♻️ Duplicate comments (2)
src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h (2)
416-418:⚠️ Potential issue | 🟡 MinorRefresh this stale SNES variable-modification note.
This still says variable modifications are disabled in SNES mode, but v1.1 keeps mothers unmodified and applies variable-mod subsets during query-time realization.
Documentation fix
- * v1 restriction: variable modifications are disabled in SNES mode. A warning is - * emitted at build time if any variable modification is configured. Fixed - * modifications (both residue-specific and terminal) are fully supported. + * SNES v1.1 keeps mothers unmodified and applies variable modifications at + * query time on realized sub-peptides. Fixed modifications (both residue- + * specific and terminal) are fully supported.As per coding guidelines,
src/openms/include/OpenMS/**/*.h: “Add Doxygen comments for new public methods and classes, and update relevant documentation when modifying existing functionality”.🤖 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 416 - 418, Update the stale Doxygen note in FragmentIndex.h describing SNES variable-mod behavior: change the wording that "variable modifications are disabled in SNES mode" to reflect v1.1 semantics — mothers remain unmodified and variable-mod subsets are applied during query-time realization; mention that fixed modifications are still fully supported and that a build-time warning is no longer emitted for configured variable modifications (or clarify when warnings occur). Locate and edit the comment block near the FragmentIndex/SNES-related documentation (e.g., references to SNES mode or FragmentIndex class) to accurately describe v1.1 behavior and ensure the header follows the project's Doxygen/documentation guidelines for public API changes.
361-371:⚠️ Potential issue | 🟡 MinorAdd the required Doxygen
@briefblock for this public API.
reconstructRealizedSubSequence()still lacks the required@briefformat and exception documentation.Documentation fix
- /// Reconstruct a realized SNES sub-peptide as an AASequence. - /// `@param` mother the SNES mother Peptide entry - /// `@param` fasta_entries the FASTA entries used to build the index - /// `@param` realized_length the length of the realized sub-peptide (from realizeSNESLength) - /// `@param` subset_bitmask SNES v1.1: active slots from buildModSlots_(seq_ptr, realized_length, ...) - /// to apply as variable modifications. 0 = unmodified (backward compatible). - /// `@return` AASequence representing the realized sub-peptide with any variable mods from subset_bitmask applied + /** + * `@brief` Reconstruct a realized SNES sub-peptide as an AASequence. + * + * Applies fixed modifications and, when `@p` subset_bitmask is non-zero, + * applies variable modifications from the realized sub-peptide slot list. + * + * `@param`[in] mother The SNES mother Peptide entry. + * `@param`[in] fasta_entries The FASTA entries used to build the index. + * `@param`[in] realized_length The length returned by realizeSNESLength(). + * `@param`[in] subset_bitmask Active SNES v1.1 mod slots; 0 means unmodified. + * `@return` AASequence representing the realized sub-peptide. + * + * `@throws` Exception::Base if sequence reconstruction or modification assignment fails. + */ AASequence reconstructRealizedSubSequence(const Peptide& mother,As per coding guidelines,
src/openms/include/OpenMS/**/*.h: “Add Doxygen comments for new public methods and classes” and**/*.h: “Use@briefplus blank line plus detailed description in Doxygen comments; required@brieftag” / “Document possible exceptions in C++ function/method documentation.”🤖 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 361 - 371, Add a proper Doxygen `@brief` block for the public method reconstructRealizedSubSequence (in class FragmentIndex), starting with an `@brief` line, a blank line, then a short detailed description describing purpose and behavior, and include `@param` tags for mother, fasta_entries, realized_length, and subset_bitmask; also add `@return` describing the AASequence result and an `@exception` section documenting any exceptions the method can throw (e.g., std::invalid_argument, std::out_of_range, std::runtime_error or specific internal error types) so callers know error conditions.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h`:
- Around line 252-269: Update the Doxygen for the three new public SNES helper
methods (isSingleCMother, isSingleNMother, isSnesMode) to include a required
`@brief` line followed by a blank line and a more detailed description; replace
the current lone `@return-only` comments with a short `@brief` describing purpose
(e.g., "Check whether the mother is Single-C/Single-N" or "Whether the index was
built in SNES mode") then a blank line and a longer explanation of semantics and
conditions, and keep the existing `@return` text intact below the detail
paragraph.
---
Outside diff comments:
In `@src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h`:
- Around line 295-318: The two-argument overload querySpectrum(const MSSpectrum&
spectrum, SpectrumMatchesTopN& sms) lacks the SNES-specific contract documented
on the three-argument overload; update its Doxygen to state that when
FragmentIndex was built in SNES mode with variable modifications callers must
use the FASTA-taking overload so sub-peptides and variable mods are realized,
and that the legacy overload ignores FASTA context and should only be used for
non-SNES or SNES-without-variable-mods paths (add a short sentence and a “see
also” reference to the overload taking std::vector<FASTAFile::FASTAEntry> and
SpectrumMatchesTopN).
---
Duplicate comments:
In `@src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h`:
- Around line 416-418: Update the stale Doxygen note in FragmentIndex.h
describing SNES variable-mod behavior: change the wording that "variable
modifications are disabled in SNES mode" to reflect v1.1 semantics — mothers
remain unmodified and variable-mod subsets are applied during query-time
realization; mention that fixed modifications are still fully supported and that
a build-time warning is no longer emitted for configured variable modifications
(or clarify when warnings occur). Locate and edit the comment block near the
FragmentIndex/SNES-related documentation (e.g., references to SNES mode or
FragmentIndex class) to accurately describe v1.1 behavior and ensure the header
follows the project's Doxygen/documentation guidelines for public API changes.
- Around line 361-371: Add a proper Doxygen `@brief` block for the public method
reconstructRealizedSubSequence (in class FragmentIndex), starting with an `@brief`
line, a blank line, then a short detailed description describing purpose and
behavior, and include `@param` tags for mother, fasta_entries, realized_length,
and subset_bitmask; also add `@return` describing the AASequence result and an
`@exception` section documenting any exceptions the method can throw (e.g.,
std::invalid_argument, std::out_of_range, std::runtime_error or specific
internal error types) so callers know error conditions.
🪄 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: 6622e3b7-4f7a-4912-b6b3-99678b58f740
📒 Files selected for processing (1)
src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h
Verified each against current code; five are valid and trivially fixable. #2 (FragmentIndex.cpp querySpectrumSNES_): collapse isotope-error loop to [0,0] when isOpenSearchMode_() is true, mirroring the non-SNES queryPeaks behavior at FragmentIndex.cpp:1478-1480. SNES + open search is already nonsensical (fragment-index-as-precursor-filter doesn't work at 500 Da precursor windows), but the guard prevents duplicate- labelled candidates if a user configures it anyway. #3 (ProSEAlgorithm.cpp:2349): "[ProSE] Calibration is not supported in SNES mode (v1)" → "(v1.1)". Text-only — calibration disable decision is unchanged. #5 (FragmentIndex.cpp subset enum): widen bitmask loop variable from uint32_t to uint64_t to prevent wraparound at n_slots == 32 (where ++bm past UINT32_MAX would re-enter the loop with bm=0). Not reachable in SNES mode today (bit 31 is reserved for the kind flag, so n_slots ≤ 31), but the defensive width keeps the loop terminating on any future widening of MAX_MOD_SLOTS. Inner `1u << s` shifts updated to `uint64_t{1} << s` to match. Narrowing cast on assignment to `SpectrumMatch::subset_bitmask_` (uint32_t) is value-preserving and explicitly documented. #7 (FragmentIndex.cpp:1512): Precursor::getCharge() returns signed Int; the previous `if (precursor.getCharge())` was truthy for negative charges and the cast `static_cast<uint16_t>(-1)` wrapped to 65535, which was then used as an actual charge downstream. Guard with `> 0` and fall back to the configured min..max range on non-positive input. #8 (ProSEAlgorithm.cpp:160-168): snes_enabled parameter docstring still said "Variable modifications on mothers are not supported in v1"; now reflects v1.1 support via query-time subset enumeration. Findings NOT addressed here (defer to separate PRs): - #1 (fixed PROTEIN_N/C_TERM specificity not preserved): real correctness bug, but the fix touches ~7 usage sites across build and query paths and changes the fragment-index layout semantics. Warrants its own design + tests. Current behavior is documented in the roadmap. - #4 (reconstructRealizedSubSequence full Doxygen block): stylistic preference; the current /// short-description + @PARAM + @return block is adequate and matches other styles used elsewhere in this file. - #6 (emitMother X/B/Z truncation vs reject): roadmap item; changes search semantics (more valid mothers admitted when ambiguous residues are present) and needs a dedicated test. Still open in the PR roadmap comment. All 29 FragmentIndex + ProSE ctest targets pass locally (47 sections). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Filed #9192 to track the two SNES review findings deferred from this PR: fixed PROTEIN_N/C_TERM specificity preservation and X/B/Z truncation in mother generation. Both verified valid in current code but require substantive changes (≥1 file with multi-site refactor each + new tests) beyond v1.1 scope. |
Add missing changelog entries for PRs merged after 2026-04-19 sync: - #9186: MascotGenericFile SEQ= field support (read/write) - #9188: ProSE Orbitrap-aware isotope defaults [0,+2] + isotope_error Percolator feature - #9191: ProSE SNES mother-peptide indexing for non-specific searches Co-authored-by: GitHub Copilot <[email protected]> Co-authored-by: Copilot <[email protected]>
Restore ProSE/FragmentIndex/File entries dropped by the FeatureFinderCentroided reorganization commit (#9159) and add new entries for commits merged after the last sync: - #9188: ProSE BREAKING: default isotope error range changed to [0,+2] - #9191: ProSE SNES mother-peptide indexing for non-specific searches - #9195: ProSE fix: defer PSM FDR when Percolator enabled; valid .pin output - #9203: FragmentIndex: fixed bucket_size 4096 for tighter candidate lists - #9204: ProSE: resolve PercolatorAdapter via findSiblingTOPPExecutable - #9205: ProSE: per-file output isolation + dangling decoy ref crash fix - #9207: File::rename: cross-device fallback (copy+remove on EXDEV) Co-authored-by: GitHub Copilot <[email protected]> Co-authored-by: Copilot <[email protected]>
Summary
Follow-up to #9189. Adds variable-modification support to SNES non-specific searches via query-time lazy enumeration (MetaMorpheus-style delta-bag precursor filter + direct per-candidate rescore).
modifications:variableandmodifications:variable_max_per_peptidenow take effect withsnes_enabled=true.SNES_KIND_BIT_MASKmasking inreconstructModifiedSequence+ fragment-generation is a no-op for non-SNES callers.Architecture
querySpectrumSNES_loops over precomputed Σ_delta values (baseline + PROTEIN_N_TERM-anchored extras + PROTEIN_C_TERM-anchored extras), each iteration shifts the precursor target and collects (mother, Σ) pairs.realizeSNESLength(shifted_mh − Σ), callbuildModSlots_scoped to the realized sub-peptide, enumerate bitmask subsets satisfying popcount ≤ max_per_peptide ∧ no position conflict ∧ Σ_subset ≈ Σ. Emit oneSpectrumMatchper valid subset.trimHitscap still applies.sigma_delta_from the realization target; forwardssubset_bitmask_toreconstructRealizedSubSequence.Design spec:
docs/superpowers/specs/2026-04-20-prose-snes-variable-mods-design.mdImplementation plan:
docs/superpowers/plans/2026-04-20-prose-snes-variable-mods-plan.mdTest plan
Key files
src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h—SpectrumMatchextended withsubset_bitmask_andsigma_delta_(4B+4B, struct grows 16 → 24 B);SnesAnchorenum; threesnes_sigma_delta_set_*members;protein_lengths_;fasta_entries_ptr_for_snes_; extendedreconstructRealizedSubSequencesignature.src/openms/source/ANALYSIS/ID/FragmentIndex.cpp—computeSnesSigmaDeltaSet_helper; populate sets inupdateMembers_; restructuredquerySpectrumSNES_with three-tier Σ loop; subset enumeration post-pass;collect_candidatesanchor filter.src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp— subtractsigma_delta_from realization target; forwardsubset_bitmask_.src/tests/class_tests/openms/source/FragmentIndex_test.cpp— 14 new test sections (default-init, masking, Σ-set values + protein-term flag, populate, reconstructRealizedSubSequence, modified candidate, emit-both, position conflict + max_mods + identical-delta, PROT_N_TERM + PROT_C_TERM anchor-gating, query-path position conflict rejection).🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Improvements
Bug Fixes
Tests