Skip to content

Store protein group quantities in consensusXML - #9844

Merged
timosachsenberg merged 9 commits into
developfrom
claude/protein-quantities-xml-export-iaag7w
Aug 3, 2026
Merged

timosachsenberg merged 9 commits into
developfrom
claude/protein-quantities-xml-export-iaag7w

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR adds support for storing and loading protein group quantification data (abundances, PSM counts, file/channel information) in consensusXML files. Previously, the data arrays attached to protein groups by PeptideAndProteinQuant::annotateQuantificationsToProteins() were silently dropped when writing to XML, causing protein abundance information to be lost in round-trip operations.

Key Changes

ConsensusXMLHandler.cpp

  • Added ProteinGroupQuant helper struct that encodes/decodes protein group data arrays as typed UserParam metavalues
  • Data arrays are stored with names like indistinguishable_proteins_0_abundances, indistinguishable_proteins_0_file_channel_level_abundance, etc.
  • Implements redundancy detection to skip all-zero arrays (psm_count, distinct_peptides) that can be reconstructed on load
  • Adds ownership tracking via _quantified_proteins suffix to detect when quantities belong to a different set of proteins (e.g., after group filtering)
  • Restores canonical array ordering on load to maintain compatibility with downstream consumers (MzTab, ProteinGroupArrowExport)

PeptideAndProteinQuant.cpp

  • Fixed normalization to handle channels with mostly undetected reporters by computing medians only over detected (non-zero) values
  • Updated parameter documentation for consensus:normalize

IDFilter.cpp

  • Preserves data arrays when filtering proteins from groups

StringUtils.cpp

  • Fixed handling of non-finite values (inf, -inf, NaN) in string conversion to prevent malformed XML

ProteinIdentification.cpp

  • Updated equality operator to include data arrays in comparison

Test Coverage

  • Added comprehensive round-trip test in ConsensusXMLFile_test.cpp verifying data array preservation and canonical ordering
  • Added test for ownership validation (quantities with mismatched proteins are discarded)
  • Added normalization test for sparse channels in PeptideAndProteinQuant_test.cpp
  • Added test for data array preservation in IDFilter_test.cpp
  • Updated reference files for ProteomicsLFQ and IsobaricWorkflow tests with new quantity data
  • All existing tests pass

Backward Compatibility

  • No schema changes required; uses existing unbounded UserParam elements
  • Older readers will load files without the quantity data but remain functional
  • Files are still schema-valid

Checklist

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

https://claude.ai/code/session_01XLHJSH5hvWj559Uak2WTGP

Summary by CodeRabbit

  • New Features

    • Protein-group quantitative data is now preserved when saving and loading ConsensusXML files.
    • Filtering protein groups retains associated quantitative values.
    • Protein-group comparisons include attached quantitative data.
  • Bug Fixes

    • Improved median normalization for partially observed or signal-free samples.
    • Samples without positive measurements retain their values safely.
    • Infinity values are serialized correctly as inf and -inf.
  • Tests

    • Added coverage for quantitative data, normalization edge cases, special floating-point values, and isobaric workflows.

claude added 8 commits August 1, 2026 14:51
PeptideAndProteinQuant attaches protein abundances to the data arrays of
ProteinIdentification::ProteinGroup, but those arrays had no representation in
consensusXML. addProteinGroups_() wrote only "probability,PH_0,PH_1" per group,
so ProteomicsLFQ -out_cxml and IsobaricWorkflow -out silently dropped every
quantity. The symptom: MzTabExporter on a stored consensusXML produced no
protein abundances at all, while the same map exported straight from memory did.

Each non-empty data array is now written as one typed UserParam list beside the
group it belongs to and restored into the same positional layout on load, which
MzTab (float[0] == "abundances") and ProteinGroupArrowExport (float[3], string[0],
integer[0]) rely on. Arrays that are empty or all-zero are skipped: "psm_count"
and "distinct_peptides" are resized but never filled upstream, so writing them
would only add columns of zeros. The check is on the values, so they start being
written by themselves once that is fixed.

No schema change was needed - UserParam is already unbounded inside
ProteinIdentificationType and intList/floatList/stringList are already valid
UserParam types, so older OpenMS versions still read the files. Groups without
quantities produce no additional output, so the 37 reference files with protein
groups from other tools are byte-identical; only the 12 ProteomicsLFQ ones gain
lines.

Because the group index is part of the key, a tool that renumbers groups without
knowing these params would leave them pointing at the wrong group. Each quantified
group therefore also records the protein hits its quantities were computed for;
on load a mismatch discards the quantities with a warning instead of
mis-attributing them, and both the reader and the writer strip stale entries.

Two fixes the export depends on:

- IDFilter::updateProteinGroups() rebuilt each group copying only accessions and
  probability, discarding the data arrays. Every tool that filters after
  quantification - Epifany, ProteinInference, FalseDiscoveryRate,
  PercolatorAdapter, ProteomicsLFQ itself - therefore threw the quantities away.
  They are indexed by sample resp. by (file, channel), so removing a protein from
  a group does not invalidate them.

