Package {bgw}


Type: Package
Title: Bunch-Gay-Welsch Statistical Estimation
Version: 0.1.5
Maintainer: David S. Bunch <dsbunch@ucdavis.edu>
Description: Performs statistical estimation and inference-related computations by accessing and executing modified versions of 'Fortran' subroutines originally published in the Association for Computing Machinery (ACM) journal Transactions on Mathematical Software (TOMS) by Bunch, Gay and Welsch (1993) <doi:10.1145/151271.151279>. The acronym 'BGW' (from the authors' last names) will be used when making reference to technical content (e.g., algorithm, methodology) that originally appeared in ACM TOMS. A key feature of BGW is that it exploits the special structure of statistical estimation problems within a trust-region-based optimization approach to produce an estimation algorithm that is much more effective than the usual practice of using optimization methods and codes originally developed for general optimization. The 'bgw' package bundles 'R' wrapper (and related) functions with modified 'Fortran' source code so that it can be compiled and linked in the 'R' environment for fast execution. This version implements a function ('bgw_mle.R') that performs maximum likelihood estimation (MLE) for a user-provided model object that computes probabilities (a.k.a. probability densities). The original motivation for producing this package was to provide fast, efficient, and reliable MLE for discrete choice models that can be called from the 'Apollo' choice modelling 'R' package ( see https://www.apollochoicemodelling.com). Starting with the release of Apollo 0.3.0, BGW is the default estimation package. However, estimation can also be performed using BGW in a stand-alone fashion without using 'Apollo' (as shown in simple examples included in the package). Note also that BGW capabilities are not limited to MLE, and future extension to other estimators (e.g., nonlinear least squares, generalized method of moments, etc.) is possible. The 'Fortran' code included in 'bgw' was modified by one of the original BGW authors (Bunch) under his rights as confirmed by direct consultation with the ACM Intellectual Property and Rights Manager. See https://authors.acm.org/author-resources/author-rights. The main requirement is clear citation of the original publication (see above).
License: GPL-3
Encoding: UTF-8
NeedsCompilation: yes
Depends: R (≥ 4.0.0)
Suggests: knitr, rmarkdown, testthat (≥ 3.0.0),
VignetteBuilder: knitr
Author: David S. Bunch ORCID iD [aut, cre], David M. Gay [ctb], Roy E. Welsch [ctb], Stephane Hess [ctb], David Palma [ctb]
Config/testthat/edition: 3
Config/roxygen2/version: 8.1.1
Packaged: 2026-11-10 21:24:21 UTC; dsbunch
Repository: CRAN
Date/Publication: 2026-11-10 22:20:17 UTC

Internal BGW Functions

Description

Internal BGW functions

Details

These are not to be called by the user.

Value

These functions are wrappers for 'Fortran' routines, and are not meant to be called by the user.


bgw_mle

Description

Performs maximum likelihood estimation (MLE) for the user-provided model defined in calcR. Version 0.1.5.

Usage

bgw_mle(calcR, betaStart, calcJ = NULL, bgw_settings = NULL, calcJ_type = NULL)

Arguments

calcR

Function that computes an n-vector (R) of model residuals for a p-vector of (numeric) parameters beta (the first argument). (The beta vector can be named or unnamed.) Because bgw_mle performs maximum likelihood estimation (MLE), R_i is the likelihood (probability) of the ith observation, and the estimate is the value of beta that minimizes the negative log-likelihood NLL = -Sum_i [log(R_i)].

betaStart

Vector of initial starting values for beta. Can be either a named or unnamed vector.

calcJ

Optional function that computes analytic derivative (Jacobian) information for the n-vector R, with beta as its first argument, as for calcR. If calcJ is NULL (the default), estimation uses finite-difference derivatives. Starting with version 0.1.5, the Jacobian can be supplied in several forms (see Details), so whenever calcJ is supplied, calcJ_type should be supplied as well.

bgw_settings

List. Contains control parameters for BGW estimation code. All parameters have default values, so user input is entirely optional.

  • printLevel: Integer (0-3). Controls the level of detail for iteration information written to the console during estimation. 0 = silent, 1 = print starting values and final solution only, 2 = short line summary, 3 = long line summary (see documentation). Default = 3.

  • silent: Logical. Suppresses all output. Default = FALSE. (Currently redundant with printLevel = 0.)

  • printNonDefaultSettings: Logical. Echos any user-provided bgw_settings. Default = TRUE.

  • printStartingValues: Logical. Default = TRUE. Print starting values for beta.

  • printFinalResults: Logical. Default = TRUE. Print final status of estimation (convergence/error message), summary statistics (negative log-likelihood, iterations, function evals, etc.), beta, gradient, and (if available) estimated standard errors and t-ratios. (See vcHessianMethod for variance-covariance specification.)

  • maxIterations: Numeric. Maximum number of iterations for the estimation. Default is 200. A value of 0 requests a model object at betaStart without estimation (see userRequestModelObject).

  • maxFunctionEvals: Numeric. Maximum number of objective function evaluations. Default is 300.

  • modelName: Character. Used to create names for requested output files. Default is "bgw_mle_model."

  • outputDirectory: Character. Directory in which to write output files. It is created if it does not exist. Default is the current working directory.

  • writeItSummary: Logical. If TRUE, iteration information is echoed in the output file "modelName_itSummary.csv". Default is FALSE. [Not currently implemented.]

  • writeIter: Logical. If TRUE, parameters and log-likelihood for each iteration are written to "modelName_iterations.csv". The columns are the parameter names (or beta1, beta2, ... if betaStart has no names), logLike, Iteration and ItType. An existing file is replaced, unless writeIterMode is "append". Default is FALSE.

  • writeIterMode: Character. "overWrite" (the default) replaces any existing iteration files; "append" adds to them. Applies to writeIter, writeIterGradient and writeIterScaleVec.

  • writeIterGradient: Logical. If TRUE, the gradient of the log-likelihood at each iteration is written to "modelName_gradients.csv", with the same columns as for writeIter. Its sign is opposite to that of the returned gradient, which is the gradient of the negative log-likelihood. Default is FALSE.

  • writeIterScaleVec: Logical. If TRUE, the scale vector at each iteration is written to "modelName_scaleVecs.csv", with the same columns as for writeIter. Default is FALSE.

  • vcHessianMethod: Character. Method for computing the Hessian approximation used for the variance-covariance matrix (VC = H^(-1)). Options are: "none","bhhh","finiteDifferences", or "fdFunction" ("finiteDifferences" automatically uses gradient differences if a gradient is available, otherwise it uses objective function differences. "fdFunction" allows the user to use objective function differences even if a gradient is available). Default is "bhhh."

  • scalingMethod: Character. Method used to compute a scaling vector (scaleVec_i, i=1,..,p). Define a matrix D = diag(scaleVec_1,..., scaleVec_p). When using scaling, values in scaleVec should be chosen so that the elements of D*beta are roughly comparable in size. The re-scaled beta is used when computing trial steps using trust regions, and when computing stopping criteria. Options are: "adaptive," "none," and "userScaling": the default is "adaptive." For a description of the "adaptive" method, which updates scaleVec at each iteration using information from the model Jacobian, see Bunch, Gay, and Welsch (1993). For "none," scaleVec is set to a p-vector of ones for the entire search. The "userScaling" option indicates that the user is supplying their own (fixed) scaleVec in bgw_settings[["userScaleVector"]] (see next item). Both items must be properly set or an error occurs.

  • userScaleVector: Numeric, with dimension p = number of free parameters. Can be either a named or unnamed vector. This is a user-provided scaling vector that is used ONLY in conjunction with the non-default option "userScaling" for bgw_settings[["scalingMethod"]] (see previous item).

  • userRequestIndLevelGradients: Logical. If TRUE, BGW returns an n x p matrix containing individual-level gradients at the final value of beta. Specifically, if the log-likelihood = sum_i[log(R_i)], row i of the matrix is d log(R_i)/d beta. Available with both analytic (calcJ) and finite-difference derivatives. Default is FALSE.

  • userRequestModelObject: Logical. If TRUE, no estimation is performed. BGW returns a model object evaluated at betaStart, with code 20, iterations equal to 0, and a variance-covariance matrix based on the BHHH matrix (NULL if that matrix is singular). Requires vcHessianMethod = "bhhh" or "none". Default is FALSE.

calcJ_type

Character. Should be supplied whenever calcJ is supplied: "probability" if calcJ returns derivatives of R_i, or "log_probability" if it returns derivatives of log(R_i). See Details. If omitted, "log_probability" is assumed (see "Version 0.1.4 and earlier" under Details). Ignored if calcJ is NULL.

Details

This function has been written to provide an R-based interface to Fortran estimation software published in Bunch, Gay and Welsch (1993), "Algorithm 717-Subroutines for Maximum Likelihood and Quasi-Likelihood Estimation of Parameters in Nonlinear Regression Models," ACM Transactions on Mathematical Software, 19 (1), March 1993, 109-130. The letters BGW will be used in various ways to denote the source of the estimation functionality.

A primary motivation was to develop a more efficient maximum likelihood estimation function for use in the Apollo choice modelling package: see https://www.apollochoicemodelling.com/. However, we have adopted a design whereby the BGW package is wholly independent of Apollo, and can be used in a stand-alone fashion. Note also that the BGW Fortran subroutines are written to support general statistical estimation for an arbitrary objective/criterion function. So, although this version of the package is specifically written for MLE, the package may see future updates that expand the number of estimation options (for, e.g., nonlinear least squares, generalized method of moments, etc.).

Remark: Following the convention in the numerical optimization literature, BGW minimizes the objective function. That is, bgw_mle minimizes the negative-log-likelihood for the model calcR.

Forms of the Jacobian (calcJ)

calcJ must return a matrix (not a vector), in one of the following forms.

Derivatives of probabilities. Formally, the Jacobian (J) is an n x p matrix whose [i,k] element is dR_i/dbeta_k. The equivalent information can be provided as a p x n matrix (J transpose). Because these are derivatives of probabilities, if J is provided in either form, the user should also set calcJ_type = "probability".

Derivatives of log-probabilities. Alternatively, J can be provided as an n x p matrix whose [i,k] element is d[log(R_i)]/dbeta_k, or, equivalently, the p x n matrix that is its transpose. In either case the user should set calcJ_type = "log_probability".

Orientation. bgw identifies from the dimensions whether J is n x p or p x n. In the rare case where n = p, the dimensions cannot show this and the matrix is read as n x p, so a square matrix must be supplied in the n x p form.

Version 0.1.4 and earlier. In earlier versions of bgw, the assumed form for J was the n x p matrix with [i,k] element d[log(R_i)]/dbeta_k. To maintain backward compatibility, if calcJ_type is missing, bgw assumes that J contains derivatives of log(R_i). Because this cannot be verified from the matrix itself, a calcJ that returns derivatives of probabilities must be accompanied by calcJ_type = "probability"; otherwise the results will be wrong.

Value

model object of class 'bgw_mle'. Output of a bgw maximum likelihood estimation procedure. A list with the following attributes: