Package 'spicyR'

Title: Test Changes in the Co-Localisation of Cell Types Between Groups of Patients
Description: spicyR tests whether the spatial co-localisation of pairs of cell types differs between groups of patients, or is associated with patient outcome, in cell-resolution spatial omics data (imaging mass cytometry, CODEX, MIBI, Xenium, CosMx and others). Its default method, spicyR Cell, counts the cells of one type within a radius of each cell of another and compares the count with its exact expectation under random labelling of the observed cells. Images are combined within patients by a frailty generalised estimating equation, and differences are tested with a small-sample cluster-robust (CR2) variance with patients as the units. Covariates, several conditions, several radii and survival outcomes are supported, and the original image-level test is kept as an option. The computations run in a C++ core shared with the Python package spicyr.
Authors: Nicolas Canete [aut], Ellis Patrick [aut, cre], Sadiq Dohadwalla [aut], Elijah Willie [aut], Nicholas Robertson [ctb], Alex Qin [ctb], Farhan Ameen [ctb], Shreya Rao [ctb]
Maintainer: Ellis Patrick <[email protected]>
License: GPL (>=2)
Version: 2.0.1
Built: 2026-11-24 23:56:58 UTC
Source: https://github.com/bioc/spicyR

Help Index


The per-image values of every pair, or of one pair, as a data frame

Description

Returns, for each image, its condition and the value of each pair that spicy() tested: for the cell method its effect (by default the extra fraction of to cells with a from cell within r; with effect = "count", the extra from cells per to cell), or the L-function summary for the image method. Use it for your own plots or models, or with from and to to look up the images behind one pair.

Usage

bind(results, pairName = NULL, from = NULL, to = NULL, parent = NULL)

Arguments

results

The SpicyResults object returned by spicy().

pairName

A pair, as "from__to". If NULL, all pairs are returned.

from, to

One pair: a table of that pair alone, with its value in a column effect (value for the image method) and, for the cell method, each image's weight in the test.

parent

For a Kontextual result, the parent population of the pair given by from and to.

Value

A data.frame with one row per image, named by image: imageID, condition, subject (if given) and one column per pair, named "from__to", or with from and to the columns effect (or value) and weight. NA where the pair could not be measured in an image.

Examples

data(spicyTest)
df <- bind(spicyTest)

data("diabetesData")
res <- spicy(diabetesData, condition = "stage", subject = "case", r = 50, from = "Tc", to = "Th")
head(bind(res, from = "Tc", to = "Th"))

Build a k-nearest-neighbour graph between cells

Description

Finds the k nearest neighbours of every cell within its own image and stores them as a colPair of cells, ready for convPairs(). Distances are Euclidean, a cell is not its own neighbour, and ties are broken as in spatstat.geom::nnwhich(). The graph is the one imcRtools::buildSpatialGraph(type = "knn") builds, computed by the C++ core that spicy() uses for k.

Usage

buildKnnGraph(
  cells,
  k = 20,
  imageID = "imageID",
  spatialCoords = c("x", "y"),
  name = "knn_interaction_graph",
  cores = 1
)

Arguments

cells

A SingleCellExperiment or SpatialExperiment.

k

The number of neighbours of each cell. Cells in images with at most k cells get no neighbours.

imageID

The colData column holding the image of each cell.

spatialCoords

The colData columns holding the coordinates. A SpatialExperiment's own spatialCoords() are used unless these name colData columns.

name

The name of the colPair the graph is stored in.

cores

The number of threads; images are processed in parallel.

Value

cells, with the graph in colPair(cells, name): one edge from each cell to each of its neighbours.

Examples

data("diabetesData")
diabetesData <- buildKnnGraph(diabetesData, k = 10)
head(SingleCellExperiment::colPair(diabetesData, "knn_interaction_graph"))

Check that spicy() is calibrated on your data by shuffling the condition

Description

Shuffles the condition across patients (or across images, without subject), which removes any real difference between the groups while keeping everything else about the study, and runs spicy() on each shuffle. If the test is calibrated, about 5% of pairs have p < 0.05 and about 1% p < 0.01 in each shuffle. Pairs share cells, so the percentage moves by a few points from one shuffle to the next; look at the average over shuffles.

Usage

calibrationCheck(
  cells,
  condition,
  subject = NULL,
  nShuffles = 10,
  thresholds = c(0.05, 0.01),
  ...
)

## S3 method for class 'spicyCalibration'
summary(object, ...)

## S3 method for class 'spicyCalibration'
plot(x, ...)

Arguments

cells

The cells, as for spicy(): a SpatialExperiment, SingleCellExperiment or data.frame (not a store).

condition

The column of the condition to shuffle (a factor, character, number or Surv column).

subject

The column of the patient. Each patient keeps one condition, moved as a whole; without it, the condition is shuffled across images.

nShuffles

The number of shuffles.

thresholds

The p-value thresholds to report.

...

Other arguments of spicy(), such as r, imageID, cellType or covariates.

object, x

