Quest 03 / 03 · ProjectTier 02 · Weekly

Bounty boards / Weekly · Week of November 23, 2026

Test how stable glioblastoma cell clusters are under Scanpy and scVI, logged in W&B

  • Scanpy
  • scvi-tools
  • single-cell analysis
  • experiment tracking
  • clustering evaluation
  • Time9 hours
  • Stages9
  • BoardWeek of November 23, 2026

Overview

You finish with a config-driven pipeline that clusters one public glioblastoma sample through a Scanpy PCA route and an scVI latent space, across five resolutions and five seeds each. All 50 runs are logged to W&B. The results show how often each cluster holds and which marker genes justify its label, and a rerun confirms the assignments reproduce.

  • A YAML config and a set of Python scripts that filter the sample, run both routes and sweep 50 settings.
  • Fifty W&B runs, online or offline, each with its config, cluster count, silhouette score and UMAP image.
  • A pairwise adjusted Rand index matrix and a table of mean ARI and stable cell share per route and resolution.
  • Marker gene tables that label each cluster you can support and leave the rest unassigned.
  • A write-up that names the clusters that held and the ones that split or merged, backed by a verified rerun.
01SETUP45 minutesSet up the project a...02DATA40 minutesDownload and inspect...03DATA45 minutesCompute quality metr...04BUILD60 minutesBuild the Scanpy PCA...05BUILD75 minutesTrain scVI on raw co...06BUILD90 minutesSweep both routes an...07TEST60 minutesMeasure stability wi...08TEST60 minutesRank marker genes an...09SHIP60 minutesProve a rerun matche...
DATAKaggle glioblastomamatrixCODEQC and filteringconfigTOOLScanpy PCA routeMODELscVI latent routeCODELeiden sweep, 50 runsSTOREW&B runsTESTARI and stable shareOUTMarkers and labels5,697 cellslog-normalizedraw countsconfig and UMAPlabels.csvmost stable setting
One sample, two clustering routes, 50 logged runs and the stability checks built on them.

Tools

  • Scanpy

    Scanpy is BSD-3-Clause software available without a subscription. Compute, storage and the rights attached to input datasets remain separate.

  • scvi-tools

    The package uses BSD-3-Clause licensing and is free to install. Dataset rights and local or rented GPU costs require separate assessment.

  • Weights & Biases SDK

    The Python SDK is MIT-licensed and free. The hosted and private W&B service has separate licenses, free and subscription plans, usage charges and enterprise sales terms.

Datasets

  • Human Glioblastoma Dataset Kaggle

    Glioblastoma cells from one donor provide the count matrix that both clustering routes analyze.

    Attribution 4.0 International (CC BY 4.0) · 20.6 MB · updated 2020-11-26

Before you begin

Python 3.13

Scanpy 1.13.0 requires Python 3.13 or newer. Check with python --version or py -3.13 --version on Windows. Free.

A computer with 8 GB of RAM or more

Everything runs on CPU. A GPU shortens scVI training but is optional.

A few GB of free disk

PyTorch and its dependencies take most of it; the dataset is 20 MB.

A W&B account (optional)

Offline mode needs no account. Syncing to the hosted service needs a free or paid W&B account.

A Kaggle account (optional)

Only needed if the direct download asks for credentials and you use the Kaggle CLI. Free.

Single-cell basics

You should know what a count matrix, a highly variable gene and a cluster marker are. Python and pandas at an intermediate level.

Stage 01 · setup45 minutes

Set up the project and the Python environment

Create an isolated Python 3.13 environment for the three tools and confirm each one imports.

Scanpy 1.13.0 requires Python 3.13 or newer, and scvi-tools 1.5.2 requires Python 3.12 or newer. Use Python 3.13 so both packages install from the same environment without a resolver conflict.

bashmacOS and Linux
mkdir gbm-stability && cd gbm-stability
mkdir -p config src data results
python3.13 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
powershellWindows PowerShell
mkdir gbm-stability; cd gbm-stability
mkdir config, src, data, results
py -3.13 -m venv .venv
.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip

Install the pinned versions this walkthrough was checked against. The leiden extra pulls in igraph and leidenalg, which Scanpy needs for Leiden clustering; tabulate lets pandas write Markdown tables for the write-up.

bash
pip install "scanpy[leiden]==1.13.0" "scvi-tools==1.5.2" "wandb==0.31.2" pyyaml tabulate
bash
python -c "from importlib.metadata import version as v; print(*(f'{p} {v(p)}' for p in ['scanpy', 'scvi-tools', 'wandb', 'anndata', 'torch']), sep='\n')"
Output
scanpy 1.13.0
scvi-tools 1.5.2
wandb 0.31.2
anndata <version>
torch <version>

Keep data, trained models and W&B run folders out of version control. The config file and the scripts are the parts worth committing.

text.gitignore
.venv/
data/
models/
models_rerun/
wandb/
__pycache__/
LayoutProject tree
gbm-stability/
  config/
    sweep.yaml  # every threshold and sweep setting
  data/
    raw/  # the three Kaggle files
  src/
    common.py
    prep.py
    routes.py
    try_route.py
    sweep.py
    stability.py
    markers.py
    rerun.py
    report.py
  results/  # CSV tables, plots and writeup.md
  models/  # one saved scVI model per seed
  wandb/  # one folder per logged run
Stage 01 Checkpoint

The version command prints scanpy 1.13.0, scvi-tools 1.5.2 and wandb 0.31.2 with no import error. The project folder has empty config, src, data and results folders and a .gitignore.

