Skip to contents

This document provides a detailed mathematical description of the nested logit (NL) model as implemented in src/nestlogit.cpp.

Notation

Symbol Description
i=1,…,Ni = 1, \ldots, N Index for individuals (choice situations)
j=1,…,Jij = 1, \ldots, J_i Index for inside alternatives available to individual ii
CiC_i Choice set of inside alternatives available in situation ii
jij_i The alternative chosen by individual ii
wiw_i Weight for individual ii
XijX_{ij} Row vector of covariates for individual ii and alternative jj (1×K1 \times K)
β\beta Coefficient vector (K×1K \times 1)
δj\delta_j Alternative-specific constant (ASC) for alternative jj
VijV_{ij} Systematic (deterministic) utility
BkB_k Global set of inside alternatives belonging to nest kk; situation ii contributes Bk∩CiB_k\cap C_i
k(j)k(j) The nest containing alternative jj
λk\lambda_k Inclusive value (dissimilarity) coefficient for nest kk
IkI_k Inclusive value for nest kk
P(j∣k)P(j \mid k) Probability of choosing jj conditional on choosing nest kk
PkP_k Marginal probability of choosing nest kk
PijP_{ij} Probability that individual ii chooses alternative jj

1. Model Definition

1.1 Utility Specification

The utility that individual ii derives from alternative jj is:

Uij=Vij+εij U_{ij} = V_{ij} + \varepsilon_{ij}

where the systematic utility is:

Vij=Xijβ+δj V_{ij} = X_{ij}\beta + \delta_j

The error term εij\varepsilon_{ij} follows a Generalized Extreme Value (GEV) distribution that induces within-nest correlation.

1.2 Nest Structure

The JJ inside alternatives are partitioned into KK mutually exclusive and exhaustive nests B1,…,BKB_1, \ldots, B_K. An outside option (alternative 0) with Vi0=0V_{i0} = 0 may optionally be included, and it is always assigned its own singleton nest with λ0=1\lambda_0 = 1.

1.3 Inclusive Value Coefficients

Each nest kk has a dissimilarity parameter λk>0\lambda_k > 0 that governs within-nest substitution:

  • λk=1\lambda_k = 1 corresponds to independent (MNL-like) alternatives within the nest.
  • 0<λk<10 < \lambda_k < 1 indicates positive within-nest correlation (the typical case).
  • λk>1\lambda_k > 1 is mathematically evaluable in the implemented probability formula but lies outside the standard globally RUM-consistent nested-GEV restriction 0<λk≤10<\lambda_k\leq1. It should not automatically be interpreted as a valid negative within-nest correlation parameter.

The optimizer in run_nestlogit() currently imposes the lower bound λk>0\lambda_k > 0 but does not impose λk≤1\lambda_k \leq 1. An estimate above one should therefore be read as a diagnostic about the nesting tree or maintained assumptions, not as evidence of especially strong within-nest substitution.

Singleton nests (nests with exactly one alternative) have λk\lambda_k fixed to 1 and are not estimated. Only non-singleton nests contribute λ\lambda parameters to θ\theta. The low-level parser requires at least one globally non-singleton nest; a specification in which every nest is a singleton is rejected rather than estimated as an MNL through this entry point.

Code reference: src/nestlogit.cpp

1.4 Alternative-Specific Constants (ASCs)

The ASC identification follows the same convention as MNL:

  • Without outside option (include_outside_option = FALSE): The first inside alternative’s ASC is fixed to zero (δ1=0\delta_1 = 0). The parameter vector contains J−1J-1 free ASC parameters.
  • With outside option (include_outside_option = TRUE): The outside option serves as the reference with Vi0=0V_{i0} = 0. All JJ inside alternatives have free ASC parameters.

Code reference: src/nestlogit.cpp


2. Log-Likelihood Function

2.1 Probability Decomposition

The nested logit choice probability decomposes as:

Pij=P(j∣k(j))⋅Pk(j) P_{ij} = P(j \mid k(j)) \cdot P_{k(j)}

The two components are derived from the GEV generating function.

2.2 Inclusive Value

The inclusive value for nest kk is the log-sum of scaled utilities within the nest:

Iik=∑j∈Bk∩Ciexp⁡(Vijλk) I_{ik} = \sum_{j \in B_k\cap C_i} \exp\!\left(\frac{V_{ij}}{\lambda_k}\right)

log⁡Iik=log⁡(∑j∈Bk∩Ciexp(Vijλk)) \log I_{ik} = \log\!\left(\sum_{j \in B_k\cap C_i} \exp\!\left(\frac{V_{ij}}{\lambda_k}\right)\right)

The rest of the article suppresses the ii subscript and writes IkI_k. Nests with no available alternative in CiC_i have log inclusive value −∞-\infty and contribute zero to the upper-level denominator.

2.3 Conditional Choice Probability

The probability of choosing alternative jj given that nest k(j)k(j) is chosen:

P(j∣k)=exp⁡(Vij/λk)Ik P(j \mid k) = \frac{\exp(V_{ij}/\lambda_k)}{I_k}

In log form:

log⁡P(j∣k)=Vijλk−log⁡Ik \log P(j \mid k) = \frac{V_{ij}}{\lambda_k} - \log I_k

2.4 Nest (Marginal) Probability

The probability of choosing nest kk:

Pk=exp⁡(λklog⁡Ik)∑lexp⁡(λllog⁡Il) P_k = \frac{\exp(\lambda_k \log I_k)}{\sum_{l} \exp(\lambda_l \log I_l)}

If an outside option is included, its contribution enters the denominator as exp⁡(λ0log⁡I0)=exp⁡(1⋅log⁡(exp⁡(0/1)))=exp⁡(0)=1\exp(\lambda_0 \log I_0) = \exp(1 \cdot \log(\exp(0/1))) = \exp(0) = 1.

In log form:

log⁡Pk=λklog⁡Ik−log⁡(∑lexp(λllogIl)) \log P_k = \lambda_k \log I_k - \log\!\left(\sum_l \exp(\lambda_l \log I_l)\right)

2.5 Joint Choice Probability

Taking logs of the joint probability:

log⁡Pij=log⁡P(j∣k(j))+log⁡Pk(j) \log P_{ij} = \log P(j \mid k(j)) + \log P_{k(j)}

log⁡Pij=Vijλk(j)−log⁡Ik(j)+λk(j)log⁡Ik(j)−log⁡Di \log P_{ij} = \frac{V_{ij}}{\lambda_{k(j)}} - \log I_{k(j)} + \lambda_{k(j)} \log I_{k(j)} - \log D_i

where Di=∑lexp⁡(λllog⁡Il)D_i = \sum_l \exp(\lambda_l \log I_l) (plus 1 if an outside option is present).

Code reference: src/nestlogit.cpp

2.6 Log-Likelihood

The log-likelihood is the weighted sum of log-probabilities of the observed choices:

ℓ(θ)=∑i=1Nwilog⁡Piji \ell(\theta) = \sum_{i=1}^{N} w_i \log P_{ij_i}

where θ=(β,λ,δ)\theta = (\beta, \lambda, \delta) and jij_i is the alternative chosen by individual ii.

Code reference: src/nestlogit.cpp

2.7 Log-Sum-Exp Trick for Numerical Stability

Two log-sum-exp stabilizations are applied.

Within-nest inclusive value. To compute log⁡Ik\log I_k without overflow, the implementation subtracts the maximum scaled utility in each nest:

log⁡Ik=Vmax⁡,k+log⁡(∑j∈Bkexp(Vijλk−Vmax⁡,k)) \log I_k = V_{\max,k} + \log\!\left(\sum_{j \in B_k} \exp\!\left(\frac{V_{ij}}{\lambda_k} - V_{\max,k}\right)\right)

where Vmax⁡,k=max⁡j∈BkVij/λkV_{\max,k} = \max_{j \in B_k} V_{ij}/\lambda_k.

Across-nest denominator. The denominator Di=∑lexp⁡(λllog⁡Il)D_i = \sum_l \exp(\lambda_l \log I_l) is similarly stabilized by subtracting max⁡lλllog⁡Il\max_l \lambda_l \log I_l before exponentiation.

Nests an individual does not face. A nest none of whose alternatives individual ii faces has log⁡Ik=−∞\log I_k = -\infty, so λklog⁡Ik=−∞\lambda_k \log I_k = -\infty when λk>0\lambda_k > 0: it never raises the maximum, and its term exp⁡(−∞)=0\exp(-\infty) = 0 adds nothing to DiD_i. Where every λk\lambda_k is positive and the nests outnumber an individual’s alternatives on average, the kernels therefore form the inclusive values, the maximum and DiD_i over the nests the individual faces, in increasing order and in the same two partial sums (by each nest’s index parity) as the loops over every nest, which changes no bit of the result. With a λk\lambda_k that is NaN, zero or negative (which no exported function accepts), they loop over every nest.

Code reference: src/nestlogit.cpp

2.8 Relation to Other Nested-Logit Parameterizations

The probabilities in §§2.3–2.4 are the utility-normalized GEV form used by choicer (McFadden 1978; Train 2009, Ch. 4): utility is scaled by 1/λk1/\lambda_k inside the conditional probability, and the inclusive value is multiplied by λk\lambda_k in the nest probability. Some software uses a normalization in which its reported systematic index enters the within-nest logit unscaled. These conventions can represent different definitions of utility coefficients and error scales; they are not generally numerically identical under a common-coefficient restriction, and their reported β\beta and λ\lambda cannot be compared without deriving the normalization mapping. It is too strong to label every unscaled convention non-RUM; the precise point is which utility, inclusive-value, and scale normalization is being estimated (Koppelman & Wen 1998; Hensher & Greene 2002; Heiss 2002).


3. Gradient Computation

3.1 Gradient with Respect to ViaV_{ia} (Utility Scores)

To derive the gradients with respect to β\beta and δ\delta, we first compute the derivative of the log-probability of the chosen alternative with respect to the systematic utility ViaV_{ia} of each alternative aa.

Let kik_i denote the chosen nest (i.e., k(ji)k(j_i)). The log-probability of the chosen alternative is:

log⁡Piji=log⁡P(ji∣ki)+log⁡Pki \log P_{ij_i} = \log P(j_i \mid k_i) + \log P_{k_i}

Derivative of the conditional term. Since log⁡P(j∣k)=Vij/λk−log⁡Ik\log P(j \mid k) = V_{ij}/\lambda_k - \log I_k and ∂log⁡Ik∂Via=1λk𝟏a∈BkP(a∣k)\frac{\partial \log I_k}{\partial V_{ia}} = \frac{1}{\lambda_k} \mathbf{1}_{a \in B_k} P(a \mid k):

∂log⁡P(ji∣ki)∂Via=1λki(𝟏a=ji−𝟏a∈BkiP(a∣ki)) \frac{\partial \log P(j_i \mid k_i)}{\partial V_{ia}} = \frac{1}{\lambda_{k_i}}\left(\mathbf{1}_{a = j_i} - \mathbf{1}_{a \in B_{k_i}} P(a \mid k_i)\right)

Derivative of the nest term. Using ∂log⁡Di∂Via=Pk(a)P(a∣k(a))=Pia\frac{\partial \log D_i}{\partial V_{ia}} = P_{k(a)} P(a \mid k(a)) = P_{ia}:

∂log⁡Pki∂Via=𝟏a∈BkiP(a∣ki)−Pia \frac{\partial \log P_{k_i}}{\partial V_{ia}} = \mathbf{1}_{a \in B_{k_i}} P(a \mid k_i) - P_{ia}

Combined. Adding both terms:

∂log⁡Piji∂Via=𝟏a=jiλki+(1−1λki)𝟏a∈BkiP(a∣ki)−Pia \frac{\partial \log P_{ij_i}}{\partial V_{ia}} = \frac{\mathbf{1}_{a = j_i}}{\lambda_{k_i}} + \left(1 - \frac{1}{\lambda_{k_i}}\right)\mathbf{1}_{a \in B_{k_i}} P(a \mid k_i) - P_{ia}

This is implemented as the vector grad_vec of length JiJ_i:

