apb-export 0.2.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. apb_export/__init__.py +1 -0
  2. apb_export/api.py +98 -0
  3. apb_export/cli.py +562 -0
  4. apb_export/computed.py +135 -0
  5. apb_export/engine.py +717 -0
  6. apb_export/export_rules/__init__.py +0 -0
  7. apb_export/export_rules/documents/_schema/document.schema.json +1280 -0
  8. apb_export/export_rules/documents/_schema/rule.schema.json +1454 -0
  9. apb_export/export_rules/documents/alphapepttools/v0_4/rules.json +98 -0
  10. apb_export/export_rules/documents/explorede/v1_0/rules.json +197 -0
  11. apb_export/export_rules/documents/msmu/v0_4/rules.json +127 -0
  12. apb_export/export_rules/documents/msstats/v4_20/rules.json +66 -0
  13. apb_export/export_rules/documents/perseus/v2/rules.json +59 -0
  14. apb_export/export_rules/documents/prolfqua/v2_11/rules.json +223 -0
  15. apb_export/export_rules/documents/proteopy/v0_1/rules.json +53 -0
  16. apb_export/export_rules/documents/proteopy_ion/v0_1/rules.json +62 -0
  17. apb_export/export_rules/documents/qfeatures/v1_22/rules.json +98 -0
  18. apb_export/export_rules/documents/qpx/v1_1/rules.json +110 -0
  19. apb_export/export_rules/layout.py +60 -0
  20. apb_export/export_rules/loader.py +208 -0
  21. apb_export/export_rules/schema.py +502 -0
  22. apb_export/export_rules/schema_artifact.py +40 -0
  23. apb_export/long_table.py +75 -0
  24. apb_export/outputs.py +90 -0
  25. apb_export/perseus_table.py +100 -0
  26. apb_export/py.typed +1 -0
  27. apb_export/qpx/LICENSE.qpx +81 -0
  28. apb_export/qpx/__init__.py +0 -0
  29. apb_export/qpx/output.py +215 -0
  30. apb_export/qpx/schema.json +662 -0
  31. apb_export/qpx/schema.py +32 -0
  32. apb_export/rows.py +72 -0
  33. apb_export/sources.py +415 -0
  34. apb_export-0.2.2.dist-info/METADATA +159 -0
  35. apb_export-0.2.2.dist-info/RECORD +39 -0
  36. apb_export-0.2.2.dist-info/WHEEL +4 -0
  37. apb_export-0.2.2.dist-info/entry_points.txt +3 -0
  38. apb_export-0.2.2.dist-info/licenses/LICENSE +21 -0
  39. apb_export-0.2.2.dist-info/licenses/src/apb_export/qpx/LICENSE.qpx +81 -0
