R/InvGamma.R

Defines functions InvGamma

Documented in InvGamma

#' (Weighted) MLE of Inverse Gamma Distribution
#' 
#' Inverse Gamma distribution is characterized by the following probability density function,
#' \deqn{f(x;\alpha,\beta) = \frac{\beta^\alpha}{\Gamma(\alpha)} x^{-\alpha-1} \exp\left( -\frac{\beta}{x}\right)}
#' where the domain is \eqn{x \in (0,\infty)} with two parameters \eqn{\alpha > 0} for shape and \eqn{\beta > 0} for scale.
#' 
#' @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}{scale parameter \eqn{\beta}.}
#' }
#' 
#' @examples
#' #  generate data from exponential distribution
#' x = stats::rexp(100)
#' 
#' #  fit unweighted
#' InvGamma(x)
#' 
#' \dontrun{
#' # put random weights to see effect of weights
#' niter = 500
#' ndata = 200
#' 
#' # generate data as above and fit unweighted MLE
#' x    = stats::rexp(ndata)
#' xmle = InvGamma(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 = InvGamma(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="scale 'beta'")
#' abline(v=xmle$beta, lwd=3, col="blue")
#' par(opar)
#' } 
#' 
#' @author Kisung You
#' @export
InvGamma <- function(x, weight=NULL){
  #############################################
  # Preprocessing
  x      = handle_cts_pos("InvGamma", x) # nonnegative real numbers
  nx     = length(x)
  weight = handle_weight("InvGamma", weight, nx)
  maceps = 10*.Machine$double.eps
  
  #############################################
  # Optimize : DEoptim
  fopt.InvGamma <- function(pars){
    # parameters
    alpha = pars[1]
    beta  = pars[2]
    # log-likelihood
    term1 = alpha*log(beta) - base::lgamma(alpha)
    term2 = (-alpha-1)*log(x)
    term3 = -beta/x
    loglkd = term1+term2+term3
    # return
    return(-sum(loglkd*weight))
  }
  sol = DEoptim::DEoptim(fopt.InvGamma, 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.