grad_vec[a]=−Pia+(1−1λki)𝟏a∈BkiP(a∣ki)+1λki𝟏a=ji \text{grad\_vec}[a] = -P_{ia} + \left(1 - \frac{1}{\lambda_{k_i}}\right) \mathbf{1}_{a \in B_{k_i}} P(a \mid k_i) + \frac{1}{\lambda_{k_i}} \mathbf{1}_{a = j_i}

Code reference: src/nestlogit.cpp

3.2 Gradient with Respect to β\beta

Since ∂Vij∂β=XijT\frac{\partial V_{ij}}{\partial \beta} = X_{ij}^T, the contribution from individual ii is:

∂ℓi∂β=wi∑j=1Jigrad_vec[j]⋅XijT=wiXiTgrad_vec \frac{\partial \ell_i}{\partial \beta} = w_i \sum_{j=1}^{J_i} \text{grad\_vec}[j] \cdot X_{ij}^T = w_i \, X_i^T \, \text{grad\_vec}

The full gradient is accumulated as a single BLAS matrix-vector product, identically to MNL.

Code reference: src/nestlogit.cpp

3.3 Gradient with Respect to δ\delta

Since ∂Vij∂δa=𝟏j=a\frac{\partial V_{ij}}{\partial \delta_a} = \mathbf{1}_{j = a}, the gradient entries are the corresponding elements of grad_vec, scattered to the appropriate positions in θ\theta:

∂ℓi∂δa=wi⋅grad_vec[a] \frac{\partial \ell_i}{\partial \delta_a} = w_i \cdot \text{grad\_vec}[a]

The same free-ASC convention as MNL applies (first inside alternative’s ASC excluded when no outside option).

Code reference: src/nestlogit.cpp

3.4 Gradient with Respect to λk\lambda_k

Define the within-nest probability-weighted mean utility:

V‾k=∑j∈BkP(j∣k)⋅Vij \bar{V}_k = \sum_{j \in B_k} P(j \mid k) \cdot V_{ij}

For the chosen nest (k=kik = k_i). The log-probability decomposes as:

log⁡Piji=Vijiλki−log⁡Iki⏟log⁡P(ji∣ki)+λkilog⁡Iki−log⁡Di⏟log⁡Pki \log P_{ij_i} = \underbrace{\frac{V_{ij_i}}{\lambda_{k_i}} - \log I_{k_i}}_{\log P(j_i \mid k_i)} + \underbrace{\lambda_{k_i} \log I_{k_i} - \log D_i}_{\log P_{k_i}}

Using ∂log⁡Ik∂λk=−V‾k/λk2\frac{\partial \log I_k}{\partial \lambda_k} = -\bar{V}_k / \lambda_k^2:

∂log⁡P(ji∣ki)∂λki=V‾ki−Vijiλki2 \frac{\partial \log P(j_i \mid k_i)}{\partial \lambda_{k_i}} = \frac{\bar{V}_{k_i} - V_{ij_i}}{\lambda_{k_i}^2}

∂log⁡Pki∂λki=(1−Pki)(logIki−V‾kiλki) \frac{\partial \log P_{k_i}}{\partial \lambda_{k_i}} = (1 - P_{k_i})\!\left(\log I_{k_i} - \frac{\bar{V}_{k_i}}{\lambda_{k_i}}\right)

Combining:

∂ℓi∂λki=wi[(1−Pki)(logIki−V‾kiλki)+V‾ki−Vijiλki2] \frac{\partial \ell_i}{\partial \lambda_{k_i}} = w_i \left[(1 - P_{k_i})\!\left(\log I_{k_i} - \frac{\bar{V}_{k_i}}{\lambda_{k_i}}\right) + \frac{\bar{V}_{k_i} - V_{ij_i}}{\lambda_{k_i}^2}\right]

For a non-chosen nest (k≠kik \neq k_i). The conditional probability P(ji∣ki)P(j_i \mid k_i) is independent of λk\lambda_k, so only the nest probability contributes:

∂log⁡Pki∂λk=−Pk(logIk−V‾kλk) \frac{\partial \log P_{k_i}}{\partial \lambda_k} = -P_k \!\left(\log I_k - \frac{\bar{V}_k}{\lambda_k}\right)

∂ℓi∂λk=−wiPk(logIk−V‾kλk) \frac{\partial \ell_i}{\partial \lambda_k} = -w_i \, P_k \!\left(\log I_k - \frac{\bar{V}_k}{\lambda_k}\right)

The common factor log⁡Ik−V‾k/λk\log I_k - \bar{V}_k / \lambda_k is labeled term_in_brackets in the code.

Code reference: src/nestlogit.cpp


4. Hessian Computation

This section documents the Hessian of the negated log-likelihood. The function nl_loglik_hessian_parallel returns H(θ)=−∇2ℓ(θ)H(\theta) = -\nabla^2 \ell(\theta), the same quantity that invert_hessian() expects (positive semi-definite at the MLE) and inverts equilibrated (§5.8). The sign convention matches the numeric oracle nl_loglik_numeric_hessian (which differences the negated gradient), so both functions are interchangeable as inputs to invert_hessian().

Two implementations are available:

  • nl_loglik_hessian_parallel — default (se_method = "hessian"): single-pass analytical Hessian derived below. Validated against the numeric oracle at a maximum absolute difference of ≈2.6×10−8\approx 2.6 \times 10^{-8} across the package’s test fixtures, well below the 10−610^{-6} tolerance those tests enforce. At extreme λk<0.1\lambda_k < 0.1, the oracle’s own finite-difference accuracy degrades; the analytical Hessian remains finite and symmetric throughout.
  • nl_loglik_numeric_hessian — retained oracle (se_method = "numeric"): central finite differences on the analytical gradient with step ϵi=10−6⋅max⁡(|θi|,1)\epsilon_i = 10^{-6} \cdot \max(|\theta_i|, 1). Use for diagnostic comparison or whenever a direct verification of the analytical path is required.

4.1 Notation and Scope

All notation follows §§0–3. Subscripts ii (individual), j/a/bj/a/b (alternative local indices within ii’s choice set, 0-based), and kk/ll (nest indices, 0-based) are used throughout. Additional symbols specific to this section:

Symbol Description
kik_i 0-based index of the chosen nest (−1-1 when outside option is chosen)
cac_a 0-based local index of the chosen inside alternative
V‾k\bar{V}_k ∑j∈BkP(j∣k)⋅Vij\sum_{j \in B_k} P(j \mid k) \cdot V_{ij} — P(⋅∣k)P(\cdot \mid k)-weighted mean utility in nest kk
TkT_k log⁡Ik−V‾k/λk\log I_k - \bar{V}_k / \lambda_k — the “bracket term” from §3.4
Ṽk2\widetilde{V}^2_k ∑j∈BkP(j∣k)⋅Vij2\sum_{j \in B_k} P(j \mid k) \cdot V_{ij}^2 — conditional second moment
VarVk\mathrm{VarV}_k Ṽk2−V‾k2\widetilde{V}^2_k - \bar{V}_k^2 — P(⋅∣k)P(\cdot\mid k)-weighted variance of VV in nest kk
𝐦k\mathbf{m}_k ∑j∈BkPij⋅𝐱ij\sum_{j \in B_k} P_{ij} \cdot \mathbf{x}_{ij} — PijP_{ij}-weighted mean of XX in nest kk (KK-vector)
𝐜k\mathbf{c}_k ∑j∈BkP(j∣k)⋅𝐱ij\sum_{j \in B_k} P(j \mid k) \cdot \mathbf{x}_{ij} — P(⋅∣k)P(\cdot\mid k)-weighted mean of XX in nest kk (KK-vector)
𝐒k(2)\mathbf{S}^{(2)}_k ∑j∈BkPij⋅𝐱ij𝐱ijT\sum_{j \in B_k} P_{ij} \cdot \mathbf{x}_{ij} \mathbf{x}_{ij}^T — PijP_{ij}-weighted second moment of XX (K×KK \times K)
𝐐k\mathbf{Q}_k ∑j∈BkP(j∣k)⋅𝐱ij𝐱ijT\sum_{j \in B_k} P(j \mid k) \cdot \mathbf{x}_{ij} \mathbf{x}_{ij}^T — P(⋅∣k)P(\cdot\mid k)-weighted second moment of XX (K×KK \times K)
𝐱‾i\bar{\mathbf{x}}_i ∑jPij⋅𝐱ij\sum_j P_{ij} \cdot \mathbf{x}_{ij} — PijP_{ij}-weighted global mean of XX for individual ii (KK-vector)

The negated per-individual log-likelihood contribution is fi=−wilog⁡Pi,caf_i = -w_i \log P_{i,c_a}. The full Hessian is the sum H=∑i=1NH(i)H = \sum_{i=1}^N H^{(i)} where H(i)=−wi∇2log⁡Pi,caH^{(i)} = -w_i \nabla^2 \log P_{i,c_a}.


4.2 V-Space Hessian QiQ_i

Because Vij=𝐱ijβ+δjV_{ij} = \mathbf{x}_{ij} \beta + \delta_j is linear in β\beta and δ\delta, the second derivatives with respect to these parameters factor through the mi×mim_i \times m_i V-space Hessian. Define:

Qi[a,b]=−∂2log⁡Pi,ca∂Via∂Vib Q_i[a, b] = -\frac{\partial^2 \log P_{i,c_a}}{\partial V_{ia} \, \partial V_{ib}}

Starting from the gradient formula (§3.1):

g[a]=∂log⁡Pi,ca∂Via=−Pia+(1−1λki)𝟏a∈BkiP(a∣ki)+𝟏a=caλki g[a] = \frac{\partial \log P_{i,c_a}}{\partial V_{ia}} = -P_{ia} + \left(1 - \frac{1}{\lambda_{k_i}}\right) \mathbf{1}_{a \in B_{k_i}} P(a \mid k_i) + \frac{\mathbf{1}_{a = c_a}}{\lambda_{k_i}}

differentiating with respect to VibV_{ib} yields:

∂g[a]∂Vib=−∂Pia∂Vib+(1−1λki)𝟏a∈Bki∂P(a∣ki)∂Vib \frac{\partial g[a]}{\partial V_{ib}} = -\frac{\partial P_{ia}}{\partial V_{ib}} + \left(1 - \frac{1}{\lambda_{k_i}}\right) \mathbf{1}_{a \in B_{k_i}} \frac{\partial P(a \mid k_i)}{\partial V_{ib}}

Partial derivative of PiaP_{ia} with respect to VibV_{ib}. Write ka=k(a)k_a = k(a), kb=k(b)k_b = k(b). Expanding Pia=P(a∣ka)⋅PkaP_{ia} = P(a \mid k_a) \cdot P_{k_a} via the product rule and using ∂Pka/∂Vib=Pka[𝟏kb=kaP(b∣ka)−Pib]\partial P_{k_a}/\partial V_{ib} = P_{k_a}[\mathbf{1}_{k_b=k_a} P(b\mid k_a) - P_{ib}]:

∂Pia∂Vib=Pia{𝟏ka=kb[𝟏a=bλka+P(b∣ka)(1−1λka)]−Pib} \frac{\partial P_{ia}}{\partial V_{ib}} = P_{ia} \left\{ \mathbf{1}_{k_a = k_b}\left[ \frac{\mathbf{1}_{a=b}}{\lambda_{k_a}} + P(b \mid k_a)\left(1-\frac{1}{\lambda_{k_a}}\right) \right] - P_{ib} \right\}

Partial derivative of P(a∣ki)P(a \mid k_i) with respect to VibV_{ib}. Non-zero only when a∈Bkia \in B_{k_i}:

∂P(a∣ki)∂Vib=1λki𝟏kb=kiP(b∣ki)(𝟏a=b−P(a∣ki)) \frac{\partial P(a \mid k_i)}{\partial V_{ib}} = \frac{1}{\lambda_{k_i}} \mathbf{1}_{k_b = k_i} P(b \mid k_i) \left(\mathbf{1}_{a=b} - P(a \mid k_i)\right)

Combined V-space Hessian (correct formula). Negating and combining:

