{ "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": [ "# Cell-level representation learning\n", "\n", "The goal: turn raw, multi-batch, multi-modal single-cell data into one clean\n", "**embedding** — a handful of coordinates per cell that mix the batches together\n", "while keeping the biology — so you can cluster and analyze all your data as one.\n", "\n", "This demo runs end-to-end on **3,000 cells of the built-in Liu subsample** (3 batches,\n", "RNA + ADT, six major cell types) — one line to load, no downloads. It uses the\n", "same settings as the full-data tutorial. For the full-data run that reproduces\n", "the publication numbers, see `m3pkg/tutorials/01_representation_learning.py`." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-02", "metadata": {}, "outputs": [], "source": [ "import os\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "import scanpy as sc\n", "import m3\n", "\n", "OUT = \"./tutorial_out_demo/01_representation_learning\"\n", "os.makedirs(OUT, exist_ok=True)\n", "sc.settings.verbosity = 1" ] }, { "cell_type": "markdown", "id": "cell-03", "metadata": {}, "source": [ "## 1. Load the demo data\n", "\n", "`m3.datasets.liu_demo()` returns a ready-to-use `m3.Dataset` — a subsample of the\n", "Liu et al. COVID-19 CITE-seq data (RNA + ADT), with the obs columns already set up.\n", "No downloads." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-04", "metadata": {}, "outputs": [], "source": [ "data = m3.datasets.liu_demo(n_cells=3000)\n", "print(data) # cells, batches, modalities\n", "print(\"celltypes:\", data.obs[\"mergedcelltype\"].value_counts().to_dict())" ] }, { "cell_type": "markdown", "id": "cell-05", "metadata": {}, "source": [ "## 2. Build and train the model\n", "\n", "`m3.M3(...)` sets up the model from your data, telling it which obs columns to use:\n", "\n", "- `condition_keys` — the conditions you're comparing across (here disease group +\n", " 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\n", "name, pass it as `batch_key=`. The model corrects for batch, so cells group by\n", "biology rather than by batch. Cell-type labels are not used in training; they are\n", "used below only to colour the UMAP.\n", "\n", "`.train()` fits the model, and `model.capabilities` then shows which outputs are\n", "available." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-06", "metadata": {}, "outputs": [], "source": [ "model = m3.M3(\n", " data,\n", " condition_keys=[\"cond_group\", \"Age_interval\"],\n", " embedding_dim=30,\n", ")\n", "model.train(max_epochs=500)\n", "print(\"capabilities:\", model.capabilities)" ] }, { "cell_type": "markdown", "id": "cell-07", "metadata": {}, "source": [ "## 3. Get the embedding\n", "\n", "`model.embedding(part=...)` returns the trained coordinates as a\n", "`cells x embedding_dim` array. Ask for the part you want by name:\n", "\n", "- `\"bio\"` — the biological signal, with batch differences removed. **This is the\n", " one you cluster and analyze.**\n", "- `\"batch\"` — the batch signal on its own, if you ever want to inspect it separately.\n", "\n", "`model.cell_metadata` is the per-cell obs table, in the same row order as the\n", "embedding, so you can colour plots by cell type / batch / condition." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-08", "metadata": {}, "outputs": [], "source": [ "emb_bio = model.embedding(part=\"bio\")\n", "emb_batch = model.embedding(part=\"batch\")\n", "meta = model.cell_metadata.copy()\n", "print(\"bio:\", emb_bio.shape, \"batch:\", emb_batch.shape)" ] }, { "cell_type": "markdown", "id": "cell-09", "metadata": {}, "source": [ "## 4. Save the embedding\n", "\n", "Save the embedding and its metadata to disk. The three formats below hold the same\n", "data — pick whichever suits your downstream tools:\n", "\n", "- `.npy` — the raw array (plus a CSV of the metadata).\n", "- `.h5` — the array in an HDF5 file.\n", "- `.h5ad` — an AnnData (embedding as `X`, metadata as `obs`) — handy for scanpy." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-10", "metadata": {}, "outputs": [], "source": [ "import h5py\n", "import anndata as ad\n", "\n", "np.save(os.path.join(OUT, \"embedding_bio.npy\"), emb_bio)\n", "meta.to_csv(os.path.join(OUT, \"cell_metadata.csv\"), index=False)\n", "with h5py.File(os.path.join(OUT, \"embedding_bio.h5\"), \"w\") as f:\n", " f[\"data\"] = emb_bio\n", "ad.AnnData(X=emb_bio, obs=meta.astype(str).reset_index(drop=True)).write_h5ad(\n", " os.path.join(OUT, \"embedding_bio.h5ad\"))\n", "print(\"saved -> .npy / .h5 / .h5ad in\", OUT)" ] }, { "cell_type": "markdown", "id": "cell-11", "metadata": {}, "source": [ "## 5. Visualise with UMAP\n", "\n", "A UMAP of the `\"bio\"` embedding. If integration worked, cells should group by\n", "**cell type** (biology kept) while the **batches mix together** (batch difference\n", "removed) — colour by each to check." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-12", "metadata": {}, "outputs": [], "source": [ "# Build an AnnData from the bio embedding, then colour the UMAP by cell type, batch,\n", "# and condition.\n", "adn = sc.AnnData(X=emb_bio, obs=meta.reset_index(drop=True))\n", "adn.obs[\"batch\"] = adn.obs[\"batch\"].astype(\"category\")\n", "adn.obs[\"mergedcelltype\"] = adn.obs[\"mergedcelltype\"].astype(str).astype(\"category\")\n", "adn.obs[\"cond_group\"] = adn.obs[\"cond_group\"].astype(str).astype(\"category\")\n", "sc.pp.neighbors(adn, use_rep=\"X\", n_neighbors=15)\n", "sc.tl.umap(adn)\n", "fig, axes = plt.subplots(1, 3, figsize=(18, 5))\n", "for ax, key, title in zip(\n", " axes,\n", " [\"mergedcelltype\", \"batch\", \"cond_group\"],\n", " [\"Cell type (biology preserved)\", \"Batch (mixed)\", \"Condition\"],\n", "):\n", " sc.pl.umap(adn, color=key, ax=ax, show=False, title=title,\n", " legend_loc=\"right margin\" if key != \"mergedcelltype\" else \"on data\",\n", " legend_fontsize=6)\n", "fig.tight_layout()\n", "fig.savefig(os.path.join(OUT, \"umap_bio.png\"), dpi=130, bbox_inches=\"tight\")\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "cell-13", "metadata": {}, "source": [ "**Done.** You now have an integrated cell embedding, ready for clustering and\n", "downstream analysis. For the full-data run, see `tutorials/01_representation_learning.py`." ] } ], "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.13.12" } }, "nbformat": 4, "nbformat_minor": 5 }