R/LogLaplace.R

Defines functions LogLaplace

Documented in LogLaplace

#' (Weighted) MLE of Log-Laplace Distribution
#' 
#' Log-Laplace distribution is characterized by the following probability density function,
#' \deqn{f(x;\mu,b) = \frac{1}{2bx} \exp\left( -\frac{|\log(x) - \mu|}{b} \right)}
#' where the domain is \eqn{x \in (0,\infty)} with two parameters \eqn{\mu} for location and \eqn{b > 0} for spread.
#' 
#' @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{mu}{location parameter \eqn{\mu}.}
#' \item{b}{scale parameter \eqn{b}.}
#' }
#' 
#' @examples
#' #  generate data from exponential distribution
#' x = abs(stats::rexp(100))
#' 
#' #  fit unweighted
#' LogLaplace(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 = LogLaplace(x)
#' 
#' # iterate
#' vec.mu = rep(0,niter)
#' vec.b  = rep(0,niter)
#' for (i in 1:niter){
#'   # random weight
#'   ww = abs(stats::rnorm(ndata))
#' 
#'   MLE = LogLaplace(x, weight=ww)
#'   vec.mu[i] = MLE$mu
#'   vec.b[i]  = MLE$b
#'   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.mu, main="location 'mu'")
#' abline(v=xmle$mu, lwd=3, col="red")
#' hist(vec.b,  main="scale 'b'")
#' abline(v=xmle$b,  lwd=3, col="blue")
#' par(opar)
#' } 
#' 
#' @export
LogLaplace <- function(x, weight=NULL){
  #############################################
  # Preprocessing
  x      = handle_cts_pos("LogLaplace", x) # nonnegative real numbers
  nx     = length(x)
  weight = handle_weight("LogLaplace", weight, nx)
  maceps = 10*.Machine$double.eps
  
  
  #############################################
  # Optimize : DEoptim
  fopt.LogLaplace <- function(pars){
    # parameters
    mu = pars[1]
    b  = pars[2]
    # log-likelihood
    term1 = -(log(2)+log(b)+log(x))
    term2 = -abs(log(x)-mu)/b
    loglkd = term1+term2
    # return
    return(-sum(loglkd*weight))
  }
  sol = DEoptim::DEoptim(fopt.LogLaplace, lower=c(-1e+5, maceps), upper=c(1e+5,1e+5), 
                         control=DEoptim::DEoptim.control(trace=FALSE))$optim$bestmem
  
  #############################################
  # Return
  output = list()
  output$mu = as.double(sol[1])
  output$b  = as.double(sol[2])
  return(output)
}
kyoustat/T4mle documentation built on March 26, 2020, 12:09 a.m.