[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EFST8Q0524EJFCK2H60Y97":3,"skill-same:01M7EFST8Q0524EJFCK2H60Y97":62},{"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":30,"commitSha":31,"skillDirectory":32,"forksCount":14,"repositoryHtmlUrl":33,"repositoryHomepageUrl":33,"ownerHtmlUrl":34,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":35,"install":36,"resources":49},"01M7EFST8Q0524EJFCK2H60Y97","bio-spatial-transcriptomics-spatial-statistics",null,"Detects spatially variable genes, spatial autocorrelation, and cell-type colocalization for spatial transcriptomics using Squidpy with PySAL\u002Fesda for local statistics. Use when choosing an SVG method by its null and scaling (SpatialDE\u002FSPARK GP variance-component vs SPARK-X\u002FnnSVG linear vs Moran\u002FGeary graph autocorrelation); separating genes that are spatially variable because of cell-type composition from genes regulated within a cell type; choosing the right autocorrelation statistic (global Moran\u002FGeary vs Getis-Ord hot\u002Fcold spots vs local LISA and its FDR trap); and choosing a colocalization null strong enough to defeat the abundance\u002Fcompartment confound (conditional or toroidal vs the weak Squidpy default permutation).","Mr-Nobody-Anonymous\u002FAll-skills","Mr-Nobody-Anonymous","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184253119?v=4","01M7AEXFJHKTYQW5R0ZCQQTWFV","anonymous","01M7C00M3GQR4QKP9GZA42GFAK",0,"MIT","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-spatial-transcriptomics-spatial-statistics\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-spatial-transcriptomics-spatial-statistics\ndescription: Detects spatially variable genes, spatial autocorrelation, and cell-type colocalization for spatial transcriptomics using Squidpy with PySAL\u002Fesda for local statistics. Use when choosing an SVG method by its null and scaling (SpatialDE\u002FSPARK GP variance-component vs SPARK-X\u002FnnSVG linear vs Moran\u002FGeary graph autocorrelation); separating genes that are spatially variable because of cell-type composition from genes regulated within a cell type; choosing the right autocorrelation statistic (global Moran\u002FGeary vs Getis-Ord hot\u002Fcold spots vs local LISA and its FDR trap); and choosing a colocalization null strong enough to defeat the abundance\u002Fcompartment confound (conditional or toroidal vs the weak Squidpy default permutation).\ntool_type: python\nprimary_tool: squidpy\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"spatial-transcriptomics\u002Fspatial-statistics\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: squidpy 1.4+, scanpy 1.10+, anndata 0.10+, esda 2.5+, libpysal 4.9+ (SPARK, SPARK-X, and nnSVG are R\u002FBioconductor packages)\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n- R: `packageVersion('\u003Cpkg>')` then `?function_name` to verify parameters\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\n# Spatial Statistics\n\n**\"Find spatially variable genes \u002F run Moran's I \u002F test which cell types colocalize\"** -> Quantify spatial structure in expression or in cell-type arrangement against an explicit null model.\n- Python: `squidpy.gr.spatial_autocorr` (Moran\u002FGeary), `squidpy.gr.nhood_enrichment`, `squidpy.gr.co_occurrence`, `esda.Moran_Local`\u002F`esda.getisord.G_Local` (LISA, Getis-Ord)\n- R: SPARK \u002F SPARK-X \u002F nnSVG (SVG), `spdep` (Moran\u002FGeary\u002FGetis-Ord\u002FLISA)\n\n## Governing Principle\n\nTwo reframes decide whether a spatial-statistics result means anything. Both are silent failures: the code runs, the numbers look clean, and the interpretation is wrong.\n\nA \"spatially variable gene\" is not necessarily spatially REGULATED. Moran's I, Geary's C, SPARK-X, and SpatialDE all detect that a gene's expression is spatially autocorrelated -- but a gene that is simply a marker of a spatially clustered cell type scores as \"spatially variable\" with zero cell-intrinsic spatial regulation, purely because the CELL TYPE is spatially organized. A hepatocyte gene in zonated liver, MAG in white matter, KRT17 in epithelium: all top SVGs, none of them regulated in space. This cell-type-driven signal swamps the genuinely interesting cell-type-INDEPENDENT signal (a gene graded across a niche WITHIN one cell type). Sample-wide SVG lists therefore largely re-derive marker genes and overlap heavily with HVGs -- if the SVG list is roughly the HVG list, the spatial test added almost nothing. The interesting question (within-type spatial regulation) needs cell-type-aware methods (C-SIDE, CTSV, CELINA\u002FCelina), which are themselves unsettled and carry their own false positives. Decision: if the question is \"where is tissue organized,\" sample-wide SVG is correct (the cell-type structure IS the answer); if the question is \"which genes are regulated beyond cell identity,\" sample-wide SVG is the WRONG tool -- test within cell type or regress out composition first.\n\nThe null and the graph define the result. Every spatial statistic is computed on a neighbor graph (a weights matrix W) against a null distribution, and both are researcher choices, not properties of the tissue. Change kNN k from 6 to 30 and Moran's I, the enrichment z-scores, and the SVG ranking all move. Change the colocalization null from global label-shuffle to within-compartment and most \"A is near B\" claims evaporate. SVG methods disagree heavily across the literature precisely because each tests a DIFFERENT null (variance-component-zero vs covariance-independence vs graph-autocorrelation-zero) -- that disagreement is expected, not a bug. The honest workflow names the null, names the graph (cross-ref spatial-neighbors), and reports whether a hit survives a second graph or a stronger null.\n\n## Choosing an SVG Method\n\n**Goal:** Pick a spatially-variable-gene test whose null hypothesis and computational scaling match the platform and the biological question.\n\n**Approach:** Match GP variance-component methods to small Gaussian\u002Fcount data, linear-scaling methods to single-cell-resolution data, and treat the SVG list as method-conditional -- cross-method intersection is more trustworthy than any single ranking, though it is small.\n\n| Method | Null it tests | Scaling | Best when | Fails when |\n|--------|---------------|---------|-----------|------------|\n| SpatialDE (GP) | spatial variance component = 0 at the tested length scale | O(n^3); infeasible past ~1e4 locations | Small Visium-scale, Gaussian on log-normalized | Sparse\u002Flow counts violate Gaussian; fixed length-scale grid misses other scales |\n| SPARK (count GLSM) | no pattern matching any of 10 fixed kernels | O(n^3)-ish (PQL); slow at large n | Small count data; want Poisson model, not Gaussian | Pattern unlike its 10 kernels; still cell-type-confounded |\n| SPARK-X | expression covariance independent of location covariance | LINEAR in n and genes | 1e4-1e6 cells (MERFISH\u002FXenium\u002FCosMx) needing scalability | Fixed location kernels miss unusual length scales; low power on small focal hotspots |\n| nnSVG (NNGP) | spatial variance = 0, with a per-gene length scale | LINEAR in n | Length scales genuinely differ across genes; large single-cell data | Still cell-type-confounded; more compute per gene than SPARK-X; needs adequate counts |\n| Moran's I \u002F Geary's C | no autocorrelation on graph W | Fast (sparse W) | Quick screen on an existing neighbor graph | Single fixed scale (the graph); misses multi-focal\u002Fsmall hotspots |\n\nThere is no uniformly best SVG method; power is pattern-specific (SPARK-X, nnSVG, and Moran's I all have LOW power for genes high in small focal areas). Methods evolve fast -- verify the current benchmark before committing. Threshold on EFFECT SIZE (fraction of spatial variance), not p alone: with thousands of cells, trivial autocorrelation reaches tiny p-values.\n\n## Computing Spatial Autocorrelation with Squidpy\n\n**Goal:** Rank genes by graph-based spatial autocorrelation as a fast SVG screen.\n\n**Approach:** Build a neighbor graph, run Moran's I (or Geary's C) per gene with a permutation\u002Fanalytic p-value and FDR, then read effect size before significance.\n\n```python\nimport squidpy as sq\nimport scanpy as sc\n\n# The graph IS the model: k, coord_type, and units all change the result (see spatial-neighbors)\nsq.gr.spatial_neighbors(adata, coord_type='generic', n_neighs=6)   # 6 mimics the Visium hex lattice\n\n# genes=None defaults to highly_variable if present; n_perms adds a permutation null, corr_method applies FDR\nsq.gr.spatial_autocorr(adata, mode='moran', n_perms=100, corr_method='fdr_bh')   # statsmodels name, not 'benjamini-hochberg'\nmoran = adata.uns['moranI']                  # columns: I, pval_norm, pval_norm_fdr_bh, ...\n\n# Threshold on effect size (I) AND FDR, not p alone -- large n makes trivial autocorrelation 'significant'\nsvg = moran[(moran['I'] > 0.1) & (moran['pval_norm_fdr_bh'] \u003C 0.05)].sort_values('I', ascending=False)\n```\n\nA top-ranked SVG here is a hypothesis about spatial structure, NOT evidence of spatial regulation. Before interpreting, compare the SVG list to the HVG list: the overlap is cell-type marker genes; the SVG-not-HVG subset (modest-amplitude gradients) is where spatial information actually lives.\n\n## Choosing an Autocorrelation Statistic\n\n**Goal:** Match the statistic to the spatial question -- \"is this gene clustered\" is a different question from \"where is it HIGH\" and from \"is THIS region a cluster.\"\n\n**Approach:** Use a global statistic for one tissue-wide number, Getis-Ord when the sign (hot vs cold) matters, and local LISA for non-stationary tissue -- but pay the local multiple-testing tax correctly.\n\n| Statistic | Global \u002F local | Hot vs cold? | Use when |\n|-----------|----------------|--------------|----------|\n| Moran's I | global | NO (clustering of like values only) | One number: is this gene spatially structured across the whole section |\n| Geary's C | global | NO | Same as Moran but more sensitive to LOCAL\u002Fshort-range differences; disagreement with Moran is informative |\n| Getis-Ord Gi* | local | YES -- separates high-clusters from low-clusters | \"Where is this gene HIGH\" -- hot\u002Fcold spot mapping |\n| Local Moran \u002F LISA | local | partial (HH\u002FLL\u002FHL\u002FLH quadrants) | Non-stationary tissue: per-location clusters and spatial outliers |\n\nMoran's I and Geary's C cannot tell a hot spot from a cold spot -- both flag \"similar values cluster\" regardless of high or low. Choosing Moran when the question is \"where is this gene HIGH\" is a category error; use Getis-Ord Gi*. A non-significant GLOBAL Moran's I does NOT mean \"no spatial structure\": over heterogeneous tissue, positive autocorrelation in one region cancels negative in another, so use local statistics for non-stationary sections.\n\n```python\nfrom esda.getisord import G_Local\nfrom esda.moran import Moran_Local\nfrom libpysal.weights import KNN\n\ncoords = adata.obsm['spatial']\nw = KNN.from_array(coords, k=6)\nw.transform = 'r'                            # row-standardized; changes the value AND its variance vs binary W\n\ngene = adata[:, 'GENE1'].X.toarray().ravel()\ngi = G_Local(gene, w, transform='B', star=True, permutations=999)   # star=True -> Gi* (includes self); binary weights for Getis-Ord\nlisa = Moran_Local(gene, w, permutations=999)            # conditional-permutation local null\nadata.obs['GENE1_hotspot'] = gi.Zs                       # positive Z = hot spot, negative = cold spot\nadata.obs['GENE1_lisa_q'] = lisa.q                       # 1=HH, 2=LH, 3=LL, 4=HL\n```\n\nLocal statistics carry a DOUBLE trap. There are n tests (one per location), so uncorrected LISA\u002FGi* maps are mostly false positives -- FDR is mandatory, and Anselin recommends stricter base cutoffs (0.01\u002F0.005\u002F0.001), not 0.05. Worse, the local statistics are themselves spatially autocorrelated (adjacent locations share neighbors, so adjacent I_i values are correlated), which violates the independence assumption of standard BH-FDR; the effective number of tests is far below n. Conditional permutation gives the correct local null but does not fix the cross-location dependence. Treat the cluster map as exploratory, not a set of independent discoveries.\n\n## Testing Cell-Type Colocalization\n\n**Goal:** Decide whether two cell types are SPECIFICALLY associated in space, not merely both abundant or both in the same compartment.\n\n**Approach:** Choose a permutation null strong enough to defeat the abundance\u002Fcompartment confound; the Squidpy default answers only the weak question, and a co-occurrence distance profile is more informative than a single z-score.\n\n| Null model | What it permutes | Controls for | Misses |\n|------------|------------------|--------------|--------|\n| Global label permutation (Squidpy `nhood_enrichment` default) | all labels over all positions | graph topology, marginal counts | tissue compartmentalization -- two abundant co-compartment types pass trivially |\n| Conditional \u002F within-compartment permutation | labels within a region only | shared-compartment forcing | cross-compartment questions; the region choice is itself a degree of freedom |\n| Toroidal shift | whole label field translated (wrapped) | each type's first-order density pattern | anisotropy; boundary realism (wrapping a bounded tissue is artificial) |\n| Grid-tile shuffle across scales (CRAWDAD) | labels within tiles of size s | structure above scale s -- isolates colocalization AT scale s | within-tile structure below s |\n\nThe single most common error in spatial-omics papers is reading a positive `nhood_enrichment` z-score as a specific A-B interaction. Under the weak global-permutation null it usually reflects co-compartmentalization plus abundance: two stromal populations, or tumor plus tumor-associated macrophages both in the tumor bed, pass trivially. A specific-affinity claim must SURVIVE a stronger null (conditional\u002Fwithin-compartment, toroidal shift preserving each type's density, or CRAWDAD's scale-explicit tiles). Rare-type enrichment is the least trustworthy: few edges give high-variance, often spuriously large |z| -- be most skeptical exactly where the biology is most exciting (a rare type near the tumor).\n\nFor clustering as a function of distance rather than a single graph z, Ripley's K\u002FL (`squidpy.gr.ripley`, mode `'L'`) counts within-cluster neighbors within radius r against a complete-spatial-randomness expectation, so it reads as clustering vs dispersion ACROSS scale per cell type (squidpy computes the univariate L per cluster; a true bivariate cross-K answering \"are A and B closer than chance, at what radius\" needs a dedicated point-process tool such as spatstat). Its assumptions are the geostatistics ones tissue violates: a bounded, holey, non-stationary window. EDGE CORRECTION is mandatory and usually omitted -- without it, counts near the tissue boundary or a necrotic hole are biased DOWN and read as false depletion, so an ROI with gaps needs an edge-corrected estimator (or restrict analysis to the interior).\n\n```python\nsq.gr.spatial_neighbors(adata, coord_type='generic', delaunay=True)   # nhood_enrichment reuses this stored graph\n\n# Global label-permutation null -- the WEAK question: more adjacent than complete spatial randomness?\nsq.gr.nhood_enrichment(adata, cluster_key='cell_type', n_perms=1000)\nz = adata.uns['cell_type_nhood_enrichment']['zscore']\n\n# co_occurrence gives a DISTANCE PROFILE (at what scale colocalization appears\u002Fvanishes), unlike a single z\nsq.gr.co_occurrence(adata, cluster_key='cell_type')\n```\n\nCellular Neighborhoods (Schurch\u002FNolan: cluster per-cell windows of neighbor composition) have NO inferential null at all -- they are descriptive k-means clusters whose number and window size are user knobs. They are useful summaries but routinely over-read as tested findings; the number of neighborhoods is chosen, not discovered, and identity shifts with window size. Test them downstream (neighborhood composition vs outcome), do not report them as significant in themselves.\n\n## Common Errors\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| Top SVGs are all known cell-type markers; SVG list ~= HVG list | Sample-wide SVG re-derives markers of spatially clustered cell types (cell-type-driven, not regulated) | Ask within-type: regress out cell-type composition or use ctSVG (C-SIDE\u002FCTSV\u002FCELINA); report the SVG-not-HVG subset |\n| Moran's I finds \"clustering\" but cannot locate where the gene is HIGH | Moran\u002FGeary detect clustering of like values, blind to high vs low | Use Getis-Ord Gi* for hot\u002Fcold spots |\n| LISA\u002FGi* map is mostly \"significant\"; thousands of hits | n tests, AND local statistics are spatially autocorrelated so naive BH-FDR is invalid | FDR with stricter cutoffs (0.001); conditional permutation; treat map as exploratory, not independent discoveries |\n| Confident \"cell type A interacts with B\" that vanishes on a second look | Default `nhood_enrichment` global-permutation null only beats complete randomness; abundant co-compartment types pass trivially | Demand survival under a conditional\u002Fwithin-compartment or toroidal null; report abundances |\n| Global Moran's I near zero but tissue is clearly structured | Non-stationarity: opposite-sign local regions cancel in one global number | Use local statistics (LISA\u002FGi*); stratify by region |\n| SVG ranking changes completely between two runs\u002Ftools | Different graph (k, Delaunay vs kNN) or different null -- methods test different hypotheses | Name the graph and null; report graph-robust hits; expect cross-method intersection to be small |\n| Radius\u002Flength-scale statistic gives nonsense | Coordinates in pixels\u002Farray units, parameter in microns; Visium array coords are not microns | Convert to microns via scale factors before any distance parameter (see spatial-neighbors) |\n| Rare cell type shows a huge enrichment z-score | Few edges -> high-variance estimate -> large |z| by chance | Report cell-type abundances; discount enrichment involving rare types |\n\n## Related Skills\n\n- spatial-neighbors - builds the graph W that every statistic here inherits; the choice propagates\n- spatial-domains - region-level structure; a domain is not a colocalization result\n- spatial-communication - ligand-receptor in space; the spillover\u002Fabundance confounds recur there\n- single-cell\u002Fmarkers-annotation - cell-type labels feeding colocalization, and the marker overlap that confounds SVG\n\n## References\n\n- Svensson V, Teichmann SA, Stegle O (2018) SpatialDE: identification of spatially variable genes. Nature Methods 15(5):343-346. DOI 10.1038\u002Fnmeth.4636\n- Sun S, Zhu J, Zhou X (2020) Statistical analysis of spatial expression patterns for spatially resolved transcriptomic studies (SPARK). Nature Methods 17(2):193-200. DOI 10.1038\u002Fs41592-019-0701-7\n- Zhu J, Sun S, Zhou X (2021) SPARK-X: non-parametric modeling enables scalable and robust detection of spatial expression patterns for large spatial transcriptomic studies. Genome Biology 22:184. DOI 10.1186\u002Fs13059-021-02404-0\n- Weber LM, Saha A, Datta A, Hansen KD, Hicks SC (2023) nnSVG for the scalable identification of spatially variable genes using nearest-neighbor Gaussian processes. Nature Communications 14:4059. DOI 10.1038\u002Fs41467-023-39748-z\n- Palla G, Spitzer H, Klein M, et al. (2022) Squidpy: a scalable framework for spatial omics analysis. Nature Methods 19(2):171-178. DOI 10.1038\u002Fs41592-021-01358-2\n- Schurch CM, Bhate SS, Barlow GL, et al. (2020) Coordinated cellular neighborhoods orchestrate antitumoral immunity at the colorectal cancer invasive front. Cell 182(5):1341-1359. DOI 10.1016\u002Fj.cell.2020.07.005\n- Dos Santos Peixoto R, Miller BF, Brusko MA, et al. (2025) Characterizing cell-type spatial relationships across length scales in spatially resolved omics data (CRAWDAD). Nature Communications 16:350. DOI 10.1038\u002Fs41467-024-55700-1\n- Moran PAP (1950) Notes on continuous stochastic phenomena. Biometrika 37(1\u002F2):17-23. DOI 10.2307\u002F2332142\n- Geary RC (1954) The contiguity ratio and statistical mapping. The Incorporated Statistician 5(3):115-145. DOI 10.2307\u002F2986645\n- Getis A, Ord JK (1992) The analysis of spatial association by use of distance statistics. Geographical Analysis 24(3):189-206. DOI 10.1111\u002Fj.1538-4632.1992.tb00261.x\n- Anselin L (1995) Local indicators of spatial association -- LISA. Geographical Analysis 27(2):93-115. DOI 10.1111\u002Fj.1538-4632.1995.tb00338.x\n","## Version Compatibility\n\nReference examples tested with: squidpy 1.4+, scanpy 1.10+, anndata 0.10+, esda 2.5+, libpysal 4.9+ (SPARK, SPARK-X, and nnSVG are R\u002FBioconductor packages)\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n- R: `packageVersion('\u003Cpkg>')` then `?function_name` to verify parameters\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\n# Spatial Statistics\n\n**\"Find spatially variable genes \u002F run Moran's I \u002F test which cell types colocalize\"** -> Quantify spatial structure in expression or in cell-type arrangement against an explicit null model.\n- Python: `squidpy.gr.spatial_autocorr` (Moran\u002FGeary), `squidpy.gr.nhood_enrichment`, `squidpy.gr.co_occurrence`, `esda.Moran_Local`\u002F`esda.getisord.G_Local` (LISA, Getis-Ord)\n- R: SPARK \u002F SPARK-X \u002F nnSVG (SVG), `spdep` (Moran\u002FGeary\u002FGetis-Ord\u002FLISA)\n\n## Governing Principle\n\nTwo reframes decide whether a spatial-statistics result means anything. Both are silent failures: the code runs, the numbers look clean, and the interpretation is wrong.\n\nA \"spatially variable gene\" is not necessarily spatially REGULATED. Moran's I, Geary's C, SPARK-X, and SpatialDE all detect that a gene's expression is spatially autocorrelated -- but a gene that is simply a marker of a spatially clustered cell type scores as \"spatially variable\" with zero cell-intrinsic spatial regulation, purely because the CELL TYPE is spatially organized. A hepatocyte gene in zonated liver, MAG in white matter, KRT17 in epithelium: all top SVGs, none of them regulated in space. This cell-type-driven signal swamps the genuinely interesting cell-type-INDEPENDENT signal (a gene graded across a niche WITHIN one cell type). Sample-wide SVG lists therefore largely re-derive marker genes and overlap heavily with HVGs -- if the SVG list is roughly the HVG list, the spatial test added almost nothing. The interesting question (within-type spatial regulation) needs cell-type-aware methods (C-SIDE, CTSV, CELINA\u002FCelina), which are themselves unsettled and carry their own false positives. Decision: if the question is \"where is tissue organized,\" sample-wide SVG is correct (the cell-type structure IS the answer); if the question is \"which genes are regulated beyond cell identity,\" sample-wide SVG is the WRONG tool -- test within cell type or regress out composition first.\n\nThe null and the graph define the result. Every spatial statistic is computed on a neighbor graph (a weights matrix W) against a null distribution, and both are researcher choices, not properties of the tissue. Change kNN k from 6 to 30 and Moran's I, the enrichment z-scores, and the SVG ranking all move. Change the colocalization null from global label-shuffle to within-compartment and most \"A is near B\" claims evaporate. SVG methods disagree heavily across the literature precisely because each tests a DIFFERENT null (variance-component-zero vs covariance-independence vs graph-autocorrelation-zero) -- that disagreement is expected, not a bug. The honest workflow names the null, names the graph (cross-ref spatial-neighbors), and reports whether a hit survives a second graph or a stronger null.\n\n## Choosing an SVG Method\n\n**Goal:** Pick a spatially-variable-gene test whose null hypothesis and computational scaling match the platform and the biological question.\n\n**Approach:** Match GP variance-component methods to small Gaussian\u002Fcount data, linear-scaling methods to single-cell-resolution data, and treat the SVG list as method-conditional -- cross-method intersection is more trustworthy than any single ranking, though it is small.\n\n| Method | Null it tests | Scaling | Best when | Fails when |\n|--------|---------------|---------|-----------|------------|\n| SpatialDE (GP) | spatial variance component = 0 at the tested length scale | O(n^3); infeasible past ~1e4 locations | Small Visium-scale, Gaussian on log-normalized | Sparse\u002Flow counts violate Gaussian; fixed length-scale grid misses other scales |\n| SPARK (count GLSM) | no pattern matching any of 10 fixed kernels | O(n^3)-ish (PQL); slow at large n | Small count data; want Poisson model, not Gaussian | Pattern unlike its 10 kernels; still cell-type-confounded |\n| SPARK-X | expression covariance independent of location covariance | LINEAR in n and genes | 1e4-1e6 cells (MERFISH\u002FXenium\u002FCosMx) needing scalability | Fixed location kernels miss unusual length scales; low power on small focal hotspots |\n| nnSVG (NNGP) | spatial variance = 0, with a per-gene length scale | LINEAR in n | Length scales genuinely differ across genes; large single-cell data | Still cell-type-confounded; more compute per gene than SPARK-X; needs adequate counts |\n| Moran's I \u002F Geary's C | no autocorrelation on graph W | Fast (sparse W) | Quick screen on an existing neighbor graph | Single fixed scale (the graph); misses multi-focal\u002Fsmall hotspots |\n\nThere is no uniformly best SVG method; power is pattern-specific (SPARK-X, nnSVG, and Moran's I all have LOW power for genes high in small focal areas). Methods evolve fast -- verify the current benchmark before committing. Threshold on EFFECT SIZE (fraction of spatial variance), not p alone: with thousands of cells, trivial autocorrelation reaches tiny p-values.\n\n## Computing Spatial Autocorrelation with Squidpy\n\n**Goal:** Rank genes by graph-based spatial autocorrelation as a fast SVG screen.\n\n**Approach:** Build a neighbor graph, run Moran's I (or Geary's C) per gene with a permutation\u002Fanalytic p-value and FDR, then read effect size before significance.\n\n```python\nimport squidpy as sq\nimport scanpy as sc\n\n# The graph IS the model: k, coord_type, and units all change the result (see spatial-neighbors)\nsq.gr.spatial_neighbors(adata, coord_type='generic', n_neighs=6)   # 6 mimics the Visium hex lattice\n\n# genes=None defaults to highly_variable if present; n_perms adds a permutation null, corr_method applies FDR\nsq.gr.spatial_autocorr(adata, mode='moran', n_perms=100, corr_method='fdr_bh')   # statsmodels name, not 'benjamini-hochberg'\nmoran = adata.uns['moranI']                  # columns: I, pval_norm, pval_norm_fdr_bh, ...\n\n# Threshold on effect size (I) AND FDR, not p alone -- large n makes trivial autocorrelation 'significant'\nsvg = moran[(moran['I'] > 0.1) & (moran['pval_norm_fdr_bh'] \u003C 0.05)].sort_values('I', ascending=False)\n```\n\nA top-ranked SVG here is a hypothesis about spatial structure, NOT evidence of spatial regulation. Before interpreting, compare the SVG list to the HVG list: the overlap is cell-type marker genes; the SVG-not-HVG subset (modest-amplitude gradients) is where spatial information actually lives.\n\n## Choosing an Autocorrelation Statistic\n\n**Goal:** Match the statistic to the spatial question -- \"is this gene clustered\" is a different question from \"where is it HIGH\" and from \"is THIS region a cluster.\"\n\n**Approach:** Use a global statistic for one tissue-wide number, Getis-Ord when the sign (hot vs cold) matters, and local LISA for non-stationary tissue -- but pay the local multiple-testing tax correctly.\n\n| Statistic | Global \u002F local | Hot vs cold? | Use when |\n|-----------|----------------|--------------|----------|\n| Moran's I | global | NO (clustering of like values only) | One number: is this gene spatially structured across the whole section |\n| Geary's C | global | NO | Same as Moran but more sensitive to LOCAL\u002Fshort-range differences; disagreement with Moran is informative |\n| Getis-Ord Gi* | local | YES -- separates high-clusters from low-clusters | \"Where is this gene HIGH\" -- hot\u002Fcold spot mapping |\n| Local Moran \u002F LISA | local | partial (HH\u002FLL\u002FHL\u002FLH quadrants) | Non-stationary tissue: per-location clusters and spatial outliers |\n\nMoran's I and Geary's C cannot tell a hot spot from a cold spot -- both flag \"similar values cluster\" regardless of high or low. Choosing Moran when the question is \"where is this gene HIGH\" is a category error; use Getis-Ord Gi*. A non-significant GLOBAL Moran's I does NOT mean \"no spatial structure\": over heterogeneous tissue, positive autocorrelation in one region cancels negative in another, so use local statistics for non-stationary sections.\n\n```python\nfrom esda.getisord import G_Local\nfrom esda.moran import Moran_Local\nfrom libpysal.weights import KNN\n\ncoords = adata.obsm['spatial']\nw = KNN.from_array(coords, k=6)\nw.transform = 'r'                            # row-standardized; changes the value AND its variance vs binary W\n\ngene = adata[:, 'GENE1'].X.toarray().ravel()\ngi = G_Local(gene, w, transform='B', star=True, permutations=999)   # star=True -> Gi* (includes self); binary weights for Getis-Ord\nlisa = Moran_Local(gene, w, permutations=999)            # conditional-permutation local null\nadata.obs['GENE1_hotspot'] = gi.Zs                       # positive Z = hot spot, negative = cold spot\nadata.obs['GENE1_lisa_q'] = lisa.q                       # 1=HH, 2=LH, 3=LL, 4=HL\n```\n\nLocal statistics carry a DOUBLE trap. There are n tests (one per location), so uncorrected LISA\u002FGi* maps are mostly false positives -- FDR is mandatory, and Anselin recommends stricter base cutoffs (0.01\u002F0.005\u002F0.001), not 0.05. Worse, the local statistics are themselves spatially autocorrelated (adjacent locations share neighbors, so adjacent I_i values are correlated), which violates the independence assumption of standard BH-FDR; the effective number of tests is far below n. Conditional permutation gives the correct local null but does not fix the cross-location dependence. Treat the cluster map as exploratory, not a set of independent discoveries.\n\n## Testing Cell-Type Colocalization\n\n**Goal:** Decide whether two cell types are SPECIFICALLY associated in space, not merely both abundant or both in the same compartment.\n\n**Approach:** Choose a permutation null strong enough to defeat the abundance\u002Fcompartment confound; the Squidpy default answers only the weak question, and a co-occurrence distance profile is more informative than a single z-score.\n\n| Null model | What it permutes | Controls for | Misses |\n|------------|------------------|--------------|--------|\n| Global label permutation (Squidpy `nhood_enrichment` default) | all labels over all positions | graph topology, marginal counts | tissue compartmentalization -- two abundant co-compartment types pass trivially |\n| Conditional \u002F within-compartment permutation | labels within a region only | shared-compartment forcing | cross-compartment questions; the region choice is itself a degree of freedom |\n| Toroidal shift | whole label field translated (wrapped) | each type's first-order density pattern | anisotropy; boundary realism (wrapping a bounded tissue is artificial) |\n| Grid-tile shuffle across scales (CRAWDAD) | labels within tiles of size s | structure above scale s -- isolates colocalization AT scale s | within-tile structure below s |\n\nThe single most common error in spatial-omics papers is reading a positive `nhood_enrichment` z-score as a specific A-B interaction. Under the weak global-permutation null it usually reflects co-compartmentalization plus abundance: two stromal populations, or tumor plus tumor-associated macrophages both in the tumor bed, pass trivially. A specific-affinity claim must SURVIVE a stronger null (conditional\u002Fwithin-compartment, toroidal shift preserving each type's density, or CRAWDAD's scale-explicit tiles). Rare-type enrichment is the least trustworthy: few edges give high-variance, often spuriously large |z| -- be most skeptical exactly where the biology is most exciting (a rare type near the tumor).\n\nFor clustering as a function of distance rather than a single graph z, Ripley's K\u002FL (`squidpy.gr.ripley`, mode `'L'`) counts within-cluster neighbors within radius r against a complete-spatial-randomness expectation, so it reads as clustering vs dispersion ACROSS scale per cell type (squidpy computes the univariate L per cluster; a true bivariate cross-K answering \"are A and B closer than chance, at what radius\" needs a dedicated point-process tool such as spatstat). Its assumptions are the geostatistics ones tissue violates: a bounded, holey, non-stationary window. EDGE CORRECTION is mandatory and usually omitted -- without it, counts near the tissue boundary or a necrotic hole are biased DOWN and read as false depletion, so an ROI with gaps needs an edge-corrected estimator (or restrict analysis to the interior).\n\n```python\nsq.gr.spatial_neighbors(adata, coord_type='generic', delaunay=True)   # nhood_enrichment reuses this stored graph\n\n# Global label-permutation null -- the WEAK question: more adjacent than complete spatial randomness?\nsq.gr.nhood_enrichment(adata, cluster_key='cell_type', n_perms=1000)\nz = adata.uns['cell_type_nhood_enrichment']['zscore']\n\n# co_occurrence gives a DISTANCE PROFILE (at what scale colocalization appears\u002Fvanishes), unlike a single z\nsq.gr.co_occurrence(adata, cluster_key='cell_type')\n```\n\nCellular Neighborhoods (Schurch\u002FNolan: cluster per-cell windows of neighbor composition) have NO inferential null at all -- they are descriptive k-means clusters whose number and window size are user knobs. They are useful summaries but routinely over-read as tested findings; the number of neighborhoods is chosen, not discovered, and identity shifts with window size. Test them downstream (neighborhood composition vs outcome), do not report them as significant in themselves.\n\n## Common Errors\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| Top SVGs are all known cell-type markers; SVG list ~= HVG list | Sample-wide SVG re-derives markers of spatially clustered cell types (cell-type-driven, not regulated) | Ask within-type: regress out cell-type composition or use ctSVG (C-SIDE\u002FCTSV\u002FCELINA); report the SVG-not-HVG subset |\n| Moran's I finds \"clustering\" but cannot locate where the gene is HIGH | Moran\u002FGeary detect clustering of like values, blind to high vs low | Use Getis-Ord Gi* for hot\u002Fcold spots |\n| LISA\u002FGi* map is mostly \"significant\"; thousands of hits | n tests, AND local statistics are spatially autocorrelated so naive BH-FDR is invalid | FDR with stricter cutoffs (0.001); conditional permutation; treat map as exploratory, not independent discoveries |\n| Confident \"cell type A interacts with B\" that vanishes on a second look | Default `nhood_enrichment` global-permutation null only beats complete randomness; abundant co-compartment types pass trivially | Demand survival under a conditional\u002Fwithin-compartment or toroidal null; report abundances |\n| Global Moran's I near zero but tissue is clearly structured | Non-stationarity: opposite-sign local regions cancel in one global number | Use local statistics (LISA\u002FGi*); stratify by region |\n| SVG ranking changes completely between two runs\u002Ftools | Different graph (k, Delaunay vs kNN) or different null -- methods test different hypotheses | Name the graph and null; report graph-robust hits; expect cross-method intersection to be small |\n| Radius\u002Flength-scale statistic gives nonsense | Coordinates in pixels\u002Farray units, parameter in microns; Visium array coords are not microns | Convert to microns via scale factors before any distance parameter (see spatial-neighbors) |\n| Rare cell type shows a huge enrichment z-score | Few edges -> high-variance estimate -> large |z| by chance | Report cell-type abundances; discount enrichment involving rare types |\n\n## Related Skills\n\n- spatial-neighbors - builds the graph W that every statistic here inherits; the choice propagates\n- spatial-domains - region-level structure; a domain is not a colocalization result\n- spatial-communication - ligand-receptor in space; the spillover\u002Fabundance confounds recur there\n- single-cell\u002Fmarkers-annotation - cell-type labels feeding colocalization, and the marker overlap that confounds SVG\n\n## References\n\n- Svensson V, Teichmann SA, Stegle O (2018) SpatialDE: identification of spatially variable genes. Nature Methods 15(5):343-346. DOI 10.1038\u002Fnmeth.4636\n- Sun S, Zhu J, Zhou X (2020) Statistical analysis of spatial expression patterns for spatially resolved transcriptomic studies (SPARK). Nature Methods 17(2):193-200. DOI 10.1038\u002Fs41592-019-0701-7\n- Zhu J, Sun S, Zhou X (2021) SPARK-X: non-parametric modeling enables scalable and robust detection of spatial expression patterns for large spatial transcriptomic studies. Genome Biology 22:184. DOI 10.1186\u002Fs13059-021-02404-0\n- Weber LM, Saha A, Datta A, Hansen KD, Hicks SC (2023) nnSVG for the scalable identification of spatially variable genes using nearest-neighbor Gaussian processes. Nature Communications 14:4059. DOI 10.1038\u002Fs41467-023-39748-z\n- Palla G, Spitzer H, Klein M, et al. (2022) Squidpy: a scalable framework for spatial omics analysis. Nature Methods 19(2):171-178. DOI 10.1038\u002Fs41592-021-01358-2\n- Schurch CM, Bhate SS, Barlow GL, et al. (2020) Coordinated cellular neighborhoods orchestrate antitumoral immunity at the colorectal cancer invasive front. Cell 182(5):1341-1359. DOI 10.1016\u002Fj.cell.2020.07.005\n- Dos Santos Peixoto R, Miller BF, Brusko MA, et al. (2025) Characterizing cell-type spatial relationships across length scales in spatially resolved omics data (CRAWDAD). Nature Communications 16:350. DOI 10.1038\u002Fs41467-024-55700-1\n- Moran PAP (1950) Notes on continuous stochastic phenomena. Biometrika 37(1\u002F2):17-23. DOI 10.2307\u002F2332142\n- Geary RC (1954) The contiguity ratio and statistical mapping. The Incorporated Statistician 5(3):115-145. DOI 10.2307\u002F2986645\n- Getis A, Ord JK (1992) The analysis of spatial association by use of distance statistics. Geographical Analysis 24(3):189-206. DOI 10.1111\u002Fj.1538-4632.1992.tb00261.x\n- Anselin L (1995) Local indicators of spatial association -- LISA. Geographical Analysis 27(2):93-115. DOI 10.1111\u002Fj.1538-4632.1995.tb00338.x\n",{"name":5,"source":24,"license":15,"tool_type":25,"description":7,"imported_at":26,"source_path":27,"primary_tool":28,"source_repository":29},"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills","python","2026-09-20","spatial-transcriptomics\u002Fspatial-statistics\u002FSKILL.md","squidpy","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-spatial-transcriptomics-spatial-statistics","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous","2026-11-09 11:45:36",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-spatial-transcriptomics-spatial-statistics",{"tool":42,"command":43},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-spatial-transcriptomics-spatial-statistics",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-spatial-transcriptomics-spatial-statistics","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-spatial-transcriptomics-spatial-statistics\u002FSKILL.md",true,[50,56],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Fspatial_autocorr.py","SCRIPT","脚本",1891,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-spatial-transcriptomics-spatial-statistics\u002Fexamples\u002Fspatial_autocorr.py",{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},"usage-guide.md","REFERENCE","参考文档",4621,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-spatial-transcriptomics-spatial-statistics\u002Fusage-guide.md",[63,71,78,85,92,99],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":70},"01M7FFFZPC2025JQQHPHDX154J","dei-assessment","Assess diversity, equity, and inclusion with metrics. TRIGGERS - Use when user needs help with dei-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-assessment\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":70},"01M7FFFWN8H4WA7A6Y398QKB6J","dei-action-plan","Create DEI action plans with goals and initiatives. TRIGGERS - Use when user needs help with dei-action-plan related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-action-plan\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":70},"01M7FFFSHTM0QZRVZ2NRJTJ0PY","culture-fit-assessment","Design culture add assessment processes. TRIGGERS - Use when user needs help with culture-fit-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fculture-fit-assessment\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":70},"01M7FFFMA12RKEQA38KHJSXXPS","cowork-to-code-bridge","Use an already-installed, independently verified cowork-to-code bridge to run narrowly approved actions on the user's own macOS, Linux, or WSL2 machine through a local file queue.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcowork-to-code-bridge\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":70},"01M7FFFH1F6M8YRGW5V487GH1K","counter-offer-response","Draft counter-offer responses for retention. TRIGGERS - Use when user needs help with counter-offer-response related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcounter-offer-response\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":70},"01M7FFFDGEHV8Y7J9N40HZXW52","continuous-feedback-system","Design continuous feedback systems. TRIGGERS - Use when user needs help with continuous-feedback-system related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcontinuous-feedback-system\u002FSKILL.md",[],[]]