R/hybrid-estimating.R

Defines functions step_selection_constraint_grad step_hybrid_jacobian step_hybrid_profile_jacobian step_hybrid_score step_hybrid_profile_score step_selection_constraint step_weighted_logpartlik

#-------------------------------------------------------------------------------
# Log likelihood function and selection constraint function

step_weighted_logpartlik <- function(
    theta,                                      # full parameter vector
    yi,                                         # outcome vector
    sei,                                        # sampling standard errors
    pi = pnorm(Hsgn * yi / sei, lower.tail = FALSE),   # one-sided p-values
    ai = NULL,                                  # analytic weight 
    beta = NULL,                                # mean parameter coefficients
    gamma = NULL,                               # variance component coefficients
    zeta0 = NULL,                               # selection model coefficients
    zeta = NULL,                                # selection model coefficients
    steps = .025,                               # steps / cut-points
    X = NULL,                                   # mean parameter design matrix
    U = NULL,                                   # variance component design matrix
    Z0 = NULL,                                  # selection model design matrix for highest step
    Z = NULL,                                   # selection model design matrices for each cut-point
    Hsgn = 1L,                                  # valence of alternative hypothesis used to compute p-values
    priors = NULL,                              # selmodel_prior object to specify priors
    contributions = FALSE,                      # not used
    negate = FALSE                              # not used
) {
  
  params <- parse_step_params(
    theta = theta,
    yi = yi,
    sei = sei,
    pi = pi,
    beta = beta,
    gamma = gamma,
    zeta0 = zeta0,
    zeta = zeta,
    steps = steps,
    X = X,
    U = U,
    Z0 = Z0,
    Z = Z,
    Hsgn = Hsgn
  )
  
  weight_vec <- if (is.null(ai)) params$weight_vec else params$weight_vec * ai
  
  # likelihood contributions
  log_lik_i <- ((yi - params$mu)^2 / (-2 * params$eta) - log(params$eta) / 2 ) / params$weight_vec
  
  # weighted log likelihood (Eq. 51)
  log_lik <- if (is.null(ai)) sum(log_lik_i) else sum(ai * log_lik_i)
  
  # priors
  if (is.null(priors)) {
    
    return(log_lik) 
    
  } else {
    
    log_prior <- priors$log_prior(
      beta = params$beta, 
      gamma = params$gamma, 
      zeta = c(params$zeta0, params$zeta), 
      include_zeta = FALSE
    )  
    return(log_lik + log_prior)
    
  }
  
}


step_selection_constraint <- function(
    theta,                                      # full parameter vector
    yi,                                         # outcome vector
    sei,                                        # sampling standard errors
    pi = pnorm(Hsgn * yi / sei, lower.tail = FALSE),   # one-sided p-values
    ai = NULL,                                  # analytic weight
    beta = NULL,                                # mean parameter coefficients
    gamma = NULL,                               # variance component coefficients
    zeta0 = NULL,                               # selection model coefficients
    zeta = NULL,                                # selection model coefficients
    steps = .025,                               # steps / cut-points
    X = NULL,                                   # mean parameter design matrix
    U = NULL,                                   # variance component design matrix
    Z0 = NULL,                                  # selection model design matrix for highest step
    Z = NULL,                                   # selection model design matrices for each cut-point
    Hsgn = 1L,                                  # valence of alternative hypothesis used to compute p-values
    priors = NULL,                              # selmodel_prior object to specify priors
    contributions = FALSE,                      # not used
    negate = FALSE                              # not used
) {
  
  params <- parse_step_params(
    theta = theta,
    yi = yi,
    sei = sei,
    pi = pi,
    beta = beta,
    gamma = gamma,
    zeta0 = zeta0,
    zeta = zeta,
    steps = steps,
    X = X,
    U = U,
    Z0 = Z0,
    Z = Z,
    Hsgn = Hsgn,
    calc_Ai = TRUE
  )

  scores <- calculate_S_zeta_ij(
    B_mat = params$B_mat,
    Ai = params$Ai,
    weight_vec = params$weight_vec,
    cats = params$cats,
    Z0 = Z0,
    Z = Z,
    lambda0 = params$lambda0,
    lambda = params$lambda
  )
  
  S_zeta <- if (is.null(Z0)) scores$S_zeta_ij else cbind(scores$S_zeta0_ij, scores$S_zeta_ij)
  
  colSums(S_zeta)
  
}

