Skip to content

[FIX,TEST] Correct ProteinQuantifier charge selection - #9847

Merged
timosachsenberg merged 2 commits into
developfrom
codex/fix-best-charge-and-fraction
Aug 4, 2026
Merged

timosachsenberg merged 2 commits into
developfrom
codex/fix-best-charge-and-fraction

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • select one charge state per modified peptide globally across samples using the number of samples with positive signal
  • break prevalence ties by total abundance across all samples, then deterministically prefer the lower charge
  • retain every observation of the selected charge across samples and fractions, including explicit zero quantities
  • use that selected charge consistently for sample totals, QPX fraction-group/label totals, and detailed file/channel protein output
  • correct file/channel peptide aggregation so all peptidoforms contribute, charges are combined within each peptide, and top-N counts peptides
  • fix the detailed peptide TSV: preserve every fraction file in the header, and always emit a value per (file, channel) cell
  • keep PSM-count aggregation independent of the charge-selection flag
  • add class and TOPP regression coverage for prevalence, tie-breaking, zeros, fractions, file/channel output, top-N, iBAQ, and QPX output

Fixes #9796.

This also incorporates the relevant file/channel aggregation correction from #9793, without its unrelated vcpkg submodule change.

Review status

The 15-finding review below has been worked through.

Fixed in this PR — findings 11, 12 and 14:

  • 11 writePeptideTable_ — the header keyed the design's spectra file paths by fraction group, so all fractions of a group collapsed onto whichever file the design listed last (11 of 12 files vanished for a 12-fraction group); and two of the three "no value here" cases emitted nothing instead of 0.0, shifting every later cell of the row one column left so the trailing fraction value landed under an abundance header. Both confirmed by running the pre-fix binary. Now keyed by (fraction group, fraction) like the protein table already was, and every cell always writes a value. Pinned by the new TOPP_ProteinQuantifier_28 on a fractionated design, verified to fail without the fix.
  • 12 the continue did skip the PSM-count aggregation, and is fixed. One correction to the finding as written: its stated impact does not exist today, because PeptideData::psm_counts is never written anywhere in OpenMS (ConsensusXMLHandler.cpp:974 already documents this), so the loop it skipped is currently a no-op. The fix restores the invariant for when those counts are populated upstream; it could not be given a failing test, as the member is unreachable from the public API.
  • 14 confirmed: TOPP_ProteinQuantifier_19_qpx and the new _19 shared ${TESTS_TEMP_DIR}/ProteinQuantifier_19_output.tmp. The new tests are renumbered to 23–27, as suggested.

Fixed separately — finding 13. Confirmed as a behaviour description, but it is not introduced here: the default path has always materialised a total_abundances entry for an explicit 0.0 (quantifyFeature_ records every handle, including zero-intensity ones), so best-charge mode now matches the long-standing default rather than diverging from it. The real defect is older and narrower than the finding states: both size()-dependent branches are gated on consensus:fix_peptides, which is off by default and set by no OpenMS tool. Fixed in #9851, scoped to the counting only — selectPeptidesForQuantification_ and orderBest_ now count samples with a positive abundance, which is the rule normalizePeptides_() and getBestCharge_() already apply. total_abundances is untouched, so no abundance, mzTab or QPX value moves and no reference file changes.

Moved out — findings 1–10 and 15. These reviewed the #9846 validation work, which is merged; this branch was rebased and those files are no longer in the diff. Findings 3, 9 and 10 turned out to be reachable and are fixed in #9849, together with 15 (QPXValueValidation_test) and the contract documentation. The remainder (1, 2, 4, 5, 6, 7, 8) are accepted as a deliberate tightening of the QPX input contract: the supported producers are ProteomicsLFQ and IsobaricWorkflow, whose output satisfies it by construction. #9849 writes that contract down in one place.

Reference files

The eight ProteomicsLFQ references now change — the earlier "no reference files change" claim was wrong. Exactly nine lines, all indistinguishable_proteins_N_file_channel_level_abundance, verified rather than regenerated:

  • Rebuilding the same tree with only PeptideAndProteinQuant reverted to develop isolates those nine lines as the entire effect of this change. Everything else that differs locally is environment noise (this machine drifts up to 8.4e-5 relative from the CI-generated references, against a FuzzyDiff tolerance of 1e-2), so only those nine lines were edited; the rest of every file is untouched.

  • The unchanged sample-level abundances next to them are what proves the new values right. Both spectral-counting tests run top:N 0 with top:aggregate sum, where a sample's cells must sum exactly to its sample-level value — and only the new cells do:

    cells per-sample sums sample level
    ProteomicsLFQ_4 before 13, 11, 14, 15, 9, 9 24, 29, 18 35, 31, 25 ✗
    ProteomicsLFQ_4 after 19, 16, 16, 15, 15, 10 35, 31, 25 35, 31, 25 ✓

    Same for both protein groups of ProteomicsLFQ_6. Re-running the feature-intensity input under top:N 0 + sum shows 1 of 5 protein groups violating the invariant with the old code and 0 of 5 with this change.

  • The feature-intensity cells (top:N 3, median) were recomputed independently from the consensus features and protein-group definitions in the output itself: the rule "per file, one summed value per peptide over its peptidoforms and charges, top 3, median" reproduces all six new cells exactly and disagrees with the old values on precisely the two that changed.

Experimental-design and replicate semantics

The QPX protein-quantity grain remains (fraction_group, label):

  • one fraction group becomes one grouped_runs unit
  • each label within that unit must resolve unambiguously to one OpenMS sample
  • the same sample may be reused by several labels and/or several fraction groups
  • repeated-sample fraction groups remain separate quantities, so technical replicates are not merged or double-counted
  • normalization applies the shared sample scale to every separate fraction-group/label quantity

Covered by the existing ProteinGroupArrowExport_test case "fraction groups stay distinct when a sample repeats".

Validation

  • full local ctest (2782 tests): no failure in anything this PR touches. The remaining failures are the known-environmental set (Thermo .NET, Comet version string, percolator numerics), Doxygen_Warning_test (HAVE_DOT in two pre-existing files), one very slow Bruker real-data test, and TOPP_SimpleSearchEngine_DDA — a pre-existing break on develop, fixed separately in [FIX] TOPP_SimpleSearchEngine_DDA passed an argument to a flag #9850
  • 56/56 TOPP_ProteinQuantifier_* and PeptideAndProteinQuant_test
  • 66/66 TOPP_ProteomicsLFQ_*
  • doxygen regenerated: no new warnings

Merge order

These four PRs are all descendants of the same review of #9847. Test-merged locally in this order; only one conflict exists and it is trivial.

# branch base depends on
1. #9847 codex/fix-best-charge-and-fraction develop —
2. #9852 fix/file-channel-zeros-not-detected #9847 #9847 (rewrites the function it patches)
3. #9851 fix/zero-abundances-not-evidence develop — (conflicts with #9852, see below)
4. #9849 fix/qpx-feature-key-and-atomic-export develop —

Verified locally: all four merged together, conflicts resolved as above, 63/63 PeptideAndProteinQuant_test / TOPP_ProteinQuantifier_* / TOPP_IsobaricWorkflow_* / QPX / Arrow tests pass, and the two isobaric abundance arrays agree exactly.

@timosachsenberg

timosachsenberg commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Note

Status after rebase

The detailed findings are retained below for follow-up.

Code review — 15 findings

The dominant theme: the new QPXValueValidation converts several deliberate producer-side "emit the row and warn" policies into whole-file export refusals, for input shapes OpenMS itself routinely produces. Two tell-tales come from the PR itself — it had to edit pre-existing test fixtures to satisfy the new preconditions (which CLAUDE.md forbids: "always investigate the root cause first before patching reference files or test expectations"), and it inverted its own previously-passing assertions to expect "<write failed>".


A. New validator refuses inputs that exported fine before

1. src/openms/source/FORMAT/QPXValueValidation.cpp:352 — empty scan list is fatal, but QPXFile emits it by design

QPXFile.cpp:1314-1324 does scan_builder.Append(); then appends a value only if (!spec_ref.empty()) and extractScan(spec_ref) >= 0 — the comment literally reads // else: empty list. Any consensusXML/idXML without spectrum_reference (protein-inference output, ID converters, MBR/transferred IDs) now makes every row fail key_valid, writeTableToParquet returns false, and ProteinQuantifier throws UnableToCreateFile where it previously wrote a valid collection.

Evidence from the PR: it added spectrum_reference="scan=100" to the shared fixture src/tests/topp/ProteinQuantifier_input.consensusXML (churning 11 lines of the unrelated ProteinQuantifier_9 mzTab reference), and flipped a passing assertion to TEST_STRING_EQUAL(scan_format_for("some_opaque_identifier"), "<write failed>").

2. QPXValueValidation.cpp:389 — PSM primary-key uniqueness refuses duplicate rows IDMapper legitimately creates

src/topp/ProteinQuantifier.cpp:1065-1075 flattens all_pepids by concatenating every feature's PeptideIdentifications plus the unassigned ones. IDMapper maps one MS2 identification onto every consensus feature whose RT/m-z window contains it, so the same PeptideIdentification is copied into two features and appears twice with identical sequence, charge, run stem and scan list. Likewise for idXML merged by IDMerger across two search engines, and for export_all_psms=true where two hits of one spectrum differ only in score.

