Introduction to spicyr#

Do T cells gather around tumour cells more in ER-positive breast cancers than in ER-negative ones? Do patients whose tumour cells are surrounded by immune cells relapse later? spicyr answers questions like these for every pair of cell types in an imaging study. This tutorial works through a study of 456 breast tumours: testing every pair, looking closely at one, finding the images behind the result, and checking that the test behaves when there is nothing to find.

Overview#

A pair is written from → to and asks whether to cells are placed near from cells more than other cells are. For each to cell, spicyr checks whether there is a from cell within a radius, and compares the share of to cells that have one with what we would expect if the to cells were a random choice among the cells of the same image that are not from cells. The effect is the extra fraction of to cells placed next to from cells, beyond chance: 0.2 means as if a fifth of the to cells had been moved next to from cells and the rest left where chance would put them. For a pair whose to cells avoid the from cells (fewer have one nearby than chance, over all images), the effect is measured the other way: -0.2 means as if a fifth of the to cells that chance would put next to a from cell had been moved away. Each to cell counts once, however many from cells are beside it, so more numerous or more tightly packed from cells do not inflate the effect. Because the comparison uses only the cells that are actually there, empty regions such as holes or air spaces, and uneven cell density, do not by themselves create a signal (artefacts that affect one cell type more than others are not removed). spicyr then compares the effect between groups of patients, treating patients, not images or cells, as the units of the test.

Left, tumour cells marked by whether a T cell lies within 25 µm, with the circle drawn around two of them. Right, box plots of the extra fraction of tumour cells next to T cells, one point per patient, higher in ER-positive than ER-negative tumours.

The pair T cells → proliferating tumour cells. For each proliferating tumour cell (red, the to type), spicyr checks whether a T cell (blue, the from type) lies within 25 µm, and compares the share of tumour cells that have one with chance. Each patient gets an effect, and the effect is compared between ER-negative and ER-positive tumours.#

Note

Pairs are directional. Tumour cells → T cells asks whether T cells are placed near tumour cells (the extra fraction of T cells with a tumour cell nearby), which is a different question from T cells → tumour cells (are tumour cells placed near T cells?).

spicyr needs the type and position of every cell, as from imaging mass cytometry, CODEX, MIBI, Xenium, CosMx or MERSCOPE. It is not designed for spot-based data such as Visium.

Installation#

spicyr will be on PyPI with its first release. Until then, install it from GitHub (this needs a C++17 compiler):

pip install "spicyr[data,plot,anndata] @ git+https://github.com/SydneyBioX/spicyr-py"
import pandas as pd
import spicyr

pd.set_option("display.precision", 4)
pd.set_option("display.width", 120)

The data#

We use imaging mass cytometry of breast tumours from the METABRIC cohort (Ali et al., Nature Cancer 2020). Each of the 456 patients with known oestrogen receptor (ER) status contributed one tumour core, and the authors assigned each cell to one of 22 types. Their labels name tumour cells by marker: HR is hormone receptor, CK cytokeratin, and Ki67+ marks proliferating cells, so HR- Ki67+ are proliferating hormone-receptor-negative tumour cells.

spicyr.datasets.metabric_ali2020() downloads the data once (130 MB) and caches it. We ask for an AnnData object: one observation per cell, with the clinical data in obs and the coordinates, in micrometres, in obsm["spatial"]. The ER status of each patient is in ER.Status, neg or pos; we keep the patients whose ER status is known.

adata = spicyr.datasets.metabric_ali2020(as_anndata=True)
adata = adata[adata.obs["ER.Status"].notna()].copy()  # the 456 patients with known ER status

