R/05-Lun.R

Defines functions Lun_simulation Lun_estimation

Documented in Lun_estimation Lun_simulation

#' Estimate Parameters From Real Datasets by Lun
#'
#' This function is used to estimate useful parameters from a real dataset by
#' using `lunEstimate` function in Splatter package.
#'
#' @param ref_data A count matrix. Each row represents a gene and each column
#' represents a cell.
#' @param verbose Logical.
#' @param seed An integer of a random seed.
#' @importFrom splatter lunEstimate
#'
#' @return A list contains the estimated parameters and the results of execution
#' detection.
#' @export
#' @references
#' Zappia L, Phipson B, Oshlack A. Splatter: simulation of single-cell RNA sequencing data. Genome biology, 2017, 18(1): 1-15. https://doi.org/10.1186/s13059-017-1305-0
#'
#' Bioconductor URL: <https://bioconductor.org/packages/release/bioc/html/splatter.html>
#'
#' Github URL: <https://github.com/Oshlack/splatter>
#' @examples
#' \dontrun{
#' ref_data <- simmethods::data
#' estimate_result <- simmethods::Lun_estimation(ref_data = ref_data,
#'                                               verbose = TRUE,
#'                                               seed = 10)
#' estimate_result <- estimate_result[["estimate_result"]]
#' ## Check the class
#' class(estimate_result) == "LunParams"
#' }
#'
Lun_estimation <- function(ref_data,
                           verbose = FALSE,
                           seed
){
  ##############################################################################
  ####                               Check                                   ###
  ##############################################################################
  if(!is.matrix(ref_data)){
    ref_data <- as.matrix(ref_data)
  }
  ##############################################################################
  ####                            Estimation                                 ###
  ##############################################################################
  if(verbose){
    message("Estimating parameters using Lun")
  }
  # Seed
  set.seed(seed)
  # Estimation
  estimate_detection <- peakRAM::peakRAM(
    estimate_result <- splatter::lunEstimate(ref_data)
  )
  ##############################################################################
  ####                           Ouput                                       ###
  ##############################################################################
  estimate_output <- list(estimate_result = estimate_result,
                          estimate_detection = estimate_detection)
  return(estimate_output)
}


