[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EDWCFN73TYW8JQMX9VMQ02":3,"skill-same:01M7EDWCFN73TYW8JQMX9VMQ02":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},"01M7EDWCFN73TYW8JQMX9VMQ02","bio-imaging-mass-cytometry-spatial-analysis",null,"Analyze spatial cell-cell interactions, neighborhoods, and niches in IMC\u002FMIBI data with squidpy and imcRtools, covering neighborhood-enrichment permutation nulls, the abundance-vs-density confound, inhomogeneous Ripley's K, cellular-neighborhood discovery, graph-construction (contact vs proximity), and edge effects. Use when testing whether cell types co-locate, choosing a spatial null, building a neighbor graph, discovering tissue niches, or deciding whether a spatial pattern is real or a density\u002Fsegmentation artifact.","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-imaging-mass-cytometry-spatial-analysis\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-imaging-mass-cytometry-spatial-analysis\ndescription: Analyze spatial cell-cell interactions, neighborhoods, and niches in IMC\u002FMIBI data with squidpy and imcRtools, covering neighborhood-enrichment permutation nulls, the abundance-vs-density confound, inhomogeneous Ripley's K, cellular-neighborhood discovery, graph-construction (contact vs proximity), and edge effects. Use when testing whether cell types co-locate, choosing a spatial null, building a neighbor graph, discovering tissue niches, or deciding whether a spatial pattern is real or a density\u002Fsegmentation artifact.\ntool_type: python\nprimary_tool: squidpy\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"imaging-mass-cytometry\u002Fspatial-analysis\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: squidpy 1.3+, scanpy 1.10+, anndata 0.10+, numpy 1.26+, imcRtools 1.8+ (R), spatstat 3.0+ (R)\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\nNotes specific to this skill: squidpy's `nhood_enrichment` z-score is unbounded and scales with graph degree, so it is NOT comparable across images of different cell counts. squidpy does not implement Ripley's K (its `ripley` and `co_occurrence` are loose analogs); the inhomogeneous K that conditions on tissue density lives in R `spatstat::Kinhom`\u002F`Kcross.inhom`. Build the graph with `gr.spatial_neighbors(coord_type='generic')` before any test.\n\n# Spatial Analysis for IMC\n\n**\"Analyze spatial cell interactions in my IMC data\"** -> Build a neighbor graph, then test cell-type co-location against an explicitly chosen null, or discover recurrent niches.\n- Python: `squidpy.gr.spatial_neighbors`, `squidpy.gr.nhood_enrichment`, `squidpy.gr.co_occurrence`\n- R: `imcRtools::buildSpatialGraph`, `spatstat::Kcross.inhom`\n\n## The Single Most Important Modern Insight -- a spatial interaction is a hypothesis test, and the null silently decides what is measured\n\nA \"spatial interaction\" or \"niche\" is not an observation; it is a test against a null model, and which null is chosen (label-shuffle vs CSR vs density-conditioned vs patient-level) decides whether the result is real biology, a density gradient, a segmentation artifact, or upstream clustering. The label-permutation null (histoCAT, squidpy `nhood_enrichment`) holds cell positions fixed and shuffles identities: it DOES control global abundance (a rare type cannot show spurious enrichment just from being rare) but it does NOT control local density or tissue architecture -- so two cell types that merely share an anatomical compartment (both enriched in a follicle or at an invasive margin) score as strongly \"interacting\" with no direct affinity. This density confound is the dominant false-positive engine, and a finding significant under CSR but null under inhomogeneous Ripley's K is a density artifact, not an interaction. Two further facts compound it: the `nhood_enrichment` z-score is unbounded and graph-degree-dependent, so a z of 30 in a 50k-cell image and a z of 8 in a 5k-cell image are not on the same scale (never threshold a fixed z across heterogeneous images); and the replicate is the patient, not the cell or the image, so a per-cell test over tens of thousands of cells reports p~0 for trivial effects (pseudoreplication). The skill forces two questions onto every analysis: against which null, and at which unit.\n\n## Spatial Methods Taxonomy\n\n| Method | Measures | Null \u002F inference | Confound it does NOT control |\n|--------|----------|------------------|------------------------------|\n| histoCAT \u002F squidpy `nhood_enrichment` | A neighbors B more\u002Fless than chance | within-image label shuffle; z-score | local density, architecture, edges |\n| squidpy `interaction_matrix` | raw cluster-cluster edge counts | none (descriptive) | everything -- just counts |\n| squidpy `co_occurrence` | P(B \\| A at distance d) \u002F P(B) | none (descriptive curve) | needs its own CSR null |\n| Ripley's K\u002FL, cross-K, K_inhom | clustering vs dispersion over radii | CSR; K_inhom conditions on intensity | tissue inhomogeneity (unless K_inhom); ROI shape |\n| Cellular Neighborhoods (CN) | recurrent local compositions (niches) | none -- clustering, not a test | window size = scale; doubly-derived |\n| Spatial-LDA \u002F UTAG | microenvironment topics \u002F tissue domains | generative \u002F unsupervised | topic\u002Fdomain count arbitrary |\n| Moran's I \u002F Geary's C | spatial autocorrelation of a continuous mark | permutation \u002F analytic | graph definition; global stat masks local |\n\n## Decision Tree by Scenario\n\n| Question | Method | Why |\n|----------|--------|-----|\n| Do two named types co-locate more than chance? (fast screen, one image) | `nhood_enrichment` \u002F histoCAT | abundance-aware permutation z |\n| Same, but worried about density\u002Farchitecture | inhomogeneous cross-K (`Kcross.inhom`) | conditions on the tissue's own intensity surface |\n| At what scale is a type clustered\u002Fdispersed? | Ripley's K\u002FL over radii (edge-corrected) | second-order structure across distance |\n| What recurrent multicellular niches exist? (discovery) | Cellular Neighborhoods (sweep window k) | recurrent compositions; no built-in test |\n| Is a continuous marker\u002Fscore spatially structured? | Moran's I (global) \u002F Geary's C (local) | autocorrelation |\n| Does an interaction\u002Fniche differ between conditions? | hand off to differential-analysis | per-image summary -> patient unit -> mixed model + FDR |\n\n## Build the Spatial Graph (contact vs proximity)\n\n**Goal:** Construct the graph whose definition matches the biological claim.\n\n**Approach:** Delaunay approximates physical adjacency (contact\u002Fjuxtacrine) but invents long edges across lumen\u002Fnecrosis, so prune by a max distance; fixed radius gives true proximity (paracrine) at a stated micron scale; kNN silently mixes contact and proximity because fixed k spans microns in dense regions and hundreds of microns in sparse ones. Build the graph per image.\n\n```python\nimport squidpy as sq\nimport numpy as np\n\n# contact graph: Delaunay, then prune edges longer than a biological max distance (um)\nsq.gr.spatial_neighbors(adata, coord_type='generic', delaunay=True)\ndist = adata.obsp['spatial_distances']\nkeep = dist.copy(); keep.data[keep.data > 30] = 0; keep.eliminate_zeros()   # cap at ~30 um\nadata.obsp['spatial_connectivities'] = (keep > 0).astype(float)\n\n# OR proximity graph: fixed radius at a justified micron scale (paracrine range)\n# sq.gr.spatial_neighbors(adata, coord_type='generic', radius=30.0)\n```\n\n## Neighborhood Enrichment with a Named Null\n\n**Goal:** Test co-location per image with the abundance-aware permutation null, knowing its blind spot.\n\n**Approach:** Run `nhood_enrichment` per image (so the shuffle is within-image), keep the z as a per-image summary, and never threshold a fixed z across images of different size. Cross-check density-driven hits against inhomogeneous K.\n\n```python\nper_image_z = {}\nfor img_id, idx in adata.obs.groupby('image_id').groups.items():\n    sub = adata[idx].copy()\n    sq.gr.spatial_neighbors(sub, coord_type='generic', delaunay=True)\n    sq.gr.nhood_enrichment(sub, cluster_key='cell_type', seed=0)\n    per_image_z[img_id] = sub.uns['cell_type_nhood_enrichment']['zscore']\n# aggregate these per-image summaries to the PATIENT unit in differential-analysis, not here\n```\n\n## Cellular Neighborhoods (niche discovery)\n\n**Goal:** Find recurrent local cell-type compositions, treating them as exploratory.\n\n**Approach:** Per cell, summarize the composition of its window of neighbors, then cluster the windows. The window size IS the spatial scale and is almost always unjustified, so sweep it and report that the biological conclusion survives k in {10, 20, 30}. A CN has no built-in significance test; significance enters only as a cross-condition comparison (differential-analysis).\n\n```python\nfrom sklearn.cluster import KMeans\nimport pandas as pd\n\ndef cellular_neighborhoods(adata, k_window=20, n_cn=10):\n    sq.gr.spatial_neighbors(adata, coord_type='generic', n_neighs=k_window)   # window = k neighbors\n    conn = adata.obsp['spatial_connectivities']\n    onehot = pd.get_dummies(adata.obs['cell_type']).values\n    comp = (conn @ onehot)                       # neighbor composition per cell\n    comp = comp \u002F comp.sum(axis=1, keepdims=True).clip(min=1)\n    return KMeans(n_clusters=n_cn, random_state=0).fit_predict(comp)\n\nadata.obs['CN'] = cellular_neighborhoods(adata, k_window=20)   # sweep k_window to check stability\n```\n\n## Per-Method Failure Modes\n\n### nhood_enrichment -- density false positive\n**Trigger:** reporting a z-score as a \"significant interaction.\" **Mechanism:** the label-shuffle null absorbs abundance but not local density, so co-compartmentalized types score as interacting. **Symptom:** every type pair sharing a region looks attracted. **Fix:** name the null; cross-check with inhomogeneous cross-K; or shuffle within a compartment, not the whole image.\n\n### Fixed z threshold across images\n**Trigger:** calling z>2 \"significant\" across images of different cell counts. **Mechanism:** the z is unbounded and scales with graph degree. **Symptom:** large images dominate; small images never reach threshold. **Fix:** rank within image or convert to an effect size; aggregate per-image summaries to the patient unit.\n\n### Unpruned Delaunay \u002F kNN mislabeled as contact\n**Trigger:** kNN graph results called \"contact,\" or Delaunay across tissue gaps. **Mechanism:** fixed k mixes contact and proximity by density; Delaunay invents long edges across voids. **Symptom:** phantom interactions across lumen\u002Fnecrosis. **Fix:** prune Delaunay by a max distance; use fixed radius for paracrine claims; state the micron scale.\n\n### CSR Ripley's K on inhomogeneous tissue\n**Trigger:** homogeneous-Poisson K on structured tissue. **Mechanism:** CSR assumes constant intensity, so everything tests as clustered. **Symptom:** universal \"clustering\". **Fix:** inhomogeneous K (`Kinhom`\u002F`Kcross.inhom`) that divides by the estimated intensity surface.\n\n### Niche taken as a discovered fact\n**Trigger:** treating a CN as established biology. **Mechanism:** it is doubly-derived (cluster cells -> cluster windows) with an arbitrary window and k, and no significance test. **Symptom:** different labs report different niches on the same tissue. **Fix:** sweep window k; report stability (NMI\u002FARI); validate niche-defining markers against raw images for spillover.\n\n## Quantitative Thresholds\n\n| Threshold | Source | Rationale |\n|-----------|--------|-----------|\n| CN window = 10 nearest neighbors, 9 CNs retained | Schurch 2020 *Cell* 182:1341 | the canonical CN convention -- sweep it, do not adopt blindly |\n| CODEX i-niches: Delaunay 1st-tier, k-means = 100 | Goltsev 2018 *Cell* 174:968 | window\u002Fscale is a choice, not a default |\n| n_perm >= 10,000 for small corrected p | Schapiro 2017 *Nat Methods* 14:873 | n_perm=1000 floors p at ~1\u002F1001, too coarse after FDR |\n| BH-FDR across ~C(C+1)\u002F2 type pairs x radii | multiplicity | ~200 pairs at p\u003C0.05 guarantees false positives |\n| Prune Delaunay at a biological max distance (e.g. ~30 um) | graph hygiene | removes edges across acellular voids |\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|-----------------|-------|----------|\n| \"Significant interaction\" that is two types in one compartment | density confound under label-shuffle | inhomogeneous cross-K; shuffle within compartment |\n| p~0 across 50k cells | cell-level pseudoreplication | per-image summary -> patient unit (differential-analysis) |\n| Niche changes with the window\u002Fk | window IS the scale | sweep k_window and n_cn; report stability |\n| Boundary cells dominate a small ROI | ignored edge effects | edge-corrected K; erode\u002Fbuffer the ROI interior |\n| Many \"significant\" pairs | no multiple-testing correction | BH-FDR across all pairs and radii |\n\n## References\n\n- Schapiro D, Jackson HW, Raghuraman G, et al. 2017. histoCAT: analysis of cell phenotypes and interactions in multiplex image cytometry data. *Nat Methods* 14(9):873-876. — neighborhood permutation test.\n- Goltsev Y, Samusik N, Kennedy-Darling J, et al. 2018. Deep Profiling of Mouse Splenic Architecture with CODEX Multiplexed Imaging. *Cell* 174(4):968-981.e15. — cellular neighborhoods (i-niches).\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.e19. — canonical CN convention.\n- Palla G, Spitzer H, Klein M, et al. 2022. Squidpy: a scalable framework for spatial omics analysis. *Nat Methods* 19(2):171-178. — squidpy spatial functions.\n- Chen Z, Soifer I, Hilton H, Keren L, Jojic V. 2020. Modeling Multiplexed Images with Spatial-LDA Reveals Novel Tissue Microenvironments. *J Comput Biol* 27(8):1204-1218. — Spatial-LDA.\n- Kim J, Rustam S, Mosquera JM, et al. 2022. Unsupervised discovery of tissue architecture in multiplexed imaging. *Nat Methods* 19(12):1653-1661. — UTAG domains.\n- Ripley BD. 1977. Modelling Spatial Patterns. *J R Stat Soc Series B* 39(2):172-212. — the K-function.\n- Moran PAP. 1950. Notes on Continuous Stochastic Phenomena. *Biometrika* 37(1\u002F2):17-23. — Moran's I.\n- Geary RC. 1954. The Contiguity Ratio and Statistical Mapping. *Incorporated Statistician* 5(3):115-145. — Geary's C.\n\n## Related Skills\n\n- phenotyping - cell-type labels are the input to every spatial test\n- differential-analysis - testing whether interactions\u002Fniches differ between conditions at the patient level\n- cell-segmentation - over-segmentation and lateral spillover create fake niches\n- data-preprocessing - uncompensated spillover manufactures false cell-cell interactions\n- spatial-transcriptomics\u002Fspatial-statistics - shared squidpy neighborhood and autocorrelation methods\n","## Version Compatibility\n\nReference examples tested with: squidpy 1.3+, scanpy 1.10+, anndata 0.10+, numpy 1.26+, imcRtools 1.8+ (R), spatstat 3.0+ (R)\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\nNotes specific to this skill: squidpy's `nhood_enrichment` z-score is unbounded and scales with graph degree, so it is NOT comparable across images of different cell counts. squidpy does not implement Ripley's K (its `ripley` and `co_occurrence` are loose analogs); the inhomogeneous K that conditions on tissue density lives in R `spatstat::Kinhom`\u002F`Kcross.inhom`. Build the graph with `gr.spatial_neighbors(coord_type='generic')` before any test.\n\n# Spatial Analysis for IMC\n\n**\"Analyze spatial cell interactions in my IMC data\"** -> Build a neighbor graph, then test cell-type co-location against an explicitly chosen null, or discover recurrent niches.\n- Python: `squidpy.gr.spatial_neighbors`, `squidpy.gr.nhood_enrichment`, `squidpy.gr.co_occurrence`\n- R: `imcRtools::buildSpatialGraph`, `spatstat::Kcross.inhom`\n\n## The Single Most Important Modern Insight -- a spatial interaction is a hypothesis test, and the null silently decides what is measured\n\nA \"spatial interaction\" or \"niche\" is not an observation; it is a test against a null model, and which null is chosen (label-shuffle vs CSR vs density-conditioned vs patient-level) decides whether the result is real biology, a density gradient, a segmentation artifact, or upstream clustering. The label-permutation null (histoCAT, squidpy `nhood_enrichment`) holds cell positions fixed and shuffles identities: it DOES control global abundance (a rare type cannot show spurious enrichment just from being rare) but it does NOT control local density or tissue architecture -- so two cell types that merely share an anatomical compartment (both enriched in a follicle or at an invasive margin) score as strongly \"interacting\" with no direct affinity. This density confound is the dominant false-positive engine, and a finding significant under CSR but null under inhomogeneous Ripley's K is a density artifact, not an interaction. Two further facts compound it: the `nhood_enrichment` z-score is unbounded and graph-degree-dependent, so a z of 30 in a 50k-cell image and a z of 8 in a 5k-cell image are not on the same scale (never threshold a fixed z across heterogeneous images); and the replicate is the patient, not the cell or the image, so a per-cell test over tens of thousands of cells reports p~0 for trivial effects (pseudoreplication). The skill forces two questions onto every analysis: against which null, and at which unit.\n\n## Spatial Methods Taxonomy\n\n| Method | Measures | Null \u002F inference | Confound it does NOT control |\n|--------|----------|------------------|------------------------------|\n| histoCAT \u002F squidpy `nhood_enrichment` | A neighbors B more\u002Fless than chance | within-image label shuffle; z-score | local density, architecture, edges |\n| squidpy `interaction_matrix` | raw cluster-cluster edge counts | none (descriptive) | everything -- just counts |\n| squidpy `co_occurrence` | P(B \\| A at distance d) \u002F P(B) | none (descriptive curve) | needs its own CSR null |\n| Ripley's K\u002FL, cross-K, K_inhom | clustering vs dispersion over radii | CSR; K_inhom conditions on intensity | tissue inhomogeneity (unless K_inhom); ROI shape |\n| Cellular Neighborhoods (CN) | recurrent local compositions (niches) | none -- clustering, not a test | window size = scale; doubly-derived |\n| Spatial-LDA \u002F UTAG | microenvironment topics \u002F tissue domains | generative \u002F unsupervised | topic\u002Fdomain count arbitrary |\n| Moran's I \u002F Geary's C | spatial autocorrelation of a continuous mark | permutation \u002F analytic | graph definition; global stat masks local |\n\n## Decision Tree by Scenario\n\n| Question | Method | Why |\n|----------|--------|-----|\n| Do two named types co-locate more than chance? (fast screen, one image) | `nhood_enrichment` \u002F histoCAT | abundance-aware permutation z |\n| Same, but worried about density\u002Farchitecture | inhomogeneous cross-K (`Kcross.inhom`) | conditions on the tissue's own intensity surface |\n| At what scale is a type clustered\u002Fdispersed? | Ripley's K\u002FL over radii (edge-corrected) | second-order structure across distance |\n| What recurrent multicellular niches exist? (discovery) | Cellular Neighborhoods (sweep window k) | recurrent compositions; no built-in test |\n| Is a continuous marker\u002Fscore spatially structured? | Moran's I (global) \u002F Geary's C (local) | autocorrelation |\n| Does an interaction\u002Fniche differ between conditions? | hand off to differential-analysis | per-image summary -> patient unit -> mixed model + FDR |\n\n## Build the Spatial Graph (contact vs proximity)\n\n**Goal:** Construct the graph whose definition matches the biological claim.\n\n**Approach:** Delaunay approximates physical adjacency (contact\u002Fjuxtacrine) but invents long edges across lumen\u002Fnecrosis, so prune by a max distance; fixed radius gives true proximity (paracrine) at a stated micron scale; kNN silently mixes contact and proximity because fixed k spans microns in dense regions and hundreds of microns in sparse ones. Build the graph per image.\n\n```python\nimport squidpy as sq\nimport numpy as np\n\n# contact graph: Delaunay, then prune edges longer than a biological max distance (um)\nsq.gr.spatial_neighbors(adata, coord_type='generic', delaunay=True)\ndist = adata.obsp['spatial_distances']\nkeep = dist.copy(); keep.data[keep.data > 30] = 0; keep.eliminate_zeros()   # cap at ~30 um\nadata.obsp['spatial_connectivities'] = (keep > 0).astype(float)\n\n# OR proximity graph: fixed radius at a justified micron scale (paracrine range)\n# sq.gr.spatial_neighbors(adata, coord_type='generic', radius=30.0)\n```\n\n## Neighborhood Enrichment with a Named Null\n\n**Goal:** Test co-location per image with the abundance-aware permutation null, knowing its blind spot.\n\n**Approach:** Run `nhood_enrichment` per image (so the shuffle is within-image), keep the z as a per-image summary, and never threshold a fixed z across images of different size. Cross-check density-driven hits against inhomogeneous K.\n\n```python\nper_image_z = {}\nfor img_id, idx in adata.obs.groupby('image_id').groups.items():\n    sub = adata[idx].copy()\n    sq.gr.spatial_neighbors(sub, coord_type='generic', delaunay=True)\n    sq.gr.nhood_enrichment(sub, cluster_key='cell_type', seed=0)\n    per_image_z[img_id] = sub.uns['cell_type_nhood_enrichment']['zscore']\n# aggregate these per-image summaries to the PATIENT unit in differential-analysis, not here\n```\n\n## Cellular Neighborhoods (niche discovery)\n\n**Goal:** Find recurrent local cell-type compositions, treating them as exploratory.\n\n**Approach:** Per cell, summarize the composition of its window of neighbors, then cluster the windows. The window size IS the spatial scale and is almost always unjustified, so sweep it and report that the biological conclusion survives k in {10, 20, 30}. A CN has no built-in significance test; significance enters only as a cross-condition comparison (differential-analysis).\n\n```python\nfrom sklearn.cluster import KMeans\nimport pandas as pd\n\ndef cellular_neighborhoods(adata, k_window=20, n_cn=10):\n    sq.gr.spatial_neighbors(adata, coord_type='generic', n_neighs=k_window)   # window = k neighbors\n    conn = adata.obsp['spatial_connectivities']\n    onehot = pd.get_dummies(adata.obs['cell_type']).values\n    comp = (conn @ onehot)                       # neighbor composition per cell\n    comp = comp \u002F comp.sum(axis=1, keepdims=True).clip(min=1)\n    return KMeans(n_clusters=n_cn, random_state=0).fit_predict(comp)\n\nadata.obs['CN'] = cellular_neighborhoods(adata, k_window=20)   # sweep k_window to check stability\n```\n\n## Per-Method Failure Modes\n\n### nhood_enrichment -- density false positive\n**Trigger:** reporting a z-score as a \"significant interaction.\" **Mechanism:** the label-shuffle null absorbs abundance but not local density, so co-compartmentalized types score as interacting. **Symptom:** every type pair sharing a region looks attracted. **Fix:** name the null; cross-check with inhomogeneous cross-K; or shuffle within a compartment, not the whole image.\n\n### Fixed z threshold across images\n**Trigger:** calling z>2 \"significant\" across images of different cell counts. **Mechanism:** the z is unbounded and scales with graph degree. **Symptom:** large images dominate; small images never reach threshold. **Fix:** rank within image or convert to an effect size; aggregate per-image summaries to the patient unit.\n\n### Unpruned Delaunay \u002F kNN mislabeled as contact\n**Trigger:** kNN graph results called \"contact,\" or Delaunay across tissue gaps. **Mechanism:** fixed k mixes contact and proximity by density; Delaunay invents long edges across voids. **Symptom:** phantom interactions across lumen\u002Fnecrosis. **Fix:** prune Delaunay by a max distance; use fixed radius for paracrine claims; state the micron scale.\n\n### CSR Ripley's K on inhomogeneous tissue\n**Trigger:** homogeneous-Poisson K on structured tissue. **Mechanism:** CSR assumes constant intensity, so everything tests as clustered. **Symptom:** universal \"clustering\". **Fix:** inhomogeneous K (`Kinhom`\u002F`Kcross.inhom`) that divides by the estimated intensity surface.\n\n### Niche taken as a discovered fact\n**Trigger:** treating a CN as established biology. **Mechanism:** it is doubly-derived (cluster cells -> cluster windows) with an arbitrary window and k, and no significance test. **Symptom:** different labs report different niches on the same tissue. **Fix:** sweep window k; report stability (NMI\u002FARI); validate niche-defining markers against raw images for spillover.\n\n## Quantitative Thresholds\n\n| Threshold | Source | Rationale |\n|-----------|--------|-----------|\n| CN window = 10 nearest neighbors, 9 CNs retained | Schurch 2020 *Cell* 182:1341 | the canonical CN convention -- sweep it, do not adopt blindly |\n| CODEX i-niches: Delaunay 1st-tier, k-means = 100 | Goltsev 2018 *Cell* 174:968 | window\u002Fscale is a choice, not a default |\n| n_perm >= 10,000 for small corrected p | Schapiro 2017 *Nat Methods* 14:873 | n_perm=1000 floors p at ~1\u002F1001, too coarse after FDR |\n| BH-FDR across ~C(C+1)\u002F2 type pairs x radii | multiplicity | ~200 pairs at p\u003C0.05 guarantees false positives |\n| Prune Delaunay at a biological max distance (e.g. ~30 um) | graph hygiene | removes edges across acellular voids |\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|-----------------|-------|----------|\n| \"Significant interaction\" that is two types in one compartment | density confound under label-shuffle | inhomogeneous cross-K; shuffle within compartment |\n| p~0 across 50k cells | cell-level pseudoreplication | per-image summary -> patient unit (differential-analysis) |\n| Niche changes with the window\u002Fk | window IS the scale | sweep k_window and n_cn; report stability |\n| Boundary cells dominate a small ROI | ignored edge effects | edge-corrected K; erode\u002Fbuffer the ROI interior |\n| Many \"significant\" pairs | no multiple-testing correction | BH-FDR across all pairs and radii |\n\n## References\n\n- Schapiro D, Jackson HW, Raghuraman G, et al. 2017. histoCAT: analysis of cell phenotypes and interactions in multiplex image cytometry data. *Nat Methods* 14(9):873-876. — neighborhood permutation test.\n- Goltsev Y, Samusik N, Kennedy-Darling J, et al. 2018. Deep Profiling of Mouse Splenic Architecture with CODEX Multiplexed Imaging. *Cell* 174(4):968-981.e15. — cellular neighborhoods (i-niches).\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.e19. — canonical CN convention.\n- Palla G, Spitzer H, Klein M, et al. 2022. Squidpy: a scalable framework for spatial omics analysis. *Nat Methods* 19(2):171-178. — squidpy spatial functions.\n- Chen Z, Soifer I, Hilton H, Keren L, Jojic V. 2020. Modeling Multiplexed Images with Spatial-LDA Reveals Novel Tissue Microenvironments. *J Comput Biol* 27(8):1204-1218. — Spatial-LDA.\n- Kim J, Rustam S, Mosquera JM, et al. 2022. Unsupervised discovery of tissue architecture in multiplexed imaging. *Nat Methods* 19(12):1653-1661. — UTAG domains.\n- Ripley BD. 1977. Modelling Spatial Patterns. *J R Stat Soc Series B* 39(2):172-212. — the K-function.\n- Moran PAP. 1950. Notes on Continuous Stochastic Phenomena. *Biometrika* 37(1\u002F2):17-23. — Moran's I.\n- Geary RC. 1954. The Contiguity Ratio and Statistical Mapping. *Incorporated Statistician* 5(3):115-145. — Geary's C.\n\n## Related Skills\n\n- phenotyping - cell-type labels are the input to every spatial test\n- differential-analysis - testing whether interactions\u002Fniches differ between conditions at the patient level\n- cell-segmentation - over-segmentation and lateral spillover create fake niches\n- data-preprocessing - uncompensated spillover manufactures false cell-cell interactions\n- spatial-transcriptomics\u002Fspatial-statistics - shared squidpy neighborhood and autocorrelation methods\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","imaging-mass-cytometry\u002Fspatial-analysis\u002FSKILL.md","squidpy","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-imaging-mass-cytometry-spatial-analysis","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-imaging-mass-cytometry-spatial-analysis",{"tool":42,"command":43},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-imaging-mass-cytometry-spatial-analysis",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-imaging-mass-cytometry-spatial-analysis","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-imaging-mass-cytometry-spatial-analysis\u002FSKILL.md",true,[50,56],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Fspatial_analysis.py","SCRIPT","脚本",2461,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-imaging-mass-cytometry-spatial-analysis\u002Fexamples\u002Fspatial_analysis.py",{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},"usage-guide.md","REFERENCE","参考文档",3650,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-imaging-mass-cytometry-spatial-analysis\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",[],[]]