The result of calibrationCheck().

Value

A data.frame with one row per shuffle and threshold: shuffle, threshold and percent, the percentage of pairs whose p-value is below the threshold. summary() gives the average percentage over the shuffles at each threshold, with the expected one, and plot() shows each shuffle against the expected percentage.

Examples

data("diabetesData")
set.seed(1)
shuffles <- calibrationCheck(diabetesData, condition = "stage", subject = "case", r = 50, nShuffles = 2)
summary(shuffles)
plot(shuffles)

Perform a simple wilcoxon-rank-sum test or t-test on the columns of a data frame

Description

Perform a simple wilcoxon-rank-sum test or t-test on the columns of a data frame

Usage

colTest(
  df,
  condition,
  type = NULL,
  feature = NULL,
  imageID = "imageID",
  subject = NULL
)

Arguments

df

A data.frame or SingleCellExperiment, SpatialExperiment

condition

The condition of interest

type

The type of test, "wilcox", "ttest" or "survival".

feature

Can be used to calculate the proportions of this feature for each image

imageID

The imageID's if presenting a SingleCellExperiment

subject

Optional, with a SingleCellExperiment or SpatialExperiment: the column of the patient. The proportions are then those of each patient's cells, all images pooled, and each patient is one unit of the test.

Details

With a matrix or data.frame df and a condition whose names (a vector, factor or Surv with names) or row names (a matrix or data.frame) are row names of df, the rows of df are matched to condition by name, and rows without a condition are left out. Otherwise condition is taken in the row order of df.

Value

A data.frame with one row per column of df (for example per cell type), ordered by p-value: the mean (t-test) or median (Wilcoxon test) in each condition, the test statistic, the p-value (pval), the Benjamini-Hochberg adjusted p-value (adjPval) and the column name (cluster).

Examples

# Test for a difference in cell-type proportions between onset and long-duration diabetes
# (images are treated as independent here, which ignores that each donor has several)
data("diabetesData")
props <- getProp(diabetesData)
images <- unique(as.data.frame(SummarizedExperiment::colData(diabetesData))[, c("imageID", "stage")])
condition <- setNames(as.character(images$stage), images$imageID)
condition <- condition[condition %in% c("Long-duration", "Onset")]
test <- colTest(props, condition)   # the rows of props are matched to condition by name
head(test)

# with donors as the units: each donor's cells, all images pooled
diabetes <- diabetesData[, diabetesData$stage %in% c("Long-duration", "Onset")]
head(colTest(diabetes, condition = "stage", feature = "cellType", subject = "case", type = "wilcox"))

Converts colPairs object into an abundance matrix based on number of nearby interactions for every cell type.

Description

Converts colPairs object into an abundance matrix based on number of nearby interactions for every cell type.

Usage

convPairs(cells, colPair, imageID = "imageID", cellType = "cellType")

Arguments

cells

A SingleCellExperiment that contains objects in the colPairs slot.

colPair

The name of the object in the colPairs slot for which the dataframe is constructed from.

imageID

The image ID if using SingleCellExperiment.

cellType

The cell type if using SingleCellExperiment.

Value

Matrix of abundances

Examples

data("diabetesData")
images <- c("A09", "A11", "A16", "A17")
diabetesData <- diabetesData[
  , SummarizedExperiment::colData(diabetesData)$imageID %in% images
]

diabetesData <- buildKnnGraph(diabetesData, k = 20)

pairAbundances <- convPairs(diabetesData,
  colPair = "knn_interaction_graph"
)

Imaging mass cytometry of human pancreas in type 1 diabetes (Damond et al. 2019)

Description

Cell types and positions from imaging mass cytometry of pancreas sections from 12 donors at three stages of type 1 diabetes (Damond et al. 2019): 4 non-diabetic donors, 4 at onset and 4 with long-duration disease. The object holds 253,777 cells from 120 images, 10 images per donor. It has no assays: only the cell data used by spicyR.

Usage

data("diabetesData")

Format

A SingleCellExperiment with one column per cell and these colData columns:

imageID

the image (character)

cellID, imageCellID

cell identifiers, in the whole data set and within its image

x, y

the cell's coordinates in the image, in micrometres

cellType

the cell type assigned by the authors (factor)

case

the donor (integer)

slide, part

the slide, and the part of the pancreas (head, body or tail)

group, stage

the stage of type 1 diabetes, as a code and as a factor with levels "Non-diabetic", "Onset" and "Long-duration"

Source

Damond N et al. (2019). Mendeley Data, doi:10.17632/cydmwsfztj.1, under the CC BY 4.0 licence. How the subset was made is described in inst/scripts/make-diabetesData.R.

References

Damond N, Engler S, Zanotelli VRT, et al. (2019). A map of human type 1 diabetes progression by imaging mass cytometry. Cell Metabolism 29(3), 755-768. doi:10.1016/j.cmet.2018.11.014

Examples

data("diabetesData")
table(unique(as.data.frame(SummarizedExperiment::colData(diabetesData))[, c("case", "stage")])$stage)