Stage 02 · data40 minutes

Download and inspect the glioblastoma matrix

Fetch the Kaggle files, confirm they are a 10x Matrix Market count matrix, and check the gene list for mitochondrial genes.

The Kaggle dataset is a 20 MB copy of a 10x Genomics sample: glioblastoma cells from one 57-year-old male donor, sequenced with the 3' v3 targeted Neuroscience Panel. The uploader states the cells were already filtered for healthy, live cells.

The public download endpoint below returned the archive without a login when this guide was checked. If it asks for credentials, use the Kaggle CLI route further down instead.

bashmacOS and Linux
curl -L -o data/glioblastoma.zip https://www.kaggle.com/api/v1/datasets/download/reminho/human-glioblastoma-dataset
unzip -o data/glioblastoma.zip -d data/raw
powershellWindows PowerShell
curl.exe -L -o data\glioblastoma.zip https://www.kaggle.com/api/v1/datasets/download/reminho/human-glioblastoma-dataset
Expand-Archive data\glioblastoma.zip -DestinationPath data\raw -Force

The Kaggle CLI needs an API token from your Kaggle account settings. Run kaggle auth login, or save the token in ~/.kaggle/access_token, then download and unzip in one command.

bash
pip install kaggle
kaggle datasets download reminho/human-glioblastoma-dataset -p data/raw --unzip

Look at the files before loading them. The layout is the older 10x format with uncompressed genes.tsv, barcodes.tsv and matrix.mtx, which sc.io.read_10x_mtx reads directly.

bashmacOS and Linux
head -n 3 data/raw/genes.tsv data/raw/barcodes.tsv
head -n 3 data/raw/matrix.mtx
powershellWindows PowerShell
Get-Content data\raw\genes.tsv -TotalCount 3
Get-Content data\raw\barcodes.tsv -TotalCount 3
Get-Content data\raw\matrix.mtx -TotalCount 3
Output
ENSG00000078369	GNB1	Gene Expression
ENSG00000078900	TP73	Gene Expression
...
AAACCCAAGGCGATAC-1
...
%%MatrixMarket matrix coordinate integer general
%metadata_json: {"software_version": "cellranger-4.0.0", "format_version": 2}
1186 5697 1850701

The size line of matrix.mtx reads genes, then barcodes, then nonzero entries. This is a targeted panel of 1,186 genes rather than the whole transcriptome, so check whether any mitochondrial genes made it in.

bash
python -c "import pandas as pd; g = pd.read_csv('data/raw/genes.tsv', sep='\t', header=None); print(g.shape); print(g[1].str.upper().str.startswith('MT-').sum(), 'MT- genes')"
Output
(1186, 3)
0 MT- genes
Stage 02 Checkpoint

data/raw holds barcodes.tsv, genes.tsv and matrix.mtx. The matrix header reports 1186 5697, and the gene check prints 0 MT- genes.

Stage 03 · data45 minutes

Compute quality metrics and write the filtering config

Load the matrix into AnnData, add QC metrics, filter with thresholds read from a config file and print the counts before and after.

Every choice in this project lives in one YAML file, so every script reads the same values. Write the whole config now; later stages only append the marker gene sets.

yamlconfig/sweep.yaml
# Every choice the sweep makes lives here, so a run can be repeated from this file alone.
data_dir: data/raw
filtered_path: data/filtered.h5ad
results_dir: results

filter:
  min_genes_per_cell: 100   # drops the emptiest droplets the uploader kept
  max_genes_per_cell: 700   # guards against likely doublets
  min_cells_per_gene: 3     # drops genes seen in almost no cells

scanpy_route:
  target_sum: 10000
  n_top_genes: 600          # the panel has 1,186 genes, so keep about half
  n_pcs: 30

scvi_route:
  n_latent: 10
  max_epochs: 200
  batch_size: 128

graph:
  n_neighbors: 15

sweep:
  routes: [scanpy, scvi]
  resolutions: [0.2, 0.4, 0.6, 0.8, 1.0]
  seeds: [0, 1, 2, 3, 4]
  compare_resolution: 0.6   # the resolution used for the pairwise ARI matrix

wandb:
  project: gbm-cluster-stability
  mode: offline             # change to online to sync as each run finishes

stability:
  stable_fraction: 0.8      # a cell is stable if it keeps its cluster in 80 percent of runs
  top_markers: 20

The two cell thresholds come from the data rather than from a tutorial default. In this sample the median cell has 310 detected genes; fewer than 1 percent exceed 700, and about 8 percent fall under 100.

pythonsrc/common.py
from pathlib import Path

import yaml

ROOT = Path(__file__).resolve().parents[1]


def load_config(path: str = "config/sweep.yaml") -> dict:
    with open(ROOT / path, encoding="utf-8") as handle:
        return yaml.safe_load(handle)


def results_dir(cfg: dict) -> Path:
    out = ROOT / cfg["results_dir"]
    out.mkdir(parents=True, exist_ok=True)
    return out

The preparation script reads the 10x folder, adds the mitochondrial flag only when such genes exist, filters, and saves the raw counts into a counts layer for scVI. In Scanpy 1.13, calculate_qc_metrics writes into the AnnData object when you pass out=False.

pythonsrc/prep.py
"""Load the 10x matrix, add QC metrics, filter and save the counts."""
import json

import scanpy as sc

from common import ROOT, load_config, results_dir

cfg = load_config()
thresholds = cfg["filter"]

