Title: | 'ADMB' to R Interface Functions |
---|---|
Description: | A series of functions to call 'AD Model Builder' (i.e., compile and run models) from within R, read the results back into R as 'admb' objects, and provide standard accessors (i.e. coef(), vcov(), etc.) |
Authors: | Ben Bolker [aut, cre], Hans Skaug [aut], Jeff Laake [aut] |
Maintainer: | Ben Bolker <[email protected]> |
License: | GPL |
Version: | 0.7.16.3 |
Built: | 2024-11-22 03:20:51 UTC |
Source: | https://github.com/cran/R2admb |
A series of functions to call AD Model Builder (i.e., compile and run models) from within R, read the results back into R as "admb" objects, and provide standard accessors (i.e. coef(), vcov(), etc.)
Package: | R2admb |
Type: | Package |
Version: | 0.5 |
Date: | 2009-11-11 |
License: | GPL |
LazyLoad: | yes |
More here!
Ben Bolker
Maintainer: Ben Bolker <[email protected]>
PBSadmb package, glmmADMB package, ADMB2R
Report on the version of ADMB being used.
admb_version()
admb_version()
Prints the version string from a compiled ADMB file, and returns the value (invisibly) as a character vector; returns NA if ADMB is not installed
Ben Bolker
admb_version()
admb_version()
Extract standard information such as log-likelihood, AIC, coefficients, etc. from ADMB model fits
## S3 method for class 'admb' AIC(object, ..., k = 2) ## S3 method for class 'admb' confint(object, parm, level = 0.95, method = "default", type = "fixed", ...) ## S3 method for class 'admb' print(x, verbose = FALSE, ...) ## S3 method for class 'admb' summary(object, correlation = FALSE, symbolic.cor = FALSE, ...) ## S3 method for class 'summary.admb' print(x, digits = max(3, getOption("digits") - 3), symbolic.cor = x$symbolic.cor, signif.stars = getOption("show.signif.stars"), ...) ## S3 method for class 'admb' logLik(object, ...) ## S3 method for class 'admb' coef(object, type = "fixed", ...) ## S3 method for class 'admb' vcov(object, type = "fixed", ...) stdEr(object, ...) ## S3 method for class 'admb' stdEr(object, type = "fixed", ...) ## S3 method for class 'admb' deviance(object, ...)
## S3 method for class 'admb' AIC(object, ..., k = 2) ## S3 method for class 'admb' confint(object, parm, level = 0.95, method = "default", type = "fixed", ...) ## S3 method for class 'admb' print(x, verbose = FALSE, ...) ## S3 method for class 'admb' summary(object, correlation = FALSE, symbolic.cor = FALSE, ...) ## S3 method for class 'summary.admb' print(x, digits = max(3, getOption("digits") - 3), symbolic.cor = x$symbolic.cor, signif.stars = getOption("show.signif.stars"), ...) ## S3 method for class 'admb' logLik(object, ...) ## S3 method for class 'admb' coef(object, type = "fixed", ...) ## S3 method for class 'admb' vcov(object, type = "fixed", ...) stdEr(object, ...) ## S3 method for class 'admb' stdEr(object, type = "fixed", ...) ## S3 method for class 'admb' deviance(object, ...)
object |
an ADMB model fit (of class "admb") |
... |
other parameters (for S3 generic compatibility) |
k |
penalty value for AIC fits |
parm |
(currently ignored: FIXME) select parameters |
level |
alpha level for confidence interval |
method |
(character): "default" or "quad", quadratic (Wald) intervals based on approximate standard errors; "profile", profile CIs (if profile was computed); "quantile", CIs based on quantiles of the MCMC-generated posterior density (if MCMC was computed); "HPDinterval", CIs based on highest posterior density (ditto) |
type |
which type of parameters to report. Character vector, including one or more of "fixed" or "par" (standard, fixed-effect parameters); "random" (random effect parameters); "rep" (report variables); "sdrpt" (sdreport variables); "extra" (report and sdreport); "all" (all of the above). |
x |
an ADMB model fit (of class "admb") |
verbose |
show messages |
correlation |
currently unused parameter |
symbolic.cor |
currently unused parameter |
digits |
number of digits to display |
signif.stars |
show significance stars? |
Extracts appropriate values: numeric (scalar) for AIC, type logLik for logLik, numeric vector of coefficients, numeric variance-covariance matrix of parameter estimates
admbex <- system.file("doc","Reedfrog_runs.RData",package="R2admb") load(admbex) m1 coef(m1) summary(m1) coef(summary(m1)) ## returns just z-table AIC(m1) vcov(m1) logLik(m1) deviance(m1) stdEr(m1)
admbex <- system.file("doc","Reedfrog_runs.RData",package="R2admb") load(admbex) m1 coef(m1) summary(m1) coef(summary(m1)) ## returns just z-table AIC(m1) vcov(m1) logLik(m1) deviance(m1) stdEr(m1)
With various tests, calls the admb
script to compile from a TPL file
to an executable, or runs the resulting executable
compile_admb(fn,safe=FALSE,re=FALSE, verbose=FALSE, admb_errors=c("stop","warn","ignore")) run_admb(fn,verbose=FALSE,mcmc=FALSE, mcmc.opts=mcmc.control(),profile=FALSE, extra.args="",admb_errors=c("stop","warn","ignore")) read_admb(fn,verbose=FALSE,profile=FALSE, mcmc=FALSE,mcmc.opts=NULL,admbOut=NULL,checkterm=TRUE)
compile_admb(fn,safe=FALSE,re=FALSE, verbose=FALSE, admb_errors=c("stop","warn","ignore")) run_admb(fn,verbose=FALSE,mcmc=FALSE, mcmc.opts=mcmc.control(),profile=FALSE, extra.args="",admb_errors=c("stop","warn","ignore")) read_admb(fn,verbose=FALSE,profile=FALSE, mcmc=FALSE,mcmc.opts=NULL,admbOut=NULL,checkterm=TRUE)
fn |
(character) name of TPL file, without extension |
safe |
(logical) Compile in safe mode? |
re |
(logical) Compile in random effects (ADMB-RE) mode? |
verbose |
(logical) Verbose output? |
admb_errors |
(character) how to handle compilation/linking errors? |
profile |
(logical) Run likelihood profiles? |
extra.args |
(character) extra arguments for ADMB run |
mcmc |
(logical) run post-hoc MCMC? |
mcmc.opts |
options for MCMC run (see |
admbOut |
(character) ADMB run output for inclusion in |
checkterm |
(logical) compute termination criteria (ratio of min/max eigenvalue) and include it in the saved object? |
compile_admb
returns nothing (it has the side
effect of creating an executable)
run_admb
invisibly returns the
output produced by the ADMB run; it also produces output files on disk as a
side effect
read_admb
returns an object of class admb
,
containing as much information as possible gleaned from the output files
(parameter estimates, standard errors, variance-covariance matrix, profiles,
MCMC output)
Compiling also sets executable mode.
Ben Bolker
Compile an ADMB model, run it, collect output
do_admb(fn, data = NULL, params = NULL, bounds = NULL, phase = NULL, re = NULL, data_type = NULL, safe = TRUE, profile = NULL, profile.opts = NULL, mcmc = NULL, mcmc.opts = mcmc.control(), impsamp = FALSE, verbose = FALSE, run.opts = run.control(), objfunname = "f", workdir = getwd(), admb_errors = c("stop", "warn", "ignore"), extra.args)
do_admb(fn, data = NULL, params = NULL, bounds = NULL, phase = NULL, re = NULL, data_type = NULL, safe = TRUE, profile = NULL, profile.opts = NULL, mcmc = NULL, mcmc.opts = mcmc.control(), impsamp = FALSE, verbose = FALSE, run.opts = run.control(), objfunname = "f", workdir = getwd(), admb_errors = c("stop", "warn", "ignore"), extra.args)
fn |
(character) base name of a TPL function, located in the working directory |
data |
a named list of input data variables (order must match TPL file): each element of the list can either be a single value, or a list containing elements
|
params |
a named list of starting parameter values (order must match TPL file): each element of the list can either be a single value, or a list containing elements
|
bounds |
named list of 2-element vectors of lower and upper bounds for specified parameters |
phase |
named numeric vector of phases (not implemented yet) |
re |
a named list of the identities and dimensions of any random effects vectors or matrices used in the TPL file |
data_type |
a named vector specifying (optional) data types for
parameters, in parname="storage mode" format (e.g.
|
safe |
(logical) compile in safe mode? |
profile |
(logical) generate likelihood profiles? (untested!) |
profile.opts |
(list) list of options, including
|
mcmc |
(logical) run MCMC around best fit? |
mcmc.opts |
options for MCMC (see |
impsamp |
(logical) run importance sampling? |
verbose |
(logical) print details |
run.opts |
options for ADMB run (see |
objfunname |
(character) name for objective function in TPL file (only relevant if |
workdir |
temporary working directory (dat/pin/tpl files will be copied) |
admb_errors |
how to treat ADMB errors (in either compilation or run): use "ignore" option at your own risk! |
extra.args |
(character) extra argument string to pass to admb |
do_admb
will attempt to do everything required to start from the model
definition (TPL file) specified by fn
, the data list, and the list of
input parameters, compile and run (i.e. minimize the objective function of)
the model in AD Model Builder, and read the results back into an object of
class admb
in R. If checkparam
or checkdata
are set to
"write", it will attempt to construct a DATA section, and construct or
(augment an existing) PARAMETER section (which may contain definitions of
non-input parameters to be used in the model). It copies the input TPL file
to a backup (.bak); on finishing, it restores the original TPL file and
leaves the auto-generated TPL file in a file called [fn]_gen.tpl.
An object of class admb
.
1. Mixed-case file names are ignored by ADMB; this function makes a temporary copy with the file name translated to lower case. 2. Parameter names containing periods/full stops will not work, because this violates C syntax (currently not checked). 3. There are many, many, implicit restrictions and assumptions: for example, all vectors and matrices are assumed to be indexed starting from 1.
Ben Bolker
## Not run: setup_admb() file.copy(system.file("tplfiles","ReedfrogSizepred0.tpl",package="R2admb"),"tadpole.tpl") tadpoledat <- data.frame(TBL = rep(c(9,12,21,25,37),each=3), Kill = c(0,2,1,3,4,5,0,0,0,0,1,0,0,0,0L), nexposed=rep(10,15)) m1 <- do_admb("tadpole", data=c(list(nobs=15),tadpoledat), params=list(c=0.45,d=13,g=1), bounds=list(c=c(0,1),d=c(0,50),g=c(-1,25)), run.opts=run.control(checkparam="write", checkdata="write",clean="all")) m2 <- do_admb("tadpole", data=c(list(nobs=15),tadpoledat), params=list(c=list(0.45,bounds=c(0,1)), d=list(13,bounds=c(0,50)), g=list(1,bounds=c(-1,25))), run.opts=run.control(checkparam="write", checkdata="write",clean="all")) unlink("tadpole.tpl") ## End(Not run)
## Not run: setup_admb() file.copy(system.file("tplfiles","ReedfrogSizepred0.tpl",package="R2admb"),"tadpole.tpl") tadpoledat <- data.frame(TBL = rep(c(9,12,21,25,37),each=3), Kill = c(0,2,1,3,4,5,0,0,0,0,1,0,0,0,0L), nexposed=rep(10,15)) m1 <- do_admb("tadpole", data=c(list(nobs=15),tadpoledat), params=list(c=0.45,d=13,g=1), bounds=list(c=c(0,1),d=c(0,50),g=c(-1,25)), run.opts=run.control(checkparam="write", checkdata="write",clean="all")) m2 <- do_admb("tadpole", data=c(list(nobs=15),tadpoledat), params=list(c=list(0.45,bounds=c(0,1)), d=list(13,bounds=c(0,50)), g=list(1,bounds=c(-1,25))), run.opts=run.control(checkparam="write", checkdata="write",clean="all")) unlink("tadpole.tpl") ## End(Not run)
Extract gradient values from last iteration of screen output and return dataframe with variable names, values and gradient, sorted in order of ascending absolute value of the gradient.
extract_gradient(admbfile)
extract_gradient(admbfile)
admbfile |
base name of admb project |
a dataframe with 3 columns var=variable name, value= final parameter value, gradient= gradient value
Jeff Laake
Find any correlations for which their absolute value exceeds a specified amount (rho). Returns a dataframe with row and column names and correlation from lower triangular matrix.
find_large_cor(x, rho = 0.9)
find_large_cor(x, rho = 0.9)
x |
correlation matrix |
rho |
abolute value for lower bound of correlation |
a dataframe with 3 columns var1=row name, var2= column name or number, Value of matrix element. Only contains rows in which matrix element satisfies logical expression.
Jeff Laake
Determines the options (number of steps, save interval, etc.) for running MCMC based on the estimated mode (maximum likelihood estimate) and parameter variance-covariance matrix
mcmc.control(mcmc = 1000, mcmc2 = 0, mcsave, mcnoscale = FALSE, mcgrope = FALSE, mcmult = 1, mcmcpars = NULL)
mcmc.control(mcmc = 1000, mcmc2 = 0, mcsave, mcnoscale = FALSE, mcgrope = FALSE, mcmult = 1, mcmcpars = NULL)
mcmc |
Total number of MCMC steps |
mcmc2 |
MCMC2 steps (see ADMB-RE manual) |
mcsave |
Thinning interval for values saved in the PSV file. Default is
|
mcnoscale |
don't rescale step size for mcmc depending on acceptance rate |
mcgrope |
(double) Use a candidate distribution that is a mixture of a
multivariate normal and a fatter-tailed distribution with a proportion
|
mcmult |
Multiplier for the MCMC candidate distribution |
mcmcpars |
(character) vector of parameters to track in MCMC run.
At least one must be specified. ADMB produces two kinds of output for
MCMC. For any |
See the AD Model Builder reference manual. The mcrb
option (reduce
correlation of the Hessian when constructing the candidate distribution) and
the mcseed
options (seed for random number generator) are not yet
implemented; mcnoscale
above may not work properly
Returns a list of options suitable for passing as the
mcmc.opts
argument to do_admb
Some options (mcmc2
, etc.) that can be used in AD Model Builder
and ADMB-RE may not be available
Ben Bolker
mcmc.control(mcmc=2000)
mcmc.control(mcmc=2000)
Plot MCMC histogram
## S3 method for class 'admb_hist' plot(x,type=c("lattice","ggplot"),dtype=c("hist","density"),pars,...)
## S3 method for class 'admb_hist' plot(x,type=c("lattice","ggplot"),dtype=c("hist","density"),pars,...)
x |
plotting data |
type |
only "lattice" at present |
dtype |
either "hist" or "density" |
pars |
passed to rhist |
... |
additional parameters for compatibility |
plot object
Reads coefficients, standard errors, log-likelihoods, maximum gradients, correlation and variance-covariance matrices from AD Model Builder output files
read_pars(fn, drop_phase = TRUE, covfn = "admodel.cov", warn_nonstd_rep = TRUE) read_psv(fn, names = NULL) read_rep(fn, names = NULL, warn_nonstd_rep = TRUE)
read_pars(fn, drop_phase = TRUE, covfn = "admodel.cov", warn_nonstd_rep = TRUE) read_psv(fn, names = NULL) read_rep(fn, names = NULL, warn_nonstd_rep = TRUE)
fn |
(character) Base name of AD Model Builder |
drop_phase |
(logical) drop negative-phase (fixed) parameters from results? |
covfn |
(character) file name for covariance matrix information |
warn_nonstd_rep |
warn if report file is in nonstandard format? |
names |
(character) Names of variables |
Given the output from an ADMB run on FOO.tpl, read_pars
reads the
files FOO.par (parameters, log-likelihood, max gradient); FOO.std (standard
deviations); FOO.cor (correlations); FOO.rep (report variables);
admodel.hes for hessian; and admodel.cov for
covariance matrix. read_psv
reads the output of MCMC runs.
read_rep
(called by read_admb
to read the .rep
file) first
checks if the report file is in a standard format: first line starts with a
comment character (#); thereafter, each block starts with a single commented
line containing the name of the parameter (possibly ending with a colon),
followed by a block of all-numeric lines, which are read as a single vector.
If the report file is in a standard format, the values are added to the end
of the coefficients list. Otherwise, the numeric values from the report file
are included in the results as a single, concantenated numeric vector.
List containing the following elements
coefficientsparameter estimates
coeflistparameter estimates in list format, with proper shape (vectors, matrices, etc.)
seestimated standard errors of coefficients
logliklog-likelihood
maxgradmaximum gradient of log-likelihood surface
corcorrelation matrix
vcovvariance-covariance matrix
nparnumber of parameters
heshessian matrix (only if no vcov matrix)
reportvalues from report file (if non-standard report file)
The coeflist
component is untested for data
structures more complicated than scalars, vectors or matrices (i.e. higher-dimensional or ragged arrays)
Because ADMB hard-codes the file name for covariance matrix information (admodel.cov
), care is necessary when running different models in the same directory; users may want to rename this file by hand and use the covfn
argument
Read in the output from ADMB likelihood profiling stored in a .plt
file
read_plt(varname)
read_plt(varname)
varname |
(character) Name of profiled variable (base name of |
List containing the following elements:
prof |
likelihood profile: a two-column matrix containing the parameter value and the corresponding likelihood (not the log-likelihood or negative log-likelihood), scaled to integrate to 1.0 |
ci |
matrix of upper and lower confidence intervals at the 0.9, 0.95, and 0.975 levels |
prof_norm |
likelihood profile, based on a normal approximation |
cinorm |
confidence interval matrix, based on normal approximation |
A helper function
run.control(check_tpl = TRUE, write_files = TRUE, checkparam = c("stop", "warn", "write", "ignore"), checkdata = c("stop", "warn", "write", "ignore"), compile = TRUE, run = TRUE, read_files = TRUE, clean_files = "all")
run.control(check_tpl = TRUE, write_files = TRUE, checkparam = c("stop", "warn", "write", "ignore"), checkdata = c("stop", "warn", "write", "ignore"), compile = TRUE, run = TRUE, read_files = TRUE, clean_files = "all")
check_tpl |
Check the specified TPL file for problems? |
write_files |
Write out data and initialization files? |
checkparam |
How to check |
checkdata |
as with |
compile |
compile the TPL file (via ADMB) into an executable? |
run |
run the executable file with the specified data/initial values? |
read_files |
read the results of an ADMB run into R? |
clean_files |
Delete working files after completion of the run? Options
are |
A list with appropriate default values inserted for passing to
do_admb
Ben Bolker
Attempts to set environment variables so that AD Model Builder will "just work" when run from inside R
setup_admb(admb_home) clean_admb(fn,which=c("sys","output"))
setup_admb(admb_home) clean_admb(fn,which=c("sys","output"))
admb_home |
(character) directory containing AD Model Builder binary files |
fn |
(character) base name of ADMB model files |
which |
what to remove: any combination of "sys" (system), "input", "output", or "all" or "none" |
(1) If the environment variable ADMB_HOME is not already set and admb_home is not specified, this function will try to set it sensibly. (I.e., on Unix systems, it will run a "locate" command (if one is available) to try to find the binaries, and thereafter check if they are installed in the default location (/usr/local/admb); on Windows it will assume they are installed in the default location (C:/ADMB).) (2) If ADMB_HOME is set and admb_home is not specified, it will leave the original setting alone. (3) If admb_home is specified, it will set the environment variable ADMB_HOME to that value.
The function also prepends the admb_home value to the PATH variable.
A character vector containing the name of the current ADMB_HOME.
Ben Bolker
orig <- Sys.getenv("ADMB_HOME") ## this doesn't make sense but won't break anything ## until you actually try to run AD Model Builder setup_admb("elsewhere") Sys.setenv(ADMB_HOME="") ## erase environment variable ## Not run: setup_admb() ## auto-locate (fails if ADMB not found) ## End(Not run) Sys.setenv(ADMB_HOME=orig) ## restore sanity
orig <- Sys.getenv("ADMB_HOME") ## this doesn't make sense but won't break anything ## until you actually try to run AD Model Builder setup_admb("elsewhere") Sys.setenv(ADMB_HOME="") ## erase environment variable ## Not run: setup_admb() ## auto-locate (fails if ADMB not found) ## End(Not run) Sys.setenv(ADMB_HOME=orig) ## restore sanity
Given base filenames and lists, write output files for starting parameter values and data in a format suitable for input by AD Model Builder from glmmADMB, by Hans Skaug
write_pin(name,L) write_dat(name, L, append=FALSE)
write_pin(name,L) write_dat(name, L, append=FALSE)
name |
(character) the base name of the file |
L |
a list of objects to be written to file |
append |
(logical) append to existing file? |
Returns nothing; creates files in the current working directory as a side effect
numeric vectors and matrices are the only objects that can be written (at present)
Hans Skaug