{ "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": [ "# Donor-level disease prediction\n", "\n", "m3 can predict a **donor's** disease status from their cells, in a leave-one-batch-out setting: we hold out one batch (`B3`), hide its donors' disease labels during training, and predict them at the end. `m3_train(...)` fits the integration model and the donor predictor in one call; `m3_predict_donors()` then returns per-donor class probabilities.\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 + train the model with a held-out batch\n", "\n", "On top of the columns from the representation-learning tutorial, donor prediction needs a few more:\n", "\n", "- `target_condition`, the condition to predict (here `cond_group`, i.e. disease).\n", "- `donor_key`, the column identifying each donor, so cells are grouped per donor.\n", "- `held_out`, the batch(es) to hold back; these donors' `target_condition` labels are hidden during training and predicted at the end.\n", "\n", "The donor predictor summarises each donor as a cell-type-balanced mean of the latent embedding, then removes batch effects from it by adversarial domain adaptation: a **corrector** reshapes the profile while a **batch discriminator** tries to identify the batch from it, and the corrector is trained to predict disease while preventing the discriminator from succeeding. The `donor_predictor` settings:\n", "\n", "- `patient_w` — weight of the donor objective relative to the cell-level VAE loss.\n", "- `adv_max` — the maximum strength of batch removal.\n", "- `adv_warmup` — number of epochs over which batch-removal strength ramps from 0 to `adv_max`.\n", "- `n_disc` — discriminator updates per corrector update.\n", "- `glr`, `n_epochs` — the corrector's learning rate and number of epochs.\n", "\n", "`m3_reference_vocab(model)` shows the label set the model learned to predict (the held-out donors' labels never enter it)." ], "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", " held_out = \"B3\",\n", " embedding_dim = 30L,\n", " max_epochs = 500L,\n", " donor_predictor = list(glr = 3e-3, n_epochs = 120L, adv_max = 10L,\n", " adv_warmup = 7L, n_disc = 21L, patient_w = 10L),\n", " seed = 0L\n", ")\n", "cat(\"reference vocab (query labels never enter it):\",\n", " paste(m3_reference_vocab(model)$cond_group, collapse = \", \"), \"\\n\")" ], "id": "cell-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Predict the held-out donors\n", "\n", "`m3_predict_donors(model)` returns one row per held-out donor: the predicted label and the probability of each class." ], "id": "cell-05" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "preds <- m3_predict_donors(model)\n", "cat(\"query donors:\", nrow(preds), \"\\n\")\n", "\n", "print(preds)" ], "id": "cell-06" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Evaluate against the held-out truth\n", "\n", "The held-out donors' real `cond_group` lives in the metadata (never shown to the model). We join it back to score accuracy." ], "id": "cell-07" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "obs <- m3_dataset_obs(data)\n", "truth <- unique(obs[, c(\"sample_id\", \"cond_group\")])\n", "truth <- stats::setNames(as.character(truth$cond_group), as.character(truth$sample_id))\n", "preds$true_label <- truth[as.character(preds$sample_id)]\n", "acc <- mean(preds$predicted_label == preds$true_label)\n", "cat(sprintf(\"held-out accuracy = %.3f\\n\", acc))" ], "id": "cell-08" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Patient-level embedding\n", "\n", "`m3_donor_embedding()` returns one vector per donor, the donor-level representation the model actually classifies. We UMAP it and colour by reference/query, true label, and whether the held-out prediction was correct." ], "id": "cell-09" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "demb <- m3_donor_embedding(model)\n", "info <- m3_predict_donors(model, include_reference = TRUE)\n", "info <- info[match(demb$sample_id, info$sample_id), ]\n", "info$true_label <- truth[as.character(demb$sample_id)]\n", "info$set <- ifelse(info$is_reference, \"reference\", \"query\")\n", "info$correct <- ifelse(info$is_reference, \"reference\",\n", " ifelse(info$predicted_label == info$true_label, \"correct\", \"wrong\"))\n", "\n", "X <- as.matrix(demb[, grep(\"^m3_\", colnames(demb))])\n", "xy <- m3_umap(X, method = \"umap\", n_neighbors = 15L, random_state = 0L,\n", " device = model$device)\n", "pdf <- data.frame(UMAP1 = xy[, 1], UMAP2 = xy[, 2],\n", " set = factor(info$set), true_label = factor(info$true_label),\n", " correct = factor(info$correct))\n", "\n", "pl <- function(colour, title) {\n", " ggplot(pdf, aes(UMAP1, UMAP2, colour = .data[[colour]])) +\n", " geom_point(size = 3, alpha = 0.85) + theme_classic() +\n", " theme(axis.text = element_blank(), axis.ticks = element_blank()) +\n", " labs(title = title, colour = NULL)\n", "}\n", "print(pl(\"set\", \"Patient embedding — set\"))" ], "id": "cell-10" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(pl(\"true_label\", \"Patient embedding — true_label\"))" ], "id": "cell-11" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(pl(\"correct\", \"Patient embedding — correct\"))" ], "id": "cell-12" }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Done.** Leave-one-batch-out donor prediction, evaluated against the held-out truth, with a patient-level embedding." ], "id": "cell-13" } ], "metadata": { "kernelspec": { "display_name": "R", "language": "R", "name": "ir" }, "language_info": { "name": "R" }, "colab": { "provenance": [] } }, "nbformat": 4, "nbformat_minor": 5 }