# \donttest{
# Assuming existence of rkkw, grkkw, hskkw functions for kkw distribution
# Generate sample data from a known kkw distribution
set.seed(123)
true_par_kkw <- c(alpha = 2, beta = 3, delta = 1.5, lambda = 0.5)
# Use rkkw if it exists, otherwise use rgkw with gamma=1
if (exists("rkkw")) {
sample_data_kkw <- rkkw(100, alpha = true_par_kkw[1], beta = true_par_kkw[2],
delta = true_par_kkw[3], lambda = true_par_kkw[4])
} else {
sample_data_kkw <- rgkw(100, alpha = true_par_kkw[1], beta = true_par_kkw[2],
gamma = 1, delta = true_par_kkw[3], lambda = true_par_kkw[4])
}
hist(sample_data_kkw, breaks = 20, main = "kkw(2, 3, 1.5, 0.5) Sample")
# --- Maximum Likelihood Estimation using optim ---
# Initial parameter guess
start_par_kkw <- c(1.5, 2.5, 1.0, 0.6)
# Perform optimization (minimizing negative log-likelihood)
mle_result_kkw <- stats::optim(par = start_par_kkw,
fn = llkkw, # Use the kkw neg-log-likelihood
method = "BFGS",
hessian = TRUE,
data = sample_data_kkw)
# Check convergence and results
if (mle_result_kkw$convergence == 0) {
print("Optimization converged successfully.")
mle_par_kkw <- mle_result_kkw$par
print("Estimated kkw parameters:")
print(mle_par_kkw)
print("True kkw parameters:")
print(true_par_kkw)
} else {
warning("Optimization did not converge!")
print(mle_result_kkw$message)
}
# --- Compare numerical and analytical derivatives (if available) ---
# Requires 'numDeriv' package and analytical functions 'grkkw', 'hskkw'
if (mle_result_kkw$convergence == 0 &&
requireNamespace("numDeriv", quietly = TRUE) &&
exists("grkkw") && exists("hskkw")) {
cat("\nComparing Derivatives at kkw MLE estimates:\n")
# Numerical derivatives of llkkw
num_grad_kkw <- numDeriv::grad(func = llkkw, x = mle_par_kkw, data = sample_data_kkw)
num_hess_kkw <- numDeriv::hessian(func = llkkw, x = mle_par_kkw, data = sample_data_kkw)
# Analytical derivatives (assuming they return derivatives of negative LL)
ana_grad_kkw <- grkkw(par = mle_par_kkw, data = sample_data_kkw)
ana_hess_kkw <- hskkw(par = mle_par_kkw, data = sample_data_kkw)
# Check differences
cat("Max absolute difference between gradients:\n")
print(max(abs(num_grad_kkw - ana_grad_kkw)))
cat("Max absolute difference between Hessians:\n")
print(max(abs(num_hess_kkw - ana_hess_kkw)))
} else {
cat("\nSkipping derivative comparison for kkw.\n")
cat("Requires convergence, 'numDeriv' package and functions 'grkkw', 'hskkw'.\n")
}
# }
Run the code above in your browser using DataLab