{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Colab setup - run this first, then switch the runtime to R\n", "# (Runtime > Change runtime type > R). Precompiled Linux binaries via Posit P3M\n", "# keep the install to a couple of minutes instead of compiling from source.\n", "local({\n", " cn <- tryCatch(system(\"lsb_release -cs\", intern = TRUE), error = function(e) \"jammy\")\n", " options(repos = c(CRAN = sprintf(\"https://packagemanager.posit.co/cran/__linux__/%s/latest\", cn)),\n", " HTTPUserAgent = sprintf(\"R/%s R (%s)\", getRversion(),\n", " paste(getRversion(), R.version$platform, R.version$arch, R.version$os)))\n", "})\n", "if (!requireNamespace(\"BiocManager\", quietly = TRUE)) install.packages(\"BiocManager\")\n", "BiocManager::install(\n", " c(\"SingleCellExperiment\", \"SummarizedExperiment\", \"MultiAssayExperiment\",\n", " \"S4Vectors\", \"basilisk\"),\n", " update = FALSE, ask = FALSE)\n", "install.packages(c(\"remotes\", \"reticulate\", \"Matrix\", \"ggplot2\"))\n", "remotes::install_github(\"PYangLab/M3\", subdir = \"m3-r\")\n", "# The first m3_train() builds the bundled Python engine via basilisk (a few\n", "# minutes on first run); afterwards it is cached for the session." ], "id": "cell-00" }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Data augmentation\n", "\n", "m3's decoder is generative: by sampling the trained model we can synthesise new **donors** (for augmenting small cohorts) and new **cells**. This tutorial makes synthetic donors per condition with `m3_augment()`, checks they match the real data, and resamples cells with `m3_generate()`.\n", "\n", "## 1. Load the demo dataset" ], "id": "cell-01" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "library(m3)\n", "library(ggplot2)\n", "set.seed(0)\n", "data <- m3_demo()\n", "data" ], "id": "cell-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Build and train the model\n", "\n", "Augmentation only needs the generator, so we skip the donor predictor (`donor_prediction = FALSE`) to save time." ], "id": "cell-03" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#To save time, users can set max_epochs to 100 for test.\n", "model <- m3_train(\n", " data,\n", " condition_keys = c(\"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 = 30L,\n", " donor_prediction = FALSE,\n", " max_epochs = 500L,\n", " seed = 0L\n", ")" ], "id": "cell-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Synthesize new donors per condition\n", "\n", "`m3_augment(...)` samples the trained model to create brand-new synthetic donors for the conditions you ask for. It returns a list with `expression` (per-modality synthetic cells) and `obs` (their condition and donor labels).\n", "\n", "- `conditions` / `n_donors`: which conditions to synthesise, and how many new donors for each.\n", "- `batch`: draw templates from one batch only, so the new donors carry that batch's character (used in the check below); omit it to draw from all batches." ], "id": "cell-05" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "aug <- m3_augment(model, conditions = c(\"HC\", \"Severe\"), n_donors = c(3L, 3L), tau = 0.8)\n", "syn_rna <- aug$expression$rna\n", "cat(\"synthetic cells:\", paste(dim(syn_rna), collapse = \"x\"), \"\\n\")\n", "\n", "print(table(aug$obs$cond_group))" ], "id": "cell-06" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Check against the real data\n", "\n", "Do the synthetic donors look like real ones? We compare in the model's reconstruction space (where the synthetic cells live). A UMAP per batch and modality, one dot per sample: each sample is summarised by its mean expression within every shared cell type (so composition differences don't confound), then features are standardised. Real donors are open circles, m3-generated donors are crosses, colour marks the condition. Synthetic samples should sit with the real samples of the same condition in the same batch." ], "id": "cell-07" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "real_recon <- m3_reconstruct(model, remove_batch = FALSE)$rna\n", "real_recon[is.na(real_recon)] <- 0\n", "m_real <- colMeans(real_recon)\n", "m_syn <- colMeans(replace(syn_rna, is.na(syn_rna), 0))\n", "pearson <- stats::cor(m_real, m_syn)\n", "cat(sprintf(\"per-gene mean expression Pearson r = %.3f\\n\", pearson))" ], "id": "cell-08" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compare samples in the model's reconstruction (decoder) space, the same space the\n", "# generated cells live in. Each sample is summarised per shared cell type (so\n", "# composition differences don't confound), then features are standardised.\n", "recon <- m3_reconstruct(model, remove_batch = FALSE)\n", "obs <- m3_cell_metadata(model) # row-aligned with the reconstruction\n", "real_by_mod <- list(RNA = replace(recon$rna, is.na(recon$rna), 0),\n", " ADT = replace(recon$adt, is.na(recon$adt), 0))\n", "\n", "# one row per sample: mean expression within each cell type shared by all samples\n", "celltype_pseudobulk <- function(X, samples, celltypes) {\n", " keys <- unique(samples)\n", " shared <- Reduce(intersect, lapply(keys, function(k) unique(celltypes[samples == k])))\n", " M <- t(vapply(keys, function(k)\n", " unlist(lapply(shared, function(ct) colMeans(X[samples == k & celltypes == ct, , drop = FALSE]))),\n", " numeric(ncol(X) * length(shared))))\n", " list(M = M, keys = keys)\n", "}\n", "\n", "# standardise each feature, then a Euclidean UMAP of the samples\n", "embed_2d <- function(pb, dev) {\n", " Z <- scale(pb)\n", " Z <- Z[, colSums(is.na(Z)) == 0, drop = FALSE] # drop zero-variance features\n", " m3_umap(Z, method = \"umap\", n_neighbors = min(10L, nrow(Z) - 1L),\n", " min_dist = 0.3, metric = \"euclidean\", random_state = 0L, device = dev)\n", "}" ], "id": "cell-09" }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Embed** each batch and modality: augment on that batch, then pseudobulk and UMAP the real + synthetic samples together into one layout per panel." ], "id": "cell-10" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "batches <- sort(unique(as.character(obs$batch)))\n", "N_DONORS <- 5L\n", "panels <- list()\n", "for (ci in seq_along(batches)) {\n", " b <- batches[ci]\n", " in_b <- as.character(obs$batch) == b\n", "\n", " # augment templated on THIS batch, so the synthetic donors carry its character\n", " ag <- m3_augment(model, conditions = c(\"HC\", \"Severe\"),\n", " n_donors = c(N_DONORS, N_DONORS), batch = b, tau = 0.8, seed = 42L + ci - 1L)\n", "\n", " # real and synthetic cells share obs keys: sample_id (donor), cond_group, mergedcelltype\n", " samples <- c(as.character(obs$sample_id[in_b]), paste0(ag$obs$cond_group, \"/\", ag$obs$sample_id))\n", " celltypes <- c(as.character(obs$mergedcelltype[in_b]), as.character(ag$obs$mergedcelltype))\n", " cond <- c(as.character(obs$cond_group[in_b]), as.character(ag$obs$cond_group))\n", " is_real <- c(rep(TRUE, sum(in_b)), rep(FALSE, nrow(ag$obs)))\n", " cond_of <- tapply(cond, samples, function(x) x[1])\n", " real_of <- tapply(is_real, samples, function(x) x[1])\n", "\n", " for (md in c(\"RNA\", \"ADT\")) {\n", " X <- rbind(real_by_mod[[md]][in_b, , drop = FALSE], ag$expression[[tolower(md)]])\n", " pb <- celltype_pseudobulk(X, samples, celltypes)\n", " xy <- embed_2d(pb$M, model$device)\n", " panels[[length(panels) + 1L]] <- data.frame(\n", " UMAP1 = xy[, 1], UMAP2 = xy[, 2],\n", " cond = cond_of[pb$keys], kind = ifelse(real_of[pb$keys], \"real\", \"generated\"),\n", " panel = paste0(\"Batch \", b, \" (\", md, \")\"))\n", " }\n", "}\n", "plot_df <- do.call(rbind, panels)" ], "id": "cell-11" }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Draw** the panels with ggplot: real donors as open circles, m3-generated as crosses, faceted by batch and modality." ], "id": "cell-12" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cols <- c(HC = \"#E64B35\", Severe = \"#4DBBD5\")\n", "ggplot() +\n", " geom_point(data = subset(plot_df, kind == \"real\"),\n", " aes(UMAP1, UMAP2, colour = cond), shape = 1, size = 3, stroke = 1.2) +\n", " geom_point(data = subset(plot_df, kind == \"generated\"),\n", " aes(UMAP1, UMAP2, colour = cond), shape = 4, size = 3, stroke = 1.4) +\n", " scale_colour_manual(values = cols, name = NULL) +\n", " facet_wrap(~ panel, scales = \"free\", ncol = length(batches)) +\n", " labs(title = \"Liu et al — sample-level UMAP: real (o) vs m3 generated (x)\") +\n", " theme_classic() +\n", " theme(axis.text = element_blank(), axis.ticks = element_blank())" ], "id": "cell-13" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Posterior-resampled cells (`generate`)\n", "\n", "`m3_generate()` returns one synthetic cell per real cell (a 1:1 posterior resample), handy for noise-augmenting a training set at the cell level." ], "id": "cell-14" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "gen <- m3_generate(model, tau = 0.8)\n", "cat(\"generated:\", paste(names(gen), sapply(gen, function(m) paste(dim(m), collapse = \"x\")),\n", " sep = \"=\", collapse = \" \"), \"\\n\")" ], "id": "cell-15" }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Done.** Synthetic donors per condition (checked against the real data) plus a 1:1 posterior resample of the cells." ], "id": "cell-16" } ], "metadata": { "kernelspec": { "display_name": "R", "language": "R", "name": "ir" }, "language_info": { "name": "R" }, "colab": { "provenance": [] } }, "nbformat": 4, "nbformat_minor": 5 }