{ "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": [ "# Cell-level representation learning\n", "\n", "The goal: turn raw, multi-batch, multi-modal single-cell data into one clean **embedding**, a handful of coordinates per cell that mix the batches together while keeping the biology, so you can cluster and analyze all your data as one.\n", "\n", "This runs on **3,000 cells of the built-in Liu et al. COVID-19 subsample** (3 batches, RNA + ADT, six major cell types), with the same settings as a full-data run." ], "id": "cell-01" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "library(m3)\n", "library(ggplot2)\n", "set.seed(0)" ], "id": "cell-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Load the demo dataset\n", "\n", "`m3_demo()` returns a ready-to-use `m3_dataset`, a subsample of the Liu et al. COVID-19 CITE-seq data (RNA + ADT), with the obs columns already set up. `n_cells = 3000` loads a fixed 3,000 of its cells, the same number from each batch; leave it out to load all of them." ], "id": "cell-03" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data <- m3_demo(n_cells = 3000)\n", "data" ], "id": "cell-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Build and train the model\n", "\n", "`m3_train(...)` sets up the model from your data and fits it, telling it which obs columns to use:\n", "\n", "- `condition_keys`, the conditions you’re comparing across (here disease group + age band).\n", "- `embedding_dim`, how many numbers describe each cell in the output (here 30).\n", "\n", "The batches are read from the obs column `batch` (B1/B2/B3); if yours has another name, pass it as `batch_key =`. The model corrects for batch, so cells group by biology rather than by batch. Cell-type labels are not used in training; they are used below only to colour the UMAP. `seed = 0` makes the run reproducible. Afterwards `m3_capabilities(model)` shows which outputs are available." ], "id": "cell-05" }, { "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", " embedding_dim = 30L,\n", " max_epochs = 500L,\n", " seed = 0L\n", ")\n", "\n", "model\n", "\n", "m3_capabilities(model)" ], "id": "cell-06" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Get the embedding\n", "\n", "`m3_embedding(model, part = ...)` returns the trained coordinates as a cells x embedding_dim matrix. Ask for the part you want by name:\n", "\n", "- `\"bio\"`, the biological signal, with batch differences removed. This is the one you cluster and analyze.\n", "- `\"batch\"`, the batch signal on its own, if you ever want to inspect it separately.\n", "\n", "`m3_cell_metadata(model)` is the per-cell obs table, row-aligned with the embedding." ], "id": "cell-07" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "emb_bio <- m3_embedding(model, part = \"bio\")\n", "emb_intrinsic <- m3_embedding(model, part = \"intrinsic\")\n", "emb_batch <- m3_embedding(model, part = \"batch\")\n", "meta <- m3_cell_metadata(model)\n", "cat(sprintf(\"bio: %s | intrinsic: %s | batch: %s\\n\",\n", " paste(dim(emb_bio), collapse = \"x\"),\n", " paste(dim(emb_intrinsic), collapse = \"x\"),\n", " paste(dim(emb_batch), collapse = \"x\")))" ], "id": "cell-08" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Save the embedding + metadata\n", "\n", "Save the embedding and its metadata. m3 returns plain matrices, so persist them however you like, here as CSV and an `.rds`." ], "id": "cell-09" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "out <- file.path(tempdir(), \"m3_tut1\")\n", "dir.create(out, showWarnings = FALSE)\n", "utils::write.csv(emb_bio, file.path(out, \"embedding_bio.csv\"), row.names = FALSE)\n", "utils::write.csv(meta, file.path(out, \"cell_metadata.csv\"), row.names = FALSE)\n", "saveRDS(list(embedding = emb_bio, metadata = meta), file.path(out, \"embedding_bio.rds\"))\n", "cat(\"saved embedding to\", out, \"\\n\")" ], "id": "cell-10" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Visualise with UMAP\n", "\n", "A UMAP of the `\"bio\"` embedding. If integration worked, cells should group by **cell type** (biology kept) while the **batches mix together** (batch difference removed), colour by each to check." ], "id": "cell-11" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xy <- m3_umap(emb_bio, method = \"scanpy\", n_neighbors = 15L, device = model$device)\n", "df <- data.frame(UMAP1 = xy[, 1], UMAP2 = xy[, 2],\n", " celltype = factor(meta$mergedcelltype),\n", " batch = factor(meta$batch),\n", " condition = factor(meta$cond_group))\n", "\n", "plt <- function(colour, title, legend = TRUE) {\n", " ggplot(df, aes(UMAP1, UMAP2, colour = .data[[colour]])) +\n", " geom_point(size = 0.4, alpha = 0.8) +\n", " theme_classic() +\n", " theme(axis.text = element_blank(), axis.ticks = element_blank(),\n", " legend.position = if (legend) \"right\" else \"none\") +\n", " guides(colour = guide_legend(override.aes = list(size = 2))) +\n", " labs(title = title, colour = NULL)\n", "}\n", "print(plt(\"celltype\", \"Cell type (biology preserved)\"))" ], "id": "cell-12" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(plt(\"batch\", \"Batch (batch mixed)\"))" ], "id": "cell-13" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(plt(\"condition\", \"Condition\"))" ], "id": "cell-14" }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Done.** You now have an integrated cell embedding, ready for clustering and downstream analysis. The patient-prediction tutorial builds on the same model to predict donor-level disease status." ], "id": "cell-15" } ], "metadata": { "kernelspec": { "display_name": "R", "language": "R", "name": "ir" }, "language_info": { "name": "R" }, "colab": { "provenance": [] } }, "nbformat": 4, "nbformat_minor": 5 }