Skip to content

Commit b04df33

Browse files
authored
Merge pull request #386 from bigbio/fix/drop-duplicate-typed-qvalue-scores
fix(writers): Drop the scores a typed q-value column repeats
2 parents 8da3671 + 7295226 commit b04df33

9 files changed

Lines changed: 85 additions & 19 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6262

6363
### Changed
6464

65+
- A score that a typed q-value column (`feature.precursor_qvalue`, `peptide_qvalue`, `global_qvalue`, `psm.qvalue`) holds under the same name and value is no longer repeated in `additional_scores`. DIA-NN `Q.Value` is now only in `feature.precursor_qvalue`; readers that looked it up in the list must read the column.
6566
- **The PSM identity composite is `[run_file_name, scan, peptidoform, charge]`**, the order agreed in #229. Every derived `psm_id` changes and now equals the id OpenMS writes for the same row.
6667
- `qpxc transform normalize-accessions` also normalizes `psm.protein_accessions` and the pepmap, which it left behind so that PSM-to-pg matching fell from 148/148 to 27/148, and marks a pg file `identity_source=provided`, since its `pg_id` values stay and no longer re-derive.
6768
- DIA-NN feature `additional_intensities`: `maxlfq` is now `pg_maxlfq`, a protein-level value, and `precursor_normalised` is `normalize_intensity`.

‎docs/spec/converter-coverage.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ does not imply that the quantity could never be derived.
5656
| `parent_ion_fraction` / `quant_scan` / `quant_ms_level` | Not provided. | `quant_precursor_purity`, else `precursor_purity`; `scan_id`; and 2 or 3 from whether `id_scan_id` equals `scan_id`, null without `id_scan_id`. |
5757
| `id_run_file_name` | The normalized report run name. | The resolved run of a direct identification of the exported peptide with a spectrum reference. Null for transferred features without their own identification, unresolved origins or conflicting peptide assignments. |
5858
| `pg_positions` | Not populated from the report, which has no peptide-to-protein coordinates. Filled from a FASTA with `--fasta` or `qpxc transform protein-properties`: every one-based occurrence in each group member. | Known peptide-evidence `start` / `end` coordinates, converted from zero-based inclusive to one-based inclusive. For a resolved protein group, positions on its members; for a peptide shared across inferred groups (null `pg_accessions`), positions on every evidence protein, since each entry names its own protein. Null when no usable positions remain. A FASTA is not needed for coordinates already recorded in consensusXML. |
59-
| `peptide_qvalue` | Null: DIA-NN `Q.Value` is precursor-level and is stored as `precursor_qvalue` in `additional_scores`. | Read from an identification score explicitly declared to be a q-value/FDR. Null without a suitable identification in that run; raw search scores are not substituted. |
59+
| `peptide_qvalue` | Null: DIA-NN `Q.Value` is precursor-level and is written to the `precursor_qvalue` column. | Read from an identification score explicitly declared to be a q-value/FDR. Null without a suitable identification in that run; raw search scores are not substituted. |
6060
| `intensities` / `additional_intensities` | `Precursor.Quantity`; `PG.MaxLFQ`, `Precursor.Normalised` and `Ms1.Area` as `pg_maxlfq`, `normalize_intensity` and `ms1_area`. DIA-NN writes 0 for a quantity it did not measure: an unquantified precursor or channel keeps its label with a null `intensity`, and a 0 additional intensity is left out. | The consensus feature's per-map sub-feature intensities; a map element with intensity ≤ 0 has no entry. `additional_intensities` holds the ratios of an MS1-labelled multiplet; otherwise it is not populated. |
6161

6262
Protein-group ambiguity includes shared peptides spanning multiple inferred

‎docs/spec/feature.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ Each entry in `pg_positions` contains:
123123
`pg_global_qvalue` and `peptide_qvalue` are **optional** — the column may be absent from the file entirely if the search engine does not provide that q-value. When present, individual values may be null.
124124