adata = sc.io.read_10x_mtx(ROOT / cfg["data_dir"], var_names="gene_symbols")
print(f"loaded: {adata.n_obs} cells x {adata.n_vars} genes")

mito = adata.var_names.str.upper().str.startswith("MT-")
qc_vars = []
if mito.any():
    adata.var["mt"] = mito
    qc_vars = ["mt"]
else:
    print("no MT- genes in this gene list; skipping the mitochondrial fraction")

# out=False writes the metrics into adata.obs and adata.var in Scanpy 1.13.
sc.pp.calculate_qc_metrics(adata, qc_vars=qc_vars, percent_top=None, log1p=False, out=False)

before = (adata.n_obs, adata.n_vars)
print("filtering thresholds:", json.dumps(thresholds))
print(f"before filtering: {before[0]} cells x {before[1]} genes")

keep = (adata.obs["n_genes_by_counts"] >= thresholds["min_genes_per_cell"]) & (
    adata.obs["n_genes_by_counts"] <= thresholds["max_genes_per_cell"]
)
adata = adata[keep.to_numpy()].copy()
sc.pp.filter_genes(adata, min_cells=thresholds["min_cells_per_gene"])
print(f"after filtering: {adata.n_obs} cells x {adata.n_vars} genes")

adata.layers["counts"] = adata.X.copy()
adata.write_h5ad(ROOT / cfg["filtered_path"])

summary = {"thresholds": thresholds, "before": before, "after": (adata.n_obs, adata.n_vars),
           "mito_genes": int(mito.sum())}
(results_dir(cfg) / "filtering.json").write_text(json.dumps(summary, indent=2))
bash
python src/prep.py
Output
loaded: 5697 cells x 1186 genes
no MT- genes in this gene list; skipping the mitochondrial fraction
filtering thresholds: {"min_genes_per_cell": 100, "max_genes_per_cell": 700, "min_cells_per_gene": 3}
before filtering: 5697 cells x 1186 genes
after filtering: <cells> cells x <genes> genes
Stage 03 Checkpoint

The script prints the thresholds and the cell and gene counts before and after filtering. data/filtered.h5ad and results/filtering.json exist.

Stage 04 · build60 minutes

Build the Scanpy PCA route

Normalize, log-transform, pick highly variable genes, run PCA, build the neighbor graph and cluster with Leiden for a given resolution and seed.

Each route produces an embedding, and both routes share the graph and clustering code. Splitting the work this way lets the sweep build one graph per route and seed, then cluster it at every resolution without recomputing it.

DATAFiltered countsCODElog1p, HVG, PCAMODELscVI latent spaceCODENeighbor graph andUMAPOUTLeiden at 5resolutionsScanpy routeraw counts layerrng=seedrng=seed
One embedding and graph per route and seed, then Leiden at each resolution.

Scanpy 1.13 renamed several arguments, and the old names now raise deprecation warnings. The current signatures take seeds through rng, and neighbors takes use="obsm.X_route" instead of use_rep.

pythonsrc/routes.py
"""The two clustering routes. Both return labels for one resolution and one seed."""
import anndata as ad
import numpy as np
import scanpy as sc

from common import ROOT


def scanpy_embedding(adata: ad.AnnData, seed: int, cfg: dict) -> np.ndarray:
    """Normalize, log1p, pick variable genes and return the PCA coordinates."""
    route = cfg["scanpy_route"]
    work = adata.copy()
    sc.pp.normalize_total(work, target_sum=route["target_sum"])
    sc.pp.log1p(work)
    sc.pp.highly_variable_genes(work, n_top_genes=route["n_top_genes"])
    sc.pp.pca(work, n_comps=route["n_pcs"], rng=seed)
    return work.obsm["X_pca"]


EMBEDDINGS = {"scanpy": scanpy_embedding}  # stage 5 adds "scvi"


def build_graph(adata: ad.AnnData, route: str, seed: int, cfg: dict) -> ad.AnnData:
    """One embedding and one neighbor graph per route and seed."""
    work = adata.copy()
    work.obsm["X_route"] = EMBEDDINGS[route](adata, seed, cfg)
    sc.pp.neighbors(work, use="obsm.X_route", n_neighbors=cfg["graph"]["n_neighbors"], rng=seed)
    sc.tl.umap(work, rng=seed)
    return work


def leiden(graph: ad.AnnData, resolution: float, seed: int) -> np.ndarray:
    sc.tl.leiden(graph, resolution=resolution, rng=seed, flavor="igraph",
                 n_iterations=2, directed=False)
    return graph.obs["leiden"].astype(int).to_numpy()


def run_route(adata: ad.AnnData, route: str, resolution: float, seed: int, cfg: dict) -> np.ndarray:
    """The single entry point the sweep and the rerun check both call."""
    return leiden(build_graph(adata, route, seed, cfg), resolution, seed)

Leiden runs with the igraph flavor, two iterations and an undirected graph. The Scanpy docs flag the flavor and direction defaults as changing in Scanpy 2.0, so passing them explicitly keeps your labels fixed across that upgrade.

A small driver runs one route at one setting and clusters the same graph twice. The second call proves that a fixed seed gives fixed labels before you spend hours sweeping.

pythonsrc/try_route.py
"""Run one route once and check that the same seed gives the same clusters."""
import sys

import anndata as ad
import numpy as np

from common import ROOT, load_config
from routes import build_graph, leiden

