{ "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": [ "# Mosaic integration\n", "\n", "In a mosaic design the batches do not all measure the same modalities. M3 still\n", "puts every cell in one embedding.\n", "\n", "Here two batches of the demo have RNA and ADT and the third has RNA only. The\n", "tutorial uses the full demo (30,534 cells), like the patient-prediction and\n", "attribution tutorials; training takes about 20 minutes on a laptop CPU. For a\n", "quick look, `m3.datasets.liu_demo(n_cells=3000)` in step 0 brings that down to\n", "about 3 minutes." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-02", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import anndata as ad\n", "import scanpy as sc\n", "import matplotlib.pyplot as plt\n", "import m3\n", "\n", "sc.settings.verbosity = 1" ] }, { "cell_type": "markdown", "id": "cell-03", "metadata": {}, "source": [ "## 0. Example files\n", "\n", "This cell writes the demo as one `.h5ad` per modality: `rna.h5ad` with all\n", "three batches and `adt.h5ad` with `B1` and `B2` only, as batch `B3` has no ADT.\n", "**Skip it when you have your own files.**" ] }, { "cell_type": "code", "execution_count": null, "id": "cell-04", "metadata": {}, "outputs": [], "source": [ "demo = m3.datasets.liu_demo()\n", "obs = demo.obs.copy()\n", "obs.index = [f\"cell{i:05d}\" for i in range(demo.n_cells)] # cell barcodes\n", "has_adt = (obs[\"batch\"] != \"B3\").to_numpy()\n", "\n", "ad.AnnData(demo.modalities[\"rna\"], obs=obs,\n", " var=pd.DataFrame(index=demo.var[\"rna\"])).write_h5ad(\"rna.h5ad\")\n", "ad.AnnData(demo.modalities[\"adt\"][has_adt], obs=obs[has_adt],\n", " var=pd.DataFrame(index=demo.var[\"adt\"])).write_h5ad(\"adt.h5ad\")" ] }, { "cell_type": "markdown", "id": "cell-05", "metadata": {}, "source": [ "## 1. Read the files\n", "\n", "Give `m3.read_h5ad` one file per modality. It matches the cells by name and\n", "marks the cells a file does not have as not measured for that modality: here\n", "the cells of `B3` have no ADT. It prints the number of cells per batch and\n", "modality.\n", "\n", "Each file's `obs` needs the batch column. Within a batch, every modality must\n", "have the same cells, or none of them; otherwise `read_h5ad` stops before\n", "loading any counts and names the batch and example cells. If your batch column\n", "has another name, pass it as `batch_key=` here and when building the model. If\n", "`.X` holds normalised values and the counts are in a layer, pass\n", "`layer=\"counts\"`." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-06", "metadata": {}, "outputs": [], "source": [ "data = m3.read_h5ad({\"rna\": \"rna.h5ad\", \"adt\": \"adt.h5ad\"})\n", "print(data)" ] }, { "cell_type": "markdown", "id": "cell-07", "metadata": {}, "source": [ "`data.present` records, per cell, which modalities were measured. A batch can\n", "lack any modality, RNA included. For files already in memory, pass the AnnData\n", "objects to `m3.from_anndata` in the same way.\n", "\n", "### Files per batch\n", "\n", "When each batch comes as its own files, combine them per modality with\n", "anndata first. `label=\"batch\"` adds the batch column, and `index_unique=\"-\"`\n", "appends the batch to the cell names, so barcodes that repeat across batches\n", "stay distinct and match between the modalities. The first cell writes example\n", "files; the second reads them." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-08", "metadata": {}, "outputs": [], "source": [ "rna, adt = ad.read_h5ad(\"rna.h5ad\"), ad.read_h5ad(\"adt.h5ad\")\n", "for b in [\"B1\", \"B2\", \"B3\"]:\n", " for mod, adata in [(\"rna\", rna), (\"adt\", adt)]:\n", " part = adata[adata.obs[\"batch\"] == b].copy()\n", " if part.n_obs:\n", " del part.obs[\"batch\"] # the batch is only in the file name\n", " part.write_h5ad(f\"{b}_{mod}.h5ad\")" ] }, { "cell_type": "code", "execution_count": null, "id": "cell-09", "metadata": {}, "outputs": [], "source": [ "rna = ad.concat([ad.read_h5ad(f\"{b}_rna.h5ad\") for b in [\"B1\", \"B2\", \"B3\"]],\n", " label=\"batch\", keys=[\"B1\", \"B2\", \"B3\"], index_unique=\"-\")\n", "adt = ad.concat([ad.read_h5ad(f\"{b}_adt.h5ad\") for b in [\"B1\", \"B2\"]],\n", " label=\"batch\", keys=[\"B1\", \"B2\"], index_unique=\"-\")\n", "print(m3.from_anndata({\"rna\": rna, \"adt\": adt}))" ] }, { "cell_type": "markdown", "id": "cell-10", "metadata": {}, "source": [ "## 2. Train\n", "\n", "Training is the same call as for fully measured data." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-11", "metadata": {}, "outputs": [], "source": [ "model = m3.M3(data, condition_keys=\"cond_group\")\n", "model.train()\n", "print(\"capabilities:\", model.capabilities)" ] }, { "cell_type": "markdown", "id": "cell-12", "metadata": {}, "source": [ "## 3. One embedding for all cells\n", "\n", "The embedding covers every cell, including the RNA-only batch. As in\n", "[Use your own data](https://pyanglab.github.io/M3/notebooks/py_05_own_data/), it\n", "goes back into an AnnData by the `obs_names` column of `model.cell_metadata`;\n", "here that AnnData is `rna.h5ad`, which holds every cell.\n", "\n", "`part=\"bio\"` includes the condition factors, so cells also separate by\n", "condition. `part=\"intrinsic\"` leaves them out." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-13", "metadata": {}, "outputs": [], "source": [ "rna = ad.read_h5ad(\"rna.h5ad\")\n", "\n", "emb = pd.DataFrame(model.embedding(part=\"bio\"),\n", " index=model.cell_metadata[\"obs_names\"])\n", "rna.obsm[\"X_m3\"] = emb.loc[rna.obs_names].to_numpy()\n", "print(rna)" ] }, { "cell_type": "code", "execution_count": null, "id": "cell-14", "metadata": {}, "outputs": [], "source": [ "sc.pp.neighbors(rna, use_rep=\"X_m3\", transformer=\"sklearn\")\n", "sc.tl.umap(rna)\n", "sc.pl.umap(rna, color=[\"mergedcelltype\", \"batch\", \"cond_group\"], wspace=0.5, show=False)\n", "plt.savefig(\"umap_mosaic.png\", dpi=130, bbox_inches=\"tight\")\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "id": "cell-15", "metadata": {}, "outputs": [], "source": [ "rna.write_h5ad(\"mosaic_m3.h5ad\")" ] } ], "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 }