# spicyr looks for columns called imageID and cellType by default. Copying the dataset's columns to these names is
# not needed (you can give image_id="file_id", cell_type="description" to each call instead); it only keeps the
# calls below short.
adata.obs["imageID"] = adata.obs["file_id"]
adata.obs["cellType"] = adata.obs["description"]
adata
AnnData object with n_obs × n_vars = 422629 × 0
    obs: 'file_id', 'metabricId', 'core_id', 'ImageNumber', 'ObjectNumber', 'Location_Center_X', 'Location_Center_Y', 'SOM_nodes', 'pg_cluster', 'description', 'Age.At.Diagnosis', 'Breast.Tumour.Laterality', 'Date.Of.Diagnosis', 'Last.Followup.Status', 'NPI', 'ER.Status', 'Inferred.Menopausal.State', 'Lymph.Nodes.Positive', 'Breast.Surgery', 'CT', 'HT', 'RT', 'Grade', 'Size', 'Histological.Type', 'Stage', 'DeathBreast', 'Death', 'T', 'TLR', 'LR', 'TDR', 'DR', 'Complete.Rec.History', 'timeRFS', 'eventRFS', 'sample_id', 'imageID', 'cellType'
    obsm: 'spatial'
adata.obs["cellType"].value_counts()
cellType
HR+ CK7-                    114828
Myofibroblasts               57295
Fibroblasts                  49043
HR- CK7-                     34951
HR- CK7+                     29432
HRlow CKlow                  22824
T cells                      19218
HR+ CK7- Ki67+               17203
Fibroblasts CD68+            13716
HR- Ki67+                    13062
HR+ CK7- Slug+                7417
Macrophages Vim+ Slug-        6721
Hypoxia                       5639
Myoepithelial                 4637
HER2+                         4434
Macrophages Vim+ Slug+        3657
Macrophages Vim+ CD45low      3600
Endothelial                   3480
B cells                       3232
Basal CKlow                   3226
Vascular SMA+                 2908
HR- CKlow CK5+                2106
Name: count, dtype: int64

Two of the cores, one ER− and one ER+:

spicyr.plot_image(adata, ["MB0869_1_366", "MB0501_1_222"]);
_images/e0660dca2745ad47f010bae8386b08e13b86ea58ec8eefeb14e2c018bd7eb153.png

Testing every pair of cell types#

spicy() needs the column of the condition, the column of the patient (subject) and a radius. It accepts an AnnData object, a SpatialData object or a pandas DataFrame with one row per cell. By default it looks for columns called imageID and cellType; here we name the dataset’s own columns.

Tip

Choose the radius before looking at the results, from the scale at which you expect cells to interact: 10 to 25 µm for contact, 50 to 100 µm for a shared neighbourhood. Here we use 25 µm, about two to three cell diameters. If you are unsure, give several radii (see Which radius?).

res = spicyr.spicy(adata, condition="ER.Status", subject="metabricId", r=25)
res
spicyr (cell-level test): 484 pairs, pos vs neg, r = 25
Units: 456 patients (neg 83, pos 373) with 456 images
13 pairs are not tested (p_value NaN: no variation, a condition with no informative patient, one with too few effective patients, or too few degrees of freedom)
BH-adjusted p < 0.05: 37 pairs
See top_pairs().

All 484 ordered pairs of cell types are tested in a few seconds on one core. Run time and memory grow roughly in proportion to the number of cells and to the radius.

top_pairs() lists the most significant pairs. excess_ref and excess_comp are the average effect in ER− and in ER+ patients, as a fraction of the to cells, and excess_difference is their difference (ER+ minus ER−). P-values are adjusted across all pairs by the Benjamini–Hochberg method.

