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/engine.py ADDED
@@ -0,0 +1,717 @@
1
+ """Compile an export rule once, then export APB results with it.
2
+
3
+ Every entry's sources are resolved and checked against what its group can take before any
4
+ row is built, so a result the rule cannot export fails without a partial container. Each
5
+ level the rule writes becomes one level of a ``ParsedLevels`` for APB2's writer, and a rule's
6
+ feature links become one of its directed feature relations.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import copy
12
+ import re
13
+ from collections.abc import Mapping, Sequence
14
+ from dataclasses import dataclass, replace
15
+ from importlib.metadata import version
16
+ from pathlib import Path
17
+ from typing import cast
18
+
19
+ import polars as pl
20
+ from apb2.api import JsonValue, ParsedLevel, ParsedLevels
21
+ from loguru import logger
22
+
23
+ from apb_export.computed import compute, dtype
24
+ from apb_export.export_rules.loader import EffectiveRule
25
+ from apb_export.export_rules.schema import (
26
+ AccessionSyntax,
27
+ AllValues,
28
+ AnnotationMap,
29
+ CatalogueLayer,
30
+ CatalogueVar,
31
+ ColumnEntry,
32
+ Constant,
33
+ Contaminant,
34
+ EntryBase,
35
+ FeatureLink,
36
+ LayerEntry,
37
+ LayerMinimum,
38
+ MeasurementSource,
39
+ Rename,
40
+ ShortName,
41
+ SourcedBase,
42
+ SourcedEntry,
43
+ )
44
+ from apb_export.outputs import output_for
45
+ from apb_export.rows import FeatureRows, ObservationRows, Rows, ScalarRow
46
+ from apb_export.sources import (
47
+ LayerValues,
48
+ LevelSources,
49
+ ObsValues,
50
+ Provenance,
51
+ Resolved,
52
+ ScalarValue,
53
+ VarValues,
54
+ rule_field,
55
+ )
56
+
57
+ EXPORT_SCHEMA_VERSION = "1"
58
+ _CALLERS_LAYER = MeasurementSource(measurements="primary_layer")
59
+ """The primary layer's source when the caller names the abundance layer."""
60
+ _OBS_TAKES = (ObsValues, ScalarValue)
61
+ _UNS_TAKES = (ScalarValue,)
62
+ _VAR_TAKES = (VarValues, ScalarValue)
63
+ _LINKS = pl.Schema(
64
+ {
65
+ "source": pl.String,
66
+ "row": pl.Int64,
67
+ "target": pl.String,
68
+ "column": pl.Int64,
69
+ "value": pl.Float64,
70
+ }
71
+ )
72
+
73
+ type Entries = Sequence[ColumnEntry] | Sequence[ColumnEntry | AllValues]
74
+
75
+
76
+ @dataclass(frozen=True, slots=True)
77
+ class _Bound:
78
+ """An entry with its sources resolved; ``filled`` writes ``fill_value`` instead."""
79
+
80
+ entry: ColumnEntry
81
+ inputs: tuple[Resolved, ...]
82
+ provenance: Provenance
83
+ filled: bool = False
84
+
85
+
86
+ def _describe(provenance: Provenance) -> str:
87
+ return " ".join(provenance[key] for key in ("location", "name") if key in provenance)
88
+
89
+
90
+ def _absent(entry: ColumnEntry, group: str, sources: LevelSources) -> _Bound | None:
91
+ if entry.required:
92
+ sources.explain_absent(f"{group}.{entry.name}")
93
+ raise ValueError(f"{group} entry {entry.name!r}: the result carries no source for it")
94
+ if entry.fill_value is None:
95
+ return None
96
+ return _Bound(entry, (), {"location": "absent", "filled": str(entry.fill_value)}, True)
97
+
98
+
99
+ def _check_takes(
100
+ entry: ColumnEntry, resolved: Sequence[Resolved], group: str, takes: tuple[type[object], ...]
101
+ ) -> None:
102
+ for item in resolved:
103
+ if not isinstance(item, takes):
104
+ raise ValueError(
105
+ f"{group} entry {entry.name!r} cannot take {_describe(item.provenance)}"
106
+ )
107
+
108
+
109
+ def _bind(
110
+ entry: ColumnEntry,
111
+ sources: LevelSources,
112
+ group: str,
113
+ takes: tuple[type[object], ...],
114
+ layers: Mapping[str, LayerValues | None],
115
+ ) -> _Bound | None:
116
+ """Resolve an entry's sources; ``None`` skips an optional entry with nothing to fill.
117
+
118
+ ``layers`` are the level's resolved measurement layers, by name, which ``layer_minimum``
119
+ reduces."""
120
+ label = f"{group}.{entry.name}"
121
+ if isinstance(entry, Constant | AnnotationMap):
122
+ return _Bound(entry, (), {"how": entry.how})
123
+ if isinstance(entry, Contaminant):
124
+ merged = sources.contaminants()
125
+ return _Bound(entry, (merged,), {"how": entry.how, "inputs": _describe(merged.provenance)})
126
+ if isinstance(entry, LayerMinimum):
127
+ found_layer = layers.get(entry.layer)
128
+ if found_layer is None:
129
+ return _absent(entry, group, sources)
130
+ reduced = _minimum(found_layer)
131
+ if not isinstance(reduced, takes):
132
+ raise ValueError(
133
+ f"{group} entry {entry.name!r} cannot take {_describe(reduced.provenance)}"
134
+ )
135
+ return _Bound(entry, (reduced,), {**reduced.provenance, "how": entry.how})
136
+ if isinstance(entry, ShortName):
137
+ return _bind_short_name(entry, sources, group, takes)
138
+ found = (
139
+ [sources.resolve(label, entry.source, entry.fallback)]
140
+ if isinstance(entry, SourcedBase)
141
+ else [sources.resolve(label, reference) for reference in entry.inputs]
142
+ )
143
+ resolved = [item for item in found if item is not None]
144
+ if len(resolved) < len(found):
145
+ return _absent(entry, group, sources)
146
+ _check_takes(entry, resolved, group, takes)
147
+ if isinstance(entry, SourcedEntry):
148
+ return _Bound(entry, tuple(resolved), resolved[0].provenance)
149
+ inputs = ", ".join(_describe(item.provenance) for item in resolved)
150
+ return _Bound(entry, tuple(resolved), {"how": entry.how, "inputs": inputs})
151
+
152
+
153
+ def _bind_short_name(
154
+ entry: ShortName, sources: LevelSources, group: str, takes: tuple[type[object], ...]
155
+ ) -> _Bound | None:
156
+ """The inputs the result carries, then ``append``; absent inputs are passed over."""
157
+ label = f"{group}.{entry.name}"
158
+ found = [item for ref in entry.inputs if (item := sources.resolve(label, ref)) is not None]
159
+ appended = None if entry.append is None else sources.resolve(label, entry.append)
160
+ if not found or (entry.append is not None and appended is None):
161
+ return _absent(entry, group, sources)
162
+ resolved = [*found, *([] if appended is None else [appended])]
163
+ _check_takes(entry, resolved, group, takes)
164
+ inputs = ", ".join(_describe(item.provenance) for item in resolved)
165
+ return _Bound(entry, tuple(resolved), {"how": entry.how, "inputs": inputs})
166
+
167
+
168
+ def _minimum(resolved: Resolved) -> Resolved:
169
+ """A layer reduced to its smallest value per variable; anything else as it is."""
170
+ if not isinstance(resolved, LayerValues):
171
+ return resolved
172
+ values = resolved.values.select(pl.min_horizontal(pl.all().cast(pl.Float64))).to_series()
173
+ return VarValues(values, resolved.provenance)
174
+
175
+
176
+ def _fill(entry: EntryBase) -> object:
177
+ if entry.type == "number" and isinstance(entry.fill_value, str):
178
+ return float(entry.fill_value)
179
+ return entry.fill_value
180
+
181
+
182
+ def _series(bound: _Bound, rows: Rows, syntax: Mapping[str, AccessionSyntax]) -> pl.Series:
183
+ entry = bound.entry
184
+ if bound.filled:
185
+ values = pl.Series([_fill(entry)] * rows.count())
186
+ elif isinstance(entry, Constant):
187
+ values = pl.Series([entry.value] * rows.count())
188
+ elif isinstance(entry, SourcedEntry):
189
+ values = rows.align(bound.inputs[0])
190
+ elif isinstance(entry, AnnotationMap):
191
+ raise ValueError(f"entry {entry.name!r}: annotation_map writes only uns")
192
+ else:
193
+ values = compute(entry, [rows.align(item) for item in bound.inputs], syntax)
194
+ return values.cast(dtype(entry.type, entry.width)).alias(entry.name)
195
+
196
+
197
+ def _nest(values: Sequence[tuple[str, object]]) -> dict[str, object]:
198
+ """Dotted entry names become nested mappings: ``a.b`` is ``{"a": {"b": ...}}``."""
199
+ root: dict[str, object] = {}
200
+ for name, value in values:
201
+ *parents, leaf = name.split(".")
202
+ node = root
203
+ for part in parents:
204
+ child = node.setdefault(part, {})
205
+ if not isinstance(child, dict):
206
+ raise ValueError(f"uns entry {name!r} nests under a value")
207
+ node = child
208
+ node[leaf] = value
209
+ return root
210
+
211
+
212
+ def _repeated(values: VarValues, runs: int) -> LayerValues:
213
+ """A catalogued value per variable as a layer: the same value in every run."""
214
+ column = values.values.cast(pl.Float64)
215
+ frame = pl.DataFrame([column.alias(f"obs_{run}") for run in range(runs)])
216
+ return LayerValues(frame, values.provenance)
217
+
218
+
219
+ def _software(parsed: ParsedLevels) -> set[str]:
220
+ """The software apb2's rules name for the result's levels."""
221
+ names = (rule_field(level, "software_name") for level in parsed.levels.values())
222
+ return {name for name in names if isinstance(name, str)}
223
+
224
+
225
+ def _layer_frame(values: pl.DataFrame, entry: LayerEntry) -> pl.DataFrame:
226
+ """A layer as APB2 keeps it, features by observations, declared missing values blanked,
227
+ then transformed."""
228
+ numbers = values.select(pl.all().cast(pl.Float64))
229
+ if entry.missing_values:
230
+ absent = pl.all().is_in(entry.missing_values)
231
+ numbers = numbers.select(pl.when(absent).then(None).otherwise(pl.all()).name.keep())
232
+ if entry.transform == "log2":
233
+ numbers = numbers.select(pl.when(pl.all() > 0).then(pl.all().log(2)).name.keep())
234
+ return numbers.cast(pl.Float32 if entry.width == 32 else pl.Float64)
235
+
236
+
237
+ def _renamed(values: pl.Series, renames: Sequence[Rename]) -> pl.Series:
238
+ """An annotation column under its own name, or named by the first matching rename as text
239
+ whose categories are sorted, whatever order the runs come in."""
240
+ for rename in renames:
241
+ if re.search(rename.pattern, values.name):
242
+ name = re.sub(rename.pattern, rename.replacement, values.name)
243
+ if rename.identifier:
244
+ name = re.sub(r"[^a-z0-9_]", "_", name.lower())
245
+ text = values.cast(pl.Utf8)
246
+ return text.cast(pl.Enum(sorted(text.drop_nulls().unique()))).alias(name)
247
+ return values
248
+
249
+
250
+ class _LevelExport:
251
+ """One level of one result, exported by one effective rule."""
252
+
253
+ def __init__(self, rule: EffectiveRule, parsed: ParsedLevels, abundance: str | None) -> None:
254
+ self._rule = rule
255
+ self._level = parsed.levels[rule.level]
256
+ self._sources = LevelSources(parsed, rule.level, abundance)
257
+ self._provenance: dict[str, Provenance] = {}
258
+ self._written_names: dict[str, str] = {}
259
+
260
+ def has_index(self) -> bool:
261
+ """Whether the result carries the source of the level's variable index."""
262
+ key = self._rule.rule.axis.var_key
263
+ (entry,) = [entry for entry in self._rule.rule.columns.var if entry.name == key]
264
+ return (
265
+ not isinstance(entry, SourcedEntry)
266
+ or self._sources.resolve(f"var.{key}", entry.source, entry.fallback) is not None
267
+ )
268
+
269
+ def parsed_level(self) -> ParsedLevel:
270
+ """APB2's samples-by-features level for APB2's writer; key columns stay columns."""
271
+ rule = self._rule.rule
272
+ primary = rule.measurements.primary_layer
273
+ found = [
274
+ (entry, self._layer(entry, primary=entry.name == primary))
275
+ for entry in rule.measurements.layers
276
+ ]
277
+ resolved = {entry.name: values for entry, values in found}
278
+ bound = self._bind_columns(resolved)
279
+ uns = self._bind_group("uns", rule.uns, _UNS_TAKES, resolved)
280
+ obs = self._columns(bound["obs"], ObservationRows(self._level.obs.frame.height))
281
+ rows = FeatureRows(self._level.var.frame.height)
282
+ var = self._columns(bound["var"], rows)
283
+ kept = self._kept(var, rule.columns.var, rows.count())
284
+ var = [column.filter(kept) for column in var]
285
+ obs_key, var_key = rule.axis.obs_key, rule.axis.var_key
286
+ self._key(obs, obs_key, "obs")
287
+ self._key(var, var_key, "var")
288
+ layers = {
289
+ self._written(entry, values): _layer_frame(values.values.filter(kept), entry)
290
+ for entry, values in found
291
+ if values is not None
292
+ }
293
+ primary = self._written_names[primary]
294
+ return ParsedLevel.build(
295
+ obs=pl.DataFrame(obs),
296
+ obs_keys=[obs_key],
297
+ var=pl.DataFrame(var),
298
+ var_keys=[var_key],
299
+ var_roles={},
300
+ primary_layer=primary,
301
+ abundance={primary: layers.pop(primary)},
302
+ auxiliary=layers,
303
+ uns=dict(self._level.uns),
304
+ metadata={**self._level.metadata, "export": self._export_part(len(layers) + 1)},
305
+ export_uns=cast(dict[str, JsonValue], self._uns(uns)),
306
+ )
307
+
308
+ def _layer(self, entry: LayerEntry, *, primary: bool) -> LayerValues | None:
309
+ """Resolve a layer; ``None`` for an absent optional one. A caller's abundance layer
310
+ replaces the rule's source of the primary layer."""
311
+ chosen = primary and self._sources.abundance_chosen
312
+ key = f"layers.{entry.name}"
313
+ resolved = (
314
+ self._sources.resolve(key, _CALLERS_LAYER)
315
+ if chosen
316
+ else self._sources.resolve(key, entry.source, entry.fallback)
317
+ )
318
+ if resolved is None:
319
+ if primary or entry.required:
320
+ self._sources.explain_absent(key)
321
+ raise ValueError(f"layer {entry.name!r}: the result carries no layer for it")
322
+ self._provenance[key] = {"location": "absent"}
323
+ return None
324
+ if isinstance(resolved, VarValues) and "catalog" in resolved.provenance:
325
+ resolved = _repeated(resolved, self._level.obs.frame.height)
326
+ if not isinstance(resolved, LayerValues):
327
+ raise ValueError(f"layer {entry.name!r} cannot take {_describe(resolved.provenance)}")
328
+ self._provenance[key] = resolved.provenance
329
+ return resolved
330
+
331
+ def _written(self, entry: LayerEntry, values: LayerValues) -> str:
332
+ """The layer's name in the export: the entry's, or the one ``name_by_key`` gives the
333
+ first of its labels the resolved layer matches, by abundance key or by a
334
+ ``qualifier=value`` pair; the provenance follows it."""
335
+ written = entry.name
336
+ found = (
337
+ self._sources.abundance_key(values.provenance["name"]) if entry.name_by_key else None
338
+ )
339
+ if found is not None:
340
+ key, qualifiers = found
341
+ matches = {key: {}} | {
342
+ f"{name}={value}": {name: value} for name, value in qualifiers.items()
343
+ }
344
+ label = next((label for label in entry.name_by_key if label in matches), None)
345
+ if label is not None:
346
+ written = entry.name_by_key[label]
347
+ source = self._provenance.pop(f"layers.{entry.name}")
348
+ self._provenance[f"layers.{written}"] = {**source, "key": key, **matches[label]}
349
+ self._written_names[entry.name] = written
350
+ return written
351
+
352
+ def _bind_columns(
353
+ self, layers: Mapping[str, LayerValues | None]
354
+ ) -> dict[str, list[_Bound | AllValues]]:
355
+ rule = self._rule.rule
356
+ return {
357
+ "obs": self._bind_group("obs", rule.columns.obs, _OBS_TAKES, layers),
358
+ "var": self._bind_group("var", rule.columns.var, _VAR_TAKES, layers),
359
+ }
360
+
361
+ def _bind_group(
362
+ self,
363
+ group: str,
364
+ entries: Entries,
365
+ takes: tuple[type[object], ...],
366
+ layers: Mapping[str, LayerValues | None],
367
+ ) -> list[_Bound | AllValues]:
368
+ bound: list[_Bound | AllValues] = []
369
+ for entry in entries:
370
+ key = f"{group}.{entry.name}"
371
+ if isinstance(entry, AllValues):
372
+ self._provenance[key] = {"how": entry.how}
373
+ bound.append(entry)
374
+ continue
375
+ item = _bind(entry, self._sources, group, takes, layers)
376
+ self._provenance[key] = {"location": "absent"} if item is None else item.provenance
377
+ if item is not None:
378
+ bound.append(item)
379
+ return bound
380
+
381
+ def _columns(self, bound: Sequence[_Bound | AllValues], rows: Rows) -> list[pl.Series]:
382
+ """Evaluate bound entries; an obs ``all_values`` entry adds every annotation column."""
383
+ columns: list[pl.Series] = []
384
+ for item in bound:
385
+ if isinstance(item, AllValues):
386
+ names = self._sources.annotations()
387
+ columns.extend(
388
+ _renamed(self._sources.annotation(name), item.rename) for name in names
389
+ )
390
+ else:
391
+ columns.append(_series(item, rows, self._rule.rule.accession_syntax))
392
+ names = [column.name for column in columns]
393
+ repeated = sorted({name for name in names if names.count(name) > 1})
394
+ if repeated:
395
+ raise ValueError(f"level {self._rule.level!r} writes columns {repeated} twice")
396
+ return columns
397
+
398
+ def _kept(self, columns: list[pl.Series], entries: Entries, count: int) -> pl.Series:
399
+ """Features holding a value in every ``drop_missing`` column; the others are counted.
400
+
401
+ A feature is one of the ``count`` variables written.
402
+ """
403
+ dropping = {e.name for e in entries if not isinstance(e, AllValues) and e.drop_missing}
404
+ kept = pl.Series([True] * count)
405
+ for column in (column for column in columns if column.name in dropping):
406
+ kept &= (column.is_not_null() & (column.cast(pl.String) != "")).fill_null(value=False)
407
+ key = f"var.{column.name}"
408
+ dropped = kept.len() - kept.sum()
409
+ self._provenance[key] = {**self._provenance[key], "dropped": str(dropped)}
410
+ logger.info(
411
+ f"level {self._rule.level}: {dropped} features without {column.name} left out"
412
+ )
413
+ return kept
414
+
415
+ @staticmethod
416
+ def _key(columns: list[pl.Series], key: str, group: str) -> pl.Series:
417
+ (values,) = [column for column in columns if column.name == key]
418
+ if values.is_duplicated().any():
419
+ raise ValueError(f"{group} index {key!r} repeats values")
420
+ return values
421
+
422
+ def _uns(self, bound: Sequence[_Bound | AllValues]) -> dict[str, object]:
423
+ values: list[tuple[str, object]] = []
424
+ for item in bound:
425
+ if isinstance(item, _Bound):
426
+ values.append((item.entry.name, self._uns_value(item)))
427
+ return _nest(values)
428
+
429
+ def _uns_value(self, bound: _Bound) -> object:
430
+ entry = bound.entry
431
+ if isinstance(entry, AnnotationMap):
432
+ return {name: name for name in self._sources.annotations()}
433
+ if isinstance(entry, Constant) and isinstance(entry.value, dict | list):
434
+ # A copy: nested entries are written into it, and the rule is reused.
435
+ return copy.deepcopy(entry.value)
436
+ return _series(bound, ScalarRow(), self._rule.rule.accession_syntax).item()
437
+
438
+ def _export_part(self, matrices: int) -> dict[str, JsonValue]:
439
+ """The export's own record of one level: where each entry came from, and a summary."""
440
+ absent = sum(source.get("location") == "absent" for source in self._provenance.values())
441
+ return {
442
+ "provenance": {
443
+ "source_level": self._rule.level,
444
+ "sources": cast(JsonValue, self._provenance),
445
+ },
446
+ "summary": [
447
+ {
448
+ "name": "exported_matrices",
449
+ "label": "Exported matrices",
450
+ "value": matrices,
451
+ "unit": "matrices",
452
+ "status": "ok",
453
+ },
454
+ {
455
+ "name": "absent_entries",
456
+ "label": "Rule entries the result does not hold",
457
+ "value": absent,
458
+ "unit": "entries",
459
+ "status": "ok",
460
+ },
461
+ ],
462
+ }
463
+
464
+
465
+ def _labels(values: pl.Series) -> pl.Series:
466
+ """Values as the labels links match on; null, NaN and empty text match nothing."""
467
+ if values.dtype.is_float():
468
+ values = values.fill_nan(None)
469
+ return values.cast(pl.String).replace("", None)
470
+
471
+
472
+ class FeatureLinks:
473
+ """One feature link of the written levels, as a directed feature relation.
474
+
475
+ Every written level with a var column ``column`` maps each feature to the target level's
476
+ feature whose key equals that value; a value matching no key is counted as unlinked.
477
+ """
478
+
479
+ def __init__(self, link: FeatureLink, levels: Mapping[str, ParsedLevel]) -> None:
480
+ """Match each level's ``column`` against the target level's keys.
481
+
482
+ ``coordinates`` is ``None`` when the target level is not written.
483
+ """
484
+ self._name = link.name
485
+ self.coordinates: pl.DataFrame | None = None
486
+ self._unlinked = 0
487
+ if link.target not in levels:
488
+ return
489
+ target = levels[link.target].var
490
+ keys = _labels(target.frame.get_column(target.key_columns[0])).to_frame("label")
491
+ keys = keys.with_row_index("column")
492
+ blocks: list[pl.DataFrame] = []
493
+ for name, level in levels.items():
494
+ if name == link.target or link.column not in level.var.frame.columns:
495
+ continue
496
+ values = _labels(level.var.frame.get_column(link.column)).to_frame("label")
497
+ values = values.with_row_index("row").drop_nulls("label")
498
+ matched = values.join(keys, on="label", how="left", maintain_order="left")
499
+ self._unlinked += matched.get_column("column").null_count()
500
+ blocks.append(
501
+ matched.drop_nulls("column").select(
502
+ source=pl.lit(name),
503
+ row="row",
504
+ target=pl.lit(link.target),
505
+ column="column",
506
+ value=pl.lit(1.0),
507
+ )
508
+ )
509
+ self.coordinates = pl.concat(blocks).cast(_LINKS) if blocks else pl.DataFrame(schema=_LINKS)
510
+
511
+ def counts(self) -> JsonValue:
512
+ """The export record's entry: features linked and values matching no target feature."""
513
+ linked = 0 if self.coordinates is None else self.coordinates.height
514
+ return {"name": self._name, "linked": linked, "unlinked": self._unlinked}
515
+
516
+
517
+ class CompiledExport:
518
+ """One target's effective rules, checked once and applied to any number of results."""
519
+
520
+ def __init__(self, rules: Sequence[EffectiveRule]) -> None:
521
+ """Keep one target's effective rules.
522
+
523
+ Raises:
524
+ ValueError: No level.
525
+ """
526
+ if not rules:
527
+ raise ValueError("an export rule needs at least one level")
528
+ self.rules = tuple(rules)
529
+ self.output = rules[0].output
530
+ self._format = output_for(self.extension)
531
+
532
+ def write(self, exported: ParsedLevels, output: Path) -> None:
533
+ """Write the already exported levels through the selected output format."""
534
+ self._format.write(exported, output)
535
+
536
+ @property
537
+ def levels(self) -> tuple[str, ...]:
538
+ """The APB2 levels the rule reads: those it writes, then those its layers reach into."""
539
+ reached = [
540
+ reference.from_level
541
+ for rule in self.rules
542
+ for entry in rule.rule.measurements.layers
543
+ for reference in (entry.source, *entry.fallback)
544
+ if isinstance(reference, CatalogueLayer | CatalogueVar)
545
+ and reference.from_level is not None
546
+ ]
547
+ return tuple(dict.fromkeys([*self.written, *reached]))
548
+
549
+ @property
550
+ def written(self) -> tuple[str, ...]:
551
+ """The APB2 levels the rule writes, in rule order; an ``.h5ad`` export writes one."""
552
+ return tuple(rule.level for rule in self.rules)
553
+
554
+ @property
555
+ def writes_one_level(self) -> bool:
556
+ """Whether every export writes one level: a one-level format, or a rule of one level."""
557
+ return self._format.one_level or len(self.rules) == 1
558
+
559
+ @property
560
+ def extension(self) -> str:
561
+ """The target's file suffix: ``.h5ad``, ``.h5mu``, ``.csv``, ``.txt``, or ``.qpx``."""
562
+ return self.output
563
+
564
+ def export(
565
+ self, parsed: ParsedLevels, abundance: Mapping[str, str] | None = None
566
+ ) -> ParsedLevels:
567
+ """Build the target's export from one APB2 result.
568
+
569
+ Args:
570
+ parsed: An APB2 result holding the rule's required levels.
571
+ abundance: Per level, the layer that becomes X; APB2's primary layer otherwise.
572
+
573
+ Returns:
574
+ A ``ParsedLevels`` for APB2's writer, one level per level written, and one feature
575
+ relation per feature link.
576
+
577
+ Raises:
578
+ ValueError: The result lacks a required level or source, a source cannot be taken
579
+ where the rule puts it, the levels share no observations, or ``abundance`` names
580
+ a level the rule does not read.
581
+ UnresolvedField: apb-catalog finds an answer ambiguous or the rule unreviewed.
582
+ """
583
+ chosen = dict(abundance or {})
584
+ unknown = sorted(set(chosen) - set(self.written))
585
+ if unknown:
586
+ raise ValueError(f"abundance names levels the rule does not write: {unknown}")
587
+ rules = self._exported_by(parsed)
588
+ aligned = self._aligned(parsed, rules)
589
+ exports, skipped = self._held(aligned, rules, chosen)
590
+ dataset, dataset_sources = self._dataset_uns(aligned, exports[0][0].level)
591
+ levels = {rule.rule.modality or rule.level: level.parsed_level() for rule, level in exports}
592
+ record = self._export_record(dataset_sources, skipped)
593
+ relations = {link.name: FeatureLinks(link, levels) for link in self.rules[0].feature_links}
594
+ if relations:
595
+ record["feature_links"] = [links.counts() for links in relations.values()]
596
+ result = ParsedLevels(
597
+ levels=levels,
598
+ uns=dict(aligned.uns),
599
+ metadata={
600
+ **aligned.metadata,
601
+ "export": {"schema_version": EXPORT_SCHEMA_VERSION, "provenance": record},
602
+ },
603
+ export_uns=cast(dict[str, JsonValue], dataset),
604
+ )
605
+ for name, links in relations.items():
606
+ if links.coordinates is not None:
607
+ result = result.with_feature_relation(
608
+ name, links.coordinates, {"producer": "apb-export"}
609
+ )
610
+ return result
611
+
612
+ def _aligned(self, parsed: ParsedLevels, rules: Sequence[EffectiveRule]) -> ParsedLevels:
613
+ """Several levels written, with the levels their layers reach into, on one observation
614
+ axis, as APB2's writer stores them; one level written stays as it is.
615
+
616
+ APB2 relabels levels keyed by experiment onto the raw files when the two map one to one,
617
+ as in MaxQuant; the group holding the first level written is kept.
618
+ """
619
+ if len(rules) == 1:
620
+ return parsed
621
+ names = dict.fromkeys([*(rule.level for rule in rules), *self.levels])
622
+ levels = {name: parsed.levels[name] for name in names if name in parsed.levels}
623
+ return self._format.align(replace(parsed, levels=levels), rules[0].level)
624
+
625
+ def _held(
626
+ self, parsed: ParsedLevels, rules: Sequence[EffectiveRule], chosen: Mapping[str, str]
627
+ ) -> tuple[list[tuple[EffectiveRule, _LevelExport]], list[str]]:
628
+ """Each level's export; an optional level left out when the result carries no index for
629
+ it, or when its observations cannot be aligned with the first level's."""
630
+ exports: list[tuple[EffectiveRule, _LevelExport]] = []
631
+ skipped: list[str] = []
632
+ for rule in rules:
633
+ if rule.level not in parsed.levels:
634
+ if rule.rule.required:
635
+ raise ValueError(
636
+ f"level {rule.level!r} does not share the observations of "
637
+ f"{sorted(parsed.levels)}"
638
+ )
639
+ logger.info(f"level {rule.level}: its observations are not aligned; left out")
640
+ skipped.append(rule.level)
641
+ continue
642
+ level = _LevelExport(rule, parsed, chosen.get(rule.level))
643
+ if not rule.rule.required and not level.has_index():
644
+ logger.info(f"level {rule.level}: the result carries no index for it; left out")
645
+ skipped.append(rule.level)
646
+ continue
647
+ exports.append((rule, level))
648
+ if not exports:
649
+ raise ValueError(f"no level of this result carries its index: {skipped}")
650
+ return exports, skipped
651
+
652
+ def _dataset_uns(
653
+ self, parsed: ParsedLevels, level: str
654
+ ) -> tuple[dict[str, object], dict[str, Provenance]]:
655
+ """The table's own uns entries, rule fields read from the first level written."""
656
+ sources = LevelSources(parsed, level, None)
657
+ values: list[tuple[str, object]] = []
658
+ provenance: dict[str, Provenance] = {}
659
+ for entry in self.rules[0].dataset_uns:
660
+ bound = _bind(entry, sources, "uns", _UNS_TAKES, {})
661
+ provenance[f"uns.{entry.name}"] = (
662
+ {"location": "absent"} if bound is None else bound.provenance
663
+ )
664
+ if bound is None:
665
+ continue
666
+ if isinstance(entry, Constant) and isinstance(entry.value, dict | list):
667
+ values.append((entry.name, copy.deepcopy(entry.value)))
668
+ else:
669
+ values.append((entry.name, _series(bound, ScalarRow(), {}).item()))
670
+ return _nest(values), provenance
671
+
672
+ def _export_record(
673
+ self, sources: dict[str, Provenance], skipped: list[str]
674
+ ) -> dict[str, JsonValue]:
675
+ """What wrote the container from which rule, its own uns sources and left-out levels."""
676
+ rule = self.rules[0]
677
+ record: dict[str, JsonValue] = {
678
+ "package": "apb-export",
679
+ "package_version": version("apb-export"),
680
+ "apb2_version": version("apb2"),
681
+ "target_name": rule.target_name,
682
+ "target_version_pattern": rule.target_version_pattern,
683
+ "export_rule": rule.document,
684
+ "export_rule_file_version": rule.file_version,
685
+ }
686
+ if sources:
687
+ record["sources"] = cast(JsonValue, sources)
688
+ if skipped:
689
+ record["skipped_levels"] = cast(JsonValue, skipped)
690
+ return record
691
+
692
+ def _exported_by(self, parsed: ParsedLevels) -> list[EffectiveRule]:
693
+ """The levels that export this result: those for its software that it holds.
694
+
695
+ A one-level format (``.h5ad``, ``.csv``, ``.txt``) takes the first of them; the others take all
696
+ of them and need every required one.
697
+ """
698
+ software = _software(parsed)
699
+ rules = [
700
+ rule
701
+ for rule in self.rules
702
+ if rule.rule.software is None or software & set(rule.rule.software)
703
+ ]
704
+ held = [rule for rule in rules if rule.level in parsed.levels]
705
+ if self._format.one_level:
706
+ missing = [] if held else [rule.level for rule in rules]
707
+ else:
708
+ missing = [rule.level for rule in rules if rule not in held and rule.rule.required]
709
+ target = self.rules[0].target_name
710
+ if missing:
711
+ raise ValueError(
712
+ f"{target} export needs APB2's {' or '.join(missing)} level; "
713
+ f"this result has {sorted(parsed.levels)}"
714
+ )
715
+ if not held:
716
+ raise ValueError(f"{target} export reads no level of {sorted(software)} results")
717
+ return held[:1] if self._format.one_level else held