# Identifying cellular neighborhood with SPIAT

Yuzhou Feng

#### 2023-05-24

#### Package

SPIAT 1.3.2

    library(SPIAT)

# 1 Cellular neighborhood

The aggregation of cells can result in ‘cellular neighbourhoods’. A neighbourhood is defined as a group of cells that cluster together. These can be homotypic, containing cells of a single class (e.g. immune cells), or heterotypic (e.g. a mixture of tumour and immune cells).

Function `identify_neighborhoods()` identifies cellular neighbourhoods. Users can select a subset of cell types of interest if desired. SPIAT includes three algorithms for the detection of neighbourhoods.

- Hierarchical Clustering algorithm: Euclidean distances between cells are calculated, and pairs of cells with a distance less than a specified radius are considered to be ‘interacting’, with the rest being ‘non-interacting’. Hierarchical clustering is then used to separate the clusters. Larger radii will result in the merging of individual clusters.
- dbscan
- phenograph

For Hierarchical Clustering algorithm and dbscan, users need to specify a radius that defines the distance for an interaction. We suggest users to test different radii and select the one that generates intuitive clusters upon visualisation. Cells not assigned to clusters are assigned as `Cluster_NA` in the output table. The argument `min_neighborhood_size` specifies the threshold of a neighborhood size to be considered as a neighborhood. Smaller neighbourhoods will be outputted, but will not be assigned a number.

Rphenograph uses the number of nearest neighbours to detect clusters. This number should be specified by `min_neighborhood_size` argument. We also encourage users to test different values.

For this part of the tutorial, we will use the image `image_no_markers` simulated with the `spaSim` package. This image contains “Tumour”, “Immune”, “Immune1” and “Immune2” cells without marker intensities.

    data("image_no_markers")

    plot_cell_categories(
      image_no_markers, c("Tumour", "Immune","Immune1","Immune2","Others"),
      c("red","blue","darkgreen", "brown","lightgray"), "Cell.Type")

Users are recommended to test out different radii and then visualise the clustering results. To aid in this process, users can use the `average_minimum_distance()` function, which calculates the average minimum distance between all cells in an image, and can be used as a starting point.

    average_minimum_distance(image_no_markers)

    ## [1] 17.01336

We then identify the cellular neighbourhoods using our hierarchical algorithm with a radius of 50, and with a minimum neighbourhood size of 100. Cells assigned to neighbourhoods smaller than 100 will be assigned to the “Cluster_NA” neighbourhood.

    clusters <- identify_neighborhoods(
      image_no_markers, method = "hierarchical", min_neighborhood_size = 100,
      cell_types_of_interest = c("Immune", "Immune1", "Immune2"), radius = 50,
      feature_colname = "Cell.Type")

This plot shows clusters of “Immune”, “Immune1” and “Immune2” cells. Each number and colour corresponds to a distinct cluster. Black cells correspond to ‘free’, un-clustered cells.

We can visualise the cell composition of neighborhoods. To do this, we can use `composition_of_neighborhoods()` to obtain the percentages of cells with a specific marker within each neighborhood and the number of cells in the neighborhood.

In this example we select cellular neighbourhoods with at least 5 cells.

    neighorhoods_vis <-
      composition_of_neighborhoods(clusters, feature_colname = "Cell.Type")
    neighorhoods_vis <-
      neighorhoods_vis[neighorhoods_vis$Total_number_of_cells >=5,]

Finally, we can use `plot_composition_heatmap()` to produce a heatmap showing the marker percentages within each cluster, which can be used to classify the derived neighbourhoods.

    plot_composition_heatmap(neighorhoods_vis, feature_colname="Cell.Type")

This plot shows that Cluster_1 and Cluster_2 contain all three types of immune cells. Cluster_3 does not have Immune1 cells. Cluster_1 and Cluster_2 are more similar to the free cells (cells not assigned to clusters) in their composition than Cluster_3.

# 2 Average Nearest Neighbour Index (ANNI)

We can test for the presence of neighbourhoods using ANNI. We can calculate the ANNI with the function `average_nearest_neighbor_index()`, which takes one cell type of interest (e.g. `Cluster_1` under `Neighborhood` column of `clusters` object) or a combinations of cell types (e.g. `Immune1` and `Immune2` cells under `Cell.Type` column of `image_no_markers` object) and outputs whether there is a clear neighbourhood (clustered) or unclear (dispersed/random), along with a P value for the estimate.