Get statistic from pairwise L curve of a single image.

Description

Get statistic from pairwise L curve of a single image.

Usage

getPairwise(
  cells,
  imageID = "imageID",
  cellType = "cellType",
  spatialCoords = c("x", "y"),
  r = NULL,
  sigma = NULL,
  from = NULL,
  to = NULL,
  cores = 1,
  minLambda = 0.05,
  window = "convex",
  window.length = NULL,
  edgeCorrect = TRUE,
  includeZeroCells = FALSE,
  BPPARAM = NULL,
  imageIDCol = imageID,
  cellTypeCol = cellType,
  spatialCoordCols = spatialCoords,
  nCores = cores,
  Rs = r,
  cellWeights = NULL
)

Arguments

cells

A data.frame, SingleCellExperiment or SpatialExperiment with one row (column) per cell, giving its image, cell type and coordinates.

imageID

The name of the image ID column.

cellType

The name of the cell type column.

spatialCoords

The names of the coordinate columns.

r

A vector of the radii that the measures of association should be calculated over.

sigma

A numeric variable used for scaling when fitting inhomogenous L-curves.

from

The 'from' cellType for generating the L curve.

to

The 'to' cellType for generating the L curve.

cores

Number of cores to use for parallel processing or a BiocParallel MulticoreParam or SerialParam object.

minLambda

Minimum value density for scaling when fitting inhomogeneous L-curves.

window

Should the window around the regions be 'square', 'convex' or 'concave'.

window.length

A tuning parameter for controlling the level of concavity when estimating concave windows.

edgeCorrect

A logical indicating whether to perform edge correction.

includeZeroCells

A logical indicating whether to include cells with zero counts in the pairwise association.

BPPARAM

{DEPRECATED} A BiocParallel MulticoreParam or SerialParam object.

imageIDCol

{DEPRECATED} The name of the imageID column if using a SingleCellExperiment or SpatialExperiment.

cellTypeCol

{DEPRECATED} The name of the cellType column if using a SingleCellExperiment or SpatialExperiment.

spatialCoordCols

{DEPRECATED} The names of the spatialCoords column if using a SingleCellExperiment.

nCores

{DEPRECATED} Number of cores to use for parallel processing or a BiocParallel MulticoreParam or SerialParam object.

Rs

{DEPRECATED} A vector of the radii that the measures of association should be calculated over.

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 numeric matrix (or sparse Matrix) of soft cell type membership with one row per cell and one named column per label, holding each cell's weight for that label (for example a classifier's confidence). With a matrix, from and to name its columns, and labels may overlap, for example a group and its subtypes. Each cell contributes to a label in proportion to its weight; a label's density is its summed weight per unit area. Weights of 1 give the values of the cell types. Needs a "square" or "convex" window and no sigma.

Value

Statistic from pairwise L-curve of a single image.

Examples

data("diabetesData")
# Subset by imageID for fast example
selected_cells <- diabetesData[
  , SummarizedExperiment::colData(diabetesData)$imageID == "A09"
]
pairAssoc <- getPairwise(selected_cells)

Observed/expected proportion ratio for a fixed-k neighbourhood

Description

Computes a per-image, per-cell-type-pair spatial localisation statistic as a drop-in alternative to the fixed-radius L-function statistic returned by getPairwise. Instead of a search radius r, each reference cell's neighbourhood is its k nearest neighbours (Euclidean distance, any cell type, the cell itself excluded).

Usage

getPairwiseProp(
  cells,
  imageID = "imageID",
  cellType = "cellType",
  spatialCoords = c("x", "y"),
  k = 15,
  from = NULL,
  to = NULL,
  cores = 1,
  includeZeroCells = FALSE,
  BPPARAM = NULL
)

Arguments

cells

A SingleCellExperiment, SpatialExperiment or data.frame.

imageID

The name of the imageID column if a column name is provided.

cellType

The name of the cellType column if a column name is provided.

spatialCoords

The names of the spatial coordinates columns if provided.

k

Number of nearest neighbours to search per reference cell.

from

The reference cell types. Defaults to all cell types.

to

The target cell types. Defaults to all cell types.

cores

Number of threads for processing images in parallel (a BiocParallelParam object is also accepted, for backward compatibility).

includeZeroCells

If FALSE (default), image-pairs where the reference or target cell type is absent are returned as NA. If TRUE, image-pairs whose reference type is absent (but whose target type is present, so p0,j>0p_{0,j} > 0) are floored at π^j=0\hat\pi_j = 0, i.e. vj=0v_j = 0. Pairs whose target type is entirely absent (p0,j=0p_{0,j} = 0) stay NA regardless, since the ratio is undefined.

BPPARAM

A BiocParallelParam object; its number of workers overrides cores. Kept for backward compatibility.

Details

For an ordered pair (from = reference type A, to = target type B), the statistic for image jj is the plain observed-over-expected ratio

