Nothing
#' @title Choice-Confidence (CHOCO) Model
#'
#' @description
#' Simulates data from the Choice-Confidence (CHOCO) model. This model is useful for
#' subjective ratings (e.g., Likert-type scales) where responses represent a choice
#' between two underlying categories (e.g., "disagree" vs. "agree") along with a
#' degree of confidence or intensity.
#'
#' The CHOCO model divides the response scale at a middle-value. Responses above and below the
#' middle are modeled by two rescaled (and mirrored for the left side) [Beta-Gate][rcogmod_betagate()] distributions.
#' In Beta-Gate distributions, extreme values (0 or 1) are generated by the "lumping" of values
#' that crossed a threshold (or "gate"). The location of these gates from the center of the
#' distribution is controlled by the `pex` and `bex` parameters, influecing the ease of crossing
#' the gate (and thus the probability of extreme values).
#'
#' @param n Number of simulated trials.
#' @param p Proportion parameter determining the balance between the left and right sides
#' *after excluding* the probability mass at the middle (`pmid`). `P(Right Side | Not Middle) = p`.
#' @param confright,confleft Mean parameter (`mu`) for the underlying Beta-Gate distribution for the
#' *right* side and *left* side, respectively. Represents confidence towards 1. `0 < confright < 1`.
#' @param precright,precleft Precision parameter (`phi`) for the underlying Beta-Gate distribution for
#' the *right* side and *left* side, respectively. Must be positive. Higher values indicate more
#' concentrated distributions, and a value of 1 corresponds to a uniform distribution.
#' @inheritParams rcogmod_betagate
#' @param pmid Probability mass exactly at the `mid`. This determines the proportion
#' of trials where the output is directly assigned the value of `mid`, bypassing
#' the left or right components.
#' @param mid The point dividing the scale (`0 < mid < 1`). Typically set to 0.5. Note that in the Stan implementation,
#' `mid` is fixed at 0.5 and not available as a parameter.
#'
#' @seealso rcogmod_betagate
#'
#' @details
#' **Psychological Interpretation:**
#' - `p`: Represents the overall tendency to choose the "right" category (e.g., "agree") over the "left"
#' category (e.g., "disagree"), given that a choice is made (i.e., not responding exactly at `mid`).
#' - `confright` and `confleft`: Average confidence level when choosing the "right" or "left" category.
#' Higher values (closer to 1) indicate stronger confidence or agreement towards the extreme end of the
#' scale.
#' - `precright` and `precleft`: Certainty or consistency of the confidence ratings for the right and left
#' choices, respectively. Higher values indicate less variability in confidence ratings around their
#' respective means (`confright`, `confleft`).
#' - `pex`: Represents the overall tendency towards extreme responding (choosing 0 or 1).
#' This could reflect individual response styles (e.g., acquiescence, yea-saying/nay-saying)
#' or properties of the item itself (e.g., polarizing questions).
#' - `bex`: Indicates the *direction* of the extreme response bias. `bex > 0.5` suggests a bias
#' for producing ones more easily, while `bex < 0.5` suggests a bias towards zero.
#'
#' @references
#' - Kubinec, R. (2023). Ordered beta regression: a parsimonious, well-fitting model for continuous data with
#' lower and upper bounds. Political Analysis, 31(4), 519-536. (Describes the underlying ordered beta model)
#'
#' @return `rcogmod_choco()` returns a numeric vector of `n` simulated ratings
#' on the unit interval `[0, 1]`, including exact `0`s and `1`s from the
#' extreme-response gates and exact `mid` values. `dcogmod_choco()` returns
#' the density at each element of `x` - the log density if `log = TRUE` -
#' recycled to the length of the longest argument; at `0`, `1` and `mid` it
#' is the probability mass rather than a density. `cogmod_choco()` returns a
#' `brms::custom_family` object, to put on a `brms::bf()` formula.
#' `cogmod_choco_stanvars()` returns a `brms::stanvars` object holding the
#' family's Stan `functions` block, to pass to `brms::brm()`, and
#' `cogmod_choco_lpdf_expose()` compiles that Stan code and returns it as an
#' R function, for checking the density outside of a model. The remaining
#' functions are `brms` post-processing methods, called by `brms` rather than
#' directly: `log_lik_cogmod_choco()` returns a numeric vector holding one
#' log-likelihood value per posterior draw for observation `i`,
#' `posterior_predict_cogmod_choco()` a draws x 1 matrix of ratings simulated
#' for observation `i`, and `posterior_epred_cogmod_choco()` a
#' draws x observations matrix of expected ratings.
#'
#' @examples
#' # Simulate data with different parameterizations
#' # 10% at mid, 50/50 split otherwise, symmetric confidence/precision
#' x1 <- rcogmod_choco(
#' n = 5000, p = 0.5, confright = 0.5, precright = 4,
#' confleft = 0.5, precleft = 4, pex = 0.1, bex = 0.5, pmid = 0, mid = 0.5
#' )
#' hist(x1, breaks = 50, main = "CHOCO: Symmetric Confidence/Precision", xlab = "y")
#'
#' # No mid mass, 70% probability on right, higher confidence left (closer to 0)
#' x2 <- rcogmod_choco(
#' n = 5000, p = 0.7, confright = 0.5, precright = 3,
#' confleft = 0.8, precleft = 5, pex = 0.15, bex = 0.7, pmid = 0, mid = 0.5
#' )
#' hist(x2, breaks = 50, main = "CHOCO: Asymmetric p, Higher Conf Left", xlab = "y")
#'
#' # Lower confidence overall (closer to mid), high probability in the middle
#' x3 <- rcogmod_choco(
#' n = 5000, p = 0.5, confright = 0.2, precright = 3,
#' confleft = 0.2, precleft = 3, pex = 0, bex = 0.5, pmid = 0.05, mid = 0.5
#' )
#' hist(x3, breaks = 50, main = "CHOCO: Low confidence overall", xlab = "y")
#' @rdname rcogmod_choco
#' @export
rcogmod_choco <- function(
n,
p = 0.5,
confright = 0.5,
precright = 4,
confleft = 0.5,
precleft = 4,
pex = 0.1,
bex = 0.5,
pmid = 0,
mid = 0.5
) {
# --- Input Validation ---
if (any(n <= 0 | n != floor(n))) {
stop("n must be a positive integer.")
}
if (any(mid <= 0 | mid >= 1)) {
stop("mid must be between 0 and 1 (exclusive).")
}
if (any(pex < 0 | pex > 1)) {
stop("pex must be between 0 and 1.")
}
if (any(bex < 0 | bex > 1)) {
stop("bex must be between 0 and 1.")
}
if (any(p < 0 | p > 1)) {
stop("p must be between 0 and 1.")
}
if (any(pmid < 0 | pmid > 1)) {
stop("pmid must be between 0 and 1.")
}
if (any(confright <= 0 | confright >= 1)) {
stop("confright must be between 0 and 1 (exclusive).")
}
if (any(precright <= 0)) {
stop("precright must be positive.")
}
if (any(confleft <= 0 | confleft >= 1)) {
stop("confleft must be between 0 and 1 (exclusive).")
}
if (any(precleft <= 0)) {
stop("precleft must be positive.")
}
# Recycle
n_out <- n
p <- rep(p, length.out = n_out)
pex <- rep(pex, length.out = n_out)
bex <- rep(bex, length.out = n_out)
pmid <- rep(pmid, length.out = n_out)
mid <- rep(mid, length.out = n_out)
confright <- rep(confright, length.out = n_out)
precright <- rep(precright, length.out = n_out)
confleft <- rep(confleft, length.out = n_out)
precleft <- rep(precleft, length.out = n_out)
# Side probs
prob_not_mid <- 1 - pmid
prob_left <- prob_not_mid * (1 - p)
# Underlying Beta-Gate params
mu_right <- confright
phi_right <- precright
mu_left <- 1 - confleft
phi_left <- precleft
pex_right <- pex * bex
pex_left <- pex * (1 - bex)
# Draw side
u <- stats::runif(n_out)
out <- numeric(n_out)
is_mid <- u < pmid
is_left <- !is_mid & (u < pmid + prob_left)
is_right <- !(is_mid | is_left) # Remaining are right
# Assign mid
out[is_mid] <- mid[is_mid]
# Left component: draw from Beta-Gate on [0,1] then scale to [0,mid]
idxleft <- which(is_left)
n_left <- length(idxleft) # Store length
if (n_left > 0) {
# Check if > 0 instead of just length()
yleft <- rcogmod_betagate(
n_left, # Pass calculated n_left
mu = mu_left[idxleft],
phi = phi_left[idxleft],
pex = pex_left[idxleft],
bex = 0
)
out[idxleft] <- yleft * mid[idxleft]
}
# Right component: draw from Beta-Gate on [0,1] then scale to [mid,1]
idxright <- which(is_right)
n_right <- length(idxright) # Store length
if (n_right > 0) {
# Check if > 0
yright <- rcogmod_betagate(
n_right, # Pass calculated n_right
mu = mu_right[idxright],
phi = phi_right[idxright],
pex = pex_right[idxright],
bex = 1
)
out[idxright] <- mid[idxright] + yright * (1 - mid[idxright])
}
out
}
# Density function
#' @rdname rcogmod_choco
#' @export
dcogmod_choco <- function(
x,
p = 0.5,
confright = 0.5,
precright = 4,
confleft = 0.5,
precleft = 4,
pex = 0.1,
bex = 0.5,
pmid = 0,
mid = 0.5,
log = FALSE
) {
# Input validation with warnings
if (any(p < 0 | p > 1)) {
stop("p must be between 0 and 1")
}
if (any(confright <= 0 | confright >= 1)) {
stop("confright must be between 0 and 1")
}
if (any(precright <= 0)) {
stop("precright must be positive")
}
if (any(confleft <= 0 | confleft >= 1)) {
stop("confleft must be between 0 and 1")
}
if (any(precleft <= 0)) {
stop("precleft must be positive")
}
if (any(pex < 0 | pex > 1)) {
stop("pex must be between 0 and 1")
}
if (any(bex < 0 | bex > 1)) {
stop("bex must be between 0 and 1")
}
if (any(pmid < 0 | pmid > 1)) {
stop("pmid must be between 0 and 1")
}
if (any(mid <= 0 | mid >= 1)) {
stop("mid must be between 0 and 1 (exclusive)")
}
# Input & recycle
x <- as.numeric(x)
n <- length(x)
p <- rep(p, n)
pex <- rep(pex, n)
bex <- rep(bex, n)
pmid <- rep(pmid, n)
mid <- rep(mid, n)
confright <- rep(confright, n)
precright <- rep(precright, n)
confleft <- rep(confleft, n)
precleft <- rep(precleft, n)
eps <- 1e-10 # Define a small tolerance
# Side probs
prob_not_mid <- 1 - pmid
prob_left <- prob_not_mid * (1 - p)
prob_right <- prob_not_mid * p
# Underlying Beta-Gate params
mu_right <- confright
phi_right <- precright
mu_left <- 1 - confleft
phi_left <- precleft
pex_right <- pex * bex
pex_left <- pex * (1 - bex)
# Initialize density
dens <- numeric(n)
# Off support
dens[x < -eps | x > 1 + eps] <- 0
# Point-mass at mid
idx_mid <- which(abs(x - mid) < eps)
if (length(idx_mid)) {
dens[idx_mid] <- pmid[idx_mid]
}
# Point-mass at 0 and 1
idx0 <- which(abs(x - 0) < eps)
if (length(idx0)) {
mass0 <- dcogmod_betagate(
0,
mu = mu_left[idx0],
phi = phi_left[idx0],
pex = pex_left[idx0],
bex = 0
)
dens[idx0] <- prob_left[idx0] * mass0
}
idx1 <- which(abs(x - 1) < eps)
if (length(idx1)) {
mass1 <- dcogmod_betagate(
1,
mu = mu_right[idx1],
phi = phi_right[idx1],
pex = pex_right[idx1],
bex = 1
)
dens[idx1] <- prob_right[idx1] * mass1
}
# Continuous left part
idxleft <- which(x > eps & x < mid - eps)
if (length(idxleft)) {
yleft <- x[idxleft] / mid[idxleft]
fleft <- dcogmod_betagate(
yleft,
mu = mu_left[idxleft],
phi = phi_left[idxleft],
pex = pex_left[idxleft],
bex = 0
)
dens[idxleft] <- prob_left[idxleft] * fleft / mid[idxleft]
}
# Continuous right part
idxright <- which(x > mid + eps & x < 1 - eps)
if (length(idxright)) {
yright <- (x[idxright] - mid[idxright]) / (1 - mid[idxright])
fright <- dcogmod_betagate(
yright,
mu = mu_right[idxright],
phi = phi_right[idxright],
pex = pex_right[idxright],
bex = 1
)
dens[idxright] <- prob_right[idxright] * fright / (1 - mid[idxright])
}
# Return log-density if requested
if (log) {
dens <- ifelse(dens > 0, log(dens), -Inf)
}
dens
}
# Stan Functions and Custom Family for brms (CHOCO Model)
#' @keywords internal
.cogmod_choco_lpdf <- function() {
"
// mu is the probability p of the right side (0 < mu < 1) (named 'mu' as per Stan convention for main parameters)
real cogmod_choco_lpdf(
real y,
real mu, // P(right | not-mid)
real confright, // mu for right Beta-Gate
real precright, // phi for right Beta-Gate
real confleft, // mu_left = 1 - confleft
real precleft, // phi for left Beta-Gate
real pex, // proportion-extreme total
real bex, // balance of extremes (-> right vs left)
real pmid // P(mid)
) {
// Hardcoded Middle-Point
real mid = 0.5;
real eps = 1e-10;
// 1) Domain checks
if (
y < 0 || y > 1 ||
mu < 0 || mu > 1 ||
pmid < 0 || pmid > 1 ||
confright <= 0 || confright >= 1 ||
precright <= 0 ||
confleft <= 0 || confleft >= 1 ||
precleft <= 0 ||
pex < 0 || pex > 1 ||
bex < 0 || bex > 1
) {
return negative_infinity();
}
// 2) Mixture weights
real p_not_mid = 1 - pmid;
real p_left = p_not_mid * (1 - mu);
real p_right = p_not_mid * mu;
// 3) Point mass at mid
if (abs(y - mid) < eps) {
return (pmid > 0) ? log(pmid) : negative_infinity();
}
// 4) Left segment: y in [0, mid)
if (y < mid) {
if (p_left <= 0) return negative_infinity();
// Rescale to [0,1]
real y_rescaled = y / mid;
// Beta-Gate parameters for the left side
real mu_left = 1 - confleft;
real mu_ql = logit(mu_left);
real cutzero = pex * (1 - bex);
// point mass at 0
if (y_rescaled < eps) {
if (cutzero <= eps) return negative_infinity();
return log(p_left) + log1m_inv_logit(mu_ql - logit(cutzero));
}
// continuous (0 < y_rescaled <= 1)
real log_mid;
if (cutzero <= eps) {
log_mid = 0; // no lower cut
} else {
log_mid = log_inv_logit(mu_ql - logit(cutzero));
}
real shape1 = mu_left * precleft * 2;
real shape2 = (1 - mu_left) * precleft * 2;
real log_beta = beta_lpdf(y_rescaled | shape1, shape2);
real log_jacobian = -log(mid);
return log(p_left) + log_mid + log_beta + log_jacobian;
}
// 5) Right segment: y in (mid, 1]
if (y > mid) {
if (p_right <= 0) return negative_infinity();
// Rescale to [0,1]
real y_rescaled = (y - mid) / (1 - mid);
// Beta-Gate parameters for the right side
real mu_right = confright;
real mu_ql = logit(mu_right);
real cutone = 1 - pex * bex;
// point mass at 1
if (1 - y_rescaled < eps) {
if (cutone >= 1 - eps) return negative_infinity();
return log(p_right) + log_inv_logit(mu_ql - logit(cutone));
}
// continuous (0 <= y_rescaled < 1)
real log_mid;
if (cutone >= 1 - eps) {
log_mid = 0; // no upper cut
} else {
log_mid = log1m_inv_logit(mu_ql - logit(cutone));
}
real shape1 = mu_right * precright * 2;
real shape2 = (1 - mu_right) * precright * 2;
real log_beta = beta_lpdf(y_rescaled | shape1, shape2);
real log_jacobian = -log1m(mid);
return log(p_right) + log_mid + log_beta + log_jacobian;
}
// If no branch matched, return -Inf
return negative_infinity();
}
"
}
#' @rdname rcogmod_choco
#' @export
cogmod_choco_lpdf_expose <- function() {
insight::check_if_installed("cmdstanr")
stancode <- paste0(
"functions {\n",
.cogmod_choco_lpdf(),
"\n}"
)
mod <- cmdstanr::cmdstan_model(cmdstanr::write_stan_file(stancode))
mod$expose_functions()
mod$functions$cogmod_choco_lpdf
}
#' @rdname rcogmod_choco
#' @export
cogmod_choco_stanvars <- function() {
brms::stanvar(scode = .cogmod_choco_lpdf(), block = "functions")
}
#' @rdname rcogmod_choco
#' @param link_mu,link_confright,link_precright,link_confleft,link_precleft,link_pex,link_bex,link_pmid Link functions for the parameters.
#' @examples
#' cogmod_choco()
#'
#' # Example usage in a brms formula:
#' brms::bf(y ~ x1 + (1 | group),
#' confright ~ x3,
#' confleft ~ x3,
#' precright ~ 1,
#' precleft ~ 1,
#' pex ~ age,
#' bex ~ 1,
#' pmid ~ 1,
#' family = cogmod_choco()
#' )
#' @export
cogmod_choco <- function(
link_mu = "logit", link_confright = "logit", link_precright = "softplus",
link_confleft = "logit", link_precleft = "softplus",
link_pex = "logit", link_bex = "logit",
link_pmid = "logit"
) {
brms::custom_family(
name = "cogmod_choco",
dpars = c(
"mu", "confright", "precright", "confleft",
"precleft", "pex", "bex", "pmid"
),
links = c(
link_mu, link_confright, link_precright,
link_confleft, link_precleft, link_pex, link_bex,
link_pmid
),
lb = c(0, 0, 0, 0, 0, 0, 0, 0),
ub = c(1, 1, NA, 1, NA, 1, 1, 1),
type = "real"
)
}
# brms Post-processing Functions -------------------------------------------
#' @rdname rcogmod_choco
#' @export
log_lik_cogmod_choco <- function(i, prep) {
# Extract observed value for the i-th observation
if (!"Y" %in% names(prep$data)) stop("Outcome variable 'Y' not found in prep$data.")
y_scalar <- prep$data$Y[i]
# Extract model draws (vectors) for the i-th observation
mu <- brms::get_dpar(prep, "mu", i = i)
confright <- brms::get_dpar(prep, "confright", i = i)
precright <- brms::get_dpar(prep, "precright", i = i)
confleft <- brms::get_dpar(prep, "confleft", i = i)
precleft <- brms::get_dpar(prep, "precleft", i = i)
pex <- brms::get_dpar(prep, "pex", i = i)
bex <- brms::get_dpar(prep, "bex", i = i)
pmid <- brms::get_dpar(prep, "pmid", i = i)
n_draws <- length(mu)
if (n_draws == 0) {
return(numeric(0))
}
y_vec <- rep(y_scalar, length.out = n_draws)
# Calculate log-likelihood using the vectorized dcogmod_choco function
ll <- dcogmod_choco(
x = y_vec,
p = mu,
confright = confright,
precright = precright,
confleft = confleft,
precleft = precleft,
pex = pex,
bex = bex,
pmid = pmid,
mid = 0.5,
log = TRUE
)
ll[is.nan(ll) | is.na(ll)] <- -Inf
ll
}
#' @rdname rcogmod_choco
#' @export
posterior_predict_cogmod_choco <- function(i, prep, ...) {
# Extract draws for each parameter for the i-th observation
# brms::get_dpar should return vectors respecting prep$ndraws
mu <- brms::get_dpar(prep, "mu", i = i)
confright <- brms::get_dpar(prep, "confright", i = i)
precright <- brms::get_dpar(prep, "precright", i = i)
confleft <- brms::get_dpar(prep, "confleft", i = i)
precleft <- brms::get_dpar(prep, "precleft", i = i)
pex <- brms::get_dpar(prep, "pex", i = i)
bex <- brms::get_dpar(prep, "bex", i = i)
pmid <- brms::get_dpar(prep, "pmid", i = i)
# Determine number of draws from the length of the parameter vectors
# This length should correspond to prep$ndraws if ndraws was specified
n_draws <- length(mu)
if (n_draws == 0) {
# If get_dpar returns zero length, return an empty matrix.
# The number of rows should ideally match prep$ndraws, but 0 is safer if prep$ndraws is unreliable.
return(matrix(numeric(0), nrow = 0, ncol = 1))
}
# Generate exactly n_draws predictions using the extracted parameters
final_out <- rcogmod_choco(
n = n_draws, # Use n_draws determined from get_dpar length
p = mu,
confright = confright,
precright = precright,
confleft = confleft,
precleft = precleft,
pex = pex,
bex = bex,
pmid = pmid,
mid = 0.5
)
# Return as a single-column matrix, as required by brms
as.matrix(final_out)
}
#' @rdname rcogmod_choco
#' @export
posterior_epred_cogmod_choco <- function(prep) {
# Fetch parameters - these might be matrices (draws x obs) or vectors (draws)
mu <- brms::get_dpar(prep, "mu")
confright <- brms::get_dpar(prep, "confright")
confleft <- brms::get_dpar(prep, "confleft")
pex <- brms::get_dpar(prep, "pex")
bex <- brms::get_dpar(prep, "bex")
pmid <- brms::get_dpar(prep, "pmid")
# Note: precright and precleft are not needed for the expected value calculation
# Determine dimensions
# Use mu as reference; assume others conform or are vectors
if (is.matrix(mu)) {
n_draws <- nrow(mu)
n_obs <- ncol(mu)
} else { # Assume mu is a vector if not a matrix
n_draws <- length(mu)
n_obs <- prep$data$nobs # Get number of observations from prep data
# If mu is vector, reshape it to matrix for consistent indexing later
mu <- matrix(mu, nrow = n_draws, ncol = n_obs)
}
epred <- matrix(NA_real_, nrow = n_draws, ncol = n_obs)
# Helper function to get parameter values for observation j
# Handles both matrix and vector cases
get_param_j <- function(param, j) {
if (is.matrix(param)) {
return(param[, j, drop = FALSE]) # Use drop=FALSE to keep matrix structure if n_draws=1
} else {
return(param) # If vector, return the whole vector
}
}
for (j in seq_len(n_obs)) {
# Get parameters for observation j using the helper
mu_j <- get_param_j(mu, j)
confright_j <- get_param_j(confright, j)
confleft_j <- get_param_j(confleft, j)
pex_j <- get_param_j(pex, j)
bex_j <- get_param_j(bex, j)
pmid_j <- get_param_j(pmid, j)
# Side probabilities
p_not_mid <- 1 - pmid_j
p_left <- p_not_mid * (1 - mu_j)
p_right <- p_not_mid * mu_j
prob_mid <- pmid_j
# Underlying Beta-Gate params means and extreme probs
# Note: mu_left is 1 - confleft
mu_right_latent <- confright_j
mu_left_latent <- 1 - confleft_j
pex_right <- pex_j * bex_j
pex_left <- pex_j * (1 - bex_j)
# Expected value for latent left and right Beta-Gate components
# E[BetaGate(mu, phi, pex, bex=0)] = (1 - pex) * mu
# E[BetaGate(mu, phi, pex, bex=1)] = (1 - pex) * mu + pex * 1
e_latent_left <- (1 - pex_left) * mu_left_latent
e_latent_right <- (1 - pex_right) * mu_right_latent + pex_right
# Rescale expected values from latent [0,1] to observed scale
# Left side: [0, mid] -> mid * E_latent
# Right side: [mid, 1] -> mid + (1 - mid) * E_latent
mid <- 0.5 # Assuming fixed mid
e_left_rescaled <- mid * e_latent_left
e_right_rescaled <- mid + (1 - mid) * e_latent_right
# Combine weighted expected values
epred[, j] <- p_left * e_left_rescaled +
p_right * e_right_rescaled +
prob_mid * mid # E[mid] is just the threshold value
}
epred
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.