Qi[a,b]=Pia{𝟏ka=kb[𝟏a=bλka+P(b∣ka)(1−1λka)]−Pib}−𝟏ka=ki𝟏kb=ki⋅1−1/λkiλki⋅P(a∣ki)(𝟏a=b−P(b∣ki))⏟Ca,b: chosen-nest correction \boxed{ Q_i[a, b] = P_{ia} \left\{ \mathbf{1}_{k_a = k_b}\left[ \frac{\mathbf{1}_{a=b}}{\lambda_{k_a}} +P(b \mid k_a)\left(1-\frac{1}{\lambda_{k_a}}\right) \right] - P_{ib} \right\} - \underbrace{\mathbf{1}_{k_a = k_i} \mathbf{1}_{k_b = k_i} \cdot \frac{1 - 1/\lambda_{k_i}}{\lambda_{k_i}} \cdot P(a \mid k_i)\bigl(\mathbf{1}_{a=b} - P(b \mid k_i)\bigr)}_{C_{a,b}: \text{ chosen-nest correction}} }

The chosen-nest correction Ca,bC_{a,b} is nonzero only when both aa and bb are in the chosen nest kik_i (and ki≥0k_i \geq 0). It arises from the (1−1/λki)(1 - 1/\lambda_{k_i}) factor in g[a]g[a] coupling the conditional probability gradient back to VibV_{ib}.

Structural notes and MNL limit:

  • For ka≠kbk_a \neq k_b: Qi[a,b]=−PiaPibQ_i[a,b] = -P_{ia} P_{ib} (cross-nest entries are the negative product of marginal probabilities, the familiar multinomial covariance term).
  • MNL limit (λk=1\lambda_k = 1 for all kk): Qi[a,b]=Pia(𝟏a=b−Pib)Q_i[a,b] = P_{ia}(\mathbf{1}_{a=b} - P_{ib}), the standard multinomial Hessian of −log⁡Pca-\log P_{c_a}. Own diagonal =Pia(1−Pia)= P_{ia}(1-P_{ia}); off-diagonal =−PiaPib= -P_{ia}P_{ib}. The chosen-nest correction vanishes because 1−1/λki=01 - 1/\lambda_{k_i} = 0.
  • When the outside option is chosen (ki=−1k_i = -1) or when λki=1\lambda_{k_i} = 1 (singleton chosen nest), Ca,b=0C_{a,b} = 0 for all pairs.

Implementation note: The implementation never forms QiQ_i as an mi×mim_i \times m_i matrix: it forms one column at a time, for each row with a free constant (§4.4, §4.8), and the outer-product decomposition used for the beta-beta block (§4.3) needs no entry of it.

Code reference: src/nestlogit.cpp


4.3 Beta-Beta Block

Since ∂Vij/∂βr=xij,r\partial V_{ij}/\partial \beta_r = x_{ij,r}:

Hβr,βs(i)=wi∑a∑bxia,r⋅Qi[a,b]⋅xib,s=wi𝐗iT𝐐i𝐗i H^{(i)}_{\beta_r, \beta_s} = w_i \sum_{a} \sum_{b} x_{ia,r} \cdot Q_i[a,b] \cdot x_{ib,s} = w_i \, \mathbf{X}_i^T \mathbf{Q}_i \mathbf{X}_i

The matrix product is decomposed into three terms that can be accumulated in a single nest-level pass, exploiting the outer-product structure of QiQ_i:

Term A — universal outer product (subtracted): −wi𝐱‾i𝐱‾iT -w_i \, \bar{\mathbf{x}}_i \, \bar{\mathbf{x}}_i^T

This arises from the −PiaPib-P_{ia} P_{ib} term universal to all pairs: ∑a,bxia,rPiaPibxib,s=x‾i,rx‾i,s\sum_{a,b} x_{ia,r} P_{ia} P_{ib} x_{ib,s} = \bar{x}_{i,r} \bar{x}_{i,s}.

Term B — per-nest within-nest correction (added), summed over all nests kk: +wi∑k[(1−1λk)𝐦k𝐜kT+1λk𝐒k(2)] +w_i \sum_{k} \left[ \left(1 - \frac{1}{\lambda_k}\right) \mathbf{m}_k \mathbf{c}_k^T + \frac{1}{\lambda_k} \mathbf{S}^{(2)}_k \right]

For singleton nests (λk=1\lambda_k = 1): (1−1/λk)=0(1 - 1/\lambda_k) = 0, so the contribution reduces to 𝐒k(2)\mathbf{S}^{(2)}_k.

Term C — chosen-nest correction (subtracted), only when ki≥0k_i \geq 0: −wi⋅1−1/λkiλki(𝐐ki−𝐜ki𝐜kiT) -w_i \cdot \frac{1 - 1/\lambda_{k_i}}{\lambda_{k_i}} \left( \mathbf{Q}_{k_i} - \mathbf{c}_{k_i} \mathbf{c}_{k_i}^T \right)

Here 𝐐ki−𝐜ki𝐜kiT\mathbf{Q}_{k_i} - \mathbf{c}_{k_i}\mathbf{c}_{k_i}^T is the P(⋅∣ki)P(\cdot\mid k_i)-weighted covariance of XX within the chosen nest.

Full beta-beta block (Hessian of the negated log-likelihood; positive semi-definite at the MLE): Hββ(i)=wi[−𝐱‾i𝐱‾iT+∑k((1−1λk)𝐦k𝐜kT+1λk𝐒k(2))−𝟏ki≥0⋅1−1/λkiλki(𝐐ki−𝐜ki𝐜kiT)] H^{(i)}_{\beta\beta} = w_i \left[ -\bar{\mathbf{x}}_i \bar{\mathbf{x}}_i^T + \sum_k \!\left(\!\left(1-\frac{1}{\lambda_k}\right)\mathbf{m}_k \mathbf{c}_k^T + \frac{1}{\lambda_k}\mathbf{S}^{(2)}_k\right) - \mathbf{1}_{k_i \geq 0} \cdot \frac{1-1/\lambda_{k_i}}{\lambda_{k_i}} \!\left(\mathbf{Q}_{k_i} - \mathbf{c}_{k_i}\mathbf{c}_{k_i}^T\right) \right]

MNL limit check. At λk=1\lambda_k = 1 for all kk: Term B =∑k𝐒k(2)=𝐗iTdiag(Pi)𝐗i= \sum_k \mathbf{S}^{(2)}_k = \mathbf{X}_i^T \mathrm{diag}(P_i) \mathbf{X}_i; Term C vanishes; the formula yields the standard MNL expression wi(𝐗iTdiag(Pi)𝐗i−𝐱‾i𝐱‾iT)w_i(\mathbf{X}_i^T \mathrm{diag}(P_i) \mathbf{X}_i - \bar{\mathbf{x}}_i \bar{\mathbf{x}}_i^T).

Code reference: src/nestlogit.cpp


4.4 Beta-Delta and Delta-Delta Blocks

Since ∂Vij/∂δa=𝟏j=a\partial V_{ij}/\partial \delta_a = \mathbf{1}_{j=a}, these blocks are direct projections of QiQ_i onto free-ASC alternatives.

Delta-delta block (for free-ASC alternatives a′a' and b′b'): Hδa′,δb′(i)=wi⋅Qi[a′,b′] H^{(i)}_{\delta_{a'}, \delta_{b'}} = w_i \cdot Q_i[a', b']

Beta-delta block (for covariate index rr and free-ASC alternative b′b'): Hβr,δb′(i)=wi∑axia,r⋅Qi[a,b′]=wi(𝐗iT𝐐i[:,b′])r H^{(i)}_{\beta_r, \delta_{b'}} = w_i \sum_{a} x_{ia,r} \cdot Q_i[a, b'] = w_i \, \bigl(\mathbf{X}_i^T \mathbf{Q}_i[:, b']\bigr)_r

