--- title: "Introduction to `multipointR`" author: - name: "Martin Emons" affiliation: - &DMLS Department of Molecular Life Sciences, University of Zurich, Switzerland - &SIB SIB Swiss Institute of Bioinformatics, Lausanne, Switzerland email: "martin.emons@uzh.ch" - name: "Wolfgang Huber" affiliation: - &EMBL European Molecular Biology Laboratory - name: "Mark D. Robinson" affiliation: - *DMLS - *SIB package: "`r BiocStyle::Biocpkg('multipointR')`" output: BiocStyle::html_document abstract: > `multipointR` is a `Bioconductor` package to fit parametric point process models of intensity to cells approximated as points. This can be done for a single image or across multiple images. vignette: > %\VignetteIndexEntry{Introduction to `multipointR`} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} bibliography: multipointR.bib header-includes: - \usepackage{si} editor_options: chunk_output_type: console editor: markdown: wrap: 80 execute: message: false warning: false error: false --- ```{r v1, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", eval = TRUE ) ``` # Introduction `r BiocStyle::Biocpkg('multipointR')` is a package to fit point process models from `r BiocStyle::CRANpkg('spatstat.model')` on `r BiocStyle::Biocpkg('SpatialExperiment')` and `r BiocStyle::Biocpkg('SpatialFeatureExperiment')` objects. Cells are approximated as points and their distribution in space is modelled as the log-linear combination of spatial (or non-spatial) covariates. `r BiocStyle::Biocpkg('multipointR')` has a mode to do inferences on the level of a single image with `fitModel` and across multiple images with `fitModelAcrossImages`. # Installation `r BiocStyle::Biocpkg('multipointR')` can be installed and loaded from Bioconductor as follows ```{r installation, include=TRUE, eval=FALSE} if (!requireNamespace("BiocManager")) { install.packages("BiocManager") } BiocManager::install("multipointR") ``` # Setup ```{r setup, message=FALSE, warning=FALSE} library("multipointR") library("SpatialExperiment") library("SpatialFeatureExperiment") library("dplyr") library("ggplot2") library("spatstat.model") library("patchwork") ``` # Dataset For this document, we will use the well established MIBI TOF dataset from @keren2018structured. ```{r dataloading, warning=FALSE, message=FALSE} spe <- SpatialDatasets::spe_Keren_2018() spe ``` The preprocessing and visualisation of this dataset is taken from the `r BiocStyle::Biocpkg('Statial')` vignette. ```{r preprocessDataset, fig.height=50, fig.width=15} # Code source: https://www.bioconductor.org/packages/release/bioc/vignettes/ # Statial/inst/doc/Statial.html # #kontextual-identifying-discrete-changes-in-cell-state # Examine all cell types in image unique(spe$cellType) # Set up cell populations tumour <- c("Keratin_Tumour", "Tumour") bcells <- c("B_cell") tcells <- c("dn_T_CD3", "CD4_T_cell", "CD8_T_cell", "Tregs") myeloid <- c("DC_or_Mono", "DC", "Mono_or_Neu", "Macrophages", "Neutrophils") endothelial <- c("Endothelial") mesenchymal <- c("Mesenchymal") tissue <- c(endothelial, mesenchymal) immune <- c(bcells, tcells, myeloid, "NK", "other immune") all <- c(tumour, tissue, immune, "Unidentified") # Lets define a new cell type vector spe$cellTypeNew <- spe$cellType # Select for all cells that express higher than baseline level of p53 p53Pos <- assay(spe)["p53", ] > -0.300460 # Find p53+ tumour cells spe$cellTypeNew[spe$cellType %in% tumour] <- "Tumour" spe$cellTypeNew[p53Pos & spe$cellType %in% tumour] <- "p53_Tumour" # Group all immune cells under the name "Immune" spe$cellTypeNew[spe$cellType %in% immune] <- "Immune" spe$cellTypeNew <- as.factor(spe$cellTypeNew) speSub <- subset(spe, , cellTypeNew %in% c("Immune", "Tumour", "p53_Tumour")) speSub$cellTypeNew <- factor(speSub$cellTypeNew, levels = c("Immune", "Tumour", "p53_Tumour") ) ``` # Inference with parametric point process models ## The inhomogeneous Poisson point process Parametric point process models (PPMs), as implemented in the `spatstat` package, model the distribution of points in space as an (in)homogeneous Poisson distribution [@baddeley2014package]. Thus, the expected number of points falling in a region $B$ follows an inhomogeneous Poisson process with rate $\lambda(u)$, the local intensity [@baddeley2016spatial]. $$ \mathbb{E}[n(\mathbf{X} \cap B)] = \int_B \lambda(u)du $$ The PPM then models this inhomogeneous intensity $\lambda(u)$ as a function of spatial and non-spatial covariates $$ \lambda_{\Theta}(u) = \exp(\beta_0 + \Theta^TZ(u)) $$ where $\beta_0$ is the baseline intensity, $Z(u)$ are spatially varying covariate functions and $\Theta$ is the parameter vector to be estimated. In particular, parameters within $\Theta$ would be relevant for making inferences in order to make claims about spatial associations. ## The Cox point process In the inhomogeneous Poisson process we have to model the baseline inhomogeneity as fixed effects. This means we have to either "know" what drives the inhomogeneity or parametrise a flexible $\beta_0(u)$ for example with a bivariate spline surface. In such a setting we run into the possibility of overparametrising our model. An alternative are Cox point processes where the underlying inhomogeneity is modelled as a random effect. Cox processes are Poisson processes with a random intensity function $\Lambda(u)$. Given this underlying random intensity function point process is constructed with intensity equal to $\Lambda(u)$ [@baddeley2016spatial]. The expected number of points of the Cox process is then $$ \mathbb{E}[n(\mathbf{X} \cap B)] = \mathbb{E}(\mathbb{E}[n(\mathbf{X} \cap B)\mid\Lambda]) = \int_B \mathbb{E}[\Lambda(u)]\,\mathrm{d}u, $$ meaning that the expected number of points in a region $B$ is conditional on the random intensity function. The intensity of the Cox process is then an inhomogeneous Poisson process conditional on the realisation of the stochastic function $\Lambda(u)$ [@10.1214/13-STS441]. $$ \lambda(u) = \mathbb{E}[\Lambda(u)] $$ A convenient formulation is that of a _log Gaussian Cox process_ (LGCP). $$ \Lambda(u) = \exp(G(u)), $$ where $G(u)$ is a _Gaussian random field_ in $\mathbb{R}^2$, with mean $\mu(u)$ and covariance $C(u,v)$. The exponentiation keeps the intensity positive whereas the assumption of the GRF leads to a well defined model, meaning that the covariance matrix is positive definite. Furthermore, we only consider models that are isotropic and stationary. These are obvious simplifactions in comparison to highly heterogeneous tissues. The objective function of the LGCP can then be formulated as $$ \begin{aligned} \Lambda(u) &= \underbrace{\exp(\beta_0(u)+ \mathbf{\Theta}^{\mathsf{T}}\mathbf{Z}(u))}_{\lambda_{\mathbf{\Theta}}(u)} \cdot \underbrace{\exp(G_0(u) - \sigma^2/2)}_{M(u)}, \end{aligned} $$ This is a nicely separable formulation with the first order terms of the Cox proccess ($\lambda_{\mathbf{\Theta}}(u)$) and the random part $M(u)$ of the Cox model described by the second order term $\sigma^2$ and a zero mean Gaussian random field $G_0(u)=G(u) - \mu(u)$ with $\mathbb{E}[M(u)] = 1$ [@10.1214/13-STS441]. In order to estimate the mean of the GRF `spatstat` uses a two step fitting procedure of @baddeley2014package. First, the Poisson process component is fit $\log\lambda(u)$. After that, the Cox/cluster component $\sigma^2/2$ is substracted by estimating via e.g. minimum contrast of the two summary statistics or the Palm likelihood. Since the Palm likelihood approach was shown to be more stable, we will use it here [@BADDELEY2022100709]. [@baddeley2016spatial; @baddeley2000practical]. ## Single image inference For the single image case, we will analyse the relationship between the distribution of p53+ tumour cells and immune cells in image $6$. ```{r singleImagePlot, echo=TRUE} # Code source: https://www.bioconductor.org/packages/release/bioc/vignettes/ # Statial/inst/doc/Statial.html # #kontextual-identifying-discrete-changes-in-cell-state # Plot image 6 df <- spe |> colData() |> cbind(spatialCoords(spe)) |> as.data.frame() |> dplyr::filter(imageID == "6") |> dplyr::filter(cellTypeNew %in% c("Immune", "Tumour", "p53_Tumour")) df$cellTypeNew <- factor(df$cellTypeNew, levels = c("Immune", "Tumour", "p53_Tumour") ) p1 <- df |> arrange(cellTypeNew) |> ggplot(aes(x = x, y = y, color = cellTypeNew)) + geom_point(size = 1) + scale_colour_manual( values = c("#505050", "#D6D6D6", "#64BC46"), labels = c("Immune", "Tumour", "p53+ Tumour") ) + guides(colour = guide_legend( title = "Cell types", override.aes = list(size = 5) )) + coord_equal() + theme_light() p1 ``` We notice qualitatively a clearly separated tumour with p53+ cells and immune cells at the tumour border. ### Model of homogeneous intensity First, we will estimate the distribution of p53+ tumour cells as a *homogeneous* intensity in space, i.e., we fit a model of the form $$ \mu(u) = \beta_0 - \sigma^2/2 $$ with a constant intercept $\beta_0$ ```{r Ppm0} speSub <- subset(spe, , imageID == "6") m0 <- fitModel( spe = speSub, marks = "cellTypeNew", interaction = "Hardcore", method = "palm", formula = as.formula("p53_Tumour ~ 1") ) ``` The model is very basic and has not many parameters, let's look at the spatial trend of the first step Poisson model: ```{r Ppm0Plot, fig.width=8, fig.height=8} plot(m0) ``` The resulting spatial trend is a flat surface. This is not a very sensible model since we see clear a inhomogeneous distribution of points in space. ### Model of inhomogeneous intensity Next, we will formulate a null model of the distribution of p53 positive cells. For this model, we will specify an inhomogeneous intensity varying with a bivariate spline model of $x$ and $y$ ($s(x,y)$). The model we fit is of the form $$ \mu(u) = \beta_0(u) - \sigma^2/2 $$ with a spatially-varying intercept $\beta_0(u)$ an inhomogeneous intercept parameterised as a tensor product spline. ```{r Ppm1, warnings = FALSE} m1 <- fitModel( spe = speSub, marks = "cellTypeNew", method = "palm", formula = as.formula("p53_Tumour ~ splines::ns(x, df = 2)*splines::ns(y, df = 2)"), interaction = "Hardcore" ) ``` We can look at the influence of the parameters with a $z$-tests for the individual parameters ```{r Ppm1Anova} coef(summary(m1)) ``` We can see that because we already assume an underlying random baseline most of the spline terms are not significantly different from zero. Therefore, we will not consider an additional spatially varying $\beta_0(u)$ anymore. ### Model of distance to immune cells From the literature, we know that p53+ tumour cells have immune-modulatory function. Our hypothesis is therefore that p53+ tumour cells will interact spatially with immune cells. In order to test this, we formulate a Cox model of distance to immune cells. The model is then: $$ \mu(u) = \beta_0 + \beta_{dist}\mathbf{Z}_{dist}(u) - \sigma^2/2 $$ ```{r Ppm2} m2 <- fitModel( spe = speSub, marks = "cellTypeNew", formula = as.formula("p53_Tumour ~ spatstat.geom::distfun(Immune)"), method = "palm", interaction = "Hardcore" ) ``` We can again look at the contribution of the model parameters with a LRT ```{r Ppm2Anova} coef(summary(m2)) ``` We see that the model including the distance to immune cells does not lead to an improvement in model fit for this specific image. ```{r Ppm2Plot, fig.width=8, fig.height=8} plot(m2) ``` An important part when fitting statistical models for inference is to check the model diagnostics to query potential deviations from the modeling assumptions For `kppm` objects the theory and software to assess goodness-of-fit is not as developed as for `ppm` objects. We will consider two options: - Summary statistics with bootstrapped confidence bands - Q-Q plots of the first `ppm` fit and compare this to a simulated reference distribution of the `kppm` object The assessment of the summary statistics with confidence bands is a good second order check. ```{r Summarybootstrap} summaryQc <- envelope(m2, pcfinhom, global = TRUE) plot(summaryQc) ``` We notice some devitations from the at low radii $r$ of the model envelopes and the observed pair-correlation function indicating some unexplained variance ```{r} set.seed(1234) # extract the first Poisson fit poM2 <- as.ppm(m2) # simulate confidence bands under `kppm` model nsim <- 99 sims <- simulate(m2, nsim = nsim) # plot the QQ qq <- qqplot.ppm(poM2, nsim = nsim, expr = sims, type = "pearson" ) ``` Under the quantiles of the simulated `kppm` model the difference is less clear ### Model of segmented objects Another option that users have is to define a segmented polygon as spatial covariate in their `ppm` model. To do this, we first perform a segmentation on our image. For simplicity, we will use the Bioconductor package `r BiocStyle::Biocpkg('sosta')`. Of course, one can use any other segmentation method, the only requirement being that the polygon is stored as an `sf` object. ```{r sostaSegmentation, fig.width=8, fig.height=8} segmentedTumour <- sosta::reconstructShapeDensityImage( speSub, marks = "cellTypeNew", markSelect = c("Tumour", "p53_Tumour"), thres = 5e-4 ) p1 + geom_sf( data = segmentedTumour, inherit.aes = FALSE, fill = NA, color = "red", linewidth = 1 ) ``` In order to save this polygon we will convert our `SpatialExperiment` object into a `SpatialFeatureExperiment` object and store it in the `annotGeometries`. ```{r speToSfe} sfeSub <- toSpatialFeatureExperiment(speSub) annotGeometry(sfeSub, "tumour_mask") <- segmentedTumour ``` After this, we can specify our `ppm` with the segmented tumour as spatial covariate. The result will be a logical covariate, indicating the intensity of the response within the tumour (`tumour_mask == TRUE`) as compared to outside. ```{r Ppm3} m3 <- fitModel( spe = sfeSub, marks = "cellTypeNew", formula = as.formula("p53_Tumour ~ tumour_mask"), method = "palm", standardize = FALSE, interaction = "Hardcore" ) ``` We can again assess the importance of the variables with a $z$-test ```{r Ppm3Anova} coef(summary(m3)) ``` We can interpret from this test that the covariate `tumour_mask` is important for describing the distribution of p53+ cells in space. This makes sense, since p53+ tumour cells are a subset of tumour cells and can only be found within the tumour. ```{r Ppm3Plot, fig.width=8, fig.height=8} plot(m3) + geom_sf( data = segmentedTumour, inherit.aes = FALSE, fill = NA, color = "darkred", linewidth = 0.6 ) ``` The model is just a binary surface within and outside of the tumour ```{r} summaryQc <- envelope(m3, pcfinhom, global = TRUE) plot(summaryQc) ``` This model fits the data much better than model `m2`. We can combine models `m2` and `m3` and create a model that incorporates both the tumour mask plus the distance to the immune cells. ```{r Ppm4} m4 <- fitModel( spe = sfeSub, marks = "cellTypeNew", formula = as.formula("p53_Tumour ~ tumour_mask + spatstat.geom::distfun(Immune)"), standardize = FALSE, method = "palm", penalised = TRUE, interaction = "Hardcore" ) ``` ```{r} coef(summary(m4)) ``` In this model we notice again no significant effect of distance to immune cells after accounting for underlying randomness and the binary tumour mask. ```{r Ppm4Plot, fig.width=8, fig.height=8} plot(m4) + geom_sf( data = segmentedTumour, inherit.aes = FALSE, fill = NA, color = "darkred", linewidth = 0.6 ) ``` Now we have a surface of zero intensity outside of the tumour and within the tumour a varrying surface. ```{r} summaryQc <- envelope(m4, pcfinhom, global = TRUE) plot(summaryQc) ``` The goodness of fit is improved in comparison to model `m3` but still we notice some deviations at low radii. ## Multi-image inference ### Fitting a model per image As mentioned above, this dataset contains many images. We may want to fit separate models like those above to each image and look at the resulting distribution of the coefficients relating the distance to immune cells $\beta_{\text{dist}}$ ```{r mPpmLs} mdlLs <- fitModelAcrossImages( spe = spe, imageId = "imageID", imageLs = seq(1, 29), marks = "cellTypeNew", formula = as.formula("p53_Tumour ~ spatstat.geom::distfun(Immune)"), improve.type = "wclik1", method = "palm", interaction = "Hardcore", threshold = 10 ) ``` The dataset describes three tumour subtypes, cold, compartmentalised and mixed. We want to investigate the differences in the distance to immune cells coefficient $\beta_{\text{dist}}$ across these subtypes. First, we need to extract the coefficients from the model and convert this to a `data.frame`. ```{r mPpmToDf, warning=FALSE, message = FALSE, error = FALSE, results = "hide"} mdlDf <- mdlToDf( mdlLs = mdlLs, imageCovariates = c( "imageID", "tumour_type" ) ) ``` ```{r coefficientsmPpm, message=FALSE, warning=FALSE, error=FALSE} mdlDfSub <- mdlDf %>% filter(covariate %in% c("spatstat.geom.distfun.Immune.")) ggplot(mdlDfSub, aes(x = covariate, y = Estimate, label = imageID)) + geom_boxplot(outlier.shape = NA, alpha = 0.3) + geom_jitter(aes(color = log10(S.E.)), position = position_jitter(seed = 123) ) + geom_text(aes(color = log10(S.E.)), hjust = 0, vjust = 0, position = position_jitter(seed = 123) ) + theme_light() + facet_wrap(~tumour_type) ``` We see a difference between the tumour types: cold tumours show no effect and a generally positive effect of immune cell distance on p53+ cells in compartmentalised and mixed tumours despite not being significant. There is a model that is a clear outliers, let's look at it in more detail ```{r model1213Plot, fig.width=8, fig.height=8} # model 13 plot(mdlLs[[13]]) ``` The second model is very sparse in terms of the response point distribution. This could explain some of the more extreme values. ### Second-stage model of coefficients We can also test the effect of tumour type (cold, compartmentalised, mixed) on the distance to immune cells coefficient $\beta_{\text{dist}}$ with a linear model. We weight each observation by the inverse of the standard error, as done by @gerber2026mimic. The model is then parametrised as follows: $$ {\hat{\beta}}_{\text{dist}} = \gamma_0 + \gamma Z_{\text{stage}} + \epsilon \quad \epsilon \sim \mathcal{N}\!\left(0,\, \sigma^2 \text{SE}_{\text{dist}}\right) $$ We can fit this model ```{r SecondStageLm} mdl <- lm(Estimate ~ tumour_type, data = mdlDf, weights = 1 / (mdlDf$S.E.), subset = covariate == "spatstat.geom.distfun.Immune." ) print(summary(mdl)) ``` In agreement with the findings above, there are positive but only weakly significant effects for both compartmentalised and mixed tumours in comparison to cold tumours. # AI statement AI was used to revise the content in this vignette including the formulae and derivations # Session Information ```{r sessionInfo} sessionInfo() ``` # References