route, resolution, seed = sys.argv[1], float(sys.argv[2]), int(sys.argv[3])
cfg = load_config()
adata = ad.read_h5ad(ROOT / cfg["filtered_path"])
graph = build_graph(adata, route, seed, cfg)
first, second = leiden(graph, resolution, seed), leiden(graph, resolution, seed)
sizes = np.bincount(first)
print(f"{route} r={resolution} seed={seed}: {len(sizes)} clusters, sizes {sorted(sizes.tolist(), reverse=True)}")
print("same seed, same labels:", np.array_equal(first, second))
bash
python src/try_route.py scanpy 0.6 0
Output
scanpy r=0.6 seed=0: <n> clusters, sizes [<largest>, ..., <smallest>]
same seed, same labels: True
Stage 04 Checkpoint

The Scanpy route prints a cluster count and the cluster sizes, and the last line reads same seed, same labels: True.

Stage 05 · build75 minutes

Train scVI on raw counts and cluster its latent space

Add an scVI embedding trained on the same filtered cells, cache one model per seed and cluster it with the shared graph code.

scVI models the raw counts directly, so it reads the counts layer that prep.py saved rather than the log-normalized values. Setting scvi.settings.seed before building the model seeds PyTorch, NumPy and Python's random module, so a retrain with the same seed starts from the same weights.

Add from pathlib import Path, import scvi and import torch to the imports at the top of src/routes.py. Then paste this function above the EMBEDDINGS line.

pythonsrc/routes.pyAdd above EMBEDDINGS
def scvi_embedding(adata: ad.AnnData, seed: int, cfg: dict) -> np.ndarray:
    """Train scVI on raw counts with this seed, or reuse the saved model."""
    route = cfg["scvi_route"]
    model_dir = ROOT / cfg.get("model_dir", "models") / f"scvi_seed{seed}"
    work = adata.copy()
    scvi.settings.seed = seed
    scvi.model.SCVI.setup_anndata(work, layer="counts")
    if model_dir.exists():
        model = scvi.model.SCVI.load(model_dir, adata=work, accelerator="cpu")
    else:
        model = scvi.model.SCVI(work, n_latent=route["n_latent"])
        accelerator = "gpu" if torch.cuda.is_available() else "cpu"
        model.train(max_epochs=route["max_epochs"], batch_size=route["batch_size"],
                    accelerator=accelerator, devices=1)
        model.save(model_dir, overwrite=True)
    return model.get_latent_representation()
pythonsrc/routes.pyReplace the EMBEDDINGS line
EMBEDDINGS = {"scanpy": scanpy_embedding, "scvi": scvi_embedding}

Each model is saved under models/scvi_seed0, models/scvi_seed1 and so on after training. The sweep reuses it for every resolution at that seed, so you train five models in total instead of twenty-five.

bash
python src/try_route.py scvi 0.6 0
Output
GPU available: False, used: False
...
Epoch 200/200: 100%|...| 200/200 [<time>, train_loss=<loss>]
scvi r=0.6 seed=0: <n> clusters, sizes [<largest>, ..., <smallest>]
same seed, same labels: True
Stage 05 Checkpoint

models/scvi_seed0 exists with a model.pt file, and the scVI route prints its cluster sizes followed by same seed, same labels: True.

Stage 06 · build90 minutes

Sweep both routes and log every run to W&B

Run five resolutions and five seeds per route, logging config, cluster count, silhouette score and a UMAP image for each of the 50 runs.

The W&B Python SDK is free and MIT-licensed, and offline mode needs no account. Each offline run writes a folder under wandb/ that you can upload later with wandb sync.

The silhouette score is computed on the embedding each route clustered, PCA coordinates for Scanpy and the scVI latent space for scVI. The two scores are not on a common scale, so compare them within a route rather than across routes.

pythonsrc/sweep.py
"""Sweep both routes over every resolution and seed and log each run to W&B."""
import json
from pathlib import Path

import anndata as ad
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd
import wandb
from sklearn.metrics import silhouette_score

from common import ROOT, load_config, results_dir
from routes import build_graph, leiden

cfg = load_config()
out = results_dir(cfg)
adata = ad.read_h5ad(ROOT / cfg["filtered_path"])
labels, rows = {}, []


def umap_figure(graph, cell_labels, title):
    fig, ax = plt.subplots(figsize=(5, 5))
    xy = graph.obsm["X_umap"]
    ax.scatter(xy[:, 0], xy[:, 1], c=cell_labels, cmap="tab20", s=2, linewidths=0)
    ax.set_title(title)
    ax.set_axis_off()
    return fig


for route in cfg["sweep"]["routes"]:
    for seed in cfg["sweep"]["seeds"]:
        graph = build_graph(adata, route, seed, cfg)  # one embedding per route and seed
        for resolution in cfg["sweep"]["resolutions"]:
            name = f"{route}-r{resolution}-s{seed}"
            cell_labels = leiden(graph, resolution, seed)
            n_clusters = int(len(set(cell_labels)))
            silhouette = (float(silhouette_score(graph.obsm["X_route"], cell_labels))
                          if n_clusters > 1 else float("nan"))
            run_config = {"route": route, "resolution": resolution, "seed": seed,
                          "filter": cfg["filter"], "graph": cfg["graph"],
                          "route_params": cfg[f"{route}_route"]}
            with wandb.init(project=cfg["wandb"]["project"], mode=cfg["wandb"]["mode"],
                            dir=ROOT, name=name, group=route, job_type="cluster",
                            config=run_config) as run:
                # A plain copy of the config inside the run folder, readable without syncing.
                (Path(run.dir) / "run_config.json").write_text(json.dumps(run_config, indent=2))
                fig = umap_figure(graph, cell_labels, name)
                run.log({"n_clusters": n_clusters, "silhouette": silhouette,
                         "umap": wandb.Image(fig)})
                plt.close(fig)
            labels[name] = cell_labels
            rows.append({"run": name, "route": route, "resolution": resolution, "seed": seed,
                         "n_clusters": n_clusters, "silhouette": silhouette})
            print(f"{name}: {n_clusters} clusters, silhouette {silhouette:.3f}")

