analysis-workflow 0.13.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.
- analysis_workflow/__init__.py +22 -0
- analysis_workflow/cli.py +318 -0
- analysis_workflow/graph.py +242 -0
- analysis_workflow/paths.py +179 -0
- analysis_workflow/provenance.py +334 -0
- analysis_workflow/size.py +87 -0
- analysis_workflow/task_template/README.md +54 -0
- analysis_workflow/task_template/scripts/_common.py +14 -0
- analysis_workflow/trace.py +263 -0
- analysis_workflow/working.py +142 -0
- analysis_workflow-0.13.0.dist-info/METADATA +104 -0
- analysis_workflow-0.13.0.dist-info/RECORD +15 -0
- analysis_workflow-0.13.0.dist-info/WHEEL +4 -0
- analysis_workflow-0.13.0.dist-info/entry_points.txt +2 -0
- analysis_workflow-0.13.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Task paths, additive AnnData write-back, records of who wrote what, and layout checks for analysis repos."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import version
|
|
4
|
+
|
|
5
|
+
from analysis_workflow.paths import TaskPaths, main_checkout, task_paths
|
|
6
|
+
from analysis_workflow.provenance import credit, register_magic, writes
|
|
7
|
+
from analysis_workflow.size import analyze_anndata_size
|
|
8
|
+
from analysis_workflow.working import commit_adata, keys_on_disk
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"TaskPaths",
|
|
12
|
+
"analyze_anndata_size",
|
|
13
|
+
"commit_adata",
|
|
14
|
+
"credit",
|
|
15
|
+
"keys_on_disk",
|
|
16
|
+
"main_checkout",
|
|
17
|
+
"task_paths",
|
|
18
|
+
"writes",
|
|
19
|
+
]
|
|
20
|
+
__version__ = version("analysis-workflow")
|
|
21
|
+
|
|
22
|
+
register_magic() # `%%writes <path>` in a notebook
|
analysis_workflow/cli.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
"""``analysis-workflow new``: start a task; ``check ...``: report problems; ``trace``: how an artifact was made."""
|
|
2
|
+
|
|
3
|
+
import datetime
|
|
4
|
+
import re
|
|
5
|
+
import secrets
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import typer
|
|
11
|
+
|
|
12
|
+
from analysis_workflow.graph import dot, render
|
|
13
|
+
from analysis_workflow.paths import (
|
|
14
|
+
ANALYSIS_DIR,
|
|
15
|
+
LANES,
|
|
16
|
+
NON_TASK_DIRS,
|
|
17
|
+
NOTEBOOK_DIR,
|
|
18
|
+
NOTEBOOK_TEMPLATE,
|
|
19
|
+
TASK_TEMPLATE,
|
|
20
|
+
TRACKED_TASK_DIRS,
|
|
21
|
+
UNTRACKED_TASK_DIRS,
|
|
22
|
+
_checkouts_of,
|
|
23
|
+
empty_dirs,
|
|
24
|
+
main_checkout,
|
|
25
|
+
)
|
|
26
|
+
from analysis_workflow.provenance import records, uncovered
|
|
27
|
+
from analysis_workflow.trace import changed_since_declared, declared, missing_inputs, task_dirs, trace
|
|
28
|
+
|
|
29
|
+
app = typer.Typer(no_args_is_help=True)
|
|
30
|
+
check = typer.Typer(no_args_is_help=True)
|
|
31
|
+
app.add_typer(check, name="check", help="Report problems; never change anything.")
|
|
32
|
+
|
|
33
|
+
TASK_NAME = re.compile(rf"(?P<lane>{'|'.join(LANES)})_(?P<name>.+)_v(?P<version>[1-9]\d*)")
|
|
34
|
+
NOTEBOOK_NAME = re.compile(r"\d{2}_\w+")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _version(directory: str, name: str) -> int | None:
|
|
38
|
+
"""The version of ``directory`` if it answers the question ``name``, in either lane or the older unprefixed form."""
|
|
39
|
+
for prefix in (*(f"{lane}_" for lane in LANES), ""):
|
|
40
|
+
if m := re.fullmatch(rf"{re.escape(prefix + name)}_v(\d+)", directory):
|
|
41
|
+
return int(m[1])
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def new_task(
|
|
46
|
+
path: Path,
|
|
47
|
+
author: str | None = None,
|
|
48
|
+
notebook: str | None = None,
|
|
49
|
+
today: datetime.date | None = None,
|
|
50
|
+
ported_from: str | None = None,
|
|
51
|
+
) -> Path:
|
|
52
|
+
"""Create the task directory ``path`` from the task template; return it.
|
|
53
|
+
|
|
54
|
+
``path`` is ``analysis/<dataset>/<topic>/.../<lane>_<name>_vN``, relative to the working directory or absolute,
|
|
55
|
+
and ``vN`` must be the next version of ``<name>`` beside it, counted over both lanes, in this checkout and the
|
|
56
|
+
main one. ``author`` defaults, for a human's task, to the git user name; an agent's task names its model.
|
|
57
|
+
``notebook`` (``NN_<step>``) copies the repo's starter notebook into ``notebooks/``. ``ported_from`` names the
|
|
58
|
+
older work the task ports, as ``<repo>:<path>@<commit>``, in the README's header; such a task keeps that
|
|
59
|
+
work's version, which must be above every version beside it.
|
|
60
|
+
"""
|
|
61
|
+
path = Path(path).resolve()
|
|
62
|
+
checkout, main = _checkouts_of(path)
|
|
63
|
+
analysis = checkout / ANALYSIS_DIR
|
|
64
|
+
form = f"{ANALYSIS_DIR}/<dataset>/<topic>/<{'|'.join(LANES)}>_<name>_v<N>"
|
|
65
|
+
if not path.is_relative_to(analysis) or len(path.relative_to(analysis).parts) < 3:
|
|
66
|
+
raise ValueError(f"{path} is not of the form {form}, under {checkout}.")
|
|
67
|
+
if not (m := TASK_NAME.fullmatch(path.name)):
|
|
68
|
+
raise ValueError(f"{path.name!r} is not a task name: {form}.")
|
|
69
|
+
if path.exists():
|
|
70
|
+
raise FileExistsError(f"{path} already exists.")
|
|
71
|
+
if author is None and m["lane"] == "human":
|
|
72
|
+
author = subprocess.run(
|
|
73
|
+
["git", "-C", str(checkout), "config", "user.name"], capture_output=True, text=True
|
|
74
|
+
).stdout.strip()
|
|
75
|
+
if not author:
|
|
76
|
+
raise ValueError("Pass --author: the model for an agent's task, or a name where git has no `user.name`.")
|
|
77
|
+
parent = path.parent.relative_to(checkout)
|
|
78
|
+
found = [
|
|
79
|
+
v
|
|
80
|
+
for d in {checkout / parent, main / parent}
|
|
81
|
+
if d.is_dir()
|
|
82
|
+
for c in d.iterdir()
|
|
83
|
+
if (v := _version(c.name, m["name"]))
|
|
84
|
+
]
|
|
85
|
+
expected = max(found, default=0) + 1
|
|
86
|
+
if ported_from is not None and int(m["version"]) < expected:
|
|
87
|
+
raise ValueError(f"A port keeps its version, which must be v{expected} or above in {parent}.")
|
|
88
|
+
if ported_from is None and int(m["version"]) != expected:
|
|
89
|
+
raise ValueError(f"The next version of {m['name']!r} in {parent} is v{expected}, not v{m['version']}.")
|
|
90
|
+
if notebook is not None:
|
|
91
|
+
if not NOTEBOOK_NAME.fullmatch(notebook):
|
|
92
|
+
raise ValueError(f"{notebook!r} is not a notebook name: NN_<step>, e.g. 01_qc.")
|
|
93
|
+
if not (starter := checkout / NOTEBOOK_TEMPLATE).is_file():
|
|
94
|
+
raise FileNotFoundError(f"This repo has no starter notebook at {NOTEBOOK_TEMPLATE}.")
|
|
95
|
+
|
|
96
|
+
shutil.copytree(TASK_TEMPLATE, path, ignore=shutil.ignore_patterns("__pycache__"))
|
|
97
|
+
(path / NOTEBOOK_DIR).mkdir()
|
|
98
|
+
if notebook is not None:
|
|
99
|
+
shutil.copyfile(starter, path / NOTEBOOK_DIR / f"{notebook}.ipynb")
|
|
100
|
+
readme = path / "README.md"
|
|
101
|
+
fill = {
|
|
102
|
+
"# ": f"# {path.name}",
|
|
103
|
+
"**Date:**": f"**Date:** {today or datetime.date.today()}",
|
|
104
|
+
"**Author:**": f"**Author:** {author}",
|
|
105
|
+
"**Id:**": f"**Id:** {secrets.token_hex(4)}",
|
|
106
|
+
}
|
|
107
|
+
lines = readme.read_text().splitlines(keepends=True)
|
|
108
|
+
for start, line in fill.items():
|
|
109
|
+
i = next(i for i, old in enumerate(lines) if old.startswith(start))
|
|
110
|
+
lines[i] = line + "\n"
|
|
111
|
+
if ported_from is not None:
|
|
112
|
+
lines.insert(lines.index(fill["**Id:**"] + "\n") + 1, f"**Ported from:** {ported_from}\n")
|
|
113
|
+
readme.write_text("".join(lines))
|
|
114
|
+
return path
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@app.command("new")
|
|
118
|
+
def new(
|
|
119
|
+
path: Path = typer.Argument(..., help="analysis/<dataset>/<topic>/<human|agent>_<name>_v<N>"),
|
|
120
|
+
author: str | None = typer.Option(
|
|
121
|
+
None, help="A human's name or initials (default: the git user name), or the model, e.g. 'Claude Opus 5.5'."
|
|
122
|
+
),
|
|
123
|
+
notebook: str | None = typer.Option(None, help="Also copy the repo's starter notebook in, as NN_<step>."),
|
|
124
|
+
ported_from: str | None = typer.Option(
|
|
125
|
+
None, help="The older work this task ports, as <repo>:<path>@<commit>; the task keeps its version."
|
|
126
|
+
),
|
|
127
|
+
) -> None:
|
|
128
|
+
"""Start a task directory from the task template."""
|
|
129
|
+
try:
|
|
130
|
+
task = new_task(path, author, notebook, ported_from=ported_from)
|
|
131
|
+
except (ValueError, FileExistsError, FileNotFoundError) as err:
|
|
132
|
+
typer.echo(f"Error: {err}", err=True)
|
|
133
|
+
raise typer.Exit(1) from err
|
|
134
|
+
typer.echo(f"created {task}")
|
|
135
|
+
for p in sorted(task.rglob("*")):
|
|
136
|
+
typer.echo(f" {p.relative_to(task)}{'/' if p.is_dir() else ''}")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@app.command("tidy")
|
|
140
|
+
def tidy(task: Path = typer.Argument(..., help="The task directory, at its end.")) -> None:
|
|
141
|
+
"""Remove the directories the task left empty."""
|
|
142
|
+
try:
|
|
143
|
+
found = empty_dirs(task)
|
|
144
|
+
except (ValueError, RuntimeError) as err:
|
|
145
|
+
typer.echo(f"Error: {err}", err=True)
|
|
146
|
+
raise typer.Exit(1) from err
|
|
147
|
+
for path in found:
|
|
148
|
+
shutil.rmtree(path)
|
|
149
|
+
typer.echo(f"removed {path}")
|
|
150
|
+
if not found:
|
|
151
|
+
typer.echo("No empty directories.")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
# Reporting thresholds, tuning knobs rather than facts about a project.
|
|
155
|
+
HEAVY_RESULT_BYTES = 1_000_000 # a tracked evidence table this big is a data artifact in a csv costume
|
|
156
|
+
HEAVY_REPORT_BYTES = 20_000_000 # reports embed base64 figures, so large is fine, but not this large
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _is_task_output(path: Path, root: Path) -> bool:
|
|
160
|
+
"""True when ``path`` is a task's own output dir, not one nested in tooling or in another."""
|
|
161
|
+
rel = path.relative_to(root)
|
|
162
|
+
if NON_TASK_DIRS & set(rel.parts):
|
|
163
|
+
return False
|
|
164
|
+
# a results/ inside results/, or a logs/ inside outputs/, belongs to whatever made it
|
|
165
|
+
return not set(rel.parts[:-1]) & {*TRACKED_TASK_DIRS, *UNTRACKED_TASK_DIRS}
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _tracked(main: Path) -> list[str]:
|
|
169
|
+
return subprocess.run(
|
|
170
|
+
["git", "-C", str(main), "ls-files", ANALYSIS_DIR], capture_output=True, text=True, check=True
|
|
171
|
+
).stdout.splitlines()
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def stray_worktree_outputs(main: Path) -> list[Path]:
|
|
175
|
+
"""Untracked output written inside a worktree, which dies when the worktree is removed."""
|
|
176
|
+
worktrees = main / ".claude" / "worktrees"
|
|
177
|
+
if not worktrees.is_dir():
|
|
178
|
+
return []
|
|
179
|
+
stray = []
|
|
180
|
+
for tree in sorted(p for p in worktrees.iterdir() if p.is_dir()):
|
|
181
|
+
for name in UNTRACKED_TASK_DIRS:
|
|
182
|
+
for found in (tree / ANALYSIS_DIR).rglob(name):
|
|
183
|
+
if found.is_dir() and any(found.iterdir()) and _is_task_output(found, tree):
|
|
184
|
+
stray.append(found)
|
|
185
|
+
return sorted(stray)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def orphaned_outputs(main: Path) -> list[Path]:
|
|
189
|
+
"""Output dirs in the main checkout with no tracked task beside them: abandoned or deleted tasks."""
|
|
190
|
+
tracked_dirs = {str(Path(f).parent) for f in _tracked(main)}
|
|
191
|
+
orphans = []
|
|
192
|
+
for name in UNTRACKED_TASK_DIRS:
|
|
193
|
+
for found in (main / ANALYSIS_DIR).rglob(name):
|
|
194
|
+
if not found.is_dir() or not any(found.iterdir()) or not _is_task_output(found, main):
|
|
195
|
+
continue
|
|
196
|
+
task = str(found.parent.relative_to(main))
|
|
197
|
+
if not any(d == task or d.startswith(f"{task}/") for d in tracked_dirs):
|
|
198
|
+
orphans.append(found)
|
|
199
|
+
return sorted(orphans)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def heavy_tracked(main: Path) -> list[tuple[Path, int, str]]:
|
|
203
|
+
"""Tracked files too large for the directory they are in."""
|
|
204
|
+
heavy = []
|
|
205
|
+
for rel in _tracked(main):
|
|
206
|
+
path = main / rel
|
|
207
|
+
if not path.is_file():
|
|
208
|
+
continue
|
|
209
|
+
parts, size = Path(rel).parts, path.stat().st_size
|
|
210
|
+
if "results" in parts and size > HEAVY_RESULT_BYTES:
|
|
211
|
+
heavy.append((Path(rel), size, "belongs in outputs/"))
|
|
212
|
+
elif "reports" in parts and size > HEAVY_REPORT_BYTES:
|
|
213
|
+
heavy.append((Path(rel), size, "outsized even for an embedded-figure report"))
|
|
214
|
+
return sorted(heavy, key=lambda t: -t[1])
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
@check.command("layout")
|
|
218
|
+
def layout(start: Path = typer.Argument(Path("."), help="Any path inside the repository.")) -> None:
|
|
219
|
+
"""Report stray, orphaned and oversized task outputs. Never deletes anything."""
|
|
220
|
+
main = main_checkout(start)
|
|
221
|
+
typer.echo(f"main checkout: {main}\n")
|
|
222
|
+
|
|
223
|
+
stray = stray_worktree_outputs(main)
|
|
224
|
+
typer.echo(f"[stray worktree output] {len(stray)} found")
|
|
225
|
+
for p in stray:
|
|
226
|
+
typer.echo(f" {p.relative_to(main)} — will be lost when the worktree is removed")
|
|
227
|
+
|
|
228
|
+
orphans = orphaned_outputs(main)
|
|
229
|
+
typer.echo(f"\n[orphaned output dirs] {len(orphans)} found")
|
|
230
|
+
for p in orphans:
|
|
231
|
+
typer.echo(f" {p.relative_to(main)} — no tracked task beside it")
|
|
232
|
+
|
|
233
|
+
heavy = heavy_tracked(main)
|
|
234
|
+
typer.echo(f"\n[heavy tracked files] {len(heavy)} found")
|
|
235
|
+
for rel, size, why in heavy:
|
|
236
|
+
typer.echo(f" {size / 1e6:8.1f} MB {rel} — {why}")
|
|
237
|
+
|
|
238
|
+
problems = len(stray) + len(orphans) + len(heavy)
|
|
239
|
+
typer.echo(f"\n{problems} item(s) to look at." if problems else "\nClean.")
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
@check.command("provenance")
|
|
243
|
+
def provenance(store: Path = typer.Argument(..., help="An AnnData or SpatialData zarr store.")) -> None:
|
|
244
|
+
"""Report the keys of a store that no record credits to a task: written outside a `writes` block."""
|
|
245
|
+
found = records(store)
|
|
246
|
+
typer.echo(f"{store}: {len(found)} record(s) from {len({r['task'] for r in found})} task(s)\n")
|
|
247
|
+
missing = uncovered(store)
|
|
248
|
+
typer.echo(f"[keys without a record] {len(missing)} found")
|
|
249
|
+
for key in missing:
|
|
250
|
+
typer.echo(f" {key}")
|
|
251
|
+
typer.echo(f"\n{len(missing)} item(s) to look at." if missing else "\nClean.")
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
@check.command("inputs")
|
|
255
|
+
def inputs(
|
|
256
|
+
tasks: list[Path] = typer.Argument(None, help="Task directories; by default every task of this checkout."),
|
|
257
|
+
) -> None:
|
|
258
|
+
"""Report tasks that have no `inputs.yaml`, or whose list names something that is not there or is out of date."""
|
|
259
|
+
found = [t.resolve() for t in tasks] if tasks else task_dirs(_checkouts_of(Path.cwd())[0])
|
|
260
|
+
undeclared = [t for t in found if declared(t) is None]
|
|
261
|
+
missing = [(t, what) for t in found for what in missing_inputs(t)]
|
|
262
|
+
stale = [t for t in found if declared(t) is not None and changed_since_declared(t)]
|
|
263
|
+
|
|
264
|
+
typer.echo(f"[inputs not declared] {len(undeclared)} found")
|
|
265
|
+
for task in undeclared:
|
|
266
|
+
typer.echo(f" {task}")
|
|
267
|
+
typer.echo(f"\n[declared, but not there] {len(missing)} found")
|
|
268
|
+
for task, what in missing:
|
|
269
|
+
typer.echo(f" {task.name}: {what}")
|
|
270
|
+
typer.echo(f"\n[code changed since declared] {len(stale)} found")
|
|
271
|
+
for task in stale:
|
|
272
|
+
typer.echo(f" {task}")
|
|
273
|
+
|
|
274
|
+
problems = len(undeclared) + len(missing) + len(stale)
|
|
275
|
+
typer.echo(f"\n{problems} item(s) for the `declare-inputs` skill." if problems else "\nClean.")
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
@app.command("trace")
|
|
279
|
+
def trace_command(
|
|
280
|
+
artifact: Path = typer.Argument(..., help="A store in shared storage, or a file such as one in a task's outputs/."),
|
|
281
|
+
key: str | None = typer.Argument(None, help="The key in the store: obs/leiden, X, tables/table/obs/leiden."),
|
|
282
|
+
form: str = typer.Option(
|
|
283
|
+
"tree", "--format", help="tree, json or tasks; dot or pdf for a graph of the tasks, drawn by Graphviz."
|
|
284
|
+
),
|
|
285
|
+
output: Path | None = typer.Option(
|
|
286
|
+
None, "--output", "-o", help="Where `--format pdf` writes the graph; a .svg or .png suffix gives that type."
|
|
287
|
+
),
|
|
288
|
+
) -> None:
|
|
289
|
+
"""Trace one artifact back through the tasks that made it."""
|
|
290
|
+
try:
|
|
291
|
+
found = trace(artifact, key, start=Path.cwd())
|
|
292
|
+
except ValueError as err:
|
|
293
|
+
typer.echo(f"Error: {err}", err=True)
|
|
294
|
+
raise typer.Exit(1) from err
|
|
295
|
+
if found.undeclared:
|
|
296
|
+
typer.echo("No declared inputs for these tasks on the path; run the `declare-inputs` skill on them:", err=True)
|
|
297
|
+
for task in found.undeclared:
|
|
298
|
+
typer.echo(f" {task}", err=True)
|
|
299
|
+
raise typer.Exit(1)
|
|
300
|
+
formats = {
|
|
301
|
+
"tree": found.as_tree,
|
|
302
|
+
"json": found.as_json,
|
|
303
|
+
"tasks": lambda: "\n".join(found.tasks()),
|
|
304
|
+
"dot": lambda: dot(found, Path.cwd()),
|
|
305
|
+
}
|
|
306
|
+
if form not in (*formats, "pdf"):
|
|
307
|
+
typer.echo(f"Error: --format is one of {', '.join(formats)}, pdf.", err=True)
|
|
308
|
+
raise typer.Exit(1)
|
|
309
|
+
try:
|
|
310
|
+
if form != "pdf":
|
|
311
|
+
typer.echo(formats[form]())
|
|
312
|
+
elif output is None:
|
|
313
|
+
raise ValueError("`--format pdf` needs `--output <file>`.")
|
|
314
|
+
else:
|
|
315
|
+
typer.echo(f"wrote {render(dot(found, Path.cwd()), output)}")
|
|
316
|
+
except (ValueError, RuntimeError) as err:
|
|
317
|
+
typer.echo(f"Error: {err}", err=True)
|
|
318
|
+
raise typer.Exit(1) from err
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
"""A trace drawn as a graph of tasks, as DOT text for Graphviz.
|
|
2
|
+
|
|
3
|
+
One small node per task, in three bands. The bar names the task, its author and date. The shaded band is what
|
|
4
|
+
the task consumed that no task made, so the trace ends there: one row per place it lives in, a coloured bar saying
|
|
5
|
+
which place (source data in this repo, or one colour per place outside it, the same in every figure of a repo),
|
|
6
|
+
then the first few items. The white band is what the task produced on this path. One arrow runs from a task to
|
|
7
|
+
each task that consumed what it produced. Above the graph are a title and a small legend of the bars.
|
|
8
|
+
|
|
9
|
+
Graphviz places the nodes and routes the arrows, so the picture stays compact as tasks are added. Which files and
|
|
10
|
+
keys exactly is what the trace's tree lists.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import datetime
|
|
14
|
+
import shutil
|
|
15
|
+
import subprocess
|
|
16
|
+
from collections import defaultdict
|
|
17
|
+
from html import escape
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from analysis_workflow.paths import _checkouts_of, task_field
|
|
21
|
+
from analysis_workflow.trace import Trace, declared, task_dirs
|
|
22
|
+
|
|
23
|
+
#: Hues of a palette checked for colour-vision deficiencies: what a task produced; source data in this repo;
|
|
24
|
+
#: then, in this order, the places outside the repo sorted by name. A seventh place outside gets the neutral,
|
|
25
|
+
#: told apart by its name in the legend.
|
|
26
|
+
PRODUCED, HERE = "produced", "this repo"
|
|
27
|
+
PRODUCED_COLOUR, HERE_COLOUR = "#2a78d6", "#1baf7a"
|
|
28
|
+
OUTSIDE = ("#eb6834", "#eda100", "#e87ba4", "#6250d6", "#e34948", "#008300")
|
|
29
|
+
INK, SECONDARY, MUTED, BAND, SURFACE = "#0b0b0b", "#52514e", "#898781", "#efeee9", "#fcfcfb"
|
|
30
|
+
FONT = "Helvetica"
|
|
31
|
+
#: How many items a place names before counting the rest.
|
|
32
|
+
SHOWN = 3
|
|
33
|
+
#: Point sizes: the title, a task's name, what it produced, the small print (what it consumed, author and date,
|
|
34
|
+
#: the legend), and the blank line above and below the legend.
|
|
35
|
+
TITLE, NAME, BODY, SMALL, GAP = 8, 7, 6, 5, 3
|
|
36
|
+
#: Characters per line that give a node's two bands about the same width; and those of the title and legend,
|
|
37
|
+
#: about as wide as a node.
|
|
38
|
+
WRAP = {BODY: 54, SMALL: 64}
|
|
39
|
+
HEAD = 80
|
|
40
|
+
#: The task that is not in this checkout: a branch that is not merged, or a task that was removed.
|
|
41
|
+
ELSEWHERE = "task not in this checkout"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _origin(path: str) -> tuple[str, str]:
|
|
45
|
+
"""Where a path that no task made lives, HERE or the name of a place outside the repo, and a short name.
|
|
46
|
+
|
|
47
|
+
In the repo, the name is the folder under `data/<dataset>/` and the last two parts of the path; outside, its
|
|
48
|
+
last part, or its last two under the home directory.
|
|
49
|
+
"""
|
|
50
|
+
p, home = Path(path).expanduser(), Path.home()
|
|
51
|
+
if not p.is_absolute():
|
|
52
|
+
parts = p.parts[2:] if p.parts[0] == "data" and len(p.parts) > 3 else p.parts
|
|
53
|
+
return HERE, "/".join(parts) if len(parts) <= 3 else f"{parts[0]}/…/{'/'.join(parts[-2:])}"
|
|
54
|
+
for parent in p.parents:
|
|
55
|
+
if (parent / ".git").exists() and not home.is_relative_to(parent): # a home directory under version control
|
|
56
|
+
return parent.name, p.name
|
|
57
|
+
return ("home directory", "/".join(p.parts[-2:])) if p.is_relative_to(home) else ("outside any repo", str(p))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _colours(roots: list[Path]) -> dict[str, str]:
|
|
61
|
+
"""The colour of each place source data comes from, over all tasks of the repo: the same in every figure."""
|
|
62
|
+
places = set()
|
|
63
|
+
for root in roots:
|
|
64
|
+
for task in task_dirs(root):
|
|
65
|
+
places |= {_origin(str(entry["path"]))[0] for entry in declared(task) or []}
|
|
66
|
+
places.discard(HERE)
|
|
67
|
+
outside = {place: OUTSIDE[i] if i < len(OUTSIDE) else SECONDARY for i, place in enumerate(sorted(places))}
|
|
68
|
+
return {HERE: HERE_COLOUR, **outside}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _summary(found: Trace) -> tuple[dict[str, dict[str, list[str]]], set[tuple[str, str]]]:
|
|
72
|
+
"""Per task on the path the names of what it produced and of what it consumed, by where that lives.
|
|
73
|
+
|
|
74
|
+
Also which task consumed which task's work. The artifact asked about is marked by a leading ``▶``.
|
|
75
|
+
"""
|
|
76
|
+
tasks = defaultdict(lambda: defaultdict(list))
|
|
77
|
+
for node, fields in found.nodes.items():
|
|
78
|
+
if task := fields.get("task"):
|
|
79
|
+
name = Path(fields["store"]).name if "store" in fields else Path(node).name
|
|
80
|
+
if "store" in fields:
|
|
81
|
+
name += f": {fields['keys'][0]}" if len(fields["keys"]) == 1 else f" ({len(fields['keys'])} keys)"
|
|
82
|
+
tasks[task][PRODUCED].insert(0, "▶ " + name) if node == found.target else tasks[task][PRODUCED].append(name)
|
|
83
|
+
edges, keys = set(), defaultdict(lambda: defaultdict(set))
|
|
84
|
+
for edge in found.edges:
|
|
85
|
+
source = found.nodes[edge["source"]]
|
|
86
|
+
if maker := source.get("task"):
|
|
87
|
+
if maker != edge["task"]:
|
|
88
|
+
edges.add((maker, edge["task"]))
|
|
89
|
+
continue
|
|
90
|
+
path, _, key = edge["source"].partition("#")
|
|
91
|
+
place, name = _origin(path.partition("@")[0]) # a store's write-back is named `<store>@<when>`
|
|
92
|
+
status = ELSEWHERE if source["status"].startswith(ELSEWHERE) else source["status"]
|
|
93
|
+
name += "" if status == "source" else f" ({status})"
|
|
94
|
+
if name not in tasks[edge["task"]][place]:
|
|
95
|
+
tasks[edge["task"]][place].append(name)
|
|
96
|
+
keys[edge["task"]][(place, name)] |= set(source.get("keys") or ([key] if key else []))
|
|
97
|
+
for task, counted in keys.items(): # a store consumed by key shows how many
|
|
98
|
+
for (place, name), found_keys in counted.items():
|
|
99
|
+
if found_keys:
|
|
100
|
+
tasks[task][place][tasks[task][place].index(name)] = f"{name} ({len(found_keys)} keys)"
|
|
101
|
+
return tasks, edges
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _listed(names: list[str], size: float) -> list[str]:
|
|
105
|
+
"""The first names of a list, " · " between them, in lines of WRAP[size] characters; the rest counted."""
|
|
106
|
+
shown, more = names[:SHOWN], len(names) - SHOWN
|
|
107
|
+
lines, line, used = [], "", 0
|
|
108
|
+
for i, name in enumerate(shown):
|
|
109
|
+
text = name + (" · " if i < len(shown) - 1 else f" +{more}" if more > 0 else "")
|
|
110
|
+
if used and used + len(text) > WRAP[size]:
|
|
111
|
+
lines.append(line)
|
|
112
|
+
line, used = "", 0
|
|
113
|
+
# the artifact asked about is the one thing set in bold
|
|
114
|
+
line += f"<B>{escape(text)}</B>" if name.startswith("▶") else escape(text)
|
|
115
|
+
used += len(text)
|
|
116
|
+
return [*lines, line]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _rows(entries: list[tuple[str, list[str]]], size: float, ink: str) -> str:
|
|
120
|
+
"""Entries of (bar colour, lines of text): a coloured bar down the left of each entry's lines."""
|
|
121
|
+
text = "".join(
|
|
122
|
+
f'<FONT COLOR="{colour}">▌</FONT>{line}<BR ALIGN="LEFT"/>' for colour, lines in entries for line in lines
|
|
123
|
+
)
|
|
124
|
+
return f'<FONT POINT-SIZE="{size}" COLOR="{ink}">{text}</FONT>'
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _node(task: str, header: str, about: dict[str, list[str]], colour: dict[str, str], note: str) -> str:
|
|
128
|
+
"""A task's node as a Graphviz HTML-like label: the bar, what was consumed (shaded), what was produced."""
|
|
129
|
+
bar = (
|
|
130
|
+
f'<FONT COLOR="#ffffff" POINT-SIZE="{NAME}"><B>{escape(Path(task).name)}</B></FONT>'
|
|
131
|
+
f'<FONT COLOR="#ffffff" POINT-SIZE="{SMALL}"> {escape(header)}</FONT>'
|
|
132
|
+
)
|
|
133
|
+
consumed = [(colour[place], _listed(about[place], SMALL)) for place in colour if about.get(place)]
|
|
134
|
+
if note:
|
|
135
|
+
band = f'<FONT POINT-SIZE="{SMALL}" COLOR="{MUTED}">{note}</FONT>'
|
|
136
|
+
else:
|
|
137
|
+
band = _rows(consumed, SMALL, SECONDARY) if consumed else ""
|
|
138
|
+
bands = f'<TR><TD ALIGN="LEFT" BGCOLOR="{SECONDARY}">{bar}</TD></TR>'
|
|
139
|
+
if band:
|
|
140
|
+
bands += f'<TR><TD ALIGN="LEFT" BGCOLOR="{BAND}">{band}</TD></TR>'
|
|
141
|
+
produced = _rows([(PRODUCED_COLOUR, _listed(about[PRODUCED], BODY))], BODY, INK)
|
|
142
|
+
bands += f'<TR><TD ALIGN="LEFT" BGCOLOR="#ffffff">{produced}</TD></TR>'
|
|
143
|
+
return (
|
|
144
|
+
f'"{task}" [label=<<TABLE BORDER="1" COLOR="{SECONDARY}" CELLBORDER="0" CELLSPACING="0" CELLPADDING="1">'
|
|
145
|
+
f"{bands}</TABLE>>];"
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _legend(used: list[str], colour: dict[str, str]) -> str:
|
|
150
|
+
"""The legend under the title: lines of small grey text, each coloured bar followed by what it marks.
|
|
151
|
+
|
|
152
|
+
No line is longer than HEAD characters, with a little space above and below.
|
|
153
|
+
"""
|
|
154
|
+
|
|
155
|
+
def bar(shade: str, text: str) -> str:
|
|
156
|
+
return f'<FONT COLOR="{shade}">▌</FONT>{escape(text)}'
|
|
157
|
+
|
|
158
|
+
lines = [f"{bar(PRODUCED_COLOUR, 'produced by the task, consumed below')} <B>▶</B> the artifact asked about"]
|
|
159
|
+
if used:
|
|
160
|
+
lines.append("consumed by the task, not further traceable; by where it lives:")
|
|
161
|
+
line, length = "", 0
|
|
162
|
+
for place in used:
|
|
163
|
+
if length and length + len(place) + 3 > HEAD:
|
|
164
|
+
lines.append(line)
|
|
165
|
+
line, length = "", 0
|
|
166
|
+
line, length = line + bar(colour[place], place) + " ", length + len(place) + 3
|
|
167
|
+
lines.append(line)
|
|
168
|
+
gap = f'<FONT POINT-SIZE="{GAP}"> <BR ALIGN="LEFT"/></FONT>'
|
|
169
|
+
text = "".join(f'{line}<BR ALIGN="LEFT"/>' for line in lines)
|
|
170
|
+
return f'{gap}<FONT POINT-SIZE="{SMALL}" COLOR="{MUTED}">{text}</FONT>{gap}'
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def dot(found: Trace, start: str | Path = ".", *, today: datetime.date | None = None) -> str:
|
|
174
|
+
"""The trace ``found`` as DOT text: the tasks its artifact rests on, back to the data no task made.
|
|
175
|
+
|
|
176
|
+
Parameters
|
|
177
|
+
----------
|
|
178
|
+
start
|
|
179
|
+
Any path in the checkout the trace was run from; its tasks' READMEs give the authors and dates.
|
|
180
|
+
today
|
|
181
|
+
The date in the title; by default, today's.
|
|
182
|
+
|
|
183
|
+
Raises
|
|
184
|
+
------
|
|
185
|
+
ValueError
|
|
186
|
+
If no task made the artifact: there is nothing to draw.
|
|
187
|
+
"""
|
|
188
|
+
target = found.nodes[found.target]
|
|
189
|
+
if target.get("task") is None:
|
|
190
|
+
raise ValueError(f"No task made {target['label']} ({target['status']}): there is nothing to draw.")
|
|
191
|
+
roots = list(dict.fromkeys(_checkouts_of(start)))
|
|
192
|
+
about, edges = _summary(found)
|
|
193
|
+
colour, consumers = _colours(roots), {consumer for _, consumer in edges}
|
|
194
|
+
used = [place for place in colour if any(place in lists for lists in about.values())]
|
|
195
|
+
|
|
196
|
+
def header(task: str) -> tuple[str, str]:
|
|
197
|
+
"""A task's author and date, from its README in the first checkout that has the task."""
|
|
198
|
+
where = next((root / task for root in roots if (root / task / "README.md").exists()), roots[-1] / task)
|
|
199
|
+
return task_field(where, "Author") or "", task_field(where, "Date") or ""
|
|
200
|
+
|
|
201
|
+
name = (
|
|
202
|
+
Path(target["store"]).name + ": " + ", ".join(target["keys"]) if "store" in target else Path(found.target).name
|
|
203
|
+
)
|
|
204
|
+
when = escape(f"on {today or datetime.date.today()} in {roots[-1].name}")
|
|
205
|
+
# a long artifact name takes the title line to itself
|
|
206
|
+
joint = '<BR ALIGN="LEFT"/>' if len(name) + len(when) > HEAD else " "
|
|
207
|
+
lines = [
|
|
208
|
+
"digraph trace {",
|
|
209
|
+
f' graph [rankdir=TB, bgcolor="{SURFACE}", pad=0.06, nodesep=0.12, ranksep=0.16, fontname="{FONT}", '
|
|
210
|
+
"labelloc=t, labeljust=l,",
|
|
211
|
+
f' label=<<FONT POINT-SIZE="{TITLE}"><B>Tracing {escape(name)}</B></FONT>'
|
|
212
|
+
f'<FONT POINT-SIZE="{SMALL}" COLOR="{SECONDARY}">{joint}{when}</FONT><BR ALIGN="LEFT"/>'
|
|
213
|
+
f"{_legend(used, colour)}>];",
|
|
214
|
+
f' node [shape=plain, fontname="{FONT}"];',
|
|
215
|
+
f' edge [penwidth=0.7, arrowsize=0.45, color="{SECONDARY}"];',
|
|
216
|
+
]
|
|
217
|
+
for task in sorted(about, key=lambda t: (header(t)[1], t)): # the oldest task first
|
|
218
|
+
sourced = any(place != PRODUCED for place in about[task])
|
|
219
|
+
missing = "inputs not declared" if task in found.undeclared else "no inputs declared"
|
|
220
|
+
note = missing if task in found.undeclared or not (sourced or task in consumers) else ""
|
|
221
|
+
lines.append(" " + _node(task, " · ".join(filter(None, header(task))), about[task], colour, note))
|
|
222
|
+
lines += [f' "{maker}" -> "{consumer}";' for maker, consumer in sorted(edges)]
|
|
223
|
+
return "\n".join([*lines, "}"]) + "\n"
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def render(source: str, output: str | Path) -> Path:
|
|
227
|
+
"""Draw DOT text ``source`` into ``output`` with Graphviz; the suffix picks the file type (.pdf, .svg, .png).
|
|
228
|
+
|
|
229
|
+
Raises
|
|
230
|
+
------
|
|
231
|
+
RuntimeError
|
|
232
|
+
If Graphviz's ``dot`` is not on PATH.
|
|
233
|
+
"""
|
|
234
|
+
output = Path(output)
|
|
235
|
+
if shutil.which("dot") is None:
|
|
236
|
+
raise RuntimeError(
|
|
237
|
+
"Graphviz's `dot` is not on PATH. It is a conda package: in a pixi project, `pixi add graphviz`."
|
|
238
|
+
)
|
|
239
|
+
subprocess.run(
|
|
240
|
+
["dot", f"-T{output.suffix.lstrip('.') or 'pdf'}", "-o", str(output)], input=source, text=True, check=True
|
|
241
|
+
)
|
|
242
|
+
return output
|