plexembler 0.5.0rc1__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.
- plexembler/__init__.py +11 -0
- plexembler/_log.py +167 -0
- plexembler/_report/__init__.py +613 -0
- plexembler/_report/base.html.j2 +146 -0
- plexembler/_report/macros.html.j2 +144 -0
- plexembler/_report/report.css +1928 -0
- plexembler/_report/report.js +362 -0
- plexembler/ani.py +215 -0
- plexembler/browser.py +157 -0
- plexembler/circular.py +235 -0
- plexembler/cli.py +1538 -0
- plexembler/closest.py +427 -0
- plexembler/digest.py +216 -0
- plexembler/dotplot.py +758 -0
- plexembler/expression.py +129 -0
- plexembler/finalize.py +397 -0
- plexembler/genes.py +414 -0
- plexembler/junctions.py +571 -0
- plexembler/rename.py +231 -0
- plexembler/report.py +416 -0
- plexembler/run.py +244 -0
- plexembler/screen.py +503 -0
- plexembler/select.py +542 -0
- plexembler/split.py +544 -0
- plexembler-0.5.0rc1.dist-info/METADATA +110 -0
- plexembler-0.5.0rc1.dist-info/RECORD +29 -0
- plexembler-0.5.0rc1.dist-info/WHEEL +4 -0
- plexembler-0.5.0rc1.dist-info/entry_points.txt +2 -0
- plexembler-0.5.0rc1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,613 @@
|
|
|
1
|
+
# chromokit 0.2.0 - MIT - https://github.com/js2264/chromokit - the report kit: do not edit, chromokit sync replaces it and chromokit check refuses an edit
|
|
2
|
+
# Linted and formatted in chromokit, not by the package that holds it:
|
|
3
|
+
# ruff: noqa
|
|
4
|
+
# fmt: off
|
|
5
|
+
"""chromokit's report kit: the report of one run of a tool, for one sample.
|
|
6
|
+
|
|
7
|
+
A tool describes itself once, as a Tool: its name and version, the version of
|
|
8
|
+
its report's format (FORMAT_VERSION), its columns in MultiQC's General
|
|
9
|
+
Statistics table, and its page's template. It gathers a run into a Report:
|
|
10
|
+
sections, each a key and its value per line, and tables. write_report then
|
|
11
|
+
writes three files in an output directory, named after the sample
|
|
12
|
+
(report_files):
|
|
13
|
+
|
|
14
|
+
- <sample>.report.txt (write_txt): every number of the report, for scripts,
|
|
15
|
+
which read_txt reads back;
|
|
16
|
+
- <sample>.report_mqc.yaml (write_mqc): MultiQC's custom content, the sample's
|
|
17
|
+
row of its General Statistics table, which MultiQC merges with the other
|
|
18
|
+
samples' rows;
|
|
19
|
+
- <sample>.report.html (write_html): a page to read the run with, rendered by
|
|
20
|
+
Jinja2 from the tool's template, which extends this kit's base.html.j2. Its
|
|
21
|
+
plots are drawn by plotly.js, which the page loads from its CDN at a pinned
|
|
22
|
+
version (PLOTLY_JS); offline, it keeps its numbers and tables.
|
|
23
|
+
|
|
24
|
+
This is metaTOR's report (koszullab/metaTOR, src/metator/report.py),
|
|
25
|
+
generalised. It belongs to chromokit (https://github.com/js2264/chromokit):
|
|
26
|
+
`chromokit add report` and `chromokit sync` copy it into
|
|
27
|
+
src/<package>/_report/, and `chromokit check` refuses a local edit. It names no
|
|
28
|
+
package and imports nothing from the one that holds it, so one copy serves
|
|
29
|
+
every tool. Put a tool's own code in its own module, and its own page in its
|
|
30
|
+
own template.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import math
|
|
36
|
+
import numbers
|
|
37
|
+
import os
|
|
38
|
+
import re
|
|
39
|
+
import sys
|
|
40
|
+
import time
|
|
41
|
+
from collections.abc import Mapping
|
|
42
|
+
from dataclasses import dataclass, field
|
|
43
|
+
from pathlib import Path
|
|
44
|
+
|
|
45
|
+
__all__ = [
|
|
46
|
+
"PLOTLY_JS",
|
|
47
|
+
"REPORT_FILES",
|
|
48
|
+
"REPORT_HTML",
|
|
49
|
+
"REPORT_MQC",
|
|
50
|
+
"REPORT_TXT",
|
|
51
|
+
"Report",
|
|
52
|
+
"Tool",
|
|
53
|
+
"format_value",
|
|
54
|
+
"json_ready",
|
|
55
|
+
"key_numbers",
|
|
56
|
+
"read_txt",
|
|
57
|
+
"report_files",
|
|
58
|
+
"report_section",
|
|
59
|
+
"sample_name",
|
|
60
|
+
"write_html",
|
|
61
|
+
"write_mqc",
|
|
62
|
+
"write_report",
|
|
63
|
+
"write_txt",
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
#: The files of a report, in the order report_files names them: the page
|
|
67
|
+
#: links to the other two.
|
|
68
|
+
REPORT_TXT = "report.txt"
|
|
69
|
+
REPORT_HTML = "report.html"
|
|
70
|
+
REPORT_MQC = "report_mqc.yaml"
|
|
71
|
+
REPORT_FILES = (REPORT_TXT, REPORT_HTML, REPORT_MQC)
|
|
72
|
+
|
|
73
|
+
#: plotly.js, which the page loads from its CDN when it is opened: a pinned
|
|
74
|
+
#: version, which draws the plots the same over time.
|
|
75
|
+
PLOTLY_JS = "https://cdn.plot.ly/plotly-2.35.2.min.js"
|
|
76
|
+
|
|
77
|
+
#: This kit's folder: its templates, its stylesheet and its script.
|
|
78
|
+
HERE = Path(__file__).resolve().parent
|
|
79
|
+
|
|
80
|
+
#: The name of a section or a table of report.txt, which read_txt finds again.
|
|
81
|
+
_NAME = re.compile(r"[a-z][a-z0-9_]*")
|
|
82
|
+
|
|
83
|
+
#: What the page's template reads: the context given to write_html must not
|
|
84
|
+
#: take these names.
|
|
85
|
+
_KIT_CONTEXT = frozenset(
|
|
86
|
+
{
|
|
87
|
+
"tool",
|
|
88
|
+
"report",
|
|
89
|
+
"sample",
|
|
90
|
+
"tables",
|
|
91
|
+
"columns",
|
|
92
|
+
"figures",
|
|
93
|
+
"links",
|
|
94
|
+
"inputs",
|
|
95
|
+
"key_numbers",
|
|
96
|
+
"plotly_js",
|
|
97
|
+
"format_version",
|
|
98
|
+
"kit_css",
|
|
99
|
+
"kit_js",
|
|
100
|
+
}
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _numpy():
|
|
105
|
+
"""numpy, if the program has imported it: then a value may be one of its
|
|
106
|
+
scalars. The kit itself needs no numpy."""
|
|
107
|
+
return sys.modules.get("numpy")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass(frozen=True)
|
|
111
|
+
class Tool:
|
|
112
|
+
"""A tool, as its reports name it.
|
|
113
|
+
|
|
114
|
+
Attributes
|
|
115
|
+
----------
|
|
116
|
+
name : str
|
|
117
|
+
The tool's name, as its pages and files write it: "metaTOR".
|
|
118
|
+
version : str
|
|
119
|
+
The tool's version, which writes the report.
|
|
120
|
+
format_version : int
|
|
121
|
+
The version of the format of report.txt and report_mqc.yaml: a key,
|
|
122
|
+
a column, a unit or a MultiQC id that changes, or goes, raises it;
|
|
123
|
+
one that comes does not.
|
|
124
|
+
columns : tuple
|
|
125
|
+
The tool's columns in MultiQC's General Statistics table, in order:
|
|
126
|
+
for each, its key in report.txt, the section of that key, and how
|
|
127
|
+
MultiQC shows it (its pconfig: title, description, format, min, max,
|
|
128
|
+
suffix, scale). They are also the cards of the page's overview.
|
|
129
|
+
id : str
|
|
130
|
+
The MultiQC id of the tool's section: every sample's file carries it,
|
|
131
|
+
and MultiQC merges the samples into one table. It also names the
|
|
132
|
+
tool's version in the section report (<id>_version). By default, the
|
|
133
|
+
name in lower case.
|
|
134
|
+
description : str
|
|
135
|
+
One line on what the columns sum up, which MultiQC shows; the format
|
|
136
|
+
version follows it.
|
|
137
|
+
docs : str
|
|
138
|
+
Where report.txt is documented: its header links there.
|
|
139
|
+
template : str or os.PathLike
|
|
140
|
+
The tool's page: a Jinja2 template that starts with
|
|
141
|
+
``{% extends "_report/base.html.j2" %}``. Templates beside it can be
|
|
142
|
+
included or imported by name. Without one, the page is the kit's
|
|
143
|
+
base alone, which shows every section and table as it comes.
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
name: str
|
|
147
|
+
version: str
|
|
148
|
+
format_version: int
|
|
149
|
+
columns: tuple = ()
|
|
150
|
+
id: str | None = None
|
|
151
|
+
description: str | None = None
|
|
152
|
+
docs: str | None = None
|
|
153
|
+
template: str | os.PathLike | None = None
|
|
154
|
+
|
|
155
|
+
def __post_init__(self):
|
|
156
|
+
if not self.name.strip():
|
|
157
|
+
raise ValueError("a tool needs a name")
|
|
158
|
+
ident = self.id
|
|
159
|
+
if ident is None:
|
|
160
|
+
ident = re.sub(r"[^a-z0-9]+", "_", self.name.lower()).strip("_")
|
|
161
|
+
if not _NAME.fullmatch(ident):
|
|
162
|
+
raise ValueError(f"{ident!r} cannot be a MultiQC id: [a-z][a-z0-9_]*")
|
|
163
|
+
object.__setattr__(self, "id", ident)
|
|
164
|
+
columns = tuple(tuple(column) for column in self.columns)
|
|
165
|
+
for column in columns:
|
|
166
|
+
if len(column) != 3 or not isinstance(column[2], Mapping):
|
|
167
|
+
raise ValueError(f"a column is (key, section, pconfig), not {column!r}")
|
|
168
|
+
object.__setattr__(self, "columns", columns)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@dataclass
|
|
172
|
+
class Report:
|
|
173
|
+
"""The report of one run, for one sample (see write_report).
|
|
174
|
+
|
|
175
|
+
Attributes
|
|
176
|
+
----------
|
|
177
|
+
sections : dict
|
|
178
|
+
The sections of report.txt, by name, in order, each its keys and
|
|
179
|
+
their values, in order (int, float, bool or str; None when missing).
|
|
180
|
+
The first, report, says what wrote the report, for which sample, from
|
|
181
|
+
what (see report_section). The page shows run (the run's parameters)
|
|
182
|
+
and commands (its command lines, by step) in its Run section.
|
|
183
|
+
tables : dict
|
|
184
|
+
The tables of report.txt, by name, in order (pandas.DataFrame).
|
|
185
|
+
plots : dict
|
|
186
|
+
Whatever the tool draws its plots from: report.txt leaves it out.
|
|
187
|
+
"""
|
|
188
|
+
|
|
189
|
+
sections: dict = field(default_factory=dict)
|
|
190
|
+
tables: dict = field(default_factory=dict)
|
|
191
|
+
plots: dict = field(default_factory=dict)
|
|
192
|
+
|
|
193
|
+
@property
|
|
194
|
+
def sample(self):
|
|
195
|
+
"""The sample's name, which names the report's files and its MultiQC row."""
|
|
196
|
+
try:
|
|
197
|
+
return self.sections["report"]["sample"]
|
|
198
|
+
except KeyError:
|
|
199
|
+
raise ValueError(
|
|
200
|
+
"the report names no sample (see report_section)"
|
|
201
|
+
) from None
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def report_files(name):
|
|
205
|
+
"""The files of the report of the sample name, in the order of
|
|
206
|
+
REPORT_FILES: <name>.report.txt, <name>.report.html and
|
|
207
|
+
<name>.report_mqc.yaml, which MultiQC finds by its _mqc suffix."""
|
|
208
|
+
return tuple(f"{name}.{file}" for file in REPORT_FILES)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def sample_name(path, *extensions):
|
|
212
|
+
"""A sample's name from the name of its main file: the file's name without
|
|
213
|
+
the longest of extensions that it ends with (metaTOR: the map's name
|
|
214
|
+
without .metacool or .mmetacool)."""
|
|
215
|
+
name = os.path.basename(os.fspath(path).rstrip("/\\"))
|
|
216
|
+
for extension in sorted(extensions, key=len, reverse=True):
|
|
217
|
+
if name.endswith(extension) and len(name) > len(extension):
|
|
218
|
+
return name[: -len(extension)]
|
|
219
|
+
return name
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def report_section(tool, sample, inputs=None, **more):
|
|
223
|
+
"""The section report of a report, in order: format_version, sample, the
|
|
224
|
+
run's inputs (a mapping, such as {"map": path}), the version of the tool
|
|
225
|
+
that writes it (<tool.id>_version), when (written: now, in local time,
|
|
226
|
+
to the second), then more."""
|
|
227
|
+
section = {"format_version": tool.format_version, "sample": sample}
|
|
228
|
+
section.update(inputs or {})
|
|
229
|
+
section[f"{tool.id}_version"] = tool.version
|
|
230
|
+
section["written"] = time.strftime("%Y-%m-%dT%H:%M:%S")
|
|
231
|
+
section.update(more)
|
|
232
|
+
return section
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# ---------------------------------------------------------------------------
|
|
236
|
+
# report.txt
|
|
237
|
+
# ---------------------------------------------------------------------------
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _missing(value):
|
|
241
|
+
"""Whether value is missing: None, or a number that is not one (NaN)."""
|
|
242
|
+
if value is None:
|
|
243
|
+
return True
|
|
244
|
+
if isinstance(value, numbers.Real) and not isinstance(value, numbers.Integral):
|
|
245
|
+
return math.isnan(float(value))
|
|
246
|
+
return False
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _is_bool(value):
|
|
250
|
+
numpy = _numpy()
|
|
251
|
+
return isinstance(value, bool) or (
|
|
252
|
+
numpy is not None and isinstance(value, numpy.bool_)
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def format_value(key, value):
|
|
257
|
+
"""A value as report.txt writes it, under its key: NA for a missing one
|
|
258
|
+
(None, NaN); true or false; an integer as an integer; a float with 2
|
|
259
|
+
decimals for a percent (a key ending in _pct), 4 for a ratio or a
|
|
260
|
+
fraction (_ratio, _fraction), as an integer when it is one and is
|
|
261
|
+
neither, else as Python writes it shortest; a text on one line, NA when
|
|
262
|
+
empty."""
|
|
263
|
+
if _missing(value):
|
|
264
|
+
return "NA"
|
|
265
|
+
if _is_bool(value):
|
|
266
|
+
return "true" if value else "false"
|
|
267
|
+
if isinstance(value, numbers.Integral):
|
|
268
|
+
return str(int(value))
|
|
269
|
+
if isinstance(value, numbers.Real):
|
|
270
|
+
value = float(value)
|
|
271
|
+
if value.is_integer() and not key.endswith(("_pct", "_ratio", "_fraction")):
|
|
272
|
+
return str(int(value))
|
|
273
|
+
if key.endswith("_pct"):
|
|
274
|
+
return f"{value:.2f}"
|
|
275
|
+
if key.endswith(("_ratio", "_fraction")):
|
|
276
|
+
return f"{value:.4f}"
|
|
277
|
+
return repr(value)
|
|
278
|
+
return " ".join(str(value).split()) or "NA"
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _check_name(kind, name):
|
|
282
|
+
if not isinstance(name, str) or not _NAME.fullmatch(name):
|
|
283
|
+
raise ValueError(
|
|
284
|
+
f"{kind} {name!r}: report.txt names it in lowercase letters, digits and _, a letter first"
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _check_word(kind, word, where):
|
|
289
|
+
if not isinstance(word, str) or not word or word != "".join(word.split()):
|
|
290
|
+
raise ValueError(
|
|
291
|
+
f"{kind} {word!r} of {where}: report.txt splits its lines on spaces, so it holds none"
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def write_txt(report, path, tool):
|
|
296
|
+
"""Write report.txt at path: a header of comments, naming the tool, the
|
|
297
|
+
sample and the format (tool.format_version), and linking tool.docs; each
|
|
298
|
+
section, ``[name]``, then a line per key, the key, spaces, and its value
|
|
299
|
+
(see format_value); each table, ``[table: name]``, then its header and a
|
|
300
|
+
line per row, their fields aligned on spaces. No name, key, column or
|
|
301
|
+
field holds a space: a field's spaces are written as _, and a section's
|
|
302
|
+
value is the rest of its line. A missing value is NA."""
|
|
303
|
+
sample = report.sample
|
|
304
|
+
see = f" See {tool.docs}" if tool.docs else ""
|
|
305
|
+
lines = [
|
|
306
|
+
f"# {tool.name} report of {sample}",
|
|
307
|
+
f"# format {tool.format_version}: [section] then a key and its value per line; [table: name] then a header and a row",
|
|
308
|
+
f"# per line, on spaces; NA: missing.{see}",
|
|
309
|
+
"",
|
|
310
|
+
]
|
|
311
|
+
for name, values in report.sections.items():
|
|
312
|
+
_check_name("section", name)
|
|
313
|
+
for key in values:
|
|
314
|
+
_check_word("key", key, f"section {name}")
|
|
315
|
+
width = max((len(key) for key in values), default=0)
|
|
316
|
+
lines.append(f"[{name}]")
|
|
317
|
+
lines += [
|
|
318
|
+
f"{key.ljust(width)} {format_value(key, value)}"
|
|
319
|
+
for key, value in values.items()
|
|
320
|
+
]
|
|
321
|
+
lines.append("")
|
|
322
|
+
for name, table in report.tables.items():
|
|
323
|
+
_check_name("table", name)
|
|
324
|
+
columns = [str(column) for column in table.columns]
|
|
325
|
+
for column in columns:
|
|
326
|
+
_check_word("column", column, f"table {name}")
|
|
327
|
+
lines.append(f"[table: {name}]")
|
|
328
|
+
rows = [
|
|
329
|
+
[
|
|
330
|
+
format_value(column, value).replace(" ", "_")
|
|
331
|
+
for column, value in zip(columns, row, strict=True)
|
|
332
|
+
]
|
|
333
|
+
for row in table.itertuples(index=False)
|
|
334
|
+
]
|
|
335
|
+
widths = [
|
|
336
|
+
max([len(column)] + [len(row[index]) for row in rows])
|
|
337
|
+
for index, column in enumerate(columns)
|
|
338
|
+
]
|
|
339
|
+
lines.append(
|
|
340
|
+
" ".join(
|
|
341
|
+
column.ljust(width)
|
|
342
|
+
for column, width in zip(columns, widths, strict=True)
|
|
343
|
+
).rstrip()
|
|
344
|
+
)
|
|
345
|
+
lines += [
|
|
346
|
+
" ".join(
|
|
347
|
+
value.ljust(width) for value, width in zip(row, widths, strict=True)
|
|
348
|
+
).rstrip()
|
|
349
|
+
for row in rows
|
|
350
|
+
]
|
|
351
|
+
lines.append("")
|
|
352
|
+
with open(path, "w", encoding="utf-8", newline="\n") as handle:
|
|
353
|
+
handle.write("\n".join(lines))
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def read_txt(path):
|
|
357
|
+
"""Read report.txt (see write_txt) back: its sections, by name, each its
|
|
358
|
+
keys and their values, as text; and its tables, by name, as
|
|
359
|
+
pandas.DataFrame of text. NA is None. What a script, or a MultiQC module,
|
|
360
|
+
does to gather the reports of runs."""
|
|
361
|
+
import pandas as pd
|
|
362
|
+
|
|
363
|
+
sections, tables, current, header, rows = {}, {}, None, None, []
|
|
364
|
+
|
|
365
|
+
def close():
|
|
366
|
+
if header is not None:
|
|
367
|
+
tables[current] = pd.DataFrame(rows, columns=pd.Index(header), dtype=object)
|
|
368
|
+
|
|
369
|
+
with open(path, encoding="utf-8") as handle:
|
|
370
|
+
for line in handle.read().splitlines():
|
|
371
|
+
if not line.strip() or line.startswith("#"):
|
|
372
|
+
continue
|
|
373
|
+
match = re.fullmatch(r"\[(table: )?([a-z][a-z0-9_]*)\]", line.strip())
|
|
374
|
+
if match:
|
|
375
|
+
close()
|
|
376
|
+
current, header, rows = match.group(2), None, []
|
|
377
|
+
if match.group(1):
|
|
378
|
+
header = []
|
|
379
|
+
else:
|
|
380
|
+
sections[current] = {}
|
|
381
|
+
continue
|
|
382
|
+
if header == []:
|
|
383
|
+
header = line.split()
|
|
384
|
+
elif header is not None:
|
|
385
|
+
rows.append(
|
|
386
|
+
[None if value == "NA" else value for value in line.split()]
|
|
387
|
+
)
|
|
388
|
+
else:
|
|
389
|
+
key, _, value = line.partition(" ")
|
|
390
|
+
value = value.strip()
|
|
391
|
+
sections[current][key] = None if value == "NA" else value
|
|
392
|
+
close()
|
|
393
|
+
return sections, tables
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
# ---------------------------------------------------------------------------
|
|
397
|
+
# report_mqc.yaml
|
|
398
|
+
# ---------------------------------------------------------------------------
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _column_value(report, key, section):
|
|
402
|
+
"""The value of a General Statistics column: None when missing."""
|
|
403
|
+
value = report.sections.get(section, {}).get(key)
|
|
404
|
+
if _missing(value):
|
|
405
|
+
return None
|
|
406
|
+
if _is_bool(value) or isinstance(value, numbers.Integral):
|
|
407
|
+
return int(value)
|
|
408
|
+
return float(value)
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def write_mqc(report, path, tool):
|
|
412
|
+
"""Write report_mqc.yaml at path: MultiQC's custom content, the sample's
|
|
413
|
+
row of its General Statistics table, of tool.columns (a missing value
|
|
414
|
+
leaves its column out), under tool.id, which every sample's file
|
|
415
|
+
carries, so that MultiQC merges the samples into one table (``multiqc
|
|
416
|
+
.`` finds the files by their _mqc suffix)."""
|
|
417
|
+
import yaml
|
|
418
|
+
|
|
419
|
+
sample = report.sample
|
|
420
|
+
row, pconfig = {}, []
|
|
421
|
+
for key, section, config in tool.columns:
|
|
422
|
+
value = _column_value(report, key, section)
|
|
423
|
+
if value is None:
|
|
424
|
+
continue
|
|
425
|
+
row[key] = value
|
|
426
|
+
pconfig.append({key: dict(config)})
|
|
427
|
+
description = tool.description or f"{tool.name} runs"
|
|
428
|
+
content = {
|
|
429
|
+
"id": tool.id,
|
|
430
|
+
"section_name": tool.name,
|
|
431
|
+
"description": f"{description} (format {tool.format_version}).",
|
|
432
|
+
"plot_type": "generalstats",
|
|
433
|
+
"pconfig": pconfig,
|
|
434
|
+
"data": {sample: row},
|
|
435
|
+
}
|
|
436
|
+
with open(path, "w", encoding="utf-8", newline="\n") as handle:
|
|
437
|
+
handle.write(
|
|
438
|
+
f"# {tool.name} report of {sample}: MultiQC custom content (General Statistics); multiqc finds it.\n"
|
|
439
|
+
)
|
|
440
|
+
yaml.safe_dump(
|
|
441
|
+
content,
|
|
442
|
+
handle,
|
|
443
|
+
sort_keys=False,
|
|
444
|
+
default_flow_style=False,
|
|
445
|
+
allow_unicode=True,
|
|
446
|
+
)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
# ---------------------------------------------------------------------------
|
|
450
|
+
# report.html
|
|
451
|
+
# ---------------------------------------------------------------------------
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def json_ready(value):
|
|
455
|
+
"""value with NaN and the infinities as None, tuples as lists, and numpy's
|
|
456
|
+
types as Python's: what JSON.parse reads (it refuses NaN)."""
|
|
457
|
+
numpy = _numpy()
|
|
458
|
+
if isinstance(value, Mapping):
|
|
459
|
+
return {str(key): json_ready(item) for key, item in value.items()}
|
|
460
|
+
if isinstance(value, (list, tuple)):
|
|
461
|
+
return [json_ready(item) for item in value]
|
|
462
|
+
if numpy is not None and isinstance(value, numpy.ndarray):
|
|
463
|
+
return json_ready(value.tolist())
|
|
464
|
+
if _is_bool(value):
|
|
465
|
+
return bool(value)
|
|
466
|
+
if isinstance(value, numbers.Integral):
|
|
467
|
+
return int(value)
|
|
468
|
+
if isinstance(value, numbers.Real):
|
|
469
|
+
return float(value) if math.isfinite(float(value)) else None
|
|
470
|
+
return value
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def key_numbers(report, tool):
|
|
474
|
+
"""The cards of the page's overview: the tool's General Statistics
|
|
475
|
+
columns, each its title, its value as MultiQC formats it (with its
|
|
476
|
+
suffix, NA when missing) and its description."""
|
|
477
|
+
cards = []
|
|
478
|
+
for key, section, config in tool.columns:
|
|
479
|
+
value = _column_value(report, key, section)
|
|
480
|
+
if value is None:
|
|
481
|
+
shown = "NA"
|
|
482
|
+
else:
|
|
483
|
+
try:
|
|
484
|
+
shown = config.get("format", "{:,}").format(value)
|
|
485
|
+
except (ValueError, TypeError):
|
|
486
|
+
shown = format_value(key, value)
|
|
487
|
+
shown += config.get("suffix", "")
|
|
488
|
+
cards.append(
|
|
489
|
+
{
|
|
490
|
+
"key": key,
|
|
491
|
+
"section": section,
|
|
492
|
+
"label": config.get("title", key),
|
|
493
|
+
"value": shown,
|
|
494
|
+
"detail": config.get("description", ""),
|
|
495
|
+
}
|
|
496
|
+
)
|
|
497
|
+
return cards
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _environment(tool):
|
|
501
|
+
import jinja2
|
|
502
|
+
|
|
503
|
+
loaders = []
|
|
504
|
+
if tool.template is not None:
|
|
505
|
+
loaders.append(
|
|
506
|
+
jinja2.FileSystemLoader(os.path.dirname(os.path.abspath(tool.template)))
|
|
507
|
+
)
|
|
508
|
+
loaders.append(jinja2.PrefixLoader({"_report": jinja2.FileSystemLoader(str(HERE))}))
|
|
509
|
+
environment = jinja2.Environment(
|
|
510
|
+
loader=jinja2.ChoiceLoader(loaders),
|
|
511
|
+
autoescape=jinja2.select_autoescape(["html", "j2"]),
|
|
512
|
+
trim_blocks=True,
|
|
513
|
+
lstrip_blocks=True,
|
|
514
|
+
undefined=jinja2.StrictUndefined,
|
|
515
|
+
)
|
|
516
|
+
environment.filters["value"] = lambda value, key="": format_value(key, value)
|
|
517
|
+
return environment
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def write_html(report, path, tool, *, figures=None, links=None, inputs=None, **context):
|
|
521
|
+
"""Write the page at path, from tool.template, which extends the kit's
|
|
522
|
+
base.html.j2, or from the base alone.
|
|
523
|
+
|
|
524
|
+
Parameters
|
|
525
|
+
----------
|
|
526
|
+
figures : dict
|
|
527
|
+
The plots, by the id of their place in the page: Plotly figures
|
|
528
|
+
(data and layout), which plotly.js draws once the page has loaded it.
|
|
529
|
+
A colour a figure leaves out follows the page's palette, light or
|
|
530
|
+
dark.
|
|
531
|
+
links : dict
|
|
532
|
+
The run's outputs that the page links to, by whatever the tool's
|
|
533
|
+
template reads; the page's Files section lists links["files"], paths
|
|
534
|
+
relative to the page. By default, the report's other two files, when
|
|
535
|
+
they are beside the page.
|
|
536
|
+
inputs : dict
|
|
537
|
+
What the run read, as the page's header names it: label, then value
|
|
538
|
+
({"Map": "out/sample.metacool"}).
|
|
539
|
+
**context
|
|
540
|
+
Anything else the tool's template reads.
|
|
541
|
+
"""
|
|
542
|
+
clash = _KIT_CONTEXT & set(context)
|
|
543
|
+
if clash:
|
|
544
|
+
raise TypeError(
|
|
545
|
+
f"write_html's context cannot set {', '.join(sorted(clash))}: the page's template reads them already"
|
|
546
|
+
)
|
|
547
|
+
from markupsafe import Markup
|
|
548
|
+
|
|
549
|
+
if links is None:
|
|
550
|
+
here = os.path.dirname(os.path.abspath(path))
|
|
551
|
+
txt, _, mqc = report_files(report.sample)
|
|
552
|
+
links = {
|
|
553
|
+
"files": [
|
|
554
|
+
name for name in (txt, mqc) if os.path.exists(os.path.join(here, name))
|
|
555
|
+
]
|
|
556
|
+
}
|
|
557
|
+
environment = _environment(tool)
|
|
558
|
+
template = environment.get_template(
|
|
559
|
+
os.path.basename(tool.template)
|
|
560
|
+
if tool.template is not None
|
|
561
|
+
else "_report/base.html.j2"
|
|
562
|
+
)
|
|
563
|
+
page = template.render(
|
|
564
|
+
tool=tool,
|
|
565
|
+
report=report.sections,
|
|
566
|
+
sample=report.sample,
|
|
567
|
+
tables={
|
|
568
|
+
name: json_ready(table.to_dict(orient="records"))
|
|
569
|
+
for name, table in report.tables.items()
|
|
570
|
+
},
|
|
571
|
+
columns={
|
|
572
|
+
name: [str(column) for column in table.columns]
|
|
573
|
+
for name, table in report.tables.items()
|
|
574
|
+
},
|
|
575
|
+
figures=json_ready(figures or {}),
|
|
576
|
+
links=links,
|
|
577
|
+
inputs=dict(inputs or {}),
|
|
578
|
+
key_numbers=key_numbers(report, tool),
|
|
579
|
+
plotly_js=PLOTLY_JS,
|
|
580
|
+
format_version=tool.format_version,
|
|
581
|
+
kit_css=Markup((HERE / "report.css").read_text(encoding="utf-8")),
|
|
582
|
+
kit_js=Markup((HERE / "report.js").read_text(encoding="utf-8")),
|
|
583
|
+
**context,
|
|
584
|
+
)
|
|
585
|
+
with open(path, "w", encoding="utf-8", newline="\n") as handle:
|
|
586
|
+
handle.write(page)
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def write_report(
|
|
590
|
+
report, outdir, tool, *, figures=None, links=None, inputs=None, **context
|
|
591
|
+
):
|
|
592
|
+
"""Write the report of a run in outdir, named after its sample (see
|
|
593
|
+
report_files): report.txt, report_mqc.yaml, then the page, which links to
|
|
594
|
+
the other two (see write_html for figures, links, inputs and context).
|
|
595
|
+
They replace files of their names; a symbolic link of their name is
|
|
596
|
+
removed, never written through.
|
|
597
|
+
|
|
598
|
+
Returns
|
|
599
|
+
-------
|
|
600
|
+
list of str
|
|
601
|
+
Their paths, in the order of REPORT_FILES."""
|
|
602
|
+
os.makedirs(outdir, exist_ok=True)
|
|
603
|
+
paths = [os.path.join(outdir, name) for name in report_files(report.sample)]
|
|
604
|
+
for path in paths:
|
|
605
|
+
if os.path.islink(path):
|
|
606
|
+
os.remove(path)
|
|
607
|
+
txt, html, mqc = paths
|
|
608
|
+
write_txt(report, txt, tool)
|
|
609
|
+
write_mqc(report, mqc, tool)
|
|
610
|
+
write_html(
|
|
611
|
+
report, html, tool, figures=figures, links=links, inputs=inputs, **context
|
|
612
|
+
)
|
|
613
|
+
return paths
|