Metadata-Version: 2.4
Name: apb-export
Version: 0.2.2
Summary: APB2 results exported for nine downstream targets: msmu, MSstats, Perseus, prolfqua, ProteoPy, exploreDE, AlphaPeptTools, QFeatures and QPX
Author: Witold Wolski
Author-email: Witold Wolski <wew@fgcz.ethz.ch>
License-Expression: MIT
License-File: LICENSE
License-File: src/apb_export/qpx/LICENSE.qpx
Requires-Dist: apb2>=0.1.3,<0.2
Requires-Dist: apb-catalog>=0.1.5,<0.2
Requires-Dist: apb-fasta>=0.1.2,<0.2
Requires-Dist: cyclopts>=4,<5
Requires-Dist: loguru>=0.7,<1
Requires-Dist: numpy>=2,<3
Requires-Dist: polars>=1.43,<2
Requires-Dist: pyarrow>=21,<24
Requires-Dist: pydantic>=2.10,<3
Requires-Python: >=3.13
Description-Content-Type: text/markdown

# APB Export

**[Online documentation](https://anndata-omics-bridge.github.io/apb-export/)** or its [source index](docs/index.md).

Try it online:

- [Rules viewer](https://fgcz-ms.uzh.ch/public/apb-rules/): every vendor table's parse rules, as apb2 packages them
- [Catalog viewer](https://fgcz-ms.uzh.ch/public/apb-catalog/): every catalog set with its entries and coverage
- [APB Studio](https://fgcz-ms.uzh.ch/public/apb-studio/): APB's corpus runs over the test vendor files
- [APB Export](https://apps-dev.bfabric.org/apb-export/): convert a vendor table for a downstream tool in the browser

APB2 results exported as downstream AnnData, MuData, CSV long tables, Perseus tables and QPX Parquet: one export rule per target, one subcommand per target. HDF5 files get APB2's `<file>.apb.json` sidecar, which APB Studio's viewer reads; exploreDE's `.h5ad` files, one per level, live in a new `.h5ads` directory. QPX tables and their export manifest live in a new `.qpx` directory; the `.csv` and `.txt` tables have no sidecar. Each target fixes the APB2 levels it reads; `--abundance` picks which layer of a single-level target becomes X, and `--annotation` attaches an SDRF or prolfquapp-style sample table, as `apb2 annotate` does.

```bash
apb-export msmu report.tsv result.h5mu --params report.log.txt
apb-export msmu report.tsv result.h5mu --params report.log.txt --fasta proteins.fasta
apb-export prolfqua report.tsv result.h5ad --params report.log.txt --annotation dataset.csv
apb-export msstats report.tsv msstats.csv --params report.log.txt --annotation design.tsv
apb-export perseus report.tsv perseus.txt --params report.log.txt --annotation samples.tsv
apb-export proteopy report.tsv proteins.h5ad --params report.log.txt
apb-export alphapepttools report.tsv linked.h5mu --params report.log.txt
apb-export qfeatures report.tsv qfeatures.h5mu --params report.log.txt
apb-export qpx report.tsv result.qpx --params report.log.txt
```

The msmu file is the MuData [msmu](https://github.com/bertis-informatics/msmu) builds itself: apb-catalog names the confidence fields, and msmu takes the result with `msmu.read_h5mu` and runs unchanged.

```python
import msmu as mm

mdata = mm.read_h5mu("result.h5mu")
mdata = mm.pp.add_filter(mdata, modality="psm", column="q_value", keep="lt", value=0.01)
mdata = mm.pp.apply_filter(mdata, modality="psm", on="var")
mdata = mm.pp.to_peptide(mdata, calculate_q=False)
```

From Python, APB2 converts and `Exporter` exports, the shape of the other APB tools:

```python
from pathlib import Path

from apb2.api import ParseRuleCompiler
from apb_export.api import Exporter

exporter = Exporter("msmu")
parsed = ParseRuleCompiler.detect(
    Path("report.tsv"), Path("report.log.txt"), requested_levels=exporter.levels
).compile().parse()
exporter.write(exporter.export(parsed), Path("result.h5mu"))
```

`write` uses APB2's `write_parsed_levels` for HDF5, `.h5ads` included, and target-specific serializers for QPX, the `.csv` long table and the `.txt` Perseus table. An APB2 result already on disk works the same way through `apb2.api.read_parsed_levels`. `Exporter.targets()` lists the packaged targets; `extension` names the file suffix or `.qpx` or `.h5ads` directory.

QPX exports existing precursor and/or protein quantities, with no aggregation or required grouping, FASTA or SDRF. RT is resolved through APB Catalog's `chromatography` set and converted from its reviewed unit to seconds. [QPX layout and pMultiQC](docs/targets.md#qpx) describes the tables, missing metadata and report compatibility.

## Install

```bash
uv tool install --python 3.13 apb-export
```

This puts `apb-export` on the PATH in an environment of its own; `--with-executables-from apb2,apb-fasta` adds the `apb2` and `apb-fasta` commands. Python 3.13 is the tested interpreter.

## What it writes

msmu's `psm` modality, written wide. Experimental: msmu's own readers write one feature per run and precursor, and msmu's tools may expect that.

- one `psm` modality; runs are observations, precursors are features, id `<ProForma precursor>`; the keys `filename` and `precursor` stay columns and name the indices, as APB2 writes them
- `X`: dense float32, the chosen abundance layer (`--abundance`, APB2's primary layer by default); a precursor absent from a run is NaN
- `layers`: `q_value`, the library or experiment-wide q-value repeated in every run where the vendor reports one, else each run's; each run's `PEP`, where the vendor reports it
- `var`: `proteins`, `peptide`, `stripped_peptide`, `charge`, `peptide_length`, `decoy`, `contaminant`, and `PEP` and `q_value` where reported, each the precursor's lowest value across runs
- `uns`: `apb_export_status: "experimental"`, msmu's reader settings, plus APB metadata as in an APB2 result: the MuData's `uns["apb"]` holds the result's root records and the `export` record (rule, target, versions); each modality's `uns["apb"]` holds that level's apb2 records unchanged and the `export` record with each field's APB source and a summary

`peptide` is ProForma for every vendor (`AC[UNIMOD:4]K`), not each vendor's own notation. msmu's modification parser reads it, and `to_ptm` takes the tag as written, for example `"[UNIMOD:21]"`.

## Export rules

The layout above is declared in [msmu's export rule](src/apb_export/export_rules/documents/msmu/v0_4/rules.json), not coded. Rules follow APB2's rule schema read in reverse: an entry's `name` is the target's field, its `source` an APB field every vendor shares: the run key, the primary layer, or a meaning catalogued by apb-catalog, APB's own columns included (`{"catalog": "apb_alpha", "var": "peptidoform_ion"}` is `ProForma_ion`). Where the result may lack the source, `fallback` lists what to read instead, in order, and the export logs which one it read. A table's `base` holds what every level shares; a level adds its own entries, and one with a base entry's name replaces it. A catalogued source with `"from_level": "protein"` reads the protein level through each variable's protein group, named whole or by the protein that leads it: a cell takes its group's value in its run; a var column's value, the group's, repeats in every run. A level block may name the `software` it is for; an `.h5ad` rule lists its levels in order and writes the first one the result's software and levels allow. One engine checks every source before it builds anything; the published [JSON Schemas](src/apb_export/export_rules/documents/_schema) describe the documents. An installed package can add a target through the `apb_export.targets` entry-point group; see [plugin targets](docs/targets.md#plugin-targets).

| Target | File | APB2 levels | Layout |
| --- | --- | --- | --- |
| [msmu](src/apb_export/export_rules/documents/msmu/v0_4/rules.json) | `.h5mu` | peptidoform_ion | `psm` modality, precursors by runs, experimental; a feature without a protein is left out and counted in the export record |
| [MSstats](src/apb_export/export_rules/documents/msstats/v4_20/rules.json) | `.csv` | peptidoform_ion | long table, one row per precursor and run, MSstats' column names |
| [Perseus](src/apb_export/export_rules/documents/perseus/v2/rules.json) | `.txt` | protein | wide, proteinGroups.txt's names, `#!{Type}` and `#!{C:…}` header rows |
| [prolfquapp](src/apb_export/export_rules/documents/prolfqua/v2_11/rules.json) | `.h5ad` | peptidoform_ion, or peptide for MaxQuant; reading protein | wide; `uns["prolfquapp"]` for `LFQData_from_anndata`, factors from `apb2 annotate` columns; confidence layers `qValue` (precursor, per run), `pg_qValue` (protein group, per run), `pg_qValue_experiment` (protein group, library or experiment-wide, the same in every run) and `pep`, each where the vendor reports it; a feature without a protein is left out and counted in the export record; with `--fasta`, the leading protein's `fasta.id`, `description`, `IDcolumn` (accession), `gene_name`, `protein_length` and `nr_tryptic_peptides`, as prolfquapp's own FASTA annotation writes them; without one, `fasta.id`, `description` and `IDcolumn` repeat `protein_Id` |
| [ProteoPy, ions](src/apb_export/export_rules/documents/proteopy_ion/v0_1/rules.json) | `.h5ad` | peptidoform_ion | wide; `sample_id`, `peptide_id` (the ion's ProForma) and `protein_id`; an ion naming several proteins is left out, as ProteoPy's own DIA-NN reader does; ProteoPy rolls the ions up itself |
| [ProteoPy](src/apb_export/export_rules/documents/proteopy/v0_1/rules.json) | `.h5ad` | protein | wide; `sample_id` and `protein_id` beside their indexes; with `--fasta`, apb-fasta annotates the protein groups and adds `in_fasta`, `gene_id`, `description` and `fasta_organisms`, which ProteoPy does not read |
| [exploreDE](src/apb_export/export_rules/documents/explorede/v1_0/rules.json) | `.h5ads` directory | protein, peptide, peptidoform_ion, those present | `exploreDE/1.0` without differential expression, one file per level the result holds: `protein.h5ad`, `peptide.h5ad`, `precursor.h5ad`; log2 `intensities` with vendor zeros missing, linear `intensities_raw`, X a copy of `intensities`; SDRF `factor value[…]` and prolfquapp `group`/`bait` columns become `factor_<name>` with sorted categories, other annotation columns pass unprefixed; `feature_id` is the protein group, or `<protein>_<peptide>` and `<protein>_<ProForma ion>`; `label_gene_symbol` is the leading protein's FASTA gene name, else its entry name or accession, with the peptide or precursor appended; `uns` holds exploreDE's identity keys and empty `de`, `enrichment` and `enrichment_support` |
| [AlphaPeptTools](src/apb_export/export_rules/documents/alphapepttools/v0_4/rules.json) | `.h5mu` | peptidoform_ion, peptide, protein | one wide modality per level, linked by id columns for `mulink_from_anndatas`; peptidoform_ion and peptide modalities carry `contaminant` and, with `--fasta`, `in_fasta`, `fasta_proteins` and `fasta_organisms`, which AlphaPeptTools does not read |
| [QFeatures](src/apb_export/export_rules/documents/qfeatures/v1_22/rules.json) | `.h5mu` | peptidoform_ion, peptide, protein | AlphaPeptTools' layout; assays linked by `addAssayLink` on id columns |
| [QPX](src/apb_export/export_rules/documents/qpx/v1_1/rules.json) | `.qpx` directory | peptidoform_ion and/or protein | QPX 1.1 feature/protein Parquet, optional annotations and export manifest; existing primary quantities, catalogued RT in seconds |

## Confidence, by meaning

- `q_value`: the library q-value (a var column) when it holds a nonzero value, else the experiment-wide q-value (var), else the per-run q-value; the first two repeat in every run; the order msmu's DIA-NN reader uses
- `PEP`: the vendor's posterior error probability
- Lookup: apb-catalog's `confidence` and `proteobench_entrapment` catalogues, never vendor column names
- Not reported: no `q_value` column, so msmu's filter cannot act on an invented value; `PEP` is NaN, because msmu's `to_peptide` requires the column
- Unreviewed rule: apb-catalog answers "unknown" and the command stops; unknown is not missing

## Protein groups

Written as msmu's readers write them: members split on `;`, the accession taken from a UniProt `db|ACC|NAME` entry, and members spelled `contam_`, `Cont_` or `CON__` respelled `Cont_ACC`. `contaminant` flags a row that apb2 marked `apb_Contaminant`, a contaminant the software flags or adds itself, or that apb-fasta matched to a FASTA contaminant. `apb-export msmu --fasta` runs that FASTA check after conversion; without a FASTA only the vendor's own flags are known.

## Web application

The upload page, server and deployment now belong to [APB Export UI](https://github.com/anndata-omics-bridge/apb-export-ui). It installs a locked APB stack and provides `apb-export-web`; this library provides `apb-export` only.

## Limits

- A result without the level a target reads is refused: msmu needs an `peptidoform_ion` level (Sage's `lfq.tsv` is peptide-level), ProteoPy a `protein` level, ProteoPy ions a `peptidoform_ion` level
- Label-free only: a result keyed by more than one observation column, as multiplexed designs are, is refused
- `decoy` is apb2's `apb_Decoy`; most exports carry no decoys, and msmu's target-decoy q-values need them, so use `calculate_q=False` unless the vendor kept them
- Group separators other than `;` pass through unchanged; no APB2 rule declares its separator
- QPX maps retention time through the chromatography catalogue; an unknown original unit is refused instead of assumed
- msmu's file has no per-run `filename` column: msmu tools that group features by file see precursors, not identifications

## Development

The development release expects APB2, apb-catalog and apb-fasta, with apb-fasta's protein_fasta and Prozor, checked out beside this repository, on `main`, as CI checks them out:

```text
anndata_bridge/
├── apb2/
├── apb-catalog/
├── apb-fasta/
├── protein_fasta/
├── prozor/
└── apb-export/
```

```bash
uv sync --group dev
make check
make check-full
```

Tests use synthetic vendor files only and install none of the target tools. Whether the tools read the files is checked in [consumers/](consumers): the [Consumers workflow](.github/workflows/consumers.yml) exports the synthetic examples, validates the QPX ones with qpx and the released pMultiQC, builds one image with msmu, ProteoPy, AlphaPeptTools and perseuspy and one R image with QFeatures and MSstats, and runs each tool's check, msmu's comparison with its own `read_diann` and ProteoPy's ion file against its own DIA-NN reader among them. prolfquapp's check runs in prolfquapp's own image and compares its APB reader with its own `preprocess_DIANN` on peptide and protein values.
