# Spatial heterogeneity with SPIAT

Yuzhou Feng

#### 2023-05-24

#### Package

SPIAT 1.3.2

    library(SPIAT)

Cell colocalisation metrics allow capturing a dominant spatial pattern in an image. However, patterns are unlikely to be distributed evenly in a tissue, but rather there will be spatial heterogeneity of patterns. To measure this, SPIAT splits the image into smaller images (either using a grid or concentric circles around a reference cell population), followed by calculation of a spatial metric of a pattern of interest (e.g. cell colocalisation, entropy), and then measures the Prevalence and Distinctiveness of the pattern.

In this vignette we will use an inForm data file that’s already been formatted for SPIAT with `format_image_to_spe()`, which we can load with `data()`. We will use `define_celltypes()` to define the cells with certain combinations of markers.

    data("simulated_image")

    # define cell types
    formatted_image <- define_celltypes(
        simulated_image,
        categories = c("Tumour_marker","Immune_marker1,Immune_marker2",
                       "Immune_marker1,Immune_marker3",
                       "Immune_marker1,Immune_marker2,Immune_marker4", "OTHER"),
        category_colname = "Phenotype",
        names = c("Tumour", "Immune1", "Immune2", "Immune3", "Others"),
        new_colname = "Cell.Type")

# 1 Localised Entropy

Entropy in spatial analysis refers to the balance in the number of cells of distinct populations. An entropy score can be obtained for an entire image. However, the entropy of one image does not provide us spatial information of the image.

    calculate_entropy(formatted_image, cell_types_of_interest = c("Immune1","Immune2"),
                      feature_colname = "Cell.Type")

    ## [1] 0.9294873

We therefore propose the concept of Localised Entropy which calculates an entropy score for a predefined local region. These local regions can be calculated as defined in the next two sections.

## 1.1 Fishnet grid

One approach to calculate localised metric is to split the image into fishnet grid squares. For each grid square, `grid_metrics()` calculates the metric for that square and visualise the raster image. Users can choose any metric as the localised metric. Here we use entropy as an example.

For cases where the localised metric is not symmetrical (requires specifying a target and reference cell type), the first item in the vector used for `cell_types_of_interest` marks the reference cells and the second item the target cells. Here we are using Entropy, which is symmetrical, so we can use any order of cell types in the input.

    data("defined_image")
    grid <- grid_metrics(defined_image, FUN = calculate_entropy, n_split = 20,
                         cell_types_of_interest=c("Tumour","Immune3"),
                         feature_colname = "Cell.Type")

After calculating the localised entropy for each of the grid squares, we can apply metrics like percentages of grid squares with patterns (Prevalence) and Moran’s I (Distinctiveness).

For the Prevalence, we need to select a threshold over which grid squares are considered ‘positive’ for the pattern. The selection of threshold depends on the pattern and metric the user chooses to find the localised pattern. Here we chose 0.75 for entropy because 0.75 is roughly the entropy of two cell types when their ratio is 1:5 or 5:1.

    calculate_percentage_of_grids(grid, threshold = 0.75, above = TRUE)

    ## [1] 13

    calculate_spatial_autocorrelation(grid, metric = "globalmoran")

    ## [1] 0.09446964

## 1.2 Gradients (based on concentric circles)

We can use the `compute_gradient()` function to calculate metrics (entropy, mixing score, percentage of cells within radius, marker intensity) for a range of radii from reference cells. Here, an increasing circle is drawn around each cell of the reference cell type and the desired score is calculated for cells within each circle.

