% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/weight_estimation.R
\name{fit_weight_model}
\alias{fit_weight_model}
\title{Fit a weight model mapping study-level covariates to simplex weights}
\usage{
fit_weight_model(
  pi_hat,
  W,
  method = c("dirichlet"),
  boundary_eps = 1e-04,
  formula = NULL,
  ...
)
}
\arguments{
\item{pi_hat}{An \code{m}-by-\code{K} numeric matrix of simplex weights; rows must
be non-negative and sum to 1 (up to tolerance \code{1e-6}).}

\item{W}{An \code{m}-by-\code{p} matrix or data frame of study-level covariates.}

\item{method}{Weight-model method. Currently only \code{"dirichlet"} is
supported.}

\item{boundary_eps}{Small positive scalar used to shrink weights away
from the simplex boundary before Dirichlet fitting. Defaults to \code{1e-4}.}

\item{formula}{Optional RHS-only formula (e.g. \code{~ x1 + I(x2^2)}) describing
the covariate part of the Dirichlet regression. Defaults to \code{~ .}
(all columns of \code{W}).}

\item{...}{Passed through to \code{\link[DirichletReg:dirichreg]{DirichletReg::DirichReg()}}.}
}
\value{
An object of class \code{"metahunt_weight_model"}: a list with the
fitted model, formula, method, \code{K}, and training covariate names.
}
\description{
Given a matrix of simplex-valued weights \eqn{\hat\pi_1,\ldots,\hat\pi_m}
(e.g. from \code{\link[=project_to_simplex]{project_to_simplex()}}) and associated study-level covariates
\eqn{\mathbf W_1,\ldots,\mathbf W_m}, fit a model
\eqn{\widehat{\mathcal M}:\mathbf W \mapsto \boldsymbol\pi}.
The default method is Dirichlet regression via the \code{DirichletReg} package.
}
\details{
Dirichlet regression cannot handle weights exactly at the simplex boundary
(\code{0} or \code{1}), which frequently arise after constrained projection. Before
fitting, rows of \code{pi_hat} are shrunk toward the barycenter via
\eqn{\tilde\pi = (\pi + \varepsilon) / (1 + K\varepsilon)}, with
\eqn{\varepsilon} set by \code{boundary_eps}.
}
\examples{
\donttest{
set.seed(1)
m <- 80; K <- 3; p <- 2
W <- matrix(rnorm(m * p), m, p); colnames(W) <- c("w1", "w2")
# generate simplex weights driven by W
eta <- cbind(0.5 * W[, 1], -0.3 * W[, 2], rep(0, m))
pi_true <- exp(eta) / rowSums(exp(eta))
pi_hat <- pi_true + matrix(rnorm(m * K, sd = 0.01), m, K)
pi_hat <- pmax(pi_hat, 0); pi_hat <- pi_hat / rowSums(pi_hat)
model <- fit_weight_model(pi_hat, W)
predict(model, newdata = matrix(c(0, 0), 1, 2, dimnames = list(NULL, c("w1","w2"))))
}

}
