{ "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": [ "# Use your own data\n", "\n", "The other tutorials start from the built-in demo. This one starts from files on\n", "disk, in the layout most multimodal datasets are shared in: **one `.h5ad` per\n", "modality** (here RNA and ADT) for the same cells. It ends with a trained model and\n", "the embedding stored back in your AnnData.\n", "\n", "If your files are laid out differently (one set of files per batch, or one file\n", "holding every modality), section 6 shows what to change. The tutorial runs in\n", "about 3 minutes on a laptop CPU." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-02", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "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", "So that there is something to read, this cell writes 3,000 cells of the demo to\n", "`rna.h5ad` and `adt.h5ad`. **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_cells=3000)\n", "obs = demo.obs.copy()\n", "obs.index = [f\"cell{i:04d}\" for i in range(demo.n_cells)] # cell barcodes\n", "order = np.random.default_rng(0).permutation(demo.n_cells) # ADT file: other cell order\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\"][order], obs=obs[[\"batch\"]].iloc[order],\n", " var=pd.DataFrame(index=demo.var[\"adt\"])).write_h5ad(\"adt.h5ad\")" ] }, { "cell_type": "markdown", "id": "cell-05", "metadata": {}, "source": [ "## 1. What M3 needs\n", "\n", "| | |\n", "|---|---|\n", "| **Counts** | Raw, un-normalised counts for every modality. M3 normalises internally. |\n", "| **Modality names** | Exactly `\"rna\"`, `\"adt\"` and/or `\"atac\"`. |\n", "| **Cells** | Within a batch, the same cells in every modality, matched by name. A batch may lack a modality altogether. |\n", "| **Features** | Unique names per modality, named the same way in every batch. |\n", "| **`obs` columns** | A batch column (for example the sequencing run) and one or two condition columns (for example disease status). The donor-level tasks also need a cell-type column and a donor column. |\n", "\n", "## 2. Read the files\n", "\n", "`m3.read_h5ad` takes one file per modality. It matches the cells by name, so\n", "the files may list them in different orders, and keeps the cell names in an\n", "`obs_names` column, which step 5 uses to put the results back. Before loading\n", "any counts it checks that within each batch both files have the same cells.\n", "The table it prints is the number of cells per batch and modality." ] }, { "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": [ "The three batches listed here come from the `obs` column called `batch`. If\n", "your batch column has another name, name it with `batch_key=\"run\"` in\n", "`read_h5ad` and again in the next step.\n", "\n", "## 3. If reading stops\n", "\n", "Each check stops with a message that names the fix:\n", "\n", "- **Normalised values.** M3 needs raw counts and normalises internally, so a\n", " matrix with non-integer values stops the read. If `.X` is normalised and the\n", " counts are in a layer (`print(ad.read_h5ad(\"rna.h5ad\"))` lists it), pass\n", " `layer=\"counts\"`, or `layer={\"rna\": \"counts\"}` when only one file has it.\n", "- **Cells that differ within a batch.** If one file has cells of a batch that\n", " the other lacks, for example cells removed by QC in one modality only,\n", " `join=\"inner\"` keeps the cells both files have and reports how many it\n", " dropped. If the files share no cell names at all, the names were changed in\n", " one of them (for example `-1` became `.1`).\n", "- **Repeated cell names.** Cell names must be unique within a file. Barcodes\n", " that repeat across batches can be prefixed with the batch:\n", " `rna.obs_names = rna.obs[\"batch\"].astype(str) + \"_\" + rna.obs_names`, the same\n", " in every file.\n", "\n", "## 4. Train\n", "\n", "Tell the model which `obs` columns to use:\n", "\n", "- `condition_keys` — the condition column(s), at most two. Required.\n", "- `batch_key` — the batch column, when it is not called `batch`, for example\n", " `batch_key=\"run\"`. If the model finds no batch column it stops with an error\n", " that lists the columns of `obs`.\n", "\n", "`model.contract[\"batches\"]` lists the batches the model will use.\n", "\n", "With these two, `train()` fits the cell-level model, which is all the embedding\n", "needs. The lines printed before the epochs are internal messages;\n", "`Batch counts` is the number of cells per batch, in the order of\n", "`model.contract[\"batches\"]`." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-08", "metadata": {}, "outputs": [], "source": [ "model = m3.M3(data, condition_keys=\"cond_group\")\n", "print(\"batches:\", model.contract[\"batches\"])\n", "\n", "model.train()\n", "print(\"capabilities:\", model.capabilities)" ] }, { "cell_type": "markdown", "id": "cell-09", "metadata": {}, "source": [ "## 5. Put the embedding back in your AnnData\n", "\n", "Index the embedding by the `obs_names` column of `model.cell_metadata`, then\n", "reorder it to your AnnData. `part=\"bio\"` includes the condition factors, so cells\n", "also separate by condition; `part=\"intrinsic\"` leaves them out." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-10", "metadata": {}, "outputs": [], "source": [ "rna = ad.read_h5ad(\"rna.h5ad\")\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.obsm[\"X_m3\"].shape)\n", "\n", "# check the matching: the model's metadata, reordered the same way, equals yours\n", "meta = model.cell_metadata.set_index(\"obs_names\").loc[rna.obs_names]\n", "assert (meta[\"mergedcelltype\"].astype(str).to_numpy() == rna.obs[\"mergedcelltype\"].astype(str).to_numpy()).all()" ] }, { "cell_type": "code", "execution_count": null, "id": "cell-11", "metadata": {}, "outputs": [], "source": [ "sc.pp.neighbors(rna, use_rep=\"X_m3\")\n", "sc.tl.umap(rna)\n", "sc.pl.umap(rna, color=[\"mergedcelltype\", \"batch\", \"cond_group\"], wspace=0.5, show=False)\n", "plt.savefig(\"umap_m3.png\", dpi=130, bbox_inches=\"tight\")\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "id": "cell-12", "metadata": {}, "outputs": [], "source": [ "rna.write_h5ad(\"rna_m3.h5ad\") # your AnnData, with the embedding in obsm[\"X_m3\"]" ] }, { "cell_type": "markdown", "id": "cell-13", "metadata": {}, "source": [ "From here everything works as in the other tutorials. Add `celltype_key=\"...\"`\n", "and `donor_key=\"...\"` to `m3.M3` for\n", "[patient prediction](https://pyanglab.github.io/M3/notebooks/py_02_patient_prediction/) and\n", "[attribution](https://pyanglab.github.io/M3/notebooks/py_03_attribution/).\n", "\n", "## 6. Other file layouts\n", "\n", "Only step 2 changes. Steps 4 and 5 stay as they are. The cells below make\n", "their example files from the objects above, so with your own data take only the\n", "part that matches your layout.\n", "\n", "### One set of files per batch\n", "\n", "Combine each modality's files with anndata first, then read the combined\n", "objects with `m3.from_anndata`, which works like `read_h5ad` on AnnData already\n", "in memory. `label=\"batch\"` adds the batch column, which files like these lack,\n", "and `index_unique=\"-\"` appends the batch to the cell names, so barcodes that\n", "repeat across batches stay distinct and match between the modalities. Features\n", "must have the same names in every batch." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-14", "metadata": {}, "outputs": [], "source": [ "adt = ad.read_h5ad(\"adt.h5ad\")[rna.obs_names].copy() # example files, one pair per batch\n", "for b in [\"B1\", \"B2\", \"B3\"]:\n", " keep = rna.obs_names[rna.obs[\"batch\"] == b]\n", " part = rna[keep, :].copy()\n", " del part.obs[\"batch\"] # the batch is only in the file name\n", " part.write_h5ad(f\"{b}_rna.h5ad\")\n", " adt[keep, :].write_h5ad(f\"{b}_adt.h5ad\")" ] }, { "cell_type": "code", "execution_count": null, "id": "cell-15", "metadata": {}, "outputs": [], "source": [ "batches = [\"B1\", \"B2\", \"B3\"]\n", "rna_all = ad.concat([ad.read_h5ad(f\"{b}_rna.h5ad\") for b in batches],\n", " label=\"batch\", keys=batches, index_unique=\"-\")\n", "adt_all = ad.concat([ad.read_h5ad(f\"{b}_adt.h5ad\") for b in batches],\n", " label=\"batch\", keys=batches, index_unique=\"-\")\n", "data = m3.from_anndata({\"rna\": rna_all, \"adt\": adt_all})\n", "print(data)" ] }, { "cell_type": "markdown", "id": "cell-16", "metadata": {}, "source": [ "If the `obs` of every file already has a batch column, leave out `label=` and\n", "`keys=`. For batches that do not all have the same modalities, see\n", "[Mosaic integration](https://pyanglab.github.io/M3/notebooks/py_06_mosaic_integration/).\n", "\n", "### One `.h5ad` holding every modality\n", "\n", "If all features sit in one AnnData and `var[\"feature_types\"]` says which is\n", "which (`Gene Expression`, `Antibody Capture`, `Peaks`, as written by Cell\n", "Ranger), `m3.from_anndata` replaces step 2. It splits the modalities and\n", "adds the `obs_names` column itself. The column must be called `feature_types` and\n", "hold exactly these values; features with any other value are left out, so check\n", "the modalities in `print(data)`. Name the batch column with `batch_key=` in\n", "step 4 if it is not called `batch`, and use this AnnData in place of `rna` in\n", "step 5." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-17", "metadata": {}, "outputs": [], "source": [ "protein = adt.copy() # example file with both modalities\n", "protein.var_names = protein.var_names + \"_protein\"\n", "both = ad.concat([rna, protein], axis=1, merge=\"first\")\n", "both.var[\"feature_types\"] = [\"Gene Expression\"] * rna.n_vars + [\"Antibody Capture\"] * adt.n_vars\n", "both.write_h5ad(\"multimodal.h5ad\")" ] }, { "cell_type": "code", "execution_count": null, "id": "cell-18", "metadata": {}, "outputs": [], "source": [ "both = ad.read_h5ad(\"multimodal.h5ad\")\n", "data = m3.from_anndata(both)\n", "print(data)" ] }, { "cell_type": "markdown", "id": "cell-19", "metadata": {}, "source": [ "If some batches in that file lack a modality, the file holds zeros for them,\n", "not measurements. Split the AnnData into one object per modality and leave\n", "those batches out of the modality they lack:" ] }, { "cell_type": "code", "execution_count": null, "id": "cell-20", "metadata": {}, "outputs": [], "source": [ "is_rna = (both.var[\"feature_types\"] == \"Gene Expression\").to_numpy()\n", "rna_part = both[:, is_rna]\n", "adt_part = both[both.obs[\"batch\"] != \"B3\", ~is_rna] # as if B3 had no ADT\n", "data = m3.from_anndata({\"rna\": rna_part, \"adt\": adt_part})\n", "print(data)" ] }, { "cell_type": "markdown", "id": "cell-21", "metadata": {}, "source": [ "### Seurat or SingleCellExperiment\n", "\n", "Write each modality to its own `.h5ad` in R, with the raw counts in `.X`, and\n", "start from step 2. With the Bioconductor package\n", "[zellkonverter](https://bioconductor.org/packages/zellkonverter/):\n", "\n", "```r\n", "library(zellkonverter)\n", "\n", "# SingleCellExperiment: RNA in the main experiment, ADT as an altExp\n", "writeH5AD(sce, \"rna.h5ad\", X_name = \"counts\")\n", "writeH5AD(altExp(sce, \"ADT\"), \"adt.h5ad\", X_name = \"counts\")\n", "\n", "# Seurat: one assay per file\n", "writeH5AD(as.SingleCellExperiment(so, assay = \"RNA\"), \"rna.h5ad\", X_name = \"counts\")\n", "writeH5AD(as.SingleCellExperiment(so, assay = \"ADT\"), \"adt.h5ad\", X_name = \"counts\")\n", "```\n", "\n", "The cell metadata (`colData` of a SingleCellExperiment, `meta.data` of a Seurat\n", "object) becomes `obs` of the RNA file.\n", "\n", "## 7. Check before a long run\n", "\n", "- **Modality names.** A modality with any other name than `rna`, `adt`, `atac`\n", " is left out of the model without an error.\n", "- **Empty cells.** A cell whose counts in one modality are all zero is treated\n", " as not measured in that modality during training, whatever `data.present` says.\n", "- **Number of features.** Counts are converted to dense matrices for training,\n", " so keep the variable features rather than every gene or peak. The cell below\n", " keeps the top genes and leaves the counts raw.\n", "- **Batch sizes.** With the default `balance_batches=True`, training uses the\n", " same number of cells from every batch, set by the smallest one. The embedding\n", " is still returned for all cells." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-22", "metadata": {}, "outputs": [], "source": [ "tmp = rna.copy()\n", "sc.pp.normalize_total(tmp, target_sum=1e4)\n", "sc.pp.log1p(tmp)\n", "sc.pp.highly_variable_genes(tmp, n_top_genes=500, batch_key=\"batch\")\n", "rna_hvg = rna[:, tmp.var[\"highly_variable\"]].copy() # still raw counts\n", "print(rna_hvg.shape)" ] } ], "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 }