res.top_pairs(8)
from to excess_ref excess_comp excess_difference p_value p_adj
HR+ CK7-__HR+ CK7- Ki67+ HR+ CK7- HR+ CK7- Ki67+ 0.0882 0.6398 0.5516 1.8005e-33 8.4804e-31
HR+ CK7-__HR- CK7- HR+ CK7- HR- CK7- 0.0872 0.4266 0.3394 1.3083e-17 3.0811e-15
HR+ CK7-__HR- CK7+ HR+ CK7- HR- CK7+ 0.1071 0.4964 0.3893 1.5760e-16 2.4743e-14
HR+ CK7-__HR+ CK7- HR+ CK7- HR+ CK7- 0.2454 0.5508 0.3054 4.7877e-12 5.6375e-10
HR+ CK7- Ki67+__HR- CK7+ HR+ CK7- Ki67+ HR- CK7+ 0.2403 0.0252 -0.2150 2.0959e-10 1.8940e-08
HR+ CK7-__HR+ CK7- Slug+ HR+ CK7- HR+ CK7- Slug+ 0.0563 0.5505 0.4942 2.4128e-10 1.8940e-08
HR- CK7+__HR+ CK7- Ki67+ HR- CK7+ HR+ CK7- Ki67+ 0.4211 0.0862 -0.3350 8.0880e-10 5.4421e-08
HR+ CK7-__Macrophages Vim+ Slug+ HR+ CK7- Macrophages Vim+ Slug+ 0.0532 0.3664 0.3132 1.0934e-08 6.4374e-07

Most of these eight pairs have HR+ CK7- tumour cells as the from or the to type, the most significant as the from type; we come back to them in Tissue compartments.

res.top_pairs(n=None) lists every pair, and from_ and to choose pairs. Its columns:

Column

Meaning

excess_ref, excess_comp

average effect in the reference group (ER−) and the comparison group (ER+)

excess_difference

their difference

p_value, p_adj

p-value, and Benjamini–Hochberg adjusted p-value across all pairs

<covariate>_effect, <covariate>_p_value

with covariates, the effect of each covariate and its p-value

With more than two groups there is one row per pair and group, each compared with the reference group, in a column level.

Seeing every pair at once#

signif_plot() shows the whole study. Read rows as from and columns as to. Each circle is a pair: the left half is coloured by the effect in ER− tumours and the right half by the effect in ER+ tumours (red: more to cells next to from cells than chance, blue: fewer), the size reflects the p-value, and a black ring marks a BH-adjusted p-value below 0.05.

res.signif_plot(fdr=True, breaks=(-0.5, 0.5, 0.1));
_images/27ec70d151c656d0f9602f8395f690a42379b11ee3ca87a8973bbb0f6c3c44e7.png

Looking at one pair#

We focus on an immune pair, T cells → HR- Ki67+: are proliferating hormone-receptor-negative tumour cells placed near T cells? Its effect is the extra fraction of these tumour cells with a T cell within 25 µm.

res.top_pairs(from_="T cells", to="HR- Ki67+")
from to excess_ref excess_comp excess_difference p_value p_adj
T cells__HR- Ki67+ T cells HR- Ki67+ 0.0286 0.1434 0.1148 0.0019 0.0296

In ER− tumours these tumour cells have a T cell nearby barely more often than chance would give (0.02). In ER+ tumours the effect is 0.12, as if about one in nine of them had been placed next to T cells.

box_plot() shows the effect in each image (here one image per patient), with a point per image behind each box. Points are sized by how much the image contributes to the test.

res.box_plot("T cells", "HR- Ki67+");
_images/8608dca2228f699c2412295e64b29b823462408e0e95dfe54a33cd1c5f3b2f44.png

With interactive=True the plot is a plotly figure. Hover over a point to see which image it is.

res.box_plot("T cells", "HR- Ki67+", interactive=True)

Important

This is an association in one cohort; it does not show that T cells attract the tumour cells, or the reverse.

bind() returns the per-image values as a DataFrame, for your own plots or models. Images without any HR- Ki67+ cells carry no information about the pair (NaN).

res.bind(from_="T cells", to="HR- Ki67+").head(6)
imageID condition subject effect weight
MB0000_1_527 MB0000_1_527 pos MB-0000 NaN NaN
MB0002_1_345 MB0002_1_345 pos MB-0002 -0.0109 0.0061
MB0005_1_211 MB0005_1_211 pos MB-0005 -0.0131 0.0062
MB0010_1_420 MB0010_1_420 pos MB-0010 0.2566 0.0060
MB0013_1_371 MB0013_1_371 pos MB-0013 NaN NaN
MB0014_1_326 MB0014_1_326 pos MB-0014 0.4800 0.0029

