1 Overview

SpaceMarkers leverages latent feature analysis of the spatial components of transcriptomic data to identify biologically relevant molecular interactions between cell groups.This tutorial will use the latent features from CoGAPS to look at pattern interactions in a Visium 10x breast ductal carcinoma spatial transcriptomics dataset.

2 Installation

if (!require("BiocManager", quietly = TRUE))
    install.packages("BiocManager")

BiocManager::install("SpaceMarkers")
library(SpaceMarkers)

3 Setup

3.2 Extracting Counts Matrix

3.2.1 load10xExpr

Here the counts matrix will be obtained from the h5 object on the Visium site and genes with less than 3 counts are removed from the dataset.This can be achieved with the load10XExpr function.

download.file(counts_url,file.path(data_dir,basename(counts_url)), mode = "wb")
counts_matrix <- load10XExpr(visiumDir = data_dir, h5filename = counts_file)
good_gene_threshold <- 3
goodGenes <- rownames(counts_matrix)[
    apply(counts_matrix,1,function(x) sum(x>0)>=good_gene_threshold)]
## Warning in asMethod(object): sparse->dense coercion: allocating vector of size
## 1.3 GiB
counts_matrix <- counts_matrix[goodGenes,]

3.3 Obtaining CoGAPS Patterns

In this example the latent features from CoGAPS will be used to identify interacting genes with SpaceMarkers. Here the featureLoadings (genes) and samplePatterns (barcodes) for both the expression matrix and CoGAPS matrix need to match.

cogaps_result <- readRDS(system.file("extdata","CoGAPS_result.rds",
    package="SpaceMarkers",mustWork = TRUE))
features <- intersect(rownames(counts_matrix),rownames(
    slot(cogaps_result,"featureLoadings")))
barcodes <- intersect(colnames(counts_matrix),rownames(
    slot(cogaps_result,"sampleFactors")))
counts_matrix <- counts_matrix[features,barcodes]
cogaps_matrix<-slot(cogaps_result,"featureLoadings")[features,]%*%
    t(slot(cogaps_result,"sampleFactors")[barcodes,])

3.4 Obtaining Spatial Coordinates

3.4.1 load10XCoords

The spatial coordinates will also be pulled from Visium for this dataset. These are combined with the latent features to demonstrate how cells for each pattern interact in 2D space. The data can be extracted with the load10XCoords() function

download.file(sp_url, file.path(data_dir,basename(sp_url)), mode = "wb")
untar(file.path(data_dir,basename(sp_url)), exdir = file.path(data_dir))
spCoords <- load10XCoords(visiumDir = data_dir, 
                          resolution="lowres", version = "1.0")
## resolution: lowres
rownames(spCoords) <- spCoords$barcode
spCoords <- spCoords[barcodes,]
spPatterns <- cbind(spCoords,slot(cogaps_result,"sampleFactors")[barcodes,])
head(spPatterns)
##                               barcode         y        x    Pattern_1
## AAACAACGAATAGTTC-1 AAACAACGAATAGTTC-1  67.28568 207.4858 0.4676255882
## AAACAAGTATCTCCCA-1 AAACAAGTATCTCCCA-1 238.79054 375.0650 0.2690758109
## AAACAATCTACTAGCA-1 AAACAATCTACTAGCA-1  77.82161 260.3531 0.1105933860
## AAACACCAATAACTGC-1 AAACACCAATAACTGC-1 268.53653 212.2053 0.0002508377
## AAACAGAGCGACTCCT-1 AAACAGAGCGACTCCT-1 115.92419 360.0982 0.2849308848
## AAACAGCTTTCAGAAG-1 AAACAGCTTTCAGAAG-1 213.86511 192.9231 0.1583736390
##                       Pattern_2    Pattern_3    Pattern_4    Pattern_5
## AAACAACGAATAGTTC-1 1.049391e-01 2.576064e-01 0.6848062277 4.747092e-02
## AAACAAGTATCTCCCA-1 4.394425e-01 2.056469e-01 0.2921337187 1.167576e-02
## AAACAATCTACTAGCA-1 1.148523e-02 2.309153e-01 0.4111314714 9.508318e-02
## AAACACCAATAACTGC-1 1.685795e-01 1.223603e-01 0.0001562788 8.041928e-01
## AAACAGAGCGACTCCT-1 1.102506e-01 9.053156e-08 0.2429406196 3.430807e-08
## AAACAGCTTTCAGAAG-1 9.741083e-06 1.723470e-01 0.3059957027 7.167605e-01

For demonstration purposes we will look at two patterns; Pattern_1 (immune cell) and Pattern_5 (invasive carcinoma lesion). Furthermore we will only look at the relationship between a pre-curated list of genes for efficiency.

data("curated_genes")
spPatterns <- spPatterns[c("barcode","y","x","Pattern_1","Pattern_5")]
counts_matrix <- counts_matrix[curated_genes,]
cogaps_matrix <- cogaps_matrix[curated_genes, ]

4 Executing SpaceMarkers

4.1 SpaceMarker Modes

SpaceMarkers can operate in ‘residual’ or ‘DE’ (DifferentialExpression) mode. In an ideal world the overlapping patterns identified by SpaceMarkers would be a homogeneous population of cells and the relationship between them would be linear. However, due to confounding effects of variations in cell density and common cell types in any given region, this is not always true.

