[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73HBHHFPG85PNJYWABSCYEM":3,"skill-same:01M73HBHHFPG85PNJYWABSCYEM":48},{"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":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M73HBHHFPG85PNJYWABSCYEM","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.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"BSD-3-Clause","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fmuon-multiomics-singlecell\u002FSKILL.md",[],[],"2026-11-11 15:11:14",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 **omics-plotting** SKILL for generic result-table figures; joint embeddings use scanpy\u002Fmuon `sc.pl.*` \u002F `mu.pl.*`\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[all]\" \"scanpy[leiden]\" anndata\n# Optional: for MOFA+ integration\npip install mofapy2\n```\n\n## Pre-flight Interview\n\nSettle these with the user before writing any analysis code.\n\n```yaml\ndecisions:\n  - id: D1\n    param: modalities\n    kind: required\n    source: data\n    ask: \"Which measurement types are being integrated, and are they from the same cells or matched separately?\"\n    default: null\n\n  - id: D2\n    param: perModalityEmbedding\n    kind: required\n    source: data\n    depends_on: [D1]\n    ask: \"How should each modality be reduced before joint analysis - PCA for expression, latent semantic indexing for accessibility?\"\n    default: null\n\n  - id: D3\n    param: integrationMethod\n    kind: required\n    source: user\n    depends_on: [D1]\n    ask: \"Join the modalities by a weighted nearest-neighbour graph, or by a shared factor model?\"\n    default: \"weighted nearest neighbours\"\n\n  - id: D4\n    param: clusterResolution\n    kind: required\n    source: user\n    ask: \"How finely should the joint graph be split into cell groups?\"\n    default: 1.0\n\n  - id: D5\n    param: neighborhoodSize\n    kind: optional\n    source: user\n    ask: \"How many neighbours should define each cell's local structure?\"\n    default: 30\n\n  - id: D6\n    param: accessibilityNormalization\n    kind: optional\n    source: user\n    ask: \"Which scaling should the accessibility modality use before dimensionality reduction?\"\n    default: \"TF-IDF at 1e4\"\n\n  - id: D7\n    param: factorCount\n    kind: optional_conditional\n    source: user\n    depends_on: [D3]\n    ask: \"How many latent factors should the shared factor model infer?\"\n    default: 10\n    skip_if: \"weighted nearest-neighbour integration\"\n```\n\nD2 is not a formality. Applying expression-style PCA to accessibility data\nbefore joint analysis lets sequencing depth dominate the first component, and\nthe weighted graph then down-weights a modality for being uninformative when\nthe preprocessing is what made it so.\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\nmu.pp.neighbors(mdata, key_added=\"wnn\",\n                use_rep={\"rna\": \"X_pca\", \"atac\": \"X_lsi\"})\nsc.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, use_highly_variable=False)\n# LSI component 1 correlates with sequencing depth — exclude it\n# mu.atac.tl.lsi sets X_lsi starting from component 2 by default\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 (optional but enables modality-specific UMAPs)\nmu.pp.neighbors(mdata[\"rna\"],  use_rep=\"X_pca\",  n_neighbors=30, key_added=\"neighbors\")\nmu.pp.neighbors(mdata[\"atac\"], use_rep=\"X_lsi\",  n_neighbors=30, key_added=\"neighbors\")\n\n# WNN joint neighbor graph across modalities\nmu.pp.neighbors(\n    mdata,\n    key_added=\"wnn\",\n    use_rep={\"rna\": \"X_pca\", \"atac\": \"X_lsi\"},\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\nsc.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()` colors joint UMAP embeddings by features from any modality; `sc.pl.umap()` with `color` pointing to modality-prefixed feature names (e.g., `\"rna:CD3E\"`) is also supported.\n\n```python\nimport matplotlib.pyplot as plt\n\n# Joint UMAP colored by cluster assignment\nsc.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\nsc.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 (optional for modality-specific plots) ---\nmu.pp.neighbors(mdata[\"rna\"],  use_rep=\"X_pca\", n_neighbors=15, key_added=\"neighbors\")\nmu.pp.neighbors(mdata[\"atac\"], use_rep=\"X_lsi\",  n_neighbors=15, key_added=\"neighbors\")\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                use_rep={\"rna\": \"X_pca\", \"atac\": \"X_lsi\"},\n                n_neighbors=15, random_state=42)\n\n# --- 6. UMAP + Leiden clustering ---\nsc.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))\nsc.pl.umap(mdata, color=\"leiden_wnn\", ax=axes[0], show=False, title=\"WNN clusters\")\nsc.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 ---\nmu.pp.neighbors(mdata, key_added=\"wnn\",\n                use_rep={\"rna\": \"X_pca\", \"protein\": \"X_pca\"},\n                n_neighbors=20, random_state=0)\nsc.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))\nsc.pl.umap(mdata, color=\"leiden_wnn\",   ax=axes[0], show=False, title=\"WNN Leiden\")\nsc.pl.umap(mdata, color=\"protein:CD3\",  ax=axes[1], show=False, title=\"CD3 (CLR)\",\n           use_raw=False, vmax=\"p99\")\nsc.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` | `mu.pp.neighbors()` | `None` (auto) | dict of `{modality: embedding_key}` | Which embedding per modality to use for WNN |\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**: Always name the joint graph `\"wnn\"` and pass `neighbors_key=\"wnn\"` to all downstream `sc.tl.umap()`, `sc.tl.leiden()`, and `sc.tl.paga()` calls. 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 `sc.tl.umap()` and `sc.tl.leiden()` |\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 **omics-plotting** SKILL for generic result-table figures; joint embeddings use scanpy\u002Fmuon `sc.pl.*` \u002F `mu.pl.*`\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[all]\" \"scanpy[leiden]\" anndata\n# Optional: for MOFA+ integration\npip install mofapy2\n```\n\n## Pre-flight Interview\n\nSettle these with the user before writing any analysis code.\n\n```yaml\ndecisions:\n  - id: D1\n    param: modalities\n    kind: required\n    source: data\n    ask: \"Which measurement types are being integrated, and are they from the same cells or matched separately?\"\n    default: null\n\n  - id: D2\n    param: perModalityEmbedding\n    kind: required\n    source: data\n    depends_on: [D1]\n    ask: \"How should each modality be reduced before joint analysis - PCA for expression, latent semantic indexing for accessibility?\"\n    default: null\n\n  - id: D3\n    param: integrationMethod\n    kind: required\n    source: user\n    depends_on: [D1]\n    ask: \"Join the modalities by a weighted nearest-neighbour graph, or by a shared factor model?\"\n    default: \"weighted nearest neighbours\"\n\n  - id: D4\n    param: clusterResolution\n    kind: required\n    source: user\n    ask: \"How finely should the joint graph be split into cell groups?\"\n    default: 1.0\n\n  - id: D5\n    param: neighborhoodSize\n    kind: optional\n    source: user\n    ask: \"How many neighbours should define each cell's local structure?\"\n    default: 30\n\n  - id: D6\n    param: accessibilityNormalization\n    kind: optional\n    source: user\n    ask: \"Which scaling should the accessibility modality use before dimensionality reduction?\"\n    default: \"TF-IDF at 1e4\"\n\n  - id: D7\n    param: factorCount\n    kind: optional_conditional\n    source: user\n    depends_on: [D3]\n    ask: \"How many latent factors should the shared factor model infer?\"\n    default: 10\n    skip_if: \"weighted nearest-neighbour integration\"\n```\n\nD2 is not a formality. Applying expression-style PCA to accessibility data\nbefore joint analysis lets sequencing depth dominate the first component, and\nthe weighted graph then down-weights a modality for being uninformative when\nthe preprocessing is what made it so.\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\nmu.pp.neighbors(mdata, key_added=\"wnn\",\n                use_rep={\"rna\": \"X_pca\", \"atac\": \"X_lsi\"})\nsc.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, use_highly_variable=False)\n# LSI component 1 correlates with sequencing depth — exclude it\n# mu.atac.tl.lsi sets X_lsi starting from component 2 by default\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 (optional but enables modality-specific UMAPs)\nmu.pp.neighbors(mdata[\"rna\"],  use_rep=\"X_pca\",  n_neighbors=30, key_added=\"neighbors\")\nmu.pp.neighbors(mdata[\"atac\"], use_rep=\"X_lsi\",  n_neighbors=30, key_added=\"neighbors\")\n\n# WNN joint neighbor graph across modalities\nmu.pp.neighbors(\n    mdata,\n    key_added=\"wnn\",\n    use_rep={\"rna\": \"X_pca\", \"atac\": \"X_lsi\"},\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\nsc.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()` colors joint UMAP embeddings by features from any modality; `sc.pl.umap()` with `color` pointing to modality-prefixed feature names (e.g., `\"rna:CD3E\"`) is also supported.\n\n```python\nimport matplotlib.pyplot as plt\n\n# Joint UMAP colored by cluster assignment\nsc.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\nsc.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 (optional for modality-specific plots) ---\nmu.pp.neighbors(mdata[\"rna\"],  use_rep=\"X_pca\", n_neighbors=15, key_added=\"neighbors\")\nmu.pp.neighbors(mdata[\"atac\"], use_rep=\"X_lsi\",  n_neighbors=15, key_added=\"neighbors\")\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                use_rep={\"rna\": \"X_pca\", \"atac\": \"X_lsi\"},\n                n_neighbors=15, random_state=42)\n\n# --- 6. UMAP + Leiden clustering ---\nsc.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))\nsc.pl.umap(mdata, color=\"leiden_wnn\", ax=axes[0], show=False, title=\"WNN clusters\")\nsc.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 ---\nmu.pp.neighbors(mdata, key_added=\"wnn\",\n                use_rep={\"rna\": \"X_pca\", \"protein\": \"X_pca\"},\n                n_neighbors=20, random_state=0)\nsc.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))\nsc.pl.umap(mdata, color=\"leiden_wnn\",   ax=axes[0], show=False, title=\"WNN Leiden\")\nsc.pl.umap(mdata, color=\"protein:CD3\",  ax=axes[1], show=False, title=\"CD3 (CLR)\",\n           use_raw=False, vmax=\"p99\")\nsc.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` | `mu.pp.neighbors()` | `None` (auto) | dict of `{modality: embedding_key}` | Which embedding per modality to use for WNN |\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**: Always name the joint graph `\"wnn\"` and pass `neighbors_key=\"wnn\"` to all downstream `sc.tl.umap()`, `sc.tl.leiden()`, and `sc.tl.paga()` calls. 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 `sc.tl.umap()` and `sc.tl.leiden()` |\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","fd76f882a04e445e899d5cfb2732f2105ea054ee","skills\u002Fawesome-skills\u002Fmuon-multiomics-singlecell",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill muon-multiomics-singlecell",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill muon-multiomics-singlecell",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill muon-multiomics-singlecell","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fmuon-multiomics-singlecell\u002FSKILL.md",true,[],[49,58,65,72,79,86],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":57},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":57},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":57},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":57},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":57},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":57},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]