Looking at the images#

plot_image() shows images: the density of all cells in blue, the from cells in gold and the to cells in dark red. With r, it draws the circle around each to cell inside which spicyr looks for from cells. We look at three images found with the interactive box plot. bind() has their effects and weights, with the images as index.

examples = ["MB0150_1_155", "MB0132_1_533", "MB0244_1_519"]
ex = res.bind(from_="T cells", to="HR- Ki67+").loc[examples]
ex
imageID condition subject effect weight
MB0150_1_155 MB0150_1_155 pos MB-0150 0.6774 0.0061
MB0132_1_533 MB0132_1_533 neg MB-0132 -0.0791 0.0175
MB0244_1_519 MB0244_1_519 pos MB-0244 1.0000 0.0011
spicyr.plot_image(adata, examples, "T cells", "HR- Ki67+", r=25);
_images/8de51c54211837d9486b2f33400aef07c83c32289403347be9adb7e23cb98d00.png

In the ER+ image on the left, the T cells run along the band of tumour cells at the bottom: an effect of 0.68, as if two-thirds of the tumour cells had been placed next to T cells. In the ER− image in the middle, the T cells are concentrated top left, apart from most of the tumour cells, and slightly fewer tumour cells have a T cell nearby than chance would give (−0.08). The ER+ image on the right reaches the largest possible value, 1, but only because its two tumour cells both happen to sit in a cluster of T cells.

Tip

Point size matters. The right-hand image sits at the top of the box plot, but its weight is close to zero: an effect estimated from two cells says little. Weights also level off. Once an image has a few dozen to cells, more cells add little, because the differences between patients outweigh the noise within an image.

Tissue compartments#

Many of the most significant pairs, the first among them, have HR+ CK7- tumour cells as the from type. These cells make up about a quarter of the cells in a typical ER+ core and almost none in ER− cores. In ER+ tumours they make up much of the tumour tissue and the other tumour cells sit among them, so far more of those cells have an HR+ CK7- cell nearby than if they had been placed at random among all the other cells, stroma included.

res.top_pairs(from_="HR+ CK7-", n=6)
from to excess_ref excess_comp excess_difference p_value p_adj
HR+ CK7-__HR+ CK7- Ki67+ HR+ CK7- HR+ CK7- Ki67+ 0.0882 0.6398 0.5516 1.8005e-33 8.4804e-31
HR+ CK7-__HR- CK7- HR+ CK7- HR- CK7- 0.0872 0.4266 0.3394 1.3083e-17 3.0811e-15
HR+ CK7-__HR- CK7+ HR+ CK7- HR- CK7+ 0.1071 0.4964 0.3893 1.5760e-16 2.4743e-14
HR+ CK7-__HR+ CK7- HR+ CK7- HR+ CK7- 0.2454 0.5508 0.3054 4.7877e-12 5.6375e-10
HR+ CK7-__HR+ CK7- Slug+ HR+ CK7- HR+ CK7- Slug+ 0.0563 0.5505 0.4942 2.4128e-10 1.8940e-08
HR+ CK7-__Macrophages Vim+ Slug+ HR+ CK7- Macrophages Vim+ Slug+ 0.0532 0.3664 0.3132 1.0934e-08 6.4374e-07

In ER+ tumours the effect for proliferating HR+ CK7- Ki67+ cells is 0.60, against 0.07 in ER− tumours, while fibroblasts and T cells are placed away from HR+ CK7- cells (where HR+ CK7- cells are rare, as in ER− cores, an effect cannot fall far below zero). These are real differences in arrangement, but they describe the structure of the tissue (tumour cells sit with tumour cells) more than an interaction between particular cell types.

Note