#' Simulate Datasets by Lun
#'
#' This function is used to simulate datasets from learned parameters by `lunSimulate`
#' function in Splatter package.
#'
#' @param parameters A object generated by [splatter::lunEstimate()]
#' @param other_prior A list with names of certain parameters. Some methods need
#' extra parameters to execute the estimation step, so you must input them. In
#' simulation step, the number of cells, genes, groups, batches, the percent of
#' DEGs are usually customed, so before simulating a dataset you must point it out.
#' See `Details` below for more information.
#' @param return_format A character. Alternatives choices: list, SingleCellExperiment,
#' Seurat, h5ad. If you select `h5ad`, you will get a path where the .h5ad file saves to.
#' @param verbose Logical. Whether to return messages or not.
#' @param seed A random seed.
#' @importFrom splatter lunSimulate
#' @export
#' @details
#' In addtion to simulate datasets with default parameters, users want to simulate
#' other kinds of datasets, e.g. a counts matrix with 2 or more cell groups. In
#' Lun, you can set extra parameters to simulate datasets.
#'
#' The customed parameters you can set are below:
#' 1. nCells. In Lun, you can not set nCells directly and should set groupCells instead. For example, if you want to simulate 1000 cells, you can type `other_prior = list(groupCells = 1000)`. If you type `other_prior = list(groupCells = c(500, 500))`, the simulated data will have two groups
#' 2. nGenes. You can directly set `other_prior = list(nGenes = 5000)` to simulate 5000 genes.
#' 3. nGroups. You can not directly set `other_prior = list(nGroups = 3)` to simulate 3 groups. Instead, you should set `other_prior = list(prob.group = c(0.2, 0.3, 0.5))` where the sum of group probabilities must equal to 1.
#' 4. de.prob. You can directly set `other_prior = list(de.prob = 0.2)` to simulate DEGs that account for 20 percent of all genes.
#' 5. prob.group. You can directly set `other_prior = list(prob.group = c(0.2, 0.3, 0.5))` to assign three proportions of cell groups. Note that the number of groups always equals to the length of the vector.
#' 6. fc.up.group. You can directly set `other_prior = list(fc.up.group = 2)` to specify the foldchange of up-regulated DEGs.
#' 7. fc.down.group. You can directly set `other_prior = list(fc.down.group = 0.5)` to specify the foldchange of down-regulated DEGs.
#'
#' For more customed parameters in Lun, please check [splatter::LunParams()].
#' @references
#' Zappia L, Phipson B, Oshlack A. Splatter: simulation of single-cell RNA sequencing data. Genome biology, 2017, 18(1): 1-15. <https://doi.org/10.1186/s13059-017-1305-0>
#'
#' Bioconductor URL: <https://bioconductor.org/packages/release/bioc/html/splatter.html>
#'
#' Github URL: <https://github.com/Oshlack/splatter>
#'
#' @examples
#' \dontrun{
#' # Load data
#' ref_data <- simmethods::data
#' # Estimate parameters
#' estimate_result <- simmethods::Lun_estimation(ref_data = ref_data,
#'                                               verbose = TRUE,
#'                                               seed = 10)
#'
#' # (1) Simulate 500 cells (Since we can not set nCells directly, so we can set
#' # groupCells (a numeric vector)) and 2000 genes
#' simulate_result <- simmethods::Lun_simulation(parameters = estimate_result[["estimate_result"]],
#'                                               other_prior = list(groupCells = 500,
#'                                                                  nGenes = 2000),
#'                                               return_format = "list",
#'                                               verbose = TRUE,
#'                                               seed = 111)
#' count_data <- simulate_result[["simulate_result"]][["count_data"]]
#' dim(count_data)
#'
#'
#' # (2) Simulate one group
#' simulate_result <- simmethods::Lun_simulation(parameters = estimate_result[["estimate_result"]],
#'                                               other_prior = NULL,
#'                                               return_format = "list",
#'                                               verbose = TRUE,
#'                                               seed = 111)
#' count_data <- simulate_result[["simulate_result"]][["count_data"]]
#' dim(count_data)
#'
#'
#' # (3) Simulate two groups (de.prob = 0.2)
#' simulate_result <- simmethods::Lun_simulation(parameters = estimate_result[["estimate_result"]],
#'                                               other_prior = list(prob.group = c(0.4, 0.6),
#'                                                                  de.prob = 0.2),
#'                                               return_format = "list",
#'                                               verbose = TRUE,
#'                                               seed = 111)
#' count_data <- simulate_result[["simulate_result"]][["count_data"]]
#' dim(count_data)
#' ## cell information
#' col_data <- simulate_result[["simulate_result"]][["col_meta"]]
#' table(col_data$group)
#' ## gene information
#' row_data <- simulate_result[["simulate_result"]][["row_meta"]]
#' ### The result of Lun contains the factors of different groups and uses can
#' ### calculate the fold change by division. For example, the DEFactors of A gene
#' ### in Group1 and Group2 are respectively 2 and 1, and the fold change of A gene
#' ### is 2/1=2 or 1/2=0.5.
#' fc_group1_to_group2 <- row_data$DEFacGroup2/row_data$DEFacGroup1
#' table(fc_group1_to_group2 != 1)[2]/4000 ## de.prob = 0.2
#' ### number of all DEGs
#' table(row_data$de_gene)[2]/4000 ## de.prob = 0.2
#'
#'
#' # (4) Simulate two groups (de.prob = 0.2, fc.up.group = 2, fc.down.group = 0.5)
#' simulate_result <- simmethods::Lun_simulation(parameters = estimate_result[["estimate_result"]],
#'                                               other_prior = list(prob.group = c(0.4, 0.6),
#'                                                                  de.prob = 0.2,
#'                                                                  fc.up.group = 2,
#'                                                                  fc.down.group = 0.5),
#'                                               return_format = "list",
#'                                               verbose = TRUE,
#'                                               seed = 111)
#' count_data <- simulate_result[["simulate_result"]][["count_data"]]
#' dim(count_data)
#' ## cell information
#' col_data <- simulate_result[["simulate_result"]][["col_meta"]]
#' table(col_data$group)
#' ## gene information
#' row_data <- simulate_result[["simulate_result"]][["row_meta"]]
#' ### The result of Lun contains the factors of different groups and uses can
#' ### calculate the fold change by division. For example, the DEFactors of A gene
#' ### in Group1 and Group2 are respectively 2 and 1, and the fold change of A gene
#' ### is 2/1=2 or 1/2=0.5.
#' fc_group1_to_group2 <- row_data$DEFacGroup2/row_data$DEFacGroup1
#' table(fc_group1_to_group2 != 1)[2]/4000 ## de.prob = 0.2
#' ### number of all DEGs
#' table(row_data$de_gene)[2]/4000 ## de.prob = 0.2
#' ### fc.up.group
#' max(row_data$DEFacGroup1)
#' ### fc.down.group
#' min(row_data$DEFacGroup1)
#' }
#'
Lun_simulation <- function(parameters,
                           other_prior = NULL,
                           return_format,
                           verbose = FALSE,
                           seed
){
  ##############################################################################
  ####                               Check                                   ###
  ##############################################################################
  assertthat::assert_that(class(parameters) == "LunParams")

  if(!is.null(other_prior)){
    parameters <- simutils::set_parameters(parameters = parameters,
                                           other_prior = other_prior,
                                           method = "Lun")
  }
  # prob.group
  if(!is.null(other_prior[["prob.group"]])){
    groupCells <- simutils::proportionate(number = parameters@nCells,
                                          result_sum_strict = parameters@nCells,
                                          prop = other_prior[["prob.group"]],
                                          prop_sum_strict = 1,
                                          digits = 0)
    parameters <- splatter::setParam(parameters,
                                     name = "groupCells",
                                     value = groupCells)
  }
  # de.prob
  if(!is.null(other_prior[["de.prob"]])){
    nGroups <- splatter::getParam(parameters, "nGroups")
    parameters <- splatter::setParam(parameters,
                                     name = "de.nGenes",
                                     value = round(other_prior[["de.prob"]]*parameters@nGenes/nGroups))
  }
  # fc.up.group
  if(!is.null(other_prior[["fc.up.group"]])){
    parameters <- splatter::setParam(parameters,
                                     name = "de.upFC",
                                     value = other_prior[["fc.up.group"]])
  }
  # fc.down.group
  if(!is.null(other_prior[["fc.down.group"]])){
    parameters <- splatter::setParam(parameters,
                                     name = "de.downFC",
                                     value = other_prior[["fc.down.group"]])
  }
  # Get params to check
  params_check <- splatter::getParams(parameters, c("nCells",
                                                    "nGenes",
                                                    "nGroups",
                                                    "de.nGenes",
                                                    "de.upFC",
                                                    "de.downFC"))

  # Return to users
  message(paste0("nCells: ", params_check[['nCells']]))
  message(paste0("nGenes: ", params_check[['nGenes']]))
  message(paste0("nGroups: ", params_check[['nGroups']]))
  message(paste0("de.prob: ", params_check[['de.nGenes']]/params_check[['nGenes']]*params_check[['nGroups']]))
  message(paste0("fc.up.group: ", params_check[['de.upFC']]))
  message(paste0("fc.down.group: ", params_check[['de.downFC']]))
  ##############################################################################
  ####                            Simulation                                 ###
  ##############################################################################
  if(verbose){
    message("Simulating datasets using Lun")
  }
  # Seed
  parameters <- splatter::setParam(parameters, name = "seed", value = seed)

  # Simulation
  simulate_detection <- peakRAM::peakRAM(
    simulate_result <- splatter::lunSimulate(parameters,
                                             verbose = verbose)
  )
  ##############################################################################
  ####                        Format Conversion                              ###
  ##############################################################################
  # counts
  counts <- as.matrix(SingleCellExperiment::counts(simulate_result))
  # col_data
  col_data <- as.data.frame(SummarizedExperiment::colData(simulate_result))
  if(params_check[['nGroups']] == 1){
    col_data[, 2] <- rep("Group1", ncol(col_data))
    colnames(col_data) <- c("cell_name", "group")
  }else{
    col_data <- col_data[, c("Cell", "Group")]
    colnames(col_data) <- c("cell_name", "group")
  }

  # row_data
  row_data <- as.data.frame(SummarizedExperiment::rowData(simulate_result))
  if(params_check[['nGroups']] == 1){
    row_data <- data.frame("gene_name" = row_data$Gene)
    rownames(row_data) <- row_data$gene_name
  }else{
    group_fac <- row_data[, grep(colnames(row_data), pattern = "^DEFac")]
    total_sum <- rowSums(group_fac)
    de_gene <- ifelse(total_sum == params_check[['nGroups']], "no", "yes")
    row_data[, 2] <- de_gene
    row_data <- row_data[, 1:2]
    row_data <- BiocGenerics::cbind(row_data, group_fac)
    colnames(row_data) <- c("gene_name", "de_gene", colnames(group_fac))
  }
  # Establish SingleCellExperiment
  simulate_result <- SingleCellExperiment::SingleCellExperiment(list(counts = counts),
                                                                colData = col_data,
                                                                rowData = row_data)
  simulate_result <- simutils::data_conversion(SCE_object = simulate_result,
                                               return_format = return_format)

  ##############################################################################
  ####                           Ouput                                       ###
  ##############################################################################
  simulate_output <- list(simulate_result = simulate_result,
                          simulate_detection = simulate_detection)
  return(simulate_output)
}
duohongrui/simmethods documentation built on June 17, 2024, 10:49 a.m.