Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- 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.
- **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.
- `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.
- DIA-NN feature `additional_intensities`: `maxlfq` is now `pg_maxlfq`, a protein-level value, and `precursor_normalised` is `normalize_intensity`.
Expand Down
2 changes: 1 addition & 1 deletion docs/spec/converter-coverage.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ does not imply that the quantity could never be derived.
| `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`. |
| `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. |
| `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. |
| `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. |
| `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. |
| `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. |

Protein-group ambiguity includes shared peptides spanning multiple inferred
Expand Down
4 changes: 2 additions & 2 deletions docs/spec/feature.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ Each entry in `pg_positions` contains:
`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.

!!! warning "Which q-value to read"
`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.
`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.

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.

Expand Down Expand Up @@ -225,7 +225,7 @@ Several fields in the feature view use structures shared across other QPX views:
],
"additional_scores": [
{
"score_name": "global_qvalue",
"score_name": "diann_lib_qvalue",
"score_value": 0.0012,
"higher_better": false
}
Expand Down
2 changes: 1 addition & 1 deletion docs/spec/ontology.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ Sample metadata fields map to biological ontologies. These mappings are critical

## Score Fields {#scores}

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

| QPX Name (snake_case) | Ontology Name | Ontology Accession | Direction |
|---|---|---|---|
Expand Down
10 changes: 5 additions & 5 deletions docs/spec/scores.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ Filtering on a nested score reads about 100 times the data of a flat column, and
| `feature.precursor_qvalue` | Precursor, per run | `precursor_qvalue`, `qvalue`, `q_value`, `psm_level_qvalue` |
| `feature.global_qvalue` | Precursor, per experiment | `global_qvalue` |

A column stays null when the source has no such score, and the score stays in `additional_scores`.
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.

### Recommended score names

Expand All @@ -53,7 +53,7 @@ The following score names are commonly used across QPX views. All names are `sna
| Score name | Typical view(s) | Direction | Description |
| ---------- | ---------------- | --------- | ----------- |
| `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` |
| `global_qvalue` | PSM, Feature | lower is better | Global q-value at the experiment level |
| `global_qvalue` | PSM, Feature | lower is better | Global q-value at the experiment level; on a feature, read the `global_qvalue` column |
| `pg_global_qvalue` | PSM, Feature | lower is better | Protein group global q-value used to filter at the protein group level |
| `rank` | PSM | lower is better | Rank of the peptide in the search engine results (1 = best) |
| `comet_xcorr` | PSM | higher is better | Cross-correlation score from the Comet search engine |
Expand All @@ -63,7 +63,7 @@ The following score names are commonly used across QPX views. All names are `sna
| `msgf_spec_evalue` | PSM | lower is better | Spectral E-value from MS-GF+ |
| `sage_hyperscore` | PSM | higher is better | Hyperscore from Sage search engine |
| `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 |
| `precursor_qvalue` | Feature | lower is better | Run-level precursor q-value (`Q.Value`), as emitted by the DIA-NN converter |
| `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` |
| `pg_qvalue` | Feature | lower is better | Run-level protein-group q-value, as emitted by the DIA-NN converter |
| `pg_pep` | PG | lower is better | Protein-group posterior error probability (`PG.PEP`), as emitted by the DIA-NN converter |
| `diann_lib_qvalue` | Feature | lower is better | Library q-value from DIA-NN |
Expand All @@ -78,9 +78,9 @@ The following score names are commonly used across QPX views. All names are `sna
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)).

!!! warning "Names in this table are the ones producers actually write"
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.
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.

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

### Protein-level additional scores

Expand Down
2 changes: 1 addition & 1 deletion docs/spec/tool-mappings.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ The Feature view captures quantified peptide features with intensity data. Featu
| `pg_positions` | --- | --- | --- | --- |
| `run_file_name` | Raw file | Run | First raw file of the experiment (experiment_annotation.tsv or SDRF) | Reference / Run resolved through SDRF |

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

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

Expand Down
33 changes: 28 additions & 5 deletions qpx/writers/derived.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,19 +56,42 @@ def _score_values(scores: pa.Array, wanted: Callable[[str], bool]) -> np.ndarray


def fill_score_columns(table: pa.Table, columns: dict[str, Callable[[str], bool]]) -> pa.Table:
"""Fill each null of the typed *columns* from ``additional_scores``."""
"""Fill each null of the typed *columns* from ``additional_scores``.

Remove a score only when its normalized name equals a present typed column's
name and its value exactly equals that column's filled value. Aliases and
differing values stay in the list. Preserve null lists and newly empty lists.
"""
if "additional_scores" not in table.schema.names or not table.num_rows:
return table
scores = pa.concat_arrays(table.column("additional_scores").chunks)
for name, wanted in columns.items():
available = {name: wanted for name, wanted in columns.items() if name in table.schema.names}
for name, wanted in available.items():
index = table.schema.get_field_index(name)
if index < 0:
continue
derived = _score_values(scores, wanted)
typed = pa.array(derived, mask=np.isnan(derived), type=table.schema.field(index).type)
filled = pc.call_function("coalesce", [table.column(index), typed])
table = table.set_column(index, table.schema.field(index), filled)
return table
entries = scores.flatten()
if len(entries) == 0:
return table
encoded = pc.call_function("dictionary_encode", [entries.field("score_name")])
names = np.array([normalize_score_name(name) for name in encoded.dictionary.to_pylist()] + [""])
indices = encoded.indices.fill_null(-1).to_numpy(zero_copy_only=False)
parents = pc.call_function("list_parent_indices", [scores]).to_numpy()
numbers = entries.field("score_value").to_numpy(zero_copy_only=False)
drop = np.zeros(len(entries), dtype=bool)
for name in available:
values = table.column(name).to_numpy(zero_copy_only=False)
drop |= (names == name)[indices] & (numbers == values[parents])
if not drop.any():
return table
counts = np.bincount(parents[~drop], minlength=len(scores))
offsets = np.zeros(len(scores) + 1, dtype=scores.offsets.type.to_pandas_dtype())
np.cumsum(counts, out=offsets[1:])
rebuilt = type(scores).from_arrays(offsets, entries.filter(pa.array(~drop)), type=scores.type, mask=scores.is_null())
index = table.schema.get_field_index("additional_scores")
return table.set_column(index, table.schema.field(index), rebuilt)


def fill_irt(table: pa.Table) -> pa.Table:
Expand Down
12 changes: 8 additions & 4 deletions tests/converters/test_diann_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,14 +272,16 @@ def test_mass_error_ppm_matches_the_spec_formula(self, feature_table):
assert e is not None, "both m/z present but no mass error emitted"
assert abs(e - (o - c) / c * 1e6) < 0.5, f"{e} does not match the spec formula"

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

for scores in feature_table.column("additional_scores").to_pylist():
for value, scores in zip(
feature_table.column("precursor_qvalue").to_pylist(), feature_table.column("additional_scores").to_pylist()
):
by_name = {score["score_name"]: score["score_value"] for score in scores}
assert "qvalue" not in by_name
value = by_name["precursor_qvalue"]
assert "precursor_qvalue" not in by_name
assert 0.0 <= value <= 1.0, f"q-value out of range: {value}"


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

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


Expand Down
38 changes: 38 additions & 0 deletions tests/integration/test_typed_confidence.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,44 @@ def test_a_value_the_producer_typed_wins(tmp_path):
assert pq.read_table(path, columns=["peptide_qvalue"]).column("peptide_qvalue").to_pylist() == [0.001]


@pytest.mark.parametrize(
"writer_class,make_record,column,alias",
[
(FeatureWriter, make_feature_record, "peptide_qvalue", "peptide_level_qvalue"),
(FeatureWriter, make_feature_record, "precursor_qvalue", "q_value"),
(FeatureWriter, make_feature_record, "global_qvalue", "diann_global_qvalue"),
(PsmWriter, make_psm_record, "qvalue", "percolator_q_value"),
],
)
def test_writer_removes_only_duplicate_typed_qvalues(tmp_path, writer_class, make_record, column, alias):
"""Canonical equal scores move to typed columns; aliases, differing values and null lists remain."""
inputs = [
(None, [_score(column, 0.01), _score(alias, 0.01)]),
(0.02, [_score(column, 0.03), _score(alias, 0.02)]),
(None, None),
(None, [_score(column, 0.04)]),
(None, []),
(None, [_score(column.upper(), 0.05)]),
]
records = [
make_record(run_file_name=f"run{i}", additional_scores=scores, **{column: value})
for i, (value, scores) in enumerate(inputs)
]
path = tmp_path / "typed.parquet"
with writer_class(path) as writer:
writer.write_batch(records)
table = pq.read_table(path)
assert table.column(column).to_pylist() == [0.01, 0.02, None, 0.04, None, 0.05]
assert table.column("additional_scores").to_pylist() == [
[_score(alias, 0.01)],
[_score(column, 0.03), _score(alias, 0.02)],
None,
[],
[],
[],
]


def _table(records):
import pyarrow as pa

Expand Down
Loading