To ask about arrangement within a compartment, for example whether proliferating tumour cells sit closer to HR+ CK7- cells than other tumour cells do, compare with random labelling among the tumour cells only. The Kontextual test in the R package Statial does this.

Extra fraction or count?#

By default spicyr asks whether each to cell has a from cell nearby. With effect="count" it asks how many: the effect is then the number of extra from cells within the radius of each to cell.

res_count = spicyr.spicy(adata, condition="ER.Status", subject="metabricId", r=25, effect="count")
res_count.top_pairs(from_="T cells", to="HR- Ki67+")
from to excess_ref excess_comp excess_difference p_value p_adj
T cells__HR- Ki67+ T cells HR- Ki67+ 0.0439 0.2912 0.2474 0.0017 0.0235

In ER+ tumours each proliferating tumour cell has about 0.16 extra T cells within 25 µm, against 0.01 in ER− tumours. The count also reflects how many T cells surround each tumour cell, but it grows with how tightly the from cells are packed: if T cells form denser clusters in one group, each tumour cell next to a cluster counts more T cells. The default effect counts each tumour cell once, however many T cells are beside it, so denser clusters do not inflate it.

Note

Use the default when your question is whether to cells are placed next to from cells. Use effect="count" when the number of from cells around each to cell is the question, keeping in mind that it also rises when the from cells are packed more tightly. adjust_abundance=True adds the log share of the from type in each image to the model, so that groups are compared at the same abundance; it does not account for how tightly the from cells are packed, and when that share differs strongly between groups, as for HR+ CK7- here, it leaves little power.

Patients with several images#

Each patient here has one core. When patients contribute several images, give the patient column as subject: the images of each patient are combined, and patients remain the units of the test.

Warning

Treating every image as an independent patient overstates the evidence. Always give subject when patients have several images.

Adjusting for clinical covariates#

Covariates measured per patient or per image are added with covariates. Here we also adjust the ER comparison for age at diagnosis and tumour grade.

adata.obs["Grade"] = pd.Categorical(adata.obs["Grade"])
res_cov = spicyr.spicy(adata, condition="ER.Status", subject="metabricId", r=25,
                       covariates=["Age.At.Diagnosis", "Grade"])
res_cov
spicyr (cell-level test): 484 pairs, pos vs neg, r = 25
Units: 456 patients (neg 83, pos 373) with 456 images
Adjusted for: covariates (unadjusted test in the unadjusted_* columns)
50 pairs could not be adjusted and are reported unadjusted (see adjusted_for)
1 pairs have a condition with no informative patient (adjusted_for "none (no_information)") and are not tested
5 pairs have a condition with too few effective patients (adjusted_for "none (few_effective_units)") and are not tested
BH-adjusted p < 0.05: 25 pairs (37 without adjustment)
See top_pairs().

The main columns (excess_difference, p_value, p_adj) are now the ER comparison adjusted for age and grade. Each covariate also has its own effect and p-value. A categorical covariate has one per level after the first: Grade2 and Grade3 compare grades 2 and 3 with grade 1.

res_cov.top_pairs(from_="T cells", to="HR- Ki67+")
from to excess_ref excess_comp excess_difference p_value p_adj Age.At.Diagnosis_effect Age.At.Diagnosis_p_value Grade2_effect Grade2_p_value Grade3_effect Grade3_p_value
T cells__HR- Ki67+ T cells HR- Ki67+ 0.0308 0.1445 0.1136 0.0014 0.0358 0.0015 0.095 -0.0477 0.5794 -0.0418 0.624

The difference between ER+ and ER− patients is much the same after adjusting for age and grade, and neither has a clear effect of its own on this pair. Patients with a missing covariate are left out of the adjusted test.

Note

A pair that cannot be adjusted, for example because its cell types appear in images of only one grade, is reported unadjusted. The printed summary above counts these pairs.

Restricting from_ and to does not change the results for the pairs that are tested.

Which radius?#