To account for these confounding effects, the ‘residual’ mode compares the feature interactions between the expression matrix and the reconstructed latent space matrix. The features with the highest residual error are reported. The genes are then classified according to regions of overlapping vs exclusive influence. The default mode is ‘residual’ mode.

However this is not to say there is no utility for DE mode. Suppose the feature (gene) information is not readily available and only the sample (cells) latent feature patterns with P-values are available? This is the advantage of ‘DE’ mode. Where residual mode assesses the non-linear effects that may arise from confounding variables, ‘DE’ mode assesses simple linear interactions between patterns directly from expression. DE mode like residual mode also compares genes from regions of overlapping vs exclusive influence butdoes not consider residuals from the expression matrix as there is no matrix reconstruction with the latent feature matrix.

4.1.1 Residual Mode

4.1.1.1 SpaceMarkers Step1: Hotpsots

SpaceMarkers identifies regions of influence using a gaussian kernel outlier based model. Spots that have spatial influence beyond the defined outlier threshold are termed hotspots. SpaceMarkers then identifies where the hotspots are overlapping/interacting and where they are mutually exclusive.

get_spatial_params_morans_i: This function sets the width of the spatial kernel (sigmaOpt) as well as the outlier threshold around the set of spots (threshOpt) for each pattern. By default, the sigmaOpt is set to the spot diameter at the appropriate resolution. Note that the legacy function has been deprecated and has been renamed to .get_spatial_params_morans_i. Please read the documentation for more information.

optParams <- get_spatial_params_morans_i(spPatterns,visiumDir = data_dir,
                                          resolution = "lowres")
## Warning in get_spatial_params_morans_i(spPatterns, visiumDir = data_dir, : 'get_spatial_params_morans_i' is deprecated.
## Use 'get_spatial_parameters' instead.
## See help("Deprecated")

4.1.1.2 SpaceMarkers Step2: Interacting Genes

get_pairwise_interacting_genes: This function identifies the regions of influence and interaction as well as the genes associated with these regions. A non-parametric Kruskal-Wallis test is used to identify statistically significant genes in any one region of influence without discerning which region is more significant. A post hoc Dunn’s Test is used for analysis of genes between regions and can distinguish which of two regions is more significant. If ‘residual’ mode is selected the user must provide a reconstructed matrix from the latent feature matrix. The matrix is passed to the ‘reconstruction’ argument and can be left as NULL for ‘DE’ mode. The ‘data’ parameter is the original expression matrix. The ‘spPatterns’ argument takes a dataframe with the spatial coordinates of each cell as well as the patterns. The spatial coordinate columns must contain the labels ‘x’ and ‘y’ to be recognized by the function. The output of this are all possible pairs fo interactions from the spatial patterns.

SpaceMarkers <- get_pairwise_interacting_genes(data = counts_matrix,
                                    reconstruction = cogaps_matrix,
                                    optParams = optParams,
                                    spPatterns = spPatterns,
                                    mode ="residual",analysis="overlap")
## pattern_pairs not provided. Calculating all 
##             possible pairs.
## Using user provided optParams.
## Calculating genes of interest for Pattern_1 and Pattern_5
## Warning in matrixTests::row_kruskalwallis(x = testMat, g = region): 1560
## columns dropped due to missing group information

NB: When running get_pairwise_interacting_genes some warnings may be generated. The warnings are due to the nature of the ‘sparse’ data being used. Comparing two cells from the two patterns with identical information is redundant as SpaceMarkers is identifying statistically different expression for interactions exclusive to either of the two patterns and a region that is due to interaction between the given two patterns. Also, if there are too many zeros in the genes (rows) of those regions, the columns are dropped as there is nothing to compare in the Kruskal Wallis test.

print(head(SpaceMarkers[[1]]$interacting_genes[[1]]))
##        Gene Pattern_1 x Pattern_5 KW.obs.tot KW.obs.groups KW.df KW.statistic
## APOE   APOE                vsBoth       3338             3     2    100.91864
## APOC1 APOC1                vsBoth       3338             3     2    513.48823
## FAH     FAH                vsBoth       3338             3     2     87.91238
## CAPG   CAPG                vsBoth       3338             3     2    234.97212
## IFI30 IFI30                vsBoth       3338             3     2    253.32664
## CLU     CLU                vsBoth       3338             3     2     83.33640
##           KW.pvalue      KW.p.adj Dunn.zP1_Int Dunn.zP2_Int Dunn.zP2_P1
## APOE   1.218416e-22  2.893738e-22    -9.151132    -9.140726  -0.3043052
## APOC1 3.143743e-112 1.706604e-111   -18.413260   -22.059640  -5.1061583
## FAH    8.129599e-20  1.817205e-19    -8.905082    -8.067668   0.7176173
## CAPG   9.472239e-52  2.999542e-51   -12.873982   -14.735166  -2.7266981
## IFI30  9.790811e-56  3.189007e-55   -11.921986   -15.784373  -5.1459473
## CLU    8.011808e-19  1.691382e-18    -7.453496    -8.872683  -1.9972816
##       Dunn.pval_1_Int Dunn.pval_2_Int Dunn.pval_2_1 Dunn.pval_1_Int.adj
## APOE     5.634008e-20    6.203467e-20  7.608954e-01        3.001566e-19
## APOC1    1.028410e-75   7.719491e-108  3.287743e-07        1.324078e-74
## FAH      5.334680e-19    7.165349e-16  4.729933e-01        2.702322e-18
## CAPG     6.306503e-38    3.832545e-49  6.397153e-03        4.428885e-37
## IFI30    9.091481e-33    3.985916e-56  2.661742e-07        5.977165e-32
## CLU      9.089842e-14    7.140429e-19  4.579460e-02        3.745015e-13
##       Dunn.pval_2_Int.adj Dunn.pval_2_1.adj SpaceMarkersMetric
## APOE         3.248934e-19      1.000000e+00           6.403404
## APOC1       1.325179e-106      1.026174e-06           6.331795
## FAH          3.256019e-15      7.216040e-01           6.186723
## CAPG         3.289601e-48      1.259058e-02           6.141012
## IFI30        4.398743e-55      8.479156e-07           5.231463
## CLU          3.558698e-18      7.994651e-02           5.092176
print(head(SpaceMarkers[[1]]$hotspots))
##      Pattern_1   Pattern_5  
## [1,] "Pattern_1" NA         
## [2,] "Pattern_1" NA         
## [3,] NA          NA         
## [4,] NA          "Pattern_5"
## [5,] "Pattern_1" NA         
## [6,] "Pattern_1" "Pattern_5"

