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/outputs.py ADDED
@@ -0,0 +1,90 @@
1
+ """Select the target serializer once; APB2 continues to own HDF5 persistence."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, replace
6
+ from pathlib import Path
7
+ from typing import Protocol
8
+
9
+ from apb2.api import ParsedLevels, write_parsed_levels
10
+
11
+ from apb_export.long_table import LongTableOutput
12
+ from apb_export.perseus_table import PerseusOutput
13
+ from apb_export.qpx.output import QpxOutput
14
+
15
+
16
+ class OutputFormat(Protocol):
17
+ """The operations that differ between matrix containers and tables."""
18
+
19
+ @property
20
+ def one_level(self) -> bool:
21
+ """Whether the format holds one level: the first listed that the result holds."""
22
+ ...
23
+
24
+ def align(self, parsed: ParsedLevels, first_level: str) -> ParsedLevels:
25
+ """Resolve the observation axes the format can represent."""
26
+ ...
27
+
28
+ def write(self, exported: ParsedLevels, output: Path) -> None:
29
+ """Serialize the exported quantities."""
30
+ ...
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class MatrixOutput:
35
+ """AnnData/MuData require one shared observation axis, as before."""
36
+
37
+ one_level: bool
38
+
39
+ def align(self, parsed: ParsedLevels, first_level: str) -> ParsedLevels:
40
+ """Keep the observation group holding the first exported level."""
41
+ return next(group for group in parsed.observation_groups() if first_level in group.levels)
42
+
43
+ def write(self, exported: ParsedLevels, output: Path) -> None:
44
+ """Delegate HDF5 and its sidecar to APB2."""
45
+ write_parsed_levels(exported, output, var_name_prefix=False)
46
+
47
+
48
+ class H5adPerLevel:
49
+ """A new ``.h5ads`` directory holding one APB2 ``.h5ad`` per exported level, named by it."""
50
+
51
+ @property
52
+ def one_level(self) -> bool:
53
+ """Every level the result holds gets its own file."""
54
+ return False
55
+
56
+ def align(self, parsed: ParsedLevels, first_level: str) -> ParsedLevels:
57
+ """Keep the levels of every observation group: each file has its own axis."""
58
+ del first_level
59
+ return replace(
60
+ parsed,
61
+ levels={
62
+ name: level
63
+ for group in parsed.observation_groups()
64
+ for name, level in group.levels.items()
65
+ },
66
+ )
67
+
68
+ def write(self, exported: ParsedLevels, output: Path) -> None:
69
+ """Write each level with APB2's writer and its sidecar, refusing an existing directory."""
70
+ if output.exists():
71
+ raise FileExistsError(f"refusing to overwrite {output}")
72
+ output.mkdir()
73
+ for name, level in exported.levels.items():
74
+ one = replace(exported, levels={name: level})
75
+ write_parsed_levels(one, output / f"{name}.h5ad", var_name_prefix=False)
76
+
77
+
78
+ _OUTPUTS: dict[str, OutputFormat] = {
79
+ ".h5ad": MatrixOutput(one_level=True),
80
+ ".h5mu": MatrixOutput(one_level=False),
81
+ ".h5ads": H5adPerLevel(),
82
+ ".csv": LongTableOutput(),
83
+ ".txt": PerseusOutput(),
84
+ ".qpx": QpxOutput(),
85
+ }
86
+
87
+
88
+ def output_for(extension: str) -> OutputFormat:
89
+ """Select the stateless serializer for one declared target output."""
90
+ return _OUTPUTS[extension]
@@ -0,0 +1,100 @@
1
+ """The Perseus table: one row per feature, ``#!{Type}`` and ``#!{C:<name>}`` header rows."""
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
+ _EMPTY = ""
11
+
12
+
13
+ def _var_column(column: pl.Series) -> tuple[pl.Series, str]:
14
+ """A var column as Perseus reads it, and its type: a flag as ``+`` or empty, categorical;
15
+ a number numerical; anything else text."""
16
+ if column.dtype == pl.Boolean:
17
+ marked = pl.select(pl.when(column).then(pl.lit("+")).otherwise(pl.lit(_EMPTY)))
18
+ return marked.to_series().alias(column.name), "C"
19
+ if column.dtype.is_numeric():
20
+ return column.cast(pl.Float64).fill_nan(None), "N"
21
+ return column.cast(pl.Utf8), "T"
22
+
23
+
24
+ def _sample_columns(level: ParsedLevel, name: str, samples: list[str]) -> pl.DataFrame:
25
+ """One layer, a ``<layer> <sample>`` column per sample, NaN read as missing."""
26
+ values = level.layers[name].quantitative_values().cast(pl.Float64).fill_nan(None)
27
+ return values.rename(
28
+ dict(zip(values.columns, [f"{name} {sample}" for sample in samples], strict=True))
29
+ )
30
+
31
+
32
+ def perseus_table(level: ParsedLevel) -> tuple[pl.DataFrame, list[str], dict[str, list[str]]]:
33
+ """The level's var columns, then each layer as ``<layer> <sample>`` columns.
34
+
35
+ Returns:
36
+ The table, one type letter per column, and per obs annotation column its value under
37
+ each sample column, empty under the others.
38
+
39
+ Raises:
40
+ ValueError: A column name repeats.
41
+ """
42
+ (key,) = level.obs.key_columns
43
+ obs = level.obs.frame.with_columns(pl.all().cast(pl.Utf8))
44
+ samples = obs.get_column(key).to_list()
45
+ columns, types = zip(
46
+ *(_var_column(column) for column in level.var.frame.iter_columns()), strict=True
47
+ )
48
+ layers = [_sample_columns(level, name, samples) for name in level.layers]
49
+ names = [
50
+ *(column.name for column in columns),
51
+ *(name for layer in layers for name in layer.columns),
52
+ ]
53
+ repeated = sorted({name for name in names if names.count(name) > 1})
54
+ if repeated:
55
+ raise ValueError(f"the Perseus table would name {repeated} twice")
56
+ table = pl.DataFrame(list(columns)).hstack([column for layer in layers for column in layer])
57
+ categories = {
58
+ name: [_EMPTY] * len(columns)
59
+ + obs.get_column(name).fill_null(_EMPTY).to_list() * len(layers)
60
+ for name in obs.columns
61
+ if name != key
62
+ }
63
+ return table, [*types, *["E"] * (table.width - len(columns))], categories
64
+
65
+
66
+ class PerseusOutput:
67
+ """A tab-separated table of one level, as Perseus loads MaxQuant's proteinGroups.txt."""
68
+
69
+ @property
70
+ def one_level(self) -> bool:
71
+ """The table holds the first listed level the result holds."""
72
+ return True
73
+
74
+ def align(self, parsed: ParsedLevels, first_level: str) -> ParsedLevels:
75
+ """Keep the observation group holding the exported level."""
76
+ return next(group for group in parsed.observation_groups() if first_level in group.levels)
77
+
78
+ def write(self, exported: ParsedLevels, output: Path) -> None:
79
+ """Write the Perseus table, missing numbers as ``NaN``; no sidecar.
80
+
81
+ Raises:
82
+ ValueError: The export holds more than one level.
83
+ """
84
+ if len(exported.levels) != 1:
85
+ raise ValueError(f"a Perseus table holds one level, not {sorted(exported.levels)}")
86
+ (level,) = exported.levels.values()
87
+ table, types, categories = perseus_table(level)
88
+ header = [
89
+ "\t".join(table.columns),
90
+ "#!{Type}" + "\t".join(types),
91
+ *("#!{C:" + name + "}" + "\t".join(values) for name, values in categories.items()),
92
+ ]
93
+ numbers = [
94
+ name for name, kind in zip(table.columns, types, strict=True) if kind in {"E", "N"}
95
+ ]
96
+ body = table.with_columns(pl.col(numbers).fill_null(float("nan"))).write_csv(
97
+ separator="\t", include_header=False, null_value=_EMPTY, quote_style="never"
98
+ )
99
+ output.parent.mkdir(parents=True, exist_ok=True)
100
+ output.write_text("\n".join(header) + "\n" + body, encoding="utf-8")
apb_export/py.typed ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,81 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License.
30
+ Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
31
+
32
+ 3. Grant of Patent License.
33
+ Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution.
36
+ You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
37
+
38
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
39
+
40
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
41
+
42
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
43
+
44
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
45
+
46
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
47
+
48
+ 5. Submission of Contributions.
49
+ Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
50
+
51
+ 6. Trademarks.
52
+ This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
53
+
54
+ 7. Disclaimer of Warranty.
55
+ Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
56
+
57
+ 8. Limitation of Liability.
58
+ In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
59
+
60
+ 9. Accepting Warranty or Additional Liability.
61
+ While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
62
+
63
+ END OF TERMS AND CONDITIONS
64
+
65
+ APPENDIX: How to apply the Apache License to your work.
66
+
67
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
68
+
69
+ Copyright 2025 BigBio
70
+
71
+ Licensed under the Apache License, Version 2.0 (the "License");
72
+ you may not use this file except in compliance with the License.
73
+ You may obtain a copy of the License at
74
+
75
+ http://www.apache.org/licenses/LICENSE-2.0
76
+
77
+ Unless required by applicable law or agreed to in writing, software
78
+ distributed under the License is distributed on an "AS IS" BASIS,
79
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
80
+ See the License for the specific language governing permissions and
81
+ limitations under the License.
File without changes
@@ -0,0 +1,215 @@
1
+ """QPX serialization of already exported APB quantities; no vendor parsing or aggregation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import shutil
7
+ import tempfile
8
+ from dataclasses import replace
9
+ from importlib.metadata import version
10
+ from pathlib import Path
11
+
12
+ import polars as pl
13
+ import pyarrow.parquet as pq
14
+ from apb2.api import ParsedLevel, ParsedLevels
15
+
16
+ from apb_export.qpx.schema import arrow_schema
17
+
18
+ _MEMBERS = pl.col("proteins").str.split(";")
19
+
20
+
21
+ def _quantities(level: ParsedLevel) -> pl.DataFrame:
22
+ """Join stored primary quantities to their feature and observation rows by position."""
23
+ cells = level.layers[level.primary_layer_name].cells
24
+ observed = cells.filter(pl.col("value").is_not_null() & ~pl.col("value").is_nan())
25
+ if observed.select(pl.col("value").cast(pl.Float32).is_infinite().any()).item():
26
+ raise ValueError("QPX float32 intensity cannot represent an infinite or overflowing value")
27
+ return (
28
+ observed.join(level.var.frame.with_row_index("var_pos"), on="var_pos", how="left")
29
+ .join(level.obs.frame.with_row_index("obs_pos"), on="obs_pos", how="left")
30
+ .sort("var_pos", "obs_pos")
31
+ )
32
+
33
+
34
+ def _features(level: ParsedLevel) -> pl.DataFrame:
35
+ frame = _quantities(level)
36
+ if "proteins" not in frame.columns:
37
+ frame = frame.with_columns(proteins=pl.lit(None, dtype=pl.String))
38
+ members = _MEMBERS.list.eval(
39
+ pl.struct(
40
+ pl.element().alias("accession"),
41
+ pl.lit(None, dtype=pl.Int32).alias("start"),
42
+ pl.lit(None, dtype=pl.Int32).alias("end"),
43
+ pl.lit(None, dtype=pl.String).alias("pre"),
44
+ pl.lit(None, dtype=pl.String).alias("post"),
45
+ )
46
+ )
47
+ return (
48
+ _retention_time(frame, level)
49
+ .with_row_index("feature_id")
50
+ .with_columns(
51
+ pl.col("feature_id").cast(pl.Int64),
52
+ pg_accessions=members,
53
+ anchor_protein=_MEMBERS.list.first(),
54
+ intensities=pl.concat_list(
55
+ pl.struct(pl.lit("LFQ").alias("label"), pl.col("value").alias("intensity"))
56
+ ),
57
+ scan=pl.lit([], dtype=pl.List(pl.Int32)),
58
+ )
59
+ )
60
+
61
+
62
+ def _retention_time(frame: pl.DataFrame, level: ParsedLevel) -> pl.DataFrame:
63
+ """Convert only the original units resolved by the chromatography catalogue."""
64
+ values: list[pl.Expr] = []
65
+ for name, seconds in (("rt_second", 1), ("rt_minute", 60)):
66
+ layer = level.layers.get(name)
67
+ if layer is None:
68
+ continue
69
+ frame = frame.join(
70
+ layer.cells.rename({"value": name}),
71
+ on=["var_pos", "obs_pos"],
72
+ how="left",
73
+ validate="1:1",
74
+ )
75
+ values.append(pl.col(name) * seconds)
76
+ rt = pl.coalesce(values) if values else pl.lit(None, dtype=pl.Float64)
77
+ return frame.with_columns(rt.alias("rt"))
78
+
79
+
80
+ def _proteins(level: ParsedLevel) -> pl.DataFrame:
81
+ return (
82
+ _quantities(level)
83
+ .with_row_index("pg_id")
84
+ .with_columns(
85
+ pl.col("pg_id").cast(pl.Int64),
86
+ pg_accessions=_MEMBERS,
87
+ anchor_protein=_MEMBERS.list.first(),
88
+ grouped_runs=pl.concat_list("run_file_name"),
89
+ label=pl.lit("LFQ"),
90
+ intensity=pl.col("value"),
91
+ peptides=pl.lit(
92
+ [], dtype=pl.List(pl.Struct({"protein_name": pl.String, "peptide_count": pl.Int32}))
93
+ ),
94
+ )
95
+ )
96
+
97
+
98
+ def _design(parsed: ParsedLevels) -> tuple[pl.DataFrame, pl.DataFrame]:
99
+ """Use run identities as technical sample identities; carry supplied annotations."""
100
+ frames = [level.obs.frame for level in parsed.levels.values()]
101
+ obs = pl.concat(frames, how="diagonal_relaxed")
102
+ # A level may carry fewer annotation columns than another; retain known values.
103
+ annotations = [name for name in obs.columns if name != "run_file_name"]
104
+ for name in annotations:
105
+ conflicts = obs.group_by("run_file_name").agg(pl.col(name).drop_nulls().n_unique())
106
+ if conflicts.get_column(name).gt(1).any():
107
+ raise ValueError(f"conflicting observation annotation {name!r} for the same QPX run")
108
+ obs = obs.group_by("run_file_name", maintain_order=True).agg(
109
+ *(pl.col(name).drop_nulls().first() for name in annotations)
110
+ )
111
+ samples = obs.rename({"run_file_name": "sample_accession"})
112
+ # QPX 1.1 requires non-null organism/tissue strings. This is an explicit missing
113
+ # marker, never an inferred organism or experimental grouping.
114
+ samples = samples.with_columns(
115
+ *(
116
+ pl.col(name).fill_null("not available")
117
+ if name in samples.columns
118
+ else pl.lit("not available").alias(name)
119
+ for name in ("organism", "organism_part")
120
+ )
121
+ )
122
+ runs = obs.select("run_file_name").with_columns(
123
+ run_accession=pl.col("run_file_name"),
124
+ samples=pl.concat_list(
125
+ pl.struct(
126
+ pl.col("run_file_name").alias("sample_accession"),
127
+ pl.lit("LFQ").alias("label"),
128
+ pl.lit(None, dtype=pl.Int32).alias("biological_replicate"),
129
+ pl.lit(None, dtype=pl.Int32).alias("technical_replicate"),
130
+ )
131
+ ),
132
+ )
133
+ return runs, samples
134
+
135
+
136
+ def _write(view: str, frame: pl.DataFrame, output: Path, record: dict[str, str]) -> None:
137
+ schema = arrow_schema(view)
138
+ columns = frame.select(
139
+ *(
140
+ pl.col(name) if name in frame.columns else pl.lit(None).alias(name)
141
+ for name in schema.names
142
+ )
143
+ )
144
+ table = columns.to_arrow().cast(schema)
145
+ if view == "sample":
146
+ for name in frame.columns:
147
+ if name not in schema.names:
148
+ table = table.append_column(name, frame.select(name).to_arrow().column(0))
149
+ metadata = {
150
+ **record,
151
+ "file_type": f"{view}_file",
152
+ "compression_format": "zstd",
153
+ }
154
+ table = table.replace_schema_metadata({k.encode(): v.encode() for k, v in metadata.items()})
155
+ pq.write_table(table, output / f"apb.{view}.parquet", compression="zstd")
156
+
157
+
158
+ class QpxOutput:
159
+ """Separate QPX views can represent every observation group without discarding levels."""
160
+
161
+ @property
162
+ def one_level(self) -> bool:
163
+ """QPX writes a view for each level it reads."""
164
+ return False
165
+
166
+ def align(self, parsed: ParsedLevels, first_level: str) -> ParsedLevels:
167
+ """Use APB2's safe run aliases, retaining levels from every observation group."""
168
+ del first_level
169
+ return replace(
170
+ parsed,
171
+ levels={
172
+ name: level
173
+ for group in parsed.observation_groups()
174
+ for name, level in group.levels.items()
175
+ },
176
+ )
177
+
178
+ def write(self, exported: ParsedLevels, output: Path) -> None:
179
+ """Write a complete QPX directory, refusing existing destinations."""
180
+ if output.suffix != ".qpx":
181
+ raise ValueError("QPX export needs a new .qpx directory")
182
+ if output.exists():
183
+ raise FileExistsError(f"refusing to overwrite {output}")
184
+ builders = {"feature": _features, "pg": _proteins}
185
+ tables = {name: builders[name](level) for name, level in exported.levels.items()}
186
+ if not any(frame.height for frame in tables.values()):
187
+ raise ValueError("QPX export has no reported precursor or protein quantities")
188
+ tables["run"], tables["sample"] = _design(exported)
189
+ record = {
190
+ "qpx_version": "1.1",
191
+ "creator": "apb-export",
192
+ "writer_version": version("apb-export"),
193
+ "software_provider": "apb2",
194
+ }
195
+ output.parent.mkdir(parents=True, exist_ok=True)
196
+ # Build beside the destination; a failed serializer never leaves a partial export.
197
+ with tempfile.TemporaryDirectory(prefix=f".{output.name}-", dir=output.parent) as temporary:
198
+ staging = Path(temporary)
199
+ for name, frame in tables.items():
200
+ _write(name, frame, staging, record)
201
+ manifest = {
202
+ "format": "qpx",
203
+ **record,
204
+ "tables": {name: frame.height for name, frame in tables.items()},
205
+ "export": exported.metadata["export"],
206
+ }
207
+ (staging / "export.json").write_text(json.dumps(manifest, indent=2) + "\n")
208
+ # mkdir is exclusive even if another process created the destination meanwhile.
209
+ output.mkdir()
210
+ try:
211
+ for path in staging.iterdir():
212
+ path.rename(output / path.name)
213
+ except OSError:
214
+ shutil.rmtree(output)
215
+ raise