Repository navigation
feat: Expand fragment index open search with modification discovery and FDR filtering - #8414
Conversation
|
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 a statistics-first open-search analysis: new result structs and APIs in OpenSearchModificationAnalysis (C++ + Python bindings), unit tests, and integration into PeptideSearchEngineFIAlgorithm via a new searchWithModificationAnalysis API that returns structured analysis and optional TSV outputs. Changes
Sequence Diagram(s)sequenceDiagram
participant Client as Client
participant PSEFI as PeptideSearchEngineFIAlgorithm
participant OSMA as OpenSearchModificationAnalysis
participant ModDB as ModificationsDB
Client->>PSEFI: searchWithModificationAnalysis(mzML, db, output_base)
PSEFI->>PSEFI: run search() -> peptide_ids, protein_ids
PSEFI->>PSEFI: if open-search enabled
PSEFI->>OSMA: analyzeModificationsWithStatistics(peptide_ids, params)
OSMA->>OSMA: analyzeDeltaMassPatterns() -> histogram, charge_histogram
OSMA->>OSMA: generateDeltaMassStatistics(histogram, charge_histogram, peptide_ids)
OSMA->>ModDB: buildModificationMassLookup_()/query known masses
ModDB-->>OSMA: known modification masses/names
OSMA->>OSMA: generatePTMStatistics(peptide_ids)
OSMA->>OSMA: analyzeResidueFrequency(delta_mass)
OSMA->>OSMA: writeDeltaMassStatistics()/writePTMStatistics() [optional]
OSMA-->>PSEFI: OpenSearchAnalysisResult (delta_mass_stats, ptm_stats, summaries)
PSEFI->>PSEFI: log formatted top PTMs & unknown delta masses
PSEFI-->>Client: SearchResult (exit_code, protein_ids, peptide_ids, modification_analysis, is_open_search)
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: 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/PeptideSearchEngineFIAlgorithm.h (1)
39-52: Duplicate Doxygen documentation block.Lines 39-52 duplicate the class documentation from lines 25-38. This appears to be a copy-paste error that should be removed.
-/** - @brief Fragment-index-based peptide database search algorithm (experimental). - - Provides a self-contained search engine that matches MS/MS spectra against a protein - database using an FI (Fragment Index). Typical usage: - - Configure parameters via DefaultParamHandler (mass tolerances, enzyme, charges, etc.) - - Call search() with an input mzML file and a FASTA database to populate identification - outputs (ProteinIdentification and PeptideIdentificationList) - - Intended for educational/prototyping use and to demonstrate FI-backed searching - - Notes: - - Used by the PeptideDataBaseSearchFI TOPP tool - - Experimental; interfaces and behavior may change -*/ class OPENMS_DLLAPI PeptideSearchEngineFIAlgorithm :
🧹 Nitpick comments (6)
src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp (3)
664-688: Unused parameters ingeneratePTMStatistics.Both
precursor_mass_tolerance(line 666) andprecursor_mass_tolerance_unit_ppm(line 667) are unused in this method. Consider removing them from the signature if not needed, or adding a comment explaining they're reserved for future use.
899-922: Minor code duplication with existing method.This helper duplicates logic from
mapDeltaMassesToModifications(lines 112-127). Consider refactoringmapDeltaMassesToModificationsto use this helper to reduce duplication.
960-964: Broad exception handler acceptable here.The catch-all handler silently ignores exceptions when looking up modifications that may not exist in the database. This is acceptable behavior but consider logging at debug level for troubleshooting.
catch (...) { // Modification not found in database + OPENMS_LOG_DEBUG << "Modification '" << mod_name << "' not found in database" << std::endl; }src/tests/class_tests/openms/source/OpenSearchModificationAnalysis_test.cpp (1)
1-280: Good test coverage for new functionality.The test file covers the main new APIs (
analyzeDeltaMassPatterns,analyzeModificationsWithStatistics,generateDeltaMassStatistics,analyzeResidueFrequency) and the new data structures. The tests follow OpenMS testing conventions.Consider adding tests for
generatePTMStatisticsand edge cases (empty input lists, etc.) in a follow-up.Would you like me to help generate additional test cases for
generatePTMStatisticsor edge case scenarios?src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp (2)
671-723: CheckanalyzeModificationsWithStatisticsoutput-name semantics and keep usage consistentThe integration of
OpenSearchModificationAnalysis mod_analyzer;andanalyzeModificationsWithStatisticsinsearchlooks correct and adds useful high-level stats and top-PTM logging for open search results.One thing to double‑check: here you construct
mod_output_fileas a full*_ModificationAnalysis.idXMLfilename and pass it as the last argument. InsearchWithModificationAnalysisyou instead treat the argument conceptually as a base name (output_base_name) and then log*_DeltaMassStats.tsv/*_PTMStats.tsvderived from that base.If
analyzeModificationsWithStatisticsis defined to take a base name (and internally append_ModificationAnalysis.idXML,_DeltaMassStats.tsv,_PTMStats.tsv), passing a fully suffixed*_ModificationAnalysis.idXMLhere could lead to slightly odd file names or duplicated suffixes. Conversely, if it expects a full idXML path, the naming insearchWithModificationAnalysis’s logs may be misleading.I’d recommend verifying the intended contract of
analyzeModificationsWithStatistics’s last parameter and aligning both call sites and log messages to that contract so users see predictable file names. As per coding guidelines, this also avoids confusion around generated output artifacts.
762-894:searchWithModificationAnalysisis functionally solid but does double work and is too monolithicThe new
SearchResultAPI andsearchWithModificationAnalysismethod are a nice extension and correctly populate:
exit_code,protein_ids,peptide_idsis_open_search(viaisOpenSearchMode_())modification_analysisviaanalyzeModificationsWithStatistics
and add very helpful summary tables for PTMs and unknown delta masses. A few improvement points:
Modification analysis is run twice for open search
search()already performs an open-search modification analysis (including a call toanalyzeModificationsWithStatistics) whenopen_searchis true.searchWithModificationAnalysis()then re-runs the same analysis onresult.peptide_idswhenresult.is_open_searchis true.
This doubles CPU cost and memory traffic for potentially large PSM sets and produces overlapping logs for the same run.
Consider refactoring so modification analysis is executed only once per search, e.g.:- Introduce an internal
searchImpl_(..., OpenSearchAnalysisResult* opt_analysis)that performs the search and optionally fillsopt_analysis, used by bothsearch()andsearchWithModificationAnalysis(), or- Add a flag to
search()to skip internal analysis when called fromsearchWithModificationAnalysis(), and let only the wrapper own the analysis + logging.
This will better respect the “DRY”/reuse intent and, per coding guidelines, reduce avoidable runtime cost on large datasets.Method complexity and logging/formatting responsibilities
The method contains a long block of console formatting (delta-mass summary, PTM table, unknown delta-mass table), which is what CodeFactor flags as “Complex Method”. It’s mostly display logic and can be moved out without changing behavior:
- Extract helpers like
logDeltaMassSummary_(const DeltaMassStatistics&),logTopPTMs_(const PTMStatistics&), andlogUnknownDeltaMasses_(const DeltaMassStatistics&), or- Move these helpers into
OpenSearchModificationAnalysisas utility functions.
This will makesearchWithModificationAnalysis()mostly “orchestration” and keep core algorithmic logic clearer. As per coding guidelines, that improves maintainability on this hot analysis path.Iostream manipulators can leak formatting to other logs
The use ofstd::setw,std::left/std::right,std::fixed, andstd::setprecision(Lines 839–844, 870–874) is fine for alignment, but these manipulators mutate the global logging stream’s state. After this method runs, laterOPENMS_LOG_INFOcalls may still be instd::fixedmode with altered precision, which can subtly affect unrelated log output.
To avoid this, consider:
- Building each line with a local
std::ostringstreamthat sets alignment/precision and then loggingoss.str(), or- Saving/restoring the original stream state around the formatted sections.
This is a small but useful robustness improvement for shared logging infrastructure.“Top Unknown Delta Masses” ordering depends on upstream sorting
Theunknown_dmvector collects all entries with!entry.is_known_modification && entry.count >= 5and then prints the first 10. Unlessdm_stats.entriesis guaranteed to be pre-sorted bycount(or another meaningful criterion), the “top” unknowns might not actually be the highest-count ones.
Two easy options:
- Either explicitly
std::sort(unknown_dm.begin(), unknown_dm.end(), ...)by descendingcountbefore printing, or- Skip the temporary vector and iterate
dm_stats.entriesdirectly, incrementing arankcounter only on unknowns, ifentriesis already sorted appropriately.
This keeps the output semantics (“Top Unknown Delta Masses”) unambiguous.Overall, the API extension and summaries are a good addition; tightening the analysis reuse and splitting the display logic would make this code cleaner and more scalable. Based on learnings, this also keeps algorithmic and logging overhead under better control for large open-search datasets.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
src/openms/include/OpenMS/ANALYSIS/ID/OpenSearchModificationAnalysis.h(4 hunks)src/openms/include/OpenMS/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.h(3 hunks)src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp(1 hunks)src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp(4 hunks)src/tests/class_tests/openms/executables.cmake(1 hunks)src/tests/class_tests/openms/source/OpenSearchModificationAnalysis_test.cpp(1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
src/openms/**/*.{cpp,h,hpp,cc,cxx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms
Files:
src/openms/include/OpenMS/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.hsrc/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cppsrc/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cppsrc/openms/include/OpenMS/ANALYSIS/ID/OpenSearchModificationAnalysis.h
src/openms/include/OpenMS/**/*.h
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Add Doxygen comments for new public methods and classes
Files:
src/openms/include/OpenMS/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.hsrc/openms/include/OpenMS/ANALYSIS/ID/OpenSearchModificationAnalysis.h
src/tests/class_tests/openms/**/*.cpp
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Write unit tests for new functionality
Files:
src/tests/class_tests/openms/source/OpenSearchModificationAnalysis_test.cpp
🧠 Learnings (11)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/**/*.cpp : Write unit tests for new functionality
Applied to files:
src/tests/class_tests/openms/executables.cmakesrc/tests/class_tests/openms/source/OpenSearchModificationAnalysis_test.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/*Test.cpp : Follow naming convention: `ClassNameTest.cpp` for `ClassName`
Applied to files:
src/tests/class_tests/openms/executables.cmakesrc/tests/class_tests/openms/source/OpenSearchModificationAnalysis_test.cpp
📚 Learning: 2025-09-03T12:58:20.032Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8177
File: src/tests/topp/CMakeLists.txt:1857-1865
Timestamp: 2025-09-03T12:58:20.032Z
Learning: OpenMS tests: When adding new TOPP tests in src/tests/topp/CMakeLists.txt that compare outputs via FuzzyDiff, always add set_tests_properties("<tool>_<n>_out<m>" PROPERTIES DEPENDS "<tool>_<n>") to avoid flakiness under parallel CTest runs.
Applied to files:
src/tests/class_tests/openms/executables.cmakesrc/tests/class_tests/openms/source/OpenSearchModificationAnalysis_test.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/include/OpenMS/**/*.h : Add Doxygen comments for new public methods and classes
Applied to files:
src/tests/class_tests/openms/executables.cmakesrc/openms/include/OpenMS/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.hsrc/tests/class_tests/openms/source/OpenSearchModificationAnalysis_test.cppsrc/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cppsrc/openms/include/OpenMS/ANALYSIS/ID/OpenSearchModificationAnalysis.h
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Applied to files:
src/openms/include/OpenMS/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.hsrc/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cppsrc/tests/class_tests/openms/source/OpenSearchModificationAnalysis_test.cppsrc/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cppsrc/openms/include/OpenMS/ANALYSIS/ID/OpenSearchModificationAnalysis.h
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use appropriate OpenMS containers and algorithms
Applied to files:
src/openms/include/OpenMS/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.hsrc/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Utilize OpenMS logging mechanisms
Applied to files:
src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Consider algorithmic complexity for data processing operations
Applied to files:
src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Be mindful of memory usage when processing large datasets
Applied to files:
src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/tests/**/*.py : Write pyOpenMS tests for new Python bindings
Applied to files:
src/tests/class_tests/openms/source/OpenSearchModificationAnalysis_test.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/**/*.h : Add Doxygen comments for new public methods and classes in pyOpenMS bindings
Applied to files:
src/tests/class_tests/openms/source/OpenSearchModificationAnalysis_test.cppsrc/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cppsrc/openms/include/OpenMS/ANALYSIS/ID/OpenSearchModificationAnalysis.h
🧬 Code graph analysis (3)
src/tests/class_tests/openms/source/OpenSearchModificationAnalysis_test.cpp (1)
src/openms/include/OpenMS/ANALYSIS/ID/OpenSearchModificationAnalysis.h (1)
OpenMS(19-303)
src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp (2)
src/openms/source/FORMAT/GNPSMGFFile.cpp (1)
output_file(244-244)src/topp/SageAdapter.cpp (2)
mod(191-216)mod(191-191)
src/openms/include/OpenMS/ANALYSIS/ID/OpenSearchModificationAnalysis.h (1)
src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp (6)
buildModificationMassLookup_(899-922)buildModificationMassLookup_(900-900)getTargetResidues_(924-967)getTargetResidues_(924-924)countUniquePeptides_(969-991)countUniquePeptides_(969-971)
🪛 GitHub Check: CodeFactor
src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp
[notice] 763-895: src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp#L763-L895
Complex Method
src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp
[notice] 665-790: src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp#L665-L790
Complex Method
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: build-and-test (macos-26, xcode, 26.0)
- GitHub Check: build-and-test (ubuntu-22.04-arm, g++, 11)
🔇 Additional comments (11)
src/tests/class_tests/openms/executables.cmake (1)
465-465: LGTM!The test executable entry is correctly added in alphabetical order within the
analysis_executables_list. Based on learnings, this follows the naming conventionClassNameTest.cppforClassName.src/openms/include/OpenMS/ANALYSIS/ID/OpenSearchModificationAnalysis.h (3)
55-108: Well-structured data types for modification analysis.The new data structures (
DeltaMassEntry,PTMEntry,DeltaMassStatistics,PTMStatistics,OpenSearchAnalysisResult) are well-designed with clear documentation. Default member initialization ensures safe usage. As per coding guidelines, all public members have Doxygen comments.
180-270: Comprehensive API with proper documentation.The new public methods are well-documented with Doxygen comments describing parameters, return values, and usage context. The API design follows DRY principles by providing reusable building blocks (
generateDeltaMassStatistics,generatePTMStatistics) alongside the main entry point (analyzeModificationsWithStatistics).
289-300: LGTM!Private helper methods are appropriately declared to support the new statistics generation functionality.
src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp (4)
524-560: LGTM!The orchestration method cleanly integrates existing delta mass analysis with the new statistics generation, and correctly handles output file naming.
820-853: LGTM!The TSV output format is well-structured with header metadata and clear column headers.
855-897: LGTM!Consistent implementation with
writeDeltaMassStatisticsand clear residue frequency formatting.
969-991: LGTM!Clean implementation using
unordered_setfor efficient unique peptide counting.src/openms/include/OpenMS/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.h (2)
70-85: Well-designed result structure.The
SearchResultstruct cleanly encapsulates all search outputs including the new modification analysis data. Good use of default member initialization.
113-159: Excellent API documentation with usage example.The method documentation includes a complete code example demonstrating how to use the modification analysis results. This is very helpful for users of the API. As per coding guidelines, Doxygen comments are properly added for this new public method.
src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp (1)
42-42:<iomanip>include is appropriate for the new formatted loggingIncluding
<iomanip>is correct and required for the laterstd::setw/std::setprecisionusage in the modification-analysis logging. No issues here.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (4)
src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp (4)
923-946: Consider consolidating duplicate modification lookup logic.This helper duplicates the modification database loading pattern from
mapDeltaMassesToModifications(lines 113-127). Both iterate through all modifications and filter out substitutions.Consider extracting this to a single shared implementation or caching the lookup map as a class member if modification analysis is performed multiple times.
984-988: Silent catch-all exception may hide issues.The empty catch block silently swallows all exceptions when looking up a modification. While this prevents crashes from unknown modifications, it may hide unexpected errors.
Consider logging at debug level or being more specific about expected exceptions:
catch (...) { - // Modification not found in database + // Modification not found in database - this is expected for combined/unknown mods + OPENMS_LOG_DEBUG << "Modification '" << mod_name << "' not found in database" << std::endl; }
844-877: Consider checking stream state after writing.The file output methods check
is_open()but don't verify the stream state after writing. For robustness in file I/O, consider checking for write errors:- output_stream.close(); - OPENMS_LOG_INFO << "Delta mass statistics written to: " << output_file << std::endl; + output_stream.close(); + if (output_stream.fail()) + { + OPENMS_LOG_ERROR << "Error writing to file: " << output_file << std::endl; + return; + } + OPENMS_LOG_INFO << "Delta mass statistics written to: " << output_file << std::endl;The same applies to
writePTMStatisticsat lines 879-921.
769-781: Residue frequency analysis may double-count within generatePTMStatistics.The residue counting at lines 776-780 occurs for every hit with a DeltaMass, accumulating counts across all hits for a PTM. This gives residue frequency across all PSMs for that PTM, which may be the intent, but the outer condition
if (hit.metaValueExists("DeltaMass"))at line 770 is redundant since the same check was already made at line 762.- // Analyze residue frequency - if (hit.metaValueExists("DeltaMass")) - { - double delta_mass = hit.getMetaValue("DeltaMass"); - const AASequence& seq = hit.getSequence(); + // Analyze residue frequency (DeltaMass existence already verified above) + const AASequence& seq = hit.getSequence();
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp(1 hunks)src/pyOpenMS/pxds/OpenSearchModificationAnalysis.pxd(1 hunks)src/pyOpenMS/pxds/PeptideSearchEngineFIAlgorithm.pxd(2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/openms/**/*.{cpp,h,hpp,cc,cxx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms
Files:
src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp
🧠 Learnings (9)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Applied to files:
src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cppsrc/pyOpenMS/pxds/OpenSearchModificationAnalysis.pxd
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/include/OpenMS/**/*.h : Add Doxygen comments for new public methods and classes
Applied to files:
src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cppsrc/pyOpenMS/pxds/OpenSearchModificationAnalysis.pxd
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/**/*.h : Add Doxygen comments for new public methods and classes in pyOpenMS bindings
Applied to files:
src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cppsrc/pyOpenMS/pxds/PeptideSearchEngineFIAlgorithm.pxdsrc/pyOpenMS/pxds/OpenSearchModificationAnalysis.pxd
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/**/*.cpp : Write unit tests for new functionality
Applied to files:
src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp
📚 Learning: 2025-08-29T19:09:45.997Z
Learnt from: jcharkow
Repo: OpenMS/OpenMS PR: 8188
File: src/topp/OpenSwathWorkflow.cpp:1118-1123
Timestamp: 2025-08-29T19:09:45.997Z
Learning: In OpenMS OpenSwathWorkflow, the use_ms1_ion_mobility parameter should be respected when applying estimated MS1 ion mobility extraction windows. The apply_window calls for MS1 ion mobility should check both pasef AND use_ms1_ion_mobility to avoid re-enabling disabled functionality.
Applied to files:
src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp
📚 Learning: 2025-06-16T15:48:09.667Z
Learnt from: FreezB11
Repo: OpenMS/OpenMS PR: 7969
File: src/pyOpenMS/pxds/TMTThirtyTwoPlexQuantitationMethod.pxd:4-4
Timestamp: 2025-06-16T15:48:09.667Z
Learning: In OpenMS .pxd files, the established pattern for extern from statements is to include angle brackets inside the string literal, like `cdef extern from "<OpenMS/PATH/TO/FILE.h>" namespace "OpenMS":`. This is consistent across all existing quantitation method .pxd files and other .pxd files in the OpenMS codebase.
Applied to files:
src/pyOpenMS/pxds/OpenSearchModificationAnalysis.pxd
📚 Learning: 2025-11-18T20:08:08.900Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8374
File: src/pyOpenMS/pxds/SimpleSVM.pxd:0-0
Timestamp: 2025-11-18T20:08:08.900Z
Learning: In pyOpenMS .pxd files, copy constructors should be declared for wrapped C++ classes (e.g., `ClassName(ClassName&) except + nogil`) even when the C++ class has a deleted copy constructor. This is a standard pyOpenMS/Cython convention required for proper wrapper generation and Python object semantics.
Applied to files:
src/pyOpenMS/pxds/OpenSearchModificationAnalysis.pxd
📚 Learning: 2025-06-16T15:49:26.504Z
Learnt from: FreezB11
Repo: OpenMS/OpenMS PR: 7969
File: src/pyOpenMS/pxds/TMTThirtyTwoPlexQuantitationMethod.pxd:1-3
Timestamp: 2025-06-16T15:49:26.504Z
Learning: In OpenMS Python bindings (.pxd files), derived quantitation method classes like TMTThirtyTwoPlexQuantitationMethod only need to declare their constructors. All other public methods (getName, getChannelInformation, getNumberOfChannels, getIsotopeCorrectionMatrix, getReferenceChannel) are inherited from the base IsobaricQuantitationMethod class and don't need to be redeclared explicitly.
Applied to files:
src/pyOpenMS/pxds/OpenSearchModificationAnalysis.pxd
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/tests/**/*.py : Write pyOpenMS tests for new Python bindings
Applied to files:
src/pyOpenMS/pxds/OpenSearchModificationAnalysis.pxd
🧬 Code graph analysis (1)
src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp (1)
src/topp/SageAdapter.cpp (2)
mod(191-216)mod(191-191)
🪛 GitHub Check: CodeFactor
src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp
[notice] 665-790: src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp#L665-L790
Complex Method
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
- GitHub Check: build-lnx
- GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
- GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
- GitHub Check: build-and-test (ubuntu-22.04-arm, g++, 11)
- GitHub Check: build-win
- GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
- GitHub Check: cppcheck-test
🔇 Additional comments (12)
src/pyOpenMS/pxds/PeptideSearchEngineFIAlgorithm.pxd (4)
1-8: LGTM - Import statements are correct.The imports correctly include the new
OpenSearchModificationAnalysisdependency needed for theSearchResultstruct'smodification_analysisfield.
28-43: Good documentation with practical code example.The wrap-doc includes a clear, runnable Python example demonstrating the new open search modification discovery workflow. This will help users understand the new API.
64-86: New method signature looks correct.The
searchWithModificationAnalysismethod signature properly exposes the new functionality with appropriate parameters and return type. The documentation clearly explains the automatic behaviors (open search detection, statistics generation, TSV output).
97-114: SearchResult struct binding is well-structured.The struct correctly exposes all necessary fields including the new
modification_analysisresult, and follows the pyOpenMS convention withwrap-attachand constructors withexcept + nogil.src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp (3)
522-560: Well-structured orchestrating method.The
analyzeModificationsWithStatisticsmethod cleanly coordinates the analysis workflow: delta mass pattern analysis → modification mapping → statistics generation → optional file output. The base name extraction logic correctly handles both.idXMLand.idxmlsuffixes.
562-682: ppm tolerance handling is now correctly implemented.The previous review comment about unused
precursor_mass_tolerance_unit_ppmhas been addressed. The implementation correctly:
- Computes
tolerance_dabased on the unit (lines 622-629)- Uses per-comparison tolerance in the modification lookup loop (lines 638-644)
- Handles edge cases near zero mass with
min_mass_for_ppm(line 571)
684-692: Unused parameters are intentionally kept for API consistency.The comment at lines 689-691 adequately explains why
precursor_mass_toleranceandprecursor_mass_tolerance_unit_ppmare part of the signature but unused. This is acceptable for API consistency since tolerance is already applied during PTM annotation.src/pyOpenMS/pxds/OpenSearchModificationAnalysis.pxd (5)
1-7: LGTM - Standard imports for pyOpenMS binding.The imports correctly include all necessary Cython/libcpp types needed for the binding declarations.
8-50: Excellent documentation with practical example.The wrap-doc provides comprehensive documentation including:
- Clear description of the class purpose
- Explanation of the two statistics table types
- Complete working Python code example
This follows the pyOpenMS best practices for documentation.
52-56: Good use of wrap-ignore for unsupported types.The comments clearly explain why
analyzeDeltaMassPatternsandmapDeltaMassesToModificationscannot be exposed to Python (custom comparator types not supported by autowrap). This is helpful for future maintainers.
99-109: Method signature matches C++ implementation.The
analyzeResidueFrequencybinding correctly exposes the method with the appropriate return type (libcpp_map[char, int]).
130-226: Nested struct bindings are complete and well-documented.All data structures are properly bound with:
- Correct
wrap-attachdirectives linking to parent class- Field declarations matching C++ definitions
- Default and copy constructors with
except + nogil- Appropriate
wrap-doccomments where helpfulThe bindings cover the complete API surface needed for Python users.
fcdbdb9 to
daae99a
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Fix all issues with AI agents
In `@src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp`:
- Around line 800-853: The log uses sticky manipulators
(std::fixed/std::setprecision) on the global OPENMS_LOG_INFO stream which
corrupts later logging; fix by formatting each table row into a local
std::ostringstream (apply std::fixed and std::setprecision to that ostringstream
only) for both the PTM loop that iterates ptm_stats.entries and the
unknown-delta-mass loop over unknown_dm/dm_stats.entries, then output
ostringstream.str() to OPENMS_LOG_INFO so the global stream flags remain
unchanged.
In `@src/pyOpenMS/pxds/OpenSearchModificationAnalysis.pxd`:
- Around line 169-187: The PTMEntry binding exposes num_charge_states but
generatePTMStatistics() never sets it; update the binding to avoid misleading
users by either removing the num_charge_states member from the
OpenSearchModificationAnalysis_PTMEntry definition or adding a clear wrap-doc
note on OpenSearchModificationAnalysis_PTMEntry and/or generatePTMStatistics()
stating that num_charge_states is currently unset/approximate. Locate the
OpenSearchModificationAnalysis_PTMEntry cppclass in the .pxd (the String name,
double theoretical_mass... int num_charge_states fields) and either delete the
num_charge_states line or prepend/extend the wrap-doc block to explicitly
document that num_charge_states is not populated by generatePTMStatistics().
- Around line 99-109: The analyzeResidueFrequency method returns
libcpp_map[char, int], which autowrap can't handle; either add a "# wrap-ignore"
directive to the analyzeResidueFrequency declaration so the method is skipped by
the wrapper, or add a custom converter for libcpp_map[char, int] in
special_autowrap_conversionproviders.py (modeled on CVTermMapConverter) and
register it so analyzeResidueFrequency can be wrapped; reference the
analyzeResidueFrequency signature and libcpp_map[char, int] when making the
change.
🧹 Nitpick comments (4)
src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp (3)
597-662:countUniquePeptides_called per histogram entry creates an O(H × N) bottleneck.Line 632 invokes
countUniquePeptides_for every histogram entry, each time scanning all peptide hits. For large open-search datasets (e.g., 1000 bins × 100k PSMs = 100M iterations), this becomes a significant bottleneck.Consider pre-computing a single-pass grouping of unique sequences by their rounded delta-mass bin, then looking up the size for each entry inside the loop.
Sketch of single-pass approach
+ // Pre-compute unique peptide sets per histogram bin in a single pass over peptide_ids + std::unordered_map<int, std::unordered_set<std::string>> unique_pep_per_bin; + constexpr double bin_tolerance = 0.0005; + for (const auto& peptide_id : peptide_ids) + { + for (const auto& hit : peptide_id.getHits()) + { + if (!hit.metaValueExists("DeltaMass")) continue; + double dm = hit.getMetaValue("DeltaMass"); + if (std::abs(dm) <= delta_mass_zero_threshold) continue; + int bin_key = static_cast<int>(std::round(dm / bin_tolerance)); + unique_pep_per_bin[bin_key].insert(hit.getSequence().toString()); + } + } + // Convert histogram to entries for (const auto& [delta_mass, count] : histogram) { // ... existing entry setup ... - // Count unique peptides - entry.unique_peptides = countUniquePeptides_(peptide_ids, delta_mass, tolerance_da); + // Look up pre-computed unique peptide count + int bin_key = static_cast<int>(std::round(delta_mass / bin_tolerance)); + auto it = unique_pep_per_bin.find(bin_key); + entry.unique_peptides = (it != unique_pep_per_bin.end()) ? static_cast<int>(it->second.size()) : 0;Based on learnings: "Consider algorithmic complexity for data processing operations"
762-775: Running average is numerically fragile for large counts.The incremental mean formula
(old_mean * (n-1) + x) / ncan accumulate rounding error ascountgrows. The equivalent Welford-style update is more stable and avoids a large intermediate product.Suggested change
- entry.observed_mass = ((entry.observed_mass * (entry.count - 1)) + obs_mass) / entry.count; + entry.observed_mass += (obs_mass - entry.observed_mass) / entry.count;
942-985:getTargetResidues_will silently return empty for composite PTM names.When
mapDeltaMassesToModificationscreates composite names like"Oxidation//Phospho"or"Oxidation++Phospho",getModification()at line 949 will throw (caught silently). This meanstarget_residueswill be empty for any composite PTM, which could be confusing in the PTMStats output.Consider logging a debug-level message inside the catch block so users investigating missing residue data have a breadcrumb.
Suggested change
catch (const Exception::BaseException&) { - // Modification not found in database + // Modification not found in database — expected for composite PTM names + OPENMS_LOG_DEBUG << "Could not resolve target residues for: " << mod_name << "\n"; }src/openms/source/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.cpp (1)
746-776: Double modification analysis:search()already runsanalyzeModifications(), thensearchWithModificationAnalysis()re-runs the full analysis.
search()(called at line 746) internally invokesanalyzeModifications()at line 688 when in open-search mode — building the histogram, mapping modifications, annotating peptide hits with "PTM" meta values, and writing an_OutputTable.tsvnext to the input database. ThenanalyzeModificationsWithStatistics()at line 770 repeats the histogram build and modification mapping (adding another_OutputTable.tsvat theoutput_base_namelocation) before generating the new statistics.This duplicates O(N) work and produces a spurious OutputTable file at the database path.
Consider adding a flag to
search()to skip the mod analysis when called fromsearchWithModificationAnalysis(), or refactoringsearch()to never perform mod analysis (leaving it to the caller).
b5eb19f to
bb45f44
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp`:
- Around line 917-940: The buildModificationMassLookup_ function constructs
mass_to_mod with FuzzyDoubleComparator(1e-6) which differs from the epsilon used
in mapDeltaMassesToModifications (FuzzyDoubleComparator(1e-9)); change
buildModificationMassLookup_ to use the same epsilon (1e-9) or, better,
introduce a shared constant (e.g., static constexpr double FUZZY_EPSILON = 1e-9)
and use that in both buildModificationMassLookup_ and
mapDeltaMassesToModifications to ensure consistent binning for modification
masses (update references to FuzzyDoubleComparator to use the shared constant).
- Around line 942-985: getTargetResidues_ currently calls
ModificationsDB::getModification(mod_name) once and swallows exceptions for
compound PTM names (e.g. "Oxidation//Deamidated" or "Oxidation+1Da"); change
getTargetResidues_ so it first splits the incoming mod_name on known compound
separators ("//" and "++" — also handle plain "+" variants if produced by
mapDeltaMassesToModifications), then iterate over each token: for each token
call ModificationsDB::getModification(token) and apply the existing
origin/term-specificity logic to build a result (accumulate or pick the first
non-empty target-residues string), and only if no token resolves emit a LOG_WARN
(or processLogger.warn) explaining the missing mapping for the original
mod_name; keep using the same symbols (getTargetResidues_,
ModificationsDB::getInstance(), getModification(), getOrigin(),
getTermSpecificity()) so the change is local and preserves current behavior for
single-name inputs.
🧹 Nitpick comments (4)
src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp (4)
597-632: Performance:countUniquePeptides_called per histogram bin scans all PSMs each time.Inside the histogram loop (line 602),
countUniquePeptides_(line 632) iterates over every peptide identification for each delta-mass bin. This is O(H × N) where H = number of histogram bins and N = total number of PSM hits. For large open-search result sets, this can become a bottleneck.Consider building a single index (e.g., a map from rounded delta mass → set of unique sequences) in one pass over all PSMs, then looking up counts per bin.
Sketch
+ // Pre-compute unique peptide counts per delta mass bin in one pass + std::unordered_map<double, std::unordered_set<std::string>> unique_peps_by_dm; + for (const auto& peptide_id : peptide_ids) + { + for (const auto& hit : peptide_id.getHits()) + { + if (!hit.metaValueExists("DeltaMass")) continue; + double dm = hit.getMetaValue("DeltaMass"); + // match to nearest histogram bin within tolerance + for (const auto& [bin_dm, _] : histogram) + { + double tol = /* compute tolerance_da for bin_dm */; + if (std::abs(dm - bin_dm) <= tol) + { + unique_peps_by_dm[bin_dm].insert(hit.getSequence().toString()); + break; + } + } + } + } // Then in the loop: - entry.unique_peptides = countUniquePeptides_(peptide_ids, delta_mass, tolerance_da); + auto it = unique_peps_by_dm.find(delta_mass); + entry.unique_peptides = (it != unique_peps_by_dm.end()) ? static_cast<int>(it->second.size()) : 0;
574-574:buildModificationMassLookup_()is called twice per analysis run.
analyzeModificationsWithStatisticscallsgenerateDeltaMassStatistics(line 542) andgeneratePTMStatistics(line 545), each of which independently callsbuildModificationMassLookup_()(lines 574, 700). This duplicates the full iteration overModificationsDB. Consider building the lookup once and passing it as a parameter.Also applies to: 700-700
844-844: Use"\n"instead ofstd::endlin log macros.As per coding guidelines: "Avoid
std::endl; prefer\nfor better performance in logging and output operations."Example fix
- OPENMS_LOG_ERROR << "Error opening file: " << output_file << std::endl; + OPENMS_LOG_ERROR << "Error opening file: " << output_file << "\n";Also applies to: 870-870, 879-879, 914-914
762-774: Residue frequency counts all residues in matching peptides, not just the modified site.The loop at lines 770-774 counts every amino acid in each peptide sequence that carries the PTM. This gives a global residue frequency (useful for enrichment analysis) but may be misinterpreted as "which residue is modified." The TSV column header "ResidueFrequency" (line 889) is suitably neutral, but a brief code comment clarifying this is a background frequency for enrichment analysis would help future readers.
| String OpenSearchModificationAnalysis::getTargetResidues_(const String& mod_name) const | ||
| { | ||
| String result; | ||
|
|
||
| try | ||
| { | ||
| ModificationsDB* mod_db = ModificationsDB::getInstance(); | ||
| const ResidueModification* mod = mod_db->getModification(mod_name); | ||
|
|
||
| if (mod != nullptr) | ||
| { | ||
| String origin = mod->getOrigin(); | ||
| if (!origin.empty() && origin != "X") | ||
| { | ||
| result = origin; | ||
| } | ||
|
|
||
| // Also check term specificity | ||
| auto term_spec = mod->getTermSpecificity(); | ||
| if (term_spec == ResidueModification::N_TERM) | ||
| { | ||
| result = "N-term" + (result.empty() ? "" : "(" + result + ")"); | ||
| } | ||
| else if (term_spec == ResidueModification::C_TERM) | ||
| { | ||
| result = "C-term" + (result.empty() ? "" : "(" + result + ")"); | ||
| } | ||
| else if (term_spec == ResidueModification::PROTEIN_N_TERM) | ||
| { | ||
| result = "Protein N-term" + (result.empty() ? "" : "(" + result + ")"); | ||
| } | ||
| else if (term_spec == ResidueModification::PROTEIN_C_TERM) | ||
| { | ||
| result = "Protein C-term" + (result.empty() ? "" : "(" + result + ")"); | ||
| } | ||
| } | ||
| } | ||
| catch (const Exception::BaseException&) | ||
| { | ||
| // Modification not found in database | ||
| } | ||
|
|
||
| return result; | ||
| } |
There was a problem hiding this comment.
getTargetResidues_ may fail silently for compound PTM names.
getModification(mod_name) at line 949 receives the full name stored in the "PTM" meta value. For compound names like "Oxidation//Deamidated" or "Oxidation+1Da" (produced by mapDeltaMassesToModifications), the DB lookup will throw and the catch block silently returns an empty string. This means target_residues will be blank for all ambiguous or isotope-shifted mappings.
At minimum, consider splitting compound names (on "//" and "++") and resolving each part separately, or adding a log warning so users understand why target residues are missing.
🤖 Prompt for AI Agents
In `@src/openms/source/ANALYSIS/ID/OpenSearchModificationAnalysis.cpp` around
lines 942 - 985, getTargetResidues_ currently calls
ModificationsDB::getModification(mod_name) once and swallows exceptions for
compound PTM names (e.g. "Oxidation//Deamidated" or "Oxidation+1Da"); change
getTargetResidues_ so it first splits the incoming mod_name on known compound
separators ("//" and "++" — also handle plain "+" variants if produced by
mapDeltaMassesToModifications), then iterate over each token: for each token
call ModificationsDB::getModification(token) and apply the existing
origin/term-specificity logic to build a result (accumulate or pick the first
non-empty target-residues string), and only if no token resolves emit a LOG_WARN
(or processLogger.warn) explaining the missing mapping for the original
mod_name; keep using the same symbols (getTargetResidues_,
ModificationsDB::getInstance(), getModification(), getOrigin(),
getTermSpecificity()) so the change is local and preserves current behavior for
single-name inputs.
This commit enhances the fragment index-based search algorithm with comprehensive modification discovery capabilities: New Data Structures in OpenSearchModificationAnalysis: - DeltaMassEntry: Statistics for delta mass histogram bins - PTMEntry: Mapped PTM statistics with residue localization - DeltaMassStatistics: Container for delta mass table - PTMStatistics: Container for PTM table with residue analysis - OpenSearchAnalysisResult: Combined result structure New Methods: - analyzeModificationsWithStatistics(): Main entry point for modification discovery, returns structured statistics tables - generateDeltaMassStatistics(): Generates delta mass histogram table - generatePTMStatistics(): Generates PTM table with residue analysis - analyzeResidueFrequency(): Analyzes amino acid frequencies per delta mass - writeDeltaMassStatistics(): Writes delta mass TSV output - writePTMStatistics(): Writes PTM TSV output - Helper methods for modification database lookup PeptideSearchEngineFIAlgorithm enhancements: - New SearchResult struct with modification analysis results - New searchWithModificationAnalysis() method that returns comprehensive results including PTM and delta mass tables - Enhanced logging with formatted tables of top PTMs and unknown delta masses for potential novel modification discovery The modification analysis functionality is factored out into OpenSearchModificationAnalysis class following DRY principles, allowing both SageAdapter and the FI algorithm to share the code. Output files generated: - *_DeltaMassStats.tsv: Delta mass histogram with mapping status - *_PTMStats.tsv: Mapped PTMs with residue frequency analysis
Add pyOpenMS wrappers for the new modification analysis functionality: OpenSearchModificationAnalysis.pxd: - Full Python binding for OpenSearchModificationAnalysis class - Wrapped all new structs: DeltaMassEntry, PTMEntry, DeltaMassStatistics, PTMStatistics, OpenSearchAnalysisResult - Wrapped all analysis methods including analyzeModificationsWithStatistics() - Added comprehensive docstrings with usage examples PeptideSearchEngineFIAlgorithm.pxd: - Added import for OpenSearchModificationAnalysis - Added SearchResult struct wrapping - Added searchWithModificationAnalysis() method binding - Updated documentation with open search modification discovery example Both classes now provide complete Python API access for: - Delta mass histogram analysis - PTM mapping to known modifications - Residue frequency analysis for localization - Structured statistics tables for modification discovery
- Fix unused parameter warning for precursor_mass_tolerance_unit_ppm - When unit is ppm, compute tolerance_da dynamically based on the reference mass (delta_mass or mod_mass) using: mass * ppm * 1e-6 - Use minimum reference mass of 0.1 Da to avoid issues near zero - Add explanatory comment for generatePTMStatistics where tolerance parameters are part of API but not used (PTM annotations already assigned by mapDeltaMassesToModifications)
- Remove methods that take/return histogram types with custom FuzzyDoubleComparator (analyzeDeltaMassPatterns, mapDeltaMassesToModifications, generateDeltaMassStatistics, generatePTMStatistics) as these cannot be wrapped by autowrap - Remove 'const' from String& parameters which can cause autowrap issues - Remove problematic ctypedef aliases for histogram types - Keep main entry points: analyzeModifications, analyzeModificationsWithStatistics, analyzeResidueFrequency, writeDeltaMassStatistics, writePTMStatistics - All struct types remain accessible from Python
Revert search() to use analyzeModifications() instead of analyzeModificationsWithStatistics(), restoring original behavior for existing callers. The detailed statistics are now only produced by the new searchWithModificationAnalysis() method as intended. Also: remove duplicate Doxygen block, narrow bare catch(...) to Exception::BaseException, add missing trailing newlines, and document the intentional double-analysis in searchWithModificationAnalysis(). Co-Authored-By: Claude Opus 4.6 <[email protected]>
The log messages in searchWithModificationAnalysis were missing the "_ModificationAnalysis" infix, showing incorrect output file paths. The actual files are written with the infix since output_file is built as output_base_name + "_ModificationAnalysis.idXML". Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Remove unused `delta_mass` variable in generatePTMStatistics() that MSVC treats as error (/we4189), merging the redundant DeltaMass block into the existing one above - Remove `libcpp_map[char, int] residue_counts` from PTMEntry .pxd declaration as autowrap cannot handle char as a map key in struct members. Per-residue counts remain accessible via the analyzeResidueFrequency() method. - Remove `wrap-attach` directives from all nested struct types in OpenSearchModificationAnalysis.pxd and PeptideSearchEngineFIAlgorithm.pxd. Autowrap generates `__`-prefixed class names for wrap-attach types but references them without the prefix, causing "undeclared name" Cython errors. Without wrap-attach, types become module-level classes (matching the FLASHHelperClasses pattern that works correctly). Co-Authored-By: Claude Opus 4.6 <[email protected]>
The Cython definition file used PeptideIdentificationList as a parameter type but only imported PeptideIdentification, causing 6 compile errors on the GCC 13 CI builds (which run the autowrap/Cython path). Co-Authored-By: Claude Opus 4.6 <[email protected]>
…analysis - Use std::ostringstream for formatted log table rows to avoid sticky std::fixed/std::setprecision flags corrupting the global log stream - Fix FuzzyDoubleComparator epsilon inconsistency between buildModificationMassLookup_ (was 1e-6) and mapDeltaMassesToModifications (1e-9) by using the default epsilon in both - Handle compound PTM names (e.g. "Oxidation//Deamidated", "Oxidation+1Da") in getTargetResidues_ by splitting and resolving each part, with LOG_WARN on unresolvable names - Implement PTMEntry::num_charge_states tracking (was always 0) using per-PTM unique charge state sets Co-Authored-By: Claude Opus 4.6 <[email protected]>
2e525de to
5dd883f
Compare
…very tests Add in-memory search() and searchWithModificationAnalysis() overloads to PeptideSearchEngineFIAlgorithm that accept PeakMap + vector<FASTAEntry> directly, enabling efficient testing without file I/O. Refactor file-based methods to delegate to in-memory versions. Add comprehensive C++ and Python tests that generate ~4500 synthetic MS/MS spectra with 12 known modification mass shifts, run open search, and verify all delta mass bins are correctly discovered with high counts. Co-Authored-By: Claude Opus 4.6 <[email protected]>
… search
mapDeltaMassesToModifications() and generateDeltaMassStatistics() were using
the search precursor tolerance (e.g. 500 Da in open search) for matching
delta masses to known modifications. This caused every delta mass to match
the first modification found in the database ("Loss of arginine due to
transpeptidation") regardless of the actual mass shift.
Fix: use a narrow fixed tolerance (0.02 Da) for modification database lookup,
0.5 Da for cluster assignment / PSM annotation, and 0.05 Da for the near-zero
mass filter. These tolerances are intrinsic to the mapping step and must not
depend on the search precursor tolerance.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Use min(caller_tolerance, 0.02 Da) instead of raw precursor tolerance for mapping delta masses to known modifications. This prevents overly broad matching in open search mode (500 Da tolerance) while preserving SageAdapter's intentional 0.01 Da tolerance. Also fix pre-existing bug where unknown modifications were suppressed by a zero-threshold check on the unmatched mod_mass (which stayed 0.0). Add test coverage for artificial unknown delta mass (123.456 Da) in both C++ and Python tests. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…rkflow Demonstrate two quality-filtering paths before modification analysis using existing OpenMS classes (FalseDiscoveryRate, IDFilter, OpenSearchModificationAnalysis): FDR-based filtering with target-decoy search, and score-based filtering on raw ln(hyperscore). Both C++ and Python tests verify modifications survive filtering. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Summary
Enhances the fragment index-based peptide search engine with comprehensive open-search modification discovery capabilities and demonstrates quality filtering workflows using existing OpenMS classes.
Modification Discovery Engine (
OpenSearchModificationAnalysis)ModificationsDBwith capped toleranceDeltaMassEntry,PTMEntry,DeltaMassStatistics,PTMStatistics,OpenSearchAnalysisResultwriteDeltaMassStatistics()andwritePTMStatistics()for downstream analysisSearch Engine Enhancements (
PeptideSearchEngineFIAlgorithm)search(MSExperiment, FASTAEntries, ...)andsearchWithModificationAnalysis()for programmatic use without file I/OSearchResultstruct: Bundles exit code, open-search flag, peptide IDs, protein IDs, and modification analysis in one return valueFDR and Score Filtering Workflows (tests only, no new C++ code)
decoys=true→FalseDiscoveryRate::apply()→IDFilter::filterHitsByScore()at 5% FDR →removeDecoyHits→ standaloneOpenSearchModificationAnalysisIDFilter::filterHitsByScore()on raw ln(hyperscore) → standalone modification analysisPython Bindings
.pxdbindings for all new classes and result typesTest plan
PeptideSearchEngineFIAlgorithm_test(8 sections all pass)OpenSearchModificationAnalysis_test(passes)test_modification_discovery.py(5 tests, all pass)🤖 Generated with Claude Code