The first item in the vector used for `cell_types_of_interest` marks the reference cells and the second item the target cells. Here, Immune1 cells are reference cells and Immune2 are target cells.

    gradient_positions <- c(30, 50, 100)
    gradient_entropy <-
      compute_gradient(defined_image, radii = gradient_positions,
                       FUN = calculate_entropy,  cell_types_of_interest = c("Immune1","Immune2"),
                       feature_colname = "Cell.Type")
    length(gradient_entropy)

    ## [1] 3

    head(gradient_entropy[[1]])

    ##         Cell.X.Position Cell.Y.Position Immune1 Immune2 total Immune1_log2
    ## Cell_15       109.67027        17.12956       1       0     1            0
    ## Cell_25       153.22795       128.29915       1       0     1            0
    ## Cell_30        57.29037        49.88533       1       0     1            0
    ## Cell_48        83.47798       295.75058       2       0     2            1
    ## Cell_56        35.24227       242.84862       1       0     1            0
    ## Cell_61       156.39943       349.08154       2       0     2            1
    ##         Immune2_log2 total_log2 Immune1ratio Immune1_entropy Immune2ratio
    ## Cell_15            0          0            1               0            0
    ## Cell_25            0          0            1               0            0
    ## Cell_30            0          0            1               0            0
    ## Cell_48            0          1            1               0            0
    ## Cell_56            0          0            1               0            0
    ## Cell_61            0          1            1               0            0
    ##         Immune2_entropy entropy
    ## Cell_15               0       0
    ## Cell_25               0       0
    ## Cell_30               0       0
    ## Cell_48               0       0
    ## Cell_56               0       0
    ## Cell_61               0       0

The `compute_gradient()` function outputs the numbers cells within each radii for each reference cell. The output is formatted as a list of data.frames, one for each specified radii. In each data.frame, the rows show the reference cells. The last column of the data.frame is the entropy calculated for cells in the circle of the reference cell. Users can then an average score or another aggregation metric to report the results.

An alternative approach is to combine the results of all the circles (rather than have one for each individual reference cell). Here, for each radii, we simultaneously identify all the cells in the circles surrounding each reference cell, and calculate a single entropy score. We have created a specific function for this - `entropy_gradient_aggregated()`. The output of this function is an overall entropy score for each radii.

    gradient_pos <- seq(50, 500, 50) ##radii
    gradient_results <- entropy_gradient_aggregated(defined_image, cell_types_of_interest = c("Immune3","Tumour"),
                                                    feature_colname = "Cell.Type", radii = gradient_pos)
    # plot the results
    plot(1:10,gradient_results$gradient_df[1, 3:12])

# 2 You can access the vignettes for other modules of SPIAT here:

- Overview of SPIAT
- Data reading and formatting
- Quality control and visualisation
- Basic analysis
- Cell colocalisation
- Tissue structure
- Cellular neighborhood