- ProteinGroup::operator== compared only probability and accessions, so a
  store/load round-trip test passed even when every array had been dropped.

Tests: IsobaricWorkflow had no TOPP test at all (the block was commented out) and
is the maximal-exposure path, since remove_unquantified=true means every
surviving group carries arrays; added one on the existing TMT-10plex data. Plus
two ConsensusXMLFile sections: a full round-trip of all array kinds, and a check
that groups without quantities are written unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XLHJSH5hvWj559Uak2WTGP
Two problems with the encoding added in the previous commit, both reproduced before fixing.

Skipping all-zero arrays discarded their LENGTH, which the reader cannot reconstruct.
isRedundant() dropped any all-zero numeric array, so a protein quantified as zero everywhere came
back with a zero-length "abundances" instead of one zero per sample. That is not a cosmetic
difference: MzTab::getQuantStudyVariables_ takes getFloatDataArrays()[0].size() from whichever group
it sees last, so a single such group reports "no quantities" for the entire mzTab file, and
ProteinGroupArrowExport bounds-checks its lockstep loop against the same array and silently omits the
group's row. The same applied to file_channel_level_abundance, whose two lockstep partners (filenames,
channels) were still written. The skip is now restricted to "psm_count" and "distinct_peptides" - the
only arrays whose length can be recovered on load, since both are as long as "abundances", and the
only ones that are structurally all-zero (PeptideData::psm_counts is never written upstream). It is
still a value check, so they start being written by themselves once that is fixed.

The renumbering guard could not detect the renumbering it exists for. It recorded the group's
"PH_<n>" references, but those are positional indices into the protein hit list, reassigned on every
store. Dropping a leading protein hit together with its group shifts the PH_ numbers and the group
indices by the same amount, so a stale entry for old group N compares equal to new group N and its
quantities were attributed to a different protein - exactly the silent mis-attribution the guard was
added to prevent. It now records accessions, which are stable under both renumberings.

Tests: the guard had no coverage at all, so its discard path is now exercised, including an assertion
that the recorded value is an accession rather than a PH_ reference. Added a round-trip over a group
quantified as zero everywhere.

The 13 reference files change only in their "_quantified_proteins" lines (85 of them), which now hold
accessions; no other line moves.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XLHJSH5hvWj559Uak2WTGP
getQuantMetaValues() was called once per protein group and each call enumerated the whole
ProteinIdentification's metavalue list and erased its entries one at a time. MetaInfoInterface is
backed by a flat_map, so every erase memmoves the tail and every enumeration allocates one std::string
per metavalue; with ~8 metavalues per quantified group that is quadratic in the group count.

Measured on synthetic maps of single-protein quantified groups (store + load, release build):

     groups   before    after    without quantities (pre-feature baseline)
       1000    346 ms    35 ms     12 ms
       2000   1317 ms    77 ms     32 ms
       4000   6444 ms   180 ms     67 ms

i.e. 4x per doubling before, 2x after. A proteome-scale run would have been unusable.

The entries this encoding owns are now moved off the ProteinIdentification in a single pass and the
per-group lookups run against that map, whose ordering makes each group's entries a contiguous range.
Whatever is left over at the end belonged to a group whose base entry is gone; it is simply not
written back, which also replaces the separate cleanup pass.

Also skips the ownership record when harvesting a group's arrays - it is itself a stringList, so
collecting it turned it into a third string data array.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XLHJSH5hvWj559Uak2WTGP
…parsable "inf.0"

appendNumeric() special-cased NaN but not the infinities. std::to_chars writes "inf", a token with
neither '.' nor 'e', so the "keep at least one digit after the decimal point" rule - the one that
makes 5 print as 5.0 - appended ".0" and produced "inf.0". Nothing can read that back: any file
carrying an infinity stored without complaint and then failed to load in full, with a
ConversionError naming a string OpenMS had written itself.

Only the writing side was ever wrong. std::from_chars already accepts "inf", "-inf" and even
"Infinity", so toDouble()/toFloat() need no change and the new output round-trips as it stands.
The branch is an early return, so no finite value reaches different code than before, and nothing
downstream can have depended on "inf.0" because nothing could parse it. No reference file changes.

Reachable today from IsobaricWorkflow/ProteomicsLFQ: PeptideAndProteinQuant::normalizePeptides_
divides by a sample's median peptide abundance without guarding it, so a channel whose median is 0
but which still has positive peptides scales that sample to +inf, which
annotateQuantificationsToProteins then stores on the protein groups. A fully dead channel gives
0/0 = NaN instead, and NaN always round-tripped - which is why only some of these runs broke.
(The unguarded division is left alone here: what normalization should do with a zero median is a
separate question from being able to write the number down.)

