% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/betaBinomial.R
\name{gradient_log_likelihood2}
\alias{gradient_log_likelihood2}
\title{Analytic gradient of the negative log-likelihood (mode 2)}
\usage{
gradient_log_likelihood2(params, X, Z, y, n, weights = NULL, lch = NULL)
}
\arguments{
\item{params}{A numeric vector containing all model parameters. The first
n_alpha elements are coefficients for the alpha model, and the remaining
elements are coefficients for the beta model.}

\item{X}{A matrix of predictors for the alpha model.}

\item{Z}{A matrix of predictors for the beta model.}

\item{y}{A numeric vector of response values.}

\item{n}{The maximum score (number of trials).}

\item{weights}{A numeric vector of weights for each observation
(NULL = equal weights).}

\item{lch}{Optional precomputed \code{lchoose(n, y)}. Since this term does
not depend on the parameters, passing it once avoids recomputation in
every optimizer iteration.}
}
\value{
Numeric vector: gradient of the negative log-likelihood with
  respect to \code{params}.
}
\description{
Computes the exact gradient of \code{\link{log_likelihood2}} with respect
to all regression coefficients. With the per-observation log-probability
\deqn{\log p = \mathrm{lchoose}(n, y) + \mathrm{lbeta}(y+\alpha, n-y+\beta)
  - \mathrm{lbeta}(\alpha, \beta),}
the partial derivatives on the natural scale are (with digamma function
\eqn{\psi}):
\deqn{\partial \log p/\partial\alpha = \psi(y+\alpha) - \psi(\alpha)
  + \psi(\alpha+\beta) - \psi(n+\alpha+\beta)}
\deqn{\partial \log p/\partial\beta = \psi(n-y+\beta) - \psi(\beta)
  + \psi(\alpha+\beta) - \psi(n+\alpha+\beta)}
The chain rule through the log link multiplies by \eqn{\alpha} resp.
\eqn{\beta}; coefficient gradients follow as
\eqn{-X^\top(w \cdot \partial\ell/\partial\eta)} for the negative
log-likelihood. Contributions of observations whose linear predictor is
clamped (see \code{log_likelihood2}) are zeroed, which is the exact
subgradient of the clamped objective.
}
\details{
Supplying this gradient to \code{\link[stats]{optim}} (L-BFGS-B) replaces
the finite-difference approximation, which required
\code{length(params) + 1} likelihood evaluations per gradient.
}
\keyword{internal}
