Skip to content

[FIX] ProteinQuantifier: file+channel level protein abundances follow the same policy as the sample level - #9793

Closed
timosachsenberg wants to merge 6 commits into
developfrom
fix/protein-quantifier-file-channel-level-aggregation
Closed

timosachsenberg wants to merge 6 commits into
developfrom
fix/protein-quantifier-file-channel-level-aggregation

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Found while investigating #4763 (modification handling in ProteinQuantifier) — unrelated to that issue's actual question, but in the same code.

ProteinData::channel_level_abundances holds protein abundances per (file, channel) cell, the finer-grained sibling of the per-sample ProteinData::total_abundances. A sample is a (file, label) pair of the experimental design, so the two coincide 1:1 only when the design is unfractionated; under fractionation one sample spans all fraction files of its fraction group at that label, i.e. one sample maps to N cells. It feeds:

  • the abundance|<file>|ch<N> columns of ProteinQuantifier -file_and_channel_level_output true
  • annotateQuantificationsToProteins(), and through it the per-run intensities of the QPX pg.parquet export (ProteinGroupArrowExport.cpp:351-353) — this is IsobaricWorkflow's route to these values. mzTab is not a consumer: MzTab.cpp:1605 reads only float array 0, the sample-level abundances
  • PeptideAndProteinQuant_ProteinData.channel_level_abundances in pyOpenMS

It was computed by a different set of rules than the sample-level abundances, in four ways.

1. Only one peptidoform contributed

calculateFileAndChannelLevelProteinAbundances_() breaks after the first peptidoform matching the protein group leader, while the sample-level path sums all peptidoforms of an unmodified sequence in transferPeptideDataToProteins_(). Which peptidoform won was decided by AASequence::operator< — arbitrary with respect to abundance.

Peptidoforms at 10 and 90, top:N=0, aggregate=sum: sample cell 100, detailed cell 10.

2. top:N counted charge states, not peptides

The same loop pushed one entry per raw (peptidoform, charge) cell, so top:N ranked and truncated charge states, and the "enough peptides?" gate was inflated by them — one peptide observed in three charge states passed a top:N of 3 while the sample-level path correctly dropped it.

3. A cell that failed top:N kept an un-aggregated sum

transferPeptideDataToProteins_() pre-filled the map with a raw += sum over all peptides/peptidoforms/charges, and it was never cleared. Whenever the aggregation step then declined to quantify a cell, that sum survived — a positive value exactly where the value should have been absent.

4. iBAQ normalized only half the output

performIbaqNormalization_() divided only total_abundances by the theoretical peptide count, leaving the detailed values as raw summed intensity, too high by the protein-dependent divisor.

Fix

  • one value per selected peptide and (fraction, file, channel) cell, summed over peptidoforms and charge states, mirroring quantifyPeptides();
  • the pre-fill is removed, so the map is owned solely by the aggregation step, just as total_abundances is owned solely by calculateProteinAbundances_();
  • iBAQ normalizes channel_level_abundances too.

The default ProteinQuantifier sample columns and the mzTab output read total_abundances and are unaffected.

Behaviour change worth stating plainly: per-file gating is now visible

