R/solve.R

#' Solve initial value problem for Lotka-Volterra equations
#'
#' Use Euler's method to numerically integrate the Lotka-Volterra equations.
#'
#' @param params object of class "LotkaVolterraParams"
#' @param init_state object of class "LotkaVolterraState"
#' @param time_range upper limit of integration
#' @param step_size step size for linear approximations
#'
#' @return matrix
#' @export
solve <- function (params, init_state, time_range, step_size) {

  params_vec     <- mmbr::write_compact(params)
  init_state_vec <- mmbr::write_compact(init_state)

  change_equations <- function (time_point, state, parameters) {
    with(as.list(c(state, parameters)), {
      dx <- (alpha * x) - (beta * x * y)
      dy <- (gamma * beta * x * y) - (delta * y)
      return (list(c(x = dx, y = dy)))
    })
  }

  time_series <- deSolve::ode(
    init_state_vec,
    seq(0, time_range, by = step_size),
    change_equations,
    params_vec
  )

  # Un-compact column names of state variables x and y.
  colnames(time_series) <- c('time', 'prey_population', 'predator_population')

  return (time_series)
}
atmunr/mmbr documentation built on Oct. 6, 2020, 2:51 a.m.