The choice of radius determines which relationship is tested. A radius of one or two cell diameters asks whether two cell types touch, a larger one whether they share a neighbourhood. When you know the relationship you are looking for, choose the radius for it and test that one radius. When the scale is unknown, give several radii and spicyr tests them together by the largest of their test statistics, accounting for the strong correlation between neighbouring radii. By default the p-value is Davies’ bound on that maximum, which is fast for any number of radii and slightly conservative; combine="maxT" computes the exact max-T p-value instead, and combine="cauchy" uses the Cauchy combination. About 4 radii spanning the range of interest, none below about one cell diameter, are enough: neighbouring radii are highly correlated, so many closely spaced radii add little information and cost some power.

res_r = spicyr.spicy(adata, condition="ER.Status", subject="metabricId", r=[10, 25, 50, 75])
res_r.top_pairs(from_=["T cells", "B cells"], to="HR- Ki67+")
from to r excess_ref excess_comp excess_difference p_value p_adj
T cells__HR- Ki67+ T cells HR- Ki67+ 10.0 -0.2243 0.9453 1.1696 1.9097e-08 1.1554e-06
B cells__HR- Ki67+ B cells HR- Ki67+ 50.0 -0.0722 0.3472 0.4194 8.3259e-03 9.5946e-02

r is the radius with the strongest evidence, and p_value the combined p-value over all radii. radius_plot() shows the evidence at each radius.

Tip

The effect depends on the radius: at a larger radius more cells have a from cell nearby by chance, and the effect describes placement at that scale. Where most cells have a from cell nearby by chance, there is little room for an effect and it is noisy. Compare p-values across radii rather than the size of the effect. The effect at the chosen radius is a little optimistic, because that radius was picked for its strength.

res_r.radius_plot(from_=["T cells", "B cells"], to="HR- Ki67+");
_images/8dd7278f8afe3a5af2855f97f678ed88087eac4e3f25da083f57acae8a07e42e.png

Is co-localisation associated with survival?#

With survival=(time, event), spicyr asks whether a patient’s effect is associated with their outcome. Here we use relapse-free survival, adjusting for age.

res_s = spicyr.spicy(adata, survival=("timeRFS", "eventRFS"), subject="metabricId", r=25, covariates="Age.At.Diagnosis")
res_s
spicyr (cell-level test): 484 pairs, association with survival, r = 25
Units: 456 patients with 456 images
Adjusted for: covariates
2 pairs are not tested (p_value NaN; see not_tested)
BH-adjusted p < 0.05: 3 pairs
See top_pairs().
res_s.top_pairs(n=6)
from to hazard_ratio_sd p_value p_adj
HR+ CK7-__HR- CK7+ HR+ CK7- HR- CK7+ 0.6227 1.1396e-05 0.0049
HR+ CK7-__HR+ CK7- Ki67+ HR+ CK7- HR+ CK7- Ki67+ 0.6570 2.0488e-05 0.0049
HRlow CKlow__HR- CK7+ HRlow CKlow HR- CK7+ 0.6295 1.3742e-04 0.0221
Macrophages Vim+ CD45low__Myoepithelial Macrophages Vim+ CD45low Myoepithelial 0.6380 9.5168e-04 0.0999
HR- CK7+__HRlow CKlow HR- CK7+ HRlow CKlow 0.7032 1.0867e-03 0.0999
Myoepithelial__Macrophages Vim+ CD45low Myoepithelial Macrophages Vim+ CD45low 0.6532 1.2431e-03 0.0999

The p-value comes from a score test that relates each patient’s effect to their outcome. hazard_ratio_sd is the hazard ratio for a one standard deviation higher effect, from a Cox model; below one, patients with a higher effect had a lower risk of relapse. It is missing when the effect barely varies between patients.

Several pairs are significant after adjusting for multiple testing. The two strongest have HR+ CK7- tumour cells as the from type: patients in whom more of the other tumour cells sat next to HR+ CK7- cells relapsed later. These cells are typical of ER+ tumours, and ER status is itself related to relapse, so we add it to the covariates.

