# Spatial transcriptomics cluster analysis with SpatialCPie

# Notice to users using OSX with R-devel

SpatialCPie depends on the ggiraph package, for which their is no r-devel version available at the moment. This means that SpatialCPie will not work on OSX with R-devel.

# Introduction

SpatialCPie is an R package designed to facilitate cluster evaluation for Spatial Transcriptomics (ST) data by providing intuitive visualizations that display the relationship between clusters in order to guide the user during cluster identification, selection and further downstream applications

# Usage example

    library(SpatialCPie)
    set.seed(42)

## Input data

In this example, we will use a downsampled dataset from an experiment on the human heart. We begin by loading the count data1:

    counts <- read.table(
        system.file("extdata", "counts.tsv", package = "SpatialCPie"),
        sep = "\t",
        check.names = FALSE
    )
    counts[1:5, 1:5]
    # >        3x34  3x30  3x31  3x32  3x33
    # > ACTB  2.511 2.116 2.910 3.792 2.432
    # > CD74  1.744 2.323 1.666 3.061 0.000
    # > CFL1  0.000 2.116 1.666 1.909 2.432
    # > CST3  3.009 2.664 0.000 3.061 2.925
    # > ERBB2 1.744 3.461 0.000 3.473 3.584

To overlay the data on the tissue, we also need to load the tissue image and its corresponding spot data2, which specifies the pixel coordinates of each spot:

    tissue <- jpeg::readJPEG(
        system.file("extdata", "he_image.jpg", package = "SpatialCPie")
    )
    spots <- parseSpotFile(
        system.file("extdata", "spot_data.tsv", package = "SpatialCPie")
    )
    head(spots)
    # >             x        y
    # > 11x9 149.3096 119.4788
    # > 12x9 166.1704 120.5682
    # > 13x9 180.5411 120.4645
    # > 14x9 195.2749 120.3607
    # > 15x9 209.6456 120.3607
    # > 16x9 225.3132 120.9314

## Preprocessing

Typically, it’s good to conduct some data filtering prior to the analysis: This could include removing spots that are outside of the tissue or removing spots or genes that have a low number of reads.

Since the spot file only contains the spots that are under the tissue, we can use it to subset the counts:

    counts <- counts[, which(colnames(counts) %in% rownames(spots))]

Let’s also remove all spots and genes that have less than 20 reads in total:

    repeat {
        d <- dim(counts)
        counts <- counts[rowSums(counts) >= 20, colSums(counts) >= 20]
        if (all(dim(counts) == d)) {
            break
        }
    }

Our data has already been normalized. If you are using raw count data, it is usually a good idea to normalize it before proceeding. We have found `SCTransform` in the Seurat package to work well for Spatial Transcriptomics data.

## Computing cluster assignments

The cluster assignments will be calculated during the loading of the gadget. The cluster assignments are labels assigned to each spot over different cluster resolutions, where we use the terminology “(cluster) resolution k” to refer to a partitioning of the spots into \(k\) clusters.

By default, clustering is performed with `base::kmeans` at resolutions `2:4`. The arguments `resolutions` and `assignmentFunction` to `runCPie` can be used to customize these defaults. For example, to instead cluster over resolutions 3 and 5 with `cluster::pam`, call `runCPie` as follows:

    runCPie(
        counts,
        resolutions = c(3, 5),
        assignmentFunction = function(k, x) cluster::pam(x, k = k)$clustering
    )

Use `?runCPie` for a complete list of function options.

## Visualization