The output is a list of data frames with information about the interacting genes between patterns from the CoGAPS matrix (interacting_genes object). There is also a data frame with all of the regions of influence for any two of patterns (the hotspotRegions object).

For the ‘interacting_genes’ data frames, the first column is the list of genes and the second column says whether the statistical test were done vsPattern_1, vsPattern_2 or vsBoth. The remaining columns are statistics for the Kruskal-Wallis test and the post hoc Dunn’s test.The SpaceMarkersMetric column is a product of sums of the Dunn’s statistics and is used to rank the genes.

4.1.2 DE Mode

As described previously ‘DE’ mode only requires the counts matrix and spatial patterns and not the reconstructed CoGAPS matrix. It identifies simpler molecular interactions between regions and still executes the ‘hotspots’ and ‘interacting genes’ steps of SpaceMarkers

SpaceMarkers_DE <- get_pairwise_interacting_genes(
    data=counts_matrix,reconstruction=NULL,
    optParams = optParams,
    spPatterns = spPatterns,
    mode="DE",analysis="overlap")
## pattern_pairs not provided. Calculating all 
##             possible pairs.
## Using user provided optParams.
## Calculating genes of interest for Pattern_1 and Pattern_5
## Warning in matrixTests::row_kruskalwallis(x = testMat, g = region): 1558
## columns dropped due to missing group information

4.1.3 Residual Mode vs DE Mode: Differences

One of the first things to notice is the difference in the number of genes identified between the two modes.

residual_p1_p5<-SpaceMarkers[[1]]$interacting_genes[[1]]
DE_p1_p5<-SpaceMarkers_DE[[1]]$interacting_genes[[1]]
paste(
    "Residual mode identified",dim(residual_p1_p5)[1],
        "interacting genes,while DE mode identified",dim(DE_p1_p5)[1],
        "interacting genes",collapse = NULL)
## [1] "Residual mode identified 114 interacting genes,while DE mode identified 114 interacting genes"

DE mode produces more genes than residual mode because the matrix of residuals highlights less significant differences for confounding genes across the spots.The next analysis will show where the top genes rank in each mode’s list if they are identified at all. A function was created that will take the top 20 genes of a reference list of genes and compare it to the entire list of a second list of genes. The return object is a data frame of the gene, the name of each list and the ranking of each gene as compared to the reference list. If there is no gene identified in the second list compared to the reference it is classified as NA.

compare_genes <- function(ref_list, list2,ref_name = "mode1",
                            list2_name = "mode2", sub_slice = NULL){
    ref_rank <- seq(1,length(ref_list),1)
    list2_ref_rank <- which(list2 %in% ref_list)
    list2_ref_genes <- list2[which(list2 %in% ref_list)]
    ref_genes_only <- ref_list[ !ref_list  %in% list2_ref_genes ]
    mode1 <- data.frame("Gene" = ref_list,"Rank" = ref_rank,"mode"= ref_name)
    mode2 <- data.frame("Gene" = c(list2_ref_genes, ref_genes_only),"Rank" = c(
        list2_ref_rank,rep(NA,length(ref_genes_only))),"mode"= list2_name)
    mode1_mode2 <- merge(mode1, mode2, by = "Gene", all = TRUE) 
    mode1_mode2 <- mode1_mode2[order(mode1_mode2$Rank.x),]
    mode1_mode2 <- subset(mode1_mode2,select = c("Gene","Rank.x","Rank.y"))
    colnames(mode1_mode2) <- c("Gene",paste0(ref_name,"_Rank"),
                                paste0(list2_name,"_Rank"))
    return(mode1_mode2)
}
res_to_DE <- compare_genes(head(residual_p1_p5$Gene, n = 20),DE_p1_p5$Gene,
                            ref_name="residual",list2_name="DE")
DE_to_res <- compare_genes(head(DE_p1_p5$Gene, n = 20),residual_p1_p5$Gene,
                            ref_name = "DE",list2_name = "residual")

4.1.3.1 Comparing residual mode to DE mode

