[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M76EVKCAH4W2J1HR58VPBYVR":3,"skill-same:01M76EVKCAH4W2J1HR58VPBYVR":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},"01M76EVKCAH4W2J1HR58VPBYVR","spatial-domain-detection",null,"Spatial domain detection (tissue regions \u002F niches) for spatial transcriptomics: SpaGCN (expression + spatial graph + H&E histology, Visium\u002FST), GraphST (self-supervised graph contrastive embedding, spots or cells) and UTAG (spatial message passing for Xenium\u002FMERFISH\u002FCosMx\u002FIMC cells). Outputs a domain label per spot or cell, boundary refinement, cross-method agreement (ARI) and domain marker genes. For niches defined by the cell type composition of annotated cells use Step 7 of spatial-transcriptomics-cell-type-annotation; for neighbourhood enrichment and spatial statistics use spatial-transcriptomics-analysis-squidpy.","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-domain-detection\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: \"spatial-domain-detection\"\ndescription: \"Spatial domain detection (tissue regions \u002F niches) for spatial transcriptomics: SpaGCN (expression + spatial graph + H&E histology, Visium\u002FST), GraphST (self-supervised graph contrastive embedding, spots or cells) and UTAG (spatial message passing for Xenium\u002FMERFISH\u002FCosMx\u002FIMC cells). Outputs a domain label per spot or cell, boundary refinement, cross-method agreement (ARI) and domain marker genes. For niches defined by the cell type composition of annotated cells use Step 7 of spatial-transcriptomics-cell-type-annotation; for neighbourhood enrichment and spatial statistics use spatial-transcriptomics-analysis-squidpy.\"\nlicense: \"CC-BY-4.0\"\n---\n\n# Spatial Domain Detection\n\n## Overview\n\nSplit a tissue section into spatially coherent regions (cortical layers, tumour\ncore vs stroma, germinal centres) from expression plus location. Each method\nreturns one domain label per spot or cell. Output: domain labels from one or\nmore methods, their agreement, domain marker genes and domain maps.\n\n| Method | Data | Uses | Compute |\n|---|---|---|---|\n| SpaGCN | Visium \u002F ST spots, optionally with the H&E image | Expression + spatial graph + histology colour | CPU, minutes |\n| GraphST | Spots or cells up to ~30k observations | Contrastive graph embedding | GPU preferred (torch) |\n| UTAG | Single-cell resolution (Xenium, MERFISH, CosMx, IMC) | Expression averaged over a radius | CPU, scales to 10^5-10^6 cells |\n| Composition niches | Annotated single cells | Cell type mix of the neighbourhood | CPU; Step 7 of `spatial-transcriptomics-cell-type-annotation` |\n\nDomains are clusters, not ground truth: run two methods and report where they\nagree.\n\n## When to Use\n\n- Dividing a Visium or ST section into tissue regions such as layers, tumour core and stroma\n- Using the H&E image together with expression to draw region boundaries (SpaGCN)\n- Finding cellular niches in Xenium, MERFISH, CosMx or IMC data without labels (UTAG)\n- Getting region labels to summarise deconvolved compositions or cell types by\n- Checking whether two independent methods agree on the main boundaries\n- Use Step 7 of `spatial-transcriptomics-cell-type-annotation` instead when cells are already annotated and niches should be defined by cell type mix\n- For neighbourhood enrichment or spatially variable genes, use `spatial-transcriptomics-analysis-squidpy`\n\n## Prerequisites\n\n- **Input**: raw counts in `X` (or `layers[\"counts\"]`) and coordinates in `obsm[\"spatial\"]`\n- **SpaGCN**: pulls torch. Its Louvain init needs `louvain`, which has no Python 3.13\n  conda build or wheel and cannot be compiled here; without it use the k-means init (Step 3)\n- **GraphST**: pulls torch; a CUDA GPU makes training ~10x faster; the dense\n  spot-by-spot graph limits it to ~30k observations\n- **UTAG**: not on PyPI; install from GitHub\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 SpaGCN GraphST\npixi add --pypi \"utag @ git+https:\u002F\u002Fgithub.com\u002FElementoLab\u002Futag.git@main\"\n```\n\n## Workflow\n\n1. Load Visium data (or your own)\n2. Preprocess\n3. SpaGCN domains (spots, with histology)\n4. GraphST domains (spots or cells)\n5. UTAG domains (single-cell resolution)\n6. Compare methods and characterise domains\n\n### Step 1: Load Visium Data\n\nFor your own Space Ranger output set `OUTS` to the `outs\u002F` folder and skip the\ndownload. The demo is the 10x mouse brain (sagittal anterior) section.\n\n```python\nimport json\nimport tarfile\nimport urllib.request\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nimport scanpy as sc\n\nCACHE = Path(\"data_cache\u002FV1_Mouse_Brain_Sagittal_Anterior\")\nBASE = (\"https:\u002F\u002Fcf.10xgenomics.com\u002Fsamples\u002Fspatial-exp\u002F1.1.0\u002FV1_Mouse_Brain_Sagittal_Anterior\u002F\"\n        \"V1_Mouse_Brain_Sagittal_Anterior_\")\nCACHE.mkdir(parents=True, exist_ok=True)\nfor name in [\"filtered_feature_bc_matrix.h5\", \"spatial.tar.gz\"]:\n    if not (CACHE \u002F name).exists():\n        urllib.request.urlretrieve(BASE + name, CACHE \u002F name)          # ~20 MB + ~9 MB\nif not (CACHE \u002F \"spatial\").exists():\n    with tarfile.open(CACHE \u002F \"spatial.tar.gz\") as tar:\n        tar.extractall(CACHE, filter=\"data\")\nOUTS = CACHE                                    # your data: Path(\"path\u002Fto\u002Fouts\")\n\nSPATIAL_DIR = OUTS \u002F \"spatial\"\nadata = sc.read_10x_h5(OUTS \u002F \"filtered_feature_bc_matrix.h5\")\nadata.var_names_make_unique()\ncols = [\"in_tissue\", \"array_row\", \"array_col\", \"pxl_row\", \"pxl_col\"]\nif (SPATIAL_DIR \u002F \"tissue_positions.csv\").exists():                    # Space Ranger >= 2.0\n    pos = pd.read_csv(SPATIAL_DIR \u002F \"tissue_positions.csv\", index_col=0)\n    pos.columns = cols\nelse:                                                                   # older, no header\n    pos = pd.read_csv(SPATIAL_DIR \u002F \"tissue_positions_list.csv\", header=None, index_col=0, names=cols)\nadata.obs = adata.obs.join(pos, how=\"left\")\nadata.obsm[\"spatial\"] = adata.obs[[\"pxl_col\", \"pxl_row\"]].to_numpy(float)   # x, y in full-res pixels\nscale = json.loads((SPATIAL_DIR \u002F \"scalefactors_json.json\").read_text())\nprint(adata)\n```\n\n### Step 2: Preprocess\n\n```python\nadata.var[\"mt\"] = adata.var_names.str.upper().str.startswith(\"MT-\")\nsc.pp.calculate_qc_metrics(adata, qc_vars=[\"mt\"], inplace=True)\nsc.pp.filter_cells(adata, min_counts=500)       # Visium; use ~10 for imaging panels\nsc.pp.filter_genes(adata, min_cells=10)\nadata.layers[\"counts\"] = adata.X.copy()         # SpaGCN and GraphST start from counts\nsc.pp.normalize_total(adata)\nsc.pp.log1p(adata)\nprint(f\"{adata.n_obs} spots, {adata.n_vars} genes, median mt% {adata.obs['pct_counts_mt'].median():.1f}\")\n```\n\n### Step 3: SpaGCN (Visium with H&E)\n\nSpaGCN smooths expression over a graph whose edges combine spot distance and\nhistology colour, then clusters with a graph convolutional network. Coordinates\npassed with the image must be **(image row, image column)** at the image's\nscale.\n\n```python\nimport random\n\nimport SpaGCN as spg\nimport torch\nfrom PIL import Image\n\nN_DOMAINS = 7\nUSE_HISTOLOGY = True\n\nsp = adata.copy()\nsp.X = sp.layers[\"counts\"].toarray()            # dense: SpaGCN calls .A on sparse, removed in scipy>=1.14\nhires = scale[\"tissue_hires_scalef\"]\nx_pix = (sp.obs[\"pxl_row\"] * hires).round().astype(int).to_numpy()   # image row\ny_pix = (sp.obs[\"pxl_col\"] * hires).round().astype(int).to_numpy()   # image column\nif USE_HISTOLOGY:\n    img = np.array(Image.open(SPATIAL_DIR \u002F \"tissue_hires_image.png\").convert(\"RGB\"))\n    beta = max(3, int(scale[\"spot_diameter_fullres\"] * hires))       # spot size in hires pixels\n    adj = spg.calculate_adj_matrix(x=x_pix, y=y_pix, x_pixel=x_pix, y_pixel=y_pix,\n                                   image=img, beta=beta, alpha=1, histology=True)\nelse:\n    adj = spg.calculate_adj_matrix(x=x_pix, y=y_pix, histology=False)\n\nspg.prefilter_genes(sp, min_cells=3)\nspg.prefilter_specialgenes(sp)                  # drops ERCC \u002F MT- genes\nsc.pp.normalize_total(sp)\nsc.pp.log1p(sp)\n\nl = spg.search_l(0.5, adj, start=0.01, end=1000, tol=0.01, max_run=100)   # p=0.5\nr_seed = t_seed = n_seed = 100\nres = spg.search_res(sp, adj, l, N_DOMAINS, start=0.7, step=0.1, tol=5e-3, lr=0.05,\n                     max_epochs=20, r_seed=r_seed, t_seed=t_seed, n_seed=n_seed)\nrandom.seed(r_seed); torch.manual_seed(t_seed); np.random.seed(n_seed)\nclf = spg.SpaGCN()\nclf.set_l(l)\nclf.train(sp, adj, init_spa=True, init=\"louvain\", res=res, tol=5e-3, lr=0.05, max_epochs=200)\ny_pred, prob = clf.predict()\nadata.obs[\"spagcn\"] = pd.Categorical(y_pred.astype(str))\n\n# Refinement: relabel a spot when most of its ring disagrees (spot grids only)\nadj_2d = spg.calculate_adj_matrix(x=sp.obs[\"array_row\"].to_numpy(), y=sp.obs[\"array_col\"].to_numpy(),\n                                  histology=False)\nrefined = spg.refine(sample_id=sp.obs_names.tolist(), pred=y_pred.tolist(), dis=adj_2d, shape=\"hexagon\")\nadata.obs[\"spagcn_refined\"] = pd.Categorical(np.asarray(refined).astype(str))\nprint(adata.obs[\"spagcn_refined\"].value_counts())\n```\n\nWithout `louvain`, skip `search_res` and initialise with k-means:\n`clf.train(sp, adj, init_spa=True, init=\"kmeans\", n_clusters=N_DOMAINS, tol=5e-3, lr=0.05, max_epochs=200)`.\n\n`shape=\"hexagon\"` for Visium, `\"square\"` for legacy ST. Raise `alpha` to give\nhistology more weight; set `USE_HISTOLOGY = False` when the image is missing or\npoorly registered.\n\n### Step 4: GraphST\n\nGraphST learns a spatially smoothed embedding by contrasting the real graph\nwith a corrupted one, then clusters it. Give it raw counts: it selects 3,000\nHVGs (seurat_v3), normalises, log-transforms and scales internally.\n\n```python\nimport torch\nfrom GraphST import GraphST\nfrom GraphST.utils import clustering\n\ngst = sc.AnnData(adata.layers[\"counts\"].copy(), obs=adata.obs[[]].copy(), var=adata.var[[]].copy())\ngst.obsm[\"spatial\"] = adata.obsm[\"spatial\"].copy()\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n# datatype: \"10X\" (spot grids, imaging cells); \"Slide\" or \"Stereo\" for Slide-seq \u002F Stereo-seq (KNN graph)\nmodel = GraphST.GraphST(gst, device=device, random_seed=42, datatype=\"10X\")\ngst = model.train()                             # 600 epochs; embedding in obsm[\"emb\"]\n\n# Scans Leiden resolution from `end` down to `start` until exactly N_DOMAINS clusters appear\nclustering(gst, n_clusters=N_DOMAINS, radius=50, method=\"leiden\",\n           start=0.1, end=2.0, increment=0.01, refinement=False)\nadata.obs[\"graphst\"] = pd.Categorical(gst.obs[\"domain\"].astype(str).to_numpy())\nadata.obsm[\"graphst_emb\"] = gst.obsm[\"emb\"]\nprint(adata.obs[\"graphst\"].value_counts())\n```\n\nThe GraphST authors recommend `method=\"mclust\"` (needs R with the `mclust`\npackage and `rpy2`); `refinement=True` relabels each observation by its\n`radius` nearest neighbours.\n\n### Step 5: UTAG (Single-Cell Resolution)\n\nUTAG averages each cell's expression over neighbours within `max_dist`, then\nclusters. Input: one `.h5ad` of cells with log-normalised `X` and\n`obsm[\"spatial\"]` in microns (e.g. the output of\n`spatial-transcriptomics-cell-type-annotation`).\n\n```python\nfrom scipy.spatial import cKDTree\nfrom sklearn.neighbors import NearestNeighbors\nfrom utag import utag\n\ncells = sc.read_h5ad(\"celltype_annotated.h5ad\")\nSLIDE_KEY = None                     # obs column with sample\u002Fsection IDs, if several\nMIN_NICHES, MIN_CLUSTER_SIZE = 5, 100\n\n# max_dist: radius where a typical cell has ~3 neighbours (estimated per slide)\nslides = cells.obs[SLIDE_KEY].unique() if SLIDE_KEY else [None]\nd3 = []\nfor s in slides:\n    xy = cells.obsm[\"spatial\"] if s is None else cells[cells.obs[SLIDE_KEY] == s].obsm[\"spatial\"]\n    d3.append(cKDTree(xy).query(xy[:20000], k=4)[0][:, 3])\nMAX_DIST = float(np.ceil(np.median(np.concatenate(d3))))\nprint(f\"max_dist = {MAX_DIST}\")\n\nfor resolution in [0.05, 0.1, 0.3, 0.5]:          # coarsest resolution giving enough niches\n    out = utag(cells, slide_key=SLIDE_KEY, max_dist=MAX_DIST, normalization_mode=\"l1_norm\",\n               apply_umap=False, apply_clustering=True, clustering_method=[\"leiden\"],\n               resolutions=[resolution])\n    key = f\"UTAG Label_leiden_{resolution}\"\n    print(resolution, out.obs[key].nunique())\n    if out.obs[key].nunique() >= MIN_NICHES:\n        break\n\n# Merge clusters smaller than MIN_CLUSTER_SIZE (within each slide) into the nearest larger one\nlab = out.obs[key].astype(str).copy()\nfor s in slides:\n    m = np.ones(out.n_obs, bool) if s is None else (out.obs[SLIDE_KEY] == s).to_numpy()\n    counts = lab[m].value_counts()\n    small = lab[m].isin(counts[counts \u003C MIN_CLUSTER_SIZE].index).to_numpy()\n    if small.any() and (~small).any():\n        xy = out.obsm[\"spatial\"][m]\n        nn = NearestNeighbors(n_neighbors=1).fit(xy[~small])\n        idx = nn.kneighbors(xy[small], return_distance=False).ravel()\n        lab.iloc[np.flatnonzero(m)[small]] = lab[m].to_numpy()[~small][idx]\ncells.obs[\"utag\"] = pd.Categorical(lab.reindex(cells.obs_names))   # utag may reorder cells by slide\nprint(cells.obs[\"utag\"].value_counts())\n```\n\n### Step 6: Compare Methods and Characterise Domains\n\n```python\nfrom sklearn.metrics import adjusted_rand_score\n\nari = adjusted_rand_score(adata.obs[\"spagcn_refined\"], adata.obs[\"graphst\"])\nprint(f\"SpaGCN vs GraphST ARI: {ari:.2f}\")      # > ~0.5: the main boundaries agree\nprint(pd.crosstab(adata.obs[\"spagcn_refined\"], adata.obs[\"graphst\"]))\n\nimport matplotlib.pyplot as plt\n\naxes = sc.pl.embedding(adata, basis=\"spatial\", color=[\"spagcn_refined\", \"graphst\"], size=1.5, show=False)\nfor ax in axes:\n    ax.invert_yaxis()                            # pixel y grows downwards\nplt.savefig(\"domains_spatial.png\", dpi=150, bbox_inches=\"tight\")\n\nDOMAIN = \"spagcn_refined\"\nsc.tl.rank_genes_groups(adata, DOMAIN, method=\"wilcoxon\")\nmarkers = sc.get.rank_genes_groups_df(adata, group=None)\nmarkers.to_csv(\"domain_markers.csv\", index=False)\ntop = (markers[markers[\"logfoldchanges\"] > 0].groupby(\"group\").head(8)\n       .groupby(\"group\")[\"names\"].apply(\", \".join))\nprint(top)\nadata.obs[[\"spagcn\", \"spagcn_refined\", \"graphst\"]].to_csv(\"spatial_domains.csv\")\nadata.write_h5ad(\"spatial_domains.h5ad\", compression=\"gzip\")\n```\n\nName domains from their markers (e.g. `Mbp` \u002F `Plp1` = white matter, layer\nmarkers in cortex). If cell type labels or cell2location abundances exist,\n`pd.crosstab(domain, cell_type, normalize=\"index\")` shows what each domain is\nmade of. With an expert annotation, report ARI against it instead.\n\n## Key Parameters\n\n| Parameter | Default | Effect |\n|---|---|---|\n| `N_DOMAINS` | 7 | Target number of domains (SpaGCN, GraphST); try 5-15 and compare |\n| SpaGCN `p` (`search_l`) | 0.5 | Share of expression taken from neighbours; higher = smoother domains |\n| SpaGCN `alpha` | 1 | Weight of histology colour in the graph |\n| SpaGCN `shape` | `\"hexagon\"` | Neighbour ring used in refinement (`\"square\"` for ST) |\n| GraphST `datatype` | `\"10X\"` | `\"Slide\"` \u002F `\"Stereo\"` switch to a KNN graph for dense data |\n| GraphST `radius` | 50 | Neighbours used when `refinement=True` |\n| UTAG `max_dist` | auto (~3 neighbours) | Averaging radius in coordinate units; larger = coarser niches |\n| UTAG `resolutions` | 0.05-0.5 | Leiden resolution on the averaged expression |\n| `MIN_CLUSTER_SIZE` | 100 | Smaller UTAG clusters are merged into the nearest larger one |\n\n## Common Recipes\n\n### Recipe: Choose the Number of Domains\n\n`N_DOMAINS` is a guess unless the anatomy fixes it. Scan k on the GraphST\nembedding and look for a plateau or peak in silhouette:\n\n```python\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import silhouette_score\n\nemb = adata.obsm[\"graphst_emb\"]\nrng = np.random.default_rng(0)\nsub = rng.choice(emb.shape[0], min(emb.shape[0], 5000), replace=False)\nscores = {}\nfor k in range(4, 16):\n    labels = KMeans(k, n_init=10, random_state=0).fit_predict(emb)\n    scores[k] = silhouette_score(emb[sub], labels[sub])\nprint(pd.Series(scores).round(3))\n```\n\nPrefer a k that matches known anatomy over the highest score; report the scan.\n\n### Recipe: What Each Domain Is Made Of\n\nWith cell type labels (single cells) or cell2location abundances (spots):\n\n```python\nDOMAIN = \"spagcn_refined\"\nif \"cell_type\" in adata.obs:\n    comp = pd.crosstab(adata.obs[DOMAIN], adata.obs[\"cell_type\"], normalize=\"index\")\nelse:\n    abund = pd.read_csv(\"cell2location_abundance.csv\", index_col=0).reindex(adata.obs_names)\n    prop = abund.div(abund.sum(axis=1), axis=0)\n    comp = prop.groupby(adata.obs[DOMAIN], observed=True).mean()\ncomp.round(3).to_csv(\"domain_composition.csv\")\nprint(comp.apply(lambda r: \", \".join(f\"{k} {v:.0%}\" for k, v in r.nlargest(3).items()), axis=1))\n```\n\n### Recipe: Domain Boundaries and Interfaces\n\nWhich domains touch, and which spots sit on a boundary (interfaces such as the\ntumour edge are often where the biology is):\n\n```python\nimport squidpy as sq\n\nsq.gr.spatial_neighbors(adata, coord_type=\"grid\", n_rings=1)   # imaging cells: coord_type=\"generic\", n_neighs=10\nA = adata.obsp[\"spatial_connectivities\"].tocoo()\nlab = adata.obs[DOMAIN].astype(str).to_numpy()\nedges = pd.DataFrame({\"a\": lab[A.row], \"b\": lab[A.col]})\ntouch = pd.crosstab(edges[\"a\"], edges[\"b\"])\nprint(touch)                                       # off-diagonal counts = shared boundary length\n\ndiff = lab[A.row] != lab[A.col]\nboundary = np.zeros(adata.n_obs, bool)\nboundary[A.row[diff]] = True\nadata.obs[\"domain_boundary\"] = boundary\nprint(f\"boundary spots: {boundary.mean():.0%}\")\n```\n\n## Expected Outputs\n\n- `spatial_domains.csv` - `spagcn`, `spagcn_refined`, `graphst` labels per spot\n- `spatial_domains.h5ad` - data with domain labels and `obsm[\"graphst_emb\"]`\n- `domain_markers.csv` - Wilcoxon markers per domain\n- `domains_spatial.png` - domain maps on tissue coordinates\n- `domain_composition.csv` - cell type mix per domain (recipe)\n\n## Troubleshooting\n\n| Problem | Cause | Fix |\n|---|---|---|\n| SpaGCN `UnboundLocalError: y_pred` | `init` other than `\"louvain\"` \u002F `\"kmeans\"` | Use `init=\"louvain\"` (needs `louvain`) or `init=\"kmeans\"` with `n_clusters` |\n| SpaGCN `AttributeError: ... has no attribute 'A'` | Sparse `X` with scipy >= 1.14 | Densify `X` before SpaGCN (Step 3 does) |\n| SpaGCN domains ignore the tissue image | Coordinates swapped or at full-res scale on the hires image | Pass `pxl_row`\u002F`pxl_col` scaled by `tissue_hires_scalef`, row first |\n| GraphST `AssertionError` in clustering | No Leiden resolution gives exactly `n_clusters` | Widen `end` (e.g. 3.0), change `N_DOMAINS` by 1, or use `mclust` |\n| GraphST out of memory | Dense n x n adjacency | Use UTAG for >30k cells, or run per region |\n| GraphST fails on a targeted panel (\u003C 3,000 genes) | Internal `n_top_genes=3000` | Set `gst.var[\"highly_variable\"] = True`, then normalise, log1p and scale yourself before `GraphST.GraphST` |\n| UTAG gives one huge niche | `max_dist` too large | Lower `max_dist` or raise resolution |\n| Fragmented, salt-and-pepper domains | Too little spatial smoothing | Raise SpaGCN `p`, use refinement, or raise UTAG `max_dist` |\n\n## Related Skills\n\n- `spatial-transcriptomics-cell-type-annotation` - cell labels; its Step 7 builds composition niches\n- `spatial-transcriptomics-deconvolution-cell2location` - cell type abundance per spot to interpret domains\n- `spatial-transcriptomics-analysis-squidpy` - neighbourhood enrichment, co-occurrence, spatially variable genes\n- `spatial-transcriptomics-cell-cell-communication` - signalling between cell types inside or across domains\n- `trajectory-inference` - pseudotime within a domain\n\n## References\n\n- Hu et al. (2021) SpaGCN, Nature Methods: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41592-021-01255-8\n- Long et al. (2023) GraphST, Nature Communications: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41467-023-36796-3\n- Kim et al. (2022) UTAG, Nature Methods: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41592-022-01657-2\n- SpaGCN source: https:\u002F\u002Fgithub.com\u002Fjianhuupenn\u002FSpaGCN\n- GraphST source: https:\u002F\u002Fgithub.com\u002FJinmiaoChenLab\u002FGraphST\n- UTAG source: https:\u002F\u002Fgithub.com\u002FElementoLab\u002Futag\n","# Spatial Domain Detection\n\n## Overview\n\nSplit a tissue section into spatially coherent regions (cortical layers, tumour\ncore vs stroma, germinal centres) from expression plus location. Each method\nreturns one domain label per spot or cell. Output: domain labels from one or\nmore methods, their agreement, domain marker genes and domain maps.\n\n| Method | Data | Uses | Compute |\n|---|---|---|---|\n| SpaGCN | Visium \u002F ST spots, optionally with the H&E image | Expression + spatial graph + histology colour | CPU, minutes |\n| GraphST | Spots or cells up to ~30k observations | Contrastive graph embedding | GPU preferred (torch) |\n| UTAG | Single-cell resolution (Xenium, MERFISH, CosMx, IMC) | Expression averaged over a radius | CPU, scales to 10^5-10^6 cells |\n| Composition niches | Annotated single cells | Cell type mix of the neighbourhood | CPU; Step 7 of `spatial-transcriptomics-cell-type-annotation` |\n\nDomains are clusters, not ground truth: run two methods and report where they\nagree.\n\n## When to Use\n\n- Dividing a Visium or ST section into tissue regions such as layers, tumour core and stroma\n- Using the H&E image together with expression to draw region boundaries (SpaGCN)\n- Finding cellular niches in Xenium, MERFISH, CosMx or IMC data without labels (UTAG)\n- Getting region labels to summarise deconvolved compositions or cell types by\n- Checking whether two independent methods agree on the main boundaries\n- Use Step 7 of `spatial-transcriptomics-cell-type-annotation` instead when cells are already annotated and niches should be defined by cell type mix\n- For neighbourhood enrichment or spatially variable genes, use `spatial-transcriptomics-analysis-squidpy`\n\n## Prerequisites\n\n- **Input**: raw counts in `X` (or `layers[\"counts\"]`) and coordinates in `obsm[\"spatial\"]`\n- **SpaGCN**: pulls torch. Its Louvain init needs `louvain`, which has no Python 3.13\n  conda build or wheel and cannot be compiled here; without it use the k-means init (Step 3)\n- **GraphST**: pulls torch; a CUDA GPU makes training ~10x faster; the dense\n  spot-by-spot graph limits it to ~30k observations\n- **UTAG**: not on PyPI; install from GitHub\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 SpaGCN GraphST\npixi add --pypi \"utag @ git+https:\u002F\u002Fgithub.com\u002FElementoLab\u002Futag.git@main\"\n```\n\n## Workflow\n\n1. Load Visium data (or your own)\n2. Preprocess\n3. SpaGCN domains (spots, with histology)\n4. GraphST domains (spots or cells)\n5. UTAG domains (single-cell resolution)\n6. Compare methods and characterise domains\n\n### Step 1: Load Visium Data\n\nFor your own Space Ranger output set `OUTS` to the `outs\u002F` folder and skip the\ndownload. The demo is the 10x mouse brain (sagittal anterior) section.\n\n```python\nimport json\nimport tarfile\nimport urllib.request\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nimport scanpy as sc\n\nCACHE = Path(\"data_cache\u002FV1_Mouse_Brain_Sagittal_Anterior\")\nBASE = (\"https:\u002F\u002Fcf.10xgenomics.com\u002Fsamples\u002Fspatial-exp\u002F1.1.0\u002FV1_Mouse_Brain_Sagittal_Anterior\u002F\"\n        \"V1_Mouse_Brain_Sagittal_Anterior_\")\nCACHE.mkdir(parents=True, exist_ok=True)\nfor name in [\"filtered_feature_bc_matrix.h5\", \"spatial.tar.gz\"]:\n    if not (CACHE \u002F name).exists():\n        urllib.request.urlretrieve(BASE + name, CACHE \u002F name)          # ~20 MB + ~9 MB\nif not (CACHE \u002F \"spatial\").exists():\n    with tarfile.open(CACHE \u002F \"spatial.tar.gz\") as tar:\n        tar.extractall(CACHE, filter=\"data\")\nOUTS = CACHE                                    # your data: Path(\"path\u002Fto\u002Fouts\")\n\nSPATIAL_DIR = OUTS \u002F \"spatial\"\nadata = sc.read_10x_h5(OUTS \u002F \"filtered_feature_bc_matrix.h5\")\nadata.var_names_make_unique()\ncols = [\"in_tissue\", \"array_row\", \"array_col\", \"pxl_row\", \"pxl_col\"]\nif (SPATIAL_DIR \u002F \"tissue_positions.csv\").exists():                    # Space Ranger >= 2.0\n    pos = pd.read_csv(SPATIAL_DIR \u002F \"tissue_positions.csv\", index_col=0)\n    pos.columns = cols\nelse:                                                                   # older, no header\n    pos = pd.read_csv(SPATIAL_DIR \u002F \"tissue_positions_list.csv\", header=None, index_col=0, names=cols)\nadata.obs = adata.obs.join(pos, how=\"left\")\nadata.obsm[\"spatial\"] = adata.obs[[\"pxl_col\", \"pxl_row\"]].to_numpy(float)   # x, y in full-res pixels\nscale = json.loads((SPATIAL_DIR \u002F \"scalefactors_json.json\").read_text())\nprint(adata)\n```\n\n### Step 2: Preprocess\n\n```python\nadata.var[\"mt\"] = adata.var_names.str.upper().str.startswith(\"MT-\")\nsc.pp.calculate_qc_metrics(adata, qc_vars=[\"mt\"], inplace=True)\nsc.pp.filter_cells(adata, min_counts=500)       # Visium; use ~10 for imaging panels\nsc.pp.filter_genes(adata, min_cells=10)\nadata.layers[\"counts\"] = adata.X.copy()         # SpaGCN and GraphST start from counts\nsc.pp.normalize_total(adata)\nsc.pp.log1p(adata)\nprint(f\"{adata.n_obs} spots, {adata.n_vars} genes, median mt% {adata.obs['pct_counts_mt'].median():.1f}\")\n```\n\n### Step 3: SpaGCN (Visium with H&E)\n\nSpaGCN smooths expression over a graph whose edges combine spot distance and\nhistology colour, then clusters with a graph convolutional network. Coordinates\npassed with the image must be **(image row, image column)** at the image's\nscale.\n\n```python\nimport random\n\nimport SpaGCN as spg\nimport torch\nfrom PIL import Image\n\nN_DOMAINS = 7\nUSE_HISTOLOGY = True\n\nsp = adata.copy()\nsp.X = sp.layers[\"counts\"].toarray()            # dense: SpaGCN calls .A on sparse, removed in scipy>=1.14\nhires = scale[\"tissue_hires_scalef\"]\nx_pix = (sp.obs[\"pxl_row\"] * hires).round().astype(int).to_numpy()   # image row\ny_pix = (sp.obs[\"pxl_col\"] * hires).round().astype(int).to_numpy()   # image column\nif USE_HISTOLOGY:\n    img = np.array(Image.open(SPATIAL_DIR \u002F \"tissue_hires_image.png\").convert(\"RGB\"))\n    beta = max(3, int(scale[\"spot_diameter_fullres\"] * hires))       # spot size in hires pixels\n    adj = spg.calculate_adj_matrix(x=x_pix, y=y_pix, x_pixel=x_pix, y_pixel=y_pix,\n                                   image=img, beta=beta, alpha=1, histology=True)\nelse:\n    adj = spg.calculate_adj_matrix(x=x_pix, y=y_pix, histology=False)\n\nspg.prefilter_genes(sp, min_cells=3)\nspg.prefilter_specialgenes(sp)                  # drops ERCC \u002F MT- genes\nsc.pp.normalize_total(sp)\nsc.pp.log1p(sp)\n\nl = spg.search_l(0.5, adj, start=0.01, end=1000, tol=0.01, max_run=100)   # p=0.5\nr_seed = t_seed = n_seed = 100\nres = spg.search_res(sp, adj, l, N_DOMAINS, start=0.7, step=0.1, tol=5e-3, lr=0.05,\n                     max_epochs=20, r_seed=r_seed, t_seed=t_seed, n_seed=n_seed)\nrandom.seed(r_seed); torch.manual_seed(t_seed); np.random.seed(n_seed)\nclf = spg.SpaGCN()\nclf.set_l(l)\nclf.train(sp, adj, init_spa=True, init=\"louvain\", res=res, tol=5e-3, lr=0.05, max_epochs=200)\ny_pred, prob = clf.predict()\nadata.obs[\"spagcn\"] = pd.Categorical(y_pred.astype(str))\n\n# Refinement: relabel a spot when most of its ring disagrees (spot grids only)\nadj_2d = spg.calculate_adj_matrix(x=sp.obs[\"array_row\"].to_numpy(), y=sp.obs[\"array_col\"].to_numpy(),\n                                  histology=False)\nrefined = spg.refine(sample_id=sp.obs_names.tolist(), pred=y_pred.tolist(), dis=adj_2d, shape=\"hexagon\")\nadata.obs[\"spagcn_refined\"] = pd.Categorical(np.asarray(refined).astype(str))\nprint(adata.obs[\"spagcn_refined\"].value_counts())\n```\n\nWithout `louvain`, skip `search_res` and initialise with k-means:\n`clf.train(sp, adj, init_spa=True, init=\"kmeans\", n_clusters=N_DOMAINS, tol=5e-3, lr=0.05, max_epochs=200)`.\n\n`shape=\"hexagon\"` for Visium, `\"square\"` for legacy ST. Raise `alpha` to give\nhistology more weight; set `USE_HISTOLOGY = False` when the image is missing or\npoorly registered.\n\n### Step 4: GraphST\n\nGraphST learns a spatially smoothed embedding by contrasting the real graph\nwith a corrupted one, then clusters it. Give it raw counts: it selects 3,000\nHVGs (seurat_v3), normalises, log-transforms and scales internally.\n\n```python\nimport torch\nfrom GraphST import GraphST\nfrom GraphST.utils import clustering\n\ngst = sc.AnnData(adata.layers[\"counts\"].copy(), obs=adata.obs[[]].copy(), var=adata.var[[]].copy())\ngst.obsm[\"spatial\"] = adata.obsm[\"spatial\"].copy()\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n# datatype: \"10X\" (spot grids, imaging cells); \"Slide\" or \"Stereo\" for Slide-seq \u002F Stereo-seq (KNN graph)\nmodel = GraphST.GraphST(gst, device=device, random_seed=42, datatype=\"10X\")\ngst = model.train()                             # 600 epochs; embedding in obsm[\"emb\"]\n\n# Scans Leiden resolution from `end` down to `start` until exactly N_DOMAINS clusters appear\nclustering(gst, n_clusters=N_DOMAINS, radius=50, method=\"leiden\",\n           start=0.1, end=2.0, increment=0.01, refinement=False)\nadata.obs[\"graphst\"] = pd.Categorical(gst.obs[\"domain\"].astype(str).to_numpy())\nadata.obsm[\"graphst_emb\"] = gst.obsm[\"emb\"]\nprint(adata.obs[\"graphst\"].value_counts())\n```\n\nThe GraphST authors recommend `method=\"mclust\"` (needs R with the `mclust`\npackage and `rpy2`); `refinement=True` relabels each observation by its\n`radius` nearest neighbours.\n\n### Step 5: UTAG (Single-Cell Resolution)\n\nUTAG averages each cell's expression over neighbours within `max_dist`, then\nclusters. Input: one `.h5ad` of cells with log-normalised `X` and\n`obsm[\"spatial\"]` in microns (e.g. the output of\n`spatial-transcriptomics-cell-type-annotation`).\n\n```python\nfrom scipy.spatial import cKDTree\nfrom sklearn.neighbors import NearestNeighbors\nfrom utag import utag\n\ncells = sc.read_h5ad(\"celltype_annotated.h5ad\")\nSLIDE_KEY = None                     # obs column with sample\u002Fsection IDs, if several\nMIN_NICHES, MIN_CLUSTER_SIZE = 5, 100\n\n# max_dist: radius where a typical cell has ~3 neighbours (estimated per slide)\nslides = cells.obs[SLIDE_KEY].unique() if SLIDE_KEY else [None]\nd3 = []\nfor s in slides:\n    xy = cells.obsm[\"spatial\"] if s is None else cells[cells.obs[SLIDE_KEY] == s].obsm[\"spatial\"]\n    d3.append(cKDTree(xy).query(xy[:20000], k=4)[0][:, 3])\nMAX_DIST = float(np.ceil(np.median(np.concatenate(d3))))\nprint(f\"max_dist = {MAX_DIST}\")\n\nfor resolution in [0.05, 0.1, 0.3, 0.5]:          # coarsest resolution giving enough niches\n    out = utag(cells, slide_key=SLIDE_KEY, max_dist=MAX_DIST, normalization_mode=\"l1_norm\",\n               apply_umap=False, apply_clustering=True, clustering_method=[\"leiden\"],\n               resolutions=[resolution])\n    key = f\"UTAG Label_leiden_{resolution}\"\n    print(resolution, out.obs[key].nunique())\n    if out.obs[key].nunique() >= MIN_NICHES:\n        break\n\n# Merge clusters smaller than MIN_CLUSTER_SIZE (within each slide) into the nearest larger one\nlab = out.obs[key].astype(str).copy()\nfor s in slides:\n    m = np.ones(out.n_obs, bool) if s is None else (out.obs[SLIDE_KEY] == s).to_numpy()\n    counts = lab[m].value_counts()\n    small = lab[m].isin(counts[counts \u003C MIN_CLUSTER_SIZE].index).to_numpy()\n    if small.any() and (~small).any():\n        xy = out.obsm[\"spatial\"][m]\n        nn = NearestNeighbors(n_neighbors=1).fit(xy[~small])\n        idx = nn.kneighbors(xy[small], return_distance=False).ravel()\n        lab.iloc[np.flatnonzero(m)[small]] = lab[m].to_numpy()[~small][idx]\ncells.obs[\"utag\"] = pd.Categorical(lab.reindex(cells.obs_names))   # utag may reorder cells by slide\nprint(cells.obs[\"utag\"].value_counts())\n```\n\n### Step 6: Compare Methods and Characterise Domains\n\n```python\nfrom sklearn.metrics import adjusted_rand_score\n\nari = adjusted_rand_score(adata.obs[\"spagcn_refined\"], adata.obs[\"graphst\"])\nprint(f\"SpaGCN vs GraphST ARI: {ari:.2f}\")      # > ~0.5: the main boundaries agree\nprint(pd.crosstab(adata.obs[\"spagcn_refined\"], adata.obs[\"graphst\"]))\n\nimport matplotlib.pyplot as plt\n\naxes = sc.pl.embedding(adata, basis=\"spatial\", color=[\"spagcn_refined\", \"graphst\"], size=1.5, show=False)\nfor ax in axes:\n    ax.invert_yaxis()                            # pixel y grows downwards\nplt.savefig(\"domains_spatial.png\", dpi=150, bbox_inches=\"tight\")\n\nDOMAIN = \"spagcn_refined\"\nsc.tl.rank_genes_groups(adata, DOMAIN, method=\"wilcoxon\")\nmarkers = sc.get.rank_genes_groups_df(adata, group=None)\nmarkers.to_csv(\"domain_markers.csv\", index=False)\ntop = (markers[markers[\"logfoldchanges\"] > 0].groupby(\"group\").head(8)\n       .groupby(\"group\")[\"names\"].apply(\", \".join))\nprint(top)\nadata.obs[[\"spagcn\", \"spagcn_refined\", \"graphst\"]].to_csv(\"spatial_domains.csv\")\nadata.write_h5ad(\"spatial_domains.h5ad\", compression=\"gzip\")\n```\n\nName domains from their markers (e.g. `Mbp` \u002F `Plp1` = white matter, layer\nmarkers in cortex). If cell type labels or cell2location abundances exist,\n`pd.crosstab(domain, cell_type, normalize=\"index\")` shows what each domain is\nmade of. With an expert annotation, report ARI against it instead.\n\n## Key Parameters\n\n| Parameter | Default | Effect |\n|---|---|---|\n| `N_DOMAINS` | 7 | Target number of domains (SpaGCN, GraphST); try 5-15 and compare |\n| SpaGCN `p` (`search_l`) | 0.5 | Share of expression taken from neighbours; higher = smoother domains |\n| SpaGCN `alpha` | 1 | Weight of histology colour in the graph |\n| SpaGCN `shape` | `\"hexagon\"` | Neighbour ring used in refinement (`\"square\"` for ST) |\n| GraphST `datatype` | `\"10X\"` | `\"Slide\"` \u002F `\"Stereo\"` switch to a KNN graph for dense data |\n| GraphST `radius` | 50 | Neighbours used when `refinement=True` |\n| UTAG `max_dist` | auto (~3 neighbours) | Averaging radius in coordinate units; larger = coarser niches |\n| UTAG `resolutions` | 0.05-0.5 | Leiden resolution on the averaged expression |\n| `MIN_CLUSTER_SIZE` | 100 | Smaller UTAG clusters are merged into the nearest larger one |\n\n## Common Recipes\n\n### Recipe: Choose the Number of Domains\n\n`N_DOMAINS` is a guess unless the anatomy fixes it. Scan k on the GraphST\nembedding and look for a plateau or peak in silhouette:\n\n```python\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import silhouette_score\n\nemb = adata.obsm[\"graphst_emb\"]\nrng = np.random.default_rng(0)\nsub = rng.choice(emb.shape[0], min(emb.shape[0], 5000), replace=False)\nscores = {}\nfor k in range(4, 16):\n    labels = KMeans(k, n_init=10, random_state=0).fit_predict(emb)\n    scores[k] = silhouette_score(emb[sub], labels[sub])\nprint(pd.Series(scores).round(3))\n```\n\nPrefer a k that matches known anatomy over the highest score; report the scan.\n\n### Recipe: What Each Domain Is Made Of\n\nWith cell type labels (single cells) or cell2location abundances (spots):\n\n```python\nDOMAIN = \"spagcn_refined\"\nif \"cell_type\" in adata.obs:\n    comp = pd.crosstab(adata.obs[DOMAIN], adata.obs[\"cell_type\"], normalize=\"index\")\nelse:\n    abund = pd.read_csv(\"cell2location_abundance.csv\", index_col=0).reindex(adata.obs_names)\n    prop = abund.div(abund.sum(axis=1), axis=0)\n    comp = prop.groupby(adata.obs[DOMAIN], observed=True).mean()\ncomp.round(3).to_csv(\"domain_composition.csv\")\nprint(comp.apply(lambda r: \", \".join(f\"{k} {v:.0%}\" for k, v in r.nlargest(3).items()), axis=1))\n```\n\n### Recipe: Domain Boundaries and Interfaces\n\nWhich domains touch, and which spots sit on a boundary (interfaces such as the\ntumour edge are often where the biology is):\n\n```python\nimport squidpy as sq\n\nsq.gr.spatial_neighbors(adata, coord_type=\"grid\", n_rings=1)   # imaging cells: coord_type=\"generic\", n_neighs=10\nA = adata.obsp[\"spatial_connectivities\"].tocoo()\nlab = adata.obs[DOMAIN].astype(str).to_numpy()\nedges = pd.DataFrame({\"a\": lab[A.row], \"b\": lab[A.col]})\ntouch = pd.crosstab(edges[\"a\"], edges[\"b\"])\nprint(touch)                                       # off-diagonal counts = shared boundary length\n\ndiff = lab[A.row] != lab[A.col]\nboundary = np.zeros(adata.n_obs, bool)\nboundary[A.row[diff]] = True\nadata.obs[\"domain_boundary\"] = boundary\nprint(f\"boundary spots: {boundary.mean():.0%}\")\n```\n\n## Expected Outputs\n\n- `spatial_domains.csv` - `spagcn`, `spagcn_refined`, `graphst` labels per spot\n- `spatial_domains.h5ad` - data with domain labels and `obsm[\"graphst_emb\"]`\n- `domain_markers.csv` - Wilcoxon markers per domain\n- `domains_spatial.png` - domain maps on tissue coordinates\n- `domain_composition.csv` - cell type mix per domain (recipe)\n\n## Troubleshooting\n\n| Problem | Cause | Fix |\n|---|---|---|\n| SpaGCN `UnboundLocalError: y_pred` | `init` other than `\"louvain\"` \u002F `\"kmeans\"` | Use `init=\"louvain\"` (needs `louvain`) or `init=\"kmeans\"` with `n_clusters` |\n| SpaGCN `AttributeError: ... has no attribute 'A'` | Sparse `X` with scipy >= 1.14 | Densify `X` before SpaGCN (Step 3 does) |\n| SpaGCN domains ignore the tissue image | Coordinates swapped or at full-res scale on the hires image | Pass `pxl_row`\u002F`pxl_col` scaled by `tissue_hires_scalef`, row first |\n| GraphST `AssertionError` in clustering | No Leiden resolution gives exactly `n_clusters` | Widen `end` (e.g. 3.0), change `N_DOMAINS` by 1, or use `mclust` |\n| GraphST out of memory | Dense n x n adjacency | Use UTAG for >30k cells, or run per region |\n| GraphST fails on a targeted panel (\u003C 3,000 genes) | Internal `n_top_genes=3000` | Set `gst.var[\"highly_variable\"] = True`, then normalise, log1p and scale yourself before `GraphST.GraphST` |\n| UTAG gives one huge niche | `max_dist` too large | Lower `max_dist` or raise resolution |\n| Fragmented, salt-and-pepper domains | Too little spatial smoothing | Raise SpaGCN `p`, use refinement, or raise UTAG `max_dist` |\n\n## Related Skills\n\n- `spatial-transcriptomics-cell-type-annotation` - cell labels; its Step 7 builds composition niches\n- `spatial-transcriptomics-deconvolution-cell2location` - cell type abundance per spot to interpret domains\n- `spatial-transcriptomics-analysis-squidpy` - neighbourhood enrichment, co-occurrence, spatially variable genes\n- `spatial-transcriptomics-cell-cell-communication` - signalling between cell types inside or across domains\n- `trajectory-inference` - pseudotime within a domain\n\n## References\n\n- Hu et al. (2021) SpaGCN, Nature Methods: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41592-021-01255-8\n- Long et al. (2023) GraphST, Nature Communications: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41467-023-36796-3\n- Kim et al. (2022) UTAG, Nature Methods: https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41592-022-01657-2\n- SpaGCN source: https:\u002F\u002Fgithub.com\u002Fjianhuupenn\u002FSpaGCN\n- GraphST source: https:\u002F\u002Fgithub.com\u002FJinmiaoChenLab\u002FGraphST\n- UTAG source: https:\u002F\u002Fgithub.com\u002FElementoLab\u002Futag\n",{"name":5,"license":15,"description":7},"master","fd76f882a04e445e899d5cfb2732f2105ea054ee","skills\u002Fawesome-skills\u002Fspatial-domain-detection",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-domain-detection",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill spatial-domain-detection",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill spatial-domain-detection","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fspatial-domain-detection\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",[],[]]