We are now ready to use the gadget to visualize the data:

    result <- runCPie(
        counts,
        image = tissue,
        spotCoordinates = spots
    )
    # > Clustering resolution 2L
    # > Clustering resolution 3L
    # > Clustering resolution 4L
    # > Maximizing label overlap in consecutive resolutions
    # > Warning: `lift()` was deprecated in purrr 1.0.0.
    # > ℹ The deprecated feature was likely used in the SpatialCPie package.
    # >   Please report the issue to the authors.
    # > This warning is displayed once per session.
    # > Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
    # > generated.
    # > Warning: `invoke()` was deprecated in purrr 1.0.0.
    # > ℹ Please use `exec()` instead.
    # > ℹ The deprecated feature was likely used in the SpatialCPie package.
    # >   Please report the issue to the authors.
    # > This warning is displayed once per session.
    # > Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
    # > generated.
    # > Scoring spot-cluster affinity
    # > Warning: Use of .data in tidyselect expressions was deprecated in tidyselect 1.2.0.
    # > ℹ Please use `"spot"` instead of `.data$spot`
    # > This warning is displayed once per session.
    # > Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
    # > generated.
    # > Warning: Use of .data in tidyselect expressions was deprecated in tidyselect 1.2.0.
    # > ℹ Please use `"name"` instead of `.data$name`
    # > This warning is displayed once per session.
    # > Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
    # > generated.
    # > Warning: Use of .data in tidyselect expressions was deprecated in tidyselect 1.2.0.
    # > ℹ Please use `"score"` instead of `.data$score`
    # > This warning is displayed once per session.
    # > Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
    # > generated.
    # > Warning: `aes_string()` was deprecated in ggplot2 3.0.0.
    # > ℹ Please use tidy evaluation idioms with `aes()`.
    # > ℹ See also `vignette("ggplot2-in-packages")` for more information.
    # > ℹ The deprecated feature was likely used in the SpatialCPie package.
    # >   Please report the issue to the authors.
    # > This warning is displayed once per session.
    # > Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
    # > generated.
    # > Warning: `aes_()` was deprecated in ggplot2 3.0.0.
    # > ℹ Please use tidy evaluation idioms with `aes()`
    # > ℹ The deprecated feature was likely used in the SpatialCPie package.
    # >   Please report the issue to the authors.
    # > This warning is displayed once per session.
    # > Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
    # > generated.
    # > Warning: The `<scale>` argument of `guides()` cannot be `FALSE`. Use "none" instead as
    # > of ggplot2 3.3.4.
    # > ℹ The deprecated feature was likely used in the SpatialCPie package.
    # >   Please report the issue to the authors.
    # > This warning is displayed once per session.
    # > Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
    # > generated.

This opens up the gadget window, which has two main elements: the cluster graph and the spatial array plots. The cluster plot is interactive and by selecting rows of nodes, the corresponding spatial array plots are also displayed. These can be viewed by scrolling down. The information contained in these plots will be discussed in the next section. There are a number of parameters that can be changed within the gadget which affects the visual representation.