Found while reviewing the protein-group quantity export, which is what first put these values in a
file. Repro, previously fatal on load, now clean through MzTabExporter:
  IsobaricWorkflow -type tmt10plex -in TMTTenPlexMethod_test.mzML -in_id IsobaricWorkflow_1_input.idXML
    -exp_design IsobaricWorkflow_1_design.tsv -ProteinQuantification:consensus:normalize
    -ProteinQuantification:top:N 1 -extraction:min_reporter_intensity 12000 -out out.consensusXML

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XLHJSH5hvWj559Uak2WTGP
…n normalization

normalizePeptides_ scales every sample so that its median peptide abundance matches the overall
median. It counted zero abundances as measurements. For isobaric data a zero is not a measurement:
IsobaricChannelExtractor initialises each channel to 0 and leaves it there when no reporter peak is
found (IsobaricChannelExtractor.cpp:619), and zeroes anything below 'min_reporter_intensity' (:656).
A zero means "not detected".

Since a median is 0 as soon as more than half the values are, a channel in which most peptides went
undetected - which does not require the channel to be empty - got median 0, and
'overall_median / median' then scaled every abundance in it to infinity (or to NaN where the abundance
was itself zero). Since the previous commits let protein quantities reach consensusXML, that produced
a file that could not be read back at all.

Zeros are now left out of the per-channel median, so such a channel is normalized on the data it does
have. This is what MSstatsTMT, isobar, scp and DEqMS all do - zeros to NA, median with na.rm=TRUE -
and it is the convention rather than the log-vs-linear space: isobar and scp divide in linear space
exactly as OpenMS does and are safe purely because zeros never reach the statistic.

Two further problems in the same function, both silent:

- A channel with no signal contributed its median of 0 to the reference, dragging the overall median
  down and mis-scaling every OTHER channel. No infinity, no warning, just wrong numbers - and it hit
  runs that never tripped the infinity. Only samples that carry signal define the reference now, and a
  sample without any is reported via OPENMS_LOG_WARN and left alone.

- Both scaling loops looked the factor up with std::map::operator[], which default-constructs 0.0 for
  an unknown sample and wipes its abundances. This is reachable: with 'best_charge_and_fraction' only
  the single best combination per peptide enters total_abundances, while the loops walk every
  fraction/file/charge/channel, so channels that never win a best slot have no factor. Verified by
  reverting the guard against the new test: 4 of 8 abundances are zeroed. Lookups go through a helper
  that leaves such samples unscaled.

Note this changes results for channels with 1-49% zeros, which never hit the infinity: those zeros
used to drag the median down, so OpenMS systematically over-scaled the channel. That bias is the point
of the fix, but it is a behaviour change. Nothing in the test corpus enables 'consensus:normalize'
(it defaults to false and ProteomicsLFQ.cpp:1865 hardcodes it off), so no reference file changes -
these are also the first tests to exercise normalization at all.

Deletes the "maybe TODO: treat missing abundance values as zero" comment: it proposed the exact
inverse of the convention above and would have made this considerably worse.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XLHJSH5hvWj559Uak2WTGP
…what happened

Follow-up to the previous commit, from reviewing it.

- The early return when fewer than two samples carry signal was completely silent: normalization was
  requested, nothing happened, and the per-sample warnings were skipped too, so the case where the data
  is worst produced no output at all. It now says so.

- The dead-sample warning named the sample by its design-internal id, which appears in no file the user
  wrote. It now also names the (file, channel) pairs behind it, resolved through sample_id_lookup_, and
  no longer claims the sample was "left un-normalized" as if a scale factor had been skipped - its
  values are all zero, so no factor could have changed them.

- 'consensus:normalize' still advertised "Scale peptide abundances so that medians of all samples are
  equal", which is no longer what it does: zeros are excluded from the medians and a sample without
  positive values takes no part.

- A comment said the old code scaled every abundance in a dead channel to infinity. Only the positive
  ones became infinity; the zeros became NaN, since 0 * inf is NaN.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XLHJSH5hvWj559Uak2WTGP
… handle zeros

The comment added in 398e42d said the zero-exclusion "is what MSstatsTMT, isobar, scp and DEqMS do
(zeros to NA, median with na.rm=TRUE)". Checking the four sources directly rather than trusting the
summary it was written from, that is wrong about DEqMS: equalMedianNormalization is four lines, does
matrixStats::colMedians(as.matrix(dat), na.rm = TRUE) and a sweep, and converts nothing. It takes
log2 input, where a zero cannot reach the median to begin with, so it never needs to.

The other three do check out: MSstatsTMT converts zeros to NA at the converter and nulls anything
below 1 twice more before median(log2Intensity, na.rm = TRUE); isobar sets ri.corrected[<1] to NA
after impurity correction; scp calls zeroIsNA() as an early step with exactly that rationale.

