[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M75N6RPRDCCYTM2A3X0Z0V5Z":3,"skill-same:01M75N6RPRDCCYTM2A3X0Z0V5Z":46},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":6,"updatedAt":31,"install":32,"resources":45},"01M75N6RPRDCCYTM2A3X0Z0V5Z","muon-multiomics-singlecell",null,"Multi-modal single-cell analysis with muon\u002FMuData. Joint RNA+ATAC (10x Multiome), CITE-seq (RNA+protein), other multi-omics. MuData holds per-modality AnnData with shared obs. WNN joint embedding, per-modality preprocessing, MOFA factor analysis. Use scanpy-scrna-seq for single-modality RNA; use muon when combining 2+ omics from the same cells.","stanfish06\u002Fskillquarium","stanfish06","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F93099613?v=4","01M75F1CK4ZW109ZK3T26VN52F","Zhiyuan","01M75F1CM53VH6F79DZ8GXKKES",12,"BSD-3-Clause","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fmuon-multiomics-singlecell\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: \"muon-multiomics-singlecell\"\ndescription: \"Multi-modal single-cell analysis with muon\u002FMuData. Joint RNA+ATAC (10x Multiome), CITE-seq (RNA+protein), other multi-omics. MuData holds per-modality AnnData with shared obs. WNN joint embedding, per-modality preprocessing, MOFA factor analysis. Use scanpy-scrna-seq for single-modality RNA; use muon when combining 2+ omics from the same cells.\"\nlicense: \"BSD-3-Clause\"\n---\n\n# muon — Multi-Modal Single-Cell Analysis\n\n## Overview\n\nmuon is a Python framework for multi-modal single-cell data analysis that extends the AnnData ecosystem. Its core data structure, `MuData`, holds multiple `AnnData` objects (one per modality: RNA, ATAC, protein, etc.) with shared observation and variable axes, enabling coordinated operations across all modalities. muon provides modality-specific preprocessing routines (TF-IDF and LSI for ATAC, CLR normalization for surface proteins), Weighted Nearest Neighbor (WNN) graph construction for joint dimensionality reduction, and cross-modal analysis tools. It integrates directly with scanpy, scvi-tools, and MOFA+ for a complete multi-omics single-cell workflow.\n\n## When to Use\n\n- Analyzing 10x Genomics Multiome data (simultaneous RNA + ATAC from the same nuclei)\n- Processing CITE-seq experiments (RNA + surface protein from the same cells)\n- Building joint UMAP embeddings that integrate signals from two or more modalities via WNN\n- Preprocessing ATAC-seq modalities (TF-IDF normalization, LSI dimensionality reduction)\n- Normalizing surface protein data with centered log-ratio (CLR) normalization\n- Performing cross-modal feature linkage (associating ATAC peaks with nearby gene expression)\n- Applying MOFA+ factor analysis across multiple omics layers within a unified container\n- Use **scanpy-scrna-seq** instead when analyzing a single RNA-seq modality without any co-measured omics\n- Use **scvi-tools (MultiVI \u002F totalVI)** when you need probabilistic deep generative batch correction across modalities\n\n## Prerequisites\n\n- **Python packages**: `muon>=0.1.6`, `scanpy>=1.10`, `anndata>=0.10`, `numpy`, `scipy`, `pandas`, `matplotlib`, `leidenalg`\n- **Data requirements**: 10x Multiome h5 or h5mu files, or per-modality AnnData objects (cells x features) sharing the same `obs_names`\n- **Environment**: Python 3.9+; 16 GB+ RAM for datasets >50k cells; optional `mofapy2` for MOFA factor analysis\n\n```bash\npip install \"muon[atac]\" \"scanpy[leiden]\" anndata\n# Optional: for MOFA+ integration\npip install mofapy2\n```\n\n## Quick Start\n\n```python\nimport muon as mu\nimport scanpy as sc\nimport numpy as np\nimport anndata as ad\nimport pandas as pd\n\n# Simulate a small RNA + ATAC MuData object (200 cells)\nnp.random.seed(42)\nn_cells = 200\nrna  = ad.AnnData(np.abs(np.random.negative_binomial(5, 0.3, (n_cells, 2000))).astype(float),\n                  obs=pd.DataFrame(index=[f\"cell_{i}\" for i in range(n_cells)]),\n                  var=pd.DataFrame(index=[f\"gene_{j}\" for j in range(2000)]))\natac = ad.AnnData(np.abs(np.random.negative_binomial(2, 0.5, (n_cells, 5000))).astype(float),\n                  obs=rna.obs.copy(),\n                  var=pd.DataFrame(index=[f\"peak_{j}\" for j in range(5000)]))\n\nmdata = mu.MuData({\"rna\": rna, \"atac\": atac})\nprint(mdata)\n# MuData object with n_obs × n_vars = 200 × 7000\n#   2 modalities\n#     rna: 200 × 2000\n#     atac: 200 × 5000\n\n# Minimal preprocessing\nsc.pp.normalize_total(mdata[\"rna\"], target_sum=1e4)\nsc.pp.log1p(mdata[\"rna\"])\nsc.pp.highly_variable_genes(mdata[\"rna\"], n_top_genes=500)\nsc.pp.pca(mdata[\"rna\"])\n\nmu.atac.pp.tfidf(mdata[\"atac\"])\nmu.atac.tl.lsi(mdata[\"atac\"])\n\n# WNN joint embedding\n# Per-modality graphs are REQUIRED first: mu.pp.neighbors reads each modality's\n# .uns[\"neighbors\"][\"params\"] to learn which embedding to use.\nsc.pp.neighbors(mdata[\"rna\"],  use_rep=\"X_pca\")\nsc.pp.neighbors(mdata[\"atac\"], use_rep=\"X_lsi\")\nmu.pp.neighbors(mdata, key_added=\"wnn\")\nmu.tl.umap(mdata, neighbors_key=\"wnn\")\nsc.tl.leiden(mdata, neighbors_key=\"wnn\", key_added=\"leiden_wnn\")\nprint(f\"Clusters: {mdata.obs['leiden_wnn'].nunique()}\")\n```\n\n## Core API\n\n### Module 1: MuData Creation and I\u002FO\n\n`MuData` is the central container: a dictionary of `AnnData` modalities plus shared `obs` and `var` slots. The `mdata.obs` DataFrame merges per-modality observation metadata with a modality prefix for ambiguous columns.\n\n```python\nimport muon as mu\nimport anndata as ad\nimport numpy as np\nimport pandas as pd\n\n# --- Build from per-modality AnnData objects ---\nn_cells = 300\nrna  = ad.AnnData(np.abs(np.random.negative_binomial(5, 0.3, (n_cells, 3000))).astype(float),\n                  obs=pd.DataFrame(index=[f\"cell_{i}\" for i in range(n_cells)]),\n                  var=pd.DataFrame(index=[f\"gene_{j}\" for j in range(3000)]))\nprot = ad.AnnData(np.abs(np.random.randn(n_cells, 30)) + 3,\n                  obs=rna.obs.copy(),\n                  var=pd.DataFrame(index=[f\"protein_{j}\" for j in range(30)]))\n\nmdata = mu.MuData({\"rna\": rna, \"protein\": prot})\nprint(mdata)\n# Access individual modalities\nprint(mdata.mod[\"rna\"])        # AnnData: 300 × 3000\nprint(mdata[\"rna\"])            # same shorthand\nprint(mdata.obs.head())        # shared observation metadata\nprint(mdata.obs_names[:5])     # cell barcodes\n\n# Save and load\nmdata.write(\"multiome_data.h5mu\")\nmdata2 = mu.read(\"multiome_data.h5mu\")\nprint(f\"Loaded: {mdata2.n_obs} cells, {mdata2.n_mod} modalities\")\n```\n\n```python\n# --- Load from 10x Multiome h5 file ---\n# mdata = mu.read_10x_h5(\"filtered_feature_bc_matrix.h5\")\n# Produces MuData with mdata[\"rna\"] and mdata[\"atac\"] modalities\n\n# --- Subsetting by cells or features ---\n# Select high-quality cells (e.g., after QC)\nmask = np.ones(mdata.n_obs, dtype=bool)  # replace with actual QC mask\nmdata_filtered = mdata[mask].copy()\nprint(f\"After filtering: {mdata_filtered.n_obs} cells\")\n\n# Propagate obs mask to each modality\nmu.pp.intersect_obs(mdata)   # ensures obs consistency across modalities\n```\n\n### Module 2: RNA Modality Preprocessing\n\nStandard scRNA-seq preprocessing applied to `mdata[\"rna\"]` using scanpy functions. The RNA modality is preprocessed identically to a standalone scanpy workflow but operates on the slice of the MuData container.\n\n```python\nimport scanpy as sc\nimport numpy as np\n\n# Assume mdata[\"rna\"] has raw integer counts\nrna = mdata[\"rna\"]\n\n# QC metrics\nsc.pp.calculate_qc_metrics(rna, percent_top=None, log1p=False, inplace=True)\nrna.obs[\"pct_counts_mt\"] = rna[:, rna.var_names.str.startswith(\"MT-\")].X.sum(axis=1).A1 \u002F rna.obs[\"total_counts\"] * 100\n\n# Filter cells and genes\nmin_genes, max_genes, max_mt = 200, 5000, 20\nsc.pp.filter_cells(rna, min_genes=min_genes)\nsc.pp.filter_genes(rna, min_cells=5)\nrna = rna[(rna.obs[\"n_genes_by_counts\"] \u003C max_genes) &\n          (rna.obs[\"pct_counts_mt\"] \u003C max_mt)].copy()\nprint(f\"RNA after QC: {rna.n_obs} cells × {rna.n_vars} genes\")\n\n# Normalize and log-transform\nsc.pp.normalize_total(rna, target_sum=1e4)\nsc.pp.log1p(rna)\n\n# Highly variable genes\nsc.pp.highly_variable_genes(rna, n_top_genes=3000, flavor=\"seurat_v3\",\n                             batch_key=None)\nprint(f\"HVGs: {rna.var['highly_variable'].sum()}\")\n\n# PCA on HVGs\nsc.pp.pca(rna, n_comps=50, use_highly_variable=True)\nprint(f\"PCA embedding shape: {rna.obsm['X_pca'].shape}\")\n# Update slice in MuData\nmdata.mod[\"rna\"] = rna\n```\n\n### Module 3: ATAC Modality Preprocessing\n\nATAC-seq modalities require a different normalization strategy. TF-IDF (term frequency–inverse document frequency) normalizes peak accessibility across cells and peaks; LSI (latent semantic indexing, equivalent to truncated SVD after TF-IDF) produces a low-dimensional embedding. The first LSI component typically captures sequencing depth rather than biology and is excluded.\n\n```python\n# Assume mdata[\"atac\"] contains raw binary or integer peak accessibility counts\natac = mdata[\"atac\"]\n\n# Basic QC: filter low-coverage cells and low-frequency peaks\nsc.pp.calculate_qc_metrics(atac, percent_top=None, log1p=False, inplace=True)\nsc.pp.filter_cells(atac, min_genes=200)     # min peaks detected\nsc.pp.filter_genes(atac, min_cells=10)      # min cells a peak appears in\nprint(f\"ATAC after QC: {atac.n_obs} cells × {atac.n_vars} peaks\")\n\n# TF-IDF normalization (log(TF) * log(IDF) scaling)\nmu.atac.pp.tfidf(atac, scale_factor=1e4)\nprint(\"TF-IDF normalization complete\")\nprint(f\"ATAC data range: [{atac.X.min():.2f}, {atac.X.max():.2f}]\")\n\n# LSI dimensionality reduction (truncated SVD on TF-IDF matrix)\nmu.atac.tl.lsi(atac, n_comps=50)\n# LSI component 1 correlates with sequencing depth — exclude it yourself.\n# mu.atac.tl.lsi stores ALL n_comps components in X_lsi; component 1 is NOT\n# dropped. See Best Practices #2 before feeding X_lsi into WNN.\nprint(f\"LSI embedding shape: {atac.obsm['X_lsi'].shape}\")\n\n# Update modality in MuData\nmdata.mod[\"atac\"] = atac\n```\n\n### Module 4: WNN Graph and Joint Embedding\n\nWeighted Nearest Neighbor (WNN) integrates multiple modality embeddings by learning per-cell, per-modality weights. Cells with high-quality RNA signal receive higher RNA weight; cells with cleaner ATAC signal receive higher ATAC weight. The resulting WNN graph is used for UMAP layout and Leiden clustering.\n\n```python\n# Compute per-modality neighbor graphs first — REQUIRED, not optional.\n# mu.pp.neighbors reads use_rep \u002F n_pcs \u002F n_neighbors out of each modality's\n# .uns[\"neighbors\"][\"params\"]; without this it raises\n# ValueError: Did not find .uns[\"neighbors\"] for modality \"rna\".\nsc.pp.neighbors(mdata[\"rna\"],  use_rep=\"X_pca\", n_neighbors=30)\nsc.pp.neighbors(mdata[\"atac\"], use_rep=\"X_lsi\", n_neighbors=30)\n\n# WNN joint neighbor graph across modalities\nmu.pp.neighbors(\n    mdata,\n    key_added=\"wnn\",\n    n_neighbors=30,\n    random_state=42,\n)\nprint(\"WNN graph built. Keys:\", list(mdata.obsp.keys()))\n# Expected: ['wnn_connectivities', 'wnn_distances']\n\n# UMAP from WNN graph — use mu.tl.umap, not sc.tl.umap (see Best Practices #3)\nmu.tl.umap(mdata, neighbors_key=\"wnn\", random_state=42)\nprint(f\"UMAP embedding shape: {mdata.obsm['X_umap'].shape}\")\n\n# Leiden clustering from WNN graph\nsc.tl.leiden(mdata, neighbors_key=\"wnn\", resolution=0.5, key_added=\"leiden_wnn\")\nn_clusters = mdata.obs[\"leiden_wnn\"].nunique()\nprint(f\"Leiden WNN clustering: {n_clusters} clusters at resolution 0.5\")\n```\n\n### Module 5: Visualization\n\nmuon extends scanpy's plotting interface with modality-aware functions. `mu.pl.embedding()` and `mu.pl.umap()` color joint UMAP embeddings by features from any modality, including modality-prefixed feature names (e.g. `\"rna:CD3E\"`). Plain `sc.pl.umap()` cannot resolve those prefixed names and cannot index a `MuData` object — always use the `mu.pl.*` equivalents on `mdata`.\n\n```python\nimport matplotlib.pyplot as plt\n\n# Joint UMAP colored by cluster assignment\nmu.pl.umap(mdata, color=\"leiden_wnn\", title=\"WNN Leiden clusters\",\n           legend_loc=\"on data\", show=False)\nplt.savefig(\"wnn_umap_clusters.png\", dpi=150, bbox_inches=\"tight\")\nplt.close()\nprint(\"Saved wnn_umap_clusters.png\")\n\n# Color by RNA gene expression on joint UMAP\nmu.pl.umap(mdata, color=[\"rna:CD3E\", \"rna:CD19\", \"rna:CD14\"],\n           use_raw=False, vmax=\"p99\", show=False, ncols=3)\nplt.savefig(\"wnn_umap_markers.png\", dpi=150, bbox_inches=\"tight\")\nplt.close()\nprint(\"Saved wnn_umap_markers.png\")\n```\n\n```python\n# Per-modality scatter \u002F embedding plots\nmu.pl.embedding(mdata, basis=\"X_umap\", color=\"leiden_wnn\",\n                show=False)\nplt.savefig(\"embedding_clusters.png\", dpi=150, bbox_inches=\"tight\")\nplt.close()\n\n# Violin plot: RNA QC metrics per cluster\nsc.pl.violin(mdata[\"rna\"], keys=[\"n_genes_by_counts\", \"total_counts\"],\n             groupby=mdata.obs.loc[mdata[\"rna\"].obs_names, \"leiden_wnn\"],\n             rotation=90, show=False)\nplt.savefig(\"rna_qc_by_cluster.png\", dpi=150, bbox_inches=\"tight\")\nplt.close()\nprint(\"Saved rna_qc_by_cluster.png\")\n```\n\n### Module 6: Cross-Modal Analysis\n\nCross-modal analysis links features across modalities — for example, associating ATAC peak accessibility near a gene's promoter with its RNA expression, or applying MOFA+ to find shared latent factors.\n\n```python\n# --- Peak-to-gene distance annotation ---\n# Annotate ATAC peaks with nearest gene (requires genomic coordinates in var)\n# mdata[\"atac\"].var should contain columns: chrom, chromStart, chromEnd\n# mu.atac.tl.rank_peaks_groups(mdata, groupby=\"leiden_wnn\")  # differential peaks\n\n# --- Differentially accessible peaks per cluster ---\natac = mdata[\"atac\"]\n# Transfer cluster labels from MuData obs to ATAC obs\natac.obs[\"cluster\"] = mdata.obs.loc[atac.obs_names, \"leiden_wnn\"].values\nsc.tl.rank_genes_groups(atac, groupby=\"cluster\", method=\"wilcoxon\",\n                        use_raw=False)\ntop_peaks = sc.get.rank_genes_groups_df(atac, group=\"0\").head(5)\nprint(\"Top differential peaks in cluster 0:\")\nprint(top_peaks[[\"names\", \"logfoldchanges\", \"pvals_adj\"]])\n```\n\n```python\n# --- MOFA+ factor analysis on MuData ---\n# Requires: pip install mofapy2\ntry:\n    mu.tl.mofa(mdata, n_factors=10, seed=42,\n               use_obs=\"all\", outfile=\"mofa_model.hdf5\")\n    # Factor scores stored in mdata.obsm[\"X_mofa\"]\n    print(f\"MOFA factors: {mdata.obsm['X_mofa'].shape}\")\n    # Variance explained per factor per modality\n    # Inspect with mdata.uns[\"mofa\"]\nexcept ImportError:\n    print(\"Install mofapy2 to enable MOFA factor analysis\")\n```\n\n## Common Workflows\n\n### Workflow 1: Full 10x Multiome (RNA + ATAC) Joint WNN Clustering\n\n**Goal**: Process paired RNA and ATAC data from 10x Genomics Multiome, build a WNN joint embedding, cluster cells, and identify RNA marker genes per cluster.\n\n```python\nimport muon as mu\nimport scanpy as sc\nimport numpy as np\nimport anndata as ad\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# --- 1. Simulate 10x Multiome-like data (replace with mu.read_10x_h5()) ---\nnp.random.seed(0)\nn_cells = 400\ncell_ids = [f\"AAACGAATC{i:05d}-1\" for i in range(n_cells)]\n# Simulate two cell types with distinct expression\u002Faccessibility\nlabels = np.array([\"typeA\"] * 200 + [\"typeB\"] * 200)\n\nrna_counts = np.abs(np.random.negative_binomial(6, 0.35, (n_cells, 2000))).astype(float)\nrna_counts[:200, :100] += 10   # typeA marker genes\nrna_counts[200:, 100:200] += 10  # typeB marker genes\n\natac_counts = np.abs(np.random.binomial(1, 0.05, (n_cells, 50000))).astype(float)\natac_counts[:200, :5000] += 1   # typeA accessible peaks\natac_counts[200:, 5000:10000] += 1  # typeB accessible peaks\n\nrna  = ad.AnnData(rna_counts,\n                  obs=pd.DataFrame({\"cell_type\": labels}, index=cell_ids),\n                  var=pd.DataFrame(index=[f\"gene_{j}\" for j in range(2000)]))\natac = ad.AnnData(atac_counts,\n                  obs=pd.DataFrame({\"cell_type\": labels}, index=cell_ids),\n                  var=pd.DataFrame(index=[f\"peak_{j}\" for j in range(50000)]))\n\nmdata = mu.MuData({\"rna\": rna, \"atac\": atac})\nprint(f\"Loaded: {mdata}\")\n\n# --- 2. RNA preprocessing ---\nsc.pp.filter_cells(mdata[\"rna\"], min_genes=50)\nsc.pp.filter_genes(mdata[\"rna\"], min_cells=5)\nsc.pp.normalize_total(mdata[\"rna\"], target_sum=1e4)\nsc.pp.log1p(mdata[\"rna\"])\nsc.pp.highly_variable_genes(mdata[\"rna\"], n_top_genes=500)\nsc.pp.pca(mdata[\"rna\"], n_comps=30, use_highly_variable=True)\nprint(f\"RNA PCA: {mdata['rna'].obsm['X_pca'].shape}\")\n\n# --- 3. ATAC preprocessing: TF-IDF + LSI ---\nsc.pp.filter_cells(mdata[\"atac\"], min_genes=100)\nsc.pp.filter_genes(mdata[\"atac\"], min_cells=5)\nmu.atac.pp.tfidf(mdata[\"atac\"])\nmu.atac.tl.lsi(mdata[\"atac\"], n_comps=30)\nprint(f\"ATAC LSI: {mdata['atac'].obsm['X_lsi'].shape}\")\n\n# --- 4. Per-modality neighbors (REQUIRED before WNN) ---\nsc.pp.neighbors(mdata[\"rna\"],  use_rep=\"X_pca\", n_neighbors=15)\nsc.pp.neighbors(mdata[\"atac\"], use_rep=\"X_lsi\", n_neighbors=15)\n\n# --- 5. WNN joint neighbor graph ---\nmu.pp.intersect_obs(mdata)   # align obs after per-modality filtering\nmu.pp.neighbors(mdata, key_added=\"wnn\",\n                n_neighbors=15, random_state=42)\n\n# --- 6. UMAP + Leiden clustering ---\nmu.tl.umap(mdata, neighbors_key=\"wnn\", random_state=42)\nsc.tl.leiden(mdata, neighbors_key=\"wnn\", resolution=0.5, key_added=\"leiden_wnn\")\nprint(f\"Clusters: {mdata.obs['leiden_wnn'].value_counts().to_dict()}\")\n\n# --- 7. Marker genes per cluster ---\nsc.tl.rank_genes_groups(mdata[\"rna\"],\n                        groupby=mdata.obs.loc[mdata[\"rna\"].obs_names, \"leiden_wnn\"],\n                        method=\"wilcoxon\", use_raw=False)\ntop_markers = sc.get.rank_genes_groups_df(mdata[\"rna\"], group=\"0\").head(5)\nprint(\"Top RNA markers for cluster 0:\")\nprint(top_markers[[\"names\", \"logfoldchanges\", \"pvals_adj\"]])\n\n# --- 8. Visualization ---\nfig, axes = plt.subplots(1, 2, figsize=(12, 5))\nmu.pl.umap(mdata, color=\"leiden_wnn\", ax=axes[0], show=False, title=\"WNN clusters\")\nmu.pl.umap(mdata, color=\"rna:gene_0\",  ax=axes[1], show=False, title=\"gene_0 expression\",\n           use_raw=False, vmax=\"p99\")\nplt.tight_layout()\nplt.savefig(\"multiome_wnn_pipeline.png\", dpi=150, bbox_inches=\"tight\")\nplt.close()\nprint(\"Saved multiome_wnn_pipeline.png\")\n```\n\n### Workflow 2: CITE-seq (RNA + Surface Protein) Analysis\n\n**Goal**: Process CITE-seq data with paired RNA and antibody-derived tag (ADT\u002Fprotein) counts. Normalize proteins with CLR, annotate cell types from protein markers, and build a joint UMAP.\n\n```python\nimport muon as mu\nimport scanpy as sc\nimport numpy as np\nimport anndata as ad\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy.sparse import csr_matrix\n\nnp.random.seed(1)\nn_cells = 350\ncell_ids = [f\"CITESEQ_{i:04d}\" for i in range(n_cells)]\n\n# Simulate RNA + protein modalities\n# Three cell types: T-cells (CD3+CD4+), B-cells (CD19+CD20+), Monocytes (CD14+CD16+)\nn_t, n_b, n_mono = 120, 130, 100\nlabels = [\"Tcell\"] * n_t + [\"Bcell\"] * n_b + [\"Monocyte\"] * n_mono\n\nrna_mat = np.abs(np.random.negative_binomial(4, 0.4, (n_cells, 1500))).astype(float)\nrna_mat[:n_t, :50] += 15       # T-cell RNA markers\nrna_mat[n_t:n_t+n_b, 50:100] += 15   # B-cell RNA markers\nrna_mat[n_t+n_b:, 100:150] += 15     # Monocyte RNA markers\n\n# 20 surface proteins: first 5 T-cell, next 5 B-cell, next 5 Monocyte, rest baseline\nprot_mat = np.abs(np.random.normal(2, 0.5, (n_cells, 20)))\nprot_mat[:n_t, :5] += 8          # CD3, CD4, CD5, CD7, CD8 for T-cells\nprot_mat[n_t:n_t+n_b, 5:10] += 8  # CD19, CD20, CD22, CD24, CD79 for B-cells\nprot_mat[n_t+n_b:, 10:15] += 8    # CD14, CD16, CD64, CD11b, HLA-DR for Monocytes\n\nprotein_names = [\"CD3\", \"CD4\", \"CD5\", \"CD7\", \"CD8\",\n                 \"CD19\", \"CD20\", \"CD22\", \"CD24\", \"CD79a\",\n                 \"CD14\", \"CD16\", \"CD64\", \"CD11b\", \"HLA-DR\",\n                 \"CD25\", \"CD56\", \"CD45RA\", \"CD45RO\", \"IgG-ctrl\"]\n\nrna = ad.AnnData(csr_matrix(rna_mat),\n                 obs=pd.DataFrame({\"cell_type\": labels}, index=cell_ids),\n                 var=pd.DataFrame(index=[f\"gene_{j}\" for j in range(1500)]))\nprot = ad.AnnData(prot_mat,\n                  obs=pd.DataFrame({\"cell_type\": labels}, index=cell_ids),\n                  var=pd.DataFrame(index=protein_names))\n\nmdata = mu.MuData({\"rna\": rna, \"protein\": prot})\nprint(mdata)\n\n# --- RNA preprocessing ---\nsc.pp.normalize_total(mdata[\"rna\"], target_sum=1e4)\nsc.pp.log1p(mdata[\"rna\"])\nsc.pp.highly_variable_genes(mdata[\"rna\"], n_top_genes=500)\nsc.pp.pca(mdata[\"rna\"], n_comps=30, use_highly_variable=True)\n\n# --- Protein CLR normalization (Centered Log-Ratio) ---\n# CLR normalizes each protein across cells: log(x \u002F geometric_mean(x))\nmu.prot.pp.clr(mdata[\"protein\"])\nprint(\"Protein CLR normalization applied\")\nprint(f\"Protein data range: [{mdata['protein'].X.min():.2f}, {mdata['protein'].X.max():.2f}]\")\n\n# PCA on protein modality\nsc.pp.pca(mdata[\"protein\"], n_comps=min(15, prot.n_vars - 1))\n\n# --- WNN joint embedding ---\n# Per-modality graphs first (REQUIRED — mu.pp.neighbors reads their .uns params)\nsc.pp.neighbors(mdata[\"rna\"],     use_rep=\"X_pca\", n_neighbors=20)\nsc.pp.neighbors(mdata[\"protein\"], use_rep=\"X_pca\", n_neighbors=20)\nmu.pp.neighbors(mdata, key_added=\"wnn\", n_neighbors=20, random_state=0)\nmu.tl.umap(mdata, neighbors_key=\"wnn\", random_state=0)\nsc.tl.leiden(mdata, neighbors_key=\"wnn\", resolution=0.4, key_added=\"leiden_wnn\")\n\n# --- Protein-based cell type annotation ---\n# Compute mean CLR protein per cluster\nprot_df = pd.DataFrame(\n    mdata[\"protein\"].X,\n    index=mdata[\"protein\"].obs_names,\n    columns=protein_names\n)\nprot_df[\"cluster\"] = mdata.obs.loc[mdata[\"protein\"].obs_names, \"leiden_wnn\"].values\ncluster_means = prot_df.groupby(\"cluster\").mean()\nprint(\"\\nMean CLR protein per cluster:\")\nprint(cluster_means[[\"CD3\", \"CD4\", \"CD19\", \"CD14\"]].round(2))\n\n# --- Visualization ---\nfig, axes = plt.subplots(1, 3, figsize=(15, 4))\nmu.pl.umap(mdata, color=\"leiden_wnn\",   ax=axes[0], show=False, title=\"WNN Leiden\")\nmu.pl.umap(mdata, color=\"protein:CD3\",  ax=axes[1], show=False, title=\"CD3 (CLR)\",\n           use_raw=False, vmax=\"p99\")\nmu.pl.umap(mdata, color=\"protein:CD19\", ax=axes[2], show=False, title=\"CD19 (CLR)\",\n           use_raw=False, vmax=\"p99\")\nplt.tight_layout()\nplt.savefig(\"citeseq_joint_umap.png\", dpi=150, bbox_inches=\"tight\")\nplt.close()\nprint(\"Saved citeseq_joint_umap.png\")\n\n# --- Dot plot: protein markers per cluster ---\nsc.pl.dotplot(mdata[\"protein\"],\n              var_names=[\"CD3\", \"CD4\", \"CD19\", \"CD20\", \"CD14\", \"CD16\"],\n              groupby=mdata.obs.loc[mdata[\"protein\"].obs_names, \"leiden_wnn\"],\n              show=False)\nplt.savefig(\"citeseq_protein_dotplot.png\", dpi=150, bbox_inches=\"tight\")\nplt.close()\nprint(\"Saved citeseq_protein_dotplot.png\")\n```\n\n## Key Parameters\n\n| Parameter | Module \u002F Function | Default | Range \u002F Options | Effect |\n|-----------|-------------------|---------|-----------------|--------|\n| `n_neighbors` | `mu.pp.neighbors()` | `30` | `10`–`100` | Neighborhood size for graph; lower = finer local structure |\n| `use_rep` | `sc.pp.neighbors()` on each modality | `None` (auto) | embedding key, e.g. `\"X_pca\"` \u002F `\"X_lsi\"` | Set per modality *before* WNN; `mu.pp.neighbors()` has no `use_rep` parameter and reads it from each modality's `.uns[\"neighbors\"][\"params\"]` |\n| `key_added` | `mu.pp.neighbors()` | `\"neighbors\"` | any string | Key under which graph is stored; use `\"wnn\"` for joint graphs |\n| `n_comps` | `sc.pp.pca()`, `mu.atac.tl.lsi()` | `50` | `10`–`100` | Number of reduced dimensions; 30–50 typical |\n| `resolution` | `sc.tl.leiden()` | `1.0` | `0.1`–`2.0` | Clustering granularity; lower = fewer, larger clusters |\n| `scale_factor` | `mu.atac.pp.tfidf()` | `1e4` | `1e3`–`1e5` | TF scaling constant before log transform |\n| `n_factors` | `mu.tl.mofa()` | `10` | `5`–`50` | Number of MOFA latent factors; use elbow on variance explained |\n| `target_sum` | `sc.pp.normalize_total()` | `1e4` | `1e3`–`1e6` | Library size normalization target per cell (RNA) |\n| `n_top_genes` | `sc.pp.highly_variable_genes()` | varies | `1000`–`5000` | Number of highly variable genes to retain for PCA |\n\n## Best Practices\n\n1. **Align obs before WNN**: After per-modality QC filtering, cell counts across modalities may differ. Always call `mu.pp.intersect_obs(mdata)` before WNN to ensure every modality has the same cell set.\n   ```python\n   mu.pp.intersect_obs(mdata)\n   print(f\"Shared cells after intersect: {mdata.n_obs}\")\n   ```\n\n2. **Drop LSI component 1 from ATAC**: The first LSI component captures sequencing depth (total counts per cell) rather than biological signal. `mu.atac.tl.lsi()` stores all components in `X_lsi`, so verify that component 1 correlates with `log_total_counts` before using `X_lsi` in WNN; if so, restrict to `X_lsi[:, 1:]`.\n   ```python\n   import numpy as np, pandas as pd\n   atac = mdata[\"atac\"]\n   corr = np.corrcoef(atac.obsm[\"X_lsi\"][:, 0],\n                      np.log1p(atac.obs[\"total_counts\"]))[0, 1]\n   print(f\"LSI1 vs log_counts correlation: {corr:.3f}\")\n   # If |corr| > 0.9, exclude component 1:\n   # atac.obsm[\"X_lsi\"] = atac.obsm[\"X_lsi\"][:, 1:]\n   ```\n\n3. **Use `key_added=\"wnn\"` consistently, and `mu.tl.umap()` for the joint graph**: Always name the joint graph `\"wnn\"` and pass `neighbors_key=\"wnn\"` downstream. Use `mu.tl.umap()` — not `sc.tl.umap()` — on a `MuData`: muon stores a per-modality `use_rep` dict in `mdata.uns[\"wnn\"][\"params\"]`, which scanpy cannot read (`TypeError: unhashable type: 'dict'`). `sc.tl.leiden(mdata, neighbors_key=\"wnn\")` does work. Mixing `neighbors_key` values silently uses the wrong graph.\n\n4. **CLR normalization for proteins, not log-normalization**: Antibody-derived tag (ADT) counts from CITE-seq have a different noise model than RNA. Use `mu.prot.pp.clr()` for per-protein CLR normalization. Do NOT apply `sc.pp.normalize_total()` + `sc.pp.log1p()` to the protein modality.\n\n5. **Store raw RNA counts before normalization**: Before any normalization, store the raw RNA counts in `mdata[\"rna\"].layers[\"counts\"]` and set `mdata[\"rna\"].raw = mdata[\"rna\"]`. This is required for downstream differential expression tests and scvi-tools integration.\n   ```python\n   import scipy.sparse as sp\n   mdata[\"rna\"].layers[\"counts\"] = mdata[\"rna\"].X.copy()\n   # Store pre-normalization snapshot\n   mdata[\"rna\"].raw = mdata[\"rna\"]\n   ```\n\n6. **Match WNN embedding dimensions**: The RNA PCA and ATAC LSI embeddings passed to WNN should have comparable dimensionality (e.g., both 30 or 50 components). Mismatched dimensions do not cause errors but can down-weight the smaller modality.\n\n## Common Recipes\n\n### Recipe: Compute Per-Cluster Modality Weights from WNN\n\nWhen to use: Inspect which cells rely more on RNA vs ATAC signal in the WNN graph. High RNA weight in a cluster suggests cleaner RNA data; high ATAC weight suggests stronger chromatin accessibility signal.\n\n```python\n# WNN stores per-cell modality weights in mdata.obsm after mu.pp.neighbors()\n# Key name: \"{key_added}_weights\" — check available keys\nprint([k for k in mdata.obsm.keys() if \"wnn\" in k.lower()])\n\n# If weights are stored (depends on muon version):\nif \"wnn_weights\" in mdata.obsm:\n    weights_df = pd.DataFrame(\n        mdata.obsm[\"wnn_weights\"],\n        index=mdata.obs_names,\n        columns=[\"rna_weight\", \"atac_weight\"]\n    )\n    weights_df[\"cluster\"] = mdata.obs[\"leiden_wnn\"].values\n    print(weights_df.groupby(\"cluster\").mean().round(3))\nelse:\n    # Proxy: compare RNA vs ATAC PCA explained variance per cell\n    rna_var  = np.var(mdata[\"rna\"].obsm[\"X_pca\"],  axis=1)\n    atac_var = np.var(mdata[\"atac\"].obsm[\"X_lsi\"], axis=1)\n    mdata.obs[\"rna_signal_proxy\"]  = rna_var \u002F (rna_var + atac_var)\n    mdata.obs[\"atac_signal_proxy\"] = atac_var \u002F (rna_var + atac_var)\n    print(mdata.obs[[\"rna_signal_proxy\", \"atac_signal_proxy\", \"leiden_wnn\"]].groupby(\"leiden_wnn\").mean().round(3))\n```\n\n### Recipe: Export Cluster Labels Back to Per-Modality AnnData\n\nWhen to use: After joint WNN clustering, copy shared cluster labels back into each modality's `.obs` for modality-specific downstream analyses (e.g., differential peaks within clusters).\n\n```python\n# Copy joint cluster labels into each modality's obs\nfor mod_name in mdata.mod:\n    mod_adata = mdata[mod_name]\n    shared_cells = mod_adata.obs_names\n    mod_adata.obs[\"leiden_wnn\"] = mdata.obs.loc[shared_cells, \"leiden_wnn\"].values\n    print(f\"{mod_name}: added leiden_wnn, {mod_adata.obs['leiden_wnn'].nunique()} clusters\")\n\n# Now run modality-specific differential analysis per cluster\nsc.tl.rank_genes_groups(mdata[\"rna\"],  groupby=\"leiden_wnn\",\n                        method=\"wilcoxon\", use_raw=False)\nsc.tl.rank_genes_groups(mdata[\"atac\"], groupby=\"leiden_wnn\",\n                        method=\"wilcoxon\", use_raw=False)\nprint(\"Differential features computed for both modalities\")\n```\n\n### Recipe: Convert MuData to Concatenated AnnData for scvi-tools\n\nWhen to use: MultiVI and totalVI in scvi-tools require a concatenated AnnData with modality identity tracked in `var`. This recipe prepares the input for these models.\n\n```python\n# Concatenate RNA and ATAC into a single AnnData with modality column in var\nrna_adata  = mdata[\"rna\"].copy()\natac_adata = mdata[\"atac\"].copy()\n\nrna_adata.var[\"modality\"]  = \"Gene Expression\"\natac_adata.var[\"modality\"] = \"Peaks\"\n\n# Restore raw counts for scvi-tools (requires integer counts)\n# Ensure mdata[\"rna\"].layers[\"counts\"] and mdata[\"atac\"].X are integer\nimport anndata as ad\ncombined = ad.concat([rna_adata, atac_adata], axis=1, merge=\"unique\")\ncombined.obs = mdata.obs.loc[combined.obs_names].copy()\nprint(f\"Combined AnnData: {combined.n_obs} cells × {combined.n_vars} features\")\nprint(combined.var[\"modality\"].value_counts())\n# Use combined with scvi.model.MULTIVI.setup_anndata(combined, ...)\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `KeyError: 'rna'` when building MuData | Modality key not set or loaded from file without expected names | Check `mdata.mod.keys()`. When loading 10x h5 files, use `mu.read_10x_h5()` which auto-names modalities `\"rna\"` and `\"atac\"` |\n| `ValueError: obs_names mismatch` during WNN | Cells filtered differently per modality leaving mismatched obs | Call `mu.pp.intersect_obs(mdata)` after per-modality QC to harmonize cell sets |\n| UMAP\u002FLeiden uses wrong graph | Multiple neighbor graphs exist; function uses default key `\"neighbors\"` | Always pass `neighbors_key=\"wnn\"` explicitly to `mu.tl.umap()` and `sc.tl.leiden()` |\n| `TypeError: unhashable type: 'dict'` from `sc.tl.umap` | `sc.tl.umap()` cannot read muon's per-modality `use_rep` dict in `mdata.uns[\"wnn\"][\"params\"]` | Use `mu.tl.umap(mdata, neighbors_key=\"wnn\")` instead |\n| `TypeError: neighbors() got an unexpected keyword argument 'use_rep'` | `mu.pp.neighbors()` has no `use_rep` parameter | Set `use_rep` per modality via `sc.pp.neighbors(mdata[\"rna\"], use_rep=\"X_pca\")` first, then call `mu.pp.neighbors(mdata, key_added=\"wnn\")` |\n| `ValueError: Did not find .uns[\"neighbors\"] for modality ...` | Per-modality neighbor graphs not computed | Run `sc.pp.neighbors()` on every modality before `mu.pp.neighbors()` — it is required, not optional |\n| LSI component 1 dominates ATAC embedding | First component captures sequencing depth, not biology | Compute correlation of `X_lsi[:, 0]` with `log_total_counts`; if |r| > 0.9, use `X_lsi[:, 1:]` |\n| `mu.atac.pp.tfidf` raises sparse matrix error | Input matrix is dense or wrong dtype | Convert first: `mdata[\"atac\"].X = scipy.sparse.csr_matrix(mdata[\"atac\"].X.astype(float))` |\n| CLR normalization produces NaN for proteins | Zero counts in a cell for all proteins | Filter cells with `sc.pp.filter_cells(mdata[\"protein\"], min_genes=1)` before CLR |\n| `mu.tl.mofa()` fails with missing mofapy2 | mofapy2 not installed | `pip install mofapy2`; ensure `muon` version ≥ 0.1.5 for MOFA integration |\n| Memory error for large ATAC peak matrices | ATAC matrices (50k+ peaks × 10k+ cells) exceed RAM | Use `sc.pp.highly_variable_genes()` to select top 50k peaks first, or load in chunks |\n\n## Related Skills\n\n- **scanpy-scrna-seq** — single-modality RNA analysis; use as the foundation for the RNA preprocessing steps within muon\n- **scvi-tools-single-cell** — deep generative multi-modal integration (MultiVI for RNA+ATAC, totalVI for CITE-seq); use when probabilistic batch correction across samples is needed\n- **mofaplus-multi-omics** — multi-omics factor analysis; `mu.tl.mofa()` calls mofapy2 internally and stores factors in MuData\n- **anndata-data-structure** — AnnData fundamentals; each MuData modality is a standard AnnData object\n- **deeptools-ngs-analysis** — upstream ATAC-seq BAM → bigWig normalization before peak calling\n- **macs3-peak-calling** — produces the peak BED files used to generate the ATAC AnnData count matrix\n\n## References\n\n- [muon documentation](https:\u002F\u002Fmuon.readthedocs.io\u002F) — official docs, tutorials, API reference\n- [muon GitHub (scverse)](https:\u002F\u002Fgithub.com\u002Fscverse\u002Fmuon) — source code, issues, examples\n- [Bredikhin et al. Genome Biology 2022](https:\u002F\u002Fdoi.org\u002F10.1186\u002Fs13059-021-02577-8) — muon\u002FMuData publication\n- [10x Genomics Multiome analysis guide](https:\u002F\u002Fmuon-tutorials.readthedocs.io\u002Fen\u002Flatest\u002Fsingle-cell-rna-atac\u002Fpbmc10k\u002F1-Gene-Expression-Processing.html) — step-by-step Multiome tutorial in muon\n- [WNN method (Hao et al. Cell 2021)](https:\u002F\u002Fdoi.org\u002F10.1016\u002Fj.cell.2021.04.048) — original Weighted Nearest Neighbor paper from Seurat v4\n","# muon — Multi-Modal Single-Cell Analysis\n\n## Overview\n\nmuon is a Python framework for multi-modal single-cell data analysis that extends the AnnData ecosystem. Its core data structure, `MuData`, holds multiple `AnnData` objects (one per modality: RNA, ATAC, protein, etc.) with shared observation and variable axes, enabling coordinated operations across all modalities. muon provides modality-specific preprocessing routines (TF-IDF and LSI for ATAC, CLR normalization for surface proteins), Weighted Nearest Neighbor (WNN) graph construction for joint dimensionality reduction, and cross-modal analysis tools. It integrates directly with scanpy, scvi-tools, and MOFA+ for a complete multi-omics single-cell workflow.\n\n## When to Use\n\n- Analyzing 10x Genomics Multiome data (simultaneous RNA + ATAC from the same nuclei)\n- Processing CITE-seq experiments (RNA + surface protein from the same cells)\n- Building joint UMAP embeddings that integrate signals from two or more modalities via WNN\n- Preprocessing ATAC-seq modalities (TF-IDF normalization, LSI dimensionality reduction)\n- Normalizing surface protein data with centered log-ratio (CLR) normalization\n- Performing cross-modal feature linkage (associating ATAC peaks with nearby gene expression)\n- Applying MOFA+ factor analysis across multiple omics layers within a unified container\n- Use **scanpy-scrna-seq** instead when analyzing a single RNA-seq modality without any co-measured omics\n- Use **scvi-tools (MultiVI \u002F totalVI)** when you need probabilistic deep generative batch correction across modalities\n\n## Prerequisites\n\n- **Python packages**: `muon>=0.1.6`, `scanpy>=1.10`, `anndata>=0.10`, `numpy`, `scipy`, `pandas`, `matplotlib`, `leidenalg`\n- **Data requirements**: 10x Multiome h5 or h5mu files, or per-modality AnnData objects (cells x features) sharing the same `obs_names`\n- **Environment**: Python 3.9+; 16 GB+ RAM for datasets >50k cells; optional `mofapy2` for MOFA factor analysis\n\n```bash\npip install \"muon[atac]\" \"scanpy[leiden]\" anndata\n# Optional: for MOFA+ integration\npip install mofapy2\n```\n\n## Quick Start\n\n```python\nimport muon as mu\nimport scanpy as sc\nimport numpy as np\nimport anndata as ad\nimport pandas as pd\n\n# Simulate a small RNA + ATAC MuData object (200 cells)\nnp.random.seed(42)\nn_cells = 200\nrna  = ad.AnnData(np.abs(np.random.negative_binomial(5, 0.3, (n_cells, 2000))).astype(float),\n                  obs=pd.DataFrame(index=[f\"cell_{i}\" for i in range(n_cells)]),\n                  var=pd.DataFrame(index=[f\"gene_{j}\" for j in range(2000)]))\natac = ad.AnnData(np.abs(np.random.negative_binomial(2, 0.5, (n_cells, 5000))).astype(float),\n                  obs=rna.obs.copy(),\n                  var=pd.DataFrame(index=[f\"peak_{j}\" for j in range(5000)]))\n\nmdata = mu.MuData({\"rna\": rna, \"atac\": atac})\nprint(mdata)\n# MuData object with n_obs × n_vars = 200 × 7000\n#   2 modalities\n#     rna: 200 × 2000\n#     atac: 200 × 5000\n\n# Minimal preprocessing\nsc.pp.normalize_total(mdata[\"rna\"], target_sum=1e4)\nsc.pp.log1p(mdata[\"rna\"])\nsc.pp.highly_variable_genes(mdata[\"rna\"], n_top_genes=500)\nsc.pp.pca(mdata[\"rna\"])\n\nmu.atac.pp.tfidf(mdata[\"atac\"])\nmu.atac.tl.lsi(mdata[\"atac\"])\n\n# WNN joint embedding\n# Per-modality graphs are REQUIRED first: mu.pp.neighbors reads each modality's\n# .uns[\"neighbors\"][\"params\"] to learn which embedding to use.\nsc.pp.neighbors(mdata[\"rna\"],  use_rep=\"X_pca\")\nsc.pp.neighbors(mdata[\"atac\"], use_rep=\"X_lsi\")\nmu.pp.neighbors(mdata, key_added=\"wnn\")\nmu.tl.umap(mdata, neighbors_key=\"wnn\")\nsc.tl.leiden(mdata, neighbors_key=\"wnn\", key_added=\"leiden_wnn\")\nprint(f\"Clusters: {mdata.obs['leiden_wnn'].nunique()}\")\n```\n\n## Core API\n\n### Module 1: MuData Creation and I\u002FO\n\n`MuData` is the central container: a dictionary of `AnnData` modalities plus shared `obs` and `var` slots. The `mdata.obs` DataFrame merges per-modality observation metadata with a modality prefix for ambiguous columns.\n\n```python\nimport muon as mu\nimport anndata as ad\nimport numpy as np\nimport pandas as pd\n\n# --- Build from per-modality AnnData objects ---\nn_cells = 300\nrna  = ad.AnnData(np.abs(np.random.negative_binomial(5, 0.3, (n_cells, 3000))).astype(float),\n                  obs=pd.DataFrame(index=[f\"cell_{i}\" for i in range(n_cells)]),\n                  var=pd.DataFrame(index=[f\"gene_{j}\" for j in range(3000)]))\nprot = ad.AnnData(np.abs(np.random.randn(n_cells, 30)) + 3,\n                  obs=rna.obs.copy(),\n                  var=pd.DataFrame(index=[f\"protein_{j}\" for j in range(30)]))\n\nmdata = mu.MuData({\"rna\": rna, \"protein\": prot})\nprint(mdata)\n# Access individual modalities\nprint(mdata.mod[\"rna\"])        # AnnData: 300 × 3000\nprint(mdata[\"rna\"])            # same shorthand\nprint(mdata.obs.head())        # shared observation metadata\nprint(mdata.obs_names[:5])     # cell barcodes\n\n# Save and load\nmdata.write(\"multiome_data.h5mu\")\nmdata2 = mu.read(\"multiome_data.h5mu\")\nprint(f\"Loaded: {mdata2.n_obs} cells, {mdata2.n_mod} modalities\")\n```\n\n```python\n# --- Load from 10x Multiome h5 file ---\n# mdata = mu.read_10x_h5(\"filtered_feature_bc_matrix.h5\")\n# Produces MuData with mdata[\"rna\"] and mdata[\"atac\"] modalities\n\n# --- Subsetting by cells or features ---\n# Select high-quality cells (e.g., after QC)\nmask = np.ones(mdata.n_obs, dtype=bool)  # replace with actual QC mask\nmdata_filtered = mdata[mask].copy()\nprint(f\"After filtering: {mdata_filtered.n_obs} cells\")\n\n# Propagate obs mask to each modality\nmu.pp.intersect_obs(mdata)   # ensures obs consistency across modalities\n```\n\n### Module 2: RNA Modality Preprocessing\n\nStandard scRNA-seq preprocessing applied to `mdata[\"rna\"]` using scanpy functions. The RNA modality is preprocessed identically to a standalone scanpy workflow but operates on the slice of the MuData container.\n\n```python\nimport scanpy as sc\nimport numpy as np\n\n# Assume mdata[\"rna\"] has raw integer counts\nrna = mdata[\"rna\"]\n\n# QC metrics\nsc.pp.calculate_qc_metrics(rna, percent_top=None, log1p=False, inplace=True)\nrna.obs[\"pct_counts_mt\"] = rna[:, rna.var_names.str.startswith(\"MT-\")].X.sum(axis=1).A1 \u002F rna.obs[\"total_counts\"] * 100\n\n# Filter cells and genes\nmin_genes, max_genes, max_mt = 200, 5000, 20\nsc.pp.filter_cells(rna, min_genes=min_genes)\nsc.pp.filter_genes(rna, min_cells=5)\nrna = rna[(rna.obs[\"n_genes_by_counts\"] \u003C max_genes) &\n          (rna.obs[\"pct_counts_mt\"] \u003C max_mt)].copy()\nprint(f\"RNA after QC: {rna.n_obs} cells × {rna.n_vars} genes\")\n\n# Normalize and log-transform\nsc.pp.normalize_total(rna, target_sum=1e4)\nsc.pp.log1p(rna)\n\n# Highly variable genes\nsc.pp.highly_variable_genes(rna, n_top_genes=3000, flavor=\"seurat_v3\",\n                             batch_key=None)\nprint(f\"HVGs: {rna.var['highly_variable'].sum()}\")\n\n# PCA on HVGs\nsc.pp.pca(rna, n_comps=50, use_highly_variable=True)\nprint(f\"PCA embedding shape: {rna.obsm['X_pca'].shape}\")\n# Update slice in MuData\nmdata.mod[\"rna\"] = rna\n```\n\n### Module 3: ATAC Modality Preprocessing\n\nATAC-seq modalities require a different normalization strategy. TF-IDF (term frequency–inverse document frequency) normalizes peak accessibility across cells and peaks; LSI (latent semantic indexing, equivalent to truncated SVD after TF-IDF) produces a low-dimensional embedding. The first LSI component typically captures sequencing depth rather than biology and is excluded.\n\n```python\n# Assume mdata[\"atac\"] contains raw binary or integer peak accessibility counts\natac = mdata[\"atac\"]\n\n# Basic QC: filter low-coverage cells and low-frequency peaks\nsc.pp.calculate_qc_metrics(atac, percent_top=None, log1p=False, inplace=True)\nsc.pp.filter_cells(atac, min_genes=200)     # min peaks detected\nsc.pp.filter_genes(atac, min_cells=10)      # min cells a peak appears in\nprint(f\"ATAC after QC: {atac.n_obs} cells × {atac.n_vars} peaks\")\n\n# TF-IDF normalization (log(TF) * log(IDF) scaling)\nmu.atac.pp.tfidf(atac, scale_factor=1e4)\nprint(\"TF-IDF normalization complete\")\nprint(f\"ATAC data range: [{atac.X.min():.2f}, {atac.X.max():.2f}]\")\n\n# LSI dimensionality reduction (truncated SVD on TF-IDF matrix)\nmu.atac.tl.lsi(atac, n_comps=50)\n# LSI component 1 correlates with sequencing depth — exclude it yourself.\n# mu.atac.tl.lsi stores ALL n_comps components in X_lsi; component 1 is NOT\n# dropped. See Best Practices #2 before feeding X_lsi into WNN.\nprint(f\"LSI embedding shape: {atac.obsm['X_lsi'].shape}\")\n\n# Update modality in MuData\nmdata.mod[\"atac\"] = atac\n```\n\n### Module 4: WNN Graph and Joint Embedding\n\nWeighted Nearest Neighbor (WNN) integrates multiple modality embeddings by learning per-cell, per-modality weights. Cells with high-quality RNA signal receive higher RNA weight; cells with cleaner ATAC signal receive higher ATAC weight. The resulting WNN graph is used for UMAP layout and Leiden clustering.\n\n```python\n# Compute per-modality neighbor graphs first — REQUIRED, not optional.\n# mu.pp.neighbors reads use_rep \u002F n_pcs \u002F n_neighbors out of each modality's\n# .uns[\"neighbors\"][\"params\"]; without this it raises\n# ValueError: Did not find .uns[\"neighbors\"] for modality \"rna\".\nsc.pp.neighbors(mdata[\"rna\"],  use_rep=\"X_pca\", n_neighbors=30)\nsc.pp.neighbors(mdata[\"atac\"], use_rep=\"X_lsi\", n_neighbors=30)\n\n# WNN joint neighbor graph across modalities\nmu.pp.neighbors(\n    mdata,\n    key_added=\"wnn\",\n    n_neighbors=30,\n    random_state=42,\n)\nprint(\"WNN graph built. Keys:\", list(mdata.obsp.keys()))\n# Expected: ['wnn_connectivities', 'wnn_distances']\n\n# UMAP from WNN graph — use mu.tl.umap, not sc.tl.umap (see Best Practices #3)\nmu.tl.umap(mdata, neighbors_key=\"wnn\", random_state=42)\nprint(f\"UMAP embedding shape: {mdata.obsm['X_umap'].shape}\")\n\n# Leiden clustering from WNN graph\nsc.tl.leiden(mdata, neighbors_key=\"wnn\", resolution=0.5, key_added=\"leiden_wnn\")\nn_clusters = mdata.obs[\"leiden_wnn\"].nunique()\nprint(f\"Leiden WNN clustering: {n_clusters} clusters at resolution 0.5\")\n```\n\n### Module 5: Visualization\n\nmuon extends scanpy's plotting interface with modality-aware functions. `mu.pl.embedding()` and `mu.pl.umap()` color joint UMAP embeddings by features from any modality, including modality-prefixed feature names (e.g. `\"rna:CD3E\"`). Plain `sc.pl.umap()` cannot resolve those prefixed names and cannot index a `MuData` object — always use the `mu.pl.*` equivalents on `mdata`.\n\n```python\nimport matplotlib.pyplot as plt\n\n# Joint UMAP colored by cluster assignment\nmu.pl.umap(mdata, color=\"leiden_wnn\", title=\"WNN Leiden clusters\",\n           legend_loc=\"on data\", show=False)\nplt.savefig(\"wnn_umap_clusters.png\", dpi=150, bbox_inches=\"tight\")\nplt.close()\nprint(\"Saved wnn_umap_clusters.png\")\n\n# Color by RNA gene expression on joint UMAP\nmu.pl.umap(mdata, color=[\"rna:CD3E\", \"rna:CD19\", \"rna:CD14\"],\n           use_raw=False, vmax=\"p99\", show=False, ncols=3)\nplt.savefig(\"wnn_umap_markers.png\", dpi=150, bbox_inches=\"tight\")\nplt.close()\nprint(\"Saved wnn_umap_markers.png\")\n```\n\n```python\n# Per-modality scatter \u002F embedding plots\nmu.pl.embedding(mdata, basis=\"X_umap\", color=\"leiden_wnn\",\n                show=False)\nplt.savefig(\"embedding_clusters.png\", dpi=150, bbox_inches=\"tight\")\nplt.close()\n\n# Violin plot: RNA QC metrics per cluster\nsc.pl.violin(mdata[\"rna\"], keys=[\"n_genes_by_counts\", \"total_counts\"],\n             groupby=mdata.obs.loc[mdata[\"rna\"].obs_names, \"leiden_wnn\"],\n             rotation=90, show=False)\nplt.savefig(\"rna_qc_by_cluster.png\", dpi=150, bbox_inches=\"tight\")\nplt.close()\nprint(\"Saved rna_qc_by_cluster.png\")\n```\n\n### Module 6: Cross-Modal Analysis\n\nCross-modal analysis links features across modalities — for example, associating ATAC peak accessibility near a gene's promoter with its RNA expression, or applying MOFA+ to find shared latent factors.\n\n```python\n# --- Peak-to-gene distance annotation ---\n# Annotate ATAC peaks with nearest gene (requires genomic coordinates in var)\n# mdata[\"atac\"].var should contain columns: chrom, chromStart, chromEnd\n# mu.atac.tl.rank_peaks_groups(mdata, groupby=\"leiden_wnn\")  # differential peaks\n\n# --- Differentially accessible peaks per cluster ---\natac = mdata[\"atac\"]\n# Transfer cluster labels from MuData obs to ATAC obs\natac.obs[\"cluster\"] = mdata.obs.loc[atac.obs_names, \"leiden_wnn\"].values\nsc.tl.rank_genes_groups(atac, groupby=\"cluster\", method=\"wilcoxon\",\n                        use_raw=False)\ntop_peaks = sc.get.rank_genes_groups_df(atac, group=\"0\").head(5)\nprint(\"Top differential peaks in cluster 0:\")\nprint(top_peaks[[\"names\", \"logfoldchanges\", \"pvals_adj\"]])\n```\n\n```python\n# --- MOFA+ factor analysis on MuData ---\n# Requires: pip install mofapy2\ntry:\n    mu.tl.mofa(mdata, n_factors=10, seed=42,\n               use_obs=\"all\", outfile=\"mofa_model.hdf5\")\n    # Factor scores stored in mdata.obsm[\"X_mofa\"]\n    print(f\"MOFA factors: {mdata.obsm['X_mofa'].shape}\")\n    # Variance explained per factor per modality\n    # Inspect with mdata.uns[\"mofa\"]\nexcept ImportError:\n    print(\"Install mofapy2 to enable MOFA factor analysis\")\n```\n\n## Common Workflows\n\n### Workflow 1: Full 10x Multiome (RNA + ATAC) Joint WNN Clustering\n\n**Goal**: Process paired RNA and ATAC data from 10x Genomics Multiome, build a WNN joint embedding, cluster cells, and identify RNA marker genes per cluster.\n\n```python\nimport muon as mu\nimport scanpy as sc\nimport numpy as np\nimport anndata as ad\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# --- 1. Simulate 10x Multiome-like data (replace with mu.read_10x_h5()) ---\nnp.random.seed(0)\nn_cells = 400\ncell_ids = [f\"AAACGAATC{i:05d}-1\" for i in range(n_cells)]\n# Simulate two cell types with distinct expression\u002Faccessibility\nlabels = np.array([\"typeA\"] * 200 + [\"typeB\"] * 200)\n\nrna_counts = np.abs(np.random.negative_binomial(6, 0.35, (n_cells, 2000))).astype(float)\nrna_counts[:200, :100] += 10   # typeA marker genes\nrna_counts[200:, 100:200] += 10  # typeB marker genes\n\natac_counts = np.abs(np.random.binomial(1, 0.05, (n_cells, 50000))).astype(float)\natac_counts[:200, :5000] += 1   # typeA accessible peaks\natac_counts[200:, 5000:10000] += 1  # typeB accessible peaks\n\nrna  = ad.AnnData(rna_counts,\n                  obs=pd.DataFrame({\"cell_type\": labels}, index=cell_ids),\n                  var=pd.DataFrame(index=[f\"gene_{j}\" for j in range(2000)]))\natac = ad.AnnData(atac_counts,\n                  obs=pd.DataFrame({\"cell_type\": labels}, index=cell_ids),\n                  var=pd.DataFrame(index=[f\"peak_{j}\" for j in range(50000)]))\n\nmdata = mu.MuData({\"rna\": rna, \"atac\": atac})\nprint(f\"Loaded: {mdata}\")\n\n# --- 2. RNA preprocessing ---\nsc.pp.filter_cells(mdata[\"rna\"], min_genes=50)\nsc.pp.filter_genes(mdata[\"rna\"], min_cells=5)\nsc.pp.normalize_total(mdata[\"rna\"], target_sum=1e4)\nsc.pp.log1p(mdata[\"rna\"])\nsc.pp.highly_variable_genes(mdata[\"rna\"], n_top_genes=500)\nsc.pp.pca(mdata[\"rna\"], n_comps=30, use_highly_variable=True)\nprint(f\"RNA PCA: {mdata['rna'].obsm['X_pca'].shape}\")\n\n# --- 3. ATAC preprocessing: TF-IDF + LSI ---\nsc.pp.filter_cells(mdata[\"atac\"], min_genes=100)\nsc.pp.filter_genes(mdata[\"atac\"], min_cells=5)\nmu.atac.pp.tfidf(mdata[\"atac\"])\nmu.atac.tl.lsi(mdata[\"atac\"], n_comps=30)\nprint(f\"ATAC LSI: {mdata['atac'].obsm['X_lsi'].shape}\")\n\n# --- 4. Per-modality neighbors (REQUIRED before WNN) ---\nsc.pp.neighbors(mdata[\"rna\"],  use_rep=\"X_pca\", n_neighbors=15)\nsc.pp.neighbors(mdata[\"atac\"], use_rep=\"X_lsi\", n_neighbors=15)\n\n# --- 5. WNN joint neighbor graph ---\nmu.pp.intersect_obs(mdata)   # align obs after per-modality filtering\nmu.pp.neighbors(mdata, key_added=\"wnn\",\n                n_neighbors=15, random_state=42)\n\n# --- 6. UMAP + Leiden clustering ---\nmu.tl.umap(mdata, neighbors_key=\"wnn\", random_state=42)\nsc.tl.leiden(mdata, neighbors_key=\"wnn\", resolution=0.5, key_added=\"leiden_wnn\")\nprint(f\"Clusters: {mdata.obs['leiden_wnn'].value_counts().to_dict()}\")\n\n# --- 7. Marker genes per cluster ---\nsc.tl.rank_genes_groups(mdata[\"rna\"],\n                        groupby=mdata.obs.loc[mdata[\"rna\"].obs_names, \"leiden_wnn\"],\n                        method=\"wilcoxon\", use_raw=False)\ntop_markers = sc.get.rank_genes_groups_df(mdata[\"rna\"], group=\"0\").head(5)\nprint(\"Top RNA markers for cluster 0:\")\nprint(top_markers[[\"names\", \"logfoldchanges\", \"pvals_adj\"]])\n\n# --- 8. Visualization ---\nfig, axes = plt.subplots(1, 2, figsize=(12, 5))\nmu.pl.umap(mdata, color=\"leiden_wnn\", ax=axes[0], show=False, title=\"WNN clusters\")\nmu.pl.umap(mdata, color=\"rna:gene_0\",  ax=axes[1], show=False, title=\"gene_0 expression\",\n           use_raw=False, vmax=\"p99\")\nplt.tight_layout()\nplt.savefig(\"multiome_wnn_pipeline.png\", dpi=150, bbox_inches=\"tight\")\nplt.close()\nprint(\"Saved multiome_wnn_pipeline.png\")\n```\n\n### Workflow 2: CITE-seq (RNA + Surface Protein) Analysis\n\n**Goal**: Process CITE-seq data with paired RNA and antibody-derived tag (ADT\u002Fprotein) counts. Normalize proteins with CLR, annotate cell types from protein markers, and build a joint UMAP.\n\n```python\nimport muon as mu\nimport scanpy as sc\nimport numpy as np\nimport anndata as ad\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy.sparse import csr_matrix\n\nnp.random.seed(1)\nn_cells = 350\ncell_ids = [f\"CITESEQ_{i:04d}\" for i in range(n_cells)]\n\n# Simulate RNA + protein modalities\n# Three cell types: T-cells (CD3+CD4+), B-cells (CD19+CD20+), Monocytes (CD14+CD16+)\nn_t, n_b, n_mono = 120, 130, 100\nlabels = [\"Tcell\"] * n_t + [\"Bcell\"] * n_b + [\"Monocyte\"] * n_mono\n\nrna_mat = np.abs(np.random.negative_binomial(4, 0.4, (n_cells, 1500))).astype(float)\nrna_mat[:n_t, :50] += 15       # T-cell RNA markers\nrna_mat[n_t:n_t+n_b, 50:100] += 15   # B-cell RNA markers\nrna_mat[n_t+n_b:, 100:150] += 15     # Monocyte RNA markers\n\n# 20 surface proteins: first 5 T-cell, next 5 B-cell, next 5 Monocyte, rest baseline\nprot_mat = np.abs(np.random.normal(2, 0.5, (n_cells, 20)))\nprot_mat[:n_t, :5] += 8          # CD3, CD4, CD5, CD7, CD8 for T-cells\nprot_mat[n_t:n_t+n_b, 5:10] += 8  # CD19, CD20, CD22, CD24, CD79 for B-cells\nprot_mat[n_t+n_b:, 10:15] += 8    # CD14, CD16, CD64, CD11b, HLA-DR for Monocytes\n\nprotein_names = [\"CD3\", \"CD4\", \"CD5\", \"CD7\", \"CD8\",\n                 \"CD19\", \"CD20\", \"CD22\", \"CD24\", \"CD79a\",\n                 \"CD14\", \"CD16\", \"CD64\", \"CD11b\", \"HLA-DR\",\n                 \"CD25\", \"CD56\", \"CD45RA\", \"CD45RO\", \"IgG-ctrl\"]\n\nrna = ad.AnnData(csr_matrix(rna_mat),\n                 obs=pd.DataFrame({\"cell_type\": labels}, index=cell_ids),\n                 var=pd.DataFrame(index=[f\"gene_{j}\" for j in range(1500)]))\nprot = ad.AnnData(prot_mat,\n                  obs=pd.DataFrame({\"cell_type\": labels}, index=cell_ids),\n                  var=pd.DataFrame(index=protein_names))\n\nmdata = mu.MuData({\"rna\": rna, \"protein\": prot})\nprint(mdata)\n\n# --- RNA preprocessing ---\nsc.pp.normalize_total(mdata[\"rna\"], target_sum=1e4)\nsc.pp.log1p(mdata[\"rna\"])\nsc.pp.highly_variable_genes(mdata[\"rna\"], n_top_genes=500)\nsc.pp.pca(mdata[\"rna\"], n_comps=30, use_highly_variable=True)\n\n# --- Protein CLR normalization (Centered Log-Ratio) ---\n# CLR normalizes each protein across cells: log(x \u002F geometric_mean(x))\nmu.prot.pp.clr(mdata[\"protein\"])\nprint(\"Protein CLR normalization applied\")\nprint(f\"Protein data range: [{mdata['protein'].X.min():.2f}, {mdata['protein'].X.max():.2f}]\")\n\n# PCA on protein modality\nsc.pp.pca(mdata[\"protein\"], n_comps=min(15, prot.n_vars - 1))\n\n# --- WNN joint embedding ---\n# Per-modality graphs first (REQUIRED — mu.pp.neighbors reads their .uns params)\nsc.pp.neighbors(mdata[\"rna\"],     use_rep=\"X_pca\", n_neighbors=20)\nsc.pp.neighbors(mdata[\"protein\"], use_rep=\"X_pca\", n_neighbors=20)\nmu.pp.neighbors(mdata, key_added=\"wnn\", n_neighbors=20, random_state=0)\nmu.tl.umap(mdata, neighbors_key=\"wnn\", random_state=0)\nsc.tl.leiden(mdata, neighbors_key=\"wnn\", resolution=0.4, key_added=\"leiden_wnn\")\n\n# --- Protein-based cell type annotation ---\n# Compute mean CLR protein per cluster\nprot_df = pd.DataFrame(\n    mdata[\"protein\"].X,\n    index=mdata[\"protein\"].obs_names,\n    columns=protein_names\n)\nprot_df[\"cluster\"] = mdata.obs.loc[mdata[\"protein\"].obs_names, \"leiden_wnn\"].values\ncluster_means = prot_df.groupby(\"cluster\").mean()\nprint(\"\\nMean CLR protein per cluster:\")\nprint(cluster_means[[\"CD3\", \"CD4\", \"CD19\", \"CD14\"]].round(2))\n\n# --- Visualization ---\nfig, axes = plt.subplots(1, 3, figsize=(15, 4))\nmu.pl.umap(mdata, color=\"leiden_wnn\",   ax=axes[0], show=False, title=\"WNN Leiden\")\nmu.pl.umap(mdata, color=\"protein:CD3\",  ax=axes[1], show=False, title=\"CD3 (CLR)\",\n           use_raw=False, vmax=\"p99\")\nmu.pl.umap(mdata, color=\"protein:CD19\", ax=axes[2], show=False, title=\"CD19 (CLR)\",\n           use_raw=False, vmax=\"p99\")\nplt.tight_layout()\nplt.savefig(\"citeseq_joint_umap.png\", dpi=150, bbox_inches=\"tight\")\nplt.close()\nprint(\"Saved citeseq_joint_umap.png\")\n\n# --- Dot plot: protein markers per cluster ---\nsc.pl.dotplot(mdata[\"protein\"],\n              var_names=[\"CD3\", \"CD4\", \"CD19\", \"CD20\", \"CD14\", \"CD16\"],\n              groupby=mdata.obs.loc[mdata[\"protein\"].obs_names, \"leiden_wnn\"],\n              show=False)\nplt.savefig(\"citeseq_protein_dotplot.png\", dpi=150, bbox_inches=\"tight\")\nplt.close()\nprint(\"Saved citeseq_protein_dotplot.png\")\n```\n\n## Key Parameters\n\n| Parameter | Module \u002F Function | Default | Range \u002F Options | Effect |\n|-----------|-------------------|---------|-----------------|--------|\n| `n_neighbors` | `mu.pp.neighbors()` | `30` | `10`–`100` | Neighborhood size for graph; lower = finer local structure |\n| `use_rep` | `sc.pp.neighbors()` on each modality | `None` (auto) | embedding key, e.g. `\"X_pca\"` \u002F `\"X_lsi\"` | Set per modality *before* WNN; `mu.pp.neighbors()` has no `use_rep` parameter and reads it from each modality's `.uns[\"neighbors\"][\"params\"]` |\n| `key_added` | `mu.pp.neighbors()` | `\"neighbors\"` | any string | Key under which graph is stored; use `\"wnn\"` for joint graphs |\n| `n_comps` | `sc.pp.pca()`, `mu.atac.tl.lsi()` | `50` | `10`–`100` | Number of reduced dimensions; 30–50 typical |\n| `resolution` | `sc.tl.leiden()` | `1.0` | `0.1`–`2.0` | Clustering granularity; lower = fewer, larger clusters |\n| `scale_factor` | `mu.atac.pp.tfidf()` | `1e4` | `1e3`–`1e5` | TF scaling constant before log transform |\n| `n_factors` | `mu.tl.mofa()` | `10` | `5`–`50` | Number of MOFA latent factors; use elbow on variance explained |\n| `target_sum` | `sc.pp.normalize_total()` | `1e4` | `1e3`–`1e6` | Library size normalization target per cell (RNA) |\n| `n_top_genes` | `sc.pp.highly_variable_genes()` | varies | `1000`–`5000` | Number of highly variable genes to retain for PCA |\n\n## Best Practices\n\n1. **Align obs before WNN**: After per-modality QC filtering, cell counts across modalities may differ. Always call `mu.pp.intersect_obs(mdata)` before WNN to ensure every modality has the same cell set.\n   ```python\n   mu.pp.intersect_obs(mdata)\n   print(f\"Shared cells after intersect: {mdata.n_obs}\")\n   ```\n\n2. **Drop LSI component 1 from ATAC**: The first LSI component captures sequencing depth (total counts per cell) rather than biological signal. `mu.atac.tl.lsi()` stores all components in `X_lsi`, so verify that component 1 correlates with `log_total_counts` before using `X_lsi` in WNN; if so, restrict to `X_lsi[:, 1:]`.\n   ```python\n   import numpy as np, pandas as pd\n   atac = mdata[\"atac\"]\n   corr = np.corrcoef(atac.obsm[\"X_lsi\"][:, 0],\n                      np.log1p(atac.obs[\"total_counts\"]))[0, 1]\n   print(f\"LSI1 vs log_counts correlation: {corr:.3f}\")\n   # If |corr| > 0.9, exclude component 1:\n   # atac.obsm[\"X_lsi\"] = atac.obsm[\"X_lsi\"][:, 1:]\n   ```\n\n3. **Use `key_added=\"wnn\"` consistently, and `mu.tl.umap()` for the joint graph**: Always name the joint graph `\"wnn\"` and pass `neighbors_key=\"wnn\"` downstream. Use `mu.tl.umap()` — not `sc.tl.umap()` — on a `MuData`: muon stores a per-modality `use_rep` dict in `mdata.uns[\"wnn\"][\"params\"]`, which scanpy cannot read (`TypeError: unhashable type: 'dict'`). `sc.tl.leiden(mdata, neighbors_key=\"wnn\")` does work. Mixing `neighbors_key` values silently uses the wrong graph.\n\n4. **CLR normalization for proteins, not log-normalization**: Antibody-derived tag (ADT) counts from CITE-seq have a different noise model than RNA. Use `mu.prot.pp.clr()` for per-protein CLR normalization. Do NOT apply `sc.pp.normalize_total()` + `sc.pp.log1p()` to the protein modality.\n\n5. **Store raw RNA counts before normalization**: Before any normalization, store the raw RNA counts in `mdata[\"rna\"].layers[\"counts\"]` and set `mdata[\"rna\"].raw = mdata[\"rna\"]`. This is required for downstream differential expression tests and scvi-tools integration.\n   ```python\n   import scipy.sparse as sp\n   mdata[\"rna\"].layers[\"counts\"] = mdata[\"rna\"].X.copy()\n   # Store pre-normalization snapshot\n   mdata[\"rna\"].raw = mdata[\"rna\"]\n   ```\n\n6. **Match WNN embedding dimensions**: The RNA PCA and ATAC LSI embeddings passed to WNN should have comparable dimensionality (e.g., both 30 or 50 components). Mismatched dimensions do not cause errors but can down-weight the smaller modality.\n\n## Common Recipes\n\n### Recipe: Compute Per-Cluster Modality Weights from WNN\n\nWhen to use: Inspect which cells rely more on RNA vs ATAC signal in the WNN graph. High RNA weight in a cluster suggests cleaner RNA data; high ATAC weight suggests stronger chromatin accessibility signal.\n\n```python\n# WNN stores per-cell modality weights in mdata.obsm after mu.pp.neighbors()\n# Key name: \"{key_added}_weights\" — check available keys\nprint([k for k in mdata.obsm.keys() if \"wnn\" in k.lower()])\n\n# If weights are stored (depends on muon version):\nif \"wnn_weights\" in mdata.obsm:\n    weights_df = pd.DataFrame(\n        mdata.obsm[\"wnn_weights\"],\n        index=mdata.obs_names,\n        columns=[\"rna_weight\", \"atac_weight\"]\n    )\n    weights_df[\"cluster\"] = mdata.obs[\"leiden_wnn\"].values\n    print(weights_df.groupby(\"cluster\").mean().round(3))\nelse:\n    # Proxy: compare RNA vs ATAC PCA explained variance per cell\n    rna_var  = np.var(mdata[\"rna\"].obsm[\"X_pca\"],  axis=1)\n    atac_var = np.var(mdata[\"atac\"].obsm[\"X_lsi\"], axis=1)\n    mdata.obs[\"rna_signal_proxy\"]  = rna_var \u002F (rna_var + atac_var)\n    mdata.obs[\"atac_signal_proxy\"] = atac_var \u002F (rna_var + atac_var)\n    print(mdata.obs[[\"rna_signal_proxy\", \"atac_signal_proxy\", \"leiden_wnn\"]].groupby(\"leiden_wnn\").mean().round(3))\n```\n\n### Recipe: Export Cluster Labels Back to Per-Modality AnnData\n\nWhen to use: After joint WNN clustering, copy shared cluster labels back into each modality's `.obs` for modality-specific downstream analyses (e.g., differential peaks within clusters).\n\n```python\n# Copy joint cluster labels into each modality's obs\nfor mod_name in mdata.mod:\n    mod_adata = mdata[mod_name]\n    shared_cells = mod_adata.obs_names\n    mod_adata.obs[\"leiden_wnn\"] = mdata.obs.loc[shared_cells, \"leiden_wnn\"].values\n    print(f\"{mod_name}: added leiden_wnn, {mod_adata.obs['leiden_wnn'].nunique()} clusters\")\n\n# Now run modality-specific differential analysis per cluster\nsc.tl.rank_genes_groups(mdata[\"rna\"],  groupby=\"leiden_wnn\",\n                        method=\"wilcoxon\", use_raw=False)\nsc.tl.rank_genes_groups(mdata[\"atac\"], groupby=\"leiden_wnn\",\n                        method=\"wilcoxon\", use_raw=False)\nprint(\"Differential features computed for both modalities\")\n```\n\n### Recipe: Convert MuData to Concatenated AnnData for scvi-tools\n\nWhen to use: MultiVI and totalVI in scvi-tools require a concatenated AnnData with modality identity tracked in `var`. This recipe prepares the input for these models.\n\n```python\n# Concatenate RNA and ATAC into a single AnnData with modality column in var\nrna_adata  = mdata[\"rna\"].copy()\natac_adata = mdata[\"atac\"].copy()\n\nrna_adata.var[\"modality\"]  = \"Gene Expression\"\natac_adata.var[\"modality\"] = \"Peaks\"\n\n# Restore raw counts for scvi-tools (requires integer counts)\n# Ensure mdata[\"rna\"].layers[\"counts\"] and mdata[\"atac\"].X are integer\nimport anndata as ad\ncombined = ad.concat([rna_adata, atac_adata], axis=1, merge=\"unique\")\ncombined.obs = mdata.obs.loc[combined.obs_names].copy()\nprint(f\"Combined AnnData: {combined.n_obs} cells × {combined.n_vars} features\")\nprint(combined.var[\"modality\"].value_counts())\n# Use combined with scvi.model.MULTIVI.setup_anndata(combined, ...)\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `KeyError: 'rna'` when building MuData | Modality key not set or loaded from file without expected names | Check `mdata.mod.keys()`. When loading 10x h5 files, use `mu.read_10x_h5()` which auto-names modalities `\"rna\"` and `\"atac\"` |\n| `ValueError: obs_names mismatch` during WNN | Cells filtered differently per modality leaving mismatched obs | Call `mu.pp.intersect_obs(mdata)` after per-modality QC to harmonize cell sets |\n| UMAP\u002FLeiden uses wrong graph | Multiple neighbor graphs exist; function uses default key `\"neighbors\"` | Always pass `neighbors_key=\"wnn\"` explicitly to `mu.tl.umap()` and `sc.tl.leiden()` |\n| `TypeError: unhashable type: 'dict'` from `sc.tl.umap` | `sc.tl.umap()` cannot read muon's per-modality `use_rep` dict in `mdata.uns[\"wnn\"][\"params\"]` | Use `mu.tl.umap(mdata, neighbors_key=\"wnn\")` instead |\n| `TypeError: neighbors() got an unexpected keyword argument 'use_rep'` | `mu.pp.neighbors()` has no `use_rep` parameter | Set `use_rep` per modality via `sc.pp.neighbors(mdata[\"rna\"], use_rep=\"X_pca\")` first, then call `mu.pp.neighbors(mdata, key_added=\"wnn\")` |\n| `ValueError: Did not find .uns[\"neighbors\"] for modality ...` | Per-modality neighbor graphs not computed | Run `sc.pp.neighbors()` on every modality before `mu.pp.neighbors()` — it is required, not optional |\n| LSI component 1 dominates ATAC embedding | First component captures sequencing depth, not biology | Compute correlation of `X_lsi[:, 0]` with `log_total_counts`; if |r| > 0.9, use `X_lsi[:, 1:]` |\n| `mu.atac.pp.tfidf` raises sparse matrix error | Input matrix is dense or wrong dtype | Convert first: `mdata[\"atac\"].X = scipy.sparse.csr_matrix(mdata[\"atac\"].X.astype(float))` |\n| CLR normalization produces NaN for proteins | Zero counts in a cell for all proteins | Filter cells with `sc.pp.filter_cells(mdata[\"protein\"], min_genes=1)` before CLR |\n| `mu.tl.mofa()` fails with missing mofapy2 | mofapy2 not installed | `pip install mofapy2`; ensure `muon` version ≥ 0.1.5 for MOFA integration |\n| Memory error for large ATAC peak matrices | ATAC matrices (50k+ peaks × 10k+ cells) exceed RAM | Use `sc.pp.highly_variable_genes()` to select top 50k peaks first, or load in chunks |\n\n## Related Skills\n\n- **scanpy-scrna-seq** — single-modality RNA analysis; use as the foundation for the RNA preprocessing steps within muon\n- **scvi-tools-single-cell** — deep generative multi-modal integration (MultiVI for RNA+ATAC, totalVI for CITE-seq); use when probabilistic batch correction across samples is needed\n- **mofaplus-multi-omics** — multi-omics factor analysis; `mu.tl.mofa()` calls mofapy2 internally and stores factors in MuData\n- **anndata-data-structure** — AnnData fundamentals; each MuData modality is a standard AnnData object\n- **deeptools-ngs-analysis** — upstream ATAC-seq BAM → bigWig normalization before peak calling\n- **macs3-peak-calling** — produces the peak BED files used to generate the ATAC AnnData count matrix\n\n## References\n\n- [muon documentation](https:\u002F\u002Fmuon.readthedocs.io\u002F) — official docs, tutorials, API reference\n- [muon GitHub (scverse)](https:\u002F\u002Fgithub.com\u002Fscverse\u002Fmuon) — source code, issues, examples\n- [Bredikhin et al. Genome Biology 2022](https:\u002F\u002Fdoi.org\u002F10.1186\u002Fs13059-021-02577-8) — muon\u002FMuData publication\n- [10x Genomics Multiome analysis guide](https:\u002F\u002Fmuon-tutorials.readthedocs.io\u002Fen\u002Flatest\u002Fsingle-cell-rna-atac\u002Fpbmc10k\u002F1-Gene-Expression-Processing.html) — step-by-step Multiome tutorial in muon\n- [WNN method (Hao et al. Cell 2021)](https:\u002F\u002Fdoi.org\u002F10.1016\u002Fj.cell.2021.04.048) — original Weighted Nearest Neighbor paper from Seurat v4\n",{"name":5,"license":15,"description":7},"master","49e49abf2f670d429e0b7e2c0349739c3fdd5cbe","skills\u002Fmuon-multiomics-singlecell",5,"https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium","https:\u002F\u002Fgithub.com\u002Fstanfish06","https:\u002F\u002Fwww.stanfish.dev\u002F","2026-11-14 21:31:37",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add stanfish06\u002Fskillquarium --skill muon-multiomics-singlecell",{"tool":38,"command":39},"bunx","bunx skills add stanfish06\u002Fskillquarium --skill muon-multiomics-singlecell",{"tool":41,"command":42},"pnpm","pnpm dlx skills add stanfish06\u002Fskillquarium --skill muon-multiomics-singlecell","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fmuon-multiomics-singlecell\u002FSKILL.md",true,[],[47,55,64,71,78,85],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":51,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M76ZJTRVA456GD7K8Y3EP82H","zarr-python","Stores and queries chunked N-D scientific arrays with Zarr-Python 3, including codecs, sharding, S3\u002FGCS storage, and NumPy\u002FDask\u002FXarray integration. Use for array layout, bounded I\u002FO, format migration, or scientific metadata preservation.","MIT","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fzarr-python\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":59,"licenseFileUrl":60,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":19},"01M76ZJQZ15Q1HKC5V85NHE325","yeet","Publish local changes to GitHub by confirming scope, committing intentionally, pushing the branch, and opening a draft PR through the GitHub app from this plugin, with `gh` used only as a fallback where connector coverage is insufficient.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fyeet\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fyeet\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":59,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M76ZJ8ASZ4QYQ70Y6SBA4Z4S","xarray","N-dimensional labeled arrays and datasets in Python. Built on top of NumPy and Dask. It introduces labels in the form of dimensions, coordinates, and attributes on top of raw NumPy-like arrays, making data analysis in physical sciences more intuitive and less error-prone. Use for working with multi-dimensional scientific data, NetCDF\u002FGRIB\u002FZarr files, climate\u002Fweather\u002Foceanographic datasets, remote sensing, geospatial imaging, large out-of-memory datasets with Dask, and labeled array operations.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fxarray\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":51,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M76ZHFBXD6VXPQ02VCEG202B","writing-mstest-tests","Use when asked to fix, rewrite, update, improve, modernize, show corrected code for, or explain existing MSTest tests or MSTest-specific configuration. Use for \"review\" when corrected code or edits are wanted, even for one pasted assertion or passing tests with bad failure output. Covers expected\u002Factual labels; generic Boolean, collection, string, numeric, null, identity, exception, hard-cast, and object[] checks; TestContext\u002Flifecycle; timeout\u002Fcancellation; OS\u002FCI conditions, retry, cleanup, parallelization, MSTest.Sdk project setup, and MSTESTxxxx. Honor the installed MSTest version. DO NOT USE to design new test cases (code-testing), perform report-only audits, create project files rather than explain MSTest setup, run tests, migrate frameworks, or handle non-MSTest\u002Fnon-.NET code.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fwriting-mstest-tests\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":51,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M76ZDFDF4N88RH6HSYGS7GP2","wgs-prs","End-to-end WGS to polygenic risk score pipeline. Takes paired-end FASTQ files (or a pre-existing VCF) through nf-core\u002Fsarek for variant calling, applies VCF QC (normalisation, hard filtering, Ti\u002FTv and Het\u002FHom checks), then computes polygenic risk scores via the PGS Catalog. Fills the FASTQ to VCF gap upstream of the gwas-prs skill.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fwgs-prs\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":59,"licenseFileUrl":89,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M76ZCC1SC68J42QK4MDC8RCG","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fstanfish06\u002Fskillquarium\u002Fblob\u002Fmaster\u002Fskills\u002Fwebapp-testing\u002FSKILL.md",[],[]]