bugs: Run MultiBUGS from R

Description Usage Arguments Details Value Author(s) References See Also Examples

View source: R/bugs.R

Description

The bugs function takes data and starting values as input. It automatically writes a MultiBUGS script, calls the model, and saves the simulations for easy access in R.

Usage

1
2
3
4
5
6
7
8
9
bugs(data, inits, parameters.to.save, n.iter, model.file = "model.txt",
  fix.founders = TRUE, n.chains = 3, n.burnin = floor(n.iter/2),
  n.thin = 1, n.workers = detectCores() - 1, saveExec = FALSE,
  restart = FALSE, debug = FALSE, DIC = TRUE, digits = 5,
  codaPkg = FALSE, MultiBUGS.pgm = NULL, working.directory = NULL,
  clearWD = FALSE, useWINE = FALSE, WINE = NULL, newWINE = TRUE,
  WINEPATH = NULL, bugs.seed = 1, summary.only = FALSE,
  save.history = (.Platform$OS.type == "windows" | useWINE == TRUE),
  over.relax = FALSE)

Arguments

data

either a named list (names corresponding to variable names in the model.file) of the data for the MultiBUGS model, or a vector or list of the names of the data objects used by the model. If data is a one element character vector (such as 'data.txt'), it is assumed that data have already been written to the working directory into that file, e.g. by the function bugs.data.

inits

a list with n.chains elements; each element of the list is itself a list of starting values for the MultiBUGS model, or a function creating (possibly random) initial values. Alternatively, if inits=NULL, initial values are generated by MultiBUGS. If inits is a character vector with n.chains elements, it is assumed that inits have already been written to the working directory into those files, e.g. by the function bugs.inits.

parameters.to.save

character vector of the names of the parameters to save which should be monitored

n.iter

number of total iterations per chain (including burn in; default: 2000)

model.file

File containing the model written in MultiBUGS code. The extension must be ‘.txt’. The default location is given by working.directory. The old convention allowing model.file to be named ‘.bug’ has been eliminated because the MultiBUGS feature that allows the program image to be saved and later restarted uses the .bug extension for the saved images. Alternatively, model.file can be an R function that contains a BUGS model that is written to a temporary model file (see tempfile) using write.model.

fix.founders

If TRUE, If the fix founder box is checked instead of generating initial values for founder nodes (nodes of topological depth one in the graphical model) the values of therse nodes is set to the mean of their prior.

n.chains

number of Markov chains (default: 3)

n.burnin

length of burn in, i.e. number of iterations to discard at the beginning. Default is n.iter/2, that is, discarding the first half of the simulations.

n.thin

Thinning rate. Must be a positive integer. The default is n.thin = 1.

The thinning is implemented in the MultiBUGS update phase, so thinned samples are never stored, and they are not counted in n.burnin or n.iter. Setting n.thin=2, doubles the number of iterations MultiBUGS performs, but does not change n.iter or n.burnin. Thinning implemented in this manner is not captured in summaries created by packages such as coda.

n.workers

Number of workers to distribute computation within MultiBUGS across. By default one core fewer than detected by detectCores is used.

saveExec

If TRUE, a re-startable image of the MultiBUGS execution is saved with basename (model.file) and extension .bug in the working directory, which must be specified. The .bug files can be large, so users should monitor them carefully and remove them when not needed.

restart

If TRUE, execution resumes with the final status from the previous execution stored in the .bug file in the working directory. If n.burnin=0,additional iterations are performed and all iterations since the previous burnin are used (including those from past executions). If n.burnin>0, a new burnin is performed, and the previous iterations are discarded, but execution continues from the status at the end of the previous execution. When restart=TRUE, only n.burnin, n.iter, and saveExec inputs should be changed from the call creating the .bug file, otherwise failed or erratic results may be produced. Note the default has n.burnin>0.

debug

if FALSE (default), MultiBUGS is closed automatically when the script has finished running, otherwise MultiBUGS remains open for further investigation. The debug option is not available for linux execution.

