Skip to content

Commit e02ccde

Browse files
authored
Merge pull request #321 from bigbio/dev
Fix integrity verification and handle large string concatenation
2 parents 4312c8c + a173972 commit e02ccde

14 files changed

Lines changed: 815 additions & 84 deletions

File tree

‎CHANGELOG.md‎

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

1010
### Changed
1111

12+
- **OpenMS feature protein attribution for shared peptides** — releases up to 1.1.3 assigned every feature to the protein group of its *first* protein evidence, an order that carries no meaning, and set `unique` from that group's size. A peptide shared by two groups was therefore attributed to one of them arbitrarily and often reported `unique = true`. Features now resolve their group from the full evidence set and the originating identification; when the evidence spans more than one inferred group, `anchor_protein`, `pg_accessions`, `unique`, `pg_global_qvalue` and `gg_*` are null and the feature's intensities are kept. `pg` is unaffected, since protein intensities are built from unique peptides only. On PXD000612 (DDA LFQ, 231 runs) this nulls the group on 255,416 of 3,956,057 features (6.5%, 9,331 peptidoforms, 15% of feature intensity), 8,829 of which 1.1.3 had marked unique. **OpenMS datasets converted with earlier releases over-report `unique` and carry arbitrary groups on shared peptides; reconvert before relying on feature-level protein attribution.**
1213
- **MuData stack is core**: `mudata`, `anndata`, and `scipy` are required dependencies (no longer an optional extra). Use bare `pip install qpx`.
1314
- **`quantify` extra**: now `mokume[directlfq]>=0.1.0` (DirectLFQ via mokume's optional extra).
1415

@@ -20,6 +21,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2021

2122
### Fixed
2223

24+
- **OpenMS feature view left `pg_global_qvalue`, `gg_names` and `gg_accessions` null** — the consensusXML converter computed each protein group's q-value and gene names for the pg view and then discarded them, so every feature carried none while its group in pg had both (PXD000612: pg 100%, feature 0%). Features now carry their own group's values from the same derivation as pg, in both the streaming and in-memory paths, including when two groups share a leading protein. Matching uses full membership and the originating identification, independently of protein evidence order; ambiguous groups and runs with conflicting peptide sequences keep protein-group fields null while feature intensities are retained.
25+
- **`verify_integrity` read whole files into memory** — it hashed each file with `read_bytes()` while `compute_integrity` streamed the same files in 64 KiB chunks, so verifying a multi-gigabyte feature or PSM view allocated the entire file. Both paths now share one chunked hasher.
26+
- **`verify_integrity` ignored `file_row_counts` and `file_sizes_bytes`** — both were computed and stored but never read back, so only checksums were ever verified. Row counts and sizes are now compared, the `-1` "could not be read" sentinel warns instead of silently counting as verified, and `compute_integrity` logs when it stores it.
27+
- **`verify_integrity` could not detect unrecorded files** — it walked only the stored checksum keys, so a file added to a dataset after packaging verified clean. Files not covered by the integrity record are now reported as warnings.
28+
- **A failed modality left no trace a caller could act on** — `build_mudata` logged the failure and continued, so a MuData missing `precursors` was indistinguishable from one that never had it. Failures are now recorded in `mdata.uns["qpx_failed_modalities"]` (always present, empty when nothing failed), and `write_dataset_mudata` names the reason in its error rather than only the missing modality.
29+
- **MuData silently lost the `precursors` modality on large multiplexed data** — combining a `string` Arrow column over 2 GiB overflowed its int32 offsets, `build_mudata` caught the error and returned a partial MuData, and the pipeline wrote an incomplete `.h5mu` reporting success. String and binary columns are now widened to `large_string`/`large_binary` before combining. MSV000085836 (TMT, 552 runs x 10 channels) goes from `['proteins']` to `['precursors', 'proteins']`.
2330
- **`gene-map --dataset` copied only top-level files** — sharded / partitioned datasets kept their views in subdirectories, so an annotated copy came back incomplete. Subdirectories are now copied too, and a `--output-folder` that is the dataset itself or nested inside it is rejected instead of copying into its own destination.
2431
- **`gene-map` accepted `--in-place` together with `--output-folder`** — the destination silently won; it is now a usage error.
2532
- **`annotate_dataframe` divided by zero on an empty view** — the mapped-share log now reports 0.0%.

‎docs/spec/ontology.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ Sample metadata fields map to biological ontologies. These mappings are critical
198198
| `anchor_protein` | anchor protein | `MS:1001591` | Representative protein of the protein group |
199199
| `pg_positions` | --- | --- | Peptide start/end positions in each protein |
200200
| `pg_global_qvalue` | protein-level global FDR | `MS:1001214` | Global q-value of the protein group |
201-
| `unique` | --- | --- | Unique peptide indicator |
201+
| `unique` | --- | --- | True for a single-protein group; null when the peptide's evidence spans more than one inferred group |
202202
| `gg_accessions` | --- | --- | Gene group identifiers |
203203
| `gg_names` | --- | --- | Gene group names |
204204
| `mass_error_ppm` | --- | --- | Mass error in ppm |

‎docs/spec/schemas/feature.yaml‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -107,15 +107,15 @@ fields:
107107
# Protein mapping
108108
pg_accessions:
109109
type: "list<pg_protein>"
110-
doc: "Protein group accessions with optional peptide positions (start, end)"
110+
doc: "Full membership of the peptide's protein group, with optional peptide positions (start, end). Null under the same conditions as anchor_protein."
111111
anchor_protein:
112112
type: string
113113
required: true
114114
nullable: true
115-
doc: "Representative protein; null when no protein mapping was performed"
115+
doc: "Representative protein of the peptide's protein group. Null when no protein mapping was performed, or when the peptide's protein evidence spans more than one inferred protein group (a shared peptide the producer did not assign); the feature's intensities are kept either way."
116116
unique:
117117
type: bool
118-
doc: "Unique peptide indicator"
118+
doc: "True when the peptide resolves to a protein group of exactly one protein, False when that group has several members. Null when the group is unresolved, including a shared peptide whose evidence spans more than one inferred group."
119119
pg_global_qvalue:
120120
type: float64
121121
optional: true

‎qpx/converters/openms_consensus/converter.py‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@
2222
load_consensus_map,
2323
)
2424
from qpx.converters.openms_consensus.pg_adapter import (
25-
accession_to_group,
2625
consensus_protein_groups_to_records,
26+
protein_group_maps,
2727
)
2828
from qpx.converters.orchestrator import BaseOrchestrator
2929
from qpx.core.constants import FEATURE, ONTOLOGY, PG, PSM, RUN, SAMPLE
@@ -100,14 +100,14 @@ def _should_stream(path: str) -> bool:
100100
return False
101101