Direct in-PR evidence that this is not hypothetical: QPXFile_test.cpp:1610-1614 had to rewrite for (i) peps.push_back(pid); to give each of 10 replicated PSMs a distinct scan number, because the pre-existing fixture now fails validation in both the one-shot and streaming paths. The removed PrimaryKeyWatch only ever watched the pg view, so this is brand-new refusal territory for psm.parquet.

3. QPXValueValidation.cpp:417 — the feature primary key degenerates to (charge, run, quantized RT) for every unmapped feature

The feature-view key is (peptidoform, charge, run_file_name, rt), with observed_mz deliberately excluded and rt narrowed to float32. But unidentified features are exported, not dropped — ConsensusMapArrowExport.cpp:779-781 writes them via sequence_builder.Append(""); peptidoform_builder.Append(""); (only handle-less features are dropped, line 526, dropped_handleless), and observed_mz is written one line below the rt append but is not part of the key.

So for a ProteomicsLFQ/FeatureLinker map with tens of thousands of unidentified features in one run, most sharing a charge, the key is RT alone. rt is static_cast<float>(row_rt), whose ULP near 3000 s is ~2.4e-4 s, so any two co-eluting same-charge unmapped features that round to the same float32 collide; the validator reports "repeats the QPX feature primary key" and both exportToParquet and exportToParquetStreaming return false. The inline comment asserting the opposite — "the RT still distinguishes their primary key" — is the assumption to re-check. Adding observed_mz to the key, or exempting unmapped rows from the uniqueness check, would fix it.

4. QPXValueValidation.cpp:342 — empty run_file_name refusal directly contradicts the policy added in #9834

QPXFile.cpp:1302-1308 still states: "Emit the row (a PSM is a primary record; dropping it would discard an identification) but count it", increments unattributable_psms, and QPXFile.cpp:1524/1814 emits an aggregated WARN naming setPrimaryMSRunPath() as the remedy. Protein-inference output routinely drops spectra_data, so File::stemName("") is empty for every row. The trade-off "one unjoinable row plus a warning" is silently inverted into "no psm.parquet at all" — and in the streaming path the helpful WARN is still printed after the write already failed.

5. QPXValueValidation.cpp:599 — PrimaryKeyWatch deleted; its documented warn-only rationale is now a hard refusal

The deleted comment enumerated the reachable inputs — "Two ProteinIdentifications whose paths share a stem, a repeated accession group, or two identifiers mapping to one path list" — and concluded "Emitting both is deliberate -- dropping a row loses data and no merge rule exists for two group probabilities". The id-only overload emits one row per (prot_id, group, evidence run) with no cross-prot_id dedup, so an idXML with two runs sharing an anchor accession and a run stem now trips both the PK check and the new pg_run_keys disjointness rule, and pg.parquet is never written. This is also stricter than the QPX spec (qpxc validate downgrades duplicate PKs to warnings). Separately, the in-memory exportToArrow() path that ProSE consumes lost its only duplicate-key diagnostic — grep -rn PrimaryKeyWatch now returns nothing.

B. Label canonicalisation

6. src/openms/source/FORMAT/ArrowIOHelpers.cpp:208 — qpxIntensityLabel("no_label", "") returns "SILAC light" for a label-free run

FeatureFinderMultiplexAlgorithm.cpp:1104-1132 sets desc.label = "no_label" when algorithm:labels is [] — the singlets-only, label-free mode it explicitly supports at line 999 — and src/topp/FeatureFinderMultiplex.cpp:197 sets the filename. In qpxIntensityLabels() that single header groups alone; hasSILACMarker("no_label") is false (silacRole returns LIGHT, no "silac" substring), so it is not silac-shaped and falls through to the scalar helper, which returns "SILAC light". That value is written into intensities[].label and the pg label — both join keys against run.samples[].label, where the correct token is "LFQ". This is exactly the "writing a guessed token into a join key" the function's own doc says must never happen, and it is silent — no error is logged on this path. The new test only covers label = "label-free", never "no_label".

7. ArrowIOHelpers.cpp:239 — lost non-empty pass-through makes ICPL / Leu3 / label N maps unexportable

MultiplexDeltaMassesGenerator.cpp:169 lists what FeatureFinderMultiplex writes: Arg6 Arg10 Lys4 Lys6 Lys8 Leu3 Dimethyl0 Dimethyl4 Dimethyl6 Dimethyl8 ICPL0 ICPL4 ICPL6 ICPL10 no_label, plus "label <i>" when algorithm:knock_out=true (FeatureFinderMultiplexAlgorithm.cpp:1119-1122). The canonical set (ArrowIOHelpers.cpp:410-435) has no ICPL*, no Leu3, no "label N", and no title-case mTRAQ normalisation (only Dimethyl gets one). Those hit no branch, log an ERROR and return "" → ConsensusMapArrowExport sets has_unlabelable_channel and returns nullptr, ProteinGroupArrowExport returns nullptr, QPXCollectionExport::requireExportable returns false. An ICPL 4-plex or Leu-labelled consensusXML that previously exported can no longer be exported at all, with no flag or override. The deleted TEST_STRING_EQUAL(qpxIntensityLabel("Arg10", ""), "Arg10") was the pin for that guarantee.

8. ArrowIOHelpers.cpp:270 — the SILAC mass-class rule is written twice, and hasSILACMarker() gates the map-level branch on a third