res_s_er = spicyr.spicy(adata, survival=("timeRFS", "eventRFS"), subject="metabricId", r=25, covariates=["Age.At.Diagnosis", "ER.Status"])
res_s_er
spicyr (cell-level test): 484 pairs, association with survival, r = 25
Units: 456 patients with 456 images
Adjusted for: covariates
6 pairs are not tested (p_value NaN; see not_tested)
BH-adjusted p < 0.05: 0 pairs
See top_pairs().

No pair remains significant: these two pairs say little about relapse beyond the tumour’s ER status.

A check you can run#

A test should give few significant results when there is nothing to find. Shuffling the ER labels across patients removes any real difference, so about 5% of pairs should then have p < 0.05, and about 1% p < 0.01. calibration_check() shuffles the condition and runs spicy() with the same arguments, ten times by default; here five, to keep this page quick to build. summary() averages the shuffles and plot() shows each of them.

shuffles = spicyr.calibration_check(adata, condition="ER.Status", subject="metabricId", r=25, n_shuffles=5, rng=2026)
shuffles.summary()
threshold expected percent
0 0.05 5.0 4.3676
1 0.01 1.0 0.5961
shuffles.plot();
_images/c14fdae89aee9c8c02d9724f5c59c4fd1ab4a75276584ea3d23fded3745a1240.png

Pairs share cells, so the percentage moves by a few points from one shuffle to the next.

Tip

Run this check on your own data before trusting a discovery. It takes a few minutes and shows whether the test is calibrated for your study design.

How it works#

For a pair from → to and an image, let \(O\) be the number of to cells with at least one from cell within \(r\), out of \(n\) to cells. If the to cells were a random choice among the cells of the image that are not from cells, keeping every cell where it is, \(O\) would have an exact mean and variance, which spicyr computes without permutations. The effect of an image is

\[\delta = \frac{O - \mathrm{E}_{\mathrm{RL}}(O)}{n - \mathrm{E}_{\mathrm{RL}}(O)},\]

where \(\mathrm{E}_{\mathrm{RL}}(O)\) is that expectation under random labelling. If a fraction \(f\) of the to cells were placed next to from cells and the rest at random, \(\delta\) would estimate \(f\). At radius \(r\), \(O/n\) is the cross-type nearest-neighbour distribution function \(G\) of spatial statistics, and \(\delta\) compares it with random labelling, much as the J function compares \(G\) with the empty-space function (van Lieshout and Baddeley 1996). Negative values mean fewer to cells next to from cells than chance; they are not a fraction, and the lowest possible value, \(-\mathrm{E}_{\mathrm{RL}}(O)/(n - \mathrm{E}_{\mathrm{RL}}(O))\), is far below zero only where from cells are common. With effect="count", \(O\) is instead the sum, over the to cells, of the number of from cells within \(r\) of each, and the denominator is \(n\), an analogue of Ripley’s K function.

Images from the same patient are combined, giving more weight to more informative images (usually those with more to cells), up to a limit: a patient’s images can differ in their true effect, by an amount estimated from the spread between each patient’s images (Paule and Mandel), so one large image cannot outweigh the patient’s other images. Each patient has its own true effect, which varies around its group’s mean by an amount estimated from the data in the same way (a frailty, or random-effects, model). The difference between groups, adjusted for any covariates, is tested on Satterthwaite degrees of freedom with patients as the clusters, using the small-sample cluster-robust (CR2) variance, each group contributing its own CR2 variance. For a self-pair (from_ the same as to), whose cells and neighbours are both moved by random labelling, the variance is the exact random-labelling variance of the self-pair. With the extra fraction, an image whose room on the pair’s side is below one cell is not used. A radius where a group’s effective patients fall below the smaller of three and half its patients at that radius, because a few patients carry nearly all of its weight, is not tested. This is designed to keep false positives near the nominal rate even with modest numbers of patients. A paper describing the method is in preparation.