pd.DataFrame(labels, index=adata.obs_names).to_csv(out / "labels.csv")
pd.DataFrame(rows).to_csv(out / "runs.csv", index=False)
print(f"logged {len(rows)} runs")

Every run gets the route as its group, which lets the W&B workspace split the table into two sets. The script also writes run_config.json into each run folder, so the config is readable offline without syncing.

bashmacOS and Linux; set WANDB_SILENT=true to hide the per-run banner
python src/sweep.py
Output
scanpy-r0.2-s0: <n> clusters, silhouette <score>
scanpy-r0.4-s0: <n> clusters, silhouette <score>
...
scvi-r1.0-s4: <n> clusters, silhouette <score>
logged 50 runs

To sync as you go, run wandb login, which stores the API key in your user profile outside the project, and set mode: online in the YAML. To upload offline runs afterwards, run the sync command from the project folder.

bash
wandb login
wandb sync --yes
Stage 06 Checkpoint

The script ends with logged 50 runs. wandb/ holds 50 run folders, each with files/run_config.json, and results/runs.csv lists 50 rows with route, resolution, seed, cluster count and silhouette.

Stage 07 · test60 minutes

Measure stability with the adjusted Rand index

Compute ARI between seeds within each route and between routes at matched resolutions, the stable share of cells and the pairwise ARI matrix plot.

The adjusted Rand index compares two clusterings while ignoring cluster names, so cluster 3 in one run can match cluster 7 in another. It is 1.0 for identical partitions and near 0.0 for random ones.

The stable share needs aligned names, because a cell keeps its cluster only if the names line up. Each seed's labels are mapped onto seed 0 by maximum overlap with linear_sum_assignment, and a cell is stable when its most common label appears in at least 80 percent of the five runs.

pythonsrc/stability.py
"""Adjusted Rand index within and between routes, and the stable share of cells."""
import itertools
import json

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import wandb
from scipy.optimize import linear_sum_assignment
from sklearn.metrics import adjusted_rand_score

from common import ROOT, load_config, results_dir

cfg = load_config()
out = results_dir(cfg)
labels = pd.read_csv(out / "labels.csv", index_col=0)
seeds, resolutions = cfg["sweep"]["seeds"], cfg["sweep"]["resolutions"]
threshold = cfg["stability"]["stable_fraction"]


def run_name(route, resolution, seed):
    return f"{route}-r{resolution}-s{seed}"


def align(reference, other):
    """Rename clusters in `other` to the reference cluster they overlap most."""
    table = pd.crosstab(other, reference)
    rows, cols = linear_sum_assignment(-table.to_numpy())
    mapping = {table.index[r]: table.columns[c] for r, c in zip(rows, cols)}
    return np.array([mapping.get(x, -1 - x) for x in other])  # unmatched clusters stay distinct


def stable_share(route, resolution):
    runs = [labels[run_name(route, resolution, s)].to_numpy() for s in seeds]
    aligned = np.vstack([runs[0]] + [align(runs[0], r) for r in runs[1:]])
    top = pd.DataFrame(aligned.T).apply(lambda row: row.value_counts().iloc[0], axis=1)
    return float((top / len(seeds) >= threshold).mean())


rows = []
for route in cfg["sweep"]["routes"]:
    for resolution in resolutions:
        scores = [adjusted_rand_score(labels[run_name(route, resolution, a)], labels[run_name(route, resolution, b)])
                  for a, b in itertools.combinations(seeds, 2)]
        rows.append({"route": route, "resolution": resolution, "mean_ari_seeds": np.mean(scores),
                     "sd_ari_seeds": np.std(scores), "stable_share": stable_share(route, resolution)})
within = pd.DataFrame(rows)

cross = pd.DataFrame([{"resolution": r, "cross_route_ari": np.mean(
    [adjusted_rand_score(labels[run_name("scanpy", r, a)], labels[run_name("scvi", r, b)])
     for a in seeds for b in seeds])} for r in resolutions])
within.to_csv(out / "stability.csv", index=False)
cross.to_csv(out / "cross_route.csv", index=False)
print(within.round(3).to_string(index=False))
print(cross.round(3).to_string(index=False))

The second half draws the matrix of every pair of the ten runs at the comparison resolution, picks the most stable resolution per route and logs a summary run to W&B. Append it to the same file.

pythonsrc/stability.pyAppend to src/stability.py
# Pairwise ARI between every run at one resolution, drawn as a matrix plot.
res = cfg["sweep"]["compare_resolution"]
names = [run_name(route, res, s) for route in cfg["sweep"]["routes"] for s in seeds]
matrix = pd.DataFrame([[adjusted_rand_score(labels[a], labels[b]) for b in names] for a in names],
                      index=names, columns=names)
matrix.to_csv(out / f"ari_matrix_r{res}.csv")
fig, ax = plt.subplots(figsize=(8, 7))
image = ax.imshow(matrix.to_numpy(), vmin=0, vmax=1, cmap="viridis")
ax.set_xticks(range(len(names)), names, rotation=90, fontsize=7)
ax.set_yticks(range(len(names)), names, fontsize=7)
for i, j in itertools.product(range(len(names)), repeat=2):
    ax.text(j, i, f"{matrix.iat[i, j]:.2f}", ha="center", va="center", fontsize=5, color="white")