Also records what the comparison is and is not evidence for. isobar and scp divide in linear space
just as this code does and are safe purely because zeros never reach the statistic, so the relevant
convention is the zero handling, not log versus linear space. (Not claimed in the comment, but worth
knowing when reading it: only MSstatsTMT shares this code's median-of-medians reference. isobar
divides by the max of the per-channel medians, and scp and DEqMS centre each column on its own median
with no global reference at all.)

Comment text only; no behaviour change.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XLHJSH5hvWj559Uak2WTGP
…er carry-over

Two gaps in what the preceding commits shipped.

The consensusXML reader discards a group's quantities when they were computed for a different set of
proteins, but said so through XMLHandler::warning(), which routes to OPENMS_LOG_DEBUG unless
OPENMS_ASSERTIONS is set - "warn only in Debug mode but suppress warnings in release mode (more happy
users)", XMLHandler.cpp:105-110. That is the right policy for parser noise and the wrong one for
throwing a protein's abundances away: in a release build the quantities simply vanished, with nothing
on stdout or stderr at any debug level. It now logs through OPENMS_LOG_WARN directly, names the file
and the group, and says what to do about it. Verified visible in this Release build.

IDFilter::updateProteinGroups' data-array carry-over had no test and could not get one from the
existing suite: both workflows call it before quantification, so nothing in-tree reaches it with a
group that actually carries quantities. Tested directly instead. Removing the three setters again
fails the test at the first array-size check.

That check is ABORT_IF rather than TEST_EQUAL on purpose: OpenMS assertions are soft, so indexing the
arrays after a failed size expectation is undefined behaviour - the first version of this test brought
the whole binary down with a segfault instead of reporting which expectation had failed.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XLHJSH5hvWj559Uak2WTGP
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: bc5543fe-ada2-4757-ab6f-d9b1c5113fc3

📥 Commits

Reviewing files that changed from the base of the PR and between 3cc7c87 and 5b29334.

📒 Files selected for processing (1)
  • CHANGELOG

📝 Walkthrough

Walkthrough

ConsensusXML now preserves protein-group quantity arrays through storage, loading, filtering, and comparison. Peptide normalization excludes signal-free samples. StringUtils serializes infinities correctly. Unit tests and TOPP fixtures cover these changes.

Changes

Quantitative data handling

