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
@@ -0,0 +1,502 @@
1
+ """Export rule documents: apb2's rule schema, read from APB results instead of vendor tables.
2
+
3
+ Names follow apb2's ``rules.json``. Where a key keeps its name but its direction flips, its
4
+ description says so: an entry's ``name`` is the target field and its ``source`` the APB field.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from typing import Annotated, Literal, Self
11
+
12
+ from pydantic import BaseModel, ConfigDict, Field, JsonValue, field_validator, model_validator
13
+
14
+ type SchemaVersion = Literal["0.5"]
15
+ type ColumnType = Literal["string", "integer", "number", "boolean"]
16
+ type FloatWidth = Literal[32, 64]
17
+ type Scalar = str | int | float | bool | None
18
+
19
+
20
+ class ModelBase(BaseModel):
21
+ """Strict base: unknown keys are errors, as in apb2's rules."""
22
+
23
+ model_config = ConfigDict(extra="forbid", frozen=True)
24
+
25
+
26
+ class AxisSource(ModelBase):
27
+ """The level's observation or variable key column; a composite key is refused."""
28
+
29
+ axis: Literal["obs_key", "var_key"]
30
+
31
+
32
+ class MeasurementSource(ModelBase):
33
+ """The level's primary layer, or the abundance layer the caller picks."""
34
+
35
+ measurements: Literal["primary_layer"]
36
+
37
+
38
+ class RuleSource(ModelBase):
39
+ """A top-level field of the apb2 rule stored with the level, such as ``software_name``."""
40
+
41
+ rule: str = Field(min_length=1)
42
+
43
+
44
+ class CatalogueReference(ModelBase):
45
+ """A field found by meaning through apb-catalog, asked by one of the set's keys in one slot
46
+ of the level, as ``levels[level].var["protein_assignment"]`` asks it; the set ``apb_alpha`` holds
47
+ APB's own fields, such as ``ProForma_ion`` (key ``peptidoform_ion``) or the column a rule
48
+ marks with a role, and ``fasta_peptides_alpha`` and ``fasta_proteins_alpha`` apb-fasta's. A
49
+ set the result cannot open, because its app or ``apb2 annotate`` has not run, answers
50
+ nothing."""
51
+
52
+ catalog: str = Field(min_length=1)
53
+ qualifiers: dict[str, str] = Field(
54
+ default_factory=dict,
55
+ description="Further qualifiers of the request, besides those its key fixes, such as "
56
+ "a retention time's unit.",
57
+ )
58
+
59
+
60
+ class CatalogueField(CatalogueReference):
61
+ """A catalogued layer or var column, which may be read from a coarser level."""
62
+
63
+ from_level: Literal["protein"] | None = Field(
64
+ default=None,
65
+ description="Read the field from this level through each variable's protein_assignment, "
66
+ "as a layer: a cell takes its protein group's value in its run; a var column's value "
67
+ "repeats in every run. The assignment names its group whole, or else the group it "
68
+ "leads, as MaxQuant's razor protein does. A group the level lacks reads as missing.",
69
+ )
70
+ accept: Literal["present", "nonzero"] = Field(
71
+ default="present",
72
+ description="nonzero rejects a layer or var column holding no finite nonzero value, "
73
+ "such as DIA-NN's library q-value without match-between-runs.",
74
+ )
75
+
76
+
77
+ class CatalogueLayer(CatalogueField):
78
+ """A catalogued layer: ``{"catalog": "confidence_alpha", "layers": "q_value"}``."""
79
+
80
+ layers: str = Field(min_length=1, description="The set's key.")
81
+
82
+ @property
83
+ def key(self) -> str:
84
+ return self.layers
85
+
86
+ @property
87
+ def location(self) -> Literal["layers"]:
88
+ return "layers"
89
+
90
+
91
+ class CatalogueVar(CatalogueField):
92
+ """A catalogued var column: ``{"catalog": "apb_alpha", "var": "protein_assignment"}``."""
93
+
94
+ var: str = Field(min_length=1, description="The set's key.")
95
+
96
+ @property
97
+ def key(self) -> str:
98
+ return self.var
99
+
100
+ @property
101
+ def location(self) -> Literal["var"]:
102
+ return "var"
103
+
104
+
105
+ class CatalogueObs(CatalogueReference):
106
+ """A catalogued obs column: ``{"catalog": "obs_annotation_alpha", "obs": "group"}``."""
107
+
108
+ obs: str = Field(min_length=1, description="The set's key.")
109
+
110
+ @property
111
+ def key(self) -> str:
112
+ return self.obs
113
+
114
+ @property
115
+ def location(self) -> Literal["obs"]:
116
+ return "obs"
117
+
118
+
119
+ type CatalogueSource = CatalogueLayer | CatalogueVar | CatalogueObs
120
+
121
+
122
+ class ObsSource(ModelBase):
123
+ """An observation annotation column, by its name in the result, such as an SDRF column
124
+ apb2's sample annotation added; absent when the result was not annotated with it."""
125
+
126
+ obs: str = Field(min_length=1)
127
+
128
+
129
+ type Reference = (
130
+ AxisSource
131
+ | MeasurementSource
132
+ | RuleSource
133
+ | CatalogueLayer
134
+ | CatalogueVar
135
+ | CatalogueObs
136
+ | ObsSource
137
+ )
138
+
139
+
140
+ class EntryBase(ModelBase):
141
+ """Facts shared by every column and ``uns`` entry."""
142
+
143
+ name: str = Field(min_length=1, description="The target field; apb2's rules name APB fields.")
144
+ type: ColumnType = "string"
145
+ width: FloatWidth | None = Field(
146
+ default=None, description="Float width of a number entry; 64 when omitted."
147
+ )
148
+ required: bool = Field(
149
+ default=True,
150
+ description="An absent source is an error; when false, the entry is skipped or filled.",
151
+ )
152
+ fill_value: Scalar = Field(
153
+ default=None,
154
+ description='Written when an optional source is absent; "NaN" for numbers.',
155
+ )
156
+ drop_missing: bool = Field(
157
+ default=False,
158
+ description="A var entry: features whose value is missing or empty are left out "
159
+ "and counted, as prolfquapp and msmu need a protein for every feature.",
160
+ )
161
+
162
+ @model_validator(mode="after")
163
+ def _width_is_for_numbers(self) -> Self:
164
+ if self.width is not None and self.type != "number":
165
+ raise ValueError(f"entry {self.name!r}: width applies only to type number")
166
+ return self
167
+
168
+
169
+ class SourcedBase(EntryBase):
170
+ """An entry read from one APB source, or the first fallback the result carries."""
171
+
172
+ source: Reference = Field(description="The APB field; apb2's rules name a vendor column here.")
173
+ fallback: list[Reference] = Field(
174
+ default_factory=list,
175
+ description="Tried in order when the result lacks the source; one that answers is logged.",
176
+ )
177
+
178
+
179
+ class SourcedEntry(SourcedBase):
180
+ """A target field read from one APB source."""
181
+
182
+
183
+ class Constant(EntryBase):
184
+ """The same value everywhere."""
185
+
186
+ how: Literal["constant"]
187
+ value: JsonValue = Field(description="Any JSON in uns; a scalar in columns.")
188
+
189
+
190
+ class JoinNonempty(EntryBase):
191
+ """Non-empty input values joined with a separator, as apb2's ``join_nonempty``."""
192
+
193
+ how: Literal["join_nonempty"]
194
+ inputs: list[Reference] = Field(min_length=2, description="APB references, not entries.")
195
+ separator: str = Field(min_length=1)
196
+
197
+
198
+ class ProformaCharge(SourcedBase):
199
+ """The charge of a ProForma ion, ``SEQ/2`` giving 2."""
200
+
201
+ how: Literal["proforma_charge"]
202
+
203
+
204
+ class SequenceLength(SourcedBase):
205
+ """The number of characters of a sequence."""
206
+
207
+ how: Literal["sequence_length"]
208
+
209
+
210
+ class Accessions(SourcedBase):
211
+ """Protein-group members rewritten by a named ``accession_syntax``."""
212
+
213
+ how: Literal["accessions"]
214
+ syntax: str = Field(min_length=1)
215
+
216
+
217
+ class SingleAccession(SourcedBase):
218
+ """The accession a feature names when its protein list holds exactly one; otherwise missing.
219
+
220
+ ProteoPy's peptide-level data takes one protein per feature; with ``drop_missing`` the
221
+ features naming several proteins are left out, as ProteoPy's own DIA-NN reader does.
222
+ """
223
+
224
+ how: Literal["single_accession"]
225
+ separator: str = Field(default=";", min_length=1, description="The list's separator.")
226
+
227
+
228
+ class Contaminant(EntryBase):
229
+ """Whether the row is a contaminant: apb2's ``apb_Contaminant``, the contaminants the
230
+ software flags or adds itself, or apb-fasta's FASTA contaminant match where the result
231
+ was FASTA-checked."""
232
+
233
+ how: Literal["contaminant"]
234
+
235
+
236
+ class Lowercase(SourcedBase):
237
+ """The input text in lower case."""
238
+
239
+ how: Literal["lowercase"]
240
+
241
+
242
+ class ShortName(EntryBase):
243
+ """Per row, the first input holding a non-empty value, cut to its first ``separator``
244
+ member and, for a ``db|ACC|NAME`` member, to ``NAME``; ``append`` follows after ``_``.
245
+
246
+ An input the result does not carry, such as a FASTA column without a FASTA check, is passed
247
+ over; ``append`` is required.
248
+ """
249
+
250
+ how: Literal["short_name"]
251
+ inputs: list[Reference] = Field(min_length=1, description="Candidates per row, in order.")
252
+ separator: str = Field(default=";", min_length=1, description="Between group members.")
253
+ append: Reference | None = None
254
+
255
+
256
+ class AnnotationMap(EntryBase):
257
+ """Every obs annotation column mapped to its own name; ``uns`` only."""
258
+
259
+ how: Literal["annotation_map"]
260
+
261
+
262
+ class LayerMinimum(EntryBase):
263
+ """An exported layer's smallest value per variable across observations, missing values left
264
+ out, as one q-value per ion from a per-run layer."""
265
+
266
+ how: Literal["layer_minimum"]
267
+ layer: str = Field(min_length=1, description="A measurement layer of the same level.")
268
+
269
+
270
+ type ComputedEntry = Annotated[
271
+ Constant
272
+ | JoinNonempty
273
+ | ProformaCharge
274
+ | SequenceLength
275
+ | Accessions
276
+ | SingleAccession
277
+ | Contaminant
278
+ | Lowercase
279
+ | ShortName
280
+ | AnnotationMap
281
+ | LayerMinimum,
282
+ Field(discriminator="how"),
283
+ ]
284
+ type ColumnEntry = SourcedEntry | ComputedEntry
285
+
286
+
287
+ class Rename(ModelBase):
288
+ """An annotation column whose name matches ``pattern`` is written as text with sorted
289
+ categories, named as ``re.sub(pattern, replacement, name)`` gives it."""
290
+
291
+ pattern: str = Field(min_length=1, description="A Python regular expression.")
292
+ replacement: str = Field(min_length=1)
293
+ identifier: bool = Field(
294
+ default=False,
295
+ description="The new name in lower case, each character outside a-z, 0-9 and _ becoming _.",
296
+ )
297
+
298
+ @field_validator("pattern")
299
+ @classmethod
300
+ def _compiles(cls, pattern: str) -> str:
301
+ re.compile(pattern)
302
+ return pattern
303
+
304
+
305
+ class AllValues(ModelBase):
306
+ """Every obs annotation column the APB level carries, each under its own name unless a
307
+ rename matches it."""
308
+
309
+ name: str = Field(min_length=1)
310
+ how: Literal["all_values"]
311
+ rename: list[Rename] = Field(
312
+ default_factory=list,
313
+ description="Tried in order; the first whose pattern matches a column renames it.",
314
+ )
315
+
316
+
317
+ class LayerEntry(ModelBase):
318
+ """A target matrix read from one APB layer."""
319
+
320
+ name: str = Field(min_length=1)
321
+ source: Reference = Field(description="An APB layer: the primary layer or a catalogued one.")
322
+ fallback: list[Reference] = Field(
323
+ default_factory=list,
324
+ description="Tried in order when the result lacks the source; one that answers is logged.",
325
+ )
326
+ width: FloatWidth = 64
327
+ required: bool = Field(
328
+ default=True,
329
+ description="An absent source is an error; when false, the layer is left out.",
330
+ )
331
+ missing_values: list[float] = Field(
332
+ default_factory=list,
333
+ description="APB values treated as absent; apb2 lists vendor values here.",
334
+ )
335
+ name_by_key: dict[str, str] = Field(
336
+ default_factory=dict,
337
+ description="The written name per abundance key, or per qualifier=value pair, of the "
338
+ "resolved layer, as Perseus names MaxLFQ values (aggregation=maxlfq) LFQ intensity; "
339
+ "the first label the layer matches wins, and a layer matching none keeps name.",
340
+ )
341
+ transform: Literal["log2"] | None = Field(
342
+ default=None,
343
+ description="Applied after missing_values: log2, a value that is not positive becoming "
344
+ "missing.",
345
+ )
346
+
347
+
348
+ class Measurements(ModelBase):
349
+ """The target's matrices; the primary layer becomes X."""
350
+
351
+ primary_layer: str
352
+ layers: list[LayerEntry] = Field(min_length=1)
353
+
354
+ @model_validator(mode="after")
355
+ def _primary_is_declared(self) -> Self:
356
+ names = [layer.name for layer in self.layers]
357
+ if len(names) != len(set(names)):
358
+ raise ValueError("measurement layer names must be unique")
359
+ if self.primary_layer not in names:
360
+ raise ValueError(
361
+ f"measurements.primary_layer={self.primary_layer!r} matches no layer; "
362
+ f"available: {sorted(names)}"
363
+ )
364
+ return self
365
+
366
+
367
+ class Axis(ModelBase):
368
+ """The entries that become the target's observation and variable index."""
369
+
370
+ obs_key: str = Field(min_length=1)
371
+ var_key: str = Field(min_length=1)
372
+
373
+
374
+ class Columns(ModelBase):
375
+ """The target's observation and variable columns."""
376
+
377
+ obs: list[ColumnEntry | AllValues] = Field(default_factory=list)
378
+ var: list[ColumnEntry] = Field(min_length=1)
379
+
380
+
381
+ class AccessionSyntax(ModelBase):
382
+ """How a target writes protein-group members, like apb2's ``sequence_syntax``."""
383
+
384
+ separator: str = Field(min_length=1)
385
+ contaminant_markers: list[str] = Field(default_factory=list)
386
+ contaminant_prefix: str = ""
387
+
388
+
389
+ type Entries = list[ColumnEntry] | list[ColumnEntry | AllValues]
390
+
391
+
392
+ def _unique(group: str, entries: Entries) -> set[str]:
393
+ names = [entry.name for entry in entries]
394
+ if len(names) != len(set(names)):
395
+ raise ValueError(f"{group} entry names must be unique")
396
+ return set(names)
397
+
398
+
399
+ def _check_uns_only(group: str, entries: Entries) -> None:
400
+ for entry in entries:
401
+ if isinstance(entry, AnnotationMap) or (
402
+ isinstance(entry, Constant) and isinstance(entry.value, dict | list)
403
+ ):
404
+ raise ValueError(f"{group} entry {entry.name!r} can only be written to uns")
405
+
406
+
407
+ class LevelRule(ModelBase):
408
+ """One level's export, base and level merged: apb2's effective rule, reversed."""
409
+
410
+ modality: str | None = Field(default=None, description="The MuData modality it fills.")
411
+ required: bool = Field(default=True, description="When false, a result without it is fine.")
412
+ software: list[str] | None = Field(
413
+ default=None,
414
+ min_length=1,
415
+ description="The software, as apb2's rule names it, whose results this level exports; "
416
+ "every software when omitted. Another software's result skips the level.",
417
+ )
418
+ axis: Axis
419
+ measurements: Measurements
420
+ columns: Columns
421
+ uns: list[ColumnEntry] = Field(default_factory=list)
422
+ accession_syntax: dict[str, AccessionSyntax] = Field(default_factory=dict)
423
+
424
+ @model_validator(mode="after")
425
+ def _references_are_declared(self) -> Self:
426
+ obs = _unique("columns.obs", self.columns.obs)
427
+ var = _unique("columns.var", self.columns.var)
428
+ _unique("uns", self.uns)
429
+ if self.axis.obs_key not in obs:
430
+ raise ValueError(f"axis.obs_key={self.axis.obs_key!r} matches no columns.obs entry")
431
+ if self.axis.var_key not in var:
432
+ raise ValueError(f"axis.var_key={self.axis.var_key!r} matches no columns.var entry")
433
+ layers = {layer.name for layer in self.measurements.layers}
434
+ for entry in (*self.columns.obs, *self.columns.var, *self.uns):
435
+ if isinstance(entry, LayerMinimum) and entry.layer not in layers:
436
+ raise ValueError(f"entry {entry.name!r} names no measurement layer {entry.layer!r}")
437
+ _check_uns_only("columns.obs", self.columns.obs)
438
+ _check_uns_only("columns.var", self.columns.var)
439
+ for entry in (*self.columns.obs, *self.columns.var, *self.uns):
440
+ syntax = getattr(entry, "syntax", None)
441
+ if syntax is not None and syntax not in self.accession_syntax:
442
+ raise ValueError(f"entry {entry.name!r} names no accession_syntax {syntax!r}")
443
+ return self
444
+
445
+
446
+ type Output = Literal[".h5mu", ".h5ad", ".h5ads", ".csv", ".txt", ".qpx"]
447
+ """What one table writes, like apb2's ``input``: APB2's samples-by-features matrices.
448
+
449
+ ``.h5ad`` holds one level: the first listed that the result's software and levels allow.
450
+ ``.h5mu`` holds one modality per level; ``.h5ads`` is a directory of one ``.h5ad`` per level,
451
+ named by its modality. ``.csv`` holds one level as a long table and ``.txt`` one as a Perseus
452
+ table, each chosen as for ``.h5ad``.
453
+ """
454
+
455
+
456
+ class FeatureLink(ModelBase):
457
+ """A directed ``.h5mu`` relation between modalities, written to the MuData's ``varp``.
458
+
459
+ Each feature of a modality holding ``column`` maps to the ``target`` modality's feature whose
460
+ key equals its value: rows are the mapped features, columns the target's, values 1.0.
461
+ """
462
+
463
+ name: str = Field(min_length=1)
464
+ column: str = Field(min_length=1)
465
+ target: str = Field(min_length=1)
466
+
467
+
468
+ class Table(ModelBase):
469
+ """One output and the levels it reads; each level's block merges into ``base``: its entries
470
+ replace the base's of the same name, and the others are added."""
471
+
472
+ output: Output
473
+ base: dict[str, JsonValue] = Field(default_factory=dict)
474
+ levels: dict[str, dict[str, JsonValue]] = Field(min_length=1)
475
+ uns: list[ColumnEntry] = Field(
476
+ default_factory=list,
477
+ description="Dataset entries: the file's own uns beside each level's, from "
478
+ "constants and the stored apb2 rule of the first level written.",
479
+ )
480
+ feature_links: list[FeatureLink] = Field(default_factory=list)
481
+
482
+ @model_validator(mode="after")
483
+ def _dataset_entries(self) -> Self:
484
+ _unique("uns", self.uns)
485
+ if self.feature_links and self.output != ".h5mu":
486
+ raise ValueError("feature_links relate the modalities of an .h5mu output")
487
+ names = [link.name for link in self.feature_links]
488
+ if len(names) != len(set(names)):
489
+ raise ValueError("feature_links names must be unique: each is one relation")
490
+ return self
491
+
492
+
493
+ class ExportRuleDocument(ModelBase):
494
+ """One target's export rule file."""
495
+
496
+ schema_version: SchemaVersion
497
+ file_version: str = Field(min_length=1)
498
+ target_name: str = Field(min_length=1)
499
+ target_version_pattern: str = Field(
500
+ min_length=1, description="Target releases the rule was checked against; recorded only."
501
+ )
502
+ tables: list[Table] = Field(min_length=1)
@@ -0,0 +1,40 @@
1
+ """The published JSON Schemas of export rules, written from the models.
2
+
3
+ ``python -m apb_export.export_rules.schema_artifact`` rewrites them after a model change.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from pathlib import Path
10
+
11
+ from pydantic import BaseModel
12
+
13
+ from apb_export.export_rules.schema import ExportRuleDocument, LevelRule
14
+
15
+ SCHEMA_DIRECTORY = Path(__file__).parent / "documents" / "_schema"
16
+ _MODELS: dict[str, type[BaseModel]] = {
17
+ "document.schema.json": ExportRuleDocument,
18
+ "rule.schema.json": LevelRule,
19
+ }
20
+
21
+
22
+ def json_schemas() -> dict[str, dict[str, object]]:
23
+ """The document and effective-rule schemas the models declare, by file name."""
24
+ return {name: model.model_json_schema() for name, model in _MODELS.items()}
25
+
26
+
27
+ def write_artifacts() -> tuple[Path, ...]:
28
+ """Write both schemas beside the packaged rules."""
29
+ SCHEMA_DIRECTORY.mkdir(parents=True, exist_ok=True)
30
+ paths: list[Path] = []
31
+ for name, schema in json_schemas().items():
32
+ path = SCHEMA_DIRECTORY / name
33
+ path.write_text(json.dumps(schema, indent=2) + "\n", encoding="utf-8")
34
+ paths.append(path)
35
+ return tuple(paths)
36
+
37
+
38
+ if __name__ == "__main__":
39
+ for written in write_artifacts():
40
+ print(written)
@@ -0,0 +1,75 @@
1
+ """The long table: one row per observation and feature, the layers side by side."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import polars as pl
8
+ from apb2.api import ParsedLevel, ParsedLevels
9
+
10
+ _POSITIONS = ["var_pos", "obs_pos"]
11
+
12
+
13
+ def _layer(level: ParsedLevel, name: str) -> pl.DataFrame:
14
+ """One layer's stored cells, its value named as the layer: category codes as the labels
15
+ the parsing rule declared, NaN read as missing."""
16
+ layer = level.layers[name]
17
+ values = layer.semantics.decode(layer.cells.select(pl.col("value").alias(name)))
18
+ cells = layer.cells.select(_POSITIONS).hstack(values)
19
+ if cells.schema[name].is_float():
20
+ cells = cells.with_columns(pl.col(name).fill_nan(None))
21
+ return cells.filter(pl.col(name).is_not_null())
22
+
23
+
24
+ def _cells(level: ParsedLevel) -> pl.DataFrame:
25
+ """Every position some layer holds a value at, with each layer's value or null."""
26
+ frames = [_layer(level, name) for name in level.layers]
27
+ cells = frames[0]
28
+ for frame in frames[1:]:
29
+ cells = cells.join(frame, on=_POSITIONS, how="full", coalesce=True)
30
+ return cells
31
+
32
+
33
+ def long_table(level: ParsedLevel) -> pl.DataFrame:
34
+ """The level's obs columns, var columns and layers, one row per observed cell.
35
+
36
+ Raises:
37
+ ValueError: A column name repeats across obs, var and layers.
38
+ """
39
+ obs, var, layers = level.obs.frame, level.var.frame, list(level.layers)
40
+ names = [*obs.columns, *var.columns, *layers]
41
+ repeated = sorted({name for name in names if names.count(name) > 1})
42
+ if repeated:
43
+ raise ValueError(f"the long table would name {repeated} twice")
44
+ return (
45
+ _cells(level)
46
+ .sort(_POSITIONS)
47
+ .join(var.with_row_index("var_pos"), on="var_pos", how="left", maintain_order="left")
48
+ .join(obs.with_row_index("obs_pos"), on="obs_pos", how="left", maintain_order="left")
49
+ .select(*obs.columns, *var.columns, *layers)
50
+ )
51
+
52
+
53
+ class LongTableOutput:
54
+ """A CSV of one level, as MSstats reads one row per precursor and run."""
55
+
56
+ @property
57
+ def one_level(self) -> bool:
58
+ """The table holds the first listed level the result holds."""
59
+ return True
60
+
61
+ def align(self, parsed: ParsedLevels, first_level: str) -> ParsedLevels:
62
+ """Keep the observation group holding the exported level."""
63
+ return next(group for group in parsed.observation_groups() if first_level in group.levels)
64
+
65
+ def write(self, exported: ParsedLevels, output: Path) -> None:
66
+ """Write the long table, missing values as ``NA``; no sidecar.
67
+
68
+ Raises:
69
+ ValueError: The export holds more than one level.
70
+ """
71
+ if len(exported.levels) != 1:
72
+ raise ValueError(f"a long table holds one level, not {sorted(exported.levels)}")
73
+ (level,) = exported.levels.values()
74
+ output.parent.mkdir(parents=True, exist_ok=True)
75
+ long_table(level).write_csv(output, null_value="NA")