nl_loglik_gradient_parallel: Log-likelihood and gradient for Nested Logit model

View source: R/RcppExports.R

nl_loglik_gradient_parallelR Documentation

Log-likelihood and gradient for Nested Logit model

Description

Computes the log-likelihood and its gradient for the Nested Logit model using OpenMP for parallelization. Especially handles singleton nests by fixing their lambda parameters to 1. Only non-singleton nests have a inclusive value coefficient estimated in theta.

Usage

nl_loglik_gradient_parallel(
  theta,
  X,
  alt_idx,
  choice_idx,
  nest_idx,
  M,
  weights,
  use_asc = TRUE,
  include_outside_option = FALSE
)

Arguments

theta

(K + n_non_singleton_nests + n_delta) vector with model parameters. Order: ⁠[beta (K), lambda (n_non_singleton_nests), delta (n_delta)]⁠

X

sum(M) x K design matrix with covariates.

alt_idx

sum(M) x 1 vector with indices of alternatives; 1-based indexing.

choice_idx

N x 1 vector with indices of chosen alternatives; 0 for outside option, 1-based index relative to rows in X_i otherwise.

nest_idx

J x 1 vector with indices of nests for each alternative; 1-based indexing (1 to n_nests).

M

N x 1 vector with number of alternatives for each individual.

weights

N x 1 vector with weights for each observation.

use_asc

whether to use alternative-specific constants.

include_outside_option

whether to include outside option normalized to V=0, lambda=1.

Value

List with loglikelihood and gradient evaluated at input arguments

Examples


library(data.table)
set.seed(42)
N <- 50; J <- 4
dt <- data.table(id = rep(1:N, each = J), alt = rep(1:J, N))
dt[, `:=`(x1 = rnorm(.N), x2 = rnorm(.N))]
dt[, nest := ifelse(alt <= 2, "A", "B")]
dt[, choice := 0L]
dt[, choice := sample(c(1L, rep(0L, J - 1))), by = id]
d <- prepare_nl_data(dt, "id", "alt", "choice", c("x1", "x2"), "nest")
K_x <- ncol(d$X); K_l <- length(unique(d$nest_idx))
theta <- c(rep(0, K_x), rep(0.5, K_l), rep(0, J - 1))
result <- choicer:::nl_loglik_gradient_parallel(theta, d$X, d$alt_idx,
  d$choice_idx, d$nest_idx, d$M, d$weights)
result$objective


choicer documentation built on Sept. 5, 2026, 1:07 a.m.