res_to_DE
##        Gene residual_Rank DE_Rank
## 4      APOE             1      14
## 3     APOC1             2      18
## 11      FAH             3      34
## 5      CAPG             4      21
## 13    IFI30             5      12
## 6       CLU             6      53
## 8    COL4A1             7       6
## 1    AKR1A1             8       5
## 2     AP2S1             9      25
## 17    PHGR1            10      74
## 16   NDUFB2            11      20
## 15   LAPTM5            12      38
## 14     IGHE            13      55
## 7   COL18A1            14      24
## 12 HLA-DRB1            15     113
## 10     CTSB            16       1
## 9      CST1            17       2
## 20   ZNF593            18      50
## 18     TGM2            19      46
## 19  TMEM147            20      48

Here we identify the top 20 genes in ‘residual’ mode and their corresponding ranking in DE mode. HLA-DRB1 is the only gene identified in residual mode and not in DE mode. The other genes are ranked relatively high in both residual and DE mode.

4.1.3.2 Comparing DE mode to residual mode

DE_to_res
##      Gene DE_Rank residual_Rank
## 7    CTSB       1            16
## 6    CST1       2            17
## 18    SDS       3            93
## 10    FTL       4            50
## 2  AKR1A1       5             8
## 5  COL4A1       6             7
## 14 MAP2K2       7            37
## 8    CTSD       8            55
## 1    ACTB       9           104
## 19  TREM2      10            48
## 16  PRKD3      11           107
## 13  IFI30      12             5
## 12   HCP5      13            57
## 4    APOE      14             1
## 11  GCHFR      15            36
## 9    FTH1      16            65
## 17   PSAP      17            32
## 3   APOC1      18             2
## 20 TSPAN4      19            28
## 15 NDUFB2      20            11

Recall that DE mode looks at the information encoded in the latent feature space and does not filter out genes based on any confounders between the counts matrix and latent feature matrix as is done in ‘residual’ mode. Therefore there are more genes in DE mode not identified at all in residual mode.

There is some agreement with interacting genes between the two methods but there are also quite a few differences. Therefore, the selected mode can significantly impact the downstream results and should be taken into consideration based on the specific biological question being answered and the data available.

4.2 Types of Analyses

Another feature of the SpaceMarkers package is the type of analysis that can be carried out, whether ‘overlap’ or ‘enrichment’ mode. The major difference between the two is that enrichment mode includes genes even if they did not pass the post-hoc Dunn’s test. These additional genes were included to enable a more statistically powerful pathway enrichment analysis and understand to a better extent the impact of genes involved each pathway. Changing analysis = ‘enrichment’ in the get_pairwise_interacting_genes function will enable this.

SpaceMarkers_enrich <- get_pairwise_interacting_genes(data = counts_matrix,
                                    reconstruction = cogaps_matrix,
                                    optParams = optParams,
                                    spPatterns = spPatterns,
                                    mode ="residual",analysis="enrichment")
## pattern_pairs not provided. Calculating all 
##             possible pairs.
## Using user provided optParams.
## Calculating genes of interest for Pattern_1 and Pattern_5
## Warning in matrixTests::row_kruskalwallis(x = testMat, g = region): 1560
## columns dropped due to missing group information
SpaceMarkers_DE_enrich <- get_pairwise_interacting_genes(
    data=counts_matrix,reconstruction=NULL,
    optParams = optParams,
    spPatterns = spPatterns,
    mode="DE",analysis="enrichment")
## pattern_pairs not provided. Calculating all 
##             possible pairs.
## Using user provided optParams.
## Calculating genes of interest for Pattern_1 and Pattern_5
## Warning in matrixTests::row_kruskalwallis(x = testMat, g = region): 1558
## columns dropped due to missing group information
residual_p1_p5_enrichment<-SpaceMarkers_enrich[[1]]$interacting_genes[[1]]$Gene
DE_p1_p5_enrichment<-SpaceMarkers_DE_enrich[[1]]$interacting_genes[[1]]$Gene

4.2.1 Residual Mode vs DE Mode: Enrichment

The data frames for the Pattern_1 x Pattern_5 will be used to compare the results of the enrichment analyses

enrich_res_to_de<-compare_genes(
    head(DE_p1_p5_enrichment, 20),
    residual_p1_p5_enrichment,
    ref_name="DE_Enrich",list2_name = "res_Enrich")
enrich_res_to_de
##      Gene DE_Enrich_Rank res_Enrich_Rank
## 7    CTSB              1              16
## 6    CST1              2              17
## 18    SDS              3              93
## 10    FTL              4              50
## 2  AKR1A1              5               8
## 5  COL4A1              6               7
## 14 MAP2K2              7              37
## 8    CTSD              8              55
## 1    ACTB              9             104
## 19  TREM2             10              48
## 16  PRKD3             11             107
## 13  IFI30             12               5
## 12   HCP5             13              57
## 4    APOE             14               1
## 11  GCHFR             15              36
## 9    FTH1             16              65
## 17   PSAP             17              32
## 3   APOC1             18               2
## 20 TSPAN4             19              28
## 15 NDUFB2             20              11

The ranks differ alot more here because now genes that were not previously ranked are assigned a score.

overlap_enrich_de<-compare_genes(
    head(DE_p1_p5_enrichment,20),
    DE_p1_p5$Gene,
    ref_name="DE_Enrich",
    list2_name="DE_Overlap")
