MAR 580: Models for Marine Ecosystem-Based Management
TMB workshop
Session I, why TMB?
(Acknowledgements: Mollie Brooks, Kasper Kristensen, Arni Magnusson, Anders Nielsen, André Punt)
06 September 2022
Schedule
gavinfay.github.io/mebm-models/tmb�
Rstudio Cloud project
Aims of workshop:
* Introduce TMB
* Conduct several examples
Models in fisheries, fitting to data
What is Template Model Builder?
Put simply, it is an R package to help conduct optimization (parameter estimation) of highly nonlinear models. It includes:
TMB or AD Model Builder?
e.g. ASAP, Stock Synthesis, CASAL, etc.
e.g. SAM, WHAM,
Specifying the Problem – the TMB approach
Work environment – the TMB approach
Hint: make RStudio your default .cpp editor
Recommend running TMB:::setupRStudio()
8
Taken from https://github.com/James-Thorson/2016_Spatio-temporal_models
Work environment – the TMB approach
First example: linear regression
Review
#include <TMB.hpp>
template<class Type>
Type objective_function<Type>::operator() ()
{
//insert your model here
return neglogL:
}
Review
Understanding MakeADFun arguments
MakeADFun’s map
e.g. map = list(b0=factor(NA)) #don’t estimate intercept
e.g. if you have a vector beta and you want elements 2 & 4 to be the same:
map = list(beta=factor(c(1,2,3,2)))
Reporting
Use REPORT to get results back into R
e.g.
Type sigma = exp(logSigma);
REPORT(sigma);
Access in R via:
model$report();
Variances for derived quantities
sdreport(model)
- asymptotic variances for parameters
To compute standard errors for derived quantities, define ADREPORT variable:
e.g.
Type sigma = exp(logSigma);
ADREPORT(sigma);
sdreport(model);
Variance information
model$he()
solve(model$he())
cov2cor(solve(model$he()))
sqrt(diag(solve(model$he()))))
Data Types
TMB needs to know what dimensions and format your data/variables/parameters will be in.
Parameter Types
PARAMETER(par_name);
PARAMETER_VECTOR(par_name);
Local Variables
Type p; [scalar]
vector<Type> q(5); [vector]
matrix<Type> z(5,5); [matrix]
array<Type>k(5,5,5); [array]
int I; [integer]
vector<int>jj(5); [integer vector]
Variable Names
Other rules / hints:
http://kaskr.github.io/adcomp/_book/CppTutorial.html#i-know-r-but-not-c
Programming Style
Comment, comment, comment:
(indicated by “#”).
Getting Help, and debugging hints
Linear modeling review LMs, GLMs, NLMs
Quite flexible as it is
Any error distribution
Any relationship between Y and X
closed�form�solution
iterative�solution
Example: Poisson GLM
Exercise: Poisson GLM with covariate
Y(i) ~ Poisson(λ(i))
ln(λ(i)) = βmonth(i)