To exit the gadget, press the “Done” button. The plots in the gadget and the cluster assignments are stored in the output object, which has the following structure:

    str(result, max.level = 1)
    # > List of 3
    # >  $ clusters    :'data.frame':   2400 obs. of  3 variables:
    # >  $ clusterGraph: <ggplot2::ggplot>
    # >   ..@ data       : list()
    # >  .. .. - attr(*, "class")= chr "waiver"
    # >   ..@ layers     :List of 4
    # >   ..@ scales     :Classes 'ScalesList', 'ggproto', 'gg' <ggproto object: Class ScalesList, gg>
    # >     add: function
    # >     add_defaults: function
    # >     add_missing: function
    # >     backtransform_df: function
    # >     clone: function
    # >     find: function
    # >     get_scales: function
    # >     has_scale: function
    # >     input: function
    # >     map_df: function
    # >     n: function
    # >     non_position_scales: function
    # >     scales: list
    # >     set_palettes: function
    # >     train_df: function
    # >     transform_df: function
    # >     super:  <ggproto object: Class ScalesList, gg>
    # >   ..@ guides     :Classes 'Guides', 'ggproto', 'gg' <ggproto object: Class Guides, gg>
    # >     add: function
    # >     assemble: function
    # >     build: function
    # >     draw: function
    # >     get_custom: function
    # >     get_guide: function
    # >     get_params: function
    # >     get_position: function
    # >     guides: list
    # >     merge: function
    # >     missing: <ggproto object: Class GuideNone, Guide, gg>
    # >         add_title: function
    # >         arrange_layout: function
    # >         assemble_drawing: function
    # >         available_aes: any
    # >         build_decor: function
    # >         build_labels: function
    # >         build_ticks: function
    # >         build_title: function
    # >         draw: function
    # >         draw_early_exit: function
    # >         elements: list
    # >         extract_decor: function
    # >         extract_key: function
    # >         extract_params: function
    # >         get_layer_key: function
    # >         hashables: list
    # >         measure_grobs: function
    # >         merge: function
    # >         override_elements: function
    # >         params: list
    # >         process_layers: function
    # >         setup_elements: function
    # >         setup_params: function
    # >         train: function
    # >         transform: function
    # >         super:  <ggproto object: Class GuideNone, Guide, gg>
    # >     package_box: function
    # >     print: function
    # >     process_layers: function
    # >     setup: function
    # >     subset_guides: function
    # >     train: function
    # >     update_params: function
    # >     super:  <ggproto object: Class Guides, gg>
    # >   ..@ mapping    : <ggplot2::mapping>  Named list()
    # >   ..@ theme      : <theme> List of 144
    # >  .. .. $ line                            : <ggplot2::element_line>
    # >  .. ..  ..@ colour       : chr "black"
    # >  .. ..  ..@ linewidth    : num 0.5
    # >  .. ..  ..@ linetype     : num 1
    # >  .. ..  ..@ lineend      : chr "butt"
    # >  .. ..  ..@ linejoin     : chr "round"
    # >  .. ..  ..@ arrow        : logi FALSE
    # >  .. ..  ..@ arrow.fill   : chr "black"
    # >  .. ..  ..@ inherit.blank: logi TRUE
    # >  .. .. $ rect                            : <ggplot2::element_rect>
    # >  .. ..  ..@ fill         : chr "white"
    # >  .. ..  ..@ colour       : chr "black"
    # >  .. ..  ..@ linewidth    : num 0.5
    # >  .. ..  ..@ linetype     : num 1
    # >  .. ..  ..@ linejoin     : chr "round"
    # >  .. ..  ..@ inherit.blank: logi TRUE
    # >  .. .. $ text                            : <ggplot2::element_text>
    # >  .. ..  ..@ family       : chr ""
    # >  .. ..  ..@ face         : chr "plain"
    # >  .. ..  ..@ italic       : chr NA
    # >  .. ..  ..@ fontweight   : num NA
    # >  .. ..  ..@ fontwidth    : num NA
    # >  .. ..  ..@ colour       : chr "black"
    # >  .. ..  ..@ size         : num 11
    # >  .. ..  ..@ hjust        : num 0.5
    # >  .. ..  ..@ vjust        : num 0.5
    # >  .. ..  ..@ angle        : num 0
    # >  .. ..  ..@ lineheight   : num 0.9
    # >  .. ..  ..@ margin       : <ggplot2::margin> num [1:4] 0 0 0 0
    # >  .. ..  ..@ debug        : logi FALSE
    # >  .. ..  ..@ inherit.blank: logi TRUE
    # >  .. .. $ title                           : <ggplot2::element_text>
    # >  .. ..  ..@ family       : NULL
    # >  .. ..  ..@ face         : NULL
    # >  .. ..  ..@ italic       : chr NA
    # >  .. ..  ..@ fontweight   : num NA
    # >  .. ..  ..@ fontwidth    : num NA
    # >  .. ..  ..@ colour       : NULL
    # >  .. ..  ..@ size         : NULL
    # >  .. ..  ..@ hjust        : NULL
    # >  .. ..  ..@ vjust        : NULL
    # >  .. ..  ..@ angle        : NULL
    # >  .. ..  ..@ lineheight   : NULL
    # >  .. ..  ..@ margin       : NULL
    # >  .. ..  ..@ debug        : NULL
    # >  .. ..  ..@ inherit.blank: logi TRUE
    # >  .. .. $ point                           : <ggplot2::element_point>
    # >  .. ..  ..@ colour       : chr "black"
    # >  .. ..  ..@ shape        : num 19
    # >  .. ..  ..@ size         : num 1.5
    # >  .. ..  ..@ fill         : chr "white"
    # >  .. ..  ..@ stroke       : num 0.5
    # >  .. ..  ..@ inherit.blank: logi TRUE
    # >  .. .. $ polygon                         : <ggplot2::element_polygon>
    # >  .. ..  ..@ fill         : chr "white"
    # >  .. ..  ..@ colour       : chr "black"
    # >  .. ..  ..@ linewidth    : num 0.5
    # >  .. ..  ..@ linetype     : num 1
    # >  .. ..  ..@ linejoin     : chr "round"
    # >  .. ..  ..@ inherit.blank: logi TRUE
    # >  .. .. $ geom                            : <ggplot2::element_geom>
    # >  .. ..  ..@ ink        : chr "black"
    # >  .. ..  ..@ paper      : chr "white"
    # >  .. ..  ..@ accent     : chr "#3366FF"
    # >  .. ..  ..@ linewidth  : num 0.5
    # >  .. ..  ..@ borderwidth: num 0.5
    # >  .. ..  ..@ linetype   : int 1
    # >  .. ..  ..@ bordertype : int 1
    # >  .. ..  ..@ family     : chr ""
    # >  .. ..  ..@ fontsize   : num 3.87
    # >  .. ..  ..@ pointsize  : num 1.5
    # >  .. ..  ..@ pointshape : num 19
    # >  .. ..  ..@ colour     : NULL
    # >  .. ..  ..@ fill       : NULL
    # >  .. .. $ spacing                         : 'simpleUnit' num 5.5points
    # >  .. ..  ..- attr(*, "unit")= int 8
    # >  .. .. $ margins                         : <ggplot2::margin> num [1:4] 5.5 5.5 5.5 5.5
    # >  .. .. $ aspect.ratio                    : NULL
    # >  .. .. $ axis.title                      : NULL
    # >  .. .. $ axis.title.x                    : <ggplot2::element_blank>
    # >  .. .. $ axis.title.x.top                : <ggplot2::element_text>
    # >  .. ..  ..@ family       : NULL
    # >  .. ..  ..@ face         : NULL
    # >  .. ..  ..@ italic       : chr NA
    # >  .. ..  ..@ fontweight   : num NA
    # >  .. ..  ..@ fontwidth    : num NA
    # >  .. ..  ..@ colour       : NULL
    # >  .. ..  ..@ size         : NULL
    # >  .. ..  ..@ hjust        : NULL
    # >  .. ..  ..@ vjust        : num 0
    # >  .. ..  ..@ angle        : NULL
    # >  .. ..  ..@ lineheight   : NULL
    # >  .. ..  ..@ margin       : <ggplot2::margin> num [1:4] 0 0 2.75 0
    # >  .. ..  ..@ debug        : NULL
    # >  .. ..  ..@ inherit.blank: logi TRUE
    # >  .. .. $ axis.title.x.bottom             : NULL
    # >  .. .. $ axis.title.y                    : <ggplot2::element_blank>
    # >  .. .. $ axis.title.y.left               : NULL
    # >  .. .. $ axis.title.y.right              : <ggplot2::element_text>
    # >  .. ..  ..@ family       : NULL
    # >  .. ..  ..@ face         : NULL
    # >  .. ..  ..@ italic       : chr NA
    # >  .. ..  ..@ fontweight   : num NA
    # >  .. ..  ..@ fontwidth    : num NA
    # >  .. ..  ..@ colour       : NULL
    # >  .. ..  ..@ size         : NULL
    # >  .. ..  ..@ hjust        : NULL
    # >  .. ..  ..@ vjust        : num 1
    # >  .. ..  ..@ angle        : num -90
    # >  .. ..  ..@ lineheight   : NULL
    # >  .. ..  ..@ margin       : <ggplot2::margin> num [1:4] 0 0 0 2.75
    # >  .. ..  ..@ debug        : NULL
    # >  .. ..  ..@ inherit.blank: logi TRUE
    # >  .. .. $ axis.text                       : <ggplot2::element_text>
    # >  .. ..  ..@ family       : NULL
    # >  .. ..  ..@ face         : NULL
    # >  .. ..  ..@ italic       : chr NA
    # >  .. ..  ..@ fontweight   : num NA
    # >  .. ..  ..@ fontwidth    : num NA
    # >  .. ..  ..@ colour       : chr "#4D4D4DFF"
    # >  .. ..  ..@ size         : 'rel' num 0.8
    # >  .. ..  ..@ hjust        : NULL
    # >  .. ..  ..@ vjust        : NULL
    # >  .. ..  ..@ angle        : NULL
    # >  .. ..  ..@ lineheight   : NULL
    # >  .. ..  ..@ margin       : NULL
    # >  .. ..  ..@ debug        : NULL
    # >  .. ..  ..@ inherit.blank: logi TRUE
    # >  .. .. $ axis.text.x                     : <ggplot2::element_blank>
    # >  .. .. $ axis.text.x.top                 : <ggplot2::element_text>
    # >  .. ..  ..@ family       : NULL
    # >  .. ..  ..@ face         : NULL
    # >  .. ..  ..@ italic       : chr NA
    # >  .. ..  ..@ fontweight   : num NA
    # >  .. ..  ..@ fontwidth    : num NA
    # >  .. ..  ..@ colour       : NULL
    # >  .. ..  ..@ size         : NULL
    # >  .. ..  ..@ hjust        : NULL
    # >  .. ..  ..@ vjust        : num 0
    # >  .. ..  ..@ angle        : NULL
    # >  .. ..  ..@ lineheight   : NULL
    # >  .. ..  ..@ margin       : <ggplot2::margin> num [1:4] 0 0 2.2 0
    # >  .. ..  ..@ debug        : NULL
    # >  .. ..  ..@ inherit.blank: logi TRUE
    # >  .. .. $ axis.text.x.bottom              : NULL
    # >  .. .. $ axis.text.y                     : <ggplot2::element_blank>
    # >  .. .. $ axis.text.y.left                : NULL
    # >  .. .. $ axis.text.y.right               : <ggplot2::element_text>
    # >  .. ..  ..@ family       : NULL
    # >  .. ..  ..@ face         : NULL
    # >  .. ..  ..@ italic       : chr NA
    # >  .. ..  ..@ fontweight   : num NA
    # >  .. ..  ..@ fontwidth    : num NA
    # >  .. ..  ..@ colour       : NULL
    # >  .. ..  ..@ size         : NULL
    # >  .. ..  ..@ hjust        : num 0
    # >  .. ..  ..@ vjust        : NULL
    # >  .. ..  ..@ angle        : NULL
    # >  .. ..  ..@ lineheight   : NULL
    # >  .. ..  ..@ margin       : <ggplot2::margin> num [1:4] 0 0 0 2.2
    # >  .. ..  ..@ debug        : NULL
    # >  .. ..  ..@ inherit.blank: logi TRUE
    # >  .. .. $ axis.text.theta                 : NULL
    # >  .. .. $ axis.text.r                     : <ggplot2::element_text>
    # >  .. ..  ..@ family       : NULL
    # >  .. ..  ..@ face         : NULL
    # >  .. ..  ..@ italic       : chr NA
    # >  .. ..  ..@ fontweight   : num NA
    # >  .. ..  ..@ fontwidth    : num NA
    # >  .. ..  ..@ colour       : NULL
    # >  .. ..  ..@ size         : NULL
    # >  .. ..  ..@ hjust        : num 0.5
    # >  .. ..  ..@ vjust        : NULL
    # >  .. ..  ..@ angle        : NULL
    # >  .. ..  ..@ lineheight   : NULL
    # >  .. ..  ..@ margin       : <ggplot2::margin> num [1:4] 0 2.2 0 2.2
    # >  .. ..  ..@ debug        : NULL
    # >  .. ..  ..@ inherit.blank: logi TRUE
    # >  .. .. $ axis.ticks                      : <ggplot2::element_line>
    # >  .. ..  ..@ colour       : chr "#333333FF"
    # >  .. ..  ..@ linewidth    : NULL
    # >  .. ..  ..@ linetype     : NULL
    # >  .. ..  ..@ lineend      : NULL
    # >  .. ..  ..@ linejoin     : NULL
    # >  .. ..  ..@ arrow        : logi FALSE
    # >  .. ..  ..@ arrow.fill   : chr "#333333FF"
    # >  .. ..  ..@ inherit.blank: logi TRUE
    # >  .. .. $ axis.ticks.x                    : <ggplot2::element_blank>
    # >  .. .. $ axis.ticks.x.top                : NULL
    # >  .. .. $ axis.ticks.x.bottom             : NULL
    # >  .. .. $ axis.ticks.y                    : <ggplot2::element_blank>
    # >  .. .. $ axis.ticks.y.left               : NULL
    # >  .. .. $ axis.ticks.y.right              : NULL
    # >  .. .. $ axis.ticks.theta                : NULL
    # >  .. .. $ axis.ticks.r                    : NULL
    # >  .. .. $ axis.minor.ticks.x.top          : NULL
    # >  .. .. $ axis.minor.ticks.x.bottom       : NULL
    # >  .. .. $ axis.minor.ticks.y.left         : NULL
    # >  .. .. $ axis.minor.ticks.y.right        : NULL
    # >  .. .. $ axis.minor.ticks.theta          : NULL
    # >  .. .. $ axis.minor.ticks.r              : NULL
    # >  .. .. $ axis.ticks.length               : 'rel' num 0.5
    # >  .. .. $ axis.ticks.length.x             : NULL
    # >  .. .. $ axis.ticks.length.x.top         : NULL
    # >  .. .. $ axis.ticks.length.x.bottom      : NULL
    # >  .. .. $ axis.ticks.length.y             : NULL
    # >  .. .. $ axis.ticks.length.y.left        : NULL
    # >  .. .. $ axis.ticks.length.y.right       : NULL
    # >  .. .. $ axis.ticks.length.theta         : NULL
    # >  .. .. $ axis.ticks.length.r             : NULL
    # >  .. .. $ axis.minor.ticks.length         : 'rel' num 0.75
    # >  .. .. $ axis.minor.ticks.length.x       : NULL
    # >  .. .. $ axis.minor.ticks.length.x.top   : NULL
    # >  .. .. $ axis.minor.ticks.length.x.bottom: NULL
    # >  .. .. $ axis.minor.ticks.length.y       : NULL
    # >  .. .. $ axis.minor.ticks.length.y.left  : NULL
    # >  .. .. $ axis.minor.ticks.length.y.right : NULL
    # >  .. .. $ axis.minor.ticks.length.theta   : NULL
    # >  .. .. $ axis.minor.ticks.length.r       : NULL
    # >  .. .. $ axis.line                       : <ggplot2::element_blank>
    # >  .. .. $ axis.line.x                     : NULL
    # >  .. .. $ axis.line.x.top                 : NULL
    # >  .. .. $ axis.line.x.bottom              : NULL
    # >  .. .. $ axis.line.y                     : NULL
    # >  .. .. $ axis.line.y.left                : NULL
    # >  .. .. $ axis.line.y.right               : NULL
    # >  .. .. $ axis.line.theta                 : NULL
    # >  .. .. $ axis.line.r                     : NULL
    # >  .. .. $ legend.background               : <ggplot2::element_rect>
    # >  .. ..  ..@ fill         : NULL
    # >  .. ..  ..@ colour       : logi NA
    # >  .. ..  ..@ linewidth    : NULL
    # >  .. ..  ..@ linetype     : NULL
    # >  .. ..  ..@ linejoin     : NULL
    # >  .. ..  ..@ inherit.blank: logi TRUE
    # >  .. .. $ legend.margin                   : NULL
    # >  .. .. $ legend.spacing                  : 'rel' num 2
    # >  .. .. $ legend.spacing.x                : NULL
    # >  .. .. $ legend.spacing.y                : NULL
    # >  .. .. $ legend.key                      : NULL
    # >  .. .. $ legend.key.size                 : 'simpleUnit' num 1.2lines
    # >  .. ..  ..- attr(*, "unit")= int 3
    # >  .. .. $ legend.key.height               : NULL
    # >  .. .. $ legend.key.width                : NULL
    # >  .. .. $ legend.key.spacing              : NULL
    # >  .. .. $ legend.key.spacing.x            : NULL
    # >  .. .. $ legend.key.spacing.y            : NULL
    # >  .. .. $ legend.key.justification        : NULL
    # >  .. .. $ legend.frame                    : NULL
    # >  .. .. $ legend.ticks                    : NULL
    # >  .. .. $ legend.ticks.length             : 'rel' num 0.2
    # >  .. .. $ legend.axis.line                : NULL
    # >  .. .. $ legend.text                     : <ggplot2::element_text>
    # >  .. ..  ..@ family       : NULL
    # >  .. ..  ..@ face         : NULL
    # >  .. ..  ..@ italic       : chr NA
    # >  .. ..  ..@ fontweight   : num NA
    # >  .. ..  ..@ fontwidth    : num NA
    # >  .. ..  ..@ colour       : NULL
    # >  .. ..  ..@ size         : 'rel' num 0.8
    # >  .. ..  ..@ hjust        : NULL
    # >  .. ..  ..@ vjust        : NULL
    # >  .. ..  ..@ angle        : NULL
    # >  .. ..  ..@ lineheight   : NULL
    # >  .. ..  ..@ margin       : NULL
    # >  .. ..  ..@ debug        : NULL
    # >  .. ..  ..@ inherit.blank: logi TRUE
    # >  .. .. $ legend.text.position            : NULL
    # >  .. .. $ legend.title                    : <ggplot2::element_text>
    # >  .. ..  ..@ family       : NULL
    # >  .. ..  ..@ face         : NULL
    # >  .. ..  ..@ italic       : chr NA
    # >  .. ..  ..@ fontweight   : num NA
    # >  .. ..  ..@ fontwidth    : num NA
    # >  .. ..  ..@ colour       : NULL
    # >  .. ..  ..@ size         : NULL
    # >  .. ..  ..@ hjust        : num 0
    # >  .. ..  ..@ vjust        : NULL
    # >  .. ..  ..@ angle        : NULL
    # >  .. ..  ..@ lineheight   : NULL
    # >  .. ..  ..@ margin       : NULL
    # >  .. ..  ..@ debug        : NULL
    # >  .. ..  ..@ inherit.blank: logi TRUE
    # >  .. .. $ legend.title.position           : NULL
    # >  .. .. $ legend.position                 : chr "right"
    # >  .. .. $ legend.position.inside          : NULL
    # >  .. .. $ legend.direction                : NULL
    # >  .. .. $ legend.byrow                    : NULL
    # >  .. .. $ legend.justification            : chr "center"
    # >  .. .. $ legend.justification.top        : NULL
    # >  .. .. $ legend.justification.bottom     : NULL
    # >  .. .. $ legend.justification.left       : NULL
    # >  .. .. $ legend.justification.right      : NULL
    # >  .. .. $ legend.justification.inside     : NULL
    # >  .. ..  [list output truncated]
    # >  .. .. @ complete: logi TRUE
    # >  .. .. @ validate: logi TRUE
    # >   ..@ coordinates:Classes 'CoordCartesian', 'Coord', 'ggproto', 'gg' <ggproto object: Class CoordCartesian, Coord, gg>
    # >     aspect: function
    # >     backtransform_range: function
    # >     clip: on
    # >     default: TRUE
    # >     distance: function
    # >     draw_panel: function
    # >     expand: TRUE
    # >     is_free: function
    # >     is_linear: function
    # >     labels: function
    # >     limits: list
    # >     modify_scales: function
    # >     range: function
    # >     ratio: NULL
    # >     render_axis_h: function
    # >     render_axis_v: function
    # >     render_bg: function
    # >     render_fg: function
    # >     reverse: none
    # >     setup_data: function
    # >     setup_layout: function
    # >     setup_panel_guides: function
    # >     setup_panel_params: function
    # >     setup_params: function
    # >     train_panel_guides: function
    # >     transform: function
    # >     super:  <ggproto object: Class CoordCartesian, Coord, gg>
    # >   ..@ facet      :Classes 'FacetNull', 'Facet', 'ggproto', 'gg' <ggproto object: Class FacetNull, Facet, gg>
    # >     attach_axes: function
    # >     attach_strips: function
    # >     compute_layout: function
    # >     draw_back: function
    # >     draw_front: function
    # >     draw_labels: function
    # >     draw_panel_content: function
    # >     draw_panels: function
    # >     finish_data: function
    # >     format_strip_labels: function
    # >     init_gtable: function
    # >     init_scales: function
    # >     map_data: function
    # >     params: list
    # >     set_panel_size: function
    # >     setup_data: function
    # >     setup_panel_params: function
    # >     setup_params: function
    # >     shrink: TRUE
    # >     train_scales: function
    # >     vars: function
    # >     super:  <ggproto object: Class FacetNull, Facet, gg>
    # >   ..@ layout     :Classes 'Layout', 'ggproto', 'gg' <ggproto object: Class Layout, gg>
    # >     coord: NULL
    # >     coord_params: list
    # >     facet: NULL
    # >     facet_params: list
    # >     finish_data: function
    # >     get_scales: function
    # >     layout: NULL
    # >     map_position: function
    # >     panel_params: NULL
    # >     panel_scales_x: NULL
    # >     panel_scales_y: NULL
    # >     render: function
    # >     render_labels: function
    # >     reset_scales: function
    # >     resolve_label: function
    # >     setup: function
    # >     setup_panel_guides: function
    # >     setup_panel_params: function
    # >     train_position: function
    # >     super:  <ggproto object: Class Layout, gg>
    # >   ..@ labels     : <ggplot2::labels> List of 2
    # >  .. .. $ alpha : chr "Proportion"
    # >  .. .. $ colour: chr "Cluster"
    # >   ..@ meta       : list()
    # >   ..@ plot_env   :<environment: 0x55aec3ce7d20>
    # >  $ arrayPlot   :List of 4