#-------------------------------------------------------------------------------
# Hybrid score function, profiled in beta

step_hybrid_profile_score <- function(
    theta,                                      # parameter vector excluding beta
    yi,                                         # outcome vector
    sei,                                        # sampling standard errors
    pi = pnorm(Hsgn * yi / sei, lower.tail = FALSE),   # one-sided p-values
    ai = NULL,                                  # analytic weight
    steps = .025,                               # steps / cut-points
    X = NULL,                                   # mean parameter design matrix
    U = NULL,                                   # variance component design matrix
    Z0 = NULL,                                  # selection model design matrix for highest step
    Z = NULL,                                   # selection model design matrices for each cut-point
    Hsgn = 1L,                                  # valence of alternative hypothesis used to compute p-values
    priors = NULL                               # selmodel_prior object to specify priors
) {
  
  if (is.null(X)) {
    x_dim <- 1L
    theta_na <- c(NA_real_, theta)
  } else {
    x_dim <- ncol(X)
    theta_na <- c(rep(NA_real_, x_dim), theta)
  }
  
  scores <- step_hybrid_score(
    theta = theta_na,
    yi = yi, sei = sei, pi = pi, ai = ai,
    steps = steps, 
    X = X, U = U, Z0 = Z0, Z = Z,
    Hsgn = Hsgn,
    priors = priors
  )  
  
  scores[-(1:x_dim)]

}

#-------------------------------------------------------------------------------
# Hybrid score function

step_hybrid_score <- function(
  theta,                                      # full parameter vector
  yi,                                         # outcome vector
  sei,                                        # sampling standard errors
  pi = pnorm(Hsgn * yi / sei, lower.tail = FALSE),   # one-sided p-values
  ai = NULL,                                  # analytic weight
  beta = NULL,                                # mean parameter coefficients
  gamma = NULL,                               # variance component coefficients
  zeta0 = NULL,                               # selection model coefficients
  zeta = NULL,                                # selection model coefficients
  steps = .025,                               # steps / cut-points
  X = NULL,                                   # mean parameter design matrix
  U = NULL,                                   # variance component design matrix
  Z0 = NULL,                                  # selection model design matrix for highest step
  Z = NULL,                                   # selection model design matrices for each cut-point
  Hsgn = 1L,                                  # valence of alternative hypothesis used to compute p-values
  priors = NULL,                              # selmodel_prior object to specify priors
  contributions = FALSE,                      # whether to return matrix of score contributions,
  negate = FALSE                              # whether to return the negative of the scores
) {

  params <- parse_step_params(
    theta = theta,
    yi = yi,
    sei = sei,
    pi = pi,
    beta = beta,
    gamma = gamma,
    zeta0 = zeta0,
    zeta = zeta,
    steps = steps,
    X = X,
    U = U,
    Z0 = Z0,
    Z = Z,
    Hsgn = Hsgn,
    priors = priors,
    calc_Ai = TRUE
  )


  #----------------------------------------------------------
  # score contributions (Eq. 12, just for observation ij)
  zeta_i <- (yi - params$mu) / params$eta

  # score contribution for mu
  S_beta_ij  <-  zeta_i / params$weight_vec
  if (!is.null(X)) S_beta_ij <- X * S_beta_ij

  # score contribution for gamma
  S_gamma_ij <- params$tausq * (zeta_i^2 - 1 / params$eta) / (2 * params$weight_vec)
  if (!is.null(U)) S_gamma_ij <- U * S_gamma_ij

  scores <- calculate_S_zeta_ij(
    B_mat = params$B_mat,
    Ai = params$Ai,
    weight_vec = params$weight_vec,
    cats = params$cats,
    Z0 = Z0,
    Z = Z,
    lambda0 = params$lambda0,
    lambda = params$lambda
  )
  
  S_zeta_ij <- scores$S_zeta_ij
  S_zeta0_ij <- if (is.null(Z0)) NULL else scores$S_zeta0_ij

  score_contributions <- get_score_contributions(
    S_beta_ij = S_beta_ij,
    S_gamma_ij = S_gamma_ij,
    S_zeta_ij = S_zeta_ij,
    S_zeta0_ij = S_zeta0_ij,
    ai = ai,
    contributions = contributions
  )
  
  
  # handle prior contributions
  if (!is.null(priors)) {
    
    prior_score <- priors$score_prior(beta = params$beta, gamma = params$gamma, zeta = c(params$zeta0, params$zeta))
    
    if (contributions) {
      
      # prior_wt to allocate total prior score across observations
      if (is.null(ai)) {
        prior_wt <- rep(1 / params$k, times = params$k)
      } else {
        prior_wt <- ai / sum(ai)
      }
      
      score_contributions <- score_contributions + outer(prior_wt, prior_score)
      
      return(score_contributions)
      
    } else {
      
      score_contributions <- score_contributions + prior_score
      
    }
    
  }
  
  if (negate) return(-score_contributions) else return(score_contributions)
}