Small studies#

With fewer than about ten patients per group, expect few significant pairs, even when an effect is consistent across patients: a calibrated test cannot be confident with little information. A group needs at least three patients, and in practice a few more, since patients rarely carry equal weight. Look at whether the patients agree in direction with box_plot().

Note

variance="hartung_knapp" can give more power in very small studies, but it can give too many small p-values for rare cell types, so it is not the default.

Very large data sets: SpatialData stores#

Some imaging studies hold more cells than fit in memory. spicy() also reads a SpatialData Zarr store, or an AnnData Zarr store, from disk: give the path of the store as cells. Every neighbour count is a sum within one image, so spicyr loads the image and cell-type columns once as integer codes and reads the coordinates one batch of whole images at a time. Memory then depends on the size of an image and on the number of threads (cores), not on the size of the study, and the results are the same as for the same cells in memory.

write_cell_store() writes cells as a SpatialData store. An AnnData object is written whole: its obs as the table’s obs, with the image column as its region key, and X, layers, var, obsm (with the coordinates in "spatial") and uns as anndata writes them; the cells of each image also become a points element. We write the whole data set, so that the results can be compared with those above.

import tempfile
from pathlib import Path

path = spicyr.write_cell_store(adata, Path(tempfile.mkdtemp()) / "metabric.zarr")

spicy() reads the store with the same arguments as the object in memory, and gives the same results:

res_store = spicyr.spicy(str(path), condition="ER.Status", subject="metabricId", r=25)
pd.testing.assert_frame_equal(res_store.cell_results, res.cell_results, check_exact=True)
res_store.cell_results.equals(res.cell_results)
True

Every estimate, standard error and p-value is identical, not just close. The spatialdata package reads the same store as a SpatialData object, which spicy() analyses in the same way:

import spatialdata as sd

sdata = sd.read_zarr(path)
res = spicyr.spicy(sdata, condition="ER.Status", subject="metabricId", r=25)

A few arguments matter for stores. table_key chooses the cell table of a SpatialData store or object (by default "table"). image_info supplies the condition, the patient, covariates or the survival columns when they are not columns of the cell table: give a DataFrame (or an AnnData object) whose image_id column, or else its index, holds the image IDs, or the key of a table in the store. Every image needs a row in it. spatial_coords names either two obs columns or one obsm array, whose first two columns are used; by default obsm["spatial"].

Tip

Store the cells grouped by image. When the rows of each image sit together, as they do when the table is sorted by its region column before it is written, each batch of images is read as one slice of rows. Otherwise each batch needs a pass over the image codes. Categorical image and cell-type columns also keep the store small.

In a benchmark on a synthetic store of one billion cells in 500 images, spicy() ran on one thread in under 4 GB of memory.

Reporting results#

A methods sentence might read: “We used spicyr (version 1.99.15) to test, for every ordered pair of cell types, whether the fraction of to cells with at least one from cell within 25 µm, relative to random labelling of the cells in each image, differed between ER+ and ER− patients, with patients as the units of analysis. P-values were adjusted across pairs by the Benjamini–Hochberg method.” Show a per-patient plot (box_plot()) and an image of the pair (plot_image()) alongside the p-value. Please cite Canete et al. (2022), Bioinformatics 38(11), 3099–3105; a paper describing the cell-level test is in preparation.

spicyR in R#

The same test is in the Bioconductor package spicyR, for SpatialExperiment objects, with the same results. spicyR also has the original image-level test of spicyR before version 2.0.

Session information#

import importlib.metadata as md
import platform

print("Python", platform.python_version())
for p in ["spicyr", "numpy", "pandas", "anndata", "zarr", "matplotlib", "plotly"]:
    print(p, md.version(p))
Python 3.12.16
spicyr 1.99.47
numpy 2.5.5
pandas 3.1.1
anndata 0.13.4
zarr 3.4.2
matplotlib 3.11.2
plotly 7.1.0