125125
!!! warning "Which q-value to read"
126-
`peptide_qvalue` is the canonical peptide-level q-value and is the field to read when filtering or reporting peptide-level FDR. DIA-NN does not report a peptide-level q-value: its precursor-level `Q.Value` remains in `additional_scores` under `precursor_qvalue`, and the DIA-NN converter leaves `peptide_qvalue` null.
126+
`peptide_qvalue` is the canonical peptide-level q-value and is the field to read when filtering or reporting peptide-level FDR. DIA-NN does not report a peptide-level q-value: its precursor-level `Q.Value` is written to `precursor_qvalue`, and the DIA-NN converter leaves `peptide_qvalue` null.
127127

128128
Other producer-specific q-values may also appear in `additional_scores`; use the documented score name and level rather than treating every q-value as peptide-level confidence.
129129

@@ -225,7 +225,7 @@ Several fields in the feature view use structures shared across other QPX views:
225225
],
226226
"additional_scores": [
227227
{
228-
"score_name": "global_qvalue",
228+
"score_name": "diann_lib_qvalue",
229229
"score_value": 0.0012,
230230
"higher_better": false
231231
}

‎docs/spec/ontology.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ Sample metadata fields map to biological ontologies. These mappings are critical
269269

270270
## Score Fields {#scores}
271271

272-
Score names used in `additional_scores` that have PSI-MS ontology mappings. All QPX score names use **snake_case** -- the ontology name column shows the proper CV term.
272+
Score names used in `additional_scores` or the [typed q-value columns](scores.md#typed-q-value-columns) that have PSI-MS ontology mappings. In specification 1.3, a q-value matching a typed column's name and value is not duplicated in `additional_scores`. All QPX score names use **snake_case** -- the ontology name column shows the proper CV term.
273273

274274
| QPX Name (snake_case) | Ontology Name | Ontology Accession | Direction |
275275
|---|---|---|---|

‎docs/spec/scores.md‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ Filtering on a nested score reads about 100 times the data of a flat column, and
4444
| `feature.precursor_qvalue` | Precursor, per run | `precursor_qvalue`, `qvalue`, `q_value`, `psm_level_qvalue` |
4545
| `feature.global_qvalue` | Precursor, per experiment | `global_qvalue` |
4646

47-
A column stays null when the source has no such score, and the score stays in `additional_scores`.
47+
A column stays null when the source has no such score. In specification 1.3, a score whose `snake_case` name equals a typed column's name and whose value exactly equals that column's filled value is written only in the flat column, not in `additional_scores`. Aliases such as `q_value`, `psm_level_qvalue` and `percolator_q_value` stay in the list because their names record the source; a same-name score with a different value also stays.
4848

4949
### Recommended score names
5050

@@ -53,7 +53,7 @@ The following score names are commonly used across QPX views. All names are `sna
5353
| Score name | Typical view(s) | Direction | Description |
5454
| ---------- | ---------------- | --------- | ----------- |
5555
| `posterior_error_probability` | PSM | lower is better | Posterior error probability — probability that the PSM is incorrect. Ranges 0.0–1.0. This is a **top-level field** in the PSM view, not stored in `additional_scores` |
56-
| `global_qvalue` | PSM, Feature | lower is better | Global q-value at the experiment level |
56+
| `global_qvalue` | PSM, Feature | lower is better | Global q-value at the experiment level; on a feature, read the `global_qvalue` column |
5757
| `pg_global_qvalue` | PSM, Feature | lower is better | Protein group global q-value used to filter at the protein group level |
5858
| `rank` | PSM | lower is better | Rank of the peptide in the search engine results (1 = best) |
5959
| `comet_xcorr` | PSM | higher is better | Cross-correlation score from the Comet search engine |
@@ -63,7 +63,7 @@ The following score names are commonly used across QPX views. All names are `sna
6363
| `msgf_spec_evalue` | PSM | lower is better | Spectral E-value from MS-GF+ |
6464
| `sage_hyperscore` | PSM | higher is better | Hyperscore from Sage search engine |
6565
| `parent_ion_fraction` | PSM | higher is better | Fraction of the isolation window's signal from the target precursor, 0-1 (MaxQuant `PIF`, FragPipe `Purity`, CDAP `PrecursorPurity`); on a feature it is the column of that name |
66-
| `precursor_qvalue` | Feature | lower is better | Run-level precursor q-value (`Q.Value`), as emitted by the DIA-NN converter |
66+
| `precursor_qvalue` | Feature | lower is better | Run-level precursor q-value (`Q.Value`), written to the `precursor_qvalue` column by the DIA-NN converter; an exact duplicate is not kept in `additional_scores` |
6767
| `pg_qvalue` | Feature | lower is better | Run-level protein-group q-value, as emitted by the DIA-NN converter |
6868
| `pg_pep` | PG | lower is better | Protein-group posterior error probability (`PG.PEP`), as emitted by the DIA-NN converter |
6969
| `diann_lib_qvalue` | Feature | lower is better | Library q-value from DIA-NN |
@@ -78,9 +78,9 @@ The following score names are commonly used across QPX views. All names are `sna
7878
When adding tool-specific scores, use `snake_case` with the tool name as prefix: `{tool}_{score}`. For example, `comet_xcorr`, `diann_cscore`, `sage_hyperscore`. Register the mapping to the proper ontology term in `ontology.parquet` (see [Ontology Mapping](ontology.md)).
7979

8080
!!! warning "Names in this table are the ones producers actually write"
81-
Earlier revisions listed `diann_qvalue` and `diann_global_qvalue`, which no converter emits — the DIA-NN converter writes `precursor_qvalue`, `global_qvalue` and `pg_qvalue`. The table now records the emitted names so a consumer can match on them.
81+
Earlier revisions listed `diann_qvalue` and `diann_global_qvalue`, which no converter emits — the DIA-NN converter writes the `precursor_qvalue` and `global_qvalue` columns and keeps `pg_qvalue` in `additional_scores`. The table records the emitted names so a consumer can match on them.
8282

83-
`feature.peptide_qvalue` is reserved for peptide-level confidence. DIA-NN `Q.Value` is precursor-level, so it remains in `additional_scores` under `precursor_qvalue` and must not be copied into `feature.peptide_qvalue`.
83+
`feature.peptide_qvalue` is reserved for peptide-level confidence. DIA-NN `Q.Value` is precursor-level, so it is written to `feature.precursor_qvalue` and must not be copied into `feature.peptide_qvalue`.
8484

8585
### Protein-level additional scores
8686

‎docs/spec/tool-mappings.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ The Feature view captures quantified peptide features with intensity data. Featu
5757
| `pg_positions` | --- | --- | --- | --- |
5858
| `run_file_name` | Raw file | Run | First raw file of the experiment (experiment_annotation.tsv or SDRF) | Reference / Run resolved through SDRF |
5959

60-
DIA-NN `Q.Value` is precursor-level and is stored in `additional_scores` as `precursor_qvalue`; it is not mapped to the peptide-level `peptide_qvalue` field.
60+
DIA-NN `Q.Value` is precursor-level and is written to the `precursor_qvalue` column; it is not mapped to the peptide-level `peptide_qvalue` field.
6161

6262
MaxQuant `unique` follows the group the feature takes. With proteinGroups.txt, it is true when the peptide is in a single group (`Protein group IDs` names one id) and that group has one protein; a shared peptide carries its razor group and is false. Without proteinGroups.txt, or for a row whose `Protein group IDs` do not resolve, the group falls back to `Leading proteins`, which lists one leader per group, so the group's size is unknown: `unique` is then true when the peptide maps to a single protein (`Proteins`), or, without that column, when it is in a single group of any size. In ontology.parquet the feature `pg_accessions` and `anchor_protein` name the column they were read from: `Protein IDs` and `Majority protein IDs` (proteinGroups.txt) when `Protein group IDs` resolve, otherwise `Leading proteins` and `Leading razor protein`.
6363

‎qpx/writers/derived.py‎

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -56,19 +56,42 @@ def _score_values(scores: pa.Array, wanted: Callable[[str], bool]) -> np.ndarray
5656

5757

5858
def fill_score_columns(table: pa.Table, columns: dict[str, Callable[[str], bool]]) -> pa.Table:
59-
"""Fill each null of the typed *columns* from ``additional_scores``."""
59+
"""Fill each null of the typed *columns* from ``additional_scores``.
60+
61+
Remove a score only when its normalized name equals a present typed column's
62+
name and its value exactly equals that column's filled value. Aliases and
63+
differing values stay in the list. Preserve null lists and newly empty lists.
64+
"""
6065
if "additional_scores" not in table.schema.names or not table.num_rows:
6166
return table
6267
scores = pa.concat_arrays(table.column("additional_scores").chunks)
63-
for name, wanted in columns.items():
68+
available = {name: wanted for name, wanted in columns.items() if name in table.schema.names}
69+
for name, wanted in available.items():
6470
index = table.schema.get_field_index(name)
65-
if index < 0:
66-
continue
6771
derived = _score_values(scores, wanted)
6872
typed = pa.array(derived, mask=np.isnan(derived), type=table.schema.field(index).type)
6973
filled = pc.call_function("coalesce", [table.column(index), typed])
7074
table = table.set_column(index, table.schema.field(index), filled)
71-
return table
75+
entries = scores.flatten()
76+
if len(entries) == 0:
77+
return table
78+
encoded = pc.call_function("dictionary_encode", [entries.field("score_name")])
79+
names = np.array([normalize_score_name(name) for name in encoded.dictionary.to_pylist()] + [""])
80+
indices = encoded.indices.fill_null(-1).to_numpy(zero_copy_only=False)
81+
parents = pc.call_function("list_parent_indices", [scores]).to_numpy()
82+
numbers = entries.field("score_value").to_numpy(zero_copy_only=False)
83+
drop = np.zeros(len(entries), dtype=bool)
84+
for name in available:
85+
values = table.column(name).to_numpy(zero_copy_only=False)
86+
drop |= (names == name)[indices] & (numbers == values[parents])
87+
if not drop.any():
88+
return table
89+
counts = np.bincount(parents[~drop], minlength=len(scores))
90+
offsets = np.zeros(len(scores) + 1, dtype=scores.offsets.type.to_pandas_dtype())
91+
np.cumsum(counts, out=offsets[1:])
92+
rebuilt = type(scores).from_arrays(offsets, entries.filter(pa.array(~drop)), type=scores.type, mask=scores.is_null())
93+
index = table.schema.get_field_index("additional_scores")
94+
return table.set_column(index, table.schema.field(index), rebuilt)
7295

7396

7497
def fill_irt(table: pa.Table) -> pa.Table:

‎tests/converters/test_diann_converter.py‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -272,14 +272,16 @@ def test_mass_error_ppm_matches_the_spec_formula(self, feature_table):
272272
assert e is not None, "both m/z present but no mass error emitted"
273273
assert abs(e - (o - c) / c * 1e6) < 0.5, f"{e} does not match the spec formula"
274274

275-
def test_precursor_qvalue_stays_in_additional_scores(self, feature_table):
275+
def test_precursor_qvalue_moves_to_typed_column(self, feature_table):
276276
"""DIA-NN Q.Value is not mislabeled as a peptide-level q-value."""
277277
assert all(value is None for value in feature_table.column("peptide_qvalue").to_pylist())
278278

279-
for scores in feature_table.column("additional_scores").to_pylist():
279+
for value, scores in zip(
280+
feature_table.column("precursor_qvalue").to_pylist(), feature_table.column("additional_scores").to_pylist()
281+
):
280282
by_name = {score["score_name"]: score["score_value"] for score in scores}
281283
assert "qvalue" not in by_name
282-
value = by_name["precursor_qvalue"]
284+
assert "precursor_qvalue" not in by_name
283285
assert 0.0 <= value <= 1.0, f"q-value out of range: {value}"
284286

285287

@@ -319,7 +321,8 @@ def test_plexdia_feature_collapses_channels_into_one_row(tmp_path):
319321
assert {entry["label"]: entry["intensity"] for entry in rows[0]["intensities"]} == {"L": 100.0, "H": 200.0}
320322
assert rows[0]["peptide_qvalue"] is None
321323
scores = {entry["score_name"]: entry["score_value"] for entry in rows[0]["additional_scores"]}
322-
assert scores["precursor_qvalue"] == pytest.approx(0.002)
324+
assert rows[0]["precursor_qvalue"] == pytest.approx(0.002)
325+
assert "precursor_qvalue" not in scores
323326
assert rows[0]["representative_label"] == "L"
324327
assert [(entry["label"], entry["qvalue"]) for entry in rows[0]["channel_details"]] == [("H", 0.003), ("L", 0.002)]
325328
assert rows[0]["channel_details"][0]["rt"] == rows[0]["rt"]
@@ -855,6 +858,7 @@ def test_diann_feature_without_qvalue_converts_when_unfiltered(tmp_path):
855858
feature_rows = _feature_rows_single_run(tmp_path, rows)
856859

857860
assert len(feature_rows) == 2
861+
assert all(row["precursor_qvalue"] is None for row in feature_rows)
858862
assert all(all(score["score_name"] != "precursor_qvalue" for score in row["additional_scores"]) for row in feature_rows)
859863

860864

‎tests/integration/test_typed_confidence.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,44 @@ def test_a_value_the_producer_typed_wins(tmp_path):
8383
assert pq.read_table(path, columns=["peptide_qvalue"]).column("peptide_qvalue").to_pylist() == [0.001]
8484

8585

86+
@pytest.mark.parametrize(
87+
"writer_class,make_record,column,alias",
88+
[
89+
(FeatureWriter, make_feature_record, "peptide_qvalue", "peptide_level_qvalue"),
90+
(FeatureWriter, make_feature_record, "precursor_qvalue", "q_value"),
91+
(FeatureWriter, make_feature_record, "global_qvalue", "diann_global_qvalue"),
92+
(PsmWriter, make_psm_record, "qvalue", "percolator_q_value"),
93+
],
94+
)
95+
def test_writer_removes_only_duplicate_typed_qvalues(tmp_path, writer_class, make_record, column, alias):
96+
"""Canonical equal scores move to typed columns; aliases, differing values and null lists remain."""
97+
inputs = [
98+
(None, [_score(column, 0.01), _score(alias, 0.01)]),
99+
(0.02, [_score(column, 0.03), _score(alias, 0.02)]),
100+
(None, None),
101+
(None, [_score(column, 0.04)]),
102+
(None, []),
103+
(None, [_score(column.upper(), 0.05)]),
104+
]
105+
records = [
106+
make_record(run_file_name=f"run{i}", additional_scores=scores, **{column: value})
107+
for i, (value, scores) in enumerate(inputs)
108+
]
109+
path = tmp_path / "typed.parquet"
110+
with writer_class(path) as writer:
111+
writer.write_batch(records)
112+
table = pq.read_table(path)
113+
assert table.column(column).to_pylist() == [0.01, 0.02, None, 0.04, None, 0.05]
114+
assert table.column("additional_scores").to_pylist() == [
115+
[_score(alias, 0.01)],
116+
[_score(column, 0.03), _score(alias, 0.02)],
117+
None,
118+
[],
119+
[],
120+
[],
121+
]
122+
123+
86124
def _table(records):
87125
import pyarrow as pa
88126

0 commit comments

Comments
 (0)