R/Lomax.R

Defines functions Lomax

Documented in Lomax

#' (Weighted) MLE of Lomax Distribution
#' 
#' Lomax distribution, also called Pareto Type 2 distribution, is characterized by the following probability density function,
#' \deqn{f(x;\alpha,\lambda) = \frac{\alpha}{\lambda} \left[ 1 + \frac{x}{\lambda} \right]^{-(\alpha+1)}  }
#' where the domain is \eqn{x \in [0,\infty)} with two parameters \eqn{\alpha > 0} for shape and \eqn{\lambda > 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{lambda}{scale parameter \eqn{\lambda}.}
#' }
#' 
#' @examples
#' #  generate data from exponential distribution
#' x = abs(stats::rexp(100))
#' 
#' #  fit unweighted
#' Lomax(x)
#' 
#' \dontrun{
#' # put random weights to see effect of weights
#' niter = 500
#' ndata = 200
#' 
#' # generate data as above and fit unweighted MLE
#' x    = abs(stats::rexp(ndata))
#' xmle = Lomax(x)
#' 
#' # iterate
#' vec.alpha  = rep(0,niter)
#' vec.lambda = rep(0,niter)
#' for (i in 1:niter){
#'   # random weight
#'   ww = abs(stats::rnorm(ndata))
#' 
#'   MLE = Lomax(x, weight=ww)
#'   vec.alpha[i]  = MLE$alpha
#'   vec.lambda[i] = MLE$lambda
#'   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.lambda,  main="scale 'lambda'")
#' abline(v=xmle$lambda,  lwd=3, col="blue")
#' par(opar)
#' } 
#' 
#' @author Kisung You
#' @export
Lomax <- function(x, weight=NULL){
  #############################################
  # Preprocessing
  x      = handle_cts_nonneg("Lomax", x) # nonnegative real numbers
  nx     = length(x)
  weight = handle_weight("Lomax", weight, nx)
  maceps = 10*.Machine$double.eps
  
  #############################################
  # Optimize : DEoptim
  fopt.Lomax <- function(pars){
    # parameters
    alpha  = pars[1]
    lambda = pars[2]
    # log-likelihood
    term1 = log(alpha)-log(lambda)
    term2 = -(alpha+1)*log(1 + (x/lambda))
    loglkd = term1+term2
    # return
    return(-sum(loglkd*weight))
  }
  sol = DEoptim::DEoptim(fopt.Lomax, 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$lambda = as.double(sol[2])
  return(output)
}
kyoustat/T4mle documentation built on March 26, 2020, 12:09 a.m.