vj=π^j/p0,j,v_j = \hat\pi_j / p_{0,j},

where π^j\hat\pi_j is the mean over reference cells of the fraction of their k nearest neighbours that are type B, and p0,jp_{0,j} is the image's background proportion of type-B cells (B count / total cell count).

vj=1v_j = 1 is the null (complete spatial randomness); vj>1v_j > 1 indicates attraction/enrichment and 0≤vj<10 \le v_j < 1 depletion. No variance-stabilising transform (arcsine, log) is applied: vjv_j is bounded below at 0 and right-skewed, a rougher fit to the linear model's Gaussian-noise assumption than a transformed statistic, but chosen for direct interpretability ("observed is 1.4x expected").

The returned matrix is shaped identically to getPairwise()'s output (images in rows, from__to cell-type pairs in columns, same order), so it can be passed straight to spicy() as alternateResult to run the standard spicyR weighting and linear (mixed) model pipeline on the ratio.

Weights. spicy()'s variance-weighting model (weights = TRUE, the default) is calibrated to the L-function's numeric scale. It works for this ratio when the dataset has enough cross-pair variance heterogeneity (e.g. several cell types, some rare) to anchor the fit, but on a dataset with few cell types or weak spatial structure it can degenerate and return an all-NA p-value table. If that happens, refit with weights = FALSE.

No edge correction is applied: π^j\hat\pi_j estimates neighbourhood composition rather than a count within an area, so a boundary cell's truncated neighbourhood carries the same null label distribution as an interior cell's. k controls only the variance of π^j\hat\pi_j, not the location of its null value.

Value

A matrix with one row per image and one column per from__to cell-type pair, containing the observed/expected proportion ratio.

Examples

data("diabetesData")
propAssoc <- getPairwiseProp(diabetesData, k = 15)

# Use as the spicyR response, reusing the standard model:

spicy(diabetesData,
  condition = "stage", subject = "case",
  alternateResult = propAssoc
)

Get proportions from a SummarizedExperiment.

Description

Get proportions from a SummarizedExperiment.

Usage

getProp(cells, feature = "cellType", imageID = "imageID")

Arguments

cells

A SingleCellExperiment, SpatialExperiment or data.frame.

feature

The feature of interest

imageID

The imageID's

Value

Proportions

Examples

data("diabetesData")
prop <- getProp(diabetesData)

Pairwise cross-plot of spatial associations

Description

Builds a pairwise scatterplot of marker-marker associations for a single image using the output of getPairwise().

Usage

imageCrossPlot(
  result,
  image = NULL,
  colourGradient = c("#4575B4", "white", "#D73027"),
  marksToPlot = NULL,
  limits = NULL
)

Arguments

result

A matrix or data frame produced by getPairwise() where rownames are image IDs and colnames are concatenated marker pairs in the form "from__to". Must contain at least one row with name matching image.

image

Character scalar. Which image (row in result) to plot. If NULL, defaults to the first rowname of result.

colourGradient

Character vector of length 3 giving the low, mid, and high colours for a diverging palette used by scale_colour_gradient2(). Default is c("#4575B4", "white", "#D73027").

marksToPlot

Optional character vector of marker names. If supplied, the plot is restricted to rows and columns where both from and to are in this set.

limits

Numeric length-2 vector giving the lower and upper caps applied to association values for colour mapping. Use NULL to avoid clamping. Point sizes are clamped to c(0, max(abs(limits))).

Details

The function expects colnames(result) to contain "__" separating marker names; otherwise an error is thrown. Values are transformed into two aesthetics:

  • value: the (possibly clamped) signed association used for colour.

  • size: the (possibly clamped) absolute association used for point size.

The colourbar shows three ticks at lower, 0, and upper with labels "<lower", "0", and ">upper".

Value

A ggplot2 object.

See Also

getPairwise

Examples

# Minimal example (toy data)
set.seed(1)
mks <- c("A","B","C")
pairs <- as.vector(outer(mks, mks, paste, sep="__"))
res <- matrix(rnorm(length(pairs)*2), nrow = 2,
              dimnames = list(c("img1","img2"), pairs))

p <- imageCrossPlot(res, image = "img1",
                       colourGradient = c("#4575B4","white","#D73027"),
                       marksToPlot = c("A","B","C"),
                       limits = c(-3, 3))
print(p)

Plot images, showing their cell types or the from and to cells of a pair

Description

Without from and to, every cell is shown, coloured by its cell type. With them, the density of all cells is shown in blue, with the from and to cells on top. With r, a circle of radius r is drawn around each to cell: the from cells inside the circles are those that spicyR counts. Several images are drawn side by side, on the same scale.

Usage

plotImage(
  cells,
  imageToPlot,
  from = NULL,
  to = NULL,
  imageID = "imageID",
  cellType = "cellType",
  spatialCoords = c("x", "y"),
  r = NULL
)

Arguments

cells

A SummarizedExperiment object.

imageToPlot

The ID of the image to plot, or several IDs.

from

The "from" cell type. Optional, with to.

