Learn R Programming

glmmTMB (version 1.1.10)

fitTMB: Optimize TMB models and package results, modularly

Description

These functions (called internally by glmmTMB) perform the actual model optimization, after all of the appropriate structures have been set up (fitTMB), and finalize the model after optimization (finalizeTMB). It can be useful to run glmmTMB with doFit=FALSE, adjust the components as required, and then finish the fitting process with fitTMB (however, it is the user's responsibility to make sure that any modifications create an internally consistent final fitted object).

Usage

fitTMB(TMBStruc, doOptim = TRUE)

finalizeTMB(TMBStruc, obj, fit, h = NULL, data.tmb.old = NULL)

Arguments

TMBStruc

a list containing lots of stuff ...

doOptim

logical; do optimization? If FALSE, return TMB object

obj

object created by fitTMB(., doOptim = FALSE)

fit

a fitted object returned from nlminb, or more generally a similar list (i.e. containing elements par, objective, convergence, message, iterations, evaluations)

h

Hessian matrix for fit, if computed in previous step

data.tmb.old

stored TMB data, if computed in previous step

Examples

Run this code
## 1. regular (non-modular) model fit:
m0 <- glmmTMB(count ~ mined + (1|site),
             family=poisson, data=Salamanders)
## 2. the equivalent fit, done modularly:
##  a. 
m1 <- glmmTMB(count ~ mined + (1|site),
             family=poisson, data=Salamanders,
             doFit = FALSE)
## result is a list of elements (data to be passed to TMB,
## random effects structures, etc.) needed to fit the model
names(m1)
## b. The next step calls TMB to set up the automatic differentiation
## machinery
m2 <- fitTMB(m1, doOptim = FALSE)
## The result includes initial parameter values, objective function
## (fn), gradient function (gr), etc.
names(m2)
## Optionally, one could choose to 
## modify the components of m1$env$data at this point ...
## updating the TMB structure as follows may be necessary:
m2 <- with(m2$env,
               TMB::MakeADFun(data,
                               parameters,
                               map = map,
                               random = random,
                               silent = silent,
                               DLL = "glmmTMB"))
## c. Use the starting values, objective function, and gradient
## function set up in the previous step to do the nonlinear optimization
m3 <- with(m2, nlminb(par, objective = fn, gr = gr))
## the resulting object contains the fitted parameters, value of
## the objective function, information on convergence, etc.
names(m3)
## d. The last step is to combine the information from the previous
## three steps into a \code{glmmTMB} object that is equivalent to
## the original fit
m4 <- finalizeTMB(m1, m2, m3)
m4$call$doFit <- NULL ## adjust 'call' element to match
all.equal(m0, m4)

Run the code above in your browser using DataLab