Last updated: 2022-07-09

Checks: 7 0

Knit directory: BASS-analysis/

This reproducible R Markdown analysis was created with workflowr (version 1.7.0). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(0) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 8acc73b. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


working directory clean

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/about.Rmd) and HTML (docs/about.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd 8acc73b zhengli09 2022-07-09 Update introduction page
html 303b575 zhengli09 2022-06-12 Build site.
Rmd 829d10c zhengli09 2022-06-12 Update real data analysis
html 7d4801a zhengli09 2022-06-07 Build site.
Rmd 6a631f8 zhengli09 2022-06-07 Update software introduction and tutorial
html 182beeb zhengli09 2022-03-10 Build site.
Rmd 34e84d6 zhengli09 2022-03-10 Add software tutorial and multi-sample simulation
html 9a68511 zhengli09 2022-02-27 Build site.
Rmd 4ec8df1 zhengli09 2022-02-27 Publish the introduction, simulation analysis and STARmap analysis
html b2c476b zhengli09 2022-02-06 Build site.
html a6097f4 zhengli09 2022-02-06 Build site.
Rmd 9f8756a zhengli09 2022-02-06 Start workflowr project.

Introduction

In this tutorial, we introduce the workflow and core functions of BASS to help you get familiar with the BASS package and start analyzing your own datasets. Please check the Real data analyses sections for examples on how we analyze spatial transcriptomic datasets.

Installation

BASS is implemented as an R (>= 4.0.3) package with underlying efficient C++ code interfaced through Rcpp and RcppArmadillo. BASS depends on a few other R packages that include GIGrvg, Matrix, harmony, label.switching, mclust, Rcpp, RcppArmadillo, RcppDist, SPARK, scran, and scater. Please refer to the package DESCRIPTION file for details. Dependent packages are supposed to be automatically installed while installing BASS. Install the BASS R package maintained in github through the devtools package.

if(!require(devtools))
  install.packages(devtools)
devtools::install_github("zhengli09/BASS")
library(BASS)

Workflow

Find the data here.

load("data/starmap_mpfc.RData") # starmap_cnts, starmap_info

Step 1: create a BASS object

To facilitate all steps of the spatial transcriptomic analysis, we wrap up the raw data, processed data, model hyper-parameters, MCMC controlling parameters, and model results into an S4 object (BASS-class). Check details of the BASS-class object by typing help("BASS-class"). Create a BASS object to start your analysis with the function createBASSObject. There are four required arguments: an L-list of gene expression count matrices for L tissue sections (X), an L-list of spatial coordinates matrices for L tissue sections (xy), the number of cell types (C) and the number of spatial domains (R). Check the simulation section of our paper for an evaluation of the influence of the specified number of cell types/spatial domains on the performance of all methods, and the discussion section of our paper for a practical guideline on how to select the two hyper-parameters when the truths are unclear. In addition, when the purpose of the analysis is solely to detect spatial domains, C can be specified to be a relatively large number (e.g. C = 20) while exploring R. This ensures that the heterogeneity in gene expression can be fully accounted. By default, we infer the spatial interaction parameter \(\beta\) based on the data at hand by specifying beta_method = "SW". However, if you have already had a good sense about the value of \(\beta\) (usually between 1 and 2), you can fix this parameter to the value specified by beta and set beta_method = "fix". Check the documentation of createBASSObject for further details.

Notes:
The BASS software currently implements a stopping rule to automatically determine the number of MCMC samples required for inferring \(\beta\). In particular, we calculate the mean of the sampled \(\beta\) in every 100 iterations and stop sampling if the difference of the consecutive two means is below a certain threshold (tol = 0.001 by default). Such stopping rule can help improve the computational efficiency and works well in almost all cases. In cases where the default number of MCMC iterations (2000) is not sufficient to reach the stopping threshold, we have incorporated a warning message into the software to encourage users to manually inspect the trace plot of \(\beta\) to determine if a larger number of burn-in iterations is needed. Check the supplementary figure of our paper for examples of well-behaved trace plots.

# gene expression count data
cnts <- starmap_cnts
# spatial coordinates
xy <- lapply(starmap_info, function(info.i){
  as.matrix(info.i[, c("x", "y")])
})
BASS <- createBASSObject(cnts, xy, C = 15, R = 4, beta_method = "SW")
***************************************
  INPUT INFO:
    - Number of tissue sections: 3 
    - Number of cells/spots: 1049 1053 1088 
    - Number of genes: 166 
    - Potts interaction parameter estimation method: SW 
      - Estimate Potts interaction parameter with SW algorithm
  To list all hyper-parameters, Type listAllHyper(BASS_object)
***************************************

You can check all the hyper-parameters that BASS uses with the function listAllHyper.

listAllHyper(BASS)
***************************************
  Please refer to the paper for details of the paramters
  ALL HYPER-PARAMETERS:
    - Number of cell types C: 15
    - Number of spatial domains R: 4
    - Initialization method: kmeans
    - Scale matrix of the inverse-Wishart prior Psi0: 1I
    - Degrees of freedom of the inverse-Wishart prior n0: 1
    - Number of MCMC burn-in iterations: 2000
    - Number of MCMC posterior samples: 5000
    - Potts interaction parameter estimation approach: SW
    - Number of burn-in interations in Potts sampling: 10
    - Number of Potts samples to approximate the partition ratio: 10
    - Step size of a uniform random walk: 0.1
    - Threshold of convergence for beta: 0.001
    - Concentration parameter of the Dirichlet prior alpha0: 1
    - Minimum number of neighbors for each cell/spot based on the Euclidean distance: 4
***************************************

Step 2: pre-process the gene expression data

We pre-process the raw gene expression data stored at the BASS@X slot and store the processed data at the BASS@X_run slot for running the following BASS algorithm. We have provided a function BASS.preprocess to automate the pre-processing steps, where we combine cells/spots across all L tissue sections, conduct library size normalization followed by a log2-transformation (after adding a pseudo-count of 1), select feature genes, perform dimension reduction with PCA on the normalized expression matrix to extract J low-dimensional expression features, and perform batch effect adjustment with Harmony to align expression data from different tissue sections. Users can also pre-process the gene expression data by themselves and store the processed data to the BASS@X_run slot. Check the documentation of BASS.preprocess for further details and various other controls.

BASS <- BASS.preprocess(BASS)

Step 3: run the BASS algorithm

Run the Gibbs sampling algorithm in combination with the Metropolis-Hastings algorithm to sample all the parameters specified in the BASS model. Posterior samples of all the parameters are stored in the BASS@samples slot and you can find a detailed description of what has been stored in BASS@samples by typing help("BASS-class"). Check the documentation of BASS.run for further details.

BASS <- BASS.run(BASS)

Step 4: post-process the posterior sampling results

Post-process the posterior sampling results with the function BASS.postprocess. There, we address the label switching issue associated with the sampling of cell type labels and spatial domain labels based on the iterative version 1 of the equivalence class representation (ECR) algorithm implemented in the label.switching package. In addition, we summarize posterior samples and obtain final estimates of cell type labels, spatial domain labels, and cell type composition in each spatial domain. The resulting estimates are stored in the BASS@results slot. Check the documentation of BASS.postprocess for further details.

Notes:
ECR-1 algorithm can be computationally intense when the sample size, number of posterior samples, specified number of cell types, or specified number of spatial domains is large. We provide the option, adjustLS = FALSE, to directly obtain final estimates of the cell type labels and spatial domain labels as the mode of their posterior samples without adjusting for label switching. Such approach can help improve the computational efficiency and the resulting estimates are reasonably good.

BASS <- BASS.postprocess(BASS)

sessionInfo()
R version 4.2.0 (2022-04-22)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.5 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/openblas/libblas.so.3
LAPACK: /usr/lib/x86_64-linux-gnu/libopenblasp-r0.2.20.so

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] BASS_1.1.0      GIGrvg_0.5      workflowr_1.7.0

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.8.3     bslib_0.3.1      compiler_4.2.0   pillar_1.7.0    
 [5] later_1.1.0.1    git2r_0.28.0     jquerylib_0.1.4  tools_4.2.0     
 [9] getPass_0.2-2    mclust_5.4.9     digest_0.6.29    jsonlite_1.8.0  
[13] evaluate_0.15    tibble_3.1.6     lifecycle_1.0.1  pkgconfig_2.0.3 
[17] rlang_1.0.1      cli_3.2.0        rstudioapi_0.13  yaml_2.3.5      
[21] xfun_0.29        fastmap_1.1.0    httr_1.4.2       stringr_1.4.0   
[25] knitr_1.37       sass_0.4.1       fs_1.5.2         vctrs_0.3.8     
[29] rprojroot_2.0.2  glue_1.6.2       R6_2.5.1         processx_3.5.2  
[33] fansi_1.0.2      rmarkdown_2.12.1 callr_3.7.0      magrittr_2.0.2  
[37] whisker_0.4      ps_1.6.0         promises_1.1.1   htmltools_0.5.2 
[41] ellipsis_0.3.2   httpuv_1.5.4     utf8_1.2.2       stringi_1.7.6   
[45] crayon_1.5.0