\HeaderA{bugs}{Run OpenBUGS from R}{bugs}
\keyword{interface}{bugs}
\keyword{models}{bugs}
%
\begin{Description}\relax
The \code{bugs} function takes data and starting values as
input.  It automatically writes a \pkg{OpenBUGS} script, calls the model, and
saves the simulations for easy access in \R{}.
\end{Description}
%
\begin{Usage}
\begin{verbatim}
bugs(data, inits, parameters.to.save, n.iter, model.file="model.txt",
    n.chains=3, n.burnin=floor(n.iter / 2), n.thin=1,
    saveExec=FALSE,restart=FALSE,
    debug=FALSE, DIC=TRUE, digits=5, codaPkg=FALSE,
    OpenBUGS.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)
\end{verbatim}
\end{Usage}
%
\begin{Arguments}
\begin{ldescription}
\item[\code{data}] either a named list (names corresponding to variable names
in the \code{model.file}) of the data for the \pkg{OpenBUGS} model,
\emph{or} a vector or list of the names of the data objects used by
the model. If \code{data} is a one element character vector (such as \code{"data.txt"}),
it is assumed that data have already been written to the working directory into that file,
e.g. by the function \code{\LinkA{bugs.data}{bugs.data}}.
\item[\code{inits}] a list with \code{n.chains} elements; each element of the
list is itself a list of starting values for the \pkg{OpenBUGS} model,
\emph{or} a function creating (possibly random) initial values.
Alternatively, if \code{inits=NULL}, initial values are generated
by \pkg{OpenBUGS}. If \code{inits} is a character vector with \code{n.chains} elements,
it is assumed that inits have already been written to the working directory into those files,
e.g. by the function \code{\LinkA{bugs.inits}{bugs.inits}}.
\item[\code{parameters.to.save}] character vector of the names of the
parameters to save which should be monitored
\item[\code{model.file}] File containing the model written in \pkg{OpenBUGS} code.
The extension must be \file{.txt}.
The old convention allowing model.file to be named \file{.bug} has been eliminated
because the new \pkg{OpenBUGS} feature that allows the program image
to be saved and later restarted uses the .bug extension for the saved
images.
Alternatively, \code{model.file} can be an R function that contains a BUGS model that is written to a
temporary model file (see \code{\LinkA{tempfile}{tempfile}}) using \code{\LinkA{write.model}{write.model}}.
\item[\code{n.chains}] number of Markov chains (default: 3)
\item[\code{n.iter}] number of total iterations per chain (including burn in;
default: 2000)
\item[\code{n.burnin}] length of burn in, i.e. number of iterations to
discard at the beginning. Default is \code{n.iter/2}, that is,
discarding the first half of the simulations.
\item[\code{n.thin}] Thinning rate. Must be a positive integer. The default is
\code{n.thin} = 1. The thinning is implemented in the OpenBUGS update phase, so
thinned samples are never stored, and they are not counted in \code{n.burnin} or
\code{n.iter}.  Setting \code{n.thin}=2, doubles the number of iterations OpenBUGS
performs, but does not change \code{n.iter} or \code{n.burnin}.  Thinning implemented
in this manner is not captured in summaries created by packages such as \pkg{coda}.
\item[\code{saveExec}] If TRUE, a re-startable image of the OpenBUGS execution is
saved with \code{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.

\item[\code{restart}] If TRUE, execution resumes with the final status from
the previous execution stored in the .bug file in the working directory.
If \code{n.burnin=0},additional iterations are performed and all iterations since
the previous burnin are used (including those from past executions).  If
\code{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 \code{restart=TRUE}, only \code{n.burnin}, \code{n.iter},
and \code{saveExec} inputs
should be changed from the call creating the .bug file, otherwise
failed or erratic results may be produced.  Note the default has \code{n.burnin>0}.

\item[\code{debug}] if \code{FALSE} (default), \pkg{OpenBUGS} is closed automatically
when the script has finished running, otherwise \pkg{OpenBUGS} remains open
for further investigation.  The debug option is not available for linux execution.
\item[\code{DIC}] logical; if \code{TRUE} (default), compute deviance, pD,
and DIC. This is done in \pkg{OpenBUGS} directly using the rule \code{pD =
    Dbar - Dhat}.  If there are less iterations than required for the
adaptive phase, the rule \code{pD=var(deviance) / 2} is used.
\item[\code{digits}] number of significant digits used for \pkg{OpenBUGS} input, see
\code{\LinkA{formatC}{formatC}}
\item[\code{codaPkg}] logical; if \code{FALSE} (default) a \code{bugs} object
is returned, if \code{TRUE} file names of \pkg{OpenBUGS} output are
returned for easy access by the \pkg{coda} package through function
\code{\LinkA{read.bugs}{read.bugs}}.
A \code{bugs} object can be converted to an \code{mcmc.list} object as
used by the \pkg{coda} package with the method \code{\LinkA{as.mcmc.list}{as.mcmc.list}}
(for which a method is provided by R2OpenBUGS).
\item[\code{OpenBUGS.pgm}]  For Windows or WINE execution, the full path to the OpenBUGS
executable.  For linux execution, the full path to the OpenBUGS shell script (not
required if OpenBUGS is in the user's PATH variable).
If \code{NULL} (unset) and the environment variable \code{OpenBUGS\_PATH} is set the latter will be used as the default.
If \code{NULL} (unset), the environment variable \code{OpenBUGS\_PATH} is unset and the global option \code{R2OpenBUGS.pgm} is not \code{NULL} the latter will be used as the default.
If nothing of the former is set and OS is Windows, the most recent OpenBUGS version
registered in the Windows registry  will be used as the default.

\item[\code{working.directory}] sets working directory during execution of
this function; \pkg{OpenBUGS}' in- and output will be stored in this
directory; if \code{NULL}, a temporary working directory via
\code{\LinkA{tempdir}{tempdir}} is used.
\item[\code{clearWD}] logical; indicating whether the files \file{data.txt},
\file{inits[1:n.chains].txt}, \file{log.odc}, \file{codaIndex.txt},
and \file{coda[1:nchains].txt} should be removed after \pkg{OpenBUGS} has
finished.  If set to \code{TRUE}, this argument is only respected if
\code{codaPkg=FALSE}.
\item[\code{useWINE}] logical; attempt to use the Wine emulator to run
\pkg{OpenBUGS}. Default is \code{FALSE}. If WINE is used, the arguments \code{OpenBUGS.pgm} and \code{working.directory} must be given in form of Linux paths
rather than Windows paths (if not \code{NULL}).
\item[\code{WINE}] Character, path to \file{wine} binary file, it is
tried hard (by a guess and the utilities \code{which} and \code{locate})
to get the information automatically if not given.
\item[\code{newWINE}] Use new versions of Wine that have \file{winepath}
utility
\item[\code{WINEPATH}] Character, path to \file{winepath} binary file, it is
tried hard (by a guess and the utilities \code{which} and \code{locate})
to get the information automatically if not given.
\item[\code{bugs.seed}] Random seed for \pkg{OpenBUGS}.  Must be an integer between 1-14.  Seed
specification changed between WinBUGS and OpenBUGS;  see the OpenBUGS documentation for
details.
\item[\code{summary.only}] If \code{TRUE}, only a parameter summary for very quick analyses is given,
temporary created files are not removed in that case.
\item[\code{save.history}] If \code{TRUE} (the default), trace plots are generated at the end.
\item[\code{over.relax}] If \code{TRUE}, over-relaxed form of MCMC is used if available from OpenBUGS.
\end{ldescription}
\end{Arguments}
%
\begin{Details}\relax
To run:
\begin{enumerate}

\item Write a \pkg{BUGS} model in an ASCII file (hint: use
\code{\LinkA{write.model}{write.model}}).
\item Go into \R{}.
\item Prepare the inputs for the \code{bugs} function and run it (see
Example section).
\item An \pkg{OpenBUGS} window will pop up and \R{} will freeze
up. The model will now run in \pkg{OpenBUGS}. It might take awhile. You
will see things happening in the Log window within \pkg{OpenBUGS}. When
\pkg{OpenBUGS} is done, its window will close and \R{} will work
again.
\item If an error message appears, re-run with \code{debug=TRUE}.

\end{enumerate}


BUGS version support:
\begin{itemize}

\item \pkg{OpenBUGS} >=3.2.1

\end{itemize}


Operation system support:
\begin{itemize}

\item \pkg{MS Windows}no problem
\item \pkg{Linux, intel processors}GUI display and graphics not available.
\item \pkg{Mac OS X} and \pkg{Unix} in
generalpossible with Wine emulation via \code{useWINE=TRUE}

\end{itemize}


If \code{useWINE=TRUE} is used, all paths (such as
\code{working.directory} and \code{model.file}, must be given in
native (Unix) style, but \code{OpenBUGS.pgm} can be given in
Windows path style (e.g. ``c:/Program Files/OpenBUGS/'') or
native (Unix) style
(e.g. ``/path/to/wine/folder/dosdevices/c:/Program
Files/OpenBUGS/OpenBUGS321/OpenBUGS.exe'').

\end{Details}
%
\begin{Value}
If \code{codaPkg=TRUE} the returned values are the names
of coda output files written by \pkg{OpenBUGS} containing
the Markov Chain Monte Carlo output in the CODA format.
This is useful for direct access with \code{\LinkA{read.bugs}{read.bugs}}.

If \code{codaPkg=FALSE}, the following values are returned:
\begin{ldescription}
\item[\code{n.chains}] see Section `Arguments'
\item[\code{n.iter}] see Section `Arguments'
\item[\code{n.burnin}] see Section `Arguments'
\item[\code{n.thin}] see Section `Arguments'
\item[\code{n.keep}] number of iterations kept per chain (equal to
\code{(n.iter-n.burnin) / n.thin})
\item[\code{n.sims}] number of posterior simulations (equal to
\code{n.chains * n.keep})
\item[\code{sims.array}] 3-way array of simulation output, with dimensions
n.keep, n.chains, and length of combined parameter vector
\item[\code{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 \code{n.keep*n.chains} simulations in
sims.matrix and sims.list (but NOT sims.array) have been randomly
permuted)
\item[\code{sims.matrix}] matrix of simulation output, with
\code{n.chains*n.keep} rows and one column for each element of
each saved parameter (for convenience, the \code{n.keep*n.chains}
simulations in sims.matrix and sims.list (but NOT sims.array) have
been randomly permuted)
\item[\code{summary}] summary statistics and convergence information for
each saved parameter.
\item[\code{mean}] a list of the estimated parameter means
\item[\code{sd}] a list of the estimated parameter standard deviations
\item[\code{median}] a list of the estimated parameter medians
\item[\code{root.short}] names of argument \code{parameters.to.save} and
``deviance''
\item[\code{long.short}] indexes; programming stuff
\item[\code{dimension.short}] dimension of \code{indexes.short}
\item[\code{indexes.short}] indexes of \code{root.short}
\item[\code{last.values}] list of simulations from the most recent
iteration; they can be used as starting points if you wish to run
\pkg{OpenBUGS} for further iterations
\item[\code{pD}] an estimate of the effective number of parameters, for
calculations see the section ``Arguments''.
\item[\code{DIC}] \code{mean(deviance) + pD}
\end{ldescription}
\end{Value}
%
\begin{Author}\relax
Andrew Gelman, \email{gelman@stat.columbia.edu},
\url{http:/www.stat.columbia.edu/~gelman/bugsR/}; modifications and
packaged by Sibylle Sturtz, \email{sturtz@statistik.tu-dortmund.de},
Uwe Ligges, and Neal Thomas
\end{Author}
%
\begin{References}\relax
Gelman, A., Carlin, J.B., Stern, H.S., Rubin, D.B. (2003):
\emph{Bayesian Data Analysis}, 2nd edition, CRC Press.

Sturtz, S., Ligges, U., Gelman, A. (2005):
R2WinBUGS: A Package for Running WinBUGS from R.
\emph{Journal of Statistical Software} 12(3), 1-16.
\end{References}
%
\begin{SeeAlso}\relax
\code{\LinkA{print.bugs}{print.bugs}}, \code{\LinkA{plot.bugs}{plot.bugs}}, as well as
\pkg{coda} and \pkg{BRugs} packages
\end{SeeAlso}
%
\begin{Examples}
\begin{ExampleCode}
# An example model file is given in:
model.file <- system.file(package="R2OpenBUGS", "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:
## You may need to specify "OpenBUGS.pgm"
## also you need write access in the working directory:
schools.sim <- bugs(data, inits, parameters, model.file,
    n.chains=3, n.iter=5000)
print(schools.sim)
plot(schools.sim)

## End(Not run)
\end{ExampleCode}
\end{Examples}