to

The "to" cell type. Optional, with from.

imageID

The name of the imageID column in the SummarizedExperiment object.

cellType

The name of the cellType column in the SummarizedExperiment object.

spatialCoords

The names of the spatialCoords column if using a SingleCellExperiment.

r

Optional radius: draw a circle of this radius around each to cell.

Value

A ggplot object.

Examples

data("diabetesData")
plotImage(diabetesData, "A09")
plotImage(diabetesData, "A09", from = "acinar", to = "alpha")
plotImage(diabetesData, "A09", from = "acinar", to = "alpha", r = 50)
plotImage(diabetesData, c("A09", "A11"), from = "acinar", to = "alpha")

The evidence for pairs at each radius

Description

For a spicy() result with several radii, plots the p-value of each chosen pair at every radius, to show the scale at which the evidence is strongest. The combined p-value over the radii is in topPairs().

Usage

radiusPlot(results, from, to)

Arguments

results

The SpicyResults object returned by spicy() with several radii (r).

from, to

The from and to cell types of the pairs to show: every pair between them.

Value

A ggplot.

Examples

data("diabetesData")
diabetes <- diabetesData[, diabetesData$stage %in% c("Non-diabetic", "Onset")]
res <- spicy(diabetes, condition = "stage", subject = "case", r = c(25, 50, 75),
             from = c("Tc", "Th"), to = "beta")
radiusPlot(res, from = c("Tc", "Th"), to = "beta")

Plots result of signifPlot.

Description

Plots result of signifPlot.

Usage

signifPlot(
  results,
  fdr = FALSE,
  type = "bubble",
  breaks = NULL,
  comparisonGroup = NULL,
  colours = c("#4575B4", "white", "#D73027"),
  marksToPlot = NULL,
  cutoff = 0.05,
  contextColours = NULL,
  contextLabels = waiver()
)

Arguments

results

A spicy results object

fdr

TRUE if FDR correction is used.

type

Whether to make a bubble plot ("bubble") or a heatmap (any other value). Note: For survival results a bubble plot will be used.

breaks

Vector of 3 numbers giving breaks used in legend. The first number is the minimum, the second is the maximum, the third is the number of breaks.

comparisonGroup

A string specifying the name of the outcome group to compare with the base group.

colours

Vector of colours to use to colour legend.

marksToPlot

Vector of marks to include in plot.

cutoff

significance threshold for circles in bubble plot.

contextColours

Used for Kontextual results. A named list specifying the colours for each context. By default the Tableau colour palette is used.

contextLabels

Used for Kontextual results. A named list to change the default labels for each context.

Details

The heatmap has a tile for each pair, from in the rows and to in the columns. A tile's colour is the pair's signed log10 p-value for the condition (of the BH-adjusted p-value with fdr = TRUE): -log10(p) when the coefficient is positive and log10(p) when it is negative, so the most significant positive differences are at the top of the scale and the most significant negative ones at the bottom. breaks sets the scale; values beyond it take the end colours, and pairs without a p-value are grey. The values behind either plot are available from topPairs() (n = NULL for every pair). In the bubble plot, the two halves of a bubble are the pair's effect in the two groups; for a continuous condition, one SD (across images) below and above the condition's mean.

Value

a ggplot object

Examples

data(spicyTest)

p <- signifPlot(spicyTest, breaks = c(-3, 3, 0.5))
p
signifPlot(spicyTest, type = "heatmap")

Test for changes in the co-localisation of cell types between conditions

Description

spicy() 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, SingleCellExperiment or SpatialExperiment with 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 a data.frame. Column names then refer to the table's obs; imageID defaults to the table's region key and spatialCoords to its obsm array "spatial". A SpatialData object (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 a survival::Surv column 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>_effect⁠ and ⁠<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, spatialCoords is either two obs columns or the name of one obsm array (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 of to cells with at least one from cell within r; or "count", the number of extra from cells within r of each to cell. "allocation", the earlier name of "fraction", is also accepted. With k, "within r" means among the cell's k nearest neighbours.

k

Cell method: use the k nearest 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, ⁠$cellResults⁠ has maxT_converged: TRUE when 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 from type in each image (default FALSE), and for its patient average when patients have several images (see Details). Its effect is reported as abundance_effect (then the slope within patients). It does not separate more from cells 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, covariates or a survival outcome that are not columns of the cell table: a data.frame whose imageID column, 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. A survival::Surv column given as condition makes 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 sparse Matrix) 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, from and to name its columns, and labels may overlap (a group and its subtypes). Cell method: a to cell counts with its weight, and its score is the chance that it has a from neighbour within r if each cell were a from cell with probability its from weight (allocation), or the summed from weight of its neighbours (count). The null shuffles the to weights over the cells whose from weight is below 1 (so a cell of the from type 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 the from label's summed weight over the image's cells. A label with itself, and a pair where some to cells have from weight 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 of from and to weights 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 summed from weight 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 of selfVariance). One cell with from weight 1 and a to weight above 0 in any image is enough to test a pair this way in every image. One radius and cells in memory. Image method: see getPairwise().

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 soft cellWeights, "exact" gives the exact moments of the pairs tested under random labelling of all cells, and any other value the closed form described under cellWeights.

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_adj is at most alpha are followed up; see topFollowUps()). Default 0.05.

