[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M76EWRJ28YSCWK9V0VFNWG4X":3,"skill-same:01M76EWRJ28YSCWK9V0VFNWG4X":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},"01M76EWRJ28YSCWK9V0VFNWG4X","spatial-transcriptomics-deconvolution-cell2location",null,"Visium and other spot-based spatial transcriptomics (Slide-seq, ST) cell type deconvolution with cell2location: load Space Ranger output, get a tissue-matched scRNA-seq reference from CELLxGENE, learn cell type signatures, estimate cell type abundance per spot with posterior uncertainty, and check the maps against marker genes. Default route for 'annotate cell types' on Visium when a GPU is available. Limits: needs a tissue- and state-matched reference; the default 30000 epochs take hours on CPU, so without a GPU it runs only with fewer epochs (exploratory maps) and can exceed one execution call's time limit. For fast per-spot proportions on CPU use spatial-mapping-tangram (clusters mode); for single-cell-resolution data (Xenium, MERFISH, CosMx) use spatial-transcriptomics-cell-type-annotation.","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-deconvolution-cell2location\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: \"spatial-transcriptomics-deconvolution-cell2location\"\ndescription: \"Visium and other spot-based spatial transcriptomics (Slide-seq, ST) cell type deconvolution with cell2location: load Space Ranger output, get a tissue-matched scRNA-seq reference from CELLxGENE, learn cell type signatures, estimate cell type abundance per spot with posterior uncertainty, and check the maps against marker genes. Default route for 'annotate cell types' on Visium when a GPU is available. Limits: needs a tissue- and state-matched reference; the default 30000 epochs take hours on CPU, so without a GPU it runs only with fewer epochs (exploratory maps) and can exceed one execution call's time limit. For fast per-spot proportions on CPU use spatial-mapping-tangram (clusters mode); for single-cell-resolution data (Xenium, MERFISH, CosMx) use spatial-transcriptomics-cell-type-annotation.\"\nlicense: \"CC-BY-4.0\"\n---\n\n# Spot Deconvolution with cell2location\n\n## Overview\n\nEach Visium spot (55 um) holds several cells, so cell types are reported as an\nabundance per spot, not one label per spot. cell2location learns a signature\nper cell type from a scRNA-seq reference, then explains every spot's counts as\na mixture of those signatures. Output: estimated cell counts and proportions\nper spot and type, maps on the tissue, and a marker check of each map.\n\n## When to Use\n\n- Asked to \"annotate cell types\" or \"find where cell types are\" on Visium, Slide-seq or ST data\n- Mapping a published scRNA-seq atlas onto a spot-based section\n- Comparing cell type composition between tissue regions or sections\n- Producing per-spot compositions for downstream niche or communication analysis\n- Getting abundance estimates with posterior uncertainty (5% quantile)\n- Use `spatial-transcriptomics-cell-type-annotation` instead when each observation is one cell (Xenium, MERFISH, CosMx)\n- Use `spatial-mapping-tangram` (constrained deconvolution route) instead when you need single cells placed on segmented nuclei of the histology image\n\n## Prerequisites\n\n- **Input**: Space Ranger output (`filtered_feature_bc_matrix.h5` and the `spatial\u002F` folder) with raw counts\n- **Reference**: scRNA-seq with raw counts and `obs[\"cell_type\"]` (Step 2 fetches one)\n- **Compute**: GPU strongly preferred. On CPU the spatial model (Step 4) needs fewer epochs than the\n  default, chosen by the timing probe there; the reference model (Step 3) takes minutes\n- **Python packages**: `cell2location` (pulls torch, scvi-tools, pyro; large), `scanpy`\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 scanpy cell2location\n```\n\n## Pre-flight Interview\n\n```yaml\ndecisions:\n  - id: D1\n    param: STATE\n    kind: required\n    source: user\n    ask: \"Which tissue is this, and in what state (healthy, or which tumour or disease)?\"\n    default: null\n\n  - id: D2\n    param: referenceSource\n    kind: required\n    source: user\n    ask: \"Do you have a scRNA\u002FsnRNA-seq reference from the same tissue and state (h5ad with raw counts and a cell type column), or should I search public data (CELLxGENE)?\"\n    default: null\n\n  - id: D3\n    param: CELL_TYPE_KEY\n    kind: required\n    source: data\n    depends_on: [D2]\n    ask: \"Which reference column holds the cell types, and at what level: major lineages or fine subtypes?\"\n    default: null\n\n  - id: D4\n    param: COMPUTE_ROUTE\n    kind: required\n    source: user\n    ask: \"Without a GPU, cell2location runs only with fewer training epochs (exploratory maps, still long). Run it that way, or get per-spot proportions quickly with Tangram (clusters mode)?\"\n    default: \"cell2location with MAX_EPOCHS from the Step 4 timing probe, reported as exploratory\"\n\n  - id: D5\n    param: N_CELLS_PER_SPOT\n    kind: required\n    source: user\n    depends_on: [D1]\n    ask: \"About how many nuclei does one spot hold in this tissue? I can use the tutorial value of 30 if you do not know.\"\n    default: \"30\"\n\n  - id: D6\n    param: SAMPLE_KEY\n    kind: required\n    source: data\n    skip_if: \"a single section\"\n    ask: \"There are several sections: fit them in one model (shared cell type signatures, per-section sensitivity) or each on its own?\"\n    default: \"one model with batch_key = section\"\n\n  - id: D7\n    param: DETECTION_ALPHA\n    kind: optional\n    source: user\n    ask: \"Does RNA detection vary strongly across the slide (uneven tissue quality)?\"\n    default: \"20 (uneven detection); 200 when detection is even\"\n\n  - id: D8\n    param: REF_BATCH_KEY\n    kind: optional_conditional\n    source: data\n    depends_on: [D2]\n    ask: \"The reference pools several donors or studies: correct the signatures for that column?\"\n    default: \"batch_key = donor_id when the reference has more than one donor\"\n```\n\nAsk D1, D2 and D4 together, with D6 when there is more than one section. The\ntissue and state come from the user: a sample name will not be found in public\ndatabases, so do not search the web for it. Spot data cannot tell a tumour from\nhealthy tissue reliably; if the user does not know, propose a tissue from the\ntop marker genes and ask them to confirm. If D4 picks Tangram, use\n`spatial-mapping-tangram` with `MODE = \"clusters\"` and the same reference.\n\n## Workflow\n\n### Step 1: Load Visium Output\n\n```python\nimport os\nimport numpy as np\nimport pandas as pd\nimport scanpy as sc\n\nH5 = \"path\u002Fto\u002Ffiltered_feature_bc_matrix.h5\"\nSPATIAL_DIR = \"path\u002Fto\u002Fspatial\"\n\nst = sc.read_10x_h5(H5)\nst.var_names_make_unique()\nif os.path.exists(f\"{SPATIAL_DIR}\u002Ftissue_positions.csv\"):           # Space Ranger >= 2.0\n    pos = pd.read_csv(f\"{SPATIAL_DIR}\u002Ftissue_positions.csv\", index_col=0)\nelse:                                                                  # older, no header\n    pos = pd.read_csv(f\"{SPATIAL_DIR}\u002Ftissue_positions_list.csv\", header=None, index_col=0,\n                      names=[\"barcode\", \"in_tissue\", \"array_row\", \"array_col\",\n                             \"pxl_row_in_fullres\", \"pxl_col_in_fullres\"])\nst.obsm[\"spatial\"] = pos.loc[st.obs_names, [\"pxl_col_in_fullres\", \"pxl_row_in_fullres\"]].to_numpy()\nst = st[:, ~st.var_names.str.startswith(\"MT-\")].copy()   # mito reads are not cell type signal\nprint(st)\nprint(f\"median UMIs\u002Fspot: {np.median(np.asarray(st.X.sum(1)).ravel()):.0f}\")\n```\n\n### Step 2: Get a Reference\n\nUse the tissue and state from D1. Without the user's own reference (D2),\nsearch and download a subsampled CELLxGENE reference with Steps 3-4 of\n`spatial-transcriptomics-cell-type-annotation` (same code, with `GENES = None` and\n`MAX_PER_TYPE = 300` - signatures need every gene), and load it:\n\n```python\nref = sc.read_h5ad(\"reference.h5ad\")      # X = raw counts, obs[\"cell_type\"]\nprint(ref.obs[\"cell_type\"].value_counts())\n```\n\nTypes with fewer than ~20 cells cannot yield a stable signature; Step 3 drops them.\n\n### Step 3: Fit Reference Signatures\n\n```python\nfrom cell2location.models import RegressionModel\nfrom cell2location.utils.filtering import filter_genes\n\nref = ref[ref.obs[\"cell_type\"].map(ref.obs[\"cell_type\"].value_counts()) >= 20].copy()\nselected = filter_genes(ref, cell_count_cutoff=5, cell_percentage_cutoff2=0.03, nonz_mean_cutoff=1.12)\nref = ref[:, selected].copy()\n\nRegressionModel.setup_anndata(ref, labels_key=\"cell_type\")   # add batch_key=\"donor_id\" for multi-donor references\nref_model = RegressionModel(ref)\nref_model.train(max_epochs=250)\nref = ref_model.export_posterior(ref, sample_kwargs={\"num_samples\": 1000, \"batch_size\": 2500})\n\nfactors = ref.uns[\"mod\"][\"factor_names\"]\ninf_aver = ref.varm[\"means_per_cluster_mu_fg\"][[f\"means_per_cluster_mu_fg_{f}\" for f in factors]].copy()\ninf_aver.columns = factors                     # genes x cell types\nprint(inf_aver.shape)\n```\n\n### Step 4: Fit the Spatial Model\n\n```python\nfrom cell2location.models import Cell2location\n\nshared = np.intersect1d(st.var_names, inf_aver.index)\nprint(f\"shared genes: {len(shared)}\")\nst = st[:, shared].copy()\ninf_aver = inf_aver.loc[shared]\n\nN_CELLS_PER_SPOT = 30       # D5; tutorial value; set from nuclei counted on the H&E for this tissue\nDETECTION_ALPHA = 20        # D7; 20 when RNA detection varies across the slide; also try 200\nCell2location.setup_anndata(st)\n```\n\nOn CPU, time a short run on a throwaway model before choosing `MAX_EPOCHS`.\nThe default 30000 epochs often takes hours there, longer than one execution\ncall is allowed to run in many sandboxes:\n\n```python\nimport time\nimport torch\n\nprobe = Cell2location(st, cell_state_df=inf_aver,\n                      N_cells_per_location=N_CELLS_PER_SPOT, detection_alpha=DETECTION_ALPHA)\nt0 = time.time()\nprobe.train(max_epochs=50, batch_size=None, train_size=1)\nsec_per_epoch = (time.time() - t0) \u002F 50\ndel probe\n\nBUDGET_S = 20 * 60          # leave headroom under the per-call time limit\nif torch.cuda.is_available():\n    MAX_EPOCHS = 30000      # tutorial default\nelse:\n    MAX_EPOCHS = int(min(30000, BUDGET_S \u002F sec_per_epoch) \u002F\u002F 1000 * 1000)\nprint(f\"{sec_per_epoch:.2f} s\u002Fepoch -> MAX_EPOCHS = {MAX_EPOCHS} (30000 needs ~{sec_per_epoch * 30000 \u002F 3600:.1f} h)\")\n```\n\nBelow ~3000 epochs the maps are too rough to report; switch to the Tangram\nroute of D4 instead. Then fit:\n\n```python\nst_model = Cell2location(st, cell_state_df=inf_aver,\n                         N_cells_per_location=N_CELLS_PER_SPOT, detection_alpha=DETECTION_ALPHA)\nst_model.train(max_epochs=MAX_EPOCHS, batch_size=None, train_size=1)\n```\n\nReport `MAX_EPOCHS` with the maps; anything below 30000 is exploratory.\n\n### Step 5: Export and Check Abundances\n\n```python\nst = st_model.export_posterior(st, sample_kwargs={\"num_samples\": 1000, \"batch_size\": st_model.adata.n_obs})\nabund = pd.DataFrame(st.obsm[\"q05_cell_abundance_w_sf\"].to_numpy(), index=st.obs_names, columns=factors)\nprop = abund.div(abund.sum(1), axis=0)          # per-spot proportions\nabund.to_csv(\"cell2location_abundance.csv\")\nprop.to_csv(\"cell2location_proportions.csv\")\nst.write_h5ad(\"cell2location_spatial.h5ad\", compression=\"gzip\")\nprint(prop.mean().sort_values(ascending=False).head(10))\n```\n\nPlot the most abundant types on the tissue:\n\n```python\nimport matplotlib.pyplot as plt\n\ntop = prop.mean().nlargest(6).index\nfig, axes = plt.subplots(2, 3, figsize=(15, 10))\nfor ax, ct in zip(axes.flat, top):\n    sc_ = ax.scatter(st.obsm[\"spatial\"][:, 0], st.obsm[\"spatial\"][:, 1], c=abund[ct], s=8, cmap=\"magma\")\n    ax.invert_yaxis(); ax.set_title(ct); ax.axis(\"off\"); fig.colorbar(sc_, ax=ax, shrink=0.6)\nplt.tight_layout(); plt.savefig(\"cell2location_top_types.png\", dpi=150)\n```\n\nCheck each map against a marker the user's biology predicts (for example\nplasma cells vs `JCHAIN`): abundance and marker expression should correlate\nacross spots. A type whose map ignores its own markers is not supported.\n\n```python\nst_norm = st.copy(); sc.pp.normalize_total(st_norm); sc.pp.log1p(st_norm)\nchecks = {\"Plasma cell\": \"JCHAIN\"}             # fill with types present in `factors`\nfor ct, gene in checks.items():\n    if ct in abund and gene in st_norm.var_names:\n        expr = np.asarray(st_norm[:, gene].X.todense()).ravel()\n        print(f\"{ct} vs {gene}: r = {np.corrcoef(abund[ct], expr)[0, 1]:.2f}\")\n```\n\n## Key Parameters\n\n| Parameter | Default | Effect |\n|---|---|---|\n| Reference state | from the user | Healthy vs disease signatures; the most consequential choice |\n| `N_CELLS_PER_SPOT` | 30 | Prior on spot density; scales absolute abundance. Set from histology |\n| `DETECTION_ALPHA` | 20 | Regularises per-spot sensitivity; 200 when detection is even |\n| `MAX_EPOCHS` (spatial) | 30000 | Convergence; fewer epochs = rougher maps |\n| min cells per type | 20 | Types below it are dropped from the reference |\n\n## Common Recipes\n\n### Recipe: Several Sections in One Model\n\nFit all sections together so signatures are shared while sensitivity is\nestimated per section:\n\n```python\nsections = {\"S1\": (\"s1\u002Ffiltered_feature_bc_matrix.h5\", \"s1\u002Fspatial\"),\n            \"S2\": (\"s2\u002Ffiltered_feature_bc_matrix.h5\", \"s2\u002Fspatial\")}\nparts = {}\nfor name, (h5, sp_dir) in sections.items():\n    a = sc.read_10x_h5(h5); a.var_names_make_unique()\n    pos = pd.read_csv(f\"{sp_dir}\u002Ftissue_positions.csv\", index_col=0)\n    a.obsm[\"spatial\"] = pos.loc[a.obs_names, [\"pxl_col_in_fullres\", \"pxl_row_in_fullres\"]].to_numpy()\n    parts[name] = a\nst = sc.concat(parts, label=\"sample\", index_unique=\"-\")\nst = st[:, np.intersect1d(st.var_names, inf_aver.index)].copy()\nCell2location.setup_anndata(st, batch_key=\"sample\")\n```\n\nThen build and train the model as in Step 4.\n\n### Recipe: Maps over the H&E Image\n\n`squidpy` reads the Space Ranger folder with its image and draws spots on it:\n\n```python\nimport squidpy as sq\n\nst_img = sq.read.visium(\"path\u002Fto\u002Fspaceranger_outs\")   # folder with filtered_feature_bc_matrix.h5 + spatial\u002F\nst_img.var_names_make_unique()\nst_img = st_img[abund.index].copy()\nst_img.obs[list(top)] = abund.loc[st_img.obs_names, top].to_numpy()\nsq.pl.spatial_scatter(st_img, color=list(top), ncols=3, cmap=\"magma\", save=\"cell2location_on_he.png\")\n```\n\n### Recipe: Dominant Type and Composition per Region\n\n```python\nst.obs[\"dominant_type\"] = prop.idxmax(axis=1)\nst.obs[\"dominant_share\"] = prop.max(axis=1)\nprint(st.obs[\"dominant_type\"].value_counts())\n\nREGION_KEY = \"domain\"     # e.g. from spatial-domain-detection or a pathologist's annotation\nif REGION_KEY in st.obs:\n    region_comp = prop.groupby(st.obs[REGION_KEY]).mean().round(3)\n    region_comp.to_csv(\"composition_per_region.csv\")\n    print(region_comp)\n```\n\nA spot's dominant type is a summary, not a label: report its share alongside it.\n\n## Expected Outputs\n\n- `cell2location_abundance.csv` - estimated cells per spot and type (5% posterior quantile)\n- `cell2location_proportions.csv` - per-spot proportions\n- `cell2location_spatial.h5ad` - full posterior in `obsm`\n- `cell2location_top_types.png` - maps of the most abundant types\n\n## Troubleshooting\n\n| Problem | Cause | Fix |\n|---|---|---|\n| Few shared genes | Symbols vs Ensembl IDs | Use symbols on both sides (`feature_name` in Census data) |\n| Training very slow | CPU, 30000 epochs | Lower `MAX_EPOCHS`, state it in the report; or run on GPU |\n| One type dominates every spot | Reference missing the tissue's major types | Choose a better-matched reference |\n| `KeyError: means_per_cluster_mu_fg_...` | `export_posterior` not run | Run it on the reference before Step 4 |\n| Out of memory in export | Large `batch_size` | Lower `batch_size` in `sample_kwargs` |\n| Total abundance does not follow nuclei density | `DETECTION_ALPHA` too strong | Compare 20 and 200; keep the one that follows histology |\n\n## Related Skills\n\n- `spatial-transcriptomics-cell-type-annotation` - single-cell-resolution platforms; its Steps 3-4 fetch the reference\n- `spatial-mapping-tangram` - Tangram mapping, incl. per-cell mapping with histology segmentation\n- `spatial-domain-detection` - tissue regions to summarise compositions by\n- `spatial-transcriptomics-cell-cell-communication` - interactions on the deconvolved slide\n\n## References\n\n- Kleshchevnikov et al. (2022) cell2location, Nature Biotechnology: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41587-021-01139-4\n- cell2location documentation: https:\u002F\u002Fcell2location.readthedocs.io\u002Fen\u002Flatest\u002F\n- cell2location tutorial (hyperparameter guidance): https:\u002F\u002Fcell2location.readthedocs.io\u002Fen\u002Flatest\u002Fnotebooks\u002Fcell2location_tutorial.html\n- cell2location source: https:\u002F\u002Fgithub.com\u002FBayraktarLab\u002Fcell2location\n- squidpy Visium reader: https:\u002F\u002Fsquidpy.readthedocs.io\u002Fen\u002Fstable\u002Fapi\u002Fsquidpy.read.visium.html\n","# Spot Deconvolution with cell2location\n\n## Overview\n\nEach Visium spot (55 um) holds several cells, so cell types are reported as an\nabundance per spot, not one label per spot. cell2location learns a signature\nper cell type from a scRNA-seq reference, then explains every spot's counts as\na mixture of those signatures. Output: estimated cell counts and proportions\nper spot and type, maps on the tissue, and a marker check of each map.\n\n## When to Use\n\n- Asked to \"annotate cell types\" or \"find where cell types are\" on Visium, Slide-seq or ST data\n- Mapping a published scRNA-seq atlas onto a spot-based section\n- Comparing cell type composition between tissue regions or sections\n- Producing per-spot compositions for downstream niche or communication analysis\n- Getting abundance estimates with posterior uncertainty (5% quantile)\n- Use `spatial-transcriptomics-cell-type-annotation` instead when each observation is one cell (Xenium, MERFISH, CosMx)\n- Use `spatial-mapping-tangram` (constrained deconvolution route) instead when you need single cells placed on segmented nuclei of the histology image\n\n## Prerequisites\n\n- **Input**: Space Ranger output (`filtered_feature_bc_matrix.h5` and the `spatial\u002F` folder) with raw counts\n- **Reference**: scRNA-seq with raw counts and `obs[\"cell_type\"]` (Step 2 fetches one)\n- **Compute**: GPU strongly preferred. On CPU the spatial model (Step 4) needs fewer epochs than the\n  default, chosen by the timing probe there; the reference model (Step 3) takes minutes\n- **Python packages**: `cell2location` (pulls torch, scvi-tools, pyro; large), `scanpy`\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 scanpy cell2location\n```\n\n## Pre-flight Interview\n\n```yaml\ndecisions:\n  - id: D1\n    param: STATE\n    kind: required\n    source: user\n    ask: \"Which tissue is this, and in what state (healthy, or which tumour or disease)?\"\n    default: null\n\n  - id: D2\n    param: referenceSource\n    kind: required\n    source: user\n    ask: \"Do you have a scRNA\u002FsnRNA-seq reference from the same tissue and state (h5ad with raw counts and a cell type column), or should I search public data (CELLxGENE)?\"\n    default: null\n\n  - id: D3\n    param: CELL_TYPE_KEY\n    kind: required\n    source: data\n    depends_on: [D2]\n    ask: \"Which reference column holds the cell types, and at what level: major lineages or fine subtypes?\"\n    default: null\n\n  - id: D4\n    param: COMPUTE_ROUTE\n    kind: required\n    source: user\n    ask: \"Without a GPU, cell2location runs only with fewer training epochs (exploratory maps, still long). Run it that way, or get per-spot proportions quickly with Tangram (clusters mode)?\"\n    default: \"cell2location with MAX_EPOCHS from the Step 4 timing probe, reported as exploratory\"\n\n  - id: D5\n    param: N_CELLS_PER_SPOT\n    kind: required\n    source: user\n    depends_on: [D1]\n    ask: \"About how many nuclei does one spot hold in this tissue? I can use the tutorial value of 30 if you do not know.\"\n    default: \"30\"\n\n  - id: D6\n    param: SAMPLE_KEY\n    kind: required\n    source: data\n    skip_if: \"a single section\"\n    ask: \"There are several sections: fit them in one model (shared cell type signatures, per-section sensitivity) or each on its own?\"\n    default: \"one model with batch_key = section\"\n\n  - id: D7\n    param: DETECTION_ALPHA\n    kind: optional\n    source: user\n    ask: \"Does RNA detection vary strongly across the slide (uneven tissue quality)?\"\n    default: \"20 (uneven detection); 200 when detection is even\"\n\n  - id: D8\n    param: REF_BATCH_KEY\n    kind: optional_conditional\n    source: data\n    depends_on: [D2]\n    ask: \"The reference pools several donors or studies: correct the signatures for that column?\"\n    default: \"batch_key = donor_id when the reference has more than one donor\"\n```\n\nAsk D1, D2 and D4 together, with D6 when there is more than one section. The\ntissue and state come from the user: a sample name will not be found in public\ndatabases, so do not search the web for it. Spot data cannot tell a tumour from\nhealthy tissue reliably; if the user does not know, propose a tissue from the\ntop marker genes and ask them to confirm. If D4 picks Tangram, use\n`spatial-mapping-tangram` with `MODE = \"clusters\"` and the same reference.\n\n## Workflow\n\n### Step 1: Load Visium Output\n\n```python\nimport os\nimport numpy as np\nimport pandas as pd\nimport scanpy as sc\n\nH5 = \"path\u002Fto\u002Ffiltered_feature_bc_matrix.h5\"\nSPATIAL_DIR = \"path\u002Fto\u002Fspatial\"\n\nst = sc.read_10x_h5(H5)\nst.var_names_make_unique()\nif os.path.exists(f\"{SPATIAL_DIR}\u002Ftissue_positions.csv\"):           # Space Ranger >= 2.0\n    pos = pd.read_csv(f\"{SPATIAL_DIR}\u002Ftissue_positions.csv\", index_col=0)\nelse:                                                                  # older, no header\n    pos = pd.read_csv(f\"{SPATIAL_DIR}\u002Ftissue_positions_list.csv\", header=None, index_col=0,\n                      names=[\"barcode\", \"in_tissue\", \"array_row\", \"array_col\",\n                             \"pxl_row_in_fullres\", \"pxl_col_in_fullres\"])\nst.obsm[\"spatial\"] = pos.loc[st.obs_names, [\"pxl_col_in_fullres\", \"pxl_row_in_fullres\"]].to_numpy()\nst = st[:, ~st.var_names.str.startswith(\"MT-\")].copy()   # mito reads are not cell type signal\nprint(st)\nprint(f\"median UMIs\u002Fspot: {np.median(np.asarray(st.X.sum(1)).ravel()):.0f}\")\n```\n\n### Step 2: Get a Reference\n\nUse the tissue and state from D1. Without the user's own reference (D2),\nsearch and download a subsampled CELLxGENE reference with Steps 3-4 of\n`spatial-transcriptomics-cell-type-annotation` (same code, with `GENES = None` and\n`MAX_PER_TYPE = 300` - signatures need every gene), and load it:\n\n```python\nref = sc.read_h5ad(\"reference.h5ad\")      # X = raw counts, obs[\"cell_type\"]\nprint(ref.obs[\"cell_type\"].value_counts())\n```\n\nTypes with fewer than ~20 cells cannot yield a stable signature; Step 3 drops them.\n\n### Step 3: Fit Reference Signatures\n\n```python\nfrom cell2location.models import RegressionModel\nfrom cell2location.utils.filtering import filter_genes\n\nref = ref[ref.obs[\"cell_type\"].map(ref.obs[\"cell_type\"].value_counts()) >= 20].copy()\nselected = filter_genes(ref, cell_count_cutoff=5, cell_percentage_cutoff2=0.03, nonz_mean_cutoff=1.12)\nref = ref[:, selected].copy()\n\nRegressionModel.setup_anndata(ref, labels_key=\"cell_type\")   # add batch_key=\"donor_id\" for multi-donor references\nref_model = RegressionModel(ref)\nref_model.train(max_epochs=250)\nref = ref_model.export_posterior(ref, sample_kwargs={\"num_samples\": 1000, \"batch_size\": 2500})\n\nfactors = ref.uns[\"mod\"][\"factor_names\"]\ninf_aver = ref.varm[\"means_per_cluster_mu_fg\"][[f\"means_per_cluster_mu_fg_{f}\" for f in factors]].copy()\ninf_aver.columns = factors                     # genes x cell types\nprint(inf_aver.shape)\n```\n\n### Step 4: Fit the Spatial Model\n\n```python\nfrom cell2location.models import Cell2location\n\nshared = np.intersect1d(st.var_names, inf_aver.index)\nprint(f\"shared genes: {len(shared)}\")\nst = st[:, shared].copy()\ninf_aver = inf_aver.loc[shared]\n\nN_CELLS_PER_SPOT = 30       # D5; tutorial value; set from nuclei counted on the H&E for this tissue\nDETECTION_ALPHA = 20        # D7; 20 when RNA detection varies across the slide; also try 200\nCell2location.setup_anndata(st)\n```\n\nOn CPU, time a short run on a throwaway model before choosing `MAX_EPOCHS`.\nThe default 30000 epochs often takes hours there, longer than one execution\ncall is allowed to run in many sandboxes:\n\n```python\nimport time\nimport torch\n\nprobe = Cell2location(st, cell_state_df=inf_aver,\n                      N_cells_per_location=N_CELLS_PER_SPOT, detection_alpha=DETECTION_ALPHA)\nt0 = time.time()\nprobe.train(max_epochs=50, batch_size=None, train_size=1)\nsec_per_epoch = (time.time() - t0) \u002F 50\ndel probe\n\nBUDGET_S = 20 * 60          # leave headroom under the per-call time limit\nif torch.cuda.is_available():\n    MAX_EPOCHS = 30000      # tutorial default\nelse:\n    MAX_EPOCHS = int(min(30000, BUDGET_S \u002F sec_per_epoch) \u002F\u002F 1000 * 1000)\nprint(f\"{sec_per_epoch:.2f} s\u002Fepoch -> MAX_EPOCHS = {MAX_EPOCHS} (30000 needs ~{sec_per_epoch * 30000 \u002F 3600:.1f} h)\")\n```\n\nBelow ~3000 epochs the maps are too rough to report; switch to the Tangram\nroute of D4 instead. Then fit:\n\n```python\nst_model = Cell2location(st, cell_state_df=inf_aver,\n                         N_cells_per_location=N_CELLS_PER_SPOT, detection_alpha=DETECTION_ALPHA)\nst_model.train(max_epochs=MAX_EPOCHS, batch_size=None, train_size=1)\n```\n\nReport `MAX_EPOCHS` with the maps; anything below 30000 is exploratory.\n\n### Step 5: Export and Check Abundances\n\n```python\nst = st_model.export_posterior(st, sample_kwargs={\"num_samples\": 1000, \"batch_size\": st_model.adata.n_obs})\nabund = pd.DataFrame(st.obsm[\"q05_cell_abundance_w_sf\"].to_numpy(), index=st.obs_names, columns=factors)\nprop = abund.div(abund.sum(1), axis=0)          # per-spot proportions\nabund.to_csv(\"cell2location_abundance.csv\")\nprop.to_csv(\"cell2location_proportions.csv\")\nst.write_h5ad(\"cell2location_spatial.h5ad\", compression=\"gzip\")\nprint(prop.mean().sort_values(ascending=False).head(10))\n```\n\nPlot the most abundant types on the tissue:\n\n```python\nimport matplotlib.pyplot as plt\n\ntop = prop.mean().nlargest(6).index\nfig, axes = plt.subplots(2, 3, figsize=(15, 10))\nfor ax, ct in zip(axes.flat, top):\n    sc_ = ax.scatter(st.obsm[\"spatial\"][:, 0], st.obsm[\"spatial\"][:, 1], c=abund[ct], s=8, cmap=\"magma\")\n    ax.invert_yaxis(); ax.set_title(ct); ax.axis(\"off\"); fig.colorbar(sc_, ax=ax, shrink=0.6)\nplt.tight_layout(); plt.savefig(\"cell2location_top_types.png\", dpi=150)\n```\n\nCheck each map against a marker the user's biology predicts (for example\nplasma cells vs `JCHAIN`): abundance and marker expression should correlate\nacross spots. A type whose map ignores its own markers is not supported.\n\n```python\nst_norm = st.copy(); sc.pp.normalize_total(st_norm); sc.pp.log1p(st_norm)\nchecks = {\"Plasma cell\": \"JCHAIN\"}             # fill with types present in `factors`\nfor ct, gene in checks.items():\n    if ct in abund and gene in st_norm.var_names:\n        expr = np.asarray(st_norm[:, gene].X.todense()).ravel()\n        print(f\"{ct} vs {gene}: r = {np.corrcoef(abund[ct], expr)[0, 1]:.2f}\")\n```\n\n## Key Parameters\n\n| Parameter | Default | Effect |\n|---|---|---|\n| Reference state | from the user | Healthy vs disease signatures; the most consequential choice |\n| `N_CELLS_PER_SPOT` | 30 | Prior on spot density; scales absolute abundance. Set from histology |\n| `DETECTION_ALPHA` | 20 | Regularises per-spot sensitivity; 200 when detection is even |\n| `MAX_EPOCHS` (spatial) | 30000 | Convergence; fewer epochs = rougher maps |\n| min cells per type | 20 | Types below it are dropped from the reference |\n\n## Common Recipes\n\n### Recipe: Several Sections in One Model\n\nFit all sections together so signatures are shared while sensitivity is\nestimated per section:\n\n```python\nsections = {\"S1\": (\"s1\u002Ffiltered_feature_bc_matrix.h5\", \"s1\u002Fspatial\"),\n            \"S2\": (\"s2\u002Ffiltered_feature_bc_matrix.h5\", \"s2\u002Fspatial\")}\nparts = {}\nfor name, (h5, sp_dir) in sections.items():\n    a = sc.read_10x_h5(h5); a.var_names_make_unique()\n    pos = pd.read_csv(f\"{sp_dir}\u002Ftissue_positions.csv\", index_col=0)\n    a.obsm[\"spatial\"] = pos.loc[a.obs_names, [\"pxl_col_in_fullres\", \"pxl_row_in_fullres\"]].to_numpy()\n    parts[name] = a\nst = sc.concat(parts, label=\"sample\", index_unique=\"-\")\nst = st[:, np.intersect1d(st.var_names, inf_aver.index)].copy()\nCell2location.setup_anndata(st, batch_key=\"sample\")\n```\n\nThen build and train the model as in Step 4.\n\n### Recipe: Maps over the H&E Image\n\n`squidpy` reads the Space Ranger folder with its image and draws spots on it:\n\n```python\nimport squidpy as sq\n\nst_img = sq.read.visium(\"path\u002Fto\u002Fspaceranger_outs\")   # folder with filtered_feature_bc_matrix.h5 + spatial\u002F\nst_img.var_names_make_unique()\nst_img = st_img[abund.index].copy()\nst_img.obs[list(top)] = abund.loc[st_img.obs_names, top].to_numpy()\nsq.pl.spatial_scatter(st_img, color=list(top), ncols=3, cmap=\"magma\", save=\"cell2location_on_he.png\")\n```\n\n### Recipe: Dominant Type and Composition per Region\n\n```python\nst.obs[\"dominant_type\"] = prop.idxmax(axis=1)\nst.obs[\"dominant_share\"] = prop.max(axis=1)\nprint(st.obs[\"dominant_type\"].value_counts())\n\nREGION_KEY = \"domain\"     # e.g. from spatial-domain-detection or a pathologist's annotation\nif REGION_KEY in st.obs:\n    region_comp = prop.groupby(st.obs[REGION_KEY]).mean().round(3)\n    region_comp.to_csv(\"composition_per_region.csv\")\n    print(region_comp)\n```\n\nA spot's dominant type is a summary, not a label: report its share alongside it.\n\n## Expected Outputs\n\n- `cell2location_abundance.csv` - estimated cells per spot and type (5% posterior quantile)\n- `cell2location_proportions.csv` - per-spot proportions\n- `cell2location_spatial.h5ad` - full posterior in `obsm`\n- `cell2location_top_types.png` - maps of the most abundant types\n\n## Troubleshooting\n\n| Problem | Cause | Fix |\n|---|---|---|\n| Few shared genes | Symbols vs Ensembl IDs | Use symbols on both sides (`feature_name` in Census data) |\n| Training very slow | CPU, 30000 epochs | Lower `MAX_EPOCHS`, state it in the report; or run on GPU |\n| One type dominates every spot | Reference missing the tissue's major types | Choose a better-matched reference |\n| `KeyError: means_per_cluster_mu_fg_...` | `export_posterior` not run | Run it on the reference before Step 4 |\n| Out of memory in export | Large `batch_size` | Lower `batch_size` in `sample_kwargs` |\n| Total abundance does not follow nuclei density | `DETECTION_ALPHA` too strong | Compare 20 and 200; keep the one that follows histology |\n\n## Related Skills\n\n- `spatial-transcriptomics-cell-type-annotation` - single-cell-resolution platforms; its Steps 3-4 fetch the reference\n- `spatial-mapping-tangram` - Tangram mapping, incl. per-cell mapping with histology segmentation\n- `spatial-domain-detection` - tissue regions to summarise compositions by\n- `spatial-transcriptomics-cell-cell-communication` - interactions on the deconvolved slide\n\n## References\n\n- Kleshchevnikov et al. (2022) cell2location, Nature Biotechnology: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41587-021-01139-4\n- cell2location documentation: https:\u002F\u002Fcell2location.readthedocs.io\u002Fen\u002Flatest\u002F\n- cell2location tutorial (hyperparameter guidance): https:\u002F\u002Fcell2location.readthedocs.io\u002Fen\u002Flatest\u002Fnotebooks\u002Fcell2location_tutorial.html\n- cell2location source: https:\u002F\u002Fgithub.com\u002FBayraktarLab\u002Fcell2location\n- squidpy Visium reader: https:\u002F\u002Fsquidpy.readthedocs.io\u002Fen\u002Fstable\u002Fapi\u002Fsquidpy.read.visium.html\n",{"name":5,"license":15,"description":7},"master","fd76f882a04e445e899d5cfb2732f2105ea054ee","skills\u002Fawesome-skills\u002Fspatial-transcriptomics-deconvolution-cell2location",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-deconvolution-cell2location",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill spatial-transcriptomics-deconvolution-cell2location",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill spatial-transcriptomics-deconvolution-cell2location","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fspatial-transcriptomics-deconvolution-cell2location\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",[],[]]