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,179 @@
|
|
|
1
|
+
"""Where an analysis task's outputs go, so that none of them dies with a git worktree."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import subprocess
|
|
5
|
+
import sys
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from functools import lru_cache
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
#: The directory under the repo root that holds notebooks and task directories.
|
|
11
|
+
ANALYSIS_DIR = "analysis"
|
|
12
|
+
|
|
13
|
+
#: Task subdirectories git tracks: small, reviewable, they ride the PR.
|
|
14
|
+
TRACKED_TASK_DIRS = ("results", "reports")
|
|
15
|
+
|
|
16
|
+
#: Task subdirectories git ignores: heavy or noisy, anchored to the main checkout.
|
|
17
|
+
UNTRACKED_TASK_DIRS = ("figures", "outputs", "logs")
|
|
18
|
+
|
|
19
|
+
#: A task's notebooks, tracked; agents may leave it empty, so the task template does not carry it.
|
|
20
|
+
NOTEBOOK_DIR = "notebooks"
|
|
21
|
+
|
|
22
|
+
#: A workflow engine's files (Snakefile, rules, configs, profiles), tracked.
|
|
23
|
+
WORKFLOW_DIR = "workflow"
|
|
24
|
+
|
|
25
|
+
#: Directory names that are *inside* a task rather than a task themselves.
|
|
26
|
+
RESERVED_TASK_SUBDIRS = frozenset(
|
|
27
|
+
{*TRACKED_TASK_DIRS, *UNTRACKED_TASK_DIRS, NOTEBOOK_DIR, WORKFLOW_DIR, "scripts", "slurm", "audits", "docs"}
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
#: A task directory's name says which lane made it: `human_<name>_vN` or `agent_<name>_vN`.
|
|
31
|
+
LANES = ("human", "agent")
|
|
32
|
+
|
|
33
|
+
#: The template every task directory starts from, shipped with this package.
|
|
34
|
+
TASK_TEMPLATE = Path(__file__).parent / "task_template"
|
|
35
|
+
|
|
36
|
+
#: What a task's code consumed, at the top of its directory; the `declare-inputs` skill writes it.
|
|
37
|
+
INPUTS_FILE = "inputs.yaml"
|
|
38
|
+
|
|
39
|
+
#: The line of a task's README that holds its id, set by `analysis-workflow new`.
|
|
40
|
+
ID_LINE = re.compile(r"^\*\*Id:\*\*[ \t]*([0-9a-f]+)[ \t]*$", re.MULTILINE)
|
|
41
|
+
|
|
42
|
+
#: The analysis repo's starter notebook, relative to its root; the repo's template owns it.
|
|
43
|
+
NOTEBOOK_TEMPLATE = Path("templates") / "notebook.ipynb"
|
|
44
|
+
|
|
45
|
+
#: Tooling that keeps its own ``logs/`` or ``results/`` and must not be read as a task.
|
|
46
|
+
NON_TASK_DIRS = frozenset({".pixi", ".git", ".venv", "wandb", "site-packages", "node_modules", "__pycache__"})
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@lru_cache
|
|
50
|
+
def _checkouts(directory: str) -> tuple[Path, Path]:
|
|
51
|
+
"""The checkout containing ``directory`` and the repository's main checkout (equal outside a worktree)."""
|
|
52
|
+
try:
|
|
53
|
+
toplevel, common_dir = subprocess.run(
|
|
54
|
+
["git", "rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir"],
|
|
55
|
+
cwd=directory,
|
|
56
|
+
capture_output=True,
|
|
57
|
+
text=True,
|
|
58
|
+
check=True,
|
|
59
|
+
).stdout.splitlines()
|
|
60
|
+
except (subprocess.CalledProcessError, OSError) as err:
|
|
61
|
+
raise RuntimeError(f"{directory} is not inside a git checkout; cannot locate the main checkout") from err
|
|
62
|
+
return Path(toplevel), Path(common_dir).parent
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _checkouts_of(start: str | Path) -> tuple[Path, Path]:
|
|
66
|
+
path = Path(start).resolve()
|
|
67
|
+
while not path.is_dir():
|
|
68
|
+
path = path.parent
|
|
69
|
+
return _checkouts(str(path))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def main_checkout(start: str | Path = ".") -> Path:
|
|
73
|
+
"""Absolute path of the *main* checkout of the repository containing ``start``.
|
|
74
|
+
|
|
75
|
+
Works from any git worktree: ``--git-common-dir`` points at the main checkout's ``.git``.
|
|
76
|
+
Pass ``__file__`` from a script, so the answer does not depend on where it is run from.
|
|
77
|
+
"""
|
|
78
|
+
return _checkouts_of(start)[1]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True)
|
|
82
|
+
class TaskPaths:
|
|
83
|
+
"""The output directories of one analysis task. Nothing exists until :meth:`ensure`."""
|
|
84
|
+
|
|
85
|
+
task: Path
|
|
86
|
+
results: Path
|
|
87
|
+
reports: Path
|
|
88
|
+
figures: Path
|
|
89
|
+
outputs: Path
|
|
90
|
+
logs: Path
|
|
91
|
+
|
|
92
|
+
def ensure(self) -> "TaskPaths":
|
|
93
|
+
"""Create the directories. Call this from the writer, never at import time."""
|
|
94
|
+
for name in (*TRACKED_TASK_DIRS, *UNTRACKED_TASK_DIRS):
|
|
95
|
+
getattr(self, name).mkdir(parents=True, exist_ok=True)
|
|
96
|
+
return self
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def task_paths(file: str | Path | None = None) -> TaskPaths:
|
|
100
|
+
"""Resolve the output directories for the task that ``file`` belongs to.
|
|
101
|
+
|
|
102
|
+
A script passes ``__file__``. A notebook, which has none, passes nothing: the kernel's working
|
|
103
|
+
directory, which Jupyter and VS Code set to the notebook's, stands in. The task directory is the
|
|
104
|
+
nearest ancestor under ``analysis/`` whose name is not a known task subdirectory, so
|
|
105
|
+
``<task>/_common.py``, ``<task>/scripts/_common.py`` and ``<task>/notebooks/`` all resolve to ``<task>``.
|
|
106
|
+
"""
|
|
107
|
+
path = Path(file).resolve() if file is not None else Path.cwd().resolve()
|
|
108
|
+
checkout, main = _checkouts_of(path)
|
|
109
|
+
analysis = checkout / ANALYSIS_DIR
|
|
110
|
+
if not path.is_relative_to(analysis):
|
|
111
|
+
raise ValueError(f"{path} is not under the checkout's '{ANALYSIS_DIR}/' directory, {analysis}")
|
|
112
|
+
|
|
113
|
+
task = path.parent if file is not None else path
|
|
114
|
+
while task.name in RESERVED_TASK_SUBDIRS:
|
|
115
|
+
task = task.parent
|
|
116
|
+
if task == analysis:
|
|
117
|
+
raise ValueError(f"{path} is not inside a task directory under '{ANALYSIS_DIR}/'")
|
|
118
|
+
|
|
119
|
+
main_task = main / ANALYSIS_DIR / task.relative_to(analysis)
|
|
120
|
+
return TaskPaths(
|
|
121
|
+
task=task,
|
|
122
|
+
results=task / "results",
|
|
123
|
+
reports=task / "reports",
|
|
124
|
+
figures=main_task / "figures",
|
|
125
|
+
outputs=main_task / "outputs",
|
|
126
|
+
logs=main_task / "logs",
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def current_task() -> TaskPaths:
|
|
131
|
+
"""The task the running code belongs to: the script being run, or in a notebook the working directory."""
|
|
132
|
+
script = getattr(sys.modules.get("__main__"), "__file__", None)
|
|
133
|
+
if script is not None:
|
|
134
|
+
try:
|
|
135
|
+
return task_paths(script)
|
|
136
|
+
except (ValueError, RuntimeError): # run by a launcher outside `analysis/`, or outside any checkout
|
|
137
|
+
pass
|
|
138
|
+
return task_paths()
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def task_id(task: str | Path) -> str | None:
|
|
142
|
+
"""The id in the header of the task directory's README; None if it has none."""
|
|
143
|
+
readme = Path(task) / "README.md"
|
|
144
|
+
found = ID_LINE.search(readme.read_text()) if readme.exists() else None
|
|
145
|
+
return found and found[1]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def task_field(task: str | Path, field: str) -> str | None:
|
|
149
|
+
"""What the header of the task directory's README says under ``field``, ``Author`` or ``Date``; None if absent."""
|
|
150
|
+
readme = Path(task) / "README.md"
|
|
151
|
+
line = re.compile(rf"^\*\*{re.escape(field)}:\*\*[ \t]*(.+?)[ \t]*$", re.MULTILINE)
|
|
152
|
+
found = line.search(readme.read_text()) if readme.exists() else None
|
|
153
|
+
return found and found[1]
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def empty_dirs(task: str | Path) -> list[Path]:
|
|
157
|
+
"""The task's empty directories, the topmost of each, in its checkout and, for its untracked ones, in main.
|
|
158
|
+
|
|
159
|
+
A symlink is kept and never followed: what it points to is not the task's.
|
|
160
|
+
"""
|
|
161
|
+
task = Path(task).resolve()
|
|
162
|
+
|
|
163
|
+
def empty(path: Path) -> bool:
|
|
164
|
+
return path.is_dir() and not path.is_symlink() and all(empty(child) for child in path.iterdir())
|
|
165
|
+
|
|
166
|
+
def topmost(directory: Path) -> list[Path]:
|
|
167
|
+
found = []
|
|
168
|
+
for child in sorted(directory.iterdir()):
|
|
169
|
+
if empty(child):
|
|
170
|
+
found.append(child)
|
|
171
|
+
elif child.is_dir() and not child.is_symlink():
|
|
172
|
+
found += topmost(child)
|
|
173
|
+
return found
|
|
174
|
+
|
|
175
|
+
found = topmost(task)
|
|
176
|
+
main_task = task_paths(task / "README.md").outputs.parent
|
|
177
|
+
if main_task != task and main_task.is_dir(): # a worktree's task: its untracked directories are in main
|
|
178
|
+
found += [main_task] if empty(main_task) else topmost(main_task)
|
|
179
|
+
return found
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
"""Which task wrote which keys of a shared store, recorded inside the store by the block that wrote them.
|
|
2
|
+
|
|
3
|
+
``with writes(path):`` lists the store's keys before and after its body and credits what appeared to the task the
|
|
4
|
+
code runs in. The record lives with the data: in an AnnData store as one child of ``uns/provenance`` per block, in a
|
|
5
|
+
SpatialData store as one entry of the root attribute ``provenance``; readers see it as ``adata.uns["provenance"]``
|
|
6
|
+
and ``sdata.attrs["provenance"]``. A copy of a store carries its records, and a block credits only keys that none
|
|
7
|
+
of them covers, so copying an object keeps each key with the task that made it. The block that writes a copy
|
|
8
|
+
drops from those records the keys the copy did not keep.
|
|
9
|
+
|
|
10
|
+
A store older than its records gets them from `credit`, which adds the record a block would have written for keys
|
|
11
|
+
that are already there.
|
|
12
|
+
|
|
13
|
+
The stores are read as zarr groups, in format 2 or 3, so SpatialData is not imported. In an existing store only
|
|
14
|
+
children are ever added under ``uns/provenance``: rewriting that group's metadata would replace the file another
|
|
15
|
+
node is reading.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import datetime
|
|
19
|
+
import json
|
|
20
|
+
import logging
|
|
21
|
+
import subprocess
|
|
22
|
+
from contextlib import contextmanager
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
import zarr
|
|
26
|
+
from anndata.io import read_elem, write_elem
|
|
27
|
+
from zarr.errors import ContainsGroupError
|
|
28
|
+
|
|
29
|
+
from analysis_workflow.paths import TaskPaths, _checkouts_of, current_task, task_id, task_paths
|
|
30
|
+
from analysis_workflow.working import CONSOLIDATED, keys_on_disk
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
#: Where the records are: ``uns[KEY]`` in an AnnData store, ``attrs[KEY]`` at a SpatialData store's root.
|
|
35
|
+
KEY = "provenance"
|
|
36
|
+
|
|
37
|
+
#: How a record's ``at`` is written, in UTC; such strings order as their times do.
|
|
38
|
+
TIME = "%Y-%m-%dT%H:%M:%S.%fZ"
|
|
39
|
+
|
|
40
|
+
#: The element kinds of a SpatialData store.
|
|
41
|
+
ELEMENT_KINDS = ("images", "labels", "points", "shapes", "tables")
|
|
42
|
+
|
|
43
|
+
#: Stores with a block open in this process; `commit_adata` writes to no other.
|
|
44
|
+
_open: set[Path] = set()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _root(path, mode="r"):
|
|
48
|
+
# A SpatialData store's consolidated metadata lags behind elements added since it was written.
|
|
49
|
+
return zarr.open_group(str(path), mode=mode, use_consolidated=False)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _present(group, name) -> bool:
|
|
53
|
+
"""Whether ``name`` holds something: anndata writes an unset ``raw`` or ``X`` as a null element."""
|
|
54
|
+
return name in group and group[name].attrs.get("encoding-type") != "null"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _anndata_keys(path, prefix="") -> set[str]:
|
|
58
|
+
found = {f"{prefix}{slot}/{k}" for slot, ks in keys_on_disk(path).items() for k in ks if (slot, k) != ("uns", KEY)}
|
|
59
|
+
root = _root(path)
|
|
60
|
+
return found | {prefix + name for name in ("X", "raw") if _present(root, name)}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _kind(path) -> str | None:
|
|
64
|
+
"""``"anndata"`` or ``"spatialdata"`` for a store this module can record in; None for anything else."""
|
|
65
|
+
path = Path(path)
|
|
66
|
+
if not any((path / metadata).is_file() for metadata in ("zarr.json", ".zgroup")):
|
|
67
|
+
return None
|
|
68
|
+
attrs = _root(path).attrs
|
|
69
|
+
if "spatialdata_attrs" in attrs:
|
|
70
|
+
return "spatialdata"
|
|
71
|
+
return "anndata" if attrs.get("encoding-type") == "anndata" else None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def keys(path) -> set[str]:
|
|
75
|
+
"""The keys of the store at ``path``, read from its metadata; empty for anything that is not a store.
|
|
76
|
+
|
|
77
|
+
AnnData: ``<slot>/<key>``, ``X`` and ``raw``. SpatialData: ``<kind>/<element>``, and each table's keys as
|
|
78
|
+
``tables/<name>/<slot>/<key>``.
|
|
79
|
+
"""
|
|
80
|
+
kind = _kind(path)
|
|
81
|
+
if kind == "anndata":
|
|
82
|
+
return _anndata_keys(path)
|
|
83
|
+
if kind != "spatialdata":
|
|
84
|
+
return set()
|
|
85
|
+
root, found = _root(path), set()
|
|
86
|
+
for element_kind in ELEMENT_KINDS:
|
|
87
|
+
for name in root[element_kind] if element_kind in root else ():
|
|
88
|
+
found.add(f"{element_kind}/{name}")
|
|
89
|
+
if element_kind == "tables":
|
|
90
|
+
found |= _anndata_keys(Path(path) / "tables" / name, f"tables/{name}/")
|
|
91
|
+
return found
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _named(path) -> dict[str, dict]:
|
|
95
|
+
"""The store's records, by the name each is kept under."""
|
|
96
|
+
kind = _kind(path)
|
|
97
|
+
if kind == "spatialdata":
|
|
98
|
+
return dict(_root(path).attrs.get(KEY, {}))
|
|
99
|
+
root = _root(path) if kind == "anndata" else {}
|
|
100
|
+
if "uns" in root and KEY in root["uns"]:
|
|
101
|
+
return {name: json.loads(read_elem(root["uns"][KEY][name])) for name in root["uns"][KEY]}
|
|
102
|
+
return {}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def records(path) -> list[dict]:
|
|
106
|
+
"""The records in the store at ``path``, oldest first: ``{"task", "path", "branch", "keys", "at"}`` each.
|
|
107
|
+
|
|
108
|
+
One added by `credit` also holds ``recorded``, when it was added.
|
|
109
|
+
"""
|
|
110
|
+
return sorted(_named(path).values(), key=lambda record: record["at"])
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _prune(path, present: set[str]) -> None:
|
|
114
|
+
"""In a new copy, drop from the records it carries the keys it did not keep, and the records left with none."""
|
|
115
|
+
named = _named(path)
|
|
116
|
+
kept = {name: {**record, "keys": [k for k in record["keys"] if k in present]} for name, record in named.items()}
|
|
117
|
+
if kept == named:
|
|
118
|
+
return
|
|
119
|
+
root = _root(path, mode="a")
|
|
120
|
+
if _kind(path) == "spatialdata":
|
|
121
|
+
root.attrs[KEY] = {name: record for name, record in kept.items() if record["keys"]}
|
|
122
|
+
zarr.consolidate_metadata(str(path))
|
|
123
|
+
return
|
|
124
|
+
group = root["uns"][KEY]
|
|
125
|
+
for name, record in kept.items():
|
|
126
|
+
if not record["keys"]:
|
|
127
|
+
del group[name]
|
|
128
|
+
elif record != named[name]:
|
|
129
|
+
write_elem(group, name, json.dumps(record))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def uncovered(path) -> list[str]:
|
|
133
|
+
"""The keys of the store at ``path`` that no record covers."""
|
|
134
|
+
return sorted(keys(path) - {k for record in records(path) for k in record["keys"]})
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _write(path, record: dict) -> None:
|
|
138
|
+
name = record["at"].translate({ord(c): None for c in "-:."}) + "_" + record["task"]
|
|
139
|
+
root = _root(path, mode="a")
|
|
140
|
+
if _kind(path) == "spatialdata":
|
|
141
|
+
root.attrs[KEY] = {**root.attrs.get(KEY, {}), name: record}
|
|
142
|
+
zarr.consolidate_metadata(str(path)) # SpatialData reads a store through its consolidated metadata
|
|
143
|
+
return
|
|
144
|
+
uns = root["uns"]
|
|
145
|
+
try:
|
|
146
|
+
group = uns[KEY]
|
|
147
|
+
except KeyError:
|
|
148
|
+
try:
|
|
149
|
+
group = uns.create_group(KEY, attributes={"encoding-type": "dict", "encoding-version": "0.1.0"})
|
|
150
|
+
except ContainsGroupError: # another writer made it meanwhile
|
|
151
|
+
group = uns[KEY]
|
|
152
|
+
write_elem(group, name, json.dumps(record))
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _task(task) -> TaskPaths:
|
|
156
|
+
if isinstance(task, TaskPaths):
|
|
157
|
+
return task
|
|
158
|
+
try:
|
|
159
|
+
return current_task() if task is None else task_paths(Path(task) / "README.md")
|
|
160
|
+
except (ValueError, RuntimeError) as err:
|
|
161
|
+
raise ValueError(
|
|
162
|
+
"`writes` credits what it records to a task: run it from a task directory, or pass `task=<its directory>`."
|
|
163
|
+
) from err
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _consolidated(path) -> bool:
|
|
167
|
+
"""Whether ``path`` is an AnnData store with consolidated metadata, where an added record stays invisible."""
|
|
168
|
+
return _kind(path) == "anndata" and zarr.open_group(str(path), mode="r").metadata.consolidated_metadata is not None
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _record(path: Path, before: set[str], task: TaskPaths, identity: str) -> str | None:
|
|
172
|
+
"""Record what appeared in the store since ``before``; return what broke a rule, if anything did."""
|
|
173
|
+
if _kind(path) is None:
|
|
174
|
+
if before:
|
|
175
|
+
return f"{path} was a store before the block and is none now. Shared stores only grow."
|
|
176
|
+
if path.exists():
|
|
177
|
+
logger.info("%s is not an AnnData or SpatialData store: no record.", path)
|
|
178
|
+
return None
|
|
179
|
+
if _consolidated(path):
|
|
180
|
+
return CONSOLIDATED.format(path=path)
|
|
181
|
+
after = keys(path)
|
|
182
|
+
if not before: # a store this block created: if it is a copy, its records name what the original held
|
|
183
|
+
_prune(path, after)
|
|
184
|
+
covered = {k for record in records(path) for k in record["keys"]}
|
|
185
|
+
if added := sorted(after - before - covered):
|
|
186
|
+
checkout, _ = _checkouts_of(task.task)
|
|
187
|
+
branch = subprocess.run(
|
|
188
|
+
["git", "-C", str(checkout), "branch", "--show-current"], capture_output=True, text=True
|
|
189
|
+
).stdout.strip()
|
|
190
|
+
record = {
|
|
191
|
+
"task": identity,
|
|
192
|
+
"path": task.task.relative_to(checkout).as_posix(),
|
|
193
|
+
"branch": branch or None,
|
|
194
|
+
"keys": added,
|
|
195
|
+
"at": datetime.datetime.now(datetime.UTC).strftime(TIME),
|
|
196
|
+
}
|
|
197
|
+
_write(path, record)
|
|
198
|
+
logger.info("Recorded %d key(s) of %s for %s.", len(added), path.name, record["path"])
|
|
199
|
+
if gone := sorted(before - after):
|
|
200
|
+
return (
|
|
201
|
+
f"No longer in {path}: {', '.join(gone)}. Shared stores only grow; removing or renaming a key means "
|
|
202
|
+
"a new dated copy."
|
|
203
|
+
)
|
|
204
|
+
return None
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@contextmanager
|
|
208
|
+
def writes(path, *, task: TaskPaths | str | Path | None = None):
|
|
209
|
+
"""Record what the body adds to the store at ``path``; every write into shared storage sits in one.
|
|
210
|
+
|
|
211
|
+
Parameters
|
|
212
|
+
----------
|
|
213
|
+
path
|
|
214
|
+
The store on disk, an AnnData or SpatialData zarr store, existing or about to be created. Anything else
|
|
215
|
+
(a plain file) is left without a record.
|
|
216
|
+
task
|
|
217
|
+
The task to credit, as its directory, when that is not the one the code runs in.
|
|
218
|
+
|
|
219
|
+
Raises
|
|
220
|
+
------
|
|
221
|
+
ValueError
|
|
222
|
+
If the code runs in no task directory and ``task`` is not given, or the task's README has no id; if a
|
|
223
|
+
key that was in the store is gone
|
|
224
|
+
after the body, since shared stores only grow; or for an AnnData store with consolidated metadata, in
|
|
225
|
+
which a record would be invisible to readers.
|
|
226
|
+
"""
|
|
227
|
+
path = Path(path).resolve()
|
|
228
|
+
credited = _task(task)
|
|
229
|
+
if (identity := task_id(credited.task)) is None:
|
|
230
|
+
raise ValueError(
|
|
231
|
+
f"{credited.task / 'README.md'} has no `**Id:**` line, under which the store would record the write. "
|
|
232
|
+
"`analysis-workflow new` gives a task one."
|
|
233
|
+
)
|
|
234
|
+
if _consolidated(path):
|
|
235
|
+
raise ValueError(CONSOLIDATED.format(path=path))
|
|
236
|
+
before = keys(path)
|
|
237
|
+
_open.add(path)
|
|
238
|
+
try:
|
|
239
|
+
yield
|
|
240
|
+
finally: # what the body did write is recorded even when it failed part-way
|
|
241
|
+
_open.discard(path)
|
|
242
|
+
problem = _record(path, before, credited, identity)
|
|
243
|
+
if problem:
|
|
244
|
+
raise ValueError(problem)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def credit(path, keys, *, task: TaskPaths | str | Path, at: datetime.datetime, yes: bool = False) -> list[str]:
|
|
248
|
+
"""Credit ``keys`` that are already in the store at ``path`` to the task that wrote them.
|
|
249
|
+
|
|
250
|
+
For a store older than its records, in a repo that adopts these conventions: a `writes` block records only
|
|
251
|
+
what appears while it is open. Dry run by default: with ``yes=False`` the record is logged and nothing is
|
|
252
|
+
written.
|
|
253
|
+
|
|
254
|
+
Parameters
|
|
255
|
+
----------
|
|
256
|
+
keys
|
|
257
|
+
The keys to credit, named as the store's records name them: ``obs/leiden``, ``X``, ``shapes/cells``.
|
|
258
|
+
task
|
|
259
|
+
The directory of the task that wrote them.
|
|
260
|
+
at
|
|
261
|
+
When it wrote them; without a time zone, in UTC. A trace of a whole store follows only the records
|
|
262
|
+
older than what was made from it.
|
|
263
|
+
|
|
264
|
+
Returns
|
|
265
|
+
-------
|
|
266
|
+
The keys credited (or that would be credited).
|
|
267
|
+
|
|
268
|
+
Raises
|
|
269
|
+
------
|
|
270
|
+
KeyError
|
|
271
|
+
If a key is not in the store, or a record already covers it.
|
|
272
|
+
ValueError
|
|
273
|
+
If the task's README has no id, ``at`` is in the future or the time of another record of the store,
|
|
274
|
+
``path`` is no store, or it is an AnnData store with consolidated metadata.
|
|
275
|
+
"""
|
|
276
|
+
path, credited, wanted = Path(path).resolve(), _task(task), sorted(set(keys))
|
|
277
|
+
if (identity := task_id(credited.task)) is None:
|
|
278
|
+
raise ValueError(f"{credited.task / 'README.md'} has no `**Id:**` line to record the keys under.")
|
|
279
|
+
if _kind(path) is None:
|
|
280
|
+
raise ValueError(f"{path} is not an AnnData or SpatialData store: it can hold no record.")
|
|
281
|
+
if _consolidated(path):
|
|
282
|
+
raise ValueError(CONSOLIDATED.format(path=path))
|
|
283
|
+
at = at.replace(tzinfo=datetime.UTC) if at.tzinfo is None else at.astimezone(datetime.UTC)
|
|
284
|
+
now = datetime.datetime.now(datetime.UTC)
|
|
285
|
+
if at > now:
|
|
286
|
+
raise ValueError(f"{at.isoformat()} is in the future: `at` is when the task wrote the keys.")
|
|
287
|
+
found, bare = records(path), set(uncovered(path))
|
|
288
|
+
if covered := sorted({k for record in found for k in record["keys"]} & set(wanted)):
|
|
289
|
+
raise KeyError(f"A record of {path} already covers: {', '.join(covered)}.")
|
|
290
|
+
if absent := [k for k in wanted if k not in bare]:
|
|
291
|
+
raise KeyError(f"Not in {path}: {', '.join(absent)}.")
|
|
292
|
+
checkout, _ = _checkouts_of(credited.task)
|
|
293
|
+
record = {
|
|
294
|
+
"task": identity,
|
|
295
|
+
"path": credited.task.relative_to(checkout).as_posix(),
|
|
296
|
+
"branch": None,
|
|
297
|
+
"keys": wanted,
|
|
298
|
+
"at": at.strftime(TIME),
|
|
299
|
+
"recorded": now.strftime(TIME),
|
|
300
|
+
}
|
|
301
|
+
if any(r["at"] == record["at"] for r in found): # a store's records are told apart by their time
|
|
302
|
+
raise ValueError(f"{path} already holds a record written {record['at']}: give this one another time.")
|
|
303
|
+
listed = "\n".join(f" {k}" for k in wanted) or " nothing to credit"
|
|
304
|
+
logger.info("Crediting to %s, as written %s, in %s:\n%s", record["path"], record["at"], path, listed)
|
|
305
|
+
if not yes or not wanted:
|
|
306
|
+
if not yes:
|
|
307
|
+
logger.info("Dry run (yes=False): %s unchanged. Re-run with yes=True to write.", path)
|
|
308
|
+
return wanted
|
|
309
|
+
_write(path, record)
|
|
310
|
+
return wanted
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def is_open(path) -> bool:
|
|
314
|
+
"""Whether a `writes` block for the store at ``path`` is open in this process."""
|
|
315
|
+
return Path(path).resolve() in _open
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def register_magic() -> None:
|
|
319
|
+
"""In IPython, make ``%%writes <path> [--task <directory>]`` run a cell inside a `writes` block."""
|
|
320
|
+
try:
|
|
321
|
+
from IPython import get_ipython
|
|
322
|
+
except ImportError:
|
|
323
|
+
return
|
|
324
|
+
if (shell := get_ipython()) is None:
|
|
325
|
+
return
|
|
326
|
+
|
|
327
|
+
def magic(line, cell):
|
|
328
|
+
path, _, task = line.partition("--task")
|
|
329
|
+
with writes(shell.ev(path), task=shell.ev(task) if task.strip() else None):
|
|
330
|
+
result = shell.run_cell(cell)
|
|
331
|
+
if error := result.error_before_exec or result.error_in_exec:
|
|
332
|
+
raise error
|
|
333
|
+
|
|
334
|
+
shell.register_magic_function(magic, magic_kind="cell", magic_name="writes")
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""How much memory each part of an AnnData takes: the input to the size test for a write-back."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from typing import Any, Literal
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
from anndata import AnnData
|
|
9
|
+
from scipy.sparse import issparse
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
Unit = Literal["bytes", "KB", "MB", "GB"]
|
|
14
|
+
|
|
15
|
+
_DIVISORS = {"bytes": 1, "kb": 1024, "mb": 1024**2, "gb": 1024**3}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _get_array_size(array: Any, unit: Unit = "bytes") -> float:
|
|
19
|
+
"""Memory size of a NumPy array, SciPy sparse matrix or pandas DataFrame, in ``unit``."""
|
|
20
|
+
if isinstance(array, np.ndarray):
|
|
21
|
+
size_in_bytes = array.nbytes
|
|
22
|
+
elif issparse(array):
|
|
23
|
+
size_in_bytes = sum(
|
|
24
|
+
getattr(array, attr).nbytes for attr in ("data", "indices", "indptr", "row", "col") if hasattr(array, attr)
|
|
25
|
+
)
|
|
26
|
+
if size_in_bytes == 0:
|
|
27
|
+
size_in_bytes = array.nnz * array.dtype.itemsize
|
|
28
|
+
elif isinstance(array, pd.DataFrame):
|
|
29
|
+
size_in_bytes = array.memory_usage(deep=True).sum()
|
|
30
|
+
else:
|
|
31
|
+
raise TypeError(f"Unsupported type: {type(array).__name__}")
|
|
32
|
+
|
|
33
|
+
if unit.lower() not in _DIVISORS:
|
|
34
|
+
raise ValueError(f"Invalid unit '{unit}'. Choose from 'bytes', 'KB', 'MB', 'GB'.")
|
|
35
|
+
return size_in_bytes / _DIVISORS[unit.lower()]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _safe_get_size(obj: Any, unit: Unit) -> float:
|
|
39
|
+
"""Like :func:`_get_array_size`, but 0 for anything it cannot measure."""
|
|
40
|
+
if isinstance(obj, np.ndarray | pd.DataFrame) or issparse(obj):
|
|
41
|
+
return _get_array_size(obj, unit)
|
|
42
|
+
return 0.0
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def analyze_anndata_size(adata: AnnData, unit: Unit = "GB", *, log_result: bool = True) -> dict[str, float]:
|
|
46
|
+
"""Memory footprint of each component of ``adata``.
|
|
47
|
+
|
|
48
|
+
Covers ``X``, ``obs``, ``var``, ``obsm``, ``varm``, ``obsp``, ``varp``, ``layers``, ``uns``
|
|
49
|
+
and ``raw``. Dense, sparse and dataframe values are measured; anything else (dask arrays,
|
|
50
|
+
nested ``uns`` dicts) counts as 0.
|
|
51
|
+
|
|
52
|
+
Parameters
|
|
53
|
+
----------
|
|
54
|
+
adata
|
|
55
|
+
AnnData object to analyze.
|
|
56
|
+
unit
|
|
57
|
+
Unit for the returned sizes.
|
|
58
|
+
log_result
|
|
59
|
+
Whether to log the result at INFO level.
|
|
60
|
+
|
|
61
|
+
Returns
|
|
62
|
+
-------
|
|
63
|
+
Component name to size in ``unit``.
|
|
64
|
+
"""
|
|
65
|
+
sizes: dict[str, float] = {
|
|
66
|
+
"X": _get_array_size(adata.X, unit) if adata.X is not None else 0.0,
|
|
67
|
+
"obs": _get_array_size(adata.obs, unit),
|
|
68
|
+
"var": _get_array_size(adata.var, unit),
|
|
69
|
+
}
|
|
70
|
+
for slot in ("obsm", "varm", "obsp", "varp", "layers", "uns"):
|
|
71
|
+
sizes[slot] = sum(_safe_get_size(value, unit) for value in getattr(adata, slot).values())
|
|
72
|
+
|
|
73
|
+
raw = adata.raw
|
|
74
|
+
sizes["raw"] = (
|
|
75
|
+
0.0
|
|
76
|
+
if raw is None
|
|
77
|
+
else (_get_array_size(raw.X, unit) if raw.X is not None else 0.0)
|
|
78
|
+
+ _get_array_size(raw.var, unit)
|
|
79
|
+
+ sum(_safe_get_size(value, unit) for value in raw.varm.values())
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
if log_result:
|
|
83
|
+
logger.info("AnnData memory usage: %.2f %s total", sum(sizes.values()), unit.upper())
|
|
84
|
+
for component, size in sizes.items():
|
|
85
|
+
if size > 0:
|
|
86
|
+
logger.info(" %s: %.2f %s", component, size, unit.upper())
|
|
87
|
+
return sizes
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# <task directory name, e.g. human_niches_v2>
|
|
2
|
+
|
|
3
|
+
**Date:** <YYYY-MM-DD, when the task started>
|
|
4
|
+
**Author:** <a human's name or initials, or the model, e.g. Claude Opus 5.5>
|
|
5
|
+
**Id:** <set by `analysis-workflow new`; shared stores record under it what this task wrote>
|
|
6
|
+
|
|
7
|
+
<!-- Every heading below stays, in this order, and no others are added; a section with nothing to say reads "None."
|
|
8
|
+
The guidance comments stay too. -->
|
|
9
|
+
|
|
10
|
+
<One or two sentences on what this task set out to answer. A later version names the one it follows and what it
|
|
11
|
+
changes.>
|
|
12
|
+
|
|
13
|
+
## Deliverables
|
|
14
|
+
|
|
15
|
+
<!-- What the task delivers. An agent agrees them with the human at the start, from the default unless they chose
|
|
16
|
+
otherwise; a later change is recorded here too. -->
|
|
17
|
+
|
|
18
|
+
| deliverable | where |
|
|
19
|
+
| --- | --- |
|
|
20
|
+
| <e.g. a figure> | `figures/<file>` (gitignored, in the main checkout) |
|
|
21
|
+
| <e.g. a write-back> | Write-back, below |
|
|
22
|
+
|
|
23
|
+
## Write-back
|
|
24
|
+
|
|
25
|
+
<!-- What each key written to a shared object holds, and the final path of anything placed in
|
|
26
|
+
`data/<dataset>/processed/`. Which task wrote a key is recorded in the store itself. -->
|
|
27
|
+
|
|
28
|
+
- `obs["<key>"]`: one line on what it holds
|
|
29
|
+
|
|
30
|
+
## Running
|
|
31
|
+
|
|
32
|
+
<!-- The notebooks in `notebooks/` and scripts in `scripts/`, in run order, on the main checkout's environment. Batch
|
|
33
|
+
jobs get `MAIN=<main checkout>` at submit and log to `PATHS.logs`. -->
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
PY="pixi run --manifest-path <main checkout>/pixi.toml --as-is python"
|
|
37
|
+
$PY 01_<step>.py
|
|
38
|
+
LOGS=$($PY -c "from _common import PATHS; print(PATHS.ensure().logs)")
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Jobs
|
|
42
|
+
|
|
43
|
+
<!-- Batch jobs this task launched, counted at the end. -->
|
|
44
|
+
|
|
45
|
+
| queue | launched | completed | failed | cancelled |
|
|
46
|
+
| --- | --- | --- | --- | --- |
|
|
47
|
+
| <queue> | <n> | <n> | <n> | <n> |
|
|
48
|
+
|
|
49
|
+
## PRs and issues
|
|
50
|
+
|
|
51
|
+
<!-- Every PR and issue this task opened, in any repo, added when opened, with a short summary of each; the details
|
|
52
|
+
are in the PR. -->
|
|
53
|
+
|
|
54
|
+
- `<owner/repo>#<n>`: one or two lines on what it did
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Paths of this task. Every output path comes from here; create directories with ``PATHS.ensure()``."""
|
|
2
|
+
|
|
3
|
+
from analysis_workflow import task_paths
|
|
4
|
+
|
|
5
|
+
PATHS = task_paths(__file__)
|
|
6
|
+
|
|
7
|
+
RESULTS = PATHS.results
|
|
8
|
+
REPORTS = PATHS.reports
|
|
9
|
+
FIGURES = PATHS.figures
|
|
10
|
+
OUTPUTS = PATHS.outputs
|
|
11
|
+
LOGS = PATHS.logs
|
|
12
|
+
|
|
13
|
+
#: The working object this task reads, supplied by the human at session start.
|
|
14
|
+
WORKING_OBJECT = None
|