transcript.md 0.1.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.
- transcript/__init__.py +35 -0
- transcript/_rule/__init__.py +0 -0
- transcript/_rule/archive.py +128 -0
- transcript/_rule/conda.py +52 -0
- transcript/_rule/container.py +290 -0
- transcript/_rule/core.py +524 -0
- transcript/_rule/lambdas.py +120 -0
- transcript/_rule/registry.py +54 -0
- transcript/_rule/serialize.py +26 -0
- transcript/_rule/snakefile.py +81 -0
- transcript/_rule/wildcards.py +110 -0
- transcript/cli.py +363 -0
- transcript/document.py +56 -0
- transcript/execute.py +240 -0
- transcript/html/__init__.py +17 -0
- transcript/html/_assets/.frontend.sha256 +1 -0
- transcript/html/_assets/__init__.py +21 -0
- transcript/html/_assets/style.min.css +1 -0
- transcript/html/_assets/transcript.min.js +21 -0
- transcript/html/_island.py +72 -0
- transcript/html/_navigate.py +198 -0
- transcript/html/_output.py +100 -0
- transcript/html/_resources.py +171 -0
- transcript/html/_review.py +34 -0
- transcript/html/markup.py +26 -0
- transcript/html/page.py +107 -0
- transcript/output.py +308 -0
- transcript/parse.py +256 -0
- transcript/renderers/__init__.py +126 -0
- transcript/renderers/bitmap.py +166 -0
- transcript/renderers/compose.py +174 -0
- transcript/renderers/compose_runtime.js +233 -0
- transcript/renderers/datavzrd.py +321 -0
- transcript/renderers/datavzrd_runtime.js +362 -0
- transcript/renderers/label.py +211 -0
- transcript/renderers/markdown.py +45 -0
- transcript/renderers/table.py +32 -0
- transcript/renderers/vegalite.py +250 -0
- transcript/review/__init__.py +13 -0
- transcript/review/_block.py +167 -0
- transcript/review/_migrate.py +212 -0
- transcript/review/_records.py +238 -0
- transcript/review/_span.py +287 -0
- transcript/review/load.py +64 -0
- transcript/tmd.py +159 -0
- transcript_md-0.1.0.dist-info/METADATA +17 -0
- transcript_md-0.1.0.dist-info/RECORD +49 -0
- transcript_md-0.1.0.dist-info/WHEEL +4 -0
- transcript_md-0.1.0.dist-info/entry_points.txt +2 -0
transcript/_rule/core.py
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
"""Declare the Snakemake rule interface of a document.
|
|
2
|
+
|
|
3
|
+
A document declares one rule with ``with transcript.rule() as r:`` and then
|
|
4
|
+
assigns or calls ``r.input`` / ``r.output`` / ``r.log`` / ``r.params``. The
|
|
5
|
+
containers are a small declaration collector, not Snakemake's ``Namedlist``:
|
|
6
|
+
their semantics differ (declaration, validation, and wildcard resolution on
|
|
7
|
+
read). Declarations are collected while the document runs;
|
|
8
|
+
:mod:`transcript._rule.archive` writes them back into a canonical ``# transcript:rule``
|
|
9
|
+
block.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import ast
|
|
15
|
+
import math
|
|
16
|
+
import sys
|
|
17
|
+
from collections.abc import Callable
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from snakemake.exceptions import WorkflowError
|
|
21
|
+
from snakemake.io import apply_wildcards, get_wildcard_names
|
|
22
|
+
from snakemake.resources import Resources
|
|
23
|
+
|
|
24
|
+
try: # Snakemake >= 9.16
|
|
25
|
+
from snakemake.iocontainers import Namedlist, Wildcards
|
|
26
|
+
except ImportError: # Snakemake 9.x before the module split
|
|
27
|
+
from snakemake.io import Namedlist, Wildcards # type: ignore
|
|
28
|
+
|
|
29
|
+
from . import archive, registry, snakefile
|
|
30
|
+
from .conda import Conda
|
|
31
|
+
from .container import _MISSING, DeclaredList, _WildcardsView
|
|
32
|
+
from .lambdas import _StaticLambda
|
|
33
|
+
from .wildcards import WildcardState, _iter_str, _match_wildcards, _placeholderize
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _is_document_target(path: str):
|
|
37
|
+
"""Whether *path* names an archive (``.tmd.py``) or an HTML report."""
|
|
38
|
+
return path.endswith(".tmd.py") or Path(path).suffix == ".html"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Rule:
|
|
42
|
+
"""One document's Snakemake interface."""
|
|
43
|
+
|
|
44
|
+
def __init__(self, name: str | None = None):
|
|
45
|
+
if name is not None and not (isinstance(name, str) and name.isidentifier()):
|
|
46
|
+
raise WorkflowError(f"invalid rule name: {name!r}")
|
|
47
|
+
self._name = name
|
|
48
|
+
self._input = DeclaredList(self, "input")
|
|
49
|
+
self._output = DeclaredList(self, "output")
|
|
50
|
+
self._log = DeclaredList(self, "log")
|
|
51
|
+
self._params = DeclaredList(self, "params", is_path=False)
|
|
52
|
+
self._threads: int | None = None
|
|
53
|
+
self._resources: dict[str, int | float | str] = {}
|
|
54
|
+
self._conda: Conda | None = None
|
|
55
|
+
self._wildcard_state = WildcardState(registry.wildcards())
|
|
56
|
+
self._wildcards_view = _WildcardsView(self)
|
|
57
|
+
self._filename: str | None = getattr(
|
|
58
|
+
sys.modules.get("__main__"), "__file__", None
|
|
59
|
+
)
|
|
60
|
+
self._lambdas: dict[tuple[int, int], ast.Lambda] | None = None
|
|
61
|
+
self.edit: tuple[tuple[int, int], str | None] | None = None
|
|
62
|
+
self.target: str | None = None
|
|
63
|
+
self.with_declare: bool | None = None
|
|
64
|
+
"""``None`` before entering, ``True`` while inside, ``False`` after."""
|
|
65
|
+
|
|
66
|
+
def __enter__(self):
|
|
67
|
+
if self.with_declare is not None:
|
|
68
|
+
raise WorkflowError("a rule context can only be entered once")
|
|
69
|
+
self.with_declare = True
|
|
70
|
+
return self
|
|
71
|
+
|
|
72
|
+
def __exit__(self, *exc):
|
|
73
|
+
self.with_declare = False
|
|
74
|
+
self._lambdas = None
|
|
75
|
+
if exc[0] is None:
|
|
76
|
+
self._check_wildcards()
|
|
77
|
+
return False
|
|
78
|
+
|
|
79
|
+
def set_lambdas(self, node: ast.With):
|
|
80
|
+
"""Index the block's lambda nodes by body position for source recovery."""
|
|
81
|
+
self._lambdas = {
|
|
82
|
+
(child.body.lineno, child.body.col_offset): child
|
|
83
|
+
for statement in node.body
|
|
84
|
+
for child in ast.walk(statement)
|
|
85
|
+
if isinstance(child, ast.Lambda)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
def _declare_lambda(self, kind: str, value: Callable):
|
|
89
|
+
"""Wrap a declared callable, keeping the block-only rule for documents."""
|
|
90
|
+
if not registry.executing():
|
|
91
|
+
return _StaticLambda.from_runtime(self._LAMBDA_AUX[kind], value)
|
|
92
|
+
node = self._lambda_node(value)
|
|
93
|
+
if node is None:
|
|
94
|
+
raise WorkflowError(f"{kind} lambda must be declared inside the rule block")
|
|
95
|
+
return _StaticLambda.from_node(self._LAMBDA_AUX[kind], node, value)
|
|
96
|
+
|
|
97
|
+
def _lambda_node(self, value: Callable):
|
|
98
|
+
"""Return the source AST node of a lambda declared in the block."""
|
|
99
|
+
nodes = self._lambdas
|
|
100
|
+
if nodes is None or not hasattr(value, "__code__"):
|
|
101
|
+
return None
|
|
102
|
+
code = value.__code__
|
|
103
|
+
if code.co_filename != self._filename or code.co_name != "<lambda>":
|
|
104
|
+
return None
|
|
105
|
+
positions = {
|
|
106
|
+
(line, column)
|
|
107
|
+
for line, _, column, _ in code.co_positions()
|
|
108
|
+
if line is not None and column is not None
|
|
109
|
+
}
|
|
110
|
+
matches = [node for position, node in nodes.items() if position in positions]
|
|
111
|
+
return matches[0] if len(matches) == 1 else None
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def name(self):
|
|
115
|
+
return self._name
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def input(self):
|
|
119
|
+
return self._input
|
|
120
|
+
|
|
121
|
+
@property
|
|
122
|
+
def output(self):
|
|
123
|
+
return self._output
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def log(self):
|
|
127
|
+
return self._log
|
|
128
|
+
|
|
129
|
+
@property
|
|
130
|
+
def params(self):
|
|
131
|
+
return self._params
|
|
132
|
+
|
|
133
|
+
@property
|
|
134
|
+
def threads(self):
|
|
135
|
+
"""The rule's default thread request (1 when undeclared)."""
|
|
136
|
+
return self._threads or 1
|
|
137
|
+
|
|
138
|
+
@threads.setter
|
|
139
|
+
def threads(self, value: int):
|
|
140
|
+
"""Declare the rule's default thread request (idempotent)."""
|
|
141
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
|
|
142
|
+
raise WorkflowError("threads must be a positive integer")
|
|
143
|
+
if self._threads is None:
|
|
144
|
+
self._threads = value
|
|
145
|
+
elif self._threads != value:
|
|
146
|
+
raise WorkflowError(f"threads is already declared as {self._threads}")
|
|
147
|
+
|
|
148
|
+
def resources(self, **values: int | float | str):
|
|
149
|
+
"""Merge static default resource requests into this rule.
|
|
150
|
+
|
|
151
|
+
This is different from params/input/output/log,
|
|
152
|
+
because it should not set as casual as those in the script.
|
|
153
|
+
"""
|
|
154
|
+
for name, value in values.items():
|
|
155
|
+
if not name.isidentifier():
|
|
156
|
+
raise WorkflowError(f"invalid resource name: {name!r}")
|
|
157
|
+
if name in {"_cores", "_nodes"}:
|
|
158
|
+
raise WorkflowError(f"resource {name!r} is managed by Snakemake")
|
|
159
|
+
if (
|
|
160
|
+
isinstance(value, bool)
|
|
161
|
+
or not isinstance(value, (int, float, str))
|
|
162
|
+
or isinstance(value, (int, float))
|
|
163
|
+
and (value < 0 or not math.isfinite(value))
|
|
164
|
+
):
|
|
165
|
+
raise WorkflowError(
|
|
166
|
+
f"resource {name!r} must be a non-negative number or string"
|
|
167
|
+
)
|
|
168
|
+
if name in self._resources and self._resources[name] != value:
|
|
169
|
+
raise WorkflowError(
|
|
170
|
+
f"resource {name!r} is already declared as "
|
|
171
|
+
f"{self._resources[name]!r}"
|
|
172
|
+
)
|
|
173
|
+
merged = self._resources | values
|
|
174
|
+
try:
|
|
175
|
+
Resources.from_mapping(merged)
|
|
176
|
+
except (TypeError, ValueError, WorkflowError) as exc:
|
|
177
|
+
raise WorkflowError(str(exc)) from exc
|
|
178
|
+
self._resources.update(values)
|
|
179
|
+
return dict(self._resources)
|
|
180
|
+
|
|
181
|
+
def conda(self, dependencies=(), *, pip=(), channels=("conda-forge",)):
|
|
182
|
+
"""Declare the conda environment once: channels, dependencies and pip."""
|
|
183
|
+
if self._conda is not None:
|
|
184
|
+
raise WorkflowError("conda is already declared")
|
|
185
|
+
self._conda = Conda(dependencies, pip=pip, channels=channels)
|
|
186
|
+
return self._conda
|
|
187
|
+
|
|
188
|
+
@property
|
|
189
|
+
def wildcards(self):
|
|
190
|
+
"""Call to declare defaults; read attributes for effective values."""
|
|
191
|
+
return self._wildcards_view
|
|
192
|
+
|
|
193
|
+
def _declare_wildcards(self, **defaults: str):
|
|
194
|
+
"""Record the interactive defaults; declare only one distinct set.
|
|
195
|
+
|
|
196
|
+
Declaring defaults is the one sanctioned point where already-collected
|
|
197
|
+
out-of-block literals may be upgraded to patterns: a new default value
|
|
198
|
+
turns a matching literal into its pattern. A default that contradicts an
|
|
199
|
+
inferred value is an error.
|
|
200
|
+
"""
|
|
201
|
+
for value in defaults.values():
|
|
202
|
+
if not isinstance(value, str):
|
|
203
|
+
raise WorkflowError("wildcard defaults must be strings")
|
|
204
|
+
candidate = dict(defaults)
|
|
205
|
+
if self._wildcard_state.defaults is None:
|
|
206
|
+
pass
|
|
207
|
+
elif self._wildcard_state.defaults == candidate:
|
|
208
|
+
return self._wildcard_state.defaults
|
|
209
|
+
else:
|
|
210
|
+
raise WorkflowError("wildcards can only be declared once")
|
|
211
|
+
containers = (self._input, self._output, self._log, self._params)
|
|
212
|
+
snapshot = (
|
|
213
|
+
dict(self._wildcard_state.inferred),
|
|
214
|
+
self._wildcard_state.defaults,
|
|
215
|
+
[list(c._later) for c in containers],
|
|
216
|
+
)
|
|
217
|
+
try:
|
|
218
|
+
declared = self._declared_wildcards()
|
|
219
|
+
for name, value in candidate.items():
|
|
220
|
+
if name in declared and declared[name] != value:
|
|
221
|
+
raise WorkflowError(
|
|
222
|
+
f"wildcard {name!r} is {declared[name]!r}, not {value!r}"
|
|
223
|
+
)
|
|
224
|
+
self._wildcard_state.defaults = candidate
|
|
225
|
+
self._apply_declared_defaults()
|
|
226
|
+
except BaseException:
|
|
227
|
+
(
|
|
228
|
+
self._wildcard_state.inferred,
|
|
229
|
+
self._wildcard_state.defaults,
|
|
230
|
+
) = (snapshot[0], snapshot[1])
|
|
231
|
+
for container, saved in zip(containers, snapshot[2]):
|
|
232
|
+
container._later = saved
|
|
233
|
+
raise
|
|
234
|
+
return self._wildcard_state.defaults
|
|
235
|
+
|
|
236
|
+
def resolve(self, pattern: str, override: dict[str, str] | None = None):
|
|
237
|
+
"""Substitute the effective wildcards into a declared path pattern."""
|
|
238
|
+
return apply_wildcards(pattern, self._effective_wildcards(override))
|
|
239
|
+
|
|
240
|
+
def _resolved_paths(self, container: DeclaredList):
|
|
241
|
+
resolved = Namedlist()
|
|
242
|
+
for name, value in container._raw_items():
|
|
243
|
+
start = len(resolved)
|
|
244
|
+
item = container._resolve(value)
|
|
245
|
+
if isinstance(item, list):
|
|
246
|
+
resolved.extend(str(path) for path in item)
|
|
247
|
+
else:
|
|
248
|
+
resolved.append(str(item))
|
|
249
|
+
if name:
|
|
250
|
+
resolved._set_name(
|
|
251
|
+
name, start, end=len(resolved) if isinstance(item, list) else None
|
|
252
|
+
)
|
|
253
|
+
return resolved
|
|
254
|
+
|
|
255
|
+
def _evaluate_function(self, value: _StaticLambda, context: dict[str, Callable]):
|
|
256
|
+
"""Apply Snakemake's recursive callable convention in local execution."""
|
|
257
|
+
wildcards = Wildcards(fromdict=self._effective_wildcards())
|
|
258
|
+
return value.evaluate(wildcards, context)
|
|
259
|
+
|
|
260
|
+
def _run_input_lambda(self, value: _StaticLambda):
|
|
261
|
+
result = self._evaluate_function(value, {})
|
|
262
|
+
scalar = isinstance(result, (str, Path))
|
|
263
|
+
if scalar:
|
|
264
|
+
items = [result]
|
|
265
|
+
else:
|
|
266
|
+
try:
|
|
267
|
+
items = list(result)
|
|
268
|
+
except TypeError as exc:
|
|
269
|
+
raise WorkflowError(
|
|
270
|
+
"input lambda must return a path or an iterable of paths"
|
|
271
|
+
) from exc
|
|
272
|
+
if not all(isinstance(item, (str, Path)) for item in items):
|
|
273
|
+
raise WorkflowError(
|
|
274
|
+
"input lambda must return a path or an iterable of paths"
|
|
275
|
+
)
|
|
276
|
+
paths = [Path(self.resolve(str(item))) for item in items]
|
|
277
|
+
return paths[0] if scalar else paths
|
|
278
|
+
|
|
279
|
+
def _run_param_lambda(self, value: _StaticLambda):
|
|
280
|
+
"""Evaluate a params lambda with the context Snakemake makes available."""
|
|
281
|
+
return self._evaluate_function(
|
|
282
|
+
value,
|
|
283
|
+
{
|
|
284
|
+
"input": lambda: self._resolved_paths(self._input),
|
|
285
|
+
"output": lambda: self._resolved_paths(self._output),
|
|
286
|
+
"log": lambda: self._resolved_paths(self._log),
|
|
287
|
+
"threads": lambda: self._threads,
|
|
288
|
+
"resources": lambda: self._resources,
|
|
289
|
+
},
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
def _declared_wildcards(self):
|
|
293
|
+
"""Script-side wildcard values: inferred captures plus declared defaults."""
|
|
294
|
+
return self._wildcard_state.declared()
|
|
295
|
+
|
|
296
|
+
def _effective_wildcards(self, override: dict[str, str] | None = None):
|
|
297
|
+
"""Runtime wildcard values: declared, then the job's, then *override*.
|
|
298
|
+
|
|
299
|
+
The rule captures the job wildcards of the execution that created it
|
|
300
|
+
(the ``--wildcards`` values passed to ``execute``). Callers outside that
|
|
301
|
+
execution, such as the CLI after ``execute`` returns, read them back from
|
|
302
|
+
the rule instead of re-supplying ``--wildcards``.
|
|
303
|
+
"""
|
|
304
|
+
return self._wildcard_state.effective(override)
|
|
305
|
+
|
|
306
|
+
def _placeholderize(
|
|
307
|
+
self, container: DeclaredList, value, *, record=True, name=None
|
|
308
|
+
):
|
|
309
|
+
"""Infer a wildcard pattern for a concrete out-of-block *value*.
|
|
310
|
+
|
|
311
|
+
Only the value's own list is searched, and only script-side wildcard
|
|
312
|
+
values take part; CLI overrides never affect inference. A named
|
|
313
|
+
input/params entry is an independent slot: when its capture would
|
|
314
|
+
contradict a declared value, the value is kept as a literal instead of
|
|
315
|
+
rejecting the assignment. Positional entries and output/log stay
|
|
316
|
+
strict, because they define the list's wildcard space.
|
|
317
|
+
"""
|
|
318
|
+
if not isinstance(value, str) or get_wildcard_names(value):
|
|
319
|
+
return value
|
|
320
|
+
lenient = name is not None and container._kind not in ("output", "log")
|
|
321
|
+
declared = self._declared_wildcards()
|
|
322
|
+
for _, stored in container._raw_items():
|
|
323
|
+
for pattern in _iter_str(stored):
|
|
324
|
+
captured = _match_wildcards(pattern, value)
|
|
325
|
+
if captured is None:
|
|
326
|
+
continue
|
|
327
|
+
conflict = self._wildcard_state.conflict(captured)
|
|
328
|
+
if conflict:
|
|
329
|
+
if lenient:
|
|
330
|
+
continue
|
|
331
|
+
key, captured_value = conflict
|
|
332
|
+
if record:
|
|
333
|
+
raise WorkflowError(
|
|
334
|
+
f"wildcard {key!r} is {declared[key]!r},"
|
|
335
|
+
f" not {captured_value!r}"
|
|
336
|
+
)
|
|
337
|
+
if record:
|
|
338
|
+
self._wildcard_state.inferred.update(captured)
|
|
339
|
+
return pattern
|
|
340
|
+
return _placeholderize(value, declared)
|
|
341
|
+
|
|
342
|
+
def _infer_value(self, container: DeclaredList, value, *, record=True, name=None):
|
|
343
|
+
"""Infer patterns for an out-of-block declaration value."""
|
|
344
|
+
if not container._is_path and isinstance(value, list):
|
|
345
|
+
return [
|
|
346
|
+
(
|
|
347
|
+
self._placeholderize(container, item, record=record, name=name)
|
|
348
|
+
if isinstance(item, str)
|
|
349
|
+
else item
|
|
350
|
+
)
|
|
351
|
+
for item in value
|
|
352
|
+
]
|
|
353
|
+
return self._placeholderize(container, value, record=record, name=name)
|
|
354
|
+
|
|
355
|
+
def _check_resolve(self, value):
|
|
356
|
+
"""Reject an out-of-block value that the effective wildcards cannot resolve."""
|
|
357
|
+
for pattern in _iter_str(value):
|
|
358
|
+
apply_wildcards(pattern, self._effective_wildcards())
|
|
359
|
+
|
|
360
|
+
def _check_stable_inference(self, container: DeclaredList | None = None):
|
|
361
|
+
"""Reject an out-of-block value that a later declaration would rewrite.
|
|
362
|
+
|
|
363
|
+
Inference is fixed at declaration time. A new same-list pattern (or a
|
|
364
|
+
new default) that would change an already-accepted literal is ambiguous,
|
|
365
|
+
so it is reported instead of silently rewriting history.
|
|
366
|
+
"""
|
|
367
|
+
if container is None:
|
|
368
|
+
containers = [self._input, self._output, self._log, self._params]
|
|
369
|
+
else:
|
|
370
|
+
containers = [container]
|
|
371
|
+
for current in containers:
|
|
372
|
+
for name, stored in current._later:
|
|
373
|
+
if isinstance(stored, _StaticLambda):
|
|
374
|
+
continue
|
|
375
|
+
fresh = self._infer_value(current, stored, record=False, name=name)
|
|
376
|
+
if fresh != stored:
|
|
377
|
+
raise WorkflowError(
|
|
378
|
+
f"{current._kind} value {stored!r} was declared before the "
|
|
379
|
+
f"matching pattern {fresh!r}; declare the pattern first, or "
|
|
380
|
+
"put the literal inside the rule block to keep it fixed"
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
def _apply_declared_defaults(self):
|
|
384
|
+
"""Upgrade out-of-block literals now that new default values are known."""
|
|
385
|
+
containers = (self._input, self._output, self._log, self._params)
|
|
386
|
+
for container in containers:
|
|
387
|
+
container._later = [
|
|
388
|
+
(name, self._infer_value(container, value, name=name))
|
|
389
|
+
for name, value in container._later
|
|
390
|
+
]
|
|
391
|
+
self._check_wildcards()
|
|
392
|
+
for container in containers:
|
|
393
|
+
for _, value in container._later:
|
|
394
|
+
self._check_resolve(value)
|
|
395
|
+
|
|
396
|
+
def _add_out_of_block(self, container: DeclaredList, name: str | None, value):
|
|
397
|
+
"""Infer, validate, and only then commit an out-of-block declaration."""
|
|
398
|
+
if name == "document" and container._kind not in ("input", "params"):
|
|
399
|
+
raise WorkflowError("document can only be declared inside the rule block")
|
|
400
|
+
snapshot = (dict(self._wildcard_state.inferred), list(container._later))
|
|
401
|
+
try:
|
|
402
|
+
value = self._infer_value(container, value, name=name)
|
|
403
|
+
is_new = (
|
|
404
|
+
container._new_kwarg(name, value)
|
|
405
|
+
if name is not None
|
|
406
|
+
else container._new_narg(value)
|
|
407
|
+
)
|
|
408
|
+
if is_new:
|
|
409
|
+
container._later.append((name, value))
|
|
410
|
+
self._check_stable_inference(container)
|
|
411
|
+
self._check_resolve(value)
|
|
412
|
+
self._check_wildcards()
|
|
413
|
+
return value
|
|
414
|
+
except BaseException:
|
|
415
|
+
self._wildcard_state.inferred, container._later = snapshot
|
|
416
|
+
raise
|
|
417
|
+
|
|
418
|
+
def make_rule_block(self, TAB=" "):
|
|
419
|
+
return archive.make_rule_block(self, TAB)
|
|
420
|
+
|
|
421
|
+
@classmethod
|
|
422
|
+
def from_tmd(cls, source: str, filename=None):
|
|
423
|
+
"""Rebuild a rule from its canonical ``# transcript:rule`` block."""
|
|
424
|
+
return archive.from_tmd(cls, source, filename)
|
|
425
|
+
|
|
426
|
+
_LAMBDA_AUX = {
|
|
427
|
+
"input": frozenset(),
|
|
428
|
+
"params": frozenset({"input", "output", "log", "threads", "resources"}),
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
def wildcard_names(self):
|
|
432
|
+
"""Return the wildcard names shared by the output and log patterns."""
|
|
433
|
+
return self._output._all_wildcards() | self._log._all_wildcards()
|
|
434
|
+
|
|
435
|
+
def _check_wildcards(self, containers=None):
|
|
436
|
+
"""Output/log patterns share one wildcard set; input may use a subset.
|
|
437
|
+
|
|
438
|
+
*containers* limits the input/params subset check to those containers
|
|
439
|
+
(incremental use); the default checks every container.
|
|
440
|
+
"""
|
|
441
|
+
patterns = [
|
|
442
|
+
(container._kind, name, get_wildcard_names(pattern))
|
|
443
|
+
for container in (self._output, self._log)
|
|
444
|
+
for name, pattern in container._raw_items()
|
|
445
|
+
]
|
|
446
|
+
if not patterns:
|
|
447
|
+
return
|
|
448
|
+
defined = patterns[0][2]
|
|
449
|
+
for kind, name, names in patterns:
|
|
450
|
+
if names != defined:
|
|
451
|
+
raise WorkflowError(
|
|
452
|
+
f"{kind} {name or 'entry'} uses wildcards {sorted(names)}, "
|
|
453
|
+
f"but output/log share {sorted(defined)}"
|
|
454
|
+
)
|
|
455
|
+
scope = (self._input, self._params) if containers is None else containers
|
|
456
|
+
unknown = set()
|
|
457
|
+
for container in scope:
|
|
458
|
+
if container._kind not in ("output", "log"):
|
|
459
|
+
unknown |= container._all_wildcards()
|
|
460
|
+
unknown -= defined
|
|
461
|
+
if unknown:
|
|
462
|
+
raise WorkflowError(
|
|
463
|
+
"wildcards "
|
|
464
|
+
+ ", ".join(sorted(unknown))
|
|
465
|
+
+ " are used by input/params but not defined by output/log"
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
@property
|
|
469
|
+
def smk_target_document(self):
|
|
470
|
+
"""Return ``(kind, pattern)`` for the declared document, or ``None``."""
|
|
471
|
+
output_target = self._output._raw("document")
|
|
472
|
+
log_target = self._log._raw("document")
|
|
473
|
+
if output_target is _MISSING:
|
|
474
|
+
if log_target is _MISSING:
|
|
475
|
+
return
|
|
476
|
+
ret = "log", str(log_target)
|
|
477
|
+
elif log_target is _MISSING:
|
|
478
|
+
ret = "output", str(output_target)
|
|
479
|
+
else:
|
|
480
|
+
raise WorkflowError("document can only be declared in either output or log")
|
|
481
|
+
if not _is_document_target(ret[1]):
|
|
482
|
+
raise WorkflowError(
|
|
483
|
+
f"document target {ret[1]!r} must end in .tmd.py or .html"
|
|
484
|
+
)
|
|
485
|
+
return ret
|
|
486
|
+
|
|
487
|
+
@smk_target_document.setter
|
|
488
|
+
def smk_target_document(self, text: str):
|
|
489
|
+
"""Replace or drop the document declaration after execution.
|
|
490
|
+
|
|
491
|
+
Used by the CLI to reconcile the recorded document with ``-o``. This is
|
|
492
|
+
the only path allowed to change the declaration outside the rule block.
|
|
493
|
+
"""
|
|
494
|
+
pattern = _placeholderize(text, self._effective_wildcards())
|
|
495
|
+
if pattern == text:
|
|
496
|
+
pattern = None # a concrete -o cannot be recorded as a pattern
|
|
497
|
+
if pattern is not None and not _is_document_target(pattern):
|
|
498
|
+
raise WorkflowError(
|
|
499
|
+
f"document target {pattern!r} must end in .tmd.py or .html"
|
|
500
|
+
)
|
|
501
|
+
for container in (self._output, self._log):
|
|
502
|
+
if "document" in container:
|
|
503
|
+
container._remove_named("document")
|
|
504
|
+
if pattern is not None:
|
|
505
|
+
container._later.append(("document", pattern))
|
|
506
|
+
self._check_wildcards()
|
|
507
|
+
return
|
|
508
|
+
if pattern is not None:
|
|
509
|
+
self._output._later.append(("document", pattern))
|
|
510
|
+
self._check_wildcards()
|
|
511
|
+
|
|
512
|
+
def make_snakemake_rule(self, conda_path: Path | None = None, TAB=" "):
|
|
513
|
+
"""Return the Snakefile rule text for this declaration."""
|
|
514
|
+
return snakefile.make_snakemake_rule(self, conda_path, TAB)
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def rule(name: str | None = None):
|
|
518
|
+
"""Create and register the document's single rule."""
|
|
519
|
+
if registry.current() is not None:
|
|
520
|
+
raise WorkflowError("transcript.rule() can only be called once per document")
|
|
521
|
+
job = Rule(name)
|
|
522
|
+
if registry.executing():
|
|
523
|
+
registry.set_current(job)
|
|
524
|
+
return job
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Static validation and local evaluation of declared input/params lambdas."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import dis
|
|
7
|
+
import types
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
|
|
12
|
+
from snakemake.common import get_input_function_aux_params
|
|
13
|
+
from snakemake.exceptions import WorkflowError
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from snakemake.iocontainers import Wildcards
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class _StaticLambda:
|
|
21
|
+
source: str | None
|
|
22
|
+
aux: frozenset[str]
|
|
23
|
+
function: Callable | None = field(compare=False, repr=False)
|
|
24
|
+
|
|
25
|
+
def evaluate(self, wildcards: Wildcards, context: dict[str, Callable]):
|
|
26
|
+
"""Apply Snakemake's recursive callable convention in local execution."""
|
|
27
|
+
function = self.function
|
|
28
|
+
if function is None:
|
|
29
|
+
raise WorkflowError("a statically read lambda cannot be evaluated")
|
|
30
|
+
unavailable = self.aux - context.keys()
|
|
31
|
+
if unavailable:
|
|
32
|
+
raise WorkflowError(
|
|
33
|
+
"interactive lambda context does not provide: "
|
|
34
|
+
+ ", ".join(sorted(unavailable))
|
|
35
|
+
)
|
|
36
|
+
aux_params = {
|
|
37
|
+
name: resolve()
|
|
38
|
+
for name, resolve in get_input_function_aux_params(
|
|
39
|
+
function, context
|
|
40
|
+
).items()
|
|
41
|
+
}
|
|
42
|
+
result: Any = function
|
|
43
|
+
for _ in range(10):
|
|
44
|
+
if not callable(result):
|
|
45
|
+
return result
|
|
46
|
+
result = result(wildcards, **aux_params)
|
|
47
|
+
if isinstance(result, types.GeneratorType):
|
|
48
|
+
result = list(result)
|
|
49
|
+
raise WorkflowError("lambda returned a callable 10 times")
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def from_runtime(cls, cand_argnames: frozenset[str], function: Callable):
|
|
53
|
+
"""Retain a callable declared without a document AST index (REPL/plain run)."""
|
|
54
|
+
auxiliary = get_input_function_aux_params(
|
|
55
|
+
function, dict.fromkeys(cand_argnames)
|
|
56
|
+
).keys()
|
|
57
|
+
return cls(None, frozenset(auxiliary), function)
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def from_node(
|
|
61
|
+
cls,
|
|
62
|
+
cand_argnames: frozenset[str],
|
|
63
|
+
node: ast.Lambda,
|
|
64
|
+
function: Callable | None = None,
|
|
65
|
+
):
|
|
66
|
+
"""Validate and retain a self-contained Snakemake rule function."""
|
|
67
|
+
where = f"lambda on line {node.lineno}"
|
|
68
|
+
if any(isinstance(child, ast.NamedExpr) for child in ast.walk(node.body)):
|
|
69
|
+
raise WorkflowError(f"{where} cannot contain an assignment expression")
|
|
70
|
+
if any(isinstance(child, ast.Lambda) for child in ast.walk(node.body)):
|
|
71
|
+
raise WorkflowError(f"{where} cannot contain another lambda")
|
|
72
|
+
|
|
73
|
+
args = node.args
|
|
74
|
+
positional = [*args.posonlyargs, *args.args]
|
|
75
|
+
if not positional:
|
|
76
|
+
raise WorkflowError(
|
|
77
|
+
f"{where} must take wildcards as its first positional parameter"
|
|
78
|
+
)
|
|
79
|
+
if len(args.posonlyargs) > 1:
|
|
80
|
+
raise WorkflowError(
|
|
81
|
+
f"{where} auxiliary parameters cannot be positional-only"
|
|
82
|
+
)
|
|
83
|
+
if args.vararg is not None or args.kwarg is not None:
|
|
84
|
+
raise WorkflowError(f"{where} cannot use *args or **kwargs")
|
|
85
|
+
|
|
86
|
+
auxiliary = {arg.arg for arg in positional[1:]} | {
|
|
87
|
+
arg.arg for arg in args.kwonlyargs
|
|
88
|
+
}
|
|
89
|
+
unknown = auxiliary - cand_argnames
|
|
90
|
+
if unknown:
|
|
91
|
+
raise WorkflowError(
|
|
92
|
+
f"{where} has unsupported parameters: " + ", ".join(sorted(unknown))
|
|
93
|
+
)
|
|
94
|
+
defaults = [*args.defaults, *(value for value in args.kw_defaults if value)]
|
|
95
|
+
try:
|
|
96
|
+
for default in defaults:
|
|
97
|
+
ast.literal_eval(default)
|
|
98
|
+
except (ValueError, SyntaxError, TypeError) as exc:
|
|
99
|
+
raise WorkflowError(f"{where} defaults must be literals") from exc
|
|
100
|
+
|
|
101
|
+
source = ast.unparse(node)
|
|
102
|
+
code = compile(ast.parse(source, mode="eval"), "<rule lambda>", "eval")
|
|
103
|
+
external = {
|
|
104
|
+
instruction.argval
|
|
105
|
+
for child in _code_objects(code)
|
|
106
|
+
for instruction in dis.get_instructions(child)
|
|
107
|
+
if instruction.opname in {"LOAD_GLOBAL", "LOAD_NAME"}
|
|
108
|
+
}
|
|
109
|
+
if external:
|
|
110
|
+
raise WorkflowError(
|
|
111
|
+
f"{where} cannot access external names: " + ", ".join(sorted(external))
|
|
112
|
+
)
|
|
113
|
+
return cls(source, frozenset(auxiliary), function)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _code_objects(code: types.CodeType):
|
|
117
|
+
yield code
|
|
118
|
+
for value in code.co_consts:
|
|
119
|
+
if isinstance(value, types.CodeType):
|
|
120
|
+
yield from _code_objects(value)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Transient per-execution rule state, free of the optional snakemake dependency.
|
|
2
|
+
|
|
3
|
+
The values live in ``ContextVar``\\ s so that concurrent executions in one
|
|
4
|
+
process (threads or asyncio tasks) cannot clobber each other. A plain global
|
|
5
|
+
would be shared by every execution.
|
|
6
|
+
|
|
7
|
+
This module is imported by :mod:`transcript.execute` on every run, so
|
|
8
|
+
``_rule/__init__.py`` must not import :mod:`transcript._rule.core`: importing
|
|
9
|
+
this module has to stay independent of the optional ``snakemake`` extra.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from contextvars import ContextVar
|
|
15
|
+
from typing import TYPE_CHECKING
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from .core import Rule
|
|
19
|
+
|
|
20
|
+
_current: ContextVar[Rule | None] = ContextVar("transcript_rule", default=None)
|
|
21
|
+
_wildcards: ContextVar[dict[str, str] | None] = ContextVar(
|
|
22
|
+
"transcript_wildcards", default=None
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def current():
|
|
27
|
+
return _current.get()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def set_current(value: Rule | None = None):
|
|
31
|
+
"""Set the rule declared by the current document."""
|
|
32
|
+
_current.set(value)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def wildcards():
|
|
36
|
+
"""CLI wildcard overrides for the current execution, or ``{}`` outside one."""
|
|
37
|
+
return _wildcards.get() or {}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def executing():
|
|
41
|
+
"""Whether the document executor is driving the current execution."""
|
|
42
|
+
return _wildcards.get() is not None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Execution:
|
|
46
|
+
def __init__(self, wildcards: dict[str, str] | None):
|
|
47
|
+
self.wildcards = dict(wildcards or {})
|
|
48
|
+
|
|
49
|
+
def __enter__(self):
|
|
50
|
+
self.token = (_wildcards.set(self.wildcards), _current.set(None))
|
|
51
|
+
|
|
52
|
+
def __exit__(self, exc_type, exc, tb):
|
|
53
|
+
_wildcards.reset(self.token[0])
|
|
54
|
+
_current.reset(self.token[1])
|