{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Colab setup: run this first. Choose an R runtime (this notebook requests it\n", "# automatically). The first matilda_train() below builds the bundled Python env via basilisk.\n", "# Install precompiled Linux binaries (Posit Public Package Manager) instead of compiling every\n", "# CRAN dependency from source. This cuts the Seurat/CRAN build from ~20-30 min to a couple of\n", "# minutes on Colab. (If a binary isn't available P3M falls back to source automatically.)\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", "# scater is a Bioconductor package (used for the latent-space UMAP in section 4), so it must\n", "# be installed via BiocManager, NOT install.packages()/CRAN (CRAN reports it \"not available\").\n", "BiocManager::install(\n", " c(\"SingleCellExperiment\", \"SummarizedExperiment\", \"MultiAssayExperiment\",\n", " \"S4Vectors\", \"rhdf5\", \"HDF5Array\", \"basilisk\", \"scater\"),\n", " update = FALSE, ask = FALSE\n", ")\n", "install.packages(c(\"remotes\", \"Matrix\", \"Seurat\", \"ggplot2\", \"uwot\"))\n", "remotes::install_github(\"PYangLab/Matilda\", subdir = \"matilda-r\")" ], "id": "cell-00" }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Matilda in R\n", "\n", "Python users see [the Python tutorial](tutorial-python.ipynb).\n", "\n", "The complete Matilda workflow in **R** on real **TEA-seq** (RNA + ADT + ATAC): read your data →\n", "train → classification → dimension reduction → feature selection → simulation, plus a look at the\n", "different data types Matilda supports. Python users: a parallel tutorial with the same structure\n", "is available as a Jupyter notebook.\n", "\n", "## Requirements\n", "\n", "- **R**: `matilda`, `SingleCellExperiment`; `Seurat` for the `10x` and `.rds` loaders; `scater`\n", " for the latent-space UMAP; `uwot` for the per-modality simulation UMAP (§6); `ggplot2` for plots.\n", "- **Python**: none. `matilda` provisions it via `basilisk` on the first `matilda_train()`.\n", "- **Demo data**: downloaded automatically by `matilda_download_example()` (~75 MB, cached locally)." ], "id": "cell-01" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "library(matilda)\n", "library(SingleCellExperiment)\n", "library(ggplot2) # plots below use ggplot()/aes() directly\n", "data_dir <- matilda_download_example() # downloads + caches the TEA-seq demo, returns the path\n", "demo_h5 <- data_dir # native .h5 + _cty.csv\n", "demo_fmt <- file.path(data_dir, \"formats\") # .h5ad / 10x / .rds\n", "\n", "# a fixed colour list, assigned to whichever cell types your data has (works for any labels)\n", "PALETTE <- c(\"#1f77b4\",\"#aec7e8\",\"#ff7f0e\",\"#ffbb78\",\"#2ca02c\",\"#98df8a\",\"#d62728\",\"#ff9896\",\n", " \"#9467bd\",\"#c5b0d5\",\"#8c564b\",\"#c49c94\",\"#e377c2\",\"#f7b6d2\",\"#7f7f7f\",\"#bcbd22\",\"#17becf\",\"#9edae5\")" ], "id": "cell-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Read your data\n", "\n", "Matilda's R interface takes a `SingleCellExperiment`: **RNA raw counts** in the main assay, **ADT**\n", "and **ATAC** (gene activity) as `altExp`s, and a cell-type column in `colData`. Below the *same*\n", "TEA-seq training cells are loaded from **four formats**; pick whichever matches your data." ], "id": "cell-03" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# assemble an SCE from three genes x cells matrices + a label vector\n", "build_sce <- function(rna, adt, atac, cell_type) {\n", " sce <- SingleCellExperiment(assays = list(counts = as.matrix(rna)))\n", " altExp(sce, \"ADT\") <- SummarizedExperiment(list(counts = as.matrix(adt)))\n", " altExp(sce, \"ATAC\") <- SummarizedExperiment(list(counts = as.matrix(atac)))\n", " sce$cell_type <- cell_type\n", " sce\n", "}\n", "labels <- as.character(utils::read.csv(file.path(demo_h5, \"train_cty.csv\"), header = FALSE)[[2]])[-1]" ], "id": "cell-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Format A: native Matilda `.h5` (`rhdf5`)" ], "id": "cell-05" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "read_h5 <- function(path) {\n", " m <- rhdf5::h5read(path, \"matrix/data\")\n", " feats <- as.character(rhdf5::h5read(path, \"matrix/features\"))\n", " cells <- as.character(rhdf5::h5read(path, \"matrix/barcodes\"))\n", " if (nrow(m) == length(cells) && ncol(m) == length(feats)) m <- t(m) # -> genes x cells\n", " dimnames(m) <- list(feats, cells); m\n", "}\n", "g <- function(mod) file.path(demo_h5, sprintf(\"train_%s.h5\", mod))\n", "sce <- build_sce(read_h5(g(\"rna\")), read_h5(g(\"adt\")), read_h5(g(\"atac\")), labels)\n", "sce" ], "id": "cell-06" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Format B: `.h5ad` (AnnData / scanpy)\n", "\n", "A `.h5ad` is just HDF5; read its CSR-sparse `X` with `rhdf5` (no extra Python needed). For a\n", "richer object you could use `zellkonverter::readH5AD()` instead." ], "id": "cell-07" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "rd_h5ad <- function(p) { # -> genes x cells\n", " X <- rhdf5::h5read(p, \"X\") # CSR: data / indices / indptr\n", " shp <- as.integer(rhdf5::h5readAttributes(p, \"X\")$shape) # c(cells, genes)\n", " genes <- as.character(rhdf5::h5read(p, \"var/_index\"))\n", " cells <- as.character(rhdf5::h5read(p, \"obs/_index\"))\n", " m <- Matrix::sparseMatrix(i = rep(seq_len(shp[1]), diff(X$indptr)),\n", " j = X$indices + 1L, x = as.numeric(X$data), dims = shp) # cells x genes\n", " m <- Matrix::t(m); dimnames(m) <- list(genes, cells); as.matrix(m)\n", "}\n", "h <- function(mod) file.path(demo_fmt, sprintf(\"train_%s.h5ad\", mod))\n", "sce_h5ad <- build_sce(rd_h5ad(h(\"rna\")), rd_h5ad(h(\"adt\")), rd_h5ad(h(\"atac\")), labels)" ], "id": "cell-08" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Format C: 10x CellRanger (`Seurat::Read10X`)" ], "id": "cell-09" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "rd_10x <- function(d) as.matrix(Seurat::Read10X(d))\n", "x <- function(mod) file.path(demo_fmt, \"10x\", sprintf(\"train_%s\", mod))\n", "sce_10x <- build_sce(rd_10x(x(\"rna\")), rd_10x(x(\"adt\")), rd_10x(x(\"atac\")), labels)" ], "id": "cell-10" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Format D: a `Seurat` object (`.rds`)" ], "id": "cell-11" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "seu <- readRDS(file.path(demo_fmt, \"train_seurat.rds\")) # RNA/ADT/ATAC assays + cell_type\n", "ga <- function(a) as.matrix(SeuratObject::LayerData(seu, assay = a, layer = \"counts\"))\n", "sce_rds <- build_sce(ga(\"RNA\"), ga(\"ADT\"), ga(\"ATAC\"), seu$cell_type)" ], "id": "cell-12" }, { "cell_type": "markdown", "metadata": {}, "source": [ "All four give the same object, so the rest of the tutorial doesn't depend on the format. We\n", "continue with `sce` from Format A.\n", "\n", "## 2. Train the Matilda model\n", "\n", "The model is stored inside the object, so the workflow pipes." ], "id": "cell-13" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sce <- matilda_train(sce, label = \"cell_type\", seed = 1L)\n", "matilda_model(sce)" ], "id": "cell-14" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Classification (held-out query cells)" ], "id": "cell-15" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "query <- build_sce(read_h5(file.path(demo_h5, \"test_rna.h5\")),\n", " read_h5(file.path(demo_h5, \"test_adt.h5\")),\n", " read_h5(file.path(demo_h5, \"test_atac.h5\")),\n", " as.character(utils::read.csv(file.path(demo_h5, \"test_cty.csv\"), header = FALSE)[[2]])[-1])\n", "query <- matilda_classify(query, reference = sce)\n", "sprintf(\"overall query accuracy = %.4f\", mean(query$matilda_pred == query$cell_type))" ], "id": "cell-16" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# per-cell-type accuracy = fraction of each type's query cells labelled correctly\n", "acc_by_type <- tapply(query$matilda_pred == query$cell_type, query$cell_type, mean)\n", "\n", "ggplot(data.frame(cell_type = names(acc_by_type), accuracy = as.numeric(acc_by_type)),\n", " aes(reorder(cell_type, accuracy), accuracy)) +\n", " geom_col(fill = \"steelblue\") +\n", " coord_flip() +\n", " ylim(0, 1) +\n", " geom_text(aes(label = sprintf(\"%.2f\", accuracy)), hjust = -0.1, size = 3) +\n", " labs(title = \"Query accuracy by cell type\", x = NULL, y = \"accuracy\") +\n", " theme_classic()" ], "id": "cell-17" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Dimension reduction" ], "id": "cell-18" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sce <- matilda_reduce(sce) # adds reducedDim(sce, \"MATILDA\")\n", "dim(reducedDim(sce, \"MATILDA\")) # cells x z_dim (100)" ], "id": "cell-19" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "set.seed(42)\n", "sce <- scater::runUMAP(sce, dimred = \"MATILDA\", n_neighbors = 15L, min_dist = 0.1) # 2-D UMAP of the latent space\n", "\n", "cell_types <- sort(unique(as.character(sce$cell_type))) # colour whatever cell types the data has\n", "palette_map <- setNames(PALETTE[(seq_along(cell_types) - 1) %% length(PALETTE) + 1], cell_types) # wrap if >18 types\n", "\n", "scater::plotUMAP(sce, colour_by = \"cell_type\") +\n", " ggplot2::scale_colour_manual(values = palette_map) +\n", " ggtitle(\"Matilda integrated latent space (UMAP)\")" ], "id": "cell-20" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Feature selection" ], "id": "cell-21" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "markers <- matilda_markers(sce) # data.frame: celltype / feature / importance\n", "head(markers)" ], "id": "cell-22" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# take each cell type's top-3 markers, then build a feature x cell-type importance grid\n", "cell_types <- sort(unique(markers$celltype))\n", "top3 <- do.call(rbind, lapply(cell_types, function(ct) {\n", " rows <- markers[markers$celltype == ct, ]\n", " head(rows[order(-rows$importance), ], 3)\n", "}))\n", "feature_order <- unique(top3$feature)\n", "\n", "heat_df <- markers[markers$feature %in% feature_order, ]\n", "# min-max scale each feature's importance across cell types to 0..1 (comparable within a row)\n", "heat_df$imp_scaled <- ave(heat_df$importance, heat_df$feature,\n", " FUN = function(z) (z - min(z)) / (max(z) - min(z) + 1e-9))\n", "heat_df$feature <- factor(heat_df$feature, levels = rev(feature_order))\n", "heat_df$celltype <- factor(heat_df$celltype, levels = cell_types)\n", "\n", "ggplot(heat_df, aes(celltype, feature, fill = imp_scaled)) +\n", " geom_tile() +\n", " scale_fill_viridis_c() +\n", " theme_minimal() +\n", " theme(axis.text.x = element_text(angle = 45, hjust = 1)) +\n", " labs(title = \"Top-3 markers per cell type\", x = NULL, y = NULL, fill = \"scaled\\nimportance\")" ], "id": "cell-23" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6. Simulation\n", "\n", "Matilda **augments** a chosen **anchor** cell type: in the returned set that one type is replaced by\n", "`n` freshly generated synthetic cells, while **every other cell type stays real**. The returned\n", "object also carries the full **real** reference cells Matilda used (`metadata(sim)$real`), in the\n", "**same feature space**, so the two are directly comparable. The official check: per modality, UMAP\n", "the real and simulated sets together, then show the real cells\n", "(top row) and the augmented set (bottom row), highlighting the anchor. The bottom row is labelled\n", "\"Simulated\", but only the **anchor** group in it is synthetic — the other types are the real cells;\n", "if augmentation works, the synthetic anchor lands where the real anchor is in the top row." ], "id": "cell-24" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sim <- matilda_simulate(sce, celltype = \"B.Naive\", n = 200)\n", "real <- S4Vectors::metadata(sim)$real # the full real reference cells (same space as the simulation)\n", "c(total_in_sim = ncol(sim), synthetic_anchor = sum(sim$label == \"B.Naive\"), real_reference = ncol(real$rna))" ], "id": "cell-25" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "real_mat <- list(RNA = real$rna, ADT = real$adt, ATAC = real$atac)\n", "sim_mat <- list(RNA = SummarizedExperiment::assay(sim, \"counts\"),\n", " ADT = SummarizedExperiment::assay(SingleCellExperiment::altExp(sim, \"ADT\"), \"counts\"),\n", " ATAC = SummarizedExperiment::assay(SingleCellExperiment::altExp(sim, \"ATAC\"), \"counts\"))\n", "\n", "# tag each cell: the anchor type vs everything else\n", "anchor_tag <- function(lab) factor(ifelse(lab == \"B.Naive\", \"anchor cell type\", \"other cell types\"),\n", " levels = c(\"anchor cell type\", \"other cell types\"))\n", "\n", "# per modality: top-1000 variable features -> scale -> PCA -> UMAP, then split real vs simulated\n", "one_modality <- function(mod) {\n", " stacked <- t(cbind(real_mat[[mod]], sim_mat[[mod]])) # cells x features\n", " n_real <- ncol(real_mat[[mod]])\n", " n_sim <- ncol(sim_mat[[mod]])\n", " top_var <- order(apply(stacked, 2, stats::var), decreasing = TRUE)[seq_len(min(1000L, ncol(stacked)))]\n", " z_scaled <- scale(stacked[, top_var])\n", " pcs <- stats::prcomp(z_scaled, rank. = min(50L, ncol(z_scaled) - 1L),\n", " center = FALSE, scale. = FALSE)$x # denoise before UMAP\n", " set.seed(42)\n", " umap_df <- as.data.frame(uwot::umap(pcs, n_neighbors = 20, min_dist = 0.1, init = \"pca\"))\n", " names(umap_df) <- c(\"UMAP1\", \"UMAP2\")\n", " rbind(data.frame(umap_df[seq_len(n_real), ], grp = anchor_tag(real$label), panel = paste(\"Real\", mod)),\n", " data.frame(umap_df[n_real + seq_len(n_sim), ], grp = anchor_tag(sim$label), panel = paste(\"Simulated\", mod)))\n", "}\n", "\n", "plot_df <- do.call(rbind, lapply(c(\"RNA\", \"ADT\", \"ATAC\"), one_modality))\n", "plot_df$panel <- factor(plot_df$panel, levels = c(\"Real RNA\", \"Real ADT\", \"Real ATAC\",\n", " \"Simulated RNA\", \"Simulated ADT\", \"Simulated ATAC\"))\n", "ggplot(plot_df, aes(UMAP1, UMAP2, colour = grp)) +\n", " geom_point(size = 0.5, alpha = 0.8) +\n", " facet_wrap(~ panel, nrow = 2, scales = \"free\") +\n", " ggplot2::scale_colour_manual(values = c(\"anchor cell type\" = \"#F8766D\", \"other cell types\" = \"#00BFC4\")) +\n", " theme_classic() +\n", " theme(axis.text = element_blank(), axis.ticks = element_blank(),\n", " legend.title = element_blank(), aspect.ratio = 1) +\n", " labs(x = NULL, y = NULL, title = \"Real vs. simulated cells per modality (anchor: B.Naive)\")" ], "id": "cell-26" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7. Modality combinations Matilda supports\n", "\n", "Matilda works with **any combination of the three modalities** (RNA only, RNA + ADT, RNA + ATAC,\n", "or RNA + ADT + ATAC) and picks the matching model automatically from what you provide. (Internally\n", "Matilda labels these `rna_only` / `CITEseq` / `SHAREseq` / `TEAseq`, after the assays they typically\n", "come from, but your data needn't be those specific protocols; only the modalities present matter.)\n", "Training each combination on the *same* cells shows what each added modality buys; to use your own\n", "data, just build the SCE with whatever modalities you have." ], "id": "cell-27" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# drop the altExps not in `keep`, leaving only the requested modalities\n", "keep_only <- function(s, keep) {\n", " for (ae in altExpNames(s)) if (!(ae %in% keep)) altExp(s, ae) <- NULL\n", " s\n", "}\n", "combo_acc <- sapply(list(\"RNA only\" = character(0), \"RNA+ATAC\" = \"ATAC\", \"RNA+ADT\" = \"ADT\"),\n", " function(keep) {\n", " fit <- matilda_train(keep_only(sce, keep), label = \"cell_type\", seed = 1L)\n", " qy <- matilda_classify(keep_only(query, keep), reference = fit)\n", " mean(qy$matilda_pred == qy$cell_type)\n", " })\n", "combo_acc[\"RNA+ADT+ATAC\"] <- mean(query$matilda_pred == query$cell_type) # the TEA-seq model from §2/§3\n", "\n", "ggplot(data.frame(modalities = factor(names(combo_acc), levels = names(combo_acc)),\n", " accuracy = as.numeric(combo_acc)),\n", " aes(modalities, accuracy)) +\n", " geom_col(fill = \"seagreen\") +\n", " ylim(0, 1) +\n", " geom_text(aes(label = sprintf(\"%.3f\", accuracy)), vjust = -0.4, size = 3.5) +\n", " labs(title = \"Query accuracy by modality combination\", x = NULL, y = \"accuracy\") +\n", " theme_classic()" ], "id": "cell-28" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Adding the ADT (protein) panel to RNA gives the biggest gain; ATAC contributes less for this task\n", "on this dataset.\n", "\n", "## 8. Session info" ], "id": "cell-29" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sessionInfo()" ], "id": "cell-30" } ], "metadata": { "kernelspec": { "display_name": "R", "language": "R", "name": "ir" }, "language_info": { "name": "R" }, "accelerator": "GPU", "colab": { "provenance": [], "gpuType": "T4" } }, "nbformat": 4, "nbformat_minor": 5 }