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,263 @@
|
|
|
1
|
+
"""Trace an artifact back through the tasks that made it.
|
|
2
|
+
|
|
3
|
+
Two records are followed in turn. A store's own records (`provenance`) say which task wrote a key; a file in a
|
|
4
|
+
task's directory belongs to that task by its location. The task's ``inputs.yaml`` then says what its code consumed,
|
|
5
|
+
and each of those is traced the same way, down to data that no task made.
|
|
6
|
+
|
|
7
|
+
The graph has one node per artifact: a file, or the keys one `writes` block added to a store. An edge runs from
|
|
8
|
+
an input to what a task made from it, and carries that task.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import subprocess
|
|
15
|
+
from dataclasses import asdict, dataclass, field
|
|
16
|
+
from datetime import UTC, datetime
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
import yaml
|
|
20
|
+
|
|
21
|
+
from analysis_workflow.paths import (
|
|
22
|
+
ANALYSIS_DIR,
|
|
23
|
+
INPUTS_FILE,
|
|
24
|
+
NON_TASK_DIRS,
|
|
25
|
+
NOTEBOOK_DIR,
|
|
26
|
+
RESERVED_TASK_SUBDIRS,
|
|
27
|
+
UNTRACKED_TASK_DIRS,
|
|
28
|
+
WORKFLOW_DIR,
|
|
29
|
+
_checkouts_of,
|
|
30
|
+
task_id,
|
|
31
|
+
)
|
|
32
|
+
from analysis_workflow.provenance import TIME, keys, records, uncovered
|
|
33
|
+
|
|
34
|
+
TASK_DIR = re.compile(r".+_v\d+")
|
|
35
|
+
|
|
36
|
+
#: Under `data/<dataset>/`, what arrived from outside the repo: no task made it.
|
|
37
|
+
SOURCE_DIRS = frozenset({"raw", "resources"})
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def declared(task: Path) -> list[dict] | None:
|
|
41
|
+
"""The inputs a task's ``inputs.yaml`` lists; None when the task has no such file yet."""
|
|
42
|
+
file = task / INPUTS_FILE
|
|
43
|
+
return [dict(entry) for entry in yaml.safe_load(file.read_text()) or []] if file.exists() else None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def task_dirs(checkout: Path) -> list[Path]:
|
|
47
|
+
"""The task directories of a checkout: those named `<name>_vN` that hold a README."""
|
|
48
|
+
found = []
|
|
49
|
+
for directory, subdirs, files in os.walk(checkout / ANALYSIS_DIR):
|
|
50
|
+
is_task = bool(TASK_DIR.fullmatch(Path(directory).name)) and "README.md" in files
|
|
51
|
+
if is_task:
|
|
52
|
+
found.append(Path(directory))
|
|
53
|
+
skip = RESERVED_TASK_SUBDIRS if is_task else set(UNTRACKED_TASK_DIRS)
|
|
54
|
+
subdirs[:] = sorted(d for d in subdirs if d not in skip and d not in NON_TASK_DIRS and not d.startswith("."))
|
|
55
|
+
return found
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def owner(rel: Path) -> Path | None:
|
|
59
|
+
"""The task directory a repo-relative path under `analysis/` is in: the last `<name>_vN` before its contents."""
|
|
60
|
+
if not rel.parts or rel.parts[0] != ANALYSIS_DIR:
|
|
61
|
+
return None
|
|
62
|
+
task = None
|
|
63
|
+
for i, part in enumerate(rel.parts[1:-1], start=1):
|
|
64
|
+
if task is not None and part in RESERVED_TASK_SUBDIRS:
|
|
65
|
+
break
|
|
66
|
+
if TASK_DIR.fullmatch(part):
|
|
67
|
+
task = i
|
|
68
|
+
return None if task is None else Path(*rel.parts[: task + 1])
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class Trace:
|
|
73
|
+
"""What a trace found. ``nodes`` are artifacts by id; ``edges`` run from an input to what a task made of it."""
|
|
74
|
+
|
|
75
|
+
target: str
|
|
76
|
+
nodes: dict[str, dict] = field(default_factory=dict)
|
|
77
|
+
edges: list[dict] = field(default_factory=list)
|
|
78
|
+
undeclared: list[str] = field(default_factory=list)
|
|
79
|
+
|
|
80
|
+
def tasks(self) -> list[str]:
|
|
81
|
+
"""The task directories on the path, relative to the repo."""
|
|
82
|
+
return sorted({node["task"] for node in self.nodes.values() if node.get("task")})
|
|
83
|
+
|
|
84
|
+
def as_json(self) -> str:
|
|
85
|
+
"""The whole trace."""
|
|
86
|
+
return json.dumps(asdict(self), indent=2)
|
|
87
|
+
|
|
88
|
+
def as_tree(self) -> str:
|
|
89
|
+
"""The target first, each artifact's inputs indented below it."""
|
|
90
|
+
lines, seen = [], set()
|
|
91
|
+
|
|
92
|
+
def walk(node_id: str, depth: int) -> None:
|
|
93
|
+
node = self.nodes[node_id]
|
|
94
|
+
by = Path(node["task"]).name if node.get("task") else node["status"]
|
|
95
|
+
repeat = node_id in seen and any(e["target"] == node_id for e in self.edges)
|
|
96
|
+
lines.append(f"{' ' * depth}{node['label']} [{by}]{' (see above)' if repeat else ''}")
|
|
97
|
+
if node_id not in seen:
|
|
98
|
+
seen.add(node_id)
|
|
99
|
+
for edge in self.edges:
|
|
100
|
+
if edge["target"] == node_id:
|
|
101
|
+
walk(edge["source"], depth + 1)
|
|
102
|
+
|
|
103
|
+
walk(self.target, 0)
|
|
104
|
+
return "\n".join(lines)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class _Walk:
|
|
108
|
+
def __init__(self, start: Path):
|
|
109
|
+
checkout, main = _checkouts_of(start)
|
|
110
|
+
self.roots = list(dict.fromkeys([checkout, main]))
|
|
111
|
+
self.tasks: dict[str, Path] = {} # id -> directory relative to the repo
|
|
112
|
+
for root in self.roots:
|
|
113
|
+
for task in task_dirs(root):
|
|
114
|
+
rel = task.relative_to(root)
|
|
115
|
+
found = task_id(task)
|
|
116
|
+
if found and self.tasks.setdefault(found, rel) != rel:
|
|
117
|
+
raise ValueError(
|
|
118
|
+
f"Task id {found} is in both {self.tasks[found]} and {rel}: a copied task directory? "
|
|
119
|
+
"`analysis-workflow new` gives each task its own."
|
|
120
|
+
)
|
|
121
|
+
self.trace = Trace(target="")
|
|
122
|
+
self._expanded: set[str] = set()
|
|
123
|
+
|
|
124
|
+
def relative(self, path: str | Path) -> Path:
|
|
125
|
+
"""``path`` relative to the repo when it is inside one of its checkouts; else as given, absolute."""
|
|
126
|
+
path = Path(path).expanduser() # `~/...` names a per-user cache, such as a downloaded model
|
|
127
|
+
if not path.is_absolute():
|
|
128
|
+
return path
|
|
129
|
+
for root in self.roots:
|
|
130
|
+
if path.is_relative_to(root):
|
|
131
|
+
return path.relative_to(root)
|
|
132
|
+
return path
|
|
133
|
+
|
|
134
|
+
def on_disk(self, rel: Path) -> Path:
|
|
135
|
+
"""Where ``rel`` is: tracked files in this checkout, shared data and untracked outputs in the main one."""
|
|
136
|
+
return next((root / rel for root in self.roots if (root / rel).exists()), self.roots[-1] / rel)
|
|
137
|
+
|
|
138
|
+
def node(self, node_id: str, **fields) -> str:
|
|
139
|
+
self.trace.nodes.setdefault(node_id, fields)
|
|
140
|
+
return node_id
|
|
141
|
+
|
|
142
|
+
def leaf(self, rel: Path, key: str | None = None) -> str:
|
|
143
|
+
outside = rel.is_absolute() or (rel.parts[:1] == ("data",) and bool(SOURCE_DIRS & set(rel.parts[2:3])))
|
|
144
|
+
label = f"{rel.name}: {key}" if key else "/".join(rel.parts[-3:])
|
|
145
|
+
return self.node(f"{rel}#{key}" if key else str(rel), label=label, status="source" if outside else "no record")
|
|
146
|
+
|
|
147
|
+
def made_by(self, node_id: str, task: Path, when: str | None) -> None:
|
|
148
|
+
"""Add the inputs of ``task`` as what ``node_id``, written at ``when``, was made from."""
|
|
149
|
+
if node_id in self._expanded:
|
|
150
|
+
return
|
|
151
|
+
self._expanded.add(node_id)
|
|
152
|
+
inputs = declared(self.on_disk(task))
|
|
153
|
+
if inputs is None:
|
|
154
|
+
if str(task) not in self.trace.undeclared:
|
|
155
|
+
self.trace.undeclared.append(str(task))
|
|
156
|
+
return
|
|
157
|
+
for entry in inputs:
|
|
158
|
+
rel = self.relative(entry["path"])
|
|
159
|
+
for key in entry.get("keys") or [None]:
|
|
160
|
+
for source in self.artifacts(rel, key, before=when):
|
|
161
|
+
if source != node_id and self.trace.nodes[source].get("task") != str(task):
|
|
162
|
+
edge = {"source": source, "target": node_id, "task": str(task)}
|
|
163
|
+
if edge not in self.trace.edges:
|
|
164
|
+
self.trace.edges.append(edge)
|
|
165
|
+
|
|
166
|
+
def artifacts(self, rel: Path, key: str | None, before: str | None = None) -> list[str]:
|
|
167
|
+
"""The node, or for a whole store (``*``) the nodes, that ``rel`` and ``key`` name; traced further back.
|
|
168
|
+
|
|
169
|
+
A whole store means its write-backs up to ``before``, when what was made from it was written: a later
|
|
170
|
+
one cannot have gone into it.
|
|
171
|
+
"""
|
|
172
|
+
if key is None:
|
|
173
|
+
task = owner(rel)
|
|
174
|
+
if task is None:
|
|
175
|
+
return [self.leaf(rel)]
|
|
176
|
+
node_id = self.node(str(rel), label="/".join(rel.parts[-3:]), status="traced", task=str(task))
|
|
177
|
+
file = self.on_disk(rel) # modification times may be kept to the second only: allow for that
|
|
178
|
+
written = datetime.fromtimestamp(int(file.stat().st_mtime) + 1, UTC) if file.exists() else None
|
|
179
|
+
self.made_by(node_id, task, written and written.strftime(TIME))
|
|
180
|
+
return [node_id]
|
|
181
|
+
found = records(self.on_disk(rel))
|
|
182
|
+
if key == "*":
|
|
183
|
+
found = [record for record in found if before is None or record["at"] <= before]
|
|
184
|
+
else:
|
|
185
|
+
found = [record for record in found if key in record["keys"]][-1:] # the newest that names it
|
|
186
|
+
if not found:
|
|
187
|
+
return [self.leaf(rel, None if key == "*" else key)]
|
|
188
|
+
nodes = []
|
|
189
|
+
if key == "*" and (bare := uncovered(self.on_disk(rel))): # the whole store includes what no record covers
|
|
190
|
+
label = f"{rel.name}: {len(bare)} key(s) without a record"
|
|
191
|
+
nodes.append(self.node(f"{rel}#no record", label=label, keys=bare, status="no record"))
|
|
192
|
+
for record in found:
|
|
193
|
+
node_id = f"{rel}@{record['at']}"
|
|
194
|
+
task = self.tasks.get(record["task"])
|
|
195
|
+
if node_id not in self.trace.nodes:
|
|
196
|
+
self.node(
|
|
197
|
+
node_id,
|
|
198
|
+
store=str(rel),
|
|
199
|
+
keys=[],
|
|
200
|
+
written=len(record["keys"]),
|
|
201
|
+
status="traced" if task else f"task not in this checkout: {record['path']} on {record['branch']}",
|
|
202
|
+
task=str(task) if task else None,
|
|
203
|
+
)
|
|
204
|
+
node = self.trace.nodes[node_id]
|
|
205
|
+
node["keys"] = sorted({*node["keys"], *(record["keys"] if key == "*" else [key])})
|
|
206
|
+
shown = ", ".join(node["keys"][:3]) + (f" (+{len(node['keys']) - 3})" if len(node["keys"]) > 3 else "")
|
|
207
|
+
node["label"] = f"{rel.name}: {shown}"
|
|
208
|
+
if task:
|
|
209
|
+
self.made_by(node_id, task, record["at"])
|
|
210
|
+
nodes.append(node_id)
|
|
211
|
+
return nodes
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def trace(artifact: str | Path, key: str | None = None, *, start: str | Path = ".") -> Trace:
|
|
215
|
+
"""Trace one artifact back to the data no task made.
|
|
216
|
+
|
|
217
|
+
Parameters
|
|
218
|
+
----------
|
|
219
|
+
artifact
|
|
220
|
+
A store in shared storage, with ``key``; or a file, such as one in a task's ``outputs/``.
|
|
221
|
+
key
|
|
222
|
+
The key in the store, as its records name it: ``obs/leiden``, ``X``, ``shapes/cells``,
|
|
223
|
+
``tables/table/obs/leiden``.
|
|
224
|
+
start
|
|
225
|
+
Any path in the checkout to trace from; its tasks are read first, then the main checkout's.
|
|
226
|
+
|
|
227
|
+
Returns
|
|
228
|
+
-------
|
|
229
|
+
The graph. ``undeclared`` lists the tasks on the path whose ``inputs.yaml`` lists no inputs yet; the trace
|
|
230
|
+
stops at each of them.
|
|
231
|
+
"""
|
|
232
|
+
walk = _Walk(Path(start).resolve())
|
|
233
|
+
rel = walk.relative(Path(artifact).resolve())
|
|
234
|
+
walk.trace.target = walk.artifacts(rel, key)[0]
|
|
235
|
+
walk.trace.undeclared.sort()
|
|
236
|
+
return walk.trace
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def missing_inputs(task: Path) -> list[str]:
|
|
240
|
+
"""The declared inputs of ``task`` that are not there: a path that does not exist, a key its store lacks."""
|
|
241
|
+
walk = _Walk(task)
|
|
242
|
+
missing = []
|
|
243
|
+
for entry in declared(task) or []:
|
|
244
|
+
path = walk.on_disk(walk.relative(entry["path"]))
|
|
245
|
+
if not path.exists():
|
|
246
|
+
missing.append(str(entry["path"]))
|
|
247
|
+
elif wanted := [k for k in entry.get("keys") or [] if k != "*"]:
|
|
248
|
+
missing += [f"{entry['path']}: {k}" for k in sorted(set(wanted) - keys(path))]
|
|
249
|
+
return missing
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def changed_since_declared(task: Path) -> bool:
|
|
253
|
+
"""Whether the task's code changed, in git, after its ``inputs.yaml`` was last written."""
|
|
254
|
+
|
|
255
|
+
def git(*args: str) -> str:
|
|
256
|
+
return subprocess.run(["git", *args], cwd=task, capture_output=True, text=True).stdout.strip()
|
|
257
|
+
|
|
258
|
+
code = ("scripts", NOTEBOOK_DIR, WORKFLOW_DIR)
|
|
259
|
+
if git("status", "--porcelain", "--", INPUTS_FILE):
|
|
260
|
+
return False # being written now
|
|
261
|
+
declared_in = git("log", "-1", "--format=%H", "--", INPUTS_FILE)
|
|
262
|
+
later = git("log", "--format=%H", f"{declared_in}..HEAD", "--", *code) if declared_in else ""
|
|
263
|
+
return bool(later) or bool(git("status", "--porcelain", "--", *code))
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Add new keys to a shared AnnData zarr store without touching anyone else's.
|
|
2
|
+
|
|
3
|
+
Two write paths, because the on-disk encoding has two shapes. Outside ``obs``/``var`` an addition is
|
|
4
|
+
a new child node. In ``obs``/``var`` the column set lives in the element's ``column-order`` attribute
|
|
5
|
+
and readers return only the columns listed there, so adding one rewrites the dataframe, re-read fresh
|
|
6
|
+
to carry forward columns added since. Concurrent mapping additions are safe; concurrent ``obs``/``var``
|
|
7
|
+
additions fail loudly (``KeyError``), never silently.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
from collections.abc import Iterable, Mapping
|
|
12
|
+
|
|
13
|
+
import zarr
|
|
14
|
+
from anndata import AnnData
|
|
15
|
+
from anndata.io import read_elem, write_elem
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
#: Slots whose additions are independent creates.
|
|
20
|
+
MAPPING_SLOTS = ("obsm", "varm", "layers", "obsp", "varp", "uns")
|
|
21
|
+
|
|
22
|
+
#: Slots stored as a dataframe, where the column set lives in a ``column-order`` attribute.
|
|
23
|
+
FRAME_SLOTS = ("obs", "var")
|
|
24
|
+
|
|
25
|
+
SLOTS = (*FRAME_SLOTS, *MAPPING_SLOTS)
|
|
26
|
+
|
|
27
|
+
#: Why a working object must not be consolidated.
|
|
28
|
+
CONSOLIDATED = (
|
|
29
|
+
"{path} has consolidated metadata. Keys added to such a store are silently invisible to readers, so a working "
|
|
30
|
+
"object must not be consolidated. Rewrite it with adata.write_zarr(..., consolidate_metadata=False)."
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _in_memory(adata: AnnData) -> dict[str, set[str]]:
|
|
35
|
+
keys = {"obs": set(adata.obs.columns), "var": set(adata.var.columns)}
|
|
36
|
+
for slot in MAPPING_SLOTS:
|
|
37
|
+
# anndata 0.13 lists a ``None`` key in ``layers`` standing for ``X``. It is not a layer.
|
|
38
|
+
keys[slot] = {k for k in getattr(adata, slot) if k is not None}
|
|
39
|
+
return keys
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def keys_on_disk(path) -> dict[str, set[str]]:
|
|
43
|
+
"""What the store at ``path`` already holds, per slot. Reads metadata only, no data."""
|
|
44
|
+
root = zarr.open_group(str(path), mode="r")
|
|
45
|
+
keys = {}
|
|
46
|
+
for slot in FRAME_SLOTS:
|
|
47
|
+
keys[slot] = set(root[slot].attrs.get("column-order", [])) if slot in root else set()
|
|
48
|
+
for slot in MAPPING_SLOTS:
|
|
49
|
+
keys[slot] = set(root[slot]) if slot in root else set()
|
|
50
|
+
return keys
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _describe(value) -> str:
|
|
54
|
+
shape = getattr(value, "shape", None)
|
|
55
|
+
return f"shape {tuple(shape)}" if shape is not None else type(value).__name__
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _refuse_taken(path, slot: str, names: list[str], on_disk) -> None:
|
|
59
|
+
"""Raise if any of ``names`` is already in ``slot`` on disk; checked again just before writing it."""
|
|
60
|
+
if taken := [k for k in names if k in on_disk]:
|
|
61
|
+
raise KeyError(
|
|
62
|
+
f"Already in {path}: {', '.join(f'{slot}[{k!r}]' for k in taken)}. Use another name, or make a new "
|
|
63
|
+
"dated copy to change a key."
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def commit_adata(adata: AnnData, path, *, keys: Mapping[str, Iterable[str]], yes: bool = False) -> dict[str, list[str]]:
|
|
68
|
+
"""Write the ``keys`` of ``adata`` to the zarr store at ``path``, where none of them may exist yet.
|
|
69
|
+
|
|
70
|
+
Dry run by default: with ``yes=False`` the additions are logged and nothing is written. Only the
|
|
71
|
+
listed keys are written, so ``adata`` may also hold what you read.
|
|
72
|
+
|
|
73
|
+
Parameters
|
|
74
|
+
----------
|
|
75
|
+
keys
|
|
76
|
+
The keys to add, per slot: ``{"obs": ["leiden_fine"], "obsm": ["X_scvi"]}``.
|
|
77
|
+
|
|
78
|
+
Returns
|
|
79
|
+
-------
|
|
80
|
+
The keys written (or that would be written), per slot.
|
|
81
|
+
|
|
82
|
+
Raises
|
|
83
|
+
------
|
|
84
|
+
KeyError
|
|
85
|
+
If a key is not in ``adata``, or is already in the store: changing a key means a new dated copy.
|
|
86
|
+
ValueError
|
|
87
|
+
If a slot is unknown, if the store has consolidated metadata, which would make the additions
|
|
88
|
+
invisible to readers, or if another session is concurrently rewriting ``obs``/``var``.
|
|
89
|
+
RuntimeError
|
|
90
|
+
With ``yes=True`` outside a ``writes`` block for the store, where the write would leave no record.
|
|
91
|
+
"""
|
|
92
|
+
from analysis_workflow import provenance # it imports this module
|
|
93
|
+
|
|
94
|
+
if unknown := set(keys) - set(SLOTS):
|
|
95
|
+
raise ValueError(f"Unknown slot(s) {sorted(unknown)}; keys go in {', '.join(SLOTS)}.")
|
|
96
|
+
root = zarr.open_group(str(path), mode="a")
|
|
97
|
+
if root.metadata.consolidated_metadata is not None:
|
|
98
|
+
raise ValueError(CONSOLIDATED.format(path=path))
|
|
99
|
+
|
|
100
|
+
mine, theirs = _in_memory(adata), keys_on_disk(path)
|
|
101
|
+
new = {slot: sorted(set(ks)) for slot, ks in keys.items() if ks}
|
|
102
|
+
if provenance.KEY in new.get("uns", ()):
|
|
103
|
+
raise ValueError(f"uns[{provenance.KEY!r}] holds the store's records of who wrote what; use another name.")
|
|
104
|
+
if missing := [f"{slot}[{k!r}]" for slot, ks in new.items() for k in ks if k not in mine[slot]]:
|
|
105
|
+
raise KeyError(f"Not in adata: {', '.join(missing)}.")
|
|
106
|
+
for slot, names in new.items():
|
|
107
|
+
_refuse_taken(path, slot, names, theirs[slot])
|
|
108
|
+
|
|
109
|
+
lines = [f" + {slot}[{k!r}] {_describe(getattr(adata, slot)[k])}" for slot, ks in new.items() for k in ks]
|
|
110
|
+
logger.info("Committing to %s:\n%s", path, "\n".join(lines) if lines else " nothing to write")
|
|
111
|
+
if not yes or not new:
|
|
112
|
+
if not yes:
|
|
113
|
+
logger.info("Dry run (yes=False): %s unchanged. Re-run with yes=True to write.", path)
|
|
114
|
+
return new
|
|
115
|
+
if not provenance.is_open(path):
|
|
116
|
+
raise RuntimeError(
|
|
117
|
+
f"Not inside a `writes` block for {path}. Put the write in `with writes(path):` (in a notebook, a cell "
|
|
118
|
+
"starting with `%%writes path`), so the store records which task wrote these keys."
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
for slot, names in new.items():
|
|
122
|
+
if slot in FRAME_SLOTS:
|
|
123
|
+
# The column set lives in the parent's ``column-order``, so the element is rewritten.
|
|
124
|
+
# Read it fresh first, to carry forward columns another session added since.
|
|
125
|
+
try:
|
|
126
|
+
frame = read_elem(root[slot])
|
|
127
|
+
except KeyError as err:
|
|
128
|
+
raise ValueError(
|
|
129
|
+
f"Could not read {slot!r} from {path}: another session is most likely "
|
|
130
|
+
"rewriting it right now. Nothing was written; re-run in a moment."
|
|
131
|
+
) from err
|
|
132
|
+
_refuse_taken(path, slot, names, frame.columns)
|
|
133
|
+
for key in names:
|
|
134
|
+
frame[key] = getattr(adata, slot)[key]
|
|
135
|
+
write_elem(root, slot, frame)
|
|
136
|
+
else:
|
|
137
|
+
_refuse_taken(path, slot, names, root[slot] if slot in root else ())
|
|
138
|
+
for key in names:
|
|
139
|
+
write_elem(root[slot], key, getattr(adata, slot)[key])
|
|
140
|
+
|
|
141
|
+
logger.info("Committed to %s.", path)
|
|
142
|
+
return new
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: analysis-workflow
|
|
3
|
+
Version: 0.13.0
|
|
4
|
+
Summary: Task paths, additive AnnData write-back and layout checks for agent-run analysis repos.
|
|
5
|
+
Project-URL: Source, https://github.com/quadbio/analysis-workflow
|
|
6
|
+
Author: quadbio
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
13
|
+
Requires-Python: >=3.12
|
|
14
|
+
Requires-Dist: anndata>=0.12
|
|
15
|
+
Requires-Dist: numpy
|
|
16
|
+
Requires-Dist: pandas
|
|
17
|
+
Requires-Dist: pyyaml
|
|
18
|
+
Requires-Dist: scipy
|
|
19
|
+
Requires-Dist: typer
|
|
20
|
+
Requires-Dist: zarr>=3
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# analysis-workflow
|
|
24
|
+
|
|
25
|
+
A Claude Code plugin for computational-biology analysis repos where humans and coding agents work side by side.
|
|
26
|
+
Both follow the analysis template's `CONVENTIONS.md`: versioned task directories, output paths that survive a git
|
|
27
|
+
worktree being removed, and a shared AnnData zarr *working object* per dataset that grows by additive write-back
|
|
28
|
+
only. The plugin adds what only agents do: one task per session, git worktree and pull request.
|
|
29
|
+
|
|
30
|
+
| Part | What it does |
|
|
31
|
+
| --- | --- |
|
|
32
|
+
| `skills/analysis-workflow/` | The agent's side: task lifecycle in a worktree, sign-off, PRs, environments, setting up repos. Loaded on demand. |
|
|
33
|
+
| `skills/declare-inputs/`, `skills/trace-lineage/` | What a task consumed, written to its `inputs.yaml` from its code; and how an artifact was made, as a graph and a summary. |
|
|
34
|
+
| `hooks/` | Always-on core rules and the main checkout's environment at session start; guards that stop a rule being broken by accident, each of which you can lift for a session. |
|
|
35
|
+
| `src/analysis_workflow/` | The Python package and its `analysis-workflow` command: task paths, writes to shared stores and their records, tracing (as a tree, or as a graph of tasks drawn by [Graphviz](https://graphviz.org), a conda package of the analysis repo), layout checks; the task template. |
|
|
36
|
+
|
|
37
|
+
It assumes analysis repos made from [analysis_template](https://github.com/quadbio/analysis_template)
|
|
38
|
+
(pixi-managed) and code repos from the [scverse cookiecutter](https://github.com/scverse/cookiecutter-scverse)
|
|
39
|
+
(uv-managed). Nothing in it is specific to a dataset, an analysis or a compute environment.
|
|
40
|
+
|
|
41
|
+
## Use
|
|
42
|
+
|
|
43
|
+
Start each analysis task as its own session, from the analysis repo's main checkout. Pull it first: the worktree
|
|
44
|
+
branches from `origin`'s default branch but runs on the main checkout's environment.
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
claude --worktree <task>
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
1. The agent works on that worktree's branch, in a new task directory `analysis/<dataset>/<topic>/agent_<task>_vN/`;
|
|
51
|
+
a later answer to the same question gets the next version, in a new session. Earlier task directories are never
|
|
52
|
+
edited.
|
|
53
|
+
2. It asks you which working object is current and agrees what the task delivers (by default your `deliverables`
|
|
54
|
+
setting), then works in scripts; outputs go to the task directory.
|
|
55
|
+
3. Results reach shared storage only after you sign off, inside a `writes` block that records in the store which
|
|
56
|
+
task wrote them.
|
|
57
|
+
4. It opens a PR whose body holds the details; the task README summarizes each PR. Once it is merged and its batch
|
|
58
|
+
jobs have finished, leave with `/exit` and remove the worktree.
|
|
59
|
+
|
|
60
|
+
A rule is broken only with your approval. When a guard refuses something you want done, the agent passes on the
|
|
61
|
+
command that lifts it for that session, `/analysis-workflow:allow <guard>`, which only you can run; the PR notes
|
|
62
|
+
the exception (the template's `CONVENTIONS.md`).
|
|
63
|
+
|
|
64
|
+
You work the same way, in `human_` task directories in the main checkout (the template's `CONVENTIONS.md`). A task that changes the environment locks, installs and tests
|
|
65
|
+
it in a temporary checkout beside the main one; after its merge you pull and run `pixi install` there. With no
|
|
66
|
+
analysis repo yet, ask Claude to start an analysis project: the skill sets one up.
|
|
67
|
+
|
|
68
|
+
## Install
|
|
69
|
+
|
|
70
|
+
**The plugin**, once per machine, from the [quadbio marketplace](https://github.com/quadbio/claude-plugins). The
|
|
71
|
+
skill is then available everywhere; the hooks and session-start rules act only in repos that enable the plugin in
|
|
72
|
+
their committed `.claude/settings.json`. Every repo made from
|
|
73
|
+
[analysis_template](https://github.com/quadbio/analysis_template) does, and depends on the PyPI package
|
|
74
|
+
`analysis-workflow` in its `pixi.toml`. To adopt an existing repo, ask Claude to adopt the
|
|
75
|
+
conventions.
|
|
76
|
+
|
|
77
|
+
**Settings**, saved with `/plugin configure analysis-workflow@quadbio`:
|
|
78
|
+
|
|
79
|
+
| Setting | Default | Meaning |
|
|
80
|
+
| --- | --- | --- |
|
|
81
|
+
| `deliverables` | `a figure` | What a task delivers unless you choose otherwise at its start; recorded in the task README. Blank: the agent asks. |
|
|
82
|
+
|
|
83
|
+
## Develop
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
uv sync --group dev
|
|
87
|
+
uv run pytest
|
|
88
|
+
uv run pre-commit run --all-files
|
|
89
|
+
claude plugin validate .
|
|
90
|
+
claude --plugin-dir . # try the skill and hooks from this checkout
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
For live package edits in an analysis repo, depend on the checkout instead:
|
|
94
|
+
`analysis-workflow = { path = "../analysis-workflow", editable = true }`.
|
|
95
|
+
|
|
96
|
+
## Release
|
|
97
|
+
|
|
98
|
+
Bump `version` in `.claude-plugin/plugin.json` and merge: the marketplace follows `main`, and users update when the
|
|
99
|
+
version changes. On that merge, `release.yaml` publishes the package to PyPI as `analysis-workflow`, then tags
|
|
100
|
+
`v<version>` and creates a GitHub Release.
|
|
101
|
+
|
|
102
|
+
## License
|
|
103
|
+
|
|
104
|
+
MIT
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
analysis_workflow/__init__.py,sha256=VDd_45mWqR7PNfqgSkvSm8xIWW-q9QxAB6k7L7Fm45k,682
|
|
2
|
+
analysis_workflow/cli.py,sha256=MtPDUc4AHTrXRphQ80_rMmmDfcL6BOm2kGDek6iYQqA,13876
|
|
3
|
+
analysis_workflow/graph.py,sha256=zouGs0q3GGRNf09u2hp0HsG3WcPNTxZYpscEKnkRW_w,12271
|
|
4
|
+
analysis_workflow/paths.py,sha256=UFWikKHCwrzBivfMCCgwoAdLa1ZihAurDsSlpqn_Sr4,7216
|
|
5
|
+
analysis_workflow/provenance.py,sha256=Y9Ddayf2LBxA8ZbE0jL_LWcqnkBjeudLTnUwZ9mXwHw,14153
|
|
6
|
+
analysis_workflow/size.py,sha256=oQWaYT_M1o2Zf0TyTBKIOvc0PGPh3zK-AFGAG0HLplA,3111
|
|
7
|
+
analysis_workflow/trace.py,sha256=9hoS7vJLo4-nE2jbPUXc473Ha7KnQzk4-yP9--DkrgQ,11625
|
|
8
|
+
analysis_workflow/working.py,sha256=dVp95DSKd5x_IVyo5FS9QAWzN2xBO9EpO2t-IdKHGok,6372
|
|
9
|
+
analysis_workflow/task_template/README.md,sha256=YayevJd-wJPZ2rpnkIi6g5ojDhO40xWwrOyeUqLabDk,1901
|
|
10
|
+
analysis_workflow/task_template/scripts/_common.py,sha256=SMcneCLltvXbVDmz_KxXmmsUAcHqPx_LCjettG3BRfg,394
|
|
11
|
+
analysis_workflow-0.13.0.dist-info/METADATA,sha256=QIVCzm0Q6fbPjqx_9MzfRbEJ4uW3HjXb0PwuOjYEYvU,5384
|
|
12
|
+
analysis_workflow-0.13.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
13
|
+
analysis_workflow-0.13.0.dist-info/entry_points.txt,sha256=MSJSx1HmewOOiiM_J1PA_CKlMSVrVi8eq1TAxxf9v94,64
|
|
14
|
+
analysis_workflow-0.13.0.dist-info/licenses/LICENSE,sha256=4lkOIPKRK48xHbM2EZ3oKqWQ584xZMnfThy0iMECQv0,1064
|
|
15
|
+
analysis_workflow-0.13.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 quadbio
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|