R/BetaPrime.R

Defines functions BetaPrime

Documented in BetaPrime

#' (Weighted) MLE of Beta-Prime Distribution
#' 
#' Beta-Prime distribution is characterized by the following probability density function,
#' \deqn{f(x;\alpha,\beta) = \frac{x^{\alpha-1} (1+x)^{-\alpha-\beta}}{B(\alpha,\beta)}}
#' where the domain is \eqn{x \in [0,\infty)} with two shape parameters \eqn{\alpha, \beta > 0}. \eqn{B(\alpha,\beta)} is a Beta function.
#' 
#' @param x a length-\eqn{n} vector of values in \eqn{[0,\infty)}.
#' @param weight a length-\eqn{n} weight vector. If set as \code{NULL}, it gives an equal weight, leading to standard MLE.
#' 
#' @return a named list containing (weighted) MLE of \describe{
#' \item{alpha}{shape parameter \eqn{\alpha}.}
#' \item{beta}{ shape parameter \eqn{\beta}.}
#' }
#' 
#' @examples
#' #  generate data from Unif(0,1)
#' x = stats::runif(100)
#' 
#' #  fit unweighted
#' BetaPrime(x)
#' 
#' \dontrun{
#' # put random weights to see effect of weights
#' niter = 500
#' ndata = 200
#' 
#' # generate data as above and fit unweighted MLE
#' x    = stats::runif(ndata)
#' xmle = BetaPrime(x)
#' 
#' # iterate
#' vec.alpha = rep(0,niter)
#' vec.beta  = rep(0,niter)
#' for (i in 1:niter){
#'   # random weight
#'   ww = abs(stats::rnorm(ndata))
#' 
#'   MLE = BetaPrime(x, weight=ww)
#'   vec.alpha[i] = MLE$alpha
#'   vec.beta[i]  = MLE$beta
#'   if ((i%%10) == 0){
#'     print(paste0(" iteration ",i,"/",niter," complete.."))
#'   }
#' }
#' 
#' # distribution of weighted estimates + standard MLE
#' opar <- par(no.readonly=TRUE)
#' par(mfrow=c(1,2))
#' hist(vec.alpha, main="shape 'alpha'")
#' abline(v=xmle$alpha, lwd=3, col="red")
#' hist(vec.beta,  main="shape 'beta'")
#' abline(v=xmle$beta,  lwd=3, col="blue")
#' par(opar)
#' } 
#' 
#' @author Kisung You
#' @export
BetaPrime <- function(x, weight=NULL){
  #############################################
  # Preprocessing
  # inputs
  x      = handle_cts_nonneg("BetaPrime", x) # nonnegative real numbers
  nx     = length(x)
  weight = handle_weight("BetaPrime", weight, nx)
  maceps = 10*.Machine$double.eps
  
  #############################################
  # Optimize : DEoptim
  fopt.BetaPrime <- function(pars){
    # parameters
    alpha = pars[1]
    beta  = pars[2]
    # log-likelihood
    loglkd = ((alpha-1)*log(x) + (-alpha-beta)*log(1+x)) - base::lbeta(alpha,beta)
    # return
    return(-sum(loglkd*weight))
  }
  sol = DEoptim::DEoptim(fopt.BetaPrime, lower=c(maceps, maceps), upper=c(1e+5,1e+5), 
                         control=DEoptim::DEoptim.control(trace=FALSE))$optim$bestmem
  
  #############################################
  # Return
  output = list()
  output$alpha = as.double(sol[1])
  output$beta  = as.double(sol[2])
  return(output)
}
kyoustat/T4mle documentation built on March 26, 2020, 12:09 a.m.