...

Arguments of the image method: sigma, alternateResult, minLambda, weights, weightsByPair, weightFactor, weightZThreshold, window, window.length, edgeCorrect, includeZeroCells, verbose, BPPARAM. Supplying alternateResult selects the image method.

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.

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.

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)
res$cellResults

# 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")
topPairs(resImage)

Box plot of one pair, with a point per image

Description

Shows the per-image value of one pair in each condition: a box plot with the images as points behind it. For the cell method the value is the effect of spicy() in each image (by default the extra fraction of to cells with a from cell within r; with effect = "count", the extra from cells per to cell), and each point is sized by how much the image contributes to the test (its weight in the frailty model, relative to the average image of its condition). With interactive = TRUE the plot is a plotly widget: hover over a point to see its image, patient, excess and weight, which helps to find images worth looking at with plotImage(). With a continuous condition the plot is a scatter of the per-image value against the condition, with the fitted line of the cell method's slope.

Usage

spicyBoxPlot(
  results,
  from = NULL,
  to = NULL,
  rank = NULL,
  interactive = FALSE,
  parent = NULL
)

Arguments

results

The SpicyResults object returned by spicy() (either method).

from

The from cell type (the neighbours looked for around each to cell).

to

The to cell type (the centre).

rank

Alternatively, the rank of the pair by p-value (1 is the most significant).

interactive

Return an interactive plotly widget instead of a ggplot (needs the plotly package).

parent

For a Kontextual result (Statial::kontextualTest()), the parent population of the triple.

Value

A ggplot, or with interactive = TRUE a plotly htmlwidget. Images in which the pair was not tested (no to cells, for example) are not shown.

Examples

data(spicyTest)
spicyBoxPlot(spicyTest, rank = 1)

data("diabetesData")
res <- spicy(diabetesData, condition = "stage", subject = "case", r = 50,
             from = "Tc", to = c("Th", "beta"))
spicyBoxPlot(res, from = "Tc", to = "Th")

The results of spicy()

Description

spicy() returns a SpicyResults object: a list with the elements below. Use topPairs(), signifPlot(), spicyBoxPlot() and bind() on it, or take elements with $.

Details

Elements for the cell method (method = "cell", the default):

cellResults

the full table, one row per pair (and per level with more than two conditions): excess_ref, excess_comp, excess_difference, se, df, p_value, p_adj, tau2; with covariates or adjustAbundance = TRUE, what the test was adjusted for (adjusted_for), the effect and p-value of each adjustment (<covariate>_effect, <covariate>_p_value, abundance_effect) and the unadjusted test (unadjusted_difference, unadjusted_se, unadjusted_df, unadjusted_p_value, unadjusted_p_adj). For survival: score_coefficient, p_value, p_adj, hazard_ratio_sd, log_hr_se (model-based and approximate), n_deaths, not_tested and, with adjustAbundance = TRUE, the p-value and hazard ratio without it. With several radii: r, the radius with the strongest evidence, and p_value_best_radius; with combine = "maxT", maxT_converged (whether the max-T p-value met its error target of about 0.1%).

radiusResults

with several radii, the table at every radius.

followUpResults, alpha

with more than two conditions, the follow-up comparisons of two levels for the pairs called by the overall test at level alpha (see topFollowUps).

pairwiseAssoc

a list with, for every pair, the effect in every image (NA where the pair could not be measured).

effect