102102

103-
def _cf_feature_psm_records(cf, map_info, group_map, resolve_run, seen, *, want_feature, want_psm, enzyme=None):
103+
def _cf_feature_psm_records(cf, map_info, group_map, resolve_run, seen, *, want_feature, want_psm, enzyme=None, group_meta=None):
104104
"""Feature + PSM records for one consensus feature, cross-linked when both views
105105
are emitted. Shared by the streaming and in-memory paths so their output matches.
106106
"""
107107
from qpx.converters.openms_consensus.feature_adapter import feature_records_for_cf
108108
from qpx.converters.openms_consensus.psm_adapter import _cf_element_runs, psm_records_for_pid
109109

110-
cf_feats = feature_records_for_cf(cf, map_info, group_map, enzyme=enzyme) if want_feature else []
110+
cf_feats = feature_records_for_cf(cf, map_info, group_map, enzyme=enzyme, group_meta=group_meta) if want_feature else []
111111
cf_psms: list[dict] = []
112112
if want_psm:
113113
# Multi-run isobaric PIDs carry a local id_merge_index; the feature's
@@ -148,6 +148,7 @@ def _stream_feature_psm(
148148
batch,
149149
include_unassigned_psms=True,
150150
enzyme=None,
151+
group_meta=None,
151152
):
152153
"""One ordered element/unassigned pass: write feature/psm in batches and
153154
accumulate the pg maps in place (the streaming path's inner loop)."""
@@ -171,6 +172,7 @@ def _stream_feature_psm(
171172
want_feature=fw is not None,
172173
want_psm=pw is not None,
173174
enzyme=enzyme,
175+
group_meta=group_meta,
174176
)
175177
feat_buf.extend(cf_feats)
176178
psm_buf.extend(cf_psms)
@@ -222,7 +224,6 @@ def _convert_streaming(
222224
from qpx.converters.openms_consensus.feature_adapter import _run_stem, feature_map_info, resolve_enzyme
223225
from qpx.converters.openms_consensus.pg_adapter import (
224226
_ProteinMaps,
225-
accession_to_group,
226227
build_pg_records,
227228
)
228229
from qpx.converters.openms_consensus.psm_adapter import _run_resolver
@@ -237,7 +238,7 @@ def _convert_streaming(
237238
headers = cm.getColumnHeaders()
238239
map_run = {i: _run_stem(headers[i].filename) for i in headers}
239240
want_feature, want_psm, want_pg = ("feature" in structures, "psm" in structures, "pg" in structures)
240-
group_map = accession_to_group(cm) if want_feature else None
241+
group_map, group_meta = protein_group_maps(cm) if want_feature else (None, None)
241242
resolve_run = _run_resolver(cm) if want_psm or want_pg else None
242243
maps = _ProteinMaps() if want_pg else None
243244
pep_intensity: dict = defaultdict(float) if want_pg else {}
@@ -278,6 +279,7 @@ def _convert_streaming(
278279
batch=100_000,
279280
include_unassigned_psms=include_unassigned_psms,
280281
enzyme=resolve_enzyme(cm, sdrf_path),
282+
group_meta=group_meta,
281283
)
282284
if fw is not None:
283285
written["feature"] = out / f"{output_prefix}.feature.parquet"
@@ -575,7 +577,7 @@ def _convert_in_memory(
575577
map_info = feature_map_info(cm)
576578
# Share the full protein-group membership so feature.anchor_protein and
577579
# feature.pg_accessions match pg (unambiguous even for shared leaders).
578-
group_map = accession_to_group(cm) if want_feature else None
580+
group_map, group_meta = protein_group_maps(cm) if want_feature else (None, None)
579581
resolve_run = _run_resolver(cm) if want_psm else None
580582
seen: set = set()
581583
enzyme = resolve_enzyme(cm, sdrf_path)
@@ -591,6 +593,7 @@ def _convert_in_memory(
591593
want_feature=want_feature,
592594
want_psm=want_psm,
593595
enzyme=enzyme,
596+
group_meta=group_meta,
594597
)
595598
feat_recs.extend(cf_feats)
596599
psm_recs.extend(cf_psms)

‎qpx/converters/openms_consensus/feature_adapter.py‎

Lines changed: 53 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from typing import Optional
1717

1818
from qpx.converters.channel_labels import normalize_label
19+
from qpx.converters.openms_consensus.protein_groups import ProteinGroupIndex, identification_identifier
1920
from qpx.core.cleavage import count_missed_cleavages
2021
from qpx.core.files import run_file_stem as _run_stem
2122

@@ -450,30 +451,32 @@ def _group_subfeatures_by_run(cf, map_info: dict[int, tuple[str, str]]) -> dict[
450451
return by_run
451452

452453

453-
def consensus_features_to_records(consensusxml_path: str | None = None, cm=None, group_map=None, sdrf_path=None) -> list[dict]:
454+
def consensus_features_to_records(
455+
consensusxml_path: str | None = None, cm=None, group_map=None, sdrf_path=None, group_meta=None
456+
) -> list[dict]:
454457
"""Return QPX feature record dicts extracted from a consensusXML.
455458
456459
Pass either ``consensusxml_path`` (loaded here) or an already-loaded ``cm``.
457460
``sdrf_path`` is optional and only supplies the digestion enzyme for
458461
``missed_cleavages``; without it the enzyme falls back to the consensusXML
459462
``SearchParameters``.
460463
461-
``group_map`` (accession -> full protein-group membership, from
462-
``pg_adapter.accession_to_group``) makes each feature stamp BOTH the same
463-
group leader the pg view uses as ``anchor_protein`` AND the full
464-
``pg_accessions`` membership, so the feature->pg join is unambiguous even
465-
when two distinct groups share a leader; without it the anchor falls back to
466-
the peptide's first protein evidence and ``pg_accessions`` is null.
464+
``group_map`` accepts the index from ``pg_adapter.protein_group_maps`` or a
465+
legacy accession -> membership dict. Resolved groups carry the pg view's
466+
leader and full membership; unresolved groups and annotations stay null.
467+
Without a group, a sole protein evidence may still supply the anchor.
467468
"""
468469
cm = cm if cm is not None else load_consensus_map(consensusxml_path)
469470
map_info = feature_map_info(cm)
471+
if isinstance(group_map, dict):
472+
group_map = ProteinGroupIndex.from_groups(group_map.values())
470473
# Resolve the enzyme once, as the converter does, so this public entry point
471474
# reports missed_cleavages too. Without it a caller of the library API got a
472475
# null column while the same data through the CLI got a value.
473476
enzyme = resolve_enzyme(cm, sdrf_path)
474477
records: list[dict] = []
475478
for cf in cm:
476-
records.extend(feature_records_for_cf(cf, map_info, group_map, enzyme=enzyme))
479+
records.extend(feature_records_for_cf(cf, map_info, group_map, enzyme=enzyme, group_meta=group_meta))
477480
return records
478481

479482

@@ -487,7 +490,43 @@ def feature_map_info(cm) -> dict[int, tuple[str, str]]:
487490
return {idx: (_run_stem(headers[idx].filename), _map_label(headers[idx].label)) for idx in headers}
488491

489492

490-
def feature_records_for_cf(cf, map_info: dict[int, tuple[str, str]], group_map=None, enzyme=None) -> list[dict]:
493+
def _protein_group_fields(pid, group_map, group_meta) -> dict:
494+
"""Attach metadata only after resolving the identification's protein group."""
495+
accessions = {ev.getProteinAccession() for ev in pid.getHits()[0].getPeptideEvidences()}
496+
accessions = {acc.decode() if isinstance(acc, bytes) else acc for acc in accessions if acc}
497+
if isinstance(group_map, dict):
498+
group_map = ProteinGroupIndex.from_groups(group_map.values())
499+
group = group_map.resolve(accessions, identification_identifier(pid)) if group_map is not None else None
500+
qvalue, genes = (group_meta or {}).get(group, (None, None)) if group else (None, None)
501+
return {
502+
"anchor_protein": group[0] if group else (next(iter(accessions)) if len(accessions) == 1 else None),
503+
"pg_accessions": [{"accession": a, "start": None, "end": None, "pre": None, "post": None} for a in group]
504+
if group
505+
else None,
506+
"unique": len(group) == 1 if group else None,
507+
"pg_global_qvalue": qvalue,
508+
"gg_accessions": genes,
509+
"gg_names": genes,
510+
}
511+
512+
513+
def _protein_groups_by_run(pids, map_info, cf_runs, group_map, group_meta) -> dict[str, dict]:
514+
"""Use each run's own identification; conflicting assignments stay unknown."""
515+
by_run: dict[str, dict] = {}
516+
sequence = pids[0].getHits()[0].getSequence()
517+
for pid in pids:
518+
hits = pid.getHits()
519+
run = _pid_run(pid, map_info, cf_runs)
520+
if run is None or not hits:
521+
continue
522+
fields = _protein_group_fields(pid, group_map, group_meta)
523+
if hits[0].getSequence() != sequence:
524+
fields = dict.fromkeys(fields)
525+
by_run[run] = dict.fromkeys(fields) if run in by_run and by_run[run] != fields else fields
526+
return by_run
527+
528+
529+
def feature_records_for_cf(cf, map_info: dict[int, tuple[str, str]], group_map=None, enzyme=None, group_meta=None) -> list[dict]:
491530
"""Feature records for one consensus feature (one per run, channels as intensities).
492531
493532
``pg_accessions`` carries the full protein-group membership; the feature->pg
@@ -515,22 +554,10 @@ def feature_records_for_cf(cf, map_info: dict[int, tuple[str, str]], group_map=N
515554
streamed_consensus_rt = getattr(cf, "consensus_rt", None)
516555
consensus_rt = float(cf.getRT() if streamed_consensus_rt is None else streamed_consensus_rt)
517556
calculated_mz = float(seq_obj.getMZ(charge)) if charge else observed_mz
518-
evidences = hit.getPeptideEvidences()
519-
orig = evidences[0].getProteinAccession() if evidences else None
520-
if isinstance(orig, bytes):
521-
orig = orig.decode()
522-
# Resolve to the full protein-group membership so feature.anchor_protein AND
523-
# feature.pg_accessions match the pg view (peptide evidence order alone does
524-
# not identify the leader, nor the group when leaders are shared). Keep the
525-
# group in the order _merge_protein_ids/_build_groups produced so pg_accessions
526-
# lines up row-for-row with the pg view's pg_accessions for that group.
527-
group = group_map.get(orig) if (group_map and orig is not None) else None
528-
anchor_protein = group[0] if group else orig
529-
pg_accessions = [{"accession": a, "start": None, "end": None, "pre": None, "post": None} for a in group] if group else None
530-
# A peptide is unique when its resolved group holds exactly one protein.
531-
# With no resolved group the answer is unknown: a lone peptide evidence is
532-
# not proof of uniqueness, and claiming True there would invent information.
533-
unique = (len(group) == 1) if group else None
557+
protein_fields = _protein_group_fields(pids[0], group_map, group_meta)
558+
protein_fields_by_run = _protein_groups_by_run(pids, map_info, cf_runs, group_map, group_meta)
559+
if any(fields != protein_fields for fields in protein_fields_by_run.values()):
560+
protein_fields = dict.fromkeys(protein_fields)
534561
error_ppm = mass_error_ppm(calculated_mz, observed_mz) if charge > 0 else None
535562
# Missed cleavages are a property of the peptide and the search enzyme, both
536563
# of which are in hand; the DIA-NN path already reports them (bigbio/qpx#300).
@@ -557,10 +584,8 @@ def feature_records_for_cf(cf, map_info: dict[int, tuple[str, str]], group_map=N
557584
"observed_mz": observed_mz,
558585
"mass_error_ppm": error_ppm,
559586
"missed_cleavages": missed,
560-
"unique": unique,
561587
"consensus_rt": consensus_rt,
562-
"anchor_protein": anchor_protein,
563-
"pg_accessions": pg_accessions,
588+
**protein_fields_by_run.get(run, protein_fields),
564589
"additional_scores": additional_scores,
565590
}
566591
)

0 commit comments

Comments
 (0)