Layer / File(s) Summary
Protein-group quantity serialization and preservation
src/openms/source/FORMAT/HANDLERS/ConsensusXMLHandler.cpp, src/openms/source/METADATA/ProteinIdentification.cpp, src/openms/source/PROCESSING/ID/IDFilter.cpp, src/tests/class_tests/openms/source/ConsensusXMLFile_test.cpp, src/tests/class_tests/openms/source/IDFilter_test.cpp
ConsensusXML stores and restores typed quantity arrays with accession validation. IDFilter preserves arrays, and equality compares them. Tests cover round trips, stale ownership, zero arrays, and empty groups.
Signal-aware peptide normalization
src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp, src/tests/class_tests/openms/source/PeptideAndProteinQuant_test.cpp
Normalization uses positive abundances, excludes empty samples, preserves unscaled values, and uses a fallback factor of 1.0.
Non-finite numeric serialization
src/openms/source/DATASTRUCTURES/StringUtils.cpp, src/tests/class_tests/openms/source/StringUtils_test.cpp
Infinity values now serialize as inf and -inf. Tests cover infinity, NaN, finite values, and mixed lists.
Workflow fixtures and integration coverage
src/tests/topp/*
The TMT-10plex workflow test is enabled. Isobaric and LFQ ConsensusXML fixtures include protein-group quantitative metadata.

Possibly related issues

Possibly related PRs

  • OpenMS/OpenMS#8960 — The changes overlap in protein-group parsing and downstream evidence handling.
  • OpenMS/OpenMS#9790 — Both changes modify ConsensusXML protein-group serialization and equality for attached quantitative arrays.

Poem

A rabbit guards each quantity array,
And checks its protein owner there.
Empty channels keep their place,
Bright infinities parse with grace.
Tests hop through the XML space.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the primary change: storing protein-group quantities in consensusXML.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/protein-quantities-xml-export-iaag7w

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (7)
src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp (2)

386-388: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use '\n' in the new warning messages.

Replace endl with '\n' in both added log messages.

  • src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp#L386-L388: Terminate the insufficient-signal warning with '\n'.
  • src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp#L425-L430: Terminate the signal-free-sample warning with '\n'.

As per coding guidelines, “Prefer \n over std::endl”.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp` around
lines 386 - 388, Replace endl with '\n' in both warning log statements in
PeptideAndProteinQuant.cpp: the insufficient-signal warning at lines 386-388 and
the signal-free-sample warning at lines 425-430. Keep the existing warning
messages unchanged while terminating each with '\n'.

Source: Coding guidelines


381-381: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Apply the required C++ block formatting.

Move each opening brace to its own aligned line. Add braces around each nested loop body at lines 709-712.

  • src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp#L381-L381: Move the if block brace to the next line.
  • src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp#L422-L422: Move the if block brace to the next line.
  • src/tests/class_tests/openms/source/PeptideAndProteinQuant_test.cpp#L88-L88: Move the if block brace to the next line.
  • src/tests/class_tests/openms/source/PeptideAndProteinQuant_test.cpp#L101-L102: Put both blocks on separate brace lines.
  • src/tests/class_tests/openms/source/PeptideAndProteinQuant_test.cpp#L649-L649: Move the loop body brace to the next line.
  • src/tests/class_tests/openms/source/PeptideAndProteinQuant_test.cpp#L678-L678: Move the loop body brace to the next line.
  • src/tests/class_tests/openms/source/PeptideAndProteinQuant_test.cpp#L709-L712: Add braces for every nested loop.
  • src/tests/class_tests/openms/source/PeptideAndProteinQuant_test.cpp#L716-L716: Move the if block brace to the next line.

As per coding guidelines, “braces [must be] on their own aligned lines” and “always use braces for blocks”.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp` at line
381, Apply the required C++ brace formatting without changing behavior: in
src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp at lines
381-381 and 422-422, place each if opening brace on its own aligned line; in
src/tests/class_tests/openms/source/PeptideAndProteinQuant_test.cpp at lines
88-88, 101-102, 649-649, 678-678, and 716-716, put each if or loop brace on its
own aligned line; at lines 709-712, add braces around every nested loop body.

Source: Coding guidelines

src/openms/source/DATASTRUCTURES/StringUtils.cpp (1)

79-79: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Put the infinity branch on separate brace lines.

Line 79 uses an inline brace block. Reformat this early return to follow the required C++ style.

As per coding guidelines, C++ braces must be on their own aligned lines.

Proposed formatting fix
-      if (std::isinf(value)) { target += (value < T(0)) ? "-inf" : "inf"; return; }
+      if (std::isinf(value))
+      {
+        target += (value < T(0)) ? "-inf" : "inf";
+        return;
+      }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/DATASTRUCTURES/StringUtils.cpp` at line 79, Reformat the
std::isinf(value) branch in the value-to-string conversion logic so its opening
and closing braces appear on separate aligned lines, while preserving the
existing infinity formatting and early return behavior.

Source: Coding guidelines

src/tests/class_tests/openms/source/StringUtils_test.cpp (2)

564-568: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use the project-approved numeric comparison helper.

Line 564 and Line 568 use TEST_REAL_SIMILAR. The supplied class-test guideline specifies FuzzyDiff for numeric comparisons. Replace these assertions with the approved form. If TEST_REAL_SIMILAR is the scalar exception, document or confirm that exception.

As per coding guidelines, class tests should use FuzzyDiff for numeric comparisons.

#!/bin/bash
set -euo pipefail

rg -n -C 3 '\bFuzzyDiff\b|\bTEST_REAL_SIMILAR\b' src/tests/class_tests
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/class_tests/openms/source/StringUtils_test.cpp` around lines 564 -
568, Replace the scalar numeric assertions for back[0] and back[4] in this test
with the project-approved FuzzyDiff comparison form, preserving their expected
values and existing infinity/NaN checks. If TEST_REAL_SIMILAR is intentionally
required for these scalar cases, confirm and document that approved exception
instead.

558-563: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Verify the test uses the production list parser.

The production reader in src/openms/source/FORMAT/HANDLERS/ConsensusXMLHandler.cpp uses DataValue::toDoubleList() in the getQuantMetaValues path. This test removes the list delimiters and calls ListUtils::create<double>() directly. Add a check through DataValue::toDoubleList(), or verify that both paths use the same parser.

#!/bin/bash
set -euo pipefail

rg -n -C 6 '\btoDoubleList\s*\(' .
rg -n -C 6 'DataValue\s*\(' src/tests/class_tests/openms/source/StringUtils_test.cpp
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/class_tests/openms/source/StringUtils_test.cpp` around lines 558 -
563, The test around the mixed DoubleList currently validates only
ListUtils::create<double>() rather than the production DataValue parser. Update
this test to parse the encoded list through DataValue::toDoubleList(), while
preserving the existing five-value assertions and special-value coverage; if
retaining the direct parser check, explicitly verify both paths produce the same
result.
src/openms/source/FORMAT/HANDLERS/ConsensusXMLHandler.cpp (1)

1131-1137: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Derive the zero-filled slots by name instead of by index.

The loop hardcodes float array indices 1 and 2. These indices are only correct while canonicalFloatNames() keeps "psm_count" and "distinct_peptides" in positions 1 and 2. If that list is reordered or extended at the front, this silently zero-fills the wrong arrays. Resolve the slots from the same name list that fillCanonical used.

♻️ Proposed refactor
-        const Size n_samples = group.getFloatDataArrays()[0].size();
-        for (Size i = 1; i <= 2; ++i)
-        {
-          if (group.getFloatDataArrays()[i].empty()) { group.getFloatDataArrays()[i].resize(n_samples, 0.0f); }
-        }
+        const Size n_samples = group.getFloatDataArrays()[0].size();
+        for (auto& fda : group.getFloatDataArrays())
+        {
+          if ((fda.getName() == "psm_count" || fda.getName() == "distinct_peptides") && fda.empty())
+          {
+            fda.resize(n_samples, 0.0f);
+          }
+        }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/FORMAT/HANDLERS/ConsensusXMLHandler.cpp` around lines 1131
- 1137, Update the zero-filling logic in the ConsensusXML writing flow to
resolve the `"psm_count"` and `"distinct_peptides"` slots by name using the same
canonical name list consumed by `fillCanonical`, rather than iterating hardcoded
indices 1 and 2. Resize only those resolved arrays when empty, preserving the
existing sample count and zero initialization.
src/tests/class_tests/openms/source/ConsensusXMLFile_test.cpp (1)

306-334: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Add ABORT_IF before indexed container reads in the new sections. The shared root cause is that OpenMS TEST_EQUAL is a soft assertion: execution continues after a failed size expectation, so the following indexed reads go out of bounds and terminate the whole test binary instead of reporting the failed expectation. The new IDFilter_test section in this PR already uses ABORT_IF for the same reason.

  • src/tests/class_tests/openms/source/ConsensusXMLFile_test.cpp#L306-L334: add ABORT_IF for the indistinguishable-group count and for the three data-array sizes before indexing rt.
  • src/tests/class_tests/openms/source/ConsensusXMLFile_test.cpp#L372-L374: add ABORT_IF(prot.getHits().size() != 2) before reading prot.getHits()[0].
  • src/tests/class_tests/openms/source/ConsensusXMLFile_test.cpp#L415-L419: add ABORT_IF(groups.size() != 1) before reading groups[0].accessions[0].
  • src/tests/class_tests/openms/source/ConsensusXMLFile_test.cpp#L477-L482: add ABORT_IF(rt.getFloatDataArrays().size() != 4) before indexing slots 0 to 3.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/class_tests/openms/source/ConsensusXMLFile_test.cpp` around lines
306 - 334, Prevent out-of-bounds reads in the new ConsensusXMLFile_test
assertions by adding ABORT_IF guards before dependent indexing: in
src/tests/class_tests/openms/source/ConsensusXMLFile_test.cpp lines 306-334,
guard the indistinguishable-group count and each of the three data-array sizes
before accessing rt; at lines 372-374 guard prot.getHits().size() before reading
the first hit; at lines 415-419 guard groups.size() before accessing
groups[0].accessions[0]; and at lines 477-482 guard
rt.getFloatDataArrays().size() before indexing slots 0 through 3.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/openms/source/FORMAT/HANDLERS/ConsensusXMLHandler.cpp`:
- Around line 1279-1284: In the warning statement within the consensus
protein-group loading logic, replace the terminating std::endl with '\n' while
preserving the existing OPENMS_LOG_WARN message content.

In `@src/tests/class_tests/openms/source/PeptideAndProteinQuant_test.cpp`:
- Around line 705-720: Strengthen the assertions in the peptide abundance loop
around q.getPeptideResults() so factorless channels explicitly retain their
expected values: 30, 40, 60, and 70 for the two peptides. Keep the existing
finite, total, and positive checks, and associate each expected value with the
corresponding peptide/channel rather than only checking positivity.

---

Nitpick comments:
In `@src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp`:
- Around line 386-388: Replace endl with '\n' in both warning log statements in
PeptideAndProteinQuant.cpp: the insufficient-signal warning at lines 386-388 and
the signal-free-sample warning at lines 425-430. Keep the existing warning
messages unchanged while terminating each with '\n'.
- Line 381: Apply the required C++ brace formatting without changing behavior:
in src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp at lines
381-381 and 422-422, place each if opening brace on its own aligned line; in
src/tests/class_tests/openms/source/PeptideAndProteinQuant_test.cpp at lines
88-88, 101-102, 649-649, 678-678, and 716-716, put each if or loop brace on its
own aligned line; at lines 709-712, add braces around every nested loop body.

In `@src/openms/source/DATASTRUCTURES/StringUtils.cpp`:
- Line 79: Reformat the std::isinf(value) branch in the value-to-string
conversion logic so its opening and closing braces appear on separate aligned
lines, while preserving the existing infinity formatting and early return
behavior.

In `@src/openms/source/FORMAT/HANDLERS/ConsensusXMLHandler.cpp`:
- Around line 1131-1137: Update the zero-filling logic in the ConsensusXML
writing flow to resolve the `"psm_count"` and `"distinct_peptides"` slots by
name using the same canonical name list consumed by `fillCanonical`, rather than
iterating hardcoded indices 1 and 2. Resize only those resolved arrays when
empty, preserving the existing sample count and zero initialization.

In `@src/tests/class_tests/openms/source/ConsensusXMLFile_test.cpp`:
- Around line 306-334: Prevent out-of-bounds reads in the new
ConsensusXMLFile_test assertions by adding ABORT_IF guards before dependent
indexing: in src/tests/class_tests/openms/source/ConsensusXMLFile_test.cpp lines
306-334, guard the indistinguishable-group count and each of the three
data-array sizes before accessing rt; at lines 372-374 guard
prot.getHits().size() before reading the first hit; at lines 415-419 guard
groups.size() before accessing groups[0].accessions[0]; and at lines 477-482
guard rt.getFloatDataArrays().size() before indexing slots 0 through 3.

In `@src/tests/class_tests/openms/source/StringUtils_test.cpp`:
- Around line 564-568: Replace the scalar numeric assertions for back[0] and
back[4] in this test with the project-approved FuzzyDiff comparison form,
preserving their expected values and existing infinity/NaN checks. If
TEST_REAL_SIMILAR is intentionally required for these scalar cases, confirm and
document that approved exception instead.
- Around line 558-563: The test around the mixed DoubleList currently validates
only ListUtils::create<double>() rather than the production DataValue parser.
Update this test to parse the encoded list through DataValue::toDoubleList(),
while preserving the existing five-value assertions and special-value coverage;
if retaining the direct parser check, explicitly verify both paths produce the
same result.
🪄 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 Plus

Run ID: 86b3492d-d1c8-497d-9f88-d42d4bbd6320

📥 Commits

Reviewing files that changed from the base of the PR and between 552802a and 3cc7c87.

⛔ Files ignored due to path filters (1)
  • src/tests/topp/IsobaricWorkflow_1_design.tsv is excluded by !**/*.tsv
