{ "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": [ "# Feature attribution\n", "\n", "Once m3 can predict disease, attribution asks which genes, cells and cell types drove\n", "that prediction. We train on the full reference, then trace each prediction back to\n", "the genes, cells, and cell types behind it." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-02", "metadata": { "execution": { "iopub.execute_input": "2026-07-13T10:09:23.845750Z", "iopub.status.busy": "2026-07-13T10:09:23.845634Z", "iopub.status.idle": "2026-07-13T10:09:24.978637Z", "shell.execute_reply": "2026-07-13T10:09:24.977839Z" } }, "outputs": [], "source": [ "import os\n", "import pandas as pd\n", "import m3\n", "\n", "OUT = \"./tutorial_out_demo/03_attribution\"\n", "os.makedirs(OUT, exist_ok=True)" ] }, { "cell_type": "markdown", "id": "cell-03", "metadata": {}, "source": [ "## 1. Load the demo data" ] }, { "cell_type": "code", "execution_count": null, "id": "cell-04", "metadata": { "execution": { "iopub.execute_input": "2026-07-13T10:09:24.982463Z", "iopub.status.busy": "2026-07-13T10:09:24.982006Z", "iopub.status.idle": "2026-07-13T10:09:25.372846Z", "shell.execute_reply": "2026-07-13T10:09:25.371864Z" } }, "outputs": [], "source": [ "data = m3.datasets.liu_demo()\n", "print(data)" ] }, { "cell_type": "markdown", "id": "cell-05", "metadata": {}, "source": [ "## 2. Build and train the model\n", "\n", "Same setup as the patient-prediction tutorial, minus the held-out batch (we\n", "attribute on the full reference). `.train()` fits both the integration model and the\n", "disease predictor; attribution explains that predictor.\n", "\n", "Training on the full demo takes about half an hour on a laptop CPU, and longer on\n", "Colab. To skip it, do not run the next cell; run the one after it, which loads the\n", "trained model from a file instead." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-06", "metadata": { "execution": { "iopub.execute_input": "2026-07-13T10:09:25.376250Z", "iopub.status.busy": "2026-07-13T10:09:25.375954Z", "iopub.status.idle": "2026-07-13T10:32:35.555820Z", "shell.execute_reply": "2026-07-13T10:32:35.554975Z" } }, "outputs": [], "source": [ "model = m3.M3(\n", " data,\n", " condition_keys=[\"cond_group\", \"Age_interval\"],\n", " target_condition=\"cond_group\",\n", " celltype_key=\"mergedcelltype\",\n", " batch_key=\"batch\",\n", " donor_key=\"sample_id\",\n", " embedding_dim=30,\n", ")\n", "model.train(max_epochs=500)\n", "print(\"capabilities:\", model.capabilities)" ] }, { "cell_type": "markdown", "id": "cell-07", "metadata": {}, "source": [ "Instead of training, this cell loads the trained model from a file that ships with\n", "m3. The file was written with `model.save(...)` after the training above;\n", "`m3.M3.load(...)` reads it back and needs the same `data`." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-08", "metadata": {}, "outputs": [], "source": [ "model = m3.M3.load(m3.datasets.liu_demo_model(\"attribution\"), data)\n", "print(\"capabilities:\", model.capabilities)" ] }, { "cell_type": "markdown", "id": "cell-09", "metadata": {}, "source": [ "## 3. Attribute and rank the cell types\n", "\n", "`model.attribute(reference_labels=[\"HC\"])` scores how much each gene, cell, and cell\n", "type pushed the prediction away from the reference label (HC, i.e. healthy). Here we\n", "look at the **top cell types**: `attr.top_celltypes(...)` ranks them, keeping only\n", "cell types with enough cells in each condition so a small group can't mislead the\n", "ranking." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-10", "metadata": { "execution": { "iopub.execute_input": "2026-07-13T10:32:35.559487Z", "iopub.status.busy": "2026-07-13T10:32:35.559147Z", "iopub.status.idle": "2026-07-13T10:32:51.997867Z", "shell.execute_reply": "2026-07-13T10:32:51.996836Z" } }, "outputs": [], "source": [ "attr = model.attribute(reference_labels=[\"HC\"])\n", "print(\"top cell types (filtered: >= 200 cells per condition):\\n\",\n", " attr.top_celltypes(min_cells_per_condition=200).to_string(index=False))" ] }, { "cell_type": "markdown", "id": "cell-11", "metadata": {}, "source": [ "## 4. Top genes\n", "\n", "`attr.top_genes(...)` ranks the genes by how strongly they drove the prediction.\n", "`min_cells_per_condition` keeps only cell types with enough cells in each condition\n", "(so a tiny group can't dominate the ranking), and housekeeping / ribosomal genes are\n", "dropped." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-12", "metadata": { "execution": { "iopub.execute_input": "2026-07-13T10:32:52.001073Z", "iopub.status.busy": "2026-07-13T10:32:52.000946Z", "iopub.status.idle": "2026-07-13T10:32:52.030225Z", "shell.execute_reply": "2026-07-13T10:32:52.029612Z" } }, "outputs": [], "source": [ "top_rna = attr.top_genes(n=100, min_cells_per_condition=200, modality=\"rna\")\n", "print(f\"top-100 RNA genes (computed over {int(top_rna['n_celltypes_used'].iloc[0])} balanced cell types):\")\n", "print(top_rna.head(15).to_string(index=False))\n", "top_rna.to_csv(os.path.join(OUT, \"gene_importance_top100_rna.csv\"), index=False)" ] }, { "cell_type": "markdown", "id": "cell-13", "metadata": {}, "source": [ "## 5. Save the attribution\n", "\n", "The full cells-by-features attribution matrix, as an HDF5 array and an AnnData." ] }, { "cell_type": "code", "execution_count": null, "id": "cell-14", "metadata": { "execution": { "iopub.execute_input": "2026-07-13T10:32:52.033512Z", "iopub.status.busy": "2026-07-13T10:32:52.033207Z", "iopub.status.idle": "2026-07-13T10:32:52.479924Z", "shell.execute_reply": "2026-07-13T10:32:52.478897Z" } }, "outputs": [], "source": [ "import h5py\n", "import anndata as ad\n", "\n", "attr_mat = attr.attribution\n", "present = [m for m in (\"rna\", \"adt\", \"atac\") if m in data.modality_names]\n", "feat_names = [f for mm in present for f in list(data.var[mm])][: attr_mat.shape[1]]\n", "\n", "with h5py.File(os.path.join(OUT, \"attribution.h5\"), \"w\") as f:\n", " f[\"data\"] = attr_mat\n", "\n", "_obs = model.cell_metadata.astype(str).reset_index(drop=True)\n", "ad.AnnData(X=attr_mat, obs=_obs, var=pd.DataFrame(index=feat_names)).write_h5ad(\n", " os.path.join(OUT, \"attribution.h5ad\"))\n", "print(\"saved attribution -> .h5 (['data']) / .h5ad in\", OUT)" ] }, { "cell_type": "markdown", "id": "cell-15", "metadata": {}, "source": [ "**Done.** The genes, cells, and cell types behind m3's Severe-vs-HC prediction." ] } ], "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.10.12" } }, "nbformat": 4, "nbformat_minor": 5 }