Peptide selection and aggregation for these cells are applied per file. That is deliberate — they are per-file values — but removing the pre-fill (#3) makes a consequence visible that was previously masked:

For a fractionated design, a protein can be quantified at the sample level while every one of its (file, channel) cells is reported as absent, because the top:N peptide-count requirement is checked against the peptides of one fraction file rather than the union across fractions. Before this PR those cells were not absent — they carried the fabricated raw sum from #3, which obeyed neither top:N nor top:aggregate. So the old output was populated but wrong; the new output is honest about having declined to quantify.

This is intentional and kept as-is, but it was undocumented, so this PR documents it:

  • a new "Output granularity: samples vs. files and channels" section in the ProteinQuantifier doxygen
  • an expanded file_and_channel_level_output parameter description
  • a comment at the top of calculateFileAndChannelLevelProteinAbundances_()

Escape hatches, both pinned by tests: top:N 0 with top:aggregate sum makes the cells decompose the sample value exactly; top:include_all bypasses the per-file count gate.

Unfractionated isobaric data is unaffected either way. IsobaricChannelExtractor::registerChannelsInOutputMap() emits one file whose column headers differ only in label/channel_id, so every (file, channel) cell is exactly one sample and the two granularities cannot disagree. Fractionated isobaric is covered too: IsobaricWorkflow overrides the library default with pq_defaults.setValue("top:include_all", "true"), which short-circuits the per-file gate.

Tests

The path had no unit coverage at all. Eight sections are added to PeptideAndProteinQuant_test, each on a synthetic ConsensusMap/ExperimentalDesign. Five are regression tests, verified to fail before and pass after:

Section Before
must sum all peptidoforms got 10, expected 100
top:N must count peptides, not charge states fileA present; 1 peptide in 3 charges passed N=3
must not keep un-aggregated sums fileA present with a raw 12.0 that never passed top:N
top:N truncation must rank peptides (aggregate=mean) got 90, expected 135
iBAQ must also normalize the file+channel level got 300, expected 100

Three more pin behaviour rather than fix it:

Section Fails on old code? Role
fractionated: cells decompose the sample for sum no pins the top:N 0 + sum invariant
fractionated: top:N is enforced per file, not per sample yes pins the all-cells-absent behaviour described above
isobaric: one file, N channels (annotateQuantificationsToProteins) no first coverage of the QPX annotation route; pins that cell == sample for the isobaric shape

The last one exists because annotateQuantificationsToProteins() — how IsobaricWorkflow consumes this data — had no coverage, and IsobaricWorkflow itself still has no TOPP tests (src/tests/topp/CMakeLists.txt has the block commented out under # TODO). Worth a follow-up.

TOPP tests ProteinQuantifier_18 through _22 are added, exercising the detailed output end-to-end on inputs with real peptidoform/charge structure and on a fractionated design; _22 fails on old code. The pre-existing ProteinQuantifier_17 has an input of two peptides with a single peptidoform and a single charge each, run with -top:include_all, so it cannot trigger any of the four conditions — it only pins the column layout.

No reference files change.

Deliberately not fixed here — filed as #9796

best_charge_and_fraction is inconsistent between the two granularities for a separate reason: it writes PeptideData::total_abundances but never prunes PeptideData::abundances, which the detailed path reads. On top of that getBest_() hardcodes its occurrence counter to 1, so the "most prevalent charge observed of each peptide" its parameter documentation promises is never computed — it degenerates to argmax over raw cell abundance, and because the chosen tuple includes the filename and channel, each peptide ends up quantified in exactly one sample with every other sample silently zeroed. Fixing that changes sample-level numbers (ProteinQuantifier_2 and _17 references) and needs a semantics decision first, so it is tracked separately in #9796 and only cross-referenced from a comment here.

Review notes

Reviewed again with codex. It confirmed all four defects and independently reproduced every asserted test number by hand. Three things it raised, and what I did:

  • mzTab is not a consumer. An earlier revision of this description said these values reach mzTab; they do not (MzTab.cpp:1605 reads only float array 0). Corrected here, in the CHANGELOG and in the test comment.
  • The new documentation overstated consistency. "Same peptide-level policy" and "top:N 0 + sum decomposes exactly" both hold only while best_charge_and_fraction is off. Caveat added to the doxygen section and the parameter description.
  • Pre-existing, not fixed here: pd.channel_level_abundances[filename][channel] = ... drops the fraction from the collection key. For consensusXML input that is safe — readQuantData throws on an ambiguous (basename, label) → fraction mapping — but the idXML path matches by File::basename and stores File::stemName with no such guard, so two design rows whose stems collide (run.mzML / run.mzML.gz) would let the higher fraction overwrite the lower. The sample-level path merges (+=) in the same situation, so the two granularities diverge. Identical on develop; worth a guard mirroring the consensusXML check, but out of scope here.
  • Also noted: selectPeptidesForQuantification_ can resize(top_n) past the end of what orderBest_ returned, padding with empty strings. They are inert (both downstream lookups miss), so no wrong output; resize(min(top_n, peptides.size())) would be tidier. Untouched by this PR.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Corrected file+channel (detailed) protein abundance aggregation so each selected peptide cell contributes once per (fraction, file, channel).
    • Fixed handling of multiple peptidoforms/charge states and removed stale carryover that could affect dropped cells.
    • Corrected iBAQ normalization for detailed file+channel values.
    • Improved Top-N gating at the file+channel level to avoid unintended fallback values.
  • Documentation
    • Clarified sample-level vs file/channel-level output granularity and Top-N/aggregation behavior.
  • Tests
    • Added regression tests for detailed output aggregation, Top-N behavior, and iBAQ normalization.

timosachsenberg and others added 2 commits July 25, 2026 14:00
…ollow the same policy as the sample level

ProteinData::channel_level_abundances is the file/channel-granularity
counterpart of ProteinData::total_abundances. It feeds the
"-file_and_channel_level_output true" columns of ProteinQuantifier and the
per-run intensities of the QPX pg.parquet export, and it is exposed to Python
as PeptideAndProteinQuant_ProteinData.channel_level_abundances. It was computed
by a different set of rules than the sample-level abundances, in four ways:

1. calculateFileAndChannelLevelProteinAbundances_() stopped at the FIRST
   peptidoform matching the protein group leader ("break"), so only one
   peptidoform of a modified peptide contributed. The sample-level path sums all
   peptidoforms of an unmodified sequence in transferPeptideDataToProteins_().
   Which peptidoform won was decided by AASequence::operator<, i.e. arbitrary
   with respect to abundance. Now all matching peptidoforms are accumulated.

2. The same loop pushed one entry per raw (peptidoform, charge) cell, so
   "top:N" ranked and truncated charge states rather than peptides, and the
   "enough peptides?" gate was inflated by them: one peptide observed in three
   charge states passed a top:N of 3. Now exactly one value per selected peptide
   and (fraction, file, channel) cell is contributed, summed over peptidoforms
   and charge states, mirroring quantifyPeptides().

3. transferPeptideDataToProteins_() pre-filled channel_level_abundances with a
   raw "+=" sum over all peptides/peptidoforms/charges, and the map was never
   cleared. Whenever the aggregation step then declined to quantify a cell (too
   few peptides for "top:N"), that un-aggregated sum survived into the output -
   a positive value exactly where the value should have been absent. The
   pre-fill is removed, so the map is owned solely by the aggregation step, just
   as total_abundances is owned solely by calculateProteinAbundances_().

4. performIbaqNormalization_() divided only total_abundances by the number of
   theoretically observable peptides, leaving the detailed values as raw summed
   intensity - too high by the protein-dependent divisor. It now normalizes
   channel_level_abundances as well.

The default ProteinQuantifier sample columns and the mzTab output read
total_abundances and are unaffected.

Five regression sections are added to PeptideAndProteinQuant_test, each built on
a synthetic ConsensusMap/ExperimentalDesign and each failing before and passing
after: peptidoform merging (got 10, expected 100), top:N counting peptides
rather than charge states, absence instead of a stale raw sum, top:N truncation
ranking peptides under a non-sum aggregate (got 90, expected 135), and iBAQ
normalization reaching the detailed values (got 300, expected 100). The path had
no unit coverage at all before.

No reference files change: the only TOPP test exercising this output
(ProteinQuantifier_17) uses an input of two peptides with a single peptidoform
and a single charge each, run with -top:include_all, so it cannot trigger any of
the four conditions.

The related "best_charge_and_fraction" inconsistency is deliberately not
addressed here: that option writes PeptideData::total_abundances but never
prunes PeptideData::abundances, so the detailed path ignores it, and getBest_()
does not implement the "most prevalent charge" its documentation promises.
Both need a semantics decision first and are noted in a comment.

Co-Authored-By: Claude Opus 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

ProteinQuantifier now computes file/channel abundances by merging peptidoforms and charges per selected peptide cell, applies iBAQ normalization to detailed values, documents output semantics, and adds regression coverage for aggregation, gating, ranking, annotation, and normalization.

Changes

Protein quantification

Layer / File(s) Summary
File/channel peptide aggregation
src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp
Detailed abundances are computed exclusively in the file/channel path, merging matching peptidoforms and charge states before filtering and aggregation.
iBAQ normalization propagation
src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp
iBAQ normalization is applied to both total and file/channel abundances.
Detailed abundance validation and output coverage
src/tests/class_tests/openms/source/PeptideAndProteinQuant_test.cpp, src/tests/topp/*, src/topp/ProteinQuantifier.cpp, CHANGELOG
Tests and documentation cover peptide merging, per-file/channel top:N behavior, excluded cells, annotation, detailed normalization, and output semantics.

Build revision

Layer / File(s) Summary
vcpkg revision
vcpkg
The checked-out vcpkg submodule commit is updated.

Sequence Diagram(s)

sequenceDiagram
  participant ProteinQuantifier
  participant PeptideAndProteinQuant
  participant DetailedAbundances
  ProteinQuantifier->>PeptideAndProteinQuant: quantify protein evidence
  PeptideAndProteinQuant->>DetailedAbundances: aggregate peptidoforms and charges by file/channel cell
  PeptideAndProteinQuant->>DetailedAbundances: apply iBAQ theoretical-peptide scaling
  DetailedAbundances-->>ProteinQuantifier: return detailed protein abundances
Loading

Possibly related issues

Possibly related PRs

Suggested reviewers: cbielow

Poem

I hopped through channels, neat and bright,
Merged every peptide just right.
Charges gathered, details grew,
iBAQ scaled the numbers too.
Tests now guard each measured way.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main fix: aligning file+channel protein abundances with sample-level aggregation policy.
✨ 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 fix/protein-quantifier-file-channel-level-aggregation

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.

… level output

The existing TOPP test for '-file_and_channel_level_output true'
(ProteinQuantifier_17) runs on an input of two peptides with a single
peptidoform and a single charge state each, under '-top:include_all'. It
therefore cannot trigger any of the aggregation defects fixed in the previous
commit and only pins the column layout - which is why those defects survived
with zero reference churn.

Adds a small purpose-built consensusXML (6 consensus elements, 2 files) whose
detailed columns are sensitive to all four:

  sample1: PEPTIDEMK over two peptidoforms (unmodified c2 = 100,
           Oxidation c3 = 900)                                    -> 1000
           AAAAAK over two charge states (c2 = 300, c3 = 200)     ->  500
           CCCCCK (c2 = 300)                                      ->  300
  sample2: AAAAAK (c2 = 20) only, i.e. a single peptide

ProteinQuantifier_18 runs '-top:N 2 -top:aggregate mean': ranking peptides gives
mean(1000, 500) = 750 for sample1, and sample2 cannot be quantified from one
peptide so its cell is 0. Before the fix this produced 300 (the top two of the
raw cells 100/300/200/300, the 900 peptidoform having been dropped) and 20 (the
un-aggregated sum left behind by the skipped cell).

ProteinQuantifier_19 runs '-method iBAQ' on the same input: 1800 / 3 = 600 and
20 / 3 = 6.67. The protein sequence digests into 3 fully tryptic peptides rather
than 4 because trypsin does not cleave before proline, so CCCCCKPEPTIDEMK stays
intact. Before the fix this produced 900 (raw cells, one peptidoform) and 20,
both un-normalized.

Both tests were verified to fail against the parent commit and pass after it.

Co-Authored-By: Claude Opus 5 <[email protected]>
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Added the end-to-end TOPP coverage mentioned above (653a14e), so the fix is no longer only pinned by class tests.

ProteinQuantifier_17 — the only pre-existing test using -file_and_channel_level_output true — runs on two peptides with a single peptidoform and a single charge each under -top:include_all, so it cannot trigger any of the four conditions and only pins the column layout. That is precisely why these defects survived with zero reference churn.

New input ProteinQuantifier_18_input.consensusXML (6 consensus elements, 2 files):

sample1: PEPTIDEMK over two peptidoforms (unmodified c2 = 100, Oxidation c3 = 900) -> 1000
         AAAAAK over two charge states (c2 = 300, c3 = 200)                        ->  500
         CCCCCK (c2 = 300)                                                         ->  300
sample2: AAAAAK (c2 = 20) only, i.e. a single peptide
test params before after
ProteinQuantifier_18 -top:N 2 -top:aggregate mean 300.0 / 20.0 750.0 / 0.0
ProteinQuantifier_19 -method iBAQ 900.0 / 20.0 600.0 / 6.67

The 750 is mean(1000, 500) — ranking peptides. The old 300 is the top two of the raw cells 100/300/200/300, with the 900 peptidoform dropped by the break. The old 20 for sample2 is the un-aggregated sum left behind when the cell failed the top:N gate; it is now correctly absent.

For iBAQ the divisor is 3, not 4: trypsin does not cleave before proline, so CCCCCK|PEPTIDEMK is not split and the sequence digests into AAAAAK / CCCCCKPEPTIDEMK / EEEEEK.

Both tests were verified to fail against the parent commit and pass after it, by rebuilding the tool from HEAD~^ rather than assuming. Full affected-suite run is now 117/117.

…nated and isobaric shapes

The file+channel level abundances are per-(file, channel) values, while a sample
is a (file, label) pair of the experimental design. Under fractionation one
sample therefore spans several files, so one sample maps to N cells rather than
one, and both the peptide selection and the aggregation are applied per file.

Two consequences were undocumented and are now stated on the tool, on the
'file_and_channel_level_output' parameter and at the top of
calculateFileAndChannelLevelProteinAbundances_():

  - the cells decompose the sample value exactly only for 'top:N' 0 with
    'top:aggregate' sum; top-N/median/mean/weighted_mean do not commute with
    aggregation across fractions;
  - the "at least N peptides" requirement is enforced per file, which is
    stricter than the sample-level rule: a protein quantified at the sample
    level can have all of its cells dropped because no single fraction holds
    N peptides. Before 611872b those cells were not absent but carried the
    pre-filled raw sum, which obeyed neither 'top:N' nor 'top:aggregate'.

This is intentional and unchanged; 'top:include_all' bypasses the per-file gate
(IsobaricWorkflow already enables it by default).

Tests:

  - two class-test sections on a fractionated design, pinning the 'top:N' 0 +
    sum decomposition invariant and the all-cells-absent behaviour (the latter
    fails on the pre-fix code);
  - one class-test section on the isobaric shape (one file, N channels, as
    produced by IsobaricChannelExtractor::registerChannelsInOutputMap), which
    is the first coverage of annotateQuantificationsToProteins() - the route by
    which these values reach mzTab and the QPX pg export, and IsobaricWorkflow's
    only consumer of them. It pins that every cell is exactly one sample there,
    so the two granularities cannot disagree for unfractionated isobaric data;
  - TOPP tests ProteinQuantifier_20/_21/_22 on a fractionated input, covering
    the decomposition, the sample-level output and the all-zeros default
    ('_22' fails on the pre-fix code).

No reference files change.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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/topp/ProteinQuantifier.cpp`:
- Around line 82-89: The output-granularity documentation defines a sample
inconsistently and overstates charge-state equivalence. Update the text around
file_and_channel_level_output to identify samples as (fraction_group, label)
combinations spanning that group’s files, and explicitly document
best_charge_and_fraction as an exception to the otherwise shared
charge-selection policy for detailed abundances.
🪄 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: c94d4c6d-832a-4472-ba0e-e3a45afac49f

📥 Commits

Reviewing files that changed from the base of the PR and between 653a14e and 0261ad0.

⛔ Files ignored due to path filters (1)
  • src/tests/topp/ProteinQuantifier_20_input.tsv is excluded by !**/*.tsv
📒 Files selected for processing (9)
  • CHANGELOG
  • 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_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
🚧 Files skipped from review as they are similar to previous changes (2)
  • CHANGELOG
  • src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp

Comment on lines +82 to +89
<B>Output granularity: samples vs. files and channels</B>

By default one protein abundance is reported per @a sample. A sample is identified by a (file, label/channel) pair of the experimental design, so in a fractionated experiment a single sample spans <em>several</em> files - all fractions of its fraction group at that label - and the reported value aggregates over them.

With @p file_and_channel_level_output the protein abundances are instead reported per (file, channel) cell. These cells are computed with the same peptide-level policy as the sample-level values (all peptidoforms and all charge states of a peptide are accumulated into one peptide), but the peptide selection and the aggregation are applied <em>per file</em>. Two consequences are worth knowing:

- The cells only decompose the sample value exactly for @p top:N 0 together with @p top:aggregate @p sum. Top-N selection, @p median, @p mean and @p weighted_mean do not commute with aggregation across fractions, so for those settings the cells of a sample neither sum nor average to the sample-level value.
- The @p top:N requirement ("at least N peptides") is likewise enforced per file, not per sample. In a fractionated experiment this is considerably stricter than the sample-level rule: a protein can easily have N peptides in a sample while no individual fraction contains N of them, in which case the protein is quantified at the sample level but <em>all</em> of its (file, channel) cells are reported as 0. Use @p top:N 0 (optionally with @p top:aggregate @p sum) or @p top:include_all if per-file values are wanted for such data.

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Correct the fractionated-sample definition and charge-selection caveat.

Line 84 calls a sample a (file, label) pair while also saying it spans several files; it is a (fraction_group, label) combination. Line 86 also promises identical charge-state handling, but best_charge_and_fraction remains an acknowledged exception for detailed abundances. Document both accurately. The PR objective explicitly notes this inconsistency is not addressed.

🤖 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 82 - 89, The output-granularity
documentation defines a sample inconsistently and overstates charge-state
equivalence. Update the text around file_and_channel_level_output to identify
samples as (fraction_group, label) combinations spanning that group’s files, and
explicitly document best_charge_and_fraction as an exception to the otherwise
shared charge-selection policy for detailed abundances.

…omment

The comment in calculateFileAndChannelLevelProteinAbundances_ notes that
'best_charge_and_fraction' is not honoured at the file+channel level. That
defect, together with getBest_() never computing the documented "most prevalent
charge" and each peptide ending up quantified in only one sample, is now
tracked in #9796.

Comment only, no behaviour change.

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

Copy link
Copy Markdown
Contributor

Oof.. Sounds like quantification would benefit from a full rewrite 😮

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

yep. The question is who can do it and has the resources to do it? It's quite complex.

1. channel_level_abundances does NOT reach mzTab. MzTab.cpp:1605 reads only
   float data array 0 ("abundances", the sample-level values); the file+channel
   arrays (float 3 / string 0 / integer 0) are read exclusively by
   ProteinGroupArrowExport.cpp:351-353 for the QPX pg export. Corrected in the
   CHANGELOG and in the isobaric test section comment.

2. The new "Output granularity" documentation claimed the cells follow the same
   peptide-level policy as the sample-level values, and that 'top:N' 0 with
   'top:aggregate' sum makes them decompose exactly. Both hold only while
   'best_charge_and_fraction' is off: that option reduces the sample-level value
   to a single (fraction, file, charge, channel) observation while these cells
   keep accumulating all charge states, so the two granularities then describe
   different quantities and never decompose (see #9796). Caveat added to the
   doxygen section and to the parameter description.

Also reworded the transferPeptideDataToProteins_ comment, which still called
channel_level_abundances the "counterpart" of total_abundances - the mapping is
1:N under fractionation, not 1:1.

Documentation only, no behaviour change.

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

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp (1)

1070-1078: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Qualify the “same quantity” comment for best_charge_and_fraction.

The detailed path explicitly does not honor best_charge_and_fraction (Lines 1274-1278), so this comment is too absolute. Clarify that the values represent the same quantity under the normal aggregation mode, with the known option-specific exception.

🤖 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 1070 - 1078, Update the ownership comment near channel_level_abundances to
qualify that it represents the same quantity as total_abundances under normal
aggregation, except that the detailed
calculateFileAndChannelLevelProteinAbundances_() path does not honor
best_charge_and_fraction. Preserve the existing explanation of fractionation and
aggregation behavior.
🤖 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.

Outside diff comments:
In `@src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp`:
- Around line 1070-1078: Update the ownership comment near
channel_level_abundances to qualify that it represents the same quantity as
total_abundances under normal aggregation, except that the detailed
calculateFileAndChannelLevelProteinAbundances_() path does not honor
best_charge_and_fraction. Preserve the existing explanation of fractionation and
aggregation behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2e6acfe8-d2ef-46b5-aca6-e81e64d63a35

📥 Commits

Reviewing files that changed from the base of the PR and between 8dd8bcd and a73a5b9.

📒 Files selected for processing (5)
  • CHANGELOG
  • src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp
  • src/tests/class_tests/openms/source/PeptideAndProteinQuant_test.cpp
  • src/topp/ProteinQuantifier.cpp
  • vcpkg
🚧 Files skipped from review as they are similar to previous changes (3)
  • CHANGELOG
  • src/topp/ProteinQuantifier.cpp
  • src/tests/class_tests/openms/source/PeptideAndProteinQuant_test.cpp

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Since this PR turns on a distinction that is easy to lose track of — two abundance granularities computed independently from the same parameters — here is a map of the whole path for reviewers.

Colour coding is consistent across all three: teal nodes are per sample (total_abundances), amber nodes are per file × channel (channel_level_abundances).

1. The pipeline

The key structural fact is the dotted edge: calculateFileAndChannelLevelProteinAbundances_() does not consume the sample-level result. It re-derives everything from the raw pep_quant_ map. Same policy parameters, different bucket keys — which is why the two could drift apart in the first place.

flowchart TD
  IN["featureXML / consensusXML / idXML<br/>+ ExperimentalDesign"]
  IN --> RQD["readQuantData()"]
  RQD --> RAW["pep_quant_[AASequence].abundances<br/>fraction · file · charge · channel"]

  RAW --> QPH(["quantifyPeptides()"])
  QPH --> FLT["filter to peptides present<br/>in inference results"]
  FLT --> BCF{"best_charge_and_fraction"}
  BCF -->|"false — default"| SUMC["sum over fraction, file, charge"]
  BCF -->|"true"| BEST["getBest_() — argmax over all cells<br/>writes ONE sample only · #9796"]
  SUMC --> PTA["PeptideData::total_abundances<br/>per sample"]
  BEST --> PTA
  PTA --> NRM{"consensus:normalize<br/>and n_samples &gt; 1"}
  NRM -->|"true"| NRMY["normalizePeptides_()<br/>scale to equal medians"]
  NRM -->|"false"| TR
  NRMY --> TR

  TR["transferPeptideDataToProteins_()<br/>peptidoforms merged by toUnmodifiedString()"]
  TR --> PA["ProteinData::peptide_abundances<br/>peptide · sample"]

  PA --> SEL["selectPeptidesForQuantification_()<br/>consensus:fix_peptides · top:N"]
  SEL --> CPA["calculateProteinAbundances_()"]
  SEL --> CFC["calculateFileAndChannelLevelProteinAbundances_()"]
  RAW -. "re-reads the raw map" .-> CFC

  CPA --> TA["total_abundances<br/>per SAMPLE"]
  CFC --> CLA["channel_level_abundances<br/>per FILE × CHANNEL"]

  TA --> IBQ{"method = iBAQ"}
  CLA --> IBQ
  IBQ -->|"yes — forces top:N 0 + sum"| IBN["divide both by the protein's<br/>theoretical tryptic peptide count"]
  IBQ -->|"no"| OUT
  IBN --> OUT

  OUT["annotateQuantificationsToProteins()<br/>+ ProteinQuantifier text output"]
  OUT --> O1["mzTab · sample columns<br/>reads float array 0 only"]
  OUT --> O2["QPX pg.parquet<br/>reads float array 3"]

  classDef samp fill:#E4F1F2,stroke:#0E6E78,color:#0B4C53
  classDef cell fill:#F8EEDF,stroke:#9A5A08,color:#6E3F05
  classDef bad  fill:#F7E7E7,stroke:#9E2B2B,color:#7A1F1F
  class PTA,TA,O1 samp
  class CLA,O2 cell
  class BEST bad
Loading

2. One policy, two bucket keys

Both calculate* functions run the identical four steps. The only difference is what counts as one bucket, and therefore how many peptides land in it — which is exactly what top:N counts.

flowchart LR
  SEL["selected_peptides"]

  SEL --> KA["bucket by SAMPLE"]
  SEL --> KB["bucket by<br/>fraction · file · channel"]

  KA --> GA{"count &lt; top:N ?"}
  KB --> GB{"count &lt; top:N ?"}

  GA -->|"yes · not include_all"| DA["absent"]
  GB -->|"yes · not include_all"| DB["absent"]

  GA -->|"no"| TAa["keep the N largest"]
  GB -->|"no"| TBb["keep the N largest"]

  TAa --> AGA["aggregateAbundances_()<br/>median · mean · weighted_mean · sum"]
  TBb --> AGB["aggregateAbundances_()<br/>median · mean · weighted_mean · sum"]

  AGA --> OA["total_abundances[sample]"]
  AGB --> OB["channel_level_abundances[file][channel]"]

  classDef samp fill:#E4F1F2,stroke:#0E6E78,color:#0B4C53
  classDef cell fill:#F8EEDF,stroke:#9A5A08,color:#6E3F05
  classDef gone fill:#EFF2F3,stroke:#9AA7B0,color:#5A6873
  class KA,GA,TAa,AGA,OA samp
  class KB,GB,TBb,AGB,OB cell
  class DA,DB gone
Loading

A dropped bucket is absent from the map, not zero — the tool and the annotation step both print absent cells as 0.0.

3. How the two levels relate

A sample is a (file, label) pair of the experimental design. The two levels coincide exactly when each sample owns one file, and diverge under fractionation.

flowchart TB
  subgraph UF["Unfractionated LFQ — 1 file, 1 channel"]
    direction LR
    u1["fileA ch1"] --- u2["sample 1"]
  end

  subgraph ISO["Isobaric TMT — 1 file, N channels"]
    direction LR
    i1["fileA ch1"] --- i2["sample 1"]
    i3["fileA ch2"] --- i4["sample 2"]
  end

  subgraph FR["Fractionated — 1 sample spans N files"]
    direction LR
    f1["fileA ch1 · 300"] --> s1["sample 1 · 650"]
    f2["fileB ch1 · 350"] --> s1
    f3["fileA ch2 · 30"] --> s2["sample 2 · 65"]
    f4["fileB ch2 · 35"] --> s2
  end

  UF --> ISO --> FR

  classDef samp fill:#E4F1F2,stroke:#0E6E78,color:#0B4C53
  classDef cell fill:#F8EEDF,stroke:#9A5A08,color:#6E3F05
  class u2,i2,i4,s1,s2 samp
  class u1,i1,i3,f1,f2,f3,f4 cell
Loading

The fractionated numbers are the new ProteinQuantifier_20 test. Those cells add up to the sample only for top:N 0 with top:aggregate sum; under the default top:N 3 all four are absent while both samples are quantified, because no single fraction holds three peptides. That is the behaviour this PR documents rather than changes — see ProteinQuantifier_22.

Two shapes are degenerate and cannot be affected either way: unfractionated LFQ, and unfractionated isobaric — IsobaricChannelExtractor::registerChannelsInOutputMap() emits one file whose column headers differ only in label, so every cell is a sample.

4. Where each option acts

Parameter Acts in Affects Effect
best_charge_and_fraction quantifyPeptides sample only Raw → sample uses getBest_() instead of summing. The file+channel path reads abundances, which the option never prunes, so it is silently unaffected (#9796)
consensus:normalize quantifyPeptides both Median-scales peptide abundances across samples; only when n_samples > 1
consensus:fix_peptides selectPeptidesForQuantification_ both With top:N 0, only peptides seen in every sample. With top:N > 0, orderBest_ ranks by (number of samples, total abundance) and keeps N
top:N both calculate* both Two jobs in one number: the "at least N peptides" gate and truncation to the N largest. Counted per bucket, so per file for the cells
top:aggregate aggregateAbundances_ both median (default), mean, weighted_mean, sum
top:include_all both calculate* both Bypasses the count gate only — truncation still applies. IsobaricWorkflow enables it by default
method=iBAQ quantifyProteins both Silently overrides top:N to 0 and top:aggregate to sum, then divides by the theoretical tryptic peptide count
file_and_channel_level_output ProteinQuantifier reporting Tool-level only — both containers are always computed; this picks which one is printed

@jpfeuffer

jpfeuffer commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

@timosachsenberg this sounds like it doesn't quantify on (fraction_group*channel)-level which is what I thought is the new qpx 1.1 way of storing pg quants, no?

Or better question: Why/when is the amber path needed?

Copy link
Copy Markdown
Contributor Author

Closing as superseded by #9847 (d23a9f8). It landed every fix from this PR:

  • each (fraction, file, channel) cell gets one value per peptide, summed over its peptidoforms and charge states, so top:N counts peptides;
  • the raw pre-fill in transferPeptideDataToProteins_ is gone;
  • iBAQ also divides channel_level_abundances.

#9847 also has the same unit-test sections and the TOPP tests, renumbered ProteinQuantifier_23-27 with the same inputs and values. It resolved the best_charge_and_fraction follow-up #9796 as well. develop has since moved on: the sample level became assays (#9869), and stored zeros no longer count (#9852). Nothing is left here to merge.


Generated by Claude Code

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