Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# 🧬 analysis_template

A [cruft](https://cruft.github.io/cruft/) template for notebook-first single-cell and spatial analysis
repos, managed with [pixi](https://pixi.sh). Humans work in notebooks; coding agents follow the
[analysis-workflow](https://github.com/quadbio/analysis-workflow) plugin, which every generated repo enables.
repos, managed with [pixi](https://pixi.sh). Humans and coding agents share one task layout, set out in each
project's `CONVENTIONS.md`; agents also follow the [analysis-workflow](https://github.com/quadbio/analysis-workflow)
plugin, which every generated repo enables.

> Building a reusable Python library? Use the [scverse cookiecutter](https://github.com/scverse/cookiecutter-scverse) instead.

Expand Down
5 changes: 2 additions & 3 deletions {{cookiecutter.project_name}}/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,8 @@ data/**
!data/**/.gitkeep

# Directories to ignore. Unanchored, so they also match inside every analysis task directory
# (analysis/<dataset>/<topic>/.../<name>_vN/): the untracked half of a task, anchored to the main checkout.
**/figures/*
!/figures/.gitkeep
# (analysis/<dataset>/<topic>/.../<lane>_<name>_vN/): the untracked half of a task, anchored to the main checkout.
figures/
outputs/
logs/

Expand Down
10 changes: 6 additions & 4 deletions {{cookiecutter.project_name}}/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ anything documented there is referenced from here, never restated.

## Workflow

The human and agent lanes, task lifecycle, output paths, `data/` layout, working objects and their
write-back are owned by the [analysis-workflow](https://github.com/quadbio/analysis-workflow)
plugin, enabled in `.claude/settings.json`: load its skill before writing analysis code, outputs or
data. Pull requests are reviewed against [`REVIEW_GUIDE.md`](REVIEW_GUIDE.md).
Task directories, output paths, the `data/` layout and working objects follow
[`CONVENTIONS.md`](CONVENTIONS.md), for humans and agents alike. What only agents do (a worktree, a session and a
PR per task, sign-off on every write-back) comes from the
[analysis-workflow](https://github.com/quadbio/analysis-workflow) plugin, enabled in `.claude/settings.json`: load
its skill before writing analysis code, outputs or data. Pull requests are reviewed against
[`REVIEW_GUIDE.md`](REVIEW_GUIDE.md).

## This repo

Expand Down
101 changes: 101 additions & 0 deletions {{cookiecutter.project_name}}/CONVENTIONS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# Conventions

How analysis is organized in this repo. Humans and coding agents follow the same rules; agents add their own on top
(a worktree, a session and a PR per task, sign-off on every write-back), from the
[analysis-workflow](https://github.com/quadbio/analysis-workflow) plugin.

> Everything here comes from the analysis template; change it there and pull it with `cruft update`.

## Start a task

```bash
pixi run analysis-workflow new analysis/<dataset>/<topic>/human_<name>_v1 --author <your initials> --notebook 01_<step>
```

This creates the task directory with its `README.md` and a starter notebook in `notebooks/`. Open the notebook,
fill in the README's question and inputs, and work.

## Tasks

All analysis lives in task directories, `analysis/<dataset>/<topic>/<lane>_<name>_vN/`:

- `<dataset>` is there even when the repo has one dataset. Topics, such as `preprocessing/`, `annotation/` or
`spatial/`, can mostly be worked on in any order.
- `<lane>` is `human` or `agent`; the README's author line says who: initials, or the model.
- `vN` counts the answers to one question across both lanes: `human_markers_v1` may be followed by
`agent_markers_v2`. `analysis-workflow new` refuses any other version than the next.
- A task is edited freely until its first write-back to a shared object or until other tasks read its outputs (for
an agent's task: its merge). After that it is frozen, and a change is the next version, whose README names the
one it follows.

| in a task | tracked | holds |
| --- | --- | --- |
| `README.md` | yes | the question, inputs, deliverables, write-back; kept current |
| `notebooks/` | yes | `NN_<step>.ipynb`, numbered in run order; outputs committed, so keep them small |
| `scripts/` | yes | `NN_<step>.py`, numbered in run order; `_common.py` holds the task's paths |
| `results/` | yes | small evidence tables; past ~1 MB they belong in `outputs/` |
| `reports/` | yes | a report |
| `figures/` | no | figures |
| `outputs/` | no | data artifacts |
| `logs/` | no | batch-job logs |

Every output path comes from `task_paths`: `PATHS = task_paths()` in a notebook, `task_paths(__file__)` in a script;
`PATHS.ensure()` creates the directories. Dataset paths come from `FilePaths`:

```python
from analysis_workflow import task_paths
from {{ cookiecutter.package_name }} import FilePaths

PATHS = task_paths().ensure()
working = FilePaths.EXAMPLE_DATASET / "processed" / "working" / "pbmc3k_2026-01-27.zarr"
fig.savefig(PATHS.figures / "umap.pdf")
```

## Data

| `data/<dataset>/` | holds |
| --- | --- |
| `raw/` | bytes as they arrived, never changed |
| `resources/` | curated inputs that are not data: gene lists, marker tables |
| `processed/` | objects other tasks load: working objects in `working/`, others in descriptively named subdirectories |

A task writes into its own directory. An object other tasks will load goes to `processed/` (for an agent, after
sign-off), and the task README records its path.

## Working objects

A working object is an AnnData zarr store, `processed/working/<name>_<YYYY-MM-DD>.zarr`, in which results from many
tasks accumulate.

- Read only what you need: `ad.io.read_elem(zarr.open_group(path)["obs"])`, or `ad.experimental.read_lazy`.
- Write back only through `commit_adata`, naming the keys you add. It refuses a key that is already there, so
nobody's results get overwritten:

```python
from analysis_workflow import commit_adata

commit_adata(adata, path, keys={"obs": ["leiden_fine"]}) # dry run: shows what it would write
commit_adata(adata, path, keys={"obs": ["leiden_fine"]}, yes=True) # writes
```

- Never write an in-memory object over a working object: it erases what others added since you read it. Changing
or removing a key means a new dated copy.
- Give keys descriptive names, and list each in the task README's Write-back section.
- Labels: one categorical `obs` column, colours in `uns["<key>_colors"]`.
- A result that would grow the object materially (`analyze_anndata_size`) becomes a standalone AnnData on the same
`obs_names`, never a bare `.npy`.

## Git

You work in the main checkout. A pull request is optional and encouraged for anything others build on:

```bash
git switch -c <branch>
git add analysis/<dataset>/<topic>/<task> && git commit -m "<what>"
git push -u origin <branch>
gh pr create # its body starts from the PR template
```

It is reviewed against `REVIEW_GUIDE.md`. Switching
branches changes the main checkout that agents' sessions read, `pixi.toml` included: switch back to `main` when you
are done.
29 changes: 11 additions & 18 deletions {{cookiecutter.project_name}}/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,17 @@ In Jupyter Lab, check that your kernel appears (look for `{{ cookiecutter.projec

## 📊 Start Your Analysis

- **Demo notebook**: Check out `analysis/ML-2026-01-27_demo_scRNA_workflow.ipynb` for a complete scRNA-seq workflow example using scanpy's PBMC 3k dataset.
- **New notebooks**: Copy `analysis/XX-2026-01-27_sample_notebook.ipynb` as a starting point. Follow the naming convention: `[INITIALS]-[YYYY]-[MM]-[DD]_description.ipynb`.
- **Add your data**: Create folders under `data/` and register paths in `src/{{ cookiecutter.package_name }}/_constants.py`.
Each piece of analysis gets its own task directory. Start one with a notebook in it:

```bash
pixi run analysis-workflow new analysis/<dataset>/<topic>/human_<name>_v1 --author <your initials> --notebook 01_<step>
```

- **How it fits together**: [`CONVENTIONS.md`](CONVENTIONS.md): task directories, where outputs go, `data/`, and
writing to a shared working object.
- **Demo**: `analysis/example_dataset/demo/human_scrna_workflow_v1/` runs a complete scRNA-seq workflow on scanpy's
PBMC 3k dataset.
- **Add your data**: create `data/<dataset>/` and register its path in `src/{{ cookiecutter.package_name }}/_constants.py`.

---

Expand Down Expand Up @@ -149,21 +157,6 @@ Or edit `pixi.toml` directly and run `pixi install`.

</details>

<details>
<summary><strong>📓 Data and notebook conventions</strong></summary>

- **Notebook naming**: `[INITIALS]-[YYYY]-[MM]-[DD]_description.ipynb`
- **Data layout and the notebook lane**: the analysis-workflow skill's
[Data](https://github.com/quadbio/analysis-workflow/blob/main/skills/analysis-workflow/SKILL.md#data) and
[Two lanes](https://github.com/quadbio/analysis-workflow/blob/main/skills/analysis-workflow/SKILL.md#two-lanes)
- **Import paths** via the local package:

```python
from {{ cookiecutter.package_name }} import FilePaths
```

</details>

<details>
<summary><strong>🔧 Pre-commit & code quality</strong></summary>

Expand Down
29 changes: 14 additions & 15 deletions {{cookiecutter.project_name}}/REVIEW_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ PR review playbook for **review agents running on GitHub**. Imperative voice.
**Scope: review only.** Comment and suggest. Do not push commits or apply fixes.

> Everything above "This repo" comes from the analysis template; change it there and pull it with `cruft update`.
> It tells reviewers, who cannot load the analysis-workflow plugin, what to check of its rules.
> It tells reviewers, who cannot load the analysis-workflow plugin, what to check of `CONVENTIONS.md` and the
> plugin's rules. A PR's task directory says its lane: `human_…` or `agent_…`.

The code has usually already run. That is not a reason to lower the bar: requiring a rerun in better shape is a
normal outcome. Say what to redo, not just what was wrong.
Expand All @@ -27,27 +28,25 @@ A write to a working object goes through `commit_adata`, gated behind a dry run.

- an in-memory AnnData written back over a working object (`write_zarr`/`write_h5ad` onto its path): it erases
whatever other sessions added since it was read;
- a recomputed key committed under an existing name: `commit_adata` writes only keys not yet on disk, so it is a
no-op and the PR reports a result the object doesn't hold. Use a new key or a new dated copy;
- a replaced SpatialData image, labels, points or shapes element, where a new element name would do.

### 2. Promotions, which leave no diff

`data/` is gitignored, so an object written into `data/<dataset>/processed/` appears nowhere in the diff; the task
README's `Write-back` section is the only trace. The right subdirectory is not guessable. Check that the README
*says* where it went, that the PR body flags it for sign-off and that it was agreed, while moving it is still cheap.
*says* where it went and, for an agent's PR, that the PR body flags it for sign-off and that it was agreed, while
moving it is still cheap.

### 3. The task contract

Agent work belongs in a task directory `analysis/<dataset>/<topic>/.../<name>_vN/`. Check that its README's content
is real: the actual input files, the deliverables agreed with the human, a short summary of each PR. An edit to an
earlier task's directory is a finding: analysis moves forward, and a new version names the one it follows. A task is
one branch merged through one or more PRs, so a directory whose earlier PRs (its README lists them) came from this
PR's branch is this task's own, not an earlier one. Writes to `data/<dataset>/results/` or the central `figures/`
are the human lane and are a finding.
Work belongs in a task directory `analysis/<dataset>/<topic>/.../<lane>_<name>_vN/`. Check that its README's
content is real: the actual input files, the deliverables, a short summary of each PR. An edit to a frozen task's
directory (one written back from, or merged) is a finding: analysis moves forward, and a new version names the one
it follows. A task is one branch merged through one or more PRs, so a directory whose earlier PRs (its README lists
them) came from this PR's branch is this task's own, not an earlier one. Outputs written outside the task directory,
other than to a shared object, are a finding.

Every key committed to a shared object carries the task's version suffix **and** appears in that README: an
unrecorded key can't be traced back, an unsuffixed one collides with the next version.
Every key committed to a shared object appears in that README: an unrecorded key can't be traced back.

### 4. Scientific correctness

Expand Down Expand Up @@ -80,9 +79,9 @@ living file that restates another instead of linking to it is a finding, because
- Lock files, and anything under `data/`.
- Committed notebook outputs: review changed cells' code, never the output blobs.
- Absolute paths built from `main_checkout()`: task outputs are anchored there deliberately.
- A task directory's layout and its README's headings: a hook holds them to the plugin's task template.
- Worktree, temp-dir and cwd-relative `data/`/`figures/` path literals in `analysis/` code: a hook blocks them
before the file is written.
- In an `agent_` task: its layout and its README's headings, which a hook holds to the task template; and
worktree, temp-dir and cwd-relative `data/`/`figures/` path literals, which a hook blocks before the file is
written. A `human_` task has no such hook: report these there.

## Drift older than the diff

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# human_scrna_workflow_v1

**Date:** 2026-01-27
**Author:** ML

<!-- Every heading below stays, in this order, and no others are added; a section with nothing to say reads "None."
The guidance comments stay too. -->

A demo of a complete scRNA-seq workflow on scanpy's PBMC 3k data, from QC to a working object, marking which
steps to run locally and which on a GPU cluster.

## Deliverables

<!-- What the task delivers. An agent agrees them with the human at the start, from the default unless they chose
otherwise; a later change is recorded here too. -->

| deliverable | where |
| --- | --- |
| UMAP overviews | `figures/` (gitignored) |
| a new working object | Write-back, below |

## Inputs

<!-- The actual files, not concepts: this is what makes the task re-runnable. -->

- scanpy's PBMC 3k dataset, downloaded to `data/example_dataset/raw/`
- CellTypist's `Immune_All_High.pkl` model

## Write-back

<!-- What went into a shared object, under which keys, and anything placed in `data/<dataset>/processed/` with its
final path. -->

- `data/example_dataset/processed/working/pbmc3k_2026-01-27.zarr`, a new working object, holding:
- `obsm["X_scVI"]`, `obsm["X_umap"]`: scVI latent space and its UMAP
- `obs["leiden"]`: Leiden clusters at resolution 0.5
- `obs["cell_type"]`: CellTypist labels, majority-voted

## Running

<!-- The notebooks in `notebooks/` and scripts in `scripts/`, in run order, on the main checkout's environment. Batch
jobs get `MAIN=<main checkout>` at submit and log to `PATHS.logs`. -->

`notebooks/01_scrna_workflow.ipynb`, top to bottom; its scVI section is faster on a GPU.

## Jobs

<!-- Batch jobs this task launched, counted at the end. -->

None.

## PRs and issues

<!-- Every PR and issue this task opened, in any repo, added when opened, with a short summary of each; the details
are in the PR. -->

None.
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,7 @@
"\n",
"**Legend:**\n",
"- 💻 **Local** — Fast, good for development, code editing\n",
"- 🚀 **GPU/Euler** — Heavy compute, model fitting, GPU-accelerated\n",
"\n",
"**Changelog:**\n",
"- 2026-01-27: Initial demo notebook"
"- 🚀 **GPU/Euler** — Heavy compute, model fitting, GPU-accelerated"
]
},
{
Expand All @@ -30,16 +27,6 @@
"## Preliminaries"
]
},
{
"cell_type": "markdown",
"id": "2",
"metadata": {},
"source": [
"### Dependency notebooks\n",
"\n",
"This is a standalone demo — no dependencies on other notebooks."
]
},
{
"cell_type": "markdown",
"id": "3",
Expand Down Expand Up @@ -72,6 +59,7 @@
"\n",
"import matplotlib.pyplot as plt\n",
"import scanpy as sc\n",
"from analysis_workflow import task_paths\n",
"\n",
"# Local analysis package — edit these functions in src/{{ cookiecutter.package_name }}/\n",
"from {{ cookiecutter.package_name }} import FilePaths, qc_violin\n",
Expand All @@ -94,13 +82,15 @@
"metadata": {},
"outputs": [],
"source": [
"PATHS = task_paths().ensure() # this task's figures/, outputs/, results/, ...\n",
"\n",
"sc.settings.verbosity = 2\n",
"sc.settings.datasetdir = FilePaths.EXAMPLE_DATASET / \"raw\"\n",
"sc.settings.set_figure_params(dpi=100, frameon=False)\n",
"sc.settings.figdir = FilePaths.FIGURES / \"example_dataset\"\n",
"sc.settings.figdir = PATHS.figures\n",
"\n",
"print(f\"Project root: {FilePaths.ROOT}\")\n",
"print(f\"Data folder: {FilePaths.DATA}\")"
"print(f\"Data folder: {FilePaths.DATA}\")\n",
"print(f\"Task figures: {PATHS.figures}\")"
]
},
{
Expand Down Expand Up @@ -488,7 +478,7 @@
"source": [
"### 💾 Save Results — 💻 Local\n",
"\n",
"Save processed data following the template's data organization."
"This notebook starts a new working object: a dated zarr store in `processed/working/` that other tasks load and add keys to with `commit_adata`. It is written without consolidated metadata, so those additions stay visible."
]
},
{
Expand All @@ -497,7 +487,13 @@
"id": "37",
"metadata": {},
"outputs": [],
"source": "output_path = FilePaths.EXAMPLE_DATASET / \"processed\" / \"pbmc3k_processed.zarr\"\nadata.write_zarr(output_path)\nprint(f\"Saved to: {output_path}\")"
"source": [
"output_path = FilePaths.EXAMPLE_DATASET / \"processed\" / \"working\" / \"pbmc3k_2026-01-27.zarr\"\n",
"if output_path.exists(): # other tasks may have added to it since: never write over it\n",
" raise FileExistsError(f\"{output_path} exists; write a new dated copy instead.\")\n",
"adata.write_zarr(output_path, consolidate_metadata=False)\n",
Comment on lines +491 to +494

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Refuse to overwrite an existing working store

If the demo is rerun after another task has added keys to this working object through commit_adata, this unconditional write_zarr replaces the store with the demo's in-memory object and deletes those additions. The new fixed path is explicitly advertised as a shared working object, so rerunning the documented top-to-bottom workflow can now erase downstream results. Refuse creation when the destination already exists, or require a new dated destination rather than overwriting it. This also violates the working-object preservation convention referenced by the agent guidance.

AGENTS.md reference: {{cookiecutter.project_name}}/AGENTS.md:L8-L9

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in bc55f6f: the demo now raises if the working object already exists, and says to write a new dated copy instead.

"print(f\"Saved to: {output_path}\")"
]
},
{
"cell_type": "markdown",
Expand Down
3 changes: 1 addition & 2 deletions {{cookiecutter.project_name}}/data/example_dataset/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# Dataset structure

`raw/`, `resources/`, `processed/` and `results/`, as described under *Data and notebook
conventions* in the top-level `README.md`.
`raw/`, `resources/` and `processed/`, as described under *Data* in the top-level `CONVENTIONS.md`.
Empty file.
Empty file.
2 changes: 1 addition & 1 deletion {{cookiecutter.project_name}}/pixi.toml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ session-info2 = "*"

# Local editable package for path helpers
{{ cookiecutter.package_name | replace('_', '-') }} = { path = ".", editable = true }
# Task paths and additive write-back for agent-run tasks (README: "Working with coding agents")
# Task directories, task paths and additive write-back (CONVENTIONS.md)
analysis-workflow = { git = "https://github.com/quadbio/analysis-workflow" }
igraph = ">=1.0.0, <2"
celltypist = ">=1.7.1, <2"
Expand Down
Loading
Loading