Test for changes in the co-localisation of cell types between conditions
Source:R/spicy_main.R
spicy.Rdspicy() tests, for every ordered pair of cell types from → to, whether the co-localisation of
the two types differs between conditions, or is associated with survival. A pair asks whether to
cells are placed near from cells more than other cells are.
Usage
spicy(
cells,
condition,
subject = NULL,
covariates = NULL,
imageID = "imageID",
cellType = "cellType",
spatialCoords = c("x", "y"),
r = NULL,
from = NULL,
to = NULL,
method = c("cell", "image"),
effect = c("fraction", "count", "allocation"),
k = NULL,
combine = c("davies", "maxT", "cauchy"),
adjustAbundance = FALSE,
variance = c("cr2", "hartung_knapp"),
ref = NULL,
cores = 1,
tableKey = NULL,
imageInfo = NULL,
cellWeights = NULL,
selfVariance = c("sampled", "exact", "geometricSampled", "geometric"),
selfVarianceCells = 50,
alpha = 0.05,
...
)Arguments
- cells
A
data.frame,SingleCellExperimentorSpatialExperimentwith one row (column) per cell, or (cell method) the path of a SpatialData or AnnData Zarr store (read with the Rarr package). From a store, the columns are read a block of rows at a time and the coordinates a batch of whole images at a time, so the table is never held in memory; the results are those of the same cells given as adata.frame. Column names then refer to the table'sobs;imageIDdefaults to the table's region key andspatialCoordsto itsobsmarray"spatial". ASpatialDataobject (spatialdataR) read from a store is read from that store in the same way; one built in memory is analysed from its table.- condition
The column of the image-level condition (from a store, a column of
imageInfo): two groups; more than two groups (cell method: each level against the reference, and an overall test of all of them); a number with more than two values, taken as continuous (cell method: the slope of the effect on it); or asurvival::Survcolumn for a survival outcome. Give a factor to compare numeric values as groups.- subject
The column of the patient (unit) of each image. Images of one patient are combined; if omitted, every image is its own patient.
- covariates
Image- or patient-level columns to adjust for (cell method: added to the design of the excess, with the patient average of an image-level one (see Details), and the effect of each is reported as
<column>_effectand<column>_p_value, for an image-level one its slope within patients; survival: added to the null Cox model and to the model of the effect, see Details).- imageID, cellType, spatialCoords
Column names of the image, cell type and coordinates. For a Zarr store,
spatialCoordsis either twoobscolumns or the name of oneobsmarray (its first two columns).- r
Radius (or radii) of the neighbourhood, in the units of the coordinates. Cell method: one radius (default 50), or several to be combined by
combine(two conditions only; a survival outcome takes one radius). Image method: the radii of the L function (default 20, 50 and 100).- from, to
Cell types to test (all ordered pairs by default).
- method
"cell"(spicyR v2, the default) or"image"(spicyR v1, the original spicyR test).- effect
Cell method:
"fraction"(the default), the extra fraction oftocells with at least onefromcell withinr; or"count", the number of extrafromcells withinrof eachtocell."allocation", the earlier name of"fraction", is also accepted. Withk, "withinr" means among the cell'sknearest neighbours.- k
Cell method: use the
knearest neighbours instead of a radius.- combine
Cell method with several radii:
"davies"(the default: Davies' upper bound on the max-T p-value, a closed form that is never smaller than the exact p-value and takes microseconds for any number of radii; slightly conservative, about 1.1 times the exact p-value with 4 radii and 1.3 to 1.4 times with 8 to 16),"maxT"(the exact max-T p-value with the sandwich correlation across radii) or"cauchy"(Cauchy combination). Both"davies"and"maxT"use the largest |z| over the radii; Davies' bound needs only the correlations of neighbouring radii, the exact p-value all of them. The max-T p-value is the multivariate normal probability that the largest |z| over the radii is at least the one observed, computed as a sum of first-exceedance terms by the quasi-Monte Carlo method of Genz and Bretz to a relative error of about 0.1\ radii); the same inputs always give the same value. A radius whose correlation with a smaller kept radius exceeds 0.995 is left out. Choose one radius from the relationship of interest when you can; when the scale is unknown, we recommend about 4 radii spanning the range of interest, none below about one cell diameter: many closely spaced radii add little information (neighbouring radii are highly correlated), cost some power, make the correlation hard to estimate with few patients and, with max-T, are slower (with 25 radii, about a second per pair against a few milliseconds with 4); radii below a cell diameter can be liberal in large cohorts. With max-T,$cellResultshasmaxT_converged:TRUEwhen the pair's p-value met the 0.1\ when the integrator stopped at its limit of points first (its error may then be larger).- adjustAbundance
Cell method: adjust the test for the log share of the
fromtype in each image (defaultFALSE), and for its patient average when patients have several images (see Details). Its effect is reported asabundance_effect(then the slope within patients). It does not separate morefromcells from more densely packed ones, and it removes real effects when the share tracks the condition.- variance
Cell method:
"cr2"(the default: each condition's CR2 variance, on Satterthwaite df, see Details) or"hartung_knapp"(the model-based variance, scaled by the Pearson statistic when that exceeds its df and never below CR2, on m - 2 df).- ref
Cell method: the reference level of
condition(not for a continuous condition).- cores
Number of threads (cell method) or cores (image method).
- tableKey
Cell method with a SpatialData store or object: the name of the cell table in
tables/(by default the only table, or the one called"table").- imageInfo
Cell method: a table with one row per image, for
condition,subject,covariatesor a survival outcome that are not columns of the cell table: adata.framewhoseimageIDcolumn, or else its row names, gives the image IDs, or the name of a table of the SpatialData store or object. Every image of the cells needs a row, and every row an image. Asurvival::Survcolumn given asconditionmakes a survival analysis, also from a store.- cellWeights
Optional cell weights in [0, 1], in the order of
cells: a numeric vector with one weight per cell for its own cell type (for example a quality score), or a matrix (or sparseMatrix) of soft cell type membership with one row per cell and one named column per label (for example a classifier's confidence). With a matrix,fromandtoname its columns, and labels may overlap (a group and its subtypes). Cell method: atocell counts with its weight, and its score is the chance that it has afromneighbour withinrif each cell were afromcell with probability itsfromweight (allocation), or the summedfromweight of its neighbours (count). The null shuffles thetoweights over the cells whosefromweight is below 1 (so a cell of thefromtype with weight 0.6 is a candidate with the remaining 0.4), and its exact mean and variance replace those of random labelling; weights of 1 give the results of the cell types. The abundance share is thefromlabel's summed weight over the image's cells. A label with itself, and a pair where sometocells havefromweight 1 (for example a group and one of its subtypes), are tested instead under random labelling of all the image's cells, each cell keeping its pair offromandtoweights and never its own neighbour, with the mean and variance of the score under that permutation (fraction: by default from a closed form that corrects every pair of cells exactly for sampling without replacement, exact for up to two cells and second order in 1 / cells;selfVariance = "exact"computes them exactly, at a cost of cells x neighbourhood size^2 per image; count: exact) (for the count effect, as for a self-pair of cell types, the expected score is a share of the summedfromweight around all the cells, the share that gives the difference a mean of 0). With 0/1 weights a label with itself gives the self-pair of that cell type (fraction: with the variance ofselfVariance). One cell withfromweight 1 and atoweight above 0 in any image is enough to test a pair this way in every image. One radius and cells in memory. Image method: seegetPairwise().- selfVariance
Cell method, extra fraction with a radius: how a self-pair's variance counts the neighbours shared by nearby cells:
"sampled"(the default),"exact","geometricSampled"or"geometric"(see Details). With softcellWeights,"exact"gives the exact moments of the pairs tested under random labelling of all cells, and any other value the closed form described undercellWeights.- selfVarianceCells
The number of cells sampled in each image for
selfVariance = "sampled"or"geometricSampled"(every cell when an image has no more).- alpha
Cell method with more than two conditions: the level of the gate for the follow-up comparisons (pairs whose
overall_p_adjis at mostalphaare followed up; seetopFollowUps()). Default 0.05.- ...
Arguments of the image method:
sigma,alternateResult,minLambda,weights,weightsByPair,weightFactor,weightZThreshold,window,window.length,edgeCorrect,includeZeroCells,verbose,BPPARAM. SupplyingalternateResultselects the image method.
Value
A SpicyResults object. topPairs(), signifPlot(), spicyBoxPlot() and bind() work
for both methods. For the cell method, $cellResults holds the full table: for the extra fraction,
the pair's side ("attract" or "avoid", which sets the scale of the effect), the effect in each
condition (excess_ref, excess_comp, at the average covariates), the difference
(excess_difference), its standard error, df, p-value and BH-adjusted p-value, the frailty variance, the
between-image variance (tau2_image; of the adjusted test when it was adjusted for a column that differs
between a patient's images) and, when the test was adjusted, what for (adjusted_for), the effect
and p-value of each adjustment, and the unadjusted test (unadjusted_difference, unadjusted_p_value, unadjusted_p_adj).
With more than two groups, one row per pair and level against the reference, and the overall test of the pair
(overall_F on overall_df1 and overall_df2 df, overall_p_value, overall_p_adj: the CR2 Wald test of
every level equal to the reference, with the HTZ small-sample F of Tipton and Pustejovsky 2015; Pustejovsky and
Tipton 2018, eqs. 12-13: the approximate Hotelling's T^2 test that all the condition means are equal, which does
not depend on the reference; with two levels it is the t-test, F = t^2). A pair is tested only when every level
passes the rules below. For the pairs called by the overall test (overall_p_adj at most alpha),
$followUpResults compares every two levels, each by the two-condition test on the patients of those two levels,
Bonferroni-corrected within the pair at the Benjamini-Bogomolov level (see topFollowUps()). With a continuous
condition, one row per pair: the effect at the condition's mean (excess_mean) and its slope per unit of the
condition (excess_slope), with its CR2 standard error and Satterthwaite df, in place of the two groups' columns.
With a survival outcome, one row per pair: the score test (score_coefficient, the coefficient of M, with
score_se, score_df, p_value, p_adj), the hazard ratio (hazard_ratio_sd, log_hr_sd, log_hr_se,
log_hr_per_unit), tau2, the informative patients' deaths (n_deaths) and, with adjustAbundance = TRUE,
the test without the abundance share (unadjusted_p_value, unadjusted_hazard_ratio_sd, unadjusted_p_adj).
Every requested pair has a row: not_tested gives why a pair (or, in $radiusResults, a radius) was not tested
("one_patient_per_group", "no_information", "few_effective_units", "no_variation" or "too_few_df"; for a
continuous condition also "too_few_units" or "design_not_full_rank" (the condition does not vary); for
survival also "no_deaths", "no_survivors" or "too_few_units"; NA when it was), and its p-value is then
NA and not counted in the BH adjustment. $effect records which effect was estimated.
$pairwiseAssoc holds each pair's effect in every image and $imageWeights each image's share of its
condition's information in the pair's test; with two conditions, $conditionInformation holds that information
for each pair (one column per condition: the sum of the weights of its patients). With adjustment or several radii these
three are those of the unadjusted test at the radius nearest the median. testCorrelation() uses them to
estimate the correlation between the pairs' tests.
Details
method = "cell" (the default). In each image, the share of to cells with at least one from
cell within radius r is compared with its exact expectation q if the to cells were a random choice
among the cells that are not from cells. The effect (effect = "fraction", the default) is the
fraction of to cells placed next to (or kept away from) from cells. For a pair that attracts
(more to cells next to from cells than q over all images together) it is (observed share - q) / (1 - q):
if a fraction f of the to cells were moved next to from cells, the effect is f. For a pair that avoids
it is (observed share - q) / q: if a fraction f of the to cells that would have a from cell nearby were
moved away, the effect is -f. Either way it does not depend on how many from cells there are or how
densely they are packed. The side is chosen once per pair from all images with a condition, without the
conditions, and is reported in the side column. effect = "count" gives the number of extra from
cells within r of each to cell instead; it also reflects how many from cells surround a to cell
(depth of infiltration), but it grows with how densely the from cells are packed, so a change in
packing alone can appear as a change in co-localisation. Images are combined within patients and
patients within conditions by a frailty GEE with a second random effect for the images of a patient (each image
is weighted by 1 / (its sampling variance + the between-image variance), so one large image cannot outweigh the
patient's other images), and the difference between conditions is tested with a
CR2 cluster-robust variance on Satterthwaite degrees of freedom, with patients (subject) as the
units. The difference is adjusted for any covariates, and, with adjustAbundance = TRUE, for the
log share of the from type in each image; the unadjusted test is then reported alongside
(unadjusted_* columns).
An adjustment that differs between a patient's images (the from type's share, or an image-level covariate)
can relate to the effect differently within a patient than between patients. Each such column therefore gets a
second column, its plain average over the patient's images: the conditions are compared at equal patient averages,
and the reported effect of the adjustment (<column>_effect) is its slope within patients. For example, with
images of 10% and 30% from cells in one patient, the average 20% describes the patient and the 10% and 30%
the slope within it. The between-image variance is then estimated within patients from what the adjustments leave
(each patient's own mean free; tau2_image), and the patient variance (tau2) from the patients' average effects
and adjustments, each by Paule-Mandel. An adjustment with one value per patient (for example age) gets no
second column. Adjustment cannot fully remove a confounder that is measured with noise: when the adjustment varies
mostly within patients, patients have few images and it differs by condition, some bias remains.
When nearly every cell has a from cell within r (q close to 1), there is little room for attraction and
an attracting pair's images carry little information; a smaller r is more informative.
The extra fraction is bounded: an image of an avoiding pair with no to cell next to a from cell has the
effect -1, and an image of an attracting pair with every to cell next to one has +1. A patient is informative at
a radius when at least one of its images is not at -1 or +1. A radius where one condition has no informative
patient is not tested: that condition's patients all have the same effect, so its spread is exactly 0 and the
standard error would rest on the other condition alone. Its p-value is NA (with adjustment, adjusted_for is
"none (no_information)"), and it is left out of the combination over radii. With more than two conditions, a
pair where any condition has no informative patient is not tested.
The standard error of the difference is the sum of each condition's own CR2 variance, on Satterthwaite degrees of
freedom; with adjustment, the CR2 variance of the adjusted design. variance = "hartung_knapp" keeps its own
variance.
Without adjustment, the CR2 t of two conditions is corrected for skewness (a one-term Edgeworth expansion, Hall's transformation) before its p-value is taken: with conditions of unequal size, right-skewed patient effects make the t of the smaller condition's mean skewed, with too many small p-values on one side. The skewness comes from the patients' residuals, pooled over both conditions and weighted as in the test, and is shrunk by its own uncertainty, so that the correction fades out in small studies; it also vanishes for conditions of equal size and weight, and is not applied when a condition has fewer than 3 patients. The difference, standard error and df are unchanged.
For a self-pair (from = to) every cell can carry the label, so random labelling moves both the cells counted
and their neighbours. Its variance is the random-labelling variance of the self-pair (for the radius graph and for
the k nearest neighbours), not the variance of a pair of two types. For the extra fraction this variance
depends on how many neighbours each pair of nearby cells shares, which takes time in proportion to the number of
cells times the square of the number of neighbours per cell. With a radius, the shared neighbours are by default
counted from selfVarianceCells randomly chosen cells of each image and scaled up (selfVariance = "sampled"),
an unbiased estimate of the variance; the sample is fixed by the image, so results are reproducible.
selfVariance = "exact" counts them for every cell; "geometric" takes two cells to share their local density
times the area where their two discs overlap; "geometricSampled" corrects that with the sampled cells. The count
effect and the k nearest neighbours always use the exact variance.
With the extra fraction, an image whose room on the pair's side (the to cells without a from neighbour
expected by chance for an attracting pair, those with one for an avoiding pair) is below one cell is not used:
its effect could not show the pair's side, and could be large in the other direction. The side is chosen first,
from every image.
A patient's weight within its condition grows with the information of its images, so one or two patients can
carry nearly all of a condition's weight. A radius where a condition's effective patients (Kish's
(sum w)^2 / sum w^2 of the patients' weights w) fall below the smaller of 3 and half the number of its patients
that contribute at that radius is not tested: its p-value is NA (with adjustment, adjusted_for is
"none (few_effective_units)"), and it is left out of the combination over radii. A condition of 3 patients with
equal weights can therefore be tested. With more than two conditions, a pair where any condition falls below this
is not tested.
Images with a missing condition are left out of every step: the choice of the side, the between-image variance and the tests.
A test (of any condition) is not done when its Satterthwaite degrees of freedom are below 1 or not finite
(not_tested is "too_few_df"): its p-value is NA and it is left out of the BH adjustment.
Survival. With a survival::Surv outcome, a null Cox model of the outcome on the covariates gives each
patient's martingale residual M, and the effect is regressed on M (with the covariates, and with
adjustAbundance = TRUE the log share of the from type) by the same frailty model, CR2 variance and
Satterthwaite df; its numerator is Cox's score statistic. The covariates are on both sides: in the null Cox model
(an image-level covariate as its average over the patient's images) and in the model of the effect. Patients with
no outcome (or with a covariate missing in all their images) are left out before anything else, so the result is
that of the data without them. A survival outcome is tested at one radius. A pair is tested when, among its
informative patients (those with an outcome and an image row for the pair), there is at least one death
("no_deaths") and one survivor ("no_survivors"), and at least q + 2 patients ("too_few_units"), q being the
number of columns of the patient design: 2 (intercept and M), plus one per covariate column, plus one more for
each column that varies between a patient's images (the abundance share always does): 4 patients without
covariates, 5 with one patient-level covariate, 6 with the abundance share. n_deaths reports the informative
patients' deaths; with fewer than 3 the test has little power. The hazard ratio (hazard_ratio_sd, per standard
deviation of the effect; log_hr_per_unit, per unit) is from a Cox model of the outcome on each patient's
shrunken effect (from the frailty model of the effect on the covariates, without M) and the covariates; its
standard error log_hr_se is model-based and approximate (it ignores that the shrunken effect is estimated), so
the score test's p_value is the only p-value of a pair.
A column that varies between a patient's images (the abundance share, or an image-level covariate) enters
both frailty models with its patient average, as for the condition tests (see above): the between-image
variance is then re-estimated within patients (tau2_image) and tau2 from the patients' averages.
method = "image" (the original spicyR test). A per-image L-function summary of each pair is
compared between conditions with a weighted linear model, or a mixed model when subject is given
(Canete et al. 2022). With cellWeights (see getPairwise()), cells enter each label with a weight,
for example the confidence of a classifier, instead of through a single cell type.
References
Canete NP et al. (2022). spicyR: spatial analysis of in situ cytometry data in R. Bioinformatics 38(11), 3099-3105. doi:10.1093/bioinformatics/btac268
Bell RM, McCaffrey DF (2002). Bias reduction in standard errors for linear regression with multi-stage samples. Survey Methodology 28(2), 169-181.
Pustejovsky JE, Tipton E (2018). Small-sample methods for cluster-robust variance estimation and hypothesis testing in fixed effects models. Journal of Business & Economic Statistics 36(4), 672-683. doi:10.1080/07350015.2016.1247004
Tipton E, Pustejovsky JE (2015). Small-sample adjustments for tests of moderators and model fit using robust variance estimation in meta-regression. Journal of Educational and Behavioral Statistics 40(6), 604-634. doi:10.3102/1076998615606099
Paule RC, Mandel J (1982). Consensus values and weighting factors. Journal of Research of the National Bureau of Standards 87(5), 377-385. doi:10.6028/jres.087.022
Hartung J, Knapp G (2001). A refined method for the meta-analysis of controlled clinical trials with binary outcome. Statistics in Medicine 20(24), 3875-3889. doi:10.1002/sim.1009
Liu Y, Xie J (2020). Cauchy combination test: a powerful test with analytic p-value calculation under arbitrary dependency structures. Journal of the American Statistical Association 115(529), 393-402. doi:10.1080/01621459.2018.1554485
Examples
data("diabetesData")
# spicyR v2: patients ("case") are the units
# the extra fraction of Th cells, and of beta cells, with a Tc cell within 50 units
res <- spicy(diabetesData, condition = "stage", subject = "case", r = 50,
from = "Tc", to = c("Th", "beta"))
topPairs(res)
#> from to level excess_ref excess_difference
#> Tc__Th__Onset Tc Th Onset 0.3225594 0.067948496
#> Tc__Th__Long-duration Tc Th Long-duration 0.3225594 -0.001655389
#> Tc__beta__Onset Tc beta Onset NA NA
#> Tc__beta__Long-duration Tc beta Long-duration NA NA
#> p_value p_adj overall_p_value overall_p_adj
#> Tc__Th__Onset 0.6078397 0.6078397 0.8619533 0.8619533
#> Tc__Th__Long-duration 0.9859338 0.9859338 0.8619533 0.8619533
#> Tc__beta__Onset NA NA NA NA
#> Tc__beta__Long-duration NA NA NA NA
res$cellResults
#> from to level side excess_ref
#> Tc__Th__Onset Tc Th Onset attract 0.3225594
#> Tc__Th__Long-duration Tc Th Long-duration attract 0.3225594
#> Tc__beta__Onset Tc beta Onset <NA> NA
#> Tc__beta__Long-duration Tc beta Long-duration <NA> NA
#> excess_difference se df p_value
#> Tc__Th__Onset 0.067948496 0.12418948 4.993347 0.6078397
#> Tc__Th__Long-duration -0.001655389 0.08941797 5.087533 0.9859338
#> Tc__beta__Onset NA NA NA NA
#> Tc__beta__Long-duration NA NA NA NA
#> p_adj overall_F overall_df1 overall_df2
#> Tc__Th__Onset 0.6078397 0.1531064 2 4.946364
#> Tc__Th__Long-duration 0.9859338 0.1531064 2 4.946364
#> Tc__beta__Onset NA NA NA NA
#> Tc__beta__Long-duration NA NA NA NA
#> overall_p_value overall_p_adj tau2 tau2_image
#> Tc__Th__Onset 0.8619533 0.8619533 0.003755877 0.04266841
#> Tc__Th__Long-duration 0.8619533 0.8619533 0.003755877 0.04266841
#> Tc__beta__Onset NA NA NA 0.48210348
#> Tc__beta__Long-duration NA NA NA 0.48210348
#> not_tested
#> Tc__Th__Onset <NA>
#> Tc__Th__Long-duration <NA>
#> Tc__beta__Onset one_patient_per_group
#> Tc__beta__Long-duration one_patient_per_group
# the extra number of Tc cells within 50 units of each Th cell
resCount <- spicy(diabetesData, condition = "stage", subject = "case", r = 50,
from = "Tc", to = "Th", effect = "count")
# the original image-level test
resImage <- spicy(diabetesData, condition = "stage", subject = "case",
from = "Tc", to = "Th", method = "image")
#> Dropping unused levels. Using stage = Non-diabetic as base comparison group. If this is not the desired base group, please convert cells$stage into a factor and change the order of levels(cells$stage) so that the base group is at index 1.
topPairs(resImage)
#> intercept coefficient p.value adj.pvalue from to
#> Tc__Th 1.622672 5.961811 0.6122509 0.6122509 Tc Th