DIC

logical; if TRUE (default), compute deviance, pD, and DIC. The results are extracted directly from the MultiBUGS log, which uses the rule pD = Dbar - Dhat. If extraction fails or if there are less iterations than required for the adaptive phase, the rule pD=var(deviance) / 2 is computed in R. See bugs.log for more information on extracting results from the log file.

digits

number of significant digits used for MultiBUGS input, see formatC

codaPkg

logical; if FALSE (default) a bugs object is returned, if TRUE file names of MultiBUGS output are returned for easy access by the coda package through function read.bugs. A bugs object can be converted to an mcmc.list object as used by the coda package with the method as.mcmc.list (for which a method is provided by R2MultiBUGS).

MultiBUGS.pgm

For Windows or WINE execution, the full path to the MultiBUGS executable. For linux execution, the full path to the MultiBUGS executable or shell script (the path to the shell script is not required if the MultiBUGS shell script is in the user's PATH variable). If NULL (unset) and the environment variable MultiBUGS_PATH is set the latter will be used as the default. If NULL (unset), the environment variable MultiBUGS_PATH is unset and the global option R2MultiBUGS.pgm is not NULL the latter will be used as the default. If none of the former are set and OS is Windows, the most recent MultiBUGS version registered in the Windows registry will be used as the default. For other operating systems, the location is guessed by Sys.which('MultiBUGS').

working.directory

sets working directory during execution of this function; MultiBUGS' input and output will be stored in this directory; if NULL, a temporary working directory via tempdir is used.

clearWD

logical; indicating whether the files ‘data.txt’, ‘inits[1:n.chains].txt’, ‘log.odc’, ‘codaIndex.txt’, and ‘coda[1:nchains].txt’ should be removed after MultiBUGS has finished. If set to TRUE, this argument is only respected if codaPkg=FALSE.

useWINE

logical; attempt to use the Wine emulator to run MultiBUGS. Default is FALSE. If WINE is used, the arguments MultiBUGS.pgm and working.directory must be given in form of Linux paths rather than Windows paths (if not NULL).

WINE

Character, path to ‘wine’ binary file, it is tried hard (by a guess and the utilities which and locate) to get the information automatically if not given.

newWINE

Use new versions of Wine that have ‘winepath’ utility

WINEPATH

Character, path to ‘winepath’ binary file, it is tried hard (by a guess and the utilities which and locate) to get the information automatically if not given.

bugs.seed

[This is not currently honoured by R2MultiBUGS.] Random seed for MultiBUGS. Must be an integer between 1-14. Seed specification changed between WinBUGS and OpenBUGS; see the MultiBUGS documentation for details.

summary.only

If TRUE, only a parameter summary for very quick analyses is given, temporary created files are not removed in that case.

save.history

If TRUE (the default), trace plots are generated at the end.

over.relax

If TRUE, over-relaxed form of MCMC is used if available from MultiBUGS.

Details

To run:

  1. Write a BUGS model in an ASCII file (hint: use write.model).

  2. Go into R.

  3. Prepare the inputs for the bugs function and run it (see Example section).

  4. An MultiBUGS window will pop up and will freeze up. The model will now run in MultiBUGS. It might take awhile. You will see things happening in the Log window within MultiBUGS. When MultiBUGS is done, its window will close and R will work again.

  5. If an error message appears, re-run with debug=TRUE.

BUGS version support:

Operation system support:

If useWINE=TRUE is used, all paths (such as working.directory and model.file, must be given in native (Unix) style, but MultiBUGS.pgm can be given in Windows path style (e.g. “c:/Program Files/MultiBUGS/”) or native (Unix) style
(e.g. “/path/to/wine/folder/dosdevices/c:/Program Files/MultiBUGS/MultiBUGS321/MultiBUGS.exe”).

Value

If codaPkg=TRUE the returned values are the names of coda output files written by OpenBUGS containing the Markov Chain Monte Carlo output in the CODA format. This is useful for direct access with read.bugs.

If codaPkg=FALSE, the following values are returned:

n.chains

see Section ‘Arguments’

n.iter

see Section ‘Arguments’

n.burnin

see Section ‘Arguments’

n.thin

see Section ‘Arguments’

n.keep

number of iterations kept per chain (equal to (n.iter-n.burnin) / n.thin)

n.sims

number of posterior simulations (equal to n.chains * n.keep)

sims.array

3-way array of simulation output, with dimensions n.keep, n.chains, and length of combined parameter vector

sims.list

list of simulated parameters: for each scalar parameter, a vector of length n.sims for each vector parameter, a 2-way array of simulations, for each matrix parameter, a 3-way array of simulations, etc. (for convenience, the n.keep*n.chains simulations in sims.matrix and sims.list (but NOT sims.array) have been randomly permuted)

sims.matrix

matrix of simulation output, with n.chains*n.keep rows and one column for each element of each saved parameter (for convenience, the n.keep*n.chains simulations in sims.matrix and sims.list (but NOT sims.array) have been randomly permuted)

summary

summary statistics and convergence information for each saved parameter.

mean

a list of the estimated parameter means

sd

a list of the estimated parameter standard deviations

median

a list of the estimated parameter medians

root.short

names of argument parameters.to.save and “deviance”

long.short

indexes; programming stuff

dimension.short

dimension of indexes.short

indexes.short

indexes of root.short

last.values

list of simulations from the most recent iteration; they can be used as starting points if you wish to run OpenBUGS for further iterations

pD

an estimate of the effective number of parameters, for calculations see the section “Arguments”.

DIC

mean(deviance) + pD

Author(s)

Andrew Gelman, gelman@stat.columbia.edu; modifications and packaged by Sibylle Sturtz, sturtz@statistik.tu-dortmund.de, Uwe Ligges, and Neal Thomas

References

Gelman, A., Carlin, J.B., Stern, H.S., Rubin, D.B. (2003): Bayesian Data Analysis, 2nd edition, CRC Press.

Sturtz, S., Ligges, U., Gelman, A. (2005): R2WinBUGS: A Package for Running WinBUGS from R. Journal of Statistical Software 12(3), 1-16.

See Also

print.bugs, plot.bugs, as well as coda and BRugs packages

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
## Not run: 
# An example model file is given in:
model.file <- system.file(package='R2MultiBUGS', 'model', 'schools.txt')
# Let's take a look:
#file.show(model.file)

# Some example data (see ?schools for details):
data(schools)
schools

J <- nrow(schools)
y <- schools$estimate
sigma.y <- schools$sd
data <- list ('J', 'y', 'sigma.y')
inits <- function(){
    list(theta=rnorm(J, 0, 100), mu.theta=rnorm(1, 0, 100),
         sigma.theta=runif(1, 0, 100))
}
## or alternatively something like:
# inits <- list(
#   list(theta=rnorm(J, 0, 90), mu.theta=rnorm(1, 0, 90),
#        sigma.theta=runif(1, 0, 90)),
#   list(theta=rnorm(J, 0, 100), mu.theta=rnorm(1, 0, 100),
#        sigma.theta=runif(1, 0, 100))
#   list(theta=rnorm(J, 0, 110), mu.theta=rnorm(1, 0, 110),
#        sigma.theta=runif(1, 0, 110)))

parameters <- c('theta', 'mu.theta', 'sigma.theta')

## You may need to specify 'MultiBUGS.pgm'
## also you need write access in the working directory:
schools.sim <- bugs(data, inits, parameters, model.file,
    n.chains=3, n.workers = 2, n.iter=5000)
print(schools.sim)
plot(schools.sim)

## End(Not run)

MultiBUGS/R2MultiBUGS documentation built on Aug. 14, 2019, 3:15 p.m.