#-------------------------------------------------------------------------------
# Jacobian function

step_hybrid_profile_jacobian <- function(
    theta,                                      # full parameter vector
    yi,                                         # outcome vector
    sei,                                        # sampling standard errors
    pi = pnorm(Hsgn * yi / sei, lower.tail = FALSE),   # one-sided p-values  
    ai = NULL,                                  # analytic weight
    steps = .025,                               # steps / cut-points
    X = NULL,                                   # mean parameter design matrix
    U = NULL,                                   # variance component design matrix
    Z0 = NULL,                                  # selection model design matrix for highest step
    Z = NULL,                                   # selection model design matrices for each cut-point
    Hsgn = 1L,                                  # valence of alternative hypothesis used to compute p-values
    priors = NULL                               # selmodel_prior object to specify priors
) {
  
  if (is.null(X)) {
    x_dim <- 1L
    theta_na <- c(NA_real_, theta)
  } else {
    x_dim <- ncol(X)
    theta_na <- c(rep(NA_real_, x_dim), theta)
  }
  
  jac <- step_hybrid_jacobian(
    theta = theta_na,
    yi = yi, sei = sei, pi = pi, ai = ai,
    steps = steps, 
    X = X, U = U, Z0 = Z0, Z = Z,
    Hsgn = Hsgn,
    priors = priors
  )
  
  jac[-(1:x_dim),-(1:x_dim)]
  
}