"fraction" (the extra fraction of to cells with a from cell within r), "count" (the extra from cells within r of each to cell), or "kontextual" (Statial's Kontextual test).

imageWeights

a list with, for every pair, each image's weight in the test: its share of its condition's information (sums to 1 within each condition).

conditionInformation

with two conditions, a matrix with one row per pair and one column per condition: the condition's information in the pair's test (the sum of the weights of its patients), so that an image's weight times it is the image's weight on the scale of the model (see testCorrelation).

coefficient, p.value, se, statistic, df

matrices with one row per pair, as for the image method: the reference excess and the differences, and their tests.

condition, imageID, subject, nCells, r, k

the condition and patient of every image, the cell counts, and the settings of the analysis.

For the image method (method = "image") the object holds the matrices coefficient, p.value, se, statistic and df, and pairwiseAssoc, as in spicyR 1.x.

See Also

spicy, topPairs, bind


Results of the image-level test on diabetesData

Description

The result of spicy(diabetesData, condition = "stage", subject = "case", method = "image"): the original image-level test of spicyR, for all pairs of cell types, comparing the onset and long-duration stages with non-diabetic donors. It is used in examples, so that they run quickly.

Usage

data("spicyTest")

Format

A SpicyResults object (see spicy).

Source

Made by inst/scripts/make-spicyTest.R from diabetesData.

Examples

data("spicyTest")
topPairs(spicyTest, n = 5)

The correlation between the tests of a spicy() result

Description

The tests of pairs that share a cell type, or that are nested (a cell type and a group containing it), are correlated through the patients they share. testCorrelation() estimates the correlation between every two pairs' tests from the one fit, for a correction for multiple testing that uses it in place of independence.

Usage

testCorrelation(
  x,
  method = c("cr2", "permutation"),
  nPermutations = 1000,
  cores = 1
)

Arguments

x

The output of spicy() (or kontextualEngine()) with two conditions, one radius (or k), no adjustment (no covariates, adjustAbundance = FALSE) and variance = "cr2".

method

"cr2" (the default) or "permutation".

nPermutations

The number of permutations for method = "permutation".

cores

The number of threads for method = "permutation".

Details

Each pair's difference between conditions is a weighted mean over patients: a patient's summary is the weighted mean of its images' effects (x$pairwiseAssoc) with the images' weights (x$imageWeights), and its weight is the sum of its images' weights times its condition's information (x$conditionInformation).

method = "cr2": each patient's CR2 influence on the difference, psi = h (summary - its condition's mean) / sqrt(1 - h) with h the patient's share of its condition's weight, negated in the reference condition. Its squares sum to the test's squared standard error, and the cross-products of two pairs' influences, divided by the two standard errors, estimate the correlation of their differences. It is noisy when a few patients carry most of a pair's weight and one condition is small.

method = "permutation": the conditions are permuted over the patients nPermutations times; for each permutation every test is recomputed in closed form from the patients' summaries and weights (each condition's weighted mean, its CR2 variance and Satterthwaite df, as spicy() computes them; the between-patient variance is held at the fit's, and of spicy()'s rules for not testing a pair only the need for two patients in each condition is applied), and its p-value is turned into a z with the sign of its (skewness-corrected) t (0 when a condition has fewer than two of the pair's patients). The correlation of the tests' z over the permutations is returned. The permutations come from a fixed seed, so a result always gives the same matrix, in R and in Python.

Value

A symmetric matrix with one row and one column per row of x$cellResults (the same row names): the estimated correlation between the pairs' tests. The diagonal is 1, and rows and columns of pairs not tested (or, by permutation, whose z is the same in every permutation) are NA.

See Also

spicy()

Examples

data("diabetesData")
cells <- diabetesData[, diabetesData$stage != "Long-duration"]
res <- spicy(cells, condition = "stage", subject = "case", r = 50, from = c("Tc", "Th"), to = c("beta", "alpha"))
testCorrelation(res)
testCorrelation(res, method = "permutation", nPermutations = 200)

The follow-up comparisons of two levels, for more than two conditions

Description

With more than two conditions (cell method), spicy() tests each pair first with the overall test (are all the condition means equal? overall_p_value, BH-adjusted over the pairs in overall_p_adj). For the pairs that test calls (overall_p_adj at most alpha, R of the m pairs with an overall test), every two levels are then compared: each comparison is the two-condition test of spicy() on the patients of those two levels only (their own between-image and between-patient variances, the same rules for not testing, and the same adjustments). A comparison is tested whenever its two levels pass the rules, even when another level of the pair is too sparse. Within a pair the comparisons are Bonferroni-corrected at the Benjamini-Bogomolov level alpha R / m: a comparison is significant when its p-value is at most p_threshold = alpha R / (m K), K the comparisons tested in the pair. This controls the average, over the pairs called, of the chance of any false comparison within a pair (Benjamini and Bogomolov 2014). Pairs the overall test does not call have no follow-ups.

Usage

topFollowUps(
  x,
  n = NULL,
  from = NULL,
  to = NULL,
  significant = FALSE,
  figures = NULL
)

Arguments

x

The output from spicy() with more than two conditions.

n

The number of comparisons to list (NULL, the default, lists every one).

from, to

Only the comparisons of pairs with these from and to cell types.

significant

TRUE: only the comparisons significant at the Benjamini-Bogomolov level.

figures

Round to figures significant figures.

Value

A data.frame with one row per called pair and comparison, ordered by the pair's overall p-value and then the comparison's: from, to, the two levels (level_ref, level_comp), the effect in each (excess_ref, excess_comp), their difference (excess_difference, comp minus ref), its standard error, df and p-value, p_threshold, significant, the pair's overall_p_value and overall_p_adj, the number of comparisons tested in the pair (n_comparisons), the frailty variance of the comparison (tau2) and not_tested (why a comparison was not tested; NA when it was). For the extra fraction, the pair's side and the between-image variance of the comparison (tau2_image); with adjustment, adjusted_for and the unadjusted difference and p-value. Row names are "from__to__comp__ref". The same table is x$followUpResults.

References

Benjamini Y, Bogomolov M (2014). Selective inference on multiple families of hypotheses. Journal of the Royal Statistical Society B 76(1), 297-318. doi:10.1111/rssb.12028

See Also

spicy(), topPairs()

Examples

data("diabetesData")
res <- spicy(diabetesData, condition = "stage", subject = "case", r = 50, from = "Tc", to = c("Th", "beta"))
topFollowUps(res)

The most significant pairs, or the results of chosen pairs

Description

Lists the pairs tested by spicy(), most significant first. Give from and/or to to see chosen pairs, and n = NULL to see every pair.

Usage

topPairs(
  x,
  coef = NULL,
  n = 10,
  adj = "fdr",
  cutoff = NULL,
  figures = NULL,
  from = NULL,
  to = NULL,
  full = FALSE
)

Arguments

x

The output from spicy().

coef

Which coefficient to list: a column of x$p.value, or with the cell method and more than two conditions, a level of the condition.

n

The number of pairs to list. NULL lists every pair, as does leaving n out when cutoff is given.

adj

Which p-value adjustment method to use, argument for p.adjust().

cutoff

List only the pairs whose adjusted p-value is at most cutoff.

figures

Round to figures significant figures.

from, to

Only the pairs with these from and to cell types.

full

Cell method: every column of the test, not only the main ones.

Details

For the cell method (the default of spicy()) the table has one row per pair (and per level with more than two conditions), with the columns of the test: from, to, excess_ref and excess_comp (the average effect in the reference and the comparison group), excess_difference, p_value and p_adj; with several radii, r, the radius with the strongest evidence; with covariates, the effect and p-value of each (⁠<covariate>_effect⁠, ⁠<covariate>_p_value⁠); for survival, hazard_ratio_sd. full = TRUE adds the scale of the effect (side), the standard error, degrees of freedom, the variance between patients (tau2), what the test was adjusted for and the unadjusted test. For the image method the columns are intercept, coefficient, p.value, adj.pvalue, from and to, as in spicyR 1.x.

Value

A data.frame, one row per pair, with the pair ("from__to") as row names.

Examples

data(spicyTest)
topPairs(spicyTest)

data("diabetesData")
res <- spicy(diabetesData, condition = "stage", subject = "case", r = 50, from = "Tc", to = c("Th", "beta"))
topPairs(res, from = "Tc", to = "Th")

Write cells as a SpatialData Zarr store

Description

Writes a SpatialExperiment, SingleCellExperiment or data.frame of cells as a SpatialData Zarr store (Zarr v3), which spicy() reads a block of rows at a time, spatialdataR's readSpatialData() reads as a SpatialData object, and Python's spatialdata reads too. The cells become a table (AnnData, under ⁠tables/⁠):

Usage

writeCellStore(
  cells,
  path,
  imageID = "imageID",
  spatialCoords = c("x", "y"),
  tableKey = "table",
  imageInfo = NULL,
  infoKey = "images",
  points = TRUE
)

Arguments

cells

A SpatialExperiment, SingleCellExperiment or data.frame with one row (column) per cell. The colData, rowData and data.frame columns are factors, character, integer, double or logical vectors, and every assay has a name.

path

The directory of the store (replaced if it exists).

imageID, spatialCoords

The column of the image and the two columns of the coordinates. A SpatialExperiment's own spatialCoords() are used unless spatialCoords names two colData columns.

tableKey

The name of the cell table.

imageInfo

Optional: a data.frame with one row per image, written as the table infoKey. The image IDs are its imageID column, or else its row names.

infoKey

The name of the per-image table.

points

Whether to write the cells as points too, one points element per image (needs duckdb).

Details

  • obs: the colData (or the columns of a data.frame) other than the coordinates, factors as categorical columns. The image column is the table's region key (always categorical, its categories the levels of a factor, else the images in order of first appearance), and the cells are numbered 0, 1, ... in "instance_id".

  • X and layers: the first assay and the others (a sparse assay in compressed sparse row form).

  • var: the rowData, with the row names as its index.

  • obsm: the coordinates as "spatial", and the reducedDims.

The cells of each image also become a points element named after the image, with their coordinates and their "instance_id", so that the table annotates elements of the store (image IDs must then be valid element names: letters, digits, ⁠_⁠, - and .). The images of a SpatialExperiment (imgData()) become image elements named ⁠<sample_id>_<image_id>⁠, each in the coordinate system of its sample and scaled to the coordinates of the cells. A table with one row per image can be added. Every array is written in chunks (of 2^20 rows for a column) compressed with zstd, one chunk at a time, so writing needs little memory beyond that of cells, however many cells it has. metadata(), altExps() and column or row pairings are not written.

Value

path, invisibly.

Examples

cells <- data.frame(imageID = factor(rep(c("a", "b"), each = 50)), cellType = factor(rep(c("T", "B"), 50)),
                    x = runif(100, 0, 100), y = runif(100, 0, 100))
if (requireNamespace("Rarr", quietly = TRUE)) {
  path <- writeCellStore(cells, tempfile(fileext = ".zarr"))
  list.files(file.path(path, "tables"))
}