apb_export/rows.py ADDED
@@ -0,0 +1,72 @@
1
+ """Rows an export writes, and resolved sources aligned to them.
2
+
3
+ Variable rows take variable values, observation rows observation values, and the single
4
+ ``uns`` row a scalar; a scalar repeats on any row.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import polars as pl
10
+
11
+ from apb_export.sources import ObsValues, Resolved, ScalarValue, VarValues
12
+
13
+
14
+ class FeatureRows:
15
+ """One row per variable of the level."""
16
+
17
+ def __init__(self, count: int) -> None:
18
+ """Align to this many variables."""
19
+ self._count = count
20
+
21
+ def count(self) -> int:
22
+ """The number of rows."""
23
+ return self._count
24
+
25
+ def align(self, resolved: Resolved) -> pl.Series:
26
+ """Variable values as they are; a scalar repeated."""
27
+ match resolved:
28
+ case VarValues():
29
+ return resolved.values
30
+ case ScalarValue():
31
+ return pl.Series([resolved.value] * self._count)
32
+ case _:
33
+ raise ValueError(f"a variable row cannot take {resolved.provenance}")
34
+
35
+
36
+ class ObservationRows:
37
+ """One row per observation of the level."""
38
+
39
+ def __init__(self, count: int) -> None:
40
+ """Align to this many observations."""
41
+ self._count = count
42
+
43
+ def count(self) -> int:
44
+ """The number of rows."""
45
+ return self._count
46
+
47
+ def align(self, resolved: Resolved) -> pl.Series:
48
+ """Observation values as they are; a scalar repeated."""
49
+ match resolved:
50
+ case ObsValues():
51
+ return resolved.values
52
+ case ScalarValue():
53
+ return pl.Series([resolved.value] * self._count)
54
+ case _:
55
+ raise ValueError(f"an observation row cannot take {resolved.provenance}")
56
+
57
+
58
+ class ScalarRow:
59
+ """The single row of ``uns`` entries."""
60
+
61
+ def count(self) -> int:
62
+ """Always one."""
63
+ return 1
64
+
65
+ def align(self, resolved: Resolved) -> pl.Series:
66
+ """A scalar as a one-value series."""
67
+ if not isinstance(resolved, ScalarValue):
68
+ raise ValueError(f"a uns entry cannot take {resolved.provenance}")
69
+ return pl.Series([resolved.value])
70
+
71
+
72
+ type Rows = FeatureRows | ObservationRows | ScalarRow
apb_export/sources.py ADDED
@@ -0,0 +1,415 @@
1
+ """APB references resolved against one level: what an export rule's sources point at.
2
+
3
+ A reference resolves to an observation column, a variable column, a layer or a scalar, or to
4
+ nothing when the result does not carry it. Catalogue references ask apb-catalog by meaning, so
5
+ no vendor column name appears in a rule.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from collections.abc import Mapping, Sequence
12
+ from dataclasses import dataclass, replace
13
+
14
+ import numpy as np
15
+ import polars as pl
16
+ from apb2.api import FinalLayerTable, ParsedLevel, ParsedLevels
17
+ from apb_catalog.api import DataCatalog, UnresolvedField
18
+ from loguru import logger
19
+
20
+ from apb_export.export_rules.schema import (
21
+ AxisSource,
22
+ CatalogueLayer,
23
+ CatalogueObs,
24
+ CatalogueSource,
25
+ CatalogueVar,
26
+ MeasurementSource,
27
+ ObsSource,
28
+ Reference,
29
+ RuleSource,
30
+ Scalar,
31
+ )
32
+
33
+ type Provenance = dict[str, str]
34
+
35
+ _FASTA_PEPTIDES = "fasta_peptides_alpha"
36
+ """apb-fasta's peptide verification, whose ``fasta_matches_contaminant`` joins the contaminants."""
37
+
38
+ _MEMBERS = ";"
39
+ """How APB2 joins a protein group's members, as the vendors write them."""
40
+
41
+
42
+ @dataclass(frozen=True, slots=True)
43
+ class ObsValues:
44
+ """One value per observation, in the level's observation order."""
45
+
46
+ values: pl.Series
47
+ provenance: Provenance
48
+
49
+
50
+ @dataclass(frozen=True, slots=True)
51
+ class VarValues:
52
+ """One value per variable, in the level's variable order."""
53
+
54
+ values: pl.Series
55
+ provenance: Provenance
56
+
57
+
58
+ @dataclass(frozen=True, slots=True)
59
+ class LayerValues:
60
+ """One row per variable and one column per observation, by position."""
61
+
62
+ values: pl.DataFrame
63
+ provenance: Provenance
64
+
65
+
66
+ @dataclass(frozen=True, slots=True)
67
+ class ScalarValue:
68
+ """One value for the whole level."""
69
+
70
+ value: Scalar
71
+ provenance: Provenance
72
+
73
+
74
+ type Resolved = ObsValues | VarValues | LayerValues | ScalarValue
75
+
76
+
77
+ def _has_values(layer: FinalLayerTable) -> bool:
78
+ """Say whether a layer holds any finite, nonzero value."""
79
+ values = layer.quantitative_values()
80
+ total = values.select(pl.sum_horizontal(pl.all().fill_nan(0).fill_null(0)).sum()).item()
81
+ return bool(total)
82
+
83
+
84
+ def _catalogued_layer(
85
+ catalog: DataCatalog, level: ParsedLevel, name: str, key: str, qualifiers: Mapping[str, str]
86
+ ) -> FinalLayerTable | None:
87
+ """The apb2 layer a key names on level ``name``, read by its catalogued name so a categorical
88
+ layer keeps its labels; ``None`` when the level has no such layer."""
89
+ layers = catalog.levels[name].layers
90
+ try:
91
+ found = layers.name(key, **qualifiers)
92
+ except KeyError:
93
+ return None
94
+ return level.layers[found]
95
+
96
+
97
+ def _column_has_values(column: pl.Series) -> bool:
98
+ """Say whether a var column holds any finite, nonzero value."""
99
+ return bool(column.cast(pl.Float64).fill_nan(0).fill_null(0).sum())
100
+
101
+
102
+ def rule_field(level: ParsedLevel, name: str) -> object:
103
+ """A top-level field of the apb2 rule stored with a level; ``None`` when it has none."""
104
+ provenance = level.uns.get("provenance")
105
+ stored = provenance.get("rule_json") if isinstance(provenance, dict) else None
106
+ rule = json.loads(stored) if isinstance(stored, str) else {}
107
+ return rule.get(name) if isinstance(rule, dict) else None
108
+
109
+
110
+ def _scalar(value: object) -> Scalar:
111
+ if value is None or isinstance(value, str | int | float | bool):
112
+ return value
113
+ return json.dumps(value)
114
+
115
+
116
+ class LevelSources:
117
+ """Resolve references against one level of one result; catalogues are opened once."""
118
+
119
+ def __init__(self, parsed: ParsedLevels, level: str, abundance: str | None) -> None:
120
+ """Bind the result, the level read, and the caller's abundance layer, if any."""
121
+ self._parsed = parsed
122
+ self._name = level
123
+ self._level = parsed.levels[level]
124
+ self._abundance = abundance
125
+ self._catalogues: dict[str, DataCatalog] = {}
126
+ self._answering = frozenset(DataCatalog.answering_sets(parsed))
127
+ self._unanswered: dict[str, list[str]] = {}
128
+
129
+ def annotations(self) -> list[str]:
130
+ """The level's observation columns other than its keys, such as ``apb2 annotate`` adds."""
131
+ keys = self._level.obs.key_columns
132
+ return [name for name in self._level.obs.frame.columns if name not in keys]
133
+
134
+ def annotation(self, name: str) -> pl.Series:
135
+ """One observation annotation column."""
136
+ return self._level.obs.frame.get_column(name)
137
+
138
+ @property
139
+ def abundance_chosen(self) -> bool:
140
+ """Whether the caller named the abundance layer, which then becomes the target's X."""
141
+ return self._abundance is not None
142
+
143
+ def abundance_key(self, layer: str) -> tuple[str, dict[str, str]] | None:
144
+ """What the level's layer measures, as the ``abundance_alpha`` catalogue's key and the
145
+ entry's qualifiers, such as ``aggregation="maxlfq"``; ``None`` for a layer the catalogue
146
+ does not describe."""
147
+ fields = self._catalog("abundance_alpha").fields()
148
+ rows = fields.filter(
149
+ (pl.col("level") == self._name)
150
+ & (pl.col("slot") == "layers")
151
+ & (pl.col("name") == layer)
152
+ & pl.col("present")
153
+ )
154
+ if not rows.height:
155
+ return None
156
+ row = rows.row(0, named=True)
157
+ qualifiers = {
158
+ name.removeprefix("qualifier."): str(value)
159
+ for name, value in row.items()
160
+ if name.startswith("qualifier.") and value is not None
161
+ }
162
+ return str(row["key"]), qualifiers
163
+
164
+ def resolve(
165
+ self, entry: str, source: Reference, fallback: Sequence[Reference] = ()
166
+ ) -> Resolved | None:
167
+ """The source, else the first fallback the result carries, or ``None`` when it carries
168
+ none; a fallback that answers is logged as a warning naming ``entry``. A catalogue set
169
+ the result cannot open, because its app or ``apb2 annotate`` has not run, carries none.
170
+
171
+ A catalogue candidate the catalogue reviewed but cannot answer with one field, because
172
+ several match or the entries leave a requested qualifier unknown, passes to the next
173
+ fallback; the answer used records it under ``passed``.
174
+
175
+ Raises:
176
+ ValueError: A reference cannot be answered, such as a composite axis key or an
177
+ abundance layer that is absent or carries no abundance role.
178
+ UnresolvedField: apb-catalog cannot answer the last candidate with one field, or
179
+ finds the rule unreviewed.
180
+ """
181
+ candidates = [source, *fallback]
182
+ passed: list[str] = []
183
+ for reference in candidates:
184
+ if (
185
+ isinstance(reference, CatalogueLayer | CatalogueVar | CatalogueObs)
186
+ and reference.catalog not in self._answering
187
+ ):
188
+ self._unanswered.setdefault(entry, []).append(reference.catalog)
189
+ continue
190
+ try:
191
+ resolved = self._reference(reference)
192
+ except UnresolvedField as error:
193
+ reviewed = bool(error.resolution.candidates)
194
+ if (
195
+ not isinstance(reference, CatalogueLayer | CatalogueVar | CatalogueObs)
196
+ or not reviewed
197
+ or reference is candidates[-1]
198
+ ):
199
+ raise
200
+ passed.append(f"{reference.catalog} {reference.key} {error.resolution.status}")
201
+ continue
202
+ if resolved is not None:
203
+ if reference is not source:
204
+ lacked = source.model_dump_json(exclude_defaults=True)
205
+ read = reference.model_dump_json(exclude_defaults=True)
206
+ logger.warning(f"level {self._name}: {entry} lacks {lacked}; read {read}")
207
+ if not passed:
208
+ return resolved
209
+ return replace(
210
+ resolved, provenance={**resolved.provenance, "passed": "; ".join(passed)}
211
+ )
212
+ return None
213
+
214
+ def explain_absent(self, entry: str) -> None:
215
+ """Open every catalogue set ``entry`` named that the result cannot open, so apb-catalog
216
+ raises its error saying what to run; nothing when ``entry`` named none.
217
+
218
+ Raises:
219
+ ValueError: A set the entry named can answer nothing on this result.
220
+ """
221
+ for name in self._unanswered.get(entry, []):
222
+ self._catalog(name)
223
+
224
+ def contaminants(self) -> VarValues:
225
+ """apb2's vendor contaminant marking, merged with apb-fasta's FASTA match if present.
226
+
227
+ The marking is the ``apb_alpha`` set's key ``contaminant``, which every apb2 rule writes.
228
+
229
+ Raises:
230
+ ValueError: The level lacks the marking.
231
+ """
232
+ marked = self._catalog("apb_alpha").levels[self._name].var.get("contaminant")
233
+ if marked is None:
234
+ raise ValueError(f"export needs apb2's contaminant marking on level {self._name!r}")
235
+ provenance: Provenance = {"location": "var", "name": marked.name, "catalog": "apb_alpha"}
236
+ if _FASTA_PEPTIDES in self._answering:
237
+ catalog = self._catalog(_FASTA_PEPTIDES)
238
+ matched = catalog.levels[self._name].var.get("fasta_matches_contaminant")
239
+ if matched is not None:
240
+ marked = marked | matched
241
+ provenance["fasta"] = f"{_FASTA_PEPTIDES} {matched.name}"
242
+ return VarValues(marked, provenance)
243
+
244
+ def _reference(self, reference: Reference) -> Resolved | None:
245
+ match reference:
246
+ case AxisSource():
247
+ return self._axis(reference)
248
+ case MeasurementSource():
249
+ return self._measurement()
250
+ case RuleSource():
251
+ return self._rule_field(reference)
252
+ case CatalogueLayer() | CatalogueVar() | CatalogueObs():
253
+ return self._catalogue(reference)
254
+ case ObsSource():
255
+ return self._obs(reference)
256
+
257
+ def _obs(self, reference: ObsSource) -> ObsValues | None:
258
+ if reference.obs not in self.annotations():
259
+ return None
260
+ values = self.annotation(reference.obs)
261
+ return ObsValues(values, {"location": "obs", "name": reference.obs})
262
+
263
+ def _axis(self, reference: AxisSource) -> ObsValues | VarValues:
264
+ if reference.axis == "obs_key":
265
+ keys = self._level.obs.key_columns
266
+ if len(keys) != 1:
267
+ raise ValueError(
268
+ f"export needs one observation per run; this result keys samples by "
269
+ f"{keys}, as multiplexed designs do"
270
+ )
271
+ values = self._level.obs.frame.get_column(keys[0]).cast(pl.Utf8)
272
+ return ObsValues(values, {"location": "obs", "name": keys[0]})
273
+ keys = self._level.var.key_columns
274
+ if len(keys) != 1:
275
+ raise ValueError(f"export needs one variable key; this level keys by {keys}")
276
+ values = self._level.var.frame.get_column(keys[0])
277
+ return VarValues(values, {"location": "var", "name": keys[0]})
278
+
279
+ def _measurement(self) -> LayerValues:
280
+ name = self._abundance or self._level.primary_layer_name
281
+ self._level.abundance_layers((name,))
282
+ values = self._level.layers[name].decoded_values()
283
+ return LayerValues(values, {"location": "layers", "name": name})
284
+
285
+ def _rule_field(self, reference: RuleSource) -> ScalarValue | None:
286
+ value = rule_field(self._level, reference.rule)
287
+ if value is None:
288
+ return None
289
+ return ScalarValue(_scalar(value), {"location": "rule", "name": reference.rule})
290
+
291
+ def _catalog(self, name: str) -> DataCatalog:
292
+ catalog = self._catalogues.get(name)
293
+ if catalog is None:
294
+ catalog = DataCatalog(self._parsed, name)
295
+ self._catalogues[name] = catalog
296
+ return catalog
297
+
298
+ def _catalogue(self, reference: CatalogueSource) -> Resolved | None:
299
+ if not isinstance(reference, CatalogueObs) and reference.from_level is not None:
300
+ return self._through_protein_group(reference, reference.from_level)
301
+ catalog = self._catalog(reference.catalog)
302
+ qualifiers = reference.qualifiers
303
+ found: Provenance = {"catalog": reference.catalog, "key": reference.key, **qualifiers}
304
+ level = catalog.levels[self._name]
305
+ if isinstance(reference, CatalogueObs):
306
+ values = level.obs.get(reference.key, **qualifiers)
307
+ if values is None:
308
+ return None
309
+ return ObsValues(values, {"location": "obs", "name": values.name, **found})
310
+ if isinstance(reference, CatalogueVar):
311
+ column = level.var.get(reference.key, **qualifiers)
312
+ if column is None or (reference.accept == "nonzero" and not _column_has_values(column)):
313
+ return None
314
+ return VarValues(column, {"location": "var", "name": column.name, **found})
315
+ layer = _catalogued_layer(catalog, self._level, self._name, reference.key, qualifiers)
316
+ if layer is None or (reference.accept == "nonzero" and not _has_values(layer)):
317
+ return None
318
+ provenance = {"location": "layers", "name": layer.layer_name, **found}
319
+ return LayerValues(layer.decoded_values(), provenance)
320
+
321
+ def _through_protein_group(
322
+ self, reference: CatalogueLayer | CatalogueVar, level: str
323
+ ) -> LayerValues | None:
324
+ """A catalogued field of ``level``, seen from this level's cells through protein groups.
325
+
326
+ Each variable takes the group its ``protein_assignment`` names; each observation the
327
+ column of the same run. A var column has one value per group, the same in every run,
328
+ so its runs need no counterpart in ``level``.
329
+ """
330
+ assignment = self._level.var.roles.get("protein_assignment")
331
+ if level not in self._parsed.levels or assignment is None:
332
+ return None
333
+ coarse = self._parsed.levels[level]
334
+ catalog = self._catalog(reference.catalog)
335
+ if isinstance(reference, CatalogueVar):
336
+ column = catalog.levels[level].var.get(reference.key)
337
+ if column is None or (reference.accept == "nonzero" and not _column_has_values(column)):
338
+ return None
339
+ table = column.cast(pl.Float64).to_numpy()[:, np.newaxis]
340
+ runs = np.zeros(self._level.obs.frame.height, dtype=np.int64)
341
+ name = column.name
342
+ else:
343
+ layer = _catalogued_layer(catalog, coarse, level, reference.key, {})
344
+ if layer is None or (reference.accept == "nonzero" and not _has_values(layer)):
345
+ return None
346
+ table = layer.decoded_values().select(pl.all().cast(pl.Float64)).to_numpy()
347
+ runs = _positions(
348
+ self._level.obs.frame.get_column(
349
+ _key(self._level.obs.key_columns, self._name, "run")
350
+ ),
351
+ coarse.obs.frame.get_column(_key(coarse.obs.key_columns, level, "run")),
352
+ )
353
+ name = layer.layer_name
354
+ rows = _groups(
355
+ self._level.var.frame.get_column(assignment),
356
+ coarse.var.frame.get_column(_key(coarse.var.key_columns, level, "variable")),
357
+ )
358
+ gathered = np.full((rows.size, runs.size), np.nan)
359
+ known_rows, known_runs = rows >= 0, runs >= 0
360
+ gathered[np.ix_(known_rows, known_runs)] = table[np.ix_(rows[known_rows], runs[known_runs])]
361
+ values = pl.DataFrame(gathered, schema=[f"obs_{i}" for i in range(runs.size)], orient="row")
362
+ provenance: Provenance = {
363
+ "location": reference.location,
364
+ "name": name,
365
+ "level": level,
366
+ "through": assignment,
367
+ "catalog": reference.catalog,
368
+ "key": reference.key,
369
+ }
370
+ return LayerValues(values, provenance)
371
+
372
+
373
+ def _key(columns: tuple[str, ...] | list[str], level: str, axis: str) -> str:
374
+ """A level's one key column on an axis; a composite key cannot be matched across levels."""
375
+ if len(columns) != 1:
376
+ raise ValueError(f"the {level} level keys each {axis} by {list(columns)}, not one column")
377
+ return columns[0]
378
+
379
+
380
+ def _positions(
381
+ wanted: pl.Series, available: pl.Series
382
+ ) -> np.ndarray[tuple[int], np.dtype[np.int64]]:
383
+ """Each wanted value's position in ``available``; -1 where it is absent."""
384
+ index = {value: position for position, value in enumerate(available.cast(pl.Utf8).to_list())}
385
+ return np.array(
386
+ [index.get(value, -1) for value in wanted.cast(pl.Utf8).to_list()], dtype=np.int64
387
+ )
388
+
389
+
390
+ def _groups(
391
+ assignments: pl.Series, groups: pl.Series
392
+ ) -> np.ndarray[tuple[int], np.dtype[np.int64]]:
393
+ """Each assignment's protein group: the one it names whole, else the one it leads; or -1.
394
+
395
+ A group leads with its first member, as MaxQuant lists the razor protein first. A member
396
+ leading several groups names none of them.
397
+ """
398
+ keys: list[str | None] = groups.cast(pl.Utf8).to_list()
399
+ whole = {key: position for position, key in enumerate(keys) if key is not None}
400
+ leads: dict[str, int] = {}
401
+ shared: set[str] = set()
402
+ for position, key in enumerate(keys):
403
+ if key is None:
404
+ continue
405
+ lead = key.split(_MEMBERS, 1)[0]
406
+ if lead in leads:
407
+ shared.add(lead)
408
+ leads[lead] = position
409
+ for lead in shared:
410
+ del leads[lead]
411
+ wanted: list[str | None] = assignments.cast(pl.Utf8).to_list()
412
+ return np.array(
413
+ [-1 if value is None else whole.get(value, leads.get(value, -1)) for value in wanted],
414
+ dtype=np.int64,
415
+ )
@@ -0,0 +1,159 @@
1
+ Metadata-Version: 2.4
2
+ Name: apb-export
3
+ Version: 0.2.2
4
+ Summary: APB2 results exported for nine downstream targets: msmu, MSstats, Perseus, prolfqua, ProteoPy, exploreDE, AlphaPeptTools, QFeatures and QPX
5
+ Author: Witold Wolski
6
+ Author-email: Witold Wolski <wew@fgcz.ethz.ch>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ License-File: src/apb_export/qpx/LICENSE.qpx
10
+ Requires-Dist: apb2>=0.1.3,<0.2
11
+ Requires-Dist: apb-catalog>=0.1.5,<0.2
12
+ Requires-Dist: apb-fasta>=0.1.2,<0.2
13
+ Requires-Dist: cyclopts>=4,<5
14
+ Requires-Dist: loguru>=0.7,<1
15
+ Requires-Dist: numpy>=2,<3
16
+ Requires-Dist: polars>=1.43,<2
17
+ Requires-Dist: pyarrow>=21,<24
18
+ Requires-Dist: pydantic>=2.10,<3
19
+ Requires-Python: >=3.13
20
+ Description-Content-Type: text/markdown
21
+
22
+ # APB Export
23
+
24
+ **[Online documentation](https://anndata-omics-bridge.github.io/apb-export/)** or its [source index](docs/index.md).
25
+
26
+ Try it online:
27
+
28
+ - [Rules viewer](https://fgcz-ms.uzh.ch/public/apb-rules/): every vendor table's parse rules, as apb2 packages them
29
+ - [Catalog viewer](https://fgcz-ms.uzh.ch/public/apb-catalog/): every catalog set with its entries and coverage
30
+ - [APB Studio](https://fgcz-ms.uzh.ch/public/apb-studio/): APB's corpus runs over the test vendor files
31
+ - [APB Export](https://apps-dev.bfabric.org/apb-export/): convert a vendor table for a downstream tool in the browser
32
+
33
+ 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.
34
+
35
+ ```bash
36
+ apb-export msmu report.tsv result.h5mu --params report.log.txt
37
+ apb-export msmu report.tsv result.h5mu --params report.log.txt --fasta proteins.fasta
38
+ apb-export prolfqua report.tsv result.h5ad --params report.log.txt --annotation dataset.csv
39
+ apb-export msstats report.tsv msstats.csv --params report.log.txt --annotation design.tsv
40
+ apb-export perseus report.tsv perseus.txt --params report.log.txt --annotation samples.tsv
41
+ apb-export proteopy report.tsv proteins.h5ad --params report.log.txt
42
+ apb-export alphapepttools report.tsv linked.h5mu --params report.log.txt
43
+ apb-export qfeatures report.tsv qfeatures.h5mu --params report.log.txt
44
+ apb-export qpx report.tsv result.qpx --params report.log.txt
45
+ ```
46
+
47
+ 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.
48
+
49
+ ```python
50
+ import msmu as mm
51
+
52
+ mdata = mm.read_h5mu("result.h5mu")
53
+ mdata = mm.pp.add_filter(mdata, modality="psm", column="q_value", keep="lt", value=0.01)
54
+ mdata = mm.pp.apply_filter(mdata, modality="psm", on="var")
55
+ mdata = mm.pp.to_peptide(mdata, calculate_q=False)
56
+ ```
57
+
58
+ From Python, APB2 converts and `Exporter` exports, the shape of the other APB tools:
59
+
60
+ ```python
61
+ from pathlib import Path
62
+
63
+ from apb2.api import ParseRuleCompiler
64
+ from apb_export.api import Exporter
65
+
66
+ exporter = Exporter("msmu")
67
+ parsed = ParseRuleCompiler.detect(
68
+ Path("report.tsv"), Path("report.log.txt"), requested_levels=exporter.levels
69
+ ).compile().parse()
70
+ exporter.write(exporter.export(parsed), Path("result.h5mu"))
71
+ ```
72
+
73
+ `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.
74
+
75
+ 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.
76
+
77
+ ## Install
78
+
79
+ ```bash
80
+ uv tool install --python 3.13 apb-export
81
+ ```
82
+
83
+ 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.
84
+
85
+ ## What it writes
86
+
87
+ 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.
88
+
89
+ - 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
90
+ - `X`: dense float32, the chosen abundance layer (`--abundance`, APB2's primary layer by default); a precursor absent from a run is NaN
91
+ - `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
92
+ - `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
93
+ - `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
94
+
95
+ `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]"`.
96
+
97
+ ## Export rules
98
+
99
+ 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).
100
+
101
+ | Target | File | APB2 levels | Layout |
102
+ | --- | --- | --- | --- |
103
+ | [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 |
104
+ | [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 |
105
+ | [Perseus](src/apb_export/export_rules/documents/perseus/v2/rules.json) | `.txt` | protein | wide, proteinGroups.txt's names, `#!{Type}` and `#!{C:…}` header rows |
106
+ | [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` |
107
+ | [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 |
108
+ | [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 |
109
+ | [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` |
110
+ | [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 |
111
+ | [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 |
112
+ | [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 |
113
+
114
+ ## Confidence, by meaning
115
+
116
+ - `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
117
+ - `PEP`: the vendor's posterior error probability
118
+ - Lookup: apb-catalog's `confidence` and `proteobench_entrapment` catalogues, never vendor column names
119
+ - 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
120
+ - Unreviewed rule: apb-catalog answers "unknown" and the command stops; unknown is not missing
121
+
122
+ ## Protein groups
123
+
124
+ 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.
125
+
126
+ ## Web application
127
+
128
+ 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.
129
+
130
+ ## Limits
131
+
132
+ - 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
133
+ - Label-free only: a result keyed by more than one observation column, as multiplexed designs are, is refused
134
+ - `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
135
+ - Group separators other than `;` pass through unchanged; no APB2 rule declares its separator
136
+ - QPX maps retention time through the chromatography catalogue; an unknown original unit is refused instead of assumed
137
+ - msmu's file has no per-run `filename` column: msmu tools that group features by file see precursors, not identifications
138
+
139
+ ## Development
140
+
141
+ 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:
142
+
143
+ ```text
144
+ anndata_bridge/
145
+ ├── apb2/
146
+ ├── apb-catalog/
147
+ ├── apb-fasta/
148
+ ├── protein_fasta/
149
+ ├── prozor/
150
+ └── apb-export/
151
+ ```
152
+
153
+ ```bash
154
+ uv sync --group dev
155
+ make check
156
+ make check-full
157
+ ```
158
+
159
+ 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.