fig.colorbar(image, label="adjusted Rand index")
ax.set_title(f"Pairwise ARI at resolution {res}")
fig.tight_layout()
fig.savefig(out / f"ari_matrix_r{res}.png", dpi=150)

# The most stable setting per route: highest mean ARI across seeds.
best = {route: float(group.sort_values(["mean_ari_seeds", "stable_share"]).iloc[-1]["resolution"])
        for route, group in within.groupby("route")}
(out / "best.json").write_text(json.dumps(best, indent=2))
print("most stable resolution per route:", best)

with wandb.init(project=cfg["wandb"]["project"], mode=cfg["wandb"]["mode"], dir=ROOT,
                name="stability-summary", job_type="analysis", config=cfg["stability"]) as run:
    run.log({"ari_matrix": wandb.Image(fig), "stability": wandb.Table(dataframe=within),
             "cross_route": wandb.Table(dataframe=cross)})
bash
python src/stability.py
Output
 route  resolution  mean_ari_seeds  sd_ari_seeds  stable_share
scanpy         0.2         <ari>          <sd>         <share>
...
  scvi         1.0         <ari>          <sd>         <share>
 resolution  cross_route_ari
        0.2            <ari>
...
most stable resolution per route: {'scanpy': <res>, 'scvi': <res>}
The numbers the bounty evaluation asks for and where they land.
MeasureFileColumn
Mean ARI across seeds, per route and resolutionresults/stability.csvmean_ari_seeds
Stable share of cells, per route and resolutionresults/stability.csvstable_share
Cross-route ARI at matched resolutionresults/cross_route.csvcross_route_ari
Pairwise ARI at one resolutionresults/ari_matrix_r0.6.png10 by 10 matrix
Stage 07 Checkpoint

results/ari_matrix_r0.6.png shows a 10 by 10 grid with 1.00 on the diagonal and both routes on each axis. results/stability.csv has ten rows and results/best.json names one resolution per route.

Stage 08 · test60 minutes

Rank marker genes and label the clusters you can support

Rank markers for the most stable setting of each route, measure top-20 overlap between matched clusters and label clusters only from known markers.

Both routes are ranked on the same log-normalized counts with the Wilcoxon test. Any difference in their markers then comes from the clustering, since the expression values are identical.

The marker sets below contain only genes present in this panel; common markers such as PTPRC, C1QA, VWF and TOP2A are absent from it. Append the block to the config.

yamlconfig/sweep.yamlAppend to config/sweep.yaml
# Known markers that are present in this 1,186-gene neuroscience panel.
# A cluster takes a label when at least min_hits of its top markers come from one set.
labeling:
  min_hits: 2
  marker_sets:
    myeloid: [P2RY12, CX3CR1, AIF1, CD163, CD14, TYROBP, HLA-DRA, SPP1]
    oligodendrocyte: [MBP, PLP1, MOG, MAG]
    astrocyte_like: [GFAP, AQP4, SLC1A3, ALDH1L1, SOX9]
    opc_like_tumor: [OLIG2, PDGFRA, SOX2]
    mesenchymal_like_tumor: [CD44, CHI3L1, TNC]
    endothelial: [PECAM1, CLDN5, FLT1]
    neuron: [SNAP25, RBFOX3, SYT1, GAD1, SLC17A7]
    cycling: [MKI67]
pythonsrc/markers.py
"""Rank marker genes for the most stable setting of each route, compare them and label clusters."""
import json

import anndata as ad
import pandas as pd
import scanpy as sc
from scipy.optimize import linear_sum_assignment

from common import ROOT, load_config, results_dir

cfg = load_config()
out = results_dir(cfg)
labels = pd.read_csv(out / "labels.csv", index_col=0)
best = json.loads((out / "best.json").read_text())
top_n, label_cfg = cfg["stability"]["top_markers"], cfg["labeling"]

# Both routes are ranked on the same log-normalized counts, so only the clustering differs.
adata = ad.read_h5ad(ROOT / cfg["filtered_path"])
sc.pp.normalize_total(adata, target_sum=cfg["scanpy_route"]["target_sum"])
sc.pp.log1p(adata)


def top_markers(route):
    key = f"{route}-r{best[route]}-s0"
    adata.obs[route] = pd.Categorical(labels.loc[adata.obs_names, key].astype(str))
    sc.tl.rank_genes_groups(adata, groupby=route, method="wilcoxon")
    table = sc.get.rank_genes_groups_df(adata, group=None)
    table = table[(table["logfoldchanges"] > 0) & (table["pvals_adj"] < 0.05)]
    return {str(g): list(t.sort_values("scores", ascending=False)["names"].head(top_n))
            for g, t in table.groupby("group", observed=True)}


def label_cluster(genes):
    hits = {name: [g for g in genes if g in members] for name, members in label_cfg["marker_sets"].items()}
    name, support = max(hits.items(), key=lambda item: len(item[1]))
    if len(support) >= label_cfg["min_hits"]:
        return name, support
    return "unassigned", []


markers = {route: top_markers(route) for route in cfg["sweep"]["routes"]}
for route, clusters in markers.items():
    rows = []
    for cluster, genes in sorted(clusters.items(), key=lambda kv: int(kv[0])):
        label, support = label_cluster(genes)
        rows.append({"cluster": cluster, "n_cells": int((adata.obs[route] == cluster).sum()),
                     "label": label, "supporting_markers": " ".join(support),
                     "top_markers": " ".join(genes)})
    table = pd.DataFrame(rows)
    table.to_csv(out / f"labels_{route}.csv", index=False)
    print(f"\n{route} at resolution {best[route]}")
    print(table[["cluster", "n_cells", "label", "supporting_markers"]].to_string(index=False))