overlap_enrich_de
##      Gene DE_Enrich_Rank DE_Overlap_Rank
## 7    CTSB              1               1
## 6    CST1              2               2
## 18    SDS              3               3
## 10    FTL              4               4
## 2  AKR1A1              5               5
## 5  COL4A1              6               6
## 14 MAP2K2              7               7
## 8    CTSD              8               8
## 1    ACTB              9               9
## 19  TREM2             10              10
## 16  PRKD3             11              11
## 13  IFI30             12              12
## 12   HCP5             13              13
## 4    APOE             14              14
## 11  GCHFR             15              15
## 9    FTH1             16              16
## 17   PSAP             17              17
## 3   APOC1             18              18
## 20 TSPAN4             19              19
## 15 NDUFB2             20              20

The enrichment and overlap analysis are in great agreement for DE mode. Typically, you may see more changes among genes lower in the ranking. This is especially important where genes that do not pass the Dunn’s test for interactions between any of the other two patterns in the overlap analysis are now ranked in enrichment analysis. The Pattern_1 x Pattern_5 entry for these genes is labelled as FALSE.

Here is an example of the statistics for such genes.

tail(SpaceMarkers_DE_enrich[[1]]$interacting_genes[[1]])
##                  Gene Pattern_1 x Pattern_5 KW.obs.tot KW.obs.groups KW.df
## AC012236.1 AC012236.1                 FALSE       3340             3     2
## GPD1             GPD1                 FALSE       3340             3     2
## ADAM23         ADAM23                 FALSE       3340             3     2
## MAGED2         MAGED2                 FALSE       3340             3     2
## HLA-DRB1     HLA-DRB1                 FALSE       3340             3     2
## DUSP18         DUSP18                 FALSE       3340             3     2
##            KW.statistic     KW.pvalue      KW.p.adj Dunn.zP1_Int Dunn.zP2_Int
## AC012236.1    12.350893  2.079877e-03  2.605561e-03     2.213857   -0.5989079
## GPD1          63.754722  1.431654e-14  2.632396e-14     5.572919   -0.6396385
## ADAM23         9.742994  7.661888e-03  9.167087e-03     1.112164   -1.4646458
## MAGED2      1084.457241 3.259133e-236 1.857706e-234   -23.970461    1.2339654
## HLA-DRB1    1264.178744 3.069542e-275 3.499278e-273     3.055934  -24.6662937
## DUSP18         4.799923  9.072144e-02  9.849757e-02     2.190837    1.4319811
##            Dunn.zP2_P1 Dunn.pval_1_Int Dunn.pval_2_Int Dunn.pval_2_1
## AC012236.1   -3.371286    1.000000e+00    5.492343e-01  7.481815e-04
## GPD1         -7.422731    1.000000e+00    5.224076e-01  1.147298e-13
## ADAM23       -3.119894    1.000000e+00    1.430176e-01  1.809158e-03
## MAGED2       30.067432   5.654593e-127    1.000000e+00 1.292129e-198
## HLA-DRB1    -33.870493    1.000000e+00   2.460867e-134 1.812140e-251
## DUSP18       -0.854882    1.000000e+00    1.000000e+00  3.926165e-01
##            Dunn.pval_1_Int.adj Dunn.pval_2_Int.adj Dunn.pval_2_1.adj
## AC012236.1        1.000000e+00        5.778402e-01      1.016587e-03
## GPD1              1.000000e+00        5.515314e-01      2.633569e-13
## ADAM23            1.000000e+00        1.599053e-01      2.414868e-03
## MAGED2           1.427785e-125        1.000000e+00     1.957576e-196
## HLA-DRB1          1.000000e+00       8.284919e-133     5.490783e-249
## DUSP18            1.000000e+00        1.000000e+00      4.431513e-01
##            SpaceMarkersMetric
## AC012236.1         -0.4784967
## GPD1               -0.5658261
## ADAM23             -0.6060721
## MAGED2             -0.9882274
## HLA-DRB1           -1.6895201
## DUSP18             -2.0486676

The rankings of genes between the overlap and enrichment analysis in residual mode are comparable as well.

overlap_enrich_res<-compare_genes(
    head(residual_p1_p5$Gene, 20),
    residual_p1_p5_enrichment,
    ref_name ="res_overlap",list2_name="res_enrich")
overlap_enrich_res
##        Gene res_overlap_Rank res_enrich_Rank
## 4      APOE                1               1
## 3     APOC1                2               2
## 11      FAH                3               3
## 5      CAPG                4               4
## 13    IFI30                5               5
## 6       CLU                6               6
## 8    COL4A1                7               7
## 1    AKR1A1                8               8
## 2     AP2S1                9               9
## 17    PHGR1               10              10
## 16   NDUFB2               11              11
## 15   LAPTM5               12              12
## 14     IGHE               13              13
## 7   COL18A1               14              14
## 12 HLA-DRB1               15              15
## 10     CTSB               16              16
## 9      CST1               17              17
## 20   ZNF593               18              18
## 18     TGM2               19              19
## 19  TMEM147               20              20

5 Visualizing SpaceMarkers

5.1 Loading Packages

The following libraries are required to make the plots and summarize dataframes

library(Matrix)
library(rjson)
library(cowplot)
library(RColorBrewer)
library(grid)
library(readbitmap)
library(dplyr)
library(data.table)
library(viridis)
library(ggplot2)

The two main statistics used to help interpret the expression of genes across the patterns are the KW statistics/pvalue and the Dunn’s test. In this context the null hypothesis of the KW test is that the expression of a given gene across all of the spots is equal. The post hoc Dunn’s test identifies how statistically significant the difference in expression of the given gene is between two patterns. The Dunn’s test considers the differences between specific patterns and the KW test considers differences across all of the spots without considering the specific patterns. Ultimately, we summarize and rank these effects with the SpaceMarkersMetric.

