R/constant_stage.R

#' Constant size mutation simulation.
#'
#' @param gland a gland object
#' @param n number of generations
#'
#' @return a gland object
#' @export
#'
#' @examples
#' gland <- gland_create(sample(c(0, 1), 10, TRUE), n_iter = 4)
#'
#' constant_stage(gland, 300)
constant_stage <- function(gland, n) {
  for (i in seq_len(n)) {
    gland$cells <- mutation(gland$cells, gland$mutation_chance)
  }
  gland
}

#' Explosion of cell
#'
#' @param gland a gland object
#' @param target number of cells required in the end gland
#' @param simple logical, determines method of explosion
#'
#' If simple is set to TRUE, then the explosion step is being done by duplicating
#' the cells to match the desired output size. If it is set to FALSE, then cell
#' splitting in repeated until desired output size is reached.
#'
#' @return a gland object
#' @export
#'
#' @examples
#' gland <- gland_create(sample(c(0, 1), 10, TRUE), n_iter = 4)
#'
#' explosion(gland, simple = TRUE)
#' explosion(gland, simple = FALSE)
explosion <- function(gland, target = 8192, simple = TRUE) {
  if (simple) {
    gland$cells <- gland$cells[rep(seq_len(nrow(gland$cells)),
                                   each = target / nrow(gland$cells)), ]
    return(gland)
  }
  n_iter <- log2(target) - floor(log2(nrow(gland$cells)))

  for (i in seq_len(n_iter)) {
    gland$cells <- cell_split(gland$cells, change = gland$mutation_chance)
  }

  gland$cells <- gland$cells[seq_len(target), ]
  gland
}


#' Combined phase 3 simulation
#'
#' This function will calculate how many generations is happening in the
#' explosion phase and adjust the constant phase accordingly.
#'
#' @param gland a gland object
#' @param n number of generations in phase 3
#' @param target number of cells required in the end gland
#'
#' @return a gland object
#' @export
#'
#' @examples
#' gland <- gland_create(sample(c(0, 1), 10, TRUE), n_iter = 4)
#' explosion_stage(gland, 300)
explosion_stage <- function(gland, n, target = 8192) {
  n_iter <- log2(target) - floor(log2(nrow(gland$cells)))
  if(n - n_iter < 0) stop(paste0("`n` isn't big enought for explosion to reach max size.\n",
                                 "`n` was set to be ", n, " but must be at least ", n_iter))
  gland <- constant_stage(gland, n - n_iter)
  explosion(gland)
}
EmilHvitfeldt/cell documentation built on May 5, 2019, 7:03 p.m.