Both blocks use the column Qi[:,b′]Q_i[:, b'] of each row b′b' with a free constant, formed once (§4.8). No additional auxiliary quantities are required.

ASC normalization. Without an outside option, the first inside alternative’s ASC is fixed to zero: free-ASC alternatives satisfy alt_idx0[a] > 0, mapped to theta positions delta_start_idx + alt_idx0[a] - 1.

Code reference: src/nestlogit.cpp


4.5 Lambda-V Cross Derivative

The lambda parameters enter nonlinearly through both log⁡Ik\log I_k and the nest probabilities, so cross-derivatives between λk\lambda_k and β/δ\beta/\delta must be computed via the chain rule. Define:

db(k)=∂gλk∂Vib,gλk=∂log⁡Pi,ca∂λk d^{(k)}_b = \frac{\partial g_{\lambda_k}}{\partial V_{ib}}, \qquad g_{\lambda_k} = \frac{\partial \log P_{i,c_a}}{\partial \lambda_k}

Key intermediates (derived from §3.4):

∂Tk∂Vib=−𝟏k(b)=kP(b∣k)Vib−V‾kλk2,∂Pk∂Vib=Pk[𝟏k(b)=kP(b∣k)−Pib] \frac{\partial T_k}{\partial V_{ib}} = -\mathbf{1}_{k(b)=k} P(b \mid k) \frac{V_{ib} - \bar{V}_k}{\lambda_k^2}, \qquad \frac{\partial P_k}{\partial V_{ib}} = P_k \bigl[\mathbf{1}_{k(b)=k} P(b \mid k) - P_{ib}\bigr]

For non-chosen nests (k≠kik \neq k_i), using gλk=−PkTkg_{\lambda_k} = -P_k T_k: db(k)=PkTkPib+𝟏k(b)=kPkP(b∣k)[Vib−V‾kλk2−Tk] d^{(k)}_b = P_k T_k P_{ib} + \mathbf{1}_{k(b)=k} P_k P(b \mid k) \left[\frac{V_{ib} - \bar{V}_k}{\lambda_k^2} - T_k\right]

The first term is a universal “shift” proportional to PibP_{ib}; the second is the within-nest correction active only for b∈Bkb \in B_k.

For the chosen nest (k=kik = k_i, only when ki≥0k_i \geq 0), using gλki=(1−Pki)Tki+(V‾ki−Vca)/λki2g_{\lambda_{k_i}} = (1-P_{k_i})T_{k_i} + (\bar{V}_{k_i} - V_{c_a})/\lambda_{k_i}^2: db(ki)=PkiTkiPib−𝟏b=caλki2+𝟏k(b)=kiP(b∣ki)[−PkiTki+Vib−V‾kiλki2(Pki−1+1λki)+1λki2] d^{(k_i)}_b = P_{k_i} T_{k_i} P_{ib} - \frac{\mathbf{1}_{b = c_a}}{\lambda_{k_i}^2} + \mathbf{1}_{k(b)=k_i} P(b \mid k_i) \left[ -P_{k_i} T_{k_i} + \frac{V_{ib} - \bar{V}_{k_i}}{\lambda_{k_i}^2} \left(P_{k_i} - 1 + \frac{1}{\lambda_{k_i}}\right) + \frac{1}{\lambda_{k_i}^2} \right]

The extra −1/λki2-1/\lambda_{k_i}^2 term for b=cab = c_a arises from differentiating the (V‾ki−Vca)/λki2(\bar{V}_{k_i} - V_{c_a})/\lambda_{k_i}^2 component of the chosen-nest gradient.


4.6 Lambda-Beta and Lambda-Delta Blocks

Using ∂Vib/∂βr=xib,r\partial V_{ib}/\partial \beta_r = x_{ib,r} and ∂Vib/∂δb′=𝟏b=b′\partial V_{ib}/\partial \delta_{b'} = \mathbf{1}_{b=b'}:

Hλk,βr(i)=−wi∑bdb(k)⋅xib,r=−wi(𝐗iT𝐝(k))r H^{(i)}_{\lambda_k, \beta_r} = -w_i \sum_{b} d^{(k)}_b \cdot x_{ib,r} = -w_i \, \bigl(\mathbf{X}_i^T \mathbf{d}^{(k)}\bigr)_r

Hλk,δb′(i)=−widb′(k) H^{(i)}_{\lambda_k, \delta_{b'}} = -w_i \, d^{(k)}_{b'}

Both are filled symmetrically. Singleton nests (theta index =−1= -1) contribute no rows or columns to these blocks.

Code reference: src/nestlogit.cpp


4.7 Lambda-Lambda Block

Differentiating gλkg_{\lambda_k} with respect to λl\lambda_l, using: ∂Tk∂λk=VarVkλk3≥0,∂Pk∂λk=Pk(1−Pk)Tk,∂Pk∂λl=−PkPlTl(l≠k),∂Tk∂λl=0(l≠k) \frac{\partial T_k}{\partial \lambda_k} = \frac{\mathrm{VarV}_k}{\lambda_k^3} \geq 0, \qquad \frac{\partial P_k}{\partial \lambda_k} = P_k (1 - P_k) T_k, \qquad \frac{\partial P_k}{\partial \lambda_l} = -P_k P_l T_l \;(l \neq k), \qquad \frac{\partial T_k}{\partial \lambda_l} = 0 \;(l \neq k)

Off-diagonal k≠lk \neq l (any combination of chosen/non-chosen nests): Hλk,λl(i)=−wiPkPlTkTl H^{(i)}_{\lambda_k, \lambda_l} = -w_i \, P_k P_l T_k T_l

This formula holds uniformly regardless of whether kk or ll equals kik_i. It can be negative (whenever TkT_k and TlT_l share the same sign), reflecting correlation between nest-level inclusive values.

Diagonal k≠kik \neq k_i (non-chosen nest): Hλk,λk(i)=wi[Pk(1−Pk)Tk2+PkVarVkλk3] H^{(i)}_{\lambda_k, \lambda_k} = w_i \left[ P_k (1 - P_k) T_k^2 + \frac{P_k \, \mathrm{VarV}_k}{\lambda_k^3} \right]

The first term is a Fisher-information-type squared-gradient term; the second is positive and captures curvature from TkT_k’s dependence on λk\lambda_k through the within-nest utility variance.

Diagonal k=kik = k_i (chosen nest, only when ki≥0k_i \geq 0): Hλki,λki(i)=wi[Pki(1−Pki)Tki2−(1−Pki)VarVkiλki3+VarVkiλki4+2(V‾ki−Vca)λki3] H^{(i)}_{\lambda_{k_i}, \lambda_{k_i}} = w_i \left[ P_{k_i}(1 - P_{k_i}) T_{k_i}^2 - \frac{(1 - P_{k_i}) \mathrm{VarV}_{k_i}}{\lambda_{k_i}^3} + \frac{\mathrm{VarV}_{k_i}}{\lambda_{k_i}^4} + \frac{2(\bar{V}_{k_i} - V_{c_a})}{\lambda_{k_i}^3} \right]

The chosen-nest diagonal differs from the non-chosen formula because the (V‾ki−Vca)/λki2(\bar{V}_{k_i} - V_{c_a})/\lambda_{k_i}^2 term in gλkig_{\lambda_{k_i}} contributes −VarVki/λki4−2(V‾ki−Vca)/λki3-\mathrm{VarV}_{k_i}/\lambda_{k_i}^4 - 2(\bar{V}_{k_i} - V_{c_a})/\lambda_{k_i}^3 when differentiated. Since the chosen alternative tends to have above-average utility within its nest (Vca≥V‾kiV_{c_a} \geq \bar{V}_{k_i} in expectation), the last term is typically negative, making the chosen-nest diagonal somewhat smaller than the non-chosen counterpart.

When the outside option is chosen (ki=−1k_i = -1), all lambda diagonals use the non-chosen formula.

Code reference: src/nestlogit.cpp


4.8 Single-Pass Implementation and Auxiliary Accumulations

All six blocks are accumulated in a single parallel pass over individuals. The per-nest auxiliary quantities below are accumulated in an inner loop over alternatives at O(mi)O(m_i) cost before any block is computed, for the nests the situation offers only: a nest it does not offer has zero sums and contributes nothing.

Per-nest scalars (zero-initialized per individual, indexed by nest kk):

Quantity Formula Blocks that use it
V‾k\bar{V}_k ∑j∈BkP(j∣k)Vj\sum_{j \in B_k} P(j\mid k) V_j TkT_k, lambda-lambda, lambda-V cross
Ṽk2\widetilde{V}^2_k ∑j∈BkP(j∣k)Vj2\sum_{j \in B_k} P(j\mid k) V_j^2 VarVk\mathrm{VarV}_k for lambda-lambda diagonal
TkT_k log⁡Ik−V‾k/λk\log I_k - \bar{V}_k/\lambda_k lambda-lambda (all entries), lambda-V cross
VarVk\mathrm{VarV}_k Ṽk2−V‾k2\widetilde{V}^2_k - \bar{V}_k^2 lambda-lambda diagonal

Per-nest K-vectors:

Quantity Formula Blocks that use it
𝐦k\mathbf{m}_k ∑j∈BkPij𝐱j\sum_{j \in B_k} P_{ij} \mathbf{x}_j beta-beta Term B
𝐜k\mathbf{c}_k ∑j∈BkP(j∣k)𝐱j\sum_{j \in B_k} P(j\mid k) \mathbf{x}_j beta-beta Terms B and C

Per-nest K×KK \times K matrices:

Quantity Formula Blocks that use it
𝐒k(2)\mathbf{S}^{(2)}_k ∑j∈BkPij𝐱j𝐱jT\sum_{j \in B_k} P_{ij} \mathbf{x}_j \mathbf{x}_j^T beta-beta Term B
𝐐k\mathbf{Q}_k ∑j∈BkP(j∣k)𝐱j𝐱jT\sum_{j \in B_k} P(j\mid k) \mathbf{x}_j \mathbf{x}_j^T beta-beta Term C (formed for the chosen nest kik_i only)

Global per-individual: 𝐱‾i=∑jPij𝐱j=∑k𝐦k\bar{\mathbf{x}}_i = \sum_j P_{ij} \mathbf{x}_j = \sum_k \mathbf{m}_k (beta-beta Term A).

Compact blocks. A situation’s terms touch only its compact block: the KK coefficients, the dissimilarities of the non-singleton nests it offers (those whose log⁡Ik\log I_k is finite), and the free constants of its alternatives, in increasing order. QiQ_i is formed a column at a time (no mi×mim_i \times m_i matrix), the symmetric K×KK \times K sums are kept as packed upper triangles, and the lambda-lambda block runs over the pairs of touched nests. A situation’s blocks thus cost O(mi2K+miK2)O(m_i^2K + m_iK^2), whatever the number of alternatives in the model; its probabilities still visit every nest.

OpenMP structure. The outer loop over individuals is parallelized with dynamic scheduling. Each thread adds into its own packed upper triangle while the threads’ triangles fit in a budget (2 GiB by default), and above it into a shared result: each thread keeps the coefficients’ rows private (and the dissimilarities’, while the threads’ copies of them fit in the budget) and adds the rest atomically. All of it is allocated before the loop, once the kernel’s memory estimate has been checked against options(choicer.max_memory) or the physical memory.

Symmetrization and sanitization. QiQ_i and Term B’s 𝐦k𝐜kT\mathbf{m}_k\mathbf{c}_k^T are symmetric in exact arithmetic (Pij=PkP(j∣k)P_{ij} = P_k P(j\mid k), so 𝐦k=Pk𝐜k\mathbf{m}_k = P_k\mathbf{c}_k) but not in floating point. Each entry therefore receives the mean of its two transposed terms, H←(H+HT)/2H \leftarrow (H + H^T)/2 computed term by term (halving is exact except for subnormal terms, so no running sum is doubled on the way); any remaining non-finite entries are zeroed.

Singleton-nest handling. Singleton nests (λk=1\lambda_k = 1, theta index =−1= -1) contribute nothing to the lambda-lambda, lambda-beta, or lambda-delta blocks. Their beta-beta contribution via Term B simplifies to 𝐒k(2)\mathbf{S}^{(2)}_k (since 1−1/λk=01 - 1/\lambda_k = 0).

Per-individual weights. Every contribution is multiplied by wiw_i (WESML weight; equals 1 for unweighted data).

Code reference: src/nestlogit.cpp


5. Implementation Details

5.1 Parameter Vector Structure

The full parameter vector θ\theta is organized as:

Block Indices Length Description
β\beta [0,K)[0, K) KK Coefficients for design matrix XX
λ\lambda [K,K+Kλ)[K, K + K_\lambda) KλK_\lambda Non-singleton nest dissimilarity parameters
δ\delta [K+Kλ,K+Kλ+Jasc)[K + K_\lambda, K + K_\lambda + J_{\text{asc}}) 00, J−1J-1, or JJ Free alternative-specific constants

where KλK_\lambda is the number of non-singleton nests and Jasc=0J_{\text{asc}}=0 when use_asc = FALSE, J−1J-1 without an outside option, or JJ with an outside option.

Code reference: src/nestlogit.cpp

5.2 Singleton Nest Handling

At startup, the implementation identifies which nests are singletons (contain exactly one alternative). These nests: - Have their λ\lambda fixed to 1 (no contribution to the upper-level logit denominator beyond their single utility term). - Are excluded from the estimated parameter vector. - Are tracked via nest_k_to_theta_idx, an integer vector of length KK where entry kk holds the corresponding index in θ\theta for non-singleton nests and −1-1 for singletons.

This ensures that the NL model degenerates gracefully to MNL on a per-nest basis when nests are singletons.

Code reference: src/nestlogit.cpp

5.3 Data Organization

  • Design matrix XX: Stacked matrix of dimension (∑iMi)×K(\sum_i M_i) \times K, where MiM_i is the number of inside alternatives for individual ii.
  • alt_idx: 1-based indices mapping rows of XX to global alternative IDs.
  • nest_idx: 1-based nest assignment of length JJ (number of unique inside alternatives), not length ∑Mi\sum M_i. Accessed via nest_idx.elem(alt_idx0_i) to handle varying choice sets.
  • choice_idx: 1-based local row position of the chosen inside alternative within each situation’s block; 0 for the outside option.
  • Prefix sums SS: Used for efficient slicing into the stacked data: Si=∑j<iMjS_i = \sum_{j < i} M_j.

Code reference: src/nestlogit.cpp

5.4 Base Utilities

The systematic utilities Vij=Xijβ+δjV_{ij} = X_{ij}\beta + \delta_j of an individual’s alternatives are formed inside the parallel loop, when the individual’s turn comes, from its rows of XX in place:

for each individual i (in parallel):
  V_i = X_i * beta                   // each row's sum over the columns, in order
  if use_asc: V_i += delta[alt_idx0_i]

Nothing of the stacked length is formed per evaluation, and the thread that reads an individual’s rows of XX for its utilities is the one that then uses them for its gradient. The rows are taken sixteen at a time (then eight, four and two), their sums held in registers while one loop runs over the KK columns. A single product XβX\beta ahead of the loop, as the kernels formed before 0.3.0, wrote a vector as long as the design once per column and did not speed up with the threads.

Each row’s sum takes its columns in order from zero (a product and an addition per column, fused into one operation where the package is compiled for a processor that has it) and its constant last. A row’s utility therefore depends neither on the choice set it is stacked in, nor on the thread count, nor on the BLAS that R is linked to. The multinomial logit’s kernels form theirs with the same routine, and so do both models’ share inversions.

Code reference: BaseUtil in src/choicer_internal.h

5.5 OpenMP Parallelization

The implementation parallelizes over individuals using OpenMP: - Each thread keeps local accumulators (the log-likelihood and gradient, or a packed upper triangle of the Hessian or BHHH matrix, §4.8; one thread adds into the result itself) and its working arrays (the probabilities, the individual’s nests, a copy of its covariate rows where Armadillo’s product needs one), all allocated before the parallel loop once the kernel’s memory estimate has been checked, so that no individual allocates. - The Hessian’s and BHHH matrix’s triangles are added after the loop in thread order (above the budget, the shared entries atomically during it); the log-likelihood and gradient in an order that can vary between calls. - The loops over the dissimilarities (their gradient, scores and Hessian terms) run over the nests the individual faces, and so do the inclusive values and nest probabilities where every λk\lambda_k is positive and the nests outnumber the alternatives on average (§2.7). - Dynamic scheduling balances load across individuals with varying choice set sizes, each dispatch handing a thread about 256 stacked rows, at least one individual (CHOICER_CHUNK_ROWS at compile time), and fewer where the largest choice set has more than eight times the mean rows, so that no dispatch holds more than about 2,048. - The elasticity and diversion-ratio kernels add each individual’s terms into a J×JJ \times J sum, as the multinomial logit’s do: one thread into the result itself, TT threads into copies of their own while those fit in 2 GiB, and beyond that into the shared result atomically, the outside option’s row and column kept per thread; its memory is checked before it is allocated.

Code reference: src/nestlogit.cpp

5.6 Negated Objectives

The likelihood/gradient kernel returns: - −ℓ(θ)-\ell(\theta) (negated log-likelihood) - −∇ℓ(θ)-\nabla\ell(\theta) (negated gradient)

for compatibility with minimization routines (e.g., nloptr) that minimize a loss function rather than maximize a likelihood. The analytical and numeric Hessian kernels return −∇2ℓ-\nabla^2\ell; the BHHH kernel instead returns the positive-semidefinite OPG information approximation ∑iwisisiT\sum_iw_is_is_i^T.

5.7 Finite-Value Guards

The likelihood kernel replaces a non-finite chosen log probability by −1010-10^{10}. If the final negated objective is non-finite it returns 101010^{10} and a zero gradient; isolated non-finite gradient entries are zeroed. The analytical Hessian skips a situation whose chosen log probability is non-finite, adds the mean of each pair of transposed terms (§4.8), and replaces any remaining non-finite entries by zero. These rules are optimizer failure guards, not part of the regular finite-parameter nested-logit criterion; encountering them calls for rescaling or revising the specification. The likelihood kernel’s list also holds overflow, TRUE where it replaced anything (a clamped log probability, the sentinel, a gradient entry set to zero, as where an unchosen nest’s inclusive value overflows and the nest drops out of the denominator, leaving the chosen probability finite and too high): the optimizers do not see it, and the polish (§5.9) rejects a trial point that sets it.

Code reference: src/nestlogit.cpp; the flag, logit_sanitize() in src/choicer_internal.h

5.8 Inverting the Information

Every reported variance of θ̂\hat\theta is the inverse of an estimate of the information matrix, or a sandwich built on one: V=ℐ−1V = \mathcal{I}^{-1} with ℐ\mathcal{I} the negated Hessian −∇2ℓ(θ̂)-\nabla^2 \ell(\hat\theta) of §4 (se_method = "hessian", or its finite-difference oracle under "numeric") or the BHHH matrix ∑iwisisi⊤\sum_i w_i\, s_i s_i^{\top} of §5.6 ("bhhh"), or V=A−1BA−1V = A^{-1} B A^{-1} with the bread AA and meat BB of §7.3 ("sandwich") or §7.5 ("cluster"). In the data’s units the diagonal of ℐ\mathcal{I} can span many orders of magnitude: a covariate measured in thousands next to one measured in thousandths, or the constant of an alternative a handful of individuals chose next to that of one most chose. Inverted as it is, such a matrix can be refused as computationally singular although only the units make it so (solve() refuses a matrix whose estimated reciprocal condition number falls below the machine epsilon, and the units alone can push it there), and a sandwich built on it can lose digits. Every fit, whatever the coordinates its optimizer used (scale_vars, "bhhh" by default; §1.5 of the mixed logit article), therefore inverts the equilibrated matrix:

V=D(DℐD)−1D,D=diag(d),d=2round(−12log⁡2|diag(ℐ)|), V = D\,(D \mathcal{I} D)^{-1} D, \qquad D = \mathrm{diag}(d), \quad d = 2^{\,\mathrm{round}(-\frac{1}{2}\log_2 |\mathrm{diag}(\mathcal{I})|)},

with diag(ℐ)\mathrm{diag}(\mathcal{I}) the vector of the diagonal entries of ℐ\mathcal{I} and the functions applied elementwise: dd holds the powers of two nearest, on a log scale, to the inverse square roots of the diagonal’s magnitudes, with an entry of 1 where the diagonal entry is zero or not finite and every entry clamped to [2−500,2500][2^{-500}, 2^{500}]. For the sandwich, V=DVDDV = D\,V_D\,D with VD=(DAD)−1(DBD)(DAD)−1V_D = (DAD)^{-1} (DBD) (DAD)^{-1} and DD from AA. Any DD leaves VV unchanged in exact arithmetic, and powers of two make the products with DD exact too, barring overflow or underflow: only the LULU factorization and the solves round (for the sandwich, also the symmetrization below), on a matrix whose diagonal is within a factor of two of one in magnitude except where a diagonal entry is zero or not finite, or an entry of dd is clamped. The magnitude of the diagonal is used so that an information that is not positive definite (away from a maximum) is equilibrated too, and its negative variances reported: their standard errors are NA, with a message.

DℐDD \mathcal{I} D is formed in one working copy, which LAPACK factors in place (LULU with partial pivoting) with solve()’s checks: a pivot that is exactly zero is an error, and so, when every factor is finite, is a reciprocal condition number (estimated in the 1-norm) below the machine epsilon; either error leaves the fit without a variance, its standard errors NA, with a message. The identity is then solved against the factors into the result, as reference LAPACK’s dgesv does for solve(), with two p×pp \times p matrices besides ℐ\mathcal{I} (pp the number of parameters) where solve() holds three. The sandwich is solved twice against the factors of DADDAD, first (DAD)Y=DBD(DAD)\,Y = DBD and then the transposed system (DAD)⊤VD⊤=Y⊤(DAD)^{\top} V_D^{\top} = Y^{\top}, without forming an inverse: two p×pp \times p matrices besides AA and BB where an explicit inverse and two products hold four, and 423p34\tfrac{2}{3} p^3 operations against 623p36\tfrac{2}{3} p^3. VDV_D is symmetrized, (VD+VD⊤)/2(V_D + V_D^{\top})/2, before DD is applied. At p=17,000p = 17{,}000 each such matrix takes 2.3 GB. The working copy is freed as the call returns, and the package’s own passes over whole matrices (the scaling, the scan of the factors for non-finite entries, the transposition and the symmetrization) run in parallel over columns, without sums across threads, so they do not depend on the number of threads. The fit and post-hoc vcov(fit, type = ) and wesml_vcov() take this same route.

Against an exact computation on the package’s reference battery and tests (963 inversions of 477 distinct matrices, of 2 to 13 parameters), a raw inversion refused 52 as singular; equilibrated, 44 of them, with raw condition numbers from 4.5×10184.5 \times 10^{18} to 1.2×10281.2 \times 10^{28}, had condition numbers below 20 and came out with standard errors within about 10−1510^{-15} relative of exact, while the other eight stayed ill-conditioned or singular. Equilibration removes the ill-conditioning that the parameters’ units cause, not the likelihood’s own: a matrix that stays ill-conditioned after it (a likelihood nearly flat along a combination of parameters, which no rescaling of the parameters one by one removes) keeps only the digits its condition number allows, by any inversion, and one singular to working precision is refused either way. Some of the package’s nested logit test designs give such matrices, with condition numbers up to 7×10127 \times 10^{12} after equilibration; two more, near 101610^{16}, are refused (six inversions). Where an exact variance is zero, as at some degenerate test fits, the computed one is rounding noise of either sign, and a negative one gets an NA standard error like any negative variance.

Code reference: invert_hessian(), .sandwich_combine() and .jacobi_scale() in R/classes.R; equilibrated_inverse() and equilibrated_sandwich() in src/vcov.cpp.

5.9 Polishing the Optimizer’s Solution

run_nestlogit(polish = ) follows the optimizer with the Newton phase of the mixed logit (§5.7 there), which finishes the climb to the maximum the optimizer approached and certifies it; the estimator does not change. With gg the gradient of −ℓ-\ell and CC the curvature, the analytic information ℐ=−∇2ℓ\mathcal{I} = -\nabla^2 \ell of §4 (polish = "newton") or the BHHH matrix ∑iwisisi⊤\sum_i w_i\, s_i s_i^{\top} of §5.6 ("bhhh", its weights unsquared), the polish converges when the Newton decrement ν=12g⊤C−1g\nu = \tfrac{1}{2}\, g^{\top} C^{-1} g, over the mean weight, falls below tol_decrement (10−810^{-8}). On a positive definite ℐ\mathcal{I} the remaining Newton step then moves every linear combination of the estimates by at most 2ν\sqrt{2\nu} of its Hessian standard error; with "bhhh" the bound is in robust standard errors (for an unweighted fit; with weights, in the metric of ℐ−1ℬℐ−1\mathcal{I}^{-1} \mathcal{B} \mathcal{I}^{-1} with ℬ\mathcal{B}’s weights unsquared), and a small BHHH decrement on its own shows only a stationary point. The steps, their damping and maximum length, the line search and the projection onto the dissimilarities’ bound are those of the mixed logit’s §5.7.

Curvature. For given dissimilarities all at most 1 the log-likelihood is concave in (β,δ)(\beta, \delta): each log⁡Pij=Vij/λk+(λk−1)log⁡Ik−log⁡∑lexp⁡(λllog⁡Il)\log P_{ij} = V_{ij}/\lambda_k + (\lambda_k - 1) \log I_k - \log \sum_l \exp(\lambda_l \log I_l) (the sum also holding the outside option’s 1, where there is one) adds to a linear term a nonpositive multiple of a log-sum-exp, which is convex in the utilities, and subtracts a log-sum-exp, convex and nondecreasing in each argument, of the convex functions λllog⁡Il\lambda_l \log I_l. It need not be concave jointly with λ\lambda, nor in (β,δ)(\beta, \delta) where some λk>1\lambda_k > 1: the information can be indefinite away from the maximum, where the steps are damped (Levenberg–Marquardt), and a maximum the polish certifies can be local. The dissimilarities keep their lower bound of 10−1610^{-16}. Where the steps drive one to that bound, they are damped at nearly every iteration and the polish does not report convergence. In one of the package’s test designs (200 choice situations) a fit from a poor start went there, 24 log-likelihood units below the interior maximum that a polish from another stop certified in six steps; in two others every start ended at the bound. Refit from other starts: where they all end there, the likelihood’s supremum is at the bound, the dissimilarity has no interior estimate and no polish certifies the fit, and the nest is to be revised.

What is held. The constants of inside alternatives without a finite estimate are held at the optimizer’s values, and the certificate concerns the other parameters given them, with one exception. An alternative chosen wherever it is offered has a positive score for its constant at every θ\theta, and is held, as in the multinomial logit. A never-chosen alternative jj in nest kk is held only where kk is a singleton or λk≤1\lambda_k \le 1 at the optimizer’s solution. Where jj is offered and the alternative chosen, jij_i, belongs to another nest, its constant’s score is −Pij<0-P_{ij} < 0; where jij_i is a nest-mate, it is

∂log⁡Piji∂δj=P(j∣k)(1−1λk−Pk), \frac{\partial \log P_{ij_i}}{\partial \delta_j} = P(j \mid k) \left(1 - \frac{1}{\lambda_k} - P_k\right),

negative for λk≤1\lambda_k \le 1 but positive for λk>1\lambda_k > 1 where the nest’s probability PkP_k is below 1−1/λk1 - 1/\lambda_k. Above 1 the constant can then have a finite estimate, which the polish seeks, so it is moved. Both terms vanish in proportion to P(j∣k)P(j \mid k) as δj→−∞\delta_j \to -\infty: where they are negative on balance there, the constant still has no finite estimate, and the polish moves it down until its share of the decrement is below the tolerance. It may then certify a point where the constant, and its standard error, are set by tol_decrement: in mode_choice with a never-chosen copy of bus (its generalized cost raised by 5), whose public nest has λ≈1.95\lambda \approx 1.95, about −47-47, its standard error about 2×1042 \times 10^4. A polish that held such a constant at λk≤1\lambda_k \le 1 and ends with λk>1\lambda_k > 1 does not report convergence, nor does one that moved it and ends with λk≤1\lambda_k \le 1, where it has no finite estimate. The reference’s divergence is treated as in the multinomial logit (§12.7 there): the held constants must anchor every other constant that can rise (a never-chosen one cannot rise without bound, since wherever it is offered the chosen alternative lies outside any set of never-chosen ones). A never-chosen base alternative, the reference, is treated as a moved constant (the others move against it), so that rule applies only where its nest is a singleton or ends with λk≤1\lambda_k \le 1.

Other limits. A nest that no situation offers two of has a dissimilarity on which the likelihood does not depend. Its score, its BHHH column and its Hessian entries are zero in exact arithmetic. The score and the BHHH column are exactly zero at the default start of 0.5, where the optimizer then leaves it (1/λ is exact there), and of rounding size elsewhere; the Hessian’s diagonal holds a rounding residue everywhere, 0.5 included (of either sign, about 10−1610^{-16} to 6×10−146 \times 10^{-14} in a test design). The BHHH polish leaves such a dissimilarity out of its steps, as without information or as stalled, and does not report convergence. Where the Hessian’s residue is positive, the Newton polish certifies the other parameters, leaving the dissimilarity at 0.5 or moving it on the score’s rounding elsewhere; where it is negative, the steps are damped and the polish does not certify. Its standard error is huge (about 10710^{7} in a test design) or NA. A trial point fails where the likelihood kernel reports that its objective or gradient is not the log-likelihood’s (§5.7 above): a log probability clamped to −1010-10^{10}, a total that is not finite, or a gradient entry set to zero, as where an unchosen nest’s inclusive value overflows and the nest drops out of the denominator, which leaves the chosen probability finite and too high. The optimizers do not see that report.

Scales and the variance. The maximum step and the stall rule are measured in the optimizer’s coordinates mm (§1.5 of the mixed logit article). Under scale_vars = "none" those would be the parameters’ own units, so the scales come instead from the BHHH diagonal at the optimizer’s solution projected onto the bound, as "bhhh" takes them at the start values: one pass of the gradient kernel. With half of the covariates rescaled by 10310^3 and the other half by 10−310^{-3}, 20 steps at unit scales left a decrement of 1,054 to 1,786, where 8 or 9 at these scales certified the maximum. The variance is computed at the polished estimates, by se_method, and the polish’s last curvature, evaluated at the point it returns, is not evaluated again where it is the variance’s own matrix: after "newton", the analytic Hessian of "hessian" and the bread of "sandwich" and "cluster"; after "bhhh", the BHHH matrix of "bhhh". se_method = "numeric" takes its own numerical Hessian.

On census- and claims-style designs (2,504 and 2,602 alternatives in 50 nests, with 24,560 and 245,031 choice situations; 499 and 500 alternatives with 17,339 and 153,721; ten covariates; constants without a finite estimate removed; single runs at eleven threads, times modeled from the kernels’ calls), the fit under scale_vars = "none" reached its limit of 1,000 evaluations on three of the four designs: 0.35 and 15.8 log-likelihood units short of the maximum on the census-style ones (up to 6.7 standard errors), 8×10−58 \times 10^{-5} on the smaller claims-style one; the larger stopped by its tolerance, 2×10−72 \times 10^{-7} short. The Newton polish certified the maximum in 3 and 5 steps on the census-style designs, for about a tenth of the fit’s time, and in one step on the claims-style ones. Stopping the optimizer after 100 evaluations and polishing took about a fifth of the time of that fit and its polish, and the default, scale_vars = "bhhh", stopped at the maximum in 50 to 66 evaluations on three of the four designs.

Code reference: run_polish(), .polish_held(), .polish_anchors(), .polish_fit() and .polish_scales() in R/classes.R; newton_step() in src/newton.cpp; the curvature, the hold rule (.nl_nest_lambda()) and the reuse in run_nestlogit(), R/nestlogit_utils.R; the kernels’ report, logit_sanitize() in src/choicer_internal.h.


6. Post-Estimation Quantities

6.1 Choice Probabilities (predict)

The joint probability is the decomposition from §2.1:

Pij=P(j∣k(j))⋅Pk(j) P_{ij} = P(j \mid k(j)) \cdot P_{k(j)}

with P(j∣k)P(j \mid k) and PkP_k given in §§2.3–2.4. nl_predict returns individual-level probabilities PijP_{ij} and systematic utilities VijV_{ij} for every observation row. nl_predict_shares aggregates over individuals to obtain weighted market shares:

ŝj=∑i=1NwiPij∑i=1Nwi \hat{s}_j = \frac{\sum_{i=1}^{N} w_i \, P_{ij}}{\sum_{i=1}^{N} w_i}

Code reference: src/nestlogit.cpp


6.2 Elasticities

6.2.1 Semi-elasticity with respect to utility

Let r=k(j)r = k(j) be the nest of the responding alternative jj and s=k(a)s = k(a) be the nest of the perturbed alternative aa. From §3.1, the derivative of log⁡Pij\log P_{ij} with respect to the systematic utility of any alternative aa is:

∂log⁡Pij∂Via=𝟏a=jλr+(1−1λr)𝟏s=rP(a∣r)−Pia \frac{\partial \log P_{ij}}{\partial V_{ia}} = \frac{\mathbf{1}_{a=j}}{\lambda_r} + \left(1 - \frac{1}{\lambda_r}\right)\mathbf{1}_{s=r} \, P(a \mid r) - P_{ia}

This is the general expression; the gradient formula in §3.1 applies it only to the chosen alternative, whereas here we evaluate it for all pairs (j,a)(j, a) to construct the full elasticity matrix.

6.2.2 Elasticity of PijP_{ij} with respect to covariate kk of alternative aa

Since ∂Via/∂xia,k=βk\partial V_{ia} / \partial x_{ia,k} = \beta_k:

Eij,iak=∂Pij∂xia,k⋅xia,kPij=βkxia,k⋅∂log⁡Pij∂Via E_{ij,ia}^{k} = \frac{\partial P_{ij}}{\partial x_{ia,k}} \cdot \frac{x_{ia,k}}{P_{ij}} = \beta_k \, x_{ia,k} \cdot \frac{\partial \log P_{ij}}{\partial V_{ia}}

Substituting the three cases:

Case Condition Semi-elasticity ∂log⁡Pij/∂Via\partial \log P_{ij}/\partial V_{ia}
Own a=ja = j 1λr+(1−1λr)P(j∣r)−Pij\dfrac{1}{\lambda_r} + \left(1 - \dfrac{1}{\lambda_r}\right) P(j \mid r) - P_{ij}
Cross, same nest s=r,a≠js = r,\; a \neq j (1−1λr)P(a∣r)−Pia\left(1 - \dfrac{1}{\lambda_r}\right) P(a \mid r) - P_{ia}
Cross, different nest s≠rs \neq r −Pia-P_{ia}

Reduction to MNL. When λk=1\lambda_k = 1 for all nests the within-nest term (1−1/λr)(1 - 1/\lambda_r) vanishes and the conditional probability drops out, giving ∂log⁡Pij/∂Via=𝟏a=j−Pia\partial \log P_{ij}/\partial V_{ia} = \mathbf{1}_{a=j} - P_{ia}, which is exactly the MNL semi-elasticity (§3.1 of the MNL document).

Outside option. When an outside option is present it occupies its own singleton nest with λ0=1\lambda_0 = 1 and xi0,k=0x_{i0,k} = 0. Its row (responding = outside option) has semi-elasticity −Pia-P_{ia} for every inside alternative aa (different nest, §3.1); its column (perturbed = outside option) is identically zero because βk⋅0=0\beta_k \cdot 0 = 0.

The implementation accumulates wi⋅Eij,iakw_i \cdot E_{ij,ia}^k across individuals and divides by ∑iwi\sum_i w_i to produce a weighted average of individual probability elasticities. This is not generally the elasticity of an aggregate share under a common market-level perturbation when attributes vary across situations. Rows index responding alternatives and columns perturbed alternatives.

Code reference: src/nestlogit.cpp


6.3 Diversion Ratios

6.3.1 Definition

The utility-based diversion ratio from losing alternative jj to receiving alternative kk is:

DR(j→k)=−∂Qk/∂Vij∂Qj/∂Vij DR(j \to k) = -\frac{\partial Q_k / \partial V_{ij}}{\partial Q_j / \partial V_{ij}}

where Qm=∑iwiPimQ_m = \sum_i w_i P_{im} is aggregate demand and the perturbation is through the systematic utility of the losing alternative jj.

6.3.2 Partial derivatives of demand

Using ∂Pim/∂Vij=Pim⋅(∂log⁡Pim/∂Vij)\partial P_{im}/\partial V_{ij} = P_{im} \cdot (\partial \log P_{im}/\partial V_{ij}) and the semi-elasticity from §6.2.1, the three cases with r=k(j)r = k(j):

∂Pim∂Vij={Pij[1λr+(1−1λr)P(j∣r)−Pij]m=jPim[(1−1λr)P(j∣r)−Pij]k(m)=r,m≠j−PimPijk(m)≠r \frac{\partial P_{im}}{\partial V_{ij}} = \begin{cases} P_{ij}\!\left[\dfrac{1}{\lambda_r} + \left(1 - \dfrac{1}{\lambda_r}\right) P(j \mid r) - P_{ij}\right] & m = j \\[6pt] P_{im}\!\left[\left(1 - \dfrac{1}{\lambda_r}\right) P(j \mid r) - P_{ij}\right] & k(m) = r,\; m \neq j \\[6pt] -P_{im} \, P_{ij} & k(m) \neq r \end{cases}

6.3.3 Utility Perturbation and Covariate Interpretation

The implemented matrix is defined with respect to a common additive perturbation of VijV_{ij}. If a fixed-coefficient attribute of alternative jj receives the same additive change dxdx in every situation, dVij=βrdxdV_{ij}=\beta_r dx, so the common scalar cancels:

DR(j→k)=−βrdx∑iwi(∂Pik/∂Vij)βrdx∑iwi(∂Pij/∂Vij)=−∑iwi(∂Pik/∂Vij)∑iwi(∂Pij/∂Vij) DR(j \to k) = -\frac{\beta_r dx\sum_i w_i \,(\partial P_{ik}/\partial V_{ij})} {\beta_r dx\sum_i w_i \,(\partial P_{ij}/\partial V_{ij})} = -\frac{\sum_i w_i \,(\partial P_{ik}/\partial V_{ij})} {\sum_i w_i \,(\partial P_{ij}/\partial V_{ij})}

It is in this additive-shift sense that NL diversion is independent of the chosen fixed covariate. For a proportional perturbation dxi=xij,rdlog⁡xdx_i=x_{ij,r}d\log x, the values xij,rx_{ij,r} remain inside both population sums and generally do not cancel. The kernel does not compute that attribute-specific proportional diversion. In MXL even a common additive perturbation of a random-coefficient attribute carries draw-specific βirs\beta_{ir}^s, so the coefficient cannot be factored out.

6.3.4 Population aggregation and column-sum property

Define:

num(k,j)=∑i=1Nwi(−∂Pik∂Vij),den(j)=∑i=1Nwi∂Pij∂Vij \text{num}(k, j) = \sum_{i=1}^{N} w_i \left(-\frac{\partial P_{ik}}{\partial V_{ij}}\right), \qquad \text{den}(j) = \sum_{i=1}^{N} w_i \frac{\partial P_{ij}}{\partial V_{ij}}

so that DR(j→k)=num(k,j)/den(j)DR(j \to k) = \text{num}(k,j) \,/\, \text{den}(j) for k≠jk \neq j.

Columns sum to 1. The fundamental identity ∑m∂Pim/∂Vij=0\sum_{m} \partial P_{im}/\partial V_{ij} = 0 (probabilities sum to 1 for every individual and every perturbation direction, including the outside option when present) gives:

∑k≠j∂Pik∂Vij=−∂Pij∂Vij⟹∑k≠jnum(k,j)=den(j)⟹∑k≠jDR(j→k)=1 \sum_{k \neq j} \frac{\partial P_{ik}}{\partial V_{ij}} = -\frac{\partial P_{ij}}{\partial V_{ij}} \implies \sum_{k \neq j} \text{num}(k, j) = \text{den}(j) \implies \sum_{k \neq j} DR(j \to k) = 1

When an outside option is present it acts as both a source (it can lose demand) and a destination (it can receive diverted demand), so it appears in both the row index kk and the column index jj of the Jtotal×JtotalJ_{\text{total}} \times J_{\text{total}} diversion matrix, and the column sums still equal 1 over all alternatives including the outside option. Because its systematic utility is fixed at zero in estimation, the outside-as-source column is a derivative with respect to a hypothetical perturbation of that normalized utility, not an available outside-option covariate.

6.3.5 Reduction to MNL at λ=1\lambda = 1

When all λk=1\lambda_k = 1 the cross-same-nest case collapses to the cross-different-nest case (∂Pim/∂Vij=−PimPij\partial P_{im}/\partial V_{ij} = -P_{im} P_{ij} for m≠jm \neq j) and the own case gives ∂Pij/∂Vij=Pij(1−Pij)\partial P_{ij}/\partial V_{ij} = P_{ij}(1 - P_{ij}). Substituting:

DR(j→k)|λ=1=∑iwiPijPik∑iwiPij(1−Pij) DR(j \to k)\big|_{\lambda=1} = \frac{\sum_i w_i \, P_{ij} \, P_{ik}}{\sum_i w_i \, P_{ij} (1 - P_{ij})}

which is the MNL diversion ratio (§6.3 of the MNL document).

Code reference: src/nestlogit.cpp


6.4 BLP Share Inversion

6.4.1 Problem statement

Given observed market shares sj*s_j^*, find the ASC vector δ\delta such that the NL model reproduces those shares, with β\beta and λ\lambda held at their values:

ŝj(δ)=∑i=1NwiPij(δ)∑i=1Nwi=sj*∀j \hat{s}_j(\delta) = \frac{\sum_{i=1}^{N} w_i \, P_{ij}(\delta)}{\sum_{i=1}^{N} w_i} = s_j^* \quad \forall j

where Pij(δ)=P(j∣k(j))⋅Pk(j)P_{ij}(\delta) = P(j \mid k(j)) \cdot P_{k(j)}. The identification of δ\delta, the checks of the targets, the stopping rule and the result are the multinomial logit’s (§7 of the multinomial logit article); this section gives the nested logit’s step.

6.4.2 The step

With r=log⁡s*−log⁡ŝ(δ)r = \log s^* - \log \hat{s}(\delta), bb the outside option (or, without one, the reference of jj’s component) and ρj=rj−rb\rho_j = r_j - r_b, the step is the multinomial logit’s (§7.3 of the multinomial logit article): a common shift τ\tau of the component’s free constants, then the exact diagonal of the derivative of ρ\rho on the rest,

δj←δj+κ(τ+ρj−hjτDj),Dj=Ajjŝj+Cjbŝb,hj=Cjbŝj+∑kCkbŝb, \delta_j \leftarrow \delta_j + \kappa \left(\tau + \frac{\rho_j - h_j \tau}{D_j}\right), \qquad D_j = \frac{A_{jj}}{\hat{s}_j} + \frac{C_{jb}}{\hat{s}_b}, \qquad h_j = \frac{C_{jb}}{\hat{s}_j} + \sum_k \frac{C_{kb}}{\hat{s}_b},

for alternative jj in nest gg, where κ∈(0,1]\kappa \in (0, 1] is damping (default 1), τ\tau solves ∑jŝj(ρj−hjτ)=0\sum_j \hat{s}_j (\rho_j - h_j \tau) = 0,

Ajj=∂ŝj∂δj=∑iwiPij(1−Pi(j∣g)λg+Pi(j∣g)−Pij)∑iwi, A_{jj} = \frac{\partial \hat{s}_j}{\partial \delta_j} = \frac{\sum_i w_i P_{ij}\left(\frac{1 - P_i(j \mid g)}{\lambda_g} + P_i(j \mid g) - P_{ij}\right)}{\sum_i w_i},

and Cjb=−∂ŝb/∂δjC_{jb} = -\partial \hat{s}_b / \partial \delta_j: ∑iwiPijPi0\sum_i w_i P_{ij} P_{i0} over ∑iwi\sum_i w_i with an outside option, and without one

Cjb=∑iwiPib(1−λgλgPi(j∣g)1{b∈g}+Pij)∑iwi. C_{jb} = \frac{\sum_i w_i P_{ib}\left(\frac{1 - \lambda_g}{\lambda_g} P_i(j \mid g)\, 1\{b \in g\} + P_{ij}\right)}{\sum_i w_i}.

The nested logit’s share Jacobian is symmetric (its shares are the gradient of the log-sum, for any λg>0\lambda_g > 0) and its rows sum to zero, so −hj-h_j is the exact rate at which ρj\rho_j responds to the common shift, as in the logit. Berry, Levinsohn and Pakes’s (1995) contraction, method = "original", takes κrj\kappa r_j (κ(rj−rb)\kappa (r_j - r_b) without an outside option, the reference held): no shift, no outside-share correction, and 1 in place of DjD_j. It therefore overshoots within a nest: its step’s derivative there is about 1/λg1/\lambda_g, and its iteration can diverge where λg\lambda_g is small (it failed on 8 of the 18 simulated designs we tried with λg≤0.4\lambda_g \le 0.4, and on none with larger λg\lambda_g) unless damped by about λg\lambda_g. The exact diagonal carries the 1/λg1/\lambda_g, so no damping is needed. For a nest’s dominant alternative, 1−Pi(j∣g)1 - P_i(j \mid g) is formed as the sum of its nest-mates’ conditional probabilities, since λg\lambda_g can be as small as 10−1610^{-16}, where the difference loses every digit. The logit’s other safeguards apply: the step’s cap, its halving where the shares are not finite, its stalls, and the contraction racing it once 100 iterations fail to halve the best residual (multiplied by damping like the step; where it diverges, at small λg\lambda_g, it falls behind and stops, going on whenever the step alone fails to halve its best residual within 200 iterations, or its trial point fails). method = "anderson", the default, and method = "squarem" accelerate this step as in the logit (Anderson acceleration and SQUAREM; §7.3 of the multinomial logit article), with damping multiplying the step’s part of each update.

6.4.3 Nests with λg>1\lambda_g > 1

Where λg>1\lambda_g > 1 nest-mates are complements: raising δj\delta_j raises the nest’s inclusive value, and with it the shares of jj’s nest-mates where the nest is small. Two safeguards apply.

  • An alternative whose co-choice with the base is negative (bb in its nest, without an outside option) has a diagonal DjD_j of at least 1: its exact diagonal nets out the complementarity and can be near zero or negative.
  • The diagonal DjD_j is at least (1+λg)/(2λg)(1 + \lambda_g)/(2\lambda_g) times the one the same probabilities give with λg=1\lambda_g = 1 (∑iwiPij(1−Pij)/∑iwi\sum_i w_i P_{ij}(1 - P_{ij})/\sum_i w_i over ŝj\hat{s}_j, plus ∑iwiPijPib/∑iwi\sum_i w_i P_{ij}P_{ib}/\sum_i w_i over ŝb\hat{s}_b). A common shift of a nest’s constants moves its shares as in a logit, with derivative about 1, while a shift within the nest moves them with derivative about 1/λg1/\lambda_g; the exact diagonal is close to the latter, so its step would overshoot the common shift by up to λg\lambda_g and diverge for λg\lambda_g above 2. The factor relaxes the two directions equally: the step’s error then contracts by about (λg−1)/(λg+1)(\lambda_g - 1)/(\lambda_g + 1) in each.

On 80 simulated designs with λ\lambda from 1.05 to 5, nests of 2 and 5 alternatives, 12 and 60 alternatives and heterogeneous choice sets, solved to 10−1210^{-12}, the step converged on every one, in a median 0.32 of Berry’s evaluations and never more (with an outside option, Berry’s contraction needed 129 to 170 evaluations, the step 9 to 70).

6.4.4 The layout of delta

Without an outside option, delta is a full length-JJ vector, normalized by subtracting its first entry, so the returned baseline is zero. With an outside option, supplied and returned delta contain the JJ inside ASCs only, and target_shares has J+1J+1 entries, the outside option’s first.

Note on the lambda argument. nl_blp_contraction expects a full length-nnestsn_{\text{nests}} vector where singleton nests have their entry set to 1, every entry positive and finite. This differs from the estimated parameter block λ\lambda in θ\theta, which contains only non-singleton entries. The caller is responsible for expanding the estimated lambdas into the full vector before invoking the inversion.

6.4.5 Evaluating the shares

As in the logit (§7.6 of the multinomial logit article), after the first evaluation the probabilities are read from exponentials kept across evaluations wherever those allow it, here within each nest. The first, at δ0\delta^0, keeps eij=exp⁡((xij′β+δj0)/λg−cig)e_{ij} = \exp((x_{ij}'\beta + \delta^0_j)/\lambda_g - c_{ig}) for alternative jj in nest gg, where cigc_{ig} is the largest of these scaled utilities in nest gg of situation ii: one shift per situation would not do, since at λg=0.02\lambda_g = 0.02 a nest 15 utility units below the best would underflow (750 scaled units down) while its probability is still about 3×10−73 \times 10^{-7}. An evaluation at δ\delta forms uij=eijbju_{ij} = e_{ij} b_j with bj=exp⁡((δj−δj0)/λg)b_j = \exp((\delta_j - \delta^0_j)/\lambda_g), each offered nest’s inclusive value from log⁡∑k∈guik\log \sum_{k \in g} u_{ik} (one logarithm per nest), the nests’ probabilities from those (one exponential per nest) and P(j∣g)=uij/∑k∈guikP(j \mid g) = u_{ij} / \sum_{k \in g} u_{ik}: three exponentials per row fewer than afresh. The distance is d=max⁡j|δj−δj0|/λg(j)d = \max_j |\delta_j - \delta^0_j| / \lambda_{g(j)}, what bjb_j exponentiates, with the logit’s bound of 50 and its floor, so small dissimilarities make an evaluation afresh more often: at λg=0.02\lambda_g = 0.02, 3 of the 39 evaluations of an inversion of census-style data, which took 0.68 of the time.

Code reference: NlBlpModel and nl_blp_solve() in src/nestlogit.cpp, over src/blp_engine.h.

6.5 Willingness to Pay

Utility is linear in covariates, so willingness to pay is the same marginal rate of substitution as in the MNL model: for attribute kk and price coefficient α=βp\alpha = \beta_p,

WTPk=−βkα,SÊ=∇gTV̂(k,p)∇g,∇g=(−1/αβk/α2) \mathrm{WTP}_k = -\frac{\beta_k}{\alpha}, \qquad \widehat{\mathrm{SE}} = \sqrt{\nabla g^T \, \hat{V}_{(k,p)} \, \nabla g}, \quad \nabla g = \begin{pmatrix} -1/\alpha \\ \beta_k/\alpha^2 \end{pmatrix}

with V̂(k,p)\hat{V}_{(k,p)} the 2×22 \times 2 block of the coefficient covariance. The nest parameters λ\lambda rescale within-nest substitution but do not enter the ratio of marginal utilities, so they affect WTP only through the estimated covariance of (βk,α)(\beta_k, \alpha). ASCs may also be used as the numerator (−δj/α-\delta_j/\alpha). See §8 of the MNL document for the full derivation and caveats.

Code reference: R/wtp.R

6.6 Consumer Surplus and the Nested Logsum

For the nested logit, expected maximum utility is the two-level logsum below plus the scenario-invariant extreme-value location constant (omitted by logsum(), as in MNL):

logsumi=log⁡Di=log⁡(∑lexp(λllogIl)[+1]),log⁡Il=log⁡∑j∈Bl∩Ciexp⁡(Vijλl) \mathrm{logsum}_i = \log D_i = \log\left( \sum_{l} \exp\big(\lambda_l \log I_l\big) \; [+\, 1] \right), \qquad \log I_l = \log \sum_{j \in B_l \cap C_i} \exp\!\left(\frac{V_{ij}}{\lambda_l}\right)

where the +1=exp⁡(0)+1 = \exp(0) term appears when an outside option is present and singleton nests have λl=1\lambda_l = 1 (§5.2). Both levels are computed with the max-subtraction trick (§2.7).

Two useful identities:

  • Reduction to MNL. With all λl=1\lambda_l = 1, λllog⁡Il=log⁡∑j∈Blexp⁡(Vij)\lambda_l \log I_l = \log \sum_{j \in B_l} \exp(V_{ij}) and the nested logsum collapses to the MNL logsum log⁡∑jexp⁡(Vij)\log \sum_j \exp(V_{ij}).
  • Outside-option link. Since Pi0=1/DiP_{i0} = 1 / D_i (§2.5), the logsum equals −log⁡Pi0-\log P_{i0} — a direct consistency check against the probability kernel.

Expected consumer surplus follows Train (2009, Ch. 3) exactly as in the MNL case:

𝔼[CSi]=logsumi−α \mathbb{E}[CS_i] = \frac{\mathrm{logsum}_i}{-\alpha}

with the same caveats: no income effects, and CS levels inherit the ASC normalization, so only differences across scenarios (counterfactual newdata vs. baseline) are meaningful. The implementation reports point estimates for NL (the delta-method SE of the mean CS is currently provided for MNL only; Krinsky–Robb resampling of the coefficients is the practical interval method here). The routine does not enforce α<0\alpha<0; interpreting −α-\alpha as positive marginal utility of income requires the analyst to verify the estimated sign.

Code reference: R/surplus.R

6.7 Goodness of Fit

The measures are model-agnostic and identical to §10 of the MNL document, computed from the NL log-likelihood and predicted probabilities:

  • McFadden pseudo R²: R2=1−ℓ(θ̂)/ℓ0R^2 = 1 - \ell(\hat\theta)/\ell_0 and Radj2=1−(ℓ(θ̂)−K)/ℓ0R^2_{\text{adj}} = 1 - (\ell(\hat\theta) - K)/\ell_0, with KK counting all estimated parameters including the λ\lambda block.
  • Equal-shares null (default, exact for unbalanced sets and weights): ℓ0=−∑iwilog⁡(Mi+𝟏outside)\ell_0 = -\sum_i w_i \log(M_i + \mathbf{1}_{\text{outside}}).
  • Market-shares null (constants-only closed form): ℓ0=c∑jNjlog⁡(sj)\ell_0 = c\sum_j N_j \log(s_j), where cc is the common weight; requires identical choice-set composition across individuals and uniform weights. The constants-only model is itself an MNL—at β=0\beta = 0 and free ASCs the nest structure is not identified from constant shares—so the same closed form applies.
  • Hit rate: weighted share of choice situations whose observed choice has the highest predicted NL probability; with an outside option the outside good competes with Pi0=1−∑jPijP_{i0} = 1 - \sum_j P_{ij}.

Code reference: R/gof.R


7. Choice-Based Sampling and WESML Weighting

7.1 Endogenous Stratified (Choice-Based) Sampling

Under random (exogenous) sampling each choice situation is drawn independently of its outcome. Under choice-based (endogenous stratified) sampling the strata are defined by the chosen alternative jij_i and situations are drawn with stratum-specific frequencies — for example, deliberately oversampling individuals who chose a rare alternative. Let Q(j)Q(j) be the population share of alternative jj and H(j)H(j) the sample share of choosers of jj.

Unlike the MNL special case (a full set of ASCs leaves the slopes consistent), the nested logit has no such free pass: the dissimilarity parameters λl\lambda_l enter the within- and between-nest probabilities nonlinearly, so choice-based sampling generally biases the slopes β\beta, the constants δ\delta, and the λ\lambda block. Weighting is therefore required for consistent estimation of the population parameters.

7.2 The WESML Weighted Log-Likelihood

Manski and Lerman (1977) restore consistency by weighting each situation’s contribution by the ratio of population to sample share of its chosen alternative,

wi=Q(ji)H(ji),ℓW(θ)=∑i=1Nwilog⁡Piji(θ). w_i = \frac{Q(j_i)}{H(j_i)}, \qquad \ell^{W}(\theta) = \sum_{i=1}^{N} w_i \log P_{i j_i}(\theta).

The maximizer θ̂\hat\theta is invariant to multiplying every wiw_i by a common positive constant, so the weights may be normalized to mean 1 without changing the estimates.

7.3 Robust (Sandwich) Variance: the w2w^2 Meat

WESML is a weighted M-estimator solving ∑iwisi(θ̂)=0\sum_i w_i\, s_i(\hat\theta) = 0, where si=∂log⁡Piji/∂θs_i = \partial \log P_{i j_i}/\partial\theta is the full per-situation score over the β\beta, λ\lambda and δ\delta blocks ($$3) and HiH_i its Hessian ($$4). Its robust (Huber–White) asymptotic variance is the sandwich

V=A−1BA−1,A=∑iwi(−Hi),B=∑iwi2sisi⊤. V = A^{-1} B A^{-1}, \qquad A = \sum_{i} w_i\,(-H_i), \qquad B = \sum_{i} w_i^{2}\, s_i s_i^{\top}.

The weight enters the bread AA linearly, but the meat BB carries the weight squared: the contribution of situation ii to the estimating equation is wisiw_i s_i, so its variance involves (wisi)(wisi)⊤=wi2sisi⊤(w_i s_i)(w_i s_i)^{\top} = w_i^{2}\, s_i s_i^{\top}. The score sis_i is assembled exactly as in the gradient kernel ($$3.3–3.4): the β\beta and δ\delta blocks from grad_vec, and the λl\lambda_l blocks from the per-nest expression (𝟏{l=li}−Pil)[log⁡Iil−λl−1∑j∈BlPij|lVij]+𝟏{l=li}λl−2(∑j∈BlPij|lVij−Viji)(\,\mathbf{1}\{l = l_i\} - P_{il}\,)\big[\log I_{il} - \lambda_l^{-1}\!\sum_{j\in B_l} P_{ij|l} V_{ij}\big] + \mathbf{1}\{l=l_i\}\,\lambda_l^{-2}\big(\sum_{j\in B_l} P_{ij|l}V_{ij} - V_{ij_i}\big), with singleton nests (λl≡1\lambda_l \equiv 1) contributing no score.

As in the MNL/MXL cases, both naive variances are wrong under weighting: the inverse-Hessian A−1A^{-1} assumes the information-matrix equality A=BA = B (which fails once the wiw_i are non-degenerate), and ordinary BHHH/OPG (∑iwisisi⊤)−1\big(\sum_i w_i\, s_i s_i^{\top}\big)^{-1} uses the weight to the first power, not the second. The sandwich is invariant to the weight scale: A→cAA \to cA, B→c2BB \to c^2 B, hence V→A−1BA−1V \to A^{-1} B A^{-1}.

7.4 Scope: Robust vs. Design-Based Variance

The estimator implemented here is the robust weighted-M-estimator (Huber–White) variance, with uncentered meat B=∑iwi2sisi⊤B = \sum_i w_i^{2}\, s_i s_i^{\top} — the asymptotic variance under variable-probability sampling. The smaller stratum-centered (design-based) variance for a fixed-quota design is out of scope; see Manski & McFadden (1981) and Cosslett (1981).

7.5 Implementation and Cluster-Robust Extension

The meats come from compiled kernels that never form the N×pN\times p matrix of weight-free scores (singleton lambdas are not parameters, so the meats have no rows for them): the BHHH kernel nl_bhhh_parallel() adds wisisiTw_i\,s_is_i^T over each situation’s compact block (§4.8), with weights = w for the BHHH information and weights = w^2 for the robust meat, so that

A=𝚗𝚕_𝚕𝚘𝚐𝚕𝚒𝚔_𝚑𝚎𝚜𝚜𝚒𝚊𝚗_𝚙𝚊𝚛𝚊𝚕𝚕𝚎𝚕(θ̂;w),B=𝚗𝚕_𝚋𝚑𝚑𝚑_𝚙𝚊𝚛𝚊𝚕𝚕𝚎𝚕(θ̂;w2)=∑iwi2sisiT. A=\texttt{nl\_loglik\_hessian\_parallel}(\widehat\theta;w), \qquad B=\texttt{nl\_bhhh\_parallel}(\widehat\theta;w^2)=\sum_i w_i^2 s_is_i^T.

For a fit whose selected method is the numeric NL Hessian, the bread uses the numeric oracle instead. The fit-time variance (se_method), vcov(fit, type = ), the recomputation of a variance dropped from a fit and wesml_vcov() all compute it from the same kernels (.assemble_score_vcov(), or compute_hessian() for a Hessian or BHHH variance recomputed lazily), so a fit’s variance is the one vcov() returns post hoc: bit for bit at one thread, and up to the last bits with more. For cluster labels g(i)g(i), se_method = "cluster" uses

Bcluster=∑g(∑i:g(i)=gwisi)(∑i:g(i)=gwisi)T, B_{\mathrm{cluster}}=\sum_g \left(\sum_{i:g(i)=g}w_is_i\right) \left(\sum_{i:g(i)=g}w_is_i\right)^T,

formed by nl_cluster_meat_parallel() without the score matrix either (the situations sorted by cluster, each cluster’s weighted compact scores summed over the parameters its situations touch), with no finite-cluster correction. These matrices are combined as V=A−1BA−1V=A^{-1}BA^{-1}, computed equilibrated by two solves against the LULU factors of the equilibrated bread, without forming an inverse (§5.8). User-facing entry points: wesml_weights() computes the Manski–Lerman weights from the population shares QQ, while sample_by_choice() draws a choice-based sample and attaches those weights; run_nestlogit(..., se_method = "sandwich") estimates with the robust variance; wesml_vcov() returns it post hoc. Passing run_nestlogit(..., weights_col = ) collapses a row-level weight column to one weight per choice situation (validated constant within id), and a provenance guard prevents a WESML-labeled sample from being silently fit unweighted.

Code reference: nl_bhhh_parallel() / nl_cluster_meat_parallel() in src/nestlogit.cpp; .assemble_score_vcov(), .logit_meat() and .sandwich_combine() in R/classes.R (.score_meat() there forms the same meats from the score matrix of nl_scores_parallel(), as the tests’ reference); equilibrated_sandwich() in src/vcov.cpp; wesml_weights() / sample_by_choice() in R/sampling.R.


References

  • McFadden, D. (1978). Modelling the choice of residential location. In A. Karlqvist et al. (Eds.), Spatial Interaction Theory and Planning Models (pp. 75-96). North-Holland.
  • Ben-Akiva, M., & Lerman, S. R. (1985). Discrete Choice Analysis: Theory and Application to Travel Demand. MIT Press.
  • Koppelman, F. S., & Wen, C.-H. (1998). Alternative nested logit models: structure, properties and estimation. Transportation Research Part B, 32(5), 289-298.
  • Hensher, D. A., & Greene, W. H. (2002). Specification and estimation of the nested logit model: alternative normalisations. Transportation Research Part B, 36(1), 1-17.
  • Heiss, F. (2002). Structural choice analysis with nested logit models. The Stata Journal, 2(3), 227-252.
  • Berry, S., Levinsohn, J., & Pakes, A. (1995). Automobile prices in market equilibrium. Econometrica, 63(4), 841–890.
  • Train, K. E. (2009). Discrete Choice Methods with Simulation (2nd ed.). Cambridge University Press. Chapter 4.
  • Manski, C. F., & Lerman, S. R. (1977). The estimation of choice probabilities from choice based samples. Econometrica, 45(8), 1977–1988.
  • Manski, C. F., & McFadden, D. (1981). Alternative estimators and sample designs for discrete choice analysis. In C. F. Manski & D. McFadden (Eds.), Structural Analysis of Discrete Data with Econometric Applications (pp. 2–50). MIT Press.
  • Cosslett, S. R. (1981). Maximum likelihood estimator for choice-based samples. Econometrica, 49(5), 1289–1316.