step_hybrid_jacobian <- function(
    theta,                                      # full parameter vector
    yi,                                         # outcome vector
    sei,                                        # sampling standard errors
    pi = pnorm(Hsgn * yi / sei, lower.tail = FALSE),   # one-sided p-values  
    ai = NULL,                                  # analytic weight
    beta = NULL,                                # mean parameter coefficients
    gamma = NULL,                               # variance component coefficients
    zeta0 = NULL,                               # selection model coefficients
    zeta = NULL,                                # selection model coefficients
    steps = .025,                               # steps / cut-points
    X = NULL,                                   # mean parameter design matrix
    U = NULL,                                   # variance component design matrix
    Z0 = NULL,                                  # selection model design matrix for highest step
    Z = NULL,                                   # selection model design matrices for each cut-point
    Hsgn = 1L,                                  # valence of alternative hypothesis used to compute p-values
    priors = NULL                               # selmodel_prior object to specify priors
) {
  
  params <- parse_step_params(
    theta = theta,
    yi = yi,
    sei = sei,
    pi = pi,
    beta = beta,
    gamma = gamma,
    zeta0 = zeta0,
    zeta = zeta,
    steps = steps,
    X = X,
    U = U,
    Z0 = Z0,
    Z = Z,
    Hsgn = Hsgn,
    calc_Ai = TRUE
  )
  
  # analytic weights
  if (is.null(ai)) ai <- rep(1, params$k)
  
  
  #----------------------------------------------------------
  
  zeta_i <- (yi - params$mu) / params$eta
  
  # J_beta_beta is x_dim * x_dim
  J_beta_beta_right <-  1 / (params$eta * params$weight_vec)
  J_beta_beta <- -1 * matrix_diag_crossprod(d = ai * J_beta_beta_right, A = X, B = X)
  
  # J_beta_gamma is x_dim * u_dim
  J_beta_gamma_right <- params$tausq * zeta_i / (params$eta * params$weight_vec)
  J_beta_gamma <- -1 * matrix_diag_crossprod(d = ai * J_beta_gamma_right, A = X, B = U)

  # J_gamma_gamma is u_dim * u_dim
  J_gamma_gamma_right <- (params$tausq^2 * (zeta_i^2 / params$eta - 1 / (2 * params$eta^2)) - 
                            params$tausq * (zeta_i^2 / 2 - 1 / (2 * params$eta))) / params$weight_vec 
  J_gamma_gamma <- -1 * matrix_diag_crossprod(d = ai * J_gamma_gamma_right, A = U, B = U)
  
  if (is.null(Z0)) {
    dw_dlambda <- model.matrix(~ params$cats)[,-1]
    lambda_dw_wsq <- (params$lambda * dw_dlambda) / params$weight_vec^2
    J_beta_zeta_right <- lambda_dw_wsq * zeta_i
    J_gamma_zeta_right <-  params$tausq * lambda_dw_wsq * (zeta_i^2 - 1 / params$eta) / 2
    
    Z_full <- Z
    z_index <- c(0,cumsum(params$z_dim))
    
  } else {
    dw_dlambda <- model.matrix(~ 0 + params$cats)
    lambda_dw_wsq <- (params$lambda_full * dw_dlambda) / params$weight_vec^2
    J_beta_zeta_right <- lambda_dw_wsq * zeta_i
    J_gamma_zeta_right <-  params$tausq * lambda_dw_wsq * (zeta_i^2 - 1 / params$eta) / 2
    
    Z_full <- if (is.list(Z)) c(list(Z0),Z) else list(Z0, Z)
    z_index <- c(0,cumsum(c(params$z0_dim, params$z_dim)))
    
  }
  
  if (is.null(Z)) {
    if (is.null(Z0)) {
      J_beta_zeta <- -1 * matrix_diag_crossprod(A = X, B = ai * J_beta_zeta_right)
      J_gamma_zeta <- -1 * matrix_diag_crossprod(A = U, B = ai * J_gamma_zeta_right)
      
    } else {
      
      J_beta_zeta_right <- cbind(J_beta_zeta_right[,1] * Z0, J_beta_zeta_right[,-1])
      J_beta_zeta <- -1 * matrix_diag_crossprod(A = X, B = ai * J_beta_zeta_right)
      
      J_gamma_zeta_right <- cbind(J_gamma_zeta_right[,1] * Z0, J_gamma_zeta_right[,-1])
      J_gamma_zeta <- -1 * matrix_diag_crossprod(A = U, B = ai * J_gamma_zeta_right)
      
    }
    
  } else if (is.matrix(Z_full)) {
    
    J_beta_zeta <- -1 * matrix_diag_crossprod(A = X, d = ai * J_beta_zeta_right, B = Z_full)
    J_gamma_zeta <- -1 * matrix_diag_crossprod(A = U, d = ai * J_gamma_zeta_right, B = Z_full)
    
  } else {

    J_beta_zeta_right_h <-  apply(ai * J_beta_zeta_right, 2, identity, simplify = FALSE)
    J_beta_zeta_h <- mapply(matrix_diag_crossprod, d = J_beta_zeta_right_h, B = Z_full, MoreArgs = list(A = X), SIMPLIFY = FALSE)
    J_beta_zeta <- -1 * do.call(cbind, J_beta_zeta_h)
    
    J_gamma_zeta_right_h <- apply(ai * J_gamma_zeta_right, 2, identity, simplify = FALSE)
    J_gamma_zeta_h <- mapply(matrix_diag_crossprod, d = J_gamma_zeta_right_h, B = Z_full, MoreArgs = list(A = U), SIMPLIFY = FALSE)
    J_gamma_zeta <- -1 * do.call(cbind, J_gamma_zeta_h)
    
  }
  
  
  H_zeta <- calculate_H_zeta(
    B_mat = params$B_mat,
    Ai = params$Ai,
    weight_vec = params$weight_vec,
    cats = params$cats,
    eta = params$eta,
    c_mat = params$c_mat,
    k = params$k,
    H = params$H,
    tausq = params$tausq,
    X = X,
    U = U,
    Z0 = Z0,
    Z = Z,
    Hsgn = Hsgn,
    ai = ai,
    z0_dim = params$z0_dim,
    z_dim = params$z_dim,
    lambda0 = params$lambda0,
    lambda = params$lambda,
    lambda_full = params$lambda_full
  )      

  H_zeta_ <- cbind(t(H_zeta$H_beta_zeta), t(H_zeta$H_gamma_zeta), H_zeta$H_zeta_zeta)
                         

  # Put the whole Hessian together
  
  J_matrix <- rbind(
    cbind(J_beta_beta, J_beta_gamma, J_beta_zeta),
    cbind(t(J_beta_gamma), J_gamma_gamma, J_gamma_zeta),
    H_zeta_
  )
  colnames(J_matrix) <- rownames(J_matrix) <- params$H_names
  
  # Handle priors
  
  if (is.null(priors)) {
    
    return(J_matrix)
    
  } else {
    hessian_prior <- priors$hessian_prior(beta = params$beta, gamma = params$gamma, zeta = c(params$zeta0, params$zeta))
    return(J_matrix + hessian_prior)
  }
  
}


