Title: | Running 'WinBUGS' and 'OpenBUGS' from 'R' / 'S-PLUS' |
---|---|
Description: | Invoke a 'BUGS' model in 'OpenBUGS' or 'WinBUGS', a class "bugs" for 'BUGS' results and functions to work with that class. Function write.model() allows a 'BUGS' model file to be written. The class and auxiliary functions could be used with other MCMC programs, including 'JAGS'. |
Authors: | originally written by Andrew Gelman <[email protected]>; changes and packaged by Sibylle Sturtz <[email protected]> and Uwe Ligges <[email protected]>. With considerable contributions by Gregor Gorjanc <[email protected]> and Jouni Kerman <[email protected]>. Ported to S-PLUS by Insightful Corp. |
Maintainer: | Uwe Ligges <[email protected]> |
License: | GPL-2 |
Version: | 2.1-22.1 |
Built: | 2024-12-02 06:48:03 UTC |
Source: | CRAN |
R2WinBUGS package provides possiblity to call a BUGS model,
summarize inferences and convergence in a table and graph, and save the
simulations in arrays for easy access in R / S-PLUS. In S-PLUS, the
OpenBUGS functionality and the windows emulation functionality is
not yet available. The main command is bugs
.
The following are sources of information on R2WinBUGS package:
DESCRIPTION file | library(help="R2WinBUGS")
|
This file | package?R2WinBUGS
|
Vignette | vignette("R2WinBUGS")
|
Some help files | bugs
|
write.model
|
|
print.bugs
|
|
plot.bugs
|
|
News | file.show(system.file("NEWS", package="R2WinBUGS"))
|
Function converting results from Markov chain simulations,
that might not be from BUGS, to bugs object. Used mainly to display
results with plot.bugs
.
as.bugs.array(sims.array, model.file=NULL, program=NULL, DIC=FALSE, DICOutput=NULL, n.iter=NULL, n.burnin=0, n.thin=1)
as.bugs.array(sims.array, model.file=NULL, program=NULL, DIC=FALSE, DICOutput=NULL, n.iter=NULL, n.burnin=0, n.thin=1)
sims.array |
3-way array of simulation output, with dimensions n.keep, n.chains, and length of combined parameter vector. |
model.file |
file containing the model written in WinBUGS code |
program |
the program used |
DIC |
logical; whether DIC should be calculated, see also
argument |
DICOutput |
DIC value |
n.iter |
number of total iterations per chain used for generating
|
n.burnin |
length of burn in, i.e. number of iterations to
discarded at the beginning for generating |
n.thin |
thinning rate, a positive integer, used for generating
|
This function takes a 3-way array of simulations and makes it into a
bugs
object that can be conveniently displayed using
print
and plot
and accessed using attach.bugs
. If
the third dimension of sims() has names, the resulting bugs object will
respect that naming convention. For example, if the parameter names are
“alpha[1]”, “alpha[2]”, ..., “alpha[8]”,
“mu”, “tau”, then as.bugs.array
will know that
alpha is a vector of length 8, and mu and tau are scalar parameters.
These will all be plotted appropriately by plot
and attached
appropriately by attach.bugs
.
If DIC=TRUE
then DIC can be either already passed to argument
DICOutput
as it is done in openbugs
or calculated
from deviance values in sims.array
.
A bugs
object is returned
Jouni Kerman, [email protected] with modification by Andrew Gelman, [email protected], packaged by Uwe Ligges, [email protected].
The database is attached/detached to the search path. See
attach
for details.
attach.all(x, overwrite = NA, name = "attach.all") attach.bugs(x, overwrite = NA) detach.all(name = "attach.all") detach.bugs()
attach.all(x, overwrite = NA, name = "attach.all") attach.bugs(x, overwrite = NA) detach.all(name = "attach.all") detach.bugs()
x |
An object, which must be of class |
overwrite |
If |
name |
The name of the environment where |
While attach.all
attaches all elements of an object x
to
a database called name
, attach.bugs
attaches all
elements of x$sims.list
to the database bugs.sims
itself
making use of attach.all
.
detach.all
and detach.bugs
are removing the databases
mentioned above.attach.all
also attaches n.sims
(the
number of simulations saved from the MCMC runs) to the database.
Each scalar parameter in the model is attached as vectors of length
n.sims
, each vector is attached as a 2-way array (with first
dimension equal to n.sims
), each matrix is attached as a 3-way
array, and so forth.
attach.all
and attach.bugs
invisibly return the
environment
(s).
detach.all
and detach.bugs
detach the
environment
(s) named name
created by attach.all
.
Without detaching, do not use attach.all
or attach.bugs
on another (bugs
) object, because instead of the given name, an
object called name
is attached. Therefore strange things may
happen ...
# An example model file is given in: model.file <- system.file("model", "schools.txt", package="R2WinBUGS") # Some example data (see ?schools for details): data(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)) } parameters <- c("theta", "mu.theta", "sigma.theta") ## Not run: ## You may need to edit "bugs.directory", ## also you need write access in the working directory: schools.sim <- bugs(data, inits, parameters, model.file, n.chains = 3, n.iter = 1000, bugs.directory = "c:/Program Files/WinBUGS14/", working.directory = NULL) # Do some inferential summaries attach.bugs(schools.sim) # posterior probability that the coaching program in school A # is better than in school C: print(mean(theta[,1] > theta[,3])) # 50 # and school C's program: print(quantile(theta[,1] - theta[,3], c(.25, .75))) plot(theta[,1], theta[,3]) detach.bugs() ## End(Not run)
# An example model file is given in: model.file <- system.file("model", "schools.txt", package="R2WinBUGS") # Some example data (see ?schools for details): data(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)) } parameters <- c("theta", "mu.theta", "sigma.theta") ## Not run: ## You may need to edit "bugs.directory", ## also you need write access in the working directory: schools.sim <- bugs(data, inits, parameters, model.file, n.chains = 3, n.iter = 1000, bugs.directory = "c:/Program Files/WinBUGS14/", working.directory = NULL) # Do some inferential summaries attach.bugs(schools.sim) # posterior probability that the coaching program in school A # is better than in school C: print(mean(theta[,1] > theta[,3])) # 50 # and school C's program: print(quantile(theta[,1] - theta[,3], c(.25, .75))) plot(theta[,1], theta[,3]) detach.bugs() ## End(Not run)
The bugs
function takes data and starting values as
input. It automatically writes a WinBUGS script, calls the model, and
saves the simulations for easy access in R or S-PLUS.
bugs(data, inits, parameters.to.save, model.file="model.bug", n.chains=3, n.iter=2000, n.burnin=floor(n.iter/2), n.thin=max(1, floor(n.chains * (n.iter - n.burnin) / n.sims)), n.sims = 1000, bin=(n.iter - n.burnin) / n.thin, debug=FALSE, DIC=TRUE, digits=5, codaPkg=FALSE, bugs.directory="c:/Program Files/WinBUGS14/", program=c("WinBUGS", "OpenBUGS", "winbugs", "openbugs"), working.directory=NULL, clearWD=FALSE, useWINE=.Platform$OS.type != "windows", WINE=NULL, newWINE=TRUE, WINEPATH=NULL, bugs.seed=NULL, summary.only=FALSE, save.history=!summary.only, over.relax = FALSE)
bugs(data, inits, parameters.to.save, model.file="model.bug", n.chains=3, n.iter=2000, n.burnin=floor(n.iter/2), n.thin=max(1, floor(n.chains * (n.iter - n.burnin) / n.sims)), n.sims = 1000, bin=(n.iter - n.burnin) / n.thin, debug=FALSE, DIC=TRUE, digits=5, codaPkg=FALSE, bugs.directory="c:/Program Files/WinBUGS14/", program=c("WinBUGS", "OpenBUGS", "winbugs", "openbugs"), working.directory=NULL, clearWD=FALSE, useWINE=.Platform$OS.type != "windows", WINE=NULL, newWINE=TRUE, WINEPATH=NULL, bugs.seed=NULL, summary.only=FALSE, save.history=!summary.only, over.relax = FALSE)
data |
either a named list (names corresponding to variable names
in the |
inits |
a list with |
parameters.to.save |
character vector of the names of the parameters to save which should be monitored |
model.file |
file containing the model written in WinBUGS code.
The extension can be either ‘.bug’ or ‘.txt’.
If the extension is ‘.bug’ and |
n.chains |
number of Markov chains (default: 3) |
n.iter |
number of total iterations per chain (including burn in; default: 2000) |
n.burnin |
length of burn in, i.e. number of iterations to
discard at the beginning. Default is |
n.thin |
thinning rate. Must be a positive integer. Set
|
n.sims |
The approximate number of simulations to keep after thinning. |
bin |
number of iterations between saving of results
(i.e. the coda files are saved after each |
debug |
if |
DIC |
logical; if |
digits |
number of significant digits used for WinBUGS input, see
|
codaPkg |
logical; if |
bugs.directory |
directory that contains the WinBUGS executable.
If the global option |
program |
the program to use, either
|
working.directory |
sets working directory during execution of
this function; WinBUGS' in- and output will be stored in this
directory; if |
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 WinBUGS has
finished. If set to |
useWINE |
logical; attempt to use the Wine emulator to run
WinBUGS, defaults to |
WINE |
character, path to ‘wine’ binary file, it is
tried hard (by a guess and the utilities |
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 |
bugs.seed |
random seed for WinBUGS (default is no seed) |
summary.only |
If |
save.history |
If |
over.relax |
If |
To run:
Write a BUGS model in an ASCII file (hint: use
write.model
).
Go into R / S-PLUS.
Prepare the inputs for the bugs
function and run it (see
Example section).
A WinBUGS window will pop up and R / S-PLUS will freeze up. The model will now run in WinBUGS. It might take awhile. You will see things happening in the Log window within WinBUGS. When WinBUGS is done, its window will close and R / S-PLUS will work again.
If an error message appears, re-run with debug=TRUE
.
BUGS version support:
default
via argument program="OpenBUGS"
Operation system support:
no problem
possible with Wine emulation via useWINE=TRUE
, but
only for WinBUGS 1.4.*
If useWINE=TRUE
is used, all paths (such as
working.directory
and model.file
, must be given in
native (Unix) style, but bugs.directory
can be given in
Windows path style (e.g. “c:/Program Files/WinBUGS14/”) or
native (Unix) style
(e.g. “/path/to/wine/folder/dosdevices/c:/Program
Files/WinBUGS14”). This is done to achieve greatest portability with
default argument value for bugs.directory
.
If codaPkg=TRUE
the returned values are the names
of coda output files written by WinBUGS 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.sims |
number of posterior simulations (equal to
|
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 |
sims.matrix |
matrix of simulation output, with
|
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 |
long.short |
indexes; programming stuff |
dimension.short |
dimension of |
indexes.short |
indexes of |
last.values |
list of simulations from the most recent iteration; they can be used as starting points if you wish to run WinBUGS for further iterations |
pD |
an estimate of the effective number of parameters, for calculations see the section “Arguments”. |
DIC |
|
Andrew Gelman, [email protected]; modifications and packaged by Sibylle Sturtz, [email protected], and Uwe Ligges.
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.
print.bugs
, plot.bugs
, as well as
coda and BRugs packages
# An example model file is given in: model.file <- system.file(package="R2WinBUGS", "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=J, y=y, sigma.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") ## Not run: ## You may need to edit "bugs.directory", ## also you need write access in the working directory: schools.sim <- bugs(data, inits, parameters, model.file, n.chains=3, n.iter=5000, bugs.directory="c:/Program Files/WinBUGS14/") print(schools.sim) plot(schools.sim) ## End(Not run)
# An example model file is given in: model.file <- system.file(package="R2WinBUGS", "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=J, y=y, sigma.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") ## Not run: ## You may need to edit "bugs.directory", ## also you need write access in the working directory: schools.sim <- bugs(data, inits, parameters, model.file, n.chains=3, n.iter=5000, bugs.directory="c:/Program Files/WinBUGS14/") print(schools.sim) plot(schools.sim) ## End(Not run)
Read data such as summary statistics and DIC information from the WinBUGS logfile
bugs.log(file)
bugs.log(file)
file |
Location of the WinBUGS logfile |
A list with components:
stats |
A matrix containing summary statistics for each saved
parameter. Comparable to the information in the element
|
DIC |
A matrix containing the DIC statistics as returned from WinBUGS. |
Jouni Kerman
The main function that generates the log file is bugs
.
The openbugs
function takes data and starting values
as input. It automatically calls the package BRugs and runs
something similar to BRugsFit
. Not available in
S-PLUS.
openbugs(data, inits, parameters.to.save, model.file = "model.txt", n.chains = 3, n.iter = 2000, n.burnin = floor(n.iter/2), n.thin = max(1, floor(n.chains * (n.iter - n.burnin) / n.sims)), n.sims = 1000, DIC = TRUE, bugs.directory = "c:/Program Files/OpenBUGS/", working.directory = NULL, digits = 5, over.relax = FALSE, seed=NULL)
openbugs(data, inits, parameters.to.save, model.file = "model.txt", n.chains = 3, n.iter = 2000, n.burnin = floor(n.iter/2), n.thin = max(1, floor(n.chains * (n.iter - n.burnin) / n.sims)), n.sims = 1000, DIC = TRUE, bugs.directory = "c:/Program Files/OpenBUGS/", working.directory = NULL, digits = 5, over.relax = FALSE, seed=NULL)
data |
either a named list (names corresponding to variable names
in the |
inits |
a list with |
parameters.to.save |
character vector of the names of the parameters to save which should be monitored |
model.file |
file containing the model written in OpenBUGS code.
The extension can be either ‘.bug’ or ‘.txt’. If
‘.bug’, a copy of the file with extension ‘.txt’ will be
created in the |
n.chains |
number of Markov chains (default: 3) |
n.iter |
number of total iterations per chain (including burn in; default: 2000) |
n.burnin |
length of burn in, i.e. number of iterations to
discard at the beginning. Default is |
n.thin |
thinning rate. Must be a positive integer. Set
|
n.sims |
The approximate number of simulations to keep after thinning. |
DIC |
logical; if |
digits |
number of significant digits used for OpenBUGS input,
see |
bugs.directory |
directory that contains the OpenBUGS executable - currently unused |
working.directory |
sets working directory during execution of
this function; WinBUGS in- and output will be stored in this
directory; if |
over.relax |
If |
seed |
random seed (default is no seed) |
A bugs
object.
By default, BRugs (and hence openbugs()
) is quite verbose.
This can be controlled for the whole BRugs package by the option ‘BRugsVerbose’ (see options
)
which is set to TRUE
by default.
Andrew Gelman, [email protected]; modifications and packaged by Sibylle Sturtz, [email protected], and Uwe Ligges.
bugs
and the BRugs package
# An example model file is given in: model.file <- system.file(package = "R2WinBUGS", "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") ## Not run: ## both write access in the working directory and package BRugs required: schools.sim <- bugs(data, inits, parameters, model.file, n.chains = 3, n.iter = 5000, program = "openbugs", working.directory = NULL) print(schools.sim) plot(schools.sim) ## End(Not run)
# An example model file is given in: model.file <- system.file(package = "R2WinBUGS", "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") ## Not run: ## both write access in the working directory and package BRugs required: schools.sim <- bugs(data, inits, parameters, model.file, n.chains = 3, n.iter = 5000, program = "openbugs", working.directory = NULL) print(schools.sim) plot(schools.sim) ## End(Not run)
Plotting a bugs
object
## S3 method for class 'bugs' plot(x, display.parallel = FALSE, ...)
## S3 method for class 'bugs' plot(x, display.parallel = FALSE, ...)
x |
an object of class ‘bugs’, see |
display.parallel |
display parallel intervals in both halves of
the summary plots; this is a convergence-monitoring tool and is not
necessary once you have approximate convergence (default is
|
... |
further arguments to |
Printing a bugs
object
## S3 method for class 'bugs' print(x, digits.summary = 1, ...)
## S3 method for class 'bugs' print(x, digits.summary = 1, ...)
x |
an object of class ‘bugs’, see |
digits.summary |
rounding for tabular output on the console (default is to round to 1 decimal place) |
... |
further arguments to |
This function reads Markov Chain Monte Carlo output in the
CODA format produced by WinBUGS and returns an object of class
mcmc.list
for further output analysis using the
coda package.
read.bugs(codafiles, ...)
read.bugs(codafiles, ...)
codafiles |
character vector of filenames (e.g. returned from
|
... |
further arguments to be passed to
|
8 schools analysis
data(schools)
data(schools)
A data frame with 8 observations on the following 3 variables.
See Source.
See Source.
See Source.
Rubin, D.B. (1981): Estimation in Parallel Randomized Experiments. Journal of Educational Statistics 6(4), 377-400.
Section 5.5 of Gelman, A., Carlin, J.B., Stern, H.S., Rubin, D.B. (2003): Bayesian Data Analysis, 2nd edition, CRC Press.
Convert R / S-PLUS function to a WinBUGS model file
write.model(model, con = "model.bug", digits = 5)
write.model(model, con = "model.bug", digits = 5)
model |
R / S-PLUS function containing the BUGS model in the BUGS model language, for minor differences see Section Details. |
con |
passed to |
digits |
number of significant digits used for WinBUGS
input, see |
BUGS models follow closely S syntax. It is therefore possible to write most BUGS models as R functions.
As a difference, BUGS syntax allows truncation specification like this:
dnorm(...) I(...)
but this is illegal in R and S-PLUS. To
overcome this incompatibility, use dummy operator %_%
before
I(...)
: dnorm(...) %_% I(...)
. The dummy operator
%_%
will be removed before the BUGS code is saved.
In S-PLUS, a warning is generated when the model function is defined if the last statement in the model is an assignment. To avoid this warning, add the line "invisible()" to the end of the model definition. This line will be removed before the BUGS code is saved.
Nothing, but as a side effect, the model file is written
original idea by Jouni Kerman, modified by Uwe Ligges
## Same "schoolsmodel" that is used in the examples in ?bugs: schoolsmodel <- function(){ for (j in 1:J){ y[j] ~ dnorm (theta[j], tau.y[j]) theta[j] ~ dnorm (mu.theta, tau.theta) tau.y[j] <- pow(sigma.y[j], -2) } mu.theta ~ dnorm (0.0, 1.0E-6) tau.theta <- pow(sigma.theta, -2) sigma.theta ~ dunif (0, 1000) } ## some temporary filename: filename <- file.path(tempdir(), "schoolsmodel.bug") ## write model file: write.model(schoolsmodel, filename) ## and let's take a look: file.show(filename)
## Same "schoolsmodel" that is used in the examples in ?bugs: schoolsmodel <- function(){ for (j in 1:J){ y[j] ~ dnorm (theta[j], tau.y[j]) theta[j] ~ dnorm (mu.theta, tau.theta) tau.y[j] <- pow(sigma.y[j], -2) } mu.theta ~ dnorm (0.0, 1.0E-6) tau.theta <- pow(sigma.theta, -2) sigma.theta ~ dunif (0, 1000) } ## some temporary filename: filename <- file.path(tempdir(), "schoolsmodel.bug") ## write model file: write.model(schoolsmodel, filename) ## and let's take a look: file.show(filename)