R/HalfNormal.R

Defines functions HalfNormal

Documented in HalfNormal

#' (Weighted) MLE of Half-Normal Distribution
#' 
#' Half-Normal distribution is characterized by the following probability density function,
#' \deqn{f(x;\sigma) = \frac{\sqrt{2}}{\sigma \sqrt{\pi}} \exp\left( -\frac{x^2}{2\sigma^2} \right)}
#' where the domain is \eqn{x in [0,\infty)} with a scale paramter \eqn{\sigma > 0}.
#' 
#' @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{sigma}{scale parameter \eqn{\sigma}.}
#' }
#' 
#' @examples
#' #  generate data from half-normal distribution with 'sigma=1'
#' x = abs(stats::rnorm(100))
#' 
#' #  fit unweighted
#' HalfNormal(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 = HalfNormal(x)
#' 
#' # iterate
#' vec.sig = rep(0,niter)
#' for (i in 1:niter){
#'   # random weight
#'   ww = abs(stats::rnorm(ndata))
#' 
#'   MLE = HalfNormal(x, weight=ww)
#'   vec.sig[i] = MLE$sigma
#'   if ((i%%10) == 0){
#'     print(paste0(" iteration ",i,"/",niter," complete.."))
#'   }
#' }
#' 
#' # distribution of weighted estimates + standard MLE
#' opar <- par(no.readonly=TRUE)
#' hist(vec.sig,  main="scale 'sigma'")
#' abline(v=xmle$sigma, lwd=3, col="blue")
#' par(opar)
#' } 
#' 
#' @author Kisung You
#' @export
HalfNormal <- function(x, weight=NULL){
  #############################################
  # Preprocessing
  x      = handle_cts_nonneg("HalfNormal", x) # nonnegative real numbers
  nx     = length(x)
  weight = handle_weight("HalfNormal", weight, nx)
  maceps = 10*.Machine$double.eps
  
  #############################################
  # Optimize : R's optimize
  fopt.HalfNormal <- function(sigma){
    term1 = 0.5*log(2) - log(sigma) - 0.5*log(pi)
    term2 = -(x^2)/(2*(sigma^2))
    loglkd = term1+term2
    return(sum(loglkd*weight))
  }
  sol = stats::optimize(fopt.HalfNormal, lower=maceps, upper=1e+5, maximum = TRUE)
  
  #############################################
  # Return
  output = list()
  output$sigma = as.double(sol$maximum)
  return(output)
}
kyoustat/T4mle documentation built on March 26, 2020, 12:09 a.m.