step_selection_constraint_grad <- function(
    theta,                                      # full parameter vector
    yi,                                         # outcome vector
    sei,                                        # sampling standard errors
    pi = pnorm(Hsgn * yi / sei, lower.tail = FALSE),   # one-sided p-values
    ai = NULL,                                  # analytic weight
    beta = NULL,                                # mean parameter coefficients
    gamma = NULL,                               # variance component coefficients
    zeta0 = NULL,                              # selection model coefficients
    zeta = NULL,                               # selection model coefficients
    steps = .025,                               # steps / cut-points
    X = NULL,                                   # mean parameter design matrix
    U = NULL,                                   # variance component design matrix
    Z0 = NULL,                                  # selection model design matrix for highest step
    Z = NULL,                                   # selection model design matrices for each cut-point
    Hsgn = 1L,                                  # valence of alternative hypothesis used to compute p-values
    contributions = FALSE                       # not used
) {
 
  params <- parse_step_params(
    theta = theta,
    yi = yi,
    sei = sei,
    pi = pi,
    beta = beta,
    gamma = gamma,
    zeta0 = zeta0,
    zeta = zeta,
    steps = steps,
    X = X,
    U = U,
    Z0 = Z0,
    Z = Z,
    Hsgn = Hsgn,
    calc_Ai = TRUE
  )
  
  # analytic weights
  if (is.null(ai)) ai <- rep(1, params$k)
  
  H_zeta <- calculate_H_zeta(
    B_mat = params$B_mat,
    Ai = params$Ai,
    weight_vec = params$weight_vec,
    cats = params$cats,
    eta = params$eta,
    c_mat = params$c_mat,
    k = params$k,
    H = params$H,
    tausq = params$tausq,
    X = X,
    U = U,
    Z0 = Z0,
    Z = Z,
    Hsgn = Hsgn,
    ai = ai,
    z0_dim = params$z0_dim,
    z_dim = params$z_dim,
    lambda0 = params$lambda0,
    lambda = params$lambda,
    lambda_full = params$lambda_full
  )
  
  rbind(H_zeta$H_beta_zeta, H_zeta$H_gamma_zeta, H_zeta$H_zeta_zeta)
}

Try the metaselection package in your browser

Any scripts or data that you put into this service are public.

metaselection documentation built on Aug. 31, 2026, 5:08 p.m.