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 ADDED
@@ -0,0 +1,11 @@
1
+ """plexembler: genome references for every species of a pool.
2
+
3
+ The Python side of the pipeline: the commands its steps run on their data
4
+ (``plexembler <command>``), each tested in-process, and the report of a run.
5
+ """
6
+
7
+ from importlib.metadata import version
8
+
9
+ __version__ = version("plexembler")
10
+
11
+ __all__ = ["__version__"]
plexembler/_log.py ADDED
@@ -0,0 +1,167 @@
1
+ """The log of a command, beside its outputs (CONVENTIONS.md § 11).
2
+
3
+ Every command that writes outputs writes ``<sample>.plexembler_<YYYYMMDDHHMMSS>.log``
4
+ in the directory of its outputs, headed as hicstuff's logs are: the version,
5
+ the date, the command line, one line per parameter, then ``---``. Then one line
6
+ per record, and a last line that says what the run wrote and how long it took.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import sys
13
+ import time
14
+ from collections.abc import Generator, Mapping
15
+ from contextlib import contextmanager
16
+ from datetime import datetime
17
+ from pathlib import Path
18
+
19
+ from . import __version__
20
+
21
+ #: The logger of every module of the package; only the command line configures it.
22
+ LOGGER_NAME = "plexembler"
23
+ #: The format of a record, in the file and on stderr.
24
+ RECORD_FORMAT = "%(asctime)s :: %(levelname)s :: %(message)s"
25
+ #: The format of a record's date.
26
+ DATE_FORMAT = "%Y-%m-%d,%H:%M:%S"
27
+
28
+ logger = logging.getLogger(LOGGER_NAME)
29
+
30
+
31
+ def log_file_name(outdir: Path, sample: str | None, started: datetime) -> Path:
32
+ """The log's path: ``<sample>.plexembler_<YYYYMMDDHHMMSS>.log`` in ``outdir``.
33
+
34
+ Parameters
35
+ ----------
36
+ outdir
37
+ The directory of the command's outputs.
38
+ sample
39
+ The run's name (its ``-p/--prefix``), or None for a command without one.
40
+ started
41
+ When the command started, in local time.
42
+
43
+ Returns
44
+ -------
45
+ Path
46
+ The log's path; ``plexembler_<YYYYMMDDHHMMSS>.log`` without a sample.
47
+ """
48
+ stamp = started.strftime("%Y%m%d%H%M%S")
49
+ name = f"{sample}.plexembler_{stamp}.log" if sample else f"plexembler_{stamp}.log"
50
+ return Path(outdir) / name
51
+
52
+
53
+ def log_header(
54
+ started: datetime, command: str, parameters: Mapping[str, object]
55
+ ) -> str:
56
+ """The log's header, as hicstuff writes it.
57
+
58
+ Parameters
59
+ ----------
60
+ started
61
+ When the command started, in local time.
62
+ command
63
+ The command line, as it was typed.
64
+ parameters
65
+ Every parameter of the command, as given or by default.
66
+
67
+ Returns
68
+ -------
69
+ str
70
+ The header's lines, the last one ``---``.
71
+ """
72
+ lines = [
73
+ f"## plexembler: v{__version__} log file",
74
+ f"## date: {started:%Y-%m-%d %H:%M:%S}",
75
+ f"## cmd: {command}",
76
+ ]
77
+ lines += [f"## {key}: {value}" for key, value in parameters.items()]
78
+ lines.append("---")
79
+ return "\n".join(lines) + "\n"
80
+
81
+
82
+ def elapsed(seconds: float) -> str:
83
+ """A duration as the log's last line gives it: ``0h 17m 31s``."""
84
+ minutes, secs = divmod(round(seconds), 60)
85
+ hours, minutes = divmod(minutes, 60)
86
+ return f"{hours}h {minutes}m {secs}s"
87
+
88
+
89
+ @contextmanager
90
+ def stderr_log() -> Generator[None]:
91
+ """Log a command's run to stderr alone, INFO and above, for as long as it runs.
92
+
93
+ For a command that writes no log file (CONVENTIONS.md § 11), such as
94
+ ``plexembler run``, whose run Nextflow logs.
95
+ """
96
+ handler = logging.StreamHandler(sys.stderr)
97
+ handler.setFormatter(logging.Formatter(RECORD_FORMAT, datefmt=DATE_FORMAT))
98
+ handler.setLevel(logging.INFO)
99
+ previous_level = logger.level
100
+ logger.addHandler(handler)
101
+ logger.setLevel(logging.INFO)
102
+ try:
103
+ yield
104
+ finally:
105
+ logger.removeHandler(handler)
106
+ handler.close()
107
+ logger.setLevel(previous_level)
108
+
109
+
110
+ @contextmanager
111
+ def run_log(
112
+ outdir: Path,
113
+ sample: str | None,
114
+ parameters: Mapping[str, object],
115
+ *,
116
+ verbose: bool = False,
117
+ quiet: bool = False,
118
+ ) -> Generator[Path]:
119
+ """Log a command's run to stderr and to its log file, for as long as it runs.
120
+
121
+ The file always gets INFO and above; ``verbose`` adds DEBUG, to the file and
122
+ to stderr; ``quiet`` limits stderr to warnings, never the file.
123
+
124
+ Parameters
125
+ ----------
126
+ outdir
127
+ The directory of the command's outputs, where the log goes.
128
+ sample
129
+ The run's name, which names the log.
130
+ parameters
131
+ Every parameter of the command, for the header.
132
+ verbose, quiet
133
+ The command's ``-v/--verbose`` and ``-q/--quiet``.
134
+
135
+ Yields
136
+ ------
137
+ Path
138
+ The log's path.
139
+ """
140
+ started = datetime.now()
141
+ clock = time.monotonic()
142
+ path = log_file_name(outdir, sample, started)
143
+ path.parent.mkdir(parents=True, exist_ok=True)
144
+ path.write_text(
145
+ log_header(started, " ".join(sys.argv), parameters), encoding="utf-8"
146
+ )
147
+
148
+ formatter = logging.Formatter(RECORD_FORMAT, datefmt=DATE_FORMAT)
149
+ to_file = logging.FileHandler(path, mode="a", encoding="utf-8")
150
+ to_file.setLevel(logging.DEBUG if verbose else logging.INFO)
151
+ to_stderr = logging.StreamHandler(sys.stderr)
152
+ to_stderr.setLevel(
153
+ logging.DEBUG if verbose else logging.WARNING if quiet else logging.INFO
154
+ )
155
+ previous_level = logger.level
156
+ for handler in (to_file, to_stderr):
157
+ handler.setFormatter(formatter)
158
+ logger.addHandler(handler)
159
+ logger.setLevel(logging.DEBUG)
160
+ try:
161
+ yield path
162
+ logger.info("Done after %s", elapsed(time.monotonic() - clock))
163
+ finally:
164
+ for handler in (to_file, to_stderr):
165
+ logger.removeHandler(handler)
166
+ handler.close()
167
+ logger.setLevel(previous_level)