Here show the examples for both one cell type and multiple cell types.

    average_nearest_neighbor_index(clusters, reference_celltypes=c("Cluster_1"),
                                   feature_colname="Neighborhood", p_val = 0.05)

    ## $ANN_index
    ## [1] 0.4696608
    ##
    ## $pattern
    ## [1] "Clustered"
    ##
    ## $`p-value`
    ## [1] 2.623132e-68

    average_nearest_neighbor_index(
      image_no_markers, reference_celltypes=c("Immune", "Immune1" , "Immune2"),
      feature_colname="Cell.Type", p_val = 0.05)

    ## $ANN_index
    ## [1] 0.9968575
    ##
    ## $pattern
    ## [1] "Random"
    ##
    ## $`p-value`
    ## [1] 0.4000806

`p_val` is the cutoff to determine if a pattern is significant or not. If the p value of ANNI is larger than the threshold, the pattern will be “Random”. Although we give a default p value cutoff of 5e-6, we suggest the users to define their own cutoff based on the images and how they define the patterns “Clustered” and “Dispersed”.

# 3 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
- Spatial heterogeneity
- Tissue structure

# 4 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           htmltools_0.5.5
    ##  [17] S4Arrays_1.1.4            Rhdf5lib_1.23.0
    ##  [19] SparseArray_1.1.6         rhdf5_2.45.0
    ##  [21] sass_0.4.6                pracma_2.4.2
    ##  [23] bslib_0.4.2               mmand_1.6.3
    ##  [25] plyr_1.8.8                cachem_1.0.8
    ##  [27] lifecycle_1.0.3           iterators_1.0.14
    ##  [29] pkgconfig_2.0.3           Matrix_1.5-4.1
    ##  [31] R6_2.5.1                  fastmap_1.1.1
    ##  [33] clue_0.3-64               GenomeInfoDbData_1.2.10
    ##  [35] digest_0.6.31             colorspace_2.1-0
    ##  [37] tensor_1.5                dqrng_0.3.0
    ##  [39] beachmat_2.17.2           labeling_0.4.2
    ##  [41] fansi_1.0.4               spatstat.sparse_3.0-1
    ##  [43] polyclip_1.10-4           abind_1.4-5
    ##  [45] compiler_4.3.0            bit64_4.0.5
    ##  [47] withr_2.5.0               doParallel_1.0.17
    ##  [49] BiocParallel_1.35.2       apcluster_1.4.10
    ##  [51] highr_0.10                HDF5Array_1.29.3
    ##  [53] R.utils_2.12.2            DelayedArray_0.27.4
    ##  [55] rjson_0.2.21              gtools_3.9.4
    ##  [57] tools_4.3.0               goftest_1.2-3
    ##  [59] R.oo_1.25.0               glue_1.6.2
    ##  [61] dbscan_1.1-11             nlme_3.1-162
    ##  [63] rhdf5filters_1.13.2       grid_4.3.0
    ##  [65] cluster_2.1.4             reshape2_1.4.4
    ##  [67] generics_0.1.3            gtable_0.3.3
    ##  [69] spatstat.data_3.0-1       tzdb_0.4.0
    ##  [71] R.methodsS3_1.8.2         utf8_1.2.3
    ##  [73] XVector_0.41.1            spatstat.geom_3.2-1
    ##  [75] ggrepel_0.9.3             RANN_2.6.1
    ##  [77] foreach_1.5.2             pillar_1.9.0
    ##  [79] stringr_1.5.0             vroom_1.6.3
    ##  [81] limma_3.57.1              circlize_0.4.15
    ##  [83] dplyr_1.1.2               lattice_0.21-8
    ##  [85] bit_4.0.5                 deldir_1.0-9
    ##  [87] tidyselect_1.2.0          ComplexHeatmap_2.17.0
    ##  [89] locfit_1.5-9.7            scuttle_1.11.0
    ##  [91] knitr_1.42                gridExtra_2.3
    ##  [93] bookdown_0.34             edgeR_3.43.2
    ##  [95] xfun_0.39                 dittoSeq_1.13.1
    ##  [97] DropletUtils_1.21.0       pheatmap_1.0.12
    ##  [99] stringi_1.7.12            yaml_2.3.7
    ## [101] evaluate_0.21             codetools_0.2-19
    ## [103] archive_1.1.5             tibble_3.2.1
    ## [105] BiocManager_1.30.20       cli_3.6.1
    ## [107] munsell_0.5.0             jquerylib_0.1.4
    ## [109] Rcpp_1.0.10               spatstat.random_3.1-5
    ## [111] png_0.1-8                 parallel_4.3.0
    ## [113] ggplot2_3.4.2             sparseMatrixStats_1.13.0
    ## [115] bitops_1.0-7              viridisLite_0.4.2
    ## [117] scales_1.2.1              ggridges_0.5.4
    ## [119] crayon_1.5.2              GetoptLong_1.0.5
    ## [121] rlang_1.1.1               cowplot_1.1.1

# 5 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.