## Distributed as part of the supplementary material for the the paper
## ``Improving the accuracy of likelihood-based inference in
## meta-analysis and meta-regression''
##
## Authors: Ioannis Kosmidis, Anna Maria Guolo, Cristiano Varin
## Date: 14 August 2015
## Licence: GPL 2 or greater

## NOT A POLISHED PIECE OF PUBLIC-USE SOFTWARE!  Provided "as is".
## NO WARRANTY OF FITNESS FOR ANY PURPOSE!

## Returns maximum likelihood (ML), maximum penalized likelihood
## (MPL), bias-corrected (BC) and DerSimonian & Laird (DL) estimates
## for the parameters of the a meta-regression model (see Sections
## 3.1, 3.2 and 6 of the main text)

## Arguments:
## object is metaLik object
## method: the estimation method to be used (default is "all")
BiasFit <- function(object,
                    method = c("all", "MPL", "BC", "DL"), ...) {
    method <- match.arg(method)
    parstau2 <- object$mle
    p <- ncol(object$X)
    tau2 <- parstau2[p + 1]
    zeta <- tau2
    pars <- c(object$mle[seq.int(p)], zeta)
    b <- with(object, bias(pars, X, sigma2, y))
    BC <- MPL <- DL <- rep(NA, p + 1)
    if (method == "BC" | method == "all") {
        BC <- pars - c(numeric(p), b)
    }
    if (method == "MPL" | method == "all") {
        MPL <- optim(par = pars,
                    fn = penloglik,
                    gr = penscores,
                    X = object$X, y = object$y, sigma2 = object$sigma2,
                    control = list(fnscale = -1), method = "BFGS")
        MPL <- MPL$par
    }
    if (method == "DL" | method == "all") {
        DL <- c(drop(object$DL), with(object, {tau2 <- object$tau2.DL}))
    }
    ML <- optim(par = pars,
              fn = loglik,
              gr = scores,
              X = object$X, y = object$y, sigma2 = object$sigma2,
              control = list(fnscale = -1), method = "BFGS")
  list(ML = ML$par,
       MPL = MPL,
       BC = BC,
       DL = DL)
}


## Performs individual tests for the parameters of a meta-regression
## model (see Section 3.3 of the main text)

## Arguments:
## object is metaLik object
## what: the index of the parameter to test for
## null: the null hypothesis (the alternative is always not the null)
## type: likelihood based or penalized likelihood based tests (defaults to likelihood)?
## optMethod: the optimization method to be used for the profiling
lrtest <- function(object,
                   what = 1,
                   null = 0,
                   type = c("loglik", "penloglik"),
                   optMethod = "Nelder-Mead",
                   ...) {
    X <- object$X
    y <- object$y
    p <- ncol(X)
    sigma2 <- object$sigma2
    parstau2 <- pars <- object$mle
    type <- match.arg(type)
    interval <- c(0, 1000)
    IF <- switch(type,
                 "loglik" = loglik,
               "penloglik" = penloglik)
    DIF <- switch(type,
                  "loglik" = scores,
                  "penloglik" = penscores)
    profzeta <- function(zeta,
                         ystar, Xstar, X,
                         penalty = TRUE) {
        tau2 <- zeta
        w <- 1/(sigma2 + tau2)
        beta <- coef(lm.wfit(x = Xstar, y = ystar, w = w))
        res <- ystar - Xstar %*% beta
        W.X <- sqrt(w)*X
        XWX <- crossprod(W.X)
        0.5*sum(log(w)) - 0.5*sum(w*res^2) - penalty*(0.5*log(det(XWX)))
    }
    fun <- function(range) {
        params <- numeric(p)
        profvalues <- resFull$value
        params[what] <- range
        ynew <- y - as.matrix(X[, what]) %*% range
        Xnew <- as.matrix(X[, -what])
        zetaConstr <- optimize(profzeta,
                               interval = interval,
                               ystar = ynew,
                               Xstar = Xnew,
                               X = X,
                               penalty = (type == "penloglik"),
                               maximum = TRUE)$maximum
        if (NCOL(Xnew) > 0) {
            tau2Constr <- zetaConstr
            wConstr <- 1/(sigma2 + tau2Constr)
            params[-what] <- coef(lm.wfit(x = Xnew, y = ynew, w = wConstr))
        }
        profvalues <- IF(c(params, zetaConstr), X = X, y = y,
                         sigma2 = sigma2)
        list(parameterValues = params, profileValues = profvalues)
    }
    ## Get the full maximum (penalized) likelihood estimates
    resFull <- optim(par = pars,
                     fn = IF,
                     gr = DIF,
                     X = X, y = y, sigma2 = sigma2,
                      control = list(fnscale = -1),
                     method = optMethod,
                     hessian = TRUE)
    resRestricted <- fun(null)
    statistic <- 2*(resFull$value - resRestricted$profileValues)
    if (statistic < 0) {
        statistic <- 0
    }
    pvalue <- 1 - pchisq(statistic, 1)
    list(statistics = statistic,
         pvalue = pvalue)
}

## Implementation Zeng and Lin' double resampling
## it assumes a call to metaLik
## (simple double parametric bootstrap from DL?)