The second half matches each Scanpy cluster to the scVI cluster that shares the most cells. For each pair it reports the share of the top 20 markers the two clusters have in common.

pythonsrc/markers.pyAppend to src/markers.py
# Match scanpy clusters to scvi clusters by shared cells, then compare their top markers.
cells = pd.crosstab(adata.obs["scanpy"], adata.obs["scvi"])
rows, cols = linear_sum_assignment(-cells.to_numpy())
pairs = []
for r, c in zip(rows, cols):
    a, b = str(cells.index[r]), str(cells.columns[c])
    shared = set(markers["scanpy"].get(a, [])) & set(markers["scvi"].get(b, []))
    pairs.append({"scanpy_cluster": a, "scvi_cluster": b, "shared_cells": int(cells.iat[r, c]),
                  "marker_overlap": len(shared) / top_n, "shared_markers": " ".join(sorted(shared))})
pairs = pd.DataFrame(pairs).sort_values("marker_overlap", ascending=False)
pairs.to_csv(out / "marker_overlap.csv", index=False)
print("\nmatched clusters and top-marker overlap")
print(pairs.drop(columns="shared_markers").round(2).to_string(index=False))
bash
python src/markers.py
Output
scanpy at resolution <res>
cluster  n_cells  label  supporting_markers
      0   <n>    <label or unassigned>  <genes>
...
matched clusters and top-marker overlap
scanpy_cluster scvi_cluster  shared_cells  marker_overlap
...         ...           <n>           <0 to 1>

A cluster without at least two hits from one set stays unassigned. Leave it that way in the report; a label without marker support would defeat the point of the exercise.

Stage 08 Checkpoint

results/labels_scanpy.csv and results/labels_scvi.csv list every cluster with a label and, for each labeled cluster, the supporting marker genes. results/marker_overlap.csv gives a marker_overlap value for each matched pair.

Stage 09 · ship60 minutes

Prove a rerun matches, then write the report

Rerun one saved configuration from scratch, track which clusters held, split or merged, and publish the W&B report or exported run table.

The rerun script retrains scVI into a separate models_rerun folder instead of loading the cached model. A match therefore shows that the whole route reproduces, training included.

pythonsrc/rerun.py
"""Rerun one saved configuration from scratch and compare it with the sweep."""
import shutil
import sys

import anndata as ad
import numpy as np
import pandas as pd

from common import ROOT, load_config, results_dir
from routes import run_route

name = sys.argv[1] if len(sys.argv) > 1 else "scvi-r0.6-s2"
route, res, seed = name.split("-")
resolution, seed = float(res[1:]), int(seed[1:])

cfg = load_config()
cfg["model_dir"] = "models_rerun"  # retrain scVI instead of loading the saved model
shutil.rmtree(ROOT / cfg["model_dir"], ignore_errors=True)

adata = ad.read_h5ad(ROOT / cfg["filtered_path"])
fresh = run_route(adata, route, resolution, seed, cfg)
saved = pd.read_csv(results_dir(cfg) / "labels.csv", index_col=0)[name].to_numpy()
same = int((fresh == saved).sum())
print(f"{name}: {same} of {len(saved)} cells have the same cluster id")
print("identical" if np.array_equal(fresh, saved) else "DIFFERENT")
bash
python src/rerun.py scvi-r0.6-s2
python src/rerun.py scanpy-r0.4-s1
Output
scvi-r0.6-s2: <cells> of <cells> cells have the same cluster id
identical
scanpy-r0.4-s1: <cells> of <cells> cells have the same cluster id
identical

The report script takes each cluster at the most stable setting and follows it through the other 49 runs. A cluster is split when fewer than 80 percent of its cells stay together in some run, and merged when it shares its main cluster with another one.

pythonsrc/report.py
"""Track each labeled cluster through all runs and draft the write-up tables."""
import json

import pandas as pd

from common import load_config, results_dir

cfg = load_config()
out = results_dir(cfg)
labels = pd.read_csv(out / "labels.csv", index_col=0)
best = json.loads((out / "best.json").read_text())
threshold = cfg["stability"]["stable_fraction"]
lines = ["# Glioblastoma cluster stability", ""]


def fate(reference, run):
    """For each reference cluster: share of its cells kept together, and whether it merged."""
    table = pd.crosstab(reference, run)
    target = table.idxmax(axis=1)
    kept = table.max(axis=1) / table.sum(axis=1)
    merged = target.duplicated(keep=False)
    return kept, merged


for route in cfg["sweep"]["routes"]:
    reference = labels[f"{route}-r{best[route]}-s0"]
    named = pd.read_csv(out / f"labels_{route}.csv").set_index("cluster")
    others = [c for c in labels.columns if c != reference.name]
    kept = pd.DataFrame({c: fate(reference, labels[c])[0] for c in others})
    merged = pd.DataFrame({c: fate(reference, labels[c])[1] for c in others})
    summary = pd.DataFrame({
        "label": named["label"].reindex(kept.index).fillna("unassigned"),
        "min_kept": kept.min(axis=1).round(2),
        "runs_split": (kept < threshold).sum(axis=1),
        "runs_merged": merged.sum(axis=1),
    })
    summary["fate"] = "held"
    summary.loc[summary["runs_split"] > 0, "fate"] = "split"
    summary.loc[summary["runs_merged"] > 0, "fate"] = "merged"
    summary.loc[(summary["runs_split"] > 0) & (summary["runs_merged"] > 0), "fate"] = "split and merged"
    summary.to_csv(out / f"fate_{route}.csv")
    lines += [f"## {route} route, reference resolution {best[route]}, seed 0", "",
              summary.to_markdown(), ""]

