apb-export-ui 0.3.0__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.
@@ -0,0 +1,375 @@
1
+ """Example inputs served beside the page: the rows of one corpus CSV, as APB Studio writes it.
2
+
3
+ A row names an input file or folder, its parameter file, its ProteoBench module and its
4
+ software, relative to a data root. An ``sdrf.tsv`` inside an input folder, or beside an input
5
+ file, is the example's sample annotation; otherwise ``<module>.sdrf.tsv`` in an SDRF folder,
6
+ such as apb-proteobench's module data, is.
7
+
8
+ ProteoBench stores uploads as ``input_file.*`` and ``param_0.*``. An example's version, read
9
+ from its parameter file, picks the export it is, so the page shows and serves the names the
10
+ tool itself wrote. The levels apb2 finds in an example's files, as a job links them, tell the
11
+ page which outputs the example can give.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import csv
17
+ import hashlib
18
+ import json
19
+ import re
20
+ import shutil
21
+ from dataclasses import dataclass, replace
22
+ from itertools import islice
23
+ from pathlib import Path
24
+ from tempfile import TemporaryDirectory
25
+ from typing import Any
26
+
27
+ import polars as pl
28
+ from apb2.api import ConversionError, ParseRuleCompiler, parse_search_parameters
29
+ from loguru import logger
30
+
31
+ from apb_export_ui.web.exports import Export, SoftwareHint, export_for
32
+ from apb_export_ui.web.store import write_json
33
+
34
+ _COLUMNS = ("input_file", "vendor_parameter_file", "module", "software_name")
35
+ # What a preview shows: the first lines, each cut to a width a page can still scroll.
36
+ HEAD_LINES = 20
37
+ _HEAD_WIDTH = 4000
38
+
39
+
40
+ @dataclass(frozen=True, slots=True)
41
+ class Example:
42
+ id: str
43
+ # The corpus's name, such as "FragPipe (DIA-NN quant)".
44
+ label: str
45
+ # The software whose parameter file it carries, by apb2's name: "FragPipe".
46
+ software: str
47
+ # The software that wrote the result, read alone without parameters: "DIA-NN".
48
+ result_software: str
49
+ module: str
50
+ data: Path
51
+ params: Path | None
52
+ annotation: Path | None
53
+ # The version its parameter file names; None without one.
54
+ version: str | None = None
55
+ # The export it is, when its version and file kind identify one.
56
+ export: Export | None = None
57
+ # Further result files stored beside ``data`` as ``<stem>_*``, such as AlphaDIA 1.12's
58
+ # precursor.matrix.tsv; APB Studio passes them with it as one folder.
59
+ secondary: tuple[Path, ...] = ()
60
+ # The FASTA its module prescribes, from the corpus's optional ``fasta`` column.
61
+ fasta: Path | None = None
62
+ # The levels apb2 finds in its result, read with its parameter file when it has one;
63
+ # None when apb2 cannot read it.
64
+ levels: tuple[str, ...] | None = None
65
+
66
+ def inputs(self) -> dict[str, list[tuple[str, Path]]]:
67
+ """Each input field's files: the names the tool wrote, else the stored names."""
68
+ data = [self.data, *self.secondary]
69
+ native = (
70
+ self.export.result_names(len(data)) if self.export and self.data.is_file() else None
71
+ )
72
+ named = {"data": list(zip(native or [path.name for path in data], data, strict=True))}
73
+ if self.params is not None:
74
+ name = self.export.concrete_params() if self.export else None
75
+ named["params"] = [(name or self.params.name, self.params)]
76
+ if self.annotation is not None:
77
+ named["annotation"] = [(self.annotation.name, self.annotation)]
78
+ if self.fasta is not None:
79
+ named["fasta"] = [(self.fasta.name, self.fasta)]
80
+ return named
81
+
82
+ def link(self, folder: Path, fields: set[str]) -> dict[str, Path]:
83
+ """Link the chosen fields' files into ``folder/<field>`` under the names the tool wrote.
84
+
85
+ Several result files go into one folder named after the first, which the converter
86
+ reads as one vendor result.
87
+
88
+ Returns:
89
+ Each linked field's file, or folder of several files.
90
+ """
91
+ linked: dict[str, Path] = {}
92
+ for field, named in self.inputs().items():
93
+ if field not in fields:
94
+ continue
95
+ target = folder / field
96
+ if len(named) > 1:
97
+ target = target / Path(named[0][0]).stem
98
+ target.mkdir(parents=True)
99
+ for name, path in named:
100
+ (target / name).symlink_to(path, target_is_directory=path.is_dir())
101
+ linked[field] = target if len(named) > 1 else target / named[0][0]
102
+ return linked
103
+
104
+ def folder_files(self) -> list[Path]:
105
+ """The files inside a folder result, such as MaxQuant's txt folder; none for a file."""
106
+ if not self.data.is_dir():
107
+ return []
108
+ return sorted(path for path in self.data.iterdir() if path.is_file())
109
+
110
+ def files(self) -> dict[str, Path]:
111
+ """The example's downloadable files by the name they are served under.
112
+
113
+ A folder result's files go by their own names; one that is also the parameter file or
114
+ annotation, such as MaxQuant's mqpar.xml, is the same file.
115
+ """
116
+ named = {path.name: path for path in self.folder_files()}
117
+ named.update(
118
+ (name, path)
119
+ for files in self.inputs().values()
120
+ for name, path in files
121
+ if path.is_file()
122
+ )
123
+ return named
124
+
125
+ def describe(self) -> dict[str, object]:
126
+ inputs = self.inputs()
127
+ params = inputs.get("params")
128
+ annotation = inputs.get("annotation")
129
+ return {
130
+ "id": self.id,
131
+ "label": self.label,
132
+ "software": self.software,
133
+ "version": self.version,
134
+ "module": self.module,
135
+ "data": [name for name, _ in inputs["data"]],
136
+ "stored_data": [path.name for _, path in inputs["data"]],
137
+ "folder": self.data.is_dir(),
138
+ "folder_files": [path.name for path in self.folder_files()],
139
+ "params": None if params is None else params[0][0],
140
+ "stored_params": None if self.params is None else self.params.name,
141
+ "annotation": None if annotation is None else annotation[0][0],
142
+ "fasta": None if self.fasta is None else self.fasta.name,
143
+ "export": None if self.export is None else self.export.describe(),
144
+ "levels": None if self.levels is None else list(self.levels),
145
+ "bytes": sum(_size(path) for path in (self.data, *self.secondary)),
146
+ }
147
+
148
+ def record(self, root: Path) -> dict[str, object]:
149
+ """What the server needs to offer it again, its paths relative to the examples folder."""
150
+
151
+ def relative(path: Path | None) -> str | None:
152
+ return None if path is None else path.relative_to(root).as_posix()
153
+
154
+ return {
155
+ "id": self.id,
156
+ "label": self.label,
157
+ "software": self.software,
158
+ "result_software": self.result_software,
159
+ "module": self.module,
160
+ "data": relative(self.data),
161
+ "params": relative(self.params),
162
+ "annotation": relative(self.annotation),
163
+ "version": self.version,
164
+ "export": None if self.export is None else self.export.describe(),
165
+ "secondary": [relative(path) for path in self.secondary],
166
+ "fasta": relative(self.fasta),
167
+ "levels": None if self.levels is None else list(self.levels),
168
+ }
169
+
170
+ @classmethod
171
+ def from_record(cls, record: dict[str, Any], root: Path) -> Example:
172
+ """An example as :meth:`record` wrote it, its paths under ``root``."""
173
+
174
+ def absolute(path: str | None) -> Path | None:
175
+ return None if path is None else root / path
176
+
177
+ return cls(
178
+ id=record["id"],
179
+ label=record["label"],
180
+ software=record["software"],
181
+ result_software=record["result_software"],
182
+ module=record["module"],
183
+ data=root / record["data"],
184
+ params=absolute(record["params"]),
185
+ annotation=absolute(record["annotation"]),
186
+ version=record["version"],
187
+ export=None if record["export"] is None else Export.read(record["export"]),
188
+ secondary=tuple(root / path for path in record["secondary"]),
189
+ fasta=absolute(record["fasta"]),
190
+ levels=None if record["levels"] is None else tuple(record["levels"]),
191
+ )
192
+
193
+
194
+ def _size(path: Path) -> int:
195
+ if path.is_dir():
196
+ return sum(item.stat().st_size for item in path.rglob("*") if item.is_file())
197
+ return path.stat().st_size
198
+
199
+
200
+ def _secondary(data: Path) -> tuple[Path, ...]:
201
+ """Files stored beside a result as ``<stem>_*``, as APB Studio finds them."""
202
+ if data.is_dir():
203
+ return ()
204
+ return tuple(path for path in sorted(data.parent.glob(f"{data.stem}_*")) if path.is_file())
205
+
206
+
207
+ def _annotation(data: Path, module: str, sdrf: Path | None) -> Path | None:
208
+ candidates = [(data if data.is_dir() else data.parent) / "sdrf.tsv"]
209
+ if sdrf is not None:
210
+ candidates.append(sdrf / f"{module}.sdrf.tsv")
211
+ return next((candidate for candidate in candidates if candidate.is_file()), None)
212
+
213
+
214
+ def _key(name: str) -> str:
215
+ return re.sub(r"[^a-z0-9]", "", name.lower())
216
+
217
+
218
+ def _names(label: str, software: list[str]) -> tuple[str, str]:
219
+ """The parameter and result software of a corpus name, as apb2 names them.
220
+
221
+ A compound name such as "FragPipe (DIA-NN quant)" carries FragPipe's parameters and
222
+ DIA-NN's result, as APB Studio reads it.
223
+ """
224
+ by_key = {_key(name): name for name in software}
225
+ parameters = label.split("(", 1)[0].strip()
226
+ compound = re.search(r"\((.+?)\s+quant\)", label)
227
+ result = compound.group(1) if compound else parameters
228
+ return by_key.get(_key(parameters), parameters), by_key.get(_key(result), result)
229
+
230
+
231
+ def _version(params: Path | None, software: str) -> str | None:
232
+ """The version a parameter file names, as apb2 reads it; None when it cannot."""
233
+ if params is None:
234
+ return None
235
+ try:
236
+ version = parse_search_parameters(params, software).software_version
237
+ except (OSError, ValueError) as error:
238
+ # Display only: the example still runs; the page shows the stored name instead.
239
+ logger.warning(f"no version for example parameters {params}: {error}")
240
+ return None
241
+ return None if version is None else str(version).strip()
242
+
243
+
244
+ def _levels(example: Example, software: list[str]) -> tuple[str, ...] | None:
245
+ """The levels apb2 finds in the example's result and parameter file, linked and named as a
246
+ job links them and read as apb-export reads them; None when apb2 cannot read them."""
247
+ named = example.software if example.params is not None else example.result_software
248
+ chosen = named if named in software else None
249
+ with TemporaryDirectory() as folder:
250
+ linked = example.link(Path(folder), {"data", "params"})
251
+ data, params = linked["data"], linked.get("params")
252
+ try:
253
+ compiler = (
254
+ ParseRuleCompiler.from_software(data, chosen)
255
+ if params is None and chosen is not None
256
+ else ParseRuleCompiler.detect(data, params, software=chosen)
257
+ )
258
+ except ConversionError as error:
259
+ # Every output is offered, as for an upload; the job reports apb2's error.
260
+ logger.warning(f"{example.data}: apb2 finds no level: {error}")
261
+ return None
262
+ return tuple(selection.level for selection in compiler.detection.levels)
263
+
264
+
265
+ def load_examples(
266
+ corpus: Path,
267
+ root: Path,
268
+ sdrf: Path | None = None,
269
+ software: list[str] | None = None,
270
+ hints: dict[str, SoftwareHint] | None = None,
271
+ patterns: dict[str, str] | None = None,
272
+ ) -> list[Example]:
273
+ """Every row of the corpus CSV whose input exists under ``root``.
274
+
275
+ With hints, a row no export of its software describes stays in the corpus but is no
276
+ example: the page offers only what it says the converter reads. AlphaDIA 1.10's rows are
277
+ such, a table ProteoBench joined from AlphaDIA's two outputs.
278
+
279
+ Paths are absolute: jobs link to them from their own folders.
280
+
281
+ Raises:
282
+ ValueError: The CSV lacks a corpus column, or names an input that does not exist.
283
+ """
284
+ with corpus.open(encoding="utf-8", newline="") as table:
285
+ rows = list(csv.DictReader(table))
286
+ root = root.absolute()
287
+ sdrf = None if sdrf is None else sdrf.absolute()
288
+ examples: list[Example] = []
289
+ for row in rows:
290
+ absent = [column for column in _COLUMNS if column not in row]
291
+ if absent:
292
+ raise ValueError(f"{corpus} lacks columns {absent}")
293
+ data = root / row["input_file"]
294
+ if not data.exists():
295
+ raise ValueError(f"{corpus} names {data}, which does not exist")
296
+ params = root / row["vendor_parameter_file"] if row["vendor_parameter_file"] else None
297
+ parameter_software, result_software = _names(row["software_name"], software or [])
298
+ hint = (hints or {}).get(parameter_software)
299
+ version = _version(params, parameter_software) if hint is not None else None
300
+ export = (
301
+ None
302
+ if hint is None
303
+ else export_for(hint, patterns or {}, row["software_name"], version, data)
304
+ )
305
+ if hint is not None and export is None:
306
+ logger.warning(f"{row['input_file']}: no {parameter_software} hint describes it")
307
+ continue
308
+ examples.append(
309
+ Example(
310
+ id=hashlib.sha256(row["input_file"].encode()).hexdigest()[:12],
311
+ label=row["software_name"],
312
+ software=parameter_software,
313
+ result_software=result_software,
314
+ module=row["module"],
315
+ data=data,
316
+ params=params,
317
+ annotation=_annotation(data, row["module"], sdrf),
318
+ version=version,
319
+ export=export,
320
+ secondary=_secondary(data),
321
+ fasta=root / row["fasta"] if row.get("fasta") else None,
322
+ )
323
+ )
324
+ return [replace(example, levels=_levels(example, software or [])) for example in examples]
325
+
326
+
327
+ def write_examples(path: Path, examples: list[Example], root: Path) -> None:
328
+ """The page's example list, each entry with its ``source``: its record under ``root``."""
329
+ write_json(
330
+ path,
331
+ {
332
+ "examples": [
333
+ {**example.describe(), "source": example.record(root)} for example in examples
334
+ ]
335
+ },
336
+ )
337
+
338
+
339
+ def read_examples(path: Path, root: Path) -> list[Example]:
340
+ """The examples :func:`write_examples` wrote, their paths under ``root``."""
341
+ listed = json.loads(path.read_text(encoding="utf-8"))["examples"]
342
+ return [Example.from_record(entry["source"], root) for entry in listed]
343
+
344
+
345
+ def head(path: Path) -> dict[str, object]:
346
+ """The first lines of a file as the page previews it; a Parquet file's first rows as TSV."""
347
+ if path.suffix.lower() == ".parquet":
348
+ table = pl.read_parquet(path, n_rows=HEAD_LINES)
349
+ lines = table.write_csv(separator="\t").splitlines()
350
+ complete = table.height < HEAD_LINES
351
+ kind = "parquet"
352
+ else:
353
+ with path.open(encoding="utf-8", errors="replace", newline="") as text:
354
+ lines = [line.rstrip("\r\n") for line in islice(text, HEAD_LINES + 1)]
355
+ complete = len(lines) <= HEAD_LINES
356
+ lines, kind = lines[:HEAD_LINES], "text"
357
+ return {
358
+ "name": path.name,
359
+ "bytes": path.stat().st_size,
360
+ "format": kind,
361
+ "lines": [line[:_HEAD_WIDTH] for line in lines],
362
+ "complete": complete,
363
+ }
364
+
365
+
366
+ def write_previews(folder: Path, examples: list[Example]) -> None:
367
+ """Each example file's head as ``<folder>/<example id>/<served name>.json``; the folder
368
+ exists even without examples."""
369
+ if folder.exists():
370
+ shutil.rmtree(folder)
371
+ folder.mkdir(parents=True)
372
+ for example in examples:
373
+ (folder / example.id).mkdir(parents=True)
374
+ for name, path in example.files().items():
375
+ write_json(folder / example.id / f"{name}.json", {**head(path), "name": name})
@@ -0,0 +1,139 @@
1
+ """Which files each software writes, as its own documentation names them.
2
+
3
+ ``hints.json`` lists, per software, the exports the converter reads: the native result file
4
+ names, the parameter file, and the apb2 rule (and so the version range) each export belongs
5
+ to. The page shows them as upload hints; examples find their own export by version, file
6
+ kind and corpus label, so they can show and serve the names the tool wrote.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import re
13
+ from dataclasses import asdict, dataclass
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from apb2.api import get_rules
18
+
19
+ HINTS = Path(__file__).parent / "hints.json"
20
+
21
+
22
+ def _pattern(name: str) -> bool:
23
+ """A name the user or run chooses, such as "<report name>.tsv" or "*.txt"."""
24
+ return any(mark in name for mark in "*<>")
25
+
26
+
27
+ @dataclass(frozen=True, slots=True)
28
+ class Export:
29
+ """One kind of output a software writes and the converter reads."""
30
+
31
+ # The apb2 rules that read it, such as "alphadia/v1_10/rules.json"; their version
32
+ # patterns say which versions write it.
33
+ rules: tuple[str, ...]
34
+ # The versions it covers, for people: "1.10".
35
+ versions: str
36
+ # The result file or files, as the tool names them.
37
+ result: tuple[str, ...]
38
+ # The parameter or log file, as the tool names it; None when there is none.
39
+ params: str | None
40
+ # How it arrives: file suffixes such as ".tsv", or "folder" for a directory.
41
+ kinds: tuple[str, ...]
42
+ # Corpus names that choose it whatever the version, such as "FragPipe (DIA-NN quant)".
43
+ labels: tuple[str, ...] = ()
44
+ note: str | None = None
45
+
46
+ def concrete_name(self) -> str | None:
47
+ """The file name an example of this export goes by; None for a pattern or several files."""
48
+ if len(self.result) != 1 or _pattern(self.result[0]):
49
+ return None
50
+ return Path(self.result[0]).name
51
+
52
+ def result_names(self, count: int) -> list[str] | None:
53
+ """Names for ``count`` result files in the tool's order; None when they are not fixed."""
54
+ if count == 1:
55
+ name = self.concrete_name()
56
+ return None if name is None else [name]
57
+ if count != len(self.result) or any(_pattern(name) for name in self.result):
58
+ return None
59
+ return [Path(name).name for name in self.result]
60
+
61
+ def concrete_params(self) -> str | None:
62
+ """The parameter file name an example goes by; None for a pattern."""
63
+ if self.params is None or _pattern(self.params):
64
+ return None
65
+ return Path(self.params).name
66
+
67
+ def describe(self) -> dict[str, object]:
68
+ return asdict(self)
69
+
70
+ @classmethod
71
+ def read(cls, entry: dict[str, Any]) -> Export:
72
+ """An export as ``hints.json`` and :meth:`describe` write it."""
73
+ return cls(
74
+ rules=tuple(entry["rules"]),
75
+ versions=entry["versions"],
76
+ result=tuple(entry["result"]),
77
+ params=entry.get("params"),
78
+ kinds=tuple(entry["kinds"]),
79
+ labels=tuple(entry.get("labels", ())),
80
+ note=entry.get("note"),
81
+ )
82
+
83
+
84
+ @dataclass(frozen=True, slots=True)
85
+ class SoftwareHint:
86
+ exports: tuple[Export, ...]
87
+ params_required: bool
88
+ sources: tuple[str, ...]
89
+
90
+
91
+ def load_hints(path: Path = HINTS) -> tuple[dict[str, object], dict[str, SoftwareHint]]:
92
+ """The raw document for the page, and the parsed hints by software."""
93
+ document = json.loads(path.read_text(encoding="utf-8"))
94
+ hints = {
95
+ name: SoftwareHint(
96
+ exports=tuple(Export.read(export) for export in entry["exports"]),
97
+ params_required=entry.get("params_required", False),
98
+ sources=tuple(entry.get("sources", ())),
99
+ )
100
+ for name, entry in document["software"].items()
101
+ }
102
+ return document, hints
103
+
104
+
105
+ def rule_versions() -> dict[str, str]:
106
+ """Each packaged apb2 rule and the version pattern it accepts."""
107
+ return {
108
+ variant.rule: variant.software_version_pattern
109
+ for category in ("DDA", "DIA")
110
+ for rules in get_rules(category)
111
+ for variant in rules.variants
112
+ }
113
+
114
+
115
+ def export_for(
116
+ hint: SoftwareHint,
117
+ patterns: dict[str, str],
118
+ label: str,
119
+ version: str | None,
120
+ data: Path,
121
+ ) -> Export | None:
122
+ """The one export an example is: by corpus label, else by version, then by file kind.
123
+
124
+ Without a version, as for an example without a parameter file, the file kind alone must
125
+ single one out, as it does for pb_custom and MetaMorpheus.
126
+ """
127
+ kind = "folder" if data.is_dir() else data.suffix.lower()
128
+ labelled = [export for export in hint.exports if label in export.labels]
129
+ candidates = labelled or [
130
+ export
131
+ for export in hint.exports
132
+ if not export.labels
133
+ and (
134
+ version is None
135
+ or any(re.match(patterns.get(rule, r"(?!)"), version.strip()) for rule in export.rules)
136
+ )
137
+ ]
138
+ matching = [export for export in candidates if kind in export.kinds]
139
+ return matching[0] if len(matching) == 1 else None