### Cluster plot

    result$clusterGraph

The cluster graph is a visual representation of how the spatial features transition from clusters of lower resolution to clusters of higher resolution. The edge opacities show the proportion of spots that transition to or from a given cluster while node radii display the size of each cluster.

When launching the gadget, spots are relabeled so as to minimize the number of crossovers (label switches) between resolutions in the data. Moreover, cluster color labels are selected so that dissimilar clusters are farther away in color space.

### Spatial array plots

    result$arrayPlot$`4`

The spatial array plots show the spatial locations of the clusters. The pie chart proportions are based on the following scoring scheme.

#### Spot-based clustering

In the case of spot-based clustering (`margin = "spot"` in the call to `runCPie`, which is the default), the score for cluster \(k\) in spot \(s\) is computed as:

\[ \mbox{score}(s, k) = \mbox{exp}\left( - \mbox{RMSD}\left(x_s, \mbox{mean}({\{x_{s'}\}_{s' \in C(k)}})\right) \right), \]

where \(x_i\) is the gene expression vector of spot \(i\), \(C(k)\) is the set of spots in cluster \(k\), and \(\mbox{RMSD}(a, b)\) is the root-mean-square deviation between gene vectors \(a\) and \(b\).

#### Gene-based clustering

In the case of gene-based clustering (`margin = "gene"` in the call to `runCPie`), the score is computed as:

\[ \mbox{score}(s, k) = \mbox{mean}\left( {\{\tilde{x}_{sg}\}_{g \in C(k)}} \right), \]

where \(\tilde{x}_{sg}\) is a log-normalized relative count value for gene \(g\) in spot \(s\).

#### The score multiplier

The score can be tuned by a score multiplier, \(\lambda\), to either enhance or decrease the contrast between clusters. The final (visualized) score is an exponentiation of \(\mbox{score}\):

\[ \mbox{score'}(s, k) = \mbox{score}(s, k) ^ \lambda \]

Note that the definition implies that it is possible to (practically) hard-label the spots by setting \(\lambda\) to a high value. This follows since the relative score for the highest scoring cluster will tend towards \(1\) as \(\lambda\to\infty\). For example, setting \(\lambda=10.0\) yields

## Sub-clustering

After a “global” analysis of the entire tissue section, it is often interesting to sub-cluster parts of the tissue. This can be achieved via cluster selection in the gadget and subsequent sub-sampling of the clusters that the user wants to re-cluster further.

As a practical example, from the array plot above, we can see that clusters 1 and 4 in resolution 4 appear in mostly the same spatial areas and, from the cluster graph, we can also see that they are mostly derived from the same lower-resolution cluster. Therefore, it could be interesting to sub-cluster the spots assigned to these clusters:

    library(dplyr)
    subcluster <-
        result$clusters %>%
        filter(resolution == 4, cluster %in% c(1, 4)) %>%
        `$`("unit")
    head(subcluster)
    # > [1] "3x31"  "23x20" "30x15" "23x22" "23x23" "23x24"

    subclusterResult <- runCPie(
        counts = counts[, subcluster],
        image = tissue,
        spotCoordinates = spots
    )
    # > Clustering resolution 2L
    # > Clustering resolution 3L
    # > Clustering resolution 4L
    # > Maximizing label overlap in consecutive resolutions
    # > Scoring spot-cluster affinity
    subclusterResult$clusterGraph

The cluster graph indicates that we appear to pick up three different clusters of stromal cells, as there is a clear separation between the clusters up to and including resolution 3. In contrast, clusters in resolution 4 show a pattern of shared ancestry, indicating that cluster assignments are becoming more ambiguous.

    subclusterResult$arrayPlot$`3`

1. Generated by the ST pipeline↩︎

2. Generated by the ST spot detector.↩︎