(a) For a mixed heavy label such as "Lys6Arg10" or "Arg6Lys8" (FeatureFinderMultiplex concatenates a sample's labels with no separator, FeatureFinderMultiplexAlgorithm.cpp:1127-1132), silacRole() sets medium and heavy, hits if (medium == heavy) return UNKNOWN, and hasSILACMarker() then also returns false (no literal "silac" substring) — so qpxIntensityLabels() never enters the SILAC branch written to reject exactly this. Each header falls to the scalar, whose medium test additionally excludes arg10/lys8, so it returns "SILAC heavy" for that channel while the light partner becomes "LFQ". A role that could not be determined is written into a join key as heavy.

(b) Conversely, hasSILACMarker("SILAC heavy") is true, so a demultiplexed map with one canonical-labelled header per filename fails supported_silac_plex (size 1), is blanked to "" and refused — even though qpxIntensityLabel("SILAC heavy", "") and qpxIsCanonicalIntensityLabel("SILAC heavy") both accept it, and line 237 explicitly anticipates canonical input ("Already-canonical values can occur after loading a QPX-enriched intermediate"). Same for any SILAC-labelled source with 4+ columns. Grouping also uses the raw header.filename rather than the qpxRunFileName() stem every other QPX join key uses, so two headers of one run whose paths differ in spelling split the plex.

The added tests cover "Lysate_A"/"catalyst" and a literal "SILAC mystery" but neither of these two shapes.

C. Partial / truncated output

9. src/openms/source/FORMAT/QPXCollectionExport.cpp:145 — requireExportable() was edited but not extended with any new refusal mode

Its own comment says it exists to "Catch both before the feature and PSM writers can leave a partial collection behind", and the CHANGELOG for #9843 claims "a refused -out_qpx export no longer leaves a partial collection for deterministic input errors". It checks protein IDs/groups, merge indices, channel labels, design samples and fraction groups — but no PK uniqueness, no scan emptiness, no run_file_name emptiness, no label value; grep -n QPXValueValidation src/openms/source/FORMAT/QPXCollectionExport.cpp is empty. src/topp/ProteinQuantifier.cpp writes quantms.feature.parquet at line 1056 and only then hits the PSM refusal at line 1077, leaving exactly the partial collection the preflight exists to prevent. Any input from findings 1–4 reproduces it.

10. src/openms/source/FORMAT/QPXFile.cpp:1806 — refused PSM batch leaves a truncated, footer-complete parquet

The new value_validator.validate(parts[t]) at QPXFile.cpp:1766 can fail after earlier batches were flushed through writer->WriteTable(...). write_batch returns false, ok becomes false, the writer and sink are closed anyway (footer written), and the function returns ok with no cleanup — grep -n "File::remove" src/openms/source/FORMAT/QPXFile.cpp returns nothing, while this PR added if (!ok && !File::remove(filename)) at ConsensusMapArrowExport.cpp:1579 for the identical situation. QPXFile.cpp already includes <OpenMS/SYSTEM/File.h>. The asymmetry is mirrored in the tests: ProteinGroupArrowExport_test asserts TEST_FALSE(File::exists(output)), the new QPXFile streaming test only asserts the bool.

D. Quantification semantics (best_charge_and_fraction)

11. src/topp/ProteinQuantifier.cpp:457 — misaligned TSV: two of three cell cases emit nothing instead of 0.0

bool no_quant = false;
if (filename_to_chargemap.contains(filename)) {
  if (charge_map.contains(charge)) {
    if (channel_to_abundance.contains(c)) { out << ...; }   // no else
  } else { no_quant = true; }
}                                                            // no else
if (no_quant) { out << 0.0; }

When the design filename is absent from the peptide's map, no_quant stays false and no cell is emitted; likewise when channel c is absent. With the PR's own 2-file fixture (-peptide_out p.csv -best_charge_and_fraction -design ProteinQuantifier_18_input.tsv), peptide CCCCCK exists only in sample1, so the row is one cell short and fraction lands under abundance|sample2|ch1. Compounding this, design_filenames[f.fraction_group] = fn; (line 400) is keyed by fraction group, so for a fractionated design (ProteinQuantifier_16's 12 fractions in fraction_group 1) the header keeps only the last fraction's file and 11 files vanish. The only existing test of this path (TOPP_ProteinQuantifier_2) uses a single-file featureXML and cannot see either defect.

12. src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp:333 — the surviving continue still skips PSM-count aggregation

For isobaric input where IsobaricChannelExtractor stored every reporter of peptide P as 0.0 (undetected or below min_reporter_intensity): with best_charge_and_fraction=false, P falls into the else branch, reaches the pep_q.second.psm_counts loop and contributes to total_psm_counts, prot_quant_[leader].peptide_psm_counts and total_distinct_peptides. With =true, getBestCharge_ returns false and the continue skips that loop entirely, so the protein's psm_count/distinct_peptides arrays written by annotateQuantificationsToProteins() — and therefore mzTab and the QPX pg row — drop those PSMs with no diagnostic. Spectral counts should not depend on the charge-selection flag; the PR explicitly reworked this block to "retain explicit zero quantities", making the surviving skip inconsistent with its own goal.

13. PeptideAndProteinQuant.cpp:351 — retained 0.0 inflates the sample count used for top:N ranking

getBestCharge_ skips cha.second <= 0.0 when counting prevalence, and the new comment states zeros "did not count as evidence when the charge was selected". The retention loop then does total_abundances[cell.sample] += abundance for every observation of the winning charge including 0.0, materialising the map entry. selectPeptidesForQuantification_ (line 1313) selects on ab.second.size() == stats_.n_samples, and orderBest_ (PeptideAndProteinQuant.h:335) ranks by make_pair(ab_it->second.size(), total). For TMT data, a peptide with real signal in 2 of 10 channels and 0.0 in the other 8 now reports size()==10 and outranks a peptide genuinely quantified in 6 — changing which peptides win the top:N slots. Before this PR the best-charge branch assigned exactly one sample entry, so the effect is new to that mode.

E. Test infrastructure

14. src/tests/topp/CMakeLists.txt:2891 — TOPP_ProteinQuantifier_19 collides with _19_qpx on one temp path

Line 2873 (TOPP_ProteinQuantifier_19_qpx, ProteinQuantifier_16_input, -top:include_all) and the new line 2891 (TOPP_ProteinQuantifier_19, ProteinQuantifier_18_input, -method iBAQ) both pass -out ${TESTS_TEMP_DIR}/ProteinQuantifier_19_output.tmp, and TOPP_ProteinQuantifier_19_out1 DEPENDS only on TOPP_ProteinQuantifier_19. CI runs ctest in parallel, so the two processes can write concurrently, or the qpx run can clobber the file between the producer and the FuzzyDiff — comparing a 12-sample TMT protein table against the 4-column iBAQ reference. Every other ProteinQuantifier temp output appears exactly twice; this one now appears three times. The new _18 escaped the same collision only because 18_qpx happens to use .tmp.csv. Renumber to 23–27, or use distinct temp names.

15. No QPXValueValidation_test.cpp exists or is registered in executables.cmake — every sibling QPX class has one, and it is step 3 of the "Adding New Library Classes" checklist, for a 617-line OPENMS_DLLAPI class. Given findings 1–5 and 8 are all reachable-input mismatches in that one file, it is the highest-value test to add.


Smaller items that did not make the cap
  • QPXValueValidation.cpp:265 — the validator retains one heap-allocated primary-key string per row for the whole output file, and both streaming writers hold a single instance across all batches (by design, to catch cross-batch duplicates), so impl_->primary_keys is only ever inserted into, never cleared. At ~130–150 B retained per row a 50M-PSM export accumulates ~7 GB that never shrinks — contradicting the comment 20 lines above ("Peak memory stays batch-bounded") and the reason exportToParquetStreaming exists. validate() also calls table->ValidateFull() (O(n), full UTF-8 + offset checking) once per OpenMP partition per batch on tables the exporters just built with Arrow builders, plus arrow::Concatenate copies of the key columns. primary_keys.insert(begin, end) copy-constructs every key a second time where merge() would splice nodes.
  • combinedColumn() treats num_chunks()==0 as invalid, rejecting a legal 0-row column on read-modify-write.
  • addError() accumulates one unbounded string per failing row and joins them into a single log line, so the systemic failures above produce ~1 GB of diagnostics on a large input.
  • channel_level_abundances cells that the per-file top:N gate declines are absent, and the writer renders them as 0.0 — indistinguishable from a measured zero, and pyOpenMS-visible. The PR's own ProteinQuantifier_22_output.txt is all zeros for a protein that is quantified at sample level.
  • validateAdditionalIntensities() (~90 lines) is unreachable — no producer populates that column.
  • Duplication worth collapsing: combinedColumn vs ArrowIOHelpers::getColumn; Result vs ArrowSchemaValidation::ValidationResult; getBestCharge_ vs the existing orderBest_ template; three hand-rolled std::transform/tolower loops instead of StringUtils::toLowered.

Two things checked and found clean, so no action needed: the new TOPP reference numbers all follow from their fixtures (18: 750.0/0.0; 19: 1800/3=600 and 20/3=6.667 — three peptides because trypsin does not cleave the K-P bond in CCCCCK|PEPTIDEMK; 20/21/22 likewise), and both new validator calls sit in the serial write loop, outside the #pragma omp parallel for.

Edited to add finding 3 (feature primary key vs. unmapped features) and the QPXFile_test.cpp fixture evidence under finding 2; the two SILAC items were merged into finding 8.

@jpfeuffer

Copy link
Copy Markdown
Contributor

@timosachsenberg one thing we should make sure and double check is the handling of technical replicates of the same sample. I am not sure about our current samplesheet definitions but when we are checking that channels in a fraction group must map to the same sample and not be reused across fraction groups, we need to do that in a way that considers biological and technical replicates also. I think the idea was to avoid redefining sample properties for replicates so you can have the same "sample" in multiple channels if they are replicates of each other. Do you know what I mean?

@timosachsenberg
timosachsenberg marked this pull request as ready for review August 4, 2026 09:49
Select a single charge state per peptide across all samples by prevalence and summed abundance, then retain all observations for the chosen charge. Correct file/channel peptide aggregation so detailed and QPX outputs use consistent quantities.

Fixes #9796
@timosachsenberg
timosachsenberg force-pushed the codex/fix-best-charge-and-fraction branch from a343297 to 263ec86 Compare August 4, 2026 09:50

Copy link
Copy Markdown
Contributor Author

@jpfeuffer Yes — and I double-checked this against the current implementation.

  • A QPX quantification unit is exactly one OpenMS fraction_group; label is the channel dimension.
  • Several (fraction_group, label) cells may point to the same OpenMS sample, so a sample can be reused across channels and across technical-replicate fraction groups.
  • Repeated-sample fraction groups remain separate grouped_runs rows and keep separate quantities; they only share the sample's normalization factor.
  • We reject only ambiguity: one (fraction_group, label) resolving to different samples, or one raw run assigned to several fraction groups. Distinct technical-replicate runs are valid.

This is covered by ProteinGroupArrowExport_test (“fraction groups stay distinct when a sample repeats”), which uses one sample in fraction groups 1 and 4 and asserts two separate QPX rows with independent quantities. So this concern is already addressed in current develop; no additional change is needed in #9847.

@OpenMS OpenMS deleted a comment from coderabbitai Bot Aug 4, 2026
@jpfeuffer

jpfeuffer commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

they only share the sample's normalization factor.

That's what worries me! I am not sure if they should. A replicate of a sample is technically a "different" sample (for quantification purposes, not annotation purposes) and should have another normalization factor

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Caution

Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted.

Error details
Not Found - https://docs.github.com/rest/issues/comments#update-an-issue-comment

@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

🤖 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/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp`:
- Around line 332-337: Update the best-charge handling around getBestCharge_ in
the pep_quant_ loop so a missing selected charge skips only abundance
aggregation, not the subsequent PSM-count aggregation and quant_peptides
statistic. Preserve best_charge_by_peptidoform_ updates for selected charges and
ensure peptidoforms with no valid charge still reach the total_psm_counts logic.

In `@src/tests/topp/CMakeLists.txt`:
- Around line 2900-2902: Rename the temporary output file used by the new
TOPP_ProteinQuantifier_19 test and update TOPP_ProteinQuantifier_19_out1 to
consume that same renamed path, ensuring it differs from the output owned by
TOPP_ProteinQuantifier_19_qpx. Leave the non-colliding _18 paths unchanged.
🪄 Autofix

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: e7967fdd-15a2-43b4-a5bb-9eba58bd5ea4

📥 Commits

Reviewing files that changed from the base of the PR and between 39c4fe6 and 263ec86.

⛔ Files ignored due to path filters (2)
  • src/tests/topp/ProteinQuantifier_18_input.tsv is excluded by !**/*.tsv
  • src/tests/topp/ProteinQuantifier_20_input.tsv is excluded by !**/*.tsv
📒 Files selected for processing (13)
  • CHANGELOG
  • src/openms/include/OpenMS/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.h
  • src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp
  • src/tests/class_tests/openms/source/PeptideAndProteinQuant_test.cpp
  • src/tests/topp/CMakeLists.txt
  • src/tests/topp/ProteinQuantifier_18_input.consensusXML
  • src/tests/topp/ProteinQuantifier_18_output.txt
  • src/tests/topp/ProteinQuantifier_19_output.txt
  • src/tests/topp/ProteinQuantifier_20_input.consensusXML
  • src/tests/topp/ProteinQuantifier_20_output.txt
  • src/tests/topp/ProteinQuantifier_21_output.txt
  • src/tests/topp/ProteinQuantifier_22_output.txt
  • src/topp/ProteinQuantifier.cpp

Comment on lines +332 to +337
Int best_charge = 0;
if (!getBestCharge_(pep_q.second.abundances, best_charge))
{
continue;
}

// quantify according to the best combination only:
size_t best_fraction = std::get<0>(best_combination);
std::string best_filename = std::get<1>(best_combination);
size_t best_charge = std::get<2>(best_combination);
UInt best_channel = std::get<3>(best_combination);

double abundance = pep_q.second.abundances[best_fraction][best_filename][best_charge][best_channel];
const DesignCell& cell = getDesignCellFromFilenameAndChannel_(best_filename, best_channel);
pep_q.second.total_abundances[cell.sample] = abundance;
pep_q.second.fraction_group_abundances[cell.fraction_group][best_channel] = abundance;
best_charge_by_peptidoform_[pep_q.first] = best_charge;

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Do not skip PSM-count aggregation when no charge is selected.

The continue at line 335 exits the whole pep_quant_ loop body. It therefore also skips the PSM-count aggregation at lines 383-400 and the quant_peptides statistic at line 403. The default (non-best-charge) branch always runs those blocks. A peptidoform with only zero abundances (for example an isobaric reporter that IsobaricChannelExtractor stored as 0.0) then loses its total_psm_counts, so spectral-counting output differs between the two modes for the same input.

Restrict the early exit to the abundance aggregation only.

🐛 Proposed fix to keep PSM counts for peptidoforms without a selected charge
         Int best_charge = 0;
-        if (!getBestCharge_(pep_q.second.abundances, best_charge))
-        {
-          continue;
-        }
-        best_charge_by_peptidoform_[pep_q.first] = best_charge;
-
-        // Retain every observation of the selected charge. Sample abundances span all fractions;
-        // fraction-group/label abundances retain the QPX quantification grain. Explicit zeros are
-        // kept in both maps but did not count as evidence when the charge was selected above.
-        for (const auto& fa : pep_q.second.abundances)
-        {
-          for (const auto& fna : fa.second)
-          {
-            auto charge_it = fna.second.find(best_charge);
-            if (charge_it == fna.second.end()) { continue; }
-            for (const auto& [channel, abundance] : charge_it->second)
-            {
-              const DesignCell& cell = getDesignCellFromFilenameAndChannel_(fna.first, channel);
-              pep_q.second.total_abundances[cell.sample] += abundance;
-              pep_q.second.fraction_group_abundances[cell.fraction_group][channel] += abundance;
-            }
-          }
-        }
+        if (getBestCharge_(pep_q.second.abundances, best_charge))
+        {
+          best_charge_by_peptidoform_[pep_q.first] = best_charge;
+
+          // Retain every observation of the selected charge. Sample abundances span all fractions;
+          // fraction-group/label abundances retain the QPX quantification grain. Explicit zeros are
+          // kept in both maps but did not count as evidence when the charge was selected above.
+          for (const auto& fa : pep_q.second.abundances)
+          {
+            for (const auto& fna : fa.second)
+            {
+              auto charge_it = fna.second.find(best_charge);
+              if (charge_it == fna.second.end()) { continue; }
+              for (const auto& [channel, abundance] : charge_it->second)
+              {
+                const DesignCell& cell = getDesignCellFromFilenameAndChannel_(fna.first, channel);
+                pep_q.second.total_abundances[cell.sample] += abundance;
+                pep_q.second.fraction_group_abundances[cell.fraction_group][channel] += abundance;
+              }
+            }
+          }
+        }
🤖 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 332 - 337, Update the best-charge handling around getBestCharge_ in the
pep_quant_ loop so a missing selected charge skips only abundance aggregation,
not the subsequent PSM-count aggregation and quant_peptides statistic. Preserve
best_charge_by_peptidoform_ updates for selected charges and ensure peptidoforms
with no valid charge still reach the total_psm_counts logic.

Comment thread src/tests/topp/CMakeLists.txt Resolved
@jpfeuffer

Copy link
Copy Markdown
Contributor

This is covered by ProteinGroupArrowExport_test (“fraction groups stay distinct when a sample repeats”), which uses one sample in fraction groups 1 and 4 and asserts two separate QPX rows with independent quantities. So this concern is already addressed in current develop; no additional change is needed in #9847.

I am not sure if this design should be allowed! Exactly the same sample without a technical replication annotation should not be measurable across fraction_groups. Either we implicitly assume those are technical replicates when such a case is found or (probably better) we should error out!

@jpfeuffer

Copy link
Copy Markdown
Contributor

An exception might be Bridge channels across TMT plexes (fraction_groups). In this case I think we need a more flexible sample normalization algorithm however.

I think for qpx this all might be fine as long as sample normalization is off. I agree that if you write it out per "grouped_run" it should be fine.

…t paths

Addresses review findings 11, 12 and 14 on #9847, and updates the ProteomicsLFQ
reference values that the file+channel aggregation fix changes.

writePeptideTable_ ('-peptide_out' with 'best_charge_and_fraction'):
  - the header keyed the design's spectra file paths by fraction group, so all
    fractions of a group collapsed onto whichever file the design listed last
    (11 of 12 files vanished for a 12-fraction group). Now keyed by
    (fraction group, fraction), like the protein table already was.
  - two of the three "no value here" cases emitted nothing instead of 0.0, so a
    peptide absent from a file shifted every later cell of its row one column
    left and the trailing 'fraction' value landed under an abundance header.
    Every (file, channel) cell now always writes a value.
  Pinned by the new TOPP test ProteinQuantifier_28 on a fractionated design.

quantifyPeptides(): a peptidoform with no positive observation skipped the rest
of the loop body via 'continue', which also skipped the PSM-count aggregation.
Spectral counts are identification evidence and must not depend on the
charge-selection flag. (Latent today: PeptideData::psm_counts is never written
anywhere, so the loop it skipped is currently a no-op.)

Tests: the new TOPP tests were numbered 18-22, but 18 and 19 are already taken
by the "_qpx" tests and TOPP_ProteinQuantifier_19 shared a temp output path with
TOPP_ProteinQuantifier_19_qpx. Under a parallel ctest one run could clobber the
other's output between producer and FuzzyDiff. Renumbered to 23-27.

References: nine 'indistinguishable_proteins_N_file_channel_level_abundance'
values across the eight ProteomicsLFQ consensusXML references. Verified rather
than regenerated - rebuilding the same tree with only PeptideAndProteinQuant
reverted isolates these nine lines as the whole effect of the change, and the
unchanged sample-level 'abundances' prove the new values right: both
spectral-counting tests run 'top:N' 0 with 'top:aggregate' sum, where a sample's
cells must sum exactly to its sample-level value, and only the new cells do
(ProteomicsLFQ_4: 19+16, 16+15, 15+10 = 35, 31, 25, against 24, 29, 18 before).
Recomputing the feature-intensity cells from the consensus features independently
reproduces the new values and disagrees with the old ones on exactly the two
cells that change. Everything else in those files is untouched.

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

Copy link
Copy Markdown
Contributor Author

Review response — findings 11–14

Worked through the four findings that were still actionable here. Summary of what changed, what did not, and one correction to the review.

11 — detailed peptide TSV: confirmed, fixed

Both halves reproduce. Running the pre-fix binary on a fractionated two-file design:

"peptide" "protein" "n_proteins" "charge" "abundance|fileB|ch1" "abundance|fileB|ch2" "fraction"
"AAAAAK"  "Protein" 1            2        1                     ← the fraction value, in an abundance column
"CCCCCK"  "Protein" 1            2        300.0                30.0                  2

fileA's two columns are gone — design_filenames was keyed by fraction group, so both fractions collapsed onto the last file — and the rows for peptides not seen in fileB emit no cells at all, so fraction slid two columns left.

Now keyed by (fraction group, fraction), which is what writeProteinTable_ already did correctly, and every (file, channel) cell always writes a value. The sample-level branch keeps its historical header, so TOPP_ProteinQuantifier_1/2/3/14 are byte-identical. New TOPP_ProteinQuantifier_28 pins it; I verified it fails on the pre-fix binary for the right reason.

12 — confirmed mechanically, but the stated impact does not exist

The continue does skip the PSM-count loop, and I have restructured it to if (getBestCharge_(...)) { … }.

But the loop it skipped is dead code today: PeptideData::psm_counts is never written anywhere in OpenMS (repo-wide grep; ConsensusXMLHandler.cpp:974 already documents it — "they are all-zero in every run today"). So total_psm_counts, peptide_psm_counts and total_distinct_peptides are empty regardless of the flag, and nothing was being dropped. PeptideData::psm_count (singular), which is populated, comes from transferPeptideDataToProteins_ and never went through this branch.

The fix is still right — it restores the invariant for whenever those counts get populated upstream — but it could not be given a failing test, since the member is unreachable from the public C++ API.

13 — confirmed as behaviour, deliberately not changed

The retention loop does materialise total_abundances[sample] for an explicit 0.0, and orderBest_ ranks on size(). But this is not new to best-charge mode: the default branch has always done total_abundances[cell.sample] += abundance for every handle, and quantifyFeature_ records zero-intensity handles. So the change makes best-charge mode match the long-standing default rather than diverge from it.

Fixing it only here would make "quantified in a sample" mean two different things depending on a flag. Fixing it globally in selectPeptidesForQuantification_/orderBest_ changes mzTab and QPX output for all isobaric data and churns references broadly. That is a semantics decision, so it is left open rather than made silently — happy to take it either way.

14 — confirmed, renumbered

TOPP_ProteinQuantifier_19_qpx (line 2882) and the new _19 both wrote ${TESTS_TEMP_DIR}/ProteinQuantifier_19_output.tmp. The new tests are renumbered to 23–27 as suggested, fixtures git mv'd, and the stale input names in the reference headers updated.

The eight ProteomicsLFQ references

Root-caused rather than refreshed. Rebuilding the identical tree with only PeptideAndProteinQuant reverted to develop isolates the change's entire effect: nine lines, all indistinguishable_proteins_N_file_channel_level_abundance. Not the sample-level abundances, not fraction_group_level_abundance.

The unchanged sample-level values are what prove the new numbers right. Both spectral-counting tests run top:N 0 + sum, where a sample's cells must decompose it exactly:

ProteomicsLFQ_4   sample level [35, 31, 25]
  old cells [13,11,14,15, 9, 9] -> 24, 29, 18   ✗
  new cells [19,16,16,15,15,10] -> 35, 31, 25   ✓

Same for both groups of ProteomicsLFQ_6. And recomputing the feature-intensity cells independently from the consensus features in the output — "per file, one summed value per peptide over its peptidoforms and charges, top 3, median" — reproduces all six new cells exactly while disagreeing with the old values on precisely the two that changed.

Only those nine lines were edited. That matters because this machine cannot reproduce the references byte-for-byte (feature intensities drift up to 8.4e-5 relative against a 1e-2 FuzzyDiff tolerance), so a wholesale regeneration would have baked hundreds of lines of local noise into them for no reason.

Findings 1–10 and 15

Followed up separately in #9849: 3, 9 and 10 turned out to be reachable and are fixed there, along with 15 (QPXValueValidation_test) and the contract documentation. Notably finding 3 is not covered by the "supported producers" argument — it is ProteomicsLFQ's own seeded output that trips it (79 % unmapped features in the ProteomicsLFQ_3 fixture), and the only ProteomicsLFQ QPX test uses the unseeded configuration, which has none.

#9850 fixes an unrelated pre-existing break found on the way: TOPP_SimpleSearchEngine_DDA passes -Search:decoys auto to a flag and has never run where its fixture exists.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

best_charge_and_fraction now selects one charge per modified peptide using global sample prevalence, aggregates that charge across outputs, and preserves detailed observations. Protein file/channel quantification applies peptide gating and iBAQ normalization. Detailed output and regression coverage were expanded.

Changes

Best-charge selection and detailed protein aggregation

Layer / File(s) Summary
Best-charge selection contract
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.h, CHANGELOG
Defines per-peptidoform charge state and documents global prevalence-based selection, aggregation, and detailed-output behavior.
Global charge selection
src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp
Ranks charges by positive sample count, abundance, and lower-charge tie-break. It aggregates all observations for the selected charge.
Protein file/channel aggregation
src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp
Aggregates selected peptides across peptidoforms and charge states, enforces per-file selection, and applies iBAQ to file/channel values.
Detailed peptide output
src/topp/ProteinQuantifier.cpp
Preserves fraction mappings and emits every file/channel cell, including explicit zero values.
Unit tests
src/tests/class_tests/openms/source/PeptideAndProteinQuant_test.cpp
Covers charge selection, fractionation, aggregation, top-N filtering, annotations, peptidoform merging, and iBAQ normalization.
TOPP fixtures and regression outputs
src/tests/topp/*
Adds ProteinQuantifier cases and expected outputs for file/channel, fractionated, iBAQ, top-N, and detailed peptide behavior. Updates ProteomicsLFQ references.

Sequence Diagram(s)

sequenceDiagram
  participant ProteinQuantifier
  participant PeptideAndProteinQuant
  participant ChargeSelector
  participant ProteinOutput
  ProteinQuantifier->>PeptideAndProteinQuant: quantify peptide observations
  PeptideAndProteinQuant->>ChargeSelector: select charge by prevalence and abundance
  ChargeSelector-->>PeptideAndProteinQuant: selected charge per peptidoform
  PeptideAndProteinQuant->>ProteinOutput: aggregate selected peptides by sample and file/channel
  ProteinOutput-->>ProteinQuantifier: write protein and detailed peptide output
Loading

Possibly related PRs

  • OpenMS/OpenMS#9683: Both change PeptideAndProteinQuant file/channel protein quantification.
  • OpenMS/OpenMS#9793: Both modify file/channel aggregation, top-N handling, and iBAQ normalization.
  • OpenMS/OpenMS#9843: Both preserve and aggregate fraction/file/channel quantification for exports.

Poem

A rabbit counts each charge with care,
Across the samples, everywhere.
Fractions bloom in rows of light,
Zeros mark the cells just right.
Proteins sum, then iBAQ grows—
Clean results in tidy rows.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR addresses all three primary requirements from issue #9796: selecting one charge globally per peptide using sample prevalence and tie-breaking rules, quantifying peptides across all applicable samples, and propagating the selected charge to detailed file/channel output.
Out of Scope Changes check ✅ Passed All changes are within scope of correcting charge selection and related output handling. ProteomicsLFQ reference updates are expected consequences of the corrected quantification algorithm.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main change: correcting ProteinQuantifier charge selection, with relevant test coverage.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/fix-best-charge-and-fraction

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.

🧹 Nitpick comments (3)
src/topp/ProteinQuantifier.cpp (2)

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

Fix brace placement and rename the misleading abundance variable.

The for loops at lines 467 and 468 place the opening brace on the same line as the for statement. The rest of this diff (for example line 480) places the opening brace on its own line. As per coding guidelines: "format C++ with 2-space indentation, Unix line endings, spaces after control-flow keywords, spaces around binary operators, and braces on their own aligned lines; always use braces for blocks."

Separately, at line 468, abundance in the structured binding is a map<UInt, double> (channel → value), not a scalar abundance. It shares its name with the unrelated double abundance declared later at line 489 in a different scope, which makes the function harder to read. Rename it, for example channel_abundances or _ if unused.

🔧 Proposed fix
-          for (const auto& filenames : filename_to_chargemap) {
-            for (const auto& [charge, abundance] : filenames.second) {
+          for (const auto& filenames : filename_to_chargemap)
+          {
+            for (const auto& [charge, channel_abundances] : filenames.second)
+            {
               charge_of_peptide.insert(charge); // store the charge state for this peptide
             }
           }
🤖 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/topp/ProteinQuantifier.cpp` around lines 464 - 471, Update the nested
loops in the charge-state collection block to place each opening brace on its
own aligned line, preserving the existing two-space indentation and brace style.
In the structured binding within the loop over filename_to_chargemap, rename the
unused abundance binding to a descriptive name such as channel_abundances,
without changing the iteration or charge_of_peptide behavior.

Source: Coding guidelines


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

Extract the (fraction_group, fraction) → filename map building into a shared helper.

Lines 399-413 rebuild the same map that writeProteinTable_ already builds at lines 605-613, both by iterating msfile_section. The bug this PR fixes (finding 11: keying by fraction group alone collapsed all fractions onto one filename) affected one of these two independent copies. Keeping two separate implementations of the same mapping risks the same class of bug recurring if only one copy is updated in the future.

Extract a private helper, for example buildDesignFractionFilenameMap_(const ExperimentalDesign& ed), and call it from both writePeptideTable_ and writeProteinTable_.

🤖 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/topp/ProteinQuantifier.cpp` around lines 399 - 413, Extract the loop that
builds design_group_fraction_filename by iterating msfile_section into a private
helper method (such as buildDesignFractionFilenameMap_) that accepts the
ExperimentalDesign as a parameter and returns the map keyed by (fraction_group,
fraction). Replace the current loop in writePeptideTable_ with a call to this
helper. Update the existing duplicate loop in writeProteinTable_ at lines
605-613 to also call this shared helper, eliminating the separate implementation
and preventing future divergence between the two independent copies.
src/tests/topp/ProteinQuantifier_27_output.txt (1)

2-4: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Make the top-N regression distinguish zero observations.

The top:N=3 setting on Line [2] selects all three peptides. The zero-only record on Line [4] cannot detect whether explicit zeros affect quantified-sample coverage or top-N ranking. Add at least four candidate peptides with mixed zero and positive selected-charge observations, then assert the selected top-N peptides and aggregate.

🤖 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/topp/ProteinQuantifier_27_output.txt` around lines 2 - 4, The top-N
regression fixture does not distinguish zero observations from missing coverage.
Update the test data and expected output for the top:N=3, top:aggregate=median
case to include at least four candidate peptides with mixed zero and positive
selected-charge observations, and assert which three peptides are selected along
with their resulting median aggregate.
🤖 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.

Nitpick comments:
In `@src/tests/topp/ProteinQuantifier_27_output.txt`:
- Around line 2-4: The top-N regression fixture does not distinguish zero
observations from missing coverage. Update the test data and expected output for
the top:N=3, top:aggregate=median case to include at least four candidate
peptides with mixed zero and positive selected-charge observations, and assert
which three peptides are selected along with their resulting median aggregate.

In `@src/topp/ProteinQuantifier.cpp`:
- Around line 464-471: Update the nested loops in the charge-state collection
block to place each opening brace on its own aligned line, preserving the
existing two-space indentation and brace style. In the structured binding within
the loop over filename_to_chargemap, rename the unused abundance binding to a
descriptive name such as channel_abundances, without changing the iteration or
charge_of_peptide behavior.
- Around line 399-413: Extract the loop that builds
design_group_fraction_filename by iterating msfile_section into a private helper
method (such as buildDesignFractionFilenameMap_) that accepts the
ExperimentalDesign as a parameter and returns the map keyed by (fraction_group,
fraction). Replace the current loop in writePeptideTable_ with a call to this
helper. Update the existing duplicate loop in writeProteinTable_ at lines
605-613 to also call this shared helper, eliminating the separate implementation
and preventing future divergence between the two independent copies.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ec950d1a-0670-40dc-922d-ed0c5f995314

📥 Commits

Reviewing files that changed from the base of the PR and between 263ec86 and 42e52d6.

⛔ Files ignored due to path filters (2)
  • src/tests/topp/ProteinQuantifier_23_input.tsv is excluded by !**/*.tsv
  • src/tests/topp/ProteinQuantifier_25_input.tsv is excluded by !**/*.tsv
📒 Files selected for processing (20)
  • CHANGELOG
  • src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp
  • src/tests/topp/CMakeLists.txt
  • src/tests/topp/ProteinQuantifier_23_input.consensusXML
  • src/tests/topp/ProteinQuantifier_23_output.txt
  • src/tests/topp/ProteinQuantifier_24_output.txt
  • src/tests/topp/ProteinQuantifier_25_input.consensusXML
  • src/tests/topp/ProteinQuantifier_25_output.txt
  • src/tests/topp/ProteinQuantifier_26_output.txt
  • src/tests/topp/ProteinQuantifier_27_output.txt
  • src/tests/topp/ProteinQuantifier_28_output.txt
  • 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/topp/ProteinQuantifier.cpp
🚧 Files skipped from review as they are similar to previous changes (3)
  • CHANGELOG
  • src/tests/topp/CMakeLists.txt
  • src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Finding 13 — followed up in #9851

Taking the semantics question back off the table: it is fixed, in its own PR, scoped so that no quantity moves.

The mechanism, precisely. IsobaricChannelExtractor writes a reporter it could not find — or one below min_reporter_intensity — as 0.0. quantifyFeature_ records that handle like any other, so the sample key exists with value 0; total_abundances and then peptide_abundances carry it forward. selectPeptidesForQuantification_ reads ab.second.size() — the number of keys, not of positive values. A TMT peptide with signal in 2 of 10 channels therefore reports size() == 10.

Narrower than the finding states, and worse where it lands. Both size()-dependent branches are gated on consensus:fix_peptides, which defaults to false and is set by no OpenMS tool (ProteomicsLFQ sets only top:include_all). But inside that mode, top:N 0 is not merely mis-ranked: "all peptides that occur in every sample" admits every peptide seen anywhere, so the filter stops filtering entirely.

Not a regression of this PR. The default path has always materialised zeros this way. The old best-charge path did not — but only because it assigned exactly one sample entry, for the single winning (fraction, file, charge, channel) combination, which is the bug #9796 is about. "Before" was not better behaviour; it was the artefact of quantifying each peptide in exactly one sample.

Why it is a defect at all. The class has already ruled on what a zero means, twice in the opposite direction: normalizePeptides_() excludes zeros from its medians — with a comment citing MSstatsTMT, isobar and scp — and the charge-prevalence count in getBestCharge_() skips <= 0.0. Two places treat a zero as missing, one treated it as an observation. That inconsistency is the real finding.

Correcting something I said earlier in this thread. I wrote that fixing this globally would change mzTab and QPX output for all isobaric data. That is wrong if the fix is scoped to the counting rather than the data. #9851 changes only selectPeptidesForQuantification_ and orderBest_ to count positive entries; total_abundances is untouched, so no abundance, mzTab or QPX value moves — only which peptides are selected, and only under fix_peptides. The five in-tree fix_peptides tests use a fixture with no zero intensities, so no reference file changes.

Two class-test sections cover the two branches on an isobaric fixture, which nothing had before; both were confirmed to fail without the fix (600 instead of 100, and 1000 instead of 100).


All 15 findings are now resolved or dispositioned:

findings where
11, 12, 14 fixed here
13 #9851
3, 9, 10, 15 #9849 (plus the QPX input contract, written down once)
1, 2, 4, 5, 6, 7, 8 accepted as a deliberate tightening of the QPX contract; ProteomicsLFQ and IsobaricWorkflow are the supported producers and satisfy it by construction

Unrelated pre-existing break found along the way: #9850.

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

CodeRabbit review — both items were already addressed

Both comments were posted against 263ec8617b, before the follow-up commit 42e52d6919. Confirmed against the current head:

1. "Do not skip PSM-count aggregation when no charge is selected" — correct, and fixed exactly as proposed: the early exit became if (getBestCharge_(...)) { … } so the PSM-count aggregation and the quant_peptides statistic still run. One clarification worth recording: the impact described cannot be observed today, because PeptideData::psm_counts is never written anywhere in OpenMS (ConsensusXMLHandler.cpp:974 already documents this), so the loop the continue skipped is currently a no-op. The fix restores the invariant for when those counts are populated upstream; it could not be given a failing test, since the member is unreachable from the public API.

2. "Rename the temporary output path; it collides with TOPP_ProteinQuantifier_19_qpx" — correct, and fixed by renumbering the new tests to 23–27 rather than renaming one path, which also resolves the shared-numbering ambiguity flagged for the _18 pair. Every ProteinQuantifier_*_output.tmp* path is now written by exactly one producer.

@timosachsenberg
timosachsenberg merged commit d23a9f8 into develop Aug 4, 2026
34 checks passed
@timosachsenberg
timosachsenberg deleted the codex/fix-best-charge-and-fraction branch August 4, 2026 14:19
timosachsenberg added a commit that referenced this pull request Aug 4, 2026
…e a partial collection (#9849)

* [FIX,TEST] QPX: separate unmapped features, never leave a partial collection

Three defects in the QPX export contract added by #9846/#9843, found reviewing
#9847. Tightening the contract is fine where the producers can satisfy it; these
are cases where they cannot, or where the enforcement is not clean.

1. Feature primary key refused maps OpenMS itself produces.
   The key is (peptidoform, charge, run_file_name, rt). QPX permits unmapped
   features and ConsensusMapArrowExport writes them with an empty peptidoform, so
   for those rows the key collapses to (charge, run_file_name, rt) - and 'rt' is
   narrowed to float32 on write, one ULP being 244 us at 3000 s. Two co-eluting
   unmapped features of the same charge in one run then share a key although they
   are plainly different features, and the whole table is refused.
   Not a corner case for the tools that write QPX: ProteomicsLFQ with seeds
   leaves 79 % of the ProteomicsLFQ_3 fixture's consensus features unidentified,
   and a real run carries tens of thousands, where the birthday bound over the
   ~2.2e7 representable float32 retention times makes a collision expected. The
   only ProteomicsLFQ QPX test uses the unseeded configuration, whose features are
   all identified, so nothing exercised it.
   'observed_mz' - written one column over, previously excluded - joins the key.
   Genuine duplicates (same run, charge, rt AND m/z) are still refused.

2. A refused collection left its earlier files behind.
   requireExportable() catches everything decidable from the input, but a view can
   still refuse a row it only sees while building its table, and a write can fail
   on I/O; by then quantms.feature.parquet is on disk, and a directory holding it
   without a PSM file is indistinguishable from a complete export of a smaller
   dataset. New QPXCollectionExport::Transaction scope guard: constructed before
   the first write, committed after the last, and on any other exit - a view
   returning false, a writer throwing, an early return - it removes every
   collection file present. Used by ProteinQuantifier, ProteomicsLFQ and
   IsobaricWorkflow. Guarding the scope rather than enumerating the failure sites
   covers the next refusal mode without anyone having to remember it.

3. QPXFile::exportToParquetStreaming() left a truncated PSM file.
   One validator spans all batches so it can fail on a late one, and the writer
   and sink are closed regardless, so the footer is written and the file reads as
   a valid, merely smaller, PSM table. It is now removed, matching what
   ConsensusMapArrowExport's streaming writer already did for the same situation.

Each fix ships with a test that was confirmed to fail without it: the feature-key
section fails at the validate() of two co-eluting unmapped features, and the
streaming section at TEST_FALSE(File::exists(duplicate_file)).

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

* [DOC,TEST] QPX: record the input contract once, and test the validator directly

Documentation and tests only; no behaviour change.

The QPX input contract was not written down anywhere a user could find it: the
tools that offer -out_qpx just fail with UnableToCreateFile, and the four
requirements a foreign consensus map can miss (a scan per identification, a
resolvable origin file, uniqueness per (peptidoform, charge, run, scan), and a
channel label from the QPX vocabulary) were only discoverable by reading
QPXValueValidation. It is now stated on that class - the code that enforces it,
so it cannot drift - and nowhere else. ProteinQuantifier's -out_qpx parameter and
its documentation page point there rather than restating it, naming ProteomicsLFQ
and IsobaricWorkflow as the producers that satisfy the contract by construction.

QPXValueValidation had no test file of its own although every sibling QPX class
has one, and it is a 600-line OPENMS_DLLAPI class that decides whether an export
happens at all. QPXValueValidation_test covers all three views: the psm view's
empty-scan, empty/blank run_file_name and duplicate-key refusals, the feature
view's separation of unmapped rows by observed_mz and its non-finite coordinate
refusals, the documented statefulness (a validator spans batches so a key
repeated after a batch boundary is caught; a rejected batch does not advance the
key state; reset() starts a new file), the schema-mismatch path, multi-chunk
columns, null and 0-row tables, and Result::toString().

The invalid inputs are built through the exporters rather than by patching
columns, so each section exercises a shape a producer really emits - an
identification without a spectrum reference, or the one-MS2-on-two-features
duplication IDMapper creates.

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

* [FIX,TEST] Transaction must not delete a collection that predates it

Addresses the CodeRabbit review on #9849.

The scope guard removed every collection file in the output directory on a failed
export, including files that were already there. Re-running a pipeline into the
same -out_qpx directory is the normal case, so a failed re-run destroyed the
previous, complete result. The test encoded that behaviour by creating its stub
files before constructing the guard.

The guard now records which of the three files exist at construction and removes
only the ones this export created. A run that fails after overwriting a
pre-existing file still leaves the directory mixing two exports - that cannot be
undone without staging - so the destructor names the surviving files in a warning
instead of letting the directory look coherent. The test creates its files inside
the guard's lifetime, as an export does, and gains coverage that a failed export
preserves a complete previous collection; that assertion fails without the fix.

Also from the same review:
- QPXFile and ConsensusMapArrowExport left a zero-byte .parquet behind when
  parquet::arrow::FileWriter::Open failed: arrow::io::FileOutputStream::Open had
  already created and truncated the file, and this early return happens before
  the close-and-remove block that covers every later failure. Both now close and
  remove it. (ConsensusMapArrowExport is not otherwise part of this PR's changes,
  but the two writers are deliberately symmetric here.)
- Doxygen: the Transaction constructor, destructor and commit() use /** */ with
  @brief, and the constructor documents @PARAM[in] directory.
- Style: braces on their own aligned lines, and '\n' instead of std::endl in the
  new logging.

Verified end to end: a failed export into a fresh directory still leaves it
empty, and a failed export into a directory holding a previous collection leaves
all three of its files in place with the warning.

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

* [FIX] Link QPXValueValidation_test against Arrow

Fixes the windows-2025/cl.exe build failure on this branch: 37 LNK2019s, all
unresolved __declspec(dllimport) arrow:: symbols, on
QPXValueValidation_test.exe.

The test was added to executables.cmake without the matching
target_link_libraries(... ${OPENMS_ARROW_TARGET} ${OPENMS_PARQUET_TARGET}) that
every other Arrow-using class test carries. It builds its invalid inputs with
arrow::FloatBuilder and ArrayData::Make rather than through the exporters -
deliberately, so each section exercises a shape a producer really emits - so it
needs Arrow itself, not just what OpenMS re-exports. On Linux/macOS libOpenMS
statically links Arrow and re-exports its symbols, so the link happens to
succeed; on Windows they are dllimport and nothing satisfies them.

QPXCollectionExport_test, added alongside it, uses no Arrow type and correctly
stays unlinked.

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

* [FIX,TEST] Remove the partial file when a one-shot Parquet write fails

This PR taught both streaming writers to clean up after themselves, but the
one-shot writers next to them still leak. arrow::io::FileOutputStream::Open
creates and truncates the file before the table is written, so a write that
fails afterwards leaves a fragment carrying little more than the Parquet magic
bytes - no footer, so a reader reports it as corrupt rather than as the smaller
table it looks like.

Two sites, both now closing the stream and removing the file on any failure
after the open:

- ConsensusMapArrowExport::exportToParquet, directly above the streaming
  function this PR already fixed.
- ArrowIOHelpers::writeTableToParquet, the shared path behind the psm, pg,
  OpenSwath and MSExperiment exports.

ConsensusMapArrowExport::exportToParquet additionally closes explicitly instead
of leaving it to the stream's destructor, which discards the error: the final
flush is where a full disk surfaces, and that used to be reported as success
with a truncated file on disk.

Inside the three tools this was contained by QPXCollectionExport::Transaction,
which is why it did not show up as a bug; it was not contained for pyOpenMS and
library callers, or for ProSE, whose -out_qpx layout the guard cannot cover.

Each fix ships with a test confirmed to fail without it - both at the
TEST_FALSE(File::exists(...)) line, with the write failing for the intended
reason. A row group size of 0 is refused by Parquet for a non-empty table, which
reaches a post-open write failure deterministically on every platform.

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

* [TEST] Cover -out_qpx from the seeded ProteomicsLFQ configuration

The feature-key defect this PR fixes reached develop because the only
ProteomicsLFQ QPX test runs -targeted_only true, whose consensus features are
all identified: 0 of its 60 feature rows are unmapped, so nothing ever exported
the shape the key could not distinguish. The class test added here reproduces
that shape synthetically, but nothing asserts that the tool still produces it.

New TOPP_ProteomicsLFQ_qpx_seeds runs TOPP_ProteomicsLFQ_3's seeded
configuration with -out_qpx: 210 of 298 feature rows are unmapped, and all three
collection files must exist afterwards. Kept as a separate run rather than
folded into TOPP_ProteomicsLFQ_3 so no reference file is touched.

What it guards is that the shape reaches the exporter and clears it end to end.
It is not a reproducer for the float32-rt collision itself - measured on the
produced table, the pre-fix key happens not to collide at this fixture's size -
and the comment says so rather than implying more; ConsensusMapArrowExport_test
covers that directly.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
timosachsenberg added a commit that referenced this pull request Aug 4, 2026
Same defect as at the sample level, in the array that feeds the
abundance|<file>|ch<N> columns and the QPX pg view. Stacked on #9847, which
rewrites this function.

calculateFileAndChannelLevelProteinAbundances_ contributed one value per selected
peptide and (fraction, file, channel) cell whether or not that peptide had a
reporter there. IsobaricChannelExtractor writes a reporter it could not find - or
one below 'min_reporter_intensity' - as an explicit 0.0 and inserts the handle
regardless, so undetected peptides both satisfied the per-file "at least N
peptides" gate and entered the aggregate. With the default median, a cell in
which most of a protein's peptides went undetected was reported as 0: absent from
a channel the protein was measured in.

Only detected (positive) abundances are collected and counted now. 'sum' is
numerically unaffected. A cell whose peptides were all undetected still keeps its
zero entry, so it does not drop out of the parallel (filename, channel,
abundance) arrays - the previous 'if (all_abundances.empty()) continue' guard was
unreachable, since the key was only ever created by a push, and is now the case
that must NOT be skipped.

The IsobaricWorkflow_1 reference shows it on real data: its only changed line is
the file+channel array of group 1 (PROTB, two peptides). MYFINGERK has no
reporter in channels 1, 3, 6, 7, 9 and 10, exactly the six channels whose value
doubles - the old median of (GIRAFFERK, 0) reported half the single measurement.
The four channels where both peptides were detected are byte-identical.

Note the reference is internally inconsistent until #9851 lands: the sample-level
'abundances' array in the same file still carries the halved values, because that
is the other half of this fix and is independent of #9847. The two agree once
both are merged.

Label-free data is unaffected: a feature that was not found has no entry at all.
129/129 PeptideAndProteinQuant/ProteinQuantifier/IsobaricWorkflow/ProteomicsLFQ
tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VcFtJVe1PcMsBzMnnnpWBJ
timosachsenberg added a commit that referenced this pull request Aug 4, 2026
…ptide (#9851)

* [FIX,TEST] fix_peptides: a stored zero is not a sample the peptide occurs in

'consensus:fix_peptides' ranks peptides by the size() of their sample->abundance
map. That map has an entry wherever quantifyFeature_ saw a feature handle, and
IsobaricChannelExtractor writes a reporter it could not find - or one below
'min_reporter_intensity' - as an explicit 0.0, so every peptide of an isobaric
run reported the full channel count:

  - with 'top:N' 0, "all peptides that occur in every sample" admitted every
    peptide seen anywhere; the filter stopped filtering.
  - with 'top:N' > 0, all peptides tied at the channel count, so the tie-break by
    total abundance decided alone and a peptide with a large signal in 2 of 10
    channels took the slot from one genuinely measured in 6.

Both now count only the samples with a positive abundance, via one helper. This
is the rule the class already applies elsewhere and the inconsistency is the
actual defect: normalizePeptides_() excludes zeros from its medians, with a
comment explaining that a zero means "not detected" rather than "no protein",
and the charge-prevalence count in 'best_charge_and_fraction' does the same.

Scoped deliberately to the counting. total_abundances is untouched, so peptide
and protein abundances, mzTab and QPX values do not move; only which peptides are
selected changes, and only when 'consensus:fix_peptides' is enabled - off by
default and set by no OpenMS tool. The five in-tree fix_peptides tests
(TOPP_ProteinQuantifier_7/8/9/12/13) use a fixture with no zero intensities, so
no reference file changes.

Two class-test sections cover the two branches on an isobaric fixture, which
nothing had before. Both were confirmed to fail without the fix, reporting 600
instead of 100 (the undetected peptide admitted) and 1000 instead of 100 (the
taller peptide taking the top:N slot).

Reported as finding 13 of the #9847 review.

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

* [FIX,TEST] protein aggregation: a stored zero is not a detected peptide

Third and most consequential site of the same defect: calculateProteinAbundances_
aggregated peptides that were never detected, so an isobaric protein could be
reported as absent from a sample it was measured in.

quantifyFeature_ records every feature handle, and IsobaricChannelExtractor
writes a reporter it could not find - or one below 'min_reporter_intensity' - as
an explicit 0.0 and inserts the handle regardless
(IsobaricChannelExtractor.cpp:620/658/663). Every peptide of an isobaric run
therefore carries an entry for every channel. Those entries were pushed into the
per-sample list, where they both counted towards the "enough peptides in this
sample" gate and fed the aggregate: with the default median, a channel in which
most of a protein's peptides went undetected got a median of exactly 0; with mean
it was diluted towards 0.

That is the artefact normalizePeptides_() already excludes zeros to avoid, and
the opposite of what the tool documents - "(intensity weighted) mean and median
ignore missing cases, averaging only present values", with only 'sum' documented
as treating missing values as zero.

Only detected (positive) abundances are aggregated and counted now. 'sum' is
numerically unaffected, since summing zeros changes nothing. Samples are tracked
separately from their values, so a sample in which nothing was detected keeps its
zero entry under 'top:include_all' rather than disappearing from the output.

Unlike the two earlier sites this is not opt-in: IsobaricWorkflow sets
'top:include_all', otherwise takes the defaults, and passes no aggregation
override - and so does quantms, whose ISOBARIC_WORKFLOW module supplies no
-ProteinQuantification:* arguments and has no ext.args.

The IsobaricWorkflow_1 reference shows it on real data. Its only changed line is
the protein-abundance array of group 1 (PROTB, two peptides): MYFINGERK has no
reporter in channels 1, 3, 6, 7, 9 and 10, which are exactly the six channels
whose value doubles - the old median of (GIRAFFERK, 0) reported the protein at
half its single measurement. The four channels where both peptides were detected
are byte-identical.

Label-free data is unaffected: a feature that was not found has no entry at all,
rather than an entry of zero. All 97 ProteomicsLFQ/MzTab tests are unchanged.

Both new class-test sections were confirmed to fail without the fix, reporting 0
(median) and 333.33 (mean) where the protein was measured at 1000.

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

* [STYLE] expand a short if-block per review

Addresses the CodeRabbit nitpick on #9851. The repository's own .clang-format
permits the compact form (AllowShortBlocksOnASingleLine: true), and the file
already contains several instances of it, so this is cosmetic rather than a
correctness or guideline fix - applied for consistency with the same change made
on #9849.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
timosachsenberg added a commit that referenced this pull request Aug 4, 2026
Same defect as at the sample level, in the array that feeds the
abundance|<file>|ch<N> columns and the QPX pg view. Stacked on #9847, which
rewrites this function.

calculateFileAndChannelLevelProteinAbundances_ contributed one value per selected
peptide and (fraction, file, channel) cell whether or not that peptide had a
reporter there. IsobaricChannelExtractor writes a reporter it could not find - or
one below 'min_reporter_intensity' - as an explicit 0.0 and inserts the handle
regardless, so undetected peptides both satisfied the per-file "at least N
peptides" gate and entered the aggregate. With the default median, a cell in
which most of a protein's peptides went undetected was reported as 0: absent from
a channel the protein was measured in.

Only detected (positive) abundances are collected and counted now. 'sum' is
numerically unaffected. A cell whose peptides were all undetected still keeps its
zero entry, so it does not drop out of the parallel (filename, channel,
abundance) arrays - the previous 'if (all_abundances.empty()) continue' guard was
unreachable, since the key was only ever created by a push, and is now the case
that must NOT be skipped.

The IsobaricWorkflow_1 reference shows it on real data: its only changed line is
the file+channel array of group 1 (PROTB, two peptides). MYFINGERK has no
reporter in channels 1, 3, 6, 7, 9 and 10, exactly the six channels whose value
doubles - the old median of (GIRAFFERK, 0) reported half the single measurement.
The four channels where both peptides were detected are byte-identical.

Note the reference is internally inconsistent until #9851 lands: the sample-level
'abundances' array in the same file still carries the halved values, because that
is the other half of this fix and is independent of #9847. The two agree once
both are merged.

Label-free data is unaffected: a feature that was not found has no entry at all.
129/129 PeptideAndProteinQuant/ProteinQuantifier/IsobaricWorkflow/ProteomicsLFQ
tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VcFtJVe1PcMsBzMnnnpWBJ
timosachsenberg added a commit that referenced this pull request Aug 4, 2026
#9852)

* [FIX,TEST] file+channel level: a stored zero is not a detected peptide

Same defect as at the sample level, in the array that feeds the
abundance|<file>|ch<N> columns and the QPX pg view. Stacked on #9847, which
rewrites this function.

calculateFileAndChannelLevelProteinAbundances_ contributed one value per selected
peptide and (fraction, file, channel) cell whether or not that peptide had a
reporter there. IsobaricChannelExtractor writes a reporter it could not find - or
one below 'min_reporter_intensity' - as an explicit 0.0 and inserts the handle
regardless, so undetected peptides both satisfied the per-file "at least N
peptides" gate and entered the aggregate. With the default median, a cell in
which most of a protein's peptides went undetected was reported as 0: absent from
a channel the protein was measured in.

Only detected (positive) abundances are collected and counted now. 'sum' is
numerically unaffected. A cell whose peptides were all undetected still keeps its
zero entry, so it does not drop out of the parallel (filename, channel,
abundance) arrays - the previous 'if (all_abundances.empty()) continue' guard was
unreachable, since the key was only ever created by a push, and is now the case
that must NOT be skipped.

The IsobaricWorkflow_1 reference shows it on real data: its only changed line is
the file+channel array of group 1 (PROTB, two peptides). MYFINGERK has no
reporter in channels 1, 3, 6, 7, 9 and 10, exactly the six channels whose value
doubles - the old median of (GIRAFFERK, 0) reported half the single measurement.
The four channels where both peptides were detected are byte-identical.

Note the reference is internally inconsistent until #9851 lands: the sample-level
'abundances' array in the same file still carries the halved values, because that
is the other half of this fix and is independent of #9847. The two agree once
both are merged.

Label-free data is unaffected: a feature that was not found has no entry at all.
129/129 PeptideAndProteinQuant/ProteinQuantifier/IsobaricWorkflow/ProteomicsLFQ
tests pass.

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

* [FIX,TEST] fraction group level: a stored zero is not a detected peptide

The third and last copy of this aggregation. calculateFractionGroupLevelProteinAbundances_
pushed every stored abundance into its per-(fraction group, label) cell, zeros
included, so undetected peptides both satisfied its 'top_n' gate and dragged the
cell's median or mean towards zero - exactly what the sample level (#9851) and
the file+channel level (the commit before this one) already fix.

It now contributes only positive abundances while still touching every cell the
selected peptides reach, so a cell whose peptides all went undetected reports
zero rather than dropping out. Same idiom as its two siblings.

This is not a theoretical third site. The three levels describe one measurement
at different granularities and must agree where the granularities coincide, and
they did not: IsobaricWorkflow_1 is one file x 10 channels, so a cell IS a
sample, yet its fraction-group array sat at exactly half the sample-level values
in the six channels where a peptide went undetected - the signature of
mean(x, 0). All three arrays are now byte-identical there, which is the
invariant, and that one line of IsobaricWorkflow_1_out.consensusXML is the only
reference value that moves. The array feeds ProteinData::fraction_group_abundances,
which is what the QPX 1.1 pg view is keyed on.

The new class-test section mirrors the file+channel one on the same fixture and
additionally asserts the two levels agree. Confirmed to fail without the fix:
the cell reports 0 instead of 1000 (lines 1732/1737), the top_n gate section
fails at 1774, and TOPP_IsobaricWorkflow_1_out1 fails once the tool is re-run.

176 tests across PeptideAndProteinQuant, ProteinQuantifier, IsobaricWorkflow,
ProteomicsLFQ, MzTab and QPX pass.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants