--- title: "Spatial lag regression with spatialLagGLM" author: "Sahal Paladan" date: "`r Sys.Date()`" output: BiocStyle::html_document vignette: > %\VignetteIndexEntry{Spatial lag regression with spatialLagGLM} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set(collapse = TRUE, comment = "#>", message = FALSE) has_ste <- requireNamespace("STexampleData", quietly = TRUE) ``` # Introduction `spatialLagGLM` asks, gene by gene, whether the expression at a spot is associated with the expression at the spots around it, in spatial transcriptomics data stored in a `SpatialExperiment`. For each gene it fits a quasi-Poisson regression with a library-size offset, optional design terms from `colData`, and the *spatial lag* of the gene's own normalised counts as an extra covariate. The lag coefficient, its statistic and the rank of that statistic across genes are written to `rowData()` of the input object. **The package reports no p-values.** The statistic is meant for ranking genes, not for testing against a significance threshold. The reason, with evidence, is in [Why there are no p-values]. ## Relation to existing packages Several methods already find spatially variable genes (SVGs). SPARK-X [Zhu et al. 2021](#references), nnSVG [Weber et al. 2023](#references) and SpatialDE [Svensson et al. 2018](#references) test whether a gene's expression has spatial covariance structure, using kernel or Gaussian process models, and they target any spatial pattern, with calibrated tests. The closest relatives of this package are tools that build a neighbour graph and compute spatial lags or Moran's I: `spdep` (CRAN) and, in Bioconductor, `Voyager` with `SpatialFeatureExperiment`. They compute the lag and the autocorrelation statistic of each gene, with tests designed for that purpose. `spatialLagGLM` differs in that the lag enters a count regression as a covariate, next to a library-size offset and any `colData` variables, so the spatial association is estimated *given* those terms, and the results are stored in the `SpatialExperiment` you pass in. It does not provide calibrated tests, so if you need hypothesis tests for spatially variable genes use the packages above. Use `spatialLagGLM` to rank genes and to obtain design-adjusted lag estimates, and confirm hits independently. # Installation ```{r install, eval = FALSE} if (!requireNamespace("BiocManager", quietly = TRUE)) { install.packages("BiocManager") } BiocManager::install("spatialLagGLM") ``` # The model For one gene, let $y_i$ be the count at spot $i$. The model is $$\log E[y_i] = \log(s_i) + X_i\beta + \gamma\, l_i, \qquad l_i = \sum_j w_{ij}\,\frac{y_j}{s_j},$$ fitted with a quasi-Poisson family. Here $s_i$ is the size factor of spot $i$ (library size divided by the geometric mean of library sizes), $X_i$ is the row of the design matrix, and $w_{ij}$ are weights: the inverse distance between spots $i$ and $j$ if they are within `radius` of each other (and in the same sample), zero otherwise, with each row scaled to sum to one. A spot with no neighbours has $l_i = 0$. The question asked is whether $\gamma = 0$: given the offset and the design terms, is the expression at a spot associated with the weighted mean of the normalised expression of its neighbours? The **effect size** reported is $\hat\gamma$ and the **statistic** is $\hat\gamma$ divided by its quasi-Poisson standard error. Because $l_i$ is built from the same gene's counts, this is **not** a spatial autoregressive (SAR) model. # Input data The package ships a simulated dataset: a 30 x 30 grid of spots and 50 genes. Spots within 7 units of the centre are labelled `TumorCore`, the rest `Margin`. `Gene1` is up-regulated in the core; the other 49 genes are simulated without any spatial pattern. ```{r mock} library(spatialLagGLM) library(SpatialExperiment) set.seed(1) se <- makeMockSpatial() se table(se$condition) ``` The function needs a `SpatialExperiment` with a raw-count assay, spatial coordinates, and a `sample_id` column in `colData` (which every `SpatialExperiment` has). Spots with zero total counts must be removed first. # Running the analysis ```{r run-condition} res <- spatialLagGLM(se, design = ~condition, radius = 2.5) head(SummarizedExperiment::rowData(res), 3) ``` ## Arguments `design` : A formula using `colData` variables, e.g. `~ condition`. Use `~ 1` for no adjustment. With `~ condition`, the lag is estimated after allowing a different mean in each condition, so a pattern that is fully explained by `condition` is *not* reported. Compare: ```{r run-intercept} res0 <- spatialLagGLM(se, design = ~1, radius = 2.5) rd <- SummarizedExperiment::rowData cols <- c("spatial_effect_size", "spatial_statistic", "spatial_rank") out <- rbind( as.data.frame(rd(res)["Gene1", cols]), as.data.frame(rd(res0)["Gene1", cols]) ) rownames(out) <- c("~ condition", "~ 1") out ``` `radius` : A positive number: the distance within which spots count as neighbours, in the units of `spatialCoords(se)`. See [Choosing the radius]. `assay.type` : The assay holding raw counts (default `"counts"`). `size.factors` : Optional. By default size factors come from the library sizes of the assay you pass in. If you subset genes before the analysis, pass size factors computed from all genes (see the real-data example). `BPPARAM` : A `BiocParallelParam`, e.g. `BiocParallel::MulticoreParam(4)`. Genes are fitted in parallel. ## Several samples Weights are computed separately for each value of `colData(se)$sample_id`, so spots in different sections are never neighbours. All samples are assumed to share the same coordinate units, because one `radius` is used for all. # Output The input object is returned with three new columns in `rowData()`: `spatial_effect_size` : $\hat\gamma$, the change in the log expected count per unit increase in the neighbours' weighted mean normalised count. Positive means a spot tends to be high where its neighbours are high. It is in units of normalised counts, so it depends on how highly a gene is expressed and is not comparable across genes. `spatial_statistic` : $\hat\gamma$ divided by its quasi-Poisson standard error. Larger absolute values mean stronger evidence of spatial association *relative to other genes*. The values are not calibrated, so no threshold such as 1.96 applies (see below). `spatial_rank` : The rank of the absolute statistic across genes; 1 is the strongest. `NA` is returned for genes whose fit failed or did not converge, and a warning reports how many. The radius, assay and size factors used are kept in `S4Vectors::metadata(res)$spatialLagGLM`. # Plots `plotSpatialLag()` draws a gene on the tissue coordinates, either as raw counts or as its spatial lag (the covariate used in the model). It uses the assay stored by `spatialLagGLM()` unless you pass `assay.type`. ```{r plot-expression, fig.height = 4, fig.width = 5} plotSpatialLag(res0, "Gene1", metric = "expression") ``` ```{r plot-lag, fig.height = 4, fig.width = 5} plotSpatialLag(res0, "Gene1", metric = "spatial_lag") ``` `plotLagSummary()` plots the effect size against the absolute statistic for all genes and labels the top-ranked ones. It draws no significance categories. ```{r summary-plot, fig.height = 4, fig.width = 5} plotLagSummary(res0, top = 5) ``` An interactive explorer combining both is available with `runSpatialLagExplorer(res0)` (requires the `shiny` package). # Why there are no p-values A quasi-Poisson fit would give a p-value for $\gamma$ at no extra cost, but that p-value is not valid here. The lag $l_i$ is made of the counts of the neighbours of spot $i$, and spot $i$'s own count appears in the lags of those neighbours. Each pair of neighbouring spots therefore enters the regression twice, once as a response and once inside a covariate, and the usual standard error ignores this. If there is no spatial structure at all, the variance of the statistic exceeds what the model assumes by a factor of about $$1 + \frac{\sum_{i \neq j} w_{ij} w_{ji}}{\sum_{i,j} w_{ij}^2},$$ which is close to 2 when neighbours are mutual (if spot $j$ is within the radius of spot $i$, then $i$ is within the radius of $j$), as they are with a fixed radius. The standard deviation of the statistic is then about $\sqrt{2} \approx 1.41$ instead of 1. We can check this on the simulated data. Genes 2 to 50 have no spatial pattern, so their statistics should have a standard deviation of about 1.4: ```{r null-sd} null_stat <- rd(res0)$spatial_statistic[-1] sd(null_stat) ``` In a larger simulation by the package author (3,000 independent negative binomial genes on this grid, design `~ 1`), the predicted factor for these weights was 1.99, the predicted standard deviation 1.41, and the observed standard deviation 1.45. At the usual 1.96 cutoff, 18% of null genes would be called significant instead of 5%. This distortion depends on the weights, not on the gene, so it is nearly the same for every gene and does not change the *order* of the genes. That is why `spatial_statistic` and `spatial_rank` are reported and p-values and significance categories are not. Use the rank to prioritise genes. ## Getting a calibrated reference If you need calibrated inference, compare the statistics with a permutation null. Permuting the spots (columns) of the count matrix keeps each spot's library size but breaks any link between expression and location, so the statistics from permuted data show what to expect from no spatial signal. This recipe permutes all genes jointly and is only appropriate with `design = ~1`; with design terms the permutation would also break their association with the counts. ```{r perm} perm_counts <- SummarizedExperiment::assay(se, "counts")[, sample(ncol(se))] colnames(perm_counts) <- colnames(se) perm <- se SummarizedExperiment::assay(perm, "counts") <- perm_counts res_perm <- spatialLagGLM(perm, design = ~1, radius = 2.5) perm_stat <- abs(rd(res_perm)$spatial_statistic) obs_stat <- abs(rd(res0)$spatial_statistic) sd(rd(res_perm)$spatial_statistic) ## Fraction of permuted genes at least as extreme as Gene1: (1 + sum(perm_stat >= obs_stat[1])) / (1 + length(perm_stat)) ``` With only 50 genes this null is coarse. On a real dataset, pool the statistics from several permutations, and treat the resulting fractions as empirical reference values, not as formal tests, unless you use many permutations. # Choosing the radius `radius` sets the scale at which neighbours are defined. Too small and many spots have no neighbours; too large and the lag becomes a smooth regional average. A practical starting point is a small multiple of the typical nearest-neighbour distance. On the mock grid, spots are one unit apart, so `radius = 1.5` includes the 8 surrounding spots and `radius = 2.5` the 20 nearest. ```{r radius} coords <- spatialCoords(se) d <- as.matrix(dist(coords)) diag(d) <- Inf median(apply(d, 1, min)) ``` It is worth checking that the ranking does not change much over a few radii: ```{r radius-sens} rank_by_radius <- vapply(c(1.5, 2.5, 4), function(r) { out <- spatialLagGLM(se, design = ~1, radius = r) rd(out)["Gene1", "spatial_rank"] }, numeric(1)) names(rank_by_radius) <- c(1.5, 2.5, 4) rank_by_radius ``` # Example on real data This example uses a 10x Visium sample of human dorsolateral prefrontal cortex from the `STexampleData` package. To keep the vignette fast we analyse the 300 most highly expressed genes. Because `spatialLagGLM()` derives size factors from the genes it is given, we compute them first from *all* genes and pass them in. ```{r real-load, eval = has_ste} library(STexampleData) spe <- Visium_humanDLPFC() spe <- spe[, as.logical(spe$in_tissue)] counts_all <- SummarizedExperiment::assay(spe, "counts") spe <- spe[, colSums(counts_all) > 0] counts_all <- SummarizedExperiment::assay(spe, "counts") lib <- colSums(counts_all) sf <- lib / exp(mean(log(lib))) top <- order(rowSums(counts_all), decreasing = TRUE)[seq_len(300)] spe <- spe[top, ] dim(spe) ``` The coordinates are in image pixels. We set the radius to 1.5 times the median nearest-neighbour distance, which captures the first ring of neighbours on the Visium hexagonal grid. ```{r real-radius, eval = has_ste} xy <- spatialCoords(spe) d <- as.matrix(dist(xy)) diag(d) <- Inf radius <- 1.5 * median(apply(d, 1, min)) radius ``` ```{r real-run, eval = has_ste} res_real <- spatialLagGLM( spe, design = ~1, radius = radius, size.factors = sf, BPPARAM = BiocParallel::SerialParam() ) tab <- as.data.frame( SummarizedExperiment::rowData(res_real)[, c( "spatial_effect_size", "spatial_statistic", "spatial_rank" )] ) head(tab[order(tab$spatial_rank), ], 5) ``` ```{r real-plot, eval = has_ste, fig.height = 4, fig.width = 5} top_gene <- rownames(tab)[which.min(tab$spatial_rank)] plotSpatialLag(res_real, top_gene, metric = "spatial_lag") ``` # Limitations * No p-values are reported: the statistic is meant for ranking genes (see [Why there are no p-values]). * The model is not a spatial autoregressive model; it regresses a gene on the lag of its own counts. * Effect sizes depend on expression level and are not comparable across genes. * The results depend on `radius`. * Memory: counts are converted to a dense matrix, and the C++ code builds a dense $n \times n$ weight matrix for each sample, where $n$ is the number of spots in that sample, using $O(n^2)$ time and memory. Only the combined matrix across samples is stored sparsely. A single Visium slide is fine, but samples with many tens of thousands of spots will need a lot of memory. # Session information ```{r session-info} sessionInfo() ``` # References {#references} * Righelli D, et al. (2022). SpatialExperiment: infrastructure for spatially resolved transcriptomics data in R using Bioconductor. *Bioinformatics*. * Svensson V, Teichmann SA, Stegle O (2018). SpatialDE: identification of spatially variable genes. *Nature Methods*. * Weber LM, et al. (2023). nnSVG for the scalable identification of spatially variable genes using nearest-neighbor Gaussian processes. *Nature Communications*. * Zhu J, Sun S, Zhou X (2021). SPARK-X: non-parametric modeling enables scalable and robust detection of spatial expression patterns for large spatial transcriptomic studies. *Genome Biology*.