We will look at the top few genes based on our SpaceMarkersMetric

res_enrich <- SpaceMarkers_enrich[[1]]$interacting_genes[[1]]
hotspots <- SpaceMarkers_enrich[[1]]$hotspots
top <- res_enrich %>% arrange(-SpaceMarkersMetric)
print(head(top))
##        Gene Pattern_1 x Pattern_5 KW.obs.tot KW.obs.groups KW.df KW.statistic
## APOE   APOE                vsBoth       3338             3     2    100.91864
## APOC1 APOC1                vsBoth       3338             3     2    513.48823
## FAH     FAH                vsBoth       3338             3     2     87.91238
## CAPG   CAPG                vsBoth       3338             3     2    234.97212
## IFI30 IFI30                vsBoth       3338             3     2    253.32664
## CLU     CLU                vsBoth       3338             3     2     83.33640
##           KW.pvalue      KW.p.adj Dunn.zP1_Int Dunn.zP2_Int Dunn.zP2_P1
## APOE   1.218416e-22  2.893738e-22    -9.151132    -9.140726  -0.3043052
## APOC1 3.143743e-112 1.706604e-111   -18.413260   -22.059640  -5.1061583
## FAH    8.129599e-20  1.817205e-19    -8.905082    -8.067668   0.7176173
## CAPG   9.472239e-52  2.999542e-51   -12.873982   -14.735166  -2.7266981
## IFI30  9.790811e-56  3.189007e-55   -11.921986   -15.784373  -5.1459473
## CLU    8.011808e-19  1.691382e-18    -7.453496    -8.872683  -1.9972816
##       Dunn.pval_1_Int Dunn.pval_2_Int Dunn.pval_2_1 Dunn.pval_1_Int.adj
## APOE     5.634008e-20    6.203467e-20  7.608954e-01        3.001566e-19
## APOC1    1.028410e-75   7.719491e-108  3.287743e-07        1.324078e-74
## FAH      5.334680e-19    7.165349e-16  4.729933e-01        2.702322e-18
## CAPG     6.306503e-38    3.832545e-49  6.397153e-03        4.428885e-37
## IFI30    9.091481e-33    3.985916e-56  2.661742e-07        5.977165e-32
## CLU      9.089842e-14    7.140429e-19  4.579460e-02        3.745015e-13
##       Dunn.pval_2_Int.adj Dunn.pval_2_1.adj SpaceMarkersMetric
## APOE         3.248934e-19      1.000000e+00           6.403404
## APOC1       1.325179e-106      1.026174e-06           6.331795
## FAH          3.256019e-15      7.216040e-01           6.186723
## CAPG         3.289601e-48      1.259058e-02           6.141012
## IFI30        4.398743e-55      8.479156e-07           5.231463
## CLU          3.558698e-18      7.994651e-02           5.092176

5.2 Code Setup

The plot_spatial_data_over_image function allows you to look at the deconvoluted patterns on the tissue image. We can compare these spatial maps to the expression of genes identified interacting genes on violin plots.

createInteractCol <- function(spHotspots, 
                              interaction_cols = c("T.cells","B-cells")){
  col1 <- spHotspots[,interaction_cols[1]]
  col2 <- spHotspots[,interaction_cols[2]]
  one <- col1
  two <- col2
  one[!is.na(col1)] <- "match"
  two[!is.na(col2)] <- "match"
  both_idx <- which(one == two)
  both <- col1
  both[both_idx] <- "interacting"
  one_only <- setdiff(which(!is.na(col1)),unique(c(which(is.na(col1)),
                                                   both_idx)))
  two_only <- setdiff(which(!is.na(col2)),unique(c(which(is.na(col2)),
                                                   both_idx)))
  both[one_only] <- interaction_cols[1]
  both[two_only] <- interaction_cols[2]
  both <- factor(both,levels = c(interaction_cols[1],"interacting",
                                 interaction_cols[2]))
  return(both)
}