## Arguments:
## beta0 is null hypothesis
## m is metaLik object
## B number of bootstrap samples (output B^2 bootstrap estimates)
## myseed
## ci: return *also* confidence interval?
## alpha: confidence interval level (only if pval = FALSE)
double.resampling <- function(beta0, m, B = 1000, myseed = 123, ci = FALSE, alpha = 0.05)
{

    ## take care of the random seed
    if (exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) {
        seed.keep <- get(".Random.seed", envir = .GlobalEnv,
                         inherits = FALSE)
        on.exit(assign(".Random.seed", seed.keep, envir = .GlobalEnv))
    }
    set.seed(myseed)
    ## extract info
    beta.DL <- c(m$DL) ## assumes meta-analysis
    tau2.DL <- m$tau2.DL
    sigma2 <- m$sigma2
    K <- m$K

    beta.resampled <- matrix(NA, nrow = B, ncol = B)
    ## some recurrent computations
    S1 <- sum(1/sigma2)
    S2 <- sum(1/sigma2^2)
    denom <- S1-S2/S1
    compute.tau2 <- function(betak, betahat){
        eps <- t(betak) - c(betahat)
        tmp <- eps^2 %*% ( 1/sigma2 ) - (K-1)
        pmax(0, tmp/denom)
    }
    compute.betahat <- function(betak, tau2){
        t(betak) %*% (1 / (sigma2 + tau2) ) / sum(1 / (sigma2 + tau2) )
    }

    ## first run
    betak <- replicate(B, beta.DL + rnorm(K) * sqrt(sigma2 + tau2.DL) )
    betahat <- compute.betahat(betak, 0.0)
    tau2hat <- compute.tau2(betak, betahat)

    ## second run
    for(b in 1:B){
        betak <- replicate(B, beta.DL + rnorm(K) * sqrt(sigma2 + tau2hat[b]))
        beta.resampled[b,] <- compute.betahat(betak, tau2hat[b])
    }
    beta.resampled <- c(beta.resampled)
    pval <- 2 * min( mean( beta.resampled > beta0 ), mean( beta.resampled < beta0 ) )
    if(ci){
        ci <- quantile( beta.resampled, c(alpha / 2, 1 - alpha / 2) )
        return( list(pval = pval, ci = ci) )
    }
    else
        return(pval)
}


## Helper functions for BiasFit and lrtest
fitfun <- function(pars,
                   X,
                   sigma2,
                   y,
                   info = FALSE) {
  p <- ncol(X)
  zeta <- pars[p + 1]
  tau2 <- zeta
  betas <- pars[seq.int(p)]
  w <- 1/(sigma2 + tau2)
  etas <- X%*%betas
  R <- drop(y - etas)
  if (info) {
    W.X <- sqrt(w)*X
    XWX <- crossprod(W.X)
    XWXinv <- try(solve(XWX), silent = TRUE)
    if (inherits(XWXinv, "try-error"))
        XWXinv <- matrix(NA, p, p)
    h <- rowSums((X %*% XWXinv) * X) * w
    expinfo <- obsinfo <- vcove <- matrix(0, p + 1, p + 1)
    expinfo[seq.int(p), seq.int(p)] <- obsinfo[seq.int(p), seq.int(p)] <- XWX
    expinfo[p + 1, p + 1] <- sum(w^2)/2
    vcove[seq.int(p), seq.int(p)] <- XWXinv
    vcove[p + 1, p + 1] <- 2/sum(w^2)
    obsinfo[p + 1, p + 1] <- -sum(w^2)/2 + sum(w^3*R^2)
    obsinfo[seq.int(p), p + 1] <- colSums(w^2*X*R)
    obsinfo[p + 1, seq.int(p)] <- colSums(w^2*X*R)
  }
  else {
    XWX <- h <- expinfo <- obsinfo <- vcove <- NULL
  }
  zstate <- betas/sqrt(diag(vcove)[1:p])
  res <- list(sigma2 = sigma2,
              y = y,
              X = X,
              tau2 = tau2,
              betas = betas,
              R = R,
              XWX = XWX,
              expinfo = expinfo,
              vcove = vcove,
              w = w,
              h = h,
              zstate = zstate)
  c(res)
}

loglik <- function(pars,
                   X,
                   sigma2,
                   y,
                   fit = NULL) {
  if (is.null(fit)) {
    fit <- fitfun(pars, X, sigma2, y, info = FALSE)
  }
  with(fit, {
    if (tau2 < 0) {
      return(NA)
    }
    else {
      0.5*sum(log(w)) - 0.5*sum(R^2*w)
    }
  })
}

penloglik <- function(pars,
                      X,
                      sigma2,
                      y,
                      fit = NULL) {
  if (is.null(fit)) {
    fit <- fitfun(pars, X, sigma2, y, info = TRUE)
  }
  with(fit, {
    if (tau2 < 0) {
      return(NA)
    }
    else {
        0.5*sum(log(w)) - 0.5*sum(R^2*w) - 0.5*log(det(XWX))
    }
  })
}

scores <- function(pars,
                   X,
                   sigma2,
                   y,
                   fit = NULL) {
  if (is.null(fit)) {
    fit <- fitfun(pars, X, sigma2, y, info = TRUE)
  }
  with(fit, {
    c(colSums(w*X*R), sum(R^2*w^2 - w)/2)
  })
}

penscores <- function(pars,
                      X,
                      sigma2,
                      y,
                      fit = NULL) {
  if (is.null(fit)) {
    fit <- fitfun(pars, X, sigma2, y, info = TRUE)
  }
  with(fit, {
    c(colSums(w*X*R), sum(R^2*w^2 - (1 - h)*w)/2)
  })
}

bias <- function(pars, X, sigma2, y, fit = NULL) {
  if (is.null(fit)) {
    fit <- fitfun(pars, X, sigma2, y, info = TRUE)
  }
  with(fit, {
           sum(w*h)/sum(w^2)
  })
}