stability = pd.read_csv(out / "stability.csv")
cross = pd.read_csv(out / "cross_route.csv")
lines += ["## Stability by route and resolution", "", stability.round(3).to_markdown(index=False), "",
          "## Cross-route ARI", "", cross.round(3).to_markdown(index=False), "",
          "## Notes", "", "Write two or three paragraphs here on what held and what moved.", ""]
(out / "writeup.md").write_text("\n".join(lines), encoding="utf-8")
print("\n".join(lines[:40]))
bash
python src/report.py
Output
# Glioblastoma cluster stability

## scanpy route, reference resolution <res>, seed 0

| scanpy-r<res>-s0 | label | min_kept | runs_split | runs_merged | fate |
...
## Notes

Open results/writeup.md and replace the placeholder notes with a few paragraphs of your own. Name the clusters marked held, then explain the split and merged ones with the resolution where each first moved.

For a W&B report, sync the runs and open the project workspace. Then follow the in-app steps below.

  1. Open the project gbm-cluster-stability in the W&B app.
  2. Click Create report in the upper-right corner of the workspace.
  3. Select the charts to start with, including the umap images and the n_clusters and silhouette panels.
  4. Add the stability-summary run panels with the ARI matrix and the stability tables.
  5. Paste the notes from results/writeup.md, credit the dataset source, and find the saved draft under the Reports tab.
Stage 09 Checkpoint

Both rerun commands print identical. results/writeup.md contains a fate table for each route and your notes, and either a W&B report or the exported CSV tables cover both routes.

Troubleshooting

pip reports that no matching distribution exists for scanpy==1.13.0.

Your environment runs a Python older than 3.13. Delete .venv, recreate it with python3.13 -m venv .venv or py -3.13 -m venv .venv, and install again.

ImportError or ModuleNotFoundError for leidenalg or igraph when Leiden runs.

The leiden extra was skipped. Run pip install "scanpy[leiden]==1.13.0" with the quotes, which zsh needs around square brackets.

A FutureWarning says The argument use_rep is deprecated and will be removed in the future.

The code came from an older Scanpy tutorial. In Scanpy 1.13 pass use="obsm.X_route" to sc.pp.neighbors and rng=seed to pca, neighbors, umap and leiden.

curl saves a small file and unzip says it is not a zip archive.

Kaggle returned an error page instead of the data. Open the saved file in a text editor to read the message, then use kaggle auth login and the kaggle datasets download command.

The scVI step loads an old model after you change n_latent or max_epochs, or fails with a shape mismatch.

Saved models in models/ are reused by seed. Delete the models folder after any change to the scVI settings or the filtering thresholds, then rerun the sweep.

The rerun prints DIFFERENT for an scVI configuration.

Check that the rerun and the sweep used the same device and the same config file. GPU training can be nondeterministic; run both on CPU with CUDA_VISIBLE_DEVICES set to an empty string.

wandb sync says there is nothing to sync, or asks for an API key.

Run it from the project folder that contains wandb/, after wandb login. Use wandb sync --dry-run to list the local runs it can see.

Training or the sweep runs out of memory on a small laptop.

Lower batch_size in the scvi_route block and close other programs. The sweep keeps one graph in memory at a time, so the peak comes from scVI training rather than from the number of runs.

Done when

  • The sweep logs at least 50 runs, each with its config visible in the W&B run table or the offline run folder.
  • A matrix plot shows the adjusted Rand index between every pair of runs at one resolution.
  • The notebook prints the filtering thresholds and the cell counts before and after filtering.
  • Every labeled cluster lists the marker genes that justify its label.
  • Rerunning one saved configuration reproduces the same cluster assignments.

Deliverables

  • A notebook or script package with the config file that drives the sweep.
  • A W&B report or exported run table covering both routes.
  • A short write-up naming the clusters that held across every setting and the ones that split or merged.

How to measure it

Mean adjusted Rand index across seeds for each route and resolution, plus the cross-route index at the chosen resolution. A cell counts as stable when it keeps the same cluster in at least 80 percent of runs; report the stable share of cells for each route.

Going further

  • Swap the five seeds for bootstrap resamples of 90 percent of cells and see whether the stable share drops more for one route than the other.
  • Vary n_neighbors and n_top_genes in a second sweep to learn whether the graph or the gene selection moves clusters more than the resolution does.
  • Score each cell against the marker sets with sc.tl.score_genes and compare those per-cell scores with the cluster-level labels.
  • Repeat the whole pipeline on the whole-transcriptome version of the same 10x sample and check whether the panel restriction changed which clusters held.

Bounty stretch goals

  • Add a second public glioblastoma sample and integrate the two with scVI's batch handling, then check whether your labels carry over.
  • Run the resolution sweep as a W&B sweep agent instead of a Python loop and compare the logged results.
  • Compare your marker-based labels with an automatic cell-type annotation tool and count the disagreements.

References

Reporting behind this quest

An AI guide writer drafted this walkthrough against the official documentation above, automated template and style checks validated every block, and an independent AI reviewer verified commands, flags and claims before publication.