[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M76EWABHH82V5GVST7HX21W4":3,"skill-same:01M76EWABHH82V5GVST7HX21W4":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},"01M76EWABHH82V5GVST7HX21W4","spatial-transcriptomics-cell-cell-communication",null,"Spatial cell-cell communication \u002F ligand-receptor (LR) interaction analysis, one skill for every route: LIANA consensus ranking between annotated cell types, CellPhoneDB v5 permutation p-values, DEG method and spatial microenvironments, squidpy neighbourhood enrichment to keep spatially adjacent sender-receiver pairs, LIANA bivariate local LR scores on the tissue (works on Visium spots without labels), pathway-focused candidate evidence tables (immune checkpoints, chemokines, Notch, Wnt, TGF-beta) with contact vs secreted classes and PubMed co-mentions, and multi-sample Tensor-cell2cell and MISTy models. Xenium\u002FMERFISH\u002FCosMx cells, Visium spots, scRNA-seq. Route-specific steps follow the main workflow. Needs cell type labels first (spatial-transcriptomics-cell-type-annotation or a deconvolution skill).","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"CC-BY-4.0","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fspatial-transcriptomics-cell-cell-communication\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: \"spatial-transcriptomics-cell-cell-communication\"\ndescription: \"Spatial cell-cell communication \u002F ligand-receptor (LR) interaction analysis, one skill for every route: LIANA consensus ranking between annotated cell types, CellPhoneDB v5 permutation p-values, DEG method and spatial microenvironments, squidpy neighbourhood enrichment to keep spatially adjacent sender-receiver pairs, LIANA bivariate local LR scores on the tissue (works on Visium spots without labels), pathway-focused candidate evidence tables (immune checkpoints, chemokines, Notch, Wnt, TGF-beta) with contact vs secreted classes and PubMed co-mentions, and multi-sample Tensor-cell2cell and MISTy models. Xenium\u002FMERFISH\u002FCosMx cells, Visium spots, scRNA-seq. Route-specific steps follow the main workflow. Needs cell type labels first (spatial-transcriptomics-cell-type-annotation or a deconvolution skill).\"\nlicense: \"CC-BY-4.0\"\n---\n\n# Spatial Cell-Cell Communication\n\n## Overview\n\nExpression-based ligand-receptor (LR) inference ranks pairs that *could*\nsignal; spatial data adds whether sender and receiver actually sit next to\neach other. This skill runs one inference (LIANA consensus by default, or\nCellPhoneDB statistics), puts the result into one table, keeps interactions\nwhose cell types are spatial neighbours, scores LR co-expression at each\nlocation, and narrows the table to the user's question with an evidence class\nper candidate. Expression of both partners never proves signalling: every\nresult is a candidate.\n\n| Question | Route |\n|---|---|\n| Which LR pairs between my cell types, and are the types neighbours | Workflow Steps 1-6 |\n| Permutation p-values per pair, DEG-driven or microenvironment-restricted tests | Route: CellPhoneDB v5 Statistics, in place of Step 2 |\n| Where on the tissue an LR pair is co-expressed (labels not needed) | Step 5; p-value\u002Fcategory layers in Route: LIANA Multi-sample |\n| Communication differences across samples or conditions | Route: LIANA Multi-sample (by-sample ranking, Tensor-cell2cell) |\n| What in the neighbourhood explains cell type composition | Route: LIANA Multi-sample (MISTy) |\n| Literature support and which candidates to validate | After Step 6, Route: Literature Evidence |\n\nAll routes are in `## Task Routes` below the Workflow.\n\n## When to Use\n\n- Finding which annotated cell types may signal to each other in a spatial section\n- Separating interactions between neighbouring cell types from those between distant ones\n- Testing which LR pairs are specific to a sender-receiver pair with CellPhoneDB p-values\n- Mapping where on the tissue a ligand and its receptor are co-expressed, also on Visium spots\n- Asking about one pathway family (immune checkpoints, chemokines, Notch, Wnt, TGF-beta) after inference\n- Comparing communication programs across samples or conditions\n- For neighbourhood enrichment or co-occurrence alone, without LR pairs, use `spatial-transcriptomics-analysis-squidpy`\n\n## Prerequisites\n\n- **Input**: log-normalised expression in `X` (not z-scored) and `obsm[\"spatial\"]`\n- **Labels**: a cell type column in `obs` for Steps 2-4 and 6\n  (`spatial-transcriptomics-cell-type-annotation`). Visium spots have no labels:\n  Step 5 works without them; Steps 2-4 need a deconvolution first\n  (`spatial-transcriptomics-deconvolution-cell2location`)\n- **Genes**: gene symbols; CellPhoneDB is human-only (mouse via orthologs, see its reference)\n- **Python packages**: `liana`, `squidpy`, `scanpy`; `cellphonedb`, `cell2cell` only for their routes\n\n```bash\n# Install only what `import` reports missing. `--pypi` keeps the env's scanpy\u002Fnumba\n# stack; a conda add can swap it and bare pip can shadow it.\npixi add --pypi liana squidpy scanpy\n```\n\n## Pre-flight Interview\n\n```yaml\ndecisions:\n  - id: D1\n    param: CELL_TYPE_KEY\n    kind: required\n    source: data\n    ask: \"Which column holds the cell types whose communication you want to study?\"\n    default: null\n\n  - id: D2\n    param: RESOURCE\n    kind: required\n    source: data\n    ask: \"The gene symbols look \u003Chuman\u002Fmouse>: use the \u003Chuman\u002Fmouse> ligand-receptor database?\"\n    default: \"consensus for human symbols, mouseconsensus for mouse symbols\"\n\n  - id: D3\n    param: METHOD\n    kind: required\n    source: user\n    ask: \"Rank interactions by agreement across several methods (LIANA consensus, recommended), or do you need CellPhoneDB permutation p-values per pair (slower, human symbols)?\"\n    default: \"LIANA consensus\"\n\n  - id: D4\n    param: QUERY\n    kind: optional\n    source: user\n    ask: \"Is there a pathway (immune checkpoints, chemokines, growth factors, Notch, Wnt, TGF-beta) or a sender -> receiver direction you care about?\"\n    default: \"all pathways and all cell type pairs\"\n\n  - id: D5\n    param: SAMPLE_KEY\n    kind: required\n    source: data\n    skip_if: \"the data holds a single sample\"\n    ask: \"Which column identifies the samples, and which one the condition to compare?\"\n    default: null\n\n  - id: D6\n    param: expr_prop\n    kind: optional\n    source: user\n    ask: \"Minimum fraction of a cell type that must express each partner gene?\"\n    default: \"0.1\"\n\n  - id: D7\n    param: NEIGHBOUR_Z\n    kind: optional\n    source: user\n    ask: \"How strongly must two cell types co-locate to count as neighbours?\"\n    default: \"neighbourhood z > 2 over 15 nearest neighbours\"\n\n  - id: D8\n    param: BANDWIDTH\n    kind: optional_conditional\n    source: data\n    ask: \"The coordinates are in \u003Cmicrons\u002Fpixels>; how wide should the local neighbourhood be?\"\n    default: \"from li.pp.query_bandwidth: a few to tens of neighbours per location\"\n\n  - id: D9\n    param: REGION_KEY\n    kind: optional_conditional\n    source: data\n    depends_on: [D3]\n    skip_if: \"METHOD is LIANA consensus\"\n    ask: \"Should CellPhoneDB only test cell types that share a tissue region? If so, which region\u002Fniche column?\"\n    default: \"no restriction\"\n\n  - id: D10\n    param: n_perms\n    kind: optional\n    source: user\n    ask: \"How many permutations for p-values?\"\n    default: \"1000 for neighbourhood\u002FCellPhoneDB tests, 100 for local LR scores\"\n```\n\nAsk D1-D3 together, with D5 when `obs` has a sample-like column. Offer the\n`obs` columns that look like cell type labels for D1; if none exist on\nsingle-cell-resolution data, stop and annotate first. On Visium without a\ndeconvolution, say that only Step 5 can run.\n\n## Workflow\n\n1. Inputs, organism and panel coverage\n2. Rank LR pairs between cell types\n3. Harmonise results into one table\n4. Keep spatially adjacent pairs\n5. Local LR co-expression on the tissue\n6. Focus on the question and classify candidates\n\n### Step 1: Inputs and Panel Coverage\n\n```python\nimport liana as li\nimport numpy as np\nimport pandas as pd\nimport scanpy as sc\n\nadata = sc.read_h5ad(\"celltype_annotated.h5ad\")\nCELL_TYPE_KEY = \"cell_type\"                         # D1\nadata.obs[CELL_TYPE_KEY] = adata.obs[CELL_TYPE_KEY].astype(\"category\")\nprint(adata.obs[CELL_TYPE_KEY].value_counts())\n\nhead = adata.var_names[:200]                         # mouse \"Actb\" vs human \"ACTB\"\nn_mouse = sum(len(g) > 1 and g[0].isupper() and g[1:].islower() for g in head)\nRESOURCE = \"mouseconsensus\" if n_mouse > len(head) \u002F 2 else \"consensus\"   # D2\nprint(f\"resource: {RESOURCE}; max X = {adata.X.max():.1f} (expect \u003C ~15 for log data)\")\n\nresource = li.rs.select_resource(RESOURCE)\ngenes = set(adata.var_names)\ndef present(complex_):\n    return all(g in genes for g in complex_.split(\"_\"))\ncovered = resource[resource[\"ligand\"].map(present) & resource[\"receptor\"].map(present)]\nprint(f\"LR pairs measurable: {len(covered)} of {len(resource)}\")\n```\n\nA targeted panel (Xenium ~400 genes) measures only a small share of the\nresource. Report that coverage with the results: absent pairs were not\nmeasured, not ruled out.\n\n### Step 2: Rank LR Pairs Between Cell Types\n\nLIANA consensus (`magnitude_rank`, `specificity_rank`; lower = stronger,\naggregated over CellPhoneDB, CellChat, NATMI, Connectome and others). For\nCellPhoneDB statistics, run Route: CellPhoneDB v5 Statistics instead and continue\nat Step 3 with `SOURCE = \"cellphonedb\"`.\n\n```python\nli.mt.rank_aggregate(adata, groupby=CELL_TYPE_KEY, resource_name=RESOURCE,\n                     expr_prop=0.1, use_raw=False, key_added=\"liana_res\", verbose=True)\nres = adata.uns[\"liana_res\"]\nres.to_csv(\"liana_results.csv\", index=False)\nprint(res.sort_values(\"magnitude_rank\").head(15)[\n    [\"source\", \"target\", \"ligand_complex\", \"receptor_complex\", \"magnitude_rank\", \"specificity_rank\"]])\n```\n\n```python\np = li.pl.dotplot(adata=adata, colour=\"magnitude_rank\", size=\"specificity_rank\",\n                  inverse_colour=True, inverse_size=True, top_n=20,\n                  orderby=\"magnitude_rank\", orderby_ascending=True, figure_size=(10, 8),\n                  return_fig=True)          # restrict with source_labels=[...], target_labels=[...]\np.save(\"liana_dotplot.png\", dpi=150)\n```\n\n| Column | Meaning |\n|---|---|\n| `source` \u002F `target` | Sender (ligand) \u002F receiver (receptor) cell type |\n| `ligand_complex` \u002F `receptor_complex` | Genes; complexes joined by `_` |\n| `lr_means` | Mean of ligand and receptor expression |\n| `magnitude_rank` \u002F `specificity_rank` | Consensus ranks of strength \u002F cell type specificity |\n\n### Step 3: Harmonise Results\n\nOne row per (sender, receiver, ligand, receptor) with a score and a p-value\nor rank, from either tool, so Steps 4 and 6 run the same way:\n\n```python\nSOURCE = \"liana\"            # or \"cellphonedb\" (significant_long.csv from its reference)\nTOP_RANK = 0.05             # LIANA magnitude_rank cutoff for \"top\" interactions\n\nif SOURCE == \"liana\":\n    r = res[res[\"magnitude_rank\"] \u003C= TOP_RANK]\n    lr = pd.DataFrame({\n        \"sender\": r[\"source\"], \"receiver\": r[\"target\"],\n        \"ligand\": r[\"ligand_complex\"], \"receptor\": r[\"receptor_complex\"],\n        \"score\": r[\"lr_means\"], \"p_or_rank\": r[\"magnitude_rank\"], \"specificity\": r[\"specificity_rank\"]})\nelse:\n    r = pd.read_csv(\"cellphonedb\u002Fsignificant_long.csv\")\n    r = r[r[\"pval\"] \u003C 0.05]\n    for c in (\"partner_a\", \"partner_b\"):\n        r[c] = r[c].str.replace(r\"^(simple|complex):\", \"\", regex=True)\n    swap = r[\"receptor_a\"].astype(bool) & ~r[\"receptor_b\"].astype(bool)   # orient ligand -> receptor\n    lr = pd.DataFrame({\n        \"sender\": np.where(swap, r[\"cell_b\"], r[\"cell_a\"]), \"receiver\": np.where(swap, r[\"cell_a\"], r[\"cell_b\"]),\n        \"ligand\": np.where(swap, r[\"partner_b\"], r[\"partner_a\"]),\n        \"receptor\": np.where(swap, r[\"partner_a\"], r[\"partner_b\"]),\n        \"score\": r[\"mean\"], \"p_or_rank\": r[\"pval\"], \"specificity\": r.get(\"score\")})\n\nlr[\"genes\"] = (lr[\"ligand\"] + \"_\" + lr[\"receptor\"]).str.upper().str.split(\"_\").map(set)\nif SOURCE == \"cellphonedb\" and \"genes\" in r:      # subunit genes of complexes (saved as \"{'ITGA4', ...}\")\n    import ast\n    lr[\"genes\"] = [g | (ast.literal_eval(x) if isinstance(x, str) and x.startswith(\"{\") else set())\n                   for g, x in zip(lr[\"genes\"], r[\"genes\"])]\nlr = lr.reset_index(drop=True)\nprint(f\"{len(lr)} rows, {lr[['ligand', 'receptor']].drop_duplicates().shape[0]} LR pairs\")\n```\n\nFor LIANA lower `p_or_rank` \u002F `specificity` is better; for CellPhoneDB\n`p_or_rank` is a p-value and `specificity` the 0-100 interaction score\n(higher is better). CellPhoneDB complex names (e.g. `integrin_a4b1_complex`)\nare not symbols; the code adds their subunit genes.\n\n### Step 4: Keep Spatially Adjacent Pairs\n\n```python\nimport squidpy as sq\n\nsq.gr.spatial_neighbors(adata, coord_type=\"generic\", n_neighs=15)   # Visium: coord_type=\"grid\", n_rings=1\nsq.gr.nhood_enrichment(adata, cluster_key=CELL_TYPE_KEY, n_perms=1000, seed=0)\ncats = adata.obs[CELL_TYPE_KEY].cat.categories\nz = pd.DataFrame(adata.uns[f\"{CELL_TYPE_KEY}_nhood_enrichment\"][\"zscore\"], index=cats, columns=cats)\nz.to_csv(\"nhood_enrichment_z.csv\")\n\nNEIGHBOUR_Z = 2                                                     # D7\nlr[\"neighbour_z\"] = [z.loc[s, t] if s in z.index and t in z.columns else np.nan\n                     for s, t in zip(lr[\"sender\"], lr[\"receiver\"])]\nlr[\"autocrine\"] = lr[\"sender\"] == lr[\"receiver\"]\nadjacent = lr[(lr[\"neighbour_z\"] > NEIGHBOUR_Z) | lr[\"autocrine\"]].sort_values(\"p_or_rank\")\nadjacent.drop(columns=[\"genes\"]).to_csv(\"lr_adjacent_pairs.csv\", index=False)\nprint(f\"{len(adjacent)} of {len(lr)} top interactions are between neighbouring (or the same) cell types\")\n```\n\nAutocrine pairs are always adjacent; read them separately. On Visium spots\nthe label-based test is coarse; prefer Step 5 there. Show the co-location\nmatrix the filter is based on:\n\n```python\nsq.pl.nhood_enrichment(adata, cluster_key=CELL_TYPE_KEY, cmap=\"coolwarm\", vmin=-10, vmax=10,\n                       figsize=(7, 6), save=\"nhood_enrichment.png\")\n```\n\n### Step 5: Local LR Co-expression on the Tissue\n\nScores each LR pair at every location, so it also works on Visium spots\nwithout labels. Pick the bandwidth from the coordinate scale first:\n\n```python\nspatial_neighbors = li.pp.spatial_neighbors if hasattr(li, \"pp\") else li.ut.spatial_neighbors  # li.ut in older liana\nplot, bw_table = li.pp.query_bandwidth(coordinates=adata.obsm[\"spatial\"], start=0, end=500, interval_n=20)\nplot.save(\"liana_bandwidth.png\", dpi=150)\nprint(bw_table.head(10))      # average neighbours per bandwidth: aim for a few to tens\n\nBANDWIDTH = 100               # D8; coordinate units: ~50-100 um Xenium; Visium full-res px ~2-3 spot spacings\nspatial_neighbors(adata, bandwidth=BANDWIDTH, cutoff=0.1, kernel=\"gaussian\", set_diag=True)\nlrdata = li.mt.bivariate(adata, resource_name=RESOURCE, local_name=\"cosine\", global_name=\"morans\",\n                         n_perms=100, mask_negatives=False, add_categories=True, nz_prop=0.1,\n                         use_raw=False, verbose=True)\nsummary = lrdata.var.sort_values(\"morans\", ascending=False)\nsummary.to_csv(\"liana_bivariate_summary.csv\")\nlrdata.write_h5ad(\"liana_bivariate.h5ad\")\nprint(summary.head(10))\nsc.pl.embedding(lrdata, basis=\"spatial\", color=summary.index[:4].tolist(), cmap=\"coolwarm\", save=\"_lr_local.png\")\n```\n\n`var[\"morans\"]` is the global spatial co-pattern of ligand and receptor; the\nper-location p-values (`layers[\"pvals\"]`) and categories (`layers[\"cats\"]`:\nboth high \u002F one high \u002F both low) are read in Route: LIANA Multi-sample.\n\n### Step 6: Focus and Classify Candidates\n\nNarrow the table to the user's question (D4) and give each candidate an\nevidence class. Matching is per gene symbol, so `CD4` does not hit `CD40`.\n\n```python\nPATHWAYS = {\n    \"immune_checkpoint\": [\"PDCD1\", \"CD274\", \"PDCD1LG2\", \"CTLA4\", \"CD28\", \"CD80\", \"CD86\",\n                          \"LAG3\", \"HAVCR2\", \"LGALS9\", \"TIGIT\", \"PVR\", \"NECTIN2\"],\n    \"chemokine\": [\"CXCL*\", \"CCL*\", \"CX3CL1\", \"XCL*\", \"CXCR*\", \"CCR*\", \"CX3CR1\", \"XCR1\", \"ACKR*\"],\n    \"growth_factor\": [\"EGF\", \"EGFR\", \"ERBB*\", \"VEGF*\", \"KDR\", \"FLT1\", \"FLT4\", \"FGF*\", \"FGFR*\",\n                      \"PDGF*\", \"HGF\", \"MET\", \"IGF1\", \"IGF1R\"],\n    \"notch\": [\"NOTCH*\", \"JAG1\", \"JAG2\", \"DLL1\", \"DLL3\", \"DLL4\"],\n    \"wnt\": [\"WNT*\", \"FZD*\", \"LRP5\", \"LRP6\", \"RSPO*\", \"LGR*\"],\n    \"tgfb_bmp\": [\"TGFB*\", \"TGFBR*\", \"BMP*\", \"BMPR*\", \"ACVR*\", \"GDF*\"],\n}\ndef matches(genes, patterns):\n    return any(g.startswith(p[:-1]) if p.endswith(\"*\") else g == p for g in genes for p in patterns)\nfor name, pats in PATHWAYS.items():\n    lr[name] = lr[\"genes\"].map(lambda g: matches(g, pats))\nlr[\"pathway\"] = lr[list(PATHWAYS)].apply(lambda row: \",\".join(k for k, v in row.items() if v), axis=1)\n\nQUERY = list(PATHWAYS)                               # D4, e.g. [\"immune_checkpoint\", \"chemokine\"]\nSENDERS, RECEIVERS = None, None                      # e.g. {\"Tumor cell\"}, {\"T cell\"}\nq = lr[lr[QUERY].any(axis=1)]\nif SENDERS: q = q[q[\"sender\"].isin(SENDERS)]\nif RECEIVERS: q = q[q[\"receiver\"].isin(RECEIVERS)]\n\nCONTACT = {\"CD274\", \"PDCD1\", \"PDCD1LG2\", \"CTLA4\", \"CD28\", \"CD80\", \"CD86\", \"JAG1\", \"JAG2\",\n           \"DLL1\", \"DLL3\", \"DLL4\", \"NOTCH1\", \"NOTCH2\", \"NOTCH3\", \"NOTCH4\", \"TIGIT\", \"PVR\", \"NECTIN2\"}\ndef evidence_class(row):\n    if pd.isna(row[\"neighbour_z\"]):\n        return \"no spatial test\"\n    if row[\"neighbour_z\"] > NEIGHBOUR_Z or row[\"autocrine\"]:\n        return \"co-located\"\n    return \"unlikely (contact, not co-located)\" if row[\"ligand\"].split(\"_\")[0] in CONTACT else \"possible paracrine\"\nq = q.assign(evidence_class=q.apply(evidence_class, axis=1))\nev = q.drop(columns=[\"genes\"]).sort_values([\"p_or_rank\", \"score\"], ascending=[True, False])\nev.to_csv(\"lr_candidate_evidence.csv\", index=False)\nprint(ev.groupby([\"pathway\", \"evidence_class\"]).size())\n```\n\n`CONTACT` is a starting list of membrane-bound partners; extend it for the\npathways in `QUERY`. Plot the top candidates:\n\n```python\nimport matplotlib.pyplot as plt\n\ntop = ev.head(30).copy()\ntop[\"lr\"] = top[\"ligand\"] + \" -> \" + top[\"receptor\"]\ntop[\"pair\"] = top[\"sender\"].astype(str) + \" -> \" + top[\"receiver\"].astype(str)\nfig, ax = plt.subplots(figsize=(max(8, 0.4 * top[\"pair\"].nunique()), max(6, 0.3 * top[\"lr\"].nunique())))\ns = ax.scatter(top[\"pair\"], top[\"lr\"], c=top[\"neighbour_z\"], cmap=\"coolwarm\", vmin=-5, vmax=5,\n               s=30 + 200 * top[\"score\"] \u002F top[\"score\"].max())\nplt.colorbar(s, label=\"neighbourhood z (sender-receiver)\"); plt.xticks(rotation=90)\nplt.tight_layout(); plt.savefig(\"lr_candidates.png\", dpi=150); plt.close()\n```\n\n| Evidence pattern | Interpretation |\n|---|---|\n| Top-ranked \u002F significant, co-located | Strong candidate; check literature (Route: Literature Evidence) |\n| Top-ranked, not co-located, secreted ligand | Possible paracrine signal; weaker |\n| Top-ranked, not co-located, contact-dependent | Unlikely in this tissue |\n| Only one partner above `expr_prop` | Not supported |\n\nState validation routes (spatial protein staining, receptor blocking,\nperturbation) for the top candidates.\n\n## Task Routes\n\nEach route continues the Workflow session (same variable names). Only the calls\nthat differ from the Workflow, or that fail silently when written another way,\nare shown.\n\n### Route: CellPhoneDB v5 Statistics\n\nScores each curated LR pair, including multi-subunit complexes, for every\nordered pair of cell types; the statistical method tests specificity by\nshuffling labels. Run it in place of Step 2, write `cellphonedb\u002Fsignificant_long.csv`,\nthen continue at Step 3 with `SOURCE = \"cellphonedb\"`. Install\n`pixi add --pypi cellphonedb`.\n\n| Method | Call | Use when |\n|---|---|---|\n| Simple | `cpdb_analysis_method` | Quick look, no statistics |\n| Statistical | `cpdb_statistical_analysis_method` | Discovery; permutation p-values |\n| DEG-based | `cpdb_degs_analysis_method` | Interactions driven by genes up in one cell type; result has `relevant_interactions` instead of `pvalues` |\n\nInputs and gotchas:\n\n- Database: without GitHub access, download `cellphonedb.zip` from the\n  `ventolab\u002Fcellphonedb-data` releases by hand into `CPDB_DIR`.\n- `counts.h5ad` holds normalised (log) expression, not z-scored, with human HGNC\n  symbols. Cell type names must not contain `|`, the result separator.\n- Mouse: map symbols 1:1 to human first:\n  `li.rs.get_hcop_orthologs(target_organism=\"mouse\", columns=[\"human_symbol\", \"mouse_symbol\"], min_evidence=3)`,\n  keep rows unique on both columns, rename `var_names`.\n- Microenvironments (D9): a `cell_type` \u002F `microenvironment` table built from a\n  region column, a type counting as present above ~2% of the region's cells;\n  only pairs of co-located types are tested.\n- DEG method: `degs.tsv` with `cluster` \u002F `gene` columns of up-regulated genes\n  (e.g. `rank_genes_groups`, adj p \u003C 0.05, logFC > 0.25).\n\n```python\nimport os\nfrom cellphonedb.src.core.methods import cpdb_statistical_analysis_method\nfrom cellphonedb.utils import db_utils\n\nCPDB_DIR = os.path.abspath(\"ref_cache\u002Fcellphonedb\u002Fv5.0.0\")\nCPDB_ZIP = os.path.join(CPDB_DIR, \"cellphonedb.zip\")\nif not os.path.exists(CPDB_ZIP):\n    os.makedirs(CPDB_DIR, exist_ok=True)\n    db_utils.download_database(CPDB_DIR, \"v5.0.0\")\nOUT = \"cellphonedb\"\nos.makedirs(OUT, exist_ok=True)\nsc.AnnData(X=adata.X, obs=pd.DataFrame(index=adata.obs_names),\n           var=pd.DataFrame(index=adata.var_names)).write_h5ad(f\"{OUT}\u002Fcounts.h5ad\")\npd.DataFrame({\"barcode_sample\": adata.obs_names, \"cell_type\": adata.obs[CELL_TYPE_KEY].astype(str).values}\n             ).to_csv(f\"{OUT}\u002Fmeta.tsv\", sep=\"\\t\", index=False)\n\nres = cpdb_statistical_analysis_method.call(\n    cpdb_file_path=CPDB_ZIP, meta_file_path=f\"{OUT}\u002Fmeta.tsv\", counts_file_path=f\"{OUT}\u002Fcounts.h5ad\",\n    counts_data=\"hgnc_symbol\", microenvs_file_path=None,      # or f\"{OUT}\u002Fmicroenvs.tsv\"\n    score_interactions=True, iterations=1000, threshold=0.1, threads=4, debug_seed=42, pvalue=0.05,\n    subsampling=False,             # >~100k cells: True + subsampling_num_cells, subsampling_log=False\n    output_path=OUT, output_suffix=\"stat\")\n```\n\nLong table read by Step 3 (`cell_a` expresses `partner_a`; Step 3 orients\nligand -> receptor from `receptor_a` \u002F `receptor_b`):\n\n```python\nsig = res[\"significant_means\"]\nlabels = set(adata.obs[CELL_TYPE_KEY].astype(str))\npair_cols = [c for c in sig.columns if c.count(\"|\") == 1 and set(c.split(\"|\")) \u003C= labels]\nmeta_cols = [c for c in [\"id_cp_interaction\", \"interacting_pair\", \"partner_a\", \"partner_b\", \"secreted\",\n                         \"receptor_a\", \"receptor_b\"] if c in sig.columns]\nlong = sig.melt(id_vars=meta_cols, value_vars=pair_cols, var_name=\"pair\", value_name=\"mean\").dropna(subset=[\"mean\"])\npv = res[\"pvalues\"].melt(id_vars=[\"id_cp_interaction\"], value_vars=pair_cols, var_name=\"pair\", value_name=\"pval\")\nlong = long.merge(pv, on=[\"id_cp_interaction\", \"pair\"], how=\"left\")\nlong[[\"cell_a\", \"cell_b\"]] = long[\"pair\"].str.split(\"|\", expand=True)\nif \"interaction_scores\" in res:\n    sc_long = res[\"interaction_scores\"].melt(id_vars=[\"id_cp_interaction\"], value_vars=pair_cols,\n                                             var_name=\"pair\", value_name=\"score\")\n    long = long.merge(sc_long, on=[\"id_cp_interaction\", \"pair\"], how=\"left\")\nlong[\"genes\"] = long[\"id_cp_interaction\"].map(\n    res[\"deconvoluted\"].groupby(\"id_cp_interaction\")[\"gene_name\"].apply(lambda s: set(s.dropna())))\nlong.to_csv(f\"{OUT}\u002Fsignificant_long.csv\", index=False)\n```\n\n| Signal | Meaning |\n|---|---|\n| Low p-value, high mean | Expressed and specific to this cell type pair - strongest candidates |\n| High mean, p >= 0.05 | Broadly expressed; not specific to this pair |\n| High `interaction_scores` (0-100) | Partners specific to these two types relative to all types |\n| `secreted == True` | Ligand can act at a distance; membrane-bound pairs need contact |\n\nTwo conditions: run the statistical method per condition with the same database\nand parameters and compare the significant sets; this is descriptive, since cell\nnumbers per type differ between conditions and change each test's power.\n`ktplotspy` (`plot_cpdb_heatmap`, `plot_cpdb`) draws publication-style figures\nfrom `res`.\n\n### Route: LIANA Multi-sample, Local Score Layers, MISTy\n\nUses `adata`, `CELL_TYPE_KEY`, `RESOURCE`, `BANDWIDTH` and `lrdata` from the\nWorkflow. Functions follow the current `li.pp` \u002F `li.ms` namespaces (older\nreleases: `li.ut` \u002F `li.multi`).\n\n- **Per sample and condition (D5)**: `li.mt.rank_aggregate.by_sample(adata, groupby=CELL_TYPE_KEY,\n  sample_key=SAMPLE_KEY, resource_name=RESOURCE, expr_prop=0.1, use_raw=False, n_perms=None,\n  return_all_lrs=True)`, then pivot `magnitude_rank` by condition (median per\n  interaction). With few samples per condition this is descriptive; no p-values.\n- **Tensor-cell2cell** (`pixi add --pypi cell2cell`, several samples per\n  condition): factorises samples x LR x sender x receiver into patterns. Test a\n  factor's context loadings between conditions across samples (Mann-Whitney)\n  before calling it condition-specific; with few samples, exploratory.\n- **Local score layers** of `lrdata` (Step 5): `X` local score per location\n  (`ligand^receptor`), `layers[\"pvals\"]` per-location permutation p-value,\n  `layers[\"cats\"]` 1 = both high, -1 = one high one low, 0 = both low;\n  `var[\"morans\"]` \u002F `var[\"morans_pvals\"]` global co-pattern. Plot `layer=\"cats\"`\n  to separate true co-localisation (1) from one-partner regions (-1).\n- **MISTy**: for each target (e.g. cell2location proportions) how well it is\n  predicted by the same spot (intra), direct neighbours (juxta) and the wider\n  area (para). `gain_R2` = what the spatial views add over intra; `interactions`\n  with `view` juxta\u002Fpara name the predicting neighbours. Pass\n  `extra=lrdata[:, top_lr]` to ask whether local LR activity predicts\n  composition beyond composition itself.\n- **One method instead of the consensus**: `li.mt.cellphonedb(adata, groupby=CELL_TYPE_KEY,\n  resource_name=RESOURCE, expr_prop=0.1, use_raw=False, n_perms=1000, seed=0,\n  key_added=\"cpdb_res\")` gives `cellphone_pvals` without installing `cellphonedb`.\n\n```python\nimport cell2cell as c2c\nfrom collections import defaultdict\n\nSAMPLE_KEY, CONDITION_KEY = \"sample\", \"condition\"          # D5\nli.mt.rank_aggregate.by_sample(adata, groupby=CELL_TYPE_KEY, sample_key=SAMPLE_KEY, resource_name=RESOURCE,\n                               expr_prop=0.1, use_raw=False, n_perms=None, return_all_lrs=True)\ntensor = li.ms.to_tensor_c2c(adata, sample_key=SAMPLE_KEY, score_key=\"magnitude_rank\", how=\"outer_cells\")\nctx = adata.obs[[SAMPLE_KEY, CONDITION_KEY]].drop_duplicates()\ncontext_dict = defaultdict(lambda: \"Unknown\", zip(ctx[SAMPLE_KEY], ctx[CONDITION_KEY]))\nmeta = c2c.tensor.generate_tensor_metadata(interaction_tensor=tensor, metadata_dicts=[context_dict, None, None, None],\n                                           fill_with_order_elements=True)\ntensor = c2c.analysis.run_tensor_cell2cell_pipeline(\n    tensor, meta, copy_tensor=True, rank=None, tf_optimization=\"regular\", random_state=0, device=\"cpu\",\n    elbow_metric=\"error\", upper_rank=15, tf_init=\"random\", sample_col=\"Element\", group_col=\"Category\",\n    output_fig=False)                         # rank=None: elbow search (slow); or fix e.g. 6\ncontexts = tensor.factors[\"Contexts\"]         # also \"Ligand-Receptor Pairs\", \"Sender Cells\", \"Receiver Cells\"\n```\n\n```python\nfrom liana.method import genericMistyData\nfrom liana.method.sp import LinearModel\n\nadata.obsm[\"compositions\"] = pd.read_csv(\"cell2location_proportions.csv\", index_col=0).loc[adata.obs_names]\ncomps = li.pp.obsm_to_adata(adata, \"compositions\")\nmisty = genericMistyData(intra=comps, cutoff=0.05, bandwidth=BANDWIDTH, n_neighs=6)\nmisty(model=LinearModel, k_cv=10, seed=1337, bypass_intra=False, verbose=True)   # or RandomForestModel\nmisty.uns[\"target_metrics\"].to_csv(\"misty_target_metrics.csv\", index=False)       # intra_R2, multi_R2, gain_R2\nmisty.uns[\"interactions\"].to_csv(\"misty_interactions.csv\", index=False)           # target, predictor, view, importances\n```\n\n### Route: Literature Evidence for Candidates\n\nAdds PubMed support to the Step 6 candidate table (`ev`). NCBI E-utilities need\nno key below 3 requests per second; cap the number of pairs queried. The judgment\nis made from the evidence table, not by the code.\n\n```python\nimport time\nimport requests\n\nEUTILS = \"https:\u002F\u002Feutils.ncbi.nlm.nih.gov\u002Fentrez\u002Feutils\u002Fesearch.fcgi\"\nCONTEXT = \"\"        # optional, e.g. \"lung cancer\" to count context-specific co-mentions\n\ndef pubmed_count(ligand, receptor):\n    a, b = ligand.split(\"_\")[0], receptor.split(\"_\")[0]   # first subunit for complexes\n    term = f\"{a}[tiab] AND {b}[tiab]\" + (f\" AND ({CONTEXT})\" if CONTEXT else \"\")\n    r = requests.get(EUTILS, params={\"db\": \"pubmed\", \"term\": term, \"retmode\": \"json\", \"retmax\": 0}, timeout=30)\n    r.raise_for_status(); time.sleep(0.4)\n    return int(r.json()[\"esearchresult\"][\"count\"])\n\npairs = ev[[\"ligand\", \"receptor\"]].drop_duplicates().head(50)\npairs[\"pubmed_n\"] = [pubmed_count(l, r) for l, r in zip(pairs[\"ligand\"], pairs[\"receptor\"])]\nev = ev.merge(pairs, on=[\"ligand\", \"receptor\"], how=\"left\")\nev[\"final_class\"] = [(\"strong, known\" if (n or 0) > 0 else \"novel, co-located\") if c == \"co-located\" else c\n                     for c, n in zip(ev[\"evidence_class\"], ev[\"pubmed_n\"])]\nev.to_csv(\"lr_candidate_evidence.csv\", index=False)\n```\n\nA zero count with strong statistics is a novelty candidate, not an error. To read\nthe papers, fetch abstracts with `efetch.fcgi?db=pubmed&id=\u003Cids>&rettype=abstract&retmode=text`\nfor the ids of an `esearch` with `retmax=5&sort=relevance`.\n\n## Key Parameters\n\n| Parameter | Default | Effect |\n|---|---|---|\n| `expr_prop` | 0.1 | Min fraction of a cell type expressing each gene |\n| `TOP_RANK` | 0.05 | LIANA `magnitude_rank` cutoff for top interactions |\n| `NEIGHBOUR_Z` | 2 | How strongly two types must co-locate |\n| `n_neighs` | 15 | Size of the spatial neighbourhood (cells) |\n| `BANDWIDTH` | 100 | Spatial kernel for local scores, in coordinate units |\n| `nz_prop` | 0.1 | Min fraction of locations expressing each partner (local scores) |\n| `QUERY` \u002F `SENDERS` \u002F `RECEIVERS` | all | Restricts the candidate table to the question |\n| `threshold` (CellPhoneDB) | 0.1 | Min fraction of a cell type expressing each partner gene |\n| `iterations` (CellPhoneDB) | 1000 | Label permutations; fewer = coarser p-values |\n| `pvalue` | 0.05 | Significance cutoff for `significant_means` |\n| `MIN_FRAC` (microenvs) | 0.02 | Presence cutoff for a type in a region |\n| DEG cutoffs (CellPhoneDB DEG method) | adj p \u003C 0.05, logFC > 0.25 | Which genes count as up-regulated |\n| `subsampling_num_cells` | 1\u002F3 of cells | Geometric sketching size for large datasets |\n| `rank` (Tensor-cell2cell) | None (elbow) | Number of communication patterns; fix 3-6 when the elbow search is slow |\n| `how` (Tensor-cell2cell) | `\"outer_cells\"` | Keep cell types missing in some samples |\n| `bandwidth` (MISTy) | `BANDWIDTH` | Para view kernel width, in coordinate units |\n| `k_cv` (MISTy) | 10 | Cross-validation folds per target |\n| `CONTEXT` | empty | Restricts literature counts to a disease\u002Ftissue |\n| Pairs queried | 50 | Number of PubMed requests |\n| Request delay | 0.4 s | Stays under the 3 requests\u002Fsecond limit |\n\n## Common Recipes\n\n### Recipe: Sender-Receiver Count Map\n\n```python\nimport seaborn as sns\n\ntopn = res[(res[\"magnitude_rank\"] \u003C= 0.05) & (res[\"specificity_rank\"] \u003C= 0.05)]\ncounts = topn.groupby([\"source\", \"target\"]).size().unstack(fill_value=0)\nfig, ax = plt.subplots(figsize=(9, 8))\nsns.heatmap(counts, cmap=\"YlOrRd\", annot=True, fmt=\"d\", ax=ax)\nax.set_xlabel(\"receiver\"); ax.set_ylabel(\"sender\")\nplt.tight_layout(); plt.savefig(\"liana_sender_receiver_counts.png\", dpi=150); plt.close()\n```\n\n### Recipe: Distance Range of One Cell Type Pair\n\nNeighbourhood enrichment is a yes\u002Fno at one scale; co-occurrence shows over\nwhich distance two types stay together:\n\n```python\nANCHOR = \"Macrophage\"                                  # a category of CELL_TYPE_KEY\nsub = adata[np.random.default_rng(0).choice(adata.n_obs, min(adata.n_obs, 20000), replace=False)].copy()\nocc, interval = sq.gr.co_occurrence(sub, cluster_key=CELL_TYPE_KEY, interval=50, copy=True)\nsub_cats = list(sub.obs[CELL_TYPE_KEY].cat.categories)\ndist = interval[1:] if len(interval) == occ.shape[2] + 1 else interval\ncurve = pd.DataFrame(occ[sub_cats.index(ANCHOR)].T, index=np.round(dist, 1), columns=sub_cats)\nprint(curve.iloc[:10].round(2))          # ratio > 1 at short distance = attraction\n```\n\n### Recipe: Visium - Link Local LR Scores to Deconvolved Cell Types\n\n```python\nabund = pd.read_csv(\"cell2location_abundance.csv\", index_col=0).loc[lrdata.obs_names]\nlr_top = summary.index[:20]\nlocal = pd.DataFrame(np.asarray(lrdata[:, lr_top].X.todense()) if hasattr(lrdata.X, \"todense\")\n                     else lrdata[:, lr_top].X, index=lrdata.obs_names, columns=lr_top)\ncorr = pd.DataFrame({ct: local.corrwith(abund[ct]) for ct in abund.columns}).round(2)\ncorr.to_csv(\"lr_local_vs_abundance.csv\")\nprint(corr.apply(lambda r: \", \".join(f\"{k} {v}\" for k, v in r.nlargest(3).items()), axis=1))\n```\n\n### Recipe: Are Ligand and Receptor Actually Expressed?\n\nAggregated scores can hide that only a few cells express a partner:\n\n```python\ndef frac_expr(cell_type, gene):\n    if gene not in adata.var_names:\n        return np.nan\n    x = adata[adata.obs[CELL_TYPE_KEY] == cell_type, gene].X\n    x = x.toarray() if hasattr(x, \"toarray\") else np.asarray(x)\n    return float((x > 0).mean())\n\nev_top = ev.head(30).copy()\nev_top[\"ligand_frac_sender\"] = [frac_expr(s, l.split(\"_\")[0]) for s, l in zip(ev_top[\"sender\"], ev_top[\"ligand\"])]\nev_top[\"receptor_frac_receiver\"] = [frac_expr(r, rc.split(\"_\")[0]) for r, rc in zip(ev_top[\"receiver\"], ev_top[\"receptor\"])]\nprint(ev_top[[\"sender\", \"receiver\", \"ligand\", \"receptor\", \"ligand_frac_sender\", \"receptor_frac_receiver\"]].round(2))\n```\n\n## Expected Outputs\n\n- `liana_results.csv`, `liana_dotplot.png` - LR ranking per sender-receiver pair\n- `nhood_enrichment_z.csv`, `nhood_enrichment.png` - cell type co-location z-scores\n- `lr_adjacent_pairs.csv` - top interactions whose cell types are neighbours\n- `liana_bandwidth.png`, `liana_bivariate_summary.csv`, `liana_bivariate.h5ad` - local LR scores\n- `lr_candidate_evidence.csv`, `lr_candidates.png` - candidates with pathway and evidence class\n- CellPhoneDB: `ref_cache\u002Fcellphonedb\u002Fv5.0.0\u002Fcellphonedb.zip` (cached database), `cellphonedb\u002Fmeta.tsv` and `counts.h5ad` (inputs), `cellphonedb\u002Fstatistical_analysis_*_stat.txt` (means, pvalues, significant_means, deconvoluted, interaction_scores), `cellphonedb\u002Fsignificant_long.csv` (read by Step 3)\n- LIANA multi-sample \u002F MISTy: `tensor.factors` (context, LR, sender, receiver loadings), `misty_target_metrics.csv`, `misty_interactions.csv`\n- Literature: `pubmed_n` and `final_class` columns added to `lr_candidate_evidence.csv`\n\n## Troubleshooting\n\n| Problem | Cause | Fix |\n|---|---|---|\n| Very few results | Targeted panel lacks LR genes | Report coverage (Step 1); do not extrapolate |\n| `KeyError` on cell type | Column not categorical, or label spelling differs between results and `adata` | `astype(\"category\")`; use the same label column for inference and Step 4 |\n| All local scores near 0 | Bandwidth smaller than spot\u002Fcell spacing | Re-read the `query_bandwidth` table; raise `BANDWIDTH` |\n| Mouse genes not matched | Human resource | `RESOURCE = \"mouseconsensus\"` |\n| Results dominated by housekeeping-like pairs | Data was z-scored or not normalised | Use normalised (log) expression |\n| Slow permutations | Many cells | Lower `n_perms` for exploration, report it |\n| `AttributeError: module 'liana' has no attribute 'pp'` \u002F `ms` | Older liana | Step 5 falls back to `li.ut`; elsewhere use `li.ut.*` \u002F `li.multi.*`, or upgrade liana |\n| Pathway query returns nothing | Pathway genes not on the panel, or mouse symbols | Check `adata.var_names`; `genes` are upper-cased for matching |\n| Almost no interactions | Mouse or Ensembl IDs in `var_names` | Map to human HGNC symbols (ortholog step of the CellPhoneDB route) |\n| `Some clusters\u002Fcell_types in microenvironments file are not present in metadata` | Label mismatch between files | Build both files from the same cell type column |\n| Very slow \u002F out of memory | Many cells | `subsampling=True` with `subsampling_num_cells`; raise `threads` |\n| `download_database` fails | No network access to GitHub | Download `cellphonedb.zip` from the release page manually into `CPDB_DIR` |\n| Pair columns missing a cell type | Type below `threshold` for all genes or absent from microenvs | Check `value_counts`; lower `MIN_FRAC` |\n| Tensor factorization fails | Too few samples or cell types missing in many samples | `how=\"outer_cells\"`, fix `rank` low (3-4), add samples |\n| MISTy juxta view error | squidpy missing | `pixi add --pypi squidpy` |\n| `KeyError` aligning compositions | Spot IDs differ between files | Align on `adata.obs_names` before `obsm` |\n| PubMed HTTP 429 | Too many requests | Increase `time.sleep`; lower the number of pairs |\n| Literature counts inflated | Gene symbol is a common word (e.g. `MET`, `KIT`) | Add `CONTEXT` or check abstracts |\n| Complex pairs never match | CellPhoneDB complex names instead of genes | Use the subunit `genes` from Step 3 |\n\n## Bundled Resources\n\nMerged from four former skills: `spatial-transcriptomics-cell-cell-communication`\n(Steps 1-2, 4-5, recipes), `cellphonedb-cell-cell-interaction` (Route: CellPhoneDB\nv5 Statistics; its adjacency recipe is Step 4), `liana-spatial-cell-cell-communication`\n(Steps 1-2 and 5, Route: LIANA Multi-sample) and\n`spatial-single-cell-ligand-receptor-discovery` (Steps 3, 4, 6, expression-fraction\nrecipe, Route: Literature Evidence).\n\n## Related Skills\n\n- `spatial-transcriptomics-cell-type-annotation` - labels for Steps 2-4\n- `spatial-transcriptomics-deconvolution-cell2location` - abundances for Visium\n- `spatial-mapping-tangram` - per-spot proportions or per-nucleus labels from a reference\n- `spatial-domain-detection` - region labels for CellPhoneDB microenvironments\n- `spatial-transcriptomics-analysis-squidpy` - further spatial statistics and squidpy `ligrec`\n\n## References\n\n- Dimitrov et al. (2024) LIANA+, Nature Cell Biology: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41556-024-01469-w\n- LIANA+ documentation: https:\u002F\u002Fliana.readthedocs.io\u002F\n- Troule et al. (2025) CellPhoneDB v5, Nature Protocols: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41596-024-01137-1\n- Palla et al. (2022) Squidpy, Nature Methods: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41592-021-01358-2\n- squidpy documentation: https:\u002F\u002Fsquidpy.readthedocs.io\u002Fen\u002Fstable\u002F\n","# Spatial Cell-Cell Communication\n\n## Overview\n\nExpression-based ligand-receptor (LR) inference ranks pairs that *could*\nsignal; spatial data adds whether sender and receiver actually sit next to\neach other. This skill runs one inference (LIANA consensus by default, or\nCellPhoneDB statistics), puts the result into one table, keeps interactions\nwhose cell types are spatial neighbours, scores LR co-expression at each\nlocation, and narrows the table to the user's question with an evidence class\nper candidate. Expression of both partners never proves signalling: every\nresult is a candidate.\n\n| Question | Route |\n|---|---|\n| Which LR pairs between my cell types, and are the types neighbours | Workflow Steps 1-6 |\n| Permutation p-values per pair, DEG-driven or microenvironment-restricted tests | Route: CellPhoneDB v5 Statistics, in place of Step 2 |\n| Where on the tissue an LR pair is co-expressed (labels not needed) | Step 5; p-value\u002Fcategory layers in Route: LIANA Multi-sample |\n| Communication differences across samples or conditions | Route: LIANA Multi-sample (by-sample ranking, Tensor-cell2cell) |\n| What in the neighbourhood explains cell type composition | Route: LIANA Multi-sample (MISTy) |\n| Literature support and which candidates to validate | After Step 6, Route: Literature Evidence |\n\nAll routes are in `## Task Routes` below the Workflow.\n\n## When to Use\n\n- Finding which annotated cell types may signal to each other in a spatial section\n- Separating interactions between neighbouring cell types from those between distant ones\n- Testing which LR pairs are specific to a sender-receiver pair with CellPhoneDB p-values\n- Mapping where on the tissue a ligand and its receptor are co-expressed, also on Visium spots\n- Asking about one pathway family (immune checkpoints, chemokines, Notch, Wnt, TGF-beta) after inference\n- Comparing communication programs across samples or conditions\n- For neighbourhood enrichment or co-occurrence alone, without LR pairs, use `spatial-transcriptomics-analysis-squidpy`\n\n## Prerequisites\n\n- **Input**: log-normalised expression in `X` (not z-scored) and `obsm[\"spatial\"]`\n- **Labels**: a cell type column in `obs` for Steps 2-4 and 6\n  (`spatial-transcriptomics-cell-type-annotation`). Visium spots have no labels:\n  Step 5 works without them; Steps 2-4 need a deconvolution first\n  (`spatial-transcriptomics-deconvolution-cell2location`)\n- **Genes**: gene symbols; CellPhoneDB is human-only (mouse via orthologs, see its reference)\n- **Python packages**: `liana`, `squidpy`, `scanpy`; `cellphonedb`, `cell2cell` only for their routes\n\n```bash\n# Install only what `import` reports missing. `--pypi` keeps the env's scanpy\u002Fnumba\n# stack; a conda add can swap it and bare pip can shadow it.\npixi add --pypi liana squidpy scanpy\n```\n\n## Pre-flight Interview\n\n```yaml\ndecisions:\n  - id: D1\n    param: CELL_TYPE_KEY\n    kind: required\n    source: data\n    ask: \"Which column holds the cell types whose communication you want to study?\"\n    default: null\n\n  - id: D2\n    param: RESOURCE\n    kind: required\n    source: data\n    ask: \"The gene symbols look \u003Chuman\u002Fmouse>: use the \u003Chuman\u002Fmouse> ligand-receptor database?\"\n    default: \"consensus for human symbols, mouseconsensus for mouse symbols\"\n\n  - id: D3\n    param: METHOD\n    kind: required\n    source: user\n    ask: \"Rank interactions by agreement across several methods (LIANA consensus, recommended), or do you need CellPhoneDB permutation p-values per pair (slower, human symbols)?\"\n    default: \"LIANA consensus\"\n\n  - id: D4\n    param: QUERY\n    kind: optional\n    source: user\n    ask: \"Is there a pathway (immune checkpoints, chemokines, growth factors, Notch, Wnt, TGF-beta) or a sender -> receiver direction you care about?\"\n    default: \"all pathways and all cell type pairs\"\n\n  - id: D5\n    param: SAMPLE_KEY\n    kind: required\n    source: data\n    skip_if: \"the data holds a single sample\"\n    ask: \"Which column identifies the samples, and which one the condition to compare?\"\n    default: null\n\n  - id: D6\n    param: expr_prop\n    kind: optional\n    source: user\n    ask: \"Minimum fraction of a cell type that must express each partner gene?\"\n    default: \"0.1\"\n\n  - id: D7\n    param: NEIGHBOUR_Z\n    kind: optional\n    source: user\n    ask: \"How strongly must two cell types co-locate to count as neighbours?\"\n    default: \"neighbourhood z > 2 over 15 nearest neighbours\"\n\n  - id: D8\n    param: BANDWIDTH\n    kind: optional_conditional\n    source: data\n    ask: \"The coordinates are in \u003Cmicrons\u002Fpixels>; how wide should the local neighbourhood be?\"\n    default: \"from li.pp.query_bandwidth: a few to tens of neighbours per location\"\n\n  - id: D9\n    param: REGION_KEY\n    kind: optional_conditional\n    source: data\n    depends_on: [D3]\n    skip_if: \"METHOD is LIANA consensus\"\n    ask: \"Should CellPhoneDB only test cell types that share a tissue region? If so, which region\u002Fniche column?\"\n    default: \"no restriction\"\n\n  - id: D10\n    param: n_perms\n    kind: optional\n    source: user\n    ask: \"How many permutations for p-values?\"\n    default: \"1000 for neighbourhood\u002FCellPhoneDB tests, 100 for local LR scores\"\n```\n\nAsk D1-D3 together, with D5 when `obs` has a sample-like column. Offer the\n`obs` columns that look like cell type labels for D1; if none exist on\nsingle-cell-resolution data, stop and annotate first. On Visium without a\ndeconvolution, say that only Step 5 can run.\n\n## Workflow\n\n1. Inputs, organism and panel coverage\n2. Rank LR pairs between cell types\n3. Harmonise results into one table\n4. Keep spatially adjacent pairs\n5. Local LR co-expression on the tissue\n6. Focus on the question and classify candidates\n\n### Step 1: Inputs and Panel Coverage\n\n```python\nimport liana as li\nimport numpy as np\nimport pandas as pd\nimport scanpy as sc\n\nadata = sc.read_h5ad(\"celltype_annotated.h5ad\")\nCELL_TYPE_KEY = \"cell_type\"                         # D1\nadata.obs[CELL_TYPE_KEY] = adata.obs[CELL_TYPE_KEY].astype(\"category\")\nprint(adata.obs[CELL_TYPE_KEY].value_counts())\n\nhead = adata.var_names[:200]                         # mouse \"Actb\" vs human \"ACTB\"\nn_mouse = sum(len(g) > 1 and g[0].isupper() and g[1:].islower() for g in head)\nRESOURCE = \"mouseconsensus\" if n_mouse > len(head) \u002F 2 else \"consensus\"   # D2\nprint(f\"resource: {RESOURCE}; max X = {adata.X.max():.1f} (expect \u003C ~15 for log data)\")\n\nresource = li.rs.select_resource(RESOURCE)\ngenes = set(adata.var_names)\ndef present(complex_):\n    return all(g in genes for g in complex_.split(\"_\"))\ncovered = resource[resource[\"ligand\"].map(present) & resource[\"receptor\"].map(present)]\nprint(f\"LR pairs measurable: {len(covered)} of {len(resource)}\")\n```\n\nA targeted panel (Xenium ~400 genes) measures only a small share of the\nresource. Report that coverage with the results: absent pairs were not\nmeasured, not ruled out.\n\n### Step 2: Rank LR Pairs Between Cell Types\n\nLIANA consensus (`magnitude_rank`, `specificity_rank`; lower = stronger,\naggregated over CellPhoneDB, CellChat, NATMI, Connectome and others). For\nCellPhoneDB statistics, run Route: CellPhoneDB v5 Statistics instead and continue\nat Step 3 with `SOURCE = \"cellphonedb\"`.\n\n```python\nli.mt.rank_aggregate(adata, groupby=CELL_TYPE_KEY, resource_name=RESOURCE,\n                     expr_prop=0.1, use_raw=False, key_added=\"liana_res\", verbose=True)\nres = adata.uns[\"liana_res\"]\nres.to_csv(\"liana_results.csv\", index=False)\nprint(res.sort_values(\"magnitude_rank\").head(15)[\n    [\"source\", \"target\", \"ligand_complex\", \"receptor_complex\", \"magnitude_rank\", \"specificity_rank\"]])\n```\n\n```python\np = li.pl.dotplot(adata=adata, colour=\"magnitude_rank\", size=\"specificity_rank\",\n                  inverse_colour=True, inverse_size=True, top_n=20,\n                  orderby=\"magnitude_rank\", orderby_ascending=True, figure_size=(10, 8),\n                  return_fig=True)          # restrict with source_labels=[...], target_labels=[...]\np.save(\"liana_dotplot.png\", dpi=150)\n```\n\n| Column | Meaning |\n|---|---|\n| `source` \u002F `target` | Sender (ligand) \u002F receiver (receptor) cell type |\n| `ligand_complex` \u002F `receptor_complex` | Genes; complexes joined by `_` |\n| `lr_means` | Mean of ligand and receptor expression |\n| `magnitude_rank` \u002F `specificity_rank` | Consensus ranks of strength \u002F cell type specificity |\n\n### Step 3: Harmonise Results\n\nOne row per (sender, receiver, ligand, receptor) with a score and a p-value\nor rank, from either tool, so Steps 4 and 6 run the same way:\n\n```python\nSOURCE = \"liana\"            # or \"cellphonedb\" (significant_long.csv from its reference)\nTOP_RANK = 0.05             # LIANA magnitude_rank cutoff for \"top\" interactions\n\nif SOURCE == \"liana\":\n    r = res[res[\"magnitude_rank\"] \u003C= TOP_RANK]\n    lr = pd.DataFrame({\n        \"sender\": r[\"source\"], \"receiver\": r[\"target\"],\n        \"ligand\": r[\"ligand_complex\"], \"receptor\": r[\"receptor_complex\"],\n        \"score\": r[\"lr_means\"], \"p_or_rank\": r[\"magnitude_rank\"], \"specificity\": r[\"specificity_rank\"]})\nelse:\n    r = pd.read_csv(\"cellphonedb\u002Fsignificant_long.csv\")\n    r = r[r[\"pval\"] \u003C 0.05]\n    for c in (\"partner_a\", \"partner_b\"):\n        r[c] = r[c].str.replace(r\"^(simple|complex):\", \"\", regex=True)\n    swap = r[\"receptor_a\"].astype(bool) & ~r[\"receptor_b\"].astype(bool)   # orient ligand -> receptor\n    lr = pd.DataFrame({\n        \"sender\": np.where(swap, r[\"cell_b\"], r[\"cell_a\"]), \"receiver\": np.where(swap, r[\"cell_a\"], r[\"cell_b\"]),\n        \"ligand\": np.where(swap, r[\"partner_b\"], r[\"partner_a\"]),\n        \"receptor\": np.where(swap, r[\"partner_a\"], r[\"partner_b\"]),\n        \"score\": r[\"mean\"], \"p_or_rank\": r[\"pval\"], \"specificity\": r.get(\"score\")})\n\nlr[\"genes\"] = (lr[\"ligand\"] + \"_\" + lr[\"receptor\"]).str.upper().str.split(\"_\").map(set)\nif SOURCE == \"cellphonedb\" and \"genes\" in r:      # subunit genes of complexes (saved as \"{'ITGA4', ...}\")\n    import ast\n    lr[\"genes\"] = [g | (ast.literal_eval(x) if isinstance(x, str) and x.startswith(\"{\") else set())\n                   for g, x in zip(lr[\"genes\"], r[\"genes\"])]\nlr = lr.reset_index(drop=True)\nprint(f\"{len(lr)} rows, {lr[['ligand', 'receptor']].drop_duplicates().shape[0]} LR pairs\")\n```\n\nFor LIANA lower `p_or_rank` \u002F `specificity` is better; for CellPhoneDB\n`p_or_rank` is a p-value and `specificity` the 0-100 interaction score\n(higher is better). CellPhoneDB complex names (e.g. `integrin_a4b1_complex`)\nare not symbols; the code adds their subunit genes.\n\n### Step 4: Keep Spatially Adjacent Pairs\n\n```python\nimport squidpy as sq\n\nsq.gr.spatial_neighbors(adata, coord_type=\"generic\", n_neighs=15)   # Visium: coord_type=\"grid\", n_rings=1\nsq.gr.nhood_enrichment(adata, cluster_key=CELL_TYPE_KEY, n_perms=1000, seed=0)\ncats = adata.obs[CELL_TYPE_KEY].cat.categories\nz = pd.DataFrame(adata.uns[f\"{CELL_TYPE_KEY}_nhood_enrichment\"][\"zscore\"], index=cats, columns=cats)\nz.to_csv(\"nhood_enrichment_z.csv\")\n\nNEIGHBOUR_Z = 2                                                     # D7\nlr[\"neighbour_z\"] = [z.loc[s, t] if s in z.index and t in z.columns else np.nan\n                     for s, t in zip(lr[\"sender\"], lr[\"receiver\"])]\nlr[\"autocrine\"] = lr[\"sender\"] == lr[\"receiver\"]\nadjacent = lr[(lr[\"neighbour_z\"] > NEIGHBOUR_Z) | lr[\"autocrine\"]].sort_values(\"p_or_rank\")\nadjacent.drop(columns=[\"genes\"]).to_csv(\"lr_adjacent_pairs.csv\", index=False)\nprint(f\"{len(adjacent)} of {len(lr)} top interactions are between neighbouring (or the same) cell types\")\n```\n\nAutocrine pairs are always adjacent; read them separately. On Visium spots\nthe label-based test is coarse; prefer Step 5 there. Show the co-location\nmatrix the filter is based on:\n\n```python\nsq.pl.nhood_enrichment(adata, cluster_key=CELL_TYPE_KEY, cmap=\"coolwarm\", vmin=-10, vmax=10,\n                       figsize=(7, 6), save=\"nhood_enrichment.png\")\n```\n\n### Step 5: Local LR Co-expression on the Tissue\n\nScores each LR pair at every location, so it also works on Visium spots\nwithout labels. Pick the bandwidth from the coordinate scale first:\n\n```python\nspatial_neighbors = li.pp.spatial_neighbors if hasattr(li, \"pp\") else li.ut.spatial_neighbors  # li.ut in older liana\nplot, bw_table = li.pp.query_bandwidth(coordinates=adata.obsm[\"spatial\"], start=0, end=500, interval_n=20)\nplot.save(\"liana_bandwidth.png\", dpi=150)\nprint(bw_table.head(10))      # average neighbours per bandwidth: aim for a few to tens\n\nBANDWIDTH = 100               # D8; coordinate units: ~50-100 um Xenium; Visium full-res px ~2-3 spot spacings\nspatial_neighbors(adata, bandwidth=BANDWIDTH, cutoff=0.1, kernel=\"gaussian\", set_diag=True)\nlrdata = li.mt.bivariate(adata, resource_name=RESOURCE, local_name=\"cosine\", global_name=\"morans\",\n                         n_perms=100, mask_negatives=False, add_categories=True, nz_prop=0.1,\n                         use_raw=False, verbose=True)\nsummary = lrdata.var.sort_values(\"morans\", ascending=False)\nsummary.to_csv(\"liana_bivariate_summary.csv\")\nlrdata.write_h5ad(\"liana_bivariate.h5ad\")\nprint(summary.head(10))\nsc.pl.embedding(lrdata, basis=\"spatial\", color=summary.index[:4].tolist(), cmap=\"coolwarm\", save=\"_lr_local.png\")\n```\n\n`var[\"morans\"]` is the global spatial co-pattern of ligand and receptor; the\nper-location p-values (`layers[\"pvals\"]`) and categories (`layers[\"cats\"]`:\nboth high \u002F one high \u002F both low) are read in Route: LIANA Multi-sample.\n\n### Step 6: Focus and Classify Candidates\n\nNarrow the table to the user's question (D4) and give each candidate an\nevidence class. Matching is per gene symbol, so `CD4` does not hit `CD40`.\n\n```python\nPATHWAYS = {\n    \"immune_checkpoint\": [\"PDCD1\", \"CD274\", \"PDCD1LG2\", \"CTLA4\", \"CD28\", \"CD80\", \"CD86\",\n                          \"LAG3\", \"HAVCR2\", \"LGALS9\", \"TIGIT\", \"PVR\", \"NECTIN2\"],\n    \"chemokine\": [\"CXCL*\", \"CCL*\", \"CX3CL1\", \"XCL*\", \"CXCR*\", \"CCR*\", \"CX3CR1\", \"XCR1\", \"ACKR*\"],\n    \"growth_factor\": [\"EGF\", \"EGFR\", \"ERBB*\", \"VEGF*\", \"KDR\", \"FLT1\", \"FLT4\", \"FGF*\", \"FGFR*\",\n                      \"PDGF*\", \"HGF\", \"MET\", \"IGF1\", \"IGF1R\"],\n    \"notch\": [\"NOTCH*\", \"JAG1\", \"JAG2\", \"DLL1\", \"DLL3\", \"DLL4\"],\n    \"wnt\": [\"WNT*\", \"FZD*\", \"LRP5\", \"LRP6\", \"RSPO*\", \"LGR*\"],\n    \"tgfb_bmp\": [\"TGFB*\", \"TGFBR*\", \"BMP*\", \"BMPR*\", \"ACVR*\", \"GDF*\"],\n}\ndef matches(genes, patterns):\n    return any(g.startswith(p[:-1]) if p.endswith(\"*\") else g == p for g in genes for p in patterns)\nfor name, pats in PATHWAYS.items():\n    lr[name] = lr[\"genes\"].map(lambda g: matches(g, pats))\nlr[\"pathway\"] = lr[list(PATHWAYS)].apply(lambda row: \",\".join(k for k, v in row.items() if v), axis=1)\n\nQUERY = list(PATHWAYS)                               # D4, e.g. [\"immune_checkpoint\", \"chemokine\"]\nSENDERS, RECEIVERS = None, None                      # e.g. {\"Tumor cell\"}, {\"T cell\"}\nq = lr[lr[QUERY].any(axis=1)]\nif SENDERS: q = q[q[\"sender\"].isin(SENDERS)]\nif RECEIVERS: q = q[q[\"receiver\"].isin(RECEIVERS)]\n\nCONTACT = {\"CD274\", \"PDCD1\", \"PDCD1LG2\", \"CTLA4\", \"CD28\", \"CD80\", \"CD86\", \"JAG1\", \"JAG2\",\n           \"DLL1\", \"DLL3\", \"DLL4\", \"NOTCH1\", \"NOTCH2\", \"NOTCH3\", \"NOTCH4\", \"TIGIT\", \"PVR\", \"NECTIN2\"}\ndef evidence_class(row):\n    if pd.isna(row[\"neighbour_z\"]):\n        return \"no spatial test\"\n    if row[\"neighbour_z\"] > NEIGHBOUR_Z or row[\"autocrine\"]:\n        return \"co-located\"\n    return \"unlikely (contact, not co-located)\" if row[\"ligand\"].split(\"_\")[0] in CONTACT else \"possible paracrine\"\nq = q.assign(evidence_class=q.apply(evidence_class, axis=1))\nev = q.drop(columns=[\"genes\"]).sort_values([\"p_or_rank\", \"score\"], ascending=[True, False])\nev.to_csv(\"lr_candidate_evidence.csv\", index=False)\nprint(ev.groupby([\"pathway\", \"evidence_class\"]).size())\n```\n\n`CONTACT` is a starting list of membrane-bound partners; extend it for the\npathways in `QUERY`. Plot the top candidates:\n\n```python\nimport matplotlib.pyplot as plt\n\ntop = ev.head(30).copy()\ntop[\"lr\"] = top[\"ligand\"] + \" -> \" + top[\"receptor\"]\ntop[\"pair\"] = top[\"sender\"].astype(str) + \" -> \" + top[\"receiver\"].astype(str)\nfig, ax = plt.subplots(figsize=(max(8, 0.4 * top[\"pair\"].nunique()), max(6, 0.3 * top[\"lr\"].nunique())))\ns = ax.scatter(top[\"pair\"], top[\"lr\"], c=top[\"neighbour_z\"], cmap=\"coolwarm\", vmin=-5, vmax=5,\n               s=30 + 200 * top[\"score\"] \u002F top[\"score\"].max())\nplt.colorbar(s, label=\"neighbourhood z (sender-receiver)\"); plt.xticks(rotation=90)\nplt.tight_layout(); plt.savefig(\"lr_candidates.png\", dpi=150); plt.close()\n```\n\n| Evidence pattern | Interpretation |\n|---|---|\n| Top-ranked \u002F significant, co-located | Strong candidate; check literature (Route: Literature Evidence) |\n| Top-ranked, not co-located, secreted ligand | Possible paracrine signal; weaker |\n| Top-ranked, not co-located, contact-dependent | Unlikely in this tissue |\n| Only one partner above `expr_prop` | Not supported |\n\nState validation routes (spatial protein staining, receptor blocking,\nperturbation) for the top candidates.\n\n## Task Routes\n\nEach route continues the Workflow session (same variable names). Only the calls\nthat differ from the Workflow, or that fail silently when written another way,\nare shown.\n\n### Route: CellPhoneDB v5 Statistics\n\nScores each curated LR pair, including multi-subunit complexes, for every\nordered pair of cell types; the statistical method tests specificity by\nshuffling labels. Run it in place of Step 2, write `cellphonedb\u002Fsignificant_long.csv`,\nthen continue at Step 3 with `SOURCE = \"cellphonedb\"`. Install\n`pixi add --pypi cellphonedb`.\n\n| Method | Call | Use when |\n|---|---|---|\n| Simple | `cpdb_analysis_method` | Quick look, no statistics |\n| Statistical | `cpdb_statistical_analysis_method` | Discovery; permutation p-values |\n| DEG-based | `cpdb_degs_analysis_method` | Interactions driven by genes up in one cell type; result has `relevant_interactions` instead of `pvalues` |\n\nInputs and gotchas:\n\n- Database: without GitHub access, download `cellphonedb.zip` from the\n  `ventolab\u002Fcellphonedb-data` releases by hand into `CPDB_DIR`.\n- `counts.h5ad` holds normalised (log) expression, not z-scored, with human HGNC\n  symbols. Cell type names must not contain `|`, the result separator.\n- Mouse: map symbols 1:1 to human first:\n  `li.rs.get_hcop_orthologs(target_organism=\"mouse\", columns=[\"human_symbol\", \"mouse_symbol\"], min_evidence=3)`,\n  keep rows unique on both columns, rename `var_names`.\n- Microenvironments (D9): a `cell_type` \u002F `microenvironment` table built from a\n  region column, a type counting as present above ~2% of the region's cells;\n  only pairs of co-located types are tested.\n- DEG method: `degs.tsv` with `cluster` \u002F `gene` columns of up-regulated genes\n  (e.g. `rank_genes_groups`, adj p \u003C 0.05, logFC > 0.25).\n\n```python\nimport os\nfrom cellphonedb.src.core.methods import cpdb_statistical_analysis_method\nfrom cellphonedb.utils import db_utils\n\nCPDB_DIR = os.path.abspath(\"ref_cache\u002Fcellphonedb\u002Fv5.0.0\")\nCPDB_ZIP = os.path.join(CPDB_DIR, \"cellphonedb.zip\")\nif not os.path.exists(CPDB_ZIP):\n    os.makedirs(CPDB_DIR, exist_ok=True)\n    db_utils.download_database(CPDB_DIR, \"v5.0.0\")\nOUT = \"cellphonedb\"\nos.makedirs(OUT, exist_ok=True)\nsc.AnnData(X=adata.X, obs=pd.DataFrame(index=adata.obs_names),\n           var=pd.DataFrame(index=adata.var_names)).write_h5ad(f\"{OUT}\u002Fcounts.h5ad\")\npd.DataFrame({\"barcode_sample\": adata.obs_names, \"cell_type\": adata.obs[CELL_TYPE_KEY].astype(str).values}\n             ).to_csv(f\"{OUT}\u002Fmeta.tsv\", sep=\"\\t\", index=False)\n\nres = cpdb_statistical_analysis_method.call(\n    cpdb_file_path=CPDB_ZIP, meta_file_path=f\"{OUT}\u002Fmeta.tsv\", counts_file_path=f\"{OUT}\u002Fcounts.h5ad\",\n    counts_data=\"hgnc_symbol\", microenvs_file_path=None,      # or f\"{OUT}\u002Fmicroenvs.tsv\"\n    score_interactions=True, iterations=1000, threshold=0.1, threads=4, debug_seed=42, pvalue=0.05,\n    subsampling=False,             # >~100k cells: True + subsampling_num_cells, subsampling_log=False\n    output_path=OUT, output_suffix=\"stat\")\n```\n\nLong table read by Step 3 (`cell_a` expresses `partner_a`; Step 3 orients\nligand -> receptor from `receptor_a` \u002F `receptor_b`):\n\n```python\nsig = res[\"significant_means\"]\nlabels = set(adata.obs[CELL_TYPE_KEY].astype(str))\npair_cols = [c for c in sig.columns if c.count(\"|\") == 1 and set(c.split(\"|\")) \u003C= labels]\nmeta_cols = [c for c in [\"id_cp_interaction\", \"interacting_pair\", \"partner_a\", \"partner_b\", \"secreted\",\n                         \"receptor_a\", \"receptor_b\"] if c in sig.columns]\nlong = sig.melt(id_vars=meta_cols, value_vars=pair_cols, var_name=\"pair\", value_name=\"mean\").dropna(subset=[\"mean\"])\npv = res[\"pvalues\"].melt(id_vars=[\"id_cp_interaction\"], value_vars=pair_cols, var_name=\"pair\", value_name=\"pval\")\nlong = long.merge(pv, on=[\"id_cp_interaction\", \"pair\"], how=\"left\")\nlong[[\"cell_a\", \"cell_b\"]] = long[\"pair\"].str.split(\"|\", expand=True)\nif \"interaction_scores\" in res:\n    sc_long = res[\"interaction_scores\"].melt(id_vars=[\"id_cp_interaction\"], value_vars=pair_cols,\n                                             var_name=\"pair\", value_name=\"score\")\n    long = long.merge(sc_long, on=[\"id_cp_interaction\", \"pair\"], how=\"left\")\nlong[\"genes\"] = long[\"id_cp_interaction\"].map(\n    res[\"deconvoluted\"].groupby(\"id_cp_interaction\")[\"gene_name\"].apply(lambda s: set(s.dropna())))\nlong.to_csv(f\"{OUT}\u002Fsignificant_long.csv\", index=False)\n```\n\n| Signal | Meaning |\n|---|---|\n| Low p-value, high mean | Expressed and specific to this cell type pair - strongest candidates |\n| High mean, p >= 0.05 | Broadly expressed; not specific to this pair |\n| High `interaction_scores` (0-100) | Partners specific to these two types relative to all types |\n| `secreted == True` | Ligand can act at a distance; membrane-bound pairs need contact |\n\nTwo conditions: run the statistical method per condition with the same database\nand parameters and compare the significant sets; this is descriptive, since cell\nnumbers per type differ between conditions and change each test's power.\n`ktplotspy` (`plot_cpdb_heatmap`, `plot_cpdb`) draws publication-style figures\nfrom `res`.\n\n### Route: LIANA Multi-sample, Local Score Layers, MISTy\n\nUses `adata`, `CELL_TYPE_KEY`, `RESOURCE`, `BANDWIDTH` and `lrdata` from the\nWorkflow. Functions follow the current `li.pp` \u002F `li.ms` namespaces (older\nreleases: `li.ut` \u002F `li.multi`).\n\n- **Per sample and condition (D5)**: `li.mt.rank_aggregate.by_sample(adata, groupby=CELL_TYPE_KEY,\n  sample_key=SAMPLE_KEY, resource_name=RESOURCE, expr_prop=0.1, use_raw=False, n_perms=None,\n  return_all_lrs=True)`, then pivot `magnitude_rank` by condition (median per\n  interaction). With few samples per condition this is descriptive; no p-values.\n- **Tensor-cell2cell** (`pixi add --pypi cell2cell`, several samples per\n  condition): factorises samples x LR x sender x receiver into patterns. Test a\n  factor's context loadings between conditions across samples (Mann-Whitney)\n  before calling it condition-specific; with few samples, exploratory.\n- **Local score layers** of `lrdata` (Step 5): `X` local score per location\n  (`ligand^receptor`), `layers[\"pvals\"]` per-location permutation p-value,\n  `layers[\"cats\"]` 1 = both high, -1 = one high one low, 0 = both low;\n  `var[\"morans\"]` \u002F `var[\"morans_pvals\"]` global co-pattern. Plot `layer=\"cats\"`\n  to separate true co-localisation (1) from one-partner regions (-1).\n- **MISTy**: for each target (e.g. cell2location proportions) how well it is\n  predicted by the same spot (intra), direct neighbours (juxta) and the wider\n  area (para). `gain_R2` = what the spatial views add over intra; `interactions`\n  with `view` juxta\u002Fpara name the predicting neighbours. Pass\n  `extra=lrdata[:, top_lr]` to ask whether local LR activity predicts\n  composition beyond composition itself.\n- **One method instead of the consensus**: `li.mt.cellphonedb(adata, groupby=CELL_TYPE_KEY,\n  resource_name=RESOURCE, expr_prop=0.1, use_raw=False, n_perms=1000, seed=0,\n  key_added=\"cpdb_res\")` gives `cellphone_pvals` without installing `cellphonedb`.\n\n```python\nimport cell2cell as c2c\nfrom collections import defaultdict\n\nSAMPLE_KEY, CONDITION_KEY = \"sample\", \"condition\"          # D5\nli.mt.rank_aggregate.by_sample(adata, groupby=CELL_TYPE_KEY, sample_key=SAMPLE_KEY, resource_name=RESOURCE,\n                               expr_prop=0.1, use_raw=False, n_perms=None, return_all_lrs=True)\ntensor = li.ms.to_tensor_c2c(adata, sample_key=SAMPLE_KEY, score_key=\"magnitude_rank\", how=\"outer_cells\")\nctx = adata.obs[[SAMPLE_KEY, CONDITION_KEY]].drop_duplicates()\ncontext_dict = defaultdict(lambda: \"Unknown\", zip(ctx[SAMPLE_KEY], ctx[CONDITION_KEY]))\nmeta = c2c.tensor.generate_tensor_metadata(interaction_tensor=tensor, metadata_dicts=[context_dict, None, None, None],\n                                           fill_with_order_elements=True)\ntensor = c2c.analysis.run_tensor_cell2cell_pipeline(\n    tensor, meta, copy_tensor=True, rank=None, tf_optimization=\"regular\", random_state=0, device=\"cpu\",\n    elbow_metric=\"error\", upper_rank=15, tf_init=\"random\", sample_col=\"Element\", group_col=\"Category\",\n    output_fig=False)                         # rank=None: elbow search (slow); or fix e.g. 6\ncontexts = tensor.factors[\"Contexts\"]         # also \"Ligand-Receptor Pairs\", \"Sender Cells\", \"Receiver Cells\"\n```\n\n```python\nfrom liana.method import genericMistyData\nfrom liana.method.sp import LinearModel\n\nadata.obsm[\"compositions\"] = pd.read_csv(\"cell2location_proportions.csv\", index_col=0).loc[adata.obs_names]\ncomps = li.pp.obsm_to_adata(adata, \"compositions\")\nmisty = genericMistyData(intra=comps, cutoff=0.05, bandwidth=BANDWIDTH, n_neighs=6)\nmisty(model=LinearModel, k_cv=10, seed=1337, bypass_intra=False, verbose=True)   # or RandomForestModel\nmisty.uns[\"target_metrics\"].to_csv(\"misty_target_metrics.csv\", index=False)       # intra_R2, multi_R2, gain_R2\nmisty.uns[\"interactions\"].to_csv(\"misty_interactions.csv\", index=False)           # target, predictor, view, importances\n```\n\n### Route: Literature Evidence for Candidates\n\nAdds PubMed support to the Step 6 candidate table (`ev`). NCBI E-utilities need\nno key below 3 requests per second; cap the number of pairs queried. The judgment\nis made from the evidence table, not by the code.\n\n```python\nimport time\nimport requests\n\nEUTILS = \"https:\u002F\u002Feutils.ncbi.nlm.nih.gov\u002Fentrez\u002Feutils\u002Fesearch.fcgi\"\nCONTEXT = \"\"        # optional, e.g. \"lung cancer\" to count context-specific co-mentions\n\ndef pubmed_count(ligand, receptor):\n    a, b = ligand.split(\"_\")[0], receptor.split(\"_\")[0]   # first subunit for complexes\n    term = f\"{a}[tiab] AND {b}[tiab]\" + (f\" AND ({CONTEXT})\" if CONTEXT else \"\")\n    r = requests.get(EUTILS, params={\"db\": \"pubmed\", \"term\": term, \"retmode\": \"json\", \"retmax\": 0}, timeout=30)\n    r.raise_for_status(); time.sleep(0.4)\n    return int(r.json()[\"esearchresult\"][\"count\"])\n\npairs = ev[[\"ligand\", \"receptor\"]].drop_duplicates().head(50)\npairs[\"pubmed_n\"] = [pubmed_count(l, r) for l, r in zip(pairs[\"ligand\"], pairs[\"receptor\"])]\nev = ev.merge(pairs, on=[\"ligand\", \"receptor\"], how=\"left\")\nev[\"final_class\"] = [(\"strong, known\" if (n or 0) > 0 else \"novel, co-located\") if c == \"co-located\" else c\n                     for c, n in zip(ev[\"evidence_class\"], ev[\"pubmed_n\"])]\nev.to_csv(\"lr_candidate_evidence.csv\", index=False)\n```\n\nA zero count with strong statistics is a novelty candidate, not an error. To read\nthe papers, fetch abstracts with `efetch.fcgi?db=pubmed&id=\u003Cids>&rettype=abstract&retmode=text`\nfor the ids of an `esearch` with `retmax=5&sort=relevance`.\n\n## Key Parameters\n\n| Parameter | Default | Effect |\n|---|---|---|\n| `expr_prop` | 0.1 | Min fraction of a cell type expressing each gene |\n| `TOP_RANK` | 0.05 | LIANA `magnitude_rank` cutoff for top interactions |\n| `NEIGHBOUR_Z` | 2 | How strongly two types must co-locate |\n| `n_neighs` | 15 | Size of the spatial neighbourhood (cells) |\n| `BANDWIDTH` | 100 | Spatial kernel for local scores, in coordinate units |\n| `nz_prop` | 0.1 | Min fraction of locations expressing each partner (local scores) |\n| `QUERY` \u002F `SENDERS` \u002F `RECEIVERS` | all | Restricts the candidate table to the question |\n| `threshold` (CellPhoneDB) | 0.1 | Min fraction of a cell type expressing each partner gene |\n| `iterations` (CellPhoneDB) | 1000 | Label permutations; fewer = coarser p-values |\n| `pvalue` | 0.05 | Significance cutoff for `significant_means` |\n| `MIN_FRAC` (microenvs) | 0.02 | Presence cutoff for a type in a region |\n| DEG cutoffs (CellPhoneDB DEG method) | adj p \u003C 0.05, logFC > 0.25 | Which genes count as up-regulated |\n| `subsampling_num_cells` | 1\u002F3 of cells | Geometric sketching size for large datasets |\n| `rank` (Tensor-cell2cell) | None (elbow) | Number of communication patterns; fix 3-6 when the elbow search is slow |\n| `how` (Tensor-cell2cell) | `\"outer_cells\"` | Keep cell types missing in some samples |\n| `bandwidth` (MISTy) | `BANDWIDTH` | Para view kernel width, in coordinate units |\n| `k_cv` (MISTy) | 10 | Cross-validation folds per target |\n| `CONTEXT` | empty | Restricts literature counts to a disease\u002Ftissue |\n| Pairs queried | 50 | Number of PubMed requests |\n| Request delay | 0.4 s | Stays under the 3 requests\u002Fsecond limit |\n\n## Common Recipes\n\n### Recipe: Sender-Receiver Count Map\n\n```python\nimport seaborn as sns\n\ntopn = res[(res[\"magnitude_rank\"] \u003C= 0.05) & (res[\"specificity_rank\"] \u003C= 0.05)]\ncounts = topn.groupby([\"source\", \"target\"]).size().unstack(fill_value=0)\nfig, ax = plt.subplots(figsize=(9, 8))\nsns.heatmap(counts, cmap=\"YlOrRd\", annot=True, fmt=\"d\", ax=ax)\nax.set_xlabel(\"receiver\"); ax.set_ylabel(\"sender\")\nplt.tight_layout(); plt.savefig(\"liana_sender_receiver_counts.png\", dpi=150); plt.close()\n```\n\n### Recipe: Distance Range of One Cell Type Pair\n\nNeighbourhood enrichment is a yes\u002Fno at one scale; co-occurrence shows over\nwhich distance two types stay together:\n\n```python\nANCHOR = \"Macrophage\"                                  # a category of CELL_TYPE_KEY\nsub = adata[np.random.default_rng(0).choice(adata.n_obs, min(adata.n_obs, 20000), replace=False)].copy()\nocc, interval = sq.gr.co_occurrence(sub, cluster_key=CELL_TYPE_KEY, interval=50, copy=True)\nsub_cats = list(sub.obs[CELL_TYPE_KEY].cat.categories)\ndist = interval[1:] if len(interval) == occ.shape[2] + 1 else interval\ncurve = pd.DataFrame(occ[sub_cats.index(ANCHOR)].T, index=np.round(dist, 1), columns=sub_cats)\nprint(curve.iloc[:10].round(2))          # ratio > 1 at short distance = attraction\n```\n\n### Recipe: Visium - Link Local LR Scores to Deconvolved Cell Types\n\n```python\nabund = pd.read_csv(\"cell2location_abundance.csv\", index_col=0).loc[lrdata.obs_names]\nlr_top = summary.index[:20]\nlocal = pd.DataFrame(np.asarray(lrdata[:, lr_top].X.todense()) if hasattr(lrdata.X, \"todense\")\n                     else lrdata[:, lr_top].X, index=lrdata.obs_names, columns=lr_top)\ncorr = pd.DataFrame({ct: local.corrwith(abund[ct]) for ct in abund.columns}).round(2)\ncorr.to_csv(\"lr_local_vs_abundance.csv\")\nprint(corr.apply(lambda r: \", \".join(f\"{k} {v}\" for k, v in r.nlargest(3).items()), axis=1))\n```\n\n### Recipe: Are Ligand and Receptor Actually Expressed?\n\nAggregated scores can hide that only a few cells express a partner:\n\n```python\ndef frac_expr(cell_type, gene):\n    if gene not in adata.var_names:\n        return np.nan\n    x = adata[adata.obs[CELL_TYPE_KEY] == cell_type, gene].X\n    x = x.toarray() if hasattr(x, \"toarray\") else np.asarray(x)\n    return float((x > 0).mean())\n\nev_top = ev.head(30).copy()\nev_top[\"ligand_frac_sender\"] = [frac_expr(s, l.split(\"_\")[0]) for s, l in zip(ev_top[\"sender\"], ev_top[\"ligand\"])]\nev_top[\"receptor_frac_receiver\"] = [frac_expr(r, rc.split(\"_\")[0]) for r, rc in zip(ev_top[\"receiver\"], ev_top[\"receptor\"])]\nprint(ev_top[[\"sender\", \"receiver\", \"ligand\", \"receptor\", \"ligand_frac_sender\", \"receptor_frac_receiver\"]].round(2))\n```\n\n## Expected Outputs\n\n- `liana_results.csv`, `liana_dotplot.png` - LR ranking per sender-receiver pair\n- `nhood_enrichment_z.csv`, `nhood_enrichment.png` - cell type co-location z-scores\n- `lr_adjacent_pairs.csv` - top interactions whose cell types are neighbours\n- `liana_bandwidth.png`, `liana_bivariate_summary.csv`, `liana_bivariate.h5ad` - local LR scores\n- `lr_candidate_evidence.csv`, `lr_candidates.png` - candidates with pathway and evidence class\n- CellPhoneDB: `ref_cache\u002Fcellphonedb\u002Fv5.0.0\u002Fcellphonedb.zip` (cached database), `cellphonedb\u002Fmeta.tsv` and `counts.h5ad` (inputs), `cellphonedb\u002Fstatistical_analysis_*_stat.txt` (means, pvalues, significant_means, deconvoluted, interaction_scores), `cellphonedb\u002Fsignificant_long.csv` (read by Step 3)\n- LIANA multi-sample \u002F MISTy: `tensor.factors` (context, LR, sender, receiver loadings), `misty_target_metrics.csv`, `misty_interactions.csv`\n- Literature: `pubmed_n` and `final_class` columns added to `lr_candidate_evidence.csv`\n\n## Troubleshooting\n\n| Problem | Cause | Fix |\n|---|---|---|\n| Very few results | Targeted panel lacks LR genes | Report coverage (Step 1); do not extrapolate |\n| `KeyError` on cell type | Column not categorical, or label spelling differs between results and `adata` | `astype(\"category\")`; use the same label column for inference and Step 4 |\n| All local scores near 0 | Bandwidth smaller than spot\u002Fcell spacing | Re-read the `query_bandwidth` table; raise `BANDWIDTH` |\n| Mouse genes not matched | Human resource | `RESOURCE = \"mouseconsensus\"` |\n| Results dominated by housekeeping-like pairs | Data was z-scored or not normalised | Use normalised (log) expression |\n| Slow permutations | Many cells | Lower `n_perms` for exploration, report it |\n| `AttributeError: module 'liana' has no attribute 'pp'` \u002F `ms` | Older liana | Step 5 falls back to `li.ut`; elsewhere use `li.ut.*` \u002F `li.multi.*`, or upgrade liana |\n| Pathway query returns nothing | Pathway genes not on the panel, or mouse symbols | Check `adata.var_names`; `genes` are upper-cased for matching |\n| Almost no interactions | Mouse or Ensembl IDs in `var_names` | Map to human HGNC symbols (ortholog step of the CellPhoneDB route) |\n| `Some clusters\u002Fcell_types in microenvironments file are not present in metadata` | Label mismatch between files | Build both files from the same cell type column |\n| Very slow \u002F out of memory | Many cells | `subsampling=True` with `subsampling_num_cells`; raise `threads` |\n| `download_database` fails | No network access to GitHub | Download `cellphonedb.zip` from the release page manually into `CPDB_DIR` |\n| Pair columns missing a cell type | Type below `threshold` for all genes or absent from microenvs | Check `value_counts`; lower `MIN_FRAC` |\n| Tensor factorization fails | Too few samples or cell types missing in many samples | `how=\"outer_cells\"`, fix `rank` low (3-4), add samples |\n| MISTy juxta view error | squidpy missing | `pixi add --pypi squidpy` |\n| `KeyError` aligning compositions | Spot IDs differ between files | Align on `adata.obs_names` before `obsm` |\n| PubMed HTTP 429 | Too many requests | Increase `time.sleep`; lower the number of pairs |\n| Literature counts inflated | Gene symbol is a common word (e.g. `MET`, `KIT`) | Add `CONTEXT` or check abstracts |\n| Complex pairs never match | CellPhoneDB complex names instead of genes | Use the subunit `genes` from Step 3 |\n\n## Bundled Resources\n\nMerged from four former skills: `spatial-transcriptomics-cell-cell-communication`\n(Steps 1-2, 4-5, recipes), `cellphonedb-cell-cell-interaction` (Route: CellPhoneDB\nv5 Statistics; its adjacency recipe is Step 4), `liana-spatial-cell-cell-communication`\n(Steps 1-2 and 5, Route: LIANA Multi-sample) and\n`spatial-single-cell-ligand-receptor-discovery` (Steps 3, 4, 6, expression-fraction\nrecipe, Route: Literature Evidence).\n\n## Related Skills\n\n- `spatial-transcriptomics-cell-type-annotation` - labels for Steps 2-4\n- `spatial-transcriptomics-deconvolution-cell2location` - abundances for Visium\n- `spatial-mapping-tangram` - per-spot proportions or per-nucleus labels from a reference\n- `spatial-domain-detection` - region labels for CellPhoneDB microenvironments\n- `spatial-transcriptomics-analysis-squidpy` - further spatial statistics and squidpy `ligrec`\n\n## References\n\n- Dimitrov et al. (2024) LIANA+, Nature Cell Biology: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41556-024-01469-w\n- LIANA+ documentation: https:\u002F\u002Fliana.readthedocs.io\u002F\n- Troule et al. (2025) CellPhoneDB v5, Nature Protocols: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41596-024-01137-1\n- Palla et al. (2022) Squidpy, Nature Methods: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41592-021-01358-2\n- squidpy documentation: https:\u002F\u002Fsquidpy.readthedocs.io\u002Fen\u002Fstable\u002F\n",{"name":5,"license":15,"description":7},"master","fd76f882a04e445e899d5cfb2732f2105ea054ee","skills\u002Fawesome-skills\u002Fspatial-transcriptomics-cell-cell-communication",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 spatial-transcriptomics-cell-cell-communication",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill spatial-transcriptomics-cell-cell-communication",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill spatial-transcriptomics-cell-cell-communication","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fspatial-transcriptomics-cell-cell-communication\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",[],[]]