📒 Files selected for processing (25)
  • CHANGELOG
  • src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp
  • src/openms/source/DATASTRUCTURES/StringUtils.cpp
  • src/openms/source/FORMAT/HANDLERS/ConsensusXMLHandler.cpp
  • src/openms/source/METADATA/ProteinIdentification.cpp
  • src/openms/source/PROCESSING/ID/IDFilter.cpp
  • src/tests/class_tests/openms/source/ConsensusXMLFile_test.cpp
  • src/tests/class_tests/openms/source/IDFilter_test.cpp
  • src/tests/class_tests/openms/source/PeptideAndProteinQuant_test.cpp
  • src/tests/class_tests/openms/source/StringUtils_test.cpp
  • src/tests/topp/CMakeLists.txt
  • src/tests/topp/IsobaricWorkflow_1_input.idXML
  • src/tests/topp/IsobaricWorkflow_1_out.consensusXML
  • src/tests/topp/ProteomicsLFQ_1_out.consensusXML
  • src/tests/topp/ProteomicsLFQ_1_subset_out.consensusXML
  • src/tests/topp/ProteomicsLFQ_2_out.consensusXML
  • src/tests/topp/ProteomicsLFQ_3_out.consensusXML
  • src/tests/topp/ProteomicsLFQ_3_seedRT_out.consensusXML
  • src/tests/topp/ProteomicsLFQ_4_out.consensusXML
  • src/tests/topp/ProteomicsLFQ_5_out.consensusXML
  • src/tests/topp/ProteomicsLFQ_6_out.consensusXML
  • src/tests/topp/ProteomicsLFQ_7_out.consensusXML
  • src/tests/topp/ProteomicsLFQ_8_out.consensusXML
  • src/tests/topp/ProteomicsLFQ_9_out.consensusXML
  • src/tests/topp/ProteomicsLFQ_9_seedRT_out.consensusXML

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