#NB: Since we are likely to plot multipe genes, this function assumes an
#already transposed counts matrix. This saves time and memory in the long run
#for larger counts matrices
plotSpatialExpr <- function(data,gene,hotspots,patterns,
                               remove.na = TRUE,
                               title = "Expression (Log)", text_size = 15){
  counts <- data
  interact <- createInteractCol(spHotspots = hotspots,
                                interaction_cols = patterns)
  df <- cbind(counts,hotspots,data.frame("region" = interact))
  if (remove.na){
    df <- df[!is.na(df$region),]
  }
  p <- df %>% ggplot( aes_string(x='region',y=gene,
                                            fill='region')) + geom_violin() +
    scale_fill_viridis(discrete = TRUE,alpha=0.6) +
    geom_jitter(color="black",size=0.4,alpha=0.9) +
    theme(legend.position="none",plot.title = element_text(size=text_size),
            axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
    ggtitle(paste0(gene,": ",title)) + xlab("")
  return(p)
}

5.3 Get the Spatial Data

Let’s transpose the counts matrix and combine the expression information with the spatial information.

genes <- top$Gene
counts_df <- as.data.frame(as.matrix(
  t(counts_matrix[rownames(counts_matrix) %in% genes,])))

5.4 Generate Plots

spatialMaps <- list()
exprPlots <- list()

for (g in genes){
  
    spatialMaps[[length(spatialMaps)+1]] <- suppressMessages(
        plot_spatial_data_over_image(visiumDir = data_dir,
                                                         df = cbind(spPatterns, counts_df),feature_col = g,
                                                         resolution="lowres",title = g))
  exprPlots[[length(exprPlots)+1]] <- plotSpatialExpr(
    data = counts_df,gene = g,hotspots = hotspots,
                   patterns = c("Pattern_1","Pattern_5"))
}

Below are violin plots and spatial heatmaps to help visualize the expression of individual genes across different patterns.

5.4.1 Pattern_1

plot_spatial_data_over_image(visiumDir = data_dir,
                         df = cbind(spPatterns, counts_df),
                         feature_col = "Pattern_1",
                         resolution="lowres",title = "Pattern_1")

5.4.2 Pattern_5

plot_spatial_data_over_image(visiumDir = data_dir,
                         df = cbind(spPatterns, counts_df),
                         feature_col = "Pattern_5",
                         resolution="lowres",title = "Pattern_5")

On the spatial heatmap, Pattern_5, the invasive carcinoma pattern, is more prevalent on the bottom left of the tissue image. Where as Pattern_1, the immune pattern is prevalent along the diagonal of the tissue image.

5.4.3 Top SpaceMarkers

plot_grid(plotlist = list(exprPlots[[1]],spatialMaps[[1]]))

APOE is expressed highly across all patterns but is especially strong in the interacting pattern. This is a good example of a SpaceMarker that is highly expressed in the interacting region relative to both Pattern_1 and Pattern_5. The second gene also has a similar expression profile.

plot_grid(plotlist = list(exprPlots[[3]],spatialMaps[[3]]))

This gene is not as highly expressed in the tissue as the previous genes but still shows higher and specific expression in the interacting region relative to either Pattern_1 and Pattern_5 hence why it is still highly ranked by the SpaceMarkersMetric.

5.4.4 Negative SpaceMarkersMetric

More negative SpaceMarkersMetric highlights that the expression of a gene in the interacting region is lower relative to either pattern.

bottom <- res_enrich %>% arrange(SpaceMarkersMetric)
print(head(bottom))
##          Gene Pattern_1 x Pattern_5 KW.obs.tot KW.obs.groups KW.df KW.statistic
## CREB1   CREB1                 FALSE       3338             3     2     87.42857
## HMBOX1 HMBOX1                 FALSE       3338             3     2    357.86698
## ADPGK   ADPGK                 FALSE       3338             3     2     72.13570
## PCDH7   PCDH7                 FALSE       3338             3     2    475.13744
## TINF2   TINF2                 FALSE       3338             3     2     58.03803
## MPRIP   MPRIP                 FALSE       3338             3     2     80.05706
##            KW.pvalue      KW.p.adj Dunn.zP1_Int Dunn.zP2_Int Dunn.zP2_P1
## CREB1   1.035448e-19  2.270020e-19     8.329736     8.678432   0.7158832
## HMBOX1  1.950621e-78  8.235954e-78    15.178005    18.488322   4.5822634
## ADPGK   2.167366e-16  4.334732e-16     7.914611     7.526727  -0.2010898
## PCDH7  6.686776e-104 3.464966e-103    16.631151    21.552549   6.6067952
## TINF2   2.495749e-13  4.741923e-13     6.955495     6.915903   0.1924690
## MPRIP   4.128855e-18  8.557991e-18     7.628782     8.539407   1.3801732
##        Dunn.pval_1_Int Dunn.pval_2_Int Dunn.pval_2_1 Dunn.pval_1_Int.adj
## CREB1                1               1  4.740635e-01                   1
## HMBOX1               1               1  4.599701e-06                   1
## ADPGK                1               1  8.406284e-01                   1
## PCDH7                1               1  3.927286e-11                   1
## TINF2                1               1  8.473749e-01                   1
## MPRIP                1               1  1.675333e-01                   1
##        Dunn.pval_2_Int.adj Dunn.pval_2_1.adj SpaceMarkersMetric
## CREB1                    1      7.216040e-01          -6.195526
## HMBOX1                   1      1.257794e-05          -5.959760
## ADPGK                    1      1.000000e+00          -5.920558
## PCDH7                    1      1.462086e-10          -5.788002
## TINF2                    1      1.000000e+00          -5.617755
## MPRIP                    1      2.682269e-01          -5.590985
g <- bottom$Gene[1]
p1 <- plotSpatialExpr(
    data = counts_df,gene = g,hotspots = hotspots, 
                   patterns = c("Pattern_1","Pattern_5"))
p2 <- plot_spatial_data_over_image(visiumDir = data_dir,
                         df = cbind(spPatterns, counts_df),
                         feature_col = g,
                         resolution="lowres",title = g)
## resolution: lowres
## Version not provided. Trying to infer.
## probe_set.csv or .parquet not found.Assuming version 1.0.
plot_grid(plotlist = list(p1,p2))

6 Removing Directories

unlink(file.path(data_dir), recursive = TRUE)

7 References

Appendix

Deshpande, Atul, et al. “Uncovering the spatial landscape of molecular interactions within the tumor microenvironment through latent spaces.” Cell Systems 14.4 (2023): 285-301.

“Space Ranger.” Secondary Analysis in R -Software -Spatial Gene Expression - Official 10x Genomics Support, support.10xgenomics.com/spatial-gene-expression/software/pipelines/latest/rkit. Accessed 22 Dec. 2023.

1 load10XExpr() Arguments

Argument Description
visiumDir A string path to the h5 file with expression information
h5filename A string of the name of the h5 file in the directory

2 load10XCoords() Arguments

Argument Description
visiumDir A path to the location of the the spatial coordinates folder.
resolution String values to look for in the .json object;lowres or highres.

3 get_spatial_params_morans_i() Arguments

Argument Description
spPatterns A data frame of spatial coordinates and patterns.
visiumDir A directory with the spatial and expression data for
the tissue sample
spatialDir A directory with spatial data for the tissue sample
pattern A string of the .json filename with the image parameters
sigma A numeric value specifying the kernel distribution width
threshold A numeric value specifying the outlier threshold for the
kernel
resolution A string specifying the image resolution to scale

4 get_pairwise_interacting_genes() Arguments

Argument Description
data An expression matrix of genes and columns being the samples.
reconstruction Latent feature matrix. NULL if ‘DE’ mode is specified
optParams A matrix of sigmaOpts (width) and the thresOpt (outlierthreshold)
spPatterns A data frame that contains of spatial coordinates and patterns.
mode A string of the reference pattern for comparison to other patterns
minOverlap A string specifying either ‘residual’ or ‘DE’ mode.
hotspotRegions A value that specifies the minimum pattern overlap. 50 is the default
analysis A string specifying the type of analysis
sessionInfo()
## R version 4.5.1 Patched (2025-09-10 r88807)
## Platform: x86_64-apple-darwin20
## Running under: macOS Monterey 12.7.6
## 
## Matrix products: default
## BLAS:   /Library/Frameworks/R.framework/Versions/4.5-x86_64/Resources/lib/libRblas.0.dylib 
## LAPACK: /Library/Frameworks/R.framework/Versions/4.5-x86_64/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.1
## 
## locale:
## [1] C/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
## 
## time zone: America/New_York
## tzcode source: internal
## 
## attached base packages:
## [1] grid      stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
##  [1] ggplot2_4.0.0      viridis_0.6.5      viridisLite_0.4.2  data.table_1.17.8 
##  [5] dplyr_1.1.4        readbitmap_0.1.5   RColorBrewer_1.1-3 cowplot_1.2.0     
##  [9] rjson_0.2.23       Matrix_1.7-4       SpaceMarkers_2.0.0 BiocStyle_2.38.0  
## 
## loaded via a namespace (and not attached):
##  [1] deldir_2.0-4           gridExtra_2.3          rlang_1.1.6           
##  [4] magrittr_2.0.4         matrixStats_1.5.0      compiler_4.5.1        
##  [7] spatstat.geom_3.6-0    png_0.1-8              vctrs_0.6.5           
## [10] reshape2_1.4.4         hdf5r_1.3.12           stringr_1.5.2         
## [13] pkgconfig_2.0.3        shape_1.4.6.1          fastmap_1.2.0         
## [16] magick_2.9.0           backports_1.5.0        labeling_0.4.3        
## [19] nanoparquet_0.4.2      rmarkdown_2.30         effsize_0.8.1         
## [22] tinytex_0.57           purrr_1.1.0            bit_4.6.0             
## [25] xfun_0.53              cachem_1.1.0           jsonlite_2.0.0        
## [28] goftest_1.2-3          matrixTests_0.2.3.1    spatstat.utils_3.2-0  
## [31] BiocParallel_1.44.0    jpeg_0.1-11            tiff_0.1-12           
## [34] broom_1.0.10           parallel_4.5.1         R6_2.6.1              
## [37] bslib_0.9.0            stringi_1.8.7          spatstat.data_3.1-9   
## [40] spatstat.univar_3.1-4  car_3.1-3              jquerylib_0.1.4       
## [43] Rcpp_1.1.0             bookdown_0.45          knitr_1.50            
## [46] tensor_1.5.1           mixtools_2.0.0.1       splines_4.5.1         
## [49] tidyselect_1.2.1       qvalue_2.42.0          dichromat_2.0-0.1     
## [52] abind_1.4-8            yaml_2.3.10            codetools_0.2-20      
## [55] spatstat.random_3.4-2  spatstat.explore_3.5-3 lattice_0.22-7        
## [58] tibble_3.3.0           plyr_1.8.9             withr_3.0.2           
## [61] S7_0.2.0               evaluate_1.0.5         survival_3.8-3        
## [64] polyclip_1.10-7        circlize_0.4.16        kernlab_0.9-33        
## [67] pillar_1.11.1          BiocManager_1.30.26    carData_3.0-5         
## [70] plotly_4.11.0          generics_0.1.4         scales_1.4.0          
## [73] glue_1.8.0             lazyeval_0.2.2         tools_4.5.1           
## [76] bmp_0.3.1              tidyr_1.3.1            ape_5.8-1             
## [79] colorspace_2.1-2       nlme_3.1-168           Formula_1.2-5         
## [82] cli_3.6.5              spatstat.sparse_3.1-0  segmented_2.1-4       
## [85] gtable_0.3.6           rstatix_0.7.3          sass_0.4.10           
## [88] digest_0.6.37          htmlwidgets_1.6.4      farver_2.1.2          
## [91] htmltools_0.5.8.1      lifecycle_1.0.4        httr_1.4.7            
## [94] GlobalOptions_0.1.2    bit64_4.6.0-1          MASS_7.3-65