R/Gumbel.R

Defines functions Gumbel

Documented in Gumbel

#' (Weighted) MLE of Gumbel Distribution
#' 
#' Gumbel distribution is characterized by the following probability density function,
#' \deqn{f(x;\mu,\beta) = \frac{1}{\beta} \exp(-(z+e^{-z}))}
#' with \eqn{z=(x-\mu)/\beta}. The domain is real number \eqn{\mathbf{R}} with 
#' location \eqn{\mu \in \mathbf{R}} and scale \eqn{\beta > 0} parameters.
#' 
#' @param x a length-\eqn{n} vector of nonnegative real numbers.
#' @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{beta}{scale parameter \eqn{\beta}.}
#' }
#' 
#' @examples
#' #  generate data from standard normal
#' x = stats::rnorm(100)
#' 
#' #  fit unweighted
#' Gumbel(x)
#' 
#' \dontrun{
#' # put random weights to see effect of weights
#' niter = 500
#' ndata = 200
#' 
#' # generate data as above and fit unweighted MLE
#' x    = stats::rnorm(ndata)
#' xmle = Gumbel(x)
#' 
#' # iterate
#' vec.mu   = rep(0,niter)
#' vec.beta = rep(0,niter)
#' for (i in 1:niter){
#'   # random weight
#'   ww = abs(stats::rnorm(ndata))
#' 
#'   MLE = Gumbel(x, weight=ww)
#'   vec.mu[i]   = MLE$mu
#'   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.mu, main="location 'mu'")
#' abline(v=xmle$mu, lwd=3, col="red")
#' hist(vec.beta, main="scale 'beta'")
#' abline(v=xmle$beta, lwd=3, col="blue")
#' par(opar)
#' } 
#' 
#' @author Kisung You
#' @export
Gumbel <- function(x, weight=NULL){
  #############################################
  # Preprocessing
  x      = handle_cts("Gumbel", x)
  nx     = length(x)
  weight = handle_weight("Gumbel", weight, nx)
  maceps = 10*.Machine$double.eps
  
  #############################################
  # Optimize : DEoptim
  fopt.Gumbel <- function(pars){
    # parameters
    mu   = pars[1]
    beta = pars[2]
    # log-likelihood
    z = (x-mu)/beta
    term1 = -(z+exp(-z))
    term2 = -log(beta)
    loglkd = term1+term2
    # return
    return(-sum(loglkd*weight))
  }
  mylower = c(-1e+5, maceps)
  myupper = c(1e+5, 1e+5)
  sol = DEoptim::DEoptim(fopt.Gumbel, lower=mylower, upper=myupper, 
                         control=DEoptim::DEoptim.control(trace=FALSE))$optim$bestmem
  
  #############################################
  # Return
  output = list()
  output$mu   = as.double(sol[1])
  output$beta = as.double(sol[2])
  return(output)
}
kyoustat/T4mle documentation built on March 26, 2020, 12:09 a.m.