R/Nakagami.R

Defines functions Nakagami

Documented in Nakagami

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