# 3 Reproducibility

    sessionInfo()

    ## R version 4.3.0 RC (2023-04-18 r84287 ucrt)
    ## Platform: x86_64-w64-mingw32/x64 (64-bit)
    ## Running under: Windows Server 2022 x64 (build 20348)
    ##
    ## Matrix products: default
    ##
    ##
    ## locale:
    ## [1] LC_COLLATE=C
    ## [2] LC_CTYPE=English_United States.utf8
    ## [3] LC_MONETARY=English_United States.utf8
    ## [4] LC_NUMERIC=C
    ## [5] LC_TIME=English_United States.utf8
    ##
    ## time zone: America/New_York
    ## tzcode source: internal
    ##
    ## attached base packages:
    ## [1] stats4    stats     graphics  grDevices utils     datasets  methods
    ## [8] base
    ##
    ## other attached packages:
    ##  [1] SPIAT_1.3.2                 SpatialExperiment_1.11.0
    ##  [3] SingleCellExperiment_1.23.0 SummarizedExperiment_1.31.1
    ##  [5] Biobase_2.61.0              GenomicRanges_1.53.1
    ##  [7] GenomeInfoDb_1.37.1         IRanges_2.35.1
    ##  [9] S4Vectors_0.39.1            BiocGenerics_0.47.0
    ## [11] MatrixGenerics_1.13.0       matrixStats_0.63.0
    ## [13] BiocStyle_2.29.0
    ##
    ## loaded via a namespace (and not attached):
    ##   [1] RColorBrewer_1.1-3        shape_1.4.6
    ##   [3] jsonlite_1.8.4            magrittr_2.0.3
    ##   [5] spatstat.utils_3.0-3      magick_2.7.4
    ##   [7] farver_2.1.1              rmarkdown_2.21
    ##   [9] GlobalOptions_0.1.2       zlibbioc_1.47.0
    ##  [11] vctrs_0.6.2               Cairo_1.6-0
    ##  [13] spatstat.explore_3.2-1    DelayedMatrixStats_1.23.0
    ##  [15] RCurl_1.98-1.12           elsa_1.1-28
    ##  [17] terra_1.7-29              htmltools_0.5.5
    ##  [19] S4Arrays_1.1.4            raster_3.6-20
    ##  [21] Rhdf5lib_1.23.0           SparseArray_1.1.6
    ##  [23] rhdf5_2.45.0              sass_0.4.6
    ##  [25] pracma_2.4.2              bslib_0.4.2
    ##  [27] htmlwidgets_1.6.2         mmand_1.6.3
    ##  [29] plyr_1.8.8                plotly_4.10.1
    ##  [31] cachem_1.0.8              lifecycle_1.0.3
    ##  [33] iterators_1.0.14          pkgconfig_2.0.3
    ##  [35] Matrix_1.5-4.1            R6_2.5.1
    ##  [37] fastmap_1.1.1             clue_0.3-64
    ##  [39] GenomeInfoDbData_1.2.10   digest_0.6.31
    ##  [41] colorspace_2.1-0          tensor_1.5
    ##  [43] dqrng_0.3.0               crosstalk_1.2.0
    ##  [45] beachmat_2.17.2           labeling_0.4.2
    ##  [47] fansi_1.0.4               spatstat.sparse_3.0-1
    ##  [49] httr_1.4.6                polyclip_1.10-4
    ##  [51] abind_1.4-5               compiler_4.3.0
    ##  [53] bit64_4.0.5               withr_2.5.0
    ##  [55] doParallel_1.0.17         BiocParallel_1.35.2
    ##  [57] apcluster_1.4.10          highr_0.10
    ##  [59] HDF5Array_1.29.3          R.utils_2.12.2
    ##  [61] DelayedArray_0.27.4       rjson_0.2.21
    ##  [63] gtools_3.9.4              tools_4.3.0
    ##  [65] goftest_1.2-3             R.oo_1.25.0
    ##  [67] glue_1.6.2                dbscan_1.1-11
    ##  [69] nlme_3.1-162              rhdf5filters_1.13.2
    ##  [71] grid_4.3.0                Rtsne_0.16
    ##  [73] cluster_2.1.4             reshape2_1.4.4
    ##  [75] generics_0.1.3            gtable_0.3.3
    ##  [77] spatstat.data_3.0-1       tzdb_0.4.0
    ##  [79] R.methodsS3_1.8.2         tidyr_1.3.0
    ##  [81] data.table_1.14.8         sp_1.6-0
    ##  [83] utf8_1.2.3                XVector_0.41.1
    ##  [85] spatstat.geom_3.2-1       ggrepel_0.9.3
    ##  [87] RANN_2.6.1                foreach_1.5.2
    ##  [89] pillar_1.9.0              stringr_1.5.0
    ##  [91] vroom_1.6.3               limma_3.57.1
    ##  [93] circlize_0.4.15           dplyr_1.1.2
    ##  [95] lattice_0.21-8            bit_4.0.5
    ##  [97] deldir_1.0-9              tidyselect_1.2.0
    ##  [99] ComplexHeatmap_2.17.0     locfit_1.5-9.7
    ## [101] scuttle_1.11.0            knitr_1.42
    ## [103] gridExtra_2.3             bookdown_0.34
    ## [105] edgeR_3.43.2              xfun_0.39
    ## [107] dittoSeq_1.13.1           DropletUtils_1.21.0
    ## [109] pheatmap_1.0.12           stringi_1.7.12
    ## [111] lazyeval_0.2.2            yaml_2.3.7
    ## [113] evaluate_0.21             codetools_0.2-19
    ## [115] archive_1.1.5             tibble_3.2.1
    ## [117] BiocManager_1.30.20       cli_3.6.1
    ## [119] munsell_0.5.0             jquerylib_0.1.4
    ## [121] Rcpp_1.0.10               spatstat.random_3.1-5
    ## [123] png_0.1-8                 parallel_4.3.0
    ## [125] ggplot2_3.4.2             sparseMatrixStats_1.13.0
    ## [127] bitops_1.0-7              viridisLite_0.4.2
    ## [129] scales_1.2.1              ggridges_0.5.4
    ## [131] purrr_1.0.1               crayon_1.5.2
    ## [133] GetoptLong_1.0.5          rlang_1.1.1
    ## [135] cowplot_1.1.1

# 4 Author Contributions

AT, YF, TY, ML, JZ, VO, MD are authors of the package code. MD and YF wrote the vignette. AT, YF and TY designed the package.