this is required before switching to parquet / qpx. So we can properly test A vs B

@timosachsenberg
timosachsenberg merged commit 3c9b609 into develop Aug 3, 2026
1 check passed
@timosachsenberg
timosachsenberg deleted the claude/protein-quantities-xml-export-iaag7w branch August 3, 2026 13:08
timosachsenberg added a commit that referenced this pull request Aug 3, 2026
Reject duplicate identification-run identifiers in both merge-index preflight overloads and cover the value and pointer paths.

Preserve develop's safe normalization fallback for fraction-group quantities after integrating #9844.
timosachsenberg added a commit that referenced this pull request Aug 3, 2026
…#9817) (#9843)

* [FIX] QPX 1.1: re-key the pg view onto grouped_runs, bump qpx_version (#9817)

bigbio/qpx#220 (merged) defines QPX format 1.1. The protein-group view drops the
scalar required column run_file_name and gains grouped_runs (list<string>); the
primary key becomes [anchor_protein, grouped_runs], and every QPX view declares
qpx_version 1.1. The psm and feature views are otherwise unchanged by 1.1 and
keep their scalar run_file_name.

This is a change of GRAIN, not a rename. A pg row used to carry a per-file cell
from the group's file_channel_level_abundance array; it now carries the
SAMPLE-level value from the array PeptideAndProteinQuant names "abundances". The
two are not interchangeable: the quantifier accumulates
total_abundances[sample] += abundance over every fraction, file, charge and
channel of a sample, while the per-file cells aggregate within a file, so summing
them does not reproduce the sample value. Measured on the shipped BSA fixture,
summing BSA1's two per-file cells gives 304,924,936 against a true 214,289,808;
the export now emits 214,289,808.

A quantification unit is a CONNECTED COMPONENT of the (run, sample) incidence:
two runs join as soon as they share one sample, transitively. That is the weakest
grouping under which no sample straddles two units, which is what makes the
spec's "(any file in grouped_runs, label) -> run.samples[]" well defined. It is
deliberately neither of the two obvious alternatives:

  * the design's fraction_group --
    share/OpenMS/examples/FRACTIONS/BSA_design_onetable_nonconsec.tsv puts
    BSA1_F1 in fraction group 1 and BSA1_F2 in fraction group 4 while both are
    sample BSA1, so that key emits one sample's quantity twice under two keys;
  * equality of a run's whole (label -> sample) map -- OpenMS accepts designs
    with missing rows on purpose (ExperimentalDesign_test.cpp: "missing fractions
    and wrong orders should work now"), and in the shipped 4-plex
    ExperimentalDesign_input_2_wrong.tsv one fraction has no label-1 row.
    Requiring equal maps splits that plex into units that then share samples,
    refusing a design the loader accepts.

ProteinGroupArrowExport gained overloads taking the ExperimentalDesign that drove
quantification: it supplies both the grouping and the sample index space the
abundances are stored under. ProteomicsLFQ, ProteinQuantifier and
IsobaricWorkflow pass theirs; the convenience overload reconstructs one with
fromConsensusMap() and is documented as best-effort. Identification-only output
(ProSE, protein inference) has no design and writes single-element lists, the
form the 1.1 schema documents for unfractionated input.

Four shapes are refused rather than guessed at, because the row cannot represent
them: a design whose sample count does not match the abundance array (it is not
the design that produced it); a label that means two different samples within one
unit (a common reference channel shared across plexes joins the plexes, and the
remaining channels then disagree about what each label means); a sample filling
two labels of one unit, whose single aggregated quantity would be published
twice; and a label mapped to a sample the sample section does not describe.
Design files the ConsensusMap has no column header for contributed nothing and
are left out of grouped_runs, which also keeps the pg run names a subset of what
psm and feature can join to.

Two adjacent corrections. feature_counts.total_features now counts (feature, run)
pairs: the feature view melts one ConsensusFeature into one row per run, so a
feature spanning two fractions of a unit is two feature rows, and counting bare
feature indices made pg disagree with feature.parquet; unique_features stays keyed
on peptidoform+charge and does not grow. And a group melted onto a run it was only
identified in wrote an empty intensities list where the identification-only
overload writes null -- one column meaning two things depending on which overload
produced the file, contradicting the code's own comment.

The ConsensusMap overload now builds its table on QPXPgSchema::schema() instead of
restating the 20 fields inline, which is what let the two definitions drift apart.

Tests: eight new sections pin the grain, the sample-vs-fraction-group unit, the
missing-design-row unit, the foreign-design refusal, the ambiguous-label refusal,
the header intersection, the feature-row count and the null-intensity convention.
Each was verified to fail against the previous behaviour before being kept. Zero
reference-file churn: the -out_qpx TOPP tests only sha256sum for existence and no
reference file contains a pg column name.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DF2YUewPQTC5tJWqn23pUm

* [FIX,IO,TEST] Align protein-group export with QPX 1.1

Preserve protein quantities at fraction-group and label grain and emit the scalar protein-group schema used by active QPX development.

Complete collection preflight and add regression coverage for schema, grouping, label resolution, and malformed annotations.

* [FIX,TEST] Complete QPX preflight after rebase

Reject duplicate identification-run identifiers in both merge-index preflight overloads and cover the value and pointer paths.

Preserve develop's safe normalization fallback for fraction-group quantities after integrating #9844.

* [FIX] Restore normalization diagnostics after rebase

Use the design-cell lookup introduced by the QPX fraction-group work when naming samples without positive abundance.

* [FIX,TEST] Align QPX annotation keys with map headers

* [TEST] Refresh protein-quantity consensusXML fixtures

* [COMMENT,TEST,INTERNAL] Address QPX review feedback

Centralize the protein-group annotation contract so preflight and export cannot drift. Document design lookup exceptions and cover each malformed-design rejection.

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
timosachsenberg pushed a commit that referenced this pull request Aug 7, 2026
Three CHANGELOG entries already document their change in full but were
missing the trailing PR citation: consensusXML protein-group quantity
round-tripping (#9844), the FuzzyStringComparator NaN-equality fix
(#9859, #9861), and the "five more Parquet writers left a partial file
behind" fix (#9862).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YAD9pD1nBputTVhzddmCj5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants