{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import subprocess, sys, numpy, pandas\n", "from importlib.metadata import version\n", "from packaging.version import Version\n", "\n", "pins = [f\"numpy=={numpy.__version__}\", f\"pandas=={pandas.__version__}\"]\n", "\n", "def install(*packages):\n", " subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", *packages, *pins],\n", " check=True)\n", "\n", "install(\"m3-sc\")\n", "if Version(version(\"scanpy\")) < Version(\"1.12.5\"):\n", " install(\"pynndescent<0.7\")" ], "id": "cell-00" }, { "cell_type": "markdown", "id": "cell-01", "metadata": {}, "source": [ "# Data augmentation\n", "\n", "m3's decoder is generative: by sampling the trained model we can synthesise new\n", "**donors** (for augmenting small cohorts) and new **cells**. This tutorial makes\n", "synthetic donors per condition with `model.augment()`, checks they match the real\n", "data, and resamples cells with `model.generate()`." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-02", "metadata": { "execution": { "iopub.execute_input": "2026-07-14T01:19:39.854042Z", "iopub.status.busy": "2026-07-14T01:19:39.853599Z", "iopub.status.idle": "2026-07-14T01:19:42.086754Z", "shell.execute_reply": "2026-07-14T01:19:42.086231Z" } }, "outputs": [], "source": [ "import os\n", "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "import m3\n", "\n", "OUT = \"./tutorial_out_demo/04_augmentation\"\n", "os.makedirs(OUT, exist_ok=True)" ] }, { "cell_type": "markdown", "id": "cell-03", "metadata": {}, "source": [ "## 1. Load the demo data" ] }, { "cell_type": "code", "execution_count": null, "id": "cell-04", "metadata": { "execution": { "iopub.execute_input": "2026-07-14T01:19:42.089330Z", "iopub.status.busy": "2026-07-14T01:19:42.089067Z", "iopub.status.idle": "2026-07-14T01:19:42.464184Z", "shell.execute_reply": "2026-07-14T01:19:42.463439Z" } }, "outputs": [], "source": [ "data = m3.datasets.liu_demo()\n", "print(data)" ] }, { "cell_type": "markdown", "id": "cell-05", "metadata": {}, "source": [ "## 2. Build and train the model\n", "\n", "Augmentation only needs the generator, so we skip the donor predictor\n", "(`donor_prediction=False`) to save time. `donor_key` is still set because the\n", "batch column drives the batch-stratified augmentation in the check below." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-06", "metadata": { "execution": { "iopub.execute_input": "2026-07-14T01:19:42.466031Z", "iopub.status.busy": "2026-07-14T01:19:42.465907Z", "iopub.status.idle": "2026-07-14T01:42:46.951468Z", "shell.execute_reply": "2026-07-14T01:42:46.951080Z" } }, "outputs": [], "source": [ "model = m3.M3(\n", " data,\n", " condition_keys=[\"cond_group\", \"Age_interval\"],\n", " target_condition=\"cond_group\",\n", " celltype_key=\"mergedcelltype\",\n", " batch_key=\"batch\",\n", " donor_key=\"sample_id\",\n", " embedding_dim=30,\n", ")\n", "model.train(max_epochs=500, donor_prediction=False)" ] }, { "cell_type": "markdown", "id": "cell-07", "metadata": {}, "source": [ "## 3. Synthesize new donors\n", "\n", "`model.augment(...)` samples the trained model to create brand-new synthetic\n", "donors for the conditions you ask for. It returns a dict with `expression`\n", "(per-modality synthetic cells) and `obs` (their condition and donor labels).\n", "\n", "- `conditions` / `n_donors`: which conditions to synthesise, and how many new\n", " donors for each.\n", "- `batch`: draw templates from one batch only, so the new donors carry that\n", " batch's character (used in the check below); omit it to draw from all batches." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-08", "metadata": { "execution": { "iopub.execute_input": "2026-07-14T01:42:46.953058Z", "iopub.status.busy": "2026-07-14T01:42:46.952924Z", "iopub.status.idle": "2026-07-14T01:42:47.029188Z", "shell.execute_reply": "2026-07-14T01:42:47.028820Z" } }, "outputs": [], "source": [ "aug = model.augment(conditions=[\"HC\", \"Severe\"], n_donors=[3, 3], tau=0.8)\n", "syn_rna = aug[\"expression\"][\"rna\"]\n", "syn_obs = aug[\"obs\"]\n", "print(\"synthetic cells:\", syn_rna.shape, \"per condition:\")\n", "print(syn_obs.groupby(\"cond_group\").size().to_string())" ] }, { "cell_type": "markdown", "id": "cell-09", "metadata": {}, "source": [ "## 4. Save the synthetic donors\n", "\n", "The synthetic expression and labels, in the three formats from the\n", "representation-learning tutorial." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-10", "metadata": { "execution": { "iopub.execute_input": "2026-07-14T01:42:47.030742Z", "iopub.status.busy": "2026-07-14T01:42:47.030618Z", "iopub.status.idle": "2026-07-14T01:42:47.218228Z", "shell.execute_reply": "2026-07-14T01:42:47.217851Z" } }, "outputs": [], "source": [ "import h5py\n", "import anndata as ad\n", "\n", "syn_obs.to_csv(os.path.join(OUT, \"synthetic_obs.csv\"), index=False)\n", "np.save(os.path.join(OUT, \"synthetic_rna.npy\"), syn_rna)\n", "with h5py.File(os.path.join(OUT, \"synthetic_rna.h5\"), \"w\") as f:\n", " f[\"data\"] = syn_rna\n", "ad.AnnData(X=syn_rna, obs=syn_obs.astype(str).reset_index(drop=True),\n", " var=pd.DataFrame(index=list(data.var[\"rna\"]))).write_h5ad(\n", " os.path.join(OUT, \"synthetic.h5ad\"))\n", "print(\"saved synthetic -> .npy / .h5 (['data']) / .h5ad in\", OUT)" ] }, { "cell_type": "markdown", "id": "cell-11", "metadata": {}, "source": [ "## 5. Check against the real data\n", "\n", "Do the synthetic donors look like real ones? We compare in the model's\n", "reconstruction space (where the synthetic cells live), so real and generated\n", "donors of the same condition should line up." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-12", "metadata": { "execution": { "iopub.execute_input": "2026-07-14T01:42:47.219778Z", "iopub.status.busy": "2026-07-14T01:42:47.219634Z", "iopub.status.idle": "2026-07-14T01:42:47.375780Z", "shell.execute_reply": "2026-07-14T01:42:47.375387Z" } }, "outputs": [], "source": [ "# Reconstruct the real cells once, then a quick sanity number: the per-gene mean\n", "# expression of real vs synthetic should correlate almost perfectly.\n", "recon = model.reconstruct(remove_batch=False)\n", "real_rna_all = np.nan_to_num(np.asarray(recon[\"rna\"], dtype=np.float32))\n", "real_adt_all = np.nan_to_num(np.asarray(recon[\"adt\"], dtype=np.float32))\n", "pearson = float(np.corrcoef(real_rna_all.mean(0), np.nan_to_num(syn_rna).mean(0))[0, 1])\n", "print(f\"per-gene mean expression Pearson r = {pearson:.3f}\")" ] }, { "cell_type": "markdown", "id": "cell-13", "metadata": {}, "source": [ "A UMAP per batch and modality, one dot per sample. Each sample is summarised by\n", "its mean expression **within every cell type shared by all samples** (the\n", "per-cell-type means concatenated into one vector), so differences in cell-type\n", "composition don't confound the comparison; features are then standardised. Real\n", "donors are open circles, M3-generated donors are crosses, and colour marks the\n", "condition. Synthetic samples should sit with the real samples of the same\n", "condition in the same batch." ] }, { "cell_type": "code", "id": "cell-14", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "import umap\n", "from sklearn.preprocessing import StandardScaler\n", "\n", "COLORS = {\"HC\": \"#E64B35\", \"Severe\": \"#4DBBD5\"}\n", "\n", "\n", "def celltype_pseudobulk(X, samples, celltypes):\n", " \"\"\"One row per sample: mean expression within each cell type shared by all\n", " samples, concatenated. Comparing per cell type keeps composition out of it.\"\"\"\n", " keys = pd.unique(samples)\n", " shared = sorted(set.intersection(*(set(celltypes[samples == k]) for k in keys)))\n", " rows = [np.concatenate([X[(samples == k) & (celltypes == c)].mean(0) for c in shared])\n", " for k in keys]\n", " return np.vstack(rows), keys\n", "\n", "\n", "def embed_2d(pb):\n", " \"\"\"Standardise each feature, then a Euclidean UMAP of the samples.\"\"\"\n", " return umap.UMAP(n_neighbors=min(10, pb.shape[0] - 1), min_dist=0.3,\n", " random_state=0).fit_transform(StandardScaler().fit_transform(pb))\n", "\n", "\n", "def draw_panel(ax, xy, conds, is_real):\n", " \"\"\"Real samples as open circles, generated as crosses, coloured by condition.\"\"\"\n", " for cond, color in COLORS.items():\n", " real = (conds == cond) & is_real\n", " ax.scatter(xy[real, 0], xy[real, 1], facecolors=\"none\", edgecolors=color, s=80, linewidths=1.5)\n", " syn = (conds == cond) & ~is_real\n", " ax.scatter(xy[syn, 0], xy[syn, 1], marker=\"x\", c=color, s=80, linewidths=2)\n", " ax.set_xticks([])\n", " ax.set_yticks([])" ] }, { "cell_type": "markdown", "id": "cell-15", "metadata": {}, "source": [ "**Embed** each batch and modality: augment on that batch, then pseudobulk and UMAP\n", "the real + synthetic samples together into one 2D layout per panel." ] }, { "cell_type": "code", "id": "cell-16", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "# real and synthetic cells share the same obs keys: sample_id (donor), cond_group,\n", "# and mergedcelltype.\n", "real_meta = model.cell_metadata[[\"sample_id\", \"cond_group\", \"batch\", \"mergedcelltype\"]].astype(str).reset_index(drop=True)\n", "real_by_mod = {\"RNA\": real_rna_all, \"ADT\": real_adt_all}\n", "batches = sorted(real_meta[\"batch\"].unique())\n", "N_DONORS = 5\n", "\n", "panels = [] # one entry per (batch, modality): its 2D layout + sample labels\n", "for col, batch in enumerate(batches):\n", " in_batch = (real_meta[\"batch\"] == batch).to_numpy()\n", " real = real_meta.loc[in_batch]\n", "\n", " # augment templated on THIS batch, so the synthetic donors carry its character\n", " ag = model.augment(conditions=[\"HC\", \"Severe\"], n_donors=[N_DONORS, N_DONORS],\n", " batch=batch, tau=0.8, seed=42 + col)\n", " syn = ag[\"obs\"].astype(str)\n", "\n", " # per-cell labels for this batch's real + synthetic samples\n", " samples = np.concatenate([real[\"sample_id\"].to_numpy(),\n", " (syn[\"cond_group\"] + \"/\" + syn[\"sample_id\"]).to_numpy()])\n", " celltypes = np.concatenate([real[\"mergedcelltype\"].to_numpy(), syn[\"mergedcelltype\"].to_numpy()])\n", " cond_of = dict(zip(samples, np.concatenate([real[\"cond_group\"].to_numpy(), syn[\"cond_group\"].to_numpy()])))\n", " real_of = dict(zip(samples, np.concatenate([np.full(len(real), True), np.full(len(syn), False)])))\n", "\n", " for row, modname in enumerate([\"RNA\", \"ADT\"]):\n", " X = np.vstack([real_by_mod[modname][in_batch], ag[\"expression\"][modname.lower()]])\n", " pb, keys = celltype_pseudobulk(X, samples, celltypes)\n", " conds = np.array([cond_of[k] for k in keys])\n", " is_real = np.array([real_of[k] for k in keys])\n", " panels.append(dict(row=row, col=col, batch=batch, modname=modname,\n", " xy=embed_2d(pb), conds=conds, is_real=is_real))" ] }, { "cell_type": "markdown", "id": "cell-17", "metadata": {}, "source": [ "**Draw** the panels: real donors as open circles, M3-generated as crosses, colour\n", "marks the condition, with a shared legend in a spare right-hand column." ] }, { "cell_type": "code", "id": "cell-18", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "fig, axes = plt.subplots(2, len(batches) + 1, figsize=(5 * (len(batches) + 1), 9),\n", " squeeze=False, gridspec_kw=dict(width_ratios=[1] * len(batches) + [0.6]))\n", "fig.suptitle(\"Liu (demo) sample-level UMAP: real (o) vs M3 generated (x)\", y=0.99)\n", "\n", "for p in panels:\n", " ax = axes[p[\"row\"], p[\"col\"]]\n", " draw_panel(ax, p[\"xy\"], p[\"conds\"], p[\"is_real\"])\n", " if p[\"row\"] == 0:\n", " ax.set_title(p[\"batch\"])\n", " ax.set_xlabel(f\"UMAP 1 ({p['modname']})\")\n", " if p[\"col\"] == 0:\n", " ax.set_ylabel(f\"UMAP 2 ({p['modname']})\")\n", "\n", "for ax in axes[:, -1]:\n", " ax.axis(\"off\")\n", "legend_ax = axes[0, -1]\n", "legend_ax.scatter([], [], facecolors=\"none\", edgecolors=\"#E64B35\", s=80, linewidths=1.5, label=\"Healthy (real)\")\n", "legend_ax.scatter([], [], facecolors=\"none\", edgecolors=\"#4DBBD5\", s=80, linewidths=1.5, label=\"Severe (real)\")\n", "legend_ax.scatter([], [], marker=\"x\", c=\"#E64B35\", s=80, linewidths=2, label=\"Healthy (M3 generated)\")\n", "legend_ax.scatter([], [], marker=\"x\", c=\"#4DBBD5\", s=80, linewidths=2, label=\"Severe (M3 generated)\")\n", "legend_ax.legend(loc=\"center left\", frameon=False, fontsize=9)\n", "\n", "fig.tight_layout(rect=(0, 0, 1, 0.97))\n", "fig.savefig(os.path.join(OUT, \"real_vs_synthetic_samplelevel.png\"), dpi=130, bbox_inches=\"tight\")\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "cell-19", "metadata": {}, "source": [ "## 6. Posterior-resampled cells\n", "\n", "`model.generate(...)` returns one synthetic cell per real cell (a 1:1 posterior\n", "resample), handy for noise-augmenting a training set at the cell level." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-20", "metadata": { "execution": { "iopub.execute_input": "2026-07-14T01:42:59.203790Z", "iopub.status.busy": "2026-07-14T01:42:59.203241Z", "iopub.status.idle": "2026-07-14T01:42:59.625640Z", "shell.execute_reply": "2026-07-14T01:42:59.625158Z" } }, "outputs": [], "source": [ "gen = model.generate(tau=0.8)\n", "print(\"generated:\", {k: v.shape for k, v in gen.items()})\n", "np.save(os.path.join(OUT, \"generated_rna.npy\"), gen[\"rna\"])" ] }, { "cell_type": "markdown", "id": "cell-21", "metadata": {}, "source": [ "**Done.** Synthetic donors per condition (checked against the real data) plus a\n", "1:1 posterior resample of the cells." ] } ], "metadata": { "jupytext": { "cell_metadata_filter": "-all", "main_language": "python", "notebook_metadata_filter": "